forked from foundryvtt-starfinder/foundryvtt-starfinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
1527 lines (1300 loc) · 47.4 KB
/
gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { AsyncNedb } = require('nedb-async');
const archiver = require('archiver');
const argv = require('yargs').argv;
const chalk = require('chalk');
const fs = require('fs-extra');
const gulp = require('gulp');
const less = require('gulp-less');
const path = require('path');
const sanitize = require("sanitize-filename");
const stringify = require('json-stringify-pretty-compact');
const SFRPG_LESS = ["src/less/*.less"];
function getConfig() {
const configPath = path.resolve(process.cwd(), 'foundryconfig.json');
let config;
if (fs.existsSync(configPath)) {
config = fs.readJSONSync(configPath);
return config;
} else {
return;
}
}
function getManifest() {
const json = {};
if (fs.existsSync('src')) {
json.root = 'src';
} else {
json.root = 'dist';
}
const modulePath = path.join(json.root, 'module.json');
const systemPath = path.join(json.root, 'system.json');
if (fs.existsSync(modulePath)) {
json.file = fs.readJSONSync(modulePath);
json.name = 'module.json';
} else if (fs.existsSync(systemPath)) {
json.file = fs.readJSONSync(systemPath);
json.name = 'system.json';
} else {
return;
}
return json;
}
/********************/
/* BUILD */
/********************/
/**
* Build Less
*/
function buildLess() {
const name = 'sfrpg';
return gulp
.src(`src/less/${name}.less`)
.pipe(less())
.pipe(gulp.dest('dist'));
}
/**
* Copy static files
*/
async function copyFiles() {
const name = 'sfrpg';
const statics = [
'lang',
'fonts',
'images',
'templates',
'icons',
'packs',
'module',
`${name}.js`,
'module.json',
'system.json',
'template.json',
];
try {
for (const file of statics) {
if (fs.existsSync(path.join('src', file))) {
await fs.copy(path.join('src', file), path.join('dist', file));
}
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
/**
* Copy only those files that we want to watch while developing.
*
* Over time, with the inclusion of tons of images and icons, the number
* of files that are being copied over to the dist folder has increased by
* a large amount. This was causing the watch process to slow to a crawl while
* it re copied a bunch of static files. This method is only concerned with copying
* files that might actually change during development.
*/
async function copyWatchFiles() {
const name = 'sfrpg';
const statics = [
'lang',
'templates',
'module',
`${name}.js`,
'module.json',
'system.json',
'template.json',
];
try {
for (const file of statics) {
if (fs.existsSync(path.join('src', file))) {
await fs.copy(path.join('src', file), path.join('dist', file));
}
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
/**
* Does the same as copyFiles, except it only moves the
* README, OGL, and LICENSE files. These aren't needed for
* development, but they should be in the package.
*/
async function copyReadmeAndLicenses() {
const statics = ["README.md", "OGL", "LICENSE"];
try {
for (const file of statics) {
if (fs.existsSync(file)) {
await fs.copy(file, path.join('dist', file));
}
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
async function copyLibs() {
const tippyLib = "tippy.js/dist/tippy.umd.min.js";
const tippyMap = "tippy.js/dist/tippy.umd.min.js.map";
const popperLib = "@popperjs/core/dist/umd";
const cssFile = "tippy.js/dist/tippy.css";
const nodeModulesPath = "node_modules";
try {
await fs.copy(path.join(nodeModulesPath, tippyLib), "dist/lib/tippy/tippy.min.js");
await fs.copy(path.join(nodeModulesPath, tippyMap), "dist/lib/tippy/tippy.umd.min.js.map");
await fs.copy(path.join(nodeModulesPath, popperLib), "dist/lib/popperjs/core");
await fs.copy(path.join(nodeModulesPath, cssFile), "dist/styles/tippy.css");
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
/**
* Watch for changes for each build step
*/
function buildWatch() {
gulp.watch('src/**/*.less', { ignoreInitial: false }, buildLess);
gulp.watch(
['src/fonts', 'src/templates', 'src/lang', 'src/*.json', 'src/**/*.js'],
{ ignoreInitial: false },
copyWatchFiles
);
}
/**
* Sorts the keys in a JSON object, which should make it easier to find data keys.
*/
function JSONstringifyOrder( obj, space, sortingMode = "default" )
{
var allKeys = [];
var seen = {};
JSON.stringify(obj, function (key, value) {
if (!(key in seen)) {
allKeys.push(key);
seen[key] = null;
}
return value;
});
allKeys.sort();
if (sortingMode === "item") {
// Ensure name is after _id, and type is after name.
const idIndex = allKeys.indexOf("_id");
const nameIndex = allKeys.indexOf("name");
if (nameIndex > -1) {
allKeys.splice(nameIndex, 1);
allKeys.splice(idIndex + 1, 0, "name");
}
const typeIndex = allKeys.indexOf("type");
if (typeIndex > -1) {
allKeys.splice(typeIndex, 1);
allKeys.splice(idIndex + 2, 0, "type");
}
}
return JSON.stringify(obj, allKeys, space);
}
/**
* Unpack existing db files into json files.
*/
async function unpack(sourceDatabase, outputDirectory) {
await fs.mkdir(`${outputDirectory}`, { recursive: true }, (err) => { if (err) throw err; });
let db = new AsyncNedb({ filename: sourceDatabase, autoload: true });
let items = await db.asyncFind({});
for (let item of items) {
let jsonOutput = JSONstringifyOrder(item, 2, "item");
let filename = sanitize(item.name);
filename = filename.replace(/[\s]/g, "_");
filename = filename.replace(/[,;]/g, "");
filename = filename.toLowerCase();
let targetFile = `${outputDirectory}/${filename}.json`;
await fs.writeFileSync(targetFile, jsonOutput, { "flag": "w" });
}
}
async function unpackPacks() {
console.log(`Unpacking all packs`);
let sourceDir = "./src/packs";
let files = await fs.readdirSync(sourceDir);
for (let file of files) {
if (limitToPack && !file.includes(limitToPack)) {
continue;
}
if (file.endsWith(".db")) {
let fileWithoutExt = file.substr(0, file.length - 3);
let unpackDir = `./src/items/${fileWithoutExt}`;
let sourceFile = `${sourceDir}/${file}`;
console.log(`Processing ${fileWithoutExt}`);
console.log(`> Cleaning up ${unpackDir}`);
await fs.rmdirSync(unpackDir, { recursive: true });
console.log(`> Unpacking ${sourceFile} into ${unpackDir}`);
await unpack(sourceFile, unpackDir);
console.log(`> Done.`);
}
}
console.log(`\nUnpack finished.\n`);
return 0;
}
/**
* Cook db source json files into .db files with nedb
*/
var cookErrorCount = 0;
var cookAborted = false;
var packErrors = {};
var limitToPack = null;
async function cookPacksNoFormattingCheck() {
await cookWithOptions({ formattingCheck: false });
}
async function cookPacks(params) {
await cookWithOptions({parameters: params, formattingCheck: true});
}
async function cookWithOptions(options = { formattingCheck: true }) {
console.log(`Cooking db files`);
for (let i = 3; i<process.argv.length; i++) {
if (process.argv[i] === '--pack') {
limitToPack = process.argv[i+1];
i++;
}
}
let compendiumMap = {};
let allItems = [];
cookErrorCount = 0;
cookAborted = false;
packErrors = {};
let sourceDir = "./src/items";
let directories = await fs.readdirSync(sourceDir);
for (let directory of directories) {
let itemSourceDir = `${sourceDir}/${directory}`;
let outputFile = `./src/packs/${directory}.db`;
console.log(`Processing ${directory}`);
compendiumMap[directory] = {};
let db = null;
if (!limitToPack || directory === limitToPack) {
if (fs.existsSync(outputFile)) {
console.log(`> Removing ${outputFile}`);
await fs.unlinkSync(outputFile);
}
db = new AsyncNedb({ filename: outputFile, autoload: true });
}
console.log(`> Reading files in ${itemSourceDir}`);
let files = await fs.readdirSync(itemSourceDir);
for (let file of files) {
let filePath = `${itemSourceDir}/${file}`;
let jsonInput = await fs.readFileSync(filePath);
try {
jsonInput = JSON.parse(jsonInput);
} catch (err) {
if (!(directory in packErrors)) {
packErrors[directory] = [];
}
packErrors[directory].push(`${filePath}: Error parsing file: ${err}`);
cookErrorCount++;
continue;
}
// Cached conditions to be referenced later
if (directory === "conditions") {
conditionsCache[jsonInput._id] = jsonInput;
}
// Cached setting to be referenced later
else if (directory === "setting") {
settingCache[jsonInput._id] = jsonInput;
}
if (!limitToPack || directory === limitToPack) {
// For actors, we should double-check the token names are set correctly.
fixTokenName(jsonInput);
// Fix missing images
if (!jsonInput.img && !jsonInput.pages) {
// Skip if a journal
jsonInput.img = "icons/svg/mystery-man.svg";
}
const movingActorTypes = ["character", "drone", "npc"];
if (movingActorTypes.includes(jsonInput.type)) {
tryMigrateActorSpeed(jsonInput);
}
}
compendiumMap[directory][jsonInput._id] = jsonInput;
allItems.push({ pack: directory, data: jsonInput, file: file });
if (limitToPack && directory !== limitToPack) {
continue;
}
await db.asyncInsert(jsonInput);
}
if (!limitToPack || directory === limitToPack) {
console.log(`> Finished processing data for ${directory}.`);
}
}
if (cookErrorCount > 0) {
console.log(`\nCritical parsing errors occurred, aborting cook.`);
cookAborted = true;
return 1;
}
// Construct condition & setting finding regular expressions
conditionsRegularExpression = regularExpressionForFindingItemsInCache(conditionsCache);
settingRegularExpression = regularExpressionForFindingItemsInCache(settingCache);
if (options.formattingCheck === true) {
console.log(`\nStarting formatting check.`);
formattingCheck(allItems)
}
else {
console.log(`\n*Skipping* formatting check.`);
}
console.log(`\nStarting consistency check.`);
consistencyCheck(allItems, compendiumMap)
console.log(`\nUpdating items with updated IDs.\n`);
await unpackPacks();
console.log(`\nCook finished with ${cookErrorCount} errors.\n`);
return 0;
}
// Generates a regular expression to find references to the provided items
function regularExpressionForFindingItemsInCache(cache) {
let regularExpressionSubstring = "";
const conditionNames = Object.entries(cache).map(x => x[1].name);
regularExpressionSubstring = conditionNames.join("|");
return new RegExp("(" + regularExpressionSubstring + ")", "g");
}
// Ensures token names are the same as the actor name.
function fixTokenName(item) {
if (!item) return;
// Did not add Character because iconics come in multiple levels, and we don't want to include level in the name.
const actorTypes = ["npc", "starship", "vehicle"];
// Ensure token name is the same as the actor name, if applicable
if (actorTypes.includes(item.type) && item.token) {
item.token.name = item.name;
}
}
function tryMigrateActorSpeed(jsonInput) {
const speedValue = jsonInput.system?.attributes?.speed?.value;
const specialValue = jsonInput.system?.attributes?.speed?.special;
if (speedValue) {
let baseSpeed = speedValue;
if (baseSpeed && isNaN(baseSpeed)) {
baseSpeed = baseSpeed.replace(/\D/g,'');
baseSpeed = Number(baseSpeed);
}
// If all else fails, forcibly reset it to 30.
if (!baseSpeed || isNaN(baseSpeed)) {
baseSpeed = 30;
}
jsonInput.system.attributes.speed = {
land: { base: 0 },
flying: { base: 0 },
swimming: { base: 0 },
burrowing: { base: 0 },
climbing: { base: 0 },
special: "",
mainMovement: "land"
};
const lowercaseSpeedValue = speedValue.toLowerCase();
if (lowercaseSpeedValue.includes("climb")) {
jsonInput.system.attributes.speed.climbing.base = baseSpeed;
jsonInput.system.attributes.speed.mainMovement = "climbing";
} else if (lowercaseSpeedValue.includes("fly")) {
jsonInput.system.attributes.speed.flying.base = baseSpeed;
jsonInput.system.attributes.speed.mainMovement = "flying";
} else if (lowercaseSpeedValue.includes("burrow")) {
jsonInput.system.attributes.speed.burrowing.base = baseSpeed;
jsonInput.system.attributes.speed.mainMovement = "burrowing";
} else if (lowercaseSpeedValue.includes("swim")) {
jsonInput.system.attributes.speed.swimming.base = baseSpeed;
jsonInput.system.attributes.speed.mainMovement = "swimming";
} else {
jsonInput.system.attributes.speed.land.base = baseSpeed;
jsonInput.system.attributes.speed.mainMovement = "land";
}
let finalSpecial = "";
if (speedValue != baseSpeed) {
finalSpecial += "original base: " + speedValue.trim();
}
if (specialValue) {
if (finalSpecial.length > 0) {
finalSpecial += "; original special: ";
}
finalSpecial += specialValue.trim();
}
jsonInput.system.attributes.speed.special = finalSpecial;
}
}
/**
*
* The formatting check goes through all items and checks various fields to ensure the entered values meets certain criteria.
* Usually individual checks are added when we notice a larger risk of data entry error on a specific field, or when any data entry error
* would cause significant harm to the usability of the entry.
*/
// conditions / setting cache and regular expression are generated during beginning of cooking and used during formatting checks
var conditionsCache = {};
var settingCache = {};
var conditionsRegularExpression;
var settingRegularExpression;
var poisonAndDiseasesRegularExpression = new RegExp("(poison|disease)", "g");
var validArmorTypes = ["light", "power", "heavy", "shield"];
var validCreatureSizes = ["fine", "diminutive", "tiny", "small", "medium", "large", "huge", "gargantuan", "colossal"];
function formattingCheck(allItems) {
for (const item of allItems) {
const data = item;
const pack = item.pack;
if (!data || !data.system || !data.type) {
continue; // Malformed data or journal entry - outside the scope of the formatting check
}
// We only check formatting of aliens, vehicles & equipment for now
if (data.type === "npc") {
// NOTE: `checkEcology` off by default as it currently produces hundreds of errors.
formattingCheckAlien(data, pack, item.file, { checkLinks: true, checkEcology: false })
}
else if (data.type === "equipment") {
formattingCheckItems(data, pack, item.file, { checkImage: true, checkSource: true, checkPrice: true, checkLevel: true, checkLinks: true })
}
else if (data.type === "vehicle") {
formattingCheckVehicle(data, pack, item.file, { checkLinks: true });
}
else if (data.type === "spell") {
formattingCheckSpell(data, pack, item.file, { checkLinks: true });
}
else if (data.type === "race") {
formattingCheckRace(data, pack, item.file, { checkLinks: true });
}
else if (data.type === "feat") {
formattingCheckFeat(data, pack, item.file, { checkLinks: true });
}
}
}
function formattingCheckRace(data, pack, file, options = { checkLinks: true }) {
// Validate name
if (!data.name || data.name.endsWith(' ') || data.name.startsWith(' ')) {
addWarningForPack(`${file}: Name is not well formatted "${data.name}.`, pack);
}
// Validate HP values
if (data.system.hp.value < 0) {
addWarningForPack(`${file}: HP value not entered correctly.`, pack);
}
if (data.system.size) {
if (!validCreatureSizes.includes(data.system.size)) {
addWarningForPack(`${file}: Size value not entered correctly.`, pack);
}
}
else {
addWarningForPack(`${file}: Size value not entered correctly.`, pack);
}
// Validate image
if (data.img && !data.img.startsWith("systems") && !data.img.startsWith("icons")) {
addWarningForPack(`${file}: Image is pointing to invalid location "${data.name}.`, pack);
}
// Validate source
let source = data.system.source;
if (!source) {
addWarningForPack(`${file}: Missing source field.`, pack);
return;
}
if (!isSourceValid(source)) {
addWarningForPack(`${file}: Improperly formatted source field "${source}.`, pack);
}
// Check biography for references to conditions
if (options.checkLinks) {
let description = data.system.description.value
let result = searchDescriptionForUnlinkedCondition(description);
if (result.found) {
addWarningForPack(`${file}: Found reference to ${result.match} in description without link.`, pack);
}
}
}
function formattingCheckAlien(data, pack, file, options = { checkLinks: true, checkEcology: true }) {
// Validate name
if (!data.name || data.name.endsWith(' ') || data.name.startsWith(' ')) {
addWarningForPack(`${file}: Name is not well formatted "${data.name}.`, pack);
}
// Validate attributes
// Validate HP & Stamina Points
if (!data.system.attributes || !data.system.attributes.hp || !data.system.attributes.sp) {
addWarningForPack(`${file}: Missing HP/SP values.`, pack);
return;
}
// Validate HP values
else if (data.system.attributes.hp.value != data.system.attributes.hp.max) {
addWarningForPack(`${file}: HP value not entered correctly.`, pack);
}
// Validate SP values
if (data.system.attributes.sp.value != data.system.attributes.sp.max) {
addWarningForPack(`${file}: SP value not entered correctly.`, pack);
}
if (data.system.traits.size) {
if (!validCreatureSizes.includes(data.system.traits.size)) {
addWarningForPack(`${file}: Size value not entered correctly.`, pack);
}
}
else {
addWarningForPack(`${file}: Size value not entered correctly.`, pack);
}
// Validate image
if (data.img && !data.img.startsWith("systems") && !data.img.startsWith("icons")) {
addWarningForPack(`${file}: Image is pointing to invalid location "${data.name}.`, pack);
}
// Validate token image
if (data.token.img && !data.token.img.startsWith("systems") && !data.token.img.startsWith("icons")) {
addWarningForPack(`${file}: Image is pointing to invalid location "${data.name}.`, pack);
}
// Validate source
let source = data.system.details.source;
if (!source) {
addWarningForPack(`${file}: Missing source field.`, pack);
return;
}
if (!isSourceValid(source)) {
addWarningForPack(`${file}: Improperly formatted source field "${source}.`, pack);
}
if (options.checkEcology === true) {
// Validate ecology
let environment = data.system.details.environment;
let organization = data.system.details.organization;
if (environment === null || environment === "") {
addWarningForPack(`${file}: Environment is missing.`, pack);
}
if (organization === null || organization === "") {
addWarningForPack(`${file}: Organization is missing.`, pack);
}
}
if (options.checkLinks === true) {
let description = data.system.details.biography.value
// Check biography for references to conditions
let conditionResult = searchDescriptionForUnlinkedCondition(description);
if (conditionResult.found) {
addWarningForPack(`${file}: Found reference to ${conditionResult.match} in biography without link.`, pack);
}
// Check biography for references to the setting
let settingResult = searchDescriptionForUnlinkedReference(description, settingRegularExpression);
if (settingResult.found) {
addWarningForPack(`${file}: Found reference to ${settingResult.match} in description without link.`, pack);
}
}
// Validate items
for (i in data.items) {
formattingCheckItems(data.items[i], pack, file, { checkImage: true, checkSource: false, checkPrice: false, checkLinks: options.checkLinks })
}
}
function formattingCheckItems(data, pack, file, options = { checkImage: true, checkSource: true, checkPrice: true, checkLevel: true, checkLinks: true }) {
// Validate name
if (!data.name || data.name.endsWith(' ') || data.name.startsWith(' ')) {
addWarningForPack(`${file}: Name is not well formatted "${data.name}.`, pack);
}
// Validate image
if (options.checkImage) {
if (data.img && // Only validate if img is set
!data.img.startsWith("systems") && !data.img.startsWith("icons")) {
addWarningForPack(`${file}: Image is pointing to invalid location "${data.name}.`, pack);
}
}
// Validate source
if (options.checkSource) {
let source = data.system.source;
if (!isSourceValid(source)) {
addWarningForPack(`${file}: Improperly formatted source field "${source}.`, pack);
}
}
// Validate price
if (options.checkPrice) {
let price = data.system.price;
if (!price || price <= 0) {
addWarningForPack(`${file}: Improperly formatted armor price field "${price}.`, pack);
}
}
// Validate level
if (options.checkLevel) {
let level = data.system.level;
if (!level || level <= 0) {
addWarningForPack(`${file}: Improperly formatted armor level field "${level}.`, pack);
}
}
// If a weapon
if (data.system.weaponType) {
formattingCheckWeapons(data, pack, file);
}
// If armor
let armor = data.system.armor
if (armor) {
// Validate armor type
let armorType = data.system.armor.type
if (!validArmorTypes.includes(armorType)) {
addWarningForPack(`${file}: Improperly formatted armor type field "${armorType}.`, pack);
}
}
// Validate links
if (options.checkLinks) {
let description = data.system.description.value
if (description) {
// Check description for references to conditions
let conditionResult = searchDescriptionForUnlinkedReference(description, conditionsRegularExpression);
if (conditionResult.found) {
addWarningForPack(`${file}: Found reference to ${conditionResult.match} in description without link.`, pack);
}
// Check description for references to poisons / diseases
let poisonResult = searchDescriptionForUnlinkedReference(description, poisonAndDiseasesRegularExpression);
if (poisonResult.found) {
addWarningForPack(`${file}: Found reference to ${poisonResult.match} in description without link.`, pack);
}
}
else {
// Item has no description
}
}
}
function formattingCheckWeapons(data, pack, file) {
let lowecaseName = data.name.toLowerCase()
if (lowecaseName.includes("multiattack")) {
// Should be [MultiATK]
addWarningForPack(`${file}: Improperly formatted multiattack name field "${data.name}.`, pack);
}
if (lowecaseName.includes("multiatk")) {
if (data.name.includes("[MultiATK] ")) {
// Looks good, contains the proper multi-attack prefix and a space
}
else {
// Anything else is close, but is slightly off
addWarningForPack(`${file}: Improperly formatted multiattack name field "${data.name}.`, pack);
}
}
}
function formattingCheckVehicle(data, pack, file, options = { checkLinks: true }) {
// Validate name
if (!data.name || data.name.endsWith(' ') || data.name.startsWith(' ')) {
addWarningForPack(`${file}: Name is not well formatted "${data.name}.`, pack);
}
// Validate image
if (data.img && !data.img.startsWith("systems") && !data.img.startsWith("icons")) {
addWarningForPack(`${file}: Image is pointing to invalid location "${data.name}.`, pack);
}
// Validate source
let source = data.system.details.source;
if (!source) {
addWarningForPack(`${file}: Missing source field.`, pack);
return;
}
if (!isSourceValid(source)) {
addWarningForPack(`${file}: Improperly formatted source field "${source}.`, pack);
}
// Validate price
let price = data.system.details.price;
if (!price || price <= 0) {
addWarningForPack(`${file}: Improperly formatted vehicle price field "${armorType}.`, pack);
}
// Validate level
let level = data.system.details.level;
if (!level || level <= 0) {
addWarningForPack(`${file}: Improperly formatted vehicle level field "${armorType}.`, pack);
}
// Check description for references to conditions
if (options.checkLinks) {
let description = data.system.details.description.value
if (description) {
let result = searchDescriptionForUnlinkedCondition(description);
if (result.found) {
addWarningForPack(`${file}: Found reference to ${result.match} in description without link.`, pack);
}
}
else {
// Vehicle has no description
}
}
// Validate items
for (i in data.items) {
formattingCheckItems(data.items[i], pack, file, { checkImage: true, checkSource: false, checkPrice: false, checkLinks: options.checkLinks })
}
}
function formattingCheckSpell(data, pack, file, options = { checkLinks: true }) {
// Validate name
if (!data.name || data.name.endsWith(' ') || data.name.startsWith(' ')) {
addWarningForPack(`${file}: Name is not well formatted "${data.name}.`, pack);
}
// Validate image
if (data.img && !data.img.startsWith("systems") && !data.img.startsWith("icons")) {
addWarningForPack(`${file}: Image is pointing to invalid location "${data.name}.`, pack);
}
// Validate source
let source = data.system.source;
if (!source) {
addWarningForPack(`${file}: Missing source field.`, pack);
return;
}
if (!isSourceValid(source)) {
addWarningForPack(`${file}: Improperly formatted source field "${source}.`, pack);
}
//Check spell description for unlinked references to conditions
if (options.checkLinks === true) {
let description = data.system.description.value
// Check references to conditions
let conditionResult = searchDescriptionForUnlinkedReference(description, conditionsRegularExpression);
if (conditionResult.found) {
addWarningForPack(`${file}: Found reference to ${conditionResult.match} in description without link.`, pack);
}
// Check references to the setting
let settingResult = searchDescriptionForUnlinkedReference(description, settingRegularExpression);
if (settingResult.found) {
addWarningForPack(`${file}: Found reference to ${settingResult.match} in description without link.`, pack);
}
}
}
function formattingCheckFeat(data, pack, file, options = { checkLinks: true }) {
// Validate name
if (!data.name || data.name.endsWith(' ') || data.name.startsWith(' ')) {
addWarningForPack(`${file}: Name is not well formatted "${data.name}.`, pack);
}
// Validate image
if (data.img && !data.img.startsWith("systems") && !data.img.startsWith("icons")) {
addWarningForPack(`${file}: Image is pointing to invalid location "${data.name}.`, pack);
}
// NOTE: We don't validate `source` for feats as we currently are not decided if we should use this field as
// it's used for other items (it is generally used to provide an explanation of what game mechanic unlocks the
// feat)
if (options.checkLinks === true) {
let description = data.system.description.value
// Check description for references to conditions
let conditionResult = searchDescriptionForUnlinkedReference(description, conditionsRegularExpression);
if (conditionResult.found) {
addWarningForPack(`${file}: Found reference to ${conditionResult.match} in description without link.`, pack);
}
// Check description for references to the setting
let settingResult = searchDescriptionForUnlinkedReference(description, settingRegularExpression);
if (settingResult.found) {
addWarningForPack(`${file}: Found reference to ${settingResult.match} in description without link.`, pack);
}
}
}
// Check if a description contains an unlinked reference to a condition
function searchDescriptionForUnlinkedCondition(description) {
return searchDescriptionForUnlinkedReference(description, conditionsRegularExpression);
}
// Checks if a description contains an unlinked reference to any value found in the provided regular expression
function searchDescriptionForUnlinkedReference(description, regularExpression) {
let matches = [...description.matchAll(regularExpression)];
//Found a potential reference to a condition
if (matches && matches.length > 0) {
// Capture the character before and after each match and use some basic heuristics to decide if it's an linked condition in the description
for (let match of matches) {
let conditionWord = match[0];
let matchedWord = description.substring(match["index"], match["index"] + match["length"]);
// We want to capture a character before and after
let characterBeforeIndex = match["index"] - 1;
let characterAfterIndex = match["index"] + conditionWord.length;
let characterBefore = description.substring(characterBeforeIndex, characterBeforeIndex + 1);
let characterAfter = description.substring(characterAfterIndex, characterAfterIndex + 1);
let delimiterCharacters = [">", "<", ";", ",", "/", "(", ")", "."];
var unlinkedReferenceFound = false;
// If surrounded by { and } we assume it is linked and continue
if (characterBefore === "{" && characterAfter === "}") {
continue;
}
// If the condition is surrounded by spaces, it is unlinked
// it should be contained in a link to the compendium like this `@Compendium[sfrpg.spells.YDXegEus8p0BnsH1]{Invisibility}`
else if (characterBefore === " " && characterAfter === " ") {
unlinkedReferenceFound = true;
}
// If potentially within the contents of a tag or surrounded by delimiting characters
else if (delimiterCharacters.includes(characterBefore) && (delimiterCharacters.includes(characterAfter) || characterAfter === " ")) {
// The condition was found between two delimiters, most likely in the contents of an html tag.
// Or it was found at the tail of a delimiter followed by a space (at the end of a comma separated list.
unlinkedReferenceFound = true
}
// Condition was found after a space but right before a delimiting character, like the end of a sentence.
// Or hugging opening brackets, or the start of a comma separated list.
else if ((delimiterCharacters.includes(characterBefore) || characterBefore === " ") && delimiterCharacters.includes(characterAfter)) {
unlinkedReferenceFound = true;
}
// This is a simple rule of thumb which checks of the word in question is surrounded by ` `. In this case we'll ignore,
// as this can be used to escape a condition word (ie. `Burning`) in an otherwise unrelated context (ie. `... the Burning Archipelago...`)
else if (characterBefore === ";" && characterAfter === "&") {
unlinkedReferenceFound = false;
}
if (unlinkedReferenceFound) {
return { found: true, match: conditionWord };
}
}
}
return { found: false };
}
// Checks a source string for conformance to string format outlined in CONTRIBUTING.md
function isSourceValid(source) {
// NOTE: One day this should be changed if they publish further Core books (Galaxy Exploration Manual included for posterity)
const CoreBooksSourceMatch = [...source.matchAll(/(CRB|AR|PW|COM|SOM|NS|GEM|TR|GM|DC) pg\. [\d]+/g)];
// NOTE: One day this should be increased when they publish further Alien Archives (Alien Archive 5 included for posterity)
const AlienArchiveSourceMatch = [...source.matchAll(/AA([1-5]) pg\. [\d]+/g)];
const AdventurePathSourceMatch = [...source.matchAll(/AP #[\d]+ pg\. [\d]+/g)];
const StarfinderSocietySourceMatch = [...source.matchAll(/SFS #[\d]+-[\d]+ pg\. [\d]+/g)];
const StarfinderAdventureSourceMatch = [...source.matchAll(/SA:\S+ pg\. [\d]+/g)];
if (CoreBooksSourceMatch && CoreBooksSourceMatch.length > 0) {
// ✅ formatted Core book source
return true;
}
else if (AlienArchiveSourceMatch && AlienArchiveSourceMatch.length > 0) {
// ✅ formatted Alien Archives source
return true;
}
else if (AdventurePathSourceMatch && AdventurePathSourceMatch.length > 0) {
// ✅ formatted Adventure path source
return true;
}
else if (StarfinderSocietySourceMatch && StarfinderSocietySourceMatch.length > 0) {
// ✅ formatted Starfinder Society source
return true;
}
else if (StarfinderAdventureSourceMatch && StarfinderAdventureSourceMatch.length > 0) {
// ✅ formatted Starfinder Adventure source
return true;
}
else if (source === "ACD") {
// ✅ formatted Alien Card Deck source
return true
}
return false;
}
function addWarningForPack(warning, pack) {
if (!(pack in packErrors)) {
packErrors[pack] = [];
}
cookErrorCount += 1;
packErrors[pack].push(warning);
}
function consistencyCheck(allItems, compendiumMap) {
for (let item of allItems) {
let data = item;
if (!data || !data.system || !data.system.description) continue;
let desc = data.system.description.value;
if (!desc) continue;
let pack = item.pack;