tempo-sdk 0.0.69 → 0.0.75

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.
Files changed (109) hide show
  1. package/dist/assets/index.js +3 -3
  2. package/dist/astro/asset-preview-client.js +2 -2
  3. package/dist/astro.js +17 -11
  4. package/dist/astro.js.map +1 -1
  5. package/dist/canvas/astro.d.ts +1 -1
  6. package/dist/canvas/astro.js +2 -2
  7. package/dist/canvas/editor.d.ts +15 -5
  8. package/dist/canvas/editor.js +13 -8
  9. package/dist/canvas/editor.js.map +1 -1
  10. package/dist/canvas/flutter-preview.d.ts +18 -0
  11. package/dist/canvas/flutter-preview.js +9 -0
  12. package/dist/canvas/flutter-preview.js.map +1 -0
  13. package/dist/canvas/index.d.ts +33 -2
  14. package/dist/canvas/index.js +1134 -26
  15. package/dist/canvas/index.js.map +1 -1
  16. package/dist/canvas/interact-projection.js +5 -4
  17. package/dist/canvas/parser.d.ts +142 -3
  18. package/dist/canvas/parser.js +14 -1
  19. package/dist/canvas/svelte.d.ts +1 -1
  20. package/dist/canvas/svelte.js +2 -2
  21. package/dist/canvas/vue.d.ts +74 -0
  22. package/dist/canvas/vue.js +264 -0
  23. package/dist/canvas/vue.js.map +1 -0
  24. package/dist/{chunk-6BSLP7P3.js → chunk-2YX4WVFH.js} +49 -7
  25. package/dist/chunk-2YX4WVFH.js.map +1 -0
  26. package/dist/chunk-5HIIF354.js +67 -0
  27. package/dist/chunk-5HIIF354.js.map +1 -0
  28. package/dist/{chunk-FE6TYCLF.js → chunk-5VIBKVFO.js} +2 -2
  29. package/dist/{chunk-FE6TYCLF.js.map → chunk-5VIBKVFO.js.map} +1 -1
  30. package/dist/{chunk-77DZCV5Z.js → chunk-CXIW4IKC.js} +2 -2
  31. package/dist/chunk-CYQE3TLC.js +37 -0
  32. package/dist/chunk-CYQE3TLC.js.map +1 -0
  33. package/dist/{chunk-WTQQOLXM.js → chunk-DNSCVLKV.js} +1571 -1410
  34. package/dist/chunk-DNSCVLKV.js.map +1 -0
  35. package/dist/chunk-EGRHWZRV.js +1 -0
  36. package/dist/chunk-EGRHWZRV.js.map +1 -0
  37. package/dist/{chunk-EYKOOLPL.js → chunk-GKDDNDG3.js} +1039 -134
  38. package/dist/chunk-GKDDNDG3.js.map +1 -0
  39. package/dist/{chunk-KOSJXE4G.js → chunk-H6BQZOAW.js} +4 -3
  40. package/dist/chunk-HOBTDB6G.js +112 -0
  41. package/dist/chunk-HOBTDB6G.js.map +1 -0
  42. package/dist/chunk-HZXQPM4W.js +285 -0
  43. package/dist/chunk-HZXQPM4W.js.map +1 -0
  44. package/dist/chunk-SGN7BDRE.js +16 -0
  45. package/dist/chunk-SGN7BDRE.js.map +1 -0
  46. package/dist/{chunk-F23JGM4U.js → chunk-UBTL6JUF.js} +6 -2
  47. package/dist/{chunk-F23JGM4U.js.map → chunk-UBTL6JUF.js.map} +1 -1
  48. package/dist/{chunk-2JRAG36X.js → chunk-WBMO4ZYO.js} +2 -2
  49. package/dist/chunk-WBMO4ZYO.js.map +1 -0
  50. package/dist/{chunk-K3EYTZLL.js → chunk-WTXOWQ7N.js} +3 -1
  51. package/dist/chunk-WTXOWQ7N.js.map +1 -0
  52. package/dist/{chunk-Q2A46HHW.js → chunk-XFPFWTWX.js} +276 -43
  53. package/dist/chunk-XFPFWTWX.js.map +1 -0
  54. package/dist/chunk-XMFVWJUY.js +342 -0
  55. package/dist/chunk-XMFVWJUY.js.map +1 -0
  56. package/dist/{chunk-PXDTH36X.js → chunk-Y72PIE3I.js} +212 -20
  57. package/dist/chunk-Y72PIE3I.js.map +1 -0
  58. package/dist/{chunk-6IR5JY6W.js → chunk-YECMP34I.js} +41 -9
  59. package/dist/chunk-YECMP34I.js.map +1 -0
  60. package/dist/{chunk-NSKYOKG5.js → chunk-ZXC7SZIT.js} +278 -26
  61. package/dist/chunk-ZXC7SZIT.js.map +1 -0
  62. package/dist/{controls-reader-SNMI2UY7.js → controls-reader-Z7OQWYWQ.js} +4 -3
  63. package/dist/{controls-reader-SNMI2UY7.js.map → controls-reader-Z7OQWYWQ.js.map} +1 -1
  64. package/dist/expo/plugin.cjs +301 -58
  65. package/dist/expo/plugin.cjs.map +1 -1
  66. package/dist/expo/plugin.js +1 -1
  67. package/dist/expo-babel-plugin.cjs +301 -58
  68. package/dist/expo-babel-plugin.cjs.map +1 -1
  69. package/dist/expo-babel-plugin.js +1 -1
  70. package/dist/flutter-preview-path.d.ts +9 -0
  71. package/dist/flutter-preview-path.js +16 -0
  72. package/dist/flutter-preview-path.js.map +1 -0
  73. package/dist/index.d.ts +16 -15
  74. package/dist/index.js +9 -6
  75. package/dist/nextjs/plugin.cjs +46 -5
  76. package/dist/nextjs/plugin.cjs.map +1 -1
  77. package/dist/nextjs/plugin.js +1 -1
  78. package/dist/nextjs-loader.cjs +343 -68
  79. package/dist/nextjs-loader.cjs.map +1 -1
  80. package/dist/nextjs.cjs +48 -6
  81. package/dist/nextjs.cjs.map +1 -1
  82. package/dist/nextjs.d.cts +9 -1
  83. package/dist/nextjs.d.ts +9 -1
  84. package/dist/nextjs.js +1 -1
  85. package/dist/nuxt/runtime/identity.d.ts +24 -0
  86. package/dist/nuxt/runtime/identity.js +18 -0
  87. package/dist/nuxt/runtime/identity.js.map +1 -0
  88. package/dist/nuxt.d.ts +102 -0
  89. package/dist/nuxt.js +5673 -0
  90. package/dist/nuxt.js.map +1 -0
  91. package/dist/{storyboard-4YdTYq_e.d.ts → storyboard-CMJVBSXn.d.ts} +9 -3
  92. package/dist/svelte.d.ts +4 -2
  93. package/dist/svelte.js +21 -88
  94. package/dist/svelte.js.map +1 -1
  95. package/dist/vue.d.ts +66 -0
  96. package/dist/vue.js +1403 -0
  97. package/dist/vue.js.map +1 -0
  98. package/package.json +48 -5
  99. package/dist/chunk-2JRAG36X.js.map +0 -1
  100. package/dist/chunk-6BSLP7P3.js.map +0 -1
  101. package/dist/chunk-6IR5JY6W.js.map +0 -1
  102. package/dist/chunk-EYKOOLPL.js.map +0 -1
  103. package/dist/chunk-K3EYTZLL.js.map +0 -1
  104. package/dist/chunk-NSKYOKG5.js.map +0 -1
  105. package/dist/chunk-PXDTH36X.js.map +0 -1
  106. package/dist/chunk-Q2A46HHW.js.map +0 -1
  107. package/dist/chunk-WTQQOLXM.js.map +0 -1
  108. /package/dist/{chunk-77DZCV5Z.js.map → chunk-CXIW4IKC.js.map} +0 -0
  109. /package/dist/{chunk-KOSJXE4G.js.map → chunk-H6BQZOAW.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../vue.ts","../../../modules/vue-editor/escape.ts","../../../modules/annotation/style-keys.ts","../../../modules/vue-editor/compiler.ts","../../../modules/vue-editor/parse.ts","../../../modules/vue-editor/component-props.ts","../../../modules/vue-editor/annotate.ts","../../../modules/vue-editor/transfer.ts","../../../modules/vue-editor/copy.ts","../app-vite-plugins.ts"],"sourcesContent":["/**\n * Vue-specific Tempo source annotation.\n *\n * Put `tempoVuePlugin()` before `vue()` in the Vite plugins. It only supplies\n * filesystem/project identity and the Vite hook order; parsing and\n * annotation remain isolated in the framework-focused @modules/vue-editor\n * package. `tempoVueAppPlugins()` brings the app's own Vite plugins into\n * Tempo's Vue canvas host.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport {\n annotateVueSource,\n appendVueSourceRegistryRecord,\n} from \"@modules/vue-editor\";\nimport type { TempoVueSourceRegistryRecord } from \"@modules/vue-editor/records\";\nimport type { Plugin, PluginOption } from \"vite\";\nimport { sourceVersionHash } from \"../../modules/annotation/source-version.ts\";\nimport {\n defaultSourceRoot,\n readModifiedTs,\n resolveAnnotationIdentity,\n} from \"./annotation-identity.ts\";\nimport { appendModuleVersionRecord } from \"./annotation-strategy.ts\";\nimport { loadAppVitePlugins } from \"./app-vite-plugins.ts\";\nimport { TEMPO_VUE_ANNOTATION_PLUGIN_NAME } from \"./host-identity.ts\";\nimport { createSdkFileMatcher } from \"./sdk-package-files.ts\";\n\nexport interface TempoVuePluginOptions {\n /** Annotation identity root. Defaults to the process working directory. */\n root?: string;\n /** Allowed source boundary. Defaults to the package-manager workspace\n * around `root`, else `root` (see defaultSourceRoot); host sidecars set\n * this to the project root while annotations remain relative to the host\n * root. */\n sourceRoot?: string;\n /** Override the normal TEMPO environment gate, primarily for tests. */\n enabled?: boolean;\n /** Directories whose `.vue` files are never annotated or registered, even\n * inside the source boundary. The Nuxt sidecar lists its own root here:\n * its `app.vue` and host page are canvas plumbing, not authored UI. */\n exclude?: string[];\n}\n\n/** A `.vue` main module id: `?vue&type=...` sub-requests (and every other\n * query) describe generated blocks, not the authored file. */\nconst VUE_MAIN_MODULE = /\\.vue$/;\n\n/**\n * Two Vite plugins around @vitejs/plugin-vue:\n * - `pre` stamps the authored template (native elements get the four\n * `data-tempo-*` stamps, component invocations a vnode-hook marker) at\n * exact UTF-16 offsets of the raw file. It never touches `<script>`, so\n * plugin-vue's template-only HMR (`rerender`) keeps working. Its transform\n * is `order: \"pre\"`, which Vite runs ahead of every unordered transform, so\n * only a plugin listed earlier that is also `order: \"pre\"` can rewrite a\n * file before it (vue-router's `definePage`, vue-macros and markdown\n * plugins are `enforce: \"pre\"` with unordered transforms).\n * - `post` ends plugin-vue's compiled main module with the file's source\n * registry record and module version record, so both run once per module\n * evaluation (a `<script setup>` statement would run per instance).\n */\nexport function tempoVuePlugin(options: TempoVuePluginOptions = {}): Plugin[] {\n const root = resolve(options.root ?? process.cwd());\n const sourceRoot = resolve(options.sourceRoot ?? defaultSourceRoot(root));\n const enabled = options.enabled ?? Boolean(process.env.TEMPO);\n const excludedDirectories = (options.exclude ?? []).map((directory) =>\n resolve(directory),\n );\n const isSdkFile = createSdkFileMatcher();\n // What `pre` annotated for each module id, for `post` to record. Set or\n // cleared on every `pre` pass, so a skipped pass never records a stale one.\n const annotatedModules = new Map<string, TempoVueSourceRegistryRecord>();\n const warned = new Set<string>();\n\n const identityFor = (id: string) => {\n if (!enabled || id.startsWith(\"\\0\") || !VUE_MAIN_MODULE.test(id)) {\n return null;\n }\n const identity = resolveAnnotationIdentity(id, { root, sourceRoot });\n if (!identity || isSdkFile(identity.absoluteFilename)) return null;\n if (isUnderAny(identity.absoluteFilename, excludedDirectories)) return null;\n return identity;\n };\n\n return [\n {\n name: TEMPO_VUE_ANNOTATION_PLUGIN_NAME,\n enforce: \"pre\",\n // Read by tempoVitePlugin() to report the `vueSourceAnnotation`\n // identity capability: present and enabled means `.vue` files are\n // stamped on this server.\n api: { enabled },\n transform: {\n order: \"pre\",\n filter: { id: VUE_MAIN_MODULE },\n handler(code, id) {\n annotatedModules.delete(id);\n const identity = identityFor(id);\n if (!identity) return undefined;\n let raw: string;\n try {\n raw = readFileSync(identity.absoluteFilename, \"utf8\");\n } catch {\n return undefined;\n }\n const warnOnce = (reason: string, message: string) => {\n const key = `${id}\\0${reason}`;\n if (warned.has(key)) return;\n warned.add(key);\n this.warn(\n `Tempo did not annotate ${identity.filepath}: ${message}`,\n );\n };\n // Offsets must index the authored file. Another `pre` plugin that\n // already rewrote it would make every stamp point elsewhere.\n if (code !== raw) {\n warnOnce(\n \"drift\",\n \"an earlier Vite plugin changed the source; put tempoVuePlugin() first\",\n );\n return undefined;\n }\n const result = annotateVueSource({\n source: code,\n filename: id,\n filepath: identity.filepath,\n modifiedTs: readModifiedTs(identity.absoluteFilename),\n sourceVersion: sourceVersionHash(raw),\n });\n if (result.kind === \"refused\") {\n // plugin-vue reports a source that does not parse itself.\n if (result.code !== \"invalid_source\") {\n warnOnce(result.code, `${result.code}: ${result.message}`);\n }\n return undefined;\n }\n annotatedModules.set(id, result.registry);\n if (result.edits.length === 0) return undefined;\n return { code: result.code, map: result.map };\n },\n },\n },\n {\n name: \"tempo-vue-source-records\",\n enforce: \"post\",\n hotUpdate: {\n order: \"post\",\n handler(context) {\n if (\n context.type !== \"update\" ||\n this.environment.config.consumer !== \"client\" ||\n !identityFor(context.file)\n )\n return;\n if (!annotatedModules.has(context.file)) return;\n // plugin-vue compares authored blocks. A write and its inverse can\n // coalesce back to identical blocks, so it returns no modules even\n // though their source receipts are now stale. Recompile the main\n // module and any separate template through the normal pipeline:\n // only the newly rendered stamps may confirm the newer disk write.\n // Do not compare against the last transform's timestamp: Nuxt's\n // SSR environment may already have compiled the new source while\n // the client still renders the old template.\n const modules = this.environment.moduleGraph.getModulesByFile(\n context.file,\n );\n const stamped = [...(modules ?? [])].filter(\n (module) =>\n module.id === context.file ||\n module.id?.startsWith(`${context.file}?vue&type=template`),\n );\n if (stamped.length)\n return [...new Set([...context.modules, ...stamped])];\n },\n },\n transform: {\n filter: { id: VUE_MAIN_MODULE },\n handler(code, id) {\n const registry = annotatedModules.get(id);\n if (!registry) return undefined;\n const withRegistry = appendVueSourceRegistryRecord(code, registry);\n return {\n code: appendModuleVersionRecord(\n withRegistry,\n registry.filepath,\n registry.modifiedTs,\n registry.sourceVersion,\n ),\n // Appended after the last line: no mapping moves.\n map: null,\n };\n },\n },\n },\n ];\n}\n\nexport interface TempoVueAppPluginsOptions {\n /** The canvas host's Vite root (`tempo/`). */\n root: string;\n /** The folder holding the app's own vite.config. */\n appRoot: string;\n /** The host's `@vitejs/plugin-vue` factory, called only when the app's\n * config has no plugin-vue of its own or cannot load. */\n vue: () => PluginOption;\n /** App plugin names (or name prefixes) the host leaves out, for a plugin\n * the host config adds its own copy of after this call. */\n exclude?: string[];\n}\n\n/**\n * The app's own Vite plugins for Tempo's Vue canvas host, taken from the\n * app's vite.config: auto-imports, auto-registered components, macros, the\n * typed router, i18n, UnoCSS. The app's `@vitejs/plugin-vue` compiles its\n * components with the options and position the app gave it; `vue` builds the\n * host's own only when the app has none. List it after `...tempoVuePlugin()`,\n * which must stamp each `.vue` file before any app plugin rewrites it. Never\n * rejects: a config that cannot load leaves the host's `vue()` and a warning.\n */\nexport function tempoVueAppPlugins(\n options: TempoVueAppPluginsOptions,\n): Promise<PluginOption[]> {\n return loadAppVitePlugins({\n hostRoot: options.root,\n appRoot: options.appRoot,\n compiler: { name: \"vite:vue\", fallback: options.vue },\n exclude: options.exclude,\n });\n}\n\nfunction isUnderAny(file: string, directories: string[]): boolean {\n return directories.some((directory) => {\n const relativePath = relative(directory, file);\n return (\n relativePath === \"\" ||\n (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath))\n );\n });\n}\n","/**\n * Escape text for a quoted Vue template attribute value. The template\n * parser decodes HTML entities in attribute values, so the escaped text reads\n * back as exactly `value`. Vue does not interpolate inside attribute values,\n * so braces need no escaping (Svelte's do). A double quote is always an\n * entity; a single quote is one only inside single quotes.\n */\nexport function escapeVueAttributeValue(\n value: string,\n quote: '\"' | \"'\" = '\"',\n): string {\n const escaped = value\n .split(\"&\")\n .join(\"&amp;\")\n .split('\"')\n .join(\"&quot;\")\n .split(\"<\")\n .join(\"&lt;\")\n .split(\">\")\n .join(\"&gt;\");\n return quote === \"'\" ? escaped.split(\"'\").join(\"&#39;\") : escaped;\n}\n\n/**\n * Escape text for a Vue template text node: `&` and `<` as entities, and\n * `{` and `}` as character references so a typed `{{` never becomes an\n * interpolation. The parser decodes all four back.\n */\nexport function escapeVueText(value: string): string {\n return value\n .split(\"&\")\n .join(\"&amp;\")\n .split(\"<\")\n .join(\"&lt;\")\n .split(\"{\")\n .join(\"&#123;\")\n .split(\"}\")\n .join(\"&#125;\");\n}\n","/**\n * The two spellings of a CSS property the canvas uses: the CSS name a\n * markup `style` declaration writes (`background-image`, `-ms-flex`) and the\n * key a JSX style object uses for it (`backgroundImage`, `msFlex`), which is\n * also how `style.<key>` expression facts name it (`expression-facts.ts`).\n * Custom properties (`--gap`) are spelled the same both ways.\n */\n\n/** The JSX style-object key for a CSS property: dashes camelCase, except\n * that `-ms-` drops its leading dash (React's `msFlex`, where `-webkit-`\n * gives `WebkitBox`). */\nexport function camelCaseStyleKey(property: string): string {\n if (property.startsWith(\"--\")) return property;\n return property\n .replace(/^-ms-/, \"ms-\")\n .replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/** The CSS property a JSX style-object key names; the inverse of\n * `camelCaseStyleKey`. */\nexport function kebabCaseStyleKey(key: string): string {\n if (key.startsWith(\"--\")) return key;\n return key\n .replace(/^ms(?=[A-Z])/, \"-ms\")\n .replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n","/**\n * The Vue compiler functions the editor calls. Every value import of the\n * compiler goes through here, as `#vue-compiler` (package.json \"imports\"),\n * so a bundler can swap in `compiler-deferred.ts`; the other modules import\n * only its types.\n */\nexport { babelParse, compileTemplate, parse } from \"vue/compiler-sfc\";\n","import type {\n Expression,\n Node as BabelNode,\n ObjectExpression,\n Statement,\n} from \"@babel/types\";\nimport type {\n AttributeNode,\n DirectiveNode,\n ElementNode,\n ElementTypes,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { camelCaseStyleKey } from \"@modules/annotation/style-keys\";\nimport type { SFCDescriptor, SFCScriptBlock } from \"vue/compiler-sfc\";\nimport { babelParse, parse as parseSfc } from \"#vue-compiler\";\nimport type {\n VueParseResult,\n VueRootFallthrough,\n VueScriptBlockFacts,\n VueScriptFacts,\n VueScriptImport,\n VueTargetInfo,\n VueTargetKind,\n VueTargetProp,\n} from \"./types\";\n\n// compiler-core's enum values, typed as their members so comparisons narrow\n// the AST unions. They are read through `vue/compiler-sfc` at runtime: `vue`\n// is the only Vue package a consumer is guaranteed to resolve, and its\n// compiler is the exact one @vitejs/plugin-vue compiles the file with.\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\nconst TEXT_NODE = 2 as NodeTypes.TEXT;\nconst COMMENT_NODE = 3 as NodeTypes.COMMENT;\nconst SIMPLE_EXPRESSION_NODE = 4 as NodeTypes.SIMPLE_EXPRESSION;\nconst INTERPOLATION_NODE = 5 as NodeTypes.INTERPOLATION;\nconst ATTRIBUTE_NODE = 6 as NodeTypes.ATTRIBUTE;\nconst NATIVE_TAG = 0 as ElementTypes.ELEMENT;\nconst COMPONENT_TAG = 1 as ElementTypes.COMPONENT;\n/** `<template>` carrying v-if, v-else-if, v-else, v-for or v-slot. */\nconst STRUCTURAL_TEMPLATE_TAG = 3 as ElementTypes.TEMPLATE;\n\n/** Spellings the compiler resolves to a core or runtime-dom built-in. */\nconst BUILT_IN_COMPONENT_TAGS = new Set([\n \"Teleport\",\n \"teleport\",\n \"KeepAlive\",\n \"keep-alive\",\n \"Transition\",\n \"transition\",\n \"TransitionGroup\",\n \"transition-group\",\n \"Suspense\",\n \"suspense\",\n \"BaseTransition\",\n \"base-transition\",\n]);\nconst DYNAMIC_COMPONENT_TAGS = new Set([\"component\", \"Component\"]);\nconst STRUCTURAL_DIRECTIVES = new Set([\"if\", \"else-if\", \"else\", \"for\"]);\nconst CHAIN_OPENING_DIRECTIVES = new Set([\"if\", \"else-if\"]);\nconst CHAIN_CONTINUING_DIRECTIVES = new Set([\"else-if\", \"else\"]);\nconst LIST_DIRECTIVE = new Set([\"for\"]);\nconst SLOT_DIRECTIVE = new Set([\"slot\"]);\n/** Directives whose element's content binds names of its own or renders\n * once per branch or item: moving markup across one changes what it reads. */\nconst SCOPE_DIRECTIVES = new Set([\"if\", \"else-if\", \"else\", \"for\", \"slot\"]);\n\n/** Props Vue's `mergeProps` merges instead of overriding: a bound `class`\n * or `style` applies beside the tag's literal one, and a `v-bind` object's\n * `class` or `style` concatenates with it. The literal therefore stays the\n * authored text a writer edits, and the binding is a fact of its own. */\nexport const VUE_MERGED_PROP_NAMES: ReadonlySet<string> = new Set([\n \"class\",\n \"style\",\n]);\n\n/**\n * Parse a Vue 3 single-file component into its authored template tags,\n * keyed by the exact UTF-16 offset of each `<` in `source`, plus the file's\n * attribute-fallthrough fact. Offsets index the whole file: compiler-sfc\n * parses the SFC once and the template AST keeps absolute locations.\n */\nexport function parseVueSource(\n source: string,\n filename = \"Component.vue\",\n): VueParseResult {\n const { descriptor, errors } = parseSfc(source, {\n filename,\n sourceMap: false,\n });\n if (errors.length > 0) {\n return {\n kind: \"invalid\",\n code: \"invalid_vue\",\n message: errors.map((error) => error.message).join(\"\\n\"),\n };\n }\n const template = descriptor.template;\n if (template?.src) {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: `<template src=\"${template.src}\"> is outside this file, so its offsets cannot describe it`,\n };\n }\n if (template?.lang && template.lang !== \"html\") {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: `<template lang=\"${template.lang}\"> offsets would describe the generated HTML, not this file`,\n };\n }\n /* v8 ignore next 7 -- compiler-sfc omits the AST only for a preprocessed lang, refused above */\n if (template && !template.ast) {\n return {\n kind: \"unsupported\",\n code: \"unsupported_template\",\n message: \"the template has no parsed AST\",\n };\n }\n\n const targets = new Map<number, VueTargetInfo>();\n let templateBindsAttrs = false;\n /** Records every tag under `parent` and answers whether the children are\n * all static (Section 4.6 of the editing spec: no interpolation,\n * directive, bound prop, component, slot, dynamic element or v-pre). */\n const visit = (\n children: readonly TemplateChildNode[],\n parent: VueTargetInfo | null,\n parentNode: ElementNode | null,\n ): boolean => {\n let allStatic = true;\n for (const child of children) {\n if (child.type === INTERPOLATION_NODE) allStatic = false;\n if (child.type !== ELEMENT_NODE) continue;\n const props = child.props.map(readProp);\n // `v-bind=\"$attrs\"` (or any binding reading $attrs) decides by hand\n // where the component's attributes go.\n if (\n props.some(\n (prop) =>\n prop.kind === \"bind\" && /\\$attrs\\b/.test(prop.expression ?? \"\"),\n )\n ) {\n templateBindsAttrs = true;\n }\n const start = child.loc.start.offset;\n const end = child.loc.end.offset;\n const propsEnd =\n props.length > 0\n ? Math.max(...props.map((prop) => prop.end))\n : start + 1 + child.tag.length;\n // Nothing but whitespace, `/` and an attribute the parser keeps out\n // of `props` (`v-pre`) sits between the last prop and the `>`.\n const openingEnd = source.indexOf(\">\", propsEnd) + 1;\n const selfClosing = child.isSelfClosing === true;\n const hasClosingTag = !selfClosing && end > openingEnd;\n const kind = vueTargetKind(child);\n const vPre = carriesVPre(\n source,\n start + 1 + child.tag.length,\n props,\n openingEnd,\n );\n const inVPre = parent !== null && (parent.vPre || parent.inVPre);\n const opensScope =\n kind === \"component\" ||\n kind === \"dynamic-element\" ||\n isBuiltInComponent(child) ||\n child.tag === \"template\" ||\n vPre ||\n hasDirective(child, SCOPE_DIRECTIVES);\n const info: VueTargetInfo = {\n kind,\n tagName: child.tag,\n start,\n end,\n propsEnd,\n props,\n dynamicSlot:\n carriesStructuralDirective(child) || ownsDynamicSlot(parentNode),\n expressionSlot:\n hasDirective(child, LIST_DIRECTIVE) || ownsDynamicSlot(parentNode),\n parentStart: parent?.start ?? null,\n openingEnd,\n selfClosing,\n // The closing tag is the last `</` of the element's own bytes, even\n // in a <textarea> whose text may hold one.\n childrenStart: hasClosingTag ? openingEnd : null,\n childrenEnd: hasClosingTag\n ? start + child.loc.source.lastIndexOf(\"</\")\n : null,\n vPre,\n inVPre,\n opensScope,\n scopeOwner:\n parent === null\n ? -1\n : parent.opensScope\n ? parent.start\n : parent.scopeOwner,\n staticSubtree: false,\n };\n targets.set(start, info);\n const childrenStatic = visit(child.children, info, child);\n const ownStatic =\n !vPre &&\n props.every((prop) => prop.kind === \"attribute\") &&\n (kind === \"native-element\" || child.tag === \"template\");\n info.staticSubtree = ownStatic && childrenStatic;\n if (!info.staticSubtree) allStatic = false;\n }\n return allStatic;\n };\n if (template?.ast) visit(template.ast.children, null, null);\n\n const setupBody = descriptor.scriptSetup\n ? parseScriptBody(descriptor.scriptSetup)\n : null;\n return {\n kind: \"ok\",\n template: template\n ? {\n contentStart: template.loc.start.offset,\n contentEnd: template.loc.end.offset,\n }\n : null,\n targets,\n rootFallthrough: readRootFallthrough({\n descriptor,\n setupBody,\n templateBindsAttrs,\n }),\n script: readScriptFacts(descriptor, setupBody),\n };\n}\n\n/** `v-pre` is the one attribute the parser keeps out of `props`; it can\n * only sit in the opening tag's bytes between them. */\nfunction carriesVPre(\n source: string,\n tagNameEnd: number,\n props: readonly VueTargetProp[],\n openingEnd: number,\n): boolean {\n const written = /(?:^|[\\s/])v-pre(?=[\\s/=>]|$)/;\n let cursor = tagNameEnd;\n for (const prop of [...props].sort((a, b) => a.start - b.start)) {\n if (written.test(source.slice(cursor, prop.start))) return true;\n cursor = prop.end;\n }\n return written.test(source.slice(cursor, openingEnd));\n}\n\nfunction isBuiltInComponent(node: ElementNode): boolean {\n return (\n node.tagType === COMPONENT_TAG && BUILT_IN_COMPONENT_TAGS.has(node.tag)\n );\n}\n\nfunction blockFacts(block: SFCScriptBlock): VueScriptBlockFacts {\n return {\n contentStart: block.loc.start.offset,\n contentEnd: block.loc.end.offset,\n lang: block.lang ?? null,\n src: block.src ?? null,\n };\n}\n\nfunction readScriptFacts(\n descriptor: SFCDescriptor,\n setupBody: readonly Statement[] | null,\n): VueScriptFacts {\n const setup = descriptor.scriptSetup;\n const imports: VueScriptImport[] = [];\n for (const statement of setupBody ?? []) {\n if (statement.type !== \"ImportDeclaration\") continue;\n if (statement.importKind === \"type\") continue;\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === \"ImportSpecifier\" &&\n specifier.importKind === \"type\"\n )\n continue;\n imports.push({\n local: specifier.local.name,\n source: statement.source.value,\n kind:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"namespace\"\n : \"named\",\n });\n }\n }\n return {\n setup: setup ? { ...blockFacts(setup), imports } : null,\n classic: descriptor.script ? blockFacts(descriptor.script) : null,\n };\n}\n\nfunction readProp(prop: AttributeNode | DirectiveNode): VueTargetProp {\n const start = prop.loc.start.offset;\n const end = prop.loc.end.offset;\n if (prop.type === ATTRIBUTE_NODE) {\n // The value node's location includes its quotes when it has them.\n const valueLoc = prop.value?.loc;\n const delimiter = valueLoc?.source[0];\n const quote = delimiter === '\"' || delimiter === \"'\" ? delimiter : null;\n return {\n kind: \"attribute\",\n name: prop.name,\n value: prop.value ? prop.value.content : true,\n start,\n end,\n valueStart: valueLoc ? valueLoc.start.offset + (quote ? 1 : 0) : null,\n valueEnd: valueLoc ? valueLoc.end.offset - (quote ? 1 : 0) : null,\n quote,\n };\n }\n /* v8 ignore next -- the parser sets rawName on every directive it creates */\n const rawName = prop.rawName ?? prop.loc.source.split(\"=\")[0]!.trim();\n // The compiler decodes the attribute's entities before it evaluates the\n // expression; the decoded text rides along only where they differ.\n const decoded =\n prop.exp?.type === SIMPLE_EXPRESSION_NODE ? prop.exp.content : undefined;\n const expression =\n prop.exp === undefined\n ? {}\n : {\n expression: prop.exp.loc.source,\n ...(decoded !== undefined && decoded !== prop.exp.loc.source\n ? { decodedExpression: decoded }\n : {}),\n };\n if (prop.name === \"bind\") {\n const arg = prop.arg;\n const staticName =\n arg?.type === SIMPLE_EXPRESSION_NODE && arg.isStatic ? arg.content : null;\n return {\n kind: \"bind\",\n name: staticName,\n objectBind: arg === undefined,\n rawName,\n ...expression,\n ...(staticName === \"style\" ? { styleKeys: boundStyleKeys(prop) } : {}),\n start,\n end,\n };\n }\n return {\n kind: \"directive\",\n name: prop.name,\n rawName,\n ...expression,\n start,\n end,\n };\n}\n\n/**\n * The keys of a `:style` object literal, read from the compiler's own parse\n * of the expression (`exp.ast`, with the TypeScript plugin when the file's\n * script is TS): null for any other value, a spread or a computed key, which\n * leave every property possibly bound. A string key is camelCased the way\n * the canvas spells a style key, so `'margin-top'` and `marginTop` are one\n * fact.\n */\nfunction boundStyleKeys(prop: DirectiveNode): readonly string[] | null {\n const exp = prop.exp;\n if (!exp || exp.type !== SIMPLE_EXPRESSION_NODE) return null;\n let ast: BabelNode | null | false | undefined = exp.ast;\n // compiler-core parses expressions only in its Node build; the browser\n // build (the canvas renderer's certainty probe loads this module there)\n // leaves `exp.ast` unset, so the expression is parsed here the same way.\n if (ast === undefined) {\n try {\n const program = babelParse(`(${exp.content})`, {\n plugins: [\"typescript\"],\n }).program;\n const statement = program.body[0];\n ast =\n statement?.type === \"ExpressionStatement\" ? statement.expression : null;\n } catch {\n ast = null;\n }\n }\n if (!ast) return null;\n const expression = unwrapTypeScript(ast as Expression);\n if (expression.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const property of expression.properties) {\n if (property.type === \"SpreadElement\" || property.computed) return null;\n if (property.key.type === \"Identifier\") keys.push(property.key.name);\n else if (property.key.type === \"StringLiteral\")\n keys.push(camelCaseStyleKey(property.key.value));\n else return null;\n }\n return keys;\n}\n\n/** What an authored tag is to the runtime (`VueTargetKind`). */\nexport function vueTargetKind(node: ElementNode): VueTargetKind {\n // A plain <template> renders an inert DOM template; inside v-pre a\n // <slot> is literal markup. Neither is a layer of its own.\n if (node.tag === \"template\" || node.tag === \"slot\") return \"special-element\";\n if (node.tagType === NATIVE_TAG) return \"native-element\";\n if (node.tagType !== COMPONENT_TAG) return \"special-element\";\n if (BUILT_IN_COMPONENT_TAGS.has(node.tag)) return \"special-element\";\n if (DYNAMIC_COMPONENT_TAGS.has(node.tag)) return \"dynamic-element\";\n return \"component\";\n}\n\nfunction hasDirective(node: ElementNode, names: ReadonlySet<string>): boolean {\n return node.props.some(\n (prop) => prop.type !== ATTRIBUTE_NODE && names.has(prop.name),\n );\n}\n\nfunction carriesStructuralDirective(node: ElementNode): boolean {\n return hasDirective(node, STRUCTURAL_DIRECTIVES);\n}\n\n/** A child's slot is dynamic under a structural `<template>` (a loop body,\n * a branch, a named or scoped slot) and under a component that takes its\n * default slot with `v-slot` (a render prop in JSX terms). */\nfunction ownsDynamicSlot(parent: ElementNode | null): boolean {\n if (!parent) return false;\n if (parent.tagType === STRUCTURAL_TEMPLATE_TAG) return true;\n return (\n parent.tagType === COMPONENT_TAG && hasDirective(parent, SLOT_DIRECTIVE)\n );\n}\n\nfunction readRootFallthrough(options: {\n descriptor: SFCDescriptor;\n setupBody: readonly Statement[] | null;\n templateBindsAttrs: boolean;\n}): VueRootFallthrough {\n const inheritAttrs = readInheritAttrs(options.descriptor, options.setupBody);\n if (inheritAttrs === \"unknown\") return \"unknown\";\n if (options.templateBindsAttrs) return \"explicit-attrs\";\n if (inheritAttrs === false) return \"inherit-attrs-false\";\n const ast = options.descriptor.template?.ast;\n if (!ast) return \"unknown\";\n return classifyTemplateRoots(ast.children);\n}\n\n/**\n * The template's roots as Vue's fallthrough sees them: comments and\n * whitespace are not roots, and a v-if / v-else-if / v-else chain renders\n * one branch, so it is one root.\n */\nfunction classifyTemplateRoots(\n children: readonly TemplateChildNode[],\n): VueRootFallthrough {\n const groups: TemplateChildNode[][] = [];\n let chainOpen = false;\n for (const child of children) {\n const isComment = child.type === COMMENT_NODE;\n const isBlankText = child.type === TEXT_NODE && child.content.trim() === \"\";\n if (isComment || isBlankText) continue;\n const element = child.type === ELEMENT_NODE ? child : null;\n const continuesChain =\n chainOpen &&\n element !== null &&\n hasDirective(element, CHAIN_CONTINUING_DIRECTIVES);\n const lastGroup = groups[groups.length - 1];\n if (continuesChain && lastGroup) lastGroup.push(child);\n else groups.push([child]);\n chainOpen =\n element !== null && hasDirective(element, CHAIN_OPENING_DIRECTIVES);\n }\n const [only, ...others] = groups;\n if (!only) return \"unknown\";\n if (others.length > 0) return \"multi-root\";\n\n const branches = only.map(classifyRootBranch);\n if (branches.includes(\"list\")) return \"multi-root\";\n if (branches.every((branch) => branch === \"element\")) return \"single-element\";\n if (branches.every((branch) => branch === \"component\"))\n return \"single-component\";\n return \"unknown\";\n}\n\nfunction classifyRootBranch(\n node: TemplateChildNode,\n): \"element\" | \"component\" | \"list\" | \"other\" {\n if (node.type !== ELEMENT_NODE) return \"other\";\n if (hasDirective(node, LIST_DIRECTIVE)) return \"list\";\n const kind = vueTargetKind(node);\n if (kind === \"native-element\") return \"element\";\n if (kind === \"component\") return \"component\";\n return \"other\";\n}\n\ntype InheritAttrsFact = boolean | \"absent\" | \"unknown\";\n\n/**\n * `inheritAttrs` as the file states it literally. `defineOptions` is spread\n * after the default export's options, so `<script setup>` wins; an object's\n * own key wins over its mixins; anything computed is unknown.\n */\nfunction readInheritAttrs(\n descriptor: SFCDescriptor,\n setupBody: readonly Statement[] | null,\n): boolean | \"unknown\" {\n const fromSetup = descriptor.scriptSetup\n ? readScriptInheritAttrs(setupBody, defineOptionsArgument)\n : \"absent\";\n if (fromSetup !== \"absent\") return fromSetup;\n const fromOptions = descriptor.script\n ? readScriptInheritAttrs(\n parseScriptBody(descriptor.script),\n defaultExportOptions,\n )\n : \"absent\";\n return fromOptions === \"absent\" ? true : fromOptions;\n}\n\ntype OptionsObjectRead = ObjectExpression | \"absent\" | \"unknown\";\n\n/** The block's statements; null when it is external (`src`) or does not\n * parse, which leaves every fact it could state unknown. */\nfunction parseScriptBody(block: SFCScriptBlock): Statement[] | null {\n if (block.src) return null;\n try {\n return babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return null;\n }\n}\n\nfunction readScriptInheritAttrs(\n body: readonly Statement[] | null,\n findOptions: (body: readonly Statement[]) => OptionsObjectRead,\n): InheritAttrsFact {\n if (body === null) return \"unknown\";\n const options = findOptions(body);\n if (options === \"absent\" || options === \"unknown\") return options;\n return readObjectInheritAttrs(options);\n}\n\nexport function babelPluginsFor(\n lang: string | null | undefined,\n): (\"typescript\" | \"jsx\")[] {\n if (lang === \"ts\") return [\"typescript\"];\n if (lang === \"tsx\") return [\"typescript\", \"jsx\"];\n if (lang === \"jsx\") return [\"jsx\"];\n return [];\n}\n\nfunction defineOptionsArgument(body: readonly Statement[]): OptionsObjectRead {\n let found: OptionsObjectRead = \"absent\";\n for (const statement of body) {\n if (statement.type !== \"ExpressionStatement\") continue;\n const call = unwrapTypeScript(statement.expression);\n if (call.type !== \"CallExpression\") continue;\n if (call.callee.type !== \"Identifier\") continue;\n if (call.callee.name !== \"defineOptions\") continue;\n const argument = call.arguments[0];\n const options =\n argument && argument.type !== \"SpreadElement\"\n ? unwrapTypeScript(argument as Expression)\n : null;\n found = options?.type === \"ObjectExpression\" ? options : \"unknown\";\n }\n return found;\n}\n\nfunction defaultExportOptions(body: readonly Statement[]): OptionsObjectRead {\n for (const statement of body) {\n if (statement.type === \"ExportNamedDeclaration\") {\n const reExportsDefault = statement.specifiers.some(\n (specifier) =>\n specifier.exported.type === \"Identifier\" &&\n specifier.exported.name === \"default\",\n );\n if (reExportsDefault) return \"unknown\";\n continue;\n }\n if (statement.type !== \"ExportDefaultDeclaration\") continue;\n const declaration = statement.declaration;\n if (!isExpression(declaration)) return \"unknown\";\n const exported = unwrapTypeScript(declaration);\n if (exported.type === \"ObjectExpression\") return exported;\n const options = defineComponentArgument(exported);\n return options ?? \"unknown\";\n }\n return \"absent\";\n}\n\nfunction defineComponentArgument(\n expression: Expression,\n): ObjectExpression | null {\n if (expression.type !== \"CallExpression\") return null;\n const callee = expression.callee;\n const calleeName =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" &&\n !callee.computed &&\n callee.property.type === \"Identifier\"\n ? callee.property.name\n : null;\n if (calleeName !== \"defineComponent\") return null;\n const argument = expression.arguments[0];\n if (!argument || argument.type === \"SpreadElement\") return null;\n const options = unwrapTypeScript(argument as Expression);\n return options.type === \"ObjectExpression\" ? options : null;\n}\n\n/** Reads the object's own `inheritAttrs` in source order: a later spread or\n * computed key may override it, and with no own key, `extends` or `mixins`\n * may supply one. */\nfunction readObjectInheritAttrs(options: ObjectExpression): InheritAttrsFact {\n let fact: InheritAttrsFact = \"absent\";\n let inherits = false;\n for (const property of options.properties) {\n if (property.type === \"SpreadElement\" || property.computed) {\n fact = \"unknown\";\n continue;\n }\n const key =\n property.key.type === \"Identifier\"\n ? property.key.name\n : property.key.type === \"StringLiteral\"\n ? property.key.value\n : null;\n if (key === \"extends\" || key === \"mixins\") inherits = true;\n if (key !== \"inheritAttrs\") continue;\n fact =\n property.type === \"ObjectProperty\" &&\n property.value.type === \"BooleanLiteral\"\n ? property.value.value\n : \"unknown\";\n }\n if (fact === \"absent\" && inherits) return \"unknown\";\n return fact;\n}\n\nfunction isExpression(node: { type: string }): node is Expression {\n return (\n node.type !== \"FunctionDeclaration\" &&\n node.type !== \"ClassDeclaration\" &&\n node.type !== \"TSDeclareFunction\" &&\n node.type !== \"TSInterfaceDeclaration\" &&\n node.type !== \"TSTypeAliasDeclaration\" &&\n node.type !== \"TSEnumDeclaration\" &&\n node.type !== \"TSModuleDeclaration\"\n );\n}\n\n/** `x as T`, `x satisfies T`, `<T>x` and `x!` all evaluate to `x`. */\nfunction unwrapTypeScript(expression: Expression): Expression {\n let current = expression;\n while (\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\" ||\n current.type === \"ParenthesizedExpression\"\n ) {\n current = current.expression;\n }\n return current;\n}\n","import type { Expression, Node as BabelNode } from \"@babel/types\";\nimport { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport { babelParse } from \"vue/compiler-sfc\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { parseVueSource } from \"./parse\";\nimport type {\n StringEdit,\n VueEditIntent,\n VueEditRefusalCode,\n VueInstanceProps,\n VueJsonValue,\n VueTargetInfo,\n VueTargetProp,\n} from \"./types\";\n\n/** What a template passes a component but no prop receives: the runtime\n * consumes these, `class` and `style` fall through to its root, and\n * `v-on` listeners are events. */\nconst NOT_PROPS = new Set([\n \"key\",\n \"ref\",\n \"ref_for\",\n \"ref_key\",\n \"is\",\n \"class\",\n \"style\",\n \"slot\",\n]);\nconst PROP_NAME = /^[$A-Z_a-z][$\\w]*$/;\n\n/** How the template passes one prop: the authored prop and its literal\n * value, which is `undefined` when code computes it. */\ntype Passed = {\n prop: VueTargetProp;\n /** The name as written (`my-title`, `title`). */\n written: string;\n value: VueJsonValue | undefined;\n};\n\ntype Planned =\n | { kind: \"edits\"; edits: StringEdit[] }\n | { kind: \"noop\" }\n | { kind: \"refused\"; code: VueEditRefusalCode; message: string };\n\n/**\n * The props a component invocation passes at `position` (its `<`), by the\n * name the component declares them under: Vue matches `my-title` to a\n * `myTitle` prop. A static attribute is its decoded value (a bare one is\n * `true`); a binding whose expression is a JSON-shaped literal\n * (`:count=\"3\"`, `:tags=\"['a']\"`) is that value; any other binding, a\n * same-name shorthand and `v-model` are the code that computes them. An\n * object bind or a dynamic argument may pass any prop: it is the `spread`,\n * and every prop written before it reads as that code, since a later bind\n * wins. Null when no component invocation starts at `position`.\n */\nexport function readVueInstanceProps(\n source: string,\n file: string,\n position: number,\n): VueInstanceProps | null {\n const parsed = parseVueSource(source, file);\n const target = parsed.kind === \"ok\" ? parsed.targets.get(position) : null;\n if (target?.kind !== \"component\") return null;\n return {\n sourceVersion: sourceVersionHash(source),\n tag: target.tagName,\n ...readVuePassedProps(source, target.props),\n };\n}\n\n/** What an invocation's authored `props` pass, read as\n * `readVueInstanceProps` describes. The annotator records the literal\n * ones, so the canvas can tell what a prop edit wrote after a reload. */\nexport function readVuePassedProps(\n source: string,\n props: readonly VueTargetProp[],\n): Pick<VueInstanceProps, \"props\" | \"spread\"> {\n const result: Pick<VueInstanceProps, \"props\" | \"spread\"> = {\n props: Object.create(null),\n };\n for (const prop of props) {\n if (opensEverything(prop)) {\n const spread = source.slice(prop.start, prop.end);\n result.spread = result.spread ? `${result.spread} ${spread}` : spread;\n for (const name of Object.keys(result.props))\n result.props[name] = { expression: result.spread };\n continue;\n }\n const passed = passedProp(prop);\n if (!passed) continue;\n const name = camelize(passed.written);\n result.props[name] =\n passed.value === undefined\n ? { expression: expressionText(prop) }\n : { value: passed.value };\n }\n return result;\n}\n\n/**\n * Write one prop at a component invocation, as a React literal prop is\n * written: a string as a static attribute (`title=\"Hi\"`), any other JSON\n * value as a literal binding (`:count=\"3\"`), in place of the literal the\n * template already passes or after the last authored prop. Removing it\n * removes what the template passes, so the component's default applies.\n * A prop the template computes with code (a binding, `v-model`) changes\n * only through AI; a prop an object bind may pass is written only when\n * the caller confirms the written one wins (`replaceExpression`).\n */\nexport function planComponentProp(\n source: string,\n target: VueTargetInfo,\n intent: Extract<VueEditIntent, { kind: \"set-component-prop\" }>,\n): Planned {\n const { name, value } = intent;\n if (target.kind !== \"component\")\n return refused(\n \"unsupported_target\",\n `<${target.tagName}> is not a component invocation; it has no props`,\n );\n if (!PROP_NAME.test(name) || NOT_PROPS.has(name))\n return refused(\n \"invalid_attribute_name\",\n `${JSON.stringify(name)} is not an editable component prop`,\n );\n const passed = target.props.flatMap((prop) => {\n const entry = passedProp(prop);\n return entry && camelize(entry.written) === name ? [entry] : [];\n });\n if (passed.length > 1)\n return refused(\n \"duplicate_attribute\",\n `The call site passes ${name} more than once; remove the duplicate in code`,\n );\n const current = passed[0];\n const lastSpread = Math.max(\n -1,\n ...target.props.filter(opensEverything).map((prop) => prop.start),\n );\n const spread = lastSpread >= 0;\n const computed = current !== undefined && current.value === undefined;\n // A later object bind may pass the prop instead of what is written.\n const shadowed = current !== undefined && current.prop.start < lastSpread;\n if (\n current?.prop.kind === \"directive\" ||\n (computed && !intent.replaceExpression)\n )\n return refused(\n \"dynamic_attribute\",\n `${name} is computed by code at the call site; changing it requires AI`,\n );\n if ((shadowed || (!current && spread)) && !intent.replaceExpression)\n return refused(\n \"spread_attribute\",\n `A v-bind object may pass ${name}; writing it here requires confirming the written value wins`,\n );\n if (value === undefined && spread)\n return refused(\n \"spread_attribute\",\n `A v-bind object may pass ${name}; remove it in code to use the component's default`,\n );\n const unchanged =\n !computed &&\n !spread &&\n JSON.stringify(current?.value) === JSON.stringify(value);\n if (unchanged) return { kind: \"noop\" };\n if (value === undefined)\n return {\n kind: \"edits\",\n edits: current ? [removal(source, current.prop)] : [],\n };\n // In place, the template keeps its spelling of the name. Otherwise the\n // prop is written after every authored prop, so it wins over an object\n // bind as the confirmation promised.\n const quote =\n current?.prop.kind === \"attribute\" ? (current.prop.quote ?? '\"') : '\"';\n const spelled = propText(current?.written ?? name, value, quote);\n if (current && !shadowed)\n return {\n kind: \"edits\",\n edits: [\n {\n start: current.prop.start,\n end: current.prop.end,\n replacement: spelled,\n },\n ],\n };\n return {\n kind: \"edits\",\n edits: [\n ...(current ? [removal(source, current.prop)] : []),\n {\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: ` ${spelled}`,\n },\n ],\n };\n}\n\n/** An object bind (`v-bind=\"attrs\"`) or a dynamic argument (`:[key]`),\n * which can pass any prop. */\nfunction opensEverything(prop: VueTargetProp): boolean {\n return prop.kind === \"bind\" && (prop.objectBind || prop.name === null);\n}\n\n/** The prop an authored attribute, binding or `v-model` passes, or null\n * for anything that passes none (a listener, a structural directive,\n * `class`, `key`). */\nfunction passedProp(prop: VueTargetProp): Passed | null {\n if (prop.kind === \"attribute\")\n return NOT_PROPS.has(prop.name)\n ? null\n : { prop, written: prop.name, value: prop.value };\n if (prop.kind === \"bind\") {\n if (prop.name === null || NOT_PROPS.has(prop.name)) return null;\n return {\n prop,\n written: prop.name,\n value:\n prop.expression === undefined\n ? undefined\n : literalValue(prop.decodedExpression ?? prop.expression),\n };\n }\n if (prop.name !== \"model\") return null;\n // `v-model` passes `modelValue`, `v-model:title` passes `title`; a\n // dynamic argument may pass any prop and is no single name.\n const argument = /^v-model(?::([^.\\s[]+))?/.exec(prop.rawName);\n if (!argument) return null;\n return { prop, written: argument[1] ?? \"modelValue\", value: undefined };\n}\n\n/** The code a computed prop shows: its expression, or for a same-name\n * shorthand (`:title`) the name it reads. */\nfunction expressionText(prop: VueTargetProp): string {\n if (prop.kind !== \"attribute\" && prop.expression !== undefined)\n return prop.decodedExpression ?? prop.expression;\n if (prop.kind === \"attribute\") return prop.name;\n return prop.kind === \"bind\" && prop.name !== null\n ? camelize(prop.name)\n : prop.rawName;\n}\n\n/** A JSON-shaped literal expression's value: a string, number, boolean or\n * null, or an array or object of them; `undefined` for any other code. */\nfunction literalValue(expression: string): VueJsonValue | undefined {\n let node: BabelNode | undefined;\n try {\n const statement = babelParse(`(${expression})`, {\n sourceType: \"module\",\n }).program.body[0];\n node =\n statement?.type === \"ExpressionStatement\"\n ? statement.expression\n : undefined;\n } catch {\n return undefined;\n }\n return node ? literalOf(node) : undefined;\n}\n\nfunction literalOf(node: BabelNode): VueJsonValue | undefined {\n switch (node.type) {\n case \"StringLiteral\":\n case \"BooleanLiteral\":\n return node.value;\n case \"NumericLiteral\":\n return Number.isFinite(node.value) ? node.value : undefined;\n case \"NullLiteral\":\n return null;\n case \"TemplateLiteral\":\n return node.expressions.length === 0\n ? (node.quasis[0]?.value.cooked ?? undefined)\n : undefined;\n case \"UnaryExpression\":\n return node.operator === \"-\" && node.argument.type === \"NumericLiteral\"\n ? -node.argument.value\n : undefined;\n case \"ArrayExpression\": {\n const values = node.elements.map((element) =>\n element && element.type !== \"SpreadElement\"\n ? literalOf(element)\n : undefined,\n );\n return values.includes(undefined)\n ? undefined\n : (values as VueJsonValue[]);\n }\n case \"ObjectExpression\": {\n const object: Record<string, VueJsonValue> = Object.create(null);\n for (const property of node.properties) {\n if (property.type !== \"ObjectProperty\" || property.computed)\n return undefined;\n const key =\n property.key.type === \"Identifier\"\n ? property.key.name\n : property.key.type === \"StringLiteral\"\n ? property.key.value\n : null;\n const value = literalOf(property.value as Expression);\n if (key === null || value === undefined) return undefined;\n object[key] = value;\n }\n return object;\n }\n default:\n return undefined;\n }\n}\n\n/** The prop as template text: a string as a static attribute in `quote`,\n * anything else bound to its JavaScript literal, whose strings are\n * single-quoted so the attribute's double quotes stay readable. */\nfunction propText(name: string, value: VueJsonValue, quote: '\"' | \"'\"): string {\n return typeof value === \"string\"\n ? `${name}=${quote}${escapeVueAttributeValue(value, quote)}${quote}`\n : `:${name}=\"${escapeVueAttributeValue(javascriptLiteral(value))}\"`;\n}\n\nfunction javascriptLiteral(value: VueJsonValue): string {\n if (typeof value === \"string\")\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\")}'`;\n if (value === null || typeof value !== \"object\") return String(value);\n if (Array.isArray(value))\n return `[${value.map(javascriptLiteral).join(\", \")}]`;\n const entries = Object.entries(value).map(\n ([key, entry]) =>\n `${PROP_NAME.test(key) ? key : javascriptLiteral(key)}: ${javascriptLiteral(entry)}`,\n );\n return entries.length ? `{ ${entries.join(\", \")} }` : \"{}\";\n}\n\n/** The prop and the whitespace before it, so no gap is left. */\nfunction removal(source: string, prop: VueTargetProp): StringEdit {\n let start = prop.start;\n while (start > 0 && /\\s/.test(source[start - 1]!)) start -= 1;\n return { start, end: prop.end, replacement: \"\" };\n}\n\n/** Vue's prop-name normalization: `my-title` is the `myTitle` prop. */\nfunction camelize(name: string): string {\n return name.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n}\n\nfunction refused(code: VueEditRefusalCode, message: string): Planned {\n return { kind: \"refused\", code, message };\n}\n","import {\n DYNAMIC_SLOT_FACT,\n EXPRESSION_FACTS_ATTRIBUTE,\n} from \"@modules/annotation/expression-facts\";\nimport { sourceVersionHash } from \"@modules/annotation/source-version\";\nimport MagicString, { type SourceMap } from \"magic-string\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { parseVueSource, VUE_MERGED_PROP_NAMES } from \"./parse\";\nimport {\n TEMPO_VUE_INVOCATION_MARKER_PREFIX,\n TEMPO_VUE_SOURCE_REGISTRY_GLOBAL,\n type TempoVueComponentSourceRecord,\n type TempoVueHostSourceRecord,\n type TempoVueSourceRegistryRecord,\n} from \"./records\";\nimport { readVuePassedProps } from \"./component-props\";\nimport type {\n StringEdit,\n VueJsonValue,\n VueTargetInfo,\n VueTargetProp,\n} from \"./types\";\n\nconst TEMPO_STAMP_NAMES = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n] as const;\nconst TEMPO_ANNOTATION_NAMES: ReadonlySet<string> = new Set([\n ...TEMPO_STAMP_NAMES,\n EXPRESSION_FACTS_ATTRIBUTE,\n]);\n\n/**\n * Spellings that all compile to the reserved `onVnodeBeforeMount` prop. A\n * reserved prop never reaches `attrs` or the DOM, so it cannot fall through\n * to the invoked component's root, survives `cloneVNode`, and raises no\n * multi-root warning. A component that already has one spelling gets the\n * next: the parser rejects a repeated attribute name, while distinct\n * spellings of one vnode hook merge into an array.\n */\nconst INVOCATION_MARKER_SPELLINGS = [\n \"@vue:before-mount\",\n \"v-on:vue:before-mount\",\n \"@vue:beforeMount\",\n \"v-on:vue:beforeMount\",\n] as const;\nconst INVOCATION_MARKER_EXPRESSION = /^function __tempo_c(\\d+)\\(\\)\\{\\}$/;\n\n/** Bound or literal names that never render and so are never facts (JSX\n * skips `key` and `ref` alike). */\nconst UNRENDERED_PROP_NAMES = new Set([\"key\", \"ref\", \"ref_for\", \"ref_key\"]);\n\nexport interface AnnotateVueSourceOptions {\n source: string;\n /** The module id: the absolute path the dev build stores as `__file`. */\n filename: string;\n filepath: string;\n modifiedTs: number;\n /** Version identity of the file; defaults to the annotation-free source's\n * `sourceVersionHash`. */\n sourceVersion?: string;\n}\n\nexport type AnnotateVueSourceResult =\n | {\n kind: \"ok\";\n code: string;\n map: SourceMap;\n /** Insertion offsets in the source passed to this call. */\n edits: readonly StringEdit[];\n /** Native elements stamped by this call. */\n elementsAnnotated: number;\n /** Annotation-free offsets of tags whose existing annotation already\n * matched exactly and was kept. */\n skippedExistingAnnotations: readonly number[];\n sourceVersion: string;\n registry: TempoVueSourceRegistryRecord;\n }\n | {\n kind: \"refused\";\n code:\n | \"invalid_metadata\"\n | \"invalid_source\"\n | \"unsupported_template\"\n | \"annotation_conflict\"\n | \"invalid_output\";\n message: string;\n };\n\ntype Refusal = Extract<AnnotateVueSourceResult, { kind: \"refused\" }>;\n\ninterface StampMetadata {\n filepath: string;\n position: number;\n modifiedTs: number;\n sourceVersion: string;\n}\n\ntype ExistingAnnotation =\n | {\n kind: \"stamps\";\n metadata: StampMetadata;\n expressions: string | undefined;\n removal: StringEdit;\n }\n | {\n kind: \"marker\";\n spelling: string;\n position: number;\n removal: StringEdit;\n };\n\n/**\n * Pure Vue SFC annotation with exact original UTF-16 anchors. Native\n * template elements get the four `data-tempo-*` stamps (plus\n * `data-tempo-expr` when they have expression facts) after their last prop;\n * component invocations get a reserved vnode-hook marker. `<script>` blocks\n * are never touched, so @vitejs/plugin-vue's template-only HMR detection\n * keeps working on the annotated file.\n */\nexport function annotateVueSource(\n options: AnnotateVueSourceOptions,\n): AnnotateVueSourceResult {\n if (\n !options.filepath ||\n !options.filename ||\n !Number.isSafeInteger(options.modifiedTs) ||\n options.modifiedTs < 0 ||\n options.sourceVersion === \"\"\n ) {\n return refused(\n \"invalid_metadata\",\n \"filename, filepath, a non-negative integer modifiedTs, and a non-empty sourceVersion are required\",\n );\n }\n const parsed = parseVueSource(options.source, options.filename);\n if (parsed.kind === \"invalid\")\n return refused(\"invalid_source\", parsed.message);\n if (parsed.kind === \"unsupported\")\n return refused(\"unsupported_template\", parsed.message);\n\n // Existing annotations are kept only when they are exactly what this call\n // would write; positions always index the annotation-free source.\n const existing = new Map<number, ExistingAnnotation>();\n for (const target of parsed.targets.values()) {\n const read = readExistingAnnotation(options.source, target);\n if (read === null) continue;\n if (read.kind === \"refused\") return read;\n existing.set(target.start, read);\n }\n const removals = [...existing.values()].map((read) => read.removal);\n const baseOffset = (offset: number) =>\n offset -\n removals\n .filter((removal) => removal.end <= offset)\n .reduce((total, removal) => total + removal.end - removal.start, 0);\n const version =\n options.sourceVersion ??\n sourceVersionHash(removeRanges(options.source, removals));\n\n const edits: StringEdit[] = [];\n const hosts: TempoVueHostSourceRecord[] = [];\n const components: TempoVueComponentSourceRecord[] = [];\n const skippedExistingAnnotations: number[] = [];\n let elementsAnnotated = 0;\n for (const target of parsed.targets.values()) {\n const isHost = target.kind === \"native-element\";\n const isInvocation =\n target.kind === \"component\" || target.kind === \"dynamic-element\";\n if (!isHost && !isInvocation) continue;\n const position = baseOffset(target.start);\n // Hosts carry stamps and invocations carry a marker; anything else that\n // looks like either is the author's own prop.\n const isAnnotation = isHost ? isStampProp : isMarkerProp;\n const authored = target.props.filter((prop) => !isAnnotation(prop));\n const facts = authoredFacts(target, authored, position);\n const prior = existing.get(target.start);\n\n if (isHost) {\n const metadata: StampMetadata = {\n filepath: options.filepath,\n position,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n };\n // A host's facts travel only in its stamp; the record omits them.\n hosts.push({ kind: \"host\", ...facts.record });\n if (prior) {\n const matches =\n prior.kind === \"stamps\" &&\n sameStampMetadata(prior.metadata, metadata) &&\n prior.expressions === facts.expressions;\n if (!matches) return identityConflict(target.start);\n skippedExistingAnnotations.push(position);\n continue;\n }\n edits.push({\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: serializeStamps(metadata, facts.expressions),\n });\n elementsAnnotated += 1;\n continue;\n }\n\n const spelling = markerSpellingFor(authored);\n // Every spelling is already authored: this site gets no identity\n // rather than a duplicate prop the parser would reject.\n if (spelling === null) continue;\n // An invocation has no element to stamp, so its record carries them.\n const literalProps = literalPropsOf(options.source, authored);\n components.push({\n kind: \"component\",\n ...facts.record,\n ...facts.locked,\n expressions: facts.expressions,\n ...(literalProps ? { literalProps } : {}),\n });\n if (prior) {\n const matches =\n prior.kind === \"marker\" &&\n prior.position === position &&\n prior.spelling === spelling;\n if (!matches) return identityConflict(target.start);\n skippedExistingAnnotations.push(position);\n continue;\n }\n edits.push({\n start: target.propsEnd,\n end: target.propsEnd,\n replacement: serializeMarker(spelling, position),\n });\n }\n\n const magic = new MagicString(options.source);\n for (const edit of edits) magic.appendLeft(edit.start, edit.replacement);\n const code = magic.toString();\n const reparsed = parseVueSource(code, options.filename);\n /* v8 ignore next 10 -- static attributes and a function-expression vnode hook appended after the last prop preserve SFC syntax */\n if (reparsed.kind !== \"ok\" || reparsed.targets.size !== parsed.targets.size) {\n return refused(\n \"invalid_output\",\n reparsed.kind === \"ok\"\n ? \"annotation changed the template's tag structure\"\n : reparsed.message,\n );\n }\n return {\n kind: \"ok\",\n code,\n map: magic.generateMap({\n source: options.filename,\n includeContent: true,\n hires: true,\n }),\n edits,\n elementsAnnotated,\n skippedExistingAnnotations,\n sourceVersion: version,\n registry: {\n filename: options.filename,\n filepath: options.filepath,\n modifiedTs: options.modifiedTs,\n sourceVersion: version,\n components,\n hosts,\n rootFallthrough: parsed.rootFallthrough,\n },\n };\n}\n\n/** The props an invocation passes as literals, by declared name; undefined\n * when it passes none. A prop edit's history compares these after a reload\n * to tell whether the file still holds what the edit wrote. */\nfunction literalPropsOf(\n source: string,\n props: readonly VueTargetProp[],\n): Record<string, VueJsonValue> | undefined {\n // Tempo's own attributes (`data-tempo-locked`) are metadata, not props.\n const passing = props.filter(\n (prop) =>\n !(prop.kind === \"attribute\" && prop.name.startsWith(\"data-tempo-\")),\n );\n const literals = Object.entries(readVuePassedProps(source, passing).props)\n .filter(([, passed]) => \"value\" in passed)\n .map(([name, passed]) => [name, passed.value as VueJsonValue] as const);\n return literals.length > 0 ? Object.fromEntries(literals) : undefined;\n}\n\n/**\n * Append the statement that registers a file's record when its module\n * evaluates in a browser. Registration replaces the entry, so an HMR\n * re-evaluation leaves the newest record. It goes at the end and adds no\n * line above existing code, like the module version record.\n */\nexport function appendVueSourceRegistryRecord(\n source: string,\n registry: TempoVueSourceRegistryRecord,\n): string {\n const registryObject = `(globalThis.${TEMPO_VUE_SOURCE_REGISTRY_GLOBAL} || (globalThis.${TEMPO_VUE_SOURCE_REGISTRY_GLOBAL} = {}))`;\n return `${source}\\n;typeof window !== \"undefined\" && (${registryObject}[${JSON.stringify(registry.filepath)}] = ${JSON.stringify(registry)});\\n`;\n}\n\n/**\n * The record fields one tag's authored props prove, read in source order as\n * Vue merges them: an object bind overrides what comes before it (except\n * `class` and `style`, which it concatenates), a computed name may override\n * anything before it. `expressions` is the tag's `data-tempo-expr` value,\n * undefined when it gets none.\n */\nfunction authoredFacts(\n target: VueTargetInfo,\n props: readonly VueTargetProp[],\n position: number,\n): {\n record: {\n name: string;\n position: number;\n className?: string;\n style?: string;\n supportsClassName: boolean;\n supportsStyle: boolean;\n };\n expressions: string | undefined;\n locked: { locked?: boolean };\n} {\n const lastObjectBind = lastIndexWhere(\n props,\n (prop) => prop.kind === \"bind\" && prop.objectBind,\n );\n const lastComputedName = lastIndexWhere(\n props,\n (prop) => prop.kind === \"bind\" && prop.name === null && !prop.objectBind,\n );\n const canOverrideAnything = lastObjectBind >= 0 || lastComputedName >= 0;\n const facts = new Set<string>();\n if (target.expressionSlot) facts.add(DYNAMIC_SLOT_FACT);\n const literals = new Map<string, string | true>();\n const bound = new Set<string>();\n props.forEach((prop, index) => {\n if (prop.kind === \"directive\") {\n // A loop is the `#slot` fact (expressionSlot). Every other directive\n // is a fact in its own spelling, a v-if chain branch's included: the\n // page cannot show it, so a text run ends at its element, while its\n // place stays a literal position its chain moves from.\n if (prop.name !== \"for\") facts.add(prop.rawName);\n return;\n }\n if (prop.name === null || !isRenderedName(prop.name)) return;\n if (prop.kind === \"bind\") {\n // A `:style` object literal with static keys binds only those keys,\n // as a JSX style object does: every other property stays a static\n // write (the writer's `style_write_admitted` answers the same). The\n // tag still supports a literal style, at a host and at a call site\n // alike; the per-key facts route the bound keys to AI.\n if (prop.name === \"style\" && Array.isArray(prop.styleKeys)) {\n for (const key of prop.styleKeys) facts.add(`style.${key}`);\n return;\n }\n bound.add(prop.name);\n facts.add(factName(prop.name));\n return;\n }\n literals.set(prop.name, prop.value);\n const overriddenByObject =\n index < lastObjectBind && !VUE_MERGED_PROP_NAMES.has(prop.name);\n const overriddenByComputedName = index < lastComputedName;\n if (overriddenByObject || overriddenByComputedName)\n facts.add(factName(prop.name));\n });\n\n const className = literals.get(\"class\");\n const style = literals.get(\"style\");\n const lock = target.props.find(\n (prop) => prop.kind === \"attribute\" && prop.name === \"data-tempo-locked\",\n );\n const lockValue = lock?.kind === \"attribute\" ? lock.value : undefined;\n const expressions = [...facts].join(\" \");\n return {\n record: {\n name: target.tagName,\n position,\n ...(typeof className === \"string\" ? { className } : {}),\n ...(typeof style === \"string\" ? { style } : {}),\n supportsClassName:\n !canOverrideAnything &&\n !bound.has(\"class\") &&\n (className === undefined || typeof className === \"string\"),\n supportsStyle:\n !canOverrideAnything &&\n !bound.has(\"style\") &&\n (style === undefined || typeof style === \"string\"),\n },\n // An object bind or computed name gets a stamp even with no fact, as a\n // JSX spread does: what it sets is unknown until runtime.\n expressions: expressions || canOverrideAnything ? expressions : undefined,\n locked:\n lockValue === true || lockValue === \"true\" || lockValue === \"\"\n ? { locked: true }\n : lockValue === \"false\"\n ? { locked: false }\n : {},\n };\n}\n\nfunction lastIndexWhere<T>(\n items: readonly T[],\n predicate: (item: T) => boolean,\n): number {\n for (let index = items.length - 1; index >= 0; index--) {\n if (predicate(items[index]!)) return index;\n }\n return -1;\n}\n\nfunction isRenderedName(name: string): boolean {\n return !UNRENDERED_PROP_NAMES.has(name) && !name.startsWith(\"data-tempo-\");\n}\n\nfunction factName(name: string): string {\n return name === \"class\" ? \"className\" : name;\n}\n\n/** A Tempo stamp name, literal or (conflicting) bound. */\nfunction isStampProp(prop: VueTargetProp): boolean {\n return (\n prop.kind !== \"directive\" &&\n prop.name !== null &&\n TEMPO_ANNOTATION_NAMES.has(prop.name)\n );\n}\n\n/** This annotator's invocation marker. */\nfunction isMarkerProp(prop: VueTargetProp): boolean {\n return (\n prop.kind === \"directive\" &&\n (INVOCATION_MARKER_SPELLINGS as readonly string[]).includes(prop.rawName) &&\n INVOCATION_MARKER_EXPRESSION.test(prop.expression ?? \"\")\n );\n}\n\nfunction markerSpellingFor(authored: readonly VueTargetProp[]): string | null {\n const taken = new Set(\n authored.flatMap((prop) =>\n prop.kind === \"attribute\" ? [] : [prop.rawName],\n ),\n );\n return (\n INVOCATION_MARKER_SPELLINGS.find((spelling) => !taken.has(spelling)) ?? null\n );\n}\n\n/**\n * A tag's existing Tempo annotation, which must be complete, static, last,\n * and byte-identical to what this annotator serializes; anything else is a\n * conflict, never silently rewritten. Native elements carry stamps;\n * invocations carry a marker. `null` when the tag has none.\n */\nfunction readExistingAnnotation(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n if (target.kind === \"native-element\")\n return readExistingStamps(source, target);\n if (target.kind === \"component\" || target.kind === \"dynamic-element\")\n return readExistingMarker(source, target);\n return null;\n}\n\nfunction readExistingStamps(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n const annotation = target.props.filter(isStampProp);\n if (annotation.length === 0) return null;\n const expectedNames = [\n ...TEMPO_STAMP_NAMES,\n ...(annotation.length > TEMPO_STAMP_NAMES.length\n ? [EXPRESSION_FACTS_ATTRIBUTE]\n : []),\n ];\n const trailing = target.props.slice(-annotation.length);\n const values = trailing.map((prop) =>\n prop.kind === \"attribute\" && typeof prop.value === \"string\"\n ? prop.value\n : null,\n );\n const wellFormed =\n annotation.length === expectedNames.length &&\n trailing.every(\n (prop, index) =>\n prop === annotation[index] &&\n prop.kind === \"attribute\" &&\n prop.name === expectedNames[index] &&\n values[index] !== null,\n );\n if (!wellFormed) return annotationConflict(target.start);\n const [filepath, positionText, modifiedText, sourceVersion, expressions] =\n values as string[];\n const position = Number(positionText);\n const modifiedTs = Number(modifiedText);\n const first = trailing[0]!;\n const last = trailing[trailing.length - 1]!;\n if (\n !filepath ||\n !sourceVersion ||\n !Number.isSafeInteger(position) ||\n position < 0 ||\n !Number.isSafeInteger(modifiedTs) ||\n modifiedTs < 0\n ) {\n return annotationConflict(target.start);\n }\n const metadata = { filepath, position, modifiedTs, sourceVersion };\n const removal = { start: first.start - 1, end: last.end, replacement: \"\" };\n const written = source.slice(removal.start, removal.end);\n if (written !== serializeStamps(metadata, expressions))\n return annotationConflict(target.start);\n return { kind: \"stamps\", metadata, expressions, removal };\n}\n\nfunction readExistingMarker(\n source: string,\n target: VueTargetInfo,\n): ExistingAnnotation | Refusal | null {\n const markers = target.props.filter(isMarkerProp);\n if (markers.length === 0) return null;\n const marker = markers[0]!;\n if (\n markers.length > 1 ||\n marker !== target.props[target.props.length - 1] ||\n marker.kind !== \"directive\"\n ) {\n return annotationConflict(target.start);\n }\n const position = Number(\n INVOCATION_MARKER_EXPRESSION.exec(marker.expression ?? \"\")?.[1],\n );\n const removal = { start: marker.start - 1, end: marker.end, replacement: \"\" };\n if (\n source.slice(removal.start, removal.end) !==\n serializeMarker(marker.rawName, position)\n )\n return annotationConflict(target.start);\n return { kind: \"marker\", spelling: marker.rawName, position, removal };\n}\n\nfunction sameStampMetadata(a: StampMetadata, b: StampMetadata): boolean {\n return (\n a.filepath === b.filepath &&\n a.position === b.position &&\n a.modifiedTs === b.modifiedTs &&\n a.sourceVersion === b.sourceVersion\n );\n}\n\nfunction serializeStamps(\n metadata: StampMetadata,\n expressions: string | undefined,\n): string {\n const values: [string, string][] = [\n [\"data-tempo-filepath\", metadata.filepath],\n [\"data-tempo-position\", String(metadata.position)],\n [\"data-tempo-modifiedts\", String(metadata.modifiedTs)],\n [\"data-tempo-source-version\", metadata.sourceVersion],\n ...(expressions === undefined\n ? []\n : [[EXPRESSION_FACTS_ATTRIBUTE, expressions] as [string, string]]),\n ];\n return values\n .map(([name, value]) => ` ${name}=\"${escapeVueAttributeValue(value)}\"`)\n .join(\"\");\n}\n\nfunction serializeMarker(spelling: string, position: number): string {\n return ` ${spelling}=\"function ${TEMPO_VUE_INVOCATION_MARKER_PREFIX}${position}(){}\"`;\n}\n\n/** Ranges are non-overlapping and in source order. */\nfunction removeRanges(source: string, ranges: readonly StringEdit[]): string {\n let result = \"\";\n let cursor = 0;\n for (const range of ranges) {\n result += source.slice(cursor, range.start);\n cursor = range.end;\n }\n return result + source.slice(cursor);\n}\n\nfunction refused(code: Refusal[\"code\"], message: string): Refusal {\n return { kind: \"refused\", code, message };\n}\n\nfunction annotationConflict(offset: number): Refusal {\n return refused(\n \"annotation_conflict\",\n `tag at UTF-16 offset ${offset} has partial, dynamic, reordered, or conflicting Tempo annotations`,\n );\n}\n\nfunction identityConflict(offset: number): Refusal {\n return refused(\n \"annotation_conflict\",\n `existing Tempo annotation at UTF-16 offset ${offset} does not exactly match the recovered source identity`,\n );\n}\n","import type { Node as BabelNode, Statement } from \"@babel/types\";\nimport type {\n DirectiveNode,\n ElementNode,\n ExpressionNode,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { applyStringEdits } from \"@modules/template-edits\";\nimport { CssUrlError, rebaseCssUrls } from \"@modules/template-edits/css-urls\";\nimport {\n babelParse,\n compileScript,\n extractIdentifiers,\n parse as parseSfc,\n type SFCDescriptor,\n type SFCScriptBlock,\n walkIdentifiers,\n} from \"vue/compiler-sfc\";\nimport { LONE_BRANCH_MESSAGE, vueMoveUnitEnd } from \"./chain\";\nimport { escapeVueAttributeValue } from \"./escape\";\nimport { babelPluginsFor, parseVueSource } from \"./parse\";\nimport type {\n PlanVueTransferOptions,\n StringEdit,\n VueEditRefusalCode,\n VueImportUse,\n VueTransferPlan,\n} from \"./types\";\n\n// compiler-core's enum values (see parse.ts for why they are literals).\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\nconst SIMPLE_EXPRESSION_NODE = 4 as NodeTypes.SIMPLE_EXPRESSION;\nconst INTERPOLATION_NODE = 5 as NodeTypes.INTERPOLATION;\nconst DIRECTIVE_NODE = 7 as NodeTypes.DIRECTIVE;\nconst COMPONENT_TAG = 1;\nconst SLOT_TAG = 2;\n\n/** Names a template expression reads from the JavaScript global scope\n * rather than the component (`@vue/shared`'s `GLOBALS_ALLOWED`). */\nconst TEMPLATE_GLOBALS = new Set(\n (\n \"Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,\" +\n \"decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,\" +\n \"Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol\"\n ).split(\",\"),\n);\n\n/** Instance properties whose value is the component's own: moved into\n * another component they read that one's instead. Every other `$name` is\n * an app-wide global property (`$t`, `$route`), the same in any component,\n * and `$event` is a handler's own argument. */\nconst INSTANCE_PROPERTIES = new Set([\n \"$attrs\",\n \"$slots\",\n \"$props\",\n \"$emit\",\n \"$el\",\n \"$refs\",\n \"$parent\",\n \"$root\",\n \"$data\",\n \"$options\",\n \"$style\",\n \"$host\",\n \"$watch\",\n \"$forceUpdate\",\n]);\n\n/** Directives the compiler implements; any other `v-name` resolves a\n * directive the component or the app registers. */\nconst BUILT_IN_DIRECTIVES = new Set([\n \"bind\",\n \"on\",\n \"if\",\n \"else-if\",\n \"else\",\n \"for\",\n \"show\",\n \"model\",\n \"slot\",\n \"html\",\n \"text\",\n \"once\",\n \"memo\",\n \"cloak\",\n \"pre\",\n \"is\",\n]);\n\nconst BUILT_IN_COMPONENTS = new Set([\n \"Teleport\",\n \"teleport\",\n \"KeepAlive\",\n \"keep-alive\",\n \"Transition\",\n \"transition\",\n \"TransitionGroup\",\n \"transition-group\",\n \"Suspense\",\n \"suspense\",\n \"BaseTransition\",\n \"base-transition\",\n \"component\",\n \"Component\",\n]);\n\n/** The static attributes compiler-sfc's default `transformAssetUrls` turns\n * into imports when they start with `.`: their meaning is the file's\n * directory, so a move rebases them. `srcset` is `transformSrcset`'s. */\nconst ASSET_URL_ATTRIBUTES: Readonly<Record<string, readonly string[]>> = {\n video: [\"src\", \"poster\"],\n source: [\"src\", \"srcset\"],\n img: [\"src\", \"srcset\"],\n image: [\"xlink:href\", \"href\"],\n use: [\"xlink:href\", \"href\"],\n};\n\nexport class TransferRefusal extends Error {\n readonly code: VueEditRefusalCode;\n constructor(code: VueEditRefusalCode, message: string) {\n super(message);\n this.code = code;\n }\n}\n\nconst refuse = (code: VueEditRefusalCode, message: string): never => {\n throw new TransferRefusal(code, message);\n};\n\n/**\n * Plan carrying one authored element of a Vue SFC's template into another\n * SFC, refusal-first: the markup as it reads in the destination, plus the\n * destination edits that give it what it depends on. A `<script setup>`\n * import the markup reads is carried, rebased; a literal `const` is\n * carried as written; every `<style>` block comes along, because its\n * selectors may match the moved elements. Anything the markup reads from\n * its component's own state (props, refs, functions, an enclosing `v-for`\n * or `v-slot`, `$attrs`, a `<slot>`) refuses: moved, it would read another\n * component's. Where the destination's enclosing `v-for` or `v-slot`\n * binds a name the markup reads, a carried declaration takes a fresh name\n * and anything else refuses. Removing the element from the source is the\n * caller's.\n *\n * Edits are simultaneous: `markupEdits` in the coordinates of the element's\n * own bytes, `destinationEdits` in the destination's.\n */\nexport function planVueTransfer(\n options: PlanVueTransferOptions,\n): VueTransferPlan {\n try {\n return transfer(options);\n } catch (error) {\n if (error instanceof TransferRefusal)\n return { kind: \"refused\", code: error.code, message: error.message };\n throw error;\n }\n}\n\nfunction transfer(options: PlanVueTransferOptions): VueTransferPlan {\n const { source, destination } = options;\n const from = readSfc(source, options.sourceFile);\n const into = readSfc(destination, options.destinationFile);\n const parsed = parseVueSource(source, options.sourceFile);\n if (parsed.kind !== \"ok\") return refuse(\"invalid_source\", parsed.message);\n const target = parsed.targets.get(options.start);\n if (!target)\n return refuse(\n \"invalid_anchor\",\n `no Vue template tag starts at UTF-16 offset ${options.start}`,\n );\n if (target.inVPre)\n refuse(\n \"scope_change\",\n \"Markup inside v-pre is literal; moved out of it, its {{ }} would interpolate\",\n );\n const path = pathTo(from.rootNodes, options.start);\n const node = path[path.length - 1];\n if (!node)\n return refuse(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.start}`,\n );\n // A v-if carries its whole chain, one construct; a later branch cannot\n // leave it. The chain's branches are the siblings the unit spans.\n const end = vueMoveUnitEnd(source, parsed.targets, target.start);\n if (end === null) return refuse(\"unsupported_structure\", LONE_BRANCH_MESSAGE);\n const chain = (path[path.length - 2]?.children ?? from.rootNodes).filter(\n (child): child is ElementNode =>\n child.type === ELEMENT_NODE &&\n child.loc.start.offset >= target.start &&\n child.loc.end.offset <= end,\n );\n\n const uses = emptyUses();\n for (const member of chain) collectElement(member, new Set(), uses);\n const enclosing = new Set(path.slice(0, -1).flatMap(scopeBindingsOf));\n for (const name of uses.names.keys())\n if (enclosing.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${name} from an enclosing v-for or v-slot; moving it requires AI`,\n );\n if (uses.slots)\n refuse(\n \"scope_change\",\n \"The markup renders its component's <slot>; moving it requires AI\",\n );\n\n const { declarations, globals } = resolveDependencies(from, uses, options);\n const shadowing = destinationScope(into, options);\n const carried = new Set(declarations.map((declaration) => declaration.local));\n for (const name of [...uses.names.keys(), ...globals])\n if (shadowing.has(name) && !carried.has(name))\n refuse(\n \"scope_change\",\n `An enclosing v-for or v-slot at the destination binds ${name}, which the markup reads; moving it requires AI`,\n );\n const declared = declareInDestination(\n into,\n declarations,\n globals,\n shadowing,\n new Set([\n ...uses.names.keys(),\n ...[...uses.components.keys()].flatMap(spellings),\n ]),\n from.descriptor.scriptSetup?.lang ?? null,\n options,\n );\n const destinationEdits = [\n ...declared.edits,\n ...carryStyles(from, destination, options),\n ];\n const markupEdits = [\n ...chain.flatMap((member) =>\n rebaseAssetUrls(member, options, target.start),\n ),\n ...respell(declarations, declared.renames, target.start),\n ];\n const authored = source.slice(target.start, end);\n return {\n kind: \"planned\",\n markup: applyStringEdits(authored, markupEdits),\n markupEdits,\n destinationEdits,\n end,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Reading an SFC\n\ninterface ScriptRead {\n imports: { local: string; source: string; imported: string }[];\n /** Top-level `const name = <literal>`, the literal as written. */\n literals: Map<string, string>;\n /** Every name the block declares at its top level. */\n declared: Set<string>;\n lastImportEnd: number | null;\n lastImportIndent: string;\n firstStatementStart: number | null;\n}\n\ninterface SfcRead {\n source: string;\n file: string;\n descriptor: SFCDescriptor;\n rootNodes: TemplateChildNode[];\n setup: ScriptRead | null;\n classic: ScriptRead | null;\n}\n\nfunction readSfc(source: string, file: string): SfcRead {\n const { descriptor, errors } = parseSfc(source, {\n filename: file,\n sourceMap: false,\n });\n if (errors.length > 0) refuse(\"invalid_source\", errors[0]!.message);\n if (!descriptor.template?.ast)\n refuse(\"unsupported_template\", `${file} has no readable <template> block`);\n return {\n source,\n file,\n descriptor,\n rootNodes: descriptor.template!.ast!.children,\n setup: descriptor.scriptSetup ? readScript(descriptor.scriptSetup) : null,\n classic: descriptor.script ? readScript(descriptor.script) : null,\n };\n}\n\nfunction readScript(block: SFCScriptBlock): ScriptRead {\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return refuse(\"unsupported_script\", \"a <script> block does not parse\");\n }\n const read: ScriptRead = {\n imports: [],\n literals: new Map(),\n declared: new Set(),\n lastImportEnd: null,\n lastImportIndent: \"\",\n firstStatementStart: body[0]?.start ?? null,\n };\n for (const statement of body) {\n if (statement.type === \"ImportDeclaration\") {\n read.lastImportEnd = statement.end!;\n const lineStart = block.content.lastIndexOf(\"\\n\", statement.start! - 1);\n read.lastImportIndent = /^[ \\t]*/.exec(\n block.content.slice(lineStart + 1, statement.start!),\n )![0];\n for (const specifier of statement.specifiers) {\n read.declared.add(specifier.local.name);\n const typeOnly =\n statement.importKind === \"type\" ||\n (specifier.type === \"ImportSpecifier\" &&\n specifier.importKind === \"type\");\n if (typeOnly) continue;\n read.imports.push({\n local: specifier.local.name,\n source: statement.source.value,\n imported:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"*\"\n : specifier.imported.type === \"Identifier\"\n ? specifier.imported.name\n : specifier.imported.value,\n });\n }\n continue;\n }\n const declaration =\n statement.type === \"ExportNamedDeclaration\"\n ? statement.declaration\n : statement;\n if (!declaration) continue;\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations) {\n for (const id of extractIdentifiers(declarator.id))\n read.declared.add(id.name);\n const literal =\n declaration.kind === \"const\" &&\n declarator.id.type === \"Identifier\" &&\n declarator.init &&\n isLiteral(declarator.init);\n if (literal)\n read.literals.set(\n (declarator.id as { name: string }).name,\n block.content.slice(declarator.init!.start!, declarator.init!.end!),\n );\n }\n continue;\n }\n const named = declaration as { id?: { type: string; name?: string } };\n if (named.id?.type === \"Identifier\") read.declared.add(named.id.name!);\n }\n return read;\n}\n\n/** A value that means the same written anywhere: no name it reads. */\nfunction isLiteral(node: BabelNode): boolean {\n switch (node.type) {\n case \"StringLiteral\":\n case \"NumericLiteral\":\n case \"BooleanLiteral\":\n case \"NullLiteral\":\n return true;\n case \"TemplateLiteral\":\n return node.expressions.length === 0;\n case \"UnaryExpression\":\n return node.operator === \"-\" && node.argument.type === \"NumericLiteral\";\n case \"ArrayExpression\":\n return node.elements.every((element) => element && isLiteral(element));\n case \"ObjectExpression\":\n return node.properties.every(\n (property) =>\n property.type === \"ObjectProperty\" &&\n !property.computed &&\n isLiteral(property.value),\n );\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// What the markup reads\n\n/** Where the markup writes a name it reads, so a renamed declaration can\n * be spelled there: an identifier, a shorthand property (`{ fmt }`), a\n * component tag's name (opening, closing, or a static `is`), or a custom\n * directive's name. */\ninterface Occurrence {\n start: number;\n end: number;\n as: \"identifier\" | \"shorthand\" | \"tag\" | \"directive\";\n}\n\ninterface TemplateUses {\n /** Names its expressions read from outside themselves. */\n names: Map<string, Occurrence[]>;\n /** Component tags as written (`Icon`, `my-icon`). */\n components: Map<string, Occurrence[]>;\n /** Custom directive names as written (`focus` for `v-focus`). */\n directives: Map<string, Occurrence[]>;\n /** Static `ref` attribute values. */\n refs: Set<string>;\n slots: boolean;\n}\n\nexport const emptyUses = (): TemplateUses => ({\n names: new Map(),\n components: new Map(),\n directives: new Map(),\n refs: new Set(),\n slots: false,\n});\n\nfunction note(\n map: Map<string, Occurrence[]>,\n name: string,\n occurrence: Occurrence,\n): void {\n map.set(name, [...(map.get(name) ?? []), occurrence]);\n}\n\nfunction collectChildren(\n children: readonly TemplateChildNode[],\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n for (const child of children) {\n if (child.type === ELEMENT_NODE) collectElement(child, scope, uses);\n else if (child.type === INTERPOLATION_NODE)\n collectExpression(child.content, scope, uses);\n }\n}\n\n/** Every name an element and its subtree read from the component, in the\n * template scope `scope` (names bound by an enclosing `v-for` or `v-slot`\n * inside the moved or copied markup). Markup under `v-pre` holds no\n * directive or interpolation in the parsed tree, so it reads nothing. */\nexport function collectElement(\n node: ElementNode,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n const directives = node.props.filter(\n (prop): prop is DirectiveNode => prop.type === DIRECTIVE_NODE,\n );\n // `v-for` binds its aliases for the element itself and its children;\n // `v-if` is evaluated first, outside them.\n const forDirective = directives.find((prop) => prop.name === \"for\");\n let inner = scope;\n if (forDirective?.forParseResult) {\n const { source, value, key, index } = forDirective.forParseResult;\n collectExpression(source, scope, uses);\n inner = new Set([\n ...scope,\n ...[value, key, index].flatMap((alias) =>\n bindingNames(alias, scope, uses),\n ),\n ]);\n }\n let childScope = inner;\n for (const prop of node.props) {\n if (prop.type !== DIRECTIVE_NODE) {\n if (prop.name === \"ref\" && prop.value) uses.refs.add(prop.value.content);\n continue;\n }\n if (prop.name === \"for\") continue;\n if (\n prop.arg &&\n prop.arg.type === SIMPLE_EXPRESSION_NODE &&\n !prop.arg.isStatic\n )\n collectExpression(prop.arg, inner, uses);\n if (prop.name === \"slot\") {\n childScope = new Set([\n ...childScope,\n ...bindingNames(prop.exp, inner, uses),\n ]);\n continue;\n }\n const outer = prop.name === \"if\" || prop.name === \"else-if\";\n collectExpression(prop.exp, outer ? scope : inner, uses);\n // A custom directive is written `v-name`: never a shorthand.\n if (!BUILT_IN_DIRECTIVES.has(prop.name)) {\n const start = prop.loc.start.offset + \"v-\".length;\n note(uses.directives, prop.name, {\n start,\n end: start + prop.name.length,\n as: \"directive\",\n });\n }\n }\n if (node.tagType === SLOT_TAG) uses.slots = true;\n if (node.tagType === COMPONENT_TAG) {\n if (!BUILT_IN_COMPONENTS.has(node.tag)) {\n const name = node.tag.split(\".\")[0]!;\n const opening = node.loc.start.offset + 1;\n note(uses.components, name, {\n start: opening,\n end: opening + name.length,\n as: \"tag\",\n });\n const closing = node.loc.source.lastIndexOf(\"</\");\n if (!node.isSelfClosing && closing > 0) {\n const start = node.loc.start.offset + closing + 2;\n if (node.loc.source.startsWith(name, closing + 2))\n note(uses.components, name, {\n start,\n end: start + name.length,\n as: \"tag\",\n });\n }\n }\n // `<component is=\"Name\">` resolves the name like a tag; a `vue:` one is\n // a native element.\n const is = node.props.find(\n (prop) => prop.type !== DIRECTIVE_NODE && prop.name === \"is\",\n );\n const value = is?.type !== DIRECTIVE_NODE ? is?.value : undefined;\n if (value && !value.content.startsWith(\"vue:\")) {\n const start =\n value.loc.start.offset + (/^[\"']/.test(value.loc.source) ? 1 : 0);\n note(uses.components, value.content, {\n start,\n end: start + value.content.length,\n as: \"tag\",\n });\n }\n }\n collectChildren(node.children, childScope, uses);\n}\n\nfunction collectExpression(\n expression: ExpressionNode | undefined,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n if (!expression || expression.type !== SIMPLE_EXPRESSION_NODE) return;\n if (expression.isStatic) return;\n const ast = expression.ast;\n if (ast === false)\n refuse(\n \"invalid_source\",\n `the expression ${JSON.stringify(expression.content)} does not parse`,\n );\n // The parser leaves a lone identifier unparsed (`ast === null`).\n if (!ast) {\n const name = expression.content.trim();\n const start =\n expression.loc.start.offset +\n expression.content.length -\n expression.content.trimStart().length;\n if (name && !scope.has(name))\n note(uses.names, name, {\n start,\n end: start + name.length,\n as: \"identifier\",\n });\n return;\n }\n noteIdentifiers(ast as BabelNode, expression, scope, uses);\n}\n\n/** Every free identifier of a parsed expression. The parser wraps the\n * expression's text in one character (`(`, or a space for statements)\n * before parsing, so a node's offset is one past its place in the file. */\nfunction noteIdentifiers(\n ast: BabelNode,\n expression: ExpressionNode,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): void {\n walkIdentifiers(ast, (id, parent) => {\n if (scope.has(id.name)) return;\n const start = expression.loc.start.offset + id.start! - 1;\n const shorthand =\n parent?.type === \"ObjectProperty\" &&\n (parent as { shorthand?: boolean }).shorthand === true;\n note(uses.names, id.name, {\n start,\n end: start + id.name.length,\n as: shorthand ? \"shorthand\" : \"identifier\",\n });\n });\n}\n\n/** The names a `v-for` alias or `v-slot` parameter binds; a default value\n * in the pattern is read in `scope`. */\nfunction bindingNames(\n expression: ExpressionNode | undefined,\n scope: ReadonlySet<string>,\n uses: TemplateUses,\n): string[] {\n if (!expression || expression.type !== SIMPLE_EXPRESSION_NODE) return [];\n const ast = expression.ast;\n if (ast === false)\n refuse(\n \"invalid_source\",\n `the binding ${JSON.stringify(expression.content)} does not parse`,\n );\n if (!ast) return expression.content.trim() ? [expression.content.trim()] : [];\n // Parsed as `(pattern) => {}`: the walk reads the defaults, the params\n // are the bindings.\n noteIdentifiers(ast as BabelNode, expression, scope, uses);\n const params =\n ast.type === \"ArrowFunctionExpression\" ? ast.params : ([] as BabelNode[]);\n return params.flatMap((param) =>\n extractIdentifiers(param).map((id) => id.name),\n );\n}\n\n/** Names an ancestor binds for its descendants. */\nexport function scopeBindingsOf(node: ElementNode): string[] {\n const ignored = emptyUses();\n return node.props.flatMap((prop) => {\n if (prop.type !== DIRECTIVE_NODE) return [];\n if (prop.name === \"slot\") return bindingNames(prop.exp, new Set(), ignored);\n if (prop.name !== \"for\" || !prop.forParseResult) return [];\n const { value, key, index } = prop.forParseResult;\n return [value, key, index].flatMap((alias) =>\n bindingNames(alias, new Set(), ignored),\n );\n });\n}\n\n/** The names the destination's enclosing `v-for` and `v-slot` bind where\n * the markup lands: the parent's own and its ancestors'. Moved under a\n * `v-for=\"label in labels\"`, markup that read a carried `label` const\n * would read the loop variable instead. A new board's content slot has no\n * parent and no enclosing scope. */\nfunction destinationScope(\n into: SfcRead,\n options: PlanVueTransferOptions,\n): Set<string> {\n const offset = options.destinationParentOffset;\n if (offset === undefined) return new Set();\n const path = pathTo(into.rootNodes, offset);\n if (!path.length)\n refuse(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${offset} of ${options.destinationFile}`,\n );\n const parsed = parseVueSource(into.source, options.destinationFile);\n const parent = parsed.kind === \"ok\" ? parsed.targets.get(offset) : null;\n if (parent?.vPre || parent?.inVPre)\n refuse(\n \"scope_change\",\n \"Moving markup into v-pre changes how its template is read; moving it requires AI\",\n );\n return new Set(path.flatMap(scopeBindingsOf));\n}\n\n/** The elements from the template root down to the one at `start`. */\nexport function pathTo(\n children: readonly TemplateChildNode[],\n start: number,\n): ElementNode[] {\n for (const child of children) {\n if (child.type !== ELEMENT_NODE) continue;\n if (child.loc.start.offset === start) return [child];\n if (child.loc.start.offset < start && child.loc.end.offset > start) {\n const below = pathTo(child.children, start);\n if (below.length) return [child, ...below];\n }\n }\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// Resolving what the markup reads\n\n/** A declaration the destination must hold for the markup to read the same\n * value: an import or a literal const, under the source's local name, and\n * where the markup writes that name. */\ntype Declaration = (\n | { kind: \"import\"; local: string; source: string; imported: string }\n | { kind: \"const\"; local: string; literal: string }\n) & { occurrences: Occurrence[] };\n\n/** What the moved markup needs: the declarations to carry, and the names\n * it reads from the app (global components, directives and properties),\n * which a destination binding of the same name would shadow. */\ninterface Dependencies {\n declarations: Declaration[];\n globals: string[];\n}\n\nfunction resolveDependencies(\n from: SfcRead,\n uses: TemplateUses,\n options: PlanVueTransferOptions,\n): Dependencies {\n const names = [...uses.names.keys()].filter(\n (name) => !TEMPLATE_GLOBALS.has(name) && name !== \"$event\",\n );\n for (const name of names)\n if (INSTANCE_PROPERTIES.has(name))\n refuse(\n \"scope_change\",\n `The markup reads its component's ${name}; moving it requires AI`,\n );\n const componentNames = names.filter((name) => !name.startsWith(\"$\"));\n const nothingResolved =\n componentNames.length === 0 &&\n uses.components.size === 0 &&\n uses.directives.size === 0 &&\n uses.refs.size === 0;\n if (nothingResolved)\n return { declarations: [], globals: names.filter(isGlobalProperty) };\n if (!from.setup && from.classic)\n return resolveOptionsDependencies(from, uses, names, options);\n\n const scripts = [from.setup, from.classic].filter(\n (read): read is ScriptRead => read !== null,\n );\n const declarations = new Map<string, Declaration>();\n /** The declaration that gives `name` the same value in the destination,\n * or null when no script declares it. */\n const declare = (\n name: string,\n what: string,\n occurrences: readonly Occurrence[],\n ): boolean => {\n const known = declarations.get(name);\n if (known) {\n known.occurrences.push(...occurrences);\n return true;\n }\n for (const script of scripts) {\n const imported = script.imports.find((entry) => entry.local === name);\n if (imported) {\n declarations.set(name, {\n kind: \"import\",\n local: name,\n source: options.rebase(imported.source, \"import\"),\n imported: imported.imported,\n occurrences: [...occurrences],\n });\n return true;\n }\n const literal = script.literals.get(name);\n if (literal !== undefined) {\n declarations.set(name, {\n kind: \"const\",\n local: name,\n literal,\n occurrences: [...occurrences],\n });\n return true;\n }\n if (script.declared.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${what}, which its component's script defines; moving it requires AI`,\n );\n }\n return false;\n };\n // A tag or directive resolves through the script's bindings by its\n // spelling, camelCase or PascalCase (compiler-sfc's\n // `resolveSetupReference`); one the script does not declare is\n // registered for the whole app and resolves the same anywhere.\n const globals = names.filter(isGlobalProperty);\n for (const [tag, occurrences] of uses.components)\n if (!spellings(tag).some((name) => declare(name, `<${tag}>`, occurrences)))\n globals.push(...spellings(tag));\n for (const [directive, occurrences] of uses.directives)\n if (!declare(`v${pascalCase(directive)}`, `v-${directive}`, occurrences))\n globals.push(`v${pascalCase(directive)}`);\n\n let bindings: Record<string, unknown> | null | undefined;\n const scriptBindings = () => {\n if (bindings !== undefined) return bindings;\n try {\n bindings = from.descriptor.scriptSetup\n ? (compileScript(from.descriptor, { id: \"tempo-transfer\" }).bindings ??\n {})\n : {};\n } catch {\n bindings = null;\n }\n return bindings;\n };\n for (const name of componentNames) {\n if (declare(name, name, uses.names.get(name) ?? [])) continue;\n // Not declared by any statement, the name is a prop, a global property\n // or a global; only the compiler's binding analysis tells props apart.\n const known = scriptBindings();\n if (known === null)\n refuse(\n \"unsupported_script\",\n `Could not read which names its component's script defines, so ${name} may be a prop; moving it requires AI`,\n );\n if (known![name] !== undefined)\n refuse(\n \"scope_change\",\n `The markup reads ${name}, which its component defines; moving it requires AI`,\n );\n globals.push(name);\n }\n // A static ref names its owning component's slot, not necessarily a\n // script binding: useTemplateRef(\"my-input\") may be assigned to `input`.\n for (const name of uses.refs)\n refuse(\n \"scope_change\",\n `The element is its component's template ref ${name}; moving it requires AI`,\n );\n return { declarations: [...declarations.values()], globals };\n}\n\n/** An app-wide `$name` (`$t`, `$route`): not the component's own. */\nfunction isGlobalProperty(name: string): boolean {\n return name.startsWith(\"$\") && name !== \"$event\";\n}\n\n/** What an Options API component's template sees, read from its options\n * object, never executed. */\ninterface OptionsRead {\n /** Registered components and directives: the registration key (how the\n * template spells it) to the script binding it names, or null when the\n * value is not a plain binding (`defineAsyncComponent(...)`). */\n components: Map<string, string | null>;\n directives: Map<string, string | null>;\n /** Names the instance exposes: props, data, computed, methods, inject. */\n instance: Set<string>;\n /** False when the template may see names no static read lists: a\n * `setup()`, `mixins`, `extends`, a spread, or an option written as\n * anything but a literal. */\n complete: boolean;\n}\n\nfunction readOptions(block: SFCScriptBlock): OptionsRead {\n const read: OptionsRead = {\n components: new Map(),\n directives: new Map(),\n instance: new Set(),\n complete: true,\n };\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return { ...read, complete: false };\n }\n const exported = body.find(\n (statement) => statement.type === \"ExportDefaultDeclaration\",\n );\n let object: BabelNode | undefined =\n exported?.type === \"ExportDefaultDeclaration\"\n ? exported.declaration\n : undefined;\n // `defineComponent({...})` and its kind.\n if (object?.type === \"CallExpression\") object = object.arguments[0];\n if (object?.type !== \"ObjectExpression\") return { ...read, complete: false };\n const keyOf = (node: BabelNode): string | null =>\n node.type === \"Identifier\"\n ? node.name\n : node.type === \"StringLiteral\"\n ? node.value\n : null;\n /** The keys of an object literal, or of an array of strings. */\n const keysOf = (node: BabelNode | null | undefined): string[] | null => {\n if (node?.type === \"ArrayExpression\")\n return node.elements.every((element) => element?.type === \"StringLiteral\")\n ? node.elements.map((element) => (element as { value: string }).value)\n : null;\n if (node?.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const property of node.properties) {\n if (property.type === \"SpreadElement\" || property.computed) return null;\n const key = keyOf(property.key);\n if (key === null) return null;\n keys.push(key);\n }\n return keys;\n };\n /** The object `data()` returns, when it returns one literal. */\n const returned = (node: BabelNode): BabelNode | null => {\n const fn =\n node.type === \"ObjectMethod\"\n ? node\n : (node as { value?: BabelNode }).value;\n if (!fn || !(\"body\" in fn)) return null;\n const body = fn.body as BabelNode;\n if (body.type === \"ObjectExpression\") return body;\n if (body.type !== \"BlockStatement\") return null;\n const last = body.body[body.body.length - 1];\n return last?.type === \"ReturnStatement\" ? (last.argument ?? null) : null;\n };\n for (const property of object.properties) {\n if (property.type === \"SpreadElement\" || property.computed) {\n read.complete = false;\n continue;\n }\n const key = keyOf(property.key);\n const value =\n property.type === \"ObjectProperty\" ? (property.value as BabelNode) : null;\n switch (key) {\n case \"setup\":\n case \"mixins\":\n case \"extends\":\n read.complete = false;\n break;\n case \"components\":\n case \"directives\": {\n const registry = read[key];\n if (value?.type !== \"ObjectExpression\") {\n read.complete = false;\n break;\n }\n for (const entry of value.properties) {\n const name =\n entry.type === \"SpreadElement\" || entry.computed\n ? null\n : keyOf(entry.key);\n if (name === null) {\n read.complete = false;\n continue;\n }\n const bound =\n entry.type === \"ObjectProperty\" && entry.value.type === \"Identifier\"\n ? entry.value.name\n : null;\n registry.set(name, bound);\n }\n break;\n }\n case \"data\": {\n const keys = keysOf(\n value?.type === \"ObjectExpression\" ? value : returned(property),\n );\n if (keys === null) read.complete = false;\n else for (const name of keys) read.instance.add(name);\n break;\n }\n case \"props\":\n case \"computed\":\n case \"methods\":\n case \"inject\": {\n const keys = keysOf(value);\n if (keys === null) read.complete = false;\n else for (const name of keys) read.instance.add(name);\n break;\n }\n }\n }\n return read;\n}\n\n/** An Options API source: its template reads registered components and\n * directives (carried as `<script setup>` imports under the name the\n * markup's spelling resolves by), refuses names its instance exposes\n * (props, data, computed, methods, inject), and reads every other name\n * from the app, as script setup markup does. Module-scope names are not\n * visible to an Options API template, so they are not carried. */\nfunction resolveOptionsDependencies(\n from: SfcRead,\n uses: TemplateUses,\n names: readonly string[],\n options: PlanVueTransferOptions,\n): Dependencies {\n const read = readOptions(from.descriptor.script!);\n const script = from.classic!;\n if (!read.complete)\n refuse(\n \"unsupported_script\",\n \"Its Options API component may expose names no static read lists (setup(), mixins, extends, a spread); moving its markup requires AI\",\n );\n if (uses.refs.size)\n refuse(\n \"scope_change\",\n \"The element is its Options API component's template ref, which its code reads through $refs; moving it requires AI\",\n );\n const declarations = new Map<string, Declaration>();\n const globals = names.filter(isGlobalProperty);\n const carry = (\n registry: Map<string, string | null>,\n key: string,\n local: string,\n what: string,\n occurrences: readonly Occurrence[],\n ) => {\n const bound = registry.get(key);\n const imported = bound\n ? script.imports.find((entry) => entry.local === bound)\n : undefined;\n if (!imported)\n refuse(\n \"scope_change\",\n `The markup reads ${what}, which its component's script defines; moving it requires AI`,\n );\n const known = declarations.get(local);\n if (known) known.occurrences.push(...occurrences);\n else\n declarations.set(local, {\n kind: \"import\",\n local,\n source: options.rebase(imported!.source, \"import\"),\n imported: imported!.imported,\n occurrences: [...occurrences],\n });\n };\n for (const [tag, occurrences] of uses.components) {\n const key = spellings(tag).find((name) => read.components.has(name));\n if (key === undefined) globals.push(...spellings(tag));\n else carry(read.components, key, pascalCase(key), `<${tag}>`, occurrences);\n }\n for (const [directive, occurrences] of uses.directives) {\n const local = `v${pascalCase(directive)}`;\n const key = [directive, ...spellings(directive)].find((name) =>\n read.directives.has(name),\n );\n if (key === undefined) globals.push(local);\n else carry(read.directives, key, local, `v-${directive}`, occurrences);\n }\n for (const name of names) {\n if (name.startsWith(\"$\")) continue;\n if (read.instance.has(name))\n refuse(\n \"scope_change\",\n `The markup reads ${name}, which its component defines; moving it requires AI`,\n );\n globals.push(name);\n }\n return { declarations: [...declarations.values()], globals };\n}\n\nfunction spellings(tag: string): string[] {\n const camel = tag.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n return [...new Set([tag, camel, pascalCase(camel)])];\n}\n\nfunction pascalCase(name: string): string {\n const camel = name.replace(/-(\\w)/g, (_, char: string) => char.toUpperCase());\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\n// ---------------------------------------------------------------------------\n// Writing the destination\n\nfunction statementOf(declaration: Declaration, local: string): string {\n if (declaration.kind === \"const\")\n return `const ${local} = ${declaration.literal};`;\n const from = JSON.stringify(declaration.source);\n if (declaration.imported === \"default\")\n return `import ${local} from ${from};`;\n if (declaration.imported === \"*\") return `import * as ${local} from ${from};`;\n const imported = /^[$A-Z_a-z][$\\w]*$/.test(declaration.imported)\n ? declaration.imported\n : JSON.stringify(declaration.imported);\n return imported === local\n ? `import { ${imported} } from ${from};`\n : `import { ${imported} as ${local} } from ${from};`;\n}\n\n/** The edits that declare each dependency in the destination's\n * `<script setup>` (creating the block when there is none), and the name\n * each one takes there. One the destination already holds, the same import\n * or literal, is reused under the destination's name for it. A name the\n * destination already uses for something else, or reads without declaring\n * (a global component, a prop), takes the next free spelling instead\n * (`Icon2`), as Astro's transfer does; the caller re-spells the markup. */\nfunction declareInDestination(\n into: SfcRead,\n declarations: readonly Declaration[],\n /** Names the markup reads from the app, which the destination must not\n * define for itself. */\n globals: readonly string[],\n /** Names an enclosing `v-for` or `v-slot` binds where the markup lands,\n * which a declaration's name must not be: the binding would shadow it. */\n shadowing: ReadonlySet<string>,\n /** Names the moved markup itself writes, which a new name must not be. */\n markupNames: ReadonlySet<string>,\n /** The source's `<script setup>` language, so a TypeScript project's\n * new block is TypeScript too. */\n lang: string | null,\n options: PlanVueTransferOptions,\n): { edits: StringEdit[]; renames: Map<string, string> } {\n const scripts = [into.setup, into.classic].filter(\n (read): read is ScriptRead => read !== null,\n );\n // An app-wide name the destination binds for itself would read the\n // destination's value instead: a prop, state, an import.\n let destinationBindings: Record<string, unknown> | null = {};\n if (globals.length && into.descriptor.scriptSetup)\n try {\n destinationBindings =\n compileScript(into.descriptor, { id: \"tempo-transfer\" }).bindings ?? {};\n } catch {\n destinationBindings = null;\n }\n for (const name of globals) {\n const shadowed =\n destinationBindings === null ||\n destinationBindings[name] !== undefined ||\n scripts.some((script) => script.declared.has(name));\n if (shadowed)\n refuse(\n \"scope_change\",\n destinationBindings === null\n ? `Could not read which names ${options.destinationFile} defines, so it may shadow ${name}; moving the markup requires AI`\n : `The markup reads ${name} from the app, which ${options.destinationFile} defines for itself; moving it requires AI`,\n );\n }\n const destinationUses = emptyUses();\n collectChildren(into.rootNodes, new Set(), destinationUses);\n const readByDestination = new Set([\n ...destinationUses.names.keys(),\n ...[...destinationUses.components.keys()].flatMap(spellings),\n ...[...destinationUses.directives.keys()].map(\n (name) => `v${pascalCase(name)}`,\n ),\n ]);\n const spoken = new Set([\n ...(into.source.match(/[$A-Z_a-z][$\\w]*/g) ?? []),\n ...markupNames,\n ]);\n const allocate = (name: string) => {\n let fresh = name;\n for (let count = 2; spoken.has(fresh); count++) fresh = `${name}${count}`;\n spoken.add(fresh);\n return fresh;\n };\n const statements: string[] = [];\n const renames = new Map<string, string>();\n for (const declaration of declarations) {\n const held = scripts.flatMap((script) =>\n declaration.kind === \"import\"\n ? script.imports\n .filter(\n (entry) =>\n entry.source === declaration.source &&\n entry.imported === declaration.imported,\n )\n .map((entry) => entry.local)\n : script.literals.get(declaration.local) === declaration.literal\n ? [declaration.local]\n : [],\n )[0];\n // A component tag reaches the same import under any binding name; an\n // expression too. Reusing the destination's keeps one import, unless\n // the landing spot's v-for or v-slot shadows that name.\n if (held !== undefined && !shadowing.has(held)) {\n if (held !== declaration.local) renames.set(declaration.local, held);\n continue;\n }\n const taken =\n scripts.some((script) => script.declared.has(declaration.local)) ||\n readByDestination.has(declaration.local) ||\n shadowing.has(declaration.local);\n const local = taken ? allocate(declaration.local) : declaration.local;\n if (local !== declaration.local) renames.set(declaration.local, local);\n statements.push(statementOf(declaration, local));\n }\n if (statements.length === 0) return { edits: [], renames };\n\n const { source, descriptor } = into;\n const newline = source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const setup = descriptor.scriptSetup;\n if (setup && into.setup) {\n const read = into.setup;\n const contentStart = setup.loc.start.offset;\n if (read.lastImportEnd !== null)\n return {\n renames,\n edits: [\n {\n start: contentStart + read.lastImportEnd,\n end: contentStart + read.lastImportEnd,\n replacement: statements\n .map(\n (statement) => `${newline}${read.lastImportIndent}${statement}`,\n )\n .join(\"\"),\n },\n ],\n };\n const at = read.firstStatementStart ?? 0;\n const lineStart = setup.content.lastIndexOf(\"\\n\", at - 1) + 1;\n const indent = setup.content.slice(lineStart, at);\n return {\n renames,\n edits: [\n {\n start: contentStart + at,\n end: contentStart + at,\n replacement:\n statements.join(`${newline}${indent}`) +\n newline +\n (/^[ \\t]*$/.test(indent) ? indent : \"\"),\n },\n ],\n };\n }\n if (descriptor.script)\n refuse(\n \"unsupported_script\",\n `${options.destinationFile} is an Options API component; its options must register what the moved markup reads`,\n );\n // compiler-sfc drops an empty block from the descriptor, so a file with\n // `<script setup></script>` reads as having none; a second one would not\n // parse.\n const template = descriptor.template!;\n const outsideTemplate =\n source.slice(0, template.loc.start.offset) +\n source.slice(template.loc.end.offset);\n if (/<script\\b[^>]*\\bsetup\\b[^>]*>\\s*<\\/script\\s*>/.test(outsideTemplate))\n refuse(\n \"unsupported_script\",\n `${options.destinationFile} has an empty <script setup> block compiler-sfc does not read`,\n );\n const templateStart = source.lastIndexOf(\n \"<template\",\n template.loc.start.offset,\n );\n const opening = lang ? `<script setup lang=\"${lang}\">` : \"<script setup>\";\n return {\n renames,\n edits: [\n {\n start: templateStart,\n end: templateStart,\n replacement: `${opening}${newline}${statements.join(newline)}${newline}</script>${newline}${newline}`,\n },\n ],\n };\n}\n\n/** Edits, in the moved element's coordinates, that spell each renamed\n * declaration's new name where the markup wrote the old one. */\nfunction respell(\n declarations: readonly Declaration[],\n renames: ReadonlyMap<string, string>,\n base: number,\n): StringEdit[] {\n return declarations.flatMap((declaration) => {\n const local = renames.get(declaration.local);\n if (local === undefined) return [];\n return declaration.occurrences.map((occurrence) => ({\n start: occurrence.start - base,\n end: occurrence.end - base,\n replacement:\n occurrence.as === \"shorthand\"\n ? `${declaration.local}: ${local}`\n : occurrence.as === \"directive\"\n ? // `vFocus2` is written `v-focus2`.\n local.charAt(1).toLowerCase() + local.slice(2)\n : local,\n }));\n });\n}\n\n/** Every `<style>` block of the source, appended to the destination\n * verbatim: a scoped block's selectors match the moved elements under the\n * destination's scope exactly as they did under the source's. Its relative\n * `url()` and `@import` references are re-spelled for the destination's\n * directory. A block that reads component state (`v-bind()`), is a CSS\n * module (`$style`) or lives in another file refuses. */\nfunction carryStyles(\n from: SfcRead,\n destination: string,\n options: PlanVueTransferOptions,\n): StringEdit[] {\n const newline = destination.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n let appended = \"\";\n for (const style of from.descriptor.styles) {\n if (style.module || style.src)\n refuse(\n \"scoped_css\",\n \"The component's CSS module or external stylesheet belongs to it; moving its markup requires AI\",\n );\n if (/\\bv-bind\\s*\\(/.test(style.content))\n refuse(\n \"scoped_css\",\n \"The component's styles read its state through v-bind(); moving its markup requires AI\",\n );\n // Vite resolves the block's relative references from the component's\n // directory: they are re-spelled for the destination's.\n let content: string;\n try {\n content = rebaseCssUrls(style.content, options.rebase);\n } catch (error) {\n if (!(error instanceof CssUrlError)) throw error;\n return refuse(\"scoped_css\", error.message);\n }\n const start = from.source.lastIndexOf(\"<style\", style.loc.start.offset);\n const close = /^<\\/style\\s*>/i.exec(\n from.source.slice(style.loc.end.offset),\n );\n const block =\n from.source.slice(start, style.loc.start.offset) +\n content +\n from.source.slice(\n style.loc.end.offset,\n style.loc.end.offset + (close?.[0].length ?? 0),\n );\n if (!destination.includes(block) && !appended.includes(block))\n appended += `${newline}${block}${newline}`;\n }\n if (!appended) return [];\n const separator = destination.endsWith(\"\\n\") || !destination ? \"\" : newline;\n return [\n {\n start: destination.length,\n end: destination.length,\n replacement: separator + appended.slice(newline.length),\n },\n ];\n}\n\n/** Edits, in the element's own coordinates, that rebase each static asset\n * URL compiler-sfc resolves from the file's directory (`./`, `../`). */\nfunction rebaseAssetUrls(\n root: ElementNode,\n options: PlanVueTransferOptions,\n /** Where the carried bytes start. */\n base: number,\n): StringEdit[] {\n const edits: StringEdit[] = [];\n const visit = (node: ElementNode) => {\n const attributes = ASSET_URL_ATTRIBUTES[node.tag] ?? [];\n for (const prop of node.props) {\n if (prop.type === DIRECTIVE_NODE || !prop.value) continue;\n if (!attributes.includes(prop.name)) continue;\n const value = prop.value.content;\n const rebased =\n prop.name === \"srcset\"\n ? value\n .split(\",\")\n .map((candidate) =>\n candidate.replace(\n /^(\\s*)(\\S+)/,\n (_, space: string, url: string) =>\n space + rebaseRelative(url, options),\n ),\n )\n .join(\",\")\n : rebaseRelative(value, options);\n if (rebased === value) continue;\n if (prop.name === \"srcset\" && value.includes(\"data:\"))\n refuse(\n \"unsupported_target\",\n \"A srcset mixing data URLs and relative URLs needs its original file\",\n );\n // The value node's location includes its quotes when it has them.\n const quote = /^[\"']/.exec(prop.value.loc.source)?.[0] as\n | '\"'\n | \"'\"\n | undefined;\n const escaped = escapeVueAttributeValue(rebased, quote ?? '\"');\n edits.push({\n start: prop.value.loc.start.offset - base,\n end: prop.value.loc.end.offset - base,\n replacement: `${quote ?? '\"'}${escaped}${quote ?? '\"'}`,\n });\n }\n for (const child of node.children)\n if (child.type === ELEMENT_NODE) visit(child);\n };\n visit(root);\n return edits;\n}\n\nfunction rebaseRelative(url: string, options: PlanVueTransferOptions): string {\n return url.startsWith(\".\") ? options.rebase(url, \"url\") : url;\n}\n\n/**\n * The file's value imports and every name it reads outside them, so a\n * caller can drop an import an edit left unread. Over-approximate on\n * purpose: any identifier a script spells (a property key included) counts\n * as read. Null when the file does not parse.\n */\nexport function readVueImportUse(\n source: string,\n file: string,\n): VueImportUse | null {\n let sfc: SfcRead;\n try {\n sfc = readSfc(source, file);\n } catch (error) {\n if (error instanceof TransferRefusal) return null;\n throw error;\n }\n const uses = emptyUses();\n collectChildren(sfc.rootNodes, new Set(), uses);\n const referenced = new Set<string>([\n ...uses.names.keys(),\n ...[...uses.components.keys()].flatMap(spellings),\n ...[...uses.directives.keys()].map((name) => `v${pascalCase(name)}`),\n ]);\n for (const style of sfc.descriptor.styles)\n for (const match of style.content.matchAll(/v-bind\\(\\s*[\"']?([$\\w]+)/g))\n referenced.add(match[1]!);\n const imports: VueImportUse[\"imports\"] = [];\n for (const block of [sfc.descriptor.scriptSetup, sfc.descriptor.script]) {\n if (!block) continue;\n let body: Statement[];\n try {\n body = babelParse(block.content, {\n sourceType: \"module\",\n plugins: babelPluginsFor(block.lang),\n }).program.body;\n } catch {\n return null;\n }\n const offset = block.loc.start.offset;\n for (const statement of body) {\n if (statement.type !== \"ImportDeclaration\") {\n identifierNames(statement, referenced);\n continue;\n }\n if (statement.importKind === \"type\" || !statement.specifiers.length)\n continue;\n imports.push({\n start: offset + statement.start!,\n end: offset + statement.end!,\n sourceText: block.content.slice(\n statement.source.start!,\n statement.source.end!,\n ),\n rewritable: !statement.attributes?.length,\n specifiers: statement.specifiers.map((specifier) => ({\n local: specifier.local.name,\n kind:\n specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : specifier.type === \"ImportNamespaceSpecifier\"\n ? \"namespace\"\n : \"named\",\n text: block.content.slice(specifier.start!, specifier.end!),\n })),\n });\n }\n }\n return { imports, referenced };\n}\n\n/** Every identifier name under `node`. */\nfunction identifierNames(node: unknown, out: Set<string>): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const item of node) identifierNames(item, out);\n return;\n }\n const value = node as { type?: unknown; name?: unknown };\n if (\n (value.type === \"Identifier\" || value.type === \"JSXIdentifier\") &&\n typeof value.name === \"string\"\n )\n out.add(value.name);\n for (const [key, child] of Object.entries(node))\n if (\n key !== \"loc\" &&\n key !== \"leadingComments\" &&\n key !== \"trailingComments\"\n )\n identifierNames(child, out);\n}\n","import type {\n ElementNode,\n NodeTypes,\n TemplateChildNode,\n} from \"@vue/compiler-core\";\nimport { parse as parseSfc, type SFCDescriptor } from \"vue/compiler-sfc\";\nimport { vueMoveUnitEnd } from \"./chain\";\nimport { parseVueSource } from \"./parse\";\nimport {\n collectElement,\n emptyUses,\n pathTo,\n scopeBindingsOf,\n TransferRefusal,\n} from \"./transfer\";\nimport type { PlanVueCopyOptions, VueCopyPlan, VueTargetInfo } from \"./types\";\n\n// compiler-core's enum values (see parse.ts for why they are literals).\nconst ELEMENT_NODE = 1 as NodeTypes.ELEMENT;\n\ntype Refusal = Extract<VueCopyPlan, { kind: \"refused\" }>;\n\n/**\n * Where a copy of the tag at `start` begins. A later branch of a `v-if`\n * chain is what the page shows when the branches before it are false; a\n * copy of it copies the whole chain from its `v-if`, so the copy renders\n * what the original does under every condition. Any other tag, or a branch\n * no `v-if` before it reaches, begins its own copy. A move never does\n * this: a later branch alone refuses to move (`vueMoveUnitEnd`).\n */\nexport function vueCopyUnitStart(\n source: string,\n targets: ReadonlyMap<number, VueTargetInfo>,\n start: number,\n): number {\n const element = targets.get(start);\n const directive = (target: VueTargetInfo, ...names: string[]) =>\n target.props.some(\n (prop) => prop.kind === \"directive\" && names.includes(prop.name),\n );\n if (!element || !directive(element, \"else-if\", \"else\")) return start;\n const chainHead = [...targets.values()]\n .filter(\n (target) =>\n target.parentStart === element.parentStart &&\n target.end <= element.start &&\n directive(target, \"if\"),\n )\n .sort((a, b) => b.start - a.start)[0];\n const reaches =\n chainHead !== undefined &&\n (vueMoveUnitEnd(source, targets, chainHead.start) ?? 0) >= element.end;\n return reaches ? chainHead.start : start;\n}\n\n/**\n * A copy of one authored element within its own file (a Duplicate, or a\n * paste into the board it came from), landing as a child of the element at\n * `parentOffset`: the copied bytes, or why the copy would not read what the\n * original reads there. The component is the same, so props, state,\n * imports and instance properties need nothing, provided its script blocks\n * are the ones the copy was taken against; what can change is the template\n * scope around the bytes:\n *\n * - a name the copy reads from an enclosing `v-for` or `v-slot` must come\n * from that same enclosing construct, which only a copy into the file\n * as it was copied can show (a Duplicate, a paste of an unchanged file);\n * - a name the copy reads from its component must not be bound by a\n * `v-for` or `v-slot` around the destination, which would shadow it;\n * - `v-pre` decides whether `{{ }}` interpolates, so no copy crosses it.\n *\n * The copied unit is a move's (`vueMoveUnitEnd`): from a `v-if` its whole\n * chain, so the copy renders what the original does under every\n * condition; a later branch alone refuses, and the caller starts a copy of\n * one at its chain's `v-if` (`vueCopyUnitStart`). A copied template ref\n * would claim the original's ref, so it refuses too. A copy into another\n * file is `planVueTransfer`'s, which also checks the destination's scope.\n */\nexport function planVueCopy(options: PlanVueCopyOptions): VueCopyPlan {\n try {\n return copy(options);\n } catch (error) {\n // The template reader the copy shares with a transfer refuses by\n // throwing.\n if (error instanceof TransferRefusal)\n return refused(error.code, error.message);\n throw error;\n }\n}\n\nfunction copy(options: PlanVueCopyOptions): VueCopyPlan {\n const sameVersion = options.source === options.destination;\n const from = readTemplate(options.source, options.file);\n if (\"kind\" in from) return from;\n const into = sameVersion\n ? from\n : readTemplate(options.destination, options.file);\n if (\"kind\" in into) return into;\n\n const path = pathTo(from.rootNodes, options.start);\n const node = path[path.length - 1];\n if (!node || node.loc.start.offset !== options.start)\n return refused(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.start}`,\n );\n const destinationPath =\n options.parentOffset === null\n ? []\n : pathTo(into.rootNodes, options.parentOffset);\n const parent = destinationPath[destinationPath.length - 1];\n if (\n options.parentOffset !== null &&\n parent?.loc.start.offset !== options.parentOffset\n )\n return refused(\n \"invalid_anchor\",\n `no Vue template element starts at UTF-16 offset ${options.parentOffset}`,\n );\n\n if (!sameScripts(from.descriptor, into.descriptor))\n return refused(\n \"scope_change\",\n \"The component's script changed since this markup was copied; pasting it into the same component requires AI\",\n );\n const copied = parseVueSource(options.source, options.file);\n const end =\n copied.kind === \"ok\"\n ? vueMoveUnitEnd(options.source, copied.targets, options.start)\n : null;\n if (end === null)\n return refused(\n \"unsupported_structure\",\n \"A v-else-if or v-else branch is copied only with its whole chain: select the chain's v-if branch to copy it\",\n );\n // The element, or its v-if chain: the siblings the unit's bytes span.\n const unit = (path[path.length - 2]?.children ?? from.rootNodes).filter(\n (child): child is ElementNode =>\n child.type === ELEMENT_NODE &&\n child.loc.start.offset >= options.start &&\n child.loc.end.offset <= end,\n );\n // What the unit reads, by the transfer's reader: the names a move would\n // carry, checked here against the scope the copy lands in.\n const uses = emptyUses();\n for (const member of unit) collectElement(member, new Set(), uses);\n const [ref] = uses.refs;\n if (ref !== undefined)\n return refused(\n \"scope_change\",\n `The element is its component's template ref ${ref}; a copy would claim the same ref, so copying it requires AI`,\n );\n // A copy keeps its own `v-pre`; what changes is whether the markup\n // around it is literal, which `parseVueSource` decides for every tag.\n const copiedInVPre =\n (copied.kind === \"ok\" && copied.targets.get(options.start)?.inVPre) ||\n false;\n const destinationTarget =\n options.parentOffset === null\n ? null\n : vueTarget(options.destination, options.file, options.parentOffset);\n const destinationInVPre =\n !!destinationTarget && (destinationTarget.vPre || destinationTarget.inVPre);\n if (copiedInVPre !== destinationInVPre)\n return refused(\n \"scope_change\",\n \"Copying markup across a v-pre boundary changes whether {{ }} interpolates; it requires AI\",\n );\n\n const originBindings = bindingOwners(path.slice(0, -1));\n const destinationBindings = bindingOwners(destinationPath);\n for (const name of uses.names.keys()) {\n const origin = originBindings.get(name);\n const destination = destinationBindings.get(name);\n if (origin !== undefined) {\n // Offsets name the same construct only within one version of a file.\n if (sameVersion && destination === origin) continue;\n return refused(\n \"scope_change\",\n `The markup reads ${name} from an enclosing v-for or v-slot; copying it out of that scope requires AI`,\n );\n }\n if (destination !== undefined)\n return refused(\n \"scope_change\",\n `${name} is bound by a v-for or v-slot where the copy would land, so the copy would read it instead of its component's ${name}; it requires AI`,\n );\n }\n return {\n kind: \"planned\",\n markup: options.source.slice(options.start, end),\n end,\n };\n}\n\nconst refused = (code: Refusal[\"code\"], message: string): Refusal => ({\n kind: \"refused\",\n code,\n message,\n});\n\nfunction vueTarget(source: string, file: string, offset: number) {\n const parsed = parseVueSource(source, file);\n return parsed.kind === \"ok\" ? (parsed.targets.get(offset) ?? null) : null;\n}\n\n/** The SFC's descriptor and template tree. compiler-sfc caches a parse by\n * its bytes and shares the AST, so it is only ever read here. */\nfunction readTemplate(\n source: string,\n file: string,\n): { descriptor: SFCDescriptor; rootNodes: TemplateChildNode[] } | Refusal {\n const { descriptor, errors } = parseSfc(source, {\n filename: file,\n sourceMap: false,\n });\n if (errors.length > 0) return refused(\"invalid_source\", errors[0]!.message);\n if (!descriptor.template?.ast)\n return refused(\n \"unsupported_template\",\n `${file} has no readable <template> block`,\n );\n return { descriptor, rootNodes: descriptor.template.ast.children };\n}\n\n/** Both versions declare the component's bindings with the same bytes. */\nfunction sameScripts(before: SFCDescriptor, after: SFCDescriptor): boolean {\n const spelled = (descriptor: SFCDescriptor) =>\n [descriptor.script, descriptor.scriptSetup].map((block) =>\n block ? `${JSON.stringify(block.attrs)}${block.content}` : null,\n );\n const [script, setup] = spelled(before);\n const [nextScript, nextSetup] = spelled(after);\n return script === nextScript && setup === nextSetup;\n}\n\n/** Each name the ancestors bind for their descendants, by the offset of the\n * nearest one binding it. */\nfunction bindingOwners(ancestors: readonly ElementNode[]): Map<string, number> {\n const owners = new Map<string, number>();\n for (const ancestor of ancestors)\n for (const name of scopeBindingsOf(ancestor))\n owners.set(name, ancestor.loc.start.offset);\n return owners;\n}\n","/**\n * The app's own Vite plugins, composed into a Tempo canvas host.\n *\n * The canvas host serves from `tempo/`, not the app folder, so it cannot run\n * the app's vite.config as it is. This loads that config with Vite's own\n * loader and adapts the plugin instances it builds: they resolve their paths\n * against the app, transform only app modules, never touch the host's HTML,\n * and a plugin that throws while setting up is switched off instead of\n * stopping the host. Plugins that would fight the host (its React, Tempo's\n * annotation, dev tools, HTTPS) are left out. The full design is\n * specs/vue-host-app-vite-plugins.md.\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve } from \"node:path\";\nimport type {\n AliasOptions,\n ConfigEnv,\n Plugin,\n PluginOption,\n UserConfig,\n} from \"vite\";\n\n/** Served by the canvas host: what it did with the app's Vite config. */\nexport const TEMPO_APP_VITE_PLUGINS_ENDPOINT = \"/__tempo/app-vite-plugins\";\n\nexport interface AppVitePluginsReport {\n /** The app's config file, or null when the app folder has none. */\n configFile: string | null;\n status: \"loaded\" | \"missing\" | \"failed\";\n /** Why the config failed to load. */\n error?: string;\n /** Every plugin the config built, in its order. */\n plugins: Array<{ name: string; kept: boolean; reason?: string }>;\n /** Kept plugins switched off because a setup hook threw. */\n disabled: Array<{ name: string; hook: string; error: string }>;\n}\n\nexport interface AppVitePluginsOptions {\n /** The canvas host's Vite root (`tempo/`). */\n hostRoot: string;\n /** The folder holding the app's vite.config. */\n appRoot: string;\n /**\n * The plugin that compiles the app's components, which the host must run\n * exactly once. The app's own instance is used when its config has one;\n * `fallback` builds the host's when it has none or cannot load.\n */\n compiler: { name: string; fallback: () => PluginOption };\n /** More app plugin names (or name prefixes) to leave out, for a plugin the\n * host config adds its own copy of. */\n exclude?: readonly string[];\n}\n\n// Vite's own lookup order (its `DEFAULT_CONFIG_FILES`).\nconst VITE_CONFIG_FILES = [\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.ts\",\n \"vite.config.cjs\",\n \"vite.config.mts\",\n \"vite.config.cts\",\n];\n\n/**\n * App plugins the host never runs, matched by name or name prefix: a plugin\n * object carries no other identity. A name not listed is kept, because the\n * plugins worth running (auto-import, components, macros, router, i18n,\n * UnoCSS) are transform and resolve plugins.\n */\nconst DROPPED_APP_PLUGINS: ReadonlyArray<{\n names: readonly string[];\n reason: string;\n}> = [\n {\n // Route-board setup adds them to the app config; the host runs its own\n // copies with host roots.\n names: [\n \"tempo-annotate\",\n \"tempo-vue-source-annotation\",\n \"tempo-vue-source-records\",\n ],\n reason: \"Tempo's own plugin, which the host already runs\",\n },\n {\n names: [\n \"vite:react\",\n \"@vitejs/plugin-react\",\n \"vite-tsconfig-paths\",\n \"@tailwindcss/vite\",\n ],\n reason: \"the host runs its own copy\",\n },\n {\n // Its config hook takes `.tsx` from the React JSX transform that the\n // canvas files need. Vue JSX components are unsupported on the canvas.\n names: [\"vite:vue-jsx\"],\n reason: \"Vue JSX would take .tsx canvas files from React\",\n },\n {\n // An overlay injected into the host page, template rewrites after\n // Tempo's stamps, hooks wrapped around every plugin, lint findings\n // turned into board errors.\n names: [\n \"vite-plugin-vue-devtools\",\n \"vite-plugin-vue-inspector\",\n \"vite-plugin-inspect\",\n \"vite-plugin-checker\",\n \"vite:eslint\",\n \"vite-plugin-eslint\",\n \"vite-plugin-stylelint\",\n ],\n reason: \"a dev tool\",\n },\n {\n names: [\"vite:html\", \"vite-plugin-html\", \"vite-plugin-pwa\"],\n reason: \"serves the app's index.html or service worker\",\n },\n {\n // Tempo connects to the host over HTTP.\n names: [\"vite:basic-ssl\", \"vite:mkcert\", \"vite-plugin-mkcert\"],\n reason: \"switches the server to HTTPS\",\n },\n];\n\n// Hooks Vite runs once while it sets the server up. A throw in one stops the\n// whole host, so it switches off that plugin instead.\nconst SETUP_HOOKS = new Set([\n \"config\",\n \"configResolved\",\n \"configureServer\",\n \"buildStart\",\n]);\n\n// Hooks handed the config whose `root` a plugin resolves its own `dirs`,\n// `dts` files, globs and config files against.\nconst ROOT_VIEW_HOOKS = new Set([\"config\", \"configResolved\"]);\n\n// The canvas file names the Nuxt sidecar matches too.\nconst CANVAS_MODULE = /\\.canvas\\.[jt]sx$/;\n\n/**\n * Loads the app's Vite config and returns the plugins the host runs in its\n * place: Tempo's settings plugin, the compiler (the app's, or the fallback),\n * then the app's plugins in the app's order. Never throws: a config that\n * cannot load leaves the settings plugin and the fallback compiler.\n */\nexport async function loadAppVitePlugins(\n options: AppVitePluginsOptions,\n): Promise<PluginOption[]> {\n const appRoot = resolve(options.appRoot);\n const configFile = findViteConfigFile(appRoot);\n const report: AppVitePluginsReport = {\n configFile,\n status: \"missing\",\n plugins: [],\n disabled: [],\n };\n if (!configFile) {\n return [\n createHostSettingsPlugin(report, null, []),\n options.compiler.fallback(),\n ];\n }\n\n let loaded: LoadedAppConfig;\n try {\n loaded = await loadAppConfig(configFile, appRoot);\n } catch (error) {\n report.status = \"failed\";\n report.error = errorMessage(error);\n console.warn(\n `[tempo] Could not load the app's Vite config ${configFile}; component boards render without the app's Vite plugins until it loads: ${report.error}`,\n );\n // Watching the file lets a fix on save restart the host with the plugins.\n return [\n createHostSettingsPlugin(report, null, [configFile]),\n options.compiler.fallback(),\n ];\n }\n\n report.status = \"loaded\";\n // Vite resolves a config's `root` against the folder it runs in, which for\n // the app's own dev server is the app folder.\n const appViteRoot = resolve(appRoot, loaded.config.root ?? \".\");\n const isTempoOwned = createTempoOwnedModuleMatcher(options.hostRoot);\n const adopted: Plugin[] = [];\n let hasCompiler = false;\n for (const plugin of loaded.plugins) {\n const name = plugin.name ?? \"\";\n const dropReason = droppedReason(name, options.exclude ?? []);\n if (dropReason) {\n report.plugins.push({ name, kept: false, reason: dropReason });\n continue;\n }\n report.plugins.push({ name, kept: true });\n // plugin-vue turns `config.root` into the dev URL base of relative asset\n // imports, and the host serves those URLs from its own root. It keeps the\n // host's view, exactly as the host's own vue() had.\n const isCompiler = name === options.compiler.name;\n hasCompiler ||= isCompiler;\n adopted.push(\n adoptAppPlugin(plugin, {\n rootView: isCompiler ? null : appViteRoot,\n isTempoOwned,\n report,\n }),\n );\n }\n\n return [\n createHostSettingsPlugin(\n report,\n hostSettingsFromAppConfig(loaded.config, appViteRoot),\n [configFile, ...loaded.dependencies],\n ),\n ...(hasCompiler ? [] : [options.compiler.fallback()]),\n ...adopted,\n ];\n}\n\nfunction findViteConfigFile(appRoot: string): string | null {\n for (const name of VITE_CONFIG_FILES) {\n const file = join(appRoot, name);\n if (existsSync(file)) return file;\n }\n return null;\n}\n\ninterface LoadedAppConfig {\n config: UserConfig;\n plugins: Plugin[];\n dependencies: string[];\n}\n\n// Loads run one at a time, because each one moves the process's working\n// directory: two overlapping restarts must not leave it in the app folder.\nlet appConfigLoads: Promise<unknown> = Promise.resolve();\n\nfunction loadAppConfig(\n configFile: string,\n appRoot: string,\n): Promise<LoadedAppConfig> {\n const load = appConfigLoads.then(() =>\n loadAppConfigFromAppFolder(configFile, appRoot),\n );\n appConfigLoads = load.catch(() => undefined);\n return load;\n}\n\nasync function loadAppConfigFromAppFolder(\n configFile: string,\n appRoot: string,\n): Promise<LoadedAppConfig> {\n // The Vite running this host, from tempo/node_modules. Imported here so\n // `tempo-sdk/vue` loads in configs without a Vite of its own.\n const vite = await import(\"vite\");\n // The host only ever serves in development.\n const env: ConfigEnv = {\n command: \"serve\",\n mode: \"development\",\n isSsrBuild: false,\n isPreview: false,\n };\n // Plugin constructors and package top-levels read the working directory:\n // vue-router's plugin fixes its `root` from it when its module first\n // evaluates, and configs call `loadEnv(mode, process.cwd())`. In the app's\n // own dev server that is the app folder.\n const hostCwd = process.cwd();\n process.chdir(appRoot);\n try {\n const loaded = await vite.loadConfigFromFile(\n env,\n configFile,\n appRoot,\n \"silent\",\n );\n if (!loaded) throw new Error(`${configFile} produced no config`);\n // Inside the same window: a plugin entry may be a promise whose factory\n // is still running.\n const plugins = await flattenPluginOption(loaded.config.plugins);\n return {\n config: loaded.config,\n plugins,\n // Relative to the working directory the bundler ran in: the app folder.\n dependencies: loaded.dependencies.map((file) => resolve(appRoot, file)),\n };\n } finally {\n process.chdir(hostCwd);\n }\n}\n\nasync function flattenPluginOption(option: PluginOption): Promise<Plugin[]> {\n const value = await option;\n if (!value) return [];\n if (Array.isArray(value)) {\n const nested = await Promise.all(value.map(flattenPluginOption));\n return nested.flat();\n }\n return [value];\n}\n\nfunction droppedReason(\n name: string,\n exclude: readonly string[],\n): string | null {\n const matches = (prefix: string) => prefix !== \"\" && name.startsWith(prefix);\n for (const rule of DROPPED_APP_PLUGINS) {\n if (rule.names.some(matches)) return rule.reason;\n }\n if (exclude.some(matches)) return \"listed in exclude\";\n return null;\n}\n\n/**\n * Tempo's own modules: everything under the host root (the host entry,\n * `.tempo/`, canvases under `designs/`, the host's node_modules) and canvas\n * files kept elsewhere. App plugins act on app modules only: an auto-import\n * plugin whose include matches `.tsx` would otherwise rewrite canvas files.\n */\nfunction createTempoOwnedModuleMatcher(\n hostRoot: string,\n): (id: string) => boolean {\n const resolvedRoot = resolve(hostRoot);\n // Module ids are real paths; a host root reached through a symlink\n // (macOS's /var → /private/var) spells the same folder differently.\n const roots = [resolvedRoot, realPathOrSelf(resolvedRoot)];\n return (id) => {\n const file = id.split(\"?\", 1)[0] ?? id;\n return (\n CANVAS_MODULE.test(file) || roots.some((root) => isWithin(root, file))\n );\n };\n}\n\nfunction realPathOrSelf(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nfunction isWithin(directory: string, file: string): boolean {\n const relativePath = relative(directory, file);\n return (\n relativePath === \"\" ||\n (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath))\n );\n}\n\ninterface AdoptionScope {\n /** The app's Vite root shown to the plugin's config hooks; null keeps the\n * host's. */\n rootView: string | null;\n isTempoOwned: (id: string) => boolean;\n report: AppVitePluginsReport;\n}\n\ntype HookHandler = (this: unknown, ...args: unknown[]) => unknown;\n\n/**\n * Adapts an app plugin to the host in place. The instance belongs to this\n * load alone (each load imports a fresh bundle of the config), so changing it\n * is safe and keeps every property Vite reads (`enforce`, `apply`, `api`,\n * hook `order` and `filter`).\n */\nfunction adoptAppPlugin(plugin: Plugin, scope: AdoptionScope): Plugin {\n // The host document is Tempo's; an app's HTML transforms assume its own\n // index.html.\n delete plugin.transformIndexHtml;\n\n let disabled = false;\n const disable = (hook: string, error: unknown) => {\n disabled = true;\n const message = errorMessage(error);\n scope.report.disabled.push({ name: plugin.name, hook, error: message });\n console.warn(\n `[tempo] Disabled the app's Vite plugin \"${plugin.name}\": its ${hook} hook threw: ${message}`,\n );\n };\n\n const hooks = plugin as unknown as Record<string, unknown>;\n for (const key of Object.keys(hooks)) {\n // Vite calls `apply` to decide whether the plugin runs at all.\n if (key === \"apply\") continue;\n const hook = hooks[key];\n const handler = hookHandler(hook);\n if (!handler) continue;\n\n const appViteRoot = ROOT_VIEW_HOOKS.has(key) ? scope.rootView : null;\n const isSetupHook = SETUP_HOOKS.has(key);\n const wrapped: HookHandler = function (this: unknown, ...args) {\n if (disabled) return undefined;\n if (key === \"transform\" && scope.isTempoOwned(String(args[1]))) {\n return undefined;\n }\n let rootView: object | undefined;\n if (appViteRoot !== null) {\n rootView = withRoot(args[0] as object, appViteRoot);\n args[0] = rootView;\n }\n const keepHostRoot = (result: unknown) =>\n key === \"config\" && rootView ? withoutRoot(result, rootView) : result;\n if (!isSetupHook) return handler.apply(this, args);\n try {\n const result = handler.apply(this, args);\n if (!isPromiseLike(result)) return keepHostRoot(result);\n return Promise.resolve(result).then(keepHostRoot, (error) =>\n disable(key, error),\n );\n } catch (error) {\n disable(key, error);\n return undefined;\n }\n };\n hooks[key] =\n typeof hook === \"function\"\n ? wrapped\n : { ...(hook as object), handler: wrapped };\n }\n return plugin;\n}\n\nfunction hookHandler(hook: unknown): HookHandler | null {\n if (typeof hook === \"function\") return hook as HookHandler;\n if (hook && typeof hook === \"object\" && \"handler\" in hook) {\n const { handler } = hook as { handler: unknown };\n if (typeof handler === \"function\") return handler as HookHandler;\n }\n return null;\n}\n\n/** The config as the app's own dev server would show it: `root` answers the\n * app's Vite root, and every other read and write reaches the real config. */\nfunction withRoot<T extends object>(config: T, root: string): T {\n if (!config || typeof config !== \"object\") return config;\n return new Proxy(config, {\n get: (target, key) => (key === \"root\" ? root : Reflect.get(target, key)),\n });\n}\n\n/** A config hook's result without a root change: the host's root is not an\n * app plugin's to move, and a plugin that returns (or spreads) the config it\n * was handed would otherwise hand back the app's root. */\nfunction withoutRoot(result: unknown, rootView: object): unknown {\n // Returned in place: its writes already reached the real config.\n if (result === rootView) return undefined;\n if (!result || typeof result !== \"object\" || !(\"root\" in result)) {\n return result;\n }\n const { root: _appRoot, ...rest } = result as Record<string, unknown>;\n return rest;\n}\n\n/**\n * Tempo's plugin around the app's: merges the app's compile settings into the\n * host config, watches the app config, and serves the report.\n */\nfunction createHostSettingsPlugin(\n report: AppVitePluginsReport,\n settings: UserConfig | null,\n dependencies: string[],\n): Plugin {\n return {\n name: \"tempo-app-vite-config\",\n config: () => settings ?? undefined,\n configResolved(config) {\n // Vite watches its config's dependencies and restarts the server when\n // one changes. Restarting re-runs the host config, which reloads the\n // app config: an edited plugin option or a fixed config applies on\n // save.\n for (const file of dependencies) {\n const normalized = resolve(file).replace(/\\\\/g, \"/\");\n if (!config.configFileDependencies.includes(normalized)) {\n config.configFileDependencies.push(normalized);\n }\n }\n },\n configureServer(server) {\n server.middlewares.use(TEMPO_APP_VITE_PLUGINS_ENDPOINT, (_req, res) => {\n res.statusCode = 200;\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(report));\n });\n },\n };\n}\n\n/**\n * The app config's settings that change how app modules compile and resolve.\n * The host keeps its own root, server, build, dependency optimizer, PostCSS\n * and JSX settings: those serve Tempo's page and the React canvas files.\n * `resolve.dedupe` stays the host's too, because Vite resolves a deduped\n * package from `tempo/`, where the app's packages are not installed.\n */\nfunction hostSettingsFromAppConfig(\n app: UserConfig,\n appViteRoot: string,\n): UserConfig {\n const settings: UserConfig = {\n // `import.meta.env.VITE_*` from the app's `.env` files. Vite reads a\n // relative envDir from the root, which here is the app's.\n envDir:\n app.envDir === false ? false : resolve(appViteRoot, app.envDir ?? \".\"),\n };\n if (app.envPrefix) settings.envPrefix = app.envPrefix;\n if (app.define) settings.define = app.define;\n if (app.assetsInclude) settings.assetsInclude = app.assetsInclude;\n\n const resolveSettings: NonNullable<UserConfig[\"resolve\"]> = {};\n if (app.resolve?.alias) {\n resolveSettings.alias = withAbsoluteAliases(app.resolve.alias, appViteRoot);\n }\n if (app.resolve?.extensions) {\n resolveSettings.extensions = app.resolve.extensions;\n }\n if (Object.keys(resolveSettings).length > 0) {\n settings.resolve = resolveSettings;\n }\n\n const cssSettings: NonNullable<UserConfig[\"css\"]> = {};\n if (app.css?.preprocessorOptions) {\n cssSettings.preprocessorOptions = app.css.preprocessorOptions;\n }\n if (app.css?.modules) cssSettings.modules = app.css.modules;\n if (Object.keys(cssSettings).length > 0) settings.css = cssSettings;\n return settings;\n}\n\n/** `'@': '/src'` points at the app's `src`, but a leading `/` means the root,\n * and the host's root is `tempo/`. */\nfunction withAbsoluteAliases(\n alias: AliasOptions,\n appViteRoot: string,\n): AliasOptions {\n const absolute = (replacement: string) => {\n const appRelative = join(appViteRoot, replacement);\n const isRootRelative =\n replacement.startsWith(\"/\") &&\n !existsSync(replacement) &&\n existsSync(appRelative);\n return isRootRelative ? appRelative.replace(/\\\\/g, \"/\") : replacement;\n };\n if (Array.isArray(alias)) {\n return alias.map((entry) => ({\n ...entry,\n replacement: absolute(entry.replacement),\n }));\n }\n return Object.fromEntries(\n Object.entries(alias as Record<string, string>).map(\n ([find, replacement]) => [find, absolute(replacement)],\n ),\n );\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAS,oBAAoB;AAC7B,SAAS,cAAAA,aAAY,YAAAC,WAAU,WAAAC,gBAAe;;;ACJvC,SAAS,wBACd,OACA,QAAmB,KACX;AACR,QAAM,UAAU,MACb,MAAM,GAAG,EACT,KAAK,OAAO,EACZ,MAAM,GAAG,EACT,KAAK,QAAQ,EACb,MAAM,GAAG,EACT,KAAK,MAAM,EACX,MAAM,GAAG,EACT,KAAK,MAAM;AACd,SAAO,UAAU,MAAM,QAAQ,MAAM,GAAG,EAAE,KAAK,OAAO,IAAI;AAC5D;;;ACVO,SAAS,kBAAkB,UAA0B;AAC1D,MAAI,SAAS,WAAW,IAAI,EAAG,QAAO;AACtC,SAAO,SACJ,QAAQ,SAAS,KAAK,EACtB,QAAQ,aAAa,CAAC,GAAG,WAAmB,OAAO,YAAY,CAAC;AACrE;;;ACVA,SAAS,YAAY,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8B,MAAM,QAAQ;AACjE,iBAAO;AAAA,YACL,MAAM;AAAA,cACJ;AAAA,cACA,SAAS;AAAA,cACT,SAAS;AAAA,cACT,SAAS;AAAA,YACX;AAAA;AAAA,YAEA,KAAK;AAAA,UACP;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAwBO,SAAS,mBACd,SACyB;AACzB,SAAO,mBAAmB;AAAA,IACxB,UAAU,QAAQ;AAAA,IAClB,SAAS,QAAQ;AAAA,IACjB,UAAU,EAAE,MAAM,YAAY,UAAU,QAAQ,IAAI;AAAA,IACpD,SAAS,QAAQ;AAAA,EACnB,CAAC;AACH;AAEA,SAAS,WAAW,MAAc,aAAgC;AAChE,SAAO,YAAY,KAAK,CAAC,cAAc;AACrC,UAAM,eAAeC,UAAS,WAAW,IAAI;AAC7C,WACE,iBAAiB,MAChB,CAAC,aAAa,WAAW,IAAI,KAAK,CAACC,YAAW,YAAY;AAAA,EAE/D,CAAC;AACH;","names":["isAbsolute","relative","resolve","babelParse","name","babelParse","babelParse","parseSfc","resolve","relative","isAbsolute"]}
package/package.json CHANGED
@@ -1,11 +1,13 @@
1
1
  {
2
2
  "name": "tempo-sdk",
3
- "version": "0.0.69",
3
+ "version": "0.0.75",
4
+
4
5
  "publishConfig": {
5
6
  "tag": "sdk-v2-latest"
6
7
  },
7
8
  "type": "module",
8
- "description": "Tempo SDK — Vite, Next.js, Expo, Svelte and Astro canvas integration, source annotations and storyboard types",
9
+ "description": "Tempo SDK \u2014 Vite, Next.js, Nuxt, Expo, Svelte, Vue and Astro canvas integration, source annotations and storyboard types",
10
+
9
11
  "repository": {
10
12
  "type": "git",
11
13
  "url": "git+https://github.com/TempoLabsAI/tempo-monorepo.git",
@@ -44,6 +46,10 @@
44
46
  "types": "./dist/canvas/svelte.d.ts",
45
47
  "import": "./dist/canvas/svelte.js"
46
48
  },
49
+ "./canvas/vue": {
50
+ "types": "./dist/canvas/vue.d.ts",
51
+ "import": "./dist/canvas/vue.js"
52
+ },
47
53
  "./canvas/interact-projection": {
48
54
  "types": "./dist/canvas/interact-projection.d.ts",
49
55
  "import": "./dist/canvas/interact-projection.js"
@@ -77,6 +83,10 @@
77
83
  "types": "./dist/nextjs/plugin.d.ts",
78
84
  "import": "./dist/nextjs/plugin.js"
79
85
  },
86
+ "./nuxt": {
87
+ "types": "./dist/nuxt.d.ts",
88
+ "import": "./dist/nuxt.js"
89
+ },
80
90
  "./expo": {
81
91
  "types": "./dist/expo-babel-plugin.d.ts",
82
92
  "import": "./dist/expo-babel-plugin.js",
@@ -91,9 +101,21 @@
91
101
  "types": "./dist/svelte.d.ts",
92
102
  "import": "./dist/svelte.js"
93
103
  },
104
+ "./vue": {
105
+ "types": "./dist/vue.d.ts",
106
+ "import": "./dist/vue.js"
107
+ },
94
108
  "./astro/asset-preview-client": {
95
109
  "types": "./dist/astro/asset-preview-client.d.ts",
96
110
  "import": "./dist/astro/asset-preview-client.js"
111
+ },
112
+ "./flutter-preview-path": {
113
+ "types": "./dist/flutter-preview-path.d.ts",
114
+ "import": "./dist/flutter-preview-path.js"
115
+ },
116
+ "./canvas/flutter-preview": {
117
+ "types": "./dist/canvas/flutter-preview.d.ts",
118
+ "import": "./dist/canvas/flutter-preview.js"
97
119
  }
98
120
  },
99
121
  "files": [
@@ -108,8 +130,9 @@
108
130
  "prepublishOnly": "pnpm build",
109
131
  "demo": "TEMPO=true pnpm --filter @tempo-modules/vite-annotate-plugin-demo dev",
110
132
  "demo:nextjs": "TEMPO=true pnpm --filter @tempo-modules/tempo-sdk-nextjs-demo dev",
133
+ "demo:nuxt": "pnpm --filter @tempo-modules/tempo-sdk-nuxt-demo dev",
111
134
  "test": "vitest run",
112
- "test:browser": "vitest run canvas-dependency-scan-browser.test.ts pruned-module-deletion-browser.test.ts asset-live-preview-browser.test.ts asset-popover-lifecycle-browser.test.ts component-controls-browser.test.ts canvas-controls-browser.test.ts canvas-capture-determinism-browser.test.ts canvas-host-vite-e2e.test.ts canvas-host-packed-sdk-e2e.test.ts error-tracking-e2e.test.ts astro-integration.test.ts astro-storyboard-routing.test.ts astro-react-integration.test.ts astro-descriptor-browser.test.ts astro-packed.test.ts",
135
+ "test:browser": "vitest run canvas-dependency-scan-browser.test.ts pruned-module-deletion-browser.test.ts asset-live-preview-browser.test.ts asset-popover-lifecycle-browser.test.ts component-controls-browser.test.ts canvas-controls-browser.test.ts canvas-capture-determinism-browser.test.ts flutter-storyboard-browser.test.ts canvas-host-vite-e2e.test.ts canvas-host-packed-sdk-e2e.test.ts error-tracking-e2e.test.ts astro-integration.test.ts astro-storyboard-routing.test.ts astro-react-integration.test.ts astro-descriptor-browser.test.ts astro-packed.test.ts",
113
136
  "test:watch": "vitest",
114
137
  "test:nextjs:unit": "vitest run nextjs-loader.test.ts nextjs-wrapper.test.ts nextjs-fixtures.test.ts nextjs-published.test.ts",
115
138
  "test:nextjs:integration": "vitest run nextjs-e2e-correctness.test.ts",
@@ -126,10 +149,13 @@
126
149
  "peerDependencies": {
127
150
  "astro": "^7.0.0",
128
151
  "@babel/core": "^7.0.0",
152
+ "h3": "^1.12.0",
129
153
  "next": "^13 || ^14 || ^15 || ^16",
154
+ "nuxt": "^3.18.0 || ^4.0.0",
130
155
  "react": "^18 || ^19",
131
156
  "svelte": "^5.0.0",
132
- "vite": "^5 || ^6 || ^7 || ^8"
157
+ "vite": "^5 || ^6 || ^7 || ^8",
158
+ "vue": "^3.3.0"
133
159
  },
134
160
  "peerDependenciesMeta": {
135
161
  "astro": {
@@ -141,14 +167,23 @@
141
167
  "@babel/core": {
142
168
  "optional": true
143
169
  },
170
+ "h3": {
171
+ "optional": true
172
+ },
144
173
  "next": {
145
174
  "optional": true
146
175
  },
176
+ "nuxt": {
177
+ "optional": true
178
+ },
147
179
  "svelte": {
148
180
  "optional": true
149
181
  },
150
182
  "vite": {
151
183
  "optional": true
184
+ },
185
+ "vue": {
186
+ "optional": true
152
187
  }
153
188
  },
154
189
  "devDependencies": {
@@ -158,14 +193,21 @@
158
193
  "@modules/annotation": "workspace:*",
159
194
  "@modules/astro-editor": "workspace:*",
160
195
  "@modules/file-parser": "workspace:*",
196
+ "@modules/frame-pool": "workspace:*",
197
+ "@modules/iframe-projection": "workspace:*",
161
198
  "@modules/svelte-editor": "workspace:*",
199
+ "@modules/vue-editor": "workspace:*",
200
+ "@nuxt/kit": "^4.6.2",
162
201
  "@types/babel__core": "^7.20.5",
163
202
  "@types/node": "^25.0.8",
164
203
  "@types/react": "catalog:",
165
204
  "@types/react-dom": "catalog:",
166
205
  "@vitejs/plugin-react": "catalog:",
206
+ "@vitejs/plugin-vue": "6.0.10",
167
207
  "astro": "7.3.8",
208
+ "h3": "^1.15.11",
168
209
  "magic-string": "^0.30.21",
210
+ "nuxt": "^4.6.2",
169
211
  "playwright": "^1.58.2",
170
212
  "react-dom": "catalog:",
171
213
  "react-dom18": "npm:react-dom@18.3.1",
@@ -174,6 +216,7 @@
174
216
  "tsup": "^8.5.1",
175
217
  "typescript": "catalog:",
176
218
  "vite": "catalog:",
177
- "vitest": "catalog:"
219
+ "vitest": "catalog:",
220
+ "vue": "3.5.44"
178
221
  }
179
222
  }