sandboxedjs 0.1.47 → 0.1.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.d.cts +2 -1
- package/dist/agent.d.ts +2 -1
- package/dist/{container-DyRF-bY0.d.cts → container-DBMPLbUu.d.ts} +103 -410
- package/dist/{container-DyRF-bY0.d.ts → container-Dg8NwBc7.d.cts} +103 -410
- package/dist/index.cjs +2483 -311
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -65
- package/dist/index.d.ts +52 -65
- package/dist/index.js +2479 -310
- package/dist/index.js.map +1 -1
- package/dist/memory-volume-CTOXNJ6n.d.ts +66 -0
- package/dist/memory-volume-DCzGZFJb.d.cts +66 -0
- package/dist/python/python.data +16026 -66
- package/dist/python/python.js +2 -0
- package/dist/python/python.wasm +0 -0
- package/dist/python/python.worker.js +87 -0
- package/dist/python/runtime.json +34 -0
- package/dist/python-abi.cjs +2892 -0
- package/dist/python-abi.cjs.map +1 -0
- package/dist/python-abi.d.cts +645 -0
- package/dist/python-abi.d.ts +645 -0
- package/dist/python-abi.js +2839 -0
- package/dist/python-abi.js.map +1 -0
- package/dist/python-worker.js +865 -0
- package/dist/python-worker.js.map +1 -0
- package/dist/rolldown-wasi-worker.js +5 -1
- package/dist/rolldown-wasi-worker.js.map +1 -1
- package/dist/service-worker.js +34 -5
- package/dist/service-worker.js.map +1 -1
- package/dist/vfs-DzEcPbMY.d.cts +427 -0
- package/dist/vfs-DzEcPbMY.d.ts +427 -0
- package/package.json +8 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/preview/ws-client.ts","../src/preview/router.ts","../src/preview/service-worker.ts"],"names":["host","options"],"mappings":";AAgDO,SAAS,sBAAsB,KAAA,EAAkB;AACtD,EAAA,MAAM,SAAS,KAAA,CAAM,SAAA;AACrB,EAAA,MAAM,WAAW,KAAA,CAAM,QAAA;AAGvB,EAAA,IAAI,CAAC,KAAA,CAA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,OAAA,EAAQ;AAEf,EAAA,YAAA,EAAc,OAAA,EAAQ;AACxB,CAAC,CAAA;AAED,MAAA,CAAO,gBAAA,CAAiB,OAAA,EAAS,CAAC,KAAA,KAAU;AAC1C,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,KAAA,CAAM,QAAQ,GAAG,CAAA;AACrC,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,MAAA,CAAO,QAAA,CAAS,MAAA,EAAQ;AAE3C,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,WAAA,CAAY,GAAA,CAAI,QAAQ,CAAA;AAC/C,EAAA,IAAI,OAAA,KAAY,IAAA,IAAQ,KAAA,CAAM,OAAA,CAAQ,SAAS,UAAA,EAAY;AAIzD,IAAA,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,iBAAA,IAAqB,KAAA,CAAM,UAAU,OAAO,CAAA;AAC9D,IAAA,KAAA,CAAM,YAAY,MAAA,CAAO,KAAA,CAAM,SAAS,GAAA,EAAK,KAAA,CAAM,OAAO,CAAC,CAAA;AAC3D,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,QAAQ,CAAA;AAC1C,EAAA,IAAI,SAAS,MAAA,EAAW;AAIxB,EAAA,KAAA,CAAM,WAAA;AAAA,IACJ,MAAA,CAAO,KAAA,CAAM,IAAA,EAAM,MAAA,CAAO,aAAA,CAAc,GAAA,CAAI,QAAA,EAAU,GAAA,CAAI,MAAM,CAAA,EAAG,KAAA,CAAM,OAAO;AAAA,GAClF;AACF,CAAC,CAAA","file":"service-worker.js","sourcesContent":["/**\n * The WebSocket a page inside a preview actually gets.\n *\n * A service worker can answer `fetch`. It cannot answer a WebSocket handshake\n * — that was proposed and never shipped, in any browser — so the one mechanism\n * that gives a preview its URLs is structurally unable to carry the one\n * protocol a dev server needs. `new WebSocket(...)` inside the frame leaves the\n * sandbox entirely and tries the real origin, where nothing is listening.\n *\n * For a static site that costs nothing. For Vite it costs the HMR channel, and\n * with it the `full-reload` message Vite sends after re-optimizing its\n * dependencies — which is the *only* way it can tell a page that the hashes it\n * is holding are stale. Without it every `?v=` URL answers `504 Outdated\n * Optimize Dep` forever and the app never mounts, while the terminal shows a\n * dev server that started perfectly.\n *\n * So the constructor is replaced instead. {@link previewSocketSource} renders\n * this to JavaScript that the router injects into HTML it serves, where it\n * swaps in a `WebSocket` that tunnels to the host page over `postMessage`\n * rather than out to the network. URLs that do not name the container keep the\n * native implementation.\n *\n * ## Why this speaks the real protocol\n *\n * It would be less code to tunnel messages — `send(x)` on one side, `onmessage`\n * on the other — and let the container hand Vite something WebSocket-shaped.\n * That would work for Vite and nothing else, because Vite does not implement\n * WebSocket: `ws` does, and so do `socket.io` and every other server a user\n * might run. Framing the bytes here means the container emits a genuine\n * `upgrade` with a genuine socket, and those libraries run unmodified over it.\n * The sandbox gains WebSocket support, not a Vite compatibility shim.\n */\n\n/** The message names shared by the injected shim and {@link createPreview}. */\nexport const WS_OPEN = \"sandboxedjs:ws-open\";\nexport const WS_DATA = \"sandboxedjs:ws-data\";\nexport const WS_CLOSE = \"sandboxedjs:ws-close\";\nexport const WS_ERROR = \"sandboxedjs:ws-error\";\n\n/**\n * Install the tunnelling `WebSocket` on `scope`.\n *\n * Written as one self-contained function on purpose: {@link previewSocketSource}\n * serialises it with `String()`, so it may not close over anything in this\n * module. Everything it needs is either passed in or a page global. Keeping it\n * a real function rather than a template literal is what lets it be\n * type-checked and, more usefully, driven directly from a test.\n */\nexport function installPreviewSockets(scope: any): void {\n const Native = scope.WebSocket;\n const location = scope.location;\n /* No parent means this is not framed, so there is no host to tunnel to and\n * the native implementation is the best available answer. */\n if (!scope.parent || scope.parent === scope) return;\n const host = scope.parent;\n\n /** The port this document is previewing, from the path it was claimed at. */\n const claim = /(?:^|\\/)__sbx__\\/(\\d+)(?:\\/|$)/.exec(location.pathname);\n const claimedPort = claim ? Number(claim[1]) : null;\n\n const LOOPBACK = /^(?:localhost|127(?:\\.\\d{1,3}){3}|0\\.0\\.0\\.0|\\[?::1\\]?)$/i;\n\n /**\n * The container port and path a URL names, or null to leave it to the\n * network.\n *\n * Two forms arrive here. A dev server's client usually builds its URL from\n * `location`, so it points at this origin and means \"the port I am already\n * previewing\". A program with a hardcoded address says `localhost:3000` and\n * means that port. Anything else is a real remote host and is not ours.\n */\n function target(raw: string): { port: number; path: string } | null {\n let url: any;\n try {\n url = new URL(String(raw), location.href);\n } catch {\n return null;\n }\n if (url.protocol !== \"ws:\" && url.protocol !== \"wss:\") return null;\n\n const explicit = url.port ? Number(url.port) : null;\n const sameOrigin = url.hostname === location.hostname;\n let port: number | null = null;\n if (LOOPBACK.test(url.hostname) && explicit) port = explicit;\n else if (sameOrigin) port = claimedPort;\n if (port === null) return null;\n\n /* A document served under `/…/__sbx__/5173/` resolves a relative socket\n * URL against that prefix, which the container has never heard of. */\n const match = /(?:^|\\/)__sbx__\\/\\d+(?:\\/|$)/.exec(url.pathname);\n const rest = match ? url.pathname.slice(match.index + match[0].length) : url.pathname;\n const path = (rest.startsWith(\"/\") ? rest : \"/\" + rest) + url.search;\n return { port, path };\n }\n\n /** How long to wait for the host page before reporting it absent. */\n const OPEN_TIMEOUT_MS = 10_000;\n\n const encoder = new TextEncoder();\n const decoder = new TextDecoder();\n\n function concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n if (a.length === 0) return b;\n if (b.length === 0) return a;\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n }\n\n /**\n * One frame, masked.\n *\n * A client must mask; a server must not. `ws` closes the connection over\n * either mistake, so this is not a formality.\n */\n function frame(opcode: number, payload: Uint8Array): Uint8Array {\n const length = payload.length;\n const extended = length > 65535 ? 8 : length > 125 ? 2 : 0;\n const out = new Uint8Array(2 + extended + 4 + length);\n out[0] = 0x80 | opcode;\n let at = 2;\n if (extended === 0) {\n out[1] = 0x80 | length;\n } else if (extended === 2) {\n out[1] = 0x80 | 126;\n out[2] = (length >>> 8) & 0xff;\n out[3] = length & 0xff;\n at = 4;\n } else {\n out[1] = 0x80 | 127;\n /* The high four bytes stay zero: this payload came out of memory, so it\n * cannot reach 2^32. */\n out[6] = (length >>> 24) & 0xff;\n out[7] = (length >>> 16) & 0xff;\n out[8] = (length >>> 8) & 0xff;\n out[9] = length & 0xff;\n at = 10;\n }\n const mask = new Uint8Array(4);\n crypto.getRandomValues(mask);\n out.set(mask, at);\n at += 4;\n for (let i = 0; i < length; i++) out[at + i] = payload[i]! ^ mask[i & 3]!;\n return out;\n }\n\n /** An `Event` with extra properties, built without assuming `CloseEvent`. */\n function event(type: string, fields?: Record<string, unknown>): any {\n const value: any = new Event(type);\n if (fields) for (const key of Object.keys(fields)) {\n try {\n value[key] = fields[key];\n } catch {\n Object.defineProperty(value, key, { value: fields[key], enumerable: true });\n }\n }\n return value;\n }\n\n let nextId = 1;\n const live = new Map<number, any>();\n\n scope.addEventListener(\"message\", (message: any) => {\n /* Same-origin only. The preview and its host share an origin — that is the\n * documented trade-off of previewing this way — so anything from elsewhere\n * is not the host and has no business steering these sockets. */\n if (message.origin !== location.origin) return;\n const data = message.data;\n if (!data || typeof data !== \"object\") return;\n const socket = live.get(data.id);\n if (!socket) return;\n if (data.type === \"sandboxedjs:ws-data\") socket._receive(new Uint8Array(data.data));\n else if (data.type === \"sandboxedjs:ws-close\") socket._shutdown(1006, \"\", false);\n else if (data.type === \"sandboxedjs:ws-error\") socket._fail(String(data.message ?? \"connection failed\"));\n });\n\n class TunnelledWebSocket extends EventTarget {\n static readonly CONNECTING = 0;\n static readonly OPEN = 1;\n static readonly CLOSING = 2;\n static readonly CLOSED = 3;\n readonly CONNECTING = 0;\n readonly OPEN = 1;\n readonly CLOSING = 2;\n readonly CLOSED = 3;\n\n readonly url: string;\n readyState = 0;\n protocol = \"\";\n extensions = \"\";\n bufferedAmount = 0;\n binaryType: \"blob\" | \"arraybuffer\" = \"blob\";\n\n onopen: any = null;\n onmessage: any = null;\n onerror: any = null;\n onclose: any = null;\n\n private readonly id = nextId++;\n /** Handshake bytes first, frames after; the 101 arrives as bytes. */\n private handshaken = false;\n private buffer: Uint8Array<ArrayBufferLike> = new Uint8Array(0);\n /** A fragmented message in progress: its opcode and its pieces. */\n private fragmentOpcode = 0;\n private fragments: Uint8Array[] = [];\n\n constructor(url: string, protocols?: string | string[]) {\n super();\n const to = target(url);\n /* Only reachable when `create` chose this class, which it does only for\n * URLs `target` has already accepted. */\n if (!to) throw new SyntaxError(`Not a container address: ${url}`);\n this.url = String(new URL(String(url), location.href));\n\n const list = protocols === undefined ? [] : typeof protocols === \"string\" ? [protocols] : protocols;\n const key = (() => {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n })();\n\n const headers: Record<string, string> = {\n /*\n * The address the server believes it is on, not the one the page is\n * loaded from. A dev server validates `Host` on the upgrade — Vite has\n * done so since it closed CVE-2025-24010 — against a list that always\n * contains loopback and never contains whatever origin happens to be\n * hosting this preview. Sending the page's host means a handshake\n * rejected for a reason that has nothing to do with the sandbox.\n */\n host: `localhost:${to.port}`,\n connection: \"Upgrade\",\n upgrade: \"websocket\",\n \"sec-websocket-version\": \"13\",\n \"sec-websocket-key\": key,\n origin: location.origin,\n };\n if (list.length) headers[\"sec-websocket-protocol\"] = list.join(\", \");\n\n live.set(this.id, this);\n host.postMessage(\n { type: \"sandboxedjs:ws-open\", id: this.id, port: to.port, path: to.path, headers },\n location.origin,\n );\n /*\n * Nobody answering is a real state, not a hypothetical: the page hosting\n * this preview may be running a build of `createPreview` older than the\n * one that injected this script, in which case the message lands\n * nowhere. Left alone that is an open socket that never opens and never\n * closes — the worst failure to diagnose, because nothing is reported at\n * all. Failing loudly turns it into a sentence in the console.\n */\n setTimeout(() => {\n if (this.readyState === 0) {\n this._fail(\"The page hosting this preview did not answer the WebSocket. It may be running an older version of sandboxedjs.\");\n }\n }, OPEN_TIMEOUT_MS);\n }\n\n send(data: any): void {\n if (this.readyState === 0) throw new DOMException(\"Still in CONNECTING state.\", \"InvalidStateError\");\n if (this.readyState !== 1) return;\n if (typeof data === \"string\") this._write(0x1, encoder.encode(data));\n else if (data instanceof ArrayBuffer) this._write(0x2, new Uint8Array(data));\n else if (ArrayBuffer.isView(data)) this._write(0x2, new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n else this._write(0x1, encoder.encode(String(data)));\n }\n\n close(code?: number, reason?: string): void {\n if (this.readyState === 2 || this.readyState === 3) return;\n const body = encoder.encode(reason ?? \"\");\n const payload = new Uint8Array(2 + body.length);\n payload[0] = ((code ?? 1000) >>> 8) & 0xff;\n payload[1] = (code ?? 1000) & 0xff;\n payload.set(body, 2);\n if (this.readyState === 1) this._write(0x8, payload);\n this.readyState = 2;\n host.postMessage({ type: \"sandboxedjs:ws-close\", id: this.id }, location.origin);\n }\n\n private _write(opcode: number, payload: Uint8Array): void {\n const bytes = frame(opcode, payload);\n /* Copied into a fresh buffer so it can be transferred without taking the\n * caller's memory with it. */\n const carrier = bytes.slice().buffer;\n host.postMessage({ type: \"sandboxedjs:ws-data\", id: this.id, data: carrier }, location.origin, [carrier]);\n }\n\n private _emit(value: any): void {\n const handler = (this as any)[\"on\" + value.type];\n if (typeof handler === \"function\") handler.call(this, value);\n this.dispatchEvent(value);\n }\n\n _fail(message: string): void {\n if (this.readyState === 3) return;\n this._emit(event(\"error\", { message }));\n this._shutdown(1006, \"\", false);\n }\n\n /** Bytes from the container: the 101, then frames. */\n _receive(bytes: Uint8Array): void {\n if (this.readyState === 3) return;\n this.buffer = concat(this.buffer, bytes);\n if (!this.handshaken && !this._handshake()) return;\n this._frames();\n }\n\n /**\n * Read the `101` the server wrote onto the socket.\n *\n * The container builds the request from structured fields, but the reply\n * comes back as the bytes `ws` wrote — a real status line and real headers\n * — so it is parsed as one.\n */\n private _handshake(): boolean {\n const text = decoder.decode(this.buffer);\n const end = text.indexOf(\"\\r\\n\\r\\n\");\n if (end === -1) return false;\n const head = text.slice(0, end).split(\"\\r\\n\");\n const status = Number(head[0]?.split(\" \")[1]);\n if (status !== 101) {\n this._fail(`Server refused the WebSocket upgrade (${status || \"no status\"})`);\n return false;\n }\n for (const line of head.slice(1)) {\n const at = line.indexOf(\":\");\n if (at === -1) continue;\n if (line.slice(0, at).trim().toLowerCase() === \"sec-websocket-protocol\") {\n this.protocol = line.slice(at + 1).trim();\n }\n }\n /* The header is ASCII, so its character count is its byte count. */\n this.buffer = this.buffer.subarray(end + 4);\n this.handshaken = true;\n this.readyState = 1;\n this._emit(event(\"open\"));\n return true;\n }\n\n private _frames(): void {\n for (;;) {\n const view = this.buffer;\n if (view.length < 2) return;\n const first = view[0]!;\n const second = view[1]!;\n const fin = (first & 0x80) !== 0;\n const opcode = first & 0x0f;\n const masked = (second & 0x80) !== 0;\n let length = second & 0x7f;\n let at = 2;\n if (length === 126) {\n if (view.length < 4) return;\n length = (view[2]! << 8) | view[3]!;\n at = 4;\n } else if (length === 127) {\n if (view.length < 10) return;\n /* Arithmetic rather than shifts: the top half of a 64-bit length\n * does not survive a 32-bit bitwise operator. */\n const high = view[2]! * 2 ** 24 + view[3]! * 2 ** 16 + view[4]! * 2 ** 8 + view[5]!;\n const low = view[6]! * 2 ** 24 + view[7]! * 2 ** 16 + view[8]! * 2 ** 8 + view[9]!;\n length = high * 2 ** 32 + low;\n at = 10;\n }\n let mask: Uint8Array | null = null;\n if (masked) {\n if (view.length < at + 4) return;\n mask = view.subarray(at, at + 4);\n at += 4;\n }\n if (view.length < at + length) return;\n const payload = view.slice(at, at + length);\n if (mask) for (let i = 0; i < length; i++) payload[i] = payload[i]! ^ mask[i & 3]!;\n this.buffer = view.subarray(at + length);\n this._frame(fin, opcode, payload);\n if (this.readyState === 3) return;\n }\n }\n\n private _frame(fin: boolean, opcode: number, payload: Uint8Array): void {\n if (opcode === 0x9) {\n /* A pong has to carry the ping's payload back verbatim. `ws` pings on\n * a timer, and a client that never answers is dropped. */\n if (this.readyState === 1) this._write(0xa, payload);\n return;\n }\n if (opcode === 0xa) return;\n if (opcode === 0x8) {\n const code = payload.length >= 2 ? (payload[0]! << 8) | payload[1]! : 1005;\n const reason = payload.length > 2 ? decoder.decode(payload.subarray(2)) : \"\";\n if (this.readyState === 1) this._write(0x8, payload);\n this.readyState = 2;\n host.postMessage({ type: \"sandboxedjs:ws-close\", id: this.id }, location.origin);\n this._shutdown(code, reason, true);\n return;\n }\n\n if (opcode !== 0x0) {\n this.fragmentOpcode = opcode;\n this.fragments = [];\n }\n this.fragments.push(payload);\n if (!fin) return;\n\n let total = 0;\n for (const piece of this.fragments) total += piece.length;\n const body = new Uint8Array(total);\n let offset = 0;\n for (const piece of this.fragments) {\n body.set(piece, offset);\n offset += piece.length;\n }\n this.fragments = [];\n\n const data = this.fragmentOpcode === 0x1\n ? decoder.decode(body)\n : this.binaryType === \"arraybuffer\"\n ? body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)\n : new Blob([body as BlobPart]);\n this._emit(event(\"message\", { data, origin: location.origin, lastEventId: \"\", source: null, ports: [] }));\n }\n\n _shutdown(code: number, reason: string, wasClean: boolean): void {\n if (this.readyState === 3) return;\n this.readyState = 3;\n live.delete(this.id);\n this._emit(event(\"close\", { code, reason, wasClean }));\n }\n }\n\n /**\n * The replacement constructor.\n *\n * A plain function so `new WebSocket(url)` can pick an implementation per\n * URL — anything not naming the container has to keep working, and that\n * includes a page talking to a genuine remote server from inside a preview.\n */\n function create(this: any, url: string, protocols?: string | string[]): any {\n if (!target(url)) return protocols === undefined ? new Native(url) : new Native(url, protocols);\n return new TunnelledWebSocket(url, protocols);\n }\n\n create.prototype = TunnelledWebSocket.prototype;\n (create as any).CONNECTING = 0;\n (create as any).OPEN = 1;\n (create as any).CLOSING = 2;\n (create as any).CLOSED = 3;\n /* `instanceof` has to keep answering for native sockets too, since only some\n * of them are ours. */\n Object.defineProperty(create, Symbol.hasInstance, {\n value: (value: unknown) => value instanceof TunnelledWebSocket || value instanceof Native,\n });\n\n scope.WebSocket = create;\n /* A one-word answer to \"is this actually installed?\", which is otherwise\n * only observable by noticing that a WebSocket *failed* to appear in the\n * network panel. Reading a global in the frame's console is a far shorter\n * path to that answer than reasoning about it. */\n scope.__sandboxedjsPreviewSockets = true;\n}\n\n/**\n * The shim, as a `<script>` body.\n *\n * Serialising the function keeps one implementation: what a test drives is\n * character-for-character what a preview runs. The call is wrapped so a\n * failure to install cannot take the page's own scripts down with it — a\n * preview without hot reload is worth far more than a blank frame.\n */\nexport function previewSocketSource(): string {\n return `(function(){try{(${installPreviewSockets.toString()})(window);}catch(error){console.warn(\"sandboxedjs: preview WebSocket unavailable\",error);}})();`;\n}\n","/**\n * The routing a preview service worker does, separated from the worker itself.\n *\n * A service worker is awkward to test — it needs a browser, a registration and\n * a secure context — but almost none of what makes this correct is about being\n * a service worker. The interesting part is the bookkeeping: which client is\n * previewing which port, which requests belong to a preview at all, and how a\n * response is rebuilt on the way back. That lives here, where it can be\n * exercised directly.\n *\n * The rule this implements, and the reason it exists: requests are routed by\n * **who is asking**, not by what the path looks like. An iframe navigates once\n * to `/__sbx__/<port>/`; every later request from that client — however\n * absolute its path — is recognised by its client id. Nothing has to rewrite\n * `/src/main.js` or `/@vite/client`, which is what makes a real dev server\n * work rather than only a single page.\n */\n\nimport { previewSocketSource } from \"./ws-client.js\";\n\n/**\n * The one-time path an iframe navigates to in order to claim a port.\n *\n * Deliberately not anchored to the start of the path. A service worker's scope\n * is the directory its script was served from, so in a published package the\n * claim arrives under something like\n * `/node_modules/sandboxedjs/dist/__sbx__/5173/` — anchoring here would match\n * only when the worker happened to be served from the site root.\n */\nconst CLAIM = /(?:^|\\/)__sbx__\\/(\\d+)(?:\\/|$)/;\n\nexport interface ProxiedRequest {\n id: number;\n port: number;\n path: string;\n method: string;\n headers: Record<string, string>;\n body?: ArrayBuffer;\n}\n\nexport interface ProxiedResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: ArrayBuffer;\n}\n\nexport interface PreviewRouterOptions {\n /** Hand a request to whichever page owns the container. */\n send(request: ProxiedRequest, transfer: ArrayBuffer[]): void;\n /** How long to wait for that page before giving up. */\n timeoutMs?: number;\n /**\n * Ask the owning page to hand over a fresh channel, and resolve once it has.\n *\n * A service worker is not a process that stays running. The browser stops it\n * whenever it looks idle — seconds, in practice — and starts it again for\n * the next request, with every module-level value gone. The `MessagePort`\n * that reaches the container is one of those values, so a worker that has\n * been restarted has no way to answer anything, however healthy the\n * container behind it still is.\n *\n * Nothing about that is visible: the server is running, the port is open,\n * and the preview simply stops working — on reload, in a new tab, or after\n * a pause long enough for the browser to reclaim the worker. The page is\n * still there and can always supply another port, so the worker asks for one\n * rather than failing.\n */\n requestHost?(): Promise<void>;\n /**\n * The dev server has invalidated what the page is holding; reload it.\n *\n * Vite answers a request for a pre-bundled dependency with `504 Outdated\n * Optimize Dep` whenever the hash in the URL no longer matches — after the\n * optimizer re-runs, or after the server restarts. Its own client recovers\n * by reloading the whole page, and it learns to do that over the HMR\n * WebSocket.\n *\n * This bridge carries HTTP and nothing else, so that signal never arrives.\n * The page goes on requesting URLs stamped with a hash the server has\n * forgotten, every module 504s, and the app never mounts — while the\n * terminal reports a dev server that started perfectly. A plain static\n * server never does this, which is why vanilla pages worked and React did\n * not.\n */\n onStale?(): void;\n /**\n * Give previewed pages a `WebSocket` that reaches the container.\n *\n * A service worker cannot answer a WebSocket handshake — no browser ever\n * shipped that — so the only way a page inside a preview can open one is to\n * be handed a different constructor. Injecting it into the HTML is how that\n * gets there, and it is on by default because a dev server without its HMR\n * channel does not merely lose hot reload: it loses the only way it can tell\n * a page that its dependency hashes are stale, which strands the preview on\n * `504 Outdated Optimize Dep` with nothing to explain it.\n */\n injectSockets?: boolean;\n}\n\n/** Vite's answer when the page is holding a dependency hash it has dropped. */\nconst OUTDATED = /outdated optimize dep/i;\n\n/** The port to answer with when nothing has connected yet. */\nconst NOT_CONNECTED = 503;\n\nexport class PreviewRouter {\n private readonly clientPorts = new Map<string, number>();\n private readonly pending = new Map<number, (value: ProxiedResponse) => void>();\n private nextId = 1;\n private connected = false;\n\n constructor(private readonly options: PreviewRouterOptions) {}\n\n /** Whether a page has handed over a channel this worker can still use. */\n get ready(): boolean {\n return this.connected;\n }\n\n /** The page that answers requests has arrived. */\n connect(): void {\n this.connected = true;\n }\n\n /** The channel is gone; the next request has to ask for another. */\n disconnect(): void {\n this.connected = false;\n }\n\n /** Read a port out of a claim path, or null when this is not one. */\n /**\n * The path to ask the container for, given a request from a bound client.\n *\n * A document served at `/…/__sbx__/3000/` resolves its *relative* assets\n * against that prefix, so `./app.js` arrives as\n * `/…/__sbx__/3000/app.js`. Forwarding that verbatim asks the container for\n * a file inside a directory it has never heard of, and every relative asset\n * in the site 404s while the document itself loads perfectly — a page that\n * renders unstyled and inert, with nothing to explain why.\n *\n * Root-relative assets (`/main.js`) carry no prefix and pass through\n * unchanged, which is the case that always worked.\n */\n containerPath(pathname: string, search: string): string {\n const match = CLAIM.exec(pathname);\n const rest = match ? pathname.slice(match.index + match[0].length) : pathname;\n const normalised = rest.startsWith(\"/\") ? rest : `/${rest}`;\n return `${normalised}${search}`;\n }\n\n claimedPort(pathname: string): number | null {\n const match = CLAIM.exec(pathname);\n return match ? Number(match[1]) : null;\n }\n\n /** Remember that everything from `clientId` belongs to `port`. */\n bind(clientId: string, port: number): void {\n if (clientId) this.clientPorts.set(clientId, port);\n }\n\n /** Which port this client is previewing, or undefined for ordinary traffic. */\n portFor(clientId: string): number | undefined {\n return this.clientPorts.get(clientId);\n }\n\n /** A response has come back from the page. */\n settle(id: number, response: ProxiedResponse): void {\n const resolve = this.pending.get(id);\n if (!resolve) return;\n this.pending.delete(id);\n resolve(response);\n }\n\n /** Forget a client that has gone away. */\n release(clientId: string): void {\n this.clientPorts.delete(clientId);\n }\n\n /** Ask the page for one response and rebuild it as a `Response`. */\n async fetch(port: number, path: string, request: Request): Promise<Response> {\n /* Restarted, most likely, rather than never started. Ask the page for a\n * channel before concluding there is nobody to ask. */\n if (!this.connected) await this.options.requestHost?.().catch(() => undefined);\n\n if (!this.connected) {\n return isolated(\n new Response(\n 'The sandbox preview is not connected yet. The page that owns this container has to be open.',\n { status: NOT_CONNECTED, statusText: 'Service Unavailable' },\n ),\n );\n }\n const sent = request.method === \"GET\" || request.method === \"HEAD\" ? undefined : await request.arrayBuffer();\n const id = this.nextId++;\n const answered = new Promise<ProxiedResponse>((resolve) => this.pending.set(id, resolve));\n\n this.options.send(\n { id, port, path, method: request.method, headers: headerRecord(request.headers), ...(sent ? { body: sent } : {}) },\n sent ? [sent] : [],\n );\n\n const timeoutMs = this.options.timeoutMs ?? 30_000;\n const result = await Promise.race([\n answered,\n new Promise<ProxiedResponse>((resolve) =>\n setTimeout(\n () => resolve({ status: 504, statusText: \"Gateway Timeout\", headers: {}, body: new ArrayBuffer(0) }),\n timeoutMs,\n ),\n ),\n ]);\n this.pending.delete(id);\n\n /* Nothing here can rewrite the URL the page asked for — only the page can\n * ask again, and only after reloading. Report it and let the host decide;\n * a reload driven from inside the frame would fight the app for control of\n * its own navigation. */\n if (result.status === 504 && OUTDATED.test(result.statusText)) {\n this.options.onStale?.();\n }\n\n const headers = new Headers(result.headers);\n const body = this.options.injectSockets === false ? result.body : withSockets(result.body, headers);\n /*\n * Two headers, for two different refusals, both of which a cross-origin\n * isolated page makes — and pages that run Rolldown have to be isolated.\n *\n * `Cross-Origin-Resource-Policy` lets the response be loaded as a\n * subresource at all. `Cross-Origin-Embedder-Policy` lets it be *framed*:\n * without it the document is not isolation-compatible, so the iframe is\n * replaced by an error page and the parent sees an opaque, cross-origin\n * frame rather than the site it asked for. Everything served here carries\n * CORP, so the stricter policy is one this preview can satisfy.\n */\n headers.set(\"Cross-Origin-Resource-Policy\", \"cross-origin\");\n headers.set(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n return new Response(body, { status: result.status, statusText: result.statusText, headers });\n }\n}\n\n/**\n * The isolation headers, on a response this router made up itself.\n *\n * Every failure here is still framed by a cross-origin isolated page, and a\n * document without these is not merely shown as an error — it is refused\n * before it renders, so the reader gets the browser's \"refused to connect\"\n * instead of the sentence explaining what went wrong. An error nobody can read\n * is worse than the failure it describes.\n */\nfunction isolated(response: Response): Response {\n const headers = new Headers(response.headers);\n headers.set(\"Content-Type\", \"text/plain; charset=utf-8\");\n headers.set(\"Cross-Origin-Resource-Policy\", \"cross-origin\");\n headers.set(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/**\n * Put the tunnelling `WebSocket` into an HTML document before anything runs.\n *\n * Only HTML, and only HTML this router can read: a compressed body would have\n * to be decoded and re-encoded to be edited, and getting that wrong corrupts\n * the page rather than merely failing to patch it. Anything skipped here keeps\n * the native `WebSocket`, which is exactly what it had before.\n *\n * The script goes directly after `<head>` so it is installed before the\n * document's own scripts — a dev server's client is one of the first of them,\n * and it opens its socket immediately.\n */\nfunction withSockets(body: ArrayBuffer, headers: Headers): ArrayBuffer {\n const type = headers.get(\"content-type\") ?? \"\";\n if (!/^\\s*text\\/html\\b/i.test(type)) return body;\n const encoding = headers.get(\"content-encoding\");\n if (encoding && encoding.toLowerCase() !== \"identity\") return body;\n\n const html = new TextDecoder().decode(body);\n const tag = `<script>${previewSocketSource()}</script>`;\n const head = /<head[^>]*>/i.exec(html);\n const at = head ? head.index + head[0].length : 0;\n const bytes = new TextEncoder().encode(html.slice(0, at) + tag + html.slice(at));\n /* The document just got longer. A stale `Content-Length` truncates it. */\n headers.set(\"content-length\", String(bytes.byteLength));\n return bytes.buffer as ArrayBuffer;\n}\n\n/** `Headers` is iterable at runtime; the DOM lib used here does not say so. */\nfunction headerRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n (headers as unknown as { forEach(fn: (value: string, key: string) => void): void })\n .forEach((value, key) => { out[key] = value; });\n return out;\n}\n","/**\n * A service worker that gives a container's HTTP servers real URLs.\n *\n * Without one, a page can reach a server inside the container only through\n * `box.request(port, …)`, which hands back a single response. That is enough to\n * read an API or drop some HTML into an element, but not to *run* a site: a\n * dev server emits absolute URLs like `/src/main.js` and `/@vite/client`, and\n * nothing in the page resolves those to the sandbox.\n *\n * This file is deliberately only the glue. The routing lives in\n * {@link PreviewRouter}, where it can be tested without a browser — a service\n * worker otherwise needs a registration, a secure context and a real page\n * before any of its behaviour can be observed at all.\n */\n\nimport { PreviewRouter, type ProxiedResponse, type PreviewRouterOptions } from \"./router.js\";\n\n/*\n * Typed locally rather than through `lib.webworker`: this package compiles with\n * the DOM lib, and the two declare a conflicting `self`. Only the handful of\n * members actually used are described here.\n */\ninterface FetchLikeEvent extends Event {\n request: Request;\n clientId: string;\n resultingClientId: string;\n respondWith(response: Promise<Response> | Response): void;\n}\ninterface ExtendableLikeEvent extends Event {\n waitUntil(promise: Promise<unknown>): void;\n}\ninterface MessageLikeEvent extends Event {\n data: unknown;\n ports: readonly MessagePort[];\n}\ninterface WorkerClient {\n postMessage(message: unknown): void;\n}\ninterface WorkerScope {\n location: { origin: string };\n clients: {\n claim(): Promise<void>;\n matchAll(options?: { includeUncontrolled?: boolean; type?: string }): Promise<WorkerClient[]>;\n };\n skipWaiting(): Promise<void>;\n addEventListener(type: \"install\" | \"activate\", listener: (event: ExtendableLikeEvent) => void): void;\n addEventListener(type: \"fetch\", listener: (event: FetchLikeEvent) => void): void;\n addEventListener(type: \"message\", listener: (event: MessageLikeEvent) => void): void;\n}\n\nconst worker = globalThis as unknown as WorkerScope;\n\nlet host: MessagePort | null = null;\n\n/** Resolves when a page answers the call for a channel; see `requestHost`. */\nlet awaitingHost: { promise: Promise<void>; resolve: () => void } | null = null;\n\nconst HOST_WAIT_MS = 5_000;\n\nconst options: PreviewRouterOptions = {\n send: (request, transfer) => host?.postMessage(request, transfer),\n /*\n * The worker was stopped and started again, taking the channel with it.\n *\n * Every page that owns a container listens for this and hands over a fresh\n * port. Broadcasting rather than tracking an owner is deliberate: after a\n * restart the worker knows nothing about who registered it, and a page with\n * no container simply ignores the call.\n */\n requestHost: async () => {\n if (awaitingHost) return awaitingHost.promise;\n\n let resolve!: () => void;\n const promise = new Promise<void>((done) => {\n resolve = done;\n });\n awaitingHost = { promise, resolve };\n\n const clients = await worker.clients.matchAll({ includeUncontrolled: true, type: \"window\" });\n for (const client of clients) client.postMessage({ type: \"sandboxedjs:host-needed\" });\n\n /* Bounded: a page that cannot answer must not hold the request open until\n * the request timeout, which is six times longer. */\n const timer = setTimeout(() => {\n awaitingHost?.resolve();\n awaitingHost = null;\n }, HOST_WAIT_MS);\n\n await promise;\n clearTimeout(timer);\n awaitingHost = null;\n },\n /* Broadcast, for the same reason `requestHost` does: after a restart this\n * worker has no idea which page owns what. A page with no preview ignores\n * it. */\n onStale: () => {\n void worker.clients\n .matchAll({ includeUncontrolled: true, type: \"window\" })\n .then((clients) => {\n for (const client of clients) client.postMessage({ type: \"sandboxedjs:stale\" });\n });\n },\n};\n\nconst router = new PreviewRouter(options);\n\nworker.addEventListener(\"install\", () => void worker.skipWaiting());\nworker.addEventListener(\"activate\", (event) => event.waitUntil(worker.clients.claim()));\n\nworker.addEventListener(\"message\", (event) => {\n const data = event.data as { type?: string } | null;\n if (data?.type !== \"sandboxedjs:connect\") return;\n host = event.ports[0] ?? null;\n if (!host) return;\n /* The page decides whether previewed documents get a tunnelling\n * `WebSocket`, and it can only say so once it has a channel — this worker\n * may have been started fresh for a request, with no memory of the last\n * answer. */\n options.injectSockets = (event.data as { injectSockets?: boolean }).injectSockets !== false;\n host.onmessage = (message) => {\n const reply = message.data as { id: number; response: ProxiedResponse };\n router.settle(reply.id, reply.response);\n };\n host.start();\n router.connect();\n /* Release anything that was waiting on this channel arriving. */\n awaitingHost?.resolve();\n});\n\nworker.addEventListener(\"fetch\", (event) => {\n const url = new URL(event.request.url);\n if (url.origin !== worker.location.origin) return;\n\n const claimed = router.claimedPort(url.pathname);\n if (claimed !== null && event.request.mode === \"navigate\") {\n /* A navigation's client does not exist yet, so it is named by\n * `resultingClientId`. Binding it here is what lets every later request\n * from that document be recognised without touching its URLs. */\n router.bind(event.resultingClientId || event.clientId, claimed);\n event.respondWith(router.fetch(claimed, \"/\", event.request));\n return;\n }\n\n const port = router.portFor(event.clientId);\n if (port === undefined) return; // not a preview: the host page's own traffic\n /* Strip this worker's own claim prefix before asking the container: a\n * relative asset resolves against the document's URL, so it arrives carrying\n * the prefix the container knows nothing about. */\n event.respondWith(\n router.fetch(port, router.containerPath(url.pathname, url.search), event.request),\n );\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/preview/ws-client.ts","../src/preview/router.ts","../src/preview/service-worker.ts"],"names":["host","event","options"],"mappings":";AAgDO,SAAS,sBAAsB,KAAA,EAAkB;AACtD,EAAA,MAAM,SAAS,KAAA,CAAM,SAAA;AACrB,EAAA,MAAM,WAAW,KAAA,CAAM,QAAA;AAGvB,EAAA,IAAI,CAAC,KAAA,CAAM,MAAA,IAAU,KAAA,CAAM,WAAW,KAAA,EAAO;AAC7C,EAAA,MAAMA,QAAO,KAAA,CAAM,MAAA;AAGnB,EAAA,MAAM,KAAA,GAAQ,gCAAA,CAAiC,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA;AACrE,EAAA,MAAM,cAAc,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA,GAAI,IAAA;AAE/C,EAAA,MAAM,QAAA,GAAW,2DAAA;AAWjB,EAAA,SAAS,OAAO,GAAA,EAAoD;AAClE,IAAA,IAAI,GAAA;AACJ,IAAA,IAAI;AACF,MAAA,GAAA,GAAM,IAAI,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,EAAG,SAAS,IAAI,CAAA;AAAA,IAC1C,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,IAAI,IAAI,QAAA,KAAa,KAAA,IAAS,GAAA,CAAI,QAAA,KAAa,QAAQ,OAAO,IAAA;AAE9D,IAAA,MAAM,WAAW,GAAA,CAAI,IA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A,CAAQ,SAAS,UAAA,EAAY;AAIzD,IAAA,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,iBAAA,IAAqB,KAAA,CAAM,UAAU,OAAO,CAAA;AAC9D,IAAA,KAAA,CAAM,WAAA,CAAY,MAAA,CAAO,KAAA,CAAM,OAAA,EAAS,GAAA,EAAK,KAAA,CAAM,OAAA,EAAS,KAAA,CAAM,iBAAA,IAAqB,KAAA,CAAM,QAAQ,CAAC,CAAA;AACtG,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,QAAQ,CAAA;AAC1C,EAAA,IAAI,SAAS,MAAA,EAAW;AAIxB,EAAA,KAAA,CAAM,WAAA;AAAA,IACJ,MAAA,CAAO,KAAA,CAAM,IAAA,EAAM,MAAA,CAAO,aAAA,CAAc,GAAA,CAAI,QAAA,EAAU,GAAA,CAAI,MAAM,CAAA,EAAG,KAAA,CAAM,OAAA,EAAS,MAAM,QAAQ;AAAA,GAClG;AACF,CAAC,CAAA","file":"service-worker.js","sourcesContent":["/**\n * The WebSocket a page inside a preview actually gets.\n *\n * A service worker can answer `fetch`. It cannot answer a WebSocket handshake\n * — that was proposed and never shipped, in any browser — so the one mechanism\n * that gives a preview its URLs is structurally unable to carry the one\n * protocol a dev server needs. `new WebSocket(...)` inside the frame leaves the\n * sandbox entirely and tries the real origin, where nothing is listening.\n *\n * For a static site that costs nothing. For Vite it costs the HMR channel, and\n * with it the `full-reload` message Vite sends after re-optimizing its\n * dependencies — which is the *only* way it can tell a page that the hashes it\n * is holding are stale. Without it every `?v=` URL answers `504 Outdated\n * Optimize Dep` forever and the app never mounts, while the terminal shows a\n * dev server that started perfectly.\n *\n * So the constructor is replaced instead. {@link previewSocketSource} renders\n * this to JavaScript that the router injects into HTML it serves, where it\n * swaps in a `WebSocket` that tunnels to the host page over `postMessage`\n * rather than out to the network. URLs that do not name the container keep the\n * native implementation.\n *\n * ## Why this speaks the real protocol\n *\n * It would be less code to tunnel messages — `send(x)` on one side, `onmessage`\n * on the other — and let the container hand Vite something WebSocket-shaped.\n * That would work for Vite and nothing else, because Vite does not implement\n * WebSocket: `ws` does, and so do `socket.io` and every other server a user\n * might run. Framing the bytes here means the container emits a genuine\n * `upgrade` with a genuine socket, and those libraries run unmodified over it.\n * The sandbox gains WebSocket support, not a Vite compatibility shim.\n */\n\n/** The message names shared by the injected shim and {@link createPreview}. */\nexport const WS_OPEN = \"sandboxedjs:ws-open\";\nexport const WS_DATA = \"sandboxedjs:ws-data\";\nexport const WS_CLOSE = \"sandboxedjs:ws-close\";\nexport const WS_ERROR = \"sandboxedjs:ws-error\";\n\n/**\n * Install the tunnelling `WebSocket` on `scope`.\n *\n * Written as one self-contained function on purpose: {@link previewSocketSource}\n * serialises it with `String()`, so it may not close over anything in this\n * module. Everything it needs is either passed in or a page global. Keeping it\n * a real function rather than a template literal is what lets it be\n * type-checked and, more usefully, driven directly from a test.\n */\nexport function installPreviewSockets(scope: any): void {\n const Native = scope.WebSocket;\n const location = scope.location;\n /* No parent means this is not framed, so there is no host to tunnel to and\n * the native implementation is the best available answer. */\n if (!scope.parent || scope.parent === scope) return;\n const host = scope.parent;\n\n /** The port this document is previewing, from the path it was claimed at. */\n const claim = /(?:^|\\/)__sbx__\\/(\\d+)(?:\\/|$)/.exec(location.pathname);\n const claimedPort = claim ? Number(claim[1]) : null;\n\n const LOOPBACK = /^(?:localhost|127(?:\\.\\d{1,3}){3}|0\\.0\\.0\\.0|\\[?::1\\]?)$/i;\n\n /**\n * The container port and path a URL names, or null to leave it to the\n * network.\n *\n * Two forms arrive here. A dev server's client usually builds its URL from\n * `location`, so it points at this origin and means \"the port I am already\n * previewing\". A program with a hardcoded address says `localhost:3000` and\n * means that port. Anything else is a real remote host and is not ours.\n */\n function target(raw: string): { port: number; path: string } | null {\n let url: any;\n try {\n url = new URL(String(raw), location.href);\n } catch {\n return null;\n }\n if (url.protocol !== \"ws:\" && url.protocol !== \"wss:\") return null;\n\n const explicit = url.port ? Number(url.port) : null;\n const sameOrigin = url.hostname === location.hostname;\n let port: number | null = null;\n if (LOOPBACK.test(url.hostname) && explicit) port = explicit;\n else if (sameOrigin) port = claimedPort;\n if (port === null) return null;\n\n /* A document served under `/…/__sbx__/5173/` resolves a relative socket\n * URL against that prefix, which the container has never heard of. */\n const match = /(?:^|\\/)__sbx__\\/\\d+(?:\\/|$)/.exec(url.pathname);\n const rest = match ? url.pathname.slice(match.index + match[0].length) : url.pathname;\n const path = (rest.startsWith(\"/\") ? rest : \"/\" + rest) + url.search;\n return { port, path };\n }\n\n /** How long to wait for the host page before reporting it absent. */\n const OPEN_TIMEOUT_MS = 10_000;\n\n /*\n * Reload when the worker says the server has invalidated what this page\n * holds.\n *\n * This is the job Vite's own client does when it is told to over HMR, and\n * the reason it is duplicated here is that Vite's message is routinely lost:\n * it is sent the instant the optimizer finishes, and the HMR socket in a\n * preview has an iframe, a `postMessage`, the host page and a container to\n * cross before it exists. A cold start with React loses that race reliably,\n * and the result is a page whose every dependency answers `504` while its\n * HMR connection sits there, connected and silent.\n *\n * Capped, and deliberately crudely. A reload that produces another stale\n * response is a loop, and a loop of reloads is worse than the blank frame it\n * is trying to fix — it burns CPU and makes the tab hard to even close. Three\n * within ten seconds is enough for the case this exists for (one\n * re-optimization, occasionally a second) and stops well short of a page\n * that cannot recover.\n */\n const RELOAD_KEY = \"sandboxedjs:reloads\";\n const RELOAD_LIMIT = 3;\n const RELOAD_WINDOW_MS = 10_000;\n\n function reloadForStaleServer(): void {\n let count = 0;\n try {\n const raw = sessionStorage.getItem(RELOAD_KEY);\n const state = raw ? JSON.parse(raw) as { at: number; count: number } : null;\n /* Outside the window means the last reload worked, so this is a fresh\n * problem rather than a repeat of the same one. */\n count = state && Date.now() - state.at < RELOAD_WINDOW_MS ? state.count : 0;\n if (count >= RELOAD_LIMIT) {\n console.warn(\"sandboxedjs: the dev server keeps invalidating this page; not reloading again\");\n return;\n }\n sessionStorage.setItem(RELOAD_KEY, JSON.stringify({ at: Date.now(), count: count + 1 }));\n } catch {\n /* No session storage — a reload is still better than a stranded page,\n * but without a counter it must happen only once per document. */\n if ((scope as { __sandboxedjsReloaded?: boolean }).__sandboxedjsReloaded) return;\n (scope as { __sandboxedjsReloaded?: boolean }).__sandboxedjsReloaded = true;\n }\n location.reload();\n }\n\n const workers = scope.navigator?.serviceWorker;\n if (workers?.addEventListener) {\n workers.addEventListener(\"message\", (event: any) => {\n if (event?.data?.type === \"sandboxedjs:reload\") reloadForStaleServer();\n });\n }\n\n const encoder = new TextEncoder();\n const decoder = new TextDecoder();\n\n function concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n if (a.length === 0) return b;\n if (b.length === 0) return a;\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n }\n\n /**\n * One frame, masked.\n *\n * A client must mask; a server must not. `ws` closes the connection over\n * either mistake, so this is not a formality.\n */\n function frame(opcode: number, payload: Uint8Array): Uint8Array {\n const length = payload.length;\n const extended = length > 65535 ? 8 : length > 125 ? 2 : 0;\n const out = new Uint8Array(2 + extended + 4 + length);\n out[0] = 0x80 | opcode;\n let at = 2;\n if (extended === 0) {\n out[1] = 0x80 | length;\n } else if (extended === 2) {\n out[1] = 0x80 | 126;\n out[2] = (length >>> 8) & 0xff;\n out[3] = length & 0xff;\n at = 4;\n } else {\n out[1] = 0x80 | 127;\n /* The high four bytes stay zero: this payload came out of memory, so it\n * cannot reach 2^32. */\n out[6] = (length >>> 24) & 0xff;\n out[7] = (length >>> 16) & 0xff;\n out[8] = (length >>> 8) & 0xff;\n out[9] = length & 0xff;\n at = 10;\n }\n const mask = new Uint8Array(4);\n crypto.getRandomValues(mask);\n out.set(mask, at);\n at += 4;\n for (let i = 0; i < length; i++) out[at + i] = payload[i]! ^ mask[i & 3]!;\n return out;\n }\n\n /** An `Event` with extra properties, built without assuming `CloseEvent`. */\n function event(type: string, fields?: Record<string, unknown>): any {\n const value: any = new Event(type);\n if (fields) for (const key of Object.keys(fields)) {\n try {\n value[key] = fields[key];\n } catch {\n Object.defineProperty(value, key, { value: fields[key], enumerable: true });\n }\n }\n return value;\n }\n\n let nextId = 1;\n const live = new Map<number, any>();\n\n scope.addEventListener(\"message\", (message: any) => {\n /* Same-origin only. The preview and its host share an origin — that is the\n * documented trade-off of previewing this way — so anything from elsewhere\n * is not the host and has no business steering these sockets. */\n if (message.origin !== location.origin) return;\n const data = message.data;\n if (!data || typeof data !== \"object\") return;\n const socket = live.get(data.id);\n if (!socket) return;\n if (data.type === \"sandboxedjs:ws-data\") socket._receive(new Uint8Array(data.data));\n else if (data.type === \"sandboxedjs:ws-close\") socket._shutdown(1006, \"\", false);\n else if (data.type === \"sandboxedjs:ws-error\") socket._fail(String(data.message ?? \"connection failed\"));\n });\n\n class TunnelledWebSocket extends EventTarget {\n static readonly CONNECTING = 0;\n static readonly OPEN = 1;\n static readonly CLOSING = 2;\n static readonly CLOSED = 3;\n readonly CONNECTING = 0;\n readonly OPEN = 1;\n readonly CLOSING = 2;\n readonly CLOSED = 3;\n\n readonly url: string;\n readyState = 0;\n protocol = \"\";\n extensions = \"\";\n bufferedAmount = 0;\n binaryType: \"blob\" | \"arraybuffer\" = \"blob\";\n\n onopen: any = null;\n onmessage: any = null;\n onerror: any = null;\n onclose: any = null;\n\n private readonly id = nextId++;\n /** Handshake bytes first, frames after; the 101 arrives as bytes. */\n private handshaken = false;\n private buffer: Uint8Array<ArrayBufferLike> = new Uint8Array(0);\n /** A fragmented message in progress: its opcode and its pieces. */\n private fragmentOpcode = 0;\n private fragments: Uint8Array[] = [];\n\n constructor(url: string, protocols?: string | string[]) {\n super();\n const to = target(url);\n /* Only reachable when `create` chose this class, which it does only for\n * URLs `target` has already accepted. */\n if (!to) throw new SyntaxError(`Not a container address: ${url}`);\n this.url = String(new URL(String(url), location.href));\n\n const list = protocols === undefined ? [] : typeof protocols === \"string\" ? [protocols] : protocols;\n const key = (() => {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n })();\n\n const headers: Record<string, string> = {\n /*\n * The address the server believes it is on, not the one the page is\n * loaded from. A dev server validates `Host` on the upgrade — Vite has\n * done so since it closed CVE-2025-24010 — against a list that always\n * contains loopback and never contains whatever origin happens to be\n * hosting this preview. Sending the page's host means a handshake\n * rejected for a reason that has nothing to do with the sandbox.\n */\n host: `localhost:${to.port}`,\n connection: \"Upgrade\",\n upgrade: \"websocket\",\n \"sec-websocket-version\": \"13\",\n \"sec-websocket-key\": key,\n origin: location.origin,\n };\n if (list.length) headers[\"sec-websocket-protocol\"] = list.join(\", \");\n\n live.set(this.id, this);\n host.postMessage(\n { type: \"sandboxedjs:ws-open\", id: this.id, port: to.port, path: to.path, headers },\n location.origin,\n );\n /*\n * Nobody answering is a real state, not a hypothetical: the page hosting\n * this preview may be running a build of `createPreview` older than the\n * one that injected this script, in which case the message lands\n * nowhere. Left alone that is an open socket that never opens and never\n * closes — the worst failure to diagnose, because nothing is reported at\n * all. Failing loudly turns it into a sentence in the console.\n */\n setTimeout(() => {\n if (this.readyState === 0) {\n this._fail(\"The page hosting this preview did not answer the WebSocket. It may be running an older version of sandboxedjs.\");\n }\n }, OPEN_TIMEOUT_MS);\n }\n\n send(data: any): void {\n if (this.readyState === 0) throw new DOMException(\"Still in CONNECTING state.\", \"InvalidStateError\");\n if (this.readyState !== 1) return;\n if (typeof data === \"string\") this._write(0x1, encoder.encode(data));\n else if (data instanceof ArrayBuffer) this._write(0x2, new Uint8Array(data));\n else if (ArrayBuffer.isView(data)) this._write(0x2, new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n else this._write(0x1, encoder.encode(String(data)));\n }\n\n close(code?: number, reason?: string): void {\n if (this.readyState === 2 || this.readyState === 3) return;\n const body = encoder.encode(reason ?? \"\");\n const payload = new Uint8Array(2 + body.length);\n payload[0] = ((code ?? 1000) >>> 8) & 0xff;\n payload[1] = (code ?? 1000) & 0xff;\n payload.set(body, 2);\n if (this.readyState === 1) this._write(0x8, payload);\n this.readyState = 2;\n host.postMessage({ type: \"sandboxedjs:ws-close\", id: this.id }, location.origin);\n }\n\n private _write(opcode: number, payload: Uint8Array): void {\n const bytes = frame(opcode, payload);\n /* Copied into a fresh buffer so it can be transferred without taking the\n * caller's memory with it. */\n const carrier = bytes.slice().buffer;\n host.postMessage({ type: \"sandboxedjs:ws-data\", id: this.id, data: carrier }, location.origin, [carrier]);\n }\n\n private _emit(value: any): void {\n const handler = (this as any)[\"on\" + value.type];\n if (typeof handler === \"function\") handler.call(this, value);\n this.dispatchEvent(value);\n }\n\n _fail(message: string): void {\n if (this.readyState === 3) return;\n this._emit(event(\"error\", { message }));\n this._shutdown(1006, \"\", false);\n }\n\n /** Bytes from the container: the 101, then frames. */\n _receive(bytes: Uint8Array): void {\n if (this.readyState === 3) return;\n this.buffer = concat(this.buffer, bytes);\n if (!this.handshaken && !this._handshake()) return;\n this._frames();\n }\n\n /**\n * Read the `101` the server wrote onto the socket.\n *\n * The container builds the request from structured fields, but the reply\n * comes back as the bytes `ws` wrote — a real status line and real headers\n * — so it is parsed as one.\n */\n private _handshake(): boolean {\n const text = decoder.decode(this.buffer);\n const end = text.indexOf(\"\\r\\n\\r\\n\");\n if (end === -1) return false;\n const head = text.slice(0, end).split(\"\\r\\n\");\n const status = Number(head[0]?.split(\" \")[1]);\n if (status !== 101) {\n this._fail(`Server refused the WebSocket upgrade (${status || \"no status\"})`);\n return false;\n }\n for (const line of head.slice(1)) {\n const at = line.indexOf(\":\");\n if (at === -1) continue;\n if (line.slice(0, at).trim().toLowerCase() === \"sec-websocket-protocol\") {\n this.protocol = line.slice(at + 1).trim();\n }\n }\n /* The header is ASCII, so its character count is its byte count. */\n this.buffer = this.buffer.subarray(end + 4);\n this.handshaken = true;\n this.readyState = 1;\n this._emit(event(\"open\"));\n return true;\n }\n\n private _frames(): void {\n for (;;) {\n const view = this.buffer;\n if (view.length < 2) return;\n const first = view[0]!;\n const second = view[1]!;\n const fin = (first & 0x80) !== 0;\n const opcode = first & 0x0f;\n const masked = (second & 0x80) !== 0;\n let length = second & 0x7f;\n let at = 2;\n if (length === 126) {\n if (view.length < 4) return;\n length = (view[2]! << 8) | view[3]!;\n at = 4;\n } else if (length === 127) {\n if (view.length < 10) return;\n /* Arithmetic rather than shifts: the top half of a 64-bit length\n * does not survive a 32-bit bitwise operator. */\n const high = view[2]! * 2 ** 24 + view[3]! * 2 ** 16 + view[4]! * 2 ** 8 + view[5]!;\n const low = view[6]! * 2 ** 24 + view[7]! * 2 ** 16 + view[8]! * 2 ** 8 + view[9]!;\n length = high * 2 ** 32 + low;\n at = 10;\n }\n let mask: Uint8Array | null = null;\n if (masked) {\n if (view.length < at + 4) return;\n mask = view.subarray(at, at + 4);\n at += 4;\n }\n if (view.length < at + length) return;\n const payload = view.slice(at, at + length);\n if (mask) for (let i = 0; i < length; i++) payload[i] = payload[i]! ^ mask[i & 3]!;\n this.buffer = view.subarray(at + length);\n this._frame(fin, opcode, payload);\n if (this.readyState === 3) return;\n }\n }\n\n private _frame(fin: boolean, opcode: number, payload: Uint8Array): void {\n if (opcode === 0x9) {\n /* A pong has to carry the ping's payload back verbatim. `ws` pings on\n * a timer, and a client that never answers is dropped. */\n if (this.readyState === 1) this._write(0xa, payload);\n return;\n }\n if (opcode === 0xa) return;\n if (opcode === 0x8) {\n const code = payload.length >= 2 ? (payload[0]! << 8) | payload[1]! : 1005;\n const reason = payload.length > 2 ? decoder.decode(payload.subarray(2)) : \"\";\n if (this.readyState === 1) this._write(0x8, payload);\n this.readyState = 2;\n host.postMessage({ type: \"sandboxedjs:ws-close\", id: this.id }, location.origin);\n this._shutdown(code, reason, true);\n return;\n }\n\n if (opcode !== 0x0) {\n this.fragmentOpcode = opcode;\n this.fragments = [];\n }\n this.fragments.push(payload);\n if (!fin) return;\n\n let total = 0;\n for (const piece of this.fragments) total += piece.length;\n const body = new Uint8Array(total);\n let offset = 0;\n for (const piece of this.fragments) {\n body.set(piece, offset);\n offset += piece.length;\n }\n this.fragments = [];\n\n const data = this.fragmentOpcode === 0x1\n ? decoder.decode(body)\n : this.binaryType === \"arraybuffer\"\n ? body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)\n : new Blob([body as BlobPart]);\n this._emit(event(\"message\", { data, origin: location.origin, lastEventId: \"\", source: null, ports: [] }));\n }\n\n _shutdown(code: number, reason: string, wasClean: boolean): void {\n if (this.readyState === 3) return;\n this.readyState = 3;\n live.delete(this.id);\n this._emit(event(\"close\", { code, reason, wasClean }));\n }\n }\n\n /**\n * The replacement constructor.\n *\n * A plain function so `new WebSocket(url)` can pick an implementation per\n * URL — anything not naming the container has to keep working, and that\n * includes a page talking to a genuine remote server from inside a preview.\n */\n function create(this: any, url: string, protocols?: string | string[]): any {\n if (!target(url)) return protocols === undefined ? new Native(url) : new Native(url, protocols);\n return new TunnelledWebSocket(url, protocols);\n }\n\n create.prototype = TunnelledWebSocket.prototype;\n (create as any).CONNECTING = 0;\n (create as any).OPEN = 1;\n (create as any).CLOSING = 2;\n (create as any).CLOSED = 3;\n /* `instanceof` has to keep answering for native sockets too, since only some\n * of them are ours. */\n Object.defineProperty(create, Symbol.hasInstance, {\n value: (value: unknown) => value instanceof TunnelledWebSocket || value instanceof Native,\n });\n\n scope.WebSocket = create;\n /* A one-word answer to \"is this actually installed?\", which is otherwise\n * only observable by noticing that a WebSocket *failed* to appear in the\n * network panel. Reading a global in the frame's console is a far shorter\n * path to that answer than reasoning about it. */\n scope.__sandboxedjsPreviewSockets = true;\n}\n\n/**\n * The shim, as a `<script>` body.\n *\n * Serialising the function keeps one implementation: what a test drives is\n * character-for-character what a preview runs. The call is wrapped so a\n * failure to install cannot take the page's own scripts down with it — a\n * preview without hot reload is worth far more than a blank frame.\n */\nexport function previewSocketSource(): string {\n return `(function(){try{(${installPreviewSockets.toString()})(window);}catch(error){console.warn(\"sandboxedjs: preview WebSocket unavailable\",error);}})();`;\n}\n","/**\n * The routing a preview service worker does, separated from the worker itself.\n *\n * A service worker is awkward to test — it needs a browser, a registration and\n * a secure context — but almost none of what makes this correct is about being\n * a service worker. The interesting part is the bookkeeping: which client is\n * previewing which port, which requests belong to a preview at all, and how a\n * response is rebuilt on the way back. That lives here, where it can be\n * exercised directly.\n *\n * The rule this implements, and the reason it exists: requests are routed by\n * **who is asking**, not by what the path looks like. An iframe navigates once\n * to `/__sbx__/<port>/`; every later request from that client — however\n * absolute its path — is recognised by its client id. Nothing has to rewrite\n * `/src/main.js` or `/@vite/client`, which is what makes a real dev server\n * work rather than only a single page.\n */\n\nimport { previewSocketSource } from \"./ws-client.js\";\n\n/**\n * The one-time path an iframe navigates to in order to claim a port.\n *\n * Deliberately not anchored to the start of the path. A service worker's scope\n * is the directory its script was served from, so in a published package the\n * claim arrives under something like\n * `/node_modules/sandboxedjs/dist/__sbx__/5173/` — anchoring here would match\n * only when the worker happened to be served from the site root.\n */\nconst CLAIM = /(?:^|\\/)__sbx__\\/(\\d+)(?:\\/|$)/;\n\nexport interface ProxiedRequest {\n id: number;\n port: number;\n path: string;\n method: string;\n headers: Record<string, string>;\n body?: ArrayBuffer;\n}\n\nexport interface ProxiedResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: ArrayBuffer;\n}\n\nexport interface PreviewRouterOptions {\n /** Hand a request to whichever page owns the container. */\n send(request: ProxiedRequest, transfer: ArrayBuffer[]): void;\n /** How long to wait for that page before giving up. */\n timeoutMs?: number;\n /**\n * Ask the owning page to hand over a fresh channel, and resolve once it has.\n *\n * A service worker is not a process that stays running. The browser stops it\n * whenever it looks idle — seconds, in practice — and starts it again for\n * the next request, with every module-level value gone. The `MessagePort`\n * that reaches the container is one of those values, so a worker that has\n * been restarted has no way to answer anything, however healthy the\n * container behind it still is.\n *\n * Nothing about that is visible: the server is running, the port is open,\n * and the preview simply stops working — on reload, in a new tab, or after\n * a pause long enough for the browser to reclaim the worker. The page is\n * still there and can always supply another port, so the worker asks for one\n * rather than failing.\n */\n requestHost?(): Promise<void>;\n /**\n * The dev server has invalidated what the page is holding; reload it.\n *\n * Vite answers a request for a pre-bundled dependency with `504 Outdated\n * Optimize Dep` whenever the hash in the URL no longer matches — after the\n * optimizer re-runs, or after the server restarts. Its own client recovers\n * by reloading the whole page, and it learns to do that over the HMR\n * WebSocket.\n *\n * This bridge carries HTTP and nothing else, so that signal never arrives.\n * The page goes on requesting URLs stamped with a hash the server has\n * forgotten, every module 504s, and the app never mounts — while the\n * terminal reports a dev server that started perfectly. A plain static\n * server never does this, which is why vanilla pages worked and React did\n * not.\n */\n onStale?(clientId?: string): void;\n /**\n * Give previewed pages a `WebSocket` that reaches the container.\n *\n * A service worker cannot answer a WebSocket handshake — no browser ever\n * shipped that — so the only way a page inside a preview can open one is to\n * be handed a different constructor. Injecting it into the HTML is how that\n * gets there, and it is on by default because a dev server without its HMR\n * channel does not merely lose hot reload: it loses the only way it can tell\n * a page that its dependency hashes are stale, which strands the preview on\n * `504 Outdated Optimize Dep` with nothing to explain it.\n */\n injectSockets?: boolean;\n}\n\n/** Vite's answer when the page is holding a dependency hash it has dropped. */\nconst OUTDATED = /outdated optimize dep/i;\n\n/** The port to answer with when nothing has connected yet. */\nconst NOT_CONNECTED = 503;\n\nexport class PreviewRouter {\n private readonly clientPorts = new Map<string, number>();\n private readonly pending = new Map<number, (value: ProxiedResponse) => void>();\n private nextId = 1;\n private connected = false;\n\n constructor(private readonly options: PreviewRouterOptions) {}\n\n /** Whether a page has handed over a channel this worker can still use. */\n get ready(): boolean {\n return this.connected;\n }\n\n /** The page that answers requests has arrived. */\n connect(): void {\n this.connected = true;\n }\n\n /** The channel is gone; the next request has to ask for another. */\n disconnect(): void {\n this.connected = false;\n }\n\n /** Read a port out of a claim path, or null when this is not one. */\n /**\n * The path to ask the container for, given a request from a bound client.\n *\n * A document served at `/…/__sbx__/3000/` resolves its *relative* assets\n * against that prefix, so `./app.js` arrives as\n * `/…/__sbx__/3000/app.js`. Forwarding that verbatim asks the container for\n * a file inside a directory it has never heard of, and every relative asset\n * in the site 404s while the document itself loads perfectly — a page that\n * renders unstyled and inert, with nothing to explain why.\n *\n * Root-relative assets (`/main.js`) carry no prefix and pass through\n * unchanged, which is the case that always worked.\n */\n containerPath(pathname: string, search: string): string {\n const match = CLAIM.exec(pathname);\n const rest = match ? pathname.slice(match.index + match[0].length) : pathname;\n const normalised = rest.startsWith(\"/\") ? rest : `/${rest}`;\n return `${normalised}${search}`;\n }\n\n claimedPort(pathname: string): number | null {\n const match = CLAIM.exec(pathname);\n return match ? Number(match[1]) : null;\n }\n\n /** Remember that everything from `clientId` belongs to `port`. */\n bind(clientId: string, port: number): void {\n if (clientId) this.clientPorts.set(clientId, port);\n }\n\n /** Which port this client is previewing, or undefined for ordinary traffic. */\n portFor(clientId: string): number | undefined {\n return this.clientPorts.get(clientId);\n }\n\n /** A response has come back from the page. */\n settle(id: number, response: ProxiedResponse): void {\n const resolve = this.pending.get(id);\n if (!resolve) return;\n this.pending.delete(id);\n resolve(response);\n }\n\n /** Forget a client that has gone away. */\n release(clientId: string): void {\n this.clientPorts.delete(clientId);\n }\n\n /** Ask the page for one response and rebuild it as a `Response`. */\n async fetch(port: number, path: string, request: Request, clientId?: string): Promise<Response> {\n /* Restarted, most likely, rather than never started. Ask the page for a\n * channel before concluding there is nobody to ask. */\n if (!this.connected) await this.options.requestHost?.().catch(() => undefined);\n\n if (!this.connected) {\n return isolated(\n new Response(\n 'The sandbox preview is not connected yet. The page that owns this container has to be open.',\n { status: NOT_CONNECTED, statusText: 'Service Unavailable' },\n ),\n );\n }\n const sent = request.method === \"GET\" || request.method === \"HEAD\" ? undefined : await request.arrayBuffer();\n const id = this.nextId++;\n const answered = new Promise<ProxiedResponse>((resolve) => this.pending.set(id, resolve));\n\n this.options.send(\n { id, port, path, method: request.method, headers: headerRecord(request.headers), ...(sent ? { body: sent } : {}) },\n sent ? [sent] : [],\n );\n\n const timeoutMs = this.options.timeoutMs ?? 30_000;\n const result = await Promise.race([\n answered,\n new Promise<ProxiedResponse>((resolve) =>\n setTimeout(\n () => resolve({ status: 504, statusText: \"Gateway Timeout\", headers: {}, body: new ArrayBuffer(0) }),\n timeoutMs,\n ),\n ),\n ]);\n this.pending.delete(id);\n\n /*\n * Nothing here can rewrite the URL the page asked for — only the page can\n * ask again, and only after reloading. `clientId` names the frame that\n * asked, so the worker can tell that frame to do it.\n *\n * This has to be automatic rather than left to the host. Vite's own client\n * recovers by reloading when it is told to over HMR, and that message is\n * routinely *lost*: Vite sends `full-reload` the moment its optimizer\n * finishes, and the HMR socket here travels an iframe, a `postMessage`,\n * the host page and the container before it is connected. Lose that race —\n * which a cold start with React reliably does — and the reload is sent to\n * nobody, leaving a page holding hashes the server has already forgotten,\n * with a working HMR connection and nothing to say on it.\n */\n if (result.status === 504 && OUTDATED.test(result.statusText)) {\n this.options.onStale?.(clientId);\n }\n\n const headers = new Headers(result.headers);\n const body = this.options.injectSockets === false ? result.body : withSockets(result.body, headers);\n /*\n * Two headers, for two different refusals, both of which a cross-origin\n * isolated page makes — and pages that run Rolldown have to be isolated.\n *\n * `Cross-Origin-Resource-Policy` lets the response be loaded as a\n * subresource at all. `Cross-Origin-Embedder-Policy` lets it be *framed*:\n * without it the document is not isolation-compatible, so the iframe is\n * replaced by an error page and the parent sees an opaque, cross-origin\n * frame rather than the site it asked for. Everything served here carries\n * CORP, so the stricter policy is one this preview can satisfy.\n */\n headers.set(\"Cross-Origin-Resource-Policy\", \"cross-origin\");\n headers.set(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n return new Response(body, { status: result.status, statusText: result.statusText, headers });\n }\n}\n\n/**\n * The isolation headers, on a response this router made up itself.\n *\n * Every failure here is still framed by a cross-origin isolated page, and a\n * document without these is not merely shown as an error — it is refused\n * before it renders, so the reader gets the browser's \"refused to connect\"\n * instead of the sentence explaining what went wrong. An error nobody can read\n * is worse than the failure it describes.\n */\nfunction isolated(response: Response): Response {\n const headers = new Headers(response.headers);\n headers.set(\"Content-Type\", \"text/plain; charset=utf-8\");\n headers.set(\"Cross-Origin-Resource-Policy\", \"cross-origin\");\n headers.set(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/**\n * Put the tunnelling `WebSocket` into an HTML document before anything runs.\n *\n * Only HTML, and only HTML this router can read: a compressed body would have\n * to be decoded and re-encoded to be edited, and getting that wrong corrupts\n * the page rather than merely failing to patch it. Anything skipped here keeps\n * the native `WebSocket`, which is exactly what it had before.\n *\n * The script goes directly after `<head>` so it is installed before the\n * document's own scripts — a dev server's client is one of the first of them,\n * and it opens its socket immediately.\n */\nfunction withSockets(body: ArrayBuffer, headers: Headers): ArrayBuffer {\n const type = headers.get(\"content-type\") ?? \"\";\n if (!/^\\s*text\\/html\\b/i.test(type)) return body;\n const encoding = headers.get(\"content-encoding\");\n if (encoding && encoding.toLowerCase() !== \"identity\") return body;\n\n const html = new TextDecoder().decode(body);\n const tag = `<script>${previewSocketSource()}</script>`;\n const head = /<head[^>]*>/i.exec(html);\n const at = head ? head.index + head[0].length : 0;\n const bytes = new TextEncoder().encode(html.slice(0, at) + tag + html.slice(at));\n /* The document just got longer. A stale `Content-Length` truncates it. */\n headers.set(\"content-length\", String(bytes.byteLength));\n return bytes.buffer as ArrayBuffer;\n}\n\n/** `Headers` is iterable at runtime; the DOM lib used here does not say so. */\nfunction headerRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n (headers as unknown as { forEach(fn: (value: string, key: string) => void): void })\n .forEach((value, key) => { out[key] = value; });\n return out;\n}\n","/**\n * A service worker that gives a container's HTTP servers real URLs.\n *\n * Without one, a page can reach a server inside the container only through\n * `box.request(port, …)`, which hands back a single response. That is enough to\n * read an API or drop some HTML into an element, but not to *run* a site: a\n * dev server emits absolute URLs like `/src/main.js` and `/@vite/client`, and\n * nothing in the page resolves those to the sandbox.\n *\n * This file is deliberately only the glue. The routing lives in\n * {@link PreviewRouter}, where it can be tested without a browser — a service\n * worker otherwise needs a registration, a secure context and a real page\n * before any of its behaviour can be observed at all.\n */\n\nimport { PreviewRouter, type ProxiedResponse, type PreviewRouterOptions } from \"./router.js\";\n\n/*\n * Typed locally rather than through `lib.webworker`: this package compiles with\n * the DOM lib, and the two declare a conflicting `self`. Only the handful of\n * members actually used are described here.\n */\ninterface FetchLikeEvent extends Event {\n request: Request;\n clientId: string;\n resultingClientId: string;\n respondWith(response: Promise<Response> | Response): void;\n}\ninterface ExtendableLikeEvent extends Event {\n waitUntil(promise: Promise<unknown>): void;\n}\ninterface MessageLikeEvent extends Event {\n data: unknown;\n ports: readonly MessagePort[];\n}\ninterface WorkerClient {\n postMessage(message: unknown): void;\n}\ninterface WorkerScope {\n location: { origin: string };\n clients: {\n claim(): Promise<void>;\n get(id: string): Promise<WorkerClient | undefined>;\n matchAll(options?: { includeUncontrolled?: boolean; type?: string }): Promise<WorkerClient[]>;\n };\n skipWaiting(): Promise<void>;\n addEventListener(type: \"install\" | \"activate\", listener: (event: ExtendableLikeEvent) => void): void;\n addEventListener(type: \"fetch\", listener: (event: FetchLikeEvent) => void): void;\n addEventListener(type: \"message\", listener: (event: MessageLikeEvent) => void): void;\n}\n\nconst worker = globalThis as unknown as WorkerScope;\n\nlet host: MessagePort | null = null;\n\n/** Resolves when a page answers the call for a channel; see `requestHost`. */\nlet awaitingHost: { promise: Promise<void>; resolve: () => void } | null = null;\n\nconst HOST_WAIT_MS = 5_000;\n\nconst options: PreviewRouterOptions = {\n send: (request, transfer) => host?.postMessage(request, transfer),\n /*\n * The worker was stopped and started again, taking the channel with it.\n *\n * Every page that owns a container listens for this and hands over a fresh\n * port. Broadcasting rather than tracking an owner is deliberate: after a\n * restart the worker knows nothing about who registered it, and a page with\n * no container simply ignores the call.\n */\n requestHost: async () => {\n if (awaitingHost) return awaitingHost.promise;\n\n let resolve!: () => void;\n const promise = new Promise<void>((done) => {\n resolve = done;\n });\n awaitingHost = { promise, resolve };\n\n const clients = await worker.clients.matchAll({ includeUncontrolled: true, type: \"window\" });\n for (const client of clients) client.postMessage({ type: \"sandboxedjs:host-needed\" });\n\n /* Bounded: a page that cannot answer must not hold the request open until\n * the request timeout, which is six times longer. */\n const timer = setTimeout(() => {\n awaitingHost?.resolve();\n awaitingHost = null;\n }, HOST_WAIT_MS);\n\n await promise;\n clearTimeout(timer);\n awaitingHost = null;\n },\n /* Broadcast, for the same reason `requestHost` does: after a restart this\n * worker has no idea which page owns what. A page with no preview ignores\n * it. */\n onStale: (clientId) => {\n /* The frame that asked is the only thing that can ask again, and the\n * injected client in it knows how. Telling it directly is what makes\n * recovery independent of the host having wired anything up. */\n if (clientId) {\n void worker.clients.get(clientId).then((client) => client?.postMessage({ type: \"sandboxedjs:reload\" }));\n }\n /* Still announced to the pages that own containers, so a host that wants\n * to drive the reload itself — or count them — can. */\n void worker.clients\n .matchAll({ includeUncontrolled: true, type: \"window\" })\n .then((clients) => {\n for (const client of clients) client.postMessage({ type: \"sandboxedjs:stale\" });\n });\n },\n};\n\nconst router = new PreviewRouter(options);\n\nworker.addEventListener(\"install\", () => void worker.skipWaiting());\nworker.addEventListener(\"activate\", (event) => event.waitUntil(worker.clients.claim()));\n\nworker.addEventListener(\"message\", (event) => {\n const data = event.data as { type?: string } | null;\n if (data?.type !== \"sandboxedjs:connect\") return;\n host = event.ports[0] ?? null;\n if (!host) return;\n /* The page decides whether previewed documents get a tunnelling\n * `WebSocket`, and it can only say so once it has a channel — this worker\n * may have been started fresh for a request, with no memory of the last\n * answer. */\n options.injectSockets = (event.data as { injectSockets?: boolean }).injectSockets !== false;\n host.onmessage = (message) => {\n const reply = message.data as { id: number; response: ProxiedResponse };\n router.settle(reply.id, reply.response);\n };\n host.start();\n router.connect();\n /* Release anything that was waiting on this channel arriving. */\n awaitingHost?.resolve();\n});\n\nworker.addEventListener(\"fetch\", (event) => {\n const url = new URL(event.request.url);\n if (url.origin !== worker.location.origin) return;\n\n const claimed = router.claimedPort(url.pathname);\n if (claimed !== null && event.request.mode === \"navigate\") {\n /* A navigation's client does not exist yet, so it is named by\n * `resultingClientId`. Binding it here is what lets every later request\n * from that document be recognised without touching its URLs. */\n router.bind(event.resultingClientId || event.clientId, claimed);\n event.respondWith(router.fetch(claimed, \"/\", event.request, event.resultingClientId || event.clientId));\n return;\n }\n\n const port = router.portFor(event.clientId);\n if (port === undefined) return; // not a preview: the host page's own traffic\n /* Strip this worker's own claim prefix before asking the container: a\n * relative asset resolves against the document's URL, so it arrives carrying\n * the prefix the container knows nothing about. */\n event.respondWith(\n router.fetch(port, router.containerPath(url.pathname, url.search), event.request, event.clientId),\n );\n});\n"]}
|