@vttforge/cli 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @vttforge/cli
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 11afe13: `vttforge migrate` rewrites a v13 system or module for v14: bare `mergeObject`-style globals, `-=` and `==` update keys, `rollMode`, context-menu and header-control keys, numeric Active Effect modes, whole-array `CONFIG.statusEffects` assignment, `legacyTransferral`, the core-sheet unregister lines, and the manifest's `type` and `compatibility`. It reports by default and writes with `--write`; what it cannot decide it reports as needing a decision.
8
+
9
+ ### Patch Changes
10
+
11
+ - c7a9920: The templates pin `@vttforge/core` at `^0.15.0`, the release that carries `@SystemSetting`.
12
+
3
13
  ## 0.9.0
4
14
 
5
15
  ### Minor Changes
package/README.md CHANGED
@@ -14,6 +14,7 @@ vttforge init <name> [--type system|module] [--lang ts|js] [--id] [--title] [--d
14
14
  vttforge dev [--foundry-data <path>] [--port <n>]
15
15
  vttforge build
16
16
  vttforge audit [dir] [--json] [--strict]
17
+ vttforge migrate [dir] [--write] [--json]
17
18
  ```
18
19
 
19
20
  **`init`** writes a runnable system or module into `<name>/` from one of four templates (`system-ts`, `system-js`, `module-ts`, `module-js`). It asks for what you did not pass, or takes defaults with `--yes`, so it works in CI. It detects the package manager that invoked it (`pnpm`, `npm`, `bun`, `yarn`), installs, and runs `git init`.
@@ -24,6 +25,8 @@ vttforge audit [dir] [--json] [--strict]
24
25
 
25
26
  **`audit`** checks the manifest, the source and the templates against the v14 breakages that fail quietly: the `flags.hotReload` shape, the removed grid fields, the v12 `styles` shape, `HTMLField`/`FilePathField` paths missing from `documentTypes`, `TypeDataModel` without `prepareBaseData`, a bad `_addDataFieldMigrations` override, token attributes that do not point at a `{ value, max }` field, a sheet template that opens a `<form>` the sheet already is, a declared subtype with no name in any language file, a `template.json` that erases the metadata `system.json` declares for the same type, and the v13 code v14 broke or deprecated: bare `mergeObject`-style globals, `-=` update keys, `rollMode`, whole-array `CONFIG.statusEffects` assignment, `legacyTransferral`, numeric Active Effect modes. `--json` for machines; `--strict` exits non-zero on any finding rather than only on HIGH.
26
27
 
28
+ **`migrate`** rewrites a v13 project for v14: the removed globals, `-=` keys, `rollMode`, context-menu keys, numeric effect modes, whole-array `CONFIG.statusEffects`, `legacyTransferral`, the core-sheet unregister lines, and the manifest's `type` and `compatibility`. It reports by default and writes with `--write`; what it will not decide it lists as needing one.
29
+
27
30
  ## As a library
28
31
 
29
32
  Every command is exported for tooling built on top: `runInit`, `runDev`, `runBuild`, `runAudit`, `emitReleaseZip`, `resolveFoundryDataDir`, `readManifest`, and the scaffold helpers.
package/dist/bin.mjs CHANGED
@@ -1,6 +1,536 @@
1
1
  #!/usr/bin/env node
2
- import { i as runDev, l as runAuditCommand, n as ScaffoldError, o as runBuild, r as runInit, t as VTTFORGE_CLI_VERSION } from "./src-BAHJHuJ7.mjs";
2
+ import { f as REMOVED_UTILS, i as runDev, l as runAuditCommand, m as _internal, n as ScaffoldError, o as runBuild, r as runInit, t as VTTFORGE_CLI_VERSION } from "./src-CZnBIzlF.mjs";
3
+ import { existsSync } from "node:fs";
4
+ import { join, relative, resolve } from "node:path";
5
+ import { readFile, stat, writeFile } from "node:fs/promises";
3
6
  import { defineCommand, runMain } from "citty";
7
+ //#region src/migrate/transforms.ts
8
+ /**
9
+ * The rewrites `vttforge migrate` applies to a v13 source file.
10
+ *
11
+ * Each transform is a pure function over the file's text. It returns the new
12
+ * text, one `Change` per edit it made, and one `Note` per thing it saw and
13
+ * would not touch: a rewrite that needs a decision (which page a `game.template`
14
+ * read should become) is reported, not guessed.
15
+ *
16
+ * Text-based, like the audit rules they mirror (`VTTF-AUDIT-011` to `016`).
17
+ * The patterns are short and mechanical, and a syntax tree would not make
18
+ * `'-=key'` easier to find. The cost is that a match inside a string or a
19
+ * comment is rewritten too; the preview exists so that is seen before it is
20
+ * written.
21
+ */
22
+ function lineAt(source, index) {
23
+ let line = 1;
24
+ for (let i = 0; i < index && i < source.length; i += 1) if (source[i] === "\n") line += 1;
25
+ return line;
26
+ }
27
+ /** The whole line an index sits on, trimmed, for the report. */
28
+ function lineText(source, index) {
29
+ const start = source.lastIndexOf("\n", index - 1) + 1;
30
+ const end = source.indexOf("\n", index);
31
+ return source.slice(start, end === -1 ? source.length : end).trim();
32
+ }
33
+ /**
34
+ * Replace every match, recording one change per match against the original
35
+ * text. The replacement may be a string or a function, like `String#replace`.
36
+ */
37
+ function rewrite(source, pattern, replacement, rule) {
38
+ const changes = [];
39
+ return {
40
+ output: source.replace(pattern, (match, ...rest) => {
41
+ const offset = rest.find((r) => typeof r === "number") ?? 0;
42
+ const groups = rest.filter((r) => typeof r === "string");
43
+ const after = typeof replacement === "string" ? replacement : replacement(match, ...groups);
44
+ if (after !== match) changes.push({
45
+ line: lineAt(source, offset),
46
+ before: match,
47
+ after,
48
+ rule
49
+ });
50
+ return after;
51
+ }),
52
+ changes,
53
+ notes: []
54
+ };
55
+ }
56
+ function merge(...results) {
57
+ return {
58
+ output: results.at(-1)?.output ?? "",
59
+ changes: results.flatMap((r) => r.changes),
60
+ notes: results.flatMap((r) => r.notes)
61
+ };
62
+ }
63
+ /** Run transforms in sequence, each on the previous one's output. */
64
+ function pipe(source, transforms) {
65
+ const results = [];
66
+ let current = source;
67
+ for (const transform of transforms) {
68
+ const result = transform(current);
69
+ results.push(result);
70
+ current = result.output;
71
+ }
72
+ return merge(...results);
73
+ }
74
+ /**
75
+ * Bare v12 utility globals → `foundry.utils.*`; `Math.clamped` → `Math.clamp`.
76
+ *
77
+ * A name the file declares or imports itself is left alone, the same way
78
+ * `VTTF-AUDIT-011` leaves it alone. `game.template` is reported, not
79
+ * rewritten: whether it becomes `game.model` or a `documentTypes` read depends
80
+ * on what was read from it.
81
+ */
82
+ const removedGlobals = (source) => {
83
+ const own = new Set(REMOVED_UTILS.filter((name) => new RegExp(`(?:function\\s+${name}\\b|(?:const|let|var)\\s+${name}\\b|import[^;]*\\b${name}\\b|\\b${name}\\s*\\([^)]*\\)\\s*\\{)`).test(source)));
84
+ const names = REMOVED_UTILS.filter((name) => !own.has(name));
85
+ const utils = names.length ? rewrite(source, new RegExp(`(?<![\\w$.])(${names.join("|")})\\s*\\(`, "g"), (_m, name) => `foundry.utils.${name}(`, "removed-globals") : {
86
+ output: source,
87
+ changes: [],
88
+ notes: []
89
+ };
90
+ const clamped = rewrite(utils.output, /\bMath\.clamped\s*\(/g, "Math.clamp(", "removed-globals");
91
+ const notes = [];
92
+ for (const match of clamped.output.matchAll(/\bgame\.template\b/g)) notes.push({
93
+ line: lineAt(clamped.output, match.index ?? 0),
94
+ rule: "removed-globals",
95
+ message: "`game.template` is gone. Read type defaults from `game.model`, or the type list from the package's `documentTypes`."
96
+ });
97
+ return {
98
+ ...merge(utils, clamped),
99
+ notes
100
+ };
101
+ };
102
+ /**
103
+ * `'-=key': null` → `key: _del`; `'==key': value` → `key: _replace(value)`;
104
+ * `performDeletions` → `applyOperators`; `objectsEqual` → `equals`.
105
+ */
106
+ const dataOperators = (source) => {
107
+ const deletions = rewrite(source, /(['"])((?:[\w$]+\.)*)-=([\w$.]+)\1\s*:\s*null\b/g, (_m, quote, prefix, key) => `${quote}${prefix}${key}${quote}: _del`, "data-operators");
108
+ const replacements = wrapReplacementValues(deletions.output);
109
+ const flags = rewrite(replacements.output, /\bperformDeletions\s*:/g, "applyOperators:", "data-operators");
110
+ return merge(deletions, replacements, flags, rewrite(flags.output, /\bfoundry\.utils\.objectsEqual\s*\(/g, "foundry.utils.equals(", "data-operators"));
111
+ };
112
+ function wrapReplacementValues(source) {
113
+ const changes = [];
114
+ const pattern = /(['"])((?:[\w$]+\.)*)==([\w$.]+)\1\s*:\s*/g;
115
+ let out = "";
116
+ let cursor = 0;
117
+ for (const match of source.matchAll(pattern)) {
118
+ const start = match.index ?? 0;
119
+ const valueStart = start + match[0].length;
120
+ const valueEnd = scanValueEnd(source, valueStart);
121
+ if (valueEnd === -1) continue;
122
+ const value = source.slice(valueStart, valueEnd).trimEnd();
123
+ const [, quote = "\"", prefix = "", key = ""] = match;
124
+ const after = `${quote}${prefix}${key}${quote}: _replace(${value})`;
125
+ out += source.slice(cursor, start) + after;
126
+ cursor = valueStart + value.length;
127
+ changes.push({
128
+ line: lineAt(source, start),
129
+ before: source.slice(start, cursor),
130
+ after,
131
+ rule: "data-operators"
132
+ });
133
+ }
134
+ out += source.slice(cursor);
135
+ return {
136
+ output: out,
137
+ changes,
138
+ notes: []
139
+ };
140
+ }
141
+ /** Index just past a value that starts at `from`: the next `,` or `}` at depth zero. */
142
+ function scanValueEnd(source, from) {
143
+ let depth = 0;
144
+ let quote = null;
145
+ for (let i = from; i < source.length; i += 1) {
146
+ const ch = source[i] ?? "";
147
+ if (quote) {
148
+ if (ch === "\\") i += 1;
149
+ else if (ch === quote) quote = null;
150
+ continue;
151
+ }
152
+ if (ch === "\"" || ch === "'" || ch === "`") quote = ch;
153
+ else if (ch === "{" || ch === "[" || ch === "(") depth += 1;
154
+ else if (ch === "}" || ch === "]" || ch === ")") {
155
+ if (depth === 0) return i;
156
+ depth -= 1;
157
+ } else if (ch === "," && depth === 0) return i;
158
+ }
159
+ return -1;
160
+ }
161
+ const ROLL_MODE_VALUES = {
162
+ publicroll: "public",
163
+ gmroll: "gm",
164
+ blindroll: "blind",
165
+ selfroll: "self"
166
+ };
167
+ const ROLL_MODE_CONSTANTS = {
168
+ PUBLIC: "public",
169
+ PRIVATE: "gm",
170
+ BLIND: "blind",
171
+ SELF: "self"
172
+ };
173
+ /**
174
+ * `rollMode` → `messageMode`, with the value mapped when it is a literal.
175
+ *
176
+ * `"roll"` meant "whatever the user's chat dropdown says", which is what an
177
+ * absent `messageMode` means now, so it becomes `undefined`. A value that is
178
+ * an expression is left for the reader, with a note.
179
+ */
180
+ const rollMode = (source) => {
181
+ const notes = [];
182
+ 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");
183
+ const key = rewrite(option.output, /\brollMode\s*:/g, (m) => m.replace("rollMode", "messageMode"), "roll-mode");
184
+ for (const change of key.changes) notes.push({
185
+ line: change.line,
186
+ rule: "roll-mode",
187
+ message: "The value is an expression. If it can be a v13 mode name, wrap it: `Roll._mapLegacyRollMode(value)`."
188
+ });
189
+ const setting = rewrite(key.output, /(['"])core\1\s*,\s*(['"])rollMode\2/g, (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`, "roll-mode");
190
+ const modes = rewrite(setting.output, /\bCONFIG\.Dice\.rollModes\b/g, "CONFIG.ChatMessage.modes", "roll-mode");
191
+ return {
192
+ ...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")),
193
+ notes
194
+ };
195
+ };
196
+ /**
197
+ * Context-menu entries and header controls: `name` → `label`, `condition` →
198
+ * `visible`, `callback` → `onClick`. Only inside an object literal that has a
199
+ * `callback` and an `icon` or `condition`, so an unrelated `name:` elsewhere
200
+ * is not renamed. The callback's parameters change too, from `(li)` to
201
+ * `(event, target)`, and that is noted rather than rewritten.
202
+ */
203
+ const contextMenuKeys = (source) => {
204
+ const changes = [];
205
+ const notes = [];
206
+ let output = source;
207
+ const literals = objectLiterals(source);
208
+ for (const { start, end } of literals.reverse()) {
209
+ const body = output.slice(start, end);
210
+ if (!/\bcallback\s*:/.test(body) || !/\b(?:icon|condition)\s*:/.test(body)) continue;
211
+ const renamed = body.replace(/(^|[{,\s])name\s*:/g, "$1label:").replace(/(^|[{,\s])condition\s*:/g, "$1visible:").replace(/(^|[{,\s])callback\s*:/g, "$1onClick:");
212
+ if (renamed === body) continue;
213
+ changes.push({
214
+ line: lineAt(source, start),
215
+ before: lineText(source, start),
216
+ after: "label / visible / onClick keys",
217
+ rule: "context-menu-keys"
218
+ });
219
+ notes.push({
220
+ line: lineAt(source, start),
221
+ rule: "context-menu-keys",
222
+ message: "`onClick` receives `(event, target)` where `callback` received the element. Check the parameter list."
223
+ });
224
+ output = output.slice(0, start) + renamed + output.slice(end);
225
+ }
226
+ return {
227
+ output,
228
+ changes,
229
+ notes
230
+ };
231
+ };
232
+ /** Every `{ ... }` span in the text, outermost first, strings and comments skipped. */
233
+ function objectLiterals(source) {
234
+ const spans = [];
235
+ const stack = [];
236
+ let quote = null;
237
+ for (let i = 0; i < source.length; i += 1) {
238
+ const ch = source[i] ?? "";
239
+ const next = source[i + 1] ?? "";
240
+ if (quote) {
241
+ if (ch === "\\") i += 1;
242
+ else if (ch === quote) quote = null;
243
+ continue;
244
+ }
245
+ if (ch === "/" && next === "/") {
246
+ i = source.indexOf("\n", i);
247
+ if (i === -1) break;
248
+ continue;
249
+ }
250
+ if (ch === "/" && next === "*") {
251
+ const close = source.indexOf("*/", i + 2);
252
+ i = close === -1 ? source.length : close + 1;
253
+ continue;
254
+ }
255
+ if (ch === "\"" || ch === "'" || ch === "`") quote = ch;
256
+ else if (ch === "{") stack.push(i);
257
+ else if (ch === "}") {
258
+ const start = stack.pop();
259
+ if (start !== void 0) spans.push({
260
+ start,
261
+ end: i + 1
262
+ });
263
+ }
264
+ }
265
+ return spans.sort((a, b) => a.start - b.start);
266
+ }
267
+ /**
268
+ * `legacyTransferral` is gone: the assignment, and the `activeEffect`
269
+ * option `registerSystem` used to take for it.
270
+ */
271
+ const legacyTransferral = (source) => {
272
+ const statement = rewrite(source, /^[ \t]*CONFIG\.ActiveEffect\.legacyTransferral\s*=[^\n]*\n?/gm, "", "legacy-transferral");
273
+ const option = rewrite(statement.output, /^[ \t]*activeEffect\s*:\s*\{\s*legacyTransferral\s*:\s*(?:true|false)\s*,?\s*\}\s*,?[ \t]*\n?/gm, "", "legacy-transferral");
274
+ return merge(statement, option, rewrite(option.output, /^[ \t]*legacyTransferral\s*:\s*(?:true|false)\s*,?[ \t]*\n?/gm, "", "legacy-transferral"));
275
+ };
276
+ /** v14 registers no core Actor or Item sheet, so there is nothing to unregister. */
277
+ const unregisterCoreSheets = (source) => rewrite(source, /^[ \t]*(?:foundry\.documents\.collections\.)?(?:Actors|Items)\.unregisterSheet\(\s*['"]core['"][^\n]*\n?/gm, "", "unregister-core-sheets");
278
+ /**
279
+ * `CONFIG.statusEffects = list;` → add each entry by id. The setter empties
280
+ * the collection first, which wipes what other packages added.
281
+ */
282
+ const statusEffectsAssignment = (source) => {
283
+ const changes = [];
284
+ let output = "";
285
+ let cursor = 0;
286
+ for (const match of source.matchAll(/\bCONFIG\.statusEffects\s*=(?!=)\s*/g)) {
287
+ const start = match.index ?? 0;
288
+ const valueStart = start + match[0].length;
289
+ const end = scanStatementEnd(source, valueStart);
290
+ if (end === -1) continue;
291
+ const after = `for (const effect of ${source.slice(valueStart, end).trim()}) CONFIG.statusEffects[effect.id] = effect;`;
292
+ output += source.slice(cursor, start) + after;
293
+ cursor = end + 1;
294
+ changes.push({
295
+ line: lineAt(source, start),
296
+ before: source.slice(start, cursor).trim(),
297
+ after,
298
+ rule: "status-effects"
299
+ });
300
+ }
301
+ output += source.slice(cursor);
302
+ return {
303
+ output,
304
+ changes,
305
+ notes: []
306
+ };
307
+ };
308
+ /** Index of the `;` that ends a statement starting at `from`, brackets balanced. */
309
+ function scanStatementEnd(source, from) {
310
+ let depth = 0;
311
+ let quote = null;
312
+ for (let i = from; i < source.length; i += 1) {
313
+ const ch = source[i] ?? "";
314
+ if (quote) {
315
+ if (ch === "\\") i += 1;
316
+ else if (ch === quote) quote = null;
317
+ continue;
318
+ }
319
+ if (ch === "\"" || ch === "'" || ch === "`") quote = ch;
320
+ else if (ch === "{" || ch === "[" || ch === "(") depth += 1;
321
+ else if (ch === "}" || ch === "]" || ch === ")") depth -= 1;
322
+ else if (ch === ";" && depth === 0) return i;
323
+ }
324
+ return -1;
325
+ }
326
+ const EFFECT_MODES = {
327
+ CUSTOM: "custom",
328
+ MULTIPLY: "multiply",
329
+ ADD: "add",
330
+ DOWNGRADE: "downgrade",
331
+ UPGRADE: "upgrade",
332
+ OVERRIDE: "override"
333
+ };
334
+ /**
335
+ * `mode: CONST.ACTIVE_EFFECT_MODES.ADD` → `type: "add"`. A root-level
336
+ * `changes` array on an effect now lives under `system.changes`; that move
337
+ * depends on where the data is built, so it is noted.
338
+ */
339
+ const activeEffectModes = (source) => {
340
+ const typed = rewrite(source, /\bmode\s*:\s*CONST\.ACTIVE_EFFECT_MODES\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\b/g, (_m, name) => `type: "${EFFECT_MODES[name]}"`, "active-effect-modes");
341
+ const bare = rewrite(typed.output, /\bCONST\.ACTIVE_EFFECT_MODES\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\b/g, (_m, name) => `"${EFFECT_MODES[name]}"`, "active-effect-modes");
342
+ const notes = typed.changes.map((c) => ({
343
+ line: c.line,
344
+ rule: "active-effect-modes",
345
+ message: "The change now belongs under `system.changes`, not a root-level `changes` array."
346
+ }));
347
+ return {
348
+ ...merge(typed, bare),
349
+ notes
350
+ };
351
+ };
352
+ /** The transforms, in the order they run. */
353
+ const SOURCE_TRANSFORMS = [
354
+ ["removed-globals", removedGlobals],
355
+ ["data-operators", dataOperators],
356
+ ["roll-mode", rollMode],
357
+ ["context-menu-keys", contextMenuKeys],
358
+ ["legacy-transferral", legacyTransferral],
359
+ ["unregister-core-sheets", unregisterCoreSheets],
360
+ ["status-effects", statusEffectsAssignment],
361
+ ["active-effect-modes", activeEffectModes]
362
+ ];
363
+ function transformSource(source) {
364
+ return pipe(source, SOURCE_TRANSFORMS.map(([, t]) => t));
365
+ }
366
+ /**
367
+ * The manifest: `type` declared, `compatibility` raised to 14 where it is
368
+ * lower. Returns `null` when nothing needed to change.
369
+ */
370
+ function transformManifest(raw, kind) {
371
+ const parsed = JSON.parse(raw);
372
+ const changes = [];
373
+ const notes = [];
374
+ if (parsed.type !== kind) {
375
+ parsed.type = kind;
376
+ changes.push({
377
+ line: 1,
378
+ before: "(no \"type\")",
379
+ after: `"type": "${kind}"`,
380
+ rule: "manifest"
381
+ });
382
+ }
383
+ const compatibility = parsed.compatibility ?? {};
384
+ for (const field of ["minimum", "verified"]) {
385
+ const current = compatibility[field];
386
+ const major = Number.parseInt(String(current ?? "0"), 10);
387
+ if (!Number.isFinite(major) || major < 14) {
388
+ compatibility[field] = "14";
389
+ changes.push({
390
+ line: 1,
391
+ before: `compatibility.${field}: ${JSON.stringify(current ?? null)}`,
392
+ after: `compatibility.${field}: "14"`,
393
+ rule: "manifest"
394
+ });
395
+ }
396
+ }
397
+ const maximum = compatibility.maximum;
398
+ if (maximum !== void 0 && Number.parseInt(String(maximum), 10) < 14) notes.push({
399
+ line: 1,
400
+ rule: "manifest",
401
+ message: `compatibility.maximum is ${JSON.stringify(maximum)}, which keeps the package off v14. Raise it or remove it.`
402
+ });
403
+ if ("gridDistance" in parsed || "gridUnits" in parsed) notes.push({
404
+ line: 1,
405
+ rule: "manifest",
406
+ message: "gridDistance / gridUnits are ignored on v14. Move them into `\"grid\": { \"type\", \"distance\", \"units\", \"diagonals\" }`."
407
+ });
408
+ parsed.compatibility = compatibility;
409
+ if (changes.length === 0) return notes.length ? {
410
+ output: raw,
411
+ changes,
412
+ notes
413
+ } : null;
414
+ const ordered = {};
415
+ for (const [key, value] of Object.entries(parsed)) {
416
+ if (key === "type") continue;
417
+ ordered[key] = value;
418
+ if (key === "id") ordered.type = parsed.type;
419
+ }
420
+ if (!("type" in ordered)) ordered.type = parsed.type;
421
+ return {
422
+ output: `${JSON.stringify(ordered, null, 2)}\n`,
423
+ changes,
424
+ notes
425
+ };
426
+ }
427
+ //#endregion
428
+ //#region src/migrate/index.ts
429
+ /**
430
+ * `vttforge migrate`: rewrite a v13 project for v14.
431
+ *
432
+ * Walks the same files the audit walks, applies the transforms, and reports
433
+ * every edit and every thing it saw and would not decide for you. Nothing is
434
+ * written unless asked: the preview is the default, because a text rewrite
435
+ * that touched a string literal is something to see before it lands.
436
+ */
437
+ async function runMigrate(options) {
438
+ const { cwd } = options;
439
+ const write = options.write === true;
440
+ if (!existsSync(cwd) || !(await stat(cwd)).isDirectory()) throw new Error(`Migrate target is not a directory: ${cwd}`);
441
+ const files = [];
442
+ for (const [name, kind] of [["system.json", "system"], ["module.json", "module"]]) {
443
+ const path = join(cwd, name);
444
+ if (!existsSync(path)) continue;
445
+ let raw;
446
+ try {
447
+ raw = await readFile(path, "utf8");
448
+ JSON.parse(raw);
449
+ } catch {
450
+ continue;
451
+ }
452
+ const result = transformManifest(raw, kind);
453
+ if (result === null) continue;
454
+ files.push({
455
+ file: name,
456
+ changes: result.changes,
457
+ notes: result.notes
458
+ });
459
+ if (write && result.changes.length > 0) await writeFile(path, result.output, "utf8");
460
+ }
461
+ for await (const path of _internal.walkSourceFiles(cwd)) {
462
+ let source;
463
+ try {
464
+ source = await readFile(path, "utf8");
465
+ } catch {
466
+ continue;
467
+ }
468
+ const result = transformSource(source);
469
+ if (result.changes.length === 0 && result.notes.length === 0) continue;
470
+ files.push({
471
+ file: relative(cwd, path),
472
+ changes: result.changes,
473
+ notes: result.notes
474
+ });
475
+ if (write && result.output !== source) await writeFile(path, result.output, "utf8");
476
+ }
477
+ files.sort((a, b) => a.file.localeCompare(b.file));
478
+ return {
479
+ cwd,
480
+ files,
481
+ written: write,
482
+ counts: {
483
+ files: files.length,
484
+ changes: files.reduce((n, f) => n + f.changes.length, 0),
485
+ notes: files.reduce((n, f) => n + f.notes.length, 0)
486
+ }
487
+ };
488
+ }
489
+ /** The report as text: one block per file, edits then notes. */
490
+ function formatMigrateReport(report) {
491
+ const lines = [];
492
+ if (report.files.length === 0) {
493
+ lines.push("Nothing to migrate. The project already reads as v14.");
494
+ return `${lines.join("\n")}\n`;
495
+ }
496
+ 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.`);
497
+ for (const file of report.files) {
498
+ lines.push("", `${file.file}`);
499
+ for (const change of file.changes) lines.push(` ${change.line}: ${oneLine(change.before)}`, ` ${" ".repeat(String(change.line).length)} → ${oneLine(change.after)}`);
500
+ for (const note of file.notes) lines.push(` ${note.line}: needs a decision: ${note.message}`);
501
+ }
502
+ if (report.counts.notes > 0) lines.push("", `${report.counts.notes} place(s) need a decision. Run \`vttforge audit\` after editing them.`);
503
+ return `${lines.join("\n")}\n`;
504
+ }
505
+ function oneLine(text) {
506
+ const flat = text.replace(/\s+/g, " ").trim();
507
+ return flat.length > 100 ? `${flat.slice(0, 97)}...` : flat;
508
+ }
509
+ //#endregion
510
+ //#region src/commands/migrate.ts
511
+ /**
512
+ * `vttforge migrate`: the CLI surface over the v13 → v14 rewrite.
513
+ *
514
+ * Exit codes:
515
+ * 0: ran, whether or not anything changed
516
+ * 1: the target is not a directory
517
+ */
518
+ async function runMigrateCommand(options = {}) {
519
+ const cwd = resolve(options.cwd ?? process.cwd());
520
+ const out = options.out ?? ((chunk) => {
521
+ process.stdout.write(chunk);
522
+ });
523
+ const report = await runMigrate({
524
+ cwd,
525
+ write: options.write === true
526
+ });
527
+ out(options.json ? `${JSON.stringify(report, null, 2)}\n` : formatMigrateReport(report));
528
+ return {
529
+ report,
530
+ exitCode: 0
531
+ };
532
+ }
533
+ //#endregion
4
534
  //#region src/cli.ts
5
535
  /**
6
536
  * vttforge command tree.
@@ -173,17 +703,54 @@ const audit = defineCommand({
173
703
  }
174
704
  }
175
705
  });
706
+ const migrate = defineCommand({
707
+ meta: {
708
+ name: "migrate",
709
+ description: "Rewrite a v13 system or module for Foundry v14 (preview by default)"
710
+ },
711
+ args: {
712
+ path: {
713
+ type: "positional",
714
+ description: "Project root to rewrite (defaults to the current directory)",
715
+ required: false
716
+ },
717
+ write: {
718
+ type: "boolean",
719
+ default: false,
720
+ description: "Write the edits. Without it, the command only reports what it would change"
721
+ },
722
+ json: {
723
+ type: "boolean",
724
+ default: false,
725
+ description: "Emit the report as JSON"
726
+ }
727
+ },
728
+ async run({ args }) {
729
+ try {
730
+ const { exitCode } = await runMigrateCommand({
731
+ cwd: args.path ? String(args.path) : void 0,
732
+ write: Boolean(args.write),
733
+ json: Boolean(args.json)
734
+ });
735
+ process.exitCode = exitCode;
736
+ } catch (error) {
737
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
738
+ process.exitCode = 1;
739
+ }
740
+ }
741
+ });
176
742
  const main = defineCommand({
177
743
  meta: {
178
744
  name: "vttforge",
179
745
  version: VTTFORGE_CLI_VERSION,
180
- description: "VTTForge CLI: scaffold, dev, build and audit for Foundry v14+ systems and modules"
746
+ description: "VTTForge CLI: scaffold, dev, build, audit and migrate for Foundry v14+ systems and modules"
181
747
  },
182
748
  subCommands: {
183
749
  init,
184
750
  dev,
185
751
  build,
186
- audit
752
+ audit,
753
+ migrate
187
754
  }
188
755
  });
189
756
  //#endregion