@vttforge/cli 0.12.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/dist/bin.mjs CHANGED
@@ -1,9 +1,10 @@
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, y as _internal } from "./src-CzzrhCN-.mjs";
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
5
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
6
6
  import { defineCommand, runMain } from "citty";
7
+ import { parse } from "@babel/parser";
7
8
  //#region src/migrate/data-models.ts
8
9
  const RICH_TEXT_KEYS = /^(description|biography|bio|notes|details)$/i;
9
10
  function fieldFor(key, value, path, notes, indent) {
@@ -37,11 +38,11 @@ function fieldFor(key, value, path, notes, indent) {
37
38
  function safeKey(key) {
38
39
  return /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
39
40
  }
40
- function pascal(name) {
41
+ function pascal$1(name) {
41
42
  return name.replace(/(^|[^A-Za-z0-9])([a-z0-9])/g, (_m, _s, c) => c.toUpperCase()).replace(/[^A-Za-z0-9]/g, "");
42
43
  }
43
- function camel(name) {
44
- const p = pascal(name);
44
+ function camel$1(name) {
45
+ const p = pascal$1(name);
45
46
  return p.charAt(0).toLowerCase() + p.slice(1);
46
47
  }
47
48
  function schemaBody(data, path, notes) {
@@ -70,7 +71,7 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
70
71
  if (fragmentNames.length > 0) {
71
72
  const fns = fragmentNames.map((name) => {
72
73
  const body = schemaBody(templates[name] ?? {}, `${document}.templates.${name}`, notes);
73
- return `/** The \`${name}\` template, as the types that listed it spread it. */\nexport function ${camel(name)}Fields(f) {\n return {\n${body}\n };\n}`;
74
+ return `/** The \`${name}\` template, as the types that listed it spread it. */\nexport function ${camel$1(name)}Fields(f) {\n return {\n${body}\n };\n}`;
74
75
  }).join("\n\n");
75
76
  const tsHint = lang === "ts" ? "// @ts-nocheck: the field constructors are typed by the runtime, not by this file\n" : "";
76
77
  files.push({
@@ -82,12 +83,12 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
82
83
  const modelNames = [];
83
84
  for (const type of types) {
84
85
  const own = doc[type] ?? {};
85
- const listed = (own.templates ?? []).filter((t) => t !== "base");
86
- 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.`);
87
- const spreads = listed.filter((t) => t in templates).map((t) => ` ...${camel(t)}Fields(f),`).join("\n");
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
+ const spreads = listed.filter((t) => t in templates).map((t) => ` ...${camel$1(t)}Fields(f),`).join("\n");
88
89
  const body = schemaBody(own, `${document}.${type}`, notes);
89
- const className = `${pascal(type)}Data`;
90
- const importLine = listed.length ? `import { ${listed.filter((t) => t in templates).map((t) => `${camel(t)}Fields`).join(", ")} } from './templates.${ext === "ts" ? "js" : "mjs"}';\n` : "";
90
+ const className = `${pascal$1(type)}Data`;
91
+ const importLine = listed.length ? `import { ${listed.filter((t) => t in templates).map((t) => `${camel$1(t)}Fields`).join(", ")} } from './templates.${ext === "ts" ? "js" : "mjs"}';\n` : "";
91
92
  const schemaFn = `${fieldsLine(style)}\n return {\n${[spreads, body].filter(Boolean).join("\n")}\n };`;
92
93
  const classSource = style === "sdk" ? `${header(style)}${importLine}\n/** The \`${type}\` ${document}, as template.json declared it. */\nfunction define${className}Schema() {\n${schemaFn}\n}\n\nexport class ${className} extends BaseTypeDataModel(define${className}Schema) {\n prepareDerivedData() {\n // Derived values go here. Nothing here writes to the database.\n }\n}\n` : `${importLine}\n/** The \`${type}\` ${document}, as template.json declared it. */\nexport class ${className} extends foundry.abstract.TypeDataModel {\n static defineSchema() {\n${schemaFn.replace(/^/gm, " ")}\n }\n\n prepareDerivedData() {\n // Derived values go here. Nothing here writes to the database.\n }\n}\n`;
93
94
  files.push({
@@ -101,7 +102,7 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
101
102
  modelNames.push(`${type}: ${className}`);
102
103
  registrations.push(`import { ${className} } from './${docDir.replace(/^scripts\//, "")}/${type}-data.${ext === "ts" ? "js" : "mjs"}';`);
103
104
  }
104
- if (types.length) registrations.push(style === "sdk" ? `// registerSystem({ ${document === "Actor" ? "actorDataModels" : document === "Item" ? "itemDataModels" : `${camel(document)}DataModels`}: { ${modelNames.join(", ")} } })` : `// Hooks.once('init', () => Object.assign(CONFIG.${document}.dataModels, { ${modelNames.join(", ")} }));`);
105
+ if (types.length) registrations.push(style === "sdk" ? `// registerSystem({ ${document === "Actor" ? "actorDataModels" : document === "Item" ? "itemDataModels" : `${camel$1(document)}DataModels`}: { ${modelNames.join(", ")} } })` : `// Hooks.once('init', () => Object.assign(CONFIG.${document}.dataModels, { ${modelNames.join(", ")} }));`);
105
106
  }
106
107
  notes.push("When every type has a model, delete template.json: while it exists, Foundry resets each listed type's documentTypes entry on every start.");
107
108
  return {
@@ -112,6 +113,1373 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
112
113
  };
113
114
  }
114
115
  //#endregion
116
+ //#region src/migrate/sheet-templates.ts
117
+ /**
118
+ * One opening tag: the name, the attribute run, and the self-closing slash.
119
+ * Exactly three capture groups — `editTemplate` reads the replacer's `offset`
120
+ * as the fourth argument, so a fourth group would shift every reported line.
121
+ * A fresh regex per call: a shared global one carries `lastIndex` between
122
+ * `readTabIds`, `elementRange` and `String#replace`.
123
+ */
124
+ const tagRe = () => /<([a-zA-Z][\w-]*)((?:\s*\{\{[^{}]*\}\}|\s+[^\s=>/{]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?|(?<=\}\})[^\s=>/{]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*(\/?)>/g;
125
+ /** The value of one attribute in a tag's attribute run, or null when absent. */
126
+ function attr(attrs, name) {
127
+ const m = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`).exec(attrs);
128
+ return m ? m[1] ?? m[2] ?? m[3] ?? "" : null;
129
+ }
130
+ function hasClass(attrs, cls) {
131
+ return (attr(attrs, "class") ?? "").split(/\s+/).includes(cls);
132
+ }
133
+ /** Only `.class` and `#id` selectors match; anything else stays for `_onRender`. */
134
+ function matches(attrs, selector) {
135
+ const m = /^([.#])([A-Za-z_][\w-]*)/.exec(selector.trim());
136
+ if (!m) return false;
137
+ const [, kind = "", name = ""] = m;
138
+ if (!name) return false;
139
+ return kind === "." ? hasClass(attrs, name) : attr(attrs, "id") === name;
140
+ }
141
+ function lineOf(text, index) {
142
+ let n = 1;
143
+ for (let i = 0; i < index; i += 1) if (text[i] === "\n") n += 1;
144
+ return n;
145
+ }
146
+ /**
147
+ * Index range of the first element a selector opens, through its closing tag.
148
+ * Depth-aware on the tag name, so a nested `<div>` inside the match does not
149
+ * end it early.
150
+ */
151
+ function elementRange(template, selector) {
152
+ for (const m of template.matchAll(tagRe())) {
153
+ const [whole, name, attrs = ""] = m;
154
+ if (m.index === void 0 || !name || !matches(attrs, selector)) continue;
155
+ const open = new RegExp(`<${name}\\b`, "g");
156
+ const close = new RegExp(`</${name}\\s*>`, "g");
157
+ let depth = 1;
158
+ let pos = m.index + whole.length;
159
+ while (depth > 0) {
160
+ open.lastIndex = pos;
161
+ close.lastIndex = pos;
162
+ const o = open.exec(template);
163
+ const c = close.exec(template);
164
+ if (!c) return [m.index, template.length];
165
+ if (o && o.index < c.index) {
166
+ depth += 1;
167
+ pos = o.index + o[0].length;
168
+ } else {
169
+ depth -= 1;
170
+ pos = c.index + c[0].length;
171
+ }
172
+ }
173
+ return [m.index, pos];
174
+ }
175
+ return null;
176
+ }
177
+ /**
178
+ * The `data-tab` values under a tabs nav, in document order. A value holding
179
+ * an expression is skipped: its id is only known at render time.
180
+ */
181
+ function readTabIds(template, navSelector) {
182
+ const range = elementRange(template, navSelector);
183
+ if (!range) return [];
184
+ const nav = template.slice(range[0], range[1]);
185
+ const ids = [];
186
+ for (const m of nav.matchAll(tagRe())) {
187
+ const id = attr(m[2] ?? "", "data-tab");
188
+ if (id && !id.includes("{{")) ids.push(id);
189
+ }
190
+ return ids;
191
+ }
192
+ /**
193
+ * Add the attributes the generated sheet needs, and report each opening tag
194
+ * that changed. Every other byte of the template is left where it was.
195
+ */
196
+ function editTemplate(template, opts) {
197
+ const edits = [];
198
+ const navRanges = opts.navSelectors.slice(0, 1).map((selector) => elementRange(template, selector)).filter((range) => range !== null);
199
+ const inNav = (index) => navRanges.some(([start, end]) => index >= start && index < end);
200
+ return {
201
+ output: template.replace(tagRe(), (whole, name, attrs, selfClose, offset) => {
202
+ const add = [];
203
+ const hasAction = attr(attrs, "data-action") !== null;
204
+ if (!hasAction) {
205
+ for (const action of opts.actions) if (matches(attrs, action.selector)) {
206
+ add.push(`data-action="${action.name}"`);
207
+ break;
208
+ }
209
+ }
210
+ const tab = attr(attrs, "data-tab");
211
+ const needsGroup = attr(attrs, "data-group") === null;
212
+ let withClass = attrs;
213
+ const isNavLink = tab !== null && inNav(offset);
214
+ const isPane = tab !== null && !isNavLink && hasClass(attrs, "tab") && (opts.tabIds === void 0 || opts.tabIds.includes(tab));
215
+ if (isNavLink) {
216
+ if (!hasAction && !add.some((one) => one.startsWith("data-action="))) add.push("data-action=\"vttforgeTab\"");
217
+ if (needsGroup) add.push("data-group=\"primary\"");
218
+ } else if (isPane && needsGroup) add.push("data-group=\"primary\"");
219
+ if ((isNavLink || isPane) && tab !== null && !tab.includes("{{") && !/\{\{\s*tabs\./.test(attrs)) {
220
+ const marker = `{{tabs.${tab}.cssClass}}`;
221
+ withClass = /\sclass\s*=\s*"([^"]*)"/.test(attrs) ? attrs.replace(/(\sclass\s*=\s*")([^"]*)(")/, (_m, open, value, close) => `${open}${value.trimEnd()} ${marker}${close}`) : attrs;
222
+ if (withClass === attrs) add.push(`class="${marker}"`);
223
+ }
224
+ if (add.length === 0 && withClass === attrs) return whole;
225
+ const after = `<${name}${withClass.replace(/\s+$/, "")}${add.length > 0 ? ` ${add.join(" ")}` : ""}${selfClose ? " /" : ""}>`;
226
+ edits.push({
227
+ line: lineOf(template, offset),
228
+ before: whole,
229
+ after
230
+ });
231
+ return after;
232
+ }),
233
+ edits,
234
+ formRoot: /^\s*<form\b/.test(template)
235
+ };
236
+ }
237
+ //#endregion
238
+ //#region src/migrate/parse.ts
239
+ /**
240
+ * The parse side of `migrate --sheets`: an AST for the class structure, and
241
+ * the few lookups the planner needs. Bodies are never re-printed from the
242
+ * tree; the planner slices the original text by node range.
243
+ */
244
+ const CONVERTED = /* @__PURE__ */ new Set([
245
+ "ActorSheet",
246
+ "ItemSheet",
247
+ "Application",
248
+ "FormApplication"
249
+ ]);
250
+ const UNSUPPORTED = /* @__PURE__ */ new Set(["Dialog", "DocumentSheet"]);
251
+ function parseSource(source, lang) {
252
+ return parse(source, {
253
+ sourceType: "module",
254
+ errorRecovery: true,
255
+ attachComment: false,
256
+ plugins: lang === "ts" ? ["typescript", "decorators"] : ["decorators"]
257
+ });
258
+ }
259
+ function text(source, node) {
260
+ return source.slice(node.start ?? 0, node.end ?? 0);
261
+ }
262
+ /** Depth-first over every child node. Return `false` from `visit` to skip a subtree. */
263
+ function walk(node, visit) {
264
+ if (!node || typeof node.type !== "string") return;
265
+ if (visit(node) === false) return;
266
+ for (const key of Object.keys(node)) {
267
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
268
+ const value = node[key];
269
+ if (Array.isArray(value)) for (const v of value) walk(v, visit);
270
+ else if (value && typeof value === "object" && "type" in value) walk(value, visit);
271
+ }
272
+ }
273
+ /** `foundry.appv1.sheets.ActorSheet` → the leaf name, or the identifier itself. */
274
+ function superName(cls) {
275
+ const s = cls.superClass;
276
+ if (!s) return null;
277
+ if (s.type === "Identifier") return s.name;
278
+ if (s.type === "MemberExpression" && s.property.type === "Identifier") return s.property.name;
279
+ return null;
280
+ }
281
+ function classesOf(ast) {
282
+ const out = [];
283
+ walk(ast.program, (n) => {
284
+ if (n.type === "ClassDeclaration") {
285
+ out.push({
286
+ name: n.id?.name ?? "",
287
+ node: n
288
+ });
289
+ return false;
290
+ }
291
+ if (n.type === "ExportDefaultDeclaration" && n.declaration.type === "ClassDeclaration") {
292
+ const base = superName(n.declaration) ?? "Sheet";
293
+ out.push({
294
+ name: n.declaration.id?.name ?? `Default${base}`,
295
+ node: n.declaration
296
+ });
297
+ return false;
298
+ }
299
+ if (n.type === "VariableDeclarator" && n.init?.type === "ClassExpression" && n.id.type === "Identifier") {
300
+ out.push({
301
+ name: n.id.name,
302
+ node: n.init
303
+ });
304
+ return false;
305
+ }
306
+ });
307
+ return out;
308
+ }
309
+ function findSheetClasses(ast, source) {
310
+ const found = [];
311
+ for (const { name, node } of classesOf(ast)) {
312
+ const base = superName(node);
313
+ if (!base || !CONVERTED.has(base) || !node.superClass) continue;
314
+ found.push({
315
+ name,
316
+ base,
317
+ node,
318
+ superText: text(source, node.superClass)
319
+ });
320
+ }
321
+ return found;
322
+ }
323
+ function unsupportedBases(ast, source) {
324
+ const out = [];
325
+ for (const { name, node } of classesOf(ast)) {
326
+ const base = superName(node);
327
+ if (!base || !UNSUPPORTED.has(base) || !node.superClass) continue;
328
+ out.push({
329
+ name,
330
+ superText: text(source, node.superClass),
331
+ line: node.loc?.start.line ?? 0
332
+ });
333
+ }
334
+ return out;
335
+ }
336
+ function methodOf(cls, name, opts = {}) {
337
+ for (const member of cls.body.body) {
338
+ if (member.type !== "ClassMethod") continue;
339
+ if (member.key.type !== "Identifier" || member.key.name !== name) continue;
340
+ if (opts.static !== void 0 && Boolean(member.static) !== opts.static) continue;
341
+ if (opts.kind !== void 0 && member.kind !== opts.kind) continue;
342
+ return member;
343
+ }
344
+ return null;
345
+ }
346
+ //#endregion
347
+ //#region src/migrate/sheet-bodies.ts
348
+ /**
349
+ * Text rewrites applied to method bodies carried over from an Application v1
350
+ * sheet. Each one is scoped to the slice the planner hands it, so a pattern
351
+ * here never sees the rest of the file.
352
+ *
353
+ * Nothing is re-printed from a syntax tree: the bodies keep the author's
354
+ * spacing and comments, and every rewrite is a replacement the reader can
355
+ * find in the diff. What cannot be decided mechanically becomes a
356
+ * `// TODO(migrate)` line above the code that needs the decision, and the
357
+ * same message comes back in `todos` so the report can list it.
358
+ */
359
+ const TODO = (msg) => `// TODO(migrate): ${msg}`;
360
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
361
+ const camel = (s) => s.replace(/-+(\w)/g, (_m, c) => c.toUpperCase());
362
+ /** Replace outside comments and strings; the mask keeps them out of reach. */
363
+ function replaceCode(code, pattern, replacement) {
364
+ const masked = maskComments(code, { strings: true });
365
+ return code.replace(pattern, (match, ...rest) => {
366
+ const offset = rest.find((r) => typeof r === "number") ?? 0;
367
+ if (masked[offset] === "\0") return match;
368
+ return replacement(match, ...rest.filter((r) => typeof r === "string"));
369
+ });
370
+ }
371
+ /** Put a TODO line above the line that holds `index`. */
372
+ function todoAt(code, index, msg) {
373
+ const lineStart = code.lastIndexOf("\n", index - 1) + 1;
374
+ const indent = /^[ \t]*/.exec(code.slice(lineStart))?.[0] ?? "";
375
+ return `${code.slice(0, lineStart)}${indent}${TODO(msg)}\n${code.slice(lineStart)}`;
376
+ }
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|each)\(/g;
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";
381
+ /**
382
+ * A handler body from `activateListeners`, with `event.currentTarget` folded
383
+ * into the `target` the action receives and the jQuery data readers turned
384
+ * into `dataset`.
385
+ */
386
+ function rewriteHandlerBody(body, eventParam, htmlParam, targetName = "target") {
387
+ const todos = [];
388
+ let code = body;
389
+ if (eventParam) {
390
+ const ev = esc(eventParam);
391
+ code = replaceCode(code, new RegExp(`\\$\\(\\s*${ev}\\.currentTarget\\s*\\)`, "g"), () => targetName);
392
+ if (targetName !== `${eventParam}.currentTarget`) code = replaceCode(code, new RegExp(`\\b${ev}\\.currentTarget\\b`, "g"), () => targetName);
393
+ }
394
+ code = replaceCode(code, /\.data\(\s*(['"])([\w-]+)\1\s*\)/g, (_m, _q, key) => `.dataset.${camel(key)}`);
395
+ code = replaceCode(code, /\.attr\(\s*(['"])data-([\w-]+)\1\s*\)/g, (_m, _q, key) => `.dataset.${camel(key)}`);
396
+ code = replaceCode(code, /\.parents\(/g, () => ".closest(");
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
+ }
408
+ code = replaceCode(code, /this\.element\.find\(/g, () => "this.element.querySelectorAll(");
409
+ const masked = maskComments(code, { strings: true });
410
+ const lines = /* @__PURE__ */ new Set();
411
+ for (const m of code.matchAll(LEFTOVER_JQUERY)) {
412
+ const at = m.index ?? 0;
413
+ if (masked[at] === "\0") continue;
414
+ lines.add(code.lastIndexOf("\n", at - 1) + 1);
415
+ }
416
+ for (const lineStart of [...lines].sort((a, b) => b - a)) {
417
+ code = todoAt(code, lineStart, JQUERY_MSG);
418
+ todos.unshift(JQUERY_MSG);
419
+ }
420
+ return {
421
+ code,
422
+ todos
423
+ };
424
+ }
425
+ /**
426
+ * `getData()` becomes `_prepareContext(options)`. V2 hands back a much
427
+ * smaller context, so the keys a v1 body expects to already be there are
428
+ * assigned right after the `super` call — unless the method assigns them
429
+ * itself without reading the old value first.
430
+ */
431
+ function rewriteGetData(methodText, base, opts = {}) {
432
+ const todos = [];
433
+ const params = /^(\s*)(async\s+)?getData\s*\(([^)]*)\)/.exec(methodText)?.[3]?.trim() ?? "";
434
+ let code = methodText.replace(/^(\s*)(async\s+)?getData\s*\(([^)]*)\)/, (_m, indent) => `${indent}async _prepareContext(options)`);
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}`);
441
+ const varMatch = /(?:const|let|var)\s+(\w+)\s*=\s*(?:await\s+)?super\._prepareContext\(options\)\s*;/.exec(code);
442
+ const v = varMatch?.[1] ?? "context";
443
+ const isSheet = base === "ActorSheet" || base === "ItemSheet";
444
+ const own = base === "ActorSheet" ? "actor" : "item";
445
+ const wanted = isSheet ? [
446
+ [own, `${v}.${own} = this.document;`],
447
+ ["data", `${v}.data = this.document;`],
448
+ ["system", `${v}.system = this.document.system;`]
449
+ ] : base === "FormApplication" && opts.usesObject === true ? [["object", `${v}.object = this.object;`]] : [];
450
+ if (base === "ActorSheet") wanted.push(["items", `${v}.items = [...this.document.items];`]);
451
+ if (isSheet) wanted.push(["editable", `${v}.editable = this.isEditable;`], ["owner", `${v}.owner = this.document.isOwner;`]);
452
+ const masked = maskComments(code, { strings: true });
453
+ const inject = wanted.filter(([key]) => {
454
+ const assigned = new RegExp(`\\b${esc(v)}\\.${key}\\s*=(?!=)`).test(masked);
455
+ const read = new RegExp(`\\b${esc(v)}\\.${key}\\b(?!\\s*=(?!=))`).test(masked);
456
+ return !assigned || read;
457
+ }).map(([, line]) => line);
458
+ if (varMatch) {
459
+ const at = varMatch.index + varMatch[0].length;
460
+ const indent = /^[ \t]*/.exec(code.slice(code.lastIndexOf("\n", varMatch.index) + 1))?.[0] ?? " ";
461
+ code = `${code.slice(0, at)}${inject.map((l) => `\n${indent}${l}`).join("")}${code.slice(at)}`;
462
+ } else if (inject.length > 0) {
463
+ const msg = `set ${inject.join(" ")} on the context before returning it`;
464
+ code = todoAt(code, code.indexOf("{") + 1, msg);
465
+ todos.push(msg);
466
+ }
467
+ if (params !== "" && params !== "options") {
468
+ const msg = `\`getData(${params})\` took its own parameters; \`_prepareContext(options)\` does not. Read what the body needs from \`options\` or \`this.document\``;
469
+ code = todoAt(code, code.indexOf("{") + 1, msg);
470
+ todos.push(msg);
471
+ }
472
+ return {
473
+ code,
474
+ todos
475
+ };
476
+ }
477
+ /**
478
+ * `_onDropItem(event, data)` becomes `onDropItem(item, event)`: the SDK base
479
+ * resolves the dropped document before it calls the hook, so the raw drop
480
+ * payload the v1 body read is gone.
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
+ }
504
+ function rewriteDropMethod(methodText, which) {
505
+ const lower = which.toLowerCase();
506
+ const sig = new RegExp(`_onDrop${which}\\s*\\(\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)`);
507
+ const m = sig.exec(methodText);
508
+ if (!m) return {
509
+ code: methodText,
510
+ todos: []
511
+ };
512
+ const eventName = m[1] ?? "event";
513
+ const dataName = m[2] ?? "data";
514
+ const param = new RegExp(`\\b(?:const|let|var)\\s+(?:${lower}\\b|\\{[^}]*\\b${lower}\\b[^}]*\\}|\\[[^\\]]*\\b${lower}\\b[^\\]]*\\])`).test(methodText) ? `dropped${which}` : lower;
515
+ let code = methodText.replace(sig, `onDrop${which}(${param}, ${eventName})`);
516
+ const todos = [];
517
+ if (which === "Item") code = replaceCode(code, /super\._onDropItem\([^)]*\)/g, () => `this.document.createEmbeddedDocuments('Item', [${param}.toObject()])`);
518
+ else code = replaceCode(code, new RegExp(`super\\._onDrop${which}\\([^)]*\\)`, "g"), () => `super.onDrop${which}(${param}, ${eventName})`);
519
+ code = replaceCode(code, new RegExp(`\\b${esc(dataName)}\\b`, "g"), () => `${param}.toDragData()`);
520
+ const msg = which === "Item" ? `the base hands the resolved Item as \`${param}\`; the old \`${dataName}\` payload is now \`${param}.toDragData()\`, read \`${param}\` directly where you can. The old super call created it on the actor, which is what the createEmbeddedDocuments line does now (a drop from the same actor used to re-sort instead). Return true when the drop was handled, undefined to let the base do its default` : `the base hands the resolved Actor as \`${param}\`; the old \`${dataName}\` payload is now \`${param}.toDragData()\`, read \`${param}\` directly where you can. Return true when the drop was handled`;
521
+ code = todoAt(code, code.indexOf("{") + 1, msg);
522
+ todos.push(msg);
523
+ return {
524
+ code,
525
+ todos
526
+ };
527
+ }
528
+ /** `Dialog.confirm({ ... })`: the options literal is group 1. Non-greedy, so a nested `}` ends it early; `balanced` catches that. */
529
+ const CONFIRM_CALL = /\bDialog\.confirm\(\s*\{([\s\S]*?)\}\s*\)/g;
530
+ const NEW_DIALOG = /\bnew\s+Dialog\s*\(/g;
531
+ const UNREADABLE_MSG = "Dialog.confirm here could not be read (a nested object or a comma inside an option); rewrite it as DialogV2.confirm({ window: { title }, content, yes: { callback }, no: { callback } }) by hand";
532
+ const NEW_DIALOG_MSG = "Dialog v1 (removed in v16); rebuild with DialogV2.prompt / DialogV2.wait, buttons as { action, label, callback }";
533
+ /** Whether every bracket opened in `text` (outside strings and comments) is closed. */
534
+ function balanced(text) {
535
+ const masked = maskComments(text, { strings: true });
536
+ const pairs = /* @__PURE__ */ new Map([
537
+ [")", "("],
538
+ ["]", "["],
539
+ ["}", "{"]
540
+ ]);
541
+ const stack = [];
542
+ for (let i = 0; i < masked.length; i += 1) {
543
+ const ch = masked[i];
544
+ if (ch === void 0 || ch === "\0") continue;
545
+ if (ch === "(" || ch === "[" || ch === "{") stack.push(ch);
546
+ else if (pairs.has(ch)) {
547
+ if (stack.pop() !== pairs.get(ch)) return false;
548
+ }
549
+ }
550
+ return stack.length === 0;
551
+ }
552
+ /** The top-level `key: value` pairs of an object literal's inner text. */
553
+ function topLevelPairs(inner) {
554
+ const masked = maskComments(inner, { strings: true });
555
+ const pairs = [];
556
+ let depth = 0;
557
+ let start = 0;
558
+ const flush = (end) => {
559
+ const raw = inner.slice(start, end).trim();
560
+ if (!raw) return;
561
+ if (raw.startsWith("...")) {
562
+ pairs.push({
563
+ key: raw,
564
+ value: "",
565
+ spread: true
566
+ });
567
+ return;
568
+ }
569
+ const colon = raw.indexOf(":");
570
+ if (colon === -1) {
571
+ pairs.push({
572
+ key: raw,
573
+ value: raw,
574
+ spread: false
575
+ });
576
+ return;
577
+ }
578
+ pairs.push({
579
+ key: raw.slice(0, colon).trim(),
580
+ value: raw.slice(colon + 1).trim(),
581
+ spread: false
582
+ });
583
+ };
584
+ for (let i = 0; i < masked.length; i += 1) {
585
+ const ch = masked[i];
586
+ if (ch === "\0") continue;
587
+ if (ch === "(" || ch === "[" || ch === "{") depth += 1;
588
+ else if (ch === ")" || ch === "]" || ch === "}") depth -= 1;
589
+ else if (ch === "," && depth === 0) {
590
+ flush(i);
591
+ start = i + 1;
592
+ }
593
+ }
594
+ flush(inner.length);
595
+ return pairs;
596
+ }
597
+ /**
598
+ * The DialogV2.confirm call for a Dialog.confirm options literal, or `null`
599
+ * when the literal could not be read. `missing` names what the rewrite left
600
+ * behind (a spread, an option with no V2 slot). `defaultYes` is dropped on
601
+ * purpose: DialogV2 has no equivalent.
602
+ */
603
+ function readConfirmOptions(inner) {
604
+ if (!balanced(inner)) return {
605
+ code: null,
606
+ missing: []
607
+ };
608
+ const missing = [];
609
+ const found = {};
610
+ for (const pair of topLevelPairs(inner)) {
611
+ if (pair.spread) {
612
+ missing.push(`the spread ${pair.key}`);
613
+ continue;
614
+ }
615
+ const key = pair.key.replace(/^['"]|['"]$/g, "");
616
+ if (key === "title" || key === "content" || key === "yes" || key === "no") found[key] = pair.value;
617
+ else if (key === "rejectClose") found.rejectClose = pair.value;
618
+ else if (key !== "defaultYes" && key !== "options") missing.push(key);
619
+ }
620
+ return {
621
+ code: `DialogV2.confirm({ ${[
622
+ found.title ? `window: { title: ${found.title} }` : "",
623
+ found.content ? `content: ${found.content}` : "",
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}` : ""
627
+ ].filter(Boolean).join(", ")} })`,
628
+ missing
629
+ };
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
+ }
834
+ function rewriteDialogs(code) {
835
+ const todos = [];
836
+ const confirmMask = maskComments(code, { strings: true });
837
+ const hits = [];
838
+ for (const m of code.matchAll(CONFIRM_CALL)) {
839
+ const start = m.index ?? 0;
840
+ if (confirmMask[start] === "\0") continue;
841
+ const read = readConfirmOptions(m[1] ?? "");
842
+ hits.push({
843
+ start,
844
+ end: start + m[0].length,
845
+ code: read.code,
846
+ missing: read.missing
847
+ });
848
+ }
849
+ let out = code;
850
+ for (const hit of hits.reverse()) {
851
+ if (hit.code !== null) out = `${out.slice(0, hit.start)}${hit.code}${out.slice(hit.end)}`;
852
+ if (hit.code === null) {
853
+ out = todoAt(out, hit.start, UNREADABLE_MSG);
854
+ todos.unshift(UNREADABLE_MSG);
855
+ } else if (hit.missing.length > 0) {
856
+ const msg = `Dialog.confirm options left behind: ${hit.missing.join(", ")}; move them onto the DialogV2.confirm call by hand`;
857
+ out = todoAt(out, hit.start, msg);
858
+ todos.unshift(msg);
859
+ }
860
+ }
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);
863
+ return {
864
+ code: out,
865
+ todos
866
+ };
867
+ }
868
+ //#endregion
869
+ //#region src/migrate/sheet-listeners.ts
870
+ const EVENTS = /* @__PURE__ */ new Set([
871
+ "click",
872
+ "dblclick",
873
+ "change",
874
+ "contextmenu",
875
+ "input",
876
+ "keydown",
877
+ "keyup",
878
+ "focus",
879
+ "blur",
880
+ "mouseenter",
881
+ "mouseleave",
882
+ "submit"
883
+ ]);
884
+ const FIRST_CLASS_OR_ID = /[.#]([A-Za-z_][\w-]*)/;
885
+ const SEPARATOR = /[-_]+(\w)/g;
886
+ function actionName(selector, taken) {
887
+ const captured = FIRST_CLASS_OR_ID.exec(selector)?.[1];
888
+ if (!captured) return null;
889
+ const base = captured.replace(SEPARATOR, (_, c) => c.toUpperCase()).replace(/^[A-Z]/, (c) => c.toLowerCase());
890
+ let name = base;
891
+ let i = 2;
892
+ while (taken.has(name)) {
893
+ name = `${base}${i}`;
894
+ i += 1;
895
+ }
896
+ taken.add(name);
897
+ return name;
898
+ }
899
+ /** `html.find(SEL)` with `html` being the listener's parameter → the selector. */
900
+ function findSelector(callee, htmlParam) {
901
+ if (callee.type !== "CallExpression") return null;
902
+ const c = callee.callee;
903
+ if (c.type !== "MemberExpression" || c.object.type !== "Identifier" || c.object.name !== htmlParam) return null;
904
+ if (c.property.type !== "Identifier" || c.property.name !== "find") return null;
905
+ const [arg] = callee.arguments;
906
+ return arg && arg.type === "StringLiteral" ? arg.value : null;
907
+ }
908
+ /** `this._onX.bind(this)` → `_onX`; `(ev) => this._onX(ev)` → `_onX`. */
909
+ function forwardedMethod(handler) {
910
+ if (handler.type === "CallExpression" && handler.callee.type === "MemberExpression" && handler.callee.property.type === "Identifier" && handler.callee.property.name === "bind" && handler.callee.object.type === "MemberExpression" && handler.callee.object.object.type === "ThisExpression" && handler.callee.object.property.type === "Identifier") return handler.callee.object.property.name;
911
+ if (handler.type === "ArrowFunctionExpression") {
912
+ let call = null;
913
+ if (handler.body.type === "CallExpression") call = handler.body;
914
+ else if (handler.body.type === "BlockStatement" && handler.body.body.length === 1) {
915
+ const only = handler.body.body[0];
916
+ if (only?.type === "ExpressionStatement" && only.expression.type === "CallExpression") call = only.expression;
917
+ if (only?.type === "ReturnStatement" && only.argument?.type === "CallExpression") call = only.argument;
918
+ }
919
+ if (call && call.callee.type === "MemberExpression" && call.callee.object.type === "ThisExpression" && call.callee.property.type === "Identifier" && call.arguments.length <= 1) {
920
+ const [a] = call.arguments;
921
+ const p = handler.params[0];
922
+ if (!a || a.type === "Identifier" && p?.type === "Identifier" && a.name === p.name) return call.callee.property.name;
923
+ }
924
+ }
925
+ return null;
926
+ }
927
+ /**
928
+ * `html.find(SEL).<event>(H)` or `html.find(SEL).on('<event>', H)` → the parts,
929
+ * or `null` when the statement is not a jQuery binding this can translate.
930
+ */
931
+ function boundEvent(expr, htmlParam) {
932
+ if (expr.type !== "CallExpression") return null;
933
+ if (expr.callee.type !== "MemberExpression" || expr.callee.property.type !== "Identifier") return null;
934
+ const receiver = expr.callee.object;
935
+ if (receiver.type === "Super") return null;
936
+ const selector = findSelector(receiver, htmlParam);
937
+ if (selector === null) return null;
938
+ const calleeName = expr.callee.property.name;
939
+ if (EVENTS.has(calleeName)) {
940
+ const handler = expr.arguments[0];
941
+ return handler ? {
942
+ selector,
943
+ event: calleeName,
944
+ handler
945
+ } : null;
946
+ }
947
+ if (calleeName === "on" && expr.arguments.length === 2) {
948
+ const first = expr.arguments[0];
949
+ const handler = expr.arguments[1];
950
+ if (first?.type === "StringLiteral" && handler) return {
951
+ selector,
952
+ event: first.value,
953
+ handler
954
+ };
955
+ }
956
+ return null;
957
+ }
958
+ function extractListeners(cls, source) {
959
+ const out = {
960
+ actions: [],
961
+ listeners: [],
962
+ leftovers: [],
963
+ htmlParam: "html"
964
+ };
965
+ const method = methodOf(cls.node, "activateListeners");
966
+ if (!method) return out;
967
+ const p = method.params[0];
968
+ const htmlParam = p?.type === "Identifier" ? p.name : "html";
969
+ out.htmlParam = htmlParam;
970
+ const taken = /* @__PURE__ */ new Set();
971
+ const leftover = (stmt) => {
972
+ out.leftovers.push({
973
+ line: stmt.loc?.start.line ?? 0,
974
+ text: text(source, stmt)
975
+ });
976
+ };
977
+ const consider = (stmt) => {
978
+ if (stmt.type !== "ExpressionStatement") return;
979
+ const e = stmt.expression;
980
+ if (e.type === "AwaitExpression") return;
981
+ if (e.type !== "CallExpression") return;
982
+ if (e.callee.type !== "MemberExpression" || e.callee.property.type !== "Identifier") return;
983
+ if (e.callee.object.type === "Super") return;
984
+ const bound = boundEvent(e, htmlParam);
985
+ if (!bound) {
986
+ leftover(stmt);
987
+ return;
988
+ }
989
+ const { selector, event, handler } = bound;
990
+ if (event !== "click") {
991
+ out.listeners.push({
992
+ selector,
993
+ event,
994
+ handlerText: text(source, handler)
995
+ });
996
+ return;
997
+ }
998
+ const name = actionName(selector, taken);
999
+ if (name === null) {
1000
+ leftover(stmt);
1001
+ return;
1002
+ }
1003
+ const forwarded = forwardedMethod(handler);
1004
+ if (forwarded) {
1005
+ out.actions.push({
1006
+ name,
1007
+ selector,
1008
+ kind: "method",
1009
+ method: forwarded,
1010
+ param: null,
1011
+ body: null,
1012
+ isAsync: false
1013
+ });
1014
+ return;
1015
+ }
1016
+ if (handler.type === "ArrowFunctionExpression" || handler.type === "FunctionExpression") {
1017
+ const p0 = handler.params[0];
1018
+ out.actions.push({
1019
+ name,
1020
+ selector,
1021
+ kind: "inline",
1022
+ method: null,
1023
+ param: p0?.type === "Identifier" ? p0.name : null,
1024
+ body: text(source, handler.body),
1025
+ isAsync: Boolean(handler.async)
1026
+ });
1027
+ return;
1028
+ }
1029
+ leftover(stmt);
1030
+ };
1031
+ /** A guard such as `if (!this.options.editable) return;`: V2 sheets gate through isEditable. */
1032
+ const isGuard = (stmt) => {
1033
+ if (stmt.type !== "IfStatement" || stmt.alternate) return false;
1034
+ const c = stmt.consequent;
1035
+ if (c.type === "ReturnStatement") return true;
1036
+ return c.type === "BlockStatement" && c.body.length === 1 && c.body[0]?.type === "ReturnStatement";
1037
+ };
1038
+ const visit = (stmts) => {
1039
+ for (const stmt of stmts) {
1040
+ if (isGuard(stmt)) continue;
1041
+ if (stmt.type === "IfStatement") {
1042
+ const branches = [stmt.consequent, stmt.alternate].filter((b) => Boolean(b));
1043
+ for (const b of branches) visit(b.type === "BlockStatement" ? b.body : [b]);
1044
+ out.leftovers.push({
1045
+ line: stmt.loc?.start.line ?? 0,
1046
+ text: `if (${text(source, stmt.test)}) guarded the bindings above it; V2 actions run regardless, gate inside the handler`
1047
+ });
1048
+ continue;
1049
+ }
1050
+ if (stmt.type === "BlockStatement") {
1051
+ visit(stmt.body);
1052
+ continue;
1053
+ }
1054
+ consider(stmt);
1055
+ }
1056
+ };
1057
+ visit(method.body.body);
1058
+ return out;
1059
+ }
1060
+ //#endregion
1061
+ //#region src/migrate/sheet-options.ts
1062
+ function keyName(p) {
1063
+ if (p.key.type === "Identifier") return p.key.name;
1064
+ if (p.key.type === "StringLiteral") return p.key.value;
1065
+ return null;
1066
+ }
1067
+ const NOT_A_VALUE = /* @__PURE__ */ new Set([
1068
+ "ArrayPattern",
1069
+ "ObjectPattern",
1070
+ "AssignmentPattern",
1071
+ "RestElement"
1072
+ ]);
1073
+ function props(obj) {
1074
+ const out = [];
1075
+ for (const p of obj.properties) {
1076
+ if (p.type !== "ObjectProperty") continue;
1077
+ const k = keyName(p);
1078
+ if (k && !NOT_A_VALUE.has(p.value.type)) out.push([k, p.value]);
1079
+ }
1080
+ return out;
1081
+ }
1082
+ /** A string literal, or a template literal with nothing interpolated. */
1083
+ function str(e) {
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;
1087
+ }
1088
+ function num(e) {
1089
+ return e.type === "NumericLiteral" ? e.value : null;
1090
+ }
1091
+ function bool(e) {
1092
+ return e.type === "BooleanLiteral" ? e.value : null;
1093
+ }
1094
+ /** The options literal: the last object argument of the returned call, or the returned object. */
1095
+ function optionsLiteral(method) {
1096
+ let found = null;
1097
+ walk(method.body, (n) => {
1098
+ if (found) return false;
1099
+ if (n.type !== "ReturnStatement" || !n.argument) return void 0;
1100
+ const arg = n.argument;
1101
+ if (arg.type === "ObjectExpression") found = arg;
1102
+ else if (arg.type === "CallExpression") {
1103
+ const last = [...arg.arguments].reverse().find((a) => a.type === "ObjectExpression");
1104
+ if (last?.type === "ObjectExpression") found = last;
1105
+ }
1106
+ return false;
1107
+ });
1108
+ return found;
1109
+ }
1110
+ function extractOptions(cls, source) {
1111
+ const out = {
1112
+ classes: null,
1113
+ width: null,
1114
+ height: null,
1115
+ heightAuto: false,
1116
+ resizable: null,
1117
+ submitOnChange: null,
1118
+ closeOnSubmit: null,
1119
+ id: null,
1120
+ title: null,
1121
+ template: null,
1122
+ templateGetter: methodOf(cls.node, "template", {
1123
+ kind: "get",
1124
+ static: false
1125
+ }),
1126
+ tabs: [],
1127
+ dragDrop: null,
1128
+ unknown: [],
1129
+ usesThis: false
1130
+ };
1131
+ const method = methodOf(cls.node, "defaultOptions", {
1132
+ static: true,
1133
+ kind: "get"
1134
+ });
1135
+ const literal = method ? optionsLiteral(method) : null;
1136
+ if (!literal) return out;
1137
+ out.usesThis = /\bthis\b/.test(text(source, literal));
1138
+ for (const [key, value] of props(literal)) switch (key) {
1139
+ case "classes":
1140
+ out.classes = text(source, value);
1141
+ break;
1142
+ case "width":
1143
+ out.width = num(value);
1144
+ break;
1145
+ case "height":
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);
1157
+ break;
1158
+ case "resizable":
1159
+ out.resizable = bool(value);
1160
+ break;
1161
+ case "submitOnChange":
1162
+ out.submitOnChange = bool(value);
1163
+ break;
1164
+ case "template":
1165
+ out.template = str(value);
1166
+ break;
1167
+ case "dragDrop":
1168
+ out.dragDrop = text(source, value);
1169
+ break;
1170
+ case "tabs":
1171
+ out.tabs.push(...readTabs(value));
1172
+ break;
1173
+ default: out.unknown.push(key);
1174
+ }
1175
+ return out;
1176
+ }
1177
+ function readTabs(value) {
1178
+ if (value.type !== "ArrayExpression") return [];
1179
+ const tabs = [];
1180
+ for (const el of value.elements) {
1181
+ if (el?.type !== "ObjectExpression") continue;
1182
+ const t = Object.fromEntries(props(el));
1183
+ const nav = t.navSelector ? str(t.navSelector) : null;
1184
+ if (!nav) continue;
1185
+ tabs.push({
1186
+ navSelector: nav,
1187
+ contentSelector: t.contentSelector ? str(t.contentSelector) : null,
1188
+ initial: t.initial ? str(t.initial) : null
1189
+ });
1190
+ }
1191
+ return tabs;
1192
+ }
1193
+ const q = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
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");
1196
+ const lines = [];
1197
+ lines.push(" /** @override */");
1198
+ lines.push(" static DEFAULT_OPTIONS = foundry.utils.mergeObject(");
1199
+ lines.push(" super.DEFAULT_OPTIONS,");
1200
+ lines.push(" {");
1201
+ if (kind !== "sheet" && opts.id) lines.push(` id: ${opts.id},`);
1202
+ if (opts.classes) lines.push(` classes: ${opts.classes},`);
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);
1206
+ lines.push(` position: { ${parts.join(", ")} },`);
1207
+ }
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} },`);
1212
+ lines.push(" actions: {}, // filled below");
1213
+ lines.push(" },");
1214
+ lines.push(" { inplace: false },");
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)")}`);
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`)}`);
1218
+ if (opts.tabs.length > 0) {
1219
+ lines.push("", " /** @override */", " static TABS = {");
1220
+ for (const [i, tab] of opts.tabs.entries()) {
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";
1226
+ const ids = tabIds[tab.navSelector] ?? [];
1227
+ const initial = tab.initial ?? ids[0] ?? "";
1228
+ if (ids.length === 0) lines.push(` ${todo(`tab ids for ${tab.navSelector} were not found in the template; list them here`)}`);
1229
+ lines.push(` ${group}: { tabs: [${ids.map((id) => `{ id: ${q(id)} }`).join(", ")}], initial: ${q(initial)} },`);
1230
+ }
1231
+ lines.push(" };");
1232
+ }
1233
+ if (opts.dragDrop) lines.push("", " /** @override */", ` static DRAG_DROP = ${opts.dragDrop};`);
1234
+ const part = kind === "sheet" ? "sheet" : kind === "form" ? "form" : "content";
1235
+ lines.push("", " /** @override */", " static PARTS = {");
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: '' },`);
1238
+ lines.push(" };");
1239
+ return lines.join("\n");
1240
+ }
1241
+ //#endregion
1242
+ //#region src/migrate/sheets.ts
1243
+ /** v1 lifecycle methods a sheet used to override; V2 has other hooks for the same jobs. */
1244
+ const V1_LIFECYCLE = /* @__PURE__ */ new Set([
1245
+ "setPosition",
1246
+ "_getHeaderButtons",
1247
+ "_render",
1248
+ "_renderInner",
1249
+ "_replaceHTML",
1250
+ "_onSubmit",
1251
+ "_getSubmitData",
1252
+ "_onChangeInput",
1253
+ "activateEditor",
1254
+ "close"
1255
+ ]);
1256
+ const HANDLED = /* @__PURE__ */ new Set([
1257
+ "defaultOptions",
1258
+ "getData",
1259
+ "activateListeners",
1260
+ "_onDropItem",
1261
+ "_onDropActor"
1262
+ ]);
1263
+ const ACTIONS_PLACEHOLDER = " actions: {}, // filled below";
1264
+ function methodName(m) {
1265
+ return m.key.type === "Identifier" ? m.key.name : null;
1266
+ }
1267
+ const pascal = (s) => s.replace(/^[a-z]/, (c) => c.toUpperCase());
1268
+ const single = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
1269
+ /** Re-indent a member slice so its first line sits at two spaces. */
1270
+ function reindent(memberText) {
1271
+ const lines = memberText.split("\n");
1272
+ const first = lines[0] ?? "";
1273
+ const rest = lines.slice(1);
1274
+ const indents = rest.filter((l) => l.trim().length > 0).map((l) => /^[ \t]*/.exec(l)?.[0].length ?? 0);
1275
+ const min = indents.length > 0 ? Math.min(...indents) : 0;
1276
+ const strip = Math.max(0, min - 4);
1277
+ const body = rest.map((l) => {
1278
+ if (l.trim().length === 0) return "";
1279
+ const own = /^[ \t]*/.exec(l)?.[0].length ?? 0;
1280
+ return l.slice(Math.min(strip, own));
1281
+ });
1282
+ return [` ${first.trimStart()}`, ...body].join("\n");
1283
+ }
1284
+ /** Ensure `(event, target)` on a handler method, keeping the event name it used. */
1285
+ function handlerSignature(methodText, name) {
1286
+ const escaped = name.replace(/[$]/g, "\\$");
1287
+ const sig = new RegExp(`^(\\s*(?:async\\s+)?${escaped}\\s*\\()([^)]*)(\\))`);
1288
+ const m = sig.exec(methodText);
1289
+ if (!m) return {
1290
+ code: methodText,
1291
+ eventParam: null
1292
+ };
1293
+ const eventParam = (m[2] ?? "").split(",").map((p) => p.trim()).filter(Boolean)[0] ?? null;
1294
+ const first = eventParam ?? "event";
1295
+ return {
1296
+ code: methodText.replace(sig, `$1${first}, target$3`),
1297
+ eventParam
1298
+ };
1299
+ }
1300
+ /** The first parameter name of a method, from its signature text. */
1301
+ function firstParam(methodText, name) {
1302
+ const escaped = name.replace(/[$]/g, "\\$");
1303
+ const first = (new RegExp(`^\\s*(?:async\\s+)?${escaped}\\s*\\(([^)]*)\\)`).exec(methodText)?.[1] ?? "").split(",")[0]?.trim();
1304
+ return first ? first : null;
1305
+ }
1306
+ /** Lines after the first sit at `spaces`, keeping their relative indentation. */
1307
+ function indentTo(snippet, spaces) {
1308
+ const lines = snippet.split("\n");
1309
+ const rest = lines.slice(1);
1310
+ const indents = rest.filter((l) => l.trim().length > 0).map((l) => /^[ \t]*/.exec(l)?.[0].length ?? 0);
1311
+ const min = indents.length > 0 ? Math.min(...indents) : 0;
1312
+ const pad = " ".repeat(spaces);
1313
+ return [(lines[0] ?? "").trimStart(), ...rest.map((l) => l.trim().length === 0 ? "" : `${pad}${l.slice(Math.min(min, /^[ \t]*/.exec(l)?.[0].length ?? 0))}`)].join("\n");
1314
+ }
1315
+ /** A block body lifted out of `activateListeners`: inner lines at four spaces, the brace at two. */
1316
+ function dedentBlock(block) {
1317
+ const lines = block.split("\n");
1318
+ if (lines.length < 2) return block;
1319
+ const inner = lines.slice(1, -1);
1320
+ const indents = inner.filter((l) => l.trim().length > 0).map((l) => /^[ \t]*/.exec(l)?.[0].length ?? 0);
1321
+ const min = indents.length > 0 ? Math.min(...indents) : 0;
1322
+ const body = inner.map((l) => l.trim().length === 0 ? "" : ` ${l.slice(Math.min(min, /^[ \t]*/.exec(l)?.[0].length ?? 0))}`);
1323
+ return [
1324
+ lines[0] ?? "{",
1325
+ ...body,
1326
+ " }"
1327
+ ].join("\n");
1328
+ }
1329
+ function importLines(source, lang) {
1330
+ const ast = parseSource(source, lang);
1331
+ const lines = [];
1332
+ for (const n of ast.program.body) if (n.type === "ImportDeclaration") lines.push(text(source, n));
1333
+ return lines;
1334
+ }
1335
+ function isExported(source, cls) {
1336
+ const start = cls.node.start ?? 0;
1337
+ const before = source.slice(Math.max(0, start - 40), start);
1338
+ return /export\s+(?:default\s+)?$/.test(before) || new RegExp(`export\\s+\\{[^}]*\\b${cls.name}\\b`).test(source);
1339
+ }
1340
+ function planClass(cls, source, tabIds) {
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";
1344
+ const own = cls.base === "ActorSheet" ? "actor" : "item";
1345
+ const options = extractOptions(cls, source);
1346
+ const listeners = extractListeners(cls, source);
1347
+ const templates = /* @__PURE__ */ new Set();
1348
+ const navs = /* @__PURE__ */ new Set();
1349
+ let usesDialogV2 = false;
1350
+ if (options.template) templates.add(options.template);
1351
+ if (options.templateGetter) {
1352
+ for (const m of text(source, options.templateGetter).matchAll(/["'`]([^"'`$]+\.(?:hbs|html))["'`]/g)) if (m[1]) templates.add(m[1]);
1353
+ }
1354
+ for (const t of options.tabs) navs.add(t.navSelector);
1355
+ const members = [];
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
+ };
1362
+ const actionEntries = listeners.actions.map((a) => ({
1363
+ name: a.name,
1364
+ selector: a.selector,
1365
+ method: a.kind === "method" && a.method ? a.method : inlineMethodName(a.name)
1366
+ }));
1367
+ const actionsBlock = actionEntries.length === 0 ? " actions: {}," : ` actions: {\n${actionEntries.map((a) => ` ${a.name}: ${cls.name}.prototype.${a.method},`).join("\n")}\n },`;
1368
+ const statics = options.templateGetter ? {
1369
+ ...options,
1370
+ template: null
1371
+ } : options;
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; }")}`);
1376
+ if (options.templateGetter) members.push(reindent(text(source, options.templateGetter)));
1377
+ const getData = methodOf(cls.node, "getData");
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
+ };
1384
+ if (listeners.listeners.length > 0) {
1385
+ const body = listeners.listeners.map((l) => {
1386
+ const param = /^\s*(?:async\s+)?\(?\s*(\w+)/.exec(l.handlerText)?.[1] ?? null;
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;
1388
+ return ` for (const el of this.element.querySelectorAll(${single(l.selector)})) {\n el.addEventListener(${single(l.event)}, ${handler});\n }`;
1389
+ }).join("\n");
1390
+ members.push(` /** @override */\n async _onRender(context, options) {\n await super._onRender(context, options);\n${body}\n }`);
1391
+ }
1392
+ const handlerNames = new Set(listeners.actions.filter((a) => a.kind === "method" && a.method).map((a) => a.method));
1393
+ const listenerTargets = new Set(listeners.listeners.flatMap((l) => [...l.handlerText.matchAll(/this\.(\w+)/g)].map((m) => m[1] ?? "")));
1394
+ for (const member of cls.node.body.body) {
1395
+ if (member.type !== "ClassMethod" && member.type !== "ClassProperty" && member.type !== "ClassPrivateMethod") continue;
1396
+ const name = member.type === "ClassMethod" ? methodName(member) : null;
1397
+ if (name && HANDLED.has(name)) continue;
1398
+ if (name === "template" && member.type === "ClassMethod" && member.kind === "get") continue;
1399
+ let code = applyDialogs(reindent(text(source, member)));
1400
+ if (name && handlerNames.has(name)) {
1401
+ const sig = handlerSignature(code, name);
1402
+ code = rewriteHandlerBody(sig.code, sig.eventParam, null).code;
1403
+ } else if (name && listenerTargets.has(name)) {
1404
+ const ev = firstParam(code, name);
1405
+ code = rewriteHandlerBody(code, ev, null, ev ? `${ev}.currentTarget` : "target").code;
1406
+ } else if (member.type === "ClassMethod") code = rewriteHandlerBody(code, null, null).code;
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}`;
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);
1410
+ }
1411
+ for (const which of ["Item", "Actor"]) {
1412
+ const m = methodOf(cls.node, `_onDrop${which}`);
1413
+ if (!m) continue;
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))}`);
1416
+ }
1417
+ const inline = listeners.actions.filter((a) => a.kind === "inline");
1418
+ for (const a of inline) {
1419
+ const method = inlineMethodName(a.name);
1420
+ const rewritten = rewriteHandlerBody(applyDialogs(a.body ?? "{}"), a.param, null).code.trim();
1421
+ const body = rewritten.startsWith("{") ? dedentBlock(rewritten) : `{\n return ${rewritten};\n }`;
1422
+ members.push(` ${a.isAsync ? "async " : ""}${method}(${a.param ?? "event"}, target) ${body}`);
1423
+ }
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)";
1427
+ return {
1428
+ block: `${exported ? "export " : ""}class ${cls.name} extends ${extendsExpr} {\n${members.join("\n\n")}\n}`,
1429
+ base,
1430
+ actions: actionEntries,
1431
+ templates: [...templates],
1432
+ navs: [...navs],
1433
+ usesDialogV2
1434
+ };
1435
+ }
1436
+ function planSheetFile(relPath, source, opts) {
1437
+ const lang = relPath.endsWith(".ts") ? "ts" : opts.lang;
1438
+ const ast = parseSource(source, lang);
1439
+ const classes = findSheetClasses(ast, source);
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`);
1441
+ if (classes.length === 0) return {
1442
+ files: [],
1443
+ notes
1444
+ };
1445
+ const dot = relPath.lastIndexOf(".");
1446
+ const to = `${relPath.slice(0, dot)}.v2${relPath.slice(dot)}`;
1447
+ const outputs = classes.map((cls) => ({
1448
+ cls,
1449
+ out: planClass(cls, source, opts.tabIds)
1450
+ }));
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
+ }
1458
+ const fileSource = `${header.join("\n")}\n\n${outputs.map((o) => o.out.block).join("\n\n")}\n`;
1459
+ const marker = "TODO(migrate): ";
1460
+ const todos = fileSource.split("\n").flatMap((line, i) => {
1461
+ const at = line.indexOf(marker);
1462
+ return at === -1 ? [] : [{
1463
+ line: i + 1,
1464
+ message: line.slice(at + 15).trim()
1465
+ }];
1466
+ });
1467
+ return {
1468
+ files: outputs.map(({ cls, out }) => ({
1469
+ from: relPath,
1470
+ to,
1471
+ className: cls.name,
1472
+ base: out.base,
1473
+ source: fileSource,
1474
+ actions: out.actions,
1475
+ todos,
1476
+ templates: out.templates,
1477
+ tabNavSelectors: out.navs
1478
+ })),
1479
+ notes
1480
+ };
1481
+ }
1482
+ //#endregion
115
1483
  //#region src/migrate/transforms.ts
116
1484
  /**
117
1485
  * The rewrites `vttforge migrate` applies to a v13 source file.
@@ -686,7 +2054,9 @@ function transformManifest(raw, kind) {
686
2054
  const indent = output.slice(lineStart, idKey.keyStart);
687
2055
  const after = output.indexOf("\n", idKey.valueEnd);
688
2056
  const insertAt = after === -1 ? output.length : after;
689
- output = `${!/,\s*$/.test(output.slice(idKey.valueEnd, insertAt)) ? `${output.slice(0, idKey.valueEnd)},${output.slice(idKey.valueEnd, insertAt)}` : output.slice(0, insertAt)}\n${indent}"type": "${kind}",${output.slice(insertAt)}`;
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)}`;
690
2060
  changes.push({
691
2061
  line: lineAt(raw, idKey.keyStart) + 1,
692
2062
  before: "(no \"type\")",
@@ -826,11 +2196,21 @@ function topLevelKey(json, key) {
826
2196
  * written unless asked: the preview is the default, because a text rewrite
827
2197
  * that touched a string literal is something to see before it lands.
828
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
+ }
829
2208
  async function runMigrate(options) {
830
2209
  const { cwd } = options;
831
2210
  const write = options.write === true;
832
2211
  if (!existsSync(cwd) || !(await stat(cwd)).isDirectory()) throw new Error(`Migrate target is not a directory: ${cwd}`);
833
2212
  const files = [];
2213
+ const pending = [];
834
2214
  for (const [name, kind] of [["system.json", "system"], ["module.json", "module"]]) {
835
2215
  const path = join(cwd, name);
836
2216
  if (!existsSync(path)) continue;
@@ -848,7 +2228,10 @@ async function runMigrate(options) {
848
2228
  changes: result.changes,
849
2229
  notes: result.notes
850
2230
  });
851
- if (write && result.changes.length > 0) await writeFile(path, result.output, "utf8");
2231
+ if (write && result.changes.length > 0) pending.push({
2232
+ path,
2233
+ content: result.output
2234
+ });
852
2235
  }
853
2236
  for await (const path of _internal.walkSourceFiles(cwd)) {
854
2237
  let source;
@@ -864,8 +2247,20 @@ async function runMigrate(options) {
864
2247
  changes: result.changes,
865
2248
  notes: result.notes
866
2249
  });
867
- if (write && result.output !== source) await writeFile(path, result.output, "utf8");
2250
+ if (write && result.output !== source) pending.push({
2251
+ path,
2252
+ content: result.output
2253
+ });
868
2254
  }
2255
+ for (const finding of await runReleaseRules(cwd)) files.push({
2256
+ file: finding.filePath,
2257
+ changes: [],
2258
+ notes: [{
2259
+ line: finding.line ?? 1,
2260
+ rule: finding.ruleId,
2261
+ message: `${finding.message} ${finding.remediation ?? ""}`.trim()
2262
+ }]
2263
+ });
869
2264
  files.sort((a, b) => a.file.localeCompare(b.file));
870
2265
  const report = {
871
2266
  cwd,
@@ -883,7 +2278,8 @@ async function runMigrate(options) {
883
2278
  files: [],
884
2279
  documentTypes: {},
885
2280
  registration: "",
886
- notes: ["No template.json here; nothing to generate."]
2281
+ notes: ["No template.json here; nothing to generate."],
2282
+ decisions: []
887
2283
  };
888
2284
  else {
889
2285
  const plan = planDataModels(JSON.parse(await readFile(templatePath, "utf8")), {
@@ -891,32 +2287,151 @@ async function runMigrate(options) {
891
2287
  lang: options.lang ?? "js"
892
2288
  });
893
2289
  const written = [];
2290
+ const info = [];
894
2291
  for (const file of plan.files) {
895
2292
  const target = join(cwd, file.path);
896
2293
  if (existsSync(target)) {
897
- plan.notes.unshift(`${file.path} exists and was left alone.`);
2294
+ info.push(`${file.path} exists and was left alone.`);
898
2295
  continue;
899
2296
  }
900
- if (write) {
901
- await mkdir(dirname(target), { recursive: true });
902
- await writeFile(target, file.source, "utf8");
903
- }
2297
+ if (write) pending.push({
2298
+ path: target,
2299
+ content: file.source
2300
+ });
904
2301
  written.push(file.path);
905
2302
  }
906
2303
  report.dataModels = {
907
2304
  files: written,
908
2305
  documentTypes: plan.documentTypes,
909
2306
  registration: plan.registration,
910
- notes: plan.notes
2307
+ notes: info,
2308
+ decisions: plan.notes
911
2309
  };
912
2310
  }
913
2311
  }
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
+ }
914
2317
  return report;
915
2318
  }
2319
+ /** Every `.hbs` / `.html` in the project, project-relative. */
2320
+ async function allTemplates(cwd) {
2321
+ const out = [];
2322
+ for await (const file of _internal.walkTemplateFiles(cwd)) out.push(relative(cwd, file));
2323
+ return out.sort();
2324
+ }
2325
+ /** Project-relative path for a Foundry template path such as `systems/<id>/templates/x.html`. */
2326
+ function localTemplate(cwd, foundryPath) {
2327
+ const rel = /^(?:systems|modules)\/[^/]+\/(.+)$/.exec(foundryPath)?.[1] ?? foundryPath;
2328
+ return existsSync(join(cwd, rel)) ? rel : null;
2329
+ }
2330
+ async function planSheets(cwd, write, lang, pending) {
2331
+ const files = [];
2332
+ const templates = [];
2333
+ const notes = [];
2334
+ const decisions = [];
2335
+ const generated = /* @__PURE__ */ new Map();
2336
+ for await (const path of _internal.walkSourceFiles(cwd)) {
2337
+ const rel = relative(cwd, path);
2338
+ if (/\.v2\.[cm]?[jt]s$/.test(rel)) continue;
2339
+ let raw;
2340
+ try {
2341
+ raw = await readFile(path, "utf8");
2342
+ } catch {
2343
+ continue;
2344
+ }
2345
+ if (!/\bextends\s+(?:foundry\.appv1\.\w+\.)?(?:ActorSheet|ItemSheet|FormApplication|Application)\b/.test(raw)) continue;
2346
+ const source = transformSource(raw).output;
2347
+ let probe;
2348
+ try {
2349
+ probe = planSheetFile(rel, source, {
2350
+ lang,
2351
+ tabIds: {}
2352
+ });
2353
+ } catch (error) {
2354
+ const reason = error instanceof Error ? error.message : String(error);
2355
+ decisions.push(`${rel} could not be parsed and was skipped: ${reason}`);
2356
+ continue;
2357
+ }
2358
+ decisions.push(...probe.notes);
2359
+ if (probe.files.length === 0) continue;
2360
+ let templatePaths = [...new Set(probe.files.flatMap((f) => f.templates))].map((t) => localTemplate(cwd, t)).filter((t) => t !== null);
2361
+ if (templatePaths.length === 0) {
2362
+ const every = await allTemplates(cwd);
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;
2366
+ }
2367
+ const navSelectors = [...new Set(probe.files.flatMap((f) => f.tabNavSelectors))];
2368
+ const tabIds = {};
2369
+ for (const t of templatePaths) {
2370
+ const tpl = await readFile(join(cwd, t), "utf8");
2371
+ for (const nav of navSelectors) {
2372
+ if (tabIds[nav]) continue;
2373
+ const ids = readTabIds(tpl, nav);
2374
+ if (ids.length > 0) tabIds[nav] = ids;
2375
+ }
2376
+ }
2377
+ const plan = planSheetFile(rel, source, {
2378
+ lang,
2379
+ tabIds
2380
+ });
2381
+ for (const f of plan.files) {
2382
+ const { source: out, ...rest } = f;
2383
+ files.push(rest);
2384
+ generated.set(f.to, out);
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.`);
2387
+ }
2388
+ const actions = plan.files.flatMap((f) => f.actions.map((a) => ({
2389
+ name: a.name,
2390
+ selector: a.selector
2391
+ })));
2392
+ for (const t of templatePaths) {
2393
+ const tpl = await readFile(join(cwd, t), "utf8");
2394
+ const primaryNav = navSelectors[0];
2395
+ const r = editTemplate(tpl, {
2396
+ actions,
2397
+ navSelectors,
2398
+ tabIds: primaryNav === void 0 ? void 0 : tabIds[primaryNav]
2399
+ });
2400
+ if (r.edits.length === 0) continue;
2401
+ templates.push({
2402
+ file: t,
2403
+ edits: r.edits,
2404
+ formRoot: r.formRoot
2405
+ });
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
+ });
2411
+ }
2412
+ }
2413
+ for (const [to, out] of generated) {
2414
+ const target = join(cwd, to);
2415
+ if (existsSync(target)) {
2416
+ notes.unshift(`${to} exists and was left alone.`);
2417
+ continue;
2418
+ }
2419
+ if (write) pending.push({
2420
+ path: target,
2421
+ content: out
2422
+ });
2423
+ }
2424
+ return {
2425
+ files,
2426
+ templates,
2427
+ notes: [...new Set(notes)],
2428
+ decisions: [...new Set(decisions)]
2429
+ };
2430
+ }
916
2431
  /** The report as text: one block per file, edits then notes. */
917
2432
  function formatMigrateReport(report) {
918
2433
  const lines = [];
919
- if (report.files.length === 0 && !report.dataModels) {
2434
+ if (report.files.length === 0 && !report.dataModels && !report.sheets) {
920
2435
  lines.push("Nothing to migrate. The project already reads as v14.");
921
2436
  return `${lines.join("\n")}\n`;
922
2437
  }
@@ -934,7 +2449,27 @@ function formatMigrateReport(report) {
934
2449
  for (const f of dm.files) lines.push(` ${f}`);
935
2450
  if (Object.keys(dm.documentTypes).length > 0) lines.push("", "Declare the types in the manifest:", ` "documentTypes": ${JSON.stringify(dm.documentTypes)}`);
936
2451
  if (dm.registration) lines.push("", "Register the models at init:", ...dm.registration.split("\n").map((l) => ` ${l}`));
937
- for (const n of dm.notes) lines.push(` needs a decision: ${n}`);
2452
+ for (const n of dm.notes) lines.push(` ${n}`);
2453
+ for (const n of dm.decisions) lines.push(` needs a decision: ${n}`);
2454
+ }
2455
+ if (report.sheets) {
2456
+ const s = report.sheets;
2457
+ const targets = [...new Set(s.files.map((f) => f.to))];
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:`);
2459
+ for (const f of s.files) {
2460
+ lines.push(` ${f.to}: ${f.className} extends ${f.base === "ApplicationV2" ? "HandlebarsApplicationMixin(ApplicationV2)" : `${f.base}()`}`);
2461
+ for (const a of f.actions) lines.push(` action ${a.name} ← ${a.selector} (${a.method})`);
2462
+ for (const t of f.todos) lines.push(` ${t.line}: needs a decision: ${t.message}`);
2463
+ }
2464
+ if (s.templates.length > 0) {
2465
+ lines.push("", report.written ? "Edited templates:" : "Would edit templates:");
2466
+ for (const t of s.templates) {
2467
+ lines.push(` ${t.file}`);
2468
+ for (const e of t.edits) lines.push(` ${e.line}: ${oneLine(e.before)}`, ` ${" ".repeat(String(e.line).length)} → ${oneLine(e.after)}`);
2469
+ }
2470
+ }
2471
+ for (const n of s.notes) lines.push(` ${n}`);
2472
+ for (const n of s.decisions) lines.push(` needs a decision: ${n}`);
938
2473
  }
939
2474
  return `${lines.join("\n")}\n`;
940
2475
  }
@@ -949,7 +2484,7 @@ function oneLine(text) {
949
2484
  *
950
2485
  * Exit codes:
951
2486
  * 0: ran, whether or not anything changed
952
- * 1: the target is not a directory
2487
+ * 1: the target is not a directory, or --strict and a decision was left
953
2488
  */
954
2489
  async function runMigrateCommand(options = {}) {
955
2490
  const cwd = resolve(options.cwd ?? process.cwd());
@@ -961,9 +2496,18 @@ async function runMigrateCommand(options = {}) {
961
2496
  write: options.write === true,
962
2497
  dataModels: options.dataModels === true,
963
2498
  style: options.style,
964
- lang: options.lang
2499
+ lang: options.lang,
2500
+ sheets: options.sheets === true
965
2501
  });
966
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
+ }
967
2511
  return {
968
2512
  report,
969
2513
  exitCode: 0
@@ -1187,7 +2731,7 @@ const audit = defineCommand({
1187
2731
  const migrate = defineCommand({
1188
2732
  meta: {
1189
2733
  name: "migrate",
1190
- description: "Rewrite a v13 system or module for Foundry v14 (preview by default)"
2734
+ description: "Rewrite a v13 system or module for Foundry v14 (preview by default); --data-models and --sheets write the v16 replacements"
1191
2735
  },
1192
2736
  args: {
1193
2737
  path: {
@@ -1205,6 +2749,11 @@ const migrate = defineCommand({
1205
2749
  default: false,
1206
2750
  description: "Emit the report as JSON"
1207
2751
  },
2752
+ strict: {
2753
+ type: "boolean",
2754
+ default: false,
2755
+ description: "Exit 1 when anything is left that needs a decision, for CI"
2756
+ },
1208
2757
  "data-models": {
1209
2758
  type: "boolean",
1210
2759
  default: false,
@@ -1218,7 +2767,12 @@ const migrate = defineCommand({
1218
2767
  lang: {
1219
2768
  type: "string",
1220
2769
  default: "js",
1221
- description: "For --data-models: \"js\" writes .mjs, \"ts\" writes .ts"
2770
+ description: "For --data-models and --sheets: \"js\" writes .mjs, \"ts\" writes .ts"
2771
+ },
2772
+ sheets: {
2773
+ type: "boolean",
2774
+ default: false,
2775
+ description: "Also write a V2 sheet file (on the SDK bases) next to each Application v1 sheet class, and the data-action attributes its templates need"
1222
2776
  }
1223
2777
  },
1224
2778
  async run({ args }) {
@@ -1227,9 +2781,11 @@ const migrate = defineCommand({
1227
2781
  cwd: args.path ? String(args.path) : void 0,
1228
2782
  write: Boolean(args.write),
1229
2783
  json: Boolean(args.json),
2784
+ strict: Boolean(args.strict),
1230
2785
  dataModels: Boolean(args["data-models"]),
1231
2786
  style: String(args.style) === "sdk" ? "sdk" : "plain",
1232
- lang: String(args.lang) === "ts" ? "ts" : "js"
2787
+ lang: String(args.lang) === "ts" ? "ts" : "js",
2788
+ sheets: Boolean(args.sheets)
1233
2789
  });
1234
2790
  process.exitCode = exitCode;
1235
2791
  } catch (error) {