Fixed failing tests

This commit is contained in:
ThaumRystra
2025-01-16 16:24:56 +02:00
parent a2d2f43bed
commit 0bf8fdc6d3
79 changed files with 268 additions and 649 deletions

View File

@@ -1,448 +0,0 @@
import { assert } from 'chai';
import '/imports/api/simpleSchemaConfig.js';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { propsFromForest } from '/imports/api/properties/tests/propTestBuilder.testFn';
import Creatures from '/imports/api/creature/creatures/Creatures';
import computeCreature from '/imports/api/engine/computeCreature';
import { loadCreature } from '/imports/api/engine/loadCreatures';
import EngineActions, { EngineAction } from '/imports/api/engine/action/EngineActions';
import applyAction from '/imports/api/engine/action/functions/applyAction';
import { LogContent, Removal, Update } from '/imports/api/engine/action/tasks/TaskResult';
import inputProvider from './functions/userInput/inputProviderForTests.testFn';
import { removeAllCreaturesAndProps } from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const creatureId = Random.id();
const targetId = Random.id();
describe('Interrupt action system', function () {
const dummySubscription = Tracker.autorun(() => undefined)
this.timeout(8000);
before(async function () {
// Remove old data
await removeAllCreaturesAndProps();
// Add creatures
await Promise.all([
Creatures.insertAsync({
_id: creatureId,
name: 'action test creature',
owner: Random.id(),
dirty: true,
type: 'pc',
readers: [],
writers: [],
public: false,
settings: {},
}),
Creatures.insertAsync({
_id: targetId,
name: 'action test creature',
owner: Random.id(),
dirty: true,
type: 'pc',
readers: [],
writers: [],
public: false,
settings: {},
})
]);
// Add test props
await insertActionTestProps();
// Compute before load or we might run tests before the computation changes reflect in the cache
computeCreature(creatureId);
computeCreature(targetId);
loadCreature(creatureId, dummySubscription);
});
after(function () {
dummySubscription.stop();
});
it('writes notes to the log', async function () {
const action = await runActionById(note1Id);
assert.deepEqual(
allLogContent(action),
[{ value: 'Note 1 summary. 1 + 1 = 2' }]
);
});
it('Applies children of folders', async function () {
const action = await runActionById(folderId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child of folder' }]
);
});
it('Applies the children of if branches', async function () {
let action = await runActionById(ifTruthyBranchId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child of if branch' }]
);
action = await runActionById(ifFalsyBranchId);
assert.deepEqual(
allLogContent(action),
[]
);
});
it('Applies the children of index branches', async function () {
const action = await runActionById(indexBranchId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child 2 of index branch' }]
);
});
it('Gets choices from choice branches', async function () {
const action = await runActionById(choiceBranchId);
assert.deepEqual(
allLogContent(action),
[{ value: 'child 1 of choice branch' }]
);
});
it('Applies adjustments', async function () {
let action = await runActionById(adjustmentSetId);
assert.deepEqual(
allUpdates(action),
[{
propId: adjustedStatId,
type: 'attribute',
set: { damage: 5, value: 3 },
}],
'Applying set adjustments should return the correct updates'
);
action = await runActionById(adjustmentIncrementId)
assert.deepEqual(
allUpdates(action),
[{
propId: adjustedStatId,
type: 'attribute',
inc: { damage: 2, value: -2 }, // damage goes up by 2, value down by 2
}],
'Applying increment adjustments should return the correct updates'
);
});
it('Applies rolls', async function () {
const action = await runActionById(rollId);
assert.deepEqual(allLogContent(action), [
{
name: 'New Roll',
value: '7d1 [1, 1, 1, 1, 1, 1, 1] + 9\n**16**',
inline: true,
}, {
value: 'rollVar: 16'
}
]);
});
it('Applies buffs', async function () {
const action = await runActionById(buffId);
const inserts = allInserts(action);
const newIds = inserts.map(p => p._id);
assert.notEqual(buffId, newIds[0]);
assert.deepEqual(inserts, [
{
_id: newIds[0],
left: 43,
parentId: null,
right: 48,
root: {
collection: 'creatures',
id: creatureId,
},
tags: [],
target: 'self',
type: 'buff',
}, {
_id: newIds[1],
attributeType: 'stat',
baseValue: {
calculation: '13 + buffSourceStat + 7',
},
left: 44,
parentId: newIds[0],
right: 45,
root: {
collection: 'creatures',
id: creatureId,
},
tags: [],
type: 'attribute',
variableName: 'buffStat',
}, {
_id: newIds[2],
left: 46,
parentId: newIds[0],
removeAll: true,
right: 47,
root: {
collection: 'creatures',
id: creatureId,
},
tags: [],
target: 'self',
targetParentBuff: true,
type: 'buffRemover',
}
]);
});
it('Removes parent buffs', async function () {
const action = await runActionById(removeParentBuffId);
assert.deepEqual(allRemovals(action), [
{ propId: buffId }
]);
});
it('Removes all buffs by tag', async function () {
const action = await runActionById(removeTaggedBuffsId);
assert.deepEqual(allRemovals(action), [
{ propId: taggedBuffId },
{ propId: secondTaggedBuffId },
]);
});
it('Removes a single buff by tag', async function () {
const action = await runActionById(removeOneTaggedBuffId);
assert.deepEqual(allRemovals(action), [
{ propId: taggedBuffId },
]);
});
});
function createAction(prop, targetIds?) {
const action: EngineAction = {
creatureId: prop.root.id,
results: [],
taskCount: 0,
task: {
prop,
targetIds,
}
};
return EngineActions.insertAsync(action);
}
async function runActionById(propId) {
const prop = await CreatureProperties.findOneAsync(propId);
const actionId = await createAction(prop);
const action = await EngineActions.findOneAsync(actionId);
if (!action) throw 'Action is expected to exist';
await applyAction(action, inputProvider, { simulate: true });
return action;
}
function allUpdates(action: EngineAction) {
const updates: Update[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.updates?.forEach(update => {
updates.push(update);
});
});
});
return updates;
}
function allInserts(action: EngineAction) {
const inserts: any[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.inserts?.forEach(update => {
inserts.push(update);
});
});
});
return inserts;
}
function allRemovals(action: EngineAction) {
const removals: Removal[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.removals?.forEach(update => {
removals.push(update);
});
});
});
return removals
}
function allLogContent(action: EngineAction) {
const contents: LogContent[] = [];
action.results.forEach(result => {
result.mutations.forEach(mutation => {
mutation.contents?.forEach(logContent => {
contents.push(logContent);
});
});
});
return contents;
}
let note1Id, folderId, ifTruthyBranchId, ifFalsyBranchId, indexBranchId, choiceBranchId,
adjustedStatId, adjustmentIncrementId, adjustmentSetId, rollId, buffId,
removeParentBuffId, removeTaggedBuffsId, removeOneTaggedBuffId, taggedBuffId, secondTaggedBuffId;
const propForest = [
// Apply a simple note
{
_id: note1Id = Random.id(),
type: 'note',
summary: {
text: 'Note 1 summary. 1 + 1 = {1 + 1}'
},
},
// Apply a folder with a note inside
{
_id: folderId = Random.id(),
type: 'folder',
children: [{ type: 'note', summary: { text: 'child of folder' } }],
},
// Apply an if branch with a truthy condition
{
_id: ifTruthyBranchId = Random.id(),
type: 'branch',
branchType: 'if',
condition: { calculation: '1 + 1' },
children: [{ type: 'note', summary: { text: 'child of if branch' } }],
},
// Apply an if branch with a falsy condition
{
_id: ifFalsyBranchId = Random.id(),
type: 'branch',
branchType: 'if',
condition: { calculation: '1 - 1' },
children: [{ type: 'note', summary: { text: 'child of if branch' } }],
},
// Apply an index branch
{
_id: indexBranchId = Random.id(),
type: 'branch',
branchType: 'index',
condition: { calculation: '1 + 1' },
children: [
{ type: 'note', summary: { text: 'child 1 of index branch' } },
{ type: 'note', summary: { text: 'child 2 of index branch' } },
{ type: 'note', summary: { text: 'child 3 of index branch' } },
],
},
// Apply a choice branch
{
_id: choiceBranchId = Random.id(),
type: 'branch',
branchType: 'choice',
children: [
{ type: 'note', summary: { text: 'child 1 of choice branch' } },
{ type: 'note', summary: { text: 'child 2 of choice branch' } },
{ type: 'note', summary: { text: 'child 3 of choice branch' } },
],
},
// Apply adjustments
{
_id: adjustedStatId = Random.id(),
type: 'attribute',
attributeType: 'stat',
variableName: 'adjustedStat',
baseValue: { calculation: '8' },
}, {
_id: adjustmentSetId = Random.id(),
type: 'adjustment',
stat: 'adjustedStat',
operation: 'set',
amount: { calculation: '3' },
target: 'self',
children: [
{ type: 'note', summary: { text: 'adjustment set applied' } },
],
}, {
_id: adjustmentIncrementId = Random.id(),
type: 'adjustment',
stat: 'adjustedStat',
operation: 'increment',
amount: { calculation: '2' },
target: 'self',
children: [
{ type: 'note', summary: { text: 'adjustment increment applied' } },
],
},
// Apply buffs
{
_id: Random.id(),
type: 'attribute',
attributeType: 'stat',
variableName: 'buffSourceStat',
baseValue: { calculation: '13' },
}, {
_id: buffId = Random.id(),
type: 'buff',
target: 'self',
children: [
{
_id: Random.id(),
type: 'attribute',
attributeType: 'stat',
variableName: 'buffStat',
baseValue: { calculation: 'buffSourceStat + ~target.buffSourceStat + 7' },
}, {
_id: removeParentBuffId = Random.id(),
type: 'buffRemover',
target: 'self',
targetParentBuff: true,
},
],
},
// Extra buffs with and without tags
{
_id: taggedBuffId = Random.id(),
name: 'Tagged Buff',
type: 'buff',
tags: ['buff tag', 'other tag']
}, {
_id: secondTaggedBuffId = Random.id(),
name: 'Tagged buff 2',
type: 'buff',
tags: ['buff tag', 'yet another tag']
}, {
_id: Random.id(),
name: 'Untagged buff',
type: 'buff',
tags: ['other tag']
},
// Remove buffs by tag
{
_id: removeTaggedBuffsId = Random.id(),
type: 'buffRemover',
target: 'self',
removeAll: true,
targetTags: 'buff tag',
}, {
_id: removeOneTaggedBuffId = Random.id(),
type: 'buffRemover',
target: 'self',
removeAll: false,
targetTags: 'buff tag',
},
// Apply rolls
{
_id: rollId = Random.id(),
type: 'roll',
// Roll d1's because it's a pain to test random numbers
roll: { calculation: '1 + 3 + 7d1 + 5' },
variableName: 'rollVar',
children: [
{ type: 'note', summary: { text: 'rollVar: {rollVar}' } }
]
}
];
const targetPropForest = [
{
type: 'attribute',
attributeType: 'stat',
variableName: 'armor',
baseValue: { calculation: '10' },
}
];
function insertActionTestProps() {
const promises = propsFromForest(propForest, creatureId).map(prop => {
return CreatureProperties.insertAsync(prop);
});
propsFromForest(targetPropForest, targetId).forEach(prop => {
promises.push(CreatureProperties.insertAsync(prop));
});
return Promise.all(promises);
}

View File

@@ -20,18 +20,18 @@ export interface EngineAction {
const ActionSchema = new SimpleSchema({
creatureId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
max: 32,
// @ts-expect-error index not defined
index: 1,
},
rootPropId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
max: 32,
optional: true,
},
tabletopId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
max: 32,
optional: true,
// @ts-expect-error index not defined
index: 1,
@@ -53,7 +53,7 @@ const ActionSchema = new SimpleSchema({
// Should re-run the action identically from this point
'results.$.propId': {
type: String,
regEx: SimpleSchema.RegEx.Id,
max: 32,
},
'results.$.targetIds': {
type: Array,
@@ -61,7 +61,7 @@ const ActionSchema = new SimpleSchema({
},
'results.$.targetIds.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
max: 32,
},
// Changes that override the local scope
'results.$.scope': {
@@ -94,7 +94,7 @@ const ActionSchema = new SimpleSchema({
},
'results.$.mutations.$.targetIds.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
max: 32,
},
'results.$.mutations.$.updates': {
type: Array,
@@ -105,7 +105,7 @@ const ActionSchema = new SimpleSchema({
},
'results.$.mutations.$.updates.$.propId': {
type: String,
regEx: SimpleSchema.RegEx.Id,
max: 32,
},
// Required, because CreatureProperties.update requires a selector of { type }
'results.$.mutations.$.updates.$.type': {

View File

@@ -4,14 +4,15 @@ import {
createTestCreature,
getRandomIds,
removeAllCreaturesAndProps,
runActionById
runActionById,
TestCreature
} from '/imports/api/engine/action/functions/actionEngineTest.testFn';
const [
creatureId, targetCreatureId, targetCreature2Id, adjustmentToTargetId, adjustmentToSelfId, targetCreatureStrengthId, targetCreature2StrengthId, selfDexterityId
] = getRandomIds(100);
const actionTestCreature = {
const actionTestCreature: TestCreature = {
_id: creatureId,
props: [
{
@@ -41,7 +42,7 @@ const actionTestCreature = {
],
}
const actionTargetCreature = {
const actionTargetCreature: TestCreature = {
_id: targetCreatureId,
props: [
{
@@ -54,7 +55,7 @@ const actionTargetCreature = {
]
}
const actionTargetCreature2 = {
const actionTargetCreature2: TestCreature = {
_id: targetCreature2Id,
props: [
{

View File

@@ -1,10 +1,10 @@
import '/imports/api/simpleSchemaConfig.js';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { propsFromForest } from '/imports/api/properties/tests/propTestBuilder.testFn';
import propsFromForest, { ForestProp } from '/imports/api/engine/computation/utility/propsFromForest.testFn';
import Creatures from '/imports/api/creature/creatures/Creatures';
import CreatureVariables from '/imports/api/creature/creatures/CreatureVariables';
import computeCreature from '/imports/api/engine/computeCreature';
import { loadCreature } from '/imports/api/engine/loadCreatures';
import { loadCreature, unloadAllCreatures } from '/imports/api/engine/loadCreatures';
import EngineActions, { EngineAction } from '/imports/api/engine/action/EngineActions';
import applyAction from '/imports/api/engine/action/functions/applyAction';
import { LogContent, Mutation, Removal, Update } from '/imports/api/engine/action/tasks/TaskResult';
@@ -14,6 +14,7 @@ import inputProvider from './userInput/inputProviderForTests.testFn';
*/
export async function removeAllCreaturesAndProps() {
if (Meteor.isServer) {
unloadAllCreatures();
return Promise.all([
CreatureProperties.removeAsync({}),
Creatures.removeAsync({}),
@@ -38,7 +39,7 @@ export async function createTestCreature(creature: TestCreature) {
name: creature.name || 'Test Creature',
owner: Random.id(),
dirty: true,
});
} as any);
const propsInserted = propsFromForest(creature.props, creature._id).map(prop => {
return CreatureProperties.insertAsync(prop);
});
@@ -47,16 +48,16 @@ export async function createTestCreature(creature: TestCreature) {
await computeCreature(creature._id,);
}
type TestCreature = {
export type TestCreature = {
_id: string;
name?: string;
props: any[];
props: ForestProp[];
}
/**
* get a list of random Ids
*/
export const getRandomIds = (count) => new Array(count).fill(undefined).map(() => Random.id());
export const getRandomIds = (count: number) => new Array(count).fill(undefined).map(() => Random.id());
/**
* Creates a new Engine Action and applies the specified creature property
@@ -64,7 +65,7 @@ export const getRandomIds = (count) => new Array(count).fill(undefined).map(() =
* @param userInputFn A function that simulates user input
* @returns The Engine Action with mutations resulting from running the action
*/
export async function runActionById(propId, targetIds?, userInput = inputProvider) {
export async function runActionById(propId: string, targetIds?: string[], userInput = inputProvider) {
const prop = await CreatureProperties.findOneAsync(propId);
const actionId = await createAction(prop, targetIds);
const action = await EngineActions.findOneAsync(actionId);

View File

@@ -12,7 +12,7 @@ export default function () {
// Items
active('itemUnequippedId', 'Unequipped items should be active');
byAncestor('itemUnequippedChildId', 'Children of unequipped items should be inactive');
byAncestor('itemUnEQChildId', 'Children of unequipped items should be inactive');
active('itemEquippedId', 'Equipped items should be active');
active('itemEquippedChildId', 'Children of equipped items should be active');
@@ -56,7 +56,7 @@ var testProperties = [
parentId: 'charId',
}),
clean({
_id: 'itemUnequippedChildId',
_id: 'itemUnEQChildId',
type: 'folder',
parentId: 'itemUnequippedId',
}),

View File

@@ -34,7 +34,8 @@ export default function buildCreatureComputation(creatureId: string) {
const creature = getCreature(creatureId);
if (!creature) {
throw new Meteor.Error('not-found',
'Build computation failed, the creature was not found'
'Build computation failed, the creature was not found.' +
'\nid: ' + creatureId
);
}
const variables = getVariables(creatureId);

View File

@@ -0,0 +1,18 @@
import Creatures from '/imports/api/creature/creatures/Creatures';
import { TestCreature } from '/imports/api/engine/action/functions/actionEngineTest.testFn';
import { buildComputationFromProps } from '/imports/api/engine/computation/buildCreatureComputation';
import propsFromForest from '/imports/api/engine/computation/utility/propsFromForest.testFn';
import { cleanAndValidate } from '/imports/api/utility/TypedSimpleSchema';
export default function buildTestComputation(testCreature: TestCreature) {
const creature = cleanAndValidate(Creatures.simpleSchema(), {
_id: testCreature._id,
name: testCreature.name || 'Test Creature',
dirty: true,
owner: Random.id(),
readers: [],
writers: [],
});
const props = propsFromForest(testCreature.props, creature._id);
return buildComputationFromProps(props, creature, {});
}

View File

@@ -1,36 +1,42 @@
import { buildComputationFromProps } from '/imports/api/engine/computation/buildCreatureComputation';
import { assert } from 'chai';
import computeCreatureComputation from '../../computeCreatureComputation';
import clean from '../../utility/cleanProp.testFn';
import computeCreatureComputation from '/imports/api/engine/computation/computeCreatureComputation';
import buildTestComputation from './buildTestComputation';
import type { ForestProp } from '/imports/api/engine/computation/utility/propsFromForest.testFn';
import { CreaturePropertyTypes } from '/imports/api/creature/creatureProperties/CreatureProperties';
export default async function () {
const computation = buildComputationFromProps(testProperties);
const computation = buildTestComputation({
_id: 'testCreatureId',
props: testProperties,
});
await computeCreatureComputation(computation);
const prop = computation.propsById['actionId'];
assert.equal(prop.summary.value, 'test summary 3 without referencing anything 7');
assert.equal(prop.description.value, 'test description 12 with reference 0.25 prop');
assert.equal(prop.uses.value, 7);
const prop = computation.propsById['actionId'] as CreaturePropertyTypes['action'];
assert.equal(prop.summary?.value, 'test summary 3 without referencing anything 7');
assert.equal(prop.description?.value, 'test description 12 with reference 0.25 prop');
assert.equal(prop.uses?.value, 7);
assert.equal(prop.usesLeft, 2);
const rolled = computation.propsById['rolledDescriptionId'];
assert.equal(rolled.summary.value, 'test roll gets compiled 8 properly');
const rolled = computation.propsById['rolledDescriptionId'] as CreaturePropertyTypes['action'];
assert.equal(rolled.summary?.value, 'test roll gets compiled 8 properly');
const itemConsumed = prop.resources.itemsConsumed[0];
assert.equal(itemConsumed.quantity.value, 3);
assert.exists(itemConsumed);
assert.equal(itemConsumed.quantity?.value, 3);
assert.equal(itemConsumed.available, 27);
assert.equal(itemConsumed.itemName, 'Arrow');
assert.equal(itemConsumed.itemIcon, 'itemIcon');
assert.equal(itemConsumed.itemColor, 'itemColor');
assert.equal(itemConsumed.itemIcon?.name, 'itemIcon');
assert.equal(itemConsumed.itemColor, '#fff');
const attConsumed = prop.resources.attributesConsumed[0];
assert.equal(attConsumed.quantity.value, 4);
assert.exists(attConsumed);
assert.equal(attConsumed.quantity?.value, 4);
assert.equal(attConsumed.available, 9);
assert.equal(attConsumed.statName, 'Resource Var');
}
var testProperties = [
clean({
const testProperties: ForestProp[] = [
{
_id: 'actionId',
type: 'action',
summary: {
@@ -55,6 +61,7 @@ var testProperties = [
calculation: 'resourceConsumedQuantity'
}
}],
conditions: [],
},
uses: {
calculation: 'nonExistentProperty + 7',
@@ -62,8 +69,8 @@ var testProperties = [
usesUsed: 5,
left: 1,
right: 2,
}),
clean({
},
{
_id: 'rolledDescriptionId',
type: 'action',
summary: {
@@ -71,9 +78,9 @@ var testProperties = [
},
left: 3,
right: 4,
}),
clean({
_id: 'numItemsConumedId',
},
{
_id: 'numItemsConsumedId',
type: 'attribute',
variableName: 'itemConsumedQuantity',
baseValue: {
@@ -81,9 +88,9 @@ var testProperties = [
},
left: 5,
right: 6,
}),
clean({
_id: 'numResourceConumedId',
},
{
_id: 'numResourceConsumedId',
type: 'attribute',
variableName: 'resourceConsumedQuantity',
baseValue: {
@@ -91,8 +98,8 @@ var testProperties = [
},
left: 7,
right: 8,
}),
clean({
},
{
_id: 'resourceVarId',
name: 'Resource Var',
type: 'attribute',
@@ -102,8 +109,8 @@ var testProperties = [
},
left: 9,
right: 10,
}),
clean({
},
{
_id: 'inlineRefResourceId',
type: 'attribute',
variableName: 'inlineRef',
@@ -112,15 +119,15 @@ var testProperties = [
},
left: 11,
right: 12,
}),
clean({
},
{
_id: 'arrowId',
type: 'item',
name: 'Arrow',
quantity: 27,
icon: 'itemIcon',
color: 'itemColor',
icon: { name: 'itemIcon', shape: 'itemIconShape' },
color: '#fff',
left: 13,
right: 14,
}),
},
];

View File

@@ -2,7 +2,7 @@ import { buildComputationFromProps } from '/imports/api/engine/computation/build
import { assert } from 'chai';
import computeCreatureComputation from '../../computeCreatureComputation';
import clean from '../../utility/cleanProp.testFn';
import { propsFromForest } from '/imports/api/properties/tests/propTestBuilder.testFn';
import propsFromForest from '/imports/api/engine/computation/utility/propsFromForest.testFn';
export default async function () {
const computation = buildComputationFromProps(testProperties);

View File

@@ -1,7 +1,7 @@
import { buildComputationFromProps } from '/imports/api/engine/computation/buildCreatureComputation';
import { assert } from 'chai';
import computeCreatureComputation from '../../computeCreatureComputation';
import { propsFromForest } from '/imports/api/properties/tests/propTestBuilder.testFn';
import propsFromForest from '/imports/api/engine/computation/utility/propsFromForest.testFn';
export default async function () {
const computation = buildComputationFromProps(testProperties);

View File

@@ -2,12 +2,18 @@ import computeCreatureComputation from './computeCreatureComputation';
import { buildComputationFromProps } from './buildCreatureComputation';
import { assert } from 'chai';
import CreatureProperties, { CreatureProperty } from '/imports/api/creature/creatureProperties/CreatureProperties';
import computeTests from './computeComputation/tests/index';
import Creatures, { Creature } from 'imports/api/creature/creatures/Creatures';
import computeTests from '/imports/api/engine/computation/computeComputation/tstFns';
import Creatures from '/imports/api/creature/creatures/Creatures';
import { cleanAndValidate } from '/imports/api/utility/TypedSimpleSchema';
import { createTestCreature } from '/imports/api/engine/action/functions/actionEngineTest.testFn';
describe('Compute computation', function () {
it('Computes something at all', function () {
const creature: Creature = Creatures.schema.clean({});
it('Computes something at all', async function () {
const creature = cleanAndValidate(Creatures.simpleSchema(), {
owner: Random.id(),
readers: [],
writers: [],
});
const computation = buildComputationFromProps(testProperties, creature, {});
computeCreatureComputation(computation);
assert.exists(computation);
@@ -30,8 +36,8 @@ const testProperties = [
}),
];
function clean(prop: Partial<CreatureProperty>): CreatureProperty {
// @ts-expect-error don't have types for .simpleSchema
function clean(prop: Partial<CreatureProperty>) {
prop.root ??= { collection: 'creatures', id: 'testCreature' };
const schema = CreatureProperties.simpleSchema(prop);
return schema.clean(prop);
return cleanAndValidate(schema, prop);
}

View File

@@ -1,9 +0,0 @@
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
export default function cleanProp(prop) {
if (!prop.root) {
prop.root = { collection: 'creatures', id: 'testCreature' }
}
let schema = CreatureProperties.simpleSchema(prop);
return schema.clean(prop);
}

View File

@@ -0,0 +1,11 @@
import { SetRequired } from 'type-fest';
import CreatureProperties, { CreatureProperty, CreaturePropertyTypes } from '/imports/api/creature/creatureProperties/CreatureProperties';
import { cleanAndValidate } from '/imports/api/utility/TypedSimpleSchema';
export default function cleanProp<T extends SetRequired<Partial<CreatureProperty>, 'type'>>(prop: T): CreaturePropertyTypes[T['type']] {
if (!prop.root) {
prop.root = { collection: 'creatures', id: 'testCreature' }
}
const schema = CreatureProperties.simpleSchema(prop);
return cleanAndValidate(schema, prop as Partial<CreatureProperty>) as CreaturePropertyTypes[T['type']];
}

View File

@@ -0,0 +1,57 @@
import type { CreatureProperty } from '/imports/api/creature/creatureProperties/CreatureProperties';
import CreatureProperties from '/imports/api/creature/creatureProperties/CreatureProperties';
import { applyNestedSetProperties } from '/imports/api/parenting/parentingFunctions';
import { cleanAndValidate } from '/imports/api/utility/TypedSimpleSchema';
export type ForestProp = Partial<CreatureProperty> & {
type: CreatureProperty['type'];
children?: ForestProp[];
}
/**
* Take a forest of props, which can have sub-props nested in children: [], and return a list of
* clean props with correct tree and ancestry data
* @param props
* @returns
*/
export default function propsFromForest(
props: ForestProp[],
creatureId = Random.id(),
parentId?: string,
recursionDepth = 0
) {
const result: CreatureProperty[] = [];
props.forEach(prop => {
const children = prop.children;
// Check the property has a type
if (!prop.type) {
throw new Error('Type is required on every property, not found on doc: ' + JSON.stringify(prop, null, 2));
}
// Create the clean doc
const doc = {
...prop,
left: result.length,
root: { id: creatureId, collection: 'creatures' },
};
if (parentId) {
doc.parentId = parentId;
}
if (!doc._id) {
doc._id = Random.id();
}
delete doc.children;
const creatureProp = cleanAndValidate(CreatureProperties.simpleSchema(doc), doc);
// Add the doc to the result and ancestry
result.push(creatureProp);
if (children) {
result.push(...propsFromForest(children, creatureId, doc._id, recursionDepth + 1));
}
});
// Apply the nested set properties on the top level
if (recursionDepth === 0) {
applyNestedSetProperties(result);
}
return result;
}

View File

@@ -34,6 +34,13 @@ export function loadCreature(creatureId: string, subscription: Tracker.Computati
// logLoadedCreatures()
}
export function unloadAllCreatures() {
loadedCreatures.forEach((creature, id) => {
creature.stop();
loadedCreatures.delete(id);
});
}
function unloadCreature(creatureId: string, subscription: Tracker.Computation) {
if (!creatureId) throw 'creatureId is required';
const creature = loadedCreatures.get(creatureId);
@@ -86,20 +93,20 @@ export function getPropertiesOfType<T extends PropertyType>(creatureId: string,
const creature = loadedCreatures.get(creatureId);
if (creature) {
const props = Array.from(creature.properties.values())
.filter(prop => !prop.removed && prop.type === propType)
.filter((prop): prop is CreaturePropertyTypes[T] => !prop.removed && prop.type === propType)
.sort((a, b) => a.left - b.left);
return EJSON.clone(props) as unknown as CreaturePropertyTypes[T][];
return EJSON.clone(props);
}
// console.time(`Cache miss on creature properties: ${creatureId}`)
const props = CreatureProperties.find({
const props: CreaturePropertyTypes[T][] = CreatureProperties.find({
'root.id': creatureId,
'removed': { $ne: true },
'type': propType,
'type': propType as any,
}, {
sort: { left: 1 },
}).fetch();
}).fetch() as unknown as CreaturePropertyTypes[T][];
// console.timeEnd(`Cache miss on creature properties: ${creatureId}`);
return props as unknown as CreaturePropertyTypes[T][];
return props;
}
/**
@@ -267,6 +274,8 @@ class LoadedCreature {
Tracker.nonreactive(() => {
self.subs = new Set([sub]);
const compute = debounce(Meteor.bindEnvironment(() => {
// It's possible that the creature was unloaded before we get around to computing it
if (!loadedCreatures.has(creatureId)) return;
computeCreature(creatureId);
}), COMPUTE_DEBOUNCE_TIME);

View File

@@ -2,7 +2,7 @@
// in the UI because of incompatibility with latency compensation. If the
// duplicate redraws can be fixed, this is a strictly better way of processing
// writes
export default function bulkWrite(bulkWriteOps, collection): void | Promise<any> {
export default function bulkWrite<T>(bulkWriteOps, collection: Mongo.Collection<T>): void | Promise<any> {
if (!bulkWriteOps.length) return;
// bulkWrite is only available on the server
if (!Meteor.isServer) {