From b8004c6383b62b8abc73eb69ebdd9b951f033598 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Mon, 23 Nov 2026 16:20:56 -0800 Subject: [PATCH 1/5] Checkpoint isolated browser WASM validator prototype Preserve the opt-in investigation for #536 before reviewing the shared refactor and expanding worker/browser coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- typescript/README.md | 5 + typescript/experimental/browser/README.md | 191 +++++ .../experimental/browser/package-lock.json | 710 ++++++++++++++++++ typescript/experimental/browser/package.json | 30 + .../experimental/browser/src/compiler.ts | 152 ++++ typescript/experimental/browser/src/index.ts | 7 + .../experimental/browser/src/project.ts | 53 ++ .../experimental/browser/src/versions.ts | 3 + .../browser/tests/browser/browser.test.mjs | 120 +++ .../browser/tests/browser/entry.mjs | 66 ++ .../tests/browser/version-mismatch.mjs | 21 + .../experimental/browser/tests/corpus.mjs | 213 ++++++ .../browser/tests/loader.test.mjs | 88 +++ .../browser/tests/native-preview.mjs | 31 + .../browser/tests/parity.test.mjs | 23 + .../experimental/browser/tests/types.ts | 9 + typescript/experimental/browser/tsconfig.json | 16 + typescript/src/model.ts | 95 +-- typescript/src/modelTypes.ts | 94 +++ typescript/src/ts/compiler.ts | 207 +++++ typescript/src/ts/validate.ts | 626 ++------------- typescript/src/ts/validation.ts | 388 ++++++++++ typescript/src/typechat.ts | 2 +- typescript/test/compiler.test.ts | 44 ++ 24 files changed, 2544 insertions(+), 650 deletions(-) create mode 100644 typescript/experimental/browser/README.md create mode 100644 typescript/experimental/browser/package-lock.json create mode 100644 typescript/experimental/browser/package.json create mode 100644 typescript/experimental/browser/src/compiler.ts create mode 100644 typescript/experimental/browser/src/index.ts create mode 100644 typescript/experimental/browser/src/project.ts create mode 100644 typescript/experimental/browser/src/versions.ts create mode 100644 typescript/experimental/browser/tests/browser/browser.test.mjs create mode 100644 typescript/experimental/browser/tests/browser/entry.mjs create mode 100644 typescript/experimental/browser/tests/browser/version-mismatch.mjs create mode 100644 typescript/experimental/browser/tests/corpus.mjs create mode 100644 typescript/experimental/browser/tests/loader.test.mjs create mode 100644 typescript/experimental/browser/tests/native-preview.mjs create mode 100644 typescript/experimental/browser/tests/parity.test.mjs create mode 100644 typescript/experimental/browser/tests/types.ts create mode 100644 typescript/experimental/browser/tsconfig.json create mode 100644 typescript/src/modelTypes.ts create mode 100644 typescript/src/ts/compiler.ts create mode 100644 typescript/src/ts/validation.ts create mode 100644 typescript/test/compiler.test.ts diff --git a/typescript/README.md b/typescript/README.md index 07d613ea..ceafa8da 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -92,6 +92,11 @@ The symbol's runtime value and canonical declaration are shared across the ESM a CommonJS builds, so validators remain type-compatible and schema preflight also runs when a validator and translator come from different module formats. +An isolated, private [browser/WASM validator prototype](./experimental/browser/README.md) +tracks [#536](https://github.com/microsoft/TypeChat/issues/536). It requires a separate +install and explicit opt-in; it is not a published or supported browser release. +The normal package and `typechat/ts` continue to use the native Node.js backend. + To see TypeChat in action, we recommend exploring the [TypeChat example projects](https://github.com/microsoft/TypeChat/tree/main/typescript/examples). You can try them on your local machine or in a GitHub Codespace. To learn more about TypeChat, visit the [documentation](https://microsoft.github.io/TypeChat) which includes more information on TypeChat and how to get started. diff --git a/typescript/experimental/browser/README.md b/typescript/experimental/browser/README.md new file mode 100644 index 00000000..db39b58d --- /dev/null +++ b/typescript/experimental/browser/README.md @@ -0,0 +1,191 @@ +# Experimental browser/WASM validator + +Private investigation for [#536](https://github.com/microsoft/TypeChat/issues/536), +under [#534](https://github.com/microsoft/TypeChat/issues/534). This is an isolated +prototype, **not a published package, supported browser release, or merge approval**. + +The normal TypeChat package keeps its existing entry points, dependency manifest, +and native TypeScript 7.0.2 backend. This package is deliberately outside its npm +workspaces and normal build/test commands. Installing TypeChat does not install +this experimental compiler or its WASM artifact. + +## Design and boundaries + +- The native and browser adapters share schema generation, enum normalization, + schema preflight, missing-property diagnostic expansion, and repair behavior. + Small, separately typed AST adapters handle the different upstream compiler + APIs; there are no casts between incompatible compiler versions. +- The browser entry point exports the translator, result helpers, model protocol + types, and an asynchronous compiler loader. Supply your own model implementation. + It does **not** export the Node HTTP/proxy client, interactive utilities, or + program-translation helpers. Nothing silently ignores a proxy configuration. +- Load/compile the WASM module once, then create independent validator instances. + There is no global mutable reactor, hidden model call, inference fallback, + automatic download retry, or silent choice of a different backend. +- This uses matching `typescript` and `@typescript/typescript-wasip1-wasm` packages + at **7.1.0-dev.20261030.1**. The loader checks the JavaScript compiler version, + artifact length, and SHA-256 before compiling any WASM bytes. Relabeling an + incompatible artifact is not sufficient to pass these checks. + +A separate entry point/asynchronous factory is preferable to making the existing +synchronous Node factory browser-aware: it keeps experimental dependencies, +asynchronous initialization, and browser support claims opt-in. The internal +compiler contract is not a new supported public compiler-injection API. + +## Build and test + +Use the Node.js version in [`.nvmrc`](../../../.nvmrc). From the repository root: + +```sh +cd typescript +npm ci +npm run build-all +npm test + +cd experimental +cd browser +npm ci --ignore-scripts +npm test +npx playwright install chromium --only-shell +npm run test:browser +``` + +`npm test` in this directory type-checks the prototype and runs loader/lifecycle +tests plus a shared validation corpus against three backends: the default native +7.0.2 compiler, the matching development native compiler, and WASM. The two +same-version backends must match diagnostics as well as acceptance outcomes. + +`npm run test:browser` bundles the actual private-package exports with **no Node +polyfills or externalized dependencies**, then runs Chromium against a temporary +loopback server. It verifies validation, repair, schema preflight, stalled-download +cancellation, and compiler-version rejection before fetching. It closes the +browser and server, including outstanding connections. No model credentials, +remote model calls, deployment, or paid inference are needed. + +The ordinary TypeChat tests do not install or invoke Playwright. On supported +Linux hosts, Playwright may additionally require its documented system libraries. + +## Provisional API + +Serve the exact installed +`node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm` from an +application-owned static asset URL, preferably with `application/wasm` and HTTP +compression. Do not use a mutable CDN `latest` URL. Asset copying and deployment +remain application responsibilities. + +For code built within this private package, or an application that explicitly +links its built output: + +```ts +import { + createJsonTranslator, + loadBrowserTypeScriptCompiler, + success +} from "@typechat/experimental-browser"; + +interface Request { value: number; } + +const compiler = await loadBrowserTypeScriptCompiler( + "/assets/typescript-7.1.0-dev.20261030.1.wasm", + { signal: AbortSignal.timeout(60_000) } +); +const validator = await compiler.createValidator( + "export interface Request { value: number; }", + "Request" +); +try { + // Intentional offline test model, not an inference fallback. + const model = { complete: async () => success('{"value":1}') }; + const translator = createJsonTranslator(model, validator); + const result = await translator.translate("Return one."); + if (!result.success) { + throw new Error(result.message); + } + console.log(result.data.value); +} finally { + validator.close(); +} +``` + +The compiler handle can create multiple validators without refetching or +recompiling the module. Each validator has independent files, snapshots, and WASM +memory. `close()` is idempotent and releases the owned compiler references. +Validation and schema preflight after closing throw an explicit error. Dropping +the compiler handle allows its compiled module to be garbage-collected; actual +garbage-collection timing remains runtime-owned. + +Network, HTTP, cancellation, length, integrity, and compiler initialization +failures reject the loader/factory promise. Schema/instance failures retain +TypeChat's `Result` behavior and rejected data. Web Crypto requires HTTPS or a +secure local context. Browser CSP must allow the application's WASM compilation. + +Loading and instance creation are asynchronous, but **validation is synchronous +on the calling thread**. A worker-based application integration needs separate +evaluation; this prototype does not hide synchronous work behind an async name. + +## Recorded verification + +On Windows, Node.js 24.22.1 and Chromium 149.0.7827.55: + +- The normal library/examples built, and all **411** normal tests passed, + including CJS/ESM package/declaration tests and the existing enum regressions. +- **58** corpus outcomes passed in the real browser and matched the default + native backend. WASM and the matching development native backend also produced + identical diagnostics. +- HTTP/network errors, pre-aborted loads, absent/truncated/oversized/corrupt + artifacts, concurrent validator isolation, and idempotent disposal passed. +- Real-browser tests ran with no Node globals, no proxy dependency, no live + model calls, and `crossOriginIsolated === false`. + +One clean-install development-host run measured: + +| Measurement | Observed | +| --- | ---: | +| Minified library JavaScript, without the test corpus | 441,030 bytes | +| Gzipped library JavaScript | 93,789 bytes | +| WASM artifact | 52,616,552 bytes | +| Gzipped WASM artifact | 13,359,431 bytes | +| Loopback fetch, integrity check, and module compilation | 184 ms | +| Instance initialization with an already compiled module | 19-20 ms | +| 100 validations of a 100-property schema | 416 ms total | +| That validator's WASM linear memory, before/after the loop | 30,408,704 / 33,816,576 bytes | + +These are observations, not production latency guarantees. The timing does not +represent a WAN download or low-memory device. `getWasmMemoryByteLength()` measures +only owned WASM linear memory, not JavaScript, compiled code, download buffers, +peak process memory, or immediate garbage collection after closing. + +The browser test enforces **provisional investigation ceilings**, for review: +512 KiB minified / 128 KiB gzipped JavaScript; 60 MiB raw / 16 MiB gzipped WASM; +128 MiB of linear memory for the single 100-property test validator after its +100 validations. Agree target-device startup and responsiveness budgets before +shipping; wall-clock performance is measured rather than asserted on arbitrary +CI hardware. + +Only the browser/OS combination above was exercised. This is not a complete +compatibility certification for every schema, browser, worker, CSP, or edge +runtime. The full existing native suite is not yet a full browser matrix. + +## Upgrade, rollback, and recommendation + +The upstream WASM implementation is experimental: +[microsoft/TypeScript#64174](https://github.com/microsoft/TypeScript/pull/64174). +A newer published compiler version alone does not establish a stable WASM API. + +For an evaluated upgrade, change both exact package versions together, review +the upstream API/transport changes, and update the reviewed artifact length/hash +in [`src/versions.ts`](./src/versions.ts). Keep the lockfile's public registry +URLs and integrity data. Rerun native package tests, same-version compiler parity, +real-browser tests, and cost measurements. Never suppress validation failures or +disable artifact verification merely to accept an upgrade. + +Rollback is to stop opting into this package and its assets. The ordinary Node +backend remains available and does not require the experimental dependencies. +Keep the prototype out of the default workspace/build until reviewed explicitly. + +**Recommendation: continue the isolated investigation; do not merge this as +supported browser functionality yet.** Mainline gates remain an explicit +upstream-stability/maintenance decision, review of the provisional API and costs, +broader browser/OS/worker coverage, and a full regression/compatibility assessment. +The existing root-package Node-proxy bundling problem remains separate; this +package does not fix that public entry point or automatically resolve #534. diff --git a/typescript/experimental/browser/package-lock.json b/typescript/experimental/browser/package-lock.json new file mode 100644 index 00000000..2e5a774f --- /dev/null +++ b/typescript/experimental/browser/package-lock.json @@ -0,0 +1,710 @@ +{ + "name": "@typechat/experimental-browser", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@typechat/experimental-browser", + "version": "0.0.0", + "dependencies": { + "@typescript/typescript-wasip1-wasm": "7.1.0-dev.20261030.1", + "typescript": "7.1.0-dev.20261030.1" + }, + "devDependencies": { + "@types/node": "^26.2.0", + "esbuild": "0.28.2", + "playwright": "1.61.0" + }, + "engines": { + "node": ">=24.22.1" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha1-v24QMDvPLnxoaXX6Uvk37Cco2Lw=", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha1-LYTs5qTiaE2SvibuE9QnV9gxw4E=", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha1-DGJGvI0sTRcqrC2z+xGQ1yvWVQQ=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha1-/DjU1jWNjcHPU/CfdYn+Q262SAE=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha1-+Dr+6sHX2sAcei/QErPkUaBZH8w=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha1-UQFHwFWnlViNu+FP1rG4rQovMN4=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha1-CTuSAOzwsRW6Tl4kinSFycX4vV4=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha1-C+Irbfkl0hPoQeqHEjr134Cw+vc=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha1-vrEq1yuE9y0oSIzBuO6ffrFB11M=", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha1-G9vGUc2pupmVxT7ZxxzqplCUdi0=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha1-uB+dVVKbRcIGpGoTghSxqmh5aWs=", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha1-WYZnJBoEyZt27W75QKxQA4xBn5g=", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha1-HFHrnOqQP1PZe1rzsYQdtw9Vlso=", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha1-Y91h8XzrMagSJ/QT/qyKcbwsUfI=", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha1-N2Owj95c8lqx+suOd1Lt/kX7/Cc=", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha1-GhN/8pOoKQbrMXY4W9fo4OXPt8s=", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha1-Jos2IRwUbKVPj+EsV4qNbviXlIU=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha1-Ilca2VHWK7aszILY0frVyMGsC6E=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha1-QvzFcpfrCgyj9fxHUpH0waP3wN4=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha1-nrMq8QSsPaz07coB9ZZmSqsMc+8=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha1-/r7SQC1giCJekfIPtM4lIq0KTv0=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha1-hWQcPUZkKL+8zqXyHCaDZmP+9c4=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha1-pzb52JYkgQRfxMPlT1R58iyHD7Q=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha1-7lq0D60YYgG2UqM/il6xSenkJTI=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha1-xA0optmaEn2mcR8q/XSxHLY7Bqc=", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha1-shr/uATMFnwTPZX0WzodwTI7moc=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-rTW2PpYEphzAsy9OHOe2eupDS6AM8tHdrEk0MxW9y6O+uLFOZ2lUB5vVZhtKvTnpw//bN1yjeg+WZ++TUGR3bg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-6zrxK36LQW8hFQsjRXgqA6fbmN54NCTmNpdKEwVULLPm22x8mK99Vh7RbXhXpp4pwatHpSPysY1fvxcEsMNIgQ==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-Upd1yowmHih4aaEdCckNeSEAIoqRh65QZAUd4d+cEB0HD/mG4mUL8LJIbOKtbwto4mRDxs7O5CRdYfdqfdKZVw==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-id+Un0JOtIKn6RZ/deoyu4S9qR1w3f0omWSp5CapfyB7OXqB7dGLhFf3cvYDmpqnKp+BQD04oF6pyb6eEM0DDQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-i9s3tj9tp9e7F6VHiuh9s0RAiqQl5fCieizVLeynxkmRh0FK0Kg8Pco6LRzFEUSzU3gCHx9q44n1bexkpQrI0A==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-wasip1-wasm": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-wasip1-wasm/-/typescript-wasip1-wasm-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-m3WKNe9Wa0EsTOJXpf1t55hB7TzArcfuiygFi5MgD6EL5xB3eUTN9xNRklv/m0yyXSoVmpqdYNgujjgroCPlNA==", + "license": "Apache-2.0" + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-K2vICZV6aztU0NJVgc0DAvmJMqtnrA3ej5bVmRXWnjVYVKJ5mVdTAGcJQHWlNhzMxZFWD8Fv1b4ZGA3GrLaXaA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-lOtLps7lORzpCJ5ynge0aA9O1XMdSep/Ga03qtcVzLVUwvkCpwbBkpC4oX71gTOFQ2Gqjqd6mQIfu6vGxBotwA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha1-D0O9G62VW3LSTiJh46vllXzPCBY=", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha1-ilJveLj99GI7cJ4Ll1xSwkwC/Ro=", + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.0.tgz", + "integrity": "sha1-cILfPfCP+oKxFCDqX66EpAvRbj8=", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.0.tgz", + "integrity": "sha1-yvgHiyo5zXc43HXsEcs7R/OFw/A=", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/typescript": { + "version": "7.1.0-dev.20261030.1", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.1.0-dev.20261030.1.tgz", + "integrity": "sha512-y5prFqSwq0qTd/oL+E/fKsGbigIn6CJ6sVTbg8HK70GTO7wo3BAhZdkrrtUgmNn3C93xUWwDp2nXqScbbQ5bhQ==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-darwin-arm64": "7.1.0-dev.20261030.1", + "@typescript/typescript-darwin-x64": "7.1.0-dev.20261030.1", + "@typescript/typescript-linux-arm": "7.1.0-dev.20261030.1", + "@typescript/typescript-linux-arm64": "7.1.0-dev.20261030.1", + "@typescript/typescript-linux-x64": "7.1.0-dev.20261030.1", + "@typescript/typescript-win32-arm64": "7.1.0-dev.20261030.1", + "@typescript/typescript-win32-x64": "7.1.0-dev.20261030.1" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha1-4kDZfItdheU0fOc9JYZceQbB7J8=", + "dev": true, + "license": "MIT" + } + } +} diff --git a/typescript/experimental/browser/package.json b/typescript/experimental/browser/package.json new file mode 100644 index 00000000..280890a2 --- /dev/null +++ b/typescript/experimental/browser/package.json @@ -0,0 +1,30 @@ +{ + "name": "@typechat/experimental-browser", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Isolated browser/WASM validator investigation for TypeChat issue #536.", + "exports": { + ".": { + "types": "./dist/experimental/browser/src/index.d.ts", + "default": "./dist/experimental/browser/src/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "test": "npm run build && node --test \"tests/*.test.mjs\"", + "test:browser": "npm run build && node --test \"tests/browser/*.test.mjs\"" + }, + "engines": { + "node": ">=24.22.1" + }, + "dependencies": { + "@typescript/typescript-wasip1-wasm": "7.1.0-dev.20261030.1", + "typescript": "7.1.0-dev.20261030.1" + }, + "devDependencies": { + "@types/node": "^26.2.0", + "esbuild": "0.28.2", + "playwright": "1.61.0" + } +} diff --git a/typescript/experimental/browser/src/compiler.ts b/typescript/experimental/browser/src/compiler.ts new file mode 100644 index 00000000..599e1c0c --- /dev/null +++ b/typescript/experimental/browser/src/compiler.ts @@ -0,0 +1,152 @@ +import { version } from "typescript"; +import { API, type Snapshot } from "typescript/sync"; +import { instantiateWasm, WasmTransport } from "typescript/wasm"; +import { + configFileName, createCompiler, jsonFileName, schemaFileName, schemaValidationFileName +} from "../../../src/ts/compiler.js"; +import { + createTypeScriptJsonValidatorWithCompiler, type TypeScriptJsonValidatorWithSchemaValidation +} from "../../../src/ts/validation.js"; +import { projectView } from "./project.js"; +import { compilerVersion, wasmByteLength, wasmSha256 } from "./versions.js"; + +export { compilerVersion } from "./versions.js"; + +export interface BrowserTypeScriptValidator extends TypeScriptJsonValidatorWithSchemaValidation { + /** Owned WASM linear-memory bytes, excluding JavaScript allocations; zero after close. */ + getWasmMemoryByteLength(): number; +} + +export interface BrowserTypeScriptCompiler { + readonly version: string; + /** Creates an independent compiler instance. Close the returned validator when finished. */ + createValidator( + schema: string, + typeName: string, + schemaValidationTypeName?: string + ): Promise>; +} + +/** + * Loads and verifies the exact experimental compiler artifact, then compiles it once for reuse. + * Network, integrity, cancellation, and initialization failures reject; there is no fallback. + */ +export async function loadBrowserTypeScriptCompiler( + wasmUrl: string | URL, + options: { signal?: AbortSignal } = {} +): Promise { + if (version !== compilerVersion) { + throw new Error(`Expected TypeScript ${compilerVersion}, but loaded ${version}.`); + } + if (!globalThis.crypto?.subtle) { + throw new Error("WASM integrity verification requires Web Crypto in a secure context."); + } + options.signal?.throwIfAborted(); + const response = await fetch(wasmUrl, options.signal ? { signal: options.signal } : {}); + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`Unable to load the TypeScript WASM compiler: HTTP ${response.status}.`); + } + if (!response.body) { + throw new Error("The TypeScript WASM compiler response has no body."); + } + const reader = response.body.getReader(); + const bytes = new Uint8Array(wasmByteLength); + let offset = 0; + try { + while (true) { + const { value, done } = await reader.read(); + if (done) { + break; + } + if (offset + value.byteLength > bytes.byteLength) { + await reader.cancel(); + throw new Error(`The WASM artifact exceeds the expected ${wasmByteLength} bytes.`); + } + bytes.set(value, offset); + offset += value.byteLength; + } + } finally { + reader.releaseLock(); + } + if (offset !== bytes.byteLength) { + throw new Error(`Expected ${wasmByteLength} WASM bytes, but received ${offset}.`); + } + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + const actualHash = [...digest].map(value => value.toString(16).padStart(2, "0")).join(""); + if (actualHash !== wasmSha256) { + throw new Error(`The WASM artifact does not match TypeScript ${compilerVersion} (SHA-256 mismatch).`); + } + options.signal?.throwIfAborted(); + const module = await WebAssembly.compile(bytes); + options.signal?.throwIfAborted(); + return { + version: compilerVersion, + async createValidator(schema: string, typeName: string, schemaValidationTypeName = typeName) { + const instance = await instantiateWasm(module); + if (!("memory" in instance.exports) || !(instance.exports.memory instanceof WebAssembly.Memory)) { + throw new Error("The TypeScript WASM reactor did not export its memory."); + } + let memory: WebAssembly.Memory | undefined = instance.exports.memory; + let transport: WasmTransport | undefined; + let api: API | undefined; + let snapshot: Snapshot | undefined; + const close = () => { + const currentApi = api; + const currentTransport = transport; + api = undefined; + transport = undefined; + snapshot = undefined; + memory = undefined; + if (currentApi) { + currentApi.close(); + } else { + currentTransport?.close(); + } + }; + try { + transport = new WasmTransport({ instance, cwd: "/" }); + api = new API({ transport }); + const validator = createTypeScriptJsonValidatorWithCompiler( + schema, typeName, schemaValidationTypeName, + files => { + if (!transport) { + throw new Error("The TypeScript WASM transport has been closed."); + } + for (const [name, text] of Object.entries(files)) { + transport.setFile(name, text); + } + return createCompiler({ + writeFile(name, text) { + if (!transport) { + throw new Error("The TypeScript WASM transport has been closed."); + } + transport.setFile(name, text); + }, + update(changedFiles) { + if (!api) { + throw new Error("The TypeScript WASM API has been closed."); + } + const next = api.createSnapshot({ + openFiles: [schemaFileName, jsonFileName, schemaValidationFileName], + fileNotifications: { changed: [...changedFiles], deleted: [] } + }); + snapshot?.dispose(); + snapshot = next; + const project = next.getConfiguredProject(configFileName); + return project && projectView(project); + }, + close + }); + } + ); + return Object.assign(validator, { + getWasmMemoryByteLength: () => memory?.buffer.byteLength ?? 0 + }); + } catch (cause) { + close(); + throw cause; + } + } + }; +} diff --git a/typescript/experimental/browser/src/index.ts b/typescript/experimental/browser/src/index.ts new file mode 100644 index 00000000..a81b6a35 --- /dev/null +++ b/typescript/experimental/browser/src/index.ts @@ -0,0 +1,7 @@ +export * from "./compiler.js"; +export { + createJsonTranslator, typeChatSchemaValidation, + type TypeChatJsonTranslator, type TypeChatJsonValidator +} from "../../../src/typechat.js"; +export { error, success, type Result } from "../../../src/result.js"; +export type { TypeChatLanguageModel, PromptSection, PromptContent } from "../../../src/modelTypes.js"; diff --git a/typescript/experimental/browser/src/project.ts b/typescript/experimental/browser/src/project.ts new file mode 100644 index 00000000..645cb152 --- /dev/null +++ b/typescript/experimental/browser/src/project.ts @@ -0,0 +1,53 @@ +import { SymbolFlags, TypeFormatFlags, type Project, type Type } from "typescript/sync"; +import type { EnumMember, Node } from "typescript/ast"; +import { isEnumDeclaration, isTypeReferenceNode, isVariableStatement } from "typescript/ast/is"; +import { + collectStringEnumValues, describeAssignment, jsonFileName, schemaFileName, + type CompilerAssignment, type CompilerProject, type CompilerTypeDescription +} from "../../../src/ts/compiler.js"; + +export function projectView({ program, checker }: Project): CompilerProject { + function describeType(type: Type): CompilerTypeDescription { + return { + text: checker.typeToString(type, undefined, TypeFormatFlags.NoTruncation), + properties: checker.getPropertiesOfType(type).map(property => ({ + name: property.name, + optional: !!(property.flags & SymbolFlags.Optional) + })) + }; + } + return { + getSourceFile: name => program.getSourceFile(name), + getSyntacticDiagnostics: name => program.getSyntacticDiagnostics(name), + getSemanticDiagnostics: name => program.getSemanticDiagnostics(name), + getStringEnumValues() { + const source = program.getSourceFile(schemaFileName); + return source ? collectStringEnumValues( + source, + (node, visit) => node.forEachChild(visit), + node => isEnumDeclaration(node) ? node.members : [], + member => checker.getConstantValue(member) + ) : []; + }, + getAssignments() { + const file = program.getSourceFile(jsonFileName); + const assignments: CompilerAssignment[] = []; + for (const statement of file?.statements ?? []) { + if (!isVariableStatement(statement)) { + continue; + } + for (const declaration of statement.declarationList.declarations) { + const { type, initializer } = declaration; + if (type && isTypeReferenceNode(type) && initializer && file) { + assignments.push(describeAssignment( + declaration.getStart(file), type.getEnd(), type.typeName.getText(file), + type, type.typeArguments?.[0], initializer, + node => checker.getTypeAtLocation(node), describeType + )); + } + } + } + return assignments; + } + }; +} diff --git a/typescript/experimental/browser/src/versions.ts b/typescript/experimental/browser/src/versions.ts new file mode 100644 index 00000000..15becfe3 --- /dev/null +++ b/typescript/experimental/browser/src/versions.ts @@ -0,0 +1,3 @@ +export const compilerVersion = "7.1.0-dev.20261030.1"; +export const wasmByteLength = 52616552; +export const wasmSha256 = "814ceba41745ee6e4f94c5311513c4388dd8830179c018233bcedd14682329ee"; diff --git a/typescript/experimental/browser/tests/browser/browser.test.mjs b/typescript/experimental/browser/tests/browser/browser.test.mjs new file mode 100644 index 00000000..0f862730 --- /dev/null +++ b/typescript/experimental/browser/tests/browser/browser.test.mjs @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { gzipSync } from "node:zlib"; +import { build } from "esbuild"; +import { chromium } from "playwright"; + +test("the public prototype runs real browser validation without Node shims or live models", { timeout: 180000 }, async t => { + const settings = { + bundle: true, + platform: "browser", + format: "iife", + target: "es2021", + minify: true, + write: false, + metafile: true, + logLevel: "silent" + }; + const bundle = await build({ + ...settings, + entryPoints: [fileURLToPath(new URL("./entry.mjs", import.meta.url))] + }); + const library = await build({ + ...settings, + format: "esm", + entryPoints: [fileURLToPath(new URL("../../dist/experimental/browser/src/index.js", import.meta.url))] + }); + assert.ok(!Object.keys(bundle.metafile.inputs).some(path => /(?:^|\/)(?:undici|model\.js)(?:\/|$)/.test(path))); + assert.ok(Object.values(bundle.metafile.outputs).every(output => output.imports.length === 0)); + assert.ok(Object.values(library.metafile.outputs).every(output => output.imports.length === 0)); + const mismatch = await build({ + ...settings, + entryPoints: [fileURLToPath(new URL("./version-mismatch.mjs", import.meta.url))], + plugins: [{ + name: "test-compiler-version-mismatch", + setup(builder) { + builder.onResolve({ filter: /^typescript$/ }, () => ({ path: "version", namespace: "mismatch" })); + builder.onLoad({ filter: /.*/, namespace: "mismatch" }, () => ({ + contents: 'export const version = "0.0.0";', + loader: "js" + })); + } + }] + }); + const wasm = await readFile(new URL("../../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url)); + let wasmRequests = 0; + const assets = new Map([ + ["/", ["text/html", '']], + ["/mismatch", ["text/html", '']], + ["/probe.js", ["text/javascript", bundle.outputFiles[0].contents]], + ["/mismatch.js", ["text/javascript", mismatch.outputFiles[0].contents]], + ["/tsc.wasm", ["application/wasm", wasm]] + ]); + const server = createServer((request, response) => { + if (request.url === "/slow.wasm") { + response.writeHead(200, { "Content-Type": "application/wasm" }); + response.write(wasm.subarray(0, 100)); + return; + } + const asset = assets.get(request.url); + if (!asset) { + response.writeHead(404); + response.end(); + return; + } + if (request.url === "/tsc.wasm") { + wasmRequests++; + } + response.writeHead(200, { "Content-Type": asset[0], "Cache-Control": "no-store" }); + response.end(asset[1]); + }); + let browser; + t.after(async () => { + await browser?.close(); + server.closeAllConnections(); + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const address = server.address(); + assert.ok(address && typeof address !== "string"); + browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.goto(`http://127.0.0.1:${address.port}`); + const result = await page.evaluate(() => globalThis.runBrowserProbe()); + assert.equal(result.nodeGlobalsAbsent, true); + assert.equal(result.liveModelCalls, 0); + assert.equal(result.stalledLoadTimedOut, true); + assert.equal(wasmRequests, 1, "Validators should reuse the compiled module rather than refetching WASM."); + assert.deepEqual(errors, []); + await page.goto(`http://127.0.0.1:${address.port}/mismatch`); + assert.deepEqual(await page.evaluate(() => globalThis.runMismatchProbe()), { rejected: true, fetchCalls: 0 }); + const metrics = { + browser: `Chromium ${browser.version()}`, + platform: process.platform, + compiler: result.compiler, + corpusOutcomes: result.observations.length, + libraryJavascriptBytes: library.outputFiles[0].contents.length, + libraryJavascriptGzipBytes: gzipSync(library.outputFiles[0].contents).length, + testBundleBytes: bundle.outputFiles[0].contents.length, + wasmBytes: wasm.length, + wasmGzipBytes: gzipSync(wasm).length, + loadCompileMs: Math.round(result.loadCompileMs), + warmInitializationMs: result.warmInitializationMs.map(Math.round), + crossOriginIsolated: result.crossOriginIsolated, + largeSchema: result.largeSchema + }; + assert.ok(metrics.libraryJavascriptBytes <= 512 * 1024, "Prototype JavaScript exceeded 512 KiB."); + assert.ok(metrics.libraryJavascriptGzipBytes <= 128 * 1024, "Compressed prototype JavaScript exceeded 128 KiB."); + assert.ok(metrics.wasmBytes <= 60 * 1024 * 1024, "Prototype WASM exceeded 60 MiB."); + assert.ok(metrics.wasmGzipBytes <= 16 * 1024 * 1024, "Compressed prototype WASM exceeded 16 MiB."); + assert.ok(metrics.largeSchema.finalLinearMemoryBytes <= 128 * 1024 * 1024, "One validator exceeded 128 MiB of linear memory."); + t.diagnostic(JSON.stringify(metrics)); +}); diff --git a/typescript/experimental/browser/tests/browser/entry.mjs b/typescript/experimental/browser/tests/browser/entry.mjs new file mode 100644 index 00000000..221c8f27 --- /dev/null +++ b/typescript/experimental/browser/tests/browser/entry.mjs @@ -0,0 +1,66 @@ +import * as core from "@typechat/experimental-browser"; +import { runCorpus } from "../corpus.mjs"; + +globalThis.runBrowserProbe = async () => { + if (typeof globalThis.process !== "undefined" || typeof globalThis.require !== "undefined") { + throw new Error("The browser test must run without Node globals."); + } + const start = performance.now(); + const compiler = await core.loadBrowserTypeScriptCompiler("/tsc.wasm", { signal: AbortSignal.timeout(60000) }); + const loadCompileMs = performance.now() - start; + const observations = await runCorpus((...args) => compiler.createValidator(...args), core); + const initialization = []; + for (let index = 0; index < 3; index++) { + const before = performance.now(); + const validator = await compiler.createValidator("export interface Probe { value: number }", "Probe"); + initialization.push(performance.now() - before); + validator.close(); + if (validator.getWasmMemoryByteLength() !== 0) { + throw new Error("A closed validator still owns its WASM memory."); + } + } + const schema = "export interface Probe {\n" + + Array.from({ length: 100 }, (_, index) => `field${index}: number;`).join("\n") + "\n}"; + const value = Object.fromEntries(Array.from({ length: 100 }, (_, index) => [`field${index}`, index])); + const validator = await compiler.createValidator(schema, "Probe"); + let largeSchema; + try { + const initialMemory = validator.getWasmMemoryByteLength(); + const started = performance.now(); + for (let index = 0; index < 100; index++) { + if (!validator.validate(value).success) { + throw new Error("The representative 100-property schema did not validate."); + } + } + largeSchema = { + properties: 100, + validations: 100, + totalValidationMs: performance.now() - started, + initialLinearMemoryBytes: initialMemory, + finalLinearMemoryBytes: validator.getWasmMemoryByteLength() + }; + } finally { + validator.close(); + } + const signal = AbortSignal.timeout(75); + let timeout; + try { + await core.loadBrowserTypeScriptCompiler("/slow.wasm", { signal }); + } catch (error) { + timeout = error.name; + } + if (!signal.aborted || (timeout !== "TimeoutError" && timeout !== "AbortError")) { + throw new Error(`Loading a stalled response did not time out: ${timeout}`); + } + return { + compiler: compiler.version, + observations, + nodeGlobalsAbsent: true, + crossOriginIsolated: globalThis.crossOriginIsolated, + liveModelCalls: 0, + loadCompileMs, + warmInitializationMs: initialization, + largeSchema, + stalledLoadTimedOut: true + }; +}; diff --git a/typescript/experimental/browser/tests/browser/version-mismatch.mjs b/typescript/experimental/browser/tests/browser/version-mismatch.mjs new file mode 100644 index 00000000..ea487644 --- /dev/null +++ b/typescript/experimental/browser/tests/browser/version-mismatch.mjs @@ -0,0 +1,21 @@ +import { loadBrowserTypeScriptCompiler } from "@typechat/experimental-browser"; + +globalThis.runMismatchProbe = async () => { + let calls = 0; + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => { + calls++; + throw new Error("A compiler version mismatch must not fetch WASM."); + }; + try { + await loadBrowserTypeScriptCompiler("/tsc.wasm"); + throw new Error("A mismatched compiler was accepted."); + } catch (error) { + if (!/Expected TypeScript .*but loaded 0\.0\.0/.test(error.message) || calls !== 0) { + throw error; + } + return { rejected: true, fetchCalls: calls }; + } finally { + globalThis.fetch = originalFetch; + } +}; diff --git a/typescript/experimental/browser/tests/corpus.mjs b/typescript/experimental/browser/tests/corpus.mjs new file mode 100644 index 00000000..4e93d7e9 --- /dev/null +++ b/typescript/experimental/browser/tests/corpus.mjs @@ -0,0 +1,213 @@ +export const corpus = [ + { + name: "ordinary JSON", + schema: "export interface Probe { value: number; label?: string; }", + accepted: [{ value: 1 }, { value: 0, label: "zero" }], + rejected: [{}, { value: "1" }, { value: 1, extra: true }, { value: null }] + }, + { + name: "string enum", + schema: 'export enum Currency { Euro = "EUR", Dollar = "USD" } export interface Probe { value: Currency; }', + accepted: [{ value: "EUR" }, { value: "USD" }], + rejected: [{ value: "Euro" }, { value: "unknown" }, { value: 1 }] + }, + { + name: "enum member", + schema: 'export enum Currency { Euro = "EUR", Dollar = "USD" } export interface Probe { value: Currency.Euro; }', + accepted: [{ value: "EUR" }], + rejected: [{ value: "USD" }] + }, + { + name: "constant-folded string enum", + schema: 'export enum Name { A = "A", AB = A + "B" } export interface Probe { value: Name; }', + accepted: [{ value: "AB" }], + rejected: [{ value: "B" }] + }, + { + name: "numeric enums", + schema: "export enum Level { Low, High } export interface Probe { value: Level; }", + accepted: [{ value: 0 }, { value: 1 }], + rejected: [{ value: 3 }, { value: "Low" }] + }, + { + name: "nested collections and unions", + schema: ` +export enum Status { Active = "active", Paused = "paused" } +export interface Item { status: Status } +export interface Probe { + items: Item[]; + lookup: Record; + result: { ok: true; value: Status } | { ok: false; message: string }; +}`, + accepted: [{ items: [{ status: "active" }], lookup: { a: "paused" }, result: { ok: true, value: "active" } }], + rejected: [ + { items: [{ status: "bad" }], lookup: {}, result: { ok: false, message: "x" } }, + { items: [], lookup: { a: "bad" }, result: { ok: false, message: "x" } }, + { items: [], lookup: {}, result: { ok: true, value: "bad" } } + ] + }, + { + name: "recursive tuples and optional enums", + schema: 'export enum E { A = "a" } export interface Probe { pair: [E, number]; next?: Probe; optional?: E; }', + accepted: [{ pair: ["a", 1], next: { pair: ["a", 2] } }], + rejected: [{ pair: ["a"] }, { pair: ["a", "1"] }, { pair: ["a", 1], optional: "bad" }] + }, + { + name: "branded strings remain constrained", + schema: 'export enum E { A = "a" } type Brand = string & { readonly brand: unique symbol }; export interface Probe { value: Brand; enumValue: E; }', + accepted: [], + rejected: [{ value: "a", enumValue: "a" }] + }, + { + name: "call signatures remain constrained", + schema: 'export enum E { A = "a" } export interface Probe { value: () => E; }', + accepted: [], + rejected: [{ value: {} }] + }, + { + name: "construct signatures remain constrained", + schema: 'export enum E { A = "a" } export interface Probe { value: new () => { e: E }; }', + accepted: [], + rejected: [{ value: {} }] + }, + { + name: "private class members remain constrained", + schema: 'export enum E { A = "a" } export class C { private value!: E; } export interface Probe { item: C; }', + accepted: [], + rejected: [{ item: {} }, { item: { value: "a" } }] + }, + { + name: "Promise-like values remain constrained", + schema: 'export enum E { A = "a" } export interface Probe { value: PromiseLike; }', + accepted: [], + rejected: [{ value: { then: {} } }] + }, + { + name: "weak object types", + schema: 'export enum E { A = "a" } export interface Probe { value: { e?: E }; }', + accepted: [{ value: {} }, { value: { e: "a" } }], + rejected: [{ value: 1 }, { value: { extra: true } }] + }, + { + name: "explicit object intersections", + schema: 'export enum E { A = "a" } export interface Probe { value: { e?: E } & object; }', + accepted: [{ value: {} }, { value: [] }], + rejected: [{ value: 1 }, { value: "a" }] + }, + { + name: "full missing-property diagnostics", + schema: 'export enum E { A = "a" } export interface Probe { a: E; b: string; c: string; d: string; e: string; f: string; g: string; h: string; }', + accepted: [{ a: "a", b: "", c: "", d: "", e: "", f: "", g: "", h: "" }], + rejected: [{}], + diagnostic: /b, c, d, e, f, g, h/, + noDiagnostic: /and \d+ more|__TypeChatJsonWire/ + } +]; + +export const invalidSchemas = [ + { name: "missing target", schema: "export interface Other { value: number; }" }, + { name: "missing export", schema: "interface Probe { value: number; } export {};" }, + { name: "unknown type", schema: "export interface Probe { value: MissingType; }" }, + { name: "unsupported runtime type", schema: "export interface Probe { value: Date; }" }, + { name: "syntax error", schema: "export interface Probe { value: ; }" } +]; + +function check(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +export async function runCorpus(createValidator, { createJsonTranslator, success, typeChatSchemaValidation }) { + const observations = []; + for (const group of corpus) { + const validator = await createValidator(group.schema, "Probe"); + try { + const preflight = validator[typeChatSchemaValidation](); + check(preflight.success, `${group.name}: schema rejected: ${preflight.message}`); + check(validator.getSchemaText() === group.schema, "Prompt schema was changed."); + for (const [expected, values] of [[true, group.accepted], [false, group.rejected]]) { + for (const value of values) { + const result = validator.validate(value); + check(result.success === expected, `${group.name}: incorrect result for ${JSON.stringify(value)}: ${result.message}`); + if (result.success) { + check(result.data === value, `${group.name}: validation replaced the JSON object.`); + } else { + check(result.data === value, `${group.name}: rejected candidate was not retained.`); + check(result.message.length > 0, `${group.name}: missing diagnostic.`); + check(!group.diagnostic || group.diagnostic.test(result.message), `${group.name}: incomplete diagnostic: ${result.message}`); + check(!group.noDiagnostic || !group.noDiagnostic.test(result.message), `${group.name}: leaked/truncated diagnostic.`); + } + observations.push({ name: group.name, success: result.success, message: result.message ?? "" }); + } + } + } finally { + validator.close(); + } + } + for (const invalid of invalidSchemas) { + for (const attemptRepair of [false, true]) { + const validator = await createValidator(invalid.schema, "Probe"); + let calls = 0; + try { + const translator = createJsonTranslator({ + async complete() { + calls++; + throw new Error("An invalid schema must not call the model."); + } + }, validator); + translator.attemptRepair = attemptRepair; + const result = await translator.translate("Return a value."); + check(!result.success && calls === 0, `${invalid.name}: invalid schema reached the model.`); + check(result.message.includes("Schema validation failed"), `${invalid.name}: missing schema diagnostic.`); + observations.push({ name: `${invalid.name}/${attemptRepair}`, success: false, message: result.message }); + } finally { + validator.close(); + } + } + } + const translationCases = [ + { name: "valid translation", responses: ['{"value":1}'], repair: false, success: true }, + { name: "repair disabled", responses: ['{"value":"wrong"}'], repair: false, success: false }, + { name: "malformed JSON", responses: ['{"value":'], repair: false, success: false }, + { name: "successful repair", responses: ['{"value":"wrong"}', '{"value":1}'], repair: true, success: true }, + { name: "exhausted repair", responses: ['{"value":"wrong"}', '{"value":"still wrong"}'], repair: true, success: false } + ]; + const validator = await createValidator(corpus[0].schema, "Probe"); + try { + for (const example of translationCases) { + let calls = 0; + const translator = createJsonTranslator({ + async complete() { + check(calls < example.responses.length, "Unexpected repair call."); + return success(example.responses[calls++]); + } + }, validator); + translator.attemptRepair = example.repair; + const result = await translator.translate("Return one."); + check(result.success === example.success, `${example.name}: incorrect result.`); + check(calls === example.responses.length, `${example.name}: incorrect model call count.`); + if (!result.success) { + check(result.responseText === example.responses.at(-1), `${example.name}: response text was lost.`); + } + observations.push({ name: example.name, success: result.success, message: result.message ?? "" }); + } + check(validator[typeChatSchemaValidation]().success, "A rejected instance poisoned schema preflight."); + } finally { + validator.close(); + } + validator.close(); + for (const operation of [ + () => validator.validate({ value: 1 }), + () => validator[typeChatSchemaValidation]() + ]) { + let closedError; + try { + operation(); + } catch (error) { + closedError = error; + } + check(closedError?.message.includes("closed"), "Use after close did not fail explicitly."); + } + return observations; +} diff --git a/typescript/experimental/browser/tests/loader.test.mjs b/typescript/experimental/browser/tests/loader.test.mjs new file mode 100644 index 00000000..a8117aaa --- /dev/null +++ b/typescript/experimental/browser/tests/loader.test.mjs @@ -0,0 +1,88 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import { loadBrowserTypeScriptCompiler, compilerVersion } from "@typechat/experimental-browser"; +import { wasmByteLength, wasmSha256 } from "../dist/experimental/browser/src/versions.js"; + +const artifact = await readFile(new URL("../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url)); + +test("compiler and artifact are pinned to the same exact version and bytes", async () => { + for (const name of ["typescript", "@typescript/typescript-wasip1-wasm"]) { + const manifest = JSON.parse(await readFile(new URL(`../node_modules/${name}/package.json`, import.meta.url), "utf8")); + assert.equal(manifest.version, compilerVersion); + } + assert.equal(artifact.byteLength, wasmByteLength); + assert.equal(createHash("sha256").update(artifact).digest("hex"), wasmSha256); +}); + +test("load failures are explicit and never retried", async t => { + let calls = 0; + const fetch = t.mock.method(globalThis, "fetch", async () => { + calls++; + return new Response("Not found", { status: 404 }); + }); + await assert.rejects(loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"), /HTTP 404/); + assert.equal(calls, 1); + const networkError = new TypeError("synthetic network error"); + fetch.mock.mockImplementation(async () => { throw networkError; }); + await assert.rejects(loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"), error => error === networkError); +}); + +test("an already-aborted load never fetches", async t => { + let calls = 0; + t.mock.method(globalThis, "fetch", async () => { calls++; throw new Error("unexpected fetch"); }); + await assert.rejects( + loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm", { signal: AbortSignal.abort() }), + { name: "AbortError" } + ); + assert.equal(calls, 0); +}); + +test("empty, truncated, and oversized artifacts are rejected", async t => { + const fetch = t.mock.method(globalThis, "fetch", async () => new Response(null)); + await assert.rejects(loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"), /no body/); + fetch.mock.mockImplementation(async () => new Response(artifact.subarray(0, 100))); + await assert.rejects(loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"), /received 100/); + let cancelled = false; + fetch.mock.mockImplementation(async () => new Response(new ReadableStream({ + start(controller) { + controller.enqueue(artifact); + controller.enqueue(new Uint8Array([0])); + }, + cancel() { cancelled = true; } + }))); + await assert.rejects(loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"), /exceeds the expected/); + assert.equal(cancelled, true); +}); + +test("equal-sized mismatched artifacts fail integrity verification", async t => { + const incorrect = new Uint8Array(artifact); + incorrect[incorrect.length - 1] ^= 1; + t.mock.method(globalThis, "fetch", async () => new Response(incorrect)); + await assert.rejects(loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"), /SHA-256 mismatch/); +}); + +test("one compiled module supports independent disposable validators without refetching", async t => { + let calls = 0; + t.mock.method(globalThis, "fetch", async () => { calls++; return new Response(artifact); }); + const compiler = await loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"); + const [numbers, strings] = await Promise.all([ + compiler.createValidator("export interface Probe { value: number }", "Probe"), + compiler.createValidator("export interface Probe { value: string }", "Probe") + ]); + try { + assert.equal(numbers.validate({ value: 1 }).success, true); + assert.equal(strings.validate({ value: 1 }).success, false); + assert.ok(numbers.getWasmMemoryByteLength() > 0); + numbers.close(); + numbers.close(); + assert.equal(numbers.getWasmMemoryByteLength(), 0); + assert.throws(() => numbers.validate({ value: 1 }), /closed/); + assert.equal(strings.validate({ value: "still active" }).success, true); + assert.equal(calls, 1); + } finally { + numbers.close(); + strings.close(); + } +}); diff --git a/typescript/experimental/browser/tests/native-preview.mjs b/typescript/experimental/browser/tests/native-preview.mjs new file mode 100644 index 00000000..05c2ec4b --- /dev/null +++ b/typescript/experimental/browser/tests/native-preview.mjs @@ -0,0 +1,31 @@ +import { API } from "typescript/sync"; +import { createFileSystem } from "typescript/fs"; +import { + configFileName, createCompiler, jsonFileName, schemaFileName, schemaValidationFileName +} from "../dist/src/ts/compiler.js"; +import { createTypeScriptJsonValidatorWithCompiler } from "../dist/src/ts/validation.js"; +import { projectView } from "../dist/experimental/browser/src/project.js"; + +export function createPreviewNativeValidator(schema, typeName, schemaValidationTypeName = typeName) { + return createTypeScriptJsonValidatorWithCompiler(schema, typeName, schemaValidationTypeName, files => { + const api = new API({ cwd: "/", useCaseSensitiveFileNames: true }); + let previous; + return createCompiler({ + writeFile(name, text) { + files[name] = text; + }, + update(changedFiles) { + const next = api.createSnapshot({ + openFiles: [schemaFileName, jsonFileName, schemaValidationFileName], + fileSystem: createFileSystem(Object.entries(files)), + fileNotifications: { changed: [...changedFiles], deleted: [] } + }); + previous?.dispose(); + previous = next; + const project = next.getConfiguredProject(configFileName); + return project && projectView(project); + }, + close: () => api.close() + }); + }); +} diff --git a/typescript/experimental/browser/tests/parity.test.mjs b/typescript/experimental/browser/tests/parity.test.mjs new file mode 100644 index 00000000..6a1ab1a2 --- /dev/null +++ b/typescript/experimental/browser/tests/parity.test.mjs @@ -0,0 +1,23 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import { createTypeScriptJsonValidator } from "../../../dist/ts/index.js"; +import * as core from "@typechat/experimental-browser"; +import { runCorpus } from "./corpus.mjs"; +import { createPreviewNativeValidator } from "./native-preview.mjs"; + +test("WASM preserves baseline outcomes and matches the same-version native compiler", { timeout: 120000 }, async t => { + const artifact = await readFile(new URL("../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url)); + t.mock.method(globalThis, "fetch", async () => new Response(artifact)); + const compiler = await core.loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm"); + const baseline = await runCorpus(createTypeScriptJsonValidator, core); + const previewNative = await runCorpus(createPreviewNativeValidator, core); + const wasm = await runCorpus((...args) => compiler.createValidator(...args), core); + assert.deepEqual(wasm, previewNative, "Same-version WASM and native diagnostics diverged."); + assert.deepEqual( + wasm.map(({ name, success }) => ({ name, success })), + baseline.map(({ name, success }) => ({ name, success })), + "Validation behavior diverged from the current stable compiler." + ); + t.diagnostic(`${wasm.length} corpus outcomes matched the stable baseline and same-version native backend.`); +}); diff --git a/typescript/experimental/browser/tests/types.ts b/typescript/experimental/browser/tests/types.ts new file mode 100644 index 00000000..923370cc --- /dev/null +++ b/typescript/experimental/browser/tests/types.ts @@ -0,0 +1,9 @@ +import type { BrowserTypeScriptCompiler, BrowserTypeScriptValidator, Result } from "../src/index.js"; + +interface Probe { value: number; } +type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; +type Expect = T; +declare const compiler: BrowserTypeScriptCompiler; +type CreatedValidator = Awaited>>; +type ValidatorType = Expect>>; +type ValidationResult = Expect["validate"]>, Result>>; diff --git a/typescript/experimental/browser/tsconfig.json b/typescript/experimental/browser/tsconfig.json new file mode 100644 index 00000000..6163d957 --- /dev/null +++ b/typescript/experimental/browser/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "es2021", + "lib": ["es2021", "dom"], + "module": "es2022", + "moduleResolution": "bundler", + "types": ["node"], + "rootDir": "../..", + "outDir": "./dist", + "strict": true, + "exactOptionalPropertyTypes": true, + "skipLibCheck": true, + "declaration": true + }, + "include": ["src/**/*.ts", "tests/types.ts"] +} diff --git a/typescript/src/model.ts b/typescript/src/model.ts index ef74e34e..3b6af776 100644 --- a/typescript/src/model.ts +++ b/typescript/src/model.ts @@ -1,97 +1,6 @@ import { Result, success, error, withResponseMetadata, TypeChatResponseMetadata, TypeChatTokenUsage } from "./result.js"; - -/** - * Represents a section of an LLM prompt with an associated role. TypeChat uses the "user" role for - * prompts it generates and the "assistant" role for previous LLM responses (which will be part of - * the prompt in repair attempts). TypeChat currently doesn't use the "system" role. - */ -export interface PromptSection { - /** - * Specifies the role of this section. - */ - role: "system" | "user" | "assistant"; - /** - * Specifies the content of this section. - */ - content: PromptContent; -} - -export type PromptContent = - | string - | MultimodalPromptContent[]; - -/** - * GPT-4-vision, GPT-4-omni and GPT-4-turbo allow multi-modal input, where images and text can - * be part of the prompt. To support this, the content section of the prompt has an array of objects. - */ -export type MultimodalPromptContent = - | string - | TextPromptContent - | ImagePromptContent; - -export type TextPromptContent = { - type: "text"; - text: string; -}; - -export type ImagePromptContent = { - type: "image_url"; - image_url: ImageUrl; -}; - -export type ImageUrl = { - /* - * This could be a URL to a hosted image, or the base64-encoded image content. - */ - url: string; - - /* - * Controls how the model processes the image and generates its textual understanding. - * In "low" mode, the model treats the image as 512x512px, while "high" mode considers - * the image at full size. - */ - detail?: "auto" | "low" | "high"; -}; - -/** - * Represents a AI language model that can complete prompts. TypeChat uses an implementation of this - * interface to communicate with an AI service that can translate natural language requests to JSON - * instances according to a provided schema. The `createLanguageModel`, `createOpenAILanguageModel`, - * `createAzureOpenAILanguageModel`, and `createOpenAILanguageModelFromClient` functions create - * instances of this interface. - */ -export interface TypeChatLanguageModel { - /** - * Optional property that specifies the maximum number of retry attempts (the default is 3). - */ - retryMaxAttempts?: number; - /** - * Optional property that specifies the delay before retrying in milliseconds (the default is 1000ms). - */ - retryPauseMs?: number; - /** - * Optional property that specifies the timeout, in milliseconds, applied to each HTTP request - * made to the model endpoint (the default is 600000ms, i.e. 10 minutes). A request - including - * reading its response body - is aborted if it does not complete within this time, preventing a - * slow or unresponsive endpoint from causing `complete` to hang indefinitely and exhaust - * resources. Set to 0 or a negative value to disable the timeout. - */ - timeoutMs?: number; - /** - * Optional property that specifies the maximum size, in bytes, of a response body accepted from - * the model endpoint (the default is 104857600, i.e. 100 MB). A larger response is rejected - * without being fully buffered in memory, preventing a malicious or malfunctioning endpoint from - * exhausting memory. Set to 0 or a negative value to disable the limit. - */ - maxResponseBytes?: number; - /** - * Obtains a completion from the language model for the given prompt. - * @param prompt A prompt string or an array of prompt sections. If a string is specified, - * it is converted into a single "user" role prompt section. - * Optional result metadata contains service-reported usage and filtering information. - */ - complete(prompt: string | PromptSection[]): Promise>; -} +import type { PromptSection, PromptContent, TextPromptContent, ImagePromptContent, ImageUrl, TypeChatLanguageModel } from "./modelTypes.js"; +export type { PromptSection, PromptContent, MultimodalPromptContent, TextPromptContent, ImagePromptContent, ImageUrl, TypeChatLanguageModel } from "./modelTypes.js"; /** * Supplies a bearer token; credential acquisition, caching, and renewal remain caller-owned. diff --git a/typescript/src/modelTypes.ts b/typescript/src/modelTypes.ts new file mode 100644 index 00000000..aeddb828 --- /dev/null +++ b/typescript/src/modelTypes.ts @@ -0,0 +1,94 @@ +import type { Result } from "./result.js"; + +/** + * Represents a section of an LLM prompt with an associated role. TypeChat uses the "user" role for + * prompts it generates and the "assistant" role for previous LLM responses (which will be part of + * the prompt in repair attempts). TypeChat currently doesn't use the "system" role. + */ +export interface PromptSection { + /** + * Specifies the role of this section. + */ + role: "system" | "user" | "assistant"; + /** + * Specifies the content of this section. + */ + content: PromptContent; +} + +export type PromptContent = + | string + | MultimodalPromptContent[]; + +/** + * GPT-4-vision, GPT-4-omni and GPT-4-turbo allow multi-modal input, where images and text can + * be part of the prompt. To support this, the content section of the prompt has an array of objects. + */ +export type MultimodalPromptContent = + | string + | TextPromptContent + | ImagePromptContent; + +export type TextPromptContent = { + type: "text"; + text: string; +}; + +export type ImagePromptContent = { + type: "image_url"; + image_url: ImageUrl; +}; + +export type ImageUrl = { + /* + * This could be a URL to a hosted image, or the base64-encoded image content. + */ + url: string; + + /* + * Controls how the model processes the image and generates its textual understanding. + * In "low" mode, the model treats the image as 512x512px, while "high" mode considers + * the image at full size. + */ + detail?: "auto" | "low" | "high"; +}; + +/** + * Represents a AI language model that can complete prompts. TypeChat uses an implementation of this + * interface to communicate with an AI service that can translate natural language requests to JSON + * instances according to a provided schema. The `createLanguageModel`, `createOpenAILanguageModel`, + * `createAzureOpenAILanguageModel`, and `createOpenAILanguageModelFromClient` functions create + * instances of this interface. + */ +export interface TypeChatLanguageModel { + /** + * Optional property that specifies the maximum number of retry attempts (the default is 3). + */ + retryMaxAttempts?: number; + /** + * Optional property that specifies the delay before retrying in milliseconds (the default is 1000ms). + */ + retryPauseMs?: number; + /** + * Optional property that specifies the timeout, in milliseconds, applied to each HTTP request + * made to the model endpoint (the default is 600000ms, i.e. 10 minutes). A request - including + * reading its response body - is aborted if it does not complete within this time, preventing a + * slow or unresponsive endpoint from causing `complete` to hang indefinitely and exhaust + * resources. Set to 0 or a negative value to disable the timeout. + */ + timeoutMs?: number; + /** + * Optional property that specifies the maximum size, in bytes, of a response body accepted from + * the model endpoint (the default is 104857600, i.e. 100 MB). A larger response is rejected + * without being fully buffered in memory, preventing a malicious or malfunctioning endpoint from + * exhausting memory. Set to 0 or a negative value to disable the limit. + */ + maxResponseBytes?: number; + /** + * Obtains a completion from the language model for the given prompt. + * @param prompt A prompt string or an array of prompt sections. If a string is specified, + * it is converted into a single "user" role prompt section. + * Optional result metadata contains service-reported usage and filtering information. + */ + complete(prompt: string | PromptSection[]): Promise>; +} diff --git a/typescript/src/ts/compiler.ts b/typescript/src/ts/compiler.ts new file mode 100644 index 00000000..fb7f3dde --- /dev/null +++ b/typescript/src/ts/compiler.ts @@ -0,0 +1,207 @@ +import { error, success, type Result } from "../result.js"; + +export const configFileName = "/tsconfig.json"; +export const schemaFileName = "/schema.ts"; +export const jsonFileName = "/json.ts"; +export const schemaValidationFileName = "/schema-validation.ts"; + +export interface CompilerDiagnostic { + code: number; + text: string; + pos: number; + fileName?: string | undefined; + messageChain?: readonly CompilerDiagnostic[] | undefined; +} + +export interface CompilerTypeDescription { + text: string; + properties: readonly { name: string; optional: boolean }[]; +} + +export interface CompilerAssignment { + start: number; + typeEnd: number; + getTypes(wireTypeName: string): { + source: CompilerTypeDescription; + target: CompilerTypeDescription; + } | undefined; +} + +export interface CompilerProject { + getSyntacticDiagnostics(fileName?: string): readonly CompilerDiagnostic[]; + getSemanticDiagnostics(fileName?: string): readonly CompilerDiagnostic[]; + getSourceFile(fileName: string): { + fileName: string; + getLineAndCharacterOfPosition(position: number): { line: number; character: number }; + } | undefined; + getStringEnumValues(): readonly string[]; + getAssignments(): readonly CompilerAssignment[]; +} + +export interface CompilerHost { + update(changedFiles: readonly string[]): CompilerProject | undefined; + writeFile(fileName: string, text: string): void; + close(): void; +} + +export interface TypeScriptCompiler { + getStringEnumValues(): readonly string[]; + validateSchema(moduleText: string): Result; + validateJson(moduleText: string, wireTypeName: string): readonly string[]; + close(): void; +} + +export function createCompiler(host: CompilerHost): TypeScriptCompiler { + return { + getStringEnumValues: () => host.update([])?.getStringEnumValues() ?? [], + validateSchema(moduleText) { + host.writeFile(schemaValidationFileName, moduleText); + const project = host.update([schemaValidationFileName]); + if (!project) { + return error(`The TypeScript schema project '${configFileName}' couldn't be loaded.`); + } + const files = [schemaFileName, schemaValidationFileName].map(name => project.getSourceFile(name)); + if (files.some(file => !file)) { + return error("The TypeScript schema preflight files couldn't be loaded."); + } + const messages: string[] = []; + for (const file of files) { + if (!file) { + continue; + } + for (const diagnostic of [ + ...project.getSyntacticDiagnostics(file.fileName), + ...project.getSemanticDiagnostics(file.fileName) + ]) { + const message = flattenDiagnostic(diagnostic); + const sourceFile = diagnostic.fileName === undefined + ? undefined : project.getSourceFile(diagnostic.fileName); + if (!sourceFile || diagnostic.pos < 0) { + messages.push(message); + continue; + } + const { line, character } = sourceFile.getLineAndCharacterOfPosition(diagnostic.pos); + const name = sourceFile.fileName === schemaFileName ? "schema.ts" + : sourceFile.fileName === schemaValidationFileName ? "schema validation" + : sourceFile.fileName; + messages.push(`${name}(${line + 1},${character + 1}): ${message}`); + } + } + return messages.length ? error(messages.join("\n")) : success(undefined); + }, + validateJson(moduleText, wireTypeName) { + host.writeFile(jsonFileName, moduleText); + const project = host.update([jsonFileName]); + if (!project) { + return [`The TypeScript schema project '${configFileName}' couldn't be loaded.`]; + } + const syntactic = project.getSyntacticDiagnostics(); + const diagnostics = syntactic.length ? syntactic : project.getSemanticDiagnostics(); + return diagnostics.map(diagnostic => { + const truncated = findDiagnostic(diagnostic, 2740); + if (truncated?.fileName === jsonFileName) { + const expanded = expandMissingProperties(project.getAssignments(), truncated, wireTypeName); + if (expanded) { + return expanded; + } + } + return flattenDiagnostic(diagnostic); + }); + }, + close: () => host.close() + }; +} + +export function collectStringEnumValues( + source: Node, + forEachChild: (node: Node, visit: (node: Node) => void) => void, + enumMembers: (node: Node) => readonly Member[], + getConstantValue: (member: Member) => string | number | undefined +): string[] { + const values = new Set(); + forEachChild(source, function visit(node) { + for (const member of enumMembers(node)) { + const value = getConstantValue(member); + if (typeof value === "string") { + values.add(value); + } + } + forEachChild(node, visit); + }); + return [...values]; +} + +export function describeAssignment( + start: number, + typeEnd: number, + annotationName: string, + annotation: Node, + typeArgument: Node | undefined, + initializer: Node, + getType: (node: Node) => Type | undefined, + describeType: (type: Type) => CompilerTypeDescription +): CompilerAssignment { + return { + start, + typeEnd, + getTypes(wireTypeName) { + const target = getType(annotationName === wireTypeName ? typeArgument ?? annotation : annotation); + const source = getType(initializer); + return target && source ? { target: describeType(target), source: describeType(source) } : undefined; + } + }; +} + +function findDiagnostic(diagnostic: CompilerDiagnostic, code: number): CompilerDiagnostic | undefined { + if (diagnostic.code === code) { + return diagnostic; + } + for (const child of diagnostic.messageChain ?? []) { + const found = findDiagnostic(child, code); + if (found) { + return found; + } + } + return undefined; +} + +function flattenDiagnostic(diagnostic: CompilerDiagnostic): string { + const messages: string[] = []; + append(diagnostic, 0); + return messages.join("\n"); + + function append(value: CompilerDiagnostic, indent: number) { + messages.push(" ".repeat(indent) + value.text); + for (const child of value.messageChain ?? []) { + append(child, indent + 1); + } + } +} + +function expandMissingProperties( + assignments: readonly CompilerAssignment[], + diagnostic: CompilerDiagnostic, + wireTypeName: string +): string | undefined { + const reportedTarget = / from type '(.+)': /.exec(diagnostic.text)?.[1]; + for (const assignment of assignments) { + // A nested diagnostic must not be expanded using the outer declaration. + if (assignment.start > diagnostic.pos || diagnostic.pos > assignment.typeEnd) { + continue; + } + const types = assignment.getTypes(wireTypeName); + if (!types) { + continue; + } + const { target, source } = types; + const present = new Set(source.properties.map(property => property.name)); + const missing = target.properties + .filter(property => !property.optional && !present.has(property.name)) + .map(property => property.name); + if (missing.length && (reportedTarget === undefined || reportedTarget === target.text || + reportedTarget === `${wireTypeName}Object<${target.text}>`)) { + return `Type '${source.text}' is missing the following properties from type '${target.text}': ${missing.join(", ")}`; + } + } + return undefined; +} diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index 99976f66..15102c68 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -1,148 +1,17 @@ // TODO: Revisit these `typescript/unstable/*` imports once a stable API is available. -import { API, NodeBuilderFlags, SymbolFlags, type Checker, type Diagnostic } from 'typescript/unstable/sync'; -import { createVirtualFileSystem } from 'typescript/unstable/fs'; -import type { Node, SourceFile } from 'typescript/unstable/ast'; -import { isEnumDeclaration, isTypeReferenceNode, isVariableStatement } from 'typescript/unstable/ast/is'; -import { Result, success, error } from '../result.js'; -import { typeChatSchemaValidation, type TypeChatJsonValidator } from "../typechat.js"; - -const libText = `interface Array { length: number, [n: number]: T } -interface Object { toString(): string } -interface Function { prototype: unknown } -interface CallableFunction extends Function {} -interface NewableFunction extends Function {} -interface String { readonly length: number } -interface Boolean { valueOf(): boolean } -interface Number { valueOf(): number } -interface RegExp { test(string: string): boolean } -interface ReadonlyArray { readonly length: number, readonly [n: number]: T } -type Partial = { [P in keyof T]?: T[P] }; -type Required = { [P in keyof T]-?: T[P] }; -type Readonly = { readonly [P in keyof T]: T[P] }; -type Pick = { [P in K]: T[P] }; -type Record = { [P in K]: T }; -type Exclude = T extends U ? never : T; -type Extract = T extends U ? T : never; -type Omit = Pick>; -type NonNullable = T & {}; -interface PromiseLike { then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike } -interface Promise { then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise } -type ReturnType any> = T extends (...args: any) => infer R ? R : any; -type Awaited = T extends null | undefined ? T : T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? F extends ((value: infer V, ...args: infer _) => any) ? Awaited : never : T; -type Uppercase = intrinsic; -type Lowercase = intrinsic; -type Capitalize = intrinsic; -type Uncapitalize = intrinsic;`; - -const configFileName = "/tsconfig.json"; -const libFileName = "/lib.d.ts"; -const schemaFileName = "/schema.ts"; -const jsonFileName = "/json.ts"; -const schemaValidationFileName = "/schema-validation.ts"; - -/** - * Returns a type alias name that does not collide with identifiers in the schema. - */ -function createUniqueJsonWireTypeName( - schemaText: string, - importedTypeName: string, - stringEnumValues: readonly string[] -): string { - let name = "__TypeChatJsonWire"; - while ( - importedTypeName === name || - importedTypeName === `${name}Enum` || - importedTypeName === `${name}Object` || - importedTypeName === `${name}Shape` || - schemaText.includes(name) || - schemaText.includes(`${name}Enum`) || - schemaText.includes(`${name}Object`) || - schemaText.includes(`${name}Shape`) || - stringEnumValues.some(value => value.includes(name)) - ) { - name += "_"; - } - return name; -} - -/** - * Collects the string values declared by enums in the schema. Limiting the JSON wire mapping to - * these values leaves branded and opaque string types untouched. - */ -function getStringEnumValues(checker: Checker, sourceFile: SourceFile): string[] { - const values = new Set(); - sourceFile.forEachChild(function visit(node: Node) { - if (isEnumDeclaration(node)) { - for (const member of node.members) { - const value = checker.getConstantValue(member); - if (typeof value === "string") { - values.add(value); - } - } - } - node.forEachChild(visit); - }); - return [...values]; -} - -/** - * Maps serialized string-enum values back to their literal enum member types while preserving the - * rest of the schema's structure. Class instances with private or protected members are left - * unchanged because mapping their public keys would drop the nominal constraint that rejects - * plain JSON objects. - */ -function createJsonWireTypeDefinition(typeName: string, stringEnumValues: readonly string[]): string { - const enumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); - // Intersecting an all-optional mapped shape with `object` disables TypeScript's weak-type - // check. Keep the constraint when an explicit intersection accepts arrays, or when the mapped - // shape would newly accept a primitive that the original type rejects. Ordinary weak shapes - // keep their weak-type check. - return `type ${typeName}Enum = ${enumValues}; -type ${typeName}Object = { [K in keyof T]: ${typeName} }; -type ${typeName}Shape = { [K in keyof T]: T[K] }; -type ${typeName} = - T extends ${typeName}Enum ? \`\${T}\` : - T extends (...args: never[]) => unknown ? T : - T extends abstract new (...args: never[]) => unknown ? T : - T extends object ? (${typeName}Shape extends T ? - (string extends T - ? ${typeName}Object - : number extends T - ? ${typeName}Object - : boolean extends T - ? ${typeName}Object - : string extends ${typeName}Object - ? ${typeName}Object & object - : number extends ${typeName}Object - ? ${typeName}Object & object - : boolean extends ${typeName}Object - ? ${typeName}Object & object - : unknown[] extends T - ? ${typeName}Object & object - : ${typeName}Object) : T) : T;`; -} - -/** - * Represents an object that can validate JSON strings according to a given TypeScript schema. - */ -export interface TypeScriptJsonValidator extends TypeChatJsonValidator { - /** - * Transform JSON into TypeScript code for validation. Returns a `Success` object if the conversion is - * successful, or an `Error` object if the JSON can't be transformed. The returned TypeScript source code is - * expected to be an ECMAScript module that imports one or more types from `"./schema"` and combines those - * types and a representation of the JSON object in a manner suitable for type-checking by the TypeScript compiler. - */ - createModuleTextFromJson(jsonObject: object): Result; - /** - * Releases the TypeScript compiler instance backing this validator. The validator can't be used afterwards. - * Calling `close` is optional; the compiler instance doesn't keep the host process alive. - */ - close(): void; -} - -export interface TypeScriptJsonValidatorWithSchemaValidation extends TypeScriptJsonValidator { - [typeChatSchemaValidation](): Result; -} +import { API, NodeBuilderFlags, SymbolFlags, type Project, type Type } from "typescript/unstable/sync"; +import { createVirtualFileSystem } from "typescript/unstable/fs"; +import type { EnumMember, Node } from "typescript/unstable/ast"; +import { isEnumDeclaration, isTypeReferenceNode, isVariableStatement } from "typescript/unstable/ast/is"; +import { + collectStringEnumValues, configFileName, createCompiler, describeAssignment, jsonFileName, schemaFileName, + type CompilerAssignment, type CompilerProject, type CompilerTypeDescription +} from "./compiler.js"; +import { + createTypeScriptJsonValidatorWithCompiler, type TypeScriptJsonValidatorWithSchemaValidation +} from "./validation.js"; + +export type { TypeScriptJsonValidator, TypeScriptJsonValidatorWithSchemaValidation } from "./validation.js"; /** * Returns a JSON validator for a given TypeScript schema. Validation is performed by an in-memory instance of @@ -157,425 +26,70 @@ export function createTypeScriptJsonValidator( typeName: string, schemaValidationTypeName: string = typeName ): TypeScriptJsonValidatorWithSchemaValidation { - const fileSystem = createVirtualFileSystem({ - [configFileName]: JSON.stringify({ - compilerOptions: { - strict: true, - skipLibCheck: true, - noLib: true, - types: [] + return createTypeScriptJsonValidatorWithCompiler(schema, typeName, schemaValidationTypeName, files => { + const fs = createVirtualFileSystem(files); + if (!fs.writeFile) { + throw new Error("The TypeScript virtual file system doesn't support writing files."); + } + const api = new API({ fs, cwd: "/" }); + let opened = false; + return createCompiler({ + writeFile: fs.writeFile, + update(changedFiles) { + const snapshot = api.updateSnapshot(opened + ? { fileChanges: { changed: [...changedFiles] } } + : { openProjects: [configFileName] }); + opened = true; + const project = snapshot.getProject(configFileName); + return project && projectView(project); }, - files: [libFileName, schemaFileName, jsonFileName, schemaValidationFileName] - }), - [libFileName]: libText, - [schemaFileName]: schema, - [jsonFileName]: "", - [schemaValidationFileName]: "" - }); - const api = new API({ fs: fileSystem, cwd: "/" }); - if (!fileSystem.writeFile) { - throw new Error("The TypeScript virtual file system doesn't support writing files."); - } - const writeFile = fileSystem.writeFile; - const initialSnapshot = api.updateSnapshot({ openProjects: [configFileName] }); - const schemaProject = initialSnapshot.getProject(configFileName); - const schemaSourceFile = schemaProject?.program.getSourceFile(schemaFileName); - const stringEnumValues = schemaProject && schemaSourceFile - ? getStringEnumValues(schemaProject.checker, schemaSourceFile) - : []; - const jsonWireTypeName = createUniqueJsonWireTypeName(schema, typeName, stringEnumValues); - const jsonWireTypeDefinition = stringEnumValues.length - ? createJsonWireTypeDefinition(jsonWireTypeName, stringEnumValues) - : ""; - const jsonWireEnumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); - let schemaValidationResult: Result | undefined; - const validator: TypeScriptJsonValidatorWithSchemaValidation = { - getSchemaText: () => schema, - getTypeName: () => typeName, - [typeChatSchemaValidation]: validateSchema, - createModuleTextFromJson, - validate, - close: () => api.close() - }; - return validator; - - function validateSchema(): Result { - if (schemaValidationResult) { - return schemaValidationResult; - } - - writeFile( - schemaValidationFileName, - `export type __TypeChatSchemaTarget = import('./schema').${schemaValidationTypeName};\n` - ); - const snapshot = api.updateSnapshot({ - fileChanges: { changed: [schemaValidationFileName] } + close: () => api.close() }); - const project = snapshot.getProject(configFileName); - if (!project) { - schemaValidationResult = error( - `The TypeScript schema project '${configFileName}' couldn't be loaded.` - ); - return schemaValidationResult; - } - - const program = project.program; - const schemaFiles = [schemaFileName, schemaValidationFileName] - .map(fileName => program.getSourceFile(fileName)) - .filter((sourceFile): sourceFile is SourceFile => sourceFile !== undefined); - if (schemaFiles.length !== 2) { - schemaValidationResult = error("The TypeScript schema preflight files couldn't be loaded."); - return schemaValidationResult; - } - const diagnostics = schemaFiles.flatMap(sourceFile => [ - ...program.getSyntacticDiagnostics(sourceFile.fileName), - ...program.getSemanticDiagnostics(sourceFile.fileName) - ]); - schemaValidationResult = diagnostics.length - ? error( - diagnostics - .map(diagnostic => - formatSchemaDiagnostic( - diagnostic, - diagnostic.fileName === undefined - ? undefined - : program.getSourceFile(diagnostic.fileName) - ) - ) - .join("\n") - ) - : success(undefined); - return schemaValidationResult; - } - - function validate(jsonObject: object): Result { - const moduleResult = validator.createModuleTextFromJson(jsonObject); - if (!moduleResult.success) { - return "data" in moduleResult ? moduleResult : { - ...moduleResult, - success: false, - message: moduleResult.message, - data: jsonObject - }; - } - writeFile(jsonFileName, moduleResult.data); - const snapshot = api.updateSnapshot({ fileChanges: { changed: [jsonFileName] } }); - const project = snapshot.getProject(configFileName); - if (!project) { - return error(`The TypeScript schema project '${configFileName}' couldn't be loaded.`, { data: jsonObject }); - } - const program = project.program; - const syntacticDiagnostics = program.getSyntacticDiagnostics(); - const programDiagnostics = syntacticDiagnostics.length ? syntacticDiagnostics : program.getSemanticDiagnostics(); - if (programDiagnostics.length) { - const checker = project.checker; - const jsonFile = program.getSourceFile(jsonFileName); - const diagnostics = programDiagnostics.map(d => { - // TS error 2740 truncates the missing-properties list to 4 items ("and N more"). - // Use the type checker to reconstruct the full list of missing required properties. - // The truncated diagnostic may be a child of another one, for example an - // intersection target, so search the message chain rather than the rendered text. - const truncated = findDiagnosticWithCode(d, 2740); - if (jsonFile && truncated?.fileName === jsonFileName) { - const expanded = expandMissingPropertiesMessage(checker, jsonFile, truncated.pos, truncated.text); - if (expanded) { - return normalizeJsonWireTypeNames(expanded); - } - } - return normalizeJsonWireTypeNames(flattenDiagnosticMessageText(d, "\n")); - }).join("\n"); - return error(diagnostics, { data: jsonObject }); - } - return success(jsonObject as T); - } - - function findDiagnosticWithCode(diagnostic: Diagnostic, code: number): Diagnostic | undefined { - if (diagnostic.code === code) { - return diagnostic; - } - for (const child of diagnostic.messageChain ?? []) { - const match = findDiagnosticWithCode(child, code); - if (match) { - return match; - } - } - return undefined; - } - - /** - * Removes internal helper names from diagnostics so callers and repair prompts see the schema - * type that they wrote. - */ - function normalizeJsonWireTypeNames(message: string): string { - if (!jsonWireTypeDefinition) { - return message; - } - return normalizeDiagnosticText(message); - } + }); +} - /** - * Unwraps helper type applications while leaving string and template-literal spans verbatim. - * Type arguments can contain either form, so their punctuation never terminates an enclosing - * application. - */ - function normalizeDiagnosticText(text: string, insideHelper = false): string { - const names = [`${jsonWireTypeName}Shape`, `${jsonWireTypeName}Object`, jsonWireTypeName]; - let result = ""; - let index = 0; - while (index < text.length) { - if (text[index] === '"') { - const end = skipStringLiteral(text, index); - result += text.slice(index, end); - index = end; - continue; - } - if (text[index] === "`") { - const end = skipTemplateLiteral(text, index); - result += text.slice(index, end); - index = end; - continue; - } - let matched = false; - for (const name of names) { - if (!text.startsWith(name, index) || text[index + name.length] !== "<") { - continue; - } - const end = findTypeArgumentEnd(text, index + name.length); - if (end < 0) { +function projectView({ program, checker }: Project): CompilerProject { + function describeType(type: Type): CompilerTypeDescription { + return { + text: checker.typeToString(type, undefined, NodeBuilderFlags.NoTruncation), + properties: checker.getPropertiesOfType(type).map(property => ({ + name: property.name, + optional: !!(property.flags & SymbolFlags.Optional) + })) + }; + } + return { + getSourceFile: name => program.getSourceFile(name), + getSyntacticDiagnostics: name => program.getSyntacticDiagnostics(name), + getSemanticDiagnostics: name => program.getSemanticDiagnostics(name), + getStringEnumValues() { + const source = program.getSourceFile(schemaFileName); + return source ? collectStringEnumValues( + source, + (node, visit) => node.forEachChild(visit), + node => isEnumDeclaration(node) ? node.members : [], + member => checker.getConstantValue(member) + ) : []; + }, + getAssignments() { + const file = program.getSourceFile(jsonFileName); + const assignments: CompilerAssignment[] = []; + for (const statement of file?.statements ?? []) { + if (!isVariableStatement(statement)) { continue; } - result += normalizeDiagnosticText(text.slice(index + name.length + 1, end), true); - index = end + 1; - if (name.endsWith("Object")) { - // Drop the `& object` guard from the rendered helper so diagnostics mention - // the schema type alone. - const guard = /^\s*&\s*object\b/.exec(text.slice(index)); - if (guard) { - index += guard[0].length; + for (const declaration of statement.declarationList.declarations) { + const { type, initializer } = declaration; + if (type && isTypeReferenceNode(type) && initializer && file) { + assignments.push(describeAssignment( + declaration.getStart(file), type.getEnd(), type.typeName.getText(file), + type, type.typeArguments?.[0], initializer, + node => checker.getTypeAtLocation(node), describeType + )); } } - matched = true; - break; - } - if (matched) { - continue; - } - const enumName = `${jsonWireTypeName}Enum`; - if (insideHelper && jsonWireEnumValues && text.startsWith(enumName, index)) { - // Replace the alias once. Re-scanning the substituted text could turn a value - // that spells the alias into an unbounded expansion. - result += jsonWireEnumValues; - index += enumName.length; - continue; - } - result += text[index++]; - } - return result; - } - - function skipStringLiteral(text: string, start: number): number { - let index = start + 1; - while (index < text.length) { - if (text[index] === "\\") { - index += 2; - } - else if (text[index] === '"') { - return index + 1; - } - else { - index++; - } - } - return text.length; - } - - /** - * Skips a template literal type, including escaped characters and nested `${...}` - * interpolations. Diagnostic type text can contain any of these, and their punctuation must - * not be mistaken for an enclosing type argument list. - */ - function skipTemplateLiteral(text: string, start: number): number { - let index = start + 1; - while (index < text.length) { - if (text[index] === "\\") { - index += 2; - } - else if (text[index] === "`") { - return index + 1; - } - else if (text[index] === "$" && text[index + 1] === "{") { - index = skipTemplateExpression(text, index + 2); - } - else { - index++; - } - } - return text.length; - } - - function skipTemplateExpression(text: string, start: number): number { - let depth = 1; - let index = start; - while (index < text.length) { - if (text[index] === '"') { - index = skipStringLiteral(text, index); - } - else if (text[index] === "'") { - index = skipSingleQuotedString(text, index); - } - else if (text[index] === "`") { - index = skipTemplateLiteral(text, index); - } - else if (text[index] === "{") { - depth++; - index++; - } - else if (text[index] === "}" && --depth === 0) { - return index + 1; - } - else { - index++; } + return assignments; } - return text.length; - } - - function skipSingleQuotedString(text: string, start: number): number { - let index = start + 1; - while (index < text.length) { - if (text[index] === "\\") { - index += 2; - } - else if (text[index] === "'") { - return index + 1; - } - else { - index++; - } - } - return text.length; - } - - function findTypeArgumentEnd(text: string, openBracket: number): number { - let depth = 0; - for (let index = openBracket; index < text.length; index++) { - if (text[index] === '"') { - index = skipStringLiteral(text, index) - 1; - } - else if (text[index] === "`") { - index = skipTemplateLiteral(text, index) - 1; - } - else if (text[index] === "<") { - depth++; - } - else if (text[index] === ">" && text[index - 1] !== "=" && --depth === 0) { - return index; - } - } - return -1; - } - - /** - * Flattens a diagnostic and its chained messages into a single string, indenting each level of the chain. - */ - function flattenDiagnosticMessageText(diagnostic: Diagnostic, newLine: string): string { - const messages: string[] = []; - appendMessages(diagnostic, 0); - return messages.join(newLine); - - function appendMessages(d: Diagnostic, indent: number) { - messages.push(indent ? " ".repeat(indent) + d.text : d.text); - for (const child of d.messageChain ?? []) { - appendMessages(child, indent + 1); - } - } - } - - function formatSchemaDiagnostic( - diagnostic: Diagnostic, - sourceFile: SourceFile | undefined - ): string { - const message = flattenDiagnosticMessageText(diagnostic, "\n"); - if (!sourceFile || diagnostic.pos < 0) { - return message; - } - const { line, character } = sourceFile.getLineAndCharacterOfPosition( - diagnostic.pos - ); - const fileName = sourceFile.fileName === schemaFileName - ? "schema.ts" - : sourceFile.fileName === schemaValidationFileName - ? "schema validation" - : sourceFile.fileName; - return `${fileName}(${line + 1},${character + 1}): ${message}`; - } - - /** - * For TypeScript error 2740 (missing required properties, truncated with "and N more"), - * uses the type checker to compute the full list of missing required properties from the - * variable declaration at `position` in `file`. Returns `undefined` if the declaration - * cannot be located or yields no missing properties (fallback to the original message). - */ - function expandMissingPropertiesMessage( - checker: Checker, - file: SourceFile, - position: number, - diagnosticText: string - ): string | undefined { - const reportedTarget = / from type '(.+)': /.exec(diagnosticText)?.[1]; - for (const stmt of file.statements) { - if (isVariableStatement(stmt)) { - for (const decl of stmt.declarationList.declarations) { - // Only the diagnostic attached to the declaration itself belongs to the outer - // instance. A nested property diagnostic also falls within decl.end, but its - // position is inside the initializer rather than the declaration prefix or - // type annotation. - if (decl.getStart(file) <= position && - decl.type && - position <= decl.type.getEnd() && - isTypeReferenceNode(decl.type) && decl.initializer) { - // Only the declaration generated by this validator wraps the schema type in - // the JsonWire helper. A custom createModuleTextFromJson may use any generic - // annotation, so unwrap only our own helper and keep other targets intact. - const isJsonWireReference = decl.type.typeName.getText(file) === jsonWireTypeName; - const targetTypeNode = isJsonWireReference - ? decl.type.typeArguments?.[0] ?? decl.type - : decl.type; - const targetType = checker.getTypeAtLocation(targetTypeNode); - const sourceType = checker.getTypeAtLocation(decl.initializer); - if (!targetType || !sourceType) { - continue; - } - const sourceProps = new Set(checker.getPropertiesOfType(sourceType).map(p => p.name)); - const missingProps = checker.getPropertiesOfType(targetType) - .filter(p => !(p.flags & SymbolFlags.Optional) && !sourceProps.has(p.name)) - .map(p => p.name); - if (missingProps.length > 0) { - const srcStr = checker.typeToString(sourceType, undefined, NodeBuilderFlags.NoTruncation); - const tgtStr = checker.typeToString(targetType, undefined, NodeBuilderFlags.NoTruncation); - // A nested diagnostic reports the nested type. Expanding it here - // would replace it with the outer declaration's missing properties. - if (reportedTarget !== undefined && - reportedTarget !== tgtStr && - reportedTarget !== `${jsonWireTypeName}Object<${tgtStr}>`) { - continue; - } - return `Type '${srcStr}' is missing the following properties from type '${tgtStr}': ${missingProps.join(", ")}`; - } - } - } - } - } - return undefined; - } - - function createModuleTextFromJson(jsonObject: object) { - // String enums do not accept their serialized values in a normal enum-typed assignment. - // The JsonWire helper maps each enum value back to its string literal while recursively - // preserving object, array, tuple, optional-property, and union shapes. Numeric enums and - // enum-free schemas continue to validate against the original type. - const typeDefinition = jsonWireTypeDefinition ? `${jsonWireTypeDefinition}\n` : ""; - const jsonType = jsonWireTypeDefinition ? `${jsonWireTypeName}<${typeName}>` : typeName; - return success(`import { ${typeName} } from './schema';\n${typeDefinition}const json: ${jsonType} = ${JSON.stringify(jsonObject, undefined, 2)};\n`); - } + }; } diff --git a/typescript/src/ts/validation.ts b/typescript/src/ts/validation.ts new file mode 100644 index 00000000..e1fbf123 --- /dev/null +++ b/typescript/src/ts/validation.ts @@ -0,0 +1,388 @@ +import { Result, success, error } from '../result.js'; +import { typeChatSchemaValidation, type TypeChatJsonValidator } from "../typechat.js"; +import { + configFileName, schemaFileName, jsonFileName, schemaValidationFileName, type TypeScriptCompiler +} from "./compiler.js"; + +const libText = `interface Array { length: number, [n: number]: T } +interface Object { toString(): string } +interface Function { prototype: unknown } +interface CallableFunction extends Function {} +interface NewableFunction extends Function {} +interface String { readonly length: number } +interface Boolean { valueOf(): boolean } +interface Number { valueOf(): number } +interface RegExp { test(string: string): boolean } +interface ReadonlyArray { readonly length: number, readonly [n: number]: T } +type Partial = { [P in keyof T]?: T[P] }; +type Required = { [P in keyof T]-?: T[P] }; +type Readonly = { readonly [P in keyof T]: T[P] }; +type Pick = { [P in K]: T[P] }; +type Record = { [P in K]: T }; +type Exclude = T extends U ? never : T; +type Extract = T extends U ? T : never; +type Omit = Pick>; +type NonNullable = T & {}; +interface PromiseLike { then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike } +interface Promise { then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise } +type ReturnType any> = T extends (...args: any) => infer R ? R : any; +type Awaited = T extends null | undefined ? T : T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? F extends ((value: infer V, ...args: infer _) => any) ? Awaited : never : T; +type Uppercase = intrinsic; +type Lowercase = intrinsic; +type Capitalize = intrinsic; +type Uncapitalize = intrinsic;`; + +const libFileName = "/lib.d.ts"; + +/** + * Returns a type alias name that does not collide with identifiers in the schema. + */ +function createUniqueJsonWireTypeName( + schemaText: string, + importedTypeName: string, + stringEnumValues: readonly string[] +): string { + let name = "__TypeChatJsonWire"; + while ( + importedTypeName === name || + importedTypeName === `${name}Enum` || + importedTypeName === `${name}Object` || + importedTypeName === `${name}Shape` || + schemaText.includes(name) || + schemaText.includes(`${name}Enum`) || + schemaText.includes(`${name}Object`) || + schemaText.includes(`${name}Shape`) || + stringEnumValues.some(value => value.includes(name)) + ) { + name += "_"; + } + return name; +} + +/** + * Maps serialized string-enum values back to their literal enum member types while preserving the + * rest of the schema's structure. Class instances with private or protected members are left + * unchanged because mapping their public keys would drop the nominal constraint that rejects + * plain JSON objects. + */ +function createJsonWireTypeDefinition(typeName: string, stringEnumValues: readonly string[]): string { + const enumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); + // Intersecting an all-optional mapped shape with `object` disables TypeScript's weak-type + // check. Keep the constraint when an explicit intersection accepts arrays, or when the mapped + // shape would newly accept a primitive that the original type rejects. Ordinary weak shapes + // keep their weak-type check. + return `type ${typeName}Enum = ${enumValues}; +type ${typeName}Object = { [K in keyof T]: ${typeName} }; +type ${typeName}Shape = { [K in keyof T]: T[K] }; +type ${typeName} = + T extends ${typeName}Enum ? \`\${T}\` : + T extends (...args: never[]) => unknown ? T : + T extends abstract new (...args: never[]) => unknown ? T : + T extends object ? (${typeName}Shape extends T ? + (string extends T + ? ${typeName}Object + : number extends T + ? ${typeName}Object + : boolean extends T + ? ${typeName}Object + : string extends ${typeName}Object + ? ${typeName}Object & object + : number extends ${typeName}Object + ? ${typeName}Object & object + : boolean extends ${typeName}Object + ? ${typeName}Object & object + : unknown[] extends T + ? ${typeName}Object & object + : ${typeName}Object) : T) : T;`; +} + +/** + * Represents an object that can validate JSON strings according to a given TypeScript schema. + */ +export interface TypeScriptJsonValidator extends TypeChatJsonValidator { + /** + * Transform JSON into TypeScript code for validation. Returns a `Success` object if the conversion is + * successful, or an `Error` object if the JSON can't be transformed. The returned TypeScript source code is + * expected to be an ECMAScript module that imports one or more types from `"./schema"` and combines those + * types and a representation of the JSON object in a manner suitable for type-checking by the TypeScript compiler. + */ + createModuleTextFromJson(jsonObject: object): Result; + /** + * Releases the TypeScript compiler instance backing this validator. The validator can't be used afterwards. + * Calling `close` is optional; the compiler instance doesn't keep the host process alive. + */ + close(): void; +} + +export interface TypeScriptJsonValidatorWithSchemaValidation extends TypeScriptJsonValidator { + [typeChatSchemaValidation](): Result; +} + +export function createTypeScriptJsonValidatorWithCompiler( + schema: string, + typeName: string, + schemaValidationTypeName: string, + createCompiler: (files: Record) => TypeScriptCompiler +): TypeScriptJsonValidatorWithSchemaValidation { + let compiler: TypeScriptCompiler | undefined = createCompiler({ + [configFileName]: JSON.stringify({ + compilerOptions: { + strict: true, + skipLibCheck: true, + noLib: true, + types: [] + }, + files: [libFileName, schemaFileName, jsonFileName, schemaValidationFileName] + }), + [libFileName]: libText, + [schemaFileName]: schema, + [jsonFileName]: "", + [schemaValidationFileName]: "" + }); + let stringEnumValues: readonly string[]; + try { + stringEnumValues = compiler.getStringEnumValues(); + } catch (cause) { + compiler.close(); + throw cause; + } + const jsonWireTypeName = createUniqueJsonWireTypeName(schema, typeName, stringEnumValues); + const jsonWireTypeDefinition = stringEnumValues.length + ? createJsonWireTypeDefinition(jsonWireTypeName, stringEnumValues) + : ""; + const jsonWireEnumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); + let schemaValidationResult: Result | undefined; + const validator: TypeScriptJsonValidatorWithSchemaValidation = { + getSchemaText: () => schema, + getTypeName: () => typeName, + [typeChatSchemaValidation]: validateSchema, + createModuleTextFromJson, + validate, + close() { + const instance = compiler; + compiler = undefined; + instance?.close(); + } + }; + return validator; + + function openCompiler(): TypeScriptCompiler { + if (!compiler) { + throw new Error("The TypeScript validator has been closed."); + } + return compiler; + } + + function validateSchema(): Result { + const instance = openCompiler(); + if (schemaValidationResult) { + return schemaValidationResult; + } + + schemaValidationResult = instance.validateSchema( + `export type __TypeChatSchemaTarget = import('./schema').${schemaValidationTypeName};\n` + ); + return schemaValidationResult; + } + + function validate(jsonObject: object): Result { + const instance = openCompiler(); + const moduleResult = validator.createModuleTextFromJson(jsonObject); + if (!moduleResult.success) { + return "data" in moduleResult ? moduleResult : { + ...moduleResult, + success: false, + message: moduleResult.message, + data: jsonObject + }; + } + const messages = instance.validateJson(moduleResult.data, jsonWireTypeName); + if (messages.length) { + return error(messages.map(normalizeJsonWireTypeNames).join("\n"), { data: jsonObject }); + } + return success(jsonObject as T); + } + + /** + * Removes internal helper names from diagnostics so callers and repair prompts see the schema + * type that they wrote. + */ + function normalizeJsonWireTypeNames(message: string): string { + if (!jsonWireTypeDefinition) { + return message; + } + return normalizeDiagnosticText(message); + } + + /** + * Unwraps helper type applications while leaving string and template-literal spans verbatim. + * Type arguments can contain either form, so their punctuation never terminates an enclosing + * application. + */ + function normalizeDiagnosticText(text: string, insideHelper = false): string { + const names = [`${jsonWireTypeName}Shape`, `${jsonWireTypeName}Object`, jsonWireTypeName]; + let result = ""; + let index = 0; + while (index < text.length) { + if (text[index] === '"') { + const end = skipStringLiteral(text, index); + result += text.slice(index, end); + index = end; + continue; + } + if (text[index] === "`") { + const end = skipTemplateLiteral(text, index); + result += text.slice(index, end); + index = end; + continue; + } + let matched = false; + for (const name of names) { + if (!text.startsWith(name, index) || text[index + name.length] !== "<") { + continue; + } + const end = findTypeArgumentEnd(text, index + name.length); + if (end < 0) { + continue; + } + result += normalizeDiagnosticText(text.slice(index + name.length + 1, end), true); + index = end + 1; + if (name.endsWith("Object")) { + // Drop the `& object` guard from the rendered helper so diagnostics mention + // the schema type alone. + const guard = /^\s*&\s*object\b/.exec(text.slice(index)); + if (guard) { + index += guard[0].length; + } + } + matched = true; + break; + } + if (matched) { + continue; + } + const enumName = `${jsonWireTypeName}Enum`; + if (insideHelper && jsonWireEnumValues && text.startsWith(enumName, index)) { + // Replace the alias once. Re-scanning the substituted text could turn a value + // that spells the alias into an unbounded expansion. + result += jsonWireEnumValues; + index += enumName.length; + continue; + } + result += text[index++]; + } + return result; + } + + function skipStringLiteral(text: string, start: number): number { + let index = start + 1; + while (index < text.length) { + if (text[index] === "\\") { + index += 2; + } + else if (text[index] === '"') { + return index + 1; + } + else { + index++; + } + } + return text.length; + } + + /** + * Skips a template literal type, including escaped characters and nested `${...}` + * interpolations. Diagnostic type text can contain any of these, and their punctuation must + * not be mistaken for an enclosing type argument list. + */ + function skipTemplateLiteral(text: string, start: number): number { + let index = start + 1; + while (index < text.length) { + if (text[index] === "\\") { + index += 2; + } + else if (text[index] === "`") { + return index + 1; + } + else if (text[index] === "$" && text[index + 1] === "{") { + index = skipTemplateExpression(text, index + 2); + } + else { + index++; + } + } + return text.length; + } + + function skipTemplateExpression(text: string, start: number): number { + let depth = 1; + let index = start; + while (index < text.length) { + if (text[index] === '"') { + index = skipStringLiteral(text, index); + } + else if (text[index] === "'") { + index = skipSingleQuotedString(text, index); + } + else if (text[index] === "`") { + index = skipTemplateLiteral(text, index); + } + else if (text[index] === "{") { + depth++; + index++; + } + else if (text[index] === "}" && --depth === 0) { + return index + 1; + } + else { + index++; + } + } + return text.length; + } + + function skipSingleQuotedString(text: string, start: number): number { + let index = start + 1; + while (index < text.length) { + if (text[index] === "\\") { + index += 2; + } + else if (text[index] === "'") { + return index + 1; + } + else { + index++; + } + } + return text.length; + } + + function findTypeArgumentEnd(text: string, openBracket: number): number { + let depth = 0; + for (let index = openBracket; index < text.length; index++) { + if (text[index] === '"') { + index = skipStringLiteral(text, index) - 1; + } + else if (text[index] === "`") { + index = skipTemplateLiteral(text, index) - 1; + } + else if (text[index] === "<") { + depth++; + } + else if (text[index] === ">" && text[index - 1] !== "=" && --depth === 0) { + return index; + } + } + return -1; + } + + function createModuleTextFromJson(jsonObject: object) { + // String enums do not accept their serialized values in a normal enum-typed assignment. + // The JsonWire helper maps each enum value back to its string literal while recursively + // preserving object, array, tuple, optional-property, and union shapes. Numeric enums and + // enum-free schemas continue to validate against the original type. + const typeDefinition = jsonWireTypeDefinition ? `${jsonWireTypeDefinition}\n` : ""; + const jsonType = jsonWireTypeDefinition ? `${jsonWireTypeName}<${typeName}>` : typeName; + return success(`import { ${typeName} } from './schema';\n${typeDefinition}const json: ${jsonType} = ${JSON.stringify(jsonObject, undefined, 2)};\n`); + } +} diff --git a/typescript/src/typechat.ts b/typescript/src/typechat.ts index 66b082f1..e98b0747 100644 --- a/typescript/src/typechat.ts +++ b/typescript/src/typechat.ts @@ -1,5 +1,5 @@ import { Result, success, error, withResponseMetadata, TypeChatResponseMetadata, Error as TypeChatError } from "./result.js"; -import { TypeChatLanguageModel, PromptSection, PromptContent } from "./model.js"; +import type { TypeChatLanguageModel, PromptSection, PromptContent } from "./modelTypes.js"; import { typeChatSchemaValidation } from "./schemaValidation.js"; export { typeChatSchemaValidation } from "./schemaValidation.js"; diff --git a/typescript/test/compiler.test.ts b/typescript/test/compiler.test.ts new file mode 100644 index 00000000..27197248 --- /dev/null +++ b/typescript/test/compiler.test.ts @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { typeChatSchemaValidation } from "../dist/typechat.js"; +import { createTypeScriptJsonValidatorWithCompiler } from "../dist/ts/validation.js"; +import { createCompiler } from "../dist/ts/compiler.js"; + +describe("compiler-independent validator lifecycle", () => { + it("closes a backend that fails during initialization", () => { + const failure = new Error("synthetic compiler initialization failure"); + let closed = 0; + assert.throws(() => createTypeScriptJsonValidatorWithCompiler("", "Probe", "Probe", () => ({ + getStringEnumValues() { throw failure; }, + validateSchema() { throw new Error("unexpected check"); }, + validateJson() { throw new Error("unexpected check"); }, + close() { closed++; } + })), error => error === failure); + assert.equal(closed, 1); + }); + + it("reports unavailable compiler projects and remains explicitly closed afterwards", () => { + let closed = 0; + const validator = createTypeScriptJsonValidatorWithCompiler("", "Probe", "Probe", () => createCompiler({ + writeFile() {}, + update: () => undefined, + close() { closed++; } + })); + const preflight = validator[typeChatSchemaValidation](); + assert.equal(preflight.success, false); + if (!preflight.success) { + assert.match(preflight.message, /couldn't be loaded/); + } + const value = { value: 1 }; + const result = validator.validate(value); + assert.equal(result.success, false); + if (!result.success) { + assert.equal(result.data, value); + } + validator.close(); + validator.close(); + assert.equal(closed, 1); + assert.throws(() => validator.validate(value), /closed/); + assert.throws(() => validator[typeChatSchemaValidation](), /closed/); + }); +}); From c5e9bfd6c7bc4793b32d06446a8e06dd00a0fe76 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Mon, 23 Nov 2026 16:33:52 -0800 Subject: [PATCH 2/5] Exercise browser prototype with isolated worker jobs Add an application-owned worker example, Chromium/Firefox/WebKit coverage, explicit cancellation and cleanup checks, and broader performance and process-memory measurements for #536. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- typescript/experimental/browser/README.md | 112 ++++++- .../browser/examples/worker/build.mjs | 27 ++ .../browser/examples/worker/client.ts | 100 ++++++ .../browser/examples/worker/index.html | 66 ++++ .../browser/examples/worker/serve.mjs | 31 ++ .../browser/examples/worker/tsconfig.json | 9 + .../examples/worker/validator.worker.ts | 65 ++++ typescript/experimental/browser/package.json | 5 +- .../browser/tests/browser/browser.test.mjs | 308 +++++++++++------- .../browser/tests/browser/process-memory.mjs | 42 +++ .../browser/tests/browser/worker-entry.mjs | 154 +++++++++ 11 files changed, 793 insertions(+), 126 deletions(-) create mode 100644 typescript/experimental/browser/examples/worker/build.mjs create mode 100644 typescript/experimental/browser/examples/worker/client.ts create mode 100644 typescript/experimental/browser/examples/worker/index.html create mode 100644 typescript/experimental/browser/examples/worker/serve.mjs create mode 100644 typescript/experimental/browser/examples/worker/tsconfig.json create mode 100644 typescript/experimental/browser/examples/worker/validator.worker.ts create mode 100644 typescript/experimental/browser/tests/browser/process-memory.mjs create mode 100644 typescript/experimental/browser/tests/browser/worker-entry.mjs diff --git a/typescript/experimental/browser/README.md b/typescript/experimental/browser/README.md index db39b58d..24913bef 100644 --- a/typescript/experimental/browser/README.md +++ b/typescript/experimental/browser/README.md @@ -47,6 +47,7 @@ cd browser npm ci --ignore-scripts npm test npx playwright install chromium --only-shell +npx playwright install firefox webkit npm run test:browser ``` @@ -56,10 +57,11 @@ tests plus a shared validation corpus against three backends: the default native same-version backends must match diagnostics as well as acceptance outcomes. `npm run test:browser` bundles the actual private-package exports with **no Node -polyfills or externalized dependencies**, then runs Chromium against a temporary -loopback server. It verifies validation, repair, schema preflight, stalled-download -cancellation, and compiler-version rejection before fetching. It closes the -browser and server, including outstanding connections. No model credentials, +polyfills or externalized dependencies**, then runs Chromium, Firefox, and WebKit against a temporary loopback server. It +verifies validation, repair, schema preflight, stalled-download cancellation, and +compiler-version rejection before fetching. It also exercises the worker example, +concurrent job isolation, cancellation during synchronous validation, and cleanup. +It closes every worker, browser, and server, including outstanding connections. No model credentials, remote model calls, deployment, or paid inference are needed. The ordinary TypeChat tests do not install or invoke Playwright. On supported @@ -120,22 +122,64 @@ TypeChat's `Result` behavior and rejected data. Web Crypto requires HTTPS or a secure local context. Browser CSP must allow the application's WASM compilation. Loading and instance creation are asynchronous, but **validation is synchronous -on the calling thread**. A worker-based application integration needs separate -evaluation; this prototype does not hide synchronous work behind an async name. +on the calling thread**. Use an application-owned worker to keep that work off the +UI thread. A worker improves responsiveness, not the compiler's execution time. + +## Application-owned worker example + +From this directory: + +```sh +npm run example:worker +``` + +Open the printed loopback URL. The example validates a JSON batch against a schema +with a string enum, displays valid and invalid results, and keeps a main-thread +timer running. Cancel interrupts a running job; Ctrl+C stops the local server. +The development server serves the raw artifact without caching. A production +application would need deliberate asset compression and cache/version handling. + +[`examples/worker/client.ts`](./examples/worker/client.ts) and +[`examples/worker/validator.worker.ts`](./examples/worker/validator.worker.ts) are +copyable application code, **not additions to the package's public API**: + +- Each call owns one worker, compiler instance, and request batch. Jobs do not + share a mutable reactor. Concurrent calls cannot overwrite each other's schema. +- A caller-supplied `AbortSignal` covers the whole job. Termination rejects its + promise and stops even synchronous compiler work; no result is silently retried. + The demo combines a cancel button with a 60-second timeout. +- Success and failure both terminate the worker. Success additionally closes the + validator explicitly before sending the report. Termination during cancellation + destroys the worker rather than relying on JavaScript `finally` to run there. +- Schema/load errors, worker startup errors, clone failures, malformed requests, + and caller callback errors reject explicitly. Ordinary invalid JSON values + retain TypeChat's normal validation `Result`. + +The one-shot design deliberately favors simple ownership and cancellation over +throughput. It reloads/reinitializes a compiler per job. A reusable worker or +compiled-module cache would need separate lifecycle and cancellation design; this +investigation does not introduce a worker pool into TypeChat. ## Recorded verification -On Windows, Node.js 24.22.1 and Chromium 149.0.7827.55: +On Windows and Node.js 24.22.1: - The normal library/examples built, and all **411** normal tests passed, including CJS/ESM package/declaration tests and the existing enum regressions. -- **58** corpus outcomes passed in the real browser and matched the default +- **58** corpus outcomes passed in each real browser and matched the default native backend. WASM and the matching development native backend also produced identical diagnostics. - HTTP/network errors, pre-aborted loads, absent/truncated/oversized/corrupt artifacts, concurrent validator isolation, and idempotent disposal passed. - Real-browser tests ran with no Node globals, no proxy dependency, no live model calls, and `crossOriginIsolated === false`. +- Chromium 149.0.7827.55, Firefox 151.0, and Playwright WebKit 26.5 each passed the + same corpus, the runnable example UI, ten worker lifecycle/error checks, + cancellation after a partial network response, and all-worker termination. +- Review of the shared refactor confirmed that the minimal library, enum wire + mapping, diagnostic normalization, and model protocol definitions remain + unchanged. Existing custom-module diagnostics, program validation, lifecycle, + and CJS/ESM consumer tests were rechecked. One clean-install development-host run measured: @@ -162,9 +206,46 @@ The browser test enforces **provisional investigation ceilings**, for review: shipping; wall-clock performance is measured rather than asserted on arbitrary CI hardware. -Only the browser/OS combination above was exercised. This is not a complete -compatibility certification for every schema, browser, worker, CSP, or edge -runtime. The full existing native suite is not yet a full browser matrix. +### Larger worker workload and browser process memory + +One run per engine used a **500-property schema with 250 synchronous validations** +inside a worker. Main-thread timer ticks were counted only during validation: + +| Browser engine on Windows | Validation time | Main-thread ticks | Maximum WASM linear memory | +| --- | ---: | ---: | ---: | +| Chromium 149.0.7827.55 | 1,920 ms | 191 | 34,603,008 bytes | +| Firefox 151.0 | 19,389 ms | 1,843 | 34,603,008 bytes | +| Playwright WebKit 26.5 | 2,895 ms | 184 | 35,127,296 bytes | + +Firefox's substantially slower execution is an observed limitation, even though +the UI remains responsive. The worker's linear-memory report returns zero after +explicit close; this does not assert immediate OS-memory reclamation. + +The test also samples the **entire owned browser process tree** on Windows: + +| Engine | Baseline working-set sum | Largest sampled sum during worker workload | After worker jobs | +| --- | ---: | ---: | ---: | +| Chromium | 184 MB | 941 MB | 654 MB | +| Firefox | 481 MB | 1,098 MB | 1,024 MB | +| WebKit | 179 MB | 858 MB | 436 MB | + +These are decimal MB and sums of process working sets, not unique physical memory. +Shared pages can be counted more than once. Samples include the preceding corpus +and lifecycle probes in the same browser session; they do not establish the +incremental memory of a single job, a precise peak, or a leak. Browser/runtime +overhead and delayed reclamation make the cost materially larger than WASM linear +memory alone. Other operating systems report this metric as unavailable rather +than substituting a misleading value. + +A gzip-compressed compiler download was also delivered in 256 KiB chunks with +64 ms delays (nominally 4 MiB/s before backpressure). Loading, verifying, and +compiling it took roughly 4.0-4.5 seconds in these runs. This is a controlled local +transfer test, not a complete WAN simulation. + +Only the browser-engine/OS combinations above were exercised. Playwright WebKit on +Windows is **not Safari certification**. macOS, mobile/low-memory devices, production +CSPs, and real edge runtimes remain unverified. The full existing native suite is +not yet a full browser matrix. ## Upgrade, rollback, and recommendation @@ -183,9 +264,10 @@ Rollback is to stop opting into this package and its assets. The ordinary Node backend remains available and does not require the experimental dependencies. Keep the prototype out of the default workspace/build until reviewed explicitly. -**Recommendation: continue the isolated investigation; do not merge this as -supported browser functionality yet.** Mainline gates remain an explicit -upstream-stability/maintenance decision, review of the provisional API and costs, -broader browser/OS/worker coverage, and a full regression/compatibility assessment. +**Recommendation: the prototype is ready for draft design review, not for +supported browser functionality or a mainline merge.** Mainline gates remain an +explicit upstream-stability/maintenance decision, review of the provisional API +and substantial browser costs (especially Firefox latency), target-device/CSP +coverage, and a full regression/compatibility assessment. The existing root-package Node-proxy bundling problem remains separate; this package does not fix that public entry point or automatically resolve #534. diff --git a/typescript/experimental/browser/examples/worker/build.mjs b/typescript/experimental/browser/examples/worker/build.mjs new file mode 100644 index 00000000..3c052074 --- /dev/null +++ b/typescript/experimental/browser/examples/worker/build.mjs @@ -0,0 +1,27 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; + +export async function buildWorkerExample() { + const assets = new Map([ + ["/worker", ["text/html; charset=utf-8", await readFile(new URL("./index.html", import.meta.url))]] + ]); + for (const [source, route] of [["client.ts", "/worker-client.js"], ["validator.worker.ts", "/validator.worker.js"]]) { + const result = await build({ + entryPoints: [fileURLToPath(new URL(source, import.meta.url))], + platform: "browser", + format: "esm", + target: "es2021", + bundle: true, + minify: true, + write: false, + metafile: true, + logLevel: "silent" + }); + if (Object.values(result.metafile.outputs).some(output => output.imports.length !== 0)) { + throw new Error("Worker example bundles must be self-contained."); + } + assets.set(route, ["text/javascript", result.outputFiles[0].contents]); + } + return assets; +} diff --git a/typescript/experimental/browser/examples/worker/client.ts b/typescript/experimental/browser/examples/worker/client.ts new file mode 100644 index 00000000..fa6639eb --- /dev/null +++ b/typescript/experimental/browser/examples/worker/client.ts @@ -0,0 +1,100 @@ +import type { Result } from "@typechat/experimental-browser"; + +export interface ValidationJob { + wasmUrl: string; + schema: string; + typeName: string; + values: object[]; +} + +export interface ValidationReport { + results: Result[]; + loadCompileMs: number; + initializationMs: number; + validationMs: number; + maxLinearMemoryBytes: number; + closedLinearMemoryBytes: number; +} + +export type WorkerPhase = "loading" | "validating"; +export type WorkerReply = + | { kind: "phase"; phase: WorkerPhase } + | { kind: "result"; report: ValidationReport } + | { kind: "error"; name: string; message: string }; + +/** + * Application-owned, one-job-per-worker example. Aborting destroys that job's + * compiler, including synchronous validation; it does not interrupt a shared worker. + */ +export function validateInWorker( + workerUrl: string | URL, + job: ValidationJob, + options: { signal: AbortSignal; onPhase?: (phase: WorkerPhase) => void } +): Promise { + return new Promise((resolve, reject) => { + options.signal.throwIfAborted(); + const worker = new Worker(workerUrl, { type: "module" }); + let settled = false; + const cleanup = () => { + if (settled) { + return false; + } + settled = true; + options.signal.removeEventListener("abort", abort); + worker.removeEventListener("message", message); + worker.removeEventListener("error", failure); + worker.removeEventListener("messageerror", invalidMessage); + worker.terminate(); + return true; + }; + const fail = (cause: unknown) => { + if (cleanup()) { + reject(cause); + } + }; + const abort = () => fail(options.signal.reason); + const failure = (event: ErrorEvent) => { + event.preventDefault(); + fail(new Error(event.message || "The validation worker failed without error details.")); + }; + const invalidMessage = () => fail(new Error("Unable to deserialize a validation worker reply.")); + const message = (event: MessageEvent) => { + try { + const reply = event.data; + switch (reply?.kind) { + case "phase": + options.onPhase?.(reply.phase); + return; + case "result": + if (cleanup()) { + resolve(reply.report); + } + return; + case "error": { + const error = new Error(reply.message); + error.name = reply.name; + fail(error); + return; + } + default: + fail(new Error("Unexpected validation worker reply.")); + } + } catch (cause) { + fail(cause); + } + }; + worker.addEventListener("message", message); + worker.addEventListener("error", failure); + worker.addEventListener("messageerror", invalidMessage); + options.signal.addEventListener("abort", abort, { once: true }); + if (options.signal.aborted) { + abort(); + return; + } + try { + worker.postMessage(job); + } catch (cause) { + fail(cause); + } + }); +} diff --git a/typescript/experimental/browser/examples/worker/index.html b/typescript/experimental/browser/examples/worker/index.html new file mode 100644 index 00000000..05332c93 --- /dev/null +++ b/typescript/experimental/browser/examples/worker/index.html @@ -0,0 +1,66 @@ + + + + +Experimental TypeChat worker validation + +

Experimental TypeChat worker validation

+

Offline example: no model calls or credentials. Each run owns a worker and a +compiler. Cancellation terminates that worker. The experimental WASM download is +about 53 MB before compression.

+
enum Status { Active = "active", Paused = "paused" }
+interface Request { status: Status; value: number; }
+ + + + +

Ready

+

Main-thread timer ticks: 0

+

+
+
diff --git a/typescript/experimental/browser/examples/worker/serve.mjs b/typescript/experimental/browser/examples/worker/serve.mjs
new file mode 100644
index 00000000..0ad58995
--- /dev/null
+++ b/typescript/experimental/browser/examples/worker/serve.mjs
@@ -0,0 +1,31 @@
+import { readFile } from "node:fs/promises";
+import { createServer } from "node:http";
+import { buildWorkerExample } from "./build.mjs";
+
+const assets = await buildWorkerExample();
+assets.set("/tsc.wasm", [
+    "application/wasm",
+    await readFile(new URL("../../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url))
+]);
+const server = createServer((request, response) => {
+    const asset = assets.get(request.url);
+    if (request.method !== "GET" || !asset) {
+        response.writeHead(404);
+        response.end("Not found");
+        return;
+    }
+    response.writeHead(200, { "Content-Type": asset[0], "Cache-Control": "no-store" });
+    response.end(asset[1]);
+});
+server.listen(0, "127.0.0.1", () => {
+    const address = server.address();
+    if (!address || typeof address === "string") {
+        throw new Error("Unable to determine the worker example address.");
+    }
+    console.log(`Worker example: http://127.0.0.1:${address.port}/worker`);
+    console.log("Press Ctrl+C to stop the local example.");
+});
+process.once("SIGINT", () => {
+    server.closeAllConnections();
+    server.close();
+});
diff --git a/typescript/experimental/browser/examples/worker/tsconfig.json b/typescript/experimental/browser/examples/worker/tsconfig.json
new file mode 100644
index 00000000..b07e5f70
--- /dev/null
+++ b/typescript/experimental/browser/examples/worker/tsconfig.json
@@ -0,0 +1,9 @@
+{
+  "extends": "../../tsconfig.json",
+  "compilerOptions": {
+    "lib": ["es2021", "webworker"],
+    "types": [],
+    "noEmit": true
+  },
+  "include": ["client.ts", "validator.worker.ts"]
+}
diff --git a/typescript/experimental/browser/examples/worker/validator.worker.ts b/typescript/experimental/browser/examples/worker/validator.worker.ts
new file mode 100644
index 00000000..5efc7c54
--- /dev/null
+++ b/typescript/experimental/browser/examples/worker/validator.worker.ts
@@ -0,0 +1,65 @@
+import { loadBrowserTypeScriptCompiler, typeChatSchemaValidation } from "@typechat/experimental-browser";
+import type { ValidationJob, ValidationReport, WorkerReply } from "./client.js";
+
+function isJob(value: unknown): value is ValidationJob {
+    return typeof value === "object" && value !== null &&
+        "wasmUrl" in value && typeof value.wasmUrl === "string" &&
+        "schema" in value && typeof value.schema === "string" &&
+        "typeName" in value && typeof value.typeName === "string" &&
+        "values" in value && Array.isArray(value.values) &&
+        value.values.every((item: unknown) => typeof item === "object" && item !== null);
+}
+
+function reply(message: WorkerReply) {
+    self.postMessage(message);
+}
+
+self.addEventListener("message", async (event: MessageEvent) => {
+    try {
+        if (!isJob(event.data)) {
+            throw new Error("Expected a WASM URL, schema, type name, and array of JSON objects.");
+        }
+        const job = event.data;
+        reply({ kind: "phase", phase: "loading" });
+        const loadStart = performance.now();
+        const compiler = await loadBrowserTypeScriptCompiler(job.wasmUrl);
+        const loadCompileMs = performance.now() - loadStart;
+        const instanceStart = performance.now();
+        const validator = await compiler.createValidator(job.schema, job.typeName);
+        const initializationMs = performance.now() - instanceStart;
+        let report: Omit;
+        try {
+            const preflight = validator[typeChatSchemaValidation]();
+            if (!preflight.success) {
+                throw new Error(`Schema validation failed: ${preflight.message}`);
+            }
+            reply({ kind: "phase", phase: "validating" });
+            let maxLinearMemoryBytes = validator.getWasmMemoryByteLength();
+            const start = performance.now();
+            const results = job.values.map(value => {
+                const result = validator.validate(value);
+                maxLinearMemoryBytes = Math.max(maxLinearMemoryBytes, validator.getWasmMemoryByteLength());
+                return result;
+            });
+            report = {
+                results, loadCompileMs, initializationMs,
+                validationMs: performance.now() - start,
+                maxLinearMemoryBytes
+            };
+        } finally {
+            validator.close();
+        }
+        reply({
+            kind: "result",
+            report: { ...report, closedLinearMemoryBytes: validator.getWasmMemoryByteLength() }
+        });
+    } catch (cause) {
+        reply({
+            kind: "error",
+            name: cause instanceof Error ? cause.name : "Error",
+            message: cause instanceof Error ? cause.message : String(cause)
+        });
+    } finally {
+        self.close();
+    }
+}, { once: true });
diff --git a/typescript/experimental/browser/package.json b/typescript/experimental/browser/package.json
index 280890a2..198a6ae5 100644
--- a/typescript/experimental/browser/package.json
+++ b/typescript/experimental/browser/package.json
@@ -11,9 +11,10 @@
     }
   },
   "scripts": {
-    "build": "tsc -p tsconfig.json",
+    "build": "tsc -p tsconfig.json && tsc -p examples/worker/tsconfig.json",
     "test": "npm run build && node --test \"tests/*.test.mjs\"",
-    "test:browser": "npm run build && node --test \"tests/browser/*.test.mjs\""
+    "test:browser": "npm run build && node --test \"tests/browser/*.test.mjs\"",
+    "example:worker": "npm run build && node examples/worker/serve.mjs"
   },
   "engines": {
     "node": ">=24.22.1"
diff --git a/typescript/experimental/browser/tests/browser/browser.test.mjs b/typescript/experimental/browser/tests/browser/browser.test.mjs
index 0f862730..2d4f153d 100644
--- a/typescript/experimental/browser/tests/browser/browser.test.mjs
+++ b/typescript/experimental/browser/tests/browser/browser.test.mjs
@@ -1,120 +1,210 @@
 import assert from "node:assert/strict";
 import { readFile } from "node:fs/promises";
 import { createServer } from "node:http";
+import { once } from "node:events";
 import { test } from "node:test";
 import { fileURLToPath } from "node:url";
 import { gzipSync } from "node:zlib";
 import { build } from "esbuild";
-import { chromium } from "playwright";
+import { chromium, firefox, webkit } from "playwright";
+import { buildWorkerExample } from "../../examples/worker/build.mjs";
+import { sampleBrowserMemory } from "./process-memory.mjs";
 
-test("the public prototype runs real browser validation without Node shims or live models", { timeout: 180000 }, async t => {
-    const settings = {
-        bundle: true,
-        platform: "browser",
-        format: "iife",
-        target: "es2021",
-        minify: true,
-        write: false,
-        metafile: true,
-        logLevel: "silent"
-    };
-    const bundle = await build({
-        ...settings,
-        entryPoints: [fileURLToPath(new URL("./entry.mjs", import.meta.url))]
-    });
-    const library = await build({
-        ...settings,
-        format: "esm",
-        entryPoints: [fileURLToPath(new URL("../../dist/experimental/browser/src/index.js", import.meta.url))]
-    });
-    assert.ok(!Object.keys(bundle.metafile.inputs).some(path => /(?:^|\/)(?:undici|model\.js)(?:\/|$)/.test(path)));
-    assert.ok(Object.values(bundle.metafile.outputs).every(output => output.imports.length === 0));
-    assert.ok(Object.values(library.metafile.outputs).every(output => output.imports.length === 0));
-    const mismatch = await build({
-        ...settings,
-        entryPoints: [fileURLToPath(new URL("./version-mismatch.mjs", import.meta.url))],
-        plugins: [{
-            name: "test-compiler-version-mismatch",
-            setup(builder) {
-                builder.onResolve({ filter: /^typescript$/ }, () => ({ path: "version", namespace: "mismatch" }));
-                builder.onLoad({ filter: /.*/, namespace: "mismatch" }, () => ({
-                    contents: 'export const version = "0.0.0";',
-                    loader: "js"
-                }));
+for (const engine of [chromium, firefox, webkit]) {
+    test(`${engine.name()}: main-thread and worker validation without Node shims or live models`, { timeout: 240000 }, async t => {
+        const settings = {
+            bundle: true,
+            platform: "browser",
+            format: "iife",
+            target: "es2021",
+            minify: true,
+            write: false,
+            metafile: true,
+            logLevel: "silent"
+        };
+        const bundle = await build({
+            ...settings,
+            entryPoints: [fileURLToPath(new URL("./entry.mjs", import.meta.url))]
+        });
+        const library = await build({
+            ...settings,
+            format: "esm",
+            entryPoints: [fileURLToPath(new URL("../../dist/experimental/browser/src/index.js", import.meta.url))]
+        });
+        assert.ok(!Object.keys(bundle.metafile.inputs).some(path => /(?:^|\/)(?:undici|model\.js)(?:\/|$)/.test(path)));
+        assert.ok(Object.values(bundle.metafile.outputs).every(output => output.imports.length === 0));
+        assert.ok(Object.values(library.metafile.outputs).every(output => output.imports.length === 0));
+        const mismatch = await build({
+            ...settings,
+            entryPoints: [fileURLToPath(new URL("./version-mismatch.mjs", import.meta.url))],
+            plugins: [{
+                name: "test-compiler-version-mismatch",
+                setup(builder) {
+                    builder.onResolve({ filter: /^typescript$/ }, () => ({ path: "version", namespace: "mismatch" }));
+                    builder.onLoad({ filter: /.*/, namespace: "mismatch" }, () => ({
+                        contents: 'export const version = "0.0.0";',
+                        loader: "js"
+                    }));
+                }
+            }]
+        });
+        const wasm = await readFile(new URL("../../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url));
+        const compressedWasm = gzipSync(wasm);
+        const workerProbe = await build({
+            ...settings,
+            entryPoints: [fileURLToPath(new URL("./worker-entry.mjs", import.meta.url))]
+        });
+        let wasmRequests = 0;
+        let throttledChunks = 0;
+        const assets = new Map([
+            ["/", ["text/html", '']],
+            ["/mismatch", ["text/html", '']],
+            ["/probe.js", ["text/javascript", bundle.outputFiles[0].contents]],
+            ["/mismatch.js", ["text/javascript", mismatch.outputFiles[0].contents]],
+            ["/tsc.wasm", ["application/wasm", wasm]],
+            ["/worker-probe", ["text/html", '']],
+            ["/worker-probe.js", ["text/javascript", workerProbe.outputFiles[0].contents]],
+            ["/broken-worker.js", ["text/javascript", 'throw new Error("synthetic worker startup failure");']]
+        ]);
+        for (const [route, asset] of await buildWorkerExample()) assets.set(route, asset);
+        const server = createServer((request, response) => {
+            if (request.url === "/slow.wasm" || request.url === "/worker-slow.wasm") {
+                response.writeHead(200, { "Content-Type": "application/wasm" });
+                response.write(wasm.subarray(0, 100));
+                if (request.url === "/worker-slow.wasm") {
+                    response.once("close", () => server.emit("worker-slow-closed"));
+                    server.emit("worker-slow-started");
+                }
+                return;
             }
-        }]
-    });
-    const wasm = await readFile(new URL("../../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url));
-    let wasmRequests = 0;
-    const assets = new Map([
-        ["/", ["text/html", '']],
-        ["/mismatch", ["text/html", '']],
-        ["/probe.js", ["text/javascript", bundle.outputFiles[0].contents]],
-        ["/mismatch.js", ["text/javascript", mismatch.outputFiles[0].contents]],
-        ["/tsc.wasm", ["application/wasm", wasm]]
-    ]);
-    const server = createServer((request, response) => {
-        if (request.url === "/slow.wasm") {
-            response.writeHead(200, { "Content-Type": "application/wasm" });
-            response.write(wasm.subarray(0, 100));
-            return;
-        }
-        const asset = assets.get(request.url);
-        if (!asset) {
-            response.writeHead(404);
-            response.end();
-            return;
-        }
-        if (request.url === "/tsc.wasm") {
-            wasmRequests++;
+            if (request.url === "/throttled.wasm") {
+                response.writeHead(200, {
+                    "Content-Type": "application/wasm",
+                    "Content-Encoding": "gzip",
+                    "Content-Length": compressedWasm.length,
+                    "Cache-Control": "no-store"
+                });
+                let offset = 0;
+                let timer;
+                const send = () => {
+                    if (offset >= compressedWasm.length) {
+                        response.end();
+                        return;
+                    }
+                    const chunk = compressedWasm.subarray(offset, offset + 256 * 1024);
+                    offset += chunk.length;
+                    throttledChunks++;
+                    if (response.write(chunk)) {
+                        schedule();
+                    } else {
+                        response.once("drain", schedule);
+                    }
+                };
+                const schedule = () => { timer = setTimeout(send, 64); };
+                response.once("close", () => {
+                    clearTimeout(timer);
+                    response.removeListener("drain", schedule);
+                });
+                send();
+                return;
+            }
+            const asset = assets.get(request.url);
+            if (!asset) {
+                response.writeHead(404);
+                response.end();
+                return;
+            }
+            if (request.url === "/tsc.wasm") {
+                wasmRequests++;
+            }
+            response.writeHead(200, { "Content-Type": asset[0], "Cache-Control": "no-store" });
+            response.end(asset[1]);
+        });
+        let browser;
+        let browserServer;
+        t.after(async () => {
+            try {
+                await browser?.close();
+            } finally {
+                await browserServer?.close();
+                server.closeAllConnections();
+                await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
+            }
+        });
+        await new Promise((resolve, reject) => {
+            server.once("error", reject);
+            server.listen(0, "127.0.0.1", resolve);
+        });
+        const address = server.address();
+        assert.ok(address && typeof address !== "string");
+        browserServer = await engine.launchServer({ headless: true });
+        browser = await engine.connect(browserServer.wsEndpoint());
+        const page = await browser.newPage();
+        const baselineMemory = await sampleBrowserMemory(browserServer.process().pid);
+        const errors = [];
+        page.on("pageerror", error => errors.push(error.message));
+        await page.goto(`http://127.0.0.1:${address.port}`);
+        const result = await page.evaluate(() => globalThis.runBrowserProbe());
+        assert.equal(result.nodeGlobalsAbsent, true);
+        assert.equal(result.liveModelCalls, 0);
+        assert.equal(result.stalledLoadTimedOut, true);
+        assert.equal(wasmRequests, 1, "Validators should reuse the compiled module rather than refetching WASM.");
+        assert.deepEqual(errors, []);
+        await page.goto(`http://127.0.0.1:${address.port}/mismatch`);
+        assert.deepEqual(await page.evaluate(() => globalThis.runMismatchProbe()), { rejected: true, fetchCalls: 0 });
+        await page.goto(`http://127.0.0.1:${address.port}/worker`);
+        await page.locator("#run").click();
+        await page.waitForFunction(() => document.getElementById("status").textContent === "Completed; worker disposed");
+        const demo = JSON.parse(await page.locator("#result").innerText());
+        assert.deepEqual(demo.results.map(result => result.success), [true, false]);
+        assert.equal(demo.closedLinearMemoryBytes, 0);
+        await page.goto(`http://127.0.0.1:${address.port}/worker-probe`);
+        const workerChecks = await page.evaluate(() => globalThis.runWorkerChecks());
+        assert.equal(workerChecks.checks.length, 10);
+        assert.ok(throttledChunks > 1, "The compressed artifact must be delivered over multiple delayed chunks.");
+        const slowStarted = once(server, "worker-slow-started");
+        await page.evaluate(() => globalThis.startStalledWorker());
+        await slowStarted;
+        const slowClosed = once(server, "worker-slow-closed");
+        assert.deepEqual(await page.evaluate(() => globalThis.abortStalledWorker()), { aborted: true });
+        await slowClosed;
+        await page.evaluate(() => globalThis.startWorkerStress());
+        await page.waitForFunction(() => globalThis.workerStressPhase === "validating");
+        const processMemorySamples = [];
+        for (let count = 0; count < 4 && await page.evaluate(() => globalThis.workerStressActive); count++) {
+            const sample = await sampleBrowserMemory(browserServer.process().pid);
+            processMemorySamples.push(sample);
+            if (!sample.supported) break;
         }
-        response.writeHead(200, { "Content-Type": asset[0], "Cache-Control": "no-store" });
-        response.end(asset[1]);
-    });
-    let browser;
-    t.after(async () => {
-        await browser?.close();
-        server.closeAllConnections();
-        await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
-    });
-    await new Promise((resolve, reject) => {
-        server.once("error", reject);
-        server.listen(0, "127.0.0.1", resolve);
+        const workerStress = await page.evaluate(() => globalThis.workerStressResult);
+        await Promise.all(page.workers().map(worker => once(worker, "close")));
+        assert.equal(page.workers().length, 0, "All one-shot workers must be terminated after settling.");
+        const afterJobsMemory = await sampleBrowserMemory(browserServer.process().pid);
+        assert.deepEqual(errors, []);
+        const metrics = {
+            browser: `${engine.name()} ${browser.version()}`,
+            platform: process.platform,
+            compiler: result.compiler,
+            corpusOutcomes: result.observations.length,
+            libraryJavascriptBytes: library.outputFiles[0].contents.length,
+            libraryJavascriptGzipBytes: gzipSync(library.outputFiles[0].contents).length,
+            testBundleBytes: bundle.outputFiles[0].contents.length,
+            wasmBytes: wasm.length,
+            wasmGzipBytes: compressedWasm.length,
+            loadCompileMs: Math.round(result.loadCompileMs),
+            warmInitializationMs: result.warmInitializationMs.map(Math.round),
+            crossOriginIsolated: result.crossOriginIsolated,
+            largeSchema: result.largeSchema,
+            workerChecks,
+            workerStress,
+            browserProcessTree: { baselineMemory, inFlightSamples: processMemorySamples, afterJobsMemory }
+        };
+        assert.ok(metrics.libraryJavascriptBytes <= 512 * 1024, "Prototype JavaScript exceeded 512 KiB.");
+        assert.ok(metrics.libraryJavascriptGzipBytes <= 128 * 1024, "Compressed prototype JavaScript exceeded 128 KiB.");
+        assert.ok(metrics.wasmBytes <= 60 * 1024 * 1024, "Prototype WASM exceeded 60 MiB.");
+        assert.ok(metrics.wasmGzipBytes <= 16 * 1024 * 1024, "Compressed prototype WASM exceeded 16 MiB.");
+        assert.ok(metrics.largeSchema.finalLinearMemoryBytes <= 128 * 1024 * 1024, "One validator exceeded 128 MiB of linear memory.");
+        assert.ok(workerStress.maxLinearMemoryBytes <= 128 * 1024 * 1024, "The worker validator exceeded 128 MiB of linear memory.");
+        t.diagnostic(JSON.stringify(metrics));
     });
-    const address = server.address();
-    assert.ok(address && typeof address !== "string");
-    browser = await chromium.launch({ headless: true });
-    const page = await browser.newPage();
-    const errors = [];
-    page.on("pageerror", error => errors.push(error.message));
-    await page.goto(`http://127.0.0.1:${address.port}`);
-    const result = await page.evaluate(() => globalThis.runBrowserProbe());
-    assert.equal(result.nodeGlobalsAbsent, true);
-    assert.equal(result.liveModelCalls, 0);
-    assert.equal(result.stalledLoadTimedOut, true);
-    assert.equal(wasmRequests, 1, "Validators should reuse the compiled module rather than refetching WASM.");
-    assert.deepEqual(errors, []);
-    await page.goto(`http://127.0.0.1:${address.port}/mismatch`);
-    assert.deepEqual(await page.evaluate(() => globalThis.runMismatchProbe()), { rejected: true, fetchCalls: 0 });
-    const metrics = {
-        browser: `Chromium ${browser.version()}`,
-        platform: process.platform,
-        compiler: result.compiler,
-        corpusOutcomes: result.observations.length,
-        libraryJavascriptBytes: library.outputFiles[0].contents.length,
-        libraryJavascriptGzipBytes: gzipSync(library.outputFiles[0].contents).length,
-        testBundleBytes: bundle.outputFiles[0].contents.length,
-        wasmBytes: wasm.length,
-        wasmGzipBytes: gzipSync(wasm).length,
-        loadCompileMs: Math.round(result.loadCompileMs),
-        warmInitializationMs: result.warmInitializationMs.map(Math.round),
-        crossOriginIsolated: result.crossOriginIsolated,
-        largeSchema: result.largeSchema
-    };
-    assert.ok(metrics.libraryJavascriptBytes <= 512 * 1024, "Prototype JavaScript exceeded 512 KiB.");
-    assert.ok(metrics.libraryJavascriptGzipBytes <= 128 * 1024, "Compressed prototype JavaScript exceeded 128 KiB.");
-    assert.ok(metrics.wasmBytes <= 60 * 1024 * 1024, "Prototype WASM exceeded 60 MiB.");
-    assert.ok(metrics.wasmGzipBytes <= 16 * 1024 * 1024, "Compressed prototype WASM exceeded 16 MiB.");
-    assert.ok(metrics.largeSchema.finalLinearMemoryBytes <= 128 * 1024 * 1024, "One validator exceeded 128 MiB of linear memory.");
-    t.diagnostic(JSON.stringify(metrics));
-});
+}
diff --git a/typescript/experimental/browser/tests/browser/process-memory.mjs b/typescript/experimental/browser/tests/browser/process-memory.mjs
new file mode 100644
index 00000000..c7033603
--- /dev/null
+++ b/typescript/experimental/browser/tests/browser/process-memory.mjs
@@ -0,0 +1,42 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+
+const execute = promisify(execFile);
+
+export async function sampleBrowserMemory(processId) {
+    if (process.platform !== "win32") {
+        return { supported: false, reason: "Process-tree working-set sampling is implemented only for Windows." };
+    }
+    if (!Number.isSafeInteger(processId) || processId <= 0) {
+        throw new Error("Expected the PID of the test-owned browser process.");
+    }
+    const script = `
+$ErrorActionPreference = 'Stop'
+$processes = @(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize)
+$ids = [System.Collections.Generic.HashSet[uint32]]::new()
+$null = $ids.Add(${processId})
+do {
+    $added = $false
+    foreach ($process in $processes) {
+        if ($ids.Contains($process.ParentProcessId) -and $ids.Add($process.ProcessId)) { $added = $true }
+    }
+} while ($added)
+$owned = @($processes | Where-Object { $ids.Contains($_.ProcessId) })
+if (-not ($owned | Where-Object { $_.ProcessId -eq ${processId} })) { throw 'Browser process no longer exists.' }
+[pscustomobject]@{
+    supported = $true
+    processCount = $owned.Count
+    workingSetSumBytes = [long](($owned | Measure-Object WorkingSetSize -Sum).Sum)
+} | ConvertTo-Json -Compress
+`;
+    const { stdout } = await execute("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
+        windowsHide: true,
+        timeout: 30000,
+        maxBuffer: 1024 * 1024
+    });
+    const result = JSON.parse(stdout);
+    if (!Number.isFinite(result.workingSetSumBytes) || result.workingSetSumBytes <= 0) {
+        throw new Error("The browser process-memory sample was invalid.");
+    }
+    return result;
+}
diff --git a/typescript/experimental/browser/tests/browser/worker-entry.mjs b/typescript/experimental/browser/tests/browser/worker-entry.mjs
new file mode 100644
index 00000000..fc39c314
--- /dev/null
+++ b/typescript/experimental/browser/tests/browser/worker-entry.mjs
@@ -0,0 +1,154 @@
+import { validateInWorker } from "../../examples/worker/client.ts";
+
+const numericSchema = "export interface Probe { value: number; }";
+const workerUrl = "/validator.worker.js";
+const signal = () => AbortSignal.timeout(60000);
+const job = (schema = numericSchema, values = [{ value: 1 }], wasmPath = "/tsc.wasm") => ({
+    wasmUrl: new URL(wasmPath, location.href).href,
+    schema,
+    typeName: "Probe",
+    values
+});
+
+function check(condition, message) {
+    if (!condition) throw new Error(message);
+}
+
+async function expectFailure(operation, pattern) {
+    try {
+        await operation();
+    } catch (error) {
+        check(pattern.test(`${error.name}: ${error.message}`), `Unexpected worker error: ${error}`);
+        return;
+    }
+    throw new Error("Expected the worker operation to fail.");
+}
+
+function largeJob(iterations = 250) {
+    const schema = "export interface Probe {\n" +
+        Array.from({ length: 500 }, (_, index) => `field${index}: number;`).join("\n") + "\n}";
+    const value = Object.fromEntries(Array.from({ length: 500 }, (_, index) => [`field${index}`, index]));
+    return job(schema, Array(iterations).fill(value));
+}
+
+globalThis.runWorkerChecks = async () => {
+    const checks = [];
+    const enumSchema = 'export enum Status { Active = "active" } export interface Probe { status: Status; value: number; }';
+    const report = await validateInWorker(workerUrl, job(
+        enumSchema,
+        [{ status: "active", value: 1 }, { status: "wrong", value: 1 }],
+        "/throttled.wasm"
+    ), { signal: signal() });
+    check(report.results[0].success && !report.results[1].success, "Worker enum validation diverged.");
+    check(report.closedLinearMemoryBytes === 0, "Worker did not close its compiler.");
+    checks.push("valid/invalid enum values over a throttled compressed download");
+
+    await expectFailure(() => validateInWorker(workerUrl, job(
+        "export interface Probe { value: MissingType; }"
+    ), { signal: signal() }), /Schema validation failed/);
+    checks.push("schema configuration errors");
+
+    await expectFailure(() => validateInWorker(workerUrl, job(numericSchema, [], "/missing.wasm"), {
+        signal: signal()
+    }), /HTTP 404/);
+    checks.push("HTTP errors");
+
+    await expectFailure(() => validateInWorker(workerUrl, { ...job(), values: [null] }, {
+        signal: signal()
+    }), /Expected a WASM URL/);
+    checks.push("invalid worker requests");
+
+    await expectFailure(() => validateInWorker(workerUrl, job(numericSchema, [{ callback() {} }]), {
+        signal: signal()
+    }), /DataCloneError/);
+    checks.push("uncloneable requests");
+
+    await expectFailure(() => validateInWorker("/broken-worker.js", job(), {
+        signal: signal()
+    }), /worker startup failure/);
+    checks.push("worker startup errors");
+
+    await expectFailure(() => validateInWorker(workerUrl, job(), {
+        signal: AbortSignal.abort()
+    }), /AbortError/);
+    checks.push("pre-aborted requests");
+
+    await expectFailure(() => validateInWorker(workerUrl, job(), {
+        signal: signal(),
+        onPhase() { throw new Error("synthetic UI callback failure"); }
+    }), /synthetic UI callback failure/);
+    checks.push("caller callback errors");
+
+    const [numbers, strings] = await Promise.all([
+        validateInWorker(workerUrl, job(numericSchema, [{ value: 1 }, { value: "x" }]), { signal: signal() }),
+        validateInWorker(workerUrl, job("export interface Probe { value: string; }", [{ value: 1 }, { value: "x" }]), {
+            signal: signal()
+        })
+    ]);
+    check(numbers.results[0].success && !numbers.results[1].success, "Numeric job leaked state.");
+    check(!strings.results[0].success && strings.results[1].success, "String job leaked state.");
+    checks.push("concurrent job isolation");
+
+    const controller = new AbortController();
+    let started = false;
+    await expectFailure(() => validateInWorker(workerUrl, largeJob(1000), {
+        signal: AbortSignal.any([controller.signal, signal()]),
+        onPhase(phase) {
+            if (phase === "validating") {
+                started = true;
+                controller.abort();
+            }
+        }
+    }), /AbortError/);
+    check(started, "Cancellation was not exercised during validation.");
+    checks.push("termination during synchronous validation");
+    return { checks, throttledLoadCompileMs: Math.round(report.loadCompileMs) };
+};
+
+globalThis.startStalledWorker = () => {
+    const controller = new AbortController();
+    const result = validateInWorker(workerUrl, job(numericSchema, [], "/worker-slow.wasm"), {
+        signal: AbortSignal.any([controller.signal, signal()])
+    }).then(
+        () => { throw new Error("A stalled worker unexpectedly succeeded."); },
+        error => {
+            check(error.name === "AbortError", `Unexpected stalled worker result: ${error}`);
+            return { aborted: true };
+        }
+    );
+    globalThis.abortStalledWorker = () => {
+        controller.abort();
+        return result;
+    };
+};
+
+globalThis.startWorkerStress = () => {
+    let ticks = 0;
+    let timer;
+    globalThis.workerStressActive = true;
+    globalThis.workerStressPhase = "loading";
+    globalThis.workerStressResult = validateInWorker(workerUrl, largeJob(), {
+        signal: signal(),
+        onPhase(phase) {
+            globalThis.workerStressPhase = phase;
+            if (phase === "validating") {
+                timer = setInterval(() => ticks++, 10);
+            }
+        }
+    }).then(report => {
+        check(report.results.length === 250 && report.results.every(result => result.success), "Stress results were incorrect.");
+        check(ticks > 0, "The main-thread heartbeat did not run during worker validation.");
+        check(report.closedLinearMemoryBytes === 0, "Stress worker did not close its compiler.");
+        return {
+            properties: 500,
+            validations: report.results.length,
+            mainThreadTicksDuringValidation: ticks,
+            validationMs: Math.round(report.validationMs),
+            maxLinearMemoryBytes: report.maxLinearMemoryBytes,
+            closedLinearMemoryBytes: report.closedLinearMemoryBytes
+        };
+    }).finally(() => {
+        clearInterval(timer);
+        globalThis.workerStressActive = false;
+    });
+};

From 90189a723128d45438454c2f66f0ed9982bd941a Mon Sep 17 00:00:00 2001
From: Robert Gruen 
Date: Mon, 23 Nov 2026 16:37:42 -0800
Subject: [PATCH 3/5] Record integrated browser prototype verification

Document the 424 passing ordinary tests, disabled live suite, and both browser memory ceilings.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
 typescript/experimental/browser/README.md | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/typescript/experimental/browser/README.md b/typescript/experimental/browser/README.md
index 24913bef..88e6a842 100644
--- a/typescript/experimental/browser/README.md
+++ b/typescript/experimental/browser/README.md
@@ -164,8 +164,10 @@ investigation does not introduce a worker pool into TypeChat.
 
 On Windows and Node.js 24.22.1:
 
-- The normal library/examples built, and all **411** normal tests passed,
+- After integrating main's opt-in live-test work, the normal library/examples
+  built and all **424** ordinary tests passed with `TYPECHAT_LIVE_TESTS=0`,
   including CJS/ESM package/declaration tests and the existing enum regressions.
+  The live API suite remained disabled; no hosted model was called.
 - **58** corpus outcomes passed in each real browser and matched the default
   native backend. WASM and the matching development native backend also produced
   identical diagnostics.
@@ -201,8 +203,9 @@ peak process memory, or immediate garbage collection after closing.
 
 The browser test enforces **provisional investigation ceilings**, for review:
 512 KiB minified / 128 KiB gzipped JavaScript; 60 MiB raw / 16 MiB gzipped WASM;
-128 MiB of linear memory for the single 100-property test validator after its
-100 validations. Agree target-device startup and responsiveness budgets before
+128 MiB of linear memory for both the 100-property/100-validation main-thread
+probe and the 500-property/250-validation worker probe. Agree target-device startup
+and responsiveness budgets before
 shipping; wall-clock performance is measured rather than asserted on arbitrary
 CI hardware.
 

From 81666a95414e03be5067032e318634c9c4901c6f Mon Sep 17 00:00:00 2001
From: Robert Gruen 
Date: Mon, 23 Nov 2026 17:50:27 -0800
Subject: [PATCH 4/5] Fix experimental validator lifetime and record
 conformance gaps

Eliminate the closed-validator compiled-module retaining path. Add independent stability and Unicode regressions, confirm the Unicode failure on pristine main, and document the verified retail Firefox dedicated-worker comparison. Keep the two upstream conformance failures explicit.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
 typescript/experimental/browser/README.md     | 153 ++++-
 .../experimental/browser/src/compiler.ts      | 129 +++--
 .../browser/tests/repro-unicode-enum.mjs      |  45 ++
 .../browser/tests/stability.test.mjs          | 548 ++++++++++++++++++
 4 files changed, 806 insertions(+), 69 deletions(-)
 create mode 100644 typescript/experimental/browser/tests/repro-unicode-enum.mjs
 create mode 100644 typescript/experimental/browser/tests/stability.test.mjs

diff --git a/typescript/experimental/browser/README.md b/typescript/experimental/browser/README.md
index 88e6a842..84113b91 100644
--- a/typescript/experimental/browser/README.md
+++ b/typescript/experimental/browser/README.md
@@ -9,6 +9,54 @@ and native TypeScript 7.0.2 backend. This package is deliberately outside its np
 workspaces and normal build/test commands. Installing TypeChat does not install
 this experimental compiler or its WASM artifact.
 
+## Current shipping blockers
+
+The expanded stability investigation found an upstream Unicode conformance
+failure: both the stable native backend and the pinned WASM backend reject a
+valid string-enum value containing a lone surrogate immediately followed by
+U+FEFF. The altered value without U+FEFF is also rejected. See
+[microsoft/TypeScript#65458](https://github.com/microsoft/TypeScript/issues/65458).
+This is a false rejection, not permission to widen the schema or accept arbitrary
+strings.
+
+The same failure was reproduced on an **untouched main snapshot** at
+[`0ef51b0`](https://github.com/microsoft/TypeChat/commit/0ef51b05e6f9c0373870c2754070e7f12b470bf7),
+using Node.js 24.22.1 and the normal TypeScript 7.0.2 backend. All 21 library
+source/runtime-manifest files were checked against that commit, allowing only
+Git's Windows line-ending conversion, then the original package was built.
+The loader/refactor in this branch is therefore not the origin of the failure.
+The leading-U+FEFF control passes; the lone-surrogate-plus-U+FEFF declared value
+fails despite successful schema preflight.
+
+[`tests/repro-unicode-enum.mjs`](./tests/repro-unicode-enum.mjs) is a standalone
+reproduction for the existing upstream report. Copy it into the `typescript`
+directory of a fresh TypeChat checkout at the commit above, then build and run
+it **from that directory**:
+
+```sh
+npm ci
+npm run build
+node repro-unicode-enum.mjs
+```
+
+The script resolves TypeChat from the current checkout (not from the prototype),
+prints the compiler versions, code units, preflight and validation results, then
+exits nonzero when the declared value is rejected. It uses no WASM, model, or
+credentials. This reproduction has been prepared; no new upstream comment or
+pull request has been posted.
+
+The two independent semantic regression checks remain **intentionally failing**
+in `npm test`; native/WASM parity alone cannot catch a shared upstream defect.
+Do not treat the earlier green corpus, or normal repository CI, as resolving
+this blocker. No dependency upgrade, decoder patch, or validation bypass has
+been applied.
+
+The investigation also found and fixed a prototype lifetime bug: retaining a
+closed validator previously retained its compiled module through the loader's
+closure context. Validator closures are now constructed outside that context.
+The regression inspects a strong heap-reference path rather than relying on a
+garbage-collection timeout; it fails before the fix and passes afterwards.
+
 ## Design and boundaries
 
 - The native and browser adapters share schema generation, enum normalization,
@@ -55,6 +103,25 @@ npm run test:browser
 tests plus a shared validation corpus against three backends: the default native
 7.0.2 compiler, the matching development native compiler, and WASM. The two
 same-version backends must match diagnostics as well as acceptance outcomes.
+The additional stability suite also asserts independently expected semantics;
+it currently reports the two Unicode failures described above.
+
+After the lifetime fix, the complete experimental Node run reports **21 passed,
+2 failed** (the Unicode checks), and **3 skipped** opt-in browser recovery checks.
+Those three recovery checks were run separately in Chromium, Firefox, and WebKit
+and all passed: seven workers closed per engine, with no remaining abort
+listeners, page errors, or fetches for the intentionally mismatched compiler.
+A final combined run of the Node checks, full three-engine browser matrix, and
+opt-in recovery checks reported **27 passed, 2 failed, 0 skipped**. Only the two
+independently expected Unicode cases remain red. The ordinary repository build
+and 424-test suite were also rerun successfully, with live tests disabled.
+To repeat that focused recovery run in PowerShell:
+
+```powershell
+$env:TYPECHAT_STABILITY_BROWSERS = "1"
+node --test --test-concurrency=1 --test-timeout=90000 --test-name-pattern="^stability: (chromium|firefox|webkit)" tests\stability.test.mjs
+Remove-Item Env:\TYPECHAT_STABILITY_BROWSERS
+```
 
 `npm run test:browser` bundles the actual private-package exports with **no Node
 polyfills or externalized dependencies**, then runs Chromium, Firefox, and WebKit against a temporary loopback server. It
@@ -183,7 +250,8 @@ On Windows and Node.js 24.22.1:
   unchanged. Existing custom-module diagnostics, program validation, lifecycle,
   and CJS/ESM consumer tests were rechecked.
 
-One clean-install development-host run measured:
+The initial clean-install development-host run, before the lifetime follow-up,
+measured:
 
 | Measurement | Observed |
 | --- | ---: |
@@ -220,8 +288,70 @@ inside a worker. Main-thread timer ticks were counted only during validation:
 | Firefox 151.0 | 19,389 ms | 1,843 | 34,603,008 bytes |
 | Playwright WebKit 26.5 | 2,895 ms | 184 | 35,127,296 bytes |
 
-Firefox's substantially slower execution is an observed limitation, even though
-the UI remains responsive. The worker's linear-memory report returns zero after
+These Firefox numbers were obtained under Playwright's Juggler debugger. Further
+investigation found that the installed debugger lacks the `allowUnobservedWasm`
+setting, which can pin WASM to baseline compilation. Its frame actors are
+registered before the command-line flag check and attach dedicated workers;
+removing the Juggler launch flag alone did not remove the confound.
+
+A bounded follow-up used the same installed Firefox 151.0 binary, compiler,
+artifact, fixed built library, fresh profiles, and 500-property/250-validation
+workload. Direct launches used no Playwright connection or devtools; the page
+reported results to its loopback server:
+
+| Firefox execution mode | Load/verify/compile | Initialization | Preflight | First validation | Warm validation mean | All 250 validations |
+| --- | ---: | ---: | ---: | ---: | ---: | ---: |
+| Direct launch, dedicated worker | 829 ms | 104 ms | 35 ms | 91 ms | 76.09 ms | 19,040 ms |
+| Playwright-attached, dedicated worker | 932 ms | 106 ms | 36 ms | 88 ms | 77.39 ms | 19,360 ms |
+| Direct launch, unobserved service worker | 515 ms | 42 ms | 10 ms | 15 ms | 8.57 ms | 2,152 ms |
+
+Installed Juggler excludes non-dedicated workers from its attachment hook. The
+roughly 9x improvement in the unobserved case strongly supports a debugger
+confound. **It also changes worker type**, so it is not a controlled single-setting
+experiment or retail-Firefox/dedicated-worker certification. It is not a reason
+to change the application example to a service worker. Do not present the original
+automated ratio as an intrinsic Firefox production-performance result.
+
+These are three successful workloads, not a statistical sample. The attached
+control explicitly enabled both WASM JIT preferences after an earlier compile
+failure; failed setup attempts contributed no timings. All accepted results and
+untimed changed-value rejection/recovery controls passed. Each profile fetched
+the raw artifact once over uncached loopback HTTP; host filesystem caches were
+warm.
+
+#### Retail Firefox dedicated-worker confirmation
+
+A subsequent comparison used the official
+[Mozilla Firefox 151.0 Windows x64 release](https://archive.mozilla.org/pub/firefox/releases/151.0/win64/en-US/Firefox%20Setup%20151.0.exe),
+extracted into an owned temporary directory without installation. Its installer
+matched Mozilla's SHA-512 manifest; the installer and executable had valid
+Mozilla Corporation Authenticode signatures. The release resources contained no
+Juggler code. No existing profile, Playwright connection, devtools, JIT override,
+or sandbox change was used.
+
+All three fresh profiles used the **same dedicated-worker workload** and the same
+fixed built TypeChat library, compiler version, and verified WASM artifact:
+
+| Retail Firefox run | Load/verify/compile | Initialization | First validation | Warm validation mean | All 250 validations |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| 1 | 504 ms | 39 ms | 15 ms | 8.53 ms | 2,141 ms |
+| 2 | 491 ms | 43 ms | 16 ms | 8.68 ms | 2,180 ms |
+| 3 | 503 ms | 39 ms | 13 ms | 8.62 ms | 2,161 ms |
+
+Preflight took 9 ms per run. Each run also rejected a changed string-valued
+candidate, accepted its numeric replacement, rejected use after close, and
+reported zero owned linear memory after close. The downloaded browser, profiles,
+server, and helpers were removed afterwards.
+
+**The approximately 19-second automated slowdown was not reproduced in retail
+Firefox.** The 2,161 ms median supports a harness-confound explanation rather
+than an intrinsic Firefox performance problem. Retail and Playwright had the same
+151.0 version but different BuildIDs (`20260516144017` and `20260611193205`), so
+this is not a pure single-setting causal experiment. It is three localhost runs
+on one desktop, not a production latency guarantee, retail memory profile, mobile
+result, or full retail-browser conformance certification.
+
+The worker's linear-memory report returns zero after
 explicit close; this does not assert immediate OS-memory reclamation.
 
 The test also samples the **entire owned browser process tree** on Windows:
@@ -237,8 +367,9 @@ Shared pages can be counted more than once. Samples include the preceding corpus
 and lifecycle probes in the same browser session; they do not establish the
 incremental memory of a single job, a precise peak, or a leak. Browser/runtime
 overhead and delayed reclamation make the cost materially larger than WASM linear
-memory alone. Other operating systems report this metric as unavailable rather
-than substituting a misleading value.
+memory alone. These samples also used the instrumented Playwright builds; retail
+Firefox memory was not reprofiled. Other operating systems report this metric as
+unavailable rather than substituting a misleading value.
 
 A gzip-compressed compiler download was also delivered in 256 KiB chunks with
 64 ms delays (nominally 4 MiB/s before backpressure). Loading, verifying, and
@@ -248,7 +379,8 @@ transfer test, not a complete WAN simulation.
 Only the browser-engine/OS combinations above were exercised. Playwright WebKit on
 Windows is **not Safari certification**. macOS, mobile/low-memory devices, production
 CSPs, and real edge runtimes remain unverified. The full existing native suite is
-not yet a full browser matrix.
+not yet a full browser matrix, and the retail Firefox probe is a focused workload
+check rather than the full automated corpus.
 
 ## Upgrade, rollback, and recommendation
 
@@ -267,10 +399,11 @@ Rollback is to stop opting into this package and its assets. The ordinary Node
 backend remains available and does not require the experimental dependencies.
 Keep the prototype out of the default workspace/build until reviewed explicitly.
 
-**Recommendation: the prototype is ready for draft design review, not for
-supported browser functionality or a mainline merge.** Mainline gates remain an
+**Recommendation: retain draft-only status, not supported browser functionality
+or a mainline merge.** Mainline gates remain an
 explicit upstream-stability/maintenance decision, review of the provisional API
-and substantial browser costs (especially Firefox latency), target-device/CSP
-coverage, and a full regression/compatibility assessment.
+and startup/memory costs on target devices,
+resolution of the Unicode conformance failure, target-device/CSP coverage, and a
+full regression/compatibility assessment.
 The existing root-package Node-proxy bundling problem remains separate; this
 package does not fix that public entry point or automatically resolve #534.
diff --git a/typescript/experimental/browser/src/compiler.ts b/typescript/experimental/browser/src/compiler.ts
index 599e1c0c..e9ed8b76 100644
--- a/typescript/experimental/browser/src/compiler.ts
+++ b/typescript/experimental/browser/src/compiler.ts
@@ -1,6 +1,6 @@
 import { version } from "typescript";
 import { API, type Snapshot } from "typescript/sync";
-import { instantiateWasm, WasmTransport } from "typescript/wasm";
+import { instantiateWasm, WasmTransport, type WasmReactorInstance } from "typescript/wasm";
 import {
     configFileName, createCompiler, jsonFileName, schemaFileName, schemaValidationFileName
 } from "../../../src/ts/compiler.js";
@@ -83,70 +83,81 @@ export async function loadBrowserTypeScriptCompiler(
     return {
         version: compilerVersion,
         async createValidator(schema: string, typeName: string, schemaValidationTypeName = typeName) {
-            const instance = await instantiateWasm(module);
-            if (!("memory" in instance.exports) || !(instance.exports.memory instanceof WebAssembly.Memory)) {
-                throw new Error("The TypeScript WASM reactor did not export its memory.");
-            }
-            let memory: WebAssembly.Memory | undefined = instance.exports.memory;
-            let transport: WasmTransport | undefined;
-            let api: API | undefined;
-            let snapshot: Snapshot | undefined;
-            const close = () => {
-                const currentApi = api;
-                const currentTransport = transport;
-                api = undefined;
-                transport = undefined;
-                snapshot = undefined;
-                memory = undefined;
-                if (currentApi) {
-                    currentApi.close();
-                } else {
-                    currentTransport?.close();
+            return createValidatorFromInstance(
+                await instantiateWasm(module), schema, typeName, schemaValidationTypeName
+            );
+        }
+    };
+}
+
+// Keep returned validator closures outside the loader's context, which owns the compiled module.
+function createValidatorFromInstance(
+    instance: WasmReactorInstance,
+    schema: string,
+    typeName: string,
+    schemaValidationTypeName: string
+): BrowserTypeScriptValidator {
+    if (!("memory" in instance.exports) || !(instance.exports.memory instanceof WebAssembly.Memory)) {
+        throw new Error("The TypeScript WASM reactor did not export its memory.");
+    }
+    let memory: WebAssembly.Memory | undefined = instance.exports.memory;
+    let transport: WasmTransport | undefined;
+    let api: API | undefined;
+    let snapshot: Snapshot | undefined;
+    const close = () => {
+        const currentApi = api;
+        const currentTransport = transport;
+        api = undefined;
+        transport = undefined;
+        snapshot = undefined;
+        memory = undefined;
+        if (currentApi) {
+            currentApi.close();
+        } else {
+            currentTransport?.close();
+        }
+    };
+    try {
+        transport = new WasmTransport({ instance, cwd: "/" });
+        api = new API({ transport });
+        const validator = createTypeScriptJsonValidatorWithCompiler(
+            schema, typeName, schemaValidationTypeName,
+            files => {
+                if (!transport) {
+                    throw new Error("The TypeScript WASM transport has been closed.");
+                }
+                for (const [name, text] of Object.entries(files)) {
+                    transport.setFile(name, text);
                 }
-            };
-            try {
-                transport = new WasmTransport({ instance, cwd: "/" });
-                api = new API({ transport });
-                const validator = createTypeScriptJsonValidatorWithCompiler(
-                    schema, typeName, schemaValidationTypeName,
-                    files => {
+                return createCompiler({
+                    writeFile(name, text) {
                         if (!transport) {
                             throw new Error("The TypeScript WASM transport has been closed.");
                         }
-                        for (const [name, text] of Object.entries(files)) {
-                            transport.setFile(name, text);
+                        transport.setFile(name, text);
+                    },
+                    update(changedFiles) {
+                        if (!api) {
+                            throw new Error("The TypeScript WASM API has been closed.");
                         }
-                        return createCompiler({
-                            writeFile(name, text) {
-                                if (!transport) {
-                                    throw new Error("The TypeScript WASM transport has been closed.");
-                                }
-                                transport.setFile(name, text);
-                            },
-                            update(changedFiles) {
-                                if (!api) {
-                                    throw new Error("The TypeScript WASM API has been closed.");
-                                }
-                                const next = api.createSnapshot({
-                                    openFiles: [schemaFileName, jsonFileName, schemaValidationFileName],
-                                    fileNotifications: { changed: [...changedFiles], deleted: [] }
-                                });
-                                snapshot?.dispose();
-                                snapshot = next;
-                                const project = next.getConfiguredProject(configFileName);
-                                return project && projectView(project);
-                            },
-                            close
+                        const next = api.createSnapshot({
+                            openFiles: [schemaFileName, jsonFileName, schemaValidationFileName],
+                            fileNotifications: { changed: [...changedFiles], deleted: [] }
                         });
-                    }
-                );
-                return Object.assign(validator, {
-                    getWasmMemoryByteLength: () => memory?.buffer.byteLength ?? 0
+                        snapshot?.dispose();
+                        snapshot = next;
+                        const project = next.getConfiguredProject(configFileName);
+                        return project && projectView(project);
+                    },
+                    close
                 });
-            } catch (cause) {
-                close();
-                throw cause;
             }
-        }
-    };
+        );
+        return Object.assign(validator, {
+            getWasmMemoryByteLength: () => memory?.buffer.byteLength ?? 0
+        });
+    } catch (cause) {
+        close();
+        throw cause;
+    }
 }
diff --git a/typescript/experimental/browser/tests/repro-unicode-enum.mjs b/typescript/experimental/browser/tests/repro-unicode-enum.mjs
new file mode 100644
index 00000000..6d26980c
--- /dev/null
+++ b/typescript/experimental/browser/tests/repro-unicode-enum.mjs
@@ -0,0 +1,45 @@
+import assert from "node:assert/strict";
+import { createRequire } from "node:module";
+import { isAbsolute, relative, resolve, sep } from "node:path";
+
+// Run from a freshly built TypeChat typescript/ directory, not from this file's directory.
+const fromCheckout = createRequire(resolve("package.json"));
+const entry = relative(process.cwd(), fromCheckout.resolve("typechat/ts"));
+assert.ok(!isAbsolute(entry) && !entry.startsWith(`..${sep}`), "The reproduction must use the current checkout.");
+const { createTypeScriptJsonValidator } = fromCheckout("typechat/ts");
+const { typeChatSchemaValidation } = fromCheckout("typechat");
+const codeUnits = value => Array.from(
+    { length: value.length }, (_, index) => value.charCodeAt(index).toString(16).padStart(4, "0")
+);
+const cases = [];
+for (const [name, source, value] of [
+    ["leading BOM control", String.raw`\uFEFFx`, "\uFEFFx"],
+    ["BOM after lone surrogate", String.raw`\ud800\uFEFFx`, "\ud800\uFEFFx"]
+]) {
+    const schema = `export enum E { X = "${source}" } export interface Probe { value: E; }`;
+    const validator = createTypeScriptJsonValidator(schema, "Probe");
+    try {
+        cases.push({
+            name,
+            schema,
+            declaredValueCodeUnits: codeUnits(value),
+            preflight: validator[typeChatSchemaValidation](),
+            declared: validator.validate({ value }),
+            altered: validator.validate({ value: value.replace("\uFEFF", "") })
+        });
+    } finally {
+        validator.close();
+    }
+}
+console.log(JSON.stringify({
+    node: process.version,
+    typechat: fromCheckout("./package.json").version,
+    typescript: fromCheckout("typescript").version,
+    entry,
+    cases
+}, null, 2));
+for (const example of cases) {
+    assert.equal(example.preflight.success, true, `${example.name}: schema should pass preflight.`);
+    assert.equal(example.declared.success, true, `${example.name}: the declared value must validate.`);
+    assert.equal(example.altered.success, false, `${example.name}: a different value must fail.`);
+}
diff --git a/typescript/experimental/browser/tests/stability.test.mjs b/typescript/experimental/browser/tests/stability.test.mjs
new file mode 100644
index 00000000..0db39601
--- /dev/null
+++ b/typescript/experimental/browser/tests/stability.test.mjs
@@ -0,0 +1,548 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { once } from "node:events";
+import { mkdir, readFile, rm } from "node:fs/promises";
+import { createServer } from "node:http";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+import { WasmTransport } from "typescript/wasm";
+import { createTypeScriptJsonValidator } from "../../../dist/ts/index.js";
+import * as core from "@typechat/experimental-browser";
+
+const artifact = await readFile(new URL("../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url));
+const numericSchema = "export interface Probe { value: number; }";
+const stringSchema = "export interface Probe { value: string; }";
+const wasmUrl = "https://example.test/tsc.wasm";
+
+test("stability: repeated loads and interleaved validators preserve results and close deterministically", async t => {
+    let fetches = 0;
+    t.mock.method(globalThis, "fetch", async () => { fetches++; return new Response(artifact); });
+    const native = createTypeScriptJsonValidator(numericSchema, "Probe");
+    try {
+        for (let cycle = 0; cycle < 3; cycle++) {
+            const compiler = await core.loadBrowserTypeScriptCompiler(wasmUrl);
+            const [numbers, strings] = await Promise.all([
+                compiler.createValidator(numericSchema, "Probe"),
+                compiler.createValidator(stringSchema, "Probe")
+            ]);
+            try {
+                for (const value of [{ value: "bad" }, { value: cycle }, {}, { value: cycle + 1 }]) {
+                    const actual = numbers.validate(value);
+                    assert.equal(actual.success, native.validate(value).success);
+                    assert.equal(actual.data, value);
+                    if (!actual.success) assert.ok(actual.message.length > 0);
+                    assert.equal(strings.validate({ value: "independent" }).success, true);
+                }
+                assert.equal(numbers[core.typeChatSchemaValidation]().success, true);
+                numbers.close();
+                numbers.close();
+                assert.equal(numbers.getWasmMemoryByteLength(), 0);
+                assert.throws(() => numbers[core.typeChatSchemaValidation](), /closed/);
+                assert.throws(() => numbers.validate({ value: 1 }), /closed/);
+                assert.equal(strings.validate({ value: "after peer close" }).success, true);
+            } finally {
+                numbers.close();
+                strings.close();
+            }
+            assert.equal(strings.getWasmMemoryByteLength(), 0);
+        }
+        assert.equal(fetches, 3);
+    } finally {
+        native.close();
+    }
+});
+
+test("stability: initialization and write exceptions close or recover without poisoning siblings", async t => {
+    t.mock.method(globalThis, "fetch", async () => new Response(artifact));
+    const compiler = await core.loadBrowserTypeScriptCompiler(wasmUrl);
+    const originalWrite = WasmTransport.prototype.setFile;
+    const originalClose = WasmTransport.prototype.close;
+    const initializationError = new Error("injected schema write failure");
+    const validationError = new Error("injected candidate write failure");
+    let failValidation = false;
+    let closes = 0;
+    t.mock.method(WasmTransport.prototype, "close", function () {
+        closes++;
+        return originalClose.call(this);
+    });
+    t.mock.method(WasmTransport.prototype, "setFile", function (name, value) {
+        if (name === "/schema.ts" && value.includes("FailInitialization")) throw initializationError;
+        if (name === "/json.ts" && failValidation) {
+            failValidation = false;
+            throw validationError;
+        }
+        return originalWrite.call(this, name, value);
+    });
+    const survivor = await compiler.createValidator(stringSchema, "Probe");
+    let recovered;
+    try {
+        await assert.rejects(
+            compiler.createValidator("export interface FailInitialization {}", "FailInitialization"),
+            error => error === initializationError
+        );
+        assert.equal(closes, 1, "The partially initialized reactor must be closed.");
+        assert.equal(survivor.validate({ value: "alive" }).success, true);
+        recovered = await compiler.createValidator(numericSchema, "Probe");
+        failValidation = true;
+        assert.throws(() => recovered.validate({ value: 1 }), error => error === validationError);
+        const rejected = { value: "still rejected" };
+        assert.equal(recovered.validate(rejected).data, rejected);
+        assert.equal(recovered.validate(rejected).success, false);
+        assert.equal(recovered.validate({ value: 2 }).success, true);
+        assert.equal(survivor.validate({ value: "still alive" }).success, true);
+    } finally {
+        recovered?.close();
+        survivor.close();
+    }
+    assert.equal(closes, 3);
+    assert.equal(recovered.getWasmMemoryByteLength(), 0);
+    assert.equal(survivor.getWasmMemoryByteLength(), 0);
+});
+
+test("stability: invalid schema Results and concurrent translation metadata survive recovery", async t => {
+    t.mock.method(globalThis, "fetch", async () => new Response(artifact));
+    const compiler = await core.loadBrowserTypeScriptCompiler(wasmUrl);
+    const invalid = await compiler.createValidator("export interface Probe { value: MissingType; }", "Probe");
+    const valid = await compiler.createValidator(numericSchema, "Probe");
+    try {
+        assert.equal(invalid[core.typeChatSchemaValidation]().success, false);
+        let calls = 0;
+        const invalidTranslator = core.createJsonTranslator({
+            async complete() { calls++; throw new Error("Invalid schema reached the model."); }
+        }, invalid);
+        const invalidResult = await invalidTranslator.translate("offline");
+        assert.equal(invalidResult.success, false);
+        assert.match(invalidResult.message, /Schema validation failed.*|MissingType/s);
+        assert.equal(calls, 0);
+        const responses = ['{"value":"first"}', '{"value":"second"}'];
+        const results = await Promise.all(responses.map(async response => {
+            const translator = core.createJsonTranslator({ async complete() { return core.success(response); } }, valid);
+            translator.attemptRepair = false;
+            return translator.translate("offline");
+        }));
+        results.forEach((result, index) => {
+            assert.equal(result.success, false);
+            assert.deepEqual(result.data, JSON.parse(responses[index]));
+            assert.equal(result.responseText, responses[index]);
+            assert.ok(result.message.length > 0);
+        });
+        assert.equal(valid[core.typeChatSchemaValidation]().success, true);
+        assert.equal(valid.validate({ value: 1 }).success, true);
+    } finally {
+        invalid.close();
+        valid.close();
+    }
+});
+
+test("stability: cancellation at digest and compile boundaries rejects exactly and permits retry", async t => {
+    t.mock.method(globalThis, "fetch", async () => new Response(artifact));
+    const digest = crypto.subtle.digest.bind(crypto.subtle);
+    const compile = WebAssembly.compile;
+    let compilations = 0;
+    const compileMock = t.mock.method(WebAssembly, "compile", async bytes => {
+        compilations++;
+        return compile(bytes);
+    });
+    const beforeCompile = new AbortController();
+    const firstReason = new Error("cancelled after digest");
+    const digestMock = t.mock.method(crypto.subtle, "digest", async (...args) => {
+        const result = await digest(...args);
+        beforeCompile.abort(firstReason);
+        return result;
+    });
+    await assert.rejects(core.loadBrowserTypeScriptCompiler(wasmUrl, { signal: beforeCompile.signal }),
+        error => error === firstReason);
+    assert.equal(compilations, 0);
+    digestMock.mock.restore();
+    const duringCompile = new AbortController();
+    const secondReason = new Error("cancelled during compile");
+    compileMock.mock.mockImplementation(async bytes => {
+        const module = await compile(bytes);
+        duringCompile.abort(secondReason);
+        return module;
+    });
+    await assert.rejects(core.loadBrowserTypeScriptCompiler(wasmUrl, { signal: duringCompile.signal }),
+        error => error === secondReason);
+    compileMock.mock.restore();
+    const compiler = await core.loadBrowserTypeScriptCompiler(wasmUrl);
+    const validator = await compiler.createValidator(numericSchema, "Probe");
+    try {
+        assert.equal(validator.validate({ value: 1 }).success, true);
+    } finally {
+        validator.close();
+    }
+});
+
+test("stability: failed streams and corrupt artifacts do not invalidate existing handles", async t => {
+    const fetch = t.mock.method(globalThis, "fetch", async () => new Response(artifact));
+    const compiler = await core.loadBrowserTypeScriptCompiler(wasmUrl);
+    const validator = await compiler.createValidator(numericSchema, "Probe");
+    try {
+        const streamError = new Error("injected download failure");
+        let reads = 0;
+        const body = new ReadableStream({
+            pull(controller) {
+                if (reads++ === 0) controller.enqueue(artifact.subarray(0, 100));
+                else controller.error(streamError);
+            }
+        });
+        fetch.mock.mockImplementation(async () => new Response(body));
+        await assert.rejects(core.loadBrowserTypeScriptCompiler(wasmUrl), error => error === streamError);
+        assert.equal(body.locked, false);
+        const corrupt = new Uint8Array(artifact);
+        corrupt[corrupt.length - 1] ^= 1;
+        fetch.mock.mockImplementation(async () => new Response(corrupt));
+        await assert.rejects(core.loadBrowserTypeScriptCompiler(wasmUrl), /SHA-256 mismatch/);
+        assert.equal(validator.validate({ value: 7 }).success, true);
+        fetch.mock.mockImplementation(async () => new Response(artifact));
+        const retry = await core.loadBrowserTypeScriptCompiler(wasmUrl);
+        const fresh = await retry.createValidator(stringSchema, "Probe");
+        try {
+            assert.equal(fresh.validate({ value: "recovered" }).success, true);
+            assert.equal(validator.validate({ value: "wrong" }).success, false);
+        } finally {
+            fresh.close();
+        }
+    } finally {
+        validator.close();
+    }
+});
+
+test("stability: a retained closed validator must not retain its compiled module", () => {
+    // Inspect an actual strong retaining path, not whether GC happens within a timing budget.
+    const probe = String.raw`
+import { readFile } from "node:fs/promises";
+import { getHeapSnapshot } from "node:v8";
+import { loadBrowserTypeScriptCompiler } from "@typechat/experimental-browser";
+async function createClosedValidator() {
+    const bytes = await readFile(new URL("./node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url));
+    const originalFetch = globalThis.fetch;
+    const originalCompile = WebAssembly.compile;
+    globalThis.fetch = async () => new Response(bytes);
+    WebAssembly.compile = async (...args) => {
+        const module = await originalCompile(...args);
+        module.__typechatStabilityModule = true;
+        return module;
+    };
+    try {
+        const compiler = await loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm");
+        const validator = await compiler.createValidator("export interface Probe { value: number }", "Probe");
+        validator.validate({ value: 1 });
+        validator.close();
+        validator.__typechatStabilityClosedValidator = true;
+        globalThis.retainedClosedValidator = validator;
+    } finally {
+        globalThis.fetch = originalFetch;
+        WebAssembly.compile = originalCompile;
+    }
+}
+await createClosedValidator();
+await new Promise(resolve => setImmediate(resolve));
+const chunks = [];
+for await (const chunk of getHeapSnapshot()) chunks.push(chunk);
+const heap = JSON.parse(Buffer.concat(chunks).toString());
+const nf = heap.snapshot.meta.node_fields, ef = heap.snapshot.meta.edge_fields;
+const edgeTypes = heap.snapshot.meta.edge_types[0];
+const size = nf.length, edgeSize = ef.length;
+const nameIndex = nf.indexOf("name"), countIndex = nf.indexOf("edge_count");
+const typeIndex = ef.indexOf("type"), edgeNameIndex = ef.indexOf("name_or_index"), toIndex = ef.indexOf("to_node");
+const nodeName = offset => heap.strings[heap.nodes[offset + nameIndex]];
+const edgeName = offset => ["element", "hidden"].includes(edgeTypes[heap.edges[offset + typeIndex]])
+    ? String(heap.edges[offset + edgeNameIndex]) : heap.strings[heap.edges[offset + edgeNameIndex]];
+const starts = new Map();
+let cursor = 0, closedValidator, module;
+for (let offset = 0; offset < heap.nodes.length; offset += size) {
+    starts.set(offset, cursor);
+    for (let i = 0; i < heap.nodes[offset + countIndex]; i++, cursor += edgeSize) {
+        if (edgeName(cursor) === "__typechatStabilityClosedValidator") closedValidator = offset;
+        if (edgeName(cursor) === "__typechatStabilityModule") module = offset;
+    }
+}
+if (closedValidator === undefined) throw new Error("The heap probe did not find its retained validator.");
+const parents = new Map([[closedValidator, null]]), queue = [closedValidator];
+for (let q = 0; q < queue.length && module !== undefined && !parents.has(module); q++) {
+    const offset = queue[q];
+    for (let e = starts.get(offset), end = e + heap.nodes[offset + countIndex] * edgeSize; e < end; e += edgeSize) {
+        if (edgeTypes[heap.edges[e + typeIndex]] === "weak") continue;
+        const to = heap.edges[e + toIndex];
+        if (!parents.has(to)) {
+            parents.set(to, { from: offset, edge: edgeName(e) });
+            queue.push(to);
+        }
+    }
+}
+let path = null;
+if (module !== undefined && parents.has(module)) {
+    path = [];
+    for (let at = module; parents.get(at); at = parents.get(at).from) {
+        const entry = parents.get(at);
+        path.push(nodeName(entry.from) + " --" + entry.edge + "--> " + nodeName(at));
+    }
+    path.reverse();
+}
+console.log(JSON.stringify({ closedMemory: globalThis.retainedClosedValidator.getWasmMemoryByteLength(), path }));
+`;
+    const environment = { ...process.env };
+    delete environment.NODE_TEST_CONTEXT;
+    const child = spawnSync(process.execPath, ["--input-type=module", "-e", probe], {
+        cwd: fileURLToPath(new URL("..", import.meta.url)),
+        env: environment,
+        encoding: "utf8",
+        timeout: 60000,
+        maxBuffer: 1024 * 1024
+    });
+    assert.ifError(child.error);
+    assert.equal(child.status, 0, child.stderr);
+    const result = JSON.parse(child.stdout);
+    assert.equal(result.closedMemory, 0);
+    assert.equal(result.path, null, `Closed validator retains its compiled module:\n${result.path?.join("\n")}`);
+});
+
+// Independent semantic gates for microsoft/TypeScript#65451 and #65458.
+// The lone-surrogate/BOM cases must stay red until the declared value is preserved.
+const upstreamCases = [
+    {
+        name: "leading-dot numeric literal",
+        schema: "export interface Probe { value: .1; }",
+        accepted: { value: 0.1 },
+        rejected: { value: 0.2 }
+    },
+    {
+        name: "leading-dot numeric initializer",
+        schema: "export const decimal = .1; export interface Probe { value: typeof decimal; }",
+        accepted: { value: 0.1 },
+        rejected: { value: 0.2 }
+    },
+    {
+        name: "large enum followed by interface",
+        schema: "export enum E { X = 1e20 } export interface Probe { value: E; }",
+        accepted: { value: 1e20 },
+        rejected: { value: 0 }
+    },
+    {
+        name: "leading BOM enum value",
+        schema: 'export enum E { X = "\\uFEFFx" } export interface Probe { value: E; }',
+        accepted: { value: "\uFEFFx" },
+        rejected: { value: "x" }
+    },
+    {
+        name: "BOM after lone surrogate enum value",
+        schema: 'export enum E { X = "\\ud800\\uFEFFx" } export interface Probe { value: E; }',
+        accepted: { value: "\ud800\uFEFFx" },
+        rejected: { value: "\ud800x" }
+    }
+];
+
+for (const backend of ["stable-native", "pinned-wasm"]) {
+    for (const example of upstreamCases) {
+        test(`stability upstream: ${backend}: ${example.name}`, t => {
+            const probe = String.raw`
+import { readFile } from "node:fs/promises";
+import * as core from "@typechat/experimental-browser";
+import { createTypeScriptJsonValidator } from "../../dist/ts/index.js";
+const { backend, example } = JSON.parse(process.env.TYPECHAT_STABILITY_CASE);
+let validator, phase = "loading", result;
+try {
+    let createValidator = createTypeScriptJsonValidator;
+    if (backend === "pinned-wasm") {
+        const artifact = await readFile(new URL("./node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url));
+        globalThis.fetch = async () => new Response(artifact);
+        const compiler = await core.loadBrowserTypeScriptCompiler("https://example.test/tsc.wasm");
+        createValidator = (...args) => compiler.createValidator(...args);
+    }
+    phase = "createValidator";
+    validator = await createValidator(example.schema, "Probe");
+    phase = "schema preflight";
+    const schema = validator[core.typeChatSchemaValidation]();
+    phase = "validate declared value";
+    const accepted = validator.validate(example.accepted);
+    phase = "validate different value";
+    const rejected = validator.validate(example.rejected);
+    result = { kind: "results", schema, accepted, rejected };
+} catch (error) {
+    result = { kind: "exception", phase, name: error.name, message: error.message };
+} finally {
+    try { validator?.close(); }
+    catch (error) { result.closeError = error.message; }
+}
+console.log("STABILITY_UPSTREAM_RESULT=" + JSON.stringify(result));
+`;
+            const environment = { ...process.env, TYPECHAT_STABILITY_CASE: JSON.stringify({ backend, example }) };
+            delete environment.NODE_TEST_CONTEXT;
+            const child = spawnSync(process.execPath, ["--input-type=module", "-e", probe], {
+                cwd: fileURLToPath(new URL("..", import.meta.url)),
+                env: environment,
+                encoding: "utf8",
+                timeout: 15000,
+                maxBuffer: 1024 * 1024
+            });
+            const line = child.stdout?.split(/\r?\n/).find(line => line.startsWith("STABILITY_UPSTREAM_RESULT="));
+            const result = line ? JSON.parse(line.slice("STABILITY_UPSTREAM_RESULT=".length)) : undefined;
+            t.diagnostic(JSON.stringify({ backend, case: example.name, result, status: child.status,
+                error: child.error?.message, stderr: child.stderr?.slice(-1500) }));
+            assert.ifError(child.error);
+            assert.equal(child.status, 0, child.stderr);
+            assert.equal(result?.kind, "results", `${example.name} must not throw: ${JSON.stringify(result)}`);
+            assert.equal(result.schema.success, true, result.schema.message);
+            assert.equal(result.accepted.success, true, `The declared value must validate: ${result.accepted.message}`);
+            assert.deepEqual(result.accepted.data, example.accepted);
+            assert.equal(result.rejected.success, false, "A different value must not validate.");
+            assert.deepEqual(result.rejected.data, example.rejected);
+            assert.equal(result.closeError, undefined);
+        });
+    }
+}
+
+// Opt in so ordinary experimental Node tests do not acquire a browser dependency at runtime.
+for (const engineName of ["chromium", "firefox", "webkit"]) {
+    test(`stability: ${engineName} worker cancellation, sibling survival, and recovery`, {
+        skip: process.env.TYPECHAT_STABILITY_BROWSERS !== "1",
+        timeout: 90000
+    }, async t => {
+        const { build } = await import("esbuild");
+        const { [engineName]: engine } = await import("playwright");
+        const { buildWorkerExample } = await import("../examples/worker/build.mjs");
+        const settings = { bundle: true, platform: "browser", format: "iife", write: false, logLevel: "silent" };
+        const entry = await build({
+            ...settings,
+            stdin: {
+                contents: `import * as core from "@typechat/experimental-browser";
+import { validateInWorker } from "./examples/worker/client.ts";
+globalThis.stability = { core, validateInWorker };`,
+                resolveDir: fileURLToPath(new URL("..", import.meta.url))
+            }
+        });
+        const mismatch = await build({
+            ...settings,
+            stdin: {
+                contents: `import { loadBrowserTypeScriptCompiler } from "@typechat/experimental-browser";
+globalThis.mismatchedLoader = loadBrowserTypeScriptCompiler;`,
+                resolveDir: fileURLToPath(new URL("..", import.meta.url))
+            },
+            plugins: [{
+                name: "stability-version-mismatch",
+                setup(builder) {
+                    builder.onResolve({ filter: /^typescript$/ }, () => ({ path: "version", namespace: "mismatch" }));
+                    builder.onLoad({ filter: /.*/, namespace: "mismatch" }, () => ({
+                        contents: 'export const version = "0.0.0";', loader: "js"
+                    }));
+                }
+            }]
+        });
+        const assets = await buildWorkerExample();
+        assets.set("/", ["text/html", '']);
+        assets.set("/entry.js", ["text/javascript", entry.outputFiles[0].contents]);
+        assets.set("/mismatch.js", ["text/javascript", mismatch.outputFiles[0].contents]);
+        assets.set("/tsc.wasm", ["application/wasm", artifact]);
+        assets.set("/short.wasm", ["application/wasm", artifact.subarray(0, 100)]);
+        let mismatchRequests = 0;
+        const server = createServer((request, response) => {
+            if (request.url === "/never-fetch.wasm") mismatchRequests++;
+            const asset = assets.get(request.url);
+            response.writeHead(asset ? 200 : 404, { "Content-Type": asset?.[0] ?? "text/plain" });
+            response.end(asset?.[1] ?? "Not found");
+        });
+        const scratch = fileURLToPath(new URL(`./.stability-${process.pid}-${engineName}`, import.meta.url));
+        const previousEnvironment = { TMP: process.env.TMP, TEMP: process.env.TEMP };
+        let browser;
+        t.after(async () => {
+            try {
+                await browser?.close();
+            } finally {
+                server.closeAllConnections();
+                await new Promise(resolve => server.close(resolve));
+                for (const [name, value] of Object.entries(previousEnvironment)) {
+                    if (value === undefined) delete process.env[name];
+                    else process.env[name] = value;
+                }
+                await rm(scratch, { recursive: true, force: true });
+            }
+        });
+        await mkdir(scratch, { recursive: true });
+        process.env.TMP = process.env.TEMP = scratch;
+        server.listen(0, "127.0.0.1");
+        await once(server, "listening");
+        browser = await engine.launch({ headless: true, downloadsPath: scratch, artifactsDir: scratch });
+        const page = await browser.newPage();
+        const workerClosures = [];
+        const errors = [];
+        page.on("worker", worker => workerClosures.push(once(worker, "close")));
+        page.on("pageerror", error => errors.push(error.message));
+        await page.goto(`http://127.0.0.1:${server.address().port}`);
+        const result = await page.evaluate(async ({ numericSchema, stringSchema }) => {
+            const { core, validateInWorker } = globalThis.stability;
+            const check = (condition, message) => { if (!condition) throw new Error(message); };
+            const job = (schema, values, path = "/tsc.wasm") => ({
+                wasmUrl: new URL(path, location.href).href, schema, typeName: "Probe", values
+            });
+            let listeners = 0;
+            function controller() {
+                const controller = new AbortController();
+                const add = controller.signal.addEventListener.bind(controller.signal);
+                const remove = controller.signal.removeEventListener.bind(controller.signal);
+                controller.signal.addEventListener = (...args) => { if (args[0] === "abort") listeners++; return add(...args); };
+                controller.signal.removeEventListener = (...args) => { if (args[0] === "abort") listeners--; return remove(...args); };
+                return controller;
+            }
+            const shared = controller();
+            let mismatch;
+            try { await globalThis.mismatchedLoader("/never-fetch.wasm"); }
+            catch (error) { mismatch = error.message; }
+            check(/Expected TypeScript .* loaded 0\.0\.0/.test(mismatch), "Version mismatch was not explicit.");
+            const cancelled = controller();
+            const reason = new Error("cancel only the numeric job");
+            let validating = false;
+            const [aborted, sibling] = await Promise.allSettled([
+                validateInWorker("/validator.worker.js", job(numericSchema, Array.from({ length: 100 }, (_, value) => ({ value }))), {
+                    signal: cancelled.signal,
+                    onPhase(phase) {
+                        if (phase === "validating") { validating = true; cancelled.abort(reason); }
+                    }
+                }),
+                validateInWorker("/validator.worker.js", job(stringSchema, [{ value: "alive" }, { value: 1 }]), {
+                    signal: shared.signal
+                })
+            ]);
+            check(validating && aborted.status === "rejected" && aborted.reason === reason, "Cancellation lost its reason or phase.");
+            check(sibling.status === "fulfilled" && sibling.value.results[0].success && !sibling.value.results[1].success,
+                "Cancellation poisoned the sibling.");
+            check(sibling.value.results[1].data.value === 1 && sibling.value.results[1].message.length > 0,
+                "Rejected worker candidate metadata was lost.");
+            check(sibling.value.closedLinearMemoryBytes === 0, "Sibling retained its owned memory.");
+            for (const [schema, path, pattern] of [
+                ["export interface Probe { value: MissingType; }", "/tsc.wasm", /Schema validation failed/],
+                [numericSchema, "/short.wasm", /received 100/]
+            ]) {
+                let failure;
+                try { await validateInWorker("/validator.worker.js", job(schema, [], path), { signal: shared.signal }); }
+                catch (error) { failure = error.message; }
+                check(pattern.test(failure), `Worker failure was not explicit: ${failure}`);
+            }
+            for (let cycle = 0; cycle < 3; cycle++) {
+                const report = await validateInWorker("/validator.worker.js", job(numericSchema, [{ value: cycle }, { value: "bad" }]), {
+                    signal: shared.signal
+                });
+                check(report.results[0].success && !report.results[1].success, "A fresh worker did not recover.");
+                check(report.results[1].data.value === "bad", "Fresh worker lost rejected data.");
+                check(report.closedLinearMemoryBytes === 0, "Fresh worker retained owned memory.");
+                check(listeners === 0, "A settled job retained its AbortSignal listener.");
+            }
+            shared.abort(new Error("abort after settlement must have no effect"));
+            const compiler = await core.loadBrowserTypeScriptCompiler("/tsc.wasm");
+            const validator = await compiler.createValidator(numericSchema, "Probe");
+            try {
+                check(validator.validate({ value: 9 }).success, "Mismatched bundle poisoned the real compiler.");
+            } finally {
+                validator.close();
+            }
+            return { listeners, validating, closedMemory: validator.getWasmMemoryByteLength() };
+        }, { numericSchema, stringSchema });
+        assert.deepEqual(result, { listeners: 0, validating: true, closedMemory: 0 });
+        await Promise.all(workerClosures);
+        assert.equal(workerClosures.length, 7);
+        assert.equal(page.workers().length, 0);
+        assert.equal(mismatchRequests, 0);
+        assert.deepEqual(errors, []);
+        t.diagnostic(`${engineName}: seven workers closed; no abort listeners, page errors, or mismatch fetches.`);
+    });
+}

From 4484728ee87eae619fb4da1bc2ebcb9cbc6f5e47 Mon Sep 17 00:00:00 2001
From: Robert Gruen 
Date: Tue, 24 Nov 2026 09:28:58 -0800
Subject: [PATCH 5/5] Exercise strict browser hosting and versioned WASM assets

Keep hosting application-owned. Verify CSP, compressed immutable artifacts, encoding negotiation, conditional requests, and worker loading errors across the browser matrix. Preserve the separate Unicode conformance gates.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
 typescript/experimental/browser/README.md     |  59 ++++++--
 .../browser/examples/worker/build.mjs         |  16 +-
 .../browser/examples/worker/host.mjs          | 101 +++++++++++++
 .../browser/examples/worker/index.html        |  53 +------
 .../browser/examples/worker/main.mjs          |  47 ++++++
 .../browser/examples/worker/serve.mjs         |  17 +--
 .../browser/examples/worker/style.css         |   4 +
 .../browser/tests/browser/browser.test.mjs    |   8 +-
 .../browser/tests/browser/hosting.test.mjs    | 123 ++++++++++++++++
 .../browser/tests/hosting.test.mjs            | 137 ++++++++++++++++++
 .../browser/tests/stability.test.mjs          |   6 +-
 11 files changed, 493 insertions(+), 78 deletions(-)
 create mode 100644 typescript/experimental/browser/examples/worker/host.mjs
 create mode 100644 typescript/experimental/browser/examples/worker/main.mjs
 create mode 100644 typescript/experimental/browser/examples/worker/style.css
 create mode 100644 typescript/experimental/browser/tests/browser/hosting.test.mjs
 create mode 100644 typescript/experimental/browser/tests/hosting.test.mjs

diff --git a/typescript/experimental/browser/README.md b/typescript/experimental/browser/README.md
index 84113b91..ddf86881 100644
--- a/typescript/experimental/browser/README.md
+++ b/typescript/experimental/browser/README.md
@@ -106,15 +106,17 @@ same-version backends must match diagnostics as well as acceptance outcomes.
 The additional stability suite also asserts independently expected semantics;
 it currently reports the two Unicode failures described above.
 
-After the lifetime fix, the complete experimental Node run reports **21 passed,
-2 failed** (the Unicode checks), and **3 skipped** opt-in browser recovery checks.
-Those three recovery checks were run separately in Chromium, Firefox, and WebKit
-and all passed: seven workers closed per engine, with no remaining abort
-listeners, page errors, or fetches for the intentionally mismatched compiler.
-A final combined run of the Node checks, full three-engine browser matrix, and
-opt-in recovery checks reported **27 passed, 2 failed, 0 skipped**. Only the two
-independently expected Unicode cases remain red. The ordinary repository build
-and 424-test suite were also rerun successfully, with live tests disabled.
+The latest combined run of the Node checks, hosting contracts, full three-engine
+browser matrix, and opt-in recovery checks reported **34 passed, 2 failed,
+0 skipped**. Only the two independently expected Unicode cases remain red.
+The three recovery checks passed in Chromium, Firefox, and WebKit: seven workers
+closed per engine, with no remaining abort listeners, page errors, or fetches for
+the intentionally mismatched compiler. Ordinary `npm test` skips those optional
+browser recovery checks unless explicitly enabled.
+
+The ordinary repository build and 424-test suite were last verified successfully
+with live tests disabled before this hosting-only follow-up; library sources and
+dependency manifests have not changed in the hosting follow-up.
 To repeat that focused recovery run in PowerShell:
 
 ```powershell
@@ -203,8 +205,9 @@ npm run example:worker
 Open the printed loopback URL. The example validates a JSON batch against a schema
 with a string enum, displays valid and invalid results, and keeps a main-thread
 timer running. Cancel interrupts a running job; Ctrl+C stops the local server.
-The development server serves the raw artifact without caching. A production
-application would need deliberate asset compression and cache/version handling.
+The development server serves a verified, versioned WASM artifact with compression
+and explicit cache rules. It remains a loopback example, not a deployment service
+or a supported production hosting platform.
 
 [`examples/worker/client.ts`](./examples/worker/client.ts) and
 [`examples/worker/validator.worker.ts`](./examples/worker/validator.worker.ts) are
@@ -227,6 +230,40 @@ throughput. It reloads/reinitializes a compiler per job. A reusable worker or
 compiled-module cache would need separate lifecycle and cancellation design; this
 investigation does not introduce a worker pool into TypeChat.
 
+### Hosting and CSP contract
+
+The demo and its browser tests use the same
+[`examples/worker/host.mjs`](./examples/worker/host.mjs) handler:
+
+- HTML, JavaScript, and CSS use `Cache-Control: no-store`. The WASM URL contains
+  both the exact compiler version and the full artifact SHA-256, with
+  `public, max-age=31536000, immutable`. Startup verifies the artifact before
+  advertising that immutable URL.
+- Gzip and identity representations preserve the exact artifact bytes.
+  `Accept-Encoding` preferences/exclusions are honored, representation-specific
+  ETags and `Vary: Accept-Encoding` prevent mixing encoded responses, and matching
+  conditional requests return an empty `304`. `HEAD`, invalid encoding headers,
+  unsupported methods, and missing asset versions have explicit responses.
+- The HTML uses external scripts/styles. CSP permits same-origin scripts,
+  workers, connections and styles, plus **`'wasm-unsafe-eval'` only** for WASM
+  compilation. It does not enable JavaScript `'unsafe-eval'` or `'unsafe-inline'`.
+  The worker script receives the policy too; removing WASM permission makes the
+  job reject explicitly instead of falling back to another validator.
+- This policy belongs to the example, not to the library API. Applications must
+  deliberately review their HTTPS, CDN/CORS, model-endpoint, and embedding needs.
+  Do not blindly broaden `connect-src` or add API secrets to client code.
+
+Four HTTP contract tests and the three-engine hosted-page tests verify these
+behaviors. JavaScript eval is checked from a real served page script, not debugger
+evaluation that could bypass CSP. Existing validation/worker recovery suites also
+use the shared handler; **13 changed-surface checks passed** on Windows.
+
+Browser caching remains browser-controlled. In the recorded automated two-job
+tests, Firefox reused the cached artifact; Chromium and WebKit fetched it again.
+Every network representation was gzip (13,359,431 bytes), but immutable headers
+do not guarantee storage, prevent eviction, or avoid compilation in a new worker.
+These observations are not retail-browser cache guarantees.
+
 ## Recorded verification
 
 On Windows and Node.js 24.22.1:
diff --git a/typescript/experimental/browser/examples/worker/build.mjs b/typescript/experimental/browser/examples/worker/build.mjs
index 3c052074..41e40cf4 100644
--- a/typescript/experimental/browser/examples/worker/build.mjs
+++ b/typescript/experimental/browser/examples/worker/build.mjs
@@ -1,12 +1,24 @@
 import { readFile } from "node:fs/promises";
 import { fileURLToPath } from "node:url";
 import { build } from "esbuild";
+import { compilerVersion, wasmSha256 } from "../../dist/experimental/browser/src/versions.js";
+
+export const wasmAssetPath = `/typescript-${compilerVersion}-${wasmSha256}.wasm`;
 
 export async function buildWorkerExample() {
+    const html = await readFile(new URL("./index.html", import.meta.url), "utf8");
+    if (html.split("__TYPECHAT_WASM_ASSET__").length !== 2) {
+        throw new Error("The worker example must contain exactly one WASM asset placeholder.");
+    }
     const assets = new Map([
-        ["/worker", ["text/html; charset=utf-8", await readFile(new URL("./index.html", import.meta.url))]]
+        ["/worker", ["text/html; charset=utf-8", html.replace("__TYPECHAT_WASM_ASSET__", wasmAssetPath)]],
+        ["/worker.css", ["text/css; charset=utf-8", await readFile(new URL("./style.css", import.meta.url))]]
     ]);
-    for (const [source, route] of [["client.ts", "/worker-client.js"], ["validator.worker.ts", "/validator.worker.js"]]) {
+    for (const [source, route] of [
+        ["main.mjs", "/worker-main.js"],
+        ["client.ts", "/worker-client.js"],
+        ["validator.worker.ts", "/validator.worker.js"]
+    ]) {
         const result = await build({
             entryPoints: [fileURLToPath(new URL(source, import.meta.url))],
             platform: "browser",
diff --git a/typescript/experimental/browser/examples/worker/host.mjs b/typescript/experimental/browser/examples/worker/host.mjs
new file mode 100644
index 00000000..9912ef3d
--- /dev/null
+++ b/typescript/experimental/browser/examples/worker/host.mjs
@@ -0,0 +1,101 @@
+import { createHash } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { gzipSync } from "node:zlib";
+import { buildWorkerExample, wasmAssetPath } from "./build.mjs";
+import { wasmByteLength, wasmSha256 } from "../../dist/experimental/browser/src/versions.js";
+
+export { wasmAssetPath } from "./build.mjs";
+export const contentSecurityPolicy = [
+    "default-src 'none'",
+    "script-src 'self' 'wasm-unsafe-eval'",
+    "worker-src 'self'",
+    "connect-src 'self'",
+    "style-src 'self'",
+    "base-uri 'none'",
+    "form-action 'none'",
+    "frame-ancestors 'none'"
+].join("; ");
+
+function chooseEncoding(header) {
+    if (!header?.trim()) {
+        return "identity";
+    }
+    const qualities = new Map();
+    for (const entry of header.split(",")) {
+        const match = /^\s*([a-z0-9!#$%&'*+.^_`|~-]+)\s*(?:;\s*q\s*=\s*(0(?:\.\d{0,3})?|1(?:\.0{0,3})?))?\s*$/i.exec(entry);
+        if (!match) {
+            return { status: 400, message: "Invalid Accept-Encoding header." };
+        }
+        const name = match[1].toLowerCase();
+        qualities.set(name, Math.max(qualities.get(name) ?? 0, Number(match[2] ?? 1)));
+    }
+    const gzip = qualities.get("gzip") ?? qualities.get("*") ?? 0;
+    // Identity remains acceptable unless explicitly excluded, including by "*;q=0".
+    const identity = qualities.get("identity") ?? (qualities.get("*") === 0 ? 0 : 1);
+    if (gzip > 0 && gzip >= identity) {
+        return "gzip";
+    }
+    return identity > 0 ? "identity" : { status: 406, message: "No acceptable content encoding." };
+}
+
+export async function createWorkerExampleHandler() {
+    const assets = await buildWorkerExample();
+    const wasm = await readFile(new URL("../../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url));
+    if (wasm.length !== wasmByteLength || createHash("sha256").update(wasm).digest("hex") !== wasmSha256) {
+        throw new Error("The hosted WASM artifact does not match the pinned compiler.");
+    }
+    assets.set(wasmAssetPath, ["application/wasm", wasm]);
+    const representations = new Map();
+    for (const [route, [type, source]] of assets) {
+        const identity = Buffer.from(source);
+        const gzip = gzipSync(identity);
+        const etag = bytes => `"${createHash("sha256").update(bytes).digest("hex")}"`;
+        representations.set(route, { type, identity, gzip, identityTag: etag(identity), gzipTag: etag(gzip) });
+    }
+
+    return (request, response) => {
+        const asset = representations.get(request.url);
+        if (!asset) {
+            return false;
+        }
+        const headers = {
+            "Content-Security-Policy": contentSecurityPolicy,
+            "X-Content-Type-Options": "nosniff",
+            "Cache-Control": "no-store"
+        };
+        const fail = (status, message, extra = {}) => {
+            response.writeHead(status, { ...headers, "Content-Type": "text/plain; charset=utf-8", ...extra });
+            response.end(request.method === "HEAD" ? undefined : message);
+            return true;
+        };
+        if (request.method !== "GET" && request.method !== "HEAD") {
+            return fail(405, "Only GET and HEAD are supported.", { Allow: "GET, HEAD" });
+        }
+        const encoding = chooseEncoding(request.headers["accept-encoding"]);
+        if (typeof encoding !== "string") {
+            return fail(encoding.status, encoding.message);
+        }
+        const body = asset[encoding];
+        const tag = encoding === "gzip" ? asset.gzipTag : asset.identityTag;
+        headers["Content-Type"] = asset.type;
+        headers.Vary = "Accept-Encoding";
+        if (encoding === "gzip") {
+            headers["Content-Encoding"] = "gzip";
+        }
+        if (request.url === wasmAssetPath) {
+            headers["Cache-Control"] = "public, max-age=31536000, immutable";
+            headers.ETag = tag;
+            const matches = request.headers["if-none-match"]?.split(",")
+                .some(value => ["*", tag, `W/${tag}`].includes(value.trim()));
+            if (matches) {
+                response.writeHead(304, headers);
+                response.end();
+                return true;
+            }
+        }
+        headers["Content-Length"] = body.length;
+        response.writeHead(200, headers);
+        response.end(request.method === "HEAD" ? undefined : body);
+        return true;
+    };
+}
diff --git a/typescript/experimental/browser/examples/worker/index.html b/typescript/experimental/browser/examples/worker/index.html
index 05332c93..c678cbcf 100644
--- a/typescript/experimental/browser/examples/worker/index.html
+++ b/typescript/experimental/browser/examples/worker/index.html
@@ -1,14 +1,13 @@
 
 
+
 
 
 Experimental TypeChat worker validation
-
+
+
+
+
 

Experimental TypeChat worker validation

Offline example: no model calls or credentials. Each run owns a worker and a compiler. Cancellation terminates that worker. The experimental WASM download is @@ -22,45 +21,5 @@

Experimental TypeChat worker validation

Ready

Main-thread timer ticks: 0


-
+
 
diff --git a/typescript/experimental/browser/examples/worker/main.mjs b/typescript/experimental/browser/examples/worker/main.mjs
new file mode 100644
index 00000000..03e8e375
--- /dev/null
+++ b/typescript/experimental/browser/examples/worker/main.mjs
@@ -0,0 +1,47 @@
+import { validateInWorker } from "./client.js";
+
+const run = document.getElementById("run");
+const cancel = document.getElementById("cancel");
+const status = document.getElementById("status");
+const result = document.getElementById("result");
+const wasmPath = document.body.dataset.wasmUrl;
+if (!wasmPath) {
+    status.textContent = "The example has no configured WASM asset URL.";
+    throw new Error(status.textContent);
+}
+
+let controller;
+let ticks = 0;
+const timer = setInterval(() => document.getElementById("ticks").textContent = String(++ticks), 50);
+cancel.onclick = () => controller?.abort();
+run.onclick = async () => {
+    controller = new AbortController();
+    run.disabled = true;
+    cancel.disabled = false;
+    status.textContent = "Starting worker";
+    result.textContent = "";
+    try {
+        const values = JSON.parse(document.getElementById("values").value);
+        const report = await validateInWorker("/validator.worker.js", {
+            wasmUrl: new URL(wasmPath, location.href).href,
+            schema: 'export enum Status { Active = "active", Paused = "paused" } export interface Request { status: Status; value: number; }',
+            typeName: "Request",
+            values
+        }, {
+            signal: AbortSignal.any([controller.signal, AbortSignal.timeout(60_000)]),
+            onPhase: phase => status.textContent = phase
+        });
+        result.textContent = JSON.stringify(report, null, 2);
+        status.textContent = "Completed; worker disposed";
+    } catch (error) {
+        status.textContent = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
+    } finally {
+        run.disabled = false;
+        cancel.disabled = true;
+        controller = undefined;
+    }
+};
+addEventListener("pagehide", () => {
+    clearInterval(timer);
+    controller?.abort();
+}, { once: true });
diff --git a/typescript/experimental/browser/examples/worker/serve.mjs b/typescript/experimental/browser/examples/worker/serve.mjs
index 0ad58995..112a00dd 100644
--- a/typescript/experimental/browser/examples/worker/serve.mjs
+++ b/typescript/experimental/browser/examples/worker/serve.mjs
@@ -1,21 +1,12 @@
-import { readFile } from "node:fs/promises";
 import { createServer } from "node:http";
-import { buildWorkerExample } from "./build.mjs";
+import { createWorkerExampleHandler } from "./host.mjs";
 
-const assets = await buildWorkerExample();
-assets.set("/tsc.wasm", [
-    "application/wasm",
-    await readFile(new URL("../../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url))
-]);
+const handleExample = await createWorkerExampleHandler();
 const server = createServer((request, response) => {
-    const asset = assets.get(request.url);
-    if (request.method !== "GET" || !asset) {
-        response.writeHead(404);
+    if (!handleExample(request, response)) {
+        response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
         response.end("Not found");
-        return;
     }
-    response.writeHead(200, { "Content-Type": asset[0], "Cache-Control": "no-store" });
-    response.end(asset[1]);
 });
 server.listen(0, "127.0.0.1", () => {
     const address = server.address();
diff --git a/typescript/experimental/browser/examples/worker/style.css b/typescript/experimental/browser/examples/worker/style.css
new file mode 100644
index 00000000..0e4c9a30
--- /dev/null
+++ b/typescript/experimental/browser/examples/worker/style.css
@@ -0,0 +1,4 @@
+body { font: 1rem system-ui; max-width: 55rem; margin: 2rem auto; padding: 0 1rem; }
+textarea { display: block; width: 100%; min-height: 7rem; margin: 1rem 0; }
+button { padding: .5rem 1rem; margin-right: .5rem; }
+pre { white-space: pre-wrap; overflow-wrap: anywhere; }
diff --git a/typescript/experimental/browser/tests/browser/browser.test.mjs b/typescript/experimental/browser/tests/browser/browser.test.mjs
index 2d4f153d..f5eaaf18 100644
--- a/typescript/experimental/browser/tests/browser/browser.test.mjs
+++ b/typescript/experimental/browser/tests/browser/browser.test.mjs
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
 import { gzipSync } from "node:zlib";
 import { build } from "esbuild";
 import { chromium, firefox, webkit } from "playwright";
-import { buildWorkerExample } from "../../examples/worker/build.mjs";
+import { createWorkerExampleHandler } from "../../examples/worker/host.mjs";
 import { sampleBrowserMemory } from "./process-memory.mjs";
 
 for (const engine of [chromium, firefox, webkit]) {
@@ -66,8 +66,9 @@ for (const engine of [chromium, firefox, webkit]) {
             ["/worker-probe.js", ["text/javascript", workerProbe.outputFiles[0].contents]],
             ["/broken-worker.js", ["text/javascript", 'throw new Error("synthetic worker startup failure");']]
         ]);
-        for (const [route, asset] of await buildWorkerExample()) assets.set(route, asset);
+        const handleExample = await createWorkerExampleHandler();
         const server = createServer((request, response) => {
+            if (handleExample(request, response)) return;
             if (request.url === "/slow.wasm" || request.url === "/worker-slow.wasm") {
                 response.writeHead(200, { "Content-Type": "application/wasm" });
                 response.write(wasm.subarray(0, 100));
@@ -154,7 +155,8 @@ for (const engine of [chromium, firefox, webkit]) {
         assert.deepEqual(await page.evaluate(() => globalThis.runMismatchProbe()), { rejected: true, fetchCalls: 0 });
         await page.goto(`http://127.0.0.1:${address.port}/worker`);
         await page.locator("#run").click();
-        await page.waitForFunction(() => document.getElementById("status").textContent === "Completed; worker disposed");
+        await page.waitForFunction(() => !document.getElementById("run").disabled, null, { timeout: 65000 });
+        assert.equal(await page.locator("#status").innerText(), "Completed; worker disposed");
         const demo = JSON.parse(await page.locator("#result").innerText());
         assert.deepEqual(demo.results.map(result => result.success), [true, false]);
         assert.equal(demo.closedLinearMemoryBytes, 0);
diff --git a/typescript/experimental/browser/tests/browser/hosting.test.mjs b/typescript/experimental/browser/tests/browser/hosting.test.mjs
new file mode 100644
index 00000000..e53e9a46
--- /dev/null
+++ b/typescript/experimental/browser/tests/browser/hosting.test.mjs
@@ -0,0 +1,123 @@
+import assert from "node:assert/strict";
+import { once } from "node:events";
+import { createServer } from "node:http";
+import { test } from "node:test";
+import { chromium, firefox, webkit } from "playwright";
+import {
+    contentSecurityPolicy, createWorkerExampleHandler, wasmAssetPath
+} from "../../examples/worker/host.mjs";
+
+for (const engine of [chromium, firefox, webkit]) {
+    test(`${engine.name()}: hosted worker obeys CSP and consumes versioned compressed assets`, { timeout: 90000 }, async t => {
+        const handle = await createWorkerExampleHandler();
+        let workerSource;
+        const assetRequests = [];
+        const server = createServer((request, response) => {
+            if (request.url === "/csp-probe.js") {
+                response.writeHead(200, { "Content-Type": "text/javascript", "Cache-Control": "no-store" });
+                response.end(`
+                    globalThis.cspProbe = { evalBlocked: false };
+                    try { new Function("return 1")(); }
+                    catch (error) { globalThis.cspProbe.evalBlocked = error.name === "EvalError"; }
+                `);
+                return;
+            }
+            if (request.url === "/csp-denied-worker.js") {
+                response.writeHead(200, {
+                    "Content-Type": "text/javascript",
+                    "Cache-Control": "no-store",
+                    "Content-Security-Policy": contentSecurityPolicy.replace(" 'wasm-unsafe-eval'", "")
+                });
+                response.end(workerSource);
+                return;
+            }
+            if (request.url === wasmAssetPath) {
+                const writeHead = response.writeHead;
+                t.mock.method(response, "writeHead", function (status, headers) {
+                    assetRequests.push({
+                        status,
+                        encoding: headers["Content-Encoding"],
+                        bytes: Number(headers["Content-Length"] ?? 0)
+                    });
+                    return writeHead.call(this, status, headers);
+                });
+            }
+            if (!handle(request, response)) {
+                response.writeHead(404, { "Cache-Control": "no-store" });
+                response.end();
+            }
+        });
+        let browser;
+        t.after(async () => {
+            try {
+                await browser?.close();
+            } finally {
+                server.closeAllConnections();
+                await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
+            }
+        });
+        await new Promise((resolve, reject) => {
+            server.once("error", reject);
+            server.listen(0, "127.0.0.1", resolve);
+        });
+        const address = server.address();
+        assert.ok(address && typeof address !== "string");
+        const origin = `http://127.0.0.1:${address.port}`;
+        const sourceResponse = await fetch(`${origin}/validator.worker.js`);
+        assert.equal(sourceResponse.status, 200);
+        workerSource = Buffer.from(await sourceResponse.arrayBuffer());
+        browser = await engine.launch({ headless: true });
+        const page = await browser.newPage();
+        const errors = [];
+        const workersClosed = [];
+        page.on("pageerror", error => errors.push(error.message));
+        page.on("worker", worker => workersClosed.push(once(worker, "close")));
+        const pageResponse = await page.goto(`${origin}/worker`);
+        assert.equal(pageResponse.headers()["content-security-policy"], contentSecurityPolicy);
+        assert.equal(await page.locator("body").getAttribute("data-wasm-url"), wasmAssetPath);
+
+        for (let run = 0; run < 2; run++) {
+            await page.locator("#run").click();
+            await page.waitForFunction(() => !document.getElementById("run").disabled, null, { timeout: 65000 });
+            assert.equal(await page.locator("#status").innerText(), "Completed; worker disposed");
+            const report = JSON.parse(await page.locator("#result").innerText());
+            assert.deepEqual(report.results.map(result => result.success), [true, false]);
+            assert.equal(report.closedLinearMemoryBytes, 0);
+        }
+        const repeatRequests = assetRequests.slice();
+        assert.ok(repeatRequests.length >= 1 && repeatRequests.length <= 2);
+        assert.ok(repeatRequests.every(request => request.encoding === "gzip"), JSON.stringify(repeatRequests));
+        assert.ok(repeatRequests.every(request => request.status === 304 || request.bytes < 16 * 1024 * 1024));
+
+        // Execute the check as a real page script, not debugger evaluation that can bypass CSP.
+        await page.addScriptTag({ url: `${origin}/csp-probe.js` });
+        assert.equal(await page.evaluate(() => globalThis.cspProbe.evalBlocked), true);
+        const denied = await page.evaluate(async () => {
+            const { validateInWorker } = await import("/worker-client.js");
+            try {
+                await validateInWorker("/csp-denied-worker.js", {
+                    wasmUrl: new URL(document.body.dataset.wasmUrl, location.href).href,
+                    schema: "export interface Probe { value: number; }",
+                    typeName: "Probe",
+                    values: [{ value: 1 }]
+                }, { signal: AbortSignal.timeout(30000) });
+                return { rejected: false };
+            } catch (error) {
+                return { rejected: true, name: error.name, message: error.message };
+            }
+        });
+        assert.equal(denied.rejected, true, "Omitting WASM permission must not silently bypass CSP.");
+        assert.match(denied.message, /WebAssembly|Content Security Policy|CSP|unsafe-eval/i);
+        await Promise.all(workersClosed);
+        assert.equal(page.workers().length, 0);
+        assert.deepEqual(errors, []);
+        t.diagnostic(JSON.stringify({
+            browser: `${engine.name()} ${browser.version()}`,
+            cspEnforced: true,
+            repeatedJobs: 2,
+            networkArtifactResponses: repeatRequests,
+            cacheAvoidedSecondRequest: repeatRequests.length === 1,
+            wasmDeniedError: denied.name
+        }));
+    });
+}
diff --git a/typescript/experimental/browser/tests/hosting.test.mjs b/typescript/experimental/browser/tests/hosting.test.mjs
new file mode 100644
index 00000000..0215b8d6
--- /dev/null
+++ b/typescript/experimental/browser/tests/hosting.test.mjs
@@ -0,0 +1,137 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { createServer, request } from "node:http";
+import { after, before, test } from "node:test";
+import { gunzipSync } from "node:zlib";
+import {
+    contentSecurityPolicy, createWorkerExampleHandler, wasmAssetPath
+} from "../examples/worker/host.mjs";
+import { compilerVersion, wasmByteLength, wasmSha256 } from "../dist/experimental/browser/src/versions.js";
+
+let server;
+let origin;
+before(async () => {
+    const handle = await createWorkerExampleHandler();
+    server = createServer((request, response) => {
+        if (!handle(request, response)) {
+            response.writeHead(404, { "Cache-Control": "no-store" });
+            response.end();
+        }
+    });
+    await new Promise((resolve, reject) => {
+        server.once("error", reject);
+        server.listen(0, "127.0.0.1", resolve);
+    });
+    const address = server.address();
+    assert.ok(address && typeof address !== "string");
+    origin = `http://127.0.0.1:${address.port}`;
+});
+after(async () => {
+    server?.closeAllConnections();
+    if (server?.listening) {
+        await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
+    }
+});
+
+function get(path, { method = "GET", headers = {} } = {}) {
+    return new Promise((resolve, reject) => {
+        const req = request(new URL(path, origin), { method, headers }, response => {
+            const chunks = [];
+            response.on("data", chunk => chunks.push(chunk));
+            response.once("error", reject);
+            response.once("end", () => resolve({
+                status: response.statusCode,
+                headers: response.headers,
+                body: Buffer.concat(chunks)
+            }));
+        });
+        req.once("error", reject);
+        req.setTimeout(30000, () => req.destroy(new Error("Hosted asset request timed out.")));
+        req.end();
+    });
+}
+
+test("the HTML and worker use strict CSP without inline scripts/styles or JavaScript eval", async () => {
+    const page = await get("/worker");
+    assert.equal(page.status, 200);
+    assert.equal(page.headers["content-security-policy"], contentSecurityPolicy);
+    assert.equal(page.headers["cache-control"], "no-store");
+    assert.equal(page.headers["x-content-type-options"], "nosniff");
+    assert.ok(!contentSecurityPolicy.includes("'unsafe-inline'"));
+    assert.ok(!contentSecurityPolicy.includes("'unsafe-eval'"));
+    assert.ok(contentSecurityPolicy.includes("'wasm-unsafe-eval'"));
+    const html = page.body.toString("utf8");
+    assert.ok(html.includes(wasmAssetPath));
+    assert.doesNotMatch(html, /]*\bsrc=)[^>]*>/i);
+    assert.doesNotMatch(html, /)/i);
+    for (const path of ["/worker-main.js", "/worker.css", "/worker-client.js", "/validator.worker.js"]) {
+        const asset = await get(path, { method: "HEAD" });
+        assert.equal(asset.status, 200);
+        assert.equal(asset.headers["content-security-policy"], contentSecurityPolicy);
+        assert.equal(asset.headers["cache-control"], "no-store");
+        assert.equal(asset.body.length, 0);
+    }
+});
+
+test("the immutable versioned artifact preserves bytes in identity and gzip representations", async () => {
+    assert.ok(wasmAssetPath.includes(compilerVersion));
+    assert.ok(wasmAssetPath.includes(wasmSha256));
+    const identity = await get(wasmAssetPath);
+    const compressed = await get(wasmAssetPath, { headers: { "accept-encoding": "gzip" } });
+    for (const result of [identity, compressed]) {
+        assert.equal(result.status, 200);
+        assert.equal(result.headers["content-type"], "application/wasm");
+        assert.equal(result.headers.vary, "Accept-Encoding");
+        assert.equal(result.headers["cache-control"], "public, max-age=31536000, immutable");
+        assert.equal(Number(result.headers["content-length"]), result.body.length);
+        assert.equal(result.headers.etag, `"${createHash("sha256").update(result.body).digest("hex")}"`);
+    }
+    assert.equal(identity.headers["content-encoding"], undefined);
+    assert.equal(identity.body.length, wasmByteLength);
+    assert.equal(identity.headers.etag, `"${wasmSha256}"`);
+    assert.equal(compressed.headers["content-encoding"], "gzip");
+    assert.ok(compressed.body.length < 16 * 1024 * 1024);
+    assert.deepEqual(gunzipSync(compressed.body), identity.body);
+    assert.notEqual(compressed.headers.etag, identity.headers.etag);
+});
+
+test("conditional requests have no body and use the selected representation's validator", async () => {
+    const first = await get(wasmAssetPath, { method: "HEAD", headers: { "accept-encoding": "gzip" } });
+    const cached = await get(wasmAssetPath, {
+        headers: { "accept-encoding": "gzip", "if-none-match": `"other", W/${first.headers.etag}` }
+    });
+    assert.equal(cached.status, 304);
+    assert.equal(cached.body.length, 0);
+    assert.equal(cached.headers.etag, first.headers.etag);
+    assert.equal(cached.headers["content-length"], undefined);
+    const different = await get(wasmAssetPath, { method: "HEAD", headers: { "if-none-match": first.headers.etag } });
+    assert.equal(different.status, 200);
+    assert.equal(different.headers.etag, `"${wasmSha256}"`);
+    assert.equal(Number(different.headers["content-length"]), wasmByteLength);
+    const missing = await get(wasmAssetPath.replace(wasmSha256, "0".repeat(64)), { headers: { "if-none-match": "*" } });
+    assert.equal(missing.status, 404);
+    assert.equal(missing.headers["cache-control"], "no-store");
+});
+
+test("encoding exclusions, preferences, malformed headers, and unsupported methods are explicit", async () => {
+    for (const [encoding, status, expected] of [
+        ["gzip;q=0", 200, undefined],
+        ["GZIP; q=1, identity;q=0", 200, "gzip"],
+        ["gzip;q=0.1, identity;q=0.9", 200, undefined],
+        ["*", 200, "gzip"],
+        ["gzip;q=0, *;q=1", 200, undefined],
+        ["gzip;q=0, identity;q=0", 406, undefined],
+        ["*;q=0", 406, undefined],
+        ["gzip;q=2", 400, undefined]
+    ]) {
+        const result = await get(wasmAssetPath, { method: "HEAD", headers: { "accept-encoding": encoding } });
+        assert.equal(result.status, status, encoding);
+        assert.equal(result.headers["content-encoding"], expected, encoding);
+        assert.equal(result.body.length, 0);
+        if (status !== 200) assert.equal(result.headers["cache-control"], "no-store");
+    }
+    const post = await get(wasmAssetPath, { method: "POST" });
+    assert.equal(post.status, 405);
+    assert.equal(post.headers.allow, "GET, HEAD");
+    assert.match(post.body.toString("utf8"), /Only GET and HEAD/);
+});
diff --git a/typescript/experimental/browser/tests/stability.test.mjs b/typescript/experimental/browser/tests/stability.test.mjs
index 0db39601..a2348fdb 100644
--- a/typescript/experimental/browser/tests/stability.test.mjs
+++ b/typescript/experimental/browser/tests/stability.test.mjs
@@ -401,7 +401,7 @@ for (const engineName of ["chromium", "firefox", "webkit"]) {
     }, async t => {
         const { build } = await import("esbuild");
         const { [engineName]: engine } = await import("playwright");
-        const { buildWorkerExample } = await import("../examples/worker/build.mjs");
+        const { createWorkerExampleHandler } = await import("../examples/worker/host.mjs");
         const settings = { bundle: true, platform: "browser", format: "iife", write: false, logLevel: "silent" };
         const entry = await build({
             ...settings,
@@ -429,7 +429,8 @@ globalThis.mismatchedLoader = loadBrowserTypeScriptCompiler;`,
                 }
             }]
         });
-        const assets = await buildWorkerExample();
+        const handleExample = await createWorkerExampleHandler();
+        const assets = new Map();
         assets.set("/", ["text/html", '']);
         assets.set("/entry.js", ["text/javascript", entry.outputFiles[0].contents]);
         assets.set("/mismatch.js", ["text/javascript", mismatch.outputFiles[0].contents]);
@@ -437,6 +438,7 @@ globalThis.mismatchedLoader = loadBrowserTypeScriptCompiler;`,
         assets.set("/short.wasm", ["application/wasm", artifact.subarray(0, 100)]);
         let mismatchRequests = 0;
         const server = createServer((request, response) => {
+            if (handleExample(request, response)) return;
             if (request.url === "/never-fetch.wasm") mismatchRequests++;
             const asset = assets.get(request.url);
             response.writeHead(asset ? 200 : 404, { "Content-Type": asset?.[0] ?? "text/plain" });