isotone 1.1.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +84 -6
- package/CHANGELOG.md +46 -0
- package/README.md +64 -14
- package/dist/{IterationPanel-phJRYtUO.d.ts → IterationPanel-Bq77d5NT.d.ts} +3 -1
- package/dist/{chunk-FKEKBZ3E.js → chunk-2FY2JNPG.js} +95 -9
- package/dist/chunk-2FY2JNPG.js.map +1 -0
- package/dist/chunk-BDTB3DFR.js +100 -0
- package/dist/chunk-BDTB3DFR.js.map +1 -0
- package/dist/{chunk-PUXQGUMQ.js → chunk-BTJHQXF7.js} +104 -5
- package/dist/chunk-BTJHQXF7.js.map +1 -0
- package/dist/chunk-JCTWHR7U.js +13 -0
- package/dist/chunk-JCTWHR7U.js.map +1 -0
- package/dist/{chunk-I7CZUPDO.js → chunk-KRS57POF.js} +17 -33
- package/dist/chunk-KRS57POF.js.map +1 -0
- package/dist/chunk-L6O4HYGP.js +1150 -0
- package/dist/chunk-L6O4HYGP.js.map +1 -0
- package/dist/chunk-MX4RQJFV.js +9 -0
- package/dist/chunk-MX4RQJFV.js.map +1 -0
- package/dist/chunk-YPDV3PX4.js +142 -0
- package/dist/chunk-YPDV3PX4.js.map +1 -0
- package/dist/cli.js +1079 -148
- package/dist/cli.js.map +1 -1
- package/dist/core.d.ts +135 -10
- package/dist/core.js +12 -3
- package/dist/index.d.ts +13 -28
- package/dist/index.js +618 -281
- package/dist/index.js.map +1 -1
- package/dist/isotone.global.js +98 -42
- package/dist/serve.d.ts +5 -3
- package/dist/serve.js +60 -23
- package/dist/serve.js.map +1 -1
- package/dist/server.d.ts +7 -0
- package/dist/server.js +24 -11
- package/dist/server.js.map +1 -1
- package/dist/vite-plugin.d.ts +4 -3
- package/dist/vite-plugin.js +48 -128
- package/dist/vite-plugin.js.map +1 -1
- package/docs/blast.md +164 -0
- package/docs/integrations.md +75 -15
- package/docs/migration.md +19 -0
- package/docs/updates.md +110 -4
- package/docs/variants.md +102 -9
- package/package.json +2 -1
- package/dist/chunk-A4DX2V4C.js +0 -7
- package/dist/chunk-A4DX2V4C.js.map +0 -1
- package/dist/chunk-FKEKBZ3E.js.map +0 -1
- package/dist/chunk-I7CZUPDO.js.map +0 -1
- package/dist/chunk-PUXQGUMQ.js.map +0 -1
- package/dist/chunk-RQ2YI5KS.js +0 -24
- package/dist/chunk-RQ2YI5KS.js.map +0 -1
- package/dist/chunk-TGAU3WTF.js +0 -549
- package/dist/chunk-TGAU3WTF.js.map +0 -1
- package/dist/chunk-X6V2AKJL.js +0 -375
- package/dist/chunk-X6V2AKJL.js.map +0 -1
package/dist/vite-plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite/index.ts","../src/vite/exports.ts","../src/vite/live.ts"],"sourcesContent":["/**\n * Development-only notes, source variants and a self-contained panel for Vite.\n * Inject through the HTML response so SSR frameworks work too. The loader lives\n * in <head> and mounts after load, leaving the host's hydration and HMR alone.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\n\n// `normalizePath` is a plain function, so importing it as a value does not\n// pull vite's nominal `Plugin` type into the structural return type below.\nimport {\n type DevEnvironment,\n type EnvironmentModuleNode,\n type HmrContext,\n type HotUpdateOptions,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n} from 'vite';\n\nimport { ensureDirIgnored, ensureFileIgnored, notesResponse, NOTES_ENDPOINT } from '../store';\nimport type { RouteGateOptions } from '../core/index';\nimport type { IterationShortcut } from '../react/IterationPanel';\nimport type { IterationTheme } from '../react/theme';\nimport { readBundle } from '../standalone/bundle';\nimport { startUpdateCheck, UPDATE_ENDPOINT } from '../update';\nimport { checkOrigin, readNodeJson, sendFailure } from '../server/http';\nimport { type OverlayVariant, overlayGroups, VARIANTS_ENDPOINT } from '../core/variants';\nimport {\n ACTIVE_FILE,\n listVariants,\n overrideSourcePath,\n readActive,\n readVariant,\n readVariants,\n resolveOverride,\n variantDir,\n variantsDir,\n variantsResponse,\n type VariantsStoreOptions,\n} from '../variants-store';\nimport { isRouteModule, scanExports } from './exports';\nimport {\n ACTIVE_EVENT,\n BASE_VERSION,\n dispatcherModule,\n LIVE_MODULE,\n type LiveConfig,\n liveRuntimeModule,\n liveStoreScript,\n RESOLVED_LIVE_MODULE,\n VERSION_QUERY,\n} from './live';\n\nexport interface IterationViteOptions {\n /** Inject the bundled panel. false keeps endpoints and variants for a manual mount. */\n panel?: boolean;\n /** Background npm notice, at most once a day. false disables the check. */\n checkForUpdates?: boolean;\n /** Defaults to auto (page background); system follows the OS preference. */\n theme?: IterationTheme;\n /** Defaults to Cmd/Ctrl+Shift+Period; customize or disable with false. */\n shortcut?: IterationShortcut | false;\n /** Where notes persist. Relative paths resolve against Vite's `root` (the\n * directory of the app, whatever the shell's cwd), so a monorepo package\n * started from the workspace root still writes next to its own config.\n * Defaults to `.iteration-feedback.json`; git-ignored automatically via\n * `.git/info/exclude`, with the pattern anchored at the repository root. */\n file?: string;\n /** Route visibility rule (denylist/allowlist) for the injected panel. */\n rule?: RouteGateOptions;\n /** localStorage namespace override. */\n key?: string;\n /**\n * Overlay variants: alternative source files under `.isotone/variants/\n * <id>/<repo-relative path>` that `load` swaps in for the real ones while\n * the variant is active. On by default; `false` turns the whole feature\n * off (no endpoint, no watcher, no tab in the panel).\n */\n variants?:\n | false\n | {\n /** The project the manifests' file paths are relative to. Defaults to\n * Vite's root. A sibling dev server that aliases into another package\n * (a preview app rendering another package's source) points this at that\n * package so the same variants apply to both. Relative to Vite's root\n * or absolute. */\n root?: string;\n /** Where the variants live, relative to `root`. Default\n * `.isotone/variants`. */\n dir?: string;\n /** Keep the variants dir out of git via `.git/info/exclude`. Off by\n * default: the files are the reviewable artefact and commit with\n * the change they propose. */\n ignored?: boolean;\n /**\n * Switch variants in the browser instead of recompiling files. Every\n * version of an overridden script is loaded once, components switch\n * by re-rendering, and the selection is kept in the tab's `?v=`.\n * On by default in a React project on Vite 6 or later; `false` swaps\n * whole files over HMR as before.\n */\n live?: boolean;\n };\n}\n\n/**\n * What `iteration()` hands back.\n *\n * Only `name` is public, and that is deliberate. isotone is consumed as a\n * linked (`file:` / workspace) dependency, so TypeScript resolves the `vite`\n * import from *this* package's `node_modules`, not the consumer's. Two vite\n * type instances are nominally incompatible — rollup's plugin container\n * carries a private `_pluginContextMap` — and a single unassignable entry\n * poisons the overload resolution for the consumer's whole `plugins: []`\n * array, so every other plugin in it errors too. Vite's own `Plugin` requires\n * nothing but `name`, so a structural shape drops into any vite version's\n * `PluginOption` while the hooks below stay checked against the real vite\n * types inside this file.\n */\nexport interface IterationPlugin {\n name: string;\n /**\n * Declared with the loosest shape that still drops into vite's own\n * signature: a method, so its parameter is bivariant and vite's\n * `HmrContext` satisfies it, returning `void`, which any real return type\n * satisfies. The implementation returns vite's `ModuleNode[]`; naming that\n * type here would bring the nominal vite instance back.\n */\n handleHotUpdate?(ctx: { file: string }): void;\n}\n\nconst DEFAULT_FILE = '.iteration-feedback.json';\nconst INJECTED = new WeakSet<ServerResponse>();\nconst BUNDLE_PATH = '/@isotone/panel.js';\nconst MANIFEST = 'variant.json';\n\n/**\n * Import queries that hand the file to one of vite's own loaders (assets,\n * workers, inline HTML scripts). Those read the file from disk themselves\n * and shape the module around it; a `pre` load returning the override's\n * text in their place would break the module, so such requests are left to\n * them and show the real file.\n */\nconst SPECIAL_QUERY = /[?&](raw|url|inline|no-inline|worker|sharedworker|html-proxy)(?:[&=]|$)/;\n\n/** Element type comparisons, which a component wrapper would break. */\nconst COMPARES_TYPES = /\\.type\\s*[!=]==?|[!=]==?\\s*[\\w$.]+\\.type\\b/;\n\n/** The version a module id names (`?isotone=<id>`), or null for any other module. */\nfunction versionOfId(id: string | null): string | null {\n const at = id?.indexOf('?') ?? -1;\n if (!id || at < 0) return null;\n return new URLSearchParams(id.slice(at + 1)).get(VERSION_QUERY);\n}\n\n/** `dir` itself or a path below it; never a sibling whose name merely\n * starts the same (`src-old` under `src`). */\nfunction isInside(dir: string, path: string): boolean {\n const rel = relative(dir, path);\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n}\n\n/** The canonical form of a directory, or the path as given when it does not\n * exist yet (nothing to canonicalize; the comparison can only fail open). */\nfunction realDir(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nexport function iteration(options: IterationViteOptions = {}): IterationPlugin {\n let file = resolve(options.file ?? DEFAULT_FILE);\n let isDev = false;\n let isBuild = false;\n let isAsset: (file: string) => boolean = () => false;\n\n const variantsOptions = options.variants === false ? null : (options.variants ?? {});\n let vopts: VariantsStoreOptions = {\n root: resolve(variantsOptions?.root ?? '.'),\n ...(variantsOptions?.dir ? { dir: variantsOptions.dir } : {}),\n };\n let vDir = variantsDir(vopts);\n let activeFile = join(vopts.root, ACTIVE_FILE);\n\n // The active set, and which override (if any) answers each source path\n // under it. `resolveOverride` re-reads the manifests every call, and load()\n // asks once per module per page, so memoize per active set and drop the\n // memo whenever the set or anything under the variants dir changes.\n // `undefined` means not read yet: configureServer primes it, and a load()\n // that somehow runs first reads the file itself.\n let activeIds: string[] | undefined;\n const overrides = new Map<string, string | null>();\n // Real source paths activate() is reporting as changed right now. Their\n // hot update must go through, where an ordinary edit of an overridden\n // real file is dropped (see handleHotUpdate). Each path keeps the\n // environments that have already seen the swap: Vite 6 and later ask every\n // environment about one change, the browser first and the server after.\n const swapping = new Map<string, Set<string>>();\n\n // Live mode (see ./live.ts). Decided in configureServer, where the server's\n // environments show which Vite this is.\n let live = false;\n let hasReact = false;\n let ssrHost = false;\n let manifests: OverlayVariant[] | null = null;\n let byFile: Map<string, string[]> | null = null;\n let addedFiles: Map<string, string[]> | null = null;\n // The export names each dispatcher was written with, by real path. A\n // version whose names change needs a new dispatcher, which is a reload.\n const dispatched = new Map<string, string>();\n let reloadTimer: ReturnType<typeof setTimeout> | null = null;\n\n const readManifests = (): OverlayVariant[] => {\n manifests ??= readVariants(vopts);\n return manifests;\n };\n /** Variant ids that have a copy of each file, by forward-slash absolute path. */\n const versionsByFile = (): Map<string, string[]> => {\n if (byFile) return byFile;\n byFile = new Map();\n for (const variant of readManifests()) {\n for (const key of Object.keys(variant.files)) {\n const path = normalizePath(join(vopts.root, key));\n byFile.set(path, [...(byFile.get(path) ?? []), variant.id]);\n }\n }\n return byFile;\n };\n /** Files only variants have, keyed by their path without an extension. */\n const filesOnlyInVariants = (): Map<string, string[]> => {\n if (addedFiles) return addedFiles;\n addedFiles = new Map();\n for (const path of versionsByFile().keys()) {\n if (existsSync(path)) continue;\n const stem = path.replace(/\\.[cm]?[jt]sx?$/, '');\n addedFiles.set(stem, [...(addedFiles.get(stem) ?? []), path]);\n }\n return addedFiles;\n };\n const forgetManifests = () => {\n manifests = null;\n byFile = null;\n addedFiles = null;\n overrides.clear();\n };\n const groupsOf = (list: OverlayVariant[]): LiveConfig['groups'] =>\n overlayGroups(list).map((group) => ({ id: group.id, members: group.members.map((m) => m.id) }));\n const liveConfig = (): LiveConfig => ({\n groups: groupsOf(readManifests()),\n active: currentActive(),\n ssr: ssrHost,\n endpoint: VARIANTS_ENDPOINT,\n });\n const overrideOf = (id: string, path: string): string | null => {\n const key = normalizePath(relative(vopts.root, path));\n const manifest = readManifests().find((v) => v.id === id);\n if (!manifest || !Object.hasOwn(manifest.files, key)) return null;\n const file = join(variantDir(vopts, id), key);\n return existsSync(file) ? file : null;\n };\n\n /**\n * How to dispatch `path`, or null to serve it whole: a script with at\n * least one variant copy, whose every version lists its exports plainly,\n * and which is not a route module a framework reads export by export.\n */\n const dispatchPlan = (path: string): { key: string; versions: (string | null)[]; names: string[] } | null => {\n if (!/\\.[cm]?[jt]sx?$/.test(path)) return null;\n const ids = versionsByFile().get(path);\n if (!ids?.length) return null;\n const versions: (string | null)[] = [];\n const names = new Set<string>();\n const sources: [string | null, string][] = [];\n if (existsSync(path)) sources.push([null, path]);\n for (const id of ids) {\n const file = overrideOf(id, path);\n if (file) sources.push([id, file]);\n }\n for (const [id, file] of sources) {\n const code = readFileSync(file, 'utf8');\n // Code that compares element types (`child.type === Tab`) would see\n // the wrapper on one side and its own component on the other.\n if (COMPARES_TYPES.test(code)) return null;\n const found = scanExports(code);\n if (!found || isRouteModule(found)) return null;\n for (const name of found) names.add(name);\n versions.push(id);\n }\n // A file without exports runs for its side effects (an entry, a\n // registration); loading every version would run them all.\n if (versions.length === 0 || names.size === 0) return null;\n return { key: normalizePath(relative(vopts.root, path)), versions, names: [...names].sort() };\n };\n const namesChanged = (path: string): boolean => {\n const plan = dispatchPlan(path);\n return !plan || plan.names.join(',') !== dispatched.get(path);\n };\n let reloadPage: () => void = () => {};\n const swapWaiters = new Set<() => void>();\n\n /**\n * Which modules a file change updates in one environment (`null`: Vite 5,\n * which asks once for all of them). `undefined` lets Vite decide.\n */\n const hotModules = <M extends { id: string | null }>(\n changed: string,\n modulesOf: (file: string) => Iterable<M> | undefined,\n env: string | null,\n ): M[] | undefined => {\n if (!variantsOptions) return undefined;\n const client = env === null || env === 'client';\n // The module graph keys files by their forward-slash form, which is\n // what `join` produces on POSIX and not on Windows.\n if (isInside(vDir, changed)) {\n overrides.clear();\n const hit = overrideSourcePath(vopts, changed);\n // The manifest, or a file directly in the variants dir: nothing the\n // browser has loaded. The panel re-lists variants when it opens.\n if (!hit || hit.file === MANIFEST) return [];\n const source = normalizePath(join(vopts.root, hit.file));\n // Live: the copy has a module of its own; update just that one.\n if (live && client && dispatched.has(source)) {\n if (namesChanged(source)) {\n reloadPage();\n return [];\n }\n return [...(modulesOf(source) ?? [])].filter((m) => versionOfId(m.id) === hit.id);\n }\n if (!currentActive().includes(hit.id)) return [];\n // The browser holds the real file's URL, so the override's edit has\n // to be delivered as if the real file changed.\n return [...(modulesOf(source) ?? [])];\n }\n // A change activate() reported.\n const seen = swapping.get(changed);\n let swap = false;\n if (seen) {\n if (env === null) {\n swapping.delete(changed);\n swap = true;\n } else if (!seen.has(env)) {\n seen.add(env);\n swap = true;\n for (const check of [...swapWaiters]) check();\n }\n }\n const path = normalizePath(changed);\n if (live && client && dispatched.has(path)) {\n // The dispatcher already holds every version; the tab switched itself.\n if (swap) return [];\n if (namesChanged(path)) {\n reloadPage();\n return [];\n }\n return [...(modulesOf(path) ?? [])].filter((m) => versionOfId(m.id) === BASE_VERSION);\n }\n // Let Vite compute the swap's update as usual.\n if (swap) return undefined;\n // The real source of an overridden file: the browser is showing the\n // override, so there is nothing to update from this edit.\n if (overridable(changed) && overrideFor(currentActive(), changed)) return [];\n return undefined;\n };\n\n const currentActive = (): string[] => {\n // A build takes its set from the environment: `ISOTONE_VARIANT=a,b`.\n if (isBuild) return parseVariantList(process.env.ISOTONE_VARIANT);\n if (activeIds === undefined) activeIds = readActive(vopts);\n return activeIds;\n };\n\n const overrideFor = (active: string[], path: string): string | null => {\n if (active.length === 0) return null;\n // Sorted: the same set in another order answers the same for every path.\n const key = `${[...active].sort().join(',')}\\0${path}`;\n let hit = overrides.get(key);\n if (hit === undefined) {\n hit = resolveOverride(vopts, active, path);\n overrides.set(key, hit);\n }\n return hit;\n };\n\n /** Whether load() may swap `path` at all: a real file of the project the\n * variants describe, not a dependency and not an override itself. */\n // Module ids reach load() with forward slashes on every platform, while a\n // watcher path is native; splitting on either separator covers both.\n const overridable = (path: string): boolean =>\n isAbsolute(path) &&\n !path.split(/[\\\\/]/).includes('node_modules') &&\n isInside(vopts.root, path) &&\n !isInside(vDir, path) &&\n !isAsset(path);\n\n // `satisfies`, not an annotation: the hooks are checked against vite's\n // types, but the object keeps its own shape, so `handleHotUpdate` stays a\n // plain method and drops into the structural type below.\n const plugin = {\n name: 'iso:iteration',\n enforce: 'pre',\n configResolved(config: ResolvedConfig) {\n isDev = config.command === 'serve';\n isBuild = config.command === 'build';\n isAsset = config.assetsInclude;\n file = resolve(config.root, options.file ?? DEFAULT_FILE);\n // Vite hands load() realpath'd module ids but leaves `config.root` as\n // configured, so a root reached through a symlink would never contain\n // any module and no override would ever apply. Canonicalize it here.\n vopts = {\n root: realDir(resolve(config.root, variantsOptions?.root ?? '.')),\n ...(variantsOptions?.dir ? { dir: variantsOptions.dir } : {}),\n };\n vDir = variantsDir(vopts);\n activeFile = join(vopts.root, ACTIVE_FILE);\n hasReact = (config.plugins ?? []).some((p) => /react/i.test(p.name));\n ssrHost = config.appType !== 'spa' && config.appType !== 'mpa';\n forgetManifests();\n },\n async resolveId(source: string, importer: string | undefined, opts: { ssr?: boolean; isEntry?: boolean } = {}) {\n if (!variantsOptions) return null;\n if (source === LIVE_MODULE) return RESOLVED_LIVE_MODULE;\n if (!importer) return null;\n // A dispatcher's own imports, `./file.tsx?isotone=<id>`: resolved here\n // so a version of a file only variants have still has an id.\n const marker = source.indexOf(`?${VERSION_QUERY}=`);\n if (live && marker > 0 && source.startsWith('./')) {\n const dir = dirname(importer.replace(/[?#].*$/, ''));\n return normalizePath(resolve(dir, source.slice(0, marker))) + source.slice(marker);\n }\n // A file a variant adds, imported by variant code. Vite's resolver\n // cannot find it on disk, so answer with the path the variant gives it.\n const added = filesOnlyInVariants();\n if (added.size === 0 || source.startsWith('\\0')) return null;\n const bare = source.replace(/[?#].*$/, '');\n const leaf = bare.slice(bare.lastIndexOf('/') + 1).replace(/\\.[cm]?[jt]sx?$/, '');\n const candidates = [...added.entries()].filter(([stem]) =>\n stem.endsWith(`/${leaf}`) || stem.endsWith(`/${leaf}/index`));\n if (candidates.length === 0) return null;\n const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true });\n if (resolved) return resolved;\n const importerPath = importer.replace(/[?#].*$/, '');\n const target = bare.startsWith('.') ? normalizePath(resolve(dirname(importerPath), bare)).replace(/\\.[cm]?[jt]sx?$/, '') : null;\n // A relative import names the file exactly; an aliased one (`@/x/y`)\n // is matched on everything after its first segment.\n const tail = bare.split('/').slice(1).join('/').replace(/\\.[cm]?[jt]sx?$/, '');\n const hits = candidates.filter(([stem]) => target\n ? stem === target || stem === `${target}/index`\n : tail !== '' && (stem.endsWith(`/${tail}`) || stem.endsWith(`/${tail}/index`)));\n if (hits.length !== 1) return null;\n const paths = hits[0]?.[1] ?? [];\n return paths.length === 1 ? paths[0] : null;\n },\n load(id: string, opts?: { ssr?: boolean }) {\n if (!variantsOptions || SPECIAL_QUERY.test(id)) return null;\n if (id === RESOLVED_LIVE_MODULE) return { code: liveRuntimeModule(liveConfig()), map: null };\n // `?v=<hash>`, `?t=<timestamp>`, `?import`: vite's own request\n // decorations, never part of the path on disk.\n const path = id.replace(/[?#].*$/, '');\n if (!overridable(path)) return null;\n const query = id.slice(path.length).replace(/^\\?/, '').replace(/#.*$/, '');\n const version = live ? new URLSearchParams(query).get(VERSION_QUERY) : null;\n if (version !== null) {\n const from = version === BASE_VERSION ? (existsSync(path) ? path : null) : overrideOf(version, path);\n return { code: from ? readFileSync(from, 'utf8') : 'export {};\\n', map: null };\n }\n // The browser gets a dispatcher; a server render keeps the whole-file\n // swap, since the server cannot know which tab it renders for.\n if (live && !opts?.ssr && query === '') {\n const plan = dispatchPlan(path);\n if (plan) {\n dispatched.set(path, plan.names.join(','));\n const name = path.slice(path.lastIndexOf('/') + 1);\n return { code: dispatcherModule(plan.key, name, plan.versions, plan.names), map: null };\n }\n }\n const override = overrideFor(currentActive(), path);\n if (!override) return null;\n return { code: readFileSync(override, 'utf8'), map: null };\n },\n // Vite 6 and later call this once per environment and skip\n // handleHotUpdate; Vite 5 only knows handleHotUpdate.\n hotUpdate(this: { environment: DevEnvironment }, ctx: HotUpdateOptions): EnvironmentModuleNode[] | undefined {\n const env = this.environment;\n return hotModules(ctx.file, (f) => env.moduleGraph.getModulesByFile(f), env.name);\n },\n handleHotUpdate(ctx: HmrContext) {\n const { server } = ctx;\n return hotModules(ctx.file, (f) => server.moduleGraph.getModulesByFile(f), null) as HmrContext['modules'] | undefined;\n },\n configureServer(server) {\n if (!isDev) return;\n // Here, not at construction: a production build should not touch .git.\n ensureFileIgnored(file);\n\n // Say where the notes go, after Vite's own banner so it is not buried\n // under it. Portable setups fail quietly otherwise: a reviewer writes\n // notes and the agent looks in the wrong directory.\n server.httpServer?.once('listening', () => {\n const shown = relative(server.config.root, file) || file;\n server.config.logger.info(\n ` isotone notes → ${shown} (${NOTES_ENDPOINT})`,\n );\n if (variantsOptions && existsSync(vDir)) {\n const shownDir = relative(server.config.root, vDir) || vDir;\n const n = listVariants(vopts).length;\n server.config.logger.info(\n ` isotone variants → ${shownDir} (${n} variant${n === 1 ? '' : 's'})`,\n );\n }\n });\n\n const guardOrigin = (req: IncomingMessage, res: ServerResponse): boolean => {\n try { checkOrigin(req.headers.origin, req.headers.host ?? ''); return true; }\n catch (error) { sendFailure(res, error); return false; }\n };\n\n const updates = startUpdateCheck(server.config.root, options.checkForUpdates !== false);\n server.httpServer?.once('close', updates.dispose);\n server.middlewares.use(UPDATE_ENDPOINT, (req, res) => {\n if (!guardOrigin(req, res)) return;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.statusCode = req.method === 'GET' ? 200 : 405;\n res.end(JSON.stringify(req.method === 'GET' ? updates.getSnapshot() : { error: 'method not allowed' }));\n });\n\n // Notes endpoint → local file.\n server.middlewares.use(NOTES_ENDPOINT, (req, res, next) => {\n if (!guardOrigin(req, res)) return;\n const method = req.method ?? '';\n if (method !== 'GET' && method !== 'POST' && method !== 'DELETE') {\n next();\n return;\n }\n (method === 'POST' ? readNodeJson(req) : Promise.resolve(undefined)).then((body) => {\n answer(res, () => notesResponse(file, { method, url: req.url, body }));\n }).catch((error) => sendFailure(res, error));\n });\n\n if (variantsOptions) {\n // Read the pointer now, before anything can rewrite it: activate()\n // diffs the previous set against the new one, and the endpoint has\n // already written the file by the time it runs, so a lazy first read\n // would see the new set twice and switch nothing.\n activeIds = readActive(vopts);\n\n // Live switching needs the host's React for the wrappers and Vite 6's\n // per-environment hot updates, so the server render keeps its swap\n // while the browser's dispatchers are left alone.\n live = (variantsOptions.live ?? hasReact) && server.environments !== undefined;\n const clientGraph = () => server.environments?.client?.moduleGraph ?? server.moduleGraph;\n const signature = () => JSON.stringify(readManifests().map((v) => [v.id, v.group ?? '', Object.keys(v.files).sort()]));\n let listed = live ? signature() : '';\n // A dispatcher is written for one set of versions and names. When\n // either changes, the browser needs new dispatchers, which a hot\n // update cannot deliver: drop them and reload the page once.\n reloadPage = () => {\n if (reloadTimer) clearTimeout(reloadTimer);\n reloadTimer = setTimeout(() => {\n reloadTimer = null;\n const graph = clientGraph();\n // Files that were dispatchers, and files that have just gained a\n // variant and still hold their plain transform.\n const paths = new Set([...dispatched.keys(), ...versionsByFile().keys()]);\n for (const path of paths) {\n for (const mod of graph.getModulesByFile(path) ?? []) graph.invalidateModule(mod as never);\n }\n const runtime = graph.getModuleById(RESOLVED_LIVE_MODULE);\n if (runtime) graph.invalidateModule(runtime as never);\n dispatched.clear();\n server.ws.send({ type: 'full-reload', path: '*' });\n }, 50);\n };\n\n /**\n * Switch the browser to the set `next` without reloading the page.\n * Every file overridden by a variant that entered or left the set\n * is reported to Vite as if it had just been edited on disk: Vite\n * invalidates it, runs load() again (which now answers with the\n * other content) and sends the same hot update an editor save\n * would, so React Fast Refresh swaps the component in place and the\n * reviewer keeps their scroll, their form state and the open panel.\n * Variants in both sets are untouched, so switching one group leaves\n * the others' components alone. Files the browser has not loaded\n * are skipped; Vite decides on its own when a module cannot be\n * hot-swapped and falls back to a reload for that one, exactly as\n * it would for a hand edit.\n */\n const activate = (next: string[], removedFiles: string[] = []): Promise<void> => {\n const prev = currentActive();\n const changed = [\n ...prev.filter((id) => !next.includes(id)),\n ...next.filter((id) => !prev.includes(id)),\n ];\n if (changed.length === 0 && removedFiles.length === 0) return Promise.resolve();\n activeIds = next;\n overrides.clear();\n const sources = new Set<string>(removedFiles.map((file) => join(vopts.root, file)));\n for (const id of changed) {\n const manifest = readVariant(vopts, id);\n for (const key of Object.keys(manifest?.files ?? {})) {\n sources.add(join(vopts.root, key));\n }\n }\n const emitted: string[] = [];\n for (const source of sources) {\n const loaded = server.moduleGraph.getModulesByFile(normalizePath(source));\n if (!loaded || loaded.size === 0) continue;\n swapping.set(source, new Set());\n emitted.push(source);\n server.watcher.emit('change', source);\n }\n // Live tabs switch themselves; this tells the ones still on the\n // server's default to follow it, once a reload would render it.\n const settled = serverSawSwap(emitted);\n if (live) void settled.then(() => server.ws.send({ type: 'custom', event: ACTIVE_EVENT, data: { active: next } }));\n return settled;\n };\n\n /**\n * Resolves once every server environment (an SSR render) has taken\n * the swap of `files`, or after a second. A tab that reloads right\n * after its POST would otherwise be rendered from the old files and\n * fail to hydrate.\n */\n const serverSawSwap = (files: string[]): Promise<void> => {\n const envs = Object.keys(server.environments ?? {}).filter((name) => name !== 'client');\n if (!live || files.length === 0 || envs.length === 0) return Promise.resolve();\n return new Promise<void>((done) => {\n const check = () => {\n const seen = files.every((file) => {\n const by = swapping.get(file);\n return !by || envs.every((env) => by.has(env));\n });\n if (!seen) return;\n finish();\n };\n const timer = setTimeout(() => finish(), 1000);\n const finish = () => {\n clearTimeout(timer);\n swapWaiters.delete(check);\n // The update itself goes out after the hook that marked it.\n setTimeout(done, 30);\n };\n swapWaiters.add(check);\n check();\n });\n };\n\n // The exclude helpers canonicalize through the filesystem, so the\n // active file's directory has to exist before its pattern can land;\n // the panel's first POST would otherwise leave an untracked file.\n mkdirSync(dirname(activeFile), { recursive: true });\n ensureFileIgnored(activeFile);\n if (variantsOptions.ignored) {\n mkdirSync(vDir, { recursive: true });\n ensureDirIgnored(vDir);\n }\n\n server.middlewares.use(VARIANTS_ENDPOINT, (req, res, next) => {\n if (!guardOrigin(req, res)) return;\n const method = req.method ?? '';\n if (method !== 'GET' && method !== 'POST') {\n next();\n return;\n }\n // A POST switches every open tab of this dev server to another set\n // of files. A cross-site page can fire a `no-cors` form post at\n // localhost, but only with a text/plain or form content type; a\n // JSON content type needs a preflight, which vite's CORS does not\n // grant to an unknown origin. So the header is the gate.\n if (method === 'POST' && !isJsonRequest(req)) {\n res.statusCode = 415;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.end(JSON.stringify({ error: 'content-type must be application/json' }));\n return;\n }\n (method === 'POST' ? readNodeJson(req) : Promise.resolve(undefined)).then((body) => {\n // connect strips the mount from `req.url`, which is the shape\n // variantsResponse routes on (\"/\", \"/active?...\").\n let result: ReturnType<typeof variantsResponse>;\n try {\n result = variantsResponse(vopts, { method, url: req.url, body });\n } catch (error) {\n sendFailure(res, error);\n return;\n }\n const send = () => { answer(res, () => result); };\n if (result.status === 200 && method === 'POST') {\n const updated = result.body as { active: string[]; changedFiles?: string[] };\n // Answer once the switch is in place, so the panel can reload\n // straight into it.\n activate(updated.active, updated.changedFiles).then(send, send);\n } else {\n send();\n }\n }).catch((error) => sendFailure(res, error));\n });\n\n // The CLI's `variant use` writes the active file with no request to\n // this server, and an agent edits overrides in place: both have to\n // reach the browser. The active file may not exist yet, so watch its\n // directory; chokidar reports files that appear later.\n server.watcher.add(dirname(activeFile));\n server.watcher.add(vDir);\n server.watcher.on('all', (_event: string, changed: string) => {\n const path = resolve(changed);\n if (path === activeFile) {\n void activate(readActive(vopts));\n } else if (isInside(vDir, path)) {\n // Covers adds and unlinks, which handleHotUpdate never sees.\n forgetManifests();\n if (live) {\n const now = signature();\n if (now !== listed) {\n listed = now;\n reloadPage();\n }\n }\n }\n });\n }\n\n // The tab's variant store has to exist before the app's modules run,\n // so it rides in the document itself, with the server's current set.\n const liveScript = () => (live ? liveStoreScript(liveConfig()) : null);\n if (options.panel === false) {\n if (!live) return;\n server.middlewares.use((req, res, next) => {\n if (!(req.headers.accept ?? '').includes('text/html')) {\n next();\n return;\n }\n delete req.headers['if-none-match'];\n delete req.headers['if-modified-since'];\n injectHtmlResponse(res, null, liveScript);\n next();\n });\n return;\n }\n\n // A self-contained bundle keeps the panel out of the host's dependency\n // graph and works in React, Vue, Svelte and plain Vite apps alike.\n server.middlewares.use(BUNDLE_PATH, (_req, res) => {\n res.setHeader('content-type', 'text/javascript; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(readBundle());\n });\n const mountCode = mountModuleSource(options.rule ?? {}, options.key ?? '', variantsOptions !== null, options.shortcut, options.theme);\n\n server.middlewares.use((req, res, next) => {\n // Only navigations: buffering every response to look for </body>\n // would tax each of the hundreds of module requests a dev page makes.\n if (!(req.headers.accept ?? '').includes('text/html')) {\n next();\n return;\n }\n // Vite's ETag is computed from the document before the mount script\n // is appended, so a conditional request validates against the wrong\n // bytes: a browser holding a copy from before this plugin was added\n // gets 304 and never sees the panel. Ask for the full document.\n delete req.headers['if-none-match'];\n delete req.headers['if-modified-since'];\n injectHtmlResponse(res, mountCode, liveScript);\n next();\n });\n },\n } satisfies Plugin;\n\n return plugin;\n}\n\n/** `ISOTONE_VARIANT=a, b` → `['a', 'b']`; unset or blank → `[]`. */\nfunction parseVariantList(raw: string | undefined): string[] {\n return (raw ?? '')\n .split(',')\n .map((id) => id.trim())\n .filter(Boolean);\n}\n\n/** Whether the request declares a JSON body (`application/json`, with or\n * without a charset parameter). */\nfunction isJsonRequest(req: IncomingMessage): boolean {\n const type = req.headers['content-type'];\n return typeof type === 'string' && type.toLowerCase().includes('application/json');\n}\n\n/**\n * Write a store response, or a 500 when the store throws. A store that\n * cannot write (permissions, a read-only mount) must still answer, or the\n * panel's request hangs and the reviewer sees nothing; a 500 sends a note\n * to the localStorage fallback. Returns the response so the caller can act\n * on a success, `null` on a throw.\n */\nfunction answer(\n res: ServerResponse,\n respond: () => { status: number; headers: Record<string, string>; body: unknown },\n): { status: number; body: unknown } | null {\n try {\n const { status, headers, body } = respond();\n res.statusCode = status;\n for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);\n res.end(JSON.stringify(body));\n return { status, body };\n } catch (cause) {\n sendFailure(res, cause);\n return null;\n }\n}\n\n/** Load after the host has mounted, without importing its React or HMR runtime. */\nfunction mountModuleSource(rule: RouteGateOptions, key: string, variants: boolean, shortcut?: IterationShortcut | false, theme?: IterationTheme): string {\n const config = JSON.stringify({ endpoint: NOTES_ENDPOINT, updateEndpoint: UPDATE_ENDPOINT, key, shortcut, theme, rule, ...(variants ? { variants: 'overlay' } : {}) }).replace(/</g, '\\\\u003c');\n return `\n const start = () => {\n const mount = () => window.__isotone.mount(${config});\n if (window.__isotone) return mount();\n const script = document.createElement('script');\n script.src = ${JSON.stringify(BUNDLE_PATH)};\n script.onload = mount;\n document.head.appendChild(script);\n };\n if (document.readyState === 'complete') start();\n else window.addEventListener('load', start, { once: true });\n `;\n}\n\nfunction injectHtmlResponse(res: ServerResponse, code: string | null, head: () => string | null = () => null): void {\n if (INJECTED.has(res)) return;\n INJECTED.add(res);\n\n // Buffer the whole document and send it once from `end`. Passing chunks\n // through as they arrive would mean re-sending the document to inject, and\n // a streamed SSR body (React Router, Next) is chunked anyway, so nothing is\n // lost by waiting for `</body>`. Only navigations reach here (see the\n // `accept` check above), so this never buffers an SSE or module response.\n const originalWrite = res.write.bind(res);\n const originalEnd = res.end.bind(res);\n const originalSetHeader = res.setHeader.bind(res);\n const originalWriteHead = res.writeHead.bind(res);\n const chunks: Buffer[] = [];\n let buffering = true;\n\n // Web-stream adapters hand `res.write` a Uint8Array, which is neither a\n // string nor a Buffer; `chunk.toString('utf8')` on one yields a\n // comma-separated byte list, so wrap it instead of stringifying it.\n const toBuffer = (chunk: unknown): Buffer | null => {\n if (typeof chunk === 'string') return Buffer.from(chunk, 'utf8');\n if (Buffer.isBuffer(chunk)) return chunk;\n if (chunk instanceof Uint8Array) {\n return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n }\n return null;\n };\n\n // The injected script changes the bytes, so an upstream `Content-Length`\n // (Vite's `send`, a framework's own header) would truncate the document at\n // the original size, and an upstream `ETag` would describe a document the\n // browser never receives. Drop both; the response goes chunked and the\n // browser revalidates every time, which a dev page should anyway.\n const STRIPPED = new Set(['content-length', 'etag', 'last-modified']);\n const isLength = (name: string) => STRIPPED.has(name.toLowerCase());\n res.setHeader = ((name: string, value: number | string | readonly string[]) =>\n isLength(name) ? res : originalSetHeader(name, value)) as ServerResponse['setHeader'];\n res.writeHead = ((status: number, ...rest: unknown[]) => {\n const headers = rest[rest.length - 1];\n if (Array.isArray(headers)) {\n rest[rest.length - 1] = headers.filter((entry, i, all) => {\n // Either [[k, v], ...] or a flat [k, v, k, v, ...] list.\n if (Array.isArray(entry)) return !isLength(String(entry[0]));\n const key = i % 2 === 0 ? entry : all[i - 1];\n return !isLength(String(key));\n });\n } else if (headers && typeof headers === 'object') {\n for (const key of Object.keys(headers)) {\n if (isLength(key)) delete (headers as Record<string, unknown>)[key];\n }\n }\n return originalWriteHead(status, ...(rest as []));\n }) as unknown as ServerResponse['writeHead'];\n\n res.write = ((chunk: unknown, ...rest: unknown[]) => {\n if (!buffering) return originalWrite(chunk as string, ...(rest as []));\n const buf = toBuffer(chunk);\n if (buf) chunks.push(buf);\n const cb = rest.find((r): r is () => void => typeof r === 'function');\n if (cb) queueMicrotask(cb);\n return true;\n }) as unknown as ServerResponse['write'];\n\n res.end = ((...args: unknown[]) => {\n const buf = toBuffer(args[0]);\n if (buf) chunks.push(buf);\n const cb = args.find((a): a is () => void => typeof a === 'function');\n buffering = false;\n const body = Buffer.concat(chunks).toString('utf8');\n if (body.includes('<html') && (body.includes('<head') || body.includes('</body>'))) {\n const script = code === null ? '' : `<script type=\"module\" data-isotone-inject>${code}</script>`;\n // Classic, not a module: it runs during parsing, before any module.\n const store = head();\n const early = store ? `<script data-isotone-live>${store.replace(/<\\/script/gi, '<\\\\/script')}</script>` : '';\n if (!res.headersSent) originalSetHeader('Cache-Control', 'no-store');\n return originalEnd(withNativeFetch(injectIntoHead(body, `${early}${script}`)), cb);\n }\n return originalEnd(Buffer.concat(chunks), cb);\n }) as unknown as ServerResponse['end'];\n}\n\n/**\n * Put the mount loader script in `<head>`, after the opening head tag. React\n * never hydrates head contents it receives as part of a server document —\n * `<head>` is a special host that React replaces wholesale, unlike `<body>`,\n * and any stray script inside it is inert for React — so this cannot trip the\n * \"script tag while rendering React component\" warning or the hydration\n * discard that follows it in a whole-document React Router app. Falls back to\n * just before `</head>`, then just before `</body>` for a fragment without a\n * head, then appends, matching what `withNativeFetch` does below.\n */\nfunction injectIntoHead(html: string, script: string): string {\n const head = html.match(/<head[^>]*>/i);\n if (head?.index !== undefined) {\n const at = head.index + head[0].length;\n return `${html.slice(0, at)}${script}${html.slice(at)}`;\n }\n const headEnd = html.match(/<\\/head>/i);\n if (headEnd?.index !== undefined) {\n return `${html.slice(0, headEnd.index)}${script}${html.slice(headEnd.index)}`;\n }\n const body = html.match(/<body[^>]*>/i);\n if (body?.index !== undefined) {\n const at = body.index + body[0].length;\n return `${html.slice(0, at)}${script}${html.slice(at)}`;\n }\n return `${html}${script}`;\n}\n\n/**\n * A one-line script as early in the document as possible that keeps a\n * reference to the browser's own `fetch`. Apps replace `window.fetch` for\n * their own reasons — a preview app answering its backend calls, a mock\n * layer, an auth shim — and a stub that answers 404 to anything it does not\n * know would swallow the panel's saves; the store then falls back to\n * localStorage and the reviewer's notes look lost. The store prefers this\n * reference when it exists. Placed right after `<head>` (or `<body>` when\n * there is no head) so it runs before any app module.\n */\nexport function withNativeFetch(html: string): string {\n if (html.includes('__isotoneFetch')) return html;\n const capture =\n '<script data-isotone-native>window.__isotoneFetch=window.fetch.bind(window)</script>';\n const head = html.match(/<head[^>]*>/i);\n if (head?.index !== undefined) {\n const at = head.index + head[0].length;\n return `${html.slice(0, at)}${capture}${html.slice(at)}`;\n }\n const body = html.match(/<body[^>]*>/i);\n if (body?.index !== undefined) {\n const at = body.index + body[0].length;\n return `${html.slice(0, at)}${capture}${html.slice(at)}`;\n }\n return html;\n}\n","/**\n * The runtime names a source file exports, read from its text without a\n * parser. Live variants need them to write a dispatcher module whose\n * `export` statements cover every version of a file; anything this cannot\n * read with certainty answers `null`, and the plugin falls back to swapping\n * that file whole.\n *\n * Only statements that start a line are read. Formatted code always puts a\n * top-level `export` at the start of its line, while one inside a template\n * string or a comment almost never is, and a stray hit there only adds a\n * name whose value is `undefined`. Type-only exports are skipped: they do\n * not exist at runtime.\n */\n\n/** Exports whose names are only meaningful to a framework that reads the\n * module itself (React Router and Remix route modules). Such a file is\n * transformed by the framework's own plugin, which a dispatcher would hide\n * the real exports from. */\nconst ROUTE_EXPORTS = new Set([\n 'loader', 'action', 'clientLoader', 'clientAction', 'headers', 'links',\n 'meta', 'handle', 'shouldRevalidate', 'middleware', 'clientMiddleware',\n 'unstable_middleware', 'unstable_clientMiddleware', 'HydrateFallback',\n]);\n\nconst IDENT = /^[A-Za-z_$][\\w$]*$/;\n\nexport function scanExports(code: string): string[] | null {\n const names = new Set<string>();\n const lines = code.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n // A one-line block comment in front (`/** Doc */ export …`) is skipped.\n const line = (lines[i] ?? '').replace(/^(?:\\/\\*.*?\\*\\/\\s*)+/, '');\n if (!line.startsWith('export')) continue;\n const rest = line.slice('export'.length);\n if (rest !== '' && !/^[\\s{*]/.test(rest)) continue; // `exported = 1`\n const body = rest.trim();\n\n // `export { a, b as c } [from '…']`, possibly over several lines.\n if (body.startsWith('{') || body.startsWith('type {')) {\n if (body.startsWith('type')) continue;\n let clause = body;\n while (!clause.includes('}') && i + 1 < lines.length) clause += ` ${lines[++i]}`;\n const inner = clause.slice(clause.indexOf('{') + 1, clause.indexOf('}'));\n for (const raw of inner.split(',')) {\n const spec = raw.replace(/\\/\\/.*$/, '').trim();\n if (!spec || spec.startsWith('type ')) continue;\n const as = spec.split(/\\s+as\\s+/);\n const name = (as[1] ?? as[0] ?? '').trim().replace(/^[\"']|[\"']$/g, '');\n if (!name) return null;\n names.add(name);\n }\n continue;\n }\n\n if (/^type\\s*\\*/.test(body)) continue;\n // `export * as ns from '…'` names one binding; a bare `export *`\n // re-exports names this file cannot see.\n const star = body.match(/^\\*\\s+as\\s+([A-Za-z_$][\\w$]*)/);\n if (star?.[1]) { names.add(star[1]); continue; }\n if (body.startsWith('*')) return null;\n\n if (/^default\\b/.test(body)) { names.add('default'); continue; }\n if (/^(?:declare\\s|type\\s|interface\\s)/.test(body)) continue;\n if (/^(?:=|import\\s|namespace\\s|module\\s|as\\s)/.test(body)) return null;\n\n const decl = body.match(\n /^(?:async\\s+)?function\\s*\\*?\\s*([A-Za-z_$][\\w$]*)|^(?:abstract\\s+)?class\\s+([A-Za-z_$][\\w$]*)|^(?:const\\s+)?enum\\s+([A-Za-z_$][\\w$]*)/,\n );\n const declared = decl?.[1] ?? decl?.[2] ?? decl?.[3];\n if (declared) { names.add(declared); continue; }\n\n const variable = body.match(/^(?:const|let|var)\\s+(.*)$/);\n if (variable) {\n const target = (variable[1] ?? '').trim();\n // Destructuring declares names that need a real parser to list.\n if (target.startsWith('{') || target.startsWith('[')) return null;\n const name = target.match(/^([A-Za-z_$][\\w$]*)/)?.[1];\n if (!name) return null;\n // Several declarators (`export const a = 1, b = 2`, possibly over\n // lines) need a parser to list; serve such a file whole.\n if (hasSecondDeclarator(target)) return null;\n names.add(name);\n continue;\n }\n return null;\n }\n for (const name of names) if (name !== 'default' && !IDENT.test(name)) return null;\n return [...names];\n}\n\n/** True for a module a route framework reads export by export. */\nexport function isRouteModule(names: string[]): boolean {\n return names.includes('default') && names.some((name) => ROUTE_EXPORTS.has(name));\n}\n\n/**\n * Whether a declaration line goes on to a second declarator: a comma outside\n * brackets after its initializer starts, or a line that ends in one. Strings\n * are blanked first so a comma inside one does not count.\n */\nfunction hasSecondDeclarator(declaration: string): boolean {\n const text = declaration\n .replace(/\\/\\/.*$/, '')\n .replace(/'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|`(?:[^`\\\\]|\\\\.)*`/g, '\"\"');\n let depth = 0;\n let initialized = false;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (ch === '(' || ch === '[' || ch === '{' || ch === '<') depth++;\n else if (ch === ')' || ch === ']' || ch === '}' || (ch === '>' && text[i - 1] !== '=')) depth = Math.max(0, depth - 1);\n else if (depth === 0 && ch === '=' && text[i + 1] !== '=' && text[i + 1] !== '>' && text[i - 1] !== '=') initialized = true;\n else if (depth === 0 && ch === ',' && initialized) return true;\n }\n return depth === 0 && /,\\s*$/.test(text);\n}\n","/**\n * Live overlay variants: switching without recompiling anything.\n *\n * In live mode the plugin serves every overridden script file as a small\n * dispatcher module. It imports each version of the file (the real one and\n * every variant's copy) under its own module id, `<file>?isotone=<id>`, and\n * re-exports one binding per name, chosen in the browser:\n *\n * - a component becomes a wrapper that renders the active version, so a\n * switch is a re-render;\n * - a value that is the same in every version passes through untouched;\n * - any other value (a hook, a function, a constant, a context) is fixed when\n * the page loads. A switch that changes one reloads the page, with the\n * selection already in the URL, because React cannot swap a hook under a\n * mounted component.\n *\n * Which variants a tab shows lives in that tab: in `?v=` when the reviewer\n * picked something there, otherwise in `.isotone/active.json`, which the\n * server injects into every page as the default.\n *\n * The browser code below is written as plain functions without outer\n * references, serialized with `Function.prototype.toString` into an inline\n * script and a virtual module. That keeps the host's React the one the\n * wrappers use, and keeps the functions testable as ordinary code.\n */\n\n/** What the store needs from the server, per page load. */\nexport interface LiveConfig {\n /** Variant groups in panel order, each a decision with its members. */\n groups: { id: string; members: string[] }[];\n /** The server's active set: `.isotone/active.json` when the page was served. */\n active: string[];\n /** The page may be server-rendered, so a pinned mismatch has to reach the server. */\n ssr: boolean;\n /** The variants endpoint, for the SSR sync. */\n endpoint: string;\n}\n\n/** The store's public surface, also used by the panel's overlay source. */\nexport interface LiveStore {\n readonly version: 1;\n /** The selection this tab shows. */\n readonly active: string[];\n /** The set the server rendered this page with, for hydration. Fixed for\n * the life of the page. */\n readonly server: string[];\n /** Whether this tab's selection comes from its URL. */\n readonly explicit: boolean;\n subscribe(listener: () => void): () => void;\n /** Register a loaded file: its versions (`null` for the real file) and\n * whether any of its exports is fixed at load. */\n register(key: string, ids: (string | null)[], pinned: boolean): void;\n /** Whether switching to `next` needs a page reload. */\n needsReload(next: string[]): boolean;\n /**\n * Switch this tab to `next` and write it to the URL. Returns true when the\n * page has to reload to show it; the caller reloads once the server knows\n * the new set (an SSR page renders from it).\n */\n select(next: string[]): boolean;\n /** The server's default changed. Tabs without their own pick follow it. */\n follow(next: string[]): void;\n reload(): void;\n}\n\n/** The query that marks one version of a file. The real file is `_base`, a\n * name no variant id can take. */\nexport const VERSION_QUERY = 'isotone';\nexport const BASE_VERSION = '_base';\nexport const LIVE_MODULE = 'virtual:isotone/live';\nexport const RESOLVED_LIVE_MODULE = '\\0isotone-live';\n/** Sent over Vite's HMR channel when the server's active set changes. */\nexport const ACTIVE_EVENT = 'isotone:active';\n\n/**\n * Create the tab's store on `win`, or return the one already there. Runs as\n * an inline `<head>` script before any module, so every dispatcher sees the\n * same selection while the page evaluates.\n */\nexport function liveStore(win: Window & { __isotoneLive?: LiveStore }, cfg: LiveConfig): LiveStore {\n if (win.__isotoneLive && win.__isotoneLive.version === 1) return win.__isotoneLive;\n const PARAM = 'v';\n const DEFAULT = 'default';\n const groups = cfg.groups;\n const byId = new Map(groups.map((group) => [group.id, group]));\n const listeners = new Set<() => void>();\n const files = new Map<string, { ids: (string | null)[]; pinned: boolean }>();\n const history = win.history;\n const replace = history.replaceState;\n const push = history.pushState;\n\n // A malformed escape anywhere in the query must not stop the page.\n const decode = (text: string): string => {\n try { return decodeURIComponent(text.replace(/\\+/g, ' ')); } catch { return text; }\n };\n const readParam = (search: string): string | null => {\n for (const part of search.replace(/^\\?/, '').split('&')) {\n const at = part.indexOf('=');\n const key = at < 0 ? part : part.slice(0, at);\n if (decode(key) === PARAM) return decode(at < 0 ? '' : part.slice(at + 1));\n }\n return null;\n };\n /** Our picks from `?v=` (null when it names none of our groups) and the\n * pairs that belong to someone else, kept when the param is rewritten. */\n const parse = (search: string): { picks: string[] | null; foreign: string[] } => {\n const raw = readParam(search);\n if (raw === null) return { picks: null, foreign: [] };\n const foreign: string[] = [];\n const picks = new Map<string, string>();\n for (const pair of raw.split(',')) {\n if (!pair) continue;\n const at = pair.indexOf(':');\n const group = at < 0 ? undefined : byId.get(pair.slice(0, at));\n const value = at < 0 ? '' : pair.slice(at + 1);\n if (group && (value === DEFAULT || group.members.includes(value))) picks.set(group.id, value);\n else foreign.push(pair);\n }\n if (picks.size === 0) return { picks: null, foreign };\n return { picks: [...picks.values()].filter((value) => value !== DEFAULT), foreign };\n };\n const search = (set: string[]): string => {\n const { foreign } = parse(win.location.search);\n const mine: string[] = [];\n for (const group of groups) {\n const pick = group.members.find((member) => set.includes(member));\n if (pick) mine.push(`${group.id}:${pick}`);\n }\n const value = [...foreign, ...mine].join(',');\n const kept = win.location.search.replace(/^\\?/, '').split('&').filter((part) => {\n if (!part) return false;\n const at = part.indexOf('=');\n return decode(at < 0 ? part : part.slice(0, at)) !== PARAM;\n });\n if (value) kept.push(`${PARAM}=${encodeURIComponent(value).replace(/%3A/gi, ':').replace(/%2C/gi, ',')}`);\n return kept.length ? `?${kept.join('&')}` : '';\n };\n const writeUrl = (set: string[]) => {\n const next = `${win.location.pathname}${search(set)}${win.location.hash}`;\n if (next !== `${win.location.pathname}${win.location.search}${win.location.hash}`) {\n replace.call(history, history.state, '', next);\n }\n };\n\n const fromUrl = parse(win.location.search).picks;\n const server = cfg.active.slice();\n let active = fromUrl ?? server.slice();\n let explicit = fromUrl !== null;\n let reloading = false;\n\n // The first id in the set that has this file, as the server's\n // resolveOverride decides it.\n const versionOf = (ids: (string | null)[], set: string[]): string | null => {\n for (const id of set) if (ids.includes(id)) return id;\n return null;\n };\n const needsReload = (from: string[], to: string[]): boolean => {\n for (const file of files.values()) {\n if (file.pinned && versionOf(file.ids, from) !== versionOf(file.ids, to)) return true;\n }\n return false;\n };\n const emit = () => { for (const listener of listeners) listener(); };\n const reload = () => { reloading = true; win.location.reload(); };\n\n // A server-rendered page rendered the server's set. When a link opens this\n // tab on another set and a fixed export differs, hydration would mix the\n // two: tell the server, then reload once. Only a fresh navigation does\n // this. A reload (the dev server's, or the reviewer's in a tab whose pick\n // another tab has since overridden) hydrates with a recoverable mismatch\n // instead, so two tabs never take the server back and forth.\n let syncing = false;\n const freshLoad = (): boolean => {\n try {\n // The timing entry can be missing while the document is still being\n // parsed; the legacy field is there from the start.\n const entry = win.performance.getEntriesByType('navigation')[0] as { type?: string } | undefined;\n if (entry?.type) return entry.type !== 'reload';\n return (win.performance as { navigation?: { type?: number } }).navigation?.type !== 1;\n } catch {\n return true;\n }\n };\n const syncServer = () => {\n if (syncing || !freshLoad()) return;\n syncing = true;\n const key = 'isotone:live-sync';\n const target = JSON.stringify(active);\n try {\n const last = JSON.parse(win.sessionStorage.getItem(key) ?? 'null') as { target: string; at: number } | null;\n if (last && last.target === target && Date.now() - last.at < 10_000) return;\n win.sessionStorage.setItem(key, JSON.stringify({ target, at: Date.now() }));\n } catch {\n return;\n }\n const send = (win as unknown as { __isotoneFetch?: typeof fetch }).__isotoneFetch ?? win.fetch.bind(win);\n send(`${cfg.endpoint}/active`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ active }),\n }).then((res) => { if (res.ok) reload(); }, () => {});\n };\n\n // A client-side navigation pushes a URL without `?v=`. Keep the tab's pick\n // in its address bar so a copied link still shows what the tab shows.\n const keep = (original: typeof push) => function (this: History, ...args: Parameters<typeof push>) {\n const result = original.apply(this, args);\n if (explicit && parse(win.location.search).picks === null) writeUrl(active);\n return result;\n };\n history.pushState = keep(push);\n history.replaceState = keep(replace);\n win.addEventListener('popstate', () => {\n if (explicit) writeUrl(active);\n });\n\n const store: LiveStore = {\n version: 1,\n get active() { return active; },\n get server() { return server; },\n get explicit() { return explicit; },\n subscribe(listener) {\n listeners.add(listener);\n return () => { listeners.delete(listener); };\n },\n register(key, ids, pinned) {\n files.set(key, { ids, pinned });\n // Only while the page first loads: a module that runs again later (a\n // hot update) is past hydration, and the server has moved on since.\n if (cfg.ssr && pinned && win.document.readyState !== 'complete' &&\n versionOf(ids, active) !== versionOf(ids, server)) {\n queueMicrotask(syncServer);\n }\n },\n needsReload(next) {\n return needsReload(active, next);\n },\n select(next) {\n if (reloading) return true;\n const reloadNeeded = needsReload(active, next);\n active = next.slice();\n explicit = next.length > 0;\n writeUrl(active);\n if (reloadNeeded) return true;\n emit();\n return false;\n },\n follow(next) {\n if (explicit || reloading) return;\n const same = next.length === active.length && next.every((id) => active.includes(id));\n if (same) return;\n const reloadNeeded = needsReload(active, next);\n active = next.slice();\n if (reloadNeeded) reload();\n else emit();\n },\n reload,\n };\n win.__isotoneLive = store;\n return store;\n}\n\n/** The React side of a dispatcher: one binding per export name. */\nexport interface LiveBinder {\n file(key: string, ids: (string | null)[], modules: Record<string, unknown>[], names: string[]): Record<string, unknown>;\n}\n\n/**\n * Build the binder over the host's React and the tab's store. Runs inside the\n * virtual module, which imports React the way the host's own code does.\n */\nexport function liveBinder(\n React: {\n createElement: (type: unknown, props: unknown) => unknown;\n forwardRef: (render: (props: unknown, ref: unknown) => unknown) => unknown;\n useSyncExternalStore: <T>(subscribe: (cb: () => void) => () => void, get: () => T, getServer?: () => T) => T;\n version: string;\n },\n store: LiveStore,\n): LiveBinder {\n const MEMO = Symbol.for('react.memo');\n const FORWARD = Symbol.for('react.forward_ref');\n const LAZY = Symbol.for('react.lazy');\n const refAsProp = Number.parseInt(React.version, 10) >= 19;\n const BUILTIN = new Set(['length', 'name', 'prototype', 'caller', 'arguments', 'displayName',\n '$$typeof', 'render', 'type', 'compare', '_payload', '_init']);\n\n const isClass = (value: unknown): boolean =>\n typeof value === 'function' && /^class[\\s{]/.test(Function.prototype.toString.call(value));\n const isComponent = (name: string, value: unknown, jsx: boolean): boolean => {\n if (typeof value === 'function') {\n const proto = (value as { prototype?: { isReactComponent?: unknown } }).prototype;\n if (proto?.isReactComponent) return true;\n if (isClass(value)) return false;\n if (name !== 'default') return /^[A-Z]/.test(name);\n const own = (value as { name?: string }).name ?? '';\n // `export default () => …` in a JSX file is a component in practice.\n return /^[A-Z]/.test(own) || (jsx && (own === '' || own === 'default'));\n }\n if (!value || typeof value !== 'object') return false;\n const tag = (value as { $$typeof?: unknown }).$$typeof;\n return tag === MEMO || tag === FORWARD || tag === LAZY;\n };\n\n return {\n file(key, ids, modules, names) {\n // The version a selection shows: the active variant that has this\n // file, else the real file, else (a file only variants add) the first.\n const pick = (set: string[]): number => {\n for (const id of set) {\n const hit = ids.indexOf(id);\n if (hit >= 0) return hit;\n }\n const base = ids.indexOf(null);\n return base >= 0 ? base : 0;\n };\n const out: Record<string, unknown> = {};\n const renders = new Map<string, (props: Record<string, unknown>, ref?: unknown) => unknown>();\n const jsx = /x$/.test(key);\n let pinned = false;\n for (const name of names) {\n const values = modules.map((mod) => mod[name]);\n const first = values[0];\n if (values.every((value) => value === first)) {\n out[name] = first;\n continue;\n }\n const defined = values.filter((value) => value !== undefined);\n if (defined.length > 0 && defined.every((value) => isComponent(name, value, jsx))) {\n const render = (props: Record<string, unknown>, ref?: unknown) => {\n const index = React.useSyncExternalStore(\n store.subscribe,\n () => pick(store.active),\n () => pick(store.server),\n );\n const component = values[index];\n if (component == null) return null;\n return React.createElement(component, ref == null ? props : { ...props, ref });\n };\n renders.set(name, render);\n const wrapper = (refAsProp ? (props: Record<string, unknown>) => render(props) : React.forwardRef(render as (p: unknown, r: unknown) => unknown)) as Record<string, unknown>;\n const label = name === 'default'\n ? (defined[0] as { displayName?: string; name?: string }).displayName ?? (defined[0] as { name?: string }).name ?? 'Variant'\n : name;\n if (typeof wrapper === 'function') Object.defineProperty(wrapper, 'name', { value: label });\n wrapper.displayName = label;\n // Compound components (`Card.Header`) read from the active version.\n const statics = new Set<string>();\n for (const value of defined) {\n for (const prop of Object.getOwnPropertyNames(value)) if (!BUILTIN.has(prop)) statics.add(prop);\n }\n for (const prop of statics) {\n if (prop in wrapper && !Object.getOwnPropertyDescriptor(wrapper, prop)?.configurable) continue;\n Object.defineProperty(wrapper, prop, {\n configurable: true,\n enumerable: true,\n get: () => (values[pick(store.active)] as Record<string, unknown> | undefined)?.[prop],\n });\n }\n out[name] = wrapper;\n continue;\n }\n pinned = true;\n out[name] = values[pick(store.active)];\n }\n store.register(key, ids, pinned);\n // The dispatcher's hoisted stand-ins render through this, for a module\n // in an import cycle that took a component before the dispatcher ran.\n Object.defineProperty(out, '__isotoneRender', {\n value: (name: string, props: Record<string, unknown>, ref?: unknown) => {\n const render = renders.get(name);\n if (render) return render(props, ref);\n const value = out[name];\n return typeof value === 'function' || (value && typeof value === 'object')\n ? React.createElement(value, ref == null ? props : { ...props, ref })\n : null;\n },\n });\n return out;\n },\n };\n}\n\n/** The inline `<head>` script that creates the tab's store. */\nexport function liveStoreScript(cfg: LiveConfig): string {\n return `(${liveStore.toString()})(window, ${safeJson(cfg)});`;\n}\n\n/** The virtual module the dispatchers import. `fallback` configures a store\n * for a page whose HTML did not pass through the plugin. */\nexport function liveRuntimeModule(fallback: LiveConfig): string {\n return [\n `import * as React from 'react';`,\n `const store = (${liveStore.toString()})(window, ${safeJson(fallback)});`,\n `export const live = (${liveBinder.toString()})(React, store);`,\n `if (import.meta.hot) import.meta.hot.on(${JSON.stringify(ACTIVE_EVENT)}, (data) => store.follow(data.active));`,\n '',\n ].join('\\n');\n}\n\n/**\n * The module served in place of a file with variants. `versions` lists the\n * real file (`null`) and each variant that has a copy, in a fixed order;\n * `names` is every export any version has.\n */\nexport function dispatcherModule(\n key: string,\n basename: string,\n versions: (string | null)[],\n names: string[],\n): string {\n const lines = [`import { live as __isotone } from ${JSON.stringify(LIVE_MODULE)};`];\n versions.forEach((id, i) => {\n const spec = `./${basename}?${VERSION_QUERY}=${id ?? BASE_VERSION}`;\n lines.push(`import * as __v${i} from ${JSON.stringify(spec)};`);\n });\n // Component-shaped names (and the default) are function declarations, so\n // they exist before this module runs: a module in an import cycle that\n // reads one at its top level (`memo(Picker)`) gets a stand-in that renders\n // the real binding. Each is reassigned to that binding once it is known.\n const hoisted = (name: string) => name === 'default' || /^[A-Z][\\w$]*$/.test(name);\n const local = (name: string) => (name === 'default' ? '__isotoneDefault' : name);\n for (const name of names.filter(hoisted)) {\n const head = name === 'default' ? 'export default function __isotoneDefault' : `export function ${name}`;\n lines.push(`${head}(props, ref) { return __f.__isotoneRender(${JSON.stringify(name)}, props, ref); }`);\n }\n lines.push(\n `const __f = __isotone.file(${JSON.stringify(key)}, ${JSON.stringify(versions)}, [${versions.map((_, i) => `__v${i}`).join(', ')}], ${JSON.stringify(names)});`,\n );\n names.forEach((name, i) => {\n if (hoisted(name)) {\n lines.push(`${local(name)} = __f[${JSON.stringify(name)}];`);\n return;\n }\n lines.push(`const __e${i} = __f[${JSON.stringify(name)}];`);\n lines.push(`export { __e${i} as ${name} };`);\n });\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction safeJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029/g, '\\\\u2029');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,YAAY,WAAW,cAAc,oBAAoB;AAClE,SAAS,SAAS,YAAY,MAAM,UAAU,eAAe;AAI7D;AAAA,EAKE;AAAA,OAGK;;;ACDP,IAAM,gBAAgB,oBAAI,IAAI;AAAA,EAC5B;AAAA,EAAU;AAAA,EAAU;AAAA,EAAgB;AAAA,EAAgB;AAAA,EAAW;AAAA,EAC/D;AAAA,EAAQ;AAAA,EAAU;AAAA,EAAoB;AAAA,EAAc;AAAA,EACpD;AAAA,EAAuB;AAAA,EAA6B;AACtD,CAAC;AAED,IAAM,QAAQ;AAEP,SAAS,YAAY,MAA+B;AACzD,QAAM,QAAQ,oBAAI,IAAY;AAC9B,QAAM,QAAQ,KAAK,MAAM,IAAI;AAC7B,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AAErC,UAAM,QAAQ,MAAM,CAAC,KAAK,IAAI,QAAQ,wBAAwB,EAAE;AAChE,QAAI,CAAC,KAAK,WAAW,QAAQ,EAAG;AAChC,UAAM,OAAO,KAAK,MAAM,SAAS,MAAM;AACvC,QAAI,SAAS,MAAM,CAAC,UAAU,KAAK,IA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K,MAAM,EAAE,CAAC;AAAA,EACvD;AACA,QAAM,UAAU,KAAK,MAAM,WAAW;AACtC,MAAI,SAAS,UAAU,QAAW;AAChC,WAAO,GAAG,KAAK,MAAM,GAAG,QAAQ,KAAK,CAAC,GAAG,MAAM,GAAG,KAAK,MAAM,QAAQ,KAAK,CAAC;AAAA,EAC7E;AACA,QAAM,OAAO,KAAK,MAAM,cAAc;AACtC,MAAI,MAAM,UAAU,QAAW;AAC7B,UAAM,KAAK,KAAK,QAAQ,KAAK,CAAC,EAAE;AAChC,WAAO,GAAG,KAAK,MAAM,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,KAAK,MAAM,EAAE,CAAC;AAAA,EACvD;AACA,SAAO,GAAG,IAAI,GAAG,MAAM;AACzB;AAYO,SAAS,gBAAgB,MAAsB;AACpD,MAAI,KAAK,SAAS,gBAAgB,EAAG,QAAO;AAC5C,QAAM,UACJ;AACF,QAAM,OAAO,KAAK,MAAM,cAAc;AACtC,MAAI,MAAM,UAAU,QAAW;AAC7B,UAAM,KAAK,KAAK,QAAQ,KAAK,CAAC,EAAE;AAChC,WAAO,GAAG,KAAK,MAAM,GAAG,EAAE,CAAC,GAAG,OAAO,GAAG,KAAK,MAAM,EAAE,CAAC;AAAA,EACxD;AACA,QAAM,OAAO,KAAK,MAAM,cAAc;AACtC,MAAI,MAAM,UAAU,QAAW;AAC7B,UAAM,KAAK,KAAK,QAAQ,KAAK,CAAC,EAAE;AAChC,WAAO,GAAG,KAAK,MAAM,GAAG,EAAE,CAAC,GAAG,OAAO,GAAG,KAAK,MAAM,EAAE,CAAC;AAAA,EACxD;AACA,SAAO;AACT;","names":["search","file"]}
|
|
1
|
+
{"version":3,"sources":["../src/vite/index.ts","../src/vite/live.ts"],"sourcesContent":["/**\n * Development-only notes, source variants and a self-contained panel for Vite.\n * Inject through the HTML response so SSR frameworks work too. The loader lives\n * in <head> and mounts after load, leaving the host's hydration and HMR alone.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\n\n// `normalizePath` is a plain function, so importing it as a value does not\n// pull vite's nominal `Plugin` type into the structural return type below.\nimport {\n type DevEnvironment,\n type EnvironmentModuleNode,\n type HmrContext,\n type HotUpdateOptions,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n} from 'vite';\n\nimport { ensureDirIgnored, ensureFileIgnored, notesResponse, NOTES_ENDPOINT } from '../store';\nimport type { RouteGateOptions } from '../core/index';\nimport type { IterationShortcut } from '../react/IterationPanel';\nimport type { IterationTheme } from '../react/theme';\nimport { readBundle } from '../standalone/bundle';\nimport { startUpdateCheck, UPDATE_ENDPOINT } from '../update';\nimport { autoUpdateNote, updateResponse } from '../update-note';\nimport { checkOrigin, readNodeJson, sendFailure } from '../server/http';\nimport { type OverlayVariant, overlayGroups, VARIANTS_ENDPOINT } from '../core/variants';\nimport {\n ACTIVE_FILE,\n listVariants,\n overrideSourcePath,\n readActive,\n readVariant,\n readVariants,\n resolveOverride,\n variantDir,\n variantsDir,\n variantsResponse,\n type VariantsStoreOptions,\n} from '../variants-store';\nimport { isRouteModule, scanExports } from './exports';\nimport {\n ACTIVE_EVENT,\n BASE_VERSION,\n dispatcherModule,\n LIVE_MODULE,\n type LiveConfig,\n liveRuntimeModule,\n liveStoreScript,\n RESOLVED_LIVE_MODULE,\n VERSION_QUERY,\n} from './live';\n\nexport interface IterationViteOptions {\n /** Inject the bundled panel. false keeps endpoints and variants for a manual mount. */\n panel?: boolean;\n /** Background npm notice, at most once a day. false disables the check;\n * 'note' also files an update note for your agent once per new version. */\n checkForUpdates?: boolean | 'note';\n /** Defaults to auto (page background); system follows the OS preference. */\n theme?: IterationTheme;\n /** Defaults to Cmd/Ctrl+Shift+Period; customize or disable with false. */\n shortcut?: IterationShortcut | false;\n /** Where notes persist. Relative paths resolve against Vite's `root` (the\n * directory of the app, whatever the shell's cwd), so a monorepo package\n * started from the workspace root still writes next to its own config.\n * Defaults to `.iteration-feedback.json`; git-ignored automatically via\n * `.git/info/exclude`, with the pattern anchored at the repository root. */\n file?: string;\n /** Route visibility rule (denylist/allowlist) for the injected panel. */\n rule?: RouteGateOptions;\n /** localStorage namespace override. */\n key?: string;\n /**\n * Overlay variants: alternative source files under `.isotone/variants/\n * <id>/<repo-relative path>` that `load` swaps in for the real ones while\n * the variant is active. On by default; `false` turns the whole feature\n * off (no endpoint, no watcher, no tab in the panel).\n */\n variants?:\n | false\n | {\n /** The project the manifests' file paths are relative to. Defaults to\n * Vite's root. A sibling dev server that aliases into another package\n * (a preview app rendering another package's source) points this at that\n * package so the same variants apply to both. Relative to Vite's root\n * or absolute. */\n root?: string;\n /** Where the variants live, relative to `root`. Default\n * `.isotone/variants`. */\n dir?: string;\n /** Keep the variants dir out of git via `.git/info/exclude`. Off by\n * default: the files are the reviewable artefact and commit with\n * the change they propose. */\n ignored?: boolean;\n /**\n * Switch variants in the browser instead of recompiling files. Every\n * version of an overridden script is loaded once, components switch\n * by re-rendering, and the selection is kept in the tab's `?v=`.\n * On by default in a React project on Vite 6 or later; `false` swaps\n * whole files over HMR as before.\n */\n live?: boolean;\n };\n}\n\n/**\n * What `iteration()` hands back.\n *\n * Only `name` is public, and that is deliberate. isotone is consumed as a\n * linked (`file:` / workspace) dependency, so TypeScript resolves the `vite`\n * import from *this* package's `node_modules`, not the consumer's. Two vite\n * type instances are nominally incompatible — rollup's plugin container\n * carries a private `_pluginContextMap` — and a single unassignable entry\n * poisons the overload resolution for the consumer's whole `plugins: []`\n * array, so every other plugin in it errors too. Vite's own `Plugin` requires\n * nothing but `name`, so a structural shape drops into any vite version's\n * `PluginOption` while the hooks below stay checked against the real vite\n * types inside this file.\n */\nexport interface IterationPlugin {\n name: string;\n /**\n * Declared with the loosest shape that still drops into vite's own\n * signature: a method, so its parameter is bivariant and vite's\n * `HmrContext` satisfies it, returning `void`, which any real return type\n * satisfies. The implementation returns vite's `ModuleNode[]`; naming that\n * type here would bring the nominal vite instance back.\n */\n handleHotUpdate?(ctx: { file: string }): void;\n}\n\nconst DEFAULT_FILE = '.iteration-feedback.json';\nconst INJECTED = new WeakSet<ServerResponse>();\nconst BUNDLE_PATH = '/@isotone/panel.js';\nconst MANIFEST = 'variant.json';\n\n/**\n * Import queries that hand the file to one of vite's own loaders (assets,\n * workers, inline HTML scripts). Those read the file from disk themselves\n * and shape the module around it; a `pre` load returning the override's\n * text in their place would break the module, so such requests are left to\n * them and show the real file.\n */\nconst SPECIAL_QUERY = /[?&](raw|url|inline|no-inline|worker|sharedworker|html-proxy)(?:[&=]|$)/;\n\n/** Element type comparisons, which a component wrapper would break. */\nconst COMPARES_TYPES = /\\.type\\s*[!=]==?|[!=]==?\\s*[\\w$.]+\\.type\\b/;\n\n/** The version a module id names (`?isotone=<id>`), or null for any other module. */\nfunction versionOfId(id: string | null): string | null {\n const at = id?.indexOf('?') ?? -1;\n if (!id || at < 0) return null;\n return new URLSearchParams(id.slice(at + 1)).get(VERSION_QUERY);\n}\n\n/** `dir` itself or a path below it; never a sibling whose name merely\n * starts the same (`src-old` under `src`). */\nfunction isInside(dir: string, path: string): boolean {\n const rel = relative(dir, path);\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n}\n\n/** The canonical form of a directory, or the path as given when it does not\n * exist yet (nothing to canonicalize; the comparison can only fail open). */\nfunction realDir(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nexport function iteration(options: IterationViteOptions = {}): IterationPlugin {\n let file = resolve(options.file ?? DEFAULT_FILE);\n let isDev = false;\n let isBuild = false;\n let isAsset: (file: string) => boolean = () => false;\n\n const variantsOptions = options.variants === false ? null : (options.variants ?? {});\n let vopts: VariantsStoreOptions = {\n root: resolve(variantsOptions?.root ?? '.'),\n ...(variantsOptions?.dir ? { dir: variantsOptions.dir } : {}),\n };\n let vDir = variantsDir(vopts);\n let activeFile = join(vopts.root, ACTIVE_FILE);\n\n // The active set, and which override (if any) answers each source path\n // under it. `resolveOverride` re-reads the manifests every call, and load()\n // asks once per module per page, so memoize per active set and drop the\n // memo whenever the set or anything under the variants dir changes.\n // `undefined` means not read yet: configureServer primes it, and a load()\n // that somehow runs first reads the file itself.\n let activeIds: string[] | undefined;\n const overrides = new Map<string, string | null>();\n // Real source paths activate() is reporting as changed right now. Their\n // hot update must go through, where an ordinary edit of an overridden\n // real file is dropped (see handleHotUpdate). Each path keeps the\n // environments that have already seen the swap: Vite 6 and later ask every\n // environment about one change, the browser first and the server after.\n const swapping = new Map<string, Set<string>>();\n\n // Live mode (see ./live.ts). Decided in configureServer, where the server's\n // environments show which Vite this is.\n let live = false;\n let hasReact = false;\n let ssrHost = false;\n let manifests: OverlayVariant[] | null = null;\n let byFile: Map<string, string[]> | null = null;\n let addedFiles: Map<string, string[]> | null = null;\n // The export names each dispatcher was written with, by real path. A\n // version whose names change needs a new dispatcher, which is a reload.\n const dispatched = new Map<string, string>();\n let reloadTimer: ReturnType<typeof setTimeout> | null = null;\n\n const readManifests = (): OverlayVariant[] => {\n manifests ??= readVariants(vopts);\n return manifests;\n };\n /** Variant ids that have a copy of each file, by forward-slash absolute path. */\n const versionsByFile = (): Map<string, string[]> => {\n if (byFile) return byFile;\n byFile = new Map();\n for (const variant of readManifests()) {\n for (const key of Object.keys(variant.files)) {\n const path = normalizePath(join(vopts.root, key));\n byFile.set(path, [...(byFile.get(path) ?? []), variant.id]);\n }\n }\n return byFile;\n };\n /** Files only variants have, keyed by their path without an extension. */\n const filesOnlyInVariants = (): Map<string, string[]> => {\n if (addedFiles) return addedFiles;\n addedFiles = new Map();\n for (const path of versionsByFile().keys()) {\n if (existsSync(path)) continue;\n const stem = path.replace(/\\.[cm]?[jt]sx?$/, '');\n addedFiles.set(stem, [...(addedFiles.get(stem) ?? []), path]);\n }\n return addedFiles;\n };\n const forgetManifests = () => {\n manifests = null;\n byFile = null;\n addedFiles = null;\n overrides.clear();\n };\n const groupsOf = (list: OverlayVariant[]): LiveConfig['groups'] =>\n overlayGroups(list).map((group) => ({ id: group.id, members: group.members.map((m) => m.id) }));\n const liveConfig = (): LiveConfig => ({\n groups: groupsOf(readManifests()),\n active: currentActive(),\n ssr: ssrHost,\n endpoint: VARIANTS_ENDPOINT,\n });\n const overrideOf = (id: string, path: string): string | null => {\n const key = normalizePath(relative(vopts.root, path));\n const manifest = readManifests().find((v) => v.id === id);\n if (!manifest || !Object.hasOwn(manifest.files, key)) return null;\n const file = join(variantDir(vopts, id), key);\n return existsSync(file) ? file : null;\n };\n\n /**\n * How to dispatch `path`, or null to serve it whole: a script with at\n * least one variant copy, whose every version lists its exports plainly,\n * and which is not a route module a framework reads export by export.\n */\n const dispatchPlan = (path: string): { key: string; versions: (string | null)[]; names: string[] } | null => {\n if (!/\\.[cm]?[jt]sx?$/.test(path)) return null;\n const ids = versionsByFile().get(path);\n if (!ids?.length) return null;\n const versions: (string | null)[] = [];\n const names = new Set<string>();\n const sources: [string | null, string][] = [];\n if (existsSync(path)) sources.push([null, path]);\n for (const id of ids) {\n const file = overrideOf(id, path);\n if (file) sources.push([id, file]);\n }\n for (const [id, file] of sources) {\n const code = readFileSync(file, 'utf8');\n // Code that compares element types (`child.type === Tab`) would see\n // the wrapper on one side and its own component on the other.\n if (COMPARES_TYPES.test(code)) return null;\n const found = scanExports(code);\n if (!found || isRouteModule(found)) return null;\n for (const name of found) names.add(name);\n versions.push(id);\n }\n // A file without exports runs for its side effects (an entry, a\n // registration); loading every version would run them all.\n if (versions.length === 0 || names.size === 0) return null;\n return { key: normalizePath(relative(vopts.root, path)), versions, names: [...names].sort() };\n };\n const namesChanged = (path: string): boolean => {\n const plan = dispatchPlan(path);\n return !plan || plan.names.join(',') !== dispatched.get(path);\n };\n let reloadPage: () => void = () => {};\n const swapWaiters = new Set<() => void>();\n\n /**\n * Which modules a file change updates in one environment (`null`: Vite 5,\n * which asks once for all of them). `undefined` lets Vite decide.\n */\n const hotModules = <M extends { id: string | null }>(\n changed: string,\n modulesOf: (file: string) => Iterable<M> | undefined,\n env: string | null,\n ): M[] | undefined => {\n if (!variantsOptions) return undefined;\n const client = env === null || env === 'client';\n // The module graph keys files by their forward-slash form, which is\n // what `join` produces on POSIX and not on Windows.\n if (isInside(vDir, changed)) {\n overrides.clear();\n const hit = overrideSourcePath(vopts, changed);\n // The manifest, or a file directly in the variants dir: nothing the\n // browser has loaded. The panel re-lists variants when it opens.\n if (!hit || hit.file === MANIFEST) return [];\n const source = normalizePath(join(vopts.root, hit.file));\n // Live: the copy has a module of its own; update just that one.\n if (live && client && dispatched.has(source)) {\n if (namesChanged(source)) {\n reloadPage();\n return [];\n }\n return [...(modulesOf(source) ?? [])].filter((m) => versionOfId(m.id) === hit.id);\n }\n if (!currentActive().includes(hit.id)) return [];\n // The browser holds the real file's URL, so the override's edit has\n // to be delivered as if the real file changed.\n return [...(modulesOf(source) ?? [])];\n }\n // A change activate() reported.\n const seen = swapping.get(changed);\n let swap = false;\n if (seen) {\n if (env === null) {\n swapping.delete(changed);\n swap = true;\n } else if (!seen.has(env)) {\n seen.add(env);\n swap = true;\n for (const check of [...swapWaiters]) check();\n }\n }\n const path = normalizePath(changed);\n if (live && client && dispatched.has(path)) {\n // The dispatcher already holds every version; the tab switched itself.\n if (swap) return [];\n if (namesChanged(path)) {\n reloadPage();\n return [];\n }\n return [...(modulesOf(path) ?? [])].filter((m) => versionOfId(m.id) === BASE_VERSION);\n }\n // Let Vite compute the swap's update as usual.\n if (swap) return undefined;\n // The real source of an overridden file: the browser is showing the\n // override, so there is nothing to update from this edit.\n if (overridable(changed) && overrideFor(currentActive(), changed)) return [];\n return undefined;\n };\n\n const currentActive = (): string[] => {\n // A build takes its set from the environment: `ISOTONE_VARIANT=a,b`.\n if (isBuild) return parseVariantList(process.env.ISOTONE_VARIANT);\n if (activeIds === undefined) activeIds = readActive(vopts);\n return activeIds;\n };\n\n const overrideFor = (active: string[], path: string): string | null => {\n if (active.length === 0) return null;\n // Sorted: the same set in another order answers the same for every path.\n const key = `${[...active].sort().join(',')}\\0${path}`;\n let hit = overrides.get(key);\n if (hit === undefined) {\n hit = resolveOverride(vopts, active, path);\n overrides.set(key, hit);\n }\n return hit;\n };\n\n /** Whether load() may swap `path` at all: a real file of the project the\n * variants describe, not a dependency and not an override itself. */\n // Module ids reach load() with forward slashes on every platform, while a\n // watcher path is native; splitting on either separator covers both.\n const overridable = (path: string): boolean =>\n isAbsolute(path) &&\n !path.split(/[\\\\/]/).includes('node_modules') &&\n isInside(vopts.root, path) &&\n !isInside(vDir, path) &&\n !isAsset(path);\n\n // `satisfies`, not an annotation: the hooks are checked against vite's\n // types, but the object keeps its own shape, so `handleHotUpdate` stays a\n // plain method and drops into the structural type below.\n const plugin = {\n name: 'iso:iteration',\n enforce: 'pre',\n configResolved(config: ResolvedConfig) {\n isDev = config.command === 'serve';\n isBuild = config.command === 'build';\n isAsset = config.assetsInclude;\n file = resolve(config.root, options.file ?? DEFAULT_FILE);\n // Vite hands load() realpath'd module ids but leaves `config.root` as\n // configured, so a root reached through a symlink would never contain\n // any module and no override would ever apply. Canonicalize it here.\n vopts = {\n root: realDir(resolve(config.root, variantsOptions?.root ?? '.')),\n ...(variantsOptions?.dir ? { dir: variantsOptions.dir } : {}),\n };\n vDir = variantsDir(vopts);\n activeFile = join(vopts.root, ACTIVE_FILE);\n hasReact = (config.plugins ?? []).some((p) => /react/i.test(p.name));\n ssrHost = config.appType !== 'spa' && config.appType !== 'mpa';\n forgetManifests();\n },\n async resolveId(source: string, importer: string | undefined, opts: { ssr?: boolean; isEntry?: boolean } = {}) {\n if (!variantsOptions) return null;\n if (source === LIVE_MODULE) return RESOLVED_LIVE_MODULE;\n if (!importer) return null;\n // A dispatcher's own imports, `./file.tsx?isotone=<id>`: resolved here\n // so a version of a file only variants have still has an id.\n const marker = source.indexOf(`?${VERSION_QUERY}=`);\n if (live && marker > 0 && source.startsWith('./')) {\n const dir = dirname(importer.replace(/[?#].*$/, ''));\n return normalizePath(resolve(dir, source.slice(0, marker))) + source.slice(marker);\n }\n // A file a variant adds, imported by variant code. Vite's resolver\n // cannot find it on disk, so answer with the path the variant gives it.\n const added = filesOnlyInVariants();\n if (added.size === 0 || source.startsWith('\\0')) return null;\n const bare = source.replace(/[?#].*$/, '');\n const leaf = bare.slice(bare.lastIndexOf('/') + 1).replace(/\\.[cm]?[jt]sx?$/, '');\n const candidates = [...added.entries()].filter(([stem]) =>\n stem.endsWith(`/${leaf}`) || stem.endsWith(`/${leaf}/index`));\n if (candidates.length === 0) return null;\n const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true });\n if (resolved) return resolved;\n const importerPath = importer.replace(/[?#].*$/, '');\n const target = bare.startsWith('.') ? normalizePath(resolve(dirname(importerPath), bare)).replace(/\\.[cm]?[jt]sx?$/, '') : null;\n // A relative import names the file exactly; an aliased one (`@/x/y`)\n // is matched on everything after its first segment.\n const tail = bare.split('/').slice(1).join('/').replace(/\\.[cm]?[jt]sx?$/, '');\n const hits = candidates.filter(([stem]) => target\n ? stem === target || stem === `${target}/index`\n : tail !== '' && (stem.endsWith(`/${tail}`) || stem.endsWith(`/${tail}/index`)));\n if (hits.length !== 1) return null;\n const paths = hits[0]?.[1] ?? [];\n return paths.length === 1 ? paths[0] : null;\n },\n load(id: string, opts?: { ssr?: boolean }) {\n if (!variantsOptions || SPECIAL_QUERY.test(id)) return null;\n if (id === RESOLVED_LIVE_MODULE) return { code: liveRuntimeModule(liveConfig()), map: null };\n // `?v=<hash>`, `?t=<timestamp>`, `?import`: vite's own request\n // decorations, never part of the path on disk.\n const path = id.replace(/[?#].*$/, '');\n if (!overridable(path)) return null;\n const query = id.slice(path.length).replace(/^\\?/, '').replace(/#.*$/, '');\n const version = live ? new URLSearchParams(query).get(VERSION_QUERY) : null;\n if (version !== null) {\n const from = version === BASE_VERSION ? (existsSync(path) ? path : null) : overrideOf(version, path);\n return { code: from ? readFileSync(from, 'utf8') : 'export {};\\n', map: null };\n }\n // The browser gets a dispatcher; a server render keeps the whole-file\n // swap, since the server cannot know which tab it renders for.\n if (live && !opts?.ssr && query === '') {\n const plan = dispatchPlan(path);\n if (plan) {\n dispatched.set(path, plan.names.join(','));\n const name = path.slice(path.lastIndexOf('/') + 1);\n return { code: dispatcherModule(plan.key, name, plan.versions, plan.names), map: null };\n }\n }\n const override = overrideFor(currentActive(), path);\n if (!override) return null;\n return { code: readFileSync(override, 'utf8'), map: null };\n },\n // Vite 6 and later call this once per environment and skip\n // handleHotUpdate; Vite 5 only knows handleHotUpdate.\n hotUpdate(this: { environment: DevEnvironment }, ctx: HotUpdateOptions): EnvironmentModuleNode[] | undefined {\n const env = this.environment;\n return hotModules(ctx.file, (f) => env.moduleGraph.getModulesByFile(f), env.name);\n },\n handleHotUpdate(ctx: HmrContext) {\n const { server } = ctx;\n return hotModules(ctx.file, (f) => server.moduleGraph.getModulesByFile(f), null) as HmrContext['modules'] | undefined;\n },\n configureServer(server) {\n if (!isDev) return;\n // Here, not at construction: a production build should not touch .git.\n ensureFileIgnored(file);\n\n // Say where the notes go, after Vite's own banner so it is not buried\n // under it. Portable setups fail quietly otherwise: a reviewer writes\n // notes and the agent looks in the wrong directory.\n server.httpServer?.once('listening', () => {\n const shown = relative(server.config.root, file) || file;\n server.config.logger.info(\n ` isotone notes → ${shown} (${NOTES_ENDPOINT})`,\n );\n if (variantsOptions && existsSync(vDir)) {\n const shownDir = relative(server.config.root, vDir) || vDir;\n const n = listVariants(vopts).length;\n server.config.logger.info(\n ` isotone variants → ${shownDir} (${n} variant${n === 1 ? '' : 's'})`,\n );\n }\n });\n\n const guardOrigin = (req: IncomingMessage, res: ServerResponse): boolean => {\n try { checkOrigin(req.headers.origin, req.headers.host ?? ''); return true; }\n catch (error) { sendFailure(res, error); return false; }\n };\n\n const updates = startUpdateCheck(server.config.root, options.checkForUpdates !== false);\n server.httpServer?.once('close', updates.dispose);\n if (options.checkForUpdates === 'note') {\n void updates.ready.then(() => autoUpdateNote(file, updates.getSnapshot())).catch(() => {});\n }\n // GET reads the cached check; POST asks for the update note, which the\n // server builds from that check rather than from the request.\n server.middlewares.use(UPDATE_ENDPOINT, (req, res) => {\n if (!guardOrigin(req, res)) return;\n const method = req.method ?? '';\n (method === 'POST' ? readNodeJson(req) : Promise.resolve(undefined)).then((body) => {\n answer(res, () => updateResponse(file, updates.getSnapshot(), { method, body }));\n }).catch((error) => sendFailure(res, error));\n });\n\n // Notes endpoint → local file.\n server.middlewares.use(NOTES_ENDPOINT, (req, res, next) => {\n if (!guardOrigin(req, res)) return;\n const method = req.method ?? '';\n if (method !== 'GET' && method !== 'POST' && method !== 'DELETE') {\n next();\n return;\n }\n (method === 'POST' ? readNodeJson(req) : Promise.resolve(undefined)).then((body) => {\n answer(res, () => notesResponse(file, { method, url: req.url, body }));\n }).catch((error) => sendFailure(res, error));\n });\n\n if (variantsOptions) {\n // Read the pointer now, before anything can rewrite it: activate()\n // diffs the previous set against the new one, and the endpoint has\n // already written the file by the time it runs, so a lazy first read\n // would see the new set twice and switch nothing.\n activeIds = readActive(vopts);\n\n // Live switching needs the host's React for the wrappers and Vite 6's\n // per-environment hot updates, so the server render keeps its swap\n // while the browser's dispatchers are left alone.\n live = (variantsOptions.live ?? hasReact) && server.environments !== undefined;\n // A server render holds modules of its own, so a change to what a\n // variant covers has to reach those too or the HTML goes stale.\n const graphs = () => server.environments\n ? Object.values(server.environments).map((env) => env.moduleGraph as unknown as typeof server.moduleGraph)\n : [server.moduleGraph];\n // Files a manifest named before it changed: one that left the variant\n // has no entry to be found by afterwards.\n const covered = new Set<string>();\n const signature = () => JSON.stringify(readManifests().map((v) => [v.id, v.group ?? '', Object.keys(v.files).sort()]));\n let listed = signature();\n // A dispatcher is written for one set of versions and names. When\n // either changes, the browser needs new dispatchers, which a hot\n // update cannot deliver: drop them and reload the page once.\n reloadPage = () => {\n if (reloadTimer) clearTimeout(reloadTimer);\n reloadTimer = setTimeout(() => {\n reloadTimer = null;\n // Files that were dispatchers, and files that have just gained a\n // variant and still hold their plain transform.\n const paths = new Set([...dispatched.keys(), ...versionsByFile().keys(), ...covered]);\n for (const graph of graphs()) {\n for (const path of paths) {\n for (const mod of graph.getModulesByFile(path) ?? []) graph.invalidateModule(mod as never);\n }\n const runtime = graph.getModuleById(RESOLVED_LIVE_MODULE);\n if (runtime) graph.invalidateModule(runtime as never);\n }\n covered.clear();\n dispatched.clear();\n server.ws.send({ type: 'full-reload', path: '*' });\n }, 50);\n };\n\n /**\n * Switch the browser to the set `next` without reloading the page.\n * Every file overridden by a variant that entered or left the set\n * is reported to Vite as if it had just been edited on disk: Vite\n * invalidates it, runs load() again (which now answers with the\n * other content) and sends the same hot update an editor save\n * would, so React Fast Refresh swaps the component in place and the\n * reviewer keeps their scroll, their form state and the open panel.\n * Variants in both sets are untouched, so switching one group leaves\n * the others' components alone. Files the browser has not loaded\n * are skipped; Vite decides on its own when a module cannot be\n * hot-swapped and falls back to a reload for that one, exactly as\n * it would for a hand edit.\n */\n const activate = (next: string[], removedFiles: string[] = []): Promise<void> => {\n const prev = currentActive();\n const changed = [\n ...prev.filter((id) => !next.includes(id)),\n ...next.filter((id) => !prev.includes(id)),\n ];\n if (changed.length === 0 && removedFiles.length === 0) return Promise.resolve();\n activeIds = next;\n overrides.clear();\n const sources = new Set<string>(removedFiles.map((file) => join(vopts.root, file)));\n for (const id of changed) {\n const manifest = readVariant(vopts, id);\n for (const key of Object.keys(manifest?.files ?? {})) {\n sources.add(join(vopts.root, key));\n }\n }\n const emitted: string[] = [];\n for (const source of sources) {\n const loaded = server.moduleGraph.getModulesByFile(normalizePath(source));\n if (!loaded || loaded.size === 0) continue;\n swapping.set(source, new Set());\n emitted.push(source);\n server.watcher.emit('change', source);\n }\n // Live tabs switch themselves; this tells the ones still on the\n // server's default to follow it, once a reload would render it.\n const settled = serverSawSwap(emitted);\n if (live) void settled.then(() => server.ws.send({ type: 'custom', event: ACTIVE_EVENT, data: { active: next } }));\n return settled;\n };\n\n /**\n * Resolves once every server environment (an SSR render) has taken\n * the swap of `files`, or after a second. A tab that reloads right\n * after its POST would otherwise be rendered from the old files and\n * fail to hydrate.\n */\n const serverSawSwap = (files: string[]): Promise<void> => {\n const envs = Object.keys(server.environments ?? {}).filter((name) => name !== 'client');\n if (!live || files.length === 0 || envs.length === 0) return Promise.resolve();\n return new Promise<void>((done) => {\n const check = () => {\n const seen = files.every((file) => {\n const by = swapping.get(file);\n return !by || envs.every((env) => by.has(env));\n });\n if (!seen) return;\n finish();\n };\n const timer = setTimeout(() => finish(), 1000);\n const finish = () => {\n clearTimeout(timer);\n swapWaiters.delete(check);\n // The update itself goes out after the hook that marked it.\n setTimeout(done, 30);\n };\n swapWaiters.add(check);\n check();\n });\n };\n\n // The exclude helpers canonicalize through the filesystem, so the\n // active file's directory has to exist before its pattern can land;\n // the panel's first POST would otherwise leave an untracked file.\n mkdirSync(dirname(activeFile), { recursive: true });\n ensureFileIgnored(activeFile);\n if (variantsOptions.ignored) {\n mkdirSync(vDir, { recursive: true });\n ensureDirIgnored(vDir);\n }\n\n server.middlewares.use(VARIANTS_ENDPOINT, (req, res, next) => {\n if (!guardOrigin(req, res)) return;\n const method = req.method ?? '';\n if (method !== 'GET' && method !== 'POST') {\n next();\n return;\n }\n // A POST switches every open tab of this dev server to another set\n // of files. A cross-site page can fire a `no-cors` form post at\n // localhost, but only with a text/plain or form content type; a\n // JSON content type needs a preflight, which vite's CORS does not\n // grant to an unknown origin. So the header is the gate.\n if (method === 'POST' && !isJsonRequest(req)) {\n res.statusCode = 415;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.end(JSON.stringify({ error: 'content-type must be application/json' }));\n return;\n }\n (method === 'POST' ? readNodeJson(req) : Promise.resolve(undefined)).then((body) => {\n // connect strips the mount from `req.url`, which is the shape\n // variantsResponse routes on (\"/\", \"/active?...\").\n let result: ReturnType<typeof variantsResponse>;\n try {\n result = variantsResponse(vopts, { method, url: req.url, body });\n } catch (error) {\n sendFailure(res, error);\n return;\n }\n const send = () => { answer(res, () => result); };\n if (result.status === 200 && method === 'POST') {\n const updated = result.body as { active: string[]; changedFiles?: string[] };\n // Answer once the switch is in place, so the panel can reload\n // straight into it.\n activate(updated.active, updated.changedFiles).then(send, send);\n } else {\n send();\n }\n }).catch((error) => sendFailure(res, error));\n });\n\n // The CLI's `variant use` writes the active file with no request to\n // this server, and an agent edits overrides in place: both have to\n // reach the browser. The active file may not exist yet, so watch its\n // directory; chokidar reports files that appear later.\n server.watcher.add(dirname(activeFile));\n server.watcher.add(vDir);\n server.watcher.on('all', (_event: string, changed: string) => {\n const path = resolve(changed);\n if (path === activeFile) {\n void activate(readActive(vopts));\n } else if (isInside(vDir, path)) {\n // Covers adds and unlinks, which handleHotUpdate never sees.\n for (const variant of manifests ?? []) {\n for (const key of Object.keys(variant.files)) covered.add(normalizePath(join(vopts.root, key)));\n }\n forgetManifests();\n // A variant deleted by hand leaves its id in the file. Pages are\n // told this set, and a pick posts it back, so it has to go here.\n const stillActive = readActive(vopts);\n const activeChanged = stillActive.join() !== currentActive().join();\n if (activeChanged) void activate(stillActive);\n const now = signature();\n if (now !== listed) {\n listed = now;\n if (live || activeChanged || stillActive.length > 0) reloadPage();\n }\n }\n });\n }\n\n // The tab's variant store has to exist before the app's modules run,\n // so it rides in the document itself, with the server's current set.\n const liveScript = () => (live ? liveStoreScript(liveConfig()) : null);\n if (options.panel === false) {\n if (!live) return;\n server.middlewares.use((req, res, next) => {\n if (!(req.headers.accept ?? '').includes('text/html')) {\n next();\n return;\n }\n delete req.headers['if-none-match'];\n delete req.headers['if-modified-since'];\n injectHtmlResponse(res, null, liveScript);\n next();\n });\n return;\n }\n\n // A self-contained bundle keeps the panel out of the host's dependency\n // graph and works in React, Vue, Svelte and plain Vite apps alike.\n server.middlewares.use(BUNDLE_PATH, (_req, res) => {\n res.setHeader('content-type', 'text/javascript; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(readBundle());\n });\n const mountCode = mountModuleSource(options.rule ?? {}, options.key ?? '', variantsOptions !== null, options.shortcut, options.theme);\n\n server.middlewares.use((req, res, next) => {\n // Only navigations: buffering every response to look for </body>\n // would tax each of the hundreds of module requests a dev page makes.\n if (!(req.headers.accept ?? '').includes('text/html')) {\n next();\n return;\n }\n // Vite's ETag is computed from the document before the mount script\n // is appended, so a conditional request validates against the wrong\n // bytes: a browser holding a copy from before this plugin was added\n // gets 304 and never sees the panel. Ask for the full document.\n delete req.headers['if-none-match'];\n delete req.headers['if-modified-since'];\n injectHtmlResponse(res, mountCode, liveScript);\n next();\n });\n },\n } satisfies Plugin;\n\n return plugin;\n}\n\n/** `ISOTONE_VARIANT=a, b` → `['a', 'b']`; unset or blank → `[]`. */\nfunction parseVariantList(raw: string | undefined): string[] {\n return (raw ?? '')\n .split(',')\n .map((id) => id.trim())\n .filter(Boolean);\n}\n\n/** Whether the request declares a JSON body (`application/json`, with or\n * without a charset parameter). */\nfunction isJsonRequest(req: IncomingMessage): boolean {\n const type = req.headers['content-type'];\n return typeof type === 'string' && type.toLowerCase().includes('application/json');\n}\n\n/**\n * Write a store response, or a 500 when the store throws. A store that\n * cannot write (permissions, a read-only mount) must still answer, or the\n * panel's request hangs and the reviewer sees nothing; a 500 sends a note\n * to the localStorage fallback. Returns the response so the caller can act\n * on a success, `null` on a throw.\n */\nfunction answer(\n res: ServerResponse,\n respond: () => { status: number; headers: Record<string, string>; body: unknown },\n): { status: number; body: unknown } | null {\n try {\n const { status, headers, body } = respond();\n res.statusCode = status;\n for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);\n res.end(JSON.stringify(body));\n return { status, body };\n } catch (cause) {\n sendFailure(res, cause);\n return null;\n }\n}\n\n/** Load after the host has mounted, without importing its React or HMR runtime. */\nfunction mountModuleSource(rule: RouteGateOptions, key: string, variants: boolean, shortcut?: IterationShortcut | false, theme?: IterationTheme): string {\n const config = JSON.stringify({ endpoint: NOTES_ENDPOINT, updateEndpoint: UPDATE_ENDPOINT, key, shortcut, theme, rule, ...(variants ? { variants: 'overlay' } : {}) }).replace(/</g, '\\\\u003c');\n return `\n const start = () => {\n const mount = () => window.__isotone.mount(${config});\n if (window.__isotone) return mount();\n const script = document.createElement('script');\n script.src = ${JSON.stringify(BUNDLE_PATH)};\n script.onload = mount;\n document.head.appendChild(script);\n };\n if (document.readyState === 'complete') start();\n else window.addEventListener('load', start, { once: true });\n `;\n}\n\nfunction injectHtmlResponse(res: ServerResponse, code: string | null, head: () => string | null = () => null): void {\n if (INJECTED.has(res)) return;\n INJECTED.add(res);\n\n // Buffer the whole document and send it once from `end`. Passing chunks\n // through as they arrive would mean re-sending the document to inject, and\n // a streamed SSR body (React Router, Next) is chunked anyway, so nothing is\n // lost by waiting for `</body>`. Only navigations reach here (see the\n // `accept` check above), so this never buffers an SSE or module response.\n const originalWrite = res.write.bind(res);\n const originalEnd = res.end.bind(res);\n const originalSetHeader = res.setHeader.bind(res);\n const originalWriteHead = res.writeHead.bind(res);\n const chunks: Buffer[] = [];\n let buffering = true;\n\n // Web-stream adapters hand `res.write` a Uint8Array, which is neither a\n // string nor a Buffer; `chunk.toString('utf8')` on one yields a\n // comma-separated byte list, so wrap it instead of stringifying it.\n const toBuffer = (chunk: unknown): Buffer | null => {\n if (typeof chunk === 'string') return Buffer.from(chunk, 'utf8');\n if (Buffer.isBuffer(chunk)) return chunk;\n if (chunk instanceof Uint8Array) {\n return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n }\n return null;\n };\n\n // The injected script changes the bytes, so an upstream `Content-Length`\n // (Vite's `send`, a framework's own header) would truncate the document at\n // the original size, and an upstream `ETag` would describe a document the\n // browser never receives. Drop both; the response goes chunked and the\n // browser revalidates every time, which a dev page should anyway.\n const STRIPPED = new Set(['content-length', 'etag', 'last-modified']);\n const isLength = (name: string) => STRIPPED.has(name.toLowerCase());\n res.setHeader = ((name: string, value: number | string | readonly string[]) =>\n isLength(name) ? res : originalSetHeader(name, value)) as ServerResponse['setHeader'];\n res.writeHead = ((status: number, ...rest: unknown[]) => {\n const headers = rest[rest.length - 1];\n if (Array.isArray(headers)) {\n rest[rest.length - 1] = headers.filter((entry, i, all) => {\n // Either [[k, v], ...] or a flat [k, v, k, v, ...] list.\n if (Array.isArray(entry)) return !isLength(String(entry[0]));\n const key = i % 2 === 0 ? entry : all[i - 1];\n return !isLength(String(key));\n });\n } else if (headers && typeof headers === 'object') {\n for (const key of Object.keys(headers)) {\n if (isLength(key)) delete (headers as Record<string, unknown>)[key];\n }\n }\n return originalWriteHead(status, ...(rest as []));\n }) as unknown as ServerResponse['writeHead'];\n\n res.write = ((chunk: unknown, ...rest: unknown[]) => {\n if (!buffering) return originalWrite(chunk as string, ...(rest as []));\n const buf = toBuffer(chunk);\n if (buf) chunks.push(buf);\n const cb = rest.find((r): r is () => void => typeof r === 'function');\n if (cb) queueMicrotask(cb);\n return true;\n }) as unknown as ServerResponse['write'];\n\n res.end = ((...args: unknown[]) => {\n const buf = toBuffer(args[0]);\n if (buf) chunks.push(buf);\n const cb = args.find((a): a is () => void => typeof a === 'function');\n buffering = false;\n const body = Buffer.concat(chunks).toString('utf8');\n if (body.includes('<html') && (body.includes('<head') || body.includes('</body>'))) {\n const script = code === null ? '' : `<script type=\"module\" data-isotone-inject>${code}</script>`;\n // Classic, not a module: it runs during parsing, before any module.\n const store = head();\n const early = store ? `<script data-isotone-live>${store.replace(/<\\/script/gi, '<\\\\/script')}</script>` : '';\n if (!res.headersSent) originalSetHeader('Cache-Control', 'no-store');\n return originalEnd(withNativeFetch(injectIntoHead(body, `${early}${script}`)), cb);\n }\n return originalEnd(Buffer.concat(chunks), cb);\n }) as unknown as ServerResponse['end'];\n}\n\n/**\n * Put the mount loader script in `<head>`, after the opening head tag. React\n * never hydrates head contents it receives as part of a server document —\n * `<head>` is a special host that React replaces wholesale, unlike `<body>`,\n * and any stray script inside it is inert for React — so this cannot trip the\n * \"script tag while rendering React component\" warning or the hydration\n * discard that follows it in a whole-document React Router app. Falls back to\n * just before `</head>`, then just before `</body>` for a fragment without a\n * head, then appends, matching what `withNativeFetch` does below.\n */\nfunction injectIntoHead(html: string, script: string): string {\n const head = html.match(/<head[^>]*>/i);\n if (head?.index !== undefined) {\n const at = head.index + head[0].length;\n return `${html.slice(0, at)}${script}${html.slice(at)}`;\n }\n const headEnd = html.match(/<\\/head>/i);\n if (headEnd?.index !== undefined) {\n return `${html.slice(0, headEnd.index)}${script}${html.slice(headEnd.index)}`;\n }\n const body = html.match(/<body[^>]*>/i);\n if (body?.index !== undefined) {\n const at = body.index + body[0].length;\n return `${html.slice(0, at)}${script}${html.slice(at)}`;\n }\n return `${html}${script}`;\n}\n\n/**\n * A one-line script as early in the document as possible that keeps a\n * reference to the browser's own `fetch`. Apps replace `window.fetch` for\n * their own reasons — a preview app answering its backend calls, a mock\n * layer, an auth shim — and a stub that answers 404 to anything it does not\n * know would swallow the panel's saves; the store then falls back to\n * localStorage and the reviewer's notes look lost. The store prefers this\n * reference when it exists. Placed right after `<head>` (or `<body>` when\n * there is no head) so it runs before any app module.\n */\nexport function withNativeFetch(html: string): string {\n if (html.includes('__isotoneFetch')) return html;\n const capture =\n '<script data-isotone-native>window.__isotoneFetch=window.fetch.bind(window)</script>';\n const head = html.match(/<head[^>]*>/i);\n if (head?.index !== undefined) {\n const at = head.index + head[0].length;\n return `${html.slice(0, at)}${capture}${html.slice(at)}`;\n }\n const body = html.match(/<body[^>]*>/i);\n if (body?.index !== undefined) {\n const at = body.index + body[0].length;\n return `${html.slice(0, at)}${capture}${html.slice(at)}`;\n }\n return html;\n}\n","/**\n * Live overlay variants: switching without recompiling anything.\n *\n * In live mode the plugin serves every overridden script file as a small\n * dispatcher module. It imports each version of the file (the real one and\n * every variant's copy) under its own module id, `<file>?isotone=<id>`, and\n * re-exports one binding per name, chosen in the browser:\n *\n * - a component becomes a wrapper that renders the active version, so a\n * switch is a re-render;\n * - a value that is the same in every version passes through untouched;\n * - any other value (a hook, a function, a constant, a context) is fixed when\n * the page loads. A switch that changes one reloads the page, with the\n * selection already in the URL, because React cannot swap a hook under a\n * mounted component.\n *\n * Which variants a tab shows lives in that tab: in `?v=` when the reviewer\n * picked something there, otherwise in `.isotone/active.json`, which the\n * server injects into every page as the default.\n *\n * The browser code below is written as plain functions without outer\n * references, serialized with `Function.prototype.toString` into an inline\n * script and a virtual module. That keeps the host's React the one the\n * wrappers use, and keeps the functions testable as ordinary code.\n */\n\n/** What the store needs from the server, per page load. */\nexport interface LiveConfig {\n /** Variant groups in panel order, each a decision with its members. */\n groups: { id: string; members: string[] }[];\n /** The server's active set: `.isotone/active.json` when the page was served. */\n active: string[];\n /** The page may be server-rendered, so a pinned mismatch has to reach the server. */\n ssr: boolean;\n /** The variants endpoint, for the SSR sync. */\n endpoint: string;\n}\n\n/** The store's public surface, also used by the panel's overlay source. */\nexport interface LiveStore {\n readonly version: 1;\n /** The selection this tab shows. */\n readonly active: string[];\n /** The set the server rendered this page with, for hydration. Fixed for\n * the life of the page. */\n readonly server: string[];\n /** Whether this tab's selection comes from its URL. */\n readonly explicit: boolean;\n subscribe(listener: () => void): () => void;\n /** Register a loaded file: its versions (`null` for the real file) and\n * whether any of its exports is fixed at load. */\n register(key: string, ids: (string | null)[], pinned: boolean): void;\n /** Whether switching to `next` needs a page reload. */\n needsReload(next: string[]): boolean;\n /**\n * Switch this tab to `next` and write it to the URL. Returns true when the\n * page has to reload to show it; the caller reloads once the server knows\n * the new set (an SSR page renders from it).\n */\n select(next: string[]): boolean;\n /** The server's default changed. Tabs without their own pick follow it. */\n follow(next: string[]): void;\n reload(): void;\n}\n\n/** The query that marks one version of a file. The real file is `_base`, a\n * name no variant id can take. */\nexport const VERSION_QUERY = 'isotone';\nexport const BASE_VERSION = '_base';\nexport const LIVE_MODULE = 'virtual:isotone/live';\nexport const RESOLVED_LIVE_MODULE = '\\0isotone-live';\n/** Sent over Vite's HMR channel when the server's active set changes. */\nexport const ACTIVE_EVENT = 'isotone:active';\n\n/**\n * Create the tab's store on `win`, or return the one already there. Runs as\n * an inline `<head>` script before any module, so every dispatcher sees the\n * same selection while the page evaluates.\n */\nexport function liveStore(win: Window & { __isotoneLive?: LiveStore }, cfg: LiveConfig): LiveStore {\n if (win.__isotoneLive && win.__isotoneLive.version === 1) return win.__isotoneLive;\n const PARAM = 'v';\n const DEFAULT = 'default';\n const groups = cfg.groups;\n const byId = new Map(groups.map((group) => [group.id, group]));\n const listeners = new Set<() => void>();\n const files = new Map<string, { ids: (string | null)[]; pinned: boolean }>();\n const history = win.history;\n const replace = history.replaceState;\n const push = history.pushState;\n\n // A malformed escape anywhere in the query must not stop the page.\n const decode = (text: string): string => {\n try { return decodeURIComponent(text.replace(/\\+/g, ' ')); } catch { return text; }\n };\n const readParam = (search: string): string | null => {\n for (const part of search.replace(/^\\?/, '').split('&')) {\n const at = part.indexOf('=');\n const key = at < 0 ? part : part.slice(0, at);\n if (decode(key) === PARAM) return decode(at < 0 ? '' : part.slice(at + 1));\n }\n return null;\n };\n /** Our picks from `?v=` (null when it names none of our groups) and the\n * pairs that belong to someone else, kept when the param is rewritten. */\n const parse = (search: string): { picks: string[] | null; foreign: string[] } => {\n const raw = readParam(search);\n if (raw === null) return { picks: null, foreign: [] };\n const foreign: string[] = [];\n const picks = new Map<string, string>();\n for (const pair of raw.split(',')) {\n if (!pair) continue;\n const at = pair.indexOf(':');\n const group = at < 0 ? undefined : byId.get(pair.slice(0, at));\n const value = at < 0 ? '' : pair.slice(at + 1);\n if (group && (value === DEFAULT || group.members.includes(value))) picks.set(group.id, value);\n else foreign.push(pair);\n }\n if (picks.size === 0) return { picks: null, foreign };\n return { picks: [...picks.values()].filter((value) => value !== DEFAULT), foreign };\n };\n const search = (set: string[]): string => {\n const { foreign } = parse(win.location.search);\n const mine: string[] = [];\n for (const group of groups) {\n const pick = group.members.find((member) => set.includes(member));\n if (pick) mine.push(`${group.id}:${pick}`);\n }\n const value = [...foreign, ...mine].join(',');\n const kept = win.location.search.replace(/^\\?/, '').split('&').filter((part) => {\n if (!part) return false;\n const at = part.indexOf('=');\n return decode(at < 0 ? part : part.slice(0, at)) !== PARAM;\n });\n if (value) kept.push(`${PARAM}=${encodeURIComponent(value).replace(/%3A/gi, ':').replace(/%2C/gi, ',')}`);\n return kept.length ? `?${kept.join('&')}` : '';\n };\n const writeUrl = (set: string[]) => {\n const next = `${win.location.pathname}${search(set)}${win.location.hash}`;\n if (next !== `${win.location.pathname}${win.location.search}${win.location.hash}`) {\n replace.call(history, history.state, '', next);\n }\n };\n\n const fromUrl = parse(win.location.search).picks;\n const server = cfg.active.slice();\n let active = fromUrl ?? server.slice();\n let explicit = fromUrl !== null;\n let reloading = false;\n\n // The first id in the set that has this file, as the server's\n // resolveOverride decides it.\n const versionOf = (ids: (string | null)[], set: string[]): string | null => {\n for (const id of set) if (ids.includes(id)) return id;\n return null;\n };\n const needsReload = (from: string[], to: string[]): boolean => {\n for (const file of files.values()) {\n if (file.pinned && versionOf(file.ids, from) !== versionOf(file.ids, to)) return true;\n }\n return false;\n };\n const emit = () => { for (const listener of listeners) listener(); };\n const reload = () => { reloading = true; win.location.reload(); };\n\n // A server-rendered page rendered the server's set. When a link opens this\n // tab on another set and a fixed export differs, hydration would mix the\n // two: tell the server, then reload once. Only a fresh navigation does\n // this. A reload (the dev server's, or the reviewer's in a tab whose pick\n // another tab has since overridden) hydrates with a recoverable mismatch\n // instead, so two tabs never take the server back and forth.\n let syncing = false;\n const freshLoad = (): boolean => {\n try {\n // The timing entry can be missing while the document is still being\n // parsed; the legacy field is there from the start.\n const entry = win.performance.getEntriesByType('navigation')[0] as { type?: string } | undefined;\n if (entry?.type) return entry.type !== 'reload';\n return (win.performance as { navigation?: { type?: number } }).navigation?.type !== 1;\n } catch {\n return true;\n }\n };\n const syncServer = () => {\n if (syncing || !freshLoad()) return;\n syncing = true;\n const key = 'isotone:live-sync';\n const target = JSON.stringify(active);\n try {\n const last = JSON.parse(win.sessionStorage.getItem(key) ?? 'null') as { target: string; at: number } | null;\n if (last && last.target === target && Date.now() - last.at < 10_000) return;\n win.sessionStorage.setItem(key, JSON.stringify({ target, at: Date.now() }));\n } catch {\n return;\n }\n const send = (win as unknown as { __isotoneFetch?: typeof fetch }).__isotoneFetch ?? win.fetch.bind(win);\n send(`${cfg.endpoint}/active`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ active }),\n }).then((res) => { if (res.ok) reload(); }, () => {});\n };\n\n // A client-side navigation pushes a URL without `?v=`. Keep the tab's pick\n // in its address bar so a copied link still shows what the tab shows.\n const keep = (original: typeof push) => function (this: History, ...args: Parameters<typeof push>) {\n const result = original.apply(this, args);\n if (explicit && parse(win.location.search).picks === null) writeUrl(active);\n return result;\n };\n history.pushState = keep(push);\n history.replaceState = keep(replace);\n win.addEventListener('popstate', () => {\n if (explicit) writeUrl(active);\n });\n\n const store: LiveStore = {\n version: 1,\n get active() { return active; },\n get server() { return server; },\n get explicit() { return explicit; },\n subscribe(listener) {\n listeners.add(listener);\n return () => { listeners.delete(listener); };\n },\n register(key, ids, pinned) {\n files.set(key, { ids, pinned });\n // Only while the page first loads: a module that runs again later (a\n // hot update) is past hydration, and the server has moved on since.\n if (cfg.ssr && pinned && win.document.readyState !== 'complete' &&\n versionOf(ids, active) !== versionOf(ids, server)) {\n queueMicrotask(syncServer);\n }\n },\n needsReload(next) {\n return needsReload(active, next);\n },\n select(next) {\n if (reloading) return true;\n const reloadNeeded = needsReload(active, next);\n active = next.slice();\n explicit = next.length > 0;\n writeUrl(active);\n if (reloadNeeded) return true;\n emit();\n return false;\n },\n follow(next) {\n if (explicit || reloading) return;\n const same = next.length === active.length && next.every((id) => active.includes(id));\n if (same) return;\n const reloadNeeded = needsReload(active, next);\n active = next.slice();\n if (reloadNeeded) reload();\n else emit();\n },\n reload,\n };\n win.__isotoneLive = store;\n return store;\n}\n\n/** The React side of a dispatcher: one binding per export name. */\nexport interface LiveBinder {\n file(key: string, ids: (string | null)[], modules: Record<string, unknown>[], names: string[]): Record<string, unknown>;\n}\n\n/**\n * Build the binder over the host's React and the tab's store. Runs inside the\n * virtual module, which imports React the way the host's own code does.\n */\nexport function liveBinder(\n React: {\n createElement: (type: unknown, props: unknown) => unknown;\n forwardRef: (render: (props: unknown, ref: unknown) => unknown) => unknown;\n useSyncExternalStore: <T>(subscribe: (cb: () => void) => () => void, get: () => T, getServer?: () => T) => T;\n version: string;\n },\n store: LiveStore,\n): LiveBinder {\n const MEMO = Symbol.for('react.memo');\n const FORWARD = Symbol.for('react.forward_ref');\n const LAZY = Symbol.for('react.lazy');\n const refAsProp = Number.parseInt(React.version, 10) >= 19;\n const BUILTIN = new Set(['length', 'name', 'prototype', 'caller', 'arguments', 'displayName',\n '$$typeof', 'render', 'type', 'compare', '_payload', '_init']);\n\n const isClass = (value: unknown): boolean =>\n typeof value === 'function' && /^class[\\s{]/.test(Function.prototype.toString.call(value));\n const isComponent = (name: string, value: unknown, jsx: boolean): boolean => {\n if (typeof value === 'function') {\n const proto = (value as { prototype?: { isReactComponent?: unknown } }).prototype;\n if (proto?.isReactComponent) return true;\n if (isClass(value)) return false;\n if (name !== 'default') return /^[A-Z]/.test(name);\n const own = (value as { name?: string }).name ?? '';\n // `export default () => …` in a JSX file is a component in practice.\n return /^[A-Z]/.test(own) || (jsx && (own === '' || own === 'default'));\n }\n if (!value || typeof value !== 'object') return false;\n const tag = (value as { $$typeof?: unknown }).$$typeof;\n return tag === MEMO || tag === FORWARD || tag === LAZY;\n };\n\n return {\n file(key, ids, modules, names) {\n // The version a selection shows: the active variant that has this\n // file, else the real file, else (a file only variants add) the first.\n const pick = (set: string[]): number => {\n for (const id of set) {\n const hit = ids.indexOf(id);\n if (hit >= 0) return hit;\n }\n const base = ids.indexOf(null);\n return base >= 0 ? base : 0;\n };\n const out: Record<string, unknown> = {};\n const renders = new Map<string, (props: Record<string, unknown>, ref?: unknown) => unknown>();\n const jsx = /x$/.test(key);\n let pinned = false;\n for (const name of names) {\n const values = modules.map((mod) => mod[name]);\n const first = values[0];\n if (values.every((value) => value === first)) {\n out[name] = first;\n continue;\n }\n const defined = values.filter((value) => value !== undefined);\n if (defined.length > 0 && defined.every((value) => isComponent(name, value, jsx))) {\n const render = (props: Record<string, unknown>, ref?: unknown) => {\n const index = React.useSyncExternalStore(\n store.subscribe,\n () => pick(store.active),\n () => pick(store.server),\n );\n const component = values[index];\n if (component == null) return null;\n return React.createElement(component, ref == null ? props : { ...props, ref });\n };\n renders.set(name, render);\n const wrapper = (refAsProp ? (props: Record<string, unknown>) => render(props) : React.forwardRef(render as (p: unknown, r: unknown) => unknown)) as Record<string, unknown>;\n const label = name === 'default'\n ? (defined[0] as { displayName?: string; name?: string }).displayName ?? (defined[0] as { name?: string }).name ?? 'Variant'\n : name;\n if (typeof wrapper === 'function') Object.defineProperty(wrapper, 'name', { value: label });\n wrapper.displayName = label;\n // Compound components (`Card.Header`) read from the active version.\n const statics = new Set<string>();\n for (const value of defined) {\n for (const prop of Object.getOwnPropertyNames(value)) if (!BUILTIN.has(prop)) statics.add(prop);\n }\n for (const prop of statics) {\n if (prop in wrapper && !Object.getOwnPropertyDescriptor(wrapper, prop)?.configurable) continue;\n Object.defineProperty(wrapper, prop, {\n configurable: true,\n enumerable: true,\n get: () => (values[pick(store.active)] as Record<string, unknown> | undefined)?.[prop],\n });\n }\n out[name] = wrapper;\n continue;\n }\n pinned = true;\n out[name] = values[pick(store.active)];\n }\n store.register(key, ids, pinned);\n // The dispatcher's hoisted stand-ins render through this, for a module\n // in an import cycle that took a component before the dispatcher ran.\n Object.defineProperty(out, '__isotoneRender', {\n value: (name: string, props: Record<string, unknown>, ref?: unknown) => {\n const render = renders.get(name);\n if (render) return render(props, ref);\n const value = out[name];\n return typeof value === 'function' || (value && typeof value === 'object')\n ? React.createElement(value, ref == null ? props : { ...props, ref })\n : null;\n },\n });\n return out;\n },\n };\n}\n\n/** The inline `<head>` script that creates the tab's store. */\nexport function liveStoreScript(cfg: LiveConfig): string {\n return `(${liveStore.toString()})(window, ${safeJson(cfg)});`;\n}\n\n/** The virtual module the dispatchers import. `fallback` configures a store\n * for a page whose HTML did not pass through the plugin. */\nexport function liveRuntimeModule(fallback: LiveConfig): string {\n return [\n `import * as React from 'react';`,\n `const store = (${liveStore.toString()})(window, ${safeJson(fallback)});`,\n `export const live = (${liveBinder.toString()})(React, store);`,\n `if (import.meta.hot) import.meta.hot.on(${JSON.stringify(ACTIVE_EVENT)}, (data) => store.follow(data.active));`,\n '',\n ].join('\\n');\n}\n\n/**\n * The module served in place of a file with variants. `versions` lists the\n * real file (`null`) and each variant that has a copy, in a fixed order;\n * `names` is every export any version has.\n */\nexport function dispatcherModule(\n key: string,\n basename: string,\n versions: (string | null)[],\n names: string[],\n): string {\n const lines = [`import { live as __isotone } from ${JSON.stringify(LIVE_MODULE)};`];\n versions.forEach((id, i) => {\n const spec = `./${basename}?${VERSION_QUERY}=${id ?? BASE_VERSION}`;\n lines.push(`import * as __v${i} from ${JSON.stringify(spec)};`);\n });\n // Component-shaped names (and the default) are function declarations, so\n // they exist before this module runs: a module in an import cycle that\n // reads one at its top level (`memo(Picker)`) gets a stand-in that renders\n // the real binding. Each is reassigned to that binding once it is known.\n const hoisted = (name: string) => name === 'default' || /^[A-Z][\\w$]*$/.test(name);\n const local = (name: string) => (name === 'default' ? '__isotoneDefault' : name);\n for (const name of names.filter(hoisted)) {\n const head = name === 'default' ? 'export default function __isotoneDefault' : `export function ${name}`;\n lines.push(`${head}(props, ref) { return __f.__isotoneRender(${JSON.stringify(name)}, props, ref); }`);\n }\n lines.push(\n `const __f = __isotone.file(${JSON.stringify(key)}, ${JSON.stringify(versions)}, [${versions.map((_, i) => `__v${i}`).join(', ')}], ${JSON.stringify(names)});`,\n );\n names.forEach((name, i) => {\n if (hoisted(name)) {\n lines.push(`${local(name)} = __f[${JSON.stringify(name)}];`);\n return;\n }\n lines.push(`const __e${i} = __f[${JSON.stringify(name)}];`);\n lines.push(`export { __e${i} as ${name} };`);\n });\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction safeJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029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