@vttforge/cli 0.13.0 → 0.15.1

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.mjs","names":["pascal","camel"],"sources":["../src/migrate/data-models.ts","../src/migrate/sheet-templates.ts","../src/migrate/parse.ts","../src/migrate/sheet-bodies.ts","../src/migrate/sheet-listeners.ts","../src/migrate/sheet-options.ts","../src/migrate/sheets.ts","../src/migrate/transforms.ts","../src/migrate/index.ts","../src/commands/migrate.ts","../src/cli.ts","../src/bin.ts"],"sourcesContent":["/**\n * `template.json` → one data model per type.\n *\n * v14 deprecates `template.json` and removes it in v16; the replacement is a\n * `TypeDataModel` per type registered on `CONFIG.<Document>.dataModels`,\n * with the type names declared under `documentTypes` in the manifest. The\n * shape is already in the template: every default value says what field it\n * is, and every `templates` entry is a fragment several types share. This\n * reads that and writes the classes, so the move is a review of generated\n * code rather than a transcription.\n *\n * What is inferred, and what is guessed:\n * - a number is a `NumberField` (`integer` when the default is one), a\n * boolean a `BooleanField`, a string a `StringField` (`HTMLField` when the\n * key reads like rich text: description, biography, notes, details), an object a\n * `SchemaField`, an array an `ArrayField` of whatever its first element is\n * (`ObjectField` when it is empty or holds objects), `null` an\n * `ObjectField` marked for review.\n * - a `templates` fragment becomes a function returning a partial schema, so\n * each type's schema spreads the fragments it listed, in the order the\n * template listed them, then its own keys. Foundry's implicit `base`\n * template is skipped.\n */\n\nexport type EmitStyle = 'plain' | 'sdk';\n\ninterface DataModelFile {\n /** Project-relative path to write. */\n path: string;\n source: string;\n}\n\nexport interface DataModelPlan {\n files: DataModelFile[];\n /** The `documentTypes` block the manifest needs, per document. */\n documentTypes: Record<string, Record<string, Record<string, unknown>>>;\n /** The registration a system adds in `init`, as source text. */\n registration: string;\n /** Things the reader has to decide. */\n notes: string[];\n}\n\ninterface DocumentTemplate {\n types?: string[];\n templates?: Record<string, Record<string, unknown>>;\n htmlFields?: string[];\n filePathFields?: string[];\n gmOnlyFields?: string[];\n [type: string]: unknown;\n}\n\nconst RICH_TEXT_KEYS = /^(description|biography|bio|notes|details)$/i;\n\nfunction fieldFor(\n key: string,\n value: unknown,\n path: string,\n notes: string[],\n indent: string,\n): string {\n const next = `${indent} `;\n if (typeof value === 'number') {\n const integer = Number.isInteger(value);\n return `new f.NumberField({ required: true, nullable: false${integer ? ', integer: true' : ''}, initial: ${value} })`;\n }\n if (typeof value === 'boolean') {\n return `new f.BooleanField({ required: true, nullable: false, initial: ${value} })`;\n }\n if (typeof value === 'string') {\n const literal = JSON.stringify(value);\n if (RICH_TEXT_KEYS.test(key))\n return `new f.HTMLField({ required: true, blank: true, initial: ${literal} })`;\n return `new f.StringField({ required: true, blank: true, initial: ${literal} })`;\n }\n if (Array.isArray(value)) {\n const first = value[0];\n if (first === undefined || (typeof first === 'object' && first !== null)) {\n if (first === undefined)\n notes.push(\n `${path}: an empty array in the template; it is an ArrayField of ObjectField. Name the element's shape if it has one.`,\n );\n return 'new f.ArrayField(new f.ObjectField())';\n }\n return `new f.ArrayField(${fieldFor(key, first, `${path}[]`, notes, indent)})`;\n }\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) {\n notes.push(\n `${path}: an empty object in the template; it is an ObjectField. Give it a SchemaField if it has a shape.`,\n );\n return 'new f.ObjectField()';\n }\n const inner = entries\n .map(([k, v]) => `${next}${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, next)},`)\n .join('\\n');\n return `new f.SchemaField({\\n${inner}\\n${indent}})`;\n }\n notes.push(`${path}: null in the template; it is an ObjectField. Pick the real field.`);\n return 'new f.ObjectField()';\n}\n\nfunction safeKey(key: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(key) ? key : JSON.stringify(key);\n}\n\nfunction pascal(name: string): string {\n return name\n .replace(/(^|[^A-Za-z0-9])([a-z0-9])/g, (_m, _s, c: string) => c.toUpperCase())\n .replace(/[^A-Za-z0-9]/g, '');\n}\n\nfunction camel(name: string): string {\n const p = pascal(name);\n return p.charAt(0).toLowerCase() + p.slice(1);\n}\n\nfunction schemaBody(data: Record<string, unknown>, path: string, notes: string[]): string {\n return Object.entries(data)\n .filter(([k]) => k !== 'templates')\n .map(([k, v]) => ` ${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, ' ')},`)\n .join('\\n');\n}\n\nfunction header(style: EmitStyle): string {\n if (style === 'sdk') return \"import { BaseTypeDataModel, fields } from '@vttforge/core';\\n\";\n return '';\n}\n\nfunction fieldsLine(style: EmitStyle): string {\n return style === 'sdk' ? ' const f = fields();' : ' const f = foundry.data.fields;';\n}\n\nexport function planDataModels(\n template: Record<string, unknown>,\n {\n style = 'plain',\n lang = 'js',\n dir = 'scripts/data',\n }: { style?: EmitStyle; lang?: 'js' | 'ts'; dir?: string } = {},\n): DataModelPlan {\n const ext = lang === 'ts' ? 'ts' : 'mjs';\n const files: DataModelFile[] = [];\n const notes: string[] = [];\n const documentTypes: DataModelPlan['documentTypes'] = {};\n const registrations: string[] = [];\n\n for (const [document, raw] of Object.entries(template)) {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;\n const doc = raw as DocumentTemplate;\n const types = doc.types ?? [];\n const templates = doc.templates ?? {};\n const docDir = `${dir}/${document.toLowerCase()}`;\n\n // One fragment per template, so the sharing the template expressed is\n // kept, and a type that lists three fragments spreads three functions.\n const fragmentNames = Object.keys(templates);\n if (fragmentNames.length > 0) {\n const fns = fragmentNames\n .map((name) => {\n const body = schemaBody(templates[name] ?? {}, `${document}.templates.${name}`, notes);\n return `/** The \\`${name}\\` template, as the types that listed it spread it. */\\nexport function ${camel(name)}Fields(f) {\\n return {\\n${body}\\n };\\n}`;\n })\n .join('\\n\\n');\n const tsHint =\n lang === 'ts'\n ? '// @ts-nocheck: the field constructors are typed by the runtime, not by this file\\n'\n : '';\n files.push({\n path: `${docDir}/templates.${ext}`,\n 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`,\n });\n }\n\n documentTypes[document] = {};\n const modelNames: string[] = [];\n for (const type of types) {\n const own = (doc[type] ?? {}) as Record<string, unknown>;\n const listed = ((own.templates as string[] | undefined) ?? []).filter((t) => t !== 'base');\n for (const t of listed) {\n if (!(t in templates))\n notes.push(\n `${document}.${type}: lists template \"${t}\", which template.json does not define; it was skipped.`,\n );\n }\n const spreads = listed\n .filter((t) => t in templates)\n .map((t) => ` ...${camel(t)}Fields(f),`)\n .join('\\n');\n const body = schemaBody(own, `${document}.${type}`, notes);\n const className = `${pascal(type)}Data`;\n const importLine = listed.length\n ? `import { ${listed\n .filter((t) => t in templates)\n .map((t) => `${camel(t)}Fields`)\n .join(', ')} } from './templates.${ext === 'ts' ? 'js' : 'mjs'}';\\n`\n : '';\n const schemaFn = `${fieldsLine(style)}\\n return {\\n${[spreads, body].filter(Boolean).join('\\n')}\\n };`;\n const classSource =\n style === 'sdk'\n ? `${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`\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`;\n files.push({ path: `${docDir}/${type}-data.${ext}`, source: classSource });\n const meta: Record<string, unknown> = {};\n const html = (doc.htmlFields ?? []).filter(\n (k) => k in own || listed.some((t) => k in (templates[t] ?? {})),\n );\n if (html.length) meta.htmlFields = html;\n documentTypes[document][type] = meta;\n modelNames.push(`${type}: ${className}`);\n registrations.push(\n `import { ${className} } from './${docDir.replace(/^scripts\\//, '')}/${type}-data.${ext === 'ts' ? 'js' : 'mjs'}';`,\n );\n }\n if (types.length) {\n registrations.push(\n style === 'sdk'\n ? `// registerSystem({ ${document === 'Actor' ? 'actorDataModels' : document === 'Item' ? 'itemDataModels' : `${camel(document)}DataModels`}: { ${modelNames.join(', ')} } })`\n : `// Hooks.once('init', () => Object.assign(CONFIG.${document}.dataModels, { ${modelNames.join(', ')} }));`,\n );\n }\n }\n notes.push(\n \"When every type has a model, delete template.json: while it exists, Foundry resets each listed type's documentTypes entry on every start.\",\n );\n return { files, documentTypes, registration: registrations.join('\\n'), notes };\n}\n","/**\n * The template side of `migrate --sheets`: attribute insertions on opening\n * tags, nothing else. A V2 sheet finds its handlers by `data-action`, and the\n * SDK's tab action by `data-action=\"vttforgeTab\"` plus `data-group` on the\n * links and the panes. Handlebars blocks and expressions are left alone; only\n * literal `class` / `id` / `data-tab` attributes are matched, and a tab id\n * that is an expression is skipped when reading the ids.\n */\n\nexport interface TemplateEdit {\n line: number;\n before: string;\n after: string;\n}\n\nexport interface TemplateResult {\n output: string;\n edits: TemplateEdit[];\n formRoot: boolean;\n}\n\n/**\n * One opening tag: the name, the attribute run, and the self-closing slash.\n * Exactly three capture groups — `editTemplate` reads the replacer's `offset`\n * as the fourth argument, so a fourth group would shift every reported line.\n * A fresh regex per call: a shared global one carries `lastIndex` between\n * `readTabIds`, `elementRange` and `String#replace`.\n */\n// An opening tag: the name, then attributes and Handlebars mustaches (`{{#if x}}disabled{{/if}}`\n// sits inside a tag as an opaque token), then an optional self-closing slash.\nconst tagRe = () =>\n /<([a-zA-Z][\\w-]*)((?:\\s*\\{\\{[^{}]*\\}\\}|\\s+[^\\s=>/{]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+))?|(?<=\\}\\})[^\\s=>/{]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+))?)*)\\s*(\\/?)>/g;\n\n/** The value of one attribute in a tag's attribute run, or null when absent. */\nfunction attr(attrs: string, name: string): string | null {\n const m = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s>]+))`).exec(attrs);\n return m ? (m[1] ?? m[2] ?? m[3] ?? '') : null;\n}\n\nfunction hasClass(attrs: string, cls: string): boolean {\n return (attr(attrs, 'class') ?? '').split(/\\s+/).includes(cls);\n}\n\n/** Only `.class` and `#id` selectors match; anything else stays for `_onRender`. */\nfunction matches(attrs: string, selector: string): boolean {\n const m = /^([.#])([A-Za-z_][\\w-]*)/.exec(selector.trim());\n if (!m) {\n return false;\n }\n const [, kind = '', name = ''] = m;\n if (!name) {\n return false;\n }\n return kind === '.' ? hasClass(attrs, name) : attr(attrs, 'id') === name;\n}\n\nfunction lineOf(text: string, index: number): number {\n let n = 1;\n for (let i = 0; i < index; i += 1) {\n if (text[i] === '\\n') {\n n += 1;\n }\n }\n return n;\n}\n\n/**\n * Index range of the first element a selector opens, through its closing tag.\n * Depth-aware on the tag name, so a nested `<div>` inside the match does not\n * end it early.\n */\nfunction elementRange(template: string, selector: string): [number, number] | null {\n for (const m of template.matchAll(tagRe())) {\n const [whole, name, attrs = ''] = m;\n if (m.index === undefined || !name || !matches(attrs, selector)) {\n continue;\n }\n const open = new RegExp(`<${name}\\\\b`, 'g');\n const close = new RegExp(`</${name}\\\\s*>`, 'g');\n let depth = 1;\n let pos = m.index + whole.length;\n while (depth > 0) {\n open.lastIndex = pos;\n close.lastIndex = pos;\n const o = open.exec(template);\n const c = close.exec(template);\n if (!c) {\n return [m.index, template.length];\n }\n if (o && o.index < c.index) {\n depth += 1;\n pos = o.index + o[0].length;\n } else {\n depth -= 1;\n pos = c.index + c[0].length;\n }\n }\n return [m.index, pos];\n }\n return null;\n}\n\n/**\n * The `data-tab` values under a tabs nav, in document order. A value holding\n * an expression is skipped: its id is only known at render time.\n */\nexport function readTabIds(template: string, navSelector: string): string[] {\n const range = elementRange(template, navSelector);\n if (!range) {\n return [];\n }\n const nav = template.slice(range[0], range[1]);\n const ids: string[] = [];\n for (const m of nav.matchAll(tagRe())) {\n const id = attr(m[2] ?? '', 'data-tab');\n if (id && !id.includes('{{')) {\n ids.push(id);\n }\n }\n return ids;\n}\n\n/**\n * Add the attributes the generated sheet needs, and report each opening tag\n * that changed. Every other byte of the template is left where it was.\n */\nexport function editTemplate(\n template: string,\n opts: { actions: Array<{ name: string; selector: string }>; navSelectors: string[] },\n): TemplateResult {\n const edits: TemplateEdit[] = [];\n const navRanges = opts.navSelectors\n .map((selector) => elementRange(template, selector))\n .filter((range): range is [number, number] => range !== null);\n const inNav = (index: number) => navRanges.some(([start, end]) => index >= start && index < end);\n\n const output = template.replace(\n tagRe(),\n (whole: string, name: string, attrs: string, selfClose: string, offset: number) => {\n const add: string[] = [];\n const hasAction = attr(attrs, 'data-action') !== null;\n if (!hasAction) {\n for (const action of opts.actions) {\n if (matches(attrs, action.selector)) {\n add.push(`data-action=\"${action.name}\"`);\n break;\n }\n }\n }\n const tab = attr(attrs, 'data-tab');\n const needsGroup = attr(attrs, 'data-group') === null;\n let withClass = attrs;\n const isNavLink = tab !== null && inNav(offset);\n const isPane = tab !== null && !isNavLink && hasClass(attrs, 'tab');\n if (isNavLink) {\n if (!hasAction && !add.some((one) => one.startsWith('data-action='))) {\n add.push('data-action=\"vttforgeTab\"');\n }\n if (needsGroup) {\n add.push('data-group=\"primary\"');\n }\n } else if (isPane && needsGroup) {\n add.push('data-group=\"primary\"');\n }\n // The active tab comes from the context: `{{tabs.<id>.cssClass}}` on the link and the pane.\n if (\n (isNavLink || isPane) &&\n tab !== null &&\n !tab.includes('{{') &&\n !/\\{\\{\\s*tabs\\./.test(attrs)\n ) {\n const marker = `{{tabs.${tab}.cssClass}}`;\n withClass = /\\sclass\\s*=\\s*\"([^\"]*)\"/.test(attrs)\n ? attrs.replace(\n /(\\sclass\\s*=\\s*\")([^\"]*)(\")/,\n (_m, open, value, close) => `${open}${value.trimEnd()} ${marker}${close}`,\n )\n : attrs;\n if (withClass === attrs) add.push(`class=\"${marker}\"`);\n }\n if (add.length === 0 && withClass === attrs) {\n return whole;\n }\n const after = `<${name}${withClass.replace(/\\s+$/, '')}${add.length > 0 ? ` ${add.join(' ')}` : ''}${selfClose ? ' /' : ''}>`;\n edits.push({ line: lineOf(template, offset), before: whole, after });\n return after;\n },\n );\n\n return { output, edits, formRoot: /^\\s*<form\\b/.test(template) };\n}\n","/**\n * The parse side of `migrate --sheets`: an AST for the class structure, and\n * the few lookups the planner needs. Bodies are never re-printed from the\n * tree; the planner slices the original text by node range.\n */\nimport { parse } from '@babel/parser';\nimport type { ClassDeclaration, ClassExpression, ClassMethod, File, Node } from '@babel/types';\n\ntype SheetBase = 'ActorSheet' | 'ItemSheet';\n\nexport interface SheetClass {\n name: string;\n base: SheetBase;\n node: ClassDeclaration | ClassExpression;\n /** The `extends` expression as written. */\n superText: string;\n}\n\nconst CONVERTED = new Set<string>(['ActorSheet', 'ItemSheet']);\nconst UNSUPPORTED = new Set(['Application', 'FormApplication', 'Dialog', 'DocumentSheet']);\n\nexport function parseSource(source: string, lang: 'js' | 'ts'): File {\n return parse(source, {\n sourceType: 'module',\n errorRecovery: true,\n attachComment: false,\n plugins: lang === 'ts' ? ['typescript', 'decorators'] : ['decorators'],\n });\n}\n\nexport function text(source: string, node: Node): string {\n return source.slice(node.start ?? 0, node.end ?? 0);\n}\n\n/** Depth-first over every child node. Return `false` from `visit` to skip a subtree. */\nexport function walk(node: Node | null | undefined, visit: (n: Node) => undefined | false): void {\n if (!node || typeof node.type !== 'string') return;\n if (visit(node) === false) return;\n for (const key of Object.keys(node)) {\n if (key === 'loc' || key === 'leadingComments' || key === 'trailingComments') continue;\n const value = (node as unknown as Record<string, unknown>)[key];\n if (Array.isArray(value)) {\n for (const v of value) walk(v as Node, visit);\n } else if (value && typeof value === 'object' && 'type' in value) {\n walk(value as Node, visit);\n }\n }\n}\n\n/** `foundry.appv1.sheets.ActorSheet` → the leaf name, or the identifier itself. */\nfunction superName(cls: ClassDeclaration | ClassExpression): string | null {\n const s = cls.superClass;\n if (!s) return null;\n if (s.type === 'Identifier') return s.name;\n if (s.type === 'MemberExpression' && s.property.type === 'Identifier') return s.property.name;\n return null;\n}\n\ninterface NamedClass {\n name: string;\n node: ClassDeclaration | ClassExpression;\n}\n\nfunction classesOf(ast: File): NamedClass[] {\n const out: NamedClass[] = [];\n walk(ast.program, (n) => {\n if (n.type === 'ClassDeclaration') {\n out.push({ name: n.id?.name ?? '', node: n });\n return false;\n }\n if (n.type === 'ExportDefaultDeclaration' && n.declaration.type === 'ClassDeclaration') {\n const base = superName(n.declaration) ?? 'Sheet';\n out.push({ name: n.declaration.id?.name ?? `Default${base}`, node: n.declaration });\n return false;\n }\n if (\n n.type === 'VariableDeclarator' &&\n n.init?.type === 'ClassExpression' &&\n n.id.type === 'Identifier'\n ) {\n out.push({ name: n.id.name, node: n.init });\n return false;\n }\n return undefined;\n });\n return out;\n}\n\nexport function findSheetClasses(ast: File, source: string): SheetClass[] {\n const found: SheetClass[] = [];\n for (const { name, node } of classesOf(ast)) {\n const base = superName(node);\n if (!base || !CONVERTED.has(base) || !node.superClass) continue;\n found.push({ name, base: base as SheetBase, node, superText: text(source, node.superClass) });\n }\n return found;\n}\n\nexport function unsupportedBases(\n ast: File,\n source: string,\n): Array<{ name: string; superText: string; line: number }> {\n const out: Array<{ name: string; superText: string; line: number }> = [];\n for (const { name, node } of classesOf(ast)) {\n const base = superName(node);\n if (!base || !UNSUPPORTED.has(base) || !node.superClass) continue;\n out.push({ name, superText: text(source, node.superClass), line: node.loc?.start.line ?? 0 });\n }\n return out;\n}\n\nexport function methodOf(\n cls: ClassDeclaration | ClassExpression,\n name: string,\n opts: { static?: boolean; kind?: 'get' | 'method' } = {},\n): ClassMethod | null {\n for (const member of cls.body.body) {\n if (member.type !== 'ClassMethod') continue;\n if (member.key.type !== 'Identifier' || member.key.name !== name) continue;\n if (opts.static !== undefined && Boolean(member.static) !== opts.static) continue;\n if (opts.kind !== undefined && member.kind !== opts.kind) continue;\n return member;\n }\n return null;\n}\n","/**\n * Text rewrites applied to method bodies carried over from an Application v1\n * sheet. Each one is scoped to the slice the planner hands it, so a pattern\n * here never sees the rest of the file.\n *\n * Nothing is re-printed from a syntax tree: the bodies keep the author's\n * spacing and comments, and every rewrite is a replacement the reader can\n * find in the diff. What cannot be decided mechanically becomes a\n * `// TODO(migrate)` line above the code that needs the decision, and the\n * same message comes back in `todos` so the report can list it.\n */\n\nimport { MASK, maskComments } from '../audit/mask.js';\n\nexport interface Rewritten {\n code: string;\n /** One message per `// TODO(migrate)` line placed in `code`. */\n todos: string[];\n}\n\nexport const TODO = (msg: string): string => `// TODO(migrate): ${msg}`;\n\nconst esc = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nconst camel = (s: string) => s.replace(/-+(\\w)/g, (_m, c: string) => c.toUpperCase());\n\n/** Replace outside comments and strings; the mask keeps them out of reach. */\nfunction replaceCode(\n code: string,\n pattern: RegExp,\n replacement: (match: string, ...groups: string[]) => string,\n): string {\n const masked = maskComments(code, { strings: true });\n return code.replace(pattern, (match: string, ...rest: unknown[]) => {\n const offset = rest.find((r): r is number => typeof r === 'number') ?? 0;\n if (masked[offset] === MASK) return match;\n return replacement(match, ...rest.filter((r): r is string => typeof r === 'string'));\n });\n}\n\n/** Put a TODO line above the line that holds `index`. */\nfunction todoAt(code: string, index: number, msg: string): string {\n const lineStart = code.lastIndexOf('\\n', index - 1) + 1;\n const indent = /^[ \\t]*/.exec(code.slice(lineStart))?.[0] ?? '';\n return `${code.slice(0, lineStart)}${indent}${TODO(msg)}\\n${code.slice(lineStart)}`;\n}\n\n/** The jQuery calls with no one-to-one DOM rewrite. */\nconst LEFTOVER_JQUERY =\n /\\$\\(|\\.(?:val|text|html|prop|toggle|slideToggle|slideUp|slideDown|show|hide|addClass|removeClass|toggleClass|siblings|children|find|css)\\(/g;\n\nconst JQUERY_MSG = 'jQuery left here; use the DOM on `target` / `this.element`';\n\n/**\n * A handler body from `activateListeners`, with `event.currentTarget` folded\n * into the `target` the action receives and the jQuery data readers turned\n * into `dataset`.\n */\nexport function rewriteHandlerBody(\n body: string,\n eventParam: string | null,\n htmlParam: string | null,\n targetName = 'target',\n): Rewritten {\n const todos: string[] = [];\n let code = body;\n if (eventParam) {\n const ev = esc(eventParam);\n code = replaceCode(\n code,\n new RegExp(`\\\\$\\\\(\\\\s*${ev}\\\\.currentTarget\\\\s*\\\\)`, 'g'),\n () => targetName,\n );\n if (targetName !== `${eventParam}.currentTarget`) {\n code = replaceCode(code, new RegExp(`\\\\b${ev}\\\\.currentTarget\\\\b`, 'g'), () => targetName);\n }\n }\n code = replaceCode(\n code,\n /\\.data\\(\\s*(['\"])([\\w-]+)\\1\\s*\\)/g,\n (_m, _q, key) => `.dataset.${camel(key)}`,\n );\n code = replaceCode(\n code,\n /\\.attr\\(\\s*(['\"])data-([\\w-]+)\\1\\s*\\)/g,\n (_m, _q, key) => `.dataset.${camel(key)}`,\n );\n // jQuery's `parents(sel)` is read for its nearest match everywhere a sheet uses it.\n code = replaceCode(code, /\\.parents\\(/g, () => '.closest(');\n if (htmlParam) {\n code = replaceCode(\n code,\n new RegExp(`\\\\b${esc(htmlParam)}\\\\.find\\\\(`, 'g'),\n () => 'this.element.querySelectorAll(',\n );\n }\n // `this.element` was jQuery on v1 and is an HTMLElement on V2.\n // A jQuery collection reads as a NodeList: `.length`, `[0]` and `forEach` keep working.\n code = replaceCode(code, /this\\.element\\.find\\(/g, () => 'this.element.querySelectorAll(');\n // What is left of jQuery gets a marker, once per line however much it holds.\n const masked = maskComments(code, { strings: true });\n const lines = new Set<number>();\n for (const m of code.matchAll(LEFTOVER_JQUERY)) {\n const at = m.index ?? 0;\n if (masked[at] === MASK) continue;\n lines.add(code.lastIndexOf('\\n', at - 1) + 1);\n }\n for (const lineStart of [...lines].sort((a, b) => b - a)) {\n code = todoAt(code, lineStart, JQUERY_MSG);\n todos.unshift(JQUERY_MSG);\n }\n return { code, todos };\n}\n\n/**\n * `getData()` becomes `_prepareContext(options)`. V2 hands back a much\n * smaller context, so the keys a v1 body expects to already be there are\n * assigned right after the `super` call — unless the method assigns them\n * itself without reading the old value first.\n */\nexport function rewriteGetData(methodText: string, base: 'ActorSheet' | 'ItemSheet'): Rewritten {\n const todos: string[] = [];\n const sig = /^(\\s*)(async\\s+)?getData\\s*\\(([^)]*)\\)/.exec(methodText);\n const params = sig?.[3]?.trim() ?? '';\n let code = methodText.replace(\n /^(\\s*)(async\\s+)?getData\\s*\\(([^)]*)\\)/,\n (_m, indent: string) => `${indent}async _prepareContext(options)`,\n );\n code = replaceCode(code, /super\\.getData\\(\\s*[^)]*\\)/g, () => 'super._prepareContext(options)');\n\n // The variable that received super's result.\n const varMatch =\n /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:await\\s+)?super\\._prepareContext\\(options\\)\\s*;/.exec(code);\n const v = varMatch?.[1] ?? 'context';\n const own = base === 'ActorSheet' ? 'actor' : 'item';\n // What v1's getData handed the template and V2's _prepareContext does not:\n // the document under its own name and as `data`, its system, the items,\n // and the two flags every v1 template gates on.\n const wanted: Array<[string, string]> = [\n [own, `${v}.${own} = this.document;`],\n ['data', `${v}.data = this.document;`],\n ['system', `${v}.system = this.document.system;`],\n ];\n if (base === 'ActorSheet') wanted.push(['items', `${v}.items = [...this.document.items];`]);\n wanted.push(\n ['editable', `${v}.editable = this.isEditable;`],\n ['owner', `${v}.owner = this.document.isOwner;`],\n );\n\n const masked = maskComments(code, { strings: true });\n const inject = wanted\n .filter(([key]) => {\n const assigned = new RegExp(`\\\\b${esc(v)}\\\\.${key}\\\\s*=(?!=)`).test(masked);\n const read = new RegExp(`\\\\b${esc(v)}\\\\.${key}\\\\b(?!\\\\s*=(?!=))`).test(masked);\n return !assigned || read;\n })\n .map(([, line]) => line);\n\n if (varMatch) {\n const at = varMatch.index + varMatch[0].length;\n const indent =\n /^[ \\t]*/.exec(code.slice(code.lastIndexOf('\\n', varMatch.index) + 1))?.[0] ?? ' ';\n code = `${code.slice(0, at)}${inject.map((l) => `\\n${indent}${l}`).join('')}${code.slice(at)}`;\n } else if (inject.length > 0) {\n const msg = `set ${inject.join(' ')} on the context before returning it`;\n code = todoAt(code, code.indexOf('{') + 1, msg);\n todos.push(msg);\n }\n\n if (params !== '' && params !== 'options') {\n const msg = `\\`getData(${params})\\` took its own parameters; \\`_prepareContext(options)\\` does not. Read what the body needs from \\`options\\` or \\`this.document\\``;\n code = todoAt(code, code.indexOf('{') + 1, msg);\n todos.push(msg);\n }\n return { code, todos };\n}\n\n/**\n * `_onDropItem(event, data)` becomes `onDropItem(item, event)`: the SDK base\n * resolves the dropped document before it calls the hook, so the raw drop\n * payload the v1 body read is gone.\n */\nexport function rewriteDropMethod(methodText: string, which: 'Item' | 'Actor'): Rewritten {\n const lower = which.toLowerCase();\n const sig = new RegExp(`_onDrop${which}\\\\s*\\\\(\\\\s*(\\\\w+)\\\\s*,\\\\s*(\\\\w+)\\\\s*\\\\)`);\n const m = sig.exec(methodText);\n if (!m) return { code: methodText, todos: [] };\n const eventName = m[1] ?? 'event';\n const dataName = m[2] ?? 'data';\n // The body may already declare `item` / `actor`; the parameter then takes another name.\n const declares = new RegExp(\n `\\\\b(?:const|let|var)\\\\s+(?:${lower}\\\\b|\\\\{[^}]*\\\\b${lower}\\\\b[^}]*\\\\}|\\\\[[^\\\\]]*\\\\b${lower}\\\\b[^\\\\]]*\\\\])`,\n ).test(methodText);\n const param = declares ? `dropped${which}` : lower;\n let code = methodText.replace(sig, `onDrop${which}(${param}, ${eventName})`);\n const todos: string[] = [];\n if (which === 'Item') {\n // v1's super created the item on the actor and returned the created documents.\n code = replaceCode(\n code,\n /super\\._onDropItem\\([^)]*\\)/g,\n () => `this.document.createEmbeddedDocuments('Item', [${param}.toObject()])`,\n );\n } else {\n code = replaceCode(\n code,\n new RegExp(`super\\\\._onDrop${which}\\\\([^)]*\\\\)`, 'g'),\n () => `super.onDrop${which}(${param}, ${eventName})`,\n );\n }\n // The v1 body read the drag payload; the resolved document reproduces it.\n code = replaceCode(\n code,\n new RegExp(`\\\\b${esc(dataName)}\\\\b`, 'g'),\n () => `${param}.toDragData()`,\n );\n const msg =\n which === 'Item'\n ? `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`\n : `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`;\n code = todoAt(code, code.indexOf('{') + 1, msg);\n todos.push(msg);\n return { code, todos };\n}\n\n/** `Dialog.confirm({ ... })`: the options literal is group 1. Non-greedy, so a nested `}` ends it early; `balanced` catches that. */\nconst CONFIRM_CALL = /\\bDialog\\.confirm\\(\\s*\\{([\\s\\S]*?)\\}\\s*\\)/g;\nconst NEW_DIALOG = /\\bnew\\s+Dialog\\s*\\(/g;\nconst UNREADABLE_MSG =\n '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';\nconst NEW_DIALOG_MSG =\n 'Dialog v1 (removed in v16); rebuild with DialogV2.prompt / DialogV2.wait, buttons as { action, label, callback }';\n\n/** Whether every bracket opened in `text` (outside strings and comments) is closed. */\nfunction balanced(text: string): boolean {\n const masked = maskComments(text, { strings: true });\n const pairs = new Map<string, string>([\n [')', '('],\n [']', '['],\n ['}', '{'],\n ]);\n const stack: string[] = [];\n for (let i = 0; i < masked.length; i += 1) {\n const ch = masked[i];\n if (ch === undefined || ch === MASK) continue;\n if (ch === '(' || ch === '[' || ch === '{') stack.push(ch);\n else if (pairs.has(ch)) {\n if (stack.pop() !== pairs.get(ch)) return false;\n }\n }\n return stack.length === 0;\n}\n\n/** The top-level `key: value` pairs of an object literal's inner text. */\nfunction topLevelPairs(inner: string): Array<{ key: string; value: string; spread: boolean }> {\n const masked = maskComments(inner, { strings: true });\n const pairs: Array<{ key: string; value: string; spread: boolean }> = [];\n let depth = 0;\n let start = 0;\n const flush = (end: number) => {\n const raw = inner.slice(start, end).trim();\n if (!raw) return;\n if (raw.startsWith('...')) {\n pairs.push({ key: raw, value: '', spread: true });\n return;\n }\n const colon = raw.indexOf(':');\n if (colon === -1) {\n pairs.push({ key: raw, value: raw, spread: false });\n return;\n }\n pairs.push({\n key: raw.slice(0, colon).trim(),\n value: raw.slice(colon + 1).trim(),\n spread: false,\n });\n };\n for (let i = 0; i < masked.length; i += 1) {\n const ch = masked[i];\n if (ch === MASK) continue;\n if (ch === '(' || ch === '[' || ch === '{') depth += 1;\n else if (ch === ')' || ch === ']' || ch === '}') depth -= 1;\n else if (ch === ',' && depth === 0) {\n flush(i);\n start = i + 1;\n }\n }\n flush(inner.length);\n return pairs;\n}\n\n/**\n * The DialogV2.confirm call for a Dialog.confirm options literal, or `null`\n * when the literal could not be read. `missing` names what the rewrite left\n * behind (a spread, an option with no V2 slot). `defaultYes` is dropped on\n * purpose: DialogV2 has no equivalent.\n */\nfunction readConfirmOptions(inner: string): { code: string | null; missing: string[] } {\n if (!balanced(inner)) return { code: null, missing: [] };\n const missing: string[] = [];\n const found: Record<string, string> = {};\n for (const pair of topLevelPairs(inner)) {\n if (pair.spread) {\n missing.push(`the spread ${pair.key}`);\n continue;\n }\n const key = pair.key.replace(/^['\"]|['\"]$/g, '');\n if (key === 'title' || key === 'content' || key === 'yes' || key === 'no')\n found[key] = pair.value;\n else if (key !== 'defaultYes' && key !== 'rejectClose' && key !== 'options') missing.push(key);\n }\n const parts = [\n found.title ? `window: { title: ${found.title} }` : '',\n found.content ? `content: ${found.content}` : '',\n found.yes ? `yes: { callback: ${found.yes} }` : '',\n found.no ? `no: { callback: ${found.no} }` : '',\n ].filter(Boolean);\n return { code: `DialogV2.confirm({ ${parts.join(', ')} })`, missing };\n}\n\nexport function rewriteDialogs(code: string): Rewritten {\n const todos: string[] = [];\n const confirmMask = maskComments(code, { strings: true });\n const hits: Array<{ start: number; end: number; code: string | null; missing: string[] }> = [];\n for (const m of code.matchAll(CONFIRM_CALL)) {\n const start = m.index ?? 0;\n if (confirmMask[start] === MASK) continue;\n const read = readConfirmOptions(m[1] ?? '');\n hits.push({ start, end: start + m[0].length, code: read.code, missing: read.missing });\n }\n\n let out = code;\n for (const hit of hits.reverse()) {\n if (hit.code !== null) out = `${out.slice(0, hit.start)}${hit.code}${out.slice(hit.end)}`;\n if (hit.code === null) {\n out = todoAt(out, hit.start, UNREADABLE_MSG);\n todos.unshift(UNREADABLE_MSG);\n } else if (hit.missing.length > 0) {\n const msg = `Dialog.confirm options left behind: ${hit.missing.join(', ')}; move them onto the DialogV2.confirm call by hand`;\n out = todoAt(out, hit.start, msg);\n todos.unshift(msg);\n }\n }\n\n const dialogMask = maskComments(out, { strings: true });\n const starts: number[] = [];\n for (const m of out.matchAll(NEW_DIALOG)) {\n const at = m.index ?? 0;\n if (dialogMask[at] !== MASK) starts.push(at);\n }\n for (const at of starts.reverse()) {\n out = todoAt(out, at, NEW_DIALOG_MSG);\n todos.push(NEW_DIALOG_MSG);\n }\n return { code: out, todos };\n}\n","/**\n * `activateListeners(html)` → `actions` and `_onRender` listeners.\n *\n * A click bound through `html.find(SEL).click(H)` (or `.on('click', H)`)\n * becomes an action named after the selector's first class or id. A bound\n * method stays a method; an arrow that only forwards to a method is that\n * method; any other function becomes a new method. Other events keep a real\n * listener, added in `_onRender`. What does not fit either shape is listed.\n */\nimport type { Expression, Node, Statement } from '@babel/types';\nimport { methodOf, type SheetClass, text } from './parse.js';\n\nexport interface ActionBinding {\n name: string;\n selector: string;\n kind: 'method' | 'inline';\n method: string | null;\n param: string | null;\n body: string | null;\n isAsync: boolean;\n}\n\ninterface ListenerBinding {\n selector: string;\n event: string;\n handlerText: string;\n}\n\nexport interface Listeners {\n actions: ActionBinding[];\n listeners: ListenerBinding[];\n leftovers: Array<{ line: number; text: string }>;\n /** The name `activateListeners` gave its jQuery root (`html` by convention). */\n htmlParam: string;\n}\n\nconst EVENTS = new Set([\n 'click',\n 'dblclick',\n 'change',\n 'contextmenu',\n 'input',\n 'keydown',\n 'keyup',\n 'focus',\n 'blur',\n 'mouseenter',\n 'mouseleave',\n 'submit',\n]);\n\nconst FIRST_CLASS_OR_ID = /[.#]([A-Za-z_][\\w-]*)/;\nconst SEPARATOR = /[-_]+(\\w)/g;\n\nexport function actionName(selector: string, taken: Set<string>): string | null {\n const match = FIRST_CLASS_OR_ID.exec(selector);\n const captured = match?.[1];\n if (!captured) return null;\n const base = captured\n .replace(SEPARATOR, (_, c: string) => c.toUpperCase())\n .replace(/^[A-Z]/, (c) => c.toLowerCase());\n let name = base;\n let i = 2;\n while (taken.has(name)) {\n name = `${base}${i}`;\n i += 1;\n }\n taken.add(name);\n return name;\n}\n\n/** `html.find(SEL)` with `html` being the listener's parameter → the selector. */\nfunction findSelector(callee: Expression, htmlParam: string): string | null {\n if (callee.type !== 'CallExpression') return null;\n const c = callee.callee;\n if (\n c.type !== 'MemberExpression' ||\n c.object.type !== 'Identifier' ||\n c.object.name !== htmlParam\n ) {\n return null;\n }\n if (c.property.type !== 'Identifier' || c.property.name !== 'find') return null;\n const [arg] = callee.arguments;\n return arg && arg.type === 'StringLiteral' ? arg.value : null;\n}\n\n/** `this._onX.bind(this)` → `_onX`; `(ev) => this._onX(ev)` → `_onX`. */\nfunction forwardedMethod(handler: Node): string | null {\n if (\n handler.type === 'CallExpression' &&\n handler.callee.type === 'MemberExpression' &&\n handler.callee.property.type === 'Identifier' &&\n handler.callee.property.name === 'bind' &&\n handler.callee.object.type === 'MemberExpression' &&\n handler.callee.object.object.type === 'ThisExpression' &&\n handler.callee.object.property.type === 'Identifier'\n ) {\n return handler.callee.object.property.name;\n }\n if (handler.type === 'ArrowFunctionExpression') {\n let call: Expression | null = null;\n if (handler.body.type === 'CallExpression') call = handler.body;\n else if (handler.body.type === 'BlockStatement' && handler.body.body.length === 1) {\n const only = handler.body.body[0];\n if (only?.type === 'ExpressionStatement' && only.expression.type === 'CallExpression') {\n call = only.expression;\n }\n if (only?.type === 'ReturnStatement' && only.argument?.type === 'CallExpression') {\n call = only.argument;\n }\n }\n if (\n call &&\n call.callee.type === 'MemberExpression' &&\n call.callee.object.type === 'ThisExpression' &&\n call.callee.property.type === 'Identifier' &&\n call.arguments.length <= 1\n ) {\n const [a] = call.arguments;\n const p = handler.params[0];\n if (!a || (a.type === 'Identifier' && p?.type === 'Identifier' && a.name === p.name)) {\n return call.callee.property.name;\n }\n }\n }\n return null;\n}\n\ninterface Bound {\n selector: string;\n event: string;\n handler: Node;\n}\n\n/**\n * `html.find(SEL).<event>(H)` or `html.find(SEL).on('<event>', H)` → the parts,\n * or `null` when the statement is not a jQuery binding this can translate.\n */\nfunction boundEvent(expr: Expression, htmlParam: string): Bound | null {\n if (expr.type !== 'CallExpression') return null;\n if (expr.callee.type !== 'MemberExpression' || expr.callee.property.type !== 'Identifier') {\n return null;\n }\n const receiver = expr.callee.object;\n if (receiver.type === 'Super') return null;\n const selector = findSelector(receiver, htmlParam);\n if (selector === null) return null;\n\n const calleeName = expr.callee.property.name;\n if (EVENTS.has(calleeName)) {\n const handler = expr.arguments[0];\n return handler ? { selector, event: calleeName, handler } : null;\n }\n if (calleeName === 'on' && expr.arguments.length === 2) {\n const first = expr.arguments[0];\n const handler = expr.arguments[1];\n if (first?.type === 'StringLiteral' && handler) {\n return { selector, event: first.value, handler };\n }\n }\n return null;\n}\n\nexport function extractListeners(cls: SheetClass, source: string): Listeners {\n const out: Listeners = { actions: [], listeners: [], leftovers: [], htmlParam: 'html' };\n const method = methodOf(cls.node, 'activateListeners');\n if (!method) return out;\n const p = method.params[0];\n const htmlParam = p?.type === 'Identifier' ? p.name : 'html';\n out.htmlParam = htmlParam;\n const taken = new Set<string>();\n\n const leftover = (stmt: Statement): void => {\n out.leftovers.push({ line: stmt.loc?.start.line ?? 0, text: text(source, stmt) });\n };\n\n const consider = (stmt: Statement): void => {\n if (stmt.type !== 'ExpressionStatement') return;\n const e = stmt.expression;\n if (e.type === 'AwaitExpression') return;\n // Anything that is not a method call, and super.activateListeners(html): dropped.\n if (e.type !== 'CallExpression') return;\n if (e.callee.type !== 'MemberExpression' || e.callee.property.type !== 'Identifier') return;\n if (e.callee.object.type === 'Super') return;\n\n const bound = boundEvent(e, htmlParam);\n if (!bound) {\n leftover(stmt);\n return;\n }\n const { selector, event, handler } = bound;\n\n if (event !== 'click') {\n out.listeners.push({ selector, event, handlerText: text(source, handler) });\n return;\n }\n\n const name = actionName(selector, taken);\n if (name === null) {\n leftover(stmt);\n return;\n }\n const forwarded = forwardedMethod(handler);\n if (forwarded) {\n out.actions.push({\n name,\n selector,\n kind: 'method',\n method: forwarded,\n param: null,\n body: null,\n isAsync: false,\n });\n return;\n }\n if (handler.type === 'ArrowFunctionExpression' || handler.type === 'FunctionExpression') {\n const p0 = handler.params[0];\n out.actions.push({\n name,\n selector,\n kind: 'inline',\n method: null,\n param: p0?.type === 'Identifier' ? p0.name : null,\n body: text(source, handler.body),\n isAsync: Boolean(handler.async),\n });\n return;\n }\n leftover(stmt);\n };\n\n /** A guard such as `if (!this.options.editable) return;`: V2 sheets gate through isEditable. */\n const isGuard = (stmt: Statement): boolean => {\n if (stmt.type !== 'IfStatement' || stmt.alternate) return false;\n const c = stmt.consequent;\n if (c.type === 'ReturnStatement') return true;\n return (\n c.type === 'BlockStatement' && c.body.length === 1 && c.body[0]?.type === 'ReturnStatement'\n );\n };\n\n const visit = (stmts: Statement[]): void => {\n for (const stmt of stmts) {\n if (isGuard(stmt)) continue;\n if (stmt.type === 'IfStatement') {\n // Bindings under a condition are still bindings; the condition itself is lost, so say so.\n const branches = [stmt.consequent, stmt.alternate].filter((b): b is Statement =>\n Boolean(b),\n );\n for (const b of branches) visit(b.type === 'BlockStatement' ? b.body : [b]);\n out.leftovers.push({\n line: stmt.loc?.start.line ?? 0,\n text: `if (${text(source, stmt.test)}) guarded the bindings above it; V2 actions run regardless, gate inside the handler`,\n });\n continue;\n }\n if (stmt.type === 'BlockStatement') {\n visit(stmt.body);\n continue;\n }\n consider(stmt);\n }\n };\n visit(method.body.body);\n return out;\n}\n","/**\n * `static get defaultOptions()` → the V2 statics.\n *\n * Reads the object literal handed to `mergeObject(super.defaultOptions, {...})`\n * (or returned directly) and maps the keys the v1 sheets used: `classes`,\n * `template`, `width`/`height`, `resizable`, `submitOnChange`, `tabs`,\n * `dragDrop`. Anything else is listed so the reader decides.\n */\nimport type { ClassMethod, Expression, ObjectExpression, ObjectProperty } from '@babel/types';\nimport { methodOf, type SheetClass, text, walk } from './parse.js';\n\nexport interface SheetOptions {\n classes: string | null;\n width: number | null;\n height: number | null;\n resizable: boolean | null;\n submitOnChange: boolean | null;\n template: string | null;\n templateGetter: ClassMethod | null;\n tabs: Array<{ navSelector: string; contentSelector: string | null; initial: string | null }>;\n dragDrop: string | null;\n unknown: string[];\n}\n\nfunction keyName(p: ObjectProperty): string | null {\n if (p.key.type === 'Identifier') return p.key.name;\n if (p.key.type === 'StringLiteral') return p.key.value;\n return null;\n}\n\nconst NOT_A_VALUE = new Set(['ArrayPattern', 'ObjectPattern', 'AssignmentPattern', 'RestElement']);\n\nfunction props(obj: ObjectExpression): Array<[string, Expression]> {\n const out: Array<[string, Expression]> = [];\n for (const p of obj.properties) {\n if (p.type !== 'ObjectProperty') continue;\n const k = keyName(p);\n if (k && !NOT_A_VALUE.has(p.value.type)) out.push([k, p.value as Expression]);\n }\n return out;\n}\n\nfunction str(e: Expression): string | null {\n return e.type === 'StringLiteral' ? e.value : null;\n}\nfunction num(e: Expression): number | null {\n return e.type === 'NumericLiteral' ? e.value : null;\n}\nfunction bool(e: Expression): boolean | null {\n return e.type === 'BooleanLiteral' ? e.value : null;\n}\n\n/** The options literal: the last object argument of the returned call, or the returned object. */\nfunction optionsLiteral(method: ClassMethod): ObjectExpression | null {\n let found: ObjectExpression | null = null;\n walk(method.body, (n) => {\n if (found) return false;\n if (n.type !== 'ReturnStatement' || !n.argument) return undefined;\n const arg = n.argument;\n if (arg.type === 'ObjectExpression') {\n found = arg;\n } else if (arg.type === 'CallExpression') {\n const last = [...arg.arguments].reverse().find((a) => a.type === 'ObjectExpression');\n if (last?.type === 'ObjectExpression') found = last;\n }\n return false;\n });\n return found;\n}\n\nexport function extractOptions(cls: SheetClass, source: string): SheetOptions {\n const out: SheetOptions = {\n classes: null,\n width: null,\n height: null,\n resizable: null,\n submitOnChange: null,\n template: null,\n templateGetter: methodOf(cls.node, 'template', { kind: 'get', static: false }),\n tabs: [],\n dragDrop: null,\n unknown: [],\n };\n const method = methodOf(cls.node, 'defaultOptions', { static: true, kind: 'get' });\n const literal = method ? optionsLiteral(method) : null;\n if (!literal) return out;\n for (const [key, value] of props(literal)) {\n switch (key) {\n case 'classes':\n out.classes = text(source, value);\n break;\n case 'width':\n out.width = num(value);\n break;\n case 'height':\n out.height = num(value);\n break;\n case 'resizable':\n out.resizable = bool(value);\n break;\n case 'submitOnChange':\n out.submitOnChange = bool(value);\n break;\n case 'template':\n out.template = str(value);\n break;\n case 'dragDrop':\n out.dragDrop = text(source, value);\n break;\n case 'tabs':\n out.tabs.push(...readTabs(value));\n break;\n default:\n out.unknown.push(key);\n }\n }\n return out;\n}\n\nfunction readTabs(value: Expression): SheetOptions['tabs'] {\n if (value.type !== 'ArrayExpression') return [];\n const tabs: SheetOptions['tabs'] = [];\n for (const el of value.elements) {\n if (el?.type !== 'ObjectExpression') continue;\n const t = Object.fromEntries(props(el));\n const nav = t.navSelector ? str(t.navSelector) : null;\n if (!nav) continue;\n tabs.push({\n navSelector: nav,\n contentSelector: t.contentSelector ? str(t.contentSelector) : null,\n initial: t.initial ? str(t.initial) : null,\n });\n }\n return tabs;\n}\n\nconst q = (s: string) => `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n\nexport function renderStatics(\n opts: SheetOptions,\n tabIds: Record<string, string[]>,\n todo: (msg: string) => string,\n): string {\n const lines: string[] = [];\n lines.push(' /** @override */');\n lines.push(' static DEFAULT_OPTIONS = foundry.utils.mergeObject(');\n lines.push(' super.DEFAULT_OPTIONS,');\n lines.push(' {');\n if (opts.classes) lines.push(` classes: ${opts.classes},`);\n if (opts.width !== null || opts.height !== null) {\n const parts = [\n opts.width !== null ? `width: ${opts.width}` : '',\n opts.height !== null ? `height: ${opts.height}` : '',\n ].filter(Boolean);\n lines.push(` position: { ${parts.join(', ')} },`);\n }\n if (opts.resizable !== null) lines.push(` window: { resizable: ${opts.resizable} },`);\n lines.push(` form: { submitOnChange: ${opts.submitOnChange ?? true} },`);\n lines.push(' actions: {}, // filled below');\n lines.push(' },');\n lines.push(' { inplace: false },');\n lines.push(' );');\n for (const key of opts.unknown) {\n lines.push(\n ` ${todo(`${key} from defaultOptions has no V2 equivalent here; move it by hand or drop it`)}`,\n );\n }\n\n if (opts.tabs.length > 0) {\n lines.push('', ' /** @override */', ' static TABS = {');\n for (const [i, tab] of opts.tabs.entries()) {\n const group = i === 0 ? 'primary' : `group${i + 1}`;\n const ids = tabIds[tab.navSelector] ?? [];\n const initial = tab.initial ?? ids[0] ?? '';\n if (ids.length === 0) {\n lines.push(\n ` ${todo(`tab ids for ${tab.navSelector} were not found in the template; list them here`)}`,\n );\n }\n lines.push(\n ` ${group}: { tabs: [${ids.map((id) => `{ id: ${q(id)} }`).join(', ')}], initial: ${q(initial)} },`,\n );\n }\n lines.push(' };');\n }\n if (opts.dragDrop) {\n lines.push('', ' /** @override */', ` static DRAG_DROP = ${opts.dragDrop};`);\n }\n lines.push('', ' /** @override */', ' static PARTS = {');\n if (opts.template) {\n lines.push(` sheet: { template: ${q(opts.template)} },`);\n } else {\n lines.push(\n ` ${todo('the template is chosen at runtime (get template); name one part per type here or override _configureRenderParts')}`,\n ` sheet: { template: '' },`,\n );\n }\n lines.push(' };');\n return lines.join('\\n');\n}\n","/**\n * One v1 sheet class → one file on the SDK base.\n *\n * Structure comes from the AST (which members exist, where each one starts\n * and ends); every body is the original text with the scoped rewrites from\n * `sheet-bodies.ts`. The result is meant to be read, not trusted: each place\n * the planner could not decide carries a `// TODO(migrate)` line, and those\n * lines are listed in the report with their line numbers.\n */\nimport type { ClassMethod } from '@babel/types';\nimport {\n findSheetClasses,\n methodOf,\n parseSource,\n type SheetClass,\n text,\n unsupportedBases,\n} from './parse.js';\nimport {\n rewriteDialogs,\n rewriteDropMethod,\n rewriteGetData,\n rewriteHandlerBody,\n TODO,\n} from './sheet-bodies.js';\nimport { type ActionBinding, extractListeners } from './sheet-listeners.js';\nimport { extractOptions, renderStatics } from './sheet-options.js';\n\nexport interface SheetPlanFile {\n from: string;\n to: string;\n className: string;\n base: 'BaseActorSheet' | 'BaseItemSheet';\n source: string;\n actions: Array<{ name: string; selector: string; method: string }>;\n todos: Array<{ line: number; message: string }>;\n /** Template paths the class names, for the template pass. */\n templates: string[];\n tabNavSelectors: string[];\n}\n\nexport interface SheetPlan {\n files: SheetPlanFile[];\n notes: string[];\n}\n\n/** v1 lifecycle methods a sheet used to override; V2 has other hooks for the same jobs. */\nconst V1_LIFECYCLE = new Set([\n 'setPosition',\n '_getHeaderButtons',\n '_render',\n '_renderInner',\n '_replaceHTML',\n '_onSubmit',\n '_getSubmitData',\n '_onChangeInput',\n 'activateEditor',\n 'close',\n]);\n\nconst HANDLED = new Set([\n 'defaultOptions',\n 'getData',\n 'activateListeners',\n '_onDropItem',\n '_onDropActor',\n]);\nconst ACTIONS_PLACEHOLDER = ' actions: {}, // filled below';\n\nfunction methodName(m: ClassMethod): string | null {\n return m.key.type === 'Identifier' ? m.key.name : null;\n}\n\nconst pascal = (s: string) => s.replace(/^[a-z]/, (c) => c.toUpperCase());\nconst single = (s: string) => `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n\n/** Re-indent a member slice so its first line sits at two spaces. */\nfunction reindent(memberText: string): string {\n const lines = memberText.split('\\n');\n const first = lines[0] ?? '';\n const rest = lines.slice(1);\n const indents = rest\n .filter((l) => l.trim().length > 0)\n .map((l) => /^[ \\t]*/.exec(l)?.[0].length ?? 0);\n const min = indents.length > 0 ? Math.min(...indents) : 0;\n // The body sits one level under the member; keep that level at four spaces.\n const strip = Math.max(0, min - 4);\n const body = rest.map((l) => {\n if (l.trim().length === 0) return '';\n const own = /^[ \\t]*/.exec(l)?.[0].length ?? 0;\n return l.slice(Math.min(strip, own));\n });\n return [` ${first.trimStart()}`, ...body].join('\\n');\n}\n\n/** Ensure `(event, target)` on a handler method, keeping the event name it used. */\nfunction handlerSignature(\n methodText: string,\n name: string,\n): { code: string; eventParam: string | null } {\n const escaped = name.replace(/[$]/g, '\\\\$');\n const sig = new RegExp(`^(\\\\s*(?:async\\\\s+)?${escaped}\\\\s*\\\\()([^)]*)(\\\\))`);\n const m = sig.exec(methodText);\n if (!m) return { code: methodText, eventParam: null };\n const params = (m[2] ?? '')\n .split(',')\n .map((p) => p.trim())\n .filter(Boolean);\n const eventParam = params[0] ?? null;\n const first = eventParam ?? 'event';\n return { code: methodText.replace(sig, `$1${first}, target$3`), eventParam };\n}\n\n/** The first parameter name of a method, from its signature text. */\nfunction firstParam(methodText: string, name: string): string | null {\n const escaped = name.replace(/[$]/g, '\\\\$');\n const m = new RegExp(`^\\\\s*(?:async\\\\s+)?${escaped}\\\\s*\\\\(([^)]*)\\\\)`).exec(methodText);\n const first = (m?.[1] ?? '').split(',')[0]?.trim();\n return first ? first : null;\n}\n\n/** Lines after the first sit at `spaces`, keeping their relative indentation. */\nfunction indentTo(snippet: string, spaces: number): string {\n const lines = snippet.split('\\n');\n const rest = lines.slice(1);\n const indents = rest\n .filter((l) => l.trim().length > 0)\n .map((l) => /^[ \\t]*/.exec(l)?.[0].length ?? 0);\n const min = indents.length > 0 ? Math.min(...indents) : 0;\n const pad = ' '.repeat(spaces);\n return [\n (lines[0] ?? '').trimStart(),\n ...rest.map((l) =>\n l.trim().length === 0\n ? ''\n : `${pad}${l.slice(Math.min(min, /^[ \\t]*/.exec(l)?.[0].length ?? 0))}`,\n ),\n ].join('\\n');\n}\n\n/** A block body lifted out of `activateListeners`: inner lines at four spaces, the brace at two. */\nfunction dedentBlock(block: string): string {\n const lines = block.split('\\n');\n if (lines.length < 2) return block;\n const inner = lines.slice(1, -1);\n const indents = inner\n .filter((l) => l.trim().length > 0)\n .map((l) => /^[ \\t]*/.exec(l)?.[0].length ?? 0);\n const min = indents.length > 0 ? Math.min(...indents) : 0;\n const body = inner.map((l) =>\n l.trim().length === 0\n ? ''\n : ` ${l.slice(Math.min(min, /^[ \\t]*/.exec(l)?.[0].length ?? 0))}`,\n );\n return [lines[0] ?? '{', ...body, ' }'].join('\\n');\n}\n\nfunction importLines(source: string, lang: 'js' | 'ts'): string[] {\n const ast = parseSource(source, lang);\n const lines: string[] = [];\n for (const n of ast.program.body) if (n.type === 'ImportDeclaration') lines.push(text(source, n));\n return lines;\n}\n\nfunction isExported(source: string, cls: SheetClass): boolean {\n const start = cls.node.start ?? 0;\n const before = source.slice(Math.max(0, start - 40), start);\n return (\n /export\\s+(?:default\\s+)?$/.test(before) ||\n new RegExp(`export\\\\s+\\\\{[^}]*\\\\b${cls.name}\\\\b`).test(source)\n );\n}\n\ninterface ClassOutput {\n block: string;\n base: SheetPlanFile['base'];\n actions: SheetPlanFile['actions'];\n templates: string[];\n navs: string[];\n usesDialogV2: boolean;\n}\n\nfunction planClass(cls: SheetClass, source: string, tabIds: Record<string, string[]>): ClassOutput {\n const base: SheetPlanFile['base'] =\n cls.base === 'ActorSheet' ? 'BaseActorSheet' : 'BaseItemSheet';\n const own = cls.base === 'ActorSheet' ? 'actor' : 'item';\n const options = extractOptions(cls, source);\n const listeners = extractListeners(cls, source);\n const templates = new Set<string>();\n const navs = new Set<string>();\n let usesDialogV2 = false;\n\n if (options.template) templates.add(options.template);\n if (options.templateGetter) {\n for (const m of text(source, options.templateGetter).matchAll(\n /[\"'`]([^\"'`$]+\\.(?:hbs|html))[\"'`]/g,\n )) {\n if (m[1]) templates.add(m[1]);\n }\n }\n for (const t of options.tabs) navs.add(t.navSelector);\n\n const members: string[] = [];\n const todo = (msg: string) => TODO(msg);\n\n // 1. Statics, with the actions block filled in.\n const actionEntries = listeners.actions.map((a) => ({\n name: a.name,\n selector: a.selector,\n method: a.kind === 'method' && a.method ? a.method : `_on${pascal(a.name)}`,\n }));\n const actionsBlock =\n actionEntries.length === 0\n ? ' actions: {},'\n : ` actions: {\\n${actionEntries.map((a) => ` ${a.name}: ${cls.name}.prototype.${a.method},`).join('\\n')}\\n },`;\n // A runtime `get template()` decides the template; a static one next to it is not the whole story.\n const statics = options.templateGetter ? { ...options, template: null } : options;\n members.push(renderStatics(statics, tabIds, todo).replace(ACTIONS_PLACEHOLDER, actionsBlock));\n\n // 2. The document getter.\n if (!methodOf(cls.node, own, { kind: 'get' })) {\n members.push(` get ${own}() {\\n return this.document;\\n }`);\n }\n\n // 3. The template getter, when dynamic.\n if (options.templateGetter) members.push(reindent(text(source, options.templateGetter)));\n\n // 4. getData → _prepareContext.\n const getData = methodOf(cls.node, 'getData');\n if (getData) members.push(rewriteGetData(reindent(text(source, getData)), cls.base).code);\n\n // 5. _onRender for the events that are not clicks.\n if (listeners.listeners.length > 0) {\n const body = listeners.listeners\n .map((l) => {\n const param = /^\\s*(?:async\\s+)?\\(?\\s*(\\w+)/.exec(l.handlerText)?.[1] ?? null;\n const isFunction = /^\\s*(?:async\\s+)?(?:\\(|\\w+\\s*=>|function\\b)/.test(l.handlerText);\n const handler = isFunction\n ? indentTo(\n rewriteHandlerBody(\n l.handlerText,\n param,\n listeners.htmlParam,\n param ? `${param}.currentTarget` : 'target',\n ).code,\n 6,\n )\n : l.handlerText;\n return ` for (const el of this.element.querySelectorAll(${single(l.selector)})) {\\n el.addEventListener(${single(l.event)}, ${handler});\\n }`;\n })\n .join('\\n');\n members.push(\n ` /** @override */\\n _onRender(context, options) {\\n super._onRender(context, options);\\n${body}\\n }`,\n );\n }\n\n // 6. Every other member, rewritten by role.\n const handlerNames = new Set(\n listeners.actions.filter((a) => a.kind === 'method' && a.method).map((a) => a.method as string),\n );\n // Methods a render listener forwards to keep their event; jQuery on it still goes.\n const listenerTargets = new Set(\n listeners.listeners.flatMap((l) =>\n [...l.handlerText.matchAll(/this\\.(\\w+)/g)].map((m) => m[1] ?? ''),\n ),\n );\n const applyDialogs = (code: string): string => {\n const d = rewriteDialogs(code);\n if (/DialogV2\\./.test(d.code)) usesDialogV2 = true;\n return d.code;\n };\n for (const member of cls.node.body.body) {\n if (\n member.type !== 'ClassMethod' &&\n member.type !== 'ClassProperty' &&\n member.type !== 'ClassPrivateMethod'\n )\n continue;\n const name = member.type === 'ClassMethod' ? methodName(member) : null;\n if (name && HANDLED.has(name)) continue;\n if (name === 'template' && member.type === 'ClassMethod' && member.kind === 'get') continue;\n let code = reindent(text(source, member));\n if (name && handlerNames.has(name)) {\n const sig = handlerSignature(code, name);\n code = rewriteHandlerBody(sig.code, sig.eventParam, null).code;\n } else if (name && listenerTargets.has(name)) {\n const ev = firstParam(code, name);\n code = rewriteHandlerBody(code, ev, null, ev ? `${ev}.currentTarget` : 'target').code;\n } else if (member.type === 'ClassMethod') {\n // Any other method: the jQuery idioms with a DOM equivalent, the rest flagged.\n code = rewriteHandlerBody(code, null, null).code;\n }\n if (name && V1_LIFECYCLE.has(name)) {\n 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}`;\n }\n if (name === '_updateObject') {\n code = ` ${todo('_updateObject is gone on V2; DocumentSheetV2 submits the form itself. Move any shaping into _prepareSubmitData or delete this')}\\n${code}`;\n }\n members.push(applyDialogs(code));\n }\n for (const which of ['Item', 'Actor'] as const) {\n const m = methodOf(cls.node, `_onDrop${which}`);\n if (!m) continue;\n members.push(applyDialogs(rewriteDropMethod(reindent(text(source, m)), which).code));\n }\n\n // 7. Inline handlers become methods.\n const inline: ActionBinding[] = listeners.actions.filter((a) => a.kind === 'inline');\n for (const a of inline) {\n const method = `_on${pascal(a.name)}`;\n const rewritten = applyDialogs(rewriteHandlerBody(a.body ?? '{}', a.param, null).code).trim();\n const body = rewritten.startsWith('{')\n ? dedentBlock(rewritten)\n : `{\\n return ${rewritten};\\n }`;\n members.push(` ${a.isAsync ? 'async ' : ''}${method}(${a.param ?? 'event'}, target) ${body}`);\n }\n for (const l of listeners.leftovers) {\n members.push(\n ` ${todo(`from activateListeners, line ${l.line}: ${l.text.replace(/\\s+/g, ' ')}`)}`,\n );\n }\n\n const exported = isExported(source, cls);\n const block = `${exported ? 'export ' : ''}class ${cls.name} extends ${base}() {\\n${members.join('\\n\\n')}\\n}`;\n return {\n block,\n base,\n actions: actionEntries,\n templates: [...templates],\n navs: [...navs],\n usesDialogV2,\n };\n}\n\nexport function planSheetFile(\n relPath: string,\n source: string,\n opts: { lang: 'js' | 'ts'; tabIds: Record<string, string[]> },\n): SheetPlan {\n const lang: 'js' | 'ts' = relPath.endsWith('.ts') ? 'ts' : opts.lang;\n const ast = parseSource(source, lang);\n const classes = findSheetClasses(ast, source);\n const notes = unsupportedBases(ast, source).map(\n (u) =>\n `${relPath}:${u.line} ${u.name} extends ${u.superText}; only ActorSheet and ItemSheet are converted, this one stays as it is`,\n );\n if (classes.length === 0) return { files: [], notes };\n\n const dot = relPath.lastIndexOf('.');\n const to = `${relPath.slice(0, dot)}.v2${relPath.slice(dot)}`;\n const outputs = classes.map((cls) => ({ cls, out: planClass(cls, source, opts.tabIds) }));\n\n const bases = [...new Set(outputs.map((o) => o.out.base))].join(', ');\n const header = [`import { ${bases} } from '@vttforge/core';`, ...importLines(source, lang)];\n if (outputs.some((o) => o.out.usesDialogV2))\n header.push('', 'const { DialogV2 } = foundry.applications.api;');\n const fileSource = `${header.join('\\n')}\\n\\n${outputs.map((o) => o.out.block).join('\\n\\n')}\\n`;\n const marker = 'TODO(migrate): ';\n const todos = fileSource.split('\\n').flatMap((line, i) => {\n const at = line.indexOf(marker);\n return at === -1 ? [] : [{ line: i + 1, message: line.slice(at + marker.length).trim() }];\n });\n\n const files: SheetPlanFile[] = outputs.map(({ cls, out }) => ({\n from: relPath,\n to,\n className: cls.name,\n base: out.base,\n source: fileSource,\n actions: out.actions,\n todos,\n templates: out.templates,\n tabNavSelectors: out.navs,\n }));\n return { files, notes };\n}\n","/**\n * The rewrites `vttforge migrate` applies to a v13 source file.\n *\n * Each transform is a pure function over the file's text. It returns the new\n * text, one `Change` per edit it made, and one `Note` per thing it saw and\n * would not touch: a rewrite that needs a decision (which page a `game.template`\n * read should become) is reported, not guessed.\n *\n * Text-based, like the audit rules they mirror (`VTTF-AUDIT-011` to `016`).\n * The patterns are short and mechanical, and a syntax tree would not make\n * `'-=key'` easier to find. Comments are left alone: every match has to\n * start in code. A match inside a string literal is still rewritten, which\n * is what the preview is for.\n */\n\nimport { bareUsePattern, definesName, LEGACY_GLOBALS } from '../audit/legacy-globals.js';\nimport { MASK, maskComments } from '../audit/mask.js';\nimport { REMOVED_UTILS } from '../audit/v14-rules.js';\n\nexport interface Change {\n /** 1-based line of the edit, in the original text. */\n line: number;\n /** What was there. */\n before: string;\n /** What is there now. */\n after: string;\n /** Which transform made it. */\n rule: string;\n}\n\nexport interface Note {\n line: number;\n rule: string;\n /** What was seen, and what the reader has to decide. */\n message: string;\n}\n\nexport interface TransformResult {\n output: string;\n changes: Change[];\n notes: Note[];\n}\n\nexport type Transform = (source: string) => TransformResult;\n\nfunction lineAt(source: string, index: number): number {\n let line = 1;\n for (let i = 0; i < index && i < source.length; i += 1) {\n if (source[i] === '\\n') line += 1;\n }\n return line;\n}\n\n/** The whole line an index sits on, trimmed, for the report. */\nfunction lineText(source: string, index: number): string {\n const start = source.lastIndexOf('\\n', index - 1) + 1;\n const end = source.indexOf('\\n', index);\n return source.slice(start, end === -1 ? source.length : end).trim();\n}\n\n/**\n * Replace every match, recording one change per match against the original\n * text. The replacement may be a string or a function, like `String#replace`.\n */\nfunction rewrite(\n source: string,\n pattern: RegExp,\n replacement: string | ((...groups: string[]) => string),\n rule: string,\n): TransformResult {\n const changes: Change[] = [];\n const code = maskComments(source);\n const output = source.replace(pattern, (match: string, ...rest: unknown[]) => {\n const offset = rest.find((r): r is number => typeof r === 'number') ?? 0;\n if (code[offset] === MASK) return match;\n const groups = rest.filter((r): r is string => typeof r === 'string');\n const after = typeof replacement === 'string' ? replacement : replacement(match, ...groups);\n if (after !== match) {\n changes.push({ line: lineAt(source, offset), before: match, after, rule });\n }\n return after;\n });\n return { output, changes, notes: [] };\n}\n\nfunction merge(...results: TransformResult[]): TransformResult {\n const last = results.at(-1);\n return {\n output: last?.output ?? '',\n changes: results.flatMap((r) => r.changes),\n notes: results.flatMap((r) => r.notes),\n };\n}\n\n/** Run transforms in sequence, each on the previous one's output. */\nfunction pipe(source: string, transforms: readonly Transform[]): TransformResult {\n const results: TransformResult[] = [];\n let current = source;\n for (const transform of transforms) {\n const result = transform(current);\n results.push(result);\n current = result.output;\n }\n return merge(...results);\n}\n\n/**\n * Bare v12 utility globals → `foundry.utils.*`; `Math.clamped` → `Math.clamp`.\n *\n * A name the file declares or imports itself is left alone, the same way\n * `VTTF-AUDIT-011` leaves it alone. `game.template` is reported, not\n * rewritten: whether it becomes `game.model` or a `documentTypes` read depends\n * on what was read from it.\n */\nexport const removedGlobals: Transform = (source) => {\n const own = new Set(\n REMOVED_UTILS.filter((name) =>\n new RegExp(\n `(?:function\\\\s+${name}\\\\b|(?:const|let|var)\\\\s+${name}\\\\b|import[^;]*\\\\b${name}\\\\b|\\\\b${name}\\\\s*\\\\([^)]*\\\\)\\\\s*\\\\{)`,\n ).test(source),\n ),\n );\n const names = REMOVED_UTILS.filter((name) => !own.has(name));\n const utils = names.length\n ? rewrite(\n source,\n new RegExp(`(?<![\\\\w$.])(${names.join('|')})\\\\s*\\\\(`, 'g'),\n (_m, name) => `foundry.utils.${name}(`,\n 'removed-globals',\n )\n : { output: source, changes: [], notes: [] };\n const clamped = rewrite(utils.output, /\\bMath\\.clamped\\s*\\(/g, 'Math.clamp(', 'removed-globals');\n const notes: Note[] = [];\n const code = maskComments(clamped.output);\n for (const match of clamped.output.matchAll(/\\bgame\\.template\\b/g)) {\n if (code[match.index ?? 0] === MASK) continue;\n notes.push({\n line: lineAt(clamped.output, match.index ?? 0),\n rule: 'removed-globals',\n message:\n \"`game.template` is gone. Read type defaults from `game.model`, or the type list from the package's `documentTypes`.\",\n });\n }\n return { ...merge(utils, clamped), notes };\n};\n\n/**\n * Bare v13 global aliases → their `foundry.*` path: `renderTemplate(` →\n * `foundry.applications.handlebars.renderTemplate(`, `extends ActorSheet` →\n * `extends foundry.appv1.sheets.ActorSheet`. Same object, no removal date.\n * A name the file declares or imports, an object key, a property, and a\n * word inside a string or comment are left alone.\n */\nexport const namespacedGlobals: Transform = (source) => {\n const changes: Change[] = [];\n const code = maskComments(source, { strings: true });\n const edits: Array<{ start: number; end: number; text: string; name: string }> = [];\n for (const [name, path] of Object.entries(LEGACY_GLOBALS)) {\n if (definesName(code, name)) continue;\n for (const match of code.matchAll(bareUsePattern(name))) {\n const start = match.index ?? 0;\n edits.push({ start, end: start + name.length, text: path, name });\n }\n }\n let output = source;\n for (const edit of edits.sort((a, b) => b.start - a.start)) {\n output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);\n }\n for (const edit of edits.sort((a, b) => a.start - b.start)) {\n changes.push({\n line: lineAt(source, edit.start),\n before: edit.name,\n after: edit.text,\n rule: 'namespaced-globals',\n });\n }\n return { output, changes, notes: [] };\n};\n\n/**\n * `'-=key': null` → `key: _del`; `'==key': value` → `key: _replace(value)`;\n * `performDeletions` → `applyOperators`; `objectsEqual` → `equals`.\n *\n * The key may be a template literal with `${...}` segments in the prefix,\n * which is how a flag deletion is usually written: `` [`flags.${id}.-=old`] ``.\n */\nexport const dataOperators: Transform = (source) => {\n const deletions = rewrite(\n source,\n /(['\"`])((?:[\\w$]+\\.|\\$\\{[^}]*\\}\\.)*)-=([\\w$.]+)\\1(\\]?)\\s*:\\s*null\\b/g,\n (_m, quote, prefix, key, bracket) => `${quote}${prefix}${key}${quote}${bracket}: _del`,\n 'data-operators',\n );\n // `\"==key\": <value>` wraps a value of any shape, so the value is scanned to\n // its end rather than matched: up to the comma or brace that closes it, with\n // brackets, braces, parentheses and strings balanced along the way.\n const replacements = wrapReplacementValues(deletions.output);\n const flags = rewrite(\n replacements.output,\n /\\bperformDeletions\\s*:/g,\n 'applyOperators:',\n 'data-operators',\n );\n const equals = rewrite(\n flags.output,\n /\\bfoundry\\.utils\\.objectsEqual\\s*\\(/g,\n 'foundry.utils.equals(',\n 'data-operators',\n );\n return merge(deletions, replacements, flags, equals);\n};\n\nfunction wrapReplacementValues(source: string): TransformResult {\n const changes: Change[] = [];\n const pattern = /(['\"`])((?:[\\w$]+\\.|\\$\\{[^}]*\\}\\.)*)==([\\w$.]+)\\1(\\]?)\\s*:\\s*/g;\n const code = maskComments(source);\n let out = '';\n let cursor = 0;\n for (const match of source.matchAll(pattern)) {\n const start = match.index ?? 0;\n if (code[start] === MASK) continue;\n const valueStart = start + match[0].length;\n const valueEnd = scanValueEnd(source, valueStart);\n if (valueEnd === -1) continue;\n const value = source.slice(valueStart, valueEnd).trimEnd();\n const [, quote = '\"', prefix = '', key = '', bracket = ''] = match;\n const after = `${quote}${prefix}${key}${quote}${bracket}: _replace(${value})`;\n out += source.slice(cursor, start) + after;\n cursor = valueStart + value.length;\n changes.push({\n line: lineAt(source, start),\n before: source.slice(start, cursor),\n after,\n rule: 'data-operators',\n });\n }\n out += source.slice(cursor);\n return { output: out, changes, notes: [] };\n}\n\n/** Index just past a value that starts at `from`: the next `,` or `}` at depth zero. */\nfunction scanValueEnd(source: string, from: number): number {\n let depth = 0;\n let quote: string | null = null;\n for (let i = from; i < source.length; i += 1) {\n const ch = source[i] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') quote = ch;\n else if (ch === '{' || ch === '[' || ch === '(') depth += 1;\n else if (ch === '}' || ch === ']' || ch === ')') {\n if (depth === 0) return i;\n depth -= 1;\n } else if (ch === ',' && depth === 0) return i;\n }\n return -1;\n}\n\nconst ROLL_MODE_VALUES: Record<string, string> = {\n publicroll: 'public',\n gmroll: 'gm',\n blindroll: 'blind',\n selfroll: 'self',\n};\n\nconst ROLL_MODE_CONSTANTS: Record<string, string> = {\n PUBLIC: 'public',\n PRIVATE: 'gm',\n BLIND: 'blind',\n SELF: 'self',\n};\n\n/**\n * `rollMode` → `messageMode`, with the value mapped when it is a literal.\n *\n * `\"roll\"` meant \"whatever the user's chat dropdown says\", which is what an\n * absent `messageMode` means now, so it becomes `undefined`. A value that is\n * an expression is wrapped in `Roll._mapLegacyRollMode(...)`, which maps a\n * v13 name and passes a v14 key or `undefined` through unchanged, so the\n * wrap is safe whatever the expression yields.\n */\nexport const rollMode: Transform = (source) => {\n const option = rewrite(\n source,\n /\\brollMode\\s*:\\s*(['\"])(publicroll|gmroll|blindroll|selfroll|roll)\\1/g,\n (_m, quote, value) =>\n value === 'roll'\n ? 'messageMode: undefined'\n : `messageMode: ${quote}${ROLL_MODE_VALUES[value]}${quote}`,\n 'roll-mode',\n );\n const expressions = wrapRollModeExpressions(option.output);\n const setting = rewrite(\n expressions.output,\n /(['\"])core\\1\\s*,\\s*(['\"])rollMode\\2/g,\n (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`,\n 'roll-mode',\n );\n const modes = rewrite(\n setting.output,\n /\\bCONFIG\\.Dice\\.rollModes\\b/g,\n 'CONFIG.ChatMessage.modes',\n 'roll-mode',\n );\n const constants = rewrite(\n modes.output,\n /\\bCONST\\.DICE_ROLL_MODES\\.(PUBLIC|PRIVATE|BLIND|SELF)\\b/g,\n (_m, name) => `\"${ROLL_MODE_CONSTANTS[name]}\"`,\n 'roll-mode',\n );\n return merge(option, expressions, setting, modes, constants);\n};\n\n/** `rollMode: <expr>` → `messageMode: Roll._mapLegacyRollMode(<expr>)`. */\nfunction wrapRollModeExpressions(source: string): TransformResult {\n const changes: Change[] = [];\n const pattern = /\\brollMode\\s*:\\s*/g;\n const code = maskComments(source);\n let out = '';\n let cursor = 0;\n for (const match of source.matchAll(pattern)) {\n const start = match.index ?? 0;\n if (code[start] === MASK) continue;\n const valueStart = start + match[0].length;\n const valueEnd = scanValueEnd(source, valueStart);\n if (valueEnd === -1) continue;\n const value = source.slice(valueStart, valueEnd).trimEnd();\n const after = `messageMode: Roll._mapLegacyRollMode(${value})`;\n out += source.slice(cursor, start) + after;\n cursor = valueStart + value.length;\n changes.push({\n line: lineAt(source, start),\n before: source.slice(start, cursor),\n after,\n rule: 'roll-mode',\n });\n }\n out += source.slice(cursor);\n return { output: out, changes, notes: [] };\n}\n\n/**\n * Hooks that changed shape: noted, not rewritten. `renderChatMessage` is\n * removed in v15 and its replacement hands an element where it handed a\n * jQuery object, so the handler body is the reader's to change.\n */\nexport const hookNotes: Transform = (source) => {\n const notes: Note[] = [];\n const code = maskComments(source);\n for (const match of source.matchAll(/Hooks\\.(?:on|once)\\(\\s*['\"]renderChatMessage['\"]/g)) {\n if (code[match.index ?? 0] === MASK) continue;\n notes.push({\n line: lineAt(source, match.index ?? 0),\n rule: 'hooks',\n message:\n '`renderChatMessage` is removed in v15. Listen to `renderChatMessageHTML(message, html, context)`; `html` is the element, so `html.find(x)` becomes `html.querySelector(x)`.',\n });\n }\n return { output: source, changes: [], notes };\n};\n\n/**\n * Context-menu entries and header controls: `name` → `label`, `condition` →\n * `visible`, `callback` → `onClick`.\n *\n * Only an object literal whose own keys include `callback` and `name` or\n * `condition` is an entry. A Dialog button has `icon`, `label` and\n * `callback`, and keeps `callback` on v14, so `icon` is not a signal; and\n * only the literal's own keys count, so a class body or a `buttons` bag that\n * happens to contain an entry is not itself treated as one. The callback's\n * parameters change too, from `(li)` to `(event, target)`, and that is noted\n * rather than rewritten.\n */\nexport const contextMenuKeys: Transform = (source) => {\n const changes: Change[] = [];\n const notes: Note[] = [];\n const RENAME: Record<string, string> = {\n name: 'label',\n condition: 'visible',\n callback: 'onClick',\n };\n // Innermost first, so an edit never moves the offsets of a literal still\n // to be visited: an inner literal sits entirely inside its outer one, and\n // editing it changes the outer one's end, never its start.\n const edits: Array<{ start: number; end: number; text: string }> = [];\n for (const { start, end } of objectLiterals(source).sort((a, b) => b.start - a.start)) {\n const keys = ownKeys(source, start, end);\n const names = new Set(keys.map((k) => k.name));\n if (!names.has('callback') || !(names.has('name') || names.has('condition'))) continue;\n for (const key of keys) {\n const to = RENAME[key.name];\n if (to !== undefined)\n edits.push({ start: key.offset, end: key.offset + key.name.length, text: to });\n }\n changes.push({\n line: lineAt(source, start),\n before: lineText(source, start),\n after: 'label / visible / onClick keys',\n rule: 'context-menu-keys',\n });\n notes.push({\n line: lineAt(source, start),\n rule: 'context-menu-keys',\n message:\n '`onClick` receives `(event, target)` where `callback` received the element. Check the parameter list.',\n });\n }\n let output = source;\n for (const edit of edits.sort((a, b) => b.start - a.start)) {\n output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);\n }\n return { output, changes, notes };\n};\n\n/**\n * The keys an object literal declares itself, with the offset of each name.\n *\n * Walks the span between the braces at depth one: a key is an identifier\n * followed by `:` where a property may start, which is right after the\n * opening brace or after a comma at that depth. Nested literals, arrays,\n * calls, strings and comments are stepped over.\n */\nfunction ownKeys(\n source: string,\n start: number,\n end: number,\n): Array<{ name: string; offset: number }> {\n const keys: Array<{ name: string; offset: number }> = [];\n let depth = 0;\n let quote: string | null = null;\n let expectKey = true;\n for (let i = start; i < end; i += 1) {\n const ch = source[i] ?? '';\n const next = source[i + 1] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '/' && next === '/') {\n const nl = source.indexOf('\\n', i);\n i = nl === -1 ? end : nl;\n continue;\n }\n if (ch === '/' && next === '*') {\n const close = source.indexOf('*/', i + 2);\n i = close === -1 ? end : close + 1;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n quote = ch;\n expectKey = false;\n continue;\n }\n if (ch === '{' || ch === '[' || ch === '(') {\n depth += 1;\n expectKey = depth === 1 && ch === '{';\n continue;\n }\n if (ch === '}' || ch === ']' || ch === ')') {\n depth -= 1;\n expectKey = false;\n continue;\n }\n if (depth !== 1) continue;\n if (ch === ',') {\n expectKey = true;\n continue;\n }\n if (/\\s/.test(ch)) continue;\n if (expectKey && /[A-Za-z_$]/.test(ch)) {\n let j = i;\n while (j < end && /[\\w$]/.test(source[j] ?? '')) j += 1;\n let k = j;\n while (k < end && /\\s/.test(source[k] ?? '')) k += 1;\n if (source[k] === ':') keys.push({ name: source.slice(i, j), offset: i });\n i = j - 1;\n }\n expectKey = false;\n }\n return keys;\n}\n\n/** Every `{ ... }` span in the text, outermost first, strings and comments skipped. */\nfunction objectLiterals(source: string): Array<{ start: number; end: number }> {\n const spans: Array<{ start: number; end: number }> = [];\n const stack: number[] = [];\n let quote: string | null = null;\n for (let i = 0; i < source.length; i += 1) {\n const ch = source[i] ?? '';\n const next = source[i + 1] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '/' && next === '/') {\n i = source.indexOf('\\n', i);\n if (i === -1) break;\n continue;\n }\n if (ch === '/' && next === '*') {\n const close = source.indexOf('*/', i + 2);\n i = close === -1 ? source.length : close + 1;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') quote = ch;\n else if (ch === '{') stack.push(i);\n else if (ch === '}') {\n const start = stack.pop();\n if (start !== undefined) spans.push({ start, end: i + 1 });\n }\n }\n return spans.sort((a, b) => a.start - b.start);\n}\n\n/**\n * `legacyTransferral` is gone: the assignment, and the `activeEffect`\n * option `registerSystem` used to take for it.\n */\nexport const legacyTransferral: Transform = (source) => {\n const statement = rewrite(\n source,\n /^[ \\t]*CONFIG\\.ActiveEffect\\.legacyTransferral\\s*=[^\\n]*\\n?/gm,\n '',\n 'legacy-transferral',\n );\n const option = rewrite(\n statement.output,\n /^[ \\t]*activeEffect\\s*:\\s*\\{\\s*legacyTransferral\\s*:\\s*(?:true|false)\\s*,?\\s*\\}\\s*,?[ \\t]*\\n?/gm,\n '',\n 'legacy-transferral',\n );\n const key = rewrite(\n option.output,\n /^[ \\t]*legacyTransferral\\s*:\\s*(?:true|false)\\s*,?[ \\t]*\\n?/gm,\n '',\n 'legacy-transferral',\n );\n return merge(statement, option, key);\n};\n\n/** v14 registers no core Actor or Item sheet, so there is nothing to unregister. */\nexport const unregisterCoreSheets: Transform = (source) =>\n rewrite(\n source,\n /^[ \\t]*(?:foundry\\.documents\\.collections\\.)?(?:Actors|Items)\\.unregisterSheet\\(\\s*['\"]core['\"][^\\n]*\\n?/gm,\n '',\n 'unregister-core-sheets',\n );\n\n/**\n * `CONFIG.statusEffects = list;` → add each entry by id. The setter empties\n * the collection first, which wipes what other packages added.\n */\nexport const statusEffectsAssignment: Transform = (source) => {\n const changes: Change[] = [];\n let output = '';\n let cursor = 0;\n const pattern = /\\bCONFIG\\.statusEffects\\s*=(?!=)\\s*/g;\n const code = maskComments(source);\n for (const match of source.matchAll(pattern)) {\n const start = match.index ?? 0;\n if (code[start] === MASK) continue;\n const valueStart = start + match[0].length;\n const end = scanStatementEnd(source, valueStart);\n if (end === -1) continue;\n const value = source.slice(valueStart, end).trim();\n const after = `for (const effect of ${value}) CONFIG.statusEffects[effect.id] = effect;`;\n output += source.slice(cursor, start) + after;\n cursor = end + 1;\n changes.push({\n line: lineAt(source, start),\n before: source.slice(start, cursor).trim(),\n after,\n rule: 'status-effects',\n });\n }\n output += source.slice(cursor);\n return { output, changes, notes: [] };\n};\n\n/** Index of the `;` that ends a statement starting at `from`, brackets balanced. */\nfunction scanStatementEnd(source: string, from: number): number {\n let depth = 0;\n let quote: string | null = null;\n for (let i = from; i < source.length; i += 1) {\n const ch = source[i] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') quote = ch;\n else if (ch === '{' || ch === '[' || ch === '(') depth += 1;\n else if (ch === '}' || ch === ']' || ch === ')') depth -= 1;\n else if (ch === ';' && depth === 0) return i;\n }\n return -1;\n}\n\nconst EFFECT_MODES: Record<string, string> = {\n CUSTOM: 'custom',\n MULTIPLY: 'multiply',\n ADD: 'add',\n DOWNGRADE: 'downgrade',\n UPGRADE: 'upgrade',\n OVERRIDE: 'override',\n};\n\n/**\n * `mode: CONST.ACTIVE_EFFECT_MODES.ADD` → `type: \"add\"`. A root-level\n * `changes` array on an effect now lives under `system.changes`; that move\n * depends on where the data is built, so it is noted.\n */\nexport const activeEffectModes: Transform = (source) => {\n const typed = rewrite(\n source,\n /\\bmode\\s*:\\s*CONST\\.ACTIVE_EFFECT_MODES\\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\\b/g,\n (_m, name) => `type: \"${EFFECT_MODES[name]}\"`,\n 'active-effect-modes',\n );\n const bare = rewrite(\n typed.output,\n /\\bCONST\\.ACTIVE_EFFECT_MODES\\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\\b/g,\n (_m, name) => `\"${EFFECT_MODES[name]}\"`,\n 'active-effect-modes',\n );\n const notes: Note[] = typed.changes.map((c) => ({\n line: c.line,\n rule: 'active-effect-modes',\n message: 'The change now belongs under `system.changes`, not a root-level `changes` array.',\n }));\n return { ...merge(typed, bare), notes };\n};\n\n/** The transforms, in the order they run. */\nconst SOURCE_TRANSFORMS: ReadonlyArray<readonly [string, Transform]> = [\n ['removed-globals', removedGlobals],\n ['namespaced-globals', namespacedGlobals],\n ['data-operators', dataOperators],\n ['roll-mode', rollMode],\n ['context-menu-keys', contextMenuKeys],\n ['legacy-transferral', legacyTransferral],\n ['unregister-core-sheets', unregisterCoreSheets],\n ['status-effects', statusEffectsAssignment],\n ['active-effect-modes', activeEffectModes],\n ['hooks', hookNotes],\n];\n\nexport function transformSource(source: string): TransformResult {\n return pipe(\n source,\n SOURCE_TRANSFORMS.map(([, t]) => t),\n );\n}\n\n/**\n * The manifest: `type` declared, `compatibility` raised to 14 where it is\n * lower. Returns `null` when nothing needed to change.\n *\n * Edited as text, not re-serialised: a manifest carries its author's\n * indentation, key order and one-line arrays, and a diff that reformats the\n * whole file to add one key is a diff nobody merges. `type` goes on the line\n * after `id`, with that line's indentation; the compatibility values are\n * replaced in place.\n */\nexport function transformManifest(\n raw: string,\n kind: 'system' | 'module',\n): { output: string; changes: Change[]; notes: Note[] } | null {\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n const changes: Change[] = [];\n const notes: Note[] = [];\n let output = raw;\n\n if (parsed.type !== kind) {\n const typeKey = topLevelKey(output, 'type');\n if (typeKey) {\n output = `${output.slice(0, typeKey.valueStart)}\"${kind}\"${output.slice(typeKey.valueEnd)}`;\n changes.push({\n line: lineAt(raw, typeKey.keyStart),\n before: raw.slice(typeKey.keyStart, typeKey.valueEnd).trim(),\n after: `\"type\": \"${kind}\"`,\n rule: 'manifest',\n });\n } else {\n const idKey = topLevelKey(output, 'id');\n if (idKey) {\n const lineStart = output.lastIndexOf('\\n', idKey.keyStart) + 1;\n const indent = output.slice(lineStart, idKey.keyStart);\n const after = output.indexOf('\\n', idKey.valueEnd);\n const insertAt = after === -1 ? output.length : after;\n const needsComma = !/,\\s*$/.test(output.slice(idKey.valueEnd, insertAt));\n const head = needsComma\n ? `${output.slice(0, idKey.valueEnd)},${output.slice(idKey.valueEnd, insertAt)}`\n : output.slice(0, insertAt);\n output = `${head}\\n${indent}\"type\": \"${kind}\",${output.slice(insertAt)}`;\n changes.push({\n line: lineAt(raw, idKey.keyStart) + 1,\n before: '(no \"type\")',\n after: `\"type\": \"${kind}\"`,\n rule: 'manifest',\n });\n } else {\n notes.push({\n line: 1,\n rule: 'manifest',\n message: `Add \\`\"type\": \"${kind}\"\\` next to \"id\"; the key could not be placed by hand.`,\n });\n }\n }\n }\n\n const compatibility = (parsed.compatibility ?? {}) as Record<string, unknown>;\n for (const field of ['minimum', 'verified'] as const) {\n const current = compatibility[field];\n const major = Number.parseInt(String(current ?? '0'), 10);\n if (Number.isFinite(major) && major >= 14) continue;\n const block = topLevelKey(output, 'compatibility');\n const inner = block ? topLevelKey(output.slice(block.valueStart, block.valueEnd), field) : null;\n if (block && inner && current !== undefined) {\n const valueStart = block.valueStart + inner.valueStart;\n const valueEnd = block.valueStart + inner.valueEnd;\n output = `${output.slice(0, valueStart)}\"14\"${output.slice(valueEnd)}`;\n changes.push({\n line: lineAt(output, block.valueStart + inner.keyStart),\n before: `compatibility.${field}: ${JSON.stringify(current)}`,\n after: `compatibility.${field}: \"14\"`,\n rule: 'manifest',\n });\n continue;\n }\n notes.push({\n line: 1,\n rule: 'manifest',\n message: `Set compatibility.${field} to \"14\"; it is ${JSON.stringify(current ?? null)} and could not be edited in place.`,\n });\n }\n const maximum = compatibility.maximum;\n if (maximum !== undefined && Number.parseInt(String(maximum), 10) < 14) {\n notes.push({\n line: 1,\n rule: 'manifest',\n message: `compatibility.maximum is ${JSON.stringify(maximum)}, which keeps the package off v14. Raise it or remove it.`,\n });\n }\n if ('gridDistance' in parsed || 'gridUnits' in parsed) {\n notes.push({\n line: 1,\n rule: 'manifest',\n message:\n 'gridDistance / gridUnits are ignored on v14. Move them into `\"grid\": { \"type\", \"distance\", \"units\", \"diagonals\" }`.',\n });\n }\n if (changes.length === 0) return notes.length ? { output: raw, changes, notes } : null;\n JSON.parse(output); // an edit that broke the file is a bug here, not the user's problem\n return { output, changes, notes };\n}\n\n/**\n * Where a key of the root object sits in the JSON text: the start of the\n * quoted key, and the span of its value. Only depth one counts, so a\n * `\"type\"` inside `relationships.systems[]` is not the manifest's `type`.\n */\nfunction topLevelKey(\n json: string,\n key: string,\n): { keyStart: number; valueStart: number; valueEnd: number } | null {\n let depth = 0;\n let i = 0;\n const skipString = (from: number): number => {\n let j = from + 1;\n for (; j < json.length; j += 1) {\n if (json[j] === '\\\\') j += 1;\n else if (json[j] === '\"') return j + 1;\n }\n return j;\n };\n const skipValue = (from: number): number => {\n let j = from;\n while (j < json.length && /\\s/.test(json[j] ?? '')) j += 1;\n const ch = json[j] ?? '';\n if (ch === '\"') return skipString(j);\n if (ch === '{' || ch === '[') {\n let d = 0;\n for (let k = j; k < json.length; k += 1) {\n const c = json[k] ?? '';\n if (c === '\"') k = skipString(k) - 1;\n else if (c === '{' || c === '[') d += 1;\n else if (c === '}' || c === ']') {\n d -= 1;\n if (d === 0) return k + 1;\n }\n }\n return json.length;\n }\n while (j < json.length && !/[,}\\]\\s]/.test(json[j] ?? '')) j += 1;\n return j;\n };\n while (i < json.length) {\n const ch = json[i] ?? '';\n if (ch === '\"') {\n const end = skipString(i);\n if (depth === 1) {\n const name = json.slice(i + 1, end - 1);\n let k = end;\n while (k < json.length && /\\s/.test(json[k] ?? '')) k += 1;\n if (json[k] === ':') {\n const valueStart = (() => {\n let v = k + 1;\n while (v < json.length && /\\s/.test(json[v] ?? '')) v += 1;\n return v;\n })();\n const valueEnd = skipValue(k + 1);\n if (name === key) return { keyStart: i, valueStart, valueEnd };\n i = valueEnd;\n continue;\n }\n }\n i = end;\n continue;\n }\n if (ch === '{' || ch === '[') depth += 1;\n else if (ch === '}' || ch === ']') depth -= 1;\n i += 1;\n }\n return null;\n}\n","/**\n * `vttforge migrate`: rewrite a v13 project for v14.\n *\n * Walks the same files the audit walks, applies the transforms, and reports\n * every edit and every thing it saw and would not decide for you. Nothing is\n * written unless asked: the preview is the default, because a text rewrite\n * that touched a string literal is something to see before it lands.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { runReleaseRules } from '../audit/release-rules.js';\nimport { _internal } from '../audit/source-rules.js';\nimport { type EmitStyle, planDataModels } from './data-models.js';\nimport { editTemplate, readTabIds, type TemplateEdit } from './sheet-templates.js';\nimport { planSheetFile, type SheetPlanFile } from './sheets.js';\nimport { type Change, type Note, transformManifest, transformSource } from './transforms.js';\n\ninterface FileResult {\n /** Project-relative path. */\n file: string;\n changes: Change[];\n notes: Note[];\n}\n\nexport interface MigrateReport {\n cwd: string;\n /** Files with at least one change or note. */\n files: FileResult[];\n /** Whether the edits were written to disk. */\n written: boolean;\n counts: { files: number; changes: number; notes: number };\n /** Present when data models were generated from template.json. */\n dataModels?: {\n files: string[];\n documentTypes: Record<string, Record<string, Record<string, unknown>>>;\n registration: string;\n notes: string[];\n };\n /** Present when V2 sheet files were generated from Application v1 classes. */\n sheets?: {\n files: Array<Omit<SheetPlanFile, 'source'>>;\n templates: Array<{ file: string; edits: TemplateEdit[]; formRoot: boolean }>;\n notes: string[];\n };\n}\n\nexport interface MigrateOptions {\n cwd: string;\n /** Write the edits. Default false: report only. */\n write?: boolean;\n /** Also generate a data model per template.json type. */\n dataModels?: boolean;\n /** How the generated models are written: bare Foundry classes, or on the SDK's bases. */\n style?: EmitStyle;\n /** File extension of the generated models and sheets. */\n lang?: 'js' | 'ts';\n /** Also generate a V2 sheet file per Application v1 sheet class. */\n sheets?: boolean;\n}\n\nexport async function runMigrate(options: MigrateOptions): Promise<MigrateReport> {\n const { cwd } = options;\n const write = options.write === true;\n if (!existsSync(cwd) || !(await stat(cwd)).isDirectory()) {\n throw new Error(`Migrate target is not a directory: ${cwd}`);\n }\n\n const files: FileResult[] = [];\n\n for (const [name, kind] of [\n ['system.json', 'system'],\n ['module.json', 'module'],\n ] as const) {\n const path = join(cwd, name);\n if (!existsSync(path)) continue;\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n JSON.parse(raw);\n } catch {\n continue;\n }\n const result = transformManifest(raw, kind);\n if (result === null) continue;\n files.push({ file: name, changes: result.changes, notes: result.notes });\n if (write && result.changes.length > 0) await writeFile(path, result.output, 'utf8');\n }\n\n for await (const path of _internal.walkSourceFiles(cwd)) {\n let source: string;\n try {\n source = await readFile(path, 'utf8');\n } catch {\n continue;\n }\n const result = transformSource(source);\n if (result.changes.length === 0 && result.notes.length === 0) continue;\n files.push({ file: relative(cwd, path), changes: result.changes, notes: result.notes });\n if (write && result.output !== source) await writeFile(path, result.output, 'utf8');\n }\n\n // A project that builds to dist/ with a release workflow written for the old\n // layout publishes a package with no entry file. Say so here, since the\n // rewrite is what moves the project onto the build.\n for (const finding of await runReleaseRules(cwd)) {\n files.push({\n file: finding.filePath,\n changes: [],\n notes: [\n {\n line: finding.line ?? 1,\n rule: finding.ruleId,\n message: `${finding.message} ${finding.remediation ?? ''}`.trim(),\n },\n ],\n });\n }\n\n files.sort((a, b) => a.file.localeCompare(b.file));\n const report: MigrateReport = {\n cwd,\n files,\n written: write,\n counts: {\n files: files.length,\n changes: files.reduce((n, f) => n + f.changes.length, 0),\n notes: files.reduce((n, f) => n + f.notes.length, 0),\n },\n };\n\n if (options.dataModels) {\n const templatePath = join(cwd, 'template.json');\n if (!existsSync(templatePath)) {\n report.dataModels = {\n files: [],\n documentTypes: {},\n registration: '',\n notes: ['No template.json here; nothing to generate.'],\n };\n } else {\n const template = JSON.parse(await readFile(templatePath, 'utf8')) as Record<string, unknown>;\n const plan = planDataModels(template, {\n style: options.style ?? 'plain',\n lang: options.lang ?? 'js',\n });\n const written: string[] = [];\n for (const file of plan.files) {\n const target = join(cwd, file.path);\n if (existsSync(target)) {\n plan.notes.unshift(`${file.path} exists and was left alone.`);\n continue;\n }\n if (write) {\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, file.source, 'utf8');\n }\n written.push(file.path);\n }\n report.dataModels = {\n files: written,\n documentTypes: plan.documentTypes,\n registration: plan.registration,\n notes: plan.notes,\n };\n }\n }\n\n if (options.sheets) report.sheets = await planSheets(cwd, write, options.lang ?? 'js');\n\n return report;\n}\n\n/** Every `.hbs` / `.html` under `templates/`, project-relative. */\nasync function allTemplates(cwd: string): Promise<string[]> {\n const root = join(cwd, 'templates');\n if (!existsSync(root)) return [];\n const out: string[] = [];\n const visit = async (dir: string): Promise<void> => {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) await visit(full);\n else if (/\\.(?:hbs|html)$/.test(entry.name)) out.push(relative(cwd, full));\n }\n };\n await visit(root);\n return out.sort();\n}\n\n/** Project-relative path for a Foundry template path such as `systems/<id>/templates/x.html`. */\nfunction localTemplate(cwd: string, foundryPath: string): string | null {\n const m = /^(?:systems|modules)\\/[^/]+\\/(.+)$/.exec(foundryPath);\n const rel = m?.[1] ?? foundryPath;\n return existsSync(join(cwd, rel)) ? rel : null;\n}\n\nasync function planSheets(\n cwd: string,\n write: boolean,\n lang: 'js' | 'ts',\n): Promise<NonNullable<MigrateReport['sheets']>> {\n const files: Array<Omit<SheetPlanFile, 'source'>> = [];\n const templates: Array<{ file: string; edits: TemplateEdit[]; formRoot: boolean }> = [];\n const notes: string[] = [];\n const generated = new Map<string, string>();\n\n for await (const path of _internal.walkSourceFiles(cwd)) {\n const rel = relative(cwd, path);\n if (/\\.v2\\.[cm]?[jt]s$/.test(rel)) continue;\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch {\n continue;\n }\n if (!/\\b(?:ActorSheet|ItemSheet)\\b/.test(raw)) continue;\n // The generated file starts from the v14 rewrite of the source, so the bare\n // v13 aliases are already namespaced in it whether or not --write ran.\n const source = transformSource(raw).output;\n\n // First pass: which templates and nav selectors, so the tab ids can be read.\n let probe: ReturnType<typeof planSheetFile>;\n try {\n probe = planSheetFile(rel, source, { lang, tabIds: {} });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n notes.push(`${rel} could not be parsed and was skipped: ${reason}`);\n continue;\n }\n notes.push(...probe.notes);\n if (probe.files.length === 0) continue;\n let templatePaths = [...new Set(probe.files.flatMap((f) => f.templates))]\n .map((t) => localTemplate(cwd, t))\n .filter((t): t is string => t !== null);\n // A `get template()` that builds the path at runtime names nothing; every\n // sheet template in the project is a candidate then.\n if (templatePaths.length === 0) {\n const every = await allTemplates(cwd);\n // Leave out the other document's folder (item templates for an actor sheet and the\n // reverse); shared parts and dialogs stay in, since a sheet's rows often live there.\n const other =\n probe.files[0]?.base === 'BaseItemSheet' ? /(?:^|\\/)actors?\\//i : /(?:^|\\/)items?\\//i;\n templatePaths = every.filter((t) => !other.test(t));\n }\n const navSelectors = [...new Set(probe.files.flatMap((f) => f.tabNavSelectors))];\n const tabIds: Record<string, string[]> = {};\n for (const t of templatePaths) {\n const tpl = await readFile(join(cwd, t), 'utf8');\n for (const nav of navSelectors) {\n if (tabIds[nav]) continue;\n const ids = readTabIds(tpl, nav);\n if (ids.length > 0) tabIds[nav] = ids;\n }\n }\n\n const plan = planSheetFile(rel, source, { lang, tabIds });\n for (const f of plan.files) {\n const { source: out, ...rest } = f;\n files.push(rest);\n generated.set(f.to, out);\n notes.push(\n `Point registerSheet at ${f.className} from ${f.to} (a written key such as \"<id>.${f.base === 'BaseActorSheet' ? 'actor' : 'item'}\"), then delete the old class.`,\n );\n }\n const actions = plan.files.flatMap((f) =>\n f.actions.map((a) => ({ name: a.name, selector: a.selector })),\n );\n for (const t of templatePaths) {\n const tpl = await readFile(join(cwd, t), 'utf8');\n const r = editTemplate(tpl, { actions, navSelectors });\n // A template the class never touched (a dialog, a chat card) is not a sheet; its form is its own.\n if (r.edits.length === 0) continue;\n templates.push({ file: t, edits: r.edits, formRoot: r.formRoot });\n if (r.formRoot) {\n notes.push(\n `${t} opens with <form>; the SDK sheet already is one. Remove it once the old class is gone (audit rule 008).`,\n );\n }\n if (write && r.edits.length > 0) await writeFile(join(cwd, t), r.output, 'utf8');\n }\n }\n\n for (const [to, out] of generated) {\n const target = join(cwd, to);\n if (existsSync(target)) {\n notes.unshift(`${to} exists and was left alone.`);\n continue;\n }\n if (write) {\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, out, 'utf8');\n }\n }\n return { files, templates, notes: [...new Set(notes)] };\n}\n\n/** The report as text: one block per file, edits then notes. */\nexport function formatMigrateReport(report: MigrateReport): string {\n const lines: string[] = [];\n if (report.files.length === 0 && !report.dataModels && !report.sheets) {\n lines.push('Nothing to migrate. The project already reads as v14.');\n return `${lines.join('\\n')}\\n`;\n }\n if (report.files.length === 0) lines.push('Nothing to rewrite in the source or the manifest.');\n else {\n lines.push(\n report.written\n ? `Rewrote ${report.counts.changes} place(s) in ${report.counts.files} file(s).`\n : `Would rewrite ${report.counts.changes} place(s) in ${report.counts.files} file(s). Run again with --write to apply.`,\n );\n }\n for (const file of report.files) {\n lines.push('', `${file.file}`);\n for (const change of file.changes) {\n lines.push(\n ` ${change.line}: ${oneLine(change.before)}`,\n ` ${' '.repeat(String(change.line).length)} → ${oneLine(change.after)}`,\n );\n }\n for (const note of file.notes) {\n lines.push(` ${note.line}: needs a decision: ${note.message}`);\n }\n }\n if (report.counts.notes > 0) {\n lines.push(\n '',\n `${report.counts.notes} place(s) need a decision. Run \\`vttforge audit\\` after editing them.`,\n );\n }\n if (report.dataModels) {\n const dm = report.dataModels;\n lines.push(\n '',\n report.written\n ? `Wrote ${dm.files.length} data model file(s) from template.json:`\n : `Would write ${dm.files.length} data model file(s) from template.json:`,\n );\n for (const f of dm.files) lines.push(` ${f}`);\n if (Object.keys(dm.documentTypes).length > 0) {\n lines.push(\n '',\n 'Declare the types in the manifest:',\n ` \"documentTypes\": ${JSON.stringify(dm.documentTypes)}`,\n );\n }\n if (dm.registration)\n lines.push(\n '',\n 'Register the models at init:',\n ...dm.registration.split('\\n').map((l) => ` ${l}`),\n );\n for (const n of dm.notes) lines.push(` needs a decision: ${n}`);\n }\n if (report.sheets) {\n const s = report.sheets;\n const targets = [...new Set(s.files.map((f) => f.to))];\n lines.push(\n '',\n report.written\n ? `Wrote ${targets.length} sheet file(s) on the SDK bases:`\n : `Would write ${targets.length} sheet file(s) on the SDK bases:`,\n );\n for (const f of s.files) {\n lines.push(` ${f.to}: ${f.className} extends ${f.base}()`);\n for (const a of f.actions) lines.push(` action ${a.name} ← ${a.selector} (${a.method})`);\n for (const t of f.todos) lines.push(` ${t.line}: needs a decision: ${t.message}`);\n }\n if (s.templates.length > 0) {\n lines.push('', report.written ? 'Edited templates:' : 'Would edit templates:');\n for (const t of s.templates) {\n lines.push(` ${t.file}`);\n for (const e of t.edits) {\n lines.push(\n ` ${e.line}: ${oneLine(e.before)}`,\n ` ${' '.repeat(String(e.line).length)} → ${oneLine(e.after)}`,\n );\n }\n }\n }\n for (const n of s.notes) lines.push(` needs a decision: ${n}`);\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction oneLine(text: string): string {\n const flat = text.replace(/\\s+/g, ' ').trim();\n return flat.length > 100 ? `${flat.slice(0, 97)}...` : flat;\n}\n","/**\n * `vttforge migrate`: the CLI surface over the v13 → v14 rewrite.\n *\n * Exit codes:\n * 0: ran, whether or not anything changed\n * 1: the target is not a directory\n */\n\nimport { resolve } from 'node:path';\nimport { formatMigrateReport, type MigrateReport, runMigrate } from '../migrate/index.js';\n\nexport interface MigrateCommandOptions {\n cwd?: string;\n write?: boolean;\n json?: boolean;\n /** Also generate a data model per template.json type. */\n dataModels?: boolean;\n style?: 'plain' | 'sdk';\n lang?: 'js' | 'ts';\n /** Also generate a V2 sheet file per Application v1 sheet class. */\n sheets?: boolean;\n /** Custom writer (tests). Defaults to process.stdout.write. */\n out?: (chunk: string) => void;\n}\n\nexport async function runMigrateCommand(\n options: MigrateCommandOptions = {},\n): Promise<{ report: MigrateReport; exitCode: 0 | 1 }> {\n const cwd = resolve(options.cwd ?? process.cwd());\n const out =\n options.out ??\n ((chunk: string) => {\n process.stdout.write(chunk);\n });\n const report = await runMigrate({\n cwd,\n write: options.write === true,\n dataModels: options.dataModels === true,\n style: options.style,\n lang: options.lang,\n sheets: options.sheets === true,\n });\n out(options.json ? `${JSON.stringify(report, null, 2)}\\n` : formatMigrateReport(report));\n return { report, exitCode: 0 };\n}\n","/**\n * vttforge command tree.\n *\n * Kept apart from `bin.ts`, which only runs it. Argument definitions are the\n * CLI's contract with its users (`--no-install` skipping the install, an\n * alias resolving to its canonical name) and a module that calls `runMain`\n * on import cannot be reached by a test. Exporting the commands from here\n * lets the suite parse real argv against the real definitions.\n */\nimport { defineCommand } from 'citty';\nimport { runAuditCommand } from './commands/audit.js';\nimport { runBuild } from './commands/build.js';\nimport { runDev } from './commands/dev.js';\nimport { runInit, ScaffoldError } from './commands/init.js';\nimport { runLintCommand } from './commands/lint.js';\nimport { runMigrateCommand } from './commands/migrate.js';\nimport { VTTFORGE_CLI_VERSION } from './index.js';\n\nexport const init = defineCommand({\n meta: {\n name: 'init',\n description: 'Scaffold a new Foundry VTT system or module from a VTTForge template',\n },\n args: {\n name: {\n type: 'positional',\n description: 'Directory name for the new system/module (also the default manifest id)',\n required: false,\n },\n type: {\n type: 'string',\n description: 'Package type: system | module',\n },\n lang: {\n type: 'string',\n description: 'Language: ts | js',\n },\n id: {\n type: 'string',\n description: 'Manifest id (defaults to a slug of the directory name)',\n },\n title: {\n type: 'string',\n description: 'Human-readable title shown in Foundry setup screens',\n },\n description: {\n type: 'string',\n description: 'One-line description for the manifest',\n },\n author: {\n type: 'string',\n description: 'Author name for the manifest (defaults to the git author)',\n },\n license: {\n type: 'string',\n description: 'SPDX license id (default MIT)',\n },\n // Without a terminal there is nothing for a prompt to read, so it waits\n // forever. This flag takes the defaults instead, and the scaffolder\n // also assumes it when stdin is not a TTY, so CI need not pass it.\n yes: {\n type: 'boolean',\n alias: 'y',\n default: false,\n description: 'Accept defaults for anything not passed, without prompting',\n },\n // Citty parses `--no-X` as `args.X === false`, so define affirmative\n // flags with a true default. `--no-install` then yields `install: false`\n // which we forward as `noInstall: true`.\n install: {\n type: 'boolean',\n default: true,\n description: 'Install dependencies after scaffold (use --no-install to skip)',\n },\n git: {\n type: 'boolean',\n default: true,\n description: 'Initialize a git repository after scaffold (use --no-git to skip)',\n },\n },\n async run({ args }) {\n try {\n await runInit({\n name: typeof args.name === 'string' ? args.name : undefined,\n type: typeof args.type === 'string' ? (args.type as 'system' | 'module') : undefined,\n lang: typeof args.lang === 'string' ? (args.lang as 'ts' | 'js') : undefined,\n id: typeof args.id === 'string' ? args.id : undefined,\n title: typeof args.title === 'string' ? args.title : undefined,\n description: typeof args.description === 'string' ? args.description : undefined,\n author: typeof args.author === 'string' ? args.author : undefined,\n license: typeof args.license === 'string' ? args.license : undefined,\n yes: args.yes === true,\n noInstall: args.install === false,\n noGit: args.git === false,\n });\n } catch (err) {\n // ScaffoldError already surfaced its message via `p.cancel`; anything\n // else is a real crash worth showing. Either way the bin exits 1.\n if (!(err instanceof ScaffoldError)) {\n console.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n },\n});\n\nexport const dev = defineCommand({\n meta: {\n name: 'dev',\n description: 'Symlink dist/ into Foundry Data and run vite build --watch',\n },\n args: {\n 'foundry-data': {\n type: 'string',\n alias: 'data-dir',\n description:\n 'Override the Foundry user-data directory (skips env / config / first-run prompt)',\n },\n 'hmr-port': {\n type: 'string',\n description: 'Port for the hot reload bridge (default 31313)',\n },\n },\n async run({ args }) {\n // Citty surfaces aliases under the canonical name. Belt-and-suspenders:\n // accept either spelling so older docs and muscle memory keep working.\n const explicit =\n (typeof args['foundry-data'] === 'string' ? args['foundry-data'] : undefined) ??\n (typeof args['data-dir'] === 'string' ? args['data-dir'] : undefined);\n // A non-numeric port is the user's typo, not a reason to fall back to a\n // port they did not ask for. Say so and stop.\n const rawPort = typeof args['hmr-port'] === 'string' ? args['hmr-port'] : undefined;\n const hmrPort = rawPort === undefined ? undefined : Number(rawPort);\n if (hmrPort !== undefined && !Number.isInteger(hmrPort)) {\n console.error(`--hmr-port expects a whole number, got \\`${rawPort}\\`.`);\n process.exit(1);\n }\n try {\n await runDev({ dataDir: explicit, hmrPort });\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n },\n});\n\nexport const build = defineCommand({\n meta: {\n name: 'build',\n description: 'Run vite build (production) and emit <id>-<version>.zip for foundryvtt.com',\n },\n async run() {\n try {\n await runBuild();\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n },\n});\n\nexport const lint = defineCommand({\n meta: {\n name: 'lint',\n description: 'Run Biome (shipped with the CLI) over the project, then the v14 audit',\n },\n args: {\n path: {\n type: 'positional',\n description: 'Project root to lint (defaults to the current directory)',\n required: false,\n },\n fix: {\n type: 'boolean',\n default: false,\n description: 'Write the safe fixes and format the files instead of only reporting',\n },\n // Affirmative flag with a true default, so `--no-audit` parses as\n // `audit: false` (same pattern as `--no-install` on init).\n audit: {\n type: 'boolean',\n default: true,\n description: 'Run `vttforge audit` after Biome (use --no-audit to skip)',\n },\n strict: {\n type: 'boolean',\n default: false,\n description: 'For the audit: exit non-zero on any finding, not only HIGH',\n },\n },\n async run({ args }) {\n try {\n const result = await runLintCommand({\n cwd: typeof args.path === 'string' ? args.path : undefined,\n fix: args.fix === true,\n audit: args.audit !== false,\n strict: args.strict === true,\n });\n if (result.exitCode !== 0) process.exitCode = result.exitCode;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n },\n});\n\nexport const audit = defineCommand({\n meta: {\n name: 'audit',\n description:\n 'Scan a system/module project for the v14 manifest, source and template breakages that fail quietly',\n },\n args: {\n path: {\n type: 'positional',\n description: 'Project root to scan (defaults to the current directory)',\n required: false,\n },\n json: {\n type: 'boolean',\n default: false,\n description: 'Emit a machine-readable JSON report instead of markdown',\n },\n strict: {\n type: 'boolean',\n default: false,\n description: 'Exit non-zero on any finding (default: only HIGH triggers a non-zero exit)',\n },\n },\n async run({ args }) {\n try {\n const result = await runAuditCommand({\n cwd: typeof args.path === 'string' ? args.path : undefined,\n format: args.json === true ? 'json' : 'markdown',\n strict: args.strict === true,\n });\n // Set exitCode instead of calling process.exit so any pending stdout\n // writes (the JSON / markdown report) get flushed before the process\n // tears down. process.exit(1) would truncate large reports on the\n // exact runs CI needs them intact.\n if (result.exitCode !== 0) process.exitCode = result.exitCode;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n },\n});\n\nexport const migrate = defineCommand({\n meta: {\n name: 'migrate',\n description:\n 'Rewrite a v13 system or module for Foundry v14 (preview by default); --data-models and --sheets write the v16 replacements',\n },\n args: {\n path: {\n type: 'positional',\n description: 'Project root to rewrite (defaults to the current directory)',\n required: false,\n },\n write: {\n type: 'boolean',\n default: false,\n description: 'Write the edits. Without it, the command only reports what it would change',\n },\n json: {\n type: 'boolean',\n default: false,\n description: 'Emit the report as JSON',\n },\n 'data-models': {\n type: 'boolean',\n default: false,\n description:\n 'Also generate a data model per template.json type (template.json is deprecated since v14)',\n },\n style: {\n type: 'string',\n default: 'plain',\n description: 'For --data-models: \"plain\" Foundry classes, or \"sdk\" classes on @vttforge/core',\n },\n lang: {\n type: 'string',\n default: 'js',\n description: 'For --data-models and --sheets: \"js\" writes .mjs, \"ts\" writes .ts',\n },\n sheets: {\n type: 'boolean',\n default: false,\n description:\n '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',\n },\n },\n async run({ args }) {\n try {\n const { exitCode } = await runMigrateCommand({\n cwd: args.path ? String(args.path) : undefined,\n write: Boolean(args.write),\n json: Boolean(args.json),\n dataModels: Boolean(args['data-models']),\n style: String(args.style) === 'sdk' ? 'sdk' : 'plain',\n lang: String(args.lang) === 'ts' ? 'ts' : 'js',\n sheets: Boolean(args.sheets),\n });\n process.exitCode = exitCode;\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n },\n});\n\nexport const main = defineCommand({\n meta: {\n name: 'vttforge',\n version: VTTFORGE_CLI_VERSION,\n description:\n 'VTTForge CLI: scaffold, dev, build, lint, audit and migrate for Foundry v14+ systems and modules',\n },\n subCommands: {\n init,\n dev,\n build,\n lint,\n audit,\n migrate,\n },\n});\n","#!/usr/bin/env node\n/**\n * vttforge bin: the executable entry.\n *\n * Nothing but the launch. The command tree lives in `cli.ts` so tests can\n * import it without running the CLI.\n */\nimport { runMain } from 'citty';\nimport { main } from './cli.js';\n\nrunMain(main);\n"],"mappings":";;;;;;;;AAmDA,MAAM,iBAAiB;AAEvB,SAAS,SACP,KACA,OACA,MACA,OACA,QACQ;CACR,MAAM,OAAO,GAAG,OAAO;CACvB,IAAI,OAAO,UAAU,UAEnB,OAAO,sDADS,OAAO,UAAU,KACkC,IAAI,oBAAoB,GAAG,aAAa,MAAM;CAEnH,IAAI,OAAO,UAAU,WACnB,OAAO,kEAAkE,MAAM;CAEjF,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,UAAU,KAAK,UAAU,KAAK;EACpC,IAAI,eAAe,KAAK,GAAG,GACzB,OAAO,2DAA2D,QAAQ;EAC5E,OAAO,6DAA6D,QAAQ;CAC9E;CACA,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,QAAQ,MAAM;EACpB,IAAI,UAAU,KAAA,KAAc,OAAO,UAAU,YAAY,UAAU,MAAO;GACxE,IAAI,UAAU,KAAA,GACZ,MAAM,KACJ,GAAG,KAAK,8GACV;GACF,OAAO;EACT;EACA,OAAO,oBAAoB,SAAS,KAAK,OAAO,GAAG,KAAK,KAAK,OAAO,MAAM,EAAE;CAC9E;CACA,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,UAAU,OAAO,QAAQ,KAAgC;EAC/D,IAAI,QAAQ,WAAW,GAAG;GACxB,MAAM,KACJ,GAAG,KAAK,kGACV;GACA,OAAO;EACT;EAIA,OAAO,wBAHO,QACX,KAAK,CAAC,GAAG,OAAO,GAAG,OAAO,QAAQ,CAAC,EAAE,IAAI,SAAS,GAAG,GAAG,GAAG,KAAK,GAAG,KAAK,OAAO,IAAI,EAAE,EAAE,CAAC,CACxF,KAAK,IAC2B,EAAE,IAAI,OAAO;CAClD;CACA,MAAM,KAAK,GAAG,KAAK,mEAAmE;CACtF,OAAO;AACT;AAEA,SAAS,QAAQ,KAAqB;CACpC,OAAO,qBAAqB,K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;AAED,MAAa,UAAU,cAAc;CACnC,MAAM;EACJ,MAAM;EACN,aACE;CACJ;CACA,MAAM;EACJ,MAAM;GACJ,MAAM;GACN,aAAa;GACb,UAAU;EACZ;EACA,OAAO;GACL,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,MAAM;GACJ,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,eAAe;GACb,MAAM;GACN,SAAS;GACT,aACE;EACJ;EACA,OAAO;GACL,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,MAAM;GACJ,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,QAAQ;GACN,MAAM;GACN,SAAS;GACT,aACE;EACJ;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI;GACF,MAAM,EAAE,aAAa,MAAM,kBAAkB;IAC3C,KAAK,KAAK,OAAO,OAAO,KAAK,IAAI,IAAI,KAAA;IACrC,OAAO,QAAQ,KAAK,KAAK;IACzB,MAAM,QAAQ,KAAK,IAAI;IACvB,YAAY,QAAQ,KAAK,cAAc;IACvC,OAAO,OAAO,KAAK,KAAK,MAAM,QAAQ,QAAQ;IAC9C,MAAM,OAAO,KAAK,IAAI,MAAM,OAAO,OAAO;IAC1C,QAAQ,QAAQ,KAAK,MAAM;GAC7B,CAAC;GACD,QAAQ,WAAW;EACrB,SAAS,OAAO;GACd,QAAQ,OAAO,MAAM,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG;GAClF,QAAQ,WAAW;EACrB;CACF;AACF,CAAC;AAED,MAAa,OAAO,cAAc;CAChC,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aACE;CACJ;CACA,aAAa;EACX;EACA;EACA;EACA;EACA;EACA;CACF;AACF,CAAC;;;;;;;;;AC7TD,QAAQ,IAAI"}
1
+ {"version":3,"file":"bin.mjs","names":["pascal","camel"],"sources":["../src/migrate/data-models.ts","../src/migrate/sheet-templates.ts","../src/migrate/parse.ts","../src/migrate/sheet-bodies.ts","../src/migrate/sheet-listeners.ts","../src/migrate/sheet-options.ts","../src/migrate/sheets.ts","../src/migrate/transforms.ts","../src/migrate/index.ts","../src/commands/migrate.ts","../src/cli.ts","../src/bin.ts"],"sourcesContent":["/**\n * `template.json` → one data model per type.\n *\n * v14 deprecates `template.json` and removes it in v16; the replacement is a\n * `TypeDataModel` per type registered on `CONFIG.<Document>.dataModels`,\n * with the type names declared under `documentTypes` in the manifest. The\n * shape is already in the template: every default value says what field it\n * is, and every `templates` entry is a fragment several types share. This\n * reads that and writes the classes, so the move is a review of generated\n * code rather than a transcription.\n *\n * What is inferred, and what is guessed:\n * - a number is a `NumberField` (`integer` when the default is one), a\n * boolean a `BooleanField`, a string a `StringField` (`HTMLField` when the\n * key reads like rich text: description, biography, notes, details), an object a\n * `SchemaField`, an array an `ArrayField` of whatever its first element is\n * (`ObjectField` when it is empty or holds objects), `null` an\n * `ObjectField` marked for review.\n * - a `templates` fragment becomes a function returning a partial schema, so\n * each type's schema spreads the fragments it listed, in the order the\n * template listed them, then its own keys. Foundry's implicit `base`\n * template is skipped.\n */\n\nexport type EmitStyle = 'plain' | 'sdk';\n\ninterface DataModelFile {\n /** Project-relative path to write. */\n path: string;\n source: string;\n}\n\nexport interface DataModelPlan {\n files: DataModelFile[];\n /** The `documentTypes` block the manifest needs, per document. */\n documentTypes: Record<string, Record<string, Record<string, unknown>>>;\n /** The registration a system adds in `init`, as source text. */\n registration: string;\n /** Things the reader has to decide. */\n notes: string[];\n}\n\ninterface DocumentTemplate {\n types?: string[];\n templates?: Record<string, Record<string, unknown>>;\n htmlFields?: string[];\n filePathFields?: string[];\n gmOnlyFields?: string[];\n [type: string]: unknown;\n}\n\nconst RICH_TEXT_KEYS = /^(description|biography|bio|notes|details)$/i;\n\nfunction fieldFor(\n key: string,\n value: unknown,\n path: string,\n notes: string[],\n indent: string,\n): string {\n const next = `${indent} `;\n if (typeof value === 'number') {\n const integer = Number.isInteger(value);\n return `new f.NumberField({ required: true, nullable: false${integer ? ', integer: true' : ''}, initial: ${value} })`;\n }\n if (typeof value === 'boolean') {\n return `new f.BooleanField({ required: true, nullable: false, initial: ${value} })`;\n }\n if (typeof value === 'string') {\n const literal = JSON.stringify(value);\n if (RICH_TEXT_KEYS.test(key))\n return `new f.HTMLField({ required: true, blank: true, initial: ${literal} })`;\n return `new f.StringField({ required: true, blank: true, initial: ${literal} })`;\n }\n if (Array.isArray(value)) {\n const first = value[0];\n if (first === undefined || (typeof first === 'object' && first !== null)) {\n if (first === undefined)\n notes.push(\n `${path}: an empty array in the template; it is an ArrayField of ObjectField. Name the element's shape if it has one.`,\n );\n return 'new f.ArrayField(new f.ObjectField())';\n }\n return `new f.ArrayField(${fieldFor(key, first, `${path}[]`, notes, indent)})`;\n }\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) {\n notes.push(\n `${path}: an empty object in the template; it is an ObjectField. Give it a SchemaField if it has a shape.`,\n );\n return 'new f.ObjectField()';\n }\n const inner = entries\n .map(([k, v]) => `${next}${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, next)},`)\n .join('\\n');\n return `new f.SchemaField({\\n${inner}\\n${indent}})`;\n }\n notes.push(`${path}: null in the template; it is an ObjectField. Pick the real field.`);\n return 'new f.ObjectField()';\n}\n\nfunction safeKey(key: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(key) ? key : JSON.stringify(key);\n}\n\nfunction pascal(name: string): string {\n return name\n .replace(/(^|[^A-Za-z0-9])([a-z0-9])/g, (_m, _s, c: string) => c.toUpperCase())\n .replace(/[^A-Za-z0-9]/g, '');\n}\n\nfunction camel(name: string): string {\n const p = pascal(name);\n return p.charAt(0).toLowerCase() + p.slice(1);\n}\n\nfunction schemaBody(data: Record<string, unknown>, path: string, notes: string[]): string {\n return Object.entries(data)\n .filter(([k]) => k !== 'templates')\n .map(([k, v]) => ` ${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, ' ')},`)\n .join('\\n');\n}\n\nfunction header(style: EmitStyle): string {\n if (style === 'sdk') return \"import { BaseTypeDataModel, fields } from '@vttforge/core';\\n\";\n return '';\n}\n\nfunction fieldsLine(style: EmitStyle): string {\n return style === 'sdk' ? ' const f = fields();' : ' const f = foundry.data.fields;';\n}\n\nexport function planDataModels(\n template: Record<string, unknown>,\n {\n style = 'plain',\n lang = 'js',\n dir = 'scripts/data',\n }: { style?: EmitStyle; lang?: 'js' | 'ts'; dir?: string } = {},\n): DataModelPlan {\n const ext = lang === 'ts' ? 'ts' : 'mjs';\n const files: DataModelFile[] = [];\n const notes: string[] = [];\n const documentTypes: DataModelPlan['documentTypes'] = {};\n const registrations: string[] = [];\n\n for (const [document, raw] of Object.entries(template)) {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;\n const doc = raw as DocumentTemplate;\n const types = doc.types ?? [];\n const templates = doc.templates ?? {};\n const docDir = `${dir}/${document.toLowerCase()}`;\n\n // One fragment per template, so the sharing the template expressed is\n // kept, and a type that lists three fragments spreads three functions.\n const fragmentNames = Object.keys(templates);\n if (fragmentNames.length > 0) {\n const fns = fragmentNames\n .map((name) => {\n const body = schemaBody(templates[name] ?? {}, `${document}.templates.${name}`, notes);\n return `/** The \\`${name}\\` template, as the types that listed it spread it. */\\nexport function ${camel(name)}Fields(f) {\\n return {\\n${body}\\n };\\n}`;\n })\n .join('\\n\\n');\n const tsHint =\n lang === 'ts'\n ? '// @ts-nocheck: the field constructors are typed by the runtime, not by this file\\n'\n : '';\n files.push({\n path: `${docDir}/templates.${ext}`,\n 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`,\n });\n }\n\n documentTypes[document] = {};\n const modelNames: string[] = [];\n for (const type of types) {\n const own = (doc[type] ?? {}) as Record<string, unknown>;\n const listed = (own.templates as string[] | undefined) ?? [];\n for (const t of listed) {\n // Many files list a `base` the templates block never defines; that one is not worth a note.\n if (!(t in templates) && t !== 'base')\n notes.push(\n `${document}.${type}: lists template \"${t}\", which template.json does not define; it was skipped.`,\n );\n }\n const spreads = listed\n .filter((t) => t in templates)\n .map((t) => ` ...${camel(t)}Fields(f),`)\n .join('\\n');\n const body = schemaBody(own, `${document}.${type}`, notes);\n const className = `${pascal(type)}Data`;\n const importLine = listed.length\n ? `import { ${listed\n .filter((t) => t in templates)\n .map((t) => `${camel(t)}Fields`)\n .join(', ')} } from './templates.${ext === 'ts' ? 'js' : 'mjs'}';\\n`\n : '';\n const schemaFn = `${fieldsLine(style)}\\n return {\\n${[spreads, body].filter(Boolean).join('\\n')}\\n };`;\n const classSource =\n style === 'sdk'\n ? `${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`\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`;\n files.push({ path: `${docDir}/${type}-data.${ext}`, source: classSource });\n const meta: Record<string, unknown> = {};\n const html = (doc.htmlFields ?? []).filter(\n (k) => k in own || listed.some((t) => k in (templates[t] ?? {})),\n );\n if (html.length) meta.htmlFields = html;\n documentTypes[document][type] = meta;\n modelNames.push(`${type}: ${className}`);\n registrations.push(\n `import { ${className} } from './${docDir.replace(/^scripts\\//, '')}/${type}-data.${ext === 'ts' ? 'js' : 'mjs'}';`,\n );\n }\n if (types.length) {\n registrations.push(\n style === 'sdk'\n ? `// registerSystem({ ${document === 'Actor' ? 'actorDataModels' : document === 'Item' ? 'itemDataModels' : `${camel(document)}DataModels`}: { ${modelNames.join(', ')} } })`\n : `// Hooks.once('init', () => Object.assign(CONFIG.${document}.dataModels, { ${modelNames.join(', ')} }));`,\n );\n }\n }\n notes.push(\n \"When every type has a model, delete template.json: while it exists, Foundry resets each listed type's documentTypes entry on every start.\",\n );\n return { files, documentTypes, registration: registrations.join('\\n'), notes };\n}\n","/**\n * The template side of `migrate --sheets`: attribute insertions on opening\n * tags, nothing else. A V2 sheet finds its handlers by `data-action`, and the\n * SDK's tab action by `data-action=\"vttforgeTab\"` plus `data-group` on the\n * links and the panes. Handlebars blocks and expressions are left alone; only\n * literal `class` / `id` / `data-tab` attributes are matched, and a tab id\n * that is an expression is skipped when reading the ids.\n */\n\nexport interface TemplateEdit {\n line: number;\n before: string;\n after: string;\n}\n\nexport interface TemplateResult {\n output: string;\n edits: TemplateEdit[];\n formRoot: boolean;\n}\n\n/**\n * One opening tag: the name, the attribute run, and the self-closing slash.\n * Exactly three capture groups — `editTemplate` reads the replacer's `offset`\n * as the fourth argument, so a fourth group would shift every reported line.\n * A fresh regex per call: a shared global one carries `lastIndex` between\n * `readTabIds`, `elementRange` and `String#replace`.\n */\n// An opening tag: the name, then attributes and Handlebars mustaches (`{{#if x}}disabled{{/if}}`\n// sits inside a tag as an opaque token), then an optional self-closing slash.\nconst tagRe = () =>\n /<([a-zA-Z][\\w-]*)((?:\\s*\\{\\{[^{}]*\\}\\}|\\s+[^\\s=>/{]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+))?|(?<=\\}\\})[^\\s=>/{]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+))?)*)\\s*(\\/?)>/g;\n\n/** The value of one attribute in a tag's attribute run, or null when absent. */\nfunction attr(attrs: string, name: string): string | null {\n const m = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s>]+))`).exec(attrs);\n return m ? (m[1] ?? m[2] ?? m[3] ?? '') : null;\n}\n\nfunction hasClass(attrs: string, cls: string): boolean {\n return (attr(attrs, 'class') ?? '').split(/\\s+/).includes(cls);\n}\n\n/** Only `.class` and `#id` selectors match; anything else stays for `_onRender`. */\nfunction matches(attrs: string, selector: string): boolean {\n const m = /^([.#])([A-Za-z_][\\w-]*)/.exec(selector.trim());\n if (!m) {\n return false;\n }\n const [, kind = '', name = ''] = m;\n if (!name) {\n return false;\n }\n return kind === '.' ? hasClass(attrs, name) : attr(attrs, 'id') === name;\n}\n\nfunction lineOf(text: string, index: number): number {\n let n = 1;\n for (let i = 0; i < index; i += 1) {\n if (text[i] === '\\n') {\n n += 1;\n }\n }\n return n;\n}\n\n/**\n * Index range of the first element a selector opens, through its closing tag.\n * Depth-aware on the tag name, so a nested `<div>` inside the match does not\n * end it early.\n */\nfunction elementRange(template: string, selector: string): [number, number] | null {\n for (const m of template.matchAll(tagRe())) {\n const [whole, name, attrs = ''] = m;\n if (m.index === undefined || !name || !matches(attrs, selector)) {\n continue;\n }\n const open = new RegExp(`<${name}\\\\b`, 'g');\n const close = new RegExp(`</${name}\\\\s*>`, 'g');\n let depth = 1;\n let pos = m.index + whole.length;\n while (depth > 0) {\n open.lastIndex = pos;\n close.lastIndex = pos;\n const o = open.exec(template);\n const c = close.exec(template);\n if (!c) {\n return [m.index, template.length];\n }\n if (o && o.index < c.index) {\n depth += 1;\n pos = o.index + o[0].length;\n } else {\n depth -= 1;\n pos = c.index + c[0].length;\n }\n }\n return [m.index, pos];\n }\n return null;\n}\n\n/**\n * The `data-tab` values under a tabs nav, in document order. A value holding\n * an expression is skipped: its id is only known at render time.\n */\nexport function readTabIds(template: string, navSelector: string): string[] {\n const range = elementRange(template, navSelector);\n if (!range) {\n return [];\n }\n const nav = template.slice(range[0], range[1]);\n const ids: string[] = [];\n for (const m of nav.matchAll(tagRe())) {\n const id = attr(m[2] ?? '', 'data-tab');\n if (id && !id.includes('{{')) {\n ids.push(id);\n }\n }\n return ids;\n}\n\n/**\n * Add the attributes the generated sheet needs, and report each opening tag\n * that changed. Every other byte of the template is left where it was.\n */\nexport function editTemplate(\n template: string,\n opts: {\n actions: Array<{ name: string; selector: string }>;\n /** Only the first one is wired; the rest stay as they are. */\n navSelectors: string[];\n /** Tab ids of that first nav. A pane outside the list belongs to another group and is left alone. */\n tabIds?: string[];\n },\n): TemplateResult {\n const edits: TemplateEdit[] = [];\n const navRanges = opts.navSelectors\n .slice(0, 1)\n .map((selector) => elementRange(template, selector))\n .filter((range): range is [number, number] => range !== null);\n const inNav = (index: number) => navRanges.some(([start, end]) => index >= start && index < end);\n\n const output = template.replace(\n tagRe(),\n (whole: string, name: string, attrs: string, selfClose: string, offset: number) => {\n const add: string[] = [];\n const hasAction = attr(attrs, 'data-action') !== null;\n if (!hasAction) {\n for (const action of opts.actions) {\n if (matches(attrs, action.selector)) {\n add.push(`data-action=\"${action.name}\"`);\n break;\n }\n }\n }\n const tab = attr(attrs, 'data-tab');\n const needsGroup = attr(attrs, 'data-group') === null;\n let withClass = attrs;\n const isNavLink = tab !== null && inNav(offset);\n const isPane =\n tab !== null &&\n !isNavLink &&\n hasClass(attrs, 'tab') &&\n (opts.tabIds === undefined || opts.tabIds.includes(tab));\n if (isNavLink) {\n if (!hasAction && !add.some((one) => one.startsWith('data-action='))) {\n add.push('data-action=\"vttforgeTab\"');\n }\n if (needsGroup) {\n add.push('data-group=\"primary\"');\n }\n } else if (isPane && needsGroup) {\n add.push('data-group=\"primary\"');\n }\n // The active tab comes from the context: `{{tabs.<id>.cssClass}}` on the link and the pane.\n if (\n (isNavLink || isPane) &&\n tab !== null &&\n !tab.includes('{{') &&\n !/\\{\\{\\s*tabs\\./.test(attrs)\n ) {\n const marker = `{{tabs.${tab}.cssClass}}`;\n withClass = /\\sclass\\s*=\\s*\"([^\"]*)\"/.test(attrs)\n ? attrs.replace(\n /(\\sclass\\s*=\\s*\")([^\"]*)(\")/,\n (_m, open, value, close) => `${open}${value.trimEnd()} ${marker}${close}`,\n )\n : attrs;\n if (withClass === attrs) add.push(`class=\"${marker}\"`);\n }\n if (add.length === 0 && withClass === attrs) {\n return whole;\n }\n const after = `<${name}${withClass.replace(/\\s+$/, '')}${add.length > 0 ? ` ${add.join(' ')}` : ''}${selfClose ? ' /' : ''}>`;\n edits.push({ line: lineOf(template, offset), before: whole, after });\n return after;\n },\n );\n\n return { output, edits, formRoot: /^\\s*<form\\b/.test(template) };\n}\n","/**\n * The parse side of `migrate --sheets`: an AST for the class structure, and\n * the few lookups the planner needs. Bodies are never re-printed from the\n * tree; the planner slices the original text by node range.\n */\nimport { parse } from '@babel/parser';\nimport type { ClassDeclaration, ClassExpression, ClassMethod, File, Node } from '@babel/types';\n\ntype SheetBase = 'ActorSheet' | 'ItemSheet' | 'Application' | 'FormApplication';\n\nexport interface SheetClass {\n name: string;\n base: SheetBase;\n node: ClassDeclaration | ClassExpression;\n /** The `extends` expression as written. */\n superText: string;\n}\n\nconst CONVERTED = new Set<string>(['ActorSheet', 'ItemSheet', 'Application', 'FormApplication']);\nconst UNSUPPORTED = new Set(['Dialog', 'DocumentSheet']);\n\nexport function parseSource(source: string, lang: 'js' | 'ts'): File {\n return parse(source, {\n sourceType: 'module',\n errorRecovery: true,\n attachComment: false,\n plugins: lang === 'ts' ? ['typescript', 'decorators'] : ['decorators'],\n });\n}\n\nexport function text(source: string, node: Node): string {\n return source.slice(node.start ?? 0, node.end ?? 0);\n}\n\n/** Depth-first over every child node. Return `false` from `visit` to skip a subtree. */\nexport function walk(node: Node | null | undefined, visit: (n: Node) => undefined | false): void {\n if (!node || typeof node.type !== 'string') return;\n if (visit(node) === false) return;\n for (const key of Object.keys(node)) {\n if (key === 'loc' || key === 'leadingComments' || key === 'trailingComments') continue;\n const value = (node as unknown as Record<string, unknown>)[key];\n if (Array.isArray(value)) {\n for (const v of value) walk(v as Node, visit);\n } else if (value && typeof value === 'object' && 'type' in value) {\n walk(value as Node, visit);\n }\n }\n}\n\n/** `foundry.appv1.sheets.ActorSheet` → the leaf name, or the identifier itself. */\nfunction superName(cls: ClassDeclaration | ClassExpression): string | null {\n const s = cls.superClass;\n if (!s) return null;\n if (s.type === 'Identifier') return s.name;\n if (s.type === 'MemberExpression' && s.property.type === 'Identifier') return s.property.name;\n return null;\n}\n\ninterface NamedClass {\n name: string;\n node: ClassDeclaration | ClassExpression;\n}\n\nfunction classesOf(ast: File): NamedClass[] {\n const out: NamedClass[] = [];\n walk(ast.program, (n) => {\n if (n.type === 'ClassDeclaration') {\n out.push({ name: n.id?.name ?? '', node: n });\n return false;\n }\n if (n.type === 'ExportDefaultDeclaration' && n.declaration.type === 'ClassDeclaration') {\n const base = superName(n.declaration) ?? 'Sheet';\n out.push({ name: n.declaration.id?.name ?? `Default${base}`, node: n.declaration });\n return false;\n }\n if (\n n.type === 'VariableDeclarator' &&\n n.init?.type === 'ClassExpression' &&\n n.id.type === 'Identifier'\n ) {\n out.push({ name: n.id.name, node: n.init });\n return false;\n }\n return undefined;\n });\n return out;\n}\n\nexport function findSheetClasses(ast: File, source: string): SheetClass[] {\n const found: SheetClass[] = [];\n for (const { name, node } of classesOf(ast)) {\n const base = superName(node);\n if (!base || !CONVERTED.has(base) || !node.superClass) continue;\n found.push({ name, base: base as SheetBase, node, superText: text(source, node.superClass) });\n }\n return found;\n}\n\nexport function unsupportedBases(\n ast: File,\n source: string,\n): Array<{ name: string; superText: string; line: number }> {\n const out: Array<{ name: string; superText: string; line: number }> = [];\n for (const { name, node } of classesOf(ast)) {\n const base = superName(node);\n if (!base || !UNSUPPORTED.has(base) || !node.superClass) continue;\n out.push({ name, superText: text(source, node.superClass), line: node.loc?.start.line ?? 0 });\n }\n return out;\n}\n\nexport function methodOf(\n cls: ClassDeclaration | ClassExpression,\n name: string,\n opts: { static?: boolean; kind?: 'get' | 'method' } = {},\n): ClassMethod | null {\n for (const member of cls.body.body) {\n if (member.type !== 'ClassMethod') continue;\n if (member.key.type !== 'Identifier' || member.key.name !== name) continue;\n if (opts.static !== undefined && Boolean(member.static) !== opts.static) continue;\n if (opts.kind !== undefined && member.kind !== opts.kind) continue;\n return member;\n }\n return null;\n}\n","/**\n * Text rewrites applied to method bodies carried over from an Application v1\n * sheet. Each one is scoped to the slice the planner hands it, so a pattern\n * here never sees the rest of the file.\n *\n * Nothing is re-printed from a syntax tree: the bodies keep the author's\n * spacing and comments, and every rewrite is a replacement the reader can\n * find in the diff. What cannot be decided mechanically becomes a\n * `// TODO(migrate)` line above the code that needs the decision, and the\n * same message comes back in `todos` so the report can list it.\n */\n\nimport { MASK, maskComments } from '../audit/mask.js';\n\nexport interface Rewritten {\n code: string;\n /** One message per `// TODO(migrate)` line placed in `code`. */\n todos: string[];\n}\n\nexport const TODO = (msg: string): string => `// TODO(migrate): ${msg}`;\n\nconst esc = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nconst camel = (s: string) => s.replace(/-+(\\w)/g, (_m, c: string) => c.toUpperCase());\n\n/** Replace outside comments and strings; the mask keeps them out of reach. */\nfunction replaceCode(\n code: string,\n pattern: RegExp,\n replacement: (match: string, ...groups: string[]) => string,\n): string {\n const masked = maskComments(code, { strings: true });\n return code.replace(pattern, (match: string, ...rest: unknown[]) => {\n const offset = rest.find((r): r is number => typeof r === 'number') ?? 0;\n if (masked[offset] === MASK) return match;\n return replacement(match, ...rest.filter((r): r is string => typeof r === 'string'));\n });\n}\n\n/** Put a TODO line above the line that holds `index`. */\nfunction todoAt(code: string, index: number, msg: string): string {\n const lineStart = code.lastIndexOf('\\n', index - 1) + 1;\n const indent = /^[ \\t]*/.exec(code.slice(lineStart))?.[0] ?? '';\n return `${code.slice(0, lineStart)}${indent}${TODO(msg)}\\n${code.slice(lineStart)}`;\n}\n\n/** The jQuery calls with no one-to-one DOM rewrite. */\nconst LEFTOVER_JQUERY =\n /\\$\\(|\\.(?:val|text|html|prop|toggle|slideToggle|slideUp|slideDown|show|hide|addClass|removeClass|toggleClass|siblings|children|find|css|each)\\(/g;\n\nconst JQUERY_MSG = 'jQuery left here; use the DOM on `target` / `this.element`';\nconst ENRICH_MSG = 'enrichHTML returns a promise on v14; await it, and make this method async';\n\n/**\n * A handler body from `activateListeners`, with `event.currentTarget` folded\n * into the `target` the action receives and the jQuery data readers turned\n * into `dataset`.\n */\nexport function rewriteHandlerBody(\n body: string,\n eventParam: string | null,\n htmlParam: string | null,\n targetName = 'target',\n): Rewritten {\n const todos: string[] = [];\n let code = body;\n if (eventParam) {\n const ev = esc(eventParam);\n code = replaceCode(\n code,\n new RegExp(`\\\\$\\\\(\\\\s*${ev}\\\\.currentTarget\\\\s*\\\\)`, 'g'),\n () => targetName,\n );\n if (targetName !== `${eventParam}.currentTarget`) {\n code = replaceCode(code, new RegExp(`\\\\b${ev}\\\\.currentTarget\\\\b`, 'g'), () => targetName);\n }\n }\n code = replaceCode(\n code,\n /\\.data\\(\\s*(['\"])([\\w-]+)\\1\\s*\\)/g,\n (_m, _q, key) => `.dataset.${camel(key)}`,\n );\n code = replaceCode(\n code,\n /\\.attr\\(\\s*(['\"])data-([\\w-]+)\\1\\s*\\)/g,\n (_m, _q, key) => `.dataset.${camel(key)}`,\n );\n // jQuery's `parents(sel)` is read for its nearest match everywhere a sheet uses it.\n code = replaceCode(code, /\\.parents\\(/g, () => '.closest(');\n if (htmlParam) {\n code = replaceCode(\n code,\n new RegExp(`\\\\b${esc(htmlParam)}\\\\.find\\\\(`, 'g'),\n () => 'this.element.querySelectorAll(',\n );\n }\n // enrichHTML is always async on v14; the option is gone.\n code = replaceCode(code, /,\\s*\\{\\s*async:\\s*true\\s*\\}\\s*\\)/g, () => ')');\n code = replaceCode(code, /\\basync:\\s*true\\s*,\\s*/g, () => '');\n code = replaceCode(code, /,\\s*async:\\s*true\\b/g, () => '');\n // The sync form returned a string; on v14 it returns a promise, and this body may not be async.\n if (/\\basync:\\s*false\\b/.test(code)) {\n code = replaceCode(code, /,\\s*\\{\\s*async:\\s*false\\s*\\}\\s*\\)/g, () => ')');\n code = replaceCode(code, /\\basync:\\s*false\\s*,\\s*/g, () => '');\n code = replaceCode(code, /,\\s*async:\\s*false\\b/g, () => '');\n todos.push(ENRICH_MSG);\n code = todoAt(code, code.indexOf('{') + 1, ENRICH_MSG);\n }\n // `this.element` was jQuery on v1 and is an HTMLElement on V2.\n // A jQuery collection reads as a NodeList: `.length`, `[0]` and `forEach` keep working.\n code = replaceCode(code, /this\\.element\\.find\\(/g, () => 'this.element.querySelectorAll(');\n // What is left of jQuery gets a marker, once per line however much it holds.\n const masked = maskComments(code, { strings: true });\n const lines = new Set<number>();\n for (const m of code.matchAll(LEFTOVER_JQUERY)) {\n const at = m.index ?? 0;\n if (masked[at] === MASK) continue;\n lines.add(code.lastIndexOf('\\n', at - 1) + 1);\n }\n for (const lineStart of [...lines].sort((a, b) => b - a)) {\n code = todoAt(code, lineStart, JQUERY_MSG);\n todos.unshift(JQUERY_MSG);\n }\n return { code, todos };\n}\n\n/**\n * `getData()` becomes `_prepareContext(options)`. V2 hands back a much\n * smaller context, so the keys a v1 body expects to already be there are\n * assigned right after the `super` call — unless the method assigns them\n * itself without reading the old value first.\n */\nexport function rewriteGetData(\n methodText: string,\n base: 'ActorSheet' | 'ItemSheet' | 'Application' | 'FormApplication',\n opts: { usesObject?: boolean } = {},\n): Rewritten {\n const todos: string[] = [];\n const sig = /^(\\s*)(async\\s+)?getData\\s*\\(([^)]*)\\)/.exec(methodText);\n const params = sig?.[3]?.trim() ?? '';\n let code = methodText.replace(\n /^(\\s*)(async\\s+)?getData\\s*\\(([^)]*)\\)/,\n (_m, indent: string) => `${indent}async _prepareContext(options)`,\n );\n code = replaceCode(code, /super\\.getData\\(\\s*[^)]*\\)/g, () => 'super._prepareContext(options)');\n // getData was sync; _prepareContext is not, and this method is async now.\n code = replaceCode(\n code,\n /(?<!await\\s)super\\._prepareContext\\(options\\)/g,\n () => 'await super._prepareContext(options)',\n );\n // enrichHTML always returns a promise on v14, so the sync form must be awaited.\n code = replaceCode(code, /,\\s*\\{\\s*async:\\s*false\\s*\\}\\s*\\)/g, () => ')');\n code = replaceCode(code, /\\basync:\\s*false\\s*,\\s*/g, () => '');\n code = replaceCode(code, /,\\s*async:\\s*false\\b/g, () => '');\n code = replaceCode(\n code,\n /(?<!await\\s)(?<![\\w$.])(?:[\\w$]+\\.)*enrichHTML\\(/g,\n (call) => `await ${call}`,\n );\n\n // The variable that received super's result.\n const varMatch =\n /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:await\\s+)?super\\._prepareContext\\(options\\)\\s*;/.exec(code);\n const v = varMatch?.[1] ?? 'context';\n const isSheet = base === 'ActorSheet' || base === 'ItemSheet';\n const own = base === 'ActorSheet' ? 'actor' : 'item';\n // What v1's getData handed the template and V2's _prepareContext does not:\n // the document under its own name and as `data`, its system, the items,\n // and the two flags every v1 template gates on. An Application had none of\n // that; a FormApplication had `object`.\n const wanted: Array<[string, string]> = isSheet\n ? [\n [own, `${v}.${own} = this.document;`],\n ['data', `${v}.data = this.document;`],\n ['system', `${v}.system = this.document.system;`],\n ]\n : base === 'FormApplication' && opts.usesObject === true\n ? [['object', `${v}.object = this.object;`]]\n : [];\n if (base === 'ActorSheet') wanted.push(['items', `${v}.items = [...this.document.items];`]);\n if (isSheet) {\n wanted.push(\n ['editable', `${v}.editable = this.isEditable;`],\n ['owner', `${v}.owner = this.document.isOwner;`],\n );\n }\n\n const masked = maskComments(code, { strings: true });\n const inject = wanted\n .filter(([key]) => {\n const assigned = new RegExp(`\\\\b${esc(v)}\\\\.${key}\\\\s*=(?!=)`).test(masked);\n const read = new RegExp(`\\\\b${esc(v)}\\\\.${key}\\\\b(?!\\\\s*=(?!=))`).test(masked);\n return !assigned || read;\n })\n .map(([, line]) => line);\n\n if (varMatch) {\n const at = varMatch.index + varMatch[0].length;\n const indent =\n /^[ \\t]*/.exec(code.slice(code.lastIndexOf('\\n', varMatch.index) + 1))?.[0] ?? ' ';\n code = `${code.slice(0, at)}${inject.map((l) => `\\n${indent}${l}`).join('')}${code.slice(at)}`;\n } else if (inject.length > 0) {\n const msg = `set ${inject.join(' ')} on the context before returning it`;\n code = todoAt(code, code.indexOf('{') + 1, msg);\n todos.push(msg);\n }\n\n if (params !== '' && params !== 'options') {\n const msg = `\\`getData(${params})\\` took its own parameters; \\`_prepareContext(options)\\` does not. Read what the body needs from \\`options\\` or \\`this.document\\``;\n code = todoAt(code, code.indexOf('{') + 1, msg);\n todos.push(msg);\n }\n return { code, todos };\n}\n\n/**\n * `_onDropItem(event, data)` becomes `onDropItem(item, event)`: the SDK base\n * resolves the dropped document before it calls the hook, so the raw drop\n * payload the v1 body read is gone.\n */\n/**\n * `_updateObject(event, formData)` becomes the static form handler ApplicationV2\n * calls with `(event, form, formData)`; `formData.object` is the flat form\n * data, expanded here so the body reads it the way v1 handed it.\n */\nexport function rewriteUpdateObject(methodText: string): Rewritten {\n // Parameters may carry TypeScript annotations; the return type may sit before the brace.\n const sig =\n /^(\\s*)(async\\s+)?_updateObject\\s*\\(\\s*(\\w+)?(?:\\s*:\\s*(?:[^,)<]|<[^>]*>)*)?\\s*,?\\s*(\\w+)?(?:\\s*:\\s*(?:[^,)<]|<[^>]*>)*)?\\s*\\)\\s*(?::[^{]*)?\\{/.exec(\n methodText,\n );\n if (!sig) return { code: methodText, todos: [] };\n const indent = sig[1] ?? '';\n const eventName = sig[3] || 'event';\n const dataName = sig[4] || 'data';\n // The V2 handler receives a FormDataExtended; the body expects the expanded object the\n // v1 hook got, under the name it used. When that name is `formData`, the parameter moves aside.\n const param = dataName === 'formData' ? 'submission' : 'formData';\n const head = `${indent}static async formHandler(${eventName}, form, ${param}) {`;\n const first = `\\n${indent} const ${dataName} = foundry.utils.expandObject(${param}.object);`;\n const code = `${head}${first}${methodText.slice(sig[0].length)}`;\n const msg =\n 'this was _updateObject; ApplicationV2 calls the form handler with `this` bound to the app, and the flat form data is `formData.object`';\n return { code: todoAt(code, code.indexOf('{') + 1, msg), todos: [msg] };\n}\n\nexport function rewriteDropMethod(methodText: string, which: 'Item' | 'Actor'): Rewritten {\n const lower = which.toLowerCase();\n const sig = new RegExp(`_onDrop${which}\\\\s*\\\\(\\\\s*(\\\\w+)\\\\s*,\\\\s*(\\\\w+)\\\\s*\\\\)`);\n const m = sig.exec(methodText);\n if (!m) return { code: methodText, todos: [] };\n const eventName = m[1] ?? 'event';\n const dataName = m[2] ?? 'data';\n // The body may already declare `item` / `actor`; the parameter then takes another name.\n const declares = new RegExp(\n `\\\\b(?:const|let|var)\\\\s+(?:${lower}\\\\b|\\\\{[^}]*\\\\b${lower}\\\\b[^}]*\\\\}|\\\\[[^\\\\]]*\\\\b${lower}\\\\b[^\\\\]]*\\\\])`,\n ).test(methodText);\n const param = declares ? `dropped${which}` : lower;\n let code = methodText.replace(sig, `onDrop${which}(${param}, ${eventName})`);\n const todos: string[] = [];\n if (which === 'Item') {\n // v1's super created the item on the actor and returned the created documents.\n code = replaceCode(\n code,\n /super\\._onDropItem\\([^)]*\\)/g,\n () => `this.document.createEmbeddedDocuments('Item', [${param}.toObject()])`,\n );\n } else {\n code = replaceCode(\n code,\n new RegExp(`super\\\\._onDrop${which}\\\\([^)]*\\\\)`, 'g'),\n () => `super.onDrop${which}(${param}, ${eventName})`,\n );\n }\n // The v1 body read the drag payload; the resolved document reproduces it.\n code = replaceCode(\n code,\n new RegExp(`\\\\b${esc(dataName)}\\\\b`, 'g'),\n () => `${param}.toDragData()`,\n );\n const msg =\n which === 'Item'\n ? `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`\n : `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`;\n code = todoAt(code, code.indexOf('{') + 1, msg);\n todos.push(msg);\n return { code, todos };\n}\n\n/** `Dialog.confirm({ ... })`: the options literal is group 1. Non-greedy, so a nested `}` ends it early; `balanced` catches that. */\nconst CONFIRM_CALL = /\\bDialog\\.confirm\\(\\s*\\{([\\s\\S]*?)\\}\\s*\\)/g;\nconst NEW_DIALOG = /\\bnew\\s+Dialog\\s*\\(/g;\nconst UNREADABLE_MSG =\n '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';\nconst NEW_DIALOG_MSG =\n 'Dialog v1 (removed in v16); rebuild with DialogV2.prompt / DialogV2.wait, buttons as { action, label, callback }';\n\n/** Whether every bracket opened in `text` (outside strings and comments) is closed. */\nfunction balanced(text: string): boolean {\n const masked = maskComments(text, { strings: true });\n const pairs = new Map<string, string>([\n [')', '('],\n [']', '['],\n ['}', '{'],\n ]);\n const stack: string[] = [];\n for (let i = 0; i < masked.length; i += 1) {\n const ch = masked[i];\n if (ch === undefined || ch === MASK) continue;\n if (ch === '(' || ch === '[' || ch === '{') stack.push(ch);\n else if (pairs.has(ch)) {\n if (stack.pop() !== pairs.get(ch)) return false;\n }\n }\n return stack.length === 0;\n}\n\n/** The top-level `key: value` pairs of an object literal's inner text. */\nfunction topLevelPairs(inner: string): Array<{ key: string; value: string; spread: boolean }> {\n const masked = maskComments(inner, { strings: true });\n const pairs: Array<{ key: string; value: string; spread: boolean }> = [];\n let depth = 0;\n let start = 0;\n const flush = (end: number) => {\n const raw = inner.slice(start, end).trim();\n if (!raw) return;\n if (raw.startsWith('...')) {\n pairs.push({ key: raw, value: '', spread: true });\n return;\n }\n const colon = raw.indexOf(':');\n if (colon === -1) {\n pairs.push({ key: raw, value: raw, spread: false });\n return;\n }\n pairs.push({\n key: raw.slice(0, colon).trim(),\n value: raw.slice(colon + 1).trim(),\n spread: false,\n });\n };\n for (let i = 0; i < masked.length; i += 1) {\n const ch = masked[i];\n if (ch === MASK) continue;\n if (ch === '(' || ch === '[' || ch === '{') depth += 1;\n else if (ch === ')' || ch === ']' || ch === '}') depth -= 1;\n else if (ch === ',' && depth === 0) {\n flush(i);\n start = i + 1;\n }\n }\n flush(inner.length);\n return pairs;\n}\n\n/**\n * The DialogV2.confirm call for a Dialog.confirm options literal, or `null`\n * when the literal could not be read. `missing` names what the rewrite left\n * behind (a spread, an option with no V2 slot). `defaultYes` is dropped on\n * purpose: DialogV2 has no equivalent.\n */\nfunction readConfirmOptions(inner: string): { code: string | null; missing: string[] } {\n if (!balanced(inner)) return { code: null, missing: [] };\n const missing: string[] = [];\n const found: Record<string, string> = {};\n for (const pair of topLevelPairs(inner)) {\n if (pair.spread) {\n missing.push(`the spread ${pair.key}`);\n continue;\n }\n const key = pair.key.replace(/^['\"]|['\"]$/g, '');\n if (key === 'title' || key === 'content' || key === 'yes' || key === 'no')\n found[key] = pair.value;\n else if (key === 'rejectClose') found.rejectClose = pair.value;\n else if (key !== 'defaultYes' && key !== 'options') missing.push(key);\n }\n const parts = [\n found.title ? `window: { title: ${found.title} }` : '',\n found.content ? `content: ${found.content}` : '',\n found.yes\n ? `yes: { callback: ${v2Callback(found.yes, 'event, button, dialog', 'dialog.element')} }`\n : '',\n found.no\n ? `no: { callback: ${v2Callback(found.no, 'event, button, dialog', 'dialog.element')} }`\n : '',\n found.rejectClose ? `rejectClose: ${found.rejectClose}` : '',\n ].filter(Boolean);\n return { code: `DialogV2.confirm({ ${parts.join(', ')} })`, missing };\n}\n\n/** Index just past the `)` that closes the call opened at `open` (which must point at `(`), or -1. */\nfunction closingParen(text: string, open: number): number {\n const masked = maskComments(text, { strings: true });\n let depth = 0;\n for (let i = open; i < masked.length; i += 1) {\n const ch = masked[i];\n if (ch === MASK) continue;\n if (ch === '(' || ch === '[' || ch === '{') depth += 1;\n else if (ch === ')' || ch === ']' || ch === '}') {\n depth -= 1;\n if (depth === 0) return i + 1;\n }\n }\n return -1;\n}\n\n/** Strip one pair of outer braces from an object literal's text. */\nfunction innerOf(objectText: string): string | null {\n const t = objectText.trim();\n if (!t.startsWith('{') || !t.endsWith('}')) return null;\n return t.slice(1, -1);\n}\n\n/** `'<i class=\"fas fa-check\"></i>'` → `'fas fa-check'`; anything else stays. */\nfunction iconClass(value: string): string {\n const m = /<i\\s+class=([\"'])([^\"']+)\\1/.exec(value);\n if (!m) return value;\n const q = value.trim().startsWith('\"') ? '\"' : \"'\";\n return `${q}${m[2]}${q}`;\n}\n\n/**\n * A v1 dialog callback `(html) => ...` on the V2 signature. `html` was the\n * dialog's jQuery content; V2 hands `(event, button, dialog)`, so `html[0]`\n * is `dialog.element` and `html.find(sel)` is a query on it.\n */\nfunction v2Callback(fn: string, signature: string, elementExpr: string): string {\n const arrow = /^(async\\s+)?\\(?\\s*([\\w$]*)\\s*\\)?\\s*=>/.exec(fn.trim());\n const classic = /^(async\\s+)?function\\s*\\(\\s*([\\w$]*)\\s*\\)/.exec(fn.trim());\n const m = arrow ?? classic;\n if (!m) return fn;\n const param = m[2] ?? '';\n const head = arrow ? `${m[1] ?? ''}(${signature}) =>` : `${m[1] ?? ''}function (${signature})`;\n let body = fn.trim().slice(m[0].length);\n if (param) {\n const p = esc(param);\n body = replaceCode(body, new RegExp(`\\\\b${p}\\\\[0\\\\]`, 'g'), () => elementExpr);\n // A dialog callback reads single fields (`html.find(sel).val()`), so one element, not a list;\n // the sheet handlers keep the list because `.length` and `[0]` are what they read.\n body = replaceCode(\n body,\n new RegExp(`\\\\b${p}\\\\.find\\\\(`, 'g'),\n () => `${elementExpr}.querySelector(`,\n );\n body = replaceCode(body, new RegExp(`\\\\$\\\\(\\\\s*${p}\\\\s*\\\\)`, 'g'), () => elementExpr);\n // Every other use of the parameter, except as an object key (`{ html: x }`, `, html: x`).\n body = replaceCode(\n body,\n new RegExp(`(?<![{,]\\\\s*)\\\\b${p}\\\\b|\\\\b${p}\\\\b(?!\\\\s*:)`, 'g'),\n () => elementExpr,\n );\n }\n body = replaceCode(body, /\\.val\\(\\)/g, () => '.value');\n return `${head}${body}`;\n}\n\nconst NEW_DIALOG_WAIT_NOTE =\n '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';\n\ninterface DialogRead {\n code: string;\n missing: string[];\n}\n\n/** `new Dialog({...})` options → the `DialogV2.wait({...})` call, or null when unreadable. */\nfunction readDialogOptions(inner: string, indent: string): DialogRead | null {\n if (!balanced(inner)) return null;\n const missing: string[] = [];\n const found: Record<string, string> = {};\n for (const pair of topLevelPairs(inner)) {\n if (pair.spread) {\n missing.push(`the spread ${pair.key}`);\n continue;\n }\n const key = pair.key.replace(/^['\"]|['\"]$/g, '');\n if (['title', 'content', 'buttons', 'default', 'render', 'close'].includes(key))\n found[key] = pair.value;\n else missing.push(key);\n }\n const pad = `${indent} `;\n const parts: string[] = [];\n if (found.title) parts.push(`window: { title: ${found.title} }`);\n if (found.content) parts.push(`content: ${found.content}`);\n if (found.buttons) {\n const buttonsInner = innerOf(found.buttons);\n if (buttonsInner === null || !balanced(buttonsInner)) return null;\n const defaultKey = found.default?.replace(/^['\"]|['\"]$/g, '');\n const buttons: string[] = [];\n for (const b of topLevelPairs(buttonsInner)) {\n if (b.spread) {\n missing.push(`the spread ${b.key} in buttons`);\n continue;\n }\n const action = b.key.replace(/^['\"]|['\"]$/g, '');\n const fields = innerOf(b.value);\n if (fields === null) {\n missing.push(`button ${action}`);\n continue;\n }\n const entry: string[] = [`action: '${action}'`];\n for (const f of topLevelPairs(fields)) {\n const k = f.key.replace(/^['\"]|['\"]$/g, '');\n if (k === 'icon') entry.push(`icon: ${iconClass(f.value)}`);\n else if (k === 'label') entry.push(`label: ${f.value}`);\n else if (k === 'callback')\n entry.push(`callback: ${v2Callback(f.value, 'event, button, dialog', 'dialog.element')}`);\n else missing.push(`button ${action}.${k}`);\n }\n if (defaultKey && defaultKey === action) entry.push('default: true');\n buttons.push(`${pad} { ${entry.join(', ')} },`);\n }\n parts.push(`buttons: [\\n${buttons.join('\\n')}\\n${pad}]`);\n }\n if (!found.buttons) missing.push('buttons (DialogV2 needs at least one; add an ok button)');\n if (found.render)\n parts.push(`render: ${v2Callback(found.render, 'event, dialog', 'dialog.element')}`);\n if (found.close)\n parts.push(`close: ${v2Callback(found.close, 'event, dialog', 'dialog.element')}`);\n const code = `DialogV2.wait({\\n${parts.map((p) => `${pad}${p},`).join('\\n')}\\n${indent}})`;\n return { code, missing };\n}\n\n/** `Dialog.prompt({...})` options → `DialogV2.prompt({...})`, or null when unreadable. */\nfunction readPromptOptions(inner: string): DialogRead | null {\n if (!balanced(inner)) return null;\n const missing: string[] = [];\n const found: Record<string, string> = {};\n for (const pair of topLevelPairs(inner)) {\n if (pair.spread) {\n missing.push(`the spread ${pair.key}`);\n continue;\n }\n const key = pair.key.replace(/^['\"]|['\"]$/g, '');\n if (['title', 'content', 'label', 'callback', 'rejectClose'].includes(key))\n found[key] = pair.value;\n else missing.push(key);\n }\n const parts: string[] = [];\n if (found.title) parts.push(`window: { title: ${found.title} }`);\n if (found.content) parts.push(`content: ${found.content}`);\n const ok: string[] = [];\n if (found.label) ok.push(`label: ${found.label}`);\n if (found.callback)\n ok.push(`callback: ${v2Callback(found.callback, 'event, button, dialog', 'dialog.element')}`);\n if (ok.length > 0) parts.push(`ok: { ${ok.join(', ')} }`);\n if (found.rejectClose) parts.push(`rejectClose: ${found.rejectClose}`);\n return { code: `DialogV2.prompt({ ${parts.join(', ')} })`, missing };\n}\n\n/**\n * Replace each `<pattern>({...}[, more])` whose first argument is a readable\n * object literal; leave the rest as written with a TODO above it.\n */\nfunction rewriteCalls(\n code: string,\n pattern: RegExp,\n read: (inner: string, indent: string) => DialogRead | null,\n label: string,\n todos: string[],\n): string {\n const masked = maskComments(code, { strings: true });\n const hits: Array<{\n start: number;\n end: number;\n read: DialogRead | null;\n trailingRender: boolean;\n }> = [];\n for (const m of code.matchAll(pattern)) {\n const start = m.index ?? 0;\n if (masked[start] === MASK) continue;\n const open = start + m[0].length - 1;\n const end = closingParen(code, open);\n if (end === -1) continue;\n const args = code.slice(open + 1, end - 1);\n // The first argument is the options literal; anything after its closing brace is a second one.\n const firstBrace = args.indexOf('{');\n const firstEnd = firstBrace === -1 ? -1 : closingParen(args, firstBrace);\n const argsInner =\n firstEnd === -1 || args.slice(0, firstBrace).trim() !== ''\n ? null\n : innerOf(args.slice(firstBrace, firstEnd));\n const secondArg = firstEnd !== -1 && /^\\s*,\\s*\\S/.test(args.slice(firstEnd));\n const lineStart = code.lastIndexOf('\\n', start - 1) + 1;\n const indent = /^[ \\t]*/.exec(code.slice(lineStart))?.[0] ?? '';\n const result = argsInner === null ? null : read(argsInner, indent);\n if (result && secondArg) result.missing.push('the second argument (the Application options)');\n let renderEnd = end;\n let trailingRender = false;\n const after = /^\\s*\\.render\\((?:true)?\\)/.exec(code.slice(end));\n if (after) {\n renderEnd = end + after[0].length;\n trailingRender = true;\n }\n hits.push({ start, end: renderEnd, read: result, trailingRender });\n }\n let out = code;\n for (const hit of hits.reverse()) {\n if (hit.read === null) {\n out = todoAt(\n out,\n hit.start,\n `${label} here could not be read; rewrite it on DialogV2 by hand (${NEW_DIALOG_MSG})`,\n );\n todos.unshift(\n `${label} here could not be read; rewrite it on DialogV2 by hand (${NEW_DIALOG_MSG})`,\n );\n continue;\n }\n out = `${out.slice(0, hit.start)}${hit.read.code}${out.slice(hit.end)}`;\n if (hit.read.missing.length > 0) {\n const msg = `${label} options left behind: ${hit.read.missing.join(', ')}; move them onto the DialogV2 call by hand`;\n out = todoAt(out, hit.start, msg);\n todos.unshift(msg);\n }\n if (label === 'new Dialog' && !hit.trailingRender) {\n out = todoAt(out, hit.start, NEW_DIALOG_WAIT_NOTE);\n todos.unshift(NEW_DIALOG_WAIT_NOTE);\n }\n }\n return out;\n}\n\nexport function rewriteDialogs(code: string): Rewritten {\n const todos: string[] = [];\n const confirmMask = maskComments(code, { strings: true });\n const hits: Array<{ start: number; end: number; code: string | null; missing: string[] }> = [];\n for (const m of code.matchAll(CONFIRM_CALL)) {\n const start = m.index ?? 0;\n if (confirmMask[start] === MASK) continue;\n const read = readConfirmOptions(m[1] ?? '');\n hits.push({ start, end: start + m[0].length, code: read.code, missing: read.missing });\n }\n\n let out = code;\n for (const hit of hits.reverse()) {\n if (hit.code !== null) out = `${out.slice(0, hit.start)}${hit.code}${out.slice(hit.end)}`;\n if (hit.code === null) {\n out = todoAt(out, hit.start, UNREADABLE_MSG);\n todos.unshift(UNREADABLE_MSG);\n } else if (hit.missing.length > 0) {\n const msg = `Dialog.confirm options left behind: ${hit.missing.join(', ')}; move them onto the DialogV2.confirm call by hand`;\n out = todoAt(out, hit.start, msg);\n todos.unshift(msg);\n }\n }\n\n // Dialog.prompt({...}) → DialogV2.prompt({...})\n out = rewriteCalls(\n out,\n /\\bDialog\\.prompt\\s*\\(/g,\n (inner) => readPromptOptions(inner),\n 'Dialog.prompt',\n todos,\n );\n // new Dialog({...}).render(true) → DialogV2.wait({...})\n out = rewriteCalls(\n out,\n NEW_DIALOG,\n (inner, indent) => readDialogOptions(inner, indent),\n 'new Dialog',\n todos,\n );\n return { code: out, todos };\n}\n","/**\n * `activateListeners(html)` → `actions` and `_onRender` listeners.\n *\n * A click bound through `html.find(SEL).click(H)` (or `.on('click', H)`)\n * becomes an action named after the selector's first class or id. A bound\n * method stays a method; an arrow that only forwards to a method is that\n * method; any other function becomes a new method. Other events keep a real\n * listener, added in `_onRender`. What does not fit either shape is listed.\n */\nimport type { Expression, Node, Statement } from '@babel/types';\nimport { methodOf, type SheetClass, text } from './parse.js';\n\nexport interface ActionBinding {\n name: string;\n selector: string;\n kind: 'method' | 'inline';\n method: string | null;\n param: string | null;\n body: string | null;\n isAsync: boolean;\n}\n\ninterface ListenerBinding {\n selector: string;\n event: string;\n handlerText: string;\n}\n\nexport interface Listeners {\n actions: ActionBinding[];\n listeners: ListenerBinding[];\n leftovers: Array<{ line: number; text: string }>;\n /** The name `activateListeners` gave its jQuery root (`html` by convention). */\n htmlParam: string;\n}\n\nconst EVENTS = new Set([\n 'click',\n 'dblclick',\n 'change',\n 'contextmenu',\n 'input',\n 'keydown',\n 'keyup',\n 'focus',\n 'blur',\n 'mouseenter',\n 'mouseleave',\n 'submit',\n]);\n\nconst FIRST_CLASS_OR_ID = /[.#]([A-Za-z_][\\w-]*)/;\nconst SEPARATOR = /[-_]+(\\w)/g;\n\nexport function actionName(selector: string, taken: Set<string>): string | null {\n const match = FIRST_CLASS_OR_ID.exec(selector);\n const captured = match?.[1];\n if (!captured) return null;\n const base = captured\n .replace(SEPARATOR, (_, c: string) => c.toUpperCase())\n .replace(/^[A-Z]/, (c) => c.toLowerCase());\n let name = base;\n let i = 2;\n while (taken.has(name)) {\n name = `${base}${i}`;\n i += 1;\n }\n taken.add(name);\n return name;\n}\n\n/** `html.find(SEL)` with `html` being the listener's parameter → the selector. */\nfunction findSelector(callee: Expression, htmlParam: string): string | null {\n if (callee.type !== 'CallExpression') return null;\n const c = callee.callee;\n if (\n c.type !== 'MemberExpression' ||\n c.object.type !== 'Identifier' ||\n c.object.name !== htmlParam\n ) {\n return null;\n }\n if (c.property.type !== 'Identifier' || c.property.name !== 'find') return null;\n const [arg] = callee.arguments;\n return arg && arg.type === 'StringLiteral' ? arg.value : null;\n}\n\n/** `this._onX.bind(this)` → `_onX`; `(ev) => this._onX(ev)` → `_onX`. */\nfunction forwardedMethod(handler: Node): string | null {\n if (\n handler.type === 'CallExpression' &&\n handler.callee.type === 'MemberExpression' &&\n handler.callee.property.type === 'Identifier' &&\n handler.callee.property.name === 'bind' &&\n handler.callee.object.type === 'MemberExpression' &&\n handler.callee.object.object.type === 'ThisExpression' &&\n handler.callee.object.property.type === 'Identifier'\n ) {\n return handler.callee.object.property.name;\n }\n if (handler.type === 'ArrowFunctionExpression') {\n let call: Expression | null = null;\n if (handler.body.type === 'CallExpression') call = handler.body;\n else if (handler.body.type === 'BlockStatement' && handler.body.body.length === 1) {\n const only = handler.body.body[0];\n if (only?.type === 'ExpressionStatement' && only.expression.type === 'CallExpression') {\n call = only.expression;\n }\n if (only?.type === 'ReturnStatement' && only.argument?.type === 'CallExpression') {\n call = only.argument;\n }\n }\n if (\n call &&\n call.callee.type === 'MemberExpression' &&\n call.callee.object.type === 'ThisExpression' &&\n call.callee.property.type === 'Identifier' &&\n call.arguments.length <= 1\n ) {\n const [a] = call.arguments;\n const p = handler.params[0];\n if (!a || (a.type === 'Identifier' && p?.type === 'Identifier' && a.name === p.name)) {\n return call.callee.property.name;\n }\n }\n }\n return null;\n}\n\ninterface Bound {\n selector: string;\n event: string;\n handler: Node;\n}\n\n/**\n * `html.find(SEL).<event>(H)` or `html.find(SEL).on('<event>', H)` → the parts,\n * or `null` when the statement is not a jQuery binding this can translate.\n */\nfunction boundEvent(expr: Expression, htmlParam: string): Bound | null {\n if (expr.type !== 'CallExpression') return null;\n if (expr.callee.type !== 'MemberExpression' || expr.callee.property.type !== 'Identifier') {\n return null;\n }\n const receiver = expr.callee.object;\n if (receiver.type === 'Super') return null;\n const selector = findSelector(receiver, htmlParam);\n if (selector === null) return null;\n\n const calleeName = expr.callee.property.name;\n if (EVENTS.has(calleeName)) {\n const handler = expr.arguments[0];\n return handler ? { selector, event: calleeName, handler } : null;\n }\n if (calleeName === 'on' && expr.arguments.length === 2) {\n const first = expr.arguments[0];\n const handler = expr.arguments[1];\n if (first?.type === 'StringLiteral' && handler) {\n return { selector, event: first.value, handler };\n }\n }\n return null;\n}\n\nexport function extractListeners(cls: SheetClass, source: string): Listeners {\n const out: Listeners = { actions: [], listeners: [], leftovers: [], htmlParam: 'html' };\n const method = methodOf(cls.node, 'activateListeners');\n if (!method) return out;\n const p = method.params[0];\n const htmlParam = p?.type === 'Identifier' ? p.name : 'html';\n out.htmlParam = htmlParam;\n const taken = new Set<string>();\n\n const leftover = (stmt: Statement): void => {\n out.leftovers.push({ line: stmt.loc?.start.line ?? 0, text: text(source, stmt) });\n };\n\n const consider = (stmt: Statement): void => {\n if (stmt.type !== 'ExpressionStatement') return;\n const e = stmt.expression;\n if (e.type === 'AwaitExpression') return;\n // Anything that is not a method call, and super.activateListeners(html): dropped.\n if (e.type !== 'CallExpression') return;\n if (e.callee.type !== 'MemberExpression' || e.callee.property.type !== 'Identifier') return;\n if (e.callee.object.type === 'Super') return;\n\n const bound = boundEvent(e, htmlParam);\n if (!bound) {\n leftover(stmt);\n return;\n }\n const { selector, event, handler } = bound;\n\n if (event !== 'click') {\n out.listeners.push({ selector, event, handlerText: text(source, handler) });\n return;\n }\n\n const name = actionName(selector, taken);\n if (name === null) {\n leftover(stmt);\n return;\n }\n const forwarded = forwardedMethod(handler);\n if (forwarded) {\n out.actions.push({\n name,\n selector,\n kind: 'method',\n method: forwarded,\n param: null,\n body: null,\n isAsync: false,\n });\n return;\n }\n if (handler.type === 'ArrowFunctionExpression' || handler.type === 'FunctionExpression') {\n const p0 = handler.params[0];\n out.actions.push({\n name,\n selector,\n kind: 'inline',\n method: null,\n param: p0?.type === 'Identifier' ? p0.name : null,\n body: text(source, handler.body),\n isAsync: Boolean(handler.async),\n });\n return;\n }\n leftover(stmt);\n };\n\n /** A guard such as `if (!this.options.editable) return;`: V2 sheets gate through isEditable. */\n const isGuard = (stmt: Statement): boolean => {\n if (stmt.type !== 'IfStatement' || stmt.alternate) return false;\n const c = stmt.consequent;\n if (c.type === 'ReturnStatement') return true;\n return (\n c.type === 'BlockStatement' && c.body.length === 1 && c.body[0]?.type === 'ReturnStatement'\n );\n };\n\n const visit = (stmts: Statement[]): void => {\n for (const stmt of stmts) {\n if (isGuard(stmt)) continue;\n if (stmt.type === 'IfStatement') {\n // Bindings under a condition are still bindings; the condition itself is lost, so say so.\n const branches = [stmt.consequent, stmt.alternate].filter((b): b is Statement =>\n Boolean(b),\n );\n for (const b of branches) visit(b.type === 'BlockStatement' ? b.body : [b]);\n out.leftovers.push({\n line: stmt.loc?.start.line ?? 0,\n text: `if (${text(source, stmt.test)}) guarded the bindings above it; V2 actions run regardless, gate inside the handler`,\n });\n continue;\n }\n if (stmt.type === 'BlockStatement') {\n visit(stmt.body);\n continue;\n }\n consider(stmt);\n }\n };\n visit(method.body.body);\n return out;\n}\n","/**\n * `static get defaultOptions()` → the V2 statics.\n *\n * Reads the object literal handed to `mergeObject(super.defaultOptions, {...})`\n * (or returned directly) and maps the keys the v1 sheets used: `classes`,\n * `template`, `width`/`height`, `resizable`, `submitOnChange`, `tabs`,\n * `dragDrop`. Anything else is listed so the reader decides.\n */\nimport type { ClassMethod, Expression, ObjectExpression, ObjectProperty } from '@babel/types';\nimport { methodOf, type SheetClass, text, walk } from './parse.js';\n\nexport interface SheetOptions {\n classes: string | null;\n width: number | null;\n height: number | null;\n /** `height: \"auto\"`, which V2 also accepts. */\n heightAuto: boolean;\n resizable: boolean | null;\n submitOnChange: boolean | null;\n /** FormApplication only. */\n closeOnSubmit: boolean | null;\n /** Application only: `id` and `title` (the window title). */\n id: string | null;\n title: string | null;\n template: string | null;\n templateGetter: ClassMethod | null;\n tabs: Array<{ navSelector: string; contentSelector: string | null; initial: string | null }>;\n dragDrop: string | null;\n unknown: string[];\n /** The options literal read `this` (a subclass static, usually). */\n usesThis: boolean;\n}\n\nfunction keyName(p: ObjectProperty): string | null {\n if (p.key.type === 'Identifier') return p.key.name;\n if (p.key.type === 'StringLiteral') return p.key.value;\n return null;\n}\n\nconst NOT_A_VALUE = new Set(['ArrayPattern', 'ObjectPattern', 'AssignmentPattern', 'RestElement']);\n\nfunction props(obj: ObjectExpression): Array<[string, Expression]> {\n const out: Array<[string, Expression]> = [];\n for (const p of obj.properties) {\n if (p.type !== 'ObjectProperty') continue;\n const k = keyName(p);\n if (k && !NOT_A_VALUE.has(p.value.type)) out.push([k, p.value as Expression]);\n }\n return out;\n}\n\n/** A string literal, or a template literal with nothing interpolated. */\nfunction str(e: Expression): string | null {\n if (e.type === 'StringLiteral') return e.value;\n if (e.type === 'TemplateLiteral' && e.expressions.length === 0) {\n return e.quasis.map((q) => q.value.cooked ?? q.value.raw).join('');\n }\n return null;\n}\nfunction num(e: Expression): number | null {\n return e.type === 'NumericLiteral' ? e.value : null;\n}\nfunction bool(e: Expression): boolean | null {\n return e.type === 'BooleanLiteral' ? e.value : null;\n}\n\n/** The options literal: the last object argument of the returned call, or the returned object. */\nfunction optionsLiteral(method: ClassMethod): ObjectExpression | null {\n let found: ObjectExpression | null = null;\n walk(method.body, (n) => {\n if (found) return false;\n if (n.type !== 'ReturnStatement' || !n.argument) return undefined;\n const arg = n.argument;\n if (arg.type === 'ObjectExpression') {\n found = arg;\n } else if (arg.type === 'CallExpression') {\n const last = [...arg.arguments].reverse().find((a) => a.type === 'ObjectExpression');\n if (last?.type === 'ObjectExpression') found = last;\n }\n return false;\n });\n return found;\n}\n\nexport function extractOptions(cls: SheetClass, source: string): SheetOptions {\n const out: SheetOptions = {\n classes: null,\n width: null,\n height: null,\n heightAuto: false,\n resizable: null,\n submitOnChange: null,\n closeOnSubmit: null,\n id: null,\n title: null,\n template: null,\n templateGetter: methodOf(cls.node, 'template', { kind: 'get', static: false }),\n tabs: [],\n dragDrop: null,\n unknown: [],\n usesThis: false,\n };\n const method = methodOf(cls.node, 'defaultOptions', { static: true, kind: 'get' });\n const literal = method ? optionsLiteral(method) : null;\n if (!literal) return out;\n // A getter ran once per subclass, so `this` was the subclass; a static field runs once, on the class that declares it.\n out.usesThis = /\\bthis\\b/.test(text(source, literal));\n for (const [key, value] of props(literal)) {\n switch (key) {\n case 'classes':\n out.classes = text(source, value);\n break;\n case 'width':\n out.width = num(value);\n break;\n case 'height':\n out.height = num(value);\n out.heightAuto = str(value) === 'auto';\n break;\n case 'closeOnSubmit':\n out.closeOnSubmit = bool(value);\n break;\n case 'id':\n out.id = text(source, value);\n break;\n case 'title':\n out.title = text(source, value);\n break;\n case 'resizable':\n out.resizable = bool(value);\n break;\n case 'submitOnChange':\n out.submitOnChange = bool(value);\n break;\n case 'template':\n out.template = str(value);\n break;\n case 'dragDrop':\n out.dragDrop = text(source, value);\n break;\n case 'tabs':\n out.tabs.push(...readTabs(value));\n break;\n default:\n out.unknown.push(key);\n }\n }\n return out;\n}\n\nfunction readTabs(value: Expression): SheetOptions['tabs'] {\n if (value.type !== 'ArrayExpression') return [];\n const tabs: SheetOptions['tabs'] = [];\n for (const el of value.elements) {\n if (el?.type !== 'ObjectExpression') continue;\n const t = Object.fromEntries(props(el));\n const nav = t.navSelector ? str(t.navSelector) : null;\n if (!nav) continue;\n tabs.push({\n navSelector: nav,\n contentSelector: t.contentSelector ? str(t.contentSelector) : null,\n initial: t.initial ? str(t.initial) : null,\n });\n }\n return tabs;\n}\n\nconst q = (s: string) => `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n\n/** What the class is: a document sheet on the SDK base, a FormApplication, or a plain Application. */\nexport type StaticsKind = 'sheet' | 'form' | 'app';\n\nexport function renderStatics(\n opts: SheetOptions,\n tabIds: Record<string, string[]>,\n todo: (msg: string) => string,\n kind: StaticsKind = 'sheet',\n className?: string,\n): string {\n if (kind === 'form' && !className) {\n throw new Error('renderStatics needs the class name to wire form.handler');\n }\n const lines: string[] = [];\n lines.push(' /** @override */');\n lines.push(' static DEFAULT_OPTIONS = foundry.utils.mergeObject(');\n lines.push(' super.DEFAULT_OPTIONS,');\n lines.push(' {');\n if (kind !== 'sheet' && opts.id) lines.push(` id: ${opts.id},`);\n if (opts.classes) lines.push(` classes: ${opts.classes},`);\n if (kind === 'form') lines.push(` tag: 'form',`);\n if (opts.width !== null || opts.height !== null || opts.heightAuto) {\n const parts = [\n opts.width !== null ? `width: ${opts.width}` : '',\n opts.height !== null ? `height: ${opts.height}` : opts.heightAuto ? `height: 'auto'` : '',\n ].filter(Boolean);\n lines.push(` position: { ${parts.join(', ')} },`);\n }\n const win = [\n kind !== 'sheet' && opts.title ? `title: ${opts.title}` : '',\n opts.resizable !== null ? `resizable: ${opts.resizable}` : '',\n ].filter(Boolean);\n if (win.length > 0) lines.push(` window: { ${win.join(', ')} },`);\n if (kind === 'sheet')\n lines.push(` form: { submitOnChange: ${opts.submitOnChange ?? true} },`);\n if (kind === 'form') {\n lines.push(\n ` form: { handler: ${className}.formHandler, submitOnChange: ${opts.submitOnChange ?? false}, closeOnSubmit: ${opts.closeOnSubmit ?? true} },`,\n );\n }\n lines.push(' actions: {}, // filled below');\n lines.push(' },');\n lines.push(' { inplace: false },');\n lines.push(' );');\n if (opts.usesThis) {\n lines.push(\n ` ${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)')}`,\n );\n }\n for (const key of opts.unknown) {\n lines.push(\n ` ${todo(`${key} from defaultOptions has no V2 equivalent here; move it by hand or drop it`)}`,\n );\n }\n\n if (opts.tabs.length > 0) {\n lines.push('', ' /** @override */', ' static TABS = {');\n for (const [i, tab] of opts.tabs.entries()) {\n // The template edits wire one group. A second nav keeps its v1 markup and needs its own\n // group here plus data-group on its links and panes.\n if (i > 0) {\n lines.push(\n ` ${todo(`${tab.navSelector} is a second tab group; add it here and put data-group on its nav links and panes`)}`,\n );\n continue;\n }\n const group = 'primary';\n const ids = tabIds[tab.navSelector] ?? [];\n const initial = tab.initial ?? ids[0] ?? '';\n if (ids.length === 0) {\n lines.push(\n ` ${todo(`tab ids for ${tab.navSelector} were not found in the template; list them here`)}`,\n );\n }\n lines.push(\n ` ${group}: { tabs: [${ids.map((id) => `{ id: ${q(id)} }`).join(', ')}], initial: ${q(initial)} },`,\n );\n }\n lines.push(' };');\n }\n if (opts.dragDrop) {\n lines.push('', ' /** @override */', ` static DRAG_DROP = ${opts.dragDrop};`);\n }\n const part = kind === 'sheet' ? 'sheet' : kind === 'form' ? 'form' : 'content';\n lines.push('', ' /** @override */', ' static PARTS = {');\n if (opts.template) {\n lines.push(` ${part}: { template: ${q(opts.template)} },`);\n } else {\n lines.push(\n ` ${todo('the template is chosen at runtime (get template); name one part per type here or override _configureRenderParts')}`,\n ` ${part}: { template: '' },`,\n );\n }\n lines.push(' };');\n return lines.join('\\n');\n}\n","/**\n * One v1 sheet class → one file on the SDK base.\n *\n * Structure comes from the AST (which members exist, where each one starts\n * and ends); every body is the original text with the scoped rewrites from\n * `sheet-bodies.ts`. The result is meant to be read, not trusted: each place\n * the planner could not decide carries a `// TODO(migrate)` line, and those\n * lines are listed in the report with their line numbers.\n */\nimport type { ClassMethod } from '@babel/types';\nimport {\n findSheetClasses,\n methodOf,\n parseSource,\n type SheetClass,\n text,\n unsupportedBases,\n} from './parse.js';\nimport {\n rewriteDialogs,\n rewriteDropMethod,\n rewriteGetData,\n rewriteHandlerBody,\n rewriteUpdateObject,\n TODO,\n} from './sheet-bodies.js';\nimport { type ActionBinding, extractListeners } from './sheet-listeners.js';\nimport { extractOptions, renderStatics, type StaticsKind } from './sheet-options.js';\n\nexport interface SheetPlanFile {\n from: string;\n to: string;\n className: string;\n base: 'BaseActorSheet' | 'BaseItemSheet' | 'ApplicationV2';\n source: string;\n actions: Array<{ name: string; selector: string; method: string }>;\n todos: Array<{ line: number; message: string }>;\n /** Template paths the class names, for the template pass. */\n templates: string[];\n tabNavSelectors: string[];\n}\n\nexport interface SheetPlan {\n files: SheetPlanFile[];\n notes: string[];\n}\n\n/** v1 lifecycle methods a sheet used to override; V2 has other hooks for the same jobs. */\nconst V1_LIFECYCLE = new Set([\n 'setPosition',\n '_getHeaderButtons',\n '_render',\n '_renderInner',\n '_replaceHTML',\n '_onSubmit',\n '_getSubmitData',\n '_onChangeInput',\n 'activateEditor',\n 'close',\n]);\n\nconst HANDLED = new Set([\n 'defaultOptions',\n 'getData',\n 'activateListeners',\n '_onDropItem',\n '_onDropActor',\n]);\nconst ACTIONS_PLACEHOLDER = ' actions: {}, // filled below';\n\nfunction methodName(m: ClassMethod): string | null {\n return m.key.type === 'Identifier' ? m.key.name : null;\n}\n\nconst pascal = (s: string) => s.replace(/^[a-z]/, (c) => c.toUpperCase());\nconst single = (s: string) => `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n\n/** Re-indent a member slice so its first line sits at two spaces. */\nfunction reindent(memberText: string): string {\n const lines = memberText.split('\\n');\n const first = lines[0] ?? '';\n const rest = lines.slice(1);\n const indents = rest\n .filter((l) => l.trim().length > 0)\n .map((l) => /^[ \\t]*/.exec(l)?.[0].length ?? 0);\n const min = indents.length > 0 ? Math.min(...indents) : 0;\n // The body sits one level under the member; keep that level at four spaces.\n const strip = Math.max(0, min - 4);\n const body = rest.map((l) => {\n if (l.trim().length === 0) return '';\n const own = /^[ \\t]*/.exec(l)?.[0].length ?? 0;\n return l.slice(Math.min(strip, own));\n });\n return [` ${first.trimStart()}`, ...body].join('\\n');\n}\n\n/** Ensure `(event, target)` on a handler method, keeping the event name it used. */\nfunction handlerSignature(\n methodText: string,\n name: string,\n): { code: string; eventParam: string | null } {\n const escaped = name.replace(/[$]/g, '\\\\$');\n const sig = new RegExp(`^(\\\\s*(?:async\\\\s+)?${escaped}\\\\s*\\\\()([^)]*)(\\\\))`);\n const m = sig.exec(methodText);\n if (!m) return { code: methodText, eventParam: null };\n const params = (m[2] ?? '')\n .split(',')\n .map((p) => p.trim())\n .filter(Boolean);\n const eventParam = params[0] ?? null;\n const first = eventParam ?? 'event';\n return { code: methodText.replace(sig, `$1${first}, target$3`), eventParam };\n}\n\n/** The first parameter name of a method, from its signature text. */\nfunction firstParam(methodText: string, name: string): string | null {\n const escaped = name.replace(/[$]/g, '\\\\$');\n const m = new RegExp(`^\\\\s*(?:async\\\\s+)?${escaped}\\\\s*\\\\(([^)]*)\\\\)`).exec(methodText);\n const first = (m?.[1] ?? '').split(',')[0]?.trim();\n return first ? first : null;\n}\n\n/** Lines after the first sit at `spaces`, keeping their relative indentation. */\nfunction indentTo(snippet: string, spaces: number): string {\n const lines = snippet.split('\\n');\n const rest = lines.slice(1);\n const indents = rest\n .filter((l) => l.trim().length > 0)\n .map((l) => /^[ \\t]*/.exec(l)?.[0].length ?? 0);\n const min = indents.length > 0 ? Math.min(...indents) : 0;\n const pad = ' '.repeat(spaces);\n return [\n (lines[0] ?? '').trimStart(),\n ...rest.map((l) =>\n l.trim().length === 0\n ? ''\n : `${pad}${l.slice(Math.min(min, /^[ \\t]*/.exec(l)?.[0].length ?? 0))}`,\n ),\n ].join('\\n');\n}\n\n/** A block body lifted out of `activateListeners`: inner lines at four spaces, the brace at two. */\nfunction dedentBlock(block: string): string {\n const lines = block.split('\\n');\n if (lines.length < 2) return block;\n const inner = lines.slice(1, -1);\n const indents = inner\n .filter((l) => l.trim().length > 0)\n .map((l) => /^[ \\t]*/.exec(l)?.[0].length ?? 0);\n const min = indents.length > 0 ? Math.min(...indents) : 0;\n const body = inner.map((l) =>\n l.trim().length === 0\n ? ''\n : ` ${l.slice(Math.min(min, /^[ \\t]*/.exec(l)?.[0].length ?? 0))}`,\n );\n return [lines[0] ?? '{', ...body, ' }'].join('\\n');\n}\n\nfunction importLines(source: string, lang: 'js' | 'ts'): string[] {\n const ast = parseSource(source, lang);\n const lines: string[] = [];\n for (const n of ast.program.body) if (n.type === 'ImportDeclaration') lines.push(text(source, n));\n return lines;\n}\n\nfunction isExported(source: string, cls: SheetClass): boolean {\n const start = cls.node.start ?? 0;\n const before = source.slice(Math.max(0, start - 40), start);\n return (\n /export\\s+(?:default\\s+)?$/.test(before) ||\n new RegExp(`export\\\\s+\\\\{[^}]*\\\\b${cls.name}\\\\b`).test(source)\n );\n}\n\ninterface ClassOutput {\n block: string;\n base: SheetPlanFile['base'];\n actions: SheetPlanFile['actions'];\n templates: string[];\n navs: string[];\n usesDialogV2: boolean;\n}\n\nfunction planClass(cls: SheetClass, source: string, tabIds: Record<string, string[]>): ClassOutput {\n const isSheet = cls.base === 'ActorSheet' || cls.base === 'ItemSheet';\n const base: SheetPlanFile['base'] =\n cls.base === 'ActorSheet'\n ? 'BaseActorSheet'\n : cls.base === 'ItemSheet'\n ? 'BaseItemSheet'\n : 'ApplicationV2';\n const kind: StaticsKind = isSheet ? 'sheet' : cls.base === 'FormApplication' ? 'form' : 'app';\n const own = cls.base === 'ActorSheet' ? 'actor' : 'item';\n const options = extractOptions(cls, source);\n const listeners = extractListeners(cls, source);\n const templates = new Set<string>();\n const navs = new Set<string>();\n let usesDialogV2 = false;\n\n if (options.template) templates.add(options.template);\n if (options.templateGetter) {\n for (const m of text(source, options.templateGetter).matchAll(\n /[\"'`]([^\"'`$]+\\.(?:hbs|html))[\"'`]/g,\n )) {\n if (m[1]) templates.add(m[1]);\n }\n }\n for (const t of options.tabs) navs.add(t.navSelector);\n\n const members: string[] = [];\n const todo = (msg: string) => TODO(msg);\n\n // 1. Statics, with the actions block filled in. An inline handler becomes a\n // method named after its action; a name the class already uses (often the\n // very method the handler calls) gets `Action` appended.\n const memberNames = new Set(\n cls.node.body.body.flatMap((m) =>\n (m.type === 'ClassMethod' || m.type === 'ClassProperty') && m.key.type === 'Identifier'\n ? [m.key.name]\n : [],\n ),\n );\n const inlineMethodName = (name: string): string => {\n const plain = `_on${pascal(name)}`;\n return memberNames.has(plain) ? `${plain}Action` : plain;\n };\n const actionEntries = listeners.actions.map((a) => ({\n name: a.name,\n selector: a.selector,\n method: a.kind === 'method' && a.method ? a.method : inlineMethodName(a.name),\n }));\n const actionsBlock =\n actionEntries.length === 0\n ? ' actions: {},'\n : ` actions: {\\n${actionEntries.map((a) => ` ${a.name}: ${cls.name}.prototype.${a.method},`).join('\\n')}\\n },`;\n // A runtime `get template()` decides the template; a static one next to it is not the whole story.\n const statics = options.templateGetter ? { ...options, template: null } : options;\n members.push(\n renderStatics(statics, tabIds, todo, kind, cls.name).replace(ACTIONS_PLACEHOLDER, actionsBlock),\n );\n\n // 2. The document getter.\n if (isSheet && !methodOf(cls.node, own, { kind: 'get' })) {\n members.push(` get ${own}() {\\n return this.document;\\n }`);\n }\n const usesObject = /\\bthis\\.object\\b/.test(text(source, cls.node));\n if (cls.base === 'FormApplication' && usesObject) {\n members.push(\n ` ${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; }')}`,\n );\n }\n\n // 3. The template getter, when dynamic.\n if (options.templateGetter) members.push(reindent(text(source, options.templateGetter)));\n\n // 4. getData → _prepareContext.\n const getData = methodOf(cls.node, 'getData');\n if (getData) {\n members.push(rewriteGetData(reindent(text(source, getData)), cls.base, { usesObject }).code);\n }\n\n const applyDialogs = (code: string): string => {\n const d = rewriteDialogs(code);\n if (/DialogV2\\./.test(d.code)) usesDialogV2 = true;\n return d.code;\n };\n\n // 5. _onRender for the events that are not clicks.\n if (listeners.listeners.length > 0) {\n const body = listeners.listeners\n .map((l) => {\n const param = /^\\s*(?:async\\s+)?\\(?\\s*(\\w+)/.exec(l.handlerText)?.[1] ?? null;\n const isFunction = /^\\s*(?:async\\s+)?(?:\\(|\\w+\\s*=>|function\\b)/.test(l.handlerText);\n const handler = isFunction\n ? indentTo(\n rewriteHandlerBody(\n applyDialogs(l.handlerText),\n param,\n listeners.htmlParam,\n param ? `${param}.currentTarget` : 'target',\n ).code,\n 6,\n )\n : l.handlerText;\n return ` for (const el of this.element.querySelectorAll(${single(l.selector)})) {\\n el.addEventListener(${single(l.event)}, ${handler});\\n }`;\n })\n .join('\\n');\n members.push(\n ` /** @override */\\n async _onRender(context, options) {\\n await super._onRender(context, options);\\n${body}\\n }`,\n );\n }\n\n // 6. Every other member, rewritten by role.\n const handlerNames = new Set(\n listeners.actions.filter((a) => a.kind === 'method' && a.method).map((a) => a.method as string),\n );\n // Methods a render listener forwards to keep their event; jQuery on it still goes.\n const listenerTargets = new Set(\n listeners.listeners.flatMap((l) =>\n [...l.handlerText.matchAll(/this\\.(\\w+)/g)].map((m) => m[1] ?? ''),\n ),\n );\n for (const member of cls.node.body.body) {\n if (\n member.type !== 'ClassMethod' &&\n member.type !== 'ClassProperty' &&\n member.type !== 'ClassPrivateMethod'\n )\n continue;\n const name = member.type === 'ClassMethod' ? methodName(member) : null;\n if (name && HANDLED.has(name)) continue;\n if (name === 'template' && member.type === 'ClassMethod' && member.kind === 'get') continue;\n let code = applyDialogs(reindent(text(source, member)));\n if (name && handlerNames.has(name)) {\n const sig = handlerSignature(code, name);\n code = rewriteHandlerBody(sig.code, sig.eventParam, null).code;\n } else if (name && listenerTargets.has(name)) {\n const ev = firstParam(code, name);\n code = rewriteHandlerBody(code, ev, null, ev ? `${ev}.currentTarget` : 'target').code;\n } else if (member.type === 'ClassMethod') {\n // Any other method: the jQuery idioms with a DOM equivalent, the rest flagged.\n code = rewriteHandlerBody(code, null, null).code;\n }\n if (name && V1_LIFECYCLE.has(name)) {\n 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}`;\n }\n if (name === '_updateObject') {\n code = isSheet\n ? ` ${todo('_updateObject is gone on V2; DocumentSheetV2 submits the form itself. Move any shaping into _prepareSubmitData or delete this')}\\n${code}`\n : rewriteUpdateObject(code).code;\n }\n members.push(code);\n }\n for (const which of ['Item', 'Actor'] as const) {\n const m = methodOf(cls.node, `_onDrop${which}`);\n if (!m) continue;\n if (cls.base === 'ActorSheet') {\n members.push(applyDialogs(rewriteDropMethod(reindent(text(source, m)), which).code));\n } else {\n // Only an actor sheet resolves item and actor drops; on anything else the method would never run.\n members.push(\n ` ${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))}`,\n );\n }\n }\n\n // 7. Inline handlers become methods.\n const inline: ActionBinding[] = listeners.actions.filter((a) => a.kind === 'inline');\n for (const a of inline) {\n const method = inlineMethodName(a.name);\n const rewritten = rewriteHandlerBody(applyDialogs(a.body ?? '{}'), a.param, null).code.trim();\n const body = rewritten.startsWith('{')\n ? dedentBlock(rewritten)\n : `{\\n return ${rewritten};\\n }`;\n members.push(` ${a.isAsync ? 'async ' : ''}${method}(${a.param ?? 'event'}, target) ${body}`);\n }\n for (const l of listeners.leftovers) {\n members.push(\n ` ${todo(`from activateListeners, line ${l.line}: ${l.text.replace(/\\s+/g, ' ')}`)}`,\n );\n }\n\n const exported = isExported(source, cls);\n const extendsExpr = isSheet ? `${base}()` : 'HandlebarsApplicationMixin(ApplicationV2)';\n const block = `${exported ? 'export ' : ''}class ${cls.name} extends ${extendsExpr} {\\n${members.join('\\n\\n')}\\n}`;\n return {\n block,\n base,\n actions: actionEntries,\n templates: [...templates],\n navs: [...navs],\n usesDialogV2,\n };\n}\n\nexport function planSheetFile(\n relPath: string,\n source: string,\n opts: { lang: 'js' | 'ts'; tabIds: Record<string, string[]> },\n): SheetPlan {\n const lang: 'js' | 'ts' = relPath.endsWith('.ts') ? 'ts' : opts.lang;\n const ast = parseSource(source, lang);\n const classes = findSheetClasses(ast, source);\n const notes = unsupportedBases(ast, source).map(\n (u) =>\n `${relPath}:${u.line} ${u.name} extends ${u.superText}; Dialog and DocumentSheet subclasses are not converted, this one stays as it is`,\n );\n if (classes.length === 0) return { files: [], notes };\n\n const dot = relPath.lastIndexOf('.');\n const to = `${relPath.slice(0, dot)}.v2${relPath.slice(dot)}`;\n const outputs = classes.map((cls) => ({ cls, out: planClass(cls, source, opts.tabIds) }));\n\n const sdkBases = [\n ...new Set(outputs.map((o) => o.out.base).filter((b) => b !== 'ApplicationV2')),\n ];\n const header = [\n ...(sdkBases.length > 0 ? [`import { ${sdkBases.join(', ')} } from '@vttforge/core';`] : []),\n ...importLines(source, lang),\n ];\n const fromApi = [\n ...(outputs.some((o) => o.out.base === 'ApplicationV2')\n ? ['ApplicationV2', 'HandlebarsApplicationMixin']\n : []),\n ...(outputs.some((o) => o.out.usesDialogV2) ? ['DialogV2'] : []),\n ].sort();\n if (fromApi.length > 0) {\n if (header.length > 0) header.push('');\n header.push(`const { ${fromApi.join(', ')} } = foundry.applications.api;`);\n }\n const fileSource = `${header.join('\\n')}\\n\\n${outputs.map((o) => o.out.block).join('\\n\\n')}\\n`;\n const marker = 'TODO(migrate): ';\n const todos = fileSource.split('\\n').flatMap((line, i) => {\n const at = line.indexOf(marker);\n return at === -1 ? [] : [{ line: i + 1, message: line.slice(at + marker.length).trim() }];\n });\n\n const files: SheetPlanFile[] = outputs.map(({ cls, out }) => ({\n from: relPath,\n to,\n className: cls.name,\n base: out.base,\n source: fileSource,\n actions: out.actions,\n todos,\n templates: out.templates,\n tabNavSelectors: out.navs,\n }));\n return { files, notes };\n}\n","/**\n * The rewrites `vttforge migrate` applies to a v13 source file.\n *\n * Each transform is a pure function over the file's text. It returns the new\n * text, one `Change` per edit it made, and one `Note` per thing it saw and\n * would not touch: a rewrite that needs a decision (which page a `game.template`\n * read should become) is reported, not guessed.\n *\n * Text-based, like the audit rules they mirror (`VTTF-AUDIT-011` to `016`).\n * The patterns are short and mechanical, and a syntax tree would not make\n * `'-=key'` easier to find. Comments are left alone: every match has to\n * start in code. A match inside a string literal is still rewritten, which\n * is what the preview is for.\n */\n\nimport { bareUsePattern, definesName, LEGACY_GLOBALS } from '../audit/legacy-globals.js';\nimport { MASK, maskComments } from '../audit/mask.js';\nimport { REMOVED_UTILS } from '../audit/v14-rules.js';\n\nexport interface Change {\n /** 1-based line of the edit, in the original text. */\n line: number;\n /** What was there. */\n before: string;\n /** What is there now. */\n after: string;\n /** Which transform made it. */\n rule: string;\n}\n\nexport interface Note {\n line: number;\n rule: string;\n /** What was seen, and what the reader has to decide. */\n message: string;\n}\n\nexport interface TransformResult {\n output: string;\n changes: Change[];\n notes: Note[];\n}\n\nexport type Transform = (source: string) => TransformResult;\n\nfunction lineAt(source: string, index: number): number {\n let line = 1;\n for (let i = 0; i < index && i < source.length; i += 1) {\n if (source[i] === '\\n') line += 1;\n }\n return line;\n}\n\n/** The whole line an index sits on, trimmed, for the report. */\nfunction lineText(source: string, index: number): string {\n const start = source.lastIndexOf('\\n', index - 1) + 1;\n const end = source.indexOf('\\n', index);\n return source.slice(start, end === -1 ? source.length : end).trim();\n}\n\n/**\n * Replace every match, recording one change per match against the original\n * text. The replacement may be a string or a function, like `String#replace`.\n */\nfunction rewrite(\n source: string,\n pattern: RegExp,\n replacement: string | ((...groups: string[]) => string),\n rule: string,\n): TransformResult {\n const changes: Change[] = [];\n const code = maskComments(source);\n const output = source.replace(pattern, (match: string, ...rest: unknown[]) => {\n const offset = rest.find((r): r is number => typeof r === 'number') ?? 0;\n if (code[offset] === MASK) return match;\n const groups = rest.filter((r): r is string => typeof r === 'string');\n const after = typeof replacement === 'string' ? replacement : replacement(match, ...groups);\n if (after !== match) {\n changes.push({ line: lineAt(source, offset), before: match, after, rule });\n }\n return after;\n });\n return { output, changes, notes: [] };\n}\n\nfunction merge(...results: TransformResult[]): TransformResult {\n const last = results.at(-1);\n return {\n output: last?.output ?? '',\n changes: results.flatMap((r) => r.changes),\n notes: results.flatMap((r) => r.notes),\n };\n}\n\n/** Run transforms in sequence, each on the previous one's output. */\nfunction pipe(source: string, transforms: readonly Transform[]): TransformResult {\n const results: TransformResult[] = [];\n let current = source;\n for (const transform of transforms) {\n const result = transform(current);\n results.push(result);\n current = result.output;\n }\n return merge(...results);\n}\n\n/**\n * Bare v12 utility globals → `foundry.utils.*`; `Math.clamped` → `Math.clamp`.\n *\n * A name the file declares or imports itself is left alone, the same way\n * `VTTF-AUDIT-011` leaves it alone. `game.template` is reported, not\n * rewritten: whether it becomes `game.model` or a `documentTypes` read depends\n * on what was read from it.\n */\nexport const removedGlobals: Transform = (source) => {\n const own = new Set(\n REMOVED_UTILS.filter((name) =>\n new RegExp(\n `(?:function\\\\s+${name}\\\\b|(?:const|let|var)\\\\s+${name}\\\\b|import[^;]*\\\\b${name}\\\\b|\\\\b${name}\\\\s*\\\\([^)]*\\\\)\\\\s*\\\\{)`,\n ).test(source),\n ),\n );\n const names = REMOVED_UTILS.filter((name) => !own.has(name));\n const utils = names.length\n ? rewrite(\n source,\n new RegExp(`(?<![\\\\w$.])(${names.join('|')})\\\\s*\\\\(`, 'g'),\n (_m, name) => `foundry.utils.${name}(`,\n 'removed-globals',\n )\n : { output: source, changes: [], notes: [] };\n const clamped = rewrite(utils.output, /\\bMath\\.clamped\\s*\\(/g, 'Math.clamp(', 'removed-globals');\n const notes: Note[] = [];\n const code = maskComments(clamped.output);\n for (const match of clamped.output.matchAll(/\\bgame\\.template\\b/g)) {\n if (code[match.index ?? 0] === MASK) continue;\n notes.push({\n line: lineAt(clamped.output, match.index ?? 0),\n rule: 'removed-globals',\n message:\n \"`game.template` is gone. Read type defaults from `game.model`, or the type list from the package's `documentTypes`.\",\n });\n }\n return { ...merge(utils, clamped), notes };\n};\n\n/**\n * Bare v13 global aliases → their `foundry.*` path: `renderTemplate(` →\n * `foundry.applications.handlebars.renderTemplate(`, `extends ActorSheet` →\n * `extends foundry.appv1.sheets.ActorSheet`. Same object, no removal date.\n * A name the file declares or imports, an object key, a property, and a\n * word inside a string or comment are left alone.\n */\nexport const namespacedGlobals: Transform = (source) => {\n const changes: Change[] = [];\n const code = maskComments(source, { strings: true });\n const edits: Array<{ start: number; end: number; text: string; name: string }> = [];\n for (const [name, path] of Object.entries(LEGACY_GLOBALS)) {\n if (definesName(code, name)) continue;\n for (const match of code.matchAll(bareUsePattern(name))) {\n const start = match.index ?? 0;\n edits.push({ start, end: start + name.length, text: path, name });\n }\n }\n let output = source;\n for (const edit of edits.sort((a, b) => b.start - a.start)) {\n output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);\n }\n for (const edit of edits.sort((a, b) => a.start - b.start)) {\n changes.push({\n line: lineAt(source, edit.start),\n before: edit.name,\n after: edit.text,\n rule: 'namespaced-globals',\n });\n }\n return { output, changes, notes: [] };\n};\n\n/**\n * `'-=key': null` → `key: _del`; `'==key': value` → `key: _replace(value)`;\n * `performDeletions` → `applyOperators`; `objectsEqual` → `equals`.\n *\n * The key may be a template literal with `${...}` segments in the prefix,\n * which is how a flag deletion is usually written: `` [`flags.${id}.-=old`] ``.\n */\nexport const dataOperators: Transform = (source) => {\n const deletions = rewrite(\n source,\n /(['\"`])((?:[\\w$]+\\.|\\$\\{[^}]*\\}\\.)*)-=([\\w$.]+)\\1(\\]?)\\s*:\\s*null\\b/g,\n (_m, quote, prefix, key, bracket) => `${quote}${prefix}${key}${quote}${bracket}: _del`,\n 'data-operators',\n );\n // `\"==key\": <value>` wraps a value of any shape, so the value is scanned to\n // its end rather than matched: up to the comma or brace that closes it, with\n // brackets, braces, parentheses and strings balanced along the way.\n const replacements = wrapReplacementValues(deletions.output);\n const flags = rewrite(\n replacements.output,\n /\\bperformDeletions\\s*:/g,\n 'applyOperators:',\n 'data-operators',\n );\n const equals = rewrite(\n flags.output,\n /\\bfoundry\\.utils\\.objectsEqual\\s*\\(/g,\n 'foundry.utils.equals(',\n 'data-operators',\n );\n return merge(deletions, replacements, flags, equals);\n};\n\nfunction wrapReplacementValues(source: string): TransformResult {\n const changes: Change[] = [];\n const pattern = /(['\"`])((?:[\\w$]+\\.|\\$\\{[^}]*\\}\\.)*)==([\\w$.]+)\\1(\\]?)\\s*:\\s*/g;\n const code = maskComments(source);\n let out = '';\n let cursor = 0;\n for (const match of source.matchAll(pattern)) {\n const start = match.index ?? 0;\n if (code[start] === MASK) continue;\n const valueStart = start + match[0].length;\n const valueEnd = scanValueEnd(source, valueStart);\n if (valueEnd === -1) continue;\n const value = source.slice(valueStart, valueEnd).trimEnd();\n const [, quote = '\"', prefix = '', key = '', bracket = ''] = match;\n const after = `${quote}${prefix}${key}${quote}${bracket}: _replace(${value})`;\n out += source.slice(cursor, start) + after;\n cursor = valueStart + value.length;\n changes.push({\n line: lineAt(source, start),\n before: source.slice(start, cursor),\n after,\n rule: 'data-operators',\n });\n }\n out += source.slice(cursor);\n return { output: out, changes, notes: [] };\n}\n\n/** Index just past a value that starts at `from`: the next `,` or `}` at depth zero. */\nfunction scanValueEnd(source: string, from: number): number {\n let depth = 0;\n let quote: string | null = null;\n for (let i = from; i < source.length; i += 1) {\n const ch = source[i] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') quote = ch;\n else if (ch === '{' || ch === '[' || ch === '(') depth += 1;\n else if (ch === '}' || ch === ']' || ch === ')') {\n if (depth === 0) return i;\n depth -= 1;\n } else if (ch === ',' && depth === 0) return i;\n }\n return -1;\n}\n\nconst ROLL_MODE_VALUES: Record<string, string> = {\n publicroll: 'public',\n gmroll: 'gm',\n blindroll: 'blind',\n selfroll: 'self',\n};\n\nconst ROLL_MODE_CONSTANTS: Record<string, string> = {\n PUBLIC: 'public',\n PRIVATE: 'gm',\n BLIND: 'blind',\n SELF: 'self',\n};\n\n/**\n * `rollMode` → `messageMode`, with the value mapped when it is a literal.\n *\n * `\"roll\"` meant \"whatever the user's chat dropdown says\", which is what an\n * absent `messageMode` means now, so it becomes `undefined`. A value that is\n * an expression is wrapped in `Roll._mapLegacyRollMode(...)`, which maps a\n * v13 name and passes a v14 key or `undefined` through unchanged, so the\n * wrap is safe whatever the expression yields.\n */\nexport const rollMode: Transform = (source) => {\n const option = rewrite(\n source,\n /\\brollMode\\s*:\\s*(['\"])(publicroll|gmroll|blindroll|selfroll|roll)\\1/g,\n (_m, quote, value) =>\n value === 'roll'\n ? 'messageMode: undefined'\n : `messageMode: ${quote}${ROLL_MODE_VALUES[value]}${quote}`,\n 'roll-mode',\n );\n const expressions = wrapRollModeExpressions(option.output);\n const setting = rewrite(\n expressions.output,\n /(['\"])core\\1\\s*,\\s*(['\"])rollMode\\2/g,\n (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`,\n 'roll-mode',\n );\n const modes = rewrite(\n setting.output,\n /\\bCONFIG\\.Dice\\.rollModes\\b/g,\n 'CONFIG.ChatMessage.modes',\n 'roll-mode',\n );\n const constants = rewrite(\n modes.output,\n /\\bCONST\\.DICE_ROLL_MODES\\.(PUBLIC|PRIVATE|BLIND|SELF)\\b/g,\n (_m, name) => `\"${ROLL_MODE_CONSTANTS[name]}\"`,\n 'roll-mode',\n );\n return merge(option, expressions, setting, modes, constants);\n};\n\n/** `rollMode: <expr>` → `messageMode: Roll._mapLegacyRollMode(<expr>)`. */\nfunction wrapRollModeExpressions(source: string): TransformResult {\n const changes: Change[] = [];\n const pattern = /\\brollMode\\s*:\\s*/g;\n const code = maskComments(source);\n let out = '';\n let cursor = 0;\n for (const match of source.matchAll(pattern)) {\n const start = match.index ?? 0;\n if (code[start] === MASK) continue;\n const valueStart = start + match[0].length;\n const valueEnd = scanValueEnd(source, valueStart);\n if (valueEnd === -1) continue;\n const value = source.slice(valueStart, valueEnd).trimEnd();\n const after = `messageMode: Roll._mapLegacyRollMode(${value})`;\n out += source.slice(cursor, start) + after;\n cursor = valueStart + value.length;\n changes.push({\n line: lineAt(source, start),\n before: source.slice(start, cursor),\n after,\n rule: 'roll-mode',\n });\n }\n out += source.slice(cursor);\n return { output: out, changes, notes: [] };\n}\n\n/**\n * Hooks that changed shape: noted, not rewritten. `renderChatMessage` is\n * removed in v15 and its replacement hands an element where it handed a\n * jQuery object, so the handler body is the reader's to change.\n */\nexport const hookNotes: Transform = (source) => {\n const notes: Note[] = [];\n const code = maskComments(source);\n for (const match of source.matchAll(/Hooks\\.(?:on|once)\\(\\s*['\"]renderChatMessage['\"]/g)) {\n if (code[match.index ?? 0] === MASK) continue;\n notes.push({\n line: lineAt(source, match.index ?? 0),\n rule: 'hooks',\n message:\n '`renderChatMessage` is removed in v15. Listen to `renderChatMessageHTML(message, html, context)`; `html` is the element, so `html.find(x)` becomes `html.querySelector(x)`.',\n });\n }\n return { output: source, changes: [], notes };\n};\n\n/**\n * Context-menu entries and header controls: `name` → `label`, `condition` →\n * `visible`, `callback` → `onClick`.\n *\n * Only an object literal whose own keys include `callback` and `name` or\n * `condition` is an entry. A Dialog button has `icon`, `label` and\n * `callback`, and keeps `callback` on v14, so `icon` is not a signal; and\n * only the literal's own keys count, so a class body or a `buttons` bag that\n * happens to contain an entry is not itself treated as one. The callback's\n * parameters change too, from `(li)` to `(event, target)`, and that is noted\n * rather than rewritten.\n */\nexport const contextMenuKeys: Transform = (source) => {\n const changes: Change[] = [];\n const notes: Note[] = [];\n const RENAME: Record<string, string> = {\n name: 'label',\n condition: 'visible',\n callback: 'onClick',\n };\n // Innermost first, so an edit never moves the offsets of a literal still\n // to be visited: an inner literal sits entirely inside its outer one, and\n // editing it changes the outer one's end, never its start.\n const edits: Array<{ start: number; end: number; text: string }> = [];\n for (const { start, end } of objectLiterals(source).sort((a, b) => b.start - a.start)) {\n const keys = ownKeys(source, start, end);\n const names = new Set(keys.map((k) => k.name));\n if (!names.has('callback') || !(names.has('name') || names.has('condition'))) continue;\n for (const key of keys) {\n const to = RENAME[key.name];\n if (to !== undefined)\n edits.push({ start: key.offset, end: key.offset + key.name.length, text: to });\n }\n changes.push({\n line: lineAt(source, start),\n before: lineText(source, start),\n after: 'label / visible / onClick keys',\n rule: 'context-menu-keys',\n });\n notes.push({\n line: lineAt(source, start),\n rule: 'context-menu-keys',\n message:\n '`onClick` receives `(event, target)` where `callback` received the element. Check the parameter list.',\n });\n }\n let output = source;\n for (const edit of edits.sort((a, b) => b.start - a.start)) {\n output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);\n }\n return { output, changes, notes };\n};\n\n/**\n * The keys an object literal declares itself, with the offset of each name.\n *\n * Walks the span between the braces at depth one: a key is an identifier\n * followed by `:` where a property may start, which is right after the\n * opening brace or after a comma at that depth. Nested literals, arrays,\n * calls, strings and comments are stepped over.\n */\nfunction ownKeys(\n source: string,\n start: number,\n end: number,\n): Array<{ name: string; offset: number }> {\n const keys: Array<{ name: string; offset: number }> = [];\n let depth = 0;\n let quote: string | null = null;\n let expectKey = true;\n for (let i = start; i < end; i += 1) {\n const ch = source[i] ?? '';\n const next = source[i + 1] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '/' && next === '/') {\n const nl = source.indexOf('\\n', i);\n i = nl === -1 ? end : nl;\n continue;\n }\n if (ch === '/' && next === '*') {\n const close = source.indexOf('*/', i + 2);\n i = close === -1 ? end : close + 1;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n quote = ch;\n expectKey = false;\n continue;\n }\n if (ch === '{' || ch === '[' || ch === '(') {\n depth += 1;\n expectKey = depth === 1 && ch === '{';\n continue;\n }\n if (ch === '}' || ch === ']' || ch === ')') {\n depth -= 1;\n expectKey = false;\n continue;\n }\n if (depth !== 1) continue;\n if (ch === ',') {\n expectKey = true;\n continue;\n }\n if (/\\s/.test(ch)) continue;\n if (expectKey && /[A-Za-z_$]/.test(ch)) {\n let j = i;\n while (j < end && /[\\w$]/.test(source[j] ?? '')) j += 1;\n let k = j;\n while (k < end && /\\s/.test(source[k] ?? '')) k += 1;\n if (source[k] === ':') keys.push({ name: source.slice(i, j), offset: i });\n i = j - 1;\n }\n expectKey = false;\n }\n return keys;\n}\n\n/** Every `{ ... }` span in the text, outermost first, strings and comments skipped. */\nfunction objectLiterals(source: string): Array<{ start: number; end: number }> {\n const spans: Array<{ start: number; end: number }> = [];\n const stack: number[] = [];\n let quote: string | null = null;\n for (let i = 0; i < source.length; i += 1) {\n const ch = source[i] ?? '';\n const next = source[i + 1] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '/' && next === '/') {\n i = source.indexOf('\\n', i);\n if (i === -1) break;\n continue;\n }\n if (ch === '/' && next === '*') {\n const close = source.indexOf('*/', i + 2);\n i = close === -1 ? source.length : close + 1;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') quote = ch;\n else if (ch === '{') stack.push(i);\n else if (ch === '}') {\n const start = stack.pop();\n if (start !== undefined) spans.push({ start, end: i + 1 });\n }\n }\n return spans.sort((a, b) => a.start - b.start);\n}\n\n/**\n * `legacyTransferral` is gone: the assignment, and the `activeEffect`\n * option `registerSystem` used to take for it.\n */\nexport const legacyTransferral: Transform = (source) => {\n const statement = rewrite(\n source,\n /^[ \\t]*CONFIG\\.ActiveEffect\\.legacyTransferral\\s*=[^\\n]*\\n?/gm,\n '',\n 'legacy-transferral',\n );\n const option = rewrite(\n statement.output,\n /^[ \\t]*activeEffect\\s*:\\s*\\{\\s*legacyTransferral\\s*:\\s*(?:true|false)\\s*,?\\s*\\}\\s*,?[ \\t]*\\n?/gm,\n '',\n 'legacy-transferral',\n );\n const key = rewrite(\n option.output,\n /^[ \\t]*legacyTransferral\\s*:\\s*(?:true|false)\\s*,?[ \\t]*\\n?/gm,\n '',\n 'legacy-transferral',\n );\n return merge(statement, option, key);\n};\n\n/** v14 registers no core Actor or Item sheet, so there is nothing to unregister. */\nexport const unregisterCoreSheets: Transform = (source) =>\n rewrite(\n source,\n /^[ \\t]*(?:foundry\\.documents\\.collections\\.)?(?:Actors|Items)\\.unregisterSheet\\(\\s*['\"]core['\"][^\\n]*\\n?/gm,\n '',\n 'unregister-core-sheets',\n );\n\n/**\n * `CONFIG.statusEffects = list;` → add each entry by id. The setter empties\n * the collection first, which wipes what other packages added.\n */\nexport const statusEffectsAssignment: Transform = (source) => {\n const changes: Change[] = [];\n let output = '';\n let cursor = 0;\n const pattern = /\\bCONFIG\\.statusEffects\\s*=(?!=)\\s*/g;\n const code = maskComments(source);\n for (const match of source.matchAll(pattern)) {\n const start = match.index ?? 0;\n if (code[start] === MASK) continue;\n const valueStart = start + match[0].length;\n const end = scanStatementEnd(source, valueStart);\n if (end === -1) continue;\n const value = source.slice(valueStart, end).trim();\n const after = `for (const effect of ${value}) CONFIG.statusEffects[effect.id] = effect;`;\n output += source.slice(cursor, start) + after;\n cursor = end + 1;\n changes.push({\n line: lineAt(source, start),\n before: source.slice(start, cursor).trim(),\n after,\n rule: 'status-effects',\n });\n }\n output += source.slice(cursor);\n return { output, changes, notes: [] };\n};\n\n/** Index of the `;` that ends a statement starting at `from`, brackets balanced. */\nfunction scanStatementEnd(source: string, from: number): number {\n let depth = 0;\n let quote: string | null = null;\n for (let i = from; i < source.length; i += 1) {\n const ch = source[i] ?? '';\n if (quote) {\n if (ch === '\\\\') i += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') quote = ch;\n else if (ch === '{' || ch === '[' || ch === '(') depth += 1;\n else if (ch === '}' || ch === ']' || ch === ')') depth -= 1;\n else if (ch === ';' && depth === 0) return i;\n }\n return -1;\n}\n\nconst EFFECT_MODES: Record<string, string> = {\n CUSTOM: 'custom',\n MULTIPLY: 'multiply',\n ADD: 'add',\n DOWNGRADE: 'downgrade',\n UPGRADE: 'upgrade',\n OVERRIDE: 'override',\n};\n\n/**\n * `mode: CONST.ACTIVE_EFFECT_MODES.ADD` → `type: \"add\"`. A root-level\n * `changes` array on an effect now lives under `system.changes`; that move\n * depends on where the data is built, so it is noted.\n */\nexport const activeEffectModes: Transform = (source) => {\n const typed = rewrite(\n source,\n /\\bmode\\s*:\\s*CONST\\.ACTIVE_EFFECT_MODES\\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\\b/g,\n (_m, name) => `type: \"${EFFECT_MODES[name]}\"`,\n 'active-effect-modes',\n );\n const bare = rewrite(\n typed.output,\n /\\bCONST\\.ACTIVE_EFFECT_MODES\\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\\b/g,\n (_m, name) => `\"${EFFECT_MODES[name]}\"`,\n 'active-effect-modes',\n );\n const notes: Note[] = typed.changes.map((c) => ({\n line: c.line,\n rule: 'active-effect-modes',\n message: 'The change now belongs under `system.changes`, not a root-level `changes` array.',\n }));\n return { ...merge(typed, bare), notes };\n};\n\n/** The transforms, in the order they run. */\nconst SOURCE_TRANSFORMS: ReadonlyArray<readonly [string, Transform]> = [\n ['removed-globals', removedGlobals],\n ['namespaced-globals', namespacedGlobals],\n ['data-operators', dataOperators],\n ['roll-mode', rollMode],\n ['context-menu-keys', contextMenuKeys],\n ['legacy-transferral', legacyTransferral],\n ['unregister-core-sheets', unregisterCoreSheets],\n ['status-effects', statusEffectsAssignment],\n ['active-effect-modes', activeEffectModes],\n ['hooks', hookNotes],\n];\n\nexport function transformSource(source: string): TransformResult {\n return pipe(\n source,\n SOURCE_TRANSFORMS.map(([, t]) => t),\n );\n}\n\n/**\n * The manifest: `type` declared, `compatibility` raised to 14 where it is\n * lower. Returns `null` when nothing needed to change.\n *\n * Edited as text, not re-serialised: a manifest carries its author's\n * indentation, key order and one-line arrays, and a diff that reformats the\n * whole file to add one key is a diff nobody merges. `type` goes on the line\n * after `id`, with that line's indentation; the compatibility values are\n * replaced in place.\n */\nexport function transformManifest(\n raw: string,\n kind: 'system' | 'module',\n): { output: string; changes: Change[]; notes: Note[] } | null {\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n const changes: Change[] = [];\n const notes: Note[] = [];\n let output = raw;\n\n if (parsed.type !== kind) {\n const typeKey = topLevelKey(output, 'type');\n if (typeKey) {\n output = `${output.slice(0, typeKey.valueStart)}\"${kind}\"${output.slice(typeKey.valueEnd)}`;\n changes.push({\n line: lineAt(raw, typeKey.keyStart),\n before: raw.slice(typeKey.keyStart, typeKey.valueEnd).trim(),\n after: `\"type\": \"${kind}\"`,\n rule: 'manifest',\n });\n } else {\n const idKey = topLevelKey(output, 'id');\n if (idKey) {\n const lineStart = output.lastIndexOf('\\n', idKey.keyStart) + 1;\n const indent = output.slice(lineStart, idKey.keyStart);\n const after = output.indexOf('\\n', idKey.valueEnd);\n const insertAt = after === -1 ? output.length : after;\n const rest = output.slice(idKey.valueEnd, insertAt);\n if (/^\\s*,?\\s*$/.test(rest)) {\n // \"id\" ends its line: the new key gets the next line, same indent.\n const needsComma = !/,\\s*$/.test(rest);\n const head = needsComma\n ? `${output.slice(0, idKey.valueEnd)},${rest}`\n : output.slice(0, insertAt);\n output = `${head}\\n${indent}\"type\": \"${kind}\",${output.slice(insertAt)}`;\n } else {\n // More keys follow on the same line (a one-line manifest): stay inline.\n output = `${output.slice(0, idKey.valueEnd)}, \"type\": \"${kind}\"${output.slice(idKey.valueEnd)}`;\n }\n changes.push({\n line: lineAt(raw, idKey.keyStart) + 1,\n before: '(no \"type\")',\n after: `\"type\": \"${kind}\"`,\n rule: 'manifest',\n });\n } else {\n notes.push({\n line: 1,\n rule: 'manifest',\n message: `Add \\`\"type\": \"${kind}\"\\` next to \"id\"; the key could not be placed by hand.`,\n });\n }\n }\n }\n\n const compatibility = (parsed.compatibility ?? {}) as Record<string, unknown>;\n for (const field of ['minimum', 'verified'] as const) {\n const current = compatibility[field];\n const major = Number.parseInt(String(current ?? '0'), 10);\n if (Number.isFinite(major) && major >= 14) continue;\n const block = topLevelKey(output, 'compatibility');\n const inner = block ? topLevelKey(output.slice(block.valueStart, block.valueEnd), field) : null;\n if (block && inner && current !== undefined) {\n const valueStart = block.valueStart + inner.valueStart;\n const valueEnd = block.valueStart + inner.valueEnd;\n output = `${output.slice(0, valueStart)}\"14\"${output.slice(valueEnd)}`;\n changes.push({\n line: lineAt(output, block.valueStart + inner.keyStart),\n before: `compatibility.${field}: ${JSON.stringify(current)}`,\n after: `compatibility.${field}: \"14\"`,\n rule: 'manifest',\n });\n continue;\n }\n notes.push({\n line: 1,\n rule: 'manifest',\n message: `Set compatibility.${field} to \"14\"; it is ${JSON.stringify(current ?? null)} and could not be edited in place.`,\n });\n }\n const maximum = compatibility.maximum;\n if (maximum !== undefined && Number.parseInt(String(maximum), 10) < 14) {\n notes.push({\n line: 1,\n rule: 'manifest',\n message: `compatibility.maximum is ${JSON.stringify(maximum)}, which keeps the package off v14. Raise it or remove it.`,\n });\n }\n if ('gridDistance' in parsed || 'gridUnits' in parsed) {\n notes.push({\n line: 1,\n rule: 'manifest',\n message:\n 'gridDistance / gridUnits are ignored on v14. Move them into `\"grid\": { \"type\", \"distance\", \"units\", \"diagonals\" }`.',\n });\n }\n if (changes.length === 0) return notes.length ? { output: raw, changes, notes } : null;\n JSON.parse(output); // an edit that broke the file is a bug here, not the user's problem\n return { output, changes, notes };\n}\n\n/**\n * Where a key of the root object sits in the JSON text: the start of the\n * quoted key, and the span of its value. Only depth one counts, so a\n * `\"type\"` inside `relationships.systems[]` is not the manifest's `type`.\n */\nfunction topLevelKey(\n json: string,\n key: string,\n): { keyStart: number; valueStart: number; valueEnd: number } | null {\n let depth = 0;\n let i = 0;\n const skipString = (from: number): number => {\n let j = from + 1;\n for (; j < json.length; j += 1) {\n if (json[j] === '\\\\') j += 1;\n else if (json[j] === '\"') return j + 1;\n }\n return j;\n };\n const skipValue = (from: number): number => {\n let j = from;\n while (j < json.length && /\\s/.test(json[j] ?? '')) j += 1;\n const ch = json[j] ?? '';\n if (ch === '\"') return skipString(j);\n if (ch === '{' || ch === '[') {\n let d = 0;\n for (let k = j; k < json.length; k += 1) {\n const c = json[k] ?? '';\n if (c === '\"') k = skipString(k) - 1;\n else if (c === '{' || c === '[') d += 1;\n else if (c === '}' || c === ']') {\n d -= 1;\n if (d === 0) return k + 1;\n }\n }\n return json.length;\n }\n while (j < json.length && !/[,}\\]\\s]/.test(json[j] ?? '')) j += 1;\n return j;\n };\n while (i < json.length) {\n const ch = json[i] ?? '';\n if (ch === '\"') {\n const end = skipString(i);\n if (depth === 1) {\n const name = json.slice(i + 1, end - 1);\n let k = end;\n while (k < json.length && /\\s/.test(json[k] ?? '')) k += 1;\n if (json[k] === ':') {\n const valueStart = (() => {\n let v = k + 1;\n while (v < json.length && /\\s/.test(json[v] ?? '')) v += 1;\n return v;\n })();\n const valueEnd = skipValue(k + 1);\n if (name === key) return { keyStart: i, valueStart, valueEnd };\n i = valueEnd;\n continue;\n }\n }\n i = end;\n continue;\n }\n if (ch === '{' || ch === '[') depth += 1;\n else if (ch === '}' || ch === ']') depth -= 1;\n i += 1;\n }\n return null;\n}\n","/**\n * `vttforge migrate`: rewrite a v13 project for v14.\n *\n * Walks the same files the audit walks, applies the transforms, and reports\n * every edit and every thing it saw and would not decide for you. Nothing is\n * written unless asked: the preview is the default, because a text rewrite\n * that touched a string literal is something to see before it lands.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { runReleaseRules } from '../audit/release-rules.js';\nimport { _internal } from '../audit/source-rules.js';\nimport { type EmitStyle, planDataModels } from './data-models.js';\nimport { editTemplate, readTabIds, type TemplateEdit } from './sheet-templates.js';\nimport { planSheetFile, type SheetPlanFile } from './sheets.js';\nimport { type Change, type Note, transformManifest, transformSource } from './transforms.js';\n\ninterface FileResult {\n /** Project-relative path. */\n file: string;\n changes: Change[];\n notes: Note[];\n}\n\nexport interface MigrateReport {\n cwd: string;\n /** Files with at least one change or note. */\n files: FileResult[];\n /** Whether the edits were written to disk. */\n written: boolean;\n counts: { files: number; changes: number; notes: number };\n /** Present when data models were generated from template.json. */\n dataModels?: {\n files: string[];\n documentTypes: Record<string, Record<string, Record<string, unknown>>>;\n registration: string;\n /** What happened, for the reader: a file left alone, nothing to generate. */\n notes: string[];\n /** What the generator could not decide: a guessed field, a template.json to delete. */\n decisions: string[];\n };\n /** Present when V2 sheet files were generated from Application v1 classes. */\n sheets?: {\n files: Array<Omit<SheetPlanFile, 'source'>>;\n templates: Array<{ file: string; edits: TemplateEdit[]; formRoot: boolean }>;\n /** What to do next: point registerSheet at the file, run the audit again. */\n notes: string[];\n /** What the codemod could not decide: a class it skipped, a root form to replace. */\n decisions: string[];\n };\n}\n\n/** A file the run will write once every rewrite has been computed. */\ninterface PendingWrite {\n path: string;\n content: string;\n}\n\n/**\n * The lines the report prints as \"needs a decision\": the rewrites the run did\n * not make, the TODO lines in generated files, and what the generators could\n * not decide. `--strict` fails the run when any is left. A note that only says\n * what happened (a file left alone, where to point registerSheet) is not one.\n */\nexport function countDecisions(report: MigrateReport): number {\n return (\n report.counts.notes +\n (report.dataModels?.decisions.length ?? 0) +\n (report.sheets?.files.reduce((n, f) => n + f.todos.length, 0) ?? 0) +\n (report.sheets?.decisions.length ?? 0)\n );\n}\n\nexport interface MigrateOptions {\n cwd: string;\n /** Write the edits. Default false: report only. */\n write?: boolean;\n /** Also generate a data model per template.json type. */\n dataModels?: boolean;\n /** How the generated models are written: bare Foundry classes, or on the SDK's bases. */\n style?: EmitStyle;\n /** File extension of the generated models and sheets. */\n lang?: 'js' | 'ts';\n /** Also generate a V2 sheet file per Application v1 sheet class. */\n sheets?: boolean;\n}\n\nexport async function runMigrate(options: MigrateOptions): Promise<MigrateReport> {\n const { cwd } = options;\n const write = options.write === true;\n if (!existsSync(cwd) || !(await stat(cwd)).isDirectory()) {\n throw new Error(`Migrate target is not a directory: ${cwd}`);\n }\n\n const files: FileResult[] = [];\n // Every rewrite is computed before the first write, so a run that stops\n // halfway (a parser that throws on one file) leaves the tree as it was.\n const pending: PendingWrite[] = [];\n\n for (const [name, kind] of [\n ['system.json', 'system'],\n ['module.json', 'module'],\n ] as const) {\n const path = join(cwd, name);\n if (!existsSync(path)) continue;\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n JSON.parse(raw);\n } catch {\n continue;\n }\n const result = transformManifest(raw, kind);\n if (result === null) continue;\n files.push({ file: name, changes: result.changes, notes: result.notes });\n if (write && result.changes.length > 0) pending.push({ path, content: result.output });\n }\n\n for await (const path of _internal.walkSourceFiles(cwd)) {\n let source: string;\n try {\n source = await readFile(path, 'utf8');\n } catch {\n continue;\n }\n const result = transformSource(source);\n if (result.changes.length === 0 && result.notes.length === 0) continue;\n files.push({ file: relative(cwd, path), changes: result.changes, notes: result.notes });\n if (write && result.output !== source) pending.push({ path, content: result.output });\n }\n\n // A project that builds to dist/ with a release workflow written for the old\n // layout publishes a package with no entry file. Say so here, since the\n // rewrite is what moves the project onto the build.\n for (const finding of await runReleaseRules(cwd)) {\n files.push({\n file: finding.filePath,\n changes: [],\n notes: [\n {\n line: finding.line ?? 1,\n rule: finding.ruleId,\n message: `${finding.message} ${finding.remediation ?? ''}`.trim(),\n },\n ],\n });\n }\n\n files.sort((a, b) => a.file.localeCompare(b.file));\n const report: MigrateReport = {\n cwd,\n files,\n written: write,\n counts: {\n files: files.length,\n changes: files.reduce((n, f) => n + f.changes.length, 0),\n notes: files.reduce((n, f) => n + f.notes.length, 0),\n },\n };\n\n if (options.dataModels) {\n const templatePath = join(cwd, 'template.json');\n if (!existsSync(templatePath)) {\n report.dataModels = {\n files: [],\n documentTypes: {},\n registration: '',\n notes: ['No template.json here; nothing to generate.'],\n decisions: [],\n };\n } else {\n const template = JSON.parse(await readFile(templatePath, 'utf8')) as Record<string, unknown>;\n const plan = planDataModels(template, {\n style: options.style ?? 'plain',\n lang: options.lang ?? 'js',\n });\n const written: string[] = [];\n const info: string[] = [];\n for (const file of plan.files) {\n const target = join(cwd, file.path);\n if (existsSync(target)) {\n info.push(`${file.path} exists and was left alone.`);\n continue;\n }\n if (write) pending.push({ path: target, content: file.source });\n written.push(file.path);\n }\n report.dataModels = {\n files: written,\n documentTypes: plan.documentTypes,\n registration: plan.registration,\n notes: info,\n decisions: plan.notes,\n };\n }\n }\n\n if (options.sheets) report.sheets = await planSheets(cwd, write, options.lang ?? 'js', pending);\n\n for (const { path, content } of pending) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n }\n return report;\n}\n\n/** Every `.hbs` / `.html` in the project, project-relative. */\nasync function allTemplates(cwd: string): Promise<string[]> {\n const out: string[] = [];\n for await (const file of _internal.walkTemplateFiles(cwd)) out.push(relative(cwd, file));\n return out.sort();\n}\n\n/** Project-relative path for a Foundry template path such as `systems/<id>/templates/x.html`. */\nfunction localTemplate(cwd: string, foundryPath: string): string | null {\n const m = /^(?:systems|modules)\\/[^/]+\\/(.+)$/.exec(foundryPath);\n const rel = m?.[1] ?? foundryPath;\n return existsSync(join(cwd, rel)) ? rel : null;\n}\n\nasync function planSheets(\n cwd: string,\n write: boolean,\n lang: 'js' | 'ts',\n pending: PendingWrite[],\n): Promise<NonNullable<MigrateReport['sheets']>> {\n const files: Array<Omit<SheetPlanFile, 'source'>> = [];\n const templates: Array<{ file: string; edits: TemplateEdit[]; formRoot: boolean }> = [];\n const notes: string[] = [];\n const decisions: string[] = [];\n const generated = new Map<string, string>();\n\n for await (const path of _internal.walkSourceFiles(cwd)) {\n const rel = relative(cwd, path);\n if (/\\.v2\\.[cm]?[jt]s$/.test(rel)) continue;\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch {\n continue;\n }\n if (\n !/\\bextends\\s+(?:foundry\\.appv1\\.\\w+\\.)?(?:ActorSheet|ItemSheet|FormApplication|Application)\\b/.test(\n raw,\n )\n )\n continue;\n // The generated file starts from the v14 rewrite of the source, so the bare\n // v13 aliases are already namespaced in it whether or not --write ran.\n const source = transformSource(raw).output;\n\n // First pass: which templates and nav selectors, so the tab ids can be read.\n let probe: ReturnType<typeof planSheetFile>;\n try {\n probe = planSheetFile(rel, source, { lang, tabIds: {} });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n decisions.push(`${rel} could not be parsed and was skipped: ${reason}`);\n continue;\n }\n decisions.push(...probe.notes);\n if (probe.files.length === 0) continue;\n let templatePaths = [...new Set(probe.files.flatMap((f) => f.templates))]\n .map((t) => localTemplate(cwd, t))\n .filter((t): t is string => t !== null);\n // A `get template()` that builds the path at runtime names nothing; every\n // sheet template in the project is a candidate then.\n if (templatePaths.length === 0) {\n const every = await allTemplates(cwd);\n // Leave out the other document's folder (item templates for an actor sheet and the\n // reverse); shared parts and dialogs stay in, since a sheet's rows often live there.\n const first = probe.files[0]?.base;\n const other =\n first === 'BaseItemSheet'\n ? /(?:^|\\/)actors?\\//i\n : first === 'BaseActorSheet'\n ? /(?:^|\\/)items?\\//i\n : null;\n templatePaths = other ? every.filter((t) => !other.test(t)) : every;\n }\n const navSelectors = [...new Set(probe.files.flatMap((f) => f.tabNavSelectors))];\n const tabIds: Record<string, string[]> = {};\n for (const t of templatePaths) {\n const tpl = await readFile(join(cwd, t), 'utf8');\n for (const nav of navSelectors) {\n if (tabIds[nav]) continue;\n const ids = readTabIds(tpl, nav);\n if (ids.length > 0) tabIds[nav] = ids;\n }\n }\n\n const plan = planSheetFile(rel, source, { lang, tabIds });\n for (const f of plan.files) {\n const { source: out, ...rest } = f;\n files.push(rest);\n generated.set(f.to, out);\n notes.push(\n `Run \\`vttforge audit\\` again after reading ${f.to}: the v14 rules also apply to the generated file.`,\n );\n notes.push(\n f.base === 'ApplicationV2'\n ? `Point whatever constructs ${f.className} (a settings menu, a macro, a button) at ${f.to}, then delete the old class.`\n : `Point registerSheet at ${f.className} from ${f.to} (a written key such as \"<id>.${f.base === 'BaseActorSheet' ? 'actor' : 'item'}\"), then delete the old class.`,\n );\n }\n const actions = plan.files.flatMap((f) =>\n f.actions.map((a) => ({ name: a.name, selector: a.selector })),\n );\n for (const t of templatePaths) {\n const tpl = await readFile(join(cwd, t), 'utf8');\n const primaryNav = navSelectors[0];\n const r = editTemplate(tpl, {\n actions,\n navSelectors,\n tabIds: primaryNav === undefined ? undefined : tabIds[primaryNav],\n });\n // A template the class never touched (a dialog, a chat card) is not a sheet; its form is its own.\n if (r.edits.length === 0) continue;\n templates.push({ file: t, edits: r.edits, formRoot: r.formRoot });\n if (r.formRoot) {\n decisions.push(\n `${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).`,\n );\n }\n if (write && r.edits.length > 0) pending.push({ path: join(cwd, t), content: r.output });\n }\n }\n\n for (const [to, out] of generated) {\n const target = join(cwd, to);\n if (existsSync(target)) {\n notes.unshift(`${to} exists and was left alone.`);\n continue;\n }\n if (write) pending.push({ path: target, content: out });\n }\n return { files, templates, notes: [...new Set(notes)], decisions: [...new Set(decisions)] };\n}\n\n/** The report as text: one block per file, edits then notes. */\nexport function formatMigrateReport(report: MigrateReport): string {\n const lines: string[] = [];\n if (report.files.length === 0 && !report.dataModels && !report.sheets) {\n lines.push('Nothing to migrate. The project already reads as v14.');\n return `${lines.join('\\n')}\\n`;\n }\n if (report.files.length === 0) lines.push('Nothing to rewrite in the source or the manifest.');\n else {\n lines.push(\n report.written\n ? `Rewrote ${report.counts.changes} place(s) in ${report.counts.files} file(s).`\n : `Would rewrite ${report.counts.changes} place(s) in ${report.counts.files} file(s). Run again with --write to apply.`,\n );\n }\n for (const file of report.files) {\n lines.push('', `${file.file}`);\n for (const change of file.changes) {\n lines.push(\n ` ${change.line}: ${oneLine(change.before)}`,\n ` ${' '.repeat(String(change.line).length)} → ${oneLine(change.after)}`,\n );\n }\n for (const note of file.notes) {\n lines.push(` ${note.line}: needs a decision: ${note.message}`);\n }\n }\n if (report.counts.notes > 0) {\n lines.push(\n '',\n `${report.counts.notes} place(s) need a decision. Run \\`vttforge audit\\` after editing them.`,\n );\n }\n if (report.dataModels) {\n const dm = report.dataModels;\n lines.push(\n '',\n report.written\n ? `Wrote ${dm.files.length} data model file(s) from template.json:`\n : `Would write ${dm.files.length} data model file(s) from template.json:`,\n );\n for (const f of dm.files) lines.push(` ${f}`);\n if (Object.keys(dm.documentTypes).length > 0) {\n lines.push(\n '',\n 'Declare the types in the manifest:',\n ` \"documentTypes\": ${JSON.stringify(dm.documentTypes)}`,\n );\n }\n if (dm.registration)\n lines.push(\n '',\n 'Register the models at init:',\n ...dm.registration.split('\\n').map((l) => ` ${l}`),\n );\n for (const n of dm.notes) lines.push(` ${n}`);\n for (const n of dm.decisions) lines.push(` needs a decision: ${n}`);\n }\n if (report.sheets) {\n const s = report.sheets;\n const targets = [...new Set(s.files.map((f) => f.to))];\n lines.push(\n '',\n report.written\n ? `Wrote ${targets.length} sheet file(s) on the SDK bases:`\n : `Would write ${targets.length} sheet file(s) on the SDK bases:`,\n );\n for (const f of s.files) {\n lines.push(\n ` ${f.to}: ${f.className} extends ${f.base === 'ApplicationV2' ? 'HandlebarsApplicationMixin(ApplicationV2)' : `${f.base}()`}`,\n );\n for (const a of f.actions) lines.push(` action ${a.name} ← ${a.selector} (${a.method})`);\n for (const t of f.todos) lines.push(` ${t.line}: needs a decision: ${t.message}`);\n }\n if (s.templates.length > 0) {\n lines.push('', report.written ? 'Edited templates:' : 'Would edit templates:');\n for (const t of s.templates) {\n lines.push(` ${t.file}`);\n for (const e of t.edits) {\n lines.push(\n ` ${e.line}: ${oneLine(e.before)}`,\n ` ${' '.repeat(String(e.line).length)} → ${oneLine(e.after)}`,\n );\n }\n }\n }\n for (const n of s.notes) lines.push(` ${n}`);\n for (const n of s.decisions) lines.push(` needs a decision: ${n}`);\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction oneLine(text: string): string {\n const flat = text.replace(/\\s+/g, ' ').trim();\n return flat.length > 100 ? `${flat.slice(0, 97)}...` : flat;\n}\n","/**\n * `vttforge migrate`: the CLI surface over the v13 → v14 rewrite.\n *\n * Exit codes:\n * 0: ran, whether or not anything changed\n * 1: the target is not a directory, or --strict and a decision was left\n */\n\nimport { resolve } from 'node:path';\nimport {\n countDecisions,\n formatMigrateReport,\n type MigrateReport,\n runMigrate,\n} from '../migrate/index.js';\n\nexport interface MigrateCommandOptions {\n cwd?: string;\n write?: boolean;\n json?: boolean;\n /** Exit 1 when the report leaves anything that needs a decision. */\n strict?: boolean;\n /** Also generate a data model per template.json type. */\n dataModels?: boolean;\n style?: 'plain' | 'sdk';\n lang?: 'js' | 'ts';\n /** Also generate a V2 sheet file per Application v1 sheet class. */\n sheets?: boolean;\n /** Custom writer (tests). Defaults to process.stdout.write. */\n out?: (chunk: string) => void;\n}\n\nexport async function runMigrateCommand(\n options: MigrateCommandOptions = {},\n): Promise<{ report: MigrateReport; exitCode: 0 | 1 }> {\n const cwd = resolve(options.cwd ?? process.cwd());\n const out =\n options.out ??\n ((chunk: string) => {\n process.stdout.write(chunk);\n });\n const report = await runMigrate({\n cwd,\n write: options.write === true,\n dataModels: options.dataModels === true,\n style: options.style,\n lang: options.lang,\n sheets: options.sheets === true,\n });\n out(options.json ? `${JSON.stringify(report, null, 2)}\\n` : formatMigrateReport(report));\n const decisions = countDecisions(report);\n if (options.strict === true && decisions > 0) {\n if (!options.json) out(`--strict: ${decisions} decision(s) left; exiting 1.\\n`);\n return { report, exitCode: 1 };\n }\n return { report, exitCode: 0 };\n}\n","/**\n * vttforge command tree.\n *\n * Kept apart from `bin.ts`, which only runs it. Argument definitions are the\n * CLI's contract with its users (`--no-install` skipping the install, an\n * alias resolving to its canonical name) and a module that calls `runMain`\n * on import cannot be reached by a test. Exporting the commands from here\n * lets the suite parse real argv against the real definitions.\n */\nimport { defineCommand } from 'citty';\nimport { runAuditCommand } from './commands/audit.js';\nimport { runBuild } from './commands/build.js';\nimport { runDev } from './commands/dev.js';\nimport { runInit, ScaffoldError } from './commands/init.js';\nimport { runLintCommand } from './commands/lint.js';\nimport { runMigrateCommand } from './commands/migrate.js';\nimport { VTTFORGE_CLI_VERSION } from './index.js';\n\nexport const init = defineCommand({\n meta: {\n name: 'init',\n description: 'Scaffold a new Foundry VTT system or module from a VTTForge template',\n },\n args: {\n name: {\n type: 'positional',\n description: 'Directory name for the new system/module (also the default manifest id)',\n required: false,\n },\n type: {\n type: 'string',\n description: 'Package type: system | module',\n },\n lang: {\n type: 'string',\n description: 'Language: ts | js',\n },\n id: {\n type: 'string',\n description: 'Manifest id (defaults to a slug of the directory name)',\n },\n title: {\n type: 'string',\n description: 'Human-readable title shown in Foundry setup screens',\n },\n description: {\n type: 'string',\n description: 'One-line description for the manifest',\n },\n author: {\n type: 'string',\n description: 'Author name for the manifest (defaults to the git author)',\n },\n license: {\n type: 'string',\n description: 'SPDX license id (default MIT)',\n },\n // Without a terminal there is nothing for a prompt to read, so it waits\n // forever. This flag takes the defaults instead, and the scaffolder\n // also assumes it when stdin is not a TTY, so CI need not pass it.\n yes: {\n type: 'boolean',\n alias: 'y',\n default: false,\n description: 'Accept defaults for anything not passed, without prompting',\n },\n // Citty parses `--no-X` as `args.X === false`, so define affirmative\n // flags with a true default. `--no-install` then yields `install: false`\n // which we forward as `noInstall: true`.\n install: {\n type: 'boolean',\n default: true,\n description: 'Install dependencies after scaffold (use --no-install to skip)',\n },\n git: {\n type: 'boolean',\n default: true,\n description: 'Initialize a git repository after scaffold (use --no-git to skip)',\n },\n },\n async run({ args }) {\n try {\n await runInit({\n name: typeof args.name === 'string' ? args.name : undefined,\n type: typeof args.type === 'string' ? (args.type as 'system' | 'module') : undefined,\n lang: typeof args.lang === 'string' ? (args.lang as 'ts' | 'js') : undefined,\n id: typeof args.id === 'string' ? args.id : undefined,\n title: typeof args.title === 'string' ? args.title : undefined,\n description: typeof args.description === 'string' ? args.description : undefined,\n author: typeof args.author === 'string' ? args.author : undefined,\n license: typeof args.license === 'string' ? args.license : undefined,\n yes: args.yes === true,\n noInstall: args.install === false,\n noGit: args.git === false,\n });\n } catch (err) {\n // ScaffoldError already surfaced its message via `p.cancel`; anything\n // else is a real crash worth showing. Either way the bin exits 1.\n if (!(err instanceof ScaffoldError)) {\n console.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n },\n});\n\nexport const dev = defineCommand({\n meta: {\n name: 'dev',\n description: 'Symlink dist/ into Foundry Data and run vite build --watch',\n },\n args: {\n 'foundry-data': {\n type: 'string',\n alias: 'data-dir',\n description:\n 'Override the Foundry user-data directory (skips env / config / first-run prompt)',\n },\n 'hmr-port': {\n type: 'string',\n description: 'Port for the hot reload bridge (default 31313)',\n },\n },\n async run({ args }) {\n // Citty surfaces aliases under the canonical name. Belt-and-suspenders:\n // accept either spelling so older docs and muscle memory keep working.\n const explicit =\n (typeof args['foundry-data'] === 'string' ? args['foundry-data'] : undefined) ??\n (typeof args['data-dir'] === 'string' ? args['data-dir'] : undefined);\n // A non-numeric port is the user's typo, not a reason to fall back to a\n // port they did not ask for. Say so and stop.\n const rawPort = typeof args['hmr-port'] === 'string' ? args['hmr-port'] : undefined;\n const hmrPort = rawPort === undefined ? undefined : Number(rawPort);\n if (hmrPort !== undefined && !Number.isInteger(hmrPort)) {\n console.error(`--hmr-port expects a whole number, got \\`${rawPort}\\`.`);\n process.exit(1);\n }\n try {\n await runDev({ dataDir: explicit, hmrPort });\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n },\n});\n\nexport const build = defineCommand({\n meta: {\n name: 'build',\n description: 'Run vite build (production) and emit <id>-<version>.zip for foundryvtt.com',\n },\n async run() {\n try {\n await runBuild();\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n },\n});\n\nexport const lint = defineCommand({\n meta: {\n name: 'lint',\n description: 'Run Biome (shipped with the CLI) over the project, then the v14 audit',\n },\n args: {\n path: {\n type: 'positional',\n description: 'Project root to lint (defaults to the current directory)',\n required: false,\n },\n fix: {\n type: 'boolean',\n default: false,\n description: 'Write the safe fixes and format the files instead of only reporting',\n },\n // Affirmative flag with a true default, so `--no-audit` parses as\n // `audit: false` (same pattern as `--no-install` on init).\n audit: {\n type: 'boolean',\n default: true,\n description: 'Run `vttforge audit` after Biome (use --no-audit to skip)',\n },\n strict: {\n type: 'boolean',\n default: false,\n description: 'For the audit: exit non-zero on any finding, not only HIGH',\n },\n },\n async run({ args }) {\n try {\n const result = await runLintCommand({\n cwd: typeof args.path === 'string' ? args.path : undefined,\n fix: args.fix === true,\n audit: args.audit !== false,\n strict: args.strict === true,\n });\n if (result.exitCode !== 0) process.exitCode = result.exitCode;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n },\n});\n\nexport const audit = defineCommand({\n meta: {\n name: 'audit',\n description:\n 'Scan a system/module project for the v14 manifest, source and template breakages that fail quietly',\n },\n args: {\n path: {\n type: 'positional',\n description: 'Project root to scan (defaults to the current directory)',\n required: false,\n },\n json: {\n type: 'boolean',\n default: false,\n description: 'Emit a machine-readable JSON report instead of markdown',\n },\n strict: {\n type: 'boolean',\n default: false,\n description: 'Exit non-zero on any finding (default: only HIGH triggers a non-zero exit)',\n },\n },\n async run({ args }) {\n try {\n const result = await runAuditCommand({\n cwd: typeof args.path === 'string' ? args.path : undefined,\n format: args.json === true ? 'json' : 'markdown',\n strict: args.strict === true,\n });\n // Set exitCode instead of calling process.exit so any pending stdout\n // writes (the JSON / markdown report) get flushed before the process\n // tears down. process.exit(1) would truncate large reports on the\n // exact runs CI needs them intact.\n if (result.exitCode !== 0) process.exitCode = result.exitCode;\n } catch (err) {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n },\n});\n\nexport const migrate = defineCommand({\n meta: {\n name: 'migrate',\n description:\n 'Rewrite a v13 system or module for Foundry v14 (preview by default); --data-models and --sheets write the v16 replacements',\n },\n args: {\n path: {\n type: 'positional',\n description: 'Project root to rewrite (defaults to the current directory)',\n required: false,\n },\n write: {\n type: 'boolean',\n default: false,\n description: 'Write the edits. Without it, the command only reports what it would change',\n },\n json: {\n type: 'boolean',\n default: false,\n description: 'Emit the report as JSON',\n },\n strict: {\n type: 'boolean',\n default: false,\n description: 'Exit 1 when anything is left that needs a decision, for CI',\n },\n 'data-models': {\n type: 'boolean',\n default: false,\n description:\n 'Also generate a data model per template.json type (template.json is deprecated since v14)',\n },\n style: {\n type: 'string',\n default: 'plain',\n description: 'For --data-models: \"plain\" Foundry classes, or \"sdk\" classes on @vttforge/core',\n },\n lang: {\n type: 'string',\n default: 'js',\n description: 'For --data-models and --sheets: \"js\" writes .mjs, \"ts\" writes .ts',\n },\n sheets: {\n type: 'boolean',\n default: false,\n description:\n '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',\n },\n },\n async run({ args }) {\n try {\n const { exitCode } = await runMigrateCommand({\n cwd: args.path ? String(args.path) : undefined,\n write: Boolean(args.write),\n json: Boolean(args.json),\n strict: Boolean(args.strict),\n dataModels: Boolean(args['data-models']),\n style: String(args.style) === 'sdk' ? 'sdk' : 'plain',\n lang: String(args.lang) === 'ts' ? 'ts' : 'js',\n sheets: Boolean(args.sheets),\n });\n process.exitCode = exitCode;\n } catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n },\n});\n\nexport const main = defineCommand({\n meta: {\n name: 'vttforge',\n version: VTTFORGE_CLI_VERSION,\n description:\n 'VTTForge CLI: scaffold, dev, build, lint, audit and migrate for Foundry v14+ systems and modules',\n },\n subCommands: {\n init,\n dev,\n build,\n lint,\n audit,\n migrate,\n },\n});\n","#!/usr/bin/env node\n/**\n * vttforge bin: the executable entry.\n *\n * Nothing but the launch. The command tree lives in `cli.ts` so tests can\n * import it without running the CLI.\n */\nimport { runMain } from 'citty';\nimport { main } from './cli.js';\n\nrunMain(main);\n"],"mappings":";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