@tempo-ai/mcp 0.0.151-staging.1 → 0.0.151

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.
@@ -317,7 +317,7 @@ hostStyles.viteConfig = (config, options = {}) => runtime(options.base).viteConf
317
317
  hostStyles.refreshSources = () => runtime().refreshSources();
318
318
  hostStyles.stopSources = () => { for (const value of runtimes.values()) value.stopSources(); };
319
319
  module.exports = hostStyles;
320
- `;function resolveAppUiFramework(e){if("flutter"===e)return"react";if(void 0===e)return"react";if(isTempoUiFramework(e)&&"flutter"!==e)return e;const t=iy.map(e=>`"${e}"`).join(", ");throw new Error(`tempo.config.json sets apps[0].uiFramework to "${e}", which this version of Tempo does not support (it supports ${t}). Update Tempo to use this project's canvas. Tempo keeps the value as written.`)}var yT={react:["vite","nextjs","expo"],svelte:["vite"],vue:["vite","nuxt"],astro:["vite"],flutter:["vite"]};function canvasHostRendersUiFramework(e,t){return yT[t].includes(e)}async function pathExists4(e){try{return await Zy(e),!0}catch{return!1}}async function ensureDirectoryExists(e){await eb(e,{recursive:!0})}var bT={"@tailwindcss/vite":"^4.0.0","@vitejs/plugin-react":"^5.0.0",tailwindcss:"^4.0.0",postcss:"^8.5.6","tempo-sdk":vb,typescript:"^5.9.0",vite:"^7.0.0","vite-tsconfig-paths":"^6.0.0"},vT={"postcss-load-config":"^6.0.1","@vitejs/plugin-react":"^5.0.0",autoprefixer:"^10.4.20",postcss:"^8.4.49",tailwindcss:"^3.4.17","tempo-sdk":vb,typescript:"^5.9.0",vite:"^7.0.0","vite-tsconfig-paths":"^6.0.0"},wT={react:"^18.3.1","react-dom":"^18.3.1"},_T={svelte:"5.56.9"},xT={"@sveltejs/vite-plugin-svelte":"6.2.4"},TT={vue:"3.5.44"},kT={"@vitejs/plugin-vue":"6.0.10"},ST={react:{label:"React",marker:null,imports:"",pluginCalls:()=>"",reactPluginCall:" react(),\n",dedupe:[],prebundle:[],tsconfigPathsOptions:"",packages:null},svelte:{label:"Svelte",marker:"// @tempo-ui-framework: svelte",imports:'import { svelte } from "@sveltejs/vite-plugin-svelte";\n',pluginCalls:()=>' svelte({ configFile: path.join(tempoRoot, "svelte.config.mjs") }),\n',reactPluginCall:" react(),\n",dedupe:["svelte"],prebundle:[],tsconfigPathsOptions:"",packages:{dependencies:_T,runtimeFollowsApp:!1,devDependencies:xT,appSignals:["svelte","@sveltejs/kit"]}},vue:{label:"Vue",marker:"// @tempo-ui-framework: vue",imports:'import vue from "@vitejs/plugin-vue";\nimport { tempoVueAppPlugins, tempoVuePlugin } from "tempo-sdk/vue";\n',pluginCalls:e=>` ...tempoVuePlugin({ root: tempoRoot, sourceRoot: projectRoot, enabled: true }),\n tempoVueAppPlugins({ root: tempoRoot, appRoot: ${vueAppRootExpression(e)}, vue }),\n`,reactPluginCall:' react({ jsxImportSource: "react" }),\n',dedupe:["vue"],prebundle:["vue"],tsconfigPathsOptions:" importerFilter: (importer) => /\\.(vue|[mc]?[jt]sx?)$/.test(importer),\n",packages:{dependencies:TT,runtimeFollowsApp:!0,devDependencies:kT,appSignals:["vue","nuxt"]}},astro:{label:"Astro",marker:null,imports:"",pluginCalls:()=>"",reactPluginCall:" react(),\n",dedupe:[],prebundle:[],tsconfigPathsOptions:"",packages:null}},ET={dev:"vite",build:"vite build",preview:"vite preview --host 127.0.0.1"},AT={"@tailwindcss/postcss":"^4.0.0","@types/node":"^25.0.0","@types/react":"^19.0.0","@types/react-dom":"^19.0.0","tempo-sdk":vb,tailwindcss:"^4.0.0",postcss:"^8.5.6",typescript:"^5.9.0"},CT={"@types/node":"^25.0.0","@types/react":"^19.0.0","@types/react-dom":"^19.0.0",autoprefixer:"^10.4.20",postcss:"^8.4.49","postcss-import":"^16.1.0","postcss-url":"^10.1.3","tempo-sdk":vb,tailwindcss:"^3.4.17",typescript:"^5.9.0"},IT={next:"^16.0.0",react:"^19.0.0","react-dom":"^19.0.0"},PT={dev:"next dev -p 0",build:"next build",start:"next start -p 0"},DT=new Set(["@tailwindcss/vite","@vitejs/plugin-react","vite","vite-tsconfig-paths"]),RT={"@types/react":"^19.2.0","tempo-sdk":vb,typescript:"^5.9.0"},NT={expo:"~56.0.5",react:"19.2.3","react-dom":"19.2.3","react-native":"0.85.3","react-native-web":"~0.21.0"},OT=new Set(["expo-constants","expo-linking","expo-router","expo-splash-screen","react-native-reanimated","react-native-safe-area-context","react-native-screens","react-native-worklets"]),FT={dev:"expo start --web",start:"expo start --web"},LT='<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <title>tempo-host</title>\n </head>\n <body>\n <div id="root"></div>\n <script type="module" src="./main.tsx"><\/script>\n </body>\n</html>\n',MT='import { createRoot } from "react-dom/client";\nimport "./globals.css";\nimport TempoHost from "./.tempo/tempo-host";\n\n// This is the Tempo canvas dev server ("tempo-host"). It exists only to render\n// your real components onto the design canvas — it is NOT your app. Build your\n// actual app OUTSIDE the tempo/ folder, at the project root (e.g. src/...).\n//\n// Deliberately NOT wrapped in <StrictMode>: the host mounts every storyboard as\n// its own full production component tree (often dozens of live frames), and\n// StrictMode\'s dev-only double-invoke of every render + mount effect roughly\n// doubles that mount cost — a real, visible "the canvas takes a while to load"\n// hit. StrictMode renders nothing and is dev-only, so omitting it here is purely\n// a canvas load-time win with zero visual or production impact. Your real app\n// (outside tempo/) keeps whatever StrictMode setup it already had.\ncreateRoot(document.getElementById("root")!).render(<TempoHost />);\n',UT='// @tempo-home — Tempo home canvas (the workspace Run button opens this). Managed marker; do not remove.\n//\n// One storyboard rendering your app\'s home route ("/"). Run (workspace header)\n// opens this canvas beside your app\'s dev-server logs. Set the app dev command\n// (set_app_dev_command) so the "/" route renders here.\n\nimport { Canvas, RouteStoryboard } from "tempo-sdk/canvas";\n\nexport default function HomeCanvas() {\n return (\n <Canvas name="Home">\n <RouteStoryboard\n id="Home"\n name="Home (/)"\n route="/"\n layout={{ x: 0, y: 0, width: 1280, height: 832 }}\n />\n </Canvas>\n );\n}\n',jT='export default function Page() {\n return (\n <main className="min-h-screen flex items-center justify-center bg-[#0E0E0E] text-white/60">\n <p className="text-sm">Tempo canvas dev server. Open the Design tab to view canvases.</p>\n </main>\n );\n}\n',BT='"use client";\n\nimport dynamic from "next/dynamic";\n\nconst TempoHost = dynamic(() => import("../../.tempo/tempo-host"), {\n ssr: false,\n});\n\nexport default function Page() {\n return <TempoHost />;\n}\n',$T="// @tempo-owned: nuxt-sidecar",WT="nuxt.config.ts",HT="nuxt-app-layer",qT='// @tempo-owned: nuxt-app-layer\n// Loaded by your app\'s own `nuxt dev` for Tempo route storyboards through\n// `--extends` in tempo/tempo.config.json (apps[0].start), never from your\n// nuxt.config. It only annotates your .vue sources for the canvas, and only\n// when Tempo starts the server (TEMPO=true).\nexport default defineNuxtConfig({\n modules: ["tempo-sdk/nuxt"],\n});\n',zT=["nuxt.config.ts","nuxt.config.js","nuxt.config.mjs","nuxt.config.mts","nuxt.config.cjs"],GT="app",VT=["app.vue","pages/tempo-host.vue","components/TempoHostMount.vue"],KT="\x3c!-- Tempo canvas dev server, not your app. Build your app outside tempo/. --\x3e\n<template>\n <NuxtPage />\n</template>\n",XT='<script setup lang="ts">\ndefinePageMeta({ layout: false });\n<\/script>\n\n<template>\n <ClientOnly>\n <TempoHostMount />\n </ClientOnly>\n</template>\n',YT="// @tempo-owned: expo-index";function buildExpoIndexJs(e={}){const t=e.nativewind?'import "./global.css";\n':"",n=e.metroRuntime?'import "@expo/metro-runtime";\n':"";return`${YT}\n${t}${n}import { registerRootComponent } from "expo";\nimport App from "./App";\n\nregisterRootComponent(App);\n`}function isTempoOwnedExpoIndexJs(e){return!!e.startsWith(YT)||e.includes("registerRootComponent")&&e.includes('"./App"')}var JT="// Tempo-generated inert stub for Storybook imports in the canvas host.\nfunction StorybookStub() {\n return null;\n}\nmodule.exports = StorybookStub;\nmodule.exports.default = StorybookStub;\n",QT='import { Text, View } from "react-native";\nimport TempoHost from "./.tempo/tempo-host";\n\nconst isTempoHostRoute =\n typeof window !== "undefined" &&\n window.location.pathname.startsWith("/tempo-host");\n\nexport default function App() {\n if (isTempoHostRoute) {\n return <TempoHost />;\n }\n\n return (\n <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>\n <Text>Tempo Expo sidecar</Text>\n </View>\n );\n}\n';function buildExpoPublicIndexHtml(e){return'<!DOCTYPE html>\n<html lang="%LANG_ISO_CODE%">\n <head>\n <meta charset="utf-8" />\n <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />\n \x3c!--\n The `content` is stamped at runtime by the tempo-sdk Expo Babel plugin\n (which writes this machine\'s absolute sidecar root into the live DOM). It\n is intentionally left empty here so this committed file holds no\n machine-specific path. The empty marker still satisfies the dev server\'s\n tempo-host readiness check, which greps the served HTML for the attribute\n name (`tempo-devserver.ts` `isTempoHostDocument`).\n --\x3e\n <meta name="tempo-project-root" content="" />\n <title>%WEB_TITLE%</title>\n <style id="expo-reset">\n html,\n body {\n height: 100%;\n }\n body {\n overflow: hidden;\n }\n #root {\n display: flex;\n height: 100%;\n flex: 1;\n }\n </style>\n </head>\n\n <body>\n <noscript>You need to enable JavaScript to run this app.</noscript>\n <div id="root"></div>\n </body>\n</html>\n'}function buildExpoAppJson(e){return`${JSON.stringify({expo:{name:`${lb.basename(e.projectRoot)} Tempo`,slug:sanitizePackageName(`${lb.basename(e.projectRoot)}-tempo`),platforms:["web"],web:{bundler:"metro"},scheme:"tempo-sidecar"}},null,2)}\n`}var ZT="// @tempo-owned: expo-babel-config";function buildExpoBabelConfig(e={}){const t=e.nativewind?'[\n ["babel-preset-expo", { jsxImportSource: "nativewind" }],\n "nativewind/babel",\n ]':'["babel-preset-expo"]';return`${ZT}\nconst { tempoExpoBabelPlugin } = require("tempo-sdk/expo/plugin");\n\nmodule.exports = function (api) {\n // The Tempo plugin only annotates when TEMPO=true. Key Babel's config cache\n // on TEMPO (instead of api.cache(true)) so toggling it re-evaluates the\n // config rather than reusing a stale build.\n api.cache.using(() => process.env.TEMPO);\n return {\n presets: ${t},\n plugins: [\n [\n tempoExpoBabelPlugin,\n {\n // Annotate filepaths relative to the Tempo sidecar root (this dir),\n // matching the Next.js sidecar convention. The canvas resolves\n // \`data-tempo-filepath\` against the \`tempo-project-root\` meta (also\n // this dir), so parent app code resolves via \`../src/...\`.\n root: __dirname,\n },\n ],\n ],\n };\n};\n`}function isTempoOwnedExpoBabelConfig(e){return!!e.startsWith(ZT)||e.includes('require("tempo-sdk/expo/plugin")')&&e.includes("api.cache.using(() => process.env.TEMPO)")}function convertAliasPathsToMetroEntries(e){const t=[];for(const[n,r]of Object.entries(e)){if(0===r.length)continue;const e=r[0];n.endsWith("/*")&&e.endsWith("/*")&&t.push({prefix:n.slice(0,-1),targetRelToTempo:e.slice(0,-2)||"."})}return t}var ek="// @tempo-owned: expo-metro-config";function buildExpoMetroConfig(e=[],t={}){const n=JSON.stringify(e.map(e=>({prefix:e.prefix,target:e.targetRelToTempo}))),r=JSON.stringify(Object.fromEntries((t.webShims??[]).map(e=>[e.module,e.targetRelToTempo]))),s=t.svgTransformer?'\n// react-native-svg-transformer: turn .svg imports into components.\nconfig.transformer.babelTransformerPath = require.resolve(\n "react-native-svg-transformer/expo",\n);\nconfig.resolver.assetExts = config.resolver.assetExts.filter(\n (ext) => ext !== "svg",\n);\nconfig.resolver.sourceExts = [...config.resolver.sourceExts, "svg"];\n':"",i=t.nativewind?'const { withNativeWind } = require("nativewind/metro");\n':"",o=t.nativewind?'module.exports = withNativeWind(config, { input: "./global.css" });':"module.exports = config;";return`${ek}\nconst path = require("node:path");\nconst fs = require("node:fs");\nconst { getDefaultConfig } = require("expo/metro-config");\n${i}\nconst projectRoot = __dirname;\nconst workspaceRoot = path.resolve(projectRoot, "..");\nconst sidecarNodeModules = path.join(projectRoot, "node_modules");\n\nconst config = getDefaultConfig(projectRoot);\n\n// Resolve packages via their legacy \`main\`/\`react-native\`/\`browser\` fields\n// (CJS) instead of the modern \`exports\` conditions. Some deps ship an ESM\n// build under \`exports["import"]\` that uses Vite-isms (\`import.meta.env.MODE\`,\n// \`import.meta.url\`) — e.g. zustand 5's \`./esm/middleware.mjs\`, which a store\n// using \`zustand/middleware\` pulls in. On web Metro matches the \`import\`\n// condition and bundles that ESM build verbatim (it does NOT transform\n// \`import.meta\`), so the module throws "Cannot use 'import.meta' outside a\n// module" the moment it loads in the classic-script web bundle — taking the\n// storyboard that imported it down with it. Disabling package exports makes\n// Metro fall back to \`main\` (CJS, no \`import.meta\`). Tightening the condition\n// set alone is NOT enough — Metro still picks the ESM build for web. The\n// trade-off: a package that ONLY ships via \`exports\` (no \`main\`) won't\n// resolve, but those are rare in the Expo/RN ecosystem (RN requires CJS).\nconfig.resolver.unstable_enablePackageExports = false;\n\n// Storybook stub. Storybook for React Native leaks into a canvas's module\n// graph (a canvas importing \`@/app/storybook\`, Expo Router auto-discovering\n// \`app/storybook.tsx\`, or \`.rnstorybook/storybook.requires\` globbing every\n// \`*.stories.*\` file). It then pulls on-device addons (\`@storybook/addon-*\`)\n// and native-only deps (\`@gorhom/bottom-sheet\`) that aren't installed for web,\n// failing the WHOLE bundle (eager canvas requires mean one broken canvas\n// breaks all). Storybook is never rendered in a canvas, so the resolveRequest\n// hook below substitutes any storybook/story import with an inert stub\n// (emitted at \`.tempo-storybook-stub.js\`). The matching tests live in the\n// metro-resolve suite.\nconst tempoStorybookStub = path.resolve(projectRoot, ".tempo-storybook-stub.js");\nconst isStorybookModule = (name) =>\n name.includes("storybook") || /\\.stories(\\.|$)/.test(name);\n${s}\n// NOTE: We deliberately do NOT \`require()\` and inherit the user app's\n// metro.config.js. Many real configs (NativeWind via withNativeWind, Storybook\n// via withStorybook) throw when evaluated outside their own project context\n// ("Tailwind CSS has not been configured with the NativeWind preset"), which\n// would break the whole sidecar bundle. Per-feature support (svg transformer,\n// NativeWind, web shims) is added explicitly here rather than by wholesale\n// config inheritance.\nconst userMetroResolveRequest = null;\n\nconst sidecarModule = (moduleName) =>\n path.join(sidecarNodeModules, ...moduleName.split("/"));\nconst singletonModules = {\n react: sidecarModule("react"),\n "react-dom": sidecarModule("react-dom"),\n "react-native": sidecarModule("react-native"),\n "react-native-web": sidecarModule("react-native-web"),\n "react/jsx-runtime": sidecarModule("react/jsx-runtime.js"),\n "react/jsx-dev-runtime": sidecarModule("react/jsx-dev-runtime.js"),\n};\n\nconfig.watchFolders = Array.from(\n new Set([...(config.watchFolders ?? []), workspaceRoot]),\n);\nconfig.resolver.nodeModulesPaths = Array.from(\n new Set([\n sidecarNodeModules,\n path.join(workspaceRoot, "node_modules"),\n ...(config.resolver.nodeModulesPaths ?? []),\n ]),\n);\n// Hierarchical lookup stays ENABLED so Metro can walk parent directories to\n// resolve transitively-nested deps (e.g. react-native-reanimated@4's bundled\n// semver@7, required by its scripts/validate-worklets-version.js — the\n// root-hoisted semver@6 has no functions/satisfies subpath, so disabling the\n// walk fails the canvas at module load: "Unable to resolve module\n// semver/functions/satisfies").\n//\n// The trade-off: with hierarchical lookup on, Metro's resolver.alias /\n// extraNodeModules become FALLBACKS — a hierarchical walk can find a\n// duplicate React copy nested under some package BEFORE the alias applies,\n// which surfaces as "Invalid hook call ... more than one copy of React". So\n// the React singleton is NOT enforced via alias here; it's enforced via the\n// resolveRequest hook below, which takes precedence over ALL resolution.\nconfig.resolver.disableHierarchicalLookup = false;\nconfig.resolver.extraNodeModules = {\n ...(config.resolver.extraNodeModules ?? {}),\n ...singletonModules,\n};\nconfig.resolver.alias = {\n ...(config.resolver.alias ?? {}),\n ...singletonModules,\n};\n\n// React-family packages that MUST resolve to exactly one copy (the sidecar's),\n// no matter which module imports them or how deeply nested it is. react +\n// react-dom are the renderer/runtime pair whose duplication causes "Invalid\n// hook call" — forcing them through resolveRequest (which runs before\n// hierarchical resolution) is the only reliable singleton guarantee once\n// hierarchical lookup is on. NativeWind also keys its interop registry by\n// component identity: its react-native imports and Babel's direct\n// react-native-web subpath imports must resolve to the SAME web components.\nconst forcedReactSingletons = {\n react: path.join(sidecarNodeModules, "react"),\n "react-dom": path.join(sidecarNodeModules, "react-dom"),\n "react-native-web": path.join(sidecarNodeModules, "react-native-web"),\n};\nconst tempoSdkRuntimeModules = {\n "tempo-sdk/canvas": path.join(sidecarNodeModules, "tempo-sdk", "dist", "canvas", "index.js"),\n "tempo-sdk/canvas/astro": path.join(sidecarNodeModules, "tempo-sdk", "dist", "canvas", "astro.js"),\n "tempo-sdk/canvas/astro-contract": path.join(sidecarNodeModules, "tempo-sdk", "dist", "canvas", "astro-contract.js"),\n "tempo-sdk/astro/asset-preview-client": path.join(sidecarNodeModules, "tempo-sdk", "dist", "astro", "asset-preview-client.js"),\n "tempo-sdk/astro/controls": path.join(sidecarNodeModules, "tempo-sdk", "dist", "astro", "controls.js"),\n "tempo-sdk/assets": path.join(sidecarNodeModules, "tempo-sdk", "dist", "assets", "index.js"),\n};\n\n// Mirror the user app's tsconfig.paths so canvas imports like\n// "@/app/components/X" resolve through Metro the same way TypeScript and\n// the user's app already resolve them. The aliases array below is baked\n// in at scaffold time (regenerated on every ensureInitialized pass when\n// the user's tsconfig changes).\nconst tempoTsconfigAliases = ${n}.map((a) => ({\n prefix: a.prefix,\n target: path.resolve(projectRoot, a.target),\n}));\n\n// Web shims for native-only modules: { "react-native-maps": "../web-shims/..." }.\n// Native-only RN modules (react-native-maps, expo-camera, …) cannot bundle on\n// web — Metro throws "Importing native-only module … on web" and the whole\n// bundle fails. The app keeps browser stand-ins in a web-shims/ dir; we\n// replicate the mapping so any canvas transitively importing one still bundles.\nconst tempoWebShims = ${r};\n\n// Always install the resolveRequest hook (even with no tsconfig aliases) so\n// the React singleton enforcement runs on every project. Order:\n// 1. React singletons (highest priority — must win over everything).\n// 2. Tempo SDK runtime subpaths that package-exports-disabled Metro cannot\n// resolve through package.json exports.\n// 3. Web shims (web platform only) for native-only modules.\n// 4. User @/ tsconfig aliases (canvas imports of app source).\n// 5. Expo's default resolver (including native-platform react-native).\nconst baseResolveRequest = userMetroResolveRequest || config.resolver.resolveRequest;\nconfig.resolver.resolveRequest = (context, moduleName, platform) => {\n if (isStorybookModule(moduleName)) {\n return { type: "sourceFile", filePath: tempoStorybookStub };\n }\n if (platform === "web" && moduleName === "react-native") {\n return context.resolveRequest(context, forcedReactSingletons["react-native-web"], platform);\n }\n for (const pkg of Object.keys(forcedReactSingletons)) {\n const pkgRoot = forcedReactSingletons[pkg];\n if (moduleName === pkg) {\n return context.resolveRequest(context, pkgRoot, platform);\n }\n if (moduleName.startsWith(pkg + "/")) {\n const subpath = moduleName.slice(pkg.length + 1);\n return context.resolveRequest(\n context,\n path.join(pkgRoot, subpath),\n platform,\n );\n }\n }\n const tempoSdkRuntimeModule = tempoSdkRuntimeModules[moduleName];\n if (tempoSdkRuntimeModule) {\n return context.resolveRequest(context, tempoSdkRuntimeModule, platform);\n }\n if (platform === "web") {\n const shimRel = tempoWebShims[moduleName];\n if (shimRel) {\n return {\n type: "sourceFile",\n filePath: path.resolve(projectRoot, shimRel),\n };\n }\n }\n for (const { prefix, target } of tempoTsconfigAliases) {\n if (moduleName.startsWith(prefix)) {\n const rewritten = path.join(target, moduleName.slice(prefix.length));\n return context.resolveRequest(context, rewritten, platform);\n }\n }\n if (baseResolveRequest) {\n return baseResolveRequest(context, moduleName, platform);\n }\n return context.resolveRequest(context, moduleName, platform);\n};\n\n// The component pool probes every host for Vite's explicit registration\n// barrier before loading a runtime document. Metro cannot provide Vite's\n// transform receipt, but it must complete the cross-origin handshake so the\n// client can identify it as an unsupported host and use its runtime-ACK\n// fallback. Without these CORS responses the browser reports "Failed to\n// fetch", which is indistinguishable from a dead host and blocks projection.\n// Matches CANVAS_HOST_REGISTRATION_ENDPOINT in tempo-sdk's registration\n// contract (a generated config cannot import it).\nconst tempoRegistrationEndpoint = "/__tempo/canvas-host-registration";\n// The SDK also opens \`new EventSource("/__tempo/errors")\` in every host\n// document. Only the Vite plugin serves that stream; on Metro the request falls\n// through to Expo's history fallback, which answers the index HTML, and the\n// browser logs \`EventSource's response has a MIME type ("text/html") that is\n// not "text/event-stream"\` on every Expo canvas load. A 204 fails the\n// connection per the SSE spec with no console error and without holding a\n// socket open (a real stream would, and that can block Metro's shutdown).\n// Metro has no server-error stream to proxy here.\nconst tempoErrorsEndpoint = "/__tempo/errors";\nconst baseEnhanceMiddleware = config.server?.enhanceMiddleware;\nconfig.server = {\n ...(config.server ?? {}),\n enhanceMiddleware: (middleware, server) => {\n const baseMiddleware = baseEnhanceMiddleware\n ? baseEnhanceMiddleware(middleware, server)\n : middleware;\n return (req, res, next) => {\n const requestPath = req.url?.split("?")[0];\n if (requestPath === "/__tempo/identity" && req.method === "GET") {\n // Match the SDK copy forced by tempoSdkRuntimeModules, including links.\n let sdk = {};\n try {\n const sdkManifestPath = path.join(sidecarNodeModules, "tempo-sdk", "package.json");\n sdk = JSON.parse(fs.readFileSync(sdkManifestPath, "utf8")) ?? {};\n } catch {}\n let workspaceNonce = process.env.TEMPO_WORKSPACE_NONCE?.trim() ?? "";\n if (!workspaceNonce) {\n try {\n const noncePath = path.join(projectRoot, ".tempo", "workspace-nonce");\n workspaceNonce = fs.readFileSync(noncePath, "utf8").trim();\n } catch {}\n }\n res.statusCode = 200;\n res.setHeader("Cache-Control", "no-store");\n res.setHeader("Content-Type", "application/json; charset=utf-8");\n res.setHeader("x-tempo-host-identity", "1");\n res.setHeader("Access-Control-Allow-Origin", "*");\n res.end(JSON.stringify({\n tempoHost: true,\n contractVersion: 1,\n workspaceNonce,\n sdkVersion: sdk.version,\n sdkChannel: "latest",\n tempoRuntimeContract: sdk.tempoRuntimeContract,\n pluginActive: Boolean(process.env.TEMPO),\n framework: "expo",\n }));\n return;\n }\n\n // Method-gated exactly like the Vite plugin's handlers: anything else\n // (a POST to the errors path, a GET to the registration path) falls\n // through to Metro instead of being swallowed with an empty 204.\n const handled =\n (requestPath === tempoRegistrationEndpoint &&\n (req.method === "POST" || req.method === "OPTIONS")) ||\n (requestPath === tempoErrorsEndpoint &&\n (req.method === "GET" || req.method === "OPTIONS"));\n if (!handled) {\n return baseMiddleware(req, res, next);\n }\n res.setHeader("Access-Control-Allow-Origin", "*");\n if (req.method === "OPTIONS") {\n res.setHeader(\n "Access-Control-Allow-Methods",\n requestPath === tempoErrorsEndpoint\n ? "GET, OPTIONS"\n : "POST, OPTIONS",\n );\n res.setHeader("Access-Control-Allow-Headers", "content-type");\n }\n res.statusCode = 204;\n res.end();\n };\n },\n};\n\n// Metro's transform cache key does not include process.env.TEMPO, but the\n// Tempo Babel plugin only annotates when TEMPO=true. Without this, a cache\n// built while TEMPO was unset is reused (un-annotated) even after restarting\n// with TEMPO=true. Key the cache on TEMPO so on/off use separate namespaces.\n//\n// The "metrocfg-v2" token is a manual version stamp for THIS config template.\n// Bump it whenever the resolver config changes shape (alias set, hierarchical\n// lookup, resolveRequest behavior). Metro's on-disk transform + serializer\n// cache persists across restarts and is NOT keyed on metro.config.js content,\n// so without a stamp bump a resolver change reshuffles module IDs while stale\n// cached chunks still reference the old IDs — surfacing as "Requiring unknown\n// module <n>". Bumping the stamp forces a clean rebuild.\n// The Babel annotations also embed absolute source paths and the sidecar root.\n// Metro otherwise keys transforms by relative path, allowing identical files\n// in different projects/worktrees to reuse another project's source identity.\nconfig.cacheVersion = [\n config.cacheVersion,\n "tempo-metrocfg-v15",\n projectRoot,\n \`tempo-\${process.env.TEMPO === "true" ? "on" : "off"}\`,\n]\n .filter(Boolean)\n .join("~");\n\n${o}\n`}function isTempoOwnedExpoMetroConfig(e){return!!e.startsWith(ek)||e.includes('require("expo/metro-config")')&&e.includes("singletonModules")&&e.includes("sidecarNodeModules")&&e.includes("disableHierarchicalLookup = true")}async function detectExpoStyleTooling(e){const t=await readRootPackageDeps(e);return{nativewind:Boolean(t.nativewind),svgTransformer:Boolean(t["react-native-svg-transformer"])}}async function shouldImportExpoMetroRuntime(e){const[t,n]=await Promise.all([readRootPackageDeps(e.projectRoot),readRootPackageDeps(e.tempoRoot)]);if(t["@expo/metro-runtime"]||n["@expo/metro-runtime"])return!0;for(const t of[e.tempoRoot,e.projectRoot]){const e=ab(lb.join(t,"__tempo_expo_runtime_resolve__.cjs"));try{return e.resolve("@expo/metro-runtime"),!0}catch{}}return!1}async function collectExpoWebShims(e){const t=lb.join(e.projectRoot,"web-shims");let n;try{n=await tb(t,{withFileTypes:!0})}catch{return[]}const r=[];for(const s of n){if(!s.isFile())continue;const n=/^(.+)\.(js|jsx|ts|tsx|cjs|mjs)$/.exec(s.name);if(!n)continue;const i=n[1];r.push({module:i,targetRelToTempo:`${toPosixRelativePath(e.tempoRoot,lb.join(t,s.name))}`})}return r}var tk="@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",nk="// @tempo-owned: expo-tailwind-config";function buildExpoNativeWindTailwindConfig(e){const t=`./${toPosixRelativePath(e.tempoRoot,e.pagesDir)}/**/*.{js,jsx,ts,tsx}`;return`${nk}\nconst path = require("node:path");\nconst nativewindPreset = require("nativewind/preset");\n\nlet appConfig = {};\nfor (const name of ["tailwind.config.js", "tailwind.config.cjs"]) {\n try {\n appConfig = require(path.resolve(__dirname, "..", name));\n break;\n } catch (e) {\n if (!e || e.code !== "MODULE_NOT_FOUND") throw e;\n }\n}\n\nconst appContent = Array.isArray(appConfig.content) ? appConfig.content : [];\nconst rebasedAppContent = appContent\n .filter((g) => typeof g === "string")\n .map((g) => (g.startsWith("./") ? "../" + g.slice(2) : g));\n\nmodule.exports = {\n ...appConfig,\n presets: [nativewindPreset],\n content: Array.from(\n new Set([\n ...rebasedAppContent,\n "../app/**/*.{js,jsx,ts,tsx}",\n "../components/**/*.{js,jsx,ts,tsx}",\n "../src/**/*.{js,jsx,ts,tsx}",\n ${JSON.stringify(t)},\n "./App.tsx",\n ]),\n ),\n};\n`}function isTempoOwnedExpoTailwindConfig(e){return!!e.startsWith(nk)||e.includes('require("nativewind/preset")')&&e.includes("rebasedAppContent")}function isOverwriteableExpoAppTsx(e){if(/from\s+["']react-dom(?:\/[^"']*)?["']/.test(e))return!0;const t=/from\s+["']react-native["']/.test(e),n=/<(div|span|p|button|a|h1|h2|h3|input|form|section|article|ul|li)\b/.test(e);return!(!n||t)}var rk='import { tempoHostIdentity } from "tempo-sdk/nextjs";\n\nexport const dynamic = "force-dynamic";\n\nexport function GET() {\n return Response.json(tempoHostIdentity(), {\n headers: {\n "cache-control": "no-store",\n "x-tempo-host-identity": "1",\n },\n });\n}\n',sk='export const dynamic = "force-dynamic";\n\nconst headers = {\n "access-control-allow-origin": "*",\n "access-control-allow-methods": "POST, OPTIONS",\n "access-control-allow-headers": "content-type",\n "cache-control": "no-store",\n};\n\nexport function OPTIONS() {\n return new Response(null, { status: 204, headers });\n}\n\nexport function POST() {\n return new Response(null, { status: 204, headers });\n}\n',ik='import { realpathSync } from "node:fs";\n\nexport const dynamic = "force-dynamic";\n\nexport function GET() {\n let projectRoot: string;\n try {\n projectRoot = realpathSync.native(process.cwd());\n } catch {\n projectRoot = process.cwd();\n }\n return Response.json({ tempoHost: true, projectRoot });\n}\n',ok='// @tempo-owned: stylesheet-postcss-v1\nimport path from "node:path";\n// Next runs PostCSS workers with the host project as their cwd. Turbopack\n// relocates this module, so import.meta.url is not the on-disk host path.\nconst tempoStylesRoot = process.cwd();\nexport default {\n plugins: {\n [path.join(tempoStylesRoot, ".tempo-styles/host-styles.cjs")]: { base: tempoStylesRoot },\n "@tailwindcss/postcss": {},\n },\n};\n',ak='// @tempo-owned: stylesheet-postcss-v1\nimport path from "node:path";\n// Next runs PostCSS workers with the host project as their cwd. Turbopack\n// relocates this module, so import.meta.url is not the on-disk host path.\nconst tempoStylesRoot = process.cwd();\nexport default {\n plugins: {\n "postcss-import": {},\n "postcss-url": { url: "rebase" },\n [path.join(tempoStylesRoot, ".tempo-styles/host-styles.cjs")]: { base: tempoStylesRoot },\n tailwindcss: {},\n autoprefixer: {},\n },\n};\n';async function writeStylesheetFile(e,t){await readTextFileOptional3(e)!==t&&await atomicWriteText(e,t)}async function writeFileIfMissing(e,t){null===await readTextFileOptional3(e)&&await atomicWriteText(e,t)}var ck=["tailwind.config.ts","tailwind.config.js","tailwind.config.mjs","tailwind.config.cjs","src/tailwind.config.ts","src/tailwind.config.js","app/tailwind.config.ts","app/tailwind.config.js","client/tailwind.config.ts","client/tailwind.config.js"],lk=["src","app","components","pages","lib","packages","shared","ui","client/src","client/app","client/components","client/lib"],dk=["src/index.css","src/style.css","src/main.css","src/App.css","src/styles/globals.css","src/styles/global.css","src/styles/tailwind.css","styles/global.css","styles/globals.css","app/globals.css","app/global.css","app/assets/tailwind.css","client/src/index.css","src/app/globals.css","src/app/global.css"];async function pathIsFile(e){try{return(await sb(e)).isFile()}catch{return!1}}function isInsidePath(e,t){const n=lb.relative(e,t);return""===n||!n.startsWith("..")&&!lb.isAbsolute(n)}function cleanLocalSpecifier(e){const t=e.trim();return 0===t.length||/^[a-z]+:\/\//i.test(t)||t.startsWith("data:")?null:t.split(/[?#]/,1)[0]??null}function resolveDeclaredProjectPath(e,t){const n=cleanLocalSpecifier(t);return n?n.startsWith("/")?lb.resolve(e,n.slice(1)):n.startsWith("./")||n.startsWith("../")?lb.resolve(e,n):n.startsWith("@/")?lb.resolve(e,"src",n.slice(2)):n.startsWith("~/")?lb.resolve(e,n.slice(2)):/^(?:src|app|styles|components|packages|lib|pages)\//.test(n)?lb.resolve(e,n):null:null}function resolveImportCandidates(e,t,n){const r=cleanLocalSpecifier(n);if(!r)return[];if(r.startsWith("./")||r.startsWith("../"))return[lb.resolve(lb.dirname(t),r)];if(r.startsWith("/"))return[lb.resolve(e,r.slice(1))];if(r.startsWith("@/")){const t=lb.resolve(e,r.slice(2)),n=lb.resolve(e,"src",r.slice(2));return[n,t]}return r.startsWith("~/")?[lb.resolve(e,r.slice(2))]:[]}function extractCssImportSpecifiers(e){const t=[],n=/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:[?#][^"']*)?)["']/g;for(const r of e.matchAll(n)){const e=r[1];e&&!e.includes(".module.css")&&t.push(e)}return t}function extractHtmlStylesheetHrefs(e){const t=[],n=/<link\b(?=[^>]*\brel=["']?stylesheet["']?)[^>]*\bhref=["']([^"']+\.css(?:[?#][^"']*)?)["'][^>]*>/gi;for(const r of e.matchAll(n))r[1]&&t.push(r[1]);return t}function toUniqueArray(e){return Array.from(new Set(e))}function getNestedString(e,t){let n=e;for(const e of t){if(!n||"object"!=typeof n||Array.isArray(n))return null;n=n[e]}return"string"==typeof n&&n.trim().length>0?n:null}function readPackageDependencyVersions(e){const t={...toStringRecord(e?.dependencies),...toStringRecord(e?.devDependencies),...toStringRecord(e?.peerDependencies)};return{autoprefixer:t.autoprefixer??null,postcss:t.postcss??null,tailwindcss:t.tailwindcss??null,tailwindcssPostcss:t["@tailwindcss/postcss"]??null,tailwindcssVite:t["@tailwindcss/vite"]??null}}function firstCompatibleVersion(e,t){for(const n of e)if(n&&parsePackageMajorVersion(n)===t)return n;return null}function mergePackageDependencyVersions(e,t){return{autoprefixer:e.autoprefixer??t.autoprefixer,postcss:e.postcss??t.postcss,tailwindcss:e.tailwindcss??t.tailwindcss,tailwindcssPostcss:e.tailwindcssPostcss??t.tailwindcssPostcss,tailwindcssVite:e.tailwindcssVite??t.tailwindcssVite}}function parsePackageMajorVersion(e){const t=e.match(/npm:[^@]+@(.+)$/),n=t?.[1]??e,r=n.match(/\d+/);return r?.[0]?Number.parseInt(r[0],10):null}var uk=vb;function applyManagedTempoSdkSpec(e,t,n){const r=toStringRecord(n.dependencies),s=toStringRecord(n.devDependencies);void 0!==r["tempo-sdk"]?(e["tempo-sdk"]=r["tempo-sdk"],delete t["tempo-sdk"]):t["tempo-sdk"]=s["tempo-sdk"]??uk}function cssUsesTailwindV3Directives(e){return/@tailwind\s+(?:base|components|utilities)\b/.test(e)}function cssUsesTailwindV4Directives(e){return/@import\s+["']tailwindcss(?:\/[^"']*)?["']/.test(e)||/@(?:theme|source|utility|variant|custom-variant)\b/.test(e)}function inferTailwindMajorVersion(e){const t=e.projectPackageVersions.tailwindcss?parsePackageMajorVersion(e.projectPackageVersions.tailwindcss):null;if(3===t)return 3;if(null!==t&&t>=4)return 4;const n=null!==firstCompatibleVersion([e.projectPackageVersions.tailwindcssVite,e.projectPackageVersions.tailwindcssPostcss],4);if(n)return 4;const r=e.tempoPackageVersions.tailwindcss?parsePackageMajorVersion(e.tempoPackageVersions.tailwindcss):null;return 3===r?3:null!==r&&r>=4?4:e.cssSources.some(cssUsesTailwindV3Directives)?3:(e.cssSources.some(cssUsesTailwindV4Directives),4)}async function addExistingUserFile(e,t,n){if(!n)return;const r=lb.resolve(n);isInsidePath(t.projectRoot,r)&&(isInsidePath(t.tempoRoot,r)||await pathIsFile(r)&&e.add(r))}async function addExistingUserDirectory(e,t,n){const r=lb.resolve(n);isInsidePath(t.projectRoot,r)&&(isInsidePath(t.tempoRoot,r)||await pathIsDirectory(r)&&e.add(r))}async function addCssImportsFromSourceFile(e,t,n){const r=await readTextFileOptional3(n);if(null===r)return null;for(const s of extractCssImportSpecifiers(r))for(const r of resolveImportCandidates(t.projectRoot,n,s))await addExistingUserFile(e,t,r);return r}async function addCssLinksFromHtmlFile(e,t,n){const r=await readTextFileOptional3(n);if(null!==r)for(const n of extractHtmlStylesheetHrefs(r))await addExistingUserFile(e,t,resolveDeclaredProjectPath(t.projectRoot,n))}async function collectNextLayoutFiles(e){const t=["app/layout.tsx","app/layout.jsx","app/layout.ts","app/layout.js","src/app/layout.tsx","src/app/layout.jsx","src/app/layout.ts","src/app/layout.js"].map(t=>lb.join(e,t)),n=new Set;for(const e of t)await pathIsFile(e)&&n.add(e);for(const t of[lb.join(e,"app"),lb.join(e,"src","app")])await collectNamedFiles(t,/^layout\.(?:tsx|jsx|ts|js)$/,3,n);return Array.from(n)}async function collectNamedFiles(e,t,n,r){if(n<0||!await pathIsDirectory(e))return;let s;try{s=await tb(e,{withFileTypes:!0})}catch{return}for(const i of s){const s=lb.join(e,i.name);i.isFile()&&t.test(i.name)?r.add(s):i.isDirectory()&&!i.name.startsWith(".")&&"node_modules"!==i.name&&".next"!==i.name&&await collectNamedFiles(s,t,n-1,r)}}async function discoverProjectStyleContext(e,t){const n=new Set,r=new Set,s=readPackageDependencyVersions(await readJsonObjectOptional(lb.join(e.projectRoot,"package.json")));if((await readRootPackageDeps(e.projectRoot)).astro){const t=new Set;await collectNamedFiles(lb.join(e.projectRoot,"src","layouts"),/\.astro$/,5,t),await collectNamedFiles(lb.join(e.projectRoot,"src","pages"),/\.astro$/,5,t);for(const r of t)await addCssImportsFromSourceFile(n,e,r)}const i=readPackageDependencyVersions(await readJsonObjectOptional(e.packageJsonPath)),o=await readJsonObjectOptional(lb.join(e.projectRoot,"components.json")),a=getNestedString(o,["tailwind","css"]),c=getNestedString(o,["tailwind","config"]);if(await addExistingUserFile(n,e,a?resolveDeclaredProjectPath(e.projectRoot,a):null),c){const t=resolveDeclaredProjectPath(e.projectRoot,c);t&&r.add(t)}if("nextjs"===t){for(const t of await collectNextLayoutFiles(e.projectRoot))await addCssImportsFromSourceFile(n,e,t);for(const t of["pages/_app.tsx","pages/_app.jsx","pages/_app.ts","pages/_app.js","src/pages/_app.tsx","src/pages/_app.jsx","src/pages/_app.ts","src/pages/_app.js"])await addCssImportsFromSourceFile(n,e,lb.join(e.projectRoot,t))}else if("nuxt"===t)for(const t of await collectNuxtCssEntries(e.projectRoot))await addExistingUserFile(n,e,t);else{for(const t of["src/main.tsx","src/main.jsx","src/main.ts","src/main.js","src/index.tsx","src/index.jsx","src/index.ts","src/index.js","main.tsx","main.jsx","client/src/main.tsx","client/src/main.jsx","client/src/main.ts","client/src/main.js","client/src/index.tsx","client/src/index.jsx"])await addCssImportsFromSourceFile(n,e,lb.join(e.projectRoot,t));await addCssLinksFromHtmlFile(n,e,lb.join(e.projectRoot,"index.html")),await addCssLinksFromHtmlFile(n,e,lb.join(e.projectRoot,"client","index.html"))}for(const t of dk)await addExistingUserFile(n,e,lb.join(e.projectRoot,t));for(const t of ck)r.add(lb.join(e.projectRoot,t));const l=new Set;for(const t of lk)await addExistingUserDirectory(l,e,lb.join(e.projectRoot,t));l.add(e.pagesDir);const d="nextjs"===t?await discoverNextFontSetup(e,await collectNextLayoutFiles(e.projectRoot)):null;let u=null;for(const e of r)if(await pathIsFile(e)){u=e;break}const p=(await Promise.all(Array.from(n).map(async e=>await readTextFileOptional3(e)))).filter(e=>null!==e),m=inferTailwindMajorVersion({cssSources:p,projectPackageVersions:s,tempoPackageVersions:i});return{cssFiles:toUniqueArray(n),cssFilesHaveTailwindDirectives:p.some(e=>3===m?cssUsesTailwindV3Directives(e):cssUsesTailwindV4Directives(e)),packageVersions:mergePackageDependencyVersions(s,i),tailwindConfigPath:u,tailwindMajor:m,sourceDirs:toUniqueArray(l),nextFontSetup:d}}async function discoverNextFontSetup(e,t){for(const n of t){const t=await readTextFileOptional3(n);if(null===t)continue;const r=extractNextFontSetup(t,n,lb.join(e.tempoRoot,"app","layout.tsx"));if(r)return r}return null}function extractNextFontSetup(e,t,n){const r=extractJsxAttributeExpression(e,"html","className"),s=extractJsxAttributeExpression(e,"body","className"),i=[r,s].filter(e=>Boolean(e)),o=new Set;for(const e of i){if(/\b(?:cn|clsx|classNames)\s*\(/.test(e))continue;const t=/\b([A-Za-z_$][\w$]*)\.(?:className|variable)\b/g;for(const n of e.matchAll(t))n[1]&&o.add(n[1])}if(0===o.size)return null;const a=extractNextFontImports(e);if(0===a.length)return null;const c=[];for(const r of o){const s=extractConstDeclaration(e,r);if(!s)return null;c.push(rewriteLocalFontPaths(s,lb.dirname(t),lb.dirname(n)))}return{imports:a,declarations:c,htmlClassName:r,bodyClassName:s}}function extractNextFontImports(e){const t=new Set,n=/^import\s+[\s\S]*?\s+from\s+["']next\/font\/(?:google|local)["'];?/gm;for(const r of e.matchAll(n))t.add(ensureTrailingSemicolon(r[0].trim()));return Array.from(t)}function ensureTrailingSemicolon(e){return e.endsWith(";")?e:`${e};`}function extractConstDeclaration(e,t){const n=new RegExp(`\\bconst\\s+${escapeRegExp2(t)}\\s*=`).exec(e);if(!n||void 0===n.index)return null;const r=n.index,s=findStatementEnd(e,r);return-1===s?null:ensureTrailingSemicolon(e.slice(r,s+1).trim())}function findStatementEnd(e,t){let n=null,r=!1,s=0,i=0,o=0;for(let a=t;a<e.length;a+=1){const t=e[a];if(n)r?r=!1:"\\"===t?r=!0:t===n&&(n=null);else if("'"!==t&&'"'!==t&&"`"!==t){if("{"===t)s+=1;else if("}"===t)s=Math.max(0,s-1);else if("("===t)i+=1;else if(")"===t)i=Math.max(0,i-1);else if("["===t)o+=1;else if("]"===t)o=Math.max(0,o-1);else if(";"===t&&0===s&&0===i&&0===o)return a}else n=t}return-1}function rewriteLocalFontPaths(e,t,n){return e.replace(/(\b(?:src|path)\s*:\s*)(["'])(\.{1,2}\/[^"']+)\2/g,(e,r,s,i)=>{const o=lb.resolve(t,i);return`${r}${s}${toCssRelativePath(n,o)}${s}`})}function extractJsxAttributeExpression(e,t,n){const r=e.indexOf(`<${t}`);if(-1===r)return null;const s=findJsxTagEnd(e,r);if(-1===s)return null;const i=e.slice(r,s+1),o=i.indexOf(n);if(-1===o)return null;const a=i.indexOf("=",o+n.length);if(-1===a)return null;let c=a+1;for(;/\s/.test(i[c]??"");)c+=1;if("{"===i[c]){const e=findBalancedBraceEnd(i,c);return-1===e?null:i.slice(c+1,e).trim()}if('"'===i[c]||"'"===i[c]){const e=i[c],t=i.indexOf(e,c+1);return-1===t?null:JSON.stringify(i.slice(c+1,t))}return null}function findJsxTagEnd(e,t){let n=null,r=!1,s=0;for(let i=t;i<e.length;i+=1){const t=e[i];if(n)r?r=!1:"\\"===t?r=!0:t===n&&(n=null);else if("'"!==t&&'"'!==t&&"`"!==t){if("{"===t)s+=1;else if("}"===t)s=Math.max(0,s-1);else if(">"===t&&0===s)return i}else n=t}return-1}function findBalancedBraceEnd(e,t){let n=null,r=!1,s=0;for(let i=t;i<e.length;i+=1){const t=e[i];if(n)r?r=!1:"\\"===t?r=!0:t===n&&(n=null);else if("'"!==t&&'"'!==t&&"`"!==t){if("{"===t)s+=1;else if("}"===t&&(s-=1,0===s))return i}else n=t}return-1}function escapeRegExp2(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var pk="/* Legacy Tempo CSS entry - superseded by ./globals.css (imported from main.tsx). */\n",hk="/* tempo:managed:start - regenerated by Tempo; edits in this block are overwritten */",mk="/* tempo:managed:end */",fk="/* tempo:managed:start",gk="/* tempo:managed:end */";function isTailwindEngineDirectiveLine(e){const t=e.trim();return/^@import\s+["']tailwindcss["']/.test(t)||/^@tailwind\s+(?:base|components|utilities)\b/.test(t)||/^@source\b/.test(t)||/^@config\b/.test(t)}function extractUserCssOutsideTempoBlock(e,t){const n=e.indexOf(fk),r=e.indexOf(gk);if(-1!==n&&r>n){const t=e.slice(0,n),s=e.slice(r+gk.length);return`${t}\n${s}`.trim()}try{const n=Ix.parse(e),r=new Set;Ix.parse(t).walkAtRules("import",e=>{const t=e.params.match(/^["']([^"']+)["']$/);t&&r.add(t[1])});for(const e of[...n.nodes]){if("atrule"!==e.type)continue;const t="import"===e.name?e.params.match(/^["']([^"']+)["']$/):null;(t&&r.has(t[1])||isTailwindEngineDirectiveLine(e.toString()))&&e.remove()}return n.toString().trim()}catch{return e.trim()}}async function writeManagedTempoGlobalsCss(e,t,n=""){const r=await readTextFileOptional3(e),s=null===r?"":extractUserCssOutsideTempoBlock(r,`${t}\n${n}`),i=`${hk}\n${t.trim()}\n${mk}\n`,o=s.length>0?`${i}\n${s}\n`:i;o!==r&&await atomicWriteText(e,o)}async function reconcileLegacyTempoIndexCss(e){const t=lb.join(e,"index.css"),n=await readTextFileOptional3(t);if(null===n)return;const r=extractUserCssOutsideTempoBlock(n,""),s=r.length>0?`${r}\n`:pk;s!==n&&await atomicWriteText(t,s)}async function ensureNextLayoutFile(e,t,n){const r=lb.join(e.tempoRoot,"app","layout.tsx"),s=reconcileHostStyleImports(buildNextLayoutTsx(t.nextFontSetup),r,e.tempoRoot,n),i=await readTextFileOptional3(r);null===i||isTempoGeneratedNextLayout(i)?await writeStylesheetFile(r,s):await writeStylesheetFile(r,reconcileHostStyleImports(i,r,e.tempoRoot,n))}function reconcileHostStyleImports(e,t,n,r){const s=cssPath(lb.dirname(t),lb.resolve(n,r.globals)),i=[...r.roots.map(e=>cssPath(lb.dirname(t),lb.resolve(n,e.file))),s];return reconcileStylesheetImports(e,i)}async function ensureStylesheetFiles(e,t,n,r){const s=lb.join(e.tempoRoot,"nextjs"===t?"app/globals.css":"globals.css"),i=lb.join(e.tempoRoot,".tempo-styles/styles-plan.json"),o=await readJsonObjectOptional(i),a=new Set;for(const t of Array.isArray(o?.legacyRoots)?o.legacyRoots:[]){if("string"!=typeof t)continue;const r=lb.resolve(e.tempoRoot,t);t.endsWith(".css")&&isInsidePath(e.projectRoot,r)&&!isInsidePath(e.tempoRoot,r)&&await pathIsFile(r)&&(a.add(r),n.cssFiles.includes(r)||n.cssFiles.push(r))}const c=await readTextFileOptional3(s);if(c){const t=c.indexOf(fk),r=c.indexOf(gk),i=t>=0&&r>t?c.slice(t,r):t<0?c:"";let o;try{o=Ix.parse(i)}catch{}for(const t of o?.nodes??[]){if("atrule"!==t.type||"import"!==t.name)continue;const r=t.params.match(/^["'](\.{1,2}\/[^"']+\.css)["']$/);if(!r)continue;const i=lb.resolve(lb.dirname(s),r[1]);isInsidePath(e.projectRoot,i)&&!isInsidePath(e.tempoRoot,i)&&await pathIsFile(i)&&!n.cssFiles.includes(i)&&(n.cssFiles.push(i),a.add(i))}}const l=await buildStylesheetPlan({tempoRoot:e.tempoRoot,appRoot:r,globals:s,major:n.tailwindMajor,cssFiles:n.cssFiles,config:n.tailwindConfigPath,sourceDirs:n.sourceDirs});if(l.legacyRoots=[...a].map(t=>cssPath(e.tempoRoot,t)),await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/host-styles.cjs"),gT),await writeStylesheetFile(i,`${JSON.stringify(l,null,2)}\n`),3===l.major){const t=lb.join(e.tempoRoot,".tempo-styles/tailwind.editor.css");(await readTextFileOptional3(t))?.startsWith("/* @tempo-owned: Tailwind editor context;")&&await ib(t);const n=(await Promise.all(Tk.map(async t=>await pathExists4(lb.join(e.tempoRoot,t))?t:null))).find(Boolean)??"tailwind.config.ts";await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/tailwind-full.cjs"),`// @tempo-owned: full stylesheet config\nconst path = require("node:path");\nconst host = path.resolve(__dirname, "..");\n// Keep this relative require literal: Tailwind's dependency scanner follows\n// it into the host config, app config and plugins for cache invalidation.\nconst imported = require(${JSON.stringify(`../${n}`)});\nconst config = imported.default ?? imported;\nconst content = config.content ?? [];\nconst files = (Array.isArray(content) ? content : content.files ?? []).map((entry) => {\n if (typeof entry !== "string") return entry;\n const negative = entry.startsWith("!");\n return (negative ? "!" : "") + path.resolve(host, negative ? entry.slice(1) : entry).split(path.sep).join("/");\n});\nmodule.exports = { ...config, content: Array.isArray(content) ? files : { ...content, files } };\n`),await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/tailwind-partial.cjs"),'// @tempo-owned: partial stylesheet config\nconst config = require("./tailwind-full.cjs");\nmodule.exports = { ...config, corePlugins: Array.isArray(config.corePlugins) ? config.corePlugins.filter((name) => name !== "preflight") : { ...config.corePlugins, preflight: false } };\n')}else{const t=["/* @tempo-owned: Tailwind editor context; not a runtime stylesheet */",'@import "tailwindcss";',...l.roots.map(t=>`@reference ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),lb.resolve(e.tempoRoot,t.file)))};`),`@reference ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),s))};`,...l.config&&!l.roots.some(e=>e.config)?[`@config ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),lb.resolve(e.tempoRoot,l.config)))};`]:[],...l.sources.map(t=>`@source ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),lb.resolve(e.tempoRoot,t)))};`)];await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/tailwind.editor.css"),`${t.join("\n")}\n`)}return l}function isTempoGeneratedNextLayout(e){return/export\s+default\s+function\s+RootLayout/.test(e)&&/children\s*:\s*ReactNode/.test(e)&&/<head\s*\/>/.test(e)}function buildNextLayoutTsx(e){const t=toUniqueArray(['import "./globals.css";','import type { ReactNode } from "react";',...e?.imports??[]]),n=e?.declarations.length?`${e.declarations.join("\n\n")}\n\n`:"",r=e?.htmlClassName?` className={${e.htmlClassName}}`:"",s=e?.bodyClassName?` className={${e.bodyClassName}}`:"";return`${t.join("\n")}\n\n${n}export default function RootLayout({ children }: { children: ReactNode }) {\n return (\n <html lang="en"${r}>\n <head />\n <body${s}>{children}</body>\n </html>\n );\n}\n`}function buildTempoGlobalsCss(e,t,n){if(n&&n.owner!==n.globals)return"/* Application styles are loaded at their original paths by the host entry. */\n";if(3===t.tailwindMajor){const r=[];for(const s of n?[]:t.cssFiles)r.push(`@import "${toCssRelativePath(e,s)}";`);return r.length>0&&r.push(""),!n&&t.cssFilesHaveTailwindDirectives||(r.push("@tailwind base;"),r.push("@tailwind components;"),r.push("@tailwind utilities;")),`${r.join("\n")}\n`}const r=['@import "tailwindcss";'];for(const s of n?[]:t.cssFiles)r.push(`@import "${toCssRelativePath(e,s)}";`);r.push(""),t.tailwindConfigPath&&r.push(`@config "${toCssRelativePath(e,t.tailwindConfigPath)}";`);for(const n of t.sourceDirs)r.push(`@source "${toCssRelativePath(e,n)}";`);return`${r.join("\n")}\n`}var yk=/\.(ts|js|mjs|cjs)$/;function buildTailwindV3HostConfig(e,t){const n="{ts,tsx,js,jsx,mdx,svelte,vue,astro}",r=toUniqueArray([...t.sourceDirs.map(t=>`${toCssRelativePath(e.tempoRoot,t)}/**/*.${n}`),`./app/**/*.${n}`,`./components/**/*.${n}`]),s=r.map(e=>` ${JSON.stringify(e)},`).join("\n");if(t.tailwindConfigPath){const n=toCssRelativePath(e.tempoRoot,t.tailwindConfigPath.replace(yk,"")),r=toPosixRelativePath(e.tempoRoot,lb.dirname(t.tailwindConfigPath));return`${kk}\nimport type { Config } from "tailwindcss";\nimport userConfig from "${n}";\n\n// Tempo-owned Tailwind v3 config for the canvas host. Inherits the app's theme,\n// brand tokens and plugins, then rewrites \`content\` for the host: Tailwind v3\n// resolves relative content globs against the build cwd (tempo/), so the app's\n// own globs are rebased from the app config's directory and the canvas-source\n// globs are appended.\nconst appContent = Array.isArray((userConfig as Config).content)\n ? ((userConfig as Config).content as unknown[])\n : [];\nconst rebasedAppContent = appContent\n .filter((glob): glob is string => typeof glob === "string")\n .map((glob) => {\n const negation = glob.startsWith("!") ? "!" : "";\n const body = negation ? glob.slice(1) : glob;\n if (body.startsWith("/")) return glob;\n return \`\${negation}${r}/\${body.replace(/^\\.\\//, "")}\`;\n });\n\nconst config: Config = {\n ...(userConfig as Config),\n content: [\n ...rebasedAppContent,\n${s}\n ],\n};\n\nexport default config;\n`}return`${kk}\nimport type { Config } from "tailwindcss";\n\n// Tempo-owned Tailwind v3 config for the canvas host. Content globs are\n// relative to this tempo/ directory (Tailwind v3 resolves content against the\n// build cwd, which is tempo/).\nconst config: Config = {\n content: [\n${s}\n ],\n};\n\nexport default config;\n`}async function seedHomeCanvas(e){const t=await resolveFreeformCanvasesDir(e.pagesDir);await writeFileIfMissing(lb.join(t,"home","index.canvas.tsx"),UT)}async function seedZoneDirectories(e){const t=await resolveFreeformCanvasesDir(e.pagesDir);lb.resolve(t)!==lb.resolve(e.pagesDir)&&(await eb(t,{recursive:!0}),await eb(lb.join(e.pagesDir,_g),{recursive:!0}),await eb(lb.join(e.pagesDir,xg),{recursive:!0}))}async function seedSharedControls(e){await writeFileIfMissing(lb.join(e.tempoRoot,"controls.ts"),'// Optional controls for existing components whose source should stay untouched.\n// New components always keep defineControls in their own file.\n// For existing components, honor the user/repo preference; fully integrated apps\n// prefer component files. Non-dev work can use this file; ask developers if unsure.\n// Both locations work across canvases without asset registration.\n// Import app components here, and import defineControls from "tempo-sdk/assets".\n// Example (adjust the import to your app):\n// import { defineControls } from "tempo-sdk/assets";\n// import { Button } from "../src/components/Button";\n// defineControls(Button, { disabled: { type: "boolean" } });\n// Keep one declaration per component; move existing declarations rather than copying them.\n// Tempo discovers this file automatically. Do not import it into app or canvas entry points.\nexport {};\n')}async function ensureProjectScaffold(e,t="vite"){if("expo"===t){const{aliasPaths:t}=await collectHostAliasPaths(e),n=convertAliasPathsToMetroEntries(t),r=await detectExpoStyleTooling(e.projectRoot),s=await shouldImportExpoMetroRuntime(e),i=await collectExpoWebShims(e);return await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"index.js"),buildExpoIndexJs({nativewind:r.nativewind,metroRuntime:s}),isTempoOwnedExpoIndexJs),r.nativewind&&(await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"tailwind.config.js"),buildExpoNativeWindTailwindConfig(e),isTempoOwnedExpoTailwindConfig),await writeFileIfMissing(lb.join(e.tempoRoot,"global.css"),tk)),await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"App.tsx"),QT,isOverwriteableExpoAppTsx),await writeFileIfMissing(lb.join(e.tempoRoot,"public","index.html"),buildExpoPublicIndexHtml(e)),await writeFileIfMissing(lb.join(e.tempoRoot,"app.json"),buildExpoAppJson(e)),await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"babel.config.js"),buildExpoBabelConfig({nativewind:r.nativewind}),isTempoOwnedExpoBabelConfig),await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"metro.config.js"),buildExpoMetroConfig(n,{nativewind:r.nativewind,svgTransformer:r.svgTransformer,webShims:i}),isTempoOwnedExpoMetroConfig),await reconcileGeneratedTsconfig(lb.join(e.tempoRoot,"tsconfig.json"),buildExpoTsconfigFile(e,t),isTempoOwnedExpoTsconfig),await writeFileIfMissing(lb.join(e.tempoRoot,"expo-env.d.ts"),'/// <reference types="expo/types" />\n'),void await writeFileIfMissing(lb.join(e.tempoRoot,".tempo-storybook-stub.js"),JT)}const{appRoot:n}=await resolveAppRoot(e);if("nuxt"===t)return void await ensureNuxtSidecarPages(e);const r=await discoverProjectStyleContext({...e,projectRoot:n},t),s=await ensureStylesheetFiles(e,t,r,n);if("nextjs"===t){await ensureNextLayoutFile(e,r,s),await writeFileIfMissing(lb.join(e.tempoRoot,"app","page.tsx"),jT),await writeFileIfMissing(lb.join(e.tempoRoot,"app","tempo-host","page.tsx"),BT),await writeFileIfMissing(lb.join(e.tempoRoot,"app","%5F%5Ftempo","identity","route.ts"),rk),await writeFileIfMissing(lb.join(e.tempoRoot,"app","%5F%5Ftempo","canvas-host-registration","route.ts"),sk);const t=lb.join(e.tempoRoot,"app","tempo-host","identity","route.ts");return await readTextFileOptional3(t)===ik&&await ib(t),void await writeManagedTempoGlobalsCss(lb.join(e.tempoRoot,"app","globals.css"),buildTempoGlobalsCss(lb.join(e.tempoRoot,"app"),r,s),buildTempoGlobalsCss(lb.join(e.tempoRoot,"app"),r))}await writeFileIfMissing(lb.join(e.tempoRoot,"index.html"),LT),await writeFileIfMissing(lb.join(e.tempoRoot,"main.tsx"),MT);const i=lb.join(e.tempoRoot,"main.tsx"),o=await readTextFileOptional3(i);null!==o&&await writeStylesheetFile(i,reconcileHostStyleImports(o,i,e.tempoRoot,s)),await writeManagedTempoGlobalsCss(lb.join(e.tempoRoot,"globals.css"),buildTempoGlobalsCss(e.tempoRoot,r,s),buildTempoGlobalsCss(e.tempoRoot,r)),await reconcileLegacyTempoIndexCss(e.tempoRoot)}var bk=new Set(["vite","@vitejs/plugin-react"]),vk=/^vite\.config\.[cm]?[jt]s$/;async function isWorkspaceAppPackage(e){const t=await readJsonObjectOptional(lb.join(e,"package.json"));if(!t)return!1;const n=collectDependencyNames(t),r=sT.some(e=>!bk.has(e)&&n.has(e));if(r)return!0;let s;try{s=await tb(e)}catch{return!1}if(s.some(e=>vk.test(e)))return!0;const i=[...bk].some(e=>n.has(e));return i&&s.includes("index.html")}async function findAppDirToRecord(e){const t={appDir:null,warning:null};if(void 0!==e.appDir)return t;const n=await listWorkspaceMemberDirs(e.projectRoot),r=n.length>0,s=r?await isWorkspaceAppPackage(e.projectRoot):await isAppPackageDir(e.projectRoot);if(s)return t;const i=await findAppPackageSubdirs(e),o=i.length>1&&!await isAppPackageDir(e.projectRoot);if(o)return t;const a=r?[...new Set([...i,...await findWorkspaceAppMembers(e,n)])]:i;if(a.length>1)return{appDir:null,warning:multipleAppDirectoriesWarning(e,a)};const[c]=a;if(!c)return t;const l=toPosixRelativePath(e.projectRoot,c),d=e.apps[0]?.start,u=d===await nuxtAppStartFor(e.projectRoot,e.tempoRoot);return d&&!u?{appDir:null,warning:`The project's only app package is "${l}", but apps[0].start is already set, so Tempo did not record apps[0].appDir: that would change the folder the command runs from. If "${l}" is the app, set "apps[0].appDir": "${l}" in tempo/tempo.config.json.`}:{appDir:l,warning:null}}async function findWorkspaceAppMembers(e,t){const n=lb.resolve(e.tempoRoot),r=[];for(const e of t)lb.resolve(e)!==n&&await isWorkspaceAppPackage(e)&&r.push(e);return r}function assertCanvasHostRendersUiFramework(e,t){const n=resolveAppUiFramework(t);if(!canvasHostRendersUiFramework(e,n)){if("nuxt"===e){const e=void 0===t?"unset":`"${t}"`;throw new Error(`Nuxt projects host component storyboards in the Tempo Nuxt sidecar and require apps[0].uiFramework: "vue" (it is ${e}). Set it in tempo/tempo.config.json or rerun canvas_project_init.`)}throw new Error(`Tempo ${ST[n].label} component storyboards require the Vite canvas host; resolved host framework was "${e}". Use route storyboards for this app or set up a Vite canvas host.`)}}function setupWarning(e){return console.warn(`[tempo-project] ${e}`),e}async function hasCustomReactViteHost(e,t){if("vite"!==t||"react"!==resolveAppUiFramework(e.apps[0]?.uiFramework))return!1;const n=await readTextFileOptional3(e.viteConfigPath);if(null===n)return!1;const r=n.includes("tempoStylesRequire(import.meta.url)")&&n.includes(".tempo-styles/host-styles.cjs"),s=Ek.test(n)||r;return/\b(?:tempoAnnotate|tempoVitePlugin)\s*\(/.test(n)&&!s}async function ensureProjectSetupFiles(e,t="vite",n={}){const{createPackageJsonIfMissing:r=!0}=n,s=[];await ensureTempoWorkspaceNonce(e.tempoRoot);const{appRoot:i,warning:o}=await resolveAppRoot(e);o&&s.push(setupWarning(o));const a=i===e.projectRoot?e:{...e,projectRoot:i},c=resolveAppUiFramework(e.apps[0]?.uiFramework);if(assertCanvasHostRendersUiFramework(t,e.apps[0]?.uiFramework),"astro"===c&&(r&&await ensureAstroAppIntegration(i,uk),await writeFileIfMissing(lb.join(e.tempoRoot,"astro-env.d.ts"),'/// <reference types="tempo-sdk/astro/client" />\n')),!1!==n.migrateSdkDependencies)for(const t of new Set([e.projectRoot,i])){const n=lb.join(t,"package.json"),r=await migrateTempoSdkPins(n,e.tempoRoot);r.length>0&&s.push(setupWarning(`updated tempo-sdk version(s) in ${n}: ${r.join(", ")} → ${uk}`))}if("expo"===t)return await upsertPackageJson(a,"expo",null,{createIfMissing:r}),s;if("nuxt"===t){const t=await ensureNuxtAppTypesGenerated(i);t&&s.push(t),await upsertPackageJson(a,"nuxt",null,{createIfMissing:r}),await ensureNuxtTsconfigFile(e),await reconcileVueShimsFile(e,c);const n=lb.join(e.tempoRoot,WT),o=toPosixRelativePath(e.tempoRoot,i),l=toPosixRelativePath(e.tempoRoot,await resolveUserNuxtSrcDir(i,await readUserNuxtConfigSource(i)));return await writeFileIfMissing(n,buildNuxtSidecarConfigFile({extendsPath:o,srcDir:l,compatibilityDate:(new Date).toISOString().slice(0,10)})),await reconcileNuxtSidecarAppLocation(n,{extendsPath:o,srcDir:l}),await reconcileNuxtSidecarHostRole(n),await writeFileIfMissing(lb.join(e.tempoRoot,HT,WT),qT),s}const l=await discoverProjectStyleContext(a,t);if(await ensureStylesheetFiles(e,t,l,i),"nextjs"===t){await upsertPackageJson(a,"nextjs",l,{createIfMissing:r}),await ensureNextTsconfigFile(a);const t=lb.join(e.tempoRoot,"next.config.mjs");return await writeFileIfMissing(t,buildNextConfigFile(await collectAppTranspilePackages(a))),await healNextConfigTracingRoot(t),await ensureNextPostcssConfigFile(lb.join(e.tempoRoot,"postcss.config.mjs"),l),3===l.tailwindMajor&&await ensureTailwindV3HostConfigFile(a,l),s}return await upsertPackageJson(a,"vite",l,{createIfMissing:r}),await ensureViteTsconfigFile(a),3===l.tailwindMajor&&await ensureTailwindV3HostConfigFile(a,l),"svelte"===c&&await ensureSvelteHostConfigFile(e,i),await reconcileVueShimsFile(e,c),await ensureViteConfigFile(e,l,c,i),s}var wk="// @tempo-owned: vue-shims",_k=`${wk}\ndeclare module "*.vue" {\n import type { DefineComponent } from "vue";\n const component: DefineComponent<{}, {}, any>;\n export default component;\n}\n`;async function reconcileVueShimsFile(e,t){const n=lb.join(e.tempoRoot,"vue-shims.d.ts");if("vue"===t)return void await reconcileGeneratedTextFile(n,_k,e=>e.startsWith(wk));const r=await readTextFileOptional3(n);r?.startsWith(wk)&&await ib(n)}var xk=["svelte.config.js","svelte.config.mjs","svelte.config.ts","svelte.config.mts"];async function findSvelteConfigFile(e){for(const t of xk){const n=lb.join(e,t);if(await pathExists4(n))return n}return null}function importSpecifier(e,t){const n=toPosixRelativePath(e,t);return n.startsWith(".")?n:`./${n}`}async function ensureSvelteHostConfigFile(e,t){const n=await findSvelteConfigFile(t),r=n?`import configuredApp from ${JSON.stringify(importSpecifier(e.tempoRoot,n))};\n`:"const configuredApp = {};\n",s=`// @tempo-owned: svelte-host-config\n${r}import { tempoSveltePreprocess } from "tempo-sdk/svelte";\n\nconst { kit: _svelteKitOnly, ...appConfig } = configuredApp;\nvoid _svelteKitOnly;\nconst appPreprocess = appConfig.preprocess == null\n ? []\n : Array.isArray(appConfig.preprocess)\n ? appConfig.preprocess\n : [appConfig.preprocess];\n\nexport default {\n ...appConfig,\n preprocess: [\n tempoSveltePreprocess({ root: ${JSON.stringify(e.tempoRoot)}, sourceRoot: ${JSON.stringify(e.projectRoot)}, enabled: true }),\n ...appPreprocess,\n ],\n};\n`;await atomicWriteText(lb.join(e.tempoRoot,"svelte.config.mjs"),s)}var Tk=["tailwind.config.ts","tailwind.config.js","tailwind.config.mjs","tailwind.config.cjs"],kk="// @tempo-owned: tailwind-v3-host-config";function isTempoOwnedTailwindV3HostConfig(e){return!!e.startsWith(kk)||e.includes("Tempo-owned Tailwind v3 config for the canvas host")}async function ensureTailwindV3HostConfigFile(e,t){const n=lb.join(e.tempoRoot,"tailwind.config.ts"),r=buildTailwindV3HostConfig(e,t);for(const t of Tk){const s=lb.join(e.tempoRoot,t),i=await readTextFileOptional3(s);if(null!==i)return s===n&&isTempoOwnedTailwindV3HostConfig(i)?void(i!==r&&await atomicWriteText(n,r)):void 0}await atomicWriteText(n,r)}async function ensureNextPostcssConfigFile(e,t){const n=3===t.tailwindMajor?ak:ok,r=await readTextFileOptional3(e);await writeStylesheetFile(e,null===r?n:migrateNextStylesheetConfig(r,t.tailwindMajor))}async function ensureViteConfigFile(e,t,n,r){let s=await readTextFileOptional3(e.viteConfigPath);if(null===s)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));if(shouldRegenerateViteConfig(s,t,n))return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));if(s.includes("tempoVitePlugin")){const n=migrateViteStylesheetConfig(s,t.tailwindMajor);await writeStylesheetFile(e.viteConfigPath,n),s=n}const i=addSourceIdentityRootToViteConfig(s,e);if(null===i)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));const o=addHostRuntimeDedupeToViteConfig(i,n);if(null===o)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));const a=addCanvasDepScanToViteConfig(o);if(null===a)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));const c=retargetVueAppRootInViteConfig(a,toPosixRelativePath(e.tempoRoot,r));c!==s&&await atomicWriteText(e.viteConfigPath,c)}function vueAppRootExpression(e){return`path.resolve(tempoRoot, ${JSON.stringify(e)})`}var Sk=/(tempoVueAppPlugins\(\{[^)]*?appRoot: )path\.resolve\(tempoRoot, "[^"]*"\)/;function retargetVueAppRootInViteConfig(e,t){return e.replace(Sk,(e,n)=>`${n}${vueAppRootExpression(t)}`)}var Ek=/^\/\/ @tempo-ui-framework: [\w-]+/m;function shouldRegenerateViteConfig(e,t,n){const r=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(r){const t=e.match(Ek)?.[0]??null,r=ST[n].marker;if(t!==r)return!0}return 3===t.tailwindMajor?!!e.includes("@tailwindcss/vite")||!!r&&(e.includes("tailwindcss({ config:")||e.includes('from "../tailwind.config')||e.includes("from '../tailwind.config")):!!r&&(e.includes('from "tailwindcss"')||e.includes("from 'tailwindcss'"))}function addSourceIdentityRootToViteConfig(e,t){const n=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(!n||e.includes("sourceIdentityRoot"))return e;let r=e;if(!/\b(?:const|let|var)\s+projectRoot\b/.test(r)){if(!/\bpath\.resolve\b/.test(r)&&!/\bimport\s+path\b/.test(r))return null;const e=r.match(/(const\s+tempoRoot\s*=\s*path\.dirname\([^;]+;)/);if(!e)return null;const n=toRelativeAllowPath(t);r=r.replace(e[1],`${e[1]}\nconst projectRoot = path.resolve(tempoRoot, ${JSON.stringify(n)});`)}const s=/tempoVitePlugin\s*\(\s*\)/;if(s.test(r))return r.replace(s,"tempoVitePlugin({ sourceIdentityRoot: projectRoot })");const i=/tempoVitePlugin\s*\(\s*\{/;return i.test(r)?r.replace(i,"tempoVitePlugin({ sourceIdentityRoot: projectRoot,"):null}var Ak=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","tempo-sdk"];function hostRuntimeDedupeTargets(e){return[...Ak,...ST[e].dedupe]}function hostRuntimeDedupeLiteral(e){return`[${hostRuntimeDedupeTargets(e).map(e=>`"${e}"`).join(", ")}]`}var Ck=["react","react-dom","react-dom/client","react/jsx-runtime","react/jsx-dev-runtime"];function addHostRuntimeDedupeToViteConfig(e,t){const n=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(!n)return e;const r=e.match(/dedupe\s*:\s*\[([^\]]*)\]/);if(r){const n=r[1],s=n.replace(/"[^"]*"|'[^']*'/g,"");if(/[^\s,]/.test(s))return null;const i=new Set([...n.matchAll(/"([^"]*)"|'([^']*)'/g)].map(e=>e[1]??e[2])),o=hostRuntimeDedupeTargets(t).filter(e=>!i.has(e));if(0===o.length)return e;const a=n.trimEnd(),c=a.trim().length>0?", ":"",l=`${a}${c}${o.map(e=>`"${e}"`).join(", ")}${n.slice(a.length)}`;return e.replace(r[0],`dedupe: [${l}]`)}if(/\bdedupe\s*:/.test(e))return null;const s=hostRuntimeDedupeLiteral(t),i=e.match(/(\n([ \t]*)resolve:[ \t]*\{[ \t]*\n)/);if(i){const t=`${i[2]} `;return e.replace(i[1],`${i[1]}${t}dedupe: ${s},\n`)}if(/\bresolve[ \t]*:/.test(e))return null;const o=e.match(/(\n([ \t]*)root:[ \t]*tempoRoot,[ \t]*\n)/);if(o){const t=o[2],n=`${t}resolve: {\n${t} dedupe: ${s},\n${t}},\n`;return e.replace(o[1],`${o[1]}${n}`)}return null}function addCanvasDepScanToViteConfig(e){const t=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(!t)return e;if(e.includes("entries"))return e;const n='["index.html"]',r=`[${Ck.map(e=>`"${e}"`).join(", ")}]`,s=e.match(/(\n([ \t]*)optimizeDeps:[ \t]*\{[ \t]*\n)/);if(s){const t=`${s[2]} `;return e.replace(s[1],`${s[1]}${t}entries: ${n},\n${t}include: ${r},\n`)}if(/\boptimizeDeps[ \t]*:/.test(e))return null;const i=e.match(/(\n([ \t]*)root:[ \t]*tempoRoot,[ \t]*\n)/);if(i){const t=i[2],s=`${t}optimizeDeps: {\n${t} entries: ${n},\n${t} include: ${r},\n${t}},\n`;return e.replace(i[1],`${i[1]}${s}`)}return null}async function detectProjectFramework(e){const t=await readRootPackageDeps(e.projectRoot);if(t.expo)return"expo";if(t.next)return"nextjs";if(t.nuxt)return"nuxt";if(t.astro)return"vite";if(await anyFileExists2(e.projectRoot,["next.config.js","next.config.mjs","next.config.ts","next.config.cjs"]))return"nextjs";if(await anyFileExists2(e.projectRoot,zT))return"nuxt";if(await anyFileExists2(e.projectRoot,["app.config.js","app.config.ts","app.json","expo-env.d.ts"]))return"expo";if(await appRootUsesNuxt(e))return"nuxt";if(t.vite)return"vite";if(await anyFileExists2(e.projectRoot,["vite.config.js","vite.config.ts","vite.config.mjs","vite.config.cjs"]))return"vite";if(await anyFileExists2(e.tempoRoot,["next.config.js","next.config.mjs","next.config.ts","next.config.cjs"]))return"nextjs";if(await hasNuxtSidecarConfig(e.tempoRoot))return"nuxt";const n=await readRootPackageDeps(e.tempoRoot);return n.next?"nextjs":n.expo||await anyFileExists2(e.tempoRoot,["app.config.js","app.config.ts","app.json","expo-env.d.ts"])?"expo":"vite"}async function readRootPackageDeps(e){const t=lb.join(e,"package.json"),n=await readTextFileOptional3(t);if(!n)return{};let r;try{r=parsePackageJson(t,n)}catch{return{}}return{...toStringRecord(r.dependencies),...toStringRecord(r.devDependencies)}}async function anyFileExists2(e,t){for(const n of t)if(await pathExists4(lb.join(e,n)))return!0;return!1}async function detectScaffoldFramework(e){return await anyFileExists2(e.tempoRoot,["metro.config.js","expo-env.d.ts"])?"expo":await anyFileExists2(e.tempoRoot,["next.config.js","next.config.mjs","next.config.ts","next.config.cjs"])?"nextjs":await hasNuxtSidecarConfig(e.tempoRoot)?"nuxt":await anyFileExists2(e.tempoRoot,["vite.config.js","vite.config.ts","vite.config.mjs","vite.config.cjs"])?"vite":null}var Ik={vite:["vite.config.js","vite.config.ts","vite.config.mjs","vite.config.cjs","main.tsx","index.html"],nextjs:["next.config.js","next.config.mjs","next.config.ts","next.config.cjs","next-env.d.ts","postcss.config.mjs","postcss.config.cjs","postcss.config.js"],expo:["app.json","metro.config.js","babel.config.js","expo-env.d.ts","index.js"],nuxt:[...zT,".nuxt","tsconfig.json",HT,...VT.map(e=>`${GT}/${e}`)]},Pk=["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock"];async function healFrameworkMismatch(e,t,n={}){const r=await detectScaffoldFramework(e);if(null===r||r===t)return{healed:!1,previousFramework:r,backupPath:null};const s=n.now??Date.now(),i=`.tempo-backup-${r}-${s}`,o=lb.join(e.tempoRoot,i),a=[...Ik[r],...Pk,".tempo-styles"];let c=!1;for(const t of a){const n=lb.join(e.tempoRoot,t);if(!await pathExists4(n))continue;const r=lb.join(o,t);await eb(lb.dirname(r),{recursive:!0}),await rb(n,r),c=!0}return c?(await rewriteTempoConfigForFramework(e.tempoConfigPath,t,e.projectRoot),{healed:!0,previousFramework:r,backupPath:o}):{healed:!1,previousFramework:r,backupPath:null}}async function rescueWronglyBackedUpFiles(e){const t=[];let n,r=0;try{n=await tb(e.tempoRoot,{withFileTypes:!0})}catch{return{restored:t,backupsScanned:r}}for(const s of n){if(!s.isDirectory())continue;const n=/^\.tempo-backup-(vite|nextjs|expo|nuxt)-\d+$/.exec(s.name);if(!n)continue;r+=1;const i=n[1],o=new Set([...Ik[i].map(e=>e.split("/")[0]),...Pk,"App.tsx","tsconfig.json","globals.css"]),a=lb.join(e.tempoRoot,s.name);let c;try{c=await tb(a,{withFileTypes:!0})}catch{continue}for(const n of c){if(o.has(n.name))continue;const r=lb.join(e.tempoRoot,n.name);if(!await pathExists4(r))try{await rb(lb.join(a,n.name),r),t.push(n.name)}catch{}}}return{restored:t,backupsScanned:r}}async function rewriteTempoConfigForFramework(e,t,n){const r=await readTextFileOptional3(e);if(null===r)return;let s;try{s=JSON.parse(r)}catch{return}if(!s||"object"!=typeof s||Array.isArray(s))return;const i=s.scripts,o=i&&"object"==typeof i&&!Array.isArray(i)?{...i}:{};o.start="expo"===t?"npx expo start --web":"npm run dev";const a=await detectRootPackageManager(n);o.install=buildInstallScript(a?.installCmd??null),s.scripts=o,await ob(e,`${JSON.stringify(s,null,2)}\n`,"utf-8")}async function reconcileExpoStartScriptOnDisk(e,t){return await reconcileExpoStartScript(e,t)}async function reconcileExpoStartScript(e,t){if("expo"!==t)return!1;const n=await readTextFileOptional3(e);if(null===n)return!1;let r;try{r=JSON.parse(n)}catch{return!1}if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r.scripts;if(!s||"object"!=typeof s||Array.isArray(s))return!1;const i=s,o="string"==typeof i.start?i.start:"",a="npx expo start --web";return o!==a&&(!(!/\bexpo\s+start\b/.test(o)||!o.includes("--web"))&&(i.start=a,r.scripts=i,await ob(e,`${JSON.stringify(r,null,2)}\n`,"utf-8"),!0))}async function upsertPackageJson(e,t,n,r){const s=await readTextFileOptional3(e.packageJsonPath);if(null===s&&!r.createIfMissing)return;let i;if("expo"===t){const t=await readUserExpoVersions(e.projectRoot);i=n=>buildExpoTempoOwnedPackage(n,e,t)}else if("nextjs"===t){if(!n)throw new Error(`Missing style context for ${t} project setup`);i=t=>buildNextTempoOwnedPackage(t,e,n)}else if("nuxt"===t){const t=await readUserNuxtVersions(e.projectRoot),n=await readUserReactVersions(e),{links:r}=await appPackageLinks(e.projectRoot,e.tempoRoot,Bk);i=s=>buildNuxtTempoOwnedPackage(s,e,t,n,r)}else{if(!n)throw new Error(`Missing style context for ${t} project setup`);const r=await readUserReactVersions(e),s=resolveAppUiFramework(e.apps[0]?.uiFramework),o=ST[s].packages,a=o?await readUserFrameworkVersions(e,o):{},c="vue"===s?await appPackageLinks((await resolveAppRoot(e)).appRoot,e.tempoRoot,["vue"]):null;i=t=>buildTempoOwnedPackage(t,e,n,r,a,s,c)}await writeManagedDependencyManifest(e.tempoRoot,e.packageJsonPath,e=>null!==e||r.createIfMissing?i(e):null)}function pickDependencyVersion(e,t,n,r){const s=e.packageVersions[t];return s?void 0!==r&&parsePackageMajorVersion(s)!==r?n:s:n}function applyTailwindDevDependencyMode(e,t,n){if(3===t.tailwindMajor)return delete e["@tailwindcss/vite"],delete e["@tailwindcss/postcss"],e.tailwindcss=pickDependencyVersion(t,"tailwindcss",vT.tailwindcss,3),e.postcss=pickDependencyVersion(t,"postcss",vT.postcss),void(e.autoprefixer=pickDependencyVersion(t,"autoprefixer",vT.autoprefixer));e.tailwindcss=pickDependencyVersion(t,"tailwindcss",bT.tailwindcss,4),"nextjs"===n?(delete e["@tailwindcss/vite"],e["@tailwindcss/postcss"]=pickDependencyVersion(t,"tailwindcssPostcss",AT["@tailwindcss/postcss"],4)):e["@tailwindcss/vite"]=pickDependencyVersion(t,"tailwindcssVite",bT["@tailwindcss/vite"],4)}function withUserReactMajorAdopted(e,t){const n=t.react??t["react-dom"],r=n?parsePackageMajorVersion(n):null,s=parsePackageMajorVersion(e.react??"");return null===r||null===s||r<=s?{...e}:{...e,react:`^${r}.0.0`,"react-dom":`^${r}.0.0`}}function buildTempoOwnedPackage(e,t,n,r={},s={},i="react",o=null){const a=e?parsePackageJson(t.packageJsonPath,e):{},c=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),l=toStringRecord(a.devDependencies),d=toStringRecord(a.dependencies),u=ST[i].packages,p=u?fillFrameworkVitePluginPair(u,l,s):{},m=u?fillFrameworkRuntime(u,d,s):{};if(o){Object.assign(m,o.links);for(const e of o.reachedByWalkingUp)delete m[e],delete d[e]}const f=sortObjectKeys({...3===n.tailwindMajor?vT:bT,...l,...p});applyTailwindDevDependencyMode(f,n,"vite"),applyManagedTempoSdkSpec(d,f,a);const g=withUserReactMajorAdopted(wT,r),y=g.react===wT.react?{}:{react:g.react,"react-dom":g["react-dom"]},b={...a,name:"string"==typeof a.name&&a.name.trim().length>0?a.name:c,private:"boolean"!=typeof a.private||a.private,type:"string"==typeof a.type&&a.type.trim().length>0?a.type:"module",scripts:sortObjectKeys({...ET,...toStringRecord(a.scripts)}),dependencies:sortObjectKeys({...wT,...d,...m,...y}),devDependencies:f};return`${JSON.stringify(b,null,2)}\n`}function fillFrameworkVitePluginPair(e,t,n){const r=Object.keys(e.devDependencies),s=[...r,"vite"],pairFrom=e=>s.every(t=>e[t])?Object.fromEntries(s.map(t=>[t,e[t]])):null,i=pairFrom(withoutWorkspaceProtocolSpecs(t)),o=pairFrom(n),a=null!==o&&r.every(e=>t[e]===o[e]);return i&&!a?i:o??i??{...e.devDependencies,vite:bT.vite}}function fillFrameworkRuntime(e,t,n){const r=withoutWorkspaceProtocolSpecs(t);return Object.fromEntries(Object.entries(e.dependencies).map(([t,s])=>{const i=e.runtimeFollowsApp?n[t]??r[t]??s:r[t]??n[t]??s;return[t,i]}))}function isCompatibleManagedSpec(e,t){if("string"!=typeof e||0===e.trim().length)return!1;const n=parsePackageMajorVersion(t);if(null===n)return!1;const r=[...e.matchAll(/(?:^|[\s~^><=|-])(\d+)/g)].map(e=>Number.parseInt(e[1],10));return 0!==r.length&&r.every(e=>e===n)}function withCompatibleVersionsPreserved(e,t){const n={...e};for(const r of Object.keys(e))isCompatibleManagedSpec(t[r],e[r])&&(n[r]=t[r]);return n}function buildNextTempoOwnedPackage(e,t,n){const r=e?parsePackageJson(t.packageJsonPath,e):{},s=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),i=toStringRecord(r.scripts),o=toStringRecord(r.dependencies),a=toStringRecord(r.devDependencies);void 0!==o.vite||void 0!==a.vite||i.dev;i.dev===ET.dev&&delete i.dev,i.build===ET.build&&delete i.build,i.preview===ET.preview&&delete i.preview;for(const e of DT)delete o[e],delete a[e];const c=sortObjectKeys({...a,...3===n.tailwindMajor?CT:AT});applyTailwindDevDependencyMode(c,n,"nextjs"),applyManagedTempoSdkSpec(o,c,r);const l={...r,name:"string"==typeof r.name&&r.name.trim().length>0?r.name:s,private:"boolean"!=typeof r.private||r.private,type:"string"==typeof r.type&&r.type.trim().length>0?r.type:"module",scripts:sortObjectKeys({...i,...PT}),dependencies:sortObjectKeys({...o,...withCompatibleVersionsPreserved(IT,o)}),devDependencies:c};return`${JSON.stringify(l,null,2)}\n`}async function readUserExpoVersions(e){const t=lb.join(e,"package.json"),n=await readTextFileOptional3(t);if(!n)return{};let r;try{r=parsePackageJson(t,n)}catch{return{}}const s={...toStringRecord(r.dependencies),...toStringRecord(r.devDependencies)},i={};for(const e of Object.keys(NT))s[e]&&(i[e]=s[e]);return i}async function readUserReactVersions(e){const{appRoot:t}=await resolveAppRoot(e),n=await readAppDependencySpecs(t,["react","react-dom"]);return n?.specs??{}}async function readUserFrameworkVersions(e,t){const{appRoot:n}=await resolveAppRoot(e),r=await readAppDependencySpecs(n,[...Object.keys(t.dependencies),...Object.keys(t.devDependencies),"vite"]);if(!r)return{};const s=t.appSignals.some(e=>r.declared.has(e));return s?r.specs:{}}async function readAppDependencySpecs(e,t){const n=lb.join(e,"package.json"),r=await readTextFileOptional3(n);if(!r)return null;let s;try{s=parsePackageJson(n,r)}catch{return null}const i={...toStringRecord(s.dependencies),...toStringRecord(s.devDependencies)},o={};for(const n of t){const t=i[n];if(!t)continue;if(!specIsBoundToItsPackage(t)){o[n]=t;continue}const r=await findInstalledPackage(e,n);r?.version&&(o[n]=r.version)}return{declared:new Set(Object.keys(i)),specs:o}}function specIsBoundToItsPackage(e){const t=e.trim();return!!/^(catalog|workspace|link|file|portal|patch):/.test(t)||(t.startsWith(".")||t.startsWith("/"))}function withoutWorkspaceProtocolSpecs(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>!/^(catalog|workspace):/.test(e.trim())))}function buildExpoTempoOwnedPackage(e,t,n={}){const r=e?parsePackageJson(t.packageJsonPath,e):{},s=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),i=toStringRecord(r.scripts),o=toStringRecord(r.dependencies),a=toStringRecord(r.devDependencies),c=void 0!==o.vite||void 0!==a.vite||"vite"===i.dev;for(const e of DT)delete o[e],delete a[e];for(const e of OT)delete o[e],delete a[e];delete o.next,delete a.next,delete a["@tailwindcss/postcss"];for(const e of Object.keys(NT))delete o[e];const l={...NT,...n},d=sortObjectKeys({...RT,...a});applyManagedTempoSdkSpec(o,d,r);const u={...r,name:"string"==typeof r.name&&r.name.trim().length>0?r.name:s,private:"boolean"!=typeof r.private||r.private,main:"string"==typeof r.main&&r.main.trim().length>0&&"expo-router/entry"!==r.main?r.main:"index.js",scripts:sortObjectKeys({...FT,...i}),dependencies:sortObjectKeys({...l,...o}),devDependencies:d};return"string"==typeof r.type&&r.type.trim().length>0&&(!c||"module"!==r.type)&&(u.type=r.type),`${JSON.stringify(u,null,2)}\n`}var Dk={target:"ES2022",module:"ESNext",moduleResolution:"Bundler",jsx:"react-jsx",strictNullChecks:!0,noEmit:!0},Rk=new Set(["strictNullChecks"]),Nk=["./**/*.ts","./**/*.tsx"];function buildViteTsconfigFile(e){const t=Object.keys(e).length>0;return`${JSON.stringify({compilerOptions:{...Dk,...t?{baseUrl:".",paths:e}:{}},include:Nk},null,2)}\n`}function parseJsonc(e){let t="",n=!1,r=!1,s=!1;for(let i=0;i<e.length;i++){const o=e[i],a=e[i+1];r?"\n"===o&&(r=!1,t+=o):s?"*"===o&&"/"===a&&(s=!1,i++):n?(t+=o,"\\"===o?(t+=a??"",i++):'"'===o&&(n=!1)):'"'!==o?"/"!==o||"/"!==a?"/"!==o||"*"!==a?t+=o:(s=!0,i++):(r=!0,i++):(n=!0,t+=o)}const i=t.replace(/,(\s*[}\]])/g,"$1");try{return JSON.parse(i)}catch{return null}}function normalizePathsRecord(e){const t={};for(const[n,r]of Object.entries(e))if(Array.isArray(r)){const e=r.filter(e=>"string"==typeof e);e.length>0&&(t[n]=e)}else"string"==typeof r&&(t[n]=[r]);return t}function resolveReferencePath(e,t){const n=lb.resolve(e,t);return t.endsWith(".json")?n:lb.join(n,"tsconfig.json")}async function readTsconfigPathsFrom(e,t,n){if(t>8)return null;const r=lb.resolve(e);if(n.has(r))return null;n.add(r);const s=await readTextFileOptional3(r);if(null===s)return null;const i=parseJsonc(s);if(!i||"object"!=typeof i||Array.isArray(i))return null;const o=i,a=o.compilerOptions&&"object"==typeof o.compilerOptions&&!Array.isArray(o.compilerOptions)?o.compilerOptions:null,c=a?.paths;if(c&&"object"==typeof c&&!Array.isArray(c)){const e=normalizePathsRecord(c);if(Object.keys(e).length>0){const t="string"==typeof a?.baseUrl?a.baseUrl:".";return{configDir:lb.dirname(r),baseUrl:t,paths:e}}}const l=Array.isArray(o.references)?o.references:[];for(const e of l){if(!e||"object"!=typeof e||Array.isArray(e))continue;const s=e.path;if("string"!=typeof s)continue;const i=await readTsconfigPathsFrom(resolveReferencePath(lb.dirname(r),s),t+1,n);if(i)return i}const d=Array.isArray(o.extends)?o.extends:"string"==typeof o.extends?[o.extends]:[];for(const e of[...d].reverse()){if("string"!=typeof e)continue;const s=resolveExtendsConfigPath(lb.dirname(r),e);if(null===s)continue;const i=await readTsconfigPathsFrom(s,t+1,n);if(i)return i}return null}function resolveExtendsConfigPath(e,t){if(t.startsWith("./")||t.startsWith("../"))return t.endsWith(".json")?lb.resolve(e,t):lb.resolve(e,`${t}.json`);const n=ab(lb.join(e,"__tempo_tsconfig_resolve__.cjs")),r=t.endsWith(".json")?[t]:[t,`${t}/tsconfig.json`];for(const e of r)try{const t=n.resolve(e);if(t.endsWith(".json"))return t}catch{}return null}function rebaseAliasTarget(e,t,n,r){const s=lb.resolve(e,t,n);return toPosixRelativePath(r,s)}async function collectHostAliasPaths(e){for(const t of["tsconfig.json","jsconfig.json"]){const n=lb.join(e.projectRoot,t),r=await readTextFileOptional3(n);if(null===r)continue;if(null===parseJsonc(r))return{aliasPaths:{},warning:`Could not parse ${n}; "@/"-style imports in canvas files may not resolve.`};const s=await readTsconfigPathsFrom(n,0,new Set);if(!s)return{aliasPaths:{},warning:null};const i={};for(const[t,n]of Object.entries(s.paths)){const r=n.map(t=>rebaseAliasTarget(s.configDir,s.baseUrl,t,e.tempoRoot));r.length>0&&(i[t]=r)}return{aliasPaths:i,warning:null}}return{aliasPaths:{},warning:null}}function isTempoOwnedViteTsconfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;if(Object.keys(t).some(e=>"compilerOptions"!==e&&"include"!==e))return!1;const n=t.include;if(!Array.isArray(n)||n.length!==Nk.length||!Nk.every((e,t)=>n[t]===e))return!1;const r=t.compilerOptions;if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r;for(const[e,t]of Object.entries(Dk))if((e in s||!Rk.has(e))&&s[e]!==t)return!1;const i=new Set([...Object.keys(Dk),"baseUrl","paths"]);return!Object.keys(s).some(e=>!i.has(e))}async function reconcileGeneratedTsconfig(e,t,n){const r=await readTextFileOptional3(e);null!==r?r!==t&&n(parseJsonc(r))&&await atomicWriteText(e,t):await atomicWriteText(e,t)}async function reconcileGeneratedTextFile(e,t,n){const r=await readTextFileOptional3(e);null!==r?r!==t&&n(r)&&await atomicWriteText(e,t):await atomicWriteText(e,t)}async function ensureViteTsconfigFile(e){const{aliasPaths:t}=await collectHostAliasPaths(e);await reconcileGeneratedTsconfig(e.tsconfigPath,buildViteTsconfigFile(t),isTempoOwnedViteTsconfig)}async function ensureNextTsconfigFile(e){const{aliasPaths:t}=await collectHostAliasPaths(e);await reconcileGeneratedTsconfig(e.tsconfigPath,buildNextTsconfigFile(e,t),isTempoOwnedNextTsconfig)}var Ok={target:"ES2022",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,strictNullChecks:!0,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0};function buildNextTsconfigIncludes(e){const t=["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],n=toPosixRelativePath(e.tempoRoot,lb.join(e.projectRoot,"src")),r=toPosixRelativePath(e.tempoRoot,e.pagesDir);for(const e of[`${n}/**/*`,`${r}/**/*`])t.includes(e)||t.push(e);return t}function buildNextTsconfigFile(e,t){const n=Object.keys(t).length>0;return`${JSON.stringify({compilerOptions:{...Ok,...n?{baseUrl:".",paths:t}:{}},include:buildNextTsconfigIncludes(e),exclude:["node_modules"]},null,2)}\n`}function isTempoOwnedNextTsconfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e,n=new Set(["compilerOptions","include","exclude"]);if(Object.keys(t).some(e=>!n.has(e)))return!1;const r=t.compilerOptions;if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r;for(const[e,t]of Object.entries(Ok))if(e in s||!Rk.has(e))if(Array.isArray(t)){const n=s[e];if(!Array.isArray(n)||n.length!==t.length||!t.every((e,t)=>n[t]===e))return!1}else if(s[e]!==t)return!1;const i=new Set([...Object.keys(Ok),"baseUrl","paths"]);return!Object.keys(s).some(e=>!i.has(e))}var Fk={"react-native":["./node_modules/react-native"],"react-native/*":["./node_modules/react-native/*"],"react-native-web":["./node_modules/react-native-web"],"react-native-web/*":["./node_modules/react-native-web/*"]},Lk=["expo-env.d.ts","**/*.ts","**/*.tsx"];function buildExpoTsconfigFile(e,t={}){const n=[...Lk,toPosixRelativePath(e.tempoRoot,lb.join(e.projectRoot,"src"))+"/**/*",toPosixRelativePath(e.tempoRoot,e.pagesDir)+"/**/*"],r={...Fk,...t};return`${JSON.stringify({extends:"expo/tsconfig.base",compilerOptions:{strict:!1,strictNullChecks:!0,jsx:"react-jsx",noEmit:!0,baseUrl:".",paths:r},include:Array.from(new Set(n)),exclude:["node_modules"]},null,2)}\n`}function isTempoOwnedExpoTsconfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const e of Object.keys(t))if(!["extends","compilerOptions","include","exclude"].includes(e))return!1;if("expo/tsconfig.base"!==t.extends)return!1;const n=t.compilerOptions;if(!n||"object"!=typeof n||Array.isArray(n))return!1;const r=n;return!1===r.strict&&"react-jsx"===r.jsx&&!0===r.noEmit&&"."===r.baseUrl}function buildNextConfigFile(e=[]){const t=e.length>0?`\n transpilePackages: ${JSON.stringify(e)},`:"";return`import tempoNextjsPlugin from "tempo-sdk/nextjs/plugin";\nimport { fileURLToPath } from "node:url";\n\nconst withTempo = tempoNextjsPlugin();\n\nexport default withTempo({\n // Disabled for the canvas host only — see tempo-project/initialize.ts.\n reactStrictMode: false,${t}\n // fileURLToPath (not URL.pathname): pathname percent-encodes spaces/non-ASCII\n // and yields a "/C:/…" drive path on Windows — a nonexistent directory that\n // Turbopack, which uses this value as its workspace root, panics on.\n outputFileTracingRoot: fileURLToPath(new URL("..", import.meta.url)),\n});\n`}var Mk='new URL("..", import.meta.url).pathname',Uk='fileURLToPath(new URL("..", import.meta.url))';async function healNextConfigTracingRoot(e){const t=await readTextFileOptional3(e);if(null===t||!t.includes(Mk))return;let n=t.split(Mk).join(Uk);const r=/^\s*import\b[^\n;]*\bfileURLToPath\b/m.test(n);r||(n=insertLineAfterFirstImport(n,'import { fileURLToPath } from "node:url";')),n!==t&&await atomicWriteText(e,n)}function insertLineAfterFirstImport(e,t){const n=e.split("\n"),r=n.findIndex(e=>/^\s*import\b/.test(e));return-1===r?`${t}\n${e}`:(n.splice(r+1,0,t),n.join("\n"))}var jk=["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"];async function findNextConfigInDir(e){for(const t of jk){const n=lb.join(e,t);if(await pathIsFile(n))return n}return null}function extractTranspilePackagesFromSource(e){const t=/transpilePackages\s*:\s*\[([^\]]*)\]/.exec(e);if(!t)return[];const n=t[1],r=n.replace(/"[^"]*"|'[^']*'/g,"");return/[A-Za-z0-9_$]/.test(r)?[]:[...n.matchAll(/"([^"]+)"|'([^']+)'/g)].map(e=>e[1]??e[2])}async function collectAppTranspilePackages(e){const t=await findNextConfigInDir(e.projectRoot);if(null===t)return[];const n=await readTextFileOptional3(t);return null===n?[]:extractTranspilePackagesFromSource(n)}async function hasNuxtSidecarConfig(e){for(const t of zT){const n=await readTextFileOptional3(lb.join(e,t));if(n?.includes($T))return!0}return!1}async function isNuxtAppDir(e){const t=await readRootPackageDeps(e);return Boolean(t.nuxt)||await anyFileExists2(e,zT)}async function appRootUsesNuxt(e){const{appRoot:t}=await resolveAppRoot(e);return lb.resolve(t)!==lb.resolve(e.projectRoot)&&await isNuxtAppDir(t)}async function readUserNuxtConfigSource(e){for(const t of zT){const n=await readTextFileOptional3(lb.join(e,t));if(null!==n)return n}return null}async function findInstalledPackage(e,t){let n=lb.resolve(e);for(;;){const e=lb.join(n,"node_modules",t,"package.json");try{const t=await readJsonObjectOptional(e);if(t)return{dir:await nb(lb.dirname(e)),version:"string"==typeof t.version?t.version:null}}catch{}const r=lb.dirname(n);if(r===n)return null;n=r}}async function readUserNuxtVersions(e){const t=(await readRootPackageDeps(e)).nuxt??null,n=await findInstalledPackage(e,"nuxt");if(!n)return{nuxt:t,vite:null};const r=await findInstalledPackage(n.dir,"@nuxt/vite-builder"),s=r?await findInstalledPackage(r.dir,"vite"):null;return{nuxt:n.version??t,vite:s?.version??null}}async function appUsesNuxt4Layout(e){const{nuxt:t}=await readUserNuxtVersions(e),n=t?parsePackageMajorVersion(t):null;if(3!==n)return!0;const r=await readUserNuxtConfigSource(e);return null!==r&&/\bcompatibilityVersion\s*:\s*4\b/.test(r)}function buildNuxtSidecarConfigFile(e){return`${$T}\n// Tempo canvas dev server ("tempo-host"), NOT your app. Your app is a Nuxt\n// layer of this one, so its components, composables, plugins, server routes\n// and runtimeConfig are available to the canvas without copying anything.\nexport default defineNuxtConfig({\n extends: [${JSON.stringify(e.extendsPath)}],\n // Your app's own srcDir, kept in step with it by Tempo: modules that find\n // app files through \`nuxt.options.srcDir\` (pinia's stores) look there.\n // tempo-sdk/nuxt mounts the canvas host from tempo/app/.\n srcDir: ${JSON.stringify(e.srcDir)},\n ssr: false,\n devtools: { enabled: false },\n modules: ["tempo-sdk/nuxt"],\n // The module defaults to annotating an app; this config, not the module\n // list, makes it the canvas host, so the app (a layer) listing the module\n // too cannot change that.\n tempo: { role: "host" },\n experimental: { appManifest: false },\n compatibilityDate: ${JSON.stringify(e.compatibilityDate)},\n});\n`}function buildNuxtTempoHostMountVue(e){return`<script setup lang="ts">\nimport { onBeforeUnmount, onMounted, ref } from "vue";\nimport { mountTempoHost } from ${JSON.stringify(e)};\n\nconst el = ref<HTMLElement | null>(null);\nlet unmount: (() => void) | null = null;\n\nonMounted(() => {\n if (el.value) unmount = mountTempoHost(el.value);\n});\n\nonBeforeUnmount(() => {\n unmount?.();\n});\n<\/script>\n\n<template>\n <div ref="el" id="tempo-root"></div>\n</template>\n`}async function reconcileNuxtSidecarAppLocation(e,t){const n=await readTextFileOptional3(e);if(null===n||!n.includes($T))return;const r=n.replace(/^(\s*extends\s*:\s*)\[\s*(["'])[^"'\n]*\2\s*\]/m,(e,n)=>`${n}[${JSON.stringify(t.extendsPath)}]`).replace(/^(\s*srcDir\s*:\s*)(["'])[^"'\n]*\2/m,(e,n)=>`${n}${JSON.stringify(t.srcDir)}`);r!==n&&await atomicWriteText(e,r)}async function reconcileNuxtSidecarHostRole(e){const t=await readTextFileOptional3(e);if(null===t||!t.includes($T))return;const n=t.match(/\btempo\s*:/g)??[];let r=t;if(0===n.length)r=t.replace(/^(\s*)modules: \["tempo-sdk\/nuxt"\],\n/m,(e,t)=>`${e}${t}tempo: { role: "host" },\n`);else if(1===n.length){const e=/\btempo\s*:\s*\{([^{}]*)\}/.exec(t),n=e&&/\brole\s*:/.test(e[1]??"");if(e&&!n){const n=""===(e[1]??"").trim();r=t.replace(/(\btempo\s*:\s*\{)(\s*)/,(e,t,r)=>r.includes("\n")?`${t}${r}role: "host",${r}`:`${t} role: "host"${n?" ":", "}`)}}r!==t&&await atomicWriteText(e,r)}async function ensureNuxtSidecarPages(e){const t=lb.join(e.tempoRoot,GT);await writeFileIfMissing(lb.join(t,"app.vue"),KT),await writeFileIfMissing(lb.join(t,"pages","tempo-host.vue"),XT);const n=lb.join(t,"components");await writeFileIfMissing(lb.join(n,"TempoHostMount.vue"),buildNuxtTempoHostMountVue(importSpecifier(n,lb.join(e.tempoRoot,".tempo","host-entry"))))}var Bk=["nuxt","vue","vue-router","@vitejs/plugin-vue"];async function appPackageLinks(e,t,n){const r=await findOwningInstall(e),s="pnpm"===r.pin.pm?e:r.dir,i=isInsidePath(s,t),o=(await findOwningInstall(t)).pin.pm,a=await readRootPackageDeps(e),c=n.filter(e=>a[e]);if("yarn"===o||"bun"===o)return{links:{},reachedByWalkingUp:i?c:[],unsupportedInstaller:i?null:o};if("npm"===o&&i)return{links:{},reachedByWalkingUp:c,unsupportedInstaller:null};const l="pnpm"===o?"link:":"file:",d={};for(const e of c){const n=lb.join(s,"node_modules",e);d[e]=`${l}${toPosixRelativePath(t,n)}`}return{links:d,reachedByWalkingUp:[],unsupportedInstaller:null}}var $k="^5.2.0";function buildNuxtTempoOwnedPackage(e,t,n,r,s){const i=e?parsePackageJson(t.packageJsonPath,e):{},o=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),a=toStringRecord(i.dependencies),c=toStringRecord(i.devDependencies);for(const e of Bk)delete a[e],delete c[e];const l=withUserReactMajorAdopted(wT,r),d=l.react===wT.react?{}:{react:l.react,"react-dom":l["react-dom"]},u=sortObjectKeys({...wT,...a,...d,...s}),p=parsePackageMajorVersion(u.react??""),m=null===p?{}:{"@types/react":`^${p}.0.0`,"@types/react-dom":`^${p}.0.0`},f={typescript:bT.typescript,...m,...c,"@vitejs/plugin-react":$k};n.vite&&(f.vite=n.vite),applyManagedTempoSdkSpec(u,f,i);const g=n.nuxt?parsePackageMajorVersion(n.nuxt):null,y={...i,name:"string"==typeof i.name&&i.name.trim().length>0?i.name:o,private:"boolean"!=typeof i.private||i.private,type:"string"==typeof i.type&&i.type.trim().length>0?i.type:"module",scripts:sortObjectKeys({...toStringRecord(i.scripts),dev:3===g?"nuxt dev --no-fork":"nuxt dev",postinstall:"nuxt prepare"}),dependencies:u,devDependencies:sortObjectKeys(f)};return`${JSON.stringify(y,null,2)}\n`}var Wk={jsx:"react-jsx",jsxImportSource:"react",strictNullChecks:!0},Hk="./.nuxt/tsconfig.json";function buildNuxtTsconfigFile(e){const t=toPosixRelativePath(e.tempoRoot,e.pagesDir);return`${JSON.stringify({extends:Hk,compilerOptions:Wk,include:["./.nuxt/nuxt.d.ts",`${GT}/**/*`,".tempo/**/*","vue-shims.d.ts","controls.ts",`${t}/**/*`]},null,2)}\n`}function isTempoOwnedNuxtTsconfig(e){if(isTempoOwnedViteTsconfig(e)||isTempoOwnedNextTsconfig(e))return!0;if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e,n=new Set(["extends","compilerOptions","include"]);if(Object.keys(t).some(e=>!n.has(e)))return!1;if(t.extends!==Hk)return!1;const r=t.compilerOptions;if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r,i=Object.entries(Wk);return Object.keys(s).length===i.length&&i.every(([e,t])=>s[e]===t)}async function ensureNuxtTsconfigFile(e){await reconcileGeneratedTsconfig(e.tsconfigPath,buildNuxtTsconfigFile(e),isTempoOwnedNuxtTsconfig)}var qk=12e4;function resolveUserNuxtBuildDir(e,t){const n=t?.match(/\bbuildDir\s*:\s*["'`]([^"'`]+)["'`]/)?.[1];return lb.resolve(e,n??".nuxt")}async function readNuxtCliPath(e){const t=await readJsonObjectOptional(lb.join(e,"package.json")),n=t?.bin,r="string"==typeof n?n:n&&"object"==typeof n&&!Array.isArray(n)?n.nuxt??n.nuxi:void 0;if("string"!=typeof r)return null;const s=lb.resolve(e,r);return await pathIsFile(s)?s:null}async function ensureNuxtAppTypesGenerated(e){const t=await readUserNuxtConfigSource(e),n=resolveUserNuxtBuildDir(e,t);if(await pathIsFile(lb.join(n,"tsconfig.json")))return null;const r=await findInstalledPackage(e,"nuxt"),s=r?await readNuxtCliPath(r.dir):null;if(!s)return null;const i=`node "${s}" prepare`,o=augmentManagedPath({...process.env}),a=r?await pnpmHoistDirOf(r.dir):null;a&&(o.NODE_PATH=[a,o.NODE_PATH].filter(Boolean).join(lb.delimiter));const c=await runAbortableShellCommand({command:i,cwd:e,env:o,idleTimeoutMs:qk});if(0===c.exitCode)return null;const l=c.spawnError?.message??(c.timedOut?"it printed nothing for two minutes":`exit code ${c.exitCode}`);return setupWarning(`\`${i}\` in ${e} failed (${l}); the canvas host cannot transform app files until the app's .nuxt/ types exist. ${c.output.trim().slice(-800)}`)}async function resolveUserNuxtSrcDir(e,t){const n=t?.match(/\bsrcDir\s*:\s*["'`]([^"'`]+)["'`]/)?.[1];if(n)return lb.resolve(e,n);const r=lb.join(e,"app");return await appUsesNuxt4Layout(e)&&await pathIsDirectory(r)?r:e}function resolveNuxtCssSpecifier(e,t,n){const r=cleanLocalSpecifier(e);return r?/^(?:~~|@@)\//.test(r)?lb.resolve(t,r.slice(3)):/^[~@]\//.test(r)?lb.resolve(n,r.slice(2)):r.startsWith("./")||r.startsWith("../")?lb.resolve(t,r):null:null}async function collectNuxtCssEntries(e){const t=await readUserNuxtConfigSource(e),n=await resolveUserNuxtSrcDir(e,t),r=[],s=t?.match(/\bcss\s*:\s*\[([^\]]*)\]/)?.[1]??"";for(const t of s.matchAll(/["'`]([^"'`]+)["'`]/g)){const s=resolveNuxtCssSpecifier(t[1],e,n);s?.endsWith(".css")&&r.push(s)}const i=lb.join(n,"assets","css");let o=[];try{o=await tb(i,{withFileTypes:!0})}catch{}for(const e of o)e.isFile()&&e.name.endsWith(".css")&&r.push(lb.join(i,e.name));return r}function buildNuxtAppStartCommand(e,t){const n=t.startsWith(".")?t:`./${t}`,r=`nuxt dev --port \${APP_PORT} --extends ${n}`;return"pnpm"===e?`pnpm exec ${r}`:"yarn"===e?`yarn ${r}`:"bun"===e?`bunx ${r}`:`npx ${r}`}function nuxtAppLayerPathFrom(e,t){const n=toPosixRelativePath(e,lb.join(t,HT));return n.startsWith(".")?n:`./${n}`}async function nuxtAppStartFor(e,t){const n=await detectOwningPackageManager(e);return buildNuxtAppStartCommand(n?.pm??null,nuxtAppLayerPathFrom(e,t))}async function resolveNuxtAppRun(e){const{appRoot:t,warning:n}=await resolveAppRoot(e),r=lb.resolve(t)===lb.resolve(e.projectRoot),s=await nuxtAppStartFor(t,e.tempoRoot);return{appRoot:t,appDir:r?null:toPosixRelativePath(e.projectRoot,t),appLayerPath:nuxtAppLayerPathFrom(t,e.tempoRoot),start:s,projectRootStart:r?s:await nuxtAppStartFor(e.projectRoot,e.tempoRoot),appRootWarning:n}}function nuxtAppStartExtendsAppLayer(e){return new RegExp(`--extends(?:\\s+|=)\\S*${HT}\\b`).test(e)}function toCssRelativePath(e,t){const n=toPosixRelativePath(e,t);return"."===n||n.startsWith(".")?n:`./${n}`}function toRelativeAllowPath(e){const t=lb.relative(e.tempoRoot,e.projectRoot);return""===t?".":t.replace(/\\/g,"/")}function buildViteConfigFile(e,t,n,r){const s=`\n server: {\n fs: {\n allow: [${JSON.stringify(toRelativeAllowPath(e))}],\n },\n },`,i=hostRuntimeDedupeLiteral(n),o=`\n resolve: {\n dedupe: ${i},\n },`,a=ST[n],c=a.marker?`${a.marker}\n`:"",l=a.imports,d=a.pluginCalls(toPosixRelativePath(e.tempoRoot,r)),u=a.reactPluginCall,p=a.tsconfigPathsOptions,m=a.prebundle.map(e=>`\n ${JSON.stringify(e)},`).join(""),f=`\n optimizeDeps: {\n // The generated host imports only canvases requested by the user. Keep\n // unused canvases and their dependencies off the cold-start path.\n entries: ["index.html"],\n include: [\n "react",\n "react-dom",\n "react-dom/client",\n "react/jsx-runtime",\n "react/jsx-dev-runtime",${m}\n ],\n },`;return 3===t.tailwindMajor?`${c}${dT}import path from "node:path";\nimport { fileURLToPath } from "node:url";\nimport tailwindcss from "tailwindcss";\nimport autoprefixer from "autoprefixer";\nimport react from "@vitejs/plugin-react";\n${l}import { tempoVitePlugin } from "tempo-sdk";\nimport { defineConfig } from "vite";\nimport tsconfigPaths from "vite-tsconfig-paths";\n\nconst tempoRoot = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(tempoRoot, ${JSON.stringify(toRelativeAllowPath(e))});\n\nexport default defineConfig({\n root: tempoRoot,${o}\n css: {\n postcss: {\n plugins: [tempoHostStyles(), tailwindcss(), autoprefixer()],\n },\n },\n plugins: [\n tempoVitePlugin({ sourceIdentityRoot: projectRoot }),\n${d}${u} tsconfigPaths({\n projectDiscovery: "lazy",\n${p} }),\n ],${s}${f}\n});\n`:`${c}${dT}import path from "node:path";\nimport { fileURLToPath } from "node:url";\nimport tailwindcss from "@tailwindcss/vite";\nimport react from "@vitejs/plugin-react";\n${l}import { tempoVitePlugin } from "tempo-sdk";\nimport { defineConfig } from "vite";\nimport tsconfigPaths from "vite-tsconfig-paths";\n\nconst tempoRoot = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(tempoRoot, ${JSON.stringify(toRelativeAllowPath(e))});\n\nexport default defineConfig({\n root: tempoRoot,${o}\n plugins: [\n tempoHostStyles.vite(),\n tailwindcss(),\n tempoVitePlugin({ sourceIdentityRoot: projectRoot }),\n${d}${u} tsconfigPaths({\n projectDiscovery: "lazy",\n${p} }),\n ],${s}${f}\n});\n`}function parsePackageJson(e,t){let n;try{n=JSON.parse(t)}catch(t){throw new qm(e,t instanceof Error?t.message:String(t))}if(!n||"object"!=typeof n||Array.isArray(n))throw new qm(e,"expected top-level object");return n}function toStringRecord(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t={};for(const[n,r]of Object.entries(e))"string"==typeof r&&r.length>0&&(t[n]=r);return t}function sortObjectKeys(e){return Object.fromEntries(Object.entries(e).sort((e,t)=>e[0].localeCompare(t[0])))}function sanitizePackageName(e){const t=e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"tempo-project"}var zk={packages:[],previews:[],warnings:[],flutterOnly:!1};async function setUpFlutterApp(e,t={}){const n=t.env??process.env,r=my.resolve(e.projectRoot),s=await findFlutterPackages(r);if(!s.length)return zk;const i=[],o=[];for(const t of s){const n=t.dir,r=await discoverPreviews(n,t.packageName);r.previews.length||i.push(noPreviewsWarning(t.relativeDir)),r.skipped.length&&i.push(skippedPreviewsWarning(r.skipped));for(const e of await findNativeOnlyImports(n,t.packageName,r.previews.map(e=>e.libraryFile))){const{problem:n,fix:r}=describeNativeOnlyImport(e);i.push(`${t.relativeDir}: ${n} ${r}`)}o.push(...r.previews.map(t=>({...t,file:my.join(n,t.file),key:flutterPreviewKey(e.tempoRoot,my.join(n,t.file),t.name)})))}return i.push(...await flutterSdkWarnings([...s.map(e=>e.dir),r],n)),{packages:s.map(e=>({dir:e.dir,name:e.packageName})),previews:o,warnings:i,flutterOnly:s.some(e=>"."===e.relativeDir)||!await isFile(my.join(r,"package.json"))}}function noPreviewsWarning(e){return`Tempo found no @Preview functions in ${e}/lib. A FlutterStoryboard renders one top-level, public function with no required parameters that returns a Widget and is annotated with @Preview from package:flutter/widget_previews.dart. Add one (for example in lib/previews.dart), then name it in a canvas as preview="../../lib/previews.dart#<function>".`}var Gk={private:"private: drop the leading underscore","not-top-level":"not top-level: move it out of its class","required-parameters":"it has required parameters: give each a default, or wrap the call in a function without parameters","unsupported-declaration":"not a function returning Widget or WidgetBuilder","part-file":"its part file names its library in a way Tempo cannot follow: use part of '<file>.dart'"};function describeSkippedPreviewReason(e){return Gk[e]}function skippedPreviewsWarning(e){const t=e.map(e=>`${e.file}:${e.line} ${e.name??"(unnamed)"} (${describeSkippedPreviewReason(e.reason)})`).join("; ");return`Tempo cannot render these @Preview functions: ${t}.`}var Vk=10;function describeNativeOnlyImport(e){const t=e.chain[e.chain.length-1],n=e.chain.slice(1,-1),r=1===e.chain.length?"":`, reached from the preview library ${e.chain[0]}${n.length>0?` through ${n.join(", ")}`:""}`,s=`${t} imports ${e.library}${r}.`,i="or put the native code behind a conditional import whose web branch is a stub (import 'storage_stub.dart' if (dart.library.io) 'storage_io.dart')";if("build-fails"===e.effect)return{problem:`${s} ${e.library} does not compile for the web, which the canvas runs, and the canvas host imports every preview library, so the Flutter build fails and every Flutter board shows flutter_run_failed.`,fix:`Keep the previews off that import: preview a widget whose imports stay web-safe, ${i}.`};const o=e.previewLibraries.slice(0,Vk),a=e.previewLibraries.length-o.length;return{problem:`${s} ${e.library} compiles for the web, which the canvas runs, but its calls throw UnsupportedError there, so a board whose widget calls it while building shows an error box instead of the widget. Preview libraries that reach it: ${o.join(", ")}${a>0?`, and ${a} more`:""}.`,fix:`Give those widgets fake data instead of the native service, ${i}.`}}async function flutterSdkWarnings(e,t){const n=await readFvmPin(e);let r;try{r=await locateFlutterBinary(t,e)}catch(e){return e&&"object"==typeof e&&"code"in e&&"flutter_sdk_conflict"===e.code?[String(e)]:[missingSdkWarning(t,n)]}const s=[],i=n?unusedPinWarning(n,r):null;i&&s.push(i);const o=await readFlutterSdkVersion(r.path),a=o?sdkVersionWarning(o,r.path):null;return a&&s.push(a),s}async function readFvmPin(e){for(const t of new Set(e)){const e=await readFvmVersion(my.join(t,".fvmrc"),"flutter")??await readFvmVersion(my.join(t,".fvm","fvm_config.json"),"flutterSdkVersion");if(null===e)continue;const n="win32"===process.platform?"flutter.bat":"flutter",r=my.join(t,".fvm","flutter_sdk","bin",n);return{dir:t,version:e,binary:r}}return null}function missingSdkWarning(e,t){const n=e.TEMPO_FLUTTER_BIN?.trim();return n?`TEMPO_FLUTTER_BIN is set to ${n}, which is not an executable file. Point it at the flutter executable (…/flutter/bin/flutter), then restart Tempo; until then Flutter boards show flutter_sdk_missing.`:t?`This project pins Flutter ${t.version} with FVM, but the pinned SDK is not installed (${t.binary} is missing). Run \`fvm use ${t.version}\` in ${t.dir}, which installs the SDK and links it at .fvm/flutter_sdk; Tempo then runs it. Until then Flutter boards show flutter_sdk_missing.`:"Flutter boards need the Flutter SDK, but `flutter` is not on PATH and TEMPO_FLUTTER_BIN is not set. Install Flutter (https://docs.flutter.dev/get-started/install) and put flutter on the PATH of the shell Tempo starts from, or set TEMPO_FLUTTER_BIN to the flutter executable, then restart Tempo; until then Flutter boards show flutter_sdk_missing."}function unusedPinWarning(e,t){return"fvm"===t.source?null:"TEMPO_FLUTTER_BIN"===t.source?my.resolve(t.path)===my.resolve(e.binary)?null:`This project pins Flutter ${e.version} with FVM, but TEMPO_FLUTTER_BIN (${t.path}) overrides the pin, so Flutter boards build with that SDK. Unset TEMPO_FLUTTER_BIN to build with the pinned SDK, then restart Tempo.`:`This project pins Flutter ${e.version} with FVM, but the pinned SDK is not installed (${e.binary} is missing), so Flutter boards build with ${t.path}, which may be another version. Run \`fvm use ${e.version}\` in ${e.dir}, which installs the SDK and links it at .fvm/flutter_sdk; Tempo then runs it.`}var Kk={major:3,minor:35},Xk={major:3,minor:39};function sdkVersionWarning(e,t){const n=/^(\d+)\.(\d+)/.exec(e);if(!n)return null;const r=Number(n[1]),s=Number(n[2]),isBelow=e=>r<e.major||r===e.major&&s<e.minor;return isBelow(Kk)?`Tempo will run Flutter ${e} (${t}), but Flutter boards need Flutter 3.35 or newer: @Preview comes from package:flutter/widget_previews.dart. Upgrade to the latest stable release (Tempo is tested on 3.47); until then the Flutter host fails to build and boards show flutter_run_failed.`:isBelow(Xk)?`Tempo will run Flutter ${e} (${t}). Boards render, but Flutter 3.38 and older cannot hot-reload a page on the canvas, so Dart saves do not show until Flutter restarts. Upgrade to the latest stable release (Tempo is tested on 3.47).`:null}async function readFvmVersion(e,t){try{const n=JSON.parse(await uy(e,"utf-8"));if(null===n||"object"!=typeof n)return null;const r=n[t];return"string"==typeof r&&r.trim()?r.trim():null}catch{return null}}var Yk=24,Jk={width:400,height:300},Qk=40,Zk=1640;async function seedFlutterHomeCanvas(e,t){const n=await resolveFreeformCanvasesDir(e.pagesDir),r=my.join(n,"home","index.canvas.tsx");let s=null;try{s=await uy(r,"utf-8")}catch{s=null}if(null!==s&&s!==UT)return!1;const i="the project packages";return await dy(my.dirname(r),{recursive:!0}),await hy(r,buildFlutterHomeCanvas(t.previews.map(t=>({...t,key:flutterPreviewForCanvas(t.key,r,e.tempoRoot)})),i),"utf-8"),!0}function buildFlutterHomeCanvas(e,t){const n=e.slice(0,Yk),r=new Set,s=[];let i=0,o=0,a=0;for(const e of n){const t=e.size??Jk,n=Math.round(t.width),c=Math.round(t.height);i>0&&i+n>Zk&&(i=0,o+=a+Qk,a=0);const l=uniqueBoardId(e.name,r);s.push([" <FlutterStoryboard",` id=${JSON.stringify(l)}`,` name=${JSON.stringify(e.label??e.name)}`,` preview=${JSON.stringify(e.key)}`,` layout={{ x: ${i}, y: ${o}, width: ${n}, height: ${c} }}`," />"].join("\n")),i+=n+Qk,a=Math.max(a,c)}const c=e.length-n.length,l=0===n.length?[`// No @Preview functions were found in ${t}/lib when this canvas was`,"// created. Add a top-level, public function with no required parameters,","// annotated with @Preview from package:flutter/widget_previews.dart, then",'// add <FlutterStoryboard preview="../../lib/<file>.dart#<function>" .../> here.']:["// The Flutter app's previews: one FlutterStoryboard per @Preview function in",`// ${t}/lib, each sized by its @Preview(size: ...) when it states one.`,...c>0?[`// ${c} more previews were found; add them as FlutterStoryboards`,"// here or on other canvases."]:[]];return["// @tempo-home — Tempo home canvas (the workspace Run button opens this). Managed marker; do not remove.","//",...l,"",'import { Canvas, FlutterStoryboard } from "tempo-sdk/canvas";',"","export default function HomeCanvas() {"," return (",...0===s.length?[' <Canvas name="Home" />']:[' <Canvas name="Home">',...s," </Canvas>"]," );","}",""].join("\n")}function uniqueBoardId(e,t){const n=e.charAt(0).toUpperCase()+e.slice(1);let r=n;for(let e=2;t.has(r);e+=1)r=`${n}${e}`;return t.add(r),r}async function isFile(e){try{return(await py(e)).isFile()}catch{return!1}}import eS from"path";import{access as tS}from"fs/promises";import nS from"fs/promises";import rS from"path";var sS=C(Od(),1),iS=C(Rd(),1),oS=C(Fd(),1),aS=C(Fd(),1);import{Buffer as cS}from"buffer";import{spawn as lS}from"child_process";import{normalize as dS}from"path";import{EventEmitter as uS}from"events";var pS=Object.defineProperty,hS=Object.getOwnPropertyDescriptor,mS=Object.getOwnPropertyNames,fS=Object.prototype.hasOwnProperty,__esm2=(e,t)=>function __init(){return e&&(t=(0,e[mS(e)[0]])(e=0)),t},__commonJS2=(e,t)=>function __require2(){return t||(0,e[mS(e)[0]])((t={exports:{}}).exports,t),t.exports},__export2=(e,t)=>{for(var n in t)pS(e,n,{get:t[n],enumerable:!0})},__copyProps=(e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of mS(t))fS.call(e,s)||s===n||pS(e,s,{get:()=>t[s],enumerable:!(r=hS(t,s))||r.enumerable});return e},__toCommonJS2=e=>__copyProps(pS({},"__esModule",{value:!0}),e),gS;function pathspec(...e){const t=new String(e);return gS.set(t,e),t}function isPathSpec(e){return e instanceof String&&gS.has(e)}function toPaths(e){return gS.get(e)||[]}var yS=__esm2({"src/lib/args/pathspec.ts"(){gS=new WeakMap}}),bS,vS=__esm2({"src/lib/errors/git-error.ts"(){bS=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),wS,_S=__esm2({"src/lib/errors/git-response-error.ts"(){vS(),wS=class extends bS{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),xS,TS=__esm2({"src/lib/errors/task-configuration-error.ts"(){vS(),xS=class extends bS{constructor(e){super(void 0,e)}}}}),kS,SS,ES;function asFunction(e){return"function"!=typeof e?SS:e}function isUserFunction(e){return"function"==typeof e&&e!==SS}function splitOn(e,t){const n=e.indexOf(t);return n<=0?[e,""]:[e.substr(0,n),e.substr(n+1)]}function first2(e,t=0){return isArrayLike(e)&&e.length>t?e[t]:void 0}function last2(e,t=0){if(isArrayLike(e)&&e.length>t)return e[e.length-1-t]}function isArrayLike(e){return RS(e)}function toLinesWithContent(e="",t=!0,n="\n"){return e.split(n).reduce((e,n)=>{const r=t?n.trim():n;return r&&e.push(r),e},[])}function forEachLineWithContent(e,t){return toLinesWithContent(e,!0).map(e=>t(e))}function folderExists(e){return(0,sS.exists)(e,sS.FOLDER)}function append(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function including(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function remove(e,t){if(Array.isArray(e)){const n=e.indexOf(t);n>=0&&e.splice(n,1)}else e.delete(t);return t}function asArray2(e){return Array.isArray(e)?e:[e]}function asCamelCase(e){return e.replace(/[\s-]+(.)/g,(e,t)=>t.toUpperCase())}function asStringArray(e){return asArray2(e).map(e=>e instanceof String?e:String(e))}function asNumber(e,t=0){if(null==e)return t;const n=parseInt(e,10);return Number.isNaN(n)?t:n}function prefixedArray(e,t){const n=[];for(let r=0,s=e.length;r<s;r++)n.push(t,e[r]);return n}function bufferToString(e){return(Array.isArray(e)?cS.concat(e):e).toString("utf-8")}function pick(e,t){const n={};return t.forEach(t=>{void 0!==e[t]&&(n[t]=e[t])}),n}function delay2(e=0){return new Promise(t=>setTimeout(t,e))}function orVoid(e){if(!1!==e)return e}var AS=__esm2({"src/lib/utils/util.ts"(){NS(),kS="\0",SS=()=>{},ES=Object.prototype.toString.call.bind(Object.prototype.toString)}}),CS,IS,PS,DS,RS;function filterType(e,t,n){return t(e)?e:arguments.length>2?n:void 0}function filterPrimitives(e,t){const n=isPathSpec(e)?"string":typeof e;return/number|string|boolean/.test(n)&&(!t||!t.includes(n))}function filterPlainObject(e){return!!e&&"[object Object]"===ES(e)}function filterFunction(e){return"function"==typeof e}var NS=__esm2({"src/lib/utils/argument-filters.ts"(){yS(),AS(),CS=e=>Array.isArray(e),IS=e=>"number"==typeof e,PS=e=>"string"==typeof e,DS=e=>PS(e)||Array.isArray(e)&&e.every(PS),RS=e=>null!=e&&!"number|boolean|function".includes(typeof e)&&"number"==typeof e.length}}),OS,FS=__esm2({"src/lib/utils/exit-codes.ts"(){OS=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.ERROR=1]="ERROR",e[e.NOT_FOUND=-2]="NOT_FOUND",e[e.UNCLEAN=128]="UNCLEAN",e))(OS||{})}}),LS,MS=__esm2({"src/lib/utils/git-output-streams.ts"(){LS=class _GitOutputStreams{constructor(e,t){this.stdOut=e,this.stdErr=t}asStrings(){return new _GitOutputStreams(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}}),US,jS;function useMatchesDefault(){throw new Error("LineParser:useMatches not implemented")}var BS=__esm2({"src/lib/utils/line-parser.ts"(){US=class{constructor(e,t){this.matches=[],this.useMatches=useMatchesDefault,this.parse=(e,t)=>(this.resetMatches(),!!this._regExp.every((t,n)=>this.addMatch(t,n,e(n)))&&!1!==this.useMatches(t,this.prepareMatches())),this._regExp=Array.isArray(e)?e:[e],t&&(this.useMatches=t)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(e,t,n){const r=n&&e.exec(n);return r&&this.pushMatch(t,r),!!r}pushMatch(e,t){this.matches.push(...t.slice(1))}},jS=class extends US{addMatch(e,t,n){return/^remote:\s/.test(String(n))&&super.addMatch(e,t,n)}pushMatch(e,t){(e>0||t.length>1)&&super.pushMatch(e,t)}}}}),$S;function createInstanceConfig(...e){const t=process.cwd(),n=Object.assign({baseDir:t,...$S},...e.filter(e=>"object"==typeof e&&e));return n.baseDir=n.baseDir||t,n.trimmed=!0===n.trimmed,n}var WS=__esm2({"src/lib/utils/simple-git-options.ts"(){$S={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function appendTaskOptions(e,t=[]){return filterPlainObject(e)?Object.keys(e).reduce((t,n)=>{const r=e[n];if(isPathSpec(r))t.push(r);else if(filterPrimitives(r,["boolean"]))t.push(n+"="+r);else if(Array.isArray(r))for(const e of r)filterPrimitives(e,["string","number"])||t.push(n+"="+e);else t.push(n);return t},t):t}function getTrailingOptions(e,t=0,n=!1){const r=[];for(let n=0,s=t<0?e.length:t;n<s;n++)"string|number".includes(typeof e[n])&&r.push(String(e[n]));return appendTaskOptions(trailingOptionsArgument(e),r),n||r.push(...trailingArrayArgument(e)),r}function trailingArrayArgument(e){const t="function"==typeof last2(e);return asStringArray(filterType(last2(e,t?1:0),CS,[]))}function trailingOptionsArgument(e){const t=filterFunction(last2(e));return filterType(last2(e,t?1:0),filterPlainObject)}function trailingFunctionArgument(e,t=!0){const n=asFunction(last2(e));return t||isUserFunction(n)?n:void 0}var HS=__esm2({"src/lib/utils/task-options.ts"(){NS(),AS(),yS()}});function callTaskParser(e,t){return e(t.stdOut,t.stdErr)}function parseStringResponse(e,t,n,r=!0){return asArray2(n).forEach(n=>{for(let s=toLinesWithContent(n,r),i=0,o=s.length;i<o;i++){const line=(e=0)=>{if(!(i+e>=o))return s[i+e]};t.some(({parse:t})=>t(line,e))}}),e}var qS=__esm2({"src/lib/utils/task-parser.ts"(){AS()}}),zS={};__export2(zS,{ExitCodes:()=>OS,GitOutputStreams:()=>LS,LineParser:()=>US,NOOP:()=>SS,NULL:()=>kS,RemoteLineParser:()=>jS,append:()=>append,appendTaskOptions:()=>appendTaskOptions,asArray:()=>asArray2,asCamelCase:()=>asCamelCase,asFunction:()=>asFunction,asNumber:()=>asNumber,asStringArray:()=>asStringArray,bufferToString:()=>bufferToString,callTaskParser:()=>callTaskParser,createInstanceConfig:()=>createInstanceConfig,delay:()=>delay2,filterArray:()=>CS,filterFunction:()=>filterFunction,filterHasLength:()=>RS,filterNumber:()=>IS,filterPlainObject:()=>filterPlainObject,filterPrimitives:()=>filterPrimitives,filterString:()=>PS,filterStringOrStringArray:()=>DS,filterType:()=>filterType,first:()=>first2,folderExists:()=>folderExists,forEachLineWithContent:()=>forEachLineWithContent,getTrailingOptions:()=>getTrailingOptions,including:()=>including,isUserFunction:()=>isUserFunction,last:()=>last2,objectToString:()=>ES,orVoid:()=>orVoid,parseStringResponse:()=>parseStringResponse,pick:()=>pick,prefixedArray:()=>prefixedArray,remove:()=>remove,splitOn:()=>splitOn,toLinesWithContent:()=>toLinesWithContent,trailingFunctionArgument:()=>trailingFunctionArgument,trailingOptionsArgument:()=>trailingOptionsArgument});var GS=__esm2({"src/lib/utils/index.ts"(){NS(),FS(),MS(),BS(),WS(),HS(),qS(),AS()}}),VS={},KS,XS,YS;function checkIsRepoTask(e){switch(e){case"bare":return checkIsBareRepoTask();case"root":return checkIsRepoRootTask()}const t=["rev-parse","--is-inside-work-tree"];return{commands:t,format:"utf-8",onError:XS,parser:YS}}function checkIsRepoRootTask(){const e=["rev-parse","--git-dir"];return{commands:e,format:"utf-8",onError:XS,parser:e=>/^\.(git)?$/.test(e.trim())}}function checkIsBareRepoTask(){const e=["rev-parse","--is-bare-repository"];return{commands:e,format:"utf-8",onError:XS,parser:YS}}function isNotRepoMessage(e){return/(Not a git repository|Kein Git-Repository)/i.test(String(e))}__export2(VS,{CheckRepoActions:()=>KS,checkIsBareRepoTask:()=>checkIsBareRepoTask,checkIsRepoRootTask:()=>checkIsRepoRootTask,checkIsRepoTask:()=>checkIsRepoTask});var JS=__esm2({"src/lib/tasks/check-is-repo.ts"(){GS(),KS=(e=>(e.BARE="bare",e.IN_TREE="tree",e.IS_REPO_ROOT="root",e))(KS||{}),XS=({exitCode:e},t,n,r)=>{if(128===e&&isNotRepoMessage(t))return n(Buffer.from("false"));r(t)},YS=e=>"true"===e.trim()}}),QS,ZS,eE,tE;function cleanSummaryParser(e,t){const n=new QS(e),r=e?eE:ZS;return toLinesWithContent(t).forEach(e=>{const t=e.replace(r,"");n.paths.push(t),(tE.test(t)?n.folders:n.files).push(t)}),n}var nE=__esm2({"src/lib/responses/CleanSummary.ts"(){GS(),QS=class{constructor(e){this.dryRun=e,this.paths=[],this.files=[],this.folders=[]}},ZS=/^[a-z]+\s*/i,eE=/^[a-z]+\s+[a-z]+\s*/i,tE=/\/$/}}),rE={},sE;function adhocExecTask(e){return{commands:sE,format:"empty",parser:e}}function configurationErrorTask(e){return{commands:sE,format:"empty",parser(){throw"string"==typeof e?new xS(e):e}}}function straightThroughStringTask(e,t=!1){return{commands:e,format:"utf-8",parser:e=>t?String(e).trim():e}}function straightThroughBufferTask(e){return{commands:e,format:"buffer",parser:e=>e}}function isBufferTask(e){return"buffer"===e.format}function isEmptyTask(e){return"empty"===e.format||!e.commands.length}__export2(rE,{EMPTY_COMMANDS:()=>sE,adhocExecTask:()=>adhocExecTask,configurationErrorTask:()=>configurationErrorTask,isBufferTask:()=>isBufferTask,isEmptyTask:()=>isEmptyTask,straightThroughBufferTask:()=>straightThroughBufferTask,straightThroughStringTask:()=>straightThroughStringTask});var iE=__esm2({"src/lib/tasks/task.ts"(){TS(),sE=[]}}),oE={},aE,cE,lE,dE,uE;function cleanWithOptionsTask(e,t){const{cleanMode:n,options:r,valid:s}=getCleanOptions(e);return n?s.options?(r.push(...t),r.some(isInteractiveMode)?configurationErrorTask(aE):cleanTask(n,r)):configurationErrorTask(lE+JSON.stringify(e)):configurationErrorTask(cE)}function cleanTask(e,t){const n=["clean",`-${e}`,...t];return{commands:n,format:"utf-8",parser:t=>cleanSummaryParser("n"===e,t)}}function isCleanOptionsArray(e){return Array.isArray(e)&&e.every(e=>uE.has(e))}function getCleanOptions(e){let t,n=[],r={cleanMode:!1,options:!0};return e.replace(/[^a-z]i/g,"").split("").forEach(e=>{isCleanMode(e)?(t=e,r.cleanMode=!0):r.options=r.options&&isKnownOption(n[n.length]=`-${e}`)}),{cleanMode:t,options:n,valid:r}}function isCleanMode(e){return"f"===e||"n"===e}function isKnownOption(e){return/^-[a-z]$/i.test(e)&&uE.has(e.charAt(1))}function isInteractiveMode(e){return/^-[^\-]/.test(e)?e.indexOf("i")>0:"--interactive"===e}__export2(oE,{CONFIG_ERROR_INTERACTIVE_MODE:()=>aE,CONFIG_ERROR_MODE_REQUIRED:()=>cE,CONFIG_ERROR_UNKNOWN_OPTION:()=>lE,CleanOptions:()=>dE,cleanTask:()=>cleanTask,cleanWithOptionsTask:()=>cleanWithOptionsTask,isCleanOptionsArray:()=>isCleanOptionsArray});var pE=__esm2({"src/lib/tasks/clean.ts"(){nE(),GS(),iE(),aE="Git clean interactive mode is not supported",cE='Git clean mode parameter ("n" or "f") is required',lE="Git clean unknown option found in: ",dE=(e=>(e.DRY_RUN="n",e.FORCE="f",e.IGNORED_INCLUDED="x",e.IGNORED_ONLY="X",e.EXCLUDING="e",e.QUIET="q",e.RECURSIVE="d",e))(dE||{}),uE=new Set(["i",...asStringArray(Object.values(dE))])}}),hE;function configListParser(e){const t=new hE;for(const n of configParser(e))t.addValue(n.file,String(n.key),n.value);return t}function configGetParser(e,t){let n=null;const r=[],s=new Map;for(const i of configParser(e,t))i.key===t&&(r.push(n=i.value),s.has(i.file)||s.set(i.file,[]),s.get(i.file).push(n));return{key:t,paths:Array.from(s.keys()),scopes:s,value:n,values:r}}function configFilePath(e){return e.replace(/^(file):/,"")}function*configParser(e,t=null){const n=e.split("\0");for(let e=0,r=n.length-1;e<r;){const r=configFilePath(n[e++]);let s=n[e++],i=t;if(s.includes("\n")){const e=splitOn(s,"\n");i=e[0],s=e[1]}yield{file:r,key:i,value:s}}}var mE=__esm2({"src/lib/responses/ConfigList.ts"(){GS(),hE=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){return this._all||(this._all=this.files.reduce((e,t)=>Object.assign(e,this.values[t]),{})),this._all}addFile(e){if(!(e in this.values)){const t=last2(this.files);this.values[e]=t?Object.create(this.values[t]):{},this.files.push(e)}return this.values[e]}addValue(e,t,n){const r=this.addFile(e);Object.hasOwn(r,t)?Array.isArray(r[t])?r[t].push(n):r[t]=[r[t],n]:r[t]=n,this._all=void 0}}}}),fE;function asConfigScope(e,t){return"string"==typeof e&&Object.hasOwn(fE,e)?e:t}function addConfigTask(e,t,n,r){const s=["config",`--${r}`];return n&&s.push("--add"),s.push(e,t),{commands:s,format:"utf-8",parser:e=>e}}function getConfigTask(e,t){const n=["config","--null","--show-origin","--get-all",e];return t&&n.splice(1,0,`--${t}`),{commands:n,format:"utf-8",parser:t=>configGetParser(t,e)}}function listConfigTask(e){const t=["config","--list","--show-origin","--null"];return e&&t.push(`--${e}`),{commands:t,format:"utf-8",parser:e=>configListParser(e)}}function config_default(){return{addConfig(e,t,...n){return this._runTask(addConfigTask(e,t,!0===n[0],asConfigScope(n[1],"local")),trailingFunctionArgument(arguments))},getConfig(e,t){return this._runTask(getConfigTask(e,asConfigScope(t,void 0)),trailingFunctionArgument(arguments))},listConfig(...e){return this._runTask(listConfigTask(asConfigScope(e[0],void 0)),trailingFunctionArgument(arguments))}}}var gE=__esm2({"src/lib/tasks/config.ts"(){mE(),GS(),fE=(e=>(e.system="system",e.global="global",e.local="local",e.worktree="worktree",e))(fE||{})}}),yE,bE;function isDiffNameStatus(e){return bE.has(e)}var vE=__esm2({"src/lib/tasks/diff-name-status.ts"(){yE=(e=>(e.ADDED="A",e.COPIED="C",e.DELETED="D",e.MODIFIED="M",e.RENAMED="R",e.CHANGED="T",e.UNMERGED="U",e.UNKNOWN="X",e.BROKEN="B",e))(yE||{}),bE=new Set(Object.values(yE))}}),wE,_E,xE,TE;function grepQueryBuilder(...e){return(new TE).param(...e)}function parseGrep(e){const t=new Set,n={};return forEachLineWithContent(e,e=>{const[r,s,i]=e.split(kS);t.add(r),(n[r]=n[r]||[]).push({line:asNumber(s),path:r,preview:i})}),{paths:t,results:n}}function grep_default(){return{grep(e){const t=trailingFunctionArgument(arguments),n=getTrailingOptions(arguments);for(const e of wE)if(n.includes(e))return this._runTask(configurationErrorTask(`git.grep: use of "${e}" is not supported.`),t);"string"==typeof e&&(e=grepQueryBuilder().param(e));const r=["grep","--null","-n","--full-name",...n,...e];return this._runTask({commands:r,format:"utf-8",parser:e=>parseGrep(e)},t)}}}var kE=__esm2({"src/lib/tasks/grep.ts"(){GS(),iE(),wE=["-h"],_E=Symbol("grepQuery"),TE=class{constructor(){this[xE]=[]}*[(xE=_E,Symbol.iterator)](){for(const e of this[_E])yield e}and(...e){return e.length&&this[_E].push("--and","(",...prefixedArray(e,"-e"),")"),this}param(...e){return this[_E].push(...prefixedArray(e,"-e")),this}}}}),SE={},EE,AE;function resetTask(e,t){const n=["reset"];return isValidResetMode(e)&&n.push(`--${e}`),n.push(...t),straightThroughStringTask(n)}function getResetMode(e){if(isValidResetMode(e))return e;switch(typeof e){case"string":case"undefined":return"soft"}}function isValidResetMode(e){return"string"==typeof e&&AE.includes(e)}__export2(SE,{ResetMode:()=>EE,getResetMode:()=>getResetMode,resetTask:()=>resetTask});var CE=__esm2({"src/lib/tasks/reset.ts"(){GS(),iE(),EE=(e=>(e.MIXED="mixed",e.SOFT="soft",e.HARD="hard",e.MERGE="merge",e.KEEP="keep",e))(EE||{}),AE=asStringArray(Object.values(EE))}});function createLog(){return(0,iS.default)("simple-git")}function prefixedLogger(e,t,n){return t&&String(t).replace(/\s*/,"")?(r,...s)=>{e(`%s ${r}`,t,...s),n&&n(r,...s)}:n?(t,...r)=>{e(t,...r),n(t,...r)}:e}function childLoggerName(e,t,{namespace:n}){if("string"==typeof e)return e;const r=t&&t.namespace||"";return r.startsWith(n)?r.substr(n.length+1):r||n}function createLogger(e,t,n,r=createLog()){const s=e&&`[${e}]`||"",i=[],o="string"==typeof t?r.extend(t):t,a=childLoggerName(filterType(t,PS),o,r);return step(n);function sibling(t,n){return append(i,createLogger(e,a.replace(/^[^:]+/,t),n,r))}function step(t){const n=t&&`[${t}]`||"",i=o&&prefixedLogger(o,n)||SS,a=prefixedLogger(r,`${s} ${n}`,i);return Object.assign(o?i:a,{label:e,sibling,info:a,step})}}var IE=__esm2({"src/lib/git-logger.ts"(){GS(),iS.default.formatters.L=e=>String(RS(e)?e.length:"-"),iS.default.formatters.B=e=>Buffer.isBuffer(e)?e.toString("utf8"):ES(e)}}),PE,DE=__esm2({"src/lib/runners/tasks-pending-queue.ts"(){vS(),IE(),PE=class _TasksPendingQueue{constructor(e="GitExecutor"){this.logLabel=e,this._queue=new Map}withProgress(e){return this._queue.get(e)}createProgress(e){const t=_TasksPendingQueue.getName(e.commands[0]),n=createLogger(this.logLabel,t);return{task:e,logger:n,name:t}}push(e){const t=this.createProgress(e);return t.logger("Adding task to the queue, commands = %o",e.commands),this._queue.set(e,t),t}fatal(e){for(const[t,{logger:n}]of Array.from(this._queue.entries()))t===e.task?(n.info("Failed %o",e),n("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted")):n.info("A fatal exception occurred in a previous task, the queue has been purged: %o",e.message),this.complete(t);if(0!==this._queue.size)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(e){const t=this.withProgress(e);t&&this._queue.delete(e)}attempt(e){const t=this.withProgress(e);if(!t)throw new bS(void 0,"TasksPendingQueue: attempt called for an unknown task");return t.logger("Starting task"),t}static getName(e="empty"){return`task:${e}:${++_TasksPendingQueue.counter}`}static{this.counter=0}}}}),RE;function pluginContext(e,t){return{method:first2(e.commands)||"",commands:t}}function onErrorReceived(e,t){return n=>{t("[ERROR] child process exception %o",n),e.push(Buffer.from(String(n.stack),"ascii"))}}function onDataReceived(e,t,n,r){return s=>{n("%s received %L bytes",t,s),r("%B",s),e.push(s)}}var NE=__esm2({"src/lib/runners/git-executor-chain.ts"(){vS(),iE(),GS(),DE(),RE=class{constructor(e,t,n){this._executor=e,this._scheduler=t,this._plugins=n,this._chain=Promise.resolve(),this._queue=new PE}get cwd(){return this._cwd||this._executor.cwd}set cwd(e){this._cwd=e}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(e){return this._queue.push(e),this._chain=this._chain.then(()=>this.attemptTask(e))}async attemptTask(e){const t=await this._scheduler.next(),onQueueComplete=()=>this._queue.complete(e);try{const{logger:t}=this._queue.attempt(e);return await(isEmptyTask(e)?this.attemptEmptyTask(e,t):this.attemptRemoteTask(e,t))}catch(t){throw this.onFatalException(e,t)}finally{onQueueComplete(),t()}}onFatalException(e,t){const n=t instanceof bS?Object.assign(t,{task:e}):new bS(e,t&&String(t));return this._chain=Promise.resolve(),this._queue.fatal(n),n}async attemptRemoteTask(e,t){const n=this._plugins.exec("spawn.binary","",pluginContext(e,e.commands)),r=this._plugins.exec("spawn.args",[...e.commands],pluginContext(e,e.commands)),s=await this.gitResponse(e,n,r,this.outputHandler,t.step("SPAWN")),i=await this.handleTaskData(e,r,s,t.step("HANDLE"));return t("passing response to task's parser as a %s",e.format),isBufferTask(e)?callTaskParser(e.parser,i):callTaskParser(e.parser,i.asStrings())}async attemptEmptyTask(e,t){return t("empty task bypassing child process to call to task's parser"),e.parser(this)}handleTaskData(e,t,n,r){const{exitCode:s,rejection:i,stdOut:o,stdErr:a}=n;return new Promise((c,l)=>{r("Preparing to handle process response exitCode=%d stdOut=",s);const{error:d}=this._plugins.exec("task.error",{error:i},{...pluginContext(e,t),...n});return d&&e.onError?(r.info("exitCode=%s handling with custom error handler"),e.onError(n,d,e=>{r.info("custom error handler treated as success"),r("custom error returned a %s",ES(e)),c(new LS(Array.isArray(e)?Buffer.concat(e):e,Buffer.concat(a)))},l)):d?(r.info("handling as error: exitCode=%s stdErr=%s rejection=%o",s,a.length,i),l(d)):(r.info("retrieving task output complete"),void c(new LS(Buffer.concat(o),Buffer.concat(a))))})}async gitResponse(e,t,n,r,s){const i=s.sibling("output"),o=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},pluginContext(e,e.commands));return new Promise(a=>{const c=[],l=[];s.info("%s %o",t,n),s("%O",o);let d=this._beforeSpawn(e,n);if(d)return a({stdOut:c,stdErr:l,exitCode:9901,rejection:d});this._plugins.exec("spawn.before",void 0,{...pluginContext(e,n),kill(e){d=e||d}});const u=lS(t,n,o);u.stdout.on("data",onDataReceived(c,"stdOut",s,i.step("stdOut"))),u.stderr.on("data",onDataReceived(l,"stdErr",s,i.step("stdErr"))),u.on("error",onErrorReceived(l,s)),r&&(s("Passing child process stdOut/stdErr to custom outputHandler"),r(t,u.stdout,u.stderr,[...n])),this._plugins.exec("spawn.after",void 0,{...pluginContext(e,n),spawned:u,close(e,t){a({stdOut:c,stdErr:l,exitCode:e,rejection:d||t})},kill(e){u.killed||(d=e,u.kill("SIGINT"))}})})}_beforeSpawn(e,t){let n;return this._plugins.exec("spawn.before",void 0,{...pluginContext(e,t),kill(e){n=e||n}}),n}}}}),OE={},FE;__export2(OE,{GitExecutor:()=>FE});var LE=__esm2({"src/lib/runners/git-executor.ts"(){NE(),FE=class{constructor(e,t,n){this.cwd=e,this._scheduler=t,this._plugins=n,this._chain=new RE(this,this._scheduler,this._plugins)}chain(){return new RE(this,this._scheduler,this._plugins)}push(e){return this._chain.push(e)}}}});function taskCallback(e,t,n=SS){const onSuccess=e=>{n(null,e)},onError2=t=>{t?.task===e&&n(t instanceof wS?addDeprecationNoticeToError(t):t,void 0)};t.then(onSuccess,onError2)}function addDeprecationNoticeToError(e){let log=e=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${e} should be GitResponseError.git.${e}, this will no longer be available in version 3`),log=SS};return Object.create(e,Object.getOwnPropertyNames(e.git).reduce(descriptorReducer,{}));function descriptorReducer(t,n){return n in e||(t[n]={enumerable:!1,configurable:!1,get:()=>(log(n),e.git[n])}),t}}var ME=__esm2({"src/lib/task-callback.ts"(){_S(),GS()}});function changeWorkingDirectoryTask(e,t){return adhocExecTask(n=>{if(!folderExists(e))throw new Error(`Git.cwd: cannot change to non-directory "${e}"`);return(t||n).cwd=e})}var UE=__esm2({"src/lib/tasks/change-working-directory.ts"(){GS(),iE()}});function checkoutTask(e){const t=["checkout",...e];return"-b"===t[1]&&t.includes("-B")&&(t[1]=remove(t,"-B")),straightThroughStringTask(t)}function checkout_default(){return{checkout(){return this._runTask(checkoutTask(getTrailingOptions(arguments,1)),trailingFunctionArgument(arguments))},checkoutBranch(e,t){return this._runTask(checkoutTask(["-b",e,t,...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments))},checkoutLocalBranch(e){return this._runTask(checkoutTask(["-b",e,...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments))}}}var jE=__esm2({"src/lib/tasks/checkout.ts"(){GS(),iE()}}),BE;function countObjectsResponse(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function count_objects_default(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser:e=>parseStringResponse(countObjectsResponse(),[BE],e)})}}}var $E=__esm2({"src/lib/tasks/count-objects.ts"(){GS(),BE=new US(/([a-z-]+): (\d+)$/,(e,[t,n])=>{const r=asCamelCase(t);Object.hasOwn(e,r)&&(e[r]=asNumber(n))})}}),WE;function parseCommitResult(e){const t={author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}};return parseStringResponse(t,WE,e)}var HE=__esm2({"src/lib/parsers/parse-commit.ts"(){GS(),WE=[new US(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(e,[t,n,r])=>{e.branch=t,e.commit=r,e.root=!!n}),new US(/\s*Author:\s(.+)/i,(e,[t])=>{const n=t.split("<"),r=n.pop();r&&r.includes("@")&&(e.author={email:r.substr(0,r.length-1),name:n.join("<").trim()})}),new US(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0,e.summary.insertions=parseInt(n,10)||0,e.summary.deletions=parseInt(r,10)||0}),new US(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0;const s=parseInt(n,10)||0;"-"===r?e.summary.deletions=s:"+"===r&&(e.summary.insertions=s)})]}});function commitTask(e,t,n){const r=["-c","core.abbrev=40","commit",...prefixedArray(e,"-m"),...t,...n];return{commands:r,format:"utf-8",parser:parseCommitResult}}function commit_default(){return{commit(e,...t){const n=trailingFunctionArgument(arguments),r=rejectDeprecatedSignatures(e)||commitTask(asArray2(e),asArray2(filterType(t[0],DS,[])),[...asStringArray(filterType(t[1],CS,[])),...getTrailingOptions(arguments,0,!0)]);return this._runTask(r,n)}};function rejectDeprecatedSignatures(e){return!DS(e)&&configurationErrorTask("git.commit: requires the commit message to be supplied as a string/string[]")}}var qE=__esm2({"src/lib/tasks/commit.ts"(){HE(),GS(),iE()}});function first_commit_default(){return{firstCommit(){return this._runTask(straightThroughStringTask(["rev-list","--max-parents=0","HEAD"],!0),trailingFunctionArgument(arguments))}}}var zE=__esm2({"src/lib/tasks/first-commit.ts"(){GS(),iE()}});function hashObjectTask(e,t){const n=["hash-object",e];return t&&n.push("-w"),straightThroughStringTask(n,!0)}var GE=__esm2({"src/lib/tasks/hash-object.ts"(){iE()}}),VE,KE,XE;function parseInit(e,t,n){const r=String(n).trim();let s;if(s=KE.exec(r))return new VE(e,t,!1,s[1]);if(s=XE.exec(r))return new VE(e,t,!0,s[1]);let i="";const o=r.split(" ");for(;o.length;){const e=o.shift();if("in"===e){i=o.join(" ");break}}return new VE(e,t,/^re/i.test(r),i)}var YE=__esm2({"src/lib/responses/InitSummary.ts"(){VE=class{constructor(e,t,n,r){this.bare=e,this.path=t,this.existing=n,this.gitDir=r}},KE=/^Init.+ repository in (.+)$/,XE=/^Rein.+ in (.+)$/}}),JE;function hasBareCommand(e){return e.includes(JE)}function initTask(e=!1,t,n){const r=["init",...n];return e&&!hasBareCommand(r)&&r.splice(1,0,JE),{commands:r,format:"utf-8",parser:e=>parseInit(r.includes("--bare"),t,e)}}var QE=__esm2({"src/lib/tasks/init.ts"(){YE(),JE="--bare"}}),ZE;function logFormatFromCommand(e){for(let t=0;t<e.length;t++){const n=ZE.exec(e[t]);if(n)return`--${n[1]}`}return""}function isLogFormat(e){return ZE.test(e)}var eA=__esm2({"src/lib/args/log-format.ts"(){ZE=/^--(stat|numstat|name-only|name-status)(=|$)/}}),tA,nA=__esm2({"src/lib/responses/DiffSummary.ts"(){tA=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}}),rA,sA,iA,oA,aA;function getDiffParser(e=""){const t=aA[e];return e=>parseStringResponse(new tA,t,e,!1)}var cA=__esm2({"src/lib/parsers/parse-diff-summary.ts"(){eA(),nA(),vE(),GS(),rA=[new US(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(e,[t,n,r=""])=>{e.files.push({file:t.trim(),changes:asNumber(n),insertions:r.replace(/[^+]/g,"").length,deletions:r.replace(/[^-]/g,"").length,binary:!1})}),new US(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(e,[t,n,r])=>{e.files.push({file:t.trim(),before:asNumber(n),after:asNumber(r),binary:!0})}),new US(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(e,[t,n])=>{const r=/(\d+) i/.exec(n),s=/(\d+) d/.exec(n);e.changed=asNumber(t),e.insertions=asNumber(r?.[1]),e.deletions=asNumber(s?.[1])})],sA=[new US(/(\d+)\t(\d+)\t(.+)$/,(e,[t,n,r])=>{const s=asNumber(t),i=asNumber(n);e.changed++,e.insertions+=s,e.deletions+=i,e.files.push({file:r,changes:s+i,insertions:s,deletions:i,binary:!1})}),new US(/-\t-\t(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,after:0,before:0,binary:!0})})],iA=[new US(/(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,changes:0,insertions:0,deletions:0,binary:!1})})],oA=[new US(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(e,[t,n,r,s,i])=>{e.changed++,e.files.push({file:i??r,changes:0,insertions:0,deletions:0,binary:!1,status:orVoid(isDiffNameStatus(t)&&t),from:orVoid(!!i&&r!==i&&r),similarity:asNumber(n)})})],aA={"":rA,"--stat":rA,"--numstat":sA,"--name-status":oA,"--name-only":iA}}}),lA,dA,uA,pA;function lineBuilder(e,t){return t.reduce((t,n,r)=>(t[n]=e[r]||"",t),Object.create({diff:null}))}function createListLogSummaryParser(e=uA,t=pA,n=""){const r=getDiffParser(n);return function(n){const s=toLinesWithContent(n.trim(),!1,lA).map(function(n){const s=n.split(dA),i=lineBuilder(s[0].split(e),t);return s.length>1&&s[1].trim()&&(i.diff=r(s[1])),i});return{all:s,latest:s.length&&s[0]||null,total:s.length}}}var hA=__esm2({"src/lib/parsers/parse-list-log-summary.ts"(){GS(),cA(),eA(),lA="òòòòòò ",dA=" òò",uA=" ò ",pA=["hash","date","message","refs","author_name","author_email"]}}),mA={};function diffSummaryTask(e){let t=logFormatFromCommand(e);const n=["diff"];return""===t&&(t="--stat",n.push("--stat=4096")),n.push(...e),validateLogFormatConfig(n)||{commands:n,format:"utf-8",parser:getDiffParser(t)}}function validateLogFormatConfig(e){const t=e.filter(isLogFormat);return t.length>1?configurationErrorTask(`Summary flags are mutually exclusive - pick one of ${t.join(",")}`):t.length&&e.includes("-z")?configurationErrorTask(`Summary flag ${t} parsing is not compatible with null termination option '-z'`):void 0}__export2(mA,{diffSummaryTask:()=>diffSummaryTask,validateLogFormatConfig:()=>validateLogFormatConfig});var fA=__esm2({"src/lib/tasks/diff.ts"(){eA(),cA(),iE()}}),gA;function prettyFormat(e,t){const n=[],r=[];return Object.keys(e).forEach(t=>{n.push(t),r.push(String(e[t]))}),[n,r.join(t)]}function userOptions(e){return Object.keys(e).reduce((t,n)=>(n in gA||(t[n]=e[n]),t),{})}function parseLogOptions(e={},t=[]){const n=filterType(e.splitter,PS,uA),r=filterPlainObject(e.format)?e.format:{hash:"%H",date:!1===e.strictDate?"%ai":"%aI",message:"%s",refs:"%D",body:e.multiLine?"%B":"%b",author_name:!1!==e.mailMap?"%aN":"%an",author_email:!1!==e.mailMap?"%aE":"%ae"},[s,i]=prettyFormat(r,n),o=[],a=[`--pretty=format:${lA}${i}${dA}`,...t],c=e.n||e["max-count"]||e.maxCount;if(c&&a.push(`--max-count=${c}`),e.from||e.to){const t=!1!==e.symmetric?"...":"..";o.push(`${e.from||""}${t}${e.to||""}`)}return PS(e.file)&&a.push("--follow",pathspec(e.file)),appendTaskOptions(userOptions(e),a),{fields:s,splitter:n,commands:[...a,...o]}}function logTask(e,t,n){const r=createListLogSummaryParser(e,t,logFormatFromCommand(n));return{commands:["log",...n],format:"utf-8",parser:r}}function log_default(){return{log(...e){const t=trailingFunctionArgument(arguments),n=parseLogOptions(trailingOptionsArgument(arguments),asStringArray(filterType(arguments[0],CS,[]))),r=rejectDeprecatedSignatures(...e)||validateLogFormatConfig(n.commands)||createLogTask(n);return this._runTask(r,t)}};function createLogTask(e){return logTask(e.splitter,e.fields,e.commands)}function rejectDeprecatedSignatures(e,t){return PS(e)&&PS(t)&&configurationErrorTask("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var yA=__esm2({"src/lib/tasks/log.ts"(){eA(),yS(),hA(),GS(),iE(),fA(),gA=(e=>(e[e["--pretty"]=0]="--pretty",e[e["max-count"]=1]="max-count",e[e.maxCount=2]="maxCount",e[e.n=3]="n",e[e.file=4]="file",e[e.format=5]="format",e[e.from=6]="from",e[e.to=7]="to",e[e.splitter=8]="splitter",e[e.symmetric=9]="symmetric",e[e.mailMap=10]="mailMap",e[e.multiLine=11]="multiLine",e[e.strictDate=12]="strictDate",e))(gA||{})}}),bA,vA,wA=__esm2({"src/lib/responses/MergeSummary.ts"(){bA=class{constructor(e,t=null,n){this.reason=e,this.file=t,this.meta=n}toString(){return`${this.file}:${this.reason}`}},vA=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(", ")}`:"OK"}}}}),_A,xA,TA=__esm2({"src/lib/responses/PullSummary.ts"(){_A=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},xA=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}}),kA;function objectEnumerationResult(e){return e.objects=e.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function asObjectCount(e){const t=/^\s*(\d+)/.exec(e),n=/delta (\d+)/i.exec(e);return{count:asNumber(t&&t[1]||"0"),delta:asNumber(n&&n[1]||"0")}}var SA=__esm2({"src/lib/parsers/parse-remote-objects.ts"(){GS(),kA=[new jS(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(e,[t,n])=>{const r=t.toLowerCase(),s=objectEnumerationResult(e.remoteMessages);Object.assign(s,{[r]:asNumber(n)})}),new jS(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(e,[t,n])=>{const r=t.toLowerCase(),s=objectEnumerationResult(e.remoteMessages);Object.assign(s,{[r]:asNumber(n)})}),new jS(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(e,[t,n,r])=>{const s=objectEnumerationResult(e.remoteMessages);s.total=asObjectCount(t),s.reused=asObjectCount(n),s.packReused=asNumber(r)})]}}),EA,AA;function parseRemoteMessages(e,t){return parseStringResponse({remoteMessages:new AA},EA,t)}var CA=__esm2({"src/lib/parsers/parse-remote-messages.ts"(){GS(),SA(),EA=[new jS(/^remote:\s*(.+)$/,(e,[t])=>(e.remoteMessages.all.push(t.trim()),!1)),...kA,new jS([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(e,[t])=>{e.remoteMessages.pullRequestUrl=t}),new jS([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(e,[t,n,r])=>{e.remoteMessages.vulnerabilities={count:asNumber(t),summary:n,url:r}})],AA=class{constructor(){this.all=[]}}}}),IA,PA,DA,RA,NA,OA,FA;function parsePullErrorResult(e,t){const n=parseStringResponse(new xA,NA,[e,t]);return n.message&&n}var LA=__esm2({"src/lib/parsers/parse-pull.ts"(){TA(),GS(),CA(),IA=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,PA=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,DA=/^(create|delete) mode \d+ (.+)/,RA=[new US(IA,(e,[t,n,r])=>{e.files.push(t),n&&(e.insertions[t]=n.length),r&&(e.deletions[t]=r.length)}),new US(PA,(e,[t,,n,,r])=>(void 0!==n||void 0!==r)&&(e.summary.changes=+t||0,e.summary.insertions=+n||0,e.summary.deletions=+r||0,!0)),new US(DA,(e,[t,n])=>{append(e.files,n),append("create"===t?e.created:e.deleted,n)})],NA=[new US(/^from\s(.+)$/i,(e,[t])=>{e.remote=t}),new US(/^fatal:\s(.+)$/,(e,[t])=>{e.message=t}),new US(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(e,[t,n,r,s])=>{e.branch.local=r,e.hash.local=t,e.branch.remote=s,e.hash.remote=n})],OA=(e,t)=>parseStringResponse(new _A,RA,[e,t]),FA=(e,t)=>Object.assign(new _A,OA(e,t),parseRemoteMessages(e,t))}}),MA,UA,jA,BA=__esm2({"src/lib/parsers/parse-merge.ts"(){wA(),GS(),LA(),MA=[new US(/^Auto-merging\s+(.+)$/,(e,[t])=>{e.merges.push(t)}),new US(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(e,[t,n])=>{e.conflicts.push(new bA(t,n))}),new US(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(e,[t,n,r])=>{e.conflicts.push(new bA(t,n,{deleteRef:r}))}),new US(/^CONFLICT\s+\((.+)\):/,(e,[t])=>{e.conflicts.push(new bA(t,null))}),new US(/^Automatic merge failed;\s+(.+)$/,(e,[t])=>{e.result=t})],UA=(e,t)=>Object.assign(jA(e,t),FA(e,t)),jA=e=>parseStringResponse(new vA,MA,e)}});function mergeTask(e){return e.length?{commands:["merge",...e],format:"utf-8",parser(e,t){const n=UA(e,t);if(n.failed)throw new wS(n);return n}}:configurationErrorTask("Git.merge requires at least one option")}var $A=__esm2({"src/lib/tasks/merge.ts"(){_S(),BA(),iE()}}),WA,HA,qA;function pushResultPushedItem(e,t,n){const r=n.includes("deleted"),s=n.includes("tag")||/^refs\/tags/.test(e),i=!n.includes("new");return{deleted:r,tag:s,branch:!s,new:!i,alreadyUpdated:i,local:e,remote:t}}var zA=__esm2({"src/lib/parsers/parse-push.ts"(){GS(),CA(),WA=[new US(/^Pushing to (.+)$/,(e,[t])=>{e.repo=t}),new US(/^updating local tracking ref '(.+)'/,(e,[t])=>{e.ref={...e.ref||{},local:t}}),new US(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(e,[t,n,r])=>{e.pushed.push(pushResultPushedItem(t,n,r))}),new US(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(e,[t,n,r])=>{e.branch={...e.branch||{},local:t,remote:n,remoteName:r}}),new US(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(e,[t,n,r,s])=>{e.update={head:{local:t,remote:n},hash:{from:r,to:s}}})],HA=(e,t)=>{const n=qA(e,t),r=parseRemoteMessages(e,t);return{...n,...r}},qA=(e,t)=>parseStringResponse({pushed:[]},WA,[e,t])}}),GA={};function pushTagsTask(e={},t){return append(t,"--tags"),pushTask(e,t)}function pushTask(e={},t){const n=["push",...t];return e.branch&&n.splice(1,0,e.branch),e.remote&&n.splice(1,0,e.remote),remove(n,"-v"),append(n,"--verbose"),append(n,"--porcelain"),{commands:n,format:"utf-8",parser:HA}}__export2(GA,{pushTagsTask:()=>pushTagsTask,pushTask:()=>pushTask});var VA=__esm2({"src/lib/tasks/push.ts"(){zA(),GS()}});function show_default(){return{showBuffer(){const e=["show",...getTrailingOptions(arguments,1)];return e.includes("--binary")||e.splice(1,0,"--binary"),this._runTask(straightThroughBufferTask(e),trailingFunctionArgument(arguments))},show(){const e=["show",...getTrailingOptions(arguments,1)];return this._runTask(straightThroughStringTask(e),trailingFunctionArgument(arguments))}}}var KA=__esm2({"src/lib/tasks/show.ts"(){GS(),iE()}}),XA,YA,JA=__esm2({"src/lib/responses/FileStatusSummary.ts"(){XA=/^(.+)\0(.+)$/,YA=class{constructor(e,t,n){if(this.path=e,this.index=t,this.working_dir=n,"R"===t||"R"===n){const t=XA.exec(e)||[null,e,e];this.from=t[2]||"",this.path=t[1]||""}}}}}),QA,ZA,eC;function renamedFile(e){const[t,n]=e.split(kS);return{from:n||t,to:t}}function parser3(e,t,n){return[`${e}${t}`,n]}function conflicts(e,...t){return t.map(t=>parser3(e,t,(e,t)=>e.conflicted.push(t)))}function splitLine(e,t){const n=t.trim();switch(" "){case n.charAt(2):return data(n.charAt(0),n.charAt(1),n.slice(3));case n.charAt(1):return data(" ",n.charAt(0),n.slice(2));default:return}function data(t,n,r){const s=`${t}${n}`,i=ZA.get(s);i&&i(e,r),"##"!==s&&"!!"!==s&&e.files.push(new YA(r,t,n))}}var tC=__esm2({"src/lib/responses/StatusSummary.ts"(){GS(),JA(),QA=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},ZA=new Map([parser3(" ","A",(e,t)=>e.created.push(t)),parser3(" ","D",(e,t)=>e.deleted.push(t)),parser3(" ","M",(e,t)=>e.modified.push(t)),parser3("A"," ",(e,t)=>{e.created.push(t),e.staged.push(t)}),parser3("A","M",(e,t)=>{e.created.push(t),e.staged.push(t),e.modified.push(t)}),parser3("D"," ",(e,t)=>{e.deleted.push(t),e.staged.push(t)}),parser3("M"," ",(e,t)=>{e.modified.push(t),e.staged.push(t)}),parser3("M","M",(e,t)=>{e.modified.push(t),e.staged.push(t)}),parser3("R"," ",(e,t)=>{e.renamed.push(renamedFile(t))}),parser3("R","M",(e,t)=>{const n=renamedFile(t);e.renamed.push(n),e.modified.push(n.to)}),parser3("!","!",(e,t)=>{(e.ignored=e.ignored||[]).push(t)}),parser3("?","?",(e,t)=>e.not_added.push(t)),...conflicts("A","A","U"),...conflicts("D","D","U"),...conflicts("U","A","D","U"),["##",(e,t)=>{const n=/ahead (\d+)/,r=/behind (\d+)/,s=/^(.+?(?=(?:\.{3}|\s|$)))/,i=/\.{3}(\S*)/,o=/\son\s(\S+?)(?=\.{3}|$)/;let a=n.exec(t);e.ahead=a&&+a[1]||0,a=r.exec(t),e.behind=a&&+a[1]||0,a=s.exec(t),e.current=filterType(a?.[1],PS,null),a=i.exec(t),e.tracking=filterType(a?.[1],PS,null),a=o.exec(t),a&&(e.current=filterType(a?.[1],PS,e.current)),e.detached=/\(no branch\)/.test(t)}]]),eC=function(e){const t=e.split(kS),n=new QA;for(let e=0,r=t.length;e<r;){let r=t[e++].trim();r&&("R"===r.charAt(0)&&(r+=kS+(t[e++]||"")),splitLine(n,r))}return n}}}),nC;function statusTask(e){const t=["status","--porcelain","-b","-u","--null",...e.filter(e=>!nC.includes(e))];return{format:"utf-8",commands:t,parser:e=>eC(e)}}var rC=__esm2({"src/lib/tasks/status.ts"(){tC(),nC=["--null","-z"]}}),sC,iC;function versionResponse(e=0,t=0,n=0,r="",s=!0){return Object.defineProperty({major:e,minor:t,patch:n,agent:r,installed:s},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function notInstalledResponse(){return versionResponse(0,0,0,"",!1)}function version_default(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:versionParser,onError(e,t,n,r){if(-2===e.exitCode)return n(Buffer.from(sC));r(t)}})}}}function versionParser(e){return e===sC?notInstalledResponse():parseStringResponse(versionResponse(0,0,0,e),iC,e)}var oC=__esm2({"src/lib/tasks/version.ts"(){GS(),sC="installed=false",iC=[new US(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(e,[t,n,r,s=""])=>{Object.assign(e,versionResponse(asNumber(t),asNumber(n),asNumber(r),s))}),new US(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(e,[t,n,r,s=""])=>{Object.assign(e,versionResponse(asNumber(t),asNumber(n),r,s))})]}}),aC={},cC;__export2(aC,{SimpleGitApi:()=>cC});var lC=__esm2({"src/lib/simple-git-api.ts"(){ME(),UE(),jE(),$E(),qE(),gE(),zE(),kE(),GE(),QE(),yA(),$A(),VA(),KA(),rC(),iE(),oC(),GS(),cC=class{constructor(e){this._executor=e}_runTask(e,t){const n=this._executor.chain(),r=n.push(e);return t&&taskCallback(e,r,t),Object.create(this,{then:{value:r.then.bind(r)},catch:{value:r.catch.bind(r)},_executor:{value:n}})}add(e){return this._runTask(straightThroughStringTask(["add",...asArray2(e)]),trailingFunctionArgument(arguments))}cwd(e){const t=trailingFunctionArgument(arguments);return"string"==typeof e?this._runTask(changeWorkingDirectoryTask(e,this._executor),t):"string"==typeof e?.path?this._runTask(changeWorkingDirectoryTask(e.path,e.root&&this._executor||void 0),t):this._runTask(configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"),t)}hashObject(e,t){return this._runTask(hashObjectTask(e,!0===t),trailingFunctionArgument(arguments))}init(e){return this._runTask(initTask(!0===e,this._executor.cwd,getTrailingOptions(arguments)),trailingFunctionArgument(arguments))}merge(){return this._runTask(mergeTask(getTrailingOptions(arguments)),trailingFunctionArgument(arguments))}mergeFromTo(e,t){return PS(e)&&PS(t)?this._runTask(mergeTask([e,t,...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments,!1)):this._runTask(configurationErrorTask("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"))}outputHandler(e){return this._executor.outputHandler=e,this}push(){const e=pushTask({remote:filterType(arguments[0],PS),branch:filterType(arguments[1],PS)},getTrailingOptions(arguments));return this._runTask(e,trailingFunctionArgument(arguments))}stash(){return this._runTask(straightThroughStringTask(["stash",...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments))}status(){return this._runTask(statusTask(getTrailingOptions(arguments)),trailingFunctionArgument(arguments))}},Object.assign(cC.prototype,checkout_default(),commit_default(),config_default(),count_objects_default(),first_commit_default(),grep_default(),log_default(),show_default(),version_default())}}),dC={},uC,pC;__export2(dC,{Scheduler:()=>pC});var hC=__esm2({"src/lib/runners/scheduler.ts"(){GS(),IE(),uC=(()=>{let e=0;return()=>{e++;const{promise:t,done:n}=(0,oS.createDeferred)();return{promise:t,done:n,id:e}}})(),pC=class{constructor(e=2){this.concurrency=e,this.logger=createLogger("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",e)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency)return void this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);const e=append(this.running,this.pending.shift());this.logger("Attempting id=%s",e.id),e.done(()=>{this.logger("Completing id=",e.id),remove(this.running,e),this.schedule()})}next(){const{promise:e,id:t}=append(this.pending,uC());return this.logger("Scheduling id=%s",t),this.schedule(),e}}}}),mC={};function applyPatchTask(e,t){return straightThroughStringTask(["apply",...t,...e])}__export2(mC,{applyPatchTask:()=>applyPatchTask});var fC=__esm2({"src/lib/tasks/apply-patch.ts"(){iE()}}),gC;function branchDeletionSuccess(e,t){return{branch:e,hash:t,success:!0}}function branchDeletionFailure(e){return{branch:e,hash:null,success:!1}}var yC=__esm2({"src/lib/responses/BranchDeleteSummary.ts"(){gC=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}}),bC,vC,wC,_C;function hasBranchDeletionError(e,t){return 1===t&&vC.test(e)}var xC=__esm2({"src/lib/parsers/parse-branch-delete.ts"(){yC(),GS(),bC=/(\S+)\s+\(\S+\s([^)]+)\)/,vC=/^error[^']+'([^']+)'/m,wC=[new US(bC,(e,[t,n])=>{const r=branchDeletionSuccess(t,n);e.all.push(r),e.branches[t]=r}),new US(vC,(e,[t])=>{const n=branchDeletionFailure(t);e.errors.push(n),e.all.push(n),e.branches[t]=n})],_C=(e,t)=>parseStringResponse(new gC,wC,[e,t])}}),TC,kC=__esm2({"src/lib/responses/BranchSummary.ts"(){TC=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(e,t,n,r,s){"*"===e&&(this.detached=t,this.current=n),this.all.push(n),this.branches[n]={current:"*"===e,linkedWorkTree:"+"===e,name:n,commit:r,label:s}}}}}),SC,EC;function branchStatus(e){return e?e.charAt(0):""}function parseBranchSummary(e,t=!1){return parseStringResponse(new TC,t?[EC]:SC,e)}var AC=__esm2({"src/lib/parsers/parse-branch.ts"(){kC(),GS(),SC=[new US(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(e,[t,n,r,s])=>{e.push(branchStatus(t),!0,n,r,s)}),new US(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(e,[t,n,r,s])=>{e.push(branchStatus(t),!1,n,r,s)})],EC=new US(/^(\S+)$/s,(e,[t])=>{e.push("*",!1,t,"","")})}}),CC={};function containsDeleteBranchCommand(e){const t=["-d","-D","--delete"];return e.some(e=>t.includes(e))}function branchTask(e){const t=containsDeleteBranchCommand(e),n=e.includes("--show-current"),r=["branch",...e];return 1===r.length&&r.push("-a"),r.includes("-v")||r.splice(1,0,"-v"),{format:"utf-8",commands:r,parser:(e,r)=>t?_C(e,r).all[0]:parseBranchSummary(e,n)}}function branchLocalTask(){return{format:"utf-8",commands:["branch","-v"],parser:e=>parseBranchSummary(e)}}function deleteBranchesTask(e,t=!1){return{format:"utf-8",commands:["branch","-v",t?"-D":"-d",...e],parser:(e,t)=>_C(e,t),onError({exitCode:e,stdOut:t},n,r,s){if(!hasBranchDeletionError(String(n),e))return s(n);r(t)}}}function deleteBranchTask(e,t=!1){const n={format:"utf-8",commands:["branch","-v",t?"-D":"-d",e],parser:(t,n)=>_C(t,n).branches[e],onError({exitCode:e,stdErr:t,stdOut:r},s,i,o){if(!hasBranchDeletionError(String(s),e))return o(s);throw new wS(n.parser(bufferToString(r),bufferToString(t)),String(s))}};return n}__export2(CC,{branchLocalTask:()=>branchLocalTask,branchTask:()=>branchTask,containsDeleteBranchCommand:()=>containsDeleteBranchCommand,deleteBranchTask:()=>deleteBranchTask,deleteBranchesTask:()=>deleteBranchesTask});var IC=__esm2({"src/lib/tasks/branch.ts"(){_S(),xC(),AC(),GS()}}),PC;function toPath3(e){const t=e.trim().replace(/^["']|["']$/g,"");return t&&dS(t)}var DC=__esm2({"src/lib/responses/CheckIgnore.ts"(){PC=e=>e.split(/\n/g).map(toPath3).filter(Boolean)}}),RC={};function checkIgnoreTask(e){return{commands:["check-ignore",...e],format:"utf-8",parser:PC}}__export2(RC,{checkIgnoreTask:()=>checkIgnoreTask});var NC=__esm2({"src/lib/tasks/check-ignore.ts"(){DC()}}),OC={};function disallowedCommand(e){return/^--upload-pack(=|$)/.test(e)}function cloneTask(e,t,n){const r=["clone",...n];PS(e)&&r.push(e),PS(t)&&r.push(t);const s=r.find(disallowedCommand);return s?configurationErrorTask("git.fetch: potential exploit argument blocked."):straightThroughStringTask(r)}function cloneMirrorTask(e,t,n){return append(n,"--mirror"),cloneTask(e,t,n)}__export2(OC,{cloneMirrorTask:()=>cloneMirrorTask,cloneTask:()=>cloneTask});var FC=__esm2({"src/lib/tasks/clone.ts"(){iE(),GS()}}),LC;function parseFetchResult(e,t){const n={raw:e,remote:null,branches:[],tags:[],updated:[],deleted:[]};return parseStringResponse(n,LC,[e,t])}var MC=__esm2({"src/lib/parsers/parse-fetch.ts"(){GS(),LC=[new US(/From (.+)$/,(e,[t])=>{e.remote=t}),new US(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.branches.push({name:t,tracking:n})}),new US(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.tags.push({name:t,tracking:n})}),new US(/- \[deleted]\s+\S+\s*-> (.+)$/,(e,[t])=>{e.deleted.push({tracking:t})}),new US(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(e,[t,n,r,s])=>{e.updated.push({name:r,tracking:s,to:n,from:t})})]}}),UC={};function disallowedCommand2(e){return/^--upload-pack(=|$)/.test(e)}function fetchTask(e,t,n){const r=["fetch",...n];e&&t&&r.push(e,t);const s=r.find(disallowedCommand2);return s?configurationErrorTask("git.fetch: potential exploit argument blocked."):{commands:r,format:"utf-8",parser:parseFetchResult}}__export2(UC,{fetchTask:()=>fetchTask});var jC=__esm2({"src/lib/tasks/fetch.ts"(){MC(),iE()}}),BC;function parseMoveResult(e){return parseStringResponse({moves:[]},BC,e)}var $C=__esm2({"src/lib/parsers/parse-move.ts"(){GS(),BC=[new US(/^Renaming (.+) to (.+)$/,(e,[t,n])=>{e.moves.push({from:t,to:n})})]}}),WC={};function moveTask(e,t){return{commands:["mv","-v",...asArray2(e),t],format:"utf-8",parser:parseMoveResult}}__export2(WC,{moveTask:()=>moveTask});var HC=__esm2({"src/lib/tasks/move.ts"(){$C(),GS()}}),qC={};function pullTask(e,t,n){const r=["pull",...n];return e&&t&&r.splice(1,0,e,t),{commands:r,format:"utf-8",parser:(e,t)=>FA(e,t),onError(e,t,n,r){const s=parsePullErrorResult(bufferToString(e.stdOut),bufferToString(e.stdErr));if(s)return r(new wS(s));r(t)}}}__export2(qC,{pullTask:()=>pullTask});var zC=__esm2({"src/lib/tasks/pull.ts"(){_S(),LA(),GS()}});function parseGetRemotes(e){const t={};return forEach(e,([e])=>t[e]={name:e}),Object.values(t)}function parseGetRemotesVerbose(e){const t={};return forEach(e,([e,n,r])=>{Object.hasOwn(t,e)||(t[e]={name:e,refs:{fetch:"",push:""}}),r&&n&&(t[e].refs[r.replace(/[^a-z]/g,"")]=n)}),Object.values(t)}function forEach(e,t){forEachLineWithContent(e,e=>t(e.split(/\s+/)))}var GC=__esm2({"src/lib/responses/GetRemoteSummary.ts"(){GS()}}),VC={};function addRemoteTask(e,t,n){return straightThroughStringTask(["remote","add",...n,e,t])}function getRemotesTask(e){const t=["remote"];return e&&t.push("-v"),{commands:t,format:"utf-8",parser:e?parseGetRemotesVerbose:parseGetRemotes}}function listRemotesTask(e){const t=[...e];return"ls-remote"!==t[0]&&t.unshift("ls-remote"),straightThroughStringTask(t)}function remoteTask(e){const t=[...e];return"remote"!==t[0]&&t.unshift("remote"),straightThroughStringTask(t)}function removeRemoteTask(e){return straightThroughStringTask(["remote","remove",e])}__export2(VC,{addRemoteTask:()=>addRemoteTask,getRemotesTask:()=>getRemotesTask,listRemotesTask:()=>listRemotesTask,remoteTask:()=>remoteTask,removeRemoteTask:()=>removeRemoteTask});var KC=__esm2({"src/lib/tasks/remote.ts"(){GC(),iE()}}),XC={};function stashListTask(e={},t){const n=parseLogOptions(e),r=["stash","list",...n.commands,...t],s=createListLogSummaryParser(n.splitter,n.fields,logFormatFromCommand(r));return validateLogFormatConfig(r)||{commands:r,format:"utf-8",parser:s}}__export2(XC,{stashListTask:()=>stashListTask});var YC=__esm2({"src/lib/tasks/stash-list.ts"(){eA(),hA(),fA(),yA()}}),JC={};function addSubModuleTask(e,t){return subModuleTask(["add",e,t])}function initSubModuleTask(e){return subModuleTask(["init",...e])}function subModuleTask(e){const t=[...e];return"submodule"!==t[0]&&t.unshift("submodule"),straightThroughStringTask(t)}function updateSubModuleTask(e){return subModuleTask(["update",...e])}__export2(JC,{addSubModuleTask:()=>addSubModuleTask,initSubModuleTask:()=>initSubModuleTask,subModuleTask:()=>subModuleTask,updateSubModuleTask:()=>updateSubModuleTask});var QC=__esm2({"src/lib/tasks/sub-module.ts"(){iE()}}),ZC,eI;function singleSorted(e,t){const n=Number.isNaN(e),r=Number.isNaN(t);return n!==r?n?1:-1:n?sorted(e,t):0}function sorted(e,t){return e===t?0:e>t?1:-1}function trimmed(e){return e.trim()}function toNumber(e){return"string"==typeof e&&parseInt(e.replace(/^\D+/g,""),10)||0}var tI=__esm2({"src/lib/responses/TagList.ts"(){ZC=class{constructor(e,t){this.all=e,this.latest=t}},eI=function(e,t=!1){const n=e.split("\n").map(trimmed).filter(Boolean);t||n.sort(function(e,t){const n=e.split("."),r=t.split(".");if(1===n.length||1===r.length)return singleSorted(toNumber(n[0]),toNumber(r[0]));for(let e=0,t=Math.max(n.length,r.length);e<t;e++){const t=sorted(toNumber(n[e]),toNumber(r[e]));if(t)return t}return 0});const r=t?n[0]:[...n].reverse().find(e=>e.indexOf(".")>=0);return new ZC(n,r)}}}),nI={};function tagListTask(e=[]){const t=e.some(e=>/^--sort=/.test(e));return{format:"utf-8",commands:["tag","-l",...e],parser:e=>eI(e,t)}}function addTagTask(e){return{format:"utf-8",commands:["tag",e],parser:()=>({name:e})}}function addAnnotatedTagTask(e,t){return{format:"utf-8",commands:["tag","-a","-m",t,e],parser:()=>({name:e})}}__export2(nI,{addAnnotatedTagTask:()=>addAnnotatedTagTask,addTagTask:()=>addTagTask,tagListTask:()=>tagListTask});var rI=__esm2({"src/lib/tasks/tag.ts"(){tI()}}),sI=__commonJS2({"src/git.js"(e,t){var{GitExecutor:n}=(LE(),__toCommonJS2(OE)),{SimpleGitApi:r}=(lC(),__toCommonJS2(aC)),{Scheduler:s}=(hC(),__toCommonJS2(dC)),{adhocExecTask:i,configurationErrorTask:o}=(iE(),__toCommonJS2(rE)),{asArray:a,filterArray:c,filterPrimitives:l,filterString:d,filterStringOrStringArray:u,filterType:p,getTrailingOptions:m,trailingFunctionArgument:f,trailingOptionsArgument:g}=(GS(),__toCommonJS2(zS)),{applyPatchTask:y}=(fC(),__toCommonJS2(mC)),{branchTask:b,branchLocalTask:v,deleteBranchesTask:w,deleteBranchTask:x}=(IC(),__toCommonJS2(CC)),{checkIgnoreTask:S}=(NC(),__toCommonJS2(RC)),{checkIsRepoTask:E}=(JS(),__toCommonJS2(VS)),{cloneTask:A,cloneMirrorTask:C}=(FC(),__toCommonJS2(OC)),{cleanWithOptionsTask:I,isCleanOptionsArray:P}=(pE(),__toCommonJS2(oE)),{diffSummaryTask:R}=(fA(),__toCommonJS2(mA)),{fetchTask:N}=(jC(),__toCommonJS2(UC)),{moveTask:O}=(HC(),__toCommonJS2(WC)),{pullTask:F}=(zC(),__toCommonJS2(qC)),{pushTagsTask:L}=(VA(),__toCommonJS2(GA)),{addRemoteTask:M,getRemotesTask:U,listRemotesTask:j,remoteTask:B,removeRemoteTask:$}=(KC(),__toCommonJS2(VC)),{getResetMode:W,resetTask:H}=(CE(),__toCommonJS2(SE)),{stashListTask:q}=(YC(),__toCommonJS2(XC)),{addSubModuleTask:z,initSubModuleTask:G,subModuleTask:V,updateSubModuleTask:K}=(QC(),__toCommonJS2(JC)),{addAnnotatedTagTask:X,addTagTask:Y,tagListTask:J}=(rI(),__toCommonJS2(nI)),{straightThroughBufferTask:Q,straightThroughStringTask:Z}=(iE(),__toCommonJS2(rE));function Git2(e,t){this._plugins=t,this._executor=new n(e.baseDir,new s(e.maxConcurrentProcesses),t),this._trimmed=e.trimmed}function createCloneTask(e,t,n,r){return"string"!=typeof n?o(`git.${e}() requires a string 'repoPath'`):t(n,p(r,d),m(arguments))}(Git2.prototype=Object.create(r.prototype)).constructor=Git2,Git2.prototype.customBinary=function(e){return this._plugins.reconfigure("binary",e),this},Git2.prototype.env=function(e,t){return 1===arguments.length&&"object"==typeof e?this._executor.env=e:(this._executor.env=this._executor.env||{})[e]=t,this},Git2.prototype.stashList=function(e){return this._runTask(q(g(arguments)||{},c(e)&&e||[]),f(arguments))},Git2.prototype.clone=function(){return this._runTask(createCloneTask("clone",A,...arguments),f(arguments))},Git2.prototype.mirror=function(){return this._runTask(createCloneTask("mirror",C,...arguments),f(arguments))},Git2.prototype.mv=function(e,t){return this._runTask(O(e,t),f(arguments))},Git2.prototype.checkoutLatestTag=function(e){var t=this;return this.pull(function(){t.tags(function(n,r){t.checkout(r.latest,e)})})},Git2.prototype.pull=function(e,t,n,r){return this._runTask(F(p(e,d),p(t,d),m(arguments)),f(arguments))},Git2.prototype.fetch=function(e,t){return this._runTask(N(p(e,d),p(t,d),m(arguments)),f(arguments))},Git2.prototype.silent=function(e){return this._runTask(i(()=>console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this method will be removed.")))},Git2.prototype.tags=function(e,t){return this._runTask(J(m(arguments)),f(arguments))},Git2.prototype.rebase=function(){return this._runTask(Z(["rebase",...m(arguments)]),f(arguments))},Git2.prototype.reset=function(e){return this._runTask(H(W(e),m(arguments)),f(arguments))},Git2.prototype.revert=function(e){const t=f(arguments);return"string"!=typeof e?this._runTask(o("Commit must be a string"),t):this._runTask(Z(["revert",...m(arguments,0,!0),e]),t)},Git2.prototype.addTag=function(e){const t="string"==typeof e?Y(e):o("Git.addTag requires a tag name");return this._runTask(t,f(arguments))},Git2.prototype.addAnnotatedTag=function(e,t){return this._runTask(X(e,t),f(arguments))},Git2.prototype.deleteLocalBranch=function(e,t,n){return this._runTask(x(e,"boolean"==typeof t&&t),f(arguments))},Git2.prototype.deleteLocalBranches=function(e,t,n){return this._runTask(w(e,"boolean"==typeof t&&t),f(arguments))},Git2.prototype.branch=function(e,t){return this._runTask(b(m(arguments)),f(arguments))},Git2.prototype.branchLocal=function(e){return this._runTask(v(),f(arguments))},Git2.prototype.raw=function(e){const t=!Array.isArray(e),n=[].slice.call(t?arguments:e,0);for(let e=0;e<n.length&&t;e++)if(!l(n[e])){n.splice(e,n.length-e);break}n.push(...m(arguments,0,!0));var r=f(arguments);return n.length?this._runTask(Z(n,this._trimmed),r):this._runTask(o("Raw: must supply one or more command to execute"),r)},Git2.prototype.submoduleAdd=function(e,t,n){return this._runTask(z(e,t),f(arguments))},Git2.prototype.submoduleUpdate=function(e,t){return this._runTask(K(m(arguments,!0)),f(arguments))},Git2.prototype.submoduleInit=function(e,t){return this._runTask(G(m(arguments,!0)),f(arguments))},Git2.prototype.subModule=function(e,t){return this._runTask(V(m(arguments)),f(arguments))},Git2.prototype.listRemote=function(){return this._runTask(j(m(arguments)),f(arguments))},Git2.prototype.addRemote=function(e,t,n){return this._runTask(M(e,t,m(arguments)),f(arguments))},Git2.prototype.removeRemote=function(e,t){return this._runTask($(e),f(arguments))},Git2.prototype.getRemotes=function(e,t){return this._runTask(U(!0===e),f(arguments))},Git2.prototype.remote=function(e,t){return this._runTask(B(m(arguments)),f(arguments))},Git2.prototype.tag=function(e,t){const n=m(arguments);return"tag"!==n[0]&&n.unshift("tag"),this._runTask(Z(n),f(arguments))},Git2.prototype.updateServerInfo=function(e){return this._runTask(Z(["update-server-info"]),f(arguments))},Git2.prototype.pushTags=function(e,t){const n=L({remote:p(e,d)},m(arguments));return this._runTask(n,f(arguments))},Git2.prototype.rm=function(e){return this._runTask(Z(["rm","-f",...a(e)]),f(arguments))},Git2.prototype.rmKeepLocal=function(e){return this._runTask(Z(["rm","--cached",...a(e)]),f(arguments))},Git2.prototype.catFile=function(e,t){return this._catFile("utf-8",arguments)},Git2.prototype.binaryCatFile=function(){return this._catFile("buffer",arguments)},Git2.prototype._catFile=function(e,t){var n=f(t),r=["cat-file"],s=t[0];if("string"==typeof s)return this._runTask(o("Git.catFile: options must be supplied as an array of strings"),n);Array.isArray(s)&&r.push.apply(r,s);const i="buffer"===e?Q(r):Z(r);return this._runTask(i,n)},Git2.prototype.diff=function(e,t){const n=d(e)?o("git.diff: supplying options as a single string is no longer supported, switch to an array of strings"):Z(["diff",...m(arguments)]);return this._runTask(n,f(arguments))},Git2.prototype.diffSummary=function(){return this._runTask(R(m(arguments,1)),f(arguments))},Git2.prototype.applyPatch=function(e){const t=u(e)?y(a(e),m([].slice.call(arguments,1))):o("git.applyPatch requires one or more string patches as the first argument");return this._runTask(t,f(arguments))},Git2.prototype.revparse=function(){const e=["rev-parse",...m(arguments,!0)];return this._runTask(Z(e,!0),f(arguments))},Git2.prototype.clean=function(e,t,n){const r=P(e),s=r&&e.join("")||p(e,d)||"",i=m([].slice.call(arguments,r?1:0));return this._runTask(I(s,i),f(arguments))},Git2.prototype.exec=function(e){const t={commands:[],format:"utf-8",parser(){"function"==typeof e&&e()}};return this._runTask(t)},Git2.prototype.clearQueue=function(){return this._runTask(i(()=>console.warn("simple-git deprecation notice: clearQueue() is deprecated and will be removed, switch to using the abortPlugin instead.")))},Git2.prototype.checkIgnore=function(e,t){return this._runTask(S(a(p(e,u,[]))),f(arguments))},Git2.prototype.checkIsRepo=function(e,t){return this._runTask(E(p(e,d)),f(arguments))},t.exports=Git2}});yS(),vS();var iI=class extends bS{constructor(e,t){super(void 0,t),this.config=e}};vS(),vS();var oI=class extends bS{constructor(e,t,n){super(e,n),this.task=e,this.plugin=t,Object.setPrototypeOf(this,new.target.prototype)}};function abortPlugin(e){if(!e)return;const t={type:"spawn.after",action(t,n){function kill(){n.kill(new oI(void 0,"abort","Abort signal received"))}e.addEventListener("abort",kill),n.spawned.on("close",()=>e.removeEventListener("abort",kill))}},n={type:"spawn.before",action(t,n){e.aborted&&n.kill(new oI(void 0,"abort","Abort already signaled"))}};return[n,t]}function isConfigSwitch(e){return"string"==typeof e&&"-c"===e.trim().toLowerCase()}function isCloneSwitch(e,t){if("string"!=typeof t||!t.includes(e))return!1;const n=t.replace(/\0g/,"").replace(/^(--no)?-{1,2}/,"");return/^[\dlsqvnobucj]+\b/.test(n)}function preventProtocolOverride(e,t){if(isConfigSwitch(e)&&/^\s*protocol(.[a-z]+)?.allow/i.test(t))throw new oI(void 0,"unsafe","Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol")}function preventUploadPack(e,t){if(/^\s*--(upload|receive)-pack/.test(e))throw new oI(void 0,"unsafe","Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack");if("clone"===t&&isCloneSwitch("u",e))throw new oI(void 0,"unsafe","Use of clone with option -u is not permitted without enabling allowUnsafePack");if("push"===t&&/^\s*--exec\b/.test(e))throw new oI(void 0,"unsafe","Use of push with option --exec is not permitted without enabling allowUnsafePack")}function blockUnsafeOperationsPlugin({allowUnsafeProtocolOverride:e=!1,allowUnsafePack:t=!1}={}){return{type:"spawn.args",action:(n,r)=>(n.forEach((s,i)=>{const o=i<n.length?n[i+1]:"";e||preventProtocolOverride(s,o),t||preventUploadPack(s,r.method)}),n)}}function commandConfigPrefixingPlugin(e){const t=prefixedArray(e,"-c");return{type:"spawn.args",action:e=>[...t,...e]}}_S(),TS(),JS(),pE(),gE(),vE(),kE(),CE(),GS(),GS();var aI=(0,aS.deferred)().promise;function completionDetectionPlugin({onClose:e=!0,onExit:t=50}={}){function createEvents(){let n=-1;const r={close:(0,aS.deferred)(),closeTimeout:(0,aS.deferred)(),exit:(0,aS.deferred)(),exitTimeout:(0,aS.deferred)()},s=Promise.race([!1===e?aI:r.closeTimeout.promise,!1===t?aI:r.exitTimeout.promise]);return configureTimeout(e,r.close,r.closeTimeout),configureTimeout(t,r.exit,r.exitTimeout),{close(e){n=e,r.close.done()},exit(e){n=e,r.exit.done()},get exitCode(){return n},result:s}}function configureTimeout(e,t,n){!1!==e&&(!0===e?t.promise:t.promise.then(()=>delay2(e))).then(n.done)}return{type:"spawn.after",async action(e,{spawned:t,close:n}){const r=createEvents();let s=!0,quickClose=()=>{s=!1};t.stdout?.on("data",quickClose),t.stderr?.on("data",quickClose),t.on("error",quickClose),t.on("close",e=>r.close(e)),t.on("exit",e=>r.exit(e));try{await r.result,s&&await delay2(50),n(r.exitCode)}catch(e){n(r.exitCode,e)}}}}GS();var cI="Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings",lI="Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option";function isBadArgument(e){return!e||!/^([a-z]:)?([a-z0-9/.\\_~-]+)$/i.test(e)}function toBinaryConfig(e,t){if(e.length<1||e.length>2)throw new oI(void 0,"binary",cI);const n=e.some(isBadArgument);if(n){if(!t)throw new oI(void 0,"binary",lI);console.warn(lI)}const[r,s]=e;return{binary:r,prefix:s}}function customBinaryPlugin(e,t=["git"],n=!1){let r=toBinaryConfig(asArray2(t),n);e.on("binary",e=>{r=toBinaryConfig(asArray2(e),n)}),e.append("spawn.binary",()=>r.binary),e.append("spawn.args",e=>r.prefix?[r.prefix,...e]:e)}function isTaskError(e){return!(!e.exitCode||!e.stdErr.length)}function getErrorMessage(e){return Buffer.concat([...e.stdOut,...e.stdErr])}function errorDetectionHandler(e=!1,t=isTaskError,n=getErrorMessage){return(r,s)=>!e&&r||!t(s)?r:n(s)}function errorDetectionPlugin(e){return{type:"task.error",action(t,n){const r=e(t.error,{stdErr:n.stdErr,stdOut:n.stdOut,exitCode:n.exitCode});return Buffer.isBuffer(r)?{error:new bS(void 0,r.toString("utf-8"))}:{error:r}}}}vS(),GS();var dI=class{constructor(){this.plugins=new Set,this.events=new uS}on(e,t){this.events.on(e,t)}reconfigure(e,t){this.events.emit(e,t)}append(e,t){const n=append(this.plugins,{type:e,action:t});return()=>this.plugins.delete(n)}add(e){const t=[];return asArray2(e).forEach(e=>e&&this.plugins.add(append(t,e))),()=>{t.forEach(e=>this.plugins.delete(e))}}exec(e,t,n){let r=t;const s=Object.freeze(Object.create(n));for(const t of this.plugins)t.type===e&&(r=t.action(r,s));return r}};function progressMonitorPlugin(e){const t="--progress",n=["checkout","clone","fetch","pull","push"],r={type:"spawn.after",action(n,r){r.commands.includes(t)&&r.spawned.stderr?.on("data",t=>{const n=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(t.toString("utf8"));n&&e({method:r.method,stage:progressEventStage(n[1]),progress:asNumber(n[2]),processed:asNumber(n[3]),total:asNumber(n[4])})})}},s={type:"spawn.args",action:(e,r)=>n.includes(r.method)?including(e,t):e};return[s,r]}function progressEventStage(e){return String(e.toLowerCase().split(" ",1))||"unknown"}function spawnOptionsPlugin(e){const t=pick(e,["uid","gid"]);return{type:"spawn.options",action:e=>({...t,...e})}}function timeoutPlugin({block:e,stdErr:t=!0,stdOut:n=!0}){if(e>0)return{type:"spawn.after",action(r,s){let i;function wait2(){i&&clearTimeout(i),i=setTimeout(kill,e)}function stop(){s.spawned.stdout?.off("data",wait2),s.spawned.stderr?.off("data",wait2),s.spawned.off("exit",stop),s.spawned.off("close",stop),i&&clearTimeout(i)}function kill(){stop(),s.kill(new oI(void 0,"timeout","block timeout reached"))}n&&s.spawned.stdout?.on("data",wait2),t&&s.spawned.stderr?.on("data",wait2),s.spawned.on("exit",stop),s.spawned.on("close",stop),wait2()}}}function suffixPathsPlugin(){return{type:"spawn.args",action(e){const t=[];let n;function append2(e){(n=n||[]).push(...e)}for(let n=0;n<e.length;n++){const r=e[n];if(isPathSpec(r))append2(toPaths(r));else{if("--"===r){append2(e.slice(n+1).flatMap(e=>isPathSpec(e)&&toPaths(e)||e));break}t.push(r)}}return n?[...t,"--",...n.map(String)]:t}}}GS(),GS(),yS(),GS();var uI=sI();function gitInstanceFactory(e,t){const n=new dI,r=createInstanceConfig(e&&("string"==typeof e?{baseDir:e}:e)||{},t);if(!folderExists(r.baseDir))throw new iI(r,"Cannot use simple-git on a directory that does not exist");return Array.isArray(r.config)&&n.add(commandConfigPrefixingPlugin(r.config)),n.add(blockUnsafeOperationsPlugin(r.unsafe)),n.add(suffixPathsPlugin()),n.add(completionDetectionPlugin(r.completion)),r.abort&&n.add(abortPlugin(r.abort)),r.progress&&n.add(progressMonitorPlugin(r.progress)),r.timeout&&n.add(timeoutPlugin(r.timeout)),r.spawnOptions&&n.add(spawnOptionsPlugin(r.spawnOptions)),n.add(errorDetectionPlugin(errorDetectionHandler(!0))),r.errors&&n.add(errorDetectionPlugin(r.errors)),customBinaryPlugin(n,r.binary,r.unsafe?.allowUnsafeCustomBinary),new uI(r,n)}_S();var pI=gitInstanceFactory;async function pathExists5(e){try{return await nS.access(e),!0}catch{return!1}}async function ensureGitRepo(e){const t=rS.join(e,".git");await nS.mkdir(e,{recursive:!0});const n=pI(e);let r=!1;if(await pathExists5(t))try{r="true"===(await n.raw(["rev-parse","--is-inside-work-tree"])).trim()}catch{r=!1}if(!r)try{await n.init(["--initial-branch=main"])}catch{await n.init()}try{await n.raw(["rev-parse","--verify","HEAD"])}catch{await n.raw(["add","-A"]),await n.raw(["-c","user.name=Tempo","-c","user.email=tempo@local","commit","--allow-empty","-m","Initial commit"])}}async function pathExists6(e){try{return await tS(e),!0}catch{return!1}}function describeGitFailure(e){const t=e instanceof Error?e.message:String(e??"");return/xcode-select: note: No developer tools/i.test(t)||/Command Line Developer Tools/i.test(t)?"Xcode Command Line Tools are required for git. Run `xcode-select --install` to enable git, then retry.":/ENOENT/.test(t)||/git: command not found/i.test(t)?"Git isn't installed on this machine. Install git to enable version control for this project.":t||"Git failed for an unknown reason."}async function ensureTempoGitRepo(e){const t=eS.join(e,".git"),n=await pathExists6(t);try{return await ensureGitRepo(e),{initializedGit:!n,gitSkipped:!1}}catch(e){return{initializedGit:!1,gitSkipped:!0,gitSkipReason:describeGitFailure(e)}}}import hI from"path";import{access as mI,lstat as fI,mkdir as gI,readFile as yI,writeFile as bI}from"fs/promises";async function pathExists7(e){try{return await mI(e),!0}catch{return!1}}function normalizeEntry(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")+"/"}function getIgnorePrefix(e){return"."===e.rootRel?"":`${e.rootRel.replace(/^\.\//,"").replace(/\/+$/,"")}/`}async function resolveGitCommonDir(e){const t=hI.join(e,".git");let n;try{const r=await fI(t);if(r.isDirectory())n=t;else{const r=await yI(t,"utf-8"),s=r.match(/^gitdir:\s*(.+)$/m);if(!s)return null;const i=s[1].trim();n=hI.isAbsolute(i)?i:hI.resolve(e,i)}}catch{return null}try{const e=(await yI(hI.join(n,"commondir"),"utf-8")).trim();if(e)return hI.resolve(n,e)}catch{}return n}function getIgnoreEntries(e){const t=getIgnorePrefix(e);return[`${t}.tempo`,`${t}node_modules`,`${t}dist`].map(normalizeEntry)}var vI=[".tempo","app-devserver.json","app-devserver.log","node_modules",".next",".nuxt",".output",".data",".expo",".swc",".turbo","dist","out","web-build","*.log","logs",".flutter-host",".DS_Store"];function getTempoFolderGitignorePath(e){return hI.join(e.tempoRoot,".gitignore")}async function ensureTextFileEntries(e,t){const n=await pathExists7(e)?await yI(e,"utf-8"):"",r=new Set(n.split(/\r?\n/).map(e=>e.trim())),s=t.filter((e,n)=>!r.has(e)&&t.indexOf(e)===n);if(0===s.length&&await pathExists7(e))return!1;const i=n.includes("\r\n")?"\r\n":"\n",o=n.length>0&&!n.endsWith("\n"),a=s.map(e=>`${e}${i}`).join("");return await gI(hI.dirname(e),{recursive:!0}),await bI(e,`${n}${o?i:""}${a}`,"utf-8"),s.length>0}async function ensureTempoIgnoreEntries(e){const t=getIgnoreEntries(e),n=hI.join(e.projectRoot,".gitignore"),r=await ensureTextFileEntries(n,t);let s=!1;const i=await resolveGitCommonDir(e.projectRoot);if(i){const e=hI.join(i,"info","exclude");s=await ensureTextFileEntries(e,[...t,".tempo/"])}const o=await ensureTextFileEntries(getTempoFolderGitignorePath(e),vI);return{updatedGitignore:r,updatedGitExclude:s,updatedTempoFolderGitignore:o}}import{spawn as wI}from"child_process";import{access as _I}from"fs/promises";import xI from"path";var{error:TI,throwIfAborted:kI,sleep:SI}=abortableWait("Dependency installation was cancelled");import{access as EI,mkdir as AI,rm as CI}from"fs/promises";import II from"path";var PI="tempo",DI="tempo.config.json",RI={migrated:!1,movedPaths:[],installScriptRewrote:!1};async function pathExists8(e){try{return await EI(e),!0}catch{return!1}}async function writeCanonicalDefaultConfig(e){const t=await detectRootPackageManager(e.projectRoot),n=buildInstallScript(t?.installCmd??null);return await writeTempoConfigFile(e.tempoRoot,buildDefaultTempoConfig({installScript:n})),II.join(e.tempoRoot,DI)}async function migrateLegacyRootLayout(e){const t=II.resolve(e),n=II.join(t,DI),r=II.join(t,PI,DI);if(await pathExists8(n)){const s=await pathExists8(r);if(devLog("migrate-legacy:delete-root-config",{projectRoot:e,legacyConfigPath:n,canonicalConfigPath:r,canonicalExists:s}),await CI(n,{force:!0}),s)return{...RI,autoCleanedLegacyConfigPath:n};const i=II.join(t,PI);await AI(i,{recursive:!0});const o=await writeCanonicalDefaultConfig({projectRoot:t,tempoRoot:i});return devLog("migrate-legacy:create-canonical-after-delete",{projectRoot:e,legacyConfigPath:n,createdCanonicalConfigPath:o}),{...RI,autoCleanedLegacyConfigPath:n,createdCanonicalConfigPath:o}}return devLog("migrate-legacy:skip",{projectRoot:e}),RI}import{readFile as NI,realpath as OI}from"fs/promises";import{createRequire as FI}from"module";import LI from"path";import MI from"path";function configsEqual(e,t){return e.projectRoot===t.projectRoot&&e.tempoConfigPath===t.tempoConfigPath&&e.rootRel===t.rootRel&&e.tempoRoot===t.tempoRoot&&e.pagesDir===t.pagesDir&&e.packageJsonPath===t.packageJsonPath&&e.viteConfigPath===t.viteConfigPath&&e.tsconfigPath===t.tsconfigPath&&JSON.stringify(e.tempoHostUrl)===JSON.stringify(t.tempoHostUrl)&&e.uiFramework===t.uiFramework&&e.appDir===t.appDir&&e.scripts.install===t.scripts.install&&e.scripts.updateSdk===t.scripts.updateSdk&&e.scripts.start===t.scripts.start&&e.scripts.stop===t.scripts.stop}function usesTempoManagedSidecarPackage(e,t){if(!looksLikeGeneratedInstallScript(e.scripts.install))return!1;const n=e.scripts.start.trim();return"expo"===t?"npx expo start --web"===n:/^(?:npm|pnpm|bun) run dev$|^yarn dev$/.test(n)}function toDevServerConfig(e){return{tempoConfigPath:e.tempoConfigPath,tempoHostUrl:e.tempoHostUrl,appDir:e.appDir??null,scripts:{...e.scripts}}}function buildInitResult(e){return{config:e.config,createdConfig:e.createdConfig,initializedGit:e.initializedGit,gitSkipped:e.gitSkipped,...void 0!==e.gitSkipReason?{gitSkipReason:e.gitSkipReason}:{},updatedGitignore:e.updatedGitignore,updatedGitExclude:e.updatedGitExclude,createdDirectories:e.createdDirectories,legacyLayoutMigration:e.legacyLayoutMigration,devserverInit:e.devserverInit,warnings:e.warnings}}function nuxtAppDirToRecord(e,t,n){return void 0!==e.appDir||null===t.appDir?null:n===t.start?t.appDir:null}var UI=class{constructor(e,t,n){this.parseManagedLockfile=t,this.devserver=null,this.devserverConfig=null,this.initializePromise=null,this.projectRoot=MI.resolve(e),this.fastNpmInstall=!0===n}static async open(e){const t="string"==typeof e?e:e.projectRoot;return new this(t,"string"==typeof e?void 0:e.parseManagedLockfile,"string"==typeof e?void 0:e.fastNpmInstall)}getProjectRoot(){return this.projectRoot}async getResolvedConfig(){return await resolveTempoConfig(this.projectRoot)}async getFramework(){try{return await detectProjectFramework(await this.getResolvedConfig())}catch{return"vite"}}async getUiFramework(){const e=await this.getResolvedConfig();return resolveAppUiFramework(e.apps[0]?.uiFramework)}async isInitialized(){return await tempoConfigExists(this.projectRoot)}async initialize(e={}){return await this.ensureInitialized(e)}async initializeExistingProject(e={}){const t=await this.runSingleInitialize(async()=>await this.performInitializeExistingProject(e));return await seedSharedControls(t.config),t}async ensureInitialized(e={}){return await this.runSingleInitialize(async()=>{const t=await migrateLegacyRootLayout(this.projectRoot);if(await tempoConfigExists(this.projectRoot)){await ensureDirectoryExists(this.projectRoot);const n=await ensureTempoGitRepo(this.projectRoot);await ensureValidTempoConfigFile(this.projectRoot);let r=await this.getResolvedConfig();resolveAppUiFramework(r.apps[0]?.uiFramework);const s=await ensureTempoIgnoreEntries(r),i=await this.resolveSetupFramework(r,e),o=await rescueWronglyBackedUpFiles(r);o.restored.length>0&&console.log(`[tempo-project] restored ${o.restored.length} wrongly-backed-up file(s) from prior heal pass: ${o.restored.join(", ")}`);const a=await healFrameworkMismatch(r,i);a.healed&&a.backupPath&&console.log(`[tempo-project] healed framework mismatch: ${a.previousFramework} → ${i}; previous scaffold backed up to ${a.backupPath}`);const c=[];if("nuxt"===i)if(a.healed){const e=await this.recordNuxtAppDefaults(r);r=e.config,c.push(...e.warnings)}else r=await this.reconcileNuxtAppDir(r);const l=await hasCustomReactViteHost(r,i);l?await ensureTempoWorkspaceNonce(r.tempoRoot):(c.push(...await ensureProjectSetupFiles(r,i,{migrateSdkDependencies:!1,createPackageJsonIfMissing:a.healed||usesTempoManagedSidecarPackage(r,i)})),await ensureProjectScaffold(r,i));const d=await reconcileExpoStartScriptOnDisk(r.tempoConfigPath,i);d&&console.log(`[tempo-project] reconciled tempo.config.json scripts.start for framework ${i}`);const u=await this.getDevServer(r),p=await u.initialize();return buildInitResult({config:r,createdConfig:!1,initializedGit:n.initializedGit,gitSkipped:n.gitSkipped,gitSkipReason:n.gitSkipReason,updatedGitignore:s.updatedGitignore,updatedGitExclude:s.updatedGitExclude,createdDirectories:[],legacyLayoutMigration:t,devserverInit:p,warnings:c})}return await this.performInitializeExistingProject(e)})}async reconcile(e){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);return{config:t,devserver:await n.reconcile(e)}}async ensureCanvasRegistered(e){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);await n.ensureCanvasRegistered(e)}async prepareManagedDependencies(e={}){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);await n.prepareManagedDependencies(e)}async prepareDependenciesForStart(e={}){const t=await this.getDevServer(await this.getResolvedConfig());await t.prepareDependenciesForStart(e)}async startDevServer(e){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);return await n.startDevServer(e)}async listRegisteredCanvases(){const e=await this.getResolvedConfig(),t=await this.getDevServer(e);return await t.listRegisteredCanvases()}async getRequestedCanvasPaths(){const e=await this.getResolvedConfig(),t=await this.getDevServer(e);return await t.getRequestedCanvasPaths()}async getState(){try{const e=await this.getResolvedConfig(),t=await this.getDevServer(e);return t.getState()}catch{return{setupStatus:"uninitialized",reconcileStatus:"idle",processStatus:"stopped",livenessSource:null,initialized:!1,generation:0,lastError:null,dependenciesInstalled:!1,devserverUrl:null,recentReconciles:[],recentStartAttempts:[],recentExits:[]}}}async dispose(){const e=this.devserver;this.devserver=null,this.devserverConfig=null,await(e?.dispose())}createDevServer(e){return new fx(e)}async getDevServer(e){const t=e??await this.getResolvedConfig(),n=!this.devserver||!this.devserverConfig||!configsEqual(this.devserverConfig,t);return n&&(this.devserver=this.createDevServer({...toDevServerConfig(t),parseManagedLockfile:this.parseManagedLockfile,...this.fastNpmInstall?{fastNpmInstall:!0}:{}}),this.devserverConfig=t),this.devserver}async performInitializeExistingProject(e={}){await ensureDirectoryExists(this.projectRoot);const t=await migrateLegacyRootLayout(this.projectRoot),n=await ensureTempoGitRepo(this.projectRoot),r=await detectRootPackageManager(this.projectRoot),s=buildInstallScript(r?.installCmd??null),i=e.framework,o=await ensureTempoConfigFile(this.projectRoot,MI.join(this.projectRoot,ly),"expo"===i?buildExpoTempoConfig({installScript:s}):buildDefaultTempoConfig({installScript:s}));await ensureValidTempoConfigFile(this.projectRoot);let a=await this.getResolvedConfig();resolveAppUiFramework(a.apps[0]?.uiFramework);const c=await ensureTempoIgnoreEntries(a),l=[],d=await findAppDirToRecord(a);null!==d.appDir&&(await mergeTempoConfigFile(this.projectRoot,{appDir:d.appDir}),console.log(`[tempo-project] recorded apps[0].appDir "${d.appDir}", the project's only app package`),a=await this.getResolvedConfig()),d.warning&&l.push(setupWarning(d.warning));const u=await buildInstallScriptForProject(this.projectRoot,a.appDir),p=a.scripts.install===s;p&&u!==s&&(await mergeTempoConfigFile(this.projectRoot,{installScript:u}),a=await this.getResolvedConfig());const m=await this.resolveSetupFramework(a,e),f=await healFrameworkMismatch(a,m);if(f.healed&&f.backupPath&&(l.push(setupWarning(`replaced the ${f.previousFramework} canvas host in tempo/ with the ${m} one; the previous files are in ${f.backupPath}`)),a=await this.getResolvedConfig()),"nuxt"===m){const e=await this.recordNuxtAppDefaults(a,d.warning);a=e.config,l.push(...e.warnings)}l.push(...await ensureProjectSetupFiles(a,m)),await ensureProjectScaffold(a,m);const g=await this.getDevServer(a),y=await g.initialize();return buildInitResult({config:a,createdConfig:o,initializedGit:n.initializedGit,gitSkipped:n.gitSkipped,gitSkipReason:n.gitSkipReason,updatedGitignore:c.updatedGitignore,updatedGitExclude:c.updatedGitExclude,createdDirectories:[],legacyLayoutMigration:t,devserverInit:y,warnings:l})}async recordNuxtAppDefaults(e,t=null){const n=e.apps[0],r=await resolveNuxtAppRun(e);if(!await isNuxtAppDir(r.appRoot)){const e=r.appDir?`"${r.appDir}"`:"the project root";throw new Error(`No Nuxt app in ${e}: it has no nuxt dependency and no nuxt.config.*. Set "apps[0].appDir" in tempo/tempo.config.json to the Nuxt app's folder, relative to the project root (for example "apps/web"), then rerun canvas_project_init.`+(r.appRootWarning?` ${r.appRootWarning}`:"")+(t?` ${t}`:""))}const s=[],i=void 0===n?.uiFramework,o=null!==r.appDir&&n?.start===r.projectRootStart,a=!n?.start||o,c=a?r.start:n?.start??r.start;o&&s.push(setupWarning(`apps[0].start ran the Nuxt app from the project root; replaced it with "${r.start}", which runs from "${r.appDir}".`)),nuxtAppStartExtendsAppLayer(c)||s.push(setupWarning(`apps[0].start ("${c}") does not pass --extends ${r.appLayerPath}, Tempo's app layer: Nuxt route storyboards will have no Vue source layers. Add "--extends ${r.appLayerPath}" to the nuxt dev command.`));const{unsupportedInstaller:l}=await appPackageLinks(r.appRoot,e.tempoRoot,Bk);l&&s.push(setupWarning(`the Nuxt app in "${r.appDir}" installs its packages where tempo/ cannot reach them, and ${l} installs tempo/: it cannot link the app's own nuxt and vue without installing a second Nuxt, so the canvas cannot load the app. Supported: pnpm or npm, or an app whose packages install into a workspace root above tempo/.`));const d=nuxtAppDirToRecord(e,r,c);return i||a||null!==d?(await mergeTempoConfigFile(this.projectRoot,{...i?{appUiFramework:"vue"}:{},...a?{appStart:r.start}:{},...null!==d?{appDir:d}:{}}),{config:await this.getResolvedConfig(),warnings:s}):{config:e,warnings:s}}async reconcileNuxtAppDir(e){const t=e.apps[0]?.start;if(!t||void 0!==e.appDir)return e;const n=nuxtAppDirToRecord(e,await resolveNuxtAppRun(e),t);return null===n?e:(await mergeTempoConfigFile(this.projectRoot,{appDir:n}),console.log(`[tempo-project] recorded appDir "${n}": Tempo's Nuxt app start command runs from the app directory`),await this.getResolvedConfig())}async resolveSetupFramework(e,t){return t.framework?t.framework:await detectProjectFramework(e)}async runSingleInitialize(e){if(this.initializePromise)return await this.initializePromise;this.initializePromise=e();try{return await this.initializePromise}finally{this.initializePromise=null}}},jI="## Responsive storyboards",BI="## What earlier checks found in this project",$I=2e3,WI=["AGENTS.md","CLAUDE.md"];async function readProjectFindingsAppendix(e){for(const t of WI){const n=`${ly}/${t}`,r=await jm(Bm.join(e,ly,t),"utf8").catch(()=>null);if(null===r)continue;const s=extractSection(r,jI);if(s)return formatAppendix(s,n)}return""}function extractSection(e,t){const n=e.split(/\r?\n/),r=n.findIndex(e=>e.trimEnd()===t);if(-1===r)return null;const s=n.slice(r+1),i=s.findIndex(e=>e.startsWith("## ")),o=(-1===i?s:s.slice(0,i)).join("\n").trim();return""===o?null:o}function formatAppendix(e,t){const n=`\n\n---\n\n${BI}\n\nFrom \`${t}\`, \`${jI}\`:\n\n`,r=`${n}${e}\n`;if(r.length<=$I)return r;const s=`\n\n(Cut at ${$I.toLocaleString("en-US")} characters. The rest is in \`${t}\` under \`${jI}\`.)\n`,i=$I-n.length-s.length;return`${n}${cutAtLine(e,i)}${s}`}function cutAtLine(e,t){const n=e.slice(0,t),r=n.lastIndexOf("\n");return(r>0?n.slice(0,r):n).trimEnd()}var HI={"tempo-canvas-instructions":Om,"tempo-assets-instructions":Nm,"tempo-design-system-example":Mm,"tempo-visual-review-setup":Um},qI=Object.keys(HI);function resolveTemplate(e,t){const n=Dm.relative(t.workspaceRoot,t.canvasesDir)||"tempo/designs";return e.replace(/\{\{canvasesDir\}\}/g,t.canvasesDir).replace(/\{\{canvasesDirRel\}\}/g,n).replace(/\{\{workspaceRoot\}\}/g,t.workspaceRoot)}function registerDocs(e,t){const n=!1!==t.assetsEnabled,r=qI.filter(e=>n||"tempo-assets-instructions"!==e);e.tool("get_guide",n?"Returns canvas documentation by topic. Pick by INTENT, not by name similarity: 'tempo-canvas-instructions' — the full canvas authoring guide; MUST be called before your first canvas operation in a session. 'tempo-assets-instructions' — the design-system conventions: defineControls + defineAsset authoring rules, placement, and asset_* write recipes; MUST be read before ADDING or EDITING controls or asset declarations, but NOT needed to browse (browse directly with asset_list / asset_list_libraries — never via a guide). 'tempo-design-system-example' — the full source of the reference design-system canvas; read ONLY when authoring a design-system canvas, to mirror its anatomy and formatting — it is not a way to look up what's in the design system. 'tempo-visual-review-setup' — the protocol for turning on visual review (VRT) for a repo: how to read visual_review_doctor's rows, what visual_review_init writes, picking + verifying the first tracked set, other-CI limits, and the debugging ladder; MUST be read before running visual_review_doctor / visual_review_init.":"Returns canvas documentation by topic. Topics: 'tempo-canvas-instructions' (full canvas authoring guide — MUST be called before your first canvas operation in a session), 'tempo-design-system-example' (full source of the reference design-system canvas — read before authoring design-system canvases to mirror its anatomy and formatting), 'tempo-visual-review-setup' (the visual review setup protocol — MUST be read before visual_review_doctor / visual_review_init).",{topic:Rm.enum(r).describe(`Guide topic. Currently supported: ${r.join(", ")}`)},async({topic:e})=>{const n=HI[e];if(!n)return{content:[{type:"text",text:`Unknown guide topic '${e}'. Available topics: ${qI.join(", ")}`}],isError:!0};const r="tempo-canvas-instructions"===e?await readProjectFindingsAppendix(t.workspaceRoot):"";return{content:[{type:"text",text:resolveTemplate(n,t)+r}]}}),e.resource("tempo://docs/canvas","tempo://docs/canvas",async()=>({contents:[{uri:"tempo://docs/canvas",text:resolveTemplate(Om,t),mimeType:"text/markdown"}]})),e.resource("tempo://docs/design-system-example","tempo://docs/design-system-example",async()=>({contents:[{uri:"tempo://docs/design-system-example",text:resolveTemplate(Mm,t),mimeType:"text/markdown"}]})),e.resource("tempo://docs/visual-review-setup","tempo://docs/visual-review-setup",async()=>({contents:[{uri:"tempo://docs/visual-review-setup",text:resolveTemplate(Um,t),mimeType:"text/markdown"}]})),n&&e.resource("tempo://docs/assets","tempo://docs/assets",async()=>({contents:[{uri:"tempo://docs/assets",text:resolveTemplate(Nm,t),mimeType:"text/markdown"}]}))}function buildCanvasInstructions(e,t){const n=!1===t?.assetsEnabled?"":'## Asset libraries\n\nBefore creating, modifying, restyling, or reviewing ANY UI, call `asset_list` FIRST and reuse results per `usageInstructions`. Do the same for design system, component library, or UI kit requests; use `asset_list_libraries` for a collection overview. Before editing `defineControls` or `defineAsset`, read get_guide({ topic: "tempo-assets-instructions" }). Follow its controls-placement policy. Assets declare top-level components.\n\n';return`Tempo canvases are code-first. Canvases live under the canvases root ${e}/, whose storyboards render PRODUCTION components and routes — never mocks of existing UI.\n\nBefore any canvas or tempo.config.json change, you MUST call get_guide({ topic: "tempo-canvas-instructions" }); it is authoritative.\n\n${n}## Hard invariants\n\n- No tempo.config.json → canvas_project_init BEFORE any canvas work. \`tempo/\` is Tempo's canvas host, NOT the user's app — build new UI in the real app; canvas-local files only wrap it (guide §5.1).\n- Zone canvases (design-system/**, libraries/<libname>/**) MUST defineAsset-declare their showcased components — else canvas_validate fails missing_asset_declaration.\n- Canvas activity: start_working_on_canvas → edits → canvas_screenshot → finish_working_on_canvas. Frame shimmer: start_working_on_storyboard / finish_working_on_storyboard. Rendering stays live. On screenshot failure: canvas_debug once, no retries.\n- Write is blocked on *.canvas.tsx — canvas_create creates, Edit modifies.\n- Route storyboards need the user's real app: set_app_dev_command once, start_app_dev_server before screenshots.\n- VRT: canvas_set_vrt, then canvas_verify_vrt until \`vrt_stable\`. Setup: visual_review_doctor first; visual_review_init writes the workflow, never hand-write it; guide tempo-visual-review-setup.\n- Existing site/page as HTML snapshot → canvas_snapshot_route, never a custom serializer. Pixel parity: guide §9.1.\n- Link new canvases to sibling issue/doc via link_items (branch pushed).`}import{readFile as zI,realpath as GI,writeFile as VI}from"fs/promises";import KI from"path";import{readFile as XI,writeFile as YI}from"fs/promises";import JI from"path";import{z as QI}from"zod";import{parseSync as ZI}from"oxc-parser";import{createRequire as eP}from"module";var tP=Object.freeze({$unresolved:!0});function isUnresolvedValue(e){return"object"==typeof e&&null!==e&&nP in e&&!0===e.$unresolved}var nP="$unresolved";function parseAstroAssetSource(e){const t=eP(import.meta.url)("@astrojs/compiler-rs").parse(e),n=t.diagnostics.filter(e=>"error"===e.severity);if(n.length)throw new Error(n.map(e=>e.text).join("\n"));return t.ast}var rP="tempo-sdk/assets";function parseAssetFile(e,t,n=parseAssetProgram(e,t)){const{program:r}=n,s=[...n.errors];if(!r)return{filePath:e,declarations:[],errors:s};const i=readAssetImports(r);for(const e of i.misimports)s.push({code:"misimported_define_asset",severity:"structural",message:`defineAsset must be imported from "${rP}" — found import from "${e.source}"`,span:e.span});const o=new Map;for(const e of r.body){const t="ExportNamedDeclaration"===e.type?e.declaration:e;if("VariableDeclaration"===t?.type&&"const"===t.kind)for(const e of t.declarations)"Identifier"===e.id.type&&e.init&&o.set(e.id.name,e.init)}const resolveConstants=(t,n=new Set,r=0)=>{if(!t||r>16)return t;if("Identifier"===t.type&&o.has(t.name)&&!n.has(t.name))return resolveConstants(o.get(t.name),new Set(n).add(t.name),r+1);if("JSXElement"===t.type||"JSXFragment"===t.type){const s=t.openingElement,o="JSXIdentifier"===s?.name?.type?s.name.name:"";if(s&&!o)return t;const a=o&&/^[A-Z]/.test(o)?i.referenceableImports.get(o):void 0;if(o&&/^[A-Z]/.test(o)&&!a)return t;const c={};for(const e of s?.attributes??[]){if("JSXAttribute"!==e.type||"JSXIdentifier"!==e.name.type)return t;c[e.name.name]=!e.value||readStaticValue(resolveConstants("JSXExpressionContainer"===e.value.type?e.value.expression:e.value,n,r+1))}const l=[];for(const e of t.children)if("JSXText"===e.type){const t=e.value.replace(/\t/g," ").split(/\r\n|\n|\r/),n=t.map((e,n)=>(n?e.trimStart():e).replace(n<t.length-1?/ +$/:/$^/,"")).filter(Boolean).join(" ");n&&l.push(n)}else{if("JSXExpressionContainer"===e.type&&"JSXEmptyExpression"===e.expression.type)continue;l.push(readStaticValue(resolveConstants("JSXExpressionContainer"===e.type?e.expression:e,n,r+1)))}l.length&&(c.children=1===l.length?l[0]:l);let d=a?.importSpecifier;if(d?.startsWith(".")){const t=e.replace(/\\/g,"/").split("/").slice(0,-1);for(const e of d.split("/"))".."===e?t.pop():"."!==e&&t.push(e);d=t.join("/")}else d&&(d=`pkg:${d}`);return{type:"TempoJsxValue",value:{$jsx:{tag:o,...a?{reference:{source:d,importedName:a.importedName}}:{},props:c}}}}return"ArrowFunctionExpression"!==t.type||t.async||0!==t.params.length?"ObjectExpression"===t.type?{...t,properties:t.properties.map(e=>"Property"===e.type?{...e,value:resolveConstants(e.value,n,r+1),shorthand:!1}:e)}:"ArrayExpression"===t.type?{...t,elements:t.elements.map(e=>resolveConstants(e,n,r+1))}:["TSAsExpression","TSSatisfiesExpression","ParenthesizedExpression"].includes(t.type)?{...t,expression:resolveConstants(t.expression,n,r+1)}:t:{...t,body:resolveConstants(t.body,n,r+1)}},a=collectTopLevelScope(r),c=[],l=new Set,d=new Set;for(const e of r.body??[]){const n=readTopLevelTrustedCall(e,i.trustedDefineAssetNames);if(!n)continue;d.add(n);const o=readAssetDeclaration({statement:e,call:{...n,arguments:n.arguments.map((e,t)=>1===t&&"ObjectExpression"===e.type?{...e,properties:e.properties.map(e=>"Property"===e.type&&["controls","variants"].includes(e.key.name??e.key.value)?{...e,value:resolveConstants(e.value)}:e)}:e)},scope:a,imports:i,program:r,source:t,errors:s,declaredBindings:l});o&&c.push(o)}walk2(r,e=>{"CallExpression"===e.type&&"Identifier"===e.callee?.type&&i.trustedDefineAssetNames.has(e.callee.name)&&!d.has(e)&&s.push({code:"non_top_level_call",severity:"structural",message:"defineAsset must be called as a top-level statement — in the file that defines the component, or in a canvas file that imports it",span:toSourceSpan(e)})});for(const e of c){const t=s.find(t=>"duplicate_declaration"===t.code&&t.message.includes(`"${e.bindingName}"`));t&&e.warnings.push({...t,code:"duplicate_asset_declaration"})}return{filePath:e,declarations:c,errors:s}}function parseAssetProgram(e,t){try{if(e.endsWith(".astro")){const e=parseAstroAssetSource(t);return{program:e.frontmatter?.program??{type:"Program",body:[]},errors:[]}}const n=ZI(e,t),r=(n.errors??[]).map(e=>({code:"unparseable_source",severity:"structural",message:e?.message??"Unable to parse asset source",span:toSourceSpan(e)??toSourceSpan(e?.labels?.[0])}));return r.length>0?{program:null,errors:r}:{program:n.program,errors:[]}}catch(e){return{program:null,errors:[{code:"unparseable_source",severity:"structural",message:e instanceof Error?e.message:"Unable to parse asset source"}]}}}function readSourceComments(e,t){try{if(e.endsWith(".astro")){const e=parseAstroAssetSource(t),n=[...e.comments],visit2=e=>{if(e&&"object"==typeof e){"AstroComment"===e.type&&n.push(e);for(const[t,n]of Object.entries(e))"comments"!==t&&(Array.isArray(n)?n.forEach(visit2):n&&"object"==typeof n&&visit2(n))}};return visit2(e),n.map(e=>({value:e.value,span:{start:e.start,end:e.end}}))}const n=ZI(e,t);return(n.errors??[]).length>0?null:(n.comments??[]).flatMap(e=>"string"==typeof e?.value?[{value:e.value,span:toSourceSpan(e)??{start:0,end:0}}]:[])}catch{return null}}function readAssetImports(e){const t={trustedDefineControlsNames:new Set,trustedDefineAssetNames:new Set,importedBindings:new Map,referenceableImports:new Map,importDeclarationSpans:[],misimports:[]};for(const n of e?.body??[]){if("ImportDeclaration"!==n?.type||"string"!=typeof n.source?.value)continue;const e=toSourceSpan(n);if(e&&t.importDeclarationSpans.push(e),"type"===n.importKind)continue;const r=n.source.value,s=isTrustedAssetImportSource(r);for(const i of n.specifiers??[]){if("type"===i?.importKind)continue;const o=i?.local?.name;if("string"!=typeof o)continue;if(t.importedBindings.set(o,r),"ImportDefaultSpecifier"===i.type){t.referenceableImports.set(o,{importSpecifier:r,importedName:"default"});continue}if("ImportSpecifier"!==i.type)continue;const a=i.imported?.name??i.imported?.value??o;t.referenceableImports.set(o,{importSpecifier:r,importedName:a}),s&&"defineControls"===a&&t.trustedDefineControlsNames.add(o),"defineAsset"===a&&(s?t.trustedDefineAssetNames.add(o):isMisimportedAssetSdkSource(r)&&t.misimports.push({source:r,span:toSourceSpan(n.source)??e??{start:0,end:0}}))}}return t}function parseControlsFile(e,t,n=parseAssetProgram(e,t)){const{program:r}=n,s=readAssetImports(r),i=r?collectTopLevelScope(r):null,o=new Set;if(e.endsWith(".astro"))for(const e of r?.body??[])if("ImportDeclaration"===e.type&&"tempo-sdk/astro/controls"===e.source.value&&"type"!==e.importKind)for(const t of e.specifiers)"ImportSpecifier"===t.type&&"type"!==t.importKind&&"defineAstroControls"===(t.imported.name??t.imported.value)&&o.add(t.local.name);return(r?.body??[]).flatMap(e=>{const t="ExpressionStatement"===e.type?e.expression:null;if("CallExpression"===t?.type&&"Identifier"===t.callee.type&&o.has(t.callee.name)&&1===t.arguments.length)return[{bindingName:"default",exportKind:"default",start:t.start,end:t.end}];if("CallExpression"!==t?.type||"Identifier"!==t.callee.type||!s.trustedDefineControlsNames?.has(t.callee.name)||2!==t.arguments.length||"Identifier"!==t.arguments[0]?.type)return[];const n=t.arguments[0].name,r=s.referenceableImports.get(n),a=i?.bindings.get(n);return r||a?[{bindingName:n,reference:r,exportKind:"default"===r?.importedName?"default":a?.exportKind??"named",start:t.start,end:t.end}]:[]})}function isTrustedAssetImportSource(e){return e===rP||e.endsWith(`/${rP}`)}function isMisimportedAssetSdkSource(e){return("tempo-sdk"===e||e.startsWith("tempo-sdk/"))&&!isTrustedAssetImportSource(e)}function collectTopLevelScope(e){const t=new Map,n=new Set,r=new Set,s=new Set,register=(e,i,o)=>{const markExported=e=>{"named"===o&&r.add(e),"default"===o&&s.add(e)};if("FunctionDeclaration"===e?.type||"ClassDeclaration"===e?.type){const n=e.id?.name;return void("string"==typeof n&&(t.set(n,{name:n,statementSpan:i,exportKind:"none"}),markExported(n)))}if("VariableDeclaration"===e?.type)for(const r of e.declarations??[])if("Identifier"===r?.id?.type){const e=r.id.name;r.init?(t.set(e,{name:e,statementSpan:i,exportKind:"none"}),markExported(e)):n.add(e)}else collectPatternNames(r?.id,n)};for(const t of e?.body??[]){const e=toSourceSpan(t)??{start:0,end:0};if("ExportNamedDeclaration"!==t?.type){if("ExportDefaultDeclaration"===t?.type){const n=t.declaration;if("FunctionDeclaration"===n?.type||"ClassDeclaration"===n?.type)register(n,e,"default");else{const e=unwrapTsExpression2(n);"Identifier"===e?.type&&s.add(e.name)}continue}register(t,e,null)}else if(t.declaration&&register(t.declaration,e,"named"),!t.source)for(const e of t.specifiers??[]){if("ExportSpecifier"!==e?.type)continue;const t=e.local?.name;if("string"!=typeof t)continue;const n=e.exported?.name??e.exported?.value;("default"===n?s:r).add(t)}}for(const e of t.values())e.exportKind=s.has(e.name)?"default":r.has(e.name)?"named":"none";return{bindings:t,nonSimpleNames:n}}function collectPatternNames(e,t){if(e&&"object"==typeof e)if("Identifier"!==e.type||"string"!=typeof e.name)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"AssignmentPattern"!==e.type?"RestElement"===e.type&&collectPatternNames(e.argument,t):collectPatternNames(e.left,t);else for(const n of e.elements??[])collectPatternNames(n,t);else for(const n of e.properties??[])collectPatternNames(n?.value??n?.argument,t);else t.add(e.name)}function hasTopLevelDefineAssetCallFor(e,t,n){for(const r of e?.body??[]){const e=readTopLevelTrustedCall(r,t);if(!e)continue;const s=unwrapTsExpression2(e.arguments?.[0]);if("Identifier"===s?.type&&s.name===n)return!0}return!1}function collectIdentifierNames(e){const t=new Set;return walk2(e,e=>{"Identifier"!==e.type&&"JSXIdentifier"!==e.type||"string"!=typeof e.name||t.add(e.name)}),t}function readTopLevelTrustedCall(e,t){if("ExpressionStatement"!==e?.type)return null;const n=unwrapTsExpression2(e.expression);return"CallExpression"===n?.type&&"Identifier"===n.callee?.type&&t.has(n.callee.name)?n:null}function readAssetDeclaration(e){const{statement:t,call:n,scope:r,imports:s,program:i,source:o,errors:a}=e,c=statementSpanWithSemicolon(o,t),l=n.arguments??[];if(2!==l.length)return a.push({code:"invalid_call_arguments",severity:"structural",message:`defineAsset takes exactly two arguments (component, config) — found ${l.length}`,span:c}),null;const d=unwrapTsExpression2(l[0]);if("Identifier"!==d?.type)return a.push({code:"non_identifier_component",severity:"structural",message:"defineAsset's first argument must be an identifier naming a component defined in this file",span:toSourceSpan(l[0])??c}),null;const u=d.name,p=r.bindings.get(u),m=p?void 0:s.referenceableImports.get(u);if(!p&&!m)return a.push(classifyMissingBinding(u,r,s,i,toSourceSpan(d)??c)),null;const f=unwrapTsExpression2(l[1]);if("ObjectExpression"!==f?.type)return a.push({code:"config_not_object_literal",severity:"structural",message:"defineAsset's config must be an inline object literal — the span-based editor needs literal spans to mutate",span:toSourceSpan(l[1])??c}),null;if(e.declaredBindings.has(u))return a.push({code:"duplicate_declaration",severity:"structural",message:`duplicate defineAsset call for "${u}" — keep one asset declaration`,span:c}),null;e.declaredBindings.add(u);const g=[],y={call:c,config:toSourceSpan(f)??c,libraryItems:[]},b=readUsageInstructions(f),v=readLibraries(f,y,g),w=readVariants(f,g);if(getObjectProperty2(f,"controls"))return a.push({code:"invalid_control",severity:"structural",message:"Move controls to defineControls(Component, controls) in the component file or tempo/controls.ts."}),null;const x=g.filter(e=>"structural"===e.severity);return x.length?(a.push(...x),null):(p&&"none"===p.exportKind&&g.push({code:"not_exported",severity:"degraded",message:`"${u}" is not exported — other files cannot import this asset`,span:c}),{bindingName:u,exportKind:p?p.exportKind:referenceExportKind(m),libraries:v,...void 0===b?{}:{usageInstructions:b},variants:w,...m?{reference:m}:{},spans:y,warnings:g})}function referenceExportKind(e){return"default"===e.importedName?"default":"named"}function classifyMissingBinding(e,t,n,r,s){const i=n.importedBindings.get(e);return void 0!==i?{code:"imported_binding",severity:"structural",message:`"${e}" is a namespace import from "${i}" — declare the asset on a named or default import of the component instead`,span:s}:t.nonSimpleNames.has(e)?{code:"unknown_binding",severity:"structural",message:`"${e}" is not a plain initialized top-level binding — destructured and uninitialized declarations are not supported`,span:s}:hasNestedBinding(r,e)?{code:"non_top_level_binding",severity:"structural",message:`"${e}" is not declared at the top level of the module`,span:s}:{code:"unknown_binding",severity:"structural",message:`no top-level declaration of "${e}" found in this file`,span:s}}function hasNestedBinding(e,t){let n=!1;return walk2(e,e=>{n||"VariableDeclarator"!==e.type&&"FunctionDeclaration"!==e.type&&"ClassDeclaration"!==e.type||"Identifier"!==e.id?.type||e.id.name!==t||(n=!0)}),n}function readUsageInstructions(e){return readStaticStringProperty(e,"usageInstructions")}function readStaticStringProperty(e,t){const n=getObjectProperty2(e,t);if(!n)return;const r=readStaticValue(n.value);return"string"==typeof r?r:void 0}function readLibraries(e,t,n){const r=getObjectProperty2(e,"libraries");if(!r)return[];t.librariesProperty=toSourceSpan(r);const s=unwrapTsExpression2(r.value);if("ArrayExpression"!==s?.type)return n.push({code:"non_literal_library",severity:"degraded",message:"libraries must be an inline array literal of string literals — its entries were dropped",span:toSourceSpan(r.value)??t.librariesProperty}),[];t.libraries=toSourceSpan(s);const i=[];for(const e of s.elements??[]){const r=toSourceSpan(e)??t.libraries,s=readStaticString(e);null!==s?""!==s?i.includes(s)?n.push({code:"duplicate_library",severity:"degraded",message:`duplicate library name "${s}" — deduplicated`,span:r}):(i.push(s),r&&t.libraryItems.push(r)):n.push({code:"empty_library_name",severity:"degraded",message:"libraries entries must be non-empty — dropped an empty entry",span:r}):n.push({code:"non_literal_library",severity:"degraded",message:"libraries entries must be string literals — dropped a non-literal entry",span:r})}return i}function readVariants(e,t){const n=getObjectProperty2(e,"variants");if(!n)return[];const r=unwrapTsExpression2(n.value);if("ObjectExpression"!==r?.type)return t.push({code:"unresolved_prop_value",severity:"degraded",message:"variants is not an inline object literal — variant props are not statically readable",span:toSourceSpan(n.value)??toSourceSpan(n)}),[];const s=r.properties??[];if(0===s.length)return t.push({code:"empty_variants",severity:"degraded",message:"variants is present but empty",span:toSourceSpan(r)}),[];const i=[];for(const e of s){const n="Property"!==e?.type||e.computed?null:readPropertyKeyName2(e.key);null!==n?i.push(readVariant(n,e,t)):t.push({code:"unresolved_prop_value",severity:"degraded",message:"variant names must be identifier or string keys — skipped an entry that is not statically readable",span:toSourceSpan(e)??toSourceSpan(r)})}return i}function readVariant(e,t,n){const r=unwrapTsExpression2(t.value);for(const t of"ObjectExpression"===r?.type?r.properties:[])"Property"===t.type&&!t.computed&&["props","render"].includes(readPropertyKeyName2(t.key)??"")||n.push({code:"invalid_variant_config",severity:"structural",message:`Variant "${e}" accepts either props or render, with explicit keys and no spreads or inheritance`,span:toSourceSpan(t)});const s="ObjectExpression"===r?.type?getObjectProperty2(r,"render"):null,i="ObjectExpression"===r?.type?getObjectProperty2(r,"props"):null,o=unwrapTsExpression2(s?.value),a=unwrapTsExpression2(o?.body),c="TempoJsxValue"===a?.type?readStaticValue(a):tP,l="ArrowFunctionExpression"===o?.type&&!o.async&&0===o.params.length&&!i&&!containsUnresolvedValue(c);s&&!l&&n.push({code:"invalid_variant_config",severity:"structural",message:`Variant "${e}" render must be a parameterless arrow returning static JSX, without props, statements, hooks, callbacks, or computed expressions. Move logic into an imported component.`,span:toSourceSpan(s)});const d=s&&l?{jsx:c}:void 0,u=i?readStaticValue(i.value):d?{}:tP,p=isPlainRecord(u)?u:{},m=!isPlainRecord(u)||containsUnresolvedValue(u);return m&&n.push({code:"unresolved_prop_value",severity:"degraded",message:`variant "${e}" has prop values that are not statically readable`,span:toSourceSpan(t)}),{name:e,props:p,hasUnresolvedValues:m,...d?{render:d}:{}}}function readStaticValue(e){const t=unwrapTsExpression2(e);if(!t)return tP;switch(t.type){case"TempoJsxValue":return t.value;case"Literal":{if(t.regex||t.bigint)return tP;const{value:e}=t;return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:tP}case"TemplateLiteral":{if((t.expressions??[]).length>0)return tP;const e=t.quasis?.[0]?.value?.cooked;return"string"==typeof e?e:tP}case"UnaryExpression":{if("-"!==t.operator)return tP;const e=unwrapTsExpression2(t.argument);return"Literal"===e?.type&&"number"==typeof e.value&&Number.isFinite(e.value)?-e.value:tP}case"ArrayExpression":return(t.elements??[]).map(e=>null==e||"SpreadElement"===e.type?tP:readStaticValue(e));case"ObjectExpression":{const e={};for(const n of t.properties??[]){if("Property"!==n?.type||n.computed)return tP;const t=readPropertyKeyName2(n.key);if(null===t)return tP;Object.defineProperty(e,t,{value:readStaticValue(n.value),enumerable:!0,configurable:!0})}return e}default:return tP}}function readStaticString(e){const t=null==e?tP:readStaticValue(e);return"string"==typeof t?t:null}function isPlainRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!isUnresolvedValue(e)}function containsUnresolvedValue(e){return!!isUnresolvedValue(e)||(Array.isArray(e)?e.some(containsUnresolvedValue):"object"==typeof e&&null!==e&&Object.values(e).some(containsUnresolvedValue))}function statementSpanWithSemicolon(e,t){const n=toSourceSpan(t)??{start:0,end:0};if(";"===e[n.end-1])return n;let r=n.end;for(;r<e.length&&(" "===e[r]||"\t"===e[r]);)r++;return";"===e[r]?{start:n.start,end:r+1}:n}function unwrapTsExpression2(e){let t=e;for(;"TSSatisfiesExpression"===t?.type||"TSAsExpression"===t?.type||"TSNonNullExpression"===t?.type||"ParenthesizedExpression"===t?.type;)t=t.expression;return t}function readPropertyKeyName2(e){if("Identifier"===e?.type)return e.name;if("Literal"===e?.type){if("string"==typeof e.value)return e.value;if("number"==typeof e.value)return String(e.value)}return null}function getObjectProperty2(e,t){if("ObjectExpression"!==e?.type)return null;for(const n of e.properties??[])if("Property"===n?.type&&!n.computed&&readPropertyKeyName2(n.key)===t)return n;return null}function toSourceSpan(e){return"number"==typeof e?.start&&Number.isFinite(e.start)&&"number"==typeof e?.end&&Number.isFinite(e.end)?{start:e.start,end:e.end}:void 0}function walk2(e,t,n=new Set){if(e&&"object"==typeof e&&!n.has(e)){n.add(e),"string"==typeof e.type&&t(e);for(const r of Object.values(e))if(r&&"object"==typeof r)if(Array.isArray(r))for(const e of r)walk2(e,t,n);else walk2(r,t,n)}}function ensureNamedDefaultExport(e){const{program:t,errors:n}=parseAssetProgram(e.filePath,e.source);if(!t)return failure("not_definable",n[0]?.message??"asset source has syntax errors");const r=(t.body??[]).find(e=>"ExportDefaultDeclaration"===e?.type);if(!r)return failure("export_not_found",`no default export in ${e.filePath}`);const s=r.declaration,i="FunctionDeclaration"===s?.type||"ClassDeclaration"===s?.type;if(i&&"string"==typeof s.id?.name)return{ok:!0,source:e.source,changed:!1,bindingName:s.id.name};if(!i){const t=unwrapTsExpression2(s);if("Identifier"===t?.type)return{ok:!0,source:e.source,changed:!1,bindingName:t.name}}const o=toSourceSpan(r),a=toSourceSpan(s);if(!o||!a)return failure("not_definable","default export has no source span");const c=pickAvailableName(deriveDefaultExportName(e.filePath),collectIdentifierNames(t));if(void 0===c)return failure("not_definable","could not derive a free identifier for the default export");const l=detectNewline(e.source);let d;if(i){const t=e.source.slice(a.start,a.start+64),n="FunctionDeclaration"===s.type?t.match(/^(?:async\s+)?function(?:\s*\*)?/):t.match(/^class\b/);if(!n)return failure("not_definable","unsupported default export shape");const r=a.start+n[0].length;let i=r;for(;i<e.source.length&&/\s/.test(e.source[i]??"");)i++;const u="("===e.source[i]?` ${c}`:` ${c} `;d=[{start:o.start,end:a.start,value:""},{start:r,end:i,value:u},{start:o.end,end:o.end,value:`${l}export default ${c};`}]}else d=[{start:o.start,end:a.start,value:`const ${c} = `},{start:a.end,end:o.end,value:`;${l}export default ${c};`}];return{...applyEdits(e.source,d),bindingName:c}}function ensureAssetDeclaration(e){const{program:t,errors:n}=parseAssetProgram(e.filePath,e.source);if(!t)return failure("not_definable",n[0]?.message??"asset source has syntax errors");const r=parseAssetFile(e.filePath,e.source);if(r.declarations.some(t=>t.bindingName===e.bindingName))return{ok:!0,source:e.source,changed:!1};const s=readAssetImports(t);if(hasTopLevelDefineAssetCallFor(t,s.trustedDefineAssetNames,e.bindingName))return failure("config_not_editable",`an existing defineAsset declaration for "${e.bindingName}" has structural errors — fix it instead of adding another`);const i=collectTopLevelScope(t).bindings.get(e.bindingName);if(!i){const t=s.importedBindings.get(e.bindingName);return failure("not_definable",void 0!==t?`"${e.bindingName}" is imported from "${t}" — defineAsset must live in the file that defines the component`:`no top-level binding "${e.bindingName}" in ${e.filePath}`)}const o=detectCodeStyle(e.source),a=[];let c;if(s.trustedDefineAssetNames.size>0)c=s.trustedDefineAssetNames.values().next().value;else{const n=collectIdentifierNames(t);if(n.has("defineAsset")){const e=pickAvailableName("defineAsset",n);if(void 0===e)return failure("not_definable","could not derive a free identifier for the defineAsset import");c=e}else c="defineAsset";const r="defineAsset"===c?"defineAsset":`defineAsset as ${c}`,i=`import { ${r} } from ${quoteString(rP,o.quote)};`;a.push(buildImportInsertionEdit(e.source,s.importDeclarationSpans,i,o.newline))}const l=serializeDefineAssetCall(c,e.bindingName,e.initialConfig??{},o),d=statementInsertionOffset(e.source,i.statementSpan.end);return a.push({start:d,end:d,value:`${o.newline}${o.newline}${l}`}),applyEdits(e.source,a)}function addLibraries(e){const t=locateDeclaration(e);if(!t.ok)return t;const{declaration:n}=t,r=[];for(const t of e.libraries)""!==t&&(n.libraries.includes(t)||r.includes(t)||r.push(t));if(0===r.length)return{ok:!0,source:e.source,changed:!1};const s=detectCodeStyle(e.source),i=r.map(e=>quoteString(e,s.quote)).join(", "),o=n.spans;if(o.libraries){const t=o.libraryItems[o.libraryItems.length-1];if(t)return applyEdits(e.source,[{start:t.end,end:t.end,value:`, ${i}`}]);const n=e.source.slice(o.libraries.start+1,o.libraries.end-1),r=o.libraries.start+1,s=""===n.trim()?i:`${i}, `;return applyEdits(e.source,[{start:r,end:r,value:s}])}return o.librariesProperty?failure("config_not_editable",`the libraries property of "${e.bindingName}" is not an editable array literal`):applyEdits(e.source,[insertConfigProperty(e.source,o.config,`libraries: [${i}]`,s)])}function removeLibraries(e){const t=new Set(e.libraries.filter(e=>""!==e));let n=locateDeclaration(e);if(!n.ok)return n;if(t.size>0&&n.declaration.spans.librariesProperty&&!n.declaration.spans.libraries)return failure("config_not_editable",`the libraries property of "${e.bindingName}" is not an editable array literal`);let r=e.source,s=!1;for(let i=0;i<32;i++){const i=n.declaration,o=[];if(i.libraries.forEach((e,n)=>{const s=i.spans.libraryItems[n];t.has(e)&&s&&o.push(expandListItemRemoval(r,s))}),0===o.length)break;r=spliceRemovals(r,o),s=!0;const a=locateDeclaration({...e,source:r});if(!a.ok)return a;n=a}if(s){const e=n.declaration.spans;e.libraries&&e.librariesProperty&&/^\s*$/.test(r.slice(e.libraries.start+1,e.libraries.end-1))&&(r=spliceRemovals(r,[expandListItemRemoval(r,e.librariesProperty)]))}return{ok:!0,source:r,changed:s}}function locateDeclaration(e){const{program:t,errors:n}=parseAssetProgram(e.filePath,e.source);if(!t)return failure("config_not_editable",n[0]?.message??"asset source has syntax errors");const r=parseAssetFile(e.filePath,e.source),s=r.declarations.find(t=>t.bindingName===e.bindingName);if(s)return{ok:!0,declaration:s};const i=readAssetImports(t);return hasTopLevelDefineAssetCallFor(t,i.trustedDefineAssetNames,e.bindingName)?failure("config_not_editable",`the defineAsset declaration for "${e.bindingName}" has structural errors and cannot be edited`):failure("asset_not_found",`no defineAsset declaration for "${e.bindingName}" in ${e.filePath}`)}function failure(e,t){return{ok:!1,code:e,message:t}}function applyEdits(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e.length+1,s=e;for(const e of n){if(e.start<0||e.end<e.start||e.end>r)throw new Error(`Invalid overlapping asset source edit ${e.start}:${e.end}`);s=s.slice(0,e.start)+e.value+s.slice(e.end),r=e.start}return{ok:!0,source:s,changed:s!==e}}function spliceRemovals(e,t){const n=[...t].sort((e,t)=>e.start-t.start),r=[];for(const e of n){const t=r[r.length-1];t&&e.start<=t.end?t.end=Math.max(t.end,e.end):r.push({...e})}let s=e;for(let e=r.length-1;e>=0;e--){const t=r[e];s=s.slice(0,t.start)+s.slice(t.end)}return s}function expandListItemRemoval(e,t){let{start:n,end:r}=t,s=r;for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(","===e[s]){for(r=s+1;r<e.length&&(" "===e[r]||"\t"===e[r]);)r++;return expandBlankLine(e,{start:n,end:r})}let i=n;for(;i>0&&/\s/.test(e[i-1]??"");)i--;if(","===e[i-1])return{start:i-1,end:r};for(;n>0&&/\s/.test(e[n-1]??"");)n--;for(;r<e.length&&/\s/.test(e[r]??"");)r++;return{start:n,end:r}}function expandBlankLine(e,t){const n=e.lastIndexOf("\n",t.start-1)+1;return/^[ \t]*$/.test(e.slice(n,t.start))?e.startsWith("\r\n",t.end)?{start:n,end:t.end+2}:"\n"===e[t.end]?{start:n,end:t.end+1}:t:t}function insertConfigProperty(e,t,n,r){const s=t.end-1;let i=s;for(;i>t.start+1&&/\s/.test(e[i-1]??"");)i--;const o=e[i-1]??"",a=e.slice(t.start,t.end).includes("\n");if(!a)return"{"===o?{start:i,end:s,value:` ${n} `}:{start:i,end:i,value:","===o?` ${n}`:`, ${n}`};if("{"===o){const s=lineIndentAt(e,t.start);return{start:i,end:i,value:`${r.newline}${s}${r.indent}${n},`}}const c=lineIndentAt(e,i);return{start:i,end:i,value:`${","===o?"":","}${r.newline}${c}${n},`}}function buildImportInsertionEdit(e,t,n,r){const s=t[t.length-1];if(s)return{start:s.end,end:s.end,value:`${r}${n}`};const i=topLevelInsertionOffset(e),o=e[i]??"",a=i>0?r:"",c="\n"===o||"\r"===o||""===o?r:`${r}${r}`;return{start:i,end:i,value:`${a}${n}${c}`}}function topLevelInsertionOffset(e){let t=0;if(e.startsWith("#!")){const n=e.indexOf("\n");t=n>=0?n+1:e.length}for(;;){const n=e.indexOf("\n",t),r=n>=0?n+1:e.length,s=e.slice(t,r).trim();if(!/^["']use [^"']+["'];?$/.test(s))break;t=r}return t}function statementInsertionOffset(e,t){let n=t;for(;n<e.length&&(" "===e[n]||"\t"===e[n]);)n++;if("/"===e[n]&&"/"===e[n+1]){for(;n<e.length&&"\n"!==e[n]&&"\r"!==e[n];)n++;return n}return t}function serializeDefineAssetCall(e,t,n,r){const s=[];if(void 0!==n.usageInstructions&&s.push(["usageInstructions",n.usageInstructions]),void 0!==n.libraries&&s.push(["libraries",n.libraries]),void 0!==n.variants&&s.push(["variants",n.variants]),0===s.length)return`${e}(${t}, {});`;const i=s.map(([e,t])=>`${r.indent}${e}: ${serializeStaticValue(t,r,1)},`).join(r.newline);return`${e}(${t}, {${r.newline}${i}${r.newline}});`}function serializeStaticValue(e,t,n){if(isUnresolvedValue(e))throw new Error("ensureAssetDeclaration initialConfig values must be fully static");if(null===e)return"null";if("string"==typeof e)return quoteString(e,t.quote);if("number"==typeof e||"boolean"==typeof e)return String(e);if(Array.isArray(e)){if(0===e.length)return"[]";if(e.every(isPrimitiveStaticValue))return`[${e.map(e=>serializeStaticValue(e,t,n)).join(", ")}]`;const r=e.map(e=>`${t.indent.repeat(n+1)}${serializeStaticValue(e,t,n+1)},`).join(t.newline);return`[${t.newline}${r}${t.newline}${t.indent.repeat(n)}]`}const r=Object.entries(e);if(0===r.length)return"{}";if(r.every(([,e])=>isPrimitiveStaticValue(e)))return`{ ${r.map(([e,r])=>`${serializeObjectKey(e,t)}: ${serializeStaticValue(r,t,n)}`).join(", ")} }`;const s=r.map(([e,r])=>`${t.indent.repeat(n+1)}${serializeObjectKey(e,t)}: ${serializeStaticValue(r,t,n+1)},`).join(t.newline);return`{${t.newline}${s}${t.newline}${t.indent.repeat(n)}}`}function isPrimitiveStaticValue(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function serializeObjectKey(e,t){return/^[A-Za-z_$][\w$]*$/.test(e)?e:quoteString(e,t.quote)}function quoteString(e,t){const n=JSON.stringify(e);if('"'===t)return n;const r=n.slice(1,-1).replace(/\\"/g,'"').replace(/'/g,"\\'");return`'${r}'`}function detectCodeStyle(e){const t=(e.match(/"/g)??[]).length,n=(e.match(/'/g)??[]).length;let r=!1,s=Number.POSITIVE_INFINITY;for(const t of e.split("\n")){const e=t.match(/^([ \t]+)\S/);if(e){if(e[1].includes("\t")){r=!0;break}s=Math.min(s,e[1].length)}}return{quote:n>t?"'":'"',indent:r?"\t":Number.isFinite(s)?" ".repeat(s):" ",newline:detectNewline(e)}}function detectNewline(e){return e.includes("\r\n")?"\r\n":"\n"}function lineIndentAt(e,t){const n=Math.max(e.lastIndexOf("\n",t-1)+1,0),r=e.slice(n,t);return r.match(/^[ \t]*/)?.[0]??""}function pickAvailableName(e,t){if(!t.has(e))return e;for(let n=2;n<1e4;n++){const r=`${e}${n}`;if(!t.has(r))return r}}function deriveDefaultExportName(e){const t=e.replace(/\\/g,"/"),n=t.split("/").filter(Boolean),r=n[n.length-1]??"";if(/^index\.canvas\.[tj]sx?$/.test(r)){const e=n[n.length-2]??"",t=pascalCase(e);return""===t?"Canvas":`${t}Canvas`}const s=pascalCase(r.replace(/\.[tj]sx?$/,""));return""===s?"DefaultExport":/^[0-9]/.test(s)?`Component${s}`:s}function pascalCase(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function makeAssetKey(e,t){return`${e}#${t}`}function parseAssetKey(e){const t=e.lastIndexOf("#");if(!(t<=0||t===e.length-1))return{filePath:e.slice(0,t),bindingName:e.slice(t+1)}}import{readFileSync as sP,statSync as iP}from"fs";import oP from"path";import{readdir as aP,readFile as cP}from"fs/promises";import lP from"path";import dP from"typescript";import{readdir as uP,readFile as pP}from"fs/promises";import hP from"path";var mP=[".tsx",".ts",".jsx",".js",".astro"],fP="defineAsset";function hasAssetSourceExtension(e){return mP.some(t=>e.endsWith(t))}function sourceMayDeclareAssets(e){return e.includes(fP)||e.includes("defineControls")||e.includes("defineAstroControls")}var gP=new Set(["node_modules","dist","build"]);function isIgnoredSegment(e){return gP.has(e)||e.startsWith(".")&&"."!==e&&".."!==e}function isIgnoredWorkspacePath(e){return e.replace(/\\/g,"/").split("/").some(isIgnoredSegment)}async function scanRepo(e){const t=[];async function walk4(n){let r;try{r=await uP(n,{withFileTypes:!0})}catch{return}for(const s of r){if(isIgnoredSegment(s.name))continue;const r=hP.join(n,s.name);if(s.isDirectory()){await walk4(r);continue}if(!s.isFile()||!hasAssetSourceExtension(s.name))continue;let i;try{i=await pP(r,"utf8")}catch{continue}sourceMayDeclareAssets(i)&&t.push({filePath:hP.relative(e,r).replace(/\\/g,"/"),source:i})}}return await walk4(e),t.sort((e,t)=>e.filePath.localeCompare(t.filePath))}function resolveProjectModule(e,t,n="index.ts"){const r="/__tempo_workspace__/",read2=t=>t.startsWith(r)?e.readFile(t.slice(r.length))??void 0:void 0,s={fileExists:e=>void 0!==read2(e),readFile:read2},i=dP.findConfigFile(lP.posix.dirname(r+n),s.fileExists,"tsconfig.json");let o={moduleResolution:dP.ModuleResolutionKind.Bundler,allowJs:!0};if(i){const e=dP.readConfigFile(i,read2);e.error||(o={...o,...dP.parseJsonConfigFileContent(e.config,{...s,useCaseSensitiveFileNames:!0,readDirectory:()=>[]},lP.posix.dirname(i)).options})}const a=dP.resolveModuleName(t,r+n,o,s).resolvedModule?.resolvedFileName;return a?.startsWith(r)?a.slice(r.length):null}function definesVueComponent(e,t,n){if(!/\.[cm]?[jt]sx?$/.test(t)||t.endsWith(".d.ts"))return!1;const r=e.readFile(t);if(null===r)return!1;const s=dP.createSourceFile(t,r,dP.ScriptTarget.Latest,!0,/x$/.test(t)?dP.ScriptKind.TSX:dP.ScriptKind.TS),i=new Set,o=new Set,a=new Map;let c=null;for(const e of s.statements)if(dP.isImportDeclaration(e)){const t=e.moduleSpecifier,n=e.importClause?.namedBindings;if(!dP.isStringLiteral(t)||"vue"!==t.text||!n)continue;if(dP.isNamespaceImport(n))o.add(n.name.text);else for(const e of n.elements)"defineComponent"===(e.propertyName??e.name).text&&i.add(e.name.text)}else if(dP.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===dP.SyntaxKind.ExportKeyword);for(const r of e.declarationList.declarations)dP.isIdentifier(r.name)&&r.initializer&&(a.set(r.name.text,r.initializer),t&&r.name.text===n&&(c=r.initializer))}else if(dP.isExportAssignment(e)&&!e.isExportEquals&&"default"===n)c=e.expression;else if(dP.isExportDeclaration(e)&&!e.moduleSpecifier&&e.exportClause&&dP.isNamedExports(e.exportClause))for(const t of e.exportClause.elements)t.name.text===n&&(c=dP.factory.createIdentifier((t.propertyName??t.name).text));c??=a.get(n)??null;for(let e=0;c&&e<8;e+=1)if(dP.isIdentifier(c))c=a.get(c.text)??null;else{if(!(dP.isParenthesizedExpression(c)||dP.isAsExpression(c)||dP.isSatisfiesExpression(c)||dP.isNonNullExpression(c)))break;c=c.expression}if(!c||!dP.isCallExpression(c))return!1;const l=c.expression;return dP.isIdentifier(l)?i.has(l.text):dP.isPropertyAccessExpression(l)&&dP.isIdentifier(l.expression)&&o.has(l.expression.text)&&"defineComponent"===l.name.text}function installedPackageFramework(e,t,n){const r=n?.match(/^node_modules\/((?:@[^/]+\/)?[^/]+)\//)?.[1],s=r??(t.startsWith("pkg:")&&null===n?parsePackageSpecifier(t.slice(4)).packageName:null);if(!s)return null;const i=e.readFile(`node_modules/${s}/package.json`);if(null===i)return null;let o;try{const e=JSON.parse(i);o={...e.dependencies,...e.peerDependencies}}catch{return null}const writesFor=e=>void 0!==o[e];return!writesFor("vue")||writesFor("react")||writesFor("react-dom")?null:"vue"}var yP=4;function posixDirname(e){const t=e.lastIndexOf("/");return-1===t?".":e.slice(0,t)}function isRelativeSpecifier(e){return e.startsWith("./")||e.startsWith("../")}function resolveRelativeImport(e,t){const n="."===e?t:`${e}/${t}`,r=[];for(const e of n.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.length>0&&".."!==r[r.length-1]?r.pop():r.push(".."));return r.join("/")}var bP=[".tsx",".ts",".jsx",".js",".astro"],vP=Object.values(Gb).flatMap(e=>e.uiFramework&&e.componentFileExtension?[e.componentFileExtension]:[]);function isSingleFileComponent(e){return vP.some(t=>e.endsWith(t))}function moduleFileCandidates(e){if(e=componentImportPath(e),e.endsWith(".ts")||e.endsWith(".tsx")||isSingleFileComponent(e))return[e];if(e.endsWith(".js")){const t=e.slice(0,-3);return[`${t}.ts`,`${t}.tsx`,e]}return e.endsWith(".jsx")?[`${e.slice(0,-4)}.tsx`,e]:[...bP.map(t=>`${e}${t}`),...bP.map(t=>`${e}/index${t}`)]}function resolveModuleFilePath(e,t){const n=t.replace(/^\.\//,"");if(""===n||n.startsWith("../"))return null;for(const t of moduleFileCandidates(n))if(null!=e(t))return t;return null}var wP=2e3,_P=6;function parsePnpmWorkspacePatterns(e){const t=e.split(/\r?\n/),n=[];let r=!1;for(const e of t){if(/^packages\s*:\s*$/.test(e)){r=!0;continue}if(!r)continue;const t=e.trim();if(""===t||t.startsWith("#"))continue;const s=/^-\s*(.+)$/.exec(t);if(!s)break;const i=s[1].replace(/\s+#.*$/,"").trim().replace(/^["']|["']$/g,"");""===i||i.startsWith("!")||n.push(i)}return n}function globSegmentToRegExp(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,"[^/]*");return new RegExp(`^${t}$`)}async function loadPnpmWorkspacePackages(e){let t;try{t=await cP(lP.join(e,"pnpm-workspace.yaml"),"utf-8")}catch{return{}}const n={};let r=0;async function listSubdirectories(t){if(r>=wP)return[];let n;r++;try{n=await aP(lP.join(e,t),{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(e=>e.name).filter(e=>!isIgnoredWorkspacePath(e))}async function recordPackageAt(t){let r;try{r=await cP(lP.join(e,t,"package.json"),"utf-8")}catch{return}try{const e=JSON.parse(r).name;"string"!=typeof e||""===e||e in n||(n[e]=t.replace(/\\/g,"/"))}catch{}}async function expand(e,t,n){if(n>_P)return;if(0===t.length)return void(""!==e&&await recordPackageAt(e));const[r,...s]=t;if("**"!==r){if(r.includes("*")){const t=globSegmentToRegExp(r);for(const r of await listSubdirectories(e))t.test(r)&&await expand(joinRelative(e,r),s,n+1);return}await expand(joinRelative(e,r),s,n+1)}else{await expand(e,s,n);for(const r of await listSubdirectories(e))await expand(joinRelative(e,r),t,n+1)}}for(const e of parsePnpmWorkspacePatterns(t))await expand("",e.split("/").filter(Boolean),0);return n}function joinRelative(e,t){return""===e?t:`${e}/${t}`}function parsePackageSpecifier(e){const t=e.split("/"),n=e.startsWith("@")?2:1,r=t.slice(0,n).join("/"),s=t.slice(n).join("/");return""===s?{packageName:r}:{packageName:r,subpath:s}}function collectExportTargets(e,t=0){return"string"==typeof e?[e]:t>=3||null===e||"object"!=typeof e?[]:Object.values(e).flatMap(e=>collectExportTargets(e,t+1))}function resolvePackageEntryFile(e,t){const{packageName:n,subpath:r}=parsePackageSpecifier(t),s=e.workspacePackages?.[n];if(void 0===s)return resolveProjectModule(e,t);if(void 0!==r)return resolveModuleFilePath(e.readFile,`${s}/${r}`);const i=e.readFile(`${s}/package.json`);if(null!=i){let t;try{t=JSON.parse(i)}catch{t=void 0}if(t){const n=t.exports,r="string"==typeof n?n:null!=n&&"object"==typeof n?n["."]:void 0,i=[...collectExportTargets(r),..."string"==typeof t.module?[t.module]:[],..."string"==typeof t.main?[t.main]:[]];for(const t of i){const n=resolveModuleFilePath(e.readFile,`${s}/${t.replace(/^\.\//,"")}`);if(null!==n)return n}}}return resolveModuleFilePath(e.readFile,`${s}/index`)??resolveModuleFilePath(e.readFile,`${s}/src/index`)}function patternDeclaresName(e,t){return!(!e||"object"!=typeof e)&&("Identifier"===e.type?e.name===t:"ObjectPattern"===e.type?(e.properties??[]).some(e=>patternDeclaresName(e?.value??e?.argument,t)):"ArrayPattern"===e.type?(e.elements??[]).some(e=>patternDeclaresName(e,t)):"AssignmentPattern"===e.type?patternDeclaresName(e.left,t):"RestElement"===e.type&&patternDeclaresName(e.argument,t))}function declarationDeclaresName(e,t){return"FunctionDeclaration"===e?.type||"ClassDeclaration"===e?.type||"TSEnumDeclaration"===e?.type?e.id?.name===t:"VariableDeclaration"===e?.type&&(e.declarations??[]).some(e=>patternDeclaresName(e?.id,t))}function specifierName(e){return e?.name??e?.value}function findExportInProgram(e,t){const n=[];for(const r of e?.body??[]){if("ExportDefaultDeclaration"===r?.type){if("default"!==t)continue;const e=unwrapTsExpression2(r.declaration);return"Identifier"===e?.type?{finding:{type:"local",localName:e.name},starSources:n}:{finding:{type:"defined",localName:e?.id?.name??t},starSources:n}}if("ExportNamedDeclaration"!==r?.type)"ExportAllDeclaration"===r?.type&&null==r.exported&&"string"==typeof r.source?.value&&"default"!==t&&n.push(r.source.value);else{if(r.declaration&&declarationDeclaresName(r.declaration,t))return{finding:{type:"defined",localName:t},starSources:n};for(const e of r.specifiers??[]){if("ExportSpecifier"!==e?.type)continue;if(specifierName(e.exported)!==t)continue;const s=specifierName(e.local);if("string"==typeof s)return"string"==typeof r.source?.value?{finding:{type:"reexport",specifier:r.source.value,sourceName:s},starSources:n}:{finding:{type:"local",localName:s},starSources:n}}}}return{finding:null,starSources:n}}function followExportChain(e,t,n,r,s){const i=`${t}#${n}`;if(s.has(i))return null;s.add(i);const o=e.readFile(t);if(null==o)return null;if(isSingleFileComponent(t)&&"default"===n)return{filePath:t,name:"default"};const{program:a}=(e.parseProgram??parseAssetProgram)(t,o);if(!a)return null;const{finding:c,starSources:l}=findExportInProgram(a,n),hop=(n,i)=>{if(r<=0)return null;const o=resolveChainSpecifier(e,t,n);return null===o?null:followExportChain(e,o,i,r-1,s)};if("defined"===c?.type)return{filePath:t,name:c.localName??n};if("reexport"===c?.type)return hop(c.specifier,c.sourceName);if("local"===c?.type){const e=readAssetImports(a).referenceableImports.get(c.localName);return e?hop(e.importSpecifier,e.importedName):{filePath:t,name:c.localName}}for(const e of l){const t=hop(e,n);if(null!==t)return t}return null}function resolveChainSpecifier(e,t,n){return isRelativeSpecifier(n)?resolveModuleFilePath(e.readFile,resolveRelativeImport(posixDirname(t),n)):resolvePackageEntryFile(e,n)}function resolveComponentIdentity(e,t,n,r){const s=t.startsWith("pkg:")?resolvePackageEntryFile(e,t.slice(4))??resolveProjectModule(e,t.slice(4),r):resolveModuleFilePath(e.readFile,t);return s?followExportChain(e,s,n,yP,new Set):null}function resolveComponentFilePath(e,t,n){return resolveComponentIdentity(e,t,n)?.filePath??(t.startsWith("pkg:")?null:resolveModuleFilePath(e.readFile,t))}function canvasPointerDocLine(e){return`The canvas for this component is at ${e}/index.canvas.tsx. If you adjust this component in any way, ensure the canvas and its asset declaration stay consistent.`}function escapeRegExp3(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function verifyCanvasPointer(e,t,n){const r=n.canvasPath;if(void 0===r)return{warnings:[]};const s=parseAssetKey(n.key)?.bindingName;if(void 0===s)return{warnings:[]};const unverified2=e=>({warnings:[{code:"canvas_pointer_unverified",severity:"info",message:`canvas pointer not verified for "${n.key}": ${e}`}]}),i=resolveComponentFilePath(e,n.filePath,s);if(null===i)return unverified2(`could not resolve the component's defining file from "${n.filePath}"`);const o=e.readFile(i),a=null==o?null:(e.readComments??readSourceComments)(i,o);if(null===a)return{componentFilePath:i,warnings:unverified2(`could not read comments in "${i}"`).warnings};const c=new RegExp(`${escapeRegExp3(t)}/[\\w@./-]+`,"g");let l=!1;const d=[];for(const e of a)for(const t of e.value.matchAll(c)){const e=t[0].replace(/[.,;:]+$/,"");e===r||e.startsWith(`${r}/`)?l=!0:d.includes(e)||d.push(e)}return l?{componentFilePath:i,warnings:[]}:d.length>0?{componentFilePath:i,warnings:[{code:"stale_canvas_pointer",severity:"degraded",message:`"${i}" has a canvas-pointer comment naming "${d[0]}", but this component is declared on "${r}" — update the comment to: ${canvasPointerDocLine(r)}`}]}:{componentFilePath:i,warnings:[{code:"missing_canvas_pointer",severity:"degraded",message:`"${i}" has no comment mentioning its canvas — add a docstring line to the component's documentation: ${canvasPointerDocLine(r)}`}]}}import{createHash as xP}from"crypto";import{posix as TP}from"path";import{createRequire as kP}from"module";import SP from"path";import{fileURLToPath as EP}from"url";var AP="@tempo-home",CP=`// ${AP} — Tempo home canvas (the workspace Run button opens this). Managed marker; do not remove.`;function sourceHasHomeMarker(e){return e.includes(AP)}var IP=600,PP=400,DP=50,RP=3e3;function overlapsWithSpacing(e,t,n){return!(e.x+e.width+n<=t.x||t.x+t.width+n<=e.x||e.y+e.height+n<=t.y||t.y+t.height+n<=e.y)}function hasOverlap(e,t,n){return e.some(e=>overlapsWithSpacing(e,t,n))}function findOpenPosition(e,t,n,r,s){if(0===e.length)return{x:0,y:0};const i=Math.max(...e.map(e=>e.x+e.width)),o=Math.max(...e.map(e=>e.y+e.height)),a=i+r,c=0;if(a+t<=s){const s={x:a,y:c,width:t,height:n};if(!hasOverlap(e,s,r))return{x:a,y:c}}return{x:0,y:o+r}}function computeStoryboardPositions(e){const t=e.spacing??DP,n=e.maxRowWidth??RP,r=[...e.existing],s=[];for(const i of e.newStoryboards){const e=Number.isFinite(i.width)?Math.max(1,Math.round(i.width)):IP,o=Number.isFinite(i.height)?Math.max(1,Math.round(i.height)):PP,a=findOpenPosition(r,e,o,t,n);r.push({x:a.x,y:a.y,width:e,height:o}),s.push({name:i.name,x:a.x,y:a.y,width:e,height:o})}return s}var NP="undefined"!=typeof __filename?__filename:EP(import.meta.url),OP=SP.dirname(NP),FP=kP(NP);function loadParseSync(){try{const e=FP("oxc-parser");return e.parseSync}catch{const e=[SP.resolve(OP,"../../modules/file-parser/node_modules/oxc-parser"),SP.resolve(OP,"../../../../node_modules/.pnpm/node_modules/oxc-parser"),SP.resolve(process.cwd(),"../../node_modules/.pnpm/node_modules/oxc-parser")];for(const t of e)try{const e=FP(t);return e.parseSync}catch{continue}throw new Error("Unable to resolve oxc-parser for canvas page parsing")}}var LP=loadParseSync(),MP={x:0,y:0,width:600,height:400};function hasReactCanvasDeclaration(e){return void 0!==e.canvasElementSpan}function toLegacyLayoutSpans(e){if(e?.x&&e.y&&"number"==typeof e.layoutClose)return{x:e.x,y:e.y,width:e.width,height:e.height,...e.zIndex?{zIndex:e.zIndex}:{},layoutClose:e.layoutClose}}function adaptReactCanvasPage(e,t){const n=parseCanvasFile(e,t);return hasReactCanvasDeclaration(n)?{filePath:e,canvasFormat:"react",...n.canvasPath?{canvasPath:n.canvasPath}:{},pageName:n.pageName,home:sourceHasHomeMarker(t),...void 0!==n.backgroundColor?{backgroundColor:n.backgroundColor}:{},storyboards:n.storyboards.map((e,t)=>{const n=e.storyboardKey||`__invalid_react_storyboard_${t}`,r=componentFrameworkForStoryboard(e);return{exportName:n,canvasFormat:"react",storyboardKey:e.storyboardKey,...r?{uiFramework:r}:{},displayName:e.displayName,layout:e.layout,isRoute:"route"===e.kind,..."html"===e.kind?{isHtml:!0}:{},...e.route?{route:e.route}:{},...e.filepath?{filepath:e.filepath}:{},...e.vrt?{vrt:!0,vrtConfig:e.vrt}:{},...e.responsive?{responsive:!0}:{},...e.preview?{preview:e.preview}:{},layoutSpans:toLegacyLayoutSpans(e.layoutSpans),...e.errors.length>0?{error:e.errors.map(e=>e.message).join("; ")}:{},exportSpan:e.jsxElementSpan,...e.component?.expression?{componentExpression:e.component.expression}:{},...e.component?.import?{componentImport:{localName:e.component.import.localName,specifier:e.component.import.source,span:e.component.import.declarationSpan}}:{}}}),errors:n.errors.map(e=>({message:e.message,kind:e.kind}))}:null}function isObjectExpression(e){return e&&"ObjectExpression"===e.type&&Array.isArray(e.properties)}function toIdentifierName(e){return e?"Identifier"===e.type?e.name:"Literal"===e.type&&"string"==typeof e.value?e.value:null:null}function getObjectProperty3(e,t){if(!isObjectExpression(e))return null;for(const n of e.properties){if(!n||"Property"!==n.type)continue;const e=toIdentifierName(n.key);if(e===t)return n}return null}function readStringLiteral(e,t,n){if("Literal"===e?.type&&"string"==typeof e.value)return e.value;throw new Error(`Non-literal \`${t}\` property in "${n}" — ${t} must be a string literal`)}function readNumberLiteral2(e,t,n){if("Literal"===e?.type&&"number"==typeof e.value&&Number.isFinite(e.value))return{value:e.value,start:e.start,end:e.end};if("UnaryExpression"===e?.type&&"-"===e.operator&&"Literal"===e.argument?.type&&"number"==typeof e.argument.value&&Number.isFinite(e.argument.value))return{value:-e.argument.value,start:e.start,end:e.end};throw new Error(`Layout values must be number literals, found non-literal value for \`${t}\` in "${n}"`)}function readLayout2(e,t,n){const r=getObjectProperty3(e,"layout");if(!r)throw new Error(`Missing required \`layout\` property in "${t}"`);if(!isObjectExpression(r.value))throw new Error(`Storyboard "${t}" has invalid \`layout\` shape`);const s=getObjectProperty3(r.value,"x"),i=getObjectProperty3(r.value,"y"),o=getObjectProperty3(r.value,"width"),a=getObjectProperty3(r.value,"height"),c=Boolean(o&&a),l=!s||!i,d=!n&&!c,u=l||d;if(u)throw new Error(`Storyboard "${t}" layout must include x, y, width, and height`);const p=readNumberLiteral2(s.value,"x",t),m=readNumberLiteral2(i.value,"y",t),f=getObjectProperty3(r.value,"zIndex"),g=f?readNumberLiteral2(f.value,"zIndex",t):null,y=getObjectProperty3(r.value,"intrinsicSizing"),b=y?readStringLiteral(y.value,"layout.intrinsicSizing",t):null;if(null!==b&&"root-element"!==b)throw new Error(`Storyboard "${t}" \`layout.intrinsicSizing\` must be "root-element" when set`);const v="root-element"===b,w=n&&(v||!c),x=n&&Boolean(o)!==Boolean(a)?"layout.width and layout.height must be set together":void 0,S=w?null:readNumberLiteral2(o.value,"width",t),E=w?null:readNumberLiteral2(a.value,"height",t),A=readNumber(r.value.end);if(null===A)throw new Error(`Storyboard "${t}" layout literal missing position info`);const C={x:{start:p.start,end:p.end},y:{start:m.start,end:m.end},...S?{width:{start:S.start,end:S.end}}:{},...E?{height:{start:E.start,end:E.end}}:{},...g?{zIndex:{start:g.start,end:g.end}}:{},layoutClose:A-1};return{layout:{x:p.value,y:m.value,...S?{width:S.value}:{},...E?{height:E.value}:{},...g?{zIndex:g.value}:{}},spans:C,...x?{error:x}:{}}}function readNumber(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function extractTypeName(e){if(!e||"TSTypeReference"!==e.type)return null;const t=e.typeName;return t?"Identifier"===t.type?t.name:"TSQualifiedName"===t.type&&"Identifier"===t.right?.type?t.right.name:null:null}function collectComponentImports(e){const t=new Map;for(const n of e){if("ImportDeclaration"!==n?.type)continue;const e=n.source?.value;if("string"!=typeof e)continue;const r={start:n.start,end:n.end};for(const s of n.specifiers??[]){const n=s?.local?.name;"string"==typeof n&&t.set(n,{localName:n,specifier:e,span:r})}}return t}function extractRenderIdentifier(e){if(!e||"ArrowFunctionExpression"!==e.type)return null;const t=e.body;if(!t||"JSXElement"!==t.type)return null;const n=t.openingElement?.name;return n&&"JSXIdentifier"===n.type&&"string"==typeof n.name?n.name:null}function collectVariableBindings(e){const t=new Map,collectFromVariableDeclaration=e=>{if(e&&"VariableDeclaration"===e.type)for(const n of e.declarations??[]){if("Identifier"!==n?.id?.type)continue;const e=n.id.name;t.set(e,{init:n.init,typeAnnotation:n.id.typeAnnotation?.typeAnnotation??null})}};for(const t of e)collectFromVariableDeclaration(t),"ExportNamedDeclaration"===t?.type&&"VariableDeclaration"===t.declaration?.type&&collectFromVariableDeclaration(t.declaration);return t}function resolvePageNameFromObject(e){if(!isObjectExpression(e))return null;const t=getObjectProperty3(e,"name");return t&&"Literal"===t.value?.type&&"string"==typeof t.value.value?t.value.value:null}function resolvePageBackgroundColorFromObject(e){const t=getObjectProperty3(e,"backgroundColor");if(!t||"number"!=typeof t.start||"number"!=typeof t.end)return null;const n={start:t.start,end:t.end};return"Literal"===t.value?.type&&"string"==typeof t.value.value&&"number"==typeof t.value.start&&"number"==typeof t.value.end?{value:t.value.value,valueSpan:{start:t.value.start,end:t.value.end},propertySpan:n}:{propertySpan:n}}function parseStoryboardFromBinding(e){const t=extractTypeName(e.binding.typeAnnotation),n="TempoStoryboard"===t,r="TempoRouteStoryboard"===t,s="TempoHtmlStoryboard"===t;if(!n&&!r&&!s)return null;try{if(!isObjectExpression(e.binding.init))throw new Error(`Could not parse storyboard export "${e.exportName}" — expected object literal`);const t=readLayout2(e.binding.init,e.exportName,n),i=getObjectProperty3(e.binding.init,"name"),o=i?readStringLiteral(i.value,"name",e.exportName):void 0;let a,c,l,d;if(r){const t=getObjectProperty3(e.binding.init,"route");if(!t)throw new Error(`Route storyboard "${e.exportName}" is missing required \`route\` property`);a=readStringLiteral(t.value,"route",e.exportName)}if(s){const t=getObjectProperty3(e.binding.init,"filepath");if(!t)throw new Error(`Html storyboard "${e.exportName}" is missing required \`filepath\` property`);d=readStringLiteral(t.value,"filepath",e.exportName)}if(n){const t=getObjectProperty3(e.binding.init,"render");if(!t)throw new Error(`Component storyboard "${e.exportName}" is missing required \`render\` property`);const n=extractRenderIdentifier(t.value);n&&(l=e.componentImports.get(n),(l||/^[A-Z]/.test(n))&&(c=n))}return{exportName:e.exportName,displayName:o,layout:t.layout,isRoute:r,...s?{isHtml:!0}:{},...a?{route:a}:{},...d?{filepath:d}:{},layoutSpans:t.spans,...t.error?{error:t.error}:{},...c?{componentExpression:c}:{},...l?{componentImport:l}:{}}}catch(t){const i=t instanceof Error?t.message:String(t);return{exportName:e.exportName,displayName:void 0,layout:n?{x:0,y:0}:MP,isRoute:r,...s?{isHtml:!0}:{},error:i}}}function collectStoryboardExports(e,t,n){const r=[],s=new Set,maybePushStoryboard=(e,t,i)=>{if(s.has(e))return;const o=parseStoryboardFromBinding({exportName:e,binding:t,componentImports:n});o&&(i&&(o.exportSpan=i),s.add(e),r.push(o))};for(const n of e){if("ExportNamedDeclaration"!==n?.type)continue;const e={start:n.start,end:n.end};if("VariableDeclaration"!==n.declaration?.type){if(Array.isArray(n.specifiers)&&!n.source)for(const r of n.specifiers){const n=toIdentifierName(r.local),s=toIdentifierName(r.exported??r.local);if(!n||!s)continue;const i=t.get(n);i&&maybePushStoryboard(s,i,e)}}else for(const r of n.declaration.declarations??[]){if("Identifier"!==r?.id?.type)continue;const n=t.get(r.id.name);n&&maybePushStoryboard(r.id.name,n,e)}}return r}function parsePageSource(e,t){const n=adaptReactCanvasPage(e,t);if(n)return n;const r=SP.basename(SP.dirname(e)),s=[],i=LP(e,t),o=Array.isArray(i.program?.body)?i.program.body:[],a=collectVariableBindings(o),c=collectComponentImports(o);let l=r,d=!1;const u=sourceHasHomeMarker(t);let p,m,f=null;for(const e of o){if("ExportDefaultDeclaration"!==e?.type)continue;const t=e.declaration;if(isObjectExpression(t))f=t;else if("Identifier"===t?.type){const e=a.get(t.name);e&&isObjectExpression(e.init)&&(f=e.init)}break}if(f){const e=resolvePageNameFromObject(f);e&&(l=e,d=!0);const t=resolvePageBackgroundColorFromObject(f);void 0!==t?.value&&(p=t.value);const n=readNumber(f.end);null!==n&&(m={pageObjectClose:n-1,...t?.valueSpan?{backgroundColor:t.valueSpan}:{},...t?.propertySpan?{backgroundColorProperty:t.propertySpan}:{}})}d||s.push({message:"Canvas default export name could not be parsed; falling back to canvas folder name",kind:"degraded"});const g=collectStoryboardExports(o,a,c);for(const e of g)e.error&&s.push({exportName:e.exportName,message:e.error,kind:"degraded"});return{filePath:e,pageName:l,home:u,...void 0!==p?{backgroundColor:p}:{},...m?{pageConfigSpans:m}:{},storyboards:g,errors:s}}function toStoryboardRects(e){return e.storyboards.filter(e=>!e.error).map(e=>{const{x:t,y:n,zIndex:r}=e.layout,s=e.layout.width??IP,i=e.layout.height??PP;return{x:t,y:n,width:s,height:i,...null!=r?{zIndex:r}:{}}})}var UP="tempo/designs";function hashSource(e){return xP("sha256").update(e).digest("hex")}function isCanvasPageFile(e,t){return e.startsWith(`${t}/`)&&"index.canvas.tsx"===e.split("/").pop()}function referenceIdentityPath(e,t){return t=t.replace(/(\.astro)\?tempo-component$/,"$1"),isRelativeSpecifier(t)?resolveRelativeImport(posixDirname(e),t):`pkg:${t}`}function parsedPageName(e){try{return parsePageSource(e.filePath,e.source).pageName||void 0}catch{return}}function referenceDeclarationToEntry(e,t,n,r,s){const i=referenceIdentityPath(n.filePath,t.importSpecifier);return{key:makeAssetKey(i,t.importedName),kind:"component",name:"default"===t.importedName?e.bindingName:t.importedName,filePath:i,exportKind:e.exportKind,libraries:e.libraries,...void 0!==e.usageInstructions?{usageInstructions:e.usageInstructions}:{},variants:e.variants,warnings:[...e.warnings],...s?{canvasPath:posixDirname(n.filePath)}:{},...void 0!==r?{canvasName:r}:{},declaredIn:n.filePath,declaredBindingName:e.bindingName}}function declarationToEntry(e,t,n){const r=isCanvasPageFile(t.filePath,n),s=[...e.warnings];let i,o=e.variants;if(r){o.length>0&&(s.push({code:"variants_on_canvas",message:"`variants` is ignored on a canvas asset — a canvas component takes no props",severity:"degraded",span:e.spans.config}),o=[]);const n=parsePageSource(t.filePath,t.source);i={pageName:n.pageName,pageFolderPath:posixDirname(t.filePath)}}return{key:makeAssetKey(t.filePath,e.bindingName),kind:r?"canvas":"component",name:e.bindingName,filePath:t.filePath,exportKind:e.exportKind,libraries:e.libraries,...void 0!==e.usageInstructions?{usageInstructions:e.usageInstructions}:{},variants:o,warnings:s,...i?{canvas:i}:{}}}function fileToIndexedParts(e,t){const n=[],r=e.parsed.errors.filter(e=>"structural"===e.severity),s=e.filePath.startsWith(`${t}/`),i=e.parsed.declarations.some(e=>e.reference),o=i&&isCanvasPageFile(e.filePath,t)?parsedPageName(e):void 0;for(const r of e.parsed.declarations)r.reference?n.push(referenceDeclarationToEntry(r,r.reference,e,o,s)):n.push(declarationToEntry(r,e,t));const a=parseControlsFile(e.filePath,e.source,e.program).map(t=>({filePath:t.reference?referenceIdentityPath(e.filePath,t.reference.importSpecifier):e.filePath,name:t.reference?.importedName??("default"===t.exportKind?"default":t.bindingName),declaredIn:e.filePath}));return{entries:n,structuralErrors:r,...a.length?{controls:a}:{}}}function deriveLibraries(e){const t=new Map;for(const n of Object.values(e))for(const e of n.libraries){const r=t.get(e);r?r.push(n.key):t.set(e,[n.key])}const n={};for(const[e,r]of[...t.entries()].sort(([e],[t])=>e.localeCompare(t)))n[e]=r.sort((e,t)=>e.localeCompare(t));return n}var jP=/\.[tj]sx?$/;function normalizedIdentity(e){const t=parseAssetKey(e);if(!t||t.filePath.startsWith("pkg:"))return e;let n=t.filePath.replace(jP,"");return n.endsWith("/index")&&(n=n.slice(0,-6)),`${n}#${t.bindingName}`}function resolveDuplicateDeclarations(e){const t=new Map;for(const n of e){const e=normalizedIdentity(n.componentFilePath?`${n.componentFilePath}#${n.componentName??n.name}`:n.key),r=t.get(e);r?r.push(n):t.set(e,[n])}const n=[],r=new Map;for(const e of t.values()){if(1===e.length){n.push(e[0]);continue}const t=e.map(e=>e.declaredIn??e.filePath).sort(),s={code:"duplicate_asset_declaration",severity:"structural",message:`This component has multiple defineAsset declarations: ${t.join(", ")}. Keep one definition before editing or inserting it.`},i=[...e].sort((e,t)=>e.key.localeCompare(t.key)||(e.declaredIn??e.filePath).localeCompare(t.declaredIn??t.filePath))[0];n.push({...i,controls:void 0,variants:[],warnings:[...i.warnings,s]});for(const e of t)r.set(e,[...r.get(e)??[],s])}return{winners:n,errorsByFile:r}}function decorateWithCanvasPointer(e,t,n){if(!n||"component"!==e.kind||void 0===e.declaredIn||void 0===e.canvasPath)return e;const r=verifyCanvasPointer(n,t,e);return void 0===r.componentFilePath&&0===r.warnings.length?e:{...e,...void 0!==r.componentFilePath?{componentFilePath:r.componentFilePath}:{},warnings:[...e.warnings,...r.warnings]}}function decorateWithRedundancyWarning(e,t){if("canvas"!==e.kind)return e;const n=posixDirname(e.filePath);return t.has(n)?{...e,warnings:[...e.warnings,{code:"redundant_canvas_declaration",severity:"degraded",message:`the component declarations in "${n}" already link this canvas via canvasPath — remove the canvas self-registration (self-registration is strictly for component-less foundations pages)`}]}:e}function assembleIndex(e,t,n,r=!1){const s=new Map,configuredRoot=e=>{if(s.has(e))return s.get(e);let t=null;const r=n?.readFile(e);if(r)try{const n=JSON.parse(r),s=n.paths?.canvases,i="string"==typeof s&&s.trim()?s.trim().replaceAll("\\","/"):"./designs";t=TP.normalize(TP.join(TP.dirname(e),i))}catch{}return s.set(e,t),t},belongsToAnotherCanvasProject=e=>{if(!r||!n)return!1;for(let n=TP.dirname(e);;n=TP.dirname(n)){for(const r of[TP.join(n,"tempo.config.json"),TP.join(n,"tempo/tempo.config.json")]){const n=configuredRoot(r);if(n&&e.startsWith(`${n}/`))return n!==TP.normalize(t).replace(/\/$/,"")}if("."===n||"/"===n)return!1}},i=Object.fromEntries(Object.entries(e).filter(([e])=>!belongsToAnotherCanvasProject(e))),{winners:o,errorsByFile:a}=resolveDuplicateDeclarations(Object.values(i).flatMap(e=>e.entries).map(e=>{if(!n||"component"!==e.kind)return e;const t=resolveComponentIdentity(n,e.filePath,"default"===e.exportKind?"default":parseAssetKey(e.key)?.bindingName??e.name,e.declaredIn??e.filePath),r=t&&definesVueComponent(n,t.filePath,t.name)?"vue":installedPackageFramework(n,e.filePath,t?.filePath??null);return t||r?{...e,...t?{componentFilePath:t.filePath,componentName:t.name}:{},...r?{componentFramework:r}:{}}:e})),c=new Set;for(const e of o)"component"===e.kind&&void 0!==e.canvasPath&&c.add(e.canvasPath);const l={};for(const e of[...o].sort((e,t)=>e.key.localeCompare(t.key)))l[e.key]=decorateWithRedundancyWarning(decorateWithCanvasPointer(e,t,n),c);const d={},u=new Set([...Object.keys(i),...a.keys()]);for(const e of[...u].sort((e,t)=>e.localeCompare(t))){const t=[...i[e]?.structuralErrors??[],...a.get(e)??[]];t.length>0&&(d[e]=t)}const p={};for(const e of Object.keys(i).sort())for(const t of i[e].controls??[]){const r=n?resolveComponentIdentity(n,t.filePath,t.name,e):null,s=makeAssetKey(r?.filePath??t.filePath,r?.name??t.name);(p[s]??=[]).push(t.declaredIn)}return{assets:l,libraries:deriveLibraries(l),fileErrors:d,...Object.keys(p).length?{controls:p}:{}}}function buildAssetIndex(e,t={},n){const r=t.canvasesDir??UP,s=n&&(n.canvasesDir??UP)===r,i={},o={};for(const r of e){if(!hasAssetSourceExtension(r.filePath))continue;if(!sourceMayDeclareAssets(r.source))continue;const e=hashSource(r.source);o[r.filePath]=e,i[r.filePath]=s&&n.contentHashes[r.filePath]===e&&n.fileContributions[r.filePath]?n.fileContributions[r.filePath]:parseContribution(r.filePath,r.source,t)}return{index:assembleIndex(i,r,t.fileResolution,t.excludeForeignCanvasProjects),canvasesDir:r,contentHashes:o,fileContributions:i}}function parseContribution(e,t,n){const r=(n.parseProgram??parseAssetProgram)(e,t);return fileToIndexedParts({filePath:e,source:t,program:r,parsed:parseAssetFile(e,t,r)},n.canvasesDir??UP)}function toPosixPath4(e){return e.replace(/\\/g,"/")}function normalizeWorkspaceRelativePath(e,t){const n=toPosixPath4(t).replace(/^\.\//,"");return oP.isAbsolute(n)?toPosixPath4(oP.relative(e,n)):n}function resolveInsideWorkspace(e,t){const n=oP.resolve(e),r=oP.resolve(n,t),s=oP.relative(n,r),i=".."===s||s.startsWith(`..${oP.sep}`)||oP.isAbsolute(s);return i?void 0:r}function workspaceRelativeCanvasesDir(e){return toPosixPath4(oP.relative(e.workspaceRoot,oP.resolve(e.workspaceRoot,e.canvasesDir)))}function workspaceFileReader(e){return t=>{const n=resolveInsideWorkspace(e,t);if(void 0===n)return null;try{return iP(n).isFile()?sP(n,"utf-8"):null}catch{return null}}}async function loadWorkspaceAssetIndex(e){const[t,n]=await Promise.all([scanRepo(e.workspaceRoot),loadPnpmWorkspacePackages(e.workspaceRoot)]);return buildAssetIndex(t,{canvasesDir:workspaceRelativeCanvasesDir(e),excludeForeignCanvasProjects:!0,fileResolution:{readFile:workspaceFileReader(e.workspaceRoot),workspacePackages:n}}).index}function textResult(e){return{content:[{type:"text",text:e}]}}function errorResult8(e){return{content:[{type:"text",text:e}],isError:!0}}function typedErrorResult(e,t,n){return errorResult8(`${e} failed [${t}]: ${n}`)}function errorMessage(e){return e instanceof Error?e.message:String(e)}async function readWorkspaceFile(e,t){const n=resolveInsideWorkspace(e.workspaceRoot,t);if(void 0!==n)try{return await XI(n,"utf-8")}catch{return}}async function writeWorkspaceFile(e,t,n){const r=resolveInsideWorkspace(e.workspaceRoot,t);if(void 0===r)throw new Error(`refusing to write outside the workspace: "${t}"`);await YI(r,n)}function isCanvasPagePath(e,t){return"index.canvas.tsx"===JI.posix.basename(t)&&t.startsWith(`${workspaceRelativeCanvasesDir(e)}/`)}function toAssetSummary(e){return{key:e.key,kind:e.kind,name:e.name,filePath:e.filePath,...void 0!==e.usageInstructions?{usageInstructions:e.usageInstructions}:{},...void 0!==e.canvasPath?{canvasPath:e.canvasPath}:{},...void 0!==e.componentFilePath?{componentFilePath:e.componentFilePath}:{},variantNames:e.variants.map(e=>e.name)}}function sortedByName(e){return[...e].sort((e,t)=>e.name.localeCompare(t.name)||e.key.localeCompare(t.key))}function countByKind(e){return{componentCount:e.filter(e=>"component"===e.kind).length,canvasCount:e.filter(e=>"canvas"===e.kind).length}}function registerAssetTools(e,t){const loadIndex=()=>(t.loadAssetIndex??loadWorkspaceAssetIndex)({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir});e.tool("asset_list_libraries","Discover the project's asset libraries: named collections of approved reusable components and canvases, including its design system, component library, UI kit, and future collections. Call for a broad collection overview or when the user asks what libraries, reusable components, canvases, or building blocks exist; use asset_list next to search their members. **Read-only and cheap** (fresh source scan; no code execution; no guide needed to browse). Returns `{ libraries: [{ name, componentCount, canvasCount }], unassigned: { componentCount, canvasCount } }`.",{},async()=>{try{const e=await loadIndex(),t=Object.keys(e.libraries).sort().map(t=>({name:t,...countByKind(e.libraries[t].map(t=>e.assets[t]))})),n=countByKind(Object.values(e.assets).filter(e=>0===e.libraries.length));return textResult(JSON.stringify({libraries:t,unassigned:n},null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.tool("asset_library_get","Get one asset library's approved reusable components and canvases with per-asset summaries. Use after asset_list_libraries when exploring a design system, component library, UI kit, or another named collection. **Read-only and cheap** — no guide needed to browse. Returns `{ name, assets: [{ key, kind, name, filePath, usageInstructions?, canvasPath?, variantNames }] }`. Errors `library_not_found` when no asset names the library.",{name:QI.string().describe("Library name, exactly as listed by asset_list_libraries.")},async({name:e})=>{try{const t=await loadIndex(),n=t.libraries[e];if(!n){const n=Object.keys(t.libraries).sort();return typedErrorResult("asset_library_get","library_not_found",`no library named "${e}".${n.length>0?` Available libraries: ${n.join(", ")}.`:" No libraries exist yet."}`)}const r=sortedByName(n.map(e=>t.assets[e])).map(toAssetSummary);return textResult(JSON.stringify({name:e,assets:r},null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.registerTool("asset_list",{description:"Primary asset-discovery tool for UI work. Search every approved reusable component and canvas declared with `defineAsset`, across the project's design system, component library, UI kit, and other asset libraries. Call BEFORE creating, modifying, restyling, or reviewing UI to reuse an existing building block instead of hand-rolling one; each asset's `usageInstructions` says when to use it and when not to. **Read-only and cheap** (fresh source scan; no code execution; no guide needed to browse). Filter by library and/or name; pass `library: \"\"` for library-less assets. Returns `{ assets: [{ key, kind, name, filePath, usageInstructions?, canvasPath?, componentFilePath?, variantNames, libraries }], fileErrors? }`. `fileErrors` reports structural declaration problems such as `duplicate_asset_declaration` and `component_declaration_outside_canvas`, which also fail `canvas_validate`.",inputSchema:QI.object({library:QI.string().optional().describe('Exact library name to filter by. "" (empty string) selects assets that belong to no library.'),query:QI.string().optional().describe("Case-insensitive substring match on the asset name.")}),_meta:{"anthropic/alwaysLoad":!0}},async({library:e,query:t})=>{try{const n=await loadIndex(),r=t?.toLowerCase(),s=sortedByName(Object.values(n.assets).filter(t=>{if(""===e){if(t.libraries.length>0)return!1}else if(void 0!==e&&!t.libraries.includes(e))return!1;return void 0===r||t.name.toLowerCase().includes(r)})).map(e=>({...toAssetSummary(e),libraries:e.libraries})),i=Object.keys(n.fileErrors).length>0;return textResult(JSON.stringify({assets:s,...i?{fileErrors:n.fileErrors}:{}},null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.tool("asset_get",'Inspect one approved asset selected from a design system, component library, UI kit, or another asset library. Call after asset_list before reuse. Returns usageInstructions, library membership, real variants, warnings, and linked canvas/component paths. **Read-only and cheap** — no guide needed to browse. Prop values the parser could not resolve statically are `{"$unresolved": true}`. Canvas-pointer warnings identify missing or stale links and include the exact repair. Errors `asset_not_found` for an unknown key.',{assetKey:QI.string().describe('Asset key as returned by the list tools: "<workspace-relative-path>#<bindingName>".')},async({assetKey:e})=>{try{const t=await loadIndex(),n=t.assets[e];if(!n)return typedErrorResult("asset_get","asset_not_found",`no asset with key "${e}". Keys have the shape "<workspace-relative-path>#<bindingName>" — call asset_list to see what exists.`);const{declaredIn:r,...s}=n;return textResult(JSON.stringify(s,null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.tool("asset_define","Back-compat only — almost never the tool you want. **To add a component to the design system, do NOT use this tool.** The convention is a canvas reference declaration: hand-write `defineAsset(<ImportedComponent>, { libraries, usageInstructions, variants })` at the top level of the canvas that showcases the component, and add the canvas-pointer docstring line to the component's defining file — call get_guide({ topic: \"tempo-assets-instructions\" }) first for the exact authoring rules. This tool instead attaches a LEGACY same-file `defineAsset` tag in the component's own file (records no linked canvas): it adds the `tempo-sdk/assets` import if missing and inserts the statement directly after the component's definition. Anonymous default exports (`export default function () {…}`, `export default () => …`) are repaired to a named binding automatically. **MUTATING** (surgical source edit; the file is never regenerated). Returns `{ assetKey, repairedDefaultExport }`, plus a `note` when the project typecheck may additionally require `variants`. Errors: `file_not_found`, `export_not_found`, `already_defined`, `not_definable`.",{filePath:QI.string().describe("Workspace-relative path to the file that defines the component (or a canvas's index.canvas.tsx)."),exportName:QI.string().optional().describe("Named top-level binding to target. Omit to target the file's default export."),libraries:QI.array(QI.string()).optional().describe("Library names to put the asset in."),usageInstructions:QI.string().optional().describe("What this asset is and when to reach for it — and when not.")},async({filePath:e,exportName:n,libraries:r,usageInstructions:s})=>{const i=normalizeWorkspaceRelativePath(t.workspaceRoot,e);try{let e,o=await readWorkspaceFile(t,i);if(void 0===o)return typedErrorResult("asset_define","file_not_found",`no file at "${i}" (workspace-relative).`);let a=!1;if(void 0!==n)e=n;else{const t=ensureNamedDefaultExport({filePath:i,source:o});if(!t.ok)return typedErrorResult("asset_define",t.code,t.message);a=t.changed,o=t.source,e=t.bindingName}const c={...void 0!==s?{usageInstructions:s}:{},...r&&r.length>0?{libraries:r}:{}},l=ensureAssetDeclaration({filePath:i,source:o,bindingName:e,initialConfig:c});if(!l.ok)return typedErrorResult("asset_define",l.code,l.message);if(!l.changed)return typedErrorResult("asset_define","already_defined",`"${makeAssetKey(i,e)}" already has a defineAsset declaration. Use asset_add_to_libraries / asset_remove_from_libraries to change its membership.`);await writeWorkspaceFile(t,i,l.source);const d=isCanvasPagePath(t,i);return textResult(JSON.stringify({assetKey:makeAssetKey(i,e),repairedDefaultExport:a,...d?{}:{note:`If ${e} has required props, the project's typecheck will require a \`variants\` entry on this defineAsset config. Add named variants with real, renderable prop values — never invented placeholders.`}},null,2))}catch(e){return errorResult8(errorMessage(e))}}),registerMembershipTool(e,t,{name:"asset_add_to_libraries",description:"Add an asset to one or more libraries by inserting the names into its `defineAsset` config's `libraries` array (creating the property when absent). Already-present names are skipped. Edits same-file declarations only — for a canvas reference declaration (the design-system convention), hand-edit the `libraries` array in the declaring canvas instead. **MUTATING** (surgical span edit — surrounding code is byte-identical). Returns `{ assetKey, libraries }` — the resulting full membership. Errors: `asset_not_found`, `config_not_editable`.",edit:addLibraries}),registerMembershipTool(e,t,{name:"asset_remove_from_libraries",description:"Remove an asset from one or more libraries by deleting matching entries from its `defineAsset` config's `libraries` array (the property itself is removed when the array empties). Names not present are ignored. Edits same-file declarations only — for a canvas reference declaration (the design-system convention), hand-edit the `libraries` array in the declaring canvas instead. **MUTATING** (surgical span edit — surrounding code is byte-identical). Returns `{ assetKey, libraries }` — the resulting full membership, possibly empty. Errors: `asset_not_found`, `config_not_editable`.",edit:removeLibraries})}function registerMembershipTool(e,t,n){e.tool(n.name,n.description,{assetKey:QI.string().describe('Asset key as returned by the list tools: "<workspace-relative-path>#<bindingName>".'),libraries:QI.array(QI.string()).min(1).describe("Library names (non-empty).")},async({assetKey:e,libraries:r})=>{try{const s=parseAssetKey(e),i=s?await readWorkspaceFile(t,s.filePath):void 0;if(!s||void 0===i)return typedErrorResult(n.name,"asset_not_found",`no asset with key "${e}". Keys have the shape "<workspace-relative-path>#<bindingName>" — call asset_list to see what exists.`);const o=n.edit({filePath:s.filePath,source:i,bindingName:s.bindingName,libraries:r});if(!o.ok)return typedErrorResult(n.name,o.code,o.message);o.changed&&await writeWorkspaceFile(t,s.filePath,o.source);const a=parseAssetFile(s.filePath,o.source).declarations.find(e=>e.bindingName===s.bindingName);return textResult(JSON.stringify({assetKey:e,libraries:a?.libraries??[]},null,2))}catch(e){return errorResult8(errorMessage(e))}})}var BP=3840,$P=12e3;function isFidelityWindowStoryboard(e){return"component"===e.kind&&"astro"!==e.uiFramework&&void 0===e.preview}import WP from"path";import{parseSync as HP}from"oxc-parser";function applyCanvasSourceEdits(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e.length+1,s=e;for(const t of n){if(t.start<0||t.end<t.start||t.end>e.length||t.end>r)throw new Error(`Invalid overlapping canvas source edit ${t.start}:${t.end}`);s=s.slice(0,t.start)+t.value+s.slice(t.end),r=t.start}return s}function updateStoryboardVrt(e){const t=parseCanvasFile(e.filePath,e.source),n=findStoryboard(t,e.storyboardId);if("route"===n.kind)throw new Error(`Storyboard "${e.storyboardId}" is a route storyboard; VRT supports component and local HTML storyboards`);if("object"==typeof e.tracked){const r=formatStoryboardVrtConfig(e.tracked),s=null===r?"vrt":`vrt={${r}}`;return n.vrtAttributeSpan?applyResult(e.source,t,[{start:n.vrtAttributeSpan.start,end:n.vrtAttributeSpan.end,value:s}]):applyResult(e.source,t,[insertBareJsxAttributeLine({source:e.source,openingElementSpan:requireStoryboardOpeningSpan(n,e.storyboardId),name:s})])}if(!e.tracked)return n.vrtAttributeSpan?applyResult(e.source,t,[{...expandJsxAttributeRemoval(e.source,n.vrtAttributeSpan),value:""}]):applyResult(e.source,t,[]);if(n.vrt)return applyResult(e.source,t,[]);const r=requireStoryboardOpeningSpan(n,e.storyboardId);return n.vrtAttributeSpan?applyResult(e.source,t,[{...expandJsxAttributeRemoval(e.source,n.vrtAttributeSpan),value:""},insertBareJsxAttributeLine({source:e.source,openingElementSpan:r,name:"vrt"})]):applyResult(e.source,t,[insertBareJsxAttributeLine({source:e.source,openingElementSpan:r,name:"vrt"})])}function formatStoryboardVrtConfig(e){const t=[];if(void 0!==e.threshold){if("number"!=typeof e.threshold||!Number.isFinite(e.threshold)||e.threshold<0||e.threshold>.5)throw new Error("vrt.threshold must be a number between 0 and 0.5");t.push(`threshold: ${e.threshold}`)}if(void 0!==e.skip){if("boolean"!=typeof e.skip)throw new Error("vrt.skip must be a boolean");t.push(`skip: ${e.skip}`)}if(void 0!==e.ignore){if(!Array.isArray(e.ignore))throw new Error("vrt.ignore must be an array of { x, y, w, h } regions");const n=e.ignore.map(e=>{for(const t of["x","y","w","h"]){const n=e?.[t];if("number"!=typeof n||!Number.isFinite(n)||n<0)throw new Error(`vrt.ignore regions must be { x, y, w, h } non-negative numbers (bad ${t})`)}return`{ x: ${e.x}, y: ${e.y}, w: ${e.w}, h: ${e.h} }`});n.length>0&&t.push(`ignore: [${n.join(", ")}]`)}return 0===t.length?null:`{ ${t.join(", ")} }`}function addCanvasStoryboard(e){const t=parseCanvasFile(e.filePath,e.source);if(t.storyboards.some(t=>t.storyboardKey===e.storyboard.id))throw new Error(`Storyboard id "${e.storyboard.id}" already exists`);const n=[],r=sdkComponentForStoryboard(e.storyboard),s=resolveSdkTag(t,r);let i,o=s.tag;if(s.importLine&&(n.push(s.importLine),o=s.tag),"component"===e.storyboard.kind){if(i=e.storyboard.componentExpression??e.storyboard.componentImport?.localName,!i)throw new Error("Component storyboard requires componentExpression or componentImport");if(e.storyboard.componentImport){const r=buildMissingComponentImportLine(t,e.source,e.storyboard.componentImport);r&&n.push(r)}}const a=buildImportInsertionEdit2(e.source,t,n),c=buildCanvasChildInsertionEdit({source:e.source,parsed:t,tag:o,storyboard:e.storyboard,componentExpression:i}),l=[...a?[a]:[],c];return applyResult(e.source,t,l)}function applyResult(e,t,n){const r=n.filter(t=>!!t&&e.slice(t.start,t.end)!==t.value);return{source:applyCanvasSourceEdits(e,r),edits:r,parsed:t}}function findStoryboard(e,t){const n=e.storyboards.find(e=>e.storyboardKey===t);if(!n)throw new Error(`Storyboard "${t}" not found`);return n}function requireStoryboardOpeningSpan(e,t){return requiredSpan(e.openingElementSpan,`Storyboard "${t}" opening element not found`)}function formatStoryboardElement(e){const t=detectNewline2(e.source),n=lineIndentAt2(e.source,e.insertionOffset),r=`${n} `,s=" ",i=`${r} `,o=storyboardElementProps(e.storyboard,e.componentExpression);return`${s}<${e.tag}${t}${o.map(e=>`${i}${e}`).join(t)}${t}${r}/>${t}${n}`}function buildCanvasChildInsertionEdit(e){const t=e.parsed.canvasChildrenInsertionOffset;if("number"==typeof t)return{start:t,end:t,value:formatStoryboardElement({source:e.source,insertionOffset:t,tag:e.tag,storyboard:e.storyboard,componentExpression:e.componentExpression})};const n=e.parsed.canvasOpeningElementSpan;if(!n)throw new Error("Canvas closing element not found");const r=e.source.slice(n.start,n.end),s=r.match(/\s*\/\s*>$/),i=r.match(/^<\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/)?.[1];if(!s||!i)throw new Error("Canvas closing element not found");const o=detectNewline2(e.source),a=n.end-s[0].length,c=lineIndentAt2(e.source,n.start),l=`${c} `,d=`${l} `,u=storyboardElementProps(e.storyboard,e.componentExpression);return{start:a,end:n.end,value:`>${o}${l}<${e.tag}${o}${u.map(e=>`${d}${e}`).join(o)}${o}${l}/>${o}${c}</${i}>`}}function storyboardElementProps(e,t){const n=formatJsxStringAttribute("id",requireNonEmpty(e.id,"Storyboard id"));if("legacy-v1"===e.kind)return[n,`storyboard={${e.storyboardExpression}}`];if(!("route"!==e.kind&&"html"!==e.kind&&"flutter"!==e.kind||void 0!==e.layout.width&&void 0!==e.layout.height))throw new Error("Route, HTML and Flutter layouts require width and height");return[n,...e.name&&""!==e.name.trim()?[formatJsxStringAttribute("name",e.name)]:[],...storyboardKindProps(e,t),`layout={{ ${formatLayout(e.layout)} }}`]}function formatJsxStringAttribute(e,t){const n=JSON.stringify(t),r=n===`"${t}"`&&!t.includes("&");return r?`${e}=${n}`:`${e}={${n}}`}function storyboardKindProps(e,t){return"component"===e.kind?[`component={${t}}`,...e.props&&""!==e.props.trim()?[`props={${e.props.trim()}}`]:[]]:"route"===e.kind?[formatJsxStringAttribute("route",e.route)]:"flutter"===e.kind?[formatJsxStringAttribute("preview",e.preview)]:[...e.filepath?[formatJsxStringAttribute("filepath",e.filepath)]:[],...e.src?[formatJsxStringAttribute("src",e.src)]:[]]}function formatLayout(e){return[`x: ${roundLayoutNumber(e.x)}`,`y: ${roundLayoutNumber(e.y)}`,...void 0===e.width?[]:[`width: ${roundLayoutNumber(e.width)}`],...void 0===e.height?[]:[`height: ${roundLayoutNumber(e.height)}`],...void 0===e.zIndex?[]:[`zIndex: ${roundLayoutNumber(e.zIndex)}`],...void 0===e.intrinsicSizing?[]:[`intrinsicSizing: ${JSON.stringify(e.intrinsicSizing)}`]].join(", ")}function sdkComponentForStoryboard(e){return"route"===e.kind?"RouteStoryboard":"html"===e.kind?"HtmlStoryboard":"flutter"===e.kind?"FlutterStoryboard":"legacy-v1"===e.kind?"LegacyStoryboardV1":storyboardComponentForFramework(e.uiFramework)}function resolveSdkTag(e,t){const n=Gb[t].importSource;for(const r of e.imports)if(r.source===n){if("namespace"===r.kind)return{tag:`${r.localName}.${t}`};if(r.importedName===t)return{tag:r.localName}}const r=pickAvailableIdentifier(e,`TempoCanvas${t}`);return{tag:r,importLine:`import { ${t} as ${r} } from "${n}";`}}function buildMissingComponentImportLine(e,t,n){const r=e.imports.find(e=>e.localName===n.localName);if(r){if(r.source!==n.source)throw new Error(`Import binding "${n.localName}" already exists`);return null}if(sourceContainsIdentifierNode(e.filePath,t,n.localName))throw new Error(`Identifier "${n.localName}" already exists`);if(!n.importedName||"default"===n.importedName)return`import ${n.localName} from ${JSON.stringify(n.source)};`;const s=n.importedName===n.localName?n.localName:`${n.importedName} as ${n.localName}`;return`import { ${s} } from ${JSON.stringify(n.source)};`}function buildImportInsertionEdit2(e,t,n){if(0===n.length)return null;const r=detectNewline2(e),s=Array.from(new Set(n)),i=t.imports.reduce((e,t)=>!e||t.declarationSpan.end>e.declarationSpan.end?t:e,null);if(i)return{start:i.declarationSpan.end,end:i.declarationSpan.end,value:`${r}${s.join(r)}`};const o=topLevelInsertionOffset2(e);return{start:o,end:o,value:`${s.join(r)}${r}`}}function findOpeningElementAttributeInsertionOffset(e,t){const n=e.lastIndexOf(">",t.end-1);if(n<t.start)throw new Error("JSX opening element close not found");return"/"===e[n-1]?n-1:n}function insertBareJsxAttributeLine(e){const t=findOpeningElementAttributeInsertionOffset(e.source,e.openingElementSpan),n=detectNewline2(e.source),r=lineIndentAt2(e.source,e.openingElementSpan.start),s=e.source.indexOf("\n",e.openingElementSpan.start),i=s>=0&&s<t?e.source.slice(s+1,t).split(/\r?\n/).find(e=>""!==e.trim())?.match(/^[ \t]*/)?.[0]:void 0,o=i&&i.length>r.length?i:`${r}${r.includes("\t")?"\t":" "}`,a=Math.max(e.source.lastIndexOf("\n",t-1)+1,0);if(/^[ \t]*$/.test(e.source.slice(a,t)))return{start:a,end:a,value:`${o}${e.name}${n}`};let c=t;for(;c>e.openingElementSpan.start&&(" "===e.source[c-1]||"\t"===e.source[c-1]);)c--;return{start:c,end:t,value:`${n}${o}${e.name}${n}${r}`}}function expandJsxAttributeRemoval(e,t){const n=Math.max(e.lastIndexOf("\n",t.start-1)+1,0),r=e.indexOf("\n",t.end),s=r>=0?r:e.length;if(/^[ \t]*$/.test(e.slice(n,t.start))&&/^[ \t]*$/.test(e.slice(t.end,s)))return{start:n,end:r>=0?r+1:s};let i=t.start,o=t.end;for(;i>0&&(" "===e[i-1]||"\t"===e[i-1]);)i--;for(;o<e.length&&(" "===e[o]||"\t"===e[o]);)o++;return{start:i,end:o}}function expandStatementForward(e,t){let n=t.end;for(;n<e.length&&(" "===e[n]||"\t"===e[n]);)n++;return"\r\n"===e.slice(n,n+2)?n+=2:"\n"!==e[n]&&"\r"!==e[n]||n++,{start:t.start,end:n}}function lineIndentAt2(e,t){const n=Math.max(e.lastIndexOf("\n",t-1)+1,0),r=e.slice(n,t),s=r.match(/^[ \t]*/);return s?.[0]??""}function collapseBlankLines(e,t){return"\r\n"===t?e.replace(/(\r\n){3,}/g,"\r\n\r\n"):e.replace(/\n{3,}/g,"\n\n")}function detectNewline2(e){return e.includes("\r\n")?"\r\n":"\n"}function topLevelInsertionOffset2(e){let t=0;if(e.startsWith("#!")){const n=e.indexOf("\n");t=n>=0?n+1:e.length}for(;;){const n=e.indexOf("\n",t),r=n>=0?n+1:e.length,s=e.slice(t,r).trim();if(!/^["']use [^"']+["'];?$/.test(s))break;t=r}return t}function pickAvailableIdentifier(e,t){const n=new Set(e.imports.map(e=>e.localName));if(!n.has(t))return t;for(let e=2;e<1e4;e+=1){const r=`${t}${e}`;if(!n.has(r))return r}throw new Error(`Unable to find available identifier for ${t}`)}function hasIdentifier(e,t){return new RegExp(`\\b${escapeRegExp4(t)}\\b`).test(e)}function sourceContainsIdentifierNode(e,t,n){const r=HP(e,t).program;let s=!1;return walkWithParent(r,e=>{s||"Identifier"!==e.type&&"JSXIdentifier"!==e.type||e.name!==n||(s=!0)}),s}function walkWithParent(e,t,n=null,r=null,s=new Set){if(e&&"object"==typeof e&&!s.has(e)){s.add(e),"string"==typeof e.type&&t(e,n,r);for(const[n,r]of Object.entries(e))if(r&&"object"==typeof r)if(Array.isArray(r))for(const i of r)walkWithParent(i,t,e,n,s);else walkWithParent(r,t,e,n,s)}}function escapeRegExp4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function roundLayoutNumber(e){if("number"!=typeof e||!Number.isFinite(e))throw new Error("Layout values must be finite numbers");return Math.round(e)}function requireNonEmpty(e,t){const n=e.trim();if(!n)throw new Error(`${t} must be non-empty`);return n}function requiredSpan(e,t){if(void 0===e)throw new Error(t);return e}function reactStub(e,t){const n=t&&"default"!==t?t:e,r=`${e}Stub`;return`function ${r}() { return <div />; }\nexport default ${r};\nexport const ${n} = ${r};\n`}function singleFileComponentStub(e,t){return(n,r)=>{if(r&&"default"!==r)throw new Error(`Canvas-local ${e} storyboard "${n}" must use a default component import`);return t}}var qP={react:{extension:componentFileExtensionForFramework("react"),stub:reactStub},svelte:{extension:componentFileExtensionForFramework("svelte"),stub:singleFileComponentStub("Svelte","<div></div>\n")},vue:{extension:componentFileExtensionForFramework("vue"),stub:singleFileComponentStub("Vue","<template><div></div></template>\n")},astro:{extension:componentFileExtensionForFramework("astro"),stub:singleFileComponentStub("Astro","<div></div>\n")}},zP=/\.(?:jsx?|tsx?)$/;function storyboardFrameworkForImport(e,t){const n=componentImportPath(e??""),r=Object.keys(qP),s=r.find(e=>n.endsWith(qP[e].extension));return s||(zP.test(n)?"react":resolveAppUiFramework(t))}function hasComponentModuleExtension(e){const t=componentImportPath(e);return!!zP.test(t)||Object.values(qP).some(e=>t.endsWith(e.extension))}function toIdentifier(e){const t=e.replace(/[^a-zA-Z0-9_$]+/g," ").trim().split(/\s+/).map((e,t)=>{if(0===e.length)return"";const n=e.replace(/^[0-9]+/,"");if(0===n.length)return"";const r=n.toLowerCase();return 0===t?r:r[0].toUpperCase()+r.slice(1)}).join(""),n=t.length>0?t:"componentRef",r=/^[a-zA-Z_$]/.test(n);return r?n:`component${n}`}function canvasComponentName(e){const t=toIdentifier(e);return`${t[0].toUpperCase()}${t.slice(1)}Canvas`}function getDefaultLocalName(e){const t=e.importPath?WP.posix.basename(e.importPath).replace(/\.[^.]+$/,""):"",n=t||`${e.exportName}Component`,r=toIdentifier(n);return r[0].toUpperCase()+r.slice(1)}function buildComponentImports(e,t){const n=new Map,r=new Set(t),s=new Map;for(const t of e)r.add(t.exportName);const assignUniqueLocalName=e=>{let t=e,n=2;for(;r.has(t);)t=`${e}${n}`,n+=1;return r.add(t),t};for(const t of e){if(t.route||t.preview)continue;if(!t.importPath)throw new Error(`Storyboard "${t.exportName}" must include importPath for component storyboards`);const e=t.importName&&t.importName.trim().length>0?t.importName.trim():"default",r=t.importPath.replace(/\.tsx?$/,""),i=`${r}::${e}`;let o=n.get(i);if(!o){const s="default"===e?getDefaultLocalName(t):e;o={importPath:r,importName:e,localName:assignUniqueLocalName(s)},n.set(i,o)}s.set(t.exportName,o)}return s}function componentImportSource(e,t){const n=storyboardComponentForFramework(t);if(!Gb[n].componentImportQuery)return e;const r=componentImportPath(e),s=qP[t].extension;return componentImportSpecifier(r.endsWith(s)?r:`${r}${s}`)}function toAddCanvasStoryboardInput(e,t,n){const r={x:e.x,y:e.y,...e.route||e.preview?{width:e.width,height:e.height}:{},...null!=e.zIndex&&Number.isFinite(e.zIndex)?{zIndex:e.zIndex}:{}},s=e.name?{name:e.name}:{};if(e.route)return{kind:"route",id:e.exportName,route:e.route,layout:r,...s};if(e.preview)return{kind:"flutter",id:e.exportName,preview:e.preview,layout:r,...s};if(!t)throw new Error(`Storyboard "${e.exportName}" is missing a component import binding`);const i=storyboardFrameworkForImport(e.importPath,n);return{kind:"component",uiFramework:"react"===i?void 0:i,id:e.exportName,layout:"astro"===i?{...r,width:e.width,height:e.height}:r,...s,componentImport:{localName:t.localName,source:componentImportSource(t.importPath,i),importedName:t.importName}}}function generatePageFileContent(e){const t=resolveAppUiFramework(e.uiFramework),n=canvasComponentName(e.pageName),r=new Set(e.storyboards.filter(e=>!e.route&&!e.preview).map(e=>storyboardFrameworkForImport(e.importPath,t))),s=new Map([["tempo-sdk/canvas",["Canvas"]]]),addSdkName=(e,t)=>{const n=s.get(e)??[];n.push(t),s.set(e,n)};for(const e of Object.keys(qP)){if(!r.has(e))continue;const t=storyboardComponentForFramework(e);addSdkName(Gb[t].importSource,t)}e.storyboards.some(e=>e.route)&&addSdkName("tempo-sdk/canvas","RouteStoryboard"),e.storyboards.some(e=>e.preview)&&addSdkName("tempo-sdk/canvas","FlutterStoryboard");const i=buildComponentImports(e.storyboards,[n,...[...s.values()].flat()]),o=[];e.home&&o.push(CP);for(const[e,t]of s)o.push(`import { ${t.join(", ")} } from "${e}";`);o.push(""),o.push(`export default function ${n}() {`);const a=[formatJsxStringAttribute("name",e.pageName),...e.backgroundColor?[formatJsxStringAttribute("backgroundColor",e.backgroundColor)]:[]].join(" ");0===e.storyboards.length?o.push(` return <Canvas ${a} />;`):(o.push(" return ("),o.push(` <Canvas ${a}>`),o.push(" </Canvas>"),o.push(" );")),o.push("}");const c="index.canvas.tsx";let l=`${o.join("\n")}\n`;for(const n of e.storyboards)l=addCanvasStoryboard({filePath:c,source:l,storyboard:toAddCanvasStoryboardInput(n,i.get(n.exportName),t)}).source;const d=parseCanvasFile(c,l);if(!d.canvasElementSpan)throw new Error("Generated canvas source is missing a <Canvas> element");if(d.storyboards.length!==e.storyboards.length)throw new Error(`Generated canvas declares ${d.storyboards.length} storyboards, expected ${e.storyboards.length}`);return l}import{readFile as GP}from"fs/promises";async function parsePageFile(e){const t=await GP(e,"utf-8");return parsePageSource(e,t)}import VP from"fs/promises";import KP from"path";import{createHash as XP,randomUUID as YP}from"crypto";import JP from"fs/promises";import QP from"path";import{fileURLToPath as ZP}from"url";function createQueuedFileEditor(){const e=new Map;async function withFileLock(t,n){const r=normalizeAbsolutePath(t),s=e.get(r)??Promise.resolve();let i;const o=new Promise(e=>{i=e}),a=s.catch(()=>{}).then(()=>o);e.set(r,a),await s.catch(()=>{});try{return await n()}finally{i(),e.get(r)===a&&e.delete(r)}}async function withFileLocks(e,t){const n=Array.from(new Set(e.map(e=>normalizeAbsolutePath(e)))).sort(),runAtIndex=e=>{const r=n[e];return r?withFileLock(r,()=>runAtIndex(e+1)):Promise.resolve(t())};return runAtIndex(0)}async function readFile48(e){return withFileLock(e,()=>readFileUnlocked(e))}async function readBinaryFile(e){return withFileLock(e,()=>JP.readFile(normalizeAbsolutePath(e)))}async function readFileIfExists(e){return withFileLock(e,async()=>{try{return await readFileUnlocked(e)}catch(e){if(isNotFoundError(e))return null;throw e}})}async function writeFile16(e,t,n,r){return withFileLock(e,async()=>{const s=await readFileIfExistsUnlocked(e);if("number"==typeof n&&Number.isFinite(n)&&s?.mtime!==n)return{stale:!0,content:s?.content??"",mtime:s?.mtime??0};await atomicWriteFile(e,t,r);const i=await JP.stat(e);return{stale:!1,mtime:i.mtimeMs}})}async function writeBinaryFile(e,t,n){return withFileLock(e,async()=>{await atomicWriteFile(e,t,n);const r=await JP.stat(e);return{mtime:r.mtimeMs}})}async function touchFile(e){return withFileLock(e,async()=>{const t=normalizeAbsolutePath(e),n=await JP.stat(t),r=new Date(Math.max(Date.now(),Math.ceil(n.mtimeMs)+1));await JP.utimes(t,n.atime,r);const s=await JP.stat(t);return{mtime:s.mtimeMs}})}async function copyFile2(e,t){return withFileLocks([e,t],async()=>{const n=normalizeAbsolutePath(t);await JP.mkdir(QP.dirname(n),{recursive:!0}),await JP.copyFile(normalizeAbsolutePath(e),n)})}async function renamePath(e,t){return withFileLocks([e,t],async()=>{const n=normalizeAbsolutePath(t);await JP.mkdir(QP.dirname(n),{recursive:!0}),await JP.rename(normalizeAbsolutePath(e),n)})}async function removePath(e,t){return withFileLock(e,()=>JP.rm(normalizeAbsolutePath(e),{recursive:t?.recursive??!1,force:!0}))}async function unlinkFile(e){return withFileLock(e,async()=>{try{await JP.unlink(e)}catch(e){if(!isNotFoundError(e))throw e}})}return{readFile:readFile48,readBinaryFile,readFileIfExists,writeFile:writeFile16,writeBinaryFile,touchFile,copyFile:copyFile2,renamePath,removePath,unlinkFile,withFileLock,withFileLocks,readWorkspaceFile:(e,t)=>readFile48(resolveWorkspaceRelativePath(e,t)),readWorkspaceFileIfExists:(e,t)=>readFileIfExists(resolveWorkspaceRelativePath(e,t)),writeWorkspaceFile:(e,t,n,r,s)=>writeFile16(resolveWorkspaceRelativePath(e,t),n,r,s),touchWorkspaceFile:(e,t)=>touchFile(resolveWorkspaceRelativePath(e,t)),unlinkWorkspaceFile:(e,t)=>unlinkFile(resolveWorkspaceRelativePath(e,t)),withWorkspaceFileLock:(e,t,n)=>withFileLock(resolveWorkspaceRelativePath(e,t),n)}}var eD=createQueuedFileEditor();function resolveWorkspaceRelativePath(e,t){const n=/^[a-z]:[\\/]|^\\\\/i.test(e),r=n?QP.win32:QP,s=t.startsWith("file:")?ZP(t,{windows:n}):n&&/^\/[a-z]:[\\/]/i.test(t)?t.slice(1):t,i=r.resolve(e),o=r.resolve(i,s),a=r.relative(i,o);if(".."===a||a.startsWith(`..${r.sep}`)||r.isAbsolute(a))throw new Error(`Path escapes workspace root: ${t}`);return o}async function atomicWriteFile(e,t,n,r={}){const s=normalizeAbsolutePath(e),i=QP.dirname(s);await JP.mkdir(i,{recursive:!0});const o=QP.join(i,`.${QP.basename(s)}.${process.pid}.${Date.now()}.${YP()}.tmp`);try{if(await JP.writeFile(o,t),"number"==typeof n&&Number.isFinite(n)){const e=new Date(n);await JP.utimes(o,e,e)}const e=Math.trunc((await JP.stat(o)).mtimeMs);if(void 0!==r.expectedSha256){const e=await JP.readFile(s).catch(e=>{if(isNotFoundError(e))return null;throw e}),t=null===e?null:XP("sha256").update(e).digest("hex");if(t!==r.expectedSha256)return await JP.rm(o,{force:!0}),{stale:!0}}if(null===r.expectedSha256){try{await JP.link(o,s)}catch(e){if("EEXIST"===e.code)return await JP.rm(o,{force:!0}),{stale:!0};throw e}await JP.rm(o,{force:!0}).catch(()=>{})}else await JP.rename(o,s);return{stale:!1,mtime:e}}catch(e){throw await JP.rm(o,{force:!0}).catch(()=>{}),e}}async function readFileUnlocked(e){const t=normalizeAbsolutePath(e),n=await JP.readFile(t,"utf-8"),r=await JP.stat(t);return{content:n,mtime:r.mtimeMs}}async function readFileIfExistsUnlocked(e){try{return await readFileUnlocked(e)}catch(e){if(isNotFoundError(e))return null;throw e}}function normalizeAbsolutePath(e){return QP.resolve(e)}function isNotFoundError(e){return"object"==typeof e&&null!==e&&"ENOENT"===e.code}import{parseSync as tD}from"oxc-parser";var nD=class extends Error{constructor(e){super(e.join("\n")),this.name="UnsupportedLegacyCanvasError"}};function migrateLegacyCanvasToReact(e){const t=parseCanvasFile(e.filePath,e.source);if(t.canvasElementSpan)return{source:e.source,parsed:t,migrated:!1,edits:[]};if(t.misimportedSdkCanvasImports.length>0)return repairMisimportedSdkCanvasImports(e.filePath,e.source,t.misimportedSdkCanvasImports);try{return migrateNative(e.filePath,e.source,!1)}catch(t){if(t instanceof nD)throw t;return migrateNative(e.filePath,e.source,!0)}}function repairMisimportedSdkCanvasImports(e,t,n){const r=n.map(misimportedSdkCanvasImportMessage);if(!n.every(e=>e.rewritable))throw new nD(r);let s=t;for(const e of[...n].sort((e,t)=>t.sourceSpan.start-e.sourceSpan.start)){const n=t[e.sourceSpan.start]??'"';s=`${s.slice(0,e.sourceSpan.start)}${n}tempo-sdk/canvas${n}${s.slice(e.sourceSpan.end)}`}const i=parseCanvasFile(e,s),o=i.errors.filter(e=>"structural"===e.kind);if(!i.canvasElementSpan||o.length>0)throw new nD(r);return{source:s,parsed:i,migrated:!0,edits:[{start:0,end:t.length,value:s}]}}var rD=["Canvas","Storyboard","LegacyStoryboardV1","RouteStoryboard","HtmlStoryboard"];function migrateNative(e,t,n){const r=readLegacyFile(e,t),s=detectNewline2(t),i=[],o=[];for(const e of r.storyboards){const t=planStoryboard(e,r,n,i);t&&o.push(t)}if(i.length>0)throw new nD(i);const a=[];for(const e of o)a.push(...declarationEdits(e,t));for(const e of dedupeSpans(r.specifierExportSpans))a.push({...expandStatementForward(t,e),value:""});a.push(...r.defaultExportEdits);let c=collapseBlankLines(applyCanvasSourceEdits(t,a),s);c=removeUnusedLegacyTypeImports(e,c,s);const l=collectSourceIdentifiers(c),d=pickAvailableIdentifier2(l,canvasComponentName2(r.canvasName));l.add(d);const u=resolveSdkImportNames(neededSdkMembers(o),l),p=u.localNames.get("Canvas"),m=buildCanvasProps(r),f=0===o.length?`export default function ${d}() {${s} return <${p} ${m} />;${s}}${s}`:`export default function ${d}() {${s} return (${s} <${p} ${m}>${s} </${p}>${s} );${s}}${s}`;let g=collapseBlankLines(applyCanvasSourceEdits(c,[buildSdkImportEdit(e,c,u.importLine,s),{start:c.length,end:c.length,value:`${s}${f}`}]),s);for(const t of o)g=addCanvasStoryboard({filePath:e,source:g,storyboard:toAddInput(t)}).source;const y=parseCanvasFile(e,g);return assertMigratedInvariants(y,o,n),{source:g,parsed:y,migrated:!0,edits:[{start:0,end:t.length,value:g}]}}function assertMigratedInvariants(e,t,n){if(!e.canvasElementSpan)throw new Error("Migrated canvas is missing a <Canvas> element");for(const n of t){const t=e.storyboards.filter(e=>e.storyboardKey===n.id).length;if(1!==t)throw new Error(`Migrated canvas declares storyboard "${n.id}" ${t} times`)}if(e.errors.length>0){if(n){const t=e.errors.filter(e=>"structural"===e.kind);if(0===t.length)return;throw new nD(t.map(e=>e.message))}throw new Error("Migrated canvas re-parsed with errors")}}function readLegacyFile(e,t){const n=tD(e,t).program,r=Array.isArray(n?.body)?n.body:[],s=collectBindings(r),i=collectLocalFunctionReturnTypes(r),o={source:t,program:n,storyboards:[],storyboardLocalNames:new Set,specifierExportSpans:[],defaultExportEdits:[],canvasName:fallbackPageName(e),configMode:"none",hasPageBackgroundColor:!1,imports:collectImportLocalNames(r),moduleBindingNames:collectModuleBindingNames(r)},a=[],c=new Map;let l=0;const addStoryboard=(e,t,n,r,s,i,l,d)=>{c.has(e)?a.push(`Duplicate legacy storyboard export id "${e}" requires manual migration`):isLegacyStoryboardType(n)&&(c.set(e,t),o.storyboardLocalNames.add(t),o.storyboards.push({id:e,localName:t,typeName:n,init:d,editStatementSpan:s,declarationStart:i,ownerKind:r,declaratorCount:l}))};for(const e of r){const n=nodeSpan(e);if(!n)continue;if("ExportAllDeclaration"===e.type){a.push("export * declarations require manual migration");continue}if("ExportDefaultDeclaration"===e.type){if(l+=1,l>1){a.push("Multiple default exports require manual migration");continue}readDefaultExport(e,n,t,s,o,a);continue}if("ExportNamedDeclaration"!==e.type)continue;if("type"===e.exportKind)continue;if(e.source){a.push("Re-export declarations with a source require manual migration");continue}if(e.declaration){if("VariableDeclaration"===e.declaration.type){const t=e.declaration.declarations??[];for(const r of t){if("Identifier"!==r?.id?.type)continue;const s=r.id.typeAnnotation?.typeAnnotation,o=legacyTypeName(s)??(s||"const"!==e.declaration.kind?null:inferUnannotatedFactoryStoryboardType(r.init,i));addStoryboard(r.id.name,r.id.name,o,"declaration-export",n,e.declaration.start,t.length,r.init)}}continue}const r=e.specifiers??[];if(0===r.length)continue;const c=[];let d=!0;for(const e of r){const t=identifierName(e.local),n=identifierName(e.exported??e.local);if("type"===e?.exportKind){a.push(`Type-only export specifier "${t??"<unknown>"}" cannot be mixed with value export specifiers in a legacy canvas migration — requires manual migration`),d=!1;continue}if(!t||!n){a.push(exportSpecifierUnsupportedMessage(t??"<unknown>",n??t??"<unknown>")),d=!1;continue}const r=s.get(t),o=r?.typeName??(r&&!r.hasTypeAnnotation&&"const"===r.kind?inferUnannotatedFactoryStoryboardType(r.init,i):null);r&&isLegacyStoryboardType(o)?c.push({exportedName:n,localName:t,typeName:o,binding:r}):(a.push(exportSpecifierUnsupportedMessage(t,n)),d=!1)}if(d){o.specifierExportSpans.push(n);for(const e of c)addStoryboard(e.exportedName,e.localName,e.typeName,"specifier-export",e.binding.statementSpan,e.binding.statementSpan.start,e.binding.declaratorCount,e.binding.init)}}if(a.length>0)throw new nD(a);return o}function inferUnannotatedFactoryStoryboardType(e,t){const n=unwrapTsExpression(e);if("CallExpression"!==n?.type)return null;const r=unwrapTsExpression(n.callee);if("Identifier"!==r?.type)return null;const s=t.get(r.name);return"TempoStoryboard"===s?s:null}function exportSpecifierUnsupportedMessage(e,t){const n=e===t?"":` (exported as "${t}")`;return`Export specifier "${e}"${n} does not reference a recognizable legacy storyboard; migration would drop its export — requires manual migration`}function readDefaultExport(e,t,n,r,s,i){const o=unwrapTsExpression(e.declaration);if("Identifier"===o?.type){const e=r.get(o.name),i=unwrapTsExpression(e?.init),a=readObjectStringProperty(i,"name");a&&(s.canvasName=a);const c=isCleanConfigObject(i)&&void 0!==e&&!isBindingReferencedOutside(s.program,o.name,[e.statementSpan,t]);return void(c?(s.configMode="inline",s.backgroundColorLiteral=readObjectStringProperty(i,"backgroundColor")??void 0,s.defaultExportEdits.push({...expandStatementForward(n,t),value:""},{...expandStatementForward(n,e.statementSpan),value:""})):(s.configMode="kept",s.pageBindingName=o.name,s.hasPageBackgroundColor=hasObjectProperty(i,"backgroundColor"),s.defaultExportEdits.push({...expandStatementForward(n,t),value:""})))}if("ObjectExpression"===o?.type){const r=readObjectStringProperty(o,"name");if(r&&(s.canvasName=r),isCleanConfigObject(o))s.configMode="inline",s.backgroundColorLiteral=readObjectStringProperty(o,"backgroundColor")??void 0,s.defaultExportEdits.push({...expandStatementForward(n,t),value:""});else{const t=pickAvailableIdentifier2(collectSourceIdentifiers(n),"page");s.configMode="kept",s.pageBindingName=t,s.hasPageBackgroundColor=hasObjectProperty(o,"backgroundColor"),s.defaultExportEdits.push({start:e.start,end:o.start,value:`const ${t} = `})}return}i.push("Default export must be a page object or identifier")}function planStoryboard(e,t,n,r){const s=unwrapTsExpression(e.init);if("TempoRouteStoryboard"===e.typeName){let n=validateForwardedStoryboardProperties("TempoRouteStoryboard",e.id,s,sD,r);const i=readObjectStringProperty(s,"name");if(hasObjectProperty(s,"name")&&null===i&&(r.push(`Legacy TempoRouteStoryboard export "${e.id}" requires a literal name string when name is set`),n=!1),!n)return null;const o=readObjectLayoutProperty(s);if(!o||void 0===o.width||void 0===o.height)return r.push(`Legacy TempoRouteStoryboard export "${e.id}" requires a literal layout object`),null;const a=readObjectStringProperty(s,"route");return a?{kind:"route",id:e.id,route:a,...i?{name:i}:{},layout:o,scan:e,keepDeclaration:isBindingReferencedOutsideDeclaration(e,t)}:(r.push(`Legacy TempoRouteStoryboard export "${e.id}" requires a literal route string`),null)}if("TempoHtmlStoryboard"===e.typeName){let n=validateForwardedStoryboardProperties("TempoHtmlStoryboard",e.id,s,iD,r);const i=readObjectStringProperty(s,"name");if(hasObjectProperty(s,"name")&&null===i&&(r.push(`Legacy TempoHtmlStoryboard export "${e.id}" requires a literal name string when name is set`),n=!1),!n)return null;const o=readObjectLayoutProperty(s);if(!o||void 0===o.width||void 0===o.height)return r.push(`Legacy TempoHtmlStoryboard export "${e.id}" requires a literal layout object`),null;const a=readObjectStringProperty(s,"filepath");return a?{kind:"html",id:e.id,filepath:a,...i?{name:i}:{},layout:o,scan:e,keepDeclaration:isBindingReferencedOutsideDeclaration(e,t)}:(r.push(`Legacy TempoHtmlStoryboard export "${e.id}" requires a literal filepath string`),null)}const i=readObjectStringProperty(s,"name")??void 0;return planComponentStoryboard(e,s,t,n,i)}function planComponentStoryboard(e,t,n,r,s){const i={kind:"component",conversion:"WRAPPER",id:e.id,scan:e};if(r)return i;if(!isNativeEligible(e,t,n))return i;const o=getRenderFunction(t);if(!o)return i;const a=readObjectLayoutProperty(t);if(!a)return i;"root-element"===readObjectStringProperty(getObjectPropertyFromNode(t,"layout")?.value,"intrinsicSizing")&&(a.intrinsicSizing="root-element");const c=classifyRenderComponent(o,n);return"HOISTED"===c.conversion?{kind:"component",conversion:"HOISTED",id:e.id,...s?{name:s}:{},layout:a,componentExpr:e.localName,renderFn:o,scan:e}:{kind:"component",conversion:c.conversion,id:e.id,...s?{name:s}:{},layout:a,componentExpr:c.componentExpr,...c.propsExpr?{propsExpr:c.propsExpr}:{},scan:e}}var sD=new Set(["name","route","layout"]),iD=new Set(["name","filepath","layout"]);function validateForwardedStoryboardProperties(e,t,n,r,s){if(!n||"ObjectExpression"!==n.type)return!0;let i=!0;for(const o of n.properties??[]){if("SpreadElement"===o?.type){s.push(`Legacy ${e} export "${t}" has a spread property that migration cannot carry over — requires manual migration`),i=!1;continue}if("Property"!==o?.type){s.push(`Legacy ${e} export "${t}" has an unsupported property entry that migration cannot carry over — requires manual migration`),i=!1;continue}if(o.computed){s.push(`Legacy ${e} export "${t}" has a computed property key that migration cannot carry over — requires manual migration`),i=!1;continue}const n=readPropertyKeyName3(o.key);n?"get"!==o.kind&&"set"!==o.kind?r.has(n)||(s.push(`Legacy ${e} export "${t}" has property "${n}" that migration cannot carry over — requires manual migration`),i=!1):(s.push(`Legacy ${e} export "${t}" has ${"get"===o.kind?"getter":"setter"} property "${n}" that migration cannot carry over — requires manual migration`),i=!1):(s.push(`Legacy ${e} export "${t}" has a non-static property key that migration cannot carry over — requires manual migration`),i=!1)}return i}function isNativeEligible(e,t,n){if(!t||"ObjectExpression"!==t.type)return!1;let r=!1;for(const e of t.properties??[]){if("SpreadElement"===e?.type)return!1;if("Property"!==e?.type||e.computed)return!1;if("get"===e.kind||"set"===e.kind)return!1;const t=readPropertyKeyName3(e.key);if("render"!==t&&"name"!==t&&"layout"!==t)return!1;if("render"===t){if(r=!0,e.method)return!1;const t=e.value;if("ArrowFunctionExpression"!==t?.type&&"FunctionExpression"!==t?.type)return!1;if(0!==(t.params?.length??0))return!1}}if(!r)return!1;const s=getObjectPropertyFromNode(t,"name");return!(s&&!isStringLiteral(s.value))&&(!!readObjectLayoutProperty(t)&&(!(e.declaratorCount>1)&&!isBindingReferencedOutsideDeclaration(e,n)))}function isBindingReferencedOutsideDeclaration(e,t){return isBindingReferencedOutside(t.program,e.localName,[e.editStatementSpan,...t.specifierExportSpans])}function getRenderFunction(e){const t=getObjectPropertyFromNode(e,"render"),n=t?.value;return"ArrowFunctionExpression"===n?.type||"FunctionExpression"===n?.type?n:null}function classifyRenderComponent(e,t){const n=resolveRenderBody(e);if(!n||"JSXElement"!==n.type)return{conversion:"HOISTED"};const r=n.openingElement?.name,s=jsxTagRootIdentifier(r);if(!s)return{conversion:"HOISTED"};if(hasMeaningfulChildren(n))return{conversion:"HOISTED"};if(!rootIdentifierSurvives(s,t))return{conversion:"HOISTED"};const i=t.source.slice(r.start,r.end),o=n.openingElement?.attributes??[];if(0===o.length)return{conversion:"DIRECT",componentExpr:i};const a=buildPropsObject(o,t.source);return null===a?{conversion:"HOISTED"}:{conversion:"WITH_PROPS",componentExpr:i,propsExpr:a}}function resolveRenderBody(e){return"ArrowFunctionExpression"===e.type?"BlockStatement"===e.body?.type?singleReturnExpression(e.body):unwrapTsExpression(e.body):"FunctionExpression"===e.type?singleReturnExpression(e.body):null}function singleReturnExpression(e){const t=(e?.body??[]).filter(Boolean);if(1!==t.length)return null;const n=t[0];return"ReturnStatement"===n.type&&n.argument?unwrapTsExpression(n.argument):null}function jsxTagRootIdentifier(e){if("JSXIdentifier"===e?.type)return/^[A-Z]/.test(e.name)?e.name:null;if("JSXMemberExpression"===e?.type){let t=e.object;for(;"JSXMemberExpression"===t?.type;)t=t.object;return"JSXIdentifier"===t?.type?t.name:null}return null}function hasMeaningfulChildren(e){for(const t of e.children??[]){if("JSXText"===t?.type){if("string"==typeof t.value&&""===t.value.trim())continue;return!0}return!0}return!1}function rootIdentifierSurvives(e,t){return!!t.imports.has(e)||t.moduleBindingNames.has(e)&&!t.storyboardLocalNames.has(e)}function buildPropsObject(e,t){const n=[];for(const r of e){if("JSXSpreadAttribute"===r?.type){n.push(`...${t.slice(r.argument.start,r.argument.end)}`);continue}if("JSXAttribute"!==r?.type)return null;if("JSXIdentifier"!==r.name?.type)return null;const e=r.name.name;if("key"===e||"ref"===e)return null;const s=/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e),i=r.value;if(null!=i){if(!isStringLiteral(i)){if("JSXExpressionContainer"===i.type){const e=i.expression;if(!e||"JSXEmptyExpression"===e.type)return null;if("JSXElement"===e.type||"JSXFragment"===e.type)return null;if(isStringLiteral(e)){n.push(`${s}: ${JSON.stringify(e.value)}`);continue}n.push(`${s}: ${t.slice(e.start,e.end)}`);continue}return null}n.push(`${s}: ${JSON.stringify(decodeJsxEntities(i.value))}`)}else n.push(`${s}: true`)}return`{ ${n.join(", ")} }`}function declarationEdits(e,t){const n=e.scan;if("component"!==e.kind)return e.keepDeclaration?stripExportPrefixEdits(n):[{...expandStatementForward(t,n.editStatementSpan),value:""}];if("DIRECT"===e.conversion||"WITH_PROPS"===e.conversion)return[{...expandStatementForward(t,n.editStatementSpan),value:""}];if("HOISTED"===e.conversion){const r=t.slice(e.renderFn.start,e.renderFn.end);return[{start:n.editStatementSpan.start,end:n.editStatementSpan.end,value:`const ${n.localName} = ${r};`}]}return stripExportPrefixEdits(n)}function stripExportPrefixEdits(e){return"declaration-export"===e.ownerKind?[{start:e.editStatementSpan.start,end:e.declarationStart,value:""}]:[]}var oD=new Set(["TempoStoryboard","TempoRouteStoryboard","TempoHtmlStoryboard","TempoPage","TempoCanvasConfig"]);function removeUnusedLegacyTypeImports(e,t,n){const r=tD(e,t).program,s=Array.isArray(r?.body)?r.body:[],i=s.filter(e=>"ImportDeclaration"===e?.type);let o=t;for(const e of[...i].sort((e,t)=>t.start-e.start))o=o.slice(0,e.start)+" ".repeat(e.end-e.start)+o.slice(e.end);const a=[];for(const e of i){if("tempo-sdk"!==e.source?.value)continue;const n=e.specifiers??[],r=n.filter(t=>"ImportSpecifier"===t?.type&&("type"===t.importKind||"type"===e.importKind)&&oD.has(t.imported?.name)&&!hasIdentifier(o,t.local?.name??""));if(0!==r.length)if(r.length!==n.length)for(const e of r)a.push(removeImportSpecifierEdit(t,e));else a.push({...expandStatementForward(t,{start:e.start,end:e.end}),value:""})}return 0===a.length?t:collapseBlankLines(applyCanvasSourceEdits(t,a),n)}function removeImportSpecifierEdit(e,t){let n=t.start,r=t.end,s=r;for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(","===e[s]){for(r=s+1;r<e.length&&(" "===e[r]||"\t"===e[r]);)r++;return{start:n,end:r,value:""}}let i=n;for(;i>0&&/\s/.test(e[i-1]??"");)i--;return","===e[i-1]&&(n=i-1),{start:n,end:r,value:""}}function neededSdkMembers(e){const t=new Set(["Canvas"]);for(const n of e)"route"===n.kind?t.add("RouteStoryboard"):"html"===n.kind?t.add("HtmlStoryboard"):"WRAPPER"===n.conversion?t.add("LegacyStoryboardV1"):t.add("Storyboard");return rD.filter(e=>t.has(e))}function resolveSdkImportNames(e,t){const n=new Set(t),r=new Map,s=[];for(const t of e){const e=n.has(t)?pickAvailableIdentifier2(n,`TempoCanvas${t}`):t;n.add(e),r.set(t,e),s.push(e===t?t:`${t} as ${e}`)}return{localNames:r,importLine:`import { ${s.join(", ")} } from "tempo-sdk/canvas";`}}function buildSdkImportEdit(e,t,n,r){const s=tD(e,t).program,i=lastImportEnd(Array.isArray(s?.body)?s.body:[])??topLevelInsertionOffset2(t),o=0===i||t.slice(0,i).endsWith(r)?"":r;return{start:i,end:i,value:`${o}${n}${r}`}}function buildCanvasProps(e){if("inline"===e.configMode){const t=[formatJsxStringAttribute("name",e.canvasName)];return void 0!==e.backgroundColorLiteral&&t.push(formatJsxStringAttribute("backgroundColor",e.backgroundColorLiteral)),t.join(" ")}if("kept"===e.configMode&&e.pageBindingName){const t=[`name={${e.pageBindingName}.name}`];return e.hasPageBackgroundColor&&t.push(`backgroundColor={${e.pageBindingName}.backgroundColor}`),t.join(" ")}return formatJsxStringAttribute("name",e.canvasName)}function toAddInput(e){return"route"===e.kind?{kind:"route",id:e.id,route:e.route,layout:e.layout,...e.name?{name:e.name}:{}}:"html"===e.kind?{kind:"html",id:e.id,filepath:e.filepath,layout:e.layout,...e.name?{name:e.name}:{}}:"WRAPPER"===e.conversion?{kind:"legacy-v1",id:e.id,storyboardExpression:e.scan.localName}:{kind:"component",id:e.id,layout:e.layout,...e.name?{name:e.name}:{},componentExpression:e.componentExpr,...e.propsExpr?{props:e.propsExpr}:{}}}function collectBindings(e){const t=new Map,collect=e=>{if("VariableDeclaration"!==e?.type)return;const n=e.declarations?.length??0;for(const r of e.declarations??[]){if("Identifier"!==r?.id?.type)continue;const s=r.id.typeAnnotation?.typeAnnotation,i=legacyTypeName(s);t.set(r.id.name,{typeName:isLegacyStoryboardType(i)?i:null,init:r.init,kind:variableDeclarationKind(e.kind),hasTypeAnnotation:void 0!==s,statementSpan:{start:e.start,end:e.end},declaratorCount:n})}};for(const t of e)collect(t),"ExportNamedDeclaration"===t?.type&&collect(t.declaration);return t}function variableDeclarationKind(e){return"let"===e||"var"===e?e:"const"}function collectLocalFunctionReturnTypes(e){const t=new Map,collect=e=>{if("FunctionDeclaration"!==e?.type||"Identifier"!==e.id?.type)return;const n=legacyTypeName(e.returnType?.typeAnnotation);isLegacyStoryboardType(n)&&t.set(e.id.name,n)};for(const t of e)collect(t),"ExportNamedDeclaration"===t?.type&&collect(t.declaration);return t}function collectImportLocalNames(e){const t=new Set;for(const n of e)if("ImportDeclaration"===n?.type)for(const e of n.specifiers??[])e?.local?.name&&t.add(e.local.name);return t}function collectModuleBindingNames(e){const t=new Set,addVariable=e=>{if("VariableDeclaration"===e?.type)for(const n of e.declarations??[])"Identifier"===n?.id?.type&&t.add(n.id.name)},addDeclaration=e=>{e&&("VariableDeclaration"===e.type?addVariable(e):"FunctionDeclaration"!==e.type&&"ClassDeclaration"!==e.type||!e.id?.name||t.add(e.id.name))};for(const t of e)addDeclaration("ExportNamedDeclaration"===t?.type?t.declaration:t);return t}function isLegacyStoryboardType(e){return"TempoStoryboard"===e||"TempoRouteStoryboard"===e||"TempoHtmlStoryboard"===e}function legacyTypeName(e){if(!e||"TSTypeReference"!==e.type)return null;const t=e.typeName;return"Identifier"===t?.type?t.name:"TSQualifiedName"===t?.type&&"Identifier"===t.right?.type?t.right.name:null}function identifierName(e){return"Identifier"===e?.type?e.name:"Literal"===e?.type&&"string"==typeof e.value?e.value:null}function isStringLiteral(e){return"Literal"===e?.type&&"string"==typeof e.value}var aD={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",copy:"©",reg:"®",trade:"™",hellip:"…",mdash:"—",ndash:"–",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",laquo:"«",raquo:"»",times:"×",divide:"÷",deg:"°",plusmn:"±",cent:"¢",pound:"£",euro:"€",yen:"¥",sect:"§",para:"¶",middot:"·",bull:"•"};function decodeJsxEntities(e){return e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g,(e,t)=>{if("#"===t[0]){const n="x"===t[1]||"X"===t[1]?Number.parseInt(t.slice(2),16):Number.parseInt(t.slice(1),10);return Number.isFinite(n)&&n>=0&&n<=1114111?String.fromCodePoint(n):e}return aD[t]??e})}function isCleanConfigObject(e){if(!e||"ObjectExpression"!==e.type)return!1;for(const t of e.properties??[]){if("Property"!==t?.type||t.computed)return!1;const e=readPropertyKeyName3(t.key);if("name"!==e&&"backgroundColor"!==e)return!1;if(!isStringLiteral(t.value))return!1}return!0}function readObjectStringProperty(e,t){const n=getObjectPropertyFromNode(e,t);return isStringLiteral(n?.value)?n.value.value:null}function hasObjectProperty(e,t){return null!==getObjectPropertyFromNode(e,t)}function readObjectLayoutProperty(e){const t=getObjectPropertyFromNode(e,"layout"),n=unwrapTsExpression(t?.value);if(!n||"ObjectExpression"!==n.type)return null;const r=readObjectNumberProperty(n,"x"),s=readObjectNumberProperty(n,"y"),i=readObjectNumberProperty(n,"width"),o=readObjectNumberProperty(n,"height");if(null==r||null==s)return null;if((null==i||null==o)&&(getObjectPropertyFromNode(n,"width")||getObjectPropertyFromNode(n,"height")))return null;const a=readObjectNumberProperty(n,"zIndex"),c=getObjectPropertyFromNode(n,"intrinsicSizing"),l=readObjectStringProperty(n,"intrinsicSizing");return c&&"root-element"!==l?null:{x:r,y:s,...null==i||null==o?{}:{width:i,height:o},...null==a?{}:{zIndex:a}}}function readObjectNumberProperty(e,t){const n=getObjectPropertyFromNode(e,t),r=unwrapTsExpression(n?.value);return"Literal"===r?.type&&"number"==typeof r.value?r.value:"UnaryExpression"===r?.type&&"-"===r.operator&&"Literal"===r.argument?.type&&"number"==typeof r.argument.value?-r.argument.value:null}function getObjectPropertyFromNode(e,t){const n=unwrapTsExpression(e);if(!n||"ObjectExpression"!==n.type)return null;for(const e of n.properties??[])if("Property"===e?.type&&!e.computed&&readPropertyKeyName3(e.key)===t)return e;return null}function readPropertyKeyName3(e){return"Identifier"===e?.type?e.name:"Literal"===e?.type&&"string"==typeof e.value?e.value:null}function isBindingReferencedOutside(e,t,n){const excluded=e=>{const t=nodeSpan(e);return!!t&&n.some(e=>t.start>=e.start&&t.end<=e.end)};let r=!1;return walkWithParent(e,(e,n,s)=>{r||"Identifier"!==e.type&&"JSXIdentifier"!==e.type||e.name===t&&(excluded(e)||isNonReferenceNamePosition(n,s)||(r=!0))}),r}function isNonReferenceNamePosition(e,t){return!!e&&(!("string"!=typeof e.type||!e.type.startsWith("Import"))||("Property"===e.type&&"key"===t&&!e.computed&&!e.shorthand||("MemberExpression"===e.type&&"property"===t&&!e.computed||"JSXMemberExpression"===e.type&&"property"===t||"JSXAttribute"===e.type&&"name"===t)))}function nodeSpan(e){return"number"==typeof e?.start&&"number"==typeof e?.end&&Number.isFinite(e.start)&&Number.isFinite(e.end)?{start:e.start,end:e.end}:null}function lastImportEnd(e){let t=null;for(const n of e){if("ImportDeclaration"!==n?.type)continue;const e=nodeSpan(n);e&&(t=Math.max(t??0,e.end))}return t}function dedupeSpans(e){const t=new Set,n=[];for(const r of e){const e=`${r.start}:${r.end}`;t.has(e)||(t.add(e),n.push(r))}return n}function collectSourceIdentifiers(e){return new Set(Array.from(e.matchAll(/\b[A-Za-z_$][\w$]*\b/g),e=>e[0]))}function pickAvailableIdentifier2(e,t){const n=/^[A-Za-z_$]/.test(t)?t:`Canvas${t}`;if(!e.has(n))return n;for(let t=2;t<1e4;t+=1){const r=`${n}${t}`;if(!e.has(r))return r}throw new Error(`Unable to find available identifier for ${t}`)}function canvasComponentName2(e){const t=toIdentifier2(e);return`${t[0].toUpperCase()}${t.slice(1)}Canvas`}function toIdentifier2(e){const t=e.replace(/[^a-zA-Z0-9_$]+/g," ").trim().split(/\s+/).map((e,t)=>{if(0===e.length)return"";const n=e.replace(/^[0-9]+/,"");if(0===n.length)return"";const r=n.toLowerCase();return 0===t?r:r[0].toUpperCase()+r.slice(1)}).join(""),n=t.length>0?t:"componentRef";return/^[a-zA-Z_$]/.test(n)?n:`component${n}`}function isReactCanvasFile(e){return void 0!==e.canvasElementSpan}async function ensureCanvasPageFileMigrated(e){const t=await VP.readFile(e,"utf-8");if(isReactCanvasFile(parseCanvasFile(e,t)))return{migrated:!1};const n=migrateLegacyCanvasToReact({filePath:e,source:t});return n.migrated?(await eD.writeFile(e,n.source),{migrated:!0}):{migrated:!1}}import cD from"fs/promises";import lD from"path";import dD from"typescript";import{readdir as uD,stat as pD}from"fs/promises";import hD from"path";var mD="index.canvas.tsx";async function pathExists9(e){try{return await pD(e),!0}catch{return!1}}async function findPageFilesInPagesRoot(e){async function walkDirectories(e){let t=[];try{t=await uD(e,{withFileTypes:!0})}catch{return[]}const n=[],r=hD.join(e,mD);await pathExists9(r)&&n.push(r);const s=await Promise.all(t.filter(e=>e.isDirectory()).map(t=>walkDirectories(hD.join(e,t.name))));return[...n,...s.flat()]}const t=await walkDirectories(e);return t.sort((e,t)=>e.localeCompare(t))}async function resolveCanvasesRoot(e){try{return(await resolveTempoConfig(e)).pagesDir}catch{return hD.join(e,"tempo","designs")}}async function findPageFilesInRepo(e){return await findPageFilesInPagesRoot(await resolveCanvasesRoot(e))}async function listPageInfosInRepo(e){const t=await findPageFilesInRepo(e.repoRoot),n=await Promise.all(t.map(async t=>{const n=await parsePageFile(t);return{filePath:t,pageDir:hD.dirname(t),repoName:e.repoName,pageName:n.pageName,storyboardNames:n.storyboards.map(e=>e.exportName),home:n.home,homeRoute:n.storyboards.some(e=>"/"===e.route)}}));return n.sort((e,t)=>e.filePath.localeCompare(t.filePath))}import{readdir as fD,stat as gD}from"fs/promises";import yD from"path";var bD="index.canvas.tsx",vD=".canvas.tsx";async function statSafe(e){try{const t=await gD(e);return{isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}async function resolveCanvasFilePath(e){const t=yD.resolve(e),n=await statSafe(t);if(!n)return null;let r;if(n.isFile){if(t.endsWith(vD))return t;r=yD.dirname(t)}else{if(!n.isDirectory)return null;r=t}const s=yD.join(r,bD);if(await statSafe(s))return s;let i;try{i=await fD(r,{withFileTypes:!0})}catch{return null}const o=i.filter(e=>e.isFile()&&e.name.endsWith(vD));return 1===o.length?yD.join(r,o[0].name):null}async function resolveCanvasDirPath(e){const t=await resolveCanvasFilePath(e);return t?yD.dirname(t):null}import{execFile as wD}from"child_process";import{access as _D,mkdir as xD,readFile as TD,rm as kD,stat as SD}from"fs/promises";import ED from"path";import{promisify as AD}from"util";var CD=AD(wD);async function pathExists10(e){try{return await _D(e),!0}catch{return!1}}function slugifySegment(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function slugifyPageName(e){return e.split("/").map(slugifySegment).filter(e=>e.length>0).join("/")}function normalizeStoryboard(e){const t=e.exportName?.trim();if(!t)throw new Error("Each storyboard must provide a non-empty exportName");const n=Number.isFinite(e.width)?Math.max(1,Math.round(e.width)):IP,r=Number.isFinite(e.height)?Math.max(1,Math.round(e.height)):PP,s="string"==typeof e.route&&e.route.trim().length>0,i=Boolean(e.importPath?.trim()),o=e.preview?.trim()??"";if(""!==o&&(s||i))throw new Error(`Storyboard "${t}" sets preview, which cannot be combined with route or importPath`);if(!s&&!i&&""===o)throw new Error(`Storyboard "${t}" must provide route, importPath or preview`);return{exportName:t,...e.name?{name:e.name}:{},...e.importPath?{importPath:e.importPath}:{},...e.importName?{importName:e.importName}:{},...s?{route:e.route}:{},...o?{preview:o}:{},width:n,height:r}}function buildInitSummary(e){return{projectRoot:e.projectRoot,tempobookPath:e.tempobookPath,typesFile:"",tsconfigUpdated:!1,initializedNow:e.initializedNow??!0,waitedForInFlight:!1,usedCachedResult:!1,filesUpdated:e.changedFiles,installPerformed:!1,warnings:[]}}function notInitializedMessage(e){return`Project is not initialized for Tempo canvases: no tempo.config.json found in ${e} or ${ED.join(e,"tempo")}. Run canvas_project_init first.`}async function useProject(e,t,n,r){if(t)return await r(t,null);const s=await UI.open(e);try{const e=await s.initializeExistingProject({framework:n});return await r(s,e)}finally{await s.dispose()}}async function useExistingProject(e,t,n){if(!await tempoConfigExists(e))throw new Error(notInitializedMessage(e));if(t)return await n(t);const r=await UI.open(e);try{return await n(r)}finally{await r.dispose()}}async function initializePagesSupport(e){const t=ED.resolve(e.projectRoot);return useProject(t,e.project,e.framework,async(n,r)=>{const s=r?.config??await n.getResolvedConfig();let i=r?[...r.devserverInit.changedFiles]:[];const o=await setUpFlutterApp(s);if(o.packages.length>0&&o.flutterOnly?await seedFlutterHomeCanvas(s,o):await seedHomeCanvas(s),await seedZoneDirectories(s),e.onLog?.(`[page-tools] Tempo host at ${s.tempoRoot}`),e.forceRegenerate){const e=await n.reconcile("page-tools-force-regenerate");i=Array.from(new Set([...i,...e.devserver.changedFiles]))}e.onLog?.("[page-tools] Initialization complete.");const a=null!==r?e.framework:void 0;return{...buildInitSummary({projectRoot:t,tempobookPath:s.tempoRoot,changedFiles:i}),warnings:[...r?.warnings??[],...o.warnings],framework:a??await n.getFramework()}})}function resolveCanvasLocalStubPath(e,t,n){if(!e.startsWith("./")&&!e.startsWith("../"))return null;const r=ED.resolve(t,componentImportPath(e)),s=ED.relative(t,r);return s.startsWith("..")||ED.isAbsolute(s)?null:hasComponentModuleExtension(r)?r:`${r}${qP[n].extension}`}var ID=[...new Set([".tsx",".ts",".jsx",".js",...Object.values(qP).map(e=>e.extension)])];async function canvasImportSpecifier(e,t,n){const r=componentImportPath(e),s=e.slice(r.length),i=r.startsWith("./")||r.startsWith("../");if(i)return e;const relativeToCanvas=e=>{const t=ED.relative(n,e).split(ED.sep).join("/");return`${t.startsWith(".")?"":"./"}${t}${s}`};if(ED.isAbsolute(r))return relativeToCanvas(r);const o=ED.resolve(t,r);if(!await isImportableModule(o))return e;const a=r.startsWith("@")?r.split("/").slice(0,2).join("/"):r.split("/")[0],c=await findInstalledPackageDir2(n,a);if(c)throw new Error(`import_path "${e}" names both the project file ${o} and the installed package at ${c}. Pass the project file relative to the canvas folder ("${relativeToCanvas(o)}"), or the package import exactly as the app writes it.`);return relativeToCanvas(o)}async function isImportableModule(e){const isFile2=async e=>{try{return(await SD(e)).isFile()}catch{return!1}};if(await isFile2(e))return!0;for(const t of ID){if(await isFile2(`${e}${t}`))return!0;if(await isFile2(ED.join(e,`index${t}`)))return!0}return!1}async function findInstalledPackageDir2(e,t){let n=e;for(;;){const e=ED.join(n,"node_modules",t);if(await pathExists10(e))return e;const r=ED.dirname(n);if(r===n)return null;n=r}}async function scaffoldCanvasLocalStubs(e,t,n){const r=new Set,s=new Set;for(const i of e){if(!i.importPath)continue;const e=storyboardFrameworkForImport(i.importPath,n),o=resolveCanvasLocalStubPath(i.importPath,t,e);o&&(r.has(o)?s.add(i.exportName):await pathExists10(o)||(await xD(ED.dirname(o),{recursive:!0}),await eD.writeFile(o,qP[e].stub(i.exportName,i.importName)),r.add(o),s.add(i.exportName)))}return s}async function markCanvasAsHome(e){const t=await TD(e,"utf-8");if(sourceHasHomeMarker(t))return!1;const n=`${CP}\n${t}`;return await eD.writeFile(e,n),!0}async function unmarkCanvasAsHome(e){const t=await TD(e,"utf-8");if(!sourceHasHomeMarker(t))return!1;const n=t.split("\n").filter(e=>!e.includes(AP)).join("\n");return await eD.writeFile(e,n),!0}async function createPage(e){const t=ED.resolve(e.projectRoot),n=e.pageName?.trim();if(!n)throw new Error("pageName is required");if(!await pathExists10(t))throw new Error(`Project root does not exist: ${t}`);return useExistingProject(t,e.project,async r=>{const s=await r.getResolvedConfig(),i=await r.getUiFramework(),o=buildInitSummary({projectRoot:t,tempobookPath:s.tempoRoot,changedFiles:[],initializedNow:!1}),a=slugifyPageName(n);if(!a)throw new Error(`Unable to derive a valid canvas slug from pageName "${e.pageName}"`);const c=a.split("/"),l=c.length>1?ED.join(s.pagesDir,...c):ED.join(await resolveFreeformCanvasesDir(s.pagesDir),a),d=ED.join(l,"index.canvas.tsx");if(await pathExists10(d))throw new Error(`Canvas already exists: ${d}`);const u=await Promise.all((e.storyboards??[]).map(async e=>{const n=normalizeStoryboard(e);if(!n.importPath)return n;const r=await canvasImportSpecifier(n.importPath,t,l);return{...n,importPath:r}})),p=u.map(e=>({name:e.exportName,width:e.width,height:e.height})),m=computeStoryboardPositions({existing:[],newStoryboards:p}),f=u.map((e,t)=>({...e,x:m[t].x,y:m[t].y,width:m[t].width,height:m[t].height})),g=n.split("/").filter(Boolean).pop()??n,y=generatePageFileContent({pageName:g,storyboards:f,home:e.home,backgroundColor:e.backgroundColor,uiFramework:i});await xD(l,{recursive:!0}),await eD.writeFile(d,y);const b=await scaffoldCanvasLocalStubs(u,l,i);return{projectRoot:t,pageDir:l,pageFile:d,pageSlug:a,storyboards:f.map((e,t)=>({exportName:e.exportName,x:e.x,y:e.y,width:m[t].width,height:m[t].height,...b.has(e.exportName)?{stub:!0}:{}})),initResult:o}})}import PD from"path";import DD from"typescript";import RD from"path";import{relative as ND}from"path";import{access as OD,readdir as FD,readFile as LD}from"fs/promises";import{basename as MD,join as UD}from"path";import{access as jD,stat as BD}from"fs/promises";import{join as $D}from"path";var WD={NPM:"npm",YARN:"yarn",PNPM:"pnpm",BUN:"bun"};import{readFile as HD}from"fs/promises";import{join as qD}from"path";function toStringRecord2(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>"string"==typeof e))}async function readPackageJson(e){const t=qD(e,"package.json");let n,r;try{n=await HD(t,"utf8")}catch(e){const n=e instanceof Error?e.message:"Unknown read error";throw new Error(`Could not read package.json at ${t}: ${n}`)}try{r=JSON.parse(n)}catch(e){const n=e instanceof Error?e.message:"Unknown JSON parse error";throw new Error(`Invalid package.json at ${t}: ${n}`)}if(!r||"object"!=typeof r||Array.isArray(r))throw new Error(`Invalid package.json at ${t}: expected object`);const s=r,i=toStringRecord2(s.dependencies),o=toStringRecord2(s.devDependencies);return{dependencies:i,devDependencies:o,allDependencies:{...i,...o},scripts:toStringRecord2(s.scripts),packageManager:"string"==typeof s.packageManager?s.packageManager:void 0}}import{access as zD}from"fs/promises";import{join as GD}from"path";var VD=[{files:["bun.lockb","bun.lock"],packageManager:WD.BUN},{files:["pnpm-lock.yaml"],packageManager:WD.PNPM},{files:["yarn.lock"],packageManager:WD.YARN},{files:["package-lock.json"],packageManager:WD.NPM}];import{access as KD,readFile as XD}from"fs/promises";import{join as YD,normalize as JD}from"path";import QD from"typescript";import{isBuiltin as ZD}from"module";import eR from"path";import tR from"typescript";import nR from"typescript";var rR=/\.(?:ts|tsx|mts|cts)$/;function collectValueIdentifiers(e){const t=new Set;function isDeclarationName(e){const t=e.parent;if(!t)return!1;if(nR.isImportSpecifier(t)||nR.isImportClause(t)||nR.isNamespaceImport(t)||nR.isImportEqualsDeclaration(t))return!0;const isNameOf=t=>t.name===e;return nR.isPropertyAccessExpression(t)?t.name===e:(nR.isPropertyAssignment(t)||nR.isJsxAttribute(t)||!!(nR.isPropertyDeclaration(t)||nR.isMethodDeclaration(t)||nR.isPropertySignature(t)||nR.isGetAccessorDeclaration(t)||nR.isSetAccessorDeclaration(t)||nR.isEnumMember(t)))&&isNameOf(t)}function visit2(e){nR.isTypeNode(e)||nR.isInterfaceDeclaration(e)||nR.isTypeAliasDeclaration(e)||nR.isImportDeclaration(e)||(nR.isIdentifier(e)&&!isDeclarationName(e)&&t.add(e.text),nR.forEachChild(e,visit2))}return visit2(e),t}function extractImportEdges(e,t,n){const r=nR.createSourceFile(e,t,nR.ScriptTarget.Latest,!0),s=rR.test(e),i=n||!s;let o;const isUsedAsValue=e=>(o??=collectValueIdentifiers(r)).has(e),a=[];function addEdge(e,t,n,s){if(!e||!nR.isStringLiteralLike(e))return;const i=r.getLineAndCharacterOfPosition(e.getStart(r));a.push({specifier:e.text,form:t,valueNames:n,loadsAtRuntime:s,line:i.line+1,column:i.character})}function importDeclarationEdge(e){const t=e.importClause;if(!t)return void addEdge(e.moduleSpecifier,"static",[],!0);if(t.isTypeOnly)return void addEdge(e.moduleSpecifier,"static",[],!1);const r=t.namedBindings,s=r&&nR.isNamedImports(r)?r.elements.filter(e=>!e.isTypeOnly):[],o=!t.name&&void 0!==r&&nR.isNamedImports(r)&&r.elements.length>0&&0===s.length;if(!n&&o)return void addEdge(e.moduleSpecifier,"static",[],!1);const a=[];let c=!1;t.name&&(i||isUsedAsValue(t.name.text))&&(a.push("default"),c=!0);for(const e of s)(i||isUsedAsValue(e.name.text))&&(a.push((e.propertyName??e.name).text),c=!0);r&&nR.isNamespaceImport(r)&&(i||isUsedAsValue(r.name.text))&&(c=!0),addEdge(e.moduleSpecifier,"static",a,i||c)}function exportDeclarationEdge(e){if(!e.moduleSpecifier)return;if(e.isTypeOnly)return void addEdge(e.moduleSpecifier,"static",[],!1);const t=e.exportClause;if(t&&nR.isNamedExports(t)){const r=t.elements.filter(e=>!e.isTypeOnly);if(!n&&t.elements.length>0&&0===r.length)return void addEdge(e.moduleSpecifier,"static",[],!1);const s=r.map(e=>(e.propertyName??e.name).text);return void addEdge(e.moduleSpecifier,"static",s,!0)}addEdge(e.moduleSpecifier,"static",[],!0)}function visit2(e){if(!nR.isTypeNode(e))if(nR.isImportDeclaration(e))importDeclarationEdge(e);else if(nR.isExportDeclaration(e))exportDeclarationEdge(e);else if(nR.isImportEqualsDeclaration(e))!e.isTypeOnly&&nR.isExternalModuleReference(e.moduleReference)&&addEdge(e.moduleReference.expression,"require",[],!0);else{if(nR.isCallExpression(e)){const t=e.expression.kind===nR.SyntaxKind.ImportKeyword,n=nR.isIdentifier(e.expression)&&"require"===e.expression.text;(t||n)&&addEdge(e.arguments[0],t?"dynamic":"require",[],!0)}nR.forEachChild(e,visit2)}}return visit2(r),a}import{access as sR}from"fs/promises";import iR from"path";async function exists2(e){try{return await sR(e),!0}catch{return!1}}function importerResolutionDirs(e,t){const n=iR.resolve(t),r=[];let s=iR.dirname(iR.resolve(e));for(;r.push(s),s!==n;){const e=iR.dirname(s);if(e===s)break;const t=iR.relative(n,e);if(t.startsWith("..")||iR.isAbsolute(t))break;s=e}return r}async function packageResolvesFromImporter(e,t,n){const r=e.split("/");for(const e of importerResolutionDirs(t,n))if(await exists2(iR.join(e,"node_modules",...r,"package.json")))return!0;return!1}async function findNearestPackageRoot(e,t){for(const n of importerResolutionDirs(e,t))if(await exists2(iR.join(n,"package.json")))return n;return null}function repoRootForCanvasWalk(e){const t=iR.resolve(e);return"tempo"===iR.basename(t)?iR.dirname(t):t}function isServerComponentOnlySpecifier(e){const t=e.split("?")[0].split("#")[0];return"server-only"===t||"next/headers"===t||t.startsWith("next/headers/")||"next/root-params"===t}function extractPackageName(e){const t=e.split("?")[0].split("#")[0];if(!t||t.startsWith(".")||t.startsWith("/")||t.startsWith("~")||t.includes(":"))return null;if(t.startsWith("@")){const e=t.split("/");return e.length<2||e[0].length<2||!e[1]?null:`${e[0]}/${e[1]}`}const n=t.split("/")[0]||null;return n&&(ZD(t)||ZD(n))?null:n}function extractViteAliasKeys(e){const t=new Set;for(const n of e.matchAll(/\bfind\s*:\s*(['"`])([^'"`]+)\1/g))t.add(n[2]);for(const n of e.matchAll(/\balias\s*:\s*\{/g)){const r=n.index+n[0].length-1;let s=0,i=-1;for(let t=r;t<e.length;t+=1){const n=e[t];if("{"===n)s+=1;else if("}"===n&&(s-=1,0===s)){i=t;break}}if(i<0)continue;const o=e.slice(r+1,i);for(const e of o.matchAll(/(?:^|[,{\s])(?:(['"`])([^'"`]+)\1|([A-Za-z_$][\w$-]*))\s*:/g))t.add(e[2]??e[3])}return t}function walkImports(e,t,n,r,s){const i=new Set,o=new Map,a=new Map,c=new Map,l=tR.sys.realpath?.(r)??r,d=repoRootForCanvasWalk(l),u=s?eR.resolve(s):null,p=[e],m=[],f=new Map,g=new Map,y=new Map,b=new Map;function resolve6(e,t,s){let i=b.get(s);return i||(i=tR.createModuleResolutionCache(r,e=>e,s),b.set(s,i)),tR.resolveModuleName(e,t,s,n,i).resolvedModule}function resolveFromImporter(e,n,r){const s=r&&r.configPath!==u?resolve6(e,n,r.options):void 0;return s??resolve6(e,n,t)}function typeOnlyTarget(e,t,n){const r=resolveFromImporter(e,t,n);if(!r){const n=findRelativeTargetOnDisk(e,t);return n&&isWalkableSource(n)?n:void 0}return workspaceSourcePath(r.resolvedFileName)??(r.isExternalLibraryImport?void 0:r.resolvedFileName)}function nearestConfigPath(e){for(const t of importerResolutionDirs(eR.join(e,"__probe__"),d))for(const e of["tsconfig.json","jsconfig.json"]){const r=eR.join(t,e);if(n.fileExists(r))return r}return null}function hasAliasOptions(e){return void 0!==e.paths&&Object.keys(e.paths).length>0||void 0!==e.baseUrl}function resolveConfigOptions(e,t,n){if(t>8)return null;const r=eR.resolve(e);if(n.has(r))return null;n.add(r);const s=tR.readConfigFile(r,tR.sys.readFile);if(s.error)return null;const i=tR.parseJsonConfigFileContent(s.config,{...tR.sys,readDirectory:()=>[]},eR.dirname(r),void 0,r);if(hasAliasOptions(i.options))return i.options;const o=Array.isArray(s.config?.references)?s.config.references:[];for(const e of o){if(!e||"object"!=typeof e)continue;const s=e.path;if("string"!=typeof s)continue;const i=eR.resolve(eR.dirname(r),s),o=s.endsWith(".json")?i:eR.join(i,"tsconfig.json"),a=resolveConfigOptions(o,t+1,n);if(a&&hasAliasOptions(a))return a}return i.options}function importerConfig(e){const t=eR.dirname(e);let n=f.get(t);if(void 0===n&&(n=nearestConfigPath(t),f.set(t,n)),!n)return null;let r=g.get(n);return void 0===r&&(r=resolveConfigOptions(n,0,new Set),g.set(n,r)),r?{configPath:n,options:r}:null}function nearestViteAliasKeys(e){const t=eR.dirname(e);let r=y.get(t);if(void 0!==r)return r;r=new Set;e:for(const t of importerResolutionDirs(e,d))for(const e of["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs","vite.config.cjs"]){const s=eR.join(t,e);if(!n.fileExists(s))continue;const i=tR.sys.readFile(s);void 0!==i&&(r=extractViteAliasKeys(i));break e}return y.set(t,r),r}function matchesViteAlias(e,t){const n=e.split("?")[0].split("#")[0];for(const e of nearestViteAliasKeys(t))if(n===e||n.startsWith(`${e}/`))return!0;return!1}for(;p.length>0;){const e=p.pop(),n=tR.sys.realpath?.(e)??e;if(i.has(n))continue;i.add(n);const r=tR.sys.readFile(n);if(void 0===r)continue;const s=importerConfig(n),d=s?.options??t,u=extractImportEdges(n,r,!0===d.verbatimModuleSyntax),f=[];o.set(n,{content:r,edges:f});for(const e of u){const r=e.specifier;if(r.endsWith(".astro?tempo-component"))continue;const i={...e,external:!1,viteAlias:!1};if(f.push(i),!e.loadsAtRuntime){const e=typeOnlyTarget(r,n,s);e&&m.push(e);continue}isServerComponentOnlySpecifier(r)&&!c.has(r)&&c.set(r,eR.relative(l,n));const o=resolveFromImporter(r,n,s);if(!o){i.viteAlias=matchesViteAlias(r,n),i.aliasTargets=aliasTargets(r,d,t);const e=findRelativeTargetOnDisk(r,n);if(e){i.resolvedFile=e,isWalkableSource(e)&&p.push(e);continue}const s=extractPackageName(r),o=(i.aliasTargets??[]).some(e=>void 0!==existingFileFor(stripQuery(e)));!s||a.has(s)||i.viteAlias||o||a.set(s,eR.relative(l,n));continue}i.resolvedFile=o.resolvedFileName;const u=workspaceSourcePath(o.resolvedFileName),g=void 0!==u;if(u&&p.push(u),i.external=!0===o.isExternalLibraryImport&&!g,o.isExternalLibraryImport){const e=extractPackageName(r);e&&!a.has(e)&&a.set(e,eR.relative(l,n))}else g||p.push(o.resolvedFileName)}}const v=new Set;for(;m.length>0;){const e=tR.sys.realpath?.(m.pop())??"";if(!e||o.has(e)||v.has(e))continue;const n=tR.sys.readFile(e);if(void 0===n)continue;v.add(e);const r=importerConfig(e),s=!0===(r?.options??t).verbatimModuleSyntax;for(const t of extractImportEdges(e,n,s)){const n=typeOnlyTarget(t.specifier,e,r);n&&m.push(n)}}return{graph:o,npmPackages:a,serverOnlyImports:c,visitedFiles:i,typeOnlyFiles:v}}function workspaceSourcePath(e){const t=tR.sys.realpath?.(e)??e,n=t.split(eR.sep).includes("node_modules");return isWalkableSource(t)&&!n?t:void 0}var oR=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".json"],aR=/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;function isWalkableSource(e){return aR.test(e)&&!e.endsWith(".d.ts")}function stripQuery(e){return e.split("?")[0].split("#")[0]}function existingFileFor(e){if(tR.sys.fileExists(e))return e;for(const t of oR)if(tR.sys.fileExists(e+t))return e+t;for(const t of oR){const n=eR.join(e,`index${t}`);if(tR.sys.fileExists(n))return n}}function findRelativeTargetOnDisk(e,t){const n=stripQuery(e);if(n.startsWith("./")||n.startsWith("../"))return existingFileFor(eR.resolve(eR.dirname(t),n))}function aliasTargets(e,...t){const n=stripQuery(e);for(const e of t){if(!e.paths)continue;const t=e.pathsBasePath??e.baseUrl;if(t)for(const[r,s]of Object.entries(e.paths)){const e=r.indexOf("*"),i=e<0?r:r.slice(0,e),o=e<0?"":r.slice(e+1),a=e<0?n===r:n.startsWith(i)&&n.endsWith(o)&&n.length>=i.length+o.length;if(!a)continue;const c=e<0?"":n.slice(i.length,n.length-o.length);return s.map(e=>eR.resolve(t,e.replace("*",c)))}}}var cR=new Set(["tempo-sdk","react","react-dom"]);function isInstallableVersion(e){const t=e.trim();return!(t.startsWith("workspace:")||t.startsWith("catalog:")||t.startsWith("link:")||t.startsWith("file:")||t.startsWith("./")||t.startsWith("../"))}async function readDepsSafe(e){try{return(await readPackageJson(e)).allDependencies}catch{return{}}}var lR=["src","."];function toPosix3(e){return e.split(RD.sep).join("/")}function configBaseUrl(e){const t=QD.readConfigFile(e,QD.sys.readFile);if(!t.error)return QD.parseJsonConfigFileContent(t.config,{...QD.sys,readDirectory:()=>[]},RD.dirname(e),void 0,e).options.baseUrl}function localModuleImport(e,t,n,r,s){let i=null;for(const t of lR){const n=RD.join(r,t,...e.split("/"));if(QD.sys.directoryExists(n)){i={path:n,target:n,isFolder:!0};break}const s=existingFileFor(n);if(s){i={path:n,target:s,isFolder:!1};break}}if(!i)return null;const o=importerResolutionDirs(n,s).flatMap(e=>[RD.join(e,"tsconfig.json"),RD.join(e,"jsconfig.json")]).find(e=>QD.sys.fileExists(e))??null,a=o?configBaseUrl(o)??RD.dirname(o):r,c=toPosix3(RD.relative(a,i.path)),l=c.startsWith("../")?c:`./${c}`,d=i.isFolder?`"${e}": ["${l}"], "${e}/*": ["${l}/*"]`:`"${e}": ["${l}"]`,u=o?toPosix3(RD.relative(s,o)):`${toPosix3(RD.relative(s,RD.join(r,"tsconfig.json")))} or jsconfig.json`,p=toPosix3(RD.relative(s,i.target));return{kind:"local_module_import",name:e,required_by:t,target:p,message:`"${e}" names this project's ${i.isFolder?"folder":"file"} ${p}, not an npm package. The canvas resolves a short import like this only when a tsconfig.json or jsconfig.json maps it.`,fix:`Map it in compilerOptions.paths of ${u} (${d}), or import it with a relative path.`}}async function checkDependencies(e,t,n){const r=RD.resolve(t),s=repoRootForCanvasWalk(r),i=await readDepsSafe(r),o=[];for(const[t,n]of e){if(cR.has(t))continue;const e=RD.resolve(r,n);if(await packageResolvesFromImporter(t,e,s))continue;const a=await findNearestPackageRoot(e,s),c=a?await readDepsSafe(a):{},l=c[t]??i[t];if(!l){const r=localModuleImport(t,n,e,a??s,s);if(r){o.push(r);continue}}const d=c[t]?a:i[t]?r:null,u=l&&isInstallableVersion(l)?l:"latest",p=a&&RD.relative(s,RD.join(a,"package.json"))||"package.json";o.push({kind:"missing_package",package_name:t,version:u,required_by:n,package_root:a?RD.relative(s,a)||".":void 0,declared_in:d?RD.relative(s,RD.join(d,"package.json"))||"package.json":void 0,fix:l?`Install dependencies for ${p} (already declares "${t}")`:`Add "${t}": "${u}" to ${p} dependencies`})}const nameOf=e=>"missing_package"===e.kind?e.package_name:e.name;return o.sort((e,t)=>nameOf(e).localeCompare(nameOf(t)))}import{existsSync as dR,statSync as uR}from"fs";import pR from"path";import hR from"typescript";function checkCanvasEntry(e,t,n){const r=[],s=hR.createSourceFile(e,t,hR.ScriptTarget.Latest,!0),position=e=>{const{line:t,character:n}=s.getLineAndCharacterOfPosition(e);return{line:t+1,column:n}},i=findDefaultExport(s);"missing"!==i.kind&&"not-callable"!==i.kind||r.push({kind:"missing_default_export",file:e,...position("not-callable"===i.kind?i.node.getStart(s):0),message:"missing"===i.kind?"The canvas file has no default export; the host renders the default export.":"The canvas file's default export is not a component.",fix:"Default-export the component that renders <Canvas>, e.g. `export default function MyCanvas() { return <Canvas …>…</Canvas>; }`."});const o=n.canvasElementSpan;if(o&&"component"===i.kind){const t=i.node,n=o.start>=t.getStart(s)&&o.start<t.end;n||r.push({kind:"canvas_not_rendered",file:e,...position(o.start),message:"The <Canvas> element is not inside the default-exported component, so it never renders.",fix:"Return the <Canvas> element from the canvas file's default export."})}for(const t of n.storyboards){if("html"!==t.kind||!t.filepath?.trim())continue;const n=pR.resolve(pR.dirname(e),t.filepath),s=/\.html?$/i.test(n),i=dR(n)&&uR(n).isFile();s&&i||r.push({kind:"missing_file",file:e,...position(t.jsxElementSpan.start),specifier:t.filepath,message:i?`HtmlStoryboard filepath "${t.filepath}" is not an .html file.`:`HtmlStoryboard filepath "${t.filepath}" does not exist, so the storyboard renders blank.`,fix:"Point filepath at an existing .html file, relative to the canvas file."})}return r}var mR=new Set([hR.SyntaxKind.StringLiteral,hR.SyntaxKind.NoSubstitutionTemplateLiteral,hR.SyntaxKind.TemplateExpression,hR.SyntaxKind.NumericLiteral,hR.SyntaxKind.ObjectLiteralExpression,hR.SyntaxKind.ArrayLiteralExpression,hR.SyntaxKind.NullKeyword,hR.SyntaxKind.TrueKeyword,hR.SyntaxKind.FalseKeyword]);function findDefaultExport(e){const hasModifier=(e,t)=>hR.canHaveModifiers(e)&&(hR.getModifiers(e)??[]).some(e=>e.kind===t);for(const t of e.statements){const n=(hR.isFunctionDeclaration(t)||hR.isClassDeclaration(t))&&hasModifier(t,hR.SyntaxKind.ExportKeyword)&&hasModifier(t,hR.SyntaxKind.DefaultKeyword);if(n)return{kind:"component",node:t};if(hR.isExportAssignment(t)&&!t.isExportEquals)return classifyExpression(t.expression,e);if(hR.isExportDeclaration(t)&&!t.isTypeOnly&&t.exportClause&&hR.isNamedExports(t.exportClause)){const n=t.exportClause.elements.find(e=>"default"===e.name.text);if(!n)continue;if(t.moduleSpecifier)return{kind:"unknown"};const r=(n.propertyName??n.name).text;return resolveLocal(r,e)}}return{kind:"missing"}}function classifyExpression(e,t){let n=e;for(;hR.isParenthesizedExpression(n)||hR.isAsExpression(n)||hR.isSatisfiesExpression(n);)n=n.expression;if(mR.has(n.kind))return{kind:"not-callable",node:n};if(hR.isIdentifier(n))return resolveLocal(n.text,t);if(hR.isCallExpression(n)){const e=n.arguments[0],r=e?classifyExpression(e,t):void 0;return"component"===r?.kind?r:{kind:"unknown"}}return{kind:"component",node:n}}function resolveLocal(e,t){for(const n of t.statements){if((hR.isFunctionDeclaration(n)||hR.isClassDeclaration(n))&&n.name?.text===e)return{kind:"component",node:n};if(hR.isVariableStatement(n))for(const r of n.declarationList.declarations)if(hR.isIdentifier(r.name)&&r.name.text===e)return r.initializer?classifyExpression(r.initializer,t):{kind:"unknown"}}return{kind:"unknown"}}import{existsSync as fR,readFileSync as gR}from"fs";import{isBuiltin as yR}from"module";import bR from"path";import{parseSync as vR}from"oxc-parser";import wR from"typescript";function checkLoadability(e,t){const n=[],r=[],s=new Map;for(const[i,o]of e){const a=syntaxErrorsOf(i,o.content);if(n.push(...a),a.length>0)continue;for(const a of o.edges){if(!a.loadsAtRuntime)continue;const o=missingFile(i,a)??missingPackageSubpath(i,a,t)??missingExport(i,a,e,s);o&&n.push(o);const c=unverifiedImport(i,a)??nodeBuiltinImport(i,a);c&&r.push(c)}const c=processEnvRead(i,o.content);c&&r.push(c)}return{issues:n,warnings:r}}var _R={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"jsx",".jsx":"jsx",".mjs":"jsx",".cjs":"jsx"};function positionOf(e,t){let n=1,r=0;const s=Math.min(t,e.length);for(let t=0;t<s;t+=1)10===e.charCodeAt(t)&&(n+=1,r=t+1);return{line:n,column:s-r}}function syntaxErrorsOf(e,t){const n=_R[bR.extname(e)];if(!n||e.endsWith(".d.ts"))return[];const r=vR(e,t,{lang:n,sourceType:"module"}).errors?.[0];return r?[{kind:"syntax_error",file:e,...positionOf(t,r.labels?.[0]?.start??0),message:r.message,fix:"Fix the syntax error; the canvas host cannot compile this file."}]:[]}function isRelative(e){return e.startsWith("./")||e.startsWith("../")}function missingFile(e,t){if(t.resolvedFile||t.viteAlias)return;const n=t.aliasTargets??[],r=isRelative(t.specifier),s=n.length>0&&n.every(e=>void 0===existingFileFor(e.split("?")[0]));return r||s?{kind:"missing_file",file:e,line:t.line,column:t.column,specifier:t.specifier,message:`"${t.specifier}" does not exist, so this module cannot load.`,fix:`Create the file "${t.specifier}" points to, or fix the import path.`}:void 0}function findPackageDir(e,t,n){for(const r of importerResolutionDirs(t,n)){const t=bR.join(r,"node_modules",...e.split("/"));if(fR(bR.join(t,"package.json")))return t}}function exportsMapAllows(e,t){if("string"==typeof e||Array.isArray(e))return"."===t;if(!e||"object"!=typeof e)return!1;const n=Object.keys(e),r=n.every(e=>!e.startsWith("."));return r?"."===t:n.some(e=>{if(e===t)return!0;const n=e.indexOf("*");return n<0?e.endsWith("/")&&t.startsWith(e):t.startsWith(e.slice(0,n))&&t.endsWith(e.slice(n+1))})}function missingPackageSubpath(e,t,n){if(t.resolvedFile||t.viteAlias||t.aliasTargets?.length)return;const r=t.specifier.split("?")[0],s=extractPackageName(r);if(!s||r===s)return;const i=findPackageDir(s,e,n);if(!i)return;const o=r.slice(s.length+1);let a;try{a=JSON.parse(gR(bR.join(i,"package.json"),"utf8"))}catch{return}const c=void 0!==a.exports?exportsMapAllows(a.exports,`./${o}`):void 0!==existingFileFor(bR.join(i,o));return c?void 0:{kind:"unresolved_import",specifier:t.specifier,file:e,line:t.line,column:t.column,fix:`"${s}" is installed but does not provide "${o}". Import an entry point the package exports.`}}var xR=16,TR=/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;function canonicalPath(e){return wR.sys.realpath?.(e)??e}function runtimeExportsOf(e,t,n,r=0){const s=n.get(e);if(void 0!==s)return s;n.set(e,new Set);const i=computeRuntimeExports(e,t,n,r);return n.set(e,i),i}function computeRuntimeExports(e,t,n,r){if(r>xR||e.endsWith(".d.ts")||e.endsWith(".json"))return null;const s=t.get(e)?.content??wR.sys.readFile(e);if(void 0===s)return null;const i=wR.createSourceFile(e,s,wR.ScriptTarget.Latest,!1),o=new Set;let a=!1;const hasModifier=(e,t)=>wR.canHaveModifiers(e)&&(wR.getModifiers(e)??[]).some(e=>e.kind===t);function addBindingNames(e){if(wR.isIdentifier(e))o.add(e.text);else for(const t of e.elements)wR.isBindingElement(t)&&addBindingNames(t.name)}for(const s of i.statements){if(wR.isImportDeclaration(s)&&(a=!0),wR.isExportAssignment(s)){if(s.isExportEquals)return null;a=!0,o.add("default");continue}if(wR.isExportDeclaration(s)){if(a=!0,s.isTypeOnly)continue;const i=s.exportClause;if(i&&wR.isNamedExports(i)){for(const e of i.elements)e.isTypeOnly||o.add(e.name.text);continue}if(i&&wR.isNamespaceExport(i)){o.add(i.name.text);continue}const c=s.moduleSpecifier;if(!c||!wR.isStringLiteralLike(c))return null;const l=t.get(e)?.edges.find(e=>e.loadsAtRuntime&&e.specifier===c.text);if(!l?.resolvedFile||l.external||!TR.test(l.resolvedFile))return null;const d=runtimeExportsOf(canonicalPath(l.resolvedFile),t,n,r+1);if(!d)return null;for(const e of d)"default"!==e&&o.add(e);continue}if(!hasModifier(s,wR.SyntaxKind.ExportKeyword))continue;if(a=!0,hasModifier(s,wR.SyntaxKind.DeclareKeyword))continue;if(wR.isInterfaceDeclaration(s)||wR.isTypeAliasDeclaration(s))continue;if(hasModifier(s,wR.SyntaxKind.DefaultKeyword)){o.add("default");continue}if(wR.isVariableStatement(s)){for(const e of s.declarationList.declarations)addBindingNames(e.name);continue}const i=s.name;i&&wR.isIdentifier(i)&&o.add(i.text)}return a?o:null}function missingExport(e,t,n,r){if(!t.resolvedFile||t.external||0===t.valueNames.length)return;if(!TR.test(t.resolvedFile)||t.resolvedFile.endsWith(".d.ts"))return;const s=runtimeExportsOf(canonicalPath(t.resolvedFile),n,r);if(!s)return;const i=t.valueNames.find(e=>!s.has(e));if(!i)return;const o="default"===i?"a default export":`an export named "${i}"`;return{kind:"missing_export",file:e,line:t.line,column:t.column,specifier:t.specifier,name:i,message:`"${t.specifier}" does not provide ${o}, so this module fails to load.`,fix:`Import a name "${t.specifier}" actually exports, or add the export.`}}function unverifiedImport(e,t){if(!(t.resolvedFile||t.viteAlias||t.aliasTargets?.length||isRelative(t.specifier)||extractPackageName(t.specifier)||yR(t.specifier)))return{kind:"unverified_import",file:e,line:t.line,column:t.column,specifier:t.specifier,message:`"${t.specifier}" could not be resolved statically; the host may still resolve it.`,fix:"If the canvas fails to load, check that this import resolves in the canvas host."}}function nodeBuiltinImport(e,t){if(yR(t.specifier))return{kind:"client_runtime_api",file:e,line:t.line,column:t.column,message:`"${t.specifier}" is a Node built-in. In the browser it loads as an empty stub and fails when used.`,fix:"Keep Node built-ins out of components the canvas renders, or pass the data in as props."}}var kR=/\bprocess\.env\.([A-Za-z_$][\w$]*)/g,SR=/^(?:NODE_ENV|NEXT_PUBLIC_\w+)$/;function processEnvRead(e,t){if(!e.endsWith(".d.ts"))for(const n of t.matchAll(kR))if(!SR.test(n[1]))return{kind:"client_runtime_api",file:e,...positionOf(t,n.index??0),message:`process.env.${n[1]} is read in client code; unless the host defines it, \`process\` is undefined in the browser.`,fix:"Read configuration from props or a host-defined variable instead of process.env."}}import ER from"path";import AR from"v8";import{realpathSync as CR,statSync as IR}from"fs";import PR from"path";import DR from"typescript";function canonicalPath2(e){const t=PR.resolve(e);try{return CR.native(t)}catch{return t}}function compareProjectPriority(e,t){const n=t.rootDir.length-e.rootDir.length;if(0!==n)return n;const r=t.priority-e.priority;return 0!==r?r:e.id.localeCompare(t.id)}function isWithinRoot(e,t){return e===t||e.startsWith(`${t}${PR.sep}`)}function loadProject(e){const t=e.id.trim();if(!t)throw new Error("Project id must be a non-empty string");const n=canonicalPath2(e.tsconfigPath),r=canonicalPath2(e.rootDir),s=DR.readConfigFile(n,DR.sys.readFile);if(s.error)throw new Error(`Failed to read tsconfig at ${n}: ${DR.flattenDiagnosticMessageText(s.error.messageText,"\n")}`);const i=DR.parseJsonConfigFileContent(s.config,DR.sys,PR.dirname(n));if(i.errors.length>0){const e=i.errors.map(e=>DR.flattenDiagnosticMessageText(e.messageText,"\n")).join("; ");throw new Error(`Failed to parse tsconfig at ${n}: ${e}`)}const o=i.fileNames.map(e=>canonicalPath2(e));return{id:t,rootDir:r,tsconfigPath:n,priority:e.priority??0,options:i.options,fileNames:o,moduleResolutionCache:DR.createModuleResolutionCache(r,e=>e,i.options)}}var RR=/\.(?:d\.ts|ts|tsx|mts|cts|d\.mts|d\.cts)$/,NR=/\bdeclare\s+(?:global\b|module\s+["'`])/,OR=/^\s*(?:import|export)\b/m;function isGlobalDeclarationFile(e){if(!RR.test(e))return!1;const t=DR.sys.readFile(e);if(void 0===t)return!1;if(!NR.test(t)&&OR.test(t))return!1;const n=DR.createSourceFile(e,t,DR.ScriptTarget.Latest,!1);return!DR.isExternalModule(n)||n.statements.some(e=>DR.isModuleDeclaration(e)&&(0!==(e.flags&DR.NodeFlags.GlobalAugmentation)||DR.isStringLiteral(e.name)))}function mtimeOrNull(e){return IR(e,{throwIfNoEntry:!1})?.mtimeMs??null}var FR=`${PR.sep}node_modules${PR.sep}`;function isInstalledPackagePath(e){let t=e;try{t=CR(e)}catch{}return(t+PR.sep).includes(FR)}function getFileMtimeVersion(e){try{const t=IR(e);return String(t.mtimeMs)}catch{return"0"}}function createTsWorkspaceService(e){if(0===e.projects.length)throw new Error("TsWorkspaceDescriptor.projects must include at least one project");const t=canonicalPath2(e.workspaceRoot),n=e.projects.map(e=>loadProject(e)),r=new Map;for(const e of n){if(r.has(e.id))throw new Error(`Duplicate project id: ${e.id}`);r.set(e.id,e)}const s=(e.primaryProjectId?r.get(e.primaryProjectId):null)??n[0];if(e.primaryProjectId&&!r.has(e.primaryProjectId))throw new Error(`Primary project id not found: ${e.primaryProjectId}`);const i=[...n].sort(compareProjectPriority),o=new Set;for(const e of n)for(const t of e.fileNames)o.add(t);let a,c=!1;const l=new Map;let d,u=new WeakSet;const p=new Map,m=new Map;let f=0;function getOwningProject(e){const t=canonicalPath2(e);for(const e of i)if(isWithinRoot(t,e.rootDir))return e;return s}function recordResolutionInputs(e){if(u.has(e))return;u.add(e);const t=e,record=e=>{l.has(e)||isInstalledPackagePath(e)||l.set(e,mtimeOrNull(e))};let n="";for(const e of t.failedLookupLocations??[]){const t=PR.dirname(e);t!==n&&(n=t,record(t))}const r=e.resolvedModule?.resolvedFileName;r&&record(PR.dirname(r));for(const e of t.affectingLocations??[])record(e)}function resolve6(e,t,n){const r=DR.resolveModuleName(e,t,n.options,g,n.moduleResolutionCache);return recordResolutionInputs(r),r.resolvedModule}const g={fileExists:DR.sys.fileExists,readFile:DR.sys.readFile,realpath:DR.sys.realpath,directoryExists:DR.sys.directoryExists,getCurrentDirectory:()=>t,getDirectories:DR.sys.getDirectories},y={getScriptFileNames:()=>Array.from(a??o),hasInvalidatedResolutions:()=>c,getScriptVersion:e=>{const t=canonicalPath2(e),n=p.get(t);return n?String(n.version):getFileMtimeVersion(t)},getScriptSnapshot:e=>{const t=canonicalPath2(e),n=p.get(t);if(n)return DR.ScriptSnapshot.fromString(n.content);const r=DR.sys.readFile(t);return void 0!==r?DR.ScriptSnapshot.fromString(r):void 0},getCurrentDirectory:()=>t,getCompilationSettings:()=>s.options,getDefaultLibFileName:e=>DR.getDefaultLibFilePath(e),fileExists:DR.sys.fileExists,readFile:DR.sys.readFile,readDirectory:DR.sys.readDirectory,directoryExists:DR.sys.directoryExists,getDirectories:DR.sys.getDirectories,useCaseSensitiveFileNames:()=>DR.sys.useCaseSensitiveFileNames,getProjectVersion:()=>String(f),resolveModuleNames:(e,t)=>{const n=getOwningProject(t);return e.map(e=>{const r=resolve6(e,t,n);return r||(n.id!==s.id?resolve6(e,t,s):void 0)})}},b=DR.createLanguageService(y,DR.createDocumentRegistry());function afterSync(e){const t=e();return c=!1,t}return{updateFile(e,t){const n=canonicalPath2(e),r=(m.get(n)??0)+1;m.set(n,r),p.set(n,{version:r,content:t}),o.add(n),a?.add(n),f+=1},closeFile(e){const t=canonicalPath2(e);p.delete(t),f+=1},clearModuleResolutionCaches(){for(const e of n)e.moduleResolutionCache.clear();f+=1},setRootFiles(e){a=e?new Set(e.map(e=>canonicalPath2(e)).sort()):void 0,f+=1},refresh(){f+=1},refreshModuleResolutions(){f+=1;let e=!1;for(const[t,n]of l)mtimeOrNull(t)!==n&&(e=!0);if(!e)return!1;l.clear(),u=new WeakSet;for(const e of n)e.moduleResolutionCache.clear();return c=!0,!0},getGlobalDeclarationFiles:()=>(d??=[...o].filter(isGlobalDeclarationFile),d),getProgram:()=>afterSync(()=>b.getProgram()??null),getSemanticDiagnostics(e){const t=canonicalPath2(e);return afterSync(()=>b.getSemanticDiagnostics(t))},getSyntacticDiagnostics(e){const t=canonicalPath2(e);return afterSync(()=>b.getSyntacticDiagnostics(t))},getDefinition(e,t){const n=canonicalPath2(e);return afterSync(()=>b.getDefinitionAtPosition(n,t))},dispose(){b.dispose()}}}import LR from"typescript";function createIncrementalDiagnostics(){let e;const t={useCaseSensitiveFileNames:()=>LR.sys.useCaseSensitiveFileNames,createHash:LR.sys.createHash};return{get hasState(){return void 0!==e},reset(){e=void 0},dependenciesOf(t){const n=e?.getProgram(),r=n?.getSourceFile(t);return e&&r?[...e.getAllDependencies(r)]:[]},check(n,r,s={}){e=LR.createSemanticDiagnosticsBuilderProgram(n,t,e);const i=s.shouldStop??(()=>!1),o=new Map;for(const e of r){const t=n.getSourceFile(e);t&&o.set(t,e)}const a=new Map;let c=0,l=!1;for(;!l;){const t=e.getSemanticDiagnosticsOfNextAffectedFile(void 0,e=>!o.has(e));if(!t)break;const n=t.affected,r=o.get(n);void 0!==r&&(c+=1,a.set(r,[...t.result])),l=i()}const d=e.state?.semanticDiagnosticsPerFile,u=[];for(const[t,n]of o){const r=a.get(n);if(!r&&(l||i())){l=!0,u.push(n);continue}const s=r??countingRecompute(t,()=>[...e.getSemanticDiagnostics(t)]);a.set(n,[...e.getSyntacticDiagnostics(t),...s])}return{diagnostics:a,unchecked:u,recomputed:c};function countingRecompute(e,t){const n=e.resolvedPath;return d&&void 0!==n&&!d.has(n)&&(c+=1),t()}}}}import{createHash as MR}from"crypto";function unwrapOptional(e,t){if(!t.isUnion())return t;const n=t.types.find(t=>!(t.flags&e.TypeFlags.Undefined));return n??t}function resolveJsxNamespace(e,t,n,r){const s=n.resolveName?.("JSX",r,e.SymbolFlags.Namespace,!1);if(s)return s;const i=t.getCompilerOptions(),o=i.jsxImportSource??"react",a=e.resolveModuleName(`${o}/jsx-runtime`,r.fileName,i,e.sys);if(!a.resolvedModule)return;const c=t.getSourceFile(a.resolvedModule.resolvedFileName);if(!c)return;const l=n.getSymbolAtLocation(c);return l?n.getExportsOfModule(l).find(e=>"JSX"===e.name):void 0}function resolveRnStyleType(e,t,n,r,s="ViewStyle"){try{const i=e.resolveModuleName("react-native",r.fileName,t.getCompilerOptions(),e.sys);if(!i.resolvedModule)return null;const o=t.getSourceFile(i.resolvedModule.resolvedFileName);if(!o)return null;const a=n.getSymbolAtLocation(o);if(!a)return null;const c=n.getExportsOfModule(a).find(e=>e.name===s);return c?n.getDeclaredTypeOfSymbol(c):null}catch{return null}}function resolveJsxReferenceTypes(e,t,n){const r={cssProperties:null,reactNode:null,rnViewStyle:null};try{const s=t.getTypeChecker(),i=resolveRnStyleType(e,t,s,n),o={rnViewStyle:i,rnTextStyle:resolveRnStyleType(e,t,s,n,"TextStyle"),rnImageStyle:resolveRnStyleType(e,t,s,n,"ImageStyle")};let a=resolveJsxNamespace(e,t,s,n);if(!a)return{...r,...o};a.flags&e.SymbolFlags.Alias&&(a=s.getAliasedSymbol(a));const c=s.getExportsOfModule(a).find(e=>"IntrinsicElements"===e.name)??s.getDeclaredTypeOfSymbol(a).getProperty("IntrinsicElements");if(!c)return{...r,...o};const l=s.getDeclaredTypeOfSymbol(c).getProperty("div");if(!l)return{...r,...o};const d=s.getTypeOfSymbol(l),propType=t=>{const n=d.getProperty(t);if(!n)return null;const r=unwrapOptional(e,s.getTypeOfSymbol(n));return r.flags&e.TypeFlags.Undefined?null:r};return{cssProperties:propType("style"),reactNode:propType("children"),...o}}catch{return r}}var UR=new WeakMap;function componentDependencies(e,t,n){let r=UR.get(t);r||(r={imports:new Map,globals:t.getSourceFiles().filter(n=>!t.isSourceFileDefaultLibrary(n)&&!/[/\\]node_modules[/\\]/.test(n.fileName)&&(!e.isExternalModule(n)&&!n.fileName.endsWith(".json")||n.statements.some(t=>e.isModuleDeclaration(t)&&(Boolean(t.flags&e.NodeFlags.GlobalAugmentation)||e.isStringLiteral(t.name)))))},UR.set(t,r));const s=t.getTypeChecker(),i=new Set,o=[...r.globals,n];for(;o.length;){const n=o.pop();if(i.has(n)||t.isSourceFileDefaultLibrary(n))continue;if(i.add(n),/[/\\]node_modules[/\\]/.test(n.fileName))continue;let a=r.imports.get(n);if(!a){a=[];const add=t=>{if(t&&e.isStringLiteralLike(t))for(const e of s.getSymbolAtLocation(t)?.declarations??[]){const t=e.getSourceFile();t!==n&&a.push(t)}},visit2=t=>{e.isImportDeclaration(t)||e.isExportDeclaration(t)?add(t.moduleSpecifier):e.isImportTypeNode(t)&&e.isLiteralTypeNode(t.argument)?add(t.argument.literal):e.isExternalModuleReference(t)?add(t.expression):e.isCallExpression(t)&&t.expression.kind===e.SyntaxKind.ImportKeyword&&add(t.arguments[0]),e.forEachChild(t,visit2)};visit2(n),r.imports.set(n,a)}o.push(...a)}const a=t.getCompilerOptions(),c=a.configFile;return[...new Set([...[...i].map(e=>e.fileName),..."string"==typeof a.configFilePath?[a.configFilePath]:[],...c?.extendedSourceFiles??[]])]}var jR={Storyboard:{importSource:"tempo-sdk/canvas"},SvelteStoryboard:{importSource:"tempo-sdk/canvas/svelte",framework:"svelte"},VueStoryboard:{importSource:"tempo-sdk/canvas/vue",framework:"vue"}};function componentStoryboardOf(e,t){if(!t||!e.isImportSpecifier(t))return null;const n=jR[(t.propertyName??t.name).text],r=t.parent.parent.parent;return n&&e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===n.importSource?n:null}function analyzeComponentPropTypes(e,t,n,r,s){const i=t.getSourceFile(n);if(!i)return{ok:!1,reason:"file-not-in-program"};const o=t.getTypeChecker();let a,c=null;if(void 0!==s){const visit2=t=>{if(!(t.getStart(i)>s||t.end<=s)){if((e.isJsxOpeningElement(t)||e.isJsxSelfClosingElement(t))&&t.getStart(i)===s){let n=t.tagName;const r=o.getSymbolAtLocation(t.tagName),s=componentStoryboardOf(e,r?.declarations?.[0]);if(s){const r=t.attributes.properties.find(t=>e.isJsxAttribute(t)&&"component"===t.name.getText(i)),o=r&&e.isJsxAttribute(r)&&r.initializer&&e.isJsxExpression(r.initializer)?r.initializer.expression:void 0;o&&(n=o),s.framework&&(c=o?"mounted":"missing")}return void(a=o.getSymbolAtLocation(n))}e.forEachChild(t,visit2)}};visit2(i)}else{const t=o.getSymbolAtLocation(i);if(!t)return{ok:!1,reason:"not-a-module"};const n=o.getExportsOfModule(t);a=n.find(e=>e.name===r)??n.find(t=>{const n=t.flags&e.SymbolFlags.Alias?safeAliasedSymbol(o,t):t,s=n?.valueDeclaration;return s?.name?.getText()===r})??o.getSymbolsInScope(i,e.SymbolFlags.Value).find(e=>e.name===r)}const l=a&&a.flags&e.SymbolFlags.Alias?safeAliasedSymbol(o,a):a;if("missing"===c||"mounted"===c&&!l||"mounted"===c&&(l?.declarations??[]).some(t=>declaredOutsideTypeScript(e,t)))return{ok:!1,reason:"storyboard-component-unanalyzable"};if(!l)return{ok:!1,reason:"export-not-found"};const d=l.valueDeclaration??l.declarations?.[0],u=o.getTypeOfSymbolAtLocation(l,d??i),p=d?{filePath:d.getSourceFile().fileName,exportName:(()=>{const t=o.getSymbolAtLocation(d.getSourceFile());return t&&o.getExportsOfModule(t).find(t=>(t.flags&e.SymbolFlags.Alias?safeAliasedSymbol(o,t):t)===l)?.name})(),name:d.name?.getText()??l.name}:void 0,m=new Map,f=componentDependencies(e,t,d?.getSourceFile()??i),g=d?.getSourceFile()!==i?componentDependencies(e,t,i):void 0,readDefault=t=>{if(e.isBindingElement(t)&&t.initializer&&e.isIdentifier(t.name)){const n=t.initializer;let r;e.isStringLiteralLike(n)?r=n.text:e.isNumericLiteral(n)?r=Number(n.text):n.kind===e.SyntaxKind.TrueKeyword?r=!0:n.kind===e.SyntaxKind.FalseKeyword?r=!1:n.kind===e.SyntaxKind.NullKeyword?r=null:e.isPrefixUnaryExpression(n)&&n.operator===e.SyntaxKind.MinusToken&&e.isNumericLiteral(n.operand)&&(r=-Number(n.operand.text)),void 0!==r&&m.set(t.propertyName?.getText()??t.name.text,r)}e.forEachChild(t,readDefault)},y=u.getCallSignatures()[0]?.declaration;y?.parameters.forEach(readDefault);const b=resolvePropsType(e,o,u,i),v=b?null:vueInstancePropsType(o,u,i),w=b??v,x=v?HR:WR;if(!w)return u.getCallSignatures().some(e=>0===e.getParameters().length)?{ok:!0,analysis:{component:p,dependencies:f,requestDependencies:g,props:[],schema:{kind:"object",properties:{}}}}:{ok:!1,reason:"not-a-component"};const S=[];let E;const A=w.isUnion()?w.types:[w],C=new Map,describe=t=>{let n=C.get(t);return n||(n=describeValueType(e,o,t,i),C.set(t,n)),n},I=A.map(t=>{const n=Object.fromEntries(o.getPropertiesOfType(t).filter(e=>!x.has(e.name)).map(t=>[t.name,{optional:Boolean(t.flags&e.SymbolFlags.Optional),schema:describe(o.getTypeOfSymbolAtLocation(t,t.valueDeclaration??t.declarations?.[0]??i))}])),r=o.getIndexTypeOfType(t,e.IndexKind.String);return{kind:"object",properties:n,...r?{additional:describe(r)}:{}}}),P=new Map(A.flatMap(e=>o.getPropertiesOfType(e)).map(e=>[e.name,e]));for(const n of P.values()){if(x.has(n.name))continue;const r=n.valueDeclaration??n.declarations?.[0];let s;try{s=o.getTypeOfSymbolAtLocation(n,r??i)}catch{continue}S.push({name:n.name,declared:(n.declarations??[]).some(e=>{const n=e.getSourceFile();return!t.isSourceFileDefaultLibrary(n)&&!/[/\\](?:@types[/\\]react|react[/\\]).*\.d\.ts$/.test(n.fileName)}),elementSpecific:(n.declarations??[]).some(t=>{const n=t.parent;return/[/\\](?:@types[/\\]react|react[/\\]).*\.d\.ts$/.test(t.getSourceFile().fileName)&&e.isInterfaceDeclaration(n)&&/^(?!AllHTMLAttributes$).+HTMLAttributes$/.test(n.name.text)}),optional:Boolean(n.flags&e.SymbolFlags.Optional),...classifyPropType(e,o,s),...(()=>{if("style"!==n.name)return{};try{return void 0===E&&(E=resolveJsxReferenceTypes(e,t,i).cssProperties),E&&o.isTypeAssignableTo?.(E,s)?{acceptsStyleObject:!0}:{}}catch{return{}}})(),...m.has(n.name)?{defaultValue:m.get(n.name)}:{},schema:(()=>{const e=I.flatMap(e=>{const t=Object.prototype.hasOwnProperty.call(e.properties,n.name)?e.properties[n.name]:void 0;return t?[t.schema]:[]});return 1===e.length?e[0]:{kind:"union",members:e}})()})}return{ok:!0,analysis:{component:p,dependencies:f,requestDependencies:g,props:S,schema:1===I.length?I[0]:{kind:"union",members:I}}}}var BR=512,$R=Symbol("value-schema-too-large");function describeValueType(e,t,n,r){try{return buildValueSchema(e,t,n,r,new Set,0,{remaining:BR,literalBytes:256e3})}catch(e){if(e!==$R)throw e;return{kind:"unsupported"}}}function buildValueSchema(e,t,n,r,s,i,o){if(o.remaining--<=0)throw $R;const a={kind:"unsupported"};if(i>8||s.has(n))return a;const c=e.TypeFlags;if(n.flags&(c.Any|c.Unknown|c.TypeParameter|c.Never))return a;if(n.isStringLiteral()||n.isNumberLiteral()){if(o.literalBytes-=JSON.stringify(n.value).length,o.literalBytes<0)throw $R;return{kind:"literal",value:n.value}}if(n.flags&c.BooleanLiteral)return{kind:"literal",value:"true"===t.typeToString(n)};if(n.flags&c.String)return{kind:"string"};if(n.flags&c.Number)return{kind:"number"};if(n.flags&c.Boolean)return{kind:"boolean"};if(n.flags&c.Null)return{kind:"null"};const l=n.getSymbol();if("ReactElement"===l?.name&&l.declarations?.some(e=>/[/\\]@types[/\\]react[/\\]/.test(e.getSourceFile().fileName))){const e=t.getTypeArguments(n);if(e.every(e=>e.flags&(c.Any|c.Unknown)||t.typeToString(e).includes("JSXElementConstructor")))return{kind:"jsx"}}const d=new Set(s).add(n),describe=n=>buildValueSchema(e,t,n,r,d,i+1,o);if(n.isUnion()){const s=n.types.filter(e=>!(e.flags&c.Undefined)),a=s.every(e=>Boolean(e.flags&(c.StringLiteral|c.NumberLiteral|c.BooleanLiteral|c.Null)));if(a&&s.length>1e4)throw $R;if(a&&(o.literalBytes-=s.reduce((e,n)=>e+(n.isStringLiteral()||n.isNumberLiteral()?JSON.stringify(n.value).length:t.typeToString(n).length),0),o.literalBytes<0))throw $R;const l=a?s.map(n=>buildValueSchema(e,t,n,r,d,i+1,{remaining:1,literalBytes:1/0})):s.map(describe);return 1===l.length?l[0]:{kind:"union",members:l}}if(n.isIntersection()&&n.types.some(e=>e.flags&c.String)){const e=n.types.filter(e=>!(e.flags&c.String));if(e.every(e=>0===t.getPropertiesOfType(e).length&&e.flags&c.Object))return{kind:"string"}}if(t.getSignaturesOfType(n,e.SignatureKind.Call).length||t.getSignaturesOfType(n,e.SignatureKind.Construct).length)return a;if(t.isTupleType(n)){const e=n;return e.target.hasRestElement?a:{kind:"tuple",elements:t.getTypeArguments(e).map(describe),required:e.target.minLength}}if(t.isArrayType(n)){const r=t.getIndexTypeOfType(n,e.IndexKind.Number);return r?{kind:"array",element:describe(r)}:a}if(!(n.flags&(c.Object|c.Intersection)))return a;const u={};for(const s of t.getPropertiesOfType(n)){const n=s.valueDeclaration??s.declarations?.[0]??r;Object.defineProperty(u,s.name,{enumerable:!0,configurable:!0,value:{optional:Boolean(s.flags&e.SymbolFlags.Optional),schema:describe(t.getTypeOfSymbolAtLocation(s,n))}})}const p=t.getIndexTypeOfType(n,e.IndexKind.String);return{kind:"object",properties:u,...p?{additional:describe(p)}:{}}}function safeAliasedSymbol(e,t){try{return e.getAliasedSymbol(t)}catch{return null}}function resolvePropsType(e,t,n,r){const s=[...n.getCallSignatures(),...n.getConstructSignatures()];for(const n of s){const s=n.getParameters()[0];if(!s)continue;const i=s.valueDeclaration;if(!(i&&e.isParameter(i)&&i.dotDotDotToken))try{const n=t.getNonNullableType(t.getTypeOfSymbolAtLocation(s,s.valueDeclaration??r));if(!isPropsObjectType(e,n))continue;return n}catch{}}const i=n.getConstructSignatures()[0]?.getReturnType().getProperty("props");if(i)try{return t.getTypeOfSymbolAtLocation(i,i.valueDeclaration??r)}catch{return null}return null}var WR=new Set(["key","ref"]),HR=new Set(["key","ref","ref_for","ref_key","class","style","onVnodeBeforeMount","onVnodeMounted","onVnodeBeforeUpdate","onVnodeUpdated","onVnodeBeforeUnmount","onVnodeUnmounted"]);function vueInstancePropsType(e,t,n){for(const r of t.getConstructSignatures()){const t=r.getReturnType().getProperty("$props");if(t)try{return e.getTypeOfSymbolAtLocation(t,t.valueDeclaration??n)}catch{return null}}return null}function isPropsObjectType(e,t){const n=e.TypeFlags;if(t.flags&(n.Any|n.Unknown))return!1;if(t.isUnion()||t.isIntersection())return t.types.every(t=>isPropsObjectType(e,t));if(!(t.flags&n.Object))return!1;const r=t,s=e.ObjectFlags.Reference|e.ObjectFlags.Tuple;return!(r.objectFlags&e.ObjectFlags.Tuple)&&!(r.objectFlags&s&&checkerIsArrayLike(e,r))}function checkerIsArrayLike(e,t){const n=t.target,r=n?.symbol?.name??t.symbol?.name;return"Array"===r||"ReadonlyArray"===r}var qR={kind:"unsupported"};function acceptsStringValue(e,t){try{return e.isTypeAssignableTo?.(e.getStringType(),t)??!1}catch{return!1}}function classifyPropType(e,t,n){const r=e.TypeFlags,unsupported=()=>acceptsStringValue(t,n)?{kind:"unsupported",acceptsString:!0}:qR,s=(n.isUnion()?n.types:[n]).filter(e=>!(e.flags&(r.Undefined|r.Null|r.Void)));if(0===s.length)return unsupported();if(s.some(e=>e.flags&r.EnumLike))return unsupported();if(s.every(e=>e.flags&(r.Boolean|r.BooleanLiteral))){const e=new Set(s.map(e=>t.typeToString(e))),n=s.some(e=>e.flags&r.Boolean)||e.has("true")&&e.has("false");return n?{kind:"boolean"}:unsupported()}if(s.every(e=>e.flags&(r.Number|r.NumberLiteral)))return{kind:"number"};const i=[];let o=!1;for(const e of s)if(e.isStringLiteral())i.includes(e.value)||i.push(e.value);else{if(!(e.flags&r.String||e.isIntersection()&&e.types.some(e=>e.flags&r.String)))return unsupported();o=!0}return i.length>0?o?{kind:"enum",options:i,open:!0}:{kind:"enum",options:i}:o?{kind:"string"}:unsupported()}function declaredOutsideTypeScript(e,t){if(/\.(?:vue|svelte)$/.test(t.getSourceFile().fileName))return!0;for(let n=t;n;n=n.parent)if(e.isModuleDeclaration(n)&&e.isStringLiteral(n.name)&&n.name.text.includes("*"))return!0;return!1}import zR from"typescript";import GR from"typescript";function formatFixSuggestion(e,t){switch(e){case 2322:return"Change the value to match the expected type, or update the type annotation.";case 2339:return"Check the component's props interface for the correct property name.";case 2345:return"The argument type doesn't match the expected parameter type.";default:return t}}function getLineAndColumn(e){if(e.file&&void 0!==e.start){const t=e.file.getLineAndCharacterOfPosition(e.start);return{line:t.line+1,column:t.character}}return{line:0,column:0}}function typeErrorFromDiagnostic(e,t){if(!e.file)return;const n=GR.flattenDiagnosticMessageText(e.messageText," ");return{kind:"type_error",file:e.file.fileName,...getLineAndColumn(e),message:n,code:e.code,fix:formatFixSuggestion(e.code,n),provenance:t.provenance,tsconfig:t.tsconfig}}import{statSync as VR}from"fs";import KR from"path";import XR from"typescript";var YR=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock",KR.join("node_modules",".modules.yaml"),KR.join("node_modules",".package-lock.json"),KR.join("node_modules",".yarn-state.yml")];function tsconfigDependencies(e){const t=XR.readJsonConfigFile(e,XR.sys.readFile),n=XR.parseJsonSourceFileConfigFileContent(t,{...XR.sys,readDirectory:()=>[]},KR.dirname(e),void 0,e),r=(n.projectReferences??[]).map(e=>e.path.endsWith(".json")?e.path:KR.join(e.path,"tsconfig.json"));return[...t.extendedSourceFiles??[],...r]}function fingerprintsEqual(e,t){return e.tsconfig===t.tsconfig&&e.packageJson===t.packageJson&&e.tempoPackageJson===t.tempoPackageJson&&e.inputs===t.inputs}function createValidateServiceCache(e){const t=new Map;function fingerprint(t,n){const r=[t,KR.dirname(t)],s=[...e.configDependencies?.(n)??[],...r.flatMap(e=>YR.map(t=>KR.join(e,t)))];return{tsconfig:e.statMtimeMs(n),packageJson:e.statMtimeMs(KR.join(t,"package.json")),tempoPackageJson:e.statMtimeMs(KR.join(t,"tempo","package.json")),inputs:s.map(t=>`${t}=${e.statMtimeMs(t)}`).join("|")}}function buildEntry(t,n){const r={workspaceRoot:t,projects:[{id:"main",rootDir:t,tsconfigPath:n}]};return{service:e.createService(r),fingerprint:fingerprint(t,n)}}return{get(e,n){const r=KR.resolve(e),s=KR.resolve(n),i=`${r}::${s}`,o=t.get(i);if(o){const e=fingerprint(r,s);if(fingerprintsEqual(o.fingerprint,e))return o.service;try{o.service.dispose()}catch{}}const a=buildEntry(r,s);return t.set(i,a),a.service},evict(e,n){const r=`${KR.resolve(e)}::${KR.resolve(n)}`,s=t.get(r);if(s){t.delete(r);try{s.service.dispose()}catch{}}},disposeAll(){for(const e of t.values())try{e.service.dispose()}catch{}t.clear()}}}var JR=createValidateServiceCache({createService:createTsWorkspaceService,configDependencies:e=>{try{return tsconfigDependencies(e)}catch{return[]}},statMtimeMs(e){try{return VR(e).mtimeMs}catch{return null}}}),QR=5,ZR=.7,eN=.5,tN=12e4,nN=new WeakMap,rN=/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,isLocalSource=e=>rN.test(e)&&!e.endsWith(".d.ts")&&!e.includes(`${ER.sep}node_modules${ER.sep}`),megabytes=e=>Math.round(e/1048576),realPath=e=>zR.sys.realpath?.(e)??e;function runTypeCheck(e){const t=performance.now(),n=AR.getHeapStatistics().heap_size_limit;let r=0;const heapUsed=()=>{const e=AR.getHeapStatistics().used_heap_size;return r=Math.max(r,e),e};let s;const shouldStop=()=>(heapUsed()>n*ZR?s="memory":performance.now()-t>tN&&(s="time"),void 0!==s),i=e.reuse?JR.get(e.projectRoot,e.tsconfigPath):createTsWorkspaceService({workspaceRoot:e.projectRoot,projects:[{id:"main",rootDir:e.projectRoot,tsconfigPath:e.tsconfigPath}]});try{let o=nN.get(i);o&&!e.requestedCanvasOnly||(o={incremental:createIncrementalDiagnostics(),canvases:new Map},nN.set(i,o));const a=o.incremental.hasState?"warm":"cold",c=realPath(e.canvasFile),l=new Set([c,...e.reachableFiles.filter(isLocalSource)]),d=o.canvases.get(c)??new Set;o.canvases.delete(c),o.canvases.set(c,new Set([...l,...d]));let u=dropOldest(o,QR);const roots=()=>[...new Set([...o.canvases.values()].flatMap(e=>[...e])),...i.getGlobalDeclarationFiles()];i.setRootFiles(roots()),i.refreshModuleResolutions();const p=i.getProgram();if(!p)throw new Error("TypeScript produced no program for the canvas");const m=o.incremental.check(p,[...l],{shouldStop}),f=o.incremental.dependenciesOf(c).map(realPath).filter(e=>isLocalSource(e)&&!l.has(e));for(const e of f)l.add(e);const g=f.length>0&&!s?o.incremental.check(p,f,{shouldStop}):void 0;o.canvases.set(c,l),f.length>0&&i.setRootFiles(roots());const y=new Map([...m.diagnostics,...g?.diagnostics??[]]),b=[...m.unchecked,...g?.unchecked??[],...g?[]:s?f:[]],v=realPath(e.canvasesRoot),provenanceOf=e=>realPath(e).startsWith(v+ER.sep)?"canvas":"app",w=[];for(const t of y.values())for(const n of t){const t=n.file?.fileName;if(!t)continue;const r=typeErrorFromDiagnostic(n,{provenance:provenanceOf(t),tsconfig:e.tsconfigPath});r&&w.push(r)}s||w.push(...missingRequiredProps(p,e,c));const x=s?{errors:w,verified:!1}:verifyAppErrorsUnderOwnConfig(w,e,()=>heapUsed()>n*eN);"memory"===s&&e.reuse?JR.evict(e.projectRoot,e.tsconfigPath):heapUsed()>n*eN&&(u+=dropOldest(o,1));const S=o.canvases.size,E=l.size;return{typeErrors:x.errors,status:{...s?{status:"incomplete",reason:s}:{status:"passed"},files_checked:E-b.length,files_total:E,files_rechecked:m.recomputed+(g?.recomputed??0),cache:a,elapsed_ms:Math.round(performance.now()-t),peak_heap_mb:megabytes(r),heap_limit_mb:megabytes(n),retained_canvases:S,evicted_canvases:u,app_errors_verified:x.verified}}}finally{e.reuse||i.dispose()}}function dropOldest(e,t){let n=0;for(;e.canvases.size>Math.max(t,1);){const t=e.canvases.keys().next().value;e.canvases.delete(t),n+=1}return n}function missingRequiredProps(e,t,n){const r=e.getSourceFile(n);if(!r)return[];const s=[];for(const i of t.parsedCanvas.storyboards){const o="component"===i.kind&&i.component&&!i.componentFramework;if(!o||i.props)continue;const a=analyzeComponentPropTypes(zR,e,n,"default",i.jsxElementSpan.start);if(!a.ok)continue;const c=a.analysis.props.filter(e=>!e.optional).map(e=>e.name);if(0===c.length)continue;const l=a.analysis.component?.name??"its component",{line:d,character:u}=r.getLineAndCharacterOfPosition(i.jsxElementSpan.start);s.push({kind:"type_error",file:n,line:d+1,column:u,code:0,message:`Storyboard "${i.storyboardKey}" renders ${l} without props, but ${l} requires: ${c.join(", ")}.`,fix:`Pass props={{ ${c.map(e=>`${e}: …`).join(", ")} }} to the storyboard.`,provenance:"canvas",tsconfig:t.tsconfigPath})}return s}function verifyAppErrorsUnderOwnConfig(e,t,n){const r=ER.resolve(t.tsconfigPath),s=new Map,i=[],o=createOwnConfigLookup(t.projectRoot);for(const t of e){const e="app"===t.provenance?o(t.file):r;e&&e!==r?s.set(e,[...s.get(e)??[],t]):i.push(t)}let a=!0;for(const[e,t]of s){if(n()){a=!1,i.push(...t);continue}const r=reproduceUnderConfig(e,t);r?i.push(...r.map(t=>({...t,tsconfig:e}))):(a=!1,i.push(...t))}return{errors:i,verified:a}}function reproduceUnderConfig(e,t){let n;try{n=createTsWorkspaceService({workspaceRoot:ER.dirname(e),projects:[{id:"own",rootDir:ER.dirname(e),tsconfigPath:e}]})}catch{return}try{const e=[...new Set(t.map(e=>e.file))];n.setRootFiles([...e,...n.getGlobalDeclarationFiles()]);const r=new Set;for(const t of e)for(const e of[...n.getSyntacticDiagnostics(t),...n.getSemanticDiagnostics(t)]){if(!e.file||void 0===e.start)continue;const t=e.file.getLineAndCharacterOfPosition(e.start).line+1;r.add(`${realPath(e.file.fileName)}:${t}:${e.code}`)}return t.filter(e=>r.has(`${realPath(e.file)}:${e.line}:${e.code}`))}finally{n.dispose()}}function createOwnConfigLookup(e){const t=realPath(ER.resolve(e)),n="tempo"===ER.basename(t)?ER.dirname(t):t,r=new Map;function parse4(e){if(r.has(e))return r.get(e);const t=zR.readConfigFile(e,zR.sys.readFile);if(t.error)return r.set(e,null),null;const n=zR.parseJsonConfigFileContent(t.config,zR.sys,ER.dirname(e)),s={files:new Set(n.fileNames.map(e=>realPath(ER.resolve(e)))),references:(n.projectReferences??[]).map(e=>e.path.endsWith(".json")?e.path:ER.join(e.path,"tsconfig.json"))};return r.set(e,s),s}return e=>{for(const t of importerResolutionDirs(e,n))for(const n of["tsconfig.json","jsconfig.json"]){const r=ER.join(t,n);if(!zR.sys.fileExists(r))continue;const s=parse4(r);if(!s||s.files.has(realPath(e))||0===s.references.length)return ER.resolve(r);const i=s.references.find(t=>parse4(t)?.files.has(realPath(e)));return ER.resolve(i??r)}}}var sN=50;function sourcePositionForOffset(e,t){if(void 0===t||t<0)return{line:0,column:0};let n=1,r=0;const s=Math.min(t,e.length);for(let t=0;t<s;t+=1)10===e.charCodeAt(t)&&(n+=1,r=t+1);return{line:n,column:s-r}}function canvasFormatIssueFromParseError(e,t,n){const{line:r,column:s}=sourcePositionForOffset(t,n.span?.start);return{kind:"canvas_format",file:e,line:r,column:s,message:n.message,fix:"Update the canvas file so <Canvas> contains static storyboard declarations with literal ids and editable literal metadata."}}function canvasFormatIssueForDuplicateStoryboardId(e,t,n,r){const s=n.idSpan??n.jsxElementSpan,i=sourcePositionForOffset(t,r.idSpan?.start??r.jsxElementSpan.start),{line:o,column:a}=sourcePositionForOffset(t,s?.start);return{kind:"canvas_format",file:e,line:o,column:a,message:`Duplicate storyboard id "${n.storyboardKey}" also appears at line ${i.line}.`,fix:"Give every storyboard in the canvas a unique literal id."}}function isLegacyCanvasFile(e){const t=e.imports.some(e=>"tempo-sdk/canvas"===e.source||e.source.endsWith("/tempo-sdk/canvas"))||e.misimportedSdkCanvasImports.length>0,n=e.errors.filter(e=>"structural"===e.kind);return!t&&n.length>0&&n.every(e=>e.message===ev)}function getCanvasFormatIssues(e,t,n,r){if(r)return[];if(!n.canvasElementSpan&&isLegacyCanvasFile(n))return[];const s=n.errors.map(n=>canvasFormatIssueFromParseError(e,t,n)),i=new Map;for(const r of n.storyboards){if("html"===r.kind&&!r.filepath?.trim()&&r.src?.trim()&&s.push(canvasFormatIssueFromParseError(e,t,{message:'<HtmlStoryboard> must include a literal "filepath" prop naming a local .html file; to show a live URL use <RouteStoryboard route="https://…">',span:r.jsxElementSpan,kind:"degraded"})),!r.storyboardKey)continue;const n=i.get(r.storyboardKey);n?s.push(canvasFormatIssueForDuplicateStoryboardId(e,t,r,n)):i.set(r.storyboardKey,r)}return s}async function validatePage(e,t,n){const r=PD.resolve(e),s=PD.resolve(t),i=n?.tsconfigPath??PD.join(s,"tsconfig.json"),o=DD.readConfigFile(i,DD.sys.readFile);if(o.error){const e=DD.flattenDiagnosticMessageText(o.error.messageText,"\n");throw new Error(`Failed to read tsconfig at ${i}: ${e}`)}const a=DD.parseJsonConfigFileContent(o.config,{...DD.sys,readDirectory:()=>[]},PD.dirname(i),void 0,i),c=DD.sys.readFile(r);if(void 0===c)throw new Error(`Canvas file not found: ${r}`);const l=parseCanvasFile(r,c),d={fileExists:DD.sys.fileExists,readFile:DD.sys.readFile,realpath:DD.sys.realpath,directoryExists:DD.sys.directoryExists,getCurrentDirectory:()=>s,getDirectories:DD.sys.getDirectories},u=walkImports(r,a.options,d,s,i),p=checkLoadability(u.graph,repoRootForCanvasWalk(realPath2(s))),m=p.issues.some(e=>"syntax_error"===e.kind&&e.file===realPath2(r)),f=getCanvasFormatIssues(r,c,l,m),g=m||isLegacyCanvasFile(l)?[]:checkCanvasEntry(r,c,l),y=await checkDependencies(u.npmPackages,s,n?.tempoPackageDir),b=[...u.serverOnlyImports.entries()].map(([e,t])=>({kind:"server_component_import",specifier:e,file:t,message:`"${e}" is a server-only API, so this canvas renders a React Server Component. The canvas renders components client-side and cannot run server components; importing a server-only module also breaks the canvas devserver build for the whole project.`,fix:"Point the storyboard at the underlying client component (or a 'use client' wrapper) instead of the server/page component, and pass demo props in place of server data."})),v=n?.skipTypeCheck?void 0:runTypeCheck({canvasFile:r,projectRoot:s,tsconfigPath:i,canvasesRoot:n?.canvasesRoot??defaultCanvasesRoot(s),reachableFiles:[...u.graph.keys(),...u.typeOnlyFiles],parsedCanvas:l,reuse:!0===n?.reuseTypeCheckService,requestedCanvasOnly:n?.requestedCanvasOnly}),w=v?.typeErrors??[],x=w.filter(e=>"canvas"===e.provenance),S=w.filter(e=>"canvas"!==e.provenance),E=[...f,...g],A=[...p.issues,...y],C=[...b,...E,...A],statusOf=e=>e.length>0?{status:"failed"}:{status:"passed"};return{valid:0===C.length,issues:C,warnings:p.warnings,type_errors:[...x,...S.slice(0,sN)],type_error_totals:{canvas:x.length,app:S.length},canvas_type_errors:x.length,checks:{canvas_format:statusOf(E),imports:statusOf([...b,...A]),type_check:v?.status??{status:"not_run",reason:"skipped"}}}}function defaultCanvasesRoot(e){return"tempo"===PD.basename(e)?PD.join(e,"designs"):PD.join(e,"tempo","designs")}function realPath2(e){return DD.sys.realpath?.(e)??e}import{access as iN}from"fs/promises";import oN from"path";var aN="Refer to get_guide({ topic: 'tempo-canvas-instructions' }) for details on setting up the canvas infrastructure.";async function pathExists11(e){try{return await iN(e),!0}catch{return!1}}async function isUrlReachable(e){try{const t=new AbortController,n=setTimeout(()=>t.abort(),5e3),r=await fetch(e,{signal:t.signal});return clearTimeout(n),r.ok}catch{return!1}}async function validateHost(e){const t=[],n=oN.join(e.tempoRoot,"node_modules","tempo-sdk");return await pathExists11(n)||t.push({kind:"host_setup_issue",check:"dependencies_not_installed",file:n,message:"The canvas host's dependencies are not installed yet (tempo-sdk is not in its node_modules). Call start_canvas_devserver first: it runs scripts.install from tempo.config.json and starts the host. Then rerun canvas_validate.",fix:`Call start_canvas_devserver (add force_install: true after editing scripts.install), then rerun canvas_validate. ${aN}`}),e.devserverUrl?await isUrlReachable(e.devserverUrl)||t.push({kind:"host_setup_issue",check:"tempo_host_not_reachable",file:e.tempoRoot,message:`/tempo-host was not reachable at ${e.devserverUrl}.`,fix:`Call start_canvas_devserver (it restarts a host that stopped), then rerun canvas_validate; if it still fails, check_canvas_devserver reports the start error. ${aN}`}):t.push({kind:"host_setup_issue",check:"tempo_host_not_reachable",file:e.tempoRoot,message:"The devserver does not appear to be running (no devserver URL is available). Call start_canvas_devserver, then rerun canvas_validate.",fix:`Call start_canvas_devserver, then rerun canvas_validate. ${aN}`}),t}import{readFile as cN}from"fs/promises";import lN from"path";async function validateFlutterStoryboards(e){const t=await cN(e.pageFile,"utf-8").catch(()=>null);if(null===t)return[];const n=lN.join(e.projectRoot,"tempo"),r=parseCanvasFile(e.pageFile,t),s=r.storyboards.filter(e=>void 0!==e.preview),i=s.map(t=>{const r=t.preview,s=parseFlutterPreview(r);return{canvasFile:e.pageFile,storyboardId:t.storyboardKey,preview:r,key:"error"in s?null:flutterPreviewKey(n,lN.resolve(lN.dirname(e.pageFile),s.file),s.functionName)}}),o=await resolveFlutterPreviews(i,e.projectRoot,n),a=o.problems.map(n=>({kind:"canvas_format",file:e.pageFile,...positionOf2(t,s.find(e=>e.storyboardKey===n.storyboardId)?.previewSpan?.start),message:`${n.code}: ${n.message}`,fix:"Name a Dart file relative to this canvas and a public top-level @Preview function, with a valid Flutter pubspec above the file."}));for(const t of o.packages)for(const n of await findNativeOnlyImports(t.dir,t.name,t.discovery.previews.map(e=>e.libraryFile))){if("build-fails"!==n.effect)continue;const{problem:t,fix:r}=describeNativeOnlyImport(n);a.push({kind:"canvas_format",file:e.pageFile,line:0,column:0,message:t,fix:r})}return a}function positionOf2(e,t){if(void 0===t||t<0)return{line:0,column:0};const n=e.slice(0,t),r=n.split("\n").length;return{line:r,column:t-(n.lastIndexOf("\n")+1)}}import{readFile as dN}from"fs/promises";import uN from"path";import pN from"path";import{readdir as hN,stat as mN}from"fs/promises";import fN from"path";async function pathExists12(e){try{return await mN(e),!0}catch{return!1}}async function listFilesRecursively(e){const t=await hN(e,{withFileTypes:!0}),n=[];for(const r of t){const t=fN.join(e,r.name);r.isDirectory()?n.push(...await listFilesRecursively(t)):n.push(t)}return n.sort((e,t)=>e.localeCompare(t))}async function runComputeLayoutCommand(e){const t=e.new_storyboards??[];if(!Array.isArray(t))throw new Error("new_storyboards must be an array");let n=[];if(e.canvas_file){const t=await resolveCanvasFilePath(e.canvas_file)??pN.resolve(e.canvas_file);if(!await pathExists12(t))throw new Error(`Canvas file not found: ${t}`);const r=await parsePageFile(t);n=toStoryboardRects(r)}const r=t.map((e,t)=>{const n=e.name?.trim();if(!n)throw new Error(`new_storyboards[${t}] must include a non-empty name`);return{name:n,width:Number.isFinite(e.width)?Math.max(1,Math.round(e.width)):IP,height:Number.isFinite(e.height)?Math.max(1,Math.round(e.height)):PP}}),s=computeStoryboardPositions({existing:n,newStoryboards:r});return{positions:s}}import gN from"path";async function runCreatePageCommand(e){const t=gN.resolve(e.repo_root),n=e.canvas_name,r=(e.storyboards??[]).map(e=>({exportName:e.export_name,name:e.name,importPath:e.import_path,importName:e.import_name,route:e.route,preview:e.preview,width:e.width,height:e.height})),s=await createPage({projectRoot:t,pageName:n,storyboards:r,home:e.home,backgroundColor:e.background_color});return{canvas_dir:s.pageDir,canvas_file:s.pageFile,repo_root:t,storyboards:s.storyboards.map(e=>({export_name:e.exportName,x:e.x,y:e.y,width:e.width,height:e.height,...e.stub?{stub:!0}:{}}))}}import{rm as yN}from"fs/promises";import bN from"path";async function runDeletePageCommand(e){const t=await resolveCanvasDirPath(e.canvas_dir)??bN.resolve(e.canvas_dir);if(!await pathExists12(t))throw new Error(`Directory not found: ${t}`);const n=bN.join(t,"index.canvas.tsx");if(!await pathExists12(n))throw new Error(`Not a canvas folder: ${t} (missing index.canvas.tsx)`);const r=await listFilesRecursively(t);return await yN(t,{recursive:!0,force:!1}),{deleted:!0,deleted_files:r}}import vN from"path";async function runListPagesCommand(e){const t=vN.resolve(e.workspace_root);if(!await pathExists12(t))throw new Error(`Workspace root does not exist: ${t}`);const n=e.repo_names?.length?Array.from(new Set(e.repo_names.map(e=>e.trim()).filter(e=>e.length>0))).map(e=>({repoRoot:vN.join(t,e),repoName:e})):[{repoRoot:t,repoName:""}],r=[];for(const{repoRoot:e,repoName:t}of n){if(!await pathExists12(e))continue;const n=await listPageInfosInRepo({repoRoot:e,repoName:t});r.push(...n.map(e=>({file_path:e.filePath,canvas_dir:e.pageDir,repo_name:e.repoName,canvas_name:e.pageName,storyboard_names:e.storyboardNames})))}return r.sort((e,t)=>e.file_path.localeCompare(t.file_path)),{pages:r}}import wN from"path";async function runMigrateCanvasCommand(e){const t=wN.resolve(e.repo_root),n=wN.isAbsolute(e.canvas_file)?e.canvas_file:wN.join(t,e.canvas_file),r=await resolveCanvasFilePath(n);if(!r)throw new Error(`Not a canvas: ${e.canvas_file} (no index.canvas.tsx found there)`);const{migrated:s}=await ensureCanvasPageFileMigrated(r);return{canvas_file:r,migrated:s,already_latest:!s}}import _N from"path";async function runSetHomeCanvasCommand(e){const t=_N.resolve(e.repo_root),n=_N.isAbsolute(e.canvas_dir)?e.canvas_dir:_N.join(t,e.canvas_dir),r=await resolveCanvasFilePath(n);if(!r)throw new Error(`Not a canvas: ${e.canvas_dir} (no index.canvas.tsx found there)`);const s=await listPageInfosInRepo({repoRoot:t,repoName:""}),i=[];for(const e of s)!0===e.home&&e.filePath!==r&&await unmarkCanvasAsHome(e.filePath)&&i.push(e.filePath);const o=await markCanvasAsHome(r);return{canvas_dir:_N.dirname(r),canvas_file:r,repo_root:t,newly_marked:o,unmarked_previous:i}}import xN from"path";import{readFile as TN}from"fs/promises";import kN from"path";async function readDevServerStatus(e){const t=kN.join(e,".tempo","status.json");let n;try{n=await TN(t,"utf-8")}catch{return{dependenciesInstalled:!1,devserverUrl:null}}try{const e=JSON.parse(n);return{dependenciesInstalled:!0===e.dependenciesInstalled,devserverUrl:"string"==typeof e.devserverUrl?e.devserverUrl:null}}catch{return{dependenciesInstalled:!1,devserverUrl:null}}}var SN="Refer to get_guide({ topic: 'tempo-canvas-instructions' }) for details on setting up the canvas infrastructure.",EN='This project\'s apps[0].uiFramework is "vue": the set-up-vue-or-nuxt-canvas skill lists the Vue and Nuxt causes of this check by error message.';function typeErrorSummary(e){const t=e.canvas+e.app;return 0===t?[]:[`${t} type error${1===t?"":"s"} (${e.canvas} in canvas files); see type_errors. Type errors do not make the canvas invalid.`]}function formatIssueAsString(e){switch(e.kind){case"host_setup_issue":return e.message;case"server_component_import":return`${e.file} - server-only import '${e.specifier}' renders a React Server Component, which the canvas can't run. ${e.fix}`;case"canvas_format":case"syntax_error":case"missing_file":case"missing_export":case"missing_default_export":case"canvas_not_rendered":return`${e.file}:${e.line} - ${e.message}`;case"unresolved_import":return`${e.file}:${e.line} - Cannot resolve import '${e.specifier}'`;case"missing_package":return`Missing package: ${e.package_name}@${e.version} (required by ${e.required_by})`;case"local_module_import":return`${e.required_by} - ${e.message} ${e.fix}`;case"type_error":return`${e.file}:${e.line} - TS${e.code}: ${e.message}`}}async function runValidatePageCommand(e,t){const n=xN.resolve(e.repo_root),r=xN.resolve(n,e.canvas_file),s=await resolveCanvasFilePath(r)??r;let i;try{i=await resolveTempoConfig(n)}catch{const e={kind:"host_setup_issue",check:"config_invalid",file:xN.join(n,"tempo.config.json"),message:"tempo.config.json is missing or invalid.",fix:`Create or fix tempo.config.json in the project root. ${SN}`},t={status:"not_run",reason:"config_invalid"};return{valid:!1,issues:[e],errors:[formatIssueAsString(e)],warnings:[],type_errors:[],type_error_totals:{canvas:0,app:0},canvas_type_errors:0,checks:{host:{status:"failed"},canvas_format:t,imports:t,type_check:t}}}const o=await readDevServerStatus(i.tempoRoot),a=await validateHost({tempoRoot:i.tempoRoot,devserverUrl:o.devserverUrl}),c="vue"===i.apps[0]?.uiFramework,l=c?a.map(e=>({...e,fix:`${e.fix} ${EN}`})):a,d={tsconfigPath:i.tsconfigPath,tempoPackageDir:xN.dirname(i.packageJsonPath),reuseTypeCheckService:t?.reuseTypeCheckService,skipTypeCheck:"skip"===e.type_check,requestedCanvasOnly:"requested_canvas_only"===e.type_check},u=await validatePage(s,n,{...d,canvasesRoot:i.pagesDir}),p=await validateFlutterStoryboards({pageFile:s,projectRoot:n}),m=[...l,...p,...u.issues],f=p.length>0?{status:"failed"}:u.checks.canvas_format;return{valid:0===m.length,issues:m,errors:[...m.map(formatIssueAsString),...typeErrorSummary(u.type_error_totals)],warnings:u.warnings,type_errors:u.type_errors,type_error_totals:u.type_error_totals,canvas_type_errors:u.canvas_type_errors,checks:{...u.checks,canvas_format:f,host:l.length>0?{status:"failed"}:{status:"passed"}}}}import AN from"path";function toInitCommandResult(e){return{framework:e.framework,skipped:!1,types_file:e.typesFile,tsconfig_modified:e.tsconfigUpdated,warnings:e.warnings}}async function runInitCommand(e){const t=AN.resolve(e.repo_root),n=await initializePagesSupport({projectRoot:t,framework:e.framework});return toInitCommandResult(n)}async function runCanvasToolCommand(e,t){switch(e){case"create-canvas":return await runCreatePageCommand(t);case"compute-layout":return await runComputeLayoutCommand(t);case"list-canvases":return await runListPagesCommand(t);case"delete-canvas":return await runDeletePageCommand(t);case"set-home-canvas":return await runSetHomeCanvasCommand(t);case"migrate-canvas":return await runMigrateCanvasCommand(t);case"validate-canvas":return await runValidatePageCommand(t);default:throw new Error(`Unknown command: ${e}`)}}import{z as CN}from"zod";import{z as IN}from"zod";var PN=IN.enum(["vite","nextjs","nuxt","astro"]),DN=IN.object({tempoHost:IN.literal(!0),contractVersion:IN.number().int().min(1),sdkVersion:IN.string().min(1),pluginActive:IN.boolean(),framework:PN,capabilities:IN.object({astroComponents:IN.number().optional(),vueSourceAnnotation:IN.number().optional()}).optional()});function unverified(e){return{verified:!1,code:"app_instrumentation_unverified",message:e,fix:"Check that this is the app's dev-server URL and that /__tempo/identity is reachable through any auth or proxy. For Astro 7, install a tempo-sdk version exporting tempo-sdk/astro and add tempoAstro() to integrations in astro.config; require the astroComponents:1 capability. For a Vite prototype, install tempo-sdk in the app package and add tempoVitePlugin() to the app's own Vite config, preserving its other plugins. For a Nuxt app, keep `--extends` with the path to tempo/nuxt-app-layer relative to the app directory in apps[0].start (`./tempo/nuxt-app-layer` for an app at the project root, `../tempo/nuxt-app-layer` for `appDir: \"web\"`); that Tempo layer adds tempo-sdk/nuxt to the app's own `nuxt dev` without editing its nuxt.config. For Vue or Nuxt, the set-up-vue-or-nuxt-canvas skill has the exact config and checks. The tempo/ sidecar cannot instrument the app. Restart with stop_app_dev_server then start_app_dev_server({ require_instrumentation: true }); Tempo supplies TEMPO=true."}}function nuxtAppLayerMissing(e,t){return{verified:!1,code:"app_instrumentation_unverified",message:e,fix:`apps[0].start in tempo/tempo.config.json does not load Tempo's Nuxt app layer, which adds tempo-sdk/nuxt and the /__tempo/identity route to the app's own nuxt dev. Add \`--extends ${t.extendsPath}\` to the nuxt dev command in apps[0].start (Tempo's command for this app is \`${t.tempoStart}\`), then restart with stop_app_dev_server and start_app_dev_server({ require_instrumentation: true }).`}}var RN=5e3,NN=250;async function fetchIdentityPastWarmUp(e,t){const n=Date.now()+t;for(;;){const t=await fetch(e,{signal:AbortSignal.timeout(Math.max(1,n-Date.now())),cache:"no-store",redirect:"manual"}),r=503===t.status;if(!r||Date.now()+NN>=n)return t;await(t.body?.cancel()),await new Promise(e=>setTimeout(e,NN))}}async function verifyAppInstrumentation(e,t={}){if(!e.configured||!e.running||!e.url)return{verified:!1,code:"app_server_not_running",message:e.error??"The app must be running before its instrumentation can be verified.",fix:e.configured?"Resolve the app server's startup error, then call start_app_dev_server({ require_instrumentation: true }).":"Configure the app with set_app_dev_command, then call start_app_dev_server({ require_instrumentation: true })."};try{const n=new URL("/__tempo/identity",e.url),r=t.budgetMs??RN,s=await fetchIdentityPastWarmUp(n,r),i=t.nuxtAppLayer??null;if(!s.ok){if(await(s.body?.cancel()),503===s.status)return unverified(`Could not verify app instrumentation: ${n} still answered HTTP 503 (the server is starting) after ${r/1e3} seconds. Call start_app_dev_server({ require_instrumentation: true }) again once it has warmed up.`);const e=`Could not verify app instrumentation: ${n} returned HTTP ${s.status}.`;return i?nuxtAppLayerMissing(e,i):unverified(e)}if("1"!==s.headers.get("x-tempo-host-identity")){await(s.body?.cancel());const t=`The app at ${e.url} did not return the Tempo SDK identity header. Rendering successfully does not prove that its source is instrumented.`;return i?nuxtAppLayerMissing(t,i):unverified(t)}const o=DN.safeParse(await s.json());if(!o.success)return unverified("The app returned an invalid Tempo SDK identity. An active app plugin could not be verified.");if(!o.data.pluginActive)return{verified:!1,code:"app_instrumentation_inactive",message:"The app's Tempo SDK reports pluginActive: false.",fix:"Restart the app through Tempo with TEMPO=true reaching the framework process, including across container or remote launchers. Then call start_app_dev_server({ require_instrumentation: true }) again."};if("astro"===o.data.framework&&1!==o.data.capabilities?.astroComponents)return unverified("The app SDK does not support native Astro component previews; update tempo-sdk in the app package.");const a="vue"===t.uiFramework&&"vite"===o.data.framework;return a&&1!==o.data.capabilities?.vueSourceAnnotation?{verified:!1,code:"app_vue_annotation_missing",message:"The app's Tempo Vite plugin is active, but Tempo's Vue annotator is not: its .vue templates carry no source stamps, so Vue route storyboards have no .vue layers and canvas edits on them cannot write the files.",fix:'Add `import { tempoVuePlugin } from "tempo-sdk/vue";` and `...tempoVuePlugin()` to the plugins of the app\'s own vite.config, before vue() and before any other plugin that rewrites .vue source, keeping tempoVitePlugin(). A tempo-sdk in the app too old to report the annotator fails this check too: update it. Then restart with stop_app_dev_server and start_app_dev_server({ require_instrumentation: true }). The set-up-vue-or-nuxt-canvas skill has the full file.'}:{verified:!0,framework:o.data.framework,sdkVersion:o.data.sdkVersion}}catch(e){return unverified(e instanceof Error&&"TimeoutError"===e.name?`The app instrumentation check timed out after ${(t.budgetMs??RN)/1e3} seconds.`:`Could not verify app instrumentation: ${e instanceof Error?e.message:String(e)}`)}}import ON from"path";import FN from"path";import{readFileSync as LN}from"fs";var MN={duplicate_asset_declaration:"Keep one defineAsset beside the component. Existing canvas-owned declarations are also supported, but must not duplicate it.",component_declaration_outside_canvas:"Move the defineAsset reference declaration into the folder of the canvas that showcases this component (its index.canvas.tsx or a sibling file in the same folder).",redundant_canvas_declaration:"Remove the canvas-level defineAsset self-registration — the canvas's component declarations already link it; canvas self-registration is strictly for pages with truly no component to declare (foundations like color or icons).",missing_asset_declaration:"a design-system/library canvas must declare the top-level component(s) it showcases, or self-register with usageInstructions if it is a componentless foundations page"};function formatAssetDeclarationIssue(e){return`${e.file} - ${e.message}. Fix: ${e.fix}`}async function collectAssetDeclarationIssues(e){const t=FN.isAbsolute(e.canvasFile)?e.canvasFile:FN.join(e.workspaceRoot,e.canvasFile),n=/\.[cm]?[jt]sx?$/i.test(FN.basename(t)),r=normalizeWorkspaceRelativePath(e.workspaceRoot,n?FN.dirname(t):t),inCanvasFolder=e=>e===r||e.startsWith(`${r}/`),s=await loadWorkspaceAssetIndex({workspaceRoot:e.workspaceRoot,canvasesDir:e.canvasesDir}),i=new Set,readFile48=t=>{try{return LN(FN.join(e.workspaceRoot,t),"utf8")}catch{return null}},o=readFile48(`${r}/index.canvas.tsx`);if(o){const{program:e}=parseAssetProgram(`${r}/index.canvas.tsx`,o);if(e)for(const t of readAssetImports(e).referenceableImports.values()){const e=t.importSpecifier.startsWith(".")?resolveRelativeImport(r,t.importSpecifier):`pkg:${t.importSpecifier}`,n=resolveComponentIdentity({readFile:readFile48},e,t.importedName,`${r}/index.canvas.tsx`);if(n)for(const e of Object.values(s.assets))(e.componentFilePath??e.filePath)===n.filePath&&(e.componentName??e.name)===n.name&&i.add(e.key)}}const a=[];for(const[e,t]of Object.entries(s.fileErrors))for(const n of t){if("duplicate_asset_declaration"!==n.code&&"component_declaration_outside_canvas"!==n.code)continue;const t=inCanvasFolder(e)||"duplicate_asset_declaration"===n.code&&n.message.includes(`"${r}/`);t&&a.push({kind:"asset_declaration_error",code:n.code,file:e,message:n.message,fix:MN[n.code]})}for(const e of Object.values(s.assets))if("canvas"===e.kind&&inCanvasFolder(e.filePath))for(const t of e.warnings)"redundant_canvas_declaration"===t.code&&a.push({kind:"asset_declaration_error",code:"redundant_canvas_declaration",file:e.filePath,message:t.message,fix:MN.redundant_canvas_declaration});const c=normalizeWorkspaceRelativePath(e.workspaceRoot,FN.resolve(e.workspaceRoot,e.canvasesDir)),l=r===c||r.startsWith(`${c}/`),d=l?classifyCanvasZone(r.slice(c.length+1)):null;if(d&&isStrictZone(d)){const e=Object.values(s.assets).some(e=>inCanvasFolder(e.declaredIn??e.filePath)||i.has(e.key))||Object.entries(s.fileErrors).some(([e,t])=>inCanvasFolder(e)&&t.some(e=>"duplicate_asset_declaration"===e.code));if(!e){const e="design-system"===d.kind?"design-system zone":"library zone"+(d.libraryName?` ("${d.libraryName}")`:"");a.push({kind:"asset_declaration_error",code:"missing_asset_declaration",file:`${r}/index.canvas.tsx`,message:`canvas "${r}" is in the ${e} but contains no defineAsset declaration`,fix:MN.missing_asset_declaration})}}return a}async function runCanvasValidation(e,t){if(e={...e,repo_root:ON.resolve(e.repo_root),canvas_file:ON.resolve(e.repo_root,e.canvas_file)},"page-dependencies"===e.validation_kind){const n=await(t?.validatePageDependencies??((e,t)=>validatePage(e,t,{skipTypeCheck:!0})))(ON.resolve(e.canvas_file),ON.resolve(e.repo_root));return{valid:n.valid,issues:n.issues,errors:[],warnings:n.warnings,checks:n.checks}}const n=await(t?.runValidatePageCommand??runValidatePageCommand)(e);if(!1===e.assets_enabled)return{...n,checks:{...n.checks,assets:{status:"not_run"}}};const r=ON.resolve(e.workspace_root??e.repo_root),s=e.canvases_dir??ON.join(r,"tempo","designs"),i=await collectAssetDeclarationIssues({workspaceRoot:r,canvasesDir:s,canvasFile:e.canvas_file});return 0===i.length?{...n,checks:{...n.checks,assets:{status:"passed"}}}:{...n,checks:{...n.checks,assets:{status:"failed"}},valid:!1,issues:[...n.issues,...i],errors:[...n.errors,...i.map(formatAssetDeclarationIssue)]}}import{readFile as UN,realpath as jN}from"fs/promises";import BN from"path";var $N="data-tempo-projection-pending",WN="data-tempo-projection-unavailable",HN=3,qN="canvasProtocol",zN={canvasPath:"canvasPath",storyboardId:"storyboardId",width:"width",height:"height",idle:"tempoCaptureIdle"},GN={width:1600,height:1200},VN="data-tempo-storyboard-render-id",KN=`[${$N}]`,XN='[data-render-error="true"]',YN="data-render-error-message";function buildCanvasStoryboardRenderId(e,t){return`canvas:${encodeURIComponent(e.trim())}#storyboard:${encodeURIComponent(t.trim())}`}function buildStoryboardRenderSelector(e){return`[${VN}=${JSON.stringify(e)}]`}function buildCanvasHostUrl(e,t=!1){const n=new URL(e);return n.searchParams.set(qN,String(HN)),t&&n.searchParams.set("canvasRegistration","incremental"),n}function buildDirectRenderUrl(e,t){const n=void 0!==t.width,r=void 0!==t.height;if(n!==r)throw new Error("Direct render width and height must be provided together");const s=buildCanvasHostUrl(e);return s.searchParams.delete(zN.idle),s.searchParams.set(zN.canvasPath,t.canvasPath),s.searchParams.set(zN.storyboardId,t.storyboardId),n&&r?(s.searchParams.set(zN.width,String(t.width)),s.searchParams.set(zN.height,String(t.height))):(s.searchParams.delete(zN.width),s.searchParams.delete(zN.height)),s.toString()}function buildDirectRenderIdleUrl(e){const t=buildCanvasHostUrl(e);for(const e of Object.values(zN))t.searchParams.delete(e);return t.searchParams.set(zN.idle,"1"),t.toString()}import{createHash as JN}from"crypto";import{readFile as QN,realpath as ZN}from"fs/promises";import{readFileSync as eO,realpathSync as tO}from"fs";import{isAbsolute as nO,relative as rO,resolve as sO}from"path";async function readBrowserRuntimeScript(e=process.env.TEMPO_SDK_RUNTIME_PATH){if(!e||!nO(e))throw new Error("Tempo browser runtime is not provisioned. Set TEMPO_SDK_RUNTIME_PATH to the host's private runtime directory.");const t=JSON.parse(await QN(sO(e,"runtime.json"),"utf8")),n=t.browser;if(1!==t.tempoRuntimeContract||"string"!=typeof n?.file||"string"!=typeof n?.sha256)throw new Error("Incompatible Tempo browser runtime. Update the host application.");const r=await ZN(e),s=await ZN(sO(r,n.file)),i=rO(r,s);if(nO(i)||".."===i||i.startsWith("../")||i.startsWith("..\\"))throw new Error("Tempo browser runtime path escapes its directory.");const o=await QN(s,"utf8");if(JN("sha256").update(o).digest("hex")!==n.sha256)throw new Error("Tempo browser runtime artifact failed its integrity check.");return o}import{createHash as iO}from"crypto";var oO=C(ru(),1),aO=Date.UTC(2026,0,1,12,0,0);function buildFreezeInitScript(){return`(() => {\n const FROZEN_NOW = ${aO};\n const RealDate = Date;\n class FrozenDate extends RealDate {\n constructor(...args) {\n if (args.length === 0) {\n super(FROZEN_NOW);\n } else {\n super(...args);\n }\n }\n static now() {\n return FROZEN_NOW;\n }\n }\n FrozenDate.parse = RealDate.parse;\n FrozenDate.UTC = RealDate.UTC;\n Date = FrozenDate;\n globalThis.Date = FrozenDate;\n if (typeof performance !== "undefined") {\n const origin = performance.now();\n const realNow = performance.now.bind(performance);\n performance.now = () => realNow() - origin;\n }\n let seed;\n globalThis.__tempoResetCaptureDeterminism = () => {\n seed = 0x74656d70;\n };\n globalThis.__tempoResetCaptureDeterminism();\n Math.random = () => {\n seed |= 0;\n seed = (seed + 0x6d2b79f5) | 0;\n let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n})();`}var cO="\n@layer tempo-capture-motion {\n*, *::before, *::after {\n animation-duration: 0s !important;\n animation-delay: 0s !important;\n transition-duration: 0s !important;\n transition-delay: 0s !important;\n scroll-behavior: auto !important;\n caret-color: transparent !important;\n}\n}\n",lO=["target","fonts","suspense","content-quiet","paint"],dO=2e3,uO=300,pO=15e3,hO=50,mO="(function() {\n try {\n if (location.pathname.includes('/__tempo/astro/')) {\n var meta = document.querySelector('meta[name=\"tempo-astro-storyboard\"]');\n if (!meta) return false;\n var receipt = JSON.parse(meta.content);\n var address = location.pathname.split('/__tempo/astro/')[1].replace(/\\/$/, '').split('/');\n if (receipt.canvasPath !== decodeURIComponent(address[0]) || receipt.storyboardId !== decodeURIComponent(address[1])) return false;\n }\n if (document.querySelector('script[data-island-id]')) return false;\n return Array.from(document.querySelectorAll('astro-island[ssr]')).every(function(island) {\n var mode = island.getAttribute('client');\n if (mode === 'media') return !matchMedia(JSON.parse(island.getAttribute('opts') || '{}').value).matches;\n if (mode === 'visible') return !Array.from(island.children).some(function(child) {\n var r = child.getBoundingClientRect();\n return r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth && (r.width > 0 || r.height > 0);\n });\n return false;\n });\n } catch { return false; }\n})()";function buildSettleWaitScript(e){const t=Math.max(0,Math.round(e.quietMs??uO)),n=Math.max(1,Math.round(e.stepTimeoutMs??pO)),r=Math.max(1,Math.round(e.quietTimeoutMs??n)),s=Math.max(1,Math.round(e.pollMs??hO));return`\n (function() {\n var selector = ${JSON.stringify(e.selector)};\n var waitForMedia = ${!1!==e.waitForMedia};\n var pendingSelector = ${JSON.stringify(e.pendingSelector??null)};\n var quietMs = ${t};\n var stepTimeoutMs = ${n};\n var quietTimeoutMs = ${r};\n var quietBestEffort = ${!0===e.quietBestEffort?"true":"false"};\n var strictVideoFrames = ${!0===e.strictVideoFrames?"true":"false"};\n var pollMs = ${s};\n var runPaint = ${!1===e.paint?"false":"true"};\n var steps = {};\n // Cleared when the content-quiet step gives up under best effort.\n var quiet = true;\n // Monotonic and immune to the determinism kit's frozen Date.\n var now = typeof performance !== 'undefined' && performance && typeof performance.now === 'function'\n ? function() { return performance.now(); }\n : function() { return Date.now(); };\n\n function failure(step, message) {\n return { ok: false, step: step, message: message, steps: steps };\n }\n\n // Polls \`check\` until it answers true, or \`budgetMs\` elapses. The\n // first check runs synchronously so an already-settled step costs no\n // poll interval. A step run with \`giveUp\` resolves at its budget\n // instead of failing, recording that the content never held still.\n function until(step, check, budgetMs, giveUp) {\n var started = now();\n return new Promise(function(resolve, reject) {\n function tick() {\n var done;\n try {\n done = check();\n } catch (error) {\n steps[step] = Math.round(now() - started);\n reject(failure(step, String((error && error.message) || error)));\n return;\n }\n if (done) {\n steps[step] = Math.round(now() - started);\n resolve();\n return;\n }\n if (now() - started >= budgetMs) {\n steps[step] = Math.round(now() - started);\n if (step === 'content-quiet' && pendingStrictVideo !== null) {\n reject(failure(step, pendingStrictVideo + '; Timeout ' + budgetMs + 'ms exceeded'));\n return;\n }\n if (giveUp) {\n quiet = false;\n resolve();\n return;\n }\n reject(failure(step, 'Timeout ' + budgetMs + 'ms exceeded'));\n return;\n }\n setTimeout(tick, pollMs);\n }\n tick();\n });\n }\n\n var quietKey = null;\n var quietSince = 0;\n var pendingStrictVideo = null;\n // When a rendered video was first seen without a decoded frame, and how\n // long that may hold the quiet window before we give up on it.\n var videoWaitStartedAt = null;\n var videoWaitCapMs = ${dO};\n // Images that take part in the capture: laid out and not hidden. A\n // hidden responsive variant never starts native lazy loading and must\n // not hold the window; a rendered lazy image never starts either,\n // because a capture does not scroll, so it is asked for eagerly.\n function renderedMatches(target, tag) {\n var all = Array.prototype.slice.call(target.querySelectorAll(tag));\n var rendered = [];\n for (var i = 0; i < all.length; i++) {\n var el = all[i];\n if (el.getClientRects().length === 0) continue;\n var visibility = getComputedStyle(el).visibility;\n if (visibility === 'hidden' || visibility === 'collapse') continue;\n rendered.push(el);\n }\n return rendered;\n }\n function renderedImages(target) {\n return renderedMatches(target, 'img');\n }\n // The source each image was last asked to decode, and whether that\n // decode has settled. A new source asks again.\n var decodes = typeof WeakMap === 'function' ? new WeakMap() : null;\n function imageDecoded(img) {\n if (!decodes || typeof img.decode !== 'function') return true;\n var src = img.currentSrc || img.src;\n var entry = decodes.get(img);\n if (!entry || entry.src !== src) {\n entry = { src: src, done: false };\n decodes.set(img, entry);\n var settled = function() { entry.done = true; };\n img.decode().then(settled, settled);\n }\n return entry.done;\n }\n // Preserve the bounded readiness heuristic for live screenshots.\n // Strict baselines additionally prove decoding below: Chromium's\n // suspended metadata startup can report readyState 3/4 with no frame.\n function videoFrameReady(video) {\n if (video.error) return true;\n if (video.preload === 'none') return true;\n var networkState = video.networkState;\n if (networkState === 0 /* NETWORK_EMPTY */) return true;\n if (networkState === 3 /* NETWORK_NO_SOURCE */) return true;\n return video.readyState >= 2 /* HAVE_CURRENT_DATA */;\n }\n function videoSource(video) {\n var source = video.querySelector('source[src]');\n return video.currentSrc || video.src || (source && source.src) || '(no source)';\n }\n var posterDecodes = strictVideoFrames ? new WeakMap() : null;\n function videoPosterDecoded(video) {\n var src = video.poster;\n var crossOrigin = video.crossOrigin;\n var entry = posterDecodes.get(video);\n if (!entry || entry.src !== src || entry.crossOrigin !== crossOrigin) {\n var image = video.ownerDocument.createElement('img');\n entry = { src: src, crossOrigin: crossOrigin, image: image, done: false, error: null };\n posterDecodes.set(video, entry);\n // Match the poster request's CORS/credentials policy before it\n // starts. A no-CORS image could decode a blocked video poster.\n image.crossOrigin = crossOrigin;\n image.src = src;\n image.decode().then(\n function() { entry.done = true; },\n function(error) { entry.error = String((error && error.message) || error); }\n );\n }\n if (entry.error !== null) {\n throw new Error('Video poster could not decode: ' + src + ': ' + entry.error);\n }\n return entry.done;\n }\n var videoFrames = strictVideoFrames ? new Map() : null;\n function frameSource(video) {\n return JSON.stringify([video.currentSrc, video.src, video.crossOrigin,\n Array.prototype.map.call(video.querySelectorAll('source'), function(source) {\n return [source.src, source.type, source.media];\n })]);\n }\n function resetVideoFrame(entry) {\n entry.generation++;\n if (entry.callbackId !== null) {\n entry.video.cancelVideoFrameCallback(entry.callbackId);\n entry.callbackId = null;\n }\n entry.presented = false;\n quietKey = null;\n }\n function releaseVideoFrame(entry) {\n resetVideoFrame(entry);\n entry.video.removeEventListener('emptied', entry.reset);\n entry.video.removeEventListener('loadstart', entry.reset);\n entry.video.removeEventListener('seeking', entry.reset);\n videoFrames.delete(entry.video);\n }\n function releaseVideoFrames() {\n if (videoFrames) videoFrames.forEach(releaseVideoFrame);\n }\n function decodedVideoFrames(video) {\n if (typeof video.webkitDecodedFrameCount === 'number') {\n return video.webkitDecodedFrameCount;\n }\n if (typeof video.getVideoPlaybackQuality === 'function') {\n var quality = video.getVideoPlaybackQuality();\n return quality.totalVideoFrames - quality.droppedVideoFrames;\n }\n return 0;\n }\n function strictVideoFrameReady(video) {\n if (video.error) {\n throw new Error('Video frame failed for ' + videoSource(video) +\n ' (media error ' + video.error.code + '): ' + (video.error.message || 'media unavailable'));\n }\n var entry = videoFrames.get(video);\n var source = frameSource(video);\n if (entry && entry.source !== source) {\n releaseVideoFrame(entry);\n entry = null;\n }\n if (video.seeking) {\n if (entry) resetVideoFrame(entry);\n return false;\n }\n // Do not start media the author deliberately left unplayed. A\n // decoded poster is valid evidence only while it is the intended\n // still surface, never as a substitute for an autoplay/seek frame.\n if (video.preload === 'none' && video.paused && !video.autoplay &&\n video.currentTime === 0 && video.played.length === 0 && video.poster) {\n if (entry) releaseVideoFrame(entry);\n return videoPosterDecoded(video);\n }\n if (video.readyState < 2 /* HAVE_CURRENT_DATA */) {\n if (entry) resetVideoFrame(entry);\n return false;\n }\n if (entry && entry.presented) return true;\n // A paused video may decode its first frame without delivering a\n // pending presentation callback. The callback wakes suspended startup;\n // decoded-frame evidence independently satisfies readiness, including\n // when decoding races its registration. readyState and seeking still\n // gate both paths.\n if (decodedVideoFrames(video) > 0) {\n if (entry) releaseVideoFrame(entry);\n return true;\n }\n if (!entry) {\n entry = { video: video, source: source, callbackId: null,\n generation: 0, presented: false, reset: null };\n entry.reset = function() { resetVideoFrame(entry); };\n video.addEventListener('emptied', entry.reset);\n video.addEventListener('loadstart', entry.reset);\n video.addEventListener('seeking', entry.reset);\n videoFrames.set(video, entry);\n }\n if (entry.callbackId === null && typeof video.requestVideoFrameCallback === 'function') {\n var generation = entry.generation;\n // Chromium uses this request to resume suspended metadata startup,\n // even for media outside the viewport. It neither plays nor seeks.\n entry.callbackId = video.requestVideoFrameCallback(function() {\n if (entry.generation !== generation) return;\n entry.callbackId = null;\n entry.presented = !video.seeking && frameSource(video) === entry.source;\n });\n }\n return false;\n }\n function contentQuiet() {\n pendingStrictVideo = null;\n var target = document.querySelector(selector);\n if (!target) {\n releaseVideoFrames();\n return false;\n }\n var videos = waitForMedia ? renderedMatches(target, 'video') : [];\n if (strictVideoFrames) {\n videoFrames.forEach(function(entry) {\n if (videos.indexOf(entry.video) === -1) releaseVideoFrame(entry);\n });\n for (var v = 0; v < videos.length; v++) {\n if (!strictVideoFrameReady(videos[v]) && pendingStrictVideo === null) {\n pendingStrictVideo = 'Video frame not ready for ' + videoSource(videos[v]) +\n ' (readyState=' + videos[v].readyState + ', networkState=' + videos[v].networkState +\n ', seeking=' + videos[v].seeking + ', decodedFrames=' + decodedVideoFrames(videos[v]) +\n ', poster=' + (videos[v].poster || '(none)') + ')';\n }\n }\n if (pendingStrictVideo !== null) {\n quietKey = null;\n return false;\n }\n }\n var images = waitForMedia ? renderedImages(target) : [];\n for (var i = 0; i < images.length; i++) {\n if (images[i].loading === 'lazy') images[i].loading = 'eager';\n }\n for (var j = 0; j < images.length; j++) {\n if (!images[j].complete) {\n // Load/error handlers can replace content without moving its\n // geometry: start a fresh quiet window once they have run.\n quietKey = null;\n return false;\n }\n }\n // A loaded image can still paint as empty space until it decodes\n // (decoding="async" lets the browser paint first). Ask each source\n // to decode once; a failed decode counts as finished.\n var decoding = false;\n for (var d = 0; d < images.length; d++) {\n if (!imageDecoded(images[d])) decoding = true;\n }\n if (decoding) {\n quietKey = null;\n return false;\n }\n // Preserve the existing bounded wait for live screenshots. Strict\n // media readiness above cannot be bypassed by this cap.\n for (var w = 0; !strictVideoFrames && w < videos.length; w++) {\n if (!videoFrameReady(videos[w])) {\n if (videoWaitStartedAt === null) videoWaitStartedAt = now();\n if (now() - videoWaitStartedAt < videoWaitCapMs) {\n quietKey = null;\n return false;\n }\n break;\n }\n }\n var rect = target.getBoundingClientRect();\n var text = target.innerText || '';\n var key = [\n rect.x,\n rect.y,\n rect.width,\n rect.height,\n target.querySelectorAll('*').length,\n text.length,\n images.length\n ].join(',');\n var at = now();\n if (quietKey !== key) {\n quietKey = key;\n quietSince = at;\n return false;\n }\n return at - quietSince >= quietMs;\n }\n\n function paint() {\n if (!runPaint) return Promise.resolve();\n var started = now();\n return new Promise(function(resolve) {\n requestAnimationFrame(function() {\n requestAnimationFrame(function() {\n steps.paint = Math.round(now() - started);\n resolve();\n });\n });\n });\n }\n\n return until('target', function() {\n return document.querySelector(selector) !== null;\n }, stepTimeoutMs, false)\n .then(function() {\n return until('fonts', function() {\n var fonts = document.fonts;\n return !fonts || fonts.status === 'loaded';\n }, stepTimeoutMs, false);\n })\n .then(function() {\n return until('suspense', function() {\n if (!${mO}) return false;\n if (!pendingSelector) return true;\n var target = document.querySelector(selector);\n if (!target) return false;\n return !target.querySelector(pendingSelector);\n }, stepTimeoutMs, false);\n })\n .then(function() {\n return until('content-quiet', contentQuiet, quietTimeoutMs, quietBestEffort);\n })\n .then(paint)\n .then(\n function() {\n releaseVideoFrames();\n return { ok: true, steps: steps, quiet: quiet };\n },\n function(caught) {\n releaseVideoFrames();\n if (caught && caught.ok === false) return caught;\n return failure('paint', String((caught && caught.message) || caught));\n }\n );\n })()\n `}var fO="11",gO="system-1",yO=1;function buildEnvFingerprint(e){const t={os:e.os,browser:`chromium-${e.browserVersion}`,dpr:yO,fontsBundleVersion:gO,kitVersion:fO};return{fingerprint:[t.os,t.browser,`dpr${t.dpr}`,`fonts-${t.fontsBundleVersion}`,`kit-${t.kitVersion}`].join("/"),parts:t}}function isNavigationInterruptedError(e){return/Execution context was destroyed|most likely because of a navigation|Cannot find context with specified id|[Ff]rame was detached|Navigation interrupted|is interrupted by another navigation|Inspected target navigated or closed|Cannot find object with id|context was destroyed/.test(e)}var bO=["--force-color-profile=srgb",`--force-device-scale-factor=${yO}`,"--hide-scrollbars","--disable-lcd-text","--disable-partial-raster"];async function alignCaptureFonts(e){await e.send("Page.setFontFamilies",{fontFamilies:{standard:"Times New Roman",fixed:"darwin"===process.platform?"Menlo":"Courier New",serif:"Times New Roman",sansSerif:"Arial",cursive:"Script",fantasy:"Impact",math:"Latin Modern Math"}})}async function alignCaptureSubframeFonts(e){let t=!1;for(const n of e.frames()){if(n===e.mainFrame())continue;let r;try{r=await e.context().newCDPSession(n)}catch(e){if(e instanceof Error&&e.message.includes("does not have a separate CDP session"))continue;throw e}try{await alignCaptureFonts(r),t=!0}finally{await r.detach()}}return t}async function settlePage(e,t,n={}){const r=n.quietMs??300,s=n.timeoutMs??15e3,i=s*lO.length,o=Date.now()+i;let a=0;for(;;){let c;try{c=await e.evaluate(buildSettleWaitScript({selector:t,pendingSelector:KN,quietMs:r,strictVideoFrames:!0,stepTimeoutMs:Math.max(1,Math.min(s,o-Date.now()))}))}catch(e){const t=e instanceof Error?e.message:String(e);if(!isNavigationInterruptedError(t))throw e;if(a+=1,Date.now()>=o)throw new Error(`settle: Timeout ${i}ms exceeded; the document was replaced ${a} times while waiting`);continue}for(const e of lO){const t=c.steps[e];void 0!==t&&n.onStep?.(e,t)}if(!c.ok)throw new Error(`settle.${c.step}: ${c.message}`);return}}import{spawn as vO}from"child_process";import{createRequire as wO}from"module";import _O from"path";var xO=48e4;function isMissingBrowserError(e){const t=e instanceof Error?e.message:String(e);return t.includes("Executable doesn't exist")||/playwright install(?!-deps)/.test(t)}function autoInstallDisabled(){return"1"===process.env.TEMPO_MCP_NO_AUTO_INSTALL}async function installChromium(e,t=vO){const n=wO(import.meta.url),r=_O.join(_O.dirname(n.resolve("playwright/package.json")),"cli.js");await new Promise((n,s)=>{const i=t(process.execPath,[r,"install","chromium"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});let o="";const collect=e=>{o=(o+String(e)).slice(-2e3)};i.stdout?.on("data",collect),i.stderr?.on("data",collect);const a=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`Chromium download timed out after ${xO/6e4} minutes. Run \`npx playwright install chromium\` manually.`))},xO);i.on("error",e=>{clearTimeout(a),s(e)}),i.on("exit",t=>{clearTimeout(a),0===t?(e("Chromium installed."),n()):s(new Error(`playwright install chromium exited with ${t}: ${o.trim().slice(-500)}`))})})}var escapeHtml=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),TO="<style>html{width:100%;height:100%;}</style>";function serializeAttributes(e,t=!1){return Object.entries(e).filter(([e])=>t||"style"!==e).map(([e,t])=>` ${e}="${escapeHtml(t)}"`).join("")}function buildBodyStyle(e){const t=(e??"").split(";").map(e=>e.trim()).filter(e=>{const t=e.indexOf(":");if(t<=0)return!1;const n=e.slice(0,t).trim().toLowerCase();return"width"!==n&&"height"!==n});return t.push("width: 100%","height: 100%","margin: 0"),`${t.join("; ")};`}function buildStoryboardHtmlDocument(e,t){const n=t.title?`<title>${escapeHtml(t.title)}</title>`:"",r=/<base[\s>]/i.test(e.headHtml)?"":`<base href="${escapeHtml(t.baseUrl)}">`;return["<!DOCTYPE html>",`<html${serializeAttributes(e.htmlAttributes,t.preserveBody)}>`,"<head>",'<meta charset="utf-8">',n,r,t.preserveBody?"":TO,e.headHtml,"</head>",t.preserveBody?e.elementHtml:`<body${serializeAttributes(e.bodyAttributes)} style="${escapeHtml(buildBodyStyle(e.bodyAttributes.style))}">`,t.preserveBody?"":e.elementHtml,t.preserveBody?"":"</body>","</html>"].join("")}import{randomBytes as kO}from"crypto";import{readFile as SO,stat as EO}from"fs/promises";import AO from"path";import{createHash as CO}from"crypto";import{createRequire as IO}from"module";var PO=25165824,DO=67108864,RO=33554432,NO=IO(import.meta.url),OO,loadSharp=()=>OO??=NO("sharp");function createCaptureImageNormalizer(){const e=new Map;let t=0;return async n=>{if(255!==n[0]||216!==n[1]||255!==n[2])return n;if(n.length>PO)throw new Error("capture JPEG exceeds the 24 MiB input limit");const r=CO("sha256").update(n).digest("hex"),s=e.get(r);if(s)return e.delete(r),e.set(r,s),s;const i=loadSharp(),o=await i(n,{limitInputPixels:DO}).keepExif().png().toBuffer();if(e.has(r))return e.get(r);if(o.length<=RO){for(;t+o.length>RO;){const n=e.keys().next().value;t-=e.get(n).length,e.delete(n)}e.set(r,o),t+=o.length}return o}}async function installCaptureImages(e,t,n={}){const r=await e.context().newCDPSession(e),s=new Map,i=new Set,o=new Map;let a=!1;const handle=async e=>{const{requestId:n,networkId:i,request:c,responseStatusCode:l,responseHeaders:d=[]}=e,u={canceled:!1};i&&o.set(i,u);try{const e=d.find(e=>"content-type"===e.name.toLowerCase())?.value.split(";",1)[0].trim().toLowerCase(),s="image/jpeg"===e||"image/jpg"===e||"application/octet-stream"===e||!e;if(200!==l||!s)return void await r.send("Fetch.continueRequest",{requestId:n});const i=Number(d.find(e=>"content-length"===e.name.toLowerCase())?.value);if(i>PO)throw new Error("capture image exceeds the 24 MiB input limit");let o;const a=await Promise.race([r.send("Fetch.getResponseBody",{requestId:n}),new Promise((e,t)=>{o=setTimeout(()=>t(new Error("capture image download exceeded 30 seconds")),3e4)}),new Promise((e,t)=>{u.cancelBody=()=>t(new Error("capture image request was canceled")),u.canceled&&u.cancelBody()})]).finally(()=>{clearTimeout(o),u.cancelBody=void 0}),c=Buffer.from(a.body,a.base64Encoded?"base64":"utf8"),p=await t(c);if(p===c)return void await r.send("Fetch.continueRequest",{requestId:n});const m=new Set(["content-type","content-encoding","content-length","etag","content-md5","digest","content-digest","repr-digest"]),f=d.filter(e=>!m.has(e.name.toLowerCase()));f.push({name:"Content-Type",value:"image/png"}),await r.send("Fetch.fulfillRequest",{requestId:n,responseCode:l,responseHeaders:f,body:p.toString("base64")})}catch(e){a||u.canceled||s.set(c.url,String(e)),await r.send("Fetch.failRequest",{requestId:n,errorReason:"Failed"}).catch(()=>{})}finally{i&&o.get(i)===u&&o.delete(i)}};return r.on("Network.loadingFailed",e=>{if(!e.canceled)return;const t=o.get(e.requestId);t&&(t.canceled=!0,t.cancelBody?.())}),r.on("Fetch.requestPaused",e=>{const t=handle(e);i.add(t),t.finally(()=>i.delete(t)).catch(()=>{})}),await r.send("Network.enable"),n.requestLatencyMs&&await r.send("Network.emulateNetworkConditions",{offline:!1,latency:n.requestLatencyMs,downloadThroughput:-1,uploadThroughput:-1}),await r.send("Fetch.enable",{patterns:[{resourceType:"Image",requestStage:"Response"}]}),{assertHealthy(){if(s.size)throw new Error(`capture image normalization failed: ${[...s].map(([e,t])=>`${e}: ${t}`).join("; ")}`)},async forgetLoadedImages(){await r.send("Network.setCacheDisabled",{cacheDisabled:!0}),await r.send("Network.setCacheDisabled",{cacheDisabled:!1})},async dispose(){a=!0,await r.send("Fetch.disable").catch(()=>{}),await r.detach().catch(()=>{}),await Promise.allSettled([...i])}}}import FO from"path";import{realpath as LO,stat as MO}from"fs/promises";import UO from"oxc-parser/src-js/generated/visit/keys.js";var jO=UO,BO=jO.default??jO;import{parseSync as $O}from"oxc-parser";function sourceVersionHash(e){let t=5381,n=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)+t^s,n=s+(n<<6)+(n<<16)-n|0}return toHex8(t)+toHex8(n)}function toHex8(e){return(e>>>0).toString(16).padStart(8,"0")}var WO={Top:1,Function:2,Block:4,Catch:8,Class:16,For:32,Switch:64,Module:128,StrictMode:256,ClassStaticBlock:512,TsModuleBlock:1024,TsConditional:2048,Type:4096,Enum:8192};import{parseSync as HO}from"oxc-parser";var qO=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),zO="�",GO;!function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"}(GO||(GO={}));var VO={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"},KO;function isSurrogate(e){return e>=55296&&e<=57343}function isSurrogatePair(e){return e>=56320&&e<=57343}function getSurrogatePairCodePoint(e,t){return 1024*(e-55296)+9216+t}function isControlCodePoint(e){return 32!==e&&10!==e&&13!==e&&9!==e&&12!==e&&e>=1&&e<=31||e>=127&&e<=159}function isUndefinedCodePoint(e){return e>=64976&&e<=65007||qO.has(e)}!function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"}(KO||(KO={}));var XO=65536,YO=class{constructor(e){this.handler=e,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=XO,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+Number(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(e,t){const{line:n,col:r,offset:s}=this,i=r+t,o=s+t;return{code:e,startLine:n,endLine:n,startCol:i,endCol:i,startOffset:o,endOffset:o}}_err(e){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(e,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(e){if(this.pos!==this.html.length-1){const t=this.html.charCodeAt(this.pos+1);if(isSurrogatePair(t))return this.pos++,this._addGap(),getSurrogatePairCodePoint(e,t)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,GO.EOF;return this._err(KO.surrogateInInputStream),e}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(e,t){this.html.length>0?this.html+=e:this.html=e,this.endOfChunkHit=!1,this.lastChunkWritten=t}insertHtmlAtCurrentPos(e){this.html=this.html.substring(0,this.pos+1)+e+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(e,t){if(this.pos+e.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(t)return this.html.startsWith(e,this.pos);for(let t=0;t<e.length;t++){const n=32|this.html.charCodeAt(this.pos+t);if(n!==e.charCodeAt(t))return!1}return!0}peek(e){const t=this.pos+e;if(t>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,GO.EOF;const n=this.html.charCodeAt(t);return n===GO.CARRIAGE_RETURN?GO.LINE_FEED:n}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,GO.EOF;let e=this.html.charCodeAt(this.pos);if(e===GO.CARRIAGE_RETURN)return this.isEol=!0,this.skipNextNewLine=!0,GO.LINE_FEED;if(e===GO.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine))return this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance();this.skipNextNewLine=!1,isSurrogate(e)&&(e=this._processSurrogate(e));const t=null===this.handler.onParseError||e>31&&e<127||e===GO.LINE_FEED||e===GO.CARRIAGE_RETURN||e>159&&e<64976;return t||this._checkForProblematicCharacters(e),e}_checkForProblematicCharacters(e){isControlCodePoint(e)?this._err(KO.controlCharacterInInputStream):isUndefinedCodePoint(e)&&this._err(KO.noncharacterInInputStream)}retreat(e){for(this.pos-=e;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}},JO;function getTokenAttr(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}!function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"}(JO||(JO={}));var QO=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),ZO,eF=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),tF=null!==(ZO=String.fromCodePoint)&&void 0!==ZO?ZO:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e),t},nF;function replaceCodePoint(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=eF.get(e))&&void 0!==t?t:e}!function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"}(nF||(nF={}));var rF=32,sF,iF,oF;function isNumber(e){return e>=nF.ZERO&&e<=nF.NINE}function isHexadecimalCharacter(e){return e>=nF.UPPER_A&&e<=nF.UPPER_F||e>=nF.LOWER_A&&e<=nF.LOWER_F}function isAsciiAlphaNumeric(e){return e>=nF.UPPER_A&&e<=nF.UPPER_Z||e>=nF.LOWER_A&&e<=nF.LOWER_Z||isNumber(e)}function isEntityInAttributeInvalidEnd(e){return e===nF.EQUALS||isAsciiAlphaNumeric(e)}!function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"}(sF||(sF={})),function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"}(iF||(iF={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}(oF||(oF={}));var aF=class{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=iF.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=oF.Strict}startEntity(e){this.decodeMode=e,this.state=iF.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case iF.EntityStart:return e.charCodeAt(t)===nF.NUM?(this.state=iF.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=iF.NamedEntity,this.stateNamedEntity(e,t));case iF.NumericStart:return this.stateNumericStart(e,t);case iF.NumericDecimal:return this.stateNumericDecimal(e,t);case iF.NumericHex:return this.stateNumericHex(e,t);case iF.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(e.charCodeAt(t)|rF)===nF.LOWER_X?(this.state=iF.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=iF.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,r){if(t!==n){const s=n-t;this.result=this.result*Math.pow(r,s)+Number.parseInt(e.substr(t,s),r),this.consumed+=s}}stateNumericHex(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!isNumber(r)&&!isHexadecimalCharacter(r))return this.addToNumericResult(e,n,t,16),this.emitNumericEntity(r,3);t+=1}return this.addToNumericResult(e,n,t,16),-1}stateNumericDecimal(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!isNumber(r))return this.addToNumericResult(e,n,t,10),this.emitNumericEntity(r,2);t+=1}return this.addToNumericResult(e,n,t,10),-1}emitNumericEntity(e,t){var n;if(this.consumed<=t)return null===(n=this.errors)||void 0===n||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===nF.SEMI)this.consumed+=1;else if(this.decodeMode===oF.Strict)return 0;return this.emitCodePoint(replaceCodePoint(this.result),this.consumed),this.errors&&(e!==nF.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:n}=this;let r=n[this.treeIndex],s=(r&sF.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const i=e.charCodeAt(t);if(this.treeIndex=determineBranch(n,r,this.treeIndex+Math.max(1,s),i),this.treeIndex<0)return 0===this.result||this.decodeMode===oF.Attribute&&(0===s||isEntityInAttributeInvalidEnd(i))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],s=(r&sF.VALUE_LENGTH)>>14,0!==s){if(i===nF.SEMI)return this.emitNamedEntityData(this.treeIndex,s,this.consumed+this.excess);this.decodeMode!==oF.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,r=(n[t]&sF.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,r,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,n){const{decodeTree:r}=this;return this.emitCodePoint(1===t?r[e]&~sF.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n}end(){var e;switch(this.state){case iF.NamedEntity:return 0===this.result||this.decodeMode===oF.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case iF.NumericDecimal:return this.emitNumericEntity(0,2);case iF.NumericHex:return this.emitNumericEntity(0,3);case iF.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case iF.EntityStart:return 0}}},cF,lF,dF,uF,pF;function determineBranch(e,t,n,r){const s=(t&sF.BRANCH_LENGTH)>>7,i=t&sF.JUMP_TABLE;if(0===s)return 0!==i&&r===i?n:-1;if(i){const t=r-i;return t<0||t>=s?-1:e[n+t]-1}let o=n,a=o+s-1;for(;o<=a;){const t=o+a>>>1,n=e[t];if(n<r)o=t+1;else{if(!(n>r))return e[t+s];a=t-1}}return-1}!function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"}(cF||(cF={})),function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"}(lF||(lF={})),function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"}(dF||(dF={})),function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"}(uF||(uF={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"}(pF||(pF={}));var hF=new Map([[uF.A,pF.A],[uF.ADDRESS,pF.ADDRESS],[uF.ANNOTATION_XML,pF.ANNOTATION_XML],[uF.APPLET,pF.APPLET],[uF.AREA,pF.AREA],[uF.ARTICLE,pF.ARTICLE],[uF.ASIDE,pF.ASIDE],[uF.B,pF.B],[uF.BASE,pF.BASE],[uF.BASEFONT,pF.BASEFONT],[uF.BGSOUND,pF.BGSOUND],[uF.BIG,pF.BIG],[uF.BLOCKQUOTE,pF.BLOCKQUOTE],[uF.BODY,pF.BODY],[uF.BR,pF.BR],[uF.BUTTON,pF.BUTTON],[uF.CAPTION,pF.CAPTION],[uF.CENTER,pF.CENTER],[uF.CODE,pF.CODE],[uF.COL,pF.COL],[uF.COLGROUP,pF.COLGROUP],[uF.DD,pF.DD],[uF.DESC,pF.DESC],[uF.DETAILS,pF.DETAILS],[uF.DIALOG,pF.DIALOG],[uF.DIR,pF.DIR],[uF.DIV,pF.DIV],[uF.DL,pF.DL],[uF.DT,pF.DT],[uF.EM,pF.EM],[uF.EMBED,pF.EMBED],[uF.FIELDSET,pF.FIELDSET],[uF.FIGCAPTION,pF.FIGCAPTION],[uF.FIGURE,pF.FIGURE],[uF.FONT,pF.FONT],[uF.FOOTER,pF.FOOTER],[uF.FOREIGN_OBJECT,pF.FOREIGN_OBJECT],[uF.FORM,pF.FORM],[uF.FRAME,pF.FRAME],[uF.FRAMESET,pF.FRAMESET],[uF.H1,pF.H1],[uF.H2,pF.H2],[uF.H3,pF.H3],[uF.H4,pF.H4],[uF.H5,pF.H5],[uF.H6,pF.H6],[uF.HEAD,pF.HEAD],[uF.HEADER,pF.HEADER],[uF.HGROUP,pF.HGROUP],[uF.HR,pF.HR],[uF.HTML,pF.HTML],[uF.I,pF.I],[uF.IMG,pF.IMG],[uF.IMAGE,pF.IMAGE],[uF.INPUT,pF.INPUT],[uF.IFRAME,pF.IFRAME],[uF.KEYGEN,pF.KEYGEN],[uF.LABEL,pF.LABEL],[uF.LI,pF.LI],[uF.LINK,pF.LINK],[uF.LISTING,pF.LISTING],[uF.MAIN,pF.MAIN],[uF.MALIGNMARK,pF.MALIGNMARK],[uF.MARQUEE,pF.MARQUEE],[uF.MATH,pF.MATH],[uF.MENU,pF.MENU],[uF.META,pF.META],[uF.MGLYPH,pF.MGLYPH],[uF.MI,pF.MI],[uF.MO,pF.MO],[uF.MN,pF.MN],[uF.MS,pF.MS],[uF.MTEXT,pF.MTEXT],[uF.NAV,pF.NAV],[uF.NOBR,pF.NOBR],[uF.NOFRAMES,pF.NOFRAMES],[uF.NOEMBED,pF.NOEMBED],[uF.NOSCRIPT,pF.NOSCRIPT],[uF.OBJECT,pF.OBJECT],[uF.OL,pF.OL],[uF.OPTGROUP,pF.OPTGROUP],[uF.OPTION,pF.OPTION],[uF.P,pF.P],[uF.PARAM,pF.PARAM],[uF.PLAINTEXT,pF.PLAINTEXT],[uF.PRE,pF.PRE],[uF.RB,pF.RB],[uF.RP,pF.RP],[uF.RT,pF.RT],[uF.RTC,pF.RTC],[uF.RUBY,pF.RUBY],[uF.S,pF.S],[uF.SCRIPT,pF.SCRIPT],[uF.SEARCH,pF.SEARCH],[uF.SECTION,pF.SECTION],[uF.SELECT,pF.SELECT],[uF.SOURCE,pF.SOURCE],[uF.SMALL,pF.SMALL],[uF.SPAN,pF.SPAN],[uF.STRIKE,pF.STRIKE],[uF.STRONG,pF.STRONG],[uF.STYLE,pF.STYLE],[uF.SUB,pF.SUB],[uF.SUMMARY,pF.SUMMARY],[uF.SUP,pF.SUP],[uF.TABLE,pF.TABLE],[uF.TBODY,pF.TBODY],[uF.TEMPLATE,pF.TEMPLATE],[uF.TEXTAREA,pF.TEXTAREA],[uF.TFOOT,pF.TFOOT],[uF.TD,pF.TD],[uF.TH,pF.TH],[uF.THEAD,pF.THEAD],[uF.TITLE,pF.TITLE],[uF.TR,pF.TR],[uF.TRACK,pF.TRACK],[uF.TT,pF.TT],[uF.U,pF.U],[uF.UL,pF.UL],[uF.SVG,pF.SVG],[uF.VAR,pF.VAR],[uF.WBR,pF.WBR],[uF.XMP,pF.XMP]]);function getTagID(e){var t;return null!==(t=hF.get(e))&&void 0!==t?t:pF.UNKNOWN}var mF=pF,fF={[cF.HTML]:new Set([mF.ADDRESS,mF.APPLET,mF.AREA,mF.ARTICLE,mF.ASIDE,mF.BASE,mF.BASEFONT,mF.BGSOUND,mF.BLOCKQUOTE,mF.BODY,mF.BR,mF.BUTTON,mF.CAPTION,mF.CENTER,mF.COL,mF.COLGROUP,mF.DD,mF.DETAILS,mF.DIR,mF.DIV,mF.DL,mF.DT,mF.EMBED,mF.FIELDSET,mF.FIGCAPTION,mF.FIGURE,mF.FOOTER,mF.FORM,mF.FRAME,mF.FRAMESET,mF.H1,mF.H2,mF.H3,mF.H4,mF.H5,mF.H6,mF.HEAD,mF.HEADER,mF.HGROUP,mF.HR,mF.HTML,mF.IFRAME,mF.IMG,mF.INPUT,mF.LI,mF.LINK,mF.LISTING,mF.MAIN,mF.MARQUEE,mF.MENU,mF.META,mF.NAV,mF.NOEMBED,mF.NOFRAMES,mF.NOSCRIPT,mF.OBJECT,mF.OL,mF.P,mF.PARAM,mF.PLAINTEXT,mF.PRE,mF.SCRIPT,mF.SECTION,mF.SELECT,mF.SOURCE,mF.STYLE,mF.SUMMARY,mF.TABLE,mF.TBODY,mF.TD,mF.TEMPLATE,mF.TEXTAREA,mF.TFOOT,mF.TH,mF.THEAD,mF.TITLE,mF.TR,mF.TRACK,mF.UL,mF.WBR,mF.XMP]),[cF.MATHML]:new Set([mF.MI,mF.MO,mF.MN,mF.MS,mF.MTEXT,mF.ANNOTATION_XML]),[cF.SVG]:new Set([mF.TITLE,mF.FOREIGN_OBJECT,mF.DESC]),[cF.XLINK]:new Set,[cF.XML]:new Set,[cF.XMLNS]:new Set},gF=new Set([mF.H1,mF.H2,mF.H3,mF.H4,mF.H5,mF.H6]),yF=new Set([uF.STYLE,uF.SCRIPT,uF.XMP,uF.IFRAME,uF.NOEMBED,uF.NOFRAMES,uF.PLAINTEXT]),bF;!function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"}(bF||(bF={}));var vF={DATA:bF.DATA,RCDATA:bF.RCDATA,RAWTEXT:bF.RAWTEXT,SCRIPT_DATA:bF.SCRIPT_DATA,PLAINTEXT:bF.PLAINTEXT,CDATA_SECTION:bF.CDATA_SECTION};function isAsciiDigit(e){return e>=GO.DIGIT_0&&e<=GO.DIGIT_9}function isAsciiUpper(e){return e>=GO.LATIN_CAPITAL_A&&e<=GO.LATIN_CAPITAL_Z}function isAsciiLower(e){return e>=GO.LATIN_SMALL_A&&e<=GO.LATIN_SMALL_Z}function isAsciiLetter(e){return isAsciiLower(e)||isAsciiUpper(e)}function isAsciiAlphaNumeric2(e){return isAsciiLetter(e)||isAsciiDigit(e)}function toAsciiLower(e){return e+32}function isWhitespace(e){return e===GO.SPACE||e===GO.LINE_FEED||e===GO.TABULATION||e===GO.FORM_FEED}function isScriptDataDoubleEscapeSequenceEnd(e){return isWhitespace(e)||e===GO.SOLIDUS||e===GO.GREATER_THAN_SIGN}function getErrorForNumericCharacterReference(e){return e===GO.NULL?KO.nullCharacterReference:e>1114111?KO.characterReferenceOutsideUnicodeRange:isSurrogate(e)?KO.surrogateCharacterReference:isUndefinedCodePoint(e)?KO.noncharacterCharacterReference:isControlCodePoint(e)||e===GO.CARRIAGE_RETURN?KO.controlCharacterReference:null}var wF=class{constructor(e,t){this.options=e,this.handler=t,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=bF.DATA,this.returnState=bF.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new YO(t),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new aF(QO,(e,t)=>{this.preprocessor.pos=this.entityStartPos+t-1,this._flushCodePointConsumedAsCharacterReference(e)},t.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(KO.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:e=>{this._err(KO.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+e)},validateNumericCharacterReference:e=>{const t=getErrorForNumericCharacterReference(e);t&&this._err(t,1)}}:void 0)}_err(e,t=0){var n,r;null===(r=(n=this.handler).onParseError)||void 0===r||r.call(n,this.preprocessor.getError(e,t))}getCurrentLocation(e){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-e,startOffset:this.preprocessor.offset-e,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const e=this._consume();this._ensureHibernation()||this._callState(e)}this.inLoop=!1}}pause(){this.paused=!0}resume(e){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,this.inLoop||(this._runParsingLoop(),this.paused||null==e||e())}write(e,t,n){this.active=!0,this.preprocessor.write(e,t),this._runParsingLoop(),this.paused||null==n||n()}insertHtmlAtCurrentPos(e){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(e),this._runParsingLoop()}_ensureHibernation(){return!!this.preprocessor.endOfChunkHit&&(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0)}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(e){this.consumedAfterSnapshot+=e;for(let t=0;t<e;t++)this.preprocessor.advance()}_consumeSequenceIfMatch(e,t){return!!this.preprocessor.startsWith(e,t)&&(this._advanceBy(e.length-1),!0)}_createStartTagToken(){this.currentToken={type:JO.START_TAG,tagName:"",tagID:pF.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:JO.END_TAG,tagName:"",tagID:pF.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(e){this.currentToken={type:JO.COMMENT,data:"",location:this.getCurrentLocation(e)}}_createDoctypeToken(e){this.currentToken={type:JO.DOCTYPE,name:e,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(e,t){this.currentCharacterToken={type:e,chars:t,location:this.currentLocation}}_createAttr(e){this.currentAttr={name:e,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var e,t;const n=this.currentToken;if(null===getTokenAttr(n,this.currentAttr.name)){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){const r=null!==(e=(t=n.location).attrs)&&void 0!==e?e:t.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(KO.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(e){this._emitCurrentCharacterToken(e.location),this.currentToken=null,e.location&&(e.location.endLine=this.preprocessor.line,e.location.endCol=this.preprocessor.col+1,e.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const e=this.currentToken;this.prepareToken(e),e.tagID=getTagID(e.tagName),e.type===JO.START_TAG?(this.lastStartTagName=e.tagName,this.handler.onStartTag(e)):(e.attrs.length>0&&this._err(KO.endTagWithAttributes),e.selfClosing&&this._err(KO.endTagWithTrailingSolidus),this.handler.onEndTag(e)),this.preprocessor.dropParsedChunk()}emitCurrentComment(e){this.prepareToken(e),this.handler.onComment(e),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(e){this.prepareToken(e),this.handler.onDoctype(e),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(e){if(this.currentCharacterToken){switch(e&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=e.startLine,this.currentCharacterToken.location.endCol=e.startCol,this.currentCharacterToken.location.endOffset=e.startOffset),this.currentCharacterToken.type){case JO.CHARACTER:this.handler.onCharacter(this.currentCharacterToken);break;case JO.NULL_CHARACTER:this.handler.onNullCharacter(this.currentCharacterToken);break;case JO.WHITESPACE_CHARACTER:this.handler.onWhitespaceCharacter(this.currentCharacterToken)}this.currentCharacterToken=null}}_emitEOFToken(){const e=this.getCurrentLocation(0);e&&(e.endLine=e.startLine,e.endCol=e.startCol,e.endOffset=e.startOffset),this._emitCurrentCharacterToken(e),this.handler.onEof({type:JO.EOF,location:e}),this.active=!1}_appendCharToCurrentCharacterToken(e,t){if(this.currentCharacterToken){if(this.currentCharacterToken.type===e)return void(this.currentCharacterToken.chars+=t);this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk()}this._createCharacterToken(e,t)}_emitCodePoint(e){const t=isWhitespace(e)?JO.WHITESPACE_CHARACTER:e===GO.NULL?JO.NULL_CHARACTER:JO.CHARACTER;this._appendCharToCurrentCharacterToken(t,String.fromCodePoint(e))}_emitChars(e){this._appendCharToCurrentCharacterToken(JO.CHARACTER,e)}_startCharacterReference(){this.returnState=this.state,this.state=bF.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?oF.Attribute:oF.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===bF.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===bF.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===bF.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(e){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(e):this._emitCodePoint(e)}_callState(e){switch(this.state){case bF.DATA:this._stateData(e);break;case bF.RCDATA:this._stateRcdata(e);break;case bF.RAWTEXT:this._stateRawtext(e);break;case bF.SCRIPT_DATA:this._stateScriptData(e);break;case bF.PLAINTEXT:this._statePlaintext(e);break;case bF.TAG_OPEN:this._stateTagOpen(e);break;case bF.END_TAG_OPEN:this._stateEndTagOpen(e);break;case bF.TAG_NAME:this._stateTagName(e);break;case bF.RCDATA_LESS_THAN_SIGN:this._stateRcdataLessThanSign(e);break;case bF.RCDATA_END_TAG_OPEN:this._stateRcdataEndTagOpen(e);break;case bF.RCDATA_END_TAG_NAME:this._stateRcdataEndTagName(e);break;case bF.RAWTEXT_LESS_THAN_SIGN:this._stateRawtextLessThanSign(e);break;case bF.RAWTEXT_END_TAG_OPEN:this._stateRawtextEndTagOpen(e);break;case bF.RAWTEXT_END_TAG_NAME:this._stateRawtextEndTagName(e);break;case bF.SCRIPT_DATA_LESS_THAN_SIGN:this._stateScriptDataLessThanSign(e);break;case bF.SCRIPT_DATA_END_TAG_OPEN:this._stateScriptDataEndTagOpen(e);break;case bF.SCRIPT_DATA_END_TAG_NAME:this._stateScriptDataEndTagName(e);break;case bF.SCRIPT_DATA_ESCAPE_START:this._stateScriptDataEscapeStart(e);break;case bF.SCRIPT_DATA_ESCAPE_START_DASH:this._stateScriptDataEscapeStartDash(e);break;case bF.SCRIPT_DATA_ESCAPED:this._stateScriptDataEscaped(e);break;case bF.SCRIPT_DATA_ESCAPED_DASH:this._stateScriptDataEscapedDash(e);break;case bF.SCRIPT_DATA_ESCAPED_DASH_DASH:this._stateScriptDataEscapedDashDash(e);break;case bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataEscapedLessThanSign(e);break;case bF.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:this._stateScriptDataEscapedEndTagOpen(e);break;case bF.SCRIPT_DATA_ESCAPED_END_TAG_NAME:this._stateScriptDataEscapedEndTagName(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPE_START:this._stateScriptDataDoubleEscapeStart(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED:this._stateScriptDataDoubleEscaped(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:this._stateScriptDataDoubleEscapedDash(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:this._stateScriptDataDoubleEscapedDashDash(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataDoubleEscapedLessThanSign(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPE_END:this._stateScriptDataDoubleEscapeEnd(e);break;case bF.BEFORE_ATTRIBUTE_NAME:this._stateBeforeAttributeName(e);break;case bF.ATTRIBUTE_NAME:this._stateAttributeName(e);break;case bF.AFTER_ATTRIBUTE_NAME:this._stateAfterAttributeName(e);break;case bF.BEFORE_ATTRIBUTE_VALUE:this._stateBeforeAttributeValue(e);break;case bF.ATTRIBUTE_VALUE_DOUBLE_QUOTED:this._stateAttributeValueDoubleQuoted(e);break;case bF.ATTRIBUTE_VALUE_SINGLE_QUOTED:this._stateAttributeValueSingleQuoted(e);break;case bF.ATTRIBUTE_VALUE_UNQUOTED:this._stateAttributeValueUnquoted(e);break;case bF.AFTER_ATTRIBUTE_VALUE_QUOTED:this._stateAfterAttributeValueQuoted(e);break;case bF.SELF_CLOSING_START_TAG:this._stateSelfClosingStartTag(e);break;case bF.BOGUS_COMMENT:this._stateBogusComment(e);break;case bF.MARKUP_DECLARATION_OPEN:this._stateMarkupDeclarationOpen(e);break;case bF.COMMENT_START:this._stateCommentStart(e);break;case bF.COMMENT_START_DASH:this._stateCommentStartDash(e);break;case bF.COMMENT:this._stateComment(e);break;case bF.COMMENT_LESS_THAN_SIGN:this._stateCommentLessThanSign(e);break;case bF.COMMENT_LESS_THAN_SIGN_BANG:this._stateCommentLessThanSignBang(e);break;case bF.COMMENT_LESS_THAN_SIGN_BANG_DASH:this._stateCommentLessThanSignBangDash(e);break;case bF.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:this._stateCommentLessThanSignBangDashDash(e);break;case bF.COMMENT_END_DASH:this._stateCommentEndDash(e);break;case bF.COMMENT_END:this._stateCommentEnd(e);break;case bF.COMMENT_END_BANG:this._stateCommentEndBang(e);break;case bF.DOCTYPE:this._stateDoctype(e);break;case bF.BEFORE_DOCTYPE_NAME:this._stateBeforeDoctypeName(e);break;case bF.DOCTYPE_NAME:this._stateDoctypeName(e);break;case bF.AFTER_DOCTYPE_NAME:this._stateAfterDoctypeName(e);break;case bF.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._stateAfterDoctypePublicKeyword(e);break;case bF.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:this._stateBeforeDoctypePublicIdentifier(e);break;case bF.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypePublicIdentifierDoubleQuoted(e);break;case bF.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypePublicIdentifierSingleQuoted(e);break;case bF.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:this._stateAfterDoctypePublicIdentifier(e);break;case bF.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:this._stateBetweenDoctypePublicAndSystemIdentifiers(e);break;case bF.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._stateAfterDoctypeSystemKeyword(e);break;case bF.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:this._stateBeforeDoctypeSystemIdentifier(e);break;case bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypeSystemIdentifierDoubleQuoted(e);break;case bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypeSystemIdentifierSingleQuoted(e);break;case bF.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:this._stateAfterDoctypeSystemIdentifier(e);break;case bF.BOGUS_DOCTYPE:this._stateBogusDoctype(e);break;case bF.CDATA_SECTION:this._stateCdataSection(e);break;case bF.CDATA_SECTION_BRACKET:this._stateCdataSectionBracket(e);break;case bF.CDATA_SECTION_END:this._stateCdataSectionEnd(e);break;case bF.CHARACTER_REFERENCE:this._stateCharacterReference();break;case bF.AMBIGUOUS_AMPERSAND:this._stateAmbiguousAmpersand(e);break;default:throw new Error("Unknown state")}}_stateData(e){switch(e){case GO.LESS_THAN_SIGN:this.state=bF.TAG_OPEN;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitCodePoint(e);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRcdata(e){switch(e){case GO.AMPERSAND:this._startCharacterReference();break;case GO.LESS_THAN_SIGN:this.state=bF.RCDATA_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRawtext(e){switch(e){case GO.LESS_THAN_SIGN:this.state=bF.RAWTEXT_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptData(e){switch(e){case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_statePlaintext(e){switch(e){case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateTagOpen(e){if(isAsciiLetter(e))this._createStartTagToken(),this.state=bF.TAG_NAME,this._stateTagName(e);else switch(e){case GO.EXCLAMATION_MARK:this.state=bF.MARKUP_DECLARATION_OPEN;break;case GO.SOLIDUS:this.state=bF.END_TAG_OPEN;break;case GO.QUESTION_MARK:this._err(KO.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=bF.BOGUS_COMMENT,this._stateBogusComment(e);break;case GO.EOF:this._err(KO.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break;default:this._err(KO.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=bF.DATA,this._stateData(e)}}_stateEndTagOpen(e){if(isAsciiLetter(e))this._createEndTagToken(),this.state=bF.TAG_NAME,this._stateTagName(e);else switch(e){case GO.GREATER_THAN_SIGN:this._err(KO.missingEndTagName),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break;default:this._err(KO.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=bF.BOGUS_COMMENT,this._stateBogusComment(e)}}_stateTagName(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_ATTRIBUTE_NAME;break;case GO.SOLIDUS:this.state=bF.SELF_CLOSING_START_TAG;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.tagName+=zO;break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:t.tagName+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateRcdataLessThanSign(e){e===GO.SOLIDUS?this.state=bF.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=bF.RCDATA,this._stateRcdata(e))}_stateRcdataEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(e)):(this._emitChars("</"),this.state=bF.RCDATA,this._stateRcdata(e))}handleSpecialEndTag(e){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const t=this.currentToken;t.tagName=this.lastStartTagName;const n=this.preprocessor.peek(this.lastStartTagName.length);switch(n){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=bF.BEFORE_ATTRIBUTE_NAME,!1;case GO.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=bF.SELF_CLOSING_START_TAG,!1;case GO.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=bF.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.RCDATA,this._stateRcdata(e))}_stateRawtextLessThanSign(e){e===GO.SOLIDUS?this.state=bF.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=bF.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(e)):(this._emitChars("</"),this.state=bF.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.RAWTEXT,this._stateRawtext(e))}_stateScriptDataLessThanSign(e){switch(e){case GO.SOLIDUS:this.state=bF.SCRIPT_DATA_END_TAG_OPEN;break;case GO.EXCLAMATION_MARK:this.state=bF.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break;default:this._emitChars("<"),this.state=bF.SCRIPT_DATA,this._stateScriptData(e)}}_stateScriptDataEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(e)):(this._emitChars("</"),this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStart(e){e===GO.HYPHEN_MINUS?(this.state=bF.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStartDash(e){e===GO.HYPHEN_MINUS?(this.state=bF.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscaped(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataEscapedDash(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedDashDash(e){switch(e){case GO.HYPHEN_MINUS:this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case GO.GREATER_THAN_SIGN:this.state=bF.SCRIPT_DATA,this._emitChars(">");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedLessThanSign(e){e===GO.SOLIDUS?this.state=bF.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:isAsciiLetter(e)?(this._emitChars("<"),this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(e)):(this._emitChars("<"),this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(e)):(this._emitChars("</"),this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscapeStart(e){if(this.preprocessor.startsWith(VO.SCRIPT,!1)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(VO.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<VO.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscaped(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDash(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDashDash(e){switch(e){case GO.HYPHEN_MINUS:this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case GO.GREATER_THAN_SIGN:this.state=bF.SCRIPT_DATA,this._emitChars(">");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedLessThanSign(e){e===GO.SOLIDUS?(this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateScriptDataDoubleEscapeEnd(e){if(this.preprocessor.startsWith(VO.SCRIPT,!1)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(VO.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<VO.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=bF.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateBeforeAttributeName(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.SOLIDUS:case GO.GREATER_THAN_SIGN:case GO.EOF:this.state=bF.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case GO.EQUALS_SIGN:this._err(KO.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=bF.ATTRIBUTE_NAME;break;default:this._createAttr(""),this.state=bF.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateAttributeName(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:case GO.SOLIDUS:case GO.GREATER_THAN_SIGN:case GO.EOF:this._leaveAttrName(),this.state=bF.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case GO.EQUALS_SIGN:this._leaveAttrName(),this.state=bF.BEFORE_ATTRIBUTE_VALUE;break;case GO.QUOTATION_MARK:case GO.APOSTROPHE:case GO.LESS_THAN_SIGN:this._err(KO.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(e);break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.name+=zO;break;default:this.currentAttr.name+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateAfterAttributeName(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.SOLIDUS:this.state=bF.SELF_CLOSING_START_TAG;break;case GO.EQUALS_SIGN:this.state=bF.BEFORE_ATTRIBUTE_VALUE;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this._createAttr(""),this.state=bF.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateBeforeAttributeValue(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.QUOTATION_MARK:this.state=bF.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this.state=bF.ATTRIBUTE_VALUE_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingAttributeValue),this.state=bF.DATA,this.emitCurrentTagToken();break;default:this.state=bF.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(e)}}_stateAttributeValueDoubleQuoted(e){switch(e){case GO.QUOTATION_MARK:this.state=bF.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.value+=zO;break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueSingleQuoted(e){switch(e){case GO.APOSTROPHE:this.state=bF.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.value+=zO;break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueUnquoted(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this._leaveAttrValue(),this.state=bF.BEFORE_ATTRIBUTE_NAME;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.value+=zO;break;case GO.QUOTATION_MARK:case GO.APOSTROPHE:case GO.LESS_THAN_SIGN:case GO.EQUALS_SIGN:case GO.GRAVE_ACCENT:this._err(KO.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(e);break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAfterAttributeValueQuoted(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this._leaveAttrValue(),this.state=bF.BEFORE_ATTRIBUTE_NAME;break;case GO.SOLIDUS:this._leaveAttrValue(),this.state=bF.SELF_CLOSING_START_TAG;break;case GO.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this._err(KO.missingWhitespaceBetweenAttributes),this.state=bF.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateSelfClosingStartTag(e){switch(e){case GO.GREATER_THAN_SIGN:{const e=this.currentToken;e.selfClosing=!0,this.state=bF.DATA,this.emitCurrentTagToken();break}case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this._err(KO.unexpectedSolidusInTag),this.state=bF.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateBogusComment(e){const t=this.currentToken;switch(e){case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EOF:this.emitCurrentComment(t),this._emitEOFToken();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.data+=zO;break;default:t.data+=String.fromCodePoint(e)}}_stateMarkupDeclarationOpen(e){this._consumeSequenceIfMatch(VO.DASH_DASH,!0)?(this._createCommentToken(VO.DASH_DASH.length+1),this.state=bF.COMMENT_START):this._consumeSequenceIfMatch(VO.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(VO.DOCTYPE.length+1),this.state=bF.DOCTYPE):this._consumeSequenceIfMatch(VO.CDATA_START,!0)?this.inForeignNode?this.state=bF.CDATA_SECTION:(this._err(KO.cdataInHtmlContent),this._createCommentToken(VO.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=bF.BOGUS_COMMENT):this._ensureHibernation()||(this._err(KO.incorrectlyOpenedComment),this._createCommentToken(2),this.state=bF.BOGUS_COMMENT,this._stateBogusComment(e))}_stateCommentStart(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_START_DASH;break;case GO.GREATER_THAN_SIGN:{this._err(KO.abruptClosingOfEmptyComment),this.state=bF.DATA;const e=this.currentToken;this.emitCurrentComment(e);break}default:this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentStartDash(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_END;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptClosingOfEmptyComment),this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="-",this.state=bF.COMMENT,this._stateComment(e)}}_stateComment(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_END_DASH;break;case GO.LESS_THAN_SIGN:t.data+="<",this.state=bF.COMMENT_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.data+=zO;break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=String.fromCodePoint(e)}}_stateCommentLessThanSign(e){const t=this.currentToken;switch(e){case GO.EXCLAMATION_MARK:t.data+="!",this.state=bF.COMMENT_LESS_THAN_SIGN_BANG;break;case GO.LESS_THAN_SIGN:t.data+="<";break;default:this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentLessThanSignBang(e){e===GO.HYPHEN_MINUS?this.state=bF.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=bF.COMMENT,this._stateComment(e))}_stateCommentLessThanSignBangDash(e){e===GO.HYPHEN_MINUS?this.state=bF.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=bF.COMMENT_END_DASH,this._stateCommentEndDash(e))}_stateCommentLessThanSignBangDashDash(e){e!==GO.GREATER_THAN_SIGN&&e!==GO.EOF&&this._err(KO.nestedComment),this.state=bF.COMMENT_END,this._stateCommentEnd(e)}_stateCommentEndDash(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_END;break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="-",this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentEnd(e){const t=this.currentToken;switch(e){case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EXCLAMATION_MARK:this.state=bF.COMMENT_END_BANG;break;case GO.HYPHEN_MINUS:t.data+="-";break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="--",this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentEndBang(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:t.data+="--!",this.state=bF.COMMENT_END_DASH;break;case GO.GREATER_THAN_SIGN:this._err(KO.incorrectlyClosedComment),this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="--!",this.state=bF.COMMENT,this._stateComment(e)}}_stateDoctype(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_DOCTYPE_NAME;break;case GO.GREATER_THAN_SIGN:this.state=bF.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e);break;case GO.EOF:{this._err(KO.eofInDoctype),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._err(KO.missingWhitespaceBeforeDoctypeName),this.state=bF.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e)}}_stateBeforeDoctypeName(e){if(isAsciiUpper(e))this._createDoctypeToken(String.fromCharCode(toAsciiLower(e))),this.state=bF.DOCTYPE_NAME;else switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._createDoctypeToken(zO),this.state=bF.DOCTYPE_NAME;break;case GO.GREATER_THAN_SIGN:{this._err(KO.missingDoctypeName),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this.state=bF.DATA;break}case GO.EOF:{this._err(KO.eofInDoctype),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(e)),this.state=bF.DOCTYPE_NAME}}_stateDoctypeName(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.AFTER_DOCTYPE_NAME;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.name+=zO;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.name+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateAfterDoctypeName(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._consumeSequenceIfMatch(VO.PUBLIC,!1)?this.state=bF.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(VO.SYSTEM,!1)?this.state=bF.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(KO.invalidCharacterSequenceAfterDoctypeName),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e))}}_stateAfterDoctypePublicKeyword(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break;case GO.QUOTATION_MARK:this._err(KO.missingWhitespaceAfterDoctypePublicKeyword),t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this._err(KO.missingWhitespaceAfterDoctypePublicKeyword),t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypePublicIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.QUOTATION_MARK:t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypePublicIdentifierDoubleQuoted(e){const t=this.currentToken;switch(e){case GO.QUOTATION_MARK:this.state=bF.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.publicId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateDoctypePublicIdentifierSingleQuoted(e){const t=this.currentToken;switch(e){case GO.APOSTROPHE:this.state=bF.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.publicId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateAfterDoctypePublicIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.QUOTATION_MARK:this._err(KO.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this._err(KO.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBetweenDoctypePublicAndSystemIdentifiers(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.QUOTATION_MARK:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateAfterDoctypeSystemKeyword(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break;case GO.QUOTATION_MARK:this._err(KO.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this._err(KO.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypeSystemIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.QUOTATION_MARK:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypeSystemIdentifierDoubleQuoted(e){const t=this.currentToken;switch(e){case GO.QUOTATION_MARK:this.state=bF.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.systemId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateDoctypeSystemIdentifierSingleQuoted(e){const t=this.currentToken;switch(e){case GO.APOSTROPHE:this.state=bF.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.systemId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateAfterDoctypeSystemIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBogusDoctype(e){const t=this.currentToken;switch(e){case GO.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.NULL:this._err(KO.unexpectedNullCharacter);break;case GO.EOF:this.emitCurrentDoctype(t),this._emitEOFToken()}}_stateCdataSection(e){switch(e){case GO.RIGHT_SQUARE_BRACKET:this.state=bF.CDATA_SECTION_BRACKET;break;case GO.EOF:this._err(KO.eofInCdata),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateCdataSectionBracket(e){e===GO.RIGHT_SQUARE_BRACKET?this.state=bF.CDATA_SECTION_END:(this._emitChars("]"),this.state=bF.CDATA_SECTION,this._stateCdataSection(e))}_stateCdataSectionEnd(e){switch(e){case GO.GREATER_THAN_SIGN:this.state=bF.DATA;break;case GO.RIGHT_SQUARE_BRACKET:this._emitChars("]");break;default:this._emitChars("]]"),this.state=bF.CDATA_SECTION,this._stateCdataSection(e)}}_stateCharacterReference(){let e=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(e<0){if(!this.preprocessor.lastChunkWritten)return this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,void(this.preprocessor.endOfChunkHit=!0);e=this.entityDecoder.end()}0===e?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(GO.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&isAsciiAlphaNumeric2(this.preprocessor.peek(1))?bF.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(e){isAsciiAlphaNumeric2(e)?this._flushCodePointConsumedAsCharacterReference(e):(e===GO.SEMICOLON&&this._err(KO.unknownNamedCharacterReference),this.state=this.returnState,this._callState(e))}},_F=new Set([pF.DD,pF.DT,pF.LI,pF.OPTGROUP,pF.OPTION,pF.P,pF.RB,pF.RP,pF.RT,pF.RTC]),xF=new Set([..._F,pF.CAPTION,pF.COLGROUP,pF.TBODY,pF.TD,pF.TFOOT,pF.TH,pF.THEAD,pF.TR]),TF=new Set([pF.APPLET,pF.CAPTION,pF.HTML,pF.MARQUEE,pF.OBJECT,pF.TABLE,pF.TD,pF.TEMPLATE,pF.TH]),kF=new Set([...TF,pF.OL,pF.UL]),SF=new Set([...TF,pF.BUTTON]),EF=new Set([pF.ANNOTATION_XML,pF.MI,pF.MN,pF.MO,pF.MS,pF.MTEXT]),AF=new Set([pF.DESC,pF.FOREIGN_OBJECT,pF.TITLE]),CF=new Set([pF.TR,pF.TEMPLATE,pF.HTML]),IF=new Set([pF.TBODY,pF.TFOOT,pF.THEAD,pF.TEMPLATE,pF.HTML]),PF=new Set([pF.TABLE,pF.TEMPLATE,pF.HTML]),DF=new Set([pF.TD,pF.TH]),RF=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(e,t,n){this.treeAdapter=t,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=pF.UNKNOWN,this.current=e}_indexOf(e){return this.items.lastIndexOf(e,this.stackTop)}_isInTemplate(){return this.currentTagId===pF.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===cF.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(e,t){this.stackTop++,this.items[this.stackTop]=e,this.current=e,this.tagIDs[this.stackTop]=t,this.currentTagId=t,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(e,t,!0)}pop(){const e=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!0)}replace(e,t){const n=this._indexOf(e);this.items[n]=t,n===this.stackTop&&(this.current=t)}insertAfter(e,t,n){const r=this._indexOf(e)+1;this.items.splice(r,0,t),this.tagIDs.splice(r,0,n),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&void 0!==this.currentTagId&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop)}popUntilTagNamePopped(e){let t=this.stackTop+1;do{t=this.tagIDs.lastIndexOf(e,t-1)}while(t>0&&this.treeAdapter.getNamespaceURI(this.items[t])!==cF.HTML);this.shortenToLength(Math.max(t,0))}shortenToLength(e){for(;this.stackTop>=e;){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,this.stackTop<e)}}popUntilElementPopped(e){const t=this._indexOf(e);this.shortenToLength(Math.max(t,0))}popUntilPopped(e,t){const n=this._indexOfTagNames(e,t);this.shortenToLength(Math.max(n,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(gF,cF.HTML)}popUntilTableCellPopped(){this.popUntilPopped(DF,cF.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(e,t){for(let n=this.stackTop;n>=0;n--)if(e.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===t)return n;return-1}clearBackTo(e,t){const n=this._indexOfTagNames(e,t);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(PF,cF.HTML)}clearBackToTableBodyContext(){this.clearBackTo(IF,cF.HTML)}clearBackToTableRowContext(){this.clearBackTo(CF,cF.HTML)}remove(e){const t=this._indexOf(e);t>=0&&(t===this.stackTop?this.pop():(this.items.splice(t,1),this.tagIDs.splice(t,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===pF.BODY?this.items[1]:null}contains(e){return this._indexOf(e)>-1}getCommonAncestor(e){const t=this._indexOf(e)-1;return t>=0?this.items[t]:null}isRootHtmlElementCurrent(){return 0===this.stackTop&&this.tagIDs[0]===pF.HTML}hasInDynamicScope(e,t){for(let n=this.stackTop;n>=0;n--){const r=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case cF.HTML:if(r===e)return!0;if(t.has(r))return!1;break;case cF.SVG:if(AF.has(r))return!1;break;case cF.MATHML:if(EF.has(r))return!1}}return!0}hasInScope(e){return this.hasInDynamicScope(e,TF)}hasInListItemScope(e){return this.hasInDynamicScope(e,kF)}hasInButtonScope(e){return this.hasInDynamicScope(e,SF)}hasNumberedHeaderInScope(){for(let e=this.stackTop;e>=0;e--){const t=this.tagIDs[e];switch(this.treeAdapter.getNamespaceURI(this.items[e])){case cF.HTML:if(gF.has(t))return!0;if(TF.has(t))return!1;break;case cF.SVG:if(AF.has(t))return!1;break;case cF.MATHML:if(EF.has(t))return!1}}return!0}hasInTableScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===cF.HTML)switch(this.tagIDs[t]){case e:return!0;case pF.TABLE:case pF.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let e=this.stackTop;e>=0;e--)if(this.treeAdapter.getNamespaceURI(this.items[e])===cF.HTML)switch(this.tagIDs[e]){case pF.TBODY:case pF.THEAD:case pF.TFOOT:return!0;case pF.TABLE:case pF.HTML:return!1}return!0}hasInSelectScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===cF.HTML)switch(this.tagIDs[t]){case e:return!0;case pF.OPTION:case pF.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;void 0!==this.currentTagId&&_F.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;void 0!==this.currentTagId&&xF.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(e){for(;void 0!==this.currentTagId&&this.currentTagId!==e&&xF.has(this.currentTagId);)this.pop()}},NF=3,OF;!function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"}(OF||(OF={}));var FF={type:OF.Marker},LF=class{constructor(e){this.treeAdapter=e,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(e,t){const n=[],r=t.length,s=this.treeAdapter.getTagName(e),i=this.treeAdapter.getNamespaceURI(e);for(let e=0;e<this.entries.length;e++){const t=this.entries[e];if(t.type===OF.Marker)break;const{element:o}=t;if(this.treeAdapter.getTagName(o)===s&&this.treeAdapter.getNamespaceURI(o)===i){const t=this.treeAdapter.getAttrList(o);t.length===r&&n.push({idx:e,attrs:t})}}return n}_ensureNoahArkCondition(e){if(this.entries.length<NF)return;const t=this.treeAdapter.getAttrList(e),n=this._getNoahArkConditionCandidates(e,t);if(n.length<NF)return;const r=new Map(t.map(e=>[e.name,e.value]));let s=0;for(let e=0;e<n.length;e++){const t=n[e];t.attrs.every(e=>r.get(e.name)===e.value)&&(s+=1,s>=NF&&this.entries.splice(t.idx,1))}}insertMarker(){this.entries.unshift(FF)}pushElement(e,t){this._ensureNoahArkCondition(e),this.entries.unshift({type:OF.Element,element:e,token:t})}insertElementAfterBookmark(e,t){const n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:OF.Element,element:e,token:t})}removeEntry(e){const t=this.entries.indexOf(e);-1!==t&&this.entries.splice(t,1)}clearToLastMarker(){const e=this.entries.indexOf(FF);-1===e?this.entries.length=0:this.entries.splice(0,e+1)}getElementEntryInScopeWithTagName(e){const t=this.entries.find(t=>t.type===OF.Marker||this.treeAdapter.getTagName(t.element)===e);return t&&t.type===OF.Element?t:null}getElementEntry(e){return this.entries.find(t=>t.type===OF.Element&&t.element===e)}},MF={createDocument:()=>({nodeName:"#document",mode:dF.NO_QUIRKS,childNodes:[]}),createDocumentFragment:()=>({nodeName:"#document-fragment",childNodes:[]}),createElement:(e,t,n)=>({nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}),createCommentNode:e=>({nodeName:"#comment",data:e,parentNode:null}),createTextNode:e=>({nodeName:"#text",value:e,parentNode:null}),appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,n){const r=e.childNodes.indexOf(n);e.childNodes.splice(r,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent:e=>e.content,setDocumentType(e,t,n,r){const s=e.childNodes.find(e=>"#documentType"===e.nodeName);if(s)s.name=t,s.publicId=n,s.systemId=r;else{const s={nodeName:"#documentType",name:t,publicId:n,systemId:r,parentNode:null};MF.appendChild(e,s)}},setDocumentMode(e,t){e.mode=t},getDocumentMode:e=>e.mode,detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const n=e.childNodes[e.childNodes.length-1];if(MF.isTextNode(n))return void(n.value+=t)}MF.appendChild(e,MF.createTextNode(t))},insertTextBefore(e,t,n){const r=e.childNodes[e.childNodes.indexOf(n)-1];r&&MF.isTextNode(r)?r.value+=t:MF.insertBefore(e,MF.createTextNode(t),n)},adoptAttributes(e,t){const n=new Set(e.attrs.map(e=>e.name));for(let r=0;r<t.length;r++)n.has(t[r].name)||e.attrs.push(t[r])},getFirstChild:e=>e.childNodes[0],getChildNodes:e=>e.childNodes,getParentNode:e=>e.parentNode,getAttrList:e=>e.attrs,getTagName:e=>e.tagName,getNamespaceURI:e=>e.namespaceURI,getTextNodeContent:e=>e.value,getCommentNodeContent:e=>e.data,getDocumentTypeNodeName:e=>e.name,getDocumentTypeNodePublicId:e=>e.publicId,getDocumentTypeNodeSystemId:e=>e.systemId,isTextNode:e=>"#text"===e.nodeName,isCommentNode:e=>"#comment"===e.nodeName,isDocumentTypeNode:e=>"#documentType"===e.nodeName,isElementNode:e=>Object.prototype.hasOwnProperty.call(e,"tagName"),setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation:e=>e.sourceCodeLocation,updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},UF="html",jF="about:legacy-compat",BF="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",$F=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],WF=[...$F,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],HF=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),qF=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],zF=[...qF,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function hasPrefix(e,t){return t.some(t=>e.startsWith(t))}function isConforming(e){return e.name===UF&&null===e.publicId&&(null===e.systemId||e.systemId===jF)}function getDocumentMode(e){if(e.name!==UF)return dF.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===BF)return dF.QUIRKS;let{publicId:n}=e;if(null!==n){if(n=n.toLowerCase(),HF.has(n))return dF.QUIRKS;let e=null===t?WF:$F;if(hasPrefix(n,e))return dF.QUIRKS;if(e=null===t?qF:zF,hasPrefix(n,e))return dF.LIMITED_QUIRKS}return dF.NO_QUIRKS}var GF={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},VF="definitionurl",KF="definitionURL",XF=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),YF=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:cF.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:cF.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:cF.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:cF.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:cF.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:cF.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:cF.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:cF.XML}],["xml:space",{prefix:"xml",name:"space",namespace:cF.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:cF.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:cF.XMLNS}]]),JF=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),QF=new Set([pF.B,pF.BIG,pF.BLOCKQUOTE,pF.BODY,pF.BR,pF.CENTER,pF.CODE,pF.DD,pF.DIV,pF.DL,pF.DT,pF.EM,pF.EMBED,pF.H1,pF.H2,pF.H3,pF.H4,pF.H5,pF.H6,pF.HEAD,pF.HR,pF.I,pF.IMG,pF.LI,pF.LISTING,pF.MENU,pF.META,pF.NOBR,pF.OL,pF.P,pF.PRE,pF.RUBY,pF.S,pF.SMALL,pF.SPAN,pF.STRONG,pF.STRIKE,pF.SUB,pF.SUP,pF.TABLE,pF.TT,pF.U,pF.UL,pF.VAR]);function causesExit(e){const t=e.tagID,n=t===pF.FONT&&e.attrs.some(({name:e})=>e===lF.COLOR||e===lF.SIZE||e===lF.FACE);return n||QF.has(t)}function adjustTokenMathMLAttrs(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===VF){e.attrs[t].name=KF;break}}function adjustTokenSVGAttrs(e){for(let t=0;t<e.attrs.length;t++){const n=XF.get(e.attrs[t].name);null!=n&&(e.attrs[t].name=n)}}function adjustTokenXMLAttrs(e){for(let t=0;t<e.attrs.length;t++){const n=YF.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace)}}function adjustTokenSVGTagName(e){const t=JF.get(e.tagName);null!=t&&(e.tagName=t,e.tagID=getTagID(e.tagName))}function isMathMLTextIntegrationPoint(e,t){return t===cF.MATHML&&(e===pF.MI||e===pF.MO||e===pF.MN||e===pF.MS||e===pF.MTEXT)}function isHtmlIntegrationPoint(e,t,n){if(t===cF.MATHML&&e===pF.ANNOTATION_XML)for(let e=0;e<n.length;e++)if(n[e].name===lF.ENCODING){const t=n[e].value.toLowerCase();return t===GF.TEXT_HTML||t===GF.APPLICATION_XML}return t===cF.SVG&&(e===pF.FOREIGN_OBJECT||e===pF.DESC||e===pF.TITLE)}function isIntegrationPoint(e,t,n,r){return(!r||r===cF.HTML)&&isHtmlIntegrationPoint(e,t,n)||(!r||r===cF.MATHML)&&isMathMLTextIntegrationPoint(e,t)}var ZF="hidden",eL=8,tL=3,nL;!function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"}(nL||(nL={}));var rL={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},sL=new Set([pF.TABLE,pF.TBODY,pF.TFOOT,pF.THEAD,pF.TR]),iL={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:MF,onParseError:null},oL=class{constructor(e,t,n=null,r=null){this.fragmentContext=n,this.scriptHandler=r,this.currentToken=null,this.stopped=!1,this.insertionMode=nL.INITIAL,this.originalInsertionMode=nL.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...iL,...e},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=null!=t?t:this.treeAdapter.createDocument(),this.tokenizer=new wF(this.options,this),this.activeFormattingElements=new LF(this.treeAdapter),this.fragmentContextID=n?getTagID(this.treeAdapter.getTagName(n)):pF.UNKNOWN,this._setContextModes(null!=n?n:this.document,this.fragmentContextID),this.openElements=new RF(this.document,this.treeAdapter,this)}static parse(e,t){const n=new this(t);return n.tokenizer.write(e,!0),n.document}static getFragmentParser(e,t){const n={...iL,...t};null!=e||(e=n.treeAdapter.createElement(uF.TEMPLATE,cF.HTML,[]));const r=n.treeAdapter.createElement("documentmock",cF.HTML,[]),s=new this(n,r,e);return s.fragmentContextID===pF.TEMPLATE&&s.tmplInsertionModeStack.unshift(nL.IN_TEMPLATE),s._initTokenizerForFragmentParsing(),s._insertFakeRootElement(),s._resetInsertionMode(),s._findFormInFragmentContext(),s}getFragment(){const e=this.treeAdapter.getFirstChild(this.document),t=this.treeAdapter.createDocumentFragment();return this._adoptNodes(e,t),t}_err(e,t,n){var r;if(!this.onParseError)return;const s=null!==(r=e.location)&&void 0!==r?r:rL,i={code:t,startLine:s.startLine,startCol:s.startCol,startOffset:s.startOffset,endLine:n?s.startLine:s.endLine,endCol:n?s.startCol:s.endCol,endOffset:n?s.startOffset:s.endOffset};this.onParseError(i)}onItemPush(e,t,n){var r,s;null===(s=(r=this.treeAdapter).onItemPush)||void 0===s||s.call(r,e),n&&this.openElements.stackTop>0&&this._setContextModes(e,t)}onItemPop(e,t){var n,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(e,this.currentToken),null===(r=(n=this.treeAdapter).onItemPop)||void 0===r||r.call(n,e,this.openElements.current),t){let e,t;0===this.openElements.stackTop&&this.fragmentContext?(e=this.fragmentContext,t=this.fragmentContextID):({current:e,currentTagId:t}=this.openElements),this._setContextModes(e,t)}}_setContextModes(e,t){const n=e===this.document||e&&this.treeAdapter.getNamespaceURI(e)===cF.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&void 0!==e&&void 0!==t&&!this._isIntegrationPoint(t,e)}_switchToTextParsing(e,t){this._insertElement(e,cF.HTML),this.tokenizer.state=t,this.originalInsertionMode=this.insertionMode,this.insertionMode=nL.TEXT}switchToPlaintextParsing(){this.insertionMode=nL.TEXT,this.originalInsertionMode=nL.IN_BODY,this.tokenizer.state=vF.PLAINTEXT}_getAdjustedCurrentElement(){return 0===this.openElements.stackTop&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let e=this.fragmentContext;for(;e;){if(this.treeAdapter.getTagName(e)===uF.FORM){this.formElement=e;break}e=this.treeAdapter.getParentNode(e)}}_initTokenizerForFragmentParsing(){if(this.fragmentContext&&this.treeAdapter.getNamespaceURI(this.fragmentContext)===cF.HTML)switch(this.fragmentContextID){case pF.TITLE:case pF.TEXTAREA:this.tokenizer.state=vF.RCDATA;break;case pF.STYLE:case pF.XMP:case pF.IFRAME:case pF.NOEMBED:case pF.NOFRAMES:case pF.NOSCRIPT:this.tokenizer.state=vF.RAWTEXT;break;case pF.SCRIPT:this.tokenizer.state=vF.SCRIPT_DATA;break;case pF.PLAINTEXT:this.tokenizer.state=vF.PLAINTEXT}}_setDocumentType(e){const t=e.name||"",n=e.publicId||"",r=e.systemId||"";if(this.treeAdapter.setDocumentType(this.document,t,n,r),e.location){const t=this.treeAdapter.getChildNodes(this.document),n=t.find(e=>this.treeAdapter.isDocumentTypeNode(e));n&&this.treeAdapter.setNodeSourceCodeLocation(n,e.location)}}_attachElementToTree(e,t){if(this.options.sourceCodeLocationInfo){const n=t&&{...t,startTag:t};this.treeAdapter.setNodeSourceCodeLocation(e,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(e);else{const t=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(null!=t?t:this.document,e)}}_appendElement(e,t){const n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location)}_insertElement(e,t){const n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location),this.openElements.push(n,e.tagID)}_insertFakeElement(e,t){const n=this.treeAdapter.createElement(e,cF.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,t)}_insertTemplate(e){const t=this.treeAdapter.createElement(e.tagName,cF.HTML,e.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(t,n),this._attachElementToTree(t,e.location),this.openElements.push(t,e.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){const e=this.treeAdapter.createElement(uF.HTML,cF.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(e,null),this.treeAdapter.appendChild(this.openElements.current,e),this.openElements.push(e,pF.HTML)}_appendCommentNode(e,t){const n=this.treeAdapter.createCommentNode(e.data);this.treeAdapter.appendChild(t,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,e.location)}_insertCharacters(e){let t,n;if(this._shouldFosterParentOnInsertion()?(({parent:t,beforeElement:n}=this._findFosterParentingLocation()),n?this.treeAdapter.insertTextBefore(t,e.chars,n):this.treeAdapter.insertText(t,e.chars)):(t=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(t,e.chars)),!e.location)return;const r=this.treeAdapter.getChildNodes(t),s=n?r.lastIndexOf(n):r.length,i=r[s-1],o=this.treeAdapter.getNodeSourceCodeLocation(i);if(o){const{endLine:t,endCol:n,endOffset:r}=e.location;this.treeAdapter.updateNodeSourceCodeLocation(i,{endLine:t,endCol:n,endOffset:r})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(i,e.location)}_adoptNodes(e,t){for(let n=this.treeAdapter.getFirstChild(e);n;n=this.treeAdapter.getFirstChild(e))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(t,n)}_setEndLocation(e,t){if(this.treeAdapter.getNodeSourceCodeLocation(e)&&t.location){const n=t.location,r=this.treeAdapter.getTagName(e),s=t.type===JO.END_TAG&&r===t.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(e,s)}}shouldProcessStartTagTokenInForeignContent(e){if(!this.currentNotInHTML)return!1;let t,n;return 0===this.openElements.stackTop&&this.fragmentContext?(t=this.fragmentContext,n=this.fragmentContextID):({current:t,currentTagId:n}=this.openElements),(e.tagID!==pF.SVG||this.treeAdapter.getTagName(t)!==uF.ANNOTATION_XML||this.treeAdapter.getNamespaceURI(t)!==cF.MATHML)&&(this.tokenizer.inForeignNode||(e.tagID===pF.MGLYPH||e.tagID===pF.MALIGNMARK)&&void 0!==n&&!this._isIntegrationPoint(n,t,cF.HTML))}_processToken(e){switch(e.type){case JO.CHARACTER:this.onCharacter(e);break;case JO.NULL_CHARACTER:this.onNullCharacter(e);break;case JO.COMMENT:this.onComment(e);break;case JO.DOCTYPE:this.onDoctype(e);break;case JO.START_TAG:this._processStartTag(e);break;case JO.END_TAG:this.onEndTag(e);break;case JO.EOF:this.onEof(e);break;case JO.WHITESPACE_CHARACTER:this.onWhitespaceCharacter(e)}}_isIntegrationPoint(e,t,n){const r=this.treeAdapter.getNamespaceURI(t),s=this.treeAdapter.getAttrList(t);return isIntegrationPoint(e,r,s,n)}_reconstructActiveFormattingElements(){const e=this.activeFormattingElements.entries.length;if(e){const t=this.activeFormattingElements.entries.findIndex(e=>e.type===OF.Marker||this.openElements.contains(e.element)),n=-1===t?e-1:t-1;for(let e=n;e>=0;e--){const t=this.activeFormattingElements.entries[e];this._insertElement(t.token,this.treeAdapter.getNamespaceURI(t.element)),t.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=nL.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(pF.P),this.openElements.popUntilTagNamePopped(pF.P)}_resetInsertionMode(){for(let e=this.openElements.stackTop;e>=0;e--)switch(0===e&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[e]){case pF.TR:return void(this.insertionMode=nL.IN_ROW);case pF.TBODY:case pF.THEAD:case pF.TFOOT:return void(this.insertionMode=nL.IN_TABLE_BODY);case pF.CAPTION:return void(this.insertionMode=nL.IN_CAPTION);case pF.COLGROUP:return void(this.insertionMode=nL.IN_COLUMN_GROUP);case pF.TABLE:return void(this.insertionMode=nL.IN_TABLE);case pF.BODY:return void(this.insertionMode=nL.IN_BODY);case pF.FRAMESET:return void(this.insertionMode=nL.IN_FRAMESET);case pF.SELECT:return void this._resetInsertionModeForSelect(e);case pF.TEMPLATE:return void(this.insertionMode=this.tmplInsertionModeStack[0]);case pF.HTML:return void(this.insertionMode=this.headElement?nL.AFTER_HEAD:nL.BEFORE_HEAD);case pF.TD:case pF.TH:if(e>0)return void(this.insertionMode=nL.IN_CELL);break;case pF.HEAD:if(e>0)return void(this.insertionMode=nL.IN_HEAD)}this.insertionMode=nL.IN_BODY}_resetInsertionModeForSelect(e){if(e>0)for(let t=e-1;t>0;t--){const e=this.openElements.tagIDs[t];if(e===pF.TEMPLATE)break;if(e===pF.TABLE)return void(this.insertionMode=nL.IN_SELECT_IN_TABLE)}this.insertionMode=nL.IN_SELECT}_isElementCausesFosterParenting(e){return sL.has(e)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&void 0!==this.openElements.currentTagId&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let e=this.openElements.stackTop;e>=0;e--){const t=this.openElements.items[e];switch(this.openElements.tagIDs[e]){case pF.TEMPLATE:if(this.treeAdapter.getNamespaceURI(t)===cF.HTML)return{parent:this.treeAdapter.getTemplateContent(t),beforeElement:null};break;case pF.TABLE:{const n=this.treeAdapter.getParentNode(t);return n?{parent:n,beforeElement:t}:{parent:this.openElements.items[e-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(e){const t=this._findFosterParentingLocation();t.beforeElement?this.treeAdapter.insertBefore(t.parent,e,t.beforeElement):this.treeAdapter.appendChild(t.parent,e)}_isSpecialElement(e,t){const n=this.treeAdapter.getNamespaceURI(e);return fF[n].has(t)}onCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode)characterInForeignContent(this,e);else switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:tokenBeforeHtml(this,e);break;case nL.BEFORE_HEAD:tokenBeforeHead(this,e);break;case nL.IN_HEAD:tokenInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case nL.AFTER_HEAD:tokenAfterHead(this,e);break;case nL.IN_BODY:case nL.IN_CAPTION:case nL.IN_CELL:case nL.IN_TEMPLATE:characterInBody(this,e);break;case nL.TEXT:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:this._insertCharacters(e);break;case nL.IN_TABLE:case nL.IN_TABLE_BODY:case nL.IN_ROW:characterInTable(this,e);break;case nL.IN_TABLE_TEXT:characterInTableText(this,e);break;case nL.IN_COLUMN_GROUP:tokenInColumnGroup(this,e);break;case nL.AFTER_BODY:tokenAfterBody(this,e);break;case nL.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onNullCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode)nullCharacterInForeignContent(this,e);else switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:tokenBeforeHtml(this,e);break;case nL.BEFORE_HEAD:tokenBeforeHead(this,e);break;case nL.IN_HEAD:tokenInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case nL.AFTER_HEAD:tokenAfterHead(this,e);break;case nL.TEXT:this._insertCharacters(e);break;case nL.IN_TABLE:case nL.IN_TABLE_BODY:case nL.IN_ROW:characterInTable(this,e);break;case nL.IN_COLUMN_GROUP:tokenInColumnGroup(this,e);break;case nL.AFTER_BODY:tokenAfterBody(this,e);break;case nL.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onComment(e){if(this.skipNextNewLine=!1,this.currentNotInHTML)appendComment(this,e);else switch(this.insertionMode){case nL.INITIAL:case nL.BEFORE_HTML:case nL.BEFORE_HEAD:case nL.IN_HEAD:case nL.IN_HEAD_NO_SCRIPT:case nL.AFTER_HEAD:case nL.IN_BODY:case nL.IN_TABLE:case nL.IN_CAPTION:case nL.IN_COLUMN_GROUP:case nL.IN_TABLE_BODY:case nL.IN_ROW:case nL.IN_CELL:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:case nL.IN_TEMPLATE:case nL.IN_FRAMESET:case nL.AFTER_FRAMESET:appendComment(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.AFTER_BODY:appendCommentToRootHtmlElement(this,e);break;case nL.AFTER_AFTER_BODY:case nL.AFTER_AFTER_FRAMESET:appendCommentToDocument(this,e)}}onDoctype(e){switch(this.skipNextNewLine=!1,this.insertionMode){case nL.INITIAL:doctypeInInitialMode(this,e);break;case nL.BEFORE_HEAD:case nL.IN_HEAD:case nL.IN_HEAD_NO_SCRIPT:case nL.AFTER_HEAD:this._err(e,KO.misplacedDoctype);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e)}}onStartTag(e){this.skipNextNewLine=!1,this.currentToken=e,this._processStartTag(e),e.selfClosing&&!e.ackSelfClosing&&this._err(e,KO.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(e){this.shouldProcessStartTagTokenInForeignContent(e)?startTagInForeignContent(this,e):this._startTagOutsideForeignContent(e)}_startTagOutsideForeignContent(e){switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:startTagBeforeHtml(this,e);break;case nL.BEFORE_HEAD:startTagBeforeHead(this,e);break;case nL.IN_HEAD:startTagInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:startTagInHeadNoScript(this,e);break;case nL.AFTER_HEAD:startTagAfterHead(this,e);break;case nL.IN_BODY:startTagInBody(this,e);break;case nL.IN_TABLE:startTagInTable(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.IN_CAPTION:startTagInCaption(this,e);break;case nL.IN_COLUMN_GROUP:startTagInColumnGroup(this,e);break;case nL.IN_TABLE_BODY:startTagInTableBody(this,e);break;case nL.IN_ROW:startTagInRow(this,e);break;case nL.IN_CELL:startTagInCell(this,e);break;case nL.IN_SELECT:startTagInSelect(this,e);break;case nL.IN_SELECT_IN_TABLE:startTagInSelectInTable(this,e);break;case nL.IN_TEMPLATE:startTagInTemplate(this,e);break;case nL.AFTER_BODY:startTagAfterBody(this,e);break;case nL.IN_FRAMESET:startTagInFrameset(this,e);break;case nL.AFTER_FRAMESET:startTagAfterFrameset(this,e);break;case nL.AFTER_AFTER_BODY:startTagAfterAfterBody(this,e);break;case nL.AFTER_AFTER_FRAMESET:startTagAfterAfterFrameset(this,e)}}onEndTag(e){this.skipNextNewLine=!1,this.currentToken=e,this.currentNotInHTML?endTagInForeignContent(this,e):this._endTagOutsideForeignContent(e)}_endTagOutsideForeignContent(e){switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:endTagBeforeHtml(this,e);break;case nL.BEFORE_HEAD:endTagBeforeHead(this,e);break;case nL.IN_HEAD:endTagInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:endTagInHeadNoScript(this,e);break;case nL.AFTER_HEAD:endTagAfterHead(this,e);break;case nL.IN_BODY:endTagInBody(this,e);break;case nL.TEXT:endTagInText(this,e);break;case nL.IN_TABLE:endTagInTable(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.IN_CAPTION:endTagInCaption(this,e);break;case nL.IN_COLUMN_GROUP:endTagInColumnGroup(this,e);break;case nL.IN_TABLE_BODY:endTagInTableBody(this,e);break;case nL.IN_ROW:endTagInRow(this,e);break;case nL.IN_CELL:endTagInCell(this,e);break;case nL.IN_SELECT:endTagInSelect(this,e);break;case nL.IN_SELECT_IN_TABLE:endTagInSelectInTable(this,e);break;case nL.IN_TEMPLATE:endTagInTemplate(this,e);break;case nL.AFTER_BODY:endTagAfterBody(this,e);break;case nL.IN_FRAMESET:endTagInFrameset(this,e);break;case nL.AFTER_FRAMESET:endTagAfterFrameset(this,e);break;case nL.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onEof(e){switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:tokenBeforeHtml(this,e);break;case nL.BEFORE_HEAD:tokenBeforeHead(this,e);break;case nL.IN_HEAD:tokenInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case nL.AFTER_HEAD:tokenAfterHead(this,e);break;case nL.IN_BODY:case nL.IN_TABLE:case nL.IN_CAPTION:case nL.IN_COLUMN_GROUP:case nL.IN_TABLE_BODY:case nL.IN_ROW:case nL.IN_CELL:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:eofInBody(this,e);break;case nL.TEXT:eofInText(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.IN_TEMPLATE:eofInTemplate(this,e);break;case nL.AFTER_BODY:case nL.IN_FRAMESET:case nL.AFTER_FRAMESET:case nL.AFTER_AFTER_BODY:case nL.AFTER_AFTER_FRAMESET:stopParsing(this,e)}}onWhitespaceCharacter(e){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,e.chars.charCodeAt(0)===GO.LINE_FEED)){if(1===e.chars.length)return;e.chars=e.chars.substr(1)}if(this.tokenizer.inForeignNode)this._insertCharacters(e);else switch(this.insertionMode){case nL.IN_HEAD:case nL.IN_HEAD_NO_SCRIPT:case nL.AFTER_HEAD:case nL.TEXT:case nL.IN_COLUMN_GROUP:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:case nL.IN_FRAMESET:case nL.AFTER_FRAMESET:this._insertCharacters(e);break;case nL.IN_BODY:case nL.IN_CAPTION:case nL.IN_CELL:case nL.IN_TEMPLATE:case nL.AFTER_BODY:case nL.AFTER_AFTER_BODY:case nL.AFTER_AFTER_FRAMESET:whitespaceCharacterInBody(this,e);break;case nL.IN_TABLE:case nL.IN_TABLE_BODY:case nL.IN_ROW:characterInTable(this,e);break;case nL.IN_TABLE_TEXT:whitespaceCharacterInTableText(this,e)}}};function aaObtainFormattingElementEntry(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):genericEndTagInBody(e,t),n}function aaObtainFurthestBlock(e,t){let n=null,r=e.openElements.stackTop;for(;r>=0;r--){const s=e.openElements.items[r];if(s===t.element)break;e._isSpecialElement(s,e.openElements.tagIDs[r])&&(n=s)}return n||(e.openElements.shortenToLength(Math.max(r,0)),e.activeFormattingElements.removeEntry(t)),n}function aaInnerLoop(e,t,n){let r=t,s=e.openElements.getCommonAncestor(t);for(let i=0,o=s;o!==n;i++,o=s){s=e.openElements.getCommonAncestor(o);const n=e.activeFormattingElements.getElementEntry(o),a=n&&i>=tL,c=!n||a;c?(a&&e.activeFormattingElements.removeEntry(n),e.openElements.remove(o)):(o=aaRecreateElementFromEntry(e,n),r===t&&(e.activeFormattingElements.bookmark=n),e.treeAdapter.detachNode(r),e.treeAdapter.appendChild(o,r),r=o)}return r}function aaRecreateElementFromEntry(e,t){const n=e.treeAdapter.getNamespaceURI(t.element),r=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,r),t.element=r,r}function aaInsertLastNodeInCommonAncestor(e,t,n){const r=e.treeAdapter.getTagName(t),s=getTagID(r);if(e._isElementCausesFosterParenting(s))e._fosterParentElement(n);else{const r=e.treeAdapter.getNamespaceURI(t);s===pF.TEMPLATE&&r===cF.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function aaReplaceFormattingElement(e,t,n){const r=e.treeAdapter.getNamespaceURI(n.element),{token:s}=n,i=e.treeAdapter.createElement(s.tagName,r,s.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,s),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,s.tagID)}function callAdoptionAgency(e,t){for(let n=0;n<eL;n++){const n=aaObtainFormattingElementEntry(e,t);if(!n)break;const r=aaObtainFurthestBlock(e,n);if(!r)break;e.activeFormattingElements.bookmark=n;const s=aaInnerLoop(e,r,n.element),i=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),i&&aaInsertLastNodeInCommonAncestor(e,i,s),aaReplaceFormattingElement(e,r,n)}}function appendComment(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function appendCommentToRootHtmlElement(e,t){e._appendCommentNode(t,e.openElements.items[0])}function appendCommentToDocument(e,t){e._appendCommentNode(t,e.document)}function stopParsing(e,t){if(e.stopped=!0,t.location){const n=e.fragmentContext?0:2;for(let r=e.openElements.stackTop;r>=n;r--)e._setEndLocation(e.openElements.items[r],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const n=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(n);if(r&&!r.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){const n=e.openElements.items[1],r=e.treeAdapter.getNodeSourceCodeLocation(n);r&&!r.endTag&&e._setEndLocation(n,t)}}}}function doctypeInInitialMode(e,t){e._setDocumentType(t);const n=t.forceQuirks?dF.QUIRKS:getDocumentMode(t);isConforming(t)||e._err(t,KO.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=nL.BEFORE_HTML}function tokenInInitialMode(e,t){e._err(t,KO.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,dF.QUIRKS),e.insertionMode=nL.BEFORE_HTML,e._processToken(t)}function startTagBeforeHtml(e,t){t.tagID===pF.HTML?(e._insertElement(t,cF.HTML),e.insertionMode=nL.BEFORE_HEAD):tokenBeforeHtml(e,t)}function endTagBeforeHtml(e,t){const n=t.tagID;n!==pF.HTML&&n!==pF.HEAD&&n!==pF.BODY&&n!==pF.BR||tokenBeforeHtml(e,t)}function tokenBeforeHtml(e,t){e._insertFakeRootElement(),e.insertionMode=nL.BEFORE_HEAD,e._processToken(t)}function startTagBeforeHead(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.HEAD:e._insertElement(t,cF.HTML),e.headElement=e.openElements.current,e.insertionMode=nL.IN_HEAD;break;default:tokenBeforeHead(e,t)}}function endTagBeforeHead(e,t){const n=t.tagID;n===pF.HEAD||n===pF.BODY||n===pF.HTML||n===pF.BR?tokenBeforeHead(e,t):e._err(t,KO.endTagWithoutMatchingOpenElement)}function tokenBeforeHead(e,t){e._insertFakeElement(uF.HEAD,pF.HEAD),e.headElement=e.openElements.current,e.insertionMode=nL.IN_HEAD,e._processToken(t)}function startTagInHead(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.BASE:case pF.BASEFONT:case pF.BGSOUND:case pF.LINK:case pF.META:e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.TITLE:e._switchToTextParsing(t,vF.RCDATA);break;case pF.NOSCRIPT:e.options.scriptingEnabled?e._switchToTextParsing(t,vF.RAWTEXT):(e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_HEAD_NO_SCRIPT);break;case pF.NOFRAMES:case pF.STYLE:e._switchToTextParsing(t,vF.RAWTEXT);break;case pF.SCRIPT:e._switchToTextParsing(t,vF.SCRIPT_DATA);break;case pF.TEMPLATE:e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=nL.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(nL.IN_TEMPLATE);break;case pF.HEAD:e._err(t,KO.misplacedStartTagForHeadElement);break;default:tokenInHead(e,t)}}function endTagInHead(e,t){switch(t.tagID){case pF.HEAD:e.openElements.pop(),e.insertionMode=nL.AFTER_HEAD;break;case pF.BODY:case pF.BR:case pF.HTML:tokenInHead(e,t);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;default:e._err(t,KO.endTagWithoutMatchingOpenElement)}}function templateEndTagInHead(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==pF.TEMPLATE&&e._err(t,KO.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(pF.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,KO.endTagWithoutMatchingOpenElement)}function tokenInHead(e,t){e.openElements.pop(),e.insertionMode=nL.AFTER_HEAD,e._processToken(t)}function startTagInHeadNoScript(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.BASEFONT:case pF.BGSOUND:case pF.HEAD:case pF.LINK:case pF.META:case pF.NOFRAMES:case pF.STYLE:startTagInHead(e,t);break;case pF.NOSCRIPT:e._err(t,KO.nestedNoscriptInHead);break;default:tokenInHeadNoScript(e,t)}}function endTagInHeadNoScript(e,t){switch(t.tagID){case pF.NOSCRIPT:e.openElements.pop(),e.insertionMode=nL.IN_HEAD;break;case pF.BR:tokenInHeadNoScript(e,t);break;default:e._err(t,KO.endTagWithoutMatchingOpenElement)}}function tokenInHeadNoScript(e,t){const n=t.type===JO.EOF?KO.openElementsLeftAfterEof:KO.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=nL.IN_HEAD,e._processToken(t)}function startTagAfterHead(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.BODY:e._insertElement(t,cF.HTML),e.framesetOk=!1,e.insertionMode=nL.IN_BODY;break;case pF.FRAMESET:e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_FRAMESET;break;case pF.BASE:case pF.BASEFONT:case pF.BGSOUND:case pF.LINK:case pF.META:case pF.NOFRAMES:case pF.SCRIPT:case pF.STYLE:case pF.TEMPLATE:case pF.TITLE:e._err(t,KO.abandonedHeadElementChild),e.openElements.push(e.headElement,pF.HEAD),startTagInHead(e,t),e.openElements.remove(e.headElement);break;case pF.HEAD:e._err(t,KO.misplacedStartTagForHeadElement);break;default:tokenAfterHead(e,t)}}function endTagAfterHead(e,t){switch(t.tagID){case pF.BODY:case pF.HTML:case pF.BR:tokenAfterHead(e,t);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;default:e._err(t,KO.endTagWithoutMatchingOpenElement)}}function tokenAfterHead(e,t){e._insertFakeElement(uF.BODY,pF.BODY),e.insertionMode=nL.IN_BODY,modeInBody(e,t)}function modeInBody(e,t){switch(t.type){case JO.CHARACTER:characterInBody(e,t);break;case JO.WHITESPACE_CHARACTER:whitespaceCharacterInBody(e,t);break;case JO.COMMENT:appendComment(e,t);break;case JO.START_TAG:startTagInBody(e,t);break;case JO.END_TAG:endTagInBody(e,t);break;case JO.EOF:eofInBody(e,t)}}function whitespaceCharacterInBody(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function characterInBody(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function htmlStartTagInBody(e,t){0===e.openElements.tmplCount&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function bodyStartTagInBody(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&0===e.openElements.tmplCount&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function framesetStartTagInBody(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_FRAMESET)}function addressStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML)}function numberedHeaderStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),void 0!==e.openElements.currentTagId&&gF.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,cF.HTML)}function preStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function formStartTagInBody(e,t){const n=e.openElements.tmplCount>0;e.formElement&&!n||(e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),n||(e.formElement=e.openElements.current))}function listItemStartTagInBody(e,t){e.framesetOk=!1;const n=t.tagID;for(let t=e.openElements.stackTop;t>=0;t--){const r=e.openElements.tagIDs[t];if(n===pF.LI&&r===pF.LI||(n===pF.DD||n===pF.DT)&&(r===pF.DD||r===pF.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==pF.ADDRESS&&r!==pF.DIV&&r!==pF.P&&e._isSpecialElement(e.openElements.items[t],r))break}e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML)}function plaintextStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),e.tokenizer.state=vF.PLAINTEXT}function buttonStartTagInBody(e,t){e.openElements.hasInScope(pF.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(pF.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.framesetOk=!1}function aStartTagInBody(e,t){const n=e.activeFormattingElements.getElementEntryInScopeWithTagName(uF.A);n&&(callAdoptionAgency(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function bStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function nobrStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(pF.NOBR)&&(callAdoptionAgency(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,cF.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function appletStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function tableStartTagInBody(e,t){e.treeAdapter.getDocumentMode(e.document)!==dF.QUIRKS&&e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),e.framesetOk=!1,e.insertionMode=nL.IN_TABLE}function areaStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,cF.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function isHiddenInput(e){const t=getTokenAttr(e,lF.TYPE);return null!=t&&t.toLowerCase()===ZF}function inputStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,cF.HTML),isHiddenInput(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function paramStartTagInBody(e,t){e._appendElement(t,cF.HTML),t.ackSelfClosing=!0}function hrStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._appendElement(t,cF.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function imageStartTagInBody(e,t){t.tagName=uF.IMG,t.tagID=pF.IMG,areaStartTagInBody(e,t)}function textareaStartTagInBody(e,t){e._insertElement(t,cF.HTML),e.skipNextNewLine=!0,e.tokenizer.state=vF.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=nL.TEXT}function xmpStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,vF.RAWTEXT)}function iframeStartTagInBody(e,t){e.framesetOk=!1,e._switchToTextParsing(t,vF.RAWTEXT)}function rawTextStartTagInBody(e,t){e._switchToTextParsing(t,vF.RAWTEXT)}function selectStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===nL.IN_TABLE||e.insertionMode===nL.IN_CAPTION||e.insertionMode===nL.IN_TABLE_BODY||e.insertionMode===nL.IN_ROW||e.insertionMode===nL.IN_CELL?nL.IN_SELECT_IN_TABLE:nL.IN_SELECT}function optgroupStartTagInBody(e,t){e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML)}function rbStartTagInBody(e,t){e.openElements.hasInScope(pF.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,cF.HTML)}function rtStartTagInBody(e,t){e.openElements.hasInScope(pF.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(pF.RTC),e._insertElement(t,cF.HTML)}function mathStartTagInBody(e,t){e._reconstructActiveFormattingElements(),adjustTokenMathMLAttrs(t),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,cF.MATHML):e._insertElement(t,cF.MATHML),t.ackSelfClosing=!0}function svgStartTagInBody(e,t){e._reconstructActiveFormattingElements(),adjustTokenSVGAttrs(t),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,cF.SVG):e._insertElement(t,cF.SVG),t.ackSelfClosing=!0}function genericStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML)}function startTagInBody(e,t){switch(t.tagID){case pF.I:case pF.S:case pF.B:case pF.U:case pF.EM:case pF.TT:case pF.BIG:case pF.CODE:case pF.FONT:case pF.SMALL:case pF.STRIKE:case pF.STRONG:bStartTagInBody(e,t);break;case pF.A:aStartTagInBody(e,t);break;case pF.H1:case pF.H2:case pF.H3:case pF.H4:case pF.H5:case pF.H6:numberedHeaderStartTagInBody(e,t);break;case pF.P:case pF.DL:case pF.OL:case pF.UL:case pF.DIV:case pF.DIR:case pF.NAV:case pF.MAIN:case pF.MENU:case pF.ASIDE:case pF.CENTER:case pF.FIGURE:case pF.FOOTER:case pF.HEADER:case pF.HGROUP:case pF.DIALOG:case pF.DETAILS:case pF.ADDRESS:case pF.ARTICLE:case pF.SEARCH:case pF.SECTION:case pF.SUMMARY:case pF.FIELDSET:case pF.BLOCKQUOTE:case pF.FIGCAPTION:addressStartTagInBody(e,t);break;case pF.LI:case pF.DD:case pF.DT:listItemStartTagInBody(e,t);break;case pF.BR:case pF.IMG:case pF.WBR:case pF.AREA:case pF.EMBED:case pF.KEYGEN:areaStartTagInBody(e,t);break;case pF.HR:hrStartTagInBody(e,t);break;case pF.RB:case pF.RTC:rbStartTagInBody(e,t);break;case pF.RT:case pF.RP:rtStartTagInBody(e,t);break;case pF.PRE:case pF.LISTING:preStartTagInBody(e,t);break;case pF.XMP:xmpStartTagInBody(e,t);break;case pF.SVG:svgStartTagInBody(e,t);break;case pF.HTML:htmlStartTagInBody(e,t);break;case pF.BASE:case pF.LINK:case pF.META:case pF.STYLE:case pF.TITLE:case pF.SCRIPT:case pF.BGSOUND:case pF.BASEFONT:case pF.TEMPLATE:startTagInHead(e,t);break;case pF.BODY:bodyStartTagInBody(e,t);break;case pF.FORM:formStartTagInBody(e,t);break;case pF.NOBR:nobrStartTagInBody(e,t);break;case pF.MATH:mathStartTagInBody(e,t);break;case pF.TABLE:tableStartTagInBody(e,t);break;case pF.INPUT:inputStartTagInBody(e,t);break;case pF.PARAM:case pF.TRACK:case pF.SOURCE:paramStartTagInBody(e,t);break;case pF.IMAGE:imageStartTagInBody(e,t);break;case pF.BUTTON:buttonStartTagInBody(e,t);break;case pF.APPLET:case pF.OBJECT:case pF.MARQUEE:appletStartTagInBody(e,t);break;case pF.IFRAME:iframeStartTagInBody(e,t);break;case pF.SELECT:selectStartTagInBody(e,t);break;case pF.OPTION:case pF.OPTGROUP:optgroupStartTagInBody(e,t);break;case pF.NOEMBED:case pF.NOFRAMES:rawTextStartTagInBody(e,t);break;case pF.FRAMESET:framesetStartTagInBody(e,t);break;case pF.TEXTAREA:textareaStartTagInBody(e,t);break;case pF.NOSCRIPT:e.options.scriptingEnabled?rawTextStartTagInBody(e,t):genericStartTagInBody(e,t);break;case pF.PLAINTEXT:plaintextStartTagInBody(e,t);break;case pF.COL:case pF.TH:case pF.TD:case pF.TR:case pF.HEAD:case pF.FRAME:case pF.TBODY:case pF.TFOOT:case pF.THEAD:case pF.CAPTION:case pF.COLGROUP:break;default:genericStartTagInBody(e,t)}}function bodyEndTagInBody(e,t){if(e.openElements.hasInScope(pF.BODY)&&(e.insertionMode=nL.AFTER_BODY,e.options.sourceCodeLocationInfo)){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function htmlEndTagInBody(e,t){e.openElements.hasInScope(pF.BODY)&&(e.insertionMode=nL.AFTER_BODY,endTagAfterBody(e,t))}function addressEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function formEndTagInBody(e){const t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(pF.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(pF.FORM):n&&e.openElements.remove(n))}function pEndTagInBody(e){e.openElements.hasInButtonScope(pF.P)||e._insertFakeElement(uF.P,pF.P),e._closePElement()}function liEndTagInBody(e){e.openElements.hasInListItemScope(pF.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(pF.LI),e.openElements.popUntilTagNamePopped(pF.LI))}function ddEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function numberedHeaderEndTagInBody(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function appletEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function brEndTagInBody(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(uF.BR,pF.BR),e.openElements.pop(),e.framesetOk=!1}function genericEndTagInBody(e,t){const n=t.tagName,r=t.tagID;for(let t=e.openElements.stackTop;t>0;t--){const s=e.openElements.items[t],i=e.openElements.tagIDs[t];if(r===i&&(r!==pF.UNKNOWN||e.treeAdapter.getTagName(s)===n)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.stackTop>=t&&e.openElements.shortenToLength(t);break}if(e._isSpecialElement(s,i))break}}function endTagInBody(e,t){switch(t.tagID){case pF.A:case pF.B:case pF.I:case pF.S:case pF.U:case pF.EM:case pF.TT:case pF.BIG:case pF.CODE:case pF.FONT:case pF.NOBR:case pF.SMALL:case pF.STRIKE:case pF.STRONG:callAdoptionAgency(e,t);break;case pF.P:pEndTagInBody(e);break;case pF.DL:case pF.UL:case pF.OL:case pF.DIR:case pF.DIV:case pF.NAV:case pF.PRE:case pF.MAIN:case pF.MENU:case pF.ASIDE:case pF.BUTTON:case pF.CENTER:case pF.FIGURE:case pF.FOOTER:case pF.HEADER:case pF.HGROUP:case pF.DIALOG:case pF.ADDRESS:case pF.ARTICLE:case pF.DETAILS:case pF.SEARCH:case pF.SECTION:case pF.SUMMARY:case pF.LISTING:case pF.FIELDSET:case pF.BLOCKQUOTE:case pF.FIGCAPTION:addressEndTagInBody(e,t);break;case pF.LI:liEndTagInBody(e);break;case pF.DD:case pF.DT:ddEndTagInBody(e,t);break;case pF.H1:case pF.H2:case pF.H3:case pF.H4:case pF.H5:case pF.H6:numberedHeaderEndTagInBody(e);break;case pF.BR:brEndTagInBody(e);break;case pF.BODY:bodyEndTagInBody(e,t);break;case pF.HTML:htmlEndTagInBody(e,t);break;case pF.FORM:formEndTagInBody(e);break;case pF.APPLET:case pF.OBJECT:case pF.MARQUEE:appletEndTagInBody(e,t);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;default:genericEndTagInBody(e,t)}}function eofInBody(e,t){e.tmplInsertionModeStack.length>0?eofInTemplate(e,t):stopParsing(e,t)}function endTagInText(e,t){var n;t.tagID===pF.SCRIPT&&(null===(n=e.scriptHandler)||void 0===n||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function eofInText(e,t){e._err(t,KO.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function characterInTable(e,t){if(void 0!==e.openElements.currentTagId&&sL.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=nL.IN_TABLE_TEXT,t.type){case JO.CHARACTER:characterInTableText(e,t);break;case JO.WHITESPACE_CHARACTER:whitespaceCharacterInTableText(e,t)}else tokenInTable(e,t)}function captionStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_CAPTION}function colgroupStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_COLUMN_GROUP}function colStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(uF.COLGROUP,pF.COLGROUP),e.insertionMode=nL.IN_COLUMN_GROUP,startTagInColumnGroup(e,t)}function tbodyStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_TABLE_BODY}function tdStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(uF.TBODY,pF.TBODY),e.insertionMode=nL.IN_TABLE_BODY,startTagInTableBody(e,t)}function tableStartTagInTable(e,t){e.openElements.hasInTableScope(pF.TABLE)&&(e.openElements.popUntilTagNamePopped(pF.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function inputStartTagInTable(e,t){isHiddenInput(t)?e._appendElement(t,cF.HTML):tokenInTable(e,t),t.ackSelfClosing=!0}function formStartTagInTable(e,t){e.formElement||0!==e.openElements.tmplCount||(e._insertElement(t,cF.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function startTagInTable(e,t){switch(t.tagID){case pF.TD:case pF.TH:case pF.TR:tdStartTagInTable(e,t);break;case pF.STYLE:case pF.SCRIPT:case pF.TEMPLATE:startTagInHead(e,t);break;case pF.COL:colStartTagInTable(e,t);break;case pF.FORM:formStartTagInTable(e,t);break;case pF.TABLE:tableStartTagInTable(e,t);break;case pF.TBODY:case pF.TFOOT:case pF.THEAD:tbodyStartTagInTable(e,t);break;case pF.INPUT:inputStartTagInTable(e,t);break;case pF.CAPTION:captionStartTagInTable(e,t);break;case pF.COLGROUP:colgroupStartTagInTable(e,t);break;default:tokenInTable(e,t)}}function endTagInTable(e,t){switch(t.tagID){case pF.TABLE:e.openElements.hasInTableScope(pF.TABLE)&&(e.openElements.popUntilTagNamePopped(pF.TABLE),e._resetInsertionMode());break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TBODY:case pF.TD:case pF.TFOOT:case pF.TH:case pF.THEAD:case pF.TR:break;default:tokenInTable(e,t)}}function tokenInTable(e,t){const n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,modeInBody(e,t),e.fosterParentingEnabled=n}function whitespaceCharacterInTableText(e,t){e.pendingCharacterTokens.push(t)}function characterInTableText(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function tokenInTableText(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)tokenInTable(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}var aL=new Set([pF.CAPTION,pF.COL,pF.COLGROUP,pF.TBODY,pF.TD,pF.TFOOT,pF.TH,pF.THEAD,pF.TR]);function startTagInCaption(e,t){const n=t.tagID;aL.has(n)?e.openElements.hasInTableScope(pF.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(pF.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=nL.IN_TABLE,startTagInTable(e,t)):startTagInBody(e,t)}function endTagInCaption(e,t){const n=t.tagID;switch(n){case pF.CAPTION:case pF.TABLE:e.openElements.hasInTableScope(pF.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(pF.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=nL.IN_TABLE,n===pF.TABLE&&endTagInTable(e,t));break;case pF.BODY:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TBODY:case pF.TD:case pF.TFOOT:case pF.TH:case pF.THEAD:case pF.TR:break;default:endTagInBody(e,t)}}function startTagInColumnGroup(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.COL:e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.TEMPLATE:startTagInHead(e,t);break;default:tokenInColumnGroup(e,t)}}function endTagInColumnGroup(e,t){switch(t.tagID){case pF.COLGROUP:e.openElements.currentTagId===pF.COLGROUP&&(e.openElements.pop(),e.insertionMode=nL.IN_TABLE);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;case pF.COL:break;default:tokenInColumnGroup(e,t)}}function tokenInColumnGroup(e,t){e.openElements.currentTagId===pF.COLGROUP&&(e.openElements.pop(),e.insertionMode=nL.IN_TABLE,e._processToken(t))}function startTagInTableBody(e,t){switch(t.tagID){case pF.TR:e.openElements.clearBackToTableBodyContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_ROW;break;case pF.TH:case pF.TD:e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(uF.TR,pF.TR),e.insertionMode=nL.IN_ROW,startTagInRow(e,t);break;case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.TBODY:case pF.TFOOT:case pF.THEAD:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE,startTagInTable(e,t));break;default:startTagInTable(e,t)}}function endTagInTableBody(e,t){const n=t.tagID;switch(t.tagID){case pF.TBODY:case pF.TFOOT:case pF.THEAD:e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE);break;case pF.TABLE:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE,endTagInTable(e,t));break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TD:case pF.TH:case pF.TR:break;default:endTagInTable(e,t)}}function startTagInRow(e,t){switch(t.tagID){case pF.TH:case pF.TD:e.openElements.clearBackToTableRowContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_CELL,e.activeFormattingElements.insertMarker();break;case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.TBODY:case pF.TFOOT:case pF.THEAD:case pF.TR:e.openElements.hasInTableScope(pF.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY,startTagInTableBody(e,t));break;default:startTagInTable(e,t)}}function endTagInRow(e,t){switch(t.tagID){case pF.TR:e.openElements.hasInTableScope(pF.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY);break;case pF.TABLE:e.openElements.hasInTableScope(pF.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY,endTagInTableBody(e,t));break;case pF.TBODY:case pF.TFOOT:case pF.THEAD:(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(pF.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY,endTagInTableBody(e,t));break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TD:case pF.TH:break;default:endTagInTable(e,t)}}function startTagInCell(e,t){const n=t.tagID;aL.has(n)?(e.openElements.hasInTableScope(pF.TD)||e.openElements.hasInTableScope(pF.TH))&&(e._closeTableCell(),startTagInRow(e,t)):startTagInBody(e,t)}function endTagInCell(e,t){const n=t.tagID;switch(n){case pF.TD:case pF.TH:e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=nL.IN_ROW);break;case pF.TABLE:case pF.TBODY:case pF.TFOOT:case pF.THEAD:case pF.TR:e.openElements.hasInTableScope(n)&&(e._closeTableCell(),endTagInRow(e,t));break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:break;default:endTagInBody(e,t)}}function startTagInSelect(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.OPTION:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e._insertElement(t,cF.HTML);break;case pF.OPTGROUP:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e.openElements.currentTagId===pF.OPTGROUP&&e.openElements.pop(),e._insertElement(t,cF.HTML);break;case pF.HR:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e.openElements.currentTagId===pF.OPTGROUP&&e.openElements.pop(),e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.INPUT:case pF.KEYGEN:case pF.TEXTAREA:case pF.SELECT:e.openElements.hasInSelectScope(pF.SELECT)&&(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode(),t.tagID!==pF.SELECT&&e._processStartTag(t));break;case pF.SCRIPT:case pF.TEMPLATE:startTagInHead(e,t)}}function endTagInSelect(e,t){switch(t.tagID){case pF.OPTGROUP:e.openElements.stackTop>0&&e.openElements.currentTagId===pF.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===pF.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===pF.OPTGROUP&&e.openElements.pop();break;case pF.OPTION:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop();break;case pF.SELECT:e.openElements.hasInSelectScope(pF.SELECT)&&(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode());break;case pF.TEMPLATE:templateEndTagInHead(e,t)}}function startTagInSelectInTable(e,t){const n=t.tagID;n===pF.CAPTION||n===pF.TABLE||n===pF.TBODY||n===pF.TFOOT||n===pF.THEAD||n===pF.TR||n===pF.TD||n===pF.TH?(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode(),e._processStartTag(t)):startTagInSelect(e,t)}function endTagInSelectInTable(e,t){const n=t.tagID;n===pF.CAPTION||n===pF.TABLE||n===pF.TBODY||n===pF.TFOOT||n===pF.THEAD||n===pF.TR||n===pF.TD||n===pF.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode(),e.onEndTag(t)):endTagInSelect(e,t)}function startTagInTemplate(e,t){switch(t.tagID){case pF.BASE:case pF.BASEFONT:case pF.BGSOUND:case pF.LINK:case pF.META:case pF.NOFRAMES:case pF.SCRIPT:case pF.STYLE:case pF.TEMPLATE:case pF.TITLE:startTagInHead(e,t);break;case pF.CAPTION:case pF.COLGROUP:case pF.TBODY:case pF.TFOOT:case pF.THEAD:e.tmplInsertionModeStack[0]=nL.IN_TABLE,e.insertionMode=nL.IN_TABLE,startTagInTable(e,t);break;case pF.COL:e.tmplInsertionModeStack[0]=nL.IN_COLUMN_GROUP,e.insertionMode=nL.IN_COLUMN_GROUP,startTagInColumnGroup(e,t);break;case pF.TR:e.tmplInsertionModeStack[0]=nL.IN_TABLE_BODY,e.insertionMode=nL.IN_TABLE_BODY,startTagInTableBody(e,t);break;case pF.TD:case pF.TH:e.tmplInsertionModeStack[0]=nL.IN_ROW,e.insertionMode=nL.IN_ROW,startTagInRow(e,t);break;default:e.tmplInsertionModeStack[0]=nL.IN_BODY,e.insertionMode=nL.IN_BODY,startTagInBody(e,t)}}function endTagInTemplate(e,t){t.tagID===pF.TEMPLATE&&templateEndTagInHead(e,t)}function eofInTemplate(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(pF.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):stopParsing(e,t)}function startTagAfterBody(e,t){t.tagID===pF.HTML?startTagInBody(e,t):tokenAfterBody(e,t)}function endTagAfterBody(e,t){var n;if(t.tagID===pF.HTML){if(e.fragmentContext||(e.insertionMode=nL.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===pF.HTML){e._setEndLocation(e.openElements.items[0],t);const r=e.openElements.items[1];r&&!(null===(n=e.treeAdapter.getNodeSourceCodeLocation(r))||void 0===n?void 0:n.endTag)&&e._setEndLocation(r,t)}}else tokenAfterBody(e,t)}function tokenAfterBody(e,t){e.insertionMode=nL.IN_BODY,modeInBody(e,t)}function startTagInFrameset(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.FRAMESET:e._insertElement(t,cF.HTML);break;case pF.FRAME:e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.NOFRAMES:startTagInHead(e,t)}}function endTagInFrameset(e,t){t.tagID!==pF.FRAMESET||e.openElements.isRootHtmlElementCurrent()||(e.openElements.pop(),e.fragmentContext||e.openElements.currentTagId===pF.FRAMESET||(e.insertionMode=nL.AFTER_FRAMESET))}function startTagAfterFrameset(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.NOFRAMES:startTagInHead(e,t)}}function endTagAfterFrameset(e,t){t.tagID===pF.HTML&&(e.insertionMode=nL.AFTER_AFTER_FRAMESET)}function startTagAfterAfterBody(e,t){t.tagID===pF.HTML?startTagInBody(e,t):tokenAfterAfterBody(e,t)}function tokenAfterAfterBody(e,t){e.insertionMode=nL.IN_BODY,modeInBody(e,t)}function startTagAfterAfterFrameset(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.NOFRAMES:startTagInHead(e,t)}}function nullCharacterInForeignContent(e,t){t.chars=zO,e._insertCharacters(t)}function characterInForeignContent(e,t){e._insertCharacters(t),e.framesetOk=!1}function popUntilHtmlOrIntegrationPoint(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==cF.HTML&&void 0!==e.openElements.currentTagId&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function startTagInForeignContent(e,t){if(causesExit(t))popUntilHtmlOrIntegrationPoint(e),e._startTagOutsideForeignContent(t);else{const n=e._getAdjustedCurrentElement(),r=e.treeAdapter.getNamespaceURI(n);r===cF.MATHML?adjustTokenMathMLAttrs(t):r===cF.SVG&&(adjustTokenSVGTagName(t),adjustTokenSVGAttrs(t)),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,r):e._insertElement(t,r),t.ackSelfClosing=!0}}function endTagInForeignContent(e,t){if(t.tagID===pF.P||t.tagID===pF.BR)return popUntilHtmlOrIntegrationPoint(e),void e._endTagOutsideForeignContent(t);for(let n=e.openElements.stackTop;n>0;n--){const r=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(r)===cF.HTML){e._endTagOutsideForeignContent(t);break}const s=e.treeAdapter.getTagName(r);if(s.toLowerCase()===t.tagName){t.tagName=s,e.openElements.shortenToLength(n);break}}}var cL=null==String.prototype.codePointAt?(e,t)=>55296==(64512&e.charCodeAt(t))?1024*(e.charCodeAt(t)-55296)+e.charCodeAt(t+1)-56320+65536:e.charCodeAt(t):(e,t)=>e.codePointAt(t),lL=new Set([uF.AREA,uF.BASE,uF.BASEFONT,uF.BGSOUND,uF.BR,uF.COL,uF.EMBED,uF.FRAME,uF.HR,uF.IMG,uF.INPUT,uF.KEYGEN,uF.LINK,uF.META,uF.PARAM,uF.SOURCE,uF.TRACK,uF.WBR]);function parse3(e,t){return oL.parse(e,t)}function annotateHtmlSource(e,t){const n=parse3(e,{sourceCodeLocationInfo:!0}),r=new Map,stampsFor=e=>Object.entries(t(e)).map(([e,t])=>{if(!/^[a-z][a-z0-9-]*$/.test(e))throw new Error(`Invalid HTML annotation name: ${e}`);return` ${e}="${escapeAttribute2(t)}"`}).join(""),s=impliedBodyInsertion(n);null!==s&&r.set(s,`<body${stampsFor(s)}>`);const visit2=t=>{if("tagName"in t){const n=t.sourceCodeLocation?.startTag?.startOffset;if(void 0!==n){const t=/^<[^\s/>]+/.exec(e.slice(n));t&&r.set(n+t[0].length,stampsFor(n))}"content"in t&&visit2(t.content)}if("childNodes"in t)for(const e of t.childNodes)visit2(e)};visit2(n);const i=[];let o=0;for(const[t,n]of[...r].sort(([e],[t])=>e-t))i.push(e.slice(o,t),n),o=t;return i.push(e.slice(o)),i.join("")}function impliedBodyInsertion(e){const t=e.childNodes.find(e=>"tagName"in e&&"html"===e.tagName);if(!t||!("childNodes"in t))return null;const n=t.childNodes.find(e=>"tagName"in e&&"body"===e.tagName);if(!n||n.sourceCodeLocation)return null;const r=t.childNodes.find(e=>"tagName"in e&&"head"===e.tagName),s=e.childNodes.find(e=>"#documentType"===e.nodeName);return Math.max(0,s?.sourceCodeLocation?.endOffset??0,t.sourceCodeLocation?.startTag?.endOffset??0,r?.sourceCodeLocation?.endOffset??0)}function escapeAttribute2(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;")}var dL=".tempo-html-paste",uL=[".html",".htm"];function hasHtmlStoryboardEntryExtension(e){const t=e.toLowerCase();return uL.some(e=>t.endsWith(e))}function annotateHtmlStoryboardRevision(e,t){const n=sourceVersionHash(e);return annotateHtmlSource(e,e=>({"data-tempo-filepath":t.filepath,"data-tempo-position":String(e),"data-tempo-modifiedts":String(Math.trunc(t.mtime)),"data-tempo-source-version":n}))}async function authorizeHtmlStoryboardResource(e){const t=await LO(e);if(!(await MO(t)).isFile()||!hasHtmlStoryboardEntryExtension(t))throw new Error("HTML storyboard source must be an existing .html or .htm file");const n=FO.dirname(t);return{filepath:t,authorization:{root:n,entryFile:FO.basename(n)===dL?t:null}}}var pL=new Set([...uL,".css",".js",".mjs",".cjs",".png",".jpg",".jpeg",".gif",".svg",".webp",".avif",".ico",".bmp",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".ogg",".wav",".webm"]);function isWithinRoot2(e,t){const n=FO.relative(e,t);return""===n||!n.startsWith(`..${FO.sep}`)&&".."!==n&&!FO.isAbsolute(n)}async function resolveHtmlStoryboardResource(e,t){if(/%2f|%5c/i.test(t))return{status:400};let n;try{n=decodeURIComponent(t).replace(/^[/\\]+/,"")}catch{return{status:400}}if(!n)return{status:400};if(!pL.has(FO.extname(n).toLowerCase()))return{status:403};const r=FO.resolve(e.root,n);if(!isWithinRoot2(e.root,r))return{status:403};let s;try{s=await LO(r)}catch{return{status:404}}if(!isWithinRoot2(e.root,s)||null!==e.entryFile&&s!==e.entryFile||!pL.has(FO.extname(s).toLowerCase()))return{status:403};try{if(!(await MO(s)).isFile())return{status:404}}catch{return{status:404}}return{status:200,filepath:s}}var hL={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".cjs":"text/javascript",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".bmp":"image/bmp",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".mp3":"audio/mpeg",".mp4":"video/mp4",".ogg":"audio/ogg",".wav":"audio/wav",".webm":"video/webm"};async function openHeadlessHtmlSource(e,t,n=createCaptureImageNormalizer()){const r=await authorizeHtmlStoryboardResource(t),s=await SO(r.filepath,"utf8"),i=annotateHtmlStoryboardRevision(s,{filepath:r.filepath,mtime:(await EO(r.filepath)).mtimeMs}),o=`https://${kO(24).toString("hex")}.tempo-html.invalid`,a=`${o}/${encodeURIComponent(AO.basename(r.filepath))}`,c=new Set,handler=async e=>{const t=e.request(),s=new URL(t.url());if(s.origin!==o)return"file:"===s.protocol||t.isNavigationRequest()?e.abort("blockedbyclient"):e.fallback();const a=await resolveHtmlStoryboardResource(r.authorization,s.pathname);if(200!==a.status)return c.add(`${s.pathname}: ${a.status}`),e.fulfill({status:a.status,body:""});try{const s=a.filepath===r.filepath?i:await SO(a.filepath),o="image"===t.resourceType()&&Buffer.isBuffer(s)?await n(s):s;await e.fulfill({status:200,contentType:o!==s?"image/png":hL[AO.extname(a.filepath).toLowerCase()],headers:{"cache-control":"no-store","content-security-policy":"sandbox allow-scripts allow-same-origin"},body:o})}catch(t){c.add(`${s.pathname}: ${String(t)}`),await e.abort().catch(()=>{})}};return await e.route("**/*",handler),{url:a,assertResources(){if(c.size)throw new Error(`HTML storyboard resources failed: ${[...c].join(", ")}`)},dispose:()=>e.unroute("**/*",handler)}}function astroStoryboardPath(e,t){return`/__tempo/astro/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function astroCaptureUrl(e,t){if("astro"!==t.source?.kind)throw new Error("Expected an Astro document component");return new URL(astroStoryboardPath(t.source.canvasPath,t.storyboardId).slice(1),e.replace(/\/?$/,"/")).href}async function settleAstroDocument(e,t,n){if("astro"!==t.source?.kind)throw new Error("Expected an Astro document component");const r=await e.locator('meta[name="tempo-astro-storyboard"]').getAttribute("content",{timeout:n}),s=r&&JSON.parse(r);if(!s||s.canvasPath!==t.source.canvasPath||s.storyboardId!==t.storyboardId||t.source.revision&&s.revision!==t.source.revision)throw new Error("Astro preview does not match the requested storyboard revision");await e.waitForFunction(mO,void 0,{timeout:n})}var mL="html, :modal, :popover-open, :fullscreen, ::backdrop { opacity: 0 !important; }",fL="__tempoCapturePaintHold";function buildPaintHoldInitScript(){return`(() => {\n if (window.top !== window) return;\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(${JSON.stringify(mL)});\n const adopted = () => document.adoptedStyleSheets.includes(sheet);\n let holding = false;\n // Looked up per call: application code may wrap the prototype's accessor\n // after this script ran, and its wrapper must still see every assignment.\n const native = () =>\n Object.getOwnPropertyDescriptor(Document.prototype, "adoptedStyleSheets");\n Object.defineProperty(document, "adoptedStyleSheets", {\n configurable: true,\n enumerable: true,\n get() {\n return native().get.call(this);\n },\n set(sheets) {\n const next = Array.from(sheets);\n native().set.call(\n this,\n holding && !next.includes(sheet) ? [...next, sheet] : next,\n );\n },\n });\n const hold = () => {\n holding = true;\n if (!adopted()) document.adoptedStyleSheets = document.adoptedStyleSheets;\n };\n hold();\n globalThis.${fL} = {\n hold,\n held: () =>\n adopted() &&\n getComputedStyle(document.documentElement).opacity === "0",\n release: () => {\n holding = false;\n document.adoptedStyleSheets = document.adoptedStyleSheets.filter(\n (other) => other !== sheet,\n );\n },\n };\n})();`}async function holdPaint(e){await e.evaluate(e=>{window[e]?.hold()},fL)}async function releasePaintHold(e){const t=await e.evaluate(async e=>{const t=window[e];return t?t.held()?(t.release(),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),"released"):"lost":"missing"},fL);if("released"!==t)throw new Error("missing"===t?"capture paint hold was never installed in this document":"the page removed the capture paint hold before it settled (document.adoptedStyleSheets was emptied in place, or the root's opacity is forced visible); its pixels would depend on load timing")}var gL='return (function documentVisualReadiness(doc, options) {\n return new Promise(function (resolve) {\n var view = doc.defaultView;\n var failures = [];\n var failedLinks = new WeakMap();\n var checks = new Set();\n var cleanups = new Set();\n var stopped = false;\n var timer;\n var observer;\n var remaining = Math.max(\n 0,\n Math.min(\n options.timeoutMs,\n options.resourceBudget\n ? options.resourceBudget.remainingMs\n : options.timeoutMs,\n ),\n );\n var timerAt;\n var queued = 0;\n var admittedSlice;\n var checksPending = false;\n var checksDirty = false;\n var revision = 0;\n var terminalResolve;\n var terminal = new Promise(function (done) {\n terminalResolve = done;\n });\n function failure(kind, url) {\n if (\n !failures.some(function (item) {\n return item.kind === kind && item.url === url;\n })\n )\n failures.push(url ? { kind: kind, url: url } : { kind: kind });\n }\n function finish(status) {\n if (stopped) return;\n if (status === "ready" && options.onReadyProof) options.onReadyProof();\n if (stopped) return;\n stopped = true;\n if (options.resourceBudget)\n options.resourceBudget.remainingMs = queued\n ? remaining\n : Math.max(\n 0,\n remaining - (timerAt === undefined ? 0 : Date.now() - timerAt),\n );\n clearTimeout(timer);\n if (observer) observer.disconnect();\n for (var cleanup of cleanups) cleanup();\n cleanups.clear();\n checks.clear();\n if (options.signal) options.signal.removeEventListener("abort", cancel);\n terminalResolve();\n resolve({ status: status, failures: failures });\n }\n function cancel() {\n finish("cancelled");\n }\n if (options.signal && options.signal.aborted) {\n cancel();\n return;\n }\n if (!view) {\n cancel();\n return;\n }\n if (options.signal)\n options.signal.addEventListener("abort", cancel, { once: true });\n function startTimer() {\n timerAt = Date.now();\n timer = setTimeout(function () {\n finish("timeout");\n }, remaining);\n }\n startTimer();\n async function work(callback) {\n if (!options.scheduleWork) return callback();\n if (stopped) return;\n if (queued++ === 0) {\n clearTimeout(timer);\n remaining = Math.max(0, remaining - (Date.now() - timerAt));\n }\n try {\n if (\n admittedSlice &&\n admittedSlice.canContinue &&\n admittedSlice.canContinue()\n )\n return callback(admittedSlice);\n return await Promise.race([\n terminal,\n options.scheduleWork(function (slice) {\n admittedSlice = slice;\n if (!stopped) return callback(slice);\n }, options.signal),\n ]);\n } finally {\n if (--queued === 0 && !stopped) startTimer();\n }\n }\n async function mapWork(items, callback) {\n var rows = [];\n var offset = 0;\n while (offset < items.length && !stopped) {\n await work(function (slice) {\n var limit = Math.min(offset + 32, items.length);\n do {\n var value = callback(items[offset++]);\n if (value !== undefined) rows.push(value);\n } while (offset < limit && (!slice || slice.hasTime()));\n });\n }\n return rows;\n }\n if (remaining <= 0) {\n finish("timeout");\n return;\n }\n function changed() {\n if (stopped) return;\n if (!options.scheduleWork) {\n for (var check of checks) check();\n return;\n }\n if (checksPending) {\n checksDirty = true;\n return;\n }\n checksPending = true;\n checksDirty = false;\n mapWork(Array.from(checks), function (check) {\n check();\n })\n .finally(function () {\n checksPending = false;\n if (checksDirty) changed();\n })\n .catch(function () {\n finish("cancelled");\n });\n }\n observer = new view.MutationObserver(function () {\n revision++;\n changed();\n });\n observer.observe(doc, { subtree: true, childList: true, attributes: true });\n // Opt-in admission may begin after a resource\'s terminal event. Preserve\n // its URL-scoped failure evidence while the initial inventory is queued.\n if (options.scheduleWork) {\n var captureError = function (event) {\n var link = event.target;\n if (\n link &&\n link.tagName === "LINK" &&\n link.relList.contains("stylesheet") &&\n applicable(link)\n ) {\n failedLinks.set(link, link.href);\n failure("stylesheet", link.href);\n changed();\n }\n };\n doc.addEventListener("error", captureError, true);\n cleanups.add(function () {\n doc.removeEventListener("error", captureError, true);\n });\n }\n\n function applicable(link) {\n return (\n link.isConnected &&\n !link.disabled &&\n (!link.media || !view.matchMedia || view.matchMedia(link.media).matches)\n );\n }\n function links() {\n return Array.from(doc.querySelectorAll(\'link[rel~="stylesheet"]\')).filter(\n applicable,\n );\n }\n function visibleImage(img) {\n if (!img.isConnected) return false;\n var rect = img.getBoundingClientRect();\n var style = view.getComputedStyle(img);\n return (\n rect.width > 0 &&\n rect.height > 0 &&\n rect.bottom > 0 &&\n rect.right > 0 &&\n rect.top < view.innerHeight &&\n rect.left < view.innerWidth &&\n style.visibility !== "hidden" &&\n style.visibility !== "collapse"\n );\n }\n function images() {\n return Array.from(doc.querySelectorAll("img"))\n .filter(visibleImage)\n .map(function (img) {\n return [img, img.currentSrc, img.src, img.srcset];\n });\n }\n async function scheduledImages() {\n var candidates,\n selected = [],\n offset = 0;\n do {\n await work(function (slice) {\n if (!candidates) candidates = Array.from(doc.querySelectorAll("img"));\n var limit = Math.min(offset + 32, candidates.length);\n while (offset < limit) {\n var img = candidates[offset++];\n if (visibleImage(img))\n selected.push([img, img.currentSrc, img.src, img.srcset]);\n if (slice && !slice.hasTime()) break;\n }\n });\n } while (!stopped && candidates && offset < candidates.length);\n return selected;\n }\n function decodeImage(img) {\n if (!img.isConnected || !visibleImage(img)) return {};\n if (!img.naturalWidth) {\n failure("image", img.currentSrc || img.src);\n return {};\n }\n // A holder keeps a resource decode promise outside CPU admission.\n return {\n decode:\n img.decode &&\n img.decode().catch(function () {\n failure("image", img.currentSrc || img.src);\n }),\n };\n }\n function waitElement(element, ready, kind, url) {\n if (ready()) return Promise.resolve();\n return new Promise(function (done) {\n function requestCheck() {\n if (options.scheduleWork) changed();\n else check();\n }\n function cleanup() {\n element.removeEventListener("load", requestCheck);\n element.removeEventListener("error", error);\n checks.delete(check);\n cleanups.delete(cleanup);\n }\n function check() {\n if (ready()) {\n cleanup();\n done();\n }\n }\n function error() {\n failure(kind, url);\n if (kind === "stylesheet") failedLinks.set(element, url);\n cleanup();\n done();\n }\n cleanups.add(cleanup);\n checks.add(check);\n element.addEventListener("load", requestCheck);\n element.addEventListener("error", error);\n check();\n });\n }\n function inventory(includeImages) {\n return {\n links: links().map(function (link) {\n // Resource evidence can change during a font/image await without\n // changing this node\'s URL or media. Revalidate the same readiness\n // facts, not CSSStyleSheet object identities or a content hash.\n return [\n link,\n link.href,\n link.media,\n !!link.sheet,\n link.getAttribute("data-tempo-stylesheet-pending") === link.href,\n link.getAttribute("data-tempo-stylesheet-error") === link.href,\n ];\n }),\n images: includeImages ? images() : [],\n styles: Array.from(doc.querySelectorAll("style")).map(function (style) {\n return [style, style.textContent];\n }),\n };\n }\n async function scheduledInventory(includeImages) {\n var candidates,\n offset = 0;\n var result = { revision: revision, links: [], images: [], styles: [] };\n // Small inventories finish in one admission. Large ones retain the\n // same 32-node/time bound, without paying a task per resource category.\n do {\n await work(function (slice) {\n if (!candidates)\n candidates = Array.from(\n doc.querySelectorAll(\n includeImages\n ? \'link[rel~="stylesheet"],img,style\'\n : \'link[rel~="stylesheet"],style\',\n ),\n );\n var limit = Math.min(offset + 32, candidates.length);\n while (offset < limit) {\n var node = candidates[offset++];\n if (node.localName === "link" && applicable(node)) {\n result.links.push([\n node,\n node.href,\n node.media,\n !!node.sheet,\n node.getAttribute("data-tempo-stylesheet-pending") ===\n node.href,\n node.getAttribute("data-tempo-stylesheet-error") === node.href,\n ]);\n } else if (node.localName === "img" && visibleImage(node)) {\n result.images.push([\n node,\n node.currentSrc,\n node.src,\n node.srcset,\n ]);\n } else if (node.localName === "style") {\n result.styles.push([node, node.textContent]);\n }\n if (slice && !slice.hasTime()) break;\n }\n });\n } while (!stopped && candidates && offset < candidates.length);\n return result;\n }\n function same(a, b) {\n return ["links", "images", "styles"].every(function (key) {\n return (\n a[key].length === b[key].length &&\n a[key].every(function (row, i) {\n return row.every(function (value, j) {\n return value === b[key][i][j];\n });\n })\n );\n });\n }\n async function run() {\n while (!stopped) {\n var before = options.scheduleWork\n ? await scheduledInventory(false)\n : inventory(false);\n if (stopped) return;\n await Promise.race([\n terminal,\n Promise.all(\n before.links\n .map(function (row) {\n return row[0];\n })\n .map(function (link) {\n if (\n (!link.sheet &&\n (options.failedStylesheetUrls || []).includes(link.href)) ||\n link.getAttribute("data-tempo-stylesheet-error") === link.href\n ) {\n failedLinks.set(link, link.href);\n failure("stylesheet", link.href);\n }\n return waitElement(\n link,\n function () {\n return (\n !applicable(link) ||\n (link.getAttribute("data-tempo-stylesheet-pending") !==\n link.href &&\n (!!link.sheet || failedLinks.get(link) === link.href))\n );\n },\n "stylesheet",\n link.href,\n );\n }),\n ),\n ]);\n if (stopped) return;\n // Force stylesheet application/layout BEFORE reading the current font\n // promise. A previously fulfilled promise cannot certify newly used fonts.\n var readFontPromise = function () {\n if (doc.documentElement) doc.documentElement.getBoundingClientRect();\n // Read the CURRENT promise in the same admitted layout callback.\n return { promise: doc.fonts && doc.fonts.ready };\n };\n var currentFonts = options.scheduleWork\n ? await work(readFontPromise)\n : readFontPromise();\n if (stopped) return;\n var fontPromise = currentFonts.promise;\n var fontRejected = false;\n await Promise.race([\n terminal,\n Promise.resolve(fontPromise).catch(function () {\n fontRejected = true;\n failure("font");\n }),\n ]);\n if (stopped) return;\n // Fonts can change which images are visible. Capture the image evidence\n // only after their layout settles, before awaiting any selected decode.\n var selected = options.scheduleWork\n ? await scheduledImages()\n : images();\n if (stopped) return;\n before.images = selected;\n if (options.scheduleWork) {\n var pendingImages = [],\n pendingLoads = [];\n var imageWaits = await mapWork(selected, function (row) {\n var img = row[0];\n if (img.loading === "lazy") img.loading = "eager";\n // Warm images need no load-event continuation. Prepare their\n // decodes in this bounded batch rather than one new task per image.\n if (img.complete) {\n var proof = decodeImage(img);\n return Promise.race([terminal, Promise.resolve(proof.decode)]);\n }\n pendingImages.push(img);\n pendingLoads.push(\n Promise.race([\n terminal,\n waitElement(\n img,\n function () {\n return (\n !img.isConnected || !visibleImage(img) || img.complete\n );\n },\n "image",\n img.currentSrc || img.src,\n ),\n ]),\n );\n });\n await Promise.race([terminal, Promise.all(pendingLoads)]);\n if (stopped) return;\n // Load events often arrive together from the browser cache. Decode\n // their now-ready images in bounded batches, rather than granting\n // each event its own renderer task. Warm decodes above stay in flight.\n var loadedDecodes = await mapWork(pendingImages, function (img) {\n var proof = decodeImage(img);\n return Promise.race([terminal, Promise.resolve(proof.decode)]);\n });\n await Promise.race([\n terminal,\n Promise.all(imageWaits.concat(loadedDecodes)),\n ]);\n } else {\n await Promise.race([\n terminal,\n Promise.all(\n selected.map(async function (row) {\n var img = row[0];\n if (img.loading === "lazy") img.loading = "eager";\n await Promise.race([\n terminal,\n waitElement(\n img,\n function () {\n return (\n !img.isConnected || !visibleImage(img) || img.complete\n );\n },\n "image",\n img.currentSrc || img.src,\n ),\n ]);\n if (stopped || !img.isConnected || !visibleImage(img)) return;\n if (!img.naturalWidth) {\n failure("image", img.currentSrc || img.src);\n return;\n }\n if (img.decode)\n await img.decode().catch(function () {\n failure("image", img.currentSrc || img.src);\n });\n }),\n ),\n ]);\n }\n if (stopped) return;\n if (doc.fonts)\n doc.fonts.forEach(function (face) {\n if (face.status === "error") failure("font", face.family);\n });\n var after = options.scheduleWork\n ? await scheduledInventory(true)\n : inventory(true);\n if (stopped) return;\n // A scheduled inventory can span multiple tasks. A mutation during\n // its geometry reads cannot certify a mixed document observation.\n if (options.scheduleWork && observer.takeRecords().length) revision++;\n if (\n (!options.scheduleWork ||\n options.requireStableDom === false ||\n (before.revision === after.revision &&\n after.revision === revision)) &&\n same(before, after) &&\n (!doc.fonts ||\n fontRejected ||\n (doc.fonts.status !== "loading" && doc.fonts.ready === fontPromise))\n ) {\n finish("ready");\n return;\n }\n // Let resource events and the deadline run if this document keeps\n // discovering assets; never monopolize the microtask queue.\n await Promise.race([\n terminal,\n new Promise(function (done) {\n var retry = setTimeout(function () {\n cleanups.delete(cleanup);\n done();\n }, 0);\n function cleanup() {\n clearTimeout(retry);\n done();\n }\n cleanups.add(cleanup);\n }),\n ]);\n }\n }\n // Unexpected browser/document loss is not a successful fallback rendering.\n run().catch(function () {\n finish("cancelled");\n });\n });\n})(doc, options);';function buildVisualReadyWaitScript(e,t=[]){return`(function(doc, options) {${gL}})(document, ${JSON.stringify({timeoutMs:e,failedStylesheetUrls:t})})`}function requireVisualReadiness(e,t){if("ready"!==e?.status)throw new Error(`[frame-pool-readiness:${e?.status??"invalid"}] Document assets did not settle`);if(!t)throw new Error("[frame-pool-readiness:timeout] Native asset requests did not settle")}function extractStoryboardDomInPage(e){const readAttributes=e=>{const t={};for(const n of Array.from(e.attributes))/^on/i.test(n.name)||(t[n.name]=n.value);return t},t=document.querySelector(e);if(!t)throw new Error(`storyboard element not found for selector ${e}`);const n=document.head.cloneNode(!0),r=t.cloneNode(!0),s=[t,...Array.from(t.querySelectorAll("*"))],i=[r,...Array.from(r.querySelectorAll("*"))],o=new Map;s.forEach((e,t)=>o.set(e,i[t]));const a=Array.from(document.head.querySelectorAll("*")),c=Array.from(n.querySelectorAll("*"));a.forEach((e,t)=>o.set(e,c[t]));const l=Array.from(document.querySelectorAll("style,link[rel~='stylesheet']"));l.forEach(e=>{const t=o.get(e)??e.cloneNode(!0);o.has(e)||n.appendChild(t);const r=e.sheet;if(r)if(r.disabled)t.parentNode?.removeChild(t);else try{const n=document.createElement("style");for(const t of Array.from(e.attributes))["href","rel","integrity","crossorigin"].includes(t.name)||n.setAttribute(t.name,t.value);let s=Array.from(r.cssRules).map(e=>e.cssText).join("\n");const i=r.href??document.baseURI;s=s.replace(/url\(\s*(['"]?)([^'")]+?)\1\s*\)/gi,(e,t,n)=>{try{return`url("${new URL(n,i).href}")`}catch{return e}}),n.textContent=s,t.parentNode?.replaceChild(n,t)}catch{}});for(const e of Array.from(document.adoptedStyleSheets??[])){if(e.disabled)continue;const t=document.createElement("style");t.textContent=Array.from(e.cssRules).map(e=>e.cssText).join("\n"),n.appendChild(t)}s.forEach((e,t)=>{const n=i[t];e instanceof HTMLInputElement?(n.setAttribute("value",e.value),n.toggleAttribute("checked",e.checked)):e instanceof HTMLTextAreaElement?n.textContent=e.value:e instanceof HTMLOptionElement&&n.toggleAttribute("selected",e.selected)});for(const e of[n,r]){for(const t of Array.from(e.querySelectorAll("script")))t.remove();for(const t of[e,...Array.from(e.querySelectorAll("*"))])for(const e of Array.from(t.attributes))(/^on/i.test(e.name)||/^(href|src|action|formaction)$/i.test(e.name)&&/^\s*javascript:/i.test(e.value))&&t.removeAttribute(e.name)}return{headHtml:n.innerHTML,htmlAttributes:readAttributes(document.documentElement),bodyAttributes:readAttributes(document.body),elementHtml:r.outerHTML}}function assessPageStylesInPage(e){let t=0,n=0;for(const e of Array.from(document.styleSheets))try{t+=e.cssRules.length}catch{n+=1}let r=0;for(const e of Array.from(document.querySelectorAll("style")))r+=(e.textContent??"").length;const s=document.querySelector(e)??document.body;return{authorRuleCount:t,unreadableSheetCount:n,styleTextBytes:r,classElementCount:s.querySelectorAll("[class]").length,inlineStyledElementCount:s.querySelectorAll("[style]").length}}function watchRenderErrorsInPage(e){const t=document.querySelector(e.selector),n=[],record=()=>{if(t)for(const r of Array.from(t.querySelectorAll(e.errorSelector))){const t=r.getAttribute(e.messageAttribute)||"unknown error";n.includes(t)||n.push(t)}};record();const r=new MutationObserver(record);t&&r.observe(t,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[e.messageAttribute]}),window.__tempoCaptureRenderErrors=()=>(r.takeRecords(),r.disconnect(),record(),n)}function readRenderErrorsInPage(){const e=window,t=e.__tempoCaptureRenderErrors;return delete e.__tempoCaptureRenderErrors,t?t():[]}async function inlinePortableHtmlInPage(e){const t=[],warn=e=>{t.push(e)},cssUrlMatcher=()=>/url\(\s*(['"]?)([^'")]+?)\1\s*\)/gi,isPubliclyFetchableUrl=e=>{if("http:"!==e.protocol&&"https:"!==e.protocol)return!1;const t=e.hostname;return!t.endsWith(".tempo-html.invalid")&&("localhost"!==t&&!t.endsWith(".localhost")&&("::1"!==t&&"[::1]"!==t&&"0.0.0.0"!==t&&(!/^127\./.test(t)&&!(/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t)))))},resolveAssetUrl=(e,t)=>{const n=e?.trim();if(!n||n.startsWith("data:")||n.startsWith("#"))return null;try{const e=new URL(n,t);return isPubliclyFetchableUrl(e)?null:e.href}catch{return null}},bytesToBase64=e=>{let t="";const n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)},blobToDataUrl=async(e,t)=>{const n=new Uint8Array(await e.arrayBuffer()),r=e.type||t||"application/octet-stream";return`data:${r};base64,${bytesToBase64(n)}`},inlineCssUrls=async(e,t)=>{const n=new Map;for(const r of e.matchAll(cssUrlMatcher())){const e=r[2].trim(),s=resolveAssetUrl(e,t);s&&n.set(e,s)}if(0===n.size)return e;const r=new Map;return await Promise.all(Array.from(n,async([e,t])=>{try{const n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.blob(),i=s.type||n.headers.get("content-type")||"";r.set(e,await blobToDataUrl(s,i))}catch(e){warn(`failed to inline CSS asset ${t}: ${String(e)}`)}})),0===r.size?e:e.replace(cssUrlMatcher(),(e,t,n)=>{const s=r.get(n.trim());return s?`url("${s}")`:e})},n=(new DOMParser).parseFromString(e.html,"text/html"),r=n.querySelector("base[href]")?.getAttribute("href")??e.baseUrl;await Promise.all(Array.from(n.querySelectorAll("style")).map(async e=>{const t=e.textContent??"";t.includes("url(")&&(e.textContent=await inlineCssUrls(t,r))})),await Promise.all(Array.from(n.querySelectorAll('[style*="url("]')).map(async e=>{const t=e.getAttribute("style");t&&e.setAttribute("style",await inlineCssUrls(t,r))})),await Promise.all(Array.from(n.querySelectorAll('link[rel~="stylesheet"][href]')).map(async e=>{const t=resolveAssetUrl(e.getAttribute("href"),r);if(t)try{const r=await fetch(t);if(!r.ok)throw new Error(`HTTP ${r.status}`);const s=await inlineCssUrls(await r.text(),t),i=n.createElement("style");i.setAttribute("data-tempo-inlined-stylesheet","true");const o=e.getAttribute("media");o&&i.setAttribute("media",o),i.textContent=s,e.replaceWith(i)}catch(e){warn(`failed to inline stylesheet ${t}: ${String(e)}`)}})),await Promise.all(Array.from(n.querySelectorAll("img[src]")).map(async e=>{const t=resolveAssetUrl(e.getAttribute("src"),r);if(t)try{const n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);const r=await n.blob(),s=r.type||n.headers.get("content-type")||"";if(!s.toLowerCase().startsWith("image/"))return;e.setAttribute("src",await blobToDataUrl(r,s)),e.removeAttribute("srcset"),e.setAttribute("loading","eager"),e.setAttribute("decoding","sync")}catch(e){warn(`failed to inline image ${t}: ${String(e)}`)}}));for(const e of Array.from(n.querySelectorAll("script")))e.remove();const s=n.querySelector("base[href]");return s&&resolveAssetUrl(s.getAttribute("href"),e.baseUrl)&&s.remove(),{html:`<!DOCTYPE html>${n.documentElement.outerHTML}`,warnings:t}}function installRenderProfileInPage(){const e=window;performance.setResourceTimingBufferSize(1e4);const readTargetSelector=()=>{const e=new URLSearchParams(window.location.search),t=e.get("canvasPath")?.trim()??e.get("pageFile")?.trim(),n=e.get("storyboardId")?.trim()??e.get("exportName")?.trim();if(!t||!n)return"";const r=`canvas:${encodeURIComponent(t)}#storyboard:${encodeURIComponent(n)}`;return`[data-tempo-storyboard-render-id=${JSON.stringify(r)}]`},t={startedAtMs:performance.now(),fullNavigation:!0,targetSelector:readTargetSelector(),targetAttachedMs:null,reactInjectedMs:null,reactCommits:[],longTaskCount:0,longTaskDurationMs:0,begin(e){this.startedAtMs=performance.now(),this.fullNavigation=!1,this.targetSelector=e,this.targetAttachedMs=null,this.reactInjectedMs=null,this.reactCommits=[],this.longTaskCount=0,this.longTaskDurationMs=0}};e.__tempoCaptureRenderProfile=t;const markTargetAttached=()=>{null===t.targetAttachedMs&&t.targetSelector&&document.querySelector(t.targetSelector)&&(t.targetAttachedMs=performance.now()-t.startedAtMs)};markTargetAttached(),new MutationObserver(markTargetAttached).observe(document,{childList:!0,subtree:!0});try{new PerformanceObserver(e=>{for(const n of e.getEntries())t.longTaskCount+=1,t.longTaskDurationMs+=n.duration}).observe({type:"longtask",buffered:!0})}catch{}if(e.__REACT_DEVTOOLS_GLOBAL_HOOK__)return;let n=0;const r=new Map;e.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,renderers:r,inject:e=>(t.reactInjectedMs??=performance.now()-t.startedAtMs,n+=1,r.set(n,e),n),onCommitFiberRoot(e,n){const r=n.current;t.reactCommits.push({atMs:performance.now()-t.startedAtMs,actualDurationMs:"number"==typeof r?.actualDuration?r.actualDuration:0})},onCommitFiberUnmount(){},checkDCE(){},onScheduleFiberRoot(){}}}function readRenderProfileInPage(e){const t=window,n=t.__tempoCaptureRenderProfile,r=n?.startedAtMs??0,s=performance.getEntriesByType("navigation")[0],i=performance.getEntriesByType("resource").filter(e=>e.startTime>=r),o=`/${e.replace(/^tempo\//,"")}`,a=i.filter(e=>{const t=new URL(e.name).pathname;return t.includes("/designs/")&&t.includes(".canvas")}),c=a.find(e=>new URL(e.name).pathname===o),l=i.filter(e=>"script"===e.initiatorType),d=n?.reactCommits??[];return{domContentLoadedMs:n?.fullNavigation?s?.domContentLoadedEventEnd??0:0,targetAttachedMs:n?.targetAttachedMs??performance.now()-r,targetModuleLoadedMs:c?c.responseEnd-r:0,lastCanvasModuleLoadedMs:Math.max(0,...a.map(e=>e.responseEnd-r)),lastScriptLoadedMs:Math.max(0,...l.map(e=>e.responseEnd-r)),reactInjectedMs:n?.reactInjectedMs??0,reactFirstCommitMs:d[0]?.atMs??0,reactLastCommitMs:d[d.length-1]?.atMs??0,reactCommitWorkMs:d.reduce((e,t)=>e+t.actualDurationMs,0),reactCommitCount:d.length,longTaskCount:n?.longTaskCount??0,longTaskDurationMs:n?.longTaskDurationMs??0,requestCount:i.length,scriptRequestCount:l.length,canvasModuleRequestCount:a.length,unrelatedCanvasModuleRequestCount:a.filter(e=>new URL(e.name).pathname!==o).length}}import{parseSync as yL}from"oxc-parser";var bL=`(?:${['"',"'","`"].map(e=>String.raw`${e}(?:[^${e}\\]|\\.)*${e}`).join("|")})`,vL=new RegExp(String.raw`\bcanvasPath:\s*(${bL})\s*,\s*load:\s*\(\)\s*=>\s*import\(\s*(${bL})\s*\)`,"g");function escapeForRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var wL={n:"\n",t:"\t",r:"\r",b:"\b",f:"\f",v:"\v",0:"\0","\n":""};function readLiteral(e){const t=e.trim(),n=t[0];if(t.length<2||t[t.length-1]!==n)return;if('"'!==n&&"'"!==n&&"`"!==n)return;const r=t.slice(1,-1);for(let e=0;e<r.length;e+=1)if("\\"===r[e])e+=1;else{if(r[e]===n)return;if("`"===n&&r.startsWith("${",e))return}return r.replace(/\\(u\{[\da-fA-F]+\}|u[\da-fA-F]{4}|x[\da-fA-F]{2}|[\s\S])/g,(e,t)=>t.length>1?String.fromCodePoint(Number.parseInt(t.replace(/[ux{}]/g,""),16)):wL[t]??t)}function readStyleId(e,t){const n=e.lastIndexOf(`${t}(`);if(n<0)return;const r=new RegExp(String.raw`^\s*(${bL}|[A-Za-z_$][\w$]*)\s*,`).exec(e.slice(n+t.length+1))?.[1];if(!r)return;if(/^["'`]/.test(r))return readLiteral(r);const s=new RegExp(String.raw`\b(?:const|let|var)\s+${escapeForRegExp(r)}\s*=\s*(${bL})`).exec(e)?.[1];return s?readLiteral(s):void 0}function readServedModule(e){let t;try{t=yL("module.js",e,{lang:"js",sourceType:"module"})}catch{return null}if(t.errors.length>0)return null;const{staticImports:n,staticExports:r,dynamicImports:s}=t.module,i=[...n.map(e=>({start:e.start,request:e.moduleRequest.value})),...r.flatMap(e=>{const t=e.entries.find(e=>e.moduleRequest)?.moduleRequest?.value;return void 0===t?[]:[{start:e.start,request:t}]})].sort((e,t)=>e.start-t.start),o=[];let a=0;for(const{moduleRequest:t}of s){const n=readLiteral(e.slice(t.start,t.end));void 0===n?a+=1:o.push(n)}const c=n.flatMap(e=>e.entries).find(e=>"updateStyle"===e.importName.name)?.localName.value,l=c?readStyleId(e,c):void 0,d=[];for(const t of e.matchAll(vL)){const e=readLiteral(t[1]),n=readLiteral(t[2]);void 0!==e&&void 0!==n&&d.push({canvasPath:e,request:n})}return{staticRequests:i.map(e=>e.request),dynamicRequests:o,computedImports:a,...void 0===l?{}:{styleId:l},canvasLoaders:d}}var fetchServedModule=async e=>{let t;try{t=await fetch(e,{headers:{accept:"*/*"},signal:AbortSignal.timeout(3e4)})}catch(e){return{status:"failed",reason:e instanceof Error?e.message:String(e)}}try{return 404===t.status?{status:"missing"}:t.ok?/(?:java|ecma)script/i.test(t.headers.get("content-type")??"")?{status:"ok",source:await t.text()}:{status:"not-a-module"}:{status:"failed",reason:`HTTP ${t.status}`}}catch(e){return{status:"failed",reason:e instanceof Error?e.message:String(e)}}finally{t.bodyUsed||await(t.body?.cancel().catch(()=>{}))}};function resolveModuleRequest(e,t){if(!/^(?:\.{0,2}\/|[A-Za-z][A-Za-z\d+.-]*:)/.test(e))return null;let n,r;try{r=new URL(t),n=new URL(e,r)}catch{return null}return"http:"!==n.protocol&&"https:"!==n.protocol||n.origin!==r.origin?null:(n.hash="",n.href)}function insertsNothing(e){const{searchParams:t}=new URL(e);return["raw","url","inline","worker","sharedworker"].some(e=>t.has(e))}function computesOnlyItsOwnTargets(e){const{pathname:t}=new URL(e);return/(?:^|\/)node_modules\//.test(t)||/(?:^|\/)@(?:vite|react-refresh|id|tempo)(?:\/|$)/.test(t)}var _L=5e4;function createModuleGraph(e=fetchServedModule,t={}){const n=Math.max(1,t.concurrency??24),r=t.moduleLimit??_L,s=new Map,i=new Map;let o=0;const a=[],limited=async e=>{o>=n?await new Promise(e=>a.push(e)):o+=1;try{return await e()}finally{const e=a.shift();e?e():o-=1}},toNode=(e,t)=>{const n=readServedModule(t);if(!n)return{kind:"unknown",reason:"it does not parse"};const resolve6=t=>t.flatMap(t=>resolveModuleRequest(t,e)??[]);return{kind:"module",module:n,statics:resolve6(n.staticRequests),dynamics:resolve6(n.dynamicRequests)}},remember=(e,t)=>(s.set(e,t),t.then(t=>i.set(e,t)),t),read2=t=>{const n=s.get(t);if(n)return n;if(insertsNothing(t))return remember(t,Promise.resolve({kind:"leaf"}));if(s.size>=r){const e={kind:"unknown",reason:`more than ${r} modules`};return i.set(t,e),Promise.resolve(e)}return remember(t,limited(async()=>{const n=await e(t).catch(e=>({status:"failed",reason:e instanceof Error?e.message:String(e)}));return"failed"===n.status?{kind:"unknown",reason:n.reason}:"ok"!==n.status?{kind:"leaf"}:toNode(t,n.source)}))},reach=async(e,t,n)=>{const r=new Set;let s=[...e];for(;s.length>0;){const e=s.filter(e=>!r.has(e)&&!t.has(e));for(const t of e)r.add(t);const i=await Promise.all(e.map(read2));for(const[t,r]of i.entries())n?.(e[t],r);s=[...new Set(i.flatMap(e=>"module"===e.kind?[...e.statics,...e.dynamics]:[]))]}},evaluationOrder=(e,t,n)=>{const r=[];for(const s of e){const e=[],enter=r=>{n.has(r)||t.has(r)||(n.add(r),e.push({url:r,next:0}))};for(enter(s);e.length>0;){const t=e[e.length-1],n=i.get(t.url),s="module"===n?.kind?n.statics:[];t.next<s.length?(t.next+=1,enter(s[t.next-1])):(e.pop(),r.push(t.url))}}return r};return{define(e,t){const n=toNode(e,t);s.set(e,Promise.resolve(n)),i.set(e,n)},async canvasLoaders(e){const t=new Map,n=new Set;return await reach(e,n,(e,r)=>{if("module"===r.kind)for(const{canvasPath:s,request:i}of r.module.canvasLoaders){const r=resolveModuleRequest(i,e);r&&(t.set(s,r),n.add(r))}}),t},async styles(e,t={}){const n=t.stopAt??new Set;await reach(e,n);const r=new Set,s=[],o=[],a=new Set,c=new Set,visit2=(e,s)=>{const o=[];for(const l of evaluationOrder(e,n,c)){const e=i.get(l);if("leaf"===e?.kind)continue;if("module"!==e?.kind){r.add(`${l} could not be read: ${e?.reason??"not asked"}`);continue}const{module:n}=e;void 0===n.styleId||a.has(n.styleId)||(a.add(n.styleId),s.push(n.styleId)),t.computedImportsAreGaps&&n.computedImports>0&&!computesOnlyItsOwnTargets(l)&&r.add(`${l} computes the target of an import()`),o.push(...e.dynamics)}return o};let l=visit2(e,s);for(;l.length>0;)l=visit2(l,o);return{evaluated:s,deferred:o,gaps:[...r]}}}}var xL={document:"reuse",disable:[],order:[]};function canvasKey(e){return e.trim().replace(/\\/g,"/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function createStyleIsolation(e={}){const summarize2=e=>e.length>1?`${e[0]} (and ${e.length-1} more)`:e[0],startReading=()=>({graph:createModuleGraph(e.fetchModule),canvases:new Map});let t=startReading();const n=new Set,readHost=async({graph:e},t)=>{if(t.importMap)return{readable:!1,reason:"the host document has an import map"};const n=[];t.scripts.forEach((r,s)=>{if("src"in r){const e=resolveModuleRequest(r.src,t.documentUrl);return void(e&&n.push(e))}const i=new URL(t.documentUrl);i.hash=`tempo-inline-module-${s}`,e.define(i.href,r.text),n.push(i.href)});const r=await e.canvasLoaders(n),s=await e.styles(n,{stopAt:new Set(r.values())});return s.gaps.length>0?{readable:!1,reason:summarize2(s.gaps)}:{readable:!0,styles:new Set([...s.evaluated,...s.deferred]),canvases:new Map([...r].map(([e,t])=>[canvasKey(e),t]))}},hostOf=(e,t)=>(e.host||(e.host=readHost(e,t)),e.host),readCanvas=async({graph:e},t,n)=>{const r=n.canvases.get(canvasKey(t));if(!r)return{listed:!1};const s=await e.styles([r],{computedImportsAreGaps:!0});return{listed:!0,url:r,closure:s,all:new Set([...s.evaluated,...s.deferred])}};return{async plan({read:e,rendered:r,next:s}){const i=[...new Set(r)].filter(e=>canvasKey(e)!==canvasKey(s));if(0===i.length)return xL;const o=await e().catch(()=>{});if(!o||0===o.styles.length)return xL;let a=t,c=await hostOf(a,o);if(c.readable&&c.canvases.size>0&&!c.canvases.has(canvasKey(s))&&!n.has(canvasKey(s))&&(n.add(canvasKey(s)),t===a&&(t=startReading()),a=t,c=await hostOf(a,o)),!c.readable)return{document:"new",reason:`the host's modules could not be read: ${c.reason}`};const l=c,d=o.styles.filter(e=>!l.styles.has(e));if(0===d.length)return xL;const stylesOf=e=>{const t=canvasKey(e);let n=a.canvases.get(t);return n||(n=readCanvas(a,e,l),a.canvases.set(t,n)),n},u=await stylesOf(s);if(!u.listed)return{document:"new",reason:"the host wrapper does not list the canvas"};if(u.closure.gaps.length>0)return{document:"new",reason:`what the canvas imports is not fully known: ${summarize2(u.closure.gaps)}`};const p=new Set(u.closure.evaluated),m=new Set(u.closure.deferred),f=new Set;for(const e of await Promise.all(i.map(stylesOf)))if(e.listed)for(const t of e.all)f.add(t);const g=[];for(const e of d)if(!p.has(e)){if(m.has(e))return{document:"new",reason:`the document already holds ${e}, which the canvas loads only on demand`};if(!f.has(e))return{document:"new",reason:`the document holds ${e}, which no canvas it rendered is known to import`};g.push(e)}return{document:"reuse",preload:u.url,disable:g,order:u.closure.evaluated.filter(e=>!l.styles.has(e))}},forget(){t=startReading(),n.clear()}}}function installCaptureStylesInPage(){const viteStyles=()=>Array.from(document.querySelectorAll("style[data-vite-dev-id]")),idOf=e=>e.getAttribute("data-vite-dev-id")??"",e={read:()=>({documentUrl:document.baseURI,importMap:null!==document.querySelector('script[type="importmap"]'),scripts:Array.from(document.querySelectorAll('script[type="module"]')).map(e=>e.src?{src:e.src}:{text:e.textContent??""}),styles:viteStyles().map(idOf)}),async arrange(e){const t=new Map(e.map((e,t)=>[e,t])),n=viteStyles().filter(e=>t.has(idOf(e))),r=[...n].sort((e,n)=>t.get(idOf(e))-t.get(idOf(n)));if(r.every((e,t)=>n[t]===e))return{reordered:!1};const s=r.map(e=>new Promise(t=>{e.addEventListener("load",()=>t(),{once:!0}),e.addEventListener("error",()=>t(),{once:!0})})),i=document.createComment("");n[0].before(i);for(const e of r)i.before(e);return i.remove(),await Promise.all(s),{reordered:!0}},toggle(e){const t=new Set(e);let n=0;for(const e of viteStyles()){const r=t.has(idOf(e));r&&(n+=1),e.disabled!==r&&(e.disabled=r)}return{disabled:n}}};window.__tempoCaptureStyles=e}function buildCanvasPreloadScript(e,t){return`(async (url, selector) => {\n window.__tempoResetCaptureDeterminism?.();\n window.__tempoCaptureRenderProfile?.begin(selector);\n try {\n await import(url);\n } catch {}\n})(${JSON.stringify(e)}, ${JSON.stringify(t)})`}function storyboardRenderId(e,t){return buildCanvasStoryboardRenderId(e,t)}function buildDirectRenderUrl2(e,t){return buildDirectRenderUrl(e,{canvasPath:t.hostCanvasPath,storyboardId:t.storyboardId,width:t.width,height:t.height})}function sha256Hex(e){return iO("sha256").update(e).digest("hex")}function looksBlank(e){let t;try{t=oO.PNG.sync.read(Buffer.from(e))}catch{return!0}for(let e=0;e<t.data.length;e+=4){const n=t.data[e+3];if(0!==n&&(255!==t.data[e]||255!==t.data[e+1]||255!==t.data[e+2]))return!1}return!0}var TL=42e4,kL=`[${WN}]`,SL=class extends Error{constructor(e){super(e),this.code="content-unavailable",this.name="ContentUnavailableError"}},EL=3840,AL=12e3,CL=2;function sizesItsViewport(e,t){const n=void 0!==e.width&&void 0!==e.height;return!0===e.responsive&&!n&&void 0===t.viewport}async function fitViewportToStoryboard(e,t,n){for(let r=0;r<CL;r++){const r=await e.locator(t).evaluate(e=>{const t=e.getBoundingClientRect();return{width:Math.ceil(t.width),height:Math.ceil(t.height)}});if(r.width<=0||r.height<=0)return;const s={width:Math.min(r.width,EL),height:Math.min(r.height,AL)},i=e.viewportSize(),o=i?.width===s.width&&i.height===s.height;if(o)return;await e.setViewportSize(s),await n()}}async function settleCapturePage(e,t,n){await settlePage(e,t,n);const r=n?.contentUnavailableTimeoutMs??TL,s=Date.now()+r;for(;await e.locator(t).locator(kL).count();){try{await e.waitForFunction(({selector:e,unavailable:t})=>{const n=document.querySelector(e);return n&&!n.querySelector(t)},{selector:t,unavailable:kL},{timeout:Math.max(1,s-Date.now())})}catch(e){if(!(e instanceof Error)||"TimeoutError"!==e.name)throw e;throw new SL(`Storyboard content remained unavailable after ${r}ms. Check the Flutter devserver compile log or the external content producer; increase contentUnavailableTimeoutMs for a slower cold build.`)}await settlePage(e,t,n)}await alignCaptureSubframeFonts(e)&&await settlePage(e,t,n)}function isPageGoneError(e){return/Target closed|Target page, context or browser has been closed|Page closed|Target crashed/.test(e)}function isBrowserGoneError(e){return/Browser has been closed|Browser closed|browser has disconnected|Browser process crashed/.test(e)}var IL=new WeakSet;function markNavigated(e,t){t&&null!==e&&"object"==typeof e&&IL.add(e)}function readNavigatedMark(e){return null!==e&&"object"==typeof e&&IL.has(e)}function documentReplaced(e,t,n){return t.navigationRequests>e.navigationRequests+n||t.documentCommits>e.documentCommits+n}var PL=3;function decideBoardRetry(e,t,n=PL){if("content-unavailable"===e.status)return"accept";if(t>=n-1)return"accept";if("render-error"===e.status){const t=e.error??"";return isBrowserGoneError(t)?"accept":isPageGoneError(t)?"retry-fresh-worker":e.navigated||isNavigationInterruptedError(t)?"retry":"accept"}return e.navigated?"retry":"accept"}function navigatedRejectionError(e){return`document reloaded during every attempt (${e}); the capture never saw one stable document`}function finalizeAcceptedAttempt(e,t){const{result:n}=e;return e.navigated&&"render-error"!==n.status&&"content-unavailable"!==n.status?{canvasPath:n.canvasPath,storyboardId:n.storyboardId,status:"render-error",error:navigatedRejectionError(t),timings:n.timings}:"render-error"===n.status&&t>1?{...n,error:`after ${t} attempts: ${n.error}`}:n}function reloadStormWindowFor(e){return Math.max(8,4*Math.max(1,Math.floor(e)))}function isReloadStorm(e,t){return!(e.length<t)&&e.slice(-t).every(Boolean)}var DL=class extends Error{constructor(){super(...arguments),this.name="CaptureReloadStormError"}};function describeRetryReason(e){return"render-error"===e.status&&isPageGoneError(e.error??"")?"page closed mid-capture":"document reloaded mid-capture"}async function within(e,t){let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(void 0),e)})])}finally{clearTimeout(n),t.catch(()=>{})}}var RL=5,NL=GN;function captureViewportFor(e,t){return t.viewport??(e.width&&e.height?{width:Math.ceil(e.width),height:Math.ceil(e.height)}:NL)}async function startCaptureSession(e){const t=e.log??(()=>{}),n=e.parallelPages??1,r=!1===e.styleIsolation?void 0:createStyleIsolation(),s=createCaptureImageNormalizer(),{chromium:i}=await(import("playwright"));let o;try{o=await i.launch({args:bO})}catch(e){if(!isMissingBrowserError(e)||autoInstallDisabled())throw e;t("[capture] Chromium is not installed — downloading it now (one-time, ~2 min)"),await installChromium(t),o=await i.launch({args:bO})}const{fingerprint:a}=buildEnvFingerprint({os:process.platform,browserVersion:o.version()}),browserGoneError=e=>new Error(`capture browser is gone; cannot open a fresh page: ${e}`),createCaptureWorker=async t=>{const n=Date.now(),i=await o.newContext({deviceScaleFactor:t.deviceScaleFactor??yO,viewport:t.viewport??NL,reducedMotion:"reduce",colorScheme:"light",timezoneId:"UTC",locale:"en-US",serviceWorkers:"block"});process.env.TEMPO_SDK_RUNTIME_PATH&&await i.addInitScript(await readBrowserRuntimeScript()),await i.addInitScript(buildPaintHoldInitScript()),await i.addInitScript(buildFreezeInitScript()),await i.addInitScript(installRenderProfileInPage),r&&await i.addInitScript(installCaptureStylesInPage);const a=await i.newPage(),c=await installCaptureImages(a,s,{requestLatencyMs:t.requestLatencyMs}),l=await i.newCDPSession(a),d={context:i,page:a,images:c,contextMs:Date.now()-n,contextClaimed:!1,hasNavigated:!1,renderedCanvasPaths:new Set,counters:{navigationRequests:0,documentCommits:0},documentsLoaded:0,navigationsInFlight:0,async dispose(){await c.dispose(),await l.detach().catch(()=>{}),await a.close().catch(()=>{}),await i.close().catch(()=>{})}},isMainFrameNavigation=e=>{try{return e.isNavigationRequest()&&e.frame()===a.mainFrame()}catch{return!1}};return a.on("request",e=>{isMainFrameNavigation(e)&&(e.redirectedFrom()||(d.counters.navigationRequests+=1,d.navigationsInFlight+=1))}),a.on("requestfailed",e=>{isMainFrameNavigation(e)&&(d.navigationsInFlight=Math.max(0,d.navigationsInFlight-1))}),l.on("Page.frameNavigated",({frame:e})=>{e.parentId||(d.counters.documentCommits+=1)}),await l.send("Page.enable"),await alignCaptureFonts(l),a.on("domcontentloaded",()=>{d.documentsLoaded+=1,d.navigationsInFlight=0,d.hasNavigated&&(a.addStyleTag({content:cO}).catch(()=>{}),d.renderedCanvasPaths=new Set(d.currentCanvasPath?[d.currentCanvasPath]:[]),r?.forget())}),e.timing?.recordBoard("context",d.contextMs),d},planStyles=async(n,s)=>{if(!r||!n.hasNavigated)return;const i=Date.now();try{return await r.plan({read:()=>n.page.evaluate(()=>window.__tempoCaptureStyles?.read()),rendered:n.renderedCanvasPaths,next:s})}catch(e){return t(`[capture] ${s}: stylesheets not isolated: ${e instanceof Error?e.message:String(e)}`),{document:"reuse",disable:[],order:[]}}finally{e.timing?.recordBoard("style-isolation",Date.now()-i)}},sleep6=e=>new Promise(t=>setTimeout(t,e)),awaitDocumentQuiet=async(e,t)=>{const n=500,r=Date.now()+Math.min(t,1e4),settleLoad=async()=>{for(;e.navigationsInFlight>0&&Date.now()<r;)await sleep6(50);await e.page.waitForLoadState("load",{timeout:Math.max(1,r-Date.now())}).catch(()=>{})};await settleLoad();let s=e.counters.navigationRequests,i=Date.now();for(;Date.now()<r;)if(await sleep6(100),e.counters.navigationRequests!==s||e.navigationsInFlight>0)s=e.counters.navigationRequests,i=Date.now(),await settleLoad();else if(Date.now()-i>=n)return},withSettledStoryboard=async(t,n,r,i,o,a)=>{const c=captureViewportFor(t,n);if("html"===t.source?.kind||"astro"===t.source?.kind){const o=await createCaptureWorker({...n,viewport:c});r.contextMs=o.contextMs;try{const a="html"===t.source.kind?await openHeadlessHtmlSource(o.context,t.source.filepath,s):{url:astroCaptureUrl(await(e.getAppUrl?.()??Promise.reject(new Error("Astro component capture requires the app dev server"))),t),assertResources(){}},c=new Set;o.page.on("pageerror",e=>c.add(e.message)),o.page.on("response",e=>{e.status()>=400&&c.add(`${e.status()} ${e.url()}`)}),o.page.on("requestfailed",e=>c.add(`${e.failure()?.errorText} ${e.url()}`));const l={...o.counters},d=Date.now(),u=await o.page.goto(a.url,{waitUntil:"load",timeout:n.settleTimeoutMs??e.settleTimeoutMs??3e4});if("astro"===t.source.kind){if(!u?.ok())throw new Error(`Astro storyboard returned HTTP ${u?.status()}`);await settleAstroDocument(o.page,t,n.settleTimeoutMs??e.settleTimeoutMs??3e4)}r.navigateMs=Date.now()-d,await o.page.addStyleTag({content:cO});const p=Date.now();await settleCapturePage(o.page,"body",{timeoutMs:n.settleTimeoutMs??e.settleTimeoutMs??3e4,contentUnavailableTimeoutMs:n.contentUnavailableTimeoutMs??e.contentUnavailableTimeoutMs});const m=await o.page.evaluate(buildVisualReadyWaitScript(n.settleTimeoutMs??e.settleTimeoutMs??3e4));if(requireVisualReadiness(m,!0),m.failures.length)throw new Error(`HTML storyboard visual resources failed: ${JSON.stringify(m.failures)}`);if(a.assertResources(),"astro"===t.source.kind&&c.size)throw new Error(`Astro storyboard failed: ${[...c].join("; ")}`);r.settleMs=Date.now()-p,o.images.assertHealthy(),await releasePaintHold(o.page);const f=await i(o.page,"body");if(o.images.assertHealthy(),a.assertResources(),"astro"===t.source.kind&&c.size)throw new Error(`Astro storyboard failed: ${[...c].join("; ")}`);if(o.page.url()!==a.url)throw new Error("HTML storyboard navigated away from its accepted source");return{value:f,navigated:documentReplaced(l,o.counters,1)}}finally{await o.dispose()}}const l=storyboardRenderId(t.hostCanvasPath,t.storyboardId),d=buildStoryboardRenderSelector(l),u=void 0===o,p=o??await createCaptureWorker({...n,viewport:c}),{page:m}=p;p.contextClaimed||(r.contextMs=p.contextMs,p.contextClaimed=!0);const f={...p.counters},g=p.hasNavigated?0:1,navigatedSinceStart=()=>documentReplaced(f,p.counters,g);try{const s=Date.now();try{p.hasNavigated&&(await holdPaint(m),await p.images.forgetLoadedImages());const r=m.viewportSize();r?.width===c.width&&r?.height===c.height||await m.setViewportSize(c);const s=buildDirectRenderUrl2(e.hostUrl,t);if(p.hasNavigated){if(p.currentSelector===d&&(await m.evaluate(e=>{history.replaceState(history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:history.state}))},buildDirectRenderIdleUrl(e.hostUrl)),await m.waitForSelector(p.currentSelector,{state:"detached",timeout:n.settleTimeoutMs??e.settleTimeoutMs??3e4})),a?.preload){const t=n.settleTimeoutMs??e.settleTimeoutMs??3e4;await within(t,m.evaluate(buildCanvasPreloadScript(a.preload,d)));const r=await within(t,m.evaluate(e=>window.__tempoCaptureStyles?.arrange(e),a.order));r?.reordered&&e.timing?.recordBoard("style-isolation.reordered",1,"count")}await m.evaluate(({url:e,nextSelector:t,styles:n})=>{const r=window;n&&r.__tempoCaptureStyles?.toggle(n.disable),r.__tempoResetCaptureDeterminism?.(),n?.preload||r.__tempoCaptureRenderProfile?.begin(t),history.replaceState(history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:history.state}))},{url:s,nextSelector:d,styles:a})}else await m.goto(s,{waitUntil:"domcontentloaded"}),await m.addStyleTag({content:cO}),p.hasNavigated=!0;p.currentSelector=d,p.currentCanvasPath=t.hostCanvasPath,p.renderedCanvasPaths.add(t.hostCanvasPath)}finally{r.navigateMs=Date.now()-s,e.timing?.recordBoard("navigate",r.navigateMs)}const o=Date.now(),settle=()=>settleCapturePage(m,d,{timeoutMs:n.settleTimeoutMs??e.settleTimeoutMs??3e4,contentUnavailableTimeoutMs:n.contentUnavailableTimeoutMs??e.contentUnavailableTimeoutMs,onStep:(t,n)=>e.timing?.recordBoard(`settle.${t}`,n)});try{await settle(),sizesItsViewport(t,n)&&await fitViewportToStoryboard(m,d,settle)}finally{r.settleMs=Date.now()-o,e.timing?.recordBoard("settle",r.settleMs)}const l=await m.evaluate(readRenderProfileInPage,t.hostCanvasPath);e.timing?.recordBoard("render.dom-content-loaded",l.domContentLoadedMs),e.timing?.recordBoard("render.react-injected",l.reactInjectedMs),e.timing?.recordBoard("render.react-first-commit",l.reactFirstCommitMs),e.timing?.recordBoard("render.react-last-commit",l.reactLastCommitMs),e.timing?.recordBoard("render.react-commit-work",l.reactCommitWorkMs),e.timing?.recordBoard("render.target-module",l.targetModuleLoadedMs),e.timing?.recordBoard("render.target-attached",l.targetAttachedMs),e.timing?.recordBoard("render.last-canvas-module",l.lastCanvasModuleLoadedMs),e.timing?.recordBoard("render.last-script",l.lastScriptLoadedMs),e.timing?.recordBoard("render.long-task-time",l.longTaskDurationMs),e.timing?.recordBoard("requests.all",l.requestCount,"count"),e.timing?.recordBoard("requests.script",l.scriptRequestCount,"count"),e.timing?.recordBoard("requests.canvas-module",l.canvasModuleRequestCount,"count"),e.timing?.recordBoard("requests.unrelated-canvas",l.unrelatedCanvasModuleRequestCount,"count"),e.timing?.recordBoard("react.commits",l.reactCommitCount,"count"),e.timing?.recordBoard("render.long-tasks",l.longTaskCount,"count"),await m.evaluate(watchRenderErrorsInPage,{selector:d,errorSelector:XN,messageAttribute:YN}),p.images.assertHealthy();const u=Date.now();await releasePaintHold(m),e.timing?.recordBoard("reveal",Date.now()-u);const f=await i(m,d);if(p.images.assertHealthy(),await m.locator(d).locator(kL).count())throw new SL("Storyboard content became unavailable during capture. Check the Flutter devserver compile log or the external content producer and retry.");const g=await m.evaluate(readRenderErrorsInPage);if(g.length>0)throw new Error(`storyboard rendered its error boundary: ${g.join("; ")}`);return{value:f,navigated:navigatedSinceStart()}}catch(e){throw markNavigated(e,navigatedSinceStart()),e}finally{u&&await p.dispose()}},captureStoryboardArtifactsOnce=async(t,n)=>{const r=t.artifacts??["png"],s={contextMs:0,navigateMs:0,settleMs:0};return withSettledStoryboard(t,t,s,async(n,s)=>{const i={};if(i.styles=await n.evaluate(assessPageStylesInPage,s),r.includes("png")){const e=new Uint8Array(await(t.source?n.screenshot({type:"png",animations:"disabled"}):n.locator(s).screenshot({type:"png",animations:"disabled"}))),r=oO.PNG.sync.read(Buffer.from(e));i.png={pngBytes:e,width:r.width,height:r.height}}if(r.includes("html")){const r=t.source?n.url():`${new URL(e.hostUrl).origin}/`,o=await n.evaluate(extractStoryboardDomInPage,s),a=buildStoryboardHtmlDocument(o,{baseUrl:r,preserveBody:Boolean(t.source)});if(t.portableHtml??!0){const e=await n.evaluate(inlinePortableHtmlInPage,{html:a,baseUrl:r});i.html={html:e.html,baseUrl:r,portable:!0,warnings:e.warnings}}else i.html={html:a,baseUrl:r,portable:!1,warnings:[]}}return i},n)},captureWarmStoryboardArtifactsOnce=async e=>{const t=await createCaptureWorker({...e,viewport:captureViewportFor(e,e)});try{const n=await withSettledStoryboard(e,e,{contextMs:0,navigateMs:0,settleMs:0},async()=>{},t),r=await captureStoryboardArtifactsOnce(e,t);return{value:r.value,navigated:r.navigated||n.navigated}}finally{await t.dispose()}},captureStoryboardArtifacts=async e=>{const n=`${e.hostCanvasPath}#${e.storyboardId}`;for(let r=0;;r+=1){const s=r>=PL-1,i=r+1;let a;try{a=e.warm&&!e.source?await captureWarmStoryboardArtifactsOnce(e):await captureStoryboardArtifactsOnce(e)}catch(e){if(e instanceof SL)throw e;const r=e instanceof Error?e.message:String(e);if(!o.isConnected())throw browserGoneError(r);const a=!isBrowserGoneError(r)&&(readNavigatedMark(e)||isNavigationInterruptedError(r)||isPageGoneError(r));if(s||!a)throw e;t(`[capture] ${n}: ${r.split("\n")[0]} (attempt ${i}/${PL}) — re-capturing`);continue}if(!a.navigated)return a.value;if(s)throw new Error(navigatedRejectionError(i));t(`[capture] ${n}: document reloaded mid-capture (attempt ${i}/${PL}) — re-capturing`)}},captureOne=async(t,n,r)=>{const s={contextMs:0,navigateMs:0,settleMs:0,screenshotMs:0};try{const{value:i,navigated:o}=await withSettledStoryboard({source:t.source,hostCanvasPath:t.hostCanvasPath,storyboardId:t.storyboardId,width:t.layout.width,height:t.layout.height,...t.responsive?{responsive:!0}:{}},{},s,async(n,r)=>{const i=Date.now();let o,a;try{const e=n.locator(r);o=new Uint8Array(await(t.source?n.screenshot({type:"png",animations:"disabled"}):e.screenshot({type:"png",animations:"disabled"}))),a=(new TextEncoder).encode((await n.evaluate(extractStoryboardDomInPage,r)).elementHtml)}finally{s.screenshotMs=Date.now()-i,e.timing?.recordBoard("screenshot",s.screenshotMs)}return{canvasPath:t.canvasPath,storyboardId:t.storyboardId,status:looksBlank(o)?"empty":"ok",pngHash:sha256Hex(o),pngBytes:o,htmlHash:sha256Hex(a),htmlBytes:a,timings:s}},n,r);return{result:i,status:i.status,navigated:o}}catch(e){const n={canvasPath:t.canvasPath,storyboardId:t.storyboardId,status:e instanceof SL?"content-unavailable":"render-error",error:e instanceof Error?e.message:String(e),timings:s};return{result:n,status:n.status,error:n.error,navigated:readNavigatedMark(e)}}};return{browserVersion:o.version(),envFingerprint:a,captureBoards:async(r,s)=>{if(0===r.length)return[];const i=s?.label??"capture",a=e.settleTimeoutMs??3e4,c=new Array(r.length),l=Math.max(1,Math.min(n,r.length)),d=reloadStormWindowFor(l),u=[];let p=0,m=!1,f=0,g=0,y=0;const b=Array.from({length:l},async()=>{let n=await createCaptureWorker({});const replaceWorker=async()=>{if(await n.dispose(),!o.isConnected())throw browserGoneError("browser disconnected");try{n=await createCaptureWorker({})}catch(e){throw browserGoneError(e instanceof Error?e.message:String(e))}};try{for(;;){if(m)return;const s=f;if(f+=1,s>=r.length)return;const o=r[s],l=`${o.canvasPath}#${o.storyboardId}`;let b,v=0;for(let r=0;;r+=1){let s=o.source||n.currentCanvasPath===o.hostCanvasPath?void 0:await planStyles(n,o.hostCanvasPath);"new"===s?.document&&(y+=1,e.timing?.recordBoard("style-isolation.new-document",1,"count"),y<=RL&&t(`${i}: ${l}: rendered in a new document: ${s.reason}`),await replaceWorker(),s=void 0);const c=await captureOne(o,n,s),d=decideBoardRetry(c,r);if("accept"===d){b=finalizeAcceptedAttempt(c,r+1),r>0&&e.timing?.recordBoard("capture.retries",r,"count");break}const u=describeRetryReason(c);"document reloaded mid-capture"===u&&(v+=1),t(`${i}: ${l}: ${u} (attempt ${r+1}/${PL}) — re-capturing`),"retry-fresh-worker"===d?await replaceWorker():await awaitDocumentQuiet(n,a)}if(c[s]=b,g+=1,g%10!=0&&g!==r.length||t(`${i}: ${g}/${r.length}`),p+=v,u.push(v>0),u.length>d&&u.shift(),isReloadStorm(u,d))throw m=!0,new DL(`capture aborted: the document reloaded during the last ${d} storyboards in a row (${p} re-captures so far) — check the devserver output and storyboard navigation for repeated reloads`);"render-error"===b.status&&await replaceWorker()}}finally{await n.dispose()}});return await Promise.all(b),y>RL&&t(`${i}: ${y} storyboards were rendered in a new document to keep earlier canvases' stylesheets out`),c},captureStoryboard:async e=>{const{png:t}=await captureStoryboardArtifacts({...e,artifacts:["png"]});return t},captureStoryboardHtml:async e=>{const{html:t}=await captureStoryboardArtifacts({...e,artifacts:["html"],portableHtml:e.portable??!0});return t},captureStoryboardArtifacts,dispose:async()=>{await o.close().catch(()=>{})}}}var OL=C(ru(),1),FL=24;function normalizeCompositePadding(e,t,n){if(null==e)return FL;if("string"==typeof e){const r=e.trim().match(/^(\d+(?:\.\d+)?)%$/);if(!r)throw new Error('Composite padding percentage must use the form "5%"');const s=Number(r[1]);if(!Number.isFinite(s)||s<0)throw new Error("Composite padding percentage must be non-negative");return Math.round(Math.min(t,n)*(s/100))}if(!Number.isFinite(e)||e<0)throw new Error("Composite padding must be a non-negative number");return Math.round(e)}function compositeStoryboardPngs(e,t={}){if(0===e.length)throw new Error("At least one image is required to composite a canvas image");const n=t.scale??yO,r=e.map(e=>{if(!Number.isFinite(e.x)||!Number.isFinite(e.y))throw new Error("Composite image inputs must have finite positions");return{png:OL.PNG.sync.read(Buffer.from(e.pngBytes)),x:Math.round(e.x*n),y:Math.round(e.y*n)}});let s=1/0,i=1/0,o=-1/0,a=-1/0;for(const{png:e,x:t,y:n}of r)s=Math.min(s,t),i=Math.min(i,n),o=Math.max(o,t+e.width),a=Math.max(a,n+e.height);const c=o-s,l=a-i,d=normalizeCompositePadding(t.padding,c,l),u=c+2*d,p=l+2*d,m=new OL.PNG({width:u,height:p});if(t.background){const{r:e,g:n,b:r}=t.background,s=Math.round(255*(t.background.a??1));for(let t=0;t<m.data.length;t+=4)m.data[t]=e,m.data[t+1]=n,m.data[t+2]=r,m.data[t+3]=s}for(const{png:e,x:t,y:n}of r){const r=t-s+d,o=n-i+d;for(let t=0;t<e.height;t+=1)for(let n=0;n<e.width;n+=1){const s=4*(t*e.width+n),i=4*((o+t)*u+(r+n)),a=e.data[s+3]/255;if(0===a)continue;if(1===a){m.data[i]=e.data[s],m.data[i+1]=e.data[s+1],m.data[i+2]=e.data[s+2],m.data[i+3]=255;continue}const c=m.data[i+3]/255,l=a+c*(1-a);for(let t=0;t<3;t+=1){const n=e.data[s+t],r=m.data[i+t];m.data[i+t]=0===l?0:Math.round((n*a+r*c*(1-a))/l)}m.data[i+3]=Math.round(255*l)}}return{pngBytes:new Uint8Array(OL.PNG.sync.write(m)),width:u,height:p}}var LL=60,ML=12e4,UL=[{name:"cold",dependsOn:"something that differs between two loads of the same page",options:{}},{name:"slowed",dependsOn:"the order or timing in which its files arrive (a race between loading and rendering)",options:{requestLatencyMs:LL,settleTimeoutMs:ML}},{name:"warm",dependsOn:"what the document loaded before it rendered (a module singleton, font or stylesheet that is not ready on first render)",options:{warm:!0}}];function determinismProbeForRun(e){return UL[e%UL.length]}import{readFile as jL}from"fs/promises";import BL from"path";import{randomUUID as $L}from"crypto";import{readFile as WL}from"fs/promises";import HL from"path";function createSharedAppRuntime(e,t){const n=new AbortController;let r,s,i=!1;const acquire=async()=>{const s=await resolveTempoConfig(e),{appRoot:o}=await resolveAppRoot(s),a=await ensureTempoWorkspaceNonce(s.tempoRoot),accepts=async e=>{try{const t=await fetch(new URL("__tempo/identity",e.replace(/\/?$/,"/")),{signal:AbortSignal.any([n.signal,AbortSignal.timeout(5e3)])}),r=await t.json(),s=t.ok&&!0===r.tempoHost&&!0===r.pluginActive&&r.workspaceNonce===a&&"astro"===r.framework&&1===r.capabilities?.astroComponents;if(!s)return!1;if(!tempoSdkIdentitySatisfiesCanvasHost(r)){const e=await resolveTempoSdkUpgradePlan(o);throw new pf({managedUpgradeAttempted:!1,remediationCommand:e.remediationCommand,remediationDirectory:e.cwd})}return!0}catch(e){if(e instanceof pf)throw e;return!1}};let c={};try{c=JSON.parse(await WL(HL.join(e,".tempo/app-devserver.json"),"utf8"))}catch{}const l="string"==typeof s.appUrl?s.appUrl:void 0,d=!l||l.includes("${")&&!c.port?c.port?`http://127.0.0.1:${c.port}`:void 0:substituteAppPort(l,c.port??0);if(d){if(await accepts(d))return d;let e=!1;try{await fetch(d,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(1500)])}),e=!0}catch{}if(e)throw new Error("The configured app URL belongs to a running server without this workspace's Astro preview capability; restart that app with Tempo instrumentation")}if(i)throw new Error("Capture runtime is disposed");if(!s.scripts.appStart)throw new Error("Astro component capture requires apps[0].start in tempo/tempo.config.json");r=new y_({cwd:o,workspaceRoot:HL.join(s.tempoRoot,".tempo/capture-app",$L()),command:s.scripts.appStart,...s.scripts.appStop?{stop:s.scripts.appStop}:{},...s.appUrl?{url:s.appUrl}:{}}),r.onOutput(t);const u=await r.start(n.signal);if(!u.ok||!u.url)throw new Error(u.error??"App server failed to start for Astro capture");if(!await accepts(u.url))throw new Error("App server lacks the Astro component preview capability; enable tempoAstro() from tempo-sdk/astro");return u.url};return{getAppUrl:()=>i?Promise.reject(new Error("Capture runtime is disposed")):(s??=acquire().catch(async e=>{throw await(r?.stop()),e}),s),async dispose(){i=!0,n.abort(),await(s?.catch(()=>{})),await(r?.stop())}}}var qL=new Map;function createCaptureAppRuntime(e,t=()=>{}){const n=HL.resolve(e);let r,s=!1,i=!1;return{getAppUrl(){if(i)return Promise.reject(new Error("Capture runtime is disposed"));if(!s){if(r=qL.get(n),!r){const e=new Set;r={runtime:createSharedAppRuntime(n,t=>{for(const n of e)n(t)}),refs:0,logs:e},qL.set(n,r)}s=!0,r.refs++,r.logs.add(t)}return r.runtime.getAppUrl()},async dispose(){i||(i=!0,s&&(r.logs.delete(t),0===--r.refs&&(qL.get(n)===r&&qL.delete(n),await r.runtime.dispose())))}}}async function readTempoDevserverConfig(e){const t=JSON.parse(await jL(e,"utf-8"));if(!t.scripts?.install||!t.scripts?.start)throw new Error(`tempo.config.json at ${e} must declare scripts.install and scripts.start`);const n=t.scripts.updateSdk;if(null!=n&&("string"!=typeof n||0===n.trim().length))throw new Error(`tempo.config.json at ${e}: scripts.updateSdk must be a non-empty string when provided`);return{scripts:{install:t.scripts.install,start:t.scripts.start,stop:t.scripts.stop??null,..."string"==typeof n?{updateSdk:n.trim()}:{}},tempoHostUrl:t.urls?.tempoHost??null}}function projectRootForTempoDir(e){const t=BL.resolve(e);return"tempo"===BL.basename(t)?BL.dirname(t):t}async function resolveCanvasHostLayout(e){const t=BL.resolve(e.repoRoot),n=e.tempoDir?[BL.join(BL.resolve(e.tempoDir),"tempo.config.json")]:[BL.join(t,"tempo","tempo.config.json"),BL.join(t,"tempo.config.json")];for(const e of n){let t;try{t=JSON.parse(await jL(e,"utf-8"))}catch{continue}if("object"!=typeof t||null===t||!("scripts"in t))continue;const n=BL.dirname(e),r=t.paths,s="string"==typeof r?.canvases&&r.canvases.trim().length>0?r.canvases.trim().split("\\").join("/"):"designs";return{tempoDir:n,projectRoot:projectRootForTempoDir(n),pagesDir:BL.resolve(n,s),configPath:e}}const r=e.tempoDir?BL.resolve(e.tempoDir):BL.join(t,"tempo");return{tempoDir:r,projectRoot:projectRootForTempoDir(r),pagesDir:BL.join(r,"designs"),configPath:null}}function resolveTempoDir(e){if(e.tempoConfigPath)return BL.dirname(e.tempoConfigPath);if(e.tempoDir)return e.tempoDir;if(e.repoRoot)return BL.join(e.repoRoot,"tempo");throw new Error("startDevserverSession needs one of tempoDir, repoRoot, or tempoConfigPath")}async function awaitCanvasRegistration(e){const t=e.log??(()=>{}),n=e.maxAttempts??21,r=e.retryDelayMs??250;for(let s=0;;s+=1){const i=await fetch(`${e.origin}/__tempo/canvas-host-registration`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({canvasPath:e.hostCanvasPath})}).catch(()=>null);if(!i)throw new Error(`registration barrier unreachable at ${e.origin}`);if(!i.headers.get("x-tempo-canvas-host-registration"))return void t("registration barrier not supported by host framework — skipping");if(i.ok)return;if(s>=n-1)throw new Error(`canvas ${e.hostCanvasPath} never registered into the host (last status ${i.status})`);await e.reRegister(),await new Promise(e=>setTimeout(e,r))}}var zL=/\x1b\[[0-9;]*[A-Za-z]/g;function cleanDevserverLine(e){return e.replace(zL,"").trim()}function createDevserverLineSplitter(){let e="";return{push(t){const n=(e+t).split(/\r?\n/);return e=n.pop()??"",n.map(cleanDevserverLine).filter(e=>e.length>0)},flush(){const t=cleanDevserverLine(e);return e="",t.length>0?[t]:[]}}}async function startDevserverSession(e){const t=e.log??(()=>{}),n=resolveTempoDir(e),r=e.tempoConfigPath??BL.join(n,"tempo.config.json"),s=await readTempoDevserverConfig(r),i=e.hostCanvasPaths??[],o=new fx({tempoConfigPath:r,tempoHostUrl:s.tempoHostUrl,scripts:s.scripts});await o.initialize();const a=projectRootForTempoDir(n);for(const e of i)await o.ensureCanvasRegistered(BL.join(a,e));const c=await o.startDevServer(),l=e.onOutput,d=l?createDevserverLineSplitter():null,forwardOutput=e=>{if(l)for(const n of e)try{l(n)}catch(e){t(`devserver output listener threw: ${e instanceof Error?e.message:String(e)}`)}};d&&c.onOutput(e=>forwardOutput(d.push(String(e))));const u=await c.waitUntilReady(e.readyTimeoutMs??12e4);if(!u.ok||!u.url)throw await c.stop().catch(()=>{}),await o.dispose(),forwardOutput(d?.flush()??[]),new Error(`tempobook devserver failed to become ready: ${u.message??(u.timedOut?"timeout":"unknown")}`);const p=u.url,m=new URL(p).origin;t(`devserver ready at ${p}`);const registerCanvas=async e=>{await o.ensureCanvasRegistered(BL.join(a,e)),await awaitCanvasRegistration({origin:m,hostCanvasPath:e,reRegister:()=>o.ensureCanvasRegistered(BL.join(a,e)),log:t})};for(const e of i)await awaitCanvasRegistration({origin:m,hostCanvasPath:e,reRegister:()=>o.ensureCanvasRegistered(BL.join(a,e)),log:t});const f=createCaptureAppRuntime(a,t);return{getAppUrl:f.getAppUrl,origin:m,hostUrl:p,projectRoot:a,tempoDir:n,registerCanvas,dispose:async()=>{try{await f.dispose()}finally{await c.stop().catch(()=>{}),await o.dispose(),forwardOutput(d?.flush()??[])}}}}import{createHash as GL}from"crypto";import{access as VL,readFile as KL}from"fs/promises";import XL from"path";function ignoredStoryboardArea(e,t,n){const r=e.map(({x:e,y:r,w:s,h:i})=>({left:Math.max(0,e),top:Math.max(0,r),right:Math.min(t,e+s),bottom:Math.min(n,r+i)})).filter(({left:e,top:t,right:n,bottom:r})=>n>e&&r>t),s=[...new Set(r.flatMap(({left:e,right:t})=>[e,t]))].sort((e,t)=>e-t);let i=0;for(let e=1;e<s.length;e++){const t=s[e-1],n=s[e],o=r.filter(e=>e.left<n&&e.right>t).sort((e,t)=>e.top-t.top);let a=0,c=0;for(const e of o)a+=Math.max(0,e.bottom-Math.max(c,e.top)),c=Math.max(c,e.bottom);i+=(n-t)*a}return i}function toPosixPath5(e){return e.split(XL.sep).join("/")}async function enumerateCanvasStoryboards(e){const t=e.pagesDir??XL.join(e.tempoDir,"designs"),n=projectRootForTempoDir(e.tempoDir),r=await scanCanvasFiles(t),s=[],i=[],o=[],a=[];let c=0;for(const t of r){const r=await KL(t,"utf-8"),l=parseCanvasFile(t,r),d=l.errors.filter(e=>"structural"===e.kind),u=l.imports.some(e=>"tempo-sdk/canvas"===e.source||e.source.endsWith("/tempo-sdk/canvas"))||l.misimportedSdkCanvasImports.length>0,p=!u&&d.length>0&&d.every(e=>e.message===ev);if(p)continue;const m=d.filter(e=>e.newerSdkStoryboard),f=d.filter(e=>!e.newerSdkStoryboard);if(f.length>0){i.push(...d.map(e=>({filePath:t,message:e.message})));continue}for(const e of m){const{component:n,storyboardKey:r,vrt:s}=e.newerSdkStoryboard;c+=1,a.push({filePath:t,component:n,...r?{storyboardId:r}:{},vrt:s})}const g=l.errors.filter(e=>"degraded"===e.kind&&e.message.includes(" vrt"));if(g.length>0){o.push(...g.map(e=>({filePath:t,message:e.message})));continue}const y=toPosixPath5(XL.relative(e.tempoDir,XL.dirname(t))),b=toPosixPath5(XL.relative(n,t));for(const e of l.storyboards)c+=1,"route"!==e.kind&&("html"!==e.kind||e.filepath?s.push({..."astro"===componentFrameworkForStoryboard(e)?{source:{kind:"astro",canvasPath:l.canvasPath??toPosixPath5(XL.relative(n,XL.dirname(t))),revision:GL("sha256").update(r).digest("hex")}}:"html"===e.kind?{source:{kind:"html",filepath:XL.resolve(XL.dirname(t),e.filepath)}}:{},filePath:t,canvasPath:y,hostCanvasPath:b,storyboardId:e.storyboardKey,name:e.displayName,layout:{x:e.layout.x,y:e.layout.y,width:e.layout.width,height:e.layout.height},vrt:e.vrt,...e.responsive?{responsive:!0}:{}}):e.vrt&&o.push({filePath:t,message:`HTML storyboard "${e.storyboardKey}" requires a literal local filepath for headless capture.`}))}return{storyboards:s,totalStoryboards:c,totalCanvases:r.length,structuralErrors:i,vrtConfigErrors:o,newerSdkStoryboards:a}}async function enumerateTrackedStoryboards(e){try{await VL(e.tempoDir)}catch{return{tracked:[],paused:[],totalStoryboards:0,totalCanvases:0,errors:[],newerSdkStoryboards:[]}}const t=await enumerateCanvasStoryboards(e),n=[],r=[],s=[...t.structuralErrors,...t.vrtConfigErrors];for(const e of t.storyboards){if(!e.vrt)continue;const t={...e.source?{source:e.source}:{},canvasPath:e.canvasPath,hostCanvasPath:e.hostCanvasPath,storyboardId:e.storyboardId,name:e.name,layout:e.layout,threshold:e.vrt.threshold,ignore:e.vrt.ignore,...e.responsive?{responsive:!0}:{}},{width:i,height:o}=t.layout,a=void 0!==i&&void 0!==o;if(a){const t=ignoredStoryboardArea(e.vrt.ignore??[],i,o);if(t>=.9*i*o){s.push({filePath:e.filePath,message:`<Storyboard id="${e.storyboardId}"> vrt.ignore masks ≥90% of the board — untrack it instead`});continue}}e.vrt.skip?r.push(t):n.push(t)}return{tracked:n,paused:r,totalStoryboards:t.totalStoryboards,totalCanvases:t.totalCanvases,errors:s,newerSdkStoryboards:t.newerSdkStoryboards}}var YL=10,JL=20,QL=2e3;function isStyleStarved(e){return 0===e.unreadableSheetCount&&e.classElementCount>=YL&&e.authorRuleCount<JL&&e.styleTextBytes<QL}function describeStyleStarvation(e){return`page rendered with almost no CSS (${e.classElementCount} class-carrying elements but only ${e.authorRuleCount} CSS rules / ${e.styleTextBytes} style bytes). The devserver likely failed to build or serve the app's styles — most often an incomplete dependency install (rerun the project's install, check the devserver output for CSS/PostCSS/Tailwind errors), then retry.`}import{readFile as ZL}from"fs/promises";import{resolve as eM}from"path";var tM={node:{core:["index","expo-babel-plugin","flutter-preview-path","nextjs-loader","assets/parser","canvas/parser"],vue:["vue"],svelte:["svelte"],astro:["astro","astro/runtime"],nuxt:["nuxt"]}};async function provisionCaptureRuntime(e){const t=process.env.TEMPO_SDK_RUNTIME_PATH||e,n=await ZL(eM(t,"runtime.json"),"utf8").then(e=>{const t=JSON.parse(e),n=Object.values(tM.node).flat().filter(e=>!Object.prototype.hasOwnProperty.call(t.node??{},e));return n.length?`The private Tempo SDK runtime is missing entries: ${n.join(", ")}`:null}).catch(()=>null),r=n??await tempoSdkRuntimeProvisioningError({tempoRuntimeContract:1},t);if(r)throw new Error(`${t}: ${r}`);process.env.TEMPO_SDK_RUNTIME_PATH=t}function pixelmatch(e,t,n,r,s,i={}){const{threshold:o=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],includeAA:d,diffColorAlt:u,diffMask:p}=i;if(!isPixelData(e)||!isPixelData(t)||n&&!isPixelData(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==t.length||n&&n.length!==e.length)throw new Error("Image sizes do not match.");if(e.length!==r*s*4)throw new Error("Image data size does not match width/height.");const m=r*s,f=new Uint32Array(e.buffer,e.byteOffset,m),g=new Uint32Array(t.buffer,t.byteOffset,m);let y=!0;for(let e=0;e<m;e++)if(f[e]!==g[e]){y=!1;break}if(y){if(n&&!p)for(let t=0;t<m;t++)drawGrayPixel(e,4*t,a,n);return 0}const b=35215*o*o,[v,w,x]=c,[S,E,A]=l,[C,I,P]=u||l;let R=0;for(let i=0;i<s;i++)for(let o=0;o<r;o++){const c=i*r+o,l=4*c,u=f[c]===g[c]?0:colorDelta(e,t,l,l,!1);if(Math.abs(u)>b){const a=antialiased(e,o,i,r,s,f,g)||antialiased(t,o,i,r,s,g,f);!d&&a?n&&!p&&drawPixel(n,l,v,w,x):(n&&(u<0?drawPixel(n,l,C,I,P):drawPixel(n,l,S,E,A)),R++)}else n&&!p&&drawGrayPixel(e,l,a,n)}return R}function isPixelData(e){return ArrayBuffer.isView(e)&&1===e.BYTES_PER_ELEMENT}function antialiased(e,t,n,r,s,i,o){const a=Math.max(t-1,0),c=Math.max(n-1,0),l=Math.min(t+1,r-1),d=Math.min(n+1,s-1),u=n*r+t;let p=t===a||t===l||n===c||n===d?1:0,m=0,f=0,g=0,y=0,b=0,v=0;for(let s=a;s<=l;s++)for(let i=c;i<=d;i++){if(s===t&&i===n)continue;const o=colorDelta(e,e,4*u,4*(i*r+s),!0);if(0===o){if(p++,p>2)return!1}else o<m?(m=o,g=s,y=i):o>f&&(f=o,b=s,v=i)}return 0!==m&&0!==f&&(hasManySiblings(i,g,y,r,s)&&hasManySiblings(o,g,y,r,s)||hasManySiblings(i,b,v,r,s)&&hasManySiblings(o,b,v,r,s))}function hasManySiblings(e,t,n,r,s){const i=Math.max(t-1,0),o=Math.max(n-1,0),a=Math.min(t+1,r-1),c=Math.min(n+1,s-1),l=e[n*r+t];let d=t===i||t===a||n===o||n===c?1:0;for(let s=i;s<=a;s++)for(let i=o;i<=c;i++)if((s!==t||i!==n)&&(d+=+(l===e[i*r+s]),d>2))return!0;return!1}function colorDelta(e,t,n,r,s){const i=e[n],o=e[n+1],a=e[n+2],c=e[n+3],l=t[r],d=t[r+1],u=t[r+2],p=t[r+3];let m=i-l,f=o-d,g=a-u;const y=c-p;if(!(m||f||g||y))return 0;if(c<255||p<255){const e=48+n%2*159,t=48+(n/1.618033988749895|0)%2*159,r=48+(n/2.618033988749895|0)%2*159;m=(i*c-l*p-e*y)/255,f=(o*c-d*p-t*y)/255,g=(a*c-u*p-r*y)/255}const b=.29889531*m+.58662247*f+.11448223*g;if(s)return b;const v=.59597799*m-.2741761*f-.32180189*g,w=.21147017*m-.52261711*f+.31114694*g,x=.5053*b*b+.299*v*v+.1957*w*w;return b>0?-x:x}function drawPixel(e,t,n,r,s){e[t+0]=n,e[t+1]=r,e[t+2]=s,e[t+3]=255}function drawGrayPixel(e,t,n,r){const s=255+(.29889531*e[t]+.58662247*e[t+1]+.11448223*e[t+2]-255)*n*e[t+3]/255;drawPixel(r,t,s,s,s)}var nM=C(ru(),1),rM=.05,sM=1990,iM=class extends Error{constructor(e,t){super(t),this.name="StoryboardStabilityTargetError",this.code=e}};function toPosix4(e){return e.replace(/\\/g,"/")}function absoluteCanvasesRoot(e,t){return BN.isAbsolute(t)?BN.resolve(t):BN.resolve(e,t)}function isInsideRoot(e,t){const n=BN.relative(e,t);return""===n||!n.startsWith("..")&&!BN.isAbsolute(n)}async function isInsideRootForReal(e,t){try{const[n,r]=await Promise.all([jN(e),jN(t)]);return isInsideRoot(n,r)}catch{return!1}}async function resolveCanvasFile(e){const t=absoluteCanvasesRoot(e.workspaceRoot,e.canvasesDir),n=e.canvasSlug,r=new Set,s=BN.resolve(t,n),i=isInsideRoot(t,s)?await resolveCanvasFilePath(s):null;if(i&&await isInsideRootForReal(t,i)&&r.add(i),0===r.size&&!n.includes("/")){const e=await findPageFilesInPagesRoot(t);for(const s of e)BN.basename(BN.dirname(s))===n&&await isInsideRootForReal(t,s)&&r.add(s)}if(0===r.size)throw new iM("canvas_not_found",`No canvas matching "${e.canvasSlug}" exists under ${toPosix4(t)}.`);if(r.size>1){const n=[...r].map(e=>toPosix4(BN.relative(t,BN.dirname(e)))).sort();throw new iM("ambiguous_canvas_slug",`"${e.canvasSlug}" names ${n.length} canvases: ${n.join(", ")}. Pass the full canvases-root-relative path.`)}const o=r.values().next().value;if(!o)throw new iM("canvas_not_found",`No canvas matching "${e.canvasSlug}" exists under ${toPosix4(t)}.`);return o}async function resolveTestedStoryboard(e){const t=await resolveCanvasFile(e),n=await UN(t,"utf8"),r=parsePageSource(t,n),s=r.storyboards.find(t=>t.storyboardKey===e.storyboard||t.exportName===e.storyboard);if(!s){const n=r.storyboards.map(e=>e.storyboardKey??e.exportName).join(", ");throw new iM("storyboard_not_found",`Storyboard "${e.storyboard}" was not found in ${toPosix4(BN.relative(e.workspaceRoot,t))}.${n?` Available storyboards: ${n}.`:""}`)}if(s.error)throw new iM("storyboard_invalid",`Storyboard "${e.storyboard}" cannot be verified: ${s.error}`);if(s.isRoute)throw new iM("storyboard_unsupported",`Storyboard "${e.storyboard}" is a route storyboard; VRT stability verification supports component and local HTML storyboards.`);if(s.isHtml&&!s.filepath)throw new iM("storyboard_invalid",`HTML storyboard "${e.storyboard}" requires a literal local filepath for VRT.`);if(!s.vrt||!s.vrtConfig)throw new iM("storyboard_not_tested",`Storyboard "${e.storyboard}" is not VRT-tested. Add a literal vrt prop before verifying stability.`);if(s.vrtConfig.skip)throw new iM("storyboard_paused",`Storyboard "${e.storyboard}" is paused with vrt={{ skip: true }}. Remove skip before verifying it as an active test.`);const i=void 0!==s.layout.width&&void 0!==s.layout.height?s.layout.width*s.layout.height:null;if(null!==i&&ignoredStoryboardArea(s.vrtConfig.ignore??[],s.layout.width,s.layout.height)>=.9*i)throw new iM("storyboard_invalid",`Storyboard "${e.storyboard}" has vrt.ignore masking at least 90% of its area; VRT rejects this configuration.`);return{canvasFile:toPosix4(BN.relative(e.workspaceRoot,t)),canvasSlug:toPosix4(BN.relative(absoluteCanvasesRoot(e.workspaceRoot,e.canvasesDir),BN.dirname(t))),storyboardId:s.storyboardKey??s.exportName,layout:{width:s.layout.width,height:s.layout.height},vrt:s.vrtConfig}}function maskRegion(e,t){const n=Math.max(0,Math.floor(t.x)),r=Math.max(0,Math.floor(t.y)),s=Math.min(e.width,Math.ceil(t.x+t.w)),i=Math.min(e.height,Math.ceil(t.y+t.h));for(let t=r;t<i;t+=1)for(let r=n;r<s;r+=1){const n=e.width*t+r<<2;e.data[n]=0,e.data[n+1]=0,e.data[n+2]=0,e.data[n+3]=255}}function findDiffBounds(e){let t=e.width,n=e.height,r=-1,s=-1;for(let i=0;i<e.height;i+=1)for(let o=0;o<e.width;o+=1)0!==e.data[3+(e.width*i+o<<2)]&&(t=Math.min(t,o),n=Math.min(n,i),r=Math.max(r,o),s=Math.max(s,i));return r<t||s<n?null:{x:t,y:n,width:r-t+1,height:s-n+1}}function unionBounds(e,t){if(!e)return t;if(!t)return e;const n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),s=Math.max(e.x+e.width,t.x+t.width),i=Math.max(e.y+e.height,t.y+t.height);return{x:n,y:r,width:s-n,height:i-r}}function decodeCapture(e){const t=nM.PNG.sync.read(Buffer.from(e.pngBase64,"base64"));if(t.width!==e.width||t.height!==e.height)throw new Error(`Capture metadata ${e.width}x${e.height} does not match decoded PNG ${t.width}x${t.height}.`);return t}function ignoreRegionScale(e,t,n){if(void 0===t.width||void 0===t.height){const e=n??yO;return{scaleX:e,scaleY:e}}return{scaleX:e.width/t.width,scaleY:e.height/t.height}}function compareCaptureToBaseline(e,t,n,r){const s=decodeCapture(t);if(s.width!==e.width||s.height!==e.height){const r=Math.max(e.width,s.width),i=Math.max(e.height,s.height),o=new nM.PNG({width:r,height:i});for(let e=0;e<o.data.length;e+=4)o.data[e]=217,o.data[e+1]=70,o.data[e+2]=239,o.data[e+3]=255;return{diff:o,comparison:{run:n,baselineRun:1,...t.condition?{condition:t.condition}:{},diffPixels:s.width*s.height,diffRatio:1,diffBounds:{x:0,y:0,width:r,height:i},dimensions:{width:s.width,height:s.height},dimensionChange:{baseline:{width:e.width,height:e.height},candidate:{width:s.width,height:s.height}}}}}const{scaleX:i,scaleY:o}=ignoreRegionScale(e,r.layout,t.captureScale);for(const e of r.ignore){const t={x:e.x*i,y:e.y*o,w:e.w*i,h:e.h*o};maskRegion(s,t)}const{diff:a,diffPixels:c}=matchPixels(e,s,r.threshold);return{diff:a,comparison:{run:n,baselineRun:1,...t.condition?{condition:t.condition}:{},diffPixels:c,diffRatio:c/(e.width*e.height),diffBounds:findDiffBounds(a),dimensions:{width:s.width,height:s.height}}}}function matchPixels(e,t,n){const r=new nM.PNG({width:e.width,height:e.height}),s=pixelmatch(e.data,t.data,r.data,e.width,e.height,{threshold:n,includeAA:!1,diffMask:!0,diffColor:[217,70,239]});return{diff:r,diffPixels:s}}function maskedDiffRatios(e,t,n,r=rM){const s=decodeCapture(e),i=decodeCapture(t),o=decodeCapture(n),sameSize=e=>e.width===s.width&&e.height===s.height;if(!sameSize(o))return{diffRatio:1,unstableRatio:0};if(!sameSize(i))return{diffRatio:0,unstableRatio:1};const a=matchPixels(s,i,r).diff.data,c=matchPixels(s,o,r).diff.data,l=s.width*s.height;let d=0,u=0;for(let e=0;e<l;e++){const t=4*e+3;a[t]>0?d++:c[t]>0&&u++}return{diffRatio:u/l,unstableRatio:d/l}}function mergeDiffImage(e,t){const n=Math.max(e?.width??0,t.width),r=Math.max(e?.height??0,t.height),s=e&&e.width===n&&e.height===r?e:new nM.PNG({width:n,height:r}),merge=e=>{for(let t=0;t<e.height;t+=1)for(let r=0;r<e.width;r+=1){const i=e.width*t+r<<2;if(0===e.data[i+3])continue;const o=n*t+r<<2;s.data[o]=217,s.data[o+1]=70,s.data[o+2]=239,s.data[o+3]=255}};return e&&s!==e&&merge(e),merge(t),s}function downscaleDiffMaskToFit(e,t){if(e.width<=t&&e.height<=t)return e;const n=Math.min(t/e.width,t/e.height),r=Math.max(1,Math.min(t,Math.round(e.width*n))),s=Math.max(1,Math.min(t,Math.round(e.height*n))),i=new nM.PNG({width:r,height:s});for(let t=0;t<s;t+=1){const n=Math.floor(t*e.height/s),o=Math.max(n+1,Math.ceil((t+1)*e.height/s));for(let s=0;s<r;s+=1){const a=Math.floor(s*e.width/r),c=Math.max(a+1,Math.ceil((s+1)*e.width/r));let l=!1;for(let t=n;t<o&&!l;t+=1)for(let n=a;n<c;n+=1){const r=e.width*t+n<<2;if(0!==e.data[r+3]){l=!0;break}}if(!l)continue;const d=r*t+s<<2;i.data[d]=217,i.data[d+1]=70,i.data[d+2]=239,i.data[d+3]=255}}return i}function createVrtStabilityAccumulator(e){const t=e.threshold??rM,n={threshold:t,ignore:e.ignore??[],layout:e.layout};let r=null,s=null,i=0,o=0;const a=[],c=[];return{addCapture(e){if(i+=1,!0===e.retried&&(o+=1),c.push(e.condition),!r){r=decodeCapture(e);const{scaleX:t,scaleY:s}=ignoreRegionScale(r,n.layout,e.captureScale);for(const e of n.ignore)maskRegion(r,{x:e.x*t,y:e.y*s,w:e.w*t,h:e.h*s});return}const t=compareCaptureToBaseline(r,e,i,n);a.push(t.comparison),t.comparison.diffPixels>0&&(s=mergeDiffImage(s,t.diff))},get captureCount(){return i},summarize(){if(!r||i<2)throw new Error("VRT stability verification requires at least two captures.");const e=a.filter(e=>e.diffPixels>0),l=s,d=l?downscaleDiffMaskToFit(l,sM):null,u=c.every(e=>void 0!==e)?c:null,p=u?[...new Set(e.flatMap(e=>e.condition??[]))]:[];return{status:0===e.length?"stable":"unstable",vrtStable:0===e.length,conditions:u,unstableConditions:p.map(e=>({condition:e,dependsOn:UL.find(t=>t.name===e)?.dependsOn??""})),runs:i,retriedCaptures:o,threshold:t,ignoreRegions:n.ignore.length,changedRuns:e.length,maxDiffPixels:Math.max(0,...a.map(e=>e.diffPixels)),maxDiffRatio:Math.max(0,...a.map(e=>e.diffRatio)),diffBounds:a.reduce((e,t)=>unionBounds(e,t.diffBounds),null),cumulativeDiff:d&&l?{pngBase64:nM.PNG.sync.write(d).toString("base64"),width:d.width,height:d.height,sourceWidth:l.width,sourceHeight:l.height}:null,comparisons:a}}}}import{readFile as oM}from"fs/promises";import aM from"path";var cM=.005,lM=.25,dM='Record what this taught you about the project, one line per finding, under `## Responsive storyboards` in both `tempo/CLAUDE.md` and `tempo/AGENTS.md`, creating the section or the file when it is missing: the component or pattern, and whether storyboards of it need `responsive`. For example: "`AppShell` collapses its sidebar with `useMediaQuery`: storyboards of it narrower than 1024 need `responsive`." or "`Card` layouts are CSS only: no check needed." Record only what holds for other storyboards, update a line this result contradicts, and keep the section short. Do not touch any other section of those files. Tell the user what you recorded.',uM={unstable:()=>"Most of this storyboard changes by itself between captures (time, data or animation), so the check cannot compare it. Nothing to do.",not_component:()=>"This is not a component storyboard, so it cannot use `responsive`. Route and HTML storyboards already render in a window of their own size. Nothing to do.",no_fidelity_window:()=>"This environment has no window that can render the storyboard at its own size, so it cannot run the check. Nothing to do.",box_too_large:e=>`The storyboard rendered at ${formatBox(e)}, over the ${BP}x${$P} limit for a window of its own size. Nothing to do.`,timed_out:()=>"The capture at the storyboard's own size did not finish in time. The storyboard may still be loading. Try the check again once."};async function runResponsivenessCheck(e,t,n,r){const s=await resolveCanvasFile({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir,canvasSlug:n.canvasSlug}),i=parsePageSource(s,await oM(s,"utf8")),o=i.storyboards.find(e=>e.storyboardKey===n.storyboard||e.exportName===n.storyboard);if(!o){const e=i.storyboards.map(e=>e.storyboardKey??e.exportName).join(", ");return failure2("storyboard_not_found",`Storyboard "${n.storyboard}" was not found.${e?` Available storyboards in the current canvas: ${e}.`:""}`)}const a=o.isRoute?"route":o.isHtml?"html":"component",c=isFidelityWindowStoryboard({kind:a,uiFramework:o.uiFramework,preview:o.preview});if(!c)return unavailableResult(n,"not_component");if(!0===o.responsive)return verdictResult(n,"already_responsive",{note:"This storyboard already has `responsive`, so it already renders in a window of its own size. Nothing to check."});t.canvasDevserver&&!e.managesDevserver&&await t.canvasDevserver.start();const l=await e.capture({canvasSlug:n.canvasSlug,canvasFile:toPosix5(aM.relative(t.workspaceRoot,s)),storyboard:n.storyboard},{signal:r});if("error"===l.kind){const e=l.availableStoryboards?.length?` Available storyboards in the current canvas: ${l.availableStoryboards.join(", ")}.`:"";return failure2(l.code,`${l.message}${e}`)}if("unavailable"===l.kind)return unavailableResult(n,l.reason,l.box);const{diffRatio:d,unstableRatio:u}=maskedDiffRatios(l.shared,l.sharedAgain??l.shared,l.ownSize),{width:p,height:m}=l.box,f=u>0?{unstable_ratio:roundRatio(u)}:{};if(u>lM)return verdictResult(n,"unavailable",{reason:"unstable",width:p,height:m,...f,note:uM.unstable(l.box)});const g={width:p,height:m,diff_ratio:roundRatio(d),...f},y=u>0?` ${formatPercent(u)} of this storyboard changes by itself between captures (time, data or animation) and was ignored.`:"";return d<=cM?verdictResult(n,"same",{...g,note:`This storyboard's JavaScript does not depend on the window size at ${p}x${m}, so it does not need \`responsive\`.${y}`,memory:!0}):verdictResult(n,"differs",{...g,note:`The first image is what the canvas shows now. The second is this storyboard in a window of its own size, ${p}x${m}. If the second is the intended look, add \`responsive\` to this storyboard, and nothing else: keep its layout as it is, with or without a size. Then screenshot it again. If the two differ only by time, data or animation, change nothing.${y}`,memory:!0},[l.shared.pngBase64,l.ownSize.pngBase64])}function verdictResult(e,t,n,r=[]){const{note:s,memory:i,...o}=n,a={canvas_slug:e.canvasSlug,storyboard:e.storyboard,verdict:t,...o},c=[JSON.stringify(a,null,2),s];return i&&c.push(dM),{content:[...r.map(e=>({type:"image",data:e,mimeType:"image/png"})),{type:"text",text:c.join("\n\n")}]}}function unavailableResult(e,t,n){return verdictResult(e,"unavailable",{reason:t,...n?{width:n.width,height:n.height}:{},note:uM[t](n)})}function failure2(e,t){return{content:[{type:"text",text:`storyboard_responsiveness_check failed [${e}]: ${t}`}],isError:!0}}function formatBox(e){return e?`${e.width}x${e.height}`:"its size"}function formatPercent(e){return`${Number((100*e).toFixed(2))}%`}function roundRatio(e){return Math.round(1e4*e)/1e4}function toPosix5(e){return e.split(aM.sep).join("/")}import{execFile as pM}from"child_process";import{access as hM,mkdir as mM,readdir as fM,readFile as gM,realpath as yM,writeFile as bM}from"fs/promises";import vM from"path";import{promisify as wM}from"util";function normalizeRepoUrl2(e){if(!e||"string"!=typeof e)return null;let t=e.trim();if(!t)return null;const n=/^[\w.-]+@([\w.-]+):([\w./-]+)$/,r=t.match(n);if(r){const e=r[1],t=r[2];return finalize2(e,t)}const s=t.match(/^[\w+.-]+:\/\/(?:[^@]+@)?([\w.-]+)\/([\w./-]+)$/);if(s){const e=s[1],t=s[2];return finalize2(e,t)}const i=t.match(/^[\w+.-]+:\/\/(?:[^@]+@)?([\w.-]+):\d+\/([\w./-]+)$/);if(i){const e=i[1].toLowerCase(),t=i[2];return finalize2(_M[e]??e,t)}return null}var _M={"altssh.bitbucket.org":"bitbucket.org","ssh.github.com":"github.com"};function finalize2(e,t){let n=t.replace(/\.git$/,"");return n=n.replace(/^\/+|\/+$/g,""),n?`${e}/${n}`.toLowerCase():null}function githubRepoFromKey2(e){const t=/^github\.com\/([^/]+)\/([^/]+)$/.exec(e);return t?`${t[1]}/${t[2]}`:null}function bitbucketRepoFromKey2(e){const t=/^bitbucket\.org\/([^/]+)\/([^/]+)$/.exec(e);return t?`${t[1]}/${t[2]}`:null}var xM="# Written by Tempo visual-review onboarding (visual_review_init). The pnpm\n# setup and the two install lines are the package-manager-specific part;\n# init rewrites them for npm / yarn / bun. Keep every\n# `npx --yes @tempo-ai/visual-review@latest …` line as it is: Tempo's own\n# repository runs these exact commands, so each release is exercised there\n# before it reaches you. The CLI comes from npm, never from this checkout;\n# the checkout's own install scripts and canvas host do run inside the job\n# (as in any CI), so treat it like your other workflows.\nname: Visual Review\n\non:\n pull_request:\n # labeled/unlabeled: the bypass label takes effect (and is revocable)\n # without pushing a new commit.\n types: [opened, synchronize, reopened, edited, labeled, unlabeled]\n push:\n # Your default branch: pushes here publish the baseline PRs compare against.\n branches: [main]\n\npermissions:\n contents: read\n # Compatibility with older CLIs during rollout; the current CLI publishes\n # all statuses through the Tempo GitHub App instead of this token.\n statuses: write\n pull-requests: write\n # GitHub OIDC is the only credential Tempo accepts. No secret is stored.\n id-token: write\n\nconcurrency:\n # A new push never queues behind a stale run. Label events get their own\n # group so an unrelated label added mid-capture cannot cancel it.\n group: visual-review-${{ github.event.pull_request.number || github.sha }}-${{ (github.event.action == 'labeled' || github.event.action == 'unlabeled') && 'label' || 'code' }}\n cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\njobs:\n # `visual-review:bypass` label — the incident escape hatch. Posts success\n # and skips capture entirely.\n bypass:\n if: >-\n github.event_name == 'pull_request'\n && contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')\n runs-on: ubuntu-latest\n timeout-minutes: 5\n steps:\n - run: npx --yes @tempo-ai/visual-review@latest report --bypass --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n # `\x3c!-- tempo-no-visual-change --\x3e` in the PR body — a 100%-certainty claim\n # that the PR changes no UI and no tested storyboard. Posts success and\n # skips capture.\n no-visual-change:\n if: >-\n github.event_name == 'pull_request'\n && !contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')\n && contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')\n runs-on: ubuntu-latest\n timeout-minutes: 5\n steps:\n - run: npx --yes @tempo-ai/visual-review@latest report --no-visual-change --pr ${{ github.event.pull_request.number }} --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n capture:\n # Pushes to the default branch, real code events without either skip\n # declaration, and bypass-label removal (to restore the real gate).\n if: >-\n !cancelled()\n && (\n github.event_name == 'push'\n || (\n contains(fromJSON('[\"opened\",\"synchronize\",\"reopened\",\"edited\"]'), github.event.action)\n && !contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')\n && !contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')\n )\n || (\n github.event.action == 'unlabeled'\n && github.event.label.name == 'visual-review:bypass'\n && !contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')\n )\n )\n runs-on: ubuntu-latest\n # A PR may first wait for another run's baseline and then render both the\n # merge-base and its own head.\n timeout-minutes: 90\n outputs:\n status_url: ${{ steps.capture.outputs.status_url }}\n steps:\n - uses: actions/checkout@v4\n with:\n # Full history: the merge-base ancestor chain is the baseline key.\n fetch-depth: 0\n # Capture the PR head, not GitHub's synthetic merge commit.\n ref: ${{ github.event.pull_request.head.sha || github.sha }}\n\n # Announces intent before dependency/browser setup so stacked PRs wait\n # on the baseline lease instead of duplicating a capture. Purely an\n # optimization, so a registry hiccup must not fail the run.\n - run: npx --yes @tempo-ai/visual-review@latest claim || echo \"::warning::capture claim announcement unavailable; capture claims after setup\"\n\n - uses: pnpm/action-setup@v4\n - uses: actions/setup-node@v4\n with:\n node-version: 24\n cache: pnpm\n - run: pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so the\n # host's dependencies are installed here, explicitly.\n - run: cd tempo && pnpm install --no-frozen-lockfile\n\n # Chromium matching the CLI's own pinned playwright, plus its shared\n # libraries on Linux.\n - run: npx --yes @tempo-ai/visual-review@latest install-browsers\n\n - uses: actions/cache@v4\n with:\n path: tempo/node_modules/.vite\n key: visual-review-vite-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }}\n\n # `capture` infers PR-vs-main, head SHA, branch, merge-base and\n # repository from GitHub's event payload and the standard GITHUB_*\n # environment, and authenticates with short-lived OIDC tokens it mints\n # itself.\n - id: capture\n run: npx --yes @tempo-ai/visual-review@latest capture --parallel 2\n env:\n # Forbid the capture's canvas-host supervisor from running package\n # manager installs or updates inside this checkout; those would\n # churn the Vite cache mid-run and rewrite lockfiles.\n TEMPO_DEVSERVER_PROTECTED_ROOTS: ${{ github.workspace }}\n\n # A finished capture has already consumed its claim; this only releases\n # a lease left behind by a setup failure or cancellation.\n - if: always()\n run: npx --yes @tempo-ai/visual-review@latest claim --release || echo \"::warning::capture claim release unavailable; the lease expires on its own\"\n\n - if: failure() && github.event_name == 'pull_request'\n run: npx --yes @tempo-ai/visual-review@latest report --fallback-failure --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n # Polls the run until Tempo has compared it, then posts the sticky PR\n # comment. Tempo's GitHub App owns every status, including declarations,\n # failures, and portal approvals — no CI re-run needed for an approval.\n report:\n needs: capture\n if: github.event_name == 'pull_request'\n runs-on: ubuntu-latest\n timeout-minutes: 20\n steps:\n - run: npx --yes @tempo-ai/visual-review@latest report --status-url \"${{ needs.capture.outputs.status_url }}\" --pr ${{ github.event.pull_request.number }} --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n # A crashed report must not strand the check at pending. Only stomps\n # pending/absent — a verdict Tempo already delivered stays.\n - if: failure()\n run: npx --yes @tempo-ai/visual-review@latest report --fallback-failure --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n",TM=" - uses: pnpm/action-setup@v4\n - uses: actions/setup-node@v4\n with:\n node-version: 24\n cache: pnpm\n - run: pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so the\n # host's dependencies are installed here, explicitly.\n - run: cd tempo && pnpm install --no-frozen-lockfile\n",kM=" - uses: actions/cache@v4\n with:\n path: tempo/node_modules/.vite\n key: visual-review-vite-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }}\n",SM=" branches: [main]",EM="10",AM={pnpm:"pnpm-lock.yaml",npm:"package-lock.json",yarn:"yarn.lock",bun:"bun.lock"};function isValidGitBranchName(e){return!(!e||e.length>255)&&(!/[\x00-\x20\x7f~^:?*[\\]/.test(e)&&(!(e.includes("..")||e.includes("@{")||e.includes("//"))&&(!(e.startsWith("-")||e.startsWith("/")||e.endsWith("/"))&&(!e.endsWith(".")&&!e.endsWith(".lock")&&e.split("/").every(e=>e.length>0&&!e.startsWith(".")&&!e.endsWith(".lock"))))))}function yamlBranchScalar(e){const t=e.replace(/[\\*?+[\]!]/g,"\\$&"),n=/^[A-Za-z0-9_./-]+$/.test(t)&&!/^(true|false|yes|no|on|off|null|y|n)$/i.test(t)&&!/^[-+.]?\d/.test(t);return n?t:`'${t.replace(/'/g,"''")}'`}function rootInstallCommand(e,t){switch(e){case"pnpm":return t?"pnpm install --frozen-lockfile":"pnpm install --no-frozen-lockfile";case"npm":return t?"npm ci":"npm install";case"yarn":return"yarn install";case"bun":return t?"bun install --frozen-lockfile":"bun install"}}function hostInstallCommand(e){switch(e){case"pnpm":return"pnpm install --no-frozen-lockfile";case"npm":return"npm install";case"yarn":return"yarn install";case"bun":return"bun install"}}function setupSteps(e,t,n,r){const s=r?`node-version-file: ${r}`:"node-version: 24",nodeSetup=e=>` - uses: actions/setup-node@v4\n with:\n ${s}\n${e?` cache: ${e}\n`:""}`;switch(e){case"pnpm":return` - uses: pnpm/action-setup@v4\n${n?"":` with:\n # No \`packageManager\` field in package.json to read the version from.\n version: ${EM}\n`}${nodeSetup(t?"pnpm":null)}`;case"npm":return nodeSetup(t?"npm":null);case"yarn":return`${nodeSetup(t?"yarn":null)}${n?" - run: corepack enable\n":""}`;case"bun":return` - uses: oven-sh/setup-bun@v2\n${nodeSetup(null)}`}}function skipRootInstall(e,t){return!1===e.hasRootPackage&&"."!==t}function hostDirComment(e){return"."===e?"":` # The canvas host under \`${e}/\` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so the\n # host's dependencies are installed here, explicitly.\n`}function runBlockStep(e){const t=e.map(e=>` ${e}`).join("\n");return` - run: |\n${t}\n`}function renderVisualReviewWorkflow(e){const{packageManager:t,hasLockfile:n}=e,r=e.tempoDir.replace(/\\/g,"/").replace(/\/+$/,"")||".";if("."!==r&&!/^[A-Za-z0-9_./-]+$/.test(r))throw new Error(`Unsupported canvas-host directory name: ${e.tempoDir}`);const s=e.defaultBranch.trim();if(!isValidGitBranchName(s))throw new Error(`Unsupported default branch name: ${JSON.stringify(e.defaultBranch)}`);for(const[e,t]of[["install block",TM],["cache block",kM],["branch line",SM]])if(!xM.includes(t))throw new Error(`visual-review workflow template no longer contains the ${e} the renderer rewrites`);const i=e.hasPackageManagerField??!1,o=e.lockfile?.trim()||AM[t];if(!/^[A-Za-z0-9_.-]+$/.test(o))throw new Error(`Unsupported lockfile name: ${o}`);const a=(e.customInstall??"").replace(/\r\n?/g,"\n").split("\n").map(e=>e.trimEnd()).filter(e=>e.trim().length>0),c=a.length>0?` # Your tempo.config.json scripts.install, run from \`${r}/\` exactly as\n # Tempo's own canvas host runs it. It must install BOTH the project root\n # and the canvas host.\n${runBlockStep(a.map((e,t)=>0===t&&"."!==r?`cd ${r} && ${e}`:e))}`:`${skipRootInstall(e,r)?"":` - run: ${rootInstallCommand(t,n)}\n`}${hostDirComment(r)}${"."===r?"":` - run: cd ${r} && ${hostInstallCommand(t)}\n`}`,l=`${setupSteps(t,n,i,e.nodeVersionFile)}${c}`,d="."===r?"node_modules/.vite":`${r}/node_modules/.vite`,u=` - uses: actions/cache@v4\n with:\n path: ${d}\n key: visual-review-vite-\${{ runner.os }}-\${{ hashFiles('**/${o}') }}\n`;return xM.replace(TM,l).replace(kM,u).replace(SM,` branches: [${yamlBranchScalar(s)}]`)}function analyzeExistingWorkflow(e,t){const n=e.split("\n").filter(e=>!/^\s*#/.test(e)).join("\n"),r=/@tempo-ai\/visual-review@[^\s"']+[ \t]+claim(?=[ \t]*(?:$|[|&;#'"]))/m.test(n.replace(/\\\r?\n[ \t]*/g," ")),s=[],push2=e=>s.push(e);/id-token:\s*write/.test(n)||push2({code:"missing_id_token_write",message:"The workflow does not grant `id-token: write`.",fix:"Add `id-token: write` under `permissions:` — GitHub OIDC is the only credential Tempo's ingest accepts; without it every upload is rejected with 401."});const i=[["statuses: write",/statuses:\s*write/],["pull-requests: write",/pull-requests:\s*write/],["contents: read",/contents:\s*(read|write)/]].filter(([,e])=>!e.test(n)).map(([e])=>e);i.length>0&&push2({code:"missing_permissions",message:`The workflow does not grant ${i.join(", ")}.`,fix:"Under `permissions:` grant `contents: read` (checkout), `statuses: write` (compatibility with older CLI releases) and `pull-requests: write` (the sticky report comment). Current releases publish statuses through the Tempo GitHub App."}),workflowHasPullRequestTrigger(n)||push2({code:"missing_pull_request_trigger",message:"The workflow does not run on pull requests.",fix:"Add a `pull_request:` trigger with `types: [opened, synchronize, reopened, edited, labeled, unlabeled]` — PR runs are what get captured, compared and gated."});const o=t.defaultBranch;workflowRunsOnPushTo(n,o)||push2({code:"missing_default_branch_push",message:`The workflow does not run on pushes to \`${o}\`.`,fix:`Add a \`push: { branches: [${o}] }\` trigger — pushes to the default branch publish the baselines every PR compares against; without them each PR reports everything as new.`});const a=[...n.matchAll(/@tempo-ai\/visual-review@([^\s"']+)/g)];if(0===a.length)push2({code:"not_using_published_cli",message:"The workflow does not call `npx --yes @tempo-ai/visual-review@…`.",fix:"Run capture through the published CLI (`npx --yes @tempo-ai/visual-review@latest capture --parallel 2`); it infers every run parameter from the Actions environment and mints its own OIDC tokens."});else{const e=new Set(a.map(e=>e[1])),acceptable=e=>"latest"===e||/^\d+(\.\d+){0,2}$/.test(e),t=[...e].filter(e=>!acceptable(e));t.length>0&&push2({code:"unpinned_or_prerelease_cli",message:`The CLI is pinned to ${t.map(e=>`@${e}`).join(", ")}.`,fix:"Pin `@tempo-ai/visual-review@latest` (or a release version); `@next` and other dist-tags track pre-release builds."}),/visual-review@[^\s"']+\s+capture\b/.test(n)||push2({code:"missing_capture_step",message:"No `capture` step runs the CLI.",fix:"Add `npx --yes @tempo-ai/visual-review@latest capture --parallel 2` (with `TEMPO_DEVSERVER_PROTECTED_ROOTS: ${{ github.workspace }}`) after the install and browser steps — without it nothing is captured or compared."}),r||push2({code:"missing_claim_step",message:"No `claim` step runs before dependency setup.",fix:"Add `npx --yes @tempo-ai/visual-review@latest claim` as the first step after checkout (and `claim --release` under `if: always()`), so stacked PRs wait on the baseline lease instead of capturing it twice."}),/visual-review@[^\s"']+\s+report\b/.test(n)||push2({code:"missing_report_step",message:"No `report` job posts the verdict and sticky PR comment.",fix:"Add a `report` job (`needs: capture`, `if: github.event_name == 'pull_request'`) running `npx --yes @tempo-ai/visual-review@latest report --status-url … --pr … --sha …`."})}n.includes("visual-review:bypass")||push2({code:"missing_bypass_guard",message:"The `visual-review:bypass` label is not honored.",fix:"Gate capture on `!contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')` and add the `bypass` job that posts success — the incident escape hatch."}),n.includes("\x3c!-- tempo-no-visual-change --\x3e")||push2({code:"missing_no_visual_change_guard",message:"The `\x3c!-- tempo-no-visual-change --\x3e` PR-body declaration is not honored.",fix:"Gate capture on `!contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')` and add the `no-visual-change` job that posts success."});const c=/state=pending/.test(n)&&/context=visual-review/.test(n);return r||c||push2({code:"missing_pending_status",message:"The workflow never posts the `visual-review` status as pending.",fix:"Add `npx --yes @tempo-ai/visual-review@latest claim` after checkout and before dependency setup; it posts pending on the PR head through the Tempo GitHub App, so every visual-review status has the same publisher."}),s}function mappingBlock(e,t){const n=e.findIndex(e=>new RegExp(`^\\s*${t}:\\s*(\\{\\s*\\}\\s*)?$`).test(e));if(-1===n)return null;const r=e[n].match(/^\s*/)[0].length,s=[];for(let t=n+1;t<e.length;t+=1){const n=e[t];if(""===n.trim())continue;const i=n.match(/^\s*/)[0].length;if(i<=r)break;s.push(n)}return s}function listEntries(e,t){const n=e.findIndex(e=>new RegExp(`^\\s*${t}:`).test(e));if(-1===n)return null;const r=e[n],s=new RegExp(`${t}:\\s*\\[([^\\]]*)\\]`).exec(r),i=[];if(s)i.push(...splitFlowSequence(s[1]));else{const t=r.match(/^\s*/)[0].length;for(let r=n+1;r<e.length;r+=1){const n=e[r],s=n.match(/^\s*/)[0].length;if(s<=t)break;const o=/^\s*-\s*(.*)$/.exec(n);o&&i.push(o[1])}}return i.map(e=>unquoteYamlScalar(e.trim()))}function splitFlowSequence(e){const t=[];let n="",r=null;for(let s=0;s<e.length;s+=1){const i=e[s];"'"!==r?'"'!==r?"'"!==i&&'"'!==i?","!==i?n+=i:(t.push(n),n=""):(r=i,n+=i):(n+=i,"\\"===i&&s+1<e.length?(s+=1,n+=e[s]):'"'===i&&(r=null)):(n+=i,"'"===i&&("'"===e[s+1]?(n+="'",s+=1):r=null))}return t.push(n),t.filter(e=>""!==e.trim())}function unquoteYamlScalar(e){return e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).replace(/''/g,"'"):e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(["\\/])/g,"$1"):e}function branchPatternToRegExp(e){let t="";for(let n=0;n<e.length;n+=1){const r=e[n];if("\\"===r&&n+1<e.length)n+=1,t+=e[n].replace(/[.\\^$|(){}[\]*+?]/g,"\\$&");else if("*"===r)"*"===e[n+1]?(t+=".*",n+=1):t+="[^/]*";else if("?"===r||"+"===r)t+=r;else if("["===r){const r=e.indexOf("]",n);-1===r?t+="\\[":(t+=`[${e.slice(n+1,r).replace(/\\/g,"\\\\")}]`,n=r)}else t+=r.replace(/[.\\^$|(){}]/g,"\\$&")}return new RegExp(`^${t}$`)}function matchesBranch(e,t){let n=!1;for(const r of e){const e=r.startsWith("!"),s=e?r.slice(1):r;if(!s)continue;let i;try{i=branchPatternToRegExp(s).test(t)}catch{i=s===t}i&&(n=!e)}return n}function workflowRunsOnPushTo(e,t){if(/^\s*on:\s*push\s*$/m.test(e))return!0;const n=/^\s*on:\s*\[([^\]]*)\]/m.exec(e);if(n&&/\bpush\b/.test(n[1]))return!0;const r=mappingBlock(e.split("\n"),"push");if(null===r)return!1;const s=listEntries(r,"branches-ignore");if(s&&matchesBranch(s,t))return!1;const i=listEntries(r,"branches");return null===i||matchesBranch(i,t)}function workflowHasPullRequestTrigger(e){if(/^\s*on:\s*pull_request\s*$/m.test(e))return!0;const t=/^\s*on:\s*\[([^\]]*)\]/m.exec(e);return!(!t||!/\bpull_request\b/.test(t[1]))||/^\s*pull_request:\s*(\{\s*\}\s*)?$/m.test(e)}var CM='# Written by Tempo visual-review onboarding (visual_review_init). Bitbucket\n# reads ONE bitbucket-pipelines.yml per repository: when you already have\n# one, merge the `tempo-visual-review` step and the two pipeline entries\n# below into it and keep your own pipelines. The corepack line and the two\n# install lines are the package-manager-specific part; init rewrites them\n# for npm / yarn / bun. Keep every `npx --yes @tempo-ai/visual-review@latest …`\n# line as it is. The CLI comes from npm, never from this checkout; the\n# checkout\'s own install scripts and canvas host do run inside the step (as\n# in any CI), so treat it like your other pipelines.\n#\n# What Bitbucket can and cannot do here:\n# - Identity: `oidc: true` gives the step a Bitbucket-signed token\n# (BITBUCKET_STEP_OIDC_TOKEN). It cannot be re-minted mid-step, so claim,\n# capture and report run in ONE step, within that token\'s lifetime.\n# - The `visual-review` build status is posted by Tempo through the\n# repository grant you authorize in Tempo (visual_review_doctor →\n# bitbucket_grant). Portal approvals update it without re-running this\n# step, and a new push needs a new approval.\n# - Reporting works on every plan. BLOCKING merges on the verdict needs the\n# Tempo custom merge check (a Bitbucket Forge app) on a plan that supports\n# custom merge checks (Premium). "Minimum successful builds" counts every\n# build status, so it is not an exact "Tempo approved" requirement.\n# - Bitbucket has no pull-request labels, so there is no bypass label. The\n# `\x3c!-- tempo-no-visual-change --\x3e` declaration in the PR description works.\n# - The sticky report comment needs a repository access token with\n# pull-request write access, stored as the secured repository variable\n# TEMPO_VISUAL_REVIEW_BITBUCKET_TOKEN. Without it the comment is skipped;\n# the build status still posts.\nimage: node:24-bookworm\n\ndefinitions:\n caches:\n tempo-vite: tempo/node_modules/.vite\n steps:\n - step: &tempo-visual-review\n name: Tempo visual review\n oidc: true\n clone:\n # Full history: the merge-base ancestor chain is the baseline key.\n depth: full\n # A PR may first wait for another run\'s baseline and then render both\n # the merge-base and its own head.\n max-time: 90\n # Chromium plus the canvas host\'s devserver need more than 4 GB.\n size: 2x\n caches:\n - tempo-vite\n script:\n # Capture the PR head commit, not a merge of the destination branch.\n - git checkout --force --detach "$BITBUCKET_COMMIT"\n # Announces intent before dependency/browser setup so stacked PRs\n # wait on the baseline lease instead of duplicating a capture.\n - npx --yes @tempo-ai/visual-review@latest claim || echo "capture claim announcement unavailable; capture claims after setup"\n - corepack enable\n - pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so\n # the host\'s dependencies are installed here, explicitly.\n - (cd tempo && pnpm install --no-frozen-lockfile)\n # Chromium matching the CLI\'s own pinned playwright, plus its shared\n # libraries.\n - npx --yes @tempo-ai/visual-review@latest install-browsers\n # `capture` infers PR-vs-main, head SHA, branch, merge-base and\n # repository from the BITBUCKET_* environment and authenticates with\n # the step\'s OIDC token. A PR whose description carries the\n # no-visual-change declaration is skipped here.\n - TEMPO_DEVSERVER_PROTECTED_ROOTS="$BITBUCKET_CLONE_DIR" npx --yes @tempo-ai/visual-review@latest capture --parallel 2\n # Polls the run until Tempo has compared it, then upserts the sticky\n # PR comment. A no-op on branch pipelines.\n - npx --yes @tempo-ai/visual-review@latest report\n after-script:\n # A finished capture has already consumed its claim; this only\n # releases a lease left behind by a setup failure.\n - npx --yes @tempo-ai/visual-review@latest claim --release || echo "capture claim release unavailable; the lease expires on its own"\n # A failed step must not strand the status at in progress. Only\n # replaces an in-progress or absent status, never a delivered verdict.\n - if [ "$BITBUCKET_EXIT_CODE" != "0" ]; then npx --yes @tempo-ai/visual-review@latest report --fallback-failure; fi\n\npipelines:\n pull-requests:\n \'**\':\n - step: *tempo-visual-review\n branches:\n # Your default branch: pushes here publish the baseline PRs compare against.\n main:\n - step: *tempo-visual-review\n',IM="bitbucket-pipelines.yml",PM="tempo-visual-review",DM="TEMPO_VISUAL_REVIEW_BITBUCKET_TOKEN",RM="node:24-bookworm",NM=" - corepack enable\n - pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so\n # the host's dependencies are installed here, explicitly.\n - (cd tempo && pnpm install --no-frozen-lockfile)\n",OM=" tempo-vite: tempo/node_modules/.vite\n",FM=" # Your default branch: pushes here publish the baseline PRs compare against.\n main:\n",LM=" name: Tempo visual review\n",MM=" ";function setupLines(e){switch(e){case"pnpm":case"yarn":return`${MM}- corepack enable\n`;case"npm":return"";case"bun":return`${MM}- npm install -g bun@1\n`}}function yamlBranchKey(e){const t=/^[A-Za-z0-9_./-]+$/.test(e)&&!/^(true|false|yes|no|on|off|null|y|n)$/i.test(e)&&!/^[-+.]?\d/.test(e);return t?e:`'${e.replace(/'/g,"''")}'`}function normalizeTempoDir(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"")||".";if("."!==t&&!/^[A-Za-z0-9_./-]+$/.test(t))throw new Error(`Unsupported canvas-host directory name: ${e}`);return t}function validatedBranch(e){const t=e.trim();if(!isValidGitBranchName(t)||/[{}]/.test(t))throw new Error(`Unsupported default branch name: ${JSON.stringify(e)}`);return t}function customInstallItem(e,t){const n=["set -e",..."."===t?[]:[`cd ${t}`],...e].map(e=>`${MM} ${e}`);return`${MM}- |\n${MM} (\n${n.join("\n")}\n${MM} )\n`}function renderBitbucketPipelines(e){const{packageManager:t,hasLockfile:n}=e,r=normalizeTempoDir(e.tempoDir),s=validatedBranch(e.defaultBranch);for(const[e,t]of[["install block",NM],["cache line",OM],["branch block",FM]])if(!CM.includes(t))throw new Error(`visual-review Bitbucket template no longer contains the ${e} the renderer rewrites`);const i=(e.customInstall??"").replace(/\r\n?/g,"\n").split("\n").map(e=>e.trimEnd()).filter(e=>e.trim().length>0),o=i.length>0?`${MM}# Your tempo.config.json scripts.install, run from \`${r}/\` exactly as\n${MM}# Tempo's own canvas host runs it, in a subshell so the directory change\n${MM}# stays out of the lines below. It must install BOTH the project root and\n${MM}# the canvas host.\n${customInstallItem(i,r)}`:`${skipRootInstall(e,r)?"":`${MM}- ${rootInstallCommand(t,n)}\n`}${"."===r?"":`${MM}# The canvas host under \`${r}/\` is its own package. Capture never\n${MM}# mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so\n${MM}# the host's dependencies are installed here, explicitly.\n${MM}- (cd ${r} && ${hostInstallCommand(t)})\n`}`,a="."===r?"node_modules/.vite":`${r}/node_modules/.vite`;return CM.replace(NM,`${setupLines(t)}${o}`).replace(OM,` tempo-vite: ${a}\n`).replace(FM,FM.replace(" main:\n",` ${yamlBranchKey(s)}:\n`))}function renderBitbucketPipelinesStepSnippet(e){const t=renderBitbucketPipelines(e),n=t.indexOf("definitions:\n");if(-1===n||!t.includes(LM))throw new Error("visual-review Bitbucket template no longer contains the definitions block the snippet is cut from");return t.slice(n).replace(LM,`${LM} # Pinned on the step so it never inherits another global image.\n image: ${RM}\n`)}function bitbucketMergeInstructions(e){return["Bitbucket reads ONE bitbucket-pipelines.yml: merge into it, never replace it, and keep the existing pipelines.",`Put the \`tempo-vite\` cache under \`definitions.caches\` and the \`&${PM}\` step under \`definitions.steps\` (create either key if missing). The anchor must appear above every \`*${PM}\` alias.`,`Add \`- step: *${PM}\` to EVERY \`pipelines.pull-requests\` pattern (add \`'**':\` if there is none): a PR runs the pattern matching its source branch, so a pattern without the step is never captured or gated.`,`Add \`- step: *${PM}\` to the \`pipelines.branches\` entry for \`${e}\` (append it to existing steps, or create the entry): default-branch pushes publish the baselines PRs compare against.`,"Keep `oidc: true`, `clone: depth: full`, and claim → installs → capture → report in this ONE step with its after-script: the step's OIDC token cannot be re-minted in a later step. Keep every `npx --yes @tempo-ai/visual-review@latest …` line as it is.","`size: 2x` (Chromium plus the devserver need more than 4 GB) doubles that step's build minutes; say so when proposing the merge."]}var UM=String.raw`@tempo-ai\/visual-review@[^\s"']+`,jM=String.raw`(?=[ \t]*(?:$|[|&;#'"]))`,BM=new RegExp(`${UM}[ \\t]+claim${jM}`,"m"),$M=new RegExp(`${UM}[ \\t]+claim[ \\t]+--release\\b`),WM=new RegExp(`${UM}[ \\t]+capture\\b`),HM=new RegExp(`${UM}[ \\t]+report\\b([^\\n]*)`,"g"),qM=new RegExp(`${UM}[ \\t]+report[ \\t]+--fallback-failure\\b`);function indentOf(e){return e.match(/^\s*/)[0].length}function joinContinuations(e){return e.replace(/\\\r?\n[ \t]*/g," ")}function hasReport(e){return[...e.matchAll(HM)].some(e=>!/--fallback-failure\b/.test(e[1]??""))}function sectionLines(e,t,n=!1){const r=new RegExp(`^${n?"":"\\s*"}${t}:\\s*$`),s=e.findIndex(e=>r.test(e));if(-1===s)return null;const i=indentOf(e[s]),o=[];for(let t=s+1;t<e.length;t+=1){const n=e[t];if(""===n.trim()){o.push(n);continue}const r=indentOf(n);if(!(r>i||r===i&&/^\s*-(\s|$)/.test(n)))break;o.push(n)}return o}function parseKey(e){const t=/^\s*(?:'((?:[^']|'')*)'|"((?:[^"\\]|\\.)*)"|([^\s'"#-][^#]*?))\s*:\s*(?:#.*)?$/.exec(e);return t?void 0!==t[1]?unquoteYamlScalar(`'${t[1]}'`):void 0!==t[2]?unquoteYamlScalar(`"${t[2]}"`):t[3]??null:null}function childEntries(e){const t=e.find(e=>""!==e.trim());if(!t)return[];const n=indentOf(t),r=[];let s=null;for(const t of e)if(""!==t.trim()){if(indentOf(t)===n&&!/^\s*-(\s|$)/.test(t)){const e=parseKey(t);s=null===e?null:{key:e,lines:[]},s&&r.push(s);continue}s?.lines.push(t)}else s?.lines.push(t);return r}function stepBlocks(e){const t=[];for(let n=0;n<e.length;n+=1){const r=/^\s*(?:-\s+)?step:\s*(?:&([A-Za-z0-9_-]+))?\s*$/.exec(e[n]);if(!r)continue;const s=e[n].indexOf("step:"),i=[];for(let t=n+1;t<e.length;t+=1){const n=e[t];if(""!==n.trim()&&indentOf(n)<=s)break;i.push(n)}t.push({anchor:r[1]??null,lines:i,text:i.join("\n")})}return t}function globSource(e){let t="";for(let n=0;n<e.length;n+=1){const r=e[n];if("*"===r)"*"===e[n+1]?(t+=".*",n+=1):t+="[^/]*";else if("?"===r)t+="[^/]";else if("{"===r){const r=e.indexOf("}",n);-1===r?t+="\\{":(t+=`(?:${e.slice(n+1,r).split(",").map(globSource).join("|")})`,n=r)}else t+=r.replace(/[.\\^$|()[\]+}]/g,"\\$&")}return t}function bitbucketGlobMatches(e,t){try{return new RegExp(`^${globSource(e)}$`).test(t)}catch{return e===t}}function analyzeExistingBitbucketPipelines(e,t){const n=e.replace(/\r\n?/g,"\n").split("\n").filter(e=>!/^\s*#/.test(e)),r=n.join("\n"),s=[],push2=e=>s.push(e),i=[...r.matchAll(/@tempo-ai\/visual-review@([^\s"']+)/g)];if(0===i.length)return[{code:"not_using_published_cli",message:"bitbucket-pipelines.yml has no step that runs `npx --yes @tempo-ai/visual-review@…`.",fix:"Merge the `tempo-visual-review` step and its two pipeline entries into this file (visual_review_init returns them as merge_proposal; it never edits an existing file). Keep the existing pipelines."}];const o=new Set(i.map(e=>e[1])),a=[...o].filter(e=>!("latest"===e||/^\d+(\.\d+){0,2}$/.test(e)));a.length>0&&push2({code:"unpinned_or_prerelease_cli",message:`The CLI is pinned to ${a.map(e=>`@${e}`).join(", ")}.`,fix:"Pin `@tempo-ai/visual-review@latest` (or a release version); `@next` and other dist-tags track pre-release builds."});const c=stepBlocks(n).filter(e=>e.text.includes("@tempo-ai/visual-review@")),l=c.length>0?c:[{anchor:null,lines:n,text:r}],d=l.filter(e=>WM.test(e.text));0===d.length&&push2({code:"missing_capture_step",message:"No step runs the CLI's `capture`.",fix:'Add `TEMPO_DEVSERVER_PROTECTED_ROOTS="$BITBUCKET_CLONE_DIR" npx --yes @tempo-ai/visual-review@latest capture --parallel 2` to the Tempo step\'s script after the install and `install-browsers` lines — without it nothing is captured or compared.'});const u=d.length>0?d:l,p=l.filter(e=>!u.includes(e)),claimStart=e=>BM.test(joinContinuations(e.text)),m=u.some(e=>!claimStart(e)),f=u.some(e=>!hasReport(e.text)),g=p.some(claimStart),y=p.some(e=>hasReport(e.text));(m&&g||f&&y)&&push2({code:"split_steps",message:"`claim`, `capture` and `report` do not all run in the same step.",fix:"Run them in ONE step with `oidc: true` (claim, installs, install-browsers, capture, report): each step gets its own OIDC token and it cannot be re-minted mid-step, so a capture claimed in one step cannot be continued or reported from another."}),m&&!g&&push2({code:"missing_claim_step",message:"No `claim` runs before dependency setup.",fix:'Add `npx --yes @tempo-ai/visual-review@latest claim || echo "capture claim announcement unavailable; capture claims after setup"` right after the `git checkout` line, so stacked PRs wait on the baseline lease instead of capturing it twice.'}),f&&!y&&push2({code:"missing_report_step",message:"No `report` runs after capture.",fix:"Add `npx --yes @tempo-ai/visual-review@latest report` after `capture` in the same step — it waits for Tempo's comparison and upserts the sticky PR comment."}),u.some(e=>!/^\s*oidc:\s*true\s*$/m.test(e.text))&&push2({code:"missing_oidc",message:"The Tempo step does not set `oidc: true`.",fix:"Add `oidc: true` to the step — the step's Bitbucket OIDC token is the only credential Tempo's ingest accepts from Pipelines; without it every upload is rejected."});const b=sectionLines(n,"clone",!0)??[],v=b.some(e=>/^\s*depth:\s*full\s*$/.test(e)),fullClone=e=>/^\s*depth:\s*full\s*$/m.test(e.text)||v&&!/^\s*depth:/m.test(e.text);u.some(e=>!fullClone(e))&&push2({code:"shallow_clone",message:"The Tempo step clones shallow history (Bitbucket's default clone depth is 50).",fix:"Add `clone:` with `depth: full` to the step — the merge-base ancestor chain is the baseline key, so a shallow clone misses baselines."});const afterScript=e=>joinContinuations((sectionLines(e.lines,"after-script")??[]).join("\n"));u.some(e=>!$M.test(afterScript(e)))&&push2({code:"missing_claim_release",message:"The step's after-script does not release the capture claim.",fix:'Under the step\'s `after-script:` add `npx --yes @tempo-ai/visual-review@latest claim --release || echo "capture claim release unavailable; the lease expires on its own"` — otherwise a setup failure holds the baseline lease until it expires.'}),u.some(e=>{const t=afterScript(e);return!qM.test(t)||!t.includes("BITBUCKET_EXIT_CODE")})&&push2({code:"missing_fallback_failure",message:"The step's after-script does not post a fallback failure when the step fails.",fix:'Under `after-script:` add `if [ "$BITBUCKET_EXIT_CODE" != "0" ]; then npx --yes @tempo-ai/visual-review@latest report --fallback-failure; fi` — otherwise a failed step leaves the `visual-review` status in progress.'});const w=l.map(e=>e.anchor).filter(e=>null!==e),runsTempoStep=e=>{const t=e.join("\n");return WM.test(t)||w.some(e=>new RegExp(`\\*${e}(?![\\w-])`).test(t))},x=childEntries(sectionLines(n,"pipelines",!0)??[]),entry=e=>x.find(t=>t.key===e),S=childEntries(entry("pull-requests")?.lines??[]),E=S.filter(e=>!runsTempoStep(e.lines));(0===S.length||E.length>0)&&push2({code:"missing_pull_request_pipeline",message:0===S.length||E.length===S.length?"No `pipelines.pull-requests` pattern runs the Tempo step.":`The pull-requests pattern(s) ${E.map(e=>`\`${e.key}\``).join(", ")} do not run the Tempo step.`,fix:`Add \`- step: *${PM}\` to every \`pipelines.pull-requests\` pattern (\`'**':\` covers every source branch) — a PR runs the pattern matching its source branch, so a pattern without the step is never captured or gated.`});const A=t.defaultBranch,C=childEntries(entry("branches")?.lines??[]),I=C.find(e=>e.key===A),P=I?[I]:C.filter(e=>bitbucketGlobMatches(e.key,A)),R=entry("default"),N=P.length>0?P.every(e=>runsTempoStep(e.lines)):void 0!==R&&runsTempoStep(R.lines);return N||push2({code:"missing_default_branch_pipeline",message:`Pushes to \`${A}\` do not run the Tempo step.`,fix:`Add \`- step: *${PM}\` to the \`pipelines.branches\` entry for \`${A}\` (create it if absent) — default-branch pushes publish the baselines every PR compares against; without them each PR reports everything as new.`}),s}var zM=wM(pM),GM="visual-review",VM=".github/workflows/visual-review.yml",KM="visual-review:bypass",XM="\x3c!-- tempo-no-visual-change --\x3e",YM=class extends Error{constructor(e,t){super(t),this.name="VisualReviewSetupError",this.code=e}};function toPosix6(e){return e.replace(/\\/g,"/")}function errorMessage2(e){return e instanceof Error?e.message:String(e)}async function exists3(e){try{return await hM(e),!0}catch{return!1}}async function assertWriteInsideRepo(e,t){const n=await yM(e);let r=vM.resolve(t);for(;!await exists3(r);){const e=vM.dirname(r);if(e===r)break;r=e}const s=await yM(r),i=vM.relative(n,s);if(i.startsWith("..")||vM.isAbsolute(i))throw new YM("path_outside_repo",`${toPosix6(vM.relative(e,t))} resolves outside the repository (${s}), so nothing was written. Replace that symlink with a real directory or file, then re-run visual_review_init.`)}async function runGit(e,t){try{const{stdout:n}=await zM("git",t,{cwd:e,timeout:1e4,maxBuffer:1048576,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}),r=n.trim();return r.length>0?r:null}catch{return null}}async function resolveRepoIdentity(e,t={}){const n=await runGit(e,["rev-parse","--is-inside-work-tree"]),r="true"===n,s=r?await runGit(e,["config","--get","remote.origin.pushurl"])??await runGit(e,["config","--get","remote.origin.url"]):null,i=normalizeRepoUrl2(s),o=i?i.split("/")[0]??null:null,a=i?githubRepoFromKey2(i):null,c=i?bitbucketRepoFromKey2(i):null;let l=null,d="assumed";if(r){const t=await runGit(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);t&&(l=t.replace(/^origin\//,""),d="origin_head")}if(!l&&a&&t.githubApi)try{const e=await t.githubApi(`repos/${a}`);"string"==typeof e.default_branch&&e.default_branch&&(l=e.default_branch,d="github")}catch{}if(!l&&c&&t.bitbucketApi)try{const e=await t.bitbucketApi({method:"GET",path:bitbucketRepoPath(c)}),n=e?.mainbranch?.name;"string"==typeof n&&n&&(l=n,d="bitbucket")}catch{}if(!l&&r)for(const t of["main","master"]){const n=await runGit(e,["rev-parse","--verify","--quiet",`refs/heads/${t}`]);if(n){l=t,d="local_branch";break}}const u=r?await runGit(e,["rev-parse","--abbrev-ref","HEAD"]):null;return{repoRoot:e,isGitRepo:r,remoteUrl:s,repoKey:i,host:o,githubRepo:a,bitbucketRepo:c,defaultBranch:l??"main",defaultBranchSource:d,currentBranch:u}}function bitbucketRepoPath(e){const[t,n]=e.split("/");return`/repositories/${encodeURIComponent(t??"")}/${encodeURIComponent(n??"")}`}async function readHostConfig(e){try{const t=await resolveTempoConfig(e);return{config:{tempoDir:t.tempoRoot,pagesDir:t.pagesDir,install:t.scripts.install,start:t.scripts.start},missing:!1,error:null}}catch(e){const t=e instanceof Error?`${e.name} ${e.message}`:String(e),n=/ConfigMissing|not found|ENOENT/i.test(t);return{config:null,missing:n,error:n?null:errorMessage2(e)}}}async function enumerateTrackedStoryboards2(e){const t=vM.resolve(e.workspaceRoot),{tempoDir:n,pagesDir:r,projectRoot:s}=await resolveCanvasHostLayout({repoRoot:t,tempoDir:e.tempoDir}),i=await enumerateTrackedStoryboards({tempoDir:n,pagesDir:r}),summarize2=e=>{const n=vM.resolve(s,e.hostCanvasPath);return{canvas_slug:toPosix6(vM.relative(r,vM.dirname(n))),canvas_file:toPosix6(vM.relative(t,n)),storyboard:e.storyboardId,name:e.name??null,threshold:e.threshold??null,ignore_regions:e.ignore?.length??0}};return{tracked:i.tracked.map(summarize2),paused:i.paused.map(summarize2),total_canvases:i.totalCanvases,total_storyboards:i.totalStoryboards,errors:i.errors.map(e=>({file:toPosix6(vM.relative(t,e.filePath)),message:e.message}))}}async function findVisualReviewWorkflow(e){const t=vM.join(e,".github","workflows");if(!await exists3(t))return null;const n=vM.join(e,VM);if(await exists3(n))return{file:VM,content:await gM(n,"utf8")};const r=(await fM(t)).filter(e=>/\.ya?ml$/i.test(e)).sort();for(const n of r){const r=vM.join(t,n),s=await gM(r,"utf8");if(s.includes("@tempo-ai/visual-review")||s.includes(`context=${GM}`))return{file:toPosix6(vM.relative(e,r)),content:s}}return null}async function findBitbucketPipelines(e){const t=vM.join(e,IM);return await exists3(t)?{file:IM,content:await gM(t,"utf8")}:null}var JM=[".gitlab-ci.yml",".circleci/config.yml","bitbucket-pipelines.yml","Jenkinsfile",".buildkite/pipeline.yml","azure-pipelines.yml"];async function classifyCiProvider(e){const t=null!==e.bitbucketRepo,n=[];for(const r of JM)t&&r===IM||await exists3(vM.join(e.repoRoot,r))&&n.push(r);return{provider:"github.com"===e.host?"github-actions":t?"bitbucket-pipelines":e.host?"unsupported":"unknown",host:e.host,workflows_dir_exists:await exists3(vM.join(e.repoRoot,".github","workflows")),other_ci_configs:n,...t?{pipelines_file_exists:await exists3(vM.join(e.repoRoot,IM))}:{}}}function unsupportedCiMessage(e){return`Visual review supports GitHub Actions (github.com) and Bitbucket Pipelines (bitbucket.org) today: ingest authenticates with that CI's OIDC token and the check is a GitHub commit status or Bitbucket build status, so a pipeline on ${e??"another host"} cannot report to Tempo yet. Tell the user, note the interest, and stop — do not hand-write a pipeline for another CI.`}var QM={bun:"bun install",pnpm:"pnpm install --no-frozen-lockfile",yarn:"yarn install",npm:"npm install"},ZM=new Map(["bun","pnpm","yarn","npm"].flatMap(e=>[[buildInstallScript(QM[e]),e],[QM[e],e],[`${e} install`,e]]));function classifyInstallScript(e,t){const n=t?.pm??"npm",r=e?.trim()??"";if(!r)return{kind:"missing",packageManager:n,customInstall:null,warning:null};const s=ZM.get(r);if(s){const e=t&&t.pm!==s?`tempo.config.json scripts.install uses ${s} but the repo's lockfile belongs to ${t.pm}; the workflow follows the install script (${s}).`:null;return{kind:"default",packageManager:s,customInstall:null,warning:e}}return{kind:"custom",packageManager:n,customInstall:r,warning:null}}var eU={pnpm:["pnpm-lock.yaml"],npm:["package-lock.json"],yarn:["yarn.lock"],bun:["bun.lock","bun.lockb"]};async function findLockfile(e,t){for(const n of eU[t])if(await exists3(vM.join(e,n)))return n;return null}async function hasPackageManagerField(e){try{const t=JSON.parse(await gM(vM.join(e,"package.json"),"utf8"));return"string"==typeof t.packageManager&&""!==t.packageManager.trim()}catch{return!1}}async function findNodeVersionFile(e){for(const t of[".nvmrc",".node-version"])try{if((await gM(vM.join(e,t),"utf8")).trim())return t}catch{}try{const t=JSON.parse(await gM(vM.join(e,"package.json"),"utf8"));if([t?.volta?.node,t?.engines?.node].some(e=>"string"==typeof e&&""!==e.trim()))return"package.json"}catch{}}var tU="GitHub CLI (`gh`) is not installed or not authenticated on this machine, so branch protection could not be read.";async function readRequiredCheck(e,t,n,r={}){const s=[],record=(e,t,n)=>{t&&s.push({context:t,app_id:n??null,source:e})},i=[],o=[],a=encodeURIComponent(n),unavailable2=()=>({ok:null,required:[],sources:[],reason:tU});try{const n=await e(`repos/${t}/rules/branches/${a}`);i.push("rulesets");for(const e of Array.isArray(n)?n:[])if("required_status_checks"===e.type)for(const t of e.parameters?.required_status_checks??[])record("rulesets",t.context,t.integration_id)}catch(e){const t=e;if(t.unavailable)return unavailable2();o.push(`rulesets read failed (${t.status??"error"})`)}let c=null;try{const n=await e(`repos/${t}/branches/${a}`);c="boolean"==typeof n.protected?n.protected:null}catch(e){const t=e;if(t.unavailable)return unavailable2();o.push(`branch read failed (${t.status??"error"})`)}if(!1===c)i.push("branch_protection");else if(!0===c)try{const n=await e(`repos/${t}/branches/${a}/protection/required_status_checks`);if(i.push("branch_protection"),n.checks&&n.checks.length>0)for(const e of n.checks)record("branch_protection",e.context,e.app_id);else for(const e of n.contexts??[])record("branch_protection",e,null)}catch(e){const t=e;if(t.unavailable)return unavailable2();o.push(403===t.status||404===t.status?"the branch is protected but classic protection details are readable only by repo admins":`branch protection read failed (${t.status??"error"})`)}const l=s.filter(e=>e.context===GM),satisfiable=e=>null===e.app_id||null!==r.tempoAppId&&void 0!==r.tempoAppId&&e.app_id===r.tempoAppId;if(l.length>0&&l.every(satisfiable))return{ok:!0,required:s,sources:i,reason:null};if(l.length>0)return{ok:!1,required:s,sources:i,reason:"bound_to_single_app"};const d=2===i.length;return{ok:!d&&null,required:s,sources:i,reason:d?null:o.join("; ")||"unreadable"}}var nU=["canvas_host","tracked_storyboards","ci_provider","workflow","repo_registered","github_app","required_check","first_run"],rU=["repo_registered","ci_provider","canvas_host","tracked_storyboards","workflow","github_app","first_run","required_check"],sU="This repo isn't connected as a Tempo project in your org. Connect it (Home → Connect your codebase) using the same GitHub URL as `git remote get-url origin`, then re-run visual_review_doctor. Registration is the org opt-in — nothing else needs minting — and nothing below it is worth doing first.",iU=["canvas_host","tracked_storyboards","ci_provider","workflow","repo_registered","bitbucket_grant","merge_enforcement","first_run"],oU=["repo_registered","ci_provider","canvas_host","tracked_storyboards","workflow","bitbucket_grant","first_run","merge_enforcement"],aU=new Set(["merge_enforcement"]),cU="This repo isn't connected as a Tempo project in your org. Connect it (Home → Connect your codebase) using the same Bitbucket URL as `git remote get-url origin`, then re-run visual_review_doctor. Registration is the org opt-in, and nothing below it is worth doing first.";function bitbucketGrantFix(e,t){const n="Why: Tempo posts the `visual-review` build status and verifies PR heads with that grant, so without it portal approvals never reach Bitbucket and the status never turns green.";return t?`The repository grant for ${e} exists, but its Bitbucket connection${t.username?` (${t.username})`:""} is no longer active. Reconnect Bitbucket in Tempo (Settings → Connections → Bitbucket) with an account that has write access to ${e}, then re-run visual_review_init — it re-authorizes the repository with that account. ${n} Re-run visual_review_doctor afterwards.`:`Tempo is not authorized to post visual-review statuses on ${e}. With the user's yes, run visual_review_init: it checks that the Bitbucket account connected to Tempo can write to ${e} and authorizes the repository with it (connect one first in Settings → Connections → Bitbucket if needed). ${n} Re-run visual_review_doctor afterwards.`}function mergeEnforcementFix(e){return`Reporting works on every Bitbucket plan: the \`${GM}\` build status posts on each PR head through the repository grant (bitbucket_grant). BLOCKING merges on the verdict needs the Tempo custom merge check (a Bitbucket Forge app) installed on the workspace and enabled for merges into ${e}, on a plan that supports custom merge checks (Bitbucket Premium). Tempo cannot read whether it is installed, so this row is advisory and does not affect \`ready\`. Do not substitute "Minimum successful builds": it counts every build status on the commit, not Tempo's verdict, so it is not an exact "Tempo approved" requirement. Set up enforcement only after the first capture has reached Tempo, or every PR blocks on a status that never posts.`}var lU={github:{publishWarning:"The commit-status publisher's newest attempt failed, so the GitHub check may be stale — usually the Tempo GitHub App is not installed on the repo (see github_app).",captureFailed:"A capture reached Tempo but the newest run/claim failed. Read the workflow logs (the install step first — the same failure modes as the canvas host), fix the cause, and push again.",noCapture:"No capture has reached Tempo yet. Open a PR (or push to the default branch) with the workflow in place; the check posts pending and a capture claim lands here within about a minute of the push. The full capture and comparison take roughly ten more minutes."},bitbucket:{publishWarning:"The build-status publisher's newest attempt failed, so the Bitbucket `visual-review` status may be stale — usually the repository grant is missing or its Bitbucket connection expired (see bitbucket_grant).",captureFailed:"A capture reached Tempo but the newest run/claim failed. Read the pipeline's step log (the install lines first — the same failure modes as the canvas host), fix the cause, and push again.",noCapture:"No capture has reached Tempo yet. Open a PR (or push to the default branch) with the Tempo step in bitbucket-pipelines.yml and Pipelines enabled for the repository; the `visual-review` build status goes in progress and a capture claim lands here within about a minute of the push. The full capture and comparison take roughly ten more minutes."}};async function safeCheck(e,t){try{return await t()}catch(t){return{id:e,ok:null,reason:"check_failed",error:errorMessage2(t),fix:`The ${e} check itself failed (see error); fix the cause or re-run visual_review_doctor. No other row depends on it.`}}}async function runVisualReviewDoctor(e,t={}){const n=vM.resolve(t.repoRoot??e.workspaceRoot),r=await resolveRepoIdentity(n,{githubApi:e.githubApi,bitbucketApi:e.bitbucketApi}),s=null!==r.bitbucketRepo,i=await readHostConfig(n),o=new Map;let a;o.set("canvas_host",await safeCheck("canvas_host",async()=>{if(!i.config)return{id:"canvas_host",ok:!1,...i.error?{error:i.error}:{},fix:i.missing?"No tempo/tempo.config.json — the canvas host does not exist yet. Call canvas_project_init, then review its install script against this repo (initial_tempo_config + review_notes).":"tempo/tempo.config.json exists but could not be read (see error). Fix the config (canvas_validate reports host_setup_issue details), then re-run visual_review_doctor."};const e="string"==typeof i.config.install&&i.config.install.trim().length>0&&"string"==typeof i.config.start&&i.config.start.trim().length>0;return{id:"canvas_host",ok:e,tempo_dir:toPosix6(vM.relative(n,i.config.tempoDir))||".",canvases_dir:toPosix6(vM.relative(n,i.config.pagesDir)),install:i.config.install,start:i.config.start,...e?{}:{fix:"tempo.config.json is missing scripts.install or scripts.start. Call canvas_project_init, then review its install script against this repo (initial_tempo_config + review_notes)."}}})),o.set("tracked_storyboards",await safeCheck("tracked_storyboards",async()=>{const e=await enumerateTrackedStoryboards2({workspaceRoot:n}),t=e.tracked.length>0&&0===e.errors.length;return{id:"tracked_storyboards",ok:t,count:e.tracked.length,paused:e.paused.length,total_storyboards:e.total_storyboards,total_canvases:e.total_canvases,tracked:e.tracked.slice(0,50),...e.tracked.length>50?{tracked_truncated:e.tracked.length-50}:{},errors:e.errors,...t?{}:{fix:e.errors.length>0?`${e.errors.length} canvas file(s) carry tracking intent the capture cannot honor (listed in errors); fix each declaration — CI enumeration fails loudly on them rather than shrinking the tracked set.`:0===e.total_storyboards?"No storyboards exist yet, so nothing can be tracked. Author a canvas that renders real production components (design-system boards are the best first candidates), then track it with canvas_set_vrt and verify with canvas_verify_vrt.":"Nothing is tracked. Track a small first set with canvas_set_vrt (component storyboards only — design-system boards are the best first candidates; route storyboards such as the home canvas cannot be tracked) and verify each with canvas_verify_vrt until it reports vrt_stable."}}})),o.set("ci_provider",await safeCheck("ci_provider",async()=>{const e=await classifyCiProvider(r),t="github-actions"===e.provider||"bitbucket-pipelines"===e.provider;return{id:"ci_provider",ok:t,provider:e.provider,host:e.host,workflows_dir_exists:e.workflows_dir_exists,other_ci_configs:e.other_ci_configs,...void 0!==e.pipelines_file_exists?{pipelines_file_exists:e.pipelines_file_exists}:{},...t?{}:"unknown"===e.provider?{reason:r.isGitRepo?"no_git_remote":"not_a_git_repo",fix:r.isGitRepo?"The repo has no `origin` remote. Push it to GitHub or Bitbucket Cloud and add the remote — visual review keys everything (registration, ingest, the check) on the hosted repository.":"This folder is not a git repository. Initialize it and push it to GitHub or Bitbucket Cloud first."}:{reason:"unsupported_ci",fix:unsupportedCiMessage(e.host)}}})),o.set("workflow",await safeCheck("workflow",async()=>{if(s)return bitbucketWorkflowCheck(n,r.defaultBranch);const e=await findVisualReviewWorkflow(n),t=e?analyzeExistingWorkflow(e.content,{defaultBranch:r.defaultBranch}):[];return{id:"workflow",ok:null!==e&&0===t.length,file:e?.file??null,drift:t,...e?0===t.length?{}:{fix:`${e.file} exists but drifts from the contract: ${t.map(e=>e.code).join(", ")}. Never rewrite the user's workflow wholesale — propose the exact edits from each drift item's fix.`}:{fix:"Call visual_review_init."}}}));let c=null;if(r.repoKey&&e.visualReviewSetup)try{a=await e.visualReviewSetup.getSetupStatus({repoKey:r.repoKey})}catch(e){c=errorMessage2(e)}const l=r.repoKey?e.visualReviewSetup?c?"convex_error":null===a?"not_signed_in":null:"unavailable_in_environment":"no_git_remote";o.set("repo_registered",{id:"repo_registered",ok:l?null:Boolean(a?.registered),...l?{reason:l,...c?{error:c}:{},fix:"no_git_remote"===l?"Registration keys on the `origin` remote URL — add one first.":"unavailable_in_environment"===l?"Registration can only be checked from a signed-in Tempo session (the desktop app); this environment has no Tempo auth.":"not_signed_in"===l?"Sign in to Tempo, then re-run visual_review_doctor.":"Tempo could not be reached; retry visual_review_doctor."}:a?.registered?{org:a.orgName,organization_id:a.organizationId,project:a.projectName,org_project_id:a.orgProjectId}:{fix:s?cU:sU}}),s&&(o.set("bitbucket_grant",await safeCheck("bitbucket_grant",()=>bitbucketGrantCheck(e,r,a))),o.set("merge_enforcement",{id:"merge_enforcement",ok:null,reason:"not_verifiable",advisory:!0,reporting:"build_status_on_every_plan",blocking:"requires_tempo_merge_check",fix:mergeEnforcementFix(r.defaultBranch)}));let d=null;s||o.set("github_app",await safeCheck("github_app",async()=>{if(!r.githubRepo||!e.visualReviewSetup||!a?.registered)return{id:"github_app",ok:null,reason:r.githubRepo?e.visualReviewSetup?"requires_registration":"unavailable_in_environment":"not_a_github_repo",fix:r.githubRepo?e.visualReviewSetup?"Resolve repo_registered first; the installation probe is gated on registration.":"The GitHub App installation can only be checked from a signed-in Tempo session.":"The Tempo GitHub App only applies to github.com repositories."};let t,n=null;if(e.githubApi)try{await e.githubApi(`repos/${r.githubRepo}`)}catch(e){const t=e;if(403===t.status||404===t.status)return{id:"github_app",ok:null,reason:"repo_not_readable_as_user",fix:`The GitHub account \`gh\` is signed in as cannot read ${r.githubRepo} (HTTP ${t.status}), so the installation was not probed. If that is the wrong account, switch with \`gh auth status\` / \`gh auth switch\`; otherwise check the remote URL and your access, then re-run visual_review_doctor.`};n=t.unavailable?"The user-side GitHub read was skipped (gh unavailable); the probe relied on Tempo registration alone.":`The user-side GitHub read failed transiently (${t.status??errorMessage2(e)}); the probe relied on Tempo registration alone.`}try{t=await e.visualReviewSetup.probeGithubApp({repoKey:r.repoKey})}catch(e){t={status:"error",reason:errorMessage2(e),retryable:!0}}"installed"!==t.status&&"not_installed"!==t.status||(d=t.appId);const s=githubAppCheck(t,r.githubRepo);return n?{...s,warning:n}:s})),s||o.set("required_check",await safeCheck("required_check",async()=>{const t=`Settings → Branches → ${r.defaultBranch} → Require status checks to pass → add \`${GM}\` with source "Any source" (or the Tempo Labs AI app; never GitHub Actions) — needs repo admin; Tempo never changes repo settings for you. Do this only after the first capture has reached Tempo, or every PR blocks on a check that never posts.`;if(!r.githubRepo)return{id:"required_check",ok:null,reason:"not_a_github_repo",fix:"Branch protection applies to github.com repositories only."};if(!e.githubApi)return{id:"required_check",ok:null,reason:"unavailable_in_environment",fix:`Could not read branch protection (no GitHub read in this environment). Make \`${GM}\` a required status check: ${t}`};const n=await readRequiredCheck(e.githubApi,r.githubRepo,r.defaultBranch,{tempoAppId:d});return{id:"required_check",ok:n.ok,required:n.required,sources:n.sources,...n.reason?{reason:n.reason}:{},...n.ok?{}:"bound_to_single_app"===n.reason?{fix:`\`${GM}\` is required but bound to a GitHub App that is not Tempo's, so the verdict Tempo posts (from the Tempo Labs AI app) never satisfies it and the requirement can never turn green. Edit the rule: ${t}`}:{fix:`Make \`${GM}\` a required status check: ${t}`}}})),o.set("first_run",await safeCheck("first_run",async()=>{if(l||!a?.registered)return{id:"first_run",ok:null,reason:l??"requires_registration",fix:"Runs are looked up by repo registration; resolve repo_registered first."};const e=s?lU.bitbucket:lU.github,t=a.latestRun,n=a.latestClaim,r=null!==t||null!==n,i=null!==t&&"error"!==t.state||null!==n&&"failed"!==n.state;return{id:"first_run",ok:i,reached_tempo:r,latest_run:t?{created_at:t.createdAt,completed_at:t.completedAt,trigger:t.trigger,state:t.state,tracked_total:t.trackedTotal,counts:t.counts,gate_satisfied:t.gateSatisfied,approvals_needed:t.approvalsNeeded,gate_satisfied_at:t.gateSatisfiedAt,publish_failing:t.publishFailing}:null,latest_claim:n?{created_at:n.createdAt,updated_at:n.updatedAt,state:n.state}:null,...t?.publishFailing?{warning:e.publishWarning}:{},...i?{}:{reason:r?"capture_failed":"no_capture_yet",fix:r?e.captureFailed:e.noCapture}}}));const u=(s?iU:nU).map(e=>o.get(e)),p=(s?oU:rU).map(e=>o.get(e)).find(e=>!1===e.ok),m=u.filter(e=>!aU.has(e.id)),f=m.filter(e=>null===e.ok),g=m.every(e=>!0===e.ok),y=p?.fix?p.fix:f.length>0?`Every readable check passes; ${f.map(e=>e.id).join(", ")} could not be determined here (${f.map(e=>e.reason??"unknown").join(", ")}).`:s?"Visual review is set up for this repo: tracked storyboards, the pipeline, registration, the repository grant, and a first capture are all in place. Whether merges are BLOCKED on the verdict cannot be verified from Tempo — see merge_enforcement.":"Visual review is fully set up for this repo: tracked storyboards, workflow, registration, the GitHub App, the required check, and a first capture are all in place.";return{repo_root:n,repo_key:r.repoKey,remote_url:r.remoteUrl,default_branch:r.defaultBranch,default_branch_source:r.defaultBranchSource,current_branch:r.currentBranch,org:a?.orgName??null,checks:u,ready:g,next_step:y}}async function bitbucketWorkflowCheck(e,t){const n=await findBitbucketPipelines(e),r=n?analyzeExistingBitbucketPipelines(n.content,{defaultBranch:t}):[];return{id:"workflow",ok:null!==n&&0===r.length,file:n?.file??null,drift:r,...n?0===r.length?{}:{fix:`${n.file} exists but ${r.some(e=>"not_using_published_cli"===e.code)?"has no Tempo visual-review step":`drifts from the contract: ${r.map(e=>e.code).join(", ")}`}. Never rewrite the user's pipelines file wholesale: call visual_review_init for the merge proposal (it never modifies an existing file) and propose the exact edits from each drift item's fix.`}:{fix:"Call visual_review_init."}}}async function bitbucketGrantCheck(e,t,n){const r=t.bitbucketRepo,s=e.visualReviewSetup,i=s?.getBitbucketGrant;if(!s||!i||!n?.registered)return{id:"bitbucket_grant",ok:null,reason:i?"requires_registration":"unavailable_in_environment",fix:i?"Resolve repo_registered first; the repository grant is checked against the org the repo is registered to.":"The Bitbucket repository grant can only be checked from a signed-in Tempo session (the desktop app)."};let o,a=null;if(e.bitbucketApi)try{await e.bitbucketApi({method:"GET",path:bitbucketRepoPath(r)})}catch(e){const t=e,n=t.status??("forbidden"===t.kind?403:"not_found"===t.kind?404:null);if(403===n||404===n)return{id:"bitbucket_grant",ok:null,reason:"repo_not_readable_as_user",fix:`The Bitbucket account connected to Tempo cannot read ${r} (HTTP ${n}), so the grant was not checked. If that is the wrong account, connect the right one in Tempo (Settings → Connections → Bitbucket); otherwise check the remote URL and your access, then re-run visual_review_doctor.`};a=`The user-side Bitbucket read failed (${t.status??errorMessage2(e)}); the grant check relied on Tempo registration alone.`}try{o=await i.call(s,{repoKey:t.repoKey,...n.organizationId?{organizationId:n.organizationId}:{}})}catch(e){return{id:"bitbucket_grant",ok:null,reason:"grant_check_failed",detail:errorMessage2(e),fix:"Tempo could not be reached to check the repository grant; re-run visual_review_doctor in a moment."}}const c=null===o?{id:"bitbucket_grant",ok:null,reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_doctor."}:o.authorized?{id:"bitbucket_grant",ok:!0,username:o.username??null}:{id:"bitbucket_grant",ok:!1,reason:o.grantedByUserId?"grant_inactive":"not_authorized",username:o.username??null,fix:bitbucketGrantFix(r,o.grantedByUserId?{username:o.username??null}:null)};return a?{...c,warning:a}:c}function githubAppCheck(e,t){switch(e.status){case"installed":return{id:"github_app",ok:!0,app_id:e.appId,app_slug:e.appSlug};case"not_installed":return{id:"github_app",ok:!1,reason:"app_not_installed",install_url:e.installUrl,app_id:e.appId,app_slug:e.appSlug,fix:`The Tempo GitHub App isn't installed on ${t}, so portal approvals can't update the \`${GM}\` check — the gate would stay red forever. Ask a GitHub admin of ${t.split("/")[0]} to install it${e.installUrl?`: ${e.installUrl}`:" (Tempo Labs AI, the app used to connect repos to Tempo)"} and grant it this repository. Re-run visual_review_doctor afterwards.`};case"app_unconfigured":return{id:"github_app",ok:null,reason:"app_unconfigured",detail:e.reason,fix:"This Tempo deployment has no GitHub App credentials configured (a Tempo-side issue, not yours). Approvals will not flip the check until it is fixed; continue with setup and tell the user."};case"repo_not_registered":return{id:"github_app",ok:null,reason:"requires_registration",fix:sU};case"unsupported_host":return{id:"github_app",ok:null,reason:"not_a_github_repo",fix:"The Tempo GitHub App only applies to github.com repositories."};case"error":return{id:"github_app",ok:null,reason:"probe_failed",detail:e.reason,retryable:e.retryable,fix:e.retryable?"GitHub could not be reached to check the installation; re-run visual_review_doctor in a moment.":"The installation check failed; see detail."}}}var dU="## Visual review in pull requests (VRT)",uU=`${dU}\n\nVisual changes are reviewed through **tested storyboards**, not screenshots\npasted into the PR. A tested storyboard is a \`<Storyboard>\` under the\ncanvases root carrying the literal \`vrt\` prop. On every push the Visual\nReview workflow captures the tracked set, diffs it against the baseline from\nthe default branch, and posts the \`${GM}\` commit status;\nreviewers approve the pixel diffs in Tempo's review portal and the status\nturns green without a CI re-run.\n\nEvery PR with a visual change — new features, visual bug fixes, UX\nrefinements, copy changes, canvas-only changes — must leave the changed\nsurface covered by a tested storyboard. If none renders it, add one (or add\n\`vrt\` to an existing storyboard that exercises the change) in the same PR:\nuse \`canvas_set_vrt\`, then run \`canvas_verify_vrt\` until it reports\n\`vrt_stable\` and fix any nondeterminism (live clocks, random data,\nin-flight animation) before pushing — a flaky baseline fails the check for\nevery PR after yours. When it is unclear whether a change is visual, treat\nit as visual and cover it.\n\nPut \`${XM}\` in the PR body ONLY when 100% certain\nthe PR changes no UI and no tested storyboard — no shared component, token,\nor style change, no new or modified storyboards. Any doubt means no marker:\nlet capture run and prove it. The \`${KM}\` label is the\nincident escape hatch, never part of the normal workflow.\n`,pU=`${dU}\n\nVisual changes are reviewed through **tested storyboards**, not screenshots\npasted into the PR. A tested storyboard is a \`<Storyboard>\` under the\ncanvases root carrying the literal \`vrt\` prop. On every push the Tempo\nstep in Bitbucket Pipelines captures the tracked set and diffs it against\nthe baseline from the default branch, and Tempo posts the\n\`${GM}\` build status; reviewers approve the pixel diffs in\nTempo's review portal and the status turns green without re-running the\npipeline. Approvals are per head commit, so a new push needs a new approval.\n\nEvery PR with a visual change — new features, visual bug fixes, UX\nrefinements, copy changes, canvas-only changes — must leave the changed\nsurface covered by a tested storyboard. If none renders it, add one (or add\n\`vrt\` to an existing storyboard that exercises the change) in the same PR:\nuse \`canvas_set_vrt\`, then run \`canvas_verify_vrt\` until it reports\n\`vrt_stable\` and fix any nondeterminism (live clocks, random data,\nin-flight animation) before pushing — a flaky baseline fails the status for\nevery PR after yours. When it is unclear whether a change is visual, treat\nit as visual and cover it.\n\nPut \`${XM}\` in the PR description ONLY when 100%\ncertain the PR changes no UI and no tested storyboard — no shared component,\ntoken, or style change, no new or modified storyboards. Any doubt means no\nmarker: let capture run and prove it.\n`,hU="## Visual review",mU=`${hU}\n\n\x3c!--\nVisual changes are reviewed through tested storyboards (a <Storyboard>\ncarrying the \`vrt\` prop), not evidence pasted here. Make sure the changed\nsurface is covered by one — add it in this PR if none renders it. Capture\nruns on every push; reviewers approve the pixel diffs in the Tempo review\nportal linked from the \`${GM}\` check.\n\nOnly if you are 100% certain this PR changes NO UI and NO tested storyboard:\nput Tempo's hidden no-visual-change marker (an HTML comment whose text is\nexactly "tempo-no-visual-change", spelled as in your agent rules) ABOVE this\ncomment and write: Not applicable — no storyboard changes expected.\n--\x3e\n`,fU="Review initial_workflow before committing it. The install steps mirror tempo.config.json's scripts.install and the repo's lockfile — the same failure modes as the canvas host apply because it IS the same devserver: an app in a workspace/monorepo subdirectory needs the install to run at the workspace root or with the right filter; postinstall codegen (e.g. `prisma generate`) must run before capture; a private registry needs its .npmrc/token as a repository secret exported in the workflow. If scripts.install is custom, it runs verbatim from the canvas-host directory and must cover BOTH the project root and the host. What runs: the CLI comes from npm, but the repo's own install scripts and canvas host (its Vite config, its components) execute inside the job like in any CI; fork PRs get no OIDC token and cannot ingest. The workflow captures on pushes to the default branch (the baseline producer) and on PR events; approvals happen in Tempo's portal and flip the `visual-review` status without a CI re-run. Ask before pushing: the PR that adds this workflow runs it — the merge-base has no tracked boards, so every tracked storyboard reports as new and the user approves the first set in the portal.",gU=`Review initial_workflow (or merge_proposal.snippet) before committing it. The install lines mirror tempo.config.json's scripts.install and the repo's lockfile — the same failure modes as the canvas host apply because it IS the same devserver: an app in a workspace/monorepo subdirectory needs the install to run at the workspace root or with the right filter; postinstall codegen (e.g. \`prisma generate\`) must run before capture; a private registry needs its .npmrc/token as a secured repository variable. If scripts.install is custom, it runs verbatim (in a subshell) from the canvas-host directory and must cover BOTH the project root and the host. What runs: the step uses the ${RM} image; the CLI comes from npm, but the repo's own install scripts and canvas host execute inside the step like in any CI. claim, capture and report must stay in ONE step with \`oidc: true\` — the step's OIDC token cannot be re-minted. The pipeline captures on pushes to the default branch (the baseline producer) and on pull requests; approvals happen in Tempo's portal and update the \`visual-review\` build status without re-running the pipeline. Ask before pushing: the PR that adds this pipeline runs it — the merge-base has no tracked boards, so every tracked storyboard reports as new and the user approves the first set in the portal.`;function appendSeparator(e){return 0===e.length||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}async function runVisualReviewInit(e,t={}){const n=vM.resolve(t.repoRoot??e.workspaceRoot),r=[],s=await readHostConfig(n);if(!s.config)throw new YM("no_tempo_host",s.missing?"No tempo/tempo.config.json — the canvas host does not exist yet, so there is nothing to capture. Call canvas_project_init first, review its install script, then re-run visual_review_init.":`tempo/tempo.config.json could not be read (${s.error}). Fix it (canvas_validate reports host_setup_issue details), then re-run visual_review_init.`);const i=await resolveRepoIdentity(n,{githubApi:e.githubApi,bitbucketApi:e.bitbucketApi});if(!i.repoKey)throw new YM("no_git_remote",i.isGitRepo?"The repo has no `origin` remote. Push it to GitHub or Bitbucket Cloud and add the remote first — the CI config, registration and the check all key on the hosted repository.":"This folder is not a git repository. Initialize it and push it to GitHub or Bitbucket Cloud first.");if(i.bitbucketRepo)return runBitbucketInit(e,n,s.config,i,t);if("github.com"!==i.host)throw new YM("unsupported_ci",unsupportedCiMessage(i.host));const o=toPosix6(vM.relative(n,s.config.tempoDir))||".",a=await detectOwningPackageManager(n),c=classifyInstallScript(s.config.install,a);c.warning&&r.push(c.warning),"missing"===c.kind&&r.push("tempo.config.json has no scripts.install; the workflow uses the lockfile's package manager with a default install."),"assumed"===i.defaultBranchSource&&r.push(`The default branch could not be determined (no origin/HEAD, no local main/master); the workflow assumes \`${i.defaultBranch}\`. Fix the \`push: branches\` trigger if that is wrong.`);const l=t.withAgentRules?await exists3(vM.join(n,"CLAUDE.md"))?"CLAUDE.md":await exists3(vM.join(n,"AGENTS.md"))?"AGENTS.md":null:null,d=".github/PULL_REQUEST_TEMPLATE.md";for(const e of[VM,...l?[l]:[],...t.withPrTemplate?[d]:[]])await assertWriteInsideRepo(n,vM.join(n,e));let u=await findVisualReviewWorkflow(n),p=u?.file??VM,m=!1,f=null;if(!u){const e=await findLockfile(n,c.packageManager);f=renderVisualReviewWorkflow({packageManager:c.packageManager,defaultBranch:i.defaultBranch,tempoDir:o,hasLockfile:null!==e,hasRootPackage:await exists3(vM.join(n,"package.json")),lockfile:e,hasPackageManagerField:await hasPackageManagerField(n),nodeVersionFile:await findNodeVersionFile(n),customInstall:c.customInstall});const t=vM.join(n,VM);await mM(vM.dirname(t),{recursive:!0});try{await bM(t,f,{encoding:"utf8",flag:"wx"}),m=!0}catch(e){if("EEXIST"!==e.code)throw e;f=null,u=await findVisualReviewWorkflow(n),p=u?.file??VM,r.push(`${p} appeared while init was running; it was left untouched and audited instead.`)}}const g=u?analyzeExistingWorkflow(u.content,{defaultBranch:i.defaultBranch}):[];let y=null;if(t.withAgentRules){const e=l;e?y=await appendAgentRules(n,e,uU):r.push("with_agent_rules: neither CLAUDE.md nor AGENTS.md exists at the repo root, so no agent rules were written. Ask the user which file their agents read, create it, and re-run with with_agent_rules.")}let b=null;if(t.withPrTemplate){const e=d,t=vM.join(n,e);b=await eD.withFileLock(t,async()=>{if(await exists3(t)){const n=await gM(t,"utf8");return/^##\s+Visual review\b/im.test(n)?{file:e,written:!1}:(await atomicWriteFile(t,`${n}${appendSeparator(n)}${mU}`),{file:e,written:!0})}await mM(vM.dirname(t),{recursive:!0});try{return await bM(t,`## Summary\n\n\n${mU}\n## Test plan\n\n- [ ]\n`,{encoding:"utf8",flag:"wx"}),{file:e,written:!0}}catch(t){if("EEXIST"!==t.code)throw t;return{file:e,written:!1}}})}const v=[];return u?v.push(0===g.length?`${p} already speaks the contract; nothing to write.`:`Propose the exact edits for each drift item on ${p}; never replace the file wholesale.`):v.push(`Review initial_workflow (${p}) against the repo per review_notes.`),v.push("Track a small first set of component storyboards with canvas_set_vrt and verify each with canvas_verify_vrt until vrt_stable; drop unstable boards and say why.","Commit on a branch and ask before pushing/opening the PR (a third-party-visible action). The PR proves the setup: the check goes pending within a minute and visual_review_doctor's first_run row shows the claim.",`After the first capture: approve the new storyboards in the portal, then ask a repo admin to make \`${GM}\` a required status check with source "Any source" or the Tempo Labs AI app — never GitHub Actions (Settings → Branches → ${i.defaultBranch}). Offer \`gh label create ${KM} --description "Skip visual review (incident escape hatch)"\` as a runnable command.`),{workflow_file:p,written:m,skipped:null!==u,drift:g,initial_workflow:f,package_manager:c.packageManager,install:c.kind,install_command:c.customInstall??s.config.install??null,default_branch:i.defaultBranch,default_branch_source:i.defaultBranchSource,agent_rules:y,pr_template:b,review_notes:fU,warnings:r,next_steps:v}}async function appendAgentRules(e,t,n){const r=vM.join(e,t);return eD.withFileLock(r,async()=>{const e=await gM(r,"utf8");return e.includes(dU)?{file:t,written:!1}:(await atomicWriteFile(r,`${e}${appendSeparator(e)}${n}`),{file:t,written:!0})})}var yU="Tempo posts the `visual-review` build status and verifies PR heads with that grant, so without it portal approvals never reach Bitbucket.";async function ensureBitbucketGrant(e,t){const n=t.bitbucketRepo,r=t.repoKey,s=e.visualReviewSetup;if(!s?.getBitbucketGrant||!s.authorizeBitbucketGrant||!e.bitbucketApi)return{status:"not_authorized",reason:"unavailable_in_environment",fix:"The repository grant can only be set up from a signed-in Tempo session (the desktop app). Run visual_review_init there."};let i;try{const e=await s.getSetupStatus({repoKey:r});if(null===e)return{status:"not_authorized",reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_init."};if(!e.registered)return{status:"not_authorized",reason:"requires_registration",fix:cU};i=e.organizationId??void 0;const t=await s.getBitbucketGrant.call(s,{repoKey:r,...i?{organizationId:i}:{}});if(null===t)return{status:"not_authorized",reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_init."};if(t.authorized)return{status:"authorized",newly_authorized:!1,username:t.username??null}}catch(e){return{status:"not_authorized",reason:"grant_failed",fix:`Tempo could not be reached to check the repository grant (${errorMessage2(e)}); re-run visual_review_init in a moment.`}}const[o]=n.split("/");let a=!1;try{const t=await e.bitbucketApi({method:"GET",path:`/user/workspaces/${encodeURIComponent(o)}/permissions/repositories?q=${encodeURIComponent(`repository.full_name="${n}"`)}&pagelen=10`});a=(t?.values??[]).some(e=>("write"===e.permission||"admin"===e.permission)&&e.repository?.full_name?.toLowerCase()===n.toLowerCase())}catch(e){return{status:"not_authorized",reason:"no_bitbucket_connection",fix:`Connect a Bitbucket account with write access to ${n} in Tempo (Settings → Connections → Bitbucket), then re-run visual_review_init (${errorMessage2(e)}). ${yU}`}}if(!a)return{status:"not_authorized",reason:"no_write_access",fix:`The Bitbucket account connected to Tempo has no write access to ${n}. Connect an account that does (Settings → Connections → Bitbucket) or ask a workspace admin for write access, then re-run visual_review_init. ${yU}`};try{const e=await s.authorizeBitbucketGrant.call(s,{repoKey:r,...i?{organizationId:i}:{}});if(null===e)return{status:"not_authorized",reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_init."}}catch(e){return{status:"not_authorized",reason:"grant_failed",fix:`Tempo refused the repository grant: ${errorMessage2(e)} Fix that, then re-run visual_review_init.`}}const c=await s.getBitbucketGrant.call(s,{repoKey:r,...i?{organizationId:i}:{}}).catch(()=>null);return{status:"authorized",newly_authorized:!0,username:c?.username??null}}async function runBitbucketInit(e,t,n,r,s){const i=[],o=r.bitbucketRepo,a=toPosix6(vM.relative(t,n.tempoDir))||".",c=await detectOwningPackageManager(t),l=classifyInstallScript(n.install,c);l.warning&&i.push(l.warning),"missing"===l.kind&&i.push("tempo.config.json has no scripts.install; the pipeline uses the lockfile's package manager with a default install."),"assumed"===r.defaultBranchSource&&i.push(`The default branch could not be determined (no origin/HEAD, no Bitbucket read, no local main/master); the pipeline assumes \`${r.defaultBranch}\`. Fix the \`pipelines.branches\` key if that is wrong.`);const d=await findNodeVersionFile(t);d&&i.push(`The step runs on the ${RM} image (Node 24) while this repo pins Node in ${d}. If the project cannot run on Node 24, change the image tag to a matching node image.`),s.withPrTemplate&&i.push("with_pr_template: Bitbucket has no pull-request template file, so nothing was written. Use with_agent_rules for the guidance instead. If the repository uses a default PR description, never put the literal no-visual-change marker in it — every PR opened from it would skip capture.");const u=s.withAgentRules?await exists3(vM.join(t,"CLAUDE.md"))?"CLAUDE.md":await exists3(vM.join(t,"AGENTS.md"))?"AGENTS.md":null:null;for(const e of[IM,...u?[u]:[]])await assertWriteInsideRepo(t,vM.join(t,e));const p=await findLockfile(t,l.packageManager),m={packageManager:l.packageManager,defaultBranch:r.defaultBranch,tempoDir:a,hasLockfile:null!==p,hasRootPackage:await exists3(vM.join(t,"package.json")),customInstall:l.customInstall};let f=await findBitbucketPipelines(t),g=!1,y=null;if(!f){y=renderBitbucketPipelines(m);try{await bM(vM.join(t,IM),y,{encoding:"utf8",flag:"wx"}),g=!0}catch(e){if("EEXIST"!==e.code)throw e;y=null,f=await findBitbucketPipelines(t),i.push(`${IM} appeared while init was running; it was left untouched and audited instead.`)}}const b=f?analyzeExistingBitbucketPipelines(f.content,{defaultBranch:r.defaultBranch}):[],v=f&&b.length>0?{snippet:renderBitbucketPipelinesStepSnippet(m),instructions:bitbucketMergeInstructions(r.defaultBranch)}:null;let w=null;s.withAgentRules&&(u?w=await appendAgentRules(t,u,pU):i.push("with_agent_rules: neither CLAUDE.md nor AGENTS.md exists at the repo root, so no agent rules were written. Ask the user which file their agents read, create it, and re-run with with_agent_rules."));const x=await ensureBitbucketGrant(e,r),S=[f?0===b.length?`${IM} already speaks the contract; nothing to write.`:`${IM} already exists and was NOT modified. Propose merging merge_proposal.snippet into it per merge_proposal.instructions (and each drift item's fix) as exact edits; never replace the file wholesale.`:`Review initial_workflow (${IM}) against the repo per review_notes.`,"Track a small first set of component storyboards with canvas_set_vrt and verify each with canvas_verify_vrt until vrt_stable; drop unstable boards and say why.","authorized"===x.status?`Tempo is authorized to post the \`${GM}\` build status on ${o}${x.username?` (as ${x.username})`:""}; visual_review_doctor's bitbucket_grant row confirms it.`:`The repository grant is NOT in place (${x.reason}): ${x.fix}`,`Ask a repo admin to enable Pipelines for the repository (Repository settings → Pipelines → Settings) and, for the sticky report comment, to create a repository access token with pull-request write access and store it as the SECURED repository variable ${DM} (Repository settings → Pipelines → Repository variables). Without the token the comment is skipped; the build status still posts.`,"Commit on a branch and ask before pushing/opening the PR (a third-party-visible action). The PR proves the setup: the build status goes in progress within a minute and visual_review_doctor's first_run row shows the claim.",'After the first capture: approve the new storyboards in the portal (approvals are per head commit — a new push needs a new approval). Reporting works on every plan; BLOCKING merges on the verdict needs the Tempo custom merge check (a Bitbucket Forge app) on a plan with custom merge checks (Bitbucket Premium) — never substitute "Minimum successful builds", which counts every build status. Bitbucket has no PR labels, so there is no bypass label; the no-visual-change declaration goes in the PR description.'];return{ci_provider:"bitbucket-pipelines",workflow_file:IM,written:g,skipped:null!==f,drift:b,initial_workflow:y,merge_proposal:v,package_manager:l.packageManager,install:l.kind,install_command:l.customInstall??n.install??null,default_branch:r.defaultBranch,default_branch_source:r.defaultBranchSource,agent_rules:w,pr_template:null,repository_grant:x,review_notes:gU,warnings:i,next_steps:S}}async function applyStoryboardVrt(e){let t;try{t=await resolveCanvasFile({workspaceRoot:e.workspaceRoot,canvasesDir:e.canvasesDir,canvasSlug:e.canvasSlug})}catch(e){const t=e;throw new YM("ambiguous_canvas_slug"===t.code?"ambiguous_canvas_slug":"canvas_not_found",t.message??String(e))}const n=toPosix6(vM.relative(e.workspaceRoot,t)),r=await eD.withFileLock(t,async()=>{const r=await gM(t,"utf8"),s=parseCanvasFile(t,r),i=s.errors.filter(e=>"structural"===e.kind);if(i.length>0)throw new YM("storyboard_invalid",`${n} cannot be parsed: ${i.map(e=>e.message).join("; ")}`);const o=s.storyboards.find(t=>t.storyboardKey===e.storyboard);if(!o){const t=s.storyboards.map(e=>e.storyboardKey).join(", ");throw new YM("storyboard_not_found",`Storyboard "${e.storyboard}" was not found in ${n}.${t?` Available storyboards: ${t}.`:""}`)}if("route"===o.kind)throw new YM("storyboard_unsupported",`Storyboard "${e.storyboard}" is a route storyboard; visual review tracks component and local HTML storyboards.`);if("html"===o.kind&&!o.filepath)throw new YM("storyboard_invalid",`HTML storyboard "${e.storyboard}" requires a literal local filepath for VRT.`);let a;try{a=updateStoryboardVrt({filePath:t,source:r,storyboardId:e.storyboard,tracked:e.tracked})}catch(e){throw new YM("invalid_vrt_config",errorMessage2(e))}const c=a.edits.length>0;c&&await atomicWriteFile(t,a.source);const l=parseCanvasFile(t,a.source).storyboards.find(t=>t.storyboardKey===e.storyboard);return{changed:c,vrt:l?.vrt??null}}),s=null!==r.vrt,i=Boolean(r.vrt?.skip),o=vM.isAbsolute(e.canvasesDir)?vM.resolve(e.canvasesDir):vM.resolve(e.workspaceRoot,e.canvasesDir);return{canvas_slug:toPosix6(vM.relative(o,vM.dirname(t))),canvas_file:n,storyboard:e.storyboard,tracked:s,paused:i,vrt:r.vrt,changed:r.changed,next_step:s?i?"Paused (skip: true): the storyboard rides the manifest but is neither captured nor gated. Remove skip to resume.":`Run canvas_verify_vrt({ canvas_slug: "${e.canvasSlug}", storyboard: "${e.storyboard}" }) and fix nondeterminism until it reports vrt_stable before pushing.`:"Untracked. The storyboard leaves the manifest on the next capture and reports as removed once, which a reviewer approves in the portal."}}function textResult2(e){return{content:[{type:"text",text:e}]}}function errorResult9(e){return{content:[{type:"text",text:e}],isError:!0}}async function missingNuxtAppLayer(e){if("vue"!==e.apps[0]?.uiFramework)return null;const t=e.apps[0]?.start??"";if(nuxtAppStartExtendsAppLayer(t))return null;try{if("nuxt"!==await detectProjectFramework(e))return null;const t=await resolveNuxtAppRun(e);return{extendsPath:t.appLayerPath,tempoStart:t.start}}catch{return null}}async function appDevServerStatusResult(e,t,n){if(!t)return textResult2(JSON.stringify(e,null,2));const r=await resolveTempoConfig(n).catch(()=>null),s=await verifyAppInstrumentation(e,{uiFramework:r?.apps[0]?.uiFramework,nuxtAppLayer:r?await missingNuxtAppLayer(r):null}),i=JSON.stringify({...e,instrumentation:s},null,2);return s.verified?textResult2(i):errorResult9(i)}async function normalizeCanvasSlug(e,t){const n=e.trim().replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/[^/]*\.canvas\.tsx$/i,"");if(!n.includes("/"))return n;const r=resolveCanvasesDirSync(t),s=KI.isAbsolute(r)?r:KI.join(t,r),i=KI.isAbsolute(n)?[n]:[KI.join(t,n),KI.join(s,n)];for(const e of i){const t=await resolveCanvasDirPath(e);if(!t)continue;const r=KI.relative(s,t).replace(/\\/g,"/");return r&&!r.startsWith("..")?r:n}return n}async function canvasWorkIdentity(e,t){return(await resolveCanvasWork(e,t)).identity}async function resolveCanvasWork(e,t){const n=KI.resolve(e.workspaceRoot,e.canvasesDir);let r=t.trim().replace(/\\/g,"/").replace(/\/index\.canvas\.tsx$/,"").replace(/\/$/,"");const s=KI.resolve(e.workspaceRoot,r);if((KI.isAbsolute(r)||s.startsWith(n+KI.sep))&&(r=KI.relative(n,KI.isAbsolute(r)?r:s).replace(/\\/g,"/")),!r||"."===r||r.split("/").includes("..")||KI.isAbsolute(r))throw new Error("Canvas must be a folder inside the configured canvases root.");let i,o=null;try{o=await resolveCanvasFile({workspaceRoot:e.workspaceRoot,canvasesDir:n,canvasSlug:r}),i=KI.dirname(o)}catch(e){if(!(e instanceof iM&&"canvas_not_found"===e.code)&&"ENOENT"!==e.code)throw e;i=KI.join(n,r.includes("/")?r:`canvases/${r}`)}return{identity:{canvas_slug:KI.relative(n,i).replace(/\\/g,"/"),canvas_dir:i},canvasFile:o}}async function openCanvasInSplitView(e,t){if(!e.canvasSplitView)return!1;try{return await e.canvasSplitView.open({canvasFile:t})}catch{return!1}}async function persistStoryboardSizeHints(e,t){if(!e.canvasStoryboardSizeHints||0===t.sizes.length)return{};try{return await e.canvasStoryboardSizeHints.record(t),{}}catch(e){return{size_hint_warning:`Could not save storyboard size hints: ${String(e)}`}}}var bU=6e4;async function capturePreviewSnapshot(e,t){if(!e.canvasPreviewCapture)return{};try{const n=await withPreviewCaptureTimeout(e.canvasPreviewCapture.capture({canvasSlug:t}),e.canvasPreviewCapture.timeoutMs??bU);return"ok"===n.kind?{preview_captured:!0}:{preview_captured:!1,preview_error:n.message}}catch(e){return{preview_captured:!1,preview_error:e instanceof Error?e.message:String(e)}}}function withPreviewCaptureTimeout(e,t){let n;const r=new Promise((e,r)=>{n=setTimeout(()=>{r(new Error(`Capturing the canvas preview took longer than ${Math.round(t/1e3)}s and was abandoned. The canvas edits are saved, but its preview may still be missing on linked issues — tell the user rather than assuming the canvas is reviewable.`))},t),n.unref?.()});return Promise.race([e,r]).finally(()=>{n&&clearTimeout(n)})}var vU=CN.object({export_name:CN.string(),name:CN.string().optional(),import_path:CN.string().optional(),import_name:CN.string().optional(),route:CN.string().optional(),preview:CN.string().optional().describe('Flutter apps only: `"<path from this canvas to the Dart file>#<function>"`, beginning with ./ or ../, for a top-level @Preview function. The package is the nearest pubspec.yaml. Writes a <FlutterStoryboard> instead of a component or route storyboard; pass its logical width and height.'),width:CN.number().optional().describe("Width of the box to reserve on the canvas; a component storyboard's real size is its root element's. Route layouts use viewport dimensions."),height:CN.number().optional().describe("Height of the box to reserve on the canvas; a component storyboard's real size is its root element's. Route layouts use viewport dimensions.")}),wU={repo_root:CN.string().optional().describe("Forward-compat (multi-repo workspaces): absolute path to the repo root the app lives in. Omit — today only the session's project root is supported."),app_dir:CN.string().optional().describe("Forward-compat (multi-app repos): the app's directory relative to the project root (a tempo.config.json `apps[].appDir`). Omit — today only the project's single configured app is supported.")},_U={...wU,require_instrumentation:CN.boolean().optional().describe("Require the running app's SDK identity endpoint to report an active Tempo plugin. Required for generated Vite prototypes before canvas handoff. Returns a tool error with instrumentation.code and fix if verification fails; does not stop the app. Omit for ordinary previews or frameworks without the SDK identity endpoint.")};function toAppDevServerTarget(e){if(e.repo_root||e.app_dir)return{...e.repo_root?{repoRoot:e.repo_root}:{},...e.app_dir?{appDir:e.app_dir}:{}}}function withDefaults(e,t){const n={...e};return n.repo_root||(n.repo_root=t.workspaceRoot),n.workspace_root||(n.workspace_root=t.workspaceRoot),n}function withCreateCanvasDefaults(e,t){const n=withDefaults(e,t),r=t.newCanvasBackgroundColor,s="function"==typeof r?r():r;return!n.background_color&&s&&(n.background_color=s),n}function registerTools(e,t){e.tool("canvas_create","Create a new canvas under the project's canvases root (`paths.canvases` in tempo.config.json — canonically `tempo/designs`). A plain `canvas_name` creates a FREEFORM canvas at `<root>/canvases/<slug>`; a `/`-separated name is an explicit path under the root and is how you create INTO a zone — e.g. `\"design-system/Badges\"` → `<root>/design-system/badges`, `\"libraries/ios/Buttons\"` → `<root>/libraries/ios/buttons`. Zone canvases (design-system/**, libraries/**) must declare their showcased components via defineAsset or `canvas_validate` fails with `missing_asset_declaration`. **MUTATING.** **Call `start_working_on_canvas({ canvas_slug })` FIRST** to announce canvas activity. Opens the new canvas in this chat's split view; `opened: true` means no `open_in_split_view` call is needed. Use `start_working_on_storyboard` / `finish_working_on_storyboard` around each frame; normal live updates remain visible. Reuse pre-created onboarding canvases instead of recreating them. Do NOT mkdir the canvas directory or Write any files into it beforehand — this tool creates the directory itself; put canvas-local helper files inside the returned `canvas_dir` AFTER it succeeds. The scaffolded `<Canvas backgroundColor>` is the user's theme backdrop: keep it as-is when you edit the canvas — never change or remove it unless the user explicitly asks. Returns `{ canvas_dir, canvas_file, storyboards: [{export_name, x, y, width, height, stub?}], opened }`. Dimensions are cached as fallback hints below start-working hints and real measured sizes. Width/height describe the box to reserve on the canvas; a component storyboard's real size is its root element's. A canvas-local `import_path` with no file yet is scaffolded as an empty stub (`stub: true`): its frame shows as work in progress at that width/height until you finish it with `finish_working_on_storyboard` or finish the canvas, so write the component, then finish the frame. Use a local StoryboardN.tsx default export with one root carrying size through className/style, wrapping the app component in a div if needed. Component layout uses only x/y and optional zIndex; route and HTML layouts require width/height. Run `canvas_validate` afterward to surface unresolved-import / missing-package / type errors.",{canvas_name:CN.string().describe('Friendly canvas name (e.g. `"Auth Components"`). The folder slug is derived from this.'),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session."),storyboards:CN.array(vU).optional().describe("Storyboards to scaffold. Each one: `export_name` plus EITHER `import_path` (+ optional `import_name`) for a component storyboard OR `route` for a route storyboard OR `preview` for a Flutter storyboard. `import_path` is canvas-relative (`./Local`, a stub is scaffolded when missing), an alias or package import written as the app writes it (`@/components/Card`), or a project file given relative to the project root (`apps/web/src/views/Home.vue`) or absolute, which is rewritten to a canvas-relative import. A bare path naming both a project file and an installed package is refused."),home:CN.boolean().optional().describe('Mark this NEW canvas as the project\'s home canvas (give it a single `route: "/"` storyboard). The Run button opens it next to the app dev-server output. One home per project. If a `route: "/"` canvas already exists, use `canvas_set_home` instead of creating a duplicate. Pair with `set_app_dev_command` so the app actually runs.')},async e=>{try{const n=await runCanvasToolCommand("create-canvas",withCreateCanvasDefaults(e,t));t.captureEvent?.("STORYBOARD_CREATED",{actor_type:"ai",source:"mcp",storyboard_type:"create-canvas"});const r=await openCanvasInSplitView(t,n.canvas_file),s=n,i=await persistStoryboardSizeHints(t,{canvasDir:s.canvas_dir,source:"canvas_create",sizes:s.storyboards.map(({export_name:e,width:t,height:n})=>({id:e,width:t,height:n}))}),o=!0===e.home,a={...n,...i,...o?{home_canvas:{marked:!0}}:{},opened:r},c=e,l=(c.storyboards??[]).some(e=>"string"==typeof e.route&&e.route.trim().length>0);if(l&&t.appDevServer)try{const e=await t.appDevServer.getCommand();if(!e)return textResult2(JSON.stringify({...a,warnings:[...a.warnings??[],"This canvas contains a route storyboard (`<RouteStoryboard>`) but no app dev command (`apps[0].start`) is configured in tempo.config.json. Route iframes will fail to load until you configure the user's real app dev server. Read the project root's package.json `scripts.dev`, then call `set_app_dev_command` with that foreground command and, when known, its HTTP(S) readiness URL. `${APP_PORT}` is an optional allocated-port helper; legacy `${PORT}` remains supported."],app_dev_server:{configured:!1,next_step:"Call set_app_dev_command with start and, when needed, url."}},null,2))}catch{}return textResult2(JSON.stringify(a,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_delete","Delete a canvas — removes the entire canvas folder and every file in it. **MUTATING and IRREVERSIBLE on disk.** Verifies the directory contains an `index.canvas.tsx` before deleting (safety check). Returns `{ deleted, deleted_files: [...] }`. Ask the user before calling.",{canvas_dir:CN.string().describe("Absolute or repo-relative path to the canvas folder (e.g. `tempo/designs/canvases/auth-components`).")},async e=>{try{const n=await runCanvasToolCommand("delete-canvas",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_set_home",'Mark an EXISTING canvas as the project\'s home canvas (the one the Run button opens next to the app dev-server output). Use this when a `route: "/"` canvas already exists (e.g. the one the user is viewing) instead of duplicating it with `canvas_create({ home: true })`. Stamps a marker comment and clears it from any other canvas (one home per project). **MUTATING.** Returns `{ canvas_dir, canvas_file, newly_marked, unmarked_previous }`.',{canvas_dir:CN.string().describe("Absolute or repo-relative path to the canvas folder (or its `index.canvas.tsx`) to mark as home, e.g. `tempo/designs/canvases/untitled`."),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async e=>{try{const n=await runCanvasToolCommand("set-home-canvas",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_migrate_to_latest","Migrate a canvas from the legacy object-export format (`export const X: TempoStoryboard = { render: () => …, layout: {…} }`) to the current React format (default-exported component returning `<Canvas>` with `<Storyboard>`/`<RouteStoryboard>` children) — the same conversion Tempo applies automatically when a legacy canvas is opened in the Design tab. **MUTATING** (rewrites `index.canvas.tsx` in place; safe no-op when the canvas is already React format). Call this BEFORE hand-editing any canvas that still has legacy `export const …: TempoStoryboard` declarations — never edit the legacy shape directly and never mix the two formats in one file. Returns `{ canvas_file, migrated, already_latest }`. Errors when the legacy source uses constructs the migration doesn't support (those need a manual rewrite via canvas_create).",{canvas_file:CN.string().describe("Absolute or repo-relative path to the canvas's `index.canvas.tsx` (or its folder)."),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async e=>{try{const n=await runCanvasToolCommand("migrate-canvas",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_validate",'Check whether a canvas will compile, load and render, and type-check every local file it reaches. **Read-only — does NOT modify the canvas, the tempo config, the package.json, or any other file. Cheap to run; safe to spam.** `valid: true` means nothing detectable statically stops the canvas from loading (`issues` is empty): host setup, syntax errors, missing files/exports/packages, server-only imports, canvas shape. **Type errors never make `valid` false**; they are returned in `type_errors`, each tagged `provenance: "canvas"` (files under the canvases root) or `"app"`, with a `canvas_type_errors` count. Fix type errors in canvas files you wrote; mention app-code type errors without chasing them unless asked. When generating new canvases or UI, you are done only when `valid` is true, `checks.type_check.status` is `"passed"` (not `incomplete`/`not_run`), and `canvas_type_errors` is 0. `warnings` never fail. If `issues` contain a `host_setup_issue`, call `canvas_project_init` separately to fix it (validate diagnoses; init scaffolds). Asset declarations are checked workspace-wide and FAIL validation (kind `asset_declaration_error`): a `duplicate_asset_declaration` or `component_declaration_outside_canvas` involving this canvas or any file in its folder, a `redundant_canvas_declaration` (a canvas that declares components must not also self-register — self-registration is strictly for component-less foundations pages), and a `missing_asset_declaration` (a canvas in a STRICT zone of the canvases root — `design-system/**` or `libraries/**` — must declare the top-level component(s) it showcases, or self-register with usageInstructions if it is a componentless foundations page; freeform canvases have no such requirement). Always run after `canvas_create` and after meaningful edits.',{canvas_file:CN.string().describe("Absolute or repo-relative path to the canvas's `index.canvas.tsx`."),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async e=>{try{const n={...withDefaults(e,t),workspace_root:t.workspaceRoot,canvases_dir:t.canvasesDir,assets_enabled:!1!==t.assetsEnabled},r=t.runCanvasValidate?await t.runCanvasValidate(n):await runCanvasValidation(n,{runValidatePageCommand:e=>runCanvasToolCommand("validate-canvas",e)});return textResult2(JSON.stringify(r,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_list","List every canvas in the workspace by scanning for `index.canvas.tsx` files under the configured canvases root (`paths.canvases` in tempo.config.json). **Read-only.** Returns `{ pages: [{ file_path, canvas_dir, repo_name, canvas_name, storyboard_names }] }`. Optionally restrict to specific repos via `repo_names`.",{workspace_root:CN.string().optional().describe("Workspace root. Defaults to the workspace bound to this MCP session."),repo_names:CN.array(CN.string()).optional().describe("Restrict the scan to these repo names.")},async e=>{try{const n=await runCanvasToolCommand("list-canvases",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_compute_layout","Compute non-overlapping `{x, y, width, height}` positions for new storyboards on an existing canvas. **Read-only pure computation, does NOT modify any file.** Places left-to-right in rows (max row width 3000px, 50px spacing); wraps to a new row when full. Call this BEFORE editing the canvas file to add new storyboards, so the new storyboards get sensible positions. For components, copy only x/y into layout and size the root in its storyboard file; width/height only reserve space.",{canvas_file:CN.string().nullish().describe("Path to the existing `index.canvas.tsx`. When provided, existing storyboard positions are honored so new ones don't overlap."),new_storyboards:CN.array(CN.object({name:CN.string(),width:CN.number().optional().describe("Width of the box to reserve on the canvas; a component storyboard's real size is its root element's."),height:CN.number().optional().describe("Height of the box to reserve on the canvas; a component storyboard's real size is its root element's.")})).describe("Storyboards to place. Defaults to 600×400 if w/h omitted.")},async e=>{try{const n=await runCanvasToolCommand("compute-layout",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_project_init",'Initialize the PROJECT for canvas support (NOT an individual canvas — use canvas_create for that). Tempo installs dependencies in the background. Do not run package-manager installs for the canvas host or project root. Edit tempo/package.json or tempo/tempo.config.json, then call start_canvas_devserver to install and (re)start. Scaffolds `tempo/tempo.config.json`, the host entry, `vite.config.ts`, and `.tempo/` runtime files, plus the project\'s **home canvas** (a `route: "/"` storyboard backing the Run button). framework=vite scaffolds a Vite host; framework=nextjs scaffolds a Next.js sidecar host; framework=nuxt scaffolds a Nuxt sidecar host for a Nuxt 3/4 app (a Tempo-owned `nuxt dev` in `tempo/` that extends the app as a Nuxt layer, with `apps[0].uiFramework: "vue"`; detected from a `nuxt` dependency or `nuxt.config.*`, or passed explicitly); framework=expo scaffolds an Expo web sidecar host. UI source framework is not auto-detected: omission means React. For a Svelte 5 app, set `apps[0].uiFramework` to `"svelte"` in the generated config and rerun this tool before `canvas_create`; that rerun fills missing sidecar Svelte compiler and official Vite-plugin dependencies without overwriting existing specs. Svelte route storyboards also require the APP package to depend on `tempo-sdk` and, for standalone Svelte/Vite, directly dev-depend on `@sveltejs/vite-plugin-svelte`; add missing packages at versions compatible with the app\'s existing toolchain and preserve configured versions. The APP\'S OWN Vite/Svelte config (outside `tempo/`) must use `tempoVitePlugin()` and prepend `tempoSveltePreprocess(...)`; the generated sidecar cannot annotate the separately running app. Preserve existing preprocessors after Tempo\'s. For a Vue 3 or Nuxt 3/4 app, follow the `set-up-vue-or-nuxt-canvas` skill before and after this call (when it is available; otherwise the canvas guide): plain Vue on Vite sets `"vue"` and reruns like Svelte, and its route storyboards need the app\'s own vite.config to use `tempoVitePlugin()` and `...tempoVuePlugin()` from `tempo-sdk/vue`. Init finds a Nuxt app in a workspace folder (`apps/web`) itself; when several packages could be the app, its `warnings` (or, with `framework: "nuxt"`, its error) say to set `apps[0].appDir`. For an Astro 7 app, set `apps[0].uiFramework` to `"astro"` and rerun this tool; it initializes the app-side SDK integration while preserving Tailwind and other Astro integrations. Use AstroStoryboard descriptors and static JSON props as described in the canvas guide. For a Flutter app (a `pubspec.yaml` depending on `flutter: sdk: flutter`), follow the `set-up-flutter-canvas` skill before and after this call (when it is available; otherwise the canvas guide): init discovers preview packages (including pub workspace or Melos members) without adding Flutter configuration, and in a project without a web app seeds the home canvas with `<FlutterStoryboard>` boards of its previews; never pass `framework` for Flutter. Idempotent — safe to re-run; only creates files that don\'t already exist. Run this once per project before `canvas_create`, or in response to a `canvas_validate` result that contains a `host_setup_issue`. The result includes `initial_tempo_config` (the scaffolded install/start scripts), `review_notes`, and `warnings`: problems this init could not fix itself, each of which you must act on. On a FIRST-time init, review the scripts against the repo per `review_notes` (monorepos, postinstall codegen, and private registries need a custom `scripts.install`); getting this right up front is the difference between the canvas rendering on first open and a broken-install debugging session.',{repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session."),framework:CN.enum(["vite","nextjs","nuxt","expo"]).optional().describe("Framework to scaffold for. Required if not auto-detectable.")},async e=>{try{const n=withDefaults(e,t),r=await resolveTempoConfig(n.repo_root).then(()=>!0,()=>!1),s=await runInitCommand(n);r||t.canvasDevserver?.prepare?.().catch(e=>{console.error("Canvas dependency preparation failed:",e)});const i=await resolveTempoConfig(n.repo_root).catch(()=>null),o=i?{scripts:{install:i.scripts.install,start:i.scripts.start}}:void 0,a=(await findFlutterPackages(n.repo_root)).length>0?'This project has Flutter preview packages. Follow the set-up-flutter-canvas skill now. Act on every entry in warnings: SDK or dependency conflicts, @Preview functions it cannot render, a preview import that fails the web build, a missing or outdated Flutter SDK. Flutter boards are <FlutterStoryboard preview="<canvas-relative path>.dart#<function>" layout={{ x, y, width, height }} /> from tempo-sdk/canvas; check_canvas_devserver reports flutter.state until Flutter is ready.':null,c="Act on every entry in warnings: each is something this init could not fix itself (an app folder it could not pick, a Nuxt start command without Tempo's app layer, an install layout the sidecar cannot reach). UI source framework is explicit: omission means React. If this is a Svelte 5 app, set apps[0].uiFramework to \"svelte\" in tempo.config.json and rerun canvas_project_init before creating storyboards. That rerun fills the generated sidecar's missing svelte and @sveltejs/vite-plugin-svelte dependencies using starter defaults; it preserves existing sidecar package specs. For a Svelte route storyboard, setup is NOT complete until apps[0].start is configured, the app's own package depends on tempo-sdk, and a standalone Svelte/Vite app directly dev-depends on @sveltejs/vite-plugin-svelte. Use set_app_dev_command for start and its HTTP(S) readiness URL when known; `${APP_PORT}` is an optional allocated-port helper and legacy `${PORT}` remains supported. Add only missing app packages, choose versions compatible with its existing Svelte/Vite toolchain, and never replace configured versions with Tempo's starter defaults. The app's own Vite/Svelte config must use tempoVitePlugin() plus tempoSveltePreprocess(...) as the first Svelte preprocessor; the generated tempo/ sidecar config does not affect the separately running app. Preserve any existing Svelte preprocessors after Tempo's. For a Vue 3 or Nuxt 3/4 app, follow the set-up-vue-or-nuxt-canvas skill now: it has the steps, config examples, checks and error fixes. In short, plain Vue on Vite sets apps[0].uiFramework to \"vue\" and reruns canvas_project_init (the rerun fills the sidecar's vue and @vitejs/plugin-vue), and its route storyboards need the app's own vite.config to use tempoVitePlugin() and ...tempoVuePlugin() from tempo-sdk/vue. A Nuxt app gets \"vue\" from init (framework nuxt; when the warnings say init found several app directories, set apps[0].appDir and rerun), keeps its own nuxt.config untouched, and keeps the `--extends` path to tempo/nuxt-app-layer (relative to appDir) in apps[0].start. For Astro 7, set apps[0].uiFramework to \"astro\" and rerun canvas_project_init to initialize the native app integration. Double-check initial_tempo_config's scripts.install against this repo before moving on. A plain package-manager install (bare `npm install`/`pnpm install`/… or Tempo's chained `cd .. && … && cd tempo && …` form) means Tempo's DEFAULT behavior: it installs the project root and tempo/ itself with the detected package manager — correct for most single-package repos. Write a CUSTOM command instead when the default won't produce importable app code: the app lives in a workspace/monorepo subdirectory (install must run at the workspace root or with the right filter), the app needs postinstall codegen (e.g. `prisma generate`), a private registry needs .npmrc/env, or the repo has a non-standard install. A custom value runs verbatim from tempo/ (cmd.exe-compatible syntax only, cover BOTH roots' dependencies) and Tempo NEVER rewrites it; under pnpm, when tempo/ is not a package of an ancestor pnpm-workspace.yaml, its tempo/ half needs `--ignore-workspace`, which Tempo adds only to the default form. Do not run package-manager installs for the canvas host or project root. Edit tempo/package.json or tempo/tempo.config.json, then call start_canvas_devserver; Tempo installs and (re)starts.";return textResult2(JSON.stringify({...s,initial_tempo_config:o,review_notes:a?`${a} ${c}`:c,canvas_devserver_status:{running:!1,deferred:!0,message:"Tempo prepares dependencies in the background. The canvas host starts on first render or start_canvas_devserver. Do not run installs yourself."}},null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_debug","Collect detailed diagnostics for a rendered canvas. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (optional export name). Returns filtered runtime state, pipeline/error information, main-process devserver status, and screenshot images using the same static capture path as canvas_screenshot. Use when canvas_screenshot fails, a storyboard looks stale/blank, or the canvas runtime appears unhealthy.",{canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root (`design-system/web-design-system/actions`). Pass the PATH whenever the folder name may not be unique; a bare name that matches several canvases is rejected with ambiguous_canvas_slug rather than resolved by guess"),storyboard:CN.string().optional().describe("Optional storyboard export name. Omit to inspect the whole canvas.")},async({canvas_slug:e,storyboard:n})=>{if(!t.canvasDebug)return unsupportedEnvironmentResult("canvasDebug");try{const r=await normalizeCanvasSlug(e,t.workspaceRoot),s=await t.canvasDebug.capture({canvasSlug:r,storyboard:n});return canvasDebugResultToMcpContent(s)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_snapshot_route",'Snapshot a route storyboard\'s live page: create a static HTML storyboard beside it, return the HTML, or save the HTML to a file — the same "Snapshot to HTML" the route header offers, with stylesheets, images, fonts and inline-style assets kept resolvable. Use it whenever the user asks to snapshot, capture, clip or copy a website or app page onto a canvas as HTML; never write your own DOM/CSS serializer or CDP capture script. Steps: add a `<RouteStoryboard route="https://site.example/">` (an absolute URL works for external sites) whose layout width × height is the viewport to capture (for a whole page, set the height to the page height, max 12000), open the canvas with open_in_split_view({ type: "canvas" }), let the route render, then call this once per board. Args: canvas_slug, storyboard (the route storyboard\'s id), output ("storyboard" by default, or "html"). With output="html", returns HTML without creating a storyboard; set output_path to save it to a new .html file instead of returning the HTML payload. output_path is workspace-relative, its parent directory must exist, and existing files are never overwritten. With output="storyboard", the HTML file and `<HtmlStoryboard>` are written into the canvas folder. All modes return title and size.',{canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root. Pass the PATH whenever the folder name may not be unique."),storyboard:CN.string().describe("The route storyboard's `id` (its `name` also matches)."),output:CN.enum(["storyboard","html"]).optional().describe('Default: "storyboard" creates an HtmlStoryboard. "html" exports without creating a storyboard.'),output_path:CN.string().min(1).optional().describe('Only with output="html": save to a new workspace-relative .html file instead of returning HTML. Parent directory must exist; refuses overwrite.')},async({canvas_slug:e,storyboard:n,output:r,output_path:s})=>{if(!t.canvasRouteSnapshot)return unsupportedEnvironmentResult("canvasRouteSnapshot");try{let i;if(void 0!==s){if("html"!==r)return errorResult9('output_path requires output="html".');const e=await GI(t.workspaceRoot);if(KI.isAbsolute(s)||".html"!==KI.extname(s).toLowerCase())return errorResult9("output_path must be a workspace-relative .html file.");const n=KI.resolve(e,s),o=await GI(KI.dirname(n)),a=KI.relative(e,o);if(".."===a||a.startsWith(`..${KI.sep}`)||KI.isAbsolute(a))return errorResult9("output_path must stay inside the workspace (including symlinks).");i=KI.join(o,KI.basename(n))}const o=await normalizeCanvasSlug(e,t.workspaceRoot),a=await t.canvasRouteSnapshot.snapshot({canvasSlug:o,storyboard:n,...r?{output:r}:{}});return"ok"===a.kind?"html"===r&&"string"!=typeof a.html?errorResult9("snapshot_failed: The app did not return HTML. Update the app and retry."):(i&&await VI(i,a.html,{encoding:"utf8",flag:"wx"}),textResult2(JSON.stringify({created:"html"!==r,..."html"===r?i?{outputPath:s,saved:!0}:{html:a.html}:{},canvasPath:a.canvasPath,fromStoryboard:a.storyboard,snapshotName:a.snapshotName,width:a.width,height:a.height},null,2))):errorResult9(routeSnapshotErrorText(a))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("check_canvas_devserver","Check whether the canvas devserver is currently running. Returns running state, port, and url if up; `starting: true` while a start is still in progress (not a failure; `message` says what it is doing). For a project with a Flutter app a `flutter` field: `state` is starting (with a progress `message`), ready, reloading or failed (with `error.code` and `error.message`). Flutter boards paint only once it is ready. While Flutter's own output explains a problem (a failure, a start quiet for a minute, an error printed since ready such as a flutter_boot_timeout's cause), `flutter.recentOutput` carries its newest lines (`reason`, `lines`, `omitted`). Call before canvas operations if you suspect the server is down.",{},async()=>{if(!t.canvasDevserver)return unsupportedEnvironmentResult("canvas devserver");try{const e=await t.canvasDevserver.status();return textResult2(JSON.stringify(e,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("start_canvas_devserver","Start the canvas devserver if it isn't already running. Runs the command in tempo.config.json's scripts.start and waits until the /tempo-host route is reachable. A first build can take minutes: once a start runs past its notice time this returns `starting: true` while the start continues in the background; then follow it with check_canvas_devserver, never another start or stop. Every start keeps tempo-sdk on latest, moving a project off the legacy sdk-v2-latest. Pass update_sdk: true only when the user asks to update tempo-sdk: it restarts an already running host so it loads a newer SDK. No-op if already running, unless force_install: true — in that case the install step always runs first. Pass force_install: true after editing tempo.config.json's scripts.install (e.g. when fixing a `root_deps_missing` error by chaining a project-root install in front of the Tempo install) so the new install command actually executes.",{update_sdk:CN.boolean().optional().describe("Only when the user asks to update tempo-sdk. Restarts the canvas host even if it is running; the restart updates tempo-sdk to latest (through scripts.updateSdk when configured), as every start does. Never pass it routinely."),force_install:CN.boolean().optional().describe("When true, re-runs scripts.install before starting even if the supervisor thinks dependencies are already installed. Use this after editing tempo.config.json's scripts.install — without it, the start would skip install and your config change would have no effect.")},async({force_install:e,update_sdk:n})=>{if(!t.canvasDevserver)return unsupportedEnvironmentResult("canvas devserver");try{const r=await t.canvasDevserver.start({forceInstall:e,updateSdk:n,returnWhileStarting:!0}),s=JSON.stringify(r,null,2);return r.starting?textResult2("The canvas devserver is still starting and has NOT failed; it keeps starting in the background. Call check_canvas_devserver to see the outcome; do not call start_canvas_devserver or stop_canvas_devserver again. timeouts.startStallSeconds in tempo/tempo.config.json (default 300) sets how long Tempo waits on a start that prints nothing.\n\n"+s):textResult2(s)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("stop_canvas_devserver","Stop the running canvas devserver process. Use to free the port or before restarting cleanly. Canvas iframes will go blank until the canvas devserver is restarted.",{},async()=>{if(!t.canvasDevserver)return unsupportedEnvironmentResult("canvas devserver");try{const e=await t.canvasDevserver.stop();return textResult2(JSON.stringify(e,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("set_app_dev_command","Configure the user's REAL app dev server in tempo.config.json as `apps[0].start` plus optional `stop` and `url`. `url` is either an HTTP(S) string or `{ command }`; a URL command runs only during launch and must exit 0 with exactly one HTTP(S) URL on stdout. A clean early `start` exit is accepted only with `stop`, after which URL probes own liveness and `stop` owns teardown. Tempo exposes `${APP_PORT}` (legacy `${PORT}` also works) to every command. Legacy appStart spellings still read and migrate. At least one field must be provided; null clears it. Idempotent.",{command:CN.string().nullish().describe("The canonical apps[0].start foreground command. It may be arbitrary; use `${APP_PORT}` when the command should consume Tempo's allocated helper port. Legacy `${PORT}` remains supported. Omit to leave unchanged; pass null/empty to clear the app server configuration."),url:CN.union([CN.string(),CN.object({command:CN.string().min(1)}).strict()]).nullish().describe('Optional canonical apps[0].url: either a reachable HTTP(S) URL string or `{ command: "..." }`. The command runs once per launch from appDir (after start exits in the stop-backed handoff shape), receives APP_PORT/PORT/TEMPO_APP_PORT, and must print exactly one HTTP(S) URL. Omit to leave unchanged; pass null/empty to clear.'),stop:CN.string().nullish().describe("Optional canonical apps[0].stop teardown command. Required when start exits successfully while the app remains reachable externally. Runs on normal stop and stale-runtime reconciliation. Omit to leave unchanged; pass null/empty to clear."),...wU},async({command:e,stop:n,url:r,repo_root:s,app_dir:i})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");if(void 0===e&&void 0===n&&void 0===r)return errorResult9("Provide command, stop, and/or url to update.");const o=void 0===e?void 0:"string"==typeof e&&e.trim().length>0?e.trim():null,a=void 0===r?void 0:"string"==typeof r?r.trim().length>0?r.trim():null:null===r?null:{command:r.command.trim()},c=void 0===n?void 0:"string"==typeof n&&n.trim().length>0?n.trim():null;try{return await t.appDevServer.setConfig({...void 0!==o?{start:o}:{},...void 0!==c?{stop:c}:{},...void 0!==a?{url:a}:{}},toAppDevServerTarget({repo_root:s,app_dir:i})),textResult2(JSON.stringify({...void 0!==o?{app_dev_command:o}:{},...void 0!==a?{app_dev_url:a}:{},...void 0!==c?{app_dev_stop:c}:{},app_dev_config_update:{...void 0!==o?{start:o}:{},...void 0!==c?{stop:c}:{},...void 0!==a?{url:a}:{}},note:null===o?"Cleared.":"Saved. The supervisor allocates `${APP_PORT}` independently; static or command-resolved URLs are the readiness target and route base. If start hands off to an external server, stop is required and URL probes become liveness authority. Before declaring setup complete, verify the app depends on tempo-sdk and its own bundler config carries Tempo instrumentation. For standalone Svelte/Vite, add @sveltejs/vite-plugin-svelte only if missing, preserve compatible configured versions, and use tempoVitePlugin() plus tempoSveltePreprocess(...) first in the app's preprocess chain. For Vue/Vite, add tempoVitePlugin() and ...tempoVuePlugin() from tempo-sdk/vue to the app's own vite.config plugins; for Nuxt, keep `--extends` with the path to tempo/nuxt-app-layer (relative to appDir) in the command. The set-up-vue-or-nuxt-canvas skill has both. tempo/ only configures the sidecar."},null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("check_app_dev_server","Check the per-workspace app dev server configured by canonical `apps[0].start`/`stop`/`url` (legacy appStart spellings also read). Returns `{configured, running, phase, port, url, livenessSource, error}`; liveness is `child` for foreground servers and `probe` after external handoff. Use this when a route storyboard isn't rendering. `configured: false` means start is unset; `phase: 'error'` carries the supervisor failure. Pass `require_instrumentation: true` for generated Vite prototypes or to verify a route app's Tempo plugin: probes the app's /__tempo/identity within a 5s bound (polling while the server answers 503, as Nuxt does while it warms up) and adds `instrumentation.verified`; when `apps[0].uiFramework` is `\"vue\"` on Vite it also requires the identity to report tempoVuePlugin() active (`app_vue_annotation_missing` otherwise). Missing/inactive/unverifiable instrumentation is a tool error with a typed code and repair, even if running is true. This checks plugin activation, not every element's editability. Omission preserves the ordinary status-only check.",_U,async({repo_root:e,app_dir:n,require_instrumentation:r})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");try{const s=await t.appDevServer.getStatus(toAppDevServerTarget({repo_root:e,app_dir:n}));return await appDevServerStatusResult(s,r,e??t.workspaceRoot)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("start_app_dev_server","Start the per-workspace app dev server if it isn't already running. Spawns canonical `apps[0].start`, substitutes `${APP_PORT}` (or legacy `${PORT}`) in start/stop/url commands, persists the independently selected local helper port under `<workspaceRoot>/.tempo/app-devserver.json`, resolves `url.command` once when configured, and HTTP-gates readiness against the resolved/static URL or detected local URL. A clean early start exit requires `apps[0].stop`; then URL probes own liveness and stop owns teardown. A literal URL is probed as written and does not affect local allocation. No-op if already running. When start is unset, returns `{configured: false}`; call `set_app_dev_command` first. For generated Vite prototypes, pass `require_instrumentation: true`: after startup (also when already running), verify the app's active Tempo plugin via /__tempo/identity within a 5s bound (polling while the server answers 503, as Nuxt does while it warms up), and for a Vue app on Vite that tempoVuePlugin() is active. Returns `instrumentation.verified`; failure is a tool error with a typed code and repair, preserving the running app. Fix it before handing over the canvas. This checks plugin activation, not every element's editability. Omission preserves ordinary preview startup.",_U,async({repo_root:e,app_dir:n,require_instrumentation:r})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");try{const s=await t.appDevServer.start(toAppDevServerTarget({repo_root:e,app_dir:n}));return await appDevServerStatusResult(s,r,e??t.workspaceRoot)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("stop_app_dev_server","Stop the per-workspace app dev server. Use to free the allocated port, before restarting cleanly, or after editing the app dev command so the next `start_app_dev_server` picks up the new command. Route storyboard iframes will go blank until restarted. Does NOT clear the persisted port — the next start reuses it. Analogous to `stop_canvas_devserver` but for the user's app server.",{...wU},async({repo_root:e,app_dir:n})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");try{const r=await t.appDevServer.stop(toAppDevServerTarget({repo_root:e,app_dir:n}));return textResult2(JSON.stringify(r,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}});const n={canvas_slug:CN.string().min(1).describe("Canvas folder path relative to the canvases root. Use the full path when names are ambiguous.")},r={...n,storyboard:CN.string().min(1).describe("Exact Storyboard id. Starting before it exists shows a temporary frame; the real storyboard replaces it when the same id renders.")};e.tool("start_working_on_canvas","Begin a canvas editing session. Call it FIRST, the moment you decide to create or edit a canvas, before reading files or planning, and before canvas_create. Turns on this canvas's activity indicator in tabs/sidebar; does not shimmer storyboards or freeze live rendering. If the canvas exists, opens it in this chat's split view (`opened: true`; no `open_in_split_view` call needed); canvas_create opens a new one. Reuse an existing onboarding canvas. Use start_working_on_storyboard for each frame you work on. Pair with finish_working_on_canvas once the full task is verified. Takes only a canvas, never a storyboard.",n,async({canvas_slug:e})=>{try{const{identity:n,canvasFile:r}=await resolveCanvasWork(t,e);await(t.canvasEditingState?.start({canvasSlug:n.canvas_slug}));const s=!!r&&await openCanvasInSplitView(t,r);return textResult2(JSON.stringify({...n,editing:!0,opened:s}))}catch(e){return errorResult9(String(e))}}),e.tool("finish_working_on_canvas","End the canvas editing session and its tabs/sidebar activity indicator. Call once after verifying the full task, including canvas_screenshot on an edited storyboard. Also clears any outstanding storyboard shimmer owned by this run. Live rendering continues throughout. Persists the final canvas preview best-effort. Takes only a canvas; use finish_working_on_storyboard for individual frames.",n,async({canvas_slug:e})=>{try{const n=await canvasWorkIdentity(t,e);await(t.canvasEditingState?.finish({canvasSlug:n.canvas_slug})),t.canvasDevserver?.applySetup?.().catch(e=>{console.error("Canvas setup failed:",e)});const r=await capturePreviewSnapshot(t,n.canvas_slug);return textResult2(JSON.stringify({...n,editing:!1,...r}))}catch(e){return errorResult9(String(e))}}),e.tool("start_working_on_storyboard","Show work on one storyboard inside an active canvas session. Layout dimensions are saved as a fallback size hint; real measured sizes always win, and this hint outranks canvas_create. For a NEW frame, pass layout {x,y,width,height}: Tempo immediately shows a temporary shimmer rectangle at those canvas coordinates, even before the frame exists. Use the same id and layout when adding the real Storyboard; it replaces the placeholder. For an EXISTING frame, omit layout to shimmer its live content. Older calls without layout still get a default placeholder for missing frames. Does not write files, freeze previews, select a frame or move the camera. Keep publishing small useful versions; pair with finish_working_on_storyboard when this pass is ready.",{...r,layout:CN.object({x:CN.number().finite(),y:CN.number().finite(),width:CN.number().finite().positive(),height:CN.number().finite().positive()}).optional().describe("Planned canvas-world bounds for a new storyboard. Pass before writing its component so the user sees its placeholder immediately; reuse these bounds in the real Storyboard layout.")},async({canvas_slug:e,storyboard:n,layout:r})=>{try{const{identity:s,canvasFile:i}=await resolveCanvasWork(t,e),o=!r&&i?parsePageSource(i,await zI(i,"utf8")).storyboards:[],a=!r&&!o.some(e=>e.storyboardKey===n||e.exportName===n),c=r?await persistStoryboardSizeHints(t,{canvasDir:s.canvas_dir,source:"start_working_on_storyboard",sizes:[{id:n,width:r.width,height:r.height}]}):{};return textResult2(JSON.stringify({...s,storyboard:n,editing:!0,...r?{layout:r}:{},...c,...a?{warning:`Storyboard "${n}" is not in the canvas yet. Call again with layout: { x, y, width, height } so its placeholder has the frame's planned size.`}:{}}))}catch(e){return errorResult9(String(e))}}),e.tool("finish_working_on_storyboard","Turn off this run's shimmer on exactly one storyboard after a useful, valid pass. Leaves the canvas activity indicator and other storyboards alone. Fast status signal only: no capture, upload, iframe refresh or final-task completion. Continue with the next frame, or start this same storyboard again to refine it. Finish the whole canvas separately after final verification.",r,async({canvas_slug:e,storyboard:n})=>{try{return textResult2(JSON.stringify({...await canvasWorkIdentity(t,e),storyboard:n,editing:!1}))}catch(e){return errorResult9(String(e))}});const s={canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root (`design-system/web-design-system/actions`). Pass the PATH whenever the folder name may not be unique; a bare name that matches several canvases is rejected with ambiguous_canvas_slug rather than resolved by guess"),storyboard:CN.string().optional().describe("Optional storyboard export name. Recommended — without it the whole canvas is captured as a composite image.")},captureScreenshot=async(e,n,r)=>{if(!t.canvasScreenshot)return unsupportedEnvironmentResult("canvasScreenshot");if(t.canvasDevserver&&!t.canvasScreenshot.managesDevserver)try{await t.canvasDevserver.start()}catch(e){return errorResult9(`canvas_screenshot could not start the canvas devserver: ${e instanceof Error?e.message:String(e)}`)}try{const s=await normalizeCanvasSlug(e,t.workspaceRoot),i=await t.canvasScreenshot.capture({canvasSlug:s,storyboard:n},r);return"error"===i.kind?errorResult9(`canvas_screenshot failed [${i.code}]: ${i.message}${i.availableStoryboards&&i.availableStoryboards.length>0?` Available storyboards in the current canvas: ${i.availableStoryboards.join(", ")}.`:""}`):{content:[{type:"image",data:i.pngBase64,mimeType:"image/png"},{type:"text",text:JSON.stringify({canvas_slug:s,storyboard:n??null,width:i.width,height:i.height,...screenshotProvenanceSummary(i)},null,2)}]}}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}};e.tool("canvas_screenshot","Capture a PNG of rendered canvas content so you can verify your edits visually. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export name; recommended). With storyboard, returns that storyboard's rendered pixels; without storyboard, returns a composite image of the whole canvas. This call fails fast with capacity_exceeded when all five devserver slots are pinned; continue without the image, or call canvas_screenshot_queued if waiting is important. Images larger than 1990px per side are downscaled to fit. Errors are typed; do not retry on error. For a ROUTE storyboard, ensure the app dev server is running first (check_app_dev_server → start_app_dev_server). The deliverable is the canvas, not the screenshot.",s,async({canvas_slug:e,storyboard:t},n)=>captureScreenshot(e,t,{capacityMode:"fail",signal:n.signal})),e.tool("canvas_screenshot_queued","Capture the same PNG as canvas_screenshot, but wait for a managed devserver slot when all five are pinned. Use this only when the image is important enough to block the turn; otherwise prefer canvas_screenshot and continue on capacity_exceeded. queue_timeout_ms bounds only the capacity wait (default 30000, max 120000), and MCP cancellation aborts the wait immediately.",{...s,queue_timeout_ms:CN.number().int().min(1).max(12e4).default(3e4).describe("Maximum milliseconds to wait for a devserver slot.")},async({canvas_slug:e,storyboard:t,queue_timeout_ms:n},r)=>captureScreenshot(e,t,{capacityMode:"wait",timeoutMs:n,signal:r.signal})),e.tool("storyboard_responsiveness_check",xU,{canvas_slug:s.canvas_slug,storyboard:CN.string().describe("Storyboard export name.")},async({canvas_slug:e,storyboard:n},r)=>{const s=t.canvasResponsivenessCheck;if(!s)return unsupportedEnvironmentResult("canvasResponsivenessCheck");try{const i=await normalizeCanvasSlug(e,t.workspaceRoot);return await runResponsivenessCheck(s,t,{canvasSlug:i,storyboard:n},r.signal)}catch(e){const t=e instanceof iM?e.code:"capture_threw";return failure2(t,e instanceof Error?e.message:String(e))}});const stabilityErrorResult=(e,t)=>errorResult9(`canvas_verify_vrt failed [${e}]: ${t}`);e.tool("canvas_verify_vrt","Check that a VRT-tracked storyboard renders identically across fresh mounts so its baseline won't flake in CI. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export name carrying a literal `vrt` prop; `skip: true` is rejected), runs (2–10, default 3; keep at least 3). Compares each run to run 1 under the visual-review matcher, threshold, and ignore masks. The headless lane loads each run differently: run 1 cold, run 2 with every request slowed, run 3 as a second render in a warm document, then repeating; `unstable_conditions` says which load changed the pixels and what that means. Returns `vrt_stable`; when false, also changed-pixel bounds and a diff-mask image. Call after adding or changing `vrt`; fix the nondeterministic input and rerun. Read-only. Fails fast with capacity_exceeded; typed errors are not retryable.",{canvas_slug:s.canvas_slug,storyboard:CN.string().describe("Storyboard export name carrying the literal `vrt` prop."),runs:CN.number().int().min(2).max(10).default(3).describe("Number of captures to compare. Defaults to 3.")},async({canvas_slug:e,storyboard:n,runs:r},s)=>{if(!t.canvasStoryboardStability)return unsupportedEnvironmentResult("canvasStoryboardStability");try{const i=await normalizeCanvasSlug(e,t.workspaceRoot),o=await resolveTestedStoryboard({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir,canvasSlug:i,storyboard:n});if(t.canvasDevserver&&!t.canvasStoryboardStability.managesDevserver)try{await t.canvasDevserver.start()}catch(e){return errorResult9(`canvas_verify_vrt could not start the canvas devserver: ${e instanceof Error?e.message:String(e)}`)}const a=createVrtStabilityAccumulator({threshold:o.vrt.threshold,ignore:o.vrt.ignore,layout:o.layout});let c;const l=await t.canvasStoryboardStability.captureRuns({canvasSlug:o.canvasSlug,canvasFile:o.canvasFile,storyboard:o.storyboardId,runs:r},{timeoutMs:12e4,signal:s.signal,onCapture:e=>{if(!c)try{a.addCapture(e)}catch(e){c=e}}});if(c)return stabilityErrorResult("compare_failed",c instanceof Error?c.message:String(c));if("error"===l.kind)return stabilityErrorResult(l.code,`${l.message}${l.availableStoryboards&&l.availableStoryboards.length>0?` Available storyboards in the current canvas: ${l.availableStoryboards.join(", ")}.`:""}`);if(l.runs!==r||a.captureCount!==r)return stabilityErrorResult("capture_incomplete",`requested ${r} fresh captures but received ${a.captureCount}.`);let d;try{d=a.summarize()}catch(e){return stabilityErrorResult("compare_failed",e instanceof Error?e.message:String(e))}const u=d.conditions?` (${[...new Set(d.conditions)].join(", ")} loads)`:"",p=d.unstableConditions.map(({condition:e,dependsOn:t})=>` The ${e} load differs from the cold one: the storyboard depends on ${t}.`).join(""),m="stable"===d.status?`All ${r} isolated renders${u} are equivalent under the storyboard's VRT threshold and ignore masks.`:`${d.changedRuns} of ${r-1} comparisons changed under the storyboard's VRT policy; the largest changed ${d.maxDiffPixels} pixels (${(100*d.maxDiffRatio).toFixed(4)}%).${p}`,f=[];return d.cumulativeDiff&&f.push({type:"image",data:d.cumulativeDiff.pngBase64,mimeType:"image/png"}),f.push({type:"text",text:JSON.stringify({canvas_slug:o.canvasSlug,canvas_file:o.canvasFile,storyboard:o.storyboardId,vrt:o.vrt,status:d.status,vrt_stable:d.vrtStable,runs:d.runs,retried_captures:d.retriedCaptures,threshold_used:d.threshold,ignore_regions:d.ignoreRegions,changed_runs:d.changedRuns,...d.conditions?{conditions:d.conditions,unstable_conditions:d.unstableConditions.map(({condition:e,dependsOn:t})=>({condition:e,depends_on:t}))}:{},max_diff_pixels:d.maxDiffPixels,max_diff_ratio:d.maxDiffRatio,diff_bounds_device_px:d.diffBounds,cumulative_diff_image:d.cumulativeDiff?{width:d.cumulativeDiff.width,height:d.cumulativeDiff.height,source_width:d.cumulativeDiff.sourceWidth,source_height:d.cumulativeDiff.sourceHeight,meaning:"Transparent pixels were stable; fuchsia pixels changed in at least one comparison to run 1. Large masks are area-resampled to fit within 1990px without dropping thin differences."}:null,comparisons:d.comparisons.map(e=>({run:e.run,baseline_run:e.baselineRun,...e.condition?{condition:e.condition}:{},diff_pixels:e.diffPixels,diff_ratio:e.diffRatio,diff_bounds_device_px:e.diffBounds,dimensions:e.dimensions,...e.dimensionChange?{dimension_change:e.dimensionChange}:{}})),diagnosis:m,next_action:"unstable"===d.status?"Inspect the changed region and the storyboard's component dependency graph for nondeterministic render inputs. Replace them with fixed props, fixtures, or seeded inputs, and make the component suspend until what it renders from is ready, with no Suspense boundary between it and the storyboard, rather than showing a fallback it never revisits, then rerun.":"No deterministic-source change is needed for this storyboard under its current VRT policy."},null,2)}),{content:f}}catch(e){return e instanceof iM?stabilityErrorResult(e.code,e.message):errorResult9(`canvas_verify_vrt failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("canvas_set_vrt","Track, configure, pause, or untrack a component or local HTML storyboard for visual review (VRT) by writing its literal `vrt` prop through Tempo's source editor — never hand-edit `vrt` JSX. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export id), tracked: `true` (bare `vrt`; an existing object form is kept), `false` (removes the attribute, config included), or `{ threshold?, ignore?, skip? }` (writes exactly that config: threshold 0–0.5, ignore regions `{x,y,w,h}` in storyboard-local CSS px, skip pauses without losing config). Component and local HTML storyboards are supported — route storyboards are refused with `storyboard_unsupported`. **MUTATING** (rewrites the canvas file in place); bookend with start_working_on_canvas / finish_working_on_canvas like any canvas edit. Returns `{ canvas_file, storyboard, tracked, paused, vrt, changed, next_step }`. After tracking, ALWAYS run canvas_verify_vrt on the storyboard until it reports `vrt_stable`. Typed errors are not retryable.",{canvas_slug:s.canvas_slug,storyboard:CN.string().describe("Storyboard export id (the `id` prop)."),tracked:CN.union([CN.boolean(),CN.object({threshold:CN.number().min(0).max(.5).optional(),skip:CN.boolean().optional(),ignore:CN.array(CN.object({x:CN.number().min(0),y:CN.number().min(0),w:CN.number().min(0),h:CN.number().min(0)}).strict()).optional()}).strict()]).describe("true = track with defaults; false = untrack; an object = write exactly this literal config.")},async({canvas_slug:e,storyboard:n,tracked:r})=>{try{const s=await normalizeCanvasSlug(e,t.workspaceRoot),i=await applyStoryboardVrt({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir,canvasSlug:s,storyboard:n,tracked:r});return textResult2(JSON.stringify(i,null,2))}catch(e){return errorResult9(e instanceof YM?`canvas_set_vrt failed [${e.code}]: ${e.message}`:`canvas_set_vrt failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("visual_review_doctor",'Diagnose whether this repo can run Tempo visual review (VRT) and what is missing, one typed row per layer: canvas_host, tracked_storyboards, ci_provider, workflow, repo_registered, github_app + required_check (GitHub Actions) or bitbucket_grant + merge_enforcement (Bitbucket Pipelines; merge_enforcement is advisory), first_run. **Read-only — no side effects; safe to re-run and to poll.** Each row is `{ id, ok: true | false | null, fix? }` — `false` carries the exact recovery in `fix`, `null` means it could not be determined in this environment (see `reason`; never inferred). Also returns `repo_key`, `default_branch`, `org`, `ready`, and `next_step` — the first failing row\'s fix in DEPENDENCY order (registration before local setup, a first capture before the required check), so follow `next_step` rather than the rows top to bottom. `first_run` reports aggregate facts only (reached, when, state, gate); the portal link lives on the PR (comments_get_pr_visual_review). Run it BEFORE proposing any visual-review setup, and again after the user completes a manual step (GitHub App install, Bitbucket repository grant, branch protection) or after a push (poll `first_run` for a few minutes to prove the first capture reached Tempo). Read get_guide({ topic: "tempo-visual-review-setup" }) first to interpret the rows. Never hand-write the workflow — `visual_review_init` writes it.',{repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async({repo_root:e})=>{try{const n=await runVisualReviewDoctor(t,{repoRoot:e});return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(`visual_review_doctor failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("visual_review_init","Scaffold the repo-owned half of Tempo visual review: writes `.github/workflows/visual-review.yml` (GitHub Actions) or `bitbucket-pipelines.yml` (Bitbucket Pipelines) from the template the published `@tempo-ai/visual-review` CLI ships, filled with the repo's package-manager setup, the install command from tempo.config.json, the default branch, and the canvas-host directory. **MUTATING but idempotent and safe to re-run: it only creates what is absent and NEVER overwrites an existing workflow or pipelines file** — if one exists it returns `skipped: true` plus `drift[]` (missing `id-token: write`, no default-branch push trigger, not using the published CLI, …; on Bitbucket also `merge_proposal` to merge into the existing file) for you to propose exact edits. On Bitbucket it also authorizes Tempo's repository grant (`repository_grant`: build statuses + PR-head checks) with the user's connected Bitbucket account, only after verifying that account can write to the repo; a `not_authorized` result carries the fix. Optional `with_agent_rules` appends the tested-storyboard rules to the repo's CLAUDE.md / AGENTS.md (whichever exists) and `with_pr_template` adds a Visual review section to the PR template (GitHub only); both are opt-in because they edit team-owned files. Returns `{ workflow_file, written, skipped, drift, initial_workflow, package_manager, install, review_notes, warnings, next_steps }` — review `initial_workflow` against the repo per `review_notes` while you still have context (monorepo root vs app dir, postinstall codegen, private registries), exactly like canvas_project_init. Requires the canvas host (`no_tempo_host` → run canvas_project_init first), an `origin` remote (`no_git_remote`), and a github.com or bitbucket.org repo (`unsupported_ci`). Run visual_review_doctor first and get the user's yes before calling; it does not track storyboards (canvas_set_vrt) or push anything.",{repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session."),with_agent_rules:CN.boolean().optional().describe("Append the tested-storyboard rules to CLAUDE.md or AGENTS.md at the repo root (whichever exists; warns and skips if neither does). Opt-in — it edits a team-owned file."),with_pr_template:CN.boolean().optional().describe("Add a 'Visual review' section to .github/PULL_REQUEST_TEMPLATE.md (created if absent, appended if present without one). The section describes the no-visual-change marker without spelling it — a PR body containing the literal marker skips capture. Opt-in. GitHub only (Bitbucket has no PR template file; warns and skips).")},async({repo_root:e,with_agent_rules:n,with_pr_template:r})=>{try{const s=await runVisualReviewInit(t,{repoRoot:e,withAgentRules:n,withPrTemplate:r});return textResult2(JSON.stringify(s,null,2))}catch(e){return errorResult9(e instanceof YM?`visual_review_init failed [${e.code}]: ${e.message}`:`visual_review_init failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("canvas_share","Create a shareable link to a canvas and get back a screenshot of the whole canvas. **The canvas MUST be fully committed and pushed to a remote (clean git state) before sharing** — exactly like link_items — otherwise this returns a 'branch_not_pushed' error and you must commit + push the canvas's branch first so the recipient can access the code. Cache-first: when a published preview already exists for the branch's exact pushed commit, the link returns immediately with no re-capture; otherwise it captures a composite screenshot of every storyboard, publishes it as the branch's preview, then mints the link. Share links are BRANCH-LIVE: an existing link (and its public token) keeps its URL and automatically shows the newest published preview each time the branch's pushed canvas is re-captured — no need to re-share after pushing new commits. Returns the URL plus the whole-canvas screenshot (auto-displayed inline). By default the link is member-only (the recipient opens it as an org member); pass public: true to mint an anyone-with-the-link token instead. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), public (optional, default false).",{canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root (`design-system/web-design-system/actions`). Pass the PATH whenever the folder name may not be unique; a bare name that matches several canvases is rejected with ambiguous_canvas_slug rather than resolved by guess"),public:CN.boolean().optional().describe("When true, mint an anyone-with-the-link public token so the recipient doesn't need to sign in. Default false ⇒ member-only link.")},async({canvas_slug:e,public:n})=>{if(!t.canvasShare)return unsupportedEnvironmentResult("canvasShare");if(t.canvasDevserver)try{await t.canvasDevserver.start()}catch(e){return errorResult9(`canvas_share could not start the canvas devserver: ${e instanceof Error?e.message:String(e)}`)}try{const r=await normalizeCanvasSlug(e,t.workspaceRoot),s=await t.canvasShare.create({canvasSlug:r,makePublic:n??!1});return"error"===s.kind?errorResult9(`canvas_share failed [${s.code}]: ${s.message}`):{content:[{type:"image",data:s.pngBase64,mimeType:"image/png"},{type:"text",text:JSON.stringify({canvas_slug:r,share_url:s.shareUrl,visibility:s.isPublic?"public":"member",canvas_path:s.canvasPath,branch:s.branch,storyboard_count:s.storyboardCount,...s.skippedStoryboardIds?.length?{skipped_broken_storyboards:s.skippedStoryboardIds}:{},width:s.width,height:s.height},null,2)}]}}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),!1!==t.assetsEnabled&&registerAssetTools(e,t)}var xU=["Check whether a component storyboard renders differently in a window of its own size. It captures the storyboard in the canvas's shared 1920x1080 window, then in a window resized to its box, and compares them, ignoring what changes by itself.","Call it when the storyboard's code reads the viewport in JavaScript (`window.innerWidth` / `innerHeight`, `matchMedia`, or a hook such as `useMediaQuery`, `useBreakpoint`, `useIsMobile`); measures its own elements in JavaScript and uses the size (`ResizeObserver`, `getBoundingClientRect`, `offsetWidth`); shows an overlay that places itself against the viewport, most often an open menu, popover or tooltip near a frame edge; shows a whole page or app shell at a phone or tablet size; or sizes a chart, a virtual list or a canvas in JavaScript.","Do not call it for CSS-only responsiveness that no JavaScript measures (media queries, Tailwind breakpoints, viewport units); for a storyboard about as wide as a desktop window; or for content missing from a screenshot, which this does not fix.","What earlier checks found in this project is at the end of the canvas guide, and recorded in `tempo/AGENTS.md` under `## Responsive storyboards`.","Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export name). Returns a verdict in a JSON sidecar: `differs` with two images, the canvas's view, then the storyboard at its own size; `same`; `already_responsive`; or `unavailable` with a reason. Each says what to do next. Fails fast with capacity_exceeded; typed errors are not retryable."].join(" ");function unsupportedEnvironmentResult(e){return errorResult9(`${e} hook not configured in this environment — the canvas MCP server was constructed without it. This usually means the tool was invoked outside the Electron main process (e.g. from a CLI wrapper or test).`)}var TU={canvas_not_open:'Open the canvas with open_in_split_view({ type: "canvas", path }) so a canvas tab shows it, then retry once.',ambiguous_canvas_slug:"Retry with the root-relative path of the canvas you mean.",storyboard_not_found:"Retry with one of the canvas's storyboard ids, or add the RouteStoryboard first.",not_route_storyboard:"Only a <RouteStoryboard> has a live page to snapshot. Add one for the URL and snapshot that.",route_not_rendered:"The route has not rendered on the canvas yet. Wait for it to load, then retry once.",snapshot_failed:"Tell the user the snapshot failed and why. Do not hand-roll a serializer as a workaround."};function routeSnapshotErrorText(e){const t=e.availableStoryboards?.length?` Storyboards on this canvas: ${e.availableStoryboards.join(", ")}.`:"";return`${e.code}: ${e.message}${t} ${TU[e.code]}`}function canvasDebugResultToMcpContent(e){const t=e.screenshots??[],n=stripCanvasDebugImages(e),r=[{type:"text",text:JSON.stringify(n,null,2)}];for(const e of t)e.pngBase64&&(r.push({type:"text",text:JSON.stringify({screenshot:{label:e.label,canvas_slug:e.canvasSlug,storyboard:e.storyboard??null,width:e.width??null,height:e.height??null,...screenshotProvenanceSummary(e)}},null,2)}),r.push({type:"image",data:e.pngBase64,mimeType:"image/png"}));return{content:r,..."error"===e.kind?{isError:!0}:{}}}function stripCanvasDebugImages(e){return"error"===e.kind?{kind:e.kind,code:e.code,message:e.message,diagnostics:e.diagnostics??null}:{kind:e.kind,diagnostics:e.diagnostics}}function screenshotProvenanceSummary(e){return{retried:e.retried??!1,...e.fromCache?{fromCache:!0}:{},...e.highFidelity?{high_fidelity:!0}:{}}}function createCanvasMcpServer(e){const t=!1!==e.assetsEnabled,n=new Pm({name:"tempo-design-canvas-tools",version:"1.0.0"},{capabilities:{tools:{},resources:{}},instructions:buildCanvasInstructions(e.canvasesDir,{assetsEnabled:t})});return registerTools(n,e),registerDocs(n,e),n}function buildBackends(e,t,n){const r=buildDbBackends({...e,renderPdfPage:e.renderPdfPage??renderDocumentPage},t);if(t.includes("canvas")&&n){const t=createCanvasMcpServer({workspaceRoot:n.workspaceRoot,canvasesDir:n.canvasesDir,...e.canvasHooks});r.push({toolset:"canvas",server:t})}return r}var kU="0.0.151-staging.1";import{stat as SU}from"fs/promises";import EU from"path";import{gzipSync as AU}from"zlib";import{dirname as CU,resolve as IU}from"path";import{fileURLToPath as PU}from"url";async function provisionSdkRuntime(){const e=PU(import.meta.url),t=e.endsWith(".ts")?IU(CU(e),"../../tempo-sdk-runtime/dist"):IU(CU(e),"sdk-runtime");try{await provisionCaptureRuntime(t)}catch(e){throw new Error(`Tempo MCP SDK runtime is unavailable. Reinstall @tempo-ai/mcp or provide a compatible TEMPO_SDK_RUNTIME_PATH. ${e instanceof Error?e.message:String(e)}`)}}async function startDevserverSession2(e){return await provisionSdkRuntime(),startDevserverSession(e)}async function startCaptureSession2(e){return await provisionSdkRuntime(),startCaptureSession(e)}var DU=["git","--no-optional-locks"];function simpleGit2(e){return pI(e?{baseDir:e,binary:DU}:{binary:DU})}var RU=["credential.interactive=false"];function nonInteractiveGitEnv(e=process.env){return{...e,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",SSH_ASKPASS_REQUIRE:"never"}}async function getRemoteUrl2(e,t="origin"){const n=simpleGit2(e),readConfig=async e=>{try{const t=(await n.raw(["config","--get",e])).trim();return t||null}catch{return null}};return await readConfig(`remote.${t}.pushurl`)??await readConfig(`remote.${t}.url`)}async function computeShareStatus(e){const t=simpleGit2(e),n=await t.getRemotes(!0),r=n.length>0,s=n.find(e=>"origin"===e.name)?.refs.push??n[0]?.refs.push??null,i=(await t.raw(["branch","--show-current"])).trim(),o=await t.status(),a=new Map,addFile=(e,t)=>{a.has(e)||a.set(e,{path:e,status:t})};for(const e of o.staged)addFile(e,"staged");for(const e of o.modified)addFile(e,"modified");for(const e of o.deleted)addFile(e,"deleted");for(const e of o.not_added)addFile(e,"added");for(const e of o.created)addFile(e,"added");for(const e of o.renamed)addFile(e.to,"renamed");for(const e of o.conflicted)addFile(e,"conflicted");const c=[...a.values()];try{const e=await t.diff(["--cached","--numstat"]),n=await t.diff(["--numstat"]),r=new Map;for(const t of[e,n])for(const e of t.trim().split("\n").filter(Boolean)){const t=e.split("\t");if(t.length<3)continue;const n=parseInt(t[0],10)||0,s=parseInt(t[1],10)||0,i=t.slice(2).join("\t"),o=r.get(i);o?(o.additions+=n,o.deletions+=s):r.set(i,{additions:n,deletions:s})}for(const e of c){const t=r.get(e.path);t&&(e.additions=t.additions,e.deletions=t.deletions)}}catch{}let l=0;if(r&&i){const e=n.find(e=>"origin"===e.name)?.name??n[0]?.name,r=await t.raw(["log","HEAD","--not",`--remotes=${e}`,"--oneline"]);l=r.trim().split("\n").filter(Boolean).length}return{hasRemote:r,remoteUrl:s,uncommittedFiles:c,unpushedCommits:l,currentBranch:i}}async function checkBranchOnRemote(e,t){const n=pI({baseDir:e,binary:DU,config:[...RU],timeout:{block:15e3}}).env(nonInteractiveGitEnv());try{const e=await n.raw(["ls-remote","--heads","origin",t]);return e.trim().length>0}catch{return null}}var NU=C(ru(),1);import{anyApi as OU}from"convex/server";var FU=1990;function toPosix7(e){return e.split(EU.sep).join("/")}function normalizeSlug(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/[^/]*\.canvas\.tsx$/i,"")}async function isCanvasFolder(e){try{return(await SU(EU.join(e,"index.canvas.tsx"))).isFile()}catch{return!1}}async function resolveCanvas(e,t){const n=e.workspaceRoot,r=e.canvasesDir,s=EU.join(n,"tempo"),i=await enumerateCanvasStoryboards({tempoDir:s,pagesDir:r}),o=new Map;for(const e of i.storyboards){const t=EU.dirname(e.filePath);let r=o.get(t);r||(r={contentPath:toPosix7(EU.relative(n,t)),hostCanvasPath:e.hostCanvasPath,storyboards:[]},o.set(t,r)),r.storyboards.push(e)}const a=normalizeSlug(t);if(!a)return{kind:"not_found"};if(a.includes("/")||EU.isAbsolute(t))for(const[e,i]of o){const o=[toPosix7(EU.relative(r,e)),toPosix7(EU.relative(n,e)),toPosix7(EU.relative(s,e))];if(EU.isAbsolute(t)){if(EU.resolve(t)===e)return{kind:"ok",canvas:i}}else if(o.includes(a))return{kind:"ok",canvas:i}}else{const e=[...o.entries()].filter(([e])=>EU.basename(e)===a);if(e.length>1)return{kind:"ambiguous",candidates:e.map(([e])=>toPosix7(EU.relative(r,e))).sort()};if(1===e.length)return{kind:"ok",canvas:e[0][1]}}const c=EU.isAbsolute(t)?[EU.resolve(t)]:[EU.join(r,a),EU.join(n,a),EU.join(s,a)];for(const e of c)if(await isCanvasFolder(e))return{kind:"ok",canvas:{contentPath:toPosix7(EU.relative(n,e)),hostCanvasPath:toPosix7(EU.relative(n,EU.join(e,"index.canvas.tsx"))),storyboards:[]}};return{kind:"not_found"}}function ambiguousCanvasSlugMessage(e,t){return`"${e}" names ${t.length} different canvases: ${t.join(", ")}. A bare folder name cannot tell them apart — retry with the full root-relative path of the one you mean.`}function isMissingPlaywright(e){const t=e instanceof Error?e.message:String(e);return/Cannot find (module|package) '?playwright'?/.test(t)}var LU="Headless canvas capture needs Playwright's Chromium. Install it next to @tempo-ai/mcp: `npm install playwright && npx playwright install chromium`, then retry.",MU=class extends Error{};function sleep5(e){return new Promise(t=>setTimeout(t,e))}async function withCaptureSession(e,t,n,r){let s=null,i=null;try{return s=await startDevserverSession2({repoRoot:e,hostCanvasPaths:[t]}),i=await startCaptureSession2({hostUrl:s.hostUrl,getAppUrl:s.getAppUrl,settleTimeoutMs:n}),await r(i)}finally{await(i?.dispose().catch(()=>{})),await(s?.dispose().catch(()=>{}))}}function downscalePngToFit(e,t){const n=NU.PNG.sync.read(Buffer.from(e));if(n.width<=t&&n.height<=t)return{pngBase64:Buffer.from(e).toString("base64"),width:n.width,height:n.height};const r=Math.min(t/n.width,t/n.height),s=Math.min(t,Math.max(1,Math.round(n.width*r))),i=Math.min(t,Math.max(1,Math.round(n.height*r))),o=new NU.PNG({width:s,height:i});for(let e=0;e<i;e+=1){const t=Math.floor(e*n.height/i),r=Math.max(t+1,Math.ceil((e+1)*n.height/i));for(let i=0;i<s;i+=1){const a=Math.floor(i*n.width/s),c=Math.max(a+1,Math.ceil((i+1)*n.width/s));let l=0,d=0,u=0,p=0,m=0;for(let e=t;e<r;e+=1)for(let t=a;t<c;t+=1){const r=4*(e*n.width+t),s=n.data[r+3];l+=n.data[r]*s,d+=n.data[r+1]*s,u+=n.data[r+2]*s,p+=s,m+=1}const f=4*(e*s+i),g=p||1;o.data[f]=Math.round(l/g),o.data[f+1]=Math.round(d/g),o.data[f+2]=Math.round(u/g),o.data[f+3]=Math.round(p/m)}}const a=NU.PNG.sync.write(o);return{pngBase64:Buffer.from(a).toString("base64"),width:s,height:i}}function compressShareHtml(e){const t=(new TextEncoder).encode(e),n=AU(t);return n.byteLength>=t.byteLength?{bytes:t,contentType:"text/html"}:{bytes:new Uint8Array(n),contentType:"application/gzip"}}async function uploadShareBlob(e,t,n,r){const s=await e.mutation(OU.projects.generateShareUploadUrl,{orgProjectId:t}),i=await fetch(s,{method:"POST",headers:{"Content-Type":r},body:n});if(!i.ok)throw new Error(`share blob upload failed with HTTP ${i.status}`);const{storageId:o}=await i.json();if("string"!=typeof o||!o)throw new Error("share blob upload returned no storageId");return o}function buildShareUrl(e){const t=new URL(`/${encodeURIComponent(e.orgProjectId)}/canvas/${encodeURIComponent(e.orgProjectId)}`,resolveShareBaseUrl());return t.searchParams.set("branch",e.branch),t.searchParams.set("content",e.contentPath),t.searchParams.set("env","prod"),t.toString()}function appendShareToken(e,t){const n=new URL(e);return n.searchParams.set("token",t),n.toString()}function createHeadlessCanvasHooks(e){const{workspace:n}=e,r=new t({url:e.convexUrl,authProvider:e.authProvider}),verifyProjectMatchesRepo=async t=>{const s=e.getOrgId();if(!s)return{kind:"error",code:"no_active_project",message:"No orgId was provided for this canvas_share call. Pass the orgId from tempo_list_orgs."};const i=await r.query(OU.projects.getOrgProjects,{organizationId:s}),o=(i??[]).find(e=>e?._id===t);if(!o)return{kind:"error",code:"no_active_project",message:`Project "${t}" was not found in organization "${s}" (or you are not a member). Pick the project for THIS repository from tempo_list_projects.`};const a=normalizeRepoUrl(await getRemoteUrl2(n.workspaceRoot));if(!a)return{kind:"error",code:"branch_not_pushed",message:"This repository has no git remote configured — a canvas share must point at a pushed branch of a registered project repo."};const c=(o.repos??[]).map(e=>normalizeRepoUrl(e.sourceUrl)).filter(e=>null!==e);return c.includes(a)?null:{kind:"error",code:"no_active_project",message:`This repository's remote (${a}) is not a registered repo of project "${o.name??t}". Sharing would persist this canvas under an unrelated project — pass the project that owns this repository (see tempo_list_projects).`}},captureScreenshot=async(e,t)=>{const r=await resolveCanvas(n,e.canvasSlug);if("ambiguous"===r.kind)return{kind:"error",code:"ambiguous_canvas_slug",message:ambiguousCanvasSlugMessage(e.canvasSlug,r.candidates)};if("not_found"===r.kind)return{kind:"error",code:"canvas_not_open",message:`No canvas matching "${e.canvasSlug}" exists under ${n.canvasesDir}. Pass the canvas's folder name, or its path under the canvases root.`};const s=r.canvas,i=s.storyboards.map(e=>e.storyboardId);let o;if(e.storyboard){const t=s.storyboards.find(t=>t.storyboardId===e.storyboard);if(!t)return{kind:"error",code:"storyboard_not_found",message:`Storyboard "${e.storyboard}" is not an export of canvas "${s.contentPath}".`,availableStoryboards:i};o=[t]}else o=s.storyboards;if(0===o.length)return{kind:"error",code:"storyboard_empty",message:`Canvas "${s.contentPath}" has no renderable component storyboards (route/html storyboards need the user's app dev server and cannot be captured headlessly).`};try{const r=await withCaptureSession(n.workspaceRoot,s.hostCanvasPath,t?.timeoutMs,async t=>{if(1===o.length&&e.storyboard){const e=o[0],n=await t.captureStoryboard({source:e.source,hostCanvasPath:s.hostCanvasPath,storyboardId:e.storyboardId,width:e.layout.width,height:e.layout.height});return n.pngBytes}const n=[];for(const e of o){const r=await t.captureStoryboard({source:e.source,hostCanvasPath:s.hostCanvasPath,storyboardId:e.storyboardId,width:e.layout.width,height:e.layout.height});n.push({pngBytes:r.pngBytes,x:e.layout.x,y:e.layout.y})}return compositeStoryboardPngs(n,{padding:"5%"}).pngBytes}),i=downscalePngToFit(r,FU);return{kind:"ok",pngBase64:i.pngBase64,width:i.width,height:i.height}}catch(e){return{kind:"error",code:"capture_threw",message:isMissingPlaywright(e)?LU:`Headless canvas capture failed: ${e instanceof Error?e.message:String(e)}`}}},captureStoryboardStability=async(e,t)=>{const r=await resolveCanvas(n,e.canvasSlug);if("ambiguous"===r.kind)return{kind:"error",code:"ambiguous_canvas_slug",message:ambiguousCanvasSlugMessage(e.canvasSlug,r.candidates)};if("not_found"===r.kind)return{kind:"error",code:"canvas_not_open",message:`No canvas matching "${e.canvasSlug}" exists under ${n.canvasesDir}. Pass the canvas's folder name, or its path under the canvases root.`};const s=r.canvas,i=s.storyboards.find(t=>t.storyboardId===e.storyboard);if(!i)return{kind:"error",code:"storyboard_not_found",message:`Storyboard "${e.storyboard}" is not an export of canvas "${s.contentPath}".`,availableStoryboards:s.storyboards.map(e=>e.storyboardId)};try{const r=await withCaptureSession(n.workspaceRoot,s.hostCanvasPath,t?.timeoutMs,async n=>{let r=0;for(let o=0;o<e.runs;o+=1){if(t?.signal?.aborted)throw t.signal.reason??new Error("Capture aborted");const a=determinismProbeForRun(o),c=await n.captureStoryboard({source:i.source,hostCanvasPath:s.hostCanvasPath,storyboardId:i.storyboardId,width:i.layout.width,height:i.layout.height,...a.options});if(looksBlank(c.pngBytes))throw new Error(`Storyboard "${i.storyboardId}" rendered an empty frame on run ${o+1}/${e.runs} (${a.name}).`);await(t?.onCapture?.({pngBase64:Buffer.from(c.pngBytes).toString("base64"),width:c.width,height:c.height,condition:a.name})),r+=1}return r});return{kind:"ok",runs:r}}catch(e){return{kind:"error",code:"capture_threw",message:isMissingPlaywright(e)?LU:`Headless VRT stability capture failed: ${e instanceof Error?e.message:String(e)}`}}},createShareLink=async t=>{const s=e.getOrgProjectId();if(!s)return{kind:"error",code:"no_active_project",message:"No projectId was provided for this canvas_share call. Pass the projectId from tempo_list_projects."};const i=await resolveCanvas(n,t.canvasSlug);if("ambiguous"===i.kind)return{kind:"error",code:"ambiguous_canvas_slug",message:ambiguousCanvasSlugMessage(t.canvasSlug,i.candidates)};if("not_found"===i.kind)return{kind:"error",code:"no_canvas_path",message:`Could not find a local canvas for "${t.canvasSlug}". Pass the canvas's folder name (slug).`};const o=i.canvas,a=o.contentPath,c=await computeShareStatus(n.workspaceRoot),l=c.currentBranch,d=c.uncommittedFiles.length,u=c.unpushedCommits,p=0===d&&0===u&&c.hasRemote;if(!p)return{kind:"error",code:"branch_not_pushed",message:buildBranchNotPushedMessage2(a,{branch:l,uncommittedCount:d,unpushedCount:u,hasRemote:c.hasRemote}),details:{branch:l,uncommittedCount:d,unpushedCount:u,hasRemote:c.hasRemote}};const m=await checkBranchOnRemote(n.workspaceRoot,l);if(!1===m)return{kind:"error",code:"branch_not_pushed",message:`Branch "${l}" is not on the remote, even though local git history says it was pushed (the remote repository may have been recreated). Push the branch again, then share.`,details:{branch:l,uncommittedCount:0,unpushedCount:0,hasRemote:!0}};const f=await verifyProjectMatchesRepo(s);if(f)return f;if(0===o.storyboards.length)return{kind:"error",code:"capture_failed",message:`Canvas "${a}" has no renderable component storyboards to share — add a storyboard, then share again.`};let g,y,b;try{const e=await withCaptureSession(n.workspaceRoot,o.hostCanvasPath,void 0,async e=>{const t=[];for(const n of o.storyboards){const r={source:n.source,hostCanvasPath:o.hostCanvasPath,storyboardId:n.storyboardId,width:n.layout.width,height:n.layout.height,artifacts:["png","html"],portableHtml:!0};let s=await e.captureStoryboardArtifacts(r);if(s.styles&&isStyleStarved(s.styles)&&(await sleep5(5e3),s=await e.captureStoryboardArtifacts(r),s.styles&&isStyleStarved(s.styles)))throw new MU(`storyboard "${n.storyboardId}": `+describeStyleStarvation(s.styles));if(!s.png||!s.html)throw new Error(`storyboard "${n.storyboardId}" produced no capture artifacts`);t.push({storyboard:n,png:s.png,html:s.html})}return t}),t=compositeStoryboardPngs(e.map(e=>({pngBytes:e.png.pngBytes,x:e.storyboard.layout.x,y:e.storyboard.layout.y})),{padding:"5%"});b=downscalePngToFit(t.pngBytes,FU),g=[];for(const t of e){const{bytes:e,contentType:n}=compressShareHtml(t.html.html);g.push({id:t.storyboard.storyboardId,x:t.storyboard.layout.x,y:t.storyboard.layout.y,width:t.storyboard.layout.width,height:t.storyboard.layout.height,htmlStorageId:await uploadShareBlob(r,s,e,n)})}try{y=await uploadShareBlob(r,s,t.pngBytes,"image/png")}catch(e){console.error("[tempo-mcp] canvas_share: composite screenshot upload failed:",e instanceof Error?e.message:String(e))}}catch(e){return e instanceof MU?{kind:"error",code:"unstyled_render",message:`Refusing to share an unstyled render — ${e.message}`}:{kind:"error",code:"capture_failed",message:isMissingPlaywright(e)?LU:`Could not capture the canvas for sharing: ${e instanceof Error?e.message:String(e)}`}}try{await r.mutation(OU.projects.upsertShareSnapshot,{orgProjectId:s,contentPath:a,branch:l,...y?{screenshotStorageId:y}:{},storyboards:g});let e=buildShareUrl({orgProjectId:s,branch:l,contentPath:a}),n=!1;if(t.makePublic){const t=await r.mutation(OU.publicShares.enablePublicShare,{artifactType:"canvas",orgProjectId:s,contentPath:a,branch:l}),i=t?.token;if(!i)return{kind:"error",code:"share_failed",message:"The share snapshot was created, but enabling public (anyone-with-the-link) access failed — you may not be authenticated. Retry, or omit public to share a member-only link."};e=appendShareToken(e,i),n=!0}return{kind:"ok",shareUrl:e,isPublic:n,canvasPath:a,branch:l,storyboardCount:g.length,skippedStoryboardIds:[],pngBase64:b.pngBase64,width:b.width,height:b.height}}catch(e){return{kind:"error",code:"share_failed",message:`Could not create the share link: ${e instanceof Error?e.message:String(e)}`}}};return{canvasScreenshot:{capture:captureScreenshot,managesDevserver:!0},canvasStoryboardStability:{captureRuns:captureStoryboardStability,managesDevserver:!0},canvasShare:{create:createShareLink}}}function buildBranchNotPushedMessage2(e,t){const n=[];t.uncommittedCount>0&&n.push(`${t.uncommittedCount} uncommitted file(s)`),t.unpushedCount>0&&n.push(`${t.unpushedCount} unpushed commit(s)`),t.hasRemote||n.push("no git remote is configured");const r=n.length>0?` Found ${n.join(", ")}.`:"";return`Cannot share canvas "${e}": its branch "${t.branch}" must be committed and pushed to a remote (clean git state) before it can be shared, so the recipient can access the code.`+r+" Commit and push all changes, then retry canvas_share."}var UU='Tempo workspace tools. SCOPING: every issues_*/docs_*/comments_*/agents_*/slack_*/linear_*/script tool requires an explicit orgId — call tempo_list_orgs once to discover it; project-scoped agents/scripts tools (and canvas_share) also require projectId — call tempo_list_projects; if the org has no project for the current repo yet, register it with tempo_register_project. Toolsets: issues, cloud docs, canvas comments, custom agents, run scripts, Slack (acts as the org\'s Tempo bot), Linear. In a Tempo repo, canvas tools (canvas_*, asset_*) design against production components — call get_guide({ topic: "tempo-canvas-instructions" }) before canvas work. For a selection in an open Tempo desktop canvas, call list_design_context_targets then get_design_context with orgId; this works outside a repo over Convex. Cross-link artifacts with link_items.';function toolRequiresAuth(e,t){return"canvas"!==e||"canvas_share"===t}async function createTempoAggregate(e,t={}){const{signInPrompt:n,authWaitMs:r,...l}=t,u=l.convexUrl??y(),p=g(u),m=o({convexSiteUrl:p,attemptReauth:d(p),onReauthRequired:()=>{console.error("[tempo-mcp] Tempo session expired — the next Tempo tool call will prompt for sign-in.")}});m.start();const v=n??a({authUrl:process.env.TEMPO_AUTH_URL}),w=createAuthGate({convexSiteUrl:p,refreshLoop:m,signInPrompt:v,waitMs:r??b()});let x=null,S=null,E=0;const A=new Set,C=e.toolsets.includes("canvas")?c():null,I=l.authProvider??i(m),P={authProvider:I,convexUrl:u,getOrgId:()=>x,getUserId:()=>f()?.userId??null,getCurrentOrgGeneration:()=>E,onActiveOrgChange:e=>(A.add(e),()=>A.delete(e)),getOrgProjectId:()=>S,getWritePermission:()=>!e.readonly,canvasHooks:C?createHeadlessCanvasHooks({workspace:C,convexUrl:u,authProvider:I,getOrgId:()=>x,getOrgProjectId:()=>S}):void 0,...l},R=buildBackends(P,e.toolsets,C);R.push({toolset:"tempo",server:createHostToolsServer({authProvider:P.authProvider,convexUrl:P.convexUrl})});const N=await s({name:"tempo",version:kU,instructions:UU,backends:R,filterTool:(t,n)=>isExternallyExposed(n,{readonly:e.readonly}),injectParams:scopeParamsFor,gateCall:(e,t)=>toolRequiresAuth(e,t)?w.ensure():Promise.resolve(null),onScopedCall:e=>{const t=e.orgId??null;if(t!==x){x=t,E+=1;for(const e of A)e()}S=e.projectId??null}});return{aggregate:N,dispose:async()=>{m.stop(),v.dispose(),await N.dispose()}}}async function runServe(e){p({binaryName:"tempo"});const t=await createTempoAggregate(e),n=new su;return await t.aggregate.connect(n),await new Promise(e=>{n.onclose=()=>e(),process.stdin.on("close",()=>e())}),await t.dispose(),0}export{createTempoAggregate,runServe,scopeParamsFor,toolRequiresAuth};
320
+ `;function resolveAppUiFramework(e){if("flutter"===e)return"react";if(void 0===e)return"react";if(isTempoUiFramework(e)&&"flutter"!==e)return e;const t=iy.map(e=>`"${e}"`).join(", ");throw new Error(`tempo.config.json sets apps[0].uiFramework to "${e}", which this version of Tempo does not support (it supports ${t}). Update Tempo to use this project's canvas. Tempo keeps the value as written.`)}var yT={react:["vite","nextjs","expo"],svelte:["vite"],vue:["vite","nuxt"],astro:["vite"],flutter:["vite"]};function canvasHostRendersUiFramework(e,t){return yT[t].includes(e)}async function pathExists4(e){try{return await Zy(e),!0}catch{return!1}}async function ensureDirectoryExists(e){await eb(e,{recursive:!0})}var bT={"@tailwindcss/vite":"^4.0.0","@vitejs/plugin-react":"^5.0.0",tailwindcss:"^4.0.0",postcss:"^8.5.6","tempo-sdk":vb,typescript:"^5.9.0",vite:"^7.0.0","vite-tsconfig-paths":"^6.0.0"},vT={"postcss-load-config":"^6.0.1","@vitejs/plugin-react":"^5.0.0",autoprefixer:"^10.4.20",postcss:"^8.4.49",tailwindcss:"^3.4.17","tempo-sdk":vb,typescript:"^5.9.0",vite:"^7.0.0","vite-tsconfig-paths":"^6.0.0"},wT={react:"^18.3.1","react-dom":"^18.3.1"},_T={svelte:"5.56.9"},xT={"@sveltejs/vite-plugin-svelte":"6.2.4"},TT={vue:"3.5.44"},kT={"@vitejs/plugin-vue":"6.0.10"},ST={react:{label:"React",marker:null,imports:"",pluginCalls:()=>"",reactPluginCall:" react(),\n",dedupe:[],prebundle:[],tsconfigPathsOptions:"",packages:null},svelte:{label:"Svelte",marker:"// @tempo-ui-framework: svelte",imports:'import { svelte } from "@sveltejs/vite-plugin-svelte";\n',pluginCalls:()=>' svelte({ configFile: path.join(tempoRoot, "svelte.config.mjs") }),\n',reactPluginCall:" react(),\n",dedupe:["svelte"],prebundle:[],tsconfigPathsOptions:"",packages:{dependencies:_T,runtimeFollowsApp:!1,devDependencies:xT,appSignals:["svelte","@sveltejs/kit"]}},vue:{label:"Vue",marker:"// @tempo-ui-framework: vue",imports:'import vue from "@vitejs/plugin-vue";\nimport { tempoVueAppPlugins, tempoVuePlugin } from "tempo-sdk/vue";\n',pluginCalls:e=>` ...tempoVuePlugin({ root: tempoRoot, sourceRoot: projectRoot, enabled: true }),\n tempoVueAppPlugins({ root: tempoRoot, appRoot: ${vueAppRootExpression(e)}, vue }),\n`,reactPluginCall:' react({ jsxImportSource: "react" }),\n',dedupe:["vue"],prebundle:["vue"],tsconfigPathsOptions:" importerFilter: (importer) => /\\.(vue|[mc]?[jt]sx?)$/.test(importer),\n",packages:{dependencies:TT,runtimeFollowsApp:!0,devDependencies:kT,appSignals:["vue","nuxt"]}},astro:{label:"Astro",marker:null,imports:"",pluginCalls:()=>"",reactPluginCall:" react(),\n",dedupe:[],prebundle:[],tsconfigPathsOptions:"",packages:null}},ET={dev:"vite",build:"vite build",preview:"vite preview --host 127.0.0.1"},AT={"@tailwindcss/postcss":"^4.0.0","@types/node":"^25.0.0","@types/react":"^19.0.0","@types/react-dom":"^19.0.0","tempo-sdk":vb,tailwindcss:"^4.0.0",postcss:"^8.5.6",typescript:"^5.9.0"},CT={"@types/node":"^25.0.0","@types/react":"^19.0.0","@types/react-dom":"^19.0.0",autoprefixer:"^10.4.20",postcss:"^8.4.49","postcss-import":"^16.1.0","postcss-url":"^10.1.3","tempo-sdk":vb,tailwindcss:"^3.4.17",typescript:"^5.9.0"},IT={next:"^16.0.0",react:"^19.0.0","react-dom":"^19.0.0"},PT={dev:"next dev -p 0",build:"next build",start:"next start -p 0"},DT=new Set(["@tailwindcss/vite","@vitejs/plugin-react","vite","vite-tsconfig-paths"]),RT={"@types/react":"^19.2.0","tempo-sdk":vb,typescript:"^5.9.0"},NT={expo:"~56.0.5",react:"19.2.3","react-dom":"19.2.3","react-native":"0.85.3","react-native-web":"~0.21.0"},OT=new Set(["expo-constants","expo-linking","expo-router","expo-splash-screen","react-native-reanimated","react-native-safe-area-context","react-native-screens","react-native-worklets"]),FT={dev:"expo start --web",start:"expo start --web"},LT='<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <title>tempo-host</title>\n </head>\n <body>\n <div id="root"></div>\n <script type="module" src="./main.tsx"><\/script>\n </body>\n</html>\n',MT='import { createRoot } from "react-dom/client";\nimport "./globals.css";\nimport TempoHost from "./.tempo/tempo-host";\n\n// This is the Tempo canvas dev server ("tempo-host"). It exists only to render\n// your real components onto the design canvas — it is NOT your app. Build your\n// actual app OUTSIDE the tempo/ folder, at the project root (e.g. src/...).\n//\n// Deliberately NOT wrapped in <StrictMode>: the host mounts every storyboard as\n// its own full production component tree (often dozens of live frames), and\n// StrictMode\'s dev-only double-invoke of every render + mount effect roughly\n// doubles that mount cost — a real, visible "the canvas takes a while to load"\n// hit. StrictMode renders nothing and is dev-only, so omitting it here is purely\n// a canvas load-time win with zero visual or production impact. Your real app\n// (outside tempo/) keeps whatever StrictMode setup it already had.\ncreateRoot(document.getElementById("root")!).render(<TempoHost />);\n',UT='// @tempo-home — Tempo home canvas (the workspace Run button opens this). Managed marker; do not remove.\n//\n// One storyboard rendering your app\'s home route ("/"). Run (workspace header)\n// opens this canvas beside your app\'s dev-server logs. Set the app dev command\n// (set_app_dev_command) so the "/" route renders here.\n\nimport { Canvas, RouteStoryboard } from "tempo-sdk/canvas";\n\nexport default function HomeCanvas() {\n return (\n <Canvas name="Home">\n <RouteStoryboard\n id="Home"\n name="Home (/)"\n route="/"\n layout={{ x: 0, y: 0, width: 1280, height: 832 }}\n />\n </Canvas>\n );\n}\n',jT='export default function Page() {\n return (\n <main className="min-h-screen flex items-center justify-center bg-[#0E0E0E] text-white/60">\n <p className="text-sm">Tempo canvas dev server. Open the Design tab to view canvases.</p>\n </main>\n );\n}\n',BT='"use client";\n\nimport dynamic from "next/dynamic";\n\nconst TempoHost = dynamic(() => import("../../.tempo/tempo-host"), {\n ssr: false,\n});\n\nexport default function Page() {\n return <TempoHost />;\n}\n',$T="// @tempo-owned: nuxt-sidecar",WT="nuxt.config.ts",HT="nuxt-app-layer",qT='// @tempo-owned: nuxt-app-layer\n// Loaded by your app\'s own `nuxt dev` for Tempo route storyboards through\n// `--extends` in tempo/tempo.config.json (apps[0].start), never from your\n// nuxt.config. It only annotates your .vue sources for the canvas, and only\n// when Tempo starts the server (TEMPO=true).\nexport default defineNuxtConfig({\n modules: ["tempo-sdk/nuxt"],\n});\n',zT=["nuxt.config.ts","nuxt.config.js","nuxt.config.mjs","nuxt.config.mts","nuxt.config.cjs"],GT="app",VT=["app.vue","pages/tempo-host.vue","components/TempoHostMount.vue"],KT="\x3c!-- Tempo canvas dev server, not your app. Build your app outside tempo/. --\x3e\n<template>\n <NuxtPage />\n</template>\n",XT='<script setup lang="ts">\ndefinePageMeta({ layout: false });\n<\/script>\n\n<template>\n <ClientOnly>\n <TempoHostMount />\n </ClientOnly>\n</template>\n',YT="// @tempo-owned: expo-index";function buildExpoIndexJs(e={}){const t=e.nativewind?'import "./global.css";\n':"",n=e.metroRuntime?'import "@expo/metro-runtime";\n':"";return`${YT}\n${t}${n}import { registerRootComponent } from "expo";\nimport App from "./App";\n\nregisterRootComponent(App);\n`}function isTempoOwnedExpoIndexJs(e){return!!e.startsWith(YT)||e.includes("registerRootComponent")&&e.includes('"./App"')}var JT="// Tempo-generated inert stub for Storybook imports in the canvas host.\nfunction StorybookStub() {\n return null;\n}\nmodule.exports = StorybookStub;\nmodule.exports.default = StorybookStub;\n",QT='import { Text, View } from "react-native";\nimport TempoHost from "./.tempo/tempo-host";\n\nconst isTempoHostRoute =\n typeof window !== "undefined" &&\n window.location.pathname.startsWith("/tempo-host");\n\nexport default function App() {\n if (isTempoHostRoute) {\n return <TempoHost />;\n }\n\n return (\n <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>\n <Text>Tempo Expo sidecar</Text>\n </View>\n );\n}\n';function buildExpoPublicIndexHtml(e){return'<!DOCTYPE html>\n<html lang="%LANG_ISO_CODE%">\n <head>\n <meta charset="utf-8" />\n <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />\n \x3c!--\n The `content` is stamped at runtime by the tempo-sdk Expo Babel plugin\n (which writes this machine\'s absolute sidecar root into the live DOM). It\n is intentionally left empty here so this committed file holds no\n machine-specific path. The empty marker still satisfies the dev server\'s\n tempo-host readiness check, which greps the served HTML for the attribute\n name (`tempo-devserver.ts` `isTempoHostDocument`).\n --\x3e\n <meta name="tempo-project-root" content="" />\n <title>%WEB_TITLE%</title>\n <style id="expo-reset">\n html,\n body {\n height: 100%;\n }\n body {\n overflow: hidden;\n }\n #root {\n display: flex;\n height: 100%;\n flex: 1;\n }\n </style>\n </head>\n\n <body>\n <noscript>You need to enable JavaScript to run this app.</noscript>\n <div id="root"></div>\n </body>\n</html>\n'}function buildExpoAppJson(e){return`${JSON.stringify({expo:{name:`${lb.basename(e.projectRoot)} Tempo`,slug:sanitizePackageName(`${lb.basename(e.projectRoot)}-tempo`),platforms:["web"],web:{bundler:"metro"},scheme:"tempo-sidecar"}},null,2)}\n`}var ZT="// @tempo-owned: expo-babel-config";function buildExpoBabelConfig(e={}){const t=e.nativewind?'[\n ["babel-preset-expo", { jsxImportSource: "nativewind" }],\n "nativewind/babel",\n ]':'["babel-preset-expo"]';return`${ZT}\nconst { tempoExpoBabelPlugin } = require("tempo-sdk/expo/plugin");\n\nmodule.exports = function (api) {\n // The Tempo plugin only annotates when TEMPO=true. Key Babel's config cache\n // on TEMPO (instead of api.cache(true)) so toggling it re-evaluates the\n // config rather than reusing a stale build.\n api.cache.using(() => process.env.TEMPO);\n return {\n presets: ${t},\n plugins: [\n [\n tempoExpoBabelPlugin,\n {\n // Annotate filepaths relative to the Tempo sidecar root (this dir),\n // matching the Next.js sidecar convention. The canvas resolves\n // \`data-tempo-filepath\` against the \`tempo-project-root\` meta (also\n // this dir), so parent app code resolves via \`../src/...\`.\n root: __dirname,\n },\n ],\n ],\n };\n};\n`}function isTempoOwnedExpoBabelConfig(e){return!!e.startsWith(ZT)||e.includes('require("tempo-sdk/expo/plugin")')&&e.includes("api.cache.using(() => process.env.TEMPO)")}function convertAliasPathsToMetroEntries(e){const t=[];for(const[n,r]of Object.entries(e)){if(0===r.length)continue;const e=r[0];n.endsWith("/*")&&e.endsWith("/*")&&t.push({prefix:n.slice(0,-1),targetRelToTempo:e.slice(0,-2)||"."})}return t}var ek="// @tempo-owned: expo-metro-config";function buildExpoMetroConfig(e=[],t={}){const n=JSON.stringify(e.map(e=>({prefix:e.prefix,target:e.targetRelToTempo}))),r=JSON.stringify(Object.fromEntries((t.webShims??[]).map(e=>[e.module,e.targetRelToTempo]))),s=t.svgTransformer?'\n// react-native-svg-transformer: turn .svg imports into components.\nconfig.transformer.babelTransformerPath = require.resolve(\n "react-native-svg-transformer/expo",\n);\nconfig.resolver.assetExts = config.resolver.assetExts.filter(\n (ext) => ext !== "svg",\n);\nconfig.resolver.sourceExts = [...config.resolver.sourceExts, "svg"];\n':"",i=t.nativewind?'const { withNativeWind } = require("nativewind/metro");\n':"",o=t.nativewind?'module.exports = withNativeWind(config, { input: "./global.css" });':"module.exports = config;";return`${ek}\nconst path = require("node:path");\nconst fs = require("node:fs");\nconst { getDefaultConfig } = require("expo/metro-config");\n${i}\nconst projectRoot = __dirname;\nconst workspaceRoot = path.resolve(projectRoot, "..");\nconst sidecarNodeModules = path.join(projectRoot, "node_modules");\n\nconst config = getDefaultConfig(projectRoot);\n\n// Resolve packages via their legacy \`main\`/\`react-native\`/\`browser\` fields\n// (CJS) instead of the modern \`exports\` conditions. Some deps ship an ESM\n// build under \`exports["import"]\` that uses Vite-isms (\`import.meta.env.MODE\`,\n// \`import.meta.url\`) — e.g. zustand 5's \`./esm/middleware.mjs\`, which a store\n// using \`zustand/middleware\` pulls in. On web Metro matches the \`import\`\n// condition and bundles that ESM build verbatim (it does NOT transform\n// \`import.meta\`), so the module throws "Cannot use 'import.meta' outside a\n// module" the moment it loads in the classic-script web bundle — taking the\n// storyboard that imported it down with it. Disabling package exports makes\n// Metro fall back to \`main\` (CJS, no \`import.meta\`). Tightening the condition\n// set alone is NOT enough — Metro still picks the ESM build for web. The\n// trade-off: a package that ONLY ships via \`exports\` (no \`main\`) won't\n// resolve, but those are rare in the Expo/RN ecosystem (RN requires CJS).\nconfig.resolver.unstable_enablePackageExports = false;\n\n// Storybook stub. Storybook for React Native leaks into a canvas's module\n// graph (a canvas importing \`@/app/storybook\`, Expo Router auto-discovering\n// \`app/storybook.tsx\`, or \`.rnstorybook/storybook.requires\` globbing every\n// \`*.stories.*\` file). It then pulls on-device addons (\`@storybook/addon-*\`)\n// and native-only deps (\`@gorhom/bottom-sheet\`) that aren't installed for web,\n// failing the WHOLE bundle (eager canvas requires mean one broken canvas\n// breaks all). Storybook is never rendered in a canvas, so the resolveRequest\n// hook below substitutes any storybook/story import with an inert stub\n// (emitted at \`.tempo-storybook-stub.js\`). The matching tests live in the\n// metro-resolve suite.\nconst tempoStorybookStub = path.resolve(projectRoot, ".tempo-storybook-stub.js");\nconst isStorybookModule = (name) =>\n name.includes("storybook") || /\\.stories(\\.|$)/.test(name);\n${s}\n// NOTE: We deliberately do NOT \`require()\` and inherit the user app's\n// metro.config.js. Many real configs (NativeWind via withNativeWind, Storybook\n// via withStorybook) throw when evaluated outside their own project context\n// ("Tailwind CSS has not been configured with the NativeWind preset"), which\n// would break the whole sidecar bundle. Per-feature support (svg transformer,\n// NativeWind, web shims) is added explicitly here rather than by wholesale\n// config inheritance.\nconst userMetroResolveRequest = null;\n\nconst sidecarModule = (moduleName) =>\n path.join(sidecarNodeModules, ...moduleName.split("/"));\nconst singletonModules = {\n react: sidecarModule("react"),\n "react-dom": sidecarModule("react-dom"),\n "react-native": sidecarModule("react-native"),\n "react-native-web": sidecarModule("react-native-web"),\n "react/jsx-runtime": sidecarModule("react/jsx-runtime.js"),\n "react/jsx-dev-runtime": sidecarModule("react/jsx-dev-runtime.js"),\n};\n\nconfig.watchFolders = Array.from(\n new Set([...(config.watchFolders ?? []), workspaceRoot]),\n);\nconfig.resolver.nodeModulesPaths = Array.from(\n new Set([\n sidecarNodeModules,\n path.join(workspaceRoot, "node_modules"),\n ...(config.resolver.nodeModulesPaths ?? []),\n ]),\n);\n// Hierarchical lookup stays ENABLED so Metro can walk parent directories to\n// resolve transitively-nested deps (e.g. react-native-reanimated@4's bundled\n// semver@7, required by its scripts/validate-worklets-version.js — the\n// root-hoisted semver@6 has no functions/satisfies subpath, so disabling the\n// walk fails the canvas at module load: "Unable to resolve module\n// semver/functions/satisfies").\n//\n// The trade-off: with hierarchical lookup on, Metro's resolver.alias /\n// extraNodeModules become FALLBACKS — a hierarchical walk can find a\n// duplicate React copy nested under some package BEFORE the alias applies,\n// which surfaces as "Invalid hook call ... more than one copy of React". So\n// the React singleton is NOT enforced via alias here; it's enforced via the\n// resolveRequest hook below, which takes precedence over ALL resolution.\nconfig.resolver.disableHierarchicalLookup = false;\nconfig.resolver.extraNodeModules = {\n ...(config.resolver.extraNodeModules ?? {}),\n ...singletonModules,\n};\nconfig.resolver.alias = {\n ...(config.resolver.alias ?? {}),\n ...singletonModules,\n};\n\n// React-family packages that MUST resolve to exactly one copy (the sidecar's),\n// no matter which module imports them or how deeply nested it is. react +\n// react-dom are the renderer/runtime pair whose duplication causes "Invalid\n// hook call" — forcing them through resolveRequest (which runs before\n// hierarchical resolution) is the only reliable singleton guarantee once\n// hierarchical lookup is on. NativeWind also keys its interop registry by\n// component identity: its react-native imports and Babel's direct\n// react-native-web subpath imports must resolve to the SAME web components.\nconst forcedReactSingletons = {\n react: path.join(sidecarNodeModules, "react"),\n "react-dom": path.join(sidecarNodeModules, "react-dom"),\n "react-native-web": path.join(sidecarNodeModules, "react-native-web"),\n};\nconst tempoSdkRuntimeModules = {\n "tempo-sdk/canvas": path.join(sidecarNodeModules, "tempo-sdk", "dist", "canvas", "index.js"),\n "tempo-sdk/canvas/astro": path.join(sidecarNodeModules, "tempo-sdk", "dist", "canvas", "astro.js"),\n "tempo-sdk/canvas/astro-contract": path.join(sidecarNodeModules, "tempo-sdk", "dist", "canvas", "astro-contract.js"),\n "tempo-sdk/astro/asset-preview-client": path.join(sidecarNodeModules, "tempo-sdk", "dist", "astro", "asset-preview-client.js"),\n "tempo-sdk/astro/controls": path.join(sidecarNodeModules, "tempo-sdk", "dist", "astro", "controls.js"),\n "tempo-sdk/assets": path.join(sidecarNodeModules, "tempo-sdk", "dist", "assets", "index.js"),\n};\n\n// Mirror the user app's tsconfig.paths so canvas imports like\n// "@/app/components/X" resolve through Metro the same way TypeScript and\n// the user's app already resolve them. The aliases array below is baked\n// in at scaffold time (regenerated on every ensureInitialized pass when\n// the user's tsconfig changes).\nconst tempoTsconfigAliases = ${n}.map((a) => ({\n prefix: a.prefix,\n target: path.resolve(projectRoot, a.target),\n}));\n\n// Web shims for native-only modules: { "react-native-maps": "../web-shims/..." }.\n// Native-only RN modules (react-native-maps, expo-camera, …) cannot bundle on\n// web — Metro throws "Importing native-only module … on web" and the whole\n// bundle fails. The app keeps browser stand-ins in a web-shims/ dir; we\n// replicate the mapping so any canvas transitively importing one still bundles.\nconst tempoWebShims = ${r};\n\n// Always install the resolveRequest hook (even with no tsconfig aliases) so\n// the React singleton enforcement runs on every project. Order:\n// 1. React singletons (highest priority — must win over everything).\n// 2. Tempo SDK runtime subpaths that package-exports-disabled Metro cannot\n// resolve through package.json exports.\n// 3. Web shims (web platform only) for native-only modules.\n// 4. User @/ tsconfig aliases (canvas imports of app source).\n// 5. Expo's default resolver (including native-platform react-native).\nconst baseResolveRequest = userMetroResolveRequest || config.resolver.resolveRequest;\nconfig.resolver.resolveRequest = (context, moduleName, platform) => {\n if (isStorybookModule(moduleName)) {\n return { type: "sourceFile", filePath: tempoStorybookStub };\n }\n if (platform === "web" && moduleName === "react-native") {\n return context.resolveRequest(context, forcedReactSingletons["react-native-web"], platform);\n }\n for (const pkg of Object.keys(forcedReactSingletons)) {\n const pkgRoot = forcedReactSingletons[pkg];\n if (moduleName === pkg) {\n return context.resolveRequest(context, pkgRoot, platform);\n }\n if (moduleName.startsWith(pkg + "/")) {\n const subpath = moduleName.slice(pkg.length + 1);\n return context.resolveRequest(\n context,\n path.join(pkgRoot, subpath),\n platform,\n );\n }\n }\n const tempoSdkRuntimeModule = tempoSdkRuntimeModules[moduleName];\n if (tempoSdkRuntimeModule) {\n return context.resolveRequest(context, tempoSdkRuntimeModule, platform);\n }\n if (platform === "web") {\n const shimRel = tempoWebShims[moduleName];\n if (shimRel) {\n return {\n type: "sourceFile",\n filePath: path.resolve(projectRoot, shimRel),\n };\n }\n }\n for (const { prefix, target } of tempoTsconfigAliases) {\n if (moduleName.startsWith(prefix)) {\n const rewritten = path.join(target, moduleName.slice(prefix.length));\n return context.resolveRequest(context, rewritten, platform);\n }\n }\n if (baseResolveRequest) {\n return baseResolveRequest(context, moduleName, platform);\n }\n return context.resolveRequest(context, moduleName, platform);\n};\n\n// The component pool probes every host for Vite's explicit registration\n// barrier before loading a runtime document. Metro cannot provide Vite's\n// transform receipt, but it must complete the cross-origin handshake so the\n// client can identify it as an unsupported host and use its runtime-ACK\n// fallback. Without these CORS responses the browser reports "Failed to\n// fetch", which is indistinguishable from a dead host and blocks projection.\n// Matches CANVAS_HOST_REGISTRATION_ENDPOINT in tempo-sdk's registration\n// contract (a generated config cannot import it).\nconst tempoRegistrationEndpoint = "/__tempo/canvas-host-registration";\n// The SDK also opens \`new EventSource("/__tempo/errors")\` in every host\n// document. Only the Vite plugin serves that stream; on Metro the request falls\n// through to Expo's history fallback, which answers the index HTML, and the\n// browser logs \`EventSource's response has a MIME type ("text/html") that is\n// not "text/event-stream"\` on every Expo canvas load. A 204 fails the\n// connection per the SSE spec with no console error and without holding a\n// socket open (a real stream would, and that can block Metro's shutdown).\n// Metro has no server-error stream to proxy here.\nconst tempoErrorsEndpoint = "/__tempo/errors";\nconst baseEnhanceMiddleware = config.server?.enhanceMiddleware;\nconfig.server = {\n ...(config.server ?? {}),\n enhanceMiddleware: (middleware, server) => {\n const baseMiddleware = baseEnhanceMiddleware\n ? baseEnhanceMiddleware(middleware, server)\n : middleware;\n return (req, res, next) => {\n const requestPath = req.url?.split("?")[0];\n if (requestPath === "/__tempo/identity" && req.method === "GET") {\n // Match the SDK copy forced by tempoSdkRuntimeModules, including links.\n let sdk = {};\n try {\n const sdkManifestPath = path.join(sidecarNodeModules, "tempo-sdk", "package.json");\n sdk = JSON.parse(fs.readFileSync(sdkManifestPath, "utf8")) ?? {};\n } catch {}\n let workspaceNonce = process.env.TEMPO_WORKSPACE_NONCE?.trim() ?? "";\n if (!workspaceNonce) {\n try {\n const noncePath = path.join(projectRoot, ".tempo", "workspace-nonce");\n workspaceNonce = fs.readFileSync(noncePath, "utf8").trim();\n } catch {}\n }\n res.statusCode = 200;\n res.setHeader("Cache-Control", "no-store");\n res.setHeader("Content-Type", "application/json; charset=utf-8");\n res.setHeader("x-tempo-host-identity", "1");\n res.setHeader("Access-Control-Allow-Origin", "*");\n res.end(JSON.stringify({\n tempoHost: true,\n contractVersion: 1,\n workspaceNonce,\n sdkVersion: sdk.version,\n sdkChannel: "latest",\n tempoRuntimeContract: sdk.tempoRuntimeContract,\n pluginActive: Boolean(process.env.TEMPO),\n framework: "expo",\n }));\n return;\n }\n\n // Method-gated exactly like the Vite plugin's handlers: anything else\n // (a POST to the errors path, a GET to the registration path) falls\n // through to Metro instead of being swallowed with an empty 204.\n const handled =\n (requestPath === tempoRegistrationEndpoint &&\n (req.method === "POST" || req.method === "OPTIONS")) ||\n (requestPath === tempoErrorsEndpoint &&\n (req.method === "GET" || req.method === "OPTIONS"));\n if (!handled) {\n return baseMiddleware(req, res, next);\n }\n res.setHeader("Access-Control-Allow-Origin", "*");\n if (req.method === "OPTIONS") {\n res.setHeader(\n "Access-Control-Allow-Methods",\n requestPath === tempoErrorsEndpoint\n ? "GET, OPTIONS"\n : "POST, OPTIONS",\n );\n res.setHeader("Access-Control-Allow-Headers", "content-type");\n }\n res.statusCode = 204;\n res.end();\n };\n },\n};\n\n// Metro's transform cache key does not include process.env.TEMPO, but the\n// Tempo Babel plugin only annotates when TEMPO=true. Without this, a cache\n// built while TEMPO was unset is reused (un-annotated) even after restarting\n// with TEMPO=true. Key the cache on TEMPO so on/off use separate namespaces.\n//\n// The "metrocfg-v2" token is a manual version stamp for THIS config template.\n// Bump it whenever the resolver config changes shape (alias set, hierarchical\n// lookup, resolveRequest behavior). Metro's on-disk transform + serializer\n// cache persists across restarts and is NOT keyed on metro.config.js content,\n// so without a stamp bump a resolver change reshuffles module IDs while stale\n// cached chunks still reference the old IDs — surfacing as "Requiring unknown\n// module <n>". Bumping the stamp forces a clean rebuild.\n// The Babel annotations also embed absolute source paths and the sidecar root.\n// Metro otherwise keys transforms by relative path, allowing identical files\n// in different projects/worktrees to reuse another project's source identity.\nconfig.cacheVersion = [\n config.cacheVersion,\n "tempo-metrocfg-v15",\n projectRoot,\n \`tempo-\${process.env.TEMPO === "true" ? "on" : "off"}\`,\n]\n .filter(Boolean)\n .join("~");\n\n${o}\n`}function isTempoOwnedExpoMetroConfig(e){return!!e.startsWith(ek)||e.includes('require("expo/metro-config")')&&e.includes("singletonModules")&&e.includes("sidecarNodeModules")&&e.includes("disableHierarchicalLookup = true")}async function detectExpoStyleTooling(e){const t=await readRootPackageDeps(e);return{nativewind:Boolean(t.nativewind),svgTransformer:Boolean(t["react-native-svg-transformer"])}}async function shouldImportExpoMetroRuntime(e){const[t,n]=await Promise.all([readRootPackageDeps(e.projectRoot),readRootPackageDeps(e.tempoRoot)]);if(t["@expo/metro-runtime"]||n["@expo/metro-runtime"])return!0;for(const t of[e.tempoRoot,e.projectRoot]){const e=ab(lb.join(t,"__tempo_expo_runtime_resolve__.cjs"));try{return e.resolve("@expo/metro-runtime"),!0}catch{}}return!1}async function collectExpoWebShims(e){const t=lb.join(e.projectRoot,"web-shims");let n;try{n=await tb(t,{withFileTypes:!0})}catch{return[]}const r=[];for(const s of n){if(!s.isFile())continue;const n=/^(.+)\.(js|jsx|ts|tsx|cjs|mjs)$/.exec(s.name);if(!n)continue;const i=n[1];r.push({module:i,targetRelToTempo:`${toPosixRelativePath(e.tempoRoot,lb.join(t,s.name))}`})}return r}var tk="@tailwind base;\n@tailwind components;\n@tailwind utilities;\n",nk="// @tempo-owned: expo-tailwind-config";function buildExpoNativeWindTailwindConfig(e){const t=`./${toPosixRelativePath(e.tempoRoot,e.pagesDir)}/**/*.{js,jsx,ts,tsx}`;return`${nk}\nconst path = require("node:path");\nconst nativewindPreset = require("nativewind/preset");\n\nlet appConfig = {};\nfor (const name of ["tailwind.config.js", "tailwind.config.cjs"]) {\n try {\n appConfig = require(path.resolve(__dirname, "..", name));\n break;\n } catch (e) {\n if (!e || e.code !== "MODULE_NOT_FOUND") throw e;\n }\n}\n\nconst appContent = Array.isArray(appConfig.content) ? appConfig.content : [];\nconst rebasedAppContent = appContent\n .filter((g) => typeof g === "string")\n .map((g) => (g.startsWith("./") ? "../" + g.slice(2) : g));\n\nmodule.exports = {\n ...appConfig,\n presets: [nativewindPreset],\n content: Array.from(\n new Set([\n ...rebasedAppContent,\n "../app/**/*.{js,jsx,ts,tsx}",\n "../components/**/*.{js,jsx,ts,tsx}",\n "../src/**/*.{js,jsx,ts,tsx}",\n ${JSON.stringify(t)},\n "./App.tsx",\n ]),\n ),\n};\n`}function isTempoOwnedExpoTailwindConfig(e){return!!e.startsWith(nk)||e.includes('require("nativewind/preset")')&&e.includes("rebasedAppContent")}function isOverwriteableExpoAppTsx(e){if(/from\s+["']react-dom(?:\/[^"']*)?["']/.test(e))return!0;const t=/from\s+["']react-native["']/.test(e),n=/<(div|span|p|button|a|h1|h2|h3|input|form|section|article|ul|li)\b/.test(e);return!(!n||t)}var rk='import { tempoHostIdentity } from "tempo-sdk/nextjs";\n\nexport const dynamic = "force-dynamic";\n\nexport function GET() {\n return Response.json(tempoHostIdentity(), {\n headers: {\n "cache-control": "no-store",\n "x-tempo-host-identity": "1",\n },\n });\n}\n',sk='export const dynamic = "force-dynamic";\n\nconst headers = {\n "access-control-allow-origin": "*",\n "access-control-allow-methods": "POST, OPTIONS",\n "access-control-allow-headers": "content-type",\n "cache-control": "no-store",\n};\n\nexport function OPTIONS() {\n return new Response(null, { status: 204, headers });\n}\n\nexport function POST() {\n return new Response(null, { status: 204, headers });\n}\n',ik='import { realpathSync } from "node:fs";\n\nexport const dynamic = "force-dynamic";\n\nexport function GET() {\n let projectRoot: string;\n try {\n projectRoot = realpathSync.native(process.cwd());\n } catch {\n projectRoot = process.cwd();\n }\n return Response.json({ tempoHost: true, projectRoot });\n}\n',ok='// @tempo-owned: stylesheet-postcss-v1\nimport path from "node:path";\n// Next runs PostCSS workers with the host project as their cwd. Turbopack\n// relocates this module, so import.meta.url is not the on-disk host path.\nconst tempoStylesRoot = process.cwd();\nexport default {\n plugins: {\n [path.join(tempoStylesRoot, ".tempo-styles/host-styles.cjs")]: { base: tempoStylesRoot },\n "@tailwindcss/postcss": {},\n },\n};\n',ak='// @tempo-owned: stylesheet-postcss-v1\nimport path from "node:path";\n// Next runs PostCSS workers with the host project as their cwd. Turbopack\n// relocates this module, so import.meta.url is not the on-disk host path.\nconst tempoStylesRoot = process.cwd();\nexport default {\n plugins: {\n "postcss-import": {},\n "postcss-url": { url: "rebase" },\n [path.join(tempoStylesRoot, ".tempo-styles/host-styles.cjs")]: { base: tempoStylesRoot },\n tailwindcss: {},\n autoprefixer: {},\n },\n};\n';async function writeStylesheetFile(e,t){await readTextFileOptional3(e)!==t&&await atomicWriteText(e,t)}async function writeFileIfMissing(e,t){null===await readTextFileOptional3(e)&&await atomicWriteText(e,t)}var ck=["tailwind.config.ts","tailwind.config.js","tailwind.config.mjs","tailwind.config.cjs","src/tailwind.config.ts","src/tailwind.config.js","app/tailwind.config.ts","app/tailwind.config.js","client/tailwind.config.ts","client/tailwind.config.js"],lk=["src","app","components","pages","lib","packages","shared","ui","client/src","client/app","client/components","client/lib"],dk=["src/index.css","src/style.css","src/main.css","src/App.css","src/styles/globals.css","src/styles/global.css","src/styles/tailwind.css","styles/global.css","styles/globals.css","app/globals.css","app/global.css","app/assets/tailwind.css","client/src/index.css","src/app/globals.css","src/app/global.css"];async function pathIsFile(e){try{return(await sb(e)).isFile()}catch{return!1}}function isInsidePath(e,t){const n=lb.relative(e,t);return""===n||!n.startsWith("..")&&!lb.isAbsolute(n)}function cleanLocalSpecifier(e){const t=e.trim();return 0===t.length||/^[a-z]+:\/\//i.test(t)||t.startsWith("data:")?null:t.split(/[?#]/,1)[0]??null}function resolveDeclaredProjectPath(e,t){const n=cleanLocalSpecifier(t);return n?n.startsWith("/")?lb.resolve(e,n.slice(1)):n.startsWith("./")||n.startsWith("../")?lb.resolve(e,n):n.startsWith("@/")?lb.resolve(e,"src",n.slice(2)):n.startsWith("~/")?lb.resolve(e,n.slice(2)):/^(?:src|app|styles|components|packages|lib|pages)\//.test(n)?lb.resolve(e,n):null:null}function resolveImportCandidates(e,t,n){const r=cleanLocalSpecifier(n);if(!r)return[];if(r.startsWith("./")||r.startsWith("../"))return[lb.resolve(lb.dirname(t),r)];if(r.startsWith("/"))return[lb.resolve(e,r.slice(1))];if(r.startsWith("@/")){const t=lb.resolve(e,r.slice(2)),n=lb.resolve(e,"src",r.slice(2));return[n,t]}return r.startsWith("~/")?[lb.resolve(e,r.slice(2))]:[]}function extractCssImportSpecifiers(e){const t=[],n=/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:[?#][^"']*)?)["']/g;for(const r of e.matchAll(n)){const e=r[1];e&&!e.includes(".module.css")&&t.push(e)}return t}function extractHtmlStylesheetHrefs(e){const t=[],n=/<link\b(?=[^>]*\brel=["']?stylesheet["']?)[^>]*\bhref=["']([^"']+\.css(?:[?#][^"']*)?)["'][^>]*>/gi;for(const r of e.matchAll(n))r[1]&&t.push(r[1]);return t}function toUniqueArray(e){return Array.from(new Set(e))}function getNestedString(e,t){let n=e;for(const e of t){if(!n||"object"!=typeof n||Array.isArray(n))return null;n=n[e]}return"string"==typeof n&&n.trim().length>0?n:null}function readPackageDependencyVersions(e){const t={...toStringRecord(e?.dependencies),...toStringRecord(e?.devDependencies),...toStringRecord(e?.peerDependencies)};return{autoprefixer:t.autoprefixer??null,postcss:t.postcss??null,tailwindcss:t.tailwindcss??null,tailwindcssPostcss:t["@tailwindcss/postcss"]??null,tailwindcssVite:t["@tailwindcss/vite"]??null}}function firstCompatibleVersion(e,t){for(const n of e)if(n&&parsePackageMajorVersion(n)===t)return n;return null}function mergePackageDependencyVersions(e,t){return{autoprefixer:e.autoprefixer??t.autoprefixer,postcss:e.postcss??t.postcss,tailwindcss:e.tailwindcss??t.tailwindcss,tailwindcssPostcss:e.tailwindcssPostcss??t.tailwindcssPostcss,tailwindcssVite:e.tailwindcssVite??t.tailwindcssVite}}function parsePackageMajorVersion(e){const t=e.match(/npm:[^@]+@(.+)$/),n=t?.[1]??e,r=n.match(/\d+/);return r?.[0]?Number.parseInt(r[0],10):null}var uk=vb;function applyManagedTempoSdkSpec(e,t,n){const r=toStringRecord(n.dependencies),s=toStringRecord(n.devDependencies);void 0!==r["tempo-sdk"]?(e["tempo-sdk"]=r["tempo-sdk"],delete t["tempo-sdk"]):t["tempo-sdk"]=s["tempo-sdk"]??uk}function cssUsesTailwindV3Directives(e){return/@tailwind\s+(?:base|components|utilities)\b/.test(e)}function cssUsesTailwindV4Directives(e){return/@import\s+["']tailwindcss(?:\/[^"']*)?["']/.test(e)||/@(?:theme|source|utility|variant|custom-variant)\b/.test(e)}function inferTailwindMajorVersion(e){const t=e.projectPackageVersions.tailwindcss?parsePackageMajorVersion(e.projectPackageVersions.tailwindcss):null;if(3===t)return 3;if(null!==t&&t>=4)return 4;const n=null!==firstCompatibleVersion([e.projectPackageVersions.tailwindcssVite,e.projectPackageVersions.tailwindcssPostcss],4);if(n)return 4;const r=e.tempoPackageVersions.tailwindcss?parsePackageMajorVersion(e.tempoPackageVersions.tailwindcss):null;return 3===r?3:null!==r&&r>=4?4:e.cssSources.some(cssUsesTailwindV3Directives)?3:(e.cssSources.some(cssUsesTailwindV4Directives),4)}async function addExistingUserFile(e,t,n){if(!n)return;const r=lb.resolve(n);isInsidePath(t.projectRoot,r)&&(isInsidePath(t.tempoRoot,r)||await pathIsFile(r)&&e.add(r))}async function addExistingUserDirectory(e,t,n){const r=lb.resolve(n);isInsidePath(t.projectRoot,r)&&(isInsidePath(t.tempoRoot,r)||await pathIsDirectory(r)&&e.add(r))}async function addCssImportsFromSourceFile(e,t,n){const r=await readTextFileOptional3(n);if(null===r)return null;for(const s of extractCssImportSpecifiers(r))for(const r of resolveImportCandidates(t.projectRoot,n,s))await addExistingUserFile(e,t,r);return r}async function addCssLinksFromHtmlFile(e,t,n){const r=await readTextFileOptional3(n);if(null!==r)for(const n of extractHtmlStylesheetHrefs(r))await addExistingUserFile(e,t,resolveDeclaredProjectPath(t.projectRoot,n))}async function collectNextLayoutFiles(e){const t=["app/layout.tsx","app/layout.jsx","app/layout.ts","app/layout.js","src/app/layout.tsx","src/app/layout.jsx","src/app/layout.ts","src/app/layout.js"].map(t=>lb.join(e,t)),n=new Set;for(const e of t)await pathIsFile(e)&&n.add(e);for(const t of[lb.join(e,"app"),lb.join(e,"src","app")])await collectNamedFiles(t,/^layout\.(?:tsx|jsx|ts|js)$/,3,n);return Array.from(n)}async function collectNamedFiles(e,t,n,r){if(n<0||!await pathIsDirectory(e))return;let s;try{s=await tb(e,{withFileTypes:!0})}catch{return}for(const i of s){const s=lb.join(e,i.name);i.isFile()&&t.test(i.name)?r.add(s):i.isDirectory()&&!i.name.startsWith(".")&&"node_modules"!==i.name&&".next"!==i.name&&await collectNamedFiles(s,t,n-1,r)}}async function discoverProjectStyleContext(e,t){const n=new Set,r=new Set,s=readPackageDependencyVersions(await readJsonObjectOptional(lb.join(e.projectRoot,"package.json")));if((await readRootPackageDeps(e.projectRoot)).astro){const t=new Set;await collectNamedFiles(lb.join(e.projectRoot,"src","layouts"),/\.astro$/,5,t),await collectNamedFiles(lb.join(e.projectRoot,"src","pages"),/\.astro$/,5,t);for(const r of t)await addCssImportsFromSourceFile(n,e,r)}const i=readPackageDependencyVersions(await readJsonObjectOptional(e.packageJsonPath)),o=await readJsonObjectOptional(lb.join(e.projectRoot,"components.json")),a=getNestedString(o,["tailwind","css"]),c=getNestedString(o,["tailwind","config"]);if(await addExistingUserFile(n,e,a?resolveDeclaredProjectPath(e.projectRoot,a):null),c){const t=resolveDeclaredProjectPath(e.projectRoot,c);t&&r.add(t)}if("nextjs"===t){for(const t of await collectNextLayoutFiles(e.projectRoot))await addCssImportsFromSourceFile(n,e,t);for(const t of["pages/_app.tsx","pages/_app.jsx","pages/_app.ts","pages/_app.js","src/pages/_app.tsx","src/pages/_app.jsx","src/pages/_app.ts","src/pages/_app.js"])await addCssImportsFromSourceFile(n,e,lb.join(e.projectRoot,t))}else if("nuxt"===t)for(const t of await collectNuxtCssEntries(e.projectRoot))await addExistingUserFile(n,e,t);else{for(const t of["src/main.tsx","src/main.jsx","src/main.ts","src/main.js","src/index.tsx","src/index.jsx","src/index.ts","src/index.js","main.tsx","main.jsx","client/src/main.tsx","client/src/main.jsx","client/src/main.ts","client/src/main.js","client/src/index.tsx","client/src/index.jsx"])await addCssImportsFromSourceFile(n,e,lb.join(e.projectRoot,t));await addCssLinksFromHtmlFile(n,e,lb.join(e.projectRoot,"index.html")),await addCssLinksFromHtmlFile(n,e,lb.join(e.projectRoot,"client","index.html"))}for(const t of dk)await addExistingUserFile(n,e,lb.join(e.projectRoot,t));for(const t of ck)r.add(lb.join(e.projectRoot,t));const l=new Set;for(const t of lk)await addExistingUserDirectory(l,e,lb.join(e.projectRoot,t));l.add(e.pagesDir);const d="nextjs"===t?await discoverNextFontSetup(e,await collectNextLayoutFiles(e.projectRoot)):null;let u=null;for(const e of r)if(await pathIsFile(e)){u=e;break}const p=(await Promise.all(Array.from(n).map(async e=>await readTextFileOptional3(e)))).filter(e=>null!==e),m=inferTailwindMajorVersion({cssSources:p,projectPackageVersions:s,tempoPackageVersions:i});return{cssFiles:toUniqueArray(n),cssFilesHaveTailwindDirectives:p.some(e=>3===m?cssUsesTailwindV3Directives(e):cssUsesTailwindV4Directives(e)),packageVersions:mergePackageDependencyVersions(s,i),tailwindConfigPath:u,tailwindMajor:m,sourceDirs:toUniqueArray(l),nextFontSetup:d}}async function discoverNextFontSetup(e,t){for(const n of t){const t=await readTextFileOptional3(n);if(null===t)continue;const r=extractNextFontSetup(t,n,lb.join(e.tempoRoot,"app","layout.tsx"));if(r)return r}return null}function extractNextFontSetup(e,t,n){const r=extractJsxAttributeExpression(e,"html","className"),s=extractJsxAttributeExpression(e,"body","className"),i=[r,s].filter(e=>Boolean(e)),o=new Set;for(const e of i){if(/\b(?:cn|clsx|classNames)\s*\(/.test(e))continue;const t=/\b([A-Za-z_$][\w$]*)\.(?:className|variable)\b/g;for(const n of e.matchAll(t))n[1]&&o.add(n[1])}if(0===o.size)return null;const a=extractNextFontImports(e);if(0===a.length)return null;const c=[];for(const r of o){const s=extractConstDeclaration(e,r);if(!s)return null;c.push(rewriteLocalFontPaths(s,lb.dirname(t),lb.dirname(n)))}return{imports:a,declarations:c,htmlClassName:r,bodyClassName:s}}function extractNextFontImports(e){const t=new Set,n=/^import\s+[\s\S]*?\s+from\s+["']next\/font\/(?:google|local)["'];?/gm;for(const r of e.matchAll(n))t.add(ensureTrailingSemicolon(r[0].trim()));return Array.from(t)}function ensureTrailingSemicolon(e){return e.endsWith(";")?e:`${e};`}function extractConstDeclaration(e,t){const n=new RegExp(`\\bconst\\s+${escapeRegExp2(t)}\\s*=`).exec(e);if(!n||void 0===n.index)return null;const r=n.index,s=findStatementEnd(e,r);return-1===s?null:ensureTrailingSemicolon(e.slice(r,s+1).trim())}function findStatementEnd(e,t){let n=null,r=!1,s=0,i=0,o=0;for(let a=t;a<e.length;a+=1){const t=e[a];if(n)r?r=!1:"\\"===t?r=!0:t===n&&(n=null);else if("'"!==t&&'"'!==t&&"`"!==t){if("{"===t)s+=1;else if("}"===t)s=Math.max(0,s-1);else if("("===t)i+=1;else if(")"===t)i=Math.max(0,i-1);else if("["===t)o+=1;else if("]"===t)o=Math.max(0,o-1);else if(";"===t&&0===s&&0===i&&0===o)return a}else n=t}return-1}function rewriteLocalFontPaths(e,t,n){return e.replace(/(\b(?:src|path)\s*:\s*)(["'])(\.{1,2}\/[^"']+)\2/g,(e,r,s,i)=>{const o=lb.resolve(t,i);return`${r}${s}${toCssRelativePath(n,o)}${s}`})}function extractJsxAttributeExpression(e,t,n){const r=e.indexOf(`<${t}`);if(-1===r)return null;const s=findJsxTagEnd(e,r);if(-1===s)return null;const i=e.slice(r,s+1),o=i.indexOf(n);if(-1===o)return null;const a=i.indexOf("=",o+n.length);if(-1===a)return null;let c=a+1;for(;/\s/.test(i[c]??"");)c+=1;if("{"===i[c]){const e=findBalancedBraceEnd(i,c);return-1===e?null:i.slice(c+1,e).trim()}if('"'===i[c]||"'"===i[c]){const e=i[c],t=i.indexOf(e,c+1);return-1===t?null:JSON.stringify(i.slice(c+1,t))}return null}function findJsxTagEnd(e,t){let n=null,r=!1,s=0;for(let i=t;i<e.length;i+=1){const t=e[i];if(n)r?r=!1:"\\"===t?r=!0:t===n&&(n=null);else if("'"!==t&&'"'!==t&&"`"!==t){if("{"===t)s+=1;else if("}"===t)s=Math.max(0,s-1);else if(">"===t&&0===s)return i}else n=t}return-1}function findBalancedBraceEnd(e,t){let n=null,r=!1,s=0;for(let i=t;i<e.length;i+=1){const t=e[i];if(n)r?r=!1:"\\"===t?r=!0:t===n&&(n=null);else if("'"!==t&&'"'!==t&&"`"!==t){if("{"===t)s+=1;else if("}"===t&&(s-=1,0===s))return i}else n=t}return-1}function escapeRegExp2(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var pk="/* Legacy Tempo CSS entry - superseded by ./globals.css (imported from main.tsx). */\n",hk="/* tempo:managed:start - regenerated by Tempo; edits in this block are overwritten */",mk="/* tempo:managed:end */",fk="/* tempo:managed:start",gk="/* tempo:managed:end */";function isTailwindEngineDirectiveLine(e){const t=e.trim();return/^@import\s+["']tailwindcss["']/.test(t)||/^@tailwind\s+(?:base|components|utilities)\b/.test(t)||/^@source\b/.test(t)||/^@config\b/.test(t)}function extractUserCssOutsideTempoBlock(e,t){const n=e.indexOf(fk),r=e.indexOf(gk);if(-1!==n&&r>n){const t=e.slice(0,n),s=e.slice(r+gk.length);return`${t}\n${s}`.trim()}try{const n=Ix.parse(e),r=new Set;Ix.parse(t).walkAtRules("import",e=>{const t=e.params.match(/^["']([^"']+)["']$/);t&&r.add(t[1])});for(const e of[...n.nodes]){if("atrule"!==e.type)continue;const t="import"===e.name?e.params.match(/^["']([^"']+)["']$/):null;(t&&r.has(t[1])||isTailwindEngineDirectiveLine(e.toString()))&&e.remove()}return n.toString().trim()}catch{return e.trim()}}async function writeManagedTempoGlobalsCss(e,t,n=""){const r=await readTextFileOptional3(e),s=null===r?"":extractUserCssOutsideTempoBlock(r,`${t}\n${n}`),i=`${hk}\n${t.trim()}\n${mk}\n`,o=s.length>0?`${i}\n${s}\n`:i;o!==r&&await atomicWriteText(e,o)}async function reconcileLegacyTempoIndexCss(e){const t=lb.join(e,"index.css"),n=await readTextFileOptional3(t);if(null===n)return;const r=extractUserCssOutsideTempoBlock(n,""),s=r.length>0?`${r}\n`:pk;s!==n&&await atomicWriteText(t,s)}async function ensureNextLayoutFile(e,t,n){const r=lb.join(e.tempoRoot,"app","layout.tsx"),s=reconcileHostStyleImports(buildNextLayoutTsx(t.nextFontSetup),r,e.tempoRoot,n),i=await readTextFileOptional3(r);null===i||isTempoGeneratedNextLayout(i)?await writeStylesheetFile(r,s):await writeStylesheetFile(r,reconcileHostStyleImports(i,r,e.tempoRoot,n))}function reconcileHostStyleImports(e,t,n,r){const s=cssPath(lb.dirname(t),lb.resolve(n,r.globals)),i=[...r.roots.map(e=>cssPath(lb.dirname(t),lb.resolve(n,e.file))),s];return reconcileStylesheetImports(e,i)}async function ensureStylesheetFiles(e,t,n,r){const s=lb.join(e.tempoRoot,"nextjs"===t?"app/globals.css":"globals.css"),i=lb.join(e.tempoRoot,".tempo-styles/styles-plan.json"),o=await readJsonObjectOptional(i),a=new Set;for(const t of Array.isArray(o?.legacyRoots)?o.legacyRoots:[]){if("string"!=typeof t)continue;const r=lb.resolve(e.tempoRoot,t);t.endsWith(".css")&&isInsidePath(e.projectRoot,r)&&!isInsidePath(e.tempoRoot,r)&&await pathIsFile(r)&&(a.add(r),n.cssFiles.includes(r)||n.cssFiles.push(r))}const c=await readTextFileOptional3(s);if(c){const t=c.indexOf(fk),r=c.indexOf(gk),i=t>=0&&r>t?c.slice(t,r):t<0?c:"";let o;try{o=Ix.parse(i)}catch{}for(const t of o?.nodes??[]){if("atrule"!==t.type||"import"!==t.name)continue;const r=t.params.match(/^["'](\.{1,2}\/[^"']+\.css)["']$/);if(!r)continue;const i=lb.resolve(lb.dirname(s),r[1]);isInsidePath(e.projectRoot,i)&&!isInsidePath(e.tempoRoot,i)&&await pathIsFile(i)&&!n.cssFiles.includes(i)&&(n.cssFiles.push(i),a.add(i))}}const l=await buildStylesheetPlan({tempoRoot:e.tempoRoot,appRoot:r,globals:s,major:n.tailwindMajor,cssFiles:n.cssFiles,config:n.tailwindConfigPath,sourceDirs:n.sourceDirs});if(l.legacyRoots=[...a].map(t=>cssPath(e.tempoRoot,t)),await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/host-styles.cjs"),gT),await writeStylesheetFile(i,`${JSON.stringify(l,null,2)}\n`),3===l.major){const t=lb.join(e.tempoRoot,".tempo-styles/tailwind.editor.css");(await readTextFileOptional3(t))?.startsWith("/* @tempo-owned: Tailwind editor context;")&&await ib(t);const n=(await Promise.all(Tk.map(async t=>await pathExists4(lb.join(e.tempoRoot,t))?t:null))).find(Boolean)??"tailwind.config.ts";await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/tailwind-full.cjs"),`// @tempo-owned: full stylesheet config\nconst path = require("node:path");\nconst host = path.resolve(__dirname, "..");\n// Keep this relative require literal: Tailwind's dependency scanner follows\n// it into the host config, app config and plugins for cache invalidation.\nconst imported = require(${JSON.stringify(`../${n}`)});\nconst config = imported.default ?? imported;\nconst content = config.content ?? [];\nconst files = (Array.isArray(content) ? content : content.files ?? []).map((entry) => {\n if (typeof entry !== "string") return entry;\n const negative = entry.startsWith("!");\n return (negative ? "!" : "") + path.resolve(host, negative ? entry.slice(1) : entry).split(path.sep).join("/");\n});\nmodule.exports = { ...config, content: Array.isArray(content) ? files : { ...content, files } };\n`),await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/tailwind-partial.cjs"),'// @tempo-owned: partial stylesheet config\nconst config = require("./tailwind-full.cjs");\nmodule.exports = { ...config, corePlugins: Array.isArray(config.corePlugins) ? config.corePlugins.filter((name) => name !== "preflight") : { ...config.corePlugins, preflight: false } };\n')}else{const t=["/* @tempo-owned: Tailwind editor context; not a runtime stylesheet */",'@import "tailwindcss";',...l.roots.map(t=>`@reference ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),lb.resolve(e.tempoRoot,t.file)))};`),`@reference ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),s))};`,...l.config&&!l.roots.some(e=>e.config)?[`@config ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),lb.resolve(e.tempoRoot,l.config)))};`]:[],...l.sources.map(t=>`@source ${JSON.stringify(cssPath(lb.join(e.tempoRoot,".tempo-styles"),lb.resolve(e.tempoRoot,t)))};`)];await writeStylesheetFile(lb.join(e.tempoRoot,".tempo-styles/tailwind.editor.css"),`${t.join("\n")}\n`)}return l}function isTempoGeneratedNextLayout(e){return/export\s+default\s+function\s+RootLayout/.test(e)&&/children\s*:\s*ReactNode/.test(e)&&/<head\s*\/>/.test(e)}function buildNextLayoutTsx(e){const t=toUniqueArray(['import "./globals.css";','import type { ReactNode } from "react";',...e?.imports??[]]),n=e?.declarations.length?`${e.declarations.join("\n\n")}\n\n`:"",r=e?.htmlClassName?` className={${e.htmlClassName}}`:"",s=e?.bodyClassName?` className={${e.bodyClassName}}`:"";return`${t.join("\n")}\n\n${n}export default function RootLayout({ children }: { children: ReactNode }) {\n return (\n <html lang="en"${r}>\n <head />\n <body${s}>{children}</body>\n </html>\n );\n}\n`}function buildTempoGlobalsCss(e,t,n){if(n&&n.owner!==n.globals)return"/* Application styles are loaded at their original paths by the host entry. */\n";if(3===t.tailwindMajor){const r=[];for(const s of n?[]:t.cssFiles)r.push(`@import "${toCssRelativePath(e,s)}";`);return r.length>0&&r.push(""),!n&&t.cssFilesHaveTailwindDirectives||(r.push("@tailwind base;"),r.push("@tailwind components;"),r.push("@tailwind utilities;")),`${r.join("\n")}\n`}const r=['@import "tailwindcss";'];for(const s of n?[]:t.cssFiles)r.push(`@import "${toCssRelativePath(e,s)}";`);r.push(""),t.tailwindConfigPath&&r.push(`@config "${toCssRelativePath(e,t.tailwindConfigPath)}";`);for(const n of t.sourceDirs)r.push(`@source "${toCssRelativePath(e,n)}";`);return`${r.join("\n")}\n`}var yk=/\.(ts|js|mjs|cjs)$/;function buildTailwindV3HostConfig(e,t){const n="{ts,tsx,js,jsx,mdx,svelte,vue,astro}",r=toUniqueArray([...t.sourceDirs.map(t=>`${toCssRelativePath(e.tempoRoot,t)}/**/*.${n}`),`./app/**/*.${n}`,`./components/**/*.${n}`]),s=r.map(e=>` ${JSON.stringify(e)},`).join("\n");if(t.tailwindConfigPath){const n=toCssRelativePath(e.tempoRoot,t.tailwindConfigPath.replace(yk,"")),r=toPosixRelativePath(e.tempoRoot,lb.dirname(t.tailwindConfigPath));return`${kk}\nimport type { Config } from "tailwindcss";\nimport userConfig from "${n}";\n\n// Tempo-owned Tailwind v3 config for the canvas host. Inherits the app's theme,\n// brand tokens and plugins, then rewrites \`content\` for the host: Tailwind v3\n// resolves relative content globs against the build cwd (tempo/), so the app's\n// own globs are rebased from the app config's directory and the canvas-source\n// globs are appended.\nconst appContent = Array.isArray((userConfig as Config).content)\n ? ((userConfig as Config).content as unknown[])\n : [];\nconst rebasedAppContent = appContent\n .filter((glob): glob is string => typeof glob === "string")\n .map((glob) => {\n const negation = glob.startsWith("!") ? "!" : "";\n const body = negation ? glob.slice(1) : glob;\n if (body.startsWith("/")) return glob;\n return \`\${negation}${r}/\${body.replace(/^\\.\\//, "")}\`;\n });\n\nconst config: Config = {\n ...(userConfig as Config),\n content: [\n ...rebasedAppContent,\n${s}\n ],\n};\n\nexport default config;\n`}return`${kk}\nimport type { Config } from "tailwindcss";\n\n// Tempo-owned Tailwind v3 config for the canvas host. Content globs are\n// relative to this tempo/ directory (Tailwind v3 resolves content against the\n// build cwd, which is tempo/).\nconst config: Config = {\n content: [\n${s}\n ],\n};\n\nexport default config;\n`}async function seedHomeCanvas(e){const t=await resolveFreeformCanvasesDir(e.pagesDir);await writeFileIfMissing(lb.join(t,"home","index.canvas.tsx"),UT)}async function seedZoneDirectories(e){const t=await resolveFreeformCanvasesDir(e.pagesDir);lb.resolve(t)!==lb.resolve(e.pagesDir)&&(await eb(t,{recursive:!0}),await eb(lb.join(e.pagesDir,_g),{recursive:!0}),await eb(lb.join(e.pagesDir,xg),{recursive:!0}))}async function seedSharedControls(e){await writeFileIfMissing(lb.join(e.tempoRoot,"controls.ts"),'// Optional controls for existing components whose source should stay untouched.\n// New components always keep defineControls in their own file.\n// For existing components, honor the user/repo preference; fully integrated apps\n// prefer component files. Non-dev work can use this file; ask developers if unsure.\n// Both locations work across canvases without asset registration.\n// Import app components here, and import defineControls from "tempo-sdk/assets".\n// Example (adjust the import to your app):\n// import { defineControls } from "tempo-sdk/assets";\n// import { Button } from "../src/components/Button";\n// defineControls(Button, { disabled: { type: "boolean" } });\n// Keep one declaration per component; move existing declarations rather than copying them.\n// Tempo discovers this file automatically. Do not import it into app or canvas entry points.\nexport {};\n')}async function ensureProjectScaffold(e,t="vite"){if("expo"===t){const{aliasPaths:t}=await collectHostAliasPaths(e),n=convertAliasPathsToMetroEntries(t),r=await detectExpoStyleTooling(e.projectRoot),s=await shouldImportExpoMetroRuntime(e),i=await collectExpoWebShims(e);return await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"index.js"),buildExpoIndexJs({nativewind:r.nativewind,metroRuntime:s}),isTempoOwnedExpoIndexJs),r.nativewind&&(await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"tailwind.config.js"),buildExpoNativeWindTailwindConfig(e),isTempoOwnedExpoTailwindConfig),await writeFileIfMissing(lb.join(e.tempoRoot,"global.css"),tk)),await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"App.tsx"),QT,isOverwriteableExpoAppTsx),await writeFileIfMissing(lb.join(e.tempoRoot,"public","index.html"),buildExpoPublicIndexHtml(e)),await writeFileIfMissing(lb.join(e.tempoRoot,"app.json"),buildExpoAppJson(e)),await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"babel.config.js"),buildExpoBabelConfig({nativewind:r.nativewind}),isTempoOwnedExpoBabelConfig),await reconcileGeneratedTextFile(lb.join(e.tempoRoot,"metro.config.js"),buildExpoMetroConfig(n,{nativewind:r.nativewind,svgTransformer:r.svgTransformer,webShims:i}),isTempoOwnedExpoMetroConfig),await reconcileGeneratedTsconfig(lb.join(e.tempoRoot,"tsconfig.json"),buildExpoTsconfigFile(e,t),isTempoOwnedExpoTsconfig),await writeFileIfMissing(lb.join(e.tempoRoot,"expo-env.d.ts"),'/// <reference types="expo/types" />\n'),void await writeFileIfMissing(lb.join(e.tempoRoot,".tempo-storybook-stub.js"),JT)}const{appRoot:n}=await resolveAppRoot(e);if("nuxt"===t)return void await ensureNuxtSidecarPages(e);const r=await discoverProjectStyleContext({...e,projectRoot:n},t),s=await ensureStylesheetFiles(e,t,r,n);if("nextjs"===t){await ensureNextLayoutFile(e,r,s),await writeFileIfMissing(lb.join(e.tempoRoot,"app","page.tsx"),jT),await writeFileIfMissing(lb.join(e.tempoRoot,"app","tempo-host","page.tsx"),BT),await writeFileIfMissing(lb.join(e.tempoRoot,"app","%5F%5Ftempo","identity","route.ts"),rk),await writeFileIfMissing(lb.join(e.tempoRoot,"app","%5F%5Ftempo","canvas-host-registration","route.ts"),sk);const t=lb.join(e.tempoRoot,"app","tempo-host","identity","route.ts");return await readTextFileOptional3(t)===ik&&await ib(t),void await writeManagedTempoGlobalsCss(lb.join(e.tempoRoot,"app","globals.css"),buildTempoGlobalsCss(lb.join(e.tempoRoot,"app"),r,s),buildTempoGlobalsCss(lb.join(e.tempoRoot,"app"),r))}await writeFileIfMissing(lb.join(e.tempoRoot,"index.html"),LT),await writeFileIfMissing(lb.join(e.tempoRoot,"main.tsx"),MT);const i=lb.join(e.tempoRoot,"main.tsx"),o=await readTextFileOptional3(i);null!==o&&await writeStylesheetFile(i,reconcileHostStyleImports(o,i,e.tempoRoot,s)),await writeManagedTempoGlobalsCss(lb.join(e.tempoRoot,"globals.css"),buildTempoGlobalsCss(e.tempoRoot,r,s),buildTempoGlobalsCss(e.tempoRoot,r)),await reconcileLegacyTempoIndexCss(e.tempoRoot)}var bk=new Set(["vite","@vitejs/plugin-react"]),vk=/^vite\.config\.[cm]?[jt]s$/;async function isWorkspaceAppPackage(e){const t=await readJsonObjectOptional(lb.join(e,"package.json"));if(!t)return!1;const n=collectDependencyNames(t),r=sT.some(e=>!bk.has(e)&&n.has(e));if(r)return!0;let s;try{s=await tb(e)}catch{return!1}if(s.some(e=>vk.test(e)))return!0;const i=[...bk].some(e=>n.has(e));return i&&s.includes("index.html")}async function findAppDirToRecord(e){const t={appDir:null,warning:null};if(void 0!==e.appDir)return t;const n=await listWorkspaceMemberDirs(e.projectRoot),r=n.length>0,s=r?await isWorkspaceAppPackage(e.projectRoot):await isAppPackageDir(e.projectRoot);if(s)return t;const i=await findAppPackageSubdirs(e),o=i.length>1&&!await isAppPackageDir(e.projectRoot);if(o)return t;const a=r?[...new Set([...i,...await findWorkspaceAppMembers(e,n)])]:i;if(a.length>1)return{appDir:null,warning:multipleAppDirectoriesWarning(e,a)};const[c]=a;if(!c)return t;const l=toPosixRelativePath(e.projectRoot,c),d=e.apps[0]?.start,u=d===await nuxtAppStartFor(e.projectRoot,e.tempoRoot);return d&&!u?{appDir:null,warning:`The project's only app package is "${l}", but apps[0].start is already set, so Tempo did not record apps[0].appDir: that would change the folder the command runs from. If "${l}" is the app, set "apps[0].appDir": "${l}" in tempo/tempo.config.json.`}:{appDir:l,warning:null}}async function findWorkspaceAppMembers(e,t){const n=lb.resolve(e.tempoRoot),r=[];for(const e of t)lb.resolve(e)!==n&&await isWorkspaceAppPackage(e)&&r.push(e);return r}function assertCanvasHostRendersUiFramework(e,t){const n=resolveAppUiFramework(t);if(!canvasHostRendersUiFramework(e,n)){if("nuxt"===e){const e=void 0===t?"unset":`"${t}"`;throw new Error(`Nuxt projects host component storyboards in the Tempo Nuxt sidecar and require apps[0].uiFramework: "vue" (it is ${e}). Set it in tempo/tempo.config.json or rerun canvas_project_init.`)}throw new Error(`Tempo ${ST[n].label} component storyboards require the Vite canvas host; resolved host framework was "${e}". Use route storyboards for this app or set up a Vite canvas host.`)}}function setupWarning(e){return console.warn(`[tempo-project] ${e}`),e}async function hasCustomReactViteHost(e,t){if("vite"!==t||"react"!==resolveAppUiFramework(e.apps[0]?.uiFramework))return!1;const n=await readTextFileOptional3(e.viteConfigPath);if(null===n)return!1;const r=n.includes("tempoStylesRequire(import.meta.url)")&&n.includes(".tempo-styles/host-styles.cjs"),s=Ek.test(n)||r;return/\b(?:tempoAnnotate|tempoVitePlugin)\s*\(/.test(n)&&!s}async function ensureProjectSetupFiles(e,t="vite",n={}){const{createPackageJsonIfMissing:r=!0}=n,s=[];await ensureTempoWorkspaceNonce(e.tempoRoot);const{appRoot:i,warning:o}=await resolveAppRoot(e);o&&s.push(setupWarning(o));const a=i===e.projectRoot?e:{...e,projectRoot:i},c=resolveAppUiFramework(e.apps[0]?.uiFramework);if(assertCanvasHostRendersUiFramework(t,e.apps[0]?.uiFramework),"astro"===c&&(r&&await ensureAstroAppIntegration(i,uk),await writeFileIfMissing(lb.join(e.tempoRoot,"astro-env.d.ts"),'/// <reference types="tempo-sdk/astro/client" />\n')),!1!==n.migrateSdkDependencies)for(const t of new Set([e.projectRoot,i])){const n=lb.join(t,"package.json"),r=await migrateTempoSdkPins(n,e.tempoRoot);r.length>0&&s.push(setupWarning(`updated tempo-sdk version(s) in ${n}: ${r.join(", ")} → ${uk}`))}if("expo"===t)return await upsertPackageJson(a,"expo",null,{createIfMissing:r}),s;if("nuxt"===t){const t=await ensureNuxtAppTypesGenerated(i);t&&s.push(t),await upsertPackageJson(a,"nuxt",null,{createIfMissing:r}),await ensureNuxtTsconfigFile(e),await reconcileVueShimsFile(e,c);const n=lb.join(e.tempoRoot,WT),o=toPosixRelativePath(e.tempoRoot,i),l=toPosixRelativePath(e.tempoRoot,await resolveUserNuxtSrcDir(i,await readUserNuxtConfigSource(i)));return await writeFileIfMissing(n,buildNuxtSidecarConfigFile({extendsPath:o,srcDir:l,compatibilityDate:(new Date).toISOString().slice(0,10)})),await reconcileNuxtSidecarAppLocation(n,{extendsPath:o,srcDir:l}),await reconcileNuxtSidecarHostRole(n),await writeFileIfMissing(lb.join(e.tempoRoot,HT,WT),qT),s}const l=await discoverProjectStyleContext(a,t);if(await ensureStylesheetFiles(e,t,l,i),"nextjs"===t){await upsertPackageJson(a,"nextjs",l,{createIfMissing:r}),await ensureNextTsconfigFile(a);const t=lb.join(e.tempoRoot,"next.config.mjs");return await writeFileIfMissing(t,buildNextConfigFile(await collectAppTranspilePackages(a))),await healNextConfigTracingRoot(t),await ensureNextPostcssConfigFile(lb.join(e.tempoRoot,"postcss.config.mjs"),l),3===l.tailwindMajor&&await ensureTailwindV3HostConfigFile(a,l),s}return await upsertPackageJson(a,"vite",l,{createIfMissing:r}),await ensureViteTsconfigFile(a),3===l.tailwindMajor&&await ensureTailwindV3HostConfigFile(a,l),"svelte"===c&&await ensureSvelteHostConfigFile(e,i),await reconcileVueShimsFile(e,c),await ensureViteConfigFile(e,l,c,i),s}var wk="// @tempo-owned: vue-shims",_k=`${wk}\ndeclare module "*.vue" {\n import type { DefineComponent } from "vue";\n const component: DefineComponent<{}, {}, any>;\n export default component;\n}\n`;async function reconcileVueShimsFile(e,t){const n=lb.join(e.tempoRoot,"vue-shims.d.ts");if("vue"===t)return void await reconcileGeneratedTextFile(n,_k,e=>e.startsWith(wk));const r=await readTextFileOptional3(n);r?.startsWith(wk)&&await ib(n)}var xk=["svelte.config.js","svelte.config.mjs","svelte.config.ts","svelte.config.mts"];async function findSvelteConfigFile(e){for(const t of xk){const n=lb.join(e,t);if(await pathExists4(n))return n}return null}function importSpecifier(e,t){const n=toPosixRelativePath(e,t);return n.startsWith(".")?n:`./${n}`}async function ensureSvelteHostConfigFile(e,t){const n=await findSvelteConfigFile(t),r=n?`import configuredApp from ${JSON.stringify(importSpecifier(e.tempoRoot,n))};\n`:"const configuredApp = {};\n",s=`// @tempo-owned: svelte-host-config\n${r}import { tempoSveltePreprocess } from "tempo-sdk/svelte";\n\nconst { kit: _svelteKitOnly, ...appConfig } = configuredApp;\nvoid _svelteKitOnly;\nconst appPreprocess = appConfig.preprocess == null\n ? []\n : Array.isArray(appConfig.preprocess)\n ? appConfig.preprocess\n : [appConfig.preprocess];\n\nexport default {\n ...appConfig,\n preprocess: [\n tempoSveltePreprocess({ root: ${JSON.stringify(e.tempoRoot)}, sourceRoot: ${JSON.stringify(e.projectRoot)}, enabled: true }),\n ...appPreprocess,\n ],\n};\n`;await atomicWriteText(lb.join(e.tempoRoot,"svelte.config.mjs"),s)}var Tk=["tailwind.config.ts","tailwind.config.js","tailwind.config.mjs","tailwind.config.cjs"],kk="// @tempo-owned: tailwind-v3-host-config";function isTempoOwnedTailwindV3HostConfig(e){return!!e.startsWith(kk)||e.includes("Tempo-owned Tailwind v3 config for the canvas host")}async function ensureTailwindV3HostConfigFile(e,t){const n=lb.join(e.tempoRoot,"tailwind.config.ts"),r=buildTailwindV3HostConfig(e,t);for(const t of Tk){const s=lb.join(e.tempoRoot,t),i=await readTextFileOptional3(s);if(null!==i)return s===n&&isTempoOwnedTailwindV3HostConfig(i)?void(i!==r&&await atomicWriteText(n,r)):void 0}await atomicWriteText(n,r)}async function ensureNextPostcssConfigFile(e,t){const n=3===t.tailwindMajor?ak:ok,r=await readTextFileOptional3(e);await writeStylesheetFile(e,null===r?n:migrateNextStylesheetConfig(r,t.tailwindMajor))}async function ensureViteConfigFile(e,t,n,r){let s=await readTextFileOptional3(e.viteConfigPath);if(null===s)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));if(shouldRegenerateViteConfig(s,t,n))return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));if(s.includes("tempoVitePlugin")){const n=migrateViteStylesheetConfig(s,t.tailwindMajor);await writeStylesheetFile(e.viteConfigPath,n),s=n}const i=addSourceIdentityRootToViteConfig(s,e);if(null===i)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));const o=addHostRuntimeDedupeToViteConfig(i,n);if(null===o)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));const a=addCanvasDepScanToViteConfig(o);if(null===a)return void await atomicWriteText(e.viteConfigPath,buildViteConfigFile(e,t,n,r));const c=retargetVueAppRootInViteConfig(a,toPosixRelativePath(e.tempoRoot,r));c!==s&&await atomicWriteText(e.viteConfigPath,c)}function vueAppRootExpression(e){return`path.resolve(tempoRoot, ${JSON.stringify(e)})`}var Sk=/(tempoVueAppPlugins\(\{[^)]*?appRoot: )path\.resolve\(tempoRoot, "[^"]*"\)/;function retargetVueAppRootInViteConfig(e,t){return e.replace(Sk,(e,n)=>`${n}${vueAppRootExpression(t)}`)}var Ek=/^\/\/ @tempo-ui-framework: [\w-]+/m;function shouldRegenerateViteConfig(e,t,n){const r=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(r){const t=e.match(Ek)?.[0]??null,r=ST[n].marker;if(t!==r)return!0}return 3===t.tailwindMajor?!!e.includes("@tailwindcss/vite")||!!r&&(e.includes("tailwindcss({ config:")||e.includes('from "../tailwind.config')||e.includes("from '../tailwind.config")):!!r&&(e.includes('from "tailwindcss"')||e.includes("from 'tailwindcss'"))}function addSourceIdentityRootToViteConfig(e,t){const n=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(!n||e.includes("sourceIdentityRoot"))return e;let r=e;if(!/\b(?:const|let|var)\s+projectRoot\b/.test(r)){if(!/\bpath\.resolve\b/.test(r)&&!/\bimport\s+path\b/.test(r))return null;const e=r.match(/(const\s+tempoRoot\s*=\s*path\.dirname\([^;]+;)/);if(!e)return null;const n=toRelativeAllowPath(t);r=r.replace(e[1],`${e[1]}\nconst projectRoot = path.resolve(tempoRoot, ${JSON.stringify(n)});`)}const s=/tempoVitePlugin\s*\(\s*\)/;if(s.test(r))return r.replace(s,"tempoVitePlugin({ sourceIdentityRoot: projectRoot })");const i=/tempoVitePlugin\s*\(\s*\{/;return i.test(r)?r.replace(i,"tempoVitePlugin({ sourceIdentityRoot: projectRoot,"):null}var Ak=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","tempo-sdk"];function hostRuntimeDedupeTargets(e){return[...Ak,...ST[e].dedupe]}function hostRuntimeDedupeLiteral(e){return`[${hostRuntimeDedupeTargets(e).map(e=>`"${e}"`).join(", ")}]`}var Ck=["react","react-dom","react-dom/client","react/jsx-runtime","react/jsx-dev-runtime"];function addHostRuntimeDedupeToViteConfig(e,t){const n=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(!n)return e;const r=e.match(/dedupe\s*:\s*\[([^\]]*)\]/);if(r){const n=r[1],s=n.replace(/"[^"]*"|'[^']*'/g,"");if(/[^\s,]/.test(s))return null;const i=new Set([...n.matchAll(/"([^"]*)"|'([^']*)'/g)].map(e=>e[1]??e[2])),o=hostRuntimeDedupeTargets(t).filter(e=>!i.has(e));if(0===o.length)return e;const a=n.trimEnd(),c=a.trim().length>0?", ":"",l=`${a}${c}${o.map(e=>`"${e}"`).join(", ")}${n.slice(a.length)}`;return e.replace(r[0],`dedupe: [${l}]`)}if(/\bdedupe\s*:/.test(e))return null;const s=hostRuntimeDedupeLiteral(t),i=e.match(/(\n([ \t]*)resolve:[ \t]*\{[ \t]*\n)/);if(i){const t=`${i[2]} `;return e.replace(i[1],`${i[1]}${t}dedupe: ${s},\n`)}if(/\bresolve[ \t]*:/.test(e))return null;const o=e.match(/(\n([ \t]*)root:[ \t]*tempoRoot,[ \t]*\n)/);if(o){const t=o[2],n=`${t}resolve: {\n${t} dedupe: ${s},\n${t}},\n`;return e.replace(o[1],`${o[1]}${n}`)}return null}function addCanvasDepScanToViteConfig(e){const t=e.includes("tempoVitePlugin")||e.includes("tempo-sdk");if(!t)return e;if(e.includes("entries"))return e;const n='["index.html"]',r=`[${Ck.map(e=>`"${e}"`).join(", ")}]`,s=e.match(/(\n([ \t]*)optimizeDeps:[ \t]*\{[ \t]*\n)/);if(s){const t=`${s[2]} `;return e.replace(s[1],`${s[1]}${t}entries: ${n},\n${t}include: ${r},\n`)}if(/\boptimizeDeps[ \t]*:/.test(e))return null;const i=e.match(/(\n([ \t]*)root:[ \t]*tempoRoot,[ \t]*\n)/);if(i){const t=i[2],s=`${t}optimizeDeps: {\n${t} entries: ${n},\n${t} include: ${r},\n${t}},\n`;return e.replace(i[1],`${i[1]}${s}`)}return null}async function detectProjectFramework(e){const t=await readRootPackageDeps(e.projectRoot);if(t.expo)return"expo";if(t.next)return"nextjs";if(t.nuxt)return"nuxt";if(t.astro)return"vite";if(await anyFileExists2(e.projectRoot,["next.config.js","next.config.mjs","next.config.ts","next.config.cjs"]))return"nextjs";if(await anyFileExists2(e.projectRoot,zT))return"nuxt";if(await anyFileExists2(e.projectRoot,["app.config.js","app.config.ts","app.json","expo-env.d.ts"]))return"expo";if(await appRootUsesNuxt(e))return"nuxt";if(t.vite)return"vite";if(await anyFileExists2(e.projectRoot,["vite.config.js","vite.config.ts","vite.config.mjs","vite.config.cjs"]))return"vite";if(await anyFileExists2(e.tempoRoot,["next.config.js","next.config.mjs","next.config.ts","next.config.cjs"]))return"nextjs";if(await hasNuxtSidecarConfig(e.tempoRoot))return"nuxt";const n=await readRootPackageDeps(e.tempoRoot);return n.next?"nextjs":n.expo||await anyFileExists2(e.tempoRoot,["app.config.js","app.config.ts","app.json","expo-env.d.ts"])?"expo":"vite"}async function readRootPackageDeps(e){const t=lb.join(e,"package.json"),n=await readTextFileOptional3(t);if(!n)return{};let r;try{r=parsePackageJson(t,n)}catch{return{}}return{...toStringRecord(r.dependencies),...toStringRecord(r.devDependencies)}}async function anyFileExists2(e,t){for(const n of t)if(await pathExists4(lb.join(e,n)))return!0;return!1}async function detectScaffoldFramework(e){return await anyFileExists2(e.tempoRoot,["metro.config.js","expo-env.d.ts"])?"expo":await anyFileExists2(e.tempoRoot,["next.config.js","next.config.mjs","next.config.ts","next.config.cjs"])?"nextjs":await hasNuxtSidecarConfig(e.tempoRoot)?"nuxt":await anyFileExists2(e.tempoRoot,["vite.config.js","vite.config.ts","vite.config.mjs","vite.config.cjs"])?"vite":null}var Ik={vite:["vite.config.js","vite.config.ts","vite.config.mjs","vite.config.cjs","main.tsx","index.html"],nextjs:["next.config.js","next.config.mjs","next.config.ts","next.config.cjs","next-env.d.ts","postcss.config.mjs","postcss.config.cjs","postcss.config.js"],expo:["app.json","metro.config.js","babel.config.js","expo-env.d.ts","index.js"],nuxt:[...zT,".nuxt","tsconfig.json",HT,...VT.map(e=>`${GT}/${e}`)]},Pk=["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock"];async function healFrameworkMismatch(e,t,n={}){const r=await detectScaffoldFramework(e);if(null===r||r===t)return{healed:!1,previousFramework:r,backupPath:null};const s=n.now??Date.now(),i=`.tempo-backup-${r}-${s}`,o=lb.join(e.tempoRoot,i),a=[...Ik[r],...Pk,".tempo-styles"];let c=!1;for(const t of a){const n=lb.join(e.tempoRoot,t);if(!await pathExists4(n))continue;const r=lb.join(o,t);await eb(lb.dirname(r),{recursive:!0}),await rb(n,r),c=!0}return c?(await rewriteTempoConfigForFramework(e.tempoConfigPath,t,e.projectRoot),{healed:!0,previousFramework:r,backupPath:o}):{healed:!1,previousFramework:r,backupPath:null}}async function rescueWronglyBackedUpFiles(e){const t=[];let n,r=0;try{n=await tb(e.tempoRoot,{withFileTypes:!0})}catch{return{restored:t,backupsScanned:r}}for(const s of n){if(!s.isDirectory())continue;const n=/^\.tempo-backup-(vite|nextjs|expo|nuxt)-\d+$/.exec(s.name);if(!n)continue;r+=1;const i=n[1],o=new Set([...Ik[i].map(e=>e.split("/")[0]),...Pk,"App.tsx","tsconfig.json","globals.css"]),a=lb.join(e.tempoRoot,s.name);let c;try{c=await tb(a,{withFileTypes:!0})}catch{continue}for(const n of c){if(o.has(n.name))continue;const r=lb.join(e.tempoRoot,n.name);if(!await pathExists4(r))try{await rb(lb.join(a,n.name),r),t.push(n.name)}catch{}}}return{restored:t,backupsScanned:r}}async function rewriteTempoConfigForFramework(e,t,n){const r=await readTextFileOptional3(e);if(null===r)return;let s;try{s=JSON.parse(r)}catch{return}if(!s||"object"!=typeof s||Array.isArray(s))return;const i=s.scripts,o=i&&"object"==typeof i&&!Array.isArray(i)?{...i}:{};o.start="expo"===t?"npx expo start --web":"npm run dev";const a=await detectRootPackageManager(n);o.install=buildInstallScript(a?.installCmd??null),s.scripts=o,await ob(e,`${JSON.stringify(s,null,2)}\n`,"utf-8")}async function reconcileExpoStartScriptOnDisk(e,t){return await reconcileExpoStartScript(e,t)}async function reconcileExpoStartScript(e,t){if("expo"!==t)return!1;const n=await readTextFileOptional3(e);if(null===n)return!1;let r;try{r=JSON.parse(n)}catch{return!1}if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r.scripts;if(!s||"object"!=typeof s||Array.isArray(s))return!1;const i=s,o="string"==typeof i.start?i.start:"",a="npx expo start --web";return o!==a&&(!(!/\bexpo\s+start\b/.test(o)||!o.includes("--web"))&&(i.start=a,r.scripts=i,await ob(e,`${JSON.stringify(r,null,2)}\n`,"utf-8"),!0))}async function upsertPackageJson(e,t,n,r){const s=await readTextFileOptional3(e.packageJsonPath);if(null===s&&!r.createIfMissing)return;let i;if("expo"===t){const t=await readUserExpoVersions(e.projectRoot);i=n=>buildExpoTempoOwnedPackage(n,e,t)}else if("nextjs"===t){if(!n)throw new Error(`Missing style context for ${t} project setup`);i=t=>buildNextTempoOwnedPackage(t,e,n)}else if("nuxt"===t){const t=await readUserNuxtVersions(e.projectRoot),n=await readUserReactVersions(e),{links:r}=await appPackageLinks(e.projectRoot,e.tempoRoot,Bk);i=s=>buildNuxtTempoOwnedPackage(s,e,t,n,r)}else{if(!n)throw new Error(`Missing style context for ${t} project setup`);const r=await readUserReactVersions(e),s=resolveAppUiFramework(e.apps[0]?.uiFramework),o=ST[s].packages,a=o?await readUserFrameworkVersions(e,o):{},c="vue"===s?await appPackageLinks((await resolveAppRoot(e)).appRoot,e.tempoRoot,["vue"]):null;i=t=>buildTempoOwnedPackage(t,e,n,r,a,s,c)}await writeManagedDependencyManifest(e.tempoRoot,e.packageJsonPath,e=>null!==e||r.createIfMissing?i(e):null)}function pickDependencyVersion(e,t,n,r){const s=e.packageVersions[t];return s?void 0!==r&&parsePackageMajorVersion(s)!==r?n:s:n}function applyTailwindDevDependencyMode(e,t,n){if(3===t.tailwindMajor)return delete e["@tailwindcss/vite"],delete e["@tailwindcss/postcss"],e.tailwindcss=pickDependencyVersion(t,"tailwindcss",vT.tailwindcss,3),e.postcss=pickDependencyVersion(t,"postcss",vT.postcss),void(e.autoprefixer=pickDependencyVersion(t,"autoprefixer",vT.autoprefixer));e.tailwindcss=pickDependencyVersion(t,"tailwindcss",bT.tailwindcss,4),"nextjs"===n?(delete e["@tailwindcss/vite"],e["@tailwindcss/postcss"]=pickDependencyVersion(t,"tailwindcssPostcss",AT["@tailwindcss/postcss"],4)):e["@tailwindcss/vite"]=pickDependencyVersion(t,"tailwindcssVite",bT["@tailwindcss/vite"],4)}function withUserReactMajorAdopted(e,t){const n=t.react??t["react-dom"],r=n?parsePackageMajorVersion(n):null,s=parsePackageMajorVersion(e.react??"");return null===r||null===s||r<=s?{...e}:{...e,react:`^${r}.0.0`,"react-dom":`^${r}.0.0`}}function buildTempoOwnedPackage(e,t,n,r={},s={},i="react",o=null){const a=e?parsePackageJson(t.packageJsonPath,e):{},c=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),l=toStringRecord(a.devDependencies),d=toStringRecord(a.dependencies),u=ST[i].packages,p=u?fillFrameworkVitePluginPair(u,l,s):{},m=u?fillFrameworkRuntime(u,d,s):{};if(o){Object.assign(m,o.links);for(const e of o.reachedByWalkingUp)delete m[e],delete d[e]}const f=sortObjectKeys({...3===n.tailwindMajor?vT:bT,...l,...p});applyTailwindDevDependencyMode(f,n,"vite"),applyManagedTempoSdkSpec(d,f,a);const g=withUserReactMajorAdopted(wT,r),y=g.react===wT.react?{}:{react:g.react,"react-dom":g["react-dom"]},b={...a,name:"string"==typeof a.name&&a.name.trim().length>0?a.name:c,private:"boolean"!=typeof a.private||a.private,type:"string"==typeof a.type&&a.type.trim().length>0?a.type:"module",scripts:sortObjectKeys({...ET,...toStringRecord(a.scripts)}),dependencies:sortObjectKeys({...wT,...d,...m,...y}),devDependencies:f};return`${JSON.stringify(b,null,2)}\n`}function fillFrameworkVitePluginPair(e,t,n){const r=Object.keys(e.devDependencies),s=[...r,"vite"],pairFrom=e=>s.every(t=>e[t])?Object.fromEntries(s.map(t=>[t,e[t]])):null,i=pairFrom(withoutWorkspaceProtocolSpecs(t)),o=pairFrom(n),a=null!==o&&r.every(e=>t[e]===o[e]);return i&&!a?i:o??i??{...e.devDependencies,vite:bT.vite}}function fillFrameworkRuntime(e,t,n){const r=withoutWorkspaceProtocolSpecs(t);return Object.fromEntries(Object.entries(e.dependencies).map(([t,s])=>{const i=e.runtimeFollowsApp?n[t]??r[t]??s:r[t]??n[t]??s;return[t,i]}))}function isCompatibleManagedSpec(e,t){if("string"!=typeof e||0===e.trim().length)return!1;const n=parsePackageMajorVersion(t);if(null===n)return!1;const r=[...e.matchAll(/(?:^|[\s~^><=|-])(\d+)/g)].map(e=>Number.parseInt(e[1],10));return 0!==r.length&&r.every(e=>e===n)}function withCompatibleVersionsPreserved(e,t){const n={...e};for(const r of Object.keys(e))isCompatibleManagedSpec(t[r],e[r])&&(n[r]=t[r]);return n}function buildNextTempoOwnedPackage(e,t,n){const r=e?parsePackageJson(t.packageJsonPath,e):{},s=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),i=toStringRecord(r.scripts),o=toStringRecord(r.dependencies),a=toStringRecord(r.devDependencies);void 0!==o.vite||void 0!==a.vite||i.dev;i.dev===ET.dev&&delete i.dev,i.build===ET.build&&delete i.build,i.preview===ET.preview&&delete i.preview;for(const e of DT)delete o[e],delete a[e];const c=sortObjectKeys({...a,...3===n.tailwindMajor?CT:AT});applyTailwindDevDependencyMode(c,n,"nextjs"),applyManagedTempoSdkSpec(o,c,r);const l={...r,name:"string"==typeof r.name&&r.name.trim().length>0?r.name:s,private:"boolean"!=typeof r.private||r.private,type:"string"==typeof r.type&&r.type.trim().length>0?r.type:"module",scripts:sortObjectKeys({...i,...PT}),dependencies:sortObjectKeys({...o,...withCompatibleVersionsPreserved(IT,o)}),devDependencies:c};return`${JSON.stringify(l,null,2)}\n`}async function readUserExpoVersions(e){const t=lb.join(e,"package.json"),n=await readTextFileOptional3(t);if(!n)return{};let r;try{r=parsePackageJson(t,n)}catch{return{}}const s={...toStringRecord(r.dependencies),...toStringRecord(r.devDependencies)},i={};for(const e of Object.keys(NT))s[e]&&(i[e]=s[e]);return i}async function readUserReactVersions(e){const{appRoot:t}=await resolveAppRoot(e),n=await readAppDependencySpecs(t,["react","react-dom"]);return n?.specs??{}}async function readUserFrameworkVersions(e,t){const{appRoot:n}=await resolveAppRoot(e),r=await readAppDependencySpecs(n,[...Object.keys(t.dependencies),...Object.keys(t.devDependencies),"vite"]);if(!r)return{};const s=t.appSignals.some(e=>r.declared.has(e));return s?r.specs:{}}async function readAppDependencySpecs(e,t){const n=lb.join(e,"package.json"),r=await readTextFileOptional3(n);if(!r)return null;let s;try{s=parsePackageJson(n,r)}catch{return null}const i={...toStringRecord(s.dependencies),...toStringRecord(s.devDependencies)},o={};for(const n of t){const t=i[n];if(!t)continue;if(!specIsBoundToItsPackage(t)){o[n]=t;continue}const r=await findInstalledPackage(e,n);r?.version&&(o[n]=r.version)}return{declared:new Set(Object.keys(i)),specs:o}}function specIsBoundToItsPackage(e){const t=e.trim();return!!/^(catalog|workspace|link|file|portal|patch):/.test(t)||(t.startsWith(".")||t.startsWith("/"))}function withoutWorkspaceProtocolSpecs(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>!/^(catalog|workspace):/.test(e.trim())))}function buildExpoTempoOwnedPackage(e,t,n={}){const r=e?parsePackageJson(t.packageJsonPath,e):{},s=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),i=toStringRecord(r.scripts),o=toStringRecord(r.dependencies),a=toStringRecord(r.devDependencies),c=void 0!==o.vite||void 0!==a.vite||"vite"===i.dev;for(const e of DT)delete o[e],delete a[e];for(const e of OT)delete o[e],delete a[e];delete o.next,delete a.next,delete a["@tailwindcss/postcss"];for(const e of Object.keys(NT))delete o[e];const l={...NT,...n},d=sortObjectKeys({...RT,...a});applyManagedTempoSdkSpec(o,d,r);const u={...r,name:"string"==typeof r.name&&r.name.trim().length>0?r.name:s,private:"boolean"!=typeof r.private||r.private,main:"string"==typeof r.main&&r.main.trim().length>0&&"expo-router/entry"!==r.main?r.main:"index.js",scripts:sortObjectKeys({...FT,...i}),dependencies:sortObjectKeys({...l,...o}),devDependencies:d};return"string"==typeof r.type&&r.type.trim().length>0&&(!c||"module"!==r.type)&&(u.type=r.type),`${JSON.stringify(u,null,2)}\n`}var Dk={target:"ES2022",module:"ESNext",moduleResolution:"Bundler",jsx:"react-jsx",strictNullChecks:!0,noEmit:!0},Rk=new Set(["strictNullChecks"]),Nk=["./**/*.ts","./**/*.tsx"];function buildViteTsconfigFile(e){const t=Object.keys(e).length>0;return`${JSON.stringify({compilerOptions:{...Dk,...t?{baseUrl:".",paths:e}:{}},include:Nk},null,2)}\n`}function parseJsonc(e){let t="",n=!1,r=!1,s=!1;for(let i=0;i<e.length;i++){const o=e[i],a=e[i+1];r?"\n"===o&&(r=!1,t+=o):s?"*"===o&&"/"===a&&(s=!1,i++):n?(t+=o,"\\"===o?(t+=a??"",i++):'"'===o&&(n=!1)):'"'!==o?"/"!==o||"/"!==a?"/"!==o||"*"!==a?t+=o:(s=!0,i++):(r=!0,i++):(n=!0,t+=o)}const i=t.replace(/,(\s*[}\]])/g,"$1");try{return JSON.parse(i)}catch{return null}}function normalizePathsRecord(e){const t={};for(const[n,r]of Object.entries(e))if(Array.isArray(r)){const e=r.filter(e=>"string"==typeof e);e.length>0&&(t[n]=e)}else"string"==typeof r&&(t[n]=[r]);return t}function resolveReferencePath(e,t){const n=lb.resolve(e,t);return t.endsWith(".json")?n:lb.join(n,"tsconfig.json")}async function readTsconfigPathsFrom(e,t,n){if(t>8)return null;const r=lb.resolve(e);if(n.has(r))return null;n.add(r);const s=await readTextFileOptional3(r);if(null===s)return null;const i=parseJsonc(s);if(!i||"object"!=typeof i||Array.isArray(i))return null;const o=i,a=o.compilerOptions&&"object"==typeof o.compilerOptions&&!Array.isArray(o.compilerOptions)?o.compilerOptions:null,c=a?.paths;if(c&&"object"==typeof c&&!Array.isArray(c)){const e=normalizePathsRecord(c);if(Object.keys(e).length>0){const t="string"==typeof a?.baseUrl?a.baseUrl:".";return{configDir:lb.dirname(r),baseUrl:t,paths:e}}}const l=Array.isArray(o.references)?o.references:[];for(const e of l){if(!e||"object"!=typeof e||Array.isArray(e))continue;const s=e.path;if("string"!=typeof s)continue;const i=await readTsconfigPathsFrom(resolveReferencePath(lb.dirname(r),s),t+1,n);if(i)return i}const d=Array.isArray(o.extends)?o.extends:"string"==typeof o.extends?[o.extends]:[];for(const e of[...d].reverse()){if("string"!=typeof e)continue;const s=resolveExtendsConfigPath(lb.dirname(r),e);if(null===s)continue;const i=await readTsconfigPathsFrom(s,t+1,n);if(i)return i}return null}function resolveExtendsConfigPath(e,t){if(t.startsWith("./")||t.startsWith("../"))return t.endsWith(".json")?lb.resolve(e,t):lb.resolve(e,`${t}.json`);const n=ab(lb.join(e,"__tempo_tsconfig_resolve__.cjs")),r=t.endsWith(".json")?[t]:[t,`${t}/tsconfig.json`];for(const e of r)try{const t=n.resolve(e);if(t.endsWith(".json"))return t}catch{}return null}function rebaseAliasTarget(e,t,n,r){const s=lb.resolve(e,t,n);return toPosixRelativePath(r,s)}async function collectHostAliasPaths(e){for(const t of["tsconfig.json","jsconfig.json"]){const n=lb.join(e.projectRoot,t),r=await readTextFileOptional3(n);if(null===r)continue;if(null===parseJsonc(r))return{aliasPaths:{},warning:`Could not parse ${n}; "@/"-style imports in canvas files may not resolve.`};const s=await readTsconfigPathsFrom(n,0,new Set);if(!s)return{aliasPaths:{},warning:null};const i={};for(const[t,n]of Object.entries(s.paths)){const r=n.map(t=>rebaseAliasTarget(s.configDir,s.baseUrl,t,e.tempoRoot));r.length>0&&(i[t]=r)}return{aliasPaths:i,warning:null}}return{aliasPaths:{},warning:null}}function isTempoOwnedViteTsconfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;if(Object.keys(t).some(e=>"compilerOptions"!==e&&"include"!==e))return!1;const n=t.include;if(!Array.isArray(n)||n.length!==Nk.length||!Nk.every((e,t)=>n[t]===e))return!1;const r=t.compilerOptions;if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r;for(const[e,t]of Object.entries(Dk))if((e in s||!Rk.has(e))&&s[e]!==t)return!1;const i=new Set([...Object.keys(Dk),"baseUrl","paths"]);return!Object.keys(s).some(e=>!i.has(e))}async function reconcileGeneratedTsconfig(e,t,n){const r=await readTextFileOptional3(e);null!==r?r!==t&&n(parseJsonc(r))&&await atomicWriteText(e,t):await atomicWriteText(e,t)}async function reconcileGeneratedTextFile(e,t,n){const r=await readTextFileOptional3(e);null!==r?r!==t&&n(r)&&await atomicWriteText(e,t):await atomicWriteText(e,t)}async function ensureViteTsconfigFile(e){const{aliasPaths:t}=await collectHostAliasPaths(e);await reconcileGeneratedTsconfig(e.tsconfigPath,buildViteTsconfigFile(t),isTempoOwnedViteTsconfig)}async function ensureNextTsconfigFile(e){const{aliasPaths:t}=await collectHostAliasPaths(e);await reconcileGeneratedTsconfig(e.tsconfigPath,buildNextTsconfigFile(e,t),isTempoOwnedNextTsconfig)}var Ok={target:"ES2022",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,strictNullChecks:!0,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0};function buildNextTsconfigIncludes(e){const t=["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],n=toPosixRelativePath(e.tempoRoot,lb.join(e.projectRoot,"src")),r=toPosixRelativePath(e.tempoRoot,e.pagesDir);for(const e of[`${n}/**/*`,`${r}/**/*`])t.includes(e)||t.push(e);return t}function buildNextTsconfigFile(e,t){const n=Object.keys(t).length>0;return`${JSON.stringify({compilerOptions:{...Ok,...n?{baseUrl:".",paths:t}:{}},include:buildNextTsconfigIncludes(e),exclude:["node_modules"]},null,2)}\n`}function isTempoOwnedNextTsconfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e,n=new Set(["compilerOptions","include","exclude"]);if(Object.keys(t).some(e=>!n.has(e)))return!1;const r=t.compilerOptions;if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r;for(const[e,t]of Object.entries(Ok))if(e in s||!Rk.has(e))if(Array.isArray(t)){const n=s[e];if(!Array.isArray(n)||n.length!==t.length||!t.every((e,t)=>n[t]===e))return!1}else if(s[e]!==t)return!1;const i=new Set([...Object.keys(Ok),"baseUrl","paths"]);return!Object.keys(s).some(e=>!i.has(e))}var Fk={"react-native":["./node_modules/react-native"],"react-native/*":["./node_modules/react-native/*"],"react-native-web":["./node_modules/react-native-web"],"react-native-web/*":["./node_modules/react-native-web/*"]},Lk=["expo-env.d.ts","**/*.ts","**/*.tsx"];function buildExpoTsconfigFile(e,t={}){const n=[...Lk,toPosixRelativePath(e.tempoRoot,lb.join(e.projectRoot,"src"))+"/**/*",toPosixRelativePath(e.tempoRoot,e.pagesDir)+"/**/*"],r={...Fk,...t};return`${JSON.stringify({extends:"expo/tsconfig.base",compilerOptions:{strict:!1,strictNullChecks:!0,jsx:"react-jsx",noEmit:!0,baseUrl:".",paths:r},include:Array.from(new Set(n)),exclude:["node_modules"]},null,2)}\n`}function isTempoOwnedExpoTsconfig(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const e of Object.keys(t))if(!["extends","compilerOptions","include","exclude"].includes(e))return!1;if("expo/tsconfig.base"!==t.extends)return!1;const n=t.compilerOptions;if(!n||"object"!=typeof n||Array.isArray(n))return!1;const r=n;return!1===r.strict&&"react-jsx"===r.jsx&&!0===r.noEmit&&"."===r.baseUrl}function buildNextConfigFile(e=[]){const t=e.length>0?`\n transpilePackages: ${JSON.stringify(e)},`:"";return`import tempoNextjsPlugin from "tempo-sdk/nextjs/plugin";\nimport { fileURLToPath } from "node:url";\n\nconst withTempo = tempoNextjsPlugin();\n\nexport default withTempo({\n // Disabled for the canvas host only — see tempo-project/initialize.ts.\n reactStrictMode: false,${t}\n // fileURLToPath (not URL.pathname): pathname percent-encodes spaces/non-ASCII\n // and yields a "/C:/…" drive path on Windows — a nonexistent directory that\n // Turbopack, which uses this value as its workspace root, panics on.\n outputFileTracingRoot: fileURLToPath(new URL("..", import.meta.url)),\n});\n`}var Mk='new URL("..", import.meta.url).pathname',Uk='fileURLToPath(new URL("..", import.meta.url))';async function healNextConfigTracingRoot(e){const t=await readTextFileOptional3(e);if(null===t||!t.includes(Mk))return;let n=t.split(Mk).join(Uk);const r=/^\s*import\b[^\n;]*\bfileURLToPath\b/m.test(n);r||(n=insertLineAfterFirstImport(n,'import { fileURLToPath } from "node:url";')),n!==t&&await atomicWriteText(e,n)}function insertLineAfterFirstImport(e,t){const n=e.split("\n"),r=n.findIndex(e=>/^\s*import\b/.test(e));return-1===r?`${t}\n${e}`:(n.splice(r+1,0,t),n.join("\n"))}var jk=["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"];async function findNextConfigInDir(e){for(const t of jk){const n=lb.join(e,t);if(await pathIsFile(n))return n}return null}function extractTranspilePackagesFromSource(e){const t=/transpilePackages\s*:\s*\[([^\]]*)\]/.exec(e);if(!t)return[];const n=t[1],r=n.replace(/"[^"]*"|'[^']*'/g,"");return/[A-Za-z0-9_$]/.test(r)?[]:[...n.matchAll(/"([^"]+)"|'([^']+)'/g)].map(e=>e[1]??e[2])}async function collectAppTranspilePackages(e){const t=await findNextConfigInDir(e.projectRoot);if(null===t)return[];const n=await readTextFileOptional3(t);return null===n?[]:extractTranspilePackagesFromSource(n)}async function hasNuxtSidecarConfig(e){for(const t of zT){const n=await readTextFileOptional3(lb.join(e,t));if(n?.includes($T))return!0}return!1}async function isNuxtAppDir(e){const t=await readRootPackageDeps(e);return Boolean(t.nuxt)||await anyFileExists2(e,zT)}async function appRootUsesNuxt(e){const{appRoot:t}=await resolveAppRoot(e);return lb.resolve(t)!==lb.resolve(e.projectRoot)&&await isNuxtAppDir(t)}async function readUserNuxtConfigSource(e){for(const t of zT){const n=await readTextFileOptional3(lb.join(e,t));if(null!==n)return n}return null}async function findInstalledPackage(e,t){let n=lb.resolve(e);for(;;){const e=lb.join(n,"node_modules",t,"package.json");try{const t=await readJsonObjectOptional(e);if(t)return{dir:await nb(lb.dirname(e)),version:"string"==typeof t.version?t.version:null}}catch{}const r=lb.dirname(n);if(r===n)return null;n=r}}async function readUserNuxtVersions(e){const t=(await readRootPackageDeps(e)).nuxt??null,n=await findInstalledPackage(e,"nuxt");if(!n)return{nuxt:t,vite:null};const r=await findInstalledPackage(n.dir,"@nuxt/vite-builder"),s=r?await findInstalledPackage(r.dir,"vite"):null;return{nuxt:n.version??t,vite:s?.version??null}}async function appUsesNuxt4Layout(e){const{nuxt:t}=await readUserNuxtVersions(e),n=t?parsePackageMajorVersion(t):null;if(3!==n)return!0;const r=await readUserNuxtConfigSource(e);return null!==r&&/\bcompatibilityVersion\s*:\s*4\b/.test(r)}function buildNuxtSidecarConfigFile(e){return`${$T}\n// Tempo canvas dev server ("tempo-host"), NOT your app. Your app is a Nuxt\n// layer of this one, so its components, composables, plugins, server routes\n// and runtimeConfig are available to the canvas without copying anything.\nexport default defineNuxtConfig({\n extends: [${JSON.stringify(e.extendsPath)}],\n // Your app's own srcDir, kept in step with it by Tempo: modules that find\n // app files through \`nuxt.options.srcDir\` (pinia's stores) look there.\n // tempo-sdk/nuxt mounts the canvas host from tempo/app/.\n srcDir: ${JSON.stringify(e.srcDir)},\n ssr: false,\n devtools: { enabled: false },\n modules: ["tempo-sdk/nuxt"],\n // The module defaults to annotating an app; this config, not the module\n // list, makes it the canvas host, so the app (a layer) listing the module\n // too cannot change that.\n tempo: { role: "host" },\n experimental: { appManifest: false },\n compatibilityDate: ${JSON.stringify(e.compatibilityDate)},\n});\n`}function buildNuxtTempoHostMountVue(e){return`<script setup lang="ts">\nimport { onBeforeUnmount, onMounted, ref } from "vue";\nimport { mountTempoHost } from ${JSON.stringify(e)};\n\nconst el = ref<HTMLElement | null>(null);\nlet unmount: (() => void) | null = null;\n\nonMounted(() => {\n if (el.value) unmount = mountTempoHost(el.value);\n});\n\nonBeforeUnmount(() => {\n unmount?.();\n});\n<\/script>\n\n<template>\n <div ref="el" id="tempo-root"></div>\n</template>\n`}async function reconcileNuxtSidecarAppLocation(e,t){const n=await readTextFileOptional3(e);if(null===n||!n.includes($T))return;const r=n.replace(/^(\s*extends\s*:\s*)\[\s*(["'])[^"'\n]*\2\s*\]/m,(e,n)=>`${n}[${JSON.stringify(t.extendsPath)}]`).replace(/^(\s*srcDir\s*:\s*)(["'])[^"'\n]*\2/m,(e,n)=>`${n}${JSON.stringify(t.srcDir)}`);r!==n&&await atomicWriteText(e,r)}async function reconcileNuxtSidecarHostRole(e){const t=await readTextFileOptional3(e);if(null===t||!t.includes($T))return;const n=t.match(/\btempo\s*:/g)??[];let r=t;if(0===n.length)r=t.replace(/^(\s*)modules: \["tempo-sdk\/nuxt"\],\n/m,(e,t)=>`${e}${t}tempo: { role: "host" },\n`);else if(1===n.length){const e=/\btempo\s*:\s*\{([^{}]*)\}/.exec(t),n=e&&/\brole\s*:/.test(e[1]??"");if(e&&!n){const n=""===(e[1]??"").trim();r=t.replace(/(\btempo\s*:\s*\{)(\s*)/,(e,t,r)=>r.includes("\n")?`${t}${r}role: "host",${r}`:`${t} role: "host"${n?" ":", "}`)}}r!==t&&await atomicWriteText(e,r)}async function ensureNuxtSidecarPages(e){const t=lb.join(e.tempoRoot,GT);await writeFileIfMissing(lb.join(t,"app.vue"),KT),await writeFileIfMissing(lb.join(t,"pages","tempo-host.vue"),XT);const n=lb.join(t,"components");await writeFileIfMissing(lb.join(n,"TempoHostMount.vue"),buildNuxtTempoHostMountVue(importSpecifier(n,lb.join(e.tempoRoot,".tempo","host-entry"))))}var Bk=["nuxt","vue","vue-router","@vitejs/plugin-vue"];async function appPackageLinks(e,t,n){const r=await findOwningInstall(e),s="pnpm"===r.pin.pm?e:r.dir,i=isInsidePath(s,t),o=(await findOwningInstall(t)).pin.pm,a=await readRootPackageDeps(e),c=n.filter(e=>a[e]);if("yarn"===o||"bun"===o)return{links:{},reachedByWalkingUp:i?c:[],unsupportedInstaller:i?null:o};if("npm"===o&&i)return{links:{},reachedByWalkingUp:c,unsupportedInstaller:null};const l="pnpm"===o?"link:":"file:",d={};for(const e of c){const n=lb.join(s,"node_modules",e);d[e]=`${l}${toPosixRelativePath(t,n)}`}return{links:d,reachedByWalkingUp:[],unsupportedInstaller:null}}var $k="^5.2.0";function buildNuxtTempoOwnedPackage(e,t,n,r,s){const i=e?parsePackageJson(t.packageJsonPath,e):{},o=sanitizePackageName(`${lb.basename(t.projectRoot)}-tempo`),a=toStringRecord(i.dependencies),c=toStringRecord(i.devDependencies);for(const e of Bk)delete a[e],delete c[e];const l=withUserReactMajorAdopted(wT,r),d=l.react===wT.react?{}:{react:l.react,"react-dom":l["react-dom"]},u=sortObjectKeys({...wT,...a,...d,...s}),p=parsePackageMajorVersion(u.react??""),m=null===p?{}:{"@types/react":`^${p}.0.0`,"@types/react-dom":`^${p}.0.0`},f={typescript:bT.typescript,...m,...c,"@vitejs/plugin-react":$k};n.vite&&(f.vite=n.vite),applyManagedTempoSdkSpec(u,f,i);const g=n.nuxt?parsePackageMajorVersion(n.nuxt):null,y={...i,name:"string"==typeof i.name&&i.name.trim().length>0?i.name:o,private:"boolean"!=typeof i.private||i.private,type:"string"==typeof i.type&&i.type.trim().length>0?i.type:"module",scripts:sortObjectKeys({...toStringRecord(i.scripts),dev:3===g?"nuxt dev --no-fork":"nuxt dev",postinstall:"nuxt prepare"}),dependencies:u,devDependencies:sortObjectKeys(f)};return`${JSON.stringify(y,null,2)}\n`}var Wk={jsx:"react-jsx",jsxImportSource:"react",strictNullChecks:!0},Hk="./.nuxt/tsconfig.json";function buildNuxtTsconfigFile(e){const t=toPosixRelativePath(e.tempoRoot,e.pagesDir);return`${JSON.stringify({extends:Hk,compilerOptions:Wk,include:["./.nuxt/nuxt.d.ts",`${GT}/**/*`,".tempo/**/*","vue-shims.d.ts","controls.ts",`${t}/**/*`]},null,2)}\n`}function isTempoOwnedNuxtTsconfig(e){if(isTempoOwnedViteTsconfig(e)||isTempoOwnedNextTsconfig(e))return!0;if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e,n=new Set(["extends","compilerOptions","include"]);if(Object.keys(t).some(e=>!n.has(e)))return!1;if(t.extends!==Hk)return!1;const r=t.compilerOptions;if(!r||"object"!=typeof r||Array.isArray(r))return!1;const s=r,i=Object.entries(Wk);return Object.keys(s).length===i.length&&i.every(([e,t])=>s[e]===t)}async function ensureNuxtTsconfigFile(e){await reconcileGeneratedTsconfig(e.tsconfigPath,buildNuxtTsconfigFile(e),isTempoOwnedNuxtTsconfig)}var qk=12e4;function resolveUserNuxtBuildDir(e,t){const n=t?.match(/\bbuildDir\s*:\s*["'`]([^"'`]+)["'`]/)?.[1];return lb.resolve(e,n??".nuxt")}async function readNuxtCliPath(e){const t=await readJsonObjectOptional(lb.join(e,"package.json")),n=t?.bin,r="string"==typeof n?n:n&&"object"==typeof n&&!Array.isArray(n)?n.nuxt??n.nuxi:void 0;if("string"!=typeof r)return null;const s=lb.resolve(e,r);return await pathIsFile(s)?s:null}async function ensureNuxtAppTypesGenerated(e){const t=await readUserNuxtConfigSource(e),n=resolveUserNuxtBuildDir(e,t);if(await pathIsFile(lb.join(n,"tsconfig.json")))return null;const r=await findInstalledPackage(e,"nuxt"),s=r?await readNuxtCliPath(r.dir):null;if(!s)return null;const i=`node "${s}" prepare`,o=augmentManagedPath({...process.env}),a=r?await pnpmHoistDirOf(r.dir):null;a&&(o.NODE_PATH=[a,o.NODE_PATH].filter(Boolean).join(lb.delimiter));const c=await runAbortableShellCommand({command:i,cwd:e,env:o,idleTimeoutMs:qk});if(0===c.exitCode)return null;const l=c.spawnError?.message??(c.timedOut?"it printed nothing for two minutes":`exit code ${c.exitCode}`);return setupWarning(`\`${i}\` in ${e} failed (${l}); the canvas host cannot transform app files until the app's .nuxt/ types exist. ${c.output.trim().slice(-800)}`)}async function resolveUserNuxtSrcDir(e,t){const n=t?.match(/\bsrcDir\s*:\s*["'`]([^"'`]+)["'`]/)?.[1];if(n)return lb.resolve(e,n);const r=lb.join(e,"app");return await appUsesNuxt4Layout(e)&&await pathIsDirectory(r)?r:e}function resolveNuxtCssSpecifier(e,t,n){const r=cleanLocalSpecifier(e);return r?/^(?:~~|@@)\//.test(r)?lb.resolve(t,r.slice(3)):/^[~@]\//.test(r)?lb.resolve(n,r.slice(2)):r.startsWith("./")||r.startsWith("../")?lb.resolve(t,r):null:null}async function collectNuxtCssEntries(e){const t=await readUserNuxtConfigSource(e),n=await resolveUserNuxtSrcDir(e,t),r=[],s=t?.match(/\bcss\s*:\s*\[([^\]]*)\]/)?.[1]??"";for(const t of s.matchAll(/["'`]([^"'`]+)["'`]/g)){const s=resolveNuxtCssSpecifier(t[1],e,n);s?.endsWith(".css")&&r.push(s)}const i=lb.join(n,"assets","css");let o=[];try{o=await tb(i,{withFileTypes:!0})}catch{}for(const e of o)e.isFile()&&e.name.endsWith(".css")&&r.push(lb.join(i,e.name));return r}function buildNuxtAppStartCommand(e,t){const n=t.startsWith(".")?t:`./${t}`,r=`nuxt dev --port \${APP_PORT} --extends ${n}`;return"pnpm"===e?`pnpm exec ${r}`:"yarn"===e?`yarn ${r}`:"bun"===e?`bunx ${r}`:`npx ${r}`}function nuxtAppLayerPathFrom(e,t){const n=toPosixRelativePath(e,lb.join(t,HT));return n.startsWith(".")?n:`./${n}`}async function nuxtAppStartFor(e,t){const n=await detectOwningPackageManager(e);return buildNuxtAppStartCommand(n?.pm??null,nuxtAppLayerPathFrom(e,t))}async function resolveNuxtAppRun(e){const{appRoot:t,warning:n}=await resolveAppRoot(e),r=lb.resolve(t)===lb.resolve(e.projectRoot),s=await nuxtAppStartFor(t,e.tempoRoot);return{appRoot:t,appDir:r?null:toPosixRelativePath(e.projectRoot,t),appLayerPath:nuxtAppLayerPathFrom(t,e.tempoRoot),start:s,projectRootStart:r?s:await nuxtAppStartFor(e.projectRoot,e.tempoRoot),appRootWarning:n}}function nuxtAppStartExtendsAppLayer(e){return new RegExp(`--extends(?:\\s+|=)\\S*${HT}\\b`).test(e)}function toCssRelativePath(e,t){const n=toPosixRelativePath(e,t);return"."===n||n.startsWith(".")?n:`./${n}`}function toRelativeAllowPath(e){const t=lb.relative(e.tempoRoot,e.projectRoot);return""===t?".":t.replace(/\\/g,"/")}function buildViteConfigFile(e,t,n,r){const s=`\n server: {\n fs: {\n allow: [${JSON.stringify(toRelativeAllowPath(e))}],\n },\n },`,i=hostRuntimeDedupeLiteral(n),o=`\n resolve: {\n dedupe: ${i},\n },`,a=ST[n],c=a.marker?`${a.marker}\n`:"",l=a.imports,d=a.pluginCalls(toPosixRelativePath(e.tempoRoot,r)),u=a.reactPluginCall,p=a.tsconfigPathsOptions,m=a.prebundle.map(e=>`\n ${JSON.stringify(e)},`).join(""),f=`\n optimizeDeps: {\n // The generated host imports only canvases requested by the user. Keep\n // unused canvases and their dependencies off the cold-start path.\n entries: ["index.html"],\n include: [\n "react",\n "react-dom",\n "react-dom/client",\n "react/jsx-runtime",\n "react/jsx-dev-runtime",${m}\n ],\n },`;return 3===t.tailwindMajor?`${c}${dT}import path from "node:path";\nimport { fileURLToPath } from "node:url";\nimport tailwindcss from "tailwindcss";\nimport autoprefixer from "autoprefixer";\nimport react from "@vitejs/plugin-react";\n${l}import { tempoVitePlugin } from "tempo-sdk";\nimport { defineConfig } from "vite";\nimport tsconfigPaths from "vite-tsconfig-paths";\n\nconst tempoRoot = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(tempoRoot, ${JSON.stringify(toRelativeAllowPath(e))});\n\nexport default defineConfig({\n root: tempoRoot,${o}\n css: {\n postcss: {\n plugins: [tempoHostStyles(), tailwindcss(), autoprefixer()],\n },\n },\n plugins: [\n tempoVitePlugin({ sourceIdentityRoot: projectRoot }),\n${d}${u} tsconfigPaths({\n projectDiscovery: "lazy",\n${p} }),\n ],${s}${f}\n});\n`:`${c}${dT}import path from "node:path";\nimport { fileURLToPath } from "node:url";\nimport tailwindcss from "@tailwindcss/vite";\nimport react from "@vitejs/plugin-react";\n${l}import { tempoVitePlugin } from "tempo-sdk";\nimport { defineConfig } from "vite";\nimport tsconfigPaths from "vite-tsconfig-paths";\n\nconst tempoRoot = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(tempoRoot, ${JSON.stringify(toRelativeAllowPath(e))});\n\nexport default defineConfig({\n root: tempoRoot,${o}\n plugins: [\n tempoHostStyles.vite(),\n tailwindcss(),\n tempoVitePlugin({ sourceIdentityRoot: projectRoot }),\n${d}${u} tsconfigPaths({\n projectDiscovery: "lazy",\n${p} }),\n ],${s}${f}\n});\n`}function parsePackageJson(e,t){let n;try{n=JSON.parse(t)}catch(t){throw new qm(e,t instanceof Error?t.message:String(t))}if(!n||"object"!=typeof n||Array.isArray(n))throw new qm(e,"expected top-level object");return n}function toStringRecord(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t={};for(const[n,r]of Object.entries(e))"string"==typeof r&&r.length>0&&(t[n]=r);return t}function sortObjectKeys(e){return Object.fromEntries(Object.entries(e).sort((e,t)=>e[0].localeCompare(t[0])))}function sanitizePackageName(e){const t=e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return t.length>0?t:"tempo-project"}var zk={packages:[],previews:[],warnings:[],flutterOnly:!1};async function setUpFlutterApp(e,t={}){const n=t.env??process.env,r=my.resolve(e.projectRoot),s=await findFlutterPackages(r);if(!s.length)return zk;const i=[],o=[];for(const t of s){const n=t.dir,r=await discoverPreviews(n,t.packageName);r.previews.length||i.push(noPreviewsWarning(t.relativeDir)),r.skipped.length&&i.push(skippedPreviewsWarning(r.skipped));for(const e of await findNativeOnlyImports(n,t.packageName,r.previews.map(e=>e.libraryFile))){const{problem:n,fix:r}=describeNativeOnlyImport(e);i.push(`${t.relativeDir}: ${n} ${r}`)}o.push(...r.previews.map(t=>({...t,file:my.join(n,t.file),key:flutterPreviewKey(e.tempoRoot,my.join(n,t.file),t.name)})))}return i.push(...await flutterSdkWarnings([...s.map(e=>e.dir),r],n)),{packages:s.map(e=>({dir:e.dir,name:e.packageName})),previews:o,warnings:i,flutterOnly:s.some(e=>"."===e.relativeDir)||!await isFile(my.join(r,"package.json"))}}function noPreviewsWarning(e){return`Tempo found no @Preview functions in ${e}/lib. A FlutterStoryboard renders one top-level, public function with no required parameters that returns a Widget and is annotated with @Preview from package:flutter/widget_previews.dart. Add one (for example in lib/previews.dart), then name it in a canvas as preview="../../lib/previews.dart#<function>".`}var Gk={private:"private: drop the leading underscore","not-top-level":"not top-level: move it out of its class","required-parameters":"it has required parameters: give each a default, or wrap the call in a function without parameters","unsupported-declaration":"not a function returning Widget or WidgetBuilder","part-file":"its part file names its library in a way Tempo cannot follow: use part of '<file>.dart'"};function describeSkippedPreviewReason(e){return Gk[e]}function skippedPreviewsWarning(e){const t=e.map(e=>`${e.file}:${e.line} ${e.name??"(unnamed)"} (${describeSkippedPreviewReason(e.reason)})`).join("; ");return`Tempo cannot render these @Preview functions: ${t}.`}var Vk=10;function describeNativeOnlyImport(e){const t=e.chain[e.chain.length-1],n=e.chain.slice(1,-1),r=1===e.chain.length?"":`, reached from the preview library ${e.chain[0]}${n.length>0?` through ${n.join(", ")}`:""}`,s=`${t} imports ${e.library}${r}.`,i="or put the native code behind a conditional import whose web branch is a stub (import 'storage_stub.dart' if (dart.library.io) 'storage_io.dart')";if("build-fails"===e.effect)return{problem:`${s} ${e.library} does not compile for the web, which the canvas runs, and the canvas host imports every preview library, so the Flutter build fails and every Flutter board shows flutter_run_failed.`,fix:`Keep the previews off that import: preview a widget whose imports stay web-safe, ${i}.`};const o=e.previewLibraries.slice(0,Vk),a=e.previewLibraries.length-o.length;return{problem:`${s} ${e.library} compiles for the web, which the canvas runs, but its calls throw UnsupportedError there, so a board whose widget calls it while building shows an error box instead of the widget. Preview libraries that reach it: ${o.join(", ")}${a>0?`, and ${a} more`:""}.`,fix:`Give those widgets fake data instead of the native service, ${i}.`}}async function flutterSdkWarnings(e,t){const n=await readFvmPin(e);let r;try{r=await locateFlutterBinary(t,e)}catch(e){return e&&"object"==typeof e&&"code"in e&&"flutter_sdk_conflict"===e.code?[String(e)]:[missingSdkWarning(t,n)]}const s=[],i=n?unusedPinWarning(n,r):null;i&&s.push(i);const o=await readFlutterSdkVersion(r.path),a=o?sdkVersionWarning(o,r.path):null;return a&&s.push(a),s}async function readFvmPin(e){for(const t of new Set(e)){const e=await readFvmVersion(my.join(t,".fvmrc"),"flutter")??await readFvmVersion(my.join(t,".fvm","fvm_config.json"),"flutterSdkVersion");if(null===e)continue;const n="win32"===process.platform?"flutter.bat":"flutter",r=my.join(t,".fvm","flutter_sdk","bin",n);return{dir:t,version:e,binary:r}}return null}function missingSdkWarning(e,t){const n=e.TEMPO_FLUTTER_BIN?.trim();return n?`TEMPO_FLUTTER_BIN is set to ${n}, which is not an executable file. Point it at the flutter executable (…/flutter/bin/flutter), then restart Tempo; until then Flutter boards show flutter_sdk_missing.`:t?`This project pins Flutter ${t.version} with FVM, but the pinned SDK is not installed (${t.binary} is missing). Run \`fvm use ${t.version}\` in ${t.dir}, which installs the SDK and links it at .fvm/flutter_sdk; Tempo then runs it. Until then Flutter boards show flutter_sdk_missing.`:"Flutter boards need the Flutter SDK, but `flutter` is not on PATH and TEMPO_FLUTTER_BIN is not set. Install Flutter (https://docs.flutter.dev/get-started/install) and put flutter on the PATH of the shell Tempo starts from, or set TEMPO_FLUTTER_BIN to the flutter executable, then restart Tempo; until then Flutter boards show flutter_sdk_missing."}function unusedPinWarning(e,t){return"fvm"===t.source?null:"TEMPO_FLUTTER_BIN"===t.source?my.resolve(t.path)===my.resolve(e.binary)?null:`This project pins Flutter ${e.version} with FVM, but TEMPO_FLUTTER_BIN (${t.path}) overrides the pin, so Flutter boards build with that SDK. Unset TEMPO_FLUTTER_BIN to build with the pinned SDK, then restart Tempo.`:`This project pins Flutter ${e.version} with FVM, but the pinned SDK is not installed (${e.binary} is missing), so Flutter boards build with ${t.path}, which may be another version. Run \`fvm use ${e.version}\` in ${e.dir}, which installs the SDK and links it at .fvm/flutter_sdk; Tempo then runs it.`}var Kk={major:3,minor:35},Xk={major:3,minor:39};function sdkVersionWarning(e,t){const n=/^(\d+)\.(\d+)/.exec(e);if(!n)return null;const r=Number(n[1]),s=Number(n[2]),isBelow=e=>r<e.major||r===e.major&&s<e.minor;return isBelow(Kk)?`Tempo will run Flutter ${e} (${t}), but Flutter boards need Flutter 3.35 or newer: @Preview comes from package:flutter/widget_previews.dart. Upgrade to the latest stable release (Tempo is tested on 3.47); until then the Flutter host fails to build and boards show flutter_run_failed.`:isBelow(Xk)?`Tempo will run Flutter ${e} (${t}). Boards render, but Flutter 3.38 and older cannot hot-reload a page on the canvas, so Dart saves do not show until Flutter restarts. Upgrade to the latest stable release (Tempo is tested on 3.47).`:null}async function readFvmVersion(e,t){try{const n=JSON.parse(await uy(e,"utf-8"));if(null===n||"object"!=typeof n)return null;const r=n[t];return"string"==typeof r&&r.trim()?r.trim():null}catch{return null}}var Yk=24,Jk={width:400,height:300},Qk=40,Zk=1640;async function seedFlutterHomeCanvas(e,t){const n=await resolveFreeformCanvasesDir(e.pagesDir),r=my.join(n,"home","index.canvas.tsx");let s=null;try{s=await uy(r,"utf-8")}catch{s=null}if(null!==s&&s!==UT)return!1;const i="the project packages";return await dy(my.dirname(r),{recursive:!0}),await hy(r,buildFlutterHomeCanvas(t.previews.map(t=>({...t,key:flutterPreviewForCanvas(t.key,r,e.tempoRoot)})),i),"utf-8"),!0}function buildFlutterHomeCanvas(e,t){const n=e.slice(0,Yk),r=new Set,s=[];let i=0,o=0,a=0;for(const e of n){const t=e.size??Jk,n=Math.round(t.width),c=Math.round(t.height);i>0&&i+n>Zk&&(i=0,o+=a+Qk,a=0);const l=uniqueBoardId(e.name,r);s.push([" <FlutterStoryboard",` id=${JSON.stringify(l)}`,` name=${JSON.stringify(e.label??e.name)}`,` preview=${JSON.stringify(e.key)}`,` layout={{ x: ${i}, y: ${o}, width: ${n}, height: ${c} }}`," />"].join("\n")),i+=n+Qk,a=Math.max(a,c)}const c=e.length-n.length,l=0===n.length?[`// No @Preview functions were found in ${t}/lib when this canvas was`,"// created. Add a top-level, public function with no required parameters,","// annotated with @Preview from package:flutter/widget_previews.dart, then",'// add <FlutterStoryboard preview="../../lib/<file>.dart#<function>" .../> here.']:["// The Flutter app's previews: one FlutterStoryboard per @Preview function in",`// ${t}/lib, each sized by its @Preview(size: ...) when it states one.`,...c>0?[`// ${c} more previews were found; add them as FlutterStoryboards`,"// here or on other canvases."]:[]];return["// @tempo-home — Tempo home canvas (the workspace Run button opens this). Managed marker; do not remove.","//",...l,"",'import { Canvas, FlutterStoryboard } from "tempo-sdk/canvas";',"","export default function HomeCanvas() {"," return (",...0===s.length?[' <Canvas name="Home" />']:[' <Canvas name="Home">',...s," </Canvas>"]," );","}",""].join("\n")}function uniqueBoardId(e,t){const n=e.charAt(0).toUpperCase()+e.slice(1);let r=n;for(let e=2;t.has(r);e+=1)r=`${n}${e}`;return t.add(r),r}async function isFile(e){try{return(await py(e)).isFile()}catch{return!1}}import eS from"path";import{access as tS}from"fs/promises";import nS from"fs/promises";import rS from"path";var sS=C(Od(),1),iS=C(Rd(),1),oS=C(Fd(),1),aS=C(Fd(),1);import{Buffer as cS}from"buffer";import{spawn as lS}from"child_process";import{normalize as dS}from"path";import{EventEmitter as uS}from"events";var pS=Object.defineProperty,hS=Object.getOwnPropertyDescriptor,mS=Object.getOwnPropertyNames,fS=Object.prototype.hasOwnProperty,__esm2=(e,t)=>function __init(){return e&&(t=(0,e[mS(e)[0]])(e=0)),t},__commonJS2=(e,t)=>function __require2(){return t||(0,e[mS(e)[0]])((t={exports:{}}).exports,t),t.exports},__export2=(e,t)=>{for(var n in t)pS(e,n,{get:t[n],enumerable:!0})},__copyProps=(e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of mS(t))fS.call(e,s)||s===n||pS(e,s,{get:()=>t[s],enumerable:!(r=hS(t,s))||r.enumerable});return e},__toCommonJS2=e=>__copyProps(pS({},"__esModule",{value:!0}),e),gS;function pathspec(...e){const t=new String(e);return gS.set(t,e),t}function isPathSpec(e){return e instanceof String&&gS.has(e)}function toPaths(e){return gS.get(e)||[]}var yS=__esm2({"src/lib/args/pathspec.ts"(){gS=new WeakMap}}),bS,vS=__esm2({"src/lib/errors/git-error.ts"(){bS=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),wS,_S=__esm2({"src/lib/errors/git-response-error.ts"(){vS(),wS=class extends bS{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),xS,TS=__esm2({"src/lib/errors/task-configuration-error.ts"(){vS(),xS=class extends bS{constructor(e){super(void 0,e)}}}}),kS,SS,ES;function asFunction(e){return"function"!=typeof e?SS:e}function isUserFunction(e){return"function"==typeof e&&e!==SS}function splitOn(e,t){const n=e.indexOf(t);return n<=0?[e,""]:[e.substr(0,n),e.substr(n+1)]}function first2(e,t=0){return isArrayLike(e)&&e.length>t?e[t]:void 0}function last2(e,t=0){if(isArrayLike(e)&&e.length>t)return e[e.length-1-t]}function isArrayLike(e){return RS(e)}function toLinesWithContent(e="",t=!0,n="\n"){return e.split(n).reduce((e,n)=>{const r=t?n.trim():n;return r&&e.push(r),e},[])}function forEachLineWithContent(e,t){return toLinesWithContent(e,!0).map(e=>t(e))}function folderExists(e){return(0,sS.exists)(e,sS.FOLDER)}function append(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function including(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function remove(e,t){if(Array.isArray(e)){const n=e.indexOf(t);n>=0&&e.splice(n,1)}else e.delete(t);return t}function asArray2(e){return Array.isArray(e)?e:[e]}function asCamelCase(e){return e.replace(/[\s-]+(.)/g,(e,t)=>t.toUpperCase())}function asStringArray(e){return asArray2(e).map(e=>e instanceof String?e:String(e))}function asNumber(e,t=0){if(null==e)return t;const n=parseInt(e,10);return Number.isNaN(n)?t:n}function prefixedArray(e,t){const n=[];for(let r=0,s=e.length;r<s;r++)n.push(t,e[r]);return n}function bufferToString(e){return(Array.isArray(e)?cS.concat(e):e).toString("utf-8")}function pick(e,t){const n={};return t.forEach(t=>{void 0!==e[t]&&(n[t]=e[t])}),n}function delay2(e=0){return new Promise(t=>setTimeout(t,e))}function orVoid(e){if(!1!==e)return e}var AS=__esm2({"src/lib/utils/util.ts"(){NS(),kS="\0",SS=()=>{},ES=Object.prototype.toString.call.bind(Object.prototype.toString)}}),CS,IS,PS,DS,RS;function filterType(e,t,n){return t(e)?e:arguments.length>2?n:void 0}function filterPrimitives(e,t){const n=isPathSpec(e)?"string":typeof e;return/number|string|boolean/.test(n)&&(!t||!t.includes(n))}function filterPlainObject(e){return!!e&&"[object Object]"===ES(e)}function filterFunction(e){return"function"==typeof e}var NS=__esm2({"src/lib/utils/argument-filters.ts"(){yS(),AS(),CS=e=>Array.isArray(e),IS=e=>"number"==typeof e,PS=e=>"string"==typeof e,DS=e=>PS(e)||Array.isArray(e)&&e.every(PS),RS=e=>null!=e&&!"number|boolean|function".includes(typeof e)&&"number"==typeof e.length}}),OS,FS=__esm2({"src/lib/utils/exit-codes.ts"(){OS=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.ERROR=1]="ERROR",e[e.NOT_FOUND=-2]="NOT_FOUND",e[e.UNCLEAN=128]="UNCLEAN",e))(OS||{})}}),LS,MS=__esm2({"src/lib/utils/git-output-streams.ts"(){LS=class _GitOutputStreams{constructor(e,t){this.stdOut=e,this.stdErr=t}asStrings(){return new _GitOutputStreams(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}}),US,jS;function useMatchesDefault(){throw new Error("LineParser:useMatches not implemented")}var BS=__esm2({"src/lib/utils/line-parser.ts"(){US=class{constructor(e,t){this.matches=[],this.useMatches=useMatchesDefault,this.parse=(e,t)=>(this.resetMatches(),!!this._regExp.every((t,n)=>this.addMatch(t,n,e(n)))&&!1!==this.useMatches(t,this.prepareMatches())),this._regExp=Array.isArray(e)?e:[e],t&&(this.useMatches=t)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(e,t,n){const r=n&&e.exec(n);return r&&this.pushMatch(t,r),!!r}pushMatch(e,t){this.matches.push(...t.slice(1))}},jS=class extends US{addMatch(e,t,n){return/^remote:\s/.test(String(n))&&super.addMatch(e,t,n)}pushMatch(e,t){(e>0||t.length>1)&&super.pushMatch(e,t)}}}}),$S;function createInstanceConfig(...e){const t=process.cwd(),n=Object.assign({baseDir:t,...$S},...e.filter(e=>"object"==typeof e&&e));return n.baseDir=n.baseDir||t,n.trimmed=!0===n.trimmed,n}var WS=__esm2({"src/lib/utils/simple-git-options.ts"(){$S={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function appendTaskOptions(e,t=[]){return filterPlainObject(e)?Object.keys(e).reduce((t,n)=>{const r=e[n];if(isPathSpec(r))t.push(r);else if(filterPrimitives(r,["boolean"]))t.push(n+"="+r);else if(Array.isArray(r))for(const e of r)filterPrimitives(e,["string","number"])||t.push(n+"="+e);else t.push(n);return t},t):t}function getTrailingOptions(e,t=0,n=!1){const r=[];for(let n=0,s=t<0?e.length:t;n<s;n++)"string|number".includes(typeof e[n])&&r.push(String(e[n]));return appendTaskOptions(trailingOptionsArgument(e),r),n||r.push(...trailingArrayArgument(e)),r}function trailingArrayArgument(e){const t="function"==typeof last2(e);return asStringArray(filterType(last2(e,t?1:0),CS,[]))}function trailingOptionsArgument(e){const t=filterFunction(last2(e));return filterType(last2(e,t?1:0),filterPlainObject)}function trailingFunctionArgument(e,t=!0){const n=asFunction(last2(e));return t||isUserFunction(n)?n:void 0}var HS=__esm2({"src/lib/utils/task-options.ts"(){NS(),AS(),yS()}});function callTaskParser(e,t){return e(t.stdOut,t.stdErr)}function parseStringResponse(e,t,n,r=!0){return asArray2(n).forEach(n=>{for(let s=toLinesWithContent(n,r),i=0,o=s.length;i<o;i++){const line=(e=0)=>{if(!(i+e>=o))return s[i+e]};t.some(({parse:t})=>t(line,e))}}),e}var qS=__esm2({"src/lib/utils/task-parser.ts"(){AS()}}),zS={};__export2(zS,{ExitCodes:()=>OS,GitOutputStreams:()=>LS,LineParser:()=>US,NOOP:()=>SS,NULL:()=>kS,RemoteLineParser:()=>jS,append:()=>append,appendTaskOptions:()=>appendTaskOptions,asArray:()=>asArray2,asCamelCase:()=>asCamelCase,asFunction:()=>asFunction,asNumber:()=>asNumber,asStringArray:()=>asStringArray,bufferToString:()=>bufferToString,callTaskParser:()=>callTaskParser,createInstanceConfig:()=>createInstanceConfig,delay:()=>delay2,filterArray:()=>CS,filterFunction:()=>filterFunction,filterHasLength:()=>RS,filterNumber:()=>IS,filterPlainObject:()=>filterPlainObject,filterPrimitives:()=>filterPrimitives,filterString:()=>PS,filterStringOrStringArray:()=>DS,filterType:()=>filterType,first:()=>first2,folderExists:()=>folderExists,forEachLineWithContent:()=>forEachLineWithContent,getTrailingOptions:()=>getTrailingOptions,including:()=>including,isUserFunction:()=>isUserFunction,last:()=>last2,objectToString:()=>ES,orVoid:()=>orVoid,parseStringResponse:()=>parseStringResponse,pick:()=>pick,prefixedArray:()=>prefixedArray,remove:()=>remove,splitOn:()=>splitOn,toLinesWithContent:()=>toLinesWithContent,trailingFunctionArgument:()=>trailingFunctionArgument,trailingOptionsArgument:()=>trailingOptionsArgument});var GS=__esm2({"src/lib/utils/index.ts"(){NS(),FS(),MS(),BS(),WS(),HS(),qS(),AS()}}),VS={},KS,XS,YS;function checkIsRepoTask(e){switch(e){case"bare":return checkIsBareRepoTask();case"root":return checkIsRepoRootTask()}const t=["rev-parse","--is-inside-work-tree"];return{commands:t,format:"utf-8",onError:XS,parser:YS}}function checkIsRepoRootTask(){const e=["rev-parse","--git-dir"];return{commands:e,format:"utf-8",onError:XS,parser:e=>/^\.(git)?$/.test(e.trim())}}function checkIsBareRepoTask(){const e=["rev-parse","--is-bare-repository"];return{commands:e,format:"utf-8",onError:XS,parser:YS}}function isNotRepoMessage(e){return/(Not a git repository|Kein Git-Repository)/i.test(String(e))}__export2(VS,{CheckRepoActions:()=>KS,checkIsBareRepoTask:()=>checkIsBareRepoTask,checkIsRepoRootTask:()=>checkIsRepoRootTask,checkIsRepoTask:()=>checkIsRepoTask});var JS=__esm2({"src/lib/tasks/check-is-repo.ts"(){GS(),KS=(e=>(e.BARE="bare",e.IN_TREE="tree",e.IS_REPO_ROOT="root",e))(KS||{}),XS=({exitCode:e},t,n,r)=>{if(128===e&&isNotRepoMessage(t))return n(Buffer.from("false"));r(t)},YS=e=>"true"===e.trim()}}),QS,ZS,eE,tE;function cleanSummaryParser(e,t){const n=new QS(e),r=e?eE:ZS;return toLinesWithContent(t).forEach(e=>{const t=e.replace(r,"");n.paths.push(t),(tE.test(t)?n.folders:n.files).push(t)}),n}var nE=__esm2({"src/lib/responses/CleanSummary.ts"(){GS(),QS=class{constructor(e){this.dryRun=e,this.paths=[],this.files=[],this.folders=[]}},ZS=/^[a-z]+\s*/i,eE=/^[a-z]+\s+[a-z]+\s*/i,tE=/\/$/}}),rE={},sE;function adhocExecTask(e){return{commands:sE,format:"empty",parser:e}}function configurationErrorTask(e){return{commands:sE,format:"empty",parser(){throw"string"==typeof e?new xS(e):e}}}function straightThroughStringTask(e,t=!1){return{commands:e,format:"utf-8",parser:e=>t?String(e).trim():e}}function straightThroughBufferTask(e){return{commands:e,format:"buffer",parser:e=>e}}function isBufferTask(e){return"buffer"===e.format}function isEmptyTask(e){return"empty"===e.format||!e.commands.length}__export2(rE,{EMPTY_COMMANDS:()=>sE,adhocExecTask:()=>adhocExecTask,configurationErrorTask:()=>configurationErrorTask,isBufferTask:()=>isBufferTask,isEmptyTask:()=>isEmptyTask,straightThroughBufferTask:()=>straightThroughBufferTask,straightThroughStringTask:()=>straightThroughStringTask});var iE=__esm2({"src/lib/tasks/task.ts"(){TS(),sE=[]}}),oE={},aE,cE,lE,dE,uE;function cleanWithOptionsTask(e,t){const{cleanMode:n,options:r,valid:s}=getCleanOptions(e);return n?s.options?(r.push(...t),r.some(isInteractiveMode)?configurationErrorTask(aE):cleanTask(n,r)):configurationErrorTask(lE+JSON.stringify(e)):configurationErrorTask(cE)}function cleanTask(e,t){const n=["clean",`-${e}`,...t];return{commands:n,format:"utf-8",parser:t=>cleanSummaryParser("n"===e,t)}}function isCleanOptionsArray(e){return Array.isArray(e)&&e.every(e=>uE.has(e))}function getCleanOptions(e){let t,n=[],r={cleanMode:!1,options:!0};return e.replace(/[^a-z]i/g,"").split("").forEach(e=>{isCleanMode(e)?(t=e,r.cleanMode=!0):r.options=r.options&&isKnownOption(n[n.length]=`-${e}`)}),{cleanMode:t,options:n,valid:r}}function isCleanMode(e){return"f"===e||"n"===e}function isKnownOption(e){return/^-[a-z]$/i.test(e)&&uE.has(e.charAt(1))}function isInteractiveMode(e){return/^-[^\-]/.test(e)?e.indexOf("i")>0:"--interactive"===e}__export2(oE,{CONFIG_ERROR_INTERACTIVE_MODE:()=>aE,CONFIG_ERROR_MODE_REQUIRED:()=>cE,CONFIG_ERROR_UNKNOWN_OPTION:()=>lE,CleanOptions:()=>dE,cleanTask:()=>cleanTask,cleanWithOptionsTask:()=>cleanWithOptionsTask,isCleanOptionsArray:()=>isCleanOptionsArray});var pE=__esm2({"src/lib/tasks/clean.ts"(){nE(),GS(),iE(),aE="Git clean interactive mode is not supported",cE='Git clean mode parameter ("n" or "f") is required',lE="Git clean unknown option found in: ",dE=(e=>(e.DRY_RUN="n",e.FORCE="f",e.IGNORED_INCLUDED="x",e.IGNORED_ONLY="X",e.EXCLUDING="e",e.QUIET="q",e.RECURSIVE="d",e))(dE||{}),uE=new Set(["i",...asStringArray(Object.values(dE))])}}),hE;function configListParser(e){const t=new hE;for(const n of configParser(e))t.addValue(n.file,String(n.key),n.value);return t}function configGetParser(e,t){let n=null;const r=[],s=new Map;for(const i of configParser(e,t))i.key===t&&(r.push(n=i.value),s.has(i.file)||s.set(i.file,[]),s.get(i.file).push(n));return{key:t,paths:Array.from(s.keys()),scopes:s,value:n,values:r}}function configFilePath(e){return e.replace(/^(file):/,"")}function*configParser(e,t=null){const n=e.split("\0");for(let e=0,r=n.length-1;e<r;){const r=configFilePath(n[e++]);let s=n[e++],i=t;if(s.includes("\n")){const e=splitOn(s,"\n");i=e[0],s=e[1]}yield{file:r,key:i,value:s}}}var mE=__esm2({"src/lib/responses/ConfigList.ts"(){GS(),hE=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){return this._all||(this._all=this.files.reduce((e,t)=>Object.assign(e,this.values[t]),{})),this._all}addFile(e){if(!(e in this.values)){const t=last2(this.files);this.values[e]=t?Object.create(this.values[t]):{},this.files.push(e)}return this.values[e]}addValue(e,t,n){const r=this.addFile(e);Object.hasOwn(r,t)?Array.isArray(r[t])?r[t].push(n):r[t]=[r[t],n]:r[t]=n,this._all=void 0}}}}),fE;function asConfigScope(e,t){return"string"==typeof e&&Object.hasOwn(fE,e)?e:t}function addConfigTask(e,t,n,r){const s=["config",`--${r}`];return n&&s.push("--add"),s.push(e,t),{commands:s,format:"utf-8",parser:e=>e}}function getConfigTask(e,t){const n=["config","--null","--show-origin","--get-all",e];return t&&n.splice(1,0,`--${t}`),{commands:n,format:"utf-8",parser:t=>configGetParser(t,e)}}function listConfigTask(e){const t=["config","--list","--show-origin","--null"];return e&&t.push(`--${e}`),{commands:t,format:"utf-8",parser:e=>configListParser(e)}}function config_default(){return{addConfig(e,t,...n){return this._runTask(addConfigTask(e,t,!0===n[0],asConfigScope(n[1],"local")),trailingFunctionArgument(arguments))},getConfig(e,t){return this._runTask(getConfigTask(e,asConfigScope(t,void 0)),trailingFunctionArgument(arguments))},listConfig(...e){return this._runTask(listConfigTask(asConfigScope(e[0],void 0)),trailingFunctionArgument(arguments))}}}var gE=__esm2({"src/lib/tasks/config.ts"(){mE(),GS(),fE=(e=>(e.system="system",e.global="global",e.local="local",e.worktree="worktree",e))(fE||{})}}),yE,bE;function isDiffNameStatus(e){return bE.has(e)}var vE=__esm2({"src/lib/tasks/diff-name-status.ts"(){yE=(e=>(e.ADDED="A",e.COPIED="C",e.DELETED="D",e.MODIFIED="M",e.RENAMED="R",e.CHANGED="T",e.UNMERGED="U",e.UNKNOWN="X",e.BROKEN="B",e))(yE||{}),bE=new Set(Object.values(yE))}}),wE,_E,xE,TE;function grepQueryBuilder(...e){return(new TE).param(...e)}function parseGrep(e){const t=new Set,n={};return forEachLineWithContent(e,e=>{const[r,s,i]=e.split(kS);t.add(r),(n[r]=n[r]||[]).push({line:asNumber(s),path:r,preview:i})}),{paths:t,results:n}}function grep_default(){return{grep(e){const t=trailingFunctionArgument(arguments),n=getTrailingOptions(arguments);for(const e of wE)if(n.includes(e))return this._runTask(configurationErrorTask(`git.grep: use of "${e}" is not supported.`),t);"string"==typeof e&&(e=grepQueryBuilder().param(e));const r=["grep","--null","-n","--full-name",...n,...e];return this._runTask({commands:r,format:"utf-8",parser:e=>parseGrep(e)},t)}}}var kE=__esm2({"src/lib/tasks/grep.ts"(){GS(),iE(),wE=["-h"],_E=Symbol("grepQuery"),TE=class{constructor(){this[xE]=[]}*[(xE=_E,Symbol.iterator)](){for(const e of this[_E])yield e}and(...e){return e.length&&this[_E].push("--and","(",...prefixedArray(e,"-e"),")"),this}param(...e){return this[_E].push(...prefixedArray(e,"-e")),this}}}}),SE={},EE,AE;function resetTask(e,t){const n=["reset"];return isValidResetMode(e)&&n.push(`--${e}`),n.push(...t),straightThroughStringTask(n)}function getResetMode(e){if(isValidResetMode(e))return e;switch(typeof e){case"string":case"undefined":return"soft"}}function isValidResetMode(e){return"string"==typeof e&&AE.includes(e)}__export2(SE,{ResetMode:()=>EE,getResetMode:()=>getResetMode,resetTask:()=>resetTask});var CE=__esm2({"src/lib/tasks/reset.ts"(){GS(),iE(),EE=(e=>(e.MIXED="mixed",e.SOFT="soft",e.HARD="hard",e.MERGE="merge",e.KEEP="keep",e))(EE||{}),AE=asStringArray(Object.values(EE))}});function createLog(){return(0,iS.default)("simple-git")}function prefixedLogger(e,t,n){return t&&String(t).replace(/\s*/,"")?(r,...s)=>{e(`%s ${r}`,t,...s),n&&n(r,...s)}:n?(t,...r)=>{e(t,...r),n(t,...r)}:e}function childLoggerName(e,t,{namespace:n}){if("string"==typeof e)return e;const r=t&&t.namespace||"";return r.startsWith(n)?r.substr(n.length+1):r||n}function createLogger(e,t,n,r=createLog()){const s=e&&`[${e}]`||"",i=[],o="string"==typeof t?r.extend(t):t,a=childLoggerName(filterType(t,PS),o,r);return step(n);function sibling(t,n){return append(i,createLogger(e,a.replace(/^[^:]+/,t),n,r))}function step(t){const n=t&&`[${t}]`||"",i=o&&prefixedLogger(o,n)||SS,a=prefixedLogger(r,`${s} ${n}`,i);return Object.assign(o?i:a,{label:e,sibling,info:a,step})}}var IE=__esm2({"src/lib/git-logger.ts"(){GS(),iS.default.formatters.L=e=>String(RS(e)?e.length:"-"),iS.default.formatters.B=e=>Buffer.isBuffer(e)?e.toString("utf8"):ES(e)}}),PE,DE=__esm2({"src/lib/runners/tasks-pending-queue.ts"(){vS(),IE(),PE=class _TasksPendingQueue{constructor(e="GitExecutor"){this.logLabel=e,this._queue=new Map}withProgress(e){return this._queue.get(e)}createProgress(e){const t=_TasksPendingQueue.getName(e.commands[0]),n=createLogger(this.logLabel,t);return{task:e,logger:n,name:t}}push(e){const t=this.createProgress(e);return t.logger("Adding task to the queue, commands = %o",e.commands),this._queue.set(e,t),t}fatal(e){for(const[t,{logger:n}]of Array.from(this._queue.entries()))t===e.task?(n.info("Failed %o",e),n("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted")):n.info("A fatal exception occurred in a previous task, the queue has been purged: %o",e.message),this.complete(t);if(0!==this._queue.size)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(e){const t=this.withProgress(e);t&&this._queue.delete(e)}attempt(e){const t=this.withProgress(e);if(!t)throw new bS(void 0,"TasksPendingQueue: attempt called for an unknown task");return t.logger("Starting task"),t}static getName(e="empty"){return`task:${e}:${++_TasksPendingQueue.counter}`}static{this.counter=0}}}}),RE;function pluginContext(e,t){return{method:first2(e.commands)||"",commands:t}}function onErrorReceived(e,t){return n=>{t("[ERROR] child process exception %o",n),e.push(Buffer.from(String(n.stack),"ascii"))}}function onDataReceived(e,t,n,r){return s=>{n("%s received %L bytes",t,s),r("%B",s),e.push(s)}}var NE=__esm2({"src/lib/runners/git-executor-chain.ts"(){vS(),iE(),GS(),DE(),RE=class{constructor(e,t,n){this._executor=e,this._scheduler=t,this._plugins=n,this._chain=Promise.resolve(),this._queue=new PE}get cwd(){return this._cwd||this._executor.cwd}set cwd(e){this._cwd=e}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(e){return this._queue.push(e),this._chain=this._chain.then(()=>this.attemptTask(e))}async attemptTask(e){const t=await this._scheduler.next(),onQueueComplete=()=>this._queue.complete(e);try{const{logger:t}=this._queue.attempt(e);return await(isEmptyTask(e)?this.attemptEmptyTask(e,t):this.attemptRemoteTask(e,t))}catch(t){throw this.onFatalException(e,t)}finally{onQueueComplete(),t()}}onFatalException(e,t){const n=t instanceof bS?Object.assign(t,{task:e}):new bS(e,t&&String(t));return this._chain=Promise.resolve(),this._queue.fatal(n),n}async attemptRemoteTask(e,t){const n=this._plugins.exec("spawn.binary","",pluginContext(e,e.commands)),r=this._plugins.exec("spawn.args",[...e.commands],pluginContext(e,e.commands)),s=await this.gitResponse(e,n,r,this.outputHandler,t.step("SPAWN")),i=await this.handleTaskData(e,r,s,t.step("HANDLE"));return t("passing response to task's parser as a %s",e.format),isBufferTask(e)?callTaskParser(e.parser,i):callTaskParser(e.parser,i.asStrings())}async attemptEmptyTask(e,t){return t("empty task bypassing child process to call to task's parser"),e.parser(this)}handleTaskData(e,t,n,r){const{exitCode:s,rejection:i,stdOut:o,stdErr:a}=n;return new Promise((c,l)=>{r("Preparing to handle process response exitCode=%d stdOut=",s);const{error:d}=this._plugins.exec("task.error",{error:i},{...pluginContext(e,t),...n});return d&&e.onError?(r.info("exitCode=%s handling with custom error handler"),e.onError(n,d,e=>{r.info("custom error handler treated as success"),r("custom error returned a %s",ES(e)),c(new LS(Array.isArray(e)?Buffer.concat(e):e,Buffer.concat(a)))},l)):d?(r.info("handling as error: exitCode=%s stdErr=%s rejection=%o",s,a.length,i),l(d)):(r.info("retrieving task output complete"),void c(new LS(Buffer.concat(o),Buffer.concat(a))))})}async gitResponse(e,t,n,r,s){const i=s.sibling("output"),o=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},pluginContext(e,e.commands));return new Promise(a=>{const c=[],l=[];s.info("%s %o",t,n),s("%O",o);let d=this._beforeSpawn(e,n);if(d)return a({stdOut:c,stdErr:l,exitCode:9901,rejection:d});this._plugins.exec("spawn.before",void 0,{...pluginContext(e,n),kill(e){d=e||d}});const u=lS(t,n,o);u.stdout.on("data",onDataReceived(c,"stdOut",s,i.step("stdOut"))),u.stderr.on("data",onDataReceived(l,"stdErr",s,i.step("stdErr"))),u.on("error",onErrorReceived(l,s)),r&&(s("Passing child process stdOut/stdErr to custom outputHandler"),r(t,u.stdout,u.stderr,[...n])),this._plugins.exec("spawn.after",void 0,{...pluginContext(e,n),spawned:u,close(e,t){a({stdOut:c,stdErr:l,exitCode:e,rejection:d||t})},kill(e){u.killed||(d=e,u.kill("SIGINT"))}})})}_beforeSpawn(e,t){let n;return this._plugins.exec("spawn.before",void 0,{...pluginContext(e,t),kill(e){n=e||n}}),n}}}}),OE={},FE;__export2(OE,{GitExecutor:()=>FE});var LE=__esm2({"src/lib/runners/git-executor.ts"(){NE(),FE=class{constructor(e,t,n){this.cwd=e,this._scheduler=t,this._plugins=n,this._chain=new RE(this,this._scheduler,this._plugins)}chain(){return new RE(this,this._scheduler,this._plugins)}push(e){return this._chain.push(e)}}}});function taskCallback(e,t,n=SS){const onSuccess=e=>{n(null,e)},onError2=t=>{t?.task===e&&n(t instanceof wS?addDeprecationNoticeToError(t):t,void 0)};t.then(onSuccess,onError2)}function addDeprecationNoticeToError(e){let log=e=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${e} should be GitResponseError.git.${e}, this will no longer be available in version 3`),log=SS};return Object.create(e,Object.getOwnPropertyNames(e.git).reduce(descriptorReducer,{}));function descriptorReducer(t,n){return n in e||(t[n]={enumerable:!1,configurable:!1,get:()=>(log(n),e.git[n])}),t}}var ME=__esm2({"src/lib/task-callback.ts"(){_S(),GS()}});function changeWorkingDirectoryTask(e,t){return adhocExecTask(n=>{if(!folderExists(e))throw new Error(`Git.cwd: cannot change to non-directory "${e}"`);return(t||n).cwd=e})}var UE=__esm2({"src/lib/tasks/change-working-directory.ts"(){GS(),iE()}});function checkoutTask(e){const t=["checkout",...e];return"-b"===t[1]&&t.includes("-B")&&(t[1]=remove(t,"-B")),straightThroughStringTask(t)}function checkout_default(){return{checkout(){return this._runTask(checkoutTask(getTrailingOptions(arguments,1)),trailingFunctionArgument(arguments))},checkoutBranch(e,t){return this._runTask(checkoutTask(["-b",e,t,...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments))},checkoutLocalBranch(e){return this._runTask(checkoutTask(["-b",e,...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments))}}}var jE=__esm2({"src/lib/tasks/checkout.ts"(){GS(),iE()}}),BE;function countObjectsResponse(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function count_objects_default(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser:e=>parseStringResponse(countObjectsResponse(),[BE],e)})}}}var $E=__esm2({"src/lib/tasks/count-objects.ts"(){GS(),BE=new US(/([a-z-]+): (\d+)$/,(e,[t,n])=>{const r=asCamelCase(t);Object.hasOwn(e,r)&&(e[r]=asNumber(n))})}}),WE;function parseCommitResult(e){const t={author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}};return parseStringResponse(t,WE,e)}var HE=__esm2({"src/lib/parsers/parse-commit.ts"(){GS(),WE=[new US(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(e,[t,n,r])=>{e.branch=t,e.commit=r,e.root=!!n}),new US(/\s*Author:\s(.+)/i,(e,[t])=>{const n=t.split("<"),r=n.pop();r&&r.includes("@")&&(e.author={email:r.substr(0,r.length-1),name:n.join("<").trim()})}),new US(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0,e.summary.insertions=parseInt(n,10)||0,e.summary.deletions=parseInt(r,10)||0}),new US(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0;const s=parseInt(n,10)||0;"-"===r?e.summary.deletions=s:"+"===r&&(e.summary.insertions=s)})]}});function commitTask(e,t,n){const r=["-c","core.abbrev=40","commit",...prefixedArray(e,"-m"),...t,...n];return{commands:r,format:"utf-8",parser:parseCommitResult}}function commit_default(){return{commit(e,...t){const n=trailingFunctionArgument(arguments),r=rejectDeprecatedSignatures(e)||commitTask(asArray2(e),asArray2(filterType(t[0],DS,[])),[...asStringArray(filterType(t[1],CS,[])),...getTrailingOptions(arguments,0,!0)]);return this._runTask(r,n)}};function rejectDeprecatedSignatures(e){return!DS(e)&&configurationErrorTask("git.commit: requires the commit message to be supplied as a string/string[]")}}var qE=__esm2({"src/lib/tasks/commit.ts"(){HE(),GS(),iE()}});function first_commit_default(){return{firstCommit(){return this._runTask(straightThroughStringTask(["rev-list","--max-parents=0","HEAD"],!0),trailingFunctionArgument(arguments))}}}var zE=__esm2({"src/lib/tasks/first-commit.ts"(){GS(),iE()}});function hashObjectTask(e,t){const n=["hash-object",e];return t&&n.push("-w"),straightThroughStringTask(n,!0)}var GE=__esm2({"src/lib/tasks/hash-object.ts"(){iE()}}),VE,KE,XE;function parseInit(e,t,n){const r=String(n).trim();let s;if(s=KE.exec(r))return new VE(e,t,!1,s[1]);if(s=XE.exec(r))return new VE(e,t,!0,s[1]);let i="";const o=r.split(" ");for(;o.length;){const e=o.shift();if("in"===e){i=o.join(" ");break}}return new VE(e,t,/^re/i.test(r),i)}var YE=__esm2({"src/lib/responses/InitSummary.ts"(){VE=class{constructor(e,t,n,r){this.bare=e,this.path=t,this.existing=n,this.gitDir=r}},KE=/^Init.+ repository in (.+)$/,XE=/^Rein.+ in (.+)$/}}),JE;function hasBareCommand(e){return e.includes(JE)}function initTask(e=!1,t,n){const r=["init",...n];return e&&!hasBareCommand(r)&&r.splice(1,0,JE),{commands:r,format:"utf-8",parser:e=>parseInit(r.includes("--bare"),t,e)}}var QE=__esm2({"src/lib/tasks/init.ts"(){YE(),JE="--bare"}}),ZE;function logFormatFromCommand(e){for(let t=0;t<e.length;t++){const n=ZE.exec(e[t]);if(n)return`--${n[1]}`}return""}function isLogFormat(e){return ZE.test(e)}var eA=__esm2({"src/lib/args/log-format.ts"(){ZE=/^--(stat|numstat|name-only|name-status)(=|$)/}}),tA,nA=__esm2({"src/lib/responses/DiffSummary.ts"(){tA=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}}),rA,sA,iA,oA,aA;function getDiffParser(e=""){const t=aA[e];return e=>parseStringResponse(new tA,t,e,!1)}var cA=__esm2({"src/lib/parsers/parse-diff-summary.ts"(){eA(),nA(),vE(),GS(),rA=[new US(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(e,[t,n,r=""])=>{e.files.push({file:t.trim(),changes:asNumber(n),insertions:r.replace(/[^+]/g,"").length,deletions:r.replace(/[^-]/g,"").length,binary:!1})}),new US(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(e,[t,n,r])=>{e.files.push({file:t.trim(),before:asNumber(n),after:asNumber(r),binary:!0})}),new US(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(e,[t,n])=>{const r=/(\d+) i/.exec(n),s=/(\d+) d/.exec(n);e.changed=asNumber(t),e.insertions=asNumber(r?.[1]),e.deletions=asNumber(s?.[1])})],sA=[new US(/(\d+)\t(\d+)\t(.+)$/,(e,[t,n,r])=>{const s=asNumber(t),i=asNumber(n);e.changed++,e.insertions+=s,e.deletions+=i,e.files.push({file:r,changes:s+i,insertions:s,deletions:i,binary:!1})}),new US(/-\t-\t(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,after:0,before:0,binary:!0})})],iA=[new US(/(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,changes:0,insertions:0,deletions:0,binary:!1})})],oA=[new US(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(e,[t,n,r,s,i])=>{e.changed++,e.files.push({file:i??r,changes:0,insertions:0,deletions:0,binary:!1,status:orVoid(isDiffNameStatus(t)&&t),from:orVoid(!!i&&r!==i&&r),similarity:asNumber(n)})})],aA={"":rA,"--stat":rA,"--numstat":sA,"--name-status":oA,"--name-only":iA}}}),lA,dA,uA,pA;function lineBuilder(e,t){return t.reduce((t,n,r)=>(t[n]=e[r]||"",t),Object.create({diff:null}))}function createListLogSummaryParser(e=uA,t=pA,n=""){const r=getDiffParser(n);return function(n){const s=toLinesWithContent(n.trim(),!1,lA).map(function(n){const s=n.split(dA),i=lineBuilder(s[0].split(e),t);return s.length>1&&s[1].trim()&&(i.diff=r(s[1])),i});return{all:s,latest:s.length&&s[0]||null,total:s.length}}}var hA=__esm2({"src/lib/parsers/parse-list-log-summary.ts"(){GS(),cA(),eA(),lA="òòòòòò ",dA=" òò",uA=" ò ",pA=["hash","date","message","refs","author_name","author_email"]}}),mA={};function diffSummaryTask(e){let t=logFormatFromCommand(e);const n=["diff"];return""===t&&(t="--stat",n.push("--stat=4096")),n.push(...e),validateLogFormatConfig(n)||{commands:n,format:"utf-8",parser:getDiffParser(t)}}function validateLogFormatConfig(e){const t=e.filter(isLogFormat);return t.length>1?configurationErrorTask(`Summary flags are mutually exclusive - pick one of ${t.join(",")}`):t.length&&e.includes("-z")?configurationErrorTask(`Summary flag ${t} parsing is not compatible with null termination option '-z'`):void 0}__export2(mA,{diffSummaryTask:()=>diffSummaryTask,validateLogFormatConfig:()=>validateLogFormatConfig});var fA=__esm2({"src/lib/tasks/diff.ts"(){eA(),cA(),iE()}}),gA;function prettyFormat(e,t){const n=[],r=[];return Object.keys(e).forEach(t=>{n.push(t),r.push(String(e[t]))}),[n,r.join(t)]}function userOptions(e){return Object.keys(e).reduce((t,n)=>(n in gA||(t[n]=e[n]),t),{})}function parseLogOptions(e={},t=[]){const n=filterType(e.splitter,PS,uA),r=filterPlainObject(e.format)?e.format:{hash:"%H",date:!1===e.strictDate?"%ai":"%aI",message:"%s",refs:"%D",body:e.multiLine?"%B":"%b",author_name:!1!==e.mailMap?"%aN":"%an",author_email:!1!==e.mailMap?"%aE":"%ae"},[s,i]=prettyFormat(r,n),o=[],a=[`--pretty=format:${lA}${i}${dA}`,...t],c=e.n||e["max-count"]||e.maxCount;if(c&&a.push(`--max-count=${c}`),e.from||e.to){const t=!1!==e.symmetric?"...":"..";o.push(`${e.from||""}${t}${e.to||""}`)}return PS(e.file)&&a.push("--follow",pathspec(e.file)),appendTaskOptions(userOptions(e),a),{fields:s,splitter:n,commands:[...a,...o]}}function logTask(e,t,n){const r=createListLogSummaryParser(e,t,logFormatFromCommand(n));return{commands:["log",...n],format:"utf-8",parser:r}}function log_default(){return{log(...e){const t=trailingFunctionArgument(arguments),n=parseLogOptions(trailingOptionsArgument(arguments),asStringArray(filterType(arguments[0],CS,[]))),r=rejectDeprecatedSignatures(...e)||validateLogFormatConfig(n.commands)||createLogTask(n);return this._runTask(r,t)}};function createLogTask(e){return logTask(e.splitter,e.fields,e.commands)}function rejectDeprecatedSignatures(e,t){return PS(e)&&PS(t)&&configurationErrorTask("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var yA=__esm2({"src/lib/tasks/log.ts"(){eA(),yS(),hA(),GS(),iE(),fA(),gA=(e=>(e[e["--pretty"]=0]="--pretty",e[e["max-count"]=1]="max-count",e[e.maxCount=2]="maxCount",e[e.n=3]="n",e[e.file=4]="file",e[e.format=5]="format",e[e.from=6]="from",e[e.to=7]="to",e[e.splitter=8]="splitter",e[e.symmetric=9]="symmetric",e[e.mailMap=10]="mailMap",e[e.multiLine=11]="multiLine",e[e.strictDate=12]="strictDate",e))(gA||{})}}),bA,vA,wA=__esm2({"src/lib/responses/MergeSummary.ts"(){bA=class{constructor(e,t=null,n){this.reason=e,this.file=t,this.meta=n}toString(){return`${this.file}:${this.reason}`}},vA=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(", ")}`:"OK"}}}}),_A,xA,TA=__esm2({"src/lib/responses/PullSummary.ts"(){_A=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},xA=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}}),kA;function objectEnumerationResult(e){return e.objects=e.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function asObjectCount(e){const t=/^\s*(\d+)/.exec(e),n=/delta (\d+)/i.exec(e);return{count:asNumber(t&&t[1]||"0"),delta:asNumber(n&&n[1]||"0")}}var SA=__esm2({"src/lib/parsers/parse-remote-objects.ts"(){GS(),kA=[new jS(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(e,[t,n])=>{const r=t.toLowerCase(),s=objectEnumerationResult(e.remoteMessages);Object.assign(s,{[r]:asNumber(n)})}),new jS(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(e,[t,n])=>{const r=t.toLowerCase(),s=objectEnumerationResult(e.remoteMessages);Object.assign(s,{[r]:asNumber(n)})}),new jS(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(e,[t,n,r])=>{const s=objectEnumerationResult(e.remoteMessages);s.total=asObjectCount(t),s.reused=asObjectCount(n),s.packReused=asNumber(r)})]}}),EA,AA;function parseRemoteMessages(e,t){return parseStringResponse({remoteMessages:new AA},EA,t)}var CA=__esm2({"src/lib/parsers/parse-remote-messages.ts"(){GS(),SA(),EA=[new jS(/^remote:\s*(.+)$/,(e,[t])=>(e.remoteMessages.all.push(t.trim()),!1)),...kA,new jS([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(e,[t])=>{e.remoteMessages.pullRequestUrl=t}),new jS([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(e,[t,n,r])=>{e.remoteMessages.vulnerabilities={count:asNumber(t),summary:n,url:r}})],AA=class{constructor(){this.all=[]}}}}),IA,PA,DA,RA,NA,OA,FA;function parsePullErrorResult(e,t){const n=parseStringResponse(new xA,NA,[e,t]);return n.message&&n}var LA=__esm2({"src/lib/parsers/parse-pull.ts"(){TA(),GS(),CA(),IA=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,PA=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,DA=/^(create|delete) mode \d+ (.+)/,RA=[new US(IA,(e,[t,n,r])=>{e.files.push(t),n&&(e.insertions[t]=n.length),r&&(e.deletions[t]=r.length)}),new US(PA,(e,[t,,n,,r])=>(void 0!==n||void 0!==r)&&(e.summary.changes=+t||0,e.summary.insertions=+n||0,e.summary.deletions=+r||0,!0)),new US(DA,(e,[t,n])=>{append(e.files,n),append("create"===t?e.created:e.deleted,n)})],NA=[new US(/^from\s(.+)$/i,(e,[t])=>{e.remote=t}),new US(/^fatal:\s(.+)$/,(e,[t])=>{e.message=t}),new US(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(e,[t,n,r,s])=>{e.branch.local=r,e.hash.local=t,e.branch.remote=s,e.hash.remote=n})],OA=(e,t)=>parseStringResponse(new _A,RA,[e,t]),FA=(e,t)=>Object.assign(new _A,OA(e,t),parseRemoteMessages(e,t))}}),MA,UA,jA,BA=__esm2({"src/lib/parsers/parse-merge.ts"(){wA(),GS(),LA(),MA=[new US(/^Auto-merging\s+(.+)$/,(e,[t])=>{e.merges.push(t)}),new US(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(e,[t,n])=>{e.conflicts.push(new bA(t,n))}),new US(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(e,[t,n,r])=>{e.conflicts.push(new bA(t,n,{deleteRef:r}))}),new US(/^CONFLICT\s+\((.+)\):/,(e,[t])=>{e.conflicts.push(new bA(t,null))}),new US(/^Automatic merge failed;\s+(.+)$/,(e,[t])=>{e.result=t})],UA=(e,t)=>Object.assign(jA(e,t),FA(e,t)),jA=e=>parseStringResponse(new vA,MA,e)}});function mergeTask(e){return e.length?{commands:["merge",...e],format:"utf-8",parser(e,t){const n=UA(e,t);if(n.failed)throw new wS(n);return n}}:configurationErrorTask("Git.merge requires at least one option")}var $A=__esm2({"src/lib/tasks/merge.ts"(){_S(),BA(),iE()}}),WA,HA,qA;function pushResultPushedItem(e,t,n){const r=n.includes("deleted"),s=n.includes("tag")||/^refs\/tags/.test(e),i=!n.includes("new");return{deleted:r,tag:s,branch:!s,new:!i,alreadyUpdated:i,local:e,remote:t}}var zA=__esm2({"src/lib/parsers/parse-push.ts"(){GS(),CA(),WA=[new US(/^Pushing to (.+)$/,(e,[t])=>{e.repo=t}),new US(/^updating local tracking ref '(.+)'/,(e,[t])=>{e.ref={...e.ref||{},local:t}}),new US(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(e,[t,n,r])=>{e.pushed.push(pushResultPushedItem(t,n,r))}),new US(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(e,[t,n,r])=>{e.branch={...e.branch||{},local:t,remote:n,remoteName:r}}),new US(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(e,[t,n,r,s])=>{e.update={head:{local:t,remote:n},hash:{from:r,to:s}}})],HA=(e,t)=>{const n=qA(e,t),r=parseRemoteMessages(e,t);return{...n,...r}},qA=(e,t)=>parseStringResponse({pushed:[]},WA,[e,t])}}),GA={};function pushTagsTask(e={},t){return append(t,"--tags"),pushTask(e,t)}function pushTask(e={},t){const n=["push",...t];return e.branch&&n.splice(1,0,e.branch),e.remote&&n.splice(1,0,e.remote),remove(n,"-v"),append(n,"--verbose"),append(n,"--porcelain"),{commands:n,format:"utf-8",parser:HA}}__export2(GA,{pushTagsTask:()=>pushTagsTask,pushTask:()=>pushTask});var VA=__esm2({"src/lib/tasks/push.ts"(){zA(),GS()}});function show_default(){return{showBuffer(){const e=["show",...getTrailingOptions(arguments,1)];return e.includes("--binary")||e.splice(1,0,"--binary"),this._runTask(straightThroughBufferTask(e),trailingFunctionArgument(arguments))},show(){const e=["show",...getTrailingOptions(arguments,1)];return this._runTask(straightThroughStringTask(e),trailingFunctionArgument(arguments))}}}var KA=__esm2({"src/lib/tasks/show.ts"(){GS(),iE()}}),XA,YA,JA=__esm2({"src/lib/responses/FileStatusSummary.ts"(){XA=/^(.+)\0(.+)$/,YA=class{constructor(e,t,n){if(this.path=e,this.index=t,this.working_dir=n,"R"===t||"R"===n){const t=XA.exec(e)||[null,e,e];this.from=t[2]||"",this.path=t[1]||""}}}}}),QA,ZA,eC;function renamedFile(e){const[t,n]=e.split(kS);return{from:n||t,to:t}}function parser3(e,t,n){return[`${e}${t}`,n]}function conflicts(e,...t){return t.map(t=>parser3(e,t,(e,t)=>e.conflicted.push(t)))}function splitLine(e,t){const n=t.trim();switch(" "){case n.charAt(2):return data(n.charAt(0),n.charAt(1),n.slice(3));case n.charAt(1):return data(" ",n.charAt(0),n.slice(2));default:return}function data(t,n,r){const s=`${t}${n}`,i=ZA.get(s);i&&i(e,r),"##"!==s&&"!!"!==s&&e.files.push(new YA(r,t,n))}}var tC=__esm2({"src/lib/responses/StatusSummary.ts"(){GS(),JA(),QA=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},ZA=new Map([parser3(" ","A",(e,t)=>e.created.push(t)),parser3(" ","D",(e,t)=>e.deleted.push(t)),parser3(" ","M",(e,t)=>e.modified.push(t)),parser3("A"," ",(e,t)=>{e.created.push(t),e.staged.push(t)}),parser3("A","M",(e,t)=>{e.created.push(t),e.staged.push(t),e.modified.push(t)}),parser3("D"," ",(e,t)=>{e.deleted.push(t),e.staged.push(t)}),parser3("M"," ",(e,t)=>{e.modified.push(t),e.staged.push(t)}),parser3("M","M",(e,t)=>{e.modified.push(t),e.staged.push(t)}),parser3("R"," ",(e,t)=>{e.renamed.push(renamedFile(t))}),parser3("R","M",(e,t)=>{const n=renamedFile(t);e.renamed.push(n),e.modified.push(n.to)}),parser3("!","!",(e,t)=>{(e.ignored=e.ignored||[]).push(t)}),parser3("?","?",(e,t)=>e.not_added.push(t)),...conflicts("A","A","U"),...conflicts("D","D","U"),...conflicts("U","A","D","U"),["##",(e,t)=>{const n=/ahead (\d+)/,r=/behind (\d+)/,s=/^(.+?(?=(?:\.{3}|\s|$)))/,i=/\.{3}(\S*)/,o=/\son\s(\S+?)(?=\.{3}|$)/;let a=n.exec(t);e.ahead=a&&+a[1]||0,a=r.exec(t),e.behind=a&&+a[1]||0,a=s.exec(t),e.current=filterType(a?.[1],PS,null),a=i.exec(t),e.tracking=filterType(a?.[1],PS,null),a=o.exec(t),a&&(e.current=filterType(a?.[1],PS,e.current)),e.detached=/\(no branch\)/.test(t)}]]),eC=function(e){const t=e.split(kS),n=new QA;for(let e=0,r=t.length;e<r;){let r=t[e++].trim();r&&("R"===r.charAt(0)&&(r+=kS+(t[e++]||"")),splitLine(n,r))}return n}}}),nC;function statusTask(e){const t=["status","--porcelain","-b","-u","--null",...e.filter(e=>!nC.includes(e))];return{format:"utf-8",commands:t,parser:e=>eC(e)}}var rC=__esm2({"src/lib/tasks/status.ts"(){tC(),nC=["--null","-z"]}}),sC,iC;function versionResponse(e=0,t=0,n=0,r="",s=!0){return Object.defineProperty({major:e,minor:t,patch:n,agent:r,installed:s},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function notInstalledResponse(){return versionResponse(0,0,0,"",!1)}function version_default(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:versionParser,onError(e,t,n,r){if(-2===e.exitCode)return n(Buffer.from(sC));r(t)}})}}}function versionParser(e){return e===sC?notInstalledResponse():parseStringResponse(versionResponse(0,0,0,e),iC,e)}var oC=__esm2({"src/lib/tasks/version.ts"(){GS(),sC="installed=false",iC=[new US(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(e,[t,n,r,s=""])=>{Object.assign(e,versionResponse(asNumber(t),asNumber(n),asNumber(r),s))}),new US(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(e,[t,n,r,s=""])=>{Object.assign(e,versionResponse(asNumber(t),asNumber(n),r,s))})]}}),aC={},cC;__export2(aC,{SimpleGitApi:()=>cC});var lC=__esm2({"src/lib/simple-git-api.ts"(){ME(),UE(),jE(),$E(),qE(),gE(),zE(),kE(),GE(),QE(),yA(),$A(),VA(),KA(),rC(),iE(),oC(),GS(),cC=class{constructor(e){this._executor=e}_runTask(e,t){const n=this._executor.chain(),r=n.push(e);return t&&taskCallback(e,r,t),Object.create(this,{then:{value:r.then.bind(r)},catch:{value:r.catch.bind(r)},_executor:{value:n}})}add(e){return this._runTask(straightThroughStringTask(["add",...asArray2(e)]),trailingFunctionArgument(arguments))}cwd(e){const t=trailingFunctionArgument(arguments);return"string"==typeof e?this._runTask(changeWorkingDirectoryTask(e,this._executor),t):"string"==typeof e?.path?this._runTask(changeWorkingDirectoryTask(e.path,e.root&&this._executor||void 0),t):this._runTask(configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"),t)}hashObject(e,t){return this._runTask(hashObjectTask(e,!0===t),trailingFunctionArgument(arguments))}init(e){return this._runTask(initTask(!0===e,this._executor.cwd,getTrailingOptions(arguments)),trailingFunctionArgument(arguments))}merge(){return this._runTask(mergeTask(getTrailingOptions(arguments)),trailingFunctionArgument(arguments))}mergeFromTo(e,t){return PS(e)&&PS(t)?this._runTask(mergeTask([e,t,...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments,!1)):this._runTask(configurationErrorTask("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"))}outputHandler(e){return this._executor.outputHandler=e,this}push(){const e=pushTask({remote:filterType(arguments[0],PS),branch:filterType(arguments[1],PS)},getTrailingOptions(arguments));return this._runTask(e,trailingFunctionArgument(arguments))}stash(){return this._runTask(straightThroughStringTask(["stash",...getTrailingOptions(arguments)]),trailingFunctionArgument(arguments))}status(){return this._runTask(statusTask(getTrailingOptions(arguments)),trailingFunctionArgument(arguments))}},Object.assign(cC.prototype,checkout_default(),commit_default(),config_default(),count_objects_default(),first_commit_default(),grep_default(),log_default(),show_default(),version_default())}}),dC={},uC,pC;__export2(dC,{Scheduler:()=>pC});var hC=__esm2({"src/lib/runners/scheduler.ts"(){GS(),IE(),uC=(()=>{let e=0;return()=>{e++;const{promise:t,done:n}=(0,oS.createDeferred)();return{promise:t,done:n,id:e}}})(),pC=class{constructor(e=2){this.concurrency=e,this.logger=createLogger("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",e)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency)return void this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);const e=append(this.running,this.pending.shift());this.logger("Attempting id=%s",e.id),e.done(()=>{this.logger("Completing id=",e.id),remove(this.running,e),this.schedule()})}next(){const{promise:e,id:t}=append(this.pending,uC());return this.logger("Scheduling id=%s",t),this.schedule(),e}}}}),mC={};function applyPatchTask(e,t){return straightThroughStringTask(["apply",...t,...e])}__export2(mC,{applyPatchTask:()=>applyPatchTask});var fC=__esm2({"src/lib/tasks/apply-patch.ts"(){iE()}}),gC;function branchDeletionSuccess(e,t){return{branch:e,hash:t,success:!0}}function branchDeletionFailure(e){return{branch:e,hash:null,success:!1}}var yC=__esm2({"src/lib/responses/BranchDeleteSummary.ts"(){gC=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}}),bC,vC,wC,_C;function hasBranchDeletionError(e,t){return 1===t&&vC.test(e)}var xC=__esm2({"src/lib/parsers/parse-branch-delete.ts"(){yC(),GS(),bC=/(\S+)\s+\(\S+\s([^)]+)\)/,vC=/^error[^']+'([^']+)'/m,wC=[new US(bC,(e,[t,n])=>{const r=branchDeletionSuccess(t,n);e.all.push(r),e.branches[t]=r}),new US(vC,(e,[t])=>{const n=branchDeletionFailure(t);e.errors.push(n),e.all.push(n),e.branches[t]=n})],_C=(e,t)=>parseStringResponse(new gC,wC,[e,t])}}),TC,kC=__esm2({"src/lib/responses/BranchSummary.ts"(){TC=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(e,t,n,r,s){"*"===e&&(this.detached=t,this.current=n),this.all.push(n),this.branches[n]={current:"*"===e,linkedWorkTree:"+"===e,name:n,commit:r,label:s}}}}}),SC,EC;function branchStatus(e){return e?e.charAt(0):""}function parseBranchSummary(e,t=!1){return parseStringResponse(new TC,t?[EC]:SC,e)}var AC=__esm2({"src/lib/parsers/parse-branch.ts"(){kC(),GS(),SC=[new US(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(e,[t,n,r,s])=>{e.push(branchStatus(t),!0,n,r,s)}),new US(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(e,[t,n,r,s])=>{e.push(branchStatus(t),!1,n,r,s)})],EC=new US(/^(\S+)$/s,(e,[t])=>{e.push("*",!1,t,"","")})}}),CC={};function containsDeleteBranchCommand(e){const t=["-d","-D","--delete"];return e.some(e=>t.includes(e))}function branchTask(e){const t=containsDeleteBranchCommand(e),n=e.includes("--show-current"),r=["branch",...e];return 1===r.length&&r.push("-a"),r.includes("-v")||r.splice(1,0,"-v"),{format:"utf-8",commands:r,parser:(e,r)=>t?_C(e,r).all[0]:parseBranchSummary(e,n)}}function branchLocalTask(){return{format:"utf-8",commands:["branch","-v"],parser:e=>parseBranchSummary(e)}}function deleteBranchesTask(e,t=!1){return{format:"utf-8",commands:["branch","-v",t?"-D":"-d",...e],parser:(e,t)=>_C(e,t),onError({exitCode:e,stdOut:t},n,r,s){if(!hasBranchDeletionError(String(n),e))return s(n);r(t)}}}function deleteBranchTask(e,t=!1){const n={format:"utf-8",commands:["branch","-v",t?"-D":"-d",e],parser:(t,n)=>_C(t,n).branches[e],onError({exitCode:e,stdErr:t,stdOut:r},s,i,o){if(!hasBranchDeletionError(String(s),e))return o(s);throw new wS(n.parser(bufferToString(r),bufferToString(t)),String(s))}};return n}__export2(CC,{branchLocalTask:()=>branchLocalTask,branchTask:()=>branchTask,containsDeleteBranchCommand:()=>containsDeleteBranchCommand,deleteBranchTask:()=>deleteBranchTask,deleteBranchesTask:()=>deleteBranchesTask});var IC=__esm2({"src/lib/tasks/branch.ts"(){_S(),xC(),AC(),GS()}}),PC;function toPath3(e){const t=e.trim().replace(/^["']|["']$/g,"");return t&&dS(t)}var DC=__esm2({"src/lib/responses/CheckIgnore.ts"(){PC=e=>e.split(/\n/g).map(toPath3).filter(Boolean)}}),RC={};function checkIgnoreTask(e){return{commands:["check-ignore",...e],format:"utf-8",parser:PC}}__export2(RC,{checkIgnoreTask:()=>checkIgnoreTask});var NC=__esm2({"src/lib/tasks/check-ignore.ts"(){DC()}}),OC={};function disallowedCommand(e){return/^--upload-pack(=|$)/.test(e)}function cloneTask(e,t,n){const r=["clone",...n];PS(e)&&r.push(e),PS(t)&&r.push(t);const s=r.find(disallowedCommand);return s?configurationErrorTask("git.fetch: potential exploit argument blocked."):straightThroughStringTask(r)}function cloneMirrorTask(e,t,n){return append(n,"--mirror"),cloneTask(e,t,n)}__export2(OC,{cloneMirrorTask:()=>cloneMirrorTask,cloneTask:()=>cloneTask});var FC=__esm2({"src/lib/tasks/clone.ts"(){iE(),GS()}}),LC;function parseFetchResult(e,t){const n={raw:e,remote:null,branches:[],tags:[],updated:[],deleted:[]};return parseStringResponse(n,LC,[e,t])}var MC=__esm2({"src/lib/parsers/parse-fetch.ts"(){GS(),LC=[new US(/From (.+)$/,(e,[t])=>{e.remote=t}),new US(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.branches.push({name:t,tracking:n})}),new US(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.tags.push({name:t,tracking:n})}),new US(/- \[deleted]\s+\S+\s*-> (.+)$/,(e,[t])=>{e.deleted.push({tracking:t})}),new US(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(e,[t,n,r,s])=>{e.updated.push({name:r,tracking:s,to:n,from:t})})]}}),UC={};function disallowedCommand2(e){return/^--upload-pack(=|$)/.test(e)}function fetchTask(e,t,n){const r=["fetch",...n];e&&t&&r.push(e,t);const s=r.find(disallowedCommand2);return s?configurationErrorTask("git.fetch: potential exploit argument blocked."):{commands:r,format:"utf-8",parser:parseFetchResult}}__export2(UC,{fetchTask:()=>fetchTask});var jC=__esm2({"src/lib/tasks/fetch.ts"(){MC(),iE()}}),BC;function parseMoveResult(e){return parseStringResponse({moves:[]},BC,e)}var $C=__esm2({"src/lib/parsers/parse-move.ts"(){GS(),BC=[new US(/^Renaming (.+) to (.+)$/,(e,[t,n])=>{e.moves.push({from:t,to:n})})]}}),WC={};function moveTask(e,t){return{commands:["mv","-v",...asArray2(e),t],format:"utf-8",parser:parseMoveResult}}__export2(WC,{moveTask:()=>moveTask});var HC=__esm2({"src/lib/tasks/move.ts"(){$C(),GS()}}),qC={};function pullTask(e,t,n){const r=["pull",...n];return e&&t&&r.splice(1,0,e,t),{commands:r,format:"utf-8",parser:(e,t)=>FA(e,t),onError(e,t,n,r){const s=parsePullErrorResult(bufferToString(e.stdOut),bufferToString(e.stdErr));if(s)return r(new wS(s));r(t)}}}__export2(qC,{pullTask:()=>pullTask});var zC=__esm2({"src/lib/tasks/pull.ts"(){_S(),LA(),GS()}});function parseGetRemotes(e){const t={};return forEach(e,([e])=>t[e]={name:e}),Object.values(t)}function parseGetRemotesVerbose(e){const t={};return forEach(e,([e,n,r])=>{Object.hasOwn(t,e)||(t[e]={name:e,refs:{fetch:"",push:""}}),r&&n&&(t[e].refs[r.replace(/[^a-z]/g,"")]=n)}),Object.values(t)}function forEach(e,t){forEachLineWithContent(e,e=>t(e.split(/\s+/)))}var GC=__esm2({"src/lib/responses/GetRemoteSummary.ts"(){GS()}}),VC={};function addRemoteTask(e,t,n){return straightThroughStringTask(["remote","add",...n,e,t])}function getRemotesTask(e){const t=["remote"];return e&&t.push("-v"),{commands:t,format:"utf-8",parser:e?parseGetRemotesVerbose:parseGetRemotes}}function listRemotesTask(e){const t=[...e];return"ls-remote"!==t[0]&&t.unshift("ls-remote"),straightThroughStringTask(t)}function remoteTask(e){const t=[...e];return"remote"!==t[0]&&t.unshift("remote"),straightThroughStringTask(t)}function removeRemoteTask(e){return straightThroughStringTask(["remote","remove",e])}__export2(VC,{addRemoteTask:()=>addRemoteTask,getRemotesTask:()=>getRemotesTask,listRemotesTask:()=>listRemotesTask,remoteTask:()=>remoteTask,removeRemoteTask:()=>removeRemoteTask});var KC=__esm2({"src/lib/tasks/remote.ts"(){GC(),iE()}}),XC={};function stashListTask(e={},t){const n=parseLogOptions(e),r=["stash","list",...n.commands,...t],s=createListLogSummaryParser(n.splitter,n.fields,logFormatFromCommand(r));return validateLogFormatConfig(r)||{commands:r,format:"utf-8",parser:s}}__export2(XC,{stashListTask:()=>stashListTask});var YC=__esm2({"src/lib/tasks/stash-list.ts"(){eA(),hA(),fA(),yA()}}),JC={};function addSubModuleTask(e,t){return subModuleTask(["add",e,t])}function initSubModuleTask(e){return subModuleTask(["init",...e])}function subModuleTask(e){const t=[...e];return"submodule"!==t[0]&&t.unshift("submodule"),straightThroughStringTask(t)}function updateSubModuleTask(e){return subModuleTask(["update",...e])}__export2(JC,{addSubModuleTask:()=>addSubModuleTask,initSubModuleTask:()=>initSubModuleTask,subModuleTask:()=>subModuleTask,updateSubModuleTask:()=>updateSubModuleTask});var QC=__esm2({"src/lib/tasks/sub-module.ts"(){iE()}}),ZC,eI;function singleSorted(e,t){const n=Number.isNaN(e),r=Number.isNaN(t);return n!==r?n?1:-1:n?sorted(e,t):0}function sorted(e,t){return e===t?0:e>t?1:-1}function trimmed(e){return e.trim()}function toNumber(e){return"string"==typeof e&&parseInt(e.replace(/^\D+/g,""),10)||0}var tI=__esm2({"src/lib/responses/TagList.ts"(){ZC=class{constructor(e,t){this.all=e,this.latest=t}},eI=function(e,t=!1){const n=e.split("\n").map(trimmed).filter(Boolean);t||n.sort(function(e,t){const n=e.split("."),r=t.split(".");if(1===n.length||1===r.length)return singleSorted(toNumber(n[0]),toNumber(r[0]));for(let e=0,t=Math.max(n.length,r.length);e<t;e++){const t=sorted(toNumber(n[e]),toNumber(r[e]));if(t)return t}return 0});const r=t?n[0]:[...n].reverse().find(e=>e.indexOf(".")>=0);return new ZC(n,r)}}}),nI={};function tagListTask(e=[]){const t=e.some(e=>/^--sort=/.test(e));return{format:"utf-8",commands:["tag","-l",...e],parser:e=>eI(e,t)}}function addTagTask(e){return{format:"utf-8",commands:["tag",e],parser:()=>({name:e})}}function addAnnotatedTagTask(e,t){return{format:"utf-8",commands:["tag","-a","-m",t,e],parser:()=>({name:e})}}__export2(nI,{addAnnotatedTagTask:()=>addAnnotatedTagTask,addTagTask:()=>addTagTask,tagListTask:()=>tagListTask});var rI=__esm2({"src/lib/tasks/tag.ts"(){tI()}}),sI=__commonJS2({"src/git.js"(e,t){var{GitExecutor:n}=(LE(),__toCommonJS2(OE)),{SimpleGitApi:r}=(lC(),__toCommonJS2(aC)),{Scheduler:s}=(hC(),__toCommonJS2(dC)),{adhocExecTask:i,configurationErrorTask:o}=(iE(),__toCommonJS2(rE)),{asArray:a,filterArray:c,filterPrimitives:l,filterString:d,filterStringOrStringArray:u,filterType:p,getTrailingOptions:m,trailingFunctionArgument:f,trailingOptionsArgument:g}=(GS(),__toCommonJS2(zS)),{applyPatchTask:y}=(fC(),__toCommonJS2(mC)),{branchTask:b,branchLocalTask:v,deleteBranchesTask:w,deleteBranchTask:x}=(IC(),__toCommonJS2(CC)),{checkIgnoreTask:S}=(NC(),__toCommonJS2(RC)),{checkIsRepoTask:E}=(JS(),__toCommonJS2(VS)),{cloneTask:A,cloneMirrorTask:C}=(FC(),__toCommonJS2(OC)),{cleanWithOptionsTask:I,isCleanOptionsArray:P}=(pE(),__toCommonJS2(oE)),{diffSummaryTask:R}=(fA(),__toCommonJS2(mA)),{fetchTask:N}=(jC(),__toCommonJS2(UC)),{moveTask:O}=(HC(),__toCommonJS2(WC)),{pullTask:F}=(zC(),__toCommonJS2(qC)),{pushTagsTask:L}=(VA(),__toCommonJS2(GA)),{addRemoteTask:M,getRemotesTask:U,listRemotesTask:j,remoteTask:B,removeRemoteTask:$}=(KC(),__toCommonJS2(VC)),{getResetMode:W,resetTask:H}=(CE(),__toCommonJS2(SE)),{stashListTask:q}=(YC(),__toCommonJS2(XC)),{addSubModuleTask:z,initSubModuleTask:G,subModuleTask:V,updateSubModuleTask:K}=(QC(),__toCommonJS2(JC)),{addAnnotatedTagTask:X,addTagTask:Y,tagListTask:J}=(rI(),__toCommonJS2(nI)),{straightThroughBufferTask:Q,straightThroughStringTask:Z}=(iE(),__toCommonJS2(rE));function Git2(e,t){this._plugins=t,this._executor=new n(e.baseDir,new s(e.maxConcurrentProcesses),t),this._trimmed=e.trimmed}function createCloneTask(e,t,n,r){return"string"!=typeof n?o(`git.${e}() requires a string 'repoPath'`):t(n,p(r,d),m(arguments))}(Git2.prototype=Object.create(r.prototype)).constructor=Git2,Git2.prototype.customBinary=function(e){return this._plugins.reconfigure("binary",e),this},Git2.prototype.env=function(e,t){return 1===arguments.length&&"object"==typeof e?this._executor.env=e:(this._executor.env=this._executor.env||{})[e]=t,this},Git2.prototype.stashList=function(e){return this._runTask(q(g(arguments)||{},c(e)&&e||[]),f(arguments))},Git2.prototype.clone=function(){return this._runTask(createCloneTask("clone",A,...arguments),f(arguments))},Git2.prototype.mirror=function(){return this._runTask(createCloneTask("mirror",C,...arguments),f(arguments))},Git2.prototype.mv=function(e,t){return this._runTask(O(e,t),f(arguments))},Git2.prototype.checkoutLatestTag=function(e){var t=this;return this.pull(function(){t.tags(function(n,r){t.checkout(r.latest,e)})})},Git2.prototype.pull=function(e,t,n,r){return this._runTask(F(p(e,d),p(t,d),m(arguments)),f(arguments))},Git2.prototype.fetch=function(e,t){return this._runTask(N(p(e,d),p(t,d),m(arguments)),f(arguments))},Git2.prototype.silent=function(e){return this._runTask(i(()=>console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this method will be removed.")))},Git2.prototype.tags=function(e,t){return this._runTask(J(m(arguments)),f(arguments))},Git2.prototype.rebase=function(){return this._runTask(Z(["rebase",...m(arguments)]),f(arguments))},Git2.prototype.reset=function(e){return this._runTask(H(W(e),m(arguments)),f(arguments))},Git2.prototype.revert=function(e){const t=f(arguments);return"string"!=typeof e?this._runTask(o("Commit must be a string"),t):this._runTask(Z(["revert",...m(arguments,0,!0),e]),t)},Git2.prototype.addTag=function(e){const t="string"==typeof e?Y(e):o("Git.addTag requires a tag name");return this._runTask(t,f(arguments))},Git2.prototype.addAnnotatedTag=function(e,t){return this._runTask(X(e,t),f(arguments))},Git2.prototype.deleteLocalBranch=function(e,t,n){return this._runTask(x(e,"boolean"==typeof t&&t),f(arguments))},Git2.prototype.deleteLocalBranches=function(e,t,n){return this._runTask(w(e,"boolean"==typeof t&&t),f(arguments))},Git2.prototype.branch=function(e,t){return this._runTask(b(m(arguments)),f(arguments))},Git2.prototype.branchLocal=function(e){return this._runTask(v(),f(arguments))},Git2.prototype.raw=function(e){const t=!Array.isArray(e),n=[].slice.call(t?arguments:e,0);for(let e=0;e<n.length&&t;e++)if(!l(n[e])){n.splice(e,n.length-e);break}n.push(...m(arguments,0,!0));var r=f(arguments);return n.length?this._runTask(Z(n,this._trimmed),r):this._runTask(o("Raw: must supply one or more command to execute"),r)},Git2.prototype.submoduleAdd=function(e,t,n){return this._runTask(z(e,t),f(arguments))},Git2.prototype.submoduleUpdate=function(e,t){return this._runTask(K(m(arguments,!0)),f(arguments))},Git2.prototype.submoduleInit=function(e,t){return this._runTask(G(m(arguments,!0)),f(arguments))},Git2.prototype.subModule=function(e,t){return this._runTask(V(m(arguments)),f(arguments))},Git2.prototype.listRemote=function(){return this._runTask(j(m(arguments)),f(arguments))},Git2.prototype.addRemote=function(e,t,n){return this._runTask(M(e,t,m(arguments)),f(arguments))},Git2.prototype.removeRemote=function(e,t){return this._runTask($(e),f(arguments))},Git2.prototype.getRemotes=function(e,t){return this._runTask(U(!0===e),f(arguments))},Git2.prototype.remote=function(e,t){return this._runTask(B(m(arguments)),f(arguments))},Git2.prototype.tag=function(e,t){const n=m(arguments);return"tag"!==n[0]&&n.unshift("tag"),this._runTask(Z(n),f(arguments))},Git2.prototype.updateServerInfo=function(e){return this._runTask(Z(["update-server-info"]),f(arguments))},Git2.prototype.pushTags=function(e,t){const n=L({remote:p(e,d)},m(arguments));return this._runTask(n,f(arguments))},Git2.prototype.rm=function(e){return this._runTask(Z(["rm","-f",...a(e)]),f(arguments))},Git2.prototype.rmKeepLocal=function(e){return this._runTask(Z(["rm","--cached",...a(e)]),f(arguments))},Git2.prototype.catFile=function(e,t){return this._catFile("utf-8",arguments)},Git2.prototype.binaryCatFile=function(){return this._catFile("buffer",arguments)},Git2.prototype._catFile=function(e,t){var n=f(t),r=["cat-file"],s=t[0];if("string"==typeof s)return this._runTask(o("Git.catFile: options must be supplied as an array of strings"),n);Array.isArray(s)&&r.push.apply(r,s);const i="buffer"===e?Q(r):Z(r);return this._runTask(i,n)},Git2.prototype.diff=function(e,t){const n=d(e)?o("git.diff: supplying options as a single string is no longer supported, switch to an array of strings"):Z(["diff",...m(arguments)]);return this._runTask(n,f(arguments))},Git2.prototype.diffSummary=function(){return this._runTask(R(m(arguments,1)),f(arguments))},Git2.prototype.applyPatch=function(e){const t=u(e)?y(a(e),m([].slice.call(arguments,1))):o("git.applyPatch requires one or more string patches as the first argument");return this._runTask(t,f(arguments))},Git2.prototype.revparse=function(){const e=["rev-parse",...m(arguments,!0)];return this._runTask(Z(e,!0),f(arguments))},Git2.prototype.clean=function(e,t,n){const r=P(e),s=r&&e.join("")||p(e,d)||"",i=m([].slice.call(arguments,r?1:0));return this._runTask(I(s,i),f(arguments))},Git2.prototype.exec=function(e){const t={commands:[],format:"utf-8",parser(){"function"==typeof e&&e()}};return this._runTask(t)},Git2.prototype.clearQueue=function(){return this._runTask(i(()=>console.warn("simple-git deprecation notice: clearQueue() is deprecated and will be removed, switch to using the abortPlugin instead.")))},Git2.prototype.checkIgnore=function(e,t){return this._runTask(S(a(p(e,u,[]))),f(arguments))},Git2.prototype.checkIsRepo=function(e,t){return this._runTask(E(p(e,d)),f(arguments))},t.exports=Git2}});yS(),vS();var iI=class extends bS{constructor(e,t){super(void 0,t),this.config=e}};vS(),vS();var oI=class extends bS{constructor(e,t,n){super(e,n),this.task=e,this.plugin=t,Object.setPrototypeOf(this,new.target.prototype)}};function abortPlugin(e){if(!e)return;const t={type:"spawn.after",action(t,n){function kill(){n.kill(new oI(void 0,"abort","Abort signal received"))}e.addEventListener("abort",kill),n.spawned.on("close",()=>e.removeEventListener("abort",kill))}},n={type:"spawn.before",action(t,n){e.aborted&&n.kill(new oI(void 0,"abort","Abort already signaled"))}};return[n,t]}function isConfigSwitch(e){return"string"==typeof e&&"-c"===e.trim().toLowerCase()}function isCloneSwitch(e,t){if("string"!=typeof t||!t.includes(e))return!1;const n=t.replace(/\0g/,"").replace(/^(--no)?-{1,2}/,"");return/^[\dlsqvnobucj]+\b/.test(n)}function preventProtocolOverride(e,t){if(isConfigSwitch(e)&&/^\s*protocol(.[a-z]+)?.allow/i.test(t))throw new oI(void 0,"unsafe","Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol")}function preventUploadPack(e,t){if(/^\s*--(upload|receive)-pack/.test(e))throw new oI(void 0,"unsafe","Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack");if("clone"===t&&isCloneSwitch("u",e))throw new oI(void 0,"unsafe","Use of clone with option -u is not permitted without enabling allowUnsafePack");if("push"===t&&/^\s*--exec\b/.test(e))throw new oI(void 0,"unsafe","Use of push with option --exec is not permitted without enabling allowUnsafePack")}function blockUnsafeOperationsPlugin({allowUnsafeProtocolOverride:e=!1,allowUnsafePack:t=!1}={}){return{type:"spawn.args",action:(n,r)=>(n.forEach((s,i)=>{const o=i<n.length?n[i+1]:"";e||preventProtocolOverride(s,o),t||preventUploadPack(s,r.method)}),n)}}function commandConfigPrefixingPlugin(e){const t=prefixedArray(e,"-c");return{type:"spawn.args",action:e=>[...t,...e]}}_S(),TS(),JS(),pE(),gE(),vE(),kE(),CE(),GS(),GS();var aI=(0,aS.deferred)().promise;function completionDetectionPlugin({onClose:e=!0,onExit:t=50}={}){function createEvents(){let n=-1;const r={close:(0,aS.deferred)(),closeTimeout:(0,aS.deferred)(),exit:(0,aS.deferred)(),exitTimeout:(0,aS.deferred)()},s=Promise.race([!1===e?aI:r.closeTimeout.promise,!1===t?aI:r.exitTimeout.promise]);return configureTimeout(e,r.close,r.closeTimeout),configureTimeout(t,r.exit,r.exitTimeout),{close(e){n=e,r.close.done()},exit(e){n=e,r.exit.done()},get exitCode(){return n},result:s}}function configureTimeout(e,t,n){!1!==e&&(!0===e?t.promise:t.promise.then(()=>delay2(e))).then(n.done)}return{type:"spawn.after",async action(e,{spawned:t,close:n}){const r=createEvents();let s=!0,quickClose=()=>{s=!1};t.stdout?.on("data",quickClose),t.stderr?.on("data",quickClose),t.on("error",quickClose),t.on("close",e=>r.close(e)),t.on("exit",e=>r.exit(e));try{await r.result,s&&await delay2(50),n(r.exitCode)}catch(e){n(r.exitCode,e)}}}}GS();var cI="Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings",lI="Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option";function isBadArgument(e){return!e||!/^([a-z]:)?([a-z0-9/.\\_~-]+)$/i.test(e)}function toBinaryConfig(e,t){if(e.length<1||e.length>2)throw new oI(void 0,"binary",cI);const n=e.some(isBadArgument);if(n){if(!t)throw new oI(void 0,"binary",lI);console.warn(lI)}const[r,s]=e;return{binary:r,prefix:s}}function customBinaryPlugin(e,t=["git"],n=!1){let r=toBinaryConfig(asArray2(t),n);e.on("binary",e=>{r=toBinaryConfig(asArray2(e),n)}),e.append("spawn.binary",()=>r.binary),e.append("spawn.args",e=>r.prefix?[r.prefix,...e]:e)}function isTaskError(e){return!(!e.exitCode||!e.stdErr.length)}function getErrorMessage(e){return Buffer.concat([...e.stdOut,...e.stdErr])}function errorDetectionHandler(e=!1,t=isTaskError,n=getErrorMessage){return(r,s)=>!e&&r||!t(s)?r:n(s)}function errorDetectionPlugin(e){return{type:"task.error",action(t,n){const r=e(t.error,{stdErr:n.stdErr,stdOut:n.stdOut,exitCode:n.exitCode});return Buffer.isBuffer(r)?{error:new bS(void 0,r.toString("utf-8"))}:{error:r}}}}vS(),GS();var dI=class{constructor(){this.plugins=new Set,this.events=new uS}on(e,t){this.events.on(e,t)}reconfigure(e,t){this.events.emit(e,t)}append(e,t){const n=append(this.plugins,{type:e,action:t});return()=>this.plugins.delete(n)}add(e){const t=[];return asArray2(e).forEach(e=>e&&this.plugins.add(append(t,e))),()=>{t.forEach(e=>this.plugins.delete(e))}}exec(e,t,n){let r=t;const s=Object.freeze(Object.create(n));for(const t of this.plugins)t.type===e&&(r=t.action(r,s));return r}};function progressMonitorPlugin(e){const t="--progress",n=["checkout","clone","fetch","pull","push"],r={type:"spawn.after",action(n,r){r.commands.includes(t)&&r.spawned.stderr?.on("data",t=>{const n=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(t.toString("utf8"));n&&e({method:r.method,stage:progressEventStage(n[1]),progress:asNumber(n[2]),processed:asNumber(n[3]),total:asNumber(n[4])})})}},s={type:"spawn.args",action:(e,r)=>n.includes(r.method)?including(e,t):e};return[s,r]}function progressEventStage(e){return String(e.toLowerCase().split(" ",1))||"unknown"}function spawnOptionsPlugin(e){const t=pick(e,["uid","gid"]);return{type:"spawn.options",action:e=>({...t,...e})}}function timeoutPlugin({block:e,stdErr:t=!0,stdOut:n=!0}){if(e>0)return{type:"spawn.after",action(r,s){let i;function wait2(){i&&clearTimeout(i),i=setTimeout(kill,e)}function stop(){s.spawned.stdout?.off("data",wait2),s.spawned.stderr?.off("data",wait2),s.spawned.off("exit",stop),s.spawned.off("close",stop),i&&clearTimeout(i)}function kill(){stop(),s.kill(new oI(void 0,"timeout","block timeout reached"))}n&&s.spawned.stdout?.on("data",wait2),t&&s.spawned.stderr?.on("data",wait2),s.spawned.on("exit",stop),s.spawned.on("close",stop),wait2()}}}function suffixPathsPlugin(){return{type:"spawn.args",action(e){const t=[];let n;function append2(e){(n=n||[]).push(...e)}for(let n=0;n<e.length;n++){const r=e[n];if(isPathSpec(r))append2(toPaths(r));else{if("--"===r){append2(e.slice(n+1).flatMap(e=>isPathSpec(e)&&toPaths(e)||e));break}t.push(r)}}return n?[...t,"--",...n.map(String)]:t}}}GS(),GS(),yS(),GS();var uI=sI();function gitInstanceFactory(e,t){const n=new dI,r=createInstanceConfig(e&&("string"==typeof e?{baseDir:e}:e)||{},t);if(!folderExists(r.baseDir))throw new iI(r,"Cannot use simple-git on a directory that does not exist");return Array.isArray(r.config)&&n.add(commandConfigPrefixingPlugin(r.config)),n.add(blockUnsafeOperationsPlugin(r.unsafe)),n.add(suffixPathsPlugin()),n.add(completionDetectionPlugin(r.completion)),r.abort&&n.add(abortPlugin(r.abort)),r.progress&&n.add(progressMonitorPlugin(r.progress)),r.timeout&&n.add(timeoutPlugin(r.timeout)),r.spawnOptions&&n.add(spawnOptionsPlugin(r.spawnOptions)),n.add(errorDetectionPlugin(errorDetectionHandler(!0))),r.errors&&n.add(errorDetectionPlugin(r.errors)),customBinaryPlugin(n,r.binary,r.unsafe?.allowUnsafeCustomBinary),new uI(r,n)}_S();var pI=gitInstanceFactory;async function pathExists5(e){try{return await nS.access(e),!0}catch{return!1}}async function ensureGitRepo(e){const t=rS.join(e,".git");await nS.mkdir(e,{recursive:!0});const n=pI(e);let r=!1;if(await pathExists5(t))try{r="true"===(await n.raw(["rev-parse","--is-inside-work-tree"])).trim()}catch{r=!1}if(!r)try{await n.init(["--initial-branch=main"])}catch{await n.init()}try{await n.raw(["rev-parse","--verify","HEAD"])}catch{await n.raw(["add","-A"]),await n.raw(["-c","user.name=Tempo","-c","user.email=tempo@local","commit","--allow-empty","-m","Initial commit"])}}async function pathExists6(e){try{return await tS(e),!0}catch{return!1}}function describeGitFailure(e){const t=e instanceof Error?e.message:String(e??"");return/xcode-select: note: No developer tools/i.test(t)||/Command Line Developer Tools/i.test(t)?"Xcode Command Line Tools are required for git. Run `xcode-select --install` to enable git, then retry.":/ENOENT/.test(t)||/git: command not found/i.test(t)?"Git isn't installed on this machine. Install git to enable version control for this project.":t||"Git failed for an unknown reason."}async function ensureTempoGitRepo(e){const t=eS.join(e,".git"),n=await pathExists6(t);try{return await ensureGitRepo(e),{initializedGit:!n,gitSkipped:!1}}catch(e){return{initializedGit:!1,gitSkipped:!0,gitSkipReason:describeGitFailure(e)}}}import hI from"path";import{access as mI,lstat as fI,mkdir as gI,readFile as yI,writeFile as bI}from"fs/promises";async function pathExists7(e){try{return await mI(e),!0}catch{return!1}}function normalizeEntry(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")+"/"}function getIgnorePrefix(e){return"."===e.rootRel?"":`${e.rootRel.replace(/^\.\//,"").replace(/\/+$/,"")}/`}async function resolveGitCommonDir(e){const t=hI.join(e,".git");let n;try{const r=await fI(t);if(r.isDirectory())n=t;else{const r=await yI(t,"utf-8"),s=r.match(/^gitdir:\s*(.+)$/m);if(!s)return null;const i=s[1].trim();n=hI.isAbsolute(i)?i:hI.resolve(e,i)}}catch{return null}try{const e=(await yI(hI.join(n,"commondir"),"utf-8")).trim();if(e)return hI.resolve(n,e)}catch{}return n}function getIgnoreEntries(e){const t=getIgnorePrefix(e);return[`${t}.tempo`,`${t}node_modules`,`${t}dist`].map(normalizeEntry)}var vI=[".tempo","app-devserver.json","app-devserver.log","node_modules",".next",".nuxt",".output",".data",".expo",".swc",".turbo","dist","out","web-build","*.log","logs",".flutter-host",".DS_Store"];function getTempoFolderGitignorePath(e){return hI.join(e.tempoRoot,".gitignore")}async function ensureTextFileEntries(e,t){const n=await pathExists7(e)?await yI(e,"utf-8"):"",r=new Set(n.split(/\r?\n/).map(e=>e.trim())),s=t.filter((e,n)=>!r.has(e)&&t.indexOf(e)===n);if(0===s.length&&await pathExists7(e))return!1;const i=n.includes("\r\n")?"\r\n":"\n",o=n.length>0&&!n.endsWith("\n"),a=s.map(e=>`${e}${i}`).join("");return await gI(hI.dirname(e),{recursive:!0}),await bI(e,`${n}${o?i:""}${a}`,"utf-8"),s.length>0}async function ensureTempoIgnoreEntries(e){const t=getIgnoreEntries(e),n=hI.join(e.projectRoot,".gitignore"),r=await ensureTextFileEntries(n,t);let s=!1;const i=await resolveGitCommonDir(e.projectRoot);if(i){const e=hI.join(i,"info","exclude");s=await ensureTextFileEntries(e,[...t,".tempo/"])}const o=await ensureTextFileEntries(getTempoFolderGitignorePath(e),vI);return{updatedGitignore:r,updatedGitExclude:s,updatedTempoFolderGitignore:o}}import{spawn as wI}from"child_process";import{access as _I}from"fs/promises";import xI from"path";var{error:TI,throwIfAborted:kI,sleep:SI}=abortableWait("Dependency installation was cancelled");import{access as EI,mkdir as AI,rm as CI}from"fs/promises";import II from"path";var PI="tempo",DI="tempo.config.json",RI={migrated:!1,movedPaths:[],installScriptRewrote:!1};async function pathExists8(e){try{return await EI(e),!0}catch{return!1}}async function writeCanonicalDefaultConfig(e){const t=await detectRootPackageManager(e.projectRoot),n=buildInstallScript(t?.installCmd??null);return await writeTempoConfigFile(e.tempoRoot,buildDefaultTempoConfig({installScript:n})),II.join(e.tempoRoot,DI)}async function migrateLegacyRootLayout(e){const t=II.resolve(e),n=II.join(t,DI),r=II.join(t,PI,DI);if(await pathExists8(n)){const s=await pathExists8(r);if(devLog("migrate-legacy:delete-root-config",{projectRoot:e,legacyConfigPath:n,canonicalConfigPath:r,canonicalExists:s}),await CI(n,{force:!0}),s)return{...RI,autoCleanedLegacyConfigPath:n};const i=II.join(t,PI);await AI(i,{recursive:!0});const o=await writeCanonicalDefaultConfig({projectRoot:t,tempoRoot:i});return devLog("migrate-legacy:create-canonical-after-delete",{projectRoot:e,legacyConfigPath:n,createdCanonicalConfigPath:o}),{...RI,autoCleanedLegacyConfigPath:n,createdCanonicalConfigPath:o}}return devLog("migrate-legacy:skip",{projectRoot:e}),RI}import{readFile as NI,realpath as OI}from"fs/promises";import{createRequire as FI}from"module";import LI from"path";import MI from"path";function configsEqual(e,t){return e.projectRoot===t.projectRoot&&e.tempoConfigPath===t.tempoConfigPath&&e.rootRel===t.rootRel&&e.tempoRoot===t.tempoRoot&&e.pagesDir===t.pagesDir&&e.packageJsonPath===t.packageJsonPath&&e.viteConfigPath===t.viteConfigPath&&e.tsconfigPath===t.tsconfigPath&&JSON.stringify(e.tempoHostUrl)===JSON.stringify(t.tempoHostUrl)&&e.uiFramework===t.uiFramework&&e.appDir===t.appDir&&e.scripts.install===t.scripts.install&&e.scripts.updateSdk===t.scripts.updateSdk&&e.scripts.start===t.scripts.start&&e.scripts.stop===t.scripts.stop}function usesTempoManagedSidecarPackage(e,t){if(!looksLikeGeneratedInstallScript(e.scripts.install))return!1;const n=e.scripts.start.trim();return"expo"===t?"npx expo start --web"===n:/^(?:npm|pnpm|bun) run dev$|^yarn dev$/.test(n)}function toDevServerConfig(e){return{tempoConfigPath:e.tempoConfigPath,tempoHostUrl:e.tempoHostUrl,appDir:e.appDir??null,scripts:{...e.scripts}}}function buildInitResult(e){return{config:e.config,createdConfig:e.createdConfig,initializedGit:e.initializedGit,gitSkipped:e.gitSkipped,...void 0!==e.gitSkipReason?{gitSkipReason:e.gitSkipReason}:{},updatedGitignore:e.updatedGitignore,updatedGitExclude:e.updatedGitExclude,createdDirectories:e.createdDirectories,legacyLayoutMigration:e.legacyLayoutMigration,devserverInit:e.devserverInit,warnings:e.warnings}}function nuxtAppDirToRecord(e,t,n){return void 0!==e.appDir||null===t.appDir?null:n===t.start?t.appDir:null}var UI=class{constructor(e,t,n){this.parseManagedLockfile=t,this.devserver=null,this.devserverConfig=null,this.initializePromise=null,this.projectRoot=MI.resolve(e),this.fastNpmInstall=!0===n}static async open(e){const t="string"==typeof e?e:e.projectRoot;return new this(t,"string"==typeof e?void 0:e.parseManagedLockfile,"string"==typeof e?void 0:e.fastNpmInstall)}getProjectRoot(){return this.projectRoot}async getResolvedConfig(){return await resolveTempoConfig(this.projectRoot)}async getFramework(){try{return await detectProjectFramework(await this.getResolvedConfig())}catch{return"vite"}}async getUiFramework(){const e=await this.getResolvedConfig();return resolveAppUiFramework(e.apps[0]?.uiFramework)}async isInitialized(){return await tempoConfigExists(this.projectRoot)}async initialize(e={}){return await this.ensureInitialized(e)}async initializeExistingProject(e={}){const t=await this.runSingleInitialize(async()=>await this.performInitializeExistingProject(e));return await seedSharedControls(t.config),t}async ensureInitialized(e={}){return await this.runSingleInitialize(async()=>{const t=await migrateLegacyRootLayout(this.projectRoot);if(await tempoConfigExists(this.projectRoot)){await ensureDirectoryExists(this.projectRoot);const n=await ensureTempoGitRepo(this.projectRoot);await ensureValidTempoConfigFile(this.projectRoot);let r=await this.getResolvedConfig();resolveAppUiFramework(r.apps[0]?.uiFramework);const s=await ensureTempoIgnoreEntries(r),i=await this.resolveSetupFramework(r,e),o=await rescueWronglyBackedUpFiles(r);o.restored.length>0&&console.log(`[tempo-project] restored ${o.restored.length} wrongly-backed-up file(s) from prior heal pass: ${o.restored.join(", ")}`);const a=await healFrameworkMismatch(r,i);a.healed&&a.backupPath&&console.log(`[tempo-project] healed framework mismatch: ${a.previousFramework} → ${i}; previous scaffold backed up to ${a.backupPath}`);const c=[];if("nuxt"===i)if(a.healed){const e=await this.recordNuxtAppDefaults(r);r=e.config,c.push(...e.warnings)}else r=await this.reconcileNuxtAppDir(r);const l=await hasCustomReactViteHost(r,i);l?await ensureTempoWorkspaceNonce(r.tempoRoot):(c.push(...await ensureProjectSetupFiles(r,i,{migrateSdkDependencies:!1,createPackageJsonIfMissing:a.healed||usesTempoManagedSidecarPackage(r,i)})),await ensureProjectScaffold(r,i));const d=await reconcileExpoStartScriptOnDisk(r.tempoConfigPath,i);d&&console.log(`[tempo-project] reconciled tempo.config.json scripts.start for framework ${i}`);const u=await this.getDevServer(r),p=await u.initialize();return buildInitResult({config:r,createdConfig:!1,initializedGit:n.initializedGit,gitSkipped:n.gitSkipped,gitSkipReason:n.gitSkipReason,updatedGitignore:s.updatedGitignore,updatedGitExclude:s.updatedGitExclude,createdDirectories:[],legacyLayoutMigration:t,devserverInit:p,warnings:c})}return await this.performInitializeExistingProject(e)})}async reconcile(e){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);return{config:t,devserver:await n.reconcile(e)}}async ensureCanvasRegistered(e){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);await n.ensureCanvasRegistered(e)}async prepareManagedDependencies(e={}){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);await n.prepareManagedDependencies(e)}async prepareDependenciesForStart(e={}){const t=await this.getDevServer(await this.getResolvedConfig());await t.prepareDependenciesForStart(e)}async startDevServer(e){const t=await this.getResolvedConfig(),n=await this.getDevServer(t);return await n.startDevServer(e)}async listRegisteredCanvases(){const e=await this.getResolvedConfig(),t=await this.getDevServer(e);return await t.listRegisteredCanvases()}async getRequestedCanvasPaths(){const e=await this.getResolvedConfig(),t=await this.getDevServer(e);return await t.getRequestedCanvasPaths()}async getState(){try{const e=await this.getResolvedConfig(),t=await this.getDevServer(e);return t.getState()}catch{return{setupStatus:"uninitialized",reconcileStatus:"idle",processStatus:"stopped",livenessSource:null,initialized:!1,generation:0,lastError:null,dependenciesInstalled:!1,devserverUrl:null,recentReconciles:[],recentStartAttempts:[],recentExits:[]}}}async dispose(){const e=this.devserver;this.devserver=null,this.devserverConfig=null,await(e?.dispose())}createDevServer(e){return new fx(e)}async getDevServer(e){const t=e??await this.getResolvedConfig(),n=!this.devserver||!this.devserverConfig||!configsEqual(this.devserverConfig,t);return n&&(this.devserver=this.createDevServer({...toDevServerConfig(t),parseManagedLockfile:this.parseManagedLockfile,...this.fastNpmInstall?{fastNpmInstall:!0}:{}}),this.devserverConfig=t),this.devserver}async performInitializeExistingProject(e={}){await ensureDirectoryExists(this.projectRoot);const t=await migrateLegacyRootLayout(this.projectRoot),n=await ensureTempoGitRepo(this.projectRoot),r=await detectRootPackageManager(this.projectRoot),s=buildInstallScript(r?.installCmd??null),i=e.framework,o=await ensureTempoConfigFile(this.projectRoot,MI.join(this.projectRoot,ly),"expo"===i?buildExpoTempoConfig({installScript:s}):buildDefaultTempoConfig({installScript:s}));await ensureValidTempoConfigFile(this.projectRoot);let a=await this.getResolvedConfig();resolveAppUiFramework(a.apps[0]?.uiFramework);const c=await ensureTempoIgnoreEntries(a),l=[],d=await findAppDirToRecord(a);null!==d.appDir&&(await mergeTempoConfigFile(this.projectRoot,{appDir:d.appDir}),console.log(`[tempo-project] recorded apps[0].appDir "${d.appDir}", the project's only app package`),a=await this.getResolvedConfig()),d.warning&&l.push(setupWarning(d.warning));const u=await buildInstallScriptForProject(this.projectRoot,a.appDir),p=a.scripts.install===s;p&&u!==s&&(await mergeTempoConfigFile(this.projectRoot,{installScript:u}),a=await this.getResolvedConfig());const m=await this.resolveSetupFramework(a,e),f=await healFrameworkMismatch(a,m);if(f.healed&&f.backupPath&&(l.push(setupWarning(`replaced the ${f.previousFramework} canvas host in tempo/ with the ${m} one; the previous files are in ${f.backupPath}`)),a=await this.getResolvedConfig()),"nuxt"===m){const e=await this.recordNuxtAppDefaults(a,d.warning);a=e.config,l.push(...e.warnings)}l.push(...await ensureProjectSetupFiles(a,m)),await ensureProjectScaffold(a,m);const g=await this.getDevServer(a),y=await g.initialize();return buildInitResult({config:a,createdConfig:o,initializedGit:n.initializedGit,gitSkipped:n.gitSkipped,gitSkipReason:n.gitSkipReason,updatedGitignore:c.updatedGitignore,updatedGitExclude:c.updatedGitExclude,createdDirectories:[],legacyLayoutMigration:t,devserverInit:y,warnings:l})}async recordNuxtAppDefaults(e,t=null){const n=e.apps[0],r=await resolveNuxtAppRun(e);if(!await isNuxtAppDir(r.appRoot)){const e=r.appDir?`"${r.appDir}"`:"the project root";throw new Error(`No Nuxt app in ${e}: it has no nuxt dependency and no nuxt.config.*. Set "apps[0].appDir" in tempo/tempo.config.json to the Nuxt app's folder, relative to the project root (for example "apps/web"), then rerun canvas_project_init.`+(r.appRootWarning?` ${r.appRootWarning}`:"")+(t?` ${t}`:""))}const s=[],i=void 0===n?.uiFramework,o=null!==r.appDir&&n?.start===r.projectRootStart,a=!n?.start||o,c=a?r.start:n?.start??r.start;o&&s.push(setupWarning(`apps[0].start ran the Nuxt app from the project root; replaced it with "${r.start}", which runs from "${r.appDir}".`)),nuxtAppStartExtendsAppLayer(c)||s.push(setupWarning(`apps[0].start ("${c}") does not pass --extends ${r.appLayerPath}, Tempo's app layer: Nuxt route storyboards will have no Vue source layers. Add "--extends ${r.appLayerPath}" to the nuxt dev command.`));const{unsupportedInstaller:l}=await appPackageLinks(r.appRoot,e.tempoRoot,Bk);l&&s.push(setupWarning(`the Nuxt app in "${r.appDir}" installs its packages where tempo/ cannot reach them, and ${l} installs tempo/: it cannot link the app's own nuxt and vue without installing a second Nuxt, so the canvas cannot load the app. Supported: pnpm or npm, or an app whose packages install into a workspace root above tempo/.`));const d=nuxtAppDirToRecord(e,r,c);return i||a||null!==d?(await mergeTempoConfigFile(this.projectRoot,{...i?{appUiFramework:"vue"}:{},...a?{appStart:r.start}:{},...null!==d?{appDir:d}:{}}),{config:await this.getResolvedConfig(),warnings:s}):{config:e,warnings:s}}async reconcileNuxtAppDir(e){const t=e.apps[0]?.start;if(!t||void 0!==e.appDir)return e;const n=nuxtAppDirToRecord(e,await resolveNuxtAppRun(e),t);return null===n?e:(await mergeTempoConfigFile(this.projectRoot,{appDir:n}),console.log(`[tempo-project] recorded appDir "${n}": Tempo's Nuxt app start command runs from the app directory`),await this.getResolvedConfig())}async resolveSetupFramework(e,t){return t.framework?t.framework:await detectProjectFramework(e)}async runSingleInitialize(e){if(this.initializePromise)return await this.initializePromise;this.initializePromise=e();try{return await this.initializePromise}finally{this.initializePromise=null}}},jI="## Responsive storyboards",BI="## What earlier checks found in this project",$I=2e3,WI=["AGENTS.md","CLAUDE.md"];async function readProjectFindingsAppendix(e){for(const t of WI){const n=`${ly}/${t}`,r=await jm(Bm.join(e,ly,t),"utf8").catch(()=>null);if(null===r)continue;const s=extractSection(r,jI);if(s)return formatAppendix(s,n)}return""}function extractSection(e,t){const n=e.split(/\r?\n/),r=n.findIndex(e=>e.trimEnd()===t);if(-1===r)return null;const s=n.slice(r+1),i=s.findIndex(e=>e.startsWith("## ")),o=(-1===i?s:s.slice(0,i)).join("\n").trim();return""===o?null:o}function formatAppendix(e,t){const n=`\n\n---\n\n${BI}\n\nFrom \`${t}\`, \`${jI}\`:\n\n`,r=`${n}${e}\n`;if(r.length<=$I)return r;const s=`\n\n(Cut at ${$I.toLocaleString("en-US")} characters. The rest is in \`${t}\` under \`${jI}\`.)\n`,i=$I-n.length-s.length;return`${n}${cutAtLine(e,i)}${s}`}function cutAtLine(e,t){const n=e.slice(0,t),r=n.lastIndexOf("\n");return(r>0?n.slice(0,r):n).trimEnd()}var HI={"tempo-canvas-instructions":Om,"tempo-assets-instructions":Nm,"tempo-design-system-example":Mm,"tempo-visual-review-setup":Um},qI=Object.keys(HI);function resolveTemplate(e,t){const n=Dm.relative(t.workspaceRoot,t.canvasesDir)||"tempo/designs";return e.replace(/\{\{canvasesDir\}\}/g,t.canvasesDir).replace(/\{\{canvasesDirRel\}\}/g,n).replace(/\{\{workspaceRoot\}\}/g,t.workspaceRoot)}function registerDocs(e,t){const n=!1!==t.assetsEnabled,r=qI.filter(e=>n||"tempo-assets-instructions"!==e);e.tool("get_guide",n?"Returns canvas documentation by topic. Pick by INTENT, not by name similarity: 'tempo-canvas-instructions' — the full canvas authoring guide; MUST be called before your first canvas operation in a session. 'tempo-assets-instructions' — the design-system conventions: defineControls + defineAsset authoring rules, placement, and asset_* write recipes; MUST be read before ADDING or EDITING controls or asset declarations, but NOT needed to browse (browse directly with asset_list / asset_list_libraries — never via a guide). 'tempo-design-system-example' — the full source of the reference design-system canvas; read ONLY when authoring a design-system canvas, to mirror its anatomy and formatting — it is not a way to look up what's in the design system. 'tempo-visual-review-setup' — the protocol for turning on visual review (VRT) for a repo: how to read visual_review_doctor's rows, what visual_review_init writes, picking + verifying the first tracked set, other-CI limits, and the debugging ladder; MUST be read before running visual_review_doctor / visual_review_init.":"Returns canvas documentation by topic. Topics: 'tempo-canvas-instructions' (full canvas authoring guide — MUST be called before your first canvas operation in a session), 'tempo-design-system-example' (full source of the reference design-system canvas — read before authoring design-system canvases to mirror its anatomy and formatting), 'tempo-visual-review-setup' (the visual review setup protocol — MUST be read before visual_review_doctor / visual_review_init).",{topic:Rm.enum(r).describe(`Guide topic. Currently supported: ${r.join(", ")}`)},async({topic:e})=>{const n=HI[e];if(!n)return{content:[{type:"text",text:`Unknown guide topic '${e}'. Available topics: ${qI.join(", ")}`}],isError:!0};const r="tempo-canvas-instructions"===e?await readProjectFindingsAppendix(t.workspaceRoot):"";return{content:[{type:"text",text:resolveTemplate(n,t)+r}]}}),e.resource("tempo://docs/canvas","tempo://docs/canvas",async()=>({contents:[{uri:"tempo://docs/canvas",text:resolveTemplate(Om,t),mimeType:"text/markdown"}]})),e.resource("tempo://docs/design-system-example","tempo://docs/design-system-example",async()=>({contents:[{uri:"tempo://docs/design-system-example",text:resolveTemplate(Mm,t),mimeType:"text/markdown"}]})),e.resource("tempo://docs/visual-review-setup","tempo://docs/visual-review-setup",async()=>({contents:[{uri:"tempo://docs/visual-review-setup",text:resolveTemplate(Um,t),mimeType:"text/markdown"}]})),n&&e.resource("tempo://docs/assets","tempo://docs/assets",async()=>({contents:[{uri:"tempo://docs/assets",text:resolveTemplate(Nm,t),mimeType:"text/markdown"}]}))}function buildCanvasInstructions(e,t){const n=!1===t?.assetsEnabled?"":'## Asset libraries\n\nBefore creating, modifying, restyling, or reviewing ANY UI, call `asset_list` FIRST and reuse results per `usageInstructions`. Do the same for design system, component library, or UI kit requests; use `asset_list_libraries` for a collection overview. Before editing `defineControls` or `defineAsset`, read get_guide({ topic: "tempo-assets-instructions" }). Follow its controls-placement policy. Assets declare top-level components.\n\n';return`Tempo canvases are code-first. Canvases live under the canvases root ${e}/, whose storyboards render PRODUCTION components and routes — never mocks of existing UI.\n\nBefore any canvas or tempo.config.json change, you MUST call get_guide({ topic: "tempo-canvas-instructions" }); it is authoritative.\n\n${n}## Hard invariants\n\n- No tempo.config.json → canvas_project_init BEFORE any canvas work. \`tempo/\` is Tempo's canvas host, NOT the user's app — build new UI in the real app; canvas-local files only wrap it (guide §5.1).\n- Zone canvases (design-system/**, libraries/<libname>/**) MUST defineAsset-declare their showcased components — else canvas_validate fails missing_asset_declaration.\n- Canvas activity: start_working_on_canvas → edits → canvas_screenshot → finish_working_on_canvas. Frame shimmer: start_working_on_storyboard / finish_working_on_storyboard. Rendering stays live. On screenshot failure: canvas_debug once, no retries.\n- Write is blocked on *.canvas.tsx — canvas_create creates, Edit modifies.\n- Route storyboards need the user's real app: set_app_dev_command once, start_app_dev_server before screenshots.\n- VRT: canvas_set_vrt, then canvas_verify_vrt until \`vrt_stable\`. Setup: visual_review_doctor first; visual_review_init writes the workflow, never hand-write it; guide tempo-visual-review-setup.\n- Existing site/page as HTML snapshot → canvas_snapshot_route, never a custom serializer. Pixel parity: guide §9.1.\n- Link new canvases to sibling issue/doc via link_items (branch pushed).`}import{readFile as zI,realpath as GI,writeFile as VI}from"fs/promises";import KI from"path";import{readFile as XI,writeFile as YI}from"fs/promises";import JI from"path";import{z as QI}from"zod";import{parseSync as ZI}from"oxc-parser";import{createRequire as eP}from"module";var tP=Object.freeze({$unresolved:!0});function isUnresolvedValue(e){return"object"==typeof e&&null!==e&&nP in e&&!0===e.$unresolved}var nP="$unresolved";function parseAstroAssetSource(e){const t=eP(import.meta.url)("@astrojs/compiler-rs").parse(e),n=t.diagnostics.filter(e=>"error"===e.severity);if(n.length)throw new Error(n.map(e=>e.text).join("\n"));return t.ast}var rP="tempo-sdk/assets";function parseAssetFile(e,t,n=parseAssetProgram(e,t)){const{program:r}=n,s=[...n.errors];if(!r)return{filePath:e,declarations:[],errors:s};const i=readAssetImports(r);for(const e of i.misimports)s.push({code:"misimported_define_asset",severity:"structural",message:`defineAsset must be imported from "${rP}" — found import from "${e.source}"`,span:e.span});const o=new Map;for(const e of r.body){const t="ExportNamedDeclaration"===e.type?e.declaration:e;if("VariableDeclaration"===t?.type&&"const"===t.kind)for(const e of t.declarations)"Identifier"===e.id.type&&e.init&&o.set(e.id.name,e.init)}const resolveConstants=(t,n=new Set,r=0)=>{if(!t||r>16)return t;if("Identifier"===t.type&&o.has(t.name)&&!n.has(t.name))return resolveConstants(o.get(t.name),new Set(n).add(t.name),r+1);if("JSXElement"===t.type||"JSXFragment"===t.type){const s=t.openingElement,o="JSXIdentifier"===s?.name?.type?s.name.name:"";if(s&&!o)return t;const a=o&&/^[A-Z]/.test(o)?i.referenceableImports.get(o):void 0;if(o&&/^[A-Z]/.test(o)&&!a)return t;const c={};for(const e of s?.attributes??[]){if("JSXAttribute"!==e.type||"JSXIdentifier"!==e.name.type)return t;c[e.name.name]=!e.value||readStaticValue(resolveConstants("JSXExpressionContainer"===e.value.type?e.value.expression:e.value,n,r+1))}const l=[];for(const e of t.children)if("JSXText"===e.type){const t=e.value.replace(/\t/g," ").split(/\r\n|\n|\r/),n=t.map((e,n)=>(n?e.trimStart():e).replace(n<t.length-1?/ +$/:/$^/,"")).filter(Boolean).join(" ");n&&l.push(n)}else{if("JSXExpressionContainer"===e.type&&"JSXEmptyExpression"===e.expression.type)continue;l.push(readStaticValue(resolveConstants("JSXExpressionContainer"===e.type?e.expression:e,n,r+1)))}l.length&&(c.children=1===l.length?l[0]:l);let d=a?.importSpecifier;if(d?.startsWith(".")){const t=e.replace(/\\/g,"/").split("/").slice(0,-1);for(const e of d.split("/"))".."===e?t.pop():"."!==e&&t.push(e);d=t.join("/")}else d&&(d=`pkg:${d}`);return{type:"TempoJsxValue",value:{$jsx:{tag:o,...a?{reference:{source:d,importedName:a.importedName}}:{},props:c}}}}return"ArrowFunctionExpression"!==t.type||t.async||0!==t.params.length?"ObjectExpression"===t.type?{...t,properties:t.properties.map(e=>"Property"===e.type?{...e,value:resolveConstants(e.value,n,r+1),shorthand:!1}:e)}:"ArrayExpression"===t.type?{...t,elements:t.elements.map(e=>resolveConstants(e,n,r+1))}:["TSAsExpression","TSSatisfiesExpression","ParenthesizedExpression"].includes(t.type)?{...t,expression:resolveConstants(t.expression,n,r+1)}:t:{...t,body:resolveConstants(t.body,n,r+1)}},a=collectTopLevelScope(r),c=[],l=new Set,d=new Set;for(const e of r.body??[]){const n=readTopLevelTrustedCall(e,i.trustedDefineAssetNames);if(!n)continue;d.add(n);const o=readAssetDeclaration({statement:e,call:{...n,arguments:n.arguments.map((e,t)=>1===t&&"ObjectExpression"===e.type?{...e,properties:e.properties.map(e=>"Property"===e.type&&["controls","variants"].includes(e.key.name??e.key.value)?{...e,value:resolveConstants(e.value)}:e)}:e)},scope:a,imports:i,program:r,source:t,errors:s,declaredBindings:l});o&&c.push(o)}walk2(r,e=>{"CallExpression"===e.type&&"Identifier"===e.callee?.type&&i.trustedDefineAssetNames.has(e.callee.name)&&!d.has(e)&&s.push({code:"non_top_level_call",severity:"structural",message:"defineAsset must be called as a top-level statement — in the file that defines the component, or in a canvas file that imports it",span:toSourceSpan(e)})});for(const e of c){const t=s.find(t=>"duplicate_declaration"===t.code&&t.message.includes(`"${e.bindingName}"`));t&&e.warnings.push({...t,code:"duplicate_asset_declaration"})}return{filePath:e,declarations:c,errors:s}}function parseAssetProgram(e,t){try{if(e.endsWith(".astro")){const e=parseAstroAssetSource(t);return{program:e.frontmatter?.program??{type:"Program",body:[]},errors:[]}}const n=ZI(e,t),r=(n.errors??[]).map(e=>({code:"unparseable_source",severity:"structural",message:e?.message??"Unable to parse asset source",span:toSourceSpan(e)??toSourceSpan(e?.labels?.[0])}));return r.length>0?{program:null,errors:r}:{program:n.program,errors:[]}}catch(e){return{program:null,errors:[{code:"unparseable_source",severity:"structural",message:e instanceof Error?e.message:"Unable to parse asset source"}]}}}function readSourceComments(e,t){try{if(e.endsWith(".astro")){const e=parseAstroAssetSource(t),n=[...e.comments],visit2=e=>{if(e&&"object"==typeof e){"AstroComment"===e.type&&n.push(e);for(const[t,n]of Object.entries(e))"comments"!==t&&(Array.isArray(n)?n.forEach(visit2):n&&"object"==typeof n&&visit2(n))}};return visit2(e),n.map(e=>({value:e.value,span:{start:e.start,end:e.end}}))}const n=ZI(e,t);return(n.errors??[]).length>0?null:(n.comments??[]).flatMap(e=>"string"==typeof e?.value?[{value:e.value,span:toSourceSpan(e)??{start:0,end:0}}]:[])}catch{return null}}function readAssetImports(e){const t={trustedDefineControlsNames:new Set,trustedDefineAssetNames:new Set,importedBindings:new Map,referenceableImports:new Map,importDeclarationSpans:[],misimports:[]};for(const n of e?.body??[]){if("ImportDeclaration"!==n?.type||"string"!=typeof n.source?.value)continue;const e=toSourceSpan(n);if(e&&t.importDeclarationSpans.push(e),"type"===n.importKind)continue;const r=n.source.value,s=isTrustedAssetImportSource(r);for(const i of n.specifiers??[]){if("type"===i?.importKind)continue;const o=i?.local?.name;if("string"!=typeof o)continue;if(t.importedBindings.set(o,r),"ImportDefaultSpecifier"===i.type){t.referenceableImports.set(o,{importSpecifier:r,importedName:"default"});continue}if("ImportSpecifier"!==i.type)continue;const a=i.imported?.name??i.imported?.value??o;t.referenceableImports.set(o,{importSpecifier:r,importedName:a}),s&&"defineControls"===a&&t.trustedDefineControlsNames.add(o),"defineAsset"===a&&(s?t.trustedDefineAssetNames.add(o):isMisimportedAssetSdkSource(r)&&t.misimports.push({source:r,span:toSourceSpan(n.source)??e??{start:0,end:0}}))}}return t}function parseControlsFile(e,t,n=parseAssetProgram(e,t)){const{program:r}=n,s=readAssetImports(r),i=r?collectTopLevelScope(r):null,o=new Set;if(e.endsWith(".astro"))for(const e of r?.body??[])if("ImportDeclaration"===e.type&&"tempo-sdk/astro/controls"===e.source.value&&"type"!==e.importKind)for(const t of e.specifiers)"ImportSpecifier"===t.type&&"type"!==t.importKind&&"defineAstroControls"===(t.imported.name??t.imported.value)&&o.add(t.local.name);return(r?.body??[]).flatMap(e=>{const t="ExpressionStatement"===e.type?e.expression:null;if("CallExpression"===t?.type&&"Identifier"===t.callee.type&&o.has(t.callee.name)&&1===t.arguments.length)return[{bindingName:"default",exportKind:"default",start:t.start,end:t.end}];if("CallExpression"!==t?.type||"Identifier"!==t.callee.type||!s.trustedDefineControlsNames?.has(t.callee.name)||2!==t.arguments.length||"Identifier"!==t.arguments[0]?.type)return[];const n=t.arguments[0].name,r=s.referenceableImports.get(n),a=i?.bindings.get(n);return r||a?[{bindingName:n,reference:r,exportKind:"default"===r?.importedName?"default":a?.exportKind??"named",start:t.start,end:t.end}]:[]})}function isTrustedAssetImportSource(e){return e===rP||e.endsWith(`/${rP}`)}function isMisimportedAssetSdkSource(e){return("tempo-sdk"===e||e.startsWith("tempo-sdk/"))&&!isTrustedAssetImportSource(e)}function collectTopLevelScope(e){const t=new Map,n=new Set,r=new Set,s=new Set,register=(e,i,o)=>{const markExported=e=>{"named"===o&&r.add(e),"default"===o&&s.add(e)};if("FunctionDeclaration"===e?.type||"ClassDeclaration"===e?.type){const n=e.id?.name;return void("string"==typeof n&&(t.set(n,{name:n,statementSpan:i,exportKind:"none"}),markExported(n)))}if("VariableDeclaration"===e?.type)for(const r of e.declarations??[])if("Identifier"===r?.id?.type){const e=r.id.name;r.init?(t.set(e,{name:e,statementSpan:i,exportKind:"none"}),markExported(e)):n.add(e)}else collectPatternNames(r?.id,n)};for(const t of e?.body??[]){const e=toSourceSpan(t)??{start:0,end:0};if("ExportNamedDeclaration"!==t?.type){if("ExportDefaultDeclaration"===t?.type){const n=t.declaration;if("FunctionDeclaration"===n?.type||"ClassDeclaration"===n?.type)register(n,e,"default");else{const e=unwrapTsExpression2(n);"Identifier"===e?.type&&s.add(e.name)}continue}register(t,e,null)}else if(t.declaration&&register(t.declaration,e,"named"),!t.source)for(const e of t.specifiers??[]){if("ExportSpecifier"!==e?.type)continue;const t=e.local?.name;if("string"!=typeof t)continue;const n=e.exported?.name??e.exported?.value;("default"===n?s:r).add(t)}}for(const e of t.values())e.exportKind=s.has(e.name)?"default":r.has(e.name)?"named":"none";return{bindings:t,nonSimpleNames:n}}function collectPatternNames(e,t){if(e&&"object"==typeof e)if("Identifier"!==e.type||"string"!=typeof e.name)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"AssignmentPattern"!==e.type?"RestElement"===e.type&&collectPatternNames(e.argument,t):collectPatternNames(e.left,t);else for(const n of e.elements??[])collectPatternNames(n,t);else for(const n of e.properties??[])collectPatternNames(n?.value??n?.argument,t);else t.add(e.name)}function hasTopLevelDefineAssetCallFor(e,t,n){for(const r of e?.body??[]){const e=readTopLevelTrustedCall(r,t);if(!e)continue;const s=unwrapTsExpression2(e.arguments?.[0]);if("Identifier"===s?.type&&s.name===n)return!0}return!1}function collectIdentifierNames(e){const t=new Set;return walk2(e,e=>{"Identifier"!==e.type&&"JSXIdentifier"!==e.type||"string"!=typeof e.name||t.add(e.name)}),t}function readTopLevelTrustedCall(e,t){if("ExpressionStatement"!==e?.type)return null;const n=unwrapTsExpression2(e.expression);return"CallExpression"===n?.type&&"Identifier"===n.callee?.type&&t.has(n.callee.name)?n:null}function readAssetDeclaration(e){const{statement:t,call:n,scope:r,imports:s,program:i,source:o,errors:a}=e,c=statementSpanWithSemicolon(o,t),l=n.arguments??[];if(2!==l.length)return a.push({code:"invalid_call_arguments",severity:"structural",message:`defineAsset takes exactly two arguments (component, config) — found ${l.length}`,span:c}),null;const d=unwrapTsExpression2(l[0]);if("Identifier"!==d?.type)return a.push({code:"non_identifier_component",severity:"structural",message:"defineAsset's first argument must be an identifier naming a component defined in this file",span:toSourceSpan(l[0])??c}),null;const u=d.name,p=r.bindings.get(u),m=p?void 0:s.referenceableImports.get(u);if(!p&&!m)return a.push(classifyMissingBinding(u,r,s,i,toSourceSpan(d)??c)),null;const f=unwrapTsExpression2(l[1]);if("ObjectExpression"!==f?.type)return a.push({code:"config_not_object_literal",severity:"structural",message:"defineAsset's config must be an inline object literal — the span-based editor needs literal spans to mutate",span:toSourceSpan(l[1])??c}),null;if(e.declaredBindings.has(u))return a.push({code:"duplicate_declaration",severity:"structural",message:`duplicate defineAsset call for "${u}" — keep one asset declaration`,span:c}),null;e.declaredBindings.add(u);const g=[],y={call:c,config:toSourceSpan(f)??c,libraryItems:[]},b=readUsageInstructions(f),v=readLibraries(f,y,g),w=readVariants(f,g);if(getObjectProperty2(f,"controls"))return a.push({code:"invalid_control",severity:"structural",message:"Move controls to defineControls(Component, controls) in the component file or tempo/controls.ts."}),null;const x=g.filter(e=>"structural"===e.severity);return x.length?(a.push(...x),null):(p&&"none"===p.exportKind&&g.push({code:"not_exported",severity:"degraded",message:`"${u}" is not exported — other files cannot import this asset`,span:c}),{bindingName:u,exportKind:p?p.exportKind:referenceExportKind(m),libraries:v,...void 0===b?{}:{usageInstructions:b},variants:w,...m?{reference:m}:{},spans:y,warnings:g})}function referenceExportKind(e){return"default"===e.importedName?"default":"named"}function classifyMissingBinding(e,t,n,r,s){const i=n.importedBindings.get(e);return void 0!==i?{code:"imported_binding",severity:"structural",message:`"${e}" is a namespace import from "${i}" — declare the asset on a named or default import of the component instead`,span:s}:t.nonSimpleNames.has(e)?{code:"unknown_binding",severity:"structural",message:`"${e}" is not a plain initialized top-level binding — destructured and uninitialized declarations are not supported`,span:s}:hasNestedBinding(r,e)?{code:"non_top_level_binding",severity:"structural",message:`"${e}" is not declared at the top level of the module`,span:s}:{code:"unknown_binding",severity:"structural",message:`no top-level declaration of "${e}" found in this file`,span:s}}function hasNestedBinding(e,t){let n=!1;return walk2(e,e=>{n||"VariableDeclarator"!==e.type&&"FunctionDeclaration"!==e.type&&"ClassDeclaration"!==e.type||"Identifier"!==e.id?.type||e.id.name!==t||(n=!0)}),n}function readUsageInstructions(e){return readStaticStringProperty(e,"usageInstructions")}function readStaticStringProperty(e,t){const n=getObjectProperty2(e,t);if(!n)return;const r=readStaticValue(n.value);return"string"==typeof r?r:void 0}function readLibraries(e,t,n){const r=getObjectProperty2(e,"libraries");if(!r)return[];t.librariesProperty=toSourceSpan(r);const s=unwrapTsExpression2(r.value);if("ArrayExpression"!==s?.type)return n.push({code:"non_literal_library",severity:"degraded",message:"libraries must be an inline array literal of string literals — its entries were dropped",span:toSourceSpan(r.value)??t.librariesProperty}),[];t.libraries=toSourceSpan(s);const i=[];for(const e of s.elements??[]){const r=toSourceSpan(e)??t.libraries,s=readStaticString(e);null!==s?""!==s?i.includes(s)?n.push({code:"duplicate_library",severity:"degraded",message:`duplicate library name "${s}" — deduplicated`,span:r}):(i.push(s),r&&t.libraryItems.push(r)):n.push({code:"empty_library_name",severity:"degraded",message:"libraries entries must be non-empty — dropped an empty entry",span:r}):n.push({code:"non_literal_library",severity:"degraded",message:"libraries entries must be string literals — dropped a non-literal entry",span:r})}return i}function readVariants(e,t){const n=getObjectProperty2(e,"variants");if(!n)return[];const r=unwrapTsExpression2(n.value);if("ObjectExpression"!==r?.type)return t.push({code:"unresolved_prop_value",severity:"degraded",message:"variants is not an inline object literal — variant props are not statically readable",span:toSourceSpan(n.value)??toSourceSpan(n)}),[];const s=r.properties??[];if(0===s.length)return t.push({code:"empty_variants",severity:"degraded",message:"variants is present but empty",span:toSourceSpan(r)}),[];const i=[];for(const e of s){const n="Property"!==e?.type||e.computed?null:readPropertyKeyName2(e.key);null!==n?i.push(readVariant(n,e,t)):t.push({code:"unresolved_prop_value",severity:"degraded",message:"variant names must be identifier or string keys — skipped an entry that is not statically readable",span:toSourceSpan(e)??toSourceSpan(r)})}return i}function readVariant(e,t,n){const r=unwrapTsExpression2(t.value);for(const t of"ObjectExpression"===r?.type?r.properties:[])"Property"===t.type&&!t.computed&&["props","render"].includes(readPropertyKeyName2(t.key)??"")||n.push({code:"invalid_variant_config",severity:"structural",message:`Variant "${e}" accepts either props or render, with explicit keys and no spreads or inheritance`,span:toSourceSpan(t)});const s="ObjectExpression"===r?.type?getObjectProperty2(r,"render"):null,i="ObjectExpression"===r?.type?getObjectProperty2(r,"props"):null,o=unwrapTsExpression2(s?.value),a=unwrapTsExpression2(o?.body),c="TempoJsxValue"===a?.type?readStaticValue(a):tP,l="ArrowFunctionExpression"===o?.type&&!o.async&&0===o.params.length&&!i&&!containsUnresolvedValue(c);s&&!l&&n.push({code:"invalid_variant_config",severity:"structural",message:`Variant "${e}" render must be a parameterless arrow returning static JSX, without props, statements, hooks, callbacks, or computed expressions. Move logic into an imported component.`,span:toSourceSpan(s)});const d=s&&l?{jsx:c}:void 0,u=i?readStaticValue(i.value):d?{}:tP,p=isPlainRecord(u)?u:{},m=!isPlainRecord(u)||containsUnresolvedValue(u);return m&&n.push({code:"unresolved_prop_value",severity:"degraded",message:`variant "${e}" has prop values that are not statically readable`,span:toSourceSpan(t)}),{name:e,props:p,hasUnresolvedValues:m,...d?{render:d}:{}}}function readStaticValue(e){const t=unwrapTsExpression2(e);if(!t)return tP;switch(t.type){case"TempoJsxValue":return t.value;case"Literal":{if(t.regex||t.bigint)return tP;const{value:e}=t;return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:tP}case"TemplateLiteral":{if((t.expressions??[]).length>0)return tP;const e=t.quasis?.[0]?.value?.cooked;return"string"==typeof e?e:tP}case"UnaryExpression":{if("-"!==t.operator)return tP;const e=unwrapTsExpression2(t.argument);return"Literal"===e?.type&&"number"==typeof e.value&&Number.isFinite(e.value)?-e.value:tP}case"ArrayExpression":return(t.elements??[]).map(e=>null==e||"SpreadElement"===e.type?tP:readStaticValue(e));case"ObjectExpression":{const e={};for(const n of t.properties??[]){if("Property"!==n?.type||n.computed)return tP;const t=readPropertyKeyName2(n.key);if(null===t)return tP;Object.defineProperty(e,t,{value:readStaticValue(n.value),enumerable:!0,configurable:!0})}return e}default:return tP}}function readStaticString(e){const t=null==e?tP:readStaticValue(e);return"string"==typeof t?t:null}function isPlainRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!isUnresolvedValue(e)}function containsUnresolvedValue(e){return!!isUnresolvedValue(e)||(Array.isArray(e)?e.some(containsUnresolvedValue):"object"==typeof e&&null!==e&&Object.values(e).some(containsUnresolvedValue))}function statementSpanWithSemicolon(e,t){const n=toSourceSpan(t)??{start:0,end:0};if(";"===e[n.end-1])return n;let r=n.end;for(;r<e.length&&(" "===e[r]||"\t"===e[r]);)r++;return";"===e[r]?{start:n.start,end:r+1}:n}function unwrapTsExpression2(e){let t=e;for(;"TSSatisfiesExpression"===t?.type||"TSAsExpression"===t?.type||"TSNonNullExpression"===t?.type||"ParenthesizedExpression"===t?.type;)t=t.expression;return t}function readPropertyKeyName2(e){if("Identifier"===e?.type)return e.name;if("Literal"===e?.type){if("string"==typeof e.value)return e.value;if("number"==typeof e.value)return String(e.value)}return null}function getObjectProperty2(e,t){if("ObjectExpression"!==e?.type)return null;for(const n of e.properties??[])if("Property"===n?.type&&!n.computed&&readPropertyKeyName2(n.key)===t)return n;return null}function toSourceSpan(e){return"number"==typeof e?.start&&Number.isFinite(e.start)&&"number"==typeof e?.end&&Number.isFinite(e.end)?{start:e.start,end:e.end}:void 0}function walk2(e,t,n=new Set){if(e&&"object"==typeof e&&!n.has(e)){n.add(e),"string"==typeof e.type&&t(e);for(const r of Object.values(e))if(r&&"object"==typeof r)if(Array.isArray(r))for(const e of r)walk2(e,t,n);else walk2(r,t,n)}}function ensureNamedDefaultExport(e){const{program:t,errors:n}=parseAssetProgram(e.filePath,e.source);if(!t)return failure("not_definable",n[0]?.message??"asset source has syntax errors");const r=(t.body??[]).find(e=>"ExportDefaultDeclaration"===e?.type);if(!r)return failure("export_not_found",`no default export in ${e.filePath}`);const s=r.declaration,i="FunctionDeclaration"===s?.type||"ClassDeclaration"===s?.type;if(i&&"string"==typeof s.id?.name)return{ok:!0,source:e.source,changed:!1,bindingName:s.id.name};if(!i){const t=unwrapTsExpression2(s);if("Identifier"===t?.type)return{ok:!0,source:e.source,changed:!1,bindingName:t.name}}const o=toSourceSpan(r),a=toSourceSpan(s);if(!o||!a)return failure("not_definable","default export has no source span");const c=pickAvailableName(deriveDefaultExportName(e.filePath),collectIdentifierNames(t));if(void 0===c)return failure("not_definable","could not derive a free identifier for the default export");const l=detectNewline(e.source);let d;if(i){const t=e.source.slice(a.start,a.start+64),n="FunctionDeclaration"===s.type?t.match(/^(?:async\s+)?function(?:\s*\*)?/):t.match(/^class\b/);if(!n)return failure("not_definable","unsupported default export shape");const r=a.start+n[0].length;let i=r;for(;i<e.source.length&&/\s/.test(e.source[i]??"");)i++;const u="("===e.source[i]?` ${c}`:` ${c} `;d=[{start:o.start,end:a.start,value:""},{start:r,end:i,value:u},{start:o.end,end:o.end,value:`${l}export default ${c};`}]}else d=[{start:o.start,end:a.start,value:`const ${c} = `},{start:a.end,end:o.end,value:`;${l}export default ${c};`}];return{...applyEdits(e.source,d),bindingName:c}}function ensureAssetDeclaration(e){const{program:t,errors:n}=parseAssetProgram(e.filePath,e.source);if(!t)return failure("not_definable",n[0]?.message??"asset source has syntax errors");const r=parseAssetFile(e.filePath,e.source);if(r.declarations.some(t=>t.bindingName===e.bindingName))return{ok:!0,source:e.source,changed:!1};const s=readAssetImports(t);if(hasTopLevelDefineAssetCallFor(t,s.trustedDefineAssetNames,e.bindingName))return failure("config_not_editable",`an existing defineAsset declaration for "${e.bindingName}" has structural errors — fix it instead of adding another`);const i=collectTopLevelScope(t).bindings.get(e.bindingName);if(!i){const t=s.importedBindings.get(e.bindingName);return failure("not_definable",void 0!==t?`"${e.bindingName}" is imported from "${t}" — defineAsset must live in the file that defines the component`:`no top-level binding "${e.bindingName}" in ${e.filePath}`)}const o=detectCodeStyle(e.source),a=[];let c;if(s.trustedDefineAssetNames.size>0)c=s.trustedDefineAssetNames.values().next().value;else{const n=collectIdentifierNames(t);if(n.has("defineAsset")){const e=pickAvailableName("defineAsset",n);if(void 0===e)return failure("not_definable","could not derive a free identifier for the defineAsset import");c=e}else c="defineAsset";const r="defineAsset"===c?"defineAsset":`defineAsset as ${c}`,i=`import { ${r} } from ${quoteString(rP,o.quote)};`;a.push(buildImportInsertionEdit(e.source,s.importDeclarationSpans,i,o.newline))}const l=serializeDefineAssetCall(c,e.bindingName,e.initialConfig??{},o),d=statementInsertionOffset(e.source,i.statementSpan.end);return a.push({start:d,end:d,value:`${o.newline}${o.newline}${l}`}),applyEdits(e.source,a)}function addLibraries(e){const t=locateDeclaration(e);if(!t.ok)return t;const{declaration:n}=t,r=[];for(const t of e.libraries)""!==t&&(n.libraries.includes(t)||r.includes(t)||r.push(t));if(0===r.length)return{ok:!0,source:e.source,changed:!1};const s=detectCodeStyle(e.source),i=r.map(e=>quoteString(e,s.quote)).join(", "),o=n.spans;if(o.libraries){const t=o.libraryItems[o.libraryItems.length-1];if(t)return applyEdits(e.source,[{start:t.end,end:t.end,value:`, ${i}`}]);const n=e.source.slice(o.libraries.start+1,o.libraries.end-1),r=o.libraries.start+1,s=""===n.trim()?i:`${i}, `;return applyEdits(e.source,[{start:r,end:r,value:s}])}return o.librariesProperty?failure("config_not_editable",`the libraries property of "${e.bindingName}" is not an editable array literal`):applyEdits(e.source,[insertConfigProperty(e.source,o.config,`libraries: [${i}]`,s)])}function removeLibraries(e){const t=new Set(e.libraries.filter(e=>""!==e));let n=locateDeclaration(e);if(!n.ok)return n;if(t.size>0&&n.declaration.spans.librariesProperty&&!n.declaration.spans.libraries)return failure("config_not_editable",`the libraries property of "${e.bindingName}" is not an editable array literal`);let r=e.source,s=!1;for(let i=0;i<32;i++){const i=n.declaration,o=[];if(i.libraries.forEach((e,n)=>{const s=i.spans.libraryItems[n];t.has(e)&&s&&o.push(expandListItemRemoval(r,s))}),0===o.length)break;r=spliceRemovals(r,o),s=!0;const a=locateDeclaration({...e,source:r});if(!a.ok)return a;n=a}if(s){const e=n.declaration.spans;e.libraries&&e.librariesProperty&&/^\s*$/.test(r.slice(e.libraries.start+1,e.libraries.end-1))&&(r=spliceRemovals(r,[expandListItemRemoval(r,e.librariesProperty)]))}return{ok:!0,source:r,changed:s}}function locateDeclaration(e){const{program:t,errors:n}=parseAssetProgram(e.filePath,e.source);if(!t)return failure("config_not_editable",n[0]?.message??"asset source has syntax errors");const r=parseAssetFile(e.filePath,e.source),s=r.declarations.find(t=>t.bindingName===e.bindingName);if(s)return{ok:!0,declaration:s};const i=readAssetImports(t);return hasTopLevelDefineAssetCallFor(t,i.trustedDefineAssetNames,e.bindingName)?failure("config_not_editable",`the defineAsset declaration for "${e.bindingName}" has structural errors and cannot be edited`):failure("asset_not_found",`no defineAsset declaration for "${e.bindingName}" in ${e.filePath}`)}function failure(e,t){return{ok:!1,code:e,message:t}}function applyEdits(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e.length+1,s=e;for(const e of n){if(e.start<0||e.end<e.start||e.end>r)throw new Error(`Invalid overlapping asset source edit ${e.start}:${e.end}`);s=s.slice(0,e.start)+e.value+s.slice(e.end),r=e.start}return{ok:!0,source:s,changed:s!==e}}function spliceRemovals(e,t){const n=[...t].sort((e,t)=>e.start-t.start),r=[];for(const e of n){const t=r[r.length-1];t&&e.start<=t.end?t.end=Math.max(t.end,e.end):r.push({...e})}let s=e;for(let e=r.length-1;e>=0;e--){const t=r[e];s=s.slice(0,t.start)+s.slice(t.end)}return s}function expandListItemRemoval(e,t){let{start:n,end:r}=t,s=r;for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(","===e[s]){for(r=s+1;r<e.length&&(" "===e[r]||"\t"===e[r]);)r++;return expandBlankLine(e,{start:n,end:r})}let i=n;for(;i>0&&/\s/.test(e[i-1]??"");)i--;if(","===e[i-1])return{start:i-1,end:r};for(;n>0&&/\s/.test(e[n-1]??"");)n--;for(;r<e.length&&/\s/.test(e[r]??"");)r++;return{start:n,end:r}}function expandBlankLine(e,t){const n=e.lastIndexOf("\n",t.start-1)+1;return/^[ \t]*$/.test(e.slice(n,t.start))?e.startsWith("\r\n",t.end)?{start:n,end:t.end+2}:"\n"===e[t.end]?{start:n,end:t.end+1}:t:t}function insertConfigProperty(e,t,n,r){const s=t.end-1;let i=s;for(;i>t.start+1&&/\s/.test(e[i-1]??"");)i--;const o=e[i-1]??"",a=e.slice(t.start,t.end).includes("\n");if(!a)return"{"===o?{start:i,end:s,value:` ${n} `}:{start:i,end:i,value:","===o?` ${n}`:`, ${n}`};if("{"===o){const s=lineIndentAt(e,t.start);return{start:i,end:i,value:`${r.newline}${s}${r.indent}${n},`}}const c=lineIndentAt(e,i);return{start:i,end:i,value:`${","===o?"":","}${r.newline}${c}${n},`}}function buildImportInsertionEdit(e,t,n,r){const s=t[t.length-1];if(s)return{start:s.end,end:s.end,value:`${r}${n}`};const i=topLevelInsertionOffset(e),o=e[i]??"",a=i>0?r:"",c="\n"===o||"\r"===o||""===o?r:`${r}${r}`;return{start:i,end:i,value:`${a}${n}${c}`}}function topLevelInsertionOffset(e){let t=0;if(e.startsWith("#!")){const n=e.indexOf("\n");t=n>=0?n+1:e.length}for(;;){const n=e.indexOf("\n",t),r=n>=0?n+1:e.length,s=e.slice(t,r).trim();if(!/^["']use [^"']+["'];?$/.test(s))break;t=r}return t}function statementInsertionOffset(e,t){let n=t;for(;n<e.length&&(" "===e[n]||"\t"===e[n]);)n++;if("/"===e[n]&&"/"===e[n+1]){for(;n<e.length&&"\n"!==e[n]&&"\r"!==e[n];)n++;return n}return t}function serializeDefineAssetCall(e,t,n,r){const s=[];if(void 0!==n.usageInstructions&&s.push(["usageInstructions",n.usageInstructions]),void 0!==n.libraries&&s.push(["libraries",n.libraries]),void 0!==n.variants&&s.push(["variants",n.variants]),0===s.length)return`${e}(${t}, {});`;const i=s.map(([e,t])=>`${r.indent}${e}: ${serializeStaticValue(t,r,1)},`).join(r.newline);return`${e}(${t}, {${r.newline}${i}${r.newline}});`}function serializeStaticValue(e,t,n){if(isUnresolvedValue(e))throw new Error("ensureAssetDeclaration initialConfig values must be fully static");if(null===e)return"null";if("string"==typeof e)return quoteString(e,t.quote);if("number"==typeof e||"boolean"==typeof e)return String(e);if(Array.isArray(e)){if(0===e.length)return"[]";if(e.every(isPrimitiveStaticValue))return`[${e.map(e=>serializeStaticValue(e,t,n)).join(", ")}]`;const r=e.map(e=>`${t.indent.repeat(n+1)}${serializeStaticValue(e,t,n+1)},`).join(t.newline);return`[${t.newline}${r}${t.newline}${t.indent.repeat(n)}]`}const r=Object.entries(e);if(0===r.length)return"{}";if(r.every(([,e])=>isPrimitiveStaticValue(e)))return`{ ${r.map(([e,r])=>`${serializeObjectKey(e,t)}: ${serializeStaticValue(r,t,n)}`).join(", ")} }`;const s=r.map(([e,r])=>`${t.indent.repeat(n+1)}${serializeObjectKey(e,t)}: ${serializeStaticValue(r,t,n+1)},`).join(t.newline);return`{${t.newline}${s}${t.newline}${t.indent.repeat(n)}}`}function isPrimitiveStaticValue(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function serializeObjectKey(e,t){return/^[A-Za-z_$][\w$]*$/.test(e)?e:quoteString(e,t.quote)}function quoteString(e,t){const n=JSON.stringify(e);if('"'===t)return n;const r=n.slice(1,-1).replace(/\\"/g,'"').replace(/'/g,"\\'");return`'${r}'`}function detectCodeStyle(e){const t=(e.match(/"/g)??[]).length,n=(e.match(/'/g)??[]).length;let r=!1,s=Number.POSITIVE_INFINITY;for(const t of e.split("\n")){const e=t.match(/^([ \t]+)\S/);if(e){if(e[1].includes("\t")){r=!0;break}s=Math.min(s,e[1].length)}}return{quote:n>t?"'":'"',indent:r?"\t":Number.isFinite(s)?" ".repeat(s):" ",newline:detectNewline(e)}}function detectNewline(e){return e.includes("\r\n")?"\r\n":"\n"}function lineIndentAt(e,t){const n=Math.max(e.lastIndexOf("\n",t-1)+1,0),r=e.slice(n,t);return r.match(/^[ \t]*/)?.[0]??""}function pickAvailableName(e,t){if(!t.has(e))return e;for(let n=2;n<1e4;n++){const r=`${e}${n}`;if(!t.has(r))return r}}function deriveDefaultExportName(e){const t=e.replace(/\\/g,"/"),n=t.split("/").filter(Boolean),r=n[n.length-1]??"";if(/^index\.canvas\.[tj]sx?$/.test(r)){const e=n[n.length-2]??"",t=pascalCase(e);return""===t?"Canvas":`${t}Canvas`}const s=pascalCase(r.replace(/\.[tj]sx?$/,""));return""===s?"DefaultExport":/^[0-9]/.test(s)?`Component${s}`:s}function pascalCase(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function makeAssetKey(e,t){return`${e}#${t}`}function parseAssetKey(e){const t=e.lastIndexOf("#");if(!(t<=0||t===e.length-1))return{filePath:e.slice(0,t),bindingName:e.slice(t+1)}}import{readFileSync as sP,statSync as iP}from"fs";import oP from"path";import{readdir as aP,readFile as cP}from"fs/promises";import lP from"path";import dP from"typescript";import{readdir as uP,readFile as pP}from"fs/promises";import hP from"path";var mP=[".tsx",".ts",".jsx",".js",".astro"],fP="defineAsset";function hasAssetSourceExtension(e){return mP.some(t=>e.endsWith(t))}function sourceMayDeclareAssets(e){return e.includes(fP)||e.includes("defineControls")||e.includes("defineAstroControls")}var gP=new Set(["node_modules","dist","build"]);function isIgnoredSegment(e){return gP.has(e)||e.startsWith(".")&&"."!==e&&".."!==e}function isIgnoredWorkspacePath(e){return e.replace(/\\/g,"/").split("/").some(isIgnoredSegment)}async function scanRepo(e){const t=[];async function walk4(n){let r;try{r=await uP(n,{withFileTypes:!0})}catch{return}for(const s of r){if(isIgnoredSegment(s.name))continue;const r=hP.join(n,s.name);if(s.isDirectory()){await walk4(r);continue}if(!s.isFile()||!hasAssetSourceExtension(s.name))continue;let i;try{i=await pP(r,"utf8")}catch{continue}sourceMayDeclareAssets(i)&&t.push({filePath:hP.relative(e,r).replace(/\\/g,"/"),source:i})}}return await walk4(e),t.sort((e,t)=>e.filePath.localeCompare(t.filePath))}function resolveProjectModule(e,t,n="index.ts"){const r="/__tempo_workspace__/",read2=t=>t.startsWith(r)?e.readFile(t.slice(r.length))??void 0:void 0,s={fileExists:e=>void 0!==read2(e),readFile:read2},i=dP.findConfigFile(lP.posix.dirname(r+n),s.fileExists,"tsconfig.json");let o={moduleResolution:dP.ModuleResolutionKind.Bundler,allowJs:!0};if(i){const e=dP.readConfigFile(i,read2);e.error||(o={...o,...dP.parseJsonConfigFileContent(e.config,{...s,useCaseSensitiveFileNames:!0,readDirectory:()=>[]},lP.posix.dirname(i)).options})}const a=dP.resolveModuleName(t,r+n,o,s).resolvedModule?.resolvedFileName;return a?.startsWith(r)?a.slice(r.length):null}function definesVueComponent(e,t,n){if(!/\.[cm]?[jt]sx?$/.test(t)||t.endsWith(".d.ts"))return!1;const r=e.readFile(t);if(null===r)return!1;const s=dP.createSourceFile(t,r,dP.ScriptTarget.Latest,!0,/x$/.test(t)?dP.ScriptKind.TSX:dP.ScriptKind.TS),i=new Set,o=new Set,a=new Map;let c=null;for(const e of s.statements)if(dP.isImportDeclaration(e)){const t=e.moduleSpecifier,n=e.importClause?.namedBindings;if(!dP.isStringLiteral(t)||"vue"!==t.text||!n)continue;if(dP.isNamespaceImport(n))o.add(n.name.text);else for(const e of n.elements)"defineComponent"===(e.propertyName??e.name).text&&i.add(e.name.text)}else if(dP.isVariableStatement(e)){const t=e.modifiers?.some(e=>e.kind===dP.SyntaxKind.ExportKeyword);for(const r of e.declarationList.declarations)dP.isIdentifier(r.name)&&r.initializer&&(a.set(r.name.text,r.initializer),t&&r.name.text===n&&(c=r.initializer))}else if(dP.isExportAssignment(e)&&!e.isExportEquals&&"default"===n)c=e.expression;else if(dP.isExportDeclaration(e)&&!e.moduleSpecifier&&e.exportClause&&dP.isNamedExports(e.exportClause))for(const t of e.exportClause.elements)t.name.text===n&&(c=dP.factory.createIdentifier((t.propertyName??t.name).text));c??=a.get(n)??null;for(let e=0;c&&e<8;e+=1)if(dP.isIdentifier(c))c=a.get(c.text)??null;else{if(!(dP.isParenthesizedExpression(c)||dP.isAsExpression(c)||dP.isSatisfiesExpression(c)||dP.isNonNullExpression(c)))break;c=c.expression}if(!c||!dP.isCallExpression(c))return!1;const l=c.expression;return dP.isIdentifier(l)?i.has(l.text):dP.isPropertyAccessExpression(l)&&dP.isIdentifier(l.expression)&&o.has(l.expression.text)&&"defineComponent"===l.name.text}function installedPackageFramework(e,t,n){const r=n?.match(/^node_modules\/((?:@[^/]+\/)?[^/]+)\//)?.[1],s=r??(t.startsWith("pkg:")&&null===n?parsePackageSpecifier(t.slice(4)).packageName:null);if(!s)return null;const i=e.readFile(`node_modules/${s}/package.json`);if(null===i)return null;let o;try{const e=JSON.parse(i);o={...e.dependencies,...e.peerDependencies}}catch{return null}const writesFor=e=>void 0!==o[e];return!writesFor("vue")||writesFor("react")||writesFor("react-dom")?null:"vue"}var yP=4;function posixDirname(e){const t=e.lastIndexOf("/");return-1===t?".":e.slice(0,t)}function isRelativeSpecifier(e){return e.startsWith("./")||e.startsWith("../")}function resolveRelativeImport(e,t){const n="."===e?t:`${e}/${t}`,r=[];for(const e of n.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.length>0&&".."!==r[r.length-1]?r.pop():r.push(".."));return r.join("/")}var bP=[".tsx",".ts",".jsx",".js",".astro"],vP=Object.values(Gb).flatMap(e=>e.uiFramework&&e.componentFileExtension?[e.componentFileExtension]:[]);function isSingleFileComponent(e){return vP.some(t=>e.endsWith(t))}function moduleFileCandidates(e){if(e=componentImportPath(e),e.endsWith(".ts")||e.endsWith(".tsx")||isSingleFileComponent(e))return[e];if(e.endsWith(".js")){const t=e.slice(0,-3);return[`${t}.ts`,`${t}.tsx`,e]}return e.endsWith(".jsx")?[`${e.slice(0,-4)}.tsx`,e]:[...bP.map(t=>`${e}${t}`),...bP.map(t=>`${e}/index${t}`)]}function resolveModuleFilePath(e,t){const n=t.replace(/^\.\//,"");if(""===n||n.startsWith("../"))return null;for(const t of moduleFileCandidates(n))if(null!=e(t))return t;return null}var wP=2e3,_P=6;function parsePnpmWorkspacePatterns(e){const t=e.split(/\r?\n/),n=[];let r=!1;for(const e of t){if(/^packages\s*:\s*$/.test(e)){r=!0;continue}if(!r)continue;const t=e.trim();if(""===t||t.startsWith("#"))continue;const s=/^-\s*(.+)$/.exec(t);if(!s)break;const i=s[1].replace(/\s+#.*$/,"").trim().replace(/^["']|["']$/g,"");""===i||i.startsWith("!")||n.push(i)}return n}function globSegmentToRegExp(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,"[^/]*");return new RegExp(`^${t}$`)}async function loadPnpmWorkspacePackages(e){let t;try{t=await cP(lP.join(e,"pnpm-workspace.yaml"),"utf-8")}catch{return{}}const n={};let r=0;async function listSubdirectories(t){if(r>=wP)return[];let n;r++;try{n=await aP(lP.join(e,t),{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(e=>e.name).filter(e=>!isIgnoredWorkspacePath(e))}async function recordPackageAt(t){let r;try{r=await cP(lP.join(e,t,"package.json"),"utf-8")}catch{return}try{const e=JSON.parse(r).name;"string"!=typeof e||""===e||e in n||(n[e]=t.replace(/\\/g,"/"))}catch{}}async function expand(e,t,n){if(n>_P)return;if(0===t.length)return void(""!==e&&await recordPackageAt(e));const[r,...s]=t;if("**"!==r){if(r.includes("*")){const t=globSegmentToRegExp(r);for(const r of await listSubdirectories(e))t.test(r)&&await expand(joinRelative(e,r),s,n+1);return}await expand(joinRelative(e,r),s,n+1)}else{await expand(e,s,n);for(const r of await listSubdirectories(e))await expand(joinRelative(e,r),t,n+1)}}for(const e of parsePnpmWorkspacePatterns(t))await expand("",e.split("/").filter(Boolean),0);return n}function joinRelative(e,t){return""===e?t:`${e}/${t}`}function parsePackageSpecifier(e){const t=e.split("/"),n=e.startsWith("@")?2:1,r=t.slice(0,n).join("/"),s=t.slice(n).join("/");return""===s?{packageName:r}:{packageName:r,subpath:s}}function collectExportTargets(e,t=0){return"string"==typeof e?[e]:t>=3||null===e||"object"!=typeof e?[]:Object.values(e).flatMap(e=>collectExportTargets(e,t+1))}function resolvePackageEntryFile(e,t){const{packageName:n,subpath:r}=parsePackageSpecifier(t),s=e.workspacePackages?.[n];if(void 0===s)return resolveProjectModule(e,t);if(void 0!==r)return resolveModuleFilePath(e.readFile,`${s}/${r}`);const i=e.readFile(`${s}/package.json`);if(null!=i){let t;try{t=JSON.parse(i)}catch{t=void 0}if(t){const n=t.exports,r="string"==typeof n?n:null!=n&&"object"==typeof n?n["."]:void 0,i=[...collectExportTargets(r),..."string"==typeof t.module?[t.module]:[],..."string"==typeof t.main?[t.main]:[]];for(const t of i){const n=resolveModuleFilePath(e.readFile,`${s}/${t.replace(/^\.\//,"")}`);if(null!==n)return n}}}return resolveModuleFilePath(e.readFile,`${s}/index`)??resolveModuleFilePath(e.readFile,`${s}/src/index`)}function patternDeclaresName(e,t){return!(!e||"object"!=typeof e)&&("Identifier"===e.type?e.name===t:"ObjectPattern"===e.type?(e.properties??[]).some(e=>patternDeclaresName(e?.value??e?.argument,t)):"ArrayPattern"===e.type?(e.elements??[]).some(e=>patternDeclaresName(e,t)):"AssignmentPattern"===e.type?patternDeclaresName(e.left,t):"RestElement"===e.type&&patternDeclaresName(e.argument,t))}function declarationDeclaresName(e,t){return"FunctionDeclaration"===e?.type||"ClassDeclaration"===e?.type||"TSEnumDeclaration"===e?.type?e.id?.name===t:"VariableDeclaration"===e?.type&&(e.declarations??[]).some(e=>patternDeclaresName(e?.id,t))}function specifierName(e){return e?.name??e?.value}function findExportInProgram(e,t){const n=[];for(const r of e?.body??[]){if("ExportDefaultDeclaration"===r?.type){if("default"!==t)continue;const e=unwrapTsExpression2(r.declaration);return"Identifier"===e?.type?{finding:{type:"local",localName:e.name},starSources:n}:{finding:{type:"defined",localName:e?.id?.name??t},starSources:n}}if("ExportNamedDeclaration"!==r?.type)"ExportAllDeclaration"===r?.type&&null==r.exported&&"string"==typeof r.source?.value&&"default"!==t&&n.push(r.source.value);else{if(r.declaration&&declarationDeclaresName(r.declaration,t))return{finding:{type:"defined",localName:t},starSources:n};for(const e of r.specifiers??[]){if("ExportSpecifier"!==e?.type)continue;if(specifierName(e.exported)!==t)continue;const s=specifierName(e.local);if("string"==typeof s)return"string"==typeof r.source?.value?{finding:{type:"reexport",specifier:r.source.value,sourceName:s},starSources:n}:{finding:{type:"local",localName:s},starSources:n}}}}return{finding:null,starSources:n}}function followExportChain(e,t,n,r,s){const i=`${t}#${n}`;if(s.has(i))return null;s.add(i);const o=e.readFile(t);if(null==o)return null;if(isSingleFileComponent(t)&&"default"===n)return{filePath:t,name:"default"};const{program:a}=(e.parseProgram??parseAssetProgram)(t,o);if(!a)return null;const{finding:c,starSources:l}=findExportInProgram(a,n),hop=(n,i)=>{if(r<=0)return null;const o=resolveChainSpecifier(e,t,n);return null===o?null:followExportChain(e,o,i,r-1,s)};if("defined"===c?.type)return{filePath:t,name:c.localName??n};if("reexport"===c?.type)return hop(c.specifier,c.sourceName);if("local"===c?.type){const e=readAssetImports(a).referenceableImports.get(c.localName);return e?hop(e.importSpecifier,e.importedName):{filePath:t,name:c.localName}}for(const e of l){const t=hop(e,n);if(null!==t)return t}return null}function resolveChainSpecifier(e,t,n){return isRelativeSpecifier(n)?resolveModuleFilePath(e.readFile,resolveRelativeImport(posixDirname(t),n)):resolvePackageEntryFile(e,n)}function resolveComponentIdentity(e,t,n,r){const s=t.startsWith("pkg:")?resolvePackageEntryFile(e,t.slice(4))??resolveProjectModule(e,t.slice(4),r):resolveModuleFilePath(e.readFile,t);return s?followExportChain(e,s,n,yP,new Set):null}function resolveComponentFilePath(e,t,n){return resolveComponentIdentity(e,t,n)?.filePath??(t.startsWith("pkg:")?null:resolveModuleFilePath(e.readFile,t))}function canvasPointerDocLine(e){return`The canvas for this component is at ${e}/index.canvas.tsx. If you adjust this component in any way, ensure the canvas and its asset declaration stay consistent.`}function escapeRegExp3(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function verifyCanvasPointer(e,t,n){const r=n.canvasPath;if(void 0===r)return{warnings:[]};const s=parseAssetKey(n.key)?.bindingName;if(void 0===s)return{warnings:[]};const unverified2=e=>({warnings:[{code:"canvas_pointer_unverified",severity:"info",message:`canvas pointer not verified for "${n.key}": ${e}`}]}),i=resolveComponentFilePath(e,n.filePath,s);if(null===i)return unverified2(`could not resolve the component's defining file from "${n.filePath}"`);const o=e.readFile(i),a=null==o?null:(e.readComments??readSourceComments)(i,o);if(null===a)return{componentFilePath:i,warnings:unverified2(`could not read comments in "${i}"`).warnings};const c=new RegExp(`${escapeRegExp3(t)}/[\\w@./-]+`,"g");let l=!1;const d=[];for(const e of a)for(const t of e.value.matchAll(c)){const e=t[0].replace(/[.,;:]+$/,"");e===r||e.startsWith(`${r}/`)?l=!0:d.includes(e)||d.push(e)}return l?{componentFilePath:i,warnings:[]}:d.length>0?{componentFilePath:i,warnings:[{code:"stale_canvas_pointer",severity:"degraded",message:`"${i}" has a canvas-pointer comment naming "${d[0]}", but this component is declared on "${r}" — update the comment to: ${canvasPointerDocLine(r)}`}]}:{componentFilePath:i,warnings:[{code:"missing_canvas_pointer",severity:"degraded",message:`"${i}" has no comment mentioning its canvas — add a docstring line to the component's documentation: ${canvasPointerDocLine(r)}`}]}}import{createHash as xP}from"crypto";import{posix as TP}from"path";import{createRequire as kP}from"module";import SP from"path";import{fileURLToPath as EP}from"url";var AP="@tempo-home",CP=`// ${AP} — Tempo home canvas (the workspace Run button opens this). Managed marker; do not remove.`;function sourceHasHomeMarker(e){return e.includes(AP)}var IP=600,PP=400,DP=50,RP=3e3;function overlapsWithSpacing(e,t,n){return!(e.x+e.width+n<=t.x||t.x+t.width+n<=e.x||e.y+e.height+n<=t.y||t.y+t.height+n<=e.y)}function hasOverlap(e,t,n){return e.some(e=>overlapsWithSpacing(e,t,n))}function findOpenPosition(e,t,n,r,s){if(0===e.length)return{x:0,y:0};const i=Math.max(...e.map(e=>e.x+e.width)),o=Math.max(...e.map(e=>e.y+e.height)),a=i+r,c=0;if(a+t<=s){const s={x:a,y:c,width:t,height:n};if(!hasOverlap(e,s,r))return{x:a,y:c}}return{x:0,y:o+r}}function computeStoryboardPositions(e){const t=e.spacing??DP,n=e.maxRowWidth??RP,r=[...e.existing],s=[];for(const i of e.newStoryboards){const e=Number.isFinite(i.width)?Math.max(1,Math.round(i.width)):IP,o=Number.isFinite(i.height)?Math.max(1,Math.round(i.height)):PP,a=findOpenPosition(r,e,o,t,n);r.push({x:a.x,y:a.y,width:e,height:o}),s.push({name:i.name,x:a.x,y:a.y,width:e,height:o})}return s}var NP="undefined"!=typeof __filename?__filename:EP(import.meta.url),OP=SP.dirname(NP),FP=kP(NP);function loadParseSync(){try{const e=FP("oxc-parser");return e.parseSync}catch{const e=[SP.resolve(OP,"../../modules/file-parser/node_modules/oxc-parser"),SP.resolve(OP,"../../../../node_modules/.pnpm/node_modules/oxc-parser"),SP.resolve(process.cwd(),"../../node_modules/.pnpm/node_modules/oxc-parser")];for(const t of e)try{const e=FP(t);return e.parseSync}catch{continue}throw new Error("Unable to resolve oxc-parser for canvas page parsing")}}var LP=loadParseSync(),MP={x:0,y:0,width:600,height:400};function hasReactCanvasDeclaration(e){return void 0!==e.canvasElementSpan}function toLegacyLayoutSpans(e){if(e?.x&&e.y&&"number"==typeof e.layoutClose)return{x:e.x,y:e.y,width:e.width,height:e.height,...e.zIndex?{zIndex:e.zIndex}:{},layoutClose:e.layoutClose}}function adaptReactCanvasPage(e,t){const n=parseCanvasFile(e,t);return hasReactCanvasDeclaration(n)?{filePath:e,canvasFormat:"react",...n.canvasPath?{canvasPath:n.canvasPath}:{},pageName:n.pageName,home:sourceHasHomeMarker(t),...void 0!==n.backgroundColor?{backgroundColor:n.backgroundColor}:{},storyboards:n.storyboards.map((e,t)=>{const n=e.storyboardKey||`__invalid_react_storyboard_${t}`,r=componentFrameworkForStoryboard(e);return{exportName:n,canvasFormat:"react",storyboardKey:e.storyboardKey,...r?{uiFramework:r}:{},displayName:e.displayName,layout:e.layout,isRoute:"route"===e.kind,..."html"===e.kind?{isHtml:!0}:{},...e.route?{route:e.route}:{},...e.filepath?{filepath:e.filepath}:{},...e.vrt?{vrt:!0,vrtConfig:e.vrt}:{},...e.responsive?{responsive:!0}:{},...e.preview?{preview:e.preview}:{},layoutSpans:toLegacyLayoutSpans(e.layoutSpans),...e.errors.length>0?{error:e.errors.map(e=>e.message).join("; ")}:{},exportSpan:e.jsxElementSpan,...e.component?.expression?{componentExpression:e.component.expression}:{},...e.component?.import?{componentImport:{localName:e.component.import.localName,specifier:e.component.import.source,span:e.component.import.declarationSpan}}:{}}}),errors:n.errors.map(e=>({message:e.message,kind:e.kind}))}:null}function isObjectExpression(e){return e&&"ObjectExpression"===e.type&&Array.isArray(e.properties)}function toIdentifierName(e){return e?"Identifier"===e.type?e.name:"Literal"===e.type&&"string"==typeof e.value?e.value:null:null}function getObjectProperty3(e,t){if(!isObjectExpression(e))return null;for(const n of e.properties){if(!n||"Property"!==n.type)continue;const e=toIdentifierName(n.key);if(e===t)return n}return null}function readStringLiteral(e,t,n){if("Literal"===e?.type&&"string"==typeof e.value)return e.value;throw new Error(`Non-literal \`${t}\` property in "${n}" — ${t} must be a string literal`)}function readNumberLiteral2(e,t,n){if("Literal"===e?.type&&"number"==typeof e.value&&Number.isFinite(e.value))return{value:e.value,start:e.start,end:e.end};if("UnaryExpression"===e?.type&&"-"===e.operator&&"Literal"===e.argument?.type&&"number"==typeof e.argument.value&&Number.isFinite(e.argument.value))return{value:-e.argument.value,start:e.start,end:e.end};throw new Error(`Layout values must be number literals, found non-literal value for \`${t}\` in "${n}"`)}function readLayout2(e,t,n){const r=getObjectProperty3(e,"layout");if(!r)throw new Error(`Missing required \`layout\` property in "${t}"`);if(!isObjectExpression(r.value))throw new Error(`Storyboard "${t}" has invalid \`layout\` shape`);const s=getObjectProperty3(r.value,"x"),i=getObjectProperty3(r.value,"y"),o=getObjectProperty3(r.value,"width"),a=getObjectProperty3(r.value,"height"),c=Boolean(o&&a),l=!s||!i,d=!n&&!c,u=l||d;if(u)throw new Error(`Storyboard "${t}" layout must include x, y, width, and height`);const p=readNumberLiteral2(s.value,"x",t),m=readNumberLiteral2(i.value,"y",t),f=getObjectProperty3(r.value,"zIndex"),g=f?readNumberLiteral2(f.value,"zIndex",t):null,y=getObjectProperty3(r.value,"intrinsicSizing"),b=y?readStringLiteral(y.value,"layout.intrinsicSizing",t):null;if(null!==b&&"root-element"!==b)throw new Error(`Storyboard "${t}" \`layout.intrinsicSizing\` must be "root-element" when set`);const v="root-element"===b,w=n&&(v||!c),x=n&&Boolean(o)!==Boolean(a)?"layout.width and layout.height must be set together":void 0,S=w?null:readNumberLiteral2(o.value,"width",t),E=w?null:readNumberLiteral2(a.value,"height",t),A=readNumber(r.value.end);if(null===A)throw new Error(`Storyboard "${t}" layout literal missing position info`);const C={x:{start:p.start,end:p.end},y:{start:m.start,end:m.end},...S?{width:{start:S.start,end:S.end}}:{},...E?{height:{start:E.start,end:E.end}}:{},...g?{zIndex:{start:g.start,end:g.end}}:{},layoutClose:A-1};return{layout:{x:p.value,y:m.value,...S?{width:S.value}:{},...E?{height:E.value}:{},...g?{zIndex:g.value}:{}},spans:C,...x?{error:x}:{}}}function readNumber(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function extractTypeName(e){if(!e||"TSTypeReference"!==e.type)return null;const t=e.typeName;return t?"Identifier"===t.type?t.name:"TSQualifiedName"===t.type&&"Identifier"===t.right?.type?t.right.name:null:null}function collectComponentImports(e){const t=new Map;for(const n of e){if("ImportDeclaration"!==n?.type)continue;const e=n.source?.value;if("string"!=typeof e)continue;const r={start:n.start,end:n.end};for(const s of n.specifiers??[]){const n=s?.local?.name;"string"==typeof n&&t.set(n,{localName:n,specifier:e,span:r})}}return t}function extractRenderIdentifier(e){if(!e||"ArrowFunctionExpression"!==e.type)return null;const t=e.body;if(!t||"JSXElement"!==t.type)return null;const n=t.openingElement?.name;return n&&"JSXIdentifier"===n.type&&"string"==typeof n.name?n.name:null}function collectVariableBindings(e){const t=new Map,collectFromVariableDeclaration=e=>{if(e&&"VariableDeclaration"===e.type)for(const n of e.declarations??[]){if("Identifier"!==n?.id?.type)continue;const e=n.id.name;t.set(e,{init:n.init,typeAnnotation:n.id.typeAnnotation?.typeAnnotation??null})}};for(const t of e)collectFromVariableDeclaration(t),"ExportNamedDeclaration"===t?.type&&"VariableDeclaration"===t.declaration?.type&&collectFromVariableDeclaration(t.declaration);return t}function resolvePageNameFromObject(e){if(!isObjectExpression(e))return null;const t=getObjectProperty3(e,"name");return t&&"Literal"===t.value?.type&&"string"==typeof t.value.value?t.value.value:null}function resolvePageBackgroundColorFromObject(e){const t=getObjectProperty3(e,"backgroundColor");if(!t||"number"!=typeof t.start||"number"!=typeof t.end)return null;const n={start:t.start,end:t.end};return"Literal"===t.value?.type&&"string"==typeof t.value.value&&"number"==typeof t.value.start&&"number"==typeof t.value.end?{value:t.value.value,valueSpan:{start:t.value.start,end:t.value.end},propertySpan:n}:{propertySpan:n}}function parseStoryboardFromBinding(e){const t=extractTypeName(e.binding.typeAnnotation),n="TempoStoryboard"===t,r="TempoRouteStoryboard"===t,s="TempoHtmlStoryboard"===t;if(!n&&!r&&!s)return null;try{if(!isObjectExpression(e.binding.init))throw new Error(`Could not parse storyboard export "${e.exportName}" — expected object literal`);const t=readLayout2(e.binding.init,e.exportName,n),i=getObjectProperty3(e.binding.init,"name"),o=i?readStringLiteral(i.value,"name",e.exportName):void 0;let a,c,l,d;if(r){const t=getObjectProperty3(e.binding.init,"route");if(!t)throw new Error(`Route storyboard "${e.exportName}" is missing required \`route\` property`);a=readStringLiteral(t.value,"route",e.exportName)}if(s){const t=getObjectProperty3(e.binding.init,"filepath");if(!t)throw new Error(`Html storyboard "${e.exportName}" is missing required \`filepath\` property`);d=readStringLiteral(t.value,"filepath",e.exportName)}if(n){const t=getObjectProperty3(e.binding.init,"render");if(!t)throw new Error(`Component storyboard "${e.exportName}" is missing required \`render\` property`);const n=extractRenderIdentifier(t.value);n&&(l=e.componentImports.get(n),(l||/^[A-Z]/.test(n))&&(c=n))}return{exportName:e.exportName,displayName:o,layout:t.layout,isRoute:r,...s?{isHtml:!0}:{},...a?{route:a}:{},...d?{filepath:d}:{},layoutSpans:t.spans,...t.error?{error:t.error}:{},...c?{componentExpression:c}:{},...l?{componentImport:l}:{}}}catch(t){const i=t instanceof Error?t.message:String(t);return{exportName:e.exportName,displayName:void 0,layout:n?{x:0,y:0}:MP,isRoute:r,...s?{isHtml:!0}:{},error:i}}}function collectStoryboardExports(e,t,n){const r=[],s=new Set,maybePushStoryboard=(e,t,i)=>{if(s.has(e))return;const o=parseStoryboardFromBinding({exportName:e,binding:t,componentImports:n});o&&(i&&(o.exportSpan=i),s.add(e),r.push(o))};for(const n of e){if("ExportNamedDeclaration"!==n?.type)continue;const e={start:n.start,end:n.end};if("VariableDeclaration"!==n.declaration?.type){if(Array.isArray(n.specifiers)&&!n.source)for(const r of n.specifiers){const n=toIdentifierName(r.local),s=toIdentifierName(r.exported??r.local);if(!n||!s)continue;const i=t.get(n);i&&maybePushStoryboard(s,i,e)}}else for(const r of n.declaration.declarations??[]){if("Identifier"!==r?.id?.type)continue;const n=t.get(r.id.name);n&&maybePushStoryboard(r.id.name,n,e)}}return r}function parsePageSource(e,t){const n=adaptReactCanvasPage(e,t);if(n)return n;const r=SP.basename(SP.dirname(e)),s=[],i=LP(e,t),o=Array.isArray(i.program?.body)?i.program.body:[],a=collectVariableBindings(o),c=collectComponentImports(o);let l=r,d=!1;const u=sourceHasHomeMarker(t);let p,m,f=null;for(const e of o){if("ExportDefaultDeclaration"!==e?.type)continue;const t=e.declaration;if(isObjectExpression(t))f=t;else if("Identifier"===t?.type){const e=a.get(t.name);e&&isObjectExpression(e.init)&&(f=e.init)}break}if(f){const e=resolvePageNameFromObject(f);e&&(l=e,d=!0);const t=resolvePageBackgroundColorFromObject(f);void 0!==t?.value&&(p=t.value);const n=readNumber(f.end);null!==n&&(m={pageObjectClose:n-1,...t?.valueSpan?{backgroundColor:t.valueSpan}:{},...t?.propertySpan?{backgroundColorProperty:t.propertySpan}:{}})}d||s.push({message:"Canvas default export name could not be parsed; falling back to canvas folder name",kind:"degraded"});const g=collectStoryboardExports(o,a,c);for(const e of g)e.error&&s.push({exportName:e.exportName,message:e.error,kind:"degraded"});return{filePath:e,pageName:l,home:u,...void 0!==p?{backgroundColor:p}:{},...m?{pageConfigSpans:m}:{},storyboards:g,errors:s}}function toStoryboardRects(e){return e.storyboards.filter(e=>!e.error).map(e=>{const{x:t,y:n,zIndex:r}=e.layout,s=e.layout.width??IP,i=e.layout.height??PP;return{x:t,y:n,width:s,height:i,...null!=r?{zIndex:r}:{}}})}var UP="tempo/designs";function hashSource(e){return xP("sha256").update(e).digest("hex")}function isCanvasPageFile(e,t){return e.startsWith(`${t}/`)&&"index.canvas.tsx"===e.split("/").pop()}function referenceIdentityPath(e,t){return t=t.replace(/(\.astro)\?tempo-component$/,"$1"),isRelativeSpecifier(t)?resolveRelativeImport(posixDirname(e),t):`pkg:${t}`}function parsedPageName(e){try{return parsePageSource(e.filePath,e.source).pageName||void 0}catch{return}}function referenceDeclarationToEntry(e,t,n,r,s){const i=referenceIdentityPath(n.filePath,t.importSpecifier);return{key:makeAssetKey(i,t.importedName),kind:"component",name:"default"===t.importedName?e.bindingName:t.importedName,filePath:i,exportKind:e.exportKind,libraries:e.libraries,...void 0!==e.usageInstructions?{usageInstructions:e.usageInstructions}:{},variants:e.variants,warnings:[...e.warnings],...s?{canvasPath:posixDirname(n.filePath)}:{},...void 0!==r?{canvasName:r}:{},declaredIn:n.filePath,declaredBindingName:e.bindingName}}function declarationToEntry(e,t,n){const r=isCanvasPageFile(t.filePath,n),s=[...e.warnings];let i,o=e.variants;if(r){o.length>0&&(s.push({code:"variants_on_canvas",message:"`variants` is ignored on a canvas asset — a canvas component takes no props",severity:"degraded",span:e.spans.config}),o=[]);const n=parsePageSource(t.filePath,t.source);i={pageName:n.pageName,pageFolderPath:posixDirname(t.filePath)}}return{key:makeAssetKey(t.filePath,e.bindingName),kind:r?"canvas":"component",name:e.bindingName,filePath:t.filePath,exportKind:e.exportKind,libraries:e.libraries,...void 0!==e.usageInstructions?{usageInstructions:e.usageInstructions}:{},variants:o,warnings:s,...i?{canvas:i}:{}}}function fileToIndexedParts(e,t){const n=[],r=e.parsed.errors.filter(e=>"structural"===e.severity),s=e.filePath.startsWith(`${t}/`),i=e.parsed.declarations.some(e=>e.reference),o=i&&isCanvasPageFile(e.filePath,t)?parsedPageName(e):void 0;for(const r of e.parsed.declarations)r.reference?n.push(referenceDeclarationToEntry(r,r.reference,e,o,s)):n.push(declarationToEntry(r,e,t));const a=parseControlsFile(e.filePath,e.source,e.program).map(t=>({filePath:t.reference?referenceIdentityPath(e.filePath,t.reference.importSpecifier):e.filePath,name:t.reference?.importedName??("default"===t.exportKind?"default":t.bindingName),declaredIn:e.filePath}));return{entries:n,structuralErrors:r,...a.length?{controls:a}:{}}}function deriveLibraries(e){const t=new Map;for(const n of Object.values(e))for(const e of n.libraries){const r=t.get(e);r?r.push(n.key):t.set(e,[n.key])}const n={};for(const[e,r]of[...t.entries()].sort(([e],[t])=>e.localeCompare(t)))n[e]=r.sort((e,t)=>e.localeCompare(t));return n}var jP=/\.[tj]sx?$/;function normalizedIdentity(e){const t=parseAssetKey(e);if(!t||t.filePath.startsWith("pkg:"))return e;let n=t.filePath.replace(jP,"");return n.endsWith("/index")&&(n=n.slice(0,-6)),`${n}#${t.bindingName}`}function resolveDuplicateDeclarations(e){const t=new Map;for(const n of e){const e=normalizedIdentity(n.componentFilePath?`${n.componentFilePath}#${n.componentName??n.name}`:n.key),r=t.get(e);r?r.push(n):t.set(e,[n])}const n=[],r=new Map;for(const e of t.values()){if(1===e.length){n.push(e[0]);continue}const t=e.map(e=>e.declaredIn??e.filePath).sort(),s={code:"duplicate_asset_declaration",severity:"structural",message:`This component has multiple defineAsset declarations: ${t.join(", ")}. Keep one definition before editing or inserting it.`},i=[...e].sort((e,t)=>e.key.localeCompare(t.key)||(e.declaredIn??e.filePath).localeCompare(t.declaredIn??t.filePath))[0];n.push({...i,controls:void 0,variants:[],warnings:[...i.warnings,s]});for(const e of t)r.set(e,[...r.get(e)??[],s])}return{winners:n,errorsByFile:r}}function decorateWithCanvasPointer(e,t,n){if(!n||"component"!==e.kind||void 0===e.declaredIn||void 0===e.canvasPath)return e;const r=verifyCanvasPointer(n,t,e);return void 0===r.componentFilePath&&0===r.warnings.length?e:{...e,...void 0!==r.componentFilePath?{componentFilePath:r.componentFilePath}:{},warnings:[...e.warnings,...r.warnings]}}function decorateWithRedundancyWarning(e,t){if("canvas"!==e.kind)return e;const n=posixDirname(e.filePath);return t.has(n)?{...e,warnings:[...e.warnings,{code:"redundant_canvas_declaration",severity:"degraded",message:`the component declarations in "${n}" already link this canvas via canvasPath — remove the canvas self-registration (self-registration is strictly for component-less foundations pages)`}]}:e}function assembleIndex(e,t,n,r=!1){const s=new Map,configuredRoot=e=>{if(s.has(e))return s.get(e);let t=null;const r=n?.readFile(e);if(r)try{const n=JSON.parse(r),s=n.paths?.canvases,i="string"==typeof s&&s.trim()?s.trim().replaceAll("\\","/"):"./designs";t=TP.normalize(TP.join(TP.dirname(e),i))}catch{}return s.set(e,t),t},belongsToAnotherCanvasProject=e=>{if(!r||!n)return!1;for(let n=TP.dirname(e);;n=TP.dirname(n)){for(const r of[TP.join(n,"tempo.config.json"),TP.join(n,"tempo/tempo.config.json")]){const n=configuredRoot(r);if(n&&e.startsWith(`${n}/`))return n!==TP.normalize(t).replace(/\/$/,"")}if("."===n||"/"===n)return!1}},i=Object.fromEntries(Object.entries(e).filter(([e])=>!belongsToAnotherCanvasProject(e))),{winners:o,errorsByFile:a}=resolveDuplicateDeclarations(Object.values(i).flatMap(e=>e.entries).map(e=>{if(!n||"component"!==e.kind)return e;const t=resolveComponentIdentity(n,e.filePath,"default"===e.exportKind?"default":parseAssetKey(e.key)?.bindingName??e.name,e.declaredIn??e.filePath),r=t&&definesVueComponent(n,t.filePath,t.name)?"vue":installedPackageFramework(n,e.filePath,t?.filePath??null);return t||r?{...e,...t?{componentFilePath:t.filePath,componentName:t.name}:{},...r?{componentFramework:r}:{}}:e})),c=new Set;for(const e of o)"component"===e.kind&&void 0!==e.canvasPath&&c.add(e.canvasPath);const l={};for(const e of[...o].sort((e,t)=>e.key.localeCompare(t.key)))l[e.key]=decorateWithRedundancyWarning(decorateWithCanvasPointer(e,t,n),c);const d={},u=new Set([...Object.keys(i),...a.keys()]);for(const e of[...u].sort((e,t)=>e.localeCompare(t))){const t=[...i[e]?.structuralErrors??[],...a.get(e)??[]];t.length>0&&(d[e]=t)}const p={};for(const e of Object.keys(i).sort())for(const t of i[e].controls??[]){const r=n?resolveComponentIdentity(n,t.filePath,t.name,e):null,s=makeAssetKey(r?.filePath??t.filePath,r?.name??t.name);(p[s]??=[]).push(t.declaredIn)}return{assets:l,libraries:deriveLibraries(l),fileErrors:d,...Object.keys(p).length?{controls:p}:{}}}function buildAssetIndex(e,t={},n){const r=t.canvasesDir??UP,s=n&&(n.canvasesDir??UP)===r,i={},o={};for(const r of e){if(!hasAssetSourceExtension(r.filePath))continue;if(!sourceMayDeclareAssets(r.source))continue;const e=hashSource(r.source);o[r.filePath]=e,i[r.filePath]=s&&n.contentHashes[r.filePath]===e&&n.fileContributions[r.filePath]?n.fileContributions[r.filePath]:parseContribution(r.filePath,r.source,t)}return{index:assembleIndex(i,r,t.fileResolution,t.excludeForeignCanvasProjects),canvasesDir:r,contentHashes:o,fileContributions:i}}function parseContribution(e,t,n){const r=(n.parseProgram??parseAssetProgram)(e,t);return fileToIndexedParts({filePath:e,source:t,program:r,parsed:parseAssetFile(e,t,r)},n.canvasesDir??UP)}function toPosixPath4(e){return e.replace(/\\/g,"/")}function normalizeWorkspaceRelativePath(e,t){const n=toPosixPath4(t).replace(/^\.\//,"");return oP.isAbsolute(n)?toPosixPath4(oP.relative(e,n)):n}function resolveInsideWorkspace(e,t){const n=oP.resolve(e),r=oP.resolve(n,t),s=oP.relative(n,r),i=".."===s||s.startsWith(`..${oP.sep}`)||oP.isAbsolute(s);return i?void 0:r}function workspaceRelativeCanvasesDir(e){return toPosixPath4(oP.relative(e.workspaceRoot,oP.resolve(e.workspaceRoot,e.canvasesDir)))}function workspaceFileReader(e){return t=>{const n=resolveInsideWorkspace(e,t);if(void 0===n)return null;try{return iP(n).isFile()?sP(n,"utf-8"):null}catch{return null}}}async function loadWorkspaceAssetIndex(e){const[t,n]=await Promise.all([scanRepo(e.workspaceRoot),loadPnpmWorkspacePackages(e.workspaceRoot)]);return buildAssetIndex(t,{canvasesDir:workspaceRelativeCanvasesDir(e),excludeForeignCanvasProjects:!0,fileResolution:{readFile:workspaceFileReader(e.workspaceRoot),workspacePackages:n}}).index}function textResult(e){return{content:[{type:"text",text:e}]}}function errorResult8(e){return{content:[{type:"text",text:e}],isError:!0}}function typedErrorResult(e,t,n){return errorResult8(`${e} failed [${t}]: ${n}`)}function errorMessage(e){return e instanceof Error?e.message:String(e)}async function readWorkspaceFile(e,t){const n=resolveInsideWorkspace(e.workspaceRoot,t);if(void 0!==n)try{return await XI(n,"utf-8")}catch{return}}async function writeWorkspaceFile(e,t,n){const r=resolveInsideWorkspace(e.workspaceRoot,t);if(void 0===r)throw new Error(`refusing to write outside the workspace: "${t}"`);await YI(r,n)}function isCanvasPagePath(e,t){return"index.canvas.tsx"===JI.posix.basename(t)&&t.startsWith(`${workspaceRelativeCanvasesDir(e)}/`)}function toAssetSummary(e){return{key:e.key,kind:e.kind,name:e.name,filePath:e.filePath,...void 0!==e.usageInstructions?{usageInstructions:e.usageInstructions}:{},...void 0!==e.canvasPath?{canvasPath:e.canvasPath}:{},...void 0!==e.componentFilePath?{componentFilePath:e.componentFilePath}:{},variantNames:e.variants.map(e=>e.name)}}function sortedByName(e){return[...e].sort((e,t)=>e.name.localeCompare(t.name)||e.key.localeCompare(t.key))}function countByKind(e){return{componentCount:e.filter(e=>"component"===e.kind).length,canvasCount:e.filter(e=>"canvas"===e.kind).length}}function registerAssetTools(e,t){const loadIndex=()=>(t.loadAssetIndex??loadWorkspaceAssetIndex)({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir});e.tool("asset_list_libraries","Discover the project's asset libraries: named collections of approved reusable components and canvases, including its design system, component library, UI kit, and future collections. Call for a broad collection overview or when the user asks what libraries, reusable components, canvases, or building blocks exist; use asset_list next to search their members. **Read-only and cheap** (fresh source scan; no code execution; no guide needed to browse). Returns `{ libraries: [{ name, componentCount, canvasCount }], unassigned: { componentCount, canvasCount } }`.",{},async()=>{try{const e=await loadIndex(),t=Object.keys(e.libraries).sort().map(t=>({name:t,...countByKind(e.libraries[t].map(t=>e.assets[t]))})),n=countByKind(Object.values(e.assets).filter(e=>0===e.libraries.length));return textResult(JSON.stringify({libraries:t,unassigned:n},null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.tool("asset_library_get","Get one asset library's approved reusable components and canvases with per-asset summaries. Use after asset_list_libraries when exploring a design system, component library, UI kit, or another named collection. **Read-only and cheap** — no guide needed to browse. Returns `{ name, assets: [{ key, kind, name, filePath, usageInstructions?, canvasPath?, variantNames }] }`. Errors `library_not_found` when no asset names the library.",{name:QI.string().describe("Library name, exactly as listed by asset_list_libraries.")},async({name:e})=>{try{const t=await loadIndex(),n=t.libraries[e];if(!n){const n=Object.keys(t.libraries).sort();return typedErrorResult("asset_library_get","library_not_found",`no library named "${e}".${n.length>0?` Available libraries: ${n.join(", ")}.`:" No libraries exist yet."}`)}const r=sortedByName(n.map(e=>t.assets[e])).map(toAssetSummary);return textResult(JSON.stringify({name:e,assets:r},null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.registerTool("asset_list",{description:"Primary asset-discovery tool for UI work. Search every approved reusable component and canvas declared with `defineAsset`, across the project's design system, component library, UI kit, and other asset libraries. Call BEFORE creating, modifying, restyling, or reviewing UI to reuse an existing building block instead of hand-rolling one; each asset's `usageInstructions` says when to use it and when not to. **Read-only and cheap** (fresh source scan; no code execution; no guide needed to browse). Filter by library and/or name; pass `library: \"\"` for library-less assets. Returns `{ assets: [{ key, kind, name, filePath, usageInstructions?, canvasPath?, componentFilePath?, variantNames, libraries }], fileErrors? }`. `fileErrors` reports structural declaration problems such as `duplicate_asset_declaration` and `component_declaration_outside_canvas`, which also fail `canvas_validate`.",inputSchema:QI.object({library:QI.string().optional().describe('Exact library name to filter by. "" (empty string) selects assets that belong to no library.'),query:QI.string().optional().describe("Case-insensitive substring match on the asset name.")}),_meta:{"anthropic/alwaysLoad":!0}},async({library:e,query:t})=>{try{const n=await loadIndex(),r=t?.toLowerCase(),s=sortedByName(Object.values(n.assets).filter(t=>{if(""===e){if(t.libraries.length>0)return!1}else if(void 0!==e&&!t.libraries.includes(e))return!1;return void 0===r||t.name.toLowerCase().includes(r)})).map(e=>({...toAssetSummary(e),libraries:e.libraries})),i=Object.keys(n.fileErrors).length>0;return textResult(JSON.stringify({assets:s,...i?{fileErrors:n.fileErrors}:{}},null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.tool("asset_get",'Inspect one approved asset selected from a design system, component library, UI kit, or another asset library. Call after asset_list before reuse. Returns usageInstructions, library membership, real variants, warnings, and linked canvas/component paths. **Read-only and cheap** — no guide needed to browse. Prop values the parser could not resolve statically are `{"$unresolved": true}`. Canvas-pointer warnings identify missing or stale links and include the exact repair. Errors `asset_not_found` for an unknown key.',{assetKey:QI.string().describe('Asset key as returned by the list tools: "<workspace-relative-path>#<bindingName>".')},async({assetKey:e})=>{try{const t=await loadIndex(),n=t.assets[e];if(!n)return typedErrorResult("asset_get","asset_not_found",`no asset with key "${e}". Keys have the shape "<workspace-relative-path>#<bindingName>" — call asset_list to see what exists.`);const{declaredIn:r,...s}=n;return textResult(JSON.stringify(s,null,2))}catch(e){return errorResult8(errorMessage(e))}}),e.tool("asset_define","Back-compat only — almost never the tool you want. **To add a component to the design system, do NOT use this tool.** The convention is a canvas reference declaration: hand-write `defineAsset(<ImportedComponent>, { libraries, usageInstructions, variants })` at the top level of the canvas that showcases the component, and add the canvas-pointer docstring line to the component's defining file — call get_guide({ topic: \"tempo-assets-instructions\" }) first for the exact authoring rules. This tool instead attaches a LEGACY same-file `defineAsset` tag in the component's own file (records no linked canvas): it adds the `tempo-sdk/assets` import if missing and inserts the statement directly after the component's definition. Anonymous default exports (`export default function () {…}`, `export default () => …`) are repaired to a named binding automatically. **MUTATING** (surgical source edit; the file is never regenerated). Returns `{ assetKey, repairedDefaultExport }`, plus a `note` when the project typecheck may additionally require `variants`. Errors: `file_not_found`, `export_not_found`, `already_defined`, `not_definable`.",{filePath:QI.string().describe("Workspace-relative path to the file that defines the component (or a canvas's index.canvas.tsx)."),exportName:QI.string().optional().describe("Named top-level binding to target. Omit to target the file's default export."),libraries:QI.array(QI.string()).optional().describe("Library names to put the asset in."),usageInstructions:QI.string().optional().describe("What this asset is and when to reach for it — and when not.")},async({filePath:e,exportName:n,libraries:r,usageInstructions:s})=>{const i=normalizeWorkspaceRelativePath(t.workspaceRoot,e);try{let e,o=await readWorkspaceFile(t,i);if(void 0===o)return typedErrorResult("asset_define","file_not_found",`no file at "${i}" (workspace-relative).`);let a=!1;if(void 0!==n)e=n;else{const t=ensureNamedDefaultExport({filePath:i,source:o});if(!t.ok)return typedErrorResult("asset_define",t.code,t.message);a=t.changed,o=t.source,e=t.bindingName}const c={...void 0!==s?{usageInstructions:s}:{},...r&&r.length>0?{libraries:r}:{}},l=ensureAssetDeclaration({filePath:i,source:o,bindingName:e,initialConfig:c});if(!l.ok)return typedErrorResult("asset_define",l.code,l.message);if(!l.changed)return typedErrorResult("asset_define","already_defined",`"${makeAssetKey(i,e)}" already has a defineAsset declaration. Use asset_add_to_libraries / asset_remove_from_libraries to change its membership.`);await writeWorkspaceFile(t,i,l.source);const d=isCanvasPagePath(t,i);return textResult(JSON.stringify({assetKey:makeAssetKey(i,e),repairedDefaultExport:a,...d?{}:{note:`If ${e} has required props, the project's typecheck will require a \`variants\` entry on this defineAsset config. Add named variants with real, renderable prop values — never invented placeholders.`}},null,2))}catch(e){return errorResult8(errorMessage(e))}}),registerMembershipTool(e,t,{name:"asset_add_to_libraries",description:"Add an asset to one or more libraries by inserting the names into its `defineAsset` config's `libraries` array (creating the property when absent). Already-present names are skipped. Edits same-file declarations only — for a canvas reference declaration (the design-system convention), hand-edit the `libraries` array in the declaring canvas instead. **MUTATING** (surgical span edit — surrounding code is byte-identical). Returns `{ assetKey, libraries }` — the resulting full membership. Errors: `asset_not_found`, `config_not_editable`.",edit:addLibraries}),registerMembershipTool(e,t,{name:"asset_remove_from_libraries",description:"Remove an asset from one or more libraries by deleting matching entries from its `defineAsset` config's `libraries` array (the property itself is removed when the array empties). Names not present are ignored. Edits same-file declarations only — for a canvas reference declaration (the design-system convention), hand-edit the `libraries` array in the declaring canvas instead. **MUTATING** (surgical span edit — surrounding code is byte-identical). Returns `{ assetKey, libraries }` — the resulting full membership, possibly empty. Errors: `asset_not_found`, `config_not_editable`.",edit:removeLibraries})}function registerMembershipTool(e,t,n){e.tool(n.name,n.description,{assetKey:QI.string().describe('Asset key as returned by the list tools: "<workspace-relative-path>#<bindingName>".'),libraries:QI.array(QI.string()).min(1).describe("Library names (non-empty).")},async({assetKey:e,libraries:r})=>{try{const s=parseAssetKey(e),i=s?await readWorkspaceFile(t,s.filePath):void 0;if(!s||void 0===i)return typedErrorResult(n.name,"asset_not_found",`no asset with key "${e}". Keys have the shape "<workspace-relative-path>#<bindingName>" — call asset_list to see what exists.`);const o=n.edit({filePath:s.filePath,source:i,bindingName:s.bindingName,libraries:r});if(!o.ok)return typedErrorResult(n.name,o.code,o.message);o.changed&&await writeWorkspaceFile(t,s.filePath,o.source);const a=parseAssetFile(s.filePath,o.source).declarations.find(e=>e.bindingName===s.bindingName);return textResult(JSON.stringify({assetKey:e,libraries:a?.libraries??[]},null,2))}catch(e){return errorResult8(errorMessage(e))}})}var BP=3840,$P=12e3;function isFidelityWindowStoryboard(e){return"component"===e.kind&&"astro"!==e.uiFramework&&void 0===e.preview}import WP from"path";import{parseSync as HP}from"oxc-parser";function applyCanvasSourceEdits(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e.length+1,s=e;for(const t of n){if(t.start<0||t.end<t.start||t.end>e.length||t.end>r)throw new Error(`Invalid overlapping canvas source edit ${t.start}:${t.end}`);s=s.slice(0,t.start)+t.value+s.slice(t.end),r=t.start}return s}function updateStoryboardVrt(e){const t=parseCanvasFile(e.filePath,e.source),n=findStoryboard(t,e.storyboardId);if("route"===n.kind)throw new Error(`Storyboard "${e.storyboardId}" is a route storyboard; VRT supports component and local HTML storyboards`);if("object"==typeof e.tracked){const r=formatStoryboardVrtConfig(e.tracked),s=null===r?"vrt":`vrt={${r}}`;return n.vrtAttributeSpan?applyResult(e.source,t,[{start:n.vrtAttributeSpan.start,end:n.vrtAttributeSpan.end,value:s}]):applyResult(e.source,t,[insertBareJsxAttributeLine({source:e.source,openingElementSpan:requireStoryboardOpeningSpan(n,e.storyboardId),name:s})])}if(!e.tracked)return n.vrtAttributeSpan?applyResult(e.source,t,[{...expandJsxAttributeRemoval(e.source,n.vrtAttributeSpan),value:""}]):applyResult(e.source,t,[]);if(n.vrt)return applyResult(e.source,t,[]);const r=requireStoryboardOpeningSpan(n,e.storyboardId);return n.vrtAttributeSpan?applyResult(e.source,t,[{...expandJsxAttributeRemoval(e.source,n.vrtAttributeSpan),value:""},insertBareJsxAttributeLine({source:e.source,openingElementSpan:r,name:"vrt"})]):applyResult(e.source,t,[insertBareJsxAttributeLine({source:e.source,openingElementSpan:r,name:"vrt"})])}function formatStoryboardVrtConfig(e){const t=[];if(void 0!==e.threshold){if("number"!=typeof e.threshold||!Number.isFinite(e.threshold)||e.threshold<0||e.threshold>.5)throw new Error("vrt.threshold must be a number between 0 and 0.5");t.push(`threshold: ${e.threshold}`)}if(void 0!==e.skip){if("boolean"!=typeof e.skip)throw new Error("vrt.skip must be a boolean");t.push(`skip: ${e.skip}`)}if(void 0!==e.ignore){if(!Array.isArray(e.ignore))throw new Error("vrt.ignore must be an array of { x, y, w, h } regions");const n=e.ignore.map(e=>{for(const t of["x","y","w","h"]){const n=e?.[t];if("number"!=typeof n||!Number.isFinite(n)||n<0)throw new Error(`vrt.ignore regions must be { x, y, w, h } non-negative numbers (bad ${t})`)}return`{ x: ${e.x}, y: ${e.y}, w: ${e.w}, h: ${e.h} }`});n.length>0&&t.push(`ignore: [${n.join(", ")}]`)}return 0===t.length?null:`{ ${t.join(", ")} }`}function addCanvasStoryboard(e){const t=parseCanvasFile(e.filePath,e.source);if(t.storyboards.some(t=>t.storyboardKey===e.storyboard.id))throw new Error(`Storyboard id "${e.storyboard.id}" already exists`);const n=[],r=sdkComponentForStoryboard(e.storyboard),s=resolveSdkTag(t,r);let i,o=s.tag;if(s.importLine&&(n.push(s.importLine),o=s.tag),"component"===e.storyboard.kind){if(i=e.storyboard.componentExpression??e.storyboard.componentImport?.localName,!i)throw new Error("Component storyboard requires componentExpression or componentImport");if(e.storyboard.componentImport){const r=buildMissingComponentImportLine(t,e.source,e.storyboard.componentImport);r&&n.push(r)}}const a=buildImportInsertionEdit2(e.source,t,n),c=buildCanvasChildInsertionEdit({source:e.source,parsed:t,tag:o,storyboard:e.storyboard,componentExpression:i}),l=[...a?[a]:[],c];return applyResult(e.source,t,l)}function applyResult(e,t,n){const r=n.filter(t=>!!t&&e.slice(t.start,t.end)!==t.value);return{source:applyCanvasSourceEdits(e,r),edits:r,parsed:t}}function findStoryboard(e,t){const n=e.storyboards.find(e=>e.storyboardKey===t);if(!n)throw new Error(`Storyboard "${t}" not found`);return n}function requireStoryboardOpeningSpan(e,t){return requiredSpan(e.openingElementSpan,`Storyboard "${t}" opening element not found`)}function formatStoryboardElement(e){const t=detectNewline2(e.source),n=lineIndentAt2(e.source,e.insertionOffset),r=`${n} `,s=" ",i=`${r} `,o=storyboardElementProps(e.storyboard,e.componentExpression);return`${s}<${e.tag}${t}${o.map(e=>`${i}${e}`).join(t)}${t}${r}/>${t}${n}`}function buildCanvasChildInsertionEdit(e){const t=e.parsed.canvasChildrenInsertionOffset;if("number"==typeof t)return{start:t,end:t,value:formatStoryboardElement({source:e.source,insertionOffset:t,tag:e.tag,storyboard:e.storyboard,componentExpression:e.componentExpression})};const n=e.parsed.canvasOpeningElementSpan;if(!n)throw new Error("Canvas closing element not found");const r=e.source.slice(n.start,n.end),s=r.match(/\s*\/\s*>$/),i=r.match(/^<\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/)?.[1];if(!s||!i)throw new Error("Canvas closing element not found");const o=detectNewline2(e.source),a=n.end-s[0].length,c=lineIndentAt2(e.source,n.start),l=`${c} `,d=`${l} `,u=storyboardElementProps(e.storyboard,e.componentExpression);return{start:a,end:n.end,value:`>${o}${l}<${e.tag}${o}${u.map(e=>`${d}${e}`).join(o)}${o}${l}/>${o}${c}</${i}>`}}function storyboardElementProps(e,t){const n=formatJsxStringAttribute("id",requireNonEmpty(e.id,"Storyboard id"));if("legacy-v1"===e.kind)return[n,`storyboard={${e.storyboardExpression}}`];if(!("route"!==e.kind&&"html"!==e.kind&&"flutter"!==e.kind||void 0!==e.layout.width&&void 0!==e.layout.height))throw new Error("Route, HTML and Flutter layouts require width and height");return[n,...e.name&&""!==e.name.trim()?[formatJsxStringAttribute("name",e.name)]:[],...storyboardKindProps(e,t),`layout={{ ${formatLayout(e.layout)} }}`]}function formatJsxStringAttribute(e,t){const n=JSON.stringify(t),r=n===`"${t}"`&&!t.includes("&");return r?`${e}=${n}`:`${e}={${n}}`}function storyboardKindProps(e,t){return"component"===e.kind?[`component={${t}}`,...e.props&&""!==e.props.trim()?[`props={${e.props.trim()}}`]:[]]:"route"===e.kind?[formatJsxStringAttribute("route",e.route)]:"flutter"===e.kind?[formatJsxStringAttribute("preview",e.preview)]:[...e.filepath?[formatJsxStringAttribute("filepath",e.filepath)]:[],...e.src?[formatJsxStringAttribute("src",e.src)]:[]]}function formatLayout(e){return[`x: ${roundLayoutNumber(e.x)}`,`y: ${roundLayoutNumber(e.y)}`,...void 0===e.width?[]:[`width: ${roundLayoutNumber(e.width)}`],...void 0===e.height?[]:[`height: ${roundLayoutNumber(e.height)}`],...void 0===e.zIndex?[]:[`zIndex: ${roundLayoutNumber(e.zIndex)}`],...void 0===e.intrinsicSizing?[]:[`intrinsicSizing: ${JSON.stringify(e.intrinsicSizing)}`]].join(", ")}function sdkComponentForStoryboard(e){return"route"===e.kind?"RouteStoryboard":"html"===e.kind?"HtmlStoryboard":"flutter"===e.kind?"FlutterStoryboard":"legacy-v1"===e.kind?"LegacyStoryboardV1":storyboardComponentForFramework(e.uiFramework)}function resolveSdkTag(e,t){const n=Gb[t].importSource;for(const r of e.imports)if(r.source===n){if("namespace"===r.kind)return{tag:`${r.localName}.${t}`};if(r.importedName===t)return{tag:r.localName}}const r=pickAvailableIdentifier(e,`TempoCanvas${t}`);return{tag:r,importLine:`import { ${t} as ${r} } from "${n}";`}}function buildMissingComponentImportLine(e,t,n){const r=e.imports.find(e=>e.localName===n.localName);if(r){if(r.source!==n.source)throw new Error(`Import binding "${n.localName}" already exists`);return null}if(sourceContainsIdentifierNode(e.filePath,t,n.localName))throw new Error(`Identifier "${n.localName}" already exists`);if(!n.importedName||"default"===n.importedName)return`import ${n.localName} from ${JSON.stringify(n.source)};`;const s=n.importedName===n.localName?n.localName:`${n.importedName} as ${n.localName}`;return`import { ${s} } from ${JSON.stringify(n.source)};`}function buildImportInsertionEdit2(e,t,n){if(0===n.length)return null;const r=detectNewline2(e),s=Array.from(new Set(n)),i=t.imports.reduce((e,t)=>!e||t.declarationSpan.end>e.declarationSpan.end?t:e,null);if(i)return{start:i.declarationSpan.end,end:i.declarationSpan.end,value:`${r}${s.join(r)}`};const o=topLevelInsertionOffset2(e);return{start:o,end:o,value:`${s.join(r)}${r}`}}function findOpeningElementAttributeInsertionOffset(e,t){const n=e.lastIndexOf(">",t.end-1);if(n<t.start)throw new Error("JSX opening element close not found");return"/"===e[n-1]?n-1:n}function insertBareJsxAttributeLine(e){const t=findOpeningElementAttributeInsertionOffset(e.source,e.openingElementSpan),n=detectNewline2(e.source),r=lineIndentAt2(e.source,e.openingElementSpan.start),s=e.source.indexOf("\n",e.openingElementSpan.start),i=s>=0&&s<t?e.source.slice(s+1,t).split(/\r?\n/).find(e=>""!==e.trim())?.match(/^[ \t]*/)?.[0]:void 0,o=i&&i.length>r.length?i:`${r}${r.includes("\t")?"\t":" "}`,a=Math.max(e.source.lastIndexOf("\n",t-1)+1,0);if(/^[ \t]*$/.test(e.source.slice(a,t)))return{start:a,end:a,value:`${o}${e.name}${n}`};let c=t;for(;c>e.openingElementSpan.start&&(" "===e.source[c-1]||"\t"===e.source[c-1]);)c--;return{start:c,end:t,value:`${n}${o}${e.name}${n}${r}`}}function expandJsxAttributeRemoval(e,t){const n=Math.max(e.lastIndexOf("\n",t.start-1)+1,0),r=e.indexOf("\n",t.end),s=r>=0?r:e.length;if(/^[ \t]*$/.test(e.slice(n,t.start))&&/^[ \t]*$/.test(e.slice(t.end,s)))return{start:n,end:r>=0?r+1:s};let i=t.start,o=t.end;for(;i>0&&(" "===e[i-1]||"\t"===e[i-1]);)i--;for(;o<e.length&&(" "===e[o]||"\t"===e[o]);)o++;return{start:i,end:o}}function expandStatementForward(e,t){let n=t.end;for(;n<e.length&&(" "===e[n]||"\t"===e[n]);)n++;return"\r\n"===e.slice(n,n+2)?n+=2:"\n"!==e[n]&&"\r"!==e[n]||n++,{start:t.start,end:n}}function lineIndentAt2(e,t){const n=Math.max(e.lastIndexOf("\n",t-1)+1,0),r=e.slice(n,t),s=r.match(/^[ \t]*/);return s?.[0]??""}function collapseBlankLines(e,t){return"\r\n"===t?e.replace(/(\r\n){3,}/g,"\r\n\r\n"):e.replace(/\n{3,}/g,"\n\n")}function detectNewline2(e){return e.includes("\r\n")?"\r\n":"\n"}function topLevelInsertionOffset2(e){let t=0;if(e.startsWith("#!")){const n=e.indexOf("\n");t=n>=0?n+1:e.length}for(;;){const n=e.indexOf("\n",t),r=n>=0?n+1:e.length,s=e.slice(t,r).trim();if(!/^["']use [^"']+["'];?$/.test(s))break;t=r}return t}function pickAvailableIdentifier(e,t){const n=new Set(e.imports.map(e=>e.localName));if(!n.has(t))return t;for(let e=2;e<1e4;e+=1){const r=`${t}${e}`;if(!n.has(r))return r}throw new Error(`Unable to find available identifier for ${t}`)}function hasIdentifier(e,t){return new RegExp(`\\b${escapeRegExp4(t)}\\b`).test(e)}function sourceContainsIdentifierNode(e,t,n){const r=HP(e,t).program;let s=!1;return walkWithParent(r,e=>{s||"Identifier"!==e.type&&"JSXIdentifier"!==e.type||e.name!==n||(s=!0)}),s}function walkWithParent(e,t,n=null,r=null,s=new Set){if(e&&"object"==typeof e&&!s.has(e)){s.add(e),"string"==typeof e.type&&t(e,n,r);for(const[n,r]of Object.entries(e))if(r&&"object"==typeof r)if(Array.isArray(r))for(const i of r)walkWithParent(i,t,e,n,s);else walkWithParent(r,t,e,n,s)}}function escapeRegExp4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function roundLayoutNumber(e){if("number"!=typeof e||!Number.isFinite(e))throw new Error("Layout values must be finite numbers");return Math.round(e)}function requireNonEmpty(e,t){const n=e.trim();if(!n)throw new Error(`${t} must be non-empty`);return n}function requiredSpan(e,t){if(void 0===e)throw new Error(t);return e}function reactStub(e,t){const n=t&&"default"!==t?t:e,r=`${e}Stub`;return`function ${r}() { return <div />; }\nexport default ${r};\nexport const ${n} = ${r};\n`}function singleFileComponentStub(e,t){return(n,r)=>{if(r&&"default"!==r)throw new Error(`Canvas-local ${e} storyboard "${n}" must use a default component import`);return t}}var qP={react:{extension:componentFileExtensionForFramework("react"),stub:reactStub},svelte:{extension:componentFileExtensionForFramework("svelte"),stub:singleFileComponentStub("Svelte","<div></div>\n")},vue:{extension:componentFileExtensionForFramework("vue"),stub:singleFileComponentStub("Vue","<template><div></div></template>\n")},astro:{extension:componentFileExtensionForFramework("astro"),stub:singleFileComponentStub("Astro","<div></div>\n")}},zP=/\.(?:jsx?|tsx?)$/;function storyboardFrameworkForImport(e,t){const n=componentImportPath(e??""),r=Object.keys(qP),s=r.find(e=>n.endsWith(qP[e].extension));return s||(zP.test(n)?"react":resolveAppUiFramework(t))}function hasComponentModuleExtension(e){const t=componentImportPath(e);return!!zP.test(t)||Object.values(qP).some(e=>t.endsWith(e.extension))}function toIdentifier(e){const t=e.replace(/[^a-zA-Z0-9_$]+/g," ").trim().split(/\s+/).map((e,t)=>{if(0===e.length)return"";const n=e.replace(/^[0-9]+/,"");if(0===n.length)return"";const r=n.toLowerCase();return 0===t?r:r[0].toUpperCase()+r.slice(1)}).join(""),n=t.length>0?t:"componentRef",r=/^[a-zA-Z_$]/.test(n);return r?n:`component${n}`}function canvasComponentName(e){const t=toIdentifier(e);return`${t[0].toUpperCase()}${t.slice(1)}Canvas`}function getDefaultLocalName(e){const t=e.importPath?WP.posix.basename(e.importPath).replace(/\.[^.]+$/,""):"",n=t||`${e.exportName}Component`,r=toIdentifier(n);return r[0].toUpperCase()+r.slice(1)}function buildComponentImports(e,t){const n=new Map,r=new Set(t),s=new Map;for(const t of e)r.add(t.exportName);const assignUniqueLocalName=e=>{let t=e,n=2;for(;r.has(t);)t=`${e}${n}`,n+=1;return r.add(t),t};for(const t of e){if(t.route||t.preview)continue;if(!t.importPath)throw new Error(`Storyboard "${t.exportName}" must include importPath for component storyboards`);const e=t.importName&&t.importName.trim().length>0?t.importName.trim():"default",r=t.importPath.replace(/\.tsx?$/,""),i=`${r}::${e}`;let o=n.get(i);if(!o){const s="default"===e?getDefaultLocalName(t):e;o={importPath:r,importName:e,localName:assignUniqueLocalName(s)},n.set(i,o)}s.set(t.exportName,o)}return s}function componentImportSource(e,t){const n=storyboardComponentForFramework(t);if(!Gb[n].componentImportQuery)return e;const r=componentImportPath(e),s=qP[t].extension;return componentImportSpecifier(r.endsWith(s)?r:`${r}${s}`)}function toAddCanvasStoryboardInput(e,t,n){const r={x:e.x,y:e.y,...e.route||e.preview?{width:e.width,height:e.height}:{},...null!=e.zIndex&&Number.isFinite(e.zIndex)?{zIndex:e.zIndex}:{}},s=e.name?{name:e.name}:{};if(e.route)return{kind:"route",id:e.exportName,route:e.route,layout:r,...s};if(e.preview)return{kind:"flutter",id:e.exportName,preview:e.preview,layout:r,...s};if(!t)throw new Error(`Storyboard "${e.exportName}" is missing a component import binding`);const i=storyboardFrameworkForImport(e.importPath,n);return{kind:"component",uiFramework:"react"===i?void 0:i,id:e.exportName,layout:"astro"===i?{...r,width:e.width,height:e.height}:r,...s,componentImport:{localName:t.localName,source:componentImportSource(t.importPath,i),importedName:t.importName}}}function generatePageFileContent(e){const t=resolveAppUiFramework(e.uiFramework),n=canvasComponentName(e.pageName),r=new Set(e.storyboards.filter(e=>!e.route&&!e.preview).map(e=>storyboardFrameworkForImport(e.importPath,t))),s=new Map([["tempo-sdk/canvas",["Canvas"]]]),addSdkName=(e,t)=>{const n=s.get(e)??[];n.push(t),s.set(e,n)};for(const e of Object.keys(qP)){if(!r.has(e))continue;const t=storyboardComponentForFramework(e);addSdkName(Gb[t].importSource,t)}e.storyboards.some(e=>e.route)&&addSdkName("tempo-sdk/canvas","RouteStoryboard"),e.storyboards.some(e=>e.preview)&&addSdkName("tempo-sdk/canvas","FlutterStoryboard");const i=buildComponentImports(e.storyboards,[n,...[...s.values()].flat()]),o=[];e.home&&o.push(CP);for(const[e,t]of s)o.push(`import { ${t.join(", ")} } from "${e}";`);o.push(""),o.push(`export default function ${n}() {`);const a=[formatJsxStringAttribute("name",e.pageName),...e.backgroundColor?[formatJsxStringAttribute("backgroundColor",e.backgroundColor)]:[]].join(" ");0===e.storyboards.length?o.push(` return <Canvas ${a} />;`):(o.push(" return ("),o.push(` <Canvas ${a}>`),o.push(" </Canvas>"),o.push(" );")),o.push("}");const c="index.canvas.tsx";let l=`${o.join("\n")}\n`;for(const n of e.storyboards)l=addCanvasStoryboard({filePath:c,source:l,storyboard:toAddCanvasStoryboardInput(n,i.get(n.exportName),t)}).source;const d=parseCanvasFile(c,l);if(!d.canvasElementSpan)throw new Error("Generated canvas source is missing a <Canvas> element");if(d.storyboards.length!==e.storyboards.length)throw new Error(`Generated canvas declares ${d.storyboards.length} storyboards, expected ${e.storyboards.length}`);return l}import{readFile as GP}from"fs/promises";async function parsePageFile(e){const t=await GP(e,"utf-8");return parsePageSource(e,t)}import VP from"fs/promises";import KP from"path";import{createHash as XP,randomUUID as YP}from"crypto";import JP from"fs/promises";import QP from"path";import{fileURLToPath as ZP}from"url";function createQueuedFileEditor(){const e=new Map;async function withFileLock(t,n){const r=normalizeAbsolutePath(t),s=e.get(r)??Promise.resolve();let i;const o=new Promise(e=>{i=e}),a=s.catch(()=>{}).then(()=>o);e.set(r,a),await s.catch(()=>{});try{return await n()}finally{i(),e.get(r)===a&&e.delete(r)}}async function withFileLocks(e,t){const n=Array.from(new Set(e.map(e=>normalizeAbsolutePath(e)))).sort(),runAtIndex=e=>{const r=n[e];return r?withFileLock(r,()=>runAtIndex(e+1)):Promise.resolve(t())};return runAtIndex(0)}async function readFile48(e){return withFileLock(e,()=>readFileUnlocked(e))}async function readBinaryFile(e){return withFileLock(e,()=>JP.readFile(normalizeAbsolutePath(e)))}async function readFileIfExists(e){return withFileLock(e,async()=>{try{return await readFileUnlocked(e)}catch(e){if(isNotFoundError(e))return null;throw e}})}async function writeFile16(e,t,n,r){return withFileLock(e,async()=>{const s=await readFileIfExistsUnlocked(e);if("number"==typeof n&&Number.isFinite(n)&&s?.mtime!==n)return{stale:!0,content:s?.content??"",mtime:s?.mtime??0};await atomicWriteFile(e,t,r);const i=await JP.stat(e);return{stale:!1,mtime:i.mtimeMs}})}async function writeBinaryFile(e,t,n){return withFileLock(e,async()=>{await atomicWriteFile(e,t,n);const r=await JP.stat(e);return{mtime:r.mtimeMs}})}async function touchFile(e){return withFileLock(e,async()=>{const t=normalizeAbsolutePath(e),n=await JP.stat(t),r=new Date(Math.max(Date.now(),Math.ceil(n.mtimeMs)+1));await JP.utimes(t,n.atime,r);const s=await JP.stat(t);return{mtime:s.mtimeMs}})}async function copyFile2(e,t){return withFileLocks([e,t],async()=>{const n=normalizeAbsolutePath(t);await JP.mkdir(QP.dirname(n),{recursive:!0}),await JP.copyFile(normalizeAbsolutePath(e),n)})}async function renamePath(e,t){return withFileLocks([e,t],async()=>{const n=normalizeAbsolutePath(t);await JP.mkdir(QP.dirname(n),{recursive:!0}),await JP.rename(normalizeAbsolutePath(e),n)})}async function removePath(e,t){return withFileLock(e,()=>JP.rm(normalizeAbsolutePath(e),{recursive:t?.recursive??!1,force:!0}))}async function unlinkFile(e){return withFileLock(e,async()=>{try{await JP.unlink(e)}catch(e){if(!isNotFoundError(e))throw e}})}return{readFile:readFile48,readBinaryFile,readFileIfExists,writeFile:writeFile16,writeBinaryFile,touchFile,copyFile:copyFile2,renamePath,removePath,unlinkFile,withFileLock,withFileLocks,readWorkspaceFile:(e,t)=>readFile48(resolveWorkspaceRelativePath(e,t)),readWorkspaceFileIfExists:(e,t)=>readFileIfExists(resolveWorkspaceRelativePath(e,t)),writeWorkspaceFile:(e,t,n,r,s)=>writeFile16(resolveWorkspaceRelativePath(e,t),n,r,s),touchWorkspaceFile:(e,t)=>touchFile(resolveWorkspaceRelativePath(e,t)),unlinkWorkspaceFile:(e,t)=>unlinkFile(resolveWorkspaceRelativePath(e,t)),withWorkspaceFileLock:(e,t,n)=>withFileLock(resolveWorkspaceRelativePath(e,t),n)}}var eD=createQueuedFileEditor();function resolveWorkspaceRelativePath(e,t){const n=/^[a-z]:[\\/]|^\\\\/i.test(e),r=n?QP.win32:QP,s=t.startsWith("file:")?ZP(t,{windows:n}):n&&/^\/[a-z]:[\\/]/i.test(t)?t.slice(1):t,i=r.resolve(e),o=r.resolve(i,s),a=r.relative(i,o);if(".."===a||a.startsWith(`..${r.sep}`)||r.isAbsolute(a))throw new Error(`Path escapes workspace root: ${t}`);return o}async function atomicWriteFile(e,t,n,r={}){const s=normalizeAbsolutePath(e),i=QP.dirname(s);await JP.mkdir(i,{recursive:!0});const o=QP.join(i,`.${QP.basename(s)}.${process.pid}.${Date.now()}.${YP()}.tmp`);try{if(await JP.writeFile(o,t),"number"==typeof n&&Number.isFinite(n)){const e=new Date(n);await JP.utimes(o,e,e)}const e=Math.trunc((await JP.stat(o)).mtimeMs);if(void 0!==r.expectedSha256){const e=await JP.readFile(s).catch(e=>{if(isNotFoundError(e))return null;throw e}),t=null===e?null:XP("sha256").update(e).digest("hex");if(t!==r.expectedSha256)return await JP.rm(o,{force:!0}),{stale:!0}}if(null===r.expectedSha256){try{await JP.link(o,s)}catch(e){if("EEXIST"===e.code)return await JP.rm(o,{force:!0}),{stale:!0};throw e}await JP.rm(o,{force:!0}).catch(()=>{})}else await JP.rename(o,s);return{stale:!1,mtime:e}}catch(e){throw await JP.rm(o,{force:!0}).catch(()=>{}),e}}async function readFileUnlocked(e){const t=normalizeAbsolutePath(e),n=await JP.readFile(t,"utf-8"),r=await JP.stat(t);return{content:n,mtime:r.mtimeMs}}async function readFileIfExistsUnlocked(e){try{return await readFileUnlocked(e)}catch(e){if(isNotFoundError(e))return null;throw e}}function normalizeAbsolutePath(e){return QP.resolve(e)}function isNotFoundError(e){return"object"==typeof e&&null!==e&&"ENOENT"===e.code}import{parseSync as tD}from"oxc-parser";var nD=class extends Error{constructor(e){super(e.join("\n")),this.name="UnsupportedLegacyCanvasError"}};function migrateLegacyCanvasToReact(e){const t=parseCanvasFile(e.filePath,e.source);if(t.canvasElementSpan)return{source:e.source,parsed:t,migrated:!1,edits:[]};if(t.misimportedSdkCanvasImports.length>0)return repairMisimportedSdkCanvasImports(e.filePath,e.source,t.misimportedSdkCanvasImports);try{return migrateNative(e.filePath,e.source,!1)}catch(t){if(t instanceof nD)throw t;return migrateNative(e.filePath,e.source,!0)}}function repairMisimportedSdkCanvasImports(e,t,n){const r=n.map(misimportedSdkCanvasImportMessage);if(!n.every(e=>e.rewritable))throw new nD(r);let s=t;for(const e of[...n].sort((e,t)=>t.sourceSpan.start-e.sourceSpan.start)){const n=t[e.sourceSpan.start]??'"';s=`${s.slice(0,e.sourceSpan.start)}${n}tempo-sdk/canvas${n}${s.slice(e.sourceSpan.end)}`}const i=parseCanvasFile(e,s),o=i.errors.filter(e=>"structural"===e.kind);if(!i.canvasElementSpan||o.length>0)throw new nD(r);return{source:s,parsed:i,migrated:!0,edits:[{start:0,end:t.length,value:s}]}}var rD=["Canvas","Storyboard","LegacyStoryboardV1","RouteStoryboard","HtmlStoryboard"];function migrateNative(e,t,n){const r=readLegacyFile(e,t),s=detectNewline2(t),i=[],o=[];for(const e of r.storyboards){const t=planStoryboard(e,r,n,i);t&&o.push(t)}if(i.length>0)throw new nD(i);const a=[];for(const e of o)a.push(...declarationEdits(e,t));for(const e of dedupeSpans(r.specifierExportSpans))a.push({...expandStatementForward(t,e),value:""});a.push(...r.defaultExportEdits);let c=collapseBlankLines(applyCanvasSourceEdits(t,a),s);c=removeUnusedLegacyTypeImports(e,c,s);const l=collectSourceIdentifiers(c),d=pickAvailableIdentifier2(l,canvasComponentName2(r.canvasName));l.add(d);const u=resolveSdkImportNames(neededSdkMembers(o),l),p=u.localNames.get("Canvas"),m=buildCanvasProps(r),f=0===o.length?`export default function ${d}() {${s} return <${p} ${m} />;${s}}${s}`:`export default function ${d}() {${s} return (${s} <${p} ${m}>${s} </${p}>${s} );${s}}${s}`;let g=collapseBlankLines(applyCanvasSourceEdits(c,[buildSdkImportEdit(e,c,u.importLine,s),{start:c.length,end:c.length,value:`${s}${f}`}]),s);for(const t of o)g=addCanvasStoryboard({filePath:e,source:g,storyboard:toAddInput(t)}).source;const y=parseCanvasFile(e,g);return assertMigratedInvariants(y,o,n),{source:g,parsed:y,migrated:!0,edits:[{start:0,end:t.length,value:g}]}}function assertMigratedInvariants(e,t,n){if(!e.canvasElementSpan)throw new Error("Migrated canvas is missing a <Canvas> element");for(const n of t){const t=e.storyboards.filter(e=>e.storyboardKey===n.id).length;if(1!==t)throw new Error(`Migrated canvas declares storyboard "${n.id}" ${t} times`)}if(e.errors.length>0){if(n){const t=e.errors.filter(e=>"structural"===e.kind);if(0===t.length)return;throw new nD(t.map(e=>e.message))}throw new Error("Migrated canvas re-parsed with errors")}}function readLegacyFile(e,t){const n=tD(e,t).program,r=Array.isArray(n?.body)?n.body:[],s=collectBindings(r),i=collectLocalFunctionReturnTypes(r),o={source:t,program:n,storyboards:[],storyboardLocalNames:new Set,specifierExportSpans:[],defaultExportEdits:[],canvasName:fallbackPageName(e),configMode:"none",hasPageBackgroundColor:!1,imports:collectImportLocalNames(r),moduleBindingNames:collectModuleBindingNames(r)},a=[],c=new Map;let l=0;const addStoryboard=(e,t,n,r,s,i,l,d)=>{c.has(e)?a.push(`Duplicate legacy storyboard export id "${e}" requires manual migration`):isLegacyStoryboardType(n)&&(c.set(e,t),o.storyboardLocalNames.add(t),o.storyboards.push({id:e,localName:t,typeName:n,init:d,editStatementSpan:s,declarationStart:i,ownerKind:r,declaratorCount:l}))};for(const e of r){const n=nodeSpan(e);if(!n)continue;if("ExportAllDeclaration"===e.type){a.push("export * declarations require manual migration");continue}if("ExportDefaultDeclaration"===e.type){if(l+=1,l>1){a.push("Multiple default exports require manual migration");continue}readDefaultExport(e,n,t,s,o,a);continue}if("ExportNamedDeclaration"!==e.type)continue;if("type"===e.exportKind)continue;if(e.source){a.push("Re-export declarations with a source require manual migration");continue}if(e.declaration){if("VariableDeclaration"===e.declaration.type){const t=e.declaration.declarations??[];for(const r of t){if("Identifier"!==r?.id?.type)continue;const s=r.id.typeAnnotation?.typeAnnotation,o=legacyTypeName(s)??(s||"const"!==e.declaration.kind?null:inferUnannotatedFactoryStoryboardType(r.init,i));addStoryboard(r.id.name,r.id.name,o,"declaration-export",n,e.declaration.start,t.length,r.init)}}continue}const r=e.specifiers??[];if(0===r.length)continue;const c=[];let d=!0;for(const e of r){const t=identifierName(e.local),n=identifierName(e.exported??e.local);if("type"===e?.exportKind){a.push(`Type-only export specifier "${t??"<unknown>"}" cannot be mixed with value export specifiers in a legacy canvas migration — requires manual migration`),d=!1;continue}if(!t||!n){a.push(exportSpecifierUnsupportedMessage(t??"<unknown>",n??t??"<unknown>")),d=!1;continue}const r=s.get(t),o=r?.typeName??(r&&!r.hasTypeAnnotation&&"const"===r.kind?inferUnannotatedFactoryStoryboardType(r.init,i):null);r&&isLegacyStoryboardType(o)?c.push({exportedName:n,localName:t,typeName:o,binding:r}):(a.push(exportSpecifierUnsupportedMessage(t,n)),d=!1)}if(d){o.specifierExportSpans.push(n);for(const e of c)addStoryboard(e.exportedName,e.localName,e.typeName,"specifier-export",e.binding.statementSpan,e.binding.statementSpan.start,e.binding.declaratorCount,e.binding.init)}}if(a.length>0)throw new nD(a);return o}function inferUnannotatedFactoryStoryboardType(e,t){const n=unwrapTsExpression(e);if("CallExpression"!==n?.type)return null;const r=unwrapTsExpression(n.callee);if("Identifier"!==r?.type)return null;const s=t.get(r.name);return"TempoStoryboard"===s?s:null}function exportSpecifierUnsupportedMessage(e,t){const n=e===t?"":` (exported as "${t}")`;return`Export specifier "${e}"${n} does not reference a recognizable legacy storyboard; migration would drop its export — requires manual migration`}function readDefaultExport(e,t,n,r,s,i){const o=unwrapTsExpression(e.declaration);if("Identifier"===o?.type){const e=r.get(o.name),i=unwrapTsExpression(e?.init),a=readObjectStringProperty(i,"name");a&&(s.canvasName=a);const c=isCleanConfigObject(i)&&void 0!==e&&!isBindingReferencedOutside(s.program,o.name,[e.statementSpan,t]);return void(c?(s.configMode="inline",s.backgroundColorLiteral=readObjectStringProperty(i,"backgroundColor")??void 0,s.defaultExportEdits.push({...expandStatementForward(n,t),value:""},{...expandStatementForward(n,e.statementSpan),value:""})):(s.configMode="kept",s.pageBindingName=o.name,s.hasPageBackgroundColor=hasObjectProperty(i,"backgroundColor"),s.defaultExportEdits.push({...expandStatementForward(n,t),value:""})))}if("ObjectExpression"===o?.type){const r=readObjectStringProperty(o,"name");if(r&&(s.canvasName=r),isCleanConfigObject(o))s.configMode="inline",s.backgroundColorLiteral=readObjectStringProperty(o,"backgroundColor")??void 0,s.defaultExportEdits.push({...expandStatementForward(n,t),value:""});else{const t=pickAvailableIdentifier2(collectSourceIdentifiers(n),"page");s.configMode="kept",s.pageBindingName=t,s.hasPageBackgroundColor=hasObjectProperty(o,"backgroundColor"),s.defaultExportEdits.push({start:e.start,end:o.start,value:`const ${t} = `})}return}i.push("Default export must be a page object or identifier")}function planStoryboard(e,t,n,r){const s=unwrapTsExpression(e.init);if("TempoRouteStoryboard"===e.typeName){let n=validateForwardedStoryboardProperties("TempoRouteStoryboard",e.id,s,sD,r);const i=readObjectStringProperty(s,"name");if(hasObjectProperty(s,"name")&&null===i&&(r.push(`Legacy TempoRouteStoryboard export "${e.id}" requires a literal name string when name is set`),n=!1),!n)return null;const o=readObjectLayoutProperty(s);if(!o||void 0===o.width||void 0===o.height)return r.push(`Legacy TempoRouteStoryboard export "${e.id}" requires a literal layout object`),null;const a=readObjectStringProperty(s,"route");return a?{kind:"route",id:e.id,route:a,...i?{name:i}:{},layout:o,scan:e,keepDeclaration:isBindingReferencedOutsideDeclaration(e,t)}:(r.push(`Legacy TempoRouteStoryboard export "${e.id}" requires a literal route string`),null)}if("TempoHtmlStoryboard"===e.typeName){let n=validateForwardedStoryboardProperties("TempoHtmlStoryboard",e.id,s,iD,r);const i=readObjectStringProperty(s,"name");if(hasObjectProperty(s,"name")&&null===i&&(r.push(`Legacy TempoHtmlStoryboard export "${e.id}" requires a literal name string when name is set`),n=!1),!n)return null;const o=readObjectLayoutProperty(s);if(!o||void 0===o.width||void 0===o.height)return r.push(`Legacy TempoHtmlStoryboard export "${e.id}" requires a literal layout object`),null;const a=readObjectStringProperty(s,"filepath");return a?{kind:"html",id:e.id,filepath:a,...i?{name:i}:{},layout:o,scan:e,keepDeclaration:isBindingReferencedOutsideDeclaration(e,t)}:(r.push(`Legacy TempoHtmlStoryboard export "${e.id}" requires a literal filepath string`),null)}const i=readObjectStringProperty(s,"name")??void 0;return planComponentStoryboard(e,s,t,n,i)}function planComponentStoryboard(e,t,n,r,s){const i={kind:"component",conversion:"WRAPPER",id:e.id,scan:e};if(r)return i;if(!isNativeEligible(e,t,n))return i;const o=getRenderFunction(t);if(!o)return i;const a=readObjectLayoutProperty(t);if(!a)return i;"root-element"===readObjectStringProperty(getObjectPropertyFromNode(t,"layout")?.value,"intrinsicSizing")&&(a.intrinsicSizing="root-element");const c=classifyRenderComponent(o,n);return"HOISTED"===c.conversion?{kind:"component",conversion:"HOISTED",id:e.id,...s?{name:s}:{},layout:a,componentExpr:e.localName,renderFn:o,scan:e}:{kind:"component",conversion:c.conversion,id:e.id,...s?{name:s}:{},layout:a,componentExpr:c.componentExpr,...c.propsExpr?{propsExpr:c.propsExpr}:{},scan:e}}var sD=new Set(["name","route","layout"]),iD=new Set(["name","filepath","layout"]);function validateForwardedStoryboardProperties(e,t,n,r,s){if(!n||"ObjectExpression"!==n.type)return!0;let i=!0;for(const o of n.properties??[]){if("SpreadElement"===o?.type){s.push(`Legacy ${e} export "${t}" has a spread property that migration cannot carry over — requires manual migration`),i=!1;continue}if("Property"!==o?.type){s.push(`Legacy ${e} export "${t}" has an unsupported property entry that migration cannot carry over — requires manual migration`),i=!1;continue}if(o.computed){s.push(`Legacy ${e} export "${t}" has a computed property key that migration cannot carry over — requires manual migration`),i=!1;continue}const n=readPropertyKeyName3(o.key);n?"get"!==o.kind&&"set"!==o.kind?r.has(n)||(s.push(`Legacy ${e} export "${t}" has property "${n}" that migration cannot carry over — requires manual migration`),i=!1):(s.push(`Legacy ${e} export "${t}" has ${"get"===o.kind?"getter":"setter"} property "${n}" that migration cannot carry over — requires manual migration`),i=!1):(s.push(`Legacy ${e} export "${t}" has a non-static property key that migration cannot carry over — requires manual migration`),i=!1)}return i}function isNativeEligible(e,t,n){if(!t||"ObjectExpression"!==t.type)return!1;let r=!1;for(const e of t.properties??[]){if("SpreadElement"===e?.type)return!1;if("Property"!==e?.type||e.computed)return!1;if("get"===e.kind||"set"===e.kind)return!1;const t=readPropertyKeyName3(e.key);if("render"!==t&&"name"!==t&&"layout"!==t)return!1;if("render"===t){if(r=!0,e.method)return!1;const t=e.value;if("ArrowFunctionExpression"!==t?.type&&"FunctionExpression"!==t?.type)return!1;if(0!==(t.params?.length??0))return!1}}if(!r)return!1;const s=getObjectPropertyFromNode(t,"name");return!(s&&!isStringLiteral(s.value))&&(!!readObjectLayoutProperty(t)&&(!(e.declaratorCount>1)&&!isBindingReferencedOutsideDeclaration(e,n)))}function isBindingReferencedOutsideDeclaration(e,t){return isBindingReferencedOutside(t.program,e.localName,[e.editStatementSpan,...t.specifierExportSpans])}function getRenderFunction(e){const t=getObjectPropertyFromNode(e,"render"),n=t?.value;return"ArrowFunctionExpression"===n?.type||"FunctionExpression"===n?.type?n:null}function classifyRenderComponent(e,t){const n=resolveRenderBody(e);if(!n||"JSXElement"!==n.type)return{conversion:"HOISTED"};const r=n.openingElement?.name,s=jsxTagRootIdentifier(r);if(!s)return{conversion:"HOISTED"};if(hasMeaningfulChildren(n))return{conversion:"HOISTED"};if(!rootIdentifierSurvives(s,t))return{conversion:"HOISTED"};const i=t.source.slice(r.start,r.end),o=n.openingElement?.attributes??[];if(0===o.length)return{conversion:"DIRECT",componentExpr:i};const a=buildPropsObject(o,t.source);return null===a?{conversion:"HOISTED"}:{conversion:"WITH_PROPS",componentExpr:i,propsExpr:a}}function resolveRenderBody(e){return"ArrowFunctionExpression"===e.type?"BlockStatement"===e.body?.type?singleReturnExpression(e.body):unwrapTsExpression(e.body):"FunctionExpression"===e.type?singleReturnExpression(e.body):null}function singleReturnExpression(e){const t=(e?.body??[]).filter(Boolean);if(1!==t.length)return null;const n=t[0];return"ReturnStatement"===n.type&&n.argument?unwrapTsExpression(n.argument):null}function jsxTagRootIdentifier(e){if("JSXIdentifier"===e?.type)return/^[A-Z]/.test(e.name)?e.name:null;if("JSXMemberExpression"===e?.type){let t=e.object;for(;"JSXMemberExpression"===t?.type;)t=t.object;return"JSXIdentifier"===t?.type?t.name:null}return null}function hasMeaningfulChildren(e){for(const t of e.children??[]){if("JSXText"===t?.type){if("string"==typeof t.value&&""===t.value.trim())continue;return!0}return!0}return!1}function rootIdentifierSurvives(e,t){return!!t.imports.has(e)||t.moduleBindingNames.has(e)&&!t.storyboardLocalNames.has(e)}function buildPropsObject(e,t){const n=[];for(const r of e){if("JSXSpreadAttribute"===r?.type){n.push(`...${t.slice(r.argument.start,r.argument.end)}`);continue}if("JSXAttribute"!==r?.type)return null;if("JSXIdentifier"!==r.name?.type)return null;const e=r.name.name;if("key"===e||"ref"===e)return null;const s=/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e),i=r.value;if(null!=i){if(!isStringLiteral(i)){if("JSXExpressionContainer"===i.type){const e=i.expression;if(!e||"JSXEmptyExpression"===e.type)return null;if("JSXElement"===e.type||"JSXFragment"===e.type)return null;if(isStringLiteral(e)){n.push(`${s}: ${JSON.stringify(e.value)}`);continue}n.push(`${s}: ${t.slice(e.start,e.end)}`);continue}return null}n.push(`${s}: ${JSON.stringify(decodeJsxEntities(i.value))}`)}else n.push(`${s}: true`)}return`{ ${n.join(", ")} }`}function declarationEdits(e,t){const n=e.scan;if("component"!==e.kind)return e.keepDeclaration?stripExportPrefixEdits(n):[{...expandStatementForward(t,n.editStatementSpan),value:""}];if("DIRECT"===e.conversion||"WITH_PROPS"===e.conversion)return[{...expandStatementForward(t,n.editStatementSpan),value:""}];if("HOISTED"===e.conversion){const r=t.slice(e.renderFn.start,e.renderFn.end);return[{start:n.editStatementSpan.start,end:n.editStatementSpan.end,value:`const ${n.localName} = ${r};`}]}return stripExportPrefixEdits(n)}function stripExportPrefixEdits(e){return"declaration-export"===e.ownerKind?[{start:e.editStatementSpan.start,end:e.declarationStart,value:""}]:[]}var oD=new Set(["TempoStoryboard","TempoRouteStoryboard","TempoHtmlStoryboard","TempoPage","TempoCanvasConfig"]);function removeUnusedLegacyTypeImports(e,t,n){const r=tD(e,t).program,s=Array.isArray(r?.body)?r.body:[],i=s.filter(e=>"ImportDeclaration"===e?.type);let o=t;for(const e of[...i].sort((e,t)=>t.start-e.start))o=o.slice(0,e.start)+" ".repeat(e.end-e.start)+o.slice(e.end);const a=[];for(const e of i){if("tempo-sdk"!==e.source?.value)continue;const n=e.specifiers??[],r=n.filter(t=>"ImportSpecifier"===t?.type&&("type"===t.importKind||"type"===e.importKind)&&oD.has(t.imported?.name)&&!hasIdentifier(o,t.local?.name??""));if(0!==r.length)if(r.length!==n.length)for(const e of r)a.push(removeImportSpecifierEdit(t,e));else a.push({...expandStatementForward(t,{start:e.start,end:e.end}),value:""})}return 0===a.length?t:collapseBlankLines(applyCanvasSourceEdits(t,a),n)}function removeImportSpecifierEdit(e,t){let n=t.start,r=t.end,s=r;for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(","===e[s]){for(r=s+1;r<e.length&&(" "===e[r]||"\t"===e[r]);)r++;return{start:n,end:r,value:""}}let i=n;for(;i>0&&/\s/.test(e[i-1]??"");)i--;return","===e[i-1]&&(n=i-1),{start:n,end:r,value:""}}function neededSdkMembers(e){const t=new Set(["Canvas"]);for(const n of e)"route"===n.kind?t.add("RouteStoryboard"):"html"===n.kind?t.add("HtmlStoryboard"):"WRAPPER"===n.conversion?t.add("LegacyStoryboardV1"):t.add("Storyboard");return rD.filter(e=>t.has(e))}function resolveSdkImportNames(e,t){const n=new Set(t),r=new Map,s=[];for(const t of e){const e=n.has(t)?pickAvailableIdentifier2(n,`TempoCanvas${t}`):t;n.add(e),r.set(t,e),s.push(e===t?t:`${t} as ${e}`)}return{localNames:r,importLine:`import { ${s.join(", ")} } from "tempo-sdk/canvas";`}}function buildSdkImportEdit(e,t,n,r){const s=tD(e,t).program,i=lastImportEnd(Array.isArray(s?.body)?s.body:[])??topLevelInsertionOffset2(t),o=0===i||t.slice(0,i).endsWith(r)?"":r;return{start:i,end:i,value:`${o}${n}${r}`}}function buildCanvasProps(e){if("inline"===e.configMode){const t=[formatJsxStringAttribute("name",e.canvasName)];return void 0!==e.backgroundColorLiteral&&t.push(formatJsxStringAttribute("backgroundColor",e.backgroundColorLiteral)),t.join(" ")}if("kept"===e.configMode&&e.pageBindingName){const t=[`name={${e.pageBindingName}.name}`];return e.hasPageBackgroundColor&&t.push(`backgroundColor={${e.pageBindingName}.backgroundColor}`),t.join(" ")}return formatJsxStringAttribute("name",e.canvasName)}function toAddInput(e){return"route"===e.kind?{kind:"route",id:e.id,route:e.route,layout:e.layout,...e.name?{name:e.name}:{}}:"html"===e.kind?{kind:"html",id:e.id,filepath:e.filepath,layout:e.layout,...e.name?{name:e.name}:{}}:"WRAPPER"===e.conversion?{kind:"legacy-v1",id:e.id,storyboardExpression:e.scan.localName}:{kind:"component",id:e.id,layout:e.layout,...e.name?{name:e.name}:{},componentExpression:e.componentExpr,...e.propsExpr?{props:e.propsExpr}:{}}}function collectBindings(e){const t=new Map,collect=e=>{if("VariableDeclaration"!==e?.type)return;const n=e.declarations?.length??0;for(const r of e.declarations??[]){if("Identifier"!==r?.id?.type)continue;const s=r.id.typeAnnotation?.typeAnnotation,i=legacyTypeName(s);t.set(r.id.name,{typeName:isLegacyStoryboardType(i)?i:null,init:r.init,kind:variableDeclarationKind(e.kind),hasTypeAnnotation:void 0!==s,statementSpan:{start:e.start,end:e.end},declaratorCount:n})}};for(const t of e)collect(t),"ExportNamedDeclaration"===t?.type&&collect(t.declaration);return t}function variableDeclarationKind(e){return"let"===e||"var"===e?e:"const"}function collectLocalFunctionReturnTypes(e){const t=new Map,collect=e=>{if("FunctionDeclaration"!==e?.type||"Identifier"!==e.id?.type)return;const n=legacyTypeName(e.returnType?.typeAnnotation);isLegacyStoryboardType(n)&&t.set(e.id.name,n)};for(const t of e)collect(t),"ExportNamedDeclaration"===t?.type&&collect(t.declaration);return t}function collectImportLocalNames(e){const t=new Set;for(const n of e)if("ImportDeclaration"===n?.type)for(const e of n.specifiers??[])e?.local?.name&&t.add(e.local.name);return t}function collectModuleBindingNames(e){const t=new Set,addVariable=e=>{if("VariableDeclaration"===e?.type)for(const n of e.declarations??[])"Identifier"===n?.id?.type&&t.add(n.id.name)},addDeclaration=e=>{e&&("VariableDeclaration"===e.type?addVariable(e):"FunctionDeclaration"!==e.type&&"ClassDeclaration"!==e.type||!e.id?.name||t.add(e.id.name))};for(const t of e)addDeclaration("ExportNamedDeclaration"===t?.type?t.declaration:t);return t}function isLegacyStoryboardType(e){return"TempoStoryboard"===e||"TempoRouteStoryboard"===e||"TempoHtmlStoryboard"===e}function legacyTypeName(e){if(!e||"TSTypeReference"!==e.type)return null;const t=e.typeName;return"Identifier"===t?.type?t.name:"TSQualifiedName"===t?.type&&"Identifier"===t.right?.type?t.right.name:null}function identifierName(e){return"Identifier"===e?.type?e.name:"Literal"===e?.type&&"string"==typeof e.value?e.value:null}function isStringLiteral(e){return"Literal"===e?.type&&"string"==typeof e.value}var aD={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",copy:"©",reg:"®",trade:"™",hellip:"…",mdash:"—",ndash:"–",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",laquo:"«",raquo:"»",times:"×",divide:"÷",deg:"°",plusmn:"±",cent:"¢",pound:"£",euro:"€",yen:"¥",sect:"§",para:"¶",middot:"·",bull:"•"};function decodeJsxEntities(e){return e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g,(e,t)=>{if("#"===t[0]){const n="x"===t[1]||"X"===t[1]?Number.parseInt(t.slice(2),16):Number.parseInt(t.slice(1),10);return Number.isFinite(n)&&n>=0&&n<=1114111?String.fromCodePoint(n):e}return aD[t]??e})}function isCleanConfigObject(e){if(!e||"ObjectExpression"!==e.type)return!1;for(const t of e.properties??[]){if("Property"!==t?.type||t.computed)return!1;const e=readPropertyKeyName3(t.key);if("name"!==e&&"backgroundColor"!==e)return!1;if(!isStringLiteral(t.value))return!1}return!0}function readObjectStringProperty(e,t){const n=getObjectPropertyFromNode(e,t);return isStringLiteral(n?.value)?n.value.value:null}function hasObjectProperty(e,t){return null!==getObjectPropertyFromNode(e,t)}function readObjectLayoutProperty(e){const t=getObjectPropertyFromNode(e,"layout"),n=unwrapTsExpression(t?.value);if(!n||"ObjectExpression"!==n.type)return null;const r=readObjectNumberProperty(n,"x"),s=readObjectNumberProperty(n,"y"),i=readObjectNumberProperty(n,"width"),o=readObjectNumberProperty(n,"height");if(null==r||null==s)return null;if((null==i||null==o)&&(getObjectPropertyFromNode(n,"width")||getObjectPropertyFromNode(n,"height")))return null;const a=readObjectNumberProperty(n,"zIndex"),c=getObjectPropertyFromNode(n,"intrinsicSizing"),l=readObjectStringProperty(n,"intrinsicSizing");return c&&"root-element"!==l?null:{x:r,y:s,...null==i||null==o?{}:{width:i,height:o},...null==a?{}:{zIndex:a}}}function readObjectNumberProperty(e,t){const n=getObjectPropertyFromNode(e,t),r=unwrapTsExpression(n?.value);return"Literal"===r?.type&&"number"==typeof r.value?r.value:"UnaryExpression"===r?.type&&"-"===r.operator&&"Literal"===r.argument?.type&&"number"==typeof r.argument.value?-r.argument.value:null}function getObjectPropertyFromNode(e,t){const n=unwrapTsExpression(e);if(!n||"ObjectExpression"!==n.type)return null;for(const e of n.properties??[])if("Property"===e?.type&&!e.computed&&readPropertyKeyName3(e.key)===t)return e;return null}function readPropertyKeyName3(e){return"Identifier"===e?.type?e.name:"Literal"===e?.type&&"string"==typeof e.value?e.value:null}function isBindingReferencedOutside(e,t,n){const excluded=e=>{const t=nodeSpan(e);return!!t&&n.some(e=>t.start>=e.start&&t.end<=e.end)};let r=!1;return walkWithParent(e,(e,n,s)=>{r||"Identifier"!==e.type&&"JSXIdentifier"!==e.type||e.name===t&&(excluded(e)||isNonReferenceNamePosition(n,s)||(r=!0))}),r}function isNonReferenceNamePosition(e,t){return!!e&&(!("string"!=typeof e.type||!e.type.startsWith("Import"))||("Property"===e.type&&"key"===t&&!e.computed&&!e.shorthand||("MemberExpression"===e.type&&"property"===t&&!e.computed||"JSXMemberExpression"===e.type&&"property"===t||"JSXAttribute"===e.type&&"name"===t)))}function nodeSpan(e){return"number"==typeof e?.start&&"number"==typeof e?.end&&Number.isFinite(e.start)&&Number.isFinite(e.end)?{start:e.start,end:e.end}:null}function lastImportEnd(e){let t=null;for(const n of e){if("ImportDeclaration"!==n?.type)continue;const e=nodeSpan(n);e&&(t=Math.max(t??0,e.end))}return t}function dedupeSpans(e){const t=new Set,n=[];for(const r of e){const e=`${r.start}:${r.end}`;t.has(e)||(t.add(e),n.push(r))}return n}function collectSourceIdentifiers(e){return new Set(Array.from(e.matchAll(/\b[A-Za-z_$][\w$]*\b/g),e=>e[0]))}function pickAvailableIdentifier2(e,t){const n=/^[A-Za-z_$]/.test(t)?t:`Canvas${t}`;if(!e.has(n))return n;for(let t=2;t<1e4;t+=1){const r=`${n}${t}`;if(!e.has(r))return r}throw new Error(`Unable to find available identifier for ${t}`)}function canvasComponentName2(e){const t=toIdentifier2(e);return`${t[0].toUpperCase()}${t.slice(1)}Canvas`}function toIdentifier2(e){const t=e.replace(/[^a-zA-Z0-9_$]+/g," ").trim().split(/\s+/).map((e,t)=>{if(0===e.length)return"";const n=e.replace(/^[0-9]+/,"");if(0===n.length)return"";const r=n.toLowerCase();return 0===t?r:r[0].toUpperCase()+r.slice(1)}).join(""),n=t.length>0?t:"componentRef";return/^[a-zA-Z_$]/.test(n)?n:`component${n}`}function isReactCanvasFile(e){return void 0!==e.canvasElementSpan}async function ensureCanvasPageFileMigrated(e){const t=await VP.readFile(e,"utf-8");if(isReactCanvasFile(parseCanvasFile(e,t)))return{migrated:!1};const n=migrateLegacyCanvasToReact({filePath:e,source:t});return n.migrated?(await eD.writeFile(e,n.source),{migrated:!0}):{migrated:!1}}import cD from"fs/promises";import lD from"path";import dD from"typescript";import{readdir as uD,stat as pD}from"fs/promises";import hD from"path";var mD="index.canvas.tsx";async function pathExists9(e){try{return await pD(e),!0}catch{return!1}}async function findPageFilesInPagesRoot(e){async function walkDirectories(e){let t=[];try{t=await uD(e,{withFileTypes:!0})}catch{return[]}const n=[],r=hD.join(e,mD);await pathExists9(r)&&n.push(r);const s=await Promise.all(t.filter(e=>e.isDirectory()).map(t=>walkDirectories(hD.join(e,t.name))));return[...n,...s.flat()]}const t=await walkDirectories(e);return t.sort((e,t)=>e.localeCompare(t))}async function resolveCanvasesRoot(e){try{return(await resolveTempoConfig(e)).pagesDir}catch{return hD.join(e,"tempo","designs")}}async function findPageFilesInRepo(e){return await findPageFilesInPagesRoot(await resolveCanvasesRoot(e))}async function listPageInfosInRepo(e){const t=await findPageFilesInRepo(e.repoRoot),n=await Promise.all(t.map(async t=>{const n=await parsePageFile(t);return{filePath:t,pageDir:hD.dirname(t),repoName:e.repoName,pageName:n.pageName,storyboardNames:n.storyboards.map(e=>e.exportName),home:n.home,homeRoute:n.storyboards.some(e=>"/"===e.route)}}));return n.sort((e,t)=>e.filePath.localeCompare(t.filePath))}import{readdir as fD,stat as gD}from"fs/promises";import yD from"path";var bD="index.canvas.tsx",vD=".canvas.tsx";async function statSafe(e){try{const t=await gD(e);return{isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}async function resolveCanvasFilePath(e){const t=yD.resolve(e),n=await statSafe(t);if(!n)return null;let r;if(n.isFile){if(t.endsWith(vD))return t;r=yD.dirname(t)}else{if(!n.isDirectory)return null;r=t}const s=yD.join(r,bD);if(await statSafe(s))return s;let i;try{i=await fD(r,{withFileTypes:!0})}catch{return null}const o=i.filter(e=>e.isFile()&&e.name.endsWith(vD));return 1===o.length?yD.join(r,o[0].name):null}async function resolveCanvasDirPath(e){const t=await resolveCanvasFilePath(e);return t?yD.dirname(t):null}import{execFile as wD}from"child_process";import{access as _D,mkdir as xD,readFile as TD,rm as kD,stat as SD}from"fs/promises";import ED from"path";import{promisify as AD}from"util";var CD=AD(wD);async function pathExists10(e){try{return await _D(e),!0}catch{return!1}}function slugifySegment(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function slugifyPageName(e){return e.split("/").map(slugifySegment).filter(e=>e.length>0).join("/")}function normalizeStoryboard(e){const t=e.exportName?.trim();if(!t)throw new Error("Each storyboard must provide a non-empty exportName");const n=Number.isFinite(e.width)?Math.max(1,Math.round(e.width)):IP,r=Number.isFinite(e.height)?Math.max(1,Math.round(e.height)):PP,s="string"==typeof e.route&&e.route.trim().length>0,i=Boolean(e.importPath?.trim()),o=e.preview?.trim()??"";if(""!==o&&(s||i))throw new Error(`Storyboard "${t}" sets preview, which cannot be combined with route or importPath`);if(!s&&!i&&""===o)throw new Error(`Storyboard "${t}" must provide route, importPath or preview`);return{exportName:t,...e.name?{name:e.name}:{},...e.importPath?{importPath:e.importPath}:{},...e.importName?{importName:e.importName}:{},...s?{route:e.route}:{},...o?{preview:o}:{},width:n,height:r}}function buildInitSummary(e){return{projectRoot:e.projectRoot,tempobookPath:e.tempobookPath,typesFile:"",tsconfigUpdated:!1,initializedNow:e.initializedNow??!0,waitedForInFlight:!1,usedCachedResult:!1,filesUpdated:e.changedFiles,installPerformed:!1,warnings:[]}}function notInitializedMessage(e){return`Project is not initialized for Tempo canvases: no tempo.config.json found in ${e} or ${ED.join(e,"tempo")}. Run canvas_project_init first.`}async function useProject(e,t,n,r){if(t)return await r(t,null);const s=await UI.open(e);try{const e=await s.initializeExistingProject({framework:n});return await r(s,e)}finally{await s.dispose()}}async function useExistingProject(e,t,n){if(!await tempoConfigExists(e))throw new Error(notInitializedMessage(e));if(t)return await n(t);const r=await UI.open(e);try{return await n(r)}finally{await r.dispose()}}async function initializePagesSupport(e){const t=ED.resolve(e.projectRoot);return useProject(t,e.project,e.framework,async(n,r)=>{const s=r?.config??await n.getResolvedConfig();let i=r?[...r.devserverInit.changedFiles]:[];const o=await setUpFlutterApp(s);if(o.packages.length>0&&o.flutterOnly?await seedFlutterHomeCanvas(s,o):await seedHomeCanvas(s),await seedZoneDirectories(s),e.onLog?.(`[page-tools] Tempo host at ${s.tempoRoot}`),e.forceRegenerate){const e=await n.reconcile("page-tools-force-regenerate");i=Array.from(new Set([...i,...e.devserver.changedFiles]))}e.onLog?.("[page-tools] Initialization complete.");const a=null!==r?e.framework:void 0;return{...buildInitSummary({projectRoot:t,tempobookPath:s.tempoRoot,changedFiles:i}),warnings:[...r?.warnings??[],...o.warnings],framework:a??await n.getFramework()}})}function resolveCanvasLocalStubPath(e,t,n){if(!e.startsWith("./")&&!e.startsWith("../"))return null;const r=ED.resolve(t,componentImportPath(e)),s=ED.relative(t,r);return s.startsWith("..")||ED.isAbsolute(s)?null:hasComponentModuleExtension(r)?r:`${r}${qP[n].extension}`}var ID=[...new Set([".tsx",".ts",".jsx",".js",...Object.values(qP).map(e=>e.extension)])];async function canvasImportSpecifier(e,t,n){const r=componentImportPath(e),s=e.slice(r.length),i=r.startsWith("./")||r.startsWith("../");if(i)return e;const relativeToCanvas=e=>{const t=ED.relative(n,e).split(ED.sep).join("/");return`${t.startsWith(".")?"":"./"}${t}${s}`};if(ED.isAbsolute(r))return relativeToCanvas(r);const o=ED.resolve(t,r);if(!await isImportableModule(o))return e;const a=r.startsWith("@")?r.split("/").slice(0,2).join("/"):r.split("/")[0],c=await findInstalledPackageDir2(n,a);if(c)throw new Error(`import_path "${e}" names both the project file ${o} and the installed package at ${c}. Pass the project file relative to the canvas folder ("${relativeToCanvas(o)}"), or the package import exactly as the app writes it.`);return relativeToCanvas(o)}async function isImportableModule(e){const isFile2=async e=>{try{return(await SD(e)).isFile()}catch{return!1}};if(await isFile2(e))return!0;for(const t of ID){if(await isFile2(`${e}${t}`))return!0;if(await isFile2(ED.join(e,`index${t}`)))return!0}return!1}async function findInstalledPackageDir2(e,t){let n=e;for(;;){const e=ED.join(n,"node_modules",t);if(await pathExists10(e))return e;const r=ED.dirname(n);if(r===n)return null;n=r}}async function scaffoldCanvasLocalStubs(e,t,n){const r=new Set,s=new Set;for(const i of e){if(!i.importPath)continue;const e=storyboardFrameworkForImport(i.importPath,n),o=resolveCanvasLocalStubPath(i.importPath,t,e);o&&(r.has(o)?s.add(i.exportName):await pathExists10(o)||(await xD(ED.dirname(o),{recursive:!0}),await eD.writeFile(o,qP[e].stub(i.exportName,i.importName)),r.add(o),s.add(i.exportName)))}return s}async function markCanvasAsHome(e){const t=await TD(e,"utf-8");if(sourceHasHomeMarker(t))return!1;const n=`${CP}\n${t}`;return await eD.writeFile(e,n),!0}async function unmarkCanvasAsHome(e){const t=await TD(e,"utf-8");if(!sourceHasHomeMarker(t))return!1;const n=t.split("\n").filter(e=>!e.includes(AP)).join("\n");return await eD.writeFile(e,n),!0}async function createPage(e){const t=ED.resolve(e.projectRoot),n=e.pageName?.trim();if(!n)throw new Error("pageName is required");if(!await pathExists10(t))throw new Error(`Project root does not exist: ${t}`);return useExistingProject(t,e.project,async r=>{const s=await r.getResolvedConfig(),i=await r.getUiFramework(),o=buildInitSummary({projectRoot:t,tempobookPath:s.tempoRoot,changedFiles:[],initializedNow:!1}),a=slugifyPageName(n);if(!a)throw new Error(`Unable to derive a valid canvas slug from pageName "${e.pageName}"`);const c=a.split("/"),l=c.length>1?ED.join(s.pagesDir,...c):ED.join(await resolveFreeformCanvasesDir(s.pagesDir),a),d=ED.join(l,"index.canvas.tsx");if(await pathExists10(d))throw new Error(`Canvas already exists: ${d}`);const u=await Promise.all((e.storyboards??[]).map(async e=>{const n=normalizeStoryboard(e);if(!n.importPath)return n;const r=await canvasImportSpecifier(n.importPath,t,l);return{...n,importPath:r}})),p=u.map(e=>({name:e.exportName,width:e.width,height:e.height})),m=computeStoryboardPositions({existing:[],newStoryboards:p}),f=u.map((e,t)=>({...e,x:m[t].x,y:m[t].y,width:m[t].width,height:m[t].height})),g=n.split("/").filter(Boolean).pop()??n,y=generatePageFileContent({pageName:g,storyboards:f,home:e.home,backgroundColor:e.backgroundColor,uiFramework:i});await xD(l,{recursive:!0}),await eD.writeFile(d,y);const b=await scaffoldCanvasLocalStubs(u,l,i);return{projectRoot:t,pageDir:l,pageFile:d,pageSlug:a,storyboards:f.map((e,t)=>({exportName:e.exportName,x:e.x,y:e.y,width:m[t].width,height:m[t].height,...b.has(e.exportName)?{stub:!0}:{}})),initResult:o}})}import PD from"path";import DD from"typescript";import RD from"path";import{relative as ND}from"path";import{access as OD,readdir as FD,readFile as LD}from"fs/promises";import{basename as MD,join as UD}from"path";import{access as jD,stat as BD}from"fs/promises";import{join as $D}from"path";var WD={NPM:"npm",YARN:"yarn",PNPM:"pnpm",BUN:"bun"};import{readFile as HD}from"fs/promises";import{join as qD}from"path";function toStringRecord2(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>"string"==typeof e))}async function readPackageJson(e){const t=qD(e,"package.json");let n,r;try{n=await HD(t,"utf8")}catch(e){const n=e instanceof Error?e.message:"Unknown read error";throw new Error(`Could not read package.json at ${t}: ${n}`)}try{r=JSON.parse(n)}catch(e){const n=e instanceof Error?e.message:"Unknown JSON parse error";throw new Error(`Invalid package.json at ${t}: ${n}`)}if(!r||"object"!=typeof r||Array.isArray(r))throw new Error(`Invalid package.json at ${t}: expected object`);const s=r,i=toStringRecord2(s.dependencies),o=toStringRecord2(s.devDependencies);return{dependencies:i,devDependencies:o,allDependencies:{...i,...o},scripts:toStringRecord2(s.scripts),packageManager:"string"==typeof s.packageManager?s.packageManager:void 0}}import{access as zD}from"fs/promises";import{join as GD}from"path";var VD=[{files:["bun.lockb","bun.lock"],packageManager:WD.BUN},{files:["pnpm-lock.yaml"],packageManager:WD.PNPM},{files:["yarn.lock"],packageManager:WD.YARN},{files:["package-lock.json"],packageManager:WD.NPM}];import{access as KD,readFile as XD}from"fs/promises";import{join as YD,normalize as JD}from"path";import QD from"typescript";import{isBuiltin as ZD}from"module";import eR from"path";import tR from"typescript";import nR from"typescript";var rR=/\.(?:ts|tsx|mts|cts)$/;function collectValueIdentifiers(e){const t=new Set;function isDeclarationName(e){const t=e.parent;if(!t)return!1;if(nR.isImportSpecifier(t)||nR.isImportClause(t)||nR.isNamespaceImport(t)||nR.isImportEqualsDeclaration(t))return!0;const isNameOf=t=>t.name===e;return nR.isPropertyAccessExpression(t)?t.name===e:(nR.isPropertyAssignment(t)||nR.isJsxAttribute(t)||!!(nR.isPropertyDeclaration(t)||nR.isMethodDeclaration(t)||nR.isPropertySignature(t)||nR.isGetAccessorDeclaration(t)||nR.isSetAccessorDeclaration(t)||nR.isEnumMember(t)))&&isNameOf(t)}function visit2(e){nR.isTypeNode(e)||nR.isInterfaceDeclaration(e)||nR.isTypeAliasDeclaration(e)||nR.isImportDeclaration(e)||(nR.isIdentifier(e)&&!isDeclarationName(e)&&t.add(e.text),nR.forEachChild(e,visit2))}return visit2(e),t}function extractImportEdges(e,t,n){const r=nR.createSourceFile(e,t,nR.ScriptTarget.Latest,!0),s=rR.test(e),i=n||!s;let o;const isUsedAsValue=e=>(o??=collectValueIdentifiers(r)).has(e),a=[];function addEdge(e,t,n,s){if(!e||!nR.isStringLiteralLike(e))return;const i=r.getLineAndCharacterOfPosition(e.getStart(r));a.push({specifier:e.text,form:t,valueNames:n,loadsAtRuntime:s,line:i.line+1,column:i.character})}function importDeclarationEdge(e){const t=e.importClause;if(!t)return void addEdge(e.moduleSpecifier,"static",[],!0);if(t.isTypeOnly)return void addEdge(e.moduleSpecifier,"static",[],!1);const r=t.namedBindings,s=r&&nR.isNamedImports(r)?r.elements.filter(e=>!e.isTypeOnly):[],o=!t.name&&void 0!==r&&nR.isNamedImports(r)&&r.elements.length>0&&0===s.length;if(!n&&o)return void addEdge(e.moduleSpecifier,"static",[],!1);const a=[];let c=!1;t.name&&(i||isUsedAsValue(t.name.text))&&(a.push("default"),c=!0);for(const e of s)(i||isUsedAsValue(e.name.text))&&(a.push((e.propertyName??e.name).text),c=!0);r&&nR.isNamespaceImport(r)&&(i||isUsedAsValue(r.name.text))&&(c=!0),addEdge(e.moduleSpecifier,"static",a,i||c)}function exportDeclarationEdge(e){if(!e.moduleSpecifier)return;if(e.isTypeOnly)return void addEdge(e.moduleSpecifier,"static",[],!1);const t=e.exportClause;if(t&&nR.isNamedExports(t)){const r=t.elements.filter(e=>!e.isTypeOnly);if(!n&&t.elements.length>0&&0===r.length)return void addEdge(e.moduleSpecifier,"static",[],!1);const s=r.map(e=>(e.propertyName??e.name).text);return void addEdge(e.moduleSpecifier,"static",s,!0)}addEdge(e.moduleSpecifier,"static",[],!0)}function visit2(e){if(!nR.isTypeNode(e))if(nR.isImportDeclaration(e))importDeclarationEdge(e);else if(nR.isExportDeclaration(e))exportDeclarationEdge(e);else if(nR.isImportEqualsDeclaration(e))!e.isTypeOnly&&nR.isExternalModuleReference(e.moduleReference)&&addEdge(e.moduleReference.expression,"require",[],!0);else{if(nR.isCallExpression(e)){const t=e.expression.kind===nR.SyntaxKind.ImportKeyword,n=nR.isIdentifier(e.expression)&&"require"===e.expression.text;(t||n)&&addEdge(e.arguments[0],t?"dynamic":"require",[],!0)}nR.forEachChild(e,visit2)}}return visit2(r),a}import{access as sR}from"fs/promises";import iR from"path";async function exists2(e){try{return await sR(e),!0}catch{return!1}}function importerResolutionDirs(e,t){const n=iR.resolve(t),r=[];let s=iR.dirname(iR.resolve(e));for(;r.push(s),s!==n;){const e=iR.dirname(s);if(e===s)break;const t=iR.relative(n,e);if(t.startsWith("..")||iR.isAbsolute(t))break;s=e}return r}async function packageResolvesFromImporter(e,t,n){const r=e.split("/");for(const e of importerResolutionDirs(t,n))if(await exists2(iR.join(e,"node_modules",...r,"package.json")))return!0;return!1}async function findNearestPackageRoot(e,t){for(const n of importerResolutionDirs(e,t))if(await exists2(iR.join(n,"package.json")))return n;return null}function repoRootForCanvasWalk(e){const t=iR.resolve(e);return"tempo"===iR.basename(t)?iR.dirname(t):t}function isServerComponentOnlySpecifier(e){const t=e.split("?")[0].split("#")[0];return"server-only"===t||"next/headers"===t||t.startsWith("next/headers/")||"next/root-params"===t}function extractPackageName(e){const t=e.split("?")[0].split("#")[0];if(!t||t.startsWith(".")||t.startsWith("/")||t.startsWith("~")||t.includes(":"))return null;if(t.startsWith("@")){const e=t.split("/");return e.length<2||e[0].length<2||!e[1]?null:`${e[0]}/${e[1]}`}const n=t.split("/")[0]||null;return n&&(ZD(t)||ZD(n))?null:n}function extractViteAliasKeys(e){const t=new Set;for(const n of e.matchAll(/\bfind\s*:\s*(['"`])([^'"`]+)\1/g))t.add(n[2]);for(const n of e.matchAll(/\balias\s*:\s*\{/g)){const r=n.index+n[0].length-1;let s=0,i=-1;for(let t=r;t<e.length;t+=1){const n=e[t];if("{"===n)s+=1;else if("}"===n&&(s-=1,0===s)){i=t;break}}if(i<0)continue;const o=e.slice(r+1,i);for(const e of o.matchAll(/(?:^|[,{\s])(?:(['"`])([^'"`]+)\1|([A-Za-z_$][\w$-]*))\s*:/g))t.add(e[2]??e[3])}return t}function walkImports(e,t,n,r,s){const i=new Set,o=new Map,a=new Map,c=new Map,l=tR.sys.realpath?.(r)??r,d=repoRootForCanvasWalk(l),u=s?eR.resolve(s):null,p=[e],m=[],f=new Map,g=new Map,y=new Map,b=new Map;function resolve6(e,t,s){let i=b.get(s);return i||(i=tR.createModuleResolutionCache(r,e=>e,s),b.set(s,i)),tR.resolveModuleName(e,t,s,n,i).resolvedModule}function resolveFromImporter(e,n,r){const s=r&&r.configPath!==u?resolve6(e,n,r.options):void 0;return s??resolve6(e,n,t)}function typeOnlyTarget(e,t,n){const r=resolveFromImporter(e,t,n);if(!r){const n=findRelativeTargetOnDisk(e,t);return n&&isWalkableSource(n)?n:void 0}return workspaceSourcePath(r.resolvedFileName)??(r.isExternalLibraryImport?void 0:r.resolvedFileName)}function nearestConfigPath(e){for(const t of importerResolutionDirs(eR.join(e,"__probe__"),d))for(const e of["tsconfig.json","jsconfig.json"]){const r=eR.join(t,e);if(n.fileExists(r))return r}return null}function hasAliasOptions(e){return void 0!==e.paths&&Object.keys(e.paths).length>0||void 0!==e.baseUrl}function resolveConfigOptions(e,t,n){if(t>8)return null;const r=eR.resolve(e);if(n.has(r))return null;n.add(r);const s=tR.readConfigFile(r,tR.sys.readFile);if(s.error)return null;const i=tR.parseJsonConfigFileContent(s.config,{...tR.sys,readDirectory:()=>[]},eR.dirname(r),void 0,r);if(hasAliasOptions(i.options))return i.options;const o=Array.isArray(s.config?.references)?s.config.references:[];for(const e of o){if(!e||"object"!=typeof e)continue;const s=e.path;if("string"!=typeof s)continue;const i=eR.resolve(eR.dirname(r),s),o=s.endsWith(".json")?i:eR.join(i,"tsconfig.json"),a=resolveConfigOptions(o,t+1,n);if(a&&hasAliasOptions(a))return a}return i.options}function importerConfig(e){const t=eR.dirname(e);let n=f.get(t);if(void 0===n&&(n=nearestConfigPath(t),f.set(t,n)),!n)return null;let r=g.get(n);return void 0===r&&(r=resolveConfigOptions(n,0,new Set),g.set(n,r)),r?{configPath:n,options:r}:null}function nearestViteAliasKeys(e){const t=eR.dirname(e);let r=y.get(t);if(void 0!==r)return r;r=new Set;e:for(const t of importerResolutionDirs(e,d))for(const e of["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs","vite.config.cjs"]){const s=eR.join(t,e);if(!n.fileExists(s))continue;const i=tR.sys.readFile(s);void 0!==i&&(r=extractViteAliasKeys(i));break e}return y.set(t,r),r}function matchesViteAlias(e,t){const n=e.split("?")[0].split("#")[0];for(const e of nearestViteAliasKeys(t))if(n===e||n.startsWith(`${e}/`))return!0;return!1}for(;p.length>0;){const e=p.pop(),n=tR.sys.realpath?.(e)??e;if(i.has(n))continue;i.add(n);const r=tR.sys.readFile(n);if(void 0===r)continue;const s=importerConfig(n),d=s?.options??t,u=extractImportEdges(n,r,!0===d.verbatimModuleSyntax),f=[];o.set(n,{content:r,edges:f});for(const e of u){const r=e.specifier;if(r.endsWith(".astro?tempo-component"))continue;const i={...e,external:!1,viteAlias:!1};if(f.push(i),!e.loadsAtRuntime){const e=typeOnlyTarget(r,n,s);e&&m.push(e);continue}isServerComponentOnlySpecifier(r)&&!c.has(r)&&c.set(r,eR.relative(l,n));const o=resolveFromImporter(r,n,s);if(!o){i.viteAlias=matchesViteAlias(r,n),i.aliasTargets=aliasTargets(r,d,t);const e=findRelativeTargetOnDisk(r,n);if(e){i.resolvedFile=e,isWalkableSource(e)&&p.push(e);continue}const s=extractPackageName(r),o=(i.aliasTargets??[]).some(e=>void 0!==existingFileFor(stripQuery(e)));!s||a.has(s)||i.viteAlias||o||a.set(s,eR.relative(l,n));continue}i.resolvedFile=o.resolvedFileName;const u=workspaceSourcePath(o.resolvedFileName),g=void 0!==u;if(u&&p.push(u),i.external=!0===o.isExternalLibraryImport&&!g,o.isExternalLibraryImport){const e=extractPackageName(r);e&&!a.has(e)&&a.set(e,eR.relative(l,n))}else g||p.push(o.resolvedFileName)}}const v=new Set;for(;m.length>0;){const e=tR.sys.realpath?.(m.pop())??"";if(!e||o.has(e)||v.has(e))continue;const n=tR.sys.readFile(e);if(void 0===n)continue;v.add(e);const r=importerConfig(e),s=!0===(r?.options??t).verbatimModuleSyntax;for(const t of extractImportEdges(e,n,s)){const n=typeOnlyTarget(t.specifier,e,r);n&&m.push(n)}}return{graph:o,npmPackages:a,serverOnlyImports:c,visitedFiles:i,typeOnlyFiles:v}}function workspaceSourcePath(e){const t=tR.sys.realpath?.(e)??e,n=t.split(eR.sep).includes("node_modules");return isWalkableSource(t)&&!n?t:void 0}var oR=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".json"],aR=/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;function isWalkableSource(e){return aR.test(e)&&!e.endsWith(".d.ts")}function stripQuery(e){return e.split("?")[0].split("#")[0]}function existingFileFor(e){if(tR.sys.fileExists(e))return e;for(const t of oR)if(tR.sys.fileExists(e+t))return e+t;for(const t of oR){const n=eR.join(e,`index${t}`);if(tR.sys.fileExists(n))return n}}function findRelativeTargetOnDisk(e,t){const n=stripQuery(e);if(n.startsWith("./")||n.startsWith("../"))return existingFileFor(eR.resolve(eR.dirname(t),n))}function aliasTargets(e,...t){const n=stripQuery(e);for(const e of t){if(!e.paths)continue;const t=e.pathsBasePath??e.baseUrl;if(t)for(const[r,s]of Object.entries(e.paths)){const e=r.indexOf("*"),i=e<0?r:r.slice(0,e),o=e<0?"":r.slice(e+1),a=e<0?n===r:n.startsWith(i)&&n.endsWith(o)&&n.length>=i.length+o.length;if(!a)continue;const c=e<0?"":n.slice(i.length,n.length-o.length);return s.map(e=>eR.resolve(t,e.replace("*",c)))}}}var cR=new Set(["tempo-sdk","react","react-dom"]);function isInstallableVersion(e){const t=e.trim();return!(t.startsWith("workspace:")||t.startsWith("catalog:")||t.startsWith("link:")||t.startsWith("file:")||t.startsWith("./")||t.startsWith("../"))}async function readDepsSafe(e){try{return(await readPackageJson(e)).allDependencies}catch{return{}}}var lR=["src","."];function toPosix3(e){return e.split(RD.sep).join("/")}function configBaseUrl(e){const t=QD.readConfigFile(e,QD.sys.readFile);if(!t.error)return QD.parseJsonConfigFileContent(t.config,{...QD.sys,readDirectory:()=>[]},RD.dirname(e),void 0,e).options.baseUrl}function localModuleImport(e,t,n,r,s){let i=null;for(const t of lR){const n=RD.join(r,t,...e.split("/"));if(QD.sys.directoryExists(n)){i={path:n,target:n,isFolder:!0};break}const s=existingFileFor(n);if(s){i={path:n,target:s,isFolder:!1};break}}if(!i)return null;const o=importerResolutionDirs(n,s).flatMap(e=>[RD.join(e,"tsconfig.json"),RD.join(e,"jsconfig.json")]).find(e=>QD.sys.fileExists(e))??null,a=o?configBaseUrl(o)??RD.dirname(o):r,c=toPosix3(RD.relative(a,i.path)),l=c.startsWith("../")?c:`./${c}`,d=i.isFolder?`"${e}": ["${l}"], "${e}/*": ["${l}/*"]`:`"${e}": ["${l}"]`,u=o?toPosix3(RD.relative(s,o)):`${toPosix3(RD.relative(s,RD.join(r,"tsconfig.json")))} or jsconfig.json`,p=toPosix3(RD.relative(s,i.target));return{kind:"local_module_import",name:e,required_by:t,target:p,message:`"${e}" names this project's ${i.isFolder?"folder":"file"} ${p}, not an npm package. The canvas resolves a short import like this only when a tsconfig.json or jsconfig.json maps it.`,fix:`Map it in compilerOptions.paths of ${u} (${d}), or import it with a relative path.`}}async function checkDependencies(e,t,n){const r=RD.resolve(t),s=repoRootForCanvasWalk(r),i=await readDepsSafe(r),o=[];for(const[t,n]of e){if(cR.has(t))continue;const e=RD.resolve(r,n);if(await packageResolvesFromImporter(t,e,s))continue;const a=await findNearestPackageRoot(e,s),c=a?await readDepsSafe(a):{},l=c[t]??i[t];if(!l){const r=localModuleImport(t,n,e,a??s,s);if(r){o.push(r);continue}}const d=c[t]?a:i[t]?r:null,u=l&&isInstallableVersion(l)?l:"latest",p=a&&RD.relative(s,RD.join(a,"package.json"))||"package.json";o.push({kind:"missing_package",package_name:t,version:u,required_by:n,package_root:a?RD.relative(s,a)||".":void 0,declared_in:d?RD.relative(s,RD.join(d,"package.json"))||"package.json":void 0,fix:l?`Install dependencies for ${p} (already declares "${t}")`:`Add "${t}": "${u}" to ${p} dependencies`})}const nameOf=e=>"missing_package"===e.kind?e.package_name:e.name;return o.sort((e,t)=>nameOf(e).localeCompare(nameOf(t)))}import{existsSync as dR,statSync as uR}from"fs";import pR from"path";import hR from"typescript";function checkCanvasEntry(e,t,n){const r=[],s=hR.createSourceFile(e,t,hR.ScriptTarget.Latest,!0),position=e=>{const{line:t,character:n}=s.getLineAndCharacterOfPosition(e);return{line:t+1,column:n}},i=findDefaultExport(s);"missing"!==i.kind&&"not-callable"!==i.kind||r.push({kind:"missing_default_export",file:e,...position("not-callable"===i.kind?i.node.getStart(s):0),message:"missing"===i.kind?"The canvas file has no default export; the host renders the default export.":"The canvas file's default export is not a component.",fix:"Default-export the component that renders <Canvas>, e.g. `export default function MyCanvas() { return <Canvas …>…</Canvas>; }`."});const o=n.canvasElementSpan;if(o&&"component"===i.kind){const t=i.node,n=o.start>=t.getStart(s)&&o.start<t.end;n||r.push({kind:"canvas_not_rendered",file:e,...position(o.start),message:"The <Canvas> element is not inside the default-exported component, so it never renders.",fix:"Return the <Canvas> element from the canvas file's default export."})}for(const t of n.storyboards){if("html"!==t.kind||!t.filepath?.trim())continue;const n=pR.resolve(pR.dirname(e),t.filepath),s=/\.html?$/i.test(n),i=dR(n)&&uR(n).isFile();s&&i||r.push({kind:"missing_file",file:e,...position(t.jsxElementSpan.start),specifier:t.filepath,message:i?`HtmlStoryboard filepath "${t.filepath}" is not an .html file.`:`HtmlStoryboard filepath "${t.filepath}" does not exist, so the storyboard renders blank.`,fix:"Point filepath at an existing .html file, relative to the canvas file."})}return r}var mR=new Set([hR.SyntaxKind.StringLiteral,hR.SyntaxKind.NoSubstitutionTemplateLiteral,hR.SyntaxKind.TemplateExpression,hR.SyntaxKind.NumericLiteral,hR.SyntaxKind.ObjectLiteralExpression,hR.SyntaxKind.ArrayLiteralExpression,hR.SyntaxKind.NullKeyword,hR.SyntaxKind.TrueKeyword,hR.SyntaxKind.FalseKeyword]);function findDefaultExport(e){const hasModifier=(e,t)=>hR.canHaveModifiers(e)&&(hR.getModifiers(e)??[]).some(e=>e.kind===t);for(const t of e.statements){const n=(hR.isFunctionDeclaration(t)||hR.isClassDeclaration(t))&&hasModifier(t,hR.SyntaxKind.ExportKeyword)&&hasModifier(t,hR.SyntaxKind.DefaultKeyword);if(n)return{kind:"component",node:t};if(hR.isExportAssignment(t)&&!t.isExportEquals)return classifyExpression(t.expression,e);if(hR.isExportDeclaration(t)&&!t.isTypeOnly&&t.exportClause&&hR.isNamedExports(t.exportClause)){const n=t.exportClause.elements.find(e=>"default"===e.name.text);if(!n)continue;if(t.moduleSpecifier)return{kind:"unknown"};const r=(n.propertyName??n.name).text;return resolveLocal(r,e)}}return{kind:"missing"}}function classifyExpression(e,t){let n=e;for(;hR.isParenthesizedExpression(n)||hR.isAsExpression(n)||hR.isSatisfiesExpression(n);)n=n.expression;if(mR.has(n.kind))return{kind:"not-callable",node:n};if(hR.isIdentifier(n))return resolveLocal(n.text,t);if(hR.isCallExpression(n)){const e=n.arguments[0],r=e?classifyExpression(e,t):void 0;return"component"===r?.kind?r:{kind:"unknown"}}return{kind:"component",node:n}}function resolveLocal(e,t){for(const n of t.statements){if((hR.isFunctionDeclaration(n)||hR.isClassDeclaration(n))&&n.name?.text===e)return{kind:"component",node:n};if(hR.isVariableStatement(n))for(const r of n.declarationList.declarations)if(hR.isIdentifier(r.name)&&r.name.text===e)return r.initializer?classifyExpression(r.initializer,t):{kind:"unknown"}}return{kind:"unknown"}}import{existsSync as fR,readFileSync as gR}from"fs";import{isBuiltin as yR}from"module";import bR from"path";import{parseSync as vR}from"oxc-parser";import wR from"typescript";function checkLoadability(e,t){const n=[],r=[],s=new Map;for(const[i,o]of e){const a=syntaxErrorsOf(i,o.content);if(n.push(...a),a.length>0)continue;for(const a of o.edges){if(!a.loadsAtRuntime)continue;const o=missingFile(i,a)??missingPackageSubpath(i,a,t)??missingExport(i,a,e,s);o&&n.push(o);const c=unverifiedImport(i,a)??nodeBuiltinImport(i,a);c&&r.push(c)}const c=processEnvRead(i,o.content);c&&r.push(c)}return{issues:n,warnings:r}}var _R={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"jsx",".jsx":"jsx",".mjs":"jsx",".cjs":"jsx"};function positionOf(e,t){let n=1,r=0;const s=Math.min(t,e.length);for(let t=0;t<s;t+=1)10===e.charCodeAt(t)&&(n+=1,r=t+1);return{line:n,column:s-r}}function syntaxErrorsOf(e,t){const n=_R[bR.extname(e)];if(!n||e.endsWith(".d.ts"))return[];const r=vR(e,t,{lang:n,sourceType:"module"}).errors?.[0];return r?[{kind:"syntax_error",file:e,...positionOf(t,r.labels?.[0]?.start??0),message:r.message,fix:"Fix the syntax error; the canvas host cannot compile this file."}]:[]}function isRelative(e){return e.startsWith("./")||e.startsWith("../")}function missingFile(e,t){if(t.resolvedFile||t.viteAlias)return;const n=t.aliasTargets??[],r=isRelative(t.specifier),s=n.length>0&&n.every(e=>void 0===existingFileFor(e.split("?")[0]));return r||s?{kind:"missing_file",file:e,line:t.line,column:t.column,specifier:t.specifier,message:`"${t.specifier}" does not exist, so this module cannot load.`,fix:`Create the file "${t.specifier}" points to, or fix the import path.`}:void 0}function findPackageDir(e,t,n){for(const r of importerResolutionDirs(t,n)){const t=bR.join(r,"node_modules",...e.split("/"));if(fR(bR.join(t,"package.json")))return t}}function exportsMapAllows(e,t){if("string"==typeof e||Array.isArray(e))return"."===t;if(!e||"object"!=typeof e)return!1;const n=Object.keys(e),r=n.every(e=>!e.startsWith("."));return r?"."===t:n.some(e=>{if(e===t)return!0;const n=e.indexOf("*");return n<0?e.endsWith("/")&&t.startsWith(e):t.startsWith(e.slice(0,n))&&t.endsWith(e.slice(n+1))})}function missingPackageSubpath(e,t,n){if(t.resolvedFile||t.viteAlias||t.aliasTargets?.length)return;const r=t.specifier.split("?")[0],s=extractPackageName(r);if(!s||r===s)return;const i=findPackageDir(s,e,n);if(!i)return;const o=r.slice(s.length+1);let a;try{a=JSON.parse(gR(bR.join(i,"package.json"),"utf8"))}catch{return}const c=void 0!==a.exports?exportsMapAllows(a.exports,`./${o}`):void 0!==existingFileFor(bR.join(i,o));return c?void 0:{kind:"unresolved_import",specifier:t.specifier,file:e,line:t.line,column:t.column,fix:`"${s}" is installed but does not provide "${o}". Import an entry point the package exports.`}}var xR=16,TR=/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;function canonicalPath(e){return wR.sys.realpath?.(e)??e}function runtimeExportsOf(e,t,n,r=0){const s=n.get(e);if(void 0!==s)return s;n.set(e,new Set);const i=computeRuntimeExports(e,t,n,r);return n.set(e,i),i}function computeRuntimeExports(e,t,n,r){if(r>xR||e.endsWith(".d.ts")||e.endsWith(".json"))return null;const s=t.get(e)?.content??wR.sys.readFile(e);if(void 0===s)return null;const i=wR.createSourceFile(e,s,wR.ScriptTarget.Latest,!1),o=new Set;let a=!1;const hasModifier=(e,t)=>wR.canHaveModifiers(e)&&(wR.getModifiers(e)??[]).some(e=>e.kind===t);function addBindingNames(e){if(wR.isIdentifier(e))o.add(e.text);else for(const t of e.elements)wR.isBindingElement(t)&&addBindingNames(t.name)}for(const s of i.statements){if(wR.isImportDeclaration(s)&&(a=!0),wR.isExportAssignment(s)){if(s.isExportEquals)return null;a=!0,o.add("default");continue}if(wR.isExportDeclaration(s)){if(a=!0,s.isTypeOnly)continue;const i=s.exportClause;if(i&&wR.isNamedExports(i)){for(const e of i.elements)e.isTypeOnly||o.add(e.name.text);continue}if(i&&wR.isNamespaceExport(i)){o.add(i.name.text);continue}const c=s.moduleSpecifier;if(!c||!wR.isStringLiteralLike(c))return null;const l=t.get(e)?.edges.find(e=>e.loadsAtRuntime&&e.specifier===c.text);if(!l?.resolvedFile||l.external||!TR.test(l.resolvedFile))return null;const d=runtimeExportsOf(canonicalPath(l.resolvedFile),t,n,r+1);if(!d)return null;for(const e of d)"default"!==e&&o.add(e);continue}if(!hasModifier(s,wR.SyntaxKind.ExportKeyword))continue;if(a=!0,hasModifier(s,wR.SyntaxKind.DeclareKeyword))continue;if(wR.isInterfaceDeclaration(s)||wR.isTypeAliasDeclaration(s))continue;if(hasModifier(s,wR.SyntaxKind.DefaultKeyword)){o.add("default");continue}if(wR.isVariableStatement(s)){for(const e of s.declarationList.declarations)addBindingNames(e.name);continue}const i=s.name;i&&wR.isIdentifier(i)&&o.add(i.text)}return a?o:null}function missingExport(e,t,n,r){if(!t.resolvedFile||t.external||0===t.valueNames.length)return;if(!TR.test(t.resolvedFile)||t.resolvedFile.endsWith(".d.ts"))return;const s=runtimeExportsOf(canonicalPath(t.resolvedFile),n,r);if(!s)return;const i=t.valueNames.find(e=>!s.has(e));if(!i)return;const o="default"===i?"a default export":`an export named "${i}"`;return{kind:"missing_export",file:e,line:t.line,column:t.column,specifier:t.specifier,name:i,message:`"${t.specifier}" does not provide ${o}, so this module fails to load.`,fix:`Import a name "${t.specifier}" actually exports, or add the export.`}}function unverifiedImport(e,t){if(!(t.resolvedFile||t.viteAlias||t.aliasTargets?.length||isRelative(t.specifier)||extractPackageName(t.specifier)||yR(t.specifier)))return{kind:"unverified_import",file:e,line:t.line,column:t.column,specifier:t.specifier,message:`"${t.specifier}" could not be resolved statically; the host may still resolve it.`,fix:"If the canvas fails to load, check that this import resolves in the canvas host."}}function nodeBuiltinImport(e,t){if(yR(t.specifier))return{kind:"client_runtime_api",file:e,line:t.line,column:t.column,message:`"${t.specifier}" is a Node built-in. In the browser it loads as an empty stub and fails when used.`,fix:"Keep Node built-ins out of components the canvas renders, or pass the data in as props."}}var kR=/\bprocess\.env\.([A-Za-z_$][\w$]*)/g,SR=/^(?:NODE_ENV|NEXT_PUBLIC_\w+)$/;function processEnvRead(e,t){if(!e.endsWith(".d.ts"))for(const n of t.matchAll(kR))if(!SR.test(n[1]))return{kind:"client_runtime_api",file:e,...positionOf(t,n.index??0),message:`process.env.${n[1]} is read in client code; unless the host defines it, \`process\` is undefined in the browser.`,fix:"Read configuration from props or a host-defined variable instead of process.env."}}import ER from"path";import AR from"v8";import{realpathSync as CR,statSync as IR}from"fs";import PR from"path";import DR from"typescript";function canonicalPath2(e){const t=PR.resolve(e);try{return CR.native(t)}catch{return t}}function compareProjectPriority(e,t){const n=t.rootDir.length-e.rootDir.length;if(0!==n)return n;const r=t.priority-e.priority;return 0!==r?r:e.id.localeCompare(t.id)}function isWithinRoot(e,t){return e===t||e.startsWith(`${t}${PR.sep}`)}function loadProject(e){const t=e.id.trim();if(!t)throw new Error("Project id must be a non-empty string");const n=canonicalPath2(e.tsconfigPath),r=canonicalPath2(e.rootDir),s=DR.readConfigFile(n,DR.sys.readFile);if(s.error)throw new Error(`Failed to read tsconfig at ${n}: ${DR.flattenDiagnosticMessageText(s.error.messageText,"\n")}`);const i=DR.parseJsonConfigFileContent(s.config,DR.sys,PR.dirname(n));if(i.errors.length>0){const e=i.errors.map(e=>DR.flattenDiagnosticMessageText(e.messageText,"\n")).join("; ");throw new Error(`Failed to parse tsconfig at ${n}: ${e}`)}const o=i.fileNames.map(e=>canonicalPath2(e));return{id:t,rootDir:r,tsconfigPath:n,priority:e.priority??0,options:i.options,fileNames:o,moduleResolutionCache:DR.createModuleResolutionCache(r,e=>e,i.options)}}var RR=/\.(?:d\.ts|ts|tsx|mts|cts|d\.mts|d\.cts)$/,NR=/\bdeclare\s+(?:global\b|module\s+["'`])/,OR=/^\s*(?:import|export)\b/m;function isGlobalDeclarationFile(e){if(!RR.test(e))return!1;const t=DR.sys.readFile(e);if(void 0===t)return!1;if(!NR.test(t)&&OR.test(t))return!1;const n=DR.createSourceFile(e,t,DR.ScriptTarget.Latest,!1);return!DR.isExternalModule(n)||n.statements.some(e=>DR.isModuleDeclaration(e)&&(0!==(e.flags&DR.NodeFlags.GlobalAugmentation)||DR.isStringLiteral(e.name)))}function mtimeOrNull(e){return IR(e,{throwIfNoEntry:!1})?.mtimeMs??null}var FR=`${PR.sep}node_modules${PR.sep}`;function isInstalledPackagePath(e){let t=e;try{t=CR(e)}catch{}return(t+PR.sep).includes(FR)}function getFileMtimeVersion(e){try{const t=IR(e);return String(t.mtimeMs)}catch{return"0"}}function createTsWorkspaceService(e){if(0===e.projects.length)throw new Error("TsWorkspaceDescriptor.projects must include at least one project");const t=canonicalPath2(e.workspaceRoot),n=e.projects.map(e=>loadProject(e)),r=new Map;for(const e of n){if(r.has(e.id))throw new Error(`Duplicate project id: ${e.id}`);r.set(e.id,e)}const s=(e.primaryProjectId?r.get(e.primaryProjectId):null)??n[0];if(e.primaryProjectId&&!r.has(e.primaryProjectId))throw new Error(`Primary project id not found: ${e.primaryProjectId}`);const i=[...n].sort(compareProjectPriority),o=new Set;for(const e of n)for(const t of e.fileNames)o.add(t);let a,c=!1;const l=new Map;let d,u=new WeakSet;const p=new Map,m=new Map;let f=0;function getOwningProject(e){const t=canonicalPath2(e);for(const e of i)if(isWithinRoot(t,e.rootDir))return e;return s}function recordResolutionInputs(e){if(u.has(e))return;u.add(e);const t=e,record=e=>{l.has(e)||isInstalledPackagePath(e)||l.set(e,mtimeOrNull(e))};let n="";for(const e of t.failedLookupLocations??[]){const t=PR.dirname(e);t!==n&&(n=t,record(t))}const r=e.resolvedModule?.resolvedFileName;r&&record(PR.dirname(r));for(const e of t.affectingLocations??[])record(e)}function resolve6(e,t,n){const r=DR.resolveModuleName(e,t,n.options,g,n.moduleResolutionCache);return recordResolutionInputs(r),r.resolvedModule}const g={fileExists:DR.sys.fileExists,readFile:DR.sys.readFile,realpath:DR.sys.realpath,directoryExists:DR.sys.directoryExists,getCurrentDirectory:()=>t,getDirectories:DR.sys.getDirectories},y={getScriptFileNames:()=>Array.from(a??o),hasInvalidatedResolutions:()=>c,getScriptVersion:e=>{const t=canonicalPath2(e),n=p.get(t);return n?String(n.version):getFileMtimeVersion(t)},getScriptSnapshot:e=>{const t=canonicalPath2(e),n=p.get(t);if(n)return DR.ScriptSnapshot.fromString(n.content);const r=DR.sys.readFile(t);return void 0!==r?DR.ScriptSnapshot.fromString(r):void 0},getCurrentDirectory:()=>t,getCompilationSettings:()=>s.options,getDefaultLibFileName:e=>DR.getDefaultLibFilePath(e),fileExists:DR.sys.fileExists,readFile:DR.sys.readFile,readDirectory:DR.sys.readDirectory,directoryExists:DR.sys.directoryExists,getDirectories:DR.sys.getDirectories,useCaseSensitiveFileNames:()=>DR.sys.useCaseSensitiveFileNames,getProjectVersion:()=>String(f),resolveModuleNames:(e,t)=>{const n=getOwningProject(t);return e.map(e=>{const r=resolve6(e,t,n);return r||(n.id!==s.id?resolve6(e,t,s):void 0)})}},b=DR.createLanguageService(y,DR.createDocumentRegistry());function afterSync(e){const t=e();return c=!1,t}return{updateFile(e,t){const n=canonicalPath2(e),r=(m.get(n)??0)+1;m.set(n,r),p.set(n,{version:r,content:t}),o.add(n),a?.add(n),f+=1},closeFile(e){const t=canonicalPath2(e);p.delete(t),f+=1},clearModuleResolutionCaches(){for(const e of n)e.moduleResolutionCache.clear();f+=1},setRootFiles(e){a=e?new Set(e.map(e=>canonicalPath2(e)).sort()):void 0,f+=1},refresh(){f+=1},refreshModuleResolutions(){f+=1;let e=!1;for(const[t,n]of l)mtimeOrNull(t)!==n&&(e=!0);if(!e)return!1;l.clear(),u=new WeakSet;for(const e of n)e.moduleResolutionCache.clear();return c=!0,!0},getGlobalDeclarationFiles:()=>(d??=[...o].filter(isGlobalDeclarationFile),d),getProgram:()=>afterSync(()=>b.getProgram()??null),getSemanticDiagnostics(e){const t=canonicalPath2(e);return afterSync(()=>b.getSemanticDiagnostics(t))},getSyntacticDiagnostics(e){const t=canonicalPath2(e);return afterSync(()=>b.getSyntacticDiagnostics(t))},getDefinition(e,t){const n=canonicalPath2(e);return afterSync(()=>b.getDefinitionAtPosition(n,t))},dispose(){b.dispose()}}}import LR from"typescript";function createIncrementalDiagnostics(){let e;const t={useCaseSensitiveFileNames:()=>LR.sys.useCaseSensitiveFileNames,createHash:LR.sys.createHash};return{get hasState(){return void 0!==e},reset(){e=void 0},dependenciesOf(t){const n=e?.getProgram(),r=n?.getSourceFile(t);return e&&r?[...e.getAllDependencies(r)]:[]},check(n,r,s={}){e=LR.createSemanticDiagnosticsBuilderProgram(n,t,e);const i=s.shouldStop??(()=>!1),o=new Map;for(const e of r){const t=n.getSourceFile(e);t&&o.set(t,e)}const a=new Map;let c=0,l=!1;for(;!l;){const t=e.getSemanticDiagnosticsOfNextAffectedFile(void 0,e=>!o.has(e));if(!t)break;const n=t.affected,r=o.get(n);void 0!==r&&(c+=1,a.set(r,[...t.result])),l=i()}const d=e.state?.semanticDiagnosticsPerFile,u=[];for(const[t,n]of o){const r=a.get(n);if(!r&&(l||i())){l=!0,u.push(n);continue}const s=r??countingRecompute(t,()=>[...e.getSemanticDiagnostics(t)]);a.set(n,[...e.getSyntacticDiagnostics(t),...s])}return{diagnostics:a,unchecked:u,recomputed:c};function countingRecompute(e,t){const n=e.resolvedPath;return d&&void 0!==n&&!d.has(n)&&(c+=1),t()}}}}import{createHash as MR}from"crypto";function unwrapOptional(e,t){if(!t.isUnion())return t;const n=t.types.find(t=>!(t.flags&e.TypeFlags.Undefined));return n??t}function resolveJsxNamespace(e,t,n,r){const s=n.resolveName?.("JSX",r,e.SymbolFlags.Namespace,!1);if(s)return s;const i=t.getCompilerOptions(),o=i.jsxImportSource??"react",a=e.resolveModuleName(`${o}/jsx-runtime`,r.fileName,i,e.sys);if(!a.resolvedModule)return;const c=t.getSourceFile(a.resolvedModule.resolvedFileName);if(!c)return;const l=n.getSymbolAtLocation(c);return l?n.getExportsOfModule(l).find(e=>"JSX"===e.name):void 0}function resolveRnStyleType(e,t,n,r,s="ViewStyle"){try{const i=e.resolveModuleName("react-native",r.fileName,t.getCompilerOptions(),e.sys);if(!i.resolvedModule)return null;const o=t.getSourceFile(i.resolvedModule.resolvedFileName);if(!o)return null;const a=n.getSymbolAtLocation(o);if(!a)return null;const c=n.getExportsOfModule(a).find(e=>e.name===s);return c?n.getDeclaredTypeOfSymbol(c):null}catch{return null}}function resolveJsxReferenceTypes(e,t,n){const r={cssProperties:null,reactNode:null,rnViewStyle:null};try{const s=t.getTypeChecker(),i=resolveRnStyleType(e,t,s,n),o={rnViewStyle:i,rnTextStyle:resolveRnStyleType(e,t,s,n,"TextStyle"),rnImageStyle:resolveRnStyleType(e,t,s,n,"ImageStyle")};let a=resolveJsxNamespace(e,t,s,n);if(!a)return{...r,...o};a.flags&e.SymbolFlags.Alias&&(a=s.getAliasedSymbol(a));const c=s.getExportsOfModule(a).find(e=>"IntrinsicElements"===e.name)??s.getDeclaredTypeOfSymbol(a).getProperty("IntrinsicElements");if(!c)return{...r,...o};const l=s.getDeclaredTypeOfSymbol(c).getProperty("div");if(!l)return{...r,...o};const d=s.getTypeOfSymbol(l),propType=t=>{const n=d.getProperty(t);if(!n)return null;const r=unwrapOptional(e,s.getTypeOfSymbol(n));return r.flags&e.TypeFlags.Undefined?null:r};return{cssProperties:propType("style"),reactNode:propType("children"),...o}}catch{return r}}var UR=new WeakMap;function componentDependencies(e,t,n){let r=UR.get(t);r||(r={imports:new Map,globals:t.getSourceFiles().filter(n=>!t.isSourceFileDefaultLibrary(n)&&!/[/\\]node_modules[/\\]/.test(n.fileName)&&(!e.isExternalModule(n)&&!n.fileName.endsWith(".json")||n.statements.some(t=>e.isModuleDeclaration(t)&&(Boolean(t.flags&e.NodeFlags.GlobalAugmentation)||e.isStringLiteral(t.name)))))},UR.set(t,r));const s=t.getTypeChecker(),i=new Set,o=[...r.globals,n];for(;o.length;){const n=o.pop();if(i.has(n)||t.isSourceFileDefaultLibrary(n))continue;if(i.add(n),/[/\\]node_modules[/\\]/.test(n.fileName))continue;let a=r.imports.get(n);if(!a){a=[];const add=t=>{if(t&&e.isStringLiteralLike(t))for(const e of s.getSymbolAtLocation(t)?.declarations??[]){const t=e.getSourceFile();t!==n&&a.push(t)}},visit2=t=>{e.isImportDeclaration(t)||e.isExportDeclaration(t)?add(t.moduleSpecifier):e.isImportTypeNode(t)&&e.isLiteralTypeNode(t.argument)?add(t.argument.literal):e.isExternalModuleReference(t)?add(t.expression):e.isCallExpression(t)&&t.expression.kind===e.SyntaxKind.ImportKeyword&&add(t.arguments[0]),e.forEachChild(t,visit2)};visit2(n),r.imports.set(n,a)}o.push(...a)}const a=t.getCompilerOptions(),c=a.configFile;return[...new Set([...[...i].map(e=>e.fileName),..."string"==typeof a.configFilePath?[a.configFilePath]:[],...c?.extendedSourceFiles??[]])]}var jR={Storyboard:{importSource:"tempo-sdk/canvas"},SvelteStoryboard:{importSource:"tempo-sdk/canvas/svelte",framework:"svelte"},VueStoryboard:{importSource:"tempo-sdk/canvas/vue",framework:"vue"}};function componentStoryboardOf(e,t){if(!t||!e.isImportSpecifier(t))return null;const n=jR[(t.propertyName??t.name).text],r=t.parent.parent.parent;return n&&e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===n.importSource?n:null}function analyzeComponentPropTypes(e,t,n,r,s){const i=t.getSourceFile(n);if(!i)return{ok:!1,reason:"file-not-in-program"};const o=t.getTypeChecker();let a,c=null;if(void 0!==s){const visit2=t=>{if(!(t.getStart(i)>s||t.end<=s)){if((e.isJsxOpeningElement(t)||e.isJsxSelfClosingElement(t))&&t.getStart(i)===s){let n=t.tagName;const r=o.getSymbolAtLocation(t.tagName),s=componentStoryboardOf(e,r?.declarations?.[0]);if(s){const r=t.attributes.properties.find(t=>e.isJsxAttribute(t)&&"component"===t.name.getText(i)),o=r&&e.isJsxAttribute(r)&&r.initializer&&e.isJsxExpression(r.initializer)?r.initializer.expression:void 0;o&&(n=o),s.framework&&(c=o?"mounted":"missing")}return void(a=o.getSymbolAtLocation(n))}e.forEachChild(t,visit2)}};visit2(i)}else{const t=o.getSymbolAtLocation(i);if(!t)return{ok:!1,reason:"not-a-module"};const n=o.getExportsOfModule(t);a=n.find(e=>e.name===r)??n.find(t=>{const n=t.flags&e.SymbolFlags.Alias?safeAliasedSymbol(o,t):t,s=n?.valueDeclaration;return s?.name?.getText()===r})??o.getSymbolsInScope(i,e.SymbolFlags.Value).find(e=>e.name===r)}const l=a&&a.flags&e.SymbolFlags.Alias?safeAliasedSymbol(o,a):a;if("missing"===c||"mounted"===c&&!l||"mounted"===c&&(l?.declarations??[]).some(t=>declaredOutsideTypeScript(e,t)))return{ok:!1,reason:"storyboard-component-unanalyzable"};if(!l)return{ok:!1,reason:"export-not-found"};const d=l.valueDeclaration??l.declarations?.[0],u=o.getTypeOfSymbolAtLocation(l,d??i),p=d?{filePath:d.getSourceFile().fileName,exportName:(()=>{const t=o.getSymbolAtLocation(d.getSourceFile());return t&&o.getExportsOfModule(t).find(t=>(t.flags&e.SymbolFlags.Alias?safeAliasedSymbol(o,t):t)===l)?.name})(),name:d.name?.getText()??l.name}:void 0,m=new Map,f=componentDependencies(e,t,d?.getSourceFile()??i),g=d?.getSourceFile()!==i?componentDependencies(e,t,i):void 0,readDefault=t=>{if(e.isBindingElement(t)&&t.initializer&&e.isIdentifier(t.name)){const n=t.initializer;let r;e.isStringLiteralLike(n)?r=n.text:e.isNumericLiteral(n)?r=Number(n.text):n.kind===e.SyntaxKind.TrueKeyword?r=!0:n.kind===e.SyntaxKind.FalseKeyword?r=!1:n.kind===e.SyntaxKind.NullKeyword?r=null:e.isPrefixUnaryExpression(n)&&n.operator===e.SyntaxKind.MinusToken&&e.isNumericLiteral(n.operand)&&(r=-Number(n.operand.text)),void 0!==r&&m.set(t.propertyName?.getText()??t.name.text,r)}e.forEachChild(t,readDefault)},y=u.getCallSignatures()[0]?.declaration;y?.parameters.forEach(readDefault);const b=resolvePropsType(e,o,u,i),v=b?null:vueInstancePropsType(o,u,i),w=b??v,x=v?HR:WR;if(!w)return u.getCallSignatures().some(e=>0===e.getParameters().length)?{ok:!0,analysis:{component:p,dependencies:f,requestDependencies:g,props:[],schema:{kind:"object",properties:{}}}}:{ok:!1,reason:"not-a-component"};const S=[];let E;const A=w.isUnion()?w.types:[w],C=new Map,describe=t=>{let n=C.get(t);return n||(n=describeValueType(e,o,t,i),C.set(t,n)),n},I=A.map(t=>{const n=Object.fromEntries(o.getPropertiesOfType(t).filter(e=>!x.has(e.name)).map(t=>[t.name,{optional:Boolean(t.flags&e.SymbolFlags.Optional),schema:describe(o.getTypeOfSymbolAtLocation(t,t.valueDeclaration??t.declarations?.[0]??i))}])),r=o.getIndexTypeOfType(t,e.IndexKind.String);return{kind:"object",properties:n,...r?{additional:describe(r)}:{}}}),P=new Map(A.flatMap(e=>o.getPropertiesOfType(e)).map(e=>[e.name,e]));for(const n of P.values()){if(x.has(n.name))continue;const r=n.valueDeclaration??n.declarations?.[0];let s;try{s=o.getTypeOfSymbolAtLocation(n,r??i)}catch{continue}S.push({name:n.name,declared:(n.declarations??[]).some(e=>{const n=e.getSourceFile();return!t.isSourceFileDefaultLibrary(n)&&!/[/\\](?:@types[/\\]react|react[/\\]).*\.d\.ts$/.test(n.fileName)}),elementSpecific:(n.declarations??[]).some(t=>{const n=t.parent;return/[/\\](?:@types[/\\]react|react[/\\]).*\.d\.ts$/.test(t.getSourceFile().fileName)&&e.isInterfaceDeclaration(n)&&/^(?!AllHTMLAttributes$).+HTMLAttributes$/.test(n.name.text)}),optional:Boolean(n.flags&e.SymbolFlags.Optional),...classifyPropType(e,o,s),...(()=>{if("style"!==n.name)return{};try{return void 0===E&&(E=resolveJsxReferenceTypes(e,t,i).cssProperties),E&&o.isTypeAssignableTo?.(E,s)?{acceptsStyleObject:!0}:{}}catch{return{}}})(),...m.has(n.name)?{defaultValue:m.get(n.name)}:{},schema:(()=>{const e=I.flatMap(e=>{const t=Object.prototype.hasOwnProperty.call(e.properties,n.name)?e.properties[n.name]:void 0;return t?[t.schema]:[]});return 1===e.length?e[0]:{kind:"union",members:e}})()})}return{ok:!0,analysis:{component:p,dependencies:f,requestDependencies:g,props:S,schema:1===I.length?I[0]:{kind:"union",members:I}}}}var BR=512,$R=Symbol("value-schema-too-large");function describeValueType(e,t,n,r){try{return buildValueSchema(e,t,n,r,new Set,0,{remaining:BR,literalBytes:256e3})}catch(e){if(e!==$R)throw e;return{kind:"unsupported"}}}function buildValueSchema(e,t,n,r,s,i,o){if(o.remaining--<=0)throw $R;const a={kind:"unsupported"};if(i>8||s.has(n))return a;const c=e.TypeFlags;if(n.flags&(c.Any|c.Unknown|c.TypeParameter|c.Never))return a;if(n.isStringLiteral()||n.isNumberLiteral()){if(o.literalBytes-=JSON.stringify(n.value).length,o.literalBytes<0)throw $R;return{kind:"literal",value:n.value}}if(n.flags&c.BooleanLiteral)return{kind:"literal",value:"true"===t.typeToString(n)};if(n.flags&c.String)return{kind:"string"};if(n.flags&c.Number)return{kind:"number"};if(n.flags&c.Boolean)return{kind:"boolean"};if(n.flags&c.Null)return{kind:"null"};const l=n.getSymbol();if("ReactElement"===l?.name&&l.declarations?.some(e=>/[/\\]@types[/\\]react[/\\]/.test(e.getSourceFile().fileName))){const e=t.getTypeArguments(n);if(e.every(e=>e.flags&(c.Any|c.Unknown)||t.typeToString(e).includes("JSXElementConstructor")))return{kind:"jsx"}}const d=new Set(s).add(n),describe=n=>buildValueSchema(e,t,n,r,d,i+1,o);if(n.isUnion()){const s=n.types.filter(e=>!(e.flags&c.Undefined)),a=s.every(e=>Boolean(e.flags&(c.StringLiteral|c.NumberLiteral|c.BooleanLiteral|c.Null)));if(a&&s.length>1e4)throw $R;if(a&&(o.literalBytes-=s.reduce((e,n)=>e+(n.isStringLiteral()||n.isNumberLiteral()?JSON.stringify(n.value).length:t.typeToString(n).length),0),o.literalBytes<0))throw $R;const l=a?s.map(n=>buildValueSchema(e,t,n,r,d,i+1,{remaining:1,literalBytes:1/0})):s.map(describe);return 1===l.length?l[0]:{kind:"union",members:l}}if(n.isIntersection()&&n.types.some(e=>e.flags&c.String)){const e=n.types.filter(e=>!(e.flags&c.String));if(e.every(e=>0===t.getPropertiesOfType(e).length&&e.flags&c.Object))return{kind:"string"}}if(t.getSignaturesOfType(n,e.SignatureKind.Call).length||t.getSignaturesOfType(n,e.SignatureKind.Construct).length)return a;if(t.isTupleType(n)){const e=n;return e.target.hasRestElement?a:{kind:"tuple",elements:t.getTypeArguments(e).map(describe),required:e.target.minLength}}if(t.isArrayType(n)){const r=t.getIndexTypeOfType(n,e.IndexKind.Number);return r?{kind:"array",element:describe(r)}:a}if(!(n.flags&(c.Object|c.Intersection)))return a;const u={};for(const s of t.getPropertiesOfType(n)){const n=s.valueDeclaration??s.declarations?.[0]??r;Object.defineProperty(u,s.name,{enumerable:!0,configurable:!0,value:{optional:Boolean(s.flags&e.SymbolFlags.Optional),schema:describe(t.getTypeOfSymbolAtLocation(s,n))}})}const p=t.getIndexTypeOfType(n,e.IndexKind.String);return{kind:"object",properties:u,...p?{additional:describe(p)}:{}}}function safeAliasedSymbol(e,t){try{return e.getAliasedSymbol(t)}catch{return null}}function resolvePropsType(e,t,n,r){const s=[...n.getCallSignatures(),...n.getConstructSignatures()];for(const n of s){const s=n.getParameters()[0];if(!s)continue;const i=s.valueDeclaration;if(!(i&&e.isParameter(i)&&i.dotDotDotToken))try{const n=t.getNonNullableType(t.getTypeOfSymbolAtLocation(s,s.valueDeclaration??r));if(!isPropsObjectType(e,n))continue;return n}catch{}}const i=n.getConstructSignatures()[0]?.getReturnType().getProperty("props");if(i)try{return t.getTypeOfSymbolAtLocation(i,i.valueDeclaration??r)}catch{return null}return null}var WR=new Set(["key","ref"]),HR=new Set(["key","ref","ref_for","ref_key","class","style","onVnodeBeforeMount","onVnodeMounted","onVnodeBeforeUpdate","onVnodeUpdated","onVnodeBeforeUnmount","onVnodeUnmounted"]);function vueInstancePropsType(e,t,n){for(const r of t.getConstructSignatures()){const t=r.getReturnType().getProperty("$props");if(t)try{return e.getTypeOfSymbolAtLocation(t,t.valueDeclaration??n)}catch{return null}}return null}function isPropsObjectType(e,t){const n=e.TypeFlags;if(t.flags&(n.Any|n.Unknown))return!1;if(t.isUnion()||t.isIntersection())return t.types.every(t=>isPropsObjectType(e,t));if(!(t.flags&n.Object))return!1;const r=t,s=e.ObjectFlags.Reference|e.ObjectFlags.Tuple;return!(r.objectFlags&e.ObjectFlags.Tuple)&&!(r.objectFlags&s&&checkerIsArrayLike(e,r))}function checkerIsArrayLike(e,t){const n=t.target,r=n?.symbol?.name??t.symbol?.name;return"Array"===r||"ReadonlyArray"===r}var qR={kind:"unsupported"};function acceptsStringValue(e,t){try{return e.isTypeAssignableTo?.(e.getStringType(),t)??!1}catch{return!1}}function classifyPropType(e,t,n){const r=e.TypeFlags,unsupported=()=>acceptsStringValue(t,n)?{kind:"unsupported",acceptsString:!0}:qR,s=(n.isUnion()?n.types:[n]).filter(e=>!(e.flags&(r.Undefined|r.Null|r.Void)));if(0===s.length)return unsupported();if(s.some(e=>e.flags&r.EnumLike))return unsupported();if(s.every(e=>e.flags&(r.Boolean|r.BooleanLiteral))){const e=new Set(s.map(e=>t.typeToString(e))),n=s.some(e=>e.flags&r.Boolean)||e.has("true")&&e.has("false");return n?{kind:"boolean"}:unsupported()}if(s.every(e=>e.flags&(r.Number|r.NumberLiteral)))return{kind:"number"};const i=[];let o=!1;for(const e of s)if(e.isStringLiteral())i.includes(e.value)||i.push(e.value);else{if(!(e.flags&r.String||e.isIntersection()&&e.types.some(e=>e.flags&r.String)))return unsupported();o=!0}return i.length>0?o?{kind:"enum",options:i,open:!0}:{kind:"enum",options:i}:o?{kind:"string"}:unsupported()}function declaredOutsideTypeScript(e,t){if(/\.(?:vue|svelte)$/.test(t.getSourceFile().fileName))return!0;for(let n=t;n;n=n.parent)if(e.isModuleDeclaration(n)&&e.isStringLiteral(n.name)&&n.name.text.includes("*"))return!0;return!1}import zR from"typescript";import GR from"typescript";function formatFixSuggestion(e,t){switch(e){case 2322:return"Change the value to match the expected type, or update the type annotation.";case 2339:return"Check the component's props interface for the correct property name.";case 2345:return"The argument type doesn't match the expected parameter type.";default:return t}}function getLineAndColumn(e){if(e.file&&void 0!==e.start){const t=e.file.getLineAndCharacterOfPosition(e.start);return{line:t.line+1,column:t.character}}return{line:0,column:0}}function typeErrorFromDiagnostic(e,t){if(!e.file)return;const n=GR.flattenDiagnosticMessageText(e.messageText," ");return{kind:"type_error",file:e.file.fileName,...getLineAndColumn(e),message:n,code:e.code,fix:formatFixSuggestion(e.code,n),provenance:t.provenance,tsconfig:t.tsconfig}}import{statSync as VR}from"fs";import KR from"path";import XR from"typescript";var YR=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock",KR.join("node_modules",".modules.yaml"),KR.join("node_modules",".package-lock.json"),KR.join("node_modules",".yarn-state.yml")];function tsconfigDependencies(e){const t=XR.readJsonConfigFile(e,XR.sys.readFile),n=XR.parseJsonSourceFileConfigFileContent(t,{...XR.sys,readDirectory:()=>[]},KR.dirname(e),void 0,e),r=(n.projectReferences??[]).map(e=>e.path.endsWith(".json")?e.path:KR.join(e.path,"tsconfig.json"));return[...t.extendedSourceFiles??[],...r]}function fingerprintsEqual(e,t){return e.tsconfig===t.tsconfig&&e.packageJson===t.packageJson&&e.tempoPackageJson===t.tempoPackageJson&&e.inputs===t.inputs}function createValidateServiceCache(e){const t=new Map;function fingerprint(t,n){const r=[t,KR.dirname(t)],s=[...e.configDependencies?.(n)??[],...r.flatMap(e=>YR.map(t=>KR.join(e,t)))];return{tsconfig:e.statMtimeMs(n),packageJson:e.statMtimeMs(KR.join(t,"package.json")),tempoPackageJson:e.statMtimeMs(KR.join(t,"tempo","package.json")),inputs:s.map(t=>`${t}=${e.statMtimeMs(t)}`).join("|")}}function buildEntry(t,n){const r={workspaceRoot:t,projects:[{id:"main",rootDir:t,tsconfigPath:n}]};return{service:e.createService(r),fingerprint:fingerprint(t,n)}}return{get(e,n){const r=KR.resolve(e),s=KR.resolve(n),i=`${r}::${s}`,o=t.get(i);if(o){const e=fingerprint(r,s);if(fingerprintsEqual(o.fingerprint,e))return o.service;try{o.service.dispose()}catch{}}const a=buildEntry(r,s);return t.set(i,a),a.service},evict(e,n){const r=`${KR.resolve(e)}::${KR.resolve(n)}`,s=t.get(r);if(s){t.delete(r);try{s.service.dispose()}catch{}}},disposeAll(){for(const e of t.values())try{e.service.dispose()}catch{}t.clear()}}}var JR=createValidateServiceCache({createService:createTsWorkspaceService,configDependencies:e=>{try{return tsconfigDependencies(e)}catch{return[]}},statMtimeMs(e){try{return VR(e).mtimeMs}catch{return null}}}),QR=5,ZR=.7,eN=.5,tN=12e4,nN=new WeakMap,rN=/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,isLocalSource=e=>rN.test(e)&&!e.endsWith(".d.ts")&&!e.includes(`${ER.sep}node_modules${ER.sep}`),megabytes=e=>Math.round(e/1048576),realPath=e=>zR.sys.realpath?.(e)??e;function runTypeCheck(e){const t=performance.now(),n=AR.getHeapStatistics().heap_size_limit;let r=0;const heapUsed=()=>{const e=AR.getHeapStatistics().used_heap_size;return r=Math.max(r,e),e};let s;const shouldStop=()=>(heapUsed()>n*ZR?s="memory":performance.now()-t>tN&&(s="time"),void 0!==s),i=e.reuse?JR.get(e.projectRoot,e.tsconfigPath):createTsWorkspaceService({workspaceRoot:e.projectRoot,projects:[{id:"main",rootDir:e.projectRoot,tsconfigPath:e.tsconfigPath}]});try{let o=nN.get(i);o&&!e.requestedCanvasOnly||(o={incremental:createIncrementalDiagnostics(),canvases:new Map},nN.set(i,o));const a=o.incremental.hasState?"warm":"cold",c=realPath(e.canvasFile),l=new Set([c,...e.reachableFiles.filter(isLocalSource)]),d=o.canvases.get(c)??new Set;o.canvases.delete(c),o.canvases.set(c,new Set([...l,...d]));let u=dropOldest(o,QR);const roots=()=>[...new Set([...o.canvases.values()].flatMap(e=>[...e])),...i.getGlobalDeclarationFiles()];i.setRootFiles(roots()),i.refreshModuleResolutions();const p=i.getProgram();if(!p)throw new Error("TypeScript produced no program for the canvas");const m=o.incremental.check(p,[...l],{shouldStop}),f=o.incremental.dependenciesOf(c).map(realPath).filter(e=>isLocalSource(e)&&!l.has(e));for(const e of f)l.add(e);const g=f.length>0&&!s?o.incremental.check(p,f,{shouldStop}):void 0;o.canvases.set(c,l),f.length>0&&i.setRootFiles(roots());const y=new Map([...m.diagnostics,...g?.diagnostics??[]]),b=[...m.unchecked,...g?.unchecked??[],...g?[]:s?f:[]],v=realPath(e.canvasesRoot),provenanceOf=e=>realPath(e).startsWith(v+ER.sep)?"canvas":"app",w=[];for(const t of y.values())for(const n of t){const t=n.file?.fileName;if(!t)continue;const r=typeErrorFromDiagnostic(n,{provenance:provenanceOf(t),tsconfig:e.tsconfigPath});r&&w.push(r)}s||w.push(...missingRequiredProps(p,e,c));const x=s?{errors:w,verified:!1}:verifyAppErrorsUnderOwnConfig(w,e,()=>heapUsed()>n*eN);"memory"===s&&e.reuse?JR.evict(e.projectRoot,e.tsconfigPath):heapUsed()>n*eN&&(u+=dropOldest(o,1));const S=o.canvases.size,E=l.size;return{typeErrors:x.errors,status:{...s?{status:"incomplete",reason:s}:{status:"passed"},files_checked:E-b.length,files_total:E,files_rechecked:m.recomputed+(g?.recomputed??0),cache:a,elapsed_ms:Math.round(performance.now()-t),peak_heap_mb:megabytes(r),heap_limit_mb:megabytes(n),retained_canvases:S,evicted_canvases:u,app_errors_verified:x.verified}}}finally{e.reuse||i.dispose()}}function dropOldest(e,t){let n=0;for(;e.canvases.size>Math.max(t,1);){const t=e.canvases.keys().next().value;e.canvases.delete(t),n+=1}return n}function missingRequiredProps(e,t,n){const r=e.getSourceFile(n);if(!r)return[];const s=[];for(const i of t.parsedCanvas.storyboards){const o="component"===i.kind&&i.component&&!i.componentFramework;if(!o||i.props)continue;const a=analyzeComponentPropTypes(zR,e,n,"default",i.jsxElementSpan.start);if(!a.ok)continue;const c=a.analysis.props.filter(e=>!e.optional).map(e=>e.name);if(0===c.length)continue;const l=a.analysis.component?.name??"its component",{line:d,character:u}=r.getLineAndCharacterOfPosition(i.jsxElementSpan.start);s.push({kind:"type_error",file:n,line:d+1,column:u,code:0,message:`Storyboard "${i.storyboardKey}" renders ${l} without props, but ${l} requires: ${c.join(", ")}.`,fix:`Pass props={{ ${c.map(e=>`${e}: …`).join(", ")} }} to the storyboard.`,provenance:"canvas",tsconfig:t.tsconfigPath})}return s}function verifyAppErrorsUnderOwnConfig(e,t,n){const r=ER.resolve(t.tsconfigPath),s=new Map,i=[],o=createOwnConfigLookup(t.projectRoot);for(const t of e){const e="app"===t.provenance?o(t.file):r;e&&e!==r?s.set(e,[...s.get(e)??[],t]):i.push(t)}let a=!0;for(const[e,t]of s){if(n()){a=!1,i.push(...t);continue}const r=reproduceUnderConfig(e,t);r?i.push(...r.map(t=>({...t,tsconfig:e}))):(a=!1,i.push(...t))}return{errors:i,verified:a}}function reproduceUnderConfig(e,t){let n;try{n=createTsWorkspaceService({workspaceRoot:ER.dirname(e),projects:[{id:"own",rootDir:ER.dirname(e),tsconfigPath:e}]})}catch{return}try{const e=[...new Set(t.map(e=>e.file))];n.setRootFiles([...e,...n.getGlobalDeclarationFiles()]);const r=new Set;for(const t of e)for(const e of[...n.getSyntacticDiagnostics(t),...n.getSemanticDiagnostics(t)]){if(!e.file||void 0===e.start)continue;const t=e.file.getLineAndCharacterOfPosition(e.start).line+1;r.add(`${realPath(e.file.fileName)}:${t}:${e.code}`)}return t.filter(e=>r.has(`${realPath(e.file)}:${e.line}:${e.code}`))}finally{n.dispose()}}function createOwnConfigLookup(e){const t=realPath(ER.resolve(e)),n="tempo"===ER.basename(t)?ER.dirname(t):t,r=new Map;function parse4(e){if(r.has(e))return r.get(e);const t=zR.readConfigFile(e,zR.sys.readFile);if(t.error)return r.set(e,null),null;const n=zR.parseJsonConfigFileContent(t.config,zR.sys,ER.dirname(e)),s={files:new Set(n.fileNames.map(e=>realPath(ER.resolve(e)))),references:(n.projectReferences??[]).map(e=>e.path.endsWith(".json")?e.path:ER.join(e.path,"tsconfig.json"))};return r.set(e,s),s}return e=>{for(const t of importerResolutionDirs(e,n))for(const n of["tsconfig.json","jsconfig.json"]){const r=ER.join(t,n);if(!zR.sys.fileExists(r))continue;const s=parse4(r);if(!s||s.files.has(realPath(e))||0===s.references.length)return ER.resolve(r);const i=s.references.find(t=>parse4(t)?.files.has(realPath(e)));return ER.resolve(i??r)}}}var sN=50;function sourcePositionForOffset(e,t){if(void 0===t||t<0)return{line:0,column:0};let n=1,r=0;const s=Math.min(t,e.length);for(let t=0;t<s;t+=1)10===e.charCodeAt(t)&&(n+=1,r=t+1);return{line:n,column:s-r}}function canvasFormatIssueFromParseError(e,t,n){const{line:r,column:s}=sourcePositionForOffset(t,n.span?.start);return{kind:"canvas_format",file:e,line:r,column:s,message:n.message,fix:"Update the canvas file so <Canvas> contains static storyboard declarations with literal ids and editable literal metadata."}}function canvasFormatIssueForDuplicateStoryboardId(e,t,n,r){const s=n.idSpan??n.jsxElementSpan,i=sourcePositionForOffset(t,r.idSpan?.start??r.jsxElementSpan.start),{line:o,column:a}=sourcePositionForOffset(t,s?.start);return{kind:"canvas_format",file:e,line:o,column:a,message:`Duplicate storyboard id "${n.storyboardKey}" also appears at line ${i.line}.`,fix:"Give every storyboard in the canvas a unique literal id."}}function isLegacyCanvasFile(e){const t=e.imports.some(e=>"tempo-sdk/canvas"===e.source||e.source.endsWith("/tempo-sdk/canvas"))||e.misimportedSdkCanvasImports.length>0,n=e.errors.filter(e=>"structural"===e.kind);return!t&&n.length>0&&n.every(e=>e.message===ev)}function getCanvasFormatIssues(e,t,n,r){if(r)return[];if(!n.canvasElementSpan&&isLegacyCanvasFile(n))return[];const s=n.errors.map(n=>canvasFormatIssueFromParseError(e,t,n)),i=new Map;for(const r of n.storyboards){if("html"===r.kind&&!r.filepath?.trim()&&r.src?.trim()&&s.push(canvasFormatIssueFromParseError(e,t,{message:'<HtmlStoryboard> must include a literal "filepath" prop naming a local .html file; to show a live URL use <RouteStoryboard route="https://…">',span:r.jsxElementSpan,kind:"degraded"})),!r.storyboardKey)continue;const n=i.get(r.storyboardKey);n?s.push(canvasFormatIssueForDuplicateStoryboardId(e,t,r,n)):i.set(r.storyboardKey,r)}return s}async function validatePage(e,t,n){const r=PD.resolve(e),s=PD.resolve(t),i=n?.tsconfigPath??PD.join(s,"tsconfig.json"),o=DD.readConfigFile(i,DD.sys.readFile);if(o.error){const e=DD.flattenDiagnosticMessageText(o.error.messageText,"\n");throw new Error(`Failed to read tsconfig at ${i}: ${e}`)}const a=DD.parseJsonConfigFileContent(o.config,{...DD.sys,readDirectory:()=>[]},PD.dirname(i),void 0,i),c=DD.sys.readFile(r);if(void 0===c)throw new Error(`Canvas file not found: ${r}`);const l=parseCanvasFile(r,c),d={fileExists:DD.sys.fileExists,readFile:DD.sys.readFile,realpath:DD.sys.realpath,directoryExists:DD.sys.directoryExists,getCurrentDirectory:()=>s,getDirectories:DD.sys.getDirectories},u=walkImports(r,a.options,d,s,i),p=checkLoadability(u.graph,repoRootForCanvasWalk(realPath2(s))),m=p.issues.some(e=>"syntax_error"===e.kind&&e.file===realPath2(r)),f=getCanvasFormatIssues(r,c,l,m),g=m||isLegacyCanvasFile(l)?[]:checkCanvasEntry(r,c,l),y=await checkDependencies(u.npmPackages,s,n?.tempoPackageDir),b=[...u.serverOnlyImports.entries()].map(([e,t])=>({kind:"server_component_import",specifier:e,file:t,message:`"${e}" is a server-only API, so this canvas renders a React Server Component. The canvas renders components client-side and cannot run server components; importing a server-only module also breaks the canvas devserver build for the whole project.`,fix:"Point the storyboard at the underlying client component (or a 'use client' wrapper) instead of the server/page component, and pass demo props in place of server data."})),v=n?.skipTypeCheck?void 0:runTypeCheck({canvasFile:r,projectRoot:s,tsconfigPath:i,canvasesRoot:n?.canvasesRoot??defaultCanvasesRoot(s),reachableFiles:[...u.graph.keys(),...u.typeOnlyFiles],parsedCanvas:l,reuse:!0===n?.reuseTypeCheckService,requestedCanvasOnly:n?.requestedCanvasOnly}),w=v?.typeErrors??[],x=w.filter(e=>"canvas"===e.provenance),S=w.filter(e=>"canvas"!==e.provenance),E=[...f,...g],A=[...p.issues,...y],C=[...b,...E,...A],statusOf=e=>e.length>0?{status:"failed"}:{status:"passed"};return{valid:0===C.length,issues:C,warnings:p.warnings,type_errors:[...x,...S.slice(0,sN)],type_error_totals:{canvas:x.length,app:S.length},canvas_type_errors:x.length,checks:{canvas_format:statusOf(E),imports:statusOf([...b,...A]),type_check:v?.status??{status:"not_run",reason:"skipped"}}}}function defaultCanvasesRoot(e){return"tempo"===PD.basename(e)?PD.join(e,"designs"):PD.join(e,"tempo","designs")}function realPath2(e){return DD.sys.realpath?.(e)??e}import{access as iN}from"fs/promises";import oN from"path";var aN="Refer to get_guide({ topic: 'tempo-canvas-instructions' }) for details on setting up the canvas infrastructure.";async function pathExists11(e){try{return await iN(e),!0}catch{return!1}}async function isUrlReachable(e){try{const t=new AbortController,n=setTimeout(()=>t.abort(),5e3),r=await fetch(e,{signal:t.signal});return clearTimeout(n),r.ok}catch{return!1}}async function validateHost(e){const t=[],n=oN.join(e.tempoRoot,"node_modules","tempo-sdk");return await pathExists11(n)||t.push({kind:"host_setup_issue",check:"dependencies_not_installed",file:n,message:"The canvas host's dependencies are not installed yet (tempo-sdk is not in its node_modules). Call start_canvas_devserver first: it runs scripts.install from tempo.config.json and starts the host. Then rerun canvas_validate.",fix:`Call start_canvas_devserver (add force_install: true after editing scripts.install), then rerun canvas_validate. ${aN}`}),e.devserverUrl?await isUrlReachable(e.devserverUrl)||t.push({kind:"host_setup_issue",check:"tempo_host_not_reachable",file:e.tempoRoot,message:`/tempo-host was not reachable at ${e.devserverUrl}.`,fix:`Call start_canvas_devserver (it restarts a host that stopped), then rerun canvas_validate; if it still fails, check_canvas_devserver reports the start error. ${aN}`}):t.push({kind:"host_setup_issue",check:"tempo_host_not_reachable",file:e.tempoRoot,message:"The devserver does not appear to be running (no devserver URL is available). Call start_canvas_devserver, then rerun canvas_validate.",fix:`Call start_canvas_devserver, then rerun canvas_validate. ${aN}`}),t}import{readFile as cN}from"fs/promises";import lN from"path";async function validateFlutterStoryboards(e){const t=await cN(e.pageFile,"utf-8").catch(()=>null);if(null===t)return[];const n=lN.join(e.projectRoot,"tempo"),r=parseCanvasFile(e.pageFile,t),s=r.storyboards.filter(e=>void 0!==e.preview),i=s.map(t=>{const r=t.preview,s=parseFlutterPreview(r);return{canvasFile:e.pageFile,storyboardId:t.storyboardKey,preview:r,key:"error"in s?null:flutterPreviewKey(n,lN.resolve(lN.dirname(e.pageFile),s.file),s.functionName)}}),o=await resolveFlutterPreviews(i,e.projectRoot,n),a=o.problems.map(n=>({kind:"canvas_format",file:e.pageFile,...positionOf2(t,s.find(e=>e.storyboardKey===n.storyboardId)?.previewSpan?.start),message:`${n.code}: ${n.message}`,fix:"Name a Dart file relative to this canvas and a public top-level @Preview function, with a valid Flutter pubspec above the file."}));for(const t of o.packages)for(const n of await findNativeOnlyImports(t.dir,t.name,t.discovery.previews.map(e=>e.libraryFile))){if("build-fails"!==n.effect)continue;const{problem:t,fix:r}=describeNativeOnlyImport(n);a.push({kind:"canvas_format",file:e.pageFile,line:0,column:0,message:t,fix:r})}return a}function positionOf2(e,t){if(void 0===t||t<0)return{line:0,column:0};const n=e.slice(0,t),r=n.split("\n").length;return{line:r,column:t-(n.lastIndexOf("\n")+1)}}import{readFile as dN}from"fs/promises";import uN from"path";import pN from"path";import{readdir as hN,stat as mN}from"fs/promises";import fN from"path";async function pathExists12(e){try{return await mN(e),!0}catch{return!1}}async function listFilesRecursively(e){const t=await hN(e,{withFileTypes:!0}),n=[];for(const r of t){const t=fN.join(e,r.name);r.isDirectory()?n.push(...await listFilesRecursively(t)):n.push(t)}return n.sort((e,t)=>e.localeCompare(t))}async function runComputeLayoutCommand(e){const t=e.new_storyboards??[];if(!Array.isArray(t))throw new Error("new_storyboards must be an array");let n=[];if(e.canvas_file){const t=await resolveCanvasFilePath(e.canvas_file)??pN.resolve(e.canvas_file);if(!await pathExists12(t))throw new Error(`Canvas file not found: ${t}`);const r=await parsePageFile(t);n=toStoryboardRects(r)}const r=t.map((e,t)=>{const n=e.name?.trim();if(!n)throw new Error(`new_storyboards[${t}] must include a non-empty name`);return{name:n,width:Number.isFinite(e.width)?Math.max(1,Math.round(e.width)):IP,height:Number.isFinite(e.height)?Math.max(1,Math.round(e.height)):PP}}),s=computeStoryboardPositions({existing:n,newStoryboards:r});return{positions:s}}import gN from"path";async function runCreatePageCommand(e){const t=gN.resolve(e.repo_root),n=e.canvas_name,r=(e.storyboards??[]).map(e=>({exportName:e.export_name,name:e.name,importPath:e.import_path,importName:e.import_name,route:e.route,preview:e.preview,width:e.width,height:e.height})),s=await createPage({projectRoot:t,pageName:n,storyboards:r,home:e.home,backgroundColor:e.background_color});return{canvas_dir:s.pageDir,canvas_file:s.pageFile,repo_root:t,storyboards:s.storyboards.map(e=>({export_name:e.exportName,x:e.x,y:e.y,width:e.width,height:e.height,...e.stub?{stub:!0}:{}}))}}import{rm as yN}from"fs/promises";import bN from"path";async function runDeletePageCommand(e){const t=await resolveCanvasDirPath(e.canvas_dir)??bN.resolve(e.canvas_dir);if(!await pathExists12(t))throw new Error(`Directory not found: ${t}`);const n=bN.join(t,"index.canvas.tsx");if(!await pathExists12(n))throw new Error(`Not a canvas folder: ${t} (missing index.canvas.tsx)`);const r=await listFilesRecursively(t);return await yN(t,{recursive:!0,force:!1}),{deleted:!0,deleted_files:r}}import vN from"path";async function runListPagesCommand(e){const t=vN.resolve(e.workspace_root);if(!await pathExists12(t))throw new Error(`Workspace root does not exist: ${t}`);const n=e.repo_names?.length?Array.from(new Set(e.repo_names.map(e=>e.trim()).filter(e=>e.length>0))).map(e=>({repoRoot:vN.join(t,e),repoName:e})):[{repoRoot:t,repoName:""}],r=[];for(const{repoRoot:e,repoName:t}of n){if(!await pathExists12(e))continue;const n=await listPageInfosInRepo({repoRoot:e,repoName:t});r.push(...n.map(e=>({file_path:e.filePath,canvas_dir:e.pageDir,repo_name:e.repoName,canvas_name:e.pageName,storyboard_names:e.storyboardNames})))}return r.sort((e,t)=>e.file_path.localeCompare(t.file_path)),{pages:r}}import wN from"path";async function runMigrateCanvasCommand(e){const t=wN.resolve(e.repo_root),n=wN.isAbsolute(e.canvas_file)?e.canvas_file:wN.join(t,e.canvas_file),r=await resolveCanvasFilePath(n);if(!r)throw new Error(`Not a canvas: ${e.canvas_file} (no index.canvas.tsx found there)`);const{migrated:s}=await ensureCanvasPageFileMigrated(r);return{canvas_file:r,migrated:s,already_latest:!s}}import _N from"path";async function runSetHomeCanvasCommand(e){const t=_N.resolve(e.repo_root),n=_N.isAbsolute(e.canvas_dir)?e.canvas_dir:_N.join(t,e.canvas_dir),r=await resolveCanvasFilePath(n);if(!r)throw new Error(`Not a canvas: ${e.canvas_dir} (no index.canvas.tsx found there)`);const s=await listPageInfosInRepo({repoRoot:t,repoName:""}),i=[];for(const e of s)!0===e.home&&e.filePath!==r&&await unmarkCanvasAsHome(e.filePath)&&i.push(e.filePath);const o=await markCanvasAsHome(r);return{canvas_dir:_N.dirname(r),canvas_file:r,repo_root:t,newly_marked:o,unmarked_previous:i}}import xN from"path";import{readFile as TN}from"fs/promises";import kN from"path";async function readDevServerStatus(e){const t=kN.join(e,".tempo","status.json");let n;try{n=await TN(t,"utf-8")}catch{return{dependenciesInstalled:!1,devserverUrl:null}}try{const e=JSON.parse(n);return{dependenciesInstalled:!0===e.dependenciesInstalled,devserverUrl:"string"==typeof e.devserverUrl?e.devserverUrl:null}}catch{return{dependenciesInstalled:!1,devserverUrl:null}}}var SN="Refer to get_guide({ topic: 'tempo-canvas-instructions' }) for details on setting up the canvas infrastructure.",EN='This project\'s apps[0].uiFramework is "vue": the set-up-vue-or-nuxt-canvas skill lists the Vue and Nuxt causes of this check by error message.';function typeErrorSummary(e){const t=e.canvas+e.app;return 0===t?[]:[`${t} type error${1===t?"":"s"} (${e.canvas} in canvas files); see type_errors. Type errors do not make the canvas invalid.`]}function formatIssueAsString(e){switch(e.kind){case"host_setup_issue":return e.message;case"server_component_import":return`${e.file} - server-only import '${e.specifier}' renders a React Server Component, which the canvas can't run. ${e.fix}`;case"canvas_format":case"syntax_error":case"missing_file":case"missing_export":case"missing_default_export":case"canvas_not_rendered":return`${e.file}:${e.line} - ${e.message}`;case"unresolved_import":return`${e.file}:${e.line} - Cannot resolve import '${e.specifier}'`;case"missing_package":return`Missing package: ${e.package_name}@${e.version} (required by ${e.required_by})`;case"local_module_import":return`${e.required_by} - ${e.message} ${e.fix}`;case"type_error":return`${e.file}:${e.line} - TS${e.code}: ${e.message}`}}async function runValidatePageCommand(e,t){const n=xN.resolve(e.repo_root),r=xN.resolve(n,e.canvas_file),s=await resolveCanvasFilePath(r)??r;let i;try{i=await resolveTempoConfig(n)}catch{const e={kind:"host_setup_issue",check:"config_invalid",file:xN.join(n,"tempo.config.json"),message:"tempo.config.json is missing or invalid.",fix:`Create or fix tempo.config.json in the project root. ${SN}`},t={status:"not_run",reason:"config_invalid"};return{valid:!1,issues:[e],errors:[formatIssueAsString(e)],warnings:[],type_errors:[],type_error_totals:{canvas:0,app:0},canvas_type_errors:0,checks:{host:{status:"failed"},canvas_format:t,imports:t,type_check:t}}}const o=await readDevServerStatus(i.tempoRoot),a=await validateHost({tempoRoot:i.tempoRoot,devserverUrl:o.devserverUrl}),c="vue"===i.apps[0]?.uiFramework,l=c?a.map(e=>({...e,fix:`${e.fix} ${EN}`})):a,d={tsconfigPath:i.tsconfigPath,tempoPackageDir:xN.dirname(i.packageJsonPath),reuseTypeCheckService:t?.reuseTypeCheckService,skipTypeCheck:"skip"===e.type_check,requestedCanvasOnly:"requested_canvas_only"===e.type_check},u=await validatePage(s,n,{...d,canvasesRoot:i.pagesDir}),p=await validateFlutterStoryboards({pageFile:s,projectRoot:n}),m=[...l,...p,...u.issues],f=p.length>0?{status:"failed"}:u.checks.canvas_format;return{valid:0===m.length,issues:m,errors:[...m.map(formatIssueAsString),...typeErrorSummary(u.type_error_totals)],warnings:u.warnings,type_errors:u.type_errors,type_error_totals:u.type_error_totals,canvas_type_errors:u.canvas_type_errors,checks:{...u.checks,canvas_format:f,host:l.length>0?{status:"failed"}:{status:"passed"}}}}import AN from"path";function toInitCommandResult(e){return{framework:e.framework,skipped:!1,types_file:e.typesFile,tsconfig_modified:e.tsconfigUpdated,warnings:e.warnings}}async function runInitCommand(e){const t=AN.resolve(e.repo_root),n=await initializePagesSupport({projectRoot:t,framework:e.framework});return toInitCommandResult(n)}async function runCanvasToolCommand(e,t){switch(e){case"create-canvas":return await runCreatePageCommand(t);case"compute-layout":return await runComputeLayoutCommand(t);case"list-canvases":return await runListPagesCommand(t);case"delete-canvas":return await runDeletePageCommand(t);case"set-home-canvas":return await runSetHomeCanvasCommand(t);case"migrate-canvas":return await runMigrateCanvasCommand(t);case"validate-canvas":return await runValidatePageCommand(t);default:throw new Error(`Unknown command: ${e}`)}}import{z as CN}from"zod";import{z as IN}from"zod";var PN=IN.enum(["vite","nextjs","nuxt","astro"]),DN=IN.object({tempoHost:IN.literal(!0),contractVersion:IN.number().int().min(1),sdkVersion:IN.string().min(1),pluginActive:IN.boolean(),framework:PN,capabilities:IN.object({astroComponents:IN.number().optional(),vueSourceAnnotation:IN.number().optional()}).optional()});function unverified(e){return{verified:!1,code:"app_instrumentation_unverified",message:e,fix:"Check that this is the app's dev-server URL and that /__tempo/identity is reachable through any auth or proxy. For Astro 7, install a tempo-sdk version exporting tempo-sdk/astro and add tempoAstro() to integrations in astro.config; require the astroComponents:1 capability. For a Vite prototype, install tempo-sdk in the app package and add tempoVitePlugin() to the app's own Vite config, preserving its other plugins. For a Nuxt app, keep `--extends` with the path to tempo/nuxt-app-layer relative to the app directory in apps[0].start (`./tempo/nuxt-app-layer` for an app at the project root, `../tempo/nuxt-app-layer` for `appDir: \"web\"`); that Tempo layer adds tempo-sdk/nuxt to the app's own `nuxt dev` without editing its nuxt.config. For Vue or Nuxt, the set-up-vue-or-nuxt-canvas skill has the exact config and checks. The tempo/ sidecar cannot instrument the app. Restart with stop_app_dev_server then start_app_dev_server({ require_instrumentation: true }); Tempo supplies TEMPO=true."}}function nuxtAppLayerMissing(e,t){return{verified:!1,code:"app_instrumentation_unverified",message:e,fix:`apps[0].start in tempo/tempo.config.json does not load Tempo's Nuxt app layer, which adds tempo-sdk/nuxt and the /__tempo/identity route to the app's own nuxt dev. Add \`--extends ${t.extendsPath}\` to the nuxt dev command in apps[0].start (Tempo's command for this app is \`${t.tempoStart}\`), then restart with stop_app_dev_server and start_app_dev_server({ require_instrumentation: true }).`}}var RN=5e3,NN=250;async function fetchIdentityPastWarmUp(e,t){const n=Date.now()+t;for(;;){const t=await fetch(e,{signal:AbortSignal.timeout(Math.max(1,n-Date.now())),cache:"no-store",redirect:"manual"}),r=503===t.status;if(!r||Date.now()+NN>=n)return t;await(t.body?.cancel()),await new Promise(e=>setTimeout(e,NN))}}async function verifyAppInstrumentation(e,t={}){if(!e.configured||!e.running||!e.url)return{verified:!1,code:"app_server_not_running",message:e.error??"The app must be running before its instrumentation can be verified.",fix:e.configured?"Resolve the app server's startup error, then call start_app_dev_server({ require_instrumentation: true }).":"Configure the app with set_app_dev_command, then call start_app_dev_server({ require_instrumentation: true })."};try{const n=new URL("/__tempo/identity",e.url),r=t.budgetMs??RN,s=await fetchIdentityPastWarmUp(n,r),i=t.nuxtAppLayer??null;if(!s.ok){if(await(s.body?.cancel()),503===s.status)return unverified(`Could not verify app instrumentation: ${n} still answered HTTP 503 (the server is starting) after ${r/1e3} seconds. Call start_app_dev_server({ require_instrumentation: true }) again once it has warmed up.`);const e=`Could not verify app instrumentation: ${n} returned HTTP ${s.status}.`;return i?nuxtAppLayerMissing(e,i):unverified(e)}if("1"!==s.headers.get("x-tempo-host-identity")){await(s.body?.cancel());const t=`The app at ${e.url} did not return the Tempo SDK identity header. Rendering successfully does not prove that its source is instrumented.`;return i?nuxtAppLayerMissing(t,i):unverified(t)}const o=DN.safeParse(await s.json());if(!o.success)return unverified("The app returned an invalid Tempo SDK identity. An active app plugin could not be verified.");if(!o.data.pluginActive)return{verified:!1,code:"app_instrumentation_inactive",message:"The app's Tempo SDK reports pluginActive: false.",fix:"Restart the app through Tempo with TEMPO=true reaching the framework process, including across container or remote launchers. Then call start_app_dev_server({ require_instrumentation: true }) again."};if("astro"===o.data.framework&&1!==o.data.capabilities?.astroComponents)return unverified("The app SDK does not support native Astro component previews; update tempo-sdk in the app package.");const a="vue"===t.uiFramework&&"vite"===o.data.framework;return a&&1!==o.data.capabilities?.vueSourceAnnotation?{verified:!1,code:"app_vue_annotation_missing",message:"The app's Tempo Vite plugin is active, but Tempo's Vue annotator is not: its .vue templates carry no source stamps, so Vue route storyboards have no .vue layers and canvas edits on them cannot write the files.",fix:'Add `import { tempoVuePlugin } from "tempo-sdk/vue";` and `...tempoVuePlugin()` to the plugins of the app\'s own vite.config, before vue() and before any other plugin that rewrites .vue source, keeping tempoVitePlugin(). A tempo-sdk in the app too old to report the annotator fails this check too: update it. Then restart with stop_app_dev_server and start_app_dev_server({ require_instrumentation: true }). The set-up-vue-or-nuxt-canvas skill has the full file.'}:{verified:!0,framework:o.data.framework,sdkVersion:o.data.sdkVersion}}catch(e){return unverified(e instanceof Error&&"TimeoutError"===e.name?`The app instrumentation check timed out after ${(t.budgetMs??RN)/1e3} seconds.`:`Could not verify app instrumentation: ${e instanceof Error?e.message:String(e)}`)}}import ON from"path";import FN from"path";import{readFileSync as LN}from"fs";var MN={duplicate_asset_declaration:"Keep one defineAsset beside the component. Existing canvas-owned declarations are also supported, but must not duplicate it.",component_declaration_outside_canvas:"Move the defineAsset reference declaration into the folder of the canvas that showcases this component (its index.canvas.tsx or a sibling file in the same folder).",redundant_canvas_declaration:"Remove the canvas-level defineAsset self-registration — the canvas's component declarations already link it; canvas self-registration is strictly for pages with truly no component to declare (foundations like color or icons).",missing_asset_declaration:"a design-system/library canvas must declare the top-level component(s) it showcases, or self-register with usageInstructions if it is a componentless foundations page"};function formatAssetDeclarationIssue(e){return`${e.file} - ${e.message}. Fix: ${e.fix}`}async function collectAssetDeclarationIssues(e){const t=FN.isAbsolute(e.canvasFile)?e.canvasFile:FN.join(e.workspaceRoot,e.canvasFile),n=/\.[cm]?[jt]sx?$/i.test(FN.basename(t)),r=normalizeWorkspaceRelativePath(e.workspaceRoot,n?FN.dirname(t):t),inCanvasFolder=e=>e===r||e.startsWith(`${r}/`),s=await loadWorkspaceAssetIndex({workspaceRoot:e.workspaceRoot,canvasesDir:e.canvasesDir}),i=new Set,readFile48=t=>{try{return LN(FN.join(e.workspaceRoot,t),"utf8")}catch{return null}},o=readFile48(`${r}/index.canvas.tsx`);if(o){const{program:e}=parseAssetProgram(`${r}/index.canvas.tsx`,o);if(e)for(const t of readAssetImports(e).referenceableImports.values()){const e=t.importSpecifier.startsWith(".")?resolveRelativeImport(r,t.importSpecifier):`pkg:${t.importSpecifier}`,n=resolveComponentIdentity({readFile:readFile48},e,t.importedName,`${r}/index.canvas.tsx`);if(n)for(const e of Object.values(s.assets))(e.componentFilePath??e.filePath)===n.filePath&&(e.componentName??e.name)===n.name&&i.add(e.key)}}const a=[];for(const[e,t]of Object.entries(s.fileErrors))for(const n of t){if("duplicate_asset_declaration"!==n.code&&"component_declaration_outside_canvas"!==n.code)continue;const t=inCanvasFolder(e)||"duplicate_asset_declaration"===n.code&&n.message.includes(`"${r}/`);t&&a.push({kind:"asset_declaration_error",code:n.code,file:e,message:n.message,fix:MN[n.code]})}for(const e of Object.values(s.assets))if("canvas"===e.kind&&inCanvasFolder(e.filePath))for(const t of e.warnings)"redundant_canvas_declaration"===t.code&&a.push({kind:"asset_declaration_error",code:"redundant_canvas_declaration",file:e.filePath,message:t.message,fix:MN.redundant_canvas_declaration});const c=normalizeWorkspaceRelativePath(e.workspaceRoot,FN.resolve(e.workspaceRoot,e.canvasesDir)),l=r===c||r.startsWith(`${c}/`),d=l?classifyCanvasZone(r.slice(c.length+1)):null;if(d&&isStrictZone(d)){const e=Object.values(s.assets).some(e=>inCanvasFolder(e.declaredIn??e.filePath)||i.has(e.key))||Object.entries(s.fileErrors).some(([e,t])=>inCanvasFolder(e)&&t.some(e=>"duplicate_asset_declaration"===e.code));if(!e){const e="design-system"===d.kind?"design-system zone":"library zone"+(d.libraryName?` ("${d.libraryName}")`:"");a.push({kind:"asset_declaration_error",code:"missing_asset_declaration",file:`${r}/index.canvas.tsx`,message:`canvas "${r}" is in the ${e} but contains no defineAsset declaration`,fix:MN.missing_asset_declaration})}}return a}async function runCanvasValidation(e,t){if(e={...e,repo_root:ON.resolve(e.repo_root),canvas_file:ON.resolve(e.repo_root,e.canvas_file)},"page-dependencies"===e.validation_kind){const n=await(t?.validatePageDependencies??((e,t)=>validatePage(e,t,{skipTypeCheck:!0})))(ON.resolve(e.canvas_file),ON.resolve(e.repo_root));return{valid:n.valid,issues:n.issues,errors:[],warnings:n.warnings,checks:n.checks}}const n=await(t?.runValidatePageCommand??runValidatePageCommand)(e);if(!1===e.assets_enabled)return{...n,checks:{...n.checks,assets:{status:"not_run"}}};const r=ON.resolve(e.workspace_root??e.repo_root),s=e.canvases_dir??ON.join(r,"tempo","designs"),i=await collectAssetDeclarationIssues({workspaceRoot:r,canvasesDir:s,canvasFile:e.canvas_file});return 0===i.length?{...n,checks:{...n.checks,assets:{status:"passed"}}}:{...n,checks:{...n.checks,assets:{status:"failed"}},valid:!1,issues:[...n.issues,...i],errors:[...n.errors,...i.map(formatAssetDeclarationIssue)]}}import{readFile as UN,realpath as jN}from"fs/promises";import BN from"path";var $N="data-tempo-projection-pending",WN="data-tempo-projection-unavailable",HN=3,qN="canvasProtocol",zN={canvasPath:"canvasPath",storyboardId:"storyboardId",width:"width",height:"height",idle:"tempoCaptureIdle"},GN={width:1600,height:1200},VN="data-tempo-storyboard-render-id",KN=`[${$N}]`,XN='[data-render-error="true"]',YN="data-render-error-message";function buildCanvasStoryboardRenderId(e,t){return`canvas:${encodeURIComponent(e.trim())}#storyboard:${encodeURIComponent(t.trim())}`}function buildStoryboardRenderSelector(e){return`[${VN}=${JSON.stringify(e)}]`}function buildCanvasHostUrl(e,t=!1){const n=new URL(e);return n.searchParams.set(qN,String(HN)),t&&n.searchParams.set("canvasRegistration","incremental"),n}function buildDirectRenderUrl(e,t){const n=void 0!==t.width,r=void 0!==t.height;if(n!==r)throw new Error("Direct render width and height must be provided together");const s=buildCanvasHostUrl(e);return s.searchParams.delete(zN.idle),s.searchParams.set(zN.canvasPath,t.canvasPath),s.searchParams.set(zN.storyboardId,t.storyboardId),n&&r?(s.searchParams.set(zN.width,String(t.width)),s.searchParams.set(zN.height,String(t.height))):(s.searchParams.delete(zN.width),s.searchParams.delete(zN.height)),s.toString()}function buildDirectRenderIdleUrl(e){const t=buildCanvasHostUrl(e);for(const e of Object.values(zN))t.searchParams.delete(e);return t.searchParams.set(zN.idle,"1"),t.toString()}import{createHash as JN}from"crypto";import{readFile as QN,realpath as ZN}from"fs/promises";import{readFileSync as eO,realpathSync as tO}from"fs";import{isAbsolute as nO,relative as rO,resolve as sO}from"path";async function readBrowserRuntimeScript(e=process.env.TEMPO_SDK_RUNTIME_PATH){if(!e||!nO(e))throw new Error("Tempo browser runtime is not provisioned. Set TEMPO_SDK_RUNTIME_PATH to the host's private runtime directory.");const t=JSON.parse(await QN(sO(e,"runtime.json"),"utf8")),n=t.browser;if(1!==t.tempoRuntimeContract||"string"!=typeof n?.file||"string"!=typeof n?.sha256)throw new Error("Incompatible Tempo browser runtime. Update the host application.");const r=await ZN(e),s=await ZN(sO(r,n.file)),i=rO(r,s);if(nO(i)||".."===i||i.startsWith("../")||i.startsWith("..\\"))throw new Error("Tempo browser runtime path escapes its directory.");const o=await QN(s,"utf8");if(JN("sha256").update(o).digest("hex")!==n.sha256)throw new Error("Tempo browser runtime artifact failed its integrity check.");return o}import{createHash as iO}from"crypto";var oO=C(ru(),1),aO=Date.UTC(2026,0,1,12,0,0);function buildFreezeInitScript(){return`(() => {\n const FROZEN_NOW = ${aO};\n const RealDate = Date;\n class FrozenDate extends RealDate {\n constructor(...args) {\n if (args.length === 0) {\n super(FROZEN_NOW);\n } else {\n super(...args);\n }\n }\n static now() {\n return FROZEN_NOW;\n }\n }\n FrozenDate.parse = RealDate.parse;\n FrozenDate.UTC = RealDate.UTC;\n Date = FrozenDate;\n globalThis.Date = FrozenDate;\n if (typeof performance !== "undefined") {\n const origin = performance.now();\n const realNow = performance.now.bind(performance);\n performance.now = () => realNow() - origin;\n }\n let seed;\n globalThis.__tempoResetCaptureDeterminism = () => {\n seed = 0x74656d70;\n };\n globalThis.__tempoResetCaptureDeterminism();\n Math.random = () => {\n seed |= 0;\n seed = (seed + 0x6d2b79f5) | 0;\n let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n})();`}var cO="\n@layer tempo-capture-motion {\n*, *::before, *::after {\n animation-duration: 0s !important;\n animation-delay: 0s !important;\n transition-duration: 0s !important;\n transition-delay: 0s !important;\n scroll-behavior: auto !important;\n caret-color: transparent !important;\n}\n}\n",lO=["target","fonts","suspense","content-quiet","paint"],dO=2e3,uO=300,pO=15e3,hO=50,mO="(function() {\n try {\n if (location.pathname.includes('/__tempo/astro/')) {\n var meta = document.querySelector('meta[name=\"tempo-astro-storyboard\"]');\n if (!meta) return false;\n var receipt = JSON.parse(meta.content);\n var address = location.pathname.split('/__tempo/astro/')[1].replace(/\\/$/, '').split('/');\n if (receipt.canvasPath !== decodeURIComponent(address[0]) || receipt.storyboardId !== decodeURIComponent(address[1])) return false;\n }\n if (document.querySelector('script[data-island-id]')) return false;\n return Array.from(document.querySelectorAll('astro-island[ssr]')).every(function(island) {\n var mode = island.getAttribute('client');\n if (mode === 'media') return !matchMedia(JSON.parse(island.getAttribute('opts') || '{}').value).matches;\n if (mode === 'visible') return !Array.from(island.children).some(function(child) {\n var r = child.getBoundingClientRect();\n return r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth && (r.width > 0 || r.height > 0);\n });\n return false;\n });\n } catch { return false; }\n})()";function buildSettleWaitScript(e){const t=Math.max(0,Math.round(e.quietMs??uO)),n=Math.max(1,Math.round(e.stepTimeoutMs??pO)),r=Math.max(1,Math.round(e.quietTimeoutMs??n)),s=Math.max(1,Math.round(e.pollMs??hO));return`\n (function() {\n var selector = ${JSON.stringify(e.selector)};\n var waitForMedia = ${!1!==e.waitForMedia};\n var pendingSelector = ${JSON.stringify(e.pendingSelector??null)};\n var quietMs = ${t};\n var stepTimeoutMs = ${n};\n var quietTimeoutMs = ${r};\n var quietBestEffort = ${!0===e.quietBestEffort?"true":"false"};\n var strictVideoFrames = ${!0===e.strictVideoFrames?"true":"false"};\n var pollMs = ${s};\n var runPaint = ${!1===e.paint?"false":"true"};\n var steps = {};\n // Cleared when the content-quiet step gives up under best effort.\n var quiet = true;\n // Monotonic and immune to the determinism kit's frozen Date.\n var now = typeof performance !== 'undefined' && performance && typeof performance.now === 'function'\n ? function() { return performance.now(); }\n : function() { return Date.now(); };\n\n function failure(step, message) {\n return { ok: false, step: step, message: message, steps: steps };\n }\n\n // Polls \`check\` until it answers true, or \`budgetMs\` elapses. The\n // first check runs synchronously so an already-settled step costs no\n // poll interval. A step run with \`giveUp\` resolves at its budget\n // instead of failing, recording that the content never held still.\n function until(step, check, budgetMs, giveUp) {\n var started = now();\n return new Promise(function(resolve, reject) {\n function tick() {\n var done;\n try {\n done = check();\n } catch (error) {\n steps[step] = Math.round(now() - started);\n reject(failure(step, String((error && error.message) || error)));\n return;\n }\n if (done) {\n steps[step] = Math.round(now() - started);\n resolve();\n return;\n }\n if (now() - started >= budgetMs) {\n steps[step] = Math.round(now() - started);\n if (step === 'content-quiet' && pendingStrictVideo !== null) {\n reject(failure(step, pendingStrictVideo + '; Timeout ' + budgetMs + 'ms exceeded'));\n return;\n }\n if (giveUp) {\n quiet = false;\n resolve();\n return;\n }\n reject(failure(step, 'Timeout ' + budgetMs + 'ms exceeded'));\n return;\n }\n setTimeout(tick, pollMs);\n }\n tick();\n });\n }\n\n var quietKey = null;\n var quietSince = 0;\n var pendingStrictVideo = null;\n // When a rendered video was first seen without a decoded frame, and how\n // long that may hold the quiet window before we give up on it.\n var videoWaitStartedAt = null;\n var videoWaitCapMs = ${dO};\n // Images that take part in the capture: laid out and not hidden. A\n // hidden responsive variant never starts native lazy loading and must\n // not hold the window; a rendered lazy image never starts either,\n // because a capture does not scroll, so it is asked for eagerly.\n function renderedMatches(target, tag) {\n var all = Array.prototype.slice.call(target.querySelectorAll(tag));\n var rendered = [];\n for (var i = 0; i < all.length; i++) {\n var el = all[i];\n if (el.getClientRects().length === 0) continue;\n var visibility = getComputedStyle(el).visibility;\n if (visibility === 'hidden' || visibility === 'collapse') continue;\n rendered.push(el);\n }\n return rendered;\n }\n function renderedImages(target) {\n return renderedMatches(target, 'img');\n }\n // The source each image was last asked to decode, and whether that\n // decode has settled. A new source asks again.\n var decodes = typeof WeakMap === 'function' ? new WeakMap() : null;\n function imageDecoded(img) {\n if (!decodes || typeof img.decode !== 'function') return true;\n var src = img.currentSrc || img.src;\n var entry = decodes.get(img);\n if (!entry || entry.src !== src) {\n entry = { src: src, done: false };\n decodes.set(img, entry);\n var settled = function() { entry.done = true; };\n img.decode().then(settled, settled);\n }\n return entry.done;\n }\n // Preserve the bounded readiness heuristic for live screenshots.\n // Strict baselines additionally prove decoding below: Chromium's\n // suspended metadata startup can report readyState 3/4 with no frame.\n function videoFrameReady(video) {\n if (video.error) return true;\n if (video.preload === 'none') return true;\n var networkState = video.networkState;\n if (networkState === 0 /* NETWORK_EMPTY */) return true;\n if (networkState === 3 /* NETWORK_NO_SOURCE */) return true;\n return video.readyState >= 2 /* HAVE_CURRENT_DATA */;\n }\n function videoSource(video) {\n var source = video.querySelector('source[src]');\n return video.currentSrc || video.src || (source && source.src) || '(no source)';\n }\n var posterDecodes = strictVideoFrames ? new WeakMap() : null;\n function videoPosterDecoded(video) {\n var src = video.poster;\n var crossOrigin = video.crossOrigin;\n var entry = posterDecodes.get(video);\n if (!entry || entry.src !== src || entry.crossOrigin !== crossOrigin) {\n var image = video.ownerDocument.createElement('img');\n entry = { src: src, crossOrigin: crossOrigin, image: image, done: false, error: null };\n posterDecodes.set(video, entry);\n // Match the poster request's CORS/credentials policy before it\n // starts. A no-CORS image could decode a blocked video poster.\n image.crossOrigin = crossOrigin;\n image.src = src;\n image.decode().then(\n function() { entry.done = true; },\n function(error) { entry.error = String((error && error.message) || error); }\n );\n }\n if (entry.error !== null) {\n throw new Error('Video poster could not decode: ' + src + ': ' + entry.error);\n }\n return entry.done;\n }\n var videoFrames = strictVideoFrames ? new Map() : null;\n function frameSource(video) {\n return JSON.stringify([video.currentSrc, video.src, video.crossOrigin,\n Array.prototype.map.call(video.querySelectorAll('source'), function(source) {\n return [source.src, source.type, source.media];\n })]);\n }\n function resetVideoFrame(entry) {\n entry.generation++;\n if (entry.callbackId !== null) {\n entry.video.cancelVideoFrameCallback(entry.callbackId);\n entry.callbackId = null;\n }\n entry.presented = false;\n quietKey = null;\n }\n function releaseVideoFrame(entry) {\n resetVideoFrame(entry);\n entry.video.removeEventListener('emptied', entry.reset);\n entry.video.removeEventListener('loadstart', entry.reset);\n entry.video.removeEventListener('seeking', entry.reset);\n videoFrames.delete(entry.video);\n }\n function releaseVideoFrames() {\n if (videoFrames) videoFrames.forEach(releaseVideoFrame);\n }\n function decodedVideoFrames(video) {\n if (typeof video.webkitDecodedFrameCount === 'number') {\n return video.webkitDecodedFrameCount;\n }\n if (typeof video.getVideoPlaybackQuality === 'function') {\n var quality = video.getVideoPlaybackQuality();\n return quality.totalVideoFrames - quality.droppedVideoFrames;\n }\n return 0;\n }\n function strictVideoFrameReady(video) {\n if (video.error) {\n throw new Error('Video frame failed for ' + videoSource(video) +\n ' (media error ' + video.error.code + '): ' + (video.error.message || 'media unavailable'));\n }\n var entry = videoFrames.get(video);\n var source = frameSource(video);\n if (entry && entry.source !== source) {\n releaseVideoFrame(entry);\n entry = null;\n }\n if (video.seeking) {\n if (entry) resetVideoFrame(entry);\n return false;\n }\n // Do not start media the author deliberately left unplayed. A\n // decoded poster is valid evidence only while it is the intended\n // still surface, never as a substitute for an autoplay/seek frame.\n if (video.preload === 'none' && video.paused && !video.autoplay &&\n video.currentTime === 0 && video.played.length === 0 && video.poster) {\n if (entry) releaseVideoFrame(entry);\n return videoPosterDecoded(video);\n }\n if (video.readyState < 2 /* HAVE_CURRENT_DATA */) {\n if (entry) resetVideoFrame(entry);\n return false;\n }\n if (entry && entry.presented) return true;\n // A paused video may decode its first frame without delivering a\n // pending presentation callback. The callback wakes suspended startup;\n // decoded-frame evidence independently satisfies readiness, including\n // when decoding races its registration. readyState and seeking still\n // gate both paths.\n if (decodedVideoFrames(video) > 0) {\n if (entry) releaseVideoFrame(entry);\n return true;\n }\n if (!entry) {\n entry = { video: video, source: source, callbackId: null,\n generation: 0, presented: false, reset: null };\n entry.reset = function() { resetVideoFrame(entry); };\n video.addEventListener('emptied', entry.reset);\n video.addEventListener('loadstart', entry.reset);\n video.addEventListener('seeking', entry.reset);\n videoFrames.set(video, entry);\n }\n if (entry.callbackId === null && typeof video.requestVideoFrameCallback === 'function') {\n var generation = entry.generation;\n // Chromium uses this request to resume suspended metadata startup,\n // even for media outside the viewport. It neither plays nor seeks.\n entry.callbackId = video.requestVideoFrameCallback(function() {\n if (entry.generation !== generation) return;\n entry.callbackId = null;\n entry.presented = !video.seeking && frameSource(video) === entry.source;\n });\n }\n return false;\n }\n function contentQuiet() {\n pendingStrictVideo = null;\n var target = document.querySelector(selector);\n if (!target) {\n releaseVideoFrames();\n return false;\n }\n var videos = waitForMedia ? renderedMatches(target, 'video') : [];\n if (strictVideoFrames) {\n videoFrames.forEach(function(entry) {\n if (videos.indexOf(entry.video) === -1) releaseVideoFrame(entry);\n });\n for (var v = 0; v < videos.length; v++) {\n if (!strictVideoFrameReady(videos[v]) && pendingStrictVideo === null) {\n pendingStrictVideo = 'Video frame not ready for ' + videoSource(videos[v]) +\n ' (readyState=' + videos[v].readyState + ', networkState=' + videos[v].networkState +\n ', seeking=' + videos[v].seeking + ', decodedFrames=' + decodedVideoFrames(videos[v]) +\n ', poster=' + (videos[v].poster || '(none)') + ')';\n }\n }\n if (pendingStrictVideo !== null) {\n quietKey = null;\n return false;\n }\n }\n var images = waitForMedia ? renderedImages(target) : [];\n for (var i = 0; i < images.length; i++) {\n if (images[i].loading === 'lazy') images[i].loading = 'eager';\n }\n for (var j = 0; j < images.length; j++) {\n if (!images[j].complete) {\n // Load/error handlers can replace content without moving its\n // geometry: start a fresh quiet window once they have run.\n quietKey = null;\n return false;\n }\n }\n // A loaded image can still paint as empty space until it decodes\n // (decoding="async" lets the browser paint first). Ask each source\n // to decode once; a failed decode counts as finished.\n var decoding = false;\n for (var d = 0; d < images.length; d++) {\n if (!imageDecoded(images[d])) decoding = true;\n }\n if (decoding) {\n quietKey = null;\n return false;\n }\n // Preserve the existing bounded wait for live screenshots. Strict\n // media readiness above cannot be bypassed by this cap.\n for (var w = 0; !strictVideoFrames && w < videos.length; w++) {\n if (!videoFrameReady(videos[w])) {\n if (videoWaitStartedAt === null) videoWaitStartedAt = now();\n if (now() - videoWaitStartedAt < videoWaitCapMs) {\n quietKey = null;\n return false;\n }\n break;\n }\n }\n var rect = target.getBoundingClientRect();\n var text = target.innerText || '';\n var key = [\n rect.x,\n rect.y,\n rect.width,\n rect.height,\n target.querySelectorAll('*').length,\n text.length,\n images.length\n ].join(',');\n var at = now();\n if (quietKey !== key) {\n quietKey = key;\n quietSince = at;\n return false;\n }\n return at - quietSince >= quietMs;\n }\n\n function paint() {\n if (!runPaint) return Promise.resolve();\n var started = now();\n return new Promise(function(resolve) {\n requestAnimationFrame(function() {\n requestAnimationFrame(function() {\n steps.paint = Math.round(now() - started);\n resolve();\n });\n });\n });\n }\n\n return until('target', function() {\n return document.querySelector(selector) !== null;\n }, stepTimeoutMs, false)\n .then(function() {\n return until('fonts', function() {\n var fonts = document.fonts;\n return !fonts || fonts.status === 'loaded';\n }, stepTimeoutMs, false);\n })\n .then(function() {\n return until('suspense', function() {\n if (!${mO}) return false;\n if (!pendingSelector) return true;\n var target = document.querySelector(selector);\n if (!target) return false;\n return !target.querySelector(pendingSelector);\n }, stepTimeoutMs, false);\n })\n .then(function() {\n return until('content-quiet', contentQuiet, quietTimeoutMs, quietBestEffort);\n })\n .then(paint)\n .then(\n function() {\n releaseVideoFrames();\n return { ok: true, steps: steps, quiet: quiet };\n },\n function(caught) {\n releaseVideoFrames();\n if (caught && caught.ok === false) return caught;\n return failure('paint', String((caught && caught.message) || caught));\n }\n );\n })()\n `}var fO="11",gO="system-1",yO=1;function buildEnvFingerprint(e){const t={os:e.os,browser:`chromium-${e.browserVersion}`,dpr:yO,fontsBundleVersion:gO,kitVersion:fO};return{fingerprint:[t.os,t.browser,`dpr${t.dpr}`,`fonts-${t.fontsBundleVersion}`,`kit-${t.kitVersion}`].join("/"),parts:t}}function isNavigationInterruptedError(e){return/Execution context was destroyed|most likely because of a navigation|Cannot find context with specified id|[Ff]rame was detached|Navigation interrupted|is interrupted by another navigation|Inspected target navigated or closed|Cannot find object with id|context was destroyed/.test(e)}var bO=["--force-color-profile=srgb",`--force-device-scale-factor=${yO}`,"--hide-scrollbars","--disable-lcd-text","--disable-partial-raster"];async function alignCaptureFonts(e){await e.send("Page.setFontFamilies",{fontFamilies:{standard:"Times New Roman",fixed:"darwin"===process.platform?"Menlo":"Courier New",serif:"Times New Roman",sansSerif:"Arial",cursive:"Script",fantasy:"Impact",math:"Latin Modern Math"}})}async function alignCaptureSubframeFonts(e){let t=!1;for(const n of e.frames()){if(n===e.mainFrame())continue;let r;try{r=await e.context().newCDPSession(n)}catch(e){if(e instanceof Error&&e.message.includes("does not have a separate CDP session"))continue;throw e}try{await alignCaptureFonts(r),t=!0}finally{await r.detach()}}return t}async function settlePage(e,t,n={}){const r=n.quietMs??300,s=n.timeoutMs??15e3,i=s*lO.length,o=Date.now()+i;let a=0;for(;;){let c;try{c=await e.evaluate(buildSettleWaitScript({selector:t,pendingSelector:KN,quietMs:r,strictVideoFrames:!0,stepTimeoutMs:Math.max(1,Math.min(s,o-Date.now()))}))}catch(e){const t=e instanceof Error?e.message:String(e);if(!isNavigationInterruptedError(t))throw e;if(a+=1,Date.now()>=o)throw new Error(`settle: Timeout ${i}ms exceeded; the document was replaced ${a} times while waiting`);continue}for(const e of lO){const t=c.steps[e];void 0!==t&&n.onStep?.(e,t)}if(!c.ok)throw new Error(`settle.${c.step}: ${c.message}`);return}}import{spawn as vO}from"child_process";import{createRequire as wO}from"module";import _O from"path";var xO=48e4;function isMissingBrowserError(e){const t=e instanceof Error?e.message:String(e);return t.includes("Executable doesn't exist")||/playwright install(?!-deps)/.test(t)}function autoInstallDisabled(){return"1"===process.env.TEMPO_MCP_NO_AUTO_INSTALL}async function installChromium(e,t=vO){const n=wO(import.meta.url),r=_O.join(_O.dirname(n.resolve("playwright/package.json")),"cli.js");await new Promise((n,s)=>{const i=t(process.execPath,[r,"install","chromium"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});let o="";const collect=e=>{o=(o+String(e)).slice(-2e3)};i.stdout?.on("data",collect),i.stderr?.on("data",collect);const a=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`Chromium download timed out after ${xO/6e4} minutes. Run \`npx playwright install chromium\` manually.`))},xO);i.on("error",e=>{clearTimeout(a),s(e)}),i.on("exit",t=>{clearTimeout(a),0===t?(e("Chromium installed."),n()):s(new Error(`playwright install chromium exited with ${t}: ${o.trim().slice(-500)}`))})})}var escapeHtml=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),TO="<style>html{width:100%;height:100%;}</style>";function serializeAttributes(e,t=!1){return Object.entries(e).filter(([e])=>t||"style"!==e).map(([e,t])=>` ${e}="${escapeHtml(t)}"`).join("")}function buildBodyStyle(e){const t=(e??"").split(";").map(e=>e.trim()).filter(e=>{const t=e.indexOf(":");if(t<=0)return!1;const n=e.slice(0,t).trim().toLowerCase();return"width"!==n&&"height"!==n});return t.push("width: 100%","height: 100%","margin: 0"),`${t.join("; ")};`}function buildStoryboardHtmlDocument(e,t){const n=t.title?`<title>${escapeHtml(t.title)}</title>`:"",r=/<base[\s>]/i.test(e.headHtml)?"":`<base href="${escapeHtml(t.baseUrl)}">`;return["<!DOCTYPE html>",`<html${serializeAttributes(e.htmlAttributes,t.preserveBody)}>`,"<head>",'<meta charset="utf-8">',n,r,t.preserveBody?"":TO,e.headHtml,"</head>",t.preserveBody?e.elementHtml:`<body${serializeAttributes(e.bodyAttributes)} style="${escapeHtml(buildBodyStyle(e.bodyAttributes.style))}">`,t.preserveBody?"":e.elementHtml,t.preserveBody?"":"</body>","</html>"].join("")}import{randomBytes as kO}from"crypto";import{readFile as SO,stat as EO}from"fs/promises";import AO from"path";import{createHash as CO}from"crypto";import{createRequire as IO}from"module";var PO=25165824,DO=67108864,RO=33554432,NO=IO(import.meta.url),OO,loadSharp=()=>OO??=NO("sharp");function createCaptureImageNormalizer(){const e=new Map;let t=0;return async n=>{if(255!==n[0]||216!==n[1]||255!==n[2])return n;if(n.length>PO)throw new Error("capture JPEG exceeds the 24 MiB input limit");const r=CO("sha256").update(n).digest("hex"),s=e.get(r);if(s)return e.delete(r),e.set(r,s),s;const i=loadSharp(),o=await i(n,{limitInputPixels:DO}).keepExif().png().toBuffer();if(e.has(r))return e.get(r);if(o.length<=RO){for(;t+o.length>RO;){const n=e.keys().next().value;t-=e.get(n).length,e.delete(n)}e.set(r,o),t+=o.length}return o}}async function installCaptureImages(e,t,n={}){const r=await e.context().newCDPSession(e),s=new Map,i=new Set,o=new Map;let a=!1;const handle=async e=>{const{requestId:n,networkId:i,request:c,responseStatusCode:l,responseHeaders:d=[]}=e,u={canceled:!1};i&&o.set(i,u);try{const e=d.find(e=>"content-type"===e.name.toLowerCase())?.value.split(";",1)[0].trim().toLowerCase(),s="image/jpeg"===e||"image/jpg"===e||"application/octet-stream"===e||!e;if(200!==l||!s)return void await r.send("Fetch.continueRequest",{requestId:n});const i=Number(d.find(e=>"content-length"===e.name.toLowerCase())?.value);if(i>PO)throw new Error("capture image exceeds the 24 MiB input limit");let o;const a=await Promise.race([r.send("Fetch.getResponseBody",{requestId:n}),new Promise((e,t)=>{o=setTimeout(()=>t(new Error("capture image download exceeded 30 seconds")),3e4)}),new Promise((e,t)=>{u.cancelBody=()=>t(new Error("capture image request was canceled")),u.canceled&&u.cancelBody()})]).finally(()=>{clearTimeout(o),u.cancelBody=void 0}),c=Buffer.from(a.body,a.base64Encoded?"base64":"utf8"),p=await t(c);if(p===c)return void await r.send("Fetch.continueRequest",{requestId:n});const m=new Set(["content-type","content-encoding","content-length","etag","content-md5","digest","content-digest","repr-digest"]),f=d.filter(e=>!m.has(e.name.toLowerCase()));f.push({name:"Content-Type",value:"image/png"}),await r.send("Fetch.fulfillRequest",{requestId:n,responseCode:l,responseHeaders:f,body:p.toString("base64")})}catch(e){a||u.canceled||s.set(c.url,String(e)),await r.send("Fetch.failRequest",{requestId:n,errorReason:"Failed"}).catch(()=>{})}finally{i&&o.get(i)===u&&o.delete(i)}};return r.on("Network.loadingFailed",e=>{if(!e.canceled)return;const t=o.get(e.requestId);t&&(t.canceled=!0,t.cancelBody?.())}),r.on("Fetch.requestPaused",e=>{const t=handle(e);i.add(t),t.finally(()=>i.delete(t)).catch(()=>{})}),await r.send("Network.enable"),n.requestLatencyMs&&await r.send("Network.emulateNetworkConditions",{offline:!1,latency:n.requestLatencyMs,downloadThroughput:-1,uploadThroughput:-1}),await r.send("Fetch.enable",{patterns:[{resourceType:"Image",requestStage:"Response"}]}),{assertHealthy(){if(s.size)throw new Error(`capture image normalization failed: ${[...s].map(([e,t])=>`${e}: ${t}`).join("; ")}`)},async forgetLoadedImages(){await r.send("Network.setCacheDisabled",{cacheDisabled:!0}),await r.send("Network.setCacheDisabled",{cacheDisabled:!1})},async dispose(){a=!0,await r.send("Fetch.disable").catch(()=>{}),await r.detach().catch(()=>{}),await Promise.allSettled([...i])}}}import FO from"path";import{realpath as LO,stat as MO}from"fs/promises";import UO from"oxc-parser/src-js/generated/visit/keys.js";var jO=UO,BO=jO.default??jO;import{parseSync as $O}from"oxc-parser";function sourceVersionHash(e){let t=5381,n=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)+t^s,n=s+(n<<6)+(n<<16)-n|0}return toHex8(t)+toHex8(n)}function toHex8(e){return(e>>>0).toString(16).padStart(8,"0")}var WO={Top:1,Function:2,Block:4,Catch:8,Class:16,For:32,Switch:64,Module:128,StrictMode:256,ClassStaticBlock:512,TsModuleBlock:1024,TsConditional:2048,Type:4096,Enum:8192};import{parseSync as HO}from"oxc-parser";var qO=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),zO="�",GO;!function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"}(GO||(GO={}));var VO={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"},KO;function isSurrogate(e){return e>=55296&&e<=57343}function isSurrogatePair(e){return e>=56320&&e<=57343}function getSurrogatePairCodePoint(e,t){return 1024*(e-55296)+9216+t}function isControlCodePoint(e){return 32!==e&&10!==e&&13!==e&&9!==e&&12!==e&&e>=1&&e<=31||e>=127&&e<=159}function isUndefinedCodePoint(e){return e>=64976&&e<=65007||qO.has(e)}!function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"}(KO||(KO={}));var XO=65536,YO=class{constructor(e){this.handler=e,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=XO,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+Number(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(e,t){const{line:n,col:r,offset:s}=this,i=r+t,o=s+t;return{code:e,startLine:n,endLine:n,startCol:i,endCol:i,startOffset:o,endOffset:o}}_err(e){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(e,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(e){if(this.pos!==this.html.length-1){const t=this.html.charCodeAt(this.pos+1);if(isSurrogatePair(t))return this.pos++,this._addGap(),getSurrogatePairCodePoint(e,t)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,GO.EOF;return this._err(KO.surrogateInInputStream),e}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(e,t){this.html.length>0?this.html+=e:this.html=e,this.endOfChunkHit=!1,this.lastChunkWritten=t}insertHtmlAtCurrentPos(e){this.html=this.html.substring(0,this.pos+1)+e+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(e,t){if(this.pos+e.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(t)return this.html.startsWith(e,this.pos);for(let t=0;t<e.length;t++){const n=32|this.html.charCodeAt(this.pos+t);if(n!==e.charCodeAt(t))return!1}return!0}peek(e){const t=this.pos+e;if(t>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,GO.EOF;const n=this.html.charCodeAt(t);return n===GO.CARRIAGE_RETURN?GO.LINE_FEED:n}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,GO.EOF;let e=this.html.charCodeAt(this.pos);if(e===GO.CARRIAGE_RETURN)return this.isEol=!0,this.skipNextNewLine=!0,GO.LINE_FEED;if(e===GO.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine))return this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance();this.skipNextNewLine=!1,isSurrogate(e)&&(e=this._processSurrogate(e));const t=null===this.handler.onParseError||e>31&&e<127||e===GO.LINE_FEED||e===GO.CARRIAGE_RETURN||e>159&&e<64976;return t||this._checkForProblematicCharacters(e),e}_checkForProblematicCharacters(e){isControlCodePoint(e)?this._err(KO.controlCharacterInInputStream):isUndefinedCodePoint(e)&&this._err(KO.noncharacterInInputStream)}retreat(e){for(this.pos-=e;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}},JO;function getTokenAttr(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}!function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"}(JO||(JO={}));var QO=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),ZO,eF=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),tF=null!==(ZO=String.fromCodePoint)&&void 0!==ZO?ZO:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e),t},nF;function replaceCodePoint(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=eF.get(e))&&void 0!==t?t:e}!function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"}(nF||(nF={}));var rF=32,sF,iF,oF;function isNumber(e){return e>=nF.ZERO&&e<=nF.NINE}function isHexadecimalCharacter(e){return e>=nF.UPPER_A&&e<=nF.UPPER_F||e>=nF.LOWER_A&&e<=nF.LOWER_F}function isAsciiAlphaNumeric(e){return e>=nF.UPPER_A&&e<=nF.UPPER_Z||e>=nF.LOWER_A&&e<=nF.LOWER_Z||isNumber(e)}function isEntityInAttributeInvalidEnd(e){return e===nF.EQUALS||isAsciiAlphaNumeric(e)}!function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"}(sF||(sF={})),function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"}(iF||(iF={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}(oF||(oF={}));var aF=class{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=iF.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=oF.Strict}startEntity(e){this.decodeMode=e,this.state=iF.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case iF.EntityStart:return e.charCodeAt(t)===nF.NUM?(this.state=iF.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=iF.NamedEntity,this.stateNamedEntity(e,t));case iF.NumericStart:return this.stateNumericStart(e,t);case iF.NumericDecimal:return this.stateNumericDecimal(e,t);case iF.NumericHex:return this.stateNumericHex(e,t);case iF.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(e.charCodeAt(t)|rF)===nF.LOWER_X?(this.state=iF.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=iF.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,r){if(t!==n){const s=n-t;this.result=this.result*Math.pow(r,s)+Number.parseInt(e.substr(t,s),r),this.consumed+=s}}stateNumericHex(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!isNumber(r)&&!isHexadecimalCharacter(r))return this.addToNumericResult(e,n,t,16),this.emitNumericEntity(r,3);t+=1}return this.addToNumericResult(e,n,t,16),-1}stateNumericDecimal(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!isNumber(r))return this.addToNumericResult(e,n,t,10),this.emitNumericEntity(r,2);t+=1}return this.addToNumericResult(e,n,t,10),-1}emitNumericEntity(e,t){var n;if(this.consumed<=t)return null===(n=this.errors)||void 0===n||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===nF.SEMI)this.consumed+=1;else if(this.decodeMode===oF.Strict)return 0;return this.emitCodePoint(replaceCodePoint(this.result),this.consumed),this.errors&&(e!==nF.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:n}=this;let r=n[this.treeIndex],s=(r&sF.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const i=e.charCodeAt(t);if(this.treeIndex=determineBranch(n,r,this.treeIndex+Math.max(1,s),i),this.treeIndex<0)return 0===this.result||this.decodeMode===oF.Attribute&&(0===s||isEntityInAttributeInvalidEnd(i))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],s=(r&sF.VALUE_LENGTH)>>14,0!==s){if(i===nF.SEMI)return this.emitNamedEntityData(this.treeIndex,s,this.consumed+this.excess);this.decodeMode!==oF.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,r=(n[t]&sF.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,r,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,n){const{decodeTree:r}=this;return this.emitCodePoint(1===t?r[e]&~sF.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n}end(){var e;switch(this.state){case iF.NamedEntity:return 0===this.result||this.decodeMode===oF.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case iF.NumericDecimal:return this.emitNumericEntity(0,2);case iF.NumericHex:return this.emitNumericEntity(0,3);case iF.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case iF.EntityStart:return 0}}},cF,lF,dF,uF,pF;function determineBranch(e,t,n,r){const s=(t&sF.BRANCH_LENGTH)>>7,i=t&sF.JUMP_TABLE;if(0===s)return 0!==i&&r===i?n:-1;if(i){const t=r-i;return t<0||t>=s?-1:e[n+t]-1}let o=n,a=o+s-1;for(;o<=a;){const t=o+a>>>1,n=e[t];if(n<r)o=t+1;else{if(!(n>r))return e[t+s];a=t-1}}return-1}!function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"}(cF||(cF={})),function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"}(lF||(lF={})),function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"}(dF||(dF={})),function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"}(uF||(uF={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"}(pF||(pF={}));var hF=new Map([[uF.A,pF.A],[uF.ADDRESS,pF.ADDRESS],[uF.ANNOTATION_XML,pF.ANNOTATION_XML],[uF.APPLET,pF.APPLET],[uF.AREA,pF.AREA],[uF.ARTICLE,pF.ARTICLE],[uF.ASIDE,pF.ASIDE],[uF.B,pF.B],[uF.BASE,pF.BASE],[uF.BASEFONT,pF.BASEFONT],[uF.BGSOUND,pF.BGSOUND],[uF.BIG,pF.BIG],[uF.BLOCKQUOTE,pF.BLOCKQUOTE],[uF.BODY,pF.BODY],[uF.BR,pF.BR],[uF.BUTTON,pF.BUTTON],[uF.CAPTION,pF.CAPTION],[uF.CENTER,pF.CENTER],[uF.CODE,pF.CODE],[uF.COL,pF.COL],[uF.COLGROUP,pF.COLGROUP],[uF.DD,pF.DD],[uF.DESC,pF.DESC],[uF.DETAILS,pF.DETAILS],[uF.DIALOG,pF.DIALOG],[uF.DIR,pF.DIR],[uF.DIV,pF.DIV],[uF.DL,pF.DL],[uF.DT,pF.DT],[uF.EM,pF.EM],[uF.EMBED,pF.EMBED],[uF.FIELDSET,pF.FIELDSET],[uF.FIGCAPTION,pF.FIGCAPTION],[uF.FIGURE,pF.FIGURE],[uF.FONT,pF.FONT],[uF.FOOTER,pF.FOOTER],[uF.FOREIGN_OBJECT,pF.FOREIGN_OBJECT],[uF.FORM,pF.FORM],[uF.FRAME,pF.FRAME],[uF.FRAMESET,pF.FRAMESET],[uF.H1,pF.H1],[uF.H2,pF.H2],[uF.H3,pF.H3],[uF.H4,pF.H4],[uF.H5,pF.H5],[uF.H6,pF.H6],[uF.HEAD,pF.HEAD],[uF.HEADER,pF.HEADER],[uF.HGROUP,pF.HGROUP],[uF.HR,pF.HR],[uF.HTML,pF.HTML],[uF.I,pF.I],[uF.IMG,pF.IMG],[uF.IMAGE,pF.IMAGE],[uF.INPUT,pF.INPUT],[uF.IFRAME,pF.IFRAME],[uF.KEYGEN,pF.KEYGEN],[uF.LABEL,pF.LABEL],[uF.LI,pF.LI],[uF.LINK,pF.LINK],[uF.LISTING,pF.LISTING],[uF.MAIN,pF.MAIN],[uF.MALIGNMARK,pF.MALIGNMARK],[uF.MARQUEE,pF.MARQUEE],[uF.MATH,pF.MATH],[uF.MENU,pF.MENU],[uF.META,pF.META],[uF.MGLYPH,pF.MGLYPH],[uF.MI,pF.MI],[uF.MO,pF.MO],[uF.MN,pF.MN],[uF.MS,pF.MS],[uF.MTEXT,pF.MTEXT],[uF.NAV,pF.NAV],[uF.NOBR,pF.NOBR],[uF.NOFRAMES,pF.NOFRAMES],[uF.NOEMBED,pF.NOEMBED],[uF.NOSCRIPT,pF.NOSCRIPT],[uF.OBJECT,pF.OBJECT],[uF.OL,pF.OL],[uF.OPTGROUP,pF.OPTGROUP],[uF.OPTION,pF.OPTION],[uF.P,pF.P],[uF.PARAM,pF.PARAM],[uF.PLAINTEXT,pF.PLAINTEXT],[uF.PRE,pF.PRE],[uF.RB,pF.RB],[uF.RP,pF.RP],[uF.RT,pF.RT],[uF.RTC,pF.RTC],[uF.RUBY,pF.RUBY],[uF.S,pF.S],[uF.SCRIPT,pF.SCRIPT],[uF.SEARCH,pF.SEARCH],[uF.SECTION,pF.SECTION],[uF.SELECT,pF.SELECT],[uF.SOURCE,pF.SOURCE],[uF.SMALL,pF.SMALL],[uF.SPAN,pF.SPAN],[uF.STRIKE,pF.STRIKE],[uF.STRONG,pF.STRONG],[uF.STYLE,pF.STYLE],[uF.SUB,pF.SUB],[uF.SUMMARY,pF.SUMMARY],[uF.SUP,pF.SUP],[uF.TABLE,pF.TABLE],[uF.TBODY,pF.TBODY],[uF.TEMPLATE,pF.TEMPLATE],[uF.TEXTAREA,pF.TEXTAREA],[uF.TFOOT,pF.TFOOT],[uF.TD,pF.TD],[uF.TH,pF.TH],[uF.THEAD,pF.THEAD],[uF.TITLE,pF.TITLE],[uF.TR,pF.TR],[uF.TRACK,pF.TRACK],[uF.TT,pF.TT],[uF.U,pF.U],[uF.UL,pF.UL],[uF.SVG,pF.SVG],[uF.VAR,pF.VAR],[uF.WBR,pF.WBR],[uF.XMP,pF.XMP]]);function getTagID(e){var t;return null!==(t=hF.get(e))&&void 0!==t?t:pF.UNKNOWN}var mF=pF,fF={[cF.HTML]:new Set([mF.ADDRESS,mF.APPLET,mF.AREA,mF.ARTICLE,mF.ASIDE,mF.BASE,mF.BASEFONT,mF.BGSOUND,mF.BLOCKQUOTE,mF.BODY,mF.BR,mF.BUTTON,mF.CAPTION,mF.CENTER,mF.COL,mF.COLGROUP,mF.DD,mF.DETAILS,mF.DIR,mF.DIV,mF.DL,mF.DT,mF.EMBED,mF.FIELDSET,mF.FIGCAPTION,mF.FIGURE,mF.FOOTER,mF.FORM,mF.FRAME,mF.FRAMESET,mF.H1,mF.H2,mF.H3,mF.H4,mF.H5,mF.H6,mF.HEAD,mF.HEADER,mF.HGROUP,mF.HR,mF.HTML,mF.IFRAME,mF.IMG,mF.INPUT,mF.LI,mF.LINK,mF.LISTING,mF.MAIN,mF.MARQUEE,mF.MENU,mF.META,mF.NAV,mF.NOEMBED,mF.NOFRAMES,mF.NOSCRIPT,mF.OBJECT,mF.OL,mF.P,mF.PARAM,mF.PLAINTEXT,mF.PRE,mF.SCRIPT,mF.SECTION,mF.SELECT,mF.SOURCE,mF.STYLE,mF.SUMMARY,mF.TABLE,mF.TBODY,mF.TD,mF.TEMPLATE,mF.TEXTAREA,mF.TFOOT,mF.TH,mF.THEAD,mF.TITLE,mF.TR,mF.TRACK,mF.UL,mF.WBR,mF.XMP]),[cF.MATHML]:new Set([mF.MI,mF.MO,mF.MN,mF.MS,mF.MTEXT,mF.ANNOTATION_XML]),[cF.SVG]:new Set([mF.TITLE,mF.FOREIGN_OBJECT,mF.DESC]),[cF.XLINK]:new Set,[cF.XML]:new Set,[cF.XMLNS]:new Set},gF=new Set([mF.H1,mF.H2,mF.H3,mF.H4,mF.H5,mF.H6]),yF=new Set([uF.STYLE,uF.SCRIPT,uF.XMP,uF.IFRAME,uF.NOEMBED,uF.NOFRAMES,uF.PLAINTEXT]),bF;!function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"}(bF||(bF={}));var vF={DATA:bF.DATA,RCDATA:bF.RCDATA,RAWTEXT:bF.RAWTEXT,SCRIPT_DATA:bF.SCRIPT_DATA,PLAINTEXT:bF.PLAINTEXT,CDATA_SECTION:bF.CDATA_SECTION};function isAsciiDigit(e){return e>=GO.DIGIT_0&&e<=GO.DIGIT_9}function isAsciiUpper(e){return e>=GO.LATIN_CAPITAL_A&&e<=GO.LATIN_CAPITAL_Z}function isAsciiLower(e){return e>=GO.LATIN_SMALL_A&&e<=GO.LATIN_SMALL_Z}function isAsciiLetter(e){return isAsciiLower(e)||isAsciiUpper(e)}function isAsciiAlphaNumeric2(e){return isAsciiLetter(e)||isAsciiDigit(e)}function toAsciiLower(e){return e+32}function isWhitespace(e){return e===GO.SPACE||e===GO.LINE_FEED||e===GO.TABULATION||e===GO.FORM_FEED}function isScriptDataDoubleEscapeSequenceEnd(e){return isWhitespace(e)||e===GO.SOLIDUS||e===GO.GREATER_THAN_SIGN}function getErrorForNumericCharacterReference(e){return e===GO.NULL?KO.nullCharacterReference:e>1114111?KO.characterReferenceOutsideUnicodeRange:isSurrogate(e)?KO.surrogateCharacterReference:isUndefinedCodePoint(e)?KO.noncharacterCharacterReference:isControlCodePoint(e)||e===GO.CARRIAGE_RETURN?KO.controlCharacterReference:null}var wF=class{constructor(e,t){this.options=e,this.handler=t,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=bF.DATA,this.returnState=bF.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new YO(t),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new aF(QO,(e,t)=>{this.preprocessor.pos=this.entityStartPos+t-1,this._flushCodePointConsumedAsCharacterReference(e)},t.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(KO.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:e=>{this._err(KO.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+e)},validateNumericCharacterReference:e=>{const t=getErrorForNumericCharacterReference(e);t&&this._err(t,1)}}:void 0)}_err(e,t=0){var n,r;null===(r=(n=this.handler).onParseError)||void 0===r||r.call(n,this.preprocessor.getError(e,t))}getCurrentLocation(e){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-e,startOffset:this.preprocessor.offset-e,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const e=this._consume();this._ensureHibernation()||this._callState(e)}this.inLoop=!1}}pause(){this.paused=!0}resume(e){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,this.inLoop||(this._runParsingLoop(),this.paused||null==e||e())}write(e,t,n){this.active=!0,this.preprocessor.write(e,t),this._runParsingLoop(),this.paused||null==n||n()}insertHtmlAtCurrentPos(e){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(e),this._runParsingLoop()}_ensureHibernation(){return!!this.preprocessor.endOfChunkHit&&(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0)}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(e){this.consumedAfterSnapshot+=e;for(let t=0;t<e;t++)this.preprocessor.advance()}_consumeSequenceIfMatch(e,t){return!!this.preprocessor.startsWith(e,t)&&(this._advanceBy(e.length-1),!0)}_createStartTagToken(){this.currentToken={type:JO.START_TAG,tagName:"",tagID:pF.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:JO.END_TAG,tagName:"",tagID:pF.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(e){this.currentToken={type:JO.COMMENT,data:"",location:this.getCurrentLocation(e)}}_createDoctypeToken(e){this.currentToken={type:JO.DOCTYPE,name:e,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(e,t){this.currentCharacterToken={type:e,chars:t,location:this.currentLocation}}_createAttr(e){this.currentAttr={name:e,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var e,t;const n=this.currentToken;if(null===getTokenAttr(n,this.currentAttr.name)){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){const r=null!==(e=(t=n.location).attrs)&&void 0!==e?e:t.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(KO.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(e){this._emitCurrentCharacterToken(e.location),this.currentToken=null,e.location&&(e.location.endLine=this.preprocessor.line,e.location.endCol=this.preprocessor.col+1,e.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const e=this.currentToken;this.prepareToken(e),e.tagID=getTagID(e.tagName),e.type===JO.START_TAG?(this.lastStartTagName=e.tagName,this.handler.onStartTag(e)):(e.attrs.length>0&&this._err(KO.endTagWithAttributes),e.selfClosing&&this._err(KO.endTagWithTrailingSolidus),this.handler.onEndTag(e)),this.preprocessor.dropParsedChunk()}emitCurrentComment(e){this.prepareToken(e),this.handler.onComment(e),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(e){this.prepareToken(e),this.handler.onDoctype(e),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(e){if(this.currentCharacterToken){switch(e&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=e.startLine,this.currentCharacterToken.location.endCol=e.startCol,this.currentCharacterToken.location.endOffset=e.startOffset),this.currentCharacterToken.type){case JO.CHARACTER:this.handler.onCharacter(this.currentCharacterToken);break;case JO.NULL_CHARACTER:this.handler.onNullCharacter(this.currentCharacterToken);break;case JO.WHITESPACE_CHARACTER:this.handler.onWhitespaceCharacter(this.currentCharacterToken)}this.currentCharacterToken=null}}_emitEOFToken(){const e=this.getCurrentLocation(0);e&&(e.endLine=e.startLine,e.endCol=e.startCol,e.endOffset=e.startOffset),this._emitCurrentCharacterToken(e),this.handler.onEof({type:JO.EOF,location:e}),this.active=!1}_appendCharToCurrentCharacterToken(e,t){if(this.currentCharacterToken){if(this.currentCharacterToken.type===e)return void(this.currentCharacterToken.chars+=t);this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk()}this._createCharacterToken(e,t)}_emitCodePoint(e){const t=isWhitespace(e)?JO.WHITESPACE_CHARACTER:e===GO.NULL?JO.NULL_CHARACTER:JO.CHARACTER;this._appendCharToCurrentCharacterToken(t,String.fromCodePoint(e))}_emitChars(e){this._appendCharToCurrentCharacterToken(JO.CHARACTER,e)}_startCharacterReference(){this.returnState=this.state,this.state=bF.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?oF.Attribute:oF.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===bF.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===bF.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===bF.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(e){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(e):this._emitCodePoint(e)}_callState(e){switch(this.state){case bF.DATA:this._stateData(e);break;case bF.RCDATA:this._stateRcdata(e);break;case bF.RAWTEXT:this._stateRawtext(e);break;case bF.SCRIPT_DATA:this._stateScriptData(e);break;case bF.PLAINTEXT:this._statePlaintext(e);break;case bF.TAG_OPEN:this._stateTagOpen(e);break;case bF.END_TAG_OPEN:this._stateEndTagOpen(e);break;case bF.TAG_NAME:this._stateTagName(e);break;case bF.RCDATA_LESS_THAN_SIGN:this._stateRcdataLessThanSign(e);break;case bF.RCDATA_END_TAG_OPEN:this._stateRcdataEndTagOpen(e);break;case bF.RCDATA_END_TAG_NAME:this._stateRcdataEndTagName(e);break;case bF.RAWTEXT_LESS_THAN_SIGN:this._stateRawtextLessThanSign(e);break;case bF.RAWTEXT_END_TAG_OPEN:this._stateRawtextEndTagOpen(e);break;case bF.RAWTEXT_END_TAG_NAME:this._stateRawtextEndTagName(e);break;case bF.SCRIPT_DATA_LESS_THAN_SIGN:this._stateScriptDataLessThanSign(e);break;case bF.SCRIPT_DATA_END_TAG_OPEN:this._stateScriptDataEndTagOpen(e);break;case bF.SCRIPT_DATA_END_TAG_NAME:this._stateScriptDataEndTagName(e);break;case bF.SCRIPT_DATA_ESCAPE_START:this._stateScriptDataEscapeStart(e);break;case bF.SCRIPT_DATA_ESCAPE_START_DASH:this._stateScriptDataEscapeStartDash(e);break;case bF.SCRIPT_DATA_ESCAPED:this._stateScriptDataEscaped(e);break;case bF.SCRIPT_DATA_ESCAPED_DASH:this._stateScriptDataEscapedDash(e);break;case bF.SCRIPT_DATA_ESCAPED_DASH_DASH:this._stateScriptDataEscapedDashDash(e);break;case bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataEscapedLessThanSign(e);break;case bF.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:this._stateScriptDataEscapedEndTagOpen(e);break;case bF.SCRIPT_DATA_ESCAPED_END_TAG_NAME:this._stateScriptDataEscapedEndTagName(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPE_START:this._stateScriptDataDoubleEscapeStart(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED:this._stateScriptDataDoubleEscaped(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:this._stateScriptDataDoubleEscapedDash(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:this._stateScriptDataDoubleEscapedDashDash(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataDoubleEscapedLessThanSign(e);break;case bF.SCRIPT_DATA_DOUBLE_ESCAPE_END:this._stateScriptDataDoubleEscapeEnd(e);break;case bF.BEFORE_ATTRIBUTE_NAME:this._stateBeforeAttributeName(e);break;case bF.ATTRIBUTE_NAME:this._stateAttributeName(e);break;case bF.AFTER_ATTRIBUTE_NAME:this._stateAfterAttributeName(e);break;case bF.BEFORE_ATTRIBUTE_VALUE:this._stateBeforeAttributeValue(e);break;case bF.ATTRIBUTE_VALUE_DOUBLE_QUOTED:this._stateAttributeValueDoubleQuoted(e);break;case bF.ATTRIBUTE_VALUE_SINGLE_QUOTED:this._stateAttributeValueSingleQuoted(e);break;case bF.ATTRIBUTE_VALUE_UNQUOTED:this._stateAttributeValueUnquoted(e);break;case bF.AFTER_ATTRIBUTE_VALUE_QUOTED:this._stateAfterAttributeValueQuoted(e);break;case bF.SELF_CLOSING_START_TAG:this._stateSelfClosingStartTag(e);break;case bF.BOGUS_COMMENT:this._stateBogusComment(e);break;case bF.MARKUP_DECLARATION_OPEN:this._stateMarkupDeclarationOpen(e);break;case bF.COMMENT_START:this._stateCommentStart(e);break;case bF.COMMENT_START_DASH:this._stateCommentStartDash(e);break;case bF.COMMENT:this._stateComment(e);break;case bF.COMMENT_LESS_THAN_SIGN:this._stateCommentLessThanSign(e);break;case bF.COMMENT_LESS_THAN_SIGN_BANG:this._stateCommentLessThanSignBang(e);break;case bF.COMMENT_LESS_THAN_SIGN_BANG_DASH:this._stateCommentLessThanSignBangDash(e);break;case bF.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:this._stateCommentLessThanSignBangDashDash(e);break;case bF.COMMENT_END_DASH:this._stateCommentEndDash(e);break;case bF.COMMENT_END:this._stateCommentEnd(e);break;case bF.COMMENT_END_BANG:this._stateCommentEndBang(e);break;case bF.DOCTYPE:this._stateDoctype(e);break;case bF.BEFORE_DOCTYPE_NAME:this._stateBeforeDoctypeName(e);break;case bF.DOCTYPE_NAME:this._stateDoctypeName(e);break;case bF.AFTER_DOCTYPE_NAME:this._stateAfterDoctypeName(e);break;case bF.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._stateAfterDoctypePublicKeyword(e);break;case bF.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:this._stateBeforeDoctypePublicIdentifier(e);break;case bF.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypePublicIdentifierDoubleQuoted(e);break;case bF.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypePublicIdentifierSingleQuoted(e);break;case bF.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:this._stateAfterDoctypePublicIdentifier(e);break;case bF.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:this._stateBetweenDoctypePublicAndSystemIdentifiers(e);break;case bF.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._stateAfterDoctypeSystemKeyword(e);break;case bF.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:this._stateBeforeDoctypeSystemIdentifier(e);break;case bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypeSystemIdentifierDoubleQuoted(e);break;case bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypeSystemIdentifierSingleQuoted(e);break;case bF.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:this._stateAfterDoctypeSystemIdentifier(e);break;case bF.BOGUS_DOCTYPE:this._stateBogusDoctype(e);break;case bF.CDATA_SECTION:this._stateCdataSection(e);break;case bF.CDATA_SECTION_BRACKET:this._stateCdataSectionBracket(e);break;case bF.CDATA_SECTION_END:this._stateCdataSectionEnd(e);break;case bF.CHARACTER_REFERENCE:this._stateCharacterReference();break;case bF.AMBIGUOUS_AMPERSAND:this._stateAmbiguousAmpersand(e);break;default:throw new Error("Unknown state")}}_stateData(e){switch(e){case GO.LESS_THAN_SIGN:this.state=bF.TAG_OPEN;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitCodePoint(e);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRcdata(e){switch(e){case GO.AMPERSAND:this._startCharacterReference();break;case GO.LESS_THAN_SIGN:this.state=bF.RCDATA_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRawtext(e){switch(e){case GO.LESS_THAN_SIGN:this.state=bF.RAWTEXT_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptData(e){switch(e){case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_statePlaintext(e){switch(e){case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateTagOpen(e){if(isAsciiLetter(e))this._createStartTagToken(),this.state=bF.TAG_NAME,this._stateTagName(e);else switch(e){case GO.EXCLAMATION_MARK:this.state=bF.MARKUP_DECLARATION_OPEN;break;case GO.SOLIDUS:this.state=bF.END_TAG_OPEN;break;case GO.QUESTION_MARK:this._err(KO.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=bF.BOGUS_COMMENT,this._stateBogusComment(e);break;case GO.EOF:this._err(KO.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break;default:this._err(KO.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=bF.DATA,this._stateData(e)}}_stateEndTagOpen(e){if(isAsciiLetter(e))this._createEndTagToken(),this.state=bF.TAG_NAME,this._stateTagName(e);else switch(e){case GO.GREATER_THAN_SIGN:this._err(KO.missingEndTagName),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break;default:this._err(KO.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=bF.BOGUS_COMMENT,this._stateBogusComment(e)}}_stateTagName(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_ATTRIBUTE_NAME;break;case GO.SOLIDUS:this.state=bF.SELF_CLOSING_START_TAG;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.tagName+=zO;break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:t.tagName+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateRcdataLessThanSign(e){e===GO.SOLIDUS?this.state=bF.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=bF.RCDATA,this._stateRcdata(e))}_stateRcdataEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(e)):(this._emitChars("</"),this.state=bF.RCDATA,this._stateRcdata(e))}handleSpecialEndTag(e){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const t=this.currentToken;t.tagName=this.lastStartTagName;const n=this.preprocessor.peek(this.lastStartTagName.length);switch(n){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=bF.BEFORE_ATTRIBUTE_NAME,!1;case GO.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=bF.SELF_CLOSING_START_TAG,!1;case GO.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=bF.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.RCDATA,this._stateRcdata(e))}_stateRawtextLessThanSign(e){e===GO.SOLIDUS?this.state=bF.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=bF.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(e)):(this._emitChars("</"),this.state=bF.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.RAWTEXT,this._stateRawtext(e))}_stateScriptDataLessThanSign(e){switch(e){case GO.SOLIDUS:this.state=bF.SCRIPT_DATA_END_TAG_OPEN;break;case GO.EXCLAMATION_MARK:this.state=bF.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break;default:this._emitChars("<"),this.state=bF.SCRIPT_DATA,this._stateScriptData(e)}}_stateScriptDataEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(e)):(this._emitChars("</"),this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStart(e){e===GO.HYPHEN_MINUS?(this.state=bF.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStartDash(e){e===GO.HYPHEN_MINUS?(this.state=bF.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=bF.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscaped(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataEscapedDash(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedDashDash(e){switch(e){case GO.HYPHEN_MINUS:this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case GO.GREATER_THAN_SIGN:this.state=bF.SCRIPT_DATA,this._emitChars(">");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedLessThanSign(e){e===GO.SOLIDUS?this.state=bF.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:isAsciiLetter(e)?(this._emitChars("<"),this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(e)):(this._emitChars("<"),this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagOpen(e){isAsciiLetter(e)?(this.state=bF.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(e)):(this._emitChars("</"),this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscapeStart(e){if(this.preprocessor.startsWith(VO.SCRIPT,!1)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(VO.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<VO.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=bF.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscaped(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDash(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDashDash(e){switch(e){case GO.HYPHEN_MINUS:this._emitChars("-");break;case GO.LESS_THAN_SIGN:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case GO.GREATER_THAN_SIGN:this.state=bF.SCRIPT_DATA,this._emitChars(">");break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(zO);break;case GO.EOF:this._err(KO.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedLessThanSign(e){e===GO.SOLIDUS?(this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateScriptDataDoubleEscapeEnd(e){if(this.preprocessor.startsWith(VO.SCRIPT,!1)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(VO.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<VO.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=bF.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=bF.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateBeforeAttributeName(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.SOLIDUS:case GO.GREATER_THAN_SIGN:case GO.EOF:this.state=bF.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case GO.EQUALS_SIGN:this._err(KO.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=bF.ATTRIBUTE_NAME;break;default:this._createAttr(""),this.state=bF.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateAttributeName(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:case GO.SOLIDUS:case GO.GREATER_THAN_SIGN:case GO.EOF:this._leaveAttrName(),this.state=bF.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case GO.EQUALS_SIGN:this._leaveAttrName(),this.state=bF.BEFORE_ATTRIBUTE_VALUE;break;case GO.QUOTATION_MARK:case GO.APOSTROPHE:case GO.LESS_THAN_SIGN:this._err(KO.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(e);break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.name+=zO;break;default:this.currentAttr.name+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateAfterAttributeName(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.SOLIDUS:this.state=bF.SELF_CLOSING_START_TAG;break;case GO.EQUALS_SIGN:this.state=bF.BEFORE_ATTRIBUTE_VALUE;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this._createAttr(""),this.state=bF.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateBeforeAttributeValue(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.QUOTATION_MARK:this.state=bF.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this.state=bF.ATTRIBUTE_VALUE_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingAttributeValue),this.state=bF.DATA,this.emitCurrentTagToken();break;default:this.state=bF.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(e)}}_stateAttributeValueDoubleQuoted(e){switch(e){case GO.QUOTATION_MARK:this.state=bF.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.value+=zO;break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueSingleQuoted(e){switch(e){case GO.APOSTROPHE:this.state=bF.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.value+=zO;break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueUnquoted(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this._leaveAttrValue(),this.state=bF.BEFORE_ATTRIBUTE_NAME;break;case GO.AMPERSAND:this._startCharacterReference();break;case GO.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this.currentAttr.value+=zO;break;case GO.QUOTATION_MARK:case GO.APOSTROPHE:case GO.LESS_THAN_SIGN:case GO.EQUALS_SIGN:case GO.GRAVE_ACCENT:this._err(KO.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(e);break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAfterAttributeValueQuoted(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this._leaveAttrValue(),this.state=bF.BEFORE_ATTRIBUTE_NAME;break;case GO.SOLIDUS:this._leaveAttrValue(),this.state=bF.SELF_CLOSING_START_TAG;break;case GO.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=bF.DATA,this.emitCurrentTagToken();break;case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this._err(KO.missingWhitespaceBetweenAttributes),this.state=bF.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateSelfClosingStartTag(e){switch(e){case GO.GREATER_THAN_SIGN:{const e=this.currentToken;e.selfClosing=!0,this.state=bF.DATA,this.emitCurrentTagToken();break}case GO.EOF:this._err(KO.eofInTag),this._emitEOFToken();break;default:this._err(KO.unexpectedSolidusInTag),this.state=bF.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateBogusComment(e){const t=this.currentToken;switch(e){case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EOF:this.emitCurrentComment(t),this._emitEOFToken();break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.data+=zO;break;default:t.data+=String.fromCodePoint(e)}}_stateMarkupDeclarationOpen(e){this._consumeSequenceIfMatch(VO.DASH_DASH,!0)?(this._createCommentToken(VO.DASH_DASH.length+1),this.state=bF.COMMENT_START):this._consumeSequenceIfMatch(VO.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(VO.DOCTYPE.length+1),this.state=bF.DOCTYPE):this._consumeSequenceIfMatch(VO.CDATA_START,!0)?this.inForeignNode?this.state=bF.CDATA_SECTION:(this._err(KO.cdataInHtmlContent),this._createCommentToken(VO.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=bF.BOGUS_COMMENT):this._ensureHibernation()||(this._err(KO.incorrectlyOpenedComment),this._createCommentToken(2),this.state=bF.BOGUS_COMMENT,this._stateBogusComment(e))}_stateCommentStart(e){switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_START_DASH;break;case GO.GREATER_THAN_SIGN:{this._err(KO.abruptClosingOfEmptyComment),this.state=bF.DATA;const e=this.currentToken;this.emitCurrentComment(e);break}default:this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentStartDash(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_END;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptClosingOfEmptyComment),this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="-",this.state=bF.COMMENT,this._stateComment(e)}}_stateComment(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_END_DASH;break;case GO.LESS_THAN_SIGN:t.data+="<",this.state=bF.COMMENT_LESS_THAN_SIGN;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.data+=zO;break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=String.fromCodePoint(e)}}_stateCommentLessThanSign(e){const t=this.currentToken;switch(e){case GO.EXCLAMATION_MARK:t.data+="!",this.state=bF.COMMENT_LESS_THAN_SIGN_BANG;break;case GO.LESS_THAN_SIGN:t.data+="<";break;default:this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentLessThanSignBang(e){e===GO.HYPHEN_MINUS?this.state=bF.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=bF.COMMENT,this._stateComment(e))}_stateCommentLessThanSignBangDash(e){e===GO.HYPHEN_MINUS?this.state=bF.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=bF.COMMENT_END_DASH,this._stateCommentEndDash(e))}_stateCommentLessThanSignBangDashDash(e){e!==GO.GREATER_THAN_SIGN&&e!==GO.EOF&&this._err(KO.nestedComment),this.state=bF.COMMENT_END,this._stateCommentEnd(e)}_stateCommentEndDash(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:this.state=bF.COMMENT_END;break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="-",this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentEnd(e){const t=this.currentToken;switch(e){case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EXCLAMATION_MARK:this.state=bF.COMMENT_END_BANG;break;case GO.HYPHEN_MINUS:t.data+="-";break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="--",this.state=bF.COMMENT,this._stateComment(e)}}_stateCommentEndBang(e){const t=this.currentToken;switch(e){case GO.HYPHEN_MINUS:t.data+="--!",this.state=bF.COMMENT_END_DASH;break;case GO.GREATER_THAN_SIGN:this._err(KO.incorrectlyClosedComment),this.state=bF.DATA,this.emitCurrentComment(t);break;case GO.EOF:this._err(KO.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="--!",this.state=bF.COMMENT,this._stateComment(e)}}_stateDoctype(e){switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_DOCTYPE_NAME;break;case GO.GREATER_THAN_SIGN:this.state=bF.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e);break;case GO.EOF:{this._err(KO.eofInDoctype),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._err(KO.missingWhitespaceBeforeDoctypeName),this.state=bF.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e)}}_stateBeforeDoctypeName(e){if(isAsciiUpper(e))this._createDoctypeToken(String.fromCharCode(toAsciiLower(e))),this.state=bF.DOCTYPE_NAME;else switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.NULL:this._err(KO.unexpectedNullCharacter),this._createDoctypeToken(zO),this.state=bF.DOCTYPE_NAME;break;case GO.GREATER_THAN_SIGN:{this._err(KO.missingDoctypeName),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this.state=bF.DATA;break}case GO.EOF:{this._err(KO.eofInDoctype),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(e)),this.state=bF.DOCTYPE_NAME}}_stateDoctypeName(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.AFTER_DOCTYPE_NAME;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.name+=zO;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.name+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateAfterDoctypeName(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._consumeSequenceIfMatch(VO.PUBLIC,!1)?this.state=bF.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(VO.SYSTEM,!1)?this.state=bF.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(KO.invalidCharacterSequenceAfterDoctypeName),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e))}}_stateAfterDoctypePublicKeyword(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break;case GO.QUOTATION_MARK:this._err(KO.missingWhitespaceAfterDoctypePublicKeyword),t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this._err(KO.missingWhitespaceAfterDoctypePublicKeyword),t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypePublicIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.QUOTATION_MARK:t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:t.publicId="",this.state=bF.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypePublicIdentifierDoubleQuoted(e){const t=this.currentToken;switch(e){case GO.QUOTATION_MARK:this.state=bF.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.publicId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateDoctypePublicIdentifierSingleQuoted(e){const t=this.currentToken;switch(e){case GO.APOSTROPHE:this.state=bF.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.publicId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateAfterDoctypePublicIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break;case GO.GREATER_THAN_SIGN:this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.QUOTATION_MARK:this._err(KO.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this._err(KO.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBetweenDoctypePublicAndSystemIdentifiers(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.QUOTATION_MARK:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateAfterDoctypeSystemKeyword(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:this.state=bF.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break;case GO.QUOTATION_MARK:this._err(KO.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:this._err(KO.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypeSystemIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.QUOTATION_MARK:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case GO.APOSTROPHE:t.systemId="",this.state=bF.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case GO.GREATER_THAN_SIGN:this._err(KO.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.DATA,this.emitCurrentDoctype(t);break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypeSystemIdentifierDoubleQuoted(e){const t=this.currentToken;switch(e){case GO.QUOTATION_MARK:this.state=bF.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.systemId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateDoctypeSystemIdentifierSingleQuoted(e){const t=this.currentToken;switch(e){case GO.APOSTROPHE:this.state=bF.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case GO.NULL:this._err(KO.unexpectedNullCharacter),t.systemId+=zO;break;case GO.GREATER_THAN_SIGN:this._err(KO.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateAfterDoctypeSystemIdentifier(e){const t=this.currentToken;switch(e){case GO.SPACE:case GO.LINE_FEED:case GO.TABULATION:case GO.FORM_FEED:break;case GO.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.EOF:this._err(KO.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(KO.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=bF.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBogusDoctype(e){const t=this.currentToken;switch(e){case GO.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=bF.DATA;break;case GO.NULL:this._err(KO.unexpectedNullCharacter);break;case GO.EOF:this.emitCurrentDoctype(t),this._emitEOFToken()}}_stateCdataSection(e){switch(e){case GO.RIGHT_SQUARE_BRACKET:this.state=bF.CDATA_SECTION_BRACKET;break;case GO.EOF:this._err(KO.eofInCdata),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateCdataSectionBracket(e){e===GO.RIGHT_SQUARE_BRACKET?this.state=bF.CDATA_SECTION_END:(this._emitChars("]"),this.state=bF.CDATA_SECTION,this._stateCdataSection(e))}_stateCdataSectionEnd(e){switch(e){case GO.GREATER_THAN_SIGN:this.state=bF.DATA;break;case GO.RIGHT_SQUARE_BRACKET:this._emitChars("]");break;default:this._emitChars("]]"),this.state=bF.CDATA_SECTION,this._stateCdataSection(e)}}_stateCharacterReference(){let e=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(e<0){if(!this.preprocessor.lastChunkWritten)return this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,void(this.preprocessor.endOfChunkHit=!0);e=this.entityDecoder.end()}0===e?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(GO.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&isAsciiAlphaNumeric2(this.preprocessor.peek(1))?bF.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(e){isAsciiAlphaNumeric2(e)?this._flushCodePointConsumedAsCharacterReference(e):(e===GO.SEMICOLON&&this._err(KO.unknownNamedCharacterReference),this.state=this.returnState,this._callState(e))}},_F=new Set([pF.DD,pF.DT,pF.LI,pF.OPTGROUP,pF.OPTION,pF.P,pF.RB,pF.RP,pF.RT,pF.RTC]),xF=new Set([..._F,pF.CAPTION,pF.COLGROUP,pF.TBODY,pF.TD,pF.TFOOT,pF.TH,pF.THEAD,pF.TR]),TF=new Set([pF.APPLET,pF.CAPTION,pF.HTML,pF.MARQUEE,pF.OBJECT,pF.TABLE,pF.TD,pF.TEMPLATE,pF.TH]),kF=new Set([...TF,pF.OL,pF.UL]),SF=new Set([...TF,pF.BUTTON]),EF=new Set([pF.ANNOTATION_XML,pF.MI,pF.MN,pF.MO,pF.MS,pF.MTEXT]),AF=new Set([pF.DESC,pF.FOREIGN_OBJECT,pF.TITLE]),CF=new Set([pF.TR,pF.TEMPLATE,pF.HTML]),IF=new Set([pF.TBODY,pF.TFOOT,pF.THEAD,pF.TEMPLATE,pF.HTML]),PF=new Set([pF.TABLE,pF.TEMPLATE,pF.HTML]),DF=new Set([pF.TD,pF.TH]),RF=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(e,t,n){this.treeAdapter=t,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=pF.UNKNOWN,this.current=e}_indexOf(e){return this.items.lastIndexOf(e,this.stackTop)}_isInTemplate(){return this.currentTagId===pF.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===cF.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(e,t){this.stackTop++,this.items[this.stackTop]=e,this.current=e,this.tagIDs[this.stackTop]=t,this.currentTagId=t,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(e,t,!0)}pop(){const e=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!0)}replace(e,t){const n=this._indexOf(e);this.items[n]=t,n===this.stackTop&&(this.current=t)}insertAfter(e,t,n){const r=this._indexOf(e)+1;this.items.splice(r,0,t),this.tagIDs.splice(r,0,n),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&void 0!==this.currentTagId&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop)}popUntilTagNamePopped(e){let t=this.stackTop+1;do{t=this.tagIDs.lastIndexOf(e,t-1)}while(t>0&&this.treeAdapter.getNamespaceURI(this.items[t])!==cF.HTML);this.shortenToLength(Math.max(t,0))}shortenToLength(e){for(;this.stackTop>=e;){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,this.stackTop<e)}}popUntilElementPopped(e){const t=this._indexOf(e);this.shortenToLength(Math.max(t,0))}popUntilPopped(e,t){const n=this._indexOfTagNames(e,t);this.shortenToLength(Math.max(n,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(gF,cF.HTML)}popUntilTableCellPopped(){this.popUntilPopped(DF,cF.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(e,t){for(let n=this.stackTop;n>=0;n--)if(e.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===t)return n;return-1}clearBackTo(e,t){const n=this._indexOfTagNames(e,t);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(PF,cF.HTML)}clearBackToTableBodyContext(){this.clearBackTo(IF,cF.HTML)}clearBackToTableRowContext(){this.clearBackTo(CF,cF.HTML)}remove(e){const t=this._indexOf(e);t>=0&&(t===this.stackTop?this.pop():(this.items.splice(t,1),this.tagIDs.splice(t,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===pF.BODY?this.items[1]:null}contains(e){return this._indexOf(e)>-1}getCommonAncestor(e){const t=this._indexOf(e)-1;return t>=0?this.items[t]:null}isRootHtmlElementCurrent(){return 0===this.stackTop&&this.tagIDs[0]===pF.HTML}hasInDynamicScope(e,t){for(let n=this.stackTop;n>=0;n--){const r=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case cF.HTML:if(r===e)return!0;if(t.has(r))return!1;break;case cF.SVG:if(AF.has(r))return!1;break;case cF.MATHML:if(EF.has(r))return!1}}return!0}hasInScope(e){return this.hasInDynamicScope(e,TF)}hasInListItemScope(e){return this.hasInDynamicScope(e,kF)}hasInButtonScope(e){return this.hasInDynamicScope(e,SF)}hasNumberedHeaderInScope(){for(let e=this.stackTop;e>=0;e--){const t=this.tagIDs[e];switch(this.treeAdapter.getNamespaceURI(this.items[e])){case cF.HTML:if(gF.has(t))return!0;if(TF.has(t))return!1;break;case cF.SVG:if(AF.has(t))return!1;break;case cF.MATHML:if(EF.has(t))return!1}}return!0}hasInTableScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===cF.HTML)switch(this.tagIDs[t]){case e:return!0;case pF.TABLE:case pF.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let e=this.stackTop;e>=0;e--)if(this.treeAdapter.getNamespaceURI(this.items[e])===cF.HTML)switch(this.tagIDs[e]){case pF.TBODY:case pF.THEAD:case pF.TFOOT:return!0;case pF.TABLE:case pF.HTML:return!1}return!0}hasInSelectScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===cF.HTML)switch(this.tagIDs[t]){case e:return!0;case pF.OPTION:case pF.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;void 0!==this.currentTagId&&_F.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;void 0!==this.currentTagId&&xF.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(e){for(;void 0!==this.currentTagId&&this.currentTagId!==e&&xF.has(this.currentTagId);)this.pop()}},NF=3,OF;!function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"}(OF||(OF={}));var FF={type:OF.Marker},LF=class{constructor(e){this.treeAdapter=e,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(e,t){const n=[],r=t.length,s=this.treeAdapter.getTagName(e),i=this.treeAdapter.getNamespaceURI(e);for(let e=0;e<this.entries.length;e++){const t=this.entries[e];if(t.type===OF.Marker)break;const{element:o}=t;if(this.treeAdapter.getTagName(o)===s&&this.treeAdapter.getNamespaceURI(o)===i){const t=this.treeAdapter.getAttrList(o);t.length===r&&n.push({idx:e,attrs:t})}}return n}_ensureNoahArkCondition(e){if(this.entries.length<NF)return;const t=this.treeAdapter.getAttrList(e),n=this._getNoahArkConditionCandidates(e,t);if(n.length<NF)return;const r=new Map(t.map(e=>[e.name,e.value]));let s=0;for(let e=0;e<n.length;e++){const t=n[e];t.attrs.every(e=>r.get(e.name)===e.value)&&(s+=1,s>=NF&&this.entries.splice(t.idx,1))}}insertMarker(){this.entries.unshift(FF)}pushElement(e,t){this._ensureNoahArkCondition(e),this.entries.unshift({type:OF.Element,element:e,token:t})}insertElementAfterBookmark(e,t){const n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:OF.Element,element:e,token:t})}removeEntry(e){const t=this.entries.indexOf(e);-1!==t&&this.entries.splice(t,1)}clearToLastMarker(){const e=this.entries.indexOf(FF);-1===e?this.entries.length=0:this.entries.splice(0,e+1)}getElementEntryInScopeWithTagName(e){const t=this.entries.find(t=>t.type===OF.Marker||this.treeAdapter.getTagName(t.element)===e);return t&&t.type===OF.Element?t:null}getElementEntry(e){return this.entries.find(t=>t.type===OF.Element&&t.element===e)}},MF={createDocument:()=>({nodeName:"#document",mode:dF.NO_QUIRKS,childNodes:[]}),createDocumentFragment:()=>({nodeName:"#document-fragment",childNodes:[]}),createElement:(e,t,n)=>({nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}),createCommentNode:e=>({nodeName:"#comment",data:e,parentNode:null}),createTextNode:e=>({nodeName:"#text",value:e,parentNode:null}),appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,n){const r=e.childNodes.indexOf(n);e.childNodes.splice(r,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent:e=>e.content,setDocumentType(e,t,n,r){const s=e.childNodes.find(e=>"#documentType"===e.nodeName);if(s)s.name=t,s.publicId=n,s.systemId=r;else{const s={nodeName:"#documentType",name:t,publicId:n,systemId:r,parentNode:null};MF.appendChild(e,s)}},setDocumentMode(e,t){e.mode=t},getDocumentMode:e=>e.mode,detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const n=e.childNodes[e.childNodes.length-1];if(MF.isTextNode(n))return void(n.value+=t)}MF.appendChild(e,MF.createTextNode(t))},insertTextBefore(e,t,n){const r=e.childNodes[e.childNodes.indexOf(n)-1];r&&MF.isTextNode(r)?r.value+=t:MF.insertBefore(e,MF.createTextNode(t),n)},adoptAttributes(e,t){const n=new Set(e.attrs.map(e=>e.name));for(let r=0;r<t.length;r++)n.has(t[r].name)||e.attrs.push(t[r])},getFirstChild:e=>e.childNodes[0],getChildNodes:e=>e.childNodes,getParentNode:e=>e.parentNode,getAttrList:e=>e.attrs,getTagName:e=>e.tagName,getNamespaceURI:e=>e.namespaceURI,getTextNodeContent:e=>e.value,getCommentNodeContent:e=>e.data,getDocumentTypeNodeName:e=>e.name,getDocumentTypeNodePublicId:e=>e.publicId,getDocumentTypeNodeSystemId:e=>e.systemId,isTextNode:e=>"#text"===e.nodeName,isCommentNode:e=>"#comment"===e.nodeName,isDocumentTypeNode:e=>"#documentType"===e.nodeName,isElementNode:e=>Object.prototype.hasOwnProperty.call(e,"tagName"),setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation:e=>e.sourceCodeLocation,updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},UF="html",jF="about:legacy-compat",BF="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",$F=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],WF=[...$F,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],HF=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),qF=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],zF=[...qF,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function hasPrefix(e,t){return t.some(t=>e.startsWith(t))}function isConforming(e){return e.name===UF&&null===e.publicId&&(null===e.systemId||e.systemId===jF)}function getDocumentMode(e){if(e.name!==UF)return dF.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===BF)return dF.QUIRKS;let{publicId:n}=e;if(null!==n){if(n=n.toLowerCase(),HF.has(n))return dF.QUIRKS;let e=null===t?WF:$F;if(hasPrefix(n,e))return dF.QUIRKS;if(e=null===t?qF:zF,hasPrefix(n,e))return dF.LIMITED_QUIRKS}return dF.NO_QUIRKS}var GF={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},VF="definitionurl",KF="definitionURL",XF=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),YF=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:cF.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:cF.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:cF.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:cF.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:cF.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:cF.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:cF.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:cF.XML}],["xml:space",{prefix:"xml",name:"space",namespace:cF.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:cF.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:cF.XMLNS}]]),JF=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),QF=new Set([pF.B,pF.BIG,pF.BLOCKQUOTE,pF.BODY,pF.BR,pF.CENTER,pF.CODE,pF.DD,pF.DIV,pF.DL,pF.DT,pF.EM,pF.EMBED,pF.H1,pF.H2,pF.H3,pF.H4,pF.H5,pF.H6,pF.HEAD,pF.HR,pF.I,pF.IMG,pF.LI,pF.LISTING,pF.MENU,pF.META,pF.NOBR,pF.OL,pF.P,pF.PRE,pF.RUBY,pF.S,pF.SMALL,pF.SPAN,pF.STRONG,pF.STRIKE,pF.SUB,pF.SUP,pF.TABLE,pF.TT,pF.U,pF.UL,pF.VAR]);function causesExit(e){const t=e.tagID,n=t===pF.FONT&&e.attrs.some(({name:e})=>e===lF.COLOR||e===lF.SIZE||e===lF.FACE);return n||QF.has(t)}function adjustTokenMathMLAttrs(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===VF){e.attrs[t].name=KF;break}}function adjustTokenSVGAttrs(e){for(let t=0;t<e.attrs.length;t++){const n=XF.get(e.attrs[t].name);null!=n&&(e.attrs[t].name=n)}}function adjustTokenXMLAttrs(e){for(let t=0;t<e.attrs.length;t++){const n=YF.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace)}}function adjustTokenSVGTagName(e){const t=JF.get(e.tagName);null!=t&&(e.tagName=t,e.tagID=getTagID(e.tagName))}function isMathMLTextIntegrationPoint(e,t){return t===cF.MATHML&&(e===pF.MI||e===pF.MO||e===pF.MN||e===pF.MS||e===pF.MTEXT)}function isHtmlIntegrationPoint(e,t,n){if(t===cF.MATHML&&e===pF.ANNOTATION_XML)for(let e=0;e<n.length;e++)if(n[e].name===lF.ENCODING){const t=n[e].value.toLowerCase();return t===GF.TEXT_HTML||t===GF.APPLICATION_XML}return t===cF.SVG&&(e===pF.FOREIGN_OBJECT||e===pF.DESC||e===pF.TITLE)}function isIntegrationPoint(e,t,n,r){return(!r||r===cF.HTML)&&isHtmlIntegrationPoint(e,t,n)||(!r||r===cF.MATHML)&&isMathMLTextIntegrationPoint(e,t)}var ZF="hidden",eL=8,tL=3,nL;!function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"}(nL||(nL={}));var rL={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},sL=new Set([pF.TABLE,pF.TBODY,pF.TFOOT,pF.THEAD,pF.TR]),iL={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:MF,onParseError:null},oL=class{constructor(e,t,n=null,r=null){this.fragmentContext=n,this.scriptHandler=r,this.currentToken=null,this.stopped=!1,this.insertionMode=nL.INITIAL,this.originalInsertionMode=nL.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...iL,...e},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=null!=t?t:this.treeAdapter.createDocument(),this.tokenizer=new wF(this.options,this),this.activeFormattingElements=new LF(this.treeAdapter),this.fragmentContextID=n?getTagID(this.treeAdapter.getTagName(n)):pF.UNKNOWN,this._setContextModes(null!=n?n:this.document,this.fragmentContextID),this.openElements=new RF(this.document,this.treeAdapter,this)}static parse(e,t){const n=new this(t);return n.tokenizer.write(e,!0),n.document}static getFragmentParser(e,t){const n={...iL,...t};null!=e||(e=n.treeAdapter.createElement(uF.TEMPLATE,cF.HTML,[]));const r=n.treeAdapter.createElement("documentmock",cF.HTML,[]),s=new this(n,r,e);return s.fragmentContextID===pF.TEMPLATE&&s.tmplInsertionModeStack.unshift(nL.IN_TEMPLATE),s._initTokenizerForFragmentParsing(),s._insertFakeRootElement(),s._resetInsertionMode(),s._findFormInFragmentContext(),s}getFragment(){const e=this.treeAdapter.getFirstChild(this.document),t=this.treeAdapter.createDocumentFragment();return this._adoptNodes(e,t),t}_err(e,t,n){var r;if(!this.onParseError)return;const s=null!==(r=e.location)&&void 0!==r?r:rL,i={code:t,startLine:s.startLine,startCol:s.startCol,startOffset:s.startOffset,endLine:n?s.startLine:s.endLine,endCol:n?s.startCol:s.endCol,endOffset:n?s.startOffset:s.endOffset};this.onParseError(i)}onItemPush(e,t,n){var r,s;null===(s=(r=this.treeAdapter).onItemPush)||void 0===s||s.call(r,e),n&&this.openElements.stackTop>0&&this._setContextModes(e,t)}onItemPop(e,t){var n,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(e,this.currentToken),null===(r=(n=this.treeAdapter).onItemPop)||void 0===r||r.call(n,e,this.openElements.current),t){let e,t;0===this.openElements.stackTop&&this.fragmentContext?(e=this.fragmentContext,t=this.fragmentContextID):({current:e,currentTagId:t}=this.openElements),this._setContextModes(e,t)}}_setContextModes(e,t){const n=e===this.document||e&&this.treeAdapter.getNamespaceURI(e)===cF.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&void 0!==e&&void 0!==t&&!this._isIntegrationPoint(t,e)}_switchToTextParsing(e,t){this._insertElement(e,cF.HTML),this.tokenizer.state=t,this.originalInsertionMode=this.insertionMode,this.insertionMode=nL.TEXT}switchToPlaintextParsing(){this.insertionMode=nL.TEXT,this.originalInsertionMode=nL.IN_BODY,this.tokenizer.state=vF.PLAINTEXT}_getAdjustedCurrentElement(){return 0===this.openElements.stackTop&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let e=this.fragmentContext;for(;e;){if(this.treeAdapter.getTagName(e)===uF.FORM){this.formElement=e;break}e=this.treeAdapter.getParentNode(e)}}_initTokenizerForFragmentParsing(){if(this.fragmentContext&&this.treeAdapter.getNamespaceURI(this.fragmentContext)===cF.HTML)switch(this.fragmentContextID){case pF.TITLE:case pF.TEXTAREA:this.tokenizer.state=vF.RCDATA;break;case pF.STYLE:case pF.XMP:case pF.IFRAME:case pF.NOEMBED:case pF.NOFRAMES:case pF.NOSCRIPT:this.tokenizer.state=vF.RAWTEXT;break;case pF.SCRIPT:this.tokenizer.state=vF.SCRIPT_DATA;break;case pF.PLAINTEXT:this.tokenizer.state=vF.PLAINTEXT}}_setDocumentType(e){const t=e.name||"",n=e.publicId||"",r=e.systemId||"";if(this.treeAdapter.setDocumentType(this.document,t,n,r),e.location){const t=this.treeAdapter.getChildNodes(this.document),n=t.find(e=>this.treeAdapter.isDocumentTypeNode(e));n&&this.treeAdapter.setNodeSourceCodeLocation(n,e.location)}}_attachElementToTree(e,t){if(this.options.sourceCodeLocationInfo){const n=t&&{...t,startTag:t};this.treeAdapter.setNodeSourceCodeLocation(e,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(e);else{const t=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(null!=t?t:this.document,e)}}_appendElement(e,t){const n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location)}_insertElement(e,t){const n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location),this.openElements.push(n,e.tagID)}_insertFakeElement(e,t){const n=this.treeAdapter.createElement(e,cF.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,t)}_insertTemplate(e){const t=this.treeAdapter.createElement(e.tagName,cF.HTML,e.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(t,n),this._attachElementToTree(t,e.location),this.openElements.push(t,e.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){const e=this.treeAdapter.createElement(uF.HTML,cF.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(e,null),this.treeAdapter.appendChild(this.openElements.current,e),this.openElements.push(e,pF.HTML)}_appendCommentNode(e,t){const n=this.treeAdapter.createCommentNode(e.data);this.treeAdapter.appendChild(t,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,e.location)}_insertCharacters(e){let t,n;if(this._shouldFosterParentOnInsertion()?(({parent:t,beforeElement:n}=this._findFosterParentingLocation()),n?this.treeAdapter.insertTextBefore(t,e.chars,n):this.treeAdapter.insertText(t,e.chars)):(t=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(t,e.chars)),!e.location)return;const r=this.treeAdapter.getChildNodes(t),s=n?r.lastIndexOf(n):r.length,i=r[s-1],o=this.treeAdapter.getNodeSourceCodeLocation(i);if(o){const{endLine:t,endCol:n,endOffset:r}=e.location;this.treeAdapter.updateNodeSourceCodeLocation(i,{endLine:t,endCol:n,endOffset:r})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(i,e.location)}_adoptNodes(e,t){for(let n=this.treeAdapter.getFirstChild(e);n;n=this.treeAdapter.getFirstChild(e))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(t,n)}_setEndLocation(e,t){if(this.treeAdapter.getNodeSourceCodeLocation(e)&&t.location){const n=t.location,r=this.treeAdapter.getTagName(e),s=t.type===JO.END_TAG&&r===t.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(e,s)}}shouldProcessStartTagTokenInForeignContent(e){if(!this.currentNotInHTML)return!1;let t,n;return 0===this.openElements.stackTop&&this.fragmentContext?(t=this.fragmentContext,n=this.fragmentContextID):({current:t,currentTagId:n}=this.openElements),(e.tagID!==pF.SVG||this.treeAdapter.getTagName(t)!==uF.ANNOTATION_XML||this.treeAdapter.getNamespaceURI(t)!==cF.MATHML)&&(this.tokenizer.inForeignNode||(e.tagID===pF.MGLYPH||e.tagID===pF.MALIGNMARK)&&void 0!==n&&!this._isIntegrationPoint(n,t,cF.HTML))}_processToken(e){switch(e.type){case JO.CHARACTER:this.onCharacter(e);break;case JO.NULL_CHARACTER:this.onNullCharacter(e);break;case JO.COMMENT:this.onComment(e);break;case JO.DOCTYPE:this.onDoctype(e);break;case JO.START_TAG:this._processStartTag(e);break;case JO.END_TAG:this.onEndTag(e);break;case JO.EOF:this.onEof(e);break;case JO.WHITESPACE_CHARACTER:this.onWhitespaceCharacter(e)}}_isIntegrationPoint(e,t,n){const r=this.treeAdapter.getNamespaceURI(t),s=this.treeAdapter.getAttrList(t);return isIntegrationPoint(e,r,s,n)}_reconstructActiveFormattingElements(){const e=this.activeFormattingElements.entries.length;if(e){const t=this.activeFormattingElements.entries.findIndex(e=>e.type===OF.Marker||this.openElements.contains(e.element)),n=-1===t?e-1:t-1;for(let e=n;e>=0;e--){const t=this.activeFormattingElements.entries[e];this._insertElement(t.token,this.treeAdapter.getNamespaceURI(t.element)),t.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=nL.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(pF.P),this.openElements.popUntilTagNamePopped(pF.P)}_resetInsertionMode(){for(let e=this.openElements.stackTop;e>=0;e--)switch(0===e&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[e]){case pF.TR:return void(this.insertionMode=nL.IN_ROW);case pF.TBODY:case pF.THEAD:case pF.TFOOT:return void(this.insertionMode=nL.IN_TABLE_BODY);case pF.CAPTION:return void(this.insertionMode=nL.IN_CAPTION);case pF.COLGROUP:return void(this.insertionMode=nL.IN_COLUMN_GROUP);case pF.TABLE:return void(this.insertionMode=nL.IN_TABLE);case pF.BODY:return void(this.insertionMode=nL.IN_BODY);case pF.FRAMESET:return void(this.insertionMode=nL.IN_FRAMESET);case pF.SELECT:return void this._resetInsertionModeForSelect(e);case pF.TEMPLATE:return void(this.insertionMode=this.tmplInsertionModeStack[0]);case pF.HTML:return void(this.insertionMode=this.headElement?nL.AFTER_HEAD:nL.BEFORE_HEAD);case pF.TD:case pF.TH:if(e>0)return void(this.insertionMode=nL.IN_CELL);break;case pF.HEAD:if(e>0)return void(this.insertionMode=nL.IN_HEAD)}this.insertionMode=nL.IN_BODY}_resetInsertionModeForSelect(e){if(e>0)for(let t=e-1;t>0;t--){const e=this.openElements.tagIDs[t];if(e===pF.TEMPLATE)break;if(e===pF.TABLE)return void(this.insertionMode=nL.IN_SELECT_IN_TABLE)}this.insertionMode=nL.IN_SELECT}_isElementCausesFosterParenting(e){return sL.has(e)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&void 0!==this.openElements.currentTagId&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let e=this.openElements.stackTop;e>=0;e--){const t=this.openElements.items[e];switch(this.openElements.tagIDs[e]){case pF.TEMPLATE:if(this.treeAdapter.getNamespaceURI(t)===cF.HTML)return{parent:this.treeAdapter.getTemplateContent(t),beforeElement:null};break;case pF.TABLE:{const n=this.treeAdapter.getParentNode(t);return n?{parent:n,beforeElement:t}:{parent:this.openElements.items[e-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(e){const t=this._findFosterParentingLocation();t.beforeElement?this.treeAdapter.insertBefore(t.parent,e,t.beforeElement):this.treeAdapter.appendChild(t.parent,e)}_isSpecialElement(e,t){const n=this.treeAdapter.getNamespaceURI(e);return fF[n].has(t)}onCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode)characterInForeignContent(this,e);else switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:tokenBeforeHtml(this,e);break;case nL.BEFORE_HEAD:tokenBeforeHead(this,e);break;case nL.IN_HEAD:tokenInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case nL.AFTER_HEAD:tokenAfterHead(this,e);break;case nL.IN_BODY:case nL.IN_CAPTION:case nL.IN_CELL:case nL.IN_TEMPLATE:characterInBody(this,e);break;case nL.TEXT:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:this._insertCharacters(e);break;case nL.IN_TABLE:case nL.IN_TABLE_BODY:case nL.IN_ROW:characterInTable(this,e);break;case nL.IN_TABLE_TEXT:characterInTableText(this,e);break;case nL.IN_COLUMN_GROUP:tokenInColumnGroup(this,e);break;case nL.AFTER_BODY:tokenAfterBody(this,e);break;case nL.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onNullCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode)nullCharacterInForeignContent(this,e);else switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:tokenBeforeHtml(this,e);break;case nL.BEFORE_HEAD:tokenBeforeHead(this,e);break;case nL.IN_HEAD:tokenInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case nL.AFTER_HEAD:tokenAfterHead(this,e);break;case nL.TEXT:this._insertCharacters(e);break;case nL.IN_TABLE:case nL.IN_TABLE_BODY:case nL.IN_ROW:characterInTable(this,e);break;case nL.IN_COLUMN_GROUP:tokenInColumnGroup(this,e);break;case nL.AFTER_BODY:tokenAfterBody(this,e);break;case nL.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onComment(e){if(this.skipNextNewLine=!1,this.currentNotInHTML)appendComment(this,e);else switch(this.insertionMode){case nL.INITIAL:case nL.BEFORE_HTML:case nL.BEFORE_HEAD:case nL.IN_HEAD:case nL.IN_HEAD_NO_SCRIPT:case nL.AFTER_HEAD:case nL.IN_BODY:case nL.IN_TABLE:case nL.IN_CAPTION:case nL.IN_COLUMN_GROUP:case nL.IN_TABLE_BODY:case nL.IN_ROW:case nL.IN_CELL:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:case nL.IN_TEMPLATE:case nL.IN_FRAMESET:case nL.AFTER_FRAMESET:appendComment(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.AFTER_BODY:appendCommentToRootHtmlElement(this,e);break;case nL.AFTER_AFTER_BODY:case nL.AFTER_AFTER_FRAMESET:appendCommentToDocument(this,e)}}onDoctype(e){switch(this.skipNextNewLine=!1,this.insertionMode){case nL.INITIAL:doctypeInInitialMode(this,e);break;case nL.BEFORE_HEAD:case nL.IN_HEAD:case nL.IN_HEAD_NO_SCRIPT:case nL.AFTER_HEAD:this._err(e,KO.misplacedDoctype);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e)}}onStartTag(e){this.skipNextNewLine=!1,this.currentToken=e,this._processStartTag(e),e.selfClosing&&!e.ackSelfClosing&&this._err(e,KO.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(e){this.shouldProcessStartTagTokenInForeignContent(e)?startTagInForeignContent(this,e):this._startTagOutsideForeignContent(e)}_startTagOutsideForeignContent(e){switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:startTagBeforeHtml(this,e);break;case nL.BEFORE_HEAD:startTagBeforeHead(this,e);break;case nL.IN_HEAD:startTagInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:startTagInHeadNoScript(this,e);break;case nL.AFTER_HEAD:startTagAfterHead(this,e);break;case nL.IN_BODY:startTagInBody(this,e);break;case nL.IN_TABLE:startTagInTable(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.IN_CAPTION:startTagInCaption(this,e);break;case nL.IN_COLUMN_GROUP:startTagInColumnGroup(this,e);break;case nL.IN_TABLE_BODY:startTagInTableBody(this,e);break;case nL.IN_ROW:startTagInRow(this,e);break;case nL.IN_CELL:startTagInCell(this,e);break;case nL.IN_SELECT:startTagInSelect(this,e);break;case nL.IN_SELECT_IN_TABLE:startTagInSelectInTable(this,e);break;case nL.IN_TEMPLATE:startTagInTemplate(this,e);break;case nL.AFTER_BODY:startTagAfterBody(this,e);break;case nL.IN_FRAMESET:startTagInFrameset(this,e);break;case nL.AFTER_FRAMESET:startTagAfterFrameset(this,e);break;case nL.AFTER_AFTER_BODY:startTagAfterAfterBody(this,e);break;case nL.AFTER_AFTER_FRAMESET:startTagAfterAfterFrameset(this,e)}}onEndTag(e){this.skipNextNewLine=!1,this.currentToken=e,this.currentNotInHTML?endTagInForeignContent(this,e):this._endTagOutsideForeignContent(e)}_endTagOutsideForeignContent(e){switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:endTagBeforeHtml(this,e);break;case nL.BEFORE_HEAD:endTagBeforeHead(this,e);break;case nL.IN_HEAD:endTagInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:endTagInHeadNoScript(this,e);break;case nL.AFTER_HEAD:endTagAfterHead(this,e);break;case nL.IN_BODY:endTagInBody(this,e);break;case nL.TEXT:endTagInText(this,e);break;case nL.IN_TABLE:endTagInTable(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.IN_CAPTION:endTagInCaption(this,e);break;case nL.IN_COLUMN_GROUP:endTagInColumnGroup(this,e);break;case nL.IN_TABLE_BODY:endTagInTableBody(this,e);break;case nL.IN_ROW:endTagInRow(this,e);break;case nL.IN_CELL:endTagInCell(this,e);break;case nL.IN_SELECT:endTagInSelect(this,e);break;case nL.IN_SELECT_IN_TABLE:endTagInSelectInTable(this,e);break;case nL.IN_TEMPLATE:endTagInTemplate(this,e);break;case nL.AFTER_BODY:endTagAfterBody(this,e);break;case nL.IN_FRAMESET:endTagInFrameset(this,e);break;case nL.AFTER_FRAMESET:endTagAfterFrameset(this,e);break;case nL.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onEof(e){switch(this.insertionMode){case nL.INITIAL:tokenInInitialMode(this,e);break;case nL.BEFORE_HTML:tokenBeforeHtml(this,e);break;case nL.BEFORE_HEAD:tokenBeforeHead(this,e);break;case nL.IN_HEAD:tokenInHead(this,e);break;case nL.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case nL.AFTER_HEAD:tokenAfterHead(this,e);break;case nL.IN_BODY:case nL.IN_TABLE:case nL.IN_CAPTION:case nL.IN_COLUMN_GROUP:case nL.IN_TABLE_BODY:case nL.IN_ROW:case nL.IN_CELL:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:eofInBody(this,e);break;case nL.TEXT:eofInText(this,e);break;case nL.IN_TABLE_TEXT:tokenInTableText(this,e);break;case nL.IN_TEMPLATE:eofInTemplate(this,e);break;case nL.AFTER_BODY:case nL.IN_FRAMESET:case nL.AFTER_FRAMESET:case nL.AFTER_AFTER_BODY:case nL.AFTER_AFTER_FRAMESET:stopParsing(this,e)}}onWhitespaceCharacter(e){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,e.chars.charCodeAt(0)===GO.LINE_FEED)){if(1===e.chars.length)return;e.chars=e.chars.substr(1)}if(this.tokenizer.inForeignNode)this._insertCharacters(e);else switch(this.insertionMode){case nL.IN_HEAD:case nL.IN_HEAD_NO_SCRIPT:case nL.AFTER_HEAD:case nL.TEXT:case nL.IN_COLUMN_GROUP:case nL.IN_SELECT:case nL.IN_SELECT_IN_TABLE:case nL.IN_FRAMESET:case nL.AFTER_FRAMESET:this._insertCharacters(e);break;case nL.IN_BODY:case nL.IN_CAPTION:case nL.IN_CELL:case nL.IN_TEMPLATE:case nL.AFTER_BODY:case nL.AFTER_AFTER_BODY:case nL.AFTER_AFTER_FRAMESET:whitespaceCharacterInBody(this,e);break;case nL.IN_TABLE:case nL.IN_TABLE_BODY:case nL.IN_ROW:characterInTable(this,e);break;case nL.IN_TABLE_TEXT:whitespaceCharacterInTableText(this,e)}}};function aaObtainFormattingElementEntry(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):genericEndTagInBody(e,t),n}function aaObtainFurthestBlock(e,t){let n=null,r=e.openElements.stackTop;for(;r>=0;r--){const s=e.openElements.items[r];if(s===t.element)break;e._isSpecialElement(s,e.openElements.tagIDs[r])&&(n=s)}return n||(e.openElements.shortenToLength(Math.max(r,0)),e.activeFormattingElements.removeEntry(t)),n}function aaInnerLoop(e,t,n){let r=t,s=e.openElements.getCommonAncestor(t);for(let i=0,o=s;o!==n;i++,o=s){s=e.openElements.getCommonAncestor(o);const n=e.activeFormattingElements.getElementEntry(o),a=n&&i>=tL,c=!n||a;c?(a&&e.activeFormattingElements.removeEntry(n),e.openElements.remove(o)):(o=aaRecreateElementFromEntry(e,n),r===t&&(e.activeFormattingElements.bookmark=n),e.treeAdapter.detachNode(r),e.treeAdapter.appendChild(o,r),r=o)}return r}function aaRecreateElementFromEntry(e,t){const n=e.treeAdapter.getNamespaceURI(t.element),r=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,r),t.element=r,r}function aaInsertLastNodeInCommonAncestor(e,t,n){const r=e.treeAdapter.getTagName(t),s=getTagID(r);if(e._isElementCausesFosterParenting(s))e._fosterParentElement(n);else{const r=e.treeAdapter.getNamespaceURI(t);s===pF.TEMPLATE&&r===cF.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function aaReplaceFormattingElement(e,t,n){const r=e.treeAdapter.getNamespaceURI(n.element),{token:s}=n,i=e.treeAdapter.createElement(s.tagName,r,s.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,s),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,s.tagID)}function callAdoptionAgency(e,t){for(let n=0;n<eL;n++){const n=aaObtainFormattingElementEntry(e,t);if(!n)break;const r=aaObtainFurthestBlock(e,n);if(!r)break;e.activeFormattingElements.bookmark=n;const s=aaInnerLoop(e,r,n.element),i=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),i&&aaInsertLastNodeInCommonAncestor(e,i,s),aaReplaceFormattingElement(e,r,n)}}function appendComment(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function appendCommentToRootHtmlElement(e,t){e._appendCommentNode(t,e.openElements.items[0])}function appendCommentToDocument(e,t){e._appendCommentNode(t,e.document)}function stopParsing(e,t){if(e.stopped=!0,t.location){const n=e.fragmentContext?0:2;for(let r=e.openElements.stackTop;r>=n;r--)e._setEndLocation(e.openElements.items[r],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const n=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(n);if(r&&!r.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){const n=e.openElements.items[1],r=e.treeAdapter.getNodeSourceCodeLocation(n);r&&!r.endTag&&e._setEndLocation(n,t)}}}}function doctypeInInitialMode(e,t){e._setDocumentType(t);const n=t.forceQuirks?dF.QUIRKS:getDocumentMode(t);isConforming(t)||e._err(t,KO.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=nL.BEFORE_HTML}function tokenInInitialMode(e,t){e._err(t,KO.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,dF.QUIRKS),e.insertionMode=nL.BEFORE_HTML,e._processToken(t)}function startTagBeforeHtml(e,t){t.tagID===pF.HTML?(e._insertElement(t,cF.HTML),e.insertionMode=nL.BEFORE_HEAD):tokenBeforeHtml(e,t)}function endTagBeforeHtml(e,t){const n=t.tagID;n!==pF.HTML&&n!==pF.HEAD&&n!==pF.BODY&&n!==pF.BR||tokenBeforeHtml(e,t)}function tokenBeforeHtml(e,t){e._insertFakeRootElement(),e.insertionMode=nL.BEFORE_HEAD,e._processToken(t)}function startTagBeforeHead(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.HEAD:e._insertElement(t,cF.HTML),e.headElement=e.openElements.current,e.insertionMode=nL.IN_HEAD;break;default:tokenBeforeHead(e,t)}}function endTagBeforeHead(e,t){const n=t.tagID;n===pF.HEAD||n===pF.BODY||n===pF.HTML||n===pF.BR?tokenBeforeHead(e,t):e._err(t,KO.endTagWithoutMatchingOpenElement)}function tokenBeforeHead(e,t){e._insertFakeElement(uF.HEAD,pF.HEAD),e.headElement=e.openElements.current,e.insertionMode=nL.IN_HEAD,e._processToken(t)}function startTagInHead(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.BASE:case pF.BASEFONT:case pF.BGSOUND:case pF.LINK:case pF.META:e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.TITLE:e._switchToTextParsing(t,vF.RCDATA);break;case pF.NOSCRIPT:e.options.scriptingEnabled?e._switchToTextParsing(t,vF.RAWTEXT):(e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_HEAD_NO_SCRIPT);break;case pF.NOFRAMES:case pF.STYLE:e._switchToTextParsing(t,vF.RAWTEXT);break;case pF.SCRIPT:e._switchToTextParsing(t,vF.SCRIPT_DATA);break;case pF.TEMPLATE:e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=nL.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(nL.IN_TEMPLATE);break;case pF.HEAD:e._err(t,KO.misplacedStartTagForHeadElement);break;default:tokenInHead(e,t)}}function endTagInHead(e,t){switch(t.tagID){case pF.HEAD:e.openElements.pop(),e.insertionMode=nL.AFTER_HEAD;break;case pF.BODY:case pF.BR:case pF.HTML:tokenInHead(e,t);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;default:e._err(t,KO.endTagWithoutMatchingOpenElement)}}function templateEndTagInHead(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==pF.TEMPLATE&&e._err(t,KO.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(pF.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,KO.endTagWithoutMatchingOpenElement)}function tokenInHead(e,t){e.openElements.pop(),e.insertionMode=nL.AFTER_HEAD,e._processToken(t)}function startTagInHeadNoScript(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.BASEFONT:case pF.BGSOUND:case pF.HEAD:case pF.LINK:case pF.META:case pF.NOFRAMES:case pF.STYLE:startTagInHead(e,t);break;case pF.NOSCRIPT:e._err(t,KO.nestedNoscriptInHead);break;default:tokenInHeadNoScript(e,t)}}function endTagInHeadNoScript(e,t){switch(t.tagID){case pF.NOSCRIPT:e.openElements.pop(),e.insertionMode=nL.IN_HEAD;break;case pF.BR:tokenInHeadNoScript(e,t);break;default:e._err(t,KO.endTagWithoutMatchingOpenElement)}}function tokenInHeadNoScript(e,t){const n=t.type===JO.EOF?KO.openElementsLeftAfterEof:KO.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=nL.IN_HEAD,e._processToken(t)}function startTagAfterHead(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.BODY:e._insertElement(t,cF.HTML),e.framesetOk=!1,e.insertionMode=nL.IN_BODY;break;case pF.FRAMESET:e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_FRAMESET;break;case pF.BASE:case pF.BASEFONT:case pF.BGSOUND:case pF.LINK:case pF.META:case pF.NOFRAMES:case pF.SCRIPT:case pF.STYLE:case pF.TEMPLATE:case pF.TITLE:e._err(t,KO.abandonedHeadElementChild),e.openElements.push(e.headElement,pF.HEAD),startTagInHead(e,t),e.openElements.remove(e.headElement);break;case pF.HEAD:e._err(t,KO.misplacedStartTagForHeadElement);break;default:tokenAfterHead(e,t)}}function endTagAfterHead(e,t){switch(t.tagID){case pF.BODY:case pF.HTML:case pF.BR:tokenAfterHead(e,t);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;default:e._err(t,KO.endTagWithoutMatchingOpenElement)}}function tokenAfterHead(e,t){e._insertFakeElement(uF.BODY,pF.BODY),e.insertionMode=nL.IN_BODY,modeInBody(e,t)}function modeInBody(e,t){switch(t.type){case JO.CHARACTER:characterInBody(e,t);break;case JO.WHITESPACE_CHARACTER:whitespaceCharacterInBody(e,t);break;case JO.COMMENT:appendComment(e,t);break;case JO.START_TAG:startTagInBody(e,t);break;case JO.END_TAG:endTagInBody(e,t);break;case JO.EOF:eofInBody(e,t)}}function whitespaceCharacterInBody(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function characterInBody(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function htmlStartTagInBody(e,t){0===e.openElements.tmplCount&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function bodyStartTagInBody(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&0===e.openElements.tmplCount&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function framesetStartTagInBody(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_FRAMESET)}function addressStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML)}function numberedHeaderStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),void 0!==e.openElements.currentTagId&&gF.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,cF.HTML)}function preStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function formStartTagInBody(e,t){const n=e.openElements.tmplCount>0;e.formElement&&!n||(e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),n||(e.formElement=e.openElements.current))}function listItemStartTagInBody(e,t){e.framesetOk=!1;const n=t.tagID;for(let t=e.openElements.stackTop;t>=0;t--){const r=e.openElements.tagIDs[t];if(n===pF.LI&&r===pF.LI||(n===pF.DD||n===pF.DT)&&(r===pF.DD||r===pF.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==pF.ADDRESS&&r!==pF.DIV&&r!==pF.P&&e._isSpecialElement(e.openElements.items[t],r))break}e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML)}function plaintextStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),e.tokenizer.state=vF.PLAINTEXT}function buttonStartTagInBody(e,t){e.openElements.hasInScope(pF.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(pF.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.framesetOk=!1}function aStartTagInBody(e,t){const n=e.activeFormattingElements.getElementEntryInScopeWithTagName(uF.A);n&&(callAdoptionAgency(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function bStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function nobrStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(pF.NOBR)&&(callAdoptionAgency(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,cF.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function appletStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function tableStartTagInBody(e,t){e.treeAdapter.getDocumentMode(e.document)!==dF.QUIRKS&&e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._insertElement(t,cF.HTML),e.framesetOk=!1,e.insertionMode=nL.IN_TABLE}function areaStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,cF.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function isHiddenInput(e){const t=getTokenAttr(e,lF.TYPE);return null!=t&&t.toLowerCase()===ZF}function inputStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,cF.HTML),isHiddenInput(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function paramStartTagInBody(e,t){e._appendElement(t,cF.HTML),t.ackSelfClosing=!0}function hrStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._appendElement(t,cF.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function imageStartTagInBody(e,t){t.tagName=uF.IMG,t.tagID=pF.IMG,areaStartTagInBody(e,t)}function textareaStartTagInBody(e,t){e._insertElement(t,cF.HTML),e.skipNextNewLine=!0,e.tokenizer.state=vF.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=nL.TEXT}function xmpStartTagInBody(e,t){e.openElements.hasInButtonScope(pF.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,vF.RAWTEXT)}function iframeStartTagInBody(e,t){e.framesetOk=!1,e._switchToTextParsing(t,vF.RAWTEXT)}function rawTextStartTagInBody(e,t){e._switchToTextParsing(t,vF.RAWTEXT)}function selectStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===nL.IN_TABLE||e.insertionMode===nL.IN_CAPTION||e.insertionMode===nL.IN_TABLE_BODY||e.insertionMode===nL.IN_ROW||e.insertionMode===nL.IN_CELL?nL.IN_SELECT_IN_TABLE:nL.IN_SELECT}function optgroupStartTagInBody(e,t){e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML)}function rbStartTagInBody(e,t){e.openElements.hasInScope(pF.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,cF.HTML)}function rtStartTagInBody(e,t){e.openElements.hasInScope(pF.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(pF.RTC),e._insertElement(t,cF.HTML)}function mathStartTagInBody(e,t){e._reconstructActiveFormattingElements(),adjustTokenMathMLAttrs(t),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,cF.MATHML):e._insertElement(t,cF.MATHML),t.ackSelfClosing=!0}function svgStartTagInBody(e,t){e._reconstructActiveFormattingElements(),adjustTokenSVGAttrs(t),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,cF.SVG):e._insertElement(t,cF.SVG),t.ackSelfClosing=!0}function genericStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,cF.HTML)}function startTagInBody(e,t){switch(t.tagID){case pF.I:case pF.S:case pF.B:case pF.U:case pF.EM:case pF.TT:case pF.BIG:case pF.CODE:case pF.FONT:case pF.SMALL:case pF.STRIKE:case pF.STRONG:bStartTagInBody(e,t);break;case pF.A:aStartTagInBody(e,t);break;case pF.H1:case pF.H2:case pF.H3:case pF.H4:case pF.H5:case pF.H6:numberedHeaderStartTagInBody(e,t);break;case pF.P:case pF.DL:case pF.OL:case pF.UL:case pF.DIV:case pF.DIR:case pF.NAV:case pF.MAIN:case pF.MENU:case pF.ASIDE:case pF.CENTER:case pF.FIGURE:case pF.FOOTER:case pF.HEADER:case pF.HGROUP:case pF.DIALOG:case pF.DETAILS:case pF.ADDRESS:case pF.ARTICLE:case pF.SEARCH:case pF.SECTION:case pF.SUMMARY:case pF.FIELDSET:case pF.BLOCKQUOTE:case pF.FIGCAPTION:addressStartTagInBody(e,t);break;case pF.LI:case pF.DD:case pF.DT:listItemStartTagInBody(e,t);break;case pF.BR:case pF.IMG:case pF.WBR:case pF.AREA:case pF.EMBED:case pF.KEYGEN:areaStartTagInBody(e,t);break;case pF.HR:hrStartTagInBody(e,t);break;case pF.RB:case pF.RTC:rbStartTagInBody(e,t);break;case pF.RT:case pF.RP:rtStartTagInBody(e,t);break;case pF.PRE:case pF.LISTING:preStartTagInBody(e,t);break;case pF.XMP:xmpStartTagInBody(e,t);break;case pF.SVG:svgStartTagInBody(e,t);break;case pF.HTML:htmlStartTagInBody(e,t);break;case pF.BASE:case pF.LINK:case pF.META:case pF.STYLE:case pF.TITLE:case pF.SCRIPT:case pF.BGSOUND:case pF.BASEFONT:case pF.TEMPLATE:startTagInHead(e,t);break;case pF.BODY:bodyStartTagInBody(e,t);break;case pF.FORM:formStartTagInBody(e,t);break;case pF.NOBR:nobrStartTagInBody(e,t);break;case pF.MATH:mathStartTagInBody(e,t);break;case pF.TABLE:tableStartTagInBody(e,t);break;case pF.INPUT:inputStartTagInBody(e,t);break;case pF.PARAM:case pF.TRACK:case pF.SOURCE:paramStartTagInBody(e,t);break;case pF.IMAGE:imageStartTagInBody(e,t);break;case pF.BUTTON:buttonStartTagInBody(e,t);break;case pF.APPLET:case pF.OBJECT:case pF.MARQUEE:appletStartTagInBody(e,t);break;case pF.IFRAME:iframeStartTagInBody(e,t);break;case pF.SELECT:selectStartTagInBody(e,t);break;case pF.OPTION:case pF.OPTGROUP:optgroupStartTagInBody(e,t);break;case pF.NOEMBED:case pF.NOFRAMES:rawTextStartTagInBody(e,t);break;case pF.FRAMESET:framesetStartTagInBody(e,t);break;case pF.TEXTAREA:textareaStartTagInBody(e,t);break;case pF.NOSCRIPT:e.options.scriptingEnabled?rawTextStartTagInBody(e,t):genericStartTagInBody(e,t);break;case pF.PLAINTEXT:plaintextStartTagInBody(e,t);break;case pF.COL:case pF.TH:case pF.TD:case pF.TR:case pF.HEAD:case pF.FRAME:case pF.TBODY:case pF.TFOOT:case pF.THEAD:case pF.CAPTION:case pF.COLGROUP:break;default:genericStartTagInBody(e,t)}}function bodyEndTagInBody(e,t){if(e.openElements.hasInScope(pF.BODY)&&(e.insertionMode=nL.AFTER_BODY,e.options.sourceCodeLocationInfo)){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function htmlEndTagInBody(e,t){e.openElements.hasInScope(pF.BODY)&&(e.insertionMode=nL.AFTER_BODY,endTagAfterBody(e,t))}function addressEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function formEndTagInBody(e){const t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(pF.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(pF.FORM):n&&e.openElements.remove(n))}function pEndTagInBody(e){e.openElements.hasInButtonScope(pF.P)||e._insertFakeElement(uF.P,pF.P),e._closePElement()}function liEndTagInBody(e){e.openElements.hasInListItemScope(pF.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(pF.LI),e.openElements.popUntilTagNamePopped(pF.LI))}function ddEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function numberedHeaderEndTagInBody(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function appletEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function brEndTagInBody(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(uF.BR,pF.BR),e.openElements.pop(),e.framesetOk=!1}function genericEndTagInBody(e,t){const n=t.tagName,r=t.tagID;for(let t=e.openElements.stackTop;t>0;t--){const s=e.openElements.items[t],i=e.openElements.tagIDs[t];if(r===i&&(r!==pF.UNKNOWN||e.treeAdapter.getTagName(s)===n)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.stackTop>=t&&e.openElements.shortenToLength(t);break}if(e._isSpecialElement(s,i))break}}function endTagInBody(e,t){switch(t.tagID){case pF.A:case pF.B:case pF.I:case pF.S:case pF.U:case pF.EM:case pF.TT:case pF.BIG:case pF.CODE:case pF.FONT:case pF.NOBR:case pF.SMALL:case pF.STRIKE:case pF.STRONG:callAdoptionAgency(e,t);break;case pF.P:pEndTagInBody(e);break;case pF.DL:case pF.UL:case pF.OL:case pF.DIR:case pF.DIV:case pF.NAV:case pF.PRE:case pF.MAIN:case pF.MENU:case pF.ASIDE:case pF.BUTTON:case pF.CENTER:case pF.FIGURE:case pF.FOOTER:case pF.HEADER:case pF.HGROUP:case pF.DIALOG:case pF.ADDRESS:case pF.ARTICLE:case pF.DETAILS:case pF.SEARCH:case pF.SECTION:case pF.SUMMARY:case pF.LISTING:case pF.FIELDSET:case pF.BLOCKQUOTE:case pF.FIGCAPTION:addressEndTagInBody(e,t);break;case pF.LI:liEndTagInBody(e);break;case pF.DD:case pF.DT:ddEndTagInBody(e,t);break;case pF.H1:case pF.H2:case pF.H3:case pF.H4:case pF.H5:case pF.H6:numberedHeaderEndTagInBody(e);break;case pF.BR:brEndTagInBody(e);break;case pF.BODY:bodyEndTagInBody(e,t);break;case pF.HTML:htmlEndTagInBody(e,t);break;case pF.FORM:formEndTagInBody(e);break;case pF.APPLET:case pF.OBJECT:case pF.MARQUEE:appletEndTagInBody(e,t);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;default:genericEndTagInBody(e,t)}}function eofInBody(e,t){e.tmplInsertionModeStack.length>0?eofInTemplate(e,t):stopParsing(e,t)}function endTagInText(e,t){var n;t.tagID===pF.SCRIPT&&(null===(n=e.scriptHandler)||void 0===n||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function eofInText(e,t){e._err(t,KO.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function characterInTable(e,t){if(void 0!==e.openElements.currentTagId&&sL.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=nL.IN_TABLE_TEXT,t.type){case JO.CHARACTER:characterInTableText(e,t);break;case JO.WHITESPACE_CHARACTER:whitespaceCharacterInTableText(e,t)}else tokenInTable(e,t)}function captionStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_CAPTION}function colgroupStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_COLUMN_GROUP}function colStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(uF.COLGROUP,pF.COLGROUP),e.insertionMode=nL.IN_COLUMN_GROUP,startTagInColumnGroup(e,t)}function tbodyStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_TABLE_BODY}function tdStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(uF.TBODY,pF.TBODY),e.insertionMode=nL.IN_TABLE_BODY,startTagInTableBody(e,t)}function tableStartTagInTable(e,t){e.openElements.hasInTableScope(pF.TABLE)&&(e.openElements.popUntilTagNamePopped(pF.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function inputStartTagInTable(e,t){isHiddenInput(t)?e._appendElement(t,cF.HTML):tokenInTable(e,t),t.ackSelfClosing=!0}function formStartTagInTable(e,t){e.formElement||0!==e.openElements.tmplCount||(e._insertElement(t,cF.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function startTagInTable(e,t){switch(t.tagID){case pF.TD:case pF.TH:case pF.TR:tdStartTagInTable(e,t);break;case pF.STYLE:case pF.SCRIPT:case pF.TEMPLATE:startTagInHead(e,t);break;case pF.COL:colStartTagInTable(e,t);break;case pF.FORM:formStartTagInTable(e,t);break;case pF.TABLE:tableStartTagInTable(e,t);break;case pF.TBODY:case pF.TFOOT:case pF.THEAD:tbodyStartTagInTable(e,t);break;case pF.INPUT:inputStartTagInTable(e,t);break;case pF.CAPTION:captionStartTagInTable(e,t);break;case pF.COLGROUP:colgroupStartTagInTable(e,t);break;default:tokenInTable(e,t)}}function endTagInTable(e,t){switch(t.tagID){case pF.TABLE:e.openElements.hasInTableScope(pF.TABLE)&&(e.openElements.popUntilTagNamePopped(pF.TABLE),e._resetInsertionMode());break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TBODY:case pF.TD:case pF.TFOOT:case pF.TH:case pF.THEAD:case pF.TR:break;default:tokenInTable(e,t)}}function tokenInTable(e,t){const n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,modeInBody(e,t),e.fosterParentingEnabled=n}function whitespaceCharacterInTableText(e,t){e.pendingCharacterTokens.push(t)}function characterInTableText(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function tokenInTableText(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)tokenInTable(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}var aL=new Set([pF.CAPTION,pF.COL,pF.COLGROUP,pF.TBODY,pF.TD,pF.TFOOT,pF.TH,pF.THEAD,pF.TR]);function startTagInCaption(e,t){const n=t.tagID;aL.has(n)?e.openElements.hasInTableScope(pF.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(pF.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=nL.IN_TABLE,startTagInTable(e,t)):startTagInBody(e,t)}function endTagInCaption(e,t){const n=t.tagID;switch(n){case pF.CAPTION:case pF.TABLE:e.openElements.hasInTableScope(pF.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(pF.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=nL.IN_TABLE,n===pF.TABLE&&endTagInTable(e,t));break;case pF.BODY:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TBODY:case pF.TD:case pF.TFOOT:case pF.TH:case pF.THEAD:case pF.TR:break;default:endTagInBody(e,t)}}function startTagInColumnGroup(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.COL:e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.TEMPLATE:startTagInHead(e,t);break;default:tokenInColumnGroup(e,t)}}function endTagInColumnGroup(e,t){switch(t.tagID){case pF.COLGROUP:e.openElements.currentTagId===pF.COLGROUP&&(e.openElements.pop(),e.insertionMode=nL.IN_TABLE);break;case pF.TEMPLATE:templateEndTagInHead(e,t);break;case pF.COL:break;default:tokenInColumnGroup(e,t)}}function tokenInColumnGroup(e,t){e.openElements.currentTagId===pF.COLGROUP&&(e.openElements.pop(),e.insertionMode=nL.IN_TABLE,e._processToken(t))}function startTagInTableBody(e,t){switch(t.tagID){case pF.TR:e.openElements.clearBackToTableBodyContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_ROW;break;case pF.TH:case pF.TD:e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(uF.TR,pF.TR),e.insertionMode=nL.IN_ROW,startTagInRow(e,t);break;case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.TBODY:case pF.TFOOT:case pF.THEAD:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE,startTagInTable(e,t));break;default:startTagInTable(e,t)}}function endTagInTableBody(e,t){const n=t.tagID;switch(t.tagID){case pF.TBODY:case pF.TFOOT:case pF.THEAD:e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE);break;case pF.TABLE:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE,endTagInTable(e,t));break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TD:case pF.TH:case pF.TR:break;default:endTagInTable(e,t)}}function startTagInRow(e,t){switch(t.tagID){case pF.TH:case pF.TD:e.openElements.clearBackToTableRowContext(),e._insertElement(t,cF.HTML),e.insertionMode=nL.IN_CELL,e.activeFormattingElements.insertMarker();break;case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.TBODY:case pF.TFOOT:case pF.THEAD:case pF.TR:e.openElements.hasInTableScope(pF.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY,startTagInTableBody(e,t));break;default:startTagInTable(e,t)}}function endTagInRow(e,t){switch(t.tagID){case pF.TR:e.openElements.hasInTableScope(pF.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY);break;case pF.TABLE:e.openElements.hasInTableScope(pF.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY,endTagInTableBody(e,t));break;case pF.TBODY:case pF.TFOOT:case pF.THEAD:(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(pF.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=nL.IN_TABLE_BODY,endTagInTableBody(e,t));break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:case pF.TD:case pF.TH:break;default:endTagInTable(e,t)}}function startTagInCell(e,t){const n=t.tagID;aL.has(n)?(e.openElements.hasInTableScope(pF.TD)||e.openElements.hasInTableScope(pF.TH))&&(e._closeTableCell(),startTagInRow(e,t)):startTagInBody(e,t)}function endTagInCell(e,t){const n=t.tagID;switch(n){case pF.TD:case pF.TH:e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=nL.IN_ROW);break;case pF.TABLE:case pF.TBODY:case pF.TFOOT:case pF.THEAD:case pF.TR:e.openElements.hasInTableScope(n)&&(e._closeTableCell(),endTagInRow(e,t));break;case pF.BODY:case pF.CAPTION:case pF.COL:case pF.COLGROUP:case pF.HTML:break;default:endTagInBody(e,t)}}function startTagInSelect(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.OPTION:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e._insertElement(t,cF.HTML);break;case pF.OPTGROUP:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e.openElements.currentTagId===pF.OPTGROUP&&e.openElements.pop(),e._insertElement(t,cF.HTML);break;case pF.HR:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop(),e.openElements.currentTagId===pF.OPTGROUP&&e.openElements.pop(),e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.INPUT:case pF.KEYGEN:case pF.TEXTAREA:case pF.SELECT:e.openElements.hasInSelectScope(pF.SELECT)&&(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode(),t.tagID!==pF.SELECT&&e._processStartTag(t));break;case pF.SCRIPT:case pF.TEMPLATE:startTagInHead(e,t)}}function endTagInSelect(e,t){switch(t.tagID){case pF.OPTGROUP:e.openElements.stackTop>0&&e.openElements.currentTagId===pF.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===pF.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===pF.OPTGROUP&&e.openElements.pop();break;case pF.OPTION:e.openElements.currentTagId===pF.OPTION&&e.openElements.pop();break;case pF.SELECT:e.openElements.hasInSelectScope(pF.SELECT)&&(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode());break;case pF.TEMPLATE:templateEndTagInHead(e,t)}}function startTagInSelectInTable(e,t){const n=t.tagID;n===pF.CAPTION||n===pF.TABLE||n===pF.TBODY||n===pF.TFOOT||n===pF.THEAD||n===pF.TR||n===pF.TD||n===pF.TH?(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode(),e._processStartTag(t)):startTagInSelect(e,t)}function endTagInSelectInTable(e,t){const n=t.tagID;n===pF.CAPTION||n===pF.TABLE||n===pF.TBODY||n===pF.TFOOT||n===pF.THEAD||n===pF.TR||n===pF.TD||n===pF.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(pF.SELECT),e._resetInsertionMode(),e.onEndTag(t)):endTagInSelect(e,t)}function startTagInTemplate(e,t){switch(t.tagID){case pF.BASE:case pF.BASEFONT:case pF.BGSOUND:case pF.LINK:case pF.META:case pF.NOFRAMES:case pF.SCRIPT:case pF.STYLE:case pF.TEMPLATE:case pF.TITLE:startTagInHead(e,t);break;case pF.CAPTION:case pF.COLGROUP:case pF.TBODY:case pF.TFOOT:case pF.THEAD:e.tmplInsertionModeStack[0]=nL.IN_TABLE,e.insertionMode=nL.IN_TABLE,startTagInTable(e,t);break;case pF.COL:e.tmplInsertionModeStack[0]=nL.IN_COLUMN_GROUP,e.insertionMode=nL.IN_COLUMN_GROUP,startTagInColumnGroup(e,t);break;case pF.TR:e.tmplInsertionModeStack[0]=nL.IN_TABLE_BODY,e.insertionMode=nL.IN_TABLE_BODY,startTagInTableBody(e,t);break;case pF.TD:case pF.TH:e.tmplInsertionModeStack[0]=nL.IN_ROW,e.insertionMode=nL.IN_ROW,startTagInRow(e,t);break;default:e.tmplInsertionModeStack[0]=nL.IN_BODY,e.insertionMode=nL.IN_BODY,startTagInBody(e,t)}}function endTagInTemplate(e,t){t.tagID===pF.TEMPLATE&&templateEndTagInHead(e,t)}function eofInTemplate(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(pF.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):stopParsing(e,t)}function startTagAfterBody(e,t){t.tagID===pF.HTML?startTagInBody(e,t):tokenAfterBody(e,t)}function endTagAfterBody(e,t){var n;if(t.tagID===pF.HTML){if(e.fragmentContext||(e.insertionMode=nL.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===pF.HTML){e._setEndLocation(e.openElements.items[0],t);const r=e.openElements.items[1];r&&!(null===(n=e.treeAdapter.getNodeSourceCodeLocation(r))||void 0===n?void 0:n.endTag)&&e._setEndLocation(r,t)}}else tokenAfterBody(e,t)}function tokenAfterBody(e,t){e.insertionMode=nL.IN_BODY,modeInBody(e,t)}function startTagInFrameset(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.FRAMESET:e._insertElement(t,cF.HTML);break;case pF.FRAME:e._appendElement(t,cF.HTML),t.ackSelfClosing=!0;break;case pF.NOFRAMES:startTagInHead(e,t)}}function endTagInFrameset(e,t){t.tagID!==pF.FRAMESET||e.openElements.isRootHtmlElementCurrent()||(e.openElements.pop(),e.fragmentContext||e.openElements.currentTagId===pF.FRAMESET||(e.insertionMode=nL.AFTER_FRAMESET))}function startTagAfterFrameset(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.NOFRAMES:startTagInHead(e,t)}}function endTagAfterFrameset(e,t){t.tagID===pF.HTML&&(e.insertionMode=nL.AFTER_AFTER_FRAMESET)}function startTagAfterAfterBody(e,t){t.tagID===pF.HTML?startTagInBody(e,t):tokenAfterAfterBody(e,t)}function tokenAfterAfterBody(e,t){e.insertionMode=nL.IN_BODY,modeInBody(e,t)}function startTagAfterAfterFrameset(e,t){switch(t.tagID){case pF.HTML:startTagInBody(e,t);break;case pF.NOFRAMES:startTagInHead(e,t)}}function nullCharacterInForeignContent(e,t){t.chars=zO,e._insertCharacters(t)}function characterInForeignContent(e,t){e._insertCharacters(t),e.framesetOk=!1}function popUntilHtmlOrIntegrationPoint(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==cF.HTML&&void 0!==e.openElements.currentTagId&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function startTagInForeignContent(e,t){if(causesExit(t))popUntilHtmlOrIntegrationPoint(e),e._startTagOutsideForeignContent(t);else{const n=e._getAdjustedCurrentElement(),r=e.treeAdapter.getNamespaceURI(n);r===cF.MATHML?adjustTokenMathMLAttrs(t):r===cF.SVG&&(adjustTokenSVGTagName(t),adjustTokenSVGAttrs(t)),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,r):e._insertElement(t,r),t.ackSelfClosing=!0}}function endTagInForeignContent(e,t){if(t.tagID===pF.P||t.tagID===pF.BR)return popUntilHtmlOrIntegrationPoint(e),void e._endTagOutsideForeignContent(t);for(let n=e.openElements.stackTop;n>0;n--){const r=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(r)===cF.HTML){e._endTagOutsideForeignContent(t);break}const s=e.treeAdapter.getTagName(r);if(s.toLowerCase()===t.tagName){t.tagName=s,e.openElements.shortenToLength(n);break}}}var cL=null==String.prototype.codePointAt?(e,t)=>55296==(64512&e.charCodeAt(t))?1024*(e.charCodeAt(t)-55296)+e.charCodeAt(t+1)-56320+65536:e.charCodeAt(t):(e,t)=>e.codePointAt(t),lL=new Set([uF.AREA,uF.BASE,uF.BASEFONT,uF.BGSOUND,uF.BR,uF.COL,uF.EMBED,uF.FRAME,uF.HR,uF.IMG,uF.INPUT,uF.KEYGEN,uF.LINK,uF.META,uF.PARAM,uF.SOURCE,uF.TRACK,uF.WBR]);function parse3(e,t){return oL.parse(e,t)}function annotateHtmlSource(e,t){const n=parse3(e,{sourceCodeLocationInfo:!0}),r=new Map,stampsFor=e=>Object.entries(t(e)).map(([e,t])=>{if(!/^[a-z][a-z0-9-]*$/.test(e))throw new Error(`Invalid HTML annotation name: ${e}`);return` ${e}="${escapeAttribute2(t)}"`}).join(""),s=impliedBodyInsertion(n);null!==s&&r.set(s,`<body${stampsFor(s)}>`);const visit2=t=>{if("tagName"in t){const n=t.sourceCodeLocation?.startTag?.startOffset;if(void 0!==n){const t=/^<[^\s/>]+/.exec(e.slice(n));t&&r.set(n+t[0].length,stampsFor(n))}"content"in t&&visit2(t.content)}if("childNodes"in t)for(const e of t.childNodes)visit2(e)};visit2(n);const i=[];let o=0;for(const[t,n]of[...r].sort(([e],[t])=>e-t))i.push(e.slice(o,t),n),o=t;return i.push(e.slice(o)),i.join("")}function impliedBodyInsertion(e){const t=e.childNodes.find(e=>"tagName"in e&&"html"===e.tagName);if(!t||!("childNodes"in t))return null;const n=t.childNodes.find(e=>"tagName"in e&&"body"===e.tagName);if(!n||n.sourceCodeLocation)return null;const r=t.childNodes.find(e=>"tagName"in e&&"head"===e.tagName),s=e.childNodes.find(e=>"#documentType"===e.nodeName);return Math.max(0,s?.sourceCodeLocation?.endOffset??0,t.sourceCodeLocation?.startTag?.endOffset??0,r?.sourceCodeLocation?.endOffset??0)}function escapeAttribute2(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;")}var dL=".tempo-html-paste",uL=[".html",".htm"];function hasHtmlStoryboardEntryExtension(e){const t=e.toLowerCase();return uL.some(e=>t.endsWith(e))}function annotateHtmlStoryboardRevision(e,t){const n=sourceVersionHash(e);return annotateHtmlSource(e,e=>({"data-tempo-filepath":t.filepath,"data-tempo-position":String(e),"data-tempo-modifiedts":String(Math.trunc(t.mtime)),"data-tempo-source-version":n}))}async function authorizeHtmlStoryboardResource(e){const t=await LO(e);if(!(await MO(t)).isFile()||!hasHtmlStoryboardEntryExtension(t))throw new Error("HTML storyboard source must be an existing .html or .htm file");const n=FO.dirname(t);return{filepath:t,authorization:{root:n,entryFile:FO.basename(n)===dL?t:null}}}var pL=new Set([...uL,".css",".js",".mjs",".cjs",".png",".jpg",".jpeg",".gif",".svg",".webp",".avif",".ico",".bmp",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".ogg",".wav",".webm"]);function isWithinRoot2(e,t){const n=FO.relative(e,t);return""===n||!n.startsWith(`..${FO.sep}`)&&".."!==n&&!FO.isAbsolute(n)}async function resolveHtmlStoryboardResource(e,t){if(/%2f|%5c/i.test(t))return{status:400};let n;try{n=decodeURIComponent(t).replace(/^[/\\]+/,"")}catch{return{status:400}}if(!n)return{status:400};if(!pL.has(FO.extname(n).toLowerCase()))return{status:403};const r=FO.resolve(e.root,n);if(!isWithinRoot2(e.root,r))return{status:403};let s;try{s=await LO(r)}catch{return{status:404}}if(!isWithinRoot2(e.root,s)||null!==e.entryFile&&s!==e.entryFile||!pL.has(FO.extname(s).toLowerCase()))return{status:403};try{if(!(await MO(s)).isFile())return{status:404}}catch{return{status:404}}return{status:200,filepath:s}}var hL={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".cjs":"text/javascript",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".bmp":"image/bmp",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".mp3":"audio/mpeg",".mp4":"video/mp4",".ogg":"audio/ogg",".wav":"audio/wav",".webm":"video/webm"};async function openHeadlessHtmlSource(e,t,n=createCaptureImageNormalizer()){const r=await authorizeHtmlStoryboardResource(t),s=await SO(r.filepath,"utf8"),i=annotateHtmlStoryboardRevision(s,{filepath:r.filepath,mtime:(await EO(r.filepath)).mtimeMs}),o=`https://${kO(24).toString("hex")}.tempo-html.invalid`,a=`${o}/${encodeURIComponent(AO.basename(r.filepath))}`,c=new Set,handler=async e=>{const t=e.request(),s=new URL(t.url());if(s.origin!==o)return"file:"===s.protocol||t.isNavigationRequest()?e.abort("blockedbyclient"):e.fallback();const a=await resolveHtmlStoryboardResource(r.authorization,s.pathname);if(200!==a.status)return c.add(`${s.pathname}: ${a.status}`),e.fulfill({status:a.status,body:""});try{const s=a.filepath===r.filepath?i:await SO(a.filepath),o="image"===t.resourceType()&&Buffer.isBuffer(s)?await n(s):s;await e.fulfill({status:200,contentType:o!==s?"image/png":hL[AO.extname(a.filepath).toLowerCase()],headers:{"cache-control":"no-store","content-security-policy":"sandbox allow-scripts allow-same-origin"},body:o})}catch(t){c.add(`${s.pathname}: ${String(t)}`),await e.abort().catch(()=>{})}};return await e.route("**/*",handler),{url:a,assertResources(){if(c.size)throw new Error(`HTML storyboard resources failed: ${[...c].join(", ")}`)},dispose:()=>e.unroute("**/*",handler)}}function astroStoryboardPath(e,t){return`/__tempo/astro/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function astroCaptureUrl(e,t){if("astro"!==t.source?.kind)throw new Error("Expected an Astro document component");return new URL(astroStoryboardPath(t.source.canvasPath,t.storyboardId).slice(1),e.replace(/\/?$/,"/")).href}async function settleAstroDocument(e,t,n){if("astro"!==t.source?.kind)throw new Error("Expected an Astro document component");const r=await e.locator('meta[name="tempo-astro-storyboard"]').getAttribute("content",{timeout:n}),s=r&&JSON.parse(r);if(!s||s.canvasPath!==t.source.canvasPath||s.storyboardId!==t.storyboardId||t.source.revision&&s.revision!==t.source.revision)throw new Error("Astro preview does not match the requested storyboard revision");await e.waitForFunction(mO,void 0,{timeout:n})}var mL="html, :modal, :popover-open, :fullscreen, ::backdrop { opacity: 0 !important; }",fL="__tempoCapturePaintHold";function buildPaintHoldInitScript(){return`(() => {\n if (window.top !== window) return;\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(${JSON.stringify(mL)});\n const adopted = () => document.adoptedStyleSheets.includes(sheet);\n let holding = false;\n // Looked up per call: application code may wrap the prototype's accessor\n // after this script ran, and its wrapper must still see every assignment.\n const native = () =>\n Object.getOwnPropertyDescriptor(Document.prototype, "adoptedStyleSheets");\n Object.defineProperty(document, "adoptedStyleSheets", {\n configurable: true,\n enumerable: true,\n get() {\n return native().get.call(this);\n },\n set(sheets) {\n const next = Array.from(sheets);\n native().set.call(\n this,\n holding && !next.includes(sheet) ? [...next, sheet] : next,\n );\n },\n });\n const hold = () => {\n holding = true;\n if (!adopted()) document.adoptedStyleSheets = document.adoptedStyleSheets;\n };\n hold();\n globalThis.${fL} = {\n hold,\n held: () =>\n adopted() &&\n getComputedStyle(document.documentElement).opacity === "0",\n release: () => {\n holding = false;\n document.adoptedStyleSheets = document.adoptedStyleSheets.filter(\n (other) => other !== sheet,\n );\n },\n };\n})();`}async function holdPaint(e){await e.evaluate(e=>{window[e]?.hold()},fL)}async function releasePaintHold(e){const t=await e.evaluate(async e=>{const t=window[e];return t?t.held()?(t.release(),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),"released"):"lost":"missing"},fL);if("released"!==t)throw new Error("missing"===t?"capture paint hold was never installed in this document":"the page removed the capture paint hold before it settled (document.adoptedStyleSheets was emptied in place, or the root's opacity is forced visible); its pixels would depend on load timing")}var gL='return (function documentVisualReadiness(doc, options) {\n return new Promise(function (resolve) {\n var view = doc.defaultView;\n var failures = [];\n var failedLinks = new WeakMap();\n var checks = new Set();\n var cleanups = new Set();\n var stopped = false;\n var timer;\n var observer;\n var remaining = Math.max(\n 0,\n Math.min(\n options.timeoutMs,\n options.resourceBudget\n ? options.resourceBudget.remainingMs\n : options.timeoutMs,\n ),\n );\n var timerAt;\n var queued = 0;\n var admittedSlice;\n var checksPending = false;\n var checksDirty = false;\n var revision = 0;\n var terminalResolve;\n var terminal = new Promise(function (done) {\n terminalResolve = done;\n });\n function failure(kind, url) {\n if (\n !failures.some(function (item) {\n return item.kind === kind && item.url === url;\n })\n )\n failures.push(url ? { kind: kind, url: url } : { kind: kind });\n }\n function finish(status) {\n if (stopped) return;\n if (status === "ready" && options.onReadyProof) options.onReadyProof();\n if (stopped) return;\n stopped = true;\n if (options.resourceBudget)\n options.resourceBudget.remainingMs = queued\n ? remaining\n : Math.max(\n 0,\n remaining - (timerAt === undefined ? 0 : Date.now() - timerAt),\n );\n clearTimeout(timer);\n if (observer) observer.disconnect();\n for (var cleanup of cleanups) cleanup();\n cleanups.clear();\n checks.clear();\n if (options.signal) options.signal.removeEventListener("abort", cancel);\n terminalResolve();\n resolve({ status: status, failures: failures });\n }\n function cancel() {\n finish("cancelled");\n }\n if (options.signal && options.signal.aborted) {\n cancel();\n return;\n }\n if (!view) {\n cancel();\n return;\n }\n if (options.signal)\n options.signal.addEventListener("abort", cancel, { once: true });\n function startTimer() {\n timerAt = Date.now();\n timer = setTimeout(function () {\n finish("timeout");\n }, remaining);\n }\n startTimer();\n async function work(callback) {\n if (!options.scheduleWork) return callback();\n if (stopped) return;\n if (queued++ === 0) {\n clearTimeout(timer);\n remaining = Math.max(0, remaining - (Date.now() - timerAt));\n }\n try {\n if (\n admittedSlice &&\n admittedSlice.canContinue &&\n admittedSlice.canContinue()\n )\n return callback(admittedSlice);\n return await Promise.race([\n terminal,\n options.scheduleWork(function (slice) {\n admittedSlice = slice;\n if (!stopped) return callback(slice);\n }, options.signal),\n ]);\n } finally {\n if (--queued === 0 && !stopped) startTimer();\n }\n }\n async function mapWork(items, callback) {\n var rows = [];\n var offset = 0;\n while (offset < items.length && !stopped) {\n await work(function (slice) {\n var limit = Math.min(offset + 32, items.length);\n do {\n var value = callback(items[offset++]);\n if (value !== undefined) rows.push(value);\n } while (offset < limit && (!slice || slice.hasTime()));\n });\n }\n return rows;\n }\n if (remaining <= 0) {\n finish("timeout");\n return;\n }\n function changed() {\n if (stopped) return;\n if (!options.scheduleWork) {\n for (var check of checks) check();\n return;\n }\n if (checksPending) {\n checksDirty = true;\n return;\n }\n checksPending = true;\n checksDirty = false;\n mapWork(Array.from(checks), function (check) {\n check();\n })\n .finally(function () {\n checksPending = false;\n if (checksDirty) changed();\n })\n .catch(function () {\n finish("cancelled");\n });\n }\n observer = new view.MutationObserver(function () {\n revision++;\n changed();\n });\n observer.observe(doc, { subtree: true, childList: true, attributes: true });\n // Opt-in admission may begin after a resource\'s terminal event. Preserve\n // its URL-scoped failure evidence while the initial inventory is queued.\n if (options.scheduleWork) {\n var captureError = function (event) {\n var link = event.target;\n if (\n link &&\n link.tagName === "LINK" &&\n link.relList.contains("stylesheet") &&\n applicable(link)\n ) {\n failedLinks.set(link, link.href);\n failure("stylesheet", link.href);\n changed();\n }\n };\n doc.addEventListener("error", captureError, true);\n cleanups.add(function () {\n doc.removeEventListener("error", captureError, true);\n });\n }\n\n function applicable(link) {\n return (\n link.isConnected &&\n !link.disabled &&\n (!link.media || !view.matchMedia || view.matchMedia(link.media).matches)\n );\n }\n function links() {\n return Array.from(doc.querySelectorAll(\'link[rel~="stylesheet"]\')).filter(\n applicable,\n );\n }\n function visibleImage(img) {\n if (!img.isConnected) return false;\n var rect = img.getBoundingClientRect();\n var style = view.getComputedStyle(img);\n return (\n rect.width > 0 &&\n rect.height > 0 &&\n rect.bottom > 0 &&\n rect.right > 0 &&\n rect.top < view.innerHeight &&\n rect.left < view.innerWidth &&\n style.visibility !== "hidden" &&\n style.visibility !== "collapse"\n );\n }\n function images() {\n return Array.from(doc.querySelectorAll("img"))\n .filter(visibleImage)\n .map(function (img) {\n return [img, img.currentSrc, img.src, img.srcset];\n });\n }\n async function scheduledImages() {\n var candidates,\n selected = [],\n offset = 0;\n do {\n await work(function (slice) {\n if (!candidates) candidates = Array.from(doc.querySelectorAll("img"));\n var limit = Math.min(offset + 32, candidates.length);\n while (offset < limit) {\n var img = candidates[offset++];\n if (visibleImage(img))\n selected.push([img, img.currentSrc, img.src, img.srcset]);\n if (slice && !slice.hasTime()) break;\n }\n });\n } while (!stopped && candidates && offset < candidates.length);\n return selected;\n }\n function decodeImage(img) {\n if (!img.isConnected || !visibleImage(img)) return {};\n if (!img.naturalWidth) {\n failure("image", img.currentSrc || img.src);\n return {};\n }\n // A holder keeps a resource decode promise outside CPU admission.\n return {\n decode:\n img.decode &&\n img.decode().catch(function () {\n failure("image", img.currentSrc || img.src);\n }),\n };\n }\n function waitElement(element, ready, kind, url) {\n if (ready()) return Promise.resolve();\n return new Promise(function (done) {\n function requestCheck() {\n if (options.scheduleWork) changed();\n else check();\n }\n function cleanup() {\n element.removeEventListener("load", requestCheck);\n element.removeEventListener("error", error);\n checks.delete(check);\n cleanups.delete(cleanup);\n }\n function check() {\n if (ready()) {\n cleanup();\n done();\n }\n }\n function error() {\n failure(kind, url);\n if (kind === "stylesheet") failedLinks.set(element, url);\n cleanup();\n done();\n }\n cleanups.add(cleanup);\n checks.add(check);\n element.addEventListener("load", requestCheck);\n element.addEventListener("error", error);\n check();\n });\n }\n function inventory(includeImages) {\n return {\n links: links().map(function (link) {\n // Resource evidence can change during a font/image await without\n // changing this node\'s URL or media. Revalidate the same readiness\n // facts, not CSSStyleSheet object identities or a content hash.\n return [\n link,\n link.href,\n link.media,\n !!link.sheet,\n link.getAttribute("data-tempo-stylesheet-pending") === link.href,\n link.getAttribute("data-tempo-stylesheet-error") === link.href,\n ];\n }),\n images: includeImages ? images() : [],\n styles: Array.from(doc.querySelectorAll("style")).map(function (style) {\n return [style, style.textContent];\n }),\n };\n }\n async function scheduledInventory(includeImages) {\n var candidates,\n offset = 0;\n var result = { revision: revision, links: [], images: [], styles: [] };\n // Small inventories finish in one admission. Large ones retain the\n // same 32-node/time bound, without paying a task per resource category.\n do {\n await work(function (slice) {\n if (!candidates)\n candidates = Array.from(\n doc.querySelectorAll(\n includeImages\n ? \'link[rel~="stylesheet"],img,style\'\n : \'link[rel~="stylesheet"],style\',\n ),\n );\n var limit = Math.min(offset + 32, candidates.length);\n while (offset < limit) {\n var node = candidates[offset++];\n if (node.localName === "link" && applicable(node)) {\n result.links.push([\n node,\n node.href,\n node.media,\n !!node.sheet,\n node.getAttribute("data-tempo-stylesheet-pending") ===\n node.href,\n node.getAttribute("data-tempo-stylesheet-error") === node.href,\n ]);\n } else if (node.localName === "img" && visibleImage(node)) {\n result.images.push([\n node,\n node.currentSrc,\n node.src,\n node.srcset,\n ]);\n } else if (node.localName === "style") {\n result.styles.push([node, node.textContent]);\n }\n if (slice && !slice.hasTime()) break;\n }\n });\n } while (!stopped && candidates && offset < candidates.length);\n return result;\n }\n function same(a, b) {\n return ["links", "images", "styles"].every(function (key) {\n return (\n a[key].length === b[key].length &&\n a[key].every(function (row, i) {\n return row.every(function (value, j) {\n return value === b[key][i][j];\n });\n })\n );\n });\n }\n async function run() {\n while (!stopped) {\n var before = options.scheduleWork\n ? await scheduledInventory(false)\n : inventory(false);\n if (stopped) return;\n await Promise.race([\n terminal,\n Promise.all(\n before.links\n .map(function (row) {\n return row[0];\n })\n .map(function (link) {\n if (\n (!link.sheet &&\n (options.failedStylesheetUrls || []).includes(link.href)) ||\n link.getAttribute("data-tempo-stylesheet-error") === link.href\n ) {\n failedLinks.set(link, link.href);\n failure("stylesheet", link.href);\n }\n return waitElement(\n link,\n function () {\n return (\n !applicable(link) ||\n (link.getAttribute("data-tempo-stylesheet-pending") !==\n link.href &&\n (!!link.sheet || failedLinks.get(link) === link.href))\n );\n },\n "stylesheet",\n link.href,\n );\n }),\n ),\n ]);\n if (stopped) return;\n // Force stylesheet application/layout BEFORE reading the current font\n // promise. A previously fulfilled promise cannot certify newly used fonts.\n var readFontPromise = function () {\n if (doc.documentElement) doc.documentElement.getBoundingClientRect();\n // Read the CURRENT promise in the same admitted layout callback.\n return { promise: doc.fonts && doc.fonts.ready };\n };\n var currentFonts = options.scheduleWork\n ? await work(readFontPromise)\n : readFontPromise();\n if (stopped) return;\n var fontPromise = currentFonts.promise;\n var fontRejected = false;\n await Promise.race([\n terminal,\n Promise.resolve(fontPromise).catch(function () {\n fontRejected = true;\n failure("font");\n }),\n ]);\n if (stopped) return;\n // Fonts can change which images are visible. Capture the image evidence\n // only after their layout settles, before awaiting any selected decode.\n var selected = options.scheduleWork\n ? await scheduledImages()\n : images();\n if (stopped) return;\n before.images = selected;\n if (options.scheduleWork) {\n var pendingImages = [],\n pendingLoads = [];\n var imageWaits = await mapWork(selected, function (row) {\n var img = row[0];\n if (img.loading === "lazy") img.loading = "eager";\n // Warm images need no load-event continuation. Prepare their\n // decodes in this bounded batch rather than one new task per image.\n if (img.complete) {\n var proof = decodeImage(img);\n return Promise.race([terminal, Promise.resolve(proof.decode)]);\n }\n pendingImages.push(img);\n pendingLoads.push(\n Promise.race([\n terminal,\n waitElement(\n img,\n function () {\n return (\n !img.isConnected || !visibleImage(img) || img.complete\n );\n },\n "image",\n img.currentSrc || img.src,\n ),\n ]),\n );\n });\n await Promise.race([terminal, Promise.all(pendingLoads)]);\n if (stopped) return;\n // Load events often arrive together from the browser cache. Decode\n // their now-ready images in bounded batches, rather than granting\n // each event its own renderer task. Warm decodes above stay in flight.\n var loadedDecodes = await mapWork(pendingImages, function (img) {\n var proof = decodeImage(img);\n return Promise.race([terminal, Promise.resolve(proof.decode)]);\n });\n await Promise.race([\n terminal,\n Promise.all(imageWaits.concat(loadedDecodes)),\n ]);\n } else {\n await Promise.race([\n terminal,\n Promise.all(\n selected.map(async function (row) {\n var img = row[0];\n if (img.loading === "lazy") img.loading = "eager";\n await Promise.race([\n terminal,\n waitElement(\n img,\n function () {\n return (\n !img.isConnected || !visibleImage(img) || img.complete\n );\n },\n "image",\n img.currentSrc || img.src,\n ),\n ]);\n if (stopped || !img.isConnected || !visibleImage(img)) return;\n if (!img.naturalWidth) {\n failure("image", img.currentSrc || img.src);\n return;\n }\n if (img.decode)\n await img.decode().catch(function () {\n failure("image", img.currentSrc || img.src);\n });\n }),\n ),\n ]);\n }\n if (stopped) return;\n if (doc.fonts)\n doc.fonts.forEach(function (face) {\n if (face.status === "error") failure("font", face.family);\n });\n var after = options.scheduleWork\n ? await scheduledInventory(true)\n : inventory(true);\n if (stopped) return;\n // A scheduled inventory can span multiple tasks. A mutation during\n // its geometry reads cannot certify a mixed document observation.\n if (options.scheduleWork && observer.takeRecords().length) revision++;\n if (\n (!options.scheduleWork ||\n options.requireStableDom === false ||\n (before.revision === after.revision &&\n after.revision === revision)) &&\n same(before, after) &&\n (!doc.fonts ||\n fontRejected ||\n (doc.fonts.status !== "loading" && doc.fonts.ready === fontPromise))\n ) {\n finish("ready");\n return;\n }\n // Let resource events and the deadline run if this document keeps\n // discovering assets; never monopolize the microtask queue.\n await Promise.race([\n terminal,\n new Promise(function (done) {\n var retry = setTimeout(function () {\n cleanups.delete(cleanup);\n done();\n }, 0);\n function cleanup() {\n clearTimeout(retry);\n done();\n }\n cleanups.add(cleanup);\n }),\n ]);\n }\n }\n // Unexpected browser/document loss is not a successful fallback rendering.\n run().catch(function () {\n finish("cancelled");\n });\n });\n})(doc, options);';function buildVisualReadyWaitScript(e,t=[]){return`(function(doc, options) {${gL}})(document, ${JSON.stringify({timeoutMs:e,failedStylesheetUrls:t})})`}function requireVisualReadiness(e,t){if("ready"!==e?.status)throw new Error(`[frame-pool-readiness:${e?.status??"invalid"}] Document assets did not settle`);if(!t)throw new Error("[frame-pool-readiness:timeout] Native asset requests did not settle")}function extractStoryboardDomInPage(e){const readAttributes=e=>{const t={};for(const n of Array.from(e.attributes))/^on/i.test(n.name)||(t[n.name]=n.value);return t},t=document.querySelector(e);if(!t)throw new Error(`storyboard element not found for selector ${e}`);const n=document.head.cloneNode(!0),r=t.cloneNode(!0),s=[t,...Array.from(t.querySelectorAll("*"))],i=[r,...Array.from(r.querySelectorAll("*"))],o=new Map;s.forEach((e,t)=>o.set(e,i[t]));const a=Array.from(document.head.querySelectorAll("*")),c=Array.from(n.querySelectorAll("*"));a.forEach((e,t)=>o.set(e,c[t]));const l=Array.from(document.querySelectorAll("style,link[rel~='stylesheet']"));l.forEach(e=>{const t=o.get(e)??e.cloneNode(!0);o.has(e)||n.appendChild(t);const r=e.sheet;if(r)if(r.disabled)t.parentNode?.removeChild(t);else try{const n=document.createElement("style");for(const t of Array.from(e.attributes))["href","rel","integrity","crossorigin"].includes(t.name)||n.setAttribute(t.name,t.value);let s=Array.from(r.cssRules).map(e=>e.cssText).join("\n");const i=r.href??document.baseURI;s=s.replace(/url\(\s*(['"]?)([^'")]+?)\1\s*\)/gi,(e,t,n)=>{try{return`url("${new URL(n,i).href}")`}catch{return e}}),n.textContent=s,t.parentNode?.replaceChild(n,t)}catch{}});for(const e of Array.from(document.adoptedStyleSheets??[])){if(e.disabled)continue;const t=document.createElement("style");t.textContent=Array.from(e.cssRules).map(e=>e.cssText).join("\n"),n.appendChild(t)}s.forEach((e,t)=>{const n=i[t];e instanceof HTMLInputElement?(n.setAttribute("value",e.value),n.toggleAttribute("checked",e.checked)):e instanceof HTMLTextAreaElement?n.textContent=e.value:e instanceof HTMLOptionElement&&n.toggleAttribute("selected",e.selected)});for(const e of[n,r]){for(const t of Array.from(e.querySelectorAll("script")))t.remove();for(const t of[e,...Array.from(e.querySelectorAll("*"))])for(const e of Array.from(t.attributes))(/^on/i.test(e.name)||/^(href|src|action|formaction)$/i.test(e.name)&&/^\s*javascript:/i.test(e.value))&&t.removeAttribute(e.name)}return{headHtml:n.innerHTML,htmlAttributes:readAttributes(document.documentElement),bodyAttributes:readAttributes(document.body),elementHtml:r.outerHTML}}function assessPageStylesInPage(e){let t=0,n=0;for(const e of Array.from(document.styleSheets))try{t+=e.cssRules.length}catch{n+=1}let r=0;for(const e of Array.from(document.querySelectorAll("style")))r+=(e.textContent??"").length;const s=document.querySelector(e)??document.body;return{authorRuleCount:t,unreadableSheetCount:n,styleTextBytes:r,classElementCount:s.querySelectorAll("[class]").length,inlineStyledElementCount:s.querySelectorAll("[style]").length}}function watchRenderErrorsInPage(e){const t=document.querySelector(e.selector),n=[],record=()=>{if(t)for(const r of Array.from(t.querySelectorAll(e.errorSelector))){const t=r.getAttribute(e.messageAttribute)||"unknown error";n.includes(t)||n.push(t)}};record();const r=new MutationObserver(record);t&&r.observe(t,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[e.messageAttribute]}),window.__tempoCaptureRenderErrors=()=>(r.takeRecords(),r.disconnect(),record(),n)}function readRenderErrorsInPage(){const e=window,t=e.__tempoCaptureRenderErrors;return delete e.__tempoCaptureRenderErrors,t?t():[]}async function inlinePortableHtmlInPage(e){const t=[],warn=e=>{t.push(e)},cssUrlMatcher=()=>/url\(\s*(['"]?)([^'")]+?)\1\s*\)/gi,isPubliclyFetchableUrl=e=>{if("http:"!==e.protocol&&"https:"!==e.protocol)return!1;const t=e.hostname;return!t.endsWith(".tempo-html.invalid")&&("localhost"!==t&&!t.endsWith(".localhost")&&("::1"!==t&&"[::1]"!==t&&"0.0.0.0"!==t&&(!/^127\./.test(t)&&!(/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t)))))},resolveAssetUrl=(e,t)=>{const n=e?.trim();if(!n||n.startsWith("data:")||n.startsWith("#"))return null;try{const e=new URL(n,t);return isPubliclyFetchableUrl(e)?null:e.href}catch{return null}},bytesToBase64=e=>{let t="";const n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)},blobToDataUrl=async(e,t)=>{const n=new Uint8Array(await e.arrayBuffer()),r=e.type||t||"application/octet-stream";return`data:${r};base64,${bytesToBase64(n)}`},inlineCssUrls=async(e,t)=>{const n=new Map;for(const r of e.matchAll(cssUrlMatcher())){const e=r[2].trim(),s=resolveAssetUrl(e,t);s&&n.set(e,s)}if(0===n.size)return e;const r=new Map;return await Promise.all(Array.from(n,async([e,t])=>{try{const n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.blob(),i=s.type||n.headers.get("content-type")||"";r.set(e,await blobToDataUrl(s,i))}catch(e){warn(`failed to inline CSS asset ${t}: ${String(e)}`)}})),0===r.size?e:e.replace(cssUrlMatcher(),(e,t,n)=>{const s=r.get(n.trim());return s?`url("${s}")`:e})},n=(new DOMParser).parseFromString(e.html,"text/html"),r=n.querySelector("base[href]")?.getAttribute("href")??e.baseUrl;await Promise.all(Array.from(n.querySelectorAll("style")).map(async e=>{const t=e.textContent??"";t.includes("url(")&&(e.textContent=await inlineCssUrls(t,r))})),await Promise.all(Array.from(n.querySelectorAll('[style*="url("]')).map(async e=>{const t=e.getAttribute("style");t&&e.setAttribute("style",await inlineCssUrls(t,r))})),await Promise.all(Array.from(n.querySelectorAll('link[rel~="stylesheet"][href]')).map(async e=>{const t=resolveAssetUrl(e.getAttribute("href"),r);if(t)try{const r=await fetch(t);if(!r.ok)throw new Error(`HTTP ${r.status}`);const s=await inlineCssUrls(await r.text(),t),i=n.createElement("style");i.setAttribute("data-tempo-inlined-stylesheet","true");const o=e.getAttribute("media");o&&i.setAttribute("media",o),i.textContent=s,e.replaceWith(i)}catch(e){warn(`failed to inline stylesheet ${t}: ${String(e)}`)}})),await Promise.all(Array.from(n.querySelectorAll("img[src]")).map(async e=>{const t=resolveAssetUrl(e.getAttribute("src"),r);if(t)try{const n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);const r=await n.blob(),s=r.type||n.headers.get("content-type")||"";if(!s.toLowerCase().startsWith("image/"))return;e.setAttribute("src",await blobToDataUrl(r,s)),e.removeAttribute("srcset"),e.setAttribute("loading","eager"),e.setAttribute("decoding","sync")}catch(e){warn(`failed to inline image ${t}: ${String(e)}`)}}));for(const e of Array.from(n.querySelectorAll("script")))e.remove();const s=n.querySelector("base[href]");return s&&resolveAssetUrl(s.getAttribute("href"),e.baseUrl)&&s.remove(),{html:`<!DOCTYPE html>${n.documentElement.outerHTML}`,warnings:t}}function installRenderProfileInPage(){const e=window;performance.setResourceTimingBufferSize(1e4);const readTargetSelector=()=>{const e=new URLSearchParams(window.location.search),t=e.get("canvasPath")?.trim()??e.get("pageFile")?.trim(),n=e.get("storyboardId")?.trim()??e.get("exportName")?.trim();if(!t||!n)return"";const r=`canvas:${encodeURIComponent(t)}#storyboard:${encodeURIComponent(n)}`;return`[data-tempo-storyboard-render-id=${JSON.stringify(r)}]`},t={startedAtMs:performance.now(),fullNavigation:!0,targetSelector:readTargetSelector(),targetAttachedMs:null,reactInjectedMs:null,reactCommits:[],longTaskCount:0,longTaskDurationMs:0,begin(e){this.startedAtMs=performance.now(),this.fullNavigation=!1,this.targetSelector=e,this.targetAttachedMs=null,this.reactInjectedMs=null,this.reactCommits=[],this.longTaskCount=0,this.longTaskDurationMs=0}};e.__tempoCaptureRenderProfile=t;const markTargetAttached=()=>{null===t.targetAttachedMs&&t.targetSelector&&document.querySelector(t.targetSelector)&&(t.targetAttachedMs=performance.now()-t.startedAtMs)};markTargetAttached(),new MutationObserver(markTargetAttached).observe(document,{childList:!0,subtree:!0});try{new PerformanceObserver(e=>{for(const n of e.getEntries())t.longTaskCount+=1,t.longTaskDurationMs+=n.duration}).observe({type:"longtask",buffered:!0})}catch{}if(e.__REACT_DEVTOOLS_GLOBAL_HOOK__)return;let n=0;const r=new Map;e.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,renderers:r,inject:e=>(t.reactInjectedMs??=performance.now()-t.startedAtMs,n+=1,r.set(n,e),n),onCommitFiberRoot(e,n){const r=n.current;t.reactCommits.push({atMs:performance.now()-t.startedAtMs,actualDurationMs:"number"==typeof r?.actualDuration?r.actualDuration:0})},onCommitFiberUnmount(){},checkDCE(){},onScheduleFiberRoot(){}}}function readRenderProfileInPage(e){const t=window,n=t.__tempoCaptureRenderProfile,r=n?.startedAtMs??0,s=performance.getEntriesByType("navigation")[0],i=performance.getEntriesByType("resource").filter(e=>e.startTime>=r),o=`/${e.replace(/^tempo\//,"")}`,a=i.filter(e=>{const t=new URL(e.name).pathname;return t.includes("/designs/")&&t.includes(".canvas")}),c=a.find(e=>new URL(e.name).pathname===o),l=i.filter(e=>"script"===e.initiatorType),d=n?.reactCommits??[];return{domContentLoadedMs:n?.fullNavigation?s?.domContentLoadedEventEnd??0:0,targetAttachedMs:n?.targetAttachedMs??performance.now()-r,targetModuleLoadedMs:c?c.responseEnd-r:0,lastCanvasModuleLoadedMs:Math.max(0,...a.map(e=>e.responseEnd-r)),lastScriptLoadedMs:Math.max(0,...l.map(e=>e.responseEnd-r)),reactInjectedMs:n?.reactInjectedMs??0,reactFirstCommitMs:d[0]?.atMs??0,reactLastCommitMs:d[d.length-1]?.atMs??0,reactCommitWorkMs:d.reduce((e,t)=>e+t.actualDurationMs,0),reactCommitCount:d.length,longTaskCount:n?.longTaskCount??0,longTaskDurationMs:n?.longTaskDurationMs??0,requestCount:i.length,scriptRequestCount:l.length,canvasModuleRequestCount:a.length,unrelatedCanvasModuleRequestCount:a.filter(e=>new URL(e.name).pathname!==o).length}}import{parseSync as yL}from"oxc-parser";var bL=`(?:${['"',"'","`"].map(e=>String.raw`${e}(?:[^${e}\\]|\\.)*${e}`).join("|")})`,vL=new RegExp(String.raw`\bcanvasPath:\s*(${bL})\s*,\s*load:\s*\(\)\s*=>\s*import\(\s*(${bL})\s*\)`,"g");function escapeForRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var wL={n:"\n",t:"\t",r:"\r",b:"\b",f:"\f",v:"\v",0:"\0","\n":""};function readLiteral(e){const t=e.trim(),n=t[0];if(t.length<2||t[t.length-1]!==n)return;if('"'!==n&&"'"!==n&&"`"!==n)return;const r=t.slice(1,-1);for(let e=0;e<r.length;e+=1)if("\\"===r[e])e+=1;else{if(r[e]===n)return;if("`"===n&&r.startsWith("${",e))return}return r.replace(/\\(u\{[\da-fA-F]+\}|u[\da-fA-F]{4}|x[\da-fA-F]{2}|[\s\S])/g,(e,t)=>t.length>1?String.fromCodePoint(Number.parseInt(t.replace(/[ux{}]/g,""),16)):wL[t]??t)}function readStyleId(e,t){const n=e.lastIndexOf(`${t}(`);if(n<0)return;const r=new RegExp(String.raw`^\s*(${bL}|[A-Za-z_$][\w$]*)\s*,`).exec(e.slice(n+t.length+1))?.[1];if(!r)return;if(/^["'`]/.test(r))return readLiteral(r);const s=new RegExp(String.raw`\b(?:const|let|var)\s+${escapeForRegExp(r)}\s*=\s*(${bL})`).exec(e)?.[1];return s?readLiteral(s):void 0}function readServedModule(e){let t;try{t=yL("module.js",e,{lang:"js",sourceType:"module"})}catch{return null}if(t.errors.length>0)return null;const{staticImports:n,staticExports:r,dynamicImports:s}=t.module,i=[...n.map(e=>({start:e.start,request:e.moduleRequest.value})),...r.flatMap(e=>{const t=e.entries.find(e=>e.moduleRequest)?.moduleRequest?.value;return void 0===t?[]:[{start:e.start,request:t}]})].sort((e,t)=>e.start-t.start),o=[];let a=0;for(const{moduleRequest:t}of s){const n=readLiteral(e.slice(t.start,t.end));void 0===n?a+=1:o.push(n)}const c=n.flatMap(e=>e.entries).find(e=>"updateStyle"===e.importName.name)?.localName.value,l=c?readStyleId(e,c):void 0,d=[];for(const t of e.matchAll(vL)){const e=readLiteral(t[1]),n=readLiteral(t[2]);void 0!==e&&void 0!==n&&d.push({canvasPath:e,request:n})}return{staticRequests:i.map(e=>e.request),dynamicRequests:o,computedImports:a,...void 0===l?{}:{styleId:l},canvasLoaders:d}}var fetchServedModule=async e=>{let t;try{t=await fetch(e,{headers:{accept:"*/*"},signal:AbortSignal.timeout(3e4)})}catch(e){return{status:"failed",reason:e instanceof Error?e.message:String(e)}}try{return 404===t.status?{status:"missing"}:t.ok?/(?:java|ecma)script/i.test(t.headers.get("content-type")??"")?{status:"ok",source:await t.text()}:{status:"not-a-module"}:{status:"failed",reason:`HTTP ${t.status}`}}catch(e){return{status:"failed",reason:e instanceof Error?e.message:String(e)}}finally{t.bodyUsed||await(t.body?.cancel().catch(()=>{}))}};function resolveModuleRequest(e,t){if(!/^(?:\.{0,2}\/|[A-Za-z][A-Za-z\d+.-]*:)/.test(e))return null;let n,r;try{r=new URL(t),n=new URL(e,r)}catch{return null}return"http:"!==n.protocol&&"https:"!==n.protocol||n.origin!==r.origin?null:(n.hash="",n.href)}function insertsNothing(e){const{searchParams:t}=new URL(e);return["raw","url","inline","worker","sharedworker"].some(e=>t.has(e))}function computesOnlyItsOwnTargets(e){const{pathname:t}=new URL(e);return/(?:^|\/)node_modules\//.test(t)||/(?:^|\/)@(?:vite|react-refresh|id|tempo)(?:\/|$)/.test(t)}var _L=5e4;function createModuleGraph(e=fetchServedModule,t={}){const n=Math.max(1,t.concurrency??24),r=t.moduleLimit??_L,s=new Map,i=new Map;let o=0;const a=[],limited=async e=>{o>=n?await new Promise(e=>a.push(e)):o+=1;try{return await e()}finally{const e=a.shift();e?e():o-=1}},toNode=(e,t)=>{const n=readServedModule(t);if(!n)return{kind:"unknown",reason:"it does not parse"};const resolve6=t=>t.flatMap(t=>resolveModuleRequest(t,e)??[]);return{kind:"module",module:n,statics:resolve6(n.staticRequests),dynamics:resolve6(n.dynamicRequests)}},remember=(e,t)=>(s.set(e,t),t.then(t=>i.set(e,t)),t),read2=t=>{const n=s.get(t);if(n)return n;if(insertsNothing(t))return remember(t,Promise.resolve({kind:"leaf"}));if(s.size>=r){const e={kind:"unknown",reason:`more than ${r} modules`};return i.set(t,e),Promise.resolve(e)}return remember(t,limited(async()=>{const n=await e(t).catch(e=>({status:"failed",reason:e instanceof Error?e.message:String(e)}));return"failed"===n.status?{kind:"unknown",reason:n.reason}:"ok"!==n.status?{kind:"leaf"}:toNode(t,n.source)}))},reach=async(e,t,n)=>{const r=new Set;let s=[...e];for(;s.length>0;){const e=s.filter(e=>!r.has(e)&&!t.has(e));for(const t of e)r.add(t);const i=await Promise.all(e.map(read2));for(const[t,r]of i.entries())n?.(e[t],r);s=[...new Set(i.flatMap(e=>"module"===e.kind?[...e.statics,...e.dynamics]:[]))]}},evaluationOrder=(e,t,n)=>{const r=[];for(const s of e){const e=[],enter=r=>{n.has(r)||t.has(r)||(n.add(r),e.push({url:r,next:0}))};for(enter(s);e.length>0;){const t=e[e.length-1],n=i.get(t.url),s="module"===n?.kind?n.statics:[];t.next<s.length?(t.next+=1,enter(s[t.next-1])):(e.pop(),r.push(t.url))}}return r};return{define(e,t){const n=toNode(e,t);s.set(e,Promise.resolve(n)),i.set(e,n)},async canvasLoaders(e){const t=new Map,n=new Set;return await reach(e,n,(e,r)=>{if("module"===r.kind)for(const{canvasPath:s,request:i}of r.module.canvasLoaders){const r=resolveModuleRequest(i,e);r&&(t.set(s,r),n.add(r))}}),t},async styles(e,t={}){const n=t.stopAt??new Set;await reach(e,n);const r=new Set,s=[],o=[],a=new Set,c=new Set,visit2=(e,s)=>{const o=[];for(const l of evaluationOrder(e,n,c)){const e=i.get(l);if("leaf"===e?.kind)continue;if("module"!==e?.kind){r.add(`${l} could not be read: ${e?.reason??"not asked"}`);continue}const{module:n}=e;void 0===n.styleId||a.has(n.styleId)||(a.add(n.styleId),s.push(n.styleId)),t.computedImportsAreGaps&&n.computedImports>0&&!computesOnlyItsOwnTargets(l)&&r.add(`${l} computes the target of an import()`),o.push(...e.dynamics)}return o};let l=visit2(e,s);for(;l.length>0;)l=visit2(l,o);return{evaluated:s,deferred:o,gaps:[...r]}}}}var xL={document:"reuse",disable:[],order:[]};function canvasKey(e){return e.trim().replace(/\\/g,"/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function createStyleIsolation(e={}){const summarize2=e=>e.length>1?`${e[0]} (and ${e.length-1} more)`:e[0],startReading=()=>({graph:createModuleGraph(e.fetchModule),canvases:new Map});let t=startReading();const n=new Set,readHost=async({graph:e},t)=>{if(t.importMap)return{readable:!1,reason:"the host document has an import map"};const n=[];t.scripts.forEach((r,s)=>{if("src"in r){const e=resolveModuleRequest(r.src,t.documentUrl);return void(e&&n.push(e))}const i=new URL(t.documentUrl);i.hash=`tempo-inline-module-${s}`,e.define(i.href,r.text),n.push(i.href)});const r=await e.canvasLoaders(n),s=await e.styles(n,{stopAt:new Set(r.values())});return s.gaps.length>0?{readable:!1,reason:summarize2(s.gaps)}:{readable:!0,styles:new Set([...s.evaluated,...s.deferred]),canvases:new Map([...r].map(([e,t])=>[canvasKey(e),t]))}},hostOf=(e,t)=>(e.host||(e.host=readHost(e,t)),e.host),readCanvas=async({graph:e},t,n)=>{const r=n.canvases.get(canvasKey(t));if(!r)return{listed:!1};const s=await e.styles([r],{computedImportsAreGaps:!0});return{listed:!0,url:r,closure:s,all:new Set([...s.evaluated,...s.deferred])}};return{async plan({read:e,rendered:r,next:s}){const i=[...new Set(r)].filter(e=>canvasKey(e)!==canvasKey(s));if(0===i.length)return xL;const o=await e().catch(()=>{});if(!o||0===o.styles.length)return xL;let a=t,c=await hostOf(a,o);if(c.readable&&c.canvases.size>0&&!c.canvases.has(canvasKey(s))&&!n.has(canvasKey(s))&&(n.add(canvasKey(s)),t===a&&(t=startReading()),a=t,c=await hostOf(a,o)),!c.readable)return{document:"new",reason:`the host's modules could not be read: ${c.reason}`};const l=c,d=o.styles.filter(e=>!l.styles.has(e));if(0===d.length)return xL;const stylesOf=e=>{const t=canvasKey(e);let n=a.canvases.get(t);return n||(n=readCanvas(a,e,l),a.canvases.set(t,n)),n},u=await stylesOf(s);if(!u.listed)return{document:"new",reason:"the host wrapper does not list the canvas"};if(u.closure.gaps.length>0)return{document:"new",reason:`what the canvas imports is not fully known: ${summarize2(u.closure.gaps)}`};const p=new Set(u.closure.evaluated),m=new Set(u.closure.deferred),f=new Set;for(const e of await Promise.all(i.map(stylesOf)))if(e.listed)for(const t of e.all)f.add(t);const g=[];for(const e of d)if(!p.has(e)){if(m.has(e))return{document:"new",reason:`the document already holds ${e}, which the canvas loads only on demand`};if(!f.has(e))return{document:"new",reason:`the document holds ${e}, which no canvas it rendered is known to import`};g.push(e)}return{document:"reuse",preload:u.url,disable:g,order:u.closure.evaluated.filter(e=>!l.styles.has(e))}},forget(){t=startReading(),n.clear()}}}function installCaptureStylesInPage(){const viteStyles=()=>Array.from(document.querySelectorAll("style[data-vite-dev-id]")),idOf=e=>e.getAttribute("data-vite-dev-id")??"",e={read:()=>({documentUrl:document.baseURI,importMap:null!==document.querySelector('script[type="importmap"]'),scripts:Array.from(document.querySelectorAll('script[type="module"]')).map(e=>e.src?{src:e.src}:{text:e.textContent??""}),styles:viteStyles().map(idOf)}),async arrange(e){const t=new Map(e.map((e,t)=>[e,t])),n=viteStyles().filter(e=>t.has(idOf(e))),r=[...n].sort((e,n)=>t.get(idOf(e))-t.get(idOf(n)));if(r.every((e,t)=>n[t]===e))return{reordered:!1};const s=r.map(e=>new Promise(t=>{e.addEventListener("load",()=>t(),{once:!0}),e.addEventListener("error",()=>t(),{once:!0})})),i=document.createComment("");n[0].before(i);for(const e of r)i.before(e);return i.remove(),await Promise.all(s),{reordered:!0}},toggle(e){const t=new Set(e);let n=0;for(const e of viteStyles()){const r=t.has(idOf(e));r&&(n+=1),e.disabled!==r&&(e.disabled=r)}return{disabled:n}}};window.__tempoCaptureStyles=e}function buildCanvasPreloadScript(e,t){return`(async (url, selector) => {\n window.__tempoResetCaptureDeterminism?.();\n window.__tempoCaptureRenderProfile?.begin(selector);\n try {\n await import(url);\n } catch {}\n})(${JSON.stringify(e)}, ${JSON.stringify(t)})`}function storyboardRenderId(e,t){return buildCanvasStoryboardRenderId(e,t)}function buildDirectRenderUrl2(e,t){return buildDirectRenderUrl(e,{canvasPath:t.hostCanvasPath,storyboardId:t.storyboardId,width:t.width,height:t.height})}function sha256Hex(e){return iO("sha256").update(e).digest("hex")}function looksBlank(e){let t;try{t=oO.PNG.sync.read(Buffer.from(e))}catch{return!0}for(let e=0;e<t.data.length;e+=4){const n=t.data[e+3];if(0!==n&&(255!==t.data[e]||255!==t.data[e+1]||255!==t.data[e+2]))return!1}return!0}var TL=42e4,kL=`[${WN}]`,SL=class extends Error{constructor(e){super(e),this.code="content-unavailable",this.name="ContentUnavailableError"}},EL=3840,AL=12e3,CL=2;function sizesItsViewport(e,t){const n=void 0!==e.width&&void 0!==e.height;return!0===e.responsive&&!n&&void 0===t.viewport}async function fitViewportToStoryboard(e,t,n){for(let r=0;r<CL;r++){const r=await e.locator(t).evaluate(e=>{const t=e.getBoundingClientRect();return{width:Math.ceil(t.width),height:Math.ceil(t.height)}});if(r.width<=0||r.height<=0)return;const s={width:Math.min(r.width,EL),height:Math.min(r.height,AL)},i=e.viewportSize(),o=i?.width===s.width&&i.height===s.height;if(o)return;await e.setViewportSize(s),await n()}}async function settleCapturePage(e,t,n){await settlePage(e,t,n);const r=n?.contentUnavailableTimeoutMs??TL,s=Date.now()+r;for(;await e.locator(t).locator(kL).count();){try{await e.waitForFunction(({selector:e,unavailable:t})=>{const n=document.querySelector(e);return n&&!n.querySelector(t)},{selector:t,unavailable:kL},{timeout:Math.max(1,s-Date.now())})}catch(e){if(!(e instanceof Error)||"TimeoutError"!==e.name)throw e;throw new SL(`Storyboard content remained unavailable after ${r}ms. Check the Flutter devserver compile log or the external content producer; increase contentUnavailableTimeoutMs for a slower cold build.`)}await settlePage(e,t,n)}await alignCaptureSubframeFonts(e)&&await settlePage(e,t,n)}function isPageGoneError(e){return/Target closed|Target page, context or browser has been closed|Page closed|Target crashed/.test(e)}function isBrowserGoneError(e){return/Browser has been closed|Browser closed|browser has disconnected|Browser process crashed/.test(e)}var IL=new WeakSet;function markNavigated(e,t){t&&null!==e&&"object"==typeof e&&IL.add(e)}function readNavigatedMark(e){return null!==e&&"object"==typeof e&&IL.has(e)}function documentReplaced(e,t,n){return t.navigationRequests>e.navigationRequests+n||t.documentCommits>e.documentCommits+n}var PL=3;function decideBoardRetry(e,t,n=PL){if("content-unavailable"===e.status)return"accept";if(t>=n-1)return"accept";if("render-error"===e.status){const t=e.error??"";return isBrowserGoneError(t)?"accept":isPageGoneError(t)?"retry-fresh-worker":e.navigated||isNavigationInterruptedError(t)?"retry":"accept"}return e.navigated?"retry":"accept"}function navigatedRejectionError(e){return`document reloaded during every attempt (${e}); the capture never saw one stable document`}function finalizeAcceptedAttempt(e,t){const{result:n}=e;return e.navigated&&"render-error"!==n.status&&"content-unavailable"!==n.status?{canvasPath:n.canvasPath,storyboardId:n.storyboardId,status:"render-error",error:navigatedRejectionError(t),timings:n.timings}:"render-error"===n.status&&t>1?{...n,error:`after ${t} attempts: ${n.error}`}:n}function reloadStormWindowFor(e){return Math.max(8,4*Math.max(1,Math.floor(e)))}function isReloadStorm(e,t){return!(e.length<t)&&e.slice(-t).every(Boolean)}var DL=class extends Error{constructor(){super(...arguments),this.name="CaptureReloadStormError"}};function describeRetryReason(e){return"render-error"===e.status&&isPageGoneError(e.error??"")?"page closed mid-capture":"document reloaded mid-capture"}async function within(e,t){let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(void 0),e)})])}finally{clearTimeout(n),t.catch(()=>{})}}var RL=5,NL=GN;function captureViewportFor(e,t){return t.viewport??(e.width&&e.height?{width:Math.ceil(e.width),height:Math.ceil(e.height)}:NL)}async function startCaptureSession(e){const t=e.log??(()=>{}),n=e.parallelPages??1,r=!1===e.styleIsolation?void 0:createStyleIsolation(),s=createCaptureImageNormalizer(),{chromium:i}=await(import("playwright"));let o;try{o=await i.launch({args:bO})}catch(e){if(!isMissingBrowserError(e)||autoInstallDisabled())throw e;t("[capture] Chromium is not installed — downloading it now (one-time, ~2 min)"),await installChromium(t),o=await i.launch({args:bO})}const{fingerprint:a}=buildEnvFingerprint({os:process.platform,browserVersion:o.version()}),browserGoneError=e=>new Error(`capture browser is gone; cannot open a fresh page: ${e}`),createCaptureWorker=async t=>{const n=Date.now(),i=await o.newContext({deviceScaleFactor:t.deviceScaleFactor??yO,viewport:t.viewport??NL,reducedMotion:"reduce",colorScheme:"light",timezoneId:"UTC",locale:"en-US",serviceWorkers:"block"});process.env.TEMPO_SDK_RUNTIME_PATH&&await i.addInitScript(await readBrowserRuntimeScript()),await i.addInitScript(buildPaintHoldInitScript()),await i.addInitScript(buildFreezeInitScript()),await i.addInitScript(installRenderProfileInPage),r&&await i.addInitScript(installCaptureStylesInPage);const a=await i.newPage(),c=await installCaptureImages(a,s,{requestLatencyMs:t.requestLatencyMs}),l=await i.newCDPSession(a),d={context:i,page:a,images:c,contextMs:Date.now()-n,contextClaimed:!1,hasNavigated:!1,renderedCanvasPaths:new Set,counters:{navigationRequests:0,documentCommits:0},documentsLoaded:0,navigationsInFlight:0,async dispose(){await c.dispose(),await l.detach().catch(()=>{}),await a.close().catch(()=>{}),await i.close().catch(()=>{})}},isMainFrameNavigation=e=>{try{return e.isNavigationRequest()&&e.frame()===a.mainFrame()}catch{return!1}};return a.on("request",e=>{isMainFrameNavigation(e)&&(e.redirectedFrom()||(d.counters.navigationRequests+=1,d.navigationsInFlight+=1))}),a.on("requestfailed",e=>{isMainFrameNavigation(e)&&(d.navigationsInFlight=Math.max(0,d.navigationsInFlight-1))}),l.on("Page.frameNavigated",({frame:e})=>{e.parentId||(d.counters.documentCommits+=1)}),await l.send("Page.enable"),await alignCaptureFonts(l),a.on("domcontentloaded",()=>{d.documentsLoaded+=1,d.navigationsInFlight=0,d.hasNavigated&&(a.addStyleTag({content:cO}).catch(()=>{}),d.renderedCanvasPaths=new Set(d.currentCanvasPath?[d.currentCanvasPath]:[]),r?.forget())}),e.timing?.recordBoard("context",d.contextMs),d},planStyles=async(n,s)=>{if(!r||!n.hasNavigated)return;const i=Date.now();try{return await r.plan({read:()=>n.page.evaluate(()=>window.__tempoCaptureStyles?.read()),rendered:n.renderedCanvasPaths,next:s})}catch(e){return t(`[capture] ${s}: stylesheets not isolated: ${e instanceof Error?e.message:String(e)}`),{document:"reuse",disable:[],order:[]}}finally{e.timing?.recordBoard("style-isolation",Date.now()-i)}},sleep6=e=>new Promise(t=>setTimeout(t,e)),awaitDocumentQuiet=async(e,t)=>{const n=500,r=Date.now()+Math.min(t,1e4),settleLoad=async()=>{for(;e.navigationsInFlight>0&&Date.now()<r;)await sleep6(50);await e.page.waitForLoadState("load",{timeout:Math.max(1,r-Date.now())}).catch(()=>{})};await settleLoad();let s=e.counters.navigationRequests,i=Date.now();for(;Date.now()<r;)if(await sleep6(100),e.counters.navigationRequests!==s||e.navigationsInFlight>0)s=e.counters.navigationRequests,i=Date.now(),await settleLoad();else if(Date.now()-i>=n)return},withSettledStoryboard=async(t,n,r,i,o,a)=>{const c=captureViewportFor(t,n);if("html"===t.source?.kind||"astro"===t.source?.kind){const o=await createCaptureWorker({...n,viewport:c});r.contextMs=o.contextMs;try{const a="html"===t.source.kind?await openHeadlessHtmlSource(o.context,t.source.filepath,s):{url:astroCaptureUrl(await(e.getAppUrl?.()??Promise.reject(new Error("Astro component capture requires the app dev server"))),t),assertResources(){}},c=new Set;o.page.on("pageerror",e=>c.add(e.message)),o.page.on("response",e=>{e.status()>=400&&c.add(`${e.status()} ${e.url()}`)}),o.page.on("requestfailed",e=>c.add(`${e.failure()?.errorText} ${e.url()}`));const l={...o.counters},d=Date.now(),u=await o.page.goto(a.url,{waitUntil:"load",timeout:n.settleTimeoutMs??e.settleTimeoutMs??3e4});if("astro"===t.source.kind){if(!u?.ok())throw new Error(`Astro storyboard returned HTTP ${u?.status()}`);await settleAstroDocument(o.page,t,n.settleTimeoutMs??e.settleTimeoutMs??3e4)}r.navigateMs=Date.now()-d,await o.page.addStyleTag({content:cO});const p=Date.now();await settleCapturePage(o.page,"body",{timeoutMs:n.settleTimeoutMs??e.settleTimeoutMs??3e4,contentUnavailableTimeoutMs:n.contentUnavailableTimeoutMs??e.contentUnavailableTimeoutMs});const m=await o.page.evaluate(buildVisualReadyWaitScript(n.settleTimeoutMs??e.settleTimeoutMs??3e4));if(requireVisualReadiness(m,!0),m.failures.length)throw new Error(`HTML storyboard visual resources failed: ${JSON.stringify(m.failures)}`);if(a.assertResources(),"astro"===t.source.kind&&c.size)throw new Error(`Astro storyboard failed: ${[...c].join("; ")}`);r.settleMs=Date.now()-p,o.images.assertHealthy(),await releasePaintHold(o.page);const f=await i(o.page,"body");if(o.images.assertHealthy(),a.assertResources(),"astro"===t.source.kind&&c.size)throw new Error(`Astro storyboard failed: ${[...c].join("; ")}`);if(o.page.url()!==a.url)throw new Error("HTML storyboard navigated away from its accepted source");return{value:f,navigated:documentReplaced(l,o.counters,1)}}finally{await o.dispose()}}const l=storyboardRenderId(t.hostCanvasPath,t.storyboardId),d=buildStoryboardRenderSelector(l),u=void 0===o,p=o??await createCaptureWorker({...n,viewport:c}),{page:m}=p;p.contextClaimed||(r.contextMs=p.contextMs,p.contextClaimed=!0);const f={...p.counters},g=p.hasNavigated?0:1,navigatedSinceStart=()=>documentReplaced(f,p.counters,g);try{const s=Date.now();try{p.hasNavigated&&(await holdPaint(m),await p.images.forgetLoadedImages());const r=m.viewportSize();r?.width===c.width&&r?.height===c.height||await m.setViewportSize(c);const s=buildDirectRenderUrl2(e.hostUrl,t);if(p.hasNavigated){if(p.currentSelector===d&&(await m.evaluate(e=>{history.replaceState(history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:history.state}))},buildDirectRenderIdleUrl(e.hostUrl)),await m.waitForSelector(p.currentSelector,{state:"detached",timeout:n.settleTimeoutMs??e.settleTimeoutMs??3e4})),a?.preload){const t=n.settleTimeoutMs??e.settleTimeoutMs??3e4;await within(t,m.evaluate(buildCanvasPreloadScript(a.preload,d)));const r=await within(t,m.evaluate(e=>window.__tempoCaptureStyles?.arrange(e),a.order));r?.reordered&&e.timing?.recordBoard("style-isolation.reordered",1,"count")}await m.evaluate(({url:e,nextSelector:t,styles:n})=>{const r=window;n&&r.__tempoCaptureStyles?.toggle(n.disable),r.__tempoResetCaptureDeterminism?.(),n?.preload||r.__tempoCaptureRenderProfile?.begin(t),history.replaceState(history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:history.state}))},{url:s,nextSelector:d,styles:a})}else await m.goto(s,{waitUntil:"domcontentloaded"}),await m.addStyleTag({content:cO}),p.hasNavigated=!0;p.currentSelector=d,p.currentCanvasPath=t.hostCanvasPath,p.renderedCanvasPaths.add(t.hostCanvasPath)}finally{r.navigateMs=Date.now()-s,e.timing?.recordBoard("navigate",r.navigateMs)}const o=Date.now(),settle=()=>settleCapturePage(m,d,{timeoutMs:n.settleTimeoutMs??e.settleTimeoutMs??3e4,contentUnavailableTimeoutMs:n.contentUnavailableTimeoutMs??e.contentUnavailableTimeoutMs,onStep:(t,n)=>e.timing?.recordBoard(`settle.${t}`,n)});try{await settle(),sizesItsViewport(t,n)&&await fitViewportToStoryboard(m,d,settle)}finally{r.settleMs=Date.now()-o,e.timing?.recordBoard("settle",r.settleMs)}const l=await m.evaluate(readRenderProfileInPage,t.hostCanvasPath);e.timing?.recordBoard("render.dom-content-loaded",l.domContentLoadedMs),e.timing?.recordBoard("render.react-injected",l.reactInjectedMs),e.timing?.recordBoard("render.react-first-commit",l.reactFirstCommitMs),e.timing?.recordBoard("render.react-last-commit",l.reactLastCommitMs),e.timing?.recordBoard("render.react-commit-work",l.reactCommitWorkMs),e.timing?.recordBoard("render.target-module",l.targetModuleLoadedMs),e.timing?.recordBoard("render.target-attached",l.targetAttachedMs),e.timing?.recordBoard("render.last-canvas-module",l.lastCanvasModuleLoadedMs),e.timing?.recordBoard("render.last-script",l.lastScriptLoadedMs),e.timing?.recordBoard("render.long-task-time",l.longTaskDurationMs),e.timing?.recordBoard("requests.all",l.requestCount,"count"),e.timing?.recordBoard("requests.script",l.scriptRequestCount,"count"),e.timing?.recordBoard("requests.canvas-module",l.canvasModuleRequestCount,"count"),e.timing?.recordBoard("requests.unrelated-canvas",l.unrelatedCanvasModuleRequestCount,"count"),e.timing?.recordBoard("react.commits",l.reactCommitCount,"count"),e.timing?.recordBoard("render.long-tasks",l.longTaskCount,"count"),await m.evaluate(watchRenderErrorsInPage,{selector:d,errorSelector:XN,messageAttribute:YN}),p.images.assertHealthy();const u=Date.now();await releasePaintHold(m),e.timing?.recordBoard("reveal",Date.now()-u);const f=await i(m,d);if(p.images.assertHealthy(),await m.locator(d).locator(kL).count())throw new SL("Storyboard content became unavailable during capture. Check the Flutter devserver compile log or the external content producer and retry.");const g=await m.evaluate(readRenderErrorsInPage);if(g.length>0)throw new Error(`storyboard rendered its error boundary: ${g.join("; ")}`);return{value:f,navigated:navigatedSinceStart()}}catch(e){throw markNavigated(e,navigatedSinceStart()),e}finally{u&&await p.dispose()}},captureStoryboardArtifactsOnce=async(t,n)=>{const r=t.artifacts??["png"],s={contextMs:0,navigateMs:0,settleMs:0};return withSettledStoryboard(t,t,s,async(n,s)=>{const i={};if(i.styles=await n.evaluate(assessPageStylesInPage,s),r.includes("png")){const e=new Uint8Array(await(t.source?n.screenshot({type:"png",animations:"disabled"}):n.locator(s).screenshot({type:"png",animations:"disabled"}))),r=oO.PNG.sync.read(Buffer.from(e));i.png={pngBytes:e,width:r.width,height:r.height}}if(r.includes("html")){const r=t.source?n.url():`${new URL(e.hostUrl).origin}/`,o=await n.evaluate(extractStoryboardDomInPage,s),a=buildStoryboardHtmlDocument(o,{baseUrl:r,preserveBody:Boolean(t.source)});if(t.portableHtml??!0){const e=await n.evaluate(inlinePortableHtmlInPage,{html:a,baseUrl:r});i.html={html:e.html,baseUrl:r,portable:!0,warnings:e.warnings}}else i.html={html:a,baseUrl:r,portable:!1,warnings:[]}}return i},n)},captureWarmStoryboardArtifactsOnce=async e=>{const t=await createCaptureWorker({...e,viewport:captureViewportFor(e,e)});try{const n=await withSettledStoryboard(e,e,{contextMs:0,navigateMs:0,settleMs:0},async()=>{},t),r=await captureStoryboardArtifactsOnce(e,t);return{value:r.value,navigated:r.navigated||n.navigated}}finally{await t.dispose()}},captureStoryboardArtifacts=async e=>{const n=`${e.hostCanvasPath}#${e.storyboardId}`;for(let r=0;;r+=1){const s=r>=PL-1,i=r+1;let a;try{a=e.warm&&!e.source?await captureWarmStoryboardArtifactsOnce(e):await captureStoryboardArtifactsOnce(e)}catch(e){if(e instanceof SL)throw e;const r=e instanceof Error?e.message:String(e);if(!o.isConnected())throw browserGoneError(r);const a=!isBrowserGoneError(r)&&(readNavigatedMark(e)||isNavigationInterruptedError(r)||isPageGoneError(r));if(s||!a)throw e;t(`[capture] ${n}: ${r.split("\n")[0]} (attempt ${i}/${PL}) — re-capturing`);continue}if(!a.navigated)return a.value;if(s)throw new Error(navigatedRejectionError(i));t(`[capture] ${n}: document reloaded mid-capture (attempt ${i}/${PL}) — re-capturing`)}},captureOne=async(t,n,r)=>{const s={contextMs:0,navigateMs:0,settleMs:0,screenshotMs:0};try{const{value:i,navigated:o}=await withSettledStoryboard({source:t.source,hostCanvasPath:t.hostCanvasPath,storyboardId:t.storyboardId,width:t.layout.width,height:t.layout.height,...t.responsive?{responsive:!0}:{}},{},s,async(n,r)=>{const i=Date.now();let o,a;try{const e=n.locator(r);o=new Uint8Array(await(t.source?n.screenshot({type:"png",animations:"disabled"}):e.screenshot({type:"png",animations:"disabled"}))),a=(new TextEncoder).encode((await n.evaluate(extractStoryboardDomInPage,r)).elementHtml)}finally{s.screenshotMs=Date.now()-i,e.timing?.recordBoard("screenshot",s.screenshotMs)}return{canvasPath:t.canvasPath,storyboardId:t.storyboardId,status:looksBlank(o)?"empty":"ok",pngHash:sha256Hex(o),pngBytes:o,htmlHash:sha256Hex(a),htmlBytes:a,timings:s}},n,r);return{result:i,status:i.status,navigated:o}}catch(e){const n={canvasPath:t.canvasPath,storyboardId:t.storyboardId,status:e instanceof SL?"content-unavailable":"render-error",error:e instanceof Error?e.message:String(e),timings:s};return{result:n,status:n.status,error:n.error,navigated:readNavigatedMark(e)}}};return{browserVersion:o.version(),envFingerprint:a,captureBoards:async(r,s)=>{if(0===r.length)return[];const i=s?.label??"capture",a=e.settleTimeoutMs??3e4,c=new Array(r.length),l=Math.max(1,Math.min(n,r.length)),d=reloadStormWindowFor(l),u=[];let p=0,m=!1,f=0,g=0,y=0;const b=Array.from({length:l},async()=>{let n=await createCaptureWorker({});const replaceWorker=async()=>{if(await n.dispose(),!o.isConnected())throw browserGoneError("browser disconnected");try{n=await createCaptureWorker({})}catch(e){throw browserGoneError(e instanceof Error?e.message:String(e))}};try{for(;;){if(m)return;const s=f;if(f+=1,s>=r.length)return;const o=r[s],l=`${o.canvasPath}#${o.storyboardId}`;let b,v=0;for(let r=0;;r+=1){let s=o.source||n.currentCanvasPath===o.hostCanvasPath?void 0:await planStyles(n,o.hostCanvasPath);"new"===s?.document&&(y+=1,e.timing?.recordBoard("style-isolation.new-document",1,"count"),y<=RL&&t(`${i}: ${l}: rendered in a new document: ${s.reason}`),await replaceWorker(),s=void 0);const c=await captureOne(o,n,s),d=decideBoardRetry(c,r);if("accept"===d){b=finalizeAcceptedAttempt(c,r+1),r>0&&e.timing?.recordBoard("capture.retries",r,"count");break}const u=describeRetryReason(c);"document reloaded mid-capture"===u&&(v+=1),t(`${i}: ${l}: ${u} (attempt ${r+1}/${PL}) — re-capturing`),"retry-fresh-worker"===d?await replaceWorker():await awaitDocumentQuiet(n,a)}if(c[s]=b,g+=1,g%10!=0&&g!==r.length||t(`${i}: ${g}/${r.length}`),p+=v,u.push(v>0),u.length>d&&u.shift(),isReloadStorm(u,d))throw m=!0,new DL(`capture aborted: the document reloaded during the last ${d} storyboards in a row (${p} re-captures so far) — check the devserver output and storyboard navigation for repeated reloads`);"render-error"===b.status&&await replaceWorker()}}finally{await n.dispose()}});return await Promise.all(b),y>RL&&t(`${i}: ${y} storyboards were rendered in a new document to keep earlier canvases' stylesheets out`),c},captureStoryboard:async e=>{const{png:t}=await captureStoryboardArtifacts({...e,artifacts:["png"]});return t},captureStoryboardHtml:async e=>{const{html:t}=await captureStoryboardArtifacts({...e,artifacts:["html"],portableHtml:e.portable??!0});return t},captureStoryboardArtifacts,dispose:async()=>{await o.close().catch(()=>{})}}}var OL=C(ru(),1),FL=24;function normalizeCompositePadding(e,t,n){if(null==e)return FL;if("string"==typeof e){const r=e.trim().match(/^(\d+(?:\.\d+)?)%$/);if(!r)throw new Error('Composite padding percentage must use the form "5%"');const s=Number(r[1]);if(!Number.isFinite(s)||s<0)throw new Error("Composite padding percentage must be non-negative");return Math.round(Math.min(t,n)*(s/100))}if(!Number.isFinite(e)||e<0)throw new Error("Composite padding must be a non-negative number");return Math.round(e)}function compositeStoryboardPngs(e,t={}){if(0===e.length)throw new Error("At least one image is required to composite a canvas image");const n=t.scale??yO,r=e.map(e=>{if(!Number.isFinite(e.x)||!Number.isFinite(e.y))throw new Error("Composite image inputs must have finite positions");return{png:OL.PNG.sync.read(Buffer.from(e.pngBytes)),x:Math.round(e.x*n),y:Math.round(e.y*n)}});let s=1/0,i=1/0,o=-1/0,a=-1/0;for(const{png:e,x:t,y:n}of r)s=Math.min(s,t),i=Math.min(i,n),o=Math.max(o,t+e.width),a=Math.max(a,n+e.height);const c=o-s,l=a-i,d=normalizeCompositePadding(t.padding,c,l),u=c+2*d,p=l+2*d,m=new OL.PNG({width:u,height:p});if(t.background){const{r:e,g:n,b:r}=t.background,s=Math.round(255*(t.background.a??1));for(let t=0;t<m.data.length;t+=4)m.data[t]=e,m.data[t+1]=n,m.data[t+2]=r,m.data[t+3]=s}for(const{png:e,x:t,y:n}of r){const r=t-s+d,o=n-i+d;for(let t=0;t<e.height;t+=1)for(let n=0;n<e.width;n+=1){const s=4*(t*e.width+n),i=4*((o+t)*u+(r+n)),a=e.data[s+3]/255;if(0===a)continue;if(1===a){m.data[i]=e.data[s],m.data[i+1]=e.data[s+1],m.data[i+2]=e.data[s+2],m.data[i+3]=255;continue}const c=m.data[i+3]/255,l=a+c*(1-a);for(let t=0;t<3;t+=1){const n=e.data[s+t],r=m.data[i+t];m.data[i+t]=0===l?0:Math.round((n*a+r*c*(1-a))/l)}m.data[i+3]=Math.round(255*l)}}return{pngBytes:new Uint8Array(OL.PNG.sync.write(m)),width:u,height:p}}var LL=60,ML=12e4,UL=[{name:"cold",dependsOn:"something that differs between two loads of the same page",options:{}},{name:"slowed",dependsOn:"the order or timing in which its files arrive (a race between loading and rendering)",options:{requestLatencyMs:LL,settleTimeoutMs:ML}},{name:"warm",dependsOn:"what the document loaded before it rendered (a module singleton, font or stylesheet that is not ready on first render)",options:{warm:!0}}];function determinismProbeForRun(e){return UL[e%UL.length]}import{readFile as jL}from"fs/promises";import BL from"path";import{randomUUID as $L}from"crypto";import{readFile as WL}from"fs/promises";import HL from"path";function createSharedAppRuntime(e,t){const n=new AbortController;let r,s,i=!1;const acquire=async()=>{const s=await resolveTempoConfig(e),{appRoot:o}=await resolveAppRoot(s),a=await ensureTempoWorkspaceNonce(s.tempoRoot),accepts=async e=>{try{const t=await fetch(new URL("__tempo/identity",e.replace(/\/?$/,"/")),{signal:AbortSignal.any([n.signal,AbortSignal.timeout(5e3)])}),r=await t.json(),s=t.ok&&!0===r.tempoHost&&!0===r.pluginActive&&r.workspaceNonce===a&&"astro"===r.framework&&1===r.capabilities?.astroComponents;if(!s)return!1;if(!tempoSdkIdentitySatisfiesCanvasHost(r)){const e=await resolveTempoSdkUpgradePlan(o);throw new pf({managedUpgradeAttempted:!1,remediationCommand:e.remediationCommand,remediationDirectory:e.cwd})}return!0}catch(e){if(e instanceof pf)throw e;return!1}};let c={};try{c=JSON.parse(await WL(HL.join(e,".tempo/app-devserver.json"),"utf8"))}catch{}const l="string"==typeof s.appUrl?s.appUrl:void 0,d=!l||l.includes("${")&&!c.port?c.port?`http://127.0.0.1:${c.port}`:void 0:substituteAppPort(l,c.port??0);if(d){if(await accepts(d))return d;let e=!1;try{await fetch(d,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(1500)])}),e=!0}catch{}if(e)throw new Error("The configured app URL belongs to a running server without this workspace's Astro preview capability; restart that app with Tempo instrumentation")}if(i)throw new Error("Capture runtime is disposed");if(!s.scripts.appStart)throw new Error("Astro component capture requires apps[0].start in tempo/tempo.config.json");r=new y_({cwd:o,workspaceRoot:HL.join(s.tempoRoot,".tempo/capture-app",$L()),command:s.scripts.appStart,...s.scripts.appStop?{stop:s.scripts.appStop}:{},...s.appUrl?{url:s.appUrl}:{}}),r.onOutput(t);const u=await r.start(n.signal);if(!u.ok||!u.url)throw new Error(u.error??"App server failed to start for Astro capture");if(!await accepts(u.url))throw new Error("App server lacks the Astro component preview capability; enable tempoAstro() from tempo-sdk/astro");return u.url};return{getAppUrl:()=>i?Promise.reject(new Error("Capture runtime is disposed")):(s??=acquire().catch(async e=>{throw await(r?.stop()),e}),s),async dispose(){i=!0,n.abort(),await(s?.catch(()=>{})),await(r?.stop())}}}var qL=new Map;function createCaptureAppRuntime(e,t=()=>{}){const n=HL.resolve(e);let r,s=!1,i=!1;return{getAppUrl(){if(i)return Promise.reject(new Error("Capture runtime is disposed"));if(!s){if(r=qL.get(n),!r){const e=new Set;r={runtime:createSharedAppRuntime(n,t=>{for(const n of e)n(t)}),refs:0,logs:e},qL.set(n,r)}s=!0,r.refs++,r.logs.add(t)}return r.runtime.getAppUrl()},async dispose(){i||(i=!0,s&&(r.logs.delete(t),0===--r.refs&&(qL.get(n)===r&&qL.delete(n),await r.runtime.dispose())))}}}async function readTempoDevserverConfig(e){const t=JSON.parse(await jL(e,"utf-8"));if(!t.scripts?.install||!t.scripts?.start)throw new Error(`tempo.config.json at ${e} must declare scripts.install and scripts.start`);const n=t.scripts.updateSdk;if(null!=n&&("string"!=typeof n||0===n.trim().length))throw new Error(`tempo.config.json at ${e}: scripts.updateSdk must be a non-empty string when provided`);return{scripts:{install:t.scripts.install,start:t.scripts.start,stop:t.scripts.stop??null,..."string"==typeof n?{updateSdk:n.trim()}:{}},tempoHostUrl:t.urls?.tempoHost??null}}function projectRootForTempoDir(e){const t=BL.resolve(e);return"tempo"===BL.basename(t)?BL.dirname(t):t}async function resolveCanvasHostLayout(e){const t=BL.resolve(e.repoRoot),n=e.tempoDir?[BL.join(BL.resolve(e.tempoDir),"tempo.config.json")]:[BL.join(t,"tempo","tempo.config.json"),BL.join(t,"tempo.config.json")];for(const e of n){let t;try{t=JSON.parse(await jL(e,"utf-8"))}catch{continue}if("object"!=typeof t||null===t||!("scripts"in t))continue;const n=BL.dirname(e),r=t.paths,s="string"==typeof r?.canvases&&r.canvases.trim().length>0?r.canvases.trim().split("\\").join("/"):"designs";return{tempoDir:n,projectRoot:projectRootForTempoDir(n),pagesDir:BL.resolve(n,s),configPath:e}}const r=e.tempoDir?BL.resolve(e.tempoDir):BL.join(t,"tempo");return{tempoDir:r,projectRoot:projectRootForTempoDir(r),pagesDir:BL.join(r,"designs"),configPath:null}}function resolveTempoDir(e){if(e.tempoConfigPath)return BL.dirname(e.tempoConfigPath);if(e.tempoDir)return e.tempoDir;if(e.repoRoot)return BL.join(e.repoRoot,"tempo");throw new Error("startDevserverSession needs one of tempoDir, repoRoot, or tempoConfigPath")}async function awaitCanvasRegistration(e){const t=e.log??(()=>{}),n=e.maxAttempts??21,r=e.retryDelayMs??250;for(let s=0;;s+=1){const i=await fetch(`${e.origin}/__tempo/canvas-host-registration`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({canvasPath:e.hostCanvasPath})}).catch(()=>null);if(!i)throw new Error(`registration barrier unreachable at ${e.origin}`);if(!i.headers.get("x-tempo-canvas-host-registration"))return void t("registration barrier not supported by host framework — skipping");if(i.ok)return;if(s>=n-1)throw new Error(`canvas ${e.hostCanvasPath} never registered into the host (last status ${i.status})`);await e.reRegister(),await new Promise(e=>setTimeout(e,r))}}var zL=/\x1b\[[0-9;]*[A-Za-z]/g;function cleanDevserverLine(e){return e.replace(zL,"").trim()}function createDevserverLineSplitter(){let e="";return{push(t){const n=(e+t).split(/\r?\n/);return e=n.pop()??"",n.map(cleanDevserverLine).filter(e=>e.length>0)},flush(){const t=cleanDevserverLine(e);return e="",t.length>0?[t]:[]}}}async function startDevserverSession(e){const t=e.log??(()=>{}),n=resolveTempoDir(e),r=e.tempoConfigPath??BL.join(n,"tempo.config.json"),s=await readTempoDevserverConfig(r),i=e.hostCanvasPaths??[],o=new fx({tempoConfigPath:r,tempoHostUrl:s.tempoHostUrl,scripts:s.scripts});await o.initialize();const a=projectRootForTempoDir(n);for(const e of i)await o.ensureCanvasRegistered(BL.join(a,e));const c=await o.startDevServer(),l=e.onOutput,d=l?createDevserverLineSplitter():null,forwardOutput=e=>{if(l)for(const n of e)try{l(n)}catch(e){t(`devserver output listener threw: ${e instanceof Error?e.message:String(e)}`)}};d&&c.onOutput(e=>forwardOutput(d.push(String(e))));const u=await c.waitUntilReady(e.readyTimeoutMs??12e4);if(!u.ok||!u.url)throw await c.stop().catch(()=>{}),await o.dispose(),forwardOutput(d?.flush()??[]),new Error(`tempobook devserver failed to become ready: ${u.message??(u.timedOut?"timeout":"unknown")}`);const p=u.url,m=new URL(p).origin;t(`devserver ready at ${p}`);const registerCanvas=async e=>{await o.ensureCanvasRegistered(BL.join(a,e)),await awaitCanvasRegistration({origin:m,hostCanvasPath:e,reRegister:()=>o.ensureCanvasRegistered(BL.join(a,e)),log:t})};for(const e of i)await awaitCanvasRegistration({origin:m,hostCanvasPath:e,reRegister:()=>o.ensureCanvasRegistered(BL.join(a,e)),log:t});const f=createCaptureAppRuntime(a,t);return{getAppUrl:f.getAppUrl,origin:m,hostUrl:p,projectRoot:a,tempoDir:n,registerCanvas,dispose:async()=>{try{await f.dispose()}finally{await c.stop().catch(()=>{}),await o.dispose(),forwardOutput(d?.flush()??[])}}}}import{createHash as GL}from"crypto";import{access as VL,readFile as KL}from"fs/promises";import XL from"path";function ignoredStoryboardArea(e,t,n){const r=e.map(({x:e,y:r,w:s,h:i})=>({left:Math.max(0,e),top:Math.max(0,r),right:Math.min(t,e+s),bottom:Math.min(n,r+i)})).filter(({left:e,top:t,right:n,bottom:r})=>n>e&&r>t),s=[...new Set(r.flatMap(({left:e,right:t})=>[e,t]))].sort((e,t)=>e-t);let i=0;for(let e=1;e<s.length;e++){const t=s[e-1],n=s[e],o=r.filter(e=>e.left<n&&e.right>t).sort((e,t)=>e.top-t.top);let a=0,c=0;for(const e of o)a+=Math.max(0,e.bottom-Math.max(c,e.top)),c=Math.max(c,e.bottom);i+=(n-t)*a}return i}function toPosixPath5(e){return e.split(XL.sep).join("/")}async function enumerateCanvasStoryboards(e){const t=e.pagesDir??XL.join(e.tempoDir,"designs"),n=projectRootForTempoDir(e.tempoDir),r=await scanCanvasFiles(t),s=[],i=[],o=[],a=[];let c=0;for(const t of r){const r=await KL(t,"utf-8"),l=parseCanvasFile(t,r),d=l.errors.filter(e=>"structural"===e.kind),u=l.imports.some(e=>"tempo-sdk/canvas"===e.source||e.source.endsWith("/tempo-sdk/canvas"))||l.misimportedSdkCanvasImports.length>0,p=!u&&d.length>0&&d.every(e=>e.message===ev);if(p)continue;const m=d.filter(e=>e.newerSdkStoryboard),f=d.filter(e=>!e.newerSdkStoryboard);if(f.length>0){i.push(...d.map(e=>({filePath:t,message:e.message})));continue}for(const e of m){const{component:n,storyboardKey:r,vrt:s}=e.newerSdkStoryboard;c+=1,a.push({filePath:t,component:n,...r?{storyboardId:r}:{},vrt:s})}const g=l.errors.filter(e=>"degraded"===e.kind&&e.message.includes(" vrt"));if(g.length>0){o.push(...g.map(e=>({filePath:t,message:e.message})));continue}const y=toPosixPath5(XL.relative(e.tempoDir,XL.dirname(t))),b=toPosixPath5(XL.relative(n,t));for(const e of l.storyboards)c+=1,"route"!==e.kind&&("html"!==e.kind||e.filepath?s.push({..."astro"===componentFrameworkForStoryboard(e)?{source:{kind:"astro",canvasPath:l.canvasPath??toPosixPath5(XL.relative(n,XL.dirname(t))),revision:GL("sha256").update(r).digest("hex")}}:"html"===e.kind?{source:{kind:"html",filepath:XL.resolve(XL.dirname(t),e.filepath)}}:{},filePath:t,canvasPath:y,hostCanvasPath:b,storyboardId:e.storyboardKey,name:e.displayName,layout:{x:e.layout.x,y:e.layout.y,width:e.layout.width,height:e.layout.height},vrt:e.vrt,...e.responsive?{responsive:!0}:{}}):e.vrt&&o.push({filePath:t,message:`HTML storyboard "${e.storyboardKey}" requires a literal local filepath for headless capture.`}))}return{storyboards:s,totalStoryboards:c,totalCanvases:r.length,structuralErrors:i,vrtConfigErrors:o,newerSdkStoryboards:a}}async function enumerateTrackedStoryboards(e){try{await VL(e.tempoDir)}catch{return{tracked:[],paused:[],totalStoryboards:0,totalCanvases:0,errors:[],newerSdkStoryboards:[]}}const t=await enumerateCanvasStoryboards(e),n=[],r=[],s=[...t.structuralErrors,...t.vrtConfigErrors];for(const e of t.storyboards){if(!e.vrt)continue;const t={...e.source?{source:e.source}:{},canvasPath:e.canvasPath,hostCanvasPath:e.hostCanvasPath,storyboardId:e.storyboardId,name:e.name,layout:e.layout,threshold:e.vrt.threshold,ignore:e.vrt.ignore,...e.responsive?{responsive:!0}:{}},{width:i,height:o}=t.layout,a=void 0!==i&&void 0!==o;if(a){const t=ignoredStoryboardArea(e.vrt.ignore??[],i,o);if(t>=.9*i*o){s.push({filePath:e.filePath,message:`<Storyboard id="${e.storyboardId}"> vrt.ignore masks ≥90% of the board — untrack it instead`});continue}}e.vrt.skip?r.push(t):n.push(t)}return{tracked:n,paused:r,totalStoryboards:t.totalStoryboards,totalCanvases:t.totalCanvases,errors:s,newerSdkStoryboards:t.newerSdkStoryboards}}var YL=10,JL=20,QL=2e3;function isStyleStarved(e){return 0===e.unreadableSheetCount&&e.classElementCount>=YL&&e.authorRuleCount<JL&&e.styleTextBytes<QL}function describeStyleStarvation(e){return`page rendered with almost no CSS (${e.classElementCount} class-carrying elements but only ${e.authorRuleCount} CSS rules / ${e.styleTextBytes} style bytes). The devserver likely failed to build or serve the app's styles — most often an incomplete dependency install (rerun the project's install, check the devserver output for CSS/PostCSS/Tailwind errors), then retry.`}import{readFile as ZL}from"fs/promises";import{resolve as eM}from"path";var tM={node:{core:["index","expo-babel-plugin","flutter-preview-path","nextjs-loader","assets/parser","canvas/parser"],vue:["vue"],svelte:["svelte"],astro:["astro","astro/runtime"],nuxt:["nuxt"]}};async function provisionCaptureRuntime(e){const t=process.env.TEMPO_SDK_RUNTIME_PATH||e,n=await ZL(eM(t,"runtime.json"),"utf8").then(e=>{const t=JSON.parse(e),n=Object.values(tM.node).flat().filter(e=>!Object.prototype.hasOwnProperty.call(t.node??{},e));return n.length?`The private Tempo SDK runtime is missing entries: ${n.join(", ")}`:null}).catch(()=>null),r=n??await tempoSdkRuntimeProvisioningError({tempoRuntimeContract:1},t);if(r)throw new Error(`${t}: ${r}`);process.env.TEMPO_SDK_RUNTIME_PATH=t}function pixelmatch(e,t,n,r,s,i={}){const{threshold:o=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],includeAA:d,diffColorAlt:u,diffMask:p}=i;if(!isPixelData(e)||!isPixelData(t)||n&&!isPixelData(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==t.length||n&&n.length!==e.length)throw new Error("Image sizes do not match.");if(e.length!==r*s*4)throw new Error("Image data size does not match width/height.");const m=r*s,f=new Uint32Array(e.buffer,e.byteOffset,m),g=new Uint32Array(t.buffer,t.byteOffset,m);let y=!0;for(let e=0;e<m;e++)if(f[e]!==g[e]){y=!1;break}if(y){if(n&&!p)for(let t=0;t<m;t++)drawGrayPixel(e,4*t,a,n);return 0}const b=35215*o*o,[v,w,x]=c,[S,E,A]=l,[C,I,P]=u||l;let R=0;for(let i=0;i<s;i++)for(let o=0;o<r;o++){const c=i*r+o,l=4*c,u=f[c]===g[c]?0:colorDelta(e,t,l,l,!1);if(Math.abs(u)>b){const a=antialiased(e,o,i,r,s,f,g)||antialiased(t,o,i,r,s,g,f);!d&&a?n&&!p&&drawPixel(n,l,v,w,x):(n&&(u<0?drawPixel(n,l,C,I,P):drawPixel(n,l,S,E,A)),R++)}else n&&!p&&drawGrayPixel(e,l,a,n)}return R}function isPixelData(e){return ArrayBuffer.isView(e)&&1===e.BYTES_PER_ELEMENT}function antialiased(e,t,n,r,s,i,o){const a=Math.max(t-1,0),c=Math.max(n-1,0),l=Math.min(t+1,r-1),d=Math.min(n+1,s-1),u=n*r+t;let p=t===a||t===l||n===c||n===d?1:0,m=0,f=0,g=0,y=0,b=0,v=0;for(let s=a;s<=l;s++)for(let i=c;i<=d;i++){if(s===t&&i===n)continue;const o=colorDelta(e,e,4*u,4*(i*r+s),!0);if(0===o){if(p++,p>2)return!1}else o<m?(m=o,g=s,y=i):o>f&&(f=o,b=s,v=i)}return 0!==m&&0!==f&&(hasManySiblings(i,g,y,r,s)&&hasManySiblings(o,g,y,r,s)||hasManySiblings(i,b,v,r,s)&&hasManySiblings(o,b,v,r,s))}function hasManySiblings(e,t,n,r,s){const i=Math.max(t-1,0),o=Math.max(n-1,0),a=Math.min(t+1,r-1),c=Math.min(n+1,s-1),l=e[n*r+t];let d=t===i||t===a||n===o||n===c?1:0;for(let s=i;s<=a;s++)for(let i=o;i<=c;i++)if((s!==t||i!==n)&&(d+=+(l===e[i*r+s]),d>2))return!0;return!1}function colorDelta(e,t,n,r,s){const i=e[n],o=e[n+1],a=e[n+2],c=e[n+3],l=t[r],d=t[r+1],u=t[r+2],p=t[r+3];let m=i-l,f=o-d,g=a-u;const y=c-p;if(!(m||f||g||y))return 0;if(c<255||p<255){const e=48+n%2*159,t=48+(n/1.618033988749895|0)%2*159,r=48+(n/2.618033988749895|0)%2*159;m=(i*c-l*p-e*y)/255,f=(o*c-d*p-t*y)/255,g=(a*c-u*p-r*y)/255}const b=.29889531*m+.58662247*f+.11448223*g;if(s)return b;const v=.59597799*m-.2741761*f-.32180189*g,w=.21147017*m-.52261711*f+.31114694*g,x=.5053*b*b+.299*v*v+.1957*w*w;return b>0?-x:x}function drawPixel(e,t,n,r,s){e[t+0]=n,e[t+1]=r,e[t+2]=s,e[t+3]=255}function drawGrayPixel(e,t,n,r){const s=255+(.29889531*e[t]+.58662247*e[t+1]+.11448223*e[t+2]-255)*n*e[t+3]/255;drawPixel(r,t,s,s,s)}var nM=C(ru(),1),rM=.05,sM=1990,iM=class extends Error{constructor(e,t){super(t),this.name="StoryboardStabilityTargetError",this.code=e}};function toPosix4(e){return e.replace(/\\/g,"/")}function absoluteCanvasesRoot(e,t){return BN.isAbsolute(t)?BN.resolve(t):BN.resolve(e,t)}function isInsideRoot(e,t){const n=BN.relative(e,t);return""===n||!n.startsWith("..")&&!BN.isAbsolute(n)}async function isInsideRootForReal(e,t){try{const[n,r]=await Promise.all([jN(e),jN(t)]);return isInsideRoot(n,r)}catch{return!1}}async function resolveCanvasFile(e){const t=absoluteCanvasesRoot(e.workspaceRoot,e.canvasesDir),n=e.canvasSlug,r=new Set,s=BN.resolve(t,n),i=isInsideRoot(t,s)?await resolveCanvasFilePath(s):null;if(i&&await isInsideRootForReal(t,i)&&r.add(i),0===r.size&&!n.includes("/")){const e=await findPageFilesInPagesRoot(t);for(const s of e)BN.basename(BN.dirname(s))===n&&await isInsideRootForReal(t,s)&&r.add(s)}if(0===r.size)throw new iM("canvas_not_found",`No canvas matching "${e.canvasSlug}" exists under ${toPosix4(t)}.`);if(r.size>1){const n=[...r].map(e=>toPosix4(BN.relative(t,BN.dirname(e)))).sort();throw new iM("ambiguous_canvas_slug",`"${e.canvasSlug}" names ${n.length} canvases: ${n.join(", ")}. Pass the full canvases-root-relative path.`)}const o=r.values().next().value;if(!o)throw new iM("canvas_not_found",`No canvas matching "${e.canvasSlug}" exists under ${toPosix4(t)}.`);return o}async function resolveTestedStoryboard(e){const t=await resolveCanvasFile(e),n=await UN(t,"utf8"),r=parsePageSource(t,n),s=r.storyboards.find(t=>t.storyboardKey===e.storyboard||t.exportName===e.storyboard);if(!s){const n=r.storyboards.map(e=>e.storyboardKey??e.exportName).join(", ");throw new iM("storyboard_not_found",`Storyboard "${e.storyboard}" was not found in ${toPosix4(BN.relative(e.workspaceRoot,t))}.${n?` Available storyboards: ${n}.`:""}`)}if(s.error)throw new iM("storyboard_invalid",`Storyboard "${e.storyboard}" cannot be verified: ${s.error}`);if(s.isRoute)throw new iM("storyboard_unsupported",`Storyboard "${e.storyboard}" is a route storyboard; VRT stability verification supports component and local HTML storyboards.`);if(s.isHtml&&!s.filepath)throw new iM("storyboard_invalid",`HTML storyboard "${e.storyboard}" requires a literal local filepath for VRT.`);if(!s.vrt||!s.vrtConfig)throw new iM("storyboard_not_tested",`Storyboard "${e.storyboard}" is not VRT-tested. Add a literal vrt prop before verifying stability.`);if(s.vrtConfig.skip)throw new iM("storyboard_paused",`Storyboard "${e.storyboard}" is paused with vrt={{ skip: true }}. Remove skip before verifying it as an active test.`);const i=void 0!==s.layout.width&&void 0!==s.layout.height?s.layout.width*s.layout.height:null;if(null!==i&&ignoredStoryboardArea(s.vrtConfig.ignore??[],s.layout.width,s.layout.height)>=.9*i)throw new iM("storyboard_invalid",`Storyboard "${e.storyboard}" has vrt.ignore masking at least 90% of its area; VRT rejects this configuration.`);return{canvasFile:toPosix4(BN.relative(e.workspaceRoot,t)),canvasSlug:toPosix4(BN.relative(absoluteCanvasesRoot(e.workspaceRoot,e.canvasesDir),BN.dirname(t))),storyboardId:s.storyboardKey??s.exportName,layout:{width:s.layout.width,height:s.layout.height},vrt:s.vrtConfig}}function maskRegion(e,t){const n=Math.max(0,Math.floor(t.x)),r=Math.max(0,Math.floor(t.y)),s=Math.min(e.width,Math.ceil(t.x+t.w)),i=Math.min(e.height,Math.ceil(t.y+t.h));for(let t=r;t<i;t+=1)for(let r=n;r<s;r+=1){const n=e.width*t+r<<2;e.data[n]=0,e.data[n+1]=0,e.data[n+2]=0,e.data[n+3]=255}}function findDiffBounds(e){let t=e.width,n=e.height,r=-1,s=-1;for(let i=0;i<e.height;i+=1)for(let o=0;o<e.width;o+=1)0!==e.data[3+(e.width*i+o<<2)]&&(t=Math.min(t,o),n=Math.min(n,i),r=Math.max(r,o),s=Math.max(s,i));return r<t||s<n?null:{x:t,y:n,width:r-t+1,height:s-n+1}}function unionBounds(e,t){if(!e)return t;if(!t)return e;const n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),s=Math.max(e.x+e.width,t.x+t.width),i=Math.max(e.y+e.height,t.y+t.height);return{x:n,y:r,width:s-n,height:i-r}}function decodeCapture(e){const t=nM.PNG.sync.read(Buffer.from(e.pngBase64,"base64"));if(t.width!==e.width||t.height!==e.height)throw new Error(`Capture metadata ${e.width}x${e.height} does not match decoded PNG ${t.width}x${t.height}.`);return t}function ignoreRegionScale(e,t,n){if(void 0===t.width||void 0===t.height){const e=n??yO;return{scaleX:e,scaleY:e}}return{scaleX:e.width/t.width,scaleY:e.height/t.height}}function compareCaptureToBaseline(e,t,n,r){const s=decodeCapture(t);if(s.width!==e.width||s.height!==e.height){const r=Math.max(e.width,s.width),i=Math.max(e.height,s.height),o=new nM.PNG({width:r,height:i});for(let e=0;e<o.data.length;e+=4)o.data[e]=217,o.data[e+1]=70,o.data[e+2]=239,o.data[e+3]=255;return{diff:o,comparison:{run:n,baselineRun:1,...t.condition?{condition:t.condition}:{},diffPixels:s.width*s.height,diffRatio:1,diffBounds:{x:0,y:0,width:r,height:i},dimensions:{width:s.width,height:s.height},dimensionChange:{baseline:{width:e.width,height:e.height},candidate:{width:s.width,height:s.height}}}}}const{scaleX:i,scaleY:o}=ignoreRegionScale(e,r.layout,t.captureScale);for(const e of r.ignore){const t={x:e.x*i,y:e.y*o,w:e.w*i,h:e.h*o};maskRegion(s,t)}const{diff:a,diffPixels:c}=matchPixels(e,s,r.threshold);return{diff:a,comparison:{run:n,baselineRun:1,...t.condition?{condition:t.condition}:{},diffPixels:c,diffRatio:c/(e.width*e.height),diffBounds:findDiffBounds(a),dimensions:{width:s.width,height:s.height}}}}function matchPixels(e,t,n){const r=new nM.PNG({width:e.width,height:e.height}),s=pixelmatch(e.data,t.data,r.data,e.width,e.height,{threshold:n,includeAA:!1,diffMask:!0,diffColor:[217,70,239]});return{diff:r,diffPixels:s}}function maskedDiffRatios(e,t,n,r=rM){const s=decodeCapture(e),i=decodeCapture(t),o=decodeCapture(n),sameSize=e=>e.width===s.width&&e.height===s.height;if(!sameSize(o))return{diffRatio:1,unstableRatio:0};if(!sameSize(i))return{diffRatio:0,unstableRatio:1};const a=matchPixels(s,i,r).diff.data,c=matchPixels(s,o,r).diff.data,l=s.width*s.height;let d=0,u=0;for(let e=0;e<l;e++){const t=4*e+3;a[t]>0?d++:c[t]>0&&u++}return{diffRatio:u/l,unstableRatio:d/l}}function mergeDiffImage(e,t){const n=Math.max(e?.width??0,t.width),r=Math.max(e?.height??0,t.height),s=e&&e.width===n&&e.height===r?e:new nM.PNG({width:n,height:r}),merge=e=>{for(let t=0;t<e.height;t+=1)for(let r=0;r<e.width;r+=1){const i=e.width*t+r<<2;if(0===e.data[i+3])continue;const o=n*t+r<<2;s.data[o]=217,s.data[o+1]=70,s.data[o+2]=239,s.data[o+3]=255}};return e&&s!==e&&merge(e),merge(t),s}function downscaleDiffMaskToFit(e,t){if(e.width<=t&&e.height<=t)return e;const n=Math.min(t/e.width,t/e.height),r=Math.max(1,Math.min(t,Math.round(e.width*n))),s=Math.max(1,Math.min(t,Math.round(e.height*n))),i=new nM.PNG({width:r,height:s});for(let t=0;t<s;t+=1){const n=Math.floor(t*e.height/s),o=Math.max(n+1,Math.ceil((t+1)*e.height/s));for(let s=0;s<r;s+=1){const a=Math.floor(s*e.width/r),c=Math.max(a+1,Math.ceil((s+1)*e.width/r));let l=!1;for(let t=n;t<o&&!l;t+=1)for(let n=a;n<c;n+=1){const r=e.width*t+n<<2;if(0!==e.data[r+3]){l=!0;break}}if(!l)continue;const d=r*t+s<<2;i.data[d]=217,i.data[d+1]=70,i.data[d+2]=239,i.data[d+3]=255}}return i}function createVrtStabilityAccumulator(e){const t=e.threshold??rM,n={threshold:t,ignore:e.ignore??[],layout:e.layout};let r=null,s=null,i=0,o=0;const a=[],c=[];return{addCapture(e){if(i+=1,!0===e.retried&&(o+=1),c.push(e.condition),!r){r=decodeCapture(e);const{scaleX:t,scaleY:s}=ignoreRegionScale(r,n.layout,e.captureScale);for(const e of n.ignore)maskRegion(r,{x:e.x*t,y:e.y*s,w:e.w*t,h:e.h*s});return}const t=compareCaptureToBaseline(r,e,i,n);a.push(t.comparison),t.comparison.diffPixels>0&&(s=mergeDiffImage(s,t.diff))},get captureCount(){return i},summarize(){if(!r||i<2)throw new Error("VRT stability verification requires at least two captures.");const e=a.filter(e=>e.diffPixels>0),l=s,d=l?downscaleDiffMaskToFit(l,sM):null,u=c.every(e=>void 0!==e)?c:null,p=u?[...new Set(e.flatMap(e=>e.condition??[]))]:[];return{status:0===e.length?"stable":"unstable",vrtStable:0===e.length,conditions:u,unstableConditions:p.map(e=>({condition:e,dependsOn:UL.find(t=>t.name===e)?.dependsOn??""})),runs:i,retriedCaptures:o,threshold:t,ignoreRegions:n.ignore.length,changedRuns:e.length,maxDiffPixels:Math.max(0,...a.map(e=>e.diffPixels)),maxDiffRatio:Math.max(0,...a.map(e=>e.diffRatio)),diffBounds:a.reduce((e,t)=>unionBounds(e,t.diffBounds),null),cumulativeDiff:d&&l?{pngBase64:nM.PNG.sync.write(d).toString("base64"),width:d.width,height:d.height,sourceWidth:l.width,sourceHeight:l.height}:null,comparisons:a}}}}import{readFile as oM}from"fs/promises";import aM from"path";var cM=.005,lM=.25,dM='Record what this taught you about the project, one line per finding, under `## Responsive storyboards` in both `tempo/CLAUDE.md` and `tempo/AGENTS.md`, creating the section or the file when it is missing: the component or pattern, and whether storyboards of it need `responsive`. For example: "`AppShell` collapses its sidebar with `useMediaQuery`: storyboards of it narrower than 1024 need `responsive`." or "`Card` layouts are CSS only: no check needed." Record only what holds for other storyboards, update a line this result contradicts, and keep the section short. Do not touch any other section of those files. Tell the user what you recorded.',uM={unstable:()=>"Most of this storyboard changes by itself between captures (time, data or animation), so the check cannot compare it. Nothing to do.",not_component:()=>"This is not a component storyboard, so it cannot use `responsive`. Route and HTML storyboards already render in a window of their own size. Nothing to do.",no_fidelity_window:()=>"This environment has no window that can render the storyboard at its own size, so it cannot run the check. Nothing to do.",box_too_large:e=>`The storyboard rendered at ${formatBox(e)}, over the ${BP}x${$P} limit for a window of its own size. Nothing to do.`,timed_out:()=>"The capture at the storyboard's own size did not finish in time. The storyboard may still be loading. Try the check again once."};async function runResponsivenessCheck(e,t,n,r){const s=await resolveCanvasFile({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir,canvasSlug:n.canvasSlug}),i=parsePageSource(s,await oM(s,"utf8")),o=i.storyboards.find(e=>e.storyboardKey===n.storyboard||e.exportName===n.storyboard);if(!o){const e=i.storyboards.map(e=>e.storyboardKey??e.exportName).join(", ");return failure2("storyboard_not_found",`Storyboard "${n.storyboard}" was not found.${e?` Available storyboards in the current canvas: ${e}.`:""}`)}const a=o.isRoute?"route":o.isHtml?"html":"component",c=isFidelityWindowStoryboard({kind:a,uiFramework:o.uiFramework,preview:o.preview});if(!c)return unavailableResult(n,"not_component");if(!0===o.responsive)return verdictResult(n,"already_responsive",{note:"This storyboard already has `responsive`, so it already renders in a window of its own size. Nothing to check."});t.canvasDevserver&&!e.managesDevserver&&await t.canvasDevserver.start();const l=await e.capture({canvasSlug:n.canvasSlug,canvasFile:toPosix5(aM.relative(t.workspaceRoot,s)),storyboard:n.storyboard},{signal:r});if("error"===l.kind){const e=l.availableStoryboards?.length?` Available storyboards in the current canvas: ${l.availableStoryboards.join(", ")}.`:"";return failure2(l.code,`${l.message}${e}`)}if("unavailable"===l.kind)return unavailableResult(n,l.reason,l.box);const{diffRatio:d,unstableRatio:u}=maskedDiffRatios(l.shared,l.sharedAgain??l.shared,l.ownSize),{width:p,height:m}=l.box,f=u>0?{unstable_ratio:roundRatio(u)}:{};if(u>lM)return verdictResult(n,"unavailable",{reason:"unstable",width:p,height:m,...f,note:uM.unstable(l.box)});const g={width:p,height:m,diff_ratio:roundRatio(d),...f},y=u>0?` ${formatPercent(u)} of this storyboard changes by itself between captures (time, data or animation) and was ignored.`:"";return d<=cM?verdictResult(n,"same",{...g,note:`This storyboard's JavaScript does not depend on the window size at ${p}x${m}, so it does not need \`responsive\`.${y}`,memory:!0}):verdictResult(n,"differs",{...g,note:`The first image is what the canvas shows now. The second is this storyboard in a window of its own size, ${p}x${m}. If the second is the intended look, add \`responsive\` to this storyboard, and nothing else: keep its layout as it is, with or without a size. Then screenshot it again. If the two differ only by time, data or animation, change nothing.${y}`,memory:!0},[l.shared.pngBase64,l.ownSize.pngBase64])}function verdictResult(e,t,n,r=[]){const{note:s,memory:i,...o}=n,a={canvas_slug:e.canvasSlug,storyboard:e.storyboard,verdict:t,...o},c=[JSON.stringify(a,null,2),s];return i&&c.push(dM),{content:[...r.map(e=>({type:"image",data:e,mimeType:"image/png"})),{type:"text",text:c.join("\n\n")}]}}function unavailableResult(e,t,n){return verdictResult(e,"unavailable",{reason:t,...n?{width:n.width,height:n.height}:{},note:uM[t](n)})}function failure2(e,t){return{content:[{type:"text",text:`storyboard_responsiveness_check failed [${e}]: ${t}`}],isError:!0}}function formatBox(e){return e?`${e.width}x${e.height}`:"its size"}function formatPercent(e){return`${Number((100*e).toFixed(2))}%`}function roundRatio(e){return Math.round(1e4*e)/1e4}function toPosix5(e){return e.split(aM.sep).join("/")}import{execFile as pM}from"child_process";import{access as hM,mkdir as mM,readdir as fM,readFile as gM,realpath as yM,writeFile as bM}from"fs/promises";import vM from"path";import{promisify as wM}from"util";function normalizeRepoUrl2(e){if(!e||"string"!=typeof e)return null;let t=e.trim();if(!t)return null;const n=/^[\w.-]+@([\w.-]+):([\w./-]+)$/,r=t.match(n);if(r){const e=r[1],t=r[2];return finalize2(e,t)}const s=t.match(/^[\w+.-]+:\/\/(?:[^@]+@)?([\w.-]+)\/([\w./-]+)$/);if(s){const e=s[1],t=s[2];return finalize2(e,t)}const i=t.match(/^[\w+.-]+:\/\/(?:[^@]+@)?([\w.-]+):\d+\/([\w./-]+)$/);if(i){const e=i[1].toLowerCase(),t=i[2];return finalize2(_M[e]??e,t)}return null}var _M={"altssh.bitbucket.org":"bitbucket.org","ssh.github.com":"github.com"};function finalize2(e,t){let n=t.replace(/\.git$/,"");return n=n.replace(/^\/+|\/+$/g,""),n?`${e}/${n}`.toLowerCase():null}function githubRepoFromKey2(e){const t=/^github\.com\/([^/]+)\/([^/]+)$/.exec(e);return t?`${t[1]}/${t[2]}`:null}function bitbucketRepoFromKey2(e){const t=/^bitbucket\.org\/([^/]+)\/([^/]+)$/.exec(e);return t?`${t[1]}/${t[2]}`:null}var xM="# Written by Tempo visual-review onboarding (visual_review_init). The pnpm\n# setup and the two install lines are the package-manager-specific part;\n# init rewrites them for npm / yarn / bun. Keep every\n# `npx --yes @tempo-ai/visual-review@latest …` line as it is: Tempo's own\n# repository runs these exact commands, so each release is exercised there\n# before it reaches you. The CLI comes from npm, never from this checkout;\n# the checkout's own install scripts and canvas host do run inside the job\n# (as in any CI), so treat it like your other workflows.\nname: Visual Review\n\non:\n pull_request:\n # labeled/unlabeled: the bypass label takes effect (and is revocable)\n # without pushing a new commit.\n types: [opened, synchronize, reopened, edited, labeled, unlabeled]\n push:\n # Your default branch: pushes here publish the baseline PRs compare against.\n branches: [main]\n\npermissions:\n contents: read\n # Compatibility with older CLIs during rollout; the current CLI publishes\n # all statuses through the Tempo GitHub App instead of this token.\n statuses: write\n pull-requests: write\n # GitHub OIDC is the only credential Tempo accepts. No secret is stored.\n id-token: write\n\nconcurrency:\n # A new push never queues behind a stale run. Label events get their own\n # group so an unrelated label added mid-capture cannot cancel it.\n group: visual-review-${{ github.event.pull_request.number || github.sha }}-${{ (github.event.action == 'labeled' || github.event.action == 'unlabeled') && 'label' || 'code' }}\n cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\njobs:\n # `visual-review:bypass` label — the incident escape hatch. Posts success\n # and skips capture entirely.\n bypass:\n if: >-\n github.event_name == 'pull_request'\n && contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')\n runs-on: ubuntu-latest\n timeout-minutes: 5\n steps:\n - run: npx --yes @tempo-ai/visual-review@latest report --bypass --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n # `\x3c!-- tempo-no-visual-change --\x3e` in the PR body — a 100%-certainty claim\n # that the PR changes no UI and no tested storyboard. Posts success and\n # skips capture.\n no-visual-change:\n if: >-\n github.event_name == 'pull_request'\n && !contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')\n && contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')\n runs-on: ubuntu-latest\n timeout-minutes: 5\n steps:\n - run: npx --yes @tempo-ai/visual-review@latest report --no-visual-change --pr ${{ github.event.pull_request.number }} --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n capture:\n # Pushes to the default branch, real code events without either skip\n # declaration, and bypass-label removal (to restore the real gate).\n if: >-\n !cancelled()\n && (\n github.event_name == 'push'\n || (\n contains(fromJSON('[\"opened\",\"synchronize\",\"reopened\",\"edited\"]'), github.event.action)\n && !contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')\n && !contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')\n )\n || (\n github.event.action == 'unlabeled'\n && github.event.label.name == 'visual-review:bypass'\n && !contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')\n )\n )\n runs-on: ubuntu-latest\n # A PR may first wait for another run's baseline and then render both the\n # merge-base and its own head.\n timeout-minutes: 90\n outputs:\n status_url: ${{ steps.capture.outputs.status_url }}\n steps:\n - uses: actions/checkout@v4\n with:\n # Full history: the merge-base ancestor chain is the baseline key.\n fetch-depth: 0\n # Capture the PR head, not GitHub's synthetic merge commit.\n ref: ${{ github.event.pull_request.head.sha || github.sha }}\n\n # Announces intent before dependency/browser setup so stacked PRs wait\n # on the baseline lease instead of duplicating a capture. Purely an\n # optimization, so a registry hiccup must not fail the run.\n - run: npx --yes @tempo-ai/visual-review@latest claim || echo \"::warning::capture claim announcement unavailable; capture claims after setup\"\n\n - uses: pnpm/action-setup@v4\n - uses: actions/setup-node@v4\n with:\n node-version: 24\n cache: pnpm\n - run: pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so the\n # host's dependencies are installed here, explicitly.\n - run: cd tempo && pnpm install --no-frozen-lockfile\n\n # Chromium matching the CLI's own pinned playwright, plus its shared\n # libraries on Linux.\n - run: npx --yes @tempo-ai/visual-review@latest install-browsers\n\n - uses: actions/cache@v4\n with:\n path: tempo/node_modules/.vite\n key: visual-review-vite-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }}\n\n # `capture` infers PR-vs-main, head SHA, branch, merge-base and\n # repository from GitHub's event payload and the standard GITHUB_*\n # environment, and authenticates with short-lived OIDC tokens it mints\n # itself.\n - id: capture\n run: npx --yes @tempo-ai/visual-review@latest capture --parallel 2\n env:\n # Forbid the capture's canvas-host supervisor from running package\n # manager installs or updates inside this checkout; those would\n # churn the Vite cache mid-run and rewrite lockfiles.\n TEMPO_DEVSERVER_PROTECTED_ROOTS: ${{ github.workspace }}\n\n # A finished capture has already consumed its claim; this only releases\n # a lease left behind by a setup failure or cancellation.\n - if: always()\n run: npx --yes @tempo-ai/visual-review@latest claim --release || echo \"::warning::capture claim release unavailable; the lease expires on its own\"\n\n - if: failure() && github.event_name == 'pull_request'\n run: npx --yes @tempo-ai/visual-review@latest report --fallback-failure --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n # Polls the run until Tempo has compared it, then posts the sticky PR\n # comment. Tempo's GitHub App owns every status, including declarations,\n # failures, and portal approvals — no CI re-run needed for an approval.\n report:\n needs: capture\n if: github.event_name == 'pull_request'\n runs-on: ubuntu-latest\n timeout-minutes: 20\n steps:\n - run: npx --yes @tempo-ai/visual-review@latest report --status-url \"${{ needs.capture.outputs.status_url }}\" --pr ${{ github.event.pull_request.number }} --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n\n # A crashed report must not strand the check at pending. Only stomps\n # pending/absent — a verdict Tempo already delivered stays.\n - if: failure()\n run: npx --yes @tempo-ai/visual-review@latest report --fallback-failure --sha ${{ github.event.pull_request.head.sha }}\n env:\n GH_TOKEN: ${{ github.token }}\n",TM=" - uses: pnpm/action-setup@v4\n - uses: actions/setup-node@v4\n with:\n node-version: 24\n cache: pnpm\n - run: pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so the\n # host's dependencies are installed here, explicitly.\n - run: cd tempo && pnpm install --no-frozen-lockfile\n",kM=" - uses: actions/cache@v4\n with:\n path: tempo/node_modules/.vite\n key: visual-review-vite-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }}\n",SM=" branches: [main]",EM="10",AM={pnpm:"pnpm-lock.yaml",npm:"package-lock.json",yarn:"yarn.lock",bun:"bun.lock"};function isValidGitBranchName(e){return!(!e||e.length>255)&&(!/[\x00-\x20\x7f~^:?*[\\]/.test(e)&&(!(e.includes("..")||e.includes("@{")||e.includes("//"))&&(!(e.startsWith("-")||e.startsWith("/")||e.endsWith("/"))&&(!e.endsWith(".")&&!e.endsWith(".lock")&&e.split("/").every(e=>e.length>0&&!e.startsWith(".")&&!e.endsWith(".lock"))))))}function yamlBranchScalar(e){const t=e.replace(/[\\*?+[\]!]/g,"\\$&"),n=/^[A-Za-z0-9_./-]+$/.test(t)&&!/^(true|false|yes|no|on|off|null|y|n)$/i.test(t)&&!/^[-+.]?\d/.test(t);return n?t:`'${t.replace(/'/g,"''")}'`}function rootInstallCommand(e,t){switch(e){case"pnpm":return t?"pnpm install --frozen-lockfile":"pnpm install --no-frozen-lockfile";case"npm":return t?"npm ci":"npm install";case"yarn":return"yarn install";case"bun":return t?"bun install --frozen-lockfile":"bun install"}}function hostInstallCommand(e){switch(e){case"pnpm":return"pnpm install --no-frozen-lockfile";case"npm":return"npm install";case"yarn":return"yarn install";case"bun":return"bun install"}}function setupSteps(e,t,n,r){const s=r?`node-version-file: ${r}`:"node-version: 24",nodeSetup=e=>` - uses: actions/setup-node@v4\n with:\n ${s}\n${e?` cache: ${e}\n`:""}`;switch(e){case"pnpm":return` - uses: pnpm/action-setup@v4\n${n?"":` with:\n # No \`packageManager\` field in package.json to read the version from.\n version: ${EM}\n`}${nodeSetup(t?"pnpm":null)}`;case"npm":return nodeSetup(t?"npm":null);case"yarn":return`${nodeSetup(t?"yarn":null)}${n?" - run: corepack enable\n":""}`;case"bun":return` - uses: oven-sh/setup-bun@v2\n${nodeSetup(null)}`}}function skipRootInstall(e,t){return!1===e.hasRootPackage&&"."!==t}function hostDirComment(e){return"."===e?"":` # The canvas host under \`${e}/\` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so the\n # host's dependencies are installed here, explicitly.\n`}function runBlockStep(e){const t=e.map(e=>` ${e}`).join("\n");return` - run: |\n${t}\n`}function renderVisualReviewWorkflow(e){const{packageManager:t,hasLockfile:n}=e,r=e.tempoDir.replace(/\\/g,"/").replace(/\/+$/,"")||".";if("."!==r&&!/^[A-Za-z0-9_./-]+$/.test(r))throw new Error(`Unsupported canvas-host directory name: ${e.tempoDir}`);const s=e.defaultBranch.trim();if(!isValidGitBranchName(s))throw new Error(`Unsupported default branch name: ${JSON.stringify(e.defaultBranch)}`);for(const[e,t]of[["install block",TM],["cache block",kM],["branch line",SM]])if(!xM.includes(t))throw new Error(`visual-review workflow template no longer contains the ${e} the renderer rewrites`);const i=e.hasPackageManagerField??!1,o=e.lockfile?.trim()||AM[t];if(!/^[A-Za-z0-9_.-]+$/.test(o))throw new Error(`Unsupported lockfile name: ${o}`);const a=(e.customInstall??"").replace(/\r\n?/g,"\n").split("\n").map(e=>e.trimEnd()).filter(e=>e.trim().length>0),c=a.length>0?` # Your tempo.config.json scripts.install, run from \`${r}/\` exactly as\n # Tempo's own canvas host runs it. It must install BOTH the project root\n # and the canvas host.\n${runBlockStep(a.map((e,t)=>0===t&&"."!==r?`cd ${r} && ${e}`:e))}`:`${skipRootInstall(e,r)?"":` - run: ${rootInstallCommand(t,n)}\n`}${hostDirComment(r)}${"."===r?"":` - run: cd ${r} && ${hostInstallCommand(t)}\n`}`,l=`${setupSteps(t,n,i,e.nodeVersionFile)}${c}`,d="."===r?"node_modules/.vite":`${r}/node_modules/.vite`,u=` - uses: actions/cache@v4\n with:\n path: ${d}\n key: visual-review-vite-\${{ runner.os }}-\${{ hashFiles('**/${o}') }}\n`;return xM.replace(TM,l).replace(kM,u).replace(SM,` branches: [${yamlBranchScalar(s)}]`)}function analyzeExistingWorkflow(e,t){const n=e.split("\n").filter(e=>!/^\s*#/.test(e)).join("\n"),r=/@tempo-ai\/visual-review@[^\s"']+[ \t]+claim(?=[ \t]*(?:$|[|&;#'"]))/m.test(n.replace(/\\\r?\n[ \t]*/g," ")),s=[],push2=e=>s.push(e);/id-token:\s*write/.test(n)||push2({code:"missing_id_token_write",message:"The workflow does not grant `id-token: write`.",fix:"Add `id-token: write` under `permissions:` — GitHub OIDC is the only credential Tempo's ingest accepts; without it every upload is rejected with 401."});const i=[["statuses: write",/statuses:\s*write/],["pull-requests: write",/pull-requests:\s*write/],["contents: read",/contents:\s*(read|write)/]].filter(([,e])=>!e.test(n)).map(([e])=>e);i.length>0&&push2({code:"missing_permissions",message:`The workflow does not grant ${i.join(", ")}.`,fix:"Under `permissions:` grant `contents: read` (checkout), `statuses: write` (compatibility with older CLI releases) and `pull-requests: write` (the sticky report comment). Current releases publish statuses through the Tempo GitHub App."}),workflowHasPullRequestTrigger(n)||push2({code:"missing_pull_request_trigger",message:"The workflow does not run on pull requests.",fix:"Add a `pull_request:` trigger with `types: [opened, synchronize, reopened, edited, labeled, unlabeled]` — PR runs are what get captured, compared and gated."});const o=t.defaultBranch;workflowRunsOnPushTo(n,o)||push2({code:"missing_default_branch_push",message:`The workflow does not run on pushes to \`${o}\`.`,fix:`Add a \`push: { branches: [${o}] }\` trigger — pushes to the default branch publish the baselines every PR compares against; without them each PR reports everything as new.`});const a=[...n.matchAll(/@tempo-ai\/visual-review@([^\s"']+)/g)];if(0===a.length)push2({code:"not_using_published_cli",message:"The workflow does not call `npx --yes @tempo-ai/visual-review@…`.",fix:"Run capture through the published CLI (`npx --yes @tempo-ai/visual-review@latest capture --parallel 2`); it infers every run parameter from the Actions environment and mints its own OIDC tokens."});else{const e=new Set(a.map(e=>e[1])),acceptable=e=>"latest"===e||/^\d+(\.\d+){0,2}$/.test(e),t=[...e].filter(e=>!acceptable(e));t.length>0&&push2({code:"unpinned_or_prerelease_cli",message:`The CLI is pinned to ${t.map(e=>`@${e}`).join(", ")}.`,fix:"Pin `@tempo-ai/visual-review@latest` (or a release version); `@next` and other dist-tags track pre-release builds."}),/visual-review@[^\s"']+\s+capture\b/.test(n)||push2({code:"missing_capture_step",message:"No `capture` step runs the CLI.",fix:"Add `npx --yes @tempo-ai/visual-review@latest capture --parallel 2` (with `TEMPO_DEVSERVER_PROTECTED_ROOTS: ${{ github.workspace }}`) after the install and browser steps — without it nothing is captured or compared."}),r||push2({code:"missing_claim_step",message:"No `claim` step runs before dependency setup.",fix:"Add `npx --yes @tempo-ai/visual-review@latest claim` as the first step after checkout (and `claim --release` under `if: always()`), so stacked PRs wait on the baseline lease instead of capturing it twice."}),/visual-review@[^\s"']+\s+report\b/.test(n)||push2({code:"missing_report_step",message:"No `report` job posts the verdict and sticky PR comment.",fix:"Add a `report` job (`needs: capture`, `if: github.event_name == 'pull_request'`) running `npx --yes @tempo-ai/visual-review@latest report --status-url … --pr … --sha …`."})}n.includes("visual-review:bypass")||push2({code:"missing_bypass_guard",message:"The `visual-review:bypass` label is not honored.",fix:"Gate capture on `!contains(github.event.pull_request.labels.*.name, 'visual-review:bypass')` and add the `bypass` job that posts success — the incident escape hatch."}),n.includes("\x3c!-- tempo-no-visual-change --\x3e")||push2({code:"missing_no_visual_change_guard",message:"The `\x3c!-- tempo-no-visual-change --\x3e` PR-body declaration is not honored.",fix:"Gate capture on `!contains(github.event.pull_request.body, '\x3c!-- tempo-no-visual-change --\x3e')` and add the `no-visual-change` job that posts success."});const c=/state=pending/.test(n)&&/context=visual-review/.test(n);return r||c||push2({code:"missing_pending_status",message:"The workflow never posts the `visual-review` status as pending.",fix:"Add `npx --yes @tempo-ai/visual-review@latest claim` after checkout and before dependency setup; it posts pending on the PR head through the Tempo GitHub App, so every visual-review status has the same publisher."}),s}function mappingBlock(e,t){const n=e.findIndex(e=>new RegExp(`^\\s*${t}:\\s*(\\{\\s*\\}\\s*)?$`).test(e));if(-1===n)return null;const r=e[n].match(/^\s*/)[0].length,s=[];for(let t=n+1;t<e.length;t+=1){const n=e[t];if(""===n.trim())continue;const i=n.match(/^\s*/)[0].length;if(i<=r)break;s.push(n)}return s}function listEntries(e,t){const n=e.findIndex(e=>new RegExp(`^\\s*${t}:`).test(e));if(-1===n)return null;const r=e[n],s=new RegExp(`${t}:\\s*\\[([^\\]]*)\\]`).exec(r),i=[];if(s)i.push(...splitFlowSequence(s[1]));else{const t=r.match(/^\s*/)[0].length;for(let r=n+1;r<e.length;r+=1){const n=e[r],s=n.match(/^\s*/)[0].length;if(s<=t)break;const o=/^\s*-\s*(.*)$/.exec(n);o&&i.push(o[1])}}return i.map(e=>unquoteYamlScalar(e.trim()))}function splitFlowSequence(e){const t=[];let n="",r=null;for(let s=0;s<e.length;s+=1){const i=e[s];"'"!==r?'"'!==r?"'"!==i&&'"'!==i?","!==i?n+=i:(t.push(n),n=""):(r=i,n+=i):(n+=i,"\\"===i&&s+1<e.length?(s+=1,n+=e[s]):'"'===i&&(r=null)):(n+=i,"'"===i&&("'"===e[s+1]?(n+="'",s+=1):r=null))}return t.push(n),t.filter(e=>""!==e.trim())}function unquoteYamlScalar(e){return e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).replace(/''/g,"'"):e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(["\\/])/g,"$1"):e}function branchPatternToRegExp(e){let t="";for(let n=0;n<e.length;n+=1){const r=e[n];if("\\"===r&&n+1<e.length)n+=1,t+=e[n].replace(/[.\\^$|(){}[\]*+?]/g,"\\$&");else if("*"===r)"*"===e[n+1]?(t+=".*",n+=1):t+="[^/]*";else if("?"===r||"+"===r)t+=r;else if("["===r){const r=e.indexOf("]",n);-1===r?t+="\\[":(t+=`[${e.slice(n+1,r).replace(/\\/g,"\\\\")}]`,n=r)}else t+=r.replace(/[.\\^$|(){}]/g,"\\$&")}return new RegExp(`^${t}$`)}function matchesBranch(e,t){let n=!1;for(const r of e){const e=r.startsWith("!"),s=e?r.slice(1):r;if(!s)continue;let i;try{i=branchPatternToRegExp(s).test(t)}catch{i=s===t}i&&(n=!e)}return n}function workflowRunsOnPushTo(e,t){if(/^\s*on:\s*push\s*$/m.test(e))return!0;const n=/^\s*on:\s*\[([^\]]*)\]/m.exec(e);if(n&&/\bpush\b/.test(n[1]))return!0;const r=mappingBlock(e.split("\n"),"push");if(null===r)return!1;const s=listEntries(r,"branches-ignore");if(s&&matchesBranch(s,t))return!1;const i=listEntries(r,"branches");return null===i||matchesBranch(i,t)}function workflowHasPullRequestTrigger(e){if(/^\s*on:\s*pull_request\s*$/m.test(e))return!0;const t=/^\s*on:\s*\[([^\]]*)\]/m.exec(e);return!(!t||!/\bpull_request\b/.test(t[1]))||/^\s*pull_request:\s*(\{\s*\}\s*)?$/m.test(e)}var CM='# Written by Tempo visual-review onboarding (visual_review_init). Bitbucket\n# reads ONE bitbucket-pipelines.yml per repository: when you already have\n# one, merge the `tempo-visual-review` step and the two pipeline entries\n# below into it and keep your own pipelines. The corepack line and the two\n# install lines are the package-manager-specific part; init rewrites them\n# for npm / yarn / bun. Keep every `npx --yes @tempo-ai/visual-review@latest …`\n# line as it is. The CLI comes from npm, never from this checkout; the\n# checkout\'s own install scripts and canvas host do run inside the step (as\n# in any CI), so treat it like your other pipelines.\n#\n# What Bitbucket can and cannot do here:\n# - Identity: `oidc: true` gives the step a Bitbucket-signed token\n# (BITBUCKET_STEP_OIDC_TOKEN). It cannot be re-minted mid-step, so claim,\n# capture and report run in ONE step, within that token\'s lifetime.\n# - The `visual-review` build status is posted by Tempo through the\n# repository grant you authorize in Tempo (visual_review_doctor →\n# bitbucket_grant). Portal approvals update it without re-running this\n# step, and a new push needs a new approval.\n# - Reporting works on every plan. BLOCKING merges on the verdict needs the\n# Tempo custom merge check (a Bitbucket Forge app) on a plan that supports\n# custom merge checks (Premium). "Minimum successful builds" counts every\n# build status, so it is not an exact "Tempo approved" requirement.\n# - Bitbucket has no pull-request labels, so there is no bypass label. The\n# `\x3c!-- tempo-no-visual-change --\x3e` declaration in the PR description works.\n# - The sticky report comment needs a repository access token with\n# pull-request write access, stored as the secured repository variable\n# TEMPO_VISUAL_REVIEW_BITBUCKET_TOKEN. Without it the comment is skipped;\n# the build status still posts.\nimage: node:24-bookworm\n\ndefinitions:\n caches:\n tempo-vite: tempo/node_modules/.vite\n steps:\n - step: &tempo-visual-review\n name: Tempo visual review\n oidc: true\n clone:\n # Full history: the merge-base ancestor chain is the baseline key.\n depth: full\n # A PR may first wait for another run\'s baseline and then render both\n # the merge-base and its own head.\n max-time: 90\n # Chromium plus the canvas host\'s devserver need more than 4 GB.\n size: 2x\n caches:\n - tempo-vite\n script:\n # Capture the PR head commit, not a merge of the destination branch.\n - git checkout --force --detach "$BITBUCKET_COMMIT"\n # Announces intent before dependency/browser setup so stacked PRs\n # wait on the baseline lease instead of duplicating a capture.\n - npx --yes @tempo-ai/visual-review@latest claim || echo "capture claim announcement unavailable; capture claims after setup"\n - corepack enable\n - pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so\n # the host\'s dependencies are installed here, explicitly.\n - (cd tempo && pnpm install --no-frozen-lockfile)\n # Chromium matching the CLI\'s own pinned playwright, plus its shared\n # libraries.\n - npx --yes @tempo-ai/visual-review@latest install-browsers\n # `capture` infers PR-vs-main, head SHA, branch, merge-base and\n # repository from the BITBUCKET_* environment and authenticates with\n # the step\'s OIDC token. A PR whose description carries the\n # no-visual-change declaration is skipped here.\n - TEMPO_DEVSERVER_PROTECTED_ROOTS="$BITBUCKET_CLONE_DIR" npx --yes @tempo-ai/visual-review@latest capture --parallel 2\n # Polls the run until Tempo has compared it, then upserts the sticky\n # PR comment. A no-op on branch pipelines.\n - npx --yes @tempo-ai/visual-review@latest report\n after-script:\n # A finished capture has already consumed its claim; this only\n # releases a lease left behind by a setup failure.\n - npx --yes @tempo-ai/visual-review@latest claim --release || echo "capture claim release unavailable; the lease expires on its own"\n # A failed step must not strand the status at in progress. Only\n # replaces an in-progress or absent status, never a delivered verdict.\n - if [ "$BITBUCKET_EXIT_CODE" != "0" ]; then npx --yes @tempo-ai/visual-review@latest report --fallback-failure; fi\n\npipelines:\n pull-requests:\n \'**\':\n - step: *tempo-visual-review\n branches:\n # Your default branch: pushes here publish the baseline PRs compare against.\n main:\n - step: *tempo-visual-review\n',IM="bitbucket-pipelines.yml",PM="tempo-visual-review",DM="TEMPO_VISUAL_REVIEW_BITBUCKET_TOKEN",RM="node:24-bookworm",NM=" - corepack enable\n - pnpm install --frozen-lockfile\n # The canvas host under `tempo/` is its own package. Capture never\n # mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so\n # the host's dependencies are installed here, explicitly.\n - (cd tempo && pnpm install --no-frozen-lockfile)\n",OM=" tempo-vite: tempo/node_modules/.vite\n",FM=" # Your default branch: pushes here publish the baseline PRs compare against.\n main:\n",LM=" name: Tempo visual review\n",MM=" ";function setupLines(e){switch(e){case"pnpm":case"yarn":return`${MM}- corepack enable\n`;case"npm":return"";case"bun":return`${MM}- npm install -g bun@1\n`}}function yamlBranchKey(e){const t=/^[A-Za-z0-9_./-]+$/.test(e)&&!/^(true|false|yes|no|on|off|null|y|n)$/i.test(e)&&!/^[-+.]?\d/.test(e);return t?e:`'${e.replace(/'/g,"''")}'`}function normalizeTempoDir(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"")||".";if("."!==t&&!/^[A-Za-z0-9_./-]+$/.test(t))throw new Error(`Unsupported canvas-host directory name: ${e}`);return t}function validatedBranch(e){const t=e.trim();if(!isValidGitBranchName(t)||/[{}]/.test(t))throw new Error(`Unsupported default branch name: ${JSON.stringify(e)}`);return t}function customInstallItem(e,t){const n=["set -e",..."."===t?[]:[`cd ${t}`],...e].map(e=>`${MM} ${e}`);return`${MM}- |\n${MM} (\n${n.join("\n")}\n${MM} )\n`}function renderBitbucketPipelines(e){const{packageManager:t,hasLockfile:n}=e,r=normalizeTempoDir(e.tempoDir),s=validatedBranch(e.defaultBranch);for(const[e,t]of[["install block",NM],["cache line",OM],["branch block",FM]])if(!CM.includes(t))throw new Error(`visual-review Bitbucket template no longer contains the ${e} the renderer rewrites`);const i=(e.customInstall??"").replace(/\r\n?/g,"\n").split("\n").map(e=>e.trimEnd()).filter(e=>e.trim().length>0),o=i.length>0?`${MM}# Your tempo.config.json scripts.install, run from \`${r}/\` exactly as\n${MM}# Tempo's own canvas host runs it, in a subshell so the directory change\n${MM}# stays out of the lines below. It must install BOTH the project root and\n${MM}# the canvas host.\n${customInstallItem(i,r)}`:`${skipRootInstall(e,r)?"":`${MM}- ${rootInstallCommand(t,n)}\n`}${"."===r?"":`${MM}# The canvas host under \`${r}/\` is its own package. Capture never\n${MM}# mutates this checkout (TEMPO_DEVSERVER_PROTECTED_ROOTS below), so\n${MM}# the host's dependencies are installed here, explicitly.\n${MM}- (cd ${r} && ${hostInstallCommand(t)})\n`}`,a="."===r?"node_modules/.vite":`${r}/node_modules/.vite`;return CM.replace(NM,`${setupLines(t)}${o}`).replace(OM,` tempo-vite: ${a}\n`).replace(FM,FM.replace(" main:\n",` ${yamlBranchKey(s)}:\n`))}function renderBitbucketPipelinesStepSnippet(e){const t=renderBitbucketPipelines(e),n=t.indexOf("definitions:\n");if(-1===n||!t.includes(LM))throw new Error("visual-review Bitbucket template no longer contains the definitions block the snippet is cut from");return t.slice(n).replace(LM,`${LM} # Pinned on the step so it never inherits another global image.\n image: ${RM}\n`)}function bitbucketMergeInstructions(e){return["Bitbucket reads ONE bitbucket-pipelines.yml: merge into it, never replace it, and keep the existing pipelines.",`Put the \`tempo-vite\` cache under \`definitions.caches\` and the \`&${PM}\` step under \`definitions.steps\` (create either key if missing). The anchor must appear above every \`*${PM}\` alias.`,`Add \`- step: *${PM}\` to EVERY \`pipelines.pull-requests\` pattern (add \`'**':\` if there is none): a PR runs the pattern matching its source branch, so a pattern without the step is never captured or gated.`,`Add \`- step: *${PM}\` to the \`pipelines.branches\` entry for \`${e}\` (append it to existing steps, or create the entry): default-branch pushes publish the baselines PRs compare against.`,"Keep `oidc: true`, `clone: depth: full`, and claim → installs → capture → report in this ONE step with its after-script: the step's OIDC token cannot be re-minted in a later step. Keep every `npx --yes @tempo-ai/visual-review@latest …` line as it is.","`size: 2x` (Chromium plus the devserver need more than 4 GB) doubles that step's build minutes; say so when proposing the merge."]}var UM=String.raw`@tempo-ai\/visual-review@[^\s"']+`,jM=String.raw`(?=[ \t]*(?:$|[|&;#'"]))`,BM=new RegExp(`${UM}[ \\t]+claim${jM}`,"m"),$M=new RegExp(`${UM}[ \\t]+claim[ \\t]+--release\\b`),WM=new RegExp(`${UM}[ \\t]+capture\\b`),HM=new RegExp(`${UM}[ \\t]+report\\b([^\\n]*)`,"g"),qM=new RegExp(`${UM}[ \\t]+report[ \\t]+--fallback-failure\\b`);function indentOf(e){return e.match(/^\s*/)[0].length}function joinContinuations(e){return e.replace(/\\\r?\n[ \t]*/g," ")}function hasReport(e){return[...e.matchAll(HM)].some(e=>!/--fallback-failure\b/.test(e[1]??""))}function sectionLines(e,t,n=!1){const r=new RegExp(`^${n?"":"\\s*"}${t}:\\s*$`),s=e.findIndex(e=>r.test(e));if(-1===s)return null;const i=indentOf(e[s]),o=[];for(let t=s+1;t<e.length;t+=1){const n=e[t];if(""===n.trim()){o.push(n);continue}const r=indentOf(n);if(!(r>i||r===i&&/^\s*-(\s|$)/.test(n)))break;o.push(n)}return o}function parseKey(e){const t=/^\s*(?:'((?:[^']|'')*)'|"((?:[^"\\]|\\.)*)"|([^\s'"#-][^#]*?))\s*:\s*(?:#.*)?$/.exec(e);return t?void 0!==t[1]?unquoteYamlScalar(`'${t[1]}'`):void 0!==t[2]?unquoteYamlScalar(`"${t[2]}"`):t[3]??null:null}function childEntries(e){const t=e.find(e=>""!==e.trim());if(!t)return[];const n=indentOf(t),r=[];let s=null;for(const t of e)if(""!==t.trim()){if(indentOf(t)===n&&!/^\s*-(\s|$)/.test(t)){const e=parseKey(t);s=null===e?null:{key:e,lines:[]},s&&r.push(s);continue}s?.lines.push(t)}else s?.lines.push(t);return r}function stepBlocks(e){const t=[];for(let n=0;n<e.length;n+=1){const r=/^\s*(?:-\s+)?step:\s*(?:&([A-Za-z0-9_-]+))?\s*$/.exec(e[n]);if(!r)continue;const s=e[n].indexOf("step:"),i=[];for(let t=n+1;t<e.length;t+=1){const n=e[t];if(""!==n.trim()&&indentOf(n)<=s)break;i.push(n)}t.push({anchor:r[1]??null,lines:i,text:i.join("\n")})}return t}function globSource(e){let t="";for(let n=0;n<e.length;n+=1){const r=e[n];if("*"===r)"*"===e[n+1]?(t+=".*",n+=1):t+="[^/]*";else if("?"===r)t+="[^/]";else if("{"===r){const r=e.indexOf("}",n);-1===r?t+="\\{":(t+=`(?:${e.slice(n+1,r).split(",").map(globSource).join("|")})`,n=r)}else t+=r.replace(/[.\\^$|()[\]+}]/g,"\\$&")}return t}function bitbucketGlobMatches(e,t){try{return new RegExp(`^${globSource(e)}$`).test(t)}catch{return e===t}}function analyzeExistingBitbucketPipelines(e,t){const n=e.replace(/\r\n?/g,"\n").split("\n").filter(e=>!/^\s*#/.test(e)),r=n.join("\n"),s=[],push2=e=>s.push(e),i=[...r.matchAll(/@tempo-ai\/visual-review@([^\s"']+)/g)];if(0===i.length)return[{code:"not_using_published_cli",message:"bitbucket-pipelines.yml has no step that runs `npx --yes @tempo-ai/visual-review@…`.",fix:"Merge the `tempo-visual-review` step and its two pipeline entries into this file (visual_review_init returns them as merge_proposal; it never edits an existing file). Keep the existing pipelines."}];const o=new Set(i.map(e=>e[1])),a=[...o].filter(e=>!("latest"===e||/^\d+(\.\d+){0,2}$/.test(e)));a.length>0&&push2({code:"unpinned_or_prerelease_cli",message:`The CLI is pinned to ${a.map(e=>`@${e}`).join(", ")}.`,fix:"Pin `@tempo-ai/visual-review@latest` (or a release version); `@next` and other dist-tags track pre-release builds."});const c=stepBlocks(n).filter(e=>e.text.includes("@tempo-ai/visual-review@")),l=c.length>0?c:[{anchor:null,lines:n,text:r}],d=l.filter(e=>WM.test(e.text));0===d.length&&push2({code:"missing_capture_step",message:"No step runs the CLI's `capture`.",fix:'Add `TEMPO_DEVSERVER_PROTECTED_ROOTS="$BITBUCKET_CLONE_DIR" npx --yes @tempo-ai/visual-review@latest capture --parallel 2` to the Tempo step\'s script after the install and `install-browsers` lines — without it nothing is captured or compared.'});const u=d.length>0?d:l,p=l.filter(e=>!u.includes(e)),claimStart=e=>BM.test(joinContinuations(e.text)),m=u.some(e=>!claimStart(e)),f=u.some(e=>!hasReport(e.text)),g=p.some(claimStart),y=p.some(e=>hasReport(e.text));(m&&g||f&&y)&&push2({code:"split_steps",message:"`claim`, `capture` and `report` do not all run in the same step.",fix:"Run them in ONE step with `oidc: true` (claim, installs, install-browsers, capture, report): each step gets its own OIDC token and it cannot be re-minted mid-step, so a capture claimed in one step cannot be continued or reported from another."}),m&&!g&&push2({code:"missing_claim_step",message:"No `claim` runs before dependency setup.",fix:'Add `npx --yes @tempo-ai/visual-review@latest claim || echo "capture claim announcement unavailable; capture claims after setup"` right after the `git checkout` line, so stacked PRs wait on the baseline lease instead of capturing it twice.'}),f&&!y&&push2({code:"missing_report_step",message:"No `report` runs after capture.",fix:"Add `npx --yes @tempo-ai/visual-review@latest report` after `capture` in the same step — it waits for Tempo's comparison and upserts the sticky PR comment."}),u.some(e=>!/^\s*oidc:\s*true\s*$/m.test(e.text))&&push2({code:"missing_oidc",message:"The Tempo step does not set `oidc: true`.",fix:"Add `oidc: true` to the step — the step's Bitbucket OIDC token is the only credential Tempo's ingest accepts from Pipelines; without it every upload is rejected."});const b=sectionLines(n,"clone",!0)??[],v=b.some(e=>/^\s*depth:\s*full\s*$/.test(e)),fullClone=e=>/^\s*depth:\s*full\s*$/m.test(e.text)||v&&!/^\s*depth:/m.test(e.text);u.some(e=>!fullClone(e))&&push2({code:"shallow_clone",message:"The Tempo step clones shallow history (Bitbucket's default clone depth is 50).",fix:"Add `clone:` with `depth: full` to the step — the merge-base ancestor chain is the baseline key, so a shallow clone misses baselines."});const afterScript=e=>joinContinuations((sectionLines(e.lines,"after-script")??[]).join("\n"));u.some(e=>!$M.test(afterScript(e)))&&push2({code:"missing_claim_release",message:"The step's after-script does not release the capture claim.",fix:'Under the step\'s `after-script:` add `npx --yes @tempo-ai/visual-review@latest claim --release || echo "capture claim release unavailable; the lease expires on its own"` — otherwise a setup failure holds the baseline lease until it expires.'}),u.some(e=>{const t=afterScript(e);return!qM.test(t)||!t.includes("BITBUCKET_EXIT_CODE")})&&push2({code:"missing_fallback_failure",message:"The step's after-script does not post a fallback failure when the step fails.",fix:'Under `after-script:` add `if [ "$BITBUCKET_EXIT_CODE" != "0" ]; then npx --yes @tempo-ai/visual-review@latest report --fallback-failure; fi` — otherwise a failed step leaves the `visual-review` status in progress.'});const w=l.map(e=>e.anchor).filter(e=>null!==e),runsTempoStep=e=>{const t=e.join("\n");return WM.test(t)||w.some(e=>new RegExp(`\\*${e}(?![\\w-])`).test(t))},x=childEntries(sectionLines(n,"pipelines",!0)??[]),entry=e=>x.find(t=>t.key===e),S=childEntries(entry("pull-requests")?.lines??[]),E=S.filter(e=>!runsTempoStep(e.lines));(0===S.length||E.length>0)&&push2({code:"missing_pull_request_pipeline",message:0===S.length||E.length===S.length?"No `pipelines.pull-requests` pattern runs the Tempo step.":`The pull-requests pattern(s) ${E.map(e=>`\`${e.key}\``).join(", ")} do not run the Tempo step.`,fix:`Add \`- step: *${PM}\` to every \`pipelines.pull-requests\` pattern (\`'**':\` covers every source branch) — a PR runs the pattern matching its source branch, so a pattern without the step is never captured or gated.`});const A=t.defaultBranch,C=childEntries(entry("branches")?.lines??[]),I=C.find(e=>e.key===A),P=I?[I]:C.filter(e=>bitbucketGlobMatches(e.key,A)),R=entry("default"),N=P.length>0?P.every(e=>runsTempoStep(e.lines)):void 0!==R&&runsTempoStep(R.lines);return N||push2({code:"missing_default_branch_pipeline",message:`Pushes to \`${A}\` do not run the Tempo step.`,fix:`Add \`- step: *${PM}\` to the \`pipelines.branches\` entry for \`${A}\` (create it if absent) — default-branch pushes publish the baselines every PR compares against; without them each PR reports everything as new.`}),s}var zM=wM(pM),GM="visual-review",VM=".github/workflows/visual-review.yml",KM="visual-review:bypass",XM="\x3c!-- tempo-no-visual-change --\x3e",YM=class extends Error{constructor(e,t){super(t),this.name="VisualReviewSetupError",this.code=e}};function toPosix6(e){return e.replace(/\\/g,"/")}function errorMessage2(e){return e instanceof Error?e.message:String(e)}async function exists3(e){try{return await hM(e),!0}catch{return!1}}async function assertWriteInsideRepo(e,t){const n=await yM(e);let r=vM.resolve(t);for(;!await exists3(r);){const e=vM.dirname(r);if(e===r)break;r=e}const s=await yM(r),i=vM.relative(n,s);if(i.startsWith("..")||vM.isAbsolute(i))throw new YM("path_outside_repo",`${toPosix6(vM.relative(e,t))} resolves outside the repository (${s}), so nothing was written. Replace that symlink with a real directory or file, then re-run visual_review_init.`)}async function runGit(e,t){try{const{stdout:n}=await zM("git",t,{cwd:e,timeout:1e4,maxBuffer:1048576,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}),r=n.trim();return r.length>0?r:null}catch{return null}}async function resolveRepoIdentity(e,t={}){const n=await runGit(e,["rev-parse","--is-inside-work-tree"]),r="true"===n,s=r?await runGit(e,["config","--get","remote.origin.pushurl"])??await runGit(e,["config","--get","remote.origin.url"]):null,i=normalizeRepoUrl2(s),o=i?i.split("/")[0]??null:null,a=i?githubRepoFromKey2(i):null,c=i?bitbucketRepoFromKey2(i):null;let l=null,d="assumed";if(r){const t=await runGit(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);t&&(l=t.replace(/^origin\//,""),d="origin_head")}if(!l&&a&&t.githubApi)try{const e=await t.githubApi(`repos/${a}`);"string"==typeof e.default_branch&&e.default_branch&&(l=e.default_branch,d="github")}catch{}if(!l&&c&&t.bitbucketApi)try{const e=await t.bitbucketApi({method:"GET",path:bitbucketRepoPath(c)}),n=e?.mainbranch?.name;"string"==typeof n&&n&&(l=n,d="bitbucket")}catch{}if(!l&&r)for(const t of["main","master"]){const n=await runGit(e,["rev-parse","--verify","--quiet",`refs/heads/${t}`]);if(n){l=t,d="local_branch";break}}const u=r?await runGit(e,["rev-parse","--abbrev-ref","HEAD"]):null;return{repoRoot:e,isGitRepo:r,remoteUrl:s,repoKey:i,host:o,githubRepo:a,bitbucketRepo:c,defaultBranch:l??"main",defaultBranchSource:d,currentBranch:u}}function bitbucketRepoPath(e){const[t,n]=e.split("/");return`/repositories/${encodeURIComponent(t??"")}/${encodeURIComponent(n??"")}`}async function readHostConfig(e){try{const t=await resolveTempoConfig(e);return{config:{tempoDir:t.tempoRoot,pagesDir:t.pagesDir,install:t.scripts.install,start:t.scripts.start},missing:!1,error:null}}catch(e){const t=e instanceof Error?`${e.name} ${e.message}`:String(e),n=/ConfigMissing|not found|ENOENT/i.test(t);return{config:null,missing:n,error:n?null:errorMessage2(e)}}}async function enumerateTrackedStoryboards2(e){const t=vM.resolve(e.workspaceRoot),{tempoDir:n,pagesDir:r,projectRoot:s}=await resolveCanvasHostLayout({repoRoot:t,tempoDir:e.tempoDir}),i=await enumerateTrackedStoryboards({tempoDir:n,pagesDir:r}),summarize2=e=>{const n=vM.resolve(s,e.hostCanvasPath);return{canvas_slug:toPosix6(vM.relative(r,vM.dirname(n))),canvas_file:toPosix6(vM.relative(t,n)),storyboard:e.storyboardId,name:e.name??null,threshold:e.threshold??null,ignore_regions:e.ignore?.length??0}};return{tracked:i.tracked.map(summarize2),paused:i.paused.map(summarize2),total_canvases:i.totalCanvases,total_storyboards:i.totalStoryboards,errors:i.errors.map(e=>({file:toPosix6(vM.relative(t,e.filePath)),message:e.message}))}}async function findVisualReviewWorkflow(e){const t=vM.join(e,".github","workflows");if(!await exists3(t))return null;const n=vM.join(e,VM);if(await exists3(n))return{file:VM,content:await gM(n,"utf8")};const r=(await fM(t)).filter(e=>/\.ya?ml$/i.test(e)).sort();for(const n of r){const r=vM.join(t,n),s=await gM(r,"utf8");if(s.includes("@tempo-ai/visual-review")||s.includes(`context=${GM}`))return{file:toPosix6(vM.relative(e,r)),content:s}}return null}async function findBitbucketPipelines(e){const t=vM.join(e,IM);return await exists3(t)?{file:IM,content:await gM(t,"utf8")}:null}var JM=[".gitlab-ci.yml",".circleci/config.yml","bitbucket-pipelines.yml","Jenkinsfile",".buildkite/pipeline.yml","azure-pipelines.yml"];async function classifyCiProvider(e){const t=null!==e.bitbucketRepo,n=[];for(const r of JM)t&&r===IM||await exists3(vM.join(e.repoRoot,r))&&n.push(r);return{provider:"github.com"===e.host?"github-actions":t?"bitbucket-pipelines":e.host?"unsupported":"unknown",host:e.host,workflows_dir_exists:await exists3(vM.join(e.repoRoot,".github","workflows")),other_ci_configs:n,...t?{pipelines_file_exists:await exists3(vM.join(e.repoRoot,IM))}:{}}}function unsupportedCiMessage(e){return`Visual review supports GitHub Actions (github.com) and Bitbucket Pipelines (bitbucket.org) today: ingest authenticates with that CI's OIDC token and the check is a GitHub commit status or Bitbucket build status, so a pipeline on ${e??"another host"} cannot report to Tempo yet. Tell the user, note the interest, and stop — do not hand-write a pipeline for another CI.`}var QM={bun:"bun install",pnpm:"pnpm install --no-frozen-lockfile",yarn:"yarn install",npm:"npm install"},ZM=new Map(["bun","pnpm","yarn","npm"].flatMap(e=>[[buildInstallScript(QM[e]),e],[QM[e],e],[`${e} install`,e]]));function classifyInstallScript(e,t){const n=t?.pm??"npm",r=e?.trim()??"";if(!r)return{kind:"missing",packageManager:n,customInstall:null,warning:null};const s=ZM.get(r);if(s){const e=t&&t.pm!==s?`tempo.config.json scripts.install uses ${s} but the repo's lockfile belongs to ${t.pm}; the workflow follows the install script (${s}).`:null;return{kind:"default",packageManager:s,customInstall:null,warning:e}}return{kind:"custom",packageManager:n,customInstall:r,warning:null}}var eU={pnpm:["pnpm-lock.yaml"],npm:["package-lock.json"],yarn:["yarn.lock"],bun:["bun.lock","bun.lockb"]};async function findLockfile(e,t){for(const n of eU[t])if(await exists3(vM.join(e,n)))return n;return null}async function hasPackageManagerField(e){try{const t=JSON.parse(await gM(vM.join(e,"package.json"),"utf8"));return"string"==typeof t.packageManager&&""!==t.packageManager.trim()}catch{return!1}}async function findNodeVersionFile(e){for(const t of[".nvmrc",".node-version"])try{if((await gM(vM.join(e,t),"utf8")).trim())return t}catch{}try{const t=JSON.parse(await gM(vM.join(e,"package.json"),"utf8"));if([t?.volta?.node,t?.engines?.node].some(e=>"string"==typeof e&&""!==e.trim()))return"package.json"}catch{}}var tU="GitHub CLI (`gh`) is not installed or not authenticated on this machine, so branch protection could not be read.";async function readRequiredCheck(e,t,n,r={}){const s=[],record=(e,t,n)=>{t&&s.push({context:t,app_id:n??null,source:e})},i=[],o=[],a=encodeURIComponent(n),unavailable2=()=>({ok:null,required:[],sources:[],reason:tU});try{const n=await e(`repos/${t}/rules/branches/${a}`);i.push("rulesets");for(const e of Array.isArray(n)?n:[])if("required_status_checks"===e.type)for(const t of e.parameters?.required_status_checks??[])record("rulesets",t.context,t.integration_id)}catch(e){const t=e;if(t.unavailable)return unavailable2();o.push(`rulesets read failed (${t.status??"error"})`)}let c=null;try{const n=await e(`repos/${t}/branches/${a}`);c="boolean"==typeof n.protected?n.protected:null}catch(e){const t=e;if(t.unavailable)return unavailable2();o.push(`branch read failed (${t.status??"error"})`)}if(!1===c)i.push("branch_protection");else if(!0===c)try{const n=await e(`repos/${t}/branches/${a}/protection/required_status_checks`);if(i.push("branch_protection"),n.checks&&n.checks.length>0)for(const e of n.checks)record("branch_protection",e.context,e.app_id);else for(const e of n.contexts??[])record("branch_protection",e,null)}catch(e){const t=e;if(t.unavailable)return unavailable2();o.push(403===t.status||404===t.status?"the branch is protected but classic protection details are readable only by repo admins":`branch protection read failed (${t.status??"error"})`)}const l=s.filter(e=>e.context===GM),satisfiable=e=>null===e.app_id||null!==r.tempoAppId&&void 0!==r.tempoAppId&&e.app_id===r.tempoAppId;if(l.length>0&&l.every(satisfiable))return{ok:!0,required:s,sources:i,reason:null};if(l.length>0)return{ok:!1,required:s,sources:i,reason:"bound_to_single_app"};const d=2===i.length;return{ok:!d&&null,required:s,sources:i,reason:d?null:o.join("; ")||"unreadable"}}var nU=["canvas_host","tracked_storyboards","ci_provider","workflow","repo_registered","github_app","required_check","first_run"],rU=["repo_registered","ci_provider","canvas_host","tracked_storyboards","workflow","github_app","first_run","required_check"],sU="This repo isn't connected as a Tempo project in your org. Connect it (Home → Connect your codebase) using the same GitHub URL as `git remote get-url origin`, then re-run visual_review_doctor. Registration is the org opt-in — nothing else needs minting — and nothing below it is worth doing first.",iU=["canvas_host","tracked_storyboards","ci_provider","workflow","repo_registered","bitbucket_grant","merge_enforcement","first_run"],oU=["repo_registered","ci_provider","canvas_host","tracked_storyboards","workflow","bitbucket_grant","first_run","merge_enforcement"],aU=new Set(["merge_enforcement"]),cU="This repo isn't connected as a Tempo project in your org. Connect it (Home → Connect your codebase) using the same Bitbucket URL as `git remote get-url origin`, then re-run visual_review_doctor. Registration is the org opt-in, and nothing below it is worth doing first.";function bitbucketGrantFix(e,t){const n="Why: Tempo posts the `visual-review` build status and verifies PR heads with that grant, so without it portal approvals never reach Bitbucket and the status never turns green.";return t?`The repository grant for ${e} exists, but its Bitbucket connection${t.username?` (${t.username})`:""} is no longer active. Reconnect Bitbucket in Tempo (Settings → Connections → Bitbucket) with an account that has write access to ${e}, then re-run visual_review_init — it re-authorizes the repository with that account. ${n} Re-run visual_review_doctor afterwards.`:`Tempo is not authorized to post visual-review statuses on ${e}. With the user's yes, run visual_review_init: it checks that the Bitbucket account connected to Tempo can write to ${e} and authorizes the repository with it (connect one first in Settings → Connections → Bitbucket if needed). ${n} Re-run visual_review_doctor afterwards.`}function mergeEnforcementFix(e){return`Reporting works on every Bitbucket plan: the \`${GM}\` build status posts on each PR head through the repository grant (bitbucket_grant). BLOCKING merges on the verdict needs the Tempo custom merge check (a Bitbucket Forge app) installed on the workspace and enabled for merges into ${e}, on a plan that supports custom merge checks (Bitbucket Premium). Tempo cannot read whether it is installed, so this row is advisory and does not affect \`ready\`. Do not substitute "Minimum successful builds": it counts every build status on the commit, not Tempo's verdict, so it is not an exact "Tempo approved" requirement. Set up enforcement only after the first capture has reached Tempo, or every PR blocks on a status that never posts.`}var lU={github:{publishWarning:"The commit-status publisher's newest attempt failed, so the GitHub check may be stale — usually the Tempo GitHub App is not installed on the repo (see github_app).",captureFailed:"A capture reached Tempo but the newest run/claim failed. Read the workflow logs (the install step first — the same failure modes as the canvas host), fix the cause, and push again.",noCapture:"No capture has reached Tempo yet. Open a PR (or push to the default branch) with the workflow in place; the check posts pending and a capture claim lands here within about a minute of the push. The full capture and comparison take roughly ten more minutes."},bitbucket:{publishWarning:"The build-status publisher's newest attempt failed, so the Bitbucket `visual-review` status may be stale — usually the repository grant is missing or its Bitbucket connection expired (see bitbucket_grant).",captureFailed:"A capture reached Tempo but the newest run/claim failed. Read the pipeline's step log (the install lines first — the same failure modes as the canvas host), fix the cause, and push again.",noCapture:"No capture has reached Tempo yet. Open a PR (or push to the default branch) with the Tempo step in bitbucket-pipelines.yml and Pipelines enabled for the repository; the `visual-review` build status goes in progress and a capture claim lands here within about a minute of the push. The full capture and comparison take roughly ten more minutes."}};async function safeCheck(e,t){try{return await t()}catch(t){return{id:e,ok:null,reason:"check_failed",error:errorMessage2(t),fix:`The ${e} check itself failed (see error); fix the cause or re-run visual_review_doctor. No other row depends on it.`}}}async function runVisualReviewDoctor(e,t={}){const n=vM.resolve(t.repoRoot??e.workspaceRoot),r=await resolveRepoIdentity(n,{githubApi:e.githubApi,bitbucketApi:e.bitbucketApi}),s=null!==r.bitbucketRepo,i=await readHostConfig(n),o=new Map;let a;o.set("canvas_host",await safeCheck("canvas_host",async()=>{if(!i.config)return{id:"canvas_host",ok:!1,...i.error?{error:i.error}:{},fix:i.missing?"No tempo/tempo.config.json — the canvas host does not exist yet. Call canvas_project_init, then review its install script against this repo (initial_tempo_config + review_notes).":"tempo/tempo.config.json exists but could not be read (see error). Fix the config (canvas_validate reports host_setup_issue details), then re-run visual_review_doctor."};const e="string"==typeof i.config.install&&i.config.install.trim().length>0&&"string"==typeof i.config.start&&i.config.start.trim().length>0;return{id:"canvas_host",ok:e,tempo_dir:toPosix6(vM.relative(n,i.config.tempoDir))||".",canvases_dir:toPosix6(vM.relative(n,i.config.pagesDir)),install:i.config.install,start:i.config.start,...e?{}:{fix:"tempo.config.json is missing scripts.install or scripts.start. Call canvas_project_init, then review its install script against this repo (initial_tempo_config + review_notes)."}}})),o.set("tracked_storyboards",await safeCheck("tracked_storyboards",async()=>{const e=await enumerateTrackedStoryboards2({workspaceRoot:n}),t=e.tracked.length>0&&0===e.errors.length;return{id:"tracked_storyboards",ok:t,count:e.tracked.length,paused:e.paused.length,total_storyboards:e.total_storyboards,total_canvases:e.total_canvases,tracked:e.tracked.slice(0,50),...e.tracked.length>50?{tracked_truncated:e.tracked.length-50}:{},errors:e.errors,...t?{}:{fix:e.errors.length>0?`${e.errors.length} canvas file(s) carry tracking intent the capture cannot honor (listed in errors); fix each declaration — CI enumeration fails loudly on them rather than shrinking the tracked set.`:0===e.total_storyboards?"No storyboards exist yet, so nothing can be tracked. Author a canvas that renders real production components (design-system boards are the best first candidates), then track it with canvas_set_vrt and verify with canvas_verify_vrt.":"Nothing is tracked. Track a small first set with canvas_set_vrt (component storyboards only — design-system boards are the best first candidates; route storyboards such as the home canvas cannot be tracked) and verify each with canvas_verify_vrt until it reports vrt_stable."}}})),o.set("ci_provider",await safeCheck("ci_provider",async()=>{const e=await classifyCiProvider(r),t="github-actions"===e.provider||"bitbucket-pipelines"===e.provider;return{id:"ci_provider",ok:t,provider:e.provider,host:e.host,workflows_dir_exists:e.workflows_dir_exists,other_ci_configs:e.other_ci_configs,...void 0!==e.pipelines_file_exists?{pipelines_file_exists:e.pipelines_file_exists}:{},...t?{}:"unknown"===e.provider?{reason:r.isGitRepo?"no_git_remote":"not_a_git_repo",fix:r.isGitRepo?"The repo has no `origin` remote. Push it to GitHub or Bitbucket Cloud and add the remote — visual review keys everything (registration, ingest, the check) on the hosted repository.":"This folder is not a git repository. Initialize it and push it to GitHub or Bitbucket Cloud first."}:{reason:"unsupported_ci",fix:unsupportedCiMessage(e.host)}}})),o.set("workflow",await safeCheck("workflow",async()=>{if(s)return bitbucketWorkflowCheck(n,r.defaultBranch);const e=await findVisualReviewWorkflow(n),t=e?analyzeExistingWorkflow(e.content,{defaultBranch:r.defaultBranch}):[];return{id:"workflow",ok:null!==e&&0===t.length,file:e?.file??null,drift:t,...e?0===t.length?{}:{fix:`${e.file} exists but drifts from the contract: ${t.map(e=>e.code).join(", ")}. Never rewrite the user's workflow wholesale — propose the exact edits from each drift item's fix.`}:{fix:"Call visual_review_init."}}}));let c=null;if(r.repoKey&&e.visualReviewSetup)try{a=await e.visualReviewSetup.getSetupStatus({repoKey:r.repoKey})}catch(e){c=errorMessage2(e)}const l=r.repoKey?e.visualReviewSetup?c?"convex_error":null===a?"not_signed_in":null:"unavailable_in_environment":"no_git_remote";o.set("repo_registered",{id:"repo_registered",ok:l?null:Boolean(a?.registered),...l?{reason:l,...c?{error:c}:{},fix:"no_git_remote"===l?"Registration keys on the `origin` remote URL — add one first.":"unavailable_in_environment"===l?"Registration can only be checked from a signed-in Tempo session (the desktop app); this environment has no Tempo auth.":"not_signed_in"===l?"Sign in to Tempo, then re-run visual_review_doctor.":"Tempo could not be reached; retry visual_review_doctor."}:a?.registered?{org:a.orgName,organization_id:a.organizationId,project:a.projectName,org_project_id:a.orgProjectId}:{fix:s?cU:sU}}),s&&(o.set("bitbucket_grant",await safeCheck("bitbucket_grant",()=>bitbucketGrantCheck(e,r,a))),o.set("merge_enforcement",{id:"merge_enforcement",ok:null,reason:"not_verifiable",advisory:!0,reporting:"build_status_on_every_plan",blocking:"requires_tempo_merge_check",fix:mergeEnforcementFix(r.defaultBranch)}));let d=null;s||o.set("github_app",await safeCheck("github_app",async()=>{if(!r.githubRepo||!e.visualReviewSetup||!a?.registered)return{id:"github_app",ok:null,reason:r.githubRepo?e.visualReviewSetup?"requires_registration":"unavailable_in_environment":"not_a_github_repo",fix:r.githubRepo?e.visualReviewSetup?"Resolve repo_registered first; the installation probe is gated on registration.":"The GitHub App installation can only be checked from a signed-in Tempo session.":"The Tempo GitHub App only applies to github.com repositories."};let t,n=null;if(e.githubApi)try{await e.githubApi(`repos/${r.githubRepo}`)}catch(e){const t=e;if(403===t.status||404===t.status)return{id:"github_app",ok:null,reason:"repo_not_readable_as_user",fix:`The GitHub account \`gh\` is signed in as cannot read ${r.githubRepo} (HTTP ${t.status}), so the installation was not probed. If that is the wrong account, switch with \`gh auth status\` / \`gh auth switch\`; otherwise check the remote URL and your access, then re-run visual_review_doctor.`};n=t.unavailable?"The user-side GitHub read was skipped (gh unavailable); the probe relied on Tempo registration alone.":`The user-side GitHub read failed transiently (${t.status??errorMessage2(e)}); the probe relied on Tempo registration alone.`}try{t=await e.visualReviewSetup.probeGithubApp({repoKey:r.repoKey})}catch(e){t={status:"error",reason:errorMessage2(e),retryable:!0}}"installed"!==t.status&&"not_installed"!==t.status||(d=t.appId);const s=githubAppCheck(t,r.githubRepo);return n?{...s,warning:n}:s})),s||o.set("required_check",await safeCheck("required_check",async()=>{const t=`Settings → Branches → ${r.defaultBranch} → Require status checks to pass → add \`${GM}\` with source "Any source" (or the Tempo Labs AI app; never GitHub Actions) — needs repo admin; Tempo never changes repo settings for you. Do this only after the first capture has reached Tempo, or every PR blocks on a check that never posts.`;if(!r.githubRepo)return{id:"required_check",ok:null,reason:"not_a_github_repo",fix:"Branch protection applies to github.com repositories only."};if(!e.githubApi)return{id:"required_check",ok:null,reason:"unavailable_in_environment",fix:`Could not read branch protection (no GitHub read in this environment). Make \`${GM}\` a required status check: ${t}`};const n=await readRequiredCheck(e.githubApi,r.githubRepo,r.defaultBranch,{tempoAppId:d});return{id:"required_check",ok:n.ok,required:n.required,sources:n.sources,...n.reason?{reason:n.reason}:{},...n.ok?{}:"bound_to_single_app"===n.reason?{fix:`\`${GM}\` is required but bound to a GitHub App that is not Tempo's, so the verdict Tempo posts (from the Tempo Labs AI app) never satisfies it and the requirement can never turn green. Edit the rule: ${t}`}:{fix:`Make \`${GM}\` a required status check: ${t}`}}})),o.set("first_run",await safeCheck("first_run",async()=>{if(l||!a?.registered)return{id:"first_run",ok:null,reason:l??"requires_registration",fix:"Runs are looked up by repo registration; resolve repo_registered first."};const e=s?lU.bitbucket:lU.github,t=a.latestRun,n=a.latestClaim,r=null!==t||null!==n,i=null!==t&&"error"!==t.state||null!==n&&"failed"!==n.state;return{id:"first_run",ok:i,reached_tempo:r,latest_run:t?{created_at:t.createdAt,completed_at:t.completedAt,trigger:t.trigger,state:t.state,tracked_total:t.trackedTotal,counts:t.counts,gate_satisfied:t.gateSatisfied,approvals_needed:t.approvalsNeeded,gate_satisfied_at:t.gateSatisfiedAt,publish_failing:t.publishFailing}:null,latest_claim:n?{created_at:n.createdAt,updated_at:n.updatedAt,state:n.state}:null,...t?.publishFailing?{warning:e.publishWarning}:{},...i?{}:{reason:r?"capture_failed":"no_capture_yet",fix:r?e.captureFailed:e.noCapture}}}));const u=(s?iU:nU).map(e=>o.get(e)),p=(s?oU:rU).map(e=>o.get(e)).find(e=>!1===e.ok),m=u.filter(e=>!aU.has(e.id)),f=m.filter(e=>null===e.ok),g=m.every(e=>!0===e.ok),y=p?.fix?p.fix:f.length>0?`Every readable check passes; ${f.map(e=>e.id).join(", ")} could not be determined here (${f.map(e=>e.reason??"unknown").join(", ")}).`:s?"Visual review is set up for this repo: tracked storyboards, the pipeline, registration, the repository grant, and a first capture are all in place. Whether merges are BLOCKED on the verdict cannot be verified from Tempo — see merge_enforcement.":"Visual review is fully set up for this repo: tracked storyboards, workflow, registration, the GitHub App, the required check, and a first capture are all in place.";return{repo_root:n,repo_key:r.repoKey,remote_url:r.remoteUrl,default_branch:r.defaultBranch,default_branch_source:r.defaultBranchSource,current_branch:r.currentBranch,org:a?.orgName??null,checks:u,ready:g,next_step:y}}async function bitbucketWorkflowCheck(e,t){const n=await findBitbucketPipelines(e),r=n?analyzeExistingBitbucketPipelines(n.content,{defaultBranch:t}):[];return{id:"workflow",ok:null!==n&&0===r.length,file:n?.file??null,drift:r,...n?0===r.length?{}:{fix:`${n.file} exists but ${r.some(e=>"not_using_published_cli"===e.code)?"has no Tempo visual-review step":`drifts from the contract: ${r.map(e=>e.code).join(", ")}`}. Never rewrite the user's pipelines file wholesale: call visual_review_init for the merge proposal (it never modifies an existing file) and propose the exact edits from each drift item's fix.`}:{fix:"Call visual_review_init."}}}async function bitbucketGrantCheck(e,t,n){const r=t.bitbucketRepo,s=e.visualReviewSetup,i=s?.getBitbucketGrant;if(!s||!i||!n?.registered)return{id:"bitbucket_grant",ok:null,reason:i?"requires_registration":"unavailable_in_environment",fix:i?"Resolve repo_registered first; the repository grant is checked against the org the repo is registered to.":"The Bitbucket repository grant can only be checked from a signed-in Tempo session (the desktop app)."};let o,a=null;if(e.bitbucketApi)try{await e.bitbucketApi({method:"GET",path:bitbucketRepoPath(r)})}catch(e){const t=e,n=t.status??("forbidden"===t.kind?403:"not_found"===t.kind?404:null);if(403===n||404===n)return{id:"bitbucket_grant",ok:null,reason:"repo_not_readable_as_user",fix:`The Bitbucket account connected to Tempo cannot read ${r} (HTTP ${n}), so the grant was not checked. If that is the wrong account, connect the right one in Tempo (Settings → Connections → Bitbucket); otherwise check the remote URL and your access, then re-run visual_review_doctor.`};a=`The user-side Bitbucket read failed (${t.status??errorMessage2(e)}); the grant check relied on Tempo registration alone.`}try{o=await i.call(s,{repoKey:t.repoKey,...n.organizationId?{organizationId:n.organizationId}:{}})}catch(e){return{id:"bitbucket_grant",ok:null,reason:"grant_check_failed",detail:errorMessage2(e),fix:"Tempo could not be reached to check the repository grant; re-run visual_review_doctor in a moment."}}const c=null===o?{id:"bitbucket_grant",ok:null,reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_doctor."}:o.authorized?{id:"bitbucket_grant",ok:!0,username:o.username??null}:{id:"bitbucket_grant",ok:!1,reason:o.grantedByUserId?"grant_inactive":"not_authorized",username:o.username??null,fix:bitbucketGrantFix(r,o.grantedByUserId?{username:o.username??null}:null)};return a?{...c,warning:a}:c}function githubAppCheck(e,t){switch(e.status){case"installed":return{id:"github_app",ok:!0,app_id:e.appId,app_slug:e.appSlug};case"not_installed":return{id:"github_app",ok:!1,reason:"app_not_installed",install_url:e.installUrl,app_id:e.appId,app_slug:e.appSlug,fix:`The Tempo GitHub App isn't installed on ${t}, so portal approvals can't update the \`${GM}\` check — the gate would stay red forever. Ask a GitHub admin of ${t.split("/")[0]} to install it${e.installUrl?`: ${e.installUrl}`:" (Tempo Labs AI, the app used to connect repos to Tempo)"} and grant it this repository. Re-run visual_review_doctor afterwards.`};case"app_unconfigured":return{id:"github_app",ok:null,reason:"app_unconfigured",detail:e.reason,fix:"This Tempo deployment has no GitHub App credentials configured (a Tempo-side issue, not yours). Approvals will not flip the check until it is fixed; continue with setup and tell the user."};case"repo_not_registered":return{id:"github_app",ok:null,reason:"requires_registration",fix:sU};case"unsupported_host":return{id:"github_app",ok:null,reason:"not_a_github_repo",fix:"The Tempo GitHub App only applies to github.com repositories."};case"error":return{id:"github_app",ok:null,reason:"probe_failed",detail:e.reason,retryable:e.retryable,fix:e.retryable?"GitHub could not be reached to check the installation; re-run visual_review_doctor in a moment.":"The installation check failed; see detail."}}}var dU="## Visual review in pull requests (VRT)",uU=`${dU}\n\nVisual changes are reviewed through **tested storyboards**, not screenshots\npasted into the PR. A tested storyboard is a \`<Storyboard>\` under the\ncanvases root carrying the literal \`vrt\` prop. On every push the Visual\nReview workflow captures the tracked set, diffs it against the baseline from\nthe default branch, and posts the \`${GM}\` commit status;\nreviewers approve the pixel diffs in Tempo's review portal and the status\nturns green without a CI re-run.\n\nEvery PR with a visual change — new features, visual bug fixes, UX\nrefinements, copy changes, canvas-only changes — must leave the changed\nsurface covered by a tested storyboard. If none renders it, add one (or add\n\`vrt\` to an existing storyboard that exercises the change) in the same PR:\nuse \`canvas_set_vrt\`, then run \`canvas_verify_vrt\` until it reports\n\`vrt_stable\` and fix any nondeterminism (live clocks, random data,\nin-flight animation) before pushing — a flaky baseline fails the check for\nevery PR after yours. When it is unclear whether a change is visual, treat\nit as visual and cover it.\n\nPut \`${XM}\` in the PR body ONLY when 100% certain\nthe PR changes no UI and no tested storyboard — no shared component, token,\nor style change, no new or modified storyboards. Any doubt means no marker:\nlet capture run and prove it. The \`${KM}\` label is the\nincident escape hatch, never part of the normal workflow.\n`,pU=`${dU}\n\nVisual changes are reviewed through **tested storyboards**, not screenshots\npasted into the PR. A tested storyboard is a \`<Storyboard>\` under the\ncanvases root carrying the literal \`vrt\` prop. On every push the Tempo\nstep in Bitbucket Pipelines captures the tracked set and diffs it against\nthe baseline from the default branch, and Tempo posts the\n\`${GM}\` build status; reviewers approve the pixel diffs in\nTempo's review portal and the status turns green without re-running the\npipeline. Approvals are per head commit, so a new push needs a new approval.\n\nEvery PR with a visual change — new features, visual bug fixes, UX\nrefinements, copy changes, canvas-only changes — must leave the changed\nsurface covered by a tested storyboard. If none renders it, add one (or add\n\`vrt\` to an existing storyboard that exercises the change) in the same PR:\nuse \`canvas_set_vrt\`, then run \`canvas_verify_vrt\` until it reports\n\`vrt_stable\` and fix any nondeterminism (live clocks, random data,\nin-flight animation) before pushing — a flaky baseline fails the status for\nevery PR after yours. When it is unclear whether a change is visual, treat\nit as visual and cover it.\n\nPut \`${XM}\` in the PR description ONLY when 100%\ncertain the PR changes no UI and no tested storyboard — no shared component,\ntoken, or style change, no new or modified storyboards. Any doubt means no\nmarker: let capture run and prove it.\n`,hU="## Visual review",mU=`${hU}\n\n\x3c!--\nVisual changes are reviewed through tested storyboards (a <Storyboard>\ncarrying the \`vrt\` prop), not evidence pasted here. Make sure the changed\nsurface is covered by one — add it in this PR if none renders it. Capture\nruns on every push; reviewers approve the pixel diffs in the Tempo review\nportal linked from the \`${GM}\` check.\n\nOnly if you are 100% certain this PR changes NO UI and NO tested storyboard:\nput Tempo's hidden no-visual-change marker (an HTML comment whose text is\nexactly "tempo-no-visual-change", spelled as in your agent rules) ABOVE this\ncomment and write: Not applicable — no storyboard changes expected.\n--\x3e\n`,fU="Review initial_workflow before committing it. The install steps mirror tempo.config.json's scripts.install and the repo's lockfile — the same failure modes as the canvas host apply because it IS the same devserver: an app in a workspace/monorepo subdirectory needs the install to run at the workspace root or with the right filter; postinstall codegen (e.g. `prisma generate`) must run before capture; a private registry needs its .npmrc/token as a repository secret exported in the workflow. If scripts.install is custom, it runs verbatim from the canvas-host directory and must cover BOTH the project root and the host. What runs: the CLI comes from npm, but the repo's own install scripts and canvas host (its Vite config, its components) execute inside the job like in any CI; fork PRs get no OIDC token and cannot ingest. The workflow captures on pushes to the default branch (the baseline producer) and on PR events; approvals happen in Tempo's portal and flip the `visual-review` status without a CI re-run. Ask before pushing: the PR that adds this workflow runs it — the merge-base has no tracked boards, so every tracked storyboard reports as new and the user approves the first set in the portal.",gU=`Review initial_workflow (or merge_proposal.snippet) before committing it. The install lines mirror tempo.config.json's scripts.install and the repo's lockfile — the same failure modes as the canvas host apply because it IS the same devserver: an app in a workspace/monorepo subdirectory needs the install to run at the workspace root or with the right filter; postinstall codegen (e.g. \`prisma generate\`) must run before capture; a private registry needs its .npmrc/token as a secured repository variable. If scripts.install is custom, it runs verbatim (in a subshell) from the canvas-host directory and must cover BOTH the project root and the host. What runs: the step uses the ${RM} image; the CLI comes from npm, but the repo's own install scripts and canvas host execute inside the step like in any CI. claim, capture and report must stay in ONE step with \`oidc: true\` — the step's OIDC token cannot be re-minted. The pipeline captures on pushes to the default branch (the baseline producer) and on pull requests; approvals happen in Tempo's portal and update the \`visual-review\` build status without re-running the pipeline. Ask before pushing: the PR that adds this pipeline runs it — the merge-base has no tracked boards, so every tracked storyboard reports as new and the user approves the first set in the portal.`;function appendSeparator(e){return 0===e.length||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}async function runVisualReviewInit(e,t={}){const n=vM.resolve(t.repoRoot??e.workspaceRoot),r=[],s=await readHostConfig(n);if(!s.config)throw new YM("no_tempo_host",s.missing?"No tempo/tempo.config.json — the canvas host does not exist yet, so there is nothing to capture. Call canvas_project_init first, review its install script, then re-run visual_review_init.":`tempo/tempo.config.json could not be read (${s.error}). Fix it (canvas_validate reports host_setup_issue details), then re-run visual_review_init.`);const i=await resolveRepoIdentity(n,{githubApi:e.githubApi,bitbucketApi:e.bitbucketApi});if(!i.repoKey)throw new YM("no_git_remote",i.isGitRepo?"The repo has no `origin` remote. Push it to GitHub or Bitbucket Cloud and add the remote first — the CI config, registration and the check all key on the hosted repository.":"This folder is not a git repository. Initialize it and push it to GitHub or Bitbucket Cloud first.");if(i.bitbucketRepo)return runBitbucketInit(e,n,s.config,i,t);if("github.com"!==i.host)throw new YM("unsupported_ci",unsupportedCiMessage(i.host));const o=toPosix6(vM.relative(n,s.config.tempoDir))||".",a=await detectOwningPackageManager(n),c=classifyInstallScript(s.config.install,a);c.warning&&r.push(c.warning),"missing"===c.kind&&r.push("tempo.config.json has no scripts.install; the workflow uses the lockfile's package manager with a default install."),"assumed"===i.defaultBranchSource&&r.push(`The default branch could not be determined (no origin/HEAD, no local main/master); the workflow assumes \`${i.defaultBranch}\`. Fix the \`push: branches\` trigger if that is wrong.`);const l=t.withAgentRules?await exists3(vM.join(n,"CLAUDE.md"))?"CLAUDE.md":await exists3(vM.join(n,"AGENTS.md"))?"AGENTS.md":null:null,d=".github/PULL_REQUEST_TEMPLATE.md";for(const e of[VM,...l?[l]:[],...t.withPrTemplate?[d]:[]])await assertWriteInsideRepo(n,vM.join(n,e));let u=await findVisualReviewWorkflow(n),p=u?.file??VM,m=!1,f=null;if(!u){const e=await findLockfile(n,c.packageManager);f=renderVisualReviewWorkflow({packageManager:c.packageManager,defaultBranch:i.defaultBranch,tempoDir:o,hasLockfile:null!==e,hasRootPackage:await exists3(vM.join(n,"package.json")),lockfile:e,hasPackageManagerField:await hasPackageManagerField(n),nodeVersionFile:await findNodeVersionFile(n),customInstall:c.customInstall});const t=vM.join(n,VM);await mM(vM.dirname(t),{recursive:!0});try{await bM(t,f,{encoding:"utf8",flag:"wx"}),m=!0}catch(e){if("EEXIST"!==e.code)throw e;f=null,u=await findVisualReviewWorkflow(n),p=u?.file??VM,r.push(`${p} appeared while init was running; it was left untouched and audited instead.`)}}const g=u?analyzeExistingWorkflow(u.content,{defaultBranch:i.defaultBranch}):[];let y=null;if(t.withAgentRules){const e=l;e?y=await appendAgentRules(n,e,uU):r.push("with_agent_rules: neither CLAUDE.md nor AGENTS.md exists at the repo root, so no agent rules were written. Ask the user which file their agents read, create it, and re-run with with_agent_rules.")}let b=null;if(t.withPrTemplate){const e=d,t=vM.join(n,e);b=await eD.withFileLock(t,async()=>{if(await exists3(t)){const n=await gM(t,"utf8");return/^##\s+Visual review\b/im.test(n)?{file:e,written:!1}:(await atomicWriteFile(t,`${n}${appendSeparator(n)}${mU}`),{file:e,written:!0})}await mM(vM.dirname(t),{recursive:!0});try{return await bM(t,`## Summary\n\n\n${mU}\n## Test plan\n\n- [ ]\n`,{encoding:"utf8",flag:"wx"}),{file:e,written:!0}}catch(t){if("EEXIST"!==t.code)throw t;return{file:e,written:!1}}})}const v=[];return u?v.push(0===g.length?`${p} already speaks the contract; nothing to write.`:`Propose the exact edits for each drift item on ${p}; never replace the file wholesale.`):v.push(`Review initial_workflow (${p}) against the repo per review_notes.`),v.push("Track a small first set of component storyboards with canvas_set_vrt and verify each with canvas_verify_vrt until vrt_stable; drop unstable boards and say why.","Commit on a branch and ask before pushing/opening the PR (a third-party-visible action). The PR proves the setup: the check goes pending within a minute and visual_review_doctor's first_run row shows the claim.",`After the first capture: approve the new storyboards in the portal, then ask a repo admin to make \`${GM}\` a required status check with source "Any source" or the Tempo Labs AI app — never GitHub Actions (Settings → Branches → ${i.defaultBranch}). Offer \`gh label create ${KM} --description "Skip visual review (incident escape hatch)"\` as a runnable command.`),{workflow_file:p,written:m,skipped:null!==u,drift:g,initial_workflow:f,package_manager:c.packageManager,install:c.kind,install_command:c.customInstall??s.config.install??null,default_branch:i.defaultBranch,default_branch_source:i.defaultBranchSource,agent_rules:y,pr_template:b,review_notes:fU,warnings:r,next_steps:v}}async function appendAgentRules(e,t,n){const r=vM.join(e,t);return eD.withFileLock(r,async()=>{const e=await gM(r,"utf8");return e.includes(dU)?{file:t,written:!1}:(await atomicWriteFile(r,`${e}${appendSeparator(e)}${n}`),{file:t,written:!0})})}var yU="Tempo posts the `visual-review` build status and verifies PR heads with that grant, so without it portal approvals never reach Bitbucket.";async function ensureBitbucketGrant(e,t){const n=t.bitbucketRepo,r=t.repoKey,s=e.visualReviewSetup;if(!s?.getBitbucketGrant||!s.authorizeBitbucketGrant||!e.bitbucketApi)return{status:"not_authorized",reason:"unavailable_in_environment",fix:"The repository grant can only be set up from a signed-in Tempo session (the desktop app). Run visual_review_init there."};let i;try{const e=await s.getSetupStatus({repoKey:r});if(null===e)return{status:"not_authorized",reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_init."};if(!e.registered)return{status:"not_authorized",reason:"requires_registration",fix:cU};i=e.organizationId??void 0;const t=await s.getBitbucketGrant.call(s,{repoKey:r,...i?{organizationId:i}:{}});if(null===t)return{status:"not_authorized",reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_init."};if(t.authorized)return{status:"authorized",newly_authorized:!1,username:t.username??null}}catch(e){return{status:"not_authorized",reason:"grant_failed",fix:`Tempo could not be reached to check the repository grant (${errorMessage2(e)}); re-run visual_review_init in a moment.`}}const[o]=n.split("/");let a=!1;try{const t=await e.bitbucketApi({method:"GET",path:`/user/workspaces/${encodeURIComponent(o)}/permissions/repositories?q=${encodeURIComponent(`repository.full_name="${n}"`)}&pagelen=10`});a=(t?.values??[]).some(e=>("write"===e.permission||"admin"===e.permission)&&e.repository?.full_name?.toLowerCase()===n.toLowerCase())}catch(e){return{status:"not_authorized",reason:"no_bitbucket_connection",fix:`Connect a Bitbucket account with write access to ${n} in Tempo (Settings → Connections → Bitbucket), then re-run visual_review_init (${errorMessage2(e)}). ${yU}`}}if(!a)return{status:"not_authorized",reason:"no_write_access",fix:`The Bitbucket account connected to Tempo has no write access to ${n}. Connect an account that does (Settings → Connections → Bitbucket) or ask a workspace admin for write access, then re-run visual_review_init. ${yU}`};try{const e=await s.authorizeBitbucketGrant.call(s,{repoKey:r,...i?{organizationId:i}:{}});if(null===e)return{status:"not_authorized",reason:"not_signed_in",fix:"Sign in to Tempo, then re-run visual_review_init."}}catch(e){return{status:"not_authorized",reason:"grant_failed",fix:`Tempo refused the repository grant: ${errorMessage2(e)} Fix that, then re-run visual_review_init.`}}const c=await s.getBitbucketGrant.call(s,{repoKey:r,...i?{organizationId:i}:{}}).catch(()=>null);return{status:"authorized",newly_authorized:!0,username:c?.username??null}}async function runBitbucketInit(e,t,n,r,s){const i=[],o=r.bitbucketRepo,a=toPosix6(vM.relative(t,n.tempoDir))||".",c=await detectOwningPackageManager(t),l=classifyInstallScript(n.install,c);l.warning&&i.push(l.warning),"missing"===l.kind&&i.push("tempo.config.json has no scripts.install; the pipeline uses the lockfile's package manager with a default install."),"assumed"===r.defaultBranchSource&&i.push(`The default branch could not be determined (no origin/HEAD, no Bitbucket read, no local main/master); the pipeline assumes \`${r.defaultBranch}\`. Fix the \`pipelines.branches\` key if that is wrong.`);const d=await findNodeVersionFile(t);d&&i.push(`The step runs on the ${RM} image (Node 24) while this repo pins Node in ${d}. If the project cannot run on Node 24, change the image tag to a matching node image.`),s.withPrTemplate&&i.push("with_pr_template: Bitbucket has no pull-request template file, so nothing was written. Use with_agent_rules for the guidance instead. If the repository uses a default PR description, never put the literal no-visual-change marker in it — every PR opened from it would skip capture.");const u=s.withAgentRules?await exists3(vM.join(t,"CLAUDE.md"))?"CLAUDE.md":await exists3(vM.join(t,"AGENTS.md"))?"AGENTS.md":null:null;for(const e of[IM,...u?[u]:[]])await assertWriteInsideRepo(t,vM.join(t,e));const p=await findLockfile(t,l.packageManager),m={packageManager:l.packageManager,defaultBranch:r.defaultBranch,tempoDir:a,hasLockfile:null!==p,hasRootPackage:await exists3(vM.join(t,"package.json")),customInstall:l.customInstall};let f=await findBitbucketPipelines(t),g=!1,y=null;if(!f){y=renderBitbucketPipelines(m);try{await bM(vM.join(t,IM),y,{encoding:"utf8",flag:"wx"}),g=!0}catch(e){if("EEXIST"!==e.code)throw e;y=null,f=await findBitbucketPipelines(t),i.push(`${IM} appeared while init was running; it was left untouched and audited instead.`)}}const b=f?analyzeExistingBitbucketPipelines(f.content,{defaultBranch:r.defaultBranch}):[],v=f&&b.length>0?{snippet:renderBitbucketPipelinesStepSnippet(m),instructions:bitbucketMergeInstructions(r.defaultBranch)}:null;let w=null;s.withAgentRules&&(u?w=await appendAgentRules(t,u,pU):i.push("with_agent_rules: neither CLAUDE.md nor AGENTS.md exists at the repo root, so no agent rules were written. Ask the user which file their agents read, create it, and re-run with with_agent_rules."));const x=await ensureBitbucketGrant(e,r),S=[f?0===b.length?`${IM} already speaks the contract; nothing to write.`:`${IM} already exists and was NOT modified. Propose merging merge_proposal.snippet into it per merge_proposal.instructions (and each drift item's fix) as exact edits; never replace the file wholesale.`:`Review initial_workflow (${IM}) against the repo per review_notes.`,"Track a small first set of component storyboards with canvas_set_vrt and verify each with canvas_verify_vrt until vrt_stable; drop unstable boards and say why.","authorized"===x.status?`Tempo is authorized to post the \`${GM}\` build status on ${o}${x.username?` (as ${x.username})`:""}; visual_review_doctor's bitbucket_grant row confirms it.`:`The repository grant is NOT in place (${x.reason}): ${x.fix}`,`Ask a repo admin to enable Pipelines for the repository (Repository settings → Pipelines → Settings) and, for the sticky report comment, to create a repository access token with pull-request write access and store it as the SECURED repository variable ${DM} (Repository settings → Pipelines → Repository variables). Without the token the comment is skipped; the build status still posts.`,"Commit on a branch and ask before pushing/opening the PR (a third-party-visible action). The PR proves the setup: the build status goes in progress within a minute and visual_review_doctor's first_run row shows the claim.",'After the first capture: approve the new storyboards in the portal (approvals are per head commit — a new push needs a new approval). Reporting works on every plan; BLOCKING merges on the verdict needs the Tempo custom merge check (a Bitbucket Forge app) on a plan with custom merge checks (Bitbucket Premium) — never substitute "Minimum successful builds", which counts every build status. Bitbucket has no PR labels, so there is no bypass label; the no-visual-change declaration goes in the PR description.'];return{ci_provider:"bitbucket-pipelines",workflow_file:IM,written:g,skipped:null!==f,drift:b,initial_workflow:y,merge_proposal:v,package_manager:l.packageManager,install:l.kind,install_command:l.customInstall??n.install??null,default_branch:r.defaultBranch,default_branch_source:r.defaultBranchSource,agent_rules:w,pr_template:null,repository_grant:x,review_notes:gU,warnings:i,next_steps:S}}async function applyStoryboardVrt(e){let t;try{t=await resolveCanvasFile({workspaceRoot:e.workspaceRoot,canvasesDir:e.canvasesDir,canvasSlug:e.canvasSlug})}catch(e){const t=e;throw new YM("ambiguous_canvas_slug"===t.code?"ambiguous_canvas_slug":"canvas_not_found",t.message??String(e))}const n=toPosix6(vM.relative(e.workspaceRoot,t)),r=await eD.withFileLock(t,async()=>{const r=await gM(t,"utf8"),s=parseCanvasFile(t,r),i=s.errors.filter(e=>"structural"===e.kind);if(i.length>0)throw new YM("storyboard_invalid",`${n} cannot be parsed: ${i.map(e=>e.message).join("; ")}`);const o=s.storyboards.find(t=>t.storyboardKey===e.storyboard);if(!o){const t=s.storyboards.map(e=>e.storyboardKey).join(", ");throw new YM("storyboard_not_found",`Storyboard "${e.storyboard}" was not found in ${n}.${t?` Available storyboards: ${t}.`:""}`)}if("route"===o.kind)throw new YM("storyboard_unsupported",`Storyboard "${e.storyboard}" is a route storyboard; visual review tracks component and local HTML storyboards.`);if("html"===o.kind&&!o.filepath)throw new YM("storyboard_invalid",`HTML storyboard "${e.storyboard}" requires a literal local filepath for VRT.`);let a;try{a=updateStoryboardVrt({filePath:t,source:r,storyboardId:e.storyboard,tracked:e.tracked})}catch(e){throw new YM("invalid_vrt_config",errorMessage2(e))}const c=a.edits.length>0;c&&await atomicWriteFile(t,a.source);const l=parseCanvasFile(t,a.source).storyboards.find(t=>t.storyboardKey===e.storyboard);return{changed:c,vrt:l?.vrt??null}}),s=null!==r.vrt,i=Boolean(r.vrt?.skip),o=vM.isAbsolute(e.canvasesDir)?vM.resolve(e.canvasesDir):vM.resolve(e.workspaceRoot,e.canvasesDir);return{canvas_slug:toPosix6(vM.relative(o,vM.dirname(t))),canvas_file:n,storyboard:e.storyboard,tracked:s,paused:i,vrt:r.vrt,changed:r.changed,next_step:s?i?"Paused (skip: true): the storyboard rides the manifest but is neither captured nor gated. Remove skip to resume.":`Run canvas_verify_vrt({ canvas_slug: "${e.canvasSlug}", storyboard: "${e.storyboard}" }) and fix nondeterminism until it reports vrt_stable before pushing.`:"Untracked. The storyboard leaves the manifest on the next capture and reports as removed once, which a reviewer approves in the portal."}}function textResult2(e){return{content:[{type:"text",text:e}]}}function errorResult9(e){return{content:[{type:"text",text:e}],isError:!0}}async function missingNuxtAppLayer(e){if("vue"!==e.apps[0]?.uiFramework)return null;const t=e.apps[0]?.start??"";if(nuxtAppStartExtendsAppLayer(t))return null;try{if("nuxt"!==await detectProjectFramework(e))return null;const t=await resolveNuxtAppRun(e);return{extendsPath:t.appLayerPath,tempoStart:t.start}}catch{return null}}async function appDevServerStatusResult(e,t,n){if(!t)return textResult2(JSON.stringify(e,null,2));const r=await resolveTempoConfig(n).catch(()=>null),s=await verifyAppInstrumentation(e,{uiFramework:r?.apps[0]?.uiFramework,nuxtAppLayer:r?await missingNuxtAppLayer(r):null}),i=JSON.stringify({...e,instrumentation:s},null,2);return s.verified?textResult2(i):errorResult9(i)}async function normalizeCanvasSlug(e,t){const n=e.trim().replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/[^/]*\.canvas\.tsx$/i,"");if(!n.includes("/"))return n;const r=resolveCanvasesDirSync(t),s=KI.isAbsolute(r)?r:KI.join(t,r),i=KI.isAbsolute(n)?[n]:[KI.join(t,n),KI.join(s,n)];for(const e of i){const t=await resolveCanvasDirPath(e);if(!t)continue;const r=KI.relative(s,t).replace(/\\/g,"/");return r&&!r.startsWith("..")?r:n}return n}async function canvasWorkIdentity(e,t){return(await resolveCanvasWork(e,t)).identity}async function resolveCanvasWork(e,t){const n=KI.resolve(e.workspaceRoot,e.canvasesDir);let r=t.trim().replace(/\\/g,"/").replace(/\/index\.canvas\.tsx$/,"").replace(/\/$/,"");const s=KI.resolve(e.workspaceRoot,r);if((KI.isAbsolute(r)||s.startsWith(n+KI.sep))&&(r=KI.relative(n,KI.isAbsolute(r)?r:s).replace(/\\/g,"/")),!r||"."===r||r.split("/").includes("..")||KI.isAbsolute(r))throw new Error("Canvas must be a folder inside the configured canvases root.");let i,o=null;try{o=await resolveCanvasFile({workspaceRoot:e.workspaceRoot,canvasesDir:n,canvasSlug:r}),i=KI.dirname(o)}catch(e){if(!(e instanceof iM&&"canvas_not_found"===e.code)&&"ENOENT"!==e.code)throw e;i=KI.join(n,r.includes("/")?r:`canvases/${r}`)}return{identity:{canvas_slug:KI.relative(n,i).replace(/\\/g,"/"),canvas_dir:i},canvasFile:o}}async function openCanvasInSplitView(e,t){if(!e.canvasSplitView)return!1;try{return await e.canvasSplitView.open({canvasFile:t})}catch{return!1}}async function persistStoryboardSizeHints(e,t){if(!e.canvasStoryboardSizeHints||0===t.sizes.length)return{};try{return await e.canvasStoryboardSizeHints.record(t),{}}catch(e){return{size_hint_warning:`Could not save storyboard size hints: ${String(e)}`}}}var bU=6e4;async function capturePreviewSnapshot(e,t){if(!e.canvasPreviewCapture)return{};try{const n=await withPreviewCaptureTimeout(e.canvasPreviewCapture.capture({canvasSlug:t}),e.canvasPreviewCapture.timeoutMs??bU);return"ok"===n.kind?{preview_captured:!0}:{preview_captured:!1,preview_error:n.message}}catch(e){return{preview_captured:!1,preview_error:e instanceof Error?e.message:String(e)}}}function withPreviewCaptureTimeout(e,t){let n;const r=new Promise((e,r)=>{n=setTimeout(()=>{r(new Error(`Capturing the canvas preview took longer than ${Math.round(t/1e3)}s and was abandoned. The canvas edits are saved, but its preview may still be missing on linked issues — tell the user rather than assuming the canvas is reviewable.`))},t),n.unref?.()});return Promise.race([e,r]).finally(()=>{n&&clearTimeout(n)})}var vU=CN.object({export_name:CN.string(),name:CN.string().optional(),import_path:CN.string().optional(),import_name:CN.string().optional(),route:CN.string().optional(),preview:CN.string().optional().describe('Flutter apps only: `"<path from this canvas to the Dart file>#<function>"`, beginning with ./ or ../, for a top-level @Preview function. The package is the nearest pubspec.yaml. Writes a <FlutterStoryboard> instead of a component or route storyboard; pass its logical width and height.'),width:CN.number().optional().describe("Width of the box to reserve on the canvas; a component storyboard's real size is its root element's. Route layouts use viewport dimensions."),height:CN.number().optional().describe("Height of the box to reserve on the canvas; a component storyboard's real size is its root element's. Route layouts use viewport dimensions.")}),wU={repo_root:CN.string().optional().describe("Forward-compat (multi-repo workspaces): absolute path to the repo root the app lives in. Omit — today only the session's project root is supported."),app_dir:CN.string().optional().describe("Forward-compat (multi-app repos): the app's directory relative to the project root (a tempo.config.json `apps[].appDir`). Omit — today only the project's single configured app is supported.")},_U={...wU,require_instrumentation:CN.boolean().optional().describe("Require the running app's SDK identity endpoint to report an active Tempo plugin. Required for generated Vite prototypes before canvas handoff. Returns a tool error with instrumentation.code and fix if verification fails; does not stop the app. Omit for ordinary previews or frameworks without the SDK identity endpoint.")};function toAppDevServerTarget(e){if(e.repo_root||e.app_dir)return{...e.repo_root?{repoRoot:e.repo_root}:{},...e.app_dir?{appDir:e.app_dir}:{}}}function withDefaults(e,t){const n={...e};return n.repo_root||(n.repo_root=t.workspaceRoot),n.workspace_root||(n.workspace_root=t.workspaceRoot),n}function withCreateCanvasDefaults(e,t){const n=withDefaults(e,t),r=t.newCanvasBackgroundColor,s="function"==typeof r?r():r;return!n.background_color&&s&&(n.background_color=s),n}function registerTools(e,t){e.tool("canvas_create","Create a new canvas under the project's canvases root (`paths.canvases` in tempo.config.json — canonically `tempo/designs`). A plain `canvas_name` creates a FREEFORM canvas at `<root>/canvases/<slug>`; a `/`-separated name is an explicit path under the root and is how you create INTO a zone — e.g. `\"design-system/Badges\"` → `<root>/design-system/badges`, `\"libraries/ios/Buttons\"` → `<root>/libraries/ios/buttons`. Zone canvases (design-system/**, libraries/**) must declare their showcased components via defineAsset or `canvas_validate` fails with `missing_asset_declaration`. **MUTATING.** **Call `start_working_on_canvas({ canvas_slug })` FIRST** to announce canvas activity. Opens the new canvas in this chat's split view; `opened: true` means no `open_in_split_view` call is needed. Use `start_working_on_storyboard` / `finish_working_on_storyboard` around each frame; normal live updates remain visible. Reuse pre-created onboarding canvases instead of recreating them. Do NOT mkdir the canvas directory or Write any files into it beforehand — this tool creates the directory itself; put canvas-local helper files inside the returned `canvas_dir` AFTER it succeeds. The scaffolded `<Canvas backgroundColor>` is the user's theme backdrop: keep it as-is when you edit the canvas — never change or remove it unless the user explicitly asks. Returns `{ canvas_dir, canvas_file, storyboards: [{export_name, x, y, width, height, stub?}], opened }`. Dimensions are cached as fallback hints below start-working hints and real measured sizes. Width/height describe the box to reserve on the canvas; a component storyboard's real size is its root element's. A canvas-local `import_path` with no file yet is scaffolded as an empty stub (`stub: true`): its frame shows as work in progress at that width/height until you finish it with `finish_working_on_storyboard` or finish the canvas, so write the component, then finish the frame. Use a local StoryboardN.tsx default export with one root carrying size through className/style, wrapping the app component in a div if needed. Component layout uses only x/y and optional zIndex; route and HTML layouts require width/height. Run `canvas_validate` afterward to surface unresolved-import / missing-package / type errors.",{canvas_name:CN.string().describe('Friendly canvas name (e.g. `"Auth Components"`). The folder slug is derived from this.'),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session."),storyboards:CN.array(vU).optional().describe("Storyboards to scaffold. Each one: `export_name` plus EITHER `import_path` (+ optional `import_name`) for a component storyboard OR `route` for a route storyboard OR `preview` for a Flutter storyboard. `import_path` is canvas-relative (`./Local`, a stub is scaffolded when missing), an alias or package import written as the app writes it (`@/components/Card`), or a project file given relative to the project root (`apps/web/src/views/Home.vue`) or absolute, which is rewritten to a canvas-relative import. A bare path naming both a project file and an installed package is refused."),home:CN.boolean().optional().describe('Mark this NEW canvas as the project\'s home canvas (give it a single `route: "/"` storyboard). The Run button opens it next to the app dev-server output. One home per project. If a `route: "/"` canvas already exists, use `canvas_set_home` instead of creating a duplicate. Pair with `set_app_dev_command` so the app actually runs.')},async e=>{try{const n=await runCanvasToolCommand("create-canvas",withCreateCanvasDefaults(e,t));t.captureEvent?.("STORYBOARD_CREATED",{actor_type:"ai",source:"mcp",storyboard_type:"create-canvas"});const r=await openCanvasInSplitView(t,n.canvas_file),s=n,i=await persistStoryboardSizeHints(t,{canvasDir:s.canvas_dir,source:"canvas_create",sizes:s.storyboards.map(({export_name:e,width:t,height:n})=>({id:e,width:t,height:n}))}),o=!0===e.home,a={...n,...i,...o?{home_canvas:{marked:!0}}:{},opened:r},c=e,l=(c.storyboards??[]).some(e=>"string"==typeof e.route&&e.route.trim().length>0);if(l&&t.appDevServer)try{const e=await t.appDevServer.getCommand();if(!e)return textResult2(JSON.stringify({...a,warnings:[...a.warnings??[],"This canvas contains a route storyboard (`<RouteStoryboard>`) but no app dev command (`apps[0].start`) is configured in tempo.config.json. Route iframes will fail to load until you configure the user's real app dev server. Read the project root's package.json `scripts.dev`, then call `set_app_dev_command` with that foreground command and, when known, its HTTP(S) readiness URL. `${APP_PORT}` is an optional allocated-port helper; legacy `${PORT}` remains supported."],app_dev_server:{configured:!1,next_step:"Call set_app_dev_command with start and, when needed, url."}},null,2))}catch{}return textResult2(JSON.stringify(a,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_delete","Delete a canvas — removes the entire canvas folder and every file in it. **MUTATING and IRREVERSIBLE on disk.** Verifies the directory contains an `index.canvas.tsx` before deleting (safety check). Returns `{ deleted, deleted_files: [...] }`. Ask the user before calling.",{canvas_dir:CN.string().describe("Absolute or repo-relative path to the canvas folder (e.g. `tempo/designs/canvases/auth-components`).")},async e=>{try{const n=await runCanvasToolCommand("delete-canvas",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_set_home",'Mark an EXISTING canvas as the project\'s home canvas (the one the Run button opens next to the app dev-server output). Use this when a `route: "/"` canvas already exists (e.g. the one the user is viewing) instead of duplicating it with `canvas_create({ home: true })`. Stamps a marker comment and clears it from any other canvas (one home per project). **MUTATING.** Returns `{ canvas_dir, canvas_file, newly_marked, unmarked_previous }`.',{canvas_dir:CN.string().describe("Absolute or repo-relative path to the canvas folder (or its `index.canvas.tsx`) to mark as home, e.g. `tempo/designs/canvases/untitled`."),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async e=>{try{const n=await runCanvasToolCommand("set-home-canvas",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_migrate_to_latest","Migrate a canvas from the legacy object-export format (`export const X: TempoStoryboard = { render: () => …, layout: {…} }`) to the current React format (default-exported component returning `<Canvas>` with `<Storyboard>`/`<RouteStoryboard>` children) — the same conversion Tempo applies automatically when a legacy canvas is opened in the Design tab. **MUTATING** (rewrites `index.canvas.tsx` in place; safe no-op when the canvas is already React format). Call this BEFORE hand-editing any canvas that still has legacy `export const …: TempoStoryboard` declarations — never edit the legacy shape directly and never mix the two formats in one file. Returns `{ canvas_file, migrated, already_latest }`. Errors when the legacy source uses constructs the migration doesn't support (those need a manual rewrite via canvas_create).",{canvas_file:CN.string().describe("Absolute or repo-relative path to the canvas's `index.canvas.tsx` (or its folder)."),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async e=>{try{const n=await runCanvasToolCommand("migrate-canvas",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_validate",'Check whether a canvas will compile, load and render, and type-check every local file it reaches. **Read-only — does NOT modify the canvas, the tempo config, the package.json, or any other file. Cheap to run; safe to spam.** `valid: true` means nothing detectable statically stops the canvas from loading (`issues` is empty): host setup, syntax errors, missing files/exports/packages, server-only imports, canvas shape. **Type errors never make `valid` false**; they are returned in `type_errors`, each tagged `provenance: "canvas"` (files under the canvases root) or `"app"`, with a `canvas_type_errors` count. Fix type errors in canvas files you wrote; mention app-code type errors without chasing them unless asked. When generating new canvases or UI, you are done only when `valid` is true, `checks.type_check.status` is `"passed"` (not `incomplete`/`not_run`), and `canvas_type_errors` is 0. `warnings` never fail. If `issues` contain a `host_setup_issue`, call `canvas_project_init` separately to fix it (validate diagnoses; init scaffolds). Asset declarations are checked workspace-wide and FAIL validation (kind `asset_declaration_error`): a `duplicate_asset_declaration` or `component_declaration_outside_canvas` involving this canvas or any file in its folder, a `redundant_canvas_declaration` (a canvas that declares components must not also self-register — self-registration is strictly for component-less foundations pages), and a `missing_asset_declaration` (a canvas in a STRICT zone of the canvases root — `design-system/**` or `libraries/**` — must declare the top-level component(s) it showcases, or self-register with usageInstructions if it is a componentless foundations page; freeform canvases have no such requirement). Always run after `canvas_create` and after meaningful edits.',{canvas_file:CN.string().describe("Absolute or repo-relative path to the canvas's `index.canvas.tsx`."),repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async e=>{try{const n={...withDefaults(e,t),workspace_root:t.workspaceRoot,canvases_dir:t.canvasesDir,assets_enabled:!1!==t.assetsEnabled},r=t.runCanvasValidate?await t.runCanvasValidate(n):await runCanvasValidation(n,{runValidatePageCommand:e=>runCanvasToolCommand("validate-canvas",e)});return textResult2(JSON.stringify(r,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_list","List every canvas in the workspace by scanning for `index.canvas.tsx` files under the configured canvases root (`paths.canvases` in tempo.config.json). **Read-only.** Returns `{ pages: [{ file_path, canvas_dir, repo_name, canvas_name, storyboard_names }] }`. Optionally restrict to specific repos via `repo_names`.",{workspace_root:CN.string().optional().describe("Workspace root. Defaults to the workspace bound to this MCP session."),repo_names:CN.array(CN.string()).optional().describe("Restrict the scan to these repo names.")},async e=>{try{const n=await runCanvasToolCommand("list-canvases",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_compute_layout","Compute non-overlapping `{x, y, width, height}` positions for new storyboards on an existing canvas. **Read-only pure computation, does NOT modify any file.** Places left-to-right in rows (max row width 3000px, 50px spacing); wraps to a new row when full. Call this BEFORE editing the canvas file to add new storyboards, so the new storyboards get sensible positions. For components, copy only x/y into layout and size the root in its storyboard file; width/height only reserve space.",{canvas_file:CN.string().nullish().describe("Path to the existing `index.canvas.tsx`. When provided, existing storyboard positions are honored so new ones don't overlap."),new_storyboards:CN.array(CN.object({name:CN.string(),width:CN.number().optional().describe("Width of the box to reserve on the canvas; a component storyboard's real size is its root element's."),height:CN.number().optional().describe("Height of the box to reserve on the canvas; a component storyboard's real size is its root element's.")})).describe("Storyboards to place. Defaults to 600×400 if w/h omitted.")},async e=>{try{const n=await runCanvasToolCommand("compute-layout",withDefaults(e,t));return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_project_init",'Initialize the PROJECT for canvas support (NOT an individual canvas — use canvas_create for that). Tempo installs dependencies in the background. Do not run package-manager installs for the canvas host or project root. Edit tempo/package.json or tempo/tempo.config.json, then call start_canvas_devserver to install and (re)start. Scaffolds `tempo/tempo.config.json`, the host entry, `vite.config.ts`, and `.tempo/` runtime files, plus the project\'s **home canvas** (a `route: "/"` storyboard backing the Run button). framework=vite scaffolds a Vite host; framework=nextjs scaffolds a Next.js sidecar host; framework=nuxt scaffolds a Nuxt sidecar host for a Nuxt 3/4 app (a Tempo-owned `nuxt dev` in `tempo/` that extends the app as a Nuxt layer, with `apps[0].uiFramework: "vue"`; detected from a `nuxt` dependency or `nuxt.config.*`, or passed explicitly); framework=expo scaffolds an Expo web sidecar host. UI source framework is not auto-detected: omission means React. For a Svelte 5 app, set `apps[0].uiFramework` to `"svelte"` in the generated config and rerun this tool before `canvas_create`; that rerun fills missing sidecar Svelte compiler and official Vite-plugin dependencies without overwriting existing specs. Svelte route storyboards also require the APP package to depend on `tempo-sdk` and, for standalone Svelte/Vite, directly dev-depend on `@sveltejs/vite-plugin-svelte`; add missing packages at versions compatible with the app\'s existing toolchain and preserve configured versions. The APP\'S OWN Vite/Svelte config (outside `tempo/`) must use `tempoVitePlugin()` and prepend `tempoSveltePreprocess(...)`; the generated sidecar cannot annotate the separately running app. Preserve existing preprocessors after Tempo\'s. For a Vue 3 or Nuxt 3/4 app, follow the `set-up-vue-or-nuxt-canvas` skill before and after this call (when it is available; otherwise the canvas guide): plain Vue on Vite sets `"vue"` and reruns like Svelte, and its route storyboards need the app\'s own vite.config to use `tempoVitePlugin()` and `...tempoVuePlugin()` from `tempo-sdk/vue`. Init finds a Nuxt app in a workspace folder (`apps/web`) itself; when several packages could be the app, its `warnings` (or, with `framework: "nuxt"`, its error) say to set `apps[0].appDir`. For an Astro 7 app, set `apps[0].uiFramework` to `"astro"` and rerun this tool; it initializes the app-side SDK integration while preserving Tailwind and other Astro integrations. Use AstroStoryboard descriptors and static JSON props as described in the canvas guide. For a Flutter app (a `pubspec.yaml` depending on `flutter: sdk: flutter`), follow the `set-up-flutter-canvas` skill before and after this call (when it is available; otherwise the canvas guide): init discovers preview packages (including pub workspace or Melos members) without adding Flutter configuration, and in a project without a web app seeds the home canvas with `<FlutterStoryboard>` boards of its previews; never pass `framework` for Flutter. Idempotent — safe to re-run; only creates files that don\'t already exist. Run this once per project before `canvas_create`, or in response to a `canvas_validate` result that contains a `host_setup_issue`. The result includes `initial_tempo_config` (the scaffolded install/start scripts), `review_notes`, and `warnings`: problems this init could not fix itself, each of which you must act on. On a FIRST-time init, review the scripts against the repo per `review_notes` (monorepos, postinstall codegen, and private registries need a custom `scripts.install`); getting this right up front is the difference between the canvas rendering on first open and a broken-install debugging session.',{repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session."),framework:CN.enum(["vite","nextjs","nuxt","expo"]).optional().describe("Framework to scaffold for. Required if not auto-detectable.")},async e=>{try{const n=withDefaults(e,t),r=await resolveTempoConfig(n.repo_root).then(()=>!0,()=>!1),s=await runInitCommand(n);r||t.canvasDevserver?.prepare?.().catch(e=>{console.error("Canvas dependency preparation failed:",e)});const i=await resolveTempoConfig(n.repo_root).catch(()=>null),o=i?{scripts:{install:i.scripts.install,start:i.scripts.start}}:void 0,a=(await findFlutterPackages(n.repo_root)).length>0?'This project has Flutter preview packages. Follow the set-up-flutter-canvas skill now. Act on every entry in warnings: SDK or dependency conflicts, @Preview functions it cannot render, a preview import that fails the web build, a missing or outdated Flutter SDK. Flutter boards are <FlutterStoryboard preview="<canvas-relative path>.dart#<function>" layout={{ x, y, width, height }} /> from tempo-sdk/canvas; check_canvas_devserver reports flutter.state until Flutter is ready.':null,c="Act on every entry in warnings: each is something this init could not fix itself (an app folder it could not pick, a Nuxt start command without Tempo's app layer, an install layout the sidecar cannot reach). UI source framework is explicit: omission means React. If this is a Svelte 5 app, set apps[0].uiFramework to \"svelte\" in tempo.config.json and rerun canvas_project_init before creating storyboards. That rerun fills the generated sidecar's missing svelte and @sveltejs/vite-plugin-svelte dependencies using starter defaults; it preserves existing sidecar package specs. For a Svelte route storyboard, setup is NOT complete until apps[0].start is configured, the app's own package depends on tempo-sdk, and a standalone Svelte/Vite app directly dev-depends on @sveltejs/vite-plugin-svelte. Use set_app_dev_command for start and its HTTP(S) readiness URL when known; `${APP_PORT}` is an optional allocated-port helper and legacy `${PORT}` remains supported. Add only missing app packages, choose versions compatible with its existing Svelte/Vite toolchain, and never replace configured versions with Tempo's starter defaults. The app's own Vite/Svelte config must use tempoVitePlugin() plus tempoSveltePreprocess(...) as the first Svelte preprocessor; the generated tempo/ sidecar config does not affect the separately running app. Preserve any existing Svelte preprocessors after Tempo's. For a Vue 3 or Nuxt 3/4 app, follow the set-up-vue-or-nuxt-canvas skill now: it has the steps, config examples, checks and error fixes. In short, plain Vue on Vite sets apps[0].uiFramework to \"vue\" and reruns canvas_project_init (the rerun fills the sidecar's vue and @vitejs/plugin-vue), and its route storyboards need the app's own vite.config to use tempoVitePlugin() and ...tempoVuePlugin() from tempo-sdk/vue. A Nuxt app gets \"vue\" from init (framework nuxt; when the warnings say init found several app directories, set apps[0].appDir and rerun), keeps its own nuxt.config untouched, and keeps the `--extends` path to tempo/nuxt-app-layer (relative to appDir) in apps[0].start. For Astro 7, set apps[0].uiFramework to \"astro\" and rerun canvas_project_init to initialize the native app integration. Double-check initial_tempo_config's scripts.install against this repo before moving on. A plain package-manager install (bare `npm install`/`pnpm install`/… or Tempo's chained `cd .. && … && cd tempo && …` form) means Tempo's DEFAULT behavior: it installs the project root and tempo/ itself with the detected package manager — correct for most single-package repos. Write a CUSTOM command instead when the default won't produce importable app code: the app lives in a workspace/monorepo subdirectory (install must run at the workspace root or with the right filter), the app needs postinstall codegen (e.g. `prisma generate`), a private registry needs .npmrc/env, or the repo has a non-standard install. A custom value runs verbatim from tempo/ (cmd.exe-compatible syntax only, cover BOTH roots' dependencies) and Tempo NEVER rewrites it; under pnpm, when tempo/ is not a package of an ancestor pnpm-workspace.yaml, its tempo/ half needs `--ignore-workspace`, which Tempo adds only to the default form. Do not run package-manager installs for the canvas host or project root. Edit tempo/package.json or tempo/tempo.config.json, then call start_canvas_devserver; Tempo installs and (re)starts.";return textResult2(JSON.stringify({...s,initial_tempo_config:o,review_notes:a?`${a} ${c}`:c,canvas_devserver_status:{running:!1,deferred:!0,message:"Tempo prepares dependencies in the background. The canvas host starts on first render or start_canvas_devserver. Do not run installs yourself."}},null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_debug","Collect detailed diagnostics for a rendered canvas. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (optional export name). Returns filtered runtime state, pipeline/error information, main-process devserver status, and screenshot images using the same static capture path as canvas_screenshot. Use when canvas_screenshot fails, a storyboard looks stale/blank, or the canvas runtime appears unhealthy.",{canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root (`design-system/web-design-system/actions`). Pass the PATH whenever the folder name may not be unique; a bare name that matches several canvases is rejected with ambiguous_canvas_slug rather than resolved by guess"),storyboard:CN.string().optional().describe("Optional storyboard export name. Omit to inspect the whole canvas.")},async({canvas_slug:e,storyboard:n})=>{if(!t.canvasDebug)return unsupportedEnvironmentResult("canvasDebug");try{const r=await normalizeCanvasSlug(e,t.workspaceRoot),s=await t.canvasDebug.capture({canvasSlug:r,storyboard:n});return canvasDebugResultToMcpContent(s)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("canvas_snapshot_route",'Snapshot a route storyboard\'s live page: create a static HTML storyboard beside it, return the HTML, or save the HTML to a file — the same "Snapshot to HTML" the route header offers, with stylesheets, images, fonts and inline-style assets kept resolvable. Use it whenever the user asks to snapshot, capture, clip or copy a website or app page onto a canvas as HTML; never write your own DOM/CSS serializer or CDP capture script. Steps: add a `<RouteStoryboard route="https://site.example/">` (an absolute URL works for external sites) whose layout width × height is the viewport to capture (for a whole page, set the height to the page height, max 12000), open the canvas with open_in_split_view({ type: "canvas" }), let the route render, then call this once per board. Args: canvas_slug, storyboard (the route storyboard\'s id), output ("storyboard" by default, or "html"). With output="html", returns HTML without creating a storyboard; set output_path to save it to a new .html file instead of returning the HTML payload. output_path is workspace-relative, its parent directory must exist, and existing files are never overwritten. With output="storyboard", the HTML file and `<HtmlStoryboard>` are written into the canvas folder. All modes return title and size.',{canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root. Pass the PATH whenever the folder name may not be unique."),storyboard:CN.string().describe("The route storyboard's `id` (its `name` also matches)."),output:CN.enum(["storyboard","html"]).optional().describe('Default: "storyboard" creates an HtmlStoryboard. "html" exports without creating a storyboard.'),output_path:CN.string().min(1).optional().describe('Only with output="html": save to a new workspace-relative .html file instead of returning HTML. Parent directory must exist; refuses overwrite.')},async({canvas_slug:e,storyboard:n,output:r,output_path:s})=>{if(!t.canvasRouteSnapshot)return unsupportedEnvironmentResult("canvasRouteSnapshot");try{let i;if(void 0!==s){if("html"!==r)return errorResult9('output_path requires output="html".');const e=await GI(t.workspaceRoot);if(KI.isAbsolute(s)||".html"!==KI.extname(s).toLowerCase())return errorResult9("output_path must be a workspace-relative .html file.");const n=KI.resolve(e,s),o=await GI(KI.dirname(n)),a=KI.relative(e,o);if(".."===a||a.startsWith(`..${KI.sep}`)||KI.isAbsolute(a))return errorResult9("output_path must stay inside the workspace (including symlinks).");i=KI.join(o,KI.basename(n))}const o=await normalizeCanvasSlug(e,t.workspaceRoot),a=await t.canvasRouteSnapshot.snapshot({canvasSlug:o,storyboard:n,...r?{output:r}:{}});return"ok"===a.kind?"html"===r&&"string"!=typeof a.html?errorResult9("snapshot_failed: The app did not return HTML. Update the app and retry."):(i&&await VI(i,a.html,{encoding:"utf8",flag:"wx"}),textResult2(JSON.stringify({created:"html"!==r,..."html"===r?i?{outputPath:s,saved:!0}:{html:a.html}:{},canvasPath:a.canvasPath,fromStoryboard:a.storyboard,snapshotName:a.snapshotName,width:a.width,height:a.height},null,2))):errorResult9(routeSnapshotErrorText(a))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("check_canvas_devserver","Check whether the canvas devserver is currently running. Returns running state, port, and url if up; `starting: true` while a start is still in progress (not a failure; `message` says what it is doing). For a project with a Flutter app a `flutter` field: `state` is starting (with a progress `message`), ready, reloading or failed (with `error.code` and `error.message`). Flutter boards paint only once it is ready. While Flutter's own output explains a problem (a failure, a start quiet for a minute, an error printed since ready such as a flutter_boot_timeout's cause), `flutter.recentOutput` carries its newest lines (`reason`, `lines`, `omitted`). Call before canvas operations if you suspect the server is down.",{},async()=>{if(!t.canvasDevserver)return unsupportedEnvironmentResult("canvas devserver");try{const e=await t.canvasDevserver.status();return textResult2(JSON.stringify(e,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("start_canvas_devserver","Start the canvas devserver if it isn't already running. Runs the command in tempo.config.json's scripts.start and waits until the /tempo-host route is reachable. A first build can take minutes: once a start runs past its notice time this returns `starting: true` while the start continues in the background; then follow it with check_canvas_devserver, never another start or stop. Every start keeps tempo-sdk on latest, moving a project off the legacy sdk-v2-latest. Pass update_sdk: true only when the user asks to update tempo-sdk: it restarts an already running host so it loads a newer SDK. No-op if already running, unless force_install: true — in that case the install step always runs first. Pass force_install: true after editing tempo.config.json's scripts.install (e.g. when fixing a `root_deps_missing` error by chaining a project-root install in front of the Tempo install) so the new install command actually executes.",{update_sdk:CN.boolean().optional().describe("Only when the user asks to update tempo-sdk. Restarts the canvas host even if it is running; the restart updates tempo-sdk to latest (through scripts.updateSdk when configured), as every start does. Never pass it routinely."),force_install:CN.boolean().optional().describe("When true, re-runs scripts.install before starting even if the supervisor thinks dependencies are already installed. Use this after editing tempo.config.json's scripts.install — without it, the start would skip install and your config change would have no effect.")},async({force_install:e,update_sdk:n})=>{if(!t.canvasDevserver)return unsupportedEnvironmentResult("canvas devserver");try{const r=await t.canvasDevserver.start({forceInstall:e,updateSdk:n,returnWhileStarting:!0}),s=JSON.stringify(r,null,2);return r.starting?textResult2("The canvas devserver is still starting and has NOT failed; it keeps starting in the background. Call check_canvas_devserver to see the outcome; do not call start_canvas_devserver or stop_canvas_devserver again. timeouts.startStallSeconds in tempo/tempo.config.json (default 300) sets how long Tempo waits on a start that prints nothing.\n\n"+s):textResult2(s)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("stop_canvas_devserver","Stop the running canvas devserver process. Use to free the port or before restarting cleanly. Canvas iframes will go blank until the canvas devserver is restarted.",{},async()=>{if(!t.canvasDevserver)return unsupportedEnvironmentResult("canvas devserver");try{const e=await t.canvasDevserver.stop();return textResult2(JSON.stringify(e,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("set_app_dev_command","Configure the user's REAL app dev server in tempo.config.json as `apps[0].start` plus optional `stop` and `url`. `url` is either an HTTP(S) string or `{ command }`; a URL command runs only during launch and must exit 0 with exactly one HTTP(S) URL on stdout. A clean early `start` exit is accepted only with `stop`, after which URL probes own liveness and `stop` owns teardown. Tempo exposes `${APP_PORT}` (legacy `${PORT}` also works) to every command. Legacy appStart spellings still read and migrate. At least one field must be provided; null clears it. Idempotent.",{command:CN.string().nullish().describe("The canonical apps[0].start foreground command. It may be arbitrary; use `${APP_PORT}` when the command should consume Tempo's allocated helper port. Legacy `${PORT}` remains supported. Omit to leave unchanged; pass null/empty to clear the app server configuration."),url:CN.union([CN.string(),CN.object({command:CN.string().min(1)}).strict()]).nullish().describe('Optional canonical apps[0].url: either a reachable HTTP(S) URL string or `{ command: "..." }`. The command runs once per launch from appDir (after start exits in the stop-backed handoff shape), receives APP_PORT/PORT/TEMPO_APP_PORT, and must print exactly one HTTP(S) URL. Omit to leave unchanged; pass null/empty to clear.'),stop:CN.string().nullish().describe("Optional canonical apps[0].stop teardown command. Required when start exits successfully while the app remains reachable externally. Runs on normal stop and stale-runtime reconciliation. Omit to leave unchanged; pass null/empty to clear."),...wU},async({command:e,stop:n,url:r,repo_root:s,app_dir:i})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");if(void 0===e&&void 0===n&&void 0===r)return errorResult9("Provide command, stop, and/or url to update.");const o=void 0===e?void 0:"string"==typeof e&&e.trim().length>0?e.trim():null,a=void 0===r?void 0:"string"==typeof r?r.trim().length>0?r.trim():null:null===r?null:{command:r.command.trim()},c=void 0===n?void 0:"string"==typeof n&&n.trim().length>0?n.trim():null;try{return await t.appDevServer.setConfig({...void 0!==o?{start:o}:{},...void 0!==c?{stop:c}:{},...void 0!==a?{url:a}:{}},toAppDevServerTarget({repo_root:s,app_dir:i})),textResult2(JSON.stringify({...void 0!==o?{app_dev_command:o}:{},...void 0!==a?{app_dev_url:a}:{},...void 0!==c?{app_dev_stop:c}:{},app_dev_config_update:{...void 0!==o?{start:o}:{},...void 0!==c?{stop:c}:{},...void 0!==a?{url:a}:{}},note:null===o?"Cleared.":"Saved. The supervisor allocates `${APP_PORT}` independently; static or command-resolved URLs are the readiness target and route base. If start hands off to an external server, stop is required and URL probes become liveness authority. Before declaring setup complete, verify the app depends on tempo-sdk and its own bundler config carries Tempo instrumentation. For standalone Svelte/Vite, add @sveltejs/vite-plugin-svelte only if missing, preserve compatible configured versions, and use tempoVitePlugin() plus tempoSveltePreprocess(...) first in the app's preprocess chain. For Vue/Vite, add tempoVitePlugin() and ...tempoVuePlugin() from tempo-sdk/vue to the app's own vite.config plugins; for Nuxt, keep `--extends` with the path to tempo/nuxt-app-layer (relative to appDir) in the command. The set-up-vue-or-nuxt-canvas skill has both. tempo/ only configures the sidecar."},null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("check_app_dev_server","Check the per-workspace app dev server configured by canonical `apps[0].start`/`stop`/`url` (legacy appStart spellings also read). Returns `{configured, running, phase, port, url, livenessSource, error}`; liveness is `child` for foreground servers and `probe` after external handoff. Use this when a route storyboard isn't rendering. `configured: false` means start is unset; `phase: 'error'` carries the supervisor failure. Pass `require_instrumentation: true` for generated Vite prototypes or to verify a route app's Tempo plugin: probes the app's /__tempo/identity within a 5s bound (polling while the server answers 503, as Nuxt does while it warms up) and adds `instrumentation.verified`; when `apps[0].uiFramework` is `\"vue\"` on Vite it also requires the identity to report tempoVuePlugin() active (`app_vue_annotation_missing` otherwise). Missing/inactive/unverifiable instrumentation is a tool error with a typed code and repair, even if running is true. This checks plugin activation, not every element's editability. Omission preserves the ordinary status-only check.",_U,async({repo_root:e,app_dir:n,require_instrumentation:r})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");try{const s=await t.appDevServer.getStatus(toAppDevServerTarget({repo_root:e,app_dir:n}));return await appDevServerStatusResult(s,r,e??t.workspaceRoot)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("start_app_dev_server","Start the per-workspace app dev server if it isn't already running. Spawns canonical `apps[0].start`, substitutes `${APP_PORT}` (or legacy `${PORT}`) in start/stop/url commands, persists the independently selected local helper port under `<workspaceRoot>/.tempo/app-devserver.json`, resolves `url.command` once when configured, and HTTP-gates readiness against the resolved/static URL or detected local URL. A clean early start exit requires `apps[0].stop`; then URL probes own liveness and stop owns teardown. A literal URL is probed as written and does not affect local allocation. No-op if already running. When start is unset, returns `{configured: false}`; call `set_app_dev_command` first. For generated Vite prototypes, pass `require_instrumentation: true`: after startup (also when already running), verify the app's active Tempo plugin via /__tempo/identity within a 5s bound (polling while the server answers 503, as Nuxt does while it warms up), and for a Vue app on Vite that tempoVuePlugin() is active. Returns `instrumentation.verified`; failure is a tool error with a typed code and repair, preserving the running app. Fix it before handing over the canvas. This checks plugin activation, not every element's editability. Omission preserves ordinary preview startup.",_U,async({repo_root:e,app_dir:n,require_instrumentation:r})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");try{const s=await t.appDevServer.start(toAppDevServerTarget({repo_root:e,app_dir:n}));return await appDevServerStatusResult(s,r,e??t.workspaceRoot)}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),e.tool("stop_app_dev_server","Stop the per-workspace app dev server. Use to free the allocated port, before restarting cleanly, or after editing the app dev command so the next `start_app_dev_server` picks up the new command. Route storyboard iframes will go blank until restarted. Does NOT clear the persisted port — the next start reuses it. Analogous to `stop_canvas_devserver` but for the user's app server.",{...wU},async({repo_root:e,app_dir:n})=>{if(!t.appDevServer)return unsupportedEnvironmentResult("appDevServer");try{const r=await t.appDevServer.stop(toAppDevServerTarget({repo_root:e,app_dir:n}));return textResult2(JSON.stringify(r,null,2))}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}});const n={canvas_slug:CN.string().min(1).describe("Canvas folder path relative to the canvases root. Use the full path when names are ambiguous.")},r={...n,storyboard:CN.string().min(1).describe("Exact Storyboard id. Starting before it exists shows a temporary frame; the real storyboard replaces it when the same id renders.")};e.tool("start_working_on_canvas","Begin a canvas editing session. Call it FIRST, the moment you decide to create or edit a canvas, before reading files or planning, and before canvas_create. Turns on this canvas's activity indicator in tabs/sidebar; does not shimmer storyboards or freeze live rendering. If the canvas exists, opens it in this chat's split view (`opened: true`; no `open_in_split_view` call needed); canvas_create opens a new one. Reuse an existing onboarding canvas. Use start_working_on_storyboard for each frame you work on. Pair with finish_working_on_canvas once the full task is verified. Takes only a canvas, never a storyboard.",n,async({canvas_slug:e})=>{try{const{identity:n,canvasFile:r}=await resolveCanvasWork(t,e);await(t.canvasEditingState?.start({canvasSlug:n.canvas_slug}));const s=!!r&&await openCanvasInSplitView(t,r);return textResult2(JSON.stringify({...n,editing:!0,opened:s}))}catch(e){return errorResult9(String(e))}}),e.tool("finish_working_on_canvas","End the canvas editing session and its tabs/sidebar activity indicator. Call once after verifying the full task, including canvas_screenshot on an edited storyboard. Also clears any outstanding storyboard shimmer owned by this run. Live rendering continues throughout. Persists the final canvas preview best-effort. Takes only a canvas; use finish_working_on_storyboard for individual frames.",n,async({canvas_slug:e})=>{try{const n=await canvasWorkIdentity(t,e);await(t.canvasEditingState?.finish({canvasSlug:n.canvas_slug})),t.canvasDevserver?.applySetup?.().catch(e=>{console.error("Canvas setup failed:",e)});const r=await capturePreviewSnapshot(t,n.canvas_slug);return textResult2(JSON.stringify({...n,editing:!1,...r}))}catch(e){return errorResult9(String(e))}}),e.tool("start_working_on_storyboard","Show work on one storyboard inside an active canvas session. Layout dimensions are saved as a fallback size hint; real measured sizes always win, and this hint outranks canvas_create. For a NEW frame, pass layout {x,y,width,height}: Tempo immediately shows a temporary shimmer rectangle at those canvas coordinates, even before the frame exists. Use the same id and layout when adding the real Storyboard; it replaces the placeholder. For an EXISTING frame, omit layout to shimmer its live content. Older calls without layout still get a default placeholder for missing frames. Does not write files, freeze previews, select a frame or move the camera. Keep publishing small useful versions; pair with finish_working_on_storyboard when this pass is ready.",{...r,layout:CN.object({x:CN.number().finite(),y:CN.number().finite(),width:CN.number().finite().positive(),height:CN.number().finite().positive()}).optional().describe("Planned canvas-world bounds for a new storyboard. Pass before writing its component so the user sees its placeholder immediately; reuse these bounds in the real Storyboard layout.")},async({canvas_slug:e,storyboard:n,layout:r})=>{try{const{identity:s,canvasFile:i}=await resolveCanvasWork(t,e),o=!r&&i?parsePageSource(i,await zI(i,"utf8")).storyboards:[],a=!r&&!o.some(e=>e.storyboardKey===n||e.exportName===n),c=r?await persistStoryboardSizeHints(t,{canvasDir:s.canvas_dir,source:"start_working_on_storyboard",sizes:[{id:n,width:r.width,height:r.height}]}):{};return textResult2(JSON.stringify({...s,storyboard:n,editing:!0,...r?{layout:r}:{},...c,...a?{warning:`Storyboard "${n}" is not in the canvas yet. Call again with layout: { x, y, width, height } so its placeholder has the frame's planned size.`}:{}}))}catch(e){return errorResult9(String(e))}}),e.tool("finish_working_on_storyboard","Turn off this run's shimmer on exactly one storyboard after a useful, valid pass. Leaves the canvas activity indicator and other storyboards alone. Fast status signal only: no capture, upload, iframe refresh or final-task completion. Continue with the next frame, or start this same storyboard again to refine it. Finish the whole canvas separately after final verification.",r,async({canvas_slug:e,storyboard:n})=>{try{return textResult2(JSON.stringify({...await canvasWorkIdentity(t,e),storyboard:n,editing:!1}))}catch(e){return errorResult9(String(e))}});const s={canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root (`design-system/web-design-system/actions`). Pass the PATH whenever the folder name may not be unique; a bare name that matches several canvases is rejected with ambiguous_canvas_slug rather than resolved by guess"),storyboard:CN.string().optional().describe("Optional storyboard export name. Recommended — without it the whole canvas is captured as a composite image.")},captureScreenshot=async(e,n,r)=>{if(!t.canvasScreenshot)return unsupportedEnvironmentResult("canvasScreenshot");if(t.canvasDevserver&&!t.canvasScreenshot.managesDevserver)try{await t.canvasDevserver.start()}catch(e){return errorResult9(`canvas_screenshot could not start the canvas devserver: ${e instanceof Error?e.message:String(e)}`)}try{const s=await normalizeCanvasSlug(e,t.workspaceRoot),i=await t.canvasScreenshot.capture({canvasSlug:s,storyboard:n},r);return"error"===i.kind?errorResult9(`canvas_screenshot failed [${i.code}]: ${i.message}${i.availableStoryboards&&i.availableStoryboards.length>0?` Available storyboards in the current canvas: ${i.availableStoryboards.join(", ")}.`:""}`):{content:[{type:"image",data:i.pngBase64,mimeType:"image/png"},{type:"text",text:JSON.stringify({canvas_slug:s,storyboard:n??null,width:i.width,height:i.height,...screenshotProvenanceSummary(i)},null,2)}]}}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}};e.tool("canvas_screenshot","Capture a PNG of rendered canvas content so you can verify your edits visually. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export name; recommended). With storyboard, returns that storyboard's rendered pixels; without storyboard, returns a composite image of the whole canvas. This call fails fast with capacity_exceeded when all five devserver slots are pinned; continue without the image, or call canvas_screenshot_queued if waiting is important. Images larger than 1990px per side are downscaled to fit. Errors are typed; do not retry on error. For a ROUTE storyboard, ensure the app dev server is running first (check_app_dev_server → start_app_dev_server). The deliverable is the canvas, not the screenshot.",s,async({canvas_slug:e,storyboard:t},n)=>captureScreenshot(e,t,{capacityMode:"fail",signal:n.signal})),e.tool("canvas_screenshot_queued","Capture the same PNG as canvas_screenshot, but wait for a managed devserver slot when all five are pinned. Use this only when the image is important enough to block the turn; otherwise prefer canvas_screenshot and continue on capacity_exceeded. queue_timeout_ms bounds only the capacity wait (default 30000, max 120000), and MCP cancellation aborts the wait immediately.",{...s,queue_timeout_ms:CN.number().int().min(1).max(12e4).default(3e4).describe("Maximum milliseconds to wait for a devserver slot.")},async({canvas_slug:e,storyboard:t,queue_timeout_ms:n},r)=>captureScreenshot(e,t,{capacityMode:"wait",timeoutMs:n,signal:r.signal})),e.tool("storyboard_responsiveness_check",xU,{canvas_slug:s.canvas_slug,storyboard:CN.string().describe("Storyboard export name.")},async({canvas_slug:e,storyboard:n},r)=>{const s=t.canvasResponsivenessCheck;if(!s)return unsupportedEnvironmentResult("canvasResponsivenessCheck");try{const i=await normalizeCanvasSlug(e,t.workspaceRoot);return await runResponsivenessCheck(s,t,{canvasSlug:i,storyboard:n},r.signal)}catch(e){const t=e instanceof iM?e.code:"capture_threw";return failure2(t,e instanceof Error?e.message:String(e))}});const stabilityErrorResult=(e,t)=>errorResult9(`canvas_verify_vrt failed [${e}]: ${t}`);e.tool("canvas_verify_vrt","Check that a VRT-tracked storyboard renders identically across fresh mounts so its baseline won't flake in CI. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export name carrying a literal `vrt` prop; `skip: true` is rejected), runs (2–10, default 3; keep at least 3). Compares each run to run 1 under the visual-review matcher, threshold, and ignore masks. The headless lane loads each run differently: run 1 cold, run 2 with every request slowed, run 3 as a second render in a warm document, then repeating; `unstable_conditions` says which load changed the pixels and what that means. Returns `vrt_stable`; when false, also changed-pixel bounds and a diff-mask image. Call after adding or changing `vrt`; fix the nondeterministic input and rerun. Read-only. Fails fast with capacity_exceeded; typed errors are not retryable.",{canvas_slug:s.canvas_slug,storyboard:CN.string().describe("Storyboard export name carrying the literal `vrt` prop."),runs:CN.number().int().min(2).max(10).default(3).describe("Number of captures to compare. Defaults to 3.")},async({canvas_slug:e,storyboard:n,runs:r},s)=>{if(!t.canvasStoryboardStability)return unsupportedEnvironmentResult("canvasStoryboardStability");try{const i=await normalizeCanvasSlug(e,t.workspaceRoot),o=await resolveTestedStoryboard({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir,canvasSlug:i,storyboard:n});if(t.canvasDevserver&&!t.canvasStoryboardStability.managesDevserver)try{await t.canvasDevserver.start()}catch(e){return errorResult9(`canvas_verify_vrt could not start the canvas devserver: ${e instanceof Error?e.message:String(e)}`)}const a=createVrtStabilityAccumulator({threshold:o.vrt.threshold,ignore:o.vrt.ignore,layout:o.layout});let c;const l=await t.canvasStoryboardStability.captureRuns({canvasSlug:o.canvasSlug,canvasFile:o.canvasFile,storyboard:o.storyboardId,runs:r},{timeoutMs:12e4,signal:s.signal,onCapture:e=>{if(!c)try{a.addCapture(e)}catch(e){c=e}}});if(c)return stabilityErrorResult("compare_failed",c instanceof Error?c.message:String(c));if("error"===l.kind)return stabilityErrorResult(l.code,`${l.message}${l.availableStoryboards&&l.availableStoryboards.length>0?` Available storyboards in the current canvas: ${l.availableStoryboards.join(", ")}.`:""}`);if(l.runs!==r||a.captureCount!==r)return stabilityErrorResult("capture_incomplete",`requested ${r} fresh captures but received ${a.captureCount}.`);let d;try{d=a.summarize()}catch(e){return stabilityErrorResult("compare_failed",e instanceof Error?e.message:String(e))}const u=d.conditions?` (${[...new Set(d.conditions)].join(", ")} loads)`:"",p=d.unstableConditions.map(({condition:e,dependsOn:t})=>` The ${e} load differs from the cold one: the storyboard depends on ${t}.`).join(""),m="stable"===d.status?`All ${r} isolated renders${u} are equivalent under the storyboard's VRT threshold and ignore masks.`:`${d.changedRuns} of ${r-1} comparisons changed under the storyboard's VRT policy; the largest changed ${d.maxDiffPixels} pixels (${(100*d.maxDiffRatio).toFixed(4)}%).${p}`,f=[];return d.cumulativeDiff&&f.push({type:"image",data:d.cumulativeDiff.pngBase64,mimeType:"image/png"}),f.push({type:"text",text:JSON.stringify({canvas_slug:o.canvasSlug,canvas_file:o.canvasFile,storyboard:o.storyboardId,vrt:o.vrt,status:d.status,vrt_stable:d.vrtStable,runs:d.runs,retried_captures:d.retriedCaptures,threshold_used:d.threshold,ignore_regions:d.ignoreRegions,changed_runs:d.changedRuns,...d.conditions?{conditions:d.conditions,unstable_conditions:d.unstableConditions.map(({condition:e,dependsOn:t})=>({condition:e,depends_on:t}))}:{},max_diff_pixels:d.maxDiffPixels,max_diff_ratio:d.maxDiffRatio,diff_bounds_device_px:d.diffBounds,cumulative_diff_image:d.cumulativeDiff?{width:d.cumulativeDiff.width,height:d.cumulativeDiff.height,source_width:d.cumulativeDiff.sourceWidth,source_height:d.cumulativeDiff.sourceHeight,meaning:"Transparent pixels were stable; fuchsia pixels changed in at least one comparison to run 1. Large masks are area-resampled to fit within 1990px without dropping thin differences."}:null,comparisons:d.comparisons.map(e=>({run:e.run,baseline_run:e.baselineRun,...e.condition?{condition:e.condition}:{},diff_pixels:e.diffPixels,diff_ratio:e.diffRatio,diff_bounds_device_px:e.diffBounds,dimensions:e.dimensions,...e.dimensionChange?{dimension_change:e.dimensionChange}:{}})),diagnosis:m,next_action:"unstable"===d.status?"Inspect the changed region and the storyboard's component dependency graph for nondeterministic render inputs. Replace them with fixed props, fixtures, or seeded inputs, and make the component suspend until what it renders from is ready, with no Suspense boundary between it and the storyboard, rather than showing a fallback it never revisits, then rerun.":"No deterministic-source change is needed for this storyboard under its current VRT policy."},null,2)}),{content:f}}catch(e){return e instanceof iM?stabilityErrorResult(e.code,e.message):errorResult9(`canvas_verify_vrt failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("canvas_set_vrt","Track, configure, pause, or untrack a component or local HTML storyboard for visual review (VRT) by writing its literal `vrt` prop through Tempo's source editor — never hand-edit `vrt` JSX. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export id), tracked: `true` (bare `vrt`; an existing object form is kept), `false` (removes the attribute, config included), or `{ threshold?, ignore?, skip? }` (writes exactly that config: threshold 0–0.5, ignore regions `{x,y,w,h}` in storyboard-local CSS px, skip pauses without losing config). Component and local HTML storyboards are supported — route storyboards are refused with `storyboard_unsupported`. **MUTATING** (rewrites the canvas file in place); bookend with start_working_on_canvas / finish_working_on_canvas like any canvas edit. Returns `{ canvas_file, storyboard, tracked, paused, vrt, changed, next_step }`. After tracking, ALWAYS run canvas_verify_vrt on the storyboard until it reports `vrt_stable`. Typed errors are not retryable.",{canvas_slug:s.canvas_slug,storyboard:CN.string().describe("Storyboard export id (the `id` prop)."),tracked:CN.union([CN.boolean(),CN.object({threshold:CN.number().min(0).max(.5).optional(),skip:CN.boolean().optional(),ignore:CN.array(CN.object({x:CN.number().min(0),y:CN.number().min(0),w:CN.number().min(0),h:CN.number().min(0)}).strict()).optional()}).strict()]).describe("true = track with defaults; false = untrack; an object = write exactly this literal config.")},async({canvas_slug:e,storyboard:n,tracked:r})=>{try{const s=await normalizeCanvasSlug(e,t.workspaceRoot),i=await applyStoryboardVrt({workspaceRoot:t.workspaceRoot,canvasesDir:t.canvasesDir,canvasSlug:s,storyboard:n,tracked:r});return textResult2(JSON.stringify(i,null,2))}catch(e){return errorResult9(e instanceof YM?`canvas_set_vrt failed [${e.code}]: ${e.message}`:`canvas_set_vrt failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("visual_review_doctor",'Diagnose whether this repo can run Tempo visual review (VRT) and what is missing, one typed row per layer: canvas_host, tracked_storyboards, ci_provider, workflow, repo_registered, github_app + required_check (GitHub Actions) or bitbucket_grant + merge_enforcement (Bitbucket Pipelines; merge_enforcement is advisory), first_run. **Read-only — no side effects; safe to re-run and to poll.** Each row is `{ id, ok: true | false | null, fix? }` — `false` carries the exact recovery in `fix`, `null` means it could not be determined in this environment (see `reason`; never inferred). Also returns `repo_key`, `default_branch`, `org`, `ready`, and `next_step` — the first failing row\'s fix in DEPENDENCY order (registration before local setup, a first capture before the required check), so follow `next_step` rather than the rows top to bottom. `first_run` reports aggregate facts only (reached, when, state, gate); the portal link lives on the PR (comments_get_pr_visual_review). Run it BEFORE proposing any visual-review setup, and again after the user completes a manual step (GitHub App install, Bitbucket repository grant, branch protection) or after a push (poll `first_run` for a few minutes to prove the first capture reached Tempo). Read get_guide({ topic: "tempo-visual-review-setup" }) first to interpret the rows. Never hand-write the workflow — `visual_review_init` writes it.',{repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session.")},async({repo_root:e})=>{try{const n=await runVisualReviewDoctor(t,{repoRoot:e});return textResult2(JSON.stringify(n,null,2))}catch(e){return errorResult9(`visual_review_doctor failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("visual_review_init","Scaffold the repo-owned half of Tempo visual review: writes `.github/workflows/visual-review.yml` (GitHub Actions) or `bitbucket-pipelines.yml` (Bitbucket Pipelines) from the template the published `@tempo-ai/visual-review` CLI ships, filled with the repo's package-manager setup, the install command from tempo.config.json, the default branch, and the canvas-host directory. **MUTATING but idempotent and safe to re-run: it only creates what is absent and NEVER overwrites an existing workflow or pipelines file** — if one exists it returns `skipped: true` plus `drift[]` (missing `id-token: write`, no default-branch push trigger, not using the published CLI, …; on Bitbucket also `merge_proposal` to merge into the existing file) for you to propose exact edits. On Bitbucket it also authorizes Tempo's repository grant (`repository_grant`: build statuses + PR-head checks) with the user's connected Bitbucket account, only after verifying that account can write to the repo; a `not_authorized` result carries the fix. Optional `with_agent_rules` appends the tested-storyboard rules to the repo's CLAUDE.md / AGENTS.md (whichever exists) and `with_pr_template` adds a Visual review section to the PR template (GitHub only); both are opt-in because they edit team-owned files. Returns `{ workflow_file, written, skipped, drift, initial_workflow, package_manager, install, review_notes, warnings, next_steps }` — review `initial_workflow` against the repo per `review_notes` while you still have context (monorepo root vs app dir, postinstall codegen, private registries), exactly like canvas_project_init. Requires the canvas host (`no_tempo_host` → run canvas_project_init first), an `origin` remote (`no_git_remote`), and a github.com or bitbucket.org repo (`unsupported_ci`). Run visual_review_doctor first and get the user's yes before calling; it does not track storyboards (canvas_set_vrt) or push anything.",{repo_root:CN.string().optional().describe("Project root. Defaults to the workspace bound to this MCP session."),with_agent_rules:CN.boolean().optional().describe("Append the tested-storyboard rules to CLAUDE.md or AGENTS.md at the repo root (whichever exists; warns and skips if neither does). Opt-in — it edits a team-owned file."),with_pr_template:CN.boolean().optional().describe("Add a 'Visual review' section to .github/PULL_REQUEST_TEMPLATE.md (created if absent, appended if present without one). The section describes the no-visual-change marker without spelling it — a PR body containing the literal marker skips capture. Opt-in. GitHub only (Bitbucket has no PR template file; warns and skips).")},async({repo_root:e,with_agent_rules:n,with_pr_template:r})=>{try{const s=await runVisualReviewInit(t,{repoRoot:e,withAgentRules:n,withPrTemplate:r});return textResult2(JSON.stringify(s,null,2))}catch(e){return errorResult9(e instanceof YM?`visual_review_init failed [${e.code}]: ${e.message}`:`visual_review_init failed: ${e instanceof Error?e.message:String(e)}`)}}),e.tool("canvas_share","Create a shareable link to a canvas and get back a screenshot of the whole canvas. **The canvas MUST be fully committed and pushed to a remote (clean git state) before sharing** — exactly like link_items — otherwise this returns a 'branch_not_pushed' error and you must commit + push the canvas's branch first so the recipient can access the code. Cache-first: when a published preview already exists for the branch's exact pushed commit, the link returns immediately with no re-capture; otherwise it captures a composite screenshot of every storyboard, publishes it as the branch's preview, then mints the link. Share links are BRANCH-LIVE: an existing link (and its public token) keeps its URL and automatically shows the newest published preview each time the branch's pushed canvas is re-captured — no need to re-share after pushing new commits. Returns the URL plus the whole-canvas screenshot (auto-displayed inline). By default the link is member-only (the recipient opens it as an org member); pass public: true to mint an anyone-with-the-link token instead. Args: canvas_slug (folder name, or root-relative path when the name isn't unique), public (optional, default false).",{canvas_slug:CN.string().describe("Slug of the canvas — its folder name, or its path under the canvases root (`design-system/web-design-system/actions`). Pass the PATH whenever the folder name may not be unique; a bare name that matches several canvases is rejected with ambiguous_canvas_slug rather than resolved by guess"),public:CN.boolean().optional().describe("When true, mint an anyone-with-the-link public token so the recipient doesn't need to sign in. Default false ⇒ member-only link.")},async({canvas_slug:e,public:n})=>{if(!t.canvasShare)return unsupportedEnvironmentResult("canvasShare");if(t.canvasDevserver)try{await t.canvasDevserver.start()}catch(e){return errorResult9(`canvas_share could not start the canvas devserver: ${e instanceof Error?e.message:String(e)}`)}try{const r=await normalizeCanvasSlug(e,t.workspaceRoot),s=await t.canvasShare.create({canvasSlug:r,makePublic:n??!1});return"error"===s.kind?errorResult9(`canvas_share failed [${s.code}]: ${s.message}`):{content:[{type:"image",data:s.pngBase64,mimeType:"image/png"},{type:"text",text:JSON.stringify({canvas_slug:r,share_url:s.shareUrl,visibility:s.isPublic?"public":"member",canvas_path:s.canvasPath,branch:s.branch,storyboard_count:s.storyboardCount,...s.skippedStoryboardIds?.length?{skipped_broken_storyboards:s.skippedStoryboardIds}:{},width:s.width,height:s.height},null,2)}]}}catch(e){return errorResult9(e instanceof Error?e.message:String(e))}}),!1!==t.assetsEnabled&&registerAssetTools(e,t)}var xU=["Check whether a component storyboard renders differently in a window of its own size. It captures the storyboard in the canvas's shared 1920x1080 window, then in a window resized to its box, and compares them, ignoring what changes by itself.","Call it when the storyboard's code reads the viewport in JavaScript (`window.innerWidth` / `innerHeight`, `matchMedia`, or a hook such as `useMediaQuery`, `useBreakpoint`, `useIsMobile`); measures its own elements in JavaScript and uses the size (`ResizeObserver`, `getBoundingClientRect`, `offsetWidth`); shows an overlay that places itself against the viewport, most often an open menu, popover or tooltip near a frame edge; shows a whole page or app shell at a phone or tablet size; or sizes a chart, a virtual list or a canvas in JavaScript.","Do not call it for CSS-only responsiveness that no JavaScript measures (media queries, Tailwind breakpoints, viewport units); for a storyboard about as wide as a desktop window; or for content missing from a screenshot, which this does not fix.","What earlier checks found in this project is at the end of the canvas guide, and recorded in `tempo/AGENTS.md` under `## Responsive storyboards`.","Args: canvas_slug (folder name, or root-relative path when the name isn't unique), storyboard (export name). Returns a verdict in a JSON sidecar: `differs` with two images, the canvas's view, then the storyboard at its own size; `same`; `already_responsive`; or `unavailable` with a reason. Each says what to do next. Fails fast with capacity_exceeded; typed errors are not retryable."].join(" ");function unsupportedEnvironmentResult(e){return errorResult9(`${e} hook not configured in this environment — the canvas MCP server was constructed without it. This usually means the tool was invoked outside the Electron main process (e.g. from a CLI wrapper or test).`)}var TU={canvas_not_open:'Open the canvas with open_in_split_view({ type: "canvas", path }) so a canvas tab shows it, then retry once.',ambiguous_canvas_slug:"Retry with the root-relative path of the canvas you mean.",storyboard_not_found:"Retry with one of the canvas's storyboard ids, or add the RouteStoryboard first.",not_route_storyboard:"Only a <RouteStoryboard> has a live page to snapshot. Add one for the URL and snapshot that.",route_not_rendered:"The route has not rendered on the canvas yet. Wait for it to load, then retry once.",snapshot_failed:"Tell the user the snapshot failed and why. Do not hand-roll a serializer as a workaround."};function routeSnapshotErrorText(e){const t=e.availableStoryboards?.length?` Storyboards on this canvas: ${e.availableStoryboards.join(", ")}.`:"";return`${e.code}: ${e.message}${t} ${TU[e.code]}`}function canvasDebugResultToMcpContent(e){const t=e.screenshots??[],n=stripCanvasDebugImages(e),r=[{type:"text",text:JSON.stringify(n,null,2)}];for(const e of t)e.pngBase64&&(r.push({type:"text",text:JSON.stringify({screenshot:{label:e.label,canvas_slug:e.canvasSlug,storyboard:e.storyboard??null,width:e.width??null,height:e.height??null,...screenshotProvenanceSummary(e)}},null,2)}),r.push({type:"image",data:e.pngBase64,mimeType:"image/png"}));return{content:r,..."error"===e.kind?{isError:!0}:{}}}function stripCanvasDebugImages(e){return"error"===e.kind?{kind:e.kind,code:e.code,message:e.message,diagnostics:e.diagnostics??null}:{kind:e.kind,diagnostics:e.diagnostics}}function screenshotProvenanceSummary(e){return{retried:e.retried??!1,...e.fromCache?{fromCache:!0}:{},...e.highFidelity?{high_fidelity:!0}:{}}}function createCanvasMcpServer(e){const t=!1!==e.assetsEnabled,n=new Pm({name:"tempo-design-canvas-tools",version:"1.0.0"},{capabilities:{tools:{},resources:{}},instructions:buildCanvasInstructions(e.canvasesDir,{assetsEnabled:t})});return registerTools(n,e),registerDocs(n,e),n}function buildBackends(e,t,n){const r=buildDbBackends({...e,renderPdfPage:e.renderPdfPage??renderDocumentPage},t);if(t.includes("canvas")&&n){const t=createCanvasMcpServer({workspaceRoot:n.workspaceRoot,canvasesDir:n.canvasesDir,...e.canvasHooks});r.push({toolset:"canvas",server:t})}return r}var kU="0.0.151";import{stat as SU}from"fs/promises";import EU from"path";import{gzipSync as AU}from"zlib";import{dirname as CU,resolve as IU}from"path";import{fileURLToPath as PU}from"url";async function provisionSdkRuntime(){const e=PU(import.meta.url),t=e.endsWith(".ts")?IU(CU(e),"../../tempo-sdk-runtime/dist"):IU(CU(e),"sdk-runtime");try{await provisionCaptureRuntime(t)}catch(e){throw new Error(`Tempo MCP SDK runtime is unavailable. Reinstall @tempo-ai/mcp or provide a compatible TEMPO_SDK_RUNTIME_PATH. ${e instanceof Error?e.message:String(e)}`)}}async function startDevserverSession2(e){return await provisionSdkRuntime(),startDevserverSession(e)}async function startCaptureSession2(e){return await provisionSdkRuntime(),startCaptureSession(e)}var DU=["git","--no-optional-locks"];function simpleGit2(e){return pI(e?{baseDir:e,binary:DU}:{binary:DU})}var RU=["credential.interactive=false"];function nonInteractiveGitEnv(e=process.env){return{...e,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",SSH_ASKPASS_REQUIRE:"never"}}async function getRemoteUrl2(e,t="origin"){const n=simpleGit2(e),readConfig=async e=>{try{const t=(await n.raw(["config","--get",e])).trim();return t||null}catch{return null}};return await readConfig(`remote.${t}.pushurl`)??await readConfig(`remote.${t}.url`)}async function computeShareStatus(e){const t=simpleGit2(e),n=await t.getRemotes(!0),r=n.length>0,s=n.find(e=>"origin"===e.name)?.refs.push??n[0]?.refs.push??null,i=(await t.raw(["branch","--show-current"])).trim(),o=await t.status(),a=new Map,addFile=(e,t)=>{a.has(e)||a.set(e,{path:e,status:t})};for(const e of o.staged)addFile(e,"staged");for(const e of o.modified)addFile(e,"modified");for(const e of o.deleted)addFile(e,"deleted");for(const e of o.not_added)addFile(e,"added");for(const e of o.created)addFile(e,"added");for(const e of o.renamed)addFile(e.to,"renamed");for(const e of o.conflicted)addFile(e,"conflicted");const c=[...a.values()];try{const e=await t.diff(["--cached","--numstat"]),n=await t.diff(["--numstat"]),r=new Map;for(const t of[e,n])for(const e of t.trim().split("\n").filter(Boolean)){const t=e.split("\t");if(t.length<3)continue;const n=parseInt(t[0],10)||0,s=parseInt(t[1],10)||0,i=t.slice(2).join("\t"),o=r.get(i);o?(o.additions+=n,o.deletions+=s):r.set(i,{additions:n,deletions:s})}for(const e of c){const t=r.get(e.path);t&&(e.additions=t.additions,e.deletions=t.deletions)}}catch{}let l=0;if(r&&i){const e=n.find(e=>"origin"===e.name)?.name??n[0]?.name,r=await t.raw(["log","HEAD","--not",`--remotes=${e}`,"--oneline"]);l=r.trim().split("\n").filter(Boolean).length}return{hasRemote:r,remoteUrl:s,uncommittedFiles:c,unpushedCommits:l,currentBranch:i}}async function checkBranchOnRemote(e,t){const n=pI({baseDir:e,binary:DU,config:[...RU],timeout:{block:15e3}}).env(nonInteractiveGitEnv());try{const e=await n.raw(["ls-remote","--heads","origin",t]);return e.trim().length>0}catch{return null}}var NU=C(ru(),1);import{anyApi as OU}from"convex/server";var FU=1990;function toPosix7(e){return e.split(EU.sep).join("/")}function normalizeSlug(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/[^/]*\.canvas\.tsx$/i,"")}async function isCanvasFolder(e){try{return(await SU(EU.join(e,"index.canvas.tsx"))).isFile()}catch{return!1}}async function resolveCanvas(e,t){const n=e.workspaceRoot,r=e.canvasesDir,s=EU.join(n,"tempo"),i=await enumerateCanvasStoryboards({tempoDir:s,pagesDir:r}),o=new Map;for(const e of i.storyboards){const t=EU.dirname(e.filePath);let r=o.get(t);r||(r={contentPath:toPosix7(EU.relative(n,t)),hostCanvasPath:e.hostCanvasPath,storyboards:[]},o.set(t,r)),r.storyboards.push(e)}const a=normalizeSlug(t);if(!a)return{kind:"not_found"};if(a.includes("/")||EU.isAbsolute(t))for(const[e,i]of o){const o=[toPosix7(EU.relative(r,e)),toPosix7(EU.relative(n,e)),toPosix7(EU.relative(s,e))];if(EU.isAbsolute(t)){if(EU.resolve(t)===e)return{kind:"ok",canvas:i}}else if(o.includes(a))return{kind:"ok",canvas:i}}else{const e=[...o.entries()].filter(([e])=>EU.basename(e)===a);if(e.length>1)return{kind:"ambiguous",candidates:e.map(([e])=>toPosix7(EU.relative(r,e))).sort()};if(1===e.length)return{kind:"ok",canvas:e[0][1]}}const c=EU.isAbsolute(t)?[EU.resolve(t)]:[EU.join(r,a),EU.join(n,a),EU.join(s,a)];for(const e of c)if(await isCanvasFolder(e))return{kind:"ok",canvas:{contentPath:toPosix7(EU.relative(n,e)),hostCanvasPath:toPosix7(EU.relative(n,EU.join(e,"index.canvas.tsx"))),storyboards:[]}};return{kind:"not_found"}}function ambiguousCanvasSlugMessage(e,t){return`"${e}" names ${t.length} different canvases: ${t.join(", ")}. A bare folder name cannot tell them apart — retry with the full root-relative path of the one you mean.`}function isMissingPlaywright(e){const t=e instanceof Error?e.message:String(e);return/Cannot find (module|package) '?playwright'?/.test(t)}var LU="Headless canvas capture needs Playwright's Chromium. Install it next to @tempo-ai/mcp: `npm install playwright && npx playwright install chromium`, then retry.",MU=class extends Error{};function sleep5(e){return new Promise(t=>setTimeout(t,e))}async function withCaptureSession(e,t,n,r){let s=null,i=null;try{return s=await startDevserverSession2({repoRoot:e,hostCanvasPaths:[t]}),i=await startCaptureSession2({hostUrl:s.hostUrl,getAppUrl:s.getAppUrl,settleTimeoutMs:n}),await r(i)}finally{await(i?.dispose().catch(()=>{})),await(s?.dispose().catch(()=>{}))}}function downscalePngToFit(e,t){const n=NU.PNG.sync.read(Buffer.from(e));if(n.width<=t&&n.height<=t)return{pngBase64:Buffer.from(e).toString("base64"),width:n.width,height:n.height};const r=Math.min(t/n.width,t/n.height),s=Math.min(t,Math.max(1,Math.round(n.width*r))),i=Math.min(t,Math.max(1,Math.round(n.height*r))),o=new NU.PNG({width:s,height:i});for(let e=0;e<i;e+=1){const t=Math.floor(e*n.height/i),r=Math.max(t+1,Math.ceil((e+1)*n.height/i));for(let i=0;i<s;i+=1){const a=Math.floor(i*n.width/s),c=Math.max(a+1,Math.ceil((i+1)*n.width/s));let l=0,d=0,u=0,p=0,m=0;for(let e=t;e<r;e+=1)for(let t=a;t<c;t+=1){const r=4*(e*n.width+t),s=n.data[r+3];l+=n.data[r]*s,d+=n.data[r+1]*s,u+=n.data[r+2]*s,p+=s,m+=1}const f=4*(e*s+i),g=p||1;o.data[f]=Math.round(l/g),o.data[f+1]=Math.round(d/g),o.data[f+2]=Math.round(u/g),o.data[f+3]=Math.round(p/m)}}const a=NU.PNG.sync.write(o);return{pngBase64:Buffer.from(a).toString("base64"),width:s,height:i}}function compressShareHtml(e){const t=(new TextEncoder).encode(e),n=AU(t);return n.byteLength>=t.byteLength?{bytes:t,contentType:"text/html"}:{bytes:new Uint8Array(n),contentType:"application/gzip"}}async function uploadShareBlob(e,t,n,r){const s=await e.mutation(OU.projects.generateShareUploadUrl,{orgProjectId:t}),i=await fetch(s,{method:"POST",headers:{"Content-Type":r},body:n});if(!i.ok)throw new Error(`share blob upload failed with HTTP ${i.status}`);const{storageId:o}=await i.json();if("string"!=typeof o||!o)throw new Error("share blob upload returned no storageId");return o}function buildShareUrl(e){const t=new URL(`/${encodeURIComponent(e.orgProjectId)}/canvas/${encodeURIComponent(e.orgProjectId)}`,resolveShareBaseUrl());return t.searchParams.set("branch",e.branch),t.searchParams.set("content",e.contentPath),t.searchParams.set("env","prod"),t.toString()}function appendShareToken(e,t){const n=new URL(e);return n.searchParams.set("token",t),n.toString()}function createHeadlessCanvasHooks(e){const{workspace:n}=e,r=new t({url:e.convexUrl,authProvider:e.authProvider}),verifyProjectMatchesRepo=async t=>{const s=e.getOrgId();if(!s)return{kind:"error",code:"no_active_project",message:"No orgId was provided for this canvas_share call. Pass the orgId from tempo_list_orgs."};const i=await r.query(OU.projects.getOrgProjects,{organizationId:s}),o=(i??[]).find(e=>e?._id===t);if(!o)return{kind:"error",code:"no_active_project",message:`Project "${t}" was not found in organization "${s}" (or you are not a member). Pick the project for THIS repository from tempo_list_projects.`};const a=normalizeRepoUrl(await getRemoteUrl2(n.workspaceRoot));if(!a)return{kind:"error",code:"branch_not_pushed",message:"This repository has no git remote configured — a canvas share must point at a pushed branch of a registered project repo."};const c=(o.repos??[]).map(e=>normalizeRepoUrl(e.sourceUrl)).filter(e=>null!==e);return c.includes(a)?null:{kind:"error",code:"no_active_project",message:`This repository's remote (${a}) is not a registered repo of project "${o.name??t}". Sharing would persist this canvas under an unrelated project — pass the project that owns this repository (see tempo_list_projects).`}},captureScreenshot=async(e,t)=>{const r=await resolveCanvas(n,e.canvasSlug);if("ambiguous"===r.kind)return{kind:"error",code:"ambiguous_canvas_slug",message:ambiguousCanvasSlugMessage(e.canvasSlug,r.candidates)};if("not_found"===r.kind)return{kind:"error",code:"canvas_not_open",message:`No canvas matching "${e.canvasSlug}" exists under ${n.canvasesDir}. Pass the canvas's folder name, or its path under the canvases root.`};const s=r.canvas,i=s.storyboards.map(e=>e.storyboardId);let o;if(e.storyboard){const t=s.storyboards.find(t=>t.storyboardId===e.storyboard);if(!t)return{kind:"error",code:"storyboard_not_found",message:`Storyboard "${e.storyboard}" is not an export of canvas "${s.contentPath}".`,availableStoryboards:i};o=[t]}else o=s.storyboards;if(0===o.length)return{kind:"error",code:"storyboard_empty",message:`Canvas "${s.contentPath}" has no renderable component storyboards (route/html storyboards need the user's app dev server and cannot be captured headlessly).`};try{const r=await withCaptureSession(n.workspaceRoot,s.hostCanvasPath,t?.timeoutMs,async t=>{if(1===o.length&&e.storyboard){const e=o[0],n=await t.captureStoryboard({source:e.source,hostCanvasPath:s.hostCanvasPath,storyboardId:e.storyboardId,width:e.layout.width,height:e.layout.height});return n.pngBytes}const n=[];for(const e of o){const r=await t.captureStoryboard({source:e.source,hostCanvasPath:s.hostCanvasPath,storyboardId:e.storyboardId,width:e.layout.width,height:e.layout.height});n.push({pngBytes:r.pngBytes,x:e.layout.x,y:e.layout.y})}return compositeStoryboardPngs(n,{padding:"5%"}).pngBytes}),i=downscalePngToFit(r,FU);return{kind:"ok",pngBase64:i.pngBase64,width:i.width,height:i.height}}catch(e){return{kind:"error",code:"capture_threw",message:isMissingPlaywright(e)?LU:`Headless canvas capture failed: ${e instanceof Error?e.message:String(e)}`}}},captureStoryboardStability=async(e,t)=>{const r=await resolveCanvas(n,e.canvasSlug);if("ambiguous"===r.kind)return{kind:"error",code:"ambiguous_canvas_slug",message:ambiguousCanvasSlugMessage(e.canvasSlug,r.candidates)};if("not_found"===r.kind)return{kind:"error",code:"canvas_not_open",message:`No canvas matching "${e.canvasSlug}" exists under ${n.canvasesDir}. Pass the canvas's folder name, or its path under the canvases root.`};const s=r.canvas,i=s.storyboards.find(t=>t.storyboardId===e.storyboard);if(!i)return{kind:"error",code:"storyboard_not_found",message:`Storyboard "${e.storyboard}" is not an export of canvas "${s.contentPath}".`,availableStoryboards:s.storyboards.map(e=>e.storyboardId)};try{const r=await withCaptureSession(n.workspaceRoot,s.hostCanvasPath,t?.timeoutMs,async n=>{let r=0;for(let o=0;o<e.runs;o+=1){if(t?.signal?.aborted)throw t.signal.reason??new Error("Capture aborted");const a=determinismProbeForRun(o),c=await n.captureStoryboard({source:i.source,hostCanvasPath:s.hostCanvasPath,storyboardId:i.storyboardId,width:i.layout.width,height:i.layout.height,...a.options});if(looksBlank(c.pngBytes))throw new Error(`Storyboard "${i.storyboardId}" rendered an empty frame on run ${o+1}/${e.runs} (${a.name}).`);await(t?.onCapture?.({pngBase64:Buffer.from(c.pngBytes).toString("base64"),width:c.width,height:c.height,condition:a.name})),r+=1}return r});return{kind:"ok",runs:r}}catch(e){return{kind:"error",code:"capture_threw",message:isMissingPlaywright(e)?LU:`Headless VRT stability capture failed: ${e instanceof Error?e.message:String(e)}`}}},createShareLink=async t=>{const s=e.getOrgProjectId();if(!s)return{kind:"error",code:"no_active_project",message:"No projectId was provided for this canvas_share call. Pass the projectId from tempo_list_projects."};const i=await resolveCanvas(n,t.canvasSlug);if("ambiguous"===i.kind)return{kind:"error",code:"ambiguous_canvas_slug",message:ambiguousCanvasSlugMessage(t.canvasSlug,i.candidates)};if("not_found"===i.kind)return{kind:"error",code:"no_canvas_path",message:`Could not find a local canvas for "${t.canvasSlug}". Pass the canvas's folder name (slug).`};const o=i.canvas,a=o.contentPath,c=await computeShareStatus(n.workspaceRoot),l=c.currentBranch,d=c.uncommittedFiles.length,u=c.unpushedCommits,p=0===d&&0===u&&c.hasRemote;if(!p)return{kind:"error",code:"branch_not_pushed",message:buildBranchNotPushedMessage2(a,{branch:l,uncommittedCount:d,unpushedCount:u,hasRemote:c.hasRemote}),details:{branch:l,uncommittedCount:d,unpushedCount:u,hasRemote:c.hasRemote}};const m=await checkBranchOnRemote(n.workspaceRoot,l);if(!1===m)return{kind:"error",code:"branch_not_pushed",message:`Branch "${l}" is not on the remote, even though local git history says it was pushed (the remote repository may have been recreated). Push the branch again, then share.`,details:{branch:l,uncommittedCount:0,unpushedCount:0,hasRemote:!0}};const f=await verifyProjectMatchesRepo(s);if(f)return f;if(0===o.storyboards.length)return{kind:"error",code:"capture_failed",message:`Canvas "${a}" has no renderable component storyboards to share — add a storyboard, then share again.`};let g,y,b;try{const e=await withCaptureSession(n.workspaceRoot,o.hostCanvasPath,void 0,async e=>{const t=[];for(const n of o.storyboards){const r={source:n.source,hostCanvasPath:o.hostCanvasPath,storyboardId:n.storyboardId,width:n.layout.width,height:n.layout.height,artifacts:["png","html"],portableHtml:!0};let s=await e.captureStoryboardArtifacts(r);if(s.styles&&isStyleStarved(s.styles)&&(await sleep5(5e3),s=await e.captureStoryboardArtifacts(r),s.styles&&isStyleStarved(s.styles)))throw new MU(`storyboard "${n.storyboardId}": `+describeStyleStarvation(s.styles));if(!s.png||!s.html)throw new Error(`storyboard "${n.storyboardId}" produced no capture artifacts`);t.push({storyboard:n,png:s.png,html:s.html})}return t}),t=compositeStoryboardPngs(e.map(e=>({pngBytes:e.png.pngBytes,x:e.storyboard.layout.x,y:e.storyboard.layout.y})),{padding:"5%"});b=downscalePngToFit(t.pngBytes,FU),g=[];for(const t of e){const{bytes:e,contentType:n}=compressShareHtml(t.html.html);g.push({id:t.storyboard.storyboardId,x:t.storyboard.layout.x,y:t.storyboard.layout.y,width:t.storyboard.layout.width,height:t.storyboard.layout.height,htmlStorageId:await uploadShareBlob(r,s,e,n)})}try{y=await uploadShareBlob(r,s,t.pngBytes,"image/png")}catch(e){console.error("[tempo-mcp] canvas_share: composite screenshot upload failed:",e instanceof Error?e.message:String(e))}}catch(e){return e instanceof MU?{kind:"error",code:"unstyled_render",message:`Refusing to share an unstyled render — ${e.message}`}:{kind:"error",code:"capture_failed",message:isMissingPlaywright(e)?LU:`Could not capture the canvas for sharing: ${e instanceof Error?e.message:String(e)}`}}try{await r.mutation(OU.projects.upsertShareSnapshot,{orgProjectId:s,contentPath:a,branch:l,...y?{screenshotStorageId:y}:{},storyboards:g});let e=buildShareUrl({orgProjectId:s,branch:l,contentPath:a}),n=!1;if(t.makePublic){const t=await r.mutation(OU.publicShares.enablePublicShare,{artifactType:"canvas",orgProjectId:s,contentPath:a,branch:l}),i=t?.token;if(!i)return{kind:"error",code:"share_failed",message:"The share snapshot was created, but enabling public (anyone-with-the-link) access failed — you may not be authenticated. Retry, or omit public to share a member-only link."};e=appendShareToken(e,i),n=!0}return{kind:"ok",shareUrl:e,isPublic:n,canvasPath:a,branch:l,storyboardCount:g.length,skippedStoryboardIds:[],pngBase64:b.pngBase64,width:b.width,height:b.height}}catch(e){return{kind:"error",code:"share_failed",message:`Could not create the share link: ${e instanceof Error?e.message:String(e)}`}}};return{canvasScreenshot:{capture:captureScreenshot,managesDevserver:!0},canvasStoryboardStability:{captureRuns:captureStoryboardStability,managesDevserver:!0},canvasShare:{create:createShareLink}}}function buildBranchNotPushedMessage2(e,t){const n=[];t.uncommittedCount>0&&n.push(`${t.uncommittedCount} uncommitted file(s)`),t.unpushedCount>0&&n.push(`${t.unpushedCount} unpushed commit(s)`),t.hasRemote||n.push("no git remote is configured");const r=n.length>0?` Found ${n.join(", ")}.`:"";return`Cannot share canvas "${e}": its branch "${t.branch}" must be committed and pushed to a remote (clean git state) before it can be shared, so the recipient can access the code.`+r+" Commit and push all changes, then retry canvas_share."}var UU='Tempo workspace tools. SCOPING: every issues_*/docs_*/comments_*/agents_*/slack_*/linear_*/script tool requires an explicit orgId — call tempo_list_orgs once to discover it; project-scoped agents/scripts tools (and canvas_share) also require projectId — call tempo_list_projects; if the org has no project for the current repo yet, register it with tempo_register_project. Toolsets: issues, cloud docs, canvas comments, custom agents, run scripts, Slack (acts as the org\'s Tempo bot), Linear. In a Tempo repo, canvas tools (canvas_*, asset_*) design against production components — call get_guide({ topic: "tempo-canvas-instructions" }) before canvas work. For a selection in an open Tempo desktop canvas, call list_design_context_targets then get_design_context with orgId; this works outside a repo over Convex. Cross-link artifacts with link_items.';function toolRequiresAuth(e,t){return"canvas"!==e||"canvas_share"===t}async function createTempoAggregate(e,t={}){const{signInPrompt:n,authWaitMs:r,...l}=t,u=l.convexUrl??y(),p=g(u),m=o({convexSiteUrl:p,attemptReauth:d(p),onReauthRequired:()=>{console.error("[tempo-mcp] Tempo session expired — the next Tempo tool call will prompt for sign-in.")}});m.start();const v=n??a({authUrl:process.env.TEMPO_AUTH_URL}),w=createAuthGate({convexSiteUrl:p,refreshLoop:m,signInPrompt:v,waitMs:r??b()});let x=null,S=null,E=0;const A=new Set,C=e.toolsets.includes("canvas")?c():null,I=l.authProvider??i(m),P={authProvider:I,convexUrl:u,getOrgId:()=>x,getUserId:()=>f()?.userId??null,getCurrentOrgGeneration:()=>E,onActiveOrgChange:e=>(A.add(e),()=>A.delete(e)),getOrgProjectId:()=>S,getWritePermission:()=>!e.readonly,canvasHooks:C?createHeadlessCanvasHooks({workspace:C,convexUrl:u,authProvider:I,getOrgId:()=>x,getOrgProjectId:()=>S}):void 0,...l},R=buildBackends(P,e.toolsets,C);R.push({toolset:"tempo",server:createHostToolsServer({authProvider:P.authProvider,convexUrl:P.convexUrl})});const N=await s({name:"tempo",version:kU,instructions:UU,backends:R,filterTool:(t,n)=>isExternallyExposed(n,{readonly:e.readonly}),injectParams:scopeParamsFor,gateCall:(e,t)=>toolRequiresAuth(e,t)?w.ensure():Promise.resolve(null),onScopedCall:e=>{const t=e.orgId??null;if(t!==x){x=t,E+=1;for(const e of A)e()}S=e.projectId??null}});return{aggregate:N,dispose:async()=>{m.stop(),v.dispose(),await N.dispose()}}}async function runServe(e){p({binaryName:"tempo"});const t=await createTempoAggregate(e),n=new su;return await t.aggregate.connect(n),await new Promise(e=>{n.onclose=()=>e(),process.stdin.on("close",()=>e())}),await t.dispose(),0}export{createTempoAggregate,runServe,scopeParamsFor,toolRequiresAuth};
321
321
  /*! Bundled license information:
322
322
 
323
323
  unpdf/dist/index.mjs: