@vttforge/cli 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +5 -5
- package/dist/bin.mjs +428 -103
- package/dist/bin.mjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{src-5a2deycw.mjs → src-BK9BmFiZ.mjs} +65 -6
- package/dist/src-BK9BmFiZ.mjs.map +1 -0
- package/package.json +2 -2
- package/templates/module-js/README.md +10 -10
- package/templates/module-js/package.json +1 -1
- package/templates/module-ts/README.md +12 -13
- package/templates/module-ts/package.json +1 -1
- package/templates/system-js/README.md +12 -12
- package/templates/system-js/package.json +1 -1
- package/templates/system-ts/README.md +11 -12
- package/templates/system-ts/package.json +1 -1
- package/dist/src-5a2deycw.mjs.map +0 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { _ as definesName, a as runDev, g as bareUsePattern, h as LEGACY_GLOBALS, i as runInit, m as maskComments, n as runLintCommand, p as REMOVED_UTILS, r as ScaffoldError, s as runBuild, t as VTTFORGE_CLI_VERSION, u as runAuditCommand, x as runReleaseRules, y as _internal } from "./src-
|
|
2
|
+
import { _ as definesName, a as runDev, g as bareUsePattern, h as LEGACY_GLOBALS, i as runInit, m as maskComments, n as runLintCommand, p as REMOVED_UTILS, r as ScaffoldError, s as runBuild, t as VTTFORGE_CLI_VERSION, u as runAuditCommand, x as runReleaseRules, y as _internal } from "./src-BK9BmFiZ.mjs";
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
4
|
import { dirname, join, relative, resolve } from "node:path";
|
|
5
|
-
import { mkdir, readFile,
|
|
5
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
6
6
|
import { defineCommand, runMain } from "citty";
|
|
7
7
|
import { parse } from "@babel/parser";
|
|
8
8
|
//#region src/migrate/data-models.ts
|
|
@@ -83,8 +83,8 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
|
|
|
83
83
|
const modelNames = [];
|
|
84
84
|
for (const type of types) {
|
|
85
85
|
const own = doc[type] ?? {};
|
|
86
|
-
const listed =
|
|
87
|
-
for (const t of listed) if (!(t in templates)) notes.push(`${document}.${type}: lists template "${t}", which template.json does not define; it was skipped.`);
|
|
86
|
+
const listed = own.templates ?? [];
|
|
87
|
+
for (const t of listed) if (!(t in templates) && t !== "base") notes.push(`${document}.${type}: lists template "${t}", which template.json does not define; it was skipped.`);
|
|
88
88
|
const spreads = listed.filter((t) => t in templates).map((t) => ` ...${camel$1(t)}Fields(f),`).join("\n");
|
|
89
89
|
const body = schemaBody(own, `${document}.${type}`, notes);
|
|
90
90
|
const className = `${pascal$1(type)}Data`;
|
|
@@ -195,7 +195,7 @@ function readTabIds(template, navSelector) {
|
|
|
195
195
|
*/
|
|
196
196
|
function editTemplate(template, opts) {
|
|
197
197
|
const edits = [];
|
|
198
|
-
const navRanges = opts.navSelectors.map((selector) => elementRange(template, selector)).filter((range) => range !== null);
|
|
198
|
+
const navRanges = opts.navSelectors.slice(0, 1).map((selector) => elementRange(template, selector)).filter((range) => range !== null);
|
|
199
199
|
const inNav = (index) => navRanges.some(([start, end]) => index >= start && index < end);
|
|
200
200
|
return {
|
|
201
201
|
output: template.replace(tagRe(), (whole, name, attrs, selfClose, offset) => {
|
|
@@ -211,7 +211,7 @@ function editTemplate(template, opts) {
|
|
|
211
211
|
const needsGroup = attr(attrs, "data-group") === null;
|
|
212
212
|
let withClass = attrs;
|
|
213
213
|
const isNavLink = tab !== null && inNav(offset);
|
|
214
|
-
const isPane = tab !== null && !isNavLink && hasClass(attrs, "tab");
|
|
214
|
+
const isPane = tab !== null && !isNavLink && hasClass(attrs, "tab") && (opts.tabIds === void 0 || opts.tabIds.includes(tab));
|
|
215
215
|
if (isNavLink) {
|
|
216
216
|
if (!hasAction && !add.some((one) => one.startsWith("data-action="))) add.push("data-action=\"vttforgeTab\"");
|
|
217
217
|
if (needsGroup) add.push("data-group=\"primary\"");
|
|
@@ -241,13 +241,13 @@ function editTemplate(template, opts) {
|
|
|
241
241
|
* the few lookups the planner needs. Bodies are never re-printed from the
|
|
242
242
|
* tree; the planner slices the original text by node range.
|
|
243
243
|
*/
|
|
244
|
-
const CONVERTED = /* @__PURE__ */ new Set([
|
|
245
|
-
|
|
244
|
+
const CONVERTED = /* @__PURE__ */ new Set([
|
|
245
|
+
"ActorSheet",
|
|
246
|
+
"ItemSheet",
|
|
246
247
|
"Application",
|
|
247
|
-
"FormApplication"
|
|
248
|
-
"Dialog",
|
|
249
|
-
"DocumentSheet"
|
|
248
|
+
"FormApplication"
|
|
250
249
|
]);
|
|
250
|
+
const UNSUPPORTED = /* @__PURE__ */ new Set(["Dialog", "DocumentSheet"]);
|
|
251
251
|
function parseSource(source, lang) {
|
|
252
252
|
return parse(source, {
|
|
253
253
|
sourceType: "module",
|
|
@@ -375,8 +375,9 @@ function todoAt(code, index, msg) {
|
|
|
375
375
|
return `${code.slice(0, lineStart)}${indent}${TODO(msg)}\n${code.slice(lineStart)}`;
|
|
376
376
|
}
|
|
377
377
|
/** The jQuery calls with no one-to-one DOM rewrite. */
|
|
378
|
-
const LEFTOVER_JQUERY = /\$\(|\.(?:val|text|html|prop|toggle|slideToggle|slideUp|slideDown|show|hide|addClass|removeClass|toggleClass|siblings|children|find|css)\(/g;
|
|
378
|
+
const LEFTOVER_JQUERY = /\$\(|\.(?:val|text|html|prop|toggle|slideToggle|slideUp|slideDown|show|hide|addClass|removeClass|toggleClass|siblings|children|find|css|each)\(/g;
|
|
379
379
|
const JQUERY_MSG = "jQuery left here; use the DOM on `target` / `this.element`";
|
|
380
|
+
const ENRICH_MSG = "enrichHTML returns a promise on v14; await it, and make this method async";
|
|
380
381
|
/**
|
|
381
382
|
* A handler body from `activateListeners`, with `event.currentTarget` folded
|
|
382
383
|
* into the `target` the action receives and the jQuery data readers turned
|
|
@@ -394,6 +395,16 @@ function rewriteHandlerBody(body, eventParam, htmlParam, targetName = "target")
|
|
|
394
395
|
code = replaceCode(code, /\.attr\(\s*(['"])data-([\w-]+)\1\s*\)/g, (_m, _q, key) => `.dataset.${camel(key)}`);
|
|
395
396
|
code = replaceCode(code, /\.parents\(/g, () => ".closest(");
|
|
396
397
|
if (htmlParam) code = replaceCode(code, new RegExp(`\\b${esc(htmlParam)}\\.find\\(`, "g"), () => "this.element.querySelectorAll(");
|
|
398
|
+
code = replaceCode(code, /,\s*\{\s*async:\s*true\s*\}\s*\)/g, () => ")");
|
|
399
|
+
code = replaceCode(code, /\basync:\s*true\s*,\s*/g, () => "");
|
|
400
|
+
code = replaceCode(code, /,\s*async:\s*true\b/g, () => "");
|
|
401
|
+
if (/\basync:\s*false\b/.test(code)) {
|
|
402
|
+
code = replaceCode(code, /,\s*\{\s*async:\s*false\s*\}\s*\)/g, () => ")");
|
|
403
|
+
code = replaceCode(code, /\basync:\s*false\s*,\s*/g, () => "");
|
|
404
|
+
code = replaceCode(code, /,\s*async:\s*false\b/g, () => "");
|
|
405
|
+
todos.push(ENRICH_MSG);
|
|
406
|
+
code = todoAt(code, code.indexOf("{") + 1, ENRICH_MSG);
|
|
407
|
+
}
|
|
397
408
|
code = replaceCode(code, /this\.element\.find\(/g, () => "this.element.querySelectorAll(");
|
|
398
409
|
const masked = maskComments(code, { strings: true });
|
|
399
410
|
const lines = /* @__PURE__ */ new Set();
|
|
@@ -417,21 +428,27 @@ function rewriteHandlerBody(body, eventParam, htmlParam, targetName = "target")
|
|
|
417
428
|
* assigned right after the `super` call — unless the method assigns them
|
|
418
429
|
* itself without reading the old value first.
|
|
419
430
|
*/
|
|
420
|
-
function rewriteGetData(methodText, base) {
|
|
431
|
+
function rewriteGetData(methodText, base, opts = {}) {
|
|
421
432
|
const todos = [];
|
|
422
433
|
const params = /^(\s*)(async\s+)?getData\s*\(([^)]*)\)/.exec(methodText)?.[3]?.trim() ?? "";
|
|
423
434
|
let code = methodText.replace(/^(\s*)(async\s+)?getData\s*\(([^)]*)\)/, (_m, indent) => `${indent}async _prepareContext(options)`);
|
|
424
435
|
code = replaceCode(code, /super\.getData\(\s*[^)]*\)/g, () => "super._prepareContext(options)");
|
|
436
|
+
code = replaceCode(code, /(?<!await\s)super\._prepareContext\(options\)/g, () => "await super._prepareContext(options)");
|
|
437
|
+
code = replaceCode(code, /,\s*\{\s*async:\s*false\s*\}\s*\)/g, () => ")");
|
|
438
|
+
code = replaceCode(code, /\basync:\s*false\s*,\s*/g, () => "");
|
|
439
|
+
code = replaceCode(code, /,\s*async:\s*false\b/g, () => "");
|
|
440
|
+
code = replaceCode(code, /(?<!await\s)(?<![\w$.])(?:[\w$]+\.)*enrichHTML\(/g, (call) => `await ${call}`);
|
|
425
441
|
const varMatch = /(?:const|let|var)\s+(\w+)\s*=\s*(?:await\s+)?super\._prepareContext\(options\)\s*;/.exec(code);
|
|
426
442
|
const v = varMatch?.[1] ?? "context";
|
|
443
|
+
const isSheet = base === "ActorSheet" || base === "ItemSheet";
|
|
427
444
|
const own = base === "ActorSheet" ? "actor" : "item";
|
|
428
|
-
const wanted = [
|
|
445
|
+
const wanted = isSheet ? [
|
|
429
446
|
[own, `${v}.${own} = this.document;`],
|
|
430
447
|
["data", `${v}.data = this.document;`],
|
|
431
448
|
["system", `${v}.system = this.document.system;`]
|
|
432
|
-
];
|
|
449
|
+
] : base === "FormApplication" && opts.usesObject === true ? [["object", `${v}.object = this.object;`]] : [];
|
|
433
450
|
if (base === "ActorSheet") wanted.push(["items", `${v}.items = [...this.document.items];`]);
|
|
434
|
-
wanted.push(["editable", `${v}.editable = this.isEditable;`], ["owner", `${v}.owner = this.document.isOwner;`]);
|
|
451
|
+
if (isSheet) wanted.push(["editable", `${v}.editable = this.isEditable;`], ["owner", `${v}.owner = this.document.isOwner;`]);
|
|
435
452
|
const masked = maskComments(code, { strings: true });
|
|
436
453
|
const inject = wanted.filter(([key]) => {
|
|
437
454
|
const assigned = new RegExp(`\\b${esc(v)}\\.${key}\\s*=(?!=)`).test(masked);
|
|
@@ -462,6 +479,28 @@ function rewriteGetData(methodText, base) {
|
|
|
462
479
|
* resolves the dropped document before it calls the hook, so the raw drop
|
|
463
480
|
* payload the v1 body read is gone.
|
|
464
481
|
*/
|
|
482
|
+
/**
|
|
483
|
+
* `_updateObject(event, formData)` becomes the static form handler ApplicationV2
|
|
484
|
+
* calls with `(event, form, formData)`; `formData.object` is the flat form
|
|
485
|
+
* data, expanded here so the body reads it the way v1 handed it.
|
|
486
|
+
*/
|
|
487
|
+
function rewriteUpdateObject(methodText) {
|
|
488
|
+
const sig = /^(\s*)(async\s+)?_updateObject\s*\(\s*(\w+)?(?:\s*:\s*(?:[^,)<]|<[^>]*>)*)?\s*,?\s*(\w+)?(?:\s*:\s*(?:[^,)<]|<[^>]*>)*)?\s*\)\s*(?::[^{]*)?\{/.exec(methodText);
|
|
489
|
+
if (!sig) return {
|
|
490
|
+
code: methodText,
|
|
491
|
+
todos: []
|
|
492
|
+
};
|
|
493
|
+
const indent = sig[1] ?? "";
|
|
494
|
+
const eventName = sig[3] || "event";
|
|
495
|
+
const dataName = sig[4] || "data";
|
|
496
|
+
const param = dataName === "formData" ? "submission" : "formData";
|
|
497
|
+
const code = `${`${indent}static async formHandler(${eventName}, form, ${param}) {`}${`\n${indent} const ${dataName} = foundry.utils.expandObject(${param}.object);`}${methodText.slice(sig[0].length)}`;
|
|
498
|
+
const msg = "this was _updateObject; ApplicationV2 calls the form handler with `this` bound to the app, and the flat form data is `formData.object`";
|
|
499
|
+
return {
|
|
500
|
+
code: todoAt(code, code.indexOf("{") + 1, msg),
|
|
501
|
+
todos: [msg]
|
|
502
|
+
};
|
|
503
|
+
}
|
|
465
504
|
function rewriteDropMethod(methodText, which) {
|
|
466
505
|
const lower = which.toLowerCase();
|
|
467
506
|
const sig = new RegExp(`_onDrop${which}\\s*\\(\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)`);
|
|
@@ -575,18 +614,223 @@ function readConfirmOptions(inner) {
|
|
|
575
614
|
}
|
|
576
615
|
const key = pair.key.replace(/^['"]|['"]$/g, "");
|
|
577
616
|
if (key === "title" || key === "content" || key === "yes" || key === "no") found[key] = pair.value;
|
|
578
|
-
else if (key
|
|
617
|
+
else if (key === "rejectClose") found.rejectClose = pair.value;
|
|
618
|
+
else if (key !== "defaultYes" && key !== "options") missing.push(key);
|
|
579
619
|
}
|
|
580
620
|
return {
|
|
581
621
|
code: `DialogV2.confirm({ ${[
|
|
582
622
|
found.title ? `window: { title: ${found.title} }` : "",
|
|
583
623
|
found.content ? `content: ${found.content}` : "",
|
|
584
|
-
found.yes ? `yes: { callback: ${found.yes} }` : "",
|
|
585
|
-
found.no ? `no: { callback: ${found.no} }` : ""
|
|
624
|
+
found.yes ? `yes: { callback: ${v2Callback(found.yes, "event, button, dialog", "dialog.element")} }` : "",
|
|
625
|
+
found.no ? `no: { callback: ${v2Callback(found.no, "event, button, dialog", "dialog.element")} }` : "",
|
|
626
|
+
found.rejectClose ? `rejectClose: ${found.rejectClose}` : ""
|
|
586
627
|
].filter(Boolean).join(", ")} })`,
|
|
587
628
|
missing
|
|
588
629
|
};
|
|
589
630
|
}
|
|
631
|
+
/** Index just past the `)` that closes the call opened at `open` (which must point at `(`), or -1. */
|
|
632
|
+
function closingParen(text, open) {
|
|
633
|
+
const masked = maskComments(text, { strings: true });
|
|
634
|
+
let depth = 0;
|
|
635
|
+
for (let i = open; i < masked.length; i += 1) {
|
|
636
|
+
const ch = masked[i];
|
|
637
|
+
if (ch === "\0") continue;
|
|
638
|
+
if (ch === "(" || ch === "[" || ch === "{") depth += 1;
|
|
639
|
+
else if (ch === ")" || ch === "]" || ch === "}") {
|
|
640
|
+
depth -= 1;
|
|
641
|
+
if (depth === 0) return i + 1;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return -1;
|
|
645
|
+
}
|
|
646
|
+
/** Strip one pair of outer braces from an object literal's text. */
|
|
647
|
+
function innerOf(objectText) {
|
|
648
|
+
const t = objectText.trim();
|
|
649
|
+
if (!t.startsWith("{") || !t.endsWith("}")) return null;
|
|
650
|
+
return t.slice(1, -1);
|
|
651
|
+
}
|
|
652
|
+
/** `'<i class="fas fa-check"></i>'` → `'fas fa-check'`; anything else stays. */
|
|
653
|
+
function iconClass(value) {
|
|
654
|
+
const m = /<i\s+class=(["'])([^"']+)\1/.exec(value);
|
|
655
|
+
if (!m) return value;
|
|
656
|
+
const q = value.trim().startsWith("\"") ? "\"" : "'";
|
|
657
|
+
return `${q}${m[2]}${q}`;
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* A v1 dialog callback `(html) => ...` on the V2 signature. `html` was the
|
|
661
|
+
* dialog's jQuery content; V2 hands `(event, button, dialog)`, so `html[0]`
|
|
662
|
+
* is `dialog.element` and `html.find(sel)` is a query on it.
|
|
663
|
+
*/
|
|
664
|
+
function v2Callback(fn, signature, elementExpr) {
|
|
665
|
+
const arrow = /^(async\s+)?\(?\s*([\w$]*)\s*\)?\s*=>/.exec(fn.trim());
|
|
666
|
+
const classic = /^(async\s+)?function\s*\(\s*([\w$]*)\s*\)/.exec(fn.trim());
|
|
667
|
+
const m = arrow ?? classic;
|
|
668
|
+
if (!m) return fn;
|
|
669
|
+
const param = m[2] ?? "";
|
|
670
|
+
const head = arrow ? `${m[1] ?? ""}(${signature}) =>` : `${m[1] ?? ""}function (${signature})`;
|
|
671
|
+
let body = fn.trim().slice(m[0].length);
|
|
672
|
+
if (param) {
|
|
673
|
+
const p = esc(param);
|
|
674
|
+
body = replaceCode(body, new RegExp(`\\b${p}\\[0\\]`, "g"), () => elementExpr);
|
|
675
|
+
body = replaceCode(body, new RegExp(`\\b${p}\\.find\\(`, "g"), () => `${elementExpr}.querySelector(`);
|
|
676
|
+
body = replaceCode(body, new RegExp(`\\$\\(\\s*${p}\\s*\\)`, "g"), () => elementExpr);
|
|
677
|
+
body = replaceCode(body, new RegExp(`(?<![{,]\\s*)\\b${p}\\b|\\b${p}\\b(?!\\s*:)`, "g"), () => elementExpr);
|
|
678
|
+
}
|
|
679
|
+
body = replaceCode(body, /\.val\(\)/g, () => ".value");
|
|
680
|
+
return `${head}${body}`;
|
|
681
|
+
}
|
|
682
|
+
const NEW_DIALOG_WAIT_NOTE = "DialogV2.wait opens the dialog itself and resolves with the pressed button; drop any later .render(true) on this value and await it where the result matters";
|
|
683
|
+
/** `new Dialog({...})` options → the `DialogV2.wait({...})` call, or null when unreadable. */
|
|
684
|
+
function readDialogOptions(inner, indent) {
|
|
685
|
+
if (!balanced(inner)) return null;
|
|
686
|
+
const missing = [];
|
|
687
|
+
const found = {};
|
|
688
|
+
for (const pair of topLevelPairs(inner)) {
|
|
689
|
+
if (pair.spread) {
|
|
690
|
+
missing.push(`the spread ${pair.key}`);
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
const key = pair.key.replace(/^['"]|['"]$/g, "");
|
|
694
|
+
if ([
|
|
695
|
+
"title",
|
|
696
|
+
"content",
|
|
697
|
+
"buttons",
|
|
698
|
+
"default",
|
|
699
|
+
"render",
|
|
700
|
+
"close"
|
|
701
|
+
].includes(key)) found[key] = pair.value;
|
|
702
|
+
else missing.push(key);
|
|
703
|
+
}
|
|
704
|
+
const pad = `${indent} `;
|
|
705
|
+
const parts = [];
|
|
706
|
+
if (found.title) parts.push(`window: { title: ${found.title} }`);
|
|
707
|
+
if (found.content) parts.push(`content: ${found.content}`);
|
|
708
|
+
if (found.buttons) {
|
|
709
|
+
const buttonsInner = innerOf(found.buttons);
|
|
710
|
+
if (buttonsInner === null || !balanced(buttonsInner)) return null;
|
|
711
|
+
const defaultKey = found.default?.replace(/^['"]|['"]$/g, "");
|
|
712
|
+
const buttons = [];
|
|
713
|
+
for (const b of topLevelPairs(buttonsInner)) {
|
|
714
|
+
if (b.spread) {
|
|
715
|
+
missing.push(`the spread ${b.key} in buttons`);
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
const action = b.key.replace(/^['"]|['"]$/g, "");
|
|
719
|
+
const fields = innerOf(b.value);
|
|
720
|
+
if (fields === null) {
|
|
721
|
+
missing.push(`button ${action}`);
|
|
722
|
+
continue;
|
|
723
|
+
}
|
|
724
|
+
const entry = [`action: '${action}'`];
|
|
725
|
+
for (const f of topLevelPairs(fields)) {
|
|
726
|
+
const k = f.key.replace(/^['"]|['"]$/g, "");
|
|
727
|
+
if (k === "icon") entry.push(`icon: ${iconClass(f.value)}`);
|
|
728
|
+
else if (k === "label") entry.push(`label: ${f.value}`);
|
|
729
|
+
else if (k === "callback") entry.push(`callback: ${v2Callback(f.value, "event, button, dialog", "dialog.element")}`);
|
|
730
|
+
else missing.push(`button ${action}.${k}`);
|
|
731
|
+
}
|
|
732
|
+
if (defaultKey && defaultKey === action) entry.push("default: true");
|
|
733
|
+
buttons.push(`${pad} { ${entry.join(", ")} },`);
|
|
734
|
+
}
|
|
735
|
+
parts.push(`buttons: [\n${buttons.join("\n")}\n${pad}]`);
|
|
736
|
+
}
|
|
737
|
+
if (!found.buttons) missing.push("buttons (DialogV2 needs at least one; add an ok button)");
|
|
738
|
+
if (found.render) parts.push(`render: ${v2Callback(found.render, "event, dialog", "dialog.element")}`);
|
|
739
|
+
if (found.close) parts.push(`close: ${v2Callback(found.close, "event, dialog", "dialog.element")}`);
|
|
740
|
+
return {
|
|
741
|
+
code: `DialogV2.wait({\n${parts.map((p) => `${pad}${p},`).join("\n")}\n${indent}})`,
|
|
742
|
+
missing
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
/** `Dialog.prompt({...})` options → `DialogV2.prompt({...})`, or null when unreadable. */
|
|
746
|
+
function readPromptOptions(inner) {
|
|
747
|
+
if (!balanced(inner)) return null;
|
|
748
|
+
const missing = [];
|
|
749
|
+
const found = {};
|
|
750
|
+
for (const pair of topLevelPairs(inner)) {
|
|
751
|
+
if (pair.spread) {
|
|
752
|
+
missing.push(`the spread ${pair.key}`);
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
const key = pair.key.replace(/^['"]|['"]$/g, "");
|
|
756
|
+
if ([
|
|
757
|
+
"title",
|
|
758
|
+
"content",
|
|
759
|
+
"label",
|
|
760
|
+
"callback",
|
|
761
|
+
"rejectClose"
|
|
762
|
+
].includes(key)) found[key] = pair.value;
|
|
763
|
+
else missing.push(key);
|
|
764
|
+
}
|
|
765
|
+
const parts = [];
|
|
766
|
+
if (found.title) parts.push(`window: { title: ${found.title} }`);
|
|
767
|
+
if (found.content) parts.push(`content: ${found.content}`);
|
|
768
|
+
const ok = [];
|
|
769
|
+
if (found.label) ok.push(`label: ${found.label}`);
|
|
770
|
+
if (found.callback) ok.push(`callback: ${v2Callback(found.callback, "event, button, dialog", "dialog.element")}`);
|
|
771
|
+
if (ok.length > 0) parts.push(`ok: { ${ok.join(", ")} }`);
|
|
772
|
+
if (found.rejectClose) parts.push(`rejectClose: ${found.rejectClose}`);
|
|
773
|
+
return {
|
|
774
|
+
code: `DialogV2.prompt({ ${parts.join(", ")} })`,
|
|
775
|
+
missing
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Replace each `<pattern>({...}[, more])` whose first argument is a readable
|
|
780
|
+
* object literal; leave the rest as written with a TODO above it.
|
|
781
|
+
*/
|
|
782
|
+
function rewriteCalls(code, pattern, read, label, todos) {
|
|
783
|
+
const masked = maskComments(code, { strings: true });
|
|
784
|
+
const hits = [];
|
|
785
|
+
for (const m of code.matchAll(pattern)) {
|
|
786
|
+
const start = m.index ?? 0;
|
|
787
|
+
if (masked[start] === "\0") continue;
|
|
788
|
+
const open = start + m[0].length - 1;
|
|
789
|
+
const end = closingParen(code, open);
|
|
790
|
+
if (end === -1) continue;
|
|
791
|
+
const args = code.slice(open + 1, end - 1);
|
|
792
|
+
const firstBrace = args.indexOf("{");
|
|
793
|
+
const firstEnd = firstBrace === -1 ? -1 : closingParen(args, firstBrace);
|
|
794
|
+
const argsInner = firstEnd === -1 || args.slice(0, firstBrace).trim() !== "" ? null : innerOf(args.slice(firstBrace, firstEnd));
|
|
795
|
+
const secondArg = firstEnd !== -1 && /^\s*,\s*\S/.test(args.slice(firstEnd));
|
|
796
|
+
const lineStart = code.lastIndexOf("\n", start - 1) + 1;
|
|
797
|
+
const indent = /^[ \t]*/.exec(code.slice(lineStart))?.[0] ?? "";
|
|
798
|
+
const result = argsInner === null ? null : read(argsInner, indent);
|
|
799
|
+
if (result && secondArg) result.missing.push("the second argument (the Application options)");
|
|
800
|
+
let renderEnd = end;
|
|
801
|
+
let trailingRender = false;
|
|
802
|
+
const after = /^\s*\.render\((?:true)?\)/.exec(code.slice(end));
|
|
803
|
+
if (after) {
|
|
804
|
+
renderEnd = end + after[0].length;
|
|
805
|
+
trailingRender = true;
|
|
806
|
+
}
|
|
807
|
+
hits.push({
|
|
808
|
+
start,
|
|
809
|
+
end: renderEnd,
|
|
810
|
+
read: result,
|
|
811
|
+
trailingRender
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
let out = code;
|
|
815
|
+
for (const hit of hits.reverse()) {
|
|
816
|
+
if (hit.read === null) {
|
|
817
|
+
out = todoAt(out, hit.start, `${label} here could not be read; rewrite it on DialogV2 by hand (${NEW_DIALOG_MSG})`);
|
|
818
|
+
todos.unshift(`${label} here could not be read; rewrite it on DialogV2 by hand (${NEW_DIALOG_MSG})`);
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
out = `${out.slice(0, hit.start)}${hit.read.code}${out.slice(hit.end)}`;
|
|
822
|
+
if (hit.read.missing.length > 0) {
|
|
823
|
+
const msg = `${label} options left behind: ${hit.read.missing.join(", ")}; move them onto the DialogV2 call by hand`;
|
|
824
|
+
out = todoAt(out, hit.start, msg);
|
|
825
|
+
todos.unshift(msg);
|
|
826
|
+
}
|
|
827
|
+
if (label === "new Dialog" && !hit.trailingRender) {
|
|
828
|
+
out = todoAt(out, hit.start, NEW_DIALOG_WAIT_NOTE);
|
|
829
|
+
todos.unshift(NEW_DIALOG_WAIT_NOTE);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
return out;
|
|
833
|
+
}
|
|
590
834
|
function rewriteDialogs(code) {
|
|
591
835
|
const todos = [];
|
|
592
836
|
const confirmMask = maskComments(code, { strings: true });
|
|
@@ -614,16 +858,8 @@ function rewriteDialogs(code) {
|
|
|
614
858
|
todos.unshift(msg);
|
|
615
859
|
}
|
|
616
860
|
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
for (const m of out.matchAll(NEW_DIALOG)) {
|
|
620
|
-
const at = m.index ?? 0;
|
|
621
|
-
if (dialogMask[at] !== "\0") starts.push(at);
|
|
622
|
-
}
|
|
623
|
-
for (const at of starts.reverse()) {
|
|
624
|
-
out = todoAt(out, at, NEW_DIALOG_MSG);
|
|
625
|
-
todos.push(NEW_DIALOG_MSG);
|
|
626
|
-
}
|
|
861
|
+
out = rewriteCalls(out, /\bDialog\.prompt\s*\(/g, (inner) => readPromptOptions(inner), "Dialog.prompt", todos);
|
|
862
|
+
out = rewriteCalls(out, NEW_DIALOG, (inner, indent) => readDialogOptions(inner, indent), "new Dialog", todos);
|
|
627
863
|
return {
|
|
628
864
|
code: out,
|
|
629
865
|
todos
|
|
@@ -843,8 +1079,11 @@ function props(obj) {
|
|
|
843
1079
|
}
|
|
844
1080
|
return out;
|
|
845
1081
|
}
|
|
1082
|
+
/** A string literal, or a template literal with nothing interpolated. */
|
|
846
1083
|
function str(e) {
|
|
847
|
-
|
|
1084
|
+
if (e.type === "StringLiteral") return e.value;
|
|
1085
|
+
if (e.type === "TemplateLiteral" && e.expressions.length === 0) return e.quasis.map((q) => q.value.cooked ?? q.value.raw).join("");
|
|
1086
|
+
return null;
|
|
848
1087
|
}
|
|
849
1088
|
function num(e) {
|
|
850
1089
|
return e.type === "NumericLiteral" ? e.value : null;
|
|
@@ -873,8 +1112,12 @@ function extractOptions(cls, source) {
|
|
|
873
1112
|
classes: null,
|
|
874
1113
|
width: null,
|
|
875
1114
|
height: null,
|
|
1115
|
+
heightAuto: false,
|
|
876
1116
|
resizable: null,
|
|
877
1117
|
submitOnChange: null,
|
|
1118
|
+
closeOnSubmit: null,
|
|
1119
|
+
id: null,
|
|
1120
|
+
title: null,
|
|
878
1121
|
template: null,
|
|
879
1122
|
templateGetter: methodOf(cls.node, "template", {
|
|
880
1123
|
kind: "get",
|
|
@@ -882,7 +1125,8 @@ function extractOptions(cls, source) {
|
|
|
882
1125
|
}),
|
|
883
1126
|
tabs: [],
|
|
884
1127
|
dragDrop: null,
|
|
885
|
-
unknown: []
|
|
1128
|
+
unknown: [],
|
|
1129
|
+
usesThis: false
|
|
886
1130
|
};
|
|
887
1131
|
const method = methodOf(cls.node, "defaultOptions", {
|
|
888
1132
|
static: true,
|
|
@@ -890,6 +1134,7 @@ function extractOptions(cls, source) {
|
|
|
890
1134
|
});
|
|
891
1135
|
const literal = method ? optionsLiteral(method) : null;
|
|
892
1136
|
if (!literal) return out;
|
|
1137
|
+
out.usesThis = /\bthis\b/.test(text(source, literal));
|
|
893
1138
|
for (const [key, value] of props(literal)) switch (key) {
|
|
894
1139
|
case "classes":
|
|
895
1140
|
out.classes = text(source, value);
|
|
@@ -899,6 +1144,16 @@ function extractOptions(cls, source) {
|
|
|
899
1144
|
break;
|
|
900
1145
|
case "height":
|
|
901
1146
|
out.height = num(value);
|
|
1147
|
+
out.heightAuto = str(value) === "auto";
|
|
1148
|
+
break;
|
|
1149
|
+
case "closeOnSubmit":
|
|
1150
|
+
out.closeOnSubmit = bool(value);
|
|
1151
|
+
break;
|
|
1152
|
+
case "id":
|
|
1153
|
+
out.id = text(source, value);
|
|
1154
|
+
break;
|
|
1155
|
+
case "title":
|
|
1156
|
+
out.title = text(source, value);
|
|
902
1157
|
break;
|
|
903
1158
|
case "resizable":
|
|
904
1159
|
out.resizable = bool(value);
|
|
@@ -936,28 +1191,38 @@ function readTabs(value) {
|
|
|
936
1191
|
return tabs;
|
|
937
1192
|
}
|
|
938
1193
|
const q = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
939
|
-
function renderStatics(opts, tabIds, todo) {
|
|
1194
|
+
function renderStatics(opts, tabIds, todo, kind = "sheet", className) {
|
|
1195
|
+
if (kind === "form" && !className) throw new Error("renderStatics needs the class name to wire form.handler");
|
|
940
1196
|
const lines = [];
|
|
941
1197
|
lines.push(" /** @override */");
|
|
942
1198
|
lines.push(" static DEFAULT_OPTIONS = foundry.utils.mergeObject(");
|
|
943
1199
|
lines.push(" super.DEFAULT_OPTIONS,");
|
|
944
1200
|
lines.push(" {");
|
|
1201
|
+
if (kind !== "sheet" && opts.id) lines.push(` id: ${opts.id},`);
|
|
945
1202
|
if (opts.classes) lines.push(` classes: ${opts.classes},`);
|
|
946
|
-
if (
|
|
947
|
-
|
|
1203
|
+
if (kind === "form") lines.push(` tag: 'form',`);
|
|
1204
|
+
if (opts.width !== null || opts.height !== null || opts.heightAuto) {
|
|
1205
|
+
const parts = [opts.width !== null ? `width: ${opts.width}` : "", opts.height !== null ? `height: ${opts.height}` : opts.heightAuto ? `height: 'auto'` : ""].filter(Boolean);
|
|
948
1206
|
lines.push(` position: { ${parts.join(", ")} },`);
|
|
949
1207
|
}
|
|
950
|
-
|
|
951
|
-
lines.push(`
|
|
1208
|
+
const win = [kind !== "sheet" && opts.title ? `title: ${opts.title}` : "", opts.resizable !== null ? `resizable: ${opts.resizable}` : ""].filter(Boolean);
|
|
1209
|
+
if (win.length > 0) lines.push(` window: { ${win.join(", ")} },`);
|
|
1210
|
+
if (kind === "sheet") lines.push(` form: { submitOnChange: ${opts.submitOnChange ?? true} },`);
|
|
1211
|
+
if (kind === "form") lines.push(` form: { handler: ${className}.formHandler, submitOnChange: ${opts.submitOnChange ?? false}, closeOnSubmit: ${opts.closeOnSubmit ?? true} },`);
|
|
952
1212
|
lines.push(" actions: {}, // filled below");
|
|
953
1213
|
lines.push(" },");
|
|
954
1214
|
lines.push(" { inplace: false },");
|
|
955
1215
|
lines.push(" );");
|
|
1216
|
+
if (opts.usesThis) lines.push(` ${todo("defaultOptions read `this`, which was the subclass each time the getter ran; a static field runs once on the class that declares it. Move what depends on the subclass into _initializeApplicationOptions(options)")}`);
|
|
956
1217
|
for (const key of opts.unknown) lines.push(` ${todo(`${key} from defaultOptions has no V2 equivalent here; move it by hand or drop it`)}`);
|
|
957
1218
|
if (opts.tabs.length > 0) {
|
|
958
1219
|
lines.push("", " /** @override */", " static TABS = {");
|
|
959
1220
|
for (const [i, tab] of opts.tabs.entries()) {
|
|
960
|
-
|
|
1221
|
+
if (i > 0) {
|
|
1222
|
+
lines.push(` ${todo(`${tab.navSelector} is a second tab group; add it here and put data-group on its nav links and panes`)}`);
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
const group = "primary";
|
|
961
1226
|
const ids = tabIds[tab.navSelector] ?? [];
|
|
962
1227
|
const initial = tab.initial ?? ids[0] ?? "";
|
|
963
1228
|
if (ids.length === 0) lines.push(` ${todo(`tab ids for ${tab.navSelector} were not found in the template; list them here`)}`);
|
|
@@ -966,9 +1231,10 @@ function renderStatics(opts, tabIds, todo) {
|
|
|
966
1231
|
lines.push(" };");
|
|
967
1232
|
}
|
|
968
1233
|
if (opts.dragDrop) lines.push("", " /** @override */", ` static DRAG_DROP = ${opts.dragDrop};`);
|
|
1234
|
+
const part = kind === "sheet" ? "sheet" : kind === "form" ? "form" : "content";
|
|
969
1235
|
lines.push("", " /** @override */", " static PARTS = {");
|
|
970
|
-
if (opts.template) lines.push(`
|
|
971
|
-
else lines.push(` ${todo("the template is chosen at runtime (get template); name one part per type here or override _configureRenderParts")}`, `
|
|
1236
|
+
if (opts.template) lines.push(` ${part}: { template: ${q(opts.template)} },`);
|
|
1237
|
+
else lines.push(` ${todo("the template is chosen at runtime (get template); name one part per type here or override _configureRenderParts")}`, ` ${part}: { template: '' },`);
|
|
972
1238
|
lines.push(" };");
|
|
973
1239
|
return lines.join("\n");
|
|
974
1240
|
}
|
|
@@ -1072,7 +1338,9 @@ function isExported(source, cls) {
|
|
|
1072
1338
|
return /export\s+(?:default\s+)?$/.test(before) || new RegExp(`export\\s+\\{[^}]*\\b${cls.name}\\b`).test(source);
|
|
1073
1339
|
}
|
|
1074
1340
|
function planClass(cls, source, tabIds) {
|
|
1075
|
-
const
|
|
1341
|
+
const isSheet = cls.base === "ActorSheet" || cls.base === "ItemSheet";
|
|
1342
|
+
const base = cls.base === "ActorSheet" ? "BaseActorSheet" : cls.base === "ItemSheet" ? "BaseItemSheet" : "ApplicationV2";
|
|
1343
|
+
const kind = isSheet ? "sheet" : cls.base === "FormApplication" ? "form" : "app";
|
|
1076
1344
|
const own = cls.base === "ActorSheet" ? "actor" : "item";
|
|
1077
1345
|
const options = extractOptions(cls, source);
|
|
1078
1346
|
const listeners = extractListeners(cls, source);
|
|
@@ -1086,42 +1354,49 @@ function planClass(cls, source, tabIds) {
|
|
|
1086
1354
|
for (const t of options.tabs) navs.add(t.navSelector);
|
|
1087
1355
|
const members = [];
|
|
1088
1356
|
const todo = (msg) => TODO(msg);
|
|
1357
|
+
const memberNames = new Set(cls.node.body.body.flatMap((m) => (m.type === "ClassMethod" || m.type === "ClassProperty") && m.key.type === "Identifier" ? [m.key.name] : []));
|
|
1358
|
+
const inlineMethodName = (name) => {
|
|
1359
|
+
const plain = `_on${pascal(name)}`;
|
|
1360
|
+
return memberNames.has(plain) ? `${plain}Action` : plain;
|
|
1361
|
+
};
|
|
1089
1362
|
const actionEntries = listeners.actions.map((a) => ({
|
|
1090
1363
|
name: a.name,
|
|
1091
1364
|
selector: a.selector,
|
|
1092
|
-
method: a.kind === "method" && a.method ? a.method :
|
|
1365
|
+
method: a.kind === "method" && a.method ? a.method : inlineMethodName(a.name)
|
|
1093
1366
|
}));
|
|
1094
1367
|
const actionsBlock = actionEntries.length === 0 ? " actions: {}," : ` actions: {\n${actionEntries.map((a) => ` ${a.name}: ${cls.name}.prototype.${a.method},`).join("\n")}\n },`;
|
|
1095
1368
|
const statics = options.templateGetter ? {
|
|
1096
1369
|
...options,
|
|
1097
1370
|
template: null
|
|
1098
1371
|
} : options;
|
|
1099
|
-
members.push(renderStatics(statics, tabIds, todo).replace(ACTIONS_PLACEHOLDER, actionsBlock));
|
|
1100
|
-
if (!methodOf(cls.node, own, { kind: "get" })) members.push(` get ${own}() {\n return this.document;\n }`);
|
|
1372
|
+
members.push(renderStatics(statics, tabIds, todo, kind, cls.name).replace(ACTIONS_PLACEHOLDER, actionsBlock));
|
|
1373
|
+
if (isSheet && !methodOf(cls.node, own, { kind: "get" })) members.push(` get ${own}() {\n return this.document;\n }`);
|
|
1374
|
+
const usesObject = /\bthis\.object\b/.test(text(source, cls.node));
|
|
1375
|
+
if (cls.base === "FormApplication" && usesObject) members.push(` ${todo("FormApplication carried the edited value as this.object; ApplicationV2 does not. Take it in the constructor and keep it on a field: constructor(object, options) { super(options); this.object = object; }")}`);
|
|
1101
1376
|
if (options.templateGetter) members.push(reindent(text(source, options.templateGetter)));
|
|
1102
1377
|
const getData = methodOf(cls.node, "getData");
|
|
1103
|
-
if (getData) members.push(rewriteGetData(reindent(text(source, getData)), cls.base).code);
|
|
1378
|
+
if (getData) members.push(rewriteGetData(reindent(text(source, getData)), cls.base, { usesObject }).code);
|
|
1379
|
+
const applyDialogs = (code) => {
|
|
1380
|
+
const d = rewriteDialogs(code);
|
|
1381
|
+
if (/DialogV2\./.test(d.code)) usesDialogV2 = true;
|
|
1382
|
+
return d.code;
|
|
1383
|
+
};
|
|
1104
1384
|
if (listeners.listeners.length > 0) {
|
|
1105
1385
|
const body = listeners.listeners.map((l) => {
|
|
1106
1386
|
const param = /^\s*(?:async\s+)?\(?\s*(\w+)/.exec(l.handlerText)?.[1] ?? null;
|
|
1107
|
-
const handler = /^\s*(?:async\s+)?(?:\(|\w+\s*=>|function\b)/.test(l.handlerText) ? indentTo(rewriteHandlerBody(l.handlerText, param, listeners.htmlParam, param ? `${param}.currentTarget` : "target").code, 6) : l.handlerText;
|
|
1387
|
+
const handler = /^\s*(?:async\s+)?(?:\(|\w+\s*=>|function\b)/.test(l.handlerText) ? indentTo(rewriteHandlerBody(applyDialogs(l.handlerText), param, listeners.htmlParam, param ? `${param}.currentTarget` : "target").code, 6) : l.handlerText;
|
|
1108
1388
|
return ` for (const el of this.element.querySelectorAll(${single(l.selector)})) {\n el.addEventListener(${single(l.event)}, ${handler});\n }`;
|
|
1109
1389
|
}).join("\n");
|
|
1110
|
-
members.push(` /** @override */\n _onRender(context, options) {\n super._onRender(context, options);\n${body}\n }`);
|
|
1390
|
+
members.push(` /** @override */\n async _onRender(context, options) {\n await super._onRender(context, options);\n${body}\n }`);
|
|
1111
1391
|
}
|
|
1112
1392
|
const handlerNames = new Set(listeners.actions.filter((a) => a.kind === "method" && a.method).map((a) => a.method));
|
|
1113
1393
|
const listenerTargets = new Set(listeners.listeners.flatMap((l) => [...l.handlerText.matchAll(/this\.(\w+)/g)].map((m) => m[1] ?? "")));
|
|
1114
|
-
const applyDialogs = (code) => {
|
|
1115
|
-
const d = rewriteDialogs(code);
|
|
1116
|
-
if (/DialogV2\./.test(d.code)) usesDialogV2 = true;
|
|
1117
|
-
return d.code;
|
|
1118
|
-
};
|
|
1119
1394
|
for (const member of cls.node.body.body) {
|
|
1120
1395
|
if (member.type !== "ClassMethod" && member.type !== "ClassProperty" && member.type !== "ClassPrivateMethod") continue;
|
|
1121
1396
|
const name = member.type === "ClassMethod" ? methodName(member) : null;
|
|
1122
1397
|
if (name && HANDLED.has(name)) continue;
|
|
1123
1398
|
if (name === "template" && member.type === "ClassMethod" && member.kind === "get") continue;
|
|
1124
|
-
let code = reindent(text(source, member));
|
|
1399
|
+
let code = applyDialogs(reindent(text(source, member)));
|
|
1125
1400
|
if (name && handlerNames.has(name)) {
|
|
1126
1401
|
const sig = handlerSignature(code, name);
|
|
1127
1402
|
code = rewriteHandlerBody(sig.code, sig.eventParam, null).code;
|
|
@@ -1130,24 +1405,27 @@ function planClass(cls, source, tabIds) {
|
|
|
1130
1405
|
code = rewriteHandlerBody(code, ev, null, ev ? `${ev}.currentTarget` : "target").code;
|
|
1131
1406
|
} else if (member.type === "ClassMethod") code = rewriteHandlerBody(code, null, null).code;
|
|
1132
1407
|
if (name && V1_LIFECYCLE.has(name)) code = ` ${todo(`${name} is an Application v1 lifecycle override; ApplicationV2 sizes, submits and builds its header itself. Review it against the V2 method of the same job, or delete it`)}\n${code}`;
|
|
1133
|
-
if (name === "_updateObject") code = ` ${todo("_updateObject is gone on V2; DocumentSheetV2 submits the form itself. Move any shaping into _prepareSubmitData or delete this")}\n${code}
|
|
1134
|
-
members.push(
|
|
1408
|
+
if (name === "_updateObject") code = isSheet ? ` ${todo("_updateObject is gone on V2; DocumentSheetV2 submits the form itself. Move any shaping into _prepareSubmitData or delete this")}\n${code}` : rewriteUpdateObject(code).code;
|
|
1409
|
+
members.push(code);
|
|
1135
1410
|
}
|
|
1136
1411
|
for (const which of ["Item", "Actor"]) {
|
|
1137
1412
|
const m = methodOf(cls.node, `_onDrop${which}`);
|
|
1138
1413
|
if (!m) continue;
|
|
1139
|
-
members.push(applyDialogs(rewriteDropMethod(reindent(text(source, m)), which).code));
|
|
1414
|
+
if (cls.base === "ActorSheet") members.push(applyDialogs(rewriteDropMethod(reindent(text(source, m)), which).code));
|
|
1415
|
+
else members.push(` ${todo(`_onDrop${which} only runs on an actor sheet; ItemSheetV2 dispatches active-effect drops alone. Move this logic or delete it`)}\n${reindent(text(source, m))}`);
|
|
1140
1416
|
}
|
|
1141
1417
|
const inline = listeners.actions.filter((a) => a.kind === "inline");
|
|
1142
1418
|
for (const a of inline) {
|
|
1143
|
-
const method =
|
|
1144
|
-
const rewritten = applyDialogs(
|
|
1419
|
+
const method = inlineMethodName(a.name);
|
|
1420
|
+
const rewritten = rewriteHandlerBody(applyDialogs(a.body ?? "{}"), a.param, null).code.trim();
|
|
1145
1421
|
const body = rewritten.startsWith("{") ? dedentBlock(rewritten) : `{\n return ${rewritten};\n }`;
|
|
1146
1422
|
members.push(` ${a.isAsync ? "async " : ""}${method}(${a.param ?? "event"}, target) ${body}`);
|
|
1147
1423
|
}
|
|
1148
1424
|
for (const l of listeners.leftovers) members.push(` ${todo(`from activateListeners, line ${l.line}: ${l.text.replace(/\s+/g, " ")}`)}`);
|
|
1425
|
+
const exported = isExported(source, cls);
|
|
1426
|
+
const extendsExpr = isSheet ? `${base}()` : "HandlebarsApplicationMixin(ApplicationV2)";
|
|
1149
1427
|
return {
|
|
1150
|
-
block: `${
|
|
1428
|
+
block: `${exported ? "export " : ""}class ${cls.name} extends ${extendsExpr} {\n${members.join("\n\n")}\n}`,
|
|
1151
1429
|
base,
|
|
1152
1430
|
actions: actionEntries,
|
|
1153
1431
|
templates: [...templates],
|
|
@@ -1159,7 +1437,7 @@ function planSheetFile(relPath, source, opts) {
|
|
|
1159
1437
|
const lang = relPath.endsWith(".ts") ? "ts" : opts.lang;
|
|
1160
1438
|
const ast = parseSource(source, lang);
|
|
1161
1439
|
const classes = findSheetClasses(ast, source);
|
|
1162
|
-
const notes = unsupportedBases(ast, source).map((u) => `${relPath}:${u.line} ${u.name} extends ${u.superText};
|
|
1440
|
+
const notes = unsupportedBases(ast, source).map((u) => `${relPath}:${u.line} ${u.name} extends ${u.superText}; Dialog and DocumentSheet subclasses are not converted, this one stays as it is`);
|
|
1163
1441
|
if (classes.length === 0) return {
|
|
1164
1442
|
files: [],
|
|
1165
1443
|
notes
|
|
@@ -1170,8 +1448,13 @@ function planSheetFile(relPath, source, opts) {
|
|
|
1170
1448
|
cls,
|
|
1171
1449
|
out: planClass(cls, source, opts.tabIds)
|
|
1172
1450
|
}));
|
|
1173
|
-
const
|
|
1174
|
-
|
|
1451
|
+
const sdkBases = [...new Set(outputs.map((o) => o.out.base).filter((b) => b !== "ApplicationV2"))];
|
|
1452
|
+
const header = [...sdkBases.length > 0 ? [`import { ${sdkBases.join(", ")} } from '@vttforge/core';`] : [], ...importLines(source, lang)];
|
|
1453
|
+
const fromApi = [...outputs.some((o) => o.out.base === "ApplicationV2") ? ["ApplicationV2", "HandlebarsApplicationMixin"] : [], ...outputs.some((o) => o.out.usesDialogV2) ? ["DialogV2"] : []].sort();
|
|
1454
|
+
if (fromApi.length > 0) {
|
|
1455
|
+
if (header.length > 0) header.push("");
|
|
1456
|
+
header.push(`const { ${fromApi.join(", ")} } = foundry.applications.api;`);
|
|
1457
|
+
}
|
|
1175
1458
|
const fileSource = `${header.join("\n")}\n\n${outputs.map((o) => o.out.block).join("\n\n")}\n`;
|
|
1176
1459
|
const marker = "TODO(migrate): ";
|
|
1177
1460
|
const todos = fileSource.split("\n").flatMap((line, i) => {
|
|
@@ -1771,7 +2054,9 @@ function transformManifest(raw, kind) {
|
|
|
1771
2054
|
const indent = output.slice(lineStart, idKey.keyStart);
|
|
1772
2055
|
const after = output.indexOf("\n", idKey.valueEnd);
|
|
1773
2056
|
const insertAt = after === -1 ? output.length : after;
|
|
1774
|
-
|
|
2057
|
+
const rest = output.slice(idKey.valueEnd, insertAt);
|
|
2058
|
+
if (/^\s*,?\s*$/.test(rest)) output = `${!/,\s*$/.test(rest) ? `${output.slice(0, idKey.valueEnd)},${rest}` : output.slice(0, insertAt)}\n${indent}"type": "${kind}",${output.slice(insertAt)}`;
|
|
2059
|
+
else output = `${output.slice(0, idKey.valueEnd)}, "type": "${kind}"${output.slice(idKey.valueEnd)}`;
|
|
1775
2060
|
changes.push({
|
|
1776
2061
|
line: lineAt(raw, idKey.keyStart) + 1,
|
|
1777
2062
|
before: "(no \"type\")",
|
|
@@ -1911,11 +2196,21 @@ function topLevelKey(json, key) {
|
|
|
1911
2196
|
* written unless asked: the preview is the default, because a text rewrite
|
|
1912
2197
|
* that touched a string literal is something to see before it lands.
|
|
1913
2198
|
*/
|
|
2199
|
+
/**
|
|
2200
|
+
* The lines the report prints as "needs a decision": the rewrites the run did
|
|
2201
|
+
* not make, the TODO lines in generated files, and what the generators could
|
|
2202
|
+
* not decide. `--strict` fails the run when any is left. A note that only says
|
|
2203
|
+
* what happened (a file left alone, where to point registerSheet) is not one.
|
|
2204
|
+
*/
|
|
2205
|
+
function countDecisions(report) {
|
|
2206
|
+
return report.counts.notes + (report.dataModels?.decisions.length ?? 0) + (report.sheets?.files.reduce((n, f) => n + f.todos.length, 0) ?? 0) + (report.sheets?.decisions.length ?? 0);
|
|
2207
|
+
}
|
|
1914
2208
|
async function runMigrate(options) {
|
|
1915
2209
|
const { cwd } = options;
|
|
1916
2210
|
const write = options.write === true;
|
|
1917
2211
|
if (!existsSync(cwd) || !(await stat(cwd)).isDirectory()) throw new Error(`Migrate target is not a directory: ${cwd}`);
|
|
1918
2212
|
const files = [];
|
|
2213
|
+
const pending = [];
|
|
1919
2214
|
for (const [name, kind] of [["system.json", "system"], ["module.json", "module"]]) {
|
|
1920
2215
|
const path = join(cwd, name);
|
|
1921
2216
|
if (!existsSync(path)) continue;
|
|
@@ -1933,7 +2228,10 @@ async function runMigrate(options) {
|
|
|
1933
2228
|
changes: result.changes,
|
|
1934
2229
|
notes: result.notes
|
|
1935
2230
|
});
|
|
1936
|
-
if (write && result.changes.length > 0)
|
|
2231
|
+
if (write && result.changes.length > 0) pending.push({
|
|
2232
|
+
path,
|
|
2233
|
+
content: result.output
|
|
2234
|
+
});
|
|
1937
2235
|
}
|
|
1938
2236
|
for await (const path of _internal.walkSourceFiles(cwd)) {
|
|
1939
2237
|
let source;
|
|
@@ -1949,7 +2247,10 @@ async function runMigrate(options) {
|
|
|
1949
2247
|
changes: result.changes,
|
|
1950
2248
|
notes: result.notes
|
|
1951
2249
|
});
|
|
1952
|
-
if (write && result.output !== source)
|
|
2250
|
+
if (write && result.output !== source) pending.push({
|
|
2251
|
+
path,
|
|
2252
|
+
content: result.output
|
|
2253
|
+
});
|
|
1953
2254
|
}
|
|
1954
2255
|
for (const finding of await runReleaseRules(cwd)) files.push({
|
|
1955
2256
|
file: finding.filePath,
|
|
@@ -1977,7 +2278,8 @@ async function runMigrate(options) {
|
|
|
1977
2278
|
files: [],
|
|
1978
2279
|
documentTypes: {},
|
|
1979
2280
|
registration: "",
|
|
1980
|
-
notes: ["No template.json here; nothing to generate."]
|
|
2281
|
+
notes: ["No template.json here; nothing to generate."],
|
|
2282
|
+
decisions: []
|
|
1981
2283
|
};
|
|
1982
2284
|
else {
|
|
1983
2285
|
const plan = planDataModels(JSON.parse(await readFile(templatePath, "utf8")), {
|
|
@@ -1985,42 +2287,39 @@ async function runMigrate(options) {
|
|
|
1985
2287
|
lang: options.lang ?? "js"
|
|
1986
2288
|
});
|
|
1987
2289
|
const written = [];
|
|
2290
|
+
const info = [];
|
|
1988
2291
|
for (const file of plan.files) {
|
|
1989
2292
|
const target = join(cwd, file.path);
|
|
1990
2293
|
if (existsSync(target)) {
|
|
1991
|
-
|
|
2294
|
+
info.push(`${file.path} exists and was left alone.`);
|
|
1992
2295
|
continue;
|
|
1993
2296
|
}
|
|
1994
|
-
if (write) {
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
}
|
|
2297
|
+
if (write) pending.push({
|
|
2298
|
+
path: target,
|
|
2299
|
+
content: file.source
|
|
2300
|
+
});
|
|
1998
2301
|
written.push(file.path);
|
|
1999
2302
|
}
|
|
2000
2303
|
report.dataModels = {
|
|
2001
2304
|
files: written,
|
|
2002
2305
|
documentTypes: plan.documentTypes,
|
|
2003
2306
|
registration: plan.registration,
|
|
2004
|
-
notes:
|
|
2307
|
+
notes: info,
|
|
2308
|
+
decisions: plan.notes
|
|
2005
2309
|
};
|
|
2006
2310
|
}
|
|
2007
2311
|
}
|
|
2008
|
-
if (options.sheets) report.sheets = await planSheets(cwd, write, options.lang ?? "js");
|
|
2312
|
+
if (options.sheets) report.sheets = await planSheets(cwd, write, options.lang ?? "js", pending);
|
|
2313
|
+
for (const { path, content } of pending) {
|
|
2314
|
+
await mkdir(dirname(path), { recursive: true });
|
|
2315
|
+
await writeFile(path, content, "utf8");
|
|
2316
|
+
}
|
|
2009
2317
|
return report;
|
|
2010
2318
|
}
|
|
2011
|
-
/** Every `.hbs` / `.html`
|
|
2319
|
+
/** Every `.hbs` / `.html` in the project, project-relative. */
|
|
2012
2320
|
async function allTemplates(cwd) {
|
|
2013
|
-
const root = join(cwd, "templates");
|
|
2014
|
-
if (!existsSync(root)) return [];
|
|
2015
2321
|
const out = [];
|
|
2016
|
-
const
|
|
2017
|
-
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
2018
|
-
const full = join(dir, entry.name);
|
|
2019
|
-
if (entry.isDirectory()) await visit(full);
|
|
2020
|
-
else if (/\.(?:hbs|html)$/.test(entry.name)) out.push(relative(cwd, full));
|
|
2021
|
-
}
|
|
2022
|
-
};
|
|
2023
|
-
await visit(root);
|
|
2322
|
+
for await (const file of _internal.walkTemplateFiles(cwd)) out.push(relative(cwd, file));
|
|
2024
2323
|
return out.sort();
|
|
2025
2324
|
}
|
|
2026
2325
|
/** Project-relative path for a Foundry template path such as `systems/<id>/templates/x.html`. */
|
|
@@ -2028,10 +2327,11 @@ function localTemplate(cwd, foundryPath) {
|
|
|
2028
2327
|
const rel = /^(?:systems|modules)\/[^/]+\/(.+)$/.exec(foundryPath)?.[1] ?? foundryPath;
|
|
2029
2328
|
return existsSync(join(cwd, rel)) ? rel : null;
|
|
2030
2329
|
}
|
|
2031
|
-
async function planSheets(cwd, write, lang) {
|
|
2330
|
+
async function planSheets(cwd, write, lang, pending) {
|
|
2032
2331
|
const files = [];
|
|
2033
2332
|
const templates = [];
|
|
2034
2333
|
const notes = [];
|
|
2334
|
+
const decisions = [];
|
|
2035
2335
|
const generated = /* @__PURE__ */ new Map();
|
|
2036
2336
|
for await (const path of _internal.walkSourceFiles(cwd)) {
|
|
2037
2337
|
const rel = relative(cwd, path);
|
|
@@ -2042,7 +2342,7 @@ async function planSheets(cwd, write, lang) {
|
|
|
2042
2342
|
} catch {
|
|
2043
2343
|
continue;
|
|
2044
2344
|
}
|
|
2045
|
-
if (!/\
|
|
2345
|
+
if (!/\bextends\s+(?:foundry\.appv1\.\w+\.)?(?:ActorSheet|ItemSheet|FormApplication|Application)\b/.test(raw)) continue;
|
|
2046
2346
|
const source = transformSource(raw).output;
|
|
2047
2347
|
let probe;
|
|
2048
2348
|
try {
|
|
@@ -2052,16 +2352,17 @@ async function planSheets(cwd, write, lang) {
|
|
|
2052
2352
|
});
|
|
2053
2353
|
} catch (error) {
|
|
2054
2354
|
const reason = error instanceof Error ? error.message : String(error);
|
|
2055
|
-
|
|
2355
|
+
decisions.push(`${rel} could not be parsed and was skipped: ${reason}`);
|
|
2056
2356
|
continue;
|
|
2057
2357
|
}
|
|
2058
|
-
|
|
2358
|
+
decisions.push(...probe.notes);
|
|
2059
2359
|
if (probe.files.length === 0) continue;
|
|
2060
2360
|
let templatePaths = [...new Set(probe.files.flatMap((f) => f.templates))].map((t) => localTemplate(cwd, t)).filter((t) => t !== null);
|
|
2061
2361
|
if (templatePaths.length === 0) {
|
|
2062
2362
|
const every = await allTemplates(cwd);
|
|
2063
|
-
const
|
|
2064
|
-
|
|
2363
|
+
const first = probe.files[0]?.base;
|
|
2364
|
+
const other = first === "BaseItemSheet" ? /(?:^|\/)actors?\//i : first === "BaseActorSheet" ? /(?:^|\/)items?\//i : null;
|
|
2365
|
+
templatePaths = other ? every.filter((t) => !other.test(t)) : every;
|
|
2065
2366
|
}
|
|
2066
2367
|
const navSelectors = [...new Set(probe.files.flatMap((f) => f.tabNavSelectors))];
|
|
2067
2368
|
const tabIds = {};
|
|
@@ -2081,16 +2382,20 @@ async function planSheets(cwd, write, lang) {
|
|
|
2081
2382
|
const { source: out, ...rest } = f;
|
|
2082
2383
|
files.push(rest);
|
|
2083
2384
|
generated.set(f.to, out);
|
|
2084
|
-
notes.push(`
|
|
2385
|
+
notes.push(`Run \`vttforge audit\` again after reading ${f.to}: the v14 rules also apply to the generated file.`);
|
|
2386
|
+
notes.push(f.base === "ApplicationV2" ? `Point whatever constructs ${f.className} (a settings menu, a macro, a button) at ${f.to}, then delete the old class.` : `Point registerSheet at ${f.className} from ${f.to} (a written key such as "<id>.${f.base === "BaseActorSheet" ? "actor" : "item"}"), then delete the old class.`);
|
|
2085
2387
|
}
|
|
2086
2388
|
const actions = plan.files.flatMap((f) => f.actions.map((a) => ({
|
|
2087
2389
|
name: a.name,
|
|
2088
2390
|
selector: a.selector
|
|
2089
2391
|
})));
|
|
2090
2392
|
for (const t of templatePaths) {
|
|
2091
|
-
const
|
|
2393
|
+
const tpl = await readFile(join(cwd, t), "utf8");
|
|
2394
|
+
const primaryNav = navSelectors[0];
|
|
2395
|
+
const r = editTemplate(tpl, {
|
|
2092
2396
|
actions,
|
|
2093
|
-
navSelectors
|
|
2397
|
+
navSelectors,
|
|
2398
|
+
tabIds: primaryNav === void 0 ? void 0 : tabIds[primaryNav]
|
|
2094
2399
|
});
|
|
2095
2400
|
if (r.edits.length === 0) continue;
|
|
2096
2401
|
templates.push({
|
|
@@ -2098,8 +2403,11 @@ async function planSheets(cwd, write, lang) {
|
|
|
2098
2403
|
edits: r.edits,
|
|
2099
2404
|
formRoot: r.formRoot
|
|
2100
2405
|
});
|
|
2101
|
-
if (r.formRoot)
|
|
2102
|
-
if (write && r.edits.length > 0)
|
|
2406
|
+
if (r.formRoot) decisions.push(`${t} opens with <form>; the SDK sheet already is one. Make it a <div> once the old class is gone: a part needs one root element (audit rule 008).`);
|
|
2407
|
+
if (write && r.edits.length > 0) pending.push({
|
|
2408
|
+
path: join(cwd, t),
|
|
2409
|
+
content: r.output
|
|
2410
|
+
});
|
|
2103
2411
|
}
|
|
2104
2412
|
}
|
|
2105
2413
|
for (const [to, out] of generated) {
|
|
@@ -2108,15 +2416,16 @@ async function planSheets(cwd, write, lang) {
|
|
|
2108
2416
|
notes.unshift(`${to} exists and was left alone.`);
|
|
2109
2417
|
continue;
|
|
2110
2418
|
}
|
|
2111
|
-
if (write) {
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
}
|
|
2419
|
+
if (write) pending.push({
|
|
2420
|
+
path: target,
|
|
2421
|
+
content: out
|
|
2422
|
+
});
|
|
2115
2423
|
}
|
|
2116
2424
|
return {
|
|
2117
2425
|
files,
|
|
2118
2426
|
templates,
|
|
2119
|
-
notes: [...new Set(notes)]
|
|
2427
|
+
notes: [...new Set(notes)],
|
|
2428
|
+
decisions: [...new Set(decisions)]
|
|
2120
2429
|
};
|
|
2121
2430
|
}
|
|
2122
2431
|
/** The report as text: one block per file, edits then notes. */
|
|
@@ -2140,14 +2449,15 @@ function formatMigrateReport(report) {
|
|
|
2140
2449
|
for (const f of dm.files) lines.push(` ${f}`);
|
|
2141
2450
|
if (Object.keys(dm.documentTypes).length > 0) lines.push("", "Declare the types in the manifest:", ` "documentTypes": ${JSON.stringify(dm.documentTypes)}`);
|
|
2142
2451
|
if (dm.registration) lines.push("", "Register the models at init:", ...dm.registration.split("\n").map((l) => ` ${l}`));
|
|
2143
|
-
for (const n of dm.notes) lines.push(`
|
|
2452
|
+
for (const n of dm.notes) lines.push(` ${n}`);
|
|
2453
|
+
for (const n of dm.decisions) lines.push(` needs a decision: ${n}`);
|
|
2144
2454
|
}
|
|
2145
2455
|
if (report.sheets) {
|
|
2146
2456
|
const s = report.sheets;
|
|
2147
2457
|
const targets = [...new Set(s.files.map((f) => f.to))];
|
|
2148
2458
|
lines.push("", report.written ? `Wrote ${targets.length} sheet file(s) on the SDK bases:` : `Would write ${targets.length} sheet file(s) on the SDK bases:`);
|
|
2149
2459
|
for (const f of s.files) {
|
|
2150
|
-
lines.push(` ${f.to}: ${f.className} extends ${f.base}()`);
|
|
2460
|
+
lines.push(` ${f.to}: ${f.className} extends ${f.base === "ApplicationV2" ? "HandlebarsApplicationMixin(ApplicationV2)" : `${f.base}()`}`);
|
|
2151
2461
|
for (const a of f.actions) lines.push(` action ${a.name} ← ${a.selector} (${a.method})`);
|
|
2152
2462
|
for (const t of f.todos) lines.push(` ${t.line}: needs a decision: ${t.message}`);
|
|
2153
2463
|
}
|
|
@@ -2158,7 +2468,8 @@ function formatMigrateReport(report) {
|
|
|
2158
2468
|
for (const e of t.edits) lines.push(` ${e.line}: ${oneLine(e.before)}`, ` ${" ".repeat(String(e.line).length)} → ${oneLine(e.after)}`);
|
|
2159
2469
|
}
|
|
2160
2470
|
}
|
|
2161
|
-
for (const n of s.notes) lines.push(`
|
|
2471
|
+
for (const n of s.notes) lines.push(` ${n}`);
|
|
2472
|
+
for (const n of s.decisions) lines.push(` needs a decision: ${n}`);
|
|
2162
2473
|
}
|
|
2163
2474
|
return `${lines.join("\n")}\n`;
|
|
2164
2475
|
}
|
|
@@ -2173,7 +2484,7 @@ function oneLine(text) {
|
|
|
2173
2484
|
*
|
|
2174
2485
|
* Exit codes:
|
|
2175
2486
|
* 0: ran, whether or not anything changed
|
|
2176
|
-
* 1: the target is not a directory
|
|
2487
|
+
* 1: the target is not a directory, or --strict and a decision was left
|
|
2177
2488
|
*/
|
|
2178
2489
|
async function runMigrateCommand(options = {}) {
|
|
2179
2490
|
const cwd = resolve(options.cwd ?? process.cwd());
|
|
@@ -2189,6 +2500,14 @@ async function runMigrateCommand(options = {}) {
|
|
|
2189
2500
|
sheets: options.sheets === true
|
|
2190
2501
|
});
|
|
2191
2502
|
out(options.json ? `${JSON.stringify(report, null, 2)}\n` : formatMigrateReport(report));
|
|
2503
|
+
const decisions = countDecisions(report);
|
|
2504
|
+
if (options.strict === true && decisions > 0) {
|
|
2505
|
+
if (!options.json) out(`--strict: ${decisions} decision(s) left; exiting 1.\n`);
|
|
2506
|
+
return {
|
|
2507
|
+
report,
|
|
2508
|
+
exitCode: 1
|
|
2509
|
+
};
|
|
2510
|
+
}
|
|
2192
2511
|
return {
|
|
2193
2512
|
report,
|
|
2194
2513
|
exitCode: 0
|
|
@@ -2430,6 +2749,11 @@ const migrate = defineCommand({
|
|
|
2430
2749
|
default: false,
|
|
2431
2750
|
description: "Emit the report as JSON"
|
|
2432
2751
|
},
|
|
2752
|
+
strict: {
|
|
2753
|
+
type: "boolean",
|
|
2754
|
+
default: false,
|
|
2755
|
+
description: "Exit 1 when anything is left that needs a decision, for CI"
|
|
2756
|
+
},
|
|
2433
2757
|
"data-models": {
|
|
2434
2758
|
type: "boolean",
|
|
2435
2759
|
default: false,
|
|
@@ -2457,6 +2781,7 @@ const migrate = defineCommand({
|
|
|
2457
2781
|
cwd: args.path ? String(args.path) : void 0,
|
|
2458
2782
|
write: Boolean(args.write),
|
|
2459
2783
|
json: Boolean(args.json),
|
|
2784
|
+
strict: Boolean(args.strict),
|
|
2460
2785
|
dataModels: Boolean(args["data-models"]),
|
|
2461
2786
|
style: String(args.style) === "sdk" ? "sdk" : "plain",
|
|
2462
2787
|
lang: String(args.lang) === "ts" ? "ts" : "js",
|