@ethisyscore/vite-plugin 1.85.0 → 1.87.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/README.md +38 -0
- package/dist/index.cjs +58 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +51 -1
- package/dist/index.d.ts +51 -1
- package/dist/index.js +58 -7
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/contract-a/schema-validator.ts","../src/contract-a/emit.ts","../src/contract-b/rewrite-imports.ts","../src/contract-b/worker-bundle.ts","../src/utils/strings.ts","../src/platform-react/scope-plugin-css.ts","../src/platform-react/build-pages.ts","../src/platform-react/page-bundles.ts","../src/platform-react/test-helpers.ts","../src/platform-react/generate-manifest.ts","../src/iframeSandboxPlugin.ts","../src/index.ts"],"names":["readManifest","normalize","isAbsolute","resolve","existsSync","readFileSync","slash","end","assertHostOriginRelativePath","createHash","ID_REGEX","walk","writeFileSync","DIGEST_MAP_FILENAME","sep","defaultWriteFile","mkdirSync","dirname","assertSafeRelativePath","safeMountId"],"mappings":";;;;;;AAgDA,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAY,gBAAgB,CAAA;AAC5D,IAAM,kBAAA,GAAqB,IAAI,GAAA,CAAY,eAAe,CAAA;AAC1D,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAY,gBAAgB,CAAA;AAO5D,SAAS,cAAc,IAAA,EAA8C;AACnE,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACrB,IAAA,OAAO,EAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CACV,GAAA,CAAI,CAAC,GAAA,KAAQ;AACZ,IAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,IAAA,OAAO,EAAE,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAA,CAAE,OAAA,CA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AQ,SAAS,CAAA,CAAE,UAAU,CAAC,CAAA,KAAM;AAAA,OACnD;AACA,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,OAAO,EAAA;AAAA,MACT;AAAA,IACF,CAAA;AAAA;AAAA,IAGA,KAAK,EAAA,EAAI;AACP,MAAA,MAAM,YAAA,GAAeG,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAMH,OAAAA,CAAQ,SAAS,CAAA,CAAE,UAAU,CAAC,CAAA,KAAM;AAAA,OACnD;AACA,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,OAAO,aAAa,KAAK,CAAA;AAAA,MAC3B;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import {\n SduiNode,\n ReactiveRule,\n KNOWN_PRIMITIVES,\n KNOWN_OPERATORS,\n KNOWN_RULE_KINDS,\n} from \"@ethisyscore/protocol\";\n\n/**\n * Minimal structural shape of a Zod parse issue. Declared locally so the\n * vite-plugin package does not need a direct `zod` peer/runtime dependency —\n * the protocol package owns Zod, we just consume parse results.\n */\ninterface ZodLikeIssue {\n readonly code: string;\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n}\n\n/**\n * A single, structured validation failure surfaced by the Contract A\n * schema validators. Carries enough context for a build-time error\n * to be actionable without the plugin author opening the host runtime.\n */\nexport interface ValidationFailure {\n /** Absolute path of the source file whose JSON failed validation. */\n filePath: string;\n /**\n * JSON-pointer (RFC 6901) into the failing JSON document, pointing at\n * the offending node. Empty string when the offender is the root.\n */\n pointer: string;\n /** The offending operator / primitive / rule-kind name, if extractable. */\n offender?: string;\n /** Human-readable message suitable for surfacing at the build CLI. */\n message: string;\n}\n\n/**\n * Result of a validation call. Discriminated on `ok` so callers can branch\n * narrowly without juggling exception flow for expected outcomes.\n */\nexport type ValidationResult =\n | { ok: true }\n | { ok: false; failures: ValidationFailure[] };\n\n// ── Internal: Zod issue → ValidationFailure ─────────────────────\n\nconst KNOWN_PRIMITIVE_SET = new Set<string>(KNOWN_PRIMITIVES);\nconst KNOWN_OPERATOR_SET = new Set<string>(KNOWN_OPERATORS);\nconst KNOWN_RULE_KIND_SET = new Set<string>(KNOWN_RULE_KINDS);\n\n/**\n * Convert a Zod path array into a JSON Pointer (RFC 6901) string.\n *\n * Numeric segments stay as array indices, string segments are escaped per RFC.\n */\nfunction toJsonPointer(path: ReadonlyArray<string | number>): string {\n if (path.length === 0) {\n return \"\";\n }\n return \"/\" + path\n .map((seg) => {\n const s = String(seg);\n return s.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n })\n .join(\"/\");\n}\n\n/**\n * Walks the original JSON value and the Zod path to extract a likely offender\n * string. For unknown SDUI primitives the offender is the rejected `type`\n * value; for unknown JsonLogic operators the offender is the offending key.\n */\nfunction extractOffender(\n doc: unknown,\n issue: ZodLikeIssue,\n): string | undefined {\n // 1. enum mismatch — the offender is the input value\n if (issue.code === \"invalid_value\" || issue.code === \"invalid_enum_value\") {\n const received = (issue as unknown as { received?: unknown }).received;\n if (typeof received === \"string\") {\n return received;\n }\n }\n\n // 2. invalid_union (the operator object), or refine refusal — walk to the path\n // and look for an object whose only key is unknown.\n let cur: unknown = doc;\n for (const seg of issue.path) {\n if (cur === null || cur === undefined) {\n break;\n }\n cur = (cur as Record<string | number, unknown>)[seg as string | number];\n }\n if (cur && typeof cur === \"object\" && !Array.isArray(cur)) {\n const keys = Object.keys(cur as object);\n if (keys.length === 1 && !KNOWN_OPERATOR_SET.has(keys[0])) {\n return keys[0];\n }\n }\n\n // 3. Fall back to last path segment (e.g. an unknown rule-kind)\n if (issue.path.length > 0) {\n const last = issue.path[issue.path.length - 1];\n if (typeof last === \"string\" && !KNOWN_RULE_KIND_SET.has(last) && !KNOWN_PRIMITIVE_SET.has(last)) {\n return last;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert a Zod parse failure into structured {@link ValidationFailure}s.\n *\n * One Zod issue → one failure, preserving order. The original JSON `doc`\n * is walked in tandem with each issue's path so the offender name (an\n * unknown primitive, operator, or rule-kind) can be lifted into the\n * failure record.\n */\nfunction zodIssuesToFailures(\n doc: unknown,\n issues: readonly ZodLikeIssue[],\n filePath: string,\n): ValidationFailure[] {\n return issues.map((issue) => {\n const pointer = toJsonPointer(issue.path);\n const offender = extractOffender(doc, issue);\n const offenderSuffix = offender ? ` (offender: '${offender}')` : \"\";\n return {\n filePath,\n pointer,\n offender,\n message: `${filePath}${pointer ? ` at ${pointer}` : \"\"}: ${issue.message}${offenderSuffix}`,\n };\n });\n}\n\n/**\n * Validate a single declarative SDUI resource against the protocol's\n * {@link SduiNode} Zod schema. The recursive schema rejects unknown\n * primitives and unknown JsonLogic operators at any depth of the tree.\n *\n * `filePath` is propagated into every emitted failure so the build CLI\n * can point the author at the exact file on disk.\n */\nexport function validateDeclarativeResource(\n doc: unknown,\n uri: string,\n filePath: string,\n): ValidationResult {\n const parsed = SduiNode.safeParse(doc);\n if (parsed.success) {\n return { ok: true };\n }\n const failures = zodIssuesToFailures(doc, parsed.error.issues, filePath);\n // Tag the URI onto every message so the build CLI shows which resource failed.\n return {\n ok: false,\n failures: failures.map((f) => ({\n ...f,\n message: `[resource ${uri}] ${f.message}`,\n })),\n };\n}\n\n/**\n * Validate a single {@link ReactiveRule} against the protocol's curated\n * JsonLogic operator subset. Used for top-level reactivity declarations\n * declared on the manifest itself (i.e. not embedded under a `bindings`\n * key on a SDUI node — those are covered by {@link validateDeclarativeResource}).\n */\nexport function validateReactiveRule(\n rule: unknown,\n filePath: string,\n): ValidationResult {\n const parsed = ReactiveRule.safeParse(rule);\n if (parsed.success) {\n return { ok: true };\n }\n return {\n ok: false,\n failures: zodIssuesToFailures(rule, parsed.error.issues, filePath),\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type { Plugin } from \"vite\";\n\nimport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationFailure,\n} from \"./schema-validator\";\n\n// ── Manifest shapes (subset) ───────────────────────────────────\n\n/**\n * Reference from the plugin manifest to an SDUI resource JSON file.\n *\n * Wave 0 convention: the manifest declares each declarative resource with\n * a stable `uri` plus a `file` path (relative to the manifest's directory)\n * pointing at the JSON document the host will serve. The static-file\n * convention lets the Vite plugin validate the tree at build time without\n * having to execute plugin runtime code.\n */\nexport interface ManifestResourceRef {\n uri: string;\n /**\n * Relative path (POSIX or platform-native) to the SDUI JSON document.\n * Must not be absolute, must not contain `..` traversal segments.\n */\n file?: string;\n}\n\n/**\n * Top-level manifest reactivity-rule declaration. Each entry pairs an\n * author-supplied identifier with a {@link import(\"@ethisyscore/protocol\").ReactiveRule}.\n *\n * Reactivity declared inline on SDUI nodes (the `bindings` property) is\n * validated by the SDUI-tree pass; this surface covers the rarer case of\n * a manifest-level rule that applies cross-resource.\n */\nexport interface ManifestReactiveRuleRef {\n id: string;\n rule: unknown;\n}\n\n/**\n * The subset of the plugin manifest the Contract A Vite plugin pass cares\n * about. The full manifest is intentionally a superset — the plugin\n * tolerates additional fields it has not been taught yet so manifests\n * built against a newer schema still load.\n */\nexport interface ContractAManifest {\n resources?: ManifestResourceRef[];\n reactiveRules?: ManifestReactiveRuleRef[];\n [key: string]: unknown;\n}\n\n// ── Options ────────────────────────────────────────────────────\n\n/**\n * Author-facing options for the Contract A Vite plugin pass.\n *\n * `root` defaults to Vite's resolved root at `configResolved` time, so the\n * common case requires no configuration. `manifestPath` defaults to the\n * `feature.manifest.json` convention emitted by the host-rendered\n * scaffolding template; pass an absolute or relative path to override.\n */\nexport interface ContractAPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json` colocated with the Vite root.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted SDUI assets. Defaults to `sdui/`. The plugin\n * always emits an `${prefix}sdui-manifest.json` index alongside the\n * validated resource JSON.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────\n\n/** Slug-encode a resource URI into a filesystem-safe asset filename. */\nfunction slugForUri(uri: string): string {\n return uri.replace(/[^a-zA-Z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\n/** Reject path traversal and absolute paths in author-supplied references. */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/**\n * Render a {@link ValidationFailure} list into the multi-line build-failure\n * message Vite will surface to the author.\n */\nfunction formatFailures(failures: ValidationFailure[]): string {\n const lines = failures.map((f, i) => ` ${i + 1}. ${f.message}`);\n return [\n `[@ethisyscore/vite-plugin] Contract A schema validation failed:`,\n ...lines,\n ].join(\"\\n\");\n}\n\n// ── Plugin ─────────────────────────────────────────────────────\n\ninterface EmittedResource {\n uri: string;\n fileName: string;\n}\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract A\n * (`renderMode: host-rendered`) plugins.\n *\n * Reads `feature.manifest.json` (or `extension.manifest.json` via\n * `manifestPath`), validates each declared SDUI resource against the\n * protocol's `SduiNode` Zod schema, validates each manifest-level\n * reactivity rule against `ReactiveRule`, and emits the validated JSON\n * into the Rollup bundle under the configured output prefix. Validation\n * failures abort the build with a multi-line structured error that names\n * the offending operator/primitive and the source file path + JSON\n * pointer so the author can land on the offending node immediately.\n *\n * Worker-bundle emission for `renderMode: remote-runtime` is deferred to\n * Wave 1's E7.S1b — this pass deliberately does nothing for non-Contract-A\n * manifests.\n */\nexport function ethisysContractAPlugin(\n options: ContractAPluginOptions = {},\n): Plugin {\n const outputPrefix = (options.outputPrefix ?? \"sdui/\").replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let validatedResources: EmittedResource[] = [];\n // Plugin-internal cache so generateBundle can re-emit without re-reading + re-parsing.\n const resourcePayloads = new Map<string, string>();\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractAManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractAManifest;\n } catch (e) {\n throw new Error(\n `[@ethisyscore/vite-plugin] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n function validate(): void {\n validatedResources = [];\n resourcePayloads.clear();\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n\n const failures: ValidationFailure[] = [];\n\n // ── Resources ───────────────────────────────────────────────\n for (const ref of manifest.resources ?? []) {\n if (!ref.file) {\n // A resource without a `file` field is a dynamic / runtime-rendered\n // resource. The Vite plugin can't introspect those at build time;\n // skip them.\n continue;\n }\n assertSafeRelativePath(ref.file, \"Resource file path\");\n\n const filePath = resolve(resolvedRoot, ref.file);\n if (!existsSync(filePath)) {\n failures.push({\n filePath,\n pointer: \"\",\n message:\n `[resource ${ref.uri}] file \"${ref.file}\" referenced by the manifest does not exist on disk (resolved: ${filePath}).`,\n });\n continue;\n }\n\n const rawJson = readFileSync(filePath, \"utf-8\");\n let doc: unknown;\n try {\n doc = JSON.parse(rawJson);\n } catch (e) {\n failures.push({\n filePath,\n pointer: \"\",\n message: `[resource ${ref.uri}] failed to parse JSON: ${(e as Error).message}`,\n });\n continue;\n }\n\n const result = validateDeclarativeResource(doc, ref.uri, filePath);\n if (!result.ok) {\n failures.push(...result.failures);\n continue;\n }\n\n // Serialise canonically (validated input → emitted payload) so the\n // host always sees a byte-stable artefact regardless of source whitespace.\n const fileName = `${outputPrefix}${slugForUri(ref.uri)}.json`;\n const payload = JSON.stringify(doc);\n resourcePayloads.set(fileName, payload);\n validatedResources.push({ uri: ref.uri, fileName });\n }\n\n // ── Manifest-level reactive rules ────────────────────────────\n for (const ruleRef of manifest.reactiveRules ?? []) {\n const result = validateReactiveRule(ruleRef.rule, manifestAbsPath);\n if (!result.ok) {\n failures.push(\n ...result.failures.map((f) => ({\n ...f,\n message: `[reactiveRule ${ruleRef.id}] ${f.message}`,\n })),\n );\n }\n }\n\n if (failures.length > 0) {\n throw new Error(formatFailures(failures));\n }\n }\n\n return {\n name: \"ethisys-contract-a\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing a resource JSON.\n validate();\n },\n\n generateBundle() {\n if (validatedResources.length === 0) {\n return;\n }\n\n // Emit each validated resource as a static asset.\n for (const { fileName } of validatedResources) {\n const source = resourcePayloads.get(fileName);\n if (source === undefined) {\n continue;\n }\n this.emitFile({ type: \"asset\", fileName, source });\n }\n\n // Emit a compact index so the host can list contracts without\n // walking the bundle. `name` is stable per build; `resources` is\n // sorted by URI for deterministic output.\n const sorted = [...validatedResources].sort((a, b) =>\n a.uri.localeCompare(b.uri),\n );\n const index = {\n version: 1,\n resources: sorted.map(({ uri, fileName }) => ({ uri, file: fileName })),\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}sdui-manifest.json`,\n source: JSON.stringify(index),\n });\n },\n };\n}\n","// ── Contract B safe-import rewriter ────────────────────────────────\n//\n// Static ES `import` statements with bare specifiers are unresolvable inside\n// a Contract B worker realm: the worker has no `<script type=\"importmap\">`\n// surface (workers don't host scripts) and the spec's `WorkerOptions.importMap`\n// is still proposal-stage in 2026-05. The bootstrap script\n// (`WorkerBootstrapScriptProvider.cs` in the API repo) composes a frozen\n// `IMPORT_MAP` per worker and exposes a synchronous-wrapper-free helper at\n// `globalThis.__ethisysSafeImport(spec) -> Promise<Module>`.\n//\n// The build-time complement to that runtime surface lives here: every static\n// `import` whose specifier is on the closed Contract B allowlist is rewritten\n// into a top-level `await` against `__ethisysSafeImport`. Module workers\n// support top-level await; the host loads the plugin bundle via dynamic\n// `import(moduleUrl)` which awaits the bundle's top-level evaluation, so the\n// `mod.activate(port)` call site sees a fully-initialised module.\n//\n// Specifiers outside the allowlist would not survive `Rollup.external` (which\n// the Contract B config already enforces), so this rewriter never observes\n// them in practice. It still guards against the case defensively — a future\n// `external` widening should not silently emit bare specifiers the worker\n// realm cannot resolve.\n\nconst STATIC_IMPORT_RE = /^([ \\t]*)import[ \\t]+(.*?)[ \\t]*;?[ \\t]*$/gm;\n\n/**\n * Rewrite static ES `import` statements whose specifier is a bare allowlist\n * entry into a top-level `await globalThis.__ethisysSafeImport(...)` form.\n *\n * Non-bare specifiers (relative paths, http(s) URLs, data:/blob:/javascript:\n * schemes) are passed through untouched. Dynamic `import()` calls are passed\n * through untouched. Bare specifiers outside `allowlist` are passed through\n * untouched — the surrounding `external` config is the gate; this function\n * only rewrites what the build pipeline contract guarantees.\n */\nexport function rewriteSafeImports(\n code: string,\n allowlist: readonly string[],\n): string {\n const allowSet = new Set(allowlist);\n\n return code.replace(STATIC_IMPORT_RE, (match, indent: string, body: string) => {\n const rewrite = tryRewriteImport(body, allowSet);\n return rewrite === null ? match : `${indent}${rewrite}`;\n });\n}\n\nfunction convertNamedBindings(namedClause: string): string {\n // `{ A, B as Local, C }` -> `A, B: Local, C` (object-destructuring rename form)\n const inner = namedClause.slice(1, -1).trim();\n if (inner.length === 0) {\n return \"\";\n }\n const parts = inner.split(\",\").map((p) => p.trim()).filter((p) => p.length > 0);\n const converted = parts.map((part) => {\n const asMatch = part.match(/^(\\w[\\w$]*)\\s+as\\s+(\\w[\\w$]*)$/);\n return asMatch === null ? part : `${asMatch[1]}: ${asMatch[2]}`;\n });\n return converted.join(\", \");\n}\n\nfunction tryRewriteImport(body: string, allowSet: ReadonlySet<string>): string | null {\n // Side-effect: `\"Button\"` or `'Button'`\n const sideEffect = body.match(/^[\"']([^\"']+)[\"']$/);\n if (sideEffect !== null) {\n const spec = sideEffect[1];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default + named: `React, { useState, useEffect as fx } from \"react\"`\n const defaultPlusNamed = body.match(\n /^(\\w[\\w$]*)\\s*,\\s*(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/,\n );\n if (defaultPlusNamed !== null) {\n const defaultLocal = defaultPlusNamed[1];\n const namedClause = defaultPlusNamed[2];\n const spec = defaultPlusNamed[3];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n const inner = bindings.length === 0\n ? `default: ${defaultLocal}`\n : `default: ${defaultLocal}, ${bindings}`;\n return `const { ${inner} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default-only: `Foo from \"Button\"`\n const defaultOnly = body.match(/^(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (defaultOnly !== null) {\n const local = defaultOnly[1];\n const spec = defaultOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const { default: ${local} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Named only: `{ A, B as Local } from \"react\"`\n const namedOnly = body.match(/^(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namedOnly !== null) {\n const namedClause = namedOnly[1];\n const spec = namedOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n return `const { ${bindings} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Namespace: `* as N from \"react\"`\n const namespaceOnly = body.match(/^\\*\\s+as\\s+(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namespaceOnly !== null) {\n const local = namespaceOnly[1];\n const spec = namespaceOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const ${local} = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n return null;\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize, sep } from \"node:path\";\nimport { rewriteSafeImports } from \"./rewrite-imports\";\nimport type { Plugin } from \"vite\";\n\n// ── Frozen import-map allowlist (E4.S4) ────────────────────────────\n//\n// The Contract B worker realm can ONLY import these bare specifiers. The\n// runtime side (`WorkerBootstrapScriptProvider` in the API repo) enforces the\n// same allowlist by composing a frozen `IMPORT_MAP` at handshake time. The two\n// lists MUST agree — drift is caught by the `import-map-allowlist matches\n// extension-runtime CONTRACT_B_PRIMITIVES` test in `contract-b.test.ts`,\n// which imports `CONTRACT_B_PRIMITIVES` from the sibling extension-runtime\n// package and diffs it against {@link CONTRACT_B_SEMANTIC_PRIMITIVES} below.\n//\n// Plugin-supplied bare specifiers outside this list fail the build with a\n// structured error so authors get a build-time signal instead of a runtime\n// `import-map-violation` from the worker bootstrap.\n\n/**\n * Contract B semantic primitive vocabulary (the closed v1 set authored in\n * `sdk/extension-runtime/src/host/worker/component-registry.ts`). The names\n * mirror the registry exactly; a drift between the two breaks the cross-repo\n * agreement that E4.S4 locks in.\n */\nexport const CONTRACT_B_SEMANTIC_PRIMITIVES = [\n \"Button\",\n \"DataTable\",\n \"Form\",\n \"EntityPicker\",\n \"CommandBar\",\n \"Drawer\",\n \"Modal\",\n \"CanvasSurface\",\n \"WebGLSurface\",\n // Phase 1 additions (per Contract B + PlatformReact plan §Q6, frequency\n // survey of coreconnect-web Timesheets feature). Card / Tabs / Select /\n // Alert close the four most-common gaps in the v1 primitive set:\n // - Card: universal layout container, ~20 imports across surveyed pages.\n // - Tabs: settings / configuration surfaces (6 tabs in TimesheetSettings).\n // - Select: filter + form input, ~10 imports; Form's text input doesn't\n // cover dropdowns.\n // - Alert: lock/unlock warnings, validation banners, non-modal system\n // messages; Card doesn't carry severity semantics.\n \"Card\",\n \"Tabs\",\n \"Select\",\n \"Alert\",\n] as const;\n\n/**\n * Non-component import-map entries — the runtime libraries the worker is\n * permitted to resolve via bare specifiers. Authoring constraint: the plugin's\n * single ESM bundle (Contract B emits exactly one — see `worker-bundle.ts`)\n * can `import x from \"react\"` or `import { ... } from \"@ethisyscore/extension-runtime\"`\n * and nothing else off-bundle.\n */\nexport const CONTRACT_B_RUNTIME_IMPORTS = [\n \"react\",\n \"@ethisyscore/extension-runtime\",\n] as const;\n\n/**\n * Full allowlist of bare specifiers a Contract B plugin bundle may import.\n * Frozen at module load so plugins can't mutate it via a transitive dep.\n */\nexport const CONTRACT_B_IMPORT_MAP_ALLOWLIST: readonly string[] = Object.freeze([\n ...CONTRACT_B_RUNTIME_IMPORTS,\n ...CONTRACT_B_SEMANTIC_PRIMITIVES,\n]);\n\nconst ALLOWLIST_SET: ReadonlySet<string> = new Set(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * The subset of a Contract B (`renderMode: remote-runtime`) plugin manifest\n * that this Vite pass consumes. Manifests are tolerated as a superset — extra\n * fields are ignored so newer-schema manifests still load.\n */\nexport interface ContractBManifest {\n renderMode?: string;\n /**\n * Worker bundle declaration. Required when `renderMode === \"remote-runtime\"`.\n * The `entry` is a relative path (POSIX or platform-native) from the\n * manifest's directory to the plugin's TypeScript/JavaScript entrypoint.\n *\n * Absolute paths, path-traversal, and non-host-origin URLs are rejected at\n * build time — Contract B requires the worker bundle to be a host-origin\n * asset (the import-map enforcement in E4.S4 builds on this guarantee).\n */\n worker?: {\n entry?: string;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the Contract B Vite pass.\n */\nexport interface ContractBPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted worker assets and the worker-bundle manifest.\n * Defaults to `worker/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n // Remote URLs (any scheme + `://`) are forbidden — Contract B bundles must\n // be host-origin assets so the worker bootstrap's frozen import map can\n // enforce origin restrictions deterministically.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n // Reject `data:` / `blob:` (no `//`) too — also non-host-origin.\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/** Normalise Windows backslashes for the Rollup input table. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract B\n * (`renderMode: remote-runtime`) plugins.\n *\n * Behaviour:\n * - For `renderMode: \"remote-runtime\"`: declares a single ESM worker entry as\n * the Rollup input table. The output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so a Contract B plugin always ships as ONE\n * bundled module — no chunk splitting, no shared chunks, no async imports\n * spread across multiple files. This is the precondition for E4.S4's\n * frozen import map.\n * - For any other `renderMode` (including `host-rendered` and `undefined`):\n * the pass is a no-op. The Wave 0 Contract A path (`ethisysContractAPlugin`)\n * continues to apply without interference. Composition is expected — the\n * recommended template registers both plugins so a manifest can switch\n * render modes without changing its Vite config.\n *\n * The pass also emits a `worker/worker-bundle.json` companion asset listing\n * the bundled entry so the host (or downstream packaging) can inspect what\n * the build produced without re-parsing the bundle.\n *\n * Origin enforcement on the import map (path-pinned host origin, no `data:` /\n * `blob:` imports) is the responsibility of E4.S4 (worker bootstrap) — this\n * pass only blocks remote/absolute paths at the manifest layer so a malformed\n * manifest fails fast.\n */\nexport function ethisysContractBPlugin(\n options: ContractBPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"worker/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let workerEntryAbs: string | null = null;\n let workerEntryRel: string | null = null;\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractBManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractBManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-contract-b] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve the worker entry's absolute path.\n * Idempotent — repeated invocations return cached state.\n */\n function validate(): void {\n workerEntryAbs = null;\n workerEntryRel = null;\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n if (manifest.renderMode !== \"remote-runtime\") {\n // Non-Contract-B manifests are not our concern.\n return;\n }\n const entry = manifest.worker?.entry;\n if (typeof entry !== \"string\" || entry.length === 0) {\n throw new Error(\n `[ethisys-contract-b] manifest declares renderMode='remote-runtime' but no worker.entry. ` +\n `Set \"worker\": { \"entry\": \"src/worker.ts\" } (relative path).`,\n );\n }\n assertHostOriginRelativePath(entry, \"Worker entry\");\n\n const absPath = resolve(resolvedRoot, entry);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-contract-b] Worker entry file \"${entry}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n workerEntryAbs = absPath;\n workerEntryRel = entry;\n }\n\n return {\n name: \"ethisys-contract-b\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n /**\n * Declares the Rollup input table and locks the output to a single ESM\n * module. Only fires when the manifest opts in (`renderMode: remote-runtime`).\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n // `config` runs before `buildStart`, so we validate here too — the user\n // needs the structured error at the same lifecycle gate that fails.\n validate();\n\n if (workerEntryAbs === null) {\n return; // Non-Contract-B manifest: no-op.\n }\n\n // The allowlist runtime libraries (`react`, `@ethisyscore/extension-runtime`)\n // and the semantic primitive names are NOT bundled — they're host-served\n // and resolved by the frozen import map at worker bootstrap time. Mark\n // them as `external` so Rollup leaves the bare specifiers intact in the\n // emitted bundle (which is what `generateBundle` then inspects).\n const externalSpecifiers = new Set<string>(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n return {\n build: {\n rollupOptions: {\n input: { worker: slash(workerEntryAbs) },\n external: (id: string): boolean => externalSpecifiers.has(id),\n // CRITICAL: single-file output for the worker bundle. The\n // E4.S4 frozen import map presumes ONE module entry per plugin —\n // chunk splitting or dynamic-import shards would defeat it.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n },\n },\n };\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest.\n validate();\n },\n\n /**\n * Reject `data:` / `blob:` / `javascript:` URL specifiers at resolve time.\n *\n * Rollup normally externalises unknown URL schemes silently, which would\n * mean a malicious `import(\"data:text/javascript,...\")` survives the\n * build untouched and only fails at runtime (where the bootstrap script's\n * `safeImport` would catch it). We want build-time failure too — the\n * import-map contract is enforced at BOTH ends.\n */\n resolveId(source) {\n if (workerEntryAbs === null) {\n return null;\n }\n if (/^(data|blob|javascript):/i.test(source)) {\n const scheme = source.split(\":\", 1)[0];\n this.error(\n `[ethisys-contract-b] Contract B bundle imports forbidden URL scheme '${scheme}:' ` +\n `(specifier: \"${source.slice(0, 80)}${source.length > 80 ? \"...\" : \"\"}\"). ` +\n `The worker realm rejects ${scheme}: imports at runtime; the build rejects them too.`,\n );\n }\n return null;\n },\n\n /**\n * Rewrite the emitted worker chunk's static bare-specifier imports into\n * top-level `await globalThis.__ethisysSafeImport(...)` calls. This is\n * the build-time complement to the worker bootstrap's frozen IMPORT_MAP\n * (defined in CoreConnect-Api's WorkerBootstrapScriptProvider.cs). The\n * worker realm has no `<script type=\"importmap\">` surface, so static\n * bare specifiers reach the browser's native ES loader as\n * `Failed to resolve module specifier` errors at module load time.\n *\n * Returns `null` (no transform) when the manifest is not Contract B —\n * the Contract A path's emitted chunks are left untouched.\n */\n renderChunk(code: string, chunk: { type: string; fileName: string }): { code: string } | null {\n if (workerEntryAbs === null) {\n return null;\n }\n if (chunk.type !== \"chunk\") {\n return null;\n }\n const rewritten = rewriteSafeImports(code, CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n if (rewritten === code) {\n return null;\n }\n return { code: rewritten };\n },\n\n /**\n * Inspect the emitted bundle for out-of-allowlist bare specifiers and emit\n * the per-bundle `worker-bundle.import-map.json` manifest.\n *\n * Because we marked allowlist specifiers as `external` in `config`, any\n * other bare specifier that the plugin tried to import would have failed\n * Rollup's resolver upstream — but we re-check the surviving `chunk.imports`\n * here as belt-and-braces in case a future Rollup or Vite change relaxes\n * the resolver path. Defence in depth at the build layer matches the\n * defence in depth at the runtime layer (E4.S3 bootstrap).\n */\n generateBundle(_outputOptions, bundle) {\n if (workerEntryAbs === null || workerEntryRel === null) {\n return;\n }\n\n const importedSpecifiers = new Set<string>();\n const violations: string[] = [];\n\n for (const [, chunk] of Object.entries(bundle)) {\n if (chunk.type !== \"chunk\") {\n continue;\n }\n // Both static imports (`chunk.imports`) and dynamic imports\n // (`chunk.dynamicImports`) are surveyed. `inlineDynamicImports: true`\n // collapses dynamic-imported chunks INTO the host chunk, but the\n // specifiers themselves still surface here for externalised IDs.\n const candidates: string[] = [\n ...(chunk.imports ?? []),\n ...(chunk.dynamicImports ?? []),\n ];\n for (const spec of candidates) {\n // Relative / absolute paths are emitted bundle artefacts — not\n // bare specifiers, not subject to the import-map. Skip them.\n if (spec.startsWith(\".\") || spec.startsWith(\"/\") || isAbsolute(spec)) {\n continue;\n }\n // URL-scheme specifiers should have been caught in `resolveId`,\n // but a relaxed-resolver path could let one through. Reject here too.\n if (/^[a-z][a-z0-9+.-]*:/i.test(spec)) {\n violations.push(spec);\n continue;\n }\n if (!ALLOWLIST_SET.has(spec)) {\n violations.push(spec);\n continue;\n }\n importedSpecifiers.add(spec);\n }\n }\n\n if (violations.length > 0) {\n // Sort + de-dupe for deterministic error message ordering.\n const unique = [...new Set(violations)].sort();\n this.error(\n `[ethisys-contract-b] Worker bundle imports specifier(s) outside the frozen import-map ` +\n `allowlist: ${unique.map(s => `\"${s}\"`).join(\", \")}. ` +\n `Allowed bare specifiers: ${CONTRACT_B_IMPORT_MAP_ALLOWLIST.map(s => `\"${s}\"`).join(\", \")}.`,\n );\n }\n\n // Sort the resolved entries so the emitted manifest is deterministic\n // across builds — content-hashable downstream without spurious churn.\n const resolvedEntries = [...importedSpecifiers].sort();\n\n const workerBundleManifest = {\n version: 1,\n renderMode: \"remote-runtime\",\n worker: { entry: workerEntryRel },\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.json`,\n source: JSON.stringify(workerBundleManifest),\n });\n\n // The import-map manifest — the host fetches this at extension activation\n // time to auto-derive the frozen `IMPORT_MAP` the worker bootstrap\n // composes. Values are `null` to signal \"host fills in canonical URL at\n // serve time\" — the manifest is the SDK's authoritative list of which\n // entries the bundle declares it consumes, not a URL table.\n const importMapManifest = {\n version: 1,\n // Authoring contract: the bundle's bare-specifier surface area, in\n // sorted order, restricted to the frozen allowlist.\n imports: Object.fromEntries(resolvedEntries.map(spec => [spec, null])),\n // Mirror the canonical allowlist so consumers diffing manifests\n // across plugin versions can see the contract the build verified\n // against without re-reading SDK source.\n allowlist: [...CONTRACT_B_IMPORT_MAP_ALLOWLIST],\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.import-map.json`,\n source: JSON.stringify(importMapManifest),\n });\n },\n };\n}\n","/**\n * Small, dependency-free string helpers shared across the SDK's build-step tooling\n * (e.g. the PlatformReact manifest generator). Pure functions — no I/O, no state.\n */\n\n/** Normalise Windows backslashes to forward slashes (for manifest/module paths). */\nexport function slash(p: string): string {\n return p.replace(/\\\\/g, \"/\");\n}\n\n/**\n * Convert a PascalCase / camelCase / snake_case identifier to kebab-case, e.g.\n * `CompanyCosts` → `company-costs`, `ToolMappings` → `tool-mappings`,\n * `already_snake` → `already-snake`. A digit stays attached to its preceding letter\n * (`TaxYear2024` → `tax-year2024`).\n */\nexport function kebab(s: string): string {\n return s.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").replace(/_/g, \"-\").toLowerCase();\n}\n\n/**\n * Convert a PascalCase / camelCase identifier to spaced Title Case, e.g.\n * `companyCosts` → `Company Costs`, `ToolMappings` → `Tool Mappings`. Inserts a\n * space at each lower/digit→upper boundary and upper-cases the first character.\n */\nexport function titleCase(s: string): string {\n return s.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/^./, (c) => c.toUpperCase());\n}\n\n/**\n * Escape regex metacharacters so an interpolated string matches literally — e.g.\n * `new RegExp(escapeRegExp(userInput))` treats `.` `*` `(` etc. as literal text.\n */\nexport function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Scope selector prefixed onto plugin-global CSS layers.\n *\n * `:where()` NOT `:is()` on purpose: `:where()` contributes ZERO specificity, so a\n * scoped utility keeps exactly the specificity it had unscoped. Inside a plugin\n * surface the cascade therefore behaves identically to before this transform; the\n * only change is that the rule no longer matches host chrome. `:is()` would have\n * raised every utility by one class and could flip a plugin's own conflicts.\n *\n * Two scope roots: the plugin root applied by `definePlatformReactPluginPage`, and\n * the portal container marker, because MUI overlays render into a portal. Phase 1\n * (`PluginPortalScope`) puts that container INSIDE the plugin root, so the second\n * arm is redundant for SDK-managed overlays and exists for a plugin that supplies\n * its own container element and marks it.\n */\nexport const EHX_PLUGIN_CSS_SCOPE = \":where(.ehx-plugin-root, [data-ehx-plugin-portal])\";\n\n/**\n * Replacement for a document-root selector (`:root`, `:host`) in a plugin sheet.\n *\n * Tailwind's `theme` layer declares its scale as custom properties on\n * `:root, :host` — `--spacing`, `--text-sm--line-height`, `--ease-*`,\n * `--animate-*`. Injected into the host document that lands on the HOST root and\n * silently redefines the host's own Tailwind scale for every element on the page:\n * the same defect as the leaking utilities, one level deeper and inherited.\n *\n * These declarations cannot simply be dropped — the plugin's utilities read them —\n * and prefixing is meaningless (`:where(.ehx-plugin-root) :root` matches nothing).\n * They are REPLACED with the plugin root, which the whole surface inherits from.\n *\n * `:is()` here, not `:where()`: this is a substitution for a 0,1,0 selector, so\n * matching that specificity is the faithful choice (a prefix is what must stay\n * specificity-neutral). Note this only works because portal containment landed\n * first — before that, overlays rendered outside the plugin root and would have\n * lost the whole theme scale.\n */\nexport const EHX_PLUGIN_ROOT_SCOPE = \":is(.ehx-plugin-root, [data-ehx-plugin-portal])\";\n\n/**\n * Cascade layers whose rules a plugin emits UNSCOPED and which therefore leak into\n * the host document.\n *\n * utilities Tailwind's generated utility classes. The leak that motivated this:\n * a plugin's bare `.text-sm` is a duplicate of the host's own rule,\n * so it changes nothing until the host settles a specificity tie by\n * source order — then the plugin's copy, injected later, wins and\n * silently restyles host chrome.\n * properties Tailwind's `@property` fallback block, which sets ~40 `--tw-*`\n * custom properties on `*, :before, :after, ::backdrop` for the whole\n * document.\n *\n * The other layers are already scoped: `theme` holds custom properties on the\n * plugin's own root class, and `base`/`components`/`mui` come from the SDK's\n * `plugin-base.css`, which scopes everything to `.ehx-plugin-root`.\n */\nexport const EHX_SCOPED_CSS_LAYERS: readonly string[] = [\"utilities\", \"properties\"];\n\n/**\n * At-rules whose blocks hold DESCRIPTORS or keyframe selectors, not style rules.\n * Copied through untouched: prefixing `from`/`to`/`50%` or a descriptor block\n * would produce invalid CSS.\n */\nconst VERBATIM_AT_RULES = new Set([\n \"keyframes\",\n \"-webkit-keyframes\",\n \"property\",\n \"font-face\",\n \"font-feature-values\",\n \"font-palette-values\",\n \"counter-style\",\n \"page\",\n \"viewport\",\n]);\n\n/**\n * At-rules that merely CONDITION the style rules inside them. Descended into: the\n * inner selectors get scoped, the at-rule prelude does not. Tailwind emits variant\n * utilities inside `@media`/`@supports`, so missing these would leave a hole.\n *\n * An at-rule in neither set is copied verbatim. That is the safe default (never\n * emit invalid CSS) at the cost of leaving a leak, so a new wrapper at-rule in a\n * future Tailwind needs adding here.\n */\nconst CONDITIONAL_AT_RULES = new Set([\n \"media\",\n \"supports\",\n \"container\",\n \"layer\",\n \"scope\",\n \"starting-style\",\n \"document\",\n \"-moz-document\",\n]);\n\n/**\n * What counts as \"scoped to a plugin\" — the convention every plugin front-end\n * adheres to, and the only thing the build guard needs to know.\n *\n * .ehx-plugin-root applied to every surface by the SDK page definer\n * .ethisys-<name>-root the plugin's own root class (all plugins use this\n * shape: ethisys-sales-root, ethisys-hr-root, …)\n * [data-ehx-plugin-portal] the portal container overlays render into\n * :where(…) of the above what {@link scopePluginCss} emits\n *\n * A selector that mentions NONE of these can match host chrome, which is the whole\n * defect class. Matching anywhere in the selector (not just leftmost) is deliberate:\n * `:where(.dark) .ethisys-sales-root` is scoped even though the root is not first.\n */\nexport const EHX_PLUGIN_SCOPE_ROOTS: readonly RegExp[] = [\n /\\.ehx-plugin-root\\b/,\n /\\.ethisys-[a-z0-9-]+-root\\b/,\n /\\[data-ehx-plugin-portal\\]/,\n];\n\nexport interface ScopePluginCssOptions {\n /** Descendant scope prefix. Default {@link EHX_PLUGIN_CSS_SCOPE}. */\n scope?: string;\n /** Replacement for `:root`/`:host`. Default {@link EHX_PLUGIN_ROOT_SCOPE}. */\n rootScope?: string;\n /** Layer names to scope. Default {@link EHX_SCOPED_CSS_LAYERS}. */\n layers?: readonly string[];\n /** What counts as scoped for the guard. Default {@link EHX_PLUGIN_SCOPE_ROOTS}. */\n scopeRoots?: readonly RegExp[];\n /**\n * Guard behaviour when a selector would leak into the host document:\n * `\"error\"` (default) fails the build, `\"warn\"` logs, `\"off\"` skips the check.\n * Only reach for anything but `\"error\"` as a deliberate, time-boxed exception.\n */\n guard?: \"error\" | \"warn\" | \"off\";\n}\n\ninterface Ctx {\n scope: string;\n rootScope: string;\n layers: Set<string>;\n}\n\n/**\n * Leading document-root selector. Matched at the START of a compound only, so\n * `:root .foo` becomes `<scope> .foo` and a `:root` deeper in a selector (which\n * would not be a document-root reference) is left alone.\n */\nconst DOCUMENT_ROOT_PREFIX = /^:(?:root|host)\\b/;\n\n// ── String scanning primitives ─────────────────────────────────────\n//\n// A hand-rolled walker rather than a CSS parser dependency: the transform runs in\n// every plugin's build, and the shapes it must survive are narrow (a compiled\n// Tailwind sheet). Escapes matter more than they look — Tailwind class names are\n// full of them (`.sm\\:flex`, `.w-\\[calc\\(100\\%-2rem\\)\\]`, `.content-\\[\\'\\{\\'\\]`),\n// and an escaped brace inside a selector would desynchronise naive brace counting.\n\nfunction isSpace(ch: string): boolean {\n return ch === \" \" || ch === \"\\n\" || ch === \"\\t\" || ch === \"\\r\" || ch === \"\\f\";\n}\n\n/** Index just past the string literal opening at `i`. */\nfunction skipString(css: string, i: number): number {\n const quote = css[i];\n let j = i + 1;\n while (j < css.length) {\n const ch = css[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === quote) return j + 1;\n j++;\n }\n return j;\n}\n\n/** Index just past the comment opening at `i`. */\nfunction skipComment(css: string, i: number): number {\n const end = css.indexOf(\"*/\", i + 2);\n return end === -1 ? css.length : end + 2;\n}\n\n/**\n * Scan from `i` to the end of a statement prelude: the `{` that opens its block,\n * or the `;` that ends a blockless statement.\n */\nfunction readPrelude(css: string, i: number): { end: number; terminator: \"{\" | \";\" | \"\" } {\n let j = i;\n let depth = 0;\n while (j < css.length) {\n const ch = css[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n j = skipString(css, j);\n continue;\n }\n if (ch === \"/\" && css[j + 1] === \"*\") {\n j = skipComment(css, j);\n continue;\n }\n if (ch === \"(\" || ch === \"[\") {\n depth++;\n } else if (ch === \")\" || ch === \"]\") {\n if (depth > 0) depth--;\n } else if (depth === 0) {\n if (ch === \"{\") return { end: j, terminator: \"{\" };\n if (ch === \";\") return { end: j + 1, terminator: \";\" };\n if (ch === \"}\") return { end: j, terminator: \"\" };\n }\n j++;\n }\n return { end: css.length, terminator: \"\" };\n}\n\n/** Index just past the `}` matching the `{` at `open`. */\nfunction matchBrace(css: string, open: number): number {\n let j = open + 1;\n let depth = 1;\n while (j < css.length) {\n const ch = css[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n j = skipString(css, j);\n continue;\n }\n if (ch === \"/\" && css[j + 1] === \"*\") {\n j = skipComment(css, j);\n continue;\n }\n if (ch === \"{\") depth++;\n else if (ch === \"}\") {\n depth--;\n if (depth === 0) return j + 1;\n }\n j++;\n }\n return css.length;\n}\n\n/** Split on commas that are not inside parens, brackets, strings or comments. */\nfunction splitTopLevel(text: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n let j = 0;\n while (j < text.length) {\n const ch = text[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n j = skipString(text, j);\n continue;\n }\n if (ch === \"/\" && text[j + 1] === \"*\") {\n j = skipComment(text, j);\n continue;\n }\n if (ch === \"(\" || ch === \"[\") depth++;\n else if (ch === \")\" || ch === \"]\") {\n if (depth > 0) depth--;\n } else if (ch === \",\" && depth === 0) {\n parts.push(text.slice(start, j));\n start = j + 1;\n }\n j++;\n }\n parts.push(text.slice(start));\n return parts;\n}\n\n// ── Transform ──────────────────────────────────────────────────────\n\nfunction atRuleName(prelude: string): string {\n const m = /^@([\\w-]*)/.exec(prelude.trim());\n return (m?.[1] ?? \"\").toLowerCase();\n}\n\n/** Layer names in an `@layer` prelude (`@layer a, b` -> [\"a\", \"b\"]). */\nfunction layerNames(prelude: string): string[] {\n const body = prelude.trim().replace(/^@layer\\s*/i, \"\");\n return splitTopLevel(body)\n .map((n) => n.trim())\n .filter(Boolean);\n}\n\n/**\n * Rewrite one selector for a plugin sheet. Two different operations, and the\n * distinction matters:\n *\n * substitution a leading `:root`/`:host` becomes the plugin root, because those\n * declarations belong on the plugin's own root. Applies in EVERY\n * layer — Tailwind emits them in `theme`, which is otherwise left\n * alone.\n * prefixing a selector in a scoped layer gains the descendant scope. Applies\n * only inside {@link EHX_SCOPED_CSS_LAYERS}.\n */\nfunction rewriteSelector(selector: string, ctx: Ctx, prefixing: boolean): string {\n if (DOCUMENT_ROOT_PREFIX.test(selector)) {\n return selector.replace(DOCUMENT_ROOT_PREFIX, ctx.rootScope);\n }\n if (!prefixing) return selector;\n // Already scoped (a re-run, or hand-written scoped CSS in a scoped layer).\n if (selector.startsWith(ctx.scope) || selector.startsWith(ctx.rootScope)) return selector;\n return `${ctx.scope} ${selector}`;\n}\n\nfunction rewriteSelectorList(selectors: string, ctx: Ctx, prefixing: boolean): string {\n const seen = new Set<string>();\n let changed = false;\n for (const part of splitTopLevel(selectors)) {\n const trimmed = part.trim();\n if (trimmed.length === 0) continue;\n const rewritten = rewriteSelector(trimmed, ctx, prefixing);\n if (rewritten !== trimmed) changed = true;\n // Dedupe: `:root, :host` substitutes to the same selector twice.\n seen.add(rewritten);\n }\n // Return the ORIGINAL text when nothing was rewritten, so an untouched rule stays\n // byte-identical (reformatting it would churn every sheet and defeat the\n // \"return null when there is nothing to do\" contract of the Vite transform).\n return changed ? [...seen].join(\",\\n\") : selectors;\n}\n\nfunction walk(css: string, scoping: boolean, ctx: Ctx): string {\n let out = \"\";\n let i = 0;\n while (i < css.length) {\n const ch = css[i];\n if (isSpace(ch)) {\n out += ch;\n i++;\n continue;\n }\n if (ch === \"/\" && css[i + 1] === \"*\") {\n const end = skipComment(css, i);\n out += css.slice(i, end);\n i = end;\n continue;\n }\n // A stray `}` (malformed input): copy and carry on rather than throw.\n if (ch === \"}\") {\n out += ch;\n i++;\n continue;\n }\n\n const { end, terminator } = readPrelude(css, i);\n if (terminator !== \"{\") {\n // `@layer mui;`, `@import …;`, a bare declaration: nothing to scope.\n out += css.slice(i, end);\n i = end;\n continue;\n }\n\n const raw = css.slice(i, end);\n const blockEnd = matchBrace(css, end);\n const inner = css.slice(end + 1, blockEnd - 1);\n\n if (raw.trimStart().startsWith(\"@\")) {\n const name = atRuleName(raw);\n if (VERBATIM_AT_RULES.has(name) || !CONDITIONAL_AT_RULES.has(name)) {\n out += css.slice(i, blockEnd);\n } else {\n const nextScoping =\n name === \"layer\" ? scoping || layerNames(raw).some((n) => ctx.layers.has(n)) : scoping;\n out += `${raw}{${walk(inner, nextScoping, ctx)}}`;\n }\n } else {\n // Style rule. The BODY is copied verbatim: a nested rule inside it is\n // relative to this selector, so scoping the parent scopes it too.\n const trailing = /\\s*$/.exec(raw)?.[0] ?? \"\";\n const selectors = raw.slice(0, raw.length - trailing.length);\n const rewritten = rewriteSelectorList(selectors, ctx, scoping);\n out += rewritten === selectors ? css.slice(i, blockEnd) : `${rewritten}${trailing}{${inner}}`;\n }\n i = blockEnd;\n }\n return out;\n}\n\n/**\n * Prefix every selector inside a plugin's UNSCOPED cascade layers with the plugin\n * scope, so injecting the sheet into the host document cannot restyle host chrome.\n *\n * Pure and idempotent — running it twice is a no-op, so a rebuild or a second pass\n * over already-scoped CSS is safe. See {@link EHX_SCOPED_CSS_LAYERS} for which\n * layers are rewritten and why the others need no treatment.\n */\nexport function scopePluginCss(css: string, options: ScopePluginCssOptions = {}): string {\n const ctx: Ctx = {\n scope: options.scope ?? EHX_PLUGIN_CSS_SCOPE,\n rootScope: options.rootScope ?? EHX_PLUGIN_ROOT_SCOPE,\n layers: new Set(options.layers ?? EHX_SCOPED_CSS_LAYERS),\n };\n return walk(css, false, ctx);\n}\n\n/**\n * Every selector in `css` that mentions no plugin scope root, i.e. every selector\n * that can reach host chrome once the sheet is injected into the host document.\n *\n * The invariant this checks is the whole convention: **a plugin never emits an\n * unscoped selector.** {@link scopePluginCss} satisfies it automatically for the\n * layers Tailwind generates; everything else is authored, and this is what catches\n * an author (or a stray `@import \"tailwindcss\"` re-emitting global preflight) who\n * did not. Pure, so a plugin's own build script or test can call it directly.\n */\nexport function findUnscopedSelectors(\n css: string,\n options: Pick<ScopePluginCssOptions, \"scopeRoots\"> = {},\n): string[] {\n const roots = options.scopeRoots ?? EHX_PLUGIN_SCOPE_ROOTS;\n const found: string[] = [];\n collectSelectors(css, (selector) => {\n if (!roots.some((re) => re.test(selector))) found.push(selector);\n });\n return found;\n}\n\n/** Visit every style-rule selector in `css`, at any nesting depth. */\nfunction collectSelectors(css: string, visit: (selector: string) => void): void {\n let i = 0;\n while (i < css.length) {\n const ch = css[i];\n if (isSpace(ch) || ch === \"}\") {\n i++;\n continue;\n }\n if (ch === \"/\" && css[i + 1] === \"*\") {\n i = skipComment(css, i);\n continue;\n }\n const { end, terminator } = readPrelude(css, i);\n if (terminator !== \"{\") {\n i = end;\n continue;\n }\n const raw = css.slice(i, end).trim();\n const blockEnd = matchBrace(css, end);\n if (raw.startsWith(\"@\")) {\n // Descend through wrappers; never into keyframes/descriptor blocks, whose\n // \"selectors\" are keyframe offsets or descriptor names.\n const name = atRuleName(raw);\n if (CONDITIONAL_AT_RULES.has(name) && !VERBATIM_AT_RULES.has(name)) {\n collectSelectors(css.slice(end + 1, blockEnd - 1), visit);\n }\n } else {\n for (const part of splitTopLevel(raw)) {\n const selector = part.trim();\n // `&`-relative nested rules inherit the parent's scope.\n if (selector.length > 0 && !selector.startsWith(\"&\")) visit(selector);\n }\n // A nested rule inside this body is covered by its parent's scope, so there\n // is nothing further to check here.\n }\n i = blockEnd;\n }\n}\n\nconst MAX_REPORTED_LEAKS = 12;\n\n/** The build-failure message: what leaked, why it matters, and the usual cause. */\nexport function formatUnscopedSelectorError(id: string, leaks: readonly string[]): string {\n const shown = leaks.slice(0, MAX_REPORTED_LEAKS);\n const more = leaks.length - shown.length;\n return [\n `${leaks.length} selector(s) in ${id} would leak into the host document.`,\n \"\",\n \"A plugin's compiled CSS is injected into the HOST <head>, so every selector must\",\n \"be scoped to a plugin root (`.ehx-plugin-root`, `.ethisys-<name>-root`) or the\",\n \"portal marker `[data-ehx-plugin-portal]`. Unscoped selectors restyle host chrome.\",\n \"\",\n ...shown.map((s) => ` ${s}`),\n ...(more > 0 ? [` … and ${more} more`] : []),\n \"\",\n 'Most common cause: `@import \"tailwindcss\"` re-emits Tailwind\\'s global preflight.',\n \"Use the split import so the host's own preflight governs shared resets:\",\n ' @import \"@ethisyscore/plugin-ui/plugin-base.css\";',\n ' @import \"tailwindcss/theme.css\" layer(theme) source(none);',\n ' @import \"tailwindcss/utilities.css\" layer(utilities) source(none);',\n ].join(\"\\n\");\n}\n\n/** True for ids whose transform payload is plain CSS text we may rewrite. */\nexport function isScopableCssId(id: string): boolean {\n const qIndex = id.indexOf(\"?\");\n const path = qIndex === -1 ? id : id.slice(0, qIndex);\n const query = qIndex === -1 ? \"\" : id.slice(qIndex + 1);\n if (!path.endsWith(\".css\")) return false;\n // CSS modules are consumed through a class-name map, not injected wholesale.\n if (path.endsWith(\".module.css\")) return false;\n // `?raw` / `?url` payloads are the untransformed source or a path, not compiled CSS.\n if (/(?:^|&)(?:raw|url)(?:=|&|$)/.test(query)) return false;\n return true;\n}\n\n/**\n * Vite plugin form of {@link scopePluginCss} PLUS the guard that makes it a\n * convention rather than a courtesy, injected into every PlatformReact page\n * sub-build by `buildPlatformReactPages`.\n *\n * Scoping Tailwind's generated layers is automatic; the guard fails the build if\n * anything ELSE in the sheet is still unscoped (see\n * {@link findUnscopedSelectors}). Together they are the enforceable form of one\n * rule: a plugin never emits an unscoped selector into the host document. Prose in\n * a standards doc did not hold across seven repos — the leak that prompted this\n * shipped seven times, and the documented no-preflight rule was violated once\n * without anyone noticing.\n *\n * Deliberately declares NO `enforce`. Vite resolves plugins in the order\n * `[…prePlugins, vite:css, …normalPlugins, vite:css-post, …postPlugins]`, so a\n * plugin with no `enforce` is the only position that sees compiled CSS:\n *\n * - `@tailwindcss/vite` is `enforce: \"pre\"` and returns the generated sheet, so\n * the utilities exist by the time this runs.\n * - `vite:css-post` serialises a `*.css?inline` import into `export default \"…\"`.\n * `enforce: \"post\"` runs AFTER that and would be handed JavaScript, where the\n * CSS is an escaped string literal.\n */\nexport function scopePluginCssPlugin(options: ScopePluginCssOptions = {}): Plugin {\n return {\n name: \"ethisys-scope-plugin-css\",\n transform(code: string, id: string) {\n if (!isScopableCssId(id)) return null;\n const scoped = scopePluginCss(code, options);\n\n const guard = options.guard ?? \"error\";\n if (guard !== \"off\") {\n const leaks = findUnscopedSelectors(scoped, options);\n if (leaks.length > 0) {\n const message = formatUnscopedSelectorError(id, leaks);\n // Prefer the Rollup context (it frames the error with the plugin + file);\n // fall back to a plain throw so the guard still bites when the hook is\n // called directly, as a plugin's own check script or a test does.\n const ctx = this as { error?: (m: string) => never; warn?: (m: string) => void } | undefined;\n if (guard === \"error\") {\n if (ctx?.error) ctx.error(message);\n throw new Error(message);\n }\n if (ctx?.warn) ctx.warn(message);\n else console.warn(message);\n }\n }\n\n // Selector rewriting invalidates the CSS sourcemap; `?inline` CSS ships as a\n // string inside the page bundle, so there is no CSS map to preserve.\n return scoped === code ? null : { code: scoped, map: null };\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport type { InlineConfig, Plugin } from \"vite\";\nimport { escapeRegExp } from \"../utils/strings\";\nimport { scopePluginCssPlugin } from \"./scope-plugin-css\";\n\n// ── The PlatformReact host-realm contract (shared defaults) ────────\n//\n// A PlatformReact page is ONE self-contained ESM bundle the host loads via\n// `import(url)` at mount time. These two lists are the build-side half of the\n// host contract; both are overridable, but every migration starts from them.\n\n/**\n * Specifiers the host realm provides at runtime — never bundled into a page.\n * A `components/ui/*` abstraction that re-exports `@mui/material` therefore\n * costs zero bundle weight and shares the host's MUI singleton + theme.\n */\nexport const PLATFORM_REACT_EXTERNALS: readonly string[] = [\n \"react\",\n \"react/jsx-runtime\",\n \"react-dom\",\n \"@mui/material\",\n \"@mui/icons-material\",\n \"@emotion/react\",\n \"@emotion/styled\",\n \"date-fns\",\n \"@ethisyscore/components-react\",\n \"@ethisyscore/extension-runtime\",\n \"@ethisyscore/extension-runtime/plugin\",\n];\n\n/**\n * Bundled deps that MUST resolve to a single copy. When a bundled dep (e.g.\n * `@tanstack/react-query`) is imported by BOTH the plugin's own hooks and the\n * SDK foundation (aliased cross-repo to a sibling `dist`), the bundler otherwise\n * resolves two copies — one per repo's `node_modules`. Two module instances =\n * two React contexts, so a provider in one is invisible to a consumer in the\n * other (the classic \"No QueryClient set\"). Pin them to one copy.\n */\nexport const PLATFORM_REACT_DEDUPE: readonly string[] = [\n \"@tanstack/react-query\",\n \"react\",\n \"react-dom\",\n \"@ethisyscore/extension-runtime\",\n];\n\nconst DEFAULT_OUT_DIR = \"dist\";\nconst DEFAULT_OUTPUT_PREFIX = \"platform-react\";\nconst DEFAULT_DEFINE_PLUGIN_PAGE = \"@/app/definePluginPage\";\nconst DEFAULT_DEFINE_PLUGIN_OVERLAY = \"@/app/definePluginOverlay\";\nconst DEFAULT_SRC_DIR = \"src\";\nconst DEFAULT_ALIAS_PREFIX = \"@\";\nconst SUMMARY_FILENAME = \"platform-react-pages.json\";\nconst DIGEST_MAP_FILENAME = \"platform-react-digest-map.json\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/** A `resolve.alias` entry (string or regex find), as Vite accepts. */\nexport interface PlatformReactAlias {\n find: string | RegExp;\n replacement: string;\n}\n\n/**\n * One surface declared in `feature.manifest.json` (`ui.platformReactPages[]`).\n * `views` is the page's `useView` manifest slice — the adapter-view modules it\n * renders by name (`{ DayView: \"src/adapter/<feature>/DayView.tsx\" }`). It rides\n * along as an open extra field the SDK's manifest readers ignore.\n */\nexport interface PlatformReactPageInput {\n id: string;\n moduleSpecifier: string;\n exportName?: string;\n title?: string | null;\n views?: Record<string, string>;\n}\n\n/**\n * The singular overlay declared in `feature.manifest.json` (`ui.platformReactOverlay`,\n * WI 5160 SP-A). Same shape as {@link PlatformReactPageInput} minus `route` — an overlay\n * is never routed. `views` is its `useView` manifest slice, synthesised into the virtual\n * entry exactly as page `views` are.\n */\nexport interface PlatformReactOverlayInput {\n id: string;\n moduleSpecifier: string;\n exportName?: string;\n title?: string | null;\n views?: Record<string, string>;\n}\n\n/** The fully-resolved per-page build context handed to the (injectable) builder. */\nexport interface PlatformReactBuildContext {\n pageId: string;\n /** Virtual entry module id (`\\0virtual:surface/<id>`). */\n entryId: string;\n /** Rollup plugin that resolves + loads the synthesised virtual entry. */\n surfacePlugin: Plugin;\n root: string;\n outDir: string;\n outputPrefix: string;\n external: readonly string[];\n dedupe: readonly string[];\n alias: PlatformReactAlias[];\n plugins: Plugin[];\n target: string;\n minify: boolean;\n sourcemap: boolean;\n}\n\n/** Low-level Vite `build` function. Defaults to a dynamic `import(\"vite\")`. */\nexport type ViteBuildFn = (config: InlineConfig) => Promise<unknown>;\n\n/** Injectable per-page builder. Defaults to a real Vite library build. */\nexport type PlatformReactViteBuild = (ctx: PlatformReactBuildContext) => Promise<void>;\n\nexport interface BuildPlatformReactPagesOptions {\n /** Root the manifest + `src/…` paths resolve against. Default `process.cwd()`. */\n root?: string;\n /** Manifest path (relative to `root`). Default `feature.manifest.json`. */\n manifestPath?: string;\n /** Inline manifest object (test injection). When omitted, read from disk. */\n manifest?: unknown;\n /** Output directory the bundles + companion JSON land in. Default `dist`. */\n outDir?: string;\n /** Sub-directory + summary/digest key prefix. Default `platform-react`. */\n outputPrefix?: string;\n /** Plugin-specific `resolve.alias` entries (contracts, router shim, `@/`, …). */\n alias?: PlatformReactAlias[];\n /** Plugin-specific Vite plugins (e.g. `react()`, `tailwindcss()`). */\n plugins?: Plugin[];\n /** Bundled deps to dedupe. Default {@link PLATFORM_REACT_DEDUPE}. */\n dedupe?: readonly string[];\n /** Host externals. Default {@link PLATFORM_REACT_EXTERNALS}. */\n external?: readonly string[];\n /** Module specifier the generated entry imports `definePluginPage` from. */\n definePluginPageSpecifier?: string;\n /** Module specifier the generated overlay entry imports `definePluginOverlay` from. */\n definePluginOverlaySpecifier?: string;\n /** Source dir stripped when rewriting manifest paths to the alias. Default `src`. */\n srcDir?: string;\n /** Alias prefix manifest `src/…` paths are rewritten to. Default `@` (→ `@/…`). */\n aliasPrefix?: string;\n /** Rollup build target. Default `es2022`. */\n target?: string;\n /** Minify output. Default `false` (digest stability + debuggability). */\n minify?: boolean;\n /** Emit sourcemaps. Default `true`. */\n sourcemap?: boolean;\n /** Wipe `outDir` before building. Default `true`. */\n clean?: boolean;\n /** Progress logger. Default `console`. */\n logger?: Pick<Console, \"log\" | \"warn\">;\n /** Low-level Vite `build` (production override so the CONSUMER's vite is used). */\n viteBuild?: ViteBuildFn;\n /** Injectable per-page builder (test injection — skips Vite entirely). */\n build?: PlatformReactViteBuild;\n /** Injectable bundle reader for digesting. Default `fs.readFileSync` (utf-8). */\n readFile?: (path: string) => string;\n /** Injectable file writer. Default `fs.writeFileSync` (creating dirs). */\n writeFile?: (path: string, contents: string) => void;\n}\n\n/** One built surface (a page, or the singular overlay) as recorded in the companion summary. */\nexport interface PlatformReactSurfaceSummary {\n id: string;\n exportName: string;\n title: string | null;\n bundlePath: string;\n source: string;\n}\n\n/** One emitted bundle's SHA-256, keyed by its dist-relative path. */\nexport interface PlatformReactDigest {\n path: string;\n sha256: string;\n}\n\nexport interface PlatformReactBuildSummary {\n pages: PlatformReactSurfaceSummary[];\n /** The singular overlay, when the manifest declares `ui.platformReactOverlay`. */\n overlay?: PlatformReactSurfaceSummary;\n digests: PlatformReactDigest[];\n summaryPath: string | null;\n digestMapPath: string | null;\n}\n\n// ── Generic transforms (exported for focused unit tests) ───────────\n\n/**\n * Rollup output pass: rewrite aliased named imports from host externals into the\n * namespace-import form the host's PlatformReact loader accepts.\n *\n * esbuild emits `import { Dialog as Dialog$1 } from \"@mui/material\"` to\n * deconflict a name collision (an adapter view imports MUI `Dialog` directly\n * while a feature component pulls in the `components/ui/dialog` wrapper of the\n * same name). The host loader handles `import * as X`, plain `import { Y }`,\n * default imports, and aliased EXPORTS — but throws \"Unexpected identifier 'as'\"\n * on aliased named IMPORTS `{ X as Y }`. In a final `inlineDynamicImports`\n * bundle every remaining `import { … } from \"…\"` is an EXTERNAL import, so\n * rewriting any that contain `as` into `import * as ns from \"…\"; const local =\n * ns.imported, …;` is safe and removes the only construct the loader rejects.\n * Runs in `renderChunk`, before the host-verified digest is computed.\n */\nexport function rewriteAliasedExternalImports(): Plugin {\n return {\n name: \"rewrite-aliased-external-imports\",\n renderChunk(code: string) {\n let counter = 0;\n let changed = false;\n const out = code.replace(\n // Optional default binding (`import Foo, { … }`) then the named braces.\n /\\bimport\\s+(?:([\\w$]+)\\s*,\\s*)?\\{([^{}]*)\\}\\s*from\\s*(\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*')\\s*;?/g,\n (full, def: string | undefined, specs: string, mod: string) => {\n if (!/\\sas\\s/.test(specs)) return full;\n changed = true;\n const ns = `__ns_imp_${counter++}`;\n const decls = specs\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((s) => {\n const [imported, local] = s.split(/\\s+as\\s+/).map((t) => t.trim());\n return `${local ?? imported} = ${ns}.${imported}`;\n })\n .join(\", \");\n // Keep any default import as-is (no alias → host-safe), namespace the named part.\n const defPart = def ? `import ${def} from ${mod}; ` : \"\";\n return `${defPart}import * as ${ns} from ${mod}; const ${decls};`;\n },\n );\n return changed ? { code: out, map: null } : null;\n },\n };\n}\n\n/**\n * Synthesise one isolated PlatformReact entry per surface straight from its\n * manifest declaration: `definePluginPage(Page, { …views })`, importing ONLY\n * that surface's page (`moduleSpecifier`) + adapter views (`views`) so each\n * bundle stays self-contained. Returned as a Rollup virtual module so there are\n * no physical per-page entry files — the manifest is the single source of truth.\n * `src/…` paths are rewritten to the alias the build resolves (e.g. `@/…`).\n */\nexport function virtualPageEntry(\n page: PlatformReactPageInput,\n config: { definePluginPageSpecifier: string; toAlias: (p: string) => string },\n): { id: string; plugin: Plugin } {\n const VIRTUAL_ID = `\\0virtual:surface/${page.id}`;\n const views = page.views ?? {};\n const names = Object.keys(views);\n const viewImports = names\n .map((n) => `import { ${n} } from ${JSON.stringify(config.toAlias(views[n]))};`)\n .join(\"\\n\");\n const src =\n `import Page from ${JSON.stringify(config.toAlias(page.moduleSpecifier))};\\n` +\n `${viewImports}\\n` +\n `import { definePluginPage } from ${JSON.stringify(config.definePluginPageSpecifier)};\\n` +\n `export default definePluginPage(Page, { ${names.join(\", \")} });\\n`;\n return {\n id: VIRTUAL_ID,\n plugin: {\n name: `virtual-surface-${page.id}`,\n resolveId: (id: string) => (id === VIRTUAL_ID ? VIRTUAL_ID : null),\n load: (id: string) => (id === VIRTUAL_ID ? src : null),\n },\n };\n}\n\n/**\n * Overlay counterpart of {@link virtualPageEntry}: synthesise the singular overlay's\n * isolated entry as `definePluginOverlay(Overlay, { …views })`. Identical to the page\n * entry except the definer — an overlay is never routed.\n */\nexport function virtualOverlayEntry(\n overlay: PlatformReactOverlayInput,\n config: { definePluginOverlaySpecifier: string; toAlias: (p: string) => string },\n): { id: string; plugin: Plugin } {\n const VIRTUAL_ID = `\\0virtual:surface/${overlay.id}`;\n const views = overlay.views ?? {};\n const names = Object.keys(views);\n const viewImports = names\n .map((n) => `import { ${n} } from ${JSON.stringify(config.toAlias(views[n]))};`)\n .join(\"\\n\");\n // Honour a non-default `exportName`: import the overlay under that name from the\n // source module, and re-export the WRAPPED overlay under it too. The host loader\n // reads `bundle[exportName]` at mount, so a default-only import/export would both\n // pull the wrong symbol from source AND emit a bundle missing that export. The\n // default case keeps the terse `import X from` / `export default` form.\n const exportName =\n typeof overlay.exportName === \"string\" && overlay.exportName.length > 0\n ? overlay.exportName\n : \"default\";\n const overlayModule = JSON.stringify(config.toAlias(overlay.moduleSpecifier));\n const overlayImport =\n exportName === \"default\"\n ? `import Overlay from ${overlayModule};`\n : `import { ${exportName} as Overlay } from ${overlayModule};`;\n const overlayExport =\n exportName === \"default\"\n ? `export default definePluginOverlay(Overlay, { ${names.join(\", \")} });`\n : `const __ehxOverlay = definePluginOverlay(Overlay, { ${names.join(\", \")} });\\n` +\n `export { __ehxOverlay as ${exportName} };\\n` +\n `export default __ehxOverlay;`;\n const src =\n `${overlayImport}\\n` +\n `${viewImports}\\n` +\n `import { definePluginOverlay } from ${JSON.stringify(config.definePluginOverlaySpecifier)};\\n` +\n `${overlayExport}\\n`;\n return {\n id: VIRTUAL_ID,\n plugin: {\n name: `virtual-surface-${overlay.id}`,\n resolveId: (id: string) => (id === VIRTUAL_ID ? VIRTUAL_ID : null),\n load: (id: string) => (id === VIRTUAL_ID ? src : null),\n },\n };\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction defaultWriteFile(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n}\n\nfunction readManifest(options: BuildPlatformReactPagesOptions, root: string): unknown {\n if (options.manifest !== undefined) {\n return options.manifest;\n }\n const rel = options.manifestPath ?? \"feature.manifest.json\";\n const abs = isAbsolute(rel) ? rel : resolve(root, rel);\n if (!existsSync(abs)) {\n return null;\n }\n const raw = readFileSync(abs, \"utf-8\");\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${abs}\": ${(e as Error).message}`,\n );\n }\n}\n\n/** Build the real per-page Vite config and run it through the (injectable) vite build. */\nfunction makeDefaultBuild(viteBuild?: ViteBuildFn): PlatformReactViteBuild {\n return async (ctx) => {\n const build: ViteBuildFn = viteBuild ?? (await import(\"vite\")).build;\n await build({\n root: ctx.root,\n configFile: false,\n // `scopePluginCssPlugin` must sit AFTER the plugin's own `tailwindcss()` in\n // effect, which it does by enforce ordering, not array position: Tailwind is\n // `enforce: \"pre\"`, this one declares none. See its doc for why \"none\" is the\n // only position that sees compiled CSS.\n plugins: [\n ctx.surfacePlugin,\n ...ctx.plugins,\n scopePluginCssPlugin(),\n rewriteAliasedExternalImports(),\n ],\n resolve: {\n dedupe: [...ctx.dedupe],\n alias: ctx.alias,\n },\n build: {\n target: ctx.target,\n outDir: ctx.outDir,\n emptyOutDir: false,\n assetsDir: \"\",\n minify: ctx.minify,\n sourcemap: ctx.sourcemap,\n rollupOptions: {\n input: { [ctx.pageId]: ctx.entryId },\n preserveEntrySignatures: \"strict\",\n external: [...ctx.external],\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${ctx.outputPrefix}/[name].js`,\n chunkFileNames: `${ctx.outputPrefix}/[name]-[hash].js`,\n assetFileNames: `${ctx.outputPrefix}/[name][extname]`,\n },\n },\n },\n logLevel: \"warn\",\n });\n };\n}\n\n// ── Orchestration ──────────────────────────────────────────────────\n\n/**\n * Build every `ui.platformReactPages[]` surface as its own self-contained ESM\n * bundle and emit the companion `platform-react-pages.json` summary + the\n * per-asset SHA-256 `platform-react-digest-map.json` the host's verified loader\n * and the `.ccpkg` packaging step read.\n *\n * Each PlatformReact page must be ONE bundle (`inlineDynamicImports: true`), and\n * Rollup rejects that with more than one input — so this runs one Vite sub-build\n * per surface, each with a single synthesised virtual entry (see\n * {@link virtualPageEntry}). The generic seams (host externals, dedupe, the\n * host-loader aliased-import rewrite, the digest/summary contract) live here;\n * the plugin supplies only its `alias` entries + `plugins` (and, in production,\n * its own `viteBuild` so the consumer's Vite is used, not the SDK's).\n *\n * No-op (returns empty) when no pages are declared.\n */\nexport async function buildPlatformReactPages(\n options: BuildPlatformReactPagesOptions = {},\n): Promise<PlatformReactBuildSummary> {\n const root = options.root ?? process.cwd();\n const logger = options.logger ?? console;\n const manifest = readManifest(options, root);\n\n const ui = (\n manifest as { ui?: { platformReactPages?: unknown[]; platformReactOverlay?: unknown } } | null\n )?.ui;\n const declared = ui?.platformReactPages;\n const overlayDecl = ui?.platformReactOverlay;\n const hasPages = Array.isArray(declared) && declared.length > 0;\n const hasOverlay = overlayDecl !== undefined && overlayDecl !== null;\n if (!hasPages && !hasOverlay) {\n logger.warn(\n \"[build-pages] no platformReactPages or platformReactOverlay declared — nothing to build\",\n );\n return { pages: [], digests: [], summaryPath: null, digestMapPath: null };\n }\n\n // Validate the fields this pass consumes (the open `views` field rides along).\n const seen = new Set<string>();\n const pages: PlatformReactPageInput[] = (hasPages ? declared! : []).map((raw, i) => {\n const decl = raw as PlatformReactPageInput;\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(`[build-pages] ui.platformReactPages[${i}].id is required (non-empty string).`);\n }\n if (seen.has(decl.id)) {\n throw new Error(`[build-pages] Duplicate page id \"${decl.id}\".`);\n }\n seen.add(decl.id);\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(`[build-pages] surface \"${decl.id}\" has no moduleSpecifier in the manifest.`);\n }\n return decl;\n });\n\n // The singular overlay (WI 5160 SP-A). Its id must not collide with a page id — a\n // shared id would overwrite one bundle with the other's Rollup input.\n let overlay: PlatformReactOverlayInput | null = null;\n if (hasOverlay) {\n const decl = overlayDecl as PlatformReactOverlayInput;\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(`[build-pages] ui.platformReactOverlay.id is required (non-empty string).`);\n }\n if (seen.has(decl.id)) {\n throw new Error(\n `[build-pages] ui.platformReactOverlay.id \"${decl.id}\" collides with a page id — ids must be unique across pages and the overlay.`,\n );\n }\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(`[build-pages] ui.platformReactOverlay \"${decl.id}\" has no moduleSpecifier in the manifest.`);\n }\n overlay = decl;\n }\n\n const outDir = options.outDir ?? DEFAULT_OUT_DIR;\n const outDirAbs = isAbsolute(outDir) ? outDir : resolve(root, outDir);\n const outputPrefix = (options.outputPrefix ?? DEFAULT_OUTPUT_PREFIX).replace(/^\\/+|\\/+$/g, \"\");\n const outputPrefixDir = resolve(outDirAbs, outputPrefix);\n\n const external = options.external ?? PLATFORM_REACT_EXTERNALS;\n const dedupe = options.dedupe ?? PLATFORM_REACT_DEDUPE;\n const alias = options.alias ?? [];\n const plugins = options.plugins ?? [];\n const definePluginPageSpecifier = options.definePluginPageSpecifier ?? DEFAULT_DEFINE_PLUGIN_PAGE;\n const definePluginOverlaySpecifier =\n options.definePluginOverlaySpecifier ?? DEFAULT_DEFINE_PLUGIN_OVERLAY;\n const srcDir = options.srcDir ?? DEFAULT_SRC_DIR;\n const aliasPrefix = options.aliasPrefix ?? DEFAULT_ALIAS_PREFIX;\n const srcRe = new RegExp(`^${escapeRegExp(srcDir)}/`);\n const toAlias = (p: string) => `${aliasPrefix}/${p.replace(srcRe, \"\")}`;\n\n const write = options.writeFile ?? defaultWriteFile;\n const read = options.readFile ?? ((p: string) => readFileSync(p, \"utf-8\"));\n const runBuild = options.build ?? makeDefaultBuild(options.viteBuild);\n\n if (options.clean ?? true) {\n if (existsSync(outDirAbs)) {\n rmSync(outDirAbs, { recursive: true, force: true });\n }\n mkdirSync(outputPrefixDir, { recursive: true });\n }\n\n for (const page of pages) {\n const { id: entryId, plugin: surfacePlugin } = virtualPageEntry(page, {\n definePluginPageSpecifier,\n toAlias,\n });\n logger.log(`[build-pages] ${page.id} ← ${page.moduleSpecifier}`);\n await runBuild({\n pageId: page.id,\n entryId,\n surfacePlugin,\n root,\n outDir: outDirAbs,\n outputPrefix,\n external,\n dedupe,\n alias,\n plugins,\n target: options.target ?? \"es2022\",\n minify: options.minify ?? false,\n sourcemap: options.sourcemap ?? true,\n });\n }\n\n // The singular overlay builds through the same isolated-sub-build path as a page —\n // one self-contained ESM bundle at `platform-react/<id>.js`.\n if (overlay) {\n const { id: entryId, plugin: surfacePlugin } = virtualOverlayEntry(overlay, {\n definePluginOverlaySpecifier,\n toAlias,\n });\n logger.log(`[build-pages] ${overlay.id} ← ${overlay.moduleSpecifier} (overlay)`);\n await runBuild({\n pageId: overlay.id,\n entryId,\n surfacePlugin,\n root,\n outDir: outDirAbs,\n outputPrefix,\n external,\n dedupe,\n alias,\n plugins,\n target: options.target ?? \"es2022\",\n minify: options.minify ?? false,\n sourcemap: options.sourcemap ?? true,\n });\n }\n\n // Companion summary the host loader + `.ccpkg` packaging reads.\n const summaryPages = pages.map((p) => ({\n id: p.id,\n exportName: p.exportName ?? \"default\",\n title: p.title ?? null,\n bundlePath: `${outputPrefix}/${p.id}.js`,\n source: p.moduleSpecifier,\n }));\n const summaryOverlay = overlay\n ? {\n id: overlay.id,\n exportName: overlay.exportName ?? \"default\",\n title: overlay.title ?? null,\n bundlePath: `${outputPrefix}/${overlay.id}.js`,\n source: overlay.moduleSpecifier,\n }\n : undefined;\n const summaryPath = resolve(outputPrefixDir, SUMMARY_FILENAME);\n write(\n summaryPath,\n JSON.stringify(\n summaryOverlay ? { pages: summaryPages, overlay: summaryOverlay } : { pages: summaryPages },\n null,\n 2,\n ),\n );\n\n // Per-asset SHA-256 digest map. Hash each emitted bundle's UTF-8 bytes off\n // disk (one self-contained ESM chunk per page — `inlineDynamicImports`), keyed\n // by the dist-relative path, so the host's verified loader can check each\n // bundle before eval and packaging can lift these into `assetDigests`.\n const digests = [\n ...pages.map((p) => `${outputPrefix}/${p.id}.js`),\n ...(overlay ? [`${outputPrefix}/${overlay.id}.js`] : []),\n ]\n .sort()\n .map((relPath) => {\n const code = read(resolve(outDirAbs, relPath));\n return { path: relPath, sha256: createHash(\"sha256\").update(code, \"utf8\").digest(\"hex\") };\n });\n const digestMapPath = resolve(outputPrefixDir, DIGEST_MAP_FILENAME);\n write(digestMapPath, JSON.stringify({ digests }, null, 2));\n\n logger.log(\n `[build-pages] emitted ${pages.length} page(s)${overlay ? \" + 1 overlay\" : \"\"} + summary + digest map (${digests.length} digests)`,\n );\n\n return { pages: summaryPages, overlay: summaryOverlay, digests, summaryPath, digestMapPath };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Plugin } from \"vite\";\nimport { slash } from \"../utils/strings\";\nimport { PLATFORM_REACT_EXTERNALS } from \"./build-pages\";\nimport { scopePluginCssPlugin } from \"./scope-plugin-css\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A single PlatformReact page declaration extracted from\n * `ui.platformReactPages[]` in the manifest. Aligns with the typed interface\n * defined in `ethisyscore-protocol` RFC 0003.\n *\n * - `id` is the host-side page identifier and the basename of the emitted\n * bundle (e.g. `id: \"dashboard\"` → `platform-react/dashboard.js`).\n * - `moduleSpecifier` is a host-origin relative path to the page module — the\n * plugin author's source entry that Rollup bundles.\n * - `exportName` is the named export Rollup keeps live in the bundle. The host\n * loader reads `bundle[exportName]` at mount time.\n * - `title` is an optional display label for the host's surface chrome.\n */\nexport interface PlatformReactPageDeclaration {\n id?: string;\n moduleSpecifier?: string;\n exportName?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n/**\n * The singular PlatformReact overlay declaration extracted from\n * `ui.platformReactOverlay` in the manifest (WI 5160 SP-A).\n * At most one overlay is permitted per plugin manifest.\n *\n * - `id` is the host-side overlay identifier and the basename of the emitted\n * bundle (e.g. `id: \"ai-overlay\"` → `platform-react/ai-overlay.js`).\n * - `moduleSpecifier` is a host-origin relative path to the overlay module.\n * - `exportName` is the named export the host loader reads at mount time.\n * - `title` is an optional display label for the host's surface chrome.\n */\nexport interface PlatformReactOverlayDeclaration {\n id?: string;\n moduleSpecifier?: string;\n exportName?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n/**\n * The subset of a manifest this pass consumes. Manifests are tolerated as a\n * superset — extra fields are ignored so newer-schema manifests still load.\n */\nexport interface PlatformReactManifest {\n type?: string;\n ui?: {\n platformReactPages?: PlatformReactPageDeclaration[];\n platformReactOverlay?: PlatformReactOverlayDeclaration; // WI 5160 SP-A — singular\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the PlatformReact Vite pass.\n */\nexport interface PlatformReactPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted page assets and the companion manifest.\n * Defaults to `platform-react/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\ninterface ResolvedPage {\n id: string;\n exportName: string;\n title: string | null;\n moduleSpecifierRel: string;\n moduleSpecifierAbs: string;\n}\n\n// M-1: ResolvedOverlay is structurally identical to ResolvedPage — use a type alias (DRY).\ntype ResolvedOverlay = ResolvedPage;\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore PlatformReact pages\n * (RFC 0003: the high-trust, host-extension tier). For each entry under\n * `ui.platformReactPages[]` in the manifest, registers a Rollup input that\n * emits an ESM bundle the host loads via `import()` at surface mount time.\n *\n * Behaviour:\n * - For each declared page: registers `{ \"platform-react/<id>\": <moduleSpecifier> }`\n * in Rollup's input table. Output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so each page ships as ONE bundled module.\n * - Emits a `platform-react/platform-react-pages.json` companion asset listing\n * the declared pages so the host (and the `.ccpkg` packaging step) can\n * inspect what the build produced.\n * - When `ui.platformReactPages` is absent or empty: the pass is a no-op.\n * Composition is expected — the recommended template registers this pass\n * alongside Contract A / Contract B so a single Vite config covers every\n * render mode.\n *\n * Origin enforcement of the bundle URL at runtime is the host's responsibility\n * (see `PlatformReactSurfaceMount.tsx` in `coreconnect-web`). This pass only\n * blocks remote/absolute paths at the manifest layer so a malformed manifest\n * fails fast.\n *\n * Returns an ARRAY: this pass plus the plugin-CSS scoping pass it must always be\n * paired with. Vite flattens nested plugin arrays (`PluginOption` is recursively\n * `PluginOption[]`), so existing call sites\n * (`plugins: [react(), tailwindcss(), ethisysPlatformReactPlugin()]`) are unaffected.\n *\n * The pairing CANNOT be done by returning `{ plugins: [...] }` from this pass's own\n * `config()` hook: Vite resolves the plugin container before running config hooks, so\n * a plugin injected there is dropped SILENTLY (no warning, build still green) and the\n * scoping pass would never run. Anything needing the page pass on its own as a single\n * `Plugin` should call `ethisysPlatformReactPagesPlugin` and compose the scoping pass\n * itself.\n */\nexport function ethisysPlatformReactPlugin(\n options: PlatformReactPluginOptions = {},\n): Plugin[] {\n return [ethisysPlatformReactPagesPlugin(options), scopePluginCssPlugin()];\n}\n\n/**\n * The PlatformReact page-bundle pass ALONE, as a single `Plugin`.\n *\n * Prefer {@link ethisysPlatformReactPlugin}, which pairs this with the plugin-CSS\n * scoping pass. Reach for this only when composing the passes by hand (a plugin with\n * its own scoping step, or a test that drives one pass's hooks directly) — used on its\n * own it emits UNSCOPED CSS, which leaks into the host document.\n */\nexport function ethisysPlatformReactPagesPlugin(\n options: PlatformReactPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"platform-react/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let pages: ResolvedPage[] = [];\n let overlay: ResolvedOverlay | null = null;\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n // Vite hasn't called configResolved yet (or this plugin is being driven\n // outside Vite — e.g. a unit test that only invokes the validation\n // helper). Fall back to the explicit option then cwd. configResolved\n // will overwrite this with the correct Vite-resolved root when it\n // fires, before validate() is called for real.\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): PlatformReactManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve each page's absolute source path plus\n * the singular overlay (if declared). Idempotent — repeated invocations\n * rebuild from a fresh manifest read.\n */\n function validate(): void {\n pages = [];\n overlay = null;\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n\n // ── Pages ──────────────────────────────────────────────────────\n const declared = manifest.ui?.platformReactPages;\n if (Array.isArray(declared) && declared.length > 0) {\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n const absPath = resolve(resolvedRoot, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n\n const exportName =\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\";\n\n pages.push({\n id: decl.id,\n exportName,\n title: typeof decl.title === \"string\" && decl.title.length > 0 ? decl.title : null,\n moduleSpecifierRel: decl.moduleSpecifier,\n moduleSpecifierAbs: absPath,\n });\n }\n }\n\n // ── Overlay (singular) ─────────────────────────────────────────\n const overlayDecl = manifest.ui?.platformReactOverlay;\n if (overlayDecl !== undefined && overlayDecl !== null) {\n const where = \"ui.platformReactOverlay\";\n\n if (typeof overlayDecl.id !== \"string\" || overlayDecl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(overlayDecl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${overlayDecl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n\n if (typeof overlayDecl.moduleSpecifier !== \"string\" || overlayDecl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(overlayDecl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n const absPath = resolve(resolvedRoot, overlayDecl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${overlayDecl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n\n // M-4: Guard against id collision — overlay id must not match any page id.\n // Without this check, input[overlay.id] silently overwrites the page entry.\n const collidingPage = pages.find((p) => p.id === overlayDecl.id);\n if (collidingPage !== undefined) {\n throw new Error(\n `[ethisys-platform-react] ui.platformReactOverlay.id \"${overlayDecl.id}\" collides with a declared page id — ids must be unique across pages and the overlay.`,\n );\n }\n\n const exportName =\n typeof overlayDecl.exportName === \"string\" && overlayDecl.exportName.length > 0\n ? overlayDecl.exportName\n : \"default\";\n\n overlay = {\n id: overlayDecl.id,\n exportName,\n title: typeof overlayDecl.title === \"string\" && overlayDecl.title.length > 0 ? overlayDecl.title : null,\n moduleSpecifierRel: overlayDecl.moduleSpecifier,\n moduleSpecifierAbs: absPath,\n };\n }\n }\n\n let isBuild = false;\n\n const plugin: Plugin = {\n name: \"ethisys-platform-react\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n /**\n * Force ESM single-module output per page. Output options don't depend on\n * the resolved root, so they're safe to declare here — `config()` runs\n * before `configResolved()`. The Rollup input table is added later in\n * `configResolved()` once Vite has populated `resolvedRoot` correctly.\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n return {\n build: {\n // CRITICAL: emit NON-MINIFIED ESM. The host loads each bundle by\n // fetching it as text and REGEX-rewriting its bare-specifier imports\n // (`import { x } from \"react\"` → `const { x } = registry[\"react\"]`) —\n // the host's rewriter (hostModuleRegistry) assumes non-minified ESM,\n // so a minified bundle leaves `react`/`react-dom`/MUI unrewritten and\n // they resolve to `undefined`/`null` at mount (the overlay/page then\n // throws on the first hook). Vite minifies production builds by\n // default, so this MUST be forced off for every PlatformReact surface.\n minify: false,\n rollupOptions: {\n // CRITICAL: single-file ESM output per page. The host loads each\n // page via `import(url)` at mount time and reads the declared\n // `exportName` from the resulting module namespace. Chunk-split\n // output would break that contract because the host has no\n // import-map surface to resolve sibling chunks.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n // Externalise every host-realm specifier so the host's module-registry\n // rewriter resolves them to the live host singletons at runtime — react,\n // react-dom, MUI, emotion, components-react, extension-runtime (the shared\n // PLATFORM_REACT_EXTERNALS contract) PLUS host-ui-externals. This is\n // CRITICAL: if react is NOT externalised it gets bundled, the surface then\n // runs against a SECOND React instance, and hooks throw (invalid-hook /\n // \"reading useEffect of null\"). Must match the programmatic build-pages\n // externals so config-hook plugins (cc-scaffolded) behave identically.\n external: [...PLATFORM_REACT_EXTERNALS, \"@ethisyscore/host-ui-externals\"],\n // Nothing inside the build imports the entry module, so the bundler's\n // default entry tree-shaking would drop the declared `exportName`\n // (e.g. the overlay's `Overlay`). Pin entry signatures so the host\n // loader can read `bundle[exportName]` at mount time.\n preserveEntrySignatures: \"strict\",\n },\n },\n };\n },\n\n /**\n * Resolve the actual root Vite is using (which may differ from\n * `process.cwd()`), validate the manifest against it, and mutate the\n * resolved config's Rollup input table so each declared page becomes a\n * build entry. Mutation in `configResolved` is the standard Vite-plugin\n * pattern for input contributions that depend on the resolved root —\n * `config()` runs too early to know the real value.\n */\n configResolved(config) {\n isBuild = config.command === \"build\";\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n if (!isBuild) {\n return;\n }\n\n validate();\n if (pages.length === 0 && overlay === null) {\n return;\n }\n\n const input: Record<string, string> = {};\n for (const page of pages) {\n // Input key = bare page id. The `outputPrefix` is applied by\n // `entryFileNames` so the final output is `<outputPrefix><id>.js`.\n input[page.id] = slash(page.moduleSpecifierAbs);\n }\n // Register the singular overlay as one more Rollup input (WI 5160 SP-A).\n if (overlay !== null) {\n input[overlay.id] = slash(overlay.moduleSpecifierAbs);\n }\n\n // Merge into Vite's resolved rollupOptions.input. The existing value\n // may be undefined, a single entry path, an array of entries, or an\n // already-keyed object — handle all four shapes so coexistence with\n // other Vite plugins (Contract A / Contract B passes that declare\n // their own entries) is non-destructive.\n //\n // Vite's `ResolvedConfig.build` is typed `readonly` in its public\n // declarations. The runtime object is mutable — Vite plugins that\n // need to contribute Rollup inputs from `configResolved` (which\n // requires the resolved root) widely follow this mutation pattern.\n // Cast through a writable view to bypass the type-level readonly\n // check; runtime semantics are unchanged.\n const writable = config as unknown as {\n build?: {\n rollupOptions?: {\n input?: Record<string, string> | string | string[];\n };\n };\n };\n writable.build ??= {};\n writable.build.rollupOptions ??= {};\n const rollupOptions = writable.build.rollupOptions;\n const existing = rollupOptions.input;\n if (existing && typeof existing === \"object\" && !Array.isArray(existing)) {\n rollupOptions.input = { ...(existing as Record<string, string>), ...input };\n } else if (typeof existing === \"string\") {\n rollupOptions.input = { _entry: existing, ...input };\n } else if (Array.isArray(existing)) {\n const indexed: Record<string, string> = {};\n existing.forEach((entry, idx) => {\n indexed[`_entry${idx}`] = entry;\n });\n rollupOptions.input = { ...indexed, ...input };\n } else {\n rollupOptions.input = input;\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest. resolvedRoot is already set by\n // configResolved at this point.\n validate();\n },\n\n /**\n * Emit the companion `platform-react-pages.json` listing every declared\n * page. The `.ccpkg` packaging step (and the host's runtime loader) read\n * this file to discover which page modules ship in the bundle without\n * having to re-parse the manifest.\n */\n generateBundle(_options, bundle) {\n if (pages.length === 0 && overlay === null) {\n return;\n }\n\n // ── Per-asset SHA-256 digest map (WI 4858 sub-plan 3) ──────────\n // Hash EVERY emitted chunk (not just entries) so the host's verified\n // loader can check each asset against the manifest's `assetDigests`\n // before evaluation. The build forces `inlineDynamicImports: true`\n // (see `config()`), collapsing each page to a single chunk; if that is\n // ever relaxed, every emitted chunk URL MUST still be routed through the\n // host's `verifyAndLoadPlatformReactBundle` with this full map.\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const chunk of Object.values(bundle ?? {})) {\n if ((chunk as { type?: string }).type !== \"chunk\") {\n continue;\n }\n // Rollup `OutputChunk` exposes `code` (string) + `fileName`. Cast\n // through unknown because the union narrows on `type`.\n const code = (chunk as unknown as { code: string }).code;\n const fileName = (chunk as unknown as { fileName: string }).fileName;\n const hash = createHash(\"sha256\").update(code, \"utf8\").digest(\"hex\");\n digests.push({ path: fileName, sha256: hash });\n }\n\n // Build summary: pages array + optional overlay field (WI 5160 SP-A).\n const summary: {\n pages: Array<{ id: string; exportName: string; title: string | null; bundlePath: string; source: string }>;\n overlay?: { id: string; exportName: string; title: string | null; bundlePath: string; source: string };\n } = {\n pages: pages.map((p) => ({\n id: p.id,\n exportName: p.exportName,\n title: p.title,\n bundlePath: `${outputPrefix}${p.id}.js`,\n source: p.moduleSpecifierRel,\n })),\n };\n\n if (overlay !== null) {\n summary.overlay = {\n id: overlay.id,\n exportName: overlay.exportName,\n title: overlay.title,\n bundlePath: `${outputPrefix}${overlay.id}.js`,\n source: overlay.moduleSpecifierRel,\n };\n }\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-pages.json`,\n source: JSON.stringify(summary, null, 2),\n });\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-digest-map.json`,\n source: JSON.stringify({ digests }, null, 2),\n });\n },\n };\n\n return plugin;\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type {\n PlatformReactManifest,\n PlatformReactPageDeclaration,\n} from \"./page-bundles\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A fully-validated PlatformReact page declaration. All fields are guaranteed\n * present (no `undefined`), `exportName` is defaulted to `\"default\"`, and the\n * `moduleSpecifier` is guaranteed to exist on disk when `verifyOnDisk: true`\n * was passed to {@link parsePlatformReactPages}.\n */\nexport interface ResolvedPlatformReactPage {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n title: string | null;\n}\n\n/**\n * Options for {@link parsePlatformReactPages}.\n */\nexport interface ParsePlatformReactPagesOptions {\n /**\n * Root directory the manifest path and the page module specifiers are\n * resolved against. Defaults to `process.cwd()`.\n */\n root?: string;\n /**\n * When `true`, every declared `moduleSpecifier` must exist on disk (relative\n * to {@link root}). The default is `false` so the helper can be used to\n * snapshot-test a manifest without checking-out the page source files.\n */\n verifyOnDisk?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Parse + validate `ui.platformReactPages[]` declarations from a manifest\n * file. Designed for plugin authors writing Vitest tests against their own\n * manifest — the helper applies the same shape and uniqueness rules the\n * build-time Vite pass enforces, so a passing unit test gives the same\n * guarantee a green build would.\n *\n * Returns an empty array when the manifest does not exist OR does not\n * declare `ui.platformReactPages` OR declares it as an empty array.\n *\n * Throws on any malformed declaration. The thrown message matches the\n * build-time error so a failing test reads identically to a failing build.\n *\n * @example\n * ```ts\n * import { parsePlatformReactPages } from \"@ethisyscore/vite-plugin\";\n *\n * test(\"manifest declares dashboard and admin pages\", () => {\n * const pages = parsePlatformReactPages(\"./feature.manifest.json\");\n * expect(pages).toEqual([\n * { id: \"dashboard\", moduleSpecifier: \"src/pages/Dashboard.tsx\", exportName: \"default\", title: \"Dashboard\" },\n * { id: \"admin\", moduleSpecifier: \"src/pages/Admin.tsx\", exportName: \"AdminPage\", title: null },\n * ]);\n * });\n * ```\n */\nexport function parsePlatformReactPages(\n manifestPath: string,\n options: ParsePlatformReactPagesOptions = {},\n): ResolvedPlatformReactPage[] {\n const root = options.root ?? process.cwd();\n const verifyOnDisk = options.verifyOnDisk ?? false;\n const manifestAbsPath = isAbsolute(manifestPath)\n ? manifestPath\n : resolve(root, manifestPath);\n\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n let manifest: PlatformReactManifest;\n try {\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n manifest = JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n\n const declared = manifest.ui?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return [];\n }\n\n const result: ResolvedPlatformReactPage[] = [];\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl: PlatformReactPageDeclaration = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n if (verifyOnDisk) {\n const absPath = resolve(root, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n }\n\n result.push({\n id: decl.id,\n moduleSpecifier: decl.moduleSpecifier,\n exportName:\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\",\n title:\n typeof decl.title === \"string\" && decl.title.length > 0\n ? decl.title\n : null,\n });\n }\n\n return result;\n}\n\n","import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from \"node:fs\";\nimport { basename, relative, resolve } from \"node:path\";\nimport { slash, kebab, titleCase } from \"../utils/strings\";\n\n/**\n * Build-time codegen for a PlatformReact plugin's `feature.manifest.json` +\n * project-root `extension.manifest.json` overlay, from the plugin's `routeMeta.json`\n * and its lifted page/adapter trees. Promoted from the per-plugin `gen-manifest.mjs`\n * so every migrated plugin shares one generator instead of copying the routeMeta →\n * `platformReactPages` derivation (including the nested-URL `route` emission and the\n * dashboard-at-root empty-string route).\n *\n * NOT a Vite plugin — a plain build-step helper a plugin's `gen-manifest.mjs` calls\n * before `build-pages`. It reads the filesystem and writes both manifests.\n */\n\n/** One entry of the migrated `routeMeta.json` (a faithful shift of the monolith's `routeMeta.ts`). */\nexport interface RouteMetaEntry {\n /** Full path pattern, re-rooted under `/extensions/<slug>/` (`:seg` = param). */\n pattern: string;\n label: string;\n /** Parent route's `pattern`; omit for a top-level route. */\n parent?: string;\n /** Platform-react page id this pattern maps to (the manifest link; breadcrumbs ignore it). */\n pageId?: string;\n}\n\n/** Manifest metadata written into `feature.manifest.json`. */\nexport interface PlatformReactManifestMeta {\n id: string;\n name: string;\n version: string;\n /** Defaults to `\"platform-react\"`. */\n renderMode?: string;\n /** `$schema` value; defaults to the feature-manifest schema URL. */\n schema?: string;\n}\n\n/** A generated `ui.platformReactPages[]` entry (feature-manifest form, incl. the build-only `views`). */\nexport interface PlatformReactPageEntry {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n /** Sub-path under `/extensions/<slug>/`; `\"\"` = the extension-root (dashboard) surface. Absent → host id-match. */\n route?: string;\n title: string;\n /** View name → src-relative module path, read by the page's `useView(<module>, name)`. */\n views: Record<string, string>;\n}\n\n/**\n * The singular `ui.platformReactOverlay` entry (feature-manifest form, incl. the build-only `views`).\n * Mirrors {@link PlatformReactPageEntry} minus `route` — overlays are not routed.\n * `views` is a build-time wiring artifact consumed by `build-pages` to synthesise the\n * virtual entry's `definePluginOverlay(Overlay, { ...views })` call, exactly as page `views` are.\n * It is NOT part of the protocol `PlatformReactOverlayDeclaration` and is stripped at the\n * wire/admission boundary (parallel to how page `views` are stripped).\n */\nexport interface PlatformReactOverlayEntry {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n title: string;\n /** View name → src-relative module path (build-time wiring only; stripped from the wire manifest). */\n views: Record<string, string>;\n}\n\nconst DEFAULT_SCHEMA = \"https://ethisys.dev/schemas/feature-manifest.json\";\n\n/**\n * Per-page override, keyed by page filename (incl. `.tsx`). For plugins whose page\n * ids/titles are NOT derived from the filename (e.g. `Timesheets.tsx` → id\n * `\"dashboard\"` / title `\"Dashboard\"`). Any field omitted falls back to the derived\n * default (`id` = kebab, `title` = title-case) or the routeMeta lookup (`route`).\n */\nexport interface PlatformReactPageOverride {\n id?: string;\n title?: string;\n route?: string;\n}\n\n/** One page file read for {@link computePlatformReactPages}. */\nexport interface PlatformReactPageSource {\n /** Page filename incl. `.tsx`. */\n file: string;\n /** The page's source content (scanned for `useView(<module>, …)` calls). */\n content: string;\n /**\n * Root-relative module specifier for this page (e.g. `src/pages/admin/Foo.tsx`).\n * When pages come from multiple directories each source carries its own specifier,\n * derived from the directory it was read from.\n */\n moduleSpecifier: string;\n}\n\n/** Input to {@link computePlatformReactPages} (already-read filesystem inputs). */\nexport interface ComputePlatformReactPagesInput {\n /**\n * The plugin's own `useView` module key. This does NOT control which calls the scan\n * matches: every `useView(<anyKey>, <Name>)` is matched and then classified against\n * {@link moduleKeys}. Its only role here is being the default single entry of that set.\n */\n module: string;\n /**\n * Every module key the plugin's page definer actually registers a page's flat `views`\n * map under. Defaults to `[module]`, which is what `createPluginPageDefiner` produces.\n * Must not be empty: an empty set would classify every call as unregistered.\n * Supply the full set for a hand-rolled multi-key definer (registering the same map\n * under several keys to serve cross-module `useView` calls).\n *\n * A `useView` call naming a key OUTSIDE this set can never resolve at runtime, so it is\n * reported in {@link ComputePlatformReactPagesResult.unregisteredViews}.\n */\n moduleKeys?: string[];\n /** Extension slug for the `/extensions/<slug>/` route prefix. */\n slug: string;\n routeMeta: RouteMetaEntry[];\n /** Each page file's basename (with `.tsx`) + its source content + its root-relative module specifier. */\n pages: PlatformReactPageSource[];\n /** View name → src-relative module path (e.g. `src/adapter/<module>/XView.tsx`). */\n viewFiles: Record<string, string>;\n /** Per-file id/title/route overrides for non-filename-derived plugins. */\n pageOverrides?: Record<string, PlatformReactPageOverride>;\n}\n\n/** Result of {@link computePlatformReactPages}. */\nexport interface ComputePlatformReactPagesResult {\n entries: PlatformReactPageEntry[];\n /** `<file>: view \"<name>\" has no adapter file` diagnostics. */\n missingViews: string[];\n /**\n * `useView` calls naming a module key the definer does not register, which therefore\n * render the SDK's `MissingViewFallback` (\"View not available\") at runtime behind a\n * green build. Previously invisible: the scan was built from the plugin's own module\n * key, so such a call matched nothing and produced no binding AND no diagnostic.\n */\n unregisteredViews: string[];\n}\n\n/**\n * Pure core: derive the `platformReactPages[]` entries from already-read inputs (no\n * filesystem). Per page: `id` = `pageOverrides[file].id` ?? kebab(filename), `title`\n * = `pageOverrides[file].title` ?? title-case(filename), and `route` =\n * `pageOverrides[file].route` ?? the routeMeta lookup — the routeMeta pattern minus\n * the `/extensions/<slug>/` prefix, keyed by the RESOLVED id (the root pattern\n * `/extensions/<slug>` → the empty-string route, making that page the extension-root\n * / dashboard surface). Empty-string routes are emitted (presence, not truthiness);\n * a page with neither an override route nor a routeMeta entry gets no `route` and\n * falls back to the host's id match.\n */\nexport function computePlatformReactPages(\n input: ComputePlatformReactPagesInput,\n): ComputePlatformReactPagesResult {\n const routePrefix = `/extensions/${input.slug}/`;\n const routeRoot = `/extensions/${input.slug}`;\n const pageRouteById: Record<string, string> = Object.fromEntries(\n input.routeMeta\n .filter((e) => e.pageId && (e.pattern.startsWith(routePrefix) || e.pattern === routeRoot))\n .map((e) => [e.pageId as string, e.pattern === routeRoot ? \"\" : e.pattern.slice(routePrefix.length)]),\n );\n\n // Match `useView(\"<anyModule>\", \"SomeView\")`. Deliberately NOT anchored to this\n // plugin's own module key: a call naming another key is the failure this scan has to\n // see, not something to skip. The optional trailing comma matters too — a multi-line\n // call ending `\"SomeView\",\\n)` was silently dropped by the previous `\\s*\\)` tail, even\n // for the plugin's own key.\n const useViewRe = /useView\\(\\s*[\"']([\\w-]+)[\"']\\s*,\\s*[\"']([A-Za-z0-9_]+)[\"']\\s*,?\\s*\\)/g;\n\n // `??` only falls back on null/undefined, so an explicitly empty array would survive and\n // leave the set empty: every call would be reported unregistered and the diagnostic would\n // read `registered: ` with nothing after it. Fail loudly instead of emitting nonsense.\n if (input.moduleKeys !== undefined && input.moduleKeys.length === 0) {\n throw new Error(\n \"generate-manifest: moduleKeys was supplied but empty. Omit it to default to [module], \"\n + \"or list every module key the page definer registers views under.\",\n );\n }\n const registeredKeys = new Set(input.moduleKeys ?? [input.module]);\n\n const entries: PlatformReactPageEntry[] = [];\n const missingViews: string[] = [];\n const unregisteredViews: string[] = [];\n for (const { file, content, moduleSpecifier } of input.pages) {\n const name = basename(file, \".tsx\");\n const override = input.pageOverrides?.[file] ?? {};\n const views: Record<string, string> = {};\n useViewRe.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = useViewRe.exec(content)) !== null) {\n const [, moduleKey, v] = m;\n\n if (!registeredKeys.has(moduleKey)) {\n // Even a resolvable adapter file would be registered under a key this page never\n // reads, so binding it here would not help: report instead.\n unregisteredViews.push(\n `${file}: useView(\"${moduleKey}\", \"${v}\") names a module key the definer does not `\n + `register (registered: ${[...registeredKeys].map((k) => `\"${k}\"`).join(\", \")}), `\n + `so the lookup renders \"View not available\" at runtime`,\n );\n continue;\n }\n\n if (input.viewFiles[v] !== undefined) {\n views[v] = input.viewFiles[v];\n } else {\n missingViews.push(`${file}: view \"${v}\" has no adapter file`);\n }\n }\n const id = override.id ?? kebab(name);\n // Explicit override route wins; else the routeMeta lookup by resolved id.\n // `??` (not `||`) so an empty-string route (dashboard root) survives.\n const route = override.route ?? pageRouteById[id];\n entries.push({\n id,\n moduleSpecifier,\n exportName: \"default\",\n ...(route !== undefined ? { route } : {}),\n title: override.title ?? titleCase(name),\n views,\n });\n }\n return { entries, missingViews, unregisteredViews };\n}\n\n/** Path overrides for {@link generatePlatformReactManifest} (relative to `root` unless absolute). */\nexport interface PlatformReactManifestPaths {\n /** Source root; default `\"src\"`. */\n src?: string;\n /**\n * Pages dir(s); default `src/pages/<module>`. Accepts a single string (backward-compat)\n * or an array of directories to scan together. Each `.tsx` file's `moduleSpecifier` is\n * derived from the directory it was read from. A duplicate basename across dirs throws a\n * clear error (fail-fast) — there is no per-dir escape hatch. `pageExclude` removes a\n * filename from ALL scanned dirs, so it cannot preserve one dir's copy while dropping\n * another's; to ship two pages with the same filename, rename one of them.\n */\n pages?: string | string[];\n /** Page filenames (incl. `.tsx`) to skip — e.g. dialogs that live in a pages dir. */\n pageExclude?: string[];\n /** Adapter (views) dir; default `src/adapter/<module>`. */\n adapter?: string;\n /** routeMeta file; default `src/config/routeMeta.json`. */\n routeMeta?: string;\n /** feature manifest output; default `\"feature.manifest.json\"`. */\n featureManifest?: string;\n /** project-root overlay output; default `\"../extension.manifest.json\"`. */\n overlay?: string;\n}\n\n/** Author-facing config for {@link generatePlatformReactManifest}. */\nexport interface GeneratePlatformReactManifestConfig {\n /** Absolute path to the plugin's `ui/` root (holds `src/` + the emitted manifests). */\n root: string;\n /** `useView` module key AND the default `pages/adapter` sub-dir name (e.g. `\"finance\"`). */\n module: string;\n /** Extension slug for the `/extensions/<slug>/` route prefix; defaults to `module`. */\n slug?: string;\n /** Metadata written into `feature.manifest.json`. */\n manifest: PlatformReactManifestMeta;\n /**\n * Singular overlay declaration. When present, emits `ui.platformReactOverlay` in\n * `feature.manifest.json` (with `views` for build-pages virtual-entry synthesis) and\n * in the `extension.manifest.json` wire overlay (without `views`, mirroring the page\n * strip). Omit to suppress the key entirely.\n */\n overlay?: PlatformReactOverlayEntry;\n /**\n * Per-page id/title/route overrides, keyed by page filename (incl. `.tsx`). Only\n * needed for plugins whose ids/titles aren't the filename-derived defaults; omit\n * for the filename convention. See {@link PlatformReactPageOverride}.\n */\n pageOverrides?: Record<string, PlatformReactPageOverride>;\n /** Path overrides (relative to `root` unless absolute). See {@link PlatformReactManifestPaths}. */\n paths?: PlatformReactManifestPaths;\n /**\n * Every module key the plugin's definer registers page `views` under. Defaults to\n * `[module]`. See {@link ComputePlatformReactPagesInput.moduleKeys}.\n */\n moduleKeys?: string[];\n /**\n * Throw when any `useView` call cannot be satisfied (default `true`).\n *\n * `useView` is a name-to-component lookup against the static manifest slice the\n * generated entry registers, not an import, so an unsatisfiable call is NOT a build\n * error: the surface renders the SDK's `MissingViewFallback` (\"View not available\") at\n * runtime behind a green build. Failing the generator is what turns that into a\n * build-time error.\n *\n * Both manifests are still written before the throw, so the emitted files stay in sync\n * with the page tree; the exception, not a stale file, is the gate. Set `false` only to\n * unblock a migration mid-flight, and read the returned diagnostics instead.\n */\n strict?: boolean;\n}\n\n/** What {@link generatePlatformReactManifest} produced. */\nexport interface GeneratePlatformReactManifestResult {\n pageCount: number;\n /** Page ids whose source resolved zero views. */\n pagesWithoutView: string[];\n /** `<file>: view \"<name>\" has no adapter file` diagnostics. */\n missingViews: string[];\n /** `useView` calls naming an unregistered module key. See {@link ComputePlatformReactPagesResult.unregisteredViews}. */\n unregisteredViews: string[];\n featureManifestPath: string;\n overlayPath: string;\n}\n\nfunction walk(dir: string): string[] {\n const out: string[] = [];\n for (const n of readdirSync(dir)) {\n const p = resolve(dir, n);\n if (statSync(p).isDirectory()) {\n out.push(...walk(p));\n } else {\n out.push(p);\n }\n }\n return out;\n}\n\n/**\n * Read the plugin's `routeMeta.json` + page/adapter trees and write both\n * `feature.manifest.json` (with the build-only `views` map) and the project-root\n * `extension.manifest.json` overlay (pages WITHOUT `views` — what `cc package` reads\n * for the host's install-time nav-path validation). Returns a summary for logging.\n */\nexport function generatePlatformReactManifest(\n config: GeneratePlatformReactManifestConfig,\n): GeneratePlatformReactManifestResult {\n const { root, module } = config;\n const slug = config.slug ?? module;\n const src = config.paths?.src ?? \"src\";\n const adapterDir = resolve(root, config.paths?.adapter ?? `${src}/adapter/${module}`);\n const routeMetaPath = resolve(root, config.paths?.routeMeta ?? `${src}/config/routeMeta.json`);\n const featureManifestRel = config.paths?.featureManifest ?? \"feature.manifest.json\";\n const overlayRel = config.paths?.overlay ?? \"../extension.manifest.json\";\n\n // routeMeta is optional: a plugin that needs neither nested URLs nor breadcrumbs\n // simply ships no routeMeta.json — every page then falls back to the host id match.\n const routeMeta: RouteMetaEntry[] = existsSync(routeMetaPath)\n ? (JSON.parse(readFileSync(routeMetaPath, \"utf8\")) as RouteMetaEntry[])\n : [];\n // paths.pages: string | string[] (default single \"src/pages/<module>\")\n const pagesCfg = config.paths?.pages ?? `${src}/pages/${module}`;\n const pageDirs = (Array.isArray(pagesCfg) ? pagesCfg : [pagesCfg]).map((p) => resolve(root, p));\n const exclude = new Set(config.paths?.pageExclude ?? []);\n\n // View name → root-relative module path (e.g. `src/adapter/<module>/XView.tsx`).\n // A missing adapter dir is treated as no views (not a hard ENOENT) so a plugin\n // with no adapter tree still generates — any page that DOES call useView then\n // surfaces a helpful `missingViews` diagnostic instead of a raw filesystem error.\n const viewFiles: Record<string, string> = {};\n if (existsSync(adapterDir)) {\n for (const f of walk(adapterDir)) {\n if (f.endsWith(\".tsx\")) {\n viewFiles[basename(f, \".tsx\")] = slash(relative(root, f));\n }\n }\n }\n\n const seen = new Map<string, string>(); // basename -> dir (duplicate guard)\n const pages: PlatformReactPageSource[] = [];\n for (const dir of pageDirs) {\n if (!existsSync(dir)) {\n throw new Error(`generate-manifest: pages dir not found: ${dir}`);\n }\n for (const file of readdirSync(dir).filter((f) => f.endsWith(\".tsx\")).sort()) {\n if (exclude.has(file)) continue;\n if (seen.has(file)) {\n throw new Error(\n `generate-manifest: duplicate page filename \"${file}\" in both ${seen.get(file)} and ${dir}`,\n );\n }\n seen.set(file, dir);\n // Build the root-relative specifier. When the pages dir IS the root, relative()\n // returns \"\" and a naive `\"${relDir}/${file}\"` would yield `\"/${file}\"` (leading\n // slash). Join without the separator in that case so the root case yields just\n // `\"${file}\"` and the non-root case yields `\"src/pages/x/${file}\"` (unchanged).\n const relDir = slash(relative(root, dir));\n const moduleSpecifier = relDir ? `${relDir}/${file}` : file;\n pages.push({\n file,\n content: readFileSync(resolve(dir, file), \"utf8\"),\n moduleSpecifier,\n });\n }\n }\n\n const { entries, missingViews, unregisteredViews } = computePlatformReactPages({\n module,\n moduleKeys: config.moduleKeys,\n slug,\n routeMeta,\n pages,\n viewFiles,\n pageOverrides: config.pageOverrides,\n });\n\n const schema = config.manifest.schema ?? DEFAULT_SCHEMA;\n const renderMode = config.manifest.renderMode ?? \"platform-react\";\n\n const overlayEntry = config.overlay;\n const featureManifest = {\n $schema: schema,\n id: config.manifest.id,\n name: config.manifest.name,\n version: config.manifest.version,\n renderMode,\n ui: {\n platformReactPages: entries,\n ...(overlayEntry !== undefined ? { platformReactOverlay: overlayEntry } : {}),\n },\n };\n const featureManifestPath = resolve(root, featureManifestRel);\n writeFileSync(featureManifestPath, JSON.stringify(featureManifest, null, 2) + \"\\n\");\n\n // Wire form of the overlay entry: strip `views` (build-time wiring only, not a protocol field).\n // Parallel to how page entries are stripped of `views` for the extension.manifest.json.\n const overlayWireEntry =\n overlayEntry !== undefined\n ? {\n id: overlayEntry.id,\n moduleSpecifier: overlayEntry.moduleSpecifier,\n exportName: overlayEntry.exportName,\n title: overlayEntry.title,\n }\n : undefined;\n\n const overlay = {\n $schema: schema,\n ui: {\n platformReactPages: entries.map(({ id, moduleSpecifier, exportName, route, title }) => ({\n id,\n moduleSpecifier,\n exportName,\n ...(route !== undefined ? { route } : {}),\n title,\n })),\n ...(overlayWireEntry !== undefined ? { platformReactOverlay: overlayWireEntry } : {}),\n },\n };\n const overlayPath = resolve(root, overlayRel);\n writeFileSync(overlayPath, JSON.stringify(overlay, null, 2) + \"\\n\");\n\n const pagesWithoutView = entries\n .filter((e) => Object.keys(e.views).length === 0)\n .map((e) => e.id);\n\n const result: GeneratePlatformReactManifestResult = {\n pageCount: entries.length,\n pagesWithoutView,\n missingViews,\n unregisteredViews,\n featureManifestPath,\n overlayPath,\n };\n\n // Both manifests are already written, so the emitted files stay in sync with the page\n // tree; the throw is the gate, not a stale file. See `strict` for why this is fatal by\n // default: an unsatisfiable useView call is a runtime blank surface, not a build error.\n if ((config.strict ?? true) && (missingViews.length > 0 || unregisteredViews.length > 0)) {\n throw new Error(\n `generate-manifest: ${missingViews.length + unregisteredViews.length} unresolvable `\n + `useView call(s). Each renders \"View not available\" at runtime behind a green build:\\n`\n + [...unregisteredViews, ...missingViews].map((d) => ` - ${d}`).join(\"\\n\"),\n );\n }\n\n return result;\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve, sep } from \"node:path\";\nimport type { Plugin } from \"vite\";\n// Tier U manifest + integrity shapes are owned by the protocol SSOT (sub-plan 01 D1).\n// Consume them — do NOT re-declare a local copy.\nimport { AssetDigest, IframeSandboxPageDeclaration } from \"@ethisyscore/protocol\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/** One emitted artifact from a per-page Vite sub-build. */\nexport type IframeBuildOutputItem =\n | { type: \"chunk\"; fileName: string; code: string }\n | { type: \"asset\"; fileName: string; source: string | Uint8Array };\n\nexport interface IframeBuildResult {\n output: IframeBuildOutputItem[];\n}\n\n/** A single page handed to the (injectable) builder. */\nexport interface IframeBuildContext {\n id: string;\n title: string;\n entryPath: string;\n root: string;\n /** Per-page output directory (`<outputDir>/<id>`). */\n outDir: string;\n}\n\n/** Injectable per-page builder. Defaults to a real Vite library build. */\nexport type IframeViteBuild = (page: IframeBuildContext) => Promise<IframeBuildResult>;\n\nexport interface IframeSandboxPluginOptions {\n /** Root the manifest + entry paths resolve against. Defaults to Vite's resolved root / cwd. */\n root?: string;\n /** Manifest path (relative to `root`). Default `feature.manifest.json`. */\n manifestPath?: string;\n /** Output directory for per-page bundles + the digest map. Default `dist/iframe-sandbox`. */\n outputDir?: string;\n /** Inline manifest object (test injection). When omitted, the manifest is read from disk. */\n manifest?: unknown;\n /** Injectable per-page builder (test injection). When omitted, a real Vite build runs. */\n build?: IframeViteBuild;\n /** Injectable file writer (test injection). When omitted, writes via `fs` (creating dirs). */\n writeFile?: (path: string, contents: string) => void;\n}\n\nexport interface IframeSandboxBuildSummary {\n digests: Array<{ path: string; sha256: string }>;\n digestMapPath: string | null;\n}\n\nconst DEFAULT_MANIFEST = \"feature.manifest.json\";\nconst DEFAULT_OUTPUT_DIR = \"dist/iframe-sandbox\";\nconst DIGEST_MAP_FILENAME = \"iframe-sandbox-digest-map.json\";\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\nfunction defaultWriteFile(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n}\n\n/** Real per-page build via Vite's programmatic API. `vite` is an optional peer dep. */\nconst defaultBuild: IframeViteBuild = async (page) => {\n const { build } = await import(\"vite\");\n const result = await build({\n root: page.root,\n logLevel: \"warn\",\n build: {\n outDir: page.outDir,\n emptyOutDir: true,\n rollupOptions: {\n input: resolve(page.root, page.entryPath),\n },\n },\n });\n // `build()` returns RollupOutput | RollupOutput[] | RollupWatcher; the\n // library build (no watch) yields a single RollupOutput.\n const out = Array.isArray(result) ? result[0] : result;\n return { output: (out as unknown as IframeBuildResult).output };\n};\n\nfunction digestOf(item: IframeBuildOutputItem): string {\n const bytes = item.type === \"chunk\" ? item.code : item.source;\n return createHash(\"sha256\").update(bytes as string | Uint8Array).digest(\"hex\");\n}\n\nfunction readManifest(options: IframeSandboxPluginOptions, root: string): unknown {\n if (options.manifest !== undefined) {\n return options.manifest;\n }\n const rel = options.manifestPath ?? DEFAULT_MANIFEST;\n const abs = isAbsolute(rel) ? rel : resolve(root, rel);\n if (!existsSync(abs)) {\n return null;\n }\n const raw = readFileSync(abs, \"utf8\");\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw new Error(`[ethisys-iframe-sandbox] Failed to parse manifest at \"${abs}\": ${(e as Error).message}`);\n }\n}\n\n// ── Orchestration (exposed for unit testing) ───────────────────────\n\n/**\n * Build each `ui.iframeSandboxPages[]` declaration as its own Vite app bundle and\n * emit a per-asset SHA-256 digest map in the SAME shape `ethisysPlatformReactPlugin`\n * produces (`{ digests: [{ path, sha256 }] }`). Tier U surfaces are independent\n * cross-origin apps, so each page is a separate sub-build under `<outputDir>/<id>/`;\n * every emitted artifact is hashed (and validated against the protocol `AssetDigest`\n * schema) so the edge integrity endpoint (sub-plan 5, Task 6) can verify served bytes.\n *\n * No-op when no pages are declared. Page shape is validated by the protocol\n * `IframeSandboxPageDeclaration` schema (a malformed entry rejects the build).\n */\nexport async function buildIframeSandboxPages(\n options: IframeSandboxPluginOptions = {},\n): Promise<IframeSandboxBuildSummary> {\n const root = options.root ?? process.cwd();\n const manifest = readManifest(options, root);\n\n const declared = (manifest as { ui?: { iframeSandboxPages?: unknown[] } } | null)?.ui?.iframeSandboxPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return { digests: [], digestMapPath: null };\n }\n\n // Validate every page against the protocol schema (SSOT) before building.\n const pages = declared.map((raw, i) => {\n try {\n return IframeSandboxPageDeclaration.parse(raw);\n } catch (e) {\n throw new Error(\n `[ethisys-iframe-sandbox] ui.iframeSandboxPages[${i}] is invalid: ${(e as Error).message}`,\n );\n }\n });\n\n const seen = new Set<string>();\n for (const p of pages) {\n if (seen.has(p.id)) {\n throw new Error(`[ethisys-iframe-sandbox] Duplicate iframe-sandbox page id \"${p.id}\".`);\n }\n seen.add(p.id);\n }\n\n const build = options.build ?? defaultBuild;\n const write = options.writeFile ?? defaultWriteFile;\n const outputDir = options.outputDir ?? DEFAULT_OUTPUT_DIR;\n const outDirAbs = isAbsolute(outputDir) ? outputDir : resolve(root, outputDir);\n\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const page of pages) {\n const result = await build({\n id: page.id,\n title: page.title,\n entryPath: page.entryPath,\n root,\n outDir: resolve(outDirAbs, page.id),\n });\n for (const item of result.output) {\n const entry = { path: `${page.id}/${item.fileName}`, sha256: digestOf(item) };\n // The integrity entry conforms to the protocol AssetDigest contract.\n AssetDigest.parse(entry);\n digests.push(entry);\n }\n }\n\n const digestMapPath = resolve(outDirAbs, DIGEST_MAP_FILENAME);\n write(slash(digestMapPath), JSON.stringify({ digests }, null, 2));\n return { digests, digestMapPath };\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Tier U (iframe-sandbox) Vite build pass (WI 4858 sub-plan 5). Mirrors\n * `ethisysPlatformReactPlugin`: keyed off `ui.iframeSandboxPages[]` and a no-op\n * when absent, so a single Vite config can compose every render-mode pass.\n *\n * Unlike Tier T (ESM modules in the parent build), each Tier U page is an\n * independent cross-origin app — so the pass runs a separate Vite sub-build per\n * page in `closeBundle` and emits the integrity digest map the host verifies.\n */\nexport function ethisysIframeSandboxPlugin(options: IframeSandboxPluginOptions = {}): Plugin {\n let resolvedRoot = options.root;\n\n return {\n name: \"ethisys-iframe-sandbox\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!options.root) {\n resolvedRoot = config.root;\n }\n },\n\n async closeBundle() {\n await buildIframeSandboxPages({ ...options, root: options.root ?? resolvedRoot });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { isAbsolute, normalize, resolve, sep } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\n// ── Contract A (Wave 0): SDUI schema validation + emission ─────────\n//\n// Re-exports the Contract A pass so consumers can compose it alongside the\n// legacy manifest HTML-entry plugin (or use it on its own for host-rendered\n// plugins that ship no HTML at all).\nexport {\n ethisysContractAPlugin,\n type ContractAPluginOptions,\n type ContractAManifest,\n type ManifestResourceRef,\n type ManifestReactiveRuleRef,\n} from \"./contract-a/emit\";\nexport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationResult,\n type ValidationFailure,\n} from \"./contract-a/schema-validator\";\n\n// ── Contract B (Wave 1): Worker-bundle emission ────────────────────\n//\n// Re-export the Contract B pass so consumers can compose it alongside the\n// Contract A schema-validation pass. The two passes are non-interfering:\n// each pass keys off `renderMode` and exits early when the manifest is not\n// addressed to it. The recommended scaffold registers both plugins so a\n// manifest can switch render modes without changing its Vite config.\nexport {\n ethisysContractBPlugin,\n type ContractBPluginOptions,\n type ContractBManifest,\n CONTRACT_B_SEMANTIC_PRIMITIVES,\n CONTRACT_B_RUNTIME_IMPORTS,\n CONTRACT_B_IMPORT_MAP_ALLOWLIST,\n} from \"./contract-b/worker-bundle\";\n\n// ── PlatformReact pages (RFC 0003) ─────────────────────────────────\n//\n// Build pass for the high-trust host-extension tier. Reads\n// `ui.platformReactPages[]` from the manifest and emits one ESM bundle per\n// page. The host loads each bundle at surface mount time via `import(url)`\n// against the same-origin asset endpoint.\n// `ethisysPlatformReactPlugin` returns an ARRAY (the page pass + the plugin-CSS\n// scoping pass it must always be paired with); Vite flattens nested plugin arrays,\n// so it drops into `plugins: [...]` unchanged. `ethisysPlatformReactPagesPlugin` is\n// the page pass alone, for hand-rolled composition — see its doc comment.\nexport {\n ethisysPlatformReactPlugin,\n ethisysPlatformReactPagesPlugin,\n type PlatformReactPluginOptions,\n type PlatformReactManifest,\n type PlatformReactPageDeclaration,\n} from \"./platform-react/page-bundles\";\n\n// Test-time helper for plugin authors who want to snapshot-test their\n// manifest's PlatformReact page declarations without spinning a Vite build.\n// Applies the same shape + uniqueness rules the build-time pass enforces.\nexport {\n parsePlatformReactPages,\n type ResolvedPlatformReactPage,\n type ParsePlatformReactPagesOptions,\n} from \"./platform-react/test-helpers\";\n\n// Multi-bundle orchestrator: one isolated Vite sub-build per declared page\n// (required because `inlineDynamicImports` is illegal with >1 Rollup input).\n// Owns the host externals, dedupe, the host-loader aliased-import rewrite, and\n// the digest/summary contract; the plugin supplies only its aliases + plugins.\n// Used by a plugin's `build-pages` script in place of a hand-rolled copy.\nexport {\n buildPlatformReactPages,\n rewriteAliasedExternalImports,\n virtualPageEntry,\n PLATFORM_REACT_EXTERNALS,\n PLATFORM_REACT_DEDUPE,\n type BuildPlatformReactPagesOptions,\n type PlatformReactBuildSummary,\n type PlatformReactBuildContext,\n type PlatformReactPageInput,\n type PlatformReactAlias,\n type PlatformReactViteBuild,\n type ViteBuildFn,\n} from \"./platform-react/build-pages\";\n\n// Plugin-CSS scoping + its build guard. ONE convention, enforced rather than\n// documented: a plugin never emits an unscoped selector into the host document.\n// `scopePluginCss` handles the layers Tailwind generates unscoped (`utilities`, the\n// `@property` fallbacks in `properties`, and the `:root, :host` theme scale);\n// `findUnscopedSelectors` fails the build if anything else would still leak.\n// Applied automatically by both page-build paths; exported for a plugin with a\n// hand-rolled build, for a pre-commit check, and for tests.\nexport {\n scopePluginCss,\n scopePluginCssPlugin,\n findUnscopedSelectors,\n formatUnscopedSelectorError,\n isScopableCssId,\n EHX_PLUGIN_CSS_SCOPE,\n EHX_PLUGIN_ROOT_SCOPE,\n EHX_PLUGIN_SCOPE_ROOTS,\n EHX_SCOPED_CSS_LAYERS,\n type ScopePluginCssOptions,\n} from \"./platform-react/scope-plugin-css\";\n\n// Build-step codegen (NOT a Vite plugin): derive `feature.manifest.json` +\n// project-root `extension.manifest.json` overlay from a plugin's `routeMeta.json`\n// and its page/adapter trees — the shared replacement for a per-plugin\n// `gen-manifest.mjs` (routeMeta → platformReactPages routes, incl. nested-URL\n// `route`s and the dashboard-at-root empty-string route).\nexport {\n generatePlatformReactManifest,\n computePlatformReactPages,\n type GeneratePlatformReactManifestConfig,\n type GeneratePlatformReactManifestResult,\n type PlatformReactManifestMeta,\n type PlatformReactManifestPaths,\n type PlatformReactPageEntry,\n type PlatformReactPageOverride,\n type PlatformReactPageSource,\n type ComputePlatformReactPagesInput,\n type ComputePlatformReactPagesResult,\n type RouteMetaEntry,\n} from \"./platform-react/generate-manifest\";\n\n// ── Tier U: iframe-sandbox pages (WI 4858 sub-plan 5) ──────────────\n//\n// Build pass for the cross-origin sandboxed tier. Reads `ui.iframeSandboxPages[]`\n// (typed by the protocol `IframeSandboxPageDeclaration`), runs one Vite sub-build\n// per page, and emits the per-asset SHA-256 digest map the edge integrity endpoint\n// verifies. No-op when no iframe-sandbox pages are declared.\nexport {\n ethisysIframeSandboxPlugin,\n buildIframeSandboxPages,\n type IframeSandboxPluginOptions,\n type IframeSandboxBuildSummary,\n type IframeViteBuild,\n type IframeBuildContext,\n type IframeBuildResult,\n type IframeBuildOutputItem,\n} from \"./iframeSandboxPlugin\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\ninterface ManifestEntry {\n id?: string;\n entrypoint: string;\n source?: string;\n title?: string;\n template?: string;\n type?: string;\n route?: string;\n}\n\ninterface Manifest {\n ui?: {\n pages?: ManifestEntry[];\n surfaces?: ManifestEntry[];\n };\n}\n\nexport interface EthisysPluginOptions {\n /**\n * Path to the manifest file, relative to Vite's root directory.\n * @default \"../extension.manifest.json\"\n */\n manifestPath?: string;\n\n /**\n * ID of the mount element in the generated HTML.\n * React plugins use \"root\", Vue plugins use \"app\".\n * @default \"root\"\n */\n mountId?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Normalize Windows backslashes to forward slashes for Vite/Rollup compatibility. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n/** Escape HTML special characters to prevent XSS via manifest fields (e.g., title). */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n/** Validates a manifest path is relative with no traversal (cross-platform). */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.includes(\"..\")) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Vite plugin that reads `extension.manifest.json` (or a custom manifest path)\n * and auto-generates HTML entry points for all pages and surfaces that declare\n * a `source` field. No physical HTML files are required.\n *\n * Pages without a `source` field share the main entry point (SPA mode).\n * Surfaces (dialogs, panels) each get their own HTML shell.\n */\nexport function ethisysManifestPlugin(\n options: EthisysPluginOptions = {},\n): Plugin {\n const manifestRelPath = options.manifestPath ?? \"../extension.manifest.json\";\n const mountId = options.mountId ?? \"root\";\n let entries: ManifestEntry[] = [];\n let rootDir: string;\n let manifestAbsPath: string;\n // Cache generated HTML Promises to avoid stampede on concurrent requests (PERF-5)\n const htmlCache = new Map<string, Promise<string>>();\n\n // ── HTML generation ──────────────────────────────────────────────\n\n function generateHtml(entry: ManifestEntry): string {\n // Enterprise escape hatch: custom HTML template\n if (entry.template) {\n assertSafeRelativePath(entry.template, \"Template path\");\n\n const templatePath = resolve(rootDir, entry.template);\n if (existsSync(templatePath)) {\n let html = readFileSync(templatePath, \"utf-8\");\n\n // Validate template has a mount point (flexible — accepts any element/quoting)\n const safeMountId = escapeHtml(mountId);\n const mountPattern = new RegExp(`id=[\"']${safeMountId}[\"']`);\n if (!mountPattern.test(html)) {\n throw new Error(\n `[ethisys-manifest] Custom template \"${entry.template}\" must contain an element with id=\"${mountId}\".`,\n );\n }\n\n html = html.replaceAll(\"{{SOURCE}}\", escapeHtml(entry.source!));\n return html;\n }\n }\n\n // Default minimal HTML shell.\n // Uses relative src (no leading /) so Vite's transformIndexHtml resolves\n // it against config.base correctly for CDN/subdirectory deployments.\n const safeTitle = escapeHtml(entry.title ?? \"Plugin\");\n const safeSource = escapeHtml(entry.source!);\n const safeMountId = escapeHtml(mountId);\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${safeTitle}</title>\n </head>\n <body>\n <div id=\"${safeMountId}\"></div>\n <script type=\"module\" src=\"${safeSource}\"></script>\n </body>\n</html>`;\n }\n\n // ── Manifest parsing ─────────────────────────────────────────────\n\n function readManifest(): ManifestEntry[] {\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n let manifest: Manifest;\n try {\n manifest = JSON.parse(raw) as Manifest;\n } catch {\n throw new Error(\n `[ethisys-manifest] Failed to parse manifest at \"${manifestAbsPath}\".`,\n );\n }\n\n const result: ManifestEntry[] = [];\n\n // Collect entries with a source field (pages + surfaces)\n for (const page of manifest.ui?.pages ?? []) {\n if (page.source) {\n result.push(page);\n }\n }\n for (const surface of manifest.ui?.surfaces ?? []) {\n if (surface.source) {\n result.push(surface);\n }\n }\n\n return result;\n }\n\n // ── Validation ───────────────────────────────────────────────────\n\n function validateEntries(): void {\n // Multiple routes can share the same entrypoint (SPA mode).\n // But each entrypoint can only have ONE source file.\n const entrypointSources = new Map<string, string>();\n\n for (const entry of entries) {\n const source = entry.source!;\n\n // Validate no path traversal or absolute paths (cross-platform)\n assertSafeRelativePath(source, \"Source path\");\n\n // Validate source file exists on disk\n const sourcePath = resolve(rootDir, source);\n if (!existsSync(sourcePath)) {\n throw new Error(\n `[ethisys-manifest] Source file \"${source}\" for entry \"${entry.entrypoint}\" does not exist.`,\n );\n }\n\n // Validate entrypoint → source uniqueness\n const existingSource = entrypointSources.get(entry.entrypoint);\n if (existingSource && existingSource !== source) {\n throw new Error(\n `[ethisys-manifest] Conflicting sources for entrypoint \"${entry.entrypoint}\": ` +\n `\"${existingSource}\" and \"${source}\". ` +\n `Only one source file can be mapped to a single entrypoint.`,\n );\n }\n entrypointSources.set(entry.entrypoint, source);\n }\n }\n\n // ── Vite Plugin Hooks ────────────────────────────────────────────\n\n return {\n name: \"ethisys-manifest\",\n enforce: \"pre\",\n\n config(config, { command }) {\n rootDir = config.root ?? process.cwd();\n manifestAbsPath = resolve(rootDir, manifestRelPath);\n entries = readManifest();\n\n if (entries.length === 0) {\n return;\n }\n\n validateEntries();\n\n // Inject Rollup inputs for build mode.\n // ALL entries are virtual — including index.html.\n if (command === \"build\") {\n const input: Record<string, string> = {};\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (seen.has(entry.entrypoint)) {\n continue;\n }\n seen.add(entry.entrypoint);\n\n const name = entry.entrypoint.replace(/\\.html$/, \"\");\n input[name] = slash(resolve(rootDir, entry.entrypoint));\n }\n\n return {\n build: {\n rollupOptions: {\n input,\n },\n },\n };\n }\n },\n\n // Dev server: intercept HTML requests and serve virtual HTML.\n // Pre-middleware — runs before Vite's built-in handlers.\n // Safe because we only respond to .html requests and SPA navigation;\n // module requests (/@vite/client, /@react-refresh, .ts/.tsx/.css files)\n // don't match our conditions and pass through to Vite's transform middleware.\n configureServer(server: ViteDevServer) {\n server.watcher.add(manifestAbsPath);\n\n server.middlewares.use(async (req, res, next) => {\n try {\n const url = req.url?.split(\"?\")[0] ?? \"\";\n const acceptsHtml = req.headers.accept?.includes(\"text/html\");\n\n // 1. Explicit .html or root requests → match against entry points\n if (url.endsWith(\".html\") || url === \"/\" || url === \"/index.html\") {\n const filename =\n url === \"/\" || url === \"/index.html\"\n ? \"index.html\"\n : url.slice(1);\n\n const entry = entries.find((e) => e.entrypoint === filename);\n if (entry) {\n // Cache the Promise to prevent stampede on concurrent requests (PERF-5)\n const cacheKey = `entry:${filename}`;\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(entry);\n htmlCache.set(cacheKey, server.transformIndexHtml(url, rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n // 2. SPA fallback: non-file navigation requests (e.g., /books/catalog\n // refreshed in the browser) → serve index.html for client-side routing.\n // Only triggers for requests that explicitly Accept text/html (browser\n // navigation), not module/asset requests which use Accept: */*.\n if (acceptsHtml && !url.includes(\".\")) {\n const mainEntry = entries.find(\n (e) => e.entrypoint === \"index.html\",\n );\n if (mainEntry) {\n // SPA uses entrypoint as cache key (not url) to avoid unbounded cache growth\n const cacheKey = \"spa:index.html\";\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(mainEntry);\n htmlCache.set(cacheKey, server.transformIndexHtml(\"/\", rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n next();\n } catch (err) {\n next(err);\n }\n });\n },\n\n // Watch manifest for changes during dev — reload entries on edit.\n // Entire handler is wrapped in try/catch so JSON syntax errors in the\n // manifest don't crash the dev server (common during active editing).\n handleHotUpdate({ file, server }) {\n if (slash(file) === slash(manifestAbsPath)) {\n try {\n entries = readManifest();\n validateEntries();\n // Invalidate HTML cache on manifest change (PERF-5)\n htmlCache.clear();\n } catch (e) {\n server.config.logger.error(String(e));\n return [];\n }\n\n server.config.logger.info(\n \"[ethisys-manifest] Manifest changed — reloading entries\",\n );\n server.hot.send({ type: \"full-reload\" });\n return [];\n }\n },\n\n // Build: resolve virtual HTML module IDs (no physical files exist on disk)\n resolveId(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return id;\n }\n },\n\n // Build: provide virtual HTML content for Rollup\n load(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return generateHtml(match);\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/contract-a/schema-validator.ts","../src/contract-a/emit.ts","../src/contract-b/rewrite-imports.ts","../src/contract-b/worker-bundle.ts","../src/utils/strings.ts","../src/platform-react/scope-plugin-css.ts","../src/platform-react/build-pages.ts","../src/platform-react/page-bundles.ts","../src/platform-react/test-helpers.ts","../src/platform-react/generate-manifest.ts","../src/iframeSandboxPlugin.ts","../src/index.ts"],"names":["readManifest","normalize","isAbsolute","resolve","existsSync","readFileSync","slash","end","assertHostOriginRelativePath","createHash","ID_REGEX","walk","writeFileSync","DIGEST_MAP_FILENAME","sep","defaultWriteFile","mkdirSync","dirname","assertSafeRelativePath","safeMountId"],"mappings":";;;;;;AAgDA,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAY,gBAAgB,CAAA;AAC5D,IAAM,kBAAA,GAAqB,IAAI,GAAA,CAAY,eAAe,CAAA;AAC1D,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAY,gBAAgB,CAAA;AAO5D,SAAS,cAAc,IAAA,EAA8C;AACnE,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACrB,IAAA,OAAO,EAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CACV,GAAA,CAAI,CAAC,GAAA,KAAQ;AACZ,IAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,IAAA,OAAO,EAAE,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAA,CAAE,OAAA,CAAQ,OAAO,IAAI,CAAA;AAAA,EAClD,CAAC,CAAA,CACA,IAAA,CAAK,GAAG,CAAA;AACb;AAOA,SAAS,eAAA,CACP,KACA,KAAA,EACoB;AAEpB,EAAA,IAAI,KAAA,CAAM,IAAA,KAAS,eAAA,IAAmB,KAAA,CAAM,SAAS,oBAAA,EAAsB;AACzE,IAAA,MAAM,WAAY,KAAA,CAA4C,QAAA;AAC9D,IAAA,IAAI,OAAO,aAAa,QAAA,EAAU;AAChC,MAAA,OAAO,QAAA;AAAA,IACT;AAAA,EACF;AAIA,EAAA,IAAI,GAAA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\n SduiNode,\n ReactiveRule,\n KNOWN_PRIMITIVES,\n KNOWN_OPERATORS,\n KNOWN_RULE_KINDS,\n} from \"@ethisyscore/protocol\";\n\n/**\n * Minimal structural shape of a Zod parse issue. Declared locally so the\n * vite-plugin package does not need a direct `zod` peer/runtime dependency —\n * the protocol package owns Zod, we just consume parse results.\n */\ninterface ZodLikeIssue {\n readonly code: string;\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n}\n\n/**\n * A single, structured validation failure surfaced by the Contract A\n * schema validators. Carries enough context for a build-time error\n * to be actionable without the plugin author opening the host runtime.\n */\nexport interface ValidationFailure {\n /** Absolute path of the source file whose JSON failed validation. */\n filePath: string;\n /**\n * JSON-pointer (RFC 6901) into the failing JSON document, pointing at\n * the offending node. Empty string when the offender is the root.\n */\n pointer: string;\n /** The offending operator / primitive / rule-kind name, if extractable. */\n offender?: string;\n /** Human-readable message suitable for surfacing at the build CLI. */\n message: string;\n}\n\n/**\n * Result of a validation call. Discriminated on `ok` so callers can branch\n * narrowly without juggling exception flow for expected outcomes.\n */\nexport type ValidationResult =\n | { ok: true }\n | { ok: false; failures: ValidationFailure[] };\n\n// ── Internal: Zod issue → ValidationFailure ─────────────────────\n\nconst KNOWN_PRIMITIVE_SET = new Set<string>(KNOWN_PRIMITIVES);\nconst KNOWN_OPERATOR_SET = new Set<string>(KNOWN_OPERATORS);\nconst KNOWN_RULE_KIND_SET = new Set<string>(KNOWN_RULE_KINDS);\n\n/**\n * Convert a Zod path array into a JSON Pointer (RFC 6901) string.\n *\n * Numeric segments stay as array indices, string segments are escaped per RFC.\n */\nfunction toJsonPointer(path: ReadonlyArray<string | number>): string {\n if (path.length === 0) {\n return \"\";\n }\n return \"/\" + path\n .map((seg) => {\n const s = String(seg);\n return s.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n })\n .join(\"/\");\n}\n\n/**\n * Walks the original JSON value and the Zod path to extract a likely offender\n * string. For unknown SDUI primitives the offender is the rejected `type`\n * value; for unknown JsonLogic operators the offender is the offending key.\n */\nfunction extractOffender(\n doc: unknown,\n issue: ZodLikeIssue,\n): string | undefined {\n // 1. enum mismatch — the offender is the input value\n if (issue.code === \"invalid_value\" || issue.code === \"invalid_enum_value\") {\n const received = (issue as unknown as { received?: unknown }).received;\n if (typeof received === \"string\") {\n return received;\n }\n }\n\n // 2. invalid_union (the operator object), or refine refusal — walk to the path\n // and look for an object whose only key is unknown.\n let cur: unknown = doc;\n for (const seg of issue.path) {\n if (cur === null || cur === undefined) {\n break;\n }\n cur = (cur as Record<string | number, unknown>)[seg as string | number];\n }\n if (cur && typeof cur === \"object\" && !Array.isArray(cur)) {\n const keys = Object.keys(cur as object);\n if (keys.length === 1 && !KNOWN_OPERATOR_SET.has(keys[0])) {\n return keys[0];\n }\n }\n\n // 3. Fall back to last path segment (e.g. an unknown rule-kind)\n if (issue.path.length > 0) {\n const last = issue.path[issue.path.length - 1];\n if (typeof last === \"string\" && !KNOWN_RULE_KIND_SET.has(last) && !KNOWN_PRIMITIVE_SET.has(last)) {\n return last;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert a Zod parse failure into structured {@link ValidationFailure}s.\n *\n * One Zod issue → one failure, preserving order. The original JSON `doc`\n * is walked in tandem with each issue's path so the offender name (an\n * unknown primitive, operator, or rule-kind) can be lifted into the\n * failure record.\n */\nfunction zodIssuesToFailures(\n doc: unknown,\n issues: readonly ZodLikeIssue[],\n filePath: string,\n): ValidationFailure[] {\n return issues.map((issue) => {\n const pointer = toJsonPointer(issue.path);\n const offender = extractOffender(doc, issue);\n const offenderSuffix = offender ? ` (offender: '${offender}')` : \"\";\n return {\n filePath,\n pointer,\n offender,\n message: `${filePath}${pointer ? ` at ${pointer}` : \"\"}: ${issue.message}${offenderSuffix}`,\n };\n });\n}\n\n/**\n * Validate a single declarative SDUI resource against the protocol's\n * {@link SduiNode} Zod schema. The recursive schema rejects unknown\n * primitives and unknown JsonLogic operators at any depth of the tree.\n *\n * `filePath` is propagated into every emitted failure so the build CLI\n * can point the author at the exact file on disk.\n */\nexport function validateDeclarativeResource(\n doc: unknown,\n uri: string,\n filePath: string,\n): ValidationResult {\n const parsed = SduiNode.safeParse(doc);\n if (parsed.success) {\n return { ok: true };\n }\n const failures = zodIssuesToFailures(doc, parsed.error.issues, filePath);\n // Tag the URI onto every message so the build CLI shows which resource failed.\n return {\n ok: false,\n failures: failures.map((f) => ({\n ...f,\n message: `[resource ${uri}] ${f.message}`,\n })),\n };\n}\n\n/**\n * Validate a single {@link ReactiveRule} against the protocol's curated\n * JsonLogic operator subset. Used for top-level reactivity declarations\n * declared on the manifest itself (i.e. not embedded under a `bindings`\n * key on a SDUI node — those are covered by {@link validateDeclarativeResource}).\n */\nexport function validateReactiveRule(\n rule: unknown,\n filePath: string,\n): ValidationResult {\n const parsed = ReactiveRule.safeParse(rule);\n if (parsed.success) {\n return { ok: true };\n }\n return {\n ok: false,\n failures: zodIssuesToFailures(rule, parsed.error.issues, filePath),\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type { Plugin } from \"vite\";\n\nimport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationFailure,\n} from \"./schema-validator\";\n\n// ── Manifest shapes (subset) ───────────────────────────────────\n\n/**\n * Reference from the plugin manifest to an SDUI resource JSON file.\n *\n * Wave 0 convention: the manifest declares each declarative resource with\n * a stable `uri` plus a `file` path (relative to the manifest's directory)\n * pointing at the JSON document the host will serve. The static-file\n * convention lets the Vite plugin validate the tree at build time without\n * having to execute plugin runtime code.\n */\nexport interface ManifestResourceRef {\n uri: string;\n /**\n * Relative path (POSIX or platform-native) to the SDUI JSON document.\n * Must not be absolute, must not contain `..` traversal segments.\n */\n file?: string;\n}\n\n/**\n * Top-level manifest reactivity-rule declaration. Each entry pairs an\n * author-supplied identifier with a {@link import(\"@ethisyscore/protocol\").ReactiveRule}.\n *\n * Reactivity declared inline on SDUI nodes (the `bindings` property) is\n * validated by the SDUI-tree pass; this surface covers the rarer case of\n * a manifest-level rule that applies cross-resource.\n */\nexport interface ManifestReactiveRuleRef {\n id: string;\n rule: unknown;\n}\n\n/**\n * The subset of the plugin manifest the Contract A Vite plugin pass cares\n * about. The full manifest is intentionally a superset — the plugin\n * tolerates additional fields it has not been taught yet so manifests\n * built against a newer schema still load.\n */\nexport interface ContractAManifest {\n resources?: ManifestResourceRef[];\n reactiveRules?: ManifestReactiveRuleRef[];\n [key: string]: unknown;\n}\n\n// ── Options ────────────────────────────────────────────────────\n\n/**\n * Author-facing options for the Contract A Vite plugin pass.\n *\n * `root` defaults to Vite's resolved root at `configResolved` time, so the\n * common case requires no configuration. `manifestPath` defaults to the\n * `feature.manifest.json` convention emitted by the host-rendered\n * scaffolding template; pass an absolute or relative path to override.\n */\nexport interface ContractAPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json` colocated with the Vite root.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted SDUI assets. Defaults to `sdui/`. The plugin\n * always emits an `${prefix}sdui-manifest.json` index alongside the\n * validated resource JSON.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────\n\n/** Slug-encode a resource URI into a filesystem-safe asset filename. */\nfunction slugForUri(uri: string): string {\n return uri.replace(/[^a-zA-Z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\n/** Reject path traversal and absolute paths in author-supplied references. */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/**\n * Render a {@link ValidationFailure} list into the multi-line build-failure\n * message Vite will surface to the author.\n */\nfunction formatFailures(failures: ValidationFailure[]): string {\n const lines = failures.map((f, i) => ` ${i + 1}. ${f.message}`);\n return [\n `[@ethisyscore/vite-plugin] Contract A schema validation failed:`,\n ...lines,\n ].join(\"\\n\");\n}\n\n// ── Plugin ─────────────────────────────────────────────────────\n\ninterface EmittedResource {\n uri: string;\n fileName: string;\n}\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract A\n * (`renderMode: host-rendered`) plugins.\n *\n * Reads `feature.manifest.json` (or `extension.manifest.json` via\n * `manifestPath`), validates each declared SDUI resource against the\n * protocol's `SduiNode` Zod schema, validates each manifest-level\n * reactivity rule against `ReactiveRule`, and emits the validated JSON\n * into the Rollup bundle under the configured output prefix. Validation\n * failures abort the build with a multi-line structured error that names\n * the offending operator/primitive and the source file path + JSON\n * pointer so the author can land on the offending node immediately.\n *\n * Worker-bundle emission for `renderMode: remote-runtime` is deferred to\n * Wave 1's E7.S1b — this pass deliberately does nothing for non-Contract-A\n * manifests.\n */\nexport function ethisysContractAPlugin(\n options: ContractAPluginOptions = {},\n): Plugin {\n const outputPrefix = (options.outputPrefix ?? \"sdui/\").replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let validatedResources: EmittedResource[] = [];\n // Plugin-internal cache so generateBundle can re-emit without re-reading + re-parsing.\n const resourcePayloads = new Map<string, string>();\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractAManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractAManifest;\n } catch (e) {\n throw new Error(\n `[@ethisyscore/vite-plugin] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n function validate(): void {\n validatedResources = [];\n resourcePayloads.clear();\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n\n const failures: ValidationFailure[] = [];\n\n // ── Resources ───────────────────────────────────────────────\n for (const ref of manifest.resources ?? []) {\n if (!ref.file) {\n // A resource without a `file` field is a dynamic / runtime-rendered\n // resource. The Vite plugin can't introspect those at build time;\n // skip them.\n continue;\n }\n assertSafeRelativePath(ref.file, \"Resource file path\");\n\n const filePath = resolve(resolvedRoot, ref.file);\n if (!existsSync(filePath)) {\n failures.push({\n filePath,\n pointer: \"\",\n message:\n `[resource ${ref.uri}] file \"${ref.file}\" referenced by the manifest does not exist on disk (resolved: ${filePath}).`,\n });\n continue;\n }\n\n const rawJson = readFileSync(filePath, \"utf-8\");\n let doc: unknown;\n try {\n doc = JSON.parse(rawJson);\n } catch (e) {\n failures.push({\n filePath,\n pointer: \"\",\n message: `[resource ${ref.uri}] failed to parse JSON: ${(e as Error).message}`,\n });\n continue;\n }\n\n const result = validateDeclarativeResource(doc, ref.uri, filePath);\n if (!result.ok) {\n failures.push(...result.failures);\n continue;\n }\n\n // Serialise canonically (validated input → emitted payload) so the\n // host always sees a byte-stable artefact regardless of source whitespace.\n const fileName = `${outputPrefix}${slugForUri(ref.uri)}.json`;\n const payload = JSON.stringify(doc);\n resourcePayloads.set(fileName, payload);\n validatedResources.push({ uri: ref.uri, fileName });\n }\n\n // ── Manifest-level reactive rules ────────────────────────────\n for (const ruleRef of manifest.reactiveRules ?? []) {\n const result = validateReactiveRule(ruleRef.rule, manifestAbsPath);\n if (!result.ok) {\n failures.push(\n ...result.failures.map((f) => ({\n ...f,\n message: `[reactiveRule ${ruleRef.id}] ${f.message}`,\n })),\n );\n }\n }\n\n if (failures.length > 0) {\n throw new Error(formatFailures(failures));\n }\n }\n\n return {\n name: \"ethisys-contract-a\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing a resource JSON.\n validate();\n },\n\n generateBundle() {\n if (validatedResources.length === 0) {\n return;\n }\n\n // Emit each validated resource as a static asset.\n for (const { fileName } of validatedResources) {\n const source = resourcePayloads.get(fileName);\n if (source === undefined) {\n continue;\n }\n this.emitFile({ type: \"asset\", fileName, source });\n }\n\n // Emit a compact index so the host can list contracts without\n // walking the bundle. `name` is stable per build; `resources` is\n // sorted by URI for deterministic output.\n const sorted = [...validatedResources].sort((a, b) =>\n a.uri.localeCompare(b.uri),\n );\n const index = {\n version: 1,\n resources: sorted.map(({ uri, fileName }) => ({ uri, file: fileName })),\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}sdui-manifest.json`,\n source: JSON.stringify(index),\n });\n },\n };\n}\n","// ── Contract B safe-import rewriter ────────────────────────────────\n//\n// Static ES `import` statements with bare specifiers are unresolvable inside\n// a Contract B worker realm: the worker has no `<script type=\"importmap\">`\n// surface (workers don't host scripts) and the spec's `WorkerOptions.importMap`\n// is still proposal-stage in 2026-05. The bootstrap script\n// (`WorkerBootstrapScriptProvider.cs` in the API repo) composes a frozen\n// `IMPORT_MAP` per worker and exposes a synchronous-wrapper-free helper at\n// `globalThis.__ethisysSafeImport(spec) -> Promise<Module>`.\n//\n// The build-time complement to that runtime surface lives here: every static\n// `import` whose specifier is on the closed Contract B allowlist is rewritten\n// into a top-level `await` against `__ethisysSafeImport`. Module workers\n// support top-level await; the host loads the plugin bundle via dynamic\n// `import(moduleUrl)` which awaits the bundle's top-level evaluation, so the\n// `mod.activate(port)` call site sees a fully-initialised module.\n//\n// Specifiers outside the allowlist would not survive `Rollup.external` (which\n// the Contract B config already enforces), so this rewriter never observes\n// them in practice. It still guards against the case defensively — a future\n// `external` widening should not silently emit bare specifiers the worker\n// realm cannot resolve.\n\nconst STATIC_IMPORT_RE = /^([ \\t]*)import[ \\t]+(.*?)[ \\t]*;?[ \\t]*$/gm;\n\n/**\n * Rewrite static ES `import` statements whose specifier is a bare allowlist\n * entry into a top-level `await globalThis.__ethisysSafeImport(...)` form.\n *\n * Non-bare specifiers (relative paths, http(s) URLs, data:/blob:/javascript:\n * schemes) are passed through untouched. Dynamic `import()` calls are passed\n * through untouched. Bare specifiers outside `allowlist` are passed through\n * untouched — the surrounding `external` config is the gate; this function\n * only rewrites what the build pipeline contract guarantees.\n */\nexport function rewriteSafeImports(\n code: string,\n allowlist: readonly string[],\n): string {\n const allowSet = new Set(allowlist);\n\n return code.replace(STATIC_IMPORT_RE, (match, indent: string, body: string) => {\n const rewrite = tryRewriteImport(body, allowSet);\n return rewrite === null ? match : `${indent}${rewrite}`;\n });\n}\n\nfunction convertNamedBindings(namedClause: string): string {\n // `{ A, B as Local, C }` -> `A, B: Local, C` (object-destructuring rename form)\n const inner = namedClause.slice(1, -1).trim();\n if (inner.length === 0) {\n return \"\";\n }\n const parts = inner.split(\",\").map((p) => p.trim()).filter((p) => p.length > 0);\n const converted = parts.map((part) => {\n const asMatch = part.match(/^(\\w[\\w$]*)\\s+as\\s+(\\w[\\w$]*)$/);\n return asMatch === null ? part : `${asMatch[1]}: ${asMatch[2]}`;\n });\n return converted.join(\", \");\n}\n\nfunction tryRewriteImport(body: string, allowSet: ReadonlySet<string>): string | null {\n // Side-effect: `\"Button\"` or `'Button'`\n const sideEffect = body.match(/^[\"']([^\"']+)[\"']$/);\n if (sideEffect !== null) {\n const spec = sideEffect[1];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default + named: `React, { useState, useEffect as fx } from \"react\"`\n const defaultPlusNamed = body.match(\n /^(\\w[\\w$]*)\\s*,\\s*(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/,\n );\n if (defaultPlusNamed !== null) {\n const defaultLocal = defaultPlusNamed[1];\n const namedClause = defaultPlusNamed[2];\n const spec = defaultPlusNamed[3];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n const inner = bindings.length === 0\n ? `default: ${defaultLocal}`\n : `default: ${defaultLocal}, ${bindings}`;\n return `const { ${inner} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default-only: `Foo from \"Button\"`\n const defaultOnly = body.match(/^(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (defaultOnly !== null) {\n const local = defaultOnly[1];\n const spec = defaultOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const { default: ${local} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Named only: `{ A, B as Local } from \"react\"`\n const namedOnly = body.match(/^(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namedOnly !== null) {\n const namedClause = namedOnly[1];\n const spec = namedOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n return `const { ${bindings} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Namespace: `* as N from \"react\"`\n const namespaceOnly = body.match(/^\\*\\s+as\\s+(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namespaceOnly !== null) {\n const local = namespaceOnly[1];\n const spec = namespaceOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const ${local} = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n return null;\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize, sep } from \"node:path\";\nimport { rewriteSafeImports } from \"./rewrite-imports\";\nimport type { Plugin } from \"vite\";\n\n// ── Frozen import-map allowlist (E4.S4) ────────────────────────────\n//\n// The Contract B worker realm can ONLY import these bare specifiers. The\n// runtime side (`WorkerBootstrapScriptProvider` in the API repo) enforces the\n// same allowlist by composing a frozen `IMPORT_MAP` at handshake time. The two\n// lists MUST agree — drift is caught by the `import-map-allowlist matches\n// extension-runtime CONTRACT_B_PRIMITIVES` test in `contract-b.test.ts`,\n// which imports `CONTRACT_B_PRIMITIVES` from the sibling extension-runtime\n// package and diffs it against {@link CONTRACT_B_SEMANTIC_PRIMITIVES} below.\n//\n// Plugin-supplied bare specifiers outside this list fail the build with a\n// structured error so authors get a build-time signal instead of a runtime\n// `import-map-violation` from the worker bootstrap.\n\n/**\n * Contract B semantic primitive vocabulary (the closed v1 set authored in\n * `sdk/extension-runtime/src/host/worker/component-registry.ts`). The names\n * mirror the registry exactly; a drift between the two breaks the cross-repo\n * agreement that E4.S4 locks in.\n */\nexport const CONTRACT_B_SEMANTIC_PRIMITIVES = [\n \"Button\",\n \"DataTable\",\n \"Form\",\n \"EntityPicker\",\n \"CommandBar\",\n \"Drawer\",\n \"Modal\",\n \"CanvasSurface\",\n \"WebGLSurface\",\n // Phase 1 additions (per Contract B + PlatformReact plan §Q6, frequency\n // survey of coreconnect-web Timesheets feature). Card / Tabs / Select /\n // Alert close the four most-common gaps in the v1 primitive set:\n // - Card: universal layout container, ~20 imports across surveyed pages.\n // - Tabs: settings / configuration surfaces (6 tabs in TimesheetSettings).\n // - Select: filter + form input, ~10 imports; Form's text input doesn't\n // cover dropdowns.\n // - Alert: lock/unlock warnings, validation banners, non-modal system\n // messages; Card doesn't carry severity semantics.\n \"Card\",\n \"Tabs\",\n \"Select\",\n \"Alert\",\n] as const;\n\n/**\n * Non-component import-map entries — the runtime libraries the worker is\n * permitted to resolve via bare specifiers. Authoring constraint: the plugin's\n * single ESM bundle (Contract B emits exactly one — see `worker-bundle.ts`)\n * can `import x from \"react\"` or `import { ... } from \"@ethisyscore/extension-runtime\"`\n * and nothing else off-bundle.\n */\nexport const CONTRACT_B_RUNTIME_IMPORTS = [\n \"react\",\n \"@ethisyscore/extension-runtime\",\n] as const;\n\n/**\n * Full allowlist of bare specifiers a Contract B plugin bundle may import.\n * Frozen at module load so plugins can't mutate it via a transitive dep.\n */\nexport const CONTRACT_B_IMPORT_MAP_ALLOWLIST: readonly string[] = Object.freeze([\n ...CONTRACT_B_RUNTIME_IMPORTS,\n ...CONTRACT_B_SEMANTIC_PRIMITIVES,\n]);\n\nconst ALLOWLIST_SET: ReadonlySet<string> = new Set(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * The subset of a Contract B (`renderMode: remote-runtime`) plugin manifest\n * that this Vite pass consumes. Manifests are tolerated as a superset — extra\n * fields are ignored so newer-schema manifests still load.\n */\nexport interface ContractBManifest {\n renderMode?: string;\n /**\n * Worker bundle declaration. Required when `renderMode === \"remote-runtime\"`.\n * The `entry` is a relative path (POSIX or platform-native) from the\n * manifest's directory to the plugin's TypeScript/JavaScript entrypoint.\n *\n * Absolute paths, path-traversal, and non-host-origin URLs are rejected at\n * build time — Contract B requires the worker bundle to be a host-origin\n * asset (the import-map enforcement in E4.S4 builds on this guarantee).\n */\n worker?: {\n entry?: string;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the Contract B Vite pass.\n */\nexport interface ContractBPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted worker assets and the worker-bundle manifest.\n * Defaults to `worker/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n // Remote URLs (any scheme + `://`) are forbidden — Contract B bundles must\n // be host-origin assets so the worker bootstrap's frozen import map can\n // enforce origin restrictions deterministically.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n // Reject `data:` / `blob:` (no `//`) too — also non-host-origin.\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/** Normalise Windows backslashes for the Rollup input table. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract B\n * (`renderMode: remote-runtime`) plugins.\n *\n * Behaviour:\n * - For `renderMode: \"remote-runtime\"`: declares a single ESM worker entry as\n * the Rollup input table. The output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so a Contract B plugin always ships as ONE\n * bundled module — no chunk splitting, no shared chunks, no async imports\n * spread across multiple files. This is the precondition for E4.S4's\n * frozen import map.\n * - For any other `renderMode` (including `host-rendered` and `undefined`):\n * the pass is a no-op. The Wave 0 Contract A path (`ethisysContractAPlugin`)\n * continues to apply without interference. Composition is expected — the\n * recommended template registers both plugins so a manifest can switch\n * render modes without changing its Vite config.\n *\n * The pass also emits a `worker/worker-bundle.json` companion asset listing\n * the bundled entry so the host (or downstream packaging) can inspect what\n * the build produced without re-parsing the bundle.\n *\n * Origin enforcement on the import map (path-pinned host origin, no `data:` /\n * `blob:` imports) is the responsibility of E4.S4 (worker bootstrap) — this\n * pass only blocks remote/absolute paths at the manifest layer so a malformed\n * manifest fails fast.\n */\nexport function ethisysContractBPlugin(\n options: ContractBPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"worker/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let workerEntryAbs: string | null = null;\n let workerEntryRel: string | null = null;\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractBManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractBManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-contract-b] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve the worker entry's absolute path.\n * Idempotent — repeated invocations return cached state.\n */\n function validate(): void {\n workerEntryAbs = null;\n workerEntryRel = null;\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n if (manifest.renderMode !== \"remote-runtime\") {\n // Non-Contract-B manifests are not our concern.\n return;\n }\n const entry = manifest.worker?.entry;\n if (typeof entry !== \"string\" || entry.length === 0) {\n throw new Error(\n `[ethisys-contract-b] manifest declares renderMode='remote-runtime' but no worker.entry. ` +\n `Set \"worker\": { \"entry\": \"src/worker.ts\" } (relative path).`,\n );\n }\n assertHostOriginRelativePath(entry, \"Worker entry\");\n\n const absPath = resolve(resolvedRoot, entry);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-contract-b] Worker entry file \"${entry}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n workerEntryAbs = absPath;\n workerEntryRel = entry;\n }\n\n return {\n name: \"ethisys-contract-b\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n /**\n * Declares the Rollup input table and locks the output to a single ESM\n * module. Only fires when the manifest opts in (`renderMode: remote-runtime`).\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n // `config` runs before `buildStart`, so we validate here too — the user\n // needs the structured error at the same lifecycle gate that fails.\n validate();\n\n if (workerEntryAbs === null) {\n return; // Non-Contract-B manifest: no-op.\n }\n\n // The allowlist runtime libraries (`react`, `@ethisyscore/extension-runtime`)\n // and the semantic primitive names are NOT bundled — they're host-served\n // and resolved by the frozen import map at worker bootstrap time. Mark\n // them as `external` so Rollup leaves the bare specifiers intact in the\n // emitted bundle (which is what `generateBundle` then inspects).\n const externalSpecifiers = new Set<string>(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n return {\n build: {\n rollupOptions: {\n input: { worker: slash(workerEntryAbs) },\n external: (id: string): boolean => externalSpecifiers.has(id),\n // CRITICAL: single-file output for the worker bundle. The\n // E4.S4 frozen import map presumes ONE module entry per plugin —\n // chunk splitting or dynamic-import shards would defeat it.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n },\n },\n };\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest.\n validate();\n },\n\n /**\n * Reject `data:` / `blob:` / `javascript:` URL specifiers at resolve time.\n *\n * Rollup normally externalises unknown URL schemes silently, which would\n * mean a malicious `import(\"data:text/javascript,...\")` survives the\n * build untouched and only fails at runtime (where the bootstrap script's\n * `safeImport` would catch it). We want build-time failure too — the\n * import-map contract is enforced at BOTH ends.\n */\n resolveId(source) {\n if (workerEntryAbs === null) {\n return null;\n }\n if (/^(data|blob|javascript):/i.test(source)) {\n const scheme = source.split(\":\", 1)[0];\n this.error(\n `[ethisys-contract-b] Contract B bundle imports forbidden URL scheme '${scheme}:' ` +\n `(specifier: \"${source.slice(0, 80)}${source.length > 80 ? \"...\" : \"\"}\"). ` +\n `The worker realm rejects ${scheme}: imports at runtime; the build rejects them too.`,\n );\n }\n return null;\n },\n\n /**\n * Rewrite the emitted worker chunk's static bare-specifier imports into\n * top-level `await globalThis.__ethisysSafeImport(...)` calls. This is\n * the build-time complement to the worker bootstrap's frozen IMPORT_MAP\n * (defined in CoreConnect-Api's WorkerBootstrapScriptProvider.cs). The\n * worker realm has no `<script type=\"importmap\">` surface, so static\n * bare specifiers reach the browser's native ES loader as\n * `Failed to resolve module specifier` errors at module load time.\n *\n * Returns `null` (no transform) when the manifest is not Contract B —\n * the Contract A path's emitted chunks are left untouched.\n */\n renderChunk(code: string, chunk: { type: string; fileName: string }): { code: string } | null {\n if (workerEntryAbs === null) {\n return null;\n }\n if (chunk.type !== \"chunk\") {\n return null;\n }\n const rewritten = rewriteSafeImports(code, CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n if (rewritten === code) {\n return null;\n }\n return { code: rewritten };\n },\n\n /**\n * Inspect the emitted bundle for out-of-allowlist bare specifiers and emit\n * the per-bundle `worker-bundle.import-map.json` manifest.\n *\n * Because we marked allowlist specifiers as `external` in `config`, any\n * other bare specifier that the plugin tried to import would have failed\n * Rollup's resolver upstream — but we re-check the surviving `chunk.imports`\n * here as belt-and-braces in case a future Rollup or Vite change relaxes\n * the resolver path. Defence in depth at the build layer matches the\n * defence in depth at the runtime layer (E4.S3 bootstrap).\n */\n generateBundle(_outputOptions, bundle) {\n if (workerEntryAbs === null || workerEntryRel === null) {\n return;\n }\n\n const importedSpecifiers = new Set<string>();\n const violations: string[] = [];\n\n for (const [, chunk] of Object.entries(bundle)) {\n if (chunk.type !== \"chunk\") {\n continue;\n }\n // Both static imports (`chunk.imports`) and dynamic imports\n // (`chunk.dynamicImports`) are surveyed. `inlineDynamicImports: true`\n // collapses dynamic-imported chunks INTO the host chunk, but the\n // specifiers themselves still surface here for externalised IDs.\n const candidates: string[] = [\n ...(chunk.imports ?? []),\n ...(chunk.dynamicImports ?? []),\n ];\n for (const spec of candidates) {\n // Relative / absolute paths are emitted bundle artefacts — not\n // bare specifiers, not subject to the import-map. Skip them.\n if (spec.startsWith(\".\") || spec.startsWith(\"/\") || isAbsolute(spec)) {\n continue;\n }\n // URL-scheme specifiers should have been caught in `resolveId`,\n // but a relaxed-resolver path could let one through. Reject here too.\n if (/^[a-z][a-z0-9+.-]*:/i.test(spec)) {\n violations.push(spec);\n continue;\n }\n if (!ALLOWLIST_SET.has(spec)) {\n violations.push(spec);\n continue;\n }\n importedSpecifiers.add(spec);\n }\n }\n\n if (violations.length > 0) {\n // Sort + de-dupe for deterministic error message ordering.\n const unique = [...new Set(violations)].sort();\n this.error(\n `[ethisys-contract-b] Worker bundle imports specifier(s) outside the frozen import-map ` +\n `allowlist: ${unique.map(s => `\"${s}\"`).join(\", \")}. ` +\n `Allowed bare specifiers: ${CONTRACT_B_IMPORT_MAP_ALLOWLIST.map(s => `\"${s}\"`).join(\", \")}.`,\n );\n }\n\n // Sort the resolved entries so the emitted manifest is deterministic\n // across builds — content-hashable downstream without spurious churn.\n const resolvedEntries = [...importedSpecifiers].sort();\n\n const workerBundleManifest = {\n version: 1,\n renderMode: \"remote-runtime\",\n worker: { entry: workerEntryRel },\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.json`,\n source: JSON.stringify(workerBundleManifest),\n });\n\n // The import-map manifest — the host fetches this at extension activation\n // time to auto-derive the frozen `IMPORT_MAP` the worker bootstrap\n // composes. Values are `null` to signal \"host fills in canonical URL at\n // serve time\" — the manifest is the SDK's authoritative list of which\n // entries the bundle declares it consumes, not a URL table.\n const importMapManifest = {\n version: 1,\n // Authoring contract: the bundle's bare-specifier surface area, in\n // sorted order, restricted to the frozen allowlist.\n imports: Object.fromEntries(resolvedEntries.map(spec => [spec, null])),\n // Mirror the canonical allowlist so consumers diffing manifests\n // across plugin versions can see the contract the build verified\n // against without re-reading SDK source.\n allowlist: [...CONTRACT_B_IMPORT_MAP_ALLOWLIST],\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.import-map.json`,\n source: JSON.stringify(importMapManifest),\n });\n },\n };\n}\n","/**\n * Small, dependency-free string helpers shared across the SDK's build-step tooling\n * (e.g. the PlatformReact manifest generator). Pure functions — no I/O, no state.\n */\n\n/** Normalise Windows backslashes to forward slashes (for manifest/module paths). */\nexport function slash(p: string): string {\n return p.replace(/\\\\/g, \"/\");\n}\n\n/**\n * Convert a PascalCase / camelCase / snake_case identifier to kebab-case, e.g.\n * `CompanyCosts` → `company-costs`, `ToolMappings` → `tool-mappings`,\n * `already_snake` → `already-snake`. A digit stays attached to its preceding letter\n * (`TaxYear2024` → `tax-year2024`).\n */\nexport function kebab(s: string): string {\n return s.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").replace(/_/g, \"-\").toLowerCase();\n}\n\n/**\n * Convert a PascalCase / camelCase identifier to spaced Title Case, e.g.\n * `companyCosts` → `Company Costs`, `ToolMappings` → `Tool Mappings`. Inserts a\n * space at each lower/digit→upper boundary and upper-cases the first character.\n */\nexport function titleCase(s: string): string {\n return s.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/^./, (c) => c.toUpperCase());\n}\n\n/**\n * Escape regex metacharacters so an interpolated string matches literally — e.g.\n * `new RegExp(escapeRegExp(userInput))` treats `.` `*` `(` etc. as literal text.\n */\nexport function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Scope selector prefixed onto plugin-global CSS layers.\n *\n * `:where()` NOT `:is()` on purpose: `:where()` contributes ZERO specificity, so a\n * scoped utility keeps exactly the specificity it had unscoped. Inside a plugin\n * surface the cascade therefore behaves identically to before this transform; the\n * only change is that the rule no longer matches host chrome. `:is()` would have\n * raised every utility by one class and could flip a plugin's own conflicts.\n *\n * Two scope roots: the plugin root applied by `definePlatformReactPluginPage`, and\n * the portal container marker, because MUI overlays render into a portal. Phase 1\n * (`PluginPortalScope`) puts that container INSIDE the plugin root, so the second\n * arm is redundant for SDK-managed overlays and exists for a plugin that supplies\n * its own container element and marks it.\n */\nexport const EHX_PLUGIN_CSS_SCOPE = \":where(.ehx-plugin-root, [data-ehx-plugin-portal])\";\n\n/**\n * Replacement for a document-root selector (`:root`, `:host`) in a plugin sheet.\n *\n * Tailwind's `theme` layer declares its scale as custom properties on\n * `:root, :host` — `--spacing`, `--text-sm--line-height`, `--ease-*`,\n * `--animate-*`. Injected into the host document that lands on the HOST root and\n * silently redefines the host's own Tailwind scale for every element on the page:\n * the same defect as the leaking utilities, one level deeper and inherited.\n *\n * These declarations cannot simply be dropped — the plugin's utilities read them —\n * and prefixing is meaningless (`:where(.ehx-plugin-root) :root` matches nothing).\n * They are REPLACED with the plugin root, which the whole surface inherits from.\n *\n * `:is()` here, not `:where()`: this is a substitution for a 0,1,0 selector, so\n * matching that specificity is the faithful choice (a prefix is what must stay\n * specificity-neutral). Note this only works because portal containment landed\n * first — before that, overlays rendered outside the plugin root and would have\n * lost the whole theme scale.\n */\nexport const EHX_PLUGIN_ROOT_SCOPE = \":is(.ehx-plugin-root, [data-ehx-plugin-portal])\";\n\n/**\n * Cascade layers whose rules a plugin emits UNSCOPED and which therefore leak into\n * the host document.\n *\n * utilities Tailwind's generated utility classes. The leak that motivated this:\n * a plugin's bare `.text-sm` is a duplicate of the host's own rule,\n * so it changes nothing until the host settles a specificity tie by\n * source order — then the plugin's copy, injected later, wins and\n * silently restyles host chrome.\n * properties Tailwind's `@property` fallback block, which sets ~40 `--tw-*`\n * custom properties on `*, :before, :after, ::backdrop` for the whole\n * document.\n *\n * The other layers are already scoped: `theme` holds custom properties on the\n * plugin's own root class, and `base`/`components`/`mui` come from the SDK's\n * `plugin-base.css`, which scopes everything to `.ehx-plugin-root`.\n */\nexport const EHX_SCOPED_CSS_LAYERS: readonly string[] = [\"utilities\", \"properties\"];\n\n/**\n * At-rules whose blocks hold DESCRIPTORS or keyframe selectors, not style rules.\n * Copied through untouched: prefixing `from`/`to`/`50%` or a descriptor block\n * would produce invalid CSS.\n */\nconst VERBATIM_AT_RULES = new Set([\n \"keyframes\",\n \"-webkit-keyframes\",\n \"property\",\n \"font-face\",\n \"font-feature-values\",\n \"font-palette-values\",\n \"counter-style\",\n \"page\",\n \"viewport\",\n]);\n\n/**\n * At-rules that merely CONDITION the style rules inside them. Descended into: the\n * inner selectors get scoped, the at-rule prelude does not. Tailwind emits variant\n * utilities inside `@media`/`@supports`, so missing these would leave a hole.\n *\n * An at-rule in neither set is copied verbatim. That is the safe default (never\n * emit invalid CSS) at the cost of leaving a leak, so a new wrapper at-rule in a\n * future Tailwind needs adding here.\n */\nconst CONDITIONAL_AT_RULES = new Set([\n \"media\",\n \"supports\",\n \"container\",\n \"layer\",\n \"scope\",\n \"starting-style\",\n \"document\",\n \"-moz-document\",\n]);\n\n/**\n * What counts as \"scoped to a plugin\" — the convention every plugin front-end\n * adheres to, and the only thing the build guard needs to know.\n *\n * .ehx-plugin-root applied to every surface by the SDK page definer\n * .ethisys-<name>-root the plugin's own root class (all plugins use this\n * shape: ethisys-sales-root, ethisys-hr-root, …)\n * [data-ehx-plugin-portal] the portal container overlays render into\n * :where(…) of the above what {@link scopePluginCss} emits\n *\n * A selector that mentions NONE of these can match host chrome, which is the whole\n * defect class. Matching anywhere in the selector (not just leftmost) is deliberate:\n * `:where(.dark) .ethisys-sales-root` is scoped even though the root is not first.\n */\nexport const EHX_PLUGIN_SCOPE_ROOTS: readonly RegExp[] = [\n /\\.ehx-plugin-root\\b/,\n /\\.ethisys-[a-z0-9-]+-root\\b/,\n /\\[data-ehx-plugin-portal\\]/,\n];\n\nexport interface ScopePluginCssOptions {\n /** Descendant scope prefix. Default {@link EHX_PLUGIN_CSS_SCOPE}. */\n scope?: string;\n /** Replacement for `:root`/`:host`. Default {@link EHX_PLUGIN_ROOT_SCOPE}. */\n rootScope?: string;\n /** Layer names to scope. Default {@link EHX_SCOPED_CSS_LAYERS}. */\n layers?: readonly string[];\n /** What counts as scoped for the guard. Default {@link EHX_PLUGIN_SCOPE_ROOTS}. */\n scopeRoots?: readonly RegExp[];\n /**\n * Guard behaviour when a selector would leak into the host document:\n * `\"error\"` (default) fails the build, `\"warn\"` logs, `\"off\"` skips the check.\n * Only reach for anything but `\"error\"` as a deliberate, time-boxed exception.\n */\n guard?: \"error\" | \"warn\" | \"off\";\n}\n\ninterface Ctx {\n scope: string;\n rootScope: string;\n layers: Set<string>;\n}\n\n/**\n * Leading document-root selector. Matched at the START of a compound only, so\n * `:root .foo` becomes `<scope> .foo` and a `:root` deeper in a selector (which\n * would not be a document-root reference) is left alone.\n */\nconst DOCUMENT_ROOT_PREFIX = /^:(?:root|host)\\b/;\n\n// ── String scanning primitives ─────────────────────────────────────\n//\n// A hand-rolled walker rather than a CSS parser dependency: the transform runs in\n// every plugin's build, and the shapes it must survive are narrow (a compiled\n// Tailwind sheet). Escapes matter more than they look — Tailwind class names are\n// full of them (`.sm\\:flex`, `.w-\\[calc\\(100\\%-2rem\\)\\]`, `.content-\\[\\'\\{\\'\\]`),\n// and an escaped brace inside a selector would desynchronise naive brace counting.\n\nfunction isSpace(ch: string): boolean {\n return ch === \" \" || ch === \"\\n\" || ch === \"\\t\" || ch === \"\\r\" || ch === \"\\f\";\n}\n\n/** Index just past the string literal opening at `i`. */\nfunction skipString(css: string, i: number): number {\n const quote = css[i];\n let j = i + 1;\n while (j < css.length) {\n const ch = css[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === quote) return j + 1;\n j++;\n }\n return j;\n}\n\n/** Index just past the comment opening at `i`. */\nfunction skipComment(css: string, i: number): number {\n const end = css.indexOf(\"*/\", i + 2);\n return end === -1 ? css.length : end + 2;\n}\n\n/**\n * Scan from `i` to the end of a statement prelude: the `{` that opens its block,\n * or the `;` that ends a blockless statement.\n */\nfunction readPrelude(css: string, i: number): { end: number; terminator: \"{\" | \";\" | \"\" } {\n let j = i;\n let depth = 0;\n while (j < css.length) {\n const ch = css[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n j = skipString(css, j);\n continue;\n }\n if (ch === \"/\" && css[j + 1] === \"*\") {\n j = skipComment(css, j);\n continue;\n }\n if (ch === \"(\" || ch === \"[\") {\n depth++;\n } else if (ch === \")\" || ch === \"]\") {\n if (depth > 0) depth--;\n } else if (depth === 0) {\n if (ch === \"{\") return { end: j, terminator: \"{\" };\n if (ch === \";\") return { end: j + 1, terminator: \";\" };\n if (ch === \"}\") return { end: j, terminator: \"\" };\n }\n j++;\n }\n return { end: css.length, terminator: \"\" };\n}\n\n/** Index just past the `}` matching the `{` at `open`. */\nfunction matchBrace(css: string, open: number): number {\n let j = open + 1;\n let depth = 1;\n while (j < css.length) {\n const ch = css[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n j = skipString(css, j);\n continue;\n }\n if (ch === \"/\" && css[j + 1] === \"*\") {\n j = skipComment(css, j);\n continue;\n }\n if (ch === \"{\") depth++;\n else if (ch === \"}\") {\n depth--;\n if (depth === 0) return j + 1;\n }\n j++;\n }\n return css.length;\n}\n\n/** Split on commas that are not inside parens, brackets, strings or comments. */\nfunction splitTopLevel(text: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n let j = 0;\n while (j < text.length) {\n const ch = text[j];\n if (ch === \"\\\\\") {\n j += 2;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n j = skipString(text, j);\n continue;\n }\n if (ch === \"/\" && text[j + 1] === \"*\") {\n j = skipComment(text, j);\n continue;\n }\n if (ch === \"(\" || ch === \"[\") depth++;\n else if (ch === \")\" || ch === \"]\") {\n if (depth > 0) depth--;\n } else if (ch === \",\" && depth === 0) {\n parts.push(text.slice(start, j));\n start = j + 1;\n }\n j++;\n }\n parts.push(text.slice(start));\n return parts;\n}\n\n// ── Transform ──────────────────────────────────────────────────────\n\nfunction atRuleName(prelude: string): string {\n const m = /^@([\\w-]*)/.exec(prelude.trim());\n return (m?.[1] ?? \"\").toLowerCase();\n}\n\n/** Layer names in an `@layer` prelude (`@layer a, b` -> [\"a\", \"b\"]). */\nfunction layerNames(prelude: string): string[] {\n const body = prelude.trim().replace(/^@layer\\s*/i, \"\");\n return splitTopLevel(body)\n .map((n) => n.trim())\n .filter(Boolean);\n}\n\n/**\n * Rewrite one selector for a plugin sheet. Two different operations, and the\n * distinction matters:\n *\n * substitution a leading `:root`/`:host` becomes the plugin root, because those\n * declarations belong on the plugin's own root. Applies in EVERY\n * layer — Tailwind emits them in `theme`, which is otherwise left\n * alone.\n * prefixing a selector in a scoped layer gains the descendant scope. Applies\n * only inside {@link EHX_SCOPED_CSS_LAYERS}.\n */\nfunction rewriteSelector(selector: string, ctx: Ctx, prefixing: boolean): string {\n if (DOCUMENT_ROOT_PREFIX.test(selector)) {\n return selector.replace(DOCUMENT_ROOT_PREFIX, ctx.rootScope);\n }\n if (!prefixing) return selector;\n // Already scoped (a re-run, or hand-written scoped CSS in a scoped layer).\n if (selector.startsWith(ctx.scope) || selector.startsWith(ctx.rootScope)) return selector;\n return `${ctx.scope} ${selector}`;\n}\n\nfunction rewriteSelectorList(selectors: string, ctx: Ctx, prefixing: boolean): string {\n const seen = new Set<string>();\n let changed = false;\n for (const part of splitTopLevel(selectors)) {\n const trimmed = part.trim();\n if (trimmed.length === 0) continue;\n const rewritten = rewriteSelector(trimmed, ctx, prefixing);\n if (rewritten !== trimmed) changed = true;\n // Dedupe: `:root, :host` substitutes to the same selector twice.\n seen.add(rewritten);\n }\n // Return the ORIGINAL text when nothing was rewritten, so an untouched rule stays\n // byte-identical (reformatting it would churn every sheet and defeat the\n // \"return null when there is nothing to do\" contract of the Vite transform).\n return changed ? [...seen].join(\",\\n\") : selectors;\n}\n\nfunction walk(css: string, scoping: boolean, ctx: Ctx): string {\n let out = \"\";\n let i = 0;\n while (i < css.length) {\n const ch = css[i];\n if (isSpace(ch)) {\n out += ch;\n i++;\n continue;\n }\n if (ch === \"/\" && css[i + 1] === \"*\") {\n const end = skipComment(css, i);\n out += css.slice(i, end);\n i = end;\n continue;\n }\n // A stray `}` (malformed input): copy and carry on rather than throw.\n if (ch === \"}\") {\n out += ch;\n i++;\n continue;\n }\n\n const { end, terminator } = readPrelude(css, i);\n if (terminator !== \"{\") {\n // `@layer mui;`, `@import …;`, a bare declaration: nothing to scope.\n out += css.slice(i, end);\n i = end;\n continue;\n }\n\n const raw = css.slice(i, end);\n const blockEnd = matchBrace(css, end);\n const inner = css.slice(end + 1, blockEnd - 1);\n\n if (raw.trimStart().startsWith(\"@\")) {\n const name = atRuleName(raw);\n if (VERBATIM_AT_RULES.has(name) || !CONDITIONAL_AT_RULES.has(name)) {\n out += css.slice(i, blockEnd);\n } else {\n const nextScoping =\n name === \"layer\" ? scoping || layerNames(raw).some((n) => ctx.layers.has(n)) : scoping;\n out += `${raw}{${walk(inner, nextScoping, ctx)}}`;\n }\n } else {\n // Style rule. The BODY is copied verbatim: a nested rule inside it is\n // relative to this selector, so scoping the parent scopes it too.\n const trailing = /\\s*$/.exec(raw)?.[0] ?? \"\";\n const selectors = raw.slice(0, raw.length - trailing.length);\n const rewritten = rewriteSelectorList(selectors, ctx, scoping);\n out += rewritten === selectors ? css.slice(i, blockEnd) : `${rewritten}${trailing}{${inner}}`;\n }\n i = blockEnd;\n }\n return out;\n}\n\n/**\n * Prefix every selector inside a plugin's UNSCOPED cascade layers with the plugin\n * scope, so injecting the sheet into the host document cannot restyle host chrome.\n *\n * Pure and idempotent — running it twice is a no-op, so a rebuild or a second pass\n * over already-scoped CSS is safe. See {@link EHX_SCOPED_CSS_LAYERS} for which\n * layers are rewritten and why the others need no treatment.\n */\nexport function scopePluginCss(css: string, options: ScopePluginCssOptions = {}): string {\n const ctx: Ctx = {\n scope: options.scope ?? EHX_PLUGIN_CSS_SCOPE,\n rootScope: options.rootScope ?? EHX_PLUGIN_ROOT_SCOPE,\n layers: new Set(options.layers ?? EHX_SCOPED_CSS_LAYERS),\n };\n return walk(css, false, ctx);\n}\n\n/**\n * Every selector in `css` that mentions no plugin scope root, i.e. every selector\n * that can reach host chrome once the sheet is injected into the host document.\n *\n * The invariant this checks is the whole convention: **a plugin never emits an\n * unscoped selector.** {@link scopePluginCss} satisfies it automatically for the\n * layers Tailwind generates; everything else is authored, and this is what catches\n * an author (or a stray `@import \"tailwindcss\"` re-emitting global preflight) who\n * did not. Pure, so a plugin's own build script or test can call it directly.\n */\nexport function findUnscopedSelectors(\n css: string,\n options: Pick<ScopePluginCssOptions, \"scopeRoots\"> = {},\n): string[] {\n const roots = options.scopeRoots ?? EHX_PLUGIN_SCOPE_ROOTS;\n const found: string[] = [];\n collectSelectors(css, (selector) => {\n if (!roots.some((re) => re.test(selector))) found.push(selector);\n });\n return found;\n}\n\n/** Visit every style-rule selector in `css`, at any nesting depth. */\nfunction collectSelectors(css: string, visit: (selector: string) => void): void {\n let i = 0;\n while (i < css.length) {\n const ch = css[i];\n if (isSpace(ch) || ch === \"}\") {\n i++;\n continue;\n }\n if (ch === \"/\" && css[i + 1] === \"*\") {\n i = skipComment(css, i);\n continue;\n }\n const { end, terminator } = readPrelude(css, i);\n if (terminator !== \"{\") {\n i = end;\n continue;\n }\n const raw = css.slice(i, end).trim();\n const blockEnd = matchBrace(css, end);\n if (raw.startsWith(\"@\")) {\n // Descend through wrappers; never into keyframes/descriptor blocks, whose\n // \"selectors\" are keyframe offsets or descriptor names.\n const name = atRuleName(raw);\n if (CONDITIONAL_AT_RULES.has(name) && !VERBATIM_AT_RULES.has(name)) {\n collectSelectors(css.slice(end + 1, blockEnd - 1), visit);\n }\n } else {\n for (const part of splitTopLevel(raw)) {\n const selector = part.trim();\n // `&`-relative nested rules inherit the parent's scope.\n if (selector.length > 0 && !selector.startsWith(\"&\")) visit(selector);\n }\n // A nested rule inside this body is covered by its parent's scope, so there\n // is nothing further to check here.\n }\n i = blockEnd;\n }\n}\n\nconst MAX_REPORTED_LEAKS = 12;\n\n/** The build-failure message: what leaked, why it matters, and the usual cause. */\nexport function formatUnscopedSelectorError(id: string, leaks: readonly string[]): string {\n const shown = leaks.slice(0, MAX_REPORTED_LEAKS);\n const more = leaks.length - shown.length;\n return [\n `${leaks.length} selector(s) in ${id} would leak into the host document.`,\n \"\",\n \"A plugin's compiled CSS is injected into the HOST <head>, so every selector must\",\n \"be scoped to a plugin root (`.ehx-plugin-root`, `.ethisys-<name>-root`) or the\",\n \"portal marker `[data-ehx-plugin-portal]`. Unscoped selectors restyle host chrome.\",\n \"\",\n ...shown.map((s) => ` ${s}`),\n ...(more > 0 ? [` … and ${more} more`] : []),\n \"\",\n 'Most common cause: `@import \"tailwindcss\"` re-emits Tailwind\\'s global preflight.',\n \"Use the split import so the host's own preflight governs shared resets:\",\n ' @import \"@ethisyscore/plugin-ui/plugin-base.css\";',\n ' @import \"tailwindcss/theme.css\" layer(theme) source(none);',\n ' @import \"tailwindcss/utilities.css\" layer(utilities) source(none);',\n ].join(\"\\n\");\n}\n\n/** True for ids whose transform payload is plain CSS text we may rewrite. */\nexport function isScopableCssId(id: string): boolean {\n const qIndex = id.indexOf(\"?\");\n const path = qIndex === -1 ? id : id.slice(0, qIndex);\n const query = qIndex === -1 ? \"\" : id.slice(qIndex + 1);\n if (!path.endsWith(\".css\")) return false;\n // CSS modules are consumed through a class-name map, not injected wholesale.\n if (path.endsWith(\".module.css\")) return false;\n // `?raw` / `?url` payloads are the untransformed source or a path, not compiled CSS.\n if (/(?:^|&)(?:raw|url)(?:=|&|$)/.test(query)) return false;\n return true;\n}\n\n/**\n * Vite plugin form of {@link scopePluginCss} PLUS the guard that makes it a\n * convention rather than a courtesy, injected into every PlatformReact page\n * sub-build by `buildPlatformReactPages`.\n *\n * Scoping Tailwind's generated layers is automatic; the guard fails the build if\n * anything ELSE in the sheet is still unscoped (see\n * {@link findUnscopedSelectors}). Together they are the enforceable form of one\n * rule: a plugin never emits an unscoped selector into the host document. Prose in\n * a standards doc did not hold across seven repos — the leak that prompted this\n * shipped seven times, and the documented no-preflight rule was violated once\n * without anyone noticing.\n *\n * Deliberately declares NO `enforce`. Vite resolves plugins in the order\n * `[…prePlugins, vite:css, …normalPlugins, vite:css-post, …postPlugins]`, so a\n * plugin with no `enforce` is the only position that sees compiled CSS:\n *\n * - `@tailwindcss/vite` is `enforce: \"pre\"` and returns the generated sheet, so\n * the utilities exist by the time this runs.\n * - `vite:css-post` serialises a `*.css?inline` import into `export default \"…\"`.\n * `enforce: \"post\"` runs AFTER that and would be handed JavaScript, where the\n * CSS is an escaped string literal.\n */\nexport function scopePluginCssPlugin(options: ScopePluginCssOptions = {}): Plugin {\n return {\n name: \"ethisys-scope-plugin-css\",\n transform(code: string, id: string) {\n if (!isScopableCssId(id)) return null;\n const scoped = scopePluginCss(code, options);\n\n const guard = options.guard ?? \"error\";\n if (guard !== \"off\") {\n const leaks = findUnscopedSelectors(scoped, options);\n if (leaks.length > 0) {\n const message = formatUnscopedSelectorError(id, leaks);\n // Prefer the Rollup context (it frames the error with the plugin + file);\n // fall back to a plain throw so the guard still bites when the hook is\n // called directly, as a plugin's own check script or a test does.\n const ctx = this as { error?: (m: string) => never; warn?: (m: string) => void } | undefined;\n if (guard === \"error\") {\n if (ctx?.error) ctx.error(message);\n throw new Error(message);\n }\n if (ctx?.warn) ctx.warn(message);\n else console.warn(message);\n }\n }\n\n // Selector rewriting invalidates the CSS sourcemap; `?inline` CSS ships as a\n // string inside the page bundle, so there is no CSS map to preserve.\n return scoped === code ? null : { code: scoped, map: null };\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport type { InlineConfig, Plugin } from \"vite\";\nimport { escapeRegExp } from \"../utils/strings\";\nimport { scopePluginCssPlugin } from \"./scope-plugin-css\";\n\n// ── The PlatformReact host-realm contract (shared defaults) ────────\n//\n// A PlatformReact page is ONE self-contained ESM bundle the host loads via\n// `import(url)` at mount time. These two lists are the build-side half of the\n// host contract; both are overridable, but every migration starts from them.\n\n/**\n * Specifiers the host realm provides at runtime — never bundled into a page.\n * A `components/ui/*` abstraction that re-exports `@mui/material` therefore\n * costs zero bundle weight and shares the host's MUI singleton + theme.\n */\nexport const PLATFORM_REACT_EXTERNALS: readonly string[] = [\n \"react\",\n \"react/jsx-runtime\",\n \"react-dom\",\n \"@mui/material\",\n \"@mui/icons-material\",\n \"@emotion/react\",\n \"@emotion/styled\",\n \"date-fns\",\n \"@ethisyscore/components-react\",\n \"@ethisyscore/extension-runtime\",\n \"@ethisyscore/extension-runtime/plugin\",\n];\n\n/**\n * Bundled deps that MUST resolve to a single copy. When a bundled dep (e.g.\n * `@tanstack/react-query`) is imported by BOTH the plugin's own hooks and the\n * SDK foundation (aliased cross-repo to a sibling `dist`), the bundler otherwise\n * resolves two copies — one per repo's `node_modules`. Two module instances =\n * two React contexts, so a provider in one is invisible to a consumer in the\n * other (the classic \"No QueryClient set\"). Pin them to one copy.\n */\nexport const PLATFORM_REACT_DEDUPE: readonly string[] = [\n \"@tanstack/react-query\",\n \"react\",\n \"react-dom\",\n \"@ethisyscore/extension-runtime\",\n];\n\nconst DEFAULT_OUT_DIR = \"dist\";\nconst DEFAULT_OUTPUT_PREFIX = \"platform-react\";\nconst DEFAULT_DEFINE_PLUGIN_PAGE = \"@/app/definePluginPage\";\nconst DEFAULT_DEFINE_PLUGIN_OVERLAY = \"@/app/definePluginOverlay\";\nconst DEFAULT_SRC_DIR = \"src\";\nconst DEFAULT_ALIAS_PREFIX = \"@\";\nconst SUMMARY_FILENAME = \"platform-react-pages.json\";\nconst DIGEST_MAP_FILENAME = \"platform-react-digest-map.json\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/** A `resolve.alias` entry (string or regex find), as Vite accepts. */\nexport interface PlatformReactAlias {\n find: string | RegExp;\n replacement: string;\n}\n\n/**\n * One surface declared in `feature.manifest.json` (`ui.platformReactPages[]`).\n * `views` is the page's `useView` manifest slice — the adapter-view modules it\n * renders by name (`{ DayView: \"src/adapter/<feature>/DayView.tsx\" }`). It rides\n * along as an open extra field the SDK's manifest readers ignore.\n */\nexport interface PlatformReactPageInput {\n id: string;\n moduleSpecifier: string;\n exportName?: string;\n title?: string | null;\n views?: Record<string, string>;\n}\n\n/**\n * The singular overlay declared in `feature.manifest.json` (`ui.platformReactOverlay`,\n * WI 5160 SP-A). Same shape as {@link PlatformReactPageInput} minus `route` — an overlay\n * is never routed. `views` is its `useView` manifest slice, synthesised into the virtual\n * entry exactly as page `views` are.\n */\nexport interface PlatformReactOverlayInput {\n id: string;\n moduleSpecifier: string;\n exportName?: string;\n title?: string | null;\n views?: Record<string, string>;\n}\n\n/** The fully-resolved per-page build context handed to the (injectable) builder. */\nexport interface PlatformReactBuildContext {\n pageId: string;\n /** Virtual entry module id (`\\0virtual:surface/<id>`). */\n entryId: string;\n /** Rollup plugin that resolves + loads the synthesised virtual entry. */\n surfacePlugin: Plugin;\n root: string;\n outDir: string;\n outputPrefix: string;\n external: readonly string[];\n dedupe: readonly string[];\n alias: PlatformReactAlias[];\n plugins: Plugin[];\n target: string;\n minify: boolean;\n sourcemap: boolean;\n}\n\n/** Low-level Vite `build` function. Defaults to a dynamic `import(\"vite\")`. */\nexport type ViteBuildFn = (config: InlineConfig) => Promise<unknown>;\n\n/** Injectable per-page builder. Defaults to a real Vite library build. */\nexport type PlatformReactViteBuild = (ctx: PlatformReactBuildContext) => Promise<void>;\n\nexport interface BuildPlatformReactPagesOptions {\n /** Root the manifest + `src/…` paths resolve against. Default `process.cwd()`. */\n root?: string;\n /** Manifest path (relative to `root`). Default `feature.manifest.json`. */\n manifestPath?: string;\n /** Inline manifest object (test injection). When omitted, read from disk. */\n manifest?: unknown;\n /** Output directory the bundles + companion JSON land in. Default `dist`. */\n outDir?: string;\n /** Sub-directory + summary/digest key prefix. Default `platform-react`. */\n outputPrefix?: string;\n /** Plugin-specific `resolve.alias` entries (contracts, router shim, `@/`, …). */\n alias?: PlatformReactAlias[];\n /** Plugin-specific Vite plugins (e.g. `react()`, `tailwindcss()`). */\n plugins?: Plugin[];\n /** Bundled deps to dedupe. Default {@link PLATFORM_REACT_DEDUPE}. */\n dedupe?: readonly string[];\n /** Host externals. Default {@link PLATFORM_REACT_EXTERNALS}. */\n external?: readonly string[];\n /** Module specifier the generated entry imports `definePluginPage` from. */\n definePluginPageSpecifier?: string;\n /** Module specifier the generated overlay entry imports `definePluginOverlay` from. */\n definePluginOverlaySpecifier?: string;\n /** Source dir stripped when rewriting manifest paths to the alias. Default `src`. */\n srcDir?: string;\n /** Alias prefix manifest `src/…` paths are rewritten to. Default `@` (→ `@/…`). */\n aliasPrefix?: string;\n /** Rollup build target. Default `es2022`. */\n target?: string;\n /** Minify output. Default `false` (digest stability + debuggability). */\n minify?: boolean;\n /** Emit sourcemaps. Default `true`. */\n sourcemap?: boolean;\n /** Wipe `outDir` before building. Default `true`. */\n clean?: boolean;\n /** Progress logger. Default `console`. */\n logger?: Pick<Console, \"log\" | \"warn\">;\n /** Low-level Vite `build` (production override so the CONSUMER's vite is used). */\n viteBuild?: ViteBuildFn;\n /** Injectable per-page builder (test injection — skips Vite entirely). */\n build?: PlatformReactViteBuild;\n /** Injectable bundle reader for digesting. Default `fs.readFileSync` (utf-8). */\n readFile?: (path: string) => string;\n /** Injectable file writer. Default `fs.writeFileSync` (creating dirs). */\n writeFile?: (path: string, contents: string) => void;\n}\n\n/** One built surface (a page, or the singular overlay) as recorded in the companion summary. */\nexport interface PlatformReactSurfaceSummary {\n id: string;\n exportName: string;\n title: string | null;\n bundlePath: string;\n source: string;\n}\n\n/** One emitted bundle's SHA-256, keyed by its dist-relative path. */\nexport interface PlatformReactDigest {\n path: string;\n sha256: string;\n}\n\nexport interface PlatformReactBuildSummary {\n pages: PlatformReactSurfaceSummary[];\n /** The singular overlay, when the manifest declares `ui.platformReactOverlay`. */\n overlay?: PlatformReactSurfaceSummary;\n digests: PlatformReactDigest[];\n summaryPath: string | null;\n digestMapPath: string | null;\n}\n\n// ── Generic transforms (exported for focused unit tests) ───────────\n\n/**\n * Rollup output pass: rewrite aliased named imports from host externals into the\n * namespace-import form the host's PlatformReact loader accepts.\n *\n * esbuild emits `import { Dialog as Dialog$1 } from \"@mui/material\"` to\n * deconflict a name collision (an adapter view imports MUI `Dialog` directly\n * while a feature component pulls in the `components/ui/dialog` wrapper of the\n * same name). The host loader handles `import * as X`, plain `import { Y }`,\n * default imports, and aliased EXPORTS — but throws \"Unexpected identifier 'as'\"\n * on aliased named IMPORTS `{ X as Y }`. In a final `inlineDynamicImports`\n * bundle every remaining `import { … } from \"…\"` is an EXTERNAL import, so\n * rewriting any that contain `as` into `import * as ns from \"…\"; const local =\n * ns.imported, …;` is safe and removes the only construct the loader rejects.\n * Runs in `renderChunk`, before the host-verified digest is computed.\n */\nexport function rewriteAliasedExternalImports(): Plugin {\n return {\n name: \"rewrite-aliased-external-imports\",\n renderChunk(code: string) {\n let counter = 0;\n let changed = false;\n const out = code.replace(\n // Optional default binding (`import Foo, { … }`) then the named braces.\n /\\bimport\\s+(?:([\\w$]+)\\s*,\\s*)?\\{([^{}]*)\\}\\s*from\\s*(\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*')\\s*;?/g,\n (full, def: string | undefined, specs: string, mod: string) => {\n if (!/\\sas\\s/.test(specs)) return full;\n changed = true;\n const ns = `__ns_imp_${counter++}`;\n const decls = specs\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((s) => {\n const [imported, local] = s.split(/\\s+as\\s+/).map((t) => t.trim());\n return `${local ?? imported} = ${ns}.${imported}`;\n })\n .join(\", \");\n // Keep any default import as-is (no alias → host-safe), namespace the named part.\n const defPart = def ? `import ${def} from ${mod}; ` : \"\";\n return `${defPart}import * as ${ns} from ${mod}; const ${decls};`;\n },\n );\n return changed ? { code: out, map: null } : null;\n },\n };\n}\n\n/**\n * Synthesise one isolated PlatformReact entry per surface straight from its\n * manifest declaration: `definePluginPage(Page, { …views })`, importing ONLY\n * that surface's page (`moduleSpecifier`) + adapter views (`views`) so each\n * bundle stays self-contained. Returned as a Rollup virtual module so there are\n * no physical per-page entry files — the manifest is the single source of truth.\n * `src/…` paths are rewritten to the alias the build resolves (e.g. `@/…`).\n */\nexport function virtualPageEntry(\n page: PlatformReactPageInput,\n config: { definePluginPageSpecifier: string; toAlias: (p: string) => string },\n): { id: string; plugin: Plugin } {\n const VIRTUAL_ID = `\\0virtual:surface/${page.id}`;\n const views = page.views ?? {};\n const names = Object.keys(views);\n const viewImports = names\n .map((n) => `import { ${n} } from ${JSON.stringify(config.toAlias(views[n]))};`)\n .join(\"\\n\");\n const src =\n `import Page from ${JSON.stringify(config.toAlias(page.moduleSpecifier))};\\n` +\n `${viewImports}\\n` +\n `import { definePluginPage } from ${JSON.stringify(config.definePluginPageSpecifier)};\\n` +\n `export default definePluginPage(Page, { ${names.join(\", \")} });\\n`;\n return {\n id: VIRTUAL_ID,\n plugin: {\n name: `virtual-surface-${page.id}`,\n resolveId: (id: string) => (id === VIRTUAL_ID ? VIRTUAL_ID : null),\n load: (id: string) => (id === VIRTUAL_ID ? src : null),\n },\n };\n}\n\n/**\n * Overlay counterpart of {@link virtualPageEntry}: synthesise the singular overlay's\n * isolated entry as `definePluginOverlay(Overlay, { …views })`. Identical to the page\n * entry except the definer — an overlay is never routed.\n */\nexport function virtualOverlayEntry(\n overlay: PlatformReactOverlayInput,\n config: { definePluginOverlaySpecifier: string; toAlias: (p: string) => string },\n): { id: string; plugin: Plugin } {\n const VIRTUAL_ID = `\\0virtual:surface/${overlay.id}`;\n const views = overlay.views ?? {};\n const names = Object.keys(views);\n const viewImports = names\n .map((n) => `import { ${n} } from ${JSON.stringify(config.toAlias(views[n]))};`)\n .join(\"\\n\");\n // Honour a non-default `exportName`: import the overlay under that name from the\n // source module, and re-export the WRAPPED overlay under it too. The host loader\n // reads `bundle[exportName]` at mount, so a default-only import/export would both\n // pull the wrong symbol from source AND emit a bundle missing that export. The\n // default case keeps the terse `import X from` / `export default` form.\n const exportName =\n typeof overlay.exportName === \"string\" && overlay.exportName.length > 0\n ? overlay.exportName\n : \"default\";\n const overlayModule = JSON.stringify(config.toAlias(overlay.moduleSpecifier));\n const overlayImport =\n exportName === \"default\"\n ? `import Overlay from ${overlayModule};`\n : `import { ${exportName} as Overlay } from ${overlayModule};`;\n const overlayExport =\n exportName === \"default\"\n ? `export default definePluginOverlay(Overlay, { ${names.join(\", \")} });`\n : `const __ehxOverlay = definePluginOverlay(Overlay, { ${names.join(\", \")} });\\n` +\n `export { __ehxOverlay as ${exportName} };\\n` +\n `export default __ehxOverlay;`;\n const src =\n `${overlayImport}\\n` +\n `${viewImports}\\n` +\n `import { definePluginOverlay } from ${JSON.stringify(config.definePluginOverlaySpecifier)};\\n` +\n `${overlayExport}\\n`;\n return {\n id: VIRTUAL_ID,\n plugin: {\n name: `virtual-surface-${overlay.id}`,\n resolveId: (id: string) => (id === VIRTUAL_ID ? VIRTUAL_ID : null),\n load: (id: string) => (id === VIRTUAL_ID ? src : null),\n },\n };\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction defaultWriteFile(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n}\n\nfunction readManifest(options: BuildPlatformReactPagesOptions, root: string): unknown {\n if (options.manifest !== undefined) {\n return options.manifest;\n }\n const rel = options.manifestPath ?? \"feature.manifest.json\";\n const abs = isAbsolute(rel) ? rel : resolve(root, rel);\n if (!existsSync(abs)) {\n return null;\n }\n const raw = readFileSync(abs, \"utf-8\");\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${abs}\": ${(e as Error).message}`,\n );\n }\n}\n\n/** Build the real per-page Vite config and run it through the (injectable) vite build. */\nfunction makeDefaultBuild(viteBuild?: ViteBuildFn): PlatformReactViteBuild {\n return async (ctx) => {\n const build: ViteBuildFn = viteBuild ?? (await import(\"vite\")).build;\n await build({\n root: ctx.root,\n configFile: false,\n // `scopePluginCssPlugin` must sit AFTER the plugin's own `tailwindcss()` in\n // effect, which it does by enforce ordering, not array position: Tailwind is\n // `enforce: \"pre\"`, this one declares none. See its doc for why \"none\" is the\n // only position that sees compiled CSS.\n plugins: [\n ctx.surfacePlugin,\n ...ctx.plugins,\n scopePluginCssPlugin(),\n rewriteAliasedExternalImports(),\n ],\n resolve: {\n dedupe: [...ctx.dedupe],\n alias: ctx.alias,\n },\n build: {\n target: ctx.target,\n outDir: ctx.outDir,\n emptyOutDir: false,\n assetsDir: \"\",\n minify: ctx.minify,\n sourcemap: ctx.sourcemap,\n rollupOptions: {\n input: { [ctx.pageId]: ctx.entryId },\n preserveEntrySignatures: \"strict\",\n external: [...ctx.external],\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${ctx.outputPrefix}/[name].js`,\n chunkFileNames: `${ctx.outputPrefix}/[name]-[hash].js`,\n assetFileNames: `${ctx.outputPrefix}/[name][extname]`,\n },\n },\n },\n logLevel: \"warn\",\n });\n };\n}\n\n// ── Orchestration ──────────────────────────────────────────────────\n\n/**\n * Build every `ui.platformReactPages[]` surface as its own self-contained ESM\n * bundle and emit the companion `platform-react-pages.json` summary + the\n * per-asset SHA-256 `platform-react-digest-map.json` the host's verified loader\n * and the `.ccpkg` packaging step read.\n *\n * Each PlatformReact page must be ONE bundle (`inlineDynamicImports: true`), and\n * Rollup rejects that with more than one input — so this runs one Vite sub-build\n * per surface, each with a single synthesised virtual entry (see\n * {@link virtualPageEntry}). The generic seams (host externals, dedupe, the\n * host-loader aliased-import rewrite, the digest/summary contract) live here;\n * the plugin supplies only its `alias` entries + `plugins` (and, in production,\n * its own `viteBuild` so the consumer's Vite is used, not the SDK's).\n *\n * No-op (returns empty) when no pages are declared.\n */\nexport async function buildPlatformReactPages(\n options: BuildPlatformReactPagesOptions = {},\n): Promise<PlatformReactBuildSummary> {\n const root = options.root ?? process.cwd();\n const logger = options.logger ?? console;\n const manifest = readManifest(options, root);\n\n const ui = (\n manifest as { ui?: { platformReactPages?: unknown[]; platformReactOverlay?: unknown } } | null\n )?.ui;\n const declared = ui?.platformReactPages;\n const overlayDecl = ui?.platformReactOverlay;\n const hasPages = Array.isArray(declared) && declared.length > 0;\n const hasOverlay = overlayDecl !== undefined && overlayDecl !== null;\n if (!hasPages && !hasOverlay) {\n logger.warn(\n \"[build-pages] no platformReactPages or platformReactOverlay declared — nothing to build\",\n );\n return { pages: [], digests: [], summaryPath: null, digestMapPath: null };\n }\n\n // Validate the fields this pass consumes (the open `views` field rides along).\n const seen = new Set<string>();\n const pages: PlatformReactPageInput[] = (hasPages ? declared! : []).map((raw, i) => {\n const decl = raw as PlatformReactPageInput;\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(`[build-pages] ui.platformReactPages[${i}].id is required (non-empty string).`);\n }\n if (seen.has(decl.id)) {\n throw new Error(`[build-pages] Duplicate page id \"${decl.id}\".`);\n }\n seen.add(decl.id);\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(`[build-pages] surface \"${decl.id}\" has no moduleSpecifier in the manifest.`);\n }\n return decl;\n });\n\n // The singular overlay (WI 5160 SP-A). Its id must not collide with a page id — a\n // shared id would overwrite one bundle with the other's Rollup input.\n let overlay: PlatformReactOverlayInput | null = null;\n if (hasOverlay) {\n const decl = overlayDecl as PlatformReactOverlayInput;\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(`[build-pages] ui.platformReactOverlay.id is required (non-empty string).`);\n }\n if (seen.has(decl.id)) {\n throw new Error(\n `[build-pages] ui.platformReactOverlay.id \"${decl.id}\" collides with a page id — ids must be unique across pages and the overlay.`,\n );\n }\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(`[build-pages] ui.platformReactOverlay \"${decl.id}\" has no moduleSpecifier in the manifest.`);\n }\n overlay = decl;\n }\n\n const outDir = options.outDir ?? DEFAULT_OUT_DIR;\n const outDirAbs = isAbsolute(outDir) ? outDir : resolve(root, outDir);\n const outputPrefix = (options.outputPrefix ?? DEFAULT_OUTPUT_PREFIX).replace(/^\\/+|\\/+$/g, \"\");\n const outputPrefixDir = resolve(outDirAbs, outputPrefix);\n\n const external = options.external ?? PLATFORM_REACT_EXTERNALS;\n const dedupe = options.dedupe ?? PLATFORM_REACT_DEDUPE;\n const alias = options.alias ?? [];\n const plugins = options.plugins ?? [];\n const definePluginPageSpecifier = options.definePluginPageSpecifier ?? DEFAULT_DEFINE_PLUGIN_PAGE;\n const definePluginOverlaySpecifier =\n options.definePluginOverlaySpecifier ?? DEFAULT_DEFINE_PLUGIN_OVERLAY;\n const srcDir = options.srcDir ?? DEFAULT_SRC_DIR;\n const aliasPrefix = options.aliasPrefix ?? DEFAULT_ALIAS_PREFIX;\n const srcRe = new RegExp(`^${escapeRegExp(srcDir)}/`);\n const toAlias = (p: string) => `${aliasPrefix}/${p.replace(srcRe, \"\")}`;\n\n const write = options.writeFile ?? defaultWriteFile;\n const read = options.readFile ?? ((p: string) => readFileSync(p, \"utf-8\"));\n const runBuild = options.build ?? makeDefaultBuild(options.viteBuild);\n\n if (options.clean ?? true) {\n if (existsSync(outDirAbs)) {\n rmSync(outDirAbs, { recursive: true, force: true });\n }\n mkdirSync(outputPrefixDir, { recursive: true });\n }\n\n for (const page of pages) {\n const { id: entryId, plugin: surfacePlugin } = virtualPageEntry(page, {\n definePluginPageSpecifier,\n toAlias,\n });\n logger.log(`[build-pages] ${page.id} ← ${page.moduleSpecifier}`);\n await runBuild({\n pageId: page.id,\n entryId,\n surfacePlugin,\n root,\n outDir: outDirAbs,\n outputPrefix,\n external,\n dedupe,\n alias,\n plugins,\n target: options.target ?? \"es2022\",\n minify: options.minify ?? false,\n sourcemap: options.sourcemap ?? true,\n });\n }\n\n // The singular overlay builds through the same isolated-sub-build path as a page —\n // one self-contained ESM bundle at `platform-react/<id>.js`.\n if (overlay) {\n const { id: entryId, plugin: surfacePlugin } = virtualOverlayEntry(overlay, {\n definePluginOverlaySpecifier,\n toAlias,\n });\n logger.log(`[build-pages] ${overlay.id} ← ${overlay.moduleSpecifier} (overlay)`);\n await runBuild({\n pageId: overlay.id,\n entryId,\n surfacePlugin,\n root,\n outDir: outDirAbs,\n outputPrefix,\n external,\n dedupe,\n alias,\n plugins,\n target: options.target ?? \"es2022\",\n minify: options.minify ?? false,\n sourcemap: options.sourcemap ?? true,\n });\n }\n\n // Companion summary the host loader + `.ccpkg` packaging reads.\n const summaryPages = pages.map((p) => ({\n id: p.id,\n exportName: p.exportName ?? \"default\",\n title: p.title ?? null,\n bundlePath: `${outputPrefix}/${p.id}.js`,\n source: p.moduleSpecifier,\n }));\n const summaryOverlay = overlay\n ? {\n id: overlay.id,\n exportName: overlay.exportName ?? \"default\",\n title: overlay.title ?? null,\n bundlePath: `${outputPrefix}/${overlay.id}.js`,\n source: overlay.moduleSpecifier,\n }\n : undefined;\n const summaryPath = resolve(outputPrefixDir, SUMMARY_FILENAME);\n write(\n summaryPath,\n JSON.stringify(\n summaryOverlay ? { pages: summaryPages, overlay: summaryOverlay } : { pages: summaryPages },\n null,\n 2,\n ),\n );\n\n // Per-asset SHA-256 digest map. Hash each emitted bundle's UTF-8 bytes off\n // disk (one self-contained ESM chunk per page — `inlineDynamicImports`), keyed\n // by the dist-relative path, so the host's verified loader can check each\n // bundle before eval and packaging can lift these into `assetDigests`.\n const digests = [\n ...pages.map((p) => `${outputPrefix}/${p.id}.js`),\n ...(overlay ? [`${outputPrefix}/${overlay.id}.js`] : []),\n ]\n .sort()\n .map((relPath) => {\n const code = read(resolve(outDirAbs, relPath));\n return { path: relPath, sha256: createHash(\"sha256\").update(code, \"utf8\").digest(\"hex\") };\n });\n const digestMapPath = resolve(outputPrefixDir, DIGEST_MAP_FILENAME);\n write(digestMapPath, JSON.stringify({ digests }, null, 2));\n\n logger.log(\n `[build-pages] emitted ${pages.length} page(s)${overlay ? \" + 1 overlay\" : \"\"} + summary + digest map (${digests.length} digests)`,\n );\n\n return { pages: summaryPages, overlay: summaryOverlay, digests, summaryPath, digestMapPath };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Plugin } from \"vite\";\nimport { slash } from \"../utils/strings\";\nimport { PLATFORM_REACT_EXTERNALS } from \"./build-pages\";\nimport { scopePluginCssPlugin } from \"./scope-plugin-css\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A single PlatformReact page declaration extracted from\n * `ui.platformReactPages[]` in the manifest. Aligns with the typed interface\n * defined in `ethisyscore-protocol` RFC 0003.\n *\n * - `id` is the host-side page identifier and the basename of the emitted\n * bundle (e.g. `id: \"dashboard\"` → `platform-react/dashboard.js`).\n * - `moduleSpecifier` is a host-origin relative path to the page module — the\n * plugin author's source entry that Rollup bundles.\n * - `exportName` is the named export Rollup keeps live in the bundle. The host\n * loader reads `bundle[exportName]` at mount time.\n * - `title` is an optional display label for the host's surface chrome.\n */\nexport interface PlatformReactPageDeclaration {\n id?: string;\n moduleSpecifier?: string;\n exportName?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n/**\n * The singular PlatformReact overlay declaration extracted from\n * `ui.platformReactOverlay` in the manifest (WI 5160 SP-A).\n * At most one overlay is permitted per plugin manifest.\n *\n * - `id` is the host-side overlay identifier and the basename of the emitted\n * bundle (e.g. `id: \"ai-overlay\"` → `platform-react/ai-overlay.js`).\n * - `moduleSpecifier` is a host-origin relative path to the overlay module.\n * - `exportName` is the named export the host loader reads at mount time.\n * - `title` is an optional display label for the host's surface chrome.\n */\nexport interface PlatformReactOverlayDeclaration {\n id?: string;\n moduleSpecifier?: string;\n exportName?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n/**\n * The subset of a manifest this pass consumes. Manifests are tolerated as a\n * superset — extra fields are ignored so newer-schema manifests still load.\n */\nexport interface PlatformReactManifest {\n type?: string;\n ui?: {\n platformReactPages?: PlatformReactPageDeclaration[];\n platformReactOverlay?: PlatformReactOverlayDeclaration; // WI 5160 SP-A — singular\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the PlatformReact Vite pass.\n */\nexport interface PlatformReactPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted page assets and the companion manifest.\n * Defaults to `platform-react/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\ninterface ResolvedPage {\n id: string;\n exportName: string;\n title: string | null;\n moduleSpecifierRel: string;\n moduleSpecifierAbs: string;\n}\n\n// M-1: ResolvedOverlay is structurally identical to ResolvedPage — use a type alias (DRY).\ntype ResolvedOverlay = ResolvedPage;\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore PlatformReact pages\n * (RFC 0003: the high-trust, host-extension tier). For each entry under\n * `ui.platformReactPages[]` in the manifest, registers a Rollup input that\n * emits an ESM bundle the host loads via `import()` at surface mount time.\n *\n * Behaviour:\n * - For each declared page: registers `{ \"platform-react/<id>\": <moduleSpecifier> }`\n * in Rollup's input table. Output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so each page ships as ONE bundled module.\n * - Emits a `platform-react/platform-react-pages.json` companion asset listing\n * the declared pages so the host (and the `.ccpkg` packaging step) can\n * inspect what the build produced.\n * - When `ui.platformReactPages` is absent or empty: the pass is a no-op.\n * Composition is expected — the recommended template registers this pass\n * alongside Contract A / Contract B so a single Vite config covers every\n * render mode.\n *\n * Origin enforcement of the bundle URL at runtime is the host's responsibility\n * (see `PlatformReactSurfaceMount.tsx` in `coreconnect-web`). This pass only\n * blocks remote/absolute paths at the manifest layer so a malformed manifest\n * fails fast.\n *\n * Returns an ARRAY: this pass plus the plugin-CSS scoping pass it must always be\n * paired with. Vite flattens nested plugin arrays (`PluginOption` is recursively\n * `PluginOption[]`), so existing call sites\n * (`plugins: [react(), tailwindcss(), ethisysPlatformReactPlugin()]`) are unaffected.\n *\n * The pairing CANNOT be done by returning `{ plugins: [...] }` from this pass's own\n * `config()` hook: Vite resolves the plugin container before running config hooks, so\n * a plugin injected there is dropped SILENTLY (no warning, build still green) and the\n * scoping pass would never run. Anything needing the page pass on its own as a single\n * `Plugin` should call `ethisysPlatformReactPagesPlugin` and compose the scoping pass\n * itself.\n */\nexport function ethisysPlatformReactPlugin(\n options: PlatformReactPluginOptions = {},\n): Plugin[] {\n return [ethisysPlatformReactPagesPlugin(options), scopePluginCssPlugin()];\n}\n\n/**\n * The PlatformReact page-bundle pass ALONE, as a single `Plugin`.\n *\n * Prefer {@link ethisysPlatformReactPlugin}, which pairs this with the plugin-CSS\n * scoping pass. Reach for this only when composing the passes by hand (a plugin with\n * its own scoping step, or a test that drives one pass's hooks directly) — used on its\n * own it emits UNSCOPED CSS, which leaks into the host document.\n */\nexport function ethisysPlatformReactPagesPlugin(\n options: PlatformReactPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"platform-react/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let pages: ResolvedPage[] = [];\n let overlay: ResolvedOverlay | null = null;\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n // Vite hasn't called configResolved yet (or this plugin is being driven\n // outside Vite — e.g. a unit test that only invokes the validation\n // helper). Fall back to the explicit option then cwd. configResolved\n // will overwrite this with the correct Vite-resolved root when it\n // fires, before validate() is called for real.\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): PlatformReactManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve each page's absolute source path plus\n * the singular overlay (if declared). Idempotent — repeated invocations\n * rebuild from a fresh manifest read.\n */\n function validate(): void {\n pages = [];\n overlay = null;\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n\n // ── Pages ──────────────────────────────────────────────────────\n const declared = manifest.ui?.platformReactPages;\n if (Array.isArray(declared) && declared.length > 0) {\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n const absPath = resolve(resolvedRoot, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n\n const exportName =\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\";\n\n pages.push({\n id: decl.id,\n exportName,\n title: typeof decl.title === \"string\" && decl.title.length > 0 ? decl.title : null,\n moduleSpecifierRel: decl.moduleSpecifier,\n moduleSpecifierAbs: absPath,\n });\n }\n }\n\n // ── Overlay (singular) ─────────────────────────────────────────\n const overlayDecl = manifest.ui?.platformReactOverlay;\n if (overlayDecl !== undefined && overlayDecl !== null) {\n const where = \"ui.platformReactOverlay\";\n\n if (typeof overlayDecl.id !== \"string\" || overlayDecl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(overlayDecl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${overlayDecl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n\n if (typeof overlayDecl.moduleSpecifier !== \"string\" || overlayDecl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(overlayDecl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n const absPath = resolve(resolvedRoot, overlayDecl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${overlayDecl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n\n // M-4: Guard against id collision — overlay id must not match any page id.\n // Without this check, input[overlay.id] silently overwrites the page entry.\n const collidingPage = pages.find((p) => p.id === overlayDecl.id);\n if (collidingPage !== undefined) {\n throw new Error(\n `[ethisys-platform-react] ui.platformReactOverlay.id \"${overlayDecl.id}\" collides with a declared page id — ids must be unique across pages and the overlay.`,\n );\n }\n\n const exportName =\n typeof overlayDecl.exportName === \"string\" && overlayDecl.exportName.length > 0\n ? overlayDecl.exportName\n : \"default\";\n\n overlay = {\n id: overlayDecl.id,\n exportName,\n title: typeof overlayDecl.title === \"string\" && overlayDecl.title.length > 0 ? overlayDecl.title : null,\n moduleSpecifierRel: overlayDecl.moduleSpecifier,\n moduleSpecifierAbs: absPath,\n };\n }\n }\n\n let isBuild = false;\n\n const plugin: Plugin = {\n name: \"ethisys-platform-react\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n /**\n * Force ESM single-module output per page. Output options don't depend on\n * the resolved root, so they're safe to declare here — `config()` runs\n * before `configResolved()`. The Rollup input table is added later in\n * `configResolved()` once Vite has populated `resolvedRoot` correctly.\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n return {\n build: {\n // CRITICAL: emit NON-MINIFIED ESM. The host loads each bundle by\n // fetching it as text and REGEX-rewriting its bare-specifier imports\n // (`import { x } from \"react\"` → `const { x } = registry[\"react\"]`) —\n // the host's rewriter (hostModuleRegistry) assumes non-minified ESM,\n // so a minified bundle leaves `react`/`react-dom`/MUI unrewritten and\n // they resolve to `undefined`/`null` at mount (the overlay/page then\n // throws on the first hook). Vite minifies production builds by\n // default, so this MUST be forced off for every PlatformReact surface.\n minify: false,\n rollupOptions: {\n // CRITICAL: single-file ESM output per page. The host loads each\n // page via `import(url)` at mount time and reads the declared\n // `exportName` from the resulting module namespace. Chunk-split\n // output would break that contract because the host has no\n // import-map surface to resolve sibling chunks.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n // Externalise every host-realm specifier so the host's module-registry\n // rewriter resolves them to the live host singletons at runtime — react,\n // react-dom, MUI, emotion, components-react, extension-runtime (the shared\n // PLATFORM_REACT_EXTERNALS contract) PLUS host-ui-externals. This is\n // CRITICAL: if react is NOT externalised it gets bundled, the surface then\n // runs against a SECOND React instance, and hooks throw (invalid-hook /\n // \"reading useEffect of null\"). Must match the programmatic build-pages\n // externals so config-hook plugins (cc-scaffolded) behave identically.\n external: [...PLATFORM_REACT_EXTERNALS, \"@ethisyscore/host-ui-externals\"],\n // Nothing inside the build imports the entry module, so the bundler's\n // default entry tree-shaking would drop the declared `exportName`\n // (e.g. the overlay's `Overlay`). Pin entry signatures so the host\n // loader can read `bundle[exportName]` at mount time.\n preserveEntrySignatures: \"strict\",\n },\n },\n };\n },\n\n /**\n * Resolve the actual root Vite is using (which may differ from\n * `process.cwd()`), validate the manifest against it, and mutate the\n * resolved config's Rollup input table so each declared page becomes a\n * build entry. Mutation in `configResolved` is the standard Vite-plugin\n * pattern for input contributions that depend on the resolved root —\n * `config()` runs too early to know the real value.\n */\n configResolved(config) {\n isBuild = config.command === \"build\";\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n if (!isBuild) {\n return;\n }\n\n validate();\n if (pages.length === 0 && overlay === null) {\n return;\n }\n\n const input: Record<string, string> = {};\n for (const page of pages) {\n // Input key = bare page id. The `outputPrefix` is applied by\n // `entryFileNames` so the final output is `<outputPrefix><id>.js`.\n input[page.id] = slash(page.moduleSpecifierAbs);\n }\n // Register the singular overlay as one more Rollup input (WI 5160 SP-A).\n if (overlay !== null) {\n input[overlay.id] = slash(overlay.moduleSpecifierAbs);\n }\n\n // Merge into Vite's resolved rollupOptions.input. The existing value\n // may be undefined, a single entry path, an array of entries, or an\n // already-keyed object — handle all four shapes so coexistence with\n // other Vite plugins (Contract A / Contract B passes that declare\n // their own entries) is non-destructive.\n //\n // Vite's `ResolvedConfig.build` is typed `readonly` in its public\n // declarations. The runtime object is mutable — Vite plugins that\n // need to contribute Rollup inputs from `configResolved` (which\n // requires the resolved root) widely follow this mutation pattern.\n // Cast through a writable view to bypass the type-level readonly\n // check; runtime semantics are unchanged.\n const writable = config as unknown as {\n build?: {\n rollupOptions?: {\n input?: Record<string, string> | string | string[];\n };\n };\n };\n writable.build ??= {};\n writable.build.rollupOptions ??= {};\n const rollupOptions = writable.build.rollupOptions;\n const existing = rollupOptions.input;\n if (existing && typeof existing === \"object\" && !Array.isArray(existing)) {\n rollupOptions.input = { ...(existing as Record<string, string>), ...input };\n } else if (typeof existing === \"string\") {\n rollupOptions.input = { _entry: existing, ...input };\n } else if (Array.isArray(existing)) {\n const indexed: Record<string, string> = {};\n existing.forEach((entry, idx) => {\n indexed[`_entry${idx}`] = entry;\n });\n rollupOptions.input = { ...indexed, ...input };\n } else {\n rollupOptions.input = input;\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest. resolvedRoot is already set by\n // configResolved at this point.\n validate();\n },\n\n /**\n * Emit the companion `platform-react-pages.json` listing every declared\n * page. The `.ccpkg` packaging step (and the host's runtime loader) read\n * this file to discover which page modules ship in the bundle without\n * having to re-parse the manifest.\n */\n generateBundle(_options, bundle) {\n if (pages.length === 0 && overlay === null) {\n return;\n }\n\n // ── Per-asset SHA-256 digest map (WI 4858 sub-plan 3) ──────────\n // Hash EVERY emitted chunk (not just entries) so the host's verified\n // loader can check each asset against the manifest's `assetDigests`\n // before evaluation. The build forces `inlineDynamicImports: true`\n // (see `config()`), collapsing each page to a single chunk; if that is\n // ever relaxed, every emitted chunk URL MUST still be routed through the\n // host's `verifyAndLoadPlatformReactBundle` with this full map.\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const chunk of Object.values(bundle ?? {})) {\n if ((chunk as { type?: string }).type !== \"chunk\") {\n continue;\n }\n // Rollup `OutputChunk` exposes `code` (string) + `fileName`. Cast\n // through unknown because the union narrows on `type`.\n const code = (chunk as unknown as { code: string }).code;\n const fileName = (chunk as unknown as { fileName: string }).fileName;\n const hash = createHash(\"sha256\").update(code, \"utf8\").digest(\"hex\");\n digests.push({ path: fileName, sha256: hash });\n }\n\n // Build summary: pages array + optional overlay field (WI 5160 SP-A).\n const summary: {\n pages: Array<{ id: string; exportName: string; title: string | null; bundlePath: string; source: string }>;\n overlay?: { id: string; exportName: string; title: string | null; bundlePath: string; source: string };\n } = {\n pages: pages.map((p) => ({\n id: p.id,\n exportName: p.exportName,\n title: p.title,\n bundlePath: `${outputPrefix}${p.id}.js`,\n source: p.moduleSpecifierRel,\n })),\n };\n\n if (overlay !== null) {\n summary.overlay = {\n id: overlay.id,\n exportName: overlay.exportName,\n title: overlay.title,\n bundlePath: `${outputPrefix}${overlay.id}.js`,\n source: overlay.moduleSpecifierRel,\n };\n }\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-pages.json`,\n source: JSON.stringify(summary, null, 2),\n });\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-digest-map.json`,\n source: JSON.stringify({ digests }, null, 2),\n });\n },\n };\n\n return plugin;\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type {\n PlatformReactManifest,\n PlatformReactPageDeclaration,\n} from \"./page-bundles\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A fully-validated PlatformReact page declaration. All fields are guaranteed\n * present (no `undefined`), `exportName` is defaulted to `\"default\"`, and the\n * `moduleSpecifier` is guaranteed to exist on disk when `verifyOnDisk: true`\n * was passed to {@link parsePlatformReactPages}.\n */\nexport interface ResolvedPlatformReactPage {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n title: string | null;\n}\n\n/**\n * Options for {@link parsePlatformReactPages}.\n */\nexport interface ParsePlatformReactPagesOptions {\n /**\n * Root directory the manifest path and the page module specifiers are\n * resolved against. Defaults to `process.cwd()`.\n */\n root?: string;\n /**\n * When `true`, every declared `moduleSpecifier` must exist on disk (relative\n * to {@link root}). The default is `false` so the helper can be used to\n * snapshot-test a manifest without checking-out the page source files.\n */\n verifyOnDisk?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Parse + validate `ui.platformReactPages[]` declarations from a manifest\n * file. Designed for plugin authors writing Vitest tests against their own\n * manifest — the helper applies the same shape and uniqueness rules the\n * build-time Vite pass enforces, so a passing unit test gives the same\n * guarantee a green build would.\n *\n * Returns an empty array when the manifest does not exist OR does not\n * declare `ui.platformReactPages` OR declares it as an empty array.\n *\n * Throws on any malformed declaration. The thrown message matches the\n * build-time error so a failing test reads identically to a failing build.\n *\n * @example\n * ```ts\n * import { parsePlatformReactPages } from \"@ethisyscore/vite-plugin\";\n *\n * test(\"manifest declares dashboard and admin pages\", () => {\n * const pages = parsePlatformReactPages(\"./feature.manifest.json\");\n * expect(pages).toEqual([\n * { id: \"dashboard\", moduleSpecifier: \"src/pages/Dashboard.tsx\", exportName: \"default\", title: \"Dashboard\" },\n * { id: \"admin\", moduleSpecifier: \"src/pages/Admin.tsx\", exportName: \"AdminPage\", title: null },\n * ]);\n * });\n * ```\n */\nexport function parsePlatformReactPages(\n manifestPath: string,\n options: ParsePlatformReactPagesOptions = {},\n): ResolvedPlatformReactPage[] {\n const root = options.root ?? process.cwd();\n const verifyOnDisk = options.verifyOnDisk ?? false;\n const manifestAbsPath = isAbsolute(manifestPath)\n ? manifestPath\n : resolve(root, manifestPath);\n\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n let manifest: PlatformReactManifest;\n try {\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n manifest = JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n\n const declared = manifest.ui?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return [];\n }\n\n const result: ResolvedPlatformReactPage[] = [];\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl: PlatformReactPageDeclaration = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n if (verifyOnDisk) {\n const absPath = resolve(root, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n }\n\n result.push({\n id: decl.id,\n moduleSpecifier: decl.moduleSpecifier,\n exportName:\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\",\n title:\n typeof decl.title === \"string\" && decl.title.length > 0\n ? decl.title\n : null,\n });\n }\n\n return result;\n}\n\n","import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from \"node:fs\";\nimport { basename, relative, resolve } from \"node:path\";\nimport { slash, kebab, titleCase } from \"../utils/strings\";\n\n/**\n * Build-time codegen for a PlatformReact plugin's `feature.manifest.json` +\n * project-root `extension.manifest.json` overlay, from the plugin's `routeMeta.json`\n * and its lifted page/adapter trees. Promoted from the per-plugin `gen-manifest.mjs`\n * so every migrated plugin shares one generator instead of copying the routeMeta →\n * `platformReactPages` derivation (including the nested-URL `route` emission and the\n * dashboard-at-root empty-string route).\n *\n * NOT a Vite plugin — a plain build-step helper a plugin's `gen-manifest.mjs` calls\n * before `build-pages`. It reads the filesystem and writes both manifests.\n */\n\n/** One entry of the migrated `routeMeta.json` (a faithful shift of the monolith's `routeMeta.ts`). */\nexport interface RouteMetaEntry {\n /** Full path pattern, re-rooted under `/extensions/<slug>/` (`:seg` = param). */\n pattern: string;\n label: string;\n /** Parent route's `pattern`; omit for a top-level route. */\n parent?: string;\n /** Platform-react page id this pattern maps to (the manifest link; breadcrumbs ignore it). */\n pageId?: string;\n}\n\n/** Manifest metadata written into `feature.manifest.json`. */\nexport interface PlatformReactManifestMeta {\n id: string;\n name: string;\n version: string;\n /** Defaults to `\"platform-react\"`. */\n renderMode?: string;\n /** `$schema` value; defaults to the feature-manifest schema URL. */\n schema?: string;\n}\n\n/** A generated `ui.platformReactPages[]` entry (feature-manifest form, incl. the build-only `views`). */\nexport interface PlatformReactPageEntry {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n /** Sub-path under `/extensions/<slug>/`; `\"\"` = the extension-root (dashboard) surface. Absent → host id-match. */\n route?: string;\n title: string;\n /** View name → src-relative module path, read by the page's `useView(<module>, name)`. */\n views: Record<string, string>;\n}\n\n/**\n * The singular `ui.platformReactOverlay` entry (feature-manifest form, incl. the build-only `views`).\n * Mirrors {@link PlatformReactPageEntry} minus `route` — overlays are not routed.\n * `views` is a build-time wiring artifact consumed by `build-pages` to synthesise the\n * virtual entry's `definePluginOverlay(Overlay, { ...views })` call, exactly as page `views` are.\n * It is NOT part of the protocol `PlatformReactOverlayDeclaration` and is stripped at the\n * wire/admission boundary (parallel to how page `views` are stripped).\n */\nexport interface PlatformReactOverlayEntry {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n title: string;\n /** View name → src-relative module path (build-time wiring only; stripped from the wire manifest). */\n views: Record<string, string>;\n}\n\nconst DEFAULT_SCHEMA = \"https://ethisys.dev/schemas/feature-manifest.json\";\n\n/**\n * Per-page override, keyed by page filename (incl. `.tsx`). For plugins whose page\n * ids/titles are NOT derived from the filename (e.g. `Timesheets.tsx` → id\n * `\"dashboard\"` / title `\"Dashboard\"`). Any field omitted falls back to the derived\n * default (`id` = kebab, `title` = title-case) or the routeMeta lookup (`route`).\n */\nexport interface PlatformReactPageOverride {\n id?: string;\n title?: string;\n route?: string;\n}\n\n/** One page file read for {@link computePlatformReactPages}. */\nexport interface PlatformReactPageSource {\n /** Page filename incl. `.tsx`. */\n file: string;\n /** The page's source content (scanned for `useView(<module>, …)` calls). */\n content: string;\n /**\n * Root-relative module specifier for this page (e.g. `src/pages/admin/Foo.tsx`).\n * When pages come from multiple directories each source carries its own specifier,\n * derived from the directory it was read from.\n */\n moduleSpecifier: string;\n}\n\n/** Input to {@link computePlatformReactPages} (already-read filesystem inputs). */\nexport interface ComputePlatformReactPagesInput {\n /**\n * The plugin's own `useView` module key. This does NOT control which calls the scan\n * matches: every `useView(<anyKey>, <Name>)` is matched and then classified against\n * {@link moduleKeys}. Its only role here is being the default single entry of that set.\n */\n module: string;\n /**\n * Every module key the plugin's page definer actually registers a page's flat `views`\n * map under. Defaults to `[module]`, which is what `createPluginPageDefiner` produces.\n * Must not be empty: an empty set would classify every call as unregistered.\n * Supply the full set for a hand-rolled multi-key definer (registering the same map\n * under several keys to serve cross-module `useView` calls).\n *\n * A `useView` call naming a key OUTSIDE this set can never resolve at runtime, so it is\n * reported in {@link ComputePlatformReactPagesResult.unregisteredViews}.\n */\n moduleKeys?: string[];\n /** Extension slug for the `/extensions/<slug>/` route prefix. */\n slug: string;\n routeMeta: RouteMetaEntry[];\n /** Each page file's basename (with `.tsx`) + its source content + its root-relative module specifier. */\n pages: PlatformReactPageSource[];\n /** View name → src-relative module path (e.g. `src/adapter/<module>/XView.tsx`). */\n viewFiles: Record<string, string>;\n /**\n * Second-chance resolution: EXPORTED name → every src-relative adapter module path\n * that exports it (see {@link parseExportedNames}). Consulted only when a `useView`\n * name matches no {@link viewFiles} basename, so supplying it can never change an\n * already-resolving plugin's output.\n *\n * Exists because an adapter file may legitimately export its component under a name\n * other than its filename, e.g. `ChatChannelCreateFormView.tsx` ending with\n * `export { ChatChannelCreateFormView as ChatChannelCreateForm }`. The filename-only\n * lookup declared such a call unresolvable and refused to generate at all, which is\n * how one plugin ended up with a hand-maintained manifest the generator could no\n * longer reproduce.\n *\n * Values are arrays, not single paths, precisely so a name exported by two DIFFERENT\n * files is reported as ambiguous rather than silently bound to whichever the\n * directory walk happened to reach last.\n */\n viewExports?: Record<string, string[]>;\n /** Per-file id/title/route overrides for non-filename-derived plugins. */\n pageOverrides?: Record<string, PlatformReactPageOverride>;\n}\n\n/** Result of {@link computePlatformReactPages}. */\nexport interface ComputePlatformReactPagesResult {\n entries: PlatformReactPageEntry[];\n /** `<file>: view \"<name>\" has no adapter file` diagnostics. */\n missingViews: string[];\n /**\n * `useView` calls naming a module key the definer does not register, which therefore\n * render the SDK's `MissingViewFallback` (\"View not available\") at runtime behind a\n * green build. Previously invisible: the scan was built from the plugin's own module\n * key, so such a call matched nothing and produced no binding AND no diagnostic.\n */\n unregisteredViews: string[];\n /**\n * `useView` names that matched no adapter FILENAME and are exported by more than one\n * adapter file, so there is no single correct module to bind. Binding one arbitrarily\n * would compile and then render the wrong component, so the name is left unbound and\n * reported (fatal under `strict`, the default) with every candidate path named.\n */\n ambiguousViews: string[];\n}\n\n/**\n * `export function X` / `export async function X` / `export const|let|var|class X`.\n *\n * Anchored to a line start (`m` flag + `^[ \\t]*`) so a mention inside a JSDoc block\n * (` * export function Foo`) or a line comment (`// export const Foo`) does not match:\n * neither has only whitespace before `export`. This is the same deliberately-shallow\n * text scan the `useView` matcher uses — a full TS parse is not warranted here.\n *\n * `export default …` is NOT matched, and that is the point rather than an omission:\n * `build-pages` wires a view with a NAMED import (`import { X } from \"…\"`), so a\n * default-only export cannot satisfy a `useView` name. Real adapter files rely on this\n * (`export default memo(OrgUnitNode)`, `export default SystemTechnologyListView`).\n * `export type` / `export interface` are likewise unmatched — a type is erased at\n * runtime, so a named import of one would resolve to `undefined`.\n */\nconst EXPORT_DECL_RE = /^[ \\t]*export\\s+(?:async\\s+)?(?:function|const|let|var|class)\\s+([A-Za-z_$][\\w$]*)/gm;\n\n/**\n * `export { … }` and `export { … } from \"…\"` (re-export), including the multi-line form:\n * `[^}]*` spans newlines and stops at the closing brace. Note `export type { X }` cannot\n * match — the token after `export` is `type`, not `{` — which is exactly right.\n */\nconst EXPORT_LIST_RE = /^[ \\t]*export\\s*\\{([^}]*)\\}/gm;\n\n/** `A as B` (captures both) or a bare `A`; `\\s` covers the multi-line list form. */\nconst EXPORT_SPECIFIER_RE = /^([A-Za-z_$][\\w$]*)(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?$/;\n\n/**\n * The runtime-NAMED exports of one module's source text, in no particular order and\n * deduplicated. Used to resolve a `useView` name against an adapter file that exports\n * its component under a name other than its filename.\n *\n * Covers the export forms that actually occur in the plugin adapter trees:\n * `export function X` (by far the most common), `export const X`, and the alias list\n * `export { X as Y }` / `export { X as Y, X as Z }` / `export { X } from \"…\"`.\n *\n * Deliberately NOT covered: `export default …` and type-only exports (see\n * {@link EXPORT_DECL_RE} for why both would produce a broken binding), and\n * `export * from \"…\"` — a star re-export's names cannot be known without following the\n * module graph, which is beyond a text scan. A view reachable only through a star\n * re-export therefore still reports as unresolvable rather than being mis-resolved.\n */\nexport function parseExportedNames(content: string): string[] {\n const names = new Set<string>();\n\n EXPORT_DECL_RE.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = EXPORT_DECL_RE.exec(content)) !== null) {\n names.add(m[1]);\n }\n\n EXPORT_LIST_RE.lastIndex = 0;\n while ((m = EXPORT_LIST_RE.exec(content)) !== null) {\n for (const raw of m[1].split(\",\")) {\n const item = raw.trim();\n if (item.length === 0) continue; // trailing comma in a multi-line list\n // Inline type specifier (`export { type Foo, Bar }`) — erased at runtime.\n if (/^type\\s/.test(item)) continue;\n const spec = EXPORT_SPECIFIER_RE.exec(item);\n if (spec === null) continue; // anything this shallow scan does not understand\n // `A as B` exports B; a bare `A` exports A.\n const exported = spec[2] ?? spec[1];\n // `X as default` / `export { default }` contribute a DEFAULT export, not a named one.\n if (exported === \"default\") continue;\n names.add(exported);\n }\n }\n\n return [...names];\n}\n\n/**\n * Pure core: derive the `platformReactPages[]` entries from already-read inputs (no\n * filesystem). Per page: `id` = `pageOverrides[file].id` ?? kebab(filename), `title`\n * = `pageOverrides[file].title` ?? title-case(filename), and `route` =\n * `pageOverrides[file].route` ?? the routeMeta lookup — the routeMeta pattern minus\n * the `/extensions/<slug>/` prefix, keyed by the RESOLVED id (the root pattern\n * `/extensions/<slug>` → the empty-string route, making that page the extension-root\n * / dashboard surface). Empty-string routes are emitted (presence, not truthiness);\n * a page with neither an override route nor a routeMeta entry gets no `route` and\n * falls back to the host's id match.\n */\nexport function computePlatformReactPages(\n input: ComputePlatformReactPagesInput,\n): ComputePlatformReactPagesResult {\n const routePrefix = `/extensions/${input.slug}/`;\n const routeRoot = `/extensions/${input.slug}`;\n const pageRouteById: Record<string, string> = Object.fromEntries(\n input.routeMeta\n .filter((e) => e.pageId && (e.pattern.startsWith(routePrefix) || e.pattern === routeRoot))\n .map((e) => [e.pageId as string, e.pattern === routeRoot ? \"\" : e.pattern.slice(routePrefix.length)]),\n );\n\n // Match `useView(\"<anyModule>\", \"SomeView\")`. Deliberately NOT anchored to this\n // plugin's own module key: a call naming another key is the failure this scan has to\n // see, not something to skip. The optional trailing comma matters too — a multi-line\n // call ending `\"SomeView\",\\n)` was silently dropped by the previous `\\s*\\)` tail, even\n // for the plugin's own key.\n const useViewRe = /useView\\(\\s*[\"']([\\w-]+)[\"']\\s*,\\s*[\"']([A-Za-z0-9_]+)[\"']\\s*,?\\s*\\)/g;\n\n // `??` only falls back on null/undefined, so an explicitly empty array would survive and\n // leave the set empty: every call would be reported unregistered and the diagnostic would\n // read `registered: ` with nothing after it. Fail loudly instead of emitting nonsense.\n if (input.moduleKeys !== undefined && input.moduleKeys.length === 0) {\n throw new Error(\n \"generate-manifest: moduleKeys was supplied but empty. Omit it to default to [module], \"\n + \"or list every module key the page definer registers views under.\",\n );\n }\n const registeredKeys = new Set(input.moduleKeys ?? [input.module]);\n\n const entries: PlatformReactPageEntry[] = [];\n const missingViews: string[] = [];\n const unregisteredViews: string[] = [];\n const ambiguousViews: string[] = [];\n for (const { file, content, moduleSpecifier } of input.pages) {\n const name = basename(file, \".tsx\");\n const override = input.pageOverrides?.[file] ?? {};\n const views: Record<string, string> = {};\n useViewRe.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = useViewRe.exec(content)) !== null) {\n const [, moduleKey, v] = m;\n\n if (!registeredKeys.has(moduleKey)) {\n // Even a resolvable adapter file would be registered under a key this page never\n // reads, so binding it here would not help: report instead.\n unregisteredViews.push(\n `${file}: useView(\"${moduleKey}\", \"${v}\") names a module key the definer does not `\n + `register (registered: ${[...registeredKeys].map((k) => `\"${k}\"`).join(\", \")}), `\n + `so the lookup renders \"View not available\" at runtime`,\n );\n continue;\n }\n\n // Resolution order, deliberately filename-FIRST: an existing plugin whose views all\n // match a filename resolves exactly as before, so the export scan cannot perturb\n // any manifest that already generates cleanly.\n if (input.viewFiles[v] !== undefined) {\n views[v] = input.viewFiles[v];\n continue;\n }\n\n // Second chance: exactly one adapter file EXPORTS this name (e.g. via\n // `export { XView as X }`). `build-pages` imports the view by name, so such a file\n // satisfies the call at runtime even though its basename does not match.\n const byExport = input.viewExports?.[v] ?? [];\n if (byExport.length === 1) {\n views[v] = byExport[0];\n } else if (byExport.length > 1) {\n ambiguousViews.push(\n `${file}: view \"${v}\" matches no adapter filename and is exported by `\n + `${byExport.length} adapter files, so the binding is ambiguous: `\n + `${byExport.join(\", \")}. Rename the view, or give the intended file that basename `\n + `(a filename match always wins)`,\n );\n } else {\n missingViews.push(`${file}: view \"${v}\" has no adapter file`);\n }\n }\n const id = override.id ?? kebab(name);\n // Explicit override route wins; else the routeMeta lookup by resolved id.\n // `??` (not `||`) so an empty-string route (dashboard root) survives.\n const route = override.route ?? pageRouteById[id];\n entries.push({\n id,\n moduleSpecifier,\n exportName: \"default\",\n ...(route !== undefined ? { route } : {}),\n title: override.title ?? titleCase(name),\n views,\n });\n }\n return { entries, missingViews, unregisteredViews, ambiguousViews };\n}\n\n/** Path overrides for {@link generatePlatformReactManifest} (relative to `root` unless absolute). */\nexport interface PlatformReactManifestPaths {\n /** Source root; default `\"src\"`. */\n src?: string;\n /**\n * Pages dir(s); default `src/pages/<module>`. Accepts a single string (backward-compat)\n * or an array of directories to scan together. Each `.tsx` file's `moduleSpecifier` is\n * derived from the directory it was read from. A duplicate basename across dirs throws a\n * clear error (fail-fast) — there is no per-dir escape hatch. `pageExclude` removes a\n * filename from ALL scanned dirs, so it cannot preserve one dir's copy while dropping\n * another's; to ship two pages with the same filename, rename one of them.\n */\n pages?: string | string[];\n /** Page filenames (incl. `.tsx`) to skip — e.g. dialogs that live in a pages dir. */\n pageExclude?: string[];\n /** Adapter (views) dir; default `src/adapter/<module>`. */\n adapter?: string;\n /** routeMeta file; default `src/config/routeMeta.json`. */\n routeMeta?: string;\n /** feature manifest output; default `\"feature.manifest.json\"`. */\n featureManifest?: string;\n /** project-root overlay output; default `\"../extension.manifest.json\"`. */\n overlay?: string;\n}\n\n/** Author-facing config for {@link generatePlatformReactManifest}. */\nexport interface GeneratePlatformReactManifestConfig {\n /** Absolute path to the plugin's `ui/` root (holds `src/` + the emitted manifests). */\n root: string;\n /** `useView` module key AND the default `pages/adapter` sub-dir name (e.g. `\"finance\"`). */\n module: string;\n /** Extension slug for the `/extensions/<slug>/` route prefix; defaults to `module`. */\n slug?: string;\n /** Metadata written into `feature.manifest.json`. */\n manifest: PlatformReactManifestMeta;\n /**\n * Singular overlay declaration. When present, emits `ui.platformReactOverlay` in\n * `feature.manifest.json` (with `views` for build-pages virtual-entry synthesis) and\n * in the `extension.manifest.json` wire overlay (without `views`, mirroring the page\n * strip). Omit to suppress the key entirely.\n */\n overlay?: PlatformReactOverlayEntry;\n /**\n * Per-page id/title/route overrides, keyed by page filename (incl. `.tsx`). Only\n * needed for plugins whose ids/titles aren't the filename-derived defaults; omit\n * for the filename convention. See {@link PlatformReactPageOverride}.\n */\n pageOverrides?: Record<string, PlatformReactPageOverride>;\n /** Path overrides (relative to `root` unless absolute). See {@link PlatformReactManifestPaths}. */\n paths?: PlatformReactManifestPaths;\n /**\n * Every module key the plugin's definer registers page `views` under. Defaults to\n * `[module]`. See {@link ComputePlatformReactPagesInput.moduleKeys}.\n */\n moduleKeys?: string[];\n /**\n * Throw when any `useView` call cannot be satisfied (default `true`).\n *\n * `useView` is a name-to-component lookup against the static manifest slice the\n * generated entry registers, not an import, so an unsatisfiable call is NOT a build\n * error: the surface renders the SDK's `MissingViewFallback` (\"View not available\") at\n * runtime behind a green build. Failing the generator is what turns that into a\n * build-time error.\n *\n * \"Cannot be satisfied\" means all three diagnostics: an unregistered module key\n * ({@link ComputePlatformReactPagesResult.unregisteredViews}), a name exported by two\n * adapter files ({@link ComputePlatformReactPagesResult.ambiguousViews}), and a name\n * matching neither an adapter filename nor any adapter export\n * ({@link ComputePlatformReactPagesResult.missingViews}). All three leave the name\n * unbound, so all three produce the same runtime blank surface.\n *\n * Both manifests are still written before the throw, so the emitted files stay in sync\n * with the page tree; the exception, not a stale file, is the gate. Set `false` only to\n * unblock a migration mid-flight, and read the returned diagnostics instead.\n */\n strict?: boolean;\n}\n\n/** What {@link generatePlatformReactManifest} produced. */\nexport interface GeneratePlatformReactManifestResult {\n pageCount: number;\n /** Page ids whose source resolved zero views. */\n pagesWithoutView: string[];\n /** `<file>: view \"<name>\" has no adapter file` diagnostics. */\n missingViews: string[];\n /** `useView` calls naming an unregistered module key. See {@link ComputePlatformReactPagesResult.unregisteredViews}. */\n unregisteredViews: string[];\n /** `useView` names exported by two or more adapter files. See {@link ComputePlatformReactPagesResult.ambiguousViews}. */\n ambiguousViews: string[];\n featureManifestPath: string;\n overlayPath: string;\n}\n\nfunction walk(dir: string): string[] {\n const out: string[] = [];\n for (const n of readdirSync(dir)) {\n const p = resolve(dir, n);\n if (statSync(p).isDirectory()) {\n out.push(...walk(p));\n } else {\n out.push(p);\n }\n }\n return out;\n}\n\n/**\n * Read the plugin's `routeMeta.json` + page/adapter trees and write both\n * `feature.manifest.json` (with the build-only `views` map) and the project-root\n * `extension.manifest.json` overlay (pages WITHOUT `views` — what `cc package` reads\n * for the host's install-time nav-path validation). Returns a summary for logging.\n */\nexport function generatePlatformReactManifest(\n config: GeneratePlatformReactManifestConfig,\n): GeneratePlatformReactManifestResult {\n const { root, module } = config;\n const slug = config.slug ?? module;\n const src = config.paths?.src ?? \"src\";\n const adapterDir = resolve(root, config.paths?.adapter ?? `${src}/adapter/${module}`);\n const routeMetaPath = resolve(root, config.paths?.routeMeta ?? `${src}/config/routeMeta.json`);\n const featureManifestRel = config.paths?.featureManifest ?? \"feature.manifest.json\";\n const overlayRel = config.paths?.overlay ?? \"../extension.manifest.json\";\n\n // routeMeta is optional: a plugin that needs neither nested URLs nor breadcrumbs\n // simply ships no routeMeta.json — every page then falls back to the host id match.\n const routeMeta: RouteMetaEntry[] = existsSync(routeMetaPath)\n ? (JSON.parse(readFileSync(routeMetaPath, \"utf8\")) as RouteMetaEntry[])\n : [];\n // paths.pages: string | string[] (default single \"src/pages/<module>\")\n const pagesCfg = config.paths?.pages ?? `${src}/pages/${module}`;\n const pageDirs = (Array.isArray(pagesCfg) ? pagesCfg : [pagesCfg]).map((p) => resolve(root, p));\n const exclude = new Set(config.paths?.pageExclude ?? []);\n\n // View name → root-relative module path (e.g. `src/adapter/<module>/XView.tsx`).\n // A missing adapter dir is treated as no views (not a hard ENOENT) so a plugin\n // with no adapter tree still generates — any page that DOES call useView then\n // surfaces a helpful `missingViews` diagnostic instead of a raw filesystem error.\n //\n // Alongside it, EXPORTED name → the adapter files exporting it, so a view whose\n // exported name differs from its filename (`export { XView as X }`) still resolves.\n // Kept as a separate second-chance map rather than folded into `viewFiles` so the\n // filename lookup keeps exact precedence and duplicate exported names stay visible\n // as ambiguity instead of silently overwriting one another.\n const viewFiles: Record<string, string> = {};\n const viewExportsByName = new Map<string, Set<string>>();\n if (existsSync(adapterDir)) {\n for (const f of walk(adapterDir)) {\n if (f.endsWith(\".tsx\")) {\n const rel = slash(relative(root, f));\n viewFiles[basename(f, \".tsx\")] = rel;\n for (const name of parseExportedNames(readFileSync(f, \"utf8\"))) {\n let paths = viewExportsByName.get(name);\n if (paths === undefined) {\n paths = new Set<string>();\n viewExportsByName.set(name, paths);\n }\n // A Set: one file declaring the same name twice (`export function X` plus a\n // later `export { X }`) must not read as two candidates and fake an ambiguity.\n paths.add(rel);\n }\n }\n }\n }\n // Sort the candidate paths so an ambiguity diagnostic reads identically across\n // platforms and runs (directory-walk order is not a contract).\n const viewExports: Record<string, string[]> = Object.fromEntries(\n [...viewExportsByName].map(([name, paths]) => [name, [...paths].sort()]),\n );\n\n const seen = new Map<string, string>(); // basename -> dir (duplicate guard)\n const pages: PlatformReactPageSource[] = [];\n for (const dir of pageDirs) {\n if (!existsSync(dir)) {\n throw new Error(`generate-manifest: pages dir not found: ${dir}`);\n }\n for (const file of readdirSync(dir).filter((f) => f.endsWith(\".tsx\")).sort()) {\n if (exclude.has(file)) continue;\n if (seen.has(file)) {\n throw new Error(\n `generate-manifest: duplicate page filename \"${file}\" in both ${seen.get(file)} and ${dir}`,\n );\n }\n seen.set(file, dir);\n // Build the root-relative specifier. When the pages dir IS the root, relative()\n // returns \"\" and a naive `\"${relDir}/${file}\"` would yield `\"/${file}\"` (leading\n // slash). Join without the separator in that case so the root case yields just\n // `\"${file}\"` and the non-root case yields `\"src/pages/x/${file}\"` (unchanged).\n const relDir = slash(relative(root, dir));\n const moduleSpecifier = relDir ? `${relDir}/${file}` : file;\n pages.push({\n file,\n content: readFileSync(resolve(dir, file), \"utf8\"),\n moduleSpecifier,\n });\n }\n }\n\n const { entries, missingViews, unregisteredViews, ambiguousViews } = computePlatformReactPages({\n module,\n moduleKeys: config.moduleKeys,\n slug,\n routeMeta,\n pages,\n viewFiles,\n viewExports,\n pageOverrides: config.pageOverrides,\n });\n\n const schema = config.manifest.schema ?? DEFAULT_SCHEMA;\n const renderMode = config.manifest.renderMode ?? \"platform-react\";\n\n const overlayEntry = config.overlay;\n const featureManifest = {\n $schema: schema,\n id: config.manifest.id,\n name: config.manifest.name,\n version: config.manifest.version,\n renderMode,\n ui: {\n platformReactPages: entries,\n ...(overlayEntry !== undefined ? { platformReactOverlay: overlayEntry } : {}),\n },\n };\n const featureManifestPath = resolve(root, featureManifestRel);\n writeFileSync(featureManifestPath, JSON.stringify(featureManifest, null, 2) + \"\\n\");\n\n // Wire form of the overlay entry: strip `views` (build-time wiring only, not a protocol field).\n // Parallel to how page entries are stripped of `views` for the extension.manifest.json.\n const overlayWireEntry =\n overlayEntry !== undefined\n ? {\n id: overlayEntry.id,\n moduleSpecifier: overlayEntry.moduleSpecifier,\n exportName: overlayEntry.exportName,\n title: overlayEntry.title,\n }\n : undefined;\n\n const overlay = {\n $schema: schema,\n ui: {\n platformReactPages: entries.map(({ id, moduleSpecifier, exportName, route, title }) => ({\n id,\n moduleSpecifier,\n exportName,\n ...(route !== undefined ? { route } : {}),\n title,\n })),\n ...(overlayWireEntry !== undefined ? { platformReactOverlay: overlayWireEntry } : {}),\n },\n };\n const overlayPath = resolve(root, overlayRel);\n writeFileSync(overlayPath, JSON.stringify(overlay, null, 2) + \"\\n\");\n\n const pagesWithoutView = entries\n .filter((e) => Object.keys(e.views).length === 0)\n .map((e) => e.id);\n\n const result: GeneratePlatformReactManifestResult = {\n pageCount: entries.length,\n pagesWithoutView,\n missingViews,\n unregisteredViews,\n ambiguousViews,\n featureManifestPath,\n overlayPath,\n };\n\n // Both manifests are already written, so the emitted files stay in sync with the page\n // tree; the throw is the gate, not a stale file. See `strict` for why this is fatal by\n // default: an unsatisfiable useView call is a runtime blank surface, not a build error.\n const diagnostics = [...unregisteredViews, ...ambiguousViews, ...missingViews];\n if ((config.strict ?? true) && diagnostics.length > 0) {\n throw new Error(\n `generate-manifest: ${diagnostics.length} unresolvable `\n + `useView call(s). Each renders \"View not available\" at runtime behind a green build:\\n`\n + diagnostics.map((d) => ` - ${d}`).join(\"\\n\"),\n );\n }\n\n return result;\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve, sep } from \"node:path\";\nimport type { Plugin } from \"vite\";\n// Tier U manifest + integrity shapes are owned by the protocol SSOT (sub-plan 01 D1).\n// Consume them — do NOT re-declare a local copy.\nimport { AssetDigest, IframeSandboxPageDeclaration } from \"@ethisyscore/protocol\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/** One emitted artifact from a per-page Vite sub-build. */\nexport type IframeBuildOutputItem =\n | { type: \"chunk\"; fileName: string; code: string }\n | { type: \"asset\"; fileName: string; source: string | Uint8Array };\n\nexport interface IframeBuildResult {\n output: IframeBuildOutputItem[];\n}\n\n/** A single page handed to the (injectable) builder. */\nexport interface IframeBuildContext {\n id: string;\n title: string;\n entryPath: string;\n root: string;\n /** Per-page output directory (`<outputDir>/<id>`). */\n outDir: string;\n}\n\n/** Injectable per-page builder. Defaults to a real Vite library build. */\nexport type IframeViteBuild = (page: IframeBuildContext) => Promise<IframeBuildResult>;\n\nexport interface IframeSandboxPluginOptions {\n /** Root the manifest + entry paths resolve against. Defaults to Vite's resolved root / cwd. */\n root?: string;\n /** Manifest path (relative to `root`). Default `feature.manifest.json`. */\n manifestPath?: string;\n /** Output directory for per-page bundles + the digest map. Default `dist/iframe-sandbox`. */\n outputDir?: string;\n /** Inline manifest object (test injection). When omitted, the manifest is read from disk. */\n manifest?: unknown;\n /** Injectable per-page builder (test injection). When omitted, a real Vite build runs. */\n build?: IframeViteBuild;\n /** Injectable file writer (test injection). When omitted, writes via `fs` (creating dirs). */\n writeFile?: (path: string, contents: string) => void;\n}\n\nexport interface IframeSandboxBuildSummary {\n digests: Array<{ path: string; sha256: string }>;\n digestMapPath: string | null;\n}\n\nconst DEFAULT_MANIFEST = \"feature.manifest.json\";\nconst DEFAULT_OUTPUT_DIR = \"dist/iframe-sandbox\";\nconst DIGEST_MAP_FILENAME = \"iframe-sandbox-digest-map.json\";\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\nfunction defaultWriteFile(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n}\n\n/** Real per-page build via Vite's programmatic API. `vite` is an optional peer dep. */\nconst defaultBuild: IframeViteBuild = async (page) => {\n const { build } = await import(\"vite\");\n const result = await build({\n root: page.root,\n logLevel: \"warn\",\n build: {\n outDir: page.outDir,\n emptyOutDir: true,\n rollupOptions: {\n input: resolve(page.root, page.entryPath),\n },\n },\n });\n // `build()` returns RollupOutput | RollupOutput[] | RollupWatcher; the\n // library build (no watch) yields a single RollupOutput.\n const out = Array.isArray(result) ? result[0] : result;\n return { output: (out as unknown as IframeBuildResult).output };\n};\n\nfunction digestOf(item: IframeBuildOutputItem): string {\n const bytes = item.type === \"chunk\" ? item.code : item.source;\n return createHash(\"sha256\").update(bytes as string | Uint8Array).digest(\"hex\");\n}\n\nfunction readManifest(options: IframeSandboxPluginOptions, root: string): unknown {\n if (options.manifest !== undefined) {\n return options.manifest;\n }\n const rel = options.manifestPath ?? DEFAULT_MANIFEST;\n const abs = isAbsolute(rel) ? rel : resolve(root, rel);\n if (!existsSync(abs)) {\n return null;\n }\n const raw = readFileSync(abs, \"utf8\");\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw new Error(`[ethisys-iframe-sandbox] Failed to parse manifest at \"${abs}\": ${(e as Error).message}`);\n }\n}\n\n// ── Orchestration (exposed for unit testing) ───────────────────────\n\n/**\n * Build each `ui.iframeSandboxPages[]` declaration as its own Vite app bundle and\n * emit a per-asset SHA-256 digest map in the SAME shape `ethisysPlatformReactPlugin`\n * produces (`{ digests: [{ path, sha256 }] }`). Tier U surfaces are independent\n * cross-origin apps, so each page is a separate sub-build under `<outputDir>/<id>/`;\n * every emitted artifact is hashed (and validated against the protocol `AssetDigest`\n * schema) so the edge integrity endpoint (sub-plan 5, Task 6) can verify served bytes.\n *\n * No-op when no pages are declared. Page shape is validated by the protocol\n * `IframeSandboxPageDeclaration` schema (a malformed entry rejects the build).\n */\nexport async function buildIframeSandboxPages(\n options: IframeSandboxPluginOptions = {},\n): Promise<IframeSandboxBuildSummary> {\n const root = options.root ?? process.cwd();\n const manifest = readManifest(options, root);\n\n const declared = (manifest as { ui?: { iframeSandboxPages?: unknown[] } } | null)?.ui?.iframeSandboxPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return { digests: [], digestMapPath: null };\n }\n\n // Validate every page against the protocol schema (SSOT) before building.\n const pages = declared.map((raw, i) => {\n try {\n return IframeSandboxPageDeclaration.parse(raw);\n } catch (e) {\n throw new Error(\n `[ethisys-iframe-sandbox] ui.iframeSandboxPages[${i}] is invalid: ${(e as Error).message}`,\n );\n }\n });\n\n const seen = new Set<string>();\n for (const p of pages) {\n if (seen.has(p.id)) {\n throw new Error(`[ethisys-iframe-sandbox] Duplicate iframe-sandbox page id \"${p.id}\".`);\n }\n seen.add(p.id);\n }\n\n const build = options.build ?? defaultBuild;\n const write = options.writeFile ?? defaultWriteFile;\n const outputDir = options.outputDir ?? DEFAULT_OUTPUT_DIR;\n const outDirAbs = isAbsolute(outputDir) ? outputDir : resolve(root, outputDir);\n\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const page of pages) {\n const result = await build({\n id: page.id,\n title: page.title,\n entryPath: page.entryPath,\n root,\n outDir: resolve(outDirAbs, page.id),\n });\n for (const item of result.output) {\n const entry = { path: `${page.id}/${item.fileName}`, sha256: digestOf(item) };\n // The integrity entry conforms to the protocol AssetDigest contract.\n AssetDigest.parse(entry);\n digests.push(entry);\n }\n }\n\n const digestMapPath = resolve(outDirAbs, DIGEST_MAP_FILENAME);\n write(slash(digestMapPath), JSON.stringify({ digests }, null, 2));\n return { digests, digestMapPath };\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Tier U (iframe-sandbox) Vite build pass (WI 4858 sub-plan 5). Mirrors\n * `ethisysPlatformReactPlugin`: keyed off `ui.iframeSandboxPages[]` and a no-op\n * when absent, so a single Vite config can compose every render-mode pass.\n *\n * Unlike Tier T (ESM modules in the parent build), each Tier U page is an\n * independent cross-origin app — so the pass runs a separate Vite sub-build per\n * page in `closeBundle` and emits the integrity digest map the host verifies.\n */\nexport function ethisysIframeSandboxPlugin(options: IframeSandboxPluginOptions = {}): Plugin {\n let resolvedRoot = options.root;\n\n return {\n name: \"ethisys-iframe-sandbox\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!options.root) {\n resolvedRoot = config.root;\n }\n },\n\n async closeBundle() {\n await buildIframeSandboxPages({ ...options, root: options.root ?? resolvedRoot });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { isAbsolute, normalize, resolve, sep } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\n// ── Contract A (Wave 0): SDUI schema validation + emission ─────────\n//\n// Re-exports the Contract A pass so consumers can compose it alongside the\n// legacy manifest HTML-entry plugin (or use it on its own for host-rendered\n// plugins that ship no HTML at all).\nexport {\n ethisysContractAPlugin,\n type ContractAPluginOptions,\n type ContractAManifest,\n type ManifestResourceRef,\n type ManifestReactiveRuleRef,\n} from \"./contract-a/emit\";\nexport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationResult,\n type ValidationFailure,\n} from \"./contract-a/schema-validator\";\n\n// ── Contract B (Wave 1): Worker-bundle emission ────────────────────\n//\n// Re-export the Contract B pass so consumers can compose it alongside the\n// Contract A schema-validation pass. The two passes are non-interfering:\n// each pass keys off `renderMode` and exits early when the manifest is not\n// addressed to it. The recommended scaffold registers both plugins so a\n// manifest can switch render modes without changing its Vite config.\nexport {\n ethisysContractBPlugin,\n type ContractBPluginOptions,\n type ContractBManifest,\n CONTRACT_B_SEMANTIC_PRIMITIVES,\n CONTRACT_B_RUNTIME_IMPORTS,\n CONTRACT_B_IMPORT_MAP_ALLOWLIST,\n} from \"./contract-b/worker-bundle\";\n\n// ── PlatformReact pages (RFC 0003) ─────────────────────────────────\n//\n// Build pass for the high-trust host-extension tier. Reads\n// `ui.platformReactPages[]` from the manifest and emits one ESM bundle per\n// page. The host loads each bundle at surface mount time via `import(url)`\n// against the same-origin asset endpoint.\n// `ethisysPlatformReactPlugin` returns an ARRAY (the page pass + the plugin-CSS\n// scoping pass it must always be paired with); Vite flattens nested plugin arrays,\n// so it drops into `plugins: [...]` unchanged. `ethisysPlatformReactPagesPlugin` is\n// the page pass alone, for hand-rolled composition — see its doc comment.\nexport {\n ethisysPlatformReactPlugin,\n ethisysPlatformReactPagesPlugin,\n type PlatformReactPluginOptions,\n type PlatformReactManifest,\n type PlatformReactPageDeclaration,\n} from \"./platform-react/page-bundles\";\n\n// Test-time helper for plugin authors who want to snapshot-test their\n// manifest's PlatformReact page declarations without spinning a Vite build.\n// Applies the same shape + uniqueness rules the build-time pass enforces.\nexport {\n parsePlatformReactPages,\n type ResolvedPlatformReactPage,\n type ParsePlatformReactPagesOptions,\n} from \"./platform-react/test-helpers\";\n\n// Multi-bundle orchestrator: one isolated Vite sub-build per declared page\n// (required because `inlineDynamicImports` is illegal with >1 Rollup input).\n// Owns the host externals, dedupe, the host-loader aliased-import rewrite, and\n// the digest/summary contract; the plugin supplies only its aliases + plugins.\n// Used by a plugin's `build-pages` script in place of a hand-rolled copy.\nexport {\n buildPlatformReactPages,\n rewriteAliasedExternalImports,\n virtualPageEntry,\n PLATFORM_REACT_EXTERNALS,\n PLATFORM_REACT_DEDUPE,\n type BuildPlatformReactPagesOptions,\n type PlatformReactBuildSummary,\n type PlatformReactBuildContext,\n type PlatformReactPageInput,\n type PlatformReactAlias,\n type PlatformReactViteBuild,\n type ViteBuildFn,\n} from \"./platform-react/build-pages\";\n\n// Plugin-CSS scoping + its build guard. ONE convention, enforced rather than\n// documented: a plugin never emits an unscoped selector into the host document.\n// `scopePluginCss` handles the layers Tailwind generates unscoped (`utilities`, the\n// `@property` fallbacks in `properties`, and the `:root, :host` theme scale);\n// `findUnscopedSelectors` fails the build if anything else would still leak.\n// Applied automatically by both page-build paths; exported for a plugin with a\n// hand-rolled build, for a pre-commit check, and for tests.\nexport {\n scopePluginCss,\n scopePluginCssPlugin,\n findUnscopedSelectors,\n formatUnscopedSelectorError,\n isScopableCssId,\n EHX_PLUGIN_CSS_SCOPE,\n EHX_PLUGIN_ROOT_SCOPE,\n EHX_PLUGIN_SCOPE_ROOTS,\n EHX_SCOPED_CSS_LAYERS,\n type ScopePluginCssOptions,\n} from \"./platform-react/scope-plugin-css\";\n\n// Build-step codegen (NOT a Vite plugin): derive `feature.manifest.json` +\n// project-root `extension.manifest.json` overlay from a plugin's `routeMeta.json`\n// and its page/adapter trees — the shared replacement for a per-plugin\n// `gen-manifest.mjs` (routeMeta → platformReactPages routes, incl. nested-URL\n// `route`s and the dashboard-at-root empty-string route).\nexport {\n generatePlatformReactManifest,\n computePlatformReactPages,\n parseExportedNames,\n type GeneratePlatformReactManifestConfig,\n type GeneratePlatformReactManifestResult,\n type PlatformReactManifestMeta,\n type PlatformReactManifestPaths,\n type PlatformReactPageEntry,\n type PlatformReactPageOverride,\n type PlatformReactPageSource,\n type ComputePlatformReactPagesInput,\n type ComputePlatformReactPagesResult,\n type RouteMetaEntry,\n} from \"./platform-react/generate-manifest\";\n\n// ── Tier U: iframe-sandbox pages (WI 4858 sub-plan 5) ──────────────\n//\n// Build pass for the cross-origin sandboxed tier. Reads `ui.iframeSandboxPages[]`\n// (typed by the protocol `IframeSandboxPageDeclaration`), runs one Vite sub-build\n// per page, and emits the per-asset SHA-256 digest map the edge integrity endpoint\n// verifies. No-op when no iframe-sandbox pages are declared.\nexport {\n ethisysIframeSandboxPlugin,\n buildIframeSandboxPages,\n type IframeSandboxPluginOptions,\n type IframeSandboxBuildSummary,\n type IframeViteBuild,\n type IframeBuildContext,\n type IframeBuildResult,\n type IframeBuildOutputItem,\n} from \"./iframeSandboxPlugin\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\ninterface ManifestEntry {\n id?: string;\n entrypoint: string;\n source?: string;\n title?: string;\n template?: string;\n type?: string;\n route?: string;\n}\n\ninterface Manifest {\n ui?: {\n pages?: ManifestEntry[];\n surfaces?: ManifestEntry[];\n };\n}\n\nexport interface EthisysPluginOptions {\n /**\n * Path to the manifest file, relative to Vite's root directory.\n * @default \"../extension.manifest.json\"\n */\n manifestPath?: string;\n\n /**\n * ID of the mount element in the generated HTML.\n * React plugins use \"root\", Vue plugins use \"app\".\n * @default \"root\"\n */\n mountId?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Normalize Windows backslashes to forward slashes for Vite/Rollup compatibility. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n/** Escape HTML special characters to prevent XSS via manifest fields (e.g., title). */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n/** Validates a manifest path is relative with no traversal (cross-platform). */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.includes(\"..\")) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Vite plugin that reads `extension.manifest.json` (or a custom manifest path)\n * and auto-generates HTML entry points for all pages and surfaces that declare\n * a `source` field. No physical HTML files are required.\n *\n * Pages without a `source` field share the main entry point (SPA mode).\n * Surfaces (dialogs, panels) each get their own HTML shell.\n */\nexport function ethisysManifestPlugin(\n options: EthisysPluginOptions = {},\n): Plugin {\n const manifestRelPath = options.manifestPath ?? \"../extension.manifest.json\";\n const mountId = options.mountId ?? \"root\";\n let entries: ManifestEntry[] = [];\n let rootDir: string;\n let manifestAbsPath: string;\n // Cache generated HTML Promises to avoid stampede on concurrent requests (PERF-5)\n const htmlCache = new Map<string, Promise<string>>();\n\n // ── HTML generation ──────────────────────────────────────────────\n\n function generateHtml(entry: ManifestEntry): string {\n // Enterprise escape hatch: custom HTML template\n if (entry.template) {\n assertSafeRelativePath(entry.template, \"Template path\");\n\n const templatePath = resolve(rootDir, entry.template);\n if (existsSync(templatePath)) {\n let html = readFileSync(templatePath, \"utf-8\");\n\n // Validate template has a mount point (flexible — accepts any element/quoting)\n const safeMountId = escapeHtml(mountId);\n const mountPattern = new RegExp(`id=[\"']${safeMountId}[\"']`);\n if (!mountPattern.test(html)) {\n throw new Error(\n `[ethisys-manifest] Custom template \"${entry.template}\" must contain an element with id=\"${mountId}\".`,\n );\n }\n\n html = html.replaceAll(\"{{SOURCE}}\", escapeHtml(entry.source!));\n return html;\n }\n }\n\n // Default minimal HTML shell.\n // Uses relative src (no leading /) so Vite's transformIndexHtml resolves\n // it against config.base correctly for CDN/subdirectory deployments.\n const safeTitle = escapeHtml(entry.title ?? \"Plugin\");\n const safeSource = escapeHtml(entry.source!);\n const safeMountId = escapeHtml(mountId);\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${safeTitle}</title>\n </head>\n <body>\n <div id=\"${safeMountId}\"></div>\n <script type=\"module\" src=\"${safeSource}\"></script>\n </body>\n</html>`;\n }\n\n // ── Manifest parsing ─────────────────────────────────────────────\n\n function readManifest(): ManifestEntry[] {\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n let manifest: Manifest;\n try {\n manifest = JSON.parse(raw) as Manifest;\n } catch {\n throw new Error(\n `[ethisys-manifest] Failed to parse manifest at \"${manifestAbsPath}\".`,\n );\n }\n\n const result: ManifestEntry[] = [];\n\n // Collect entries with a source field (pages + surfaces)\n for (const page of manifest.ui?.pages ?? []) {\n if (page.source) {\n result.push(page);\n }\n }\n for (const surface of manifest.ui?.surfaces ?? []) {\n if (surface.source) {\n result.push(surface);\n }\n }\n\n return result;\n }\n\n // ── Validation ───────────────────────────────────────────────────\n\n function validateEntries(): void {\n // Multiple routes can share the same entrypoint (SPA mode).\n // But each entrypoint can only have ONE source file.\n const entrypointSources = new Map<string, string>();\n\n for (const entry of entries) {\n const source = entry.source!;\n\n // Validate no path traversal or absolute paths (cross-platform)\n assertSafeRelativePath(source, \"Source path\");\n\n // Validate source file exists on disk\n const sourcePath = resolve(rootDir, source);\n if (!existsSync(sourcePath)) {\n throw new Error(\n `[ethisys-manifest] Source file \"${source}\" for entry \"${entry.entrypoint}\" does not exist.`,\n );\n }\n\n // Validate entrypoint → source uniqueness\n const existingSource = entrypointSources.get(entry.entrypoint);\n if (existingSource && existingSource !== source) {\n throw new Error(\n `[ethisys-manifest] Conflicting sources for entrypoint \"${entry.entrypoint}\": ` +\n `\"${existingSource}\" and \"${source}\". ` +\n `Only one source file can be mapped to a single entrypoint.`,\n );\n }\n entrypointSources.set(entry.entrypoint, source);\n }\n }\n\n // ── Vite Plugin Hooks ────────────────────────────────────────────\n\n return {\n name: \"ethisys-manifest\",\n enforce: \"pre\",\n\n config(config, { command }) {\n rootDir = config.root ?? process.cwd();\n manifestAbsPath = resolve(rootDir, manifestRelPath);\n entries = readManifest();\n\n if (entries.length === 0) {\n return;\n }\n\n validateEntries();\n\n // Inject Rollup inputs for build mode.\n // ALL entries are virtual — including index.html.\n if (command === \"build\") {\n const input: Record<string, string> = {};\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (seen.has(entry.entrypoint)) {\n continue;\n }\n seen.add(entry.entrypoint);\n\n const name = entry.entrypoint.replace(/\\.html$/, \"\");\n input[name] = slash(resolve(rootDir, entry.entrypoint));\n }\n\n return {\n build: {\n rollupOptions: {\n input,\n },\n },\n };\n }\n },\n\n // Dev server: intercept HTML requests and serve virtual HTML.\n // Pre-middleware — runs before Vite's built-in handlers.\n // Safe because we only respond to .html requests and SPA navigation;\n // module requests (/@vite/client, /@react-refresh, .ts/.tsx/.css files)\n // don't match our conditions and pass through to Vite's transform middleware.\n configureServer(server: ViteDevServer) {\n server.watcher.add(manifestAbsPath);\n\n server.middlewares.use(async (req, res, next) => {\n try {\n const url = req.url?.split(\"?\")[0] ?? \"\";\n const acceptsHtml = req.headers.accept?.includes(\"text/html\");\n\n // 1. Explicit .html or root requests → match against entry points\n if (url.endsWith(\".html\") || url === \"/\" || url === \"/index.html\") {\n const filename =\n url === \"/\" || url === \"/index.html\"\n ? \"index.html\"\n : url.slice(1);\n\n const entry = entries.find((e) => e.entrypoint === filename);\n if (entry) {\n // Cache the Promise to prevent stampede on concurrent requests (PERF-5)\n const cacheKey = `entry:${filename}`;\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(entry);\n htmlCache.set(cacheKey, server.transformIndexHtml(url, rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n // 2. SPA fallback: non-file navigation requests (e.g., /books/catalog\n // refreshed in the browser) → serve index.html for client-side routing.\n // Only triggers for requests that explicitly Accept text/html (browser\n // navigation), not module/asset requests which use Accept: */*.\n if (acceptsHtml && !url.includes(\".\")) {\n const mainEntry = entries.find(\n (e) => e.entrypoint === \"index.html\",\n );\n if (mainEntry) {\n // SPA uses entrypoint as cache key (not url) to avoid unbounded cache growth\n const cacheKey = \"spa:index.html\";\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(mainEntry);\n htmlCache.set(cacheKey, server.transformIndexHtml(\"/\", rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n next();\n } catch (err) {\n next(err);\n }\n });\n },\n\n // Watch manifest for changes during dev — reload entries on edit.\n // Entire handler is wrapped in try/catch so JSON syntax errors in the\n // manifest don't crash the dev server (common during active editing).\n handleHotUpdate({ file, server }) {\n if (slash(file) === slash(manifestAbsPath)) {\n try {\n entries = readManifest();\n validateEntries();\n // Invalidate HTML cache on manifest change (PERF-5)\n htmlCache.clear();\n } catch (e) {\n server.config.logger.error(String(e));\n return [];\n }\n\n server.config.logger.info(\n \"[ethisys-manifest] Manifest changed — reloading entries\",\n );\n server.hot.send({ type: \"full-reload\" });\n return [];\n }\n },\n\n // Build: resolve virtual HTML module IDs (no physical files exist on disk)\n resolveId(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return id;\n }\n },\n\n // Build: provide virtual HTML content for Rollup\n load(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return generateHtml(match);\n }\n },\n };\n}\n"]}
|