@vttforge/cli 0.10.1 → 0.12.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,117 @@
1
1
  #!/usr/bin/env node
2
- import { f as REMOVED_UTILS, h as _internal, i as runDev, l as runAuditCommand, n as ScaffoldError, o as runBuild, p as maskComments, r as runInit, t as VTTFORGE_CLI_VERSION } from "./src-Bof8_ypF.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, y as _internal } from "./src-CzzrhCN-.mjs";
3
3
  import { existsSync } from "node:fs";
4
- import { join, relative, resolve } from "node:path";
5
- import { readFile, stat, writeFile } from "node:fs/promises";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
6
6
  import { defineCommand, runMain } from "citty";
7
+ //#region src/migrate/data-models.ts
8
+ const RICH_TEXT_KEYS = /^(description|biography|bio|notes|details)$/i;
9
+ function fieldFor(key, value, path, notes, indent) {
10
+ const next = `${indent} `;
11
+ if (typeof value === "number") return `new f.NumberField({ required: true, nullable: false${Number.isInteger(value) ? ", integer: true" : ""}, initial: ${value} })`;
12
+ if (typeof value === "boolean") return `new f.BooleanField({ required: true, nullable: false, initial: ${value} })`;
13
+ if (typeof value === "string") {
14
+ const literal = JSON.stringify(value);
15
+ if (RICH_TEXT_KEYS.test(key)) return `new f.HTMLField({ required: true, blank: true, initial: ${literal} })`;
16
+ return `new f.StringField({ required: true, blank: true, initial: ${literal} })`;
17
+ }
18
+ if (Array.isArray(value)) {
19
+ const first = value[0];
20
+ if (first === void 0 || typeof first === "object" && first !== null) {
21
+ if (first === void 0) notes.push(`${path}: an empty array in the template; it is an ArrayField of ObjectField. Name the element's shape if it has one.`);
22
+ return "new f.ArrayField(new f.ObjectField())";
23
+ }
24
+ return `new f.ArrayField(${fieldFor(key, first, `${path}[]`, notes, indent)})`;
25
+ }
26
+ if (value !== null && typeof value === "object") {
27
+ const entries = Object.entries(value);
28
+ if (entries.length === 0) {
29
+ notes.push(`${path}: an empty object in the template; it is an ObjectField. Give it a SchemaField if it has a shape.`);
30
+ return "new f.ObjectField()";
31
+ }
32
+ return `new f.SchemaField({\n${entries.map(([k, v]) => `${next}${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, next)},`).join("\n")}\n${indent}})`;
33
+ }
34
+ notes.push(`${path}: null in the template; it is an ObjectField. Pick the real field.`);
35
+ return "new f.ObjectField()";
36
+ }
37
+ function safeKey(key) {
38
+ return /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
39
+ }
40
+ function pascal(name) {
41
+ return name.replace(/(^|[^A-Za-z0-9])([a-z0-9])/g, (_m, _s, c) => c.toUpperCase()).replace(/[^A-Za-z0-9]/g, "");
42
+ }
43
+ function camel(name) {
44
+ const p = pascal(name);
45
+ return p.charAt(0).toLowerCase() + p.slice(1);
46
+ }
47
+ function schemaBody(data, path, notes) {
48
+ return Object.entries(data).filter(([k]) => k !== "templates").map(([k, v]) => ` ${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, " ")},`).join("\n");
49
+ }
50
+ function header(style) {
51
+ if (style === "sdk") return "import { BaseTypeDataModel, fields } from '@vttforge/core';\n";
52
+ return "";
53
+ }
54
+ function fieldsLine(style) {
55
+ return style === "sdk" ? " const f = fields();" : " const f = foundry.data.fields;";
56
+ }
57
+ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts/data" } = {}) {
58
+ const ext = lang === "ts" ? "ts" : "mjs";
59
+ const files = [];
60
+ const notes = [];
61
+ const documentTypes = {};
62
+ const registrations = [];
63
+ for (const [document, raw] of Object.entries(template)) {
64
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
65
+ const doc = raw;
66
+ const types = doc.types ?? [];
67
+ const templates = doc.templates ?? {};
68
+ const docDir = `${dir}/${document.toLowerCase()}`;
69
+ const fragmentNames = Object.keys(templates);
70
+ if (fragmentNames.length > 0) {
71
+ const fns = fragmentNames.map((name) => {
72
+ 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
+ }).join("\n\n");
75
+ const tsHint = lang === "ts" ? "// @ts-nocheck: the field constructors are typed by the runtime, not by this file\n" : "";
76
+ files.push({
77
+ path: `${docDir}/templates.${ext}`,
78
+ source: `${tsHint}/**\n * The \`templates\` of the old template.json for ${document}, each as a\n * function of the fields bag. A type spreads the ones it listed.\n */\n\n${fns}\n`
79
+ });
80
+ }
81
+ documentTypes[document] = {};
82
+ const modelNames = [];
83
+ for (const type of types) {
84
+ 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");
88
+ 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` : "";
91
+ const schemaFn = `${fieldsLine(style)}\n return {\n${[spreads, body].filter(Boolean).join("\n")}\n };`;
92
+ 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
+ files.push({
94
+ path: `${docDir}/${type}-data.${ext}`,
95
+ source: classSource
96
+ });
97
+ const meta = {};
98
+ const html = (doc.htmlFields ?? []).filter((k) => k in own || listed.some((t) => k in (templates[t] ?? {})));
99
+ if (html.length) meta.htmlFields = html;
100
+ documentTypes[document][type] = meta;
101
+ modelNames.push(`${type}: ${className}`);
102
+ registrations.push(`import { ${className} } from './${docDir.replace(/^scripts\//, "")}/${type}-data.${ext === "ts" ? "js" : "mjs"}';`);
103
+ }
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
+ }
106
+ 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
+ return {
108
+ files,
109
+ documentTypes,
110
+ registration: registrations.join("\n"),
111
+ notes
112
+ };
113
+ }
114
+ //#endregion
7
115
  //#region src/migrate/transforms.ts
8
116
  /**
9
117
  * The rewrites `vttforge migrate` applies to a v13 source file.
@@ -106,18 +214,58 @@ const removedGlobals = (source) => {
106
214
  };
107
215
  };
108
216
  /**
217
+ * Bare v13 global aliases → their `foundry.*` path: `renderTemplate(` →
218
+ * `foundry.applications.handlebars.renderTemplate(`, `extends ActorSheet` →
219
+ * `extends foundry.appv1.sheets.ActorSheet`. Same object, no removal date.
220
+ * A name the file declares or imports, an object key, a property, and a
221
+ * word inside a string or comment are left alone.
222
+ */
223
+ const namespacedGlobals = (source) => {
224
+ const changes = [];
225
+ const code = maskComments(source, { strings: true });
226
+ const edits = [];
227
+ for (const [name, path] of Object.entries(LEGACY_GLOBALS)) {
228
+ if (definesName(code, name)) continue;
229
+ for (const match of code.matchAll(bareUsePattern(name))) {
230
+ const start = match.index ?? 0;
231
+ edits.push({
232
+ start,
233
+ end: start + name.length,
234
+ text: path,
235
+ name
236
+ });
237
+ }
238
+ }
239
+ let output = source;
240
+ for (const edit of edits.sort((a, b) => b.start - a.start)) output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
241
+ for (const edit of edits.sort((a, b) => a.start - b.start)) changes.push({
242
+ line: lineAt(source, edit.start),
243
+ before: edit.name,
244
+ after: edit.text,
245
+ rule: "namespaced-globals"
246
+ });
247
+ return {
248
+ output,
249
+ changes,
250
+ notes: []
251
+ };
252
+ };
253
+ /**
109
254
  * `'-=key': null` → `key: _del`; `'==key': value` → `key: _replace(value)`;
110
255
  * `performDeletions` → `applyOperators`; `objectsEqual` → `equals`.
256
+ *
257
+ * The key may be a template literal with `${...}` segments in the prefix,
258
+ * which is how a flag deletion is usually written: `` [`flags.${id}.-=old`] ``.
111
259
  */
112
260
  const dataOperators = (source) => {
113
- const deletions = rewrite(source, /(['"])((?:[\w$]+\.)*)-=([\w$.]+)\1\s*:\s*null\b/g, (_m, quote, prefix, key) => `${quote}${prefix}${key}${quote}: _del`, "data-operators");
261
+ const deletions = rewrite(source, /(['"`])((?:[\w$]+\.|\$\{[^}]*\}\.)*)-=([\w$.]+)\1(\]?)\s*:\s*null\b/g, (_m, quote, prefix, key, bracket) => `${quote}${prefix}${key}${quote}${bracket}: _del`, "data-operators");
114
262
  const replacements = wrapReplacementValues(deletions.output);
115
263
  const flags = rewrite(replacements.output, /\bperformDeletions\s*:/g, "applyOperators:", "data-operators");
116
264
  return merge(deletions, replacements, flags, rewrite(flags.output, /\bfoundry\.utils\.objectsEqual\s*\(/g, "foundry.utils.equals(", "data-operators"));
117
265
  };
118
266
  function wrapReplacementValues(source) {
119
267
  const changes = [];
120
- const pattern = /(['"])((?:[\w$]+\.)*)==([\w$.]+)\1\s*:\s*/g;
268
+ const pattern = /(['"`])((?:[\w$]+\.|\$\{[^}]*\}\.)*)==([\w$.]+)\1(\]?)\s*:\s*/g;
121
269
  const code = maskComments(source);
122
270
  let out = "";
123
271
  let cursor = 0;
@@ -128,8 +276,8 @@ function wrapReplacementValues(source) {
128
276
  const valueEnd = scanValueEnd(source, valueStart);
129
277
  if (valueEnd === -1) continue;
130
278
  const value = source.slice(valueStart, valueEnd).trimEnd();
131
- const [, quote = "\"", prefix = "", key = ""] = match;
132
- const after = `${quote}${prefix}${key}${quote}: _replace(${value})`;
279
+ const [, quote = "\"", prefix = "", key = "", bracket = ""] = match;
280
+ const after = `${quote}${prefix}${key}${quote}${bracket}: _replace(${value})`;
133
281
  out += source.slice(cursor, start) + after;
134
282
  cursor = valueStart + value.length;
135
283
  changes.push({
@@ -183,47 +331,103 @@ const ROLL_MODE_CONSTANTS = {
183
331
  *
184
332
  * `"roll"` meant "whatever the user's chat dropdown says", which is what an
185
333
  * absent `messageMode` means now, so it becomes `undefined`. A value that is
186
- * an expression is left for the reader, with a note.
334
+ * an expression is wrapped in `Roll._mapLegacyRollMode(...)`, which maps a
335
+ * v13 name and passes a v14 key or `undefined` through unchanged, so the
336
+ * wrap is safe whatever the expression yields.
187
337
  */
188
338
  const rollMode = (source) => {
189
- const notes = [];
190
339
  const option = rewrite(source, /\brollMode\s*:\s*(['"])(publicroll|gmroll|blindroll|selfroll|roll)\1/g, (_m, quote, value) => value === "roll" ? "messageMode: undefined" : `messageMode: ${quote}${ROLL_MODE_VALUES[value]}${quote}`, "roll-mode");
191
- const key = rewrite(option.output, /\brollMode\s*:/g, (m) => m.replace("rollMode", "messageMode"), "roll-mode");
192
- for (const change of key.changes) notes.push({
193
- line: change.line,
194
- rule: "roll-mode",
195
- message: "The value is an expression. If it can be a v13 mode name, wrap it: `Roll._mapLegacyRollMode(value)`."
196
- });
197
- const setting = rewrite(key.output, /(['"])core\1\s*,\s*(['"])rollMode\2/g, (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`, "roll-mode");
340
+ const expressions = wrapRollModeExpressions(option.output);
341
+ const setting = rewrite(expressions.output, /(['"])core\1\s*,\s*(['"])rollMode\2/g, (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`, "roll-mode");
198
342
  const modes = rewrite(setting.output, /\bCONFIG\.Dice\.rollModes\b/g, "CONFIG.ChatMessage.modes", "roll-mode");
343
+ return merge(option, expressions, setting, modes, rewrite(modes.output, /\bCONST\.DICE_ROLL_MODES\.(PUBLIC|PRIVATE|BLIND|SELF)\b/g, (_m, name) => `"${ROLL_MODE_CONSTANTS[name]}"`, "roll-mode"));
344
+ };
345
+ /** `rollMode: <expr>` → `messageMode: Roll._mapLegacyRollMode(<expr>)`. */
346
+ function wrapRollModeExpressions(source) {
347
+ const changes = [];
348
+ const pattern = /\brollMode\s*:\s*/g;
349
+ const code = maskComments(source);
350
+ let out = "";
351
+ let cursor = 0;
352
+ for (const match of source.matchAll(pattern)) {
353
+ const start = match.index ?? 0;
354
+ if (code[start] === "\0") continue;
355
+ const valueStart = start + match[0].length;
356
+ const valueEnd = scanValueEnd(source, valueStart);
357
+ if (valueEnd === -1) continue;
358
+ const value = source.slice(valueStart, valueEnd).trimEnd();
359
+ const after = `messageMode: Roll._mapLegacyRollMode(${value})`;
360
+ out += source.slice(cursor, start) + after;
361
+ cursor = valueStart + value.length;
362
+ changes.push({
363
+ line: lineAt(source, start),
364
+ before: source.slice(start, cursor),
365
+ after,
366
+ rule: "roll-mode"
367
+ });
368
+ }
369
+ out += source.slice(cursor);
199
370
  return {
200
- ...merge(option, key, setting, modes, rewrite(modes.output, /\bCONST\.DICE_ROLL_MODES\.(PUBLIC|PRIVATE|BLIND|SELF)\b/g, (_m, name) => `"${ROLL_MODE_CONSTANTS[name]}"`, "roll-mode")),
371
+ output: out,
372
+ changes,
373
+ notes: []
374
+ };
375
+ }
376
+ /**
377
+ * Hooks that changed shape: noted, not rewritten. `renderChatMessage` is
378
+ * removed in v15 and its replacement hands an element where it handed a
379
+ * jQuery object, so the handler body is the reader's to change.
380
+ */
381
+ const hookNotes = (source) => {
382
+ const notes = [];
383
+ const code = maskComments(source);
384
+ for (const match of source.matchAll(/Hooks\.(?:on|once)\(\s*['"]renderChatMessage['"]/g)) {
385
+ if (code[match.index ?? 0] === "\0") continue;
386
+ notes.push({
387
+ line: lineAt(source, match.index ?? 0),
388
+ rule: "hooks",
389
+ message: "`renderChatMessage` is removed in v15. Listen to `renderChatMessageHTML(message, html, context)`; `html` is the element, so `html.find(x)` becomes `html.querySelector(x)`."
390
+ });
391
+ }
392
+ return {
393
+ output: source,
394
+ changes: [],
201
395
  notes
202
396
  };
203
397
  };
204
398
  /**
205
399
  * Context-menu entries and header controls: `name` → `label`, `condition` →
206
- * `visible`, `callback` → `onClick`. Only inside an object literal that has a
207
- * `callback` and an `icon` or `condition`, so an unrelated `name:` elsewhere
208
- * is not renamed. The callback's parameters change too, from `(li)` to
209
- * `(event, target)`, and that is noted rather than rewritten.
400
+ * `visible`, `callback` → `onClick`.
401
+ *
402
+ * Only an object literal whose own keys include `callback` and `name` or
403
+ * `condition` is an entry. A Dialog button has `icon`, `label` and
404
+ * `callback`, and keeps `callback` on v14, so `icon` is not a signal; and
405
+ * only the literal's own keys count, so a class body or a `buttons` bag that
406
+ * happens to contain an entry is not itself treated as one. The callback's
407
+ * parameters change too, from `(li)` to `(event, target)`, and that is noted
408
+ * rather than rewritten.
210
409
  */
211
410
  const contextMenuKeys = (source) => {
212
411
  const changes = [];
213
412
  const notes = [];
214
- let output = source;
215
- const literals = objectLiterals(source);
216
- for (const { start, end } of literals.reverse()) {
217
- const body = output.slice(start, end);
218
- if (!/\bcallback\s*:/.test(body) || !/\b(?:icon|condition)\s*:/.test(body)) continue;
219
- const bodyCode = maskComments(body);
220
- const KEYS = {
221
- name: "label",
222
- condition: "visible",
223
- callback: "onClick"
224
- };
225
- const renamed = body.replace(/(^|[{,\s])(name|condition|callback)(\s*:)/g, (m, lead, key, colon, offset) => bodyCode[offset + lead.length] === "\0" ? m : `${lead}${KEYS[key]}${colon}`);
226
- if (renamed === body) continue;
413
+ const RENAME = {
414
+ name: "label",
415
+ condition: "visible",
416
+ callback: "onClick"
417
+ };
418
+ const edits = [];
419
+ for (const { start, end } of objectLiterals(source).sort((a, b) => b.start - a.start)) {
420
+ const keys = ownKeys(source, start, end);
421
+ const names = new Set(keys.map((k) => k.name));
422
+ if (!names.has("callback") || !(names.has("name") || names.has("condition"))) continue;
423
+ for (const key of keys) {
424
+ const to = RENAME[key.name];
425
+ if (to !== void 0) edits.push({
426
+ start: key.offset,
427
+ end: key.offset + key.name.length,
428
+ text: to
429
+ });
430
+ }
227
431
  changes.push({
228
432
  line: lineAt(source, start),
229
433
  before: lineText(source, start),
@@ -235,14 +439,82 @@ const contextMenuKeys = (source) => {
235
439
  rule: "context-menu-keys",
236
440
  message: "`onClick` receives `(event, target)` where `callback` received the element. Check the parameter list."
237
441
  });
238
- output = output.slice(0, start) + renamed + output.slice(end);
239
442
  }
443
+ let output = source;
444
+ for (const edit of edits.sort((a, b) => b.start - a.start)) output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
240
445
  return {
241
446
  output,
242
447
  changes,
243
448
  notes
244
449
  };
245
450
  };
451
+ /**
452
+ * The keys an object literal declares itself, with the offset of each name.
453
+ *
454
+ * Walks the span between the braces at depth one: a key is an identifier
455
+ * followed by `:` where a property may start, which is right after the
456
+ * opening brace or after a comma at that depth. Nested literals, arrays,
457
+ * calls, strings and comments are stepped over.
458
+ */
459
+ function ownKeys(source, start, end) {
460
+ const keys = [];
461
+ let depth = 0;
462
+ let quote = null;
463
+ let expectKey = true;
464
+ for (let i = start; i < end; i += 1) {
465
+ const ch = source[i] ?? "";
466
+ const next = source[i + 1] ?? "";
467
+ if (quote) {
468
+ if (ch === "\\") i += 1;
469
+ else if (ch === quote) quote = null;
470
+ continue;
471
+ }
472
+ if (ch === "/" && next === "/") {
473
+ const nl = source.indexOf("\n", i);
474
+ i = nl === -1 ? end : nl;
475
+ continue;
476
+ }
477
+ if (ch === "/" && next === "*") {
478
+ const close = source.indexOf("*/", i + 2);
479
+ i = close === -1 ? end : close + 1;
480
+ continue;
481
+ }
482
+ if (ch === "\"" || ch === "'" || ch === "`") {
483
+ quote = ch;
484
+ expectKey = false;
485
+ continue;
486
+ }
487
+ if (ch === "{" || ch === "[" || ch === "(") {
488
+ depth += 1;
489
+ expectKey = depth === 1 && ch === "{";
490
+ continue;
491
+ }
492
+ if (ch === "}" || ch === "]" || ch === ")") {
493
+ depth -= 1;
494
+ expectKey = false;
495
+ continue;
496
+ }
497
+ if (depth !== 1) continue;
498
+ if (ch === ",") {
499
+ expectKey = true;
500
+ continue;
501
+ }
502
+ if (/\s/.test(ch)) continue;
503
+ if (expectKey && /[A-Za-z_$]/.test(ch)) {
504
+ let j = i;
505
+ while (j < end && /[\w$]/.test(source[j] ?? "")) j += 1;
506
+ let k = j;
507
+ while (k < end && /\s/.test(source[k] ?? "")) k += 1;
508
+ if (source[k] === ":") keys.push({
509
+ name: source.slice(i, j),
510
+ offset: i
511
+ });
512
+ i = j - 1;
513
+ }
514
+ expectKey = false;
515
+ }
516
+ return keys;
517
+ }
246
518
  /** Every `{ ... }` span in the text, outermost first, strings and comments skipped. */
247
519
  function objectLiterals(source) {
248
520
  const spans = [];
@@ -369,13 +641,15 @@ const activeEffectModes = (source) => {
369
641
  /** The transforms, in the order they run. */
370
642
  const SOURCE_TRANSFORMS = [
371
643
  ["removed-globals", removedGlobals],
644
+ ["namespaced-globals", namespacedGlobals],
372
645
  ["data-operators", dataOperators],
373
646
  ["roll-mode", rollMode],
374
647
  ["context-menu-keys", contextMenuKeys],
375
648
  ["legacy-transferral", legacyTransferral],
376
649
  ["unregister-core-sheets", unregisterCoreSheets],
377
650
  ["status-effects", statusEffectsAssignment],
378
- ["active-effect-modes", activeEffectModes]
651
+ ["active-effect-modes", activeEffectModes],
652
+ ["hooks", hookNotes]
379
653
  ];
380
654
  function transformSource(source) {
381
655
  return pipe(source, SOURCE_TRANSFORMS.map(([, t]) => t));
@@ -383,33 +657,73 @@ function transformSource(source) {
383
657
  /**
384
658
  * The manifest: `type` declared, `compatibility` raised to 14 where it is
385
659
  * lower. Returns `null` when nothing needed to change.
660
+ *
661
+ * Edited as text, not re-serialised: a manifest carries its author's
662
+ * indentation, key order and one-line arrays, and a diff that reformats the
663
+ * whole file to add one key is a diff nobody merges. `type` goes on the line
664
+ * after `id`, with that line's indentation; the compatibility values are
665
+ * replaced in place.
386
666
  */
387
667
  function transformManifest(raw, kind) {
388
668
  const parsed = JSON.parse(raw);
389
669
  const changes = [];
390
670
  const notes = [];
671
+ let output = raw;
391
672
  if (parsed.type !== kind) {
392
- parsed.type = kind;
393
- changes.push({
394
- line: 1,
395
- before: "(no \"type\")",
396
- after: `"type": "${kind}"`,
397
- rule: "manifest"
398
- });
673
+ const typeKey = topLevelKey(output, "type");
674
+ if (typeKey) {
675
+ output = `${output.slice(0, typeKey.valueStart)}"${kind}"${output.slice(typeKey.valueEnd)}`;
676
+ changes.push({
677
+ line: lineAt(raw, typeKey.keyStart),
678
+ before: raw.slice(typeKey.keyStart, typeKey.valueEnd).trim(),
679
+ after: `"type": "${kind}"`,
680
+ rule: "manifest"
681
+ });
682
+ } else {
683
+ const idKey = topLevelKey(output, "id");
684
+ if (idKey) {
685
+ const lineStart = output.lastIndexOf("\n", idKey.keyStart) + 1;
686
+ const indent = output.slice(lineStart, idKey.keyStart);
687
+ const after = output.indexOf("\n", idKey.valueEnd);
688
+ 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)}`;
690
+ changes.push({
691
+ line: lineAt(raw, idKey.keyStart) + 1,
692
+ before: "(no \"type\")",
693
+ after: `"type": "${kind}"`,
694
+ rule: "manifest"
695
+ });
696
+ } else notes.push({
697
+ line: 1,
698
+ rule: "manifest",
699
+ message: `Add \`"type": "${kind}"\` next to "id"; the key could not be placed by hand.`
700
+ });
701
+ }
399
702
  }
400
703
  const compatibility = parsed.compatibility ?? {};
401
704
  for (const field of ["minimum", "verified"]) {
402
705
  const current = compatibility[field];
403
706
  const major = Number.parseInt(String(current ?? "0"), 10);
404
- if (!Number.isFinite(major) || major < 14) {
405
- compatibility[field] = "14";
707
+ if (Number.isFinite(major) && major >= 14) continue;
708
+ const block = topLevelKey(output, "compatibility");
709
+ const inner = block ? topLevelKey(output.slice(block.valueStart, block.valueEnd), field) : null;
710
+ if (block && inner && current !== void 0) {
711
+ const valueStart = block.valueStart + inner.valueStart;
712
+ const valueEnd = block.valueStart + inner.valueEnd;
713
+ output = `${output.slice(0, valueStart)}"14"${output.slice(valueEnd)}`;
406
714
  changes.push({
407
- line: 1,
408
- before: `compatibility.${field}: ${JSON.stringify(current ?? null)}`,
715
+ line: lineAt(output, block.valueStart + inner.keyStart),
716
+ before: `compatibility.${field}: ${JSON.stringify(current)}`,
409
717
  after: `compatibility.${field}: "14"`,
410
718
  rule: "manifest"
411
719
  });
720
+ continue;
412
721
  }
722
+ notes.push({
723
+ line: 1,
724
+ rule: "manifest",
725
+ message: `Set compatibility.${field} to "14"; it is ${JSON.stringify(current ?? null)} and could not be edited in place.`
726
+ });
413
727
  }
414
728
  const maximum = compatibility.maximum;
415
729
  if (maximum !== void 0 && Number.parseInt(String(maximum), 10) < 14) notes.push({
@@ -422,25 +736,86 @@ function transformManifest(raw, kind) {
422
736
  rule: "manifest",
423
737
  message: "gridDistance / gridUnits are ignored on v14. Move them into `\"grid\": { \"type\", \"distance\", \"units\", \"diagonals\" }`."
424
738
  });
425
- parsed.compatibility = compatibility;
426
739
  if (changes.length === 0) return notes.length ? {
427
740
  output: raw,
428
741
  changes,
429
742
  notes
430
743
  } : null;
431
- const ordered = {};
432
- for (const [key, value] of Object.entries(parsed)) {
433
- if (key === "type") continue;
434
- ordered[key] = value;
435
- if (key === "id") ordered.type = parsed.type;
436
- }
437
- if (!("type" in ordered)) ordered.type = parsed.type;
744
+ JSON.parse(output);
438
745
  return {
439
- output: `${JSON.stringify(ordered, null, 2)}\n`,
746
+ output,
440
747
  changes,
441
748
  notes
442
749
  };
443
750
  }
751
+ /**
752
+ * Where a key of the root object sits in the JSON text: the start of the
753
+ * quoted key, and the span of its value. Only depth one counts, so a
754
+ * `"type"` inside `relationships.systems[]` is not the manifest's `type`.
755
+ */
756
+ function topLevelKey(json, key) {
757
+ let depth = 0;
758
+ let i = 0;
759
+ const skipString = (from) => {
760
+ let j = from + 1;
761
+ for (; j < json.length; j += 1) if (json[j] === "\\") j += 1;
762
+ else if (json[j] === "\"") return j + 1;
763
+ return j;
764
+ };
765
+ const skipValue = (from) => {
766
+ let j = from;
767
+ while (j < json.length && /\s/.test(json[j] ?? "")) j += 1;
768
+ const ch = json[j] ?? "";
769
+ if (ch === "\"") return skipString(j);
770
+ if (ch === "{" || ch === "[") {
771
+ let d = 0;
772
+ for (let k = j; k < json.length; k += 1) {
773
+ const c = json[k] ?? "";
774
+ if (c === "\"") k = skipString(k) - 1;
775
+ else if (c === "{" || c === "[") d += 1;
776
+ else if (c === "}" || c === "]") {
777
+ d -= 1;
778
+ if (d === 0) return k + 1;
779
+ }
780
+ }
781
+ return json.length;
782
+ }
783
+ while (j < json.length && !/[,}\]\s]/.test(json[j] ?? "")) j += 1;
784
+ return j;
785
+ };
786
+ while (i < json.length) {
787
+ const ch = json[i] ?? "";
788
+ if (ch === "\"") {
789
+ const end = skipString(i);
790
+ if (depth === 1) {
791
+ const name = json.slice(i + 1, end - 1);
792
+ let k = end;
793
+ while (k < json.length && /\s/.test(json[k] ?? "")) k += 1;
794
+ if (json[k] === ":") {
795
+ const valueStart = (() => {
796
+ let v = k + 1;
797
+ while (v < json.length && /\s/.test(json[v] ?? "")) v += 1;
798
+ return v;
799
+ })();
800
+ const valueEnd = skipValue(k + 1);
801
+ if (name === key) return {
802
+ keyStart: i,
803
+ valueStart,
804
+ valueEnd
805
+ };
806
+ i = valueEnd;
807
+ continue;
808
+ }
809
+ }
810
+ i = end;
811
+ continue;
812
+ }
813
+ if (ch === "{" || ch === "[") depth += 1;
814
+ else if (ch === "}" || ch === "]") depth -= 1;
815
+ i += 1;
816
+ }
817
+ return null;
818
+ }
444
819
  //#endregion
445
820
  //#region src/migrate/index.ts
446
821
  /**
@@ -492,7 +867,7 @@ async function runMigrate(options) {
492
867
  if (write && result.output !== source) await writeFile(path, result.output, "utf8");
493
868
  }
494
869
  files.sort((a, b) => a.file.localeCompare(b.file));
495
- return {
870
+ const report = {
496
871
  cwd,
497
872
  files,
498
873
  written: write,
@@ -502,21 +877,65 @@ async function runMigrate(options) {
502
877
  notes: files.reduce((n, f) => n + f.notes.length, 0)
503
878
  }
504
879
  };
880
+ if (options.dataModels) {
881
+ const templatePath = join(cwd, "template.json");
882
+ if (!existsSync(templatePath)) report.dataModels = {
883
+ files: [],
884
+ documentTypes: {},
885
+ registration: "",
886
+ notes: ["No template.json here; nothing to generate."]
887
+ };
888
+ else {
889
+ const plan = planDataModels(JSON.parse(await readFile(templatePath, "utf8")), {
890
+ style: options.style ?? "plain",
891
+ lang: options.lang ?? "js"
892
+ });
893
+ const written = [];
894
+ for (const file of plan.files) {
895
+ const target = join(cwd, file.path);
896
+ if (existsSync(target)) {
897
+ plan.notes.unshift(`${file.path} exists and was left alone.`);
898
+ continue;
899
+ }
900
+ if (write) {
901
+ await mkdir(dirname(target), { recursive: true });
902
+ await writeFile(target, file.source, "utf8");
903
+ }
904
+ written.push(file.path);
905
+ }
906
+ report.dataModels = {
907
+ files: written,
908
+ documentTypes: plan.documentTypes,
909
+ registration: plan.registration,
910
+ notes: plan.notes
911
+ };
912
+ }
913
+ }
914
+ return report;
505
915
  }
506
916
  /** The report as text: one block per file, edits then notes. */
507
917
  function formatMigrateReport(report) {
508
918
  const lines = [];
509
- if (report.files.length === 0) {
919
+ if (report.files.length === 0 && !report.dataModels) {
510
920
  lines.push("Nothing to migrate. The project already reads as v14.");
511
921
  return `${lines.join("\n")}\n`;
512
922
  }
513
- lines.push(report.written ? `Rewrote ${report.counts.changes} place(s) in ${report.counts.files} file(s).` : `Would rewrite ${report.counts.changes} place(s) in ${report.counts.files} file(s). Run again with --write to apply.`);
923
+ if (report.files.length === 0) lines.push("Nothing to rewrite in the source or the manifest.");
924
+ else lines.push(report.written ? `Rewrote ${report.counts.changes} place(s) in ${report.counts.files} file(s).` : `Would rewrite ${report.counts.changes} place(s) in ${report.counts.files} file(s). Run again with --write to apply.`);
514
925
  for (const file of report.files) {
515
926
  lines.push("", `${file.file}`);
516
927
  for (const change of file.changes) lines.push(` ${change.line}: ${oneLine(change.before)}`, ` ${" ".repeat(String(change.line).length)} → ${oneLine(change.after)}`);
517
928
  for (const note of file.notes) lines.push(` ${note.line}: needs a decision: ${note.message}`);
518
929
  }
519
930
  if (report.counts.notes > 0) lines.push("", `${report.counts.notes} place(s) need a decision. Run \`vttforge audit\` after editing them.`);
931
+ if (report.dataModels) {
932
+ const dm = report.dataModels;
933
+ lines.push("", report.written ? `Wrote ${dm.files.length} data model file(s) from template.json:` : `Would write ${dm.files.length} data model file(s) from template.json:`);
934
+ for (const f of dm.files) lines.push(` ${f}`);
935
+ if (Object.keys(dm.documentTypes).length > 0) lines.push("", "Declare the types in the manifest:", ` "documentTypes": ${JSON.stringify(dm.documentTypes)}`);
936
+ 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}`);
938
+ }
520
939
  return `${lines.join("\n")}\n`;
521
940
  }
522
941
  function oneLine(text) {
@@ -539,7 +958,10 @@ async function runMigrateCommand(options = {}) {
539
958
  });
540
959
  const report = await runMigrate({
541
960
  cwd,
542
- write: options.write === true
961
+ write: options.write === true,
962
+ dataModels: options.dataModels === true,
963
+ style: options.style,
964
+ lang: options.lang
543
965
  });
544
966
  out(options.json ? `${JSON.stringify(report, null, 2)}\n` : formatMigrateReport(report));
545
967
  return {
@@ -684,6 +1106,48 @@ const build = defineCommand({
684
1106
  }
685
1107
  }
686
1108
  });
1109
+ const lint = defineCommand({
1110
+ meta: {
1111
+ name: "lint",
1112
+ description: "Run Biome (shipped with the CLI) over the project, then the v14 audit"
1113
+ },
1114
+ args: {
1115
+ path: {
1116
+ type: "positional",
1117
+ description: "Project root to lint (defaults to the current directory)",
1118
+ required: false
1119
+ },
1120
+ fix: {
1121
+ type: "boolean",
1122
+ default: false,
1123
+ description: "Write the safe fixes and format the files instead of only reporting"
1124
+ },
1125
+ audit: {
1126
+ type: "boolean",
1127
+ default: true,
1128
+ description: "Run `vttforge audit` after Biome (use --no-audit to skip)"
1129
+ },
1130
+ strict: {
1131
+ type: "boolean",
1132
+ default: false,
1133
+ description: "For the audit: exit non-zero on any finding, not only HIGH"
1134
+ }
1135
+ },
1136
+ async run({ args }) {
1137
+ try {
1138
+ const result = await runLintCommand({
1139
+ cwd: typeof args.path === "string" ? args.path : void 0,
1140
+ fix: args.fix === true,
1141
+ audit: args.audit !== false,
1142
+ strict: args.strict === true
1143
+ });
1144
+ if (result.exitCode !== 0) process.exitCode = result.exitCode;
1145
+ } catch (err) {
1146
+ console.error(err instanceof Error ? err.message : String(err));
1147
+ process.exitCode = 1;
1148
+ }
1149
+ }
1150
+ });
687
1151
  const audit = defineCommand({
688
1152
  meta: {
689
1153
  name: "audit",
@@ -740,6 +1204,21 @@ const migrate = defineCommand({
740
1204
  type: "boolean",
741
1205
  default: false,
742
1206
  description: "Emit the report as JSON"
1207
+ },
1208
+ "data-models": {
1209
+ type: "boolean",
1210
+ default: false,
1211
+ description: "Also generate a data model per template.json type (template.json is deprecated since v14)"
1212
+ },
1213
+ style: {
1214
+ type: "string",
1215
+ default: "plain",
1216
+ description: "For --data-models: \"plain\" Foundry classes, or \"sdk\" classes on @vttforge/core"
1217
+ },
1218
+ lang: {
1219
+ type: "string",
1220
+ default: "js",
1221
+ description: "For --data-models: \"js\" writes .mjs, \"ts\" writes .ts"
743
1222
  }
744
1223
  },
745
1224
  async run({ args }) {
@@ -747,7 +1226,10 @@ const migrate = defineCommand({
747
1226
  const { exitCode } = await runMigrateCommand({
748
1227
  cwd: args.path ? String(args.path) : void 0,
749
1228
  write: Boolean(args.write),
750
- json: Boolean(args.json)
1229
+ json: Boolean(args.json),
1230
+ dataModels: Boolean(args["data-models"]),
1231
+ style: String(args.style) === "sdk" ? "sdk" : "plain",
1232
+ lang: String(args.lang) === "ts" ? "ts" : "js"
751
1233
  });
752
1234
  process.exitCode = exitCode;
753
1235
  } catch (error) {
@@ -760,12 +1242,13 @@ const main = defineCommand({
760
1242
  meta: {
761
1243
  name: "vttforge",
762
1244
  version: VTTFORGE_CLI_VERSION,
763
- description: "VTTForge CLI: scaffold, dev, build, audit and migrate for Foundry v14+ systems and modules"
1245
+ description: "VTTForge CLI: scaffold, dev, build, lint, audit and migrate for Foundry v14+ systems and modules"
764
1246
  },
765
1247
  subCommands: {
766
1248
  init,
767
1249
  dev,
768
1250
  build,
1251
+ lint,
769
1252
  audit,
770
1253
  migrate
771
1254
  }