@ethisyscore/vite-plugin 1.6.3 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +327 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +135 -2
- package/dist/index.d.ts +135 -2
- package/dist/index.js +326 -9
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.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/index.ts"],"names":["KNOWN_PRIMITIVES","KNOWN_OPERATORS","KNOWN_RULE_KINDS","SduiNode","ReactiveRule","normalize","isAbsolute","resolve","existsSync","readFileSync","sep","slash","assertSafeRelativePath","safeMountId"],"mappings":";;;;;;;AAgDA,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAYA,yBAAgB,CAAA;AAC5D,IAAM,kBAAA,GAAqB,IAAI,GAAA,CAAYC,wBAAe,CAAA;AAC1D,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAYC,yBAAgB,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,IAA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O,EAAC;AAAA,MACV;AAAA,IACF,CAAA;AAAA;AAAA,IAGA,UAAU,EAAA,EAAI;AACZ,MAAA,MAAM,YAAA,GAAeA,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAMJ,YAAAA,CAAQ,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,GAAeI,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAMJ,YAAAA,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.cjs","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] 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","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// ── 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/platform-react/page-bundles.ts","../src/platform-react/test-helpers.ts","../src/index.ts"],"names":["KNOWN_PRIMITIVES","KNOWN_OPERATORS","KNOWN_RULE_KINDS","SduiNode","ReactiveRule","normalize","isAbsolute","resolve","existsSync","readFileSync","sep","assertH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AA,MAAA,CAAO,GAAA,CAAI,IAAA,CAAK,EAAE,IAAA,EAAM,eAAe,CAAA;AACvC,QAAA,OAAO,EAAC;AAAA,MACV;AAAA,IACF,CAAA;AAAA;AAAA,IAGA,UAAU,EAAA,EAAI;AACZ,MAAA,MAAM,YAAA,GAAeA,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAML,YAAAA,CAAQ,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,GAAeK,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAML,YAAAA,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.cjs","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","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize, sep } from \"node:path\";\nimport type { Plugin } from \"vite\";\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 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 [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\n/** Normalise Windows backslashes for the Rollup input table. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\ninterface ResolvedPage {\n id: string;\n exportName: string;\n title: string | null;\n moduleSpecifierRel: string;\n moduleSpecifierAbs: string;\n}\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 */\nexport function ethisysPlatformReactPlugin(\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\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.\n * Idempotent — repeated invocations rebuild from a fresh manifest read.\n */\n function validate(): void {\n pages = [];\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n const declared = manifest.ui?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return;\n }\n\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 let isBuild = false;\n\n return {\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 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 },\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) {\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\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() {\n if (pages.length === 0) {\n return;\n }\n\n const summary = {\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 this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-pages.json`,\n source: JSON.stringify(summary, null, 2),\n });\n },\n };\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, 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.\nexport {\n ethisysPlatformReactPlugin,\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// ── 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"]}
|