Compare commits
192 Commits
2.0-beta.4
...
2.0-beta.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e4299e6db | ||
|
|
0e663f36db | ||
|
|
de9ea5922c | ||
|
|
a2cfe43e74 | ||
|
|
026c11c13b | ||
|
|
403f2663c2 | ||
|
|
28c042343e | ||
|
|
3f116875a1 | ||
|
|
ae5b4b7d5c | ||
|
|
75835d74f6 | ||
|
|
583b652fc4 | ||
|
|
df317a8942 | ||
|
|
ff0e9b1ff9 | ||
|
|
fa24430a7f | ||
|
|
fde2f821e7 | ||
|
|
827430c987 | ||
|
|
2a1aa02e97 | ||
|
|
aeb347084f | ||
|
|
005bc162cb | ||
|
|
9941d91bb8 | ||
|
|
23c77690a1 | ||
|
|
525b528d9a | ||
|
|
3917f63d5e | ||
|
|
bd056ab042 | ||
|
|
cd84b2562a | ||
|
|
c7436ffb1e | ||
|
|
be7d7f898f | ||
|
|
3024168e95 | ||
|
|
1f0678b50b | ||
|
|
4dad2c41e5 | ||
|
|
46385dd9b2 | ||
|
|
7cb65954b5 | ||
|
|
749799d869 | ||
|
|
3293dad671 | ||
|
|
88df942c59 | ||
|
|
9722bbc667 | ||
|
|
2fb0ba79c6 | ||
|
|
3f7ddd62fc | ||
|
|
227d6c5aae | ||
|
|
147ef97576 | ||
|
|
54806b0f3c | ||
|
|
1165158d46 | ||
|
|
32de70cd45 | ||
|
|
68499e4de5 | ||
|
|
3f4cb8e26b | ||
|
|
ebab41838c | ||
|
|
e8da7a6c17 | ||
|
|
46189c68df | ||
|
|
9fa997ed24 | ||
|
|
e3bf6557ec | ||
|
|
7aa3e5a217 | ||
|
|
dc1b025090 | ||
|
|
2e370a9884 | ||
|
|
384fa076f1 | ||
|
|
7922e30ddc | ||
|
|
1ba4f76763 | ||
|
|
839f91c3b2 | ||
|
|
26567ce840 | ||
|
|
2a729a4eca | ||
|
|
ed17d9e2d2 | ||
|
|
8e9405b5ad | ||
|
|
7fc783dcad | ||
|
|
b15ad7e51a | ||
|
|
8a3d2474fc | ||
|
|
09371e7d54 | ||
|
|
0776d33909 | ||
|
|
6e98d71c3c | ||
|
|
8f89f4b63f | ||
|
|
c0070d017e | ||
|
|
51569592ab | ||
|
|
d2cb86ac27 | ||
|
|
bde9183158 | ||
|
|
0cc9e01754 | ||
|
|
9856471202 | ||
|
|
4f77782a7a | ||
|
|
5f13aaa031 | ||
|
|
1321cf6a96 | ||
|
|
dee8249f61 | ||
|
|
0af0afc0d0 | ||
|
|
a104fc8a87 | ||
|
|
46f452987f | ||
|
|
a87cb1286a | ||
|
|
844588cdbf | ||
|
|
a6a96fc19f | ||
|
|
75ab43da00 | ||
|
|
df7000889b | ||
|
|
65754dea80 | ||
|
|
30cca39e7c | ||
|
|
5ad5c914fb | ||
|
|
f27550362a | ||
|
|
50f7977a60 | ||
|
|
bc5c465a32 | ||
|
|
c8ddf9d547 | ||
|
|
6570665c1e | ||
|
|
06f17a6d33 | ||
|
|
b69ad6c306 | ||
|
|
5dec760452 | ||
|
|
ede4e1367d | ||
|
|
81645df2a6 | ||
|
|
445171ce80 | ||
|
|
dedab7b046 | ||
|
|
a5c16ba83a | ||
|
|
46501f2759 | ||
|
|
a6ed1004be | ||
|
|
8539356b9e | ||
|
|
93db5e9288 | ||
|
|
b4cb91a892 | ||
|
|
9c93747845 | ||
|
|
a51154e434 | ||
|
|
1bde0db0ba | ||
|
|
bc001202ec | ||
|
|
c7985af83b | ||
|
|
0f20cd4bd9 | ||
|
|
1ac01941c7 | ||
|
|
95d8d2cb9a | ||
|
|
47345b3694 | ||
|
|
308168791b | ||
|
|
7be4280508 | ||
|
|
56f9e82326 | ||
|
|
6ddea8a8ab | ||
|
|
e1ddfb2cab | ||
|
|
d36d5b15d0 | ||
|
|
2af687361e | ||
|
|
e572807082 | ||
|
|
c44aeac198 | ||
|
|
757cf5c34b | ||
|
|
8cbfec25b3 | ||
|
|
c4dc5895aa | ||
|
|
cffe0ee574 | ||
|
|
ce51be7b8e | ||
|
|
315073bd8e | ||
|
|
50b99ef54f | ||
|
|
9b01f5fb45 | ||
|
|
389785f5db | ||
|
|
e1bfb173ab | ||
|
|
ecba587253 | ||
|
|
3f540d0f14 | ||
|
|
dc18734d1f | ||
|
|
1535e00093 | ||
|
|
5198c655e9 | ||
|
|
8d41643136 | ||
|
|
ea8d036c72 | ||
|
|
93d566e263 | ||
|
|
b4da32f9ab | ||
|
|
986fe8fd93 | ||
|
|
dd4596851e | ||
|
|
bc3fc9574a | ||
|
|
db1ae5db3d | ||
|
|
d1e7eb2fa0 | ||
|
|
efb8b87a2d | ||
|
|
b04b915c7b | ||
|
|
21b823f85c | ||
|
|
4631579181 | ||
|
|
edf3920e84 | ||
|
|
fb91fd12df | ||
|
|
19f4735412 | ||
|
|
fb2f1efa72 | ||
|
|
f7ee09470e | ||
|
|
a5c42fea19 | ||
|
|
8f81614294 | ||
|
|
c56cebc652 | ||
|
|
d24fb5661d | ||
|
|
4bdc254627 | ||
|
|
db652ac47f | ||
|
|
32c9283569 | ||
|
|
060c44f384 | ||
|
|
8138cd98f1 | ||
|
|
5195e3fad5 | ||
|
|
eb97a98644 | ||
|
|
51845c62a7 | ||
|
|
56cd48da9d | ||
|
|
298f659829 | ||
|
|
b99d1a00f5 | ||
|
|
15ad8b1f5d | ||
|
|
d4804e5292 | ||
|
|
36c23e1eb5 | ||
|
|
9236f3e477 | ||
|
|
cd413ba64f | ||
|
|
2c671acf72 | ||
|
|
44e726417e | ||
|
|
7f2401da81 | ||
|
|
d31f980002 | ||
|
|
4c8512af80 | ||
|
|
edf68b1355 | ||
|
|
868b9e11fa | ||
|
|
14f5c3e797 | ||
|
|
66e25c53d0 | ||
|
|
7a75d34246 | ||
|
|
70a6c817cb | ||
|
|
56879f1911 | ||
|
|
6d12bcb063 | ||
|
|
1c26b7717c |
@@ -3,7 +3,7 @@
|
|||||||
# 'meteor add' and 'meteor remove' will edit this file for you,
|
# 'meteor add' and 'meteor remove' will edit this file for you,
|
||||||
# but you can also edit it by hand.
|
# but you can also edit it by hand.
|
||||||
|
|
||||||
accounts-password@1.6.0
|
accounts-password@1.6.2
|
||||||
accounts-ui@1.3.1
|
accounts-ui@1.3.1
|
||||||
random@1.2.0
|
random@1.2.0
|
||||||
dburles:collection-helpers
|
dburles:collection-helpers
|
||||||
@@ -13,7 +13,7 @@ momentjs:moment
|
|||||||
dburles:mongo-collection-instances
|
dburles:mongo-collection-instances
|
||||||
percolate:migrations
|
percolate:migrations
|
||||||
accounts-google@1.3.3
|
accounts-google@1.3.3
|
||||||
email@1.2.3
|
email@2.0.0
|
||||||
meteorhacks:subs-manager
|
meteorhacks:subs-manager
|
||||||
chuangbo:marked
|
chuangbo:marked
|
||||||
meteor-base@1.4.0
|
meteor-base@1.4.0
|
||||||
@@ -38,7 +38,7 @@ ongoworks:speakingurl
|
|||||||
service-configuration@1.0.11
|
service-configuration@1.0.11
|
||||||
google-config-ui@1.0.1
|
google-config-ui@1.0.1
|
||||||
dynamic-import@0.5.2
|
dynamic-import@0.5.2
|
||||||
ddp-rate-limiter@1.0.7
|
ddp-rate-limiter@1.0.9
|
||||||
rate-limit@1.0.9
|
rate-limit@1.0.9
|
||||||
meteortesting:mocha
|
meteortesting:mocha
|
||||||
mdg:validated-method
|
mdg:validated-method
|
||||||
@@ -50,3 +50,6 @@ akryum:vue-component
|
|||||||
accounts-patreon
|
accounts-patreon
|
||||||
bozhao:link-accounts
|
bozhao:link-accounts
|
||||||
peerlibrary:reactive-publish
|
peerlibrary:reactive-publish
|
||||||
|
simple:rest
|
||||||
|
simple:rest-method-mixin
|
||||||
|
mikowals:batch-insert
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
METEOR@1.10.2
|
METEOR@1.11.1
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
accounts-base@1.6.0
|
accounts-base@1.7.0
|
||||||
accounts-google@1.3.3
|
accounts-google@1.3.3
|
||||||
accounts-oauth@1.2.0
|
accounts-oauth@1.2.0
|
||||||
accounts-password@1.6.0
|
accounts-password@1.6.2
|
||||||
accounts-patreon@0.1.0
|
accounts-patreon@0.1.0
|
||||||
accounts-ui@1.3.1
|
accounts-ui@1.3.1
|
||||||
accounts-ui-unstyled@1.4.2
|
accounts-ui-unstyled@1.4.2
|
||||||
@@ -10,7 +10,7 @@ akryum:vue-component@0.15.2
|
|||||||
akryum:vue-component-dev-client@0.4.7
|
akryum:vue-component-dev-client@0.4.7
|
||||||
akryum:vue-component-dev-server@0.1.4
|
akryum:vue-component-dev-server@0.1.4
|
||||||
akryum:vue-router2@0.2.3
|
akryum:vue-router2@0.2.3
|
||||||
aldeed:collection2@3.0.6
|
aldeed:collection2@3.2.1
|
||||||
aldeed:schema-index@3.0.0
|
aldeed:schema-index@3.0.0
|
||||||
allow-deny@1.1.0
|
allow-deny@1.1.0
|
||||||
autoupdate@1.6.0
|
autoupdate@1.6.0
|
||||||
@@ -20,8 +20,8 @@ base64@1.0.12
|
|||||||
binary-heap@1.0.11
|
binary-heap@1.0.11
|
||||||
blaze@2.3.4
|
blaze@2.3.4
|
||||||
blaze-tools@1.0.10
|
blaze-tools@1.0.10
|
||||||
boilerplate-generator@1.7.0
|
boilerplate-generator@1.7.1
|
||||||
bozhao:link-accounts@2.1.1
|
bozhao:link-accounts@2.2.1
|
||||||
caching-compiler@1.2.2
|
caching-compiler@1.2.2
|
||||||
caching-html-compiler@1.1.3
|
caching-html-compiler@1.1.3
|
||||||
callback-hook@1.3.0
|
callback-hook@1.3.0
|
||||||
@@ -34,17 +34,17 @@ dburles:mongo-collection-instances@0.3.5
|
|||||||
ddp@1.4.0
|
ddp@1.4.0
|
||||||
ddp-client@2.3.3
|
ddp-client@2.3.3
|
||||||
ddp-common@1.4.0
|
ddp-common@1.4.0
|
||||||
ddp-rate-limiter@1.0.7
|
ddp-rate-limiter@1.0.9
|
||||||
ddp-server@2.3.1
|
ddp-server@2.3.2
|
||||||
deps@1.0.12
|
deps@1.0.12
|
||||||
diff-sequence@1.1.1
|
diff-sequence@1.1.1
|
||||||
dynamic-import@0.5.2
|
dynamic-import@0.5.3
|
||||||
ecmascript@0.14.3
|
ecmascript@0.14.3
|
||||||
ecmascript-runtime@0.7.0
|
ecmascript-runtime@0.7.0
|
||||||
ecmascript-runtime-client@0.10.0
|
ecmascript-runtime-client@0.11.0
|
||||||
ecmascript-runtime-server@0.9.0
|
ecmascript-runtime-server@0.10.0
|
||||||
ejson@1.1.1
|
ejson@1.1.1
|
||||||
email@1.2.3
|
email@2.0.0
|
||||||
es5-shim@4.8.0
|
es5-shim@4.8.0
|
||||||
fetch@0.1.1
|
fetch@0.1.1
|
||||||
geojson-utils@1.0.10
|
geojson-utils@1.0.10
|
||||||
@@ -69,10 +69,11 @@ meteor@1.9.3
|
|||||||
meteor-base@1.4.0
|
meteor-base@1.4.0
|
||||||
meteorhacks:picker@1.0.3
|
meteorhacks:picker@1.0.3
|
||||||
meteorhacks:subs-manager@1.6.4
|
meteorhacks:subs-manager@1.6.4
|
||||||
meteortesting:browser-tests@1.3.3
|
meteortesting:browser-tests@1.3.4
|
||||||
meteortesting:mocha@1.1.5
|
meteortesting:mocha@1.1.5
|
||||||
meteortesting:mocha-core@7.0.1
|
meteortesting:mocha-core@7.0.1
|
||||||
minifier-css@1.5.0
|
mikowals:batch-insert@1.2.0
|
||||||
|
minifier-css@1.5.3
|
||||||
minifier-js@2.6.0
|
minifier-js@2.6.0
|
||||||
minimongo@1.6.0
|
minimongo@1.6.0
|
||||||
mobile-experience@1.1.0
|
mobile-experience@1.1.0
|
||||||
@@ -80,14 +81,14 @@ mobile-status-bar@1.1.0
|
|||||||
modern-browsers@0.1.5
|
modern-browsers@0.1.5
|
||||||
modules@0.15.0
|
modules@0.15.0
|
||||||
modules-runtime@0.12.0
|
modules-runtime@0.12.0
|
||||||
momentjs:moment@2.24.0
|
momentjs:moment@2.29.1
|
||||||
mongo@1.10.0
|
mongo@1.10.0
|
||||||
mongo-decimal@0.1.1
|
mongo-decimal@0.1.1
|
||||||
mongo-dev-server@1.1.0
|
mongo-dev-server@1.1.0
|
||||||
mongo-id@1.0.7
|
mongo-id@1.0.7
|
||||||
npm-bcrypt@0.9.3
|
npm-bcrypt@0.9.3
|
||||||
npm-mongo@3.7.0
|
npm-mongo@3.8.1
|
||||||
oauth@1.3.0
|
oauth@1.3.2
|
||||||
oauth2@1.3.0
|
oauth2@1.3.0
|
||||||
observe-sequence@1.0.16
|
observe-sequence@1.0.16
|
||||||
ongoworks:speakingurl@9.0.0
|
ongoworks:speakingurl@9.0.0
|
||||||
@@ -110,12 +111,15 @@ reactive-var@1.0.11
|
|||||||
reload@1.3.0
|
reload@1.3.0
|
||||||
retry@1.1.0
|
retry@1.1.0
|
||||||
routepolicy@1.1.0
|
routepolicy@1.1.0
|
||||||
seba:minifiers-autoprefixer@1.1.2
|
seba:minifiers-autoprefixer@1.2.1
|
||||||
service-configuration@1.0.11
|
service-configuration@1.0.11
|
||||||
session@1.2.0
|
session@1.2.0
|
||||||
sha@1.0.9
|
sha@1.0.9
|
||||||
shell-server@0.5.0
|
shell-server@0.5.0
|
||||||
socket-stream-client@0.3.0
|
simple:json-routes@2.1.0
|
||||||
|
simple:rest@1.1.1
|
||||||
|
simple:rest-method-mixin@1.0.1
|
||||||
|
socket-stream-client@0.3.1
|
||||||
spacebars@1.0.15
|
spacebars@1.0.15
|
||||||
spacebars-compiler@1.1.3
|
spacebars-compiler@1.1.3
|
||||||
srp@1.1.0
|
srp@1.1.0
|
||||||
@@ -129,6 +133,6 @@ templating-tools@1.1.2
|
|||||||
tmeasday:check-npm-versions@0.3.2
|
tmeasday:check-npm-versions@0.3.2
|
||||||
tracker@1.2.0
|
tracker@1.2.0
|
||||||
underscore@1.0.10
|
underscore@1.0.10
|
||||||
url@1.3.0
|
url@1.3.1
|
||||||
webapp@1.9.1
|
webapp@1.9.1
|
||||||
webapp-hashing@1.0.9
|
webapp-hashing@1.0.9
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
|
||||||
|
|
||||||
let Encounters = new Mongo.Collection("encounters");
|
|
||||||
|
|
||||||
let EncounterSchema = new SimpleSchema({
|
|
||||||
//an encounter is a single flow of time all parties in an encounter are in-sync time wise
|
|
||||||
});
|
|
||||||
|
|
||||||
Encounters.attachSchema(EncounterSchema);
|
|
||||||
|
|
||||||
export default Encounters;
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
|
||||||
|
|
||||||
let Parties = new Mongo.Collection("parties");
|
|
||||||
|
|
||||||
let partySchema = new SimpleSchema({
|
|
||||||
name: {
|
|
||||||
type: String,
|
|
||||||
defaultValue: "New Party",
|
|
||||||
trim: false,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
characters: {
|
|
||||||
type: Array,
|
|
||||||
defaultValue: [],
|
|
||||||
},
|
|
||||||
characters: {
|
|
||||||
type: String,
|
|
||||||
regEx: SimpleSchema.RegEx.Id,
|
|
||||||
index: 1,
|
|
||||||
},
|
|
||||||
owner: {
|
|
||||||
type: String,
|
|
||||||
regEx: SimpleSchema.RegEx.Id,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
Parties.attachSchema(partySchema);
|
|
||||||
|
|
||||||
Parties.allow({
|
|
||||||
insert: function(userId, doc) {
|
|
||||||
return userId && doc.owner === userId;
|
|
||||||
},
|
|
||||||
update: function(userId, doc, fields, modifier) {
|
|
||||||
return userId && doc.owner === userId;
|
|
||||||
},
|
|
||||||
remove: function(userId, doc) {
|
|
||||||
return userId && doc.owner === userId;
|
|
||||||
},
|
|
||||||
fetch: ["owner"],
|
|
||||||
});
|
|
||||||
|
|
||||||
Parties.deny({
|
|
||||||
update: function(userId, docs, fields, modifier) {
|
|
||||||
// can't change owners
|
|
||||||
return _.contains(fields, "owner");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export default Parties;
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Meteor } from 'meteor/meteor';
|
import { Meteor } from 'meteor/meteor';
|
||||||
import { Mongo } from 'meteor/mongo';
|
import { Mongo } from 'meteor/mongo';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js';
|
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js';
|
||||||
@@ -8,7 +9,7 @@ import { recomputeCreature } from '/imports/api/creature/computation/recomputeCr
|
|||||||
import LibraryNodes from '/imports/api/library/LibraryNodes.js';
|
import LibraryNodes from '/imports/api/library/LibraryNodes.js';
|
||||||
import Creatures from '/imports/api/creature/Creatures.js';
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js';
|
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js';
|
||||||
import { softRemove } from '/imports/api/parenting/softRemove.js';
|
import { softRemove, restore } from '/imports/api/parenting/softRemove.js';
|
||||||
import SoftRemovableSchema from '/imports/api/parenting/SoftRemovableSchema.js';
|
import SoftRemovableSchema from '/imports/api/parenting/SoftRemovableSchema.js';
|
||||||
import propertySchemasIndex from '/imports/api/properties/computedPropertySchemasIndex.js';
|
import propertySchemasIndex from '/imports/api/properties/computedPropertySchemasIndex.js';
|
||||||
import {
|
import {
|
||||||
@@ -17,6 +18,11 @@ import {
|
|||||||
renewDocIds
|
renewDocIds
|
||||||
} from '/imports/api/parenting/parenting.js';
|
} from '/imports/api/parenting/parenting.js';
|
||||||
import {setDocToLastOrder} from '/imports/api/parenting/order.js';
|
import {setDocToLastOrder} from '/imports/api/parenting/order.js';
|
||||||
|
import { storedIconsSchema } from '/imports/api/icons/Icons.js';
|
||||||
|
import { reorderDocs } from '/imports/api/parenting/order.js';
|
||||||
|
|
||||||
|
import '/imports/api/creature/actions/doAction.js';
|
||||||
|
import '/imports/api/creature/creatureProperties/manageEquipment.js';
|
||||||
|
|
||||||
let CreatureProperties = new Mongo.Collection('creatureProperties');
|
let CreatureProperties = new Mongo.Collection('creatureProperties');
|
||||||
|
|
||||||
@@ -36,6 +42,25 @@ let CreaturePropertySchema = new SimpleSchema({
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
icon: {
|
||||||
|
type: storedIconsSchema,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// Denormalised flag if this property is inactive on the sheet for any reason
|
||||||
|
// Including being disabled, or a decendent of a disabled property
|
||||||
|
inactive: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
// Denormalised flag if this property was made inactive by an inactive
|
||||||
|
// ancestor. True if this property has an inactive ancestor even if this
|
||||||
|
// property is itself inactive
|
||||||
|
deactivatedByAncestor: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
for (let key in propertySchemasIndex){
|
for (let key in propertySchemasIndex){
|
||||||
@@ -50,7 +75,7 @@ for (let key in propertySchemasIndex){
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function getCreature(property){
|
export function getCreature(property){
|
||||||
if (!property) throw new Meteor.Error('No property provided');
|
if (!property) throw new Meteor.Error('No property provided');
|
||||||
let creature = Creatures.findOne(property.ancestors[0].id);
|
let creature = Creatures.findOne(property.ancestors[0].id);
|
||||||
if (!creature) throw new Meteor.Error('Creature does not exist');
|
if (!creature) throw new Meteor.Error('Creature does not exist');
|
||||||
@@ -65,14 +90,20 @@ function assertPropertyEditPermission(property, userId){
|
|||||||
function recomputeCreatures(property){
|
function recomputeCreatures(property){
|
||||||
for (let ref of property.ancestors){
|
for (let ref of property.ancestors){
|
||||||
if (ref.collection === 'creatures') {
|
if (ref.collection === 'creatures') {
|
||||||
|
reorderDocs({collection: CreatureProperties, ancestorId: ref.id});
|
||||||
recomputeCreature.call({charId: ref.id});
|
recomputeCreature.call({charId: ref.id});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const insertProperty = new ValidatedMethod({
|
const insertProperty = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.insert',
|
name: 'creatureProperties.insert',
|
||||||
validate: null,
|
validate: null,
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({creatureProperty}) {
|
run({creatureProperty}) {
|
||||||
delete creatureProperty._id;
|
delete creatureProperty._id;
|
||||||
assertPropertyEditPermission(creatureProperty, this.userId);
|
assertPropertyEditPermission(creatureProperty, this.userId);
|
||||||
@@ -83,13 +114,18 @@ const insertProperty = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const duplicateProperty = new ValidatedMethod({
|
const duplicateProperty = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.duplicate',
|
name: 'creatureProperties.duplicate',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: {
|
_id: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: SimpleSchema.RegEx.Id,
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
}
|
}
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id}) {
|
run({_id}) {
|
||||||
let creatureProperty = CreatureProperties.findOne(_id);
|
let creatureProperty = CreatureProperties.findOne(_id);
|
||||||
assertPropertyEditPermission(creatureProperty, this.userId);
|
assertPropertyEditPermission(creatureProperty, this.userId);
|
||||||
@@ -100,7 +136,7 @@ const duplicateProperty = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const insertPropertyFromLibraryNode = new ValidatedMethod({
|
const insertPropertyFromLibraryNode = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.insertPropertyFromLibraryNode',
|
name: 'creatureProperties.insertPropertyFromLibraryNode',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
nodeId: {
|
nodeId: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -110,6 +146,11 @@ const insertPropertyFromLibraryNode = new ValidatedMethod({
|
|||||||
type: RefSchema,
|
type: RefSchema,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({nodeId, parentRef}) {
|
run({nodeId, parentRef}) {
|
||||||
// get the new ancestry for the properties
|
// get the new ancestry for the properties
|
||||||
let {parentDoc, ancestors} = getAncestry({parentRef});
|
let {parentDoc, ancestors} = getAncestry({parentRef});
|
||||||
@@ -135,7 +176,7 @@ const insertPropertyFromLibraryNode = new ValidatedMethod({
|
|||||||
'ancestors.id': nodeId,
|
'ancestors.id': nodeId,
|
||||||
removed: {$ne: true},
|
removed: {$ne: true},
|
||||||
}).fetch();
|
}).fetch();
|
||||||
// The root node is last in the array of nodes
|
// The root node is last in the array of nodes
|
||||||
nodes.push(node);
|
nodes.push(node);
|
||||||
|
|
||||||
// re-map all the ancestors
|
// re-map all the ancestors
|
||||||
@@ -158,24 +199,23 @@ const insertPropertyFromLibraryNode = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Insert the creature properties
|
// Insert the creature properties
|
||||||
let docId;
|
let insertedDocIds = CreatureProperties.batchInsert(nodes);
|
||||||
nodes.forEach(doc => {
|
|
||||||
docId = CreatureProperties.insert(doc);
|
// get the root inserted doc
|
||||||
});
|
let rootId = insertedDocIds[insertedDocIds.length - 1];
|
||||||
|
|
||||||
// Recompute the creatures doc was attached to
|
// Recompute the creatures doc was attached to
|
||||||
let doc = CreatureProperties.findOne(docId);
|
recomputeCreatures(node);
|
||||||
recomputeCreatures(doc);
|
|
||||||
|
|
||||||
// Return the docId of the last property, the inserted root property
|
// Return the docId of the last property, the inserted root property
|
||||||
return docId;
|
return rootId;
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const updateProperty = new ValidatedMethod({
|
const updateProperty = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.update',
|
name: 'creatureProperties.update',
|
||||||
validate({_id, path}){
|
validate({_id, path}){
|
||||||
if (!_id) return false;
|
if (!_id) throw new Meteor.Error('No _id', '_id is required');
|
||||||
// We cannot change these fields with a simple update
|
// We cannot change these fields with a simple update
|
||||||
switch (path[0]){
|
switch (path[0]){
|
||||||
case 'type':
|
case 'type':
|
||||||
@@ -187,6 +227,11 @@ const updateProperty = new ValidatedMethod({
|
|||||||
'This property can\'t be updated directly');
|
'This property can\'t be updated directly');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, path, value}) {
|
run({_id, path, value}) {
|
||||||
let property = CreatureProperties.findOne(_id);
|
let property = CreatureProperties.findOne(_id);
|
||||||
assertPropertyEditPermission(property, this.userId);
|
assertPropertyEditPermission(property, this.userId);
|
||||||
@@ -205,8 +250,86 @@ const updateProperty = new ValidatedMethod({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export function damagePropertyWork({property, operation, value}){
|
||||||
|
if (operation === 'set'){
|
||||||
|
let currentValue = property.value;
|
||||||
|
// Set represents what we want the value to be after damage
|
||||||
|
// So we need the actual damage to get to that value
|
||||||
|
let damage = currentValue - value;
|
||||||
|
// Damage can't exceed total value
|
||||||
|
if (damage > currentValue) damage = currentValue;
|
||||||
|
// Damage must be positive
|
||||||
|
if (damage < 0) damage = 0;
|
||||||
|
CreatureProperties.update(property._id, {
|
||||||
|
$set: {damage}
|
||||||
|
}, {
|
||||||
|
selector: property
|
||||||
|
});
|
||||||
|
return currentValue - damage;
|
||||||
|
} else if (operation === 'increment'){
|
||||||
|
let currentValue = property.value - (property.damage || 0);
|
||||||
|
let currentDamage = property.damage;
|
||||||
|
let increment = value;
|
||||||
|
// Can't increase damage above the remaining value
|
||||||
|
if (increment > currentValue) increment = currentValue;
|
||||||
|
// Can't decrease damage below zero
|
||||||
|
if (-increment > currentDamage) increment = -currentDamage;
|
||||||
|
CreatureProperties.update(property._id, {
|
||||||
|
$inc: {damage: increment}
|
||||||
|
}, {
|
||||||
|
selector: property
|
||||||
|
});
|
||||||
|
return increment;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const damagePropertiesByName = new ValidatedMethod({
|
||||||
|
name: 'CreatureProperties.damagePropertiesByName',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
creatureId: SimpleSchema.RegEx.Id,
|
||||||
|
variableName: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
operation: {
|
||||||
|
type: String,
|
||||||
|
allowedValues: ['set', 'increment']
|
||||||
|
},
|
||||||
|
value: Number,
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 20,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({creatureId, variableName, operation, value}) {
|
||||||
|
// Check permissions
|
||||||
|
let creature = Creatures.findOne(creatureId, {
|
||||||
|
fields: {
|
||||||
|
damageMultipliers: 1,
|
||||||
|
owner: 1,
|
||||||
|
readers: 1,
|
||||||
|
writers: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
CreatureProperties.find({
|
||||||
|
'ancestors.id': creatureId,
|
||||||
|
variableName,
|
||||||
|
removed: {$ne: false},
|
||||||
|
inactive: {$ne: true},
|
||||||
|
}).forEach(property => {
|
||||||
|
// Check if property can take damage
|
||||||
|
let schema = CreatureProperties.simpleSchema(property);
|
||||||
|
if (!schema.allowsKey('damage')) return;
|
||||||
|
// Damage the property
|
||||||
|
damagePropertyWork({property: property, operation, value})
|
||||||
|
});
|
||||||
|
recomputeCreature.call({charId: creatureId});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
const damageProperty = new ValidatedMethod({
|
const damageProperty = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.adjust',
|
name: 'creatureProperties.damage',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: SimpleSchema.RegEx.Id,
|
_id: SimpleSchema.RegEx.Id,
|
||||||
operation: {
|
operation: {
|
||||||
@@ -215,6 +338,11 @@ const damageProperty = new ValidatedMethod({
|
|||||||
},
|
},
|
||||||
value: Number,
|
value: Number,
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 20,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, operation, value}) {
|
run({_id, operation, value}) {
|
||||||
let currentProperty = CreatureProperties.findOne(_id);
|
let currentProperty = CreatureProperties.findOne(_id);
|
||||||
// Check permissions
|
// Check permissions
|
||||||
@@ -227,41 +355,161 @@ const damageProperty = new ValidatedMethod({
|
|||||||
`Property of type "${currentProperty.type}" can't be damaged`
|
`Property of type "${currentProperty.type}" can't be damaged`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (operation === 'set'){
|
damagePropertyWork({property: currentProperty, operation, value})
|
||||||
let currentValue = currentProperty.value;
|
|
||||||
// Set represents what we want the value to be after damage
|
|
||||||
// So we need the actual damage to get to that value
|
|
||||||
let damage = currentValue - value;
|
|
||||||
// Damage can't exceed total value
|
|
||||||
if (damage > currentValue) damage = currentValue;
|
|
||||||
// Damage must be positive
|
|
||||||
if (damage < 0) damage = 0;
|
|
||||||
CreatureProperties.update(_id, {
|
|
||||||
$set: {damage}
|
|
||||||
}, {
|
|
||||||
selector: currentProperty
|
|
||||||
});
|
|
||||||
} else if (operation === 'increment'){
|
|
||||||
let currentValue = currentProperty.value - (currentProperty.damage || 0);
|
|
||||||
let currentDamage = currentProperty.damage;
|
|
||||||
let increment = value;
|
|
||||||
// Can't increase damage above the remaining value
|
|
||||||
if (increment > currentValue) increment = currentValue;
|
|
||||||
// Can't decrease damage below zero
|
|
||||||
if (-increment > currentDamage) increment = -currentDamage;
|
|
||||||
CreatureProperties.update(_id, {
|
|
||||||
$inc: {damage: increment}
|
|
||||||
}, {
|
|
||||||
selector: currentProperty
|
|
||||||
});
|
|
||||||
}
|
|
||||||
recomputeCreatures(currentProperty);
|
recomputeCreatures(currentProperty);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const dealDamage = new ValidatedMethod({
|
||||||
|
name: 'creatureProperties.dealDamage',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
creatureId: SimpleSchema.RegEx.Id,
|
||||||
|
damageType: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
amount: Number,
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 20,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({creatureId, damageType, amount}) {
|
||||||
|
let creature = Creatures.findOne(creatureId, {
|
||||||
|
fields: {
|
||||||
|
damageMultipliers: 1,
|
||||||
|
owner: 1,
|
||||||
|
readers: 1,
|
||||||
|
writers: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Check permissions
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
let healthBars = CreatureProperties.find({
|
||||||
|
'ancestors.id': creatureId,
|
||||||
|
type: 'attribute',
|
||||||
|
attributeType:'healthBar',
|
||||||
|
removed: {$ne: true},
|
||||||
|
inactive: {$ne: true},
|
||||||
|
}, {
|
||||||
|
sort: {order: -1},
|
||||||
|
});
|
||||||
|
let multiplier = creature.damageMultipliers[damageType];
|
||||||
|
if (multiplier === undefined) multiplier = 1;
|
||||||
|
let totalDamage = Math.floor(amount * multiplier);
|
||||||
|
let damageLeft = totalDamage;
|
||||||
|
if (damageType === 'healing') damageLeft = -totalDamage;
|
||||||
|
healthBars.forEach(healthBar => {
|
||||||
|
if (damageLeft === 0) return;
|
||||||
|
let damageAdded = damagePropertyWork({
|
||||||
|
property: healthBar,
|
||||||
|
operation: 'increment',
|
||||||
|
value: damageLeft,
|
||||||
|
});
|
||||||
|
damageLeft -= damageAdded;
|
||||||
|
});
|
||||||
|
recomputeCreature.call({charId: creatureId});
|
||||||
|
return totalDamage;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export function adjustQuantityWork({property, operation, value}){
|
||||||
|
// Check if property has quantity
|
||||||
|
let schema = CreatureProperties.simpleSchema(property);
|
||||||
|
if (!schema.allowsKey('quantity')){
|
||||||
|
throw new Meteor.Error(
|
||||||
|
'Adjust quantity failed',
|
||||||
|
`Property of type "${property.type}" doesn't have a quantity`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (operation === 'set'){
|
||||||
|
CreatureProperties.update(property._id, {
|
||||||
|
$set: {quantity: value}
|
||||||
|
}, {
|
||||||
|
selector: property
|
||||||
|
});
|
||||||
|
} else if (operation === 'increment'){
|
||||||
|
// value here is 'damage'
|
||||||
|
value = -value;
|
||||||
|
let currentQuantity = property.quantity;
|
||||||
|
if (currentQuantity + value < 0) value = -currentQuantity;
|
||||||
|
CreatureProperties.update(property._id, {
|
||||||
|
$inc: {quantity: value}
|
||||||
|
}, {
|
||||||
|
selector: property
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const adjustQuantity = new ValidatedMethod({
|
||||||
|
name: 'creatureProperties.adjustQuantity',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
_id: SimpleSchema.RegEx.Id,
|
||||||
|
operation: {
|
||||||
|
type: String,
|
||||||
|
allowedValues: ['set', 'increment']
|
||||||
|
},
|
||||||
|
value: Number,
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({_id, operation, value}) {
|
||||||
|
let currentProperty = CreatureProperties.findOne(_id);
|
||||||
|
// Check permissions
|
||||||
|
assertPropertyEditPermission(currentProperty, this.userId);
|
||||||
|
adjustQuantityWork({property: currentProperty, operation, value});
|
||||||
|
recomputeCreatures(currentProperty);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const selectAmmoItem = new ValidatedMethod({
|
||||||
|
name: 'creatureProperties.selectAmmoItem',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
actionId: SimpleSchema.RegEx.Id,
|
||||||
|
itemId: SimpleSchema.RegEx.Id,
|
||||||
|
itemConsumedIndex: Number,
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({actionId, itemId, itemConsumedIndex}) {
|
||||||
|
let action = CreatureProperties.findOne(actionId);
|
||||||
|
// Check permissions
|
||||||
|
assertPropertyEditPermission(action, this.userId);
|
||||||
|
// Check that this index has a document to edit
|
||||||
|
let itemConsumed = action.resources.itemsConsumed[itemConsumedIndex];
|
||||||
|
if (!itemConsumed){
|
||||||
|
throw new Meteor.Error('Resouce not found',
|
||||||
|
'Could not set ammo, because the ammo document was not found');
|
||||||
|
}
|
||||||
|
let itemToLink = CreatureProperties.findOne(itemId);
|
||||||
|
if (!itemToLink){
|
||||||
|
throw new Meteor.Error('Item not found',
|
||||||
|
'Could not set ammo: the item was not found');
|
||||||
|
}
|
||||||
|
let path = `resources.itemsConsumed.${itemConsumedIndex}.itemId`;
|
||||||
|
CreatureProperties.update(actionId, {
|
||||||
|
$set: {[path]: itemId}
|
||||||
|
}, {
|
||||||
|
selector: action,
|
||||||
|
});
|
||||||
|
recomputeCreatures(action);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const pushToProperty = new ValidatedMethod({
|
const pushToProperty = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.push',
|
name: 'creatureProperties.push',
|
||||||
validate: null,
|
validate: null,
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, path, value}){
|
run({_id, path, value}){
|
||||||
let property = CreatureProperties.findOne(_id);
|
let property = CreatureProperties.findOne(_id);
|
||||||
assertPropertyEditPermission(property, this.userId);
|
assertPropertyEditPermission(property, this.userId);
|
||||||
@@ -275,8 +523,13 @@ const pushToProperty = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const pullFromProperty = new ValidatedMethod({
|
const pullFromProperty = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.pull',
|
name: 'creatureProperties.pull',
|
||||||
validate: null,
|
validate: null,
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, path, itemId}){
|
run({_id, path, itemId}){
|
||||||
let property = CreatureProperties.findOne(_id);
|
let property = CreatureProperties.findOne(_id);
|
||||||
assertPropertyEditPermission(property, this.userId);
|
assertPropertyEditPermission(property, this.userId);
|
||||||
@@ -291,10 +544,15 @@ const pullFromProperty = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const softRemoveProperty = new ValidatedMethod({
|
const softRemoveProperty = new ValidatedMethod({
|
||||||
name: 'CreatureProperties.methods.softRemove',
|
name: 'creatureProperties.softRemove',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: SimpleSchema.RegEx.Id
|
_id: SimpleSchema.RegEx.Id
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id}){
|
run({_id}){
|
||||||
let property = CreatureProperties.findOne(_id);
|
let property = CreatureProperties.findOne(_id);
|
||||||
assertPropertyEditPermission(property, this.userId);
|
assertPropertyEditPermission(property, this.userId);
|
||||||
@@ -303,6 +561,23 @@ const softRemoveProperty = new ValidatedMethod({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const restoreProperty = new ValidatedMethod({
|
||||||
|
name: 'creatureProperties.restore',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
_id: SimpleSchema.RegEx.Id
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({_id}){
|
||||||
|
let property = CreatureProperties.findOne(_id);
|
||||||
|
assertPropertyEditPermission(property, this.userId);
|
||||||
|
restore({_id, collection: CreatureProperties});
|
||||||
|
recomputeCreatures(property);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
export default CreatureProperties;
|
export default CreatureProperties;
|
||||||
export {
|
export {
|
||||||
@@ -311,8 +586,13 @@ export {
|
|||||||
duplicateProperty,
|
duplicateProperty,
|
||||||
insertPropertyFromLibraryNode,
|
insertPropertyFromLibraryNode,
|
||||||
updateProperty,
|
updateProperty,
|
||||||
|
dealDamage,
|
||||||
|
damagePropertiesByName,
|
||||||
damageProperty,
|
damageProperty,
|
||||||
|
adjustQuantity,
|
||||||
|
selectAmmoItem,
|
||||||
pushToProperty,
|
pushToProperty,
|
||||||
pullFromProperty,
|
pullFromProperty,
|
||||||
softRemoveProperty,
|
softRemoveProperty,
|
||||||
|
restoreProperty,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import deathSaveSchema from '/imports/api/properties/subSchemas/DeathSavesSchema.js'
|
import deathSaveSchema from '/imports/api/properties/subSchemas/DeathSavesSchema.js'
|
||||||
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js';
|
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js';
|
||||||
import SharingSchema from '/imports/api/sharing/SharingSchema.js';
|
import SharingSchema from '/imports/api/sharing/SharingSchema.js';
|
||||||
import {assertEditPermission} from '/imports/api/sharing/sharingPermissions.js';
|
import {assertEditPermission} from '/imports/api/sharing/sharingPermissions.js';
|
||||||
import { getUserTier } from '/imports/api/users/patreon/tiers.js';
|
import { assertUserHasPaidBenefits } from '/imports/api/users/patreon/tiers.js';
|
||||||
|
|
||||||
import '/imports/api/creature/removeCreature.js';
|
import '/imports/api/creature/removeCreature.js';
|
||||||
|
import '/imports/api/creature/restCreature.js';
|
||||||
|
|
||||||
//set up the collection for creatures
|
//set up the collection for creatures
|
||||||
let Creatures = new Mongo.Collection('creatures');
|
let Creatures = new Mongo.Collection('creatures');
|
||||||
@@ -27,6 +29,23 @@ let CreatureSettingsSchema = new SimpleSchema({
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
// Hide all the unused stats
|
||||||
|
hideUnusedStats: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// How much each hitDice resets on a long rest
|
||||||
|
hitDiceResetMultiplier: {
|
||||||
|
type: Number,
|
||||||
|
optional: true,
|
||||||
|
min: 0,
|
||||||
|
max: 1,
|
||||||
|
},
|
||||||
|
discordWebhook: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
max: 200,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
let CreatureSchema = new SimpleSchema({
|
let CreatureSchema = new SimpleSchema({
|
||||||
@@ -52,23 +71,35 @@ let CreatureSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
// Mechanics
|
// Mechanics
|
||||||
deathSave: {
|
deathSave: {
|
||||||
type: deathSaveSchema,
|
type: deathSaveSchema,
|
||||||
defaultValue: {},
|
defaultValue: {},
|
||||||
},
|
},
|
||||||
xp: {
|
// Stats that are computed and denormalised outside of recomputation
|
||||||
|
denormalizedStats: {
|
||||||
|
type: Object,
|
||||||
|
defaultValue: {},
|
||||||
|
},
|
||||||
|
// Sum of all XP gained by this character
|
||||||
|
'denormalizedStats.xp': {
|
||||||
type: SimpleSchema.Integer,
|
type: SimpleSchema.Integer,
|
||||||
defaultValue: 0,
|
defaultValue: 0,
|
||||||
},
|
},
|
||||||
weightCarried: {
|
// Sum of all levels granted by milestone XP
|
||||||
|
'denormalizedStats.milestoneLevels': {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
// Sum of all weights of items and containers that are carried
|
||||||
|
'denormalizedStats.weightCarried': {
|
||||||
type: Number,
|
type: Number,
|
||||||
defaultValue: 0,
|
defaultValue: 0,
|
||||||
},
|
},
|
||||||
level: {
|
// Version of computation engine that was last used to compute this creature
|
||||||
type: SimpleSchema.Integer,
|
computeVersion: {
|
||||||
defaultValue: 0,
|
type: String,
|
||||||
|
optional: true,
|
||||||
},
|
},
|
||||||
type: {
|
type: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -86,6 +117,17 @@ let CreatureSchema = new SimpleSchema({
|
|||||||
defaultValue: {}
|
defaultValue: {}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Tabletop
|
||||||
|
tabletop: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
initiativeRoll: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
|
||||||
// Settings
|
// Settings
|
||||||
settings: {
|
settings: {
|
||||||
type: CreatureSettingsSchema,
|
type: CreatureSettingsSchema,
|
||||||
@@ -100,20 +142,22 @@ Creatures.attachSchema(CreatureSchema);
|
|||||||
|
|
||||||
const insertCreature = new ValidatedMethod({
|
const insertCreature = new ValidatedMethod({
|
||||||
|
|
||||||
name: 'Creatures.methods.insertCreature',
|
name: 'creatures.insertCreature',
|
||||||
|
|
||||||
validate: null,
|
validate: null,
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
run() {
|
run() {
|
||||||
if (!this.userId) {
|
if (!this.userId) {
|
||||||
throw new Meteor.Error('Creatures.methods.insert.denied',
|
throw new Meteor.Error('Creatures.methods.insert.denied',
|
||||||
'You need to be logged in to insert a creature');
|
'You need to be logged in to insert a creature');
|
||||||
}
|
}
|
||||||
let tier = getUserTier(this.userId);
|
assertUserHasPaidBenefits(this.userId);
|
||||||
if (!tier.paidBenefits){
|
|
||||||
throw new Meteor.Error('Creatures.methods.insert.denied',
|
|
||||||
`The ${tier.name} tier does not allow you to insert a creature`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the creature document
|
// Create the creature document
|
||||||
let charId = Creatures.insert({
|
let charId = Creatures.insert({
|
||||||
@@ -126,22 +170,41 @@ const insertCreature = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const updateCreature = new ValidatedMethod({
|
const updateCreature = new ValidatedMethod({
|
||||||
name: 'Creatures.methods.update',
|
name: 'creatures.update',
|
||||||
validate({_id, path}){
|
validate({_id, path}){
|
||||||
if (!_id) return false;
|
if (!_id) return false;
|
||||||
// Allowed fields
|
// Allowed fields
|
||||||
let allowedFields = ['name', 'alignment', 'gender', 'picture', 'avatarPicture', 'settings'];
|
let allowedFields = [
|
||||||
|
'name',
|
||||||
|
'alignment',
|
||||||
|
'gender',
|
||||||
|
'picture',
|
||||||
|
'avatarPicture',
|
||||||
|
'color',
|
||||||
|
'settings',
|
||||||
|
];
|
||||||
if (!allowedFields.includes(path[0])){
|
if (!allowedFields.includes(path[0])){
|
||||||
throw new Meteor.Error('Creatures.methods.update.denied',
|
throw new Meteor.Error('Creatures.methods.update.denied',
|
||||||
'This field can\'t be updated using this method');
|
'This field can\'t be updated using this method');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, path, value}) {
|
run({_id, path, value}) {
|
||||||
let creature = Creatures.findOne(_id);
|
let creature = Creatures.findOne(_id);
|
||||||
assertEditPermission(creature, this.userId);
|
assertEditPermission(creature, this.userId);
|
||||||
Creatures.update(_id, {
|
if (value === undefined || value === null){
|
||||||
$set: {[path.join('.')]: value},
|
Creatures.update(_id, {
|
||||||
});
|
$unset: {[path.join('.')]: 1},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
Creatures.update(_id, {
|
||||||
|
$set: {[path.join('.')]: value},
|
||||||
|
});
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
28
app/imports/api/creature/Parties.js
Normal file
28
app/imports/api/creature/Parties.js
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
|
||||||
|
let Parties = new Mongo.Collection('parties');
|
||||||
|
|
||||||
|
let partySchema = new SimpleSchema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
defaultValue: 'New Party',
|
||||||
|
trim: false,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
creatures: {
|
||||||
|
type: Array,
|
||||||
|
defaultValue: [],
|
||||||
|
},
|
||||||
|
'creatures.$': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
},
|
||||||
|
owner: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Parties.attachSchema(partySchema);
|
||||||
|
|
||||||
|
export default Parties;
|
||||||
11
app/imports/api/creature/actions/applyAction.js
Normal file
11
app/imports/api/creature/actions/applyAction.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import spendResources from '/imports/api/creature/actions/spendResources.js'
|
||||||
|
import {insertCreatureLog} from '/imports/api/creature/log/CreatureLogs.js';
|
||||||
|
|
||||||
|
export default function applyAction({prop, creature}){
|
||||||
|
spendResources(prop);
|
||||||
|
insertCreatureLog.call({
|
||||||
|
log: {
|
||||||
|
text: prop.name,
|
||||||
|
creatureId: creature._id},
|
||||||
|
});
|
||||||
|
}
|
||||||
56
app/imports/api/creature/actions/applyAdjustment.js
Normal file
56
app/imports/api/creature/actions/applyAdjustment.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import evaluateString from '/imports/api/creature/computation/afterComputation/evaluateString.js';
|
||||||
|
import {insertCreatureLog} from '/imports/api/creature/log/CreatureLogs.js';
|
||||||
|
import { damagePropertiesByName } from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
|
||||||
|
export default function applyAdjustment({
|
||||||
|
prop,
|
||||||
|
creature,
|
||||||
|
targets,
|
||||||
|
actionContext
|
||||||
|
}){
|
||||||
|
let damageTargets = prop.target === 'self' ? [creature] : targets;
|
||||||
|
let scope = {
|
||||||
|
...creature.variables,
|
||||||
|
...actionContext,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
var {result, errors} = evaluateString(prop.amount, scope, 'reduce');
|
||||||
|
if (typeof result !== 'number') {
|
||||||
|
return insertCreatureLog.call({ log: {
|
||||||
|
text: errors.join(', ') || 'Something went wrong',
|
||||||
|
creatureId: creature._id,
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
} catch (e){
|
||||||
|
return insertCreatureLog.call({ log: {
|
||||||
|
text: e.toString(),
|
||||||
|
creatureId: creature._id,
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
if (damageTargets) {
|
||||||
|
damageTargets.forEach(target => {
|
||||||
|
if (prop.target === 'each'){
|
||||||
|
result = evaluateString(prop.amount, scope, 'reduce');
|
||||||
|
}
|
||||||
|
damagePropertiesByName.call({
|
||||||
|
creatureId: target._id,
|
||||||
|
variableName: prop.stat,
|
||||||
|
operation: prop.operation || 'increment',
|
||||||
|
value: result
|
||||||
|
});
|
||||||
|
insertCreatureLog.call({
|
||||||
|
log: {
|
||||||
|
text: `${prop.stat} ${prop.operation === 'set' ? 'set to' : ''} ${-result}`,
|
||||||
|
creatureId: target._id,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
insertCreatureLog.call({
|
||||||
|
log: {
|
||||||
|
text: `${prop.stat} ${prop.operation === 'set' ? 'set to' : ''} ${-result}`,
|
||||||
|
creatureId: creature._id,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
18
app/imports/api/creature/actions/applyAttack.js
Normal file
18
app/imports/api/creature/actions/applyAttack.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import roll from '/imports/parser/roll.js';
|
||||||
|
import {insertCreatureLog} from '/imports/api/creature/log/CreatureLogs.js';
|
||||||
|
|
||||||
|
export default function applyAttack({
|
||||||
|
prop,
|
||||||
|
//children,
|
||||||
|
creature,
|
||||||
|
//targets,
|
||||||
|
//actionContext
|
||||||
|
}){
|
||||||
|
let result = roll(1, 20)[0] + prop.rollBonusResult;
|
||||||
|
insertCreatureLog.call({
|
||||||
|
log: {
|
||||||
|
text: `${prop.name} attack. ${result} to hit`,
|
||||||
|
creatureId: creature._id,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
61
app/imports/api/creature/actions/applyBuff.js
Normal file
61
app/imports/api/creature/actions/applyBuff.js
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import {
|
||||||
|
setLineageOfDocs,
|
||||||
|
renewDocIds
|
||||||
|
} from '/imports/api/parenting/parenting.js';
|
||||||
|
import {setDocToLastOrder} from '/imports/api/parenting/order.js';
|
||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
|
||||||
|
export default function applyBuff({
|
||||||
|
prop,
|
||||||
|
children,
|
||||||
|
creature,
|
||||||
|
targets = [],
|
||||||
|
//actionContext,
|
||||||
|
}){
|
||||||
|
let buffTargets = prop.target === 'self' ? [creature] : targets;
|
||||||
|
|
||||||
|
//let scope = {
|
||||||
|
// ...creature.variables,
|
||||||
|
// ...actionContext,
|
||||||
|
//};
|
||||||
|
|
||||||
|
// TODO
|
||||||
|
// If the target is not self, walk through all decendants and replace
|
||||||
|
// variables in calculations with their values from the creature scope
|
||||||
|
// If the target is self, replace all the target.x references with just x
|
||||||
|
|
||||||
|
// Then copy the decendants of the buff to the targets
|
||||||
|
prop.applied = true;
|
||||||
|
let propList = [prop];
|
||||||
|
function addChildrenToPropList(children){
|
||||||
|
children.forEach(child => {
|
||||||
|
propList.push(child.node);
|
||||||
|
addChildrenToPropList(child.children);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
addChildrenToPropList(children);
|
||||||
|
let oldParent = {
|
||||||
|
id: prop.parent.id,
|
||||||
|
collection: prop.parent.collection,
|
||||||
|
};
|
||||||
|
buffTargets.forEach(target => {
|
||||||
|
copyNodeListToTarget(propList, target, oldParent);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyNodeListToTarget(propList, target, oldParent){
|
||||||
|
let ancestry = [{collection: 'creatures', id: target._id}];
|
||||||
|
setLineageOfDocs({
|
||||||
|
docArray: propList,
|
||||||
|
newAncestry: ancestry,
|
||||||
|
oldParent,
|
||||||
|
});
|
||||||
|
renewDocIds({
|
||||||
|
docArray: propList,
|
||||||
|
});
|
||||||
|
setDocToLastOrder({
|
||||||
|
collection: CreatureProperties,
|
||||||
|
doc: propList[0],
|
||||||
|
});
|
||||||
|
CreatureProperties.batchInsert(propList);
|
||||||
|
}
|
||||||
63
app/imports/api/creature/actions/applyDamage.js
Normal file
63
app/imports/api/creature/actions/applyDamage.js
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import evaluateString from '/imports/api/creature/computation/afterComputation/evaluateString.js';
|
||||||
|
import {insertCreatureLog} from '/imports/api/creature/log/CreatureLogs.js';
|
||||||
|
import { dealDamage } from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
|
||||||
|
export default function applyDamage({
|
||||||
|
prop,
|
||||||
|
creature,
|
||||||
|
targets,
|
||||||
|
actionContext
|
||||||
|
}){
|
||||||
|
let damageTargets = prop.target === 'self' ? [creature] : targets;
|
||||||
|
let scope = {
|
||||||
|
...creature.variables,
|
||||||
|
...actionContext,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
var {result, errors} = evaluateString(prop.amount, scope, 'reduce');
|
||||||
|
if (typeof result !== 'number') {
|
||||||
|
return insertCreatureLog.call({ log: {
|
||||||
|
text: errors.join(', '),
|
||||||
|
creatureId: creature._id,
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
} catch (e){
|
||||||
|
return insertCreatureLog.call({ log: {
|
||||||
|
text: e.toString(),
|
||||||
|
creatureId: creature._id,
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
if (damageTargets) {
|
||||||
|
damageTargets.forEach(target => {
|
||||||
|
if (prop.target === 'each'){
|
||||||
|
result = evaluateString(prop.amount, scope, 'reduce');
|
||||||
|
}
|
||||||
|
let damageDealt = dealDamage.call({
|
||||||
|
creatureId: target._id,
|
||||||
|
damageType: prop.damageType,
|
||||||
|
amount: result,
|
||||||
|
});
|
||||||
|
insertCreatureLog.call({
|
||||||
|
log: {
|
||||||
|
text: `Recieved ${damageDealt} ${prop.damageType}${prop.damageType !== 'healing'? ' damage': ''}`,
|
||||||
|
creatureId: target._id,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (target._id !== creature._id){
|
||||||
|
insertCreatureLog.call({
|
||||||
|
log: {
|
||||||
|
text: `Dealt ${damageDealt} ${prop.damageType}${prop.damageType !== 'healing'? ' damage': ''}`,
|
||||||
|
creatureId: creature._id,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
insertCreatureLog.call({
|
||||||
|
log: {
|
||||||
|
text: `${result} ${prop.damageType}${prop.damageType !== 'healing'? ' damage': ''}`,
|
||||||
|
creatureId: creature._id,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
67
app/imports/api/creature/actions/applyProperties.js
Normal file
67
app/imports/api/creature/actions/applyProperties.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import applyAction from '/imports/api/creature/actions/applyAction.js';
|
||||||
|
import applyAdjustment from '/imports/api/creature/actions/applyAdjustment.js';
|
||||||
|
import applyAttack from '/imports/api/creature/actions/applyAttack.js';
|
||||||
|
import applyDamage from '/imports/api/creature/actions/applyDamage.js';
|
||||||
|
import applyBuff from '/imports/api/creature/actions/applyBuff.js';
|
||||||
|
|
||||||
|
function applyProperty(options){
|
||||||
|
let prop = options.prop;
|
||||||
|
if (
|
||||||
|
prop.disabled === true || // ignore disabled props
|
||||||
|
prop.equipped === false || // ignore unequipped items
|
||||||
|
prop.toggleResult === false || // ignore untoggled toggles
|
||||||
|
prop.applied === true // ignore buffs that are already applied
|
||||||
|
){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
switch (prop.type){
|
||||||
|
case 'action':
|
||||||
|
case 'spell':
|
||||||
|
applyAction(options);
|
||||||
|
return true;
|
||||||
|
case 'attack':
|
||||||
|
applyAction(options);
|
||||||
|
applyAttack(options);
|
||||||
|
return true;
|
||||||
|
case 'damage':
|
||||||
|
applyDamage(options);
|
||||||
|
return true;
|
||||||
|
case 'adjustment':
|
||||||
|
applyAdjustment(options);
|
||||||
|
return true;
|
||||||
|
case 'buff':
|
||||||
|
applyBuff(options);
|
||||||
|
return false;
|
||||||
|
case 'roll':
|
||||||
|
// applyRoll(options);
|
||||||
|
return true;
|
||||||
|
case 'savingThrow':
|
||||||
|
// applySavingThrow(options);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function applyProperties({
|
||||||
|
forest,
|
||||||
|
creature,
|
||||||
|
targets,
|
||||||
|
actionContext
|
||||||
|
}){
|
||||||
|
forest.forEach(child => {
|
||||||
|
let walkChildren = applyProperty({
|
||||||
|
prop: child.node,
|
||||||
|
children: child.children,
|
||||||
|
creature,
|
||||||
|
targets,
|
||||||
|
actionContext
|
||||||
|
});
|
||||||
|
if (walkChildren){
|
||||||
|
applyProperties({
|
||||||
|
forest: child.children,
|
||||||
|
creature,
|
||||||
|
targets,
|
||||||
|
actionContext
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
62
app/imports/api/creature/actions/doAction.js
Normal file
62
app/imports/api/creature/actions/doAction.js
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import CreatureProperties, { getCreature } from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
||||||
|
import { recomputeCreatureByDoc } from '/imports/api/creature/computation/recomputeCreature.js';
|
||||||
|
import { nodesToTree } from '/imports/api/parenting/parenting.js';
|
||||||
|
import applyProperties from '/imports/api/creature/actions/applyProperties.js';
|
||||||
|
|
||||||
|
const doAction = new ValidatedMethod({
|
||||||
|
name: 'creatureProperties.doAction',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
actionId: SimpleSchema.RegEx.Id,
|
||||||
|
targetId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 10,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({actionId, targetId}) {
|
||||||
|
let action = CreatureProperties.findOne(actionId);
|
||||||
|
// Check permissions
|
||||||
|
let creature = getCreature(action);
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
let target = undefined;
|
||||||
|
if (targetId) {
|
||||||
|
target = getCreature(targetId);
|
||||||
|
assertEditPermission(target, this.userId);
|
||||||
|
}
|
||||||
|
doActionWork({action, creature, target});
|
||||||
|
// Note this only recomputes the top-level creature, not the nearest one
|
||||||
|
recomputeCreatureByDoc(creature);
|
||||||
|
if (target){
|
||||||
|
recomputeCreatureByDoc(target);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function doActionWork({action, creature, target}){
|
||||||
|
let actionContext = {};
|
||||||
|
let decendantForest = nodesToTree({
|
||||||
|
collection: CreatureProperties,
|
||||||
|
ancestorId: action._id,
|
||||||
|
});
|
||||||
|
let startingForest = [{
|
||||||
|
node: action,
|
||||||
|
children: decendantForest,
|
||||||
|
}];
|
||||||
|
applyProperties({
|
||||||
|
forest: startingForest,
|
||||||
|
creature,
|
||||||
|
target,
|
||||||
|
actionContext
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export default doAction;
|
||||||
56
app/imports/api/creature/actions/doCheck.js
Normal file
56
app/imports/api/creature/actions/doCheck.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
||||||
|
import roll from '/imports/parser/roll.js';
|
||||||
|
|
||||||
|
const doCheck = new ValidatedMethod({
|
||||||
|
name: 'creature.doCheck',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
creatureId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
attributeName: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 10,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({creatureId, attributeName}) {
|
||||||
|
let creature = Creatures.findOne(creatureId);
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
let bonus = getAttributeValue({creature, attributeName})
|
||||||
|
return doCheckWork({bonus});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function getAttributeValue({creature, attributeName}){
|
||||||
|
let att = creature.variables[attributeName];
|
||||||
|
if (!att) throw new Meteor.Error('No such attribute',
|
||||||
|
`This creature does not have a ${attributeName} property`);
|
||||||
|
let bonus = att.attributeType === 'ability'? att.modifier : att.value;
|
||||||
|
return bonus || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function doCheckWork({bonus, advantage = 0}){
|
||||||
|
let rolls = roll(2,20);
|
||||||
|
let chosenRoll;
|
||||||
|
if (advantage === 1){
|
||||||
|
chosenRoll = Math.max.apply(rolls);
|
||||||
|
} else if (advantage === -1){
|
||||||
|
chosenRoll = Math.min.apply(rolls);
|
||||||
|
} else {
|
||||||
|
chosenRoll = rolls[0];
|
||||||
|
}
|
||||||
|
let result = chosenRoll + bonus;
|
||||||
|
return {rolls, bonus, chosenRoll, result};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default doCheck;
|
||||||
57
app/imports/api/creature/actions/spendResources.js
Normal file
57
app/imports/api/creature/actions/spendResources.js
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import CreatureProperties, { damagePropertyWork, adjustQuantityWork } from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
|
||||||
|
export default function spendResources(action){
|
||||||
|
// Check Uses
|
||||||
|
if (action.usesUsed >= action.usesResult){
|
||||||
|
throw new Meteor.Error('Insufficient Uses',
|
||||||
|
'This action has no uses left');
|
||||||
|
}
|
||||||
|
// Resources
|
||||||
|
if (action.insufficientResources){
|
||||||
|
throw new Meteor.Error('Insufficient Resources',
|
||||||
|
'This creature doesn\'t have sufficient resources to perform this action');
|
||||||
|
}
|
||||||
|
// Items
|
||||||
|
let itemQuantityAdjustments = [];
|
||||||
|
action.resources.itemsConsumed.forEach(itemConsumed => {
|
||||||
|
if (!itemConsumed.itemId){
|
||||||
|
throw new Meteor.Error('Ammo not selected',
|
||||||
|
'No ammo was selected for this action');
|
||||||
|
}
|
||||||
|
let item = CreatureProperties.findOne(itemConsumed.itemId);
|
||||||
|
if (!item || item.ancestors[0].id !== action.ancestors[0].id){
|
||||||
|
throw new Meteor.Error('Ammo not found',
|
||||||
|
'The action\'s ammo was not found on the creature');
|
||||||
|
}
|
||||||
|
if (!item.equipped){
|
||||||
|
throw new Meteor.Error('Ammo not equipped',
|
||||||
|
'The selected ammo is not equipped');
|
||||||
|
}
|
||||||
|
if (!itemConsumed.quantity) return;
|
||||||
|
itemQuantityAdjustments.push({
|
||||||
|
property: item,
|
||||||
|
operation: 'increment',
|
||||||
|
value: itemConsumed.quantity,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// No more errors should be thrown after this line
|
||||||
|
// Now that we have confirmed that there are no errors, do actual work
|
||||||
|
//Items
|
||||||
|
itemQuantityAdjustments.forEach(adjustQuantityWork);
|
||||||
|
// Use uses
|
||||||
|
CreatureProperties.update(action._id, {
|
||||||
|
$inc: {usesUsed: 1}
|
||||||
|
}, {
|
||||||
|
selector: action
|
||||||
|
});
|
||||||
|
// Damage stats
|
||||||
|
action.resources.attributesConsumed.forEach(attConsumed => {
|
||||||
|
if (!attConsumed.quantity) return;
|
||||||
|
let stat = CreatureProperties.findOne(attConsumed.statId);
|
||||||
|
damagePropertyWork({
|
||||||
|
property: stat,
|
||||||
|
operation: 'increment',
|
||||||
|
value: attConsumed.quantity,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ import { includes, cloneDeep } from 'lodash';
|
|||||||
// The computation memo is an in-memory data structure used only during the
|
// The computation memo is an in-memory data structure used only during the
|
||||||
// computation process
|
// computation process
|
||||||
export default class ComputationMemo {
|
export default class ComputationMemo {
|
||||||
constructor(props){
|
constructor(props, creature){
|
||||||
this.statsByVariableName = {};
|
this.statsByVariableName = {};
|
||||||
this.extraStatsByVariableName = {};
|
this.extraStatsByVariableName = {};
|
||||||
this.statsById = {};
|
this.statsById = {};
|
||||||
@@ -15,6 +15,10 @@ export default class ComputationMemo {
|
|||||||
this.classes = {};
|
this.classes = {};
|
||||||
this.togglesById = {};
|
this.togglesById = {};
|
||||||
this.toggleIds = new Set();
|
this.toggleIds = new Set();
|
||||||
|
// Equipped items that might be used as ammo
|
||||||
|
this.equipmentById = {};
|
||||||
|
// Properties that have calculations, but don't impact other properties
|
||||||
|
this.endStepPropsById = {};
|
||||||
// First note all the ids of all the toggles
|
// First note all the ids of all the toggles
|
||||||
props.forEach((prop) => {
|
props.forEach((prop) => {
|
||||||
if (
|
if (
|
||||||
@@ -38,6 +42,10 @@ export default class ComputationMemo {
|
|||||||
) {
|
) {
|
||||||
// Add all the stats
|
// Add all the stats
|
||||||
this.addStat(prop);
|
this.addStat(prop);
|
||||||
|
} else if (
|
||||||
|
prop.type === 'item'
|
||||||
|
) {
|
||||||
|
this.addEquipment(prop);
|
||||||
} else {
|
} else {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -49,8 +57,19 @@ export default class ComputationMemo {
|
|||||||
this.addProficiency(prop);
|
this.addProficiency(prop);
|
||||||
} else if (prop.type === 'classLevel'){
|
} else if (prop.type === 'classLevel'){
|
||||||
this.addClassLevel(prop);
|
this.addClassLevel(prop);
|
||||||
|
} else {
|
||||||
|
this.addEndStepProp(prop);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
for (let name in creature.denormalizedStats){
|
||||||
|
if (!this.statsByVariableName[name]){
|
||||||
|
this.statsByVariableName[name] = {
|
||||||
|
variableName: name,
|
||||||
|
value: creature.denormalizedStats[name],
|
||||||
|
computationDetails: propDetailsByType.denormalizedStat(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
registerProperty(prop){
|
registerProperty(prop){
|
||||||
this.originalPropsById[prop._id] = cloneDeep(prop);
|
this.originalPropsById[prop._id] = cloneDeep(prop);
|
||||||
@@ -63,46 +82,6 @@ export default class ComputationMemo {
|
|||||||
});
|
});
|
||||||
return prop;
|
return prop;
|
||||||
}
|
}
|
||||||
/*
|
|
||||||
storeHighestClassLevel(name, prop, isBaseClass){
|
|
||||||
// Only store the highest level classLevel
|
|
||||||
let stat = this.statsByVariableName[name]
|
|
||||||
if (!stat){
|
|
||||||
this.statsByVariableName[name] = prop;
|
|
||||||
if (isBaseClass){
|
|
||||||
this.classes[name] = prop;
|
|
||||||
}
|
|
||||||
} else if (!has(stat, 'level')){
|
|
||||||
// Stat is overriden by an attribute
|
|
||||||
return;
|
|
||||||
} else if (stat.level < prop.level) {
|
|
||||||
this.statsByVariableName[name] = prop;
|
|
||||||
if (isBaseClass){
|
|
||||||
this.classes[name] = prop;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.updateLevel();
|
|
||||||
}
|
|
||||||
updateLevel(){
|
|
||||||
let currentLevel = this.statsByVariableName['level'];
|
|
||||||
if (!currentLevel){
|
|
||||||
currentLevel = {
|
|
||||||
value: 0,
|
|
||||||
computationDetails: {
|
|
||||||
builtIn: true,
|
|
||||||
computed: true,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
this.statsByVariableName['level'] = currentLevel;
|
|
||||||
}
|
|
||||||
// bail out if overriden by an attribute
|
|
||||||
if (!currentLevel.computationDetails.builtIn) return;
|
|
||||||
let level = 0;
|
|
||||||
for (let name in this.classes){
|
|
||||||
level += this.classes[name].level || 0;
|
|
||||||
}
|
|
||||||
this.statsByVariableName['level'].value = level;
|
|
||||||
}*/
|
|
||||||
addToggle(prop){
|
addToggle(prop){
|
||||||
prop = this.registerProperty(prop);
|
prop = this.registerProperty(prop);
|
||||||
this.togglesById[prop._id] = prop;
|
this.togglesById[prop._id] = prop;
|
||||||
@@ -212,6 +191,14 @@ export default class ComputationMemo {
|
|||||||
});
|
});
|
||||||
return targets;
|
return targets;
|
||||||
}
|
}
|
||||||
|
addEquipment(prop){
|
||||||
|
prop = this.registerProperty(prop);
|
||||||
|
this.equipmentById[prop._id] = prop;
|
||||||
|
}
|
||||||
|
addEndStepProp(prop){
|
||||||
|
prop = this.registerProperty(prop);
|
||||||
|
this.endStepPropsById[prop._id] = prop;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isAbility(prop){
|
function isAbility(prop){
|
||||||
@@ -237,10 +224,17 @@ function isSkillOperation(prop){
|
|||||||
}
|
}
|
||||||
|
|
||||||
function propDetails(prop){
|
function propDetails(prop){
|
||||||
return propDetailsByType[prop.type]() || {};
|
return propDetailsByType[prop.type] && propDetailsByType[prop.type]() ||
|
||||||
|
propDetailsByType.default();
|
||||||
}
|
}
|
||||||
|
|
||||||
const propDetailsByType = {
|
const propDetailsByType = {
|
||||||
|
default(){
|
||||||
|
return {
|
||||||
|
toggleAncestors: [],
|
||||||
|
disabledByToggle: false,
|
||||||
|
};
|
||||||
|
},
|
||||||
toggle(){
|
toggle(){
|
||||||
return {
|
return {
|
||||||
computed: false,
|
computed: false,
|
||||||
@@ -291,4 +285,10 @@ const propDetailsByType = {
|
|||||||
disabledByToggle: false,
|
disabledByToggle: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
denormalizedStat(){
|
||||||
|
return {
|
||||||
|
toggleAncestors: [],
|
||||||
|
disabledByToggle: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,14 @@ import evaluateCalculation from '/imports/api/creature/computation/evaluateCalcu
|
|||||||
|
|
||||||
export default class EffectAggregator{
|
export default class EffectAggregator{
|
||||||
constructor(stat, memo){
|
constructor(stat, memo){
|
||||||
|
delete this.baseValueErrors;
|
||||||
if (stat.baseValueCalculation){
|
if (stat.baseValueCalculation){
|
||||||
this.statBaseValue = evaluateCalculation(stat.baseValueCalculation, memo);
|
let {result, context} = evaluateCalculation(stat.baseValueCalculation, memo);
|
||||||
this.base = +this.statBaseValue;
|
this.statBaseValue = result.value;
|
||||||
|
if (context.errors.length){
|
||||||
|
this.baseValueErrors = context.errors;
|
||||||
|
}
|
||||||
|
this.base = this.statBaseValue;
|
||||||
} else {
|
} else {
|
||||||
this.base = 0;
|
this.base = 0;
|
||||||
}
|
}
|
||||||
@@ -16,17 +21,22 @@ export default class EffectAggregator{
|
|||||||
this.disadvantage = 0;
|
this.disadvantage = 0;
|
||||||
this.passiveAdd = 0;
|
this.passiveAdd = 0;
|
||||||
this.fail = 0;
|
this.fail = 0;
|
||||||
|
this.set = undefined;
|
||||||
this.conditional = [];
|
this.conditional = [];
|
||||||
this.rollBonus = [];
|
this.rollBonus = [];
|
||||||
|
this.hasNoEffects = true;
|
||||||
}
|
}
|
||||||
addEffect(effect){
|
addEffect(effect){
|
||||||
let result = effect.result;
|
let result = effect.result;
|
||||||
|
if (this.hasNoEffects) this.hasNoEffects = false;
|
||||||
switch(effect.operation){
|
switch(effect.operation){
|
||||||
case 'base':
|
case 'base':
|
||||||
// Take the largest base value
|
// Take the largest base value
|
||||||
this.base = result > this.base ? result : this.base;
|
this.base = result > this.base ? result : this.base;
|
||||||
if (effect.statBase){
|
if (effect.statBase){
|
||||||
this.statBaseValue = result > this.statBaseValue ? result : this.statBaseValue;
|
if (this.statBaseValue === undefined || result > this.statBaseValue){
|
||||||
|
this.statBaseValue = result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 'add':
|
case 'add':
|
||||||
@@ -45,6 +55,10 @@ export default class EffectAggregator{
|
|||||||
// Take the smallest max value
|
// Take the smallest max value
|
||||||
this.max = result < this.max ? result : this.max;
|
this.max = result < this.max ? result : this.max;
|
||||||
break;
|
break;
|
||||||
|
case 'set':
|
||||||
|
// Take the highest set value
|
||||||
|
this.set = this.set === undefined || result > this.set ? result : this.set;
|
||||||
|
break;
|
||||||
case 'advantage':
|
case 'advantage':
|
||||||
// Sum number of advantages
|
// Sum number of advantages
|
||||||
this.advantage++;
|
this.advantage++;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import math from '/imports/math.js';
|
import { parse, CompilationContext } from '/imports/parser/parser.js';
|
||||||
import bareSymbolSubtitutor from '/imports/api/creature/computation/utility/bareSymbolSubtitutor.js';
|
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
||||||
|
|
||||||
export default function evaluateString(string, scope){
|
export default function evaluateString(string, scope, fn = 'compile'){
|
||||||
let errors = [];
|
let errors = [];
|
||||||
if (!string){
|
if (!string){
|
||||||
errors.push('No string provided');
|
errors.push('No string provided');
|
||||||
@@ -11,88 +11,19 @@ export default function evaluateString(string, scope){
|
|||||||
if (!scope) errors.push('No scope provided');
|
if (!scope) errors.push('No scope provided');
|
||||||
|
|
||||||
// Parse the string using mathjs
|
// Parse the string using mathjs
|
||||||
let calc;
|
let node;
|
||||||
try {
|
try {
|
||||||
calc = math.parse(string);
|
node = parse(string);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
errors.push(e);
|
errors.push(e);
|
||||||
return {result: string, errors};
|
return {result: string, errors};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace all bare symbols with symbol.value
|
let context = new CompilationContext();
|
||||||
let transformedCalc = calc.transform(bareSymbolSubtitutor(scope));
|
let result = node[fn](scope, context);
|
||||||
|
if (result instanceof ConstantNode){
|
||||||
// Evaluate the expression to a number or return with substitutions
|
return {result: result.value, errors: context.errors}
|
||||||
try {
|
} else {
|
||||||
let result = transformedCalc.evaluate(scope);
|
return {result: result.toString(), errors: context.errors};
|
||||||
return {result, errors};
|
|
||||||
} catch (e1){
|
|
||||||
errors.push(e1);
|
|
||||||
try {
|
|
||||||
let result = simplifyWithAccessors(transformedCalc, scope).toHTML();
|
|
||||||
return {result, errors};
|
|
||||||
} catch (e2){
|
|
||||||
errors.push(e2);
|
|
||||||
return {result: transformedCalc.toHTML(), errors};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function simplifyWithAccessors(calc, scope){
|
|
||||||
let noAccessorCalc = calc.transform(substituteAccessors(scope));
|
|
||||||
return math.simplify(noAccessorCalc);
|
|
||||||
}
|
|
||||||
|
|
||||||
// returns a function to replace all accessors with either their resolved value
|
|
||||||
// or a symbol to simplify with
|
|
||||||
function substituteAccessors(scope){
|
|
||||||
return function(node){
|
|
||||||
if (node.isAccessorNode){
|
|
||||||
try {
|
|
||||||
return evaluateAccessor(node, scope);
|
|
||||||
} catch (e) {
|
|
||||||
return replaceAccessorWithSymbol(node);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Throws error if symbol is undefined in scope
|
|
||||||
function evaluateAccessor(node, scope){
|
|
||||||
let value = node.evaluate(scope);
|
|
||||||
if (value === undefined){
|
|
||||||
throw 'Undefined symbol'
|
|
||||||
}
|
|
||||||
return new math.ConstantNode(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function replaceAccessorWithSymbol(node){
|
|
||||||
let symbolNode = new math.SymbolNode(node.toString());
|
|
||||||
return symbolNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
function overrideSymbolNodeHTML(symbolNode){
|
|
||||||
let safeName = escape(symbolNode.name);
|
|
||||||
symbolNode.toHTML = function(){
|
|
||||||
console.log('running custom tohtml function')
|
|
||||||
return `<span class="math-symbol math-substitution-failed">${safeName}</span>`
|
|
||||||
}
|
|
||||||
return symbolNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Escape special HTML characters
|
|
||||||
// Copied directly from math.js source to help with overriding toHTML
|
|
||||||
function escape (value) {
|
|
||||||
let text = String(value)
|
|
||||||
text = text.replace(/&/g, '&')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, ''')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
|
|
||||||
return text
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import computeStat from '/imports/api/creature/computation/computeStat.js';
|
import computeStat from '/imports/api/creature/computation/computeStat.js';
|
||||||
import applyToggles from '/imports/api/creature/computation/applyToggles.js';
|
import applyToggles from '/imports/api/creature/computation/applyToggles.js';
|
||||||
|
import evaluateCalculation from '/imports/api/creature/computation/evaluateCalculation.js';
|
||||||
|
|
||||||
export default function combineStat(stat, aggregator, memo){
|
export default function combineStat(stat, aggregator, memo){
|
||||||
if (stat.type === 'attribute'){
|
if (stat.type === 'attribute'){
|
||||||
combineAttribute(stat, aggregator);
|
combineAttribute(stat, aggregator, memo);
|
||||||
} else if (stat.type === 'skill'){
|
} else if (stat.type === 'skill'){
|
||||||
combineSkill(stat, aggregator, memo);
|
combineSkill(stat, aggregator, memo);
|
||||||
} else if (stat.type === 'damageMultiplier'){
|
} else if (stat.type === 'damageMultiplier'){
|
||||||
@@ -11,17 +12,39 @@ export default function combineStat(stat, aggregator, memo){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function combineAttribute(stat, aggregator){
|
function getAggregatorResult(stat, aggregator){
|
||||||
let result = (aggregator.base + aggregator.add) * aggregator.mul;
|
let result = (aggregator.base + aggregator.add) * aggregator.mul;
|
||||||
if (result < aggregator.min) result = aggregator.min;
|
if (result < aggregator.min) {
|
||||||
if (result > aggregator.max) result = aggregator.max;
|
result = aggregator.min;
|
||||||
if (!stat.decimal) result = Math.floor(result);
|
}
|
||||||
stat.value = result;
|
if (result > aggregator.max) {
|
||||||
|
result = aggregator.max;
|
||||||
|
}
|
||||||
|
if (aggregator.set !== undefined) {
|
||||||
|
result = aggregator.set;
|
||||||
|
}
|
||||||
|
if (!stat.decimal && Number.isFinite(result)){
|
||||||
|
result = Math.floor(result);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function combineAttribute(stat, aggregator, memo){
|
||||||
|
stat.value = getAggregatorResult(stat, aggregator);
|
||||||
stat.baseValue = aggregator.statBaseValue;
|
stat.baseValue = aggregator.statBaseValue;
|
||||||
if (stat.attributeType === 'ability') {
|
stat.baseValueErrors = aggregator.baseValueErrors;
|
||||||
stat.modifier = Math.floor((result - 10) / 2);
|
if (stat.attributeType === 'spellSlot'){
|
||||||
|
let {result, context} = evaluateCalculation(stat.spellSlotLevelCalculation, memo);
|
||||||
|
stat.spellSlotLevelValue = result.value;
|
||||||
|
stat.spellSlotLevelErrors = context.errors;
|
||||||
}
|
}
|
||||||
stat.currentValue = stat.value - (stat.damage || 0);
|
stat.currentValue = stat.value - (stat.damage || 0);
|
||||||
|
if (stat.attributeType === 'ability') {
|
||||||
|
stat.modifier = Math.floor((stat.currentValue - 10) / 2);
|
||||||
|
}
|
||||||
|
stat.hide = aggregator.hasNoEffects &&
|
||||||
|
stat.baseValue === undefined ||
|
||||||
|
undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
function combineSkill(stat, aggregator, memo){
|
function combineSkill(stat, aggregator, memo){
|
||||||
@@ -55,11 +78,19 @@ function combineSkill(stat, aggregator, memo){
|
|||||||
}
|
}
|
||||||
// Multiply the proficiency bonus by the actual proficiency
|
// Multiply the proficiency bonus by the actual proficiency
|
||||||
profBonus *= stat.proficiency;
|
profBonus *= stat.proficiency;
|
||||||
|
// Base value
|
||||||
|
stat.baseValue = aggregator.statBaseValue;
|
||||||
|
stat.baseValueErrors = aggregator.baseValueErrors;
|
||||||
// Combine everything to get the final result
|
// Combine everything to get the final result
|
||||||
let result = (stat.abilityMod + profBonus + aggregator.add) * aggregator.mul;
|
let result = (aggregator.base + stat.abilityMod + profBonus + aggregator.add) * aggregator.mul;
|
||||||
if (result < aggregator.min) result = aggregator.min;
|
if (result < aggregator.min) result = aggregator.min;
|
||||||
if (result > aggregator.max) result = aggregator.max;
|
if (result > aggregator.max) result = aggregator.max;
|
||||||
result = Math.floor(result);
|
if (aggregator.set !== undefined) {
|
||||||
|
result = aggregator.set;
|
||||||
|
}
|
||||||
|
if (Number.isFinite(result)){
|
||||||
|
result = Math.floor(result);
|
||||||
|
}
|
||||||
stat.value = result;
|
stat.value = result;
|
||||||
// Advantage/disadvantage
|
// Advantage/disadvantage
|
||||||
if (aggregator.advantage && !aggregator.disadvantage){
|
if (aggregator.advantage && !aggregator.disadvantage){
|
||||||
@@ -79,6 +110,11 @@ function combineSkill(stat, aggregator, memo){
|
|||||||
stat.fail = aggregator.fail;
|
stat.fail = aggregator.fail;
|
||||||
// Rollbonus
|
// Rollbonus
|
||||||
stat.rollBonuses = aggregator.rollBonus;
|
stat.rollBonuses = aggregator.rollBonus;
|
||||||
|
// Hide
|
||||||
|
stat.hide = aggregator.hasNoEffects &&
|
||||||
|
stat.baseValue === undefined &&
|
||||||
|
stat.proficiency == 0 ||
|
||||||
|
undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function combineDamageMultiplier(stat){
|
function combineDamageMultiplier(stat){
|
||||||
|
|||||||
@@ -20,9 +20,12 @@ export default function computeEffect(effect, memo){
|
|||||||
applyToggles(effect, memo);
|
applyToggles(effect, memo);
|
||||||
|
|
||||||
// Determine result of effect calculation
|
// Determine result of effect calculation
|
||||||
|
delete effect.errors;
|
||||||
if (!effect.calculation){
|
if (!effect.calculation){
|
||||||
if(effect.operation === 'add' || effect.operation === 'base'){
|
if(effect.operation === 'add' || effect.operation === 'base'){
|
||||||
effect.result = 0;
|
effect.result = 0;
|
||||||
|
} else {
|
||||||
|
delete effect.result
|
||||||
}
|
}
|
||||||
} else if (Number.isFinite(+effect.calculation)){
|
} else if (Number.isFinite(+effect.calculation)){
|
||||||
effect.result = +effect.calculation;
|
effect.result = +effect.calculation;
|
||||||
@@ -31,7 +34,11 @@ export default function computeEffect(effect, memo){
|
|||||||
} else if(_.contains(['advantage', 'disadvantage', 'fail'], effect.operation)){
|
} else if(_.contains(['advantage', 'disadvantage', 'fail'], effect.operation)){
|
||||||
effect.result = 1;
|
effect.result = 1;
|
||||||
} else {
|
} else {
|
||||||
effect.result = evaluateCalculation(effect.calculation, memo);
|
let {result, context} = evaluateCalculation(effect.calculation, memo);
|
||||||
|
effect.result = result.value;
|
||||||
|
if (context.errors.length){
|
||||||
|
effect.errors = context.errors;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
effect.computationDetails.computed = true;
|
effect.computationDetails.computed = true;
|
||||||
effect.computationDetails.busyComputing = false;
|
effect.computationDetails.busyComputing = false;
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import evaluateCalculation from '/imports/api/creature/computation/evaluateCalculation.js';
|
||||||
|
|
||||||
|
export default function computeEndStepProperty(prop, memo){
|
||||||
|
switch (prop.type){
|
||||||
|
case 'action':
|
||||||
|
case 'spell':
|
||||||
|
computeAction(prop, memo);
|
||||||
|
break;
|
||||||
|
case 'attack':
|
||||||
|
computeAction(prop, memo);
|
||||||
|
computeAttack(prop, memo);
|
||||||
|
break;
|
||||||
|
case 'savingThrow':
|
||||||
|
computeSavingThrow(prop, memo);
|
||||||
|
break;
|
||||||
|
case 'spellList':
|
||||||
|
computeSpellList(prop, memo);
|
||||||
|
break;
|
||||||
|
case 'propertySlot':
|
||||||
|
computeSlot(prop, memo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeAction(prop, memo){
|
||||||
|
// Uses
|
||||||
|
let {result, context} = evaluateCalculation(prop.uses, memo);
|
||||||
|
prop.usesResult = result.value;
|
||||||
|
if (context.errors.length){
|
||||||
|
prop.usesErrors = context.errors;
|
||||||
|
} else {
|
||||||
|
delete prop.usesErrors;
|
||||||
|
}
|
||||||
|
prop.insufficientResources = undefined;
|
||||||
|
if (prop.usesUsed >= prop.usesResult){
|
||||||
|
prop.insufficientResources = true;
|
||||||
|
}
|
||||||
|
if (!prop.resources) return;
|
||||||
|
// Attributes consumed
|
||||||
|
prop.resources.attributesConsumed.forEach((attConsumed, i) => {
|
||||||
|
if (attConsumed.variableName){
|
||||||
|
let stat = memo.statsByVariableName[attConsumed.variableName];
|
||||||
|
prop.resources.attributesConsumed[i].statId = stat && stat._id;
|
||||||
|
prop.resources.attributesConsumed[i].statName = stat && stat.name;
|
||||||
|
let available = stat && stat.currentValue || 0;
|
||||||
|
prop.resources.attributesConsumed[i].available = available;
|
||||||
|
if (available < attConsumed.quantity){
|
||||||
|
prop.insufficientResources = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Items consumed
|
||||||
|
prop.resources.itemsConsumed.forEach((itemConsumed, i) => {
|
||||||
|
let item = itemConsumed.itemId && memo.equipmentById[itemConsumed.itemId];
|
||||||
|
prop.resources.itemsConsumed[i].itemId = item && item._id;
|
||||||
|
let available = item && item.quantity || 0;
|
||||||
|
prop.resources.itemsConsumed[i].available = available;
|
||||||
|
let name = item && item.name;
|
||||||
|
if (item && item.quantity !== 1 && item.plural){
|
||||||
|
name = item.plural;
|
||||||
|
}
|
||||||
|
prop.resources.itemsConsumed[i].itemName = name;
|
||||||
|
prop.resources.itemsConsumed[i].itemIcon = item && item.icon;
|
||||||
|
prop.resources.itemsConsumed[i].itemColor = item && item.color;
|
||||||
|
if (!item || available < itemConsumed.quantity){
|
||||||
|
prop.insufficientResources = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function computePropertyField(prop, memo, fieldName, fn){
|
||||||
|
let {result, context} = evaluateCalculation(prop[fieldName], memo, fn);
|
||||||
|
prop[`${fieldName}Result`] = result.value;
|
||||||
|
if (context.errors.length){
|
||||||
|
prop[`${fieldName}Errors`] = context.errors;
|
||||||
|
} else {
|
||||||
|
delete prop[`${fieldName}Errors`];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeAttack(prop, memo){
|
||||||
|
computePropertyField(prop, memo, 'rollBonus');
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeSavingThrow(prop, memo){
|
||||||
|
computePropertyField(prop, memo, 'dc');
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeSpellList(prop, memo){
|
||||||
|
computePropertyField(prop, memo, 'maxPrepared');
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeSlot(prop, memo){
|
||||||
|
computePropertyField(prop, memo, 'slotCondition');
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import computeLevels from '/imports/api/creature/computation/computeLevels.js';
|
|||||||
import computeStat from '/imports/api/creature/computation/computeStat.js';
|
import computeStat from '/imports/api/creature/computation/computeStat.js';
|
||||||
import computeEffect from '/imports/api/creature/computation/computeEffect.js';
|
import computeEffect from '/imports/api/creature/computation/computeEffect.js';
|
||||||
import computeToggle from '/imports/api/creature/computation/computeToggle.js';
|
import computeToggle from '/imports/api/creature/computation/computeToggle.js';
|
||||||
|
import computeEndStepProperty from '/imports/api/creature/computation/computeEndStepProperty.js';
|
||||||
|
|
||||||
export default function computeMemo(memo){
|
export default function computeMemo(memo){
|
||||||
// Compute level
|
// Compute level
|
||||||
@@ -15,8 +16,12 @@ export default function computeMemo(memo){
|
|||||||
each(memo.unassignedEffects, effect => {
|
each(memo.unassignedEffects, effect => {
|
||||||
computeEffect(effect, memo);
|
computeEffect(effect, memo);
|
||||||
});
|
});
|
||||||
|
// Compute toggles which didn't already get computed by dependencies
|
||||||
forOwn(memo.togglesById, toggle => {
|
forOwn(memo.togglesById, toggle => {
|
||||||
computeToggle(toggle, memo);
|
computeToggle(toggle, memo);
|
||||||
});
|
});
|
||||||
// Compute class levels
|
// Compute end step properties
|
||||||
|
forOwn(memo.endStepPropsById, prop => {
|
||||||
|
computeEndStepProperty(prop, memo);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export default function computeToggle(toggle, memo){
|
|||||||
toggle.computationDetails.busyComputing = true;
|
toggle.computationDetails.busyComputing = true;
|
||||||
|
|
||||||
// Do work
|
// Do work
|
||||||
|
delete toggle.errors;
|
||||||
if (toggle.enabled){
|
if (toggle.enabled){
|
||||||
toggle.toggleResult = true;
|
toggle.toggleResult = true;
|
||||||
} else if (toggle.disabled){
|
} else if (toggle.disabled){
|
||||||
@@ -25,7 +26,11 @@ export default function computeToggle(toggle, memo){
|
|||||||
} else if (Number.isFinite(+toggle.condition)){
|
} else if (Number.isFinite(+toggle.condition)){
|
||||||
toggle.toggleResult = !!+toggle.condition;
|
toggle.toggleResult = !!+toggle.condition;
|
||||||
} else {
|
} else {
|
||||||
toggle.toggleResult = evaluateCalculation(toggle.condition, memo);
|
let {result, context} = evaluateCalculation(toggle.condition, memo);
|
||||||
|
toggle.toggleResult = !!result.value;
|
||||||
|
if (context.errors.length){
|
||||||
|
toggle.errors = context.errors;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
toggle.computationDetails.computed = true;
|
toggle.computationDetails.computed = true;
|
||||||
toggle.computationDetails.busyComputing = false;
|
toggle.computationDetails.busyComputing = false;
|
||||||
|
|||||||
@@ -1,31 +1,41 @@
|
|||||||
import bareSymbolSubtitutor from '/imports/api/creature/computation/utility/bareSymbolSubtitutor.js';
|
|
||||||
import computeStat from '/imports/api/creature/computation/computeStat.js';
|
import computeStat from '/imports/api/creature/computation/computeStat.js';
|
||||||
import math from '/imports/math.js';
|
import { parse, CompilationContext } from '/imports/parser/parser.js';
|
||||||
|
import SymbolNode from '/imports/parser/parseTree/SymbolNode.js';
|
||||||
|
import AccessorNode from '/imports/parser/parseTree/AccessorNode.js';
|
||||||
|
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
||||||
|
|
||||||
export default function evaluateCalculation(string, memo){
|
/* Convert a calculation into a constant output and errors*/
|
||||||
if (!string) return string;
|
export default function evaluateCalculation(string, memo, fn = 'reduce'){
|
||||||
// Parse the string using mathjs
|
if (!string) return {
|
||||||
|
context: {errors: []},
|
||||||
|
result: new ConstantNode({value: string, type: 'string'}),
|
||||||
|
};
|
||||||
|
let errors = [];
|
||||||
|
// Parse the string
|
||||||
let calc;
|
let calc;
|
||||||
try {
|
try {
|
||||||
calc = math.parse(string);
|
calc = parse(string);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return string;
|
errors.push({
|
||||||
|
type: 'parsing',
|
||||||
|
message: e.message || e
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
context: {errors},
|
||||||
|
result: new ConstantNode({value: string, type: 'string'}),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
// Ensure all symbol nodes are defined and coputed
|
// Ensure all symbol nodes are defined and coputed
|
||||||
calc.traverse(node => {
|
calc.traverse(node => {
|
||||||
if (node.isSymbolNode){
|
if (node instanceof SymbolNode || node instanceof AccessorNode){
|
||||||
let stat = memo.statsByVariableName[node.name];
|
let stat = memo.statsByVariableName[node.name];
|
||||||
if (stat && !stat.computationDetails.computed){
|
if (stat && !stat.computationDetails.computed){
|
||||||
computeStat(stat, memo);
|
computeStat(stat, memo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// Ensure any bare symbols are value accessors instead
|
// Evaluate
|
||||||
let substitutedCalc = calc.transform(bareSymbolSubtitutor(memo.statsByVariableName));
|
let context = new CompilationContext();
|
||||||
// Evaluate the expression to a number or return with substitutions
|
let result = calc[fn](memo.statsByVariableName, context);
|
||||||
try {
|
return {result, context};
|
||||||
return substitutedCalc.evaluate(memo.statsByVariableName);
|
|
||||||
} catch (e){
|
|
||||||
return substitutedCalc.toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,35 @@
|
|||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
||||||
import ComputationMemo from '/imports/api/creature/computation/ComputationMemo.js';
|
import ComputationMemo from '/imports/api/creature/computation/ComputationMemo.js';
|
||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
import computeMemo from '/imports/api/creature/computation/computeMemo.js';
|
import computeMemo from '/imports/api/creature/computation/computeMemo.js';
|
||||||
import getActiveProperties from '/imports/api/creature/getActiveProperties.js';
|
|
||||||
import writeAlteredProperties from '/imports/api/creature/computation/writeAlteredProperties.js';
|
import writeAlteredProperties from '/imports/api/creature/computation/writeAlteredProperties.js';
|
||||||
import writeCreatureVariables from '/imports/api/creature/computation/writeCreatureVariables.js';
|
import writeCreatureVariables from '/imports/api/creature/computation/writeCreatureVariables.js';
|
||||||
import { recomputeDamageMultipliersById } from '/imports/api/creature/damageMultiplierDenormalise/recomputeDamageMultipliers.js'
|
import { recomputeDamageMultipliersById } from '/imports/api/creature/denormalise/recomputeDamageMultipliers.js';
|
||||||
|
import recomputeInactiveProperties from '/imports/api/creature/denormalise/recomputeInactiveProperties.js';
|
||||||
|
import recomputeSlotFullness from '/imports/api/creature/denormalise/recomputeSlotFullness.js';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
|
||||||
export const recomputeCreature = new ValidatedMethod({
|
export const recomputeCreature = new ValidatedMethod({
|
||||||
|
|
||||||
name: 'Creatures.methods.recomputeCreature',
|
name: 'creatures.recomputeCreature',
|
||||||
|
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
charId: { type: String }
|
charId: { type: String }
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
run({charId}) {
|
run({charId}) {
|
||||||
|
let creature = Creatures.findOne(charId);
|
||||||
// Permission
|
// Permission
|
||||||
assertEditPermission(charId, this.userId);
|
assertEditPermission(creature, this.userId);
|
||||||
// Work, call this direcly if you are already in a method that has checked
|
// Work, call this direcly if you are already in a method that has checked
|
||||||
// for permission to edit a given character
|
// for permission to edit a given character
|
||||||
recomputeCreatureById(charId);
|
recomputeCreatureById(charId);
|
||||||
@@ -33,8 +44,21 @@ const calculationPropertyTypes = [
|
|||||||
'proficiency',
|
'proficiency',
|
||||||
'classLevel',
|
'classLevel',
|
||||||
'toggle',
|
'toggle',
|
||||||
|
'item',
|
||||||
|
// End step types
|
||||||
|
'action',
|
||||||
|
'attack',
|
||||||
|
'savingThrow',
|
||||||
|
'spellList',
|
||||||
|
'spell',
|
||||||
|
'propertySlot',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
export function recomputeCreatureById(creatureId){
|
||||||
|
let creature = Creatures.findOne(creatureId);
|
||||||
|
recomputeCreatureByDoc(creature);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This function is the heart of DiceCloud. It recomputes a creature's stats,
|
* This function is the heart of DiceCloud. It recomputes a creature's stats,
|
||||||
* distilling down effects and proficiencies into the final stats that make up
|
* distilling down effects and proficiencies into the final stats that make up
|
||||||
@@ -71,17 +95,44 @@ const calculationPropertyTypes = [
|
|||||||
* - Mark the stat as computed
|
* - Mark the stat as computed
|
||||||
* - Write the computed results back to the database
|
* - Write the computed results back to the database
|
||||||
*/
|
*/
|
||||||
export function recomputeCreatureById(creatureId){
|
export function recomputeCreatureByDoc(creature){
|
||||||
let props = getActiveProperties({
|
const creatureId = creature._id;
|
||||||
ancestorId: creatureId,
|
// find all toggles that have conditions, even if they are inactive
|
||||||
filter: {type: {$in: calculationPropertyTypes}},
|
let toggleIds = CreatureProperties.find({
|
||||||
includeUntoggled: true,
|
'ancestors.id': creatureId,
|
||||||
});
|
type: 'toggle',
|
||||||
let computationMemo = new ComputationMemo(props);
|
removed: {$ne: true},
|
||||||
|
condition: { $exists: true },
|
||||||
|
}, {
|
||||||
|
fields: {_id: 1},
|
||||||
|
}).map(t => t._id);
|
||||||
|
// Find all the active properties
|
||||||
|
let props = CreatureProperties.find({
|
||||||
|
'ancestors.id': creatureId,
|
||||||
|
removed: {$ne: true},
|
||||||
|
type: {$in: calculationPropertyTypes},
|
||||||
|
$or: [
|
||||||
|
{inactive: {$ne: true}},
|
||||||
|
// But also the inactive computed toggles and their decendants
|
||||||
|
{'ancestors.id': {$in: toggleIds}},
|
||||||
|
{_id: {$in: toggleIds}},
|
||||||
|
]
|
||||||
|
}, {
|
||||||
|
fields: { // Filter out potentially large fields
|
||||||
|
icon: 0,
|
||||||
|
summary: 0,
|
||||||
|
description: 0,
|
||||||
|
},
|
||||||
|
sort: {
|
||||||
|
order: 1,
|
||||||
|
}
|
||||||
|
}).fetch();
|
||||||
|
let computationMemo = new ComputationMemo(props, creature);
|
||||||
|
recomputeInactiveProperties(creatureId);
|
||||||
computeMemo(computationMemo);
|
computeMemo(computationMemo);
|
||||||
writeAlteredProperties(computationMemo);
|
writeAlteredProperties(computationMemo);
|
||||||
writeCreatureVariables(computationMemo, creatureId);
|
writeCreatureVariables(computationMemo, creatureId);
|
||||||
// if(Meteor.isClient) console.log(computationMemo);
|
|
||||||
recomputeDamageMultipliersById(creatureId);
|
recomputeDamageMultipliersById(creatureId);
|
||||||
|
recomputeSlotFullness(creatureId);
|
||||||
return computationMemo;
|
return computationMemo;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
import math from '/imports/math.js';
|
|
||||||
|
|
||||||
export default function bareSymbolSubtitutor(scope){
|
|
||||||
return function(node, path){
|
|
||||||
if (!scope) return node;
|
|
||||||
if (node.isFunctionNode){
|
|
||||||
let fn = node.fn;
|
|
||||||
if (fn && fn.isSymbolNode){
|
|
||||||
fn.skipReplacement = true;
|
|
||||||
}
|
|
||||||
return node;
|
|
||||||
} else if (
|
|
||||||
node.isSymbolNode &&
|
|
||||||
path !== 'object' &&
|
|
||||||
node.skipReplacement !== true
|
|
||||||
) {
|
|
||||||
let stat = scope[node.name];
|
|
||||||
if (!stat) return node;
|
|
||||||
return new math.ConstantNode(stat.value);
|
|
||||||
} else {
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,31 @@
|
|||||||
import { Meteor } from 'meteor/meteor'
|
import { Meteor } from 'meteor/meteor'
|
||||||
import { isEqual, forOwn } from 'lodash';
|
import { isEqual, forOwn } from 'lodash';
|
||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
// Schemas
|
||||||
|
// Calculated props
|
||||||
import { ComputedOnlySkillSchema } from '/imports/api/properties/Skills.js';
|
import { ComputedOnlySkillSchema } from '/imports/api/properties/Skills.js';
|
||||||
import { ComputedOnlyAttributeSchema } from '/imports/api/properties/Attributes.js';
|
import { ComputedOnlyAttributeSchema } from '/imports/api/properties/Attributes.js';
|
||||||
import { ComputedOnlyEffectSchema } from '/imports/api/properties/Effects.js';
|
import { ComputedOnlyEffectSchema } from '/imports/api/properties/Effects.js';
|
||||||
import { ComputedOnlyToggleSchema } from '/imports/api/properties/Toggles.js';
|
import { ComputedOnlyToggleSchema } from '/imports/api/properties/Toggles.js';
|
||||||
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
// End step props
|
||||||
|
import { ComputedOnlyActionSchema } from '/imports/api/properties/Actions.js';
|
||||||
|
import { ComputedOnlyAttackSchema } from '/imports/api/properties/Attacks.js';
|
||||||
|
import { ComputedOnlySavingThrowSchema } from '/imports/api/properties/SavingThrows.js';
|
||||||
|
import { ComputedOnlySpellListSchema } from '/imports/api/properties/SpellLists.js';
|
||||||
|
import { ComputedOnlySpellSchema } from '/imports/api/properties/Spells.js';
|
||||||
|
import { ComputedOnlySlotSchema } from '/imports/api/properties/Slots.js';
|
||||||
|
|
||||||
const schemasByType = {
|
const schemasByType = {
|
||||||
'skill': ComputedOnlySkillSchema,
|
'skill': ComputedOnlySkillSchema,
|
||||||
'attribute': ComputedOnlyAttributeSchema,
|
'attribute': ComputedOnlyAttributeSchema,
|
||||||
'effect': ComputedOnlyEffectSchema,
|
'effect': ComputedOnlyEffectSchema,
|
||||||
'toggle': ComputedOnlyToggleSchema,
|
'toggle': ComputedOnlyToggleSchema,
|
||||||
|
'action': ComputedOnlyActionSchema,
|
||||||
|
'attack': ComputedOnlyAttackSchema,
|
||||||
|
'savingThrow': ComputedOnlySavingThrowSchema,
|
||||||
|
'spellList': ComputedOnlySpellListSchema,
|
||||||
|
'spell': ComputedOnlySpellSchema,
|
||||||
|
'propertySlot': ComputedOnlySlotSchema,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function writeAlteredProperties(memo){
|
export default function writeAlteredProperties(memo){
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { pick, forOwn } from 'lodash';
|
import { pick, forOwn } from 'lodash';
|
||||||
import Creatures from '/imports/api/creature/Creatures.js';
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import VERSION from '/imports/constants/VERSION.js';
|
||||||
|
|
||||||
export default function writeCreatureVariables(memo, creatureId) {
|
export default function writeCreatureVariables(memo, creatureId) {
|
||||||
const fields = [
|
const fields = [
|
||||||
@@ -31,5 +32,8 @@ export default function writeCreatureVariables(memo, creatureId) {
|
|||||||
let condensedStat = pick(stat, fields);
|
let condensedStat = pick(stat, fields);
|
||||||
memo.creatureVariables[variableName] = condensedStat;
|
memo.creatureVariables[variableName] = condensedStat;
|
||||||
});
|
});
|
||||||
Creatures.update(creatureId, {$set: {variables: memo.creatureVariables}});
|
Creatures.update(creatureId, {$set: {
|
||||||
|
variables: memo.creatureVariables,
|
||||||
|
computeVersion: VERSION,
|
||||||
|
}});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,6 @@ export function assertEditPermission(creature, userId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function assertViewPermission(creature, userId) {
|
export function assertViewPermission(creature, userId) {
|
||||||
creature = getCreature(creature, {owner: 1, writers: 1, public: 1});
|
creature = getCreature(creature, {owner: 1, readers:1, writers: 1, public: 1});
|
||||||
viewPermission(creature, userId);
|
viewPermission(creature, userId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js';
|
||||||
|
import getClosestPropertyAncestorCreature from '/imports/api/creature/creatureProperties/getClosestPropertyAncestorCreature.js';
|
||||||
|
|
||||||
|
export default function assertPropertyEditPermission(prop, userId){
|
||||||
|
let creature = getClosestPropertyAncestorCreature(prop);
|
||||||
|
assertEditPermission(creature, userId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import getClosestPropertyAncestorCreatureId from '/imports/api/creature/creatureProperties/getClosestPropertyAncestorCreatureId.js';
|
||||||
|
|
||||||
|
export default function getClosestPropertyAncestorCreature(prop){
|
||||||
|
let creatureId = getClosestPropertyAncestorCreatureId(prop);
|
||||||
|
return Creatures.findOne(creatureId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export default function getClosestPropertyAncestorCreatureId(prop){
|
||||||
|
if (!prop.ancestors) throw 'Property has no ancestors';
|
||||||
|
let creatureId;
|
||||||
|
// Find the last ancestor in the creature collection
|
||||||
|
for (let i = prop.ancestors.length - 1; i >= 0; i--){
|
||||||
|
if (prop.ancestors[i].collection === 'creatures'){
|
||||||
|
creatureId = prop.ancestors[i].id;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!creatureId) throw 'This property has no creature ancestors';
|
||||||
|
return creatureId;
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js';
|
||||||
|
import { organizeDoc } from '/imports/api/parenting/organizeMethods.js';
|
||||||
|
import getClosestPropertyAncestorCreature from '/imports/api/creature/creatureProperties/getClosestPropertyAncestorCreature.js';
|
||||||
|
import INVENTORY_TAGS from '/imports/constants/INVENTORY_TAGS.js';
|
||||||
|
|
||||||
|
function getParentRefByTag(creatureId, tag){
|
||||||
|
let prop = CreatureProperties.findOne({
|
||||||
|
'ancestors.id': creatureId,
|
||||||
|
removed: {$ne: true},
|
||||||
|
inactive: {$ne: true},
|
||||||
|
tags: tag,
|
||||||
|
}, {
|
||||||
|
sort: {order: 1},
|
||||||
|
});
|
||||||
|
if (prop){
|
||||||
|
return {id: prop._id, collection: 'creatureProperties'};
|
||||||
|
} else {
|
||||||
|
return {id: creatureId, collection: 'creatures'};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Equipping or unequipping an item will also change its parent
|
||||||
|
const equipItem = new ValidatedMethod({
|
||||||
|
name: 'creatureProperties.equip',
|
||||||
|
validate({_id, equipped}){
|
||||||
|
if (!_id) throw new Meteor.Error('No _id', '_id is required');
|
||||||
|
if (equipped !== true && equipped !== false) {
|
||||||
|
throw new Meteor.Error('No equipped', 'equipped is required to be true or false');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({_id, equipped}) {
|
||||||
|
let item = CreatureProperties.findOne(_id);
|
||||||
|
if (item.type !== 'item') throw new Meteor.Error('wrong type',
|
||||||
|
'Equip and unequip can only be performed on items');
|
||||||
|
let creature = getClosestPropertyAncestorCreature(item);
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
CreatureProperties.update(_id, {
|
||||||
|
$set: {equipped},
|
||||||
|
}, {
|
||||||
|
selector: {type: 'item'},
|
||||||
|
});
|
||||||
|
let tag = equipped ? INVENTORY_TAGS.equipment : INVENTORY_TAGS.carried;
|
||||||
|
let parentRef = getParentRefByTag(creature._id, tag);
|
||||||
|
// organizeDoc handles recompuation
|
||||||
|
organizeDoc.call({
|
||||||
|
docRef: {
|
||||||
|
id: _id,
|
||||||
|
collection: 'creatureProperties',
|
||||||
|
},
|
||||||
|
parentRef,
|
||||||
|
order: Number.MAX_SAFE_INTEGER,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export { equipItem, getParentRefByTag }
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
||||||
import Creatures from '/imports/api/creature/Creatures.js';
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
@@ -6,12 +7,18 @@ import getActiveProperties from '/imports/api/creature/getActiveProperties.js';
|
|||||||
|
|
||||||
export const recomputeDamageMultipliers = new ValidatedMethod({
|
export const recomputeDamageMultipliers = new ValidatedMethod({
|
||||||
|
|
||||||
name: 'Creatures.methods.recomputeDamageMultipliers',
|
name: 'creatures.recomputeDamageMultipliers',
|
||||||
|
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
creatureId: { type: String }
|
creatureId: { type: String }
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
run({creatureId}) {
|
run({creatureId}) {
|
||||||
// Permission
|
// Permission
|
||||||
assertEditPermission(creatureId, this.userId);
|
assertEditPermission(creatureId, this.userId);
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
|
||||||
|
export default function recomputeInactiveProperties(ancestorId){
|
||||||
|
let disabledFilter = {
|
||||||
|
'ancestors.id': ancestorId,
|
||||||
|
$or: [
|
||||||
|
{disabled: true}, // Everything can be disabled
|
||||||
|
{type: 'buff', applied: false}, // Buffs can be applied
|
||||||
|
{type: 'item', equipped: {$ne: true}},
|
||||||
|
{type: 'toggle', toggleResult: false},
|
||||||
|
{type: 'spell', prepared: {$ne: true}, alwaysPrepared: {$ne: true}},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let disabledIds = CreatureProperties.find(disabledFilter, {
|
||||||
|
fields: {_id: 1},
|
||||||
|
}).map(prop => prop._id);
|
||||||
|
|
||||||
|
// Deactivate relevant properties
|
||||||
|
// Inactive properties
|
||||||
|
CreatureProperties.update({
|
||||||
|
'ancestors.id': ancestorId,
|
||||||
|
'_id': {$in: disabledIds},
|
||||||
|
$or: [{inactive: {$ne: true}}, {deactivatedByAncestor: true}],
|
||||||
|
}, {
|
||||||
|
$set: {inactive: true},
|
||||||
|
$unset: {deactivatedByAncestor: 1},
|
||||||
|
}, {
|
||||||
|
multi: true,
|
||||||
|
selector: {type: 'any'},
|
||||||
|
});
|
||||||
|
// Decendants of inactive properties
|
||||||
|
CreatureProperties.update({
|
||||||
|
'ancestors.id': {$eq: ancestorId, $in: disabledIds},
|
||||||
|
$or: [{inactive: {$ne: true}}, {deactivatedByAncestor: {$ne: true}}],
|
||||||
|
}, {
|
||||||
|
$set: {
|
||||||
|
inactive: true,
|
||||||
|
deactivatedByAncestor: true,
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
multi: true,
|
||||||
|
selector: {type: 'any'},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove inactive from all the properties that are inactive but shouldn't be
|
||||||
|
CreatureProperties.update({
|
||||||
|
'ancestors.id': {$eq: ancestorId, $nin: disabledIds},
|
||||||
|
'_id': {$nin: disabledIds},
|
||||||
|
$or: [{inactive: true}, {deactivatedByAncestor: true}],
|
||||||
|
}, {
|
||||||
|
$unset: {
|
||||||
|
inactive: 1,
|
||||||
|
deactivatedByAncestor: 1,
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
multi: true,
|
||||||
|
selector: {type: 'any'},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
// n + 1 database queries + n potential updates for n slots. Could be sped up.
|
||||||
|
export default function recomputeSlotFullness(ancestorId){
|
||||||
|
CreatureProperties.find({
|
||||||
|
'ancestors.id': ancestorId,
|
||||||
|
type: 'propertySlot',
|
||||||
|
}).forEach(slot => {
|
||||||
|
let children = CreatureProperties.find({
|
||||||
|
'parent.id': slot._id,
|
||||||
|
removed: {$ne: true},
|
||||||
|
}, {
|
||||||
|
fields: {
|
||||||
|
slotQuantityFilled: 1,
|
||||||
|
type: 1
|
||||||
|
}
|
||||||
|
}).fetch();
|
||||||
|
let totalFilled = 0;
|
||||||
|
children.forEach(child => {
|
||||||
|
if (child.type === 'slotFiller'){
|
||||||
|
totalFilled += child.slotQuantityFilled;
|
||||||
|
} else {
|
||||||
|
totalFilled++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let spaceLeft;
|
||||||
|
if (slot.quantityExpected === 0){
|
||||||
|
spaceLeft = null;
|
||||||
|
} else {
|
||||||
|
spaceLeft = slot.quantityExpected - totalFilled;
|
||||||
|
}
|
||||||
|
if (slot.totalFilled !== totalFilled || slot.spaceLeft !== spaceLeft){
|
||||||
|
CreatureProperties.update(slot._id, {
|
||||||
|
$set: {totalFilled, spaceLeft},
|
||||||
|
}, {
|
||||||
|
selector: {type: 'propertySlot'}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
197
app/imports/api/creature/experience/Experiences.js
Normal file
197
app/imports/api/creature/experience/Experiences.js
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import { getUserTier } from '/imports/api/users/patreon/tiers.js';
|
||||||
|
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import { recomputeCreatureById } from '/imports/api/creature/computation/recomputeCreature.js';
|
||||||
|
|
||||||
|
let Experiences = new Mongo.Collection('experiences');
|
||||||
|
|
||||||
|
let ExperienceSchema = new SimpleSchema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// The amount of XP this experience gives
|
||||||
|
xp: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
optional: true,
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
// Setting levels instead of value grants whole levels
|
||||||
|
levels: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
optional: true,
|
||||||
|
min: 0,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
// The real-world date that it occured, usually sorted by date
|
||||||
|
date: {
|
||||||
|
type: Date,
|
||||||
|
autoValue: function() {
|
||||||
|
// If the date isn't set, set it to now
|
||||||
|
if (!this.isSet) {
|
||||||
|
return new Date();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
creatureId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Experiences.attachSchema(ExperienceSchema);
|
||||||
|
|
||||||
|
const insertExperienceForCreature = function({experience, creatureId, userId}){
|
||||||
|
assertEditPermission(creatureId, userId);
|
||||||
|
if (experience.xp){
|
||||||
|
Creatures.update(creatureId, {$inc: {
|
||||||
|
'denormalizedStats.xp': experience.xp
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
if (experience.levels) {
|
||||||
|
Creatures.update(creatureId, {$inc: {
|
||||||
|
'denormalizedStats.milestoneLevels': experience.levels
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
experience.creatureId = creatureId;
|
||||||
|
let id = Experiences.insert(experience);
|
||||||
|
recomputeCreatureById(creatureId);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
|
||||||
|
const insertExperience = new ValidatedMethod({
|
||||||
|
name: 'experiences.insert',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
experience: {
|
||||||
|
type: ExperienceSchema.omit('creatureId'),
|
||||||
|
},
|
||||||
|
creatureIds: {
|
||||||
|
type: Array,
|
||||||
|
max: 12,
|
||||||
|
},
|
||||||
|
'creatureIds.$': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({experience, creatureIds}) {
|
||||||
|
let userId = this.userId;
|
||||||
|
if (!userId) {
|
||||||
|
throw new Meteor.Error('Experiences.methods.insert.denied',
|
||||||
|
'You need to be logged in to insert an experience');
|
||||||
|
}
|
||||||
|
let tier = getUserTier(this.userId);
|
||||||
|
if (!tier.paidBenefits){
|
||||||
|
throw new Meteor.Error('Experiences.methods.insert.denied',
|
||||||
|
`The ${tier.name} tier does not allow you to grant experience`);
|
||||||
|
}
|
||||||
|
let insertedIds = [];
|
||||||
|
creatureIds.forEach(creatureId => {
|
||||||
|
let id = insertExperienceForCreature({experience, creatureId, userId});
|
||||||
|
insertedIds.push(id);
|
||||||
|
});
|
||||||
|
return insertedIds;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const removeExperience = new ValidatedMethod({
|
||||||
|
name: 'experiences.remove',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
experienceId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({experienceId}) {
|
||||||
|
let userId = this.userId;
|
||||||
|
if (!userId) {
|
||||||
|
throw new Meteor.Error('Experiences.methods.remove.denied',
|
||||||
|
'You need to be logged in to remove an experience');
|
||||||
|
}
|
||||||
|
let tier = getUserTier(this.userId);
|
||||||
|
if (!tier.paidBenefits){
|
||||||
|
throw new Meteor.Error('Experiences.methods.remove.denied',
|
||||||
|
`The ${tier.name} tier does not allow you to remove an experience`);
|
||||||
|
}
|
||||||
|
let experience = Experiences.findOne(experienceId);
|
||||||
|
if (!experience) return;
|
||||||
|
let creatureId = experience.creatureId
|
||||||
|
assertEditPermission(creatureId, userId);
|
||||||
|
if (experience.xp){
|
||||||
|
Creatures.update(creatureId, {$inc: {
|
||||||
|
'denormalizedStats.xp': -experience.xp
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
if (experience.levels) {
|
||||||
|
Creatures.update(creatureId, {$inc: {
|
||||||
|
'denormalizedStats.milestoneLevels': -experience.levels
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
experience.creatureId = creatureId;
|
||||||
|
let numRemoved = Experiences.remove(experienceId);
|
||||||
|
recomputeCreatureById(creatureId);
|
||||||
|
return numRemoved;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const recomputeExperiences = new ValidatedMethod({
|
||||||
|
name: 'experiences.recompute',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
creatureId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({creatureId}) {
|
||||||
|
let userId = this.userId;
|
||||||
|
if (!userId) {
|
||||||
|
throw new Meteor.Error('Experiences.methods.recompute.denied',
|
||||||
|
'You need to be logged in to recompute a creature\'s experiences');
|
||||||
|
}
|
||||||
|
let tier = getUserTier(this.userId);
|
||||||
|
if (!tier.paidBenefits){
|
||||||
|
throw new Meteor.Error('Experiences.methods.recompute.denied',
|
||||||
|
`The ${tier.name} tier does not allow you to recompute a creature's experiences`);
|
||||||
|
}
|
||||||
|
assertEditPermission(creatureId, userId);
|
||||||
|
|
||||||
|
let xp = 0;
|
||||||
|
let milestoneLevels = 0;
|
||||||
|
Experiences.find({
|
||||||
|
creatureId
|
||||||
|
}, {
|
||||||
|
fields: {xp: 1, levels: 1}
|
||||||
|
}).forEach(experience => {
|
||||||
|
xp += experience.xp || 0;
|
||||||
|
milestoneLevels += experience.levels || 0;
|
||||||
|
});
|
||||||
|
Creatures.update(creatureId, {$set: {
|
||||||
|
'denormalizedStats.xp': xp,
|
||||||
|
'denormalizedStats.milestoneLevels': milestoneLevels
|
||||||
|
}});
|
||||||
|
recomputeCreatureById(creatureId);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default Experiences;
|
||||||
|
export { ExperienceSchema, insertExperience, removeExperience, recomputeExperiences };
|
||||||
@@ -4,8 +4,30 @@ import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
|||||||
export default function getActiveProperties({
|
export default function getActiveProperties({
|
||||||
ancestorId,
|
ancestorId,
|
||||||
filter = {},
|
filter = {},
|
||||||
options,
|
options = {sort: {order: 1}},
|
||||||
includeUntoggled = false
|
includeUntoggled = false,
|
||||||
|
includeUnprepared = false,
|
||||||
|
includeUnequipped = false,
|
||||||
|
excludeAncestors,
|
||||||
|
}){
|
||||||
|
filter = getActivePropertyFilter({
|
||||||
|
ancestorId,
|
||||||
|
filter,
|
||||||
|
includeUntoggled,
|
||||||
|
includeUnprepared,
|
||||||
|
includeUnequipped,
|
||||||
|
excludeAncestors,
|
||||||
|
});
|
||||||
|
return CreatureProperties.find(filter, options).fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getActivePropertyFilter({
|
||||||
|
ancestorId,
|
||||||
|
filter = {},
|
||||||
|
includeUntoggled = false,
|
||||||
|
includeUnprepared = false,
|
||||||
|
includeUnequipped = false,
|
||||||
|
excludeAncestors = [],
|
||||||
}){
|
}){
|
||||||
if (!ancestorId){
|
if (!ancestorId){
|
||||||
throw 'Ancestor Id is required to get active properties'
|
throw 'Ancestor Id is required to get active properties'
|
||||||
@@ -14,14 +36,23 @@ export default function getActiveProperties({
|
|||||||
let disabledAncestorsFilter = {
|
let disabledAncestorsFilter = {
|
||||||
'ancestors.id': ancestorId,
|
'ancestors.id': ancestorId,
|
||||||
$or: [
|
$or: [
|
||||||
{disabled: true},
|
{disabled: true}, // Everything can be disabled
|
||||||
{equipped: false},
|
{applied: false}, // Buffs can be applied
|
||||||
{applied: false},
|
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
if (!includeUnequipped){
|
||||||
|
disabledAncestorsFilter.$or.push({type: 'item', equipped: {$ne: true}});
|
||||||
|
}
|
||||||
if (!includeUntoggled){
|
if (!includeUntoggled){
|
||||||
disabledAncestorsFilter.$or.push({toggleResult: false});
|
disabledAncestorsFilter.$or.push({toggleResult: false});
|
||||||
}
|
}
|
||||||
|
if (!includeUnprepared){
|
||||||
|
disabledAncestorsFilter.$or.push({
|
||||||
|
type: 'spell',
|
||||||
|
prepared: {$ne: true},
|
||||||
|
alwaysPrepared: {$ne: true}
|
||||||
|
});
|
||||||
|
}
|
||||||
let disabledAncestorIds = CreatureProperties.find(disabledAncestorsFilter, {
|
let disabledAncestorIds = CreatureProperties.find(disabledAncestorsFilter, {
|
||||||
fields: {_id: 1},
|
fields: {_id: 1},
|
||||||
}).map(prop => prop._id);
|
}).map(prop => prop._id);
|
||||||
@@ -38,9 +69,12 @@ export default function getActiveProperties({
|
|||||||
|
|
||||||
// Get all the properties that are decendents of the ancestor of interest but
|
// Get all the properties that are decendents of the ancestor of interest but
|
||||||
// aren't from the excluded decendents
|
// aren't from the excluded decendents
|
||||||
|
if (filter['ancestors.id'] && Meteor.isClient){
|
||||||
|
console.warn('Filtering on ancestor id is ignored')
|
||||||
|
}
|
||||||
filter['ancestors.id'] = {
|
filter['ancestors.id'] = {
|
||||||
$eq: ancestorId,
|
$eq: ancestorId,
|
||||||
$nin: disabledAncestorIds,
|
$nin: disabledAncestorIds.concat(excludeAncestors),
|
||||||
};
|
};
|
||||||
// Get properties that aren't removed
|
// Get properties that aren't removed
|
||||||
filter.removed = {$ne: true};
|
filter.removed = {$ne: true};
|
||||||
@@ -48,5 +82,5 @@ export default function getActiveProperties({
|
|||||||
filter._id = {
|
filter._id = {
|
||||||
$nin: disabledAncestorIds,
|
$nin: disabledAncestorIds,
|
||||||
}
|
}
|
||||||
return CreatureProperties.find(filter, options).fetch();
|
return filter;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
|
||||||
let ExperienceSchema = new SimpleSchema({
|
let ExperienceSchema = new SimpleSchema({
|
||||||
name: {
|
title: {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
@@ -10,11 +10,6 @@ let ExperienceSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
// The amount of XP this experience gives
|
|
||||||
value: {
|
|
||||||
type: SimpleSchema.Integer,
|
|
||||||
optional: true,
|
|
||||||
},
|
|
||||||
// The real-world date that it occured
|
// The real-world date that it occured
|
||||||
date: {
|
date: {
|
||||||
type: Date,
|
type: Date,
|
||||||
@@ -30,6 +25,20 @@ let ExperienceSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
// Tags to better find this entry later
|
||||||
|
tags: {
|
||||||
|
type: Array,
|
||||||
|
defaultValue: [],
|
||||||
|
},
|
||||||
|
'tags.$': {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
// ID of the journal this entry belongs to
|
||||||
|
journalId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
index: 1,
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
export { ExperienceSchema };
|
export { ExperienceSchema };
|
||||||
176
app/imports/api/creature/log/CreatureLogs.js
Normal file
176
app/imports/api/creature/log/CreatureLogs.js
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import {assertEditPermission} from '/imports/api/creature/creaturePermissions.js';
|
||||||
|
import { parse, CompilationContext } from '/imports/parser/parser.js';
|
||||||
|
const PER_CREATURE_LOG_LIMIT = 100;
|
||||||
|
|
||||||
|
if (Meteor.isServer){
|
||||||
|
var sendWebhookAsCreature = require('/imports/server/discord/sendWebhook.js').sendWebhookAsCreature;
|
||||||
|
}
|
||||||
|
|
||||||
|
let CreatureLogs = new Mongo.Collection('creatureLogs');
|
||||||
|
|
||||||
|
let CreatureLogSchema = new SimpleSchema({
|
||||||
|
text: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
type: {
|
||||||
|
type: String,
|
||||||
|
allowedValues: ['roll', 'change', 'damage', 'info'],
|
||||||
|
defaultValue: 'info',
|
||||||
|
},
|
||||||
|
// The real-world date that it occured, usually sorted by date
|
||||||
|
date: {
|
||||||
|
type: Date,
|
||||||
|
autoValue: function() {
|
||||||
|
// If the date isn't set, set it to now
|
||||||
|
if (!this.isSet) {
|
||||||
|
return new Date();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
creatureId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
CreatureLogs.attachSchema(CreatureLogSchema);
|
||||||
|
|
||||||
|
function removeOldLogs(creatureId){
|
||||||
|
// Find the first log that is over the limit
|
||||||
|
let firstExpiredLog = CreatureLogs.find({
|
||||||
|
creatureId
|
||||||
|
}, {
|
||||||
|
sort: {date: -1},
|
||||||
|
skip: PER_CREATURE_LOG_LIMIT,
|
||||||
|
});
|
||||||
|
// Remove all logs older than the one over the limit
|
||||||
|
CreatureLogs.remove({
|
||||||
|
creatureId,
|
||||||
|
date: {$lte: firstExpiredLog.date},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function logWebhook({log, creature}){
|
||||||
|
if (Meteor.isServer){
|
||||||
|
sendWebhookAsCreature({
|
||||||
|
creature,
|
||||||
|
content: log.text,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertCreatureLog = new ValidatedMethod({
|
||||||
|
name: 'creatureLogs.methods.insertCreatureLog',
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
log: CreatureLogSchema.omit('type', 'date'),
|
||||||
|
}).validator(),
|
||||||
|
run({log}){
|
||||||
|
const creatureId = log.creatureId;
|
||||||
|
const creature = Creatures.findOne(creatureId, {fields: {
|
||||||
|
readers: 1,
|
||||||
|
writers: 1,
|
||||||
|
owner: 1,
|
||||||
|
'settings.discordWebhook': 1,
|
||||||
|
name: 1,
|
||||||
|
avatarPicture: 1,
|
||||||
|
}});
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
// Build the new log
|
||||||
|
if (typeof log === 'string'){
|
||||||
|
log = {text: log};
|
||||||
|
}
|
||||||
|
log.date = new Date();
|
||||||
|
// Insert it
|
||||||
|
let id = CreatureLogs.insert(log);
|
||||||
|
if (Meteor.isServer){
|
||||||
|
this.unblock();
|
||||||
|
removeOldLogs(creatureId);
|
||||||
|
logWebhook({log, creature});
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
function equalIgnoringWhitespace(a, b){
|
||||||
|
if (typeof a !== 'string' || typeof b !== 'string') return a === b;
|
||||||
|
return a.replace(/\s/g,'') === b.replace(/\s/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
const logRoll = new ValidatedMethod({
|
||||||
|
name: 'creatureLogs.methods.logForCreature',
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
roll: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
creatureId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
run({roll, creatureId}){
|
||||||
|
const creature = Creatures.findOne(creatureId, {fields: {
|
||||||
|
variables: 1,
|
||||||
|
readers: 1,
|
||||||
|
writers: 1,
|
||||||
|
owner: 1,
|
||||||
|
'settings.discordWebhook': 1,
|
||||||
|
name: 1,
|
||||||
|
avatarPicture: 1,
|
||||||
|
}});
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
let parsedResult = parse(roll);
|
||||||
|
let logText;
|
||||||
|
if (parsedResult === null) {
|
||||||
|
logText = 'Unexpected end of input';
|
||||||
|
}
|
||||||
|
else try {
|
||||||
|
logText = [];
|
||||||
|
let rollContext = new CompilationContext();
|
||||||
|
let compiled = parsedResult.compile(creature.variables, rollContext);
|
||||||
|
let compiledString = compiled.toString();
|
||||||
|
if (!equalIgnoringWhitespace(compiledString, roll)) logText.push(roll);
|
||||||
|
logText.push(compiledString);
|
||||||
|
let rolled = compiled.roll(creature.variables, rollContext);
|
||||||
|
let rolledString = rolled.toString();
|
||||||
|
if (rolledString !== compiledString) logText.push(rolled.toString());
|
||||||
|
let result = rolled.reduce(creature.variables, rollContext);
|
||||||
|
let resultString = result.toString();
|
||||||
|
if (resultString !== rolledString) logText.push(resultString);
|
||||||
|
logText = logText.join('\n\n');
|
||||||
|
} catch (e){
|
||||||
|
logText = 'Calculation error';
|
||||||
|
}
|
||||||
|
const log = {
|
||||||
|
text: logText,
|
||||||
|
creatureId,
|
||||||
|
date: new Date(),
|
||||||
|
};
|
||||||
|
let id = CreatureLogs.insert(log);
|
||||||
|
if (Meteor.isServer){
|
||||||
|
this.unblock();
|
||||||
|
removeOldLogs(creatureId);
|
||||||
|
logWebhook({log, creature});
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default CreatureLogs;
|
||||||
|
export { CreatureLogSchema, insertCreatureLog, logRoll};
|
||||||
@@ -1,20 +1,31 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import Creatures from '/imports/api/creature/Creatures.js';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
import CreatureProperties from '/imports/api/creature/CreatureProperties.js'
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import { assertOwnership } from '/imports/api/creature/creaturePermissions.js';
|
import { assertOwnership } from '/imports/api/creature/creaturePermissions.js';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
import CreatureLogs from '/imports/api/creature/log/CreatureLogs.js';
|
||||||
|
import Experiences from '/imports/api/creature/experience/Experiences.js';
|
||||||
|
|
||||||
function removeRelatedDocuments(charId){
|
function removeRelatedDocuments(creatureId){
|
||||||
CreatureProperties.remove({'ancestors.id': charId});
|
CreatureProperties.remove({'ancestors.id': creatureId});
|
||||||
};
|
CreatureLogs.remove({creatureId});
|
||||||
|
Experiences.remove({creatureId});
|
||||||
|
}
|
||||||
|
|
||||||
const removeCreature = new ValidatedMethod({
|
const removeCreature = new ValidatedMethod({
|
||||||
name: "Creatures.methods.removeCreature", // DDP method name
|
name: 'Creatures.methods.removeCreature', // DDP method name
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
charId: {
|
charId: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: SimpleSchema.RegEx.Id,
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({charId}) {
|
run({charId}) {
|
||||||
assertOwnership(charId, this.userId)
|
assertOwnership(charId, this.userId)
|
||||||
Creatures.remove(charId);
|
Creatures.remove(charId);
|
||||||
|
|||||||
112
app/imports/api/creature/restCreature.js
Normal file
112
app/imports/api/creature/restCreature.js
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
|
||||||
|
import getActiveProperties, { getActivePropertyFilter } from '/imports/api/creature/getActiveProperties.js';
|
||||||
|
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
|
||||||
|
import { recomputeCreatureById } from '/imports/api/creature/computation/recomputeCreature.js';
|
||||||
|
|
||||||
|
const restCreature = new ValidatedMethod({
|
||||||
|
name: 'creature.methods.longRest',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
creatureId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
},
|
||||||
|
restType: {
|
||||||
|
type: String,
|
||||||
|
allowedValues: ['shortRest', 'longRest'],
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({creatureId, restType}) {
|
||||||
|
let creature = Creatures.findOne(creatureId, {
|
||||||
|
fields: {
|
||||||
|
owner: 1,
|
||||||
|
writers: 1,
|
||||||
|
settings: 1,
|
||||||
|
}
|
||||||
|
}) ;
|
||||||
|
// Need edit permissions
|
||||||
|
assertEditPermission(creature, this.userId);
|
||||||
|
|
||||||
|
// Long rests reset short rest properties as well
|
||||||
|
let resetFilter;
|
||||||
|
if (restType === 'shortRest'){
|
||||||
|
resetFilter = 'shortRest'
|
||||||
|
} else {
|
||||||
|
resetFilter = {$in: ['shortRest', 'longRest']}
|
||||||
|
}
|
||||||
|
// Only apply to active properties
|
||||||
|
let filter = getActivePropertyFilter({
|
||||||
|
filter: {reset: resetFilter},
|
||||||
|
ancestorId: creatureId,
|
||||||
|
includeUntoggled: true,
|
||||||
|
});
|
||||||
|
// update all attribute's damage
|
||||||
|
filter.type = 'attribute';
|
||||||
|
CreatureProperties.update(filter, {
|
||||||
|
$set: {damage: 0}
|
||||||
|
}, {
|
||||||
|
selector: {type: 'attribute'},
|
||||||
|
multi: true,
|
||||||
|
});
|
||||||
|
// Update all action-like properties' usesUsed
|
||||||
|
filter.type = {$in: [
|
||||||
|
'action',
|
||||||
|
'attack',
|
||||||
|
'spell'
|
||||||
|
]};
|
||||||
|
CreatureProperties.update(filter, {
|
||||||
|
$set: {usesUsed: 0}
|
||||||
|
}, {
|
||||||
|
selector: {type: 'action'},
|
||||||
|
multi: true,
|
||||||
|
});
|
||||||
|
// Reset half hit dice on a long rest, starting with the highest dice
|
||||||
|
if (restType === 'longRest'){
|
||||||
|
let hitDice = getActiveProperties({
|
||||||
|
ancestorId: creatureId,
|
||||||
|
filter: {type: 'attribute', attributeType: 'hitDice'},
|
||||||
|
options: {fields: {
|
||||||
|
hitDiceSize: 1,
|
||||||
|
damage: 1,
|
||||||
|
value: 1,
|
||||||
|
}},
|
||||||
|
});
|
||||||
|
// Use a collator to do sorting in natural order
|
||||||
|
let collator = new Intl.Collator('en', {
|
||||||
|
numeric: true, sensitivity: 'base'
|
||||||
|
});
|
||||||
|
// Get the hit dice in decending order of hitDiceSize
|
||||||
|
let compare = (a, b) => collator.compare(b.hitDiceSize, a.hitDiceSize)
|
||||||
|
hitDice.sort(compare);
|
||||||
|
// Get the total number of hit dice that can be recovered this rest
|
||||||
|
let totalHd = hitDice.reduce((sum, hd) => sum + (hd.value || 0), 0);
|
||||||
|
let resetMultiplier = creature.settings.hitDiceResetMultiplier || 0.5;
|
||||||
|
let recoverableHd = Math.max(Math.floor(totalHd*resetMultiplier), 1);
|
||||||
|
// recover each hit dice in turn until the recoverable amount is used up
|
||||||
|
let amountToRecover, resultingDamage;
|
||||||
|
hitDice.forEach(hd => {
|
||||||
|
if (!recoverableHd) return;
|
||||||
|
amountToRecover = Math.min(recoverableHd, hd.damage || 0);
|
||||||
|
if (!amountToRecover) return;
|
||||||
|
recoverableHd -= amountToRecover;
|
||||||
|
resultingDamage = hd.damage - amountToRecover;
|
||||||
|
CreatureProperties.update(hd._id, {
|
||||||
|
$set: {damage: resultingDamage}
|
||||||
|
}, {
|
||||||
|
selector: {type: 'attribute'},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
recomputeCreatureById(creatureId);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default restCreature;
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import { assertAdmin } from '/imports/api/sharing/sharingPermissions.js';
|
||||||
|
|
||||||
let Icons = new Mongo.Collection('icons');
|
let Icons = new Mongo.Collection('icons');
|
||||||
|
|
||||||
iconsSchema = new SimpleSchema({
|
let iconsSchema = new SimpleSchema({
|
||||||
name: {
|
name: {
|
||||||
type: String,
|
type: String,
|
||||||
unique: true,
|
unique: true,
|
||||||
@@ -33,21 +36,62 @@ if (Meteor.isServer) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const storedIconsSchema = new SimpleSchema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
shape: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
Icons.attachSchema(iconsSchema);
|
Icons.attachSchema(iconsSchema);
|
||||||
|
|
||||||
/*
|
// This method does not validate icons against the schema, use wisely;
|
||||||
console.warn("Write Icons is not secure, disable before deployment")
|
|
||||||
const writeIcons = new ValidatedMethod({
|
const writeIcons = new ValidatedMethod({
|
||||||
name: 'writeIcons',
|
name: 'icons.write',
|
||||||
validate: null,
|
validate: null,
|
||||||
run(icons){
|
run(icons){
|
||||||
|
assertAdmin(this.userId);
|
||||||
if (Meteor.isServer){
|
if (Meteor.isServer){
|
||||||
this.unblock();
|
this.unblock();
|
||||||
Icons.rawCollection().insert(icons, {ordered: false});
|
Icons.rawCollection().insert(icons, {ordered: false});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
*/
|
|
||||||
|
|
||||||
export { writeIcons };
|
const findIcons = new ValidatedMethod({
|
||||||
|
name: 'icons.find',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
search: {
|
||||||
|
type: String,
|
||||||
|
max: 30,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 20,
|
||||||
|
timeInterval: 10000,
|
||||||
|
},
|
||||||
|
run({search}){
|
||||||
|
if (!search) return [];
|
||||||
|
if (!Meteor.isServer) return;
|
||||||
|
return Icons.find(
|
||||||
|
{ $text: {$search: search} },
|
||||||
|
{
|
||||||
|
// relevant documents have a higher score.
|
||||||
|
fields: {
|
||||||
|
score: { $meta: 'textScore' }
|
||||||
|
},
|
||||||
|
// `score` property specified in the projection fields above.
|
||||||
|
sort: {
|
||||||
|
score: { $meta: 'textScore' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
).fetch();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export { writeIcons, findIcons, storedIconsSchema };
|
||||||
export default Icons;
|
export default Icons;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import SharingSchema from '/imports/api/sharing/SharingSchema.js';
|
import SharingSchema from '/imports/api/sharing/SharingSchema.js';
|
||||||
import simpleSchemaMixin from '/imports/api/creature/mixins/simpleSchemaMixin.js';
|
import simpleSchemaMixin from '/imports/api/creature/mixins/simpleSchemaMixin.js';
|
||||||
@@ -34,7 +35,7 @@ Libraries.attachSchema(LibrarySchema);
|
|||||||
export default Libraries;
|
export default Libraries;
|
||||||
|
|
||||||
const insertLibrary = new ValidatedMethod({
|
const insertLibrary = new ValidatedMethod({
|
||||||
name: 'Libraries.methods.insert',
|
name: 'libraries.insert',
|
||||||
mixins: [
|
mixins: [
|
||||||
simpleSchemaMixin,
|
simpleSchemaMixin,
|
||||||
],
|
],
|
||||||
@@ -55,7 +56,7 @@ const insertLibrary = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const updateLibraryName = new ValidatedMethod({
|
const updateLibraryName = new ValidatedMethod({
|
||||||
name: 'Libraries.methods.updateName',
|
name: 'libraries.updateName',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: {
|
_id: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -65,6 +66,11 @@ const updateLibraryName = new ValidatedMethod({
|
|||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, name}){
|
run({_id, name}){
|
||||||
let library = Libraries.findOne(_id);
|
let library = Libraries.findOne(_id);
|
||||||
assertEditPermission(library, this.userId);
|
assertEditPermission(library, this.userId);
|
||||||
@@ -73,7 +79,7 @@ const updateLibraryName = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const setLibraryDefault = new ValidatedMethod({
|
const setLibraryDefault = new ValidatedMethod({
|
||||||
name: 'Libraries.methods.makeLibraryDefault',
|
name: 'libraries.makeLibraryDefault',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: {
|
_id: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -83,6 +89,11 @@ const setLibraryDefault = new ValidatedMethod({
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, isDefault}) {
|
run({_id, isDefault}) {
|
||||||
if (!Meteor.users.isAdmin()){
|
if (!Meteor.users.isAdmin()){
|
||||||
throw new Meteor.Error('Permission denied', 'User must be admin to set libraries as default');
|
throw new Meteor.Error('Permission denied', 'User must be admin to set libraries as default');
|
||||||
@@ -92,13 +103,18 @@ const setLibraryDefault = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const removeLibrary = new ValidatedMethod({
|
const removeLibrary = new ValidatedMethod({
|
||||||
name: 'Libraries.methods.remove',
|
name: 'libraries.remove',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: {
|
_id: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: SimpleSchema.RegEx.id
|
regEx: SimpleSchema.RegEx.id
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id}){
|
run({_id}){
|
||||||
let library = Libraries.findOne(_id);
|
let library = Libraries.findOne(_id);
|
||||||
assertOwnership(library, this.userId);
|
assertOwnership(library, this.userId);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Meteor } from 'meteor/meteor';
|
import { Meteor } from 'meteor/meteor';
|
||||||
import { Mongo } from 'meteor/mongo';
|
import { Mongo } from 'meteor/mongo';
|
||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js';
|
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js';
|
||||||
import ChildSchema from '/imports/api/parenting/ChildSchema.js';
|
import ChildSchema from '/imports/api/parenting/ChildSchema.js';
|
||||||
@@ -9,6 +10,7 @@ import Libraries from '/imports/api/library/Libraries.js';
|
|||||||
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js';
|
import { assertEditPermission } from '/imports/api/sharing/sharingPermissions.js';
|
||||||
import { softRemove } from '/imports/api/parenting/softRemove.js';
|
import { softRemove } from '/imports/api/parenting/softRemove.js';
|
||||||
import SoftRemovableSchema from '/imports/api/parenting/SoftRemovableSchema.js';
|
import SoftRemovableSchema from '/imports/api/parenting/SoftRemovableSchema.js';
|
||||||
|
import { storedIconsSchema } from '/imports/api/icons/Icons.js';
|
||||||
|
|
||||||
let LibraryNodes = new Mongo.Collection('libraryNodes');
|
let LibraryNodes = new Mongo.Collection('libraryNodes');
|
||||||
|
|
||||||
@@ -24,6 +26,10 @@ let LibraryNodeSchema = new SimpleSchema({
|
|||||||
'tags.$': {
|
'tags.$': {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
|
icon: {
|
||||||
|
type: storedIconsSchema,
|
||||||
|
optional: true,
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
for (let key in propertySchemasIndex){
|
for (let key in propertySchemasIndex){
|
||||||
@@ -51,8 +57,13 @@ function assertNodeEditPermission(node, userId){
|
|||||||
}
|
}
|
||||||
|
|
||||||
const insertNode = new ValidatedMethod({
|
const insertNode = new ValidatedMethod({
|
||||||
name: 'LibraryNodes.methods.insert',
|
name: 'libraryNodes.insert',
|
||||||
validate: null,
|
validate: null,
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run(libraryNode) {
|
run(libraryNode) {
|
||||||
delete libraryNode._id;
|
delete libraryNode._id;
|
||||||
assertNodeEditPermission(libraryNode, this.userId);
|
assertNodeEditPermission(libraryNode, this.userId);
|
||||||
@@ -61,13 +72,18 @@ const insertNode = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const duplicateNode = new ValidatedMethod({
|
const duplicateNode = new ValidatedMethod({
|
||||||
name: 'LibraryNodes.methods.duplicate',
|
name: 'libraryNodes.duplicate',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: {
|
_id: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: SimpleSchema.RegEx.Id,
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
}
|
}
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id}) {
|
run({_id}) {
|
||||||
let libraryNode = LibraryNodes.findOne(_id);
|
let libraryNode = LibraryNodes.findOne(_id);
|
||||||
assertNodeEditPermission(libraryNode, this.userId);
|
assertNodeEditPermission(libraryNode, this.userId);
|
||||||
@@ -77,7 +93,7 @@ const duplicateNode = new ValidatedMethod({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const updateLibraryNode = new ValidatedMethod({
|
const updateLibraryNode = new ValidatedMethod({
|
||||||
name: 'LibraryNodes.methods.update',
|
name: 'libraryNodes.update',
|
||||||
validate({_id, path}){
|
validate({_id, path}){
|
||||||
if (!_id) return false;
|
if (!_id) return false;
|
||||||
// We cannot change these fields with a simple update
|
// We cannot change these fields with a simple update
|
||||||
@@ -89,6 +105,11 @@ const updateLibraryNode = new ValidatedMethod({
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, path, value}) {
|
run({_id, path, value}) {
|
||||||
let node = LibraryNodes.findOne(_id);
|
let node = LibraryNodes.findOne(_id);
|
||||||
assertNodeEditPermission(node, this.userId);
|
assertNodeEditPermission(node, this.userId);
|
||||||
@@ -107,8 +128,13 @@ const updateLibraryNode = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const pushToLibraryNode = new ValidatedMethod({
|
const pushToLibraryNode = new ValidatedMethod({
|
||||||
name: 'LibraryNodes.methods.push',
|
name: 'libraryNodes.push',
|
||||||
validate: null,
|
validate: null,
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, path, value}){
|
run({_id, path, value}){
|
||||||
let node = LibraryNodes.findOne(_id);
|
let node = LibraryNodes.findOne(_id);
|
||||||
assertNodeEditPermission(node, this.userId);
|
assertNodeEditPermission(node, this.userId);
|
||||||
@@ -121,8 +147,13 @@ const pushToLibraryNode = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const pullFromLibraryNode = new ValidatedMethod({
|
const pullFromLibraryNode = new ValidatedMethod({
|
||||||
name: 'LibraryNodes.methods.pull',
|
name: 'libraryNodes.pull',
|
||||||
validate: null,
|
validate: null,
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id, path, itemId}){
|
run({_id, path, itemId}){
|
||||||
let node = LibraryNodes.findOne(_id);
|
let node = LibraryNodes.findOne(_id);
|
||||||
assertNodeEditPermission(node, this.userId);
|
assertNodeEditPermission(node, this.userId);
|
||||||
@@ -136,10 +167,15 @@ const pullFromLibraryNode = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const softRemoveLibraryNode = new ValidatedMethod({
|
const softRemoveLibraryNode = new ValidatedMethod({
|
||||||
name: 'LibraryNodes.methods.softRemove',
|
name: 'libraryNodes.softRemove',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
_id: SimpleSchema.RegEx.Id
|
_id: SimpleSchema.RegEx.Id
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({_id}){
|
run({_id}){
|
||||||
let node = LibraryNodes.findOne(_id);
|
let node = LibraryNodes.findOne(_id);
|
||||||
assertNodeEditPermission(node, this.userId);
|
assertNodeEditPermission(node, this.userId);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import { union } from 'lodash';
|
import { union } from 'lodash';
|
||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import { updateParent } from '/imports/api/parenting/parenting.js';
|
import { updateParent } from '/imports/api/parenting/parenting.js';
|
||||||
import { reorderDocs, safeUpdateDocOrder } from '/imports/api/parenting/order.js';
|
import { reorderDocs, safeUpdateDocOrder } from '/imports/api/parenting/order.js';
|
||||||
import { RefSchema } from '/imports/api/parenting/ChildSchema.js';
|
import { RefSchema } from '/imports/api/parenting/ChildSchema.js';
|
||||||
@@ -10,7 +11,7 @@ import getCollectionByName from '/imports/api/parenting/getCollectionByName.js';
|
|||||||
import { recomputeCreatureById } from '/imports/api/creature/computation/recomputeCreature.js';
|
import { recomputeCreatureById } from '/imports/api/creature/computation/recomputeCreature.js';
|
||||||
|
|
||||||
const organizeDoc = new ValidatedMethod({
|
const organizeDoc = new ValidatedMethod({
|
||||||
name: 'organize.methods.organizeDoc',
|
name: 'organize.organizeDoc',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
docRef: RefSchema,
|
docRef: RefSchema,
|
||||||
parentRef: RefSchema,
|
parentRef: RefSchema,
|
||||||
@@ -19,6 +20,11 @@ const organizeDoc = new ValidatedMethod({
|
|||||||
// Should end in 0.5 to place it reliably between two existing documents
|
// Should end in 0.5 to place it reliably between two existing documents
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({docRef, parentRef, order}) {
|
run({docRef, parentRef, order}) {
|
||||||
let doc = fetchDocByRef(docRef);
|
let doc = fetchDocByRef(docRef);
|
||||||
let collection = getCollectionByName(docRef.collection);
|
let collection = getCollectionByName(docRef.collection);
|
||||||
@@ -54,7 +60,7 @@ const organizeDoc = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const reorderDoc = new ValidatedMethod({
|
const reorderDoc = new ValidatedMethod({
|
||||||
name: 'organize.methods.reorderDoc',
|
name: 'organize.reorderDoc',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
docRef: RefSchema,
|
docRef: RefSchema,
|
||||||
order: {
|
order: {
|
||||||
@@ -62,6 +68,11 @@ const reorderDoc = new ValidatedMethod({
|
|||||||
// Should end in 0.5 to place it reliably between two existing documents
|
// Should end in 0.5 to place it reliably between two existing documents
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({docRef, order}) {
|
run({docRef, order}) {
|
||||||
let doc = fetchDocByRef(docRef);
|
let doc = fetchDocByRef(docRef);
|
||||||
assertDocEditPermission(doc, this.userId);
|
assertDocEditPermission(doc, this.userId);
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ export function renewDocIds({docArray, collectionMap}){
|
|||||||
const remapReference = ref => {
|
const remapReference = ref => {
|
||||||
if (idMap[ref.id]){
|
if (idMap[ref.id]){
|
||||||
ref.id = idMap[ref.id];
|
ref.id = idMap[ref.id];
|
||||||
ref.collection = collectionMap[ref.collection] || ref.collection;
|
ref.collection = collectionMap && collectionMap[ref.collection] || ref.collection;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
docArray.forEach(doc => {
|
docArray.forEach(doc => {
|
||||||
@@ -154,6 +154,14 @@ export function updateParent({docRef, parentRef}){
|
|||||||
// Get the parent and its ancestry
|
// Get the parent and its ancestry
|
||||||
let {parentDoc, parent, ancestors} = getAncestry({parentRef});
|
let {parentDoc, parent, ancestors} = getAncestry({parentRef});
|
||||||
|
|
||||||
|
// Check that the doc isn't its own ancestor
|
||||||
|
ancestors.forEach(ancestor => {
|
||||||
|
if (docRef.id === ancestor.id){
|
||||||
|
throw new Meteor.Error('invalid parenting',
|
||||||
|
'A doc can\'t be its own ancestor')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// If the doc and its parent are in the same collection, apply the allowed
|
// If the doc and its parent are in the same collection, apply the allowed
|
||||||
// parent rules based on type
|
// parent rules based on type
|
||||||
if (docRef.collection === parentRef.collection){
|
if (docRef.collection === parentRef.collection){
|
||||||
@@ -204,17 +212,11 @@ export function getName(doc){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function nodesToTree({collection, ancestorId, filter, options}){
|
export function nodeArrayToTree(nodes){
|
||||||
// Store a dict of all the nodes
|
// Store a dict and list of all the nodes
|
||||||
let nodeIndex = {};
|
let nodeIndex = {};
|
||||||
let nodeList = [];
|
let nodeList = [];
|
||||||
if (!options) options = {};
|
nodes.forEach( node => {
|
||||||
options.sort = {order: 1};
|
|
||||||
collection.find({
|
|
||||||
'ancestors.id': ancestorId,
|
|
||||||
removed: {$ne: true},
|
|
||||||
...filter,
|
|
||||||
}, options).forEach( node => {
|
|
||||||
let treeNode = {
|
let treeNode = {
|
||||||
node: node,
|
node: node,
|
||||||
children: [],
|
children: [],
|
||||||
@@ -238,3 +240,12 @@ export function nodesToTree({collection, ancestorId, filter, options}){
|
|||||||
});
|
});
|
||||||
return forest;
|
return forest;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function nodesToTree({collection, ancestorId, filter = {}, options = {}}){
|
||||||
|
if (!('ancestors.id' in filter)) filter['ancestors.id'] = ancestorId;
|
||||||
|
if (!('removed' in filter)) filter['removed'] = {$ne: true};
|
||||||
|
if (!options.sort) options.sort = {order: 1};
|
||||||
|
if (!('order' in options.sort)) options.sort.order = 1;
|
||||||
|
let nodes = collection.find(filter, options);
|
||||||
|
return nodeArrayToTree(nodes);
|
||||||
|
}
|
||||||
|
|||||||
@@ -41,16 +41,21 @@ const restoreError = function(){
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function restore({_id, collection}){
|
export function restore({_id, collection}){
|
||||||
collection = getCollectionByName(collection);
|
if (typeof collection === 'string') {
|
||||||
|
collection = getCollectionByName(collection);
|
||||||
|
}
|
||||||
let numUpdated = collection.update({
|
let numUpdated = collection.update({
|
||||||
_id,
|
_id,
|
||||||
removedWith: {$exists: false}
|
removedWith: {$exists: false}
|
||||||
}, { $unset: {
|
}, { $unset: {
|
||||||
removed: 1,
|
removed: 1,
|
||||||
removedAt: 1,
|
removedAt: 1,
|
||||||
}});
|
}}, {
|
||||||
|
selector: {type: 'any'},
|
||||||
|
},);
|
||||||
if (numUpdated === 0) restoreError();
|
if (numUpdated === 0) restoreError();
|
||||||
updateDescendants({
|
updateDescendants({
|
||||||
|
collection,
|
||||||
ancestorId: _id,
|
ancestorId: _id,
|
||||||
filter: {
|
filter: {
|
||||||
removedWith: _id,
|
removedWith: _id,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import ResourcesSchema from '/imports/api/properties/subSchemas/ResourcesSchema.js'
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
|
import { storedIconsSchema } from '/imports/api/icons/Icons.js'
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Actions are things a character can do
|
* Actions are things a character can do
|
||||||
@@ -12,6 +13,10 @@ let ActionSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
summary: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
description: {
|
description: {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
@@ -40,13 +45,60 @@ let ActionSchema = new SimpleSchema({
|
|||||||
'tags.$': {
|
'tags.$': {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
|
// Duplicate the ResourceSchema here so we can extend it elegantly.
|
||||||
resources: {
|
resources: {
|
||||||
type: ResourcesSchema,
|
type: Object,
|
||||||
defaultValue: {},
|
defaultValue: {},
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed': {
|
||||||
|
type: Array,
|
||||||
|
defaultValue: [],
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$': {
|
||||||
|
type: Object,
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$._id': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
autoValue(){
|
||||||
|
if (!this.isSet) return Random.id();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$.tag': {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$.quantity': {
|
||||||
|
type: Number,
|
||||||
|
defaultValue: 1,
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$.itemId': {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed': {
|
||||||
|
type: Array,
|
||||||
|
defaultValue: [],
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed.$': {
|
||||||
|
type: Object,
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed.$._id': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
autoValue(){
|
||||||
|
if (!this.isSet) return Random.id();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed.$.variableName': {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed.$.quantity': {
|
||||||
|
type: Number,
|
||||||
|
defaultValue: 1,
|
||||||
},
|
},
|
||||||
// Calculation of how many times this action can be used
|
// Calculation of how many times this action can be used
|
||||||
// Only set if this action tracks its own uses, rather than adjusting
|
|
||||||
// resources
|
|
||||||
uses: {
|
uses: {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
@@ -64,4 +116,69 @@ let ActionSchema = new SimpleSchema({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { ActionSchema };
|
const ComputedOnlyActionSchema = new SimpleSchema({
|
||||||
|
usesResult: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
usesErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'usesErrors.$':{
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
|
resources: Object,
|
||||||
|
'resources.itemsConsumed': Array,
|
||||||
|
'resources.itemsConsumed.$': Object,
|
||||||
|
'resources.itemsConsumed.$.available': {
|
||||||
|
type: Number,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// This appears both in the computed and uncomputed schema because it can be
|
||||||
|
// set by both a computation or a form
|
||||||
|
'resources.itemsConsumed.$.itemId': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$.itemName': {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$.itemIcon': {
|
||||||
|
type: storedIconsSchema,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.itemsConsumed.$.itemColor': {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed': Array,
|
||||||
|
'resources.attributesConsumed.$': Object,
|
||||||
|
'resources.attributesConsumed.$.available': {
|
||||||
|
type: Number,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed.$.statId': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'resources.attributesConsumed.$.statName': {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// True if the uses left is zero, or any item or attribute consumed is
|
||||||
|
// insufficient
|
||||||
|
insufficientResources: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ComputedActionSchema = new SimpleSchema()
|
||||||
|
.extend(ActionSchema)
|
||||||
|
.extend(ComputedOnlyActionSchema);
|
||||||
|
|
||||||
|
export { ActionSchema, ComputedOnlyActionSchema, ComputedActionSchema};
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import SimpleSchema from 'simpl-schema';
|
|||||||
|
|
||||||
const AdjustmentSchema = new SimpleSchema({
|
const AdjustmentSchema = new SimpleSchema({
|
||||||
// The roll that determines how much to change the attribute
|
// The roll that determines how much to change the attribute
|
||||||
|
// This can be simplified, but should only compute when activated
|
||||||
amount: {
|
amount: {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
@@ -22,6 +23,11 @@ const AdjustmentSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
operation: {
|
||||||
|
type: String,
|
||||||
|
allowedValues: ['set', 'increment'],
|
||||||
|
defaultValue: 'increment',
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { AdjustmentSchema };
|
export { AdjustmentSchema };
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import { ActionSchema } from '/imports/api/properties/Actions.js';
|
import { ActionSchema, ComputedOnlyActionSchema } from '/imports/api/properties/Actions.js';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
|
|
||||||
// Attacks are special instances of actions
|
// Attacks are special instances of actions
|
||||||
let AttackSchema = new SimpleSchema()
|
let AttackSchema = new SimpleSchema()
|
||||||
@@ -25,4 +26,24 @@ let AttackSchema = new SimpleSchema()
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { AttackSchema };
|
const ComputedOnlyAttackSchema = new SimpleSchema()
|
||||||
|
.extend(ComputedOnlyActionSchema)
|
||||||
|
.extend({
|
||||||
|
rollBonusResult: {
|
||||||
|
type: Number,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
rollBonusErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'rollBonusErrors.$':{
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ComputedAttackSchema = new SimpleSchema()
|
||||||
|
.extend(AttackSchema)
|
||||||
|
.extend(ComputedOnlyAttackSchema);
|
||||||
|
|
||||||
|
export { AttackSchema, ComputedOnlyAttackSchema, ComputedAttackSchema };
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
import VARIABLE_NAME_REGEX from '/imports/constants/VARIABLE_NAME_REGEX.js';
|
import VARIABLE_NAME_REGEX from '/imports/constants/VARIABLE_NAME_REGEX.js';
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -13,7 +14,7 @@ let AttributeSchema = new SimpleSchema({
|
|||||||
variableName: {
|
variableName: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: VARIABLE_NAME_REGEX,
|
regEx: VARIABLE_NAME_REGEX,
|
||||||
min: 3,
|
min: 2,
|
||||||
defaultValue: 'newAttribute',
|
defaultValue: 'newAttribute',
|
||||||
},
|
},
|
||||||
// How it is displayed and computed is determined by type
|
// How it is displayed and computed is determined by type
|
||||||
@@ -38,6 +39,11 @@ let AttributeSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
allowedValues: ['d4', 'd6', 'd8', 'd10', 'd12', 'd20'],
|
allowedValues: ['d4', 'd6', 'd8', 'd10', 'd12', 'd20'],
|
||||||
optional: true,
|
optional: true,
|
||||||
|
},
|
||||||
|
// For type spellSlot, the level needs to be stored separately
|
||||||
|
spellSlotLevelCalculation: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
},
|
},
|
||||||
// The starting value, before effects
|
// The starting value, before effects
|
||||||
baseValueCalculation: {
|
baseValueCalculation: {
|
||||||
@@ -73,18 +79,48 @@ let ComputedOnlyAttributeSchema = new SimpleSchema({
|
|||||||
baseValue: {
|
baseValue: {
|
||||||
type: SimpleSchema.oneOf(Number, String, Boolean),
|
type: SimpleSchema.oneOf(Number, String, Boolean),
|
||||||
optional: true,
|
optional: true,
|
||||||
|
},
|
||||||
|
baseValueErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'baseValueErrors.$': {
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
|
// The result of spellSlotLevelCalculation
|
||||||
|
spellSlotLevelValue: {
|
||||||
|
type: SimpleSchema.oneOf(Number, String, Boolean),
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
spellSlotLevelErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'spellSlotLevelErrors.$': {
|
||||||
|
type: ErrorSchema,
|
||||||
},
|
},
|
||||||
// The computed value of the attribute
|
// The computed value of the attribute
|
||||||
value: {
|
value: {
|
||||||
type: SimpleSchema.oneOf(Number, String, Boolean),
|
type: SimpleSchema.oneOf(Number, String, Boolean),
|
||||||
defaultValue: 0,
|
defaultValue: 0,
|
||||||
optional: true,
|
optional: true,
|
||||||
|
},
|
||||||
|
// The computed value of the attribute minus the damage
|
||||||
|
currentValue: {
|
||||||
|
type: SimpleSchema.oneOf(Number, String, Boolean),
|
||||||
|
defaultValue: 0,
|
||||||
|
optional: true,
|
||||||
},
|
},
|
||||||
// The computed modifier, provided the attribute type is `ability`
|
// The computed modifier, provided the attribute type is `ability`
|
||||||
modifier: {
|
modifier: {
|
||||||
type: SimpleSchema.Integer,
|
type: SimpleSchema.Integer,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
// Should this attribute hide
|
||||||
|
hide: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const ComputedAttributeSchema = new SimpleSchema()
|
const ComputedAttributeSchema = new SimpleSchema()
|
||||||
|
|||||||
@@ -6,9 +6,14 @@ let ClassLevelSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
description: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
// The name of this class level's variable
|
// The name of this class level's variable
|
||||||
variableName: {
|
variableName: {
|
||||||
type: String,
|
type: String,
|
||||||
|
min: 2,
|
||||||
regEx: VARIABLE_NAME_REGEX,
|
regEx: VARIABLE_NAME_REGEX,
|
||||||
},
|
},
|
||||||
level: {
|
level: {
|
||||||
@@ -22,6 +27,11 @@ let ClassLevelSchema = new SimpleSchema({
|
|||||||
'nextLevelTags.$': {
|
'nextLevelTags.$': {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
|
// Same as in SlotFillers.js
|
||||||
|
slotFillerCondition: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { ClassLevelSchema };
|
export { ClassLevelSchema };
|
||||||
|
|||||||
@@ -18,12 +18,12 @@ let ContainerSchema = new SimpleSchema({
|
|||||||
weight: {
|
weight: {
|
||||||
type: Number,
|
type: Number,
|
||||||
min: 0,
|
min: 0,
|
||||||
defaultValue: 0
|
optional: true,
|
||||||
},
|
},
|
||||||
value: {
|
value: {
|
||||||
type: Number,
|
type: Number,
|
||||||
min: 0,
|
min: 0,
|
||||||
defaultValue: 0
|
optional: true,
|
||||||
},
|
},
|
||||||
description: {
|
description: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -32,4 +32,16 @@ let ContainerSchema = new SimpleSchema({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { ContainerSchema };
|
const ComputedOnlyContainerSchema = new SimpleSchema({
|
||||||
|
// Weight of all the contents, zero if `contentsWeightless` is true
|
||||||
|
contentsWeight:{
|
||||||
|
type: Number,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ComputedContainerSchema = new SimpleSchema()
|
||||||
|
.extend(ComputedOnlyContainerSchema)
|
||||||
|
.extend(ContainerSchema);
|
||||||
|
|
||||||
|
export { ContainerSchema, ComputedContainerSchema };
|
||||||
|
|||||||
@@ -34,11 +34,11 @@ let DamageMultiplierSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
// Tags which must be present to be affected by this multiplier (AND)
|
// Tags which must be present to be affected by this multiplier (AND)
|
||||||
targetTags: {
|
includeTags: {
|
||||||
type: Array,
|
type: Array,
|
||||||
defaultValue: [],
|
defaultValue: [],
|
||||||
},
|
},
|
||||||
'targetTags.$': {
|
'includeTags.$': {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import DAMAGE_TYPES from '/imports/constants/DAMAGE_TYPES.js';
|
|||||||
|
|
||||||
const DamageSchema = new SimpleSchema({
|
const DamageSchema = new SimpleSchema({
|
||||||
// The roll that determines how much to damage the attribute
|
// The roll that determines how much to damage the attribute
|
||||||
|
// This can be simplified, but only computed when applied
|
||||||
amount: {
|
amount: {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
/*
|
/*
|
||||||
* Effects are reason-value attached to skills and abilities
|
* Effects are reason-value attached to skills and abilities
|
||||||
* that modify their final value or presentation in some way
|
* that modify their final value or presentation in some way
|
||||||
@@ -18,6 +18,7 @@ let EffectSchema = new SimpleSchema({
|
|||||||
'mul',
|
'mul',
|
||||||
'min',
|
'min',
|
||||||
'max',
|
'max',
|
||||||
|
'set',
|
||||||
'advantage',
|
'advantage',
|
||||||
'disadvantage',
|
'disadvantage',
|
||||||
'passiveAdd',
|
'passiveAdd',
|
||||||
@@ -37,7 +38,6 @@ let EffectSchema = new SimpleSchema({
|
|||||||
},
|
},
|
||||||
'stats.$': {
|
'stats.$': {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -47,7 +47,15 @@ const ComputedOnlyEffectSchema = new SimpleSchema({
|
|||||||
type: SimpleSchema.oneOf(Number, String, Boolean),
|
type: SimpleSchema.oneOf(Number, String, Boolean),
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
})
|
// The errors encountered while computing the result
|
||||||
|
errors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'errors.$':{
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const ComputedEffectSchema = new SimpleSchema()
|
const ComputedEffectSchema = new SimpleSchema()
|
||||||
.extend(ComputedOnlyEffectSchema)
|
.extend(ComputedOnlyEffectSchema)
|
||||||
|
|||||||
@@ -24,13 +24,13 @@ const ItemSchema = new SimpleSchema({
|
|||||||
weight: {
|
weight: {
|
||||||
type: Number,
|
type: Number,
|
||||||
min: 0,
|
min: 0,
|
||||||
defaultValue: 0,
|
optional: true,
|
||||||
},
|
},
|
||||||
// Value per item in the stack, in gold pieces
|
// Value per item in the stack, in gold pieces
|
||||||
value: {
|
value: {
|
||||||
type: Number,
|
type: Number,
|
||||||
min: 0,
|
min: 0,
|
||||||
defaultValue: 0,
|
optional: true,
|
||||||
},
|
},
|
||||||
// If this item is equipped, it requires attunement
|
// If this item is equipped, it requires attunement
|
||||||
// Being equipped is `enabled === true`
|
// Being equipped is `enabled === true`
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ let ProficiencySchema = new SimpleSchema({
|
|||||||
},
|
},
|
||||||
'stats.$': {
|
'stats.$': {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
|
||||||
},
|
},
|
||||||
// A number representing how proficient the character is
|
// A number representing how proficient the character is
|
||||||
value: {
|
value: {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import SimpleSchema from 'simpl-schema';
|
|||||||
* child rolls are applied
|
* child rolls are applied
|
||||||
*/
|
*/
|
||||||
let RollSchema = new SimpleSchema({
|
let RollSchema = new SimpleSchema({
|
||||||
// The roll
|
// The roll, can be simplified, but only computed in context
|
||||||
roll: {
|
roll: {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
|
|
||||||
// These are the rolls made when saves are called for
|
// These are the rolls made when saves are called for
|
||||||
// For the saving throw bonus or proficiency, see ./Skills.js
|
// For the saving throw bonus or proficiency, see ./Skills.js
|
||||||
let SavingThrowSchema = new SimpleSchema ({
|
let SavingThrowSchema = new SimpleSchema ({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
dc: {
|
dc: {
|
||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
@@ -14,4 +19,22 @@ let SavingThrowSchema = new SimpleSchema ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { SavingThrowSchema };
|
const ComputedOnlySavingThrowSchema = new SimpleSchema({
|
||||||
|
dcResult: {
|
||||||
|
type: Number,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
dcErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'dcErrors.$':{
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ComputedSavingThrowSchema = new SimpleSchema()
|
||||||
|
.extend(SavingThrowSchema)
|
||||||
|
.extend(ComputedOnlySavingThrowSchema);
|
||||||
|
|
||||||
|
export { SavingThrowSchema, ComputedOnlySavingThrowSchema, ComputedSavingThrowSchema };
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import VARIABLE_NAME_REGEX from '/imports/constants/VARIABLE_NAME_REGEX.js';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Skills are anything that results in a modifier to be added to a D20
|
* Skills are anything that results in a modifier to be added to a D20
|
||||||
@@ -13,7 +15,8 @@ let SkillSchema = new SimpleSchema({
|
|||||||
// Ignored for skilltype = save
|
// Ignored for skilltype = save
|
||||||
variableName: {
|
variableName: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: /^\w*[a-z]\w*$/i,
|
regEx: VARIABLE_NAME_REGEX,
|
||||||
|
min: 2,
|
||||||
},
|
},
|
||||||
// The variable name of the ability this skill relies on
|
// The variable name of the ability this skill relies on
|
||||||
ability: {
|
ability: {
|
||||||
@@ -35,9 +38,9 @@ let SkillSchema = new SimpleSchema({
|
|||||||
],
|
],
|
||||||
defaultValue: 'skill',
|
defaultValue: 'skill',
|
||||||
},
|
},
|
||||||
// If the baseValue is higher than the computed value, it will be used as `value`
|
// The starting value, before effects
|
||||||
baseValue: {
|
baseValueCalculation: {
|
||||||
type: Number,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
// The base proficiency of this skill
|
// The base proficiency of this skill
|
||||||
@@ -57,6 +60,18 @@ let ComputedOnlySkillSchema = new SimpleSchema({
|
|||||||
value: {
|
value: {
|
||||||
type: Number,
|
type: Number,
|
||||||
defaultValue: 0,
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
// The result of baseValueCalculation
|
||||||
|
baseValue: {
|
||||||
|
type: SimpleSchema.oneOf(Number, String, Boolean),
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
baseValueErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'baseValueErrors.$': {
|
||||||
|
type: ErrorSchema,
|
||||||
},
|
},
|
||||||
// Computed value added by the ability
|
// Computed value added by the ability
|
||||||
abilityMod: {
|
abilityMod: {
|
||||||
@@ -101,6 +116,11 @@ let ComputedOnlySkillSchema = new SimpleSchema({
|
|||||||
type: SimpleSchema.Integer,
|
type: SimpleSchema.Integer,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
// Should this attribute hide
|
||||||
|
hide: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const ComputedSkillSchema = new SimpleSchema()
|
const ComputedSkillSchema = new SimpleSchema()
|
||||||
|
|||||||
38
app/imports/api/properties/SlotFillers.js
Normal file
38
app/imports/api/properties/SlotFillers.js
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
// SlotFiller fillers specifically fill a slot with a bit more control than
|
||||||
|
// other properties
|
||||||
|
|
||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
|
||||||
|
let SlotFillerSchema = new SimpleSchema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
picture: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// Overrides the type when searching for properties
|
||||||
|
slotFillerType: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// Fill more than one quantity in a slot, like feats and ability score
|
||||||
|
// improvements, filtered out of UI if there isn't space in quantityExpected
|
||||||
|
slotQuantityFilled: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
defaultValue: 1,
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
// Filters out of UI if condition isn't met, but isn't otherwise enforced
|
||||||
|
slotFillerCondition: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export { SlotFillerSchema };
|
||||||
@@ -1,6 +1,19 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
|
|
||||||
let SlotSchema = new SimpleSchema({
|
let SlotSchema = new SimpleSchema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
slotType: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
slotTags: {
|
slotTags: {
|
||||||
type: Array,
|
type: Array,
|
||||||
defaultValue: [],
|
defaultValue: [],
|
||||||
@@ -8,6 +21,51 @@ let SlotSchema = new SimpleSchema({
|
|||||||
'slotTags.$': {
|
'slotTags.$': {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
|
quantityExpected: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
defaultValue: 1,
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
ignored: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
slotCondition: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
hideWhenFull: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
export { SlotSchema };
|
const ComputedOnlySlotSchema = new SimpleSchema({
|
||||||
|
// The computed result of the effect
|
||||||
|
slotConditionResult: {
|
||||||
|
type: SimpleSchema.oneOf(Number, String, Boolean),
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
// The errors encountered while computing the result
|
||||||
|
slotConditionErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'slotConditionErrors.$':{
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
|
totalFilled: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
spaceLeft: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ComputedSlotSchema = new SimpleSchema()
|
||||||
|
.extend(ComputedOnlySlotSchema)
|
||||||
|
.extend(SlotSchema);
|
||||||
|
|
||||||
|
export { SlotSchema, ComputedSlotSchema, ComputedOnlySlotSchema };
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
|
import VARIABLE_NAME_REGEX from '/imports/constants/VARIABLE_NAME_REGEX.js';
|
||||||
|
|
||||||
let SpellListSchema = new SimpleSchema({
|
let SpellListSchema = new SimpleSchema({
|
||||||
name: {
|
name: {
|
||||||
@@ -9,6 +11,12 @@ let SpellListSchema = new SimpleSchema({
|
|||||||
type: String,
|
type: String,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
variableName: {
|
||||||
|
type: String,
|
||||||
|
regEx: VARIABLE_NAME_REGEX,
|
||||||
|
min: 2,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
// Calculation of how many spells in this list can be prepared
|
// Calculation of how many spells in this list can be prepared
|
||||||
maxPrepared: {
|
maxPrepared: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -16,4 +24,22 @@ let SpellListSchema = new SimpleSchema({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { SpellListSchema }
|
const ComputedOnlySpellListSchema = new SimpleSchema({
|
||||||
|
maxPreparedResult: {
|
||||||
|
type: Number,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
maxPreparedErrors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'maxPreparedErrors.$':{
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ComputedSpellListSchema = new SimpleSchema()
|
||||||
|
.extend(SpellListSchema)
|
||||||
|
.extend(ComputedOnlySpellListSchema);
|
||||||
|
|
||||||
|
export { SpellListSchema, ComputedOnlySpellListSchema, ComputedSpellListSchema };
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { ActionSchema } from '/imports/api/properties/Actions.js';
|
import { ActionSchema, ComputedOnlyActionSchema } from '/imports/api/properties/Actions.js';
|
||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import VARIABLE_NAME_REGEX from '/imports/constants/VARIABLE_NAME_REGEX.js';
|
||||||
|
|
||||||
const magicSchools = [
|
const magicSchools = [
|
||||||
'abjuration',
|
'abjuration',
|
||||||
@@ -25,6 +26,10 @@ let SpellSchema = new SimpleSchema({})
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
prepared: {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
// This spell ignores spell slot rules
|
// This spell ignores spell slot rules
|
||||||
castWithoutSpellSlots: {
|
castWithoutSpellSlots: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
@@ -33,14 +38,6 @@ let SpellSchema = new SimpleSchema({})
|
|||||||
hasAttackRoll: {
|
hasAttackRoll: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
|
||||||
// Spell lists that this spell appears on
|
|
||||||
spellLists: {
|
|
||||||
type: Array,
|
|
||||||
defaultValue: [],
|
|
||||||
},
|
|
||||||
'spellLists.$': {
|
|
||||||
type: String,
|
|
||||||
},
|
},
|
||||||
description: {
|
description: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -93,4 +90,11 @@ let SpellSchema = new SimpleSchema({})
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export { SpellSchema };
|
const ComputedOnlySpellSchema = new SimpleSchema()
|
||||||
|
.extend(ComputedOnlyActionSchema);
|
||||||
|
|
||||||
|
const ComputedSpellSchema = new SimpleSchema()
|
||||||
|
.extend(SpellSchema)
|
||||||
|
.extend(ComputedOnlySpellSchema);
|
||||||
|
|
||||||
|
export { SpellSchema, ComputedOnlySpellSchema, ComputedSpellSchema };
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import ErrorSchema from '/imports/api/properties/subSchemas/ErrorSchema.js';
|
||||||
|
|
||||||
const ToggleSchema = new SimpleSchema({
|
const ToggleSchema = new SimpleSchema({
|
||||||
name: {
|
name: {
|
||||||
@@ -24,9 +25,17 @@ const ToggleSchema = new SimpleSchema({
|
|||||||
const ComputedOnlyToggleSchema = new SimpleSchema({
|
const ComputedOnlyToggleSchema = new SimpleSchema({
|
||||||
// The computed result of the effect
|
// The computed result of the effect
|
||||||
toggleResult: {
|
toggleResult: {
|
||||||
type: SimpleSchema.oneOf(Number, String, Boolean),
|
type: Boolean,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
// The errors encountered while computing the result
|
||||||
|
errors: {
|
||||||
|
type: Array,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
'errors.$': {
|
||||||
|
type: ErrorSchema,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const ComputedToggleSchema = new SimpleSchema()
|
const ComputedToggleSchema = new SimpleSchema()
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import { ActionSchema } from '/imports/api/properties/Actions.js';
|
import { ComputedActionSchema } from '/imports/api/properties/Actions.js';
|
||||||
import { AdjustmentSchema } from '/imports/api/properties/Adjustments.js';
|
import { AdjustmentSchema } from '/imports/api/properties/Adjustments.js';
|
||||||
import { AttackSchema } from '/imports/api/properties/Attacks.js';
|
import { ComputedAttackSchema } from '/imports/api/properties/Attacks.js';
|
||||||
import { ComputedAttributeSchema } from '/imports/api/properties/Attributes.js';
|
import { ComputedAttributeSchema } from '/imports/api/properties/Attributes.js';
|
||||||
import { BuffSchema } from '/imports/api/properties/Buffs.js';
|
import { BuffSchema } from '/imports/api/properties/Buffs.js';
|
||||||
import { ClassLevelSchema } from '/imports/api/properties/ClassLevels.js';
|
import { ClassLevelSchema } from '/imports/api/properties/ClassLevels.js';
|
||||||
@@ -9,41 +9,41 @@ import { ContainerSchema } from '/imports/api/properties/Containers.js';
|
|||||||
import { DamageSchema } from '/imports/api/properties/Damages.js';
|
import { DamageSchema } from '/imports/api/properties/Damages.js';
|
||||||
import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js';
|
import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js';
|
||||||
import { ComputedEffectSchema } from '/imports/api/properties/Effects.js';
|
import { ComputedEffectSchema } from '/imports/api/properties/Effects.js';
|
||||||
import { ExperienceSchema } from '/imports/api/properties/Experiences.js';
|
|
||||||
import { FeatureSchema } from '/imports/api/properties/Features.js';
|
import { FeatureSchema } from '/imports/api/properties/Features.js';
|
||||||
import { FolderSchema } from '/imports/api/properties/Folders.js';
|
import { FolderSchema } from '/imports/api/properties/Folders.js';
|
||||||
import { ItemSchema } from '/imports/api/properties/Items.js';
|
import { ItemSchema } from '/imports/api/properties/Items.js';
|
||||||
import { NoteSchema } from '/imports/api/properties/Notes.js';
|
import { NoteSchema } from '/imports/api/properties/Notes.js';
|
||||||
import { ProficiencySchema } from '/imports/api/properties/Proficiencies.js';
|
import { ProficiencySchema } from '/imports/api/properties/Proficiencies.js';
|
||||||
import { RollSchema } from '/imports/api/properties/Rolls.js';
|
import { RollSchema } from '/imports/api/properties/Rolls.js';
|
||||||
import { SavingThrowSchema } from '/imports/api/properties/SavingThrows.js';
|
import { ComputedSavingThrowSchema } from '/imports/api/properties/SavingThrows.js';
|
||||||
import { ComputedSkillSchema } from '/imports/api/properties/Skills.js';
|
import { ComputedSkillSchema } from '/imports/api/properties/Skills.js';
|
||||||
import { SlotSchema } from '/imports/api/properties/Slots.js';
|
import { ComputedSlotSchema } from '/imports/api/properties/Slots.js';
|
||||||
import { SpellSchema } from '/imports/api/properties/Spells.js';
|
import { SlotFillerSchema } from '/imports/api/properties/SlotFillers.js';
|
||||||
import { SpellListSchema } from '/imports/api/properties/SpellLists.js';
|
import { ComputedSpellSchema } from '/imports/api/properties/Spells.js';
|
||||||
|
import { ComputedSpellListSchema } from '/imports/api/properties/SpellLists.js';
|
||||||
import { ToggleSchema } from '/imports/api/properties/Toggles.js';
|
import { ToggleSchema } from '/imports/api/properties/Toggles.js';
|
||||||
|
|
||||||
const propertySchemasIndex = {
|
const propertySchemasIndex = {
|
||||||
action: ActionSchema,
|
action: ComputedActionSchema,
|
||||||
adjustment: AdjustmentSchema,
|
adjustment: AdjustmentSchema,
|
||||||
attack: AttackSchema,
|
attack: ComputedAttackSchema,
|
||||||
attribute: ComputedAttributeSchema,
|
attribute: ComputedAttributeSchema,
|
||||||
buff: BuffSchema,
|
buff: BuffSchema,
|
||||||
classLevel: ClassLevelSchema,
|
classLevel: ClassLevelSchema,
|
||||||
damage: DamageSchema,
|
damage: DamageSchema,
|
||||||
damageMultiplier: DamageMultiplierSchema,
|
damageMultiplier: DamageMultiplierSchema,
|
||||||
effect: ComputedEffectSchema,
|
effect: ComputedEffectSchema,
|
||||||
experience: ExperienceSchema,
|
|
||||||
feature: FeatureSchema,
|
feature: FeatureSchema,
|
||||||
folder: FolderSchema,
|
folder: FolderSchema,
|
||||||
note: NoteSchema,
|
note: NoteSchema,
|
||||||
proficiency: ProficiencySchema,
|
proficiency: ProficiencySchema,
|
||||||
|
propertySlot: ComputedSlotSchema,
|
||||||
roll: RollSchema,
|
roll: RollSchema,
|
||||||
savingThrow: SavingThrowSchema,
|
savingThrow: ComputedSavingThrowSchema,
|
||||||
skill: ComputedSkillSchema,
|
skill: ComputedSkillSchema,
|
||||||
slot: SlotSchema,
|
slotFiller: SlotFillerSchema,
|
||||||
spellList: SpellListSchema,
|
spellList: ComputedSpellListSchema,
|
||||||
spell: SpellSchema,
|
spell: ComputedSpellSchema,
|
||||||
toggle: ToggleSchema,
|
toggle: ToggleSchema,
|
||||||
container: ContainerSchema,
|
container: ContainerSchema,
|
||||||
item: ItemSchema,
|
item: ItemSchema,
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import { ClassLevelSchema } from '/imports/api/properties/ClassLevels.js';
|
|||||||
import { DamageSchema } from '/imports/api/properties/Damages.js';
|
import { DamageSchema } from '/imports/api/properties/Damages.js';
|
||||||
import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js';
|
import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js';
|
||||||
import { EffectSchema } from '/imports/api/properties/Effects.js';
|
import { EffectSchema } from '/imports/api/properties/Effects.js';
|
||||||
import { ExperienceSchema } from '/imports/api/properties/Experiences.js';
|
|
||||||
import { FeatureSchema } from '/imports/api/properties/Features.js';
|
import { FeatureSchema } from '/imports/api/properties/Features.js';
|
||||||
import { FolderSchema } from '/imports/api/properties/Folders.js';
|
import { FolderSchema } from '/imports/api/properties/Folders.js';
|
||||||
import { NoteSchema } from '/imports/api/properties/Notes.js';
|
import { NoteSchema } from '/imports/api/properties/Notes.js';
|
||||||
@@ -17,6 +16,7 @@ import { RollSchema } from '/imports/api/properties/Rolls.js';
|
|||||||
import { SavingThrowSchema } from '/imports/api/properties/SavingThrows.js';
|
import { SavingThrowSchema } from '/imports/api/properties/SavingThrows.js';
|
||||||
import { SkillSchema } from '/imports/api/properties/Skills.js';
|
import { SkillSchema } from '/imports/api/properties/Skills.js';
|
||||||
import { SlotSchema } from '/imports/api/properties/Slots.js';
|
import { SlotSchema } from '/imports/api/properties/Slots.js';
|
||||||
|
import { SlotFillerSchema } from '/imports/api/properties/SlotFillers.js';
|
||||||
import { SpellListSchema } from '/imports/api/properties/SpellLists.js';
|
import { SpellListSchema } from '/imports/api/properties/SpellLists.js';
|
||||||
import { SpellSchema } from '/imports/api/properties/Spells.js';
|
import { SpellSchema } from '/imports/api/properties/Spells.js';
|
||||||
import { ToggleSchema } from '/imports/api/properties/Toggles.js';
|
import { ToggleSchema } from '/imports/api/properties/Toggles.js';
|
||||||
@@ -33,15 +33,15 @@ const propertySchemasIndex = {
|
|||||||
damage: DamageSchema,
|
damage: DamageSchema,
|
||||||
damageMultiplier: DamageMultiplierSchema,
|
damageMultiplier: DamageMultiplierSchema,
|
||||||
effect: EffectSchema,
|
effect: EffectSchema,
|
||||||
experience: ExperienceSchema,
|
|
||||||
feature: FeatureSchema,
|
feature: FeatureSchema,
|
||||||
folder: FolderSchema,
|
folder: FolderSchema,
|
||||||
note: NoteSchema,
|
note: NoteSchema,
|
||||||
proficiency: ProficiencySchema,
|
proficiency: ProficiencySchema,
|
||||||
|
propertySlot: SlotSchema,
|
||||||
roll: RollSchema,
|
roll: RollSchema,
|
||||||
savingThrow: SavingThrowSchema,
|
savingThrow: SavingThrowSchema,
|
||||||
skill: SkillSchema,
|
skill: SkillSchema,
|
||||||
slot: SlotSchema,
|
slotFiller: SlotFillerSchema,
|
||||||
spellList: SpellListSchema,
|
spellList: SpellListSchema,
|
||||||
spell: SpellSchema,
|
spell: SpellSchema,
|
||||||
toggle: ToggleSchema,
|
toggle: ToggleSchema,
|
||||||
|
|||||||
12
app/imports/api/properties/subSchemas/ErrorSchema.js
Normal file
12
app/imports/api/properties/subSchemas/ErrorSchema.js
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
|
||||||
|
const ErrorSchema = new SimpleSchema({
|
||||||
|
message: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
type: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default ErrorSchema;
|
||||||
@@ -17,6 +17,10 @@ const ItemConsumedSchema = new SimpleSchema({
|
|||||||
type: Number,
|
type: Number,
|
||||||
defaultValue: 1,
|
defaultValue: 1,
|
||||||
},
|
},
|
||||||
|
itemId: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export default ItemConsumedSchema;
|
export default ItemConsumedSchema;
|
||||||
|
|||||||
@@ -4,13 +4,19 @@ import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js';
|
|||||||
import getCollectionByName from '/imports/api/parenting/getCollectionByName.js';
|
import getCollectionByName from '/imports/api/parenting/getCollectionByName.js';
|
||||||
import { RefSchema } from '/imports/api/parenting/ChildSchema.js';
|
import { RefSchema } from '/imports/api/parenting/ChildSchema.js';
|
||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
|
||||||
const setPublic = new ValidatedMethod({
|
const setPublic = new ValidatedMethod({
|
||||||
name: 'sharing.methods.setPublic',
|
name: 'sharing.setPublic',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
docRef: RefSchema,
|
docRef: RefSchema,
|
||||||
isPublic: { type: Boolean },
|
isPublic: { type: Boolean },
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({docRef, isPublic}){
|
run({docRef, isPublic}){
|
||||||
let doc = fetchDocByRef(docRef);
|
let doc = fetchDocByRef(docRef);
|
||||||
assertOwnership(doc, this.userId);
|
assertOwnership(doc, this.userId);
|
||||||
@@ -21,7 +27,7 @@ const setPublic = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const updateUserSharePermissions = new ValidatedMethod({
|
const updateUserSharePermissions = new ValidatedMethod({
|
||||||
name: 'sharing.methods.updateUserSharePermissions',
|
name: 'sharing.updateUserSharePermissions',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
docRef: RefSchema,
|
docRef: RefSchema,
|
||||||
userId: {
|
userId: {
|
||||||
@@ -33,6 +39,11 @@ const updateUserSharePermissions = new ValidatedMethod({
|
|||||||
allowedValues: ['reader', 'writer', 'none'],
|
allowedValues: ['reader', 'writer', 'none'],
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({docRef, userId, role}){
|
run({docRef, userId, role}){
|
||||||
let doc = fetchDocByRef(docRef);
|
let doc = fetchDocByRef(docRef);
|
||||||
if (role === 'none'){
|
if (role === 'none'){
|
||||||
|
|||||||
@@ -88,18 +88,18 @@ export function assertDocEditPermission(doc, userId){
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function assertViewPermission(doc, userId) {
|
export function assertViewPermission(doc, userId) {
|
||||||
assertIdValid(userId);
|
|
||||||
assertdocExists(doc);
|
assertdocExists(doc);
|
||||||
|
if (doc.public) return true;
|
||||||
|
assertIdValid(userId);
|
||||||
if (
|
if (
|
||||||
doc.owner === userId ||
|
doc.owner === userId ||
|
||||||
doc.public ||
|
|
||||||
_.contains(doc.readers, userId) ||
|
_.contains(doc.readers, userId) ||
|
||||||
_.contains(doc.writers, userId)
|
_.contains(doc.writers, userId)
|
||||||
){
|
){
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
throw new Meteor.Error('View permission denied',
|
throw new Meteor.Error('View permission denied',
|
||||||
'You do not have permission to view this character');
|
'You do not have permission to view this document');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,3 +113,17 @@ export function assertDocViewPermission(doc, userId){
|
|||||||
let root = getRoot(doc);
|
let root = getRoot(doc);
|
||||||
assertViewPermission(root, userId);
|
assertViewPermission(root, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function assertAdmin(userId){
|
||||||
|
assertIdValid(userId);
|
||||||
|
let user = Meteor.users.findOne(userId, {fields: {roles: 1}});
|
||||||
|
if (!user){
|
||||||
|
throw new Meteor.Error('Permission denied',
|
||||||
|
'UserId does not match any existing user');
|
||||||
|
}
|
||||||
|
let isAdmin = user.roles && user.roles.includes('admin')
|
||||||
|
if (!isAdmin){
|
||||||
|
throw new Meteor.Error('Permission denied',
|
||||||
|
'User does not have the admin role');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
115
app/imports/api/tabletop/Messages.js
Normal file
115
app/imports/api/tabletop/Messages.js
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
import Tabletops, { assertUserInTabletop } from '/imports/api/tabletop/Tabletops.js';
|
||||||
|
|
||||||
|
let Messages = new Mongo.Collection('messages');
|
||||||
|
|
||||||
|
let MessagesSchema = new SimpleSchema({
|
||||||
|
tabletopId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
content: {
|
||||||
|
type: String,
|
||||||
|
max: 1000,
|
||||||
|
},
|
||||||
|
timestamp: {
|
||||||
|
type: Date,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
userId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
username: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Messages.attachSchema(MessagesSchema);
|
||||||
|
|
||||||
|
const sendMessage = new ValidatedMethod({
|
||||||
|
|
||||||
|
name: 'messages.send',
|
||||||
|
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
content: {
|
||||||
|
type: String,
|
||||||
|
max: 1000,
|
||||||
|
},
|
||||||
|
tabletopId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 10,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
|
run({content, tabletopId}) {
|
||||||
|
let user = Meteor.user();
|
||||||
|
if (!user) {
|
||||||
|
throw new Meteor.Error('messages.send.denied',
|
||||||
|
'You need to be logged in to send a message');
|
||||||
|
}
|
||||||
|
assertUserInTabletop(tabletopId, this.userId);
|
||||||
|
|
||||||
|
return Messages.insert({
|
||||||
|
content,
|
||||||
|
tabletopId,
|
||||||
|
timestamp: new Date(),
|
||||||
|
userId: user._id,
|
||||||
|
username: user.username,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
const removeMessages = new ValidatedMethod({
|
||||||
|
|
||||||
|
name: 'messages.remove',
|
||||||
|
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
messageId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
|
run({messageId, tabletopId}) {
|
||||||
|
if (!this.userId) {
|
||||||
|
throw new Meteor.Error('messages.remove.denied',
|
||||||
|
'You need to be logged in to remove a tabletop');
|
||||||
|
}
|
||||||
|
let message = Messages.findOne(messageId);
|
||||||
|
let tabletop = Tabletops.findOne(message.tabletopId);
|
||||||
|
if (this.userId !== message.userId && this.userId !== tabletop.gameMaster){
|
||||||
|
throw new Meteor.Error('messages.remove.denied',
|
||||||
|
'You don\'t have permission to remove this message');
|
||||||
|
}
|
||||||
|
let removed = Messages.remove({
|
||||||
|
_id: messageId,
|
||||||
|
});
|
||||||
|
Creatures.update({
|
||||||
|
tabletop: tabletopId,
|
||||||
|
}, {
|
||||||
|
$unset: {tabletop: 1},
|
||||||
|
});
|
||||||
|
return removed;
|
||||||
|
},
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export default Messages;
|
||||||
|
export { sendMessage, removeMessages };
|
||||||
201
app/imports/api/tabletop/Tabletops.js
Normal file
201
app/imports/api/tabletop/Tabletops.js
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
import SimpleSchema from 'simpl-schema';
|
||||||
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
import { assertUserHasPaidBenefits } from '/imports/api/users/patreon/tiers.js';
|
||||||
|
import Creatures from '/imports/api/creature/Creatures.js';
|
||||||
|
|
||||||
|
let Tabletops = new Mongo.Collection('tabletops');
|
||||||
|
|
||||||
|
const InitiativeSchema = new SimpleSchema({
|
||||||
|
active: {
|
||||||
|
type: Boolean,
|
||||||
|
defaultValue: false,
|
||||||
|
},
|
||||||
|
roundNumber: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
initiativeNumber: {
|
||||||
|
type: SimpleSchema.Integer,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
activeCreature: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// All creatures in a tabletop have a shared time and space.
|
||||||
|
let TabletopSchema = new SimpleSchema({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
|
initiative: {
|
||||||
|
type: InitiativeSchema,
|
||||||
|
defaultValue: {},
|
||||||
|
},
|
||||||
|
gameMaster: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
players: {
|
||||||
|
type: Array,
|
||||||
|
defaultValue: [],
|
||||||
|
},
|
||||||
|
'players.$': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Tabletops.attachSchema(TabletopSchema);
|
||||||
|
|
||||||
|
function assertUserIsTabletopOwner(tabletopId, userId){
|
||||||
|
let tabletop = Tabletops.findOne(tabletopId);
|
||||||
|
if (!tabletop){
|
||||||
|
throw new Meteor.Error('Tabletop does not exist',
|
||||||
|
'No tabletop could be found for the given tabletop id');
|
||||||
|
}
|
||||||
|
if (tabletop.gameMaster !== userId){
|
||||||
|
throw new Meteor.Error('Not the owner',
|
||||||
|
'The user is not the owner of the given tabletop');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertUserInTabletop(tabletopId, userId){
|
||||||
|
let tabletop = Tabletops.findOne(tabletopId);
|
||||||
|
if (!tabletop){
|
||||||
|
throw new Meteor.Error('Tabletop does not exist',
|
||||||
|
'No tabletop could be found for the given tabletop id');
|
||||||
|
}
|
||||||
|
if (tabletop.gameMaster !== userId && !tabletop.players.includes(userId)){
|
||||||
|
throw new Meteor.Error('Not in tabletop',
|
||||||
|
'The user is not the gamemaster or a player in the given tabletop');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertUserIsAdmin(userId){
|
||||||
|
if (!Meteor.users.isAdmin(userId)){
|
||||||
|
throw new Meteor.Error('Admin only',
|
||||||
|
'This is restricted to admins for now');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertTabletop = new ValidatedMethod({
|
||||||
|
|
||||||
|
name: 'tabletops.insert',
|
||||||
|
|
||||||
|
validate: null,
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
|
run() {
|
||||||
|
if (!this.userId) {
|
||||||
|
throw new Meteor.Error('tabletops.insert.denied',
|
||||||
|
'You need to be logged in to insert a tabletop');
|
||||||
|
}
|
||||||
|
assertUserHasPaidBenefits(this.userId);
|
||||||
|
assertUserIsAdmin(this.userId);
|
||||||
|
|
||||||
|
return Tabletops.insert({
|
||||||
|
gameMaster: this.userId,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
const removeTabletop = new ValidatedMethod({
|
||||||
|
|
||||||
|
name: 'tabletops.remove',
|
||||||
|
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
tabletopId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
|
run({tabletopId}) {
|
||||||
|
if (!this.userId) {
|
||||||
|
throw new Meteor.Error('tabletops.remove.denied',
|
||||||
|
'You need to be logged in to remove a tabletop');
|
||||||
|
}
|
||||||
|
assertUserHasPaidBenefits(this.userId);
|
||||||
|
assertUserIsTabletopOwner(tabletopId, this.userId);
|
||||||
|
assertUserIsAdmin(this.userId);
|
||||||
|
|
||||||
|
let removed = Tabletops.remove({
|
||||||
|
_id: tabletopId,
|
||||||
|
});
|
||||||
|
Creatures.update({
|
||||||
|
tabletop: tabletopId,
|
||||||
|
}, {
|
||||||
|
$unset: {tabletop: 1},
|
||||||
|
});
|
||||||
|
return removed;
|
||||||
|
},
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
const addCreaturesToTabletop = new ValidatedMethod({
|
||||||
|
|
||||||
|
name: 'tabletops.addCreatures',
|
||||||
|
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
'creatureIds': {
|
||||||
|
type: Array,
|
||||||
|
},
|
||||||
|
'creatureIds.$': {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
tabletopId: {
|
||||||
|
type: String,
|
||||||
|
regEx: SimpleSchema.RegEx.id,
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 10,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
|
||||||
|
run({tabletopId, creatureIds}) {
|
||||||
|
if (!this.userId) {
|
||||||
|
throw new Meteor.Error('tabletops.addCreatures.denied',
|
||||||
|
'You need to be logged in to remove a tabletop');
|
||||||
|
}
|
||||||
|
assertUserHasPaidBenefits(this.userId);
|
||||||
|
assertUserInTabletop(tabletopId, this.userId);
|
||||||
|
assertUserIsAdmin(this.userId);
|
||||||
|
|
||||||
|
Creatures.update({
|
||||||
|
_id: {$in: creatureIds},
|
||||||
|
$or: [
|
||||||
|
{writers: this.userId},
|
||||||
|
{owner: this.userId},
|
||||||
|
],
|
||||||
|
}, {
|
||||||
|
$set: {tabletop: tabletopId},
|
||||||
|
}, {
|
||||||
|
multi: true,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
export default Tabletops;
|
||||||
|
export { insertTabletop, removeTabletop, addCreaturesToTabletop };
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
import { getUserTier } from '/imports/api/users/patreon/tiers.js';
|
import { getUserTier } from '/imports/api/users/patreon/tiers.js';
|
||||||
|
|
||||||
let Invites= new Mongo.Collection('invites');
|
let Invites= new Mongo.Collection('invites');
|
||||||
@@ -85,13 +86,18 @@ function alignInvitesWithPatreonTier(user){
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getInviteToken = new ValidatedMethod({
|
const getInviteToken = new ValidatedMethod({
|
||||||
name: 'Invites.methods.getToken',
|
name: 'invites.getToken',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
inviteId: {
|
inviteId: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: SimpleSchema.RegEx.Id,
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({inviteId}) {
|
run({inviteId}) {
|
||||||
let invite = Invites.findOne(inviteId);
|
let invite = Invites.findOne(inviteId);
|
||||||
if (this.userId !== invite.inviter) {
|
if (this.userId !== invite.inviter) {
|
||||||
@@ -109,12 +115,17 @@ const getInviteToken = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const acceptInviteToken = new ValidatedMethod({
|
const acceptInviteToken = new ValidatedMethod({
|
||||||
name: 'Invites.methods.acceptToken',
|
name: 'invites.acceptToken',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
inviteToken: {
|
inviteToken: {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({inviteToken}) {
|
run({inviteToken}) {
|
||||||
if (!this.userId) {
|
if (!this.userId) {
|
||||||
throw new Meteor.Error('Invites.methods.acceptToken.denied',
|
throw new Meteor.Error('Invites.methods.acceptToken.denied',
|
||||||
@@ -146,13 +157,18 @@ const acceptInviteToken = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const revokeInvite = new ValidatedMethod({
|
const revokeInvite = new ValidatedMethod({
|
||||||
name: 'Invites.methods.revokeInvite',
|
name: 'invites.revokeInvite',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
inviteId: {
|
inviteId: {
|
||||||
type: String,
|
type: String,
|
||||||
regEx: SimpleSchema.RegEx.Id,
|
regEx: SimpleSchema.RegEx.Id,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({inviteId}) {
|
run({inviteId}) {
|
||||||
if (!this.userId) {
|
if (!this.userId) {
|
||||||
throw new Meteor.Error('Invites.methods.revokeInvite.denied',
|
throw new Meteor.Error('Invites.methods.revokeInvite.denied',
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import SimpleSchema from 'simpl-schema';
|
import SimpleSchema from 'simpl-schema';
|
||||||
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
import { ValidatedMethod } from 'meteor/mdg:validated-method';
|
||||||
|
import { RateLimiterMixin } from 'ddp-rate-limiter-mixin';
|
||||||
|
|
||||||
const userSchema = new SimpleSchema({
|
const userSchema = new SimpleSchema({
|
||||||
username: {
|
username: {
|
||||||
@@ -82,13 +83,27 @@ const userSchema = new SimpleSchema({
|
|||||||
blackbox: true,
|
blackbox: true,
|
||||||
optional: true,
|
optional: true,
|
||||||
},
|
},
|
||||||
|
preferences: {
|
||||||
|
type: Object,
|
||||||
|
optional: true,
|
||||||
|
defaultValue: {},
|
||||||
|
},
|
||||||
|
'preferences.swapAbilityScoresAndModifiers': {
|
||||||
|
type: Boolean,
|
||||||
|
optional: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Meteor.users.attachSchema(userSchema);
|
Meteor.users.attachSchema(userSchema);
|
||||||
|
|
||||||
Meteor.users.generateApiKey = new ValidatedMethod({
|
Meteor.users.generateApiKey = new ValidatedMethod({
|
||||||
name: 'Users.methods.generateApiKey',
|
name: 'users.generateApiKey',
|
||||||
validate: null,
|
validate: null,
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run(){
|
run(){
|
||||||
if(Meteor.isClient) return;
|
if(Meteor.isClient) return;
|
||||||
var user = Meteor.users.findOne(this.userId);
|
var user = Meteor.users.findOne(this.userId);
|
||||||
@@ -100,10 +115,15 @@ Meteor.users.generateApiKey = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
Meteor.users.setDarkMode = new ValidatedMethod({
|
Meteor.users.setDarkMode = new ValidatedMethod({
|
||||||
name: 'Users.methods.setDarkMode',
|
name: 'users.setDarkMode',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
darkMode: { type: Boolean },
|
darkMode: { type: Boolean },
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({darkMode}){
|
run({darkMode}){
|
||||||
if (!this.userId) return;
|
if (!this.userId) return;
|
||||||
Meteor.users.update(this.userId, {$set: {darkMode}});
|
Meteor.users.update(this.userId, {$set: {darkMode}});
|
||||||
@@ -111,7 +131,7 @@ Meteor.users.setDarkMode = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
Meteor.users.sendVerificationEmail = new ValidatedMethod({
|
Meteor.users.sendVerificationEmail = new ValidatedMethod({
|
||||||
name: 'Users.methods.sendVerificationEmail',
|
name: 'users.sendVerificationEmail',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
userId:{
|
userId:{
|
||||||
type: String,
|
type: String,
|
||||||
@@ -121,6 +141,11 @@ Meteor.users.sendVerificationEmail = new ValidatedMethod({
|
|||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({userId, address}){
|
run({userId, address}){
|
||||||
userId = this.userId || userId;
|
userId = this.userId || userId;
|
||||||
let user = Meteor.users.findOne(userId);
|
let user = Meteor.users.findOne(userId);
|
||||||
@@ -143,8 +168,13 @@ Meteor.users.isAdmin = function(userId){
|
|||||||
}
|
}
|
||||||
|
|
||||||
Meteor.users.canPickUsername = new ValidatedMethod({
|
Meteor.users.canPickUsername = new ValidatedMethod({
|
||||||
name: 'Users.methods.canPickUsername',
|
name: 'users.canPickUsername',
|
||||||
validate: userSchema.pick('username').validator(),
|
validate: userSchema.pick('username').validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({username}){
|
run({username}){
|
||||||
if (Meteor.isClient) return;
|
if (Meteor.isClient) return;
|
||||||
let user = Accounts.findUserByUsername(username);
|
let user = Accounts.findUserByUsername(username);
|
||||||
@@ -157,8 +187,13 @@ Meteor.users.canPickUsername = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
Meteor.users.setUsername = new ValidatedMethod({
|
Meteor.users.setUsername = new ValidatedMethod({
|
||||||
name: 'Users.methods.setUsername',
|
name: 'users.setUsername',
|
||||||
validate: userSchema.pick('username').validator(),
|
validate: userSchema.pick('username').validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({username}){
|
run({username}){
|
||||||
if (!this.userId) throw 'Can only set your username if logged in';
|
if (!this.userId) throw 'Can only set your username if logged in';
|
||||||
if (Meteor.isClient) return;
|
if (Meteor.isClient) return;
|
||||||
@@ -166,8 +201,38 @@ Meteor.users.setUsername = new ValidatedMethod({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Meteor.users.setPreference = new ValidatedMethod({
|
||||||
|
name: 'users.setPreference',
|
||||||
|
validate: new SimpleSchema({
|
||||||
|
preference:{
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
value: {
|
||||||
|
type: SimpleSchema.oneOf(Boolean),
|
||||||
|
},
|
||||||
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
|
run({preference, value}){
|
||||||
|
if (!this.userId) throw 'You can only set preferences once logged in';
|
||||||
|
let prefPath = `preferences.${preference}`
|
||||||
|
if (value == true){
|
||||||
|
return Meteor.users.update(this.userId, {
|
||||||
|
$set: {[prefPath]: true},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return Meteor.users.update(this.userId, {
|
||||||
|
$unset: {[prefPath]: 1},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
Meteor.users.subscribeToLibrary = new ValidatedMethod({
|
Meteor.users.subscribeToLibrary = new ValidatedMethod({
|
||||||
name: 'Users.methods.subscribeToLibrary',
|
name: 'users.subscribeToLibrary',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
libraryId:{
|
libraryId:{
|
||||||
type: String,
|
type: String,
|
||||||
@@ -177,6 +242,11 @@ Meteor.users.subscribeToLibrary = new ValidatedMethod({
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({libraryId, subscribe}){
|
run({libraryId, subscribe}){
|
||||||
if (!this.userId) throw 'Can only subscribe if logged in';
|
if (!this.userId) throw 'Can only subscribe if logged in';
|
||||||
if (subscribe){
|
if (subscribe){
|
||||||
@@ -192,12 +262,17 @@ Meteor.users.subscribeToLibrary = new ValidatedMethod({
|
|||||||
});
|
});
|
||||||
|
|
||||||
Meteor.users.findUserByUsernameOrEmail = new ValidatedMethod({
|
Meteor.users.findUserByUsernameOrEmail = new ValidatedMethod({
|
||||||
name: 'Users.methods.findUserByUsernameOrEmail',
|
name: 'users.findUserByUsernameOrEmail',
|
||||||
validate: new SimpleSchema({
|
validate: new SimpleSchema({
|
||||||
usernameOrEmail:{
|
usernameOrEmail:{
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
}).validator(),
|
}).validator(),
|
||||||
|
mixins: [RateLimiterMixin],
|
||||||
|
rateLimit: {
|
||||||
|
numRequests: 5,
|
||||||
|
timeInterval: 5000,
|
||||||
|
},
|
||||||
run({usernameOrEmail}){
|
run({usernameOrEmail}){
|
||||||
if (Meteor.isClient) return;
|
if (Meteor.isClient) return;
|
||||||
let user = Accounts.findUserByUsername(usernameOrEmail) ||
|
let user = Accounts.findUserByUsername(usernameOrEmail) ||
|
||||||
|
|||||||
@@ -77,5 +77,13 @@ export function getUserTier(user){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function assertUserHasPaidBenefits(user){
|
||||||
|
let tier = getUserTier(user);
|
||||||
|
if (!tier.paidBenefits){
|
||||||
|
throw new Meteor.Error('Creatures.methods.insert.denied',
|
||||||
|
`The ${tier.name} tier does not allow you to insert a creature`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default TIERS;
|
export default TIERS;
|
||||||
export { GUEST_TIER };
|
export { GUEST_TIER };
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import request from 'request';
|
import request from 'request';
|
||||||
|
|
||||||
if (!Meteor.isServer) throw 'Server only, do not import this code in the client';
|
if (!Meteor.isServer) throw 'Server only, do not import this code in the client';
|
||||||
|
|
||||||
const config = ServiceConfiguration.configurations.findOne({service: 'patreon'});
|
const config = ServiceConfiguration.configurations.findOne({service: 'patreon'});
|
||||||
@@ -62,7 +61,7 @@ const updateIdentity = Meteor.wrapAsync(function(accessToken, userId, callback){
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
let identity = JSON.parse(body);
|
let identity = JSON.parse(body);
|
||||||
let membership = identity.included[0];
|
let membership = identity.included && identity.included[0];
|
||||||
let entitledAmount = membership && membership.attributes
|
let entitledAmount = membership && membership.attributes
|
||||||
.currently_entitled_amount_cents || 0;
|
.currently_entitled_amount_cents || 0;
|
||||||
writeEntitledCents(userId, entitledAmount);
|
writeEntitledCents(userId, entitledAmount);
|
||||||
@@ -85,7 +84,7 @@ const updatePatreonDetails = function(user){
|
|||||||
throw new Meteor.Error('no-patreon-access', 'Patreon access token not found for this user');
|
throw new Meteor.Error('no-patreon-access', 'Patreon access token not found for this user');
|
||||||
}
|
}
|
||||||
let accessToken = user.services.patreon.accessToken;
|
let accessToken = user.services.patreon.accessToken;
|
||||||
if (user.services.patreon.tokenExpiryDate < new Date()){
|
if (user.services.patreon.expiresAt < new Date()){
|
||||||
// Token expired, refresh it before continuing
|
// Token expired, refresh it before continuing
|
||||||
accessToken = refreshAccessToken(user.services.patreon.refreshToken, user._id);
|
accessToken = refreshAccessToken(user.services.patreon.refreshToken, user._id);
|
||||||
}
|
}
|
||||||
@@ -96,7 +95,7 @@ Meteor.methods({
|
|||||||
updateMyPatreonDetails(){
|
updateMyPatreonDetails(){
|
||||||
const userId = this.userId;
|
const userId = this.userId;
|
||||||
if (!userId) throw new Meteor.Error('not-logged-in', 'You must be logged in to update Patreon details');
|
if (!userId) throw new Meteor.Error('not-logged-in', 'You must be logged in to update Patreon details');
|
||||||
const user = Meteor.users.findOne(userId, {fields: {patreon: 1}});
|
const user = Meteor.users.findOne(userId, {fields: {services: 1}});
|
||||||
updatePatreonDetails(user);
|
updatePatreonDetails(user);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -113,9 +112,9 @@ const writePatreonToken = function(userId, {
|
|||||||
// Write
|
// Write
|
||||||
Meteor.users.update(userId, {
|
Meteor.users.update(userId, {
|
||||||
$set: {
|
$set: {
|
||||||
'patreon.accessToken': access_token,
|
'services.patreon.accessToken': access_token,
|
||||||
'patreon.refreshToken': refresh_token,
|
'services.patreon.refreshToken': refresh_token,
|
||||||
'patreon.tokenExpiryDate': expiryDate,
|
'services.patreon.expiresAt': expiryDate,
|
||||||
},
|
},
|
||||||
$unset: {
|
$unset: {
|
||||||
'patreon.error': 1,
|
'patreon.error': 1,
|
||||||
@@ -127,6 +126,7 @@ const writeEntitledCents = function(userId, amount){
|
|||||||
Meteor.users.update(userId, {
|
Meteor.users.update(userId, {
|
||||||
$set: {
|
$set: {
|
||||||
'services.patreon.entitledCents': amount,
|
'services.patreon.entitledCents': amount,
|
||||||
|
'services.patreon.lastUpdatedIdentity': new Date(),
|
||||||
},
|
},
|
||||||
$unset: {
|
$unset: {
|
||||||
'patreon.error': 1,
|
'patreon.error': 1,
|
||||||
@@ -134,4 +134,4 @@ const writeEntitledCents = function(userId, amount){
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export { updatePatreonDetails };
|
export default updatePatreonDetails;
|
||||||
12
app/imports/api/users/patreon/updatePatreonOnLogin.js
Normal file
12
app/imports/api/users/patreon/updatePatreonOnLogin.js
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import updatePatreonDetails from '/imports/api/users/patreon/updatePatreonDetails.js';
|
||||||
|
const ONE_DAY = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
Accounts.onLogin(({user}) => {
|
||||||
|
let patreon = user.services && user.services.patreon;
|
||||||
|
if (patreon){
|
||||||
|
const timeSinceIdentityUpdate = new Date() - patreon.lastUpdatedIdentity;
|
||||||
|
if (timeSinceIdentityUpdate > ONE_DAY){
|
||||||
|
updatePatreonDetails(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
const DAMAGE_TYPES = Object.freeze([
|
const DAMAGE_TYPES = Object.freeze([
|
||||||
"bludgeoning",
|
'healing',
|
||||||
"piercing",
|
'bludgeoning',
|
||||||
"slashing",
|
'piercing',
|
||||||
"acid",
|
'slashing',
|
||||||
"cold",
|
'acid',
|
||||||
"fire",
|
'cold',
|
||||||
"force",
|
'fire',
|
||||||
"lightning",
|
'force',
|
||||||
"necrotic",
|
'lightning',
|
||||||
"poison",
|
'necrotic',
|
||||||
"psychic",
|
'poison',
|
||||||
"radiant",
|
'psychic',
|
||||||
"thunder",
|
'radiant',
|
||||||
|
'thunder',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export default DAMAGE_TYPES;
|
export default DAMAGE_TYPES;
|
||||||
|
|||||||
7
app/imports/constants/INVENTORY_TAGS.js
Normal file
7
app/imports/constants/INVENTORY_TAGS.js
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
const INVENTORY_TAGS = Object.freeze({
|
||||||
|
inventory: 'inventory',
|
||||||
|
equipment: 'equipment',
|
||||||
|
carried: 'carried',
|
||||||
|
});
|
||||||
|
|
||||||
|
export default INVENTORY_TAGS;
|
||||||
@@ -1,44 +1,44 @@
|
|||||||
const PROPERTIES = Object.freeze({
|
const PROPERTIES = Object.freeze({
|
||||||
action: {
|
action: {
|
||||||
icon: 'offline_bolt',
|
icon: '$vuetify.icons.action',
|
||||||
name: 'Action'
|
name: 'Action'
|
||||||
},
|
},
|
||||||
adjustment: {
|
|
||||||
icon: 'warning',
|
|
||||||
name: 'Attribute damage'
|
|
||||||
},
|
|
||||||
attack: {
|
attack: {
|
||||||
icon: 'bolt',
|
icon: '$vuetify.icons.attack',
|
||||||
name: 'Attack'
|
name: 'Attack'
|
||||||
},
|
},
|
||||||
attribute: {
|
attribute: {
|
||||||
icon: 'donut_small',
|
icon: '$vuetify.icons.attribute',
|
||||||
name: 'Attribute'
|
name: 'Attribute'
|
||||||
},
|
},
|
||||||
|
adjustment: {
|
||||||
|
icon: '$vuetify.icons.attribute_damage',
|
||||||
|
name: 'Attribute damage'
|
||||||
|
},
|
||||||
buff: {
|
buff: {
|
||||||
icon: 'star',
|
icon: '$vuetify.icons.buff',
|
||||||
name: 'Buff'
|
name: 'Buff'
|
||||||
},
|
},
|
||||||
classLevel: {
|
classLevel: {
|
||||||
icon: 'school',
|
icon: '$vuetify.icons.class_level',
|
||||||
name: 'Class level'
|
name: 'Class level'
|
||||||
},
|
},
|
||||||
|
container: {
|
||||||
|
icon: 'work',
|
||||||
|
name: 'Container'
|
||||||
|
},
|
||||||
damage: {
|
damage: {
|
||||||
icon: 'report',
|
icon: '$vuetify.icons.damage',
|
||||||
name: 'Damage'
|
name: 'Damage'
|
||||||
},
|
},
|
||||||
damageMultiplier: {
|
damageMultiplier: {
|
||||||
icon: 'layers',
|
icon: '$vuetify.icons.damage_multiplier',
|
||||||
name: 'Damage multiplier'
|
name: 'Damage multiplier'
|
||||||
},
|
},
|
||||||
effect: {
|
effect: {
|
||||||
icon: 'show_chart',
|
icon: '$vuetify.icons.effect',
|
||||||
name: 'Effect'
|
name: 'Effect'
|
||||||
},
|
},
|
||||||
experience: {
|
|
||||||
icon: 'add',
|
|
||||||
name: 'Experience'
|
|
||||||
},
|
|
||||||
feature: {
|
feature: {
|
||||||
icon: 'subject',
|
icon: 'subject',
|
||||||
name: 'Feature'
|
name: 'Feature'
|
||||||
@@ -47,6 +47,10 @@ const PROPERTIES = Object.freeze({
|
|||||||
icon: 'folder',
|
icon: 'folder',
|
||||||
name: 'Folder'
|
name: 'Folder'
|
||||||
},
|
},
|
||||||
|
item: {
|
||||||
|
icon: '$vuetify.icons.item',
|
||||||
|
name: 'Item'
|
||||||
|
},
|
||||||
note: {
|
note: {
|
||||||
icon: 'note',
|
icon: 'note',
|
||||||
name: 'Note'
|
name: 'Note'
|
||||||
@@ -56,35 +60,35 @@ const PROPERTIES = Object.freeze({
|
|||||||
name: 'Proficiency'
|
name: 'Proficiency'
|
||||||
},
|
},
|
||||||
roll: {
|
roll: {
|
||||||
icon: 'flare',
|
icon: '$vuetify.icons.roll',
|
||||||
name: 'Roll'
|
name: 'Roll'
|
||||||
},
|
},
|
||||||
savingThrow: {
|
savingThrow: {
|
||||||
icon: 'all_out',
|
icon: '$vuetify.icons.saving_throw',
|
||||||
name: 'Saving throw'
|
name: 'Saving throw'
|
||||||
},
|
},
|
||||||
skill: {
|
skill: {
|
||||||
icon: 'check_box',
|
icon: '$vuetify.icons.skill',
|
||||||
name: 'Skill'
|
name: 'Skill'
|
||||||
},
|
},
|
||||||
|
propertySlot: {
|
||||||
|
icon: 'tab_unselected',
|
||||||
|
name: 'Slot'
|
||||||
|
},
|
||||||
|
slotFiller: {
|
||||||
|
icon: 'picture_in_picture',
|
||||||
|
name: 'Slot filler'
|
||||||
|
},
|
||||||
spellList: {
|
spellList: {
|
||||||
icon: 'list',
|
icon: '$vuetify.icons.spell_list',
|
||||||
name: 'Spell list'
|
name: 'Spell list'
|
||||||
},
|
},
|
||||||
spell: {
|
spell: {
|
||||||
icon: 'whatshot',
|
icon: '$vuetify.icons.spell',
|
||||||
name: 'Spell'
|
name: 'Spell'
|
||||||
},
|
},
|
||||||
container: {
|
|
||||||
icon: 'work',
|
|
||||||
name: 'Container'
|
|
||||||
},
|
|
||||||
item: {
|
|
||||||
icon: 'category',
|
|
||||||
name: 'Item'
|
|
||||||
},
|
|
||||||
toggle: {
|
toggle: {
|
||||||
icon: 'power_settings_new',
|
icon: '$vuetify.icons.toggle',
|
||||||
name: 'Toggle'
|
name: 'Toggle'
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
96
app/imports/constants/SVG_ICONS.js
Normal file
96
app/imports/constants/SVG_ICONS.js
Normal file
File diff suppressed because one or more lines are too long
16
app/imports/constants/VERSION.js
Normal file
16
app/imports/constants/VERSION.js
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
|
||||||
|
const VERSION = Meteor.isClient ?
|
||||||
|
'CLIENT' :
|
||||||
|
process.env.CONTAINER_VERSION || getVersionFromGit();
|
||||||
|
|
||||||
|
export default VERSION;
|
||||||
|
|
||||||
|
function getVersionFromGit(){
|
||||||
|
try {
|
||||||
|
return require('child_process')
|
||||||
|
.execSync('git rev-parse --short HEAD')
|
||||||
|
.toString().trim();
|
||||||
|
} catch (e){
|
||||||
|
return 'GIT_VERSION_FAIL'
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,20 @@
|
|||||||
import { create, all } from 'mathjs';
|
import { create, all } from 'mathjs';
|
||||||
|
|
||||||
const math = create(all);
|
const math = create(all);
|
||||||
math.import({
|
math.import({
|
||||||
'if': function(pred, a, b) {
|
'if': function(pred, a, b) {
|
||||||
return pred ? a : b;
|
return pred ? a : b;
|
||||||
|
},
|
||||||
|
'roll': function(number, diceSize){
|
||||||
|
let randomSrc = DDP.randomStream('diceRoller');
|
||||||
|
if (number > 100) throw 'Can only roll 100 dice at a time';
|
||||||
|
let rollTotal = 0;
|
||||||
|
let i, roll;
|
||||||
|
for (i = 0; i < number; i++){
|
||||||
|
roll = ~~(randomSrc.fraction() * diceSize) + 1
|
||||||
|
rollTotal += roll;
|
||||||
|
}
|
||||||
|
return rollTotal;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
// All of the compile functions are provided for use in compiling parse trees
|
|
||||||
// Every compile function takes in ParseNodes as arguements and returns a single
|
|
||||||
// ConstantNode as a result
|
|
||||||
|
|
||||||
const compileFunctions = {};
|
|
||||||
|
|
||||||
export compileFunctions;
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
export default function sum(inputNode) {
|
|
||||||
let node = inputNode.roll();
|
|
||||||
if (node.type === 'numberArray'){
|
|
||||||
let total = node.value.reduce((total, num) => total + num, 0);
|
|
||||||
return new ConstantNode({type: 'number', value: total});
|
|
||||||
} else {
|
|
||||||
let errors = node.errors || [];
|
|
||||||
errors.push(`Could not sum ${node.value}`);
|
|
||||||
return new ConstantNode({
|
|
||||||
type: 'uncompiledNode',
|
|
||||||
value: node.value,
|
|
||||||
errors,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
94
app/imports/parser/functions.js
Normal file
94
app/imports/parser/functions.js
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
export default {
|
||||||
|
'abs': {
|
||||||
|
comment: 'Returns the absolute value of a number',
|
||||||
|
examples: [
|
||||||
|
{input: 'abs(9)', result: '9'},
|
||||||
|
{input: 'abs(-3)', result: '3'},
|
||||||
|
],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.abs,
|
||||||
|
},
|
||||||
|
'sqrt': {
|
||||||
|
comment: 'Returns the square root of a number',
|
||||||
|
examples: [
|
||||||
|
{input: 'sqrt(16)', result: '4'},
|
||||||
|
{input: 'sqrt(10)', result: '3.1622776601683795'},
|
||||||
|
],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.sqrt,
|
||||||
|
},
|
||||||
|
'max': {
|
||||||
|
comment: 'Returns the largest of the given numbers',
|
||||||
|
examples: [{input: 'min(12, 6, 3, 168)', result: '168'}],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.max,
|
||||||
|
},
|
||||||
|
'min': {
|
||||||
|
comment: 'Returns the smallest of the given numbers',
|
||||||
|
examples: [{input: 'min(12, 6, 3, 168)', result: '3'}],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.min,
|
||||||
|
},
|
||||||
|
'round': {
|
||||||
|
comment: 'Returns the value of a number rounded to the nearest integer',
|
||||||
|
examples: [
|
||||||
|
{input: 'round(5.95)', result: '6'},
|
||||||
|
{input: 'round(5.5)', result: '6'},
|
||||||
|
{input: 'round(5.05)', result: '5'},
|
||||||
|
],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.round,
|
||||||
|
},
|
||||||
|
'floor': {
|
||||||
|
comment: 'Rounds a number down to the next smallest integer',
|
||||||
|
examples: [
|
||||||
|
{input: 'floor(5.95)', result: '5'},
|
||||||
|
{input: 'floor(5.05)', result: '5'},
|
||||||
|
{input: 'floor(5)', result: '5'},
|
||||||
|
{input: 'floor(-5.5)', result: '-6'},
|
||||||
|
],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.floor,
|
||||||
|
},
|
||||||
|
'ceil': {
|
||||||
|
comment: 'Rounds a number up to the next largest integer',
|
||||||
|
examples: [
|
||||||
|
{input: 'ceil(5.95)', result: '6'},
|
||||||
|
{input: 'ceil(5.05)', result: '6'},
|
||||||
|
{input: 'ceil(5)', result: '5'},
|
||||||
|
{input: 'ceil(-5.5)', result: '-5'},
|
||||||
|
],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.ceil,
|
||||||
|
},
|
||||||
|
'trunc': {
|
||||||
|
comment: 'Returns the integer part of a number by removing any fractional digits',
|
||||||
|
examples: [
|
||||||
|
{input: 'trunc(5.95)', result: '5'},
|
||||||
|
{input: 'trunc(5.05)', result: '5'},
|
||||||
|
{input: 'trunc(5)', result: '5'},
|
||||||
|
{input: 'trunc(-5.5)', result: '-5'},
|
||||||
|
],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.trunc,
|
||||||
|
},
|
||||||
|
'sign': {
|
||||||
|
comment: 'Returns either a positive or negative 1, indicating the sign of a number, or zero',
|
||||||
|
examples: [
|
||||||
|
{input: 'sign(-3)', result: '-1'},
|
||||||
|
{input: 'sign(3)', result: '1'},
|
||||||
|
{input: 'sign(0)', result: '0'},
|
||||||
|
],
|
||||||
|
argumentType: 'number',
|
||||||
|
resultType: 'number',
|
||||||
|
fn: Math.sign,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,19 @@
|
|||||||
// http://github.com/Hardmath123/nearley
|
// http://github.com/Hardmath123/nearley
|
||||||
function id(x) { return x[0]; }
|
function id(x) { return x[0]; }
|
||||||
|
|
||||||
|
import AccessorNode from '/imports/parser/parseTree/AccessorNode.js';
|
||||||
|
import ArrayNode from '/imports/parser/parseTree/ArrayNode.js';
|
||||||
import CallNode from '/imports/parser/parseTree/CallNode.js';
|
import CallNode from '/imports/parser/parseTree/CallNode.js';
|
||||||
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
||||||
import IfNode from '/imports/parser/parseTree/IfNode.js';
|
import IfNode from '/imports/parser/parseTree/IfNode.js';
|
||||||
|
import IndexNode from '/imports/parser/parseTree/IndexNode.js';
|
||||||
import OperatorNode from '/imports/parser/parseTree/OperatorNode.js';
|
import OperatorNode from '/imports/parser/parseTree/OperatorNode.js';
|
||||||
import SymbolNode from '/imports/parser/parseTree/SymbolNode.js';
|
import ParenthesisNode from '/imports/parser/parseTree/ParenthesisNode.js';
|
||||||
|
import RollNode from '/imports/parser/parseTree/RollNode.js';
|
||||||
|
import SymbolNode from '/imports/parser/parseTree/SymbolNode.js';
|
||||||
|
import UnaryOperatorNode from '/imports/parser/parseTree/UnaryOperatorNode.js';
|
||||||
|
import NotOperatorNode from '/imports/parser/parseTree/NotOperatorNode.js';
|
||||||
|
|
||||||
import moo from 'moo';
|
import moo from 'moo';
|
||||||
|
|
||||||
const lexer = moo.compile({
|
const lexer = moo.compile({
|
||||||
@@ -16,26 +24,30 @@ function id(x) { return x[0]; }
|
|||||||
value: s => s.slice(1, -1),
|
value: s => s.slice(1, -1),
|
||||||
},
|
},
|
||||||
name: {
|
name: {
|
||||||
match: /[a-zA-Z]+\w*?/,
|
match: /[a-zA-Z_]*[a-ce-zA-Z_][a-zA-Z0-9_]*/,
|
||||||
type: moo.keywords({
|
type: moo.keywords({
|
||||||
'keywords': ['if', 'else', 'd'],
|
'keywords': ['true', 'false'],
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
space: {
|
space: {
|
||||||
match: /\s+/,
|
match: /\s+/,
|
||||||
lineBreaks: true,
|
lineBreaks: true,
|
||||||
},
|
},
|
||||||
separators: [',', '.'],
|
diceOperator: ['d'],
|
||||||
|
separator: [',', ';'],
|
||||||
|
period: ['.'],
|
||||||
|
ifOperator: ['?'],
|
||||||
|
elseOperator: [':'],
|
||||||
multiplicativeOperator: ['*', '/'],
|
multiplicativeOperator: ['*', '/'],
|
||||||
exponentOperator: ['^'],
|
exponentOperator: ['^'],
|
||||||
additiveOperator: ['+', '-'],
|
additiveOperator: ['+', '-'],
|
||||||
unaryOperator: ['-'],
|
|
||||||
andOperator: ['&', '&&'],
|
andOperator: ['&', '&&'],
|
||||||
orOperator: ['|', '||'],
|
orOperator: ['|', '||'],
|
||||||
stringDelimiters: ['\"', '\''],
|
stringDelimiters: ['\"', '\''],
|
||||||
equalityOperator: ['=', '==', '===', '!=', '!=='],
|
equalityOperator: ['=', '==', '===', '!=', '!=='],
|
||||||
|
notOperator: ['!'],
|
||||||
relationalOperator: ['>', '<', '>=', '<='],
|
relationalOperator: ['>', '<', '>=', '<='],
|
||||||
brackets: ['(', ')', '{', '}'],
|
brackets: ['(', ')', '{', '}', '[', ']'],
|
||||||
});
|
});
|
||||||
|
|
||||||
function nuller() { return null; }
|
function nuller() { return null; }
|
||||||
@@ -49,50 +61,78 @@ function id(x) { return x[0]; }
|
|||||||
}
|
}
|
||||||
let Lexer = lexer;
|
let Lexer = lexer;
|
||||||
let ParserRules = [
|
let ParserRules = [
|
||||||
{"name": "ifStatement", "symbols": [{"literal":"if"}, "_", {"literal":"("}, "_", "expression", "_", {"literal":")"}, "_", "ifStatement", "_", {"literal":"else"}, "_", "ifStatement"], "postprocess":
|
{"name": "spacedExpression", "symbols": ["_", "expression", "_"], "postprocess": d => d[1]},
|
||||||
d => new IfNode({condition: d[4], consequent: d[8], alternative: d[12]})
|
{"name": "expression", "symbols": ["ifStatement"], "postprocess": id},
|
||||||
|
{"name": "ifStatement", "symbols": ["orExpression", "_", (lexer.has("ifOperator") ? {type: "ifOperator"} : ifOperator), "_", "orExpression", "_", (lexer.has("elseOperator") ? {type: "elseOperator"} : elseOperator), "_", "ifStatement"], "postprocess":
|
||||||
|
d => new IfNode({condition: d[0], consequent: d[4], alternative: d[8]})
|
||||||
},
|
},
|
||||||
{"name": "ifStatement", "symbols": ["expression"], "postprocess": id},
|
{"name": "ifStatement", "symbols": ["orExpression"], "postprocess": id},
|
||||||
{"name": "expression", "symbols": ["equalityExpression"], "postprocess": d => d[0]},
|
|
||||||
{"name": "equalityExpression", "symbols": ["equalityExpression", "_", (lexer.has("equalityOperator") ? {type: "equalityOperator"} : equalityOperator), "_", "relationalExpression"], "postprocess": d => operator(d, 'equality')},
|
|
||||||
{"name": "equalityExpression", "symbols": ["relationalExpression"], "postprocess": id},
|
|
||||||
{"name": "relationalExpression", "symbols": ["relationalExpression", "_", (lexer.has("relationalOperator") ? {type: "relationalOperator"} : relationalOperator), "_", "orExpression"], "postprocess": d => operator(d, 'relation')},
|
|
||||||
{"name": "relationalExpression", "symbols": ["orExpression"], "postprocess": id},
|
|
||||||
{"name": "orExpression", "symbols": ["orExpression", "_", (lexer.has("orOperator") ? {type: "orOperator"} : orOperator), "_", "andExpression"], "postprocess": d => operator(d, 'or')},
|
{"name": "orExpression", "symbols": ["orExpression", "_", (lexer.has("orOperator") ? {type: "orOperator"} : orOperator), "_", "andExpression"], "postprocess": d => operator(d, 'or')},
|
||||||
{"name": "orExpression", "symbols": ["andExpression"], "postprocess": id},
|
{"name": "orExpression", "symbols": ["andExpression"], "postprocess": id},
|
||||||
{"name": "andExpression", "symbols": ["andExpression", "_", (lexer.has("andOperator") ? {type: "andOperator"} : andOperator), "_", "additiveExpression"], "postprocess": d => operator(d, 'and')},
|
{"name": "andExpression", "symbols": ["andExpression", "_", (lexer.has("andOperator") ? {type: "andOperator"} : andOperator), "_", "equalityExpression"], "postprocess": d => operator(d, 'and')},
|
||||||
{"name": "andExpression", "symbols": ["additiveExpression"], "postprocess": id},
|
{"name": "andExpression", "symbols": ["equalityExpression"], "postprocess": id},
|
||||||
|
{"name": "equalityExpression", "symbols": ["equalityExpression", "_", (lexer.has("equalityOperator") ? {type: "equalityOperator"} : equalityOperator), "_", "relationalExpression"], "postprocess": d => operator(d, 'equality')},
|
||||||
|
{"name": "equalityExpression", "symbols": ["relationalExpression"], "postprocess": id},
|
||||||
|
{"name": "relationalExpression", "symbols": ["relationalExpression", "_", (lexer.has("relationalOperator") ? {type: "relationalOperator"} : relationalOperator), "_", "additiveExpression"], "postprocess": d => operator(d, 'relation')},
|
||||||
|
{"name": "relationalExpression", "symbols": ["additiveExpression"], "postprocess": id},
|
||||||
{"name": "additiveExpression", "symbols": ["additiveExpression", "_", (lexer.has("additiveOperator") ? {type: "additiveOperator"} : additiveOperator), "_", "multiplicativeExpression"], "postprocess": d => operator(d, 'add')},
|
{"name": "additiveExpression", "symbols": ["additiveExpression", "_", (lexer.has("additiveOperator") ? {type: "additiveOperator"} : additiveOperator), "_", "multiplicativeExpression"], "postprocess": d => operator(d, 'add')},
|
||||||
{"name": "additiveExpression", "symbols": ["multiplicativeExpression"], "postprocess": id},
|
{"name": "additiveExpression", "symbols": ["multiplicativeExpression"], "postprocess": id},
|
||||||
{"name": "multiplicativeExpression", "symbols": ["multiplicativeExpression", "_", (lexer.has("multiplicativeOperator") ? {type: "multiplicativeOperator"} : multiplicativeOperator), "_", "rollExpression"], "postprocess": d => operator(d, 'multiply')},
|
{"name": "multiplicativeExpression", "symbols": ["multiplicativeExpression", "_", (lexer.has("multiplicativeOperator") ? {type: "multiplicativeOperator"} : multiplicativeOperator), "_", "rollExpression"], "postprocess": d => operator(d, 'multiply')},
|
||||||
{"name": "multiplicativeExpression", "symbols": ["rollExpression"], "postprocess": id},
|
{"name": "multiplicativeExpression", "symbols": ["rollExpression"], "postprocess": id},
|
||||||
{"name": "rollExpression", "symbols": ["rollExpression", "_", {"literal":"d"}, "_", "exponentExpression"], "postprocess": d => operator(d, 'roll')},
|
{"name": "rollExpression", "symbols": ["rollExpression", "_", (lexer.has("diceOperator") ? {type: "diceOperator"} : diceOperator), "_", "exponentExpression"], "postprocess": d => new RollNode({left: d[0], right: d[4]})},
|
||||||
{"name": "rollExpression", "symbols": ["exponentExpression"], "postprocess": id},
|
{"name": "rollExpression", "symbols": ["singleRollExpression"], "postprocess": id},
|
||||||
|
{"name": "singleRollExpression", "symbols": [{"literal":"d"}, "_", "singleRollExpression"], "postprocess": d => new RollNode({left: new ConstantNode({value: 1, type: 'number'}), right: d[2]})},
|
||||||
|
{"name": "singleRollExpression", "symbols": ["exponentExpression"], "postprocess": id},
|
||||||
{"name": "exponentExpression", "symbols": ["callExpression", "_", (lexer.has("exponentOperator") ? {type: "exponentOperator"} : exponentOperator), "_", "exponentExpression"], "postprocess": d => operator(d, 'exponent')},
|
{"name": "exponentExpression", "symbols": ["callExpression", "_", (lexer.has("exponentOperator") ? {type: "exponentOperator"} : exponentOperator), "_", "exponentExpression"], "postprocess": d => operator(d, 'exponent')},
|
||||||
{"name": "exponentExpression", "symbols": ["callExpression"], "postprocess": id},
|
{"name": "exponentExpression", "symbols": ["unaryExpression"], "postprocess": id},
|
||||||
|
{"name": "unaryExpression", "symbols": [(lexer.has("additiveOperator") ? {type: "additiveOperator"} : additiveOperator), "_", "unaryExpression"], "postprocess": d => new UnaryOperatorNode({operator: d[0].value, right: d[2]})},
|
||||||
|
{"name": "unaryExpression", "symbols": ["notExpression"], "postprocess": id},
|
||||||
|
{"name": "notExpression", "symbols": [(lexer.has("notOperator") ? {type: "notOperator"} : notOperator), "_", "notExpression"], "postprocess": d => new NotOperatorNode({right: d[2]})},
|
||||||
|
{"name": "notExpression", "symbols": ["callExpression"], "postprocess": id},
|
||||||
{"name": "callExpression", "symbols": ["name", "_", "arguments"], "postprocess":
|
{"name": "callExpression", "symbols": ["name", "_", "arguments"], "postprocess":
|
||||||
d => new CallNode ({type: "call", fn: d[0], arguments: d[2]})
|
d => new CallNode ({functionName: d[0].name, args: d[2]})
|
||||||
},
|
},
|
||||||
{"name": "callExpression", "symbols": ["parenthesizedExpression"], "postprocess": id},
|
{"name": "callExpression", "symbols": ["indexExpression"], "postprocess": id},
|
||||||
{"name": "arguments$ebnf$1$subexpression$1", "symbols": ["expression"], "postprocess": d => d[0]},
|
{"name": "arguments$ebnf$1$subexpression$1", "symbols": ["expression"], "postprocess": d => d[0]},
|
||||||
{"name": "arguments$ebnf$1", "symbols": ["arguments$ebnf$1$subexpression$1"], "postprocess": id},
|
{"name": "arguments$ebnf$1", "symbols": ["arguments$ebnf$1$subexpression$1"], "postprocess": id},
|
||||||
{"name": "arguments$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},
|
{"name": "arguments$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},
|
||||||
{"name": "arguments$ebnf$2", "symbols": []},
|
{"name": "arguments$ebnf$2", "symbols": []},
|
||||||
{"name": "arguments$ebnf$2$subexpression$1", "symbols": ["_", {"literal":","}, "_", "expression"], "postprocess": d => d[3]},
|
{"name": "arguments$ebnf$2$subexpression$1", "symbols": ["_", (lexer.has("separator") ? {type: "separator"} : separator), "_", "expression"], "postprocess": d => d[3]},
|
||||||
{"name": "arguments$ebnf$2", "symbols": ["arguments$ebnf$2", "arguments$ebnf$2$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},
|
{"name": "arguments$ebnf$2", "symbols": ["arguments$ebnf$2", "arguments$ebnf$2$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},
|
||||||
{"name": "arguments", "symbols": [{"literal":"("}, "_", "arguments$ebnf$1", "arguments$ebnf$2", "_", {"literal":")"}], "postprocess":
|
{"name": "arguments", "symbols": [{"literal":"("}, "_", "arguments$ebnf$1", "arguments$ebnf$2", "_", {"literal":")"}], "postprocess":
|
||||||
d => [d[2], ...d[3]]
|
d => [d[2], ...d[3]]
|
||||||
|
},
|
||||||
|
{"name": "indexExpression", "symbols": ["arrayExpression", {"literal":"["}, "_", "expression", "_", {"literal":"]"}], "postprocess": d => new IndexNode ({array: d[0], index: d[3]})},
|
||||||
|
{"name": "indexExpression", "symbols": ["arrayExpression"], "postprocess": id},
|
||||||
|
{"name": "arrayExpression$ebnf$1$subexpression$1", "symbols": ["expression"], "postprocess": d => d[0]},
|
||||||
|
{"name": "arrayExpression$ebnf$1", "symbols": ["arrayExpression$ebnf$1$subexpression$1"], "postprocess": id},
|
||||||
|
{"name": "arrayExpression$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},
|
||||||
|
{"name": "arrayExpression$ebnf$2", "symbols": []},
|
||||||
|
{"name": "arrayExpression$ebnf$2$subexpression$1", "symbols": ["_", (lexer.has("separator") ? {type: "separator"} : separator), "_", "expression"], "postprocess": d => d[3]},
|
||||||
|
{"name": "arrayExpression$ebnf$2", "symbols": ["arrayExpression$ebnf$2", "arrayExpression$ebnf$2$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},
|
||||||
|
{"name": "arrayExpression", "symbols": [{"literal":"["}, "_", "arrayExpression$ebnf$1", "arrayExpression$ebnf$2", "_", {"literal":"]"}], "postprocess":
|
||||||
|
d => new ArrayNode({values: d[2] ? [d[2], ...d[3]] : []})
|
||||||
},
|
},
|
||||||
{"name": "parenthesizedExpression", "symbols": [{"literal":"("}, "_", "expression", "_", {"literal":")"}], "postprocess": d => d[2]},
|
{"name": "arrayExpression", "symbols": ["parenthesizedExpression"], "postprocess": id},
|
||||||
{"name": "parenthesizedExpression", "symbols": ["valueExpression"], "postprocess": id},
|
{"name": "parenthesizedExpression", "symbols": [{"literal":"("}, "_", "expression", "_", {"literal":")"}], "postprocess": d => new ParenthesisNode({content: d[2]})},
|
||||||
|
{"name": "parenthesizedExpression", "symbols": ["accessorExpression"], "postprocess": id},
|
||||||
|
{"name": "accessorExpression$ebnf$1$subexpression$1", "symbols": [{"literal":"."}, "name"], "postprocess": d => d[1].name},
|
||||||
|
{"name": "accessorExpression$ebnf$1", "symbols": ["accessorExpression$ebnf$1$subexpression$1"]},
|
||||||
|
{"name": "accessorExpression$ebnf$1$subexpression$2", "symbols": [{"literal":"."}, "name"], "postprocess": d => d[1].name},
|
||||||
|
{"name": "accessorExpression$ebnf$1", "symbols": ["accessorExpression$ebnf$1", "accessorExpression$ebnf$1$subexpression$2"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},
|
||||||
|
{"name": "accessorExpression", "symbols": ["name", "accessorExpression$ebnf$1"], "postprocess": d=> new AccessorNode({name: d[0], path: d[1]})},
|
||||||
|
{"name": "accessorExpression", "symbols": ["valueExpression"], "postprocess": id},
|
||||||
{"name": "valueExpression", "symbols": ["name"], "postprocess": id},
|
{"name": "valueExpression", "symbols": ["name"], "postprocess": id},
|
||||||
{"name": "valueExpression", "symbols": ["number"], "postprocess": id},
|
{"name": "valueExpression", "symbols": ["number"], "postprocess": id},
|
||||||
{"name": "valueExpression", "symbols": ["string"], "postprocess": id},
|
{"name": "valueExpression", "symbols": ["string"], "postprocess": id},
|
||||||
{"name": "number", "symbols": [(lexer.has("number") ? {type: "number"} : number)], "postprocess": d => new ConstantNode({value: d[0].value, type: 'number'})},
|
{"name": "valueExpression", "symbols": ["boolean"], "postprocess": id},
|
||||||
|
{"name": "number", "symbols": [(lexer.has("number") ? {type: "number"} : number)], "postprocess": d => new ConstantNode({value: +d[0].value, type: 'number'})},
|
||||||
{"name": "name", "symbols": [(lexer.has("name") ? {type: "name"} : name)], "postprocess": d => new SymbolNode({name: d[0].value})},
|
{"name": "name", "symbols": [(lexer.has("name") ? {type: "name"} : name)], "postprocess": d => new SymbolNode({name: d[0].value})},
|
||||||
{"name": "string", "symbols": [(lexer.has("string") ? {type: "string"} : string)], "postprocess": d => new ConstantNode({value: d[0].value, type: 'string'})},
|
{"name": "string", "symbols": [(lexer.has("string") ? {type: "string"} : string)], "postprocess": d => new ConstantNode({value: d[0].value, type: 'string'})},
|
||||||
|
{"name": "boolean", "symbols": [{"literal":"true"}], "postprocess": d => new ConstantNode({value: true, type: 'boolean'})},
|
||||||
|
{"name": "boolean", "symbols": [{"literal":"false"}], "postprocess": d => new ConstantNode({value: false, type: 'boolean'})},
|
||||||
{"name": "_", "symbols": []},
|
{"name": "_", "symbols": []},
|
||||||
{"name": "_", "symbols": [(lexer.has("space") ? {type: "space"} : space)], "postprocess": nuller}
|
{"name": "_", "symbols": [(lexer.has("space") ? {type: "space"} : space)], "postprocess": nuller}
|
||||||
];
|
];
|
||||||
let ParserStart = "ifStatement";
|
let ParserStart = "spacedExpression";
|
||||||
export default { Lexer, ParserRules, ParserStart };
|
export default { Lexer, ParserRules, ParserStart };
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
@preprocessor esmodule
|
@preprocessor esmodule
|
||||||
@{%
|
@{%
|
||||||
|
import AccessorNode from '/imports/parser/parseTree/AccessorNode.js';
|
||||||
|
import ArrayNode from '/imports/parser/parseTree/ArrayNode.js';
|
||||||
import CallNode from '/imports/parser/parseTree/CallNode.js';
|
import CallNode from '/imports/parser/parseTree/CallNode.js';
|
||||||
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
||||||
import IfNode from '/imports/parser/parseTree/IfNode.js';
|
import IfNode from '/imports/parser/parseTree/IfNode.js';
|
||||||
|
import IndexNode from '/imports/parser/parseTree/IndexNode.js';
|
||||||
import OperatorNode from '/imports/parser/parseTree/OperatorNode.js';
|
import OperatorNode from '/imports/parser/parseTree/OperatorNode.js';
|
||||||
import SymbolNode from '/imports/parser/parseTree/SymbolNode.js';
|
import ParenthesisNode from '/imports/parser/parseTree/ParenthesisNode.js';
|
||||||
|
import RollNode from '/imports/parser/parseTree/RollNode.js';
|
||||||
|
import SymbolNode from '/imports/parser/parseTree/SymbolNode.js';
|
||||||
|
import UnaryOperatorNode from '/imports/parser/parseTree/UnaryOperatorNode.js';
|
||||||
|
import NotOperatorNode from '/imports/parser/parseTree/NotOperatorNode.js';
|
||||||
|
|
||||||
import moo from 'moo';
|
import moo from 'moo';
|
||||||
|
|
||||||
const lexer = moo.compile({
|
const lexer = moo.compile({
|
||||||
@@ -14,26 +22,30 @@
|
|||||||
value: s => s.slice(1, -1),
|
value: s => s.slice(1, -1),
|
||||||
},
|
},
|
||||||
name: {
|
name: {
|
||||||
match: /[a-zA-Z]+\w*?/,
|
match: /[a-zA-Z_]*[a-ce-zA-Z_][a-zA-Z0-9_]*/,
|
||||||
type: moo.keywords({
|
type: moo.keywords({
|
||||||
'keywords': ['if', 'else', 'd'],
|
'keywords': ['true', 'false'],
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
space: {
|
space: {
|
||||||
match: /\s+/,
|
match: /\s+/,
|
||||||
lineBreaks: true,
|
lineBreaks: true,
|
||||||
},
|
},
|
||||||
separators: [',', '.'],
|
diceOperator: ['d'],
|
||||||
|
separator: [',', ';'],
|
||||||
|
period: ['.'],
|
||||||
|
ifOperator: ['?'],
|
||||||
|
elseOperator: [':'],
|
||||||
multiplicativeOperator: ['*', '/'],
|
multiplicativeOperator: ['*', '/'],
|
||||||
exponentOperator: ['^'],
|
exponentOperator: ['^'],
|
||||||
additiveOperator: ['+', '-'],
|
additiveOperator: ['+', '-'],
|
||||||
unaryOperator: ['-'],
|
|
||||||
andOperator: ['&', '&&'],
|
andOperator: ['&', '&&'],
|
||||||
orOperator: ['|', '||'],
|
orOperator: ['|', '||'],
|
||||||
stringDelimiters: ['\"', '\''],
|
stringDelimiters: ['\"', '\''],
|
||||||
equalityOperator: ['=', '==', '===', '!=', '!=='],
|
equalityOperator: ['=', '==', '===', '!=', '!=='],
|
||||||
|
notOperator: ['!'],
|
||||||
relationalOperator: ['>', '<', '>=', '<='],
|
relationalOperator: ['>', '<', '>=', '<='],
|
||||||
brackets: ['(', ')', '{', '}'],
|
brackets: ['(', ')', '{', '}', '[', ']'],
|
||||||
});
|
});
|
||||||
|
|
||||||
function nuller() { return null; }
|
function nuller() { return null; }
|
||||||
@@ -50,21 +62,16 @@
|
|||||||
# Use the Moo lexer
|
# Use the Moo lexer
|
||||||
@lexer lexer
|
@lexer lexer
|
||||||
|
|
||||||
ifStatement ->
|
spacedExpression ->
|
||||||
"if" _ "(" _ expression _ ")" _ ifStatement _ "else" _ ifStatement {%
|
_ expression _ {% d => d[1] %}
|
||||||
d => new IfNode({condition: d[4], consequent: d[8], alternative: d[12]})
|
|
||||||
%}
|
|
||||||
| expression {% id %}
|
|
||||||
|
|
||||||
expression ->
|
expression ->
|
||||||
equalityExpression {% d => d[0] %}
|
ifStatement {% id %}
|
||||||
|
|
||||||
equalityExpression ->
|
ifStatement ->
|
||||||
equalityExpression _ %equalityOperator _ relationalExpression {% d => operator(d, 'equality') %}
|
orExpression _ %ifOperator _ orExpression _ %elseOperator _ ifStatement {%
|
||||||
| relationalExpression {% id %}
|
d => new IfNode({condition: d[0], consequent: d[4], alternative: d[8]})
|
||||||
|
%}
|
||||||
relationalExpression ->
|
|
||||||
relationalExpression _ %relationalOperator _ orExpression {% d => operator(d, 'relation') %}
|
|
||||||
| orExpression {% id %}
|
| orExpression {% id %}
|
||||||
|
|
||||||
orExpression ->
|
orExpression ->
|
||||||
@@ -72,7 +79,15 @@ orExpression ->
|
|||||||
| andExpression {% id %}
|
| andExpression {% id %}
|
||||||
|
|
||||||
andExpression ->
|
andExpression ->
|
||||||
andExpression _ %andOperator _ additiveExpression {% d => operator(d, 'and') %}
|
andExpression _ %andOperator _ equalityExpression {% d => operator(d, 'and') %}
|
||||||
|
| equalityExpression {% id %}
|
||||||
|
|
||||||
|
equalityExpression ->
|
||||||
|
equalityExpression _ %equalityOperator _ relationalExpression {% d => operator(d, 'equality') %}
|
||||||
|
| relationalExpression {% id %}
|
||||||
|
|
||||||
|
relationalExpression ->
|
||||||
|
relationalExpression _ %relationalOperator _ additiveExpression {% d => operator(d, 'relation') %}
|
||||||
| additiveExpression {% id %}
|
| additiveExpression {% id %}
|
||||||
|
|
||||||
additiveExpression ->
|
additiveExpression ->
|
||||||
@@ -84,36 +99,63 @@ multiplicativeExpression ->
|
|||||||
| rollExpression {% id %}
|
| rollExpression {% id %}
|
||||||
|
|
||||||
rollExpression ->
|
rollExpression ->
|
||||||
rollExpression _ "d" _ exponentExpression {% d => operator(d, 'roll') %}
|
rollExpression _ %diceOperator _ exponentExpression {% d => new RollNode({left: d[0], right: d[4]}) %}
|
||||||
|
| singleRollExpression {% id %}
|
||||||
|
|
||||||
|
singleRollExpression ->
|
||||||
|
"d" _ singleRollExpression {% d => new RollNode({left: new ConstantNode({value: 1, type: 'number'}), right: d[2]}) %}
|
||||||
| exponentExpression {% id %}
|
| exponentExpression {% id %}
|
||||||
|
|
||||||
exponentExpression ->
|
exponentExpression ->
|
||||||
callExpression _ %exponentOperator _ exponentExpression {% d => operator(d, 'exponent') %}
|
callExpression _ %exponentOperator _ exponentExpression {% d => operator(d, 'exponent') %}
|
||||||
|
| unaryExpression {% id %}
|
||||||
|
|
||||||
|
unaryExpression ->
|
||||||
|
%additiveOperator _ unaryExpression {% d => new UnaryOperatorNode({operator: d[0].value, right: d[2]})%}
|
||||||
|
| notExpression {% id %}
|
||||||
|
|
||||||
|
notExpression ->
|
||||||
|
%notOperator _ notExpression {% d => new NotOperatorNode({right: d[2]})%}
|
||||||
| callExpression {% id %}
|
| callExpression {% id %}
|
||||||
|
|
||||||
callExpression ->
|
callExpression ->
|
||||||
name _ arguments {%
|
name _ arguments {%
|
||||||
d => new CallNode ({type: "call", fn: d[0], arguments: d[2]})
|
d => new CallNode ({functionName: d[0].name, args: d[2]})
|
||||||
|
%}
|
||||||
|
| indexExpression {% id %}
|
||||||
|
|
||||||
|
arguments ->
|
||||||
|
"(" _ (expression {% d => d[0] %}):? ( _ %separator _ expression {% d => d[3] %} ):* _ ")" {%
|
||||||
|
d => [d[2], ...d[3]]
|
||||||
|
%}
|
||||||
|
|
||||||
|
indexExpression ->
|
||||||
|
arrayExpression "[" _ expression _ "]" {% d => new IndexNode ({array: d[0], index: d[3]}) %}
|
||||||
|
| arrayExpression {% id %}
|
||||||
|
|
||||||
|
arrayExpression ->
|
||||||
|
"[" _ (expression {% d => d[0] %}):? ( _ %separator _ expression {% d => d[3] %} ):* _ "]" {%
|
||||||
|
d => new ArrayNode({values: d[2] ? [d[2], ...d[3]] : []})
|
||||||
%}
|
%}
|
||||||
| parenthesizedExpression {% id %}
|
| parenthesizedExpression {% id %}
|
||||||
|
|
||||||
arguments ->
|
|
||||||
"(" _ (expression {% d => d[0] %}):? ( _ "," _ expression {% d => d[3] %} ):* _ ")" {%
|
|
||||||
d => [d[2], ...d[3]]
|
|
||||||
%}
|
|
||||||
|
|
||||||
parenthesizedExpression ->
|
parenthesizedExpression ->
|
||||||
"(" _ expression _ ")" {% d => d[2] %}
|
"(" _ expression _ ")" {% d => new ParenthesisNode({content: d[2]}) %}
|
||||||
|
| accessorExpression {% id %}
|
||||||
|
|
||||||
|
accessorExpression ->
|
||||||
|
name ( "." name {% d => d[1].name %} ):+ {% d=> new AccessorNode({name: d[0], path: d[1]}) %}
|
||||||
| valueExpression {% id %}
|
| valueExpression {% id %}
|
||||||
|
|
||||||
valueExpression ->
|
valueExpression ->
|
||||||
name {% id %}
|
name {% id %}
|
||||||
| number {% id %}
|
| number {% id %}
|
||||||
| string {% id %}
|
| string {% id %}
|
||||||
|
| boolean {% id %}
|
||||||
|
|
||||||
# A number or a function of a number
|
# A number or a function of a number
|
||||||
number ->
|
number ->
|
||||||
%number {% d => new ConstantNode({value: d[0].value, type: 'number'}) %}
|
%number {% d => new ConstantNode({value: +d[0].value, type: 'number'}) %}
|
||||||
|
|
||||||
name ->
|
name ->
|
||||||
%name {% d => new SymbolNode({name: d[0].value}) %}
|
%name {% d => new SymbolNode({name: d[0].value}) %}
|
||||||
@@ -121,6 +163,10 @@ name ->
|
|||||||
string ->
|
string ->
|
||||||
%string {% d => new ConstantNode({value: d[0].value, type: 'string'}) %}
|
%string {% d => new ConstantNode({value: d[0].value, type: 'string'}) %}
|
||||||
|
|
||||||
|
boolean ->
|
||||||
|
"true" {% d => new ConstantNode({value: true, type: 'boolean'}) %}
|
||||||
|
| "false" {% d => new ConstantNode({value: false, type: 'boolean'}) %}
|
||||||
|
|
||||||
_ ->
|
_ ->
|
||||||
null
|
null
|
||||||
| %space {% nuller %}
|
| %space {% nuller %}
|
||||||
|
|||||||
47
app/imports/parser/parseTree/AccessorNode.js
Normal file
47
app/imports/parser/parseTree/AccessorNode.js
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import ParseNode from '/imports/parser/parseTree/ParseNode.js';
|
||||||
|
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
||||||
|
|
||||||
|
export default class AccessorNode extends ParseNode {
|
||||||
|
constructor({name, path}) {
|
||||||
|
super(...arguments);
|
||||||
|
this.name = name;
|
||||||
|
this.path = path;
|
||||||
|
}
|
||||||
|
compile(scope){
|
||||||
|
let value = scope && scope[this.name];
|
||||||
|
// For objects, get their value
|
||||||
|
this.path.forEach(name => {
|
||||||
|
if (value === undefined) return;
|
||||||
|
value = value[name];
|
||||||
|
});
|
||||||
|
let type = typeof value;
|
||||||
|
if (type === 'string' || type === 'number' || type === 'boolean'){
|
||||||
|
return new ConstantNode({value, type, previousNodes: [this]});
|
||||||
|
} else if (type === 'undefined'){
|
||||||
|
return new AccessorNode({
|
||||||
|
name: this.name,
|
||||||
|
path: this.path,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
throw new Meteor.Error(`Unexpected case: ${this.name} resolved to ${value}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reduce(scope, context){
|
||||||
|
let result = this.compile(scope, context);
|
||||||
|
if (result instanceof AccessorNode){
|
||||||
|
if (context) context.storeError({
|
||||||
|
type: 'info',
|
||||||
|
message: `${result.toString()} not found, set to 0`
|
||||||
|
});
|
||||||
|
return new ConstantNode({
|
||||||
|
type: 'number',
|
||||||
|
value: 0,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toString(){
|
||||||
|
return `${this.name}.${this.path.join('.')}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
19
app/imports/parser/parseTree/ArrayNode.js
Normal file
19
app/imports/parser/parseTree/ArrayNode.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import ParseNode from '/imports/parser/parseTree/ParseNode.js';
|
||||||
|
|
||||||
|
export default class ArrayNode extends ParseNode {
|
||||||
|
constructor({values}) {
|
||||||
|
super(...arguments);
|
||||||
|
this.values = values;
|
||||||
|
}
|
||||||
|
resolve(fn, scope, context){
|
||||||
|
let values = this.values.map(node => node[fn](scope, context));
|
||||||
|
return new ArrayNode({values});
|
||||||
|
}
|
||||||
|
toString(){
|
||||||
|
return `[${this.values.map(node => node.toString()).join(', ')}]`;
|
||||||
|
}
|
||||||
|
traverse(fn){
|
||||||
|
fn(this);
|
||||||
|
this.values.forEach(value => value.traverse(fn));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +1,73 @@
|
|||||||
//TODO
|
import ParseNode from '/imports/parser/parseTree/ParseNode.js';
|
||||||
|
import ErrorNode from '/imports/parser/parseTree/ErrorNode.js';
|
||||||
|
import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
||||||
|
import functions from '/imports/parser/functions.js';
|
||||||
|
|
||||||
|
export default class CallNode extends ParseNode {
|
||||||
|
constructor({functionName, args}) {
|
||||||
|
super(...arguments);
|
||||||
|
this.functionName = functionName;
|
||||||
|
this.args = args;
|
||||||
|
}
|
||||||
|
resolve(fn, scope, context){
|
||||||
|
let func = functions[this.functionName];
|
||||||
|
if (!func) return new ErrorNode({
|
||||||
|
node: this,
|
||||||
|
error: `${this.functionName} is not a function`,
|
||||||
|
context,
|
||||||
|
});
|
||||||
|
let args = castArgsToType({fn, scope, context, args: this.args, type: func.argumentType});
|
||||||
|
if (args.failed){
|
||||||
|
if (fn === 'reduce'){
|
||||||
|
return new ErrorNode({
|
||||||
|
node: this,
|
||||||
|
error: 'Could not convert all arguments to the correct type',
|
||||||
|
context,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return new CallNode({
|
||||||
|
functionName: this.functionName,
|
||||||
|
args: args,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
let value = func.fn.apply(null, args);
|
||||||
|
return new ConstantNode({
|
||||||
|
value,
|
||||||
|
type: 'number',
|
||||||
|
previousNodes: [this],
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return new ErrorNode({
|
||||||
|
node: this,
|
||||||
|
error,
|
||||||
|
context,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toString(){
|
||||||
|
return `${this.functionName}(${this.args.map(node => node.toString()).join(', ')})`;
|
||||||
|
}
|
||||||
|
traverse(fn){
|
||||||
|
fn(this);
|
||||||
|
this.args.forEach(arg => arg.traverse(fn));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function castArgsToType({fn, scope, context, args, type}){
|
||||||
|
let resolvedArgs = args.map(node => node[fn](scope, context))
|
||||||
|
let result = [];
|
||||||
|
if (type === 'number'){
|
||||||
|
resolvedArgs.forEach(node => {
|
||||||
|
if (node.isNumber){
|
||||||
|
result.push(node.value);
|
||||||
|
} else {
|
||||||
|
resolvedArgs.failed = true;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (resolvedArgs.failed) return resolvedArgs;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,21 +1,22 @@
|
|||||||
import ParseNode from '/imports/parser/parseTree/ParseNode.js';
|
import ParseNode from '/imports/parser/parseTree/ParseNode.js';
|
||||||
|
|
||||||
export default class ConstantNode extends ParseNode {
|
export default class ConstantNode extends ParseNode {
|
||||||
constructor({value, type, errors}){
|
constructor({value, type}){
|
||||||
super();
|
super(...arguments);
|
||||||
// string, number, boolean, numberArray, uncompiledNode
|
// string, number, boolean, uncompiledNode
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.value = value;
|
this.value = value;
|
||||||
if (errors) this.errors = errors;
|
|
||||||
}
|
}
|
||||||
compile(){
|
compile(){
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
reduce(){
|
toString(){
|
||||||
if (this.type === 'numberArray'){
|
return `${this.value}`;
|
||||||
return this.value.reduce((total, num) => total + num, 0);
|
}
|
||||||
} else {
|
get isNumber(){
|
||||||
return this;
|
return this.type === 'number';
|
||||||
}
|
}
|
||||||
|
get isInteger(){
|
||||||
|
return this.type === 'number' && Number.isInteger(this.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
21
app/imports/parser/parseTree/ErrorNode.js
Normal file
21
app/imports/parser/parseTree/ErrorNode.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import ParseNode from '/imports/parser/parseTree/ParseNode.js';
|
||||||
|
|
||||||
|
export default class ErrorNode extends ParseNode {
|
||||||
|
constructor({node, error, context}) {
|
||||||
|
super(...arguments);
|
||||||
|
this.node = node;
|
||||||
|
this.error = error;
|
||||||
|
if (context){
|
||||||
|
context.storeError({
|
||||||
|
type: 'error',
|
||||||
|
message: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compile(){
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
toString(){
|
||||||
|
return '###';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,38 +3,35 @@ import ConstantNode from '/imports/parser/parseTree/ConstantNode.js';
|
|||||||
|
|
||||||
export default class IfNode extends ParseNode {
|
export default class IfNode extends ParseNode {
|
||||||
constructor({condition, consequent, alternative}){
|
constructor({condition, consequent, alternative}){
|
||||||
super();
|
super(...arguments);
|
||||||
this.condition = condition;
|
this.condition = condition;
|
||||||
this.consequent = consequent;
|
this.consequent = consequent;
|
||||||
this.alternative = alternative;
|
this.alternative = alternative;
|
||||||
}
|
}
|
||||||
compile(){
|
toString(){
|
||||||
let condition = this.condition.compile();
|
let {condition, consequent, alternative} = this;
|
||||||
let consequent = this.consequent.compile();
|
return `${condition.toString()} ? ${consequent.toString()} : ${alternative.toString()}`
|
||||||
let alternative = this.alternative.compile();
|
}
|
||||||
if (
|
resolve(fn, scope, context){
|
||||||
condition.type !== 'string' &&
|
let condition = this.condition[fn](scope, context);
|
||||||
condition.type !== 'number' &&
|
if (condition instanceof ConstantNode){
|
||||||
condition.type !== 'boolean'
|
|
||||||
){
|
|
||||||
// Handle unresolved condition
|
|
||||||
return new ConstantNode({
|
|
||||||
value: `if (${condition.value}) ${consequent.value} else ${alternative.value}`,
|
|
||||||
type: 'uncompiledNode',
|
|
||||||
errors: [
|
|
||||||
...condition.errors,
|
|
||||||
...consequent.errors,
|
|
||||||
...alternative.errors,
|
|
||||||
],
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// So long as the condition reolves, return the correct alternative,
|
|
||||||
// even if it's unresolved
|
|
||||||
if (condition.value){
|
if (condition.value){
|
||||||
return consequent;
|
return this.consequent[fn](scope, context);
|
||||||
} else {
|
} else {
|
||||||
return alternative;
|
return this.alternative[fn](scope, context);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
return new IfNode({
|
||||||
|
condition: condition,
|
||||||
|
consequent: this.consequent,
|
||||||
|
alternative: this.alternative,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
traverse(fn){
|
||||||
|
fn(this);
|
||||||
|
this.condition.traverse(fn);
|
||||||
|
this.consequent.traverse(fn);
|
||||||
|
this.alternative.traverse(fn);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
32
app/imports/parser/parseTree/IndexNode.js
Normal file
32
app/imports/parser/parseTree/IndexNode.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import ParseNode from '/imports/parser/parseTree/ParseNode.js';
|
||||||
|
|
||||||
|
export default class IndexNode extends ParseNode {
|
||||||
|
constructor({array, index}) {
|
||||||
|
super(...arguments);
|
||||||
|
this.array = array;
|
||||||
|
this.index = index;
|
||||||
|
}
|
||||||
|
resolve(fn, scope, context){
|
||||||
|
let index = this.index[fn](scope, context);
|
||||||
|
if (index.isInteger){
|
||||||
|
let selection = this.array.values[index.value - 1];
|
||||||
|
if (selection){
|
||||||
|
let result = selection[fn](scope, context);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new IndexNode({
|
||||||
|
index,
|
||||||
|
array: this.array[fn](scope, context),
|
||||||
|
previousNodes: [this],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
toString(){
|
||||||
|
return `${this.array.toString()}[${this.index.toString()}]`;
|
||||||
|
}
|
||||||
|
traverse(fn){
|
||||||
|
fn(this);
|
||||||
|
this.array.traverse(fn);
|
||||||
|
this.index.traverse(fn);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user