@vielzeug/sandbox 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.js","names":[],"sources":["../src/_dev.ts","../src/errors.ts","../src/_sandbox.ts"],"sourcesContent":["const isDev = !(globalThis as { __SANDBOX_PROD__?: boolean }).__SANDBOX_PROD__;\n\n/** @internal @security — some callers interpolate user-supplied values (e.g. namedStyles key) into msg; do not log PII. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/sandbox] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n","/** Base class for all sandbox errors. */\nexport class SandboxError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is SandboxError {\n return err instanceof SandboxError;\n }\n}\n\n/**\n * Thrown when render() does not receive a 'ready' signal from the sandbox document\n * within the timeout window. The document is most likely missing the bridge script —\n * use buildDocument() to generate documents that include it.\n */\nexport class SandboxTimeoutError extends SandboxError {}\n","import type { SandboxHandle, SandboxMessage, SandboxOptions, Unsubscribe } from './types.js';\n\nimport { devOnly, warn } from './_dev';\nimport { SandboxTimeoutError } from './errors.js';\n\n// Re-export types so that _sandbox.ts still exposes them via its original named exports.\n// index.ts now imports types from ./types.js directly — these re-exports are kept only\n// to avoid breaking any direct imports of _sandbox.js in tests.\nexport type {\n SandboxBridge,\n SandboxHandle,\n SandboxMessage,\n SandboxOptions,\n SandboxStateUpdateDetail,\n Unsubscribe,\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Protocol constants\n//\n// String values for the postMessage type field crossing the host↔sandbox\n// boundary. Inlined here (not a shared module) because the bridge script is\n// a plain-JS string that cannot import TypeScript modules.\n// ---------------------------------------------------------------------------\n\nconst MSG_READY = 'ready';\nconst MSG_STATE_UPDATE = 'state-update';\nconst MSG_STATE_UPDATE_ALL = 'state-update-all';\nconst MSG_STYLE_PATCH = 'style-patch';\nconst MSG_HTML_PATCH = 'html-patch';\nconst MSG_ERROR = 'error';\nconst MSG_CUSTOM = 'custom';\nconst MSG_RESIZE = 'resize';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isMsgObject(data: unknown): data is Record<string, unknown> & { type: string } {\n return typeof data === 'object' && data !== null && typeof (data as { type?: unknown }).type === 'string';\n}\n\nfunction extractOrigin(url: string): string | null {\n try {\n const o = new URL(url).origin;\n\n return o !== 'null' ? o : null;\n } catch {\n return null;\n }\n}\n\n// Prevent CSS breakout: the HTML spec treats <style> as a raw-text element —\n// it ends at the first `</style` token and the sequence cannot be escaped in\n// HTML. The correct fix is to escape `<` in CSS using its CSS unicode escape\n// `\\3C ` (trailing space terminates the escape sequence). This produces valid\n// CSS that the browser parses correctly, but breaks the HTML tokenizer's\n// `</style` match. The backslash itself is safe because CSS ignores unknown\n// escape sequences.\nfunction escapeCss(css: string): string {\n return css.replace(/<\\/style/gi, '\\\\3C /style');\n}\n\n// Escape a string for safe interpolation into an HTML double-quoted attribute\n// value (e.g. lang=\"…\", id=\"…\", nonce=\"…\"). Encodes the four characters that\n// can break out of an attribute or inject new attributes.\nfunction escapeAttr(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n// Escape a string for safe interpolation into HTML text content (e.g. <title>).\n// Encodes & and < to prevent tag/entity injection; > is included for symmetry.\nfunction escapeText(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n// ---------------------------------------------------------------------------\n// CSP builder\n// ---------------------------------------------------------------------------\n\n// Characters illegal inside CSP source-list tokens (origins and nonces alike) that\n// would allow directive injection or HTML attribute breakout. Specifically:\n// ';' — CSP directive separator (would inject a new directive)\n// '\"' / \"'\" — breaks out of the HTML content=\"...\" / nonce=\"...\" attribute\n// '\\n' / '\\r' — CSP header line folding / response-splitting\nconst CSP_UNSAFE_CHARS = /['\";\\n\\r]/g;\n\n// Origins must be scheme+host(+port) form; none of CSP_UNSAFE_CHARS belong there.\nfunction sanitizeCspOrigin(origin: string): string {\n return origin.replace(CSP_UNSAFE_CHARS, '');\n}\n\n// Sanitize a nonce for CSP-token embedding — CSP nonces must be base64\n// characters only; stripping quotes/semicolons/newlines prevents early token\n// termination inside 'nonce-{value}'. buildCsp() and buildDocument() MUST both\n// derive their nonce from this exact function: the CSP header's nonce token and\n// the bridge <script nonce=\"...\"> attribute have to match byte-for-byte, or the\n// browser silently rejects the script — breaking the bridge (and CSP nonce\n// matching is stricter than HTML-attribute escaping, so applying escapeAttr()\n// to the raw, unsanitized nonce for the attribute while sanitizing separately\n// for the CSP token can produce two different strings).\nfunction sanitizeNonce(nonce: string): string {\n return nonce.replace(CSP_UNSAFE_CHARS, '');\n}\n\n/**\n * Builds a strict Content-Security-Policy string for sandboxed iframe documents.\n *\n * Accepts SandboxOptions directly — origins from `scripts` URLs are extracted and\n * merged with `allowedScriptOrigins` automatically.\n */\nexport function buildCsp(options: SandboxOptions = {}): string {\n const safeNonce = options.nonce ? sanitizeNonce(options.nonce) : null;\n\n const scriptOrigins = [\n \"'unsafe-inline'\",\n ...(safeNonce ? [`'nonce-${safeNonce}'`] : []),\n ...(options.allowedScriptOrigins ?? []).map(sanitizeCspOrigin),\n ...(options.scripts ?? []).map(extractOrigin).filter((o): o is string => o !== null),\n ].join(' ');\n\n const styleOrigins = [\"'unsafe-inline'\", ...(options.allowedStyleOrigins ?? []).map(sanitizeCspOrigin)].join(' ');\n const imgOrigins = ['data:', ...(options.allowedImageOrigins ?? []).map(sanitizeCspOrigin)].join(' ');\n const fontOrigins = (options.allowedFontOrigins ?? []).map(sanitizeCspOrigin).join(' ') || \"'none'\";\n\n return [\n \"default-src 'none'\",\n `script-src ${scriptOrigins}`,\n `style-src ${styleOrigins}`,\n `img-src ${imgOrigins}`,\n `font-src ${fontOrigins}`,\n \"connect-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n ].join('; ');\n}\n\n// ---------------------------------------------------------------------------\n// Document builder\n// ---------------------------------------------------------------------------\n\n// Bridge script embedded in every sandbox document.\n//\n// Plain JS — cannot import TypeScript modules. Message type strings must\n// match the MSG_* constants above.\n//\n// Auto-resize: ResizeObserver on document.body emits 'resize' messages\n// automatically — consumers don't need to wire ResizeObserver in their\n// sandbox content. The observer is set up AFTER the 'ready' postMessage so\n// that the first resize callback (which fires synchronously on observe()) does\n// not arrive at the host before bridgeReady is set.\n//\n// style-patch is scoped to <style> elements (tagName guard) to prevent\n// accidental content injection into non-style elements with a matching id.\nconst BRIDGE_SCRIPT = `\nif ('ontouchstart' in window) document.addEventListener('touchstart', function() {}, { passive: true });\nwindow.addEventListener('message', function(e) {\n var msg = e.data;\n if (msg && msg.type === 'state-update') {\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: msg.key, value: msg.value } }));\n }\n if (msg && msg.type === 'state-update-all' && msg.record && typeof msg.record === 'object') {\n var keys = Object.keys(msg.record);\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i];\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: k, value: msg.record[k] } }));\n }\n }\n if (msg && msg.type === 'style-patch' && msg.id && typeof msg.css === 'string') {\n var el = document.getElementById(msg.id);\n if (el && el.tagName === 'STYLE') el.textContent = msg.css;\n }\n if (msg && msg.type === 'html-patch' && typeof msg.html === 'string') {\n document.body.innerHTML = msg.html;\n }\n});\n// post() tags every outgoing message with window.__sandboxGeneration (set by render(),\n// see below) and always targets '*' — srcdoc iframes have origin 'null' so no specific\n// origin can be addressed. The host uses the generation tag to ignore messages from a\n// document a newer render() has already superseded.\nfunction post(msg) {\n msg.generation = window.__sandboxGeneration;\n parent.postMessage(msg, '*');\n}\nwindow.onerror = function(message, _src, _line, _col, err) {\n post({ type: 'error', message: String(message), stack: err && err.stack });\n return true;\n};\nwindow.addEventListener('unhandledrejection', function(e) {\n var reason = e.reason;\n post({ type: 'error', message: String(reason), stack: reason && reason.stack });\n});\nwindow.__sandbox__ = {\n emit: function(event, detail) {\n post({ type: 'custom', event: event, detail: detail });\n },\n onState: function(key, handler) {\n function listener(e) {\n if (e.detail && e.detail.key === key) handler(e.detail.value);\n }\n document.addEventListener('sandbox:state-update', listener);\n return function() {\n document.removeEventListener('sandbox:state-update', listener);\n };\n }\n};\npost({ type: 'ready' });\nif (typeof ResizeObserver !== 'undefined') {\n new ResizeObserver(function(entries) {\n var entry = entries[0];\n if (!entry) return;\n var h = entry.borderBoxSize && entry.borderBoxSize[0]\n ? entry.borderBoxSize[0].blockSize\n : entry.contentRect.height;\n post({ type: 'resize', height: h });\n }).observe(document.body);\n}\n`.trim();\n\n/**\n * Builds a complete, standalone sandbox HTML document.\n *\n * `namedStyles` entries are rendered as `<style id=\"key\">` elements in the\n * document `<head>`. External scripts carry `crossorigin=\"anonymous\"` so the\n * bridge's error handler receives full error details for cross-origin scripts.\n * The bridge script auto-emits `resize` messages via `ResizeObserver`.\n */\nexport function buildDocument(html: string, options: SandboxOptions = {}): string {\n // escapeAttr is applied to the whole CSP string when embedding it in content=\"...\"\n // because buildCsp() does not know the embedding context. Any user-supplied origin\n // values that survived sanitizeCspOrigin() but still contain & or < (very unusual)\n // would otherwise break the HTML attribute.\n const csp = escapeAttr(buildCsp(options));\n const named = options.namedStyles ?? {};\n const lang = escapeAttr(options.lang ?? 'en');\n const title = escapeText(options.title ?? '');\n\n const styleTags = Object.entries(named)\n .map(([id, css]) => `<style id=\"${escapeAttr(id)}\">${escapeCss(css)}</style>`)\n .join('\\n');\n\n const scriptTags = (options.scripts ?? [])\n .map((src) => `<script crossorigin=\"anonymous\" src=\"${escapeAttr(src)}\"></script>`)\n .join('\\n');\n\n // Must sanitize with the exact same sanitizeNonce() used by buildCsp() — see its\n // comment. escapeAttr() alone is not enough: it HTML-encodes but does not strip,\n // so a raw nonce containing e.g. ';' would attribute-escape differently than the\n // CSP token strips it, producing a mismatched nonce and a silently broken bridge.\n const nonceAttr = options.nonce ? ` nonce=\"${escapeAttr(sanitizeNonce(options.nonce))}\"` : '';\n\n return `<!doctype html>\n<html lang=\"${lang}\">\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content=\"${csp}\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${title}</title>\n${styleTags}\n</head>\n<body>\n${scriptTags}\n${html}\n<script${nonceAttr}>\n${BRIDGE_SCRIPT}\n</script>\n</body>\n</html>`;\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox factory\n// ---------------------------------------------------------------------------\n\n// Dev-only timeout: if the bridge never fires 'ready' after a render(), warn\n// so the developer knows the bridge script is missing or broken.\nconst READY_TIMEOUT_MS = 5000;\n\nexport function createSandbox(container: HTMLElement, options: SandboxOptions = {}): SandboxHandle {\n // Iframe is created lazily on the first render() call — no DOM work until\n // there is content to show.\n let iframe: HTMLIFrameElement | null = null;\n const listeners = new Set<(msg: SandboxMessage) => void>();\n let disposed = false;\n const ac = new AbortController();\n\n // Mutable namedStyles baseline — updateStyle() patches this so re-renders\n // automatically use the latest CSS without the caller re-passing options.\n const namedStyles: Record<string, string> = { ...(options.namedStyles ?? {}) };\n\n // bridgeReady: true once the bridge inside the current document has fired MSG_READY.\n // Reset to false on each render() so setState/updateStyle guards work correctly.\n let bridgeReady = false;\n\n // Monotonic counter embedded into each srcdoc as window.__sandboxGeneration (see\n // render()). iframe.contentWindow's identity is stable across srcdoc navigations in\n // real browsers, so event.source alone cannot distinguish a superseded document's\n // messages from the current one — the generation tag closes that gap.\n let renderGeneration = 0;\n\n // First-render gate — resolves on first ready signal or on dispose().\n // Always resolves (never rejects) so callers can safely fire-and-forget it.\n // Check sandbox.disposed afterward to distinguish a dispose-resolution.\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n\n // Per-render settlers — replaced on each render(), resolved on the next 'ready'\n // message or when superseded/disposed (not an error — the document navigated away\n // or the sandbox was torn down intentionally), rejected only by the ready-timeout.\n let currentRenderSettlers: { reject: (err: unknown) => void; resolve: () => void } | null = null;\n let readyTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n function clearReadyTimeout(): void {\n if (readyTimeoutId !== null) {\n clearTimeout(readyTimeoutId);\n readyTimeoutId = null;\n }\n }\n\n // Supersede the in-flight render: resolve (not reject) its promise, clear the\n // timeout, and reset bridgeReady. All three must change together — keep them here.\n function supersedePendingRender(): void {\n clearReadyTimeout();\n currentRenderSettlers?.resolve();\n currentRenderSettlers = null;\n bridgeReady = false;\n }\n\n // Dispatch table for incoming sandbox→host messages.\n // Adding a new message type means adding one entry here — no separate allowlist.\n // Each handler constructs a typed SandboxMessage rather than casting, so the\n // compiler verifies the shape and malformed payloads are silently dropped.\n const msgHandlers: Record<string, (msg: Record<string, unknown>) => void> = {\n [MSG_CUSTOM]: (msg) => {\n if (typeof msg.event === 'string') {\n broadcast({ detail: msg.detail, event: msg.event, type: MSG_CUSTOM });\n }\n },\n [MSG_ERROR]: (msg) => {\n if (typeof msg.message === 'string') {\n broadcast({\n message: msg.message,\n ...(typeof msg.stack === 'string' ? { stack: msg.stack } : {}),\n type: MSG_ERROR,\n });\n }\n },\n [MSG_READY]: () => {\n // supersedePendingRender clears the timeout and resolves the render promise.\n // bridgeReady is re-set to true immediately after because the bridge IS ready.\n supersedePendingRender();\n resolveReady();\n bridgeReady = true;\n },\n [MSG_RESIZE]: (msg) => {\n if (typeof msg.height === 'number') broadcast({ height: msg.height, type: MSG_RESIZE });\n },\n };\n\n function broadcast(msg: SandboxMessage): void {\n for (const listener of listeners) listener(msg);\n }\n\n function handleMessage(event: MessageEvent): void {\n if (!iframe || event.source !== iframe.contentWindow) return;\n\n if (!isMsgObject(event.data)) return;\n\n // Reject messages tagged with a superseded generation — a document torn down by a\n // newer render() may still have a message in flight. Messages with no generation\n // (or a non-number one, e.g. from testing helpers) are trusted and pass through.\n const generation = event.data.generation;\n\n if (typeof generation === 'number' && generation !== renderGeneration) return;\n\n // Guard against prototype-inherited properties on msgHandlers (e.g. '__proto__',\n // '__defineGetter__') — these are not functions and calling them via ?.() throws.\n // Object.hasOwn ensures only keys explicitly defined in the dispatch table are invoked.\n if (Object.hasOwn(msgHandlers, event.data.type)) {\n msgHandlers[event.data.type]!(event.data);\n }\n }\n\n function ensureIframe(): HTMLIFrameElement {\n if (iframe) return iframe;\n\n iframe = document.createElement('iframe');\n iframe.setAttribute('sandbox', 'allow-scripts');\n iframe.setAttribute('referrerpolicy', 'no-referrer');\n container.appendChild(iframe);\n window.addEventListener('message', handleMessage);\n\n return iframe;\n }\n\n function dispose(): void {\n if (disposed) return;\n\n disposed = true;\n supersedePendingRender();\n ac.abort();\n resolveReady();\n\n if (iframe) {\n window.removeEventListener('message', handleMessage);\n iframe.remove();\n iframe = null;\n }\n\n listeners.clear();\n }\n\n function onMessage(handler: (msg: SandboxMessage) => void): Unsubscribe {\n if (disposed) {\n warn('onMessage() called on a disposed sandbox — handler will never fire.');\n\n return () => {};\n }\n\n listeners.add(handler);\n\n return () => {\n listeners.delete(handler);\n };\n }\n\n function render(html: string, renderOptions?: { signal?: AbortSignal }): Promise<void> {\n if (disposed) {\n warn('render() called on a disposed sandbox.');\n\n return Promise.resolve();\n }\n\n if (renderOptions?.signal?.aborted) return Promise.resolve();\n\n if (!html.trim()) {\n warn('render() called with empty HTML.');\n }\n\n // Supersede any in-flight render — its document navigated away.\n supersedePendingRender();\n\n const generation = ++renderGeneration;\n const docOptions = Object.keys(namedStyles).length > 0 ? { ...options, namedStyles: { ...namedStyles } } : options;\n\n // Inject the generation marker into <head> — it always appears before any user\n // content in the template, so this replace can never hit HTML inside `html`.\n const doc = buildDocument(html, docOptions).replace(\n '<head>',\n `<head>\\n<script>window.__sandboxGeneration=${generation};</script>`,\n );\n\n ensureIframe().srcdoc = doc;\n\n const p = new Promise<void>((resolve, reject) => {\n currentRenderSettlers = { reject, resolve };\n });\n\n // If the bridge never fires 'ready', reject with SandboxTimeoutError so the\n // document-missing-bridge-script failure is catchable rather than hanging forever.\n readyTimeoutId = setTimeout(() => {\n if (currentRenderSettlers) {\n currentRenderSettlers.reject(\n new SandboxTimeoutError(\n `render() did not receive a 'ready' signal from the sandbox document within ${READY_TIMEOUT_MS}ms. ` +\n 'The document is likely missing the bridge script — use buildDocument() to generate documents that include it.',\n ),\n );\n currentRenderSettlers = null;\n readyTimeoutId = null;\n }\n }, READY_TIMEOUT_MS);\n\n return p;\n }\n\n function patch(html: string): void {\n if (disposed) {\n warn('patch() called on a disposed sandbox.');\n\n return;\n }\n\n if (!bridgeReady || !iframe?.contentWindow) {\n warn(\n 'patch() called before render() has resolved — bridge is not yet initialized. Await the Promise returned by render() first.',\n );\n\n return;\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ html, type: MSG_HTML_PATCH }, '*');\n }\n\n function setState(key: string, value: unknown): void {\n if (disposed) {\n warn('setState() called on a disposed sandbox.');\n\n return;\n }\n\n if (!iframe?.contentWindow) {\n warn('setState() called before render() — sandbox has no document yet.');\n\n return;\n }\n\n if (!bridgeReady) {\n warn(\n 'setState() called before ready — state update may be lost if bridge is not yet initialized. Await the Promise returned by render() first.',\n );\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ key, type: MSG_STATE_UPDATE, value }, '*');\n }\n\n function setStateAll(record: Record<string, unknown>): void {\n if (disposed) {\n warn('setStateAll() called on a disposed sandbox.');\n\n return;\n }\n\n if (!iframe?.contentWindow) {\n warn('setStateAll() called before render() — sandbox has no document yet.');\n\n return;\n }\n\n if (!bridgeReady) {\n warn(\n 'setStateAll() called before ready — state updates may be lost. Await the Promise returned by render() first.',\n );\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ record, type: MSG_STATE_UPDATE_ALL }, '*');\n }\n\n function updateStyle(id: string, css: string): void {\n if (disposed) return;\n\n devOnly(() => {\n if (!(id in namedStyles)) {\n warn(\n `updateStyle('${id}', …) — '${id}' is not a known namedStyles key. ` +\n 'The live patch will have no effect. Pass the id as a key in namedStyles when calling createSandbox().',\n );\n }\n });\n\n namedStyles[id] = css;\n\n if (bridgeReady && iframe?.contentWindow) {\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ css, id, type: MSG_STYLE_PATCH }, '*');\n }\n }\n\n return {\n get disposalSignal() {\n return ac.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n onMessage,\n patch,\n ready,\n render,\n setState,\n setStateAll,\n [Symbol.dispose]() {\n dispose();\n },\n updateStyle,\n };\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA8C,iBAG9D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,uBAAuB,GAAK,CACtD,CAGA,SAAgB,EAAQ,EAAsB,CACxC,GAAO,EAAG,CAChB,CCTA,IAAa,EAAb,MAAa,UAAqB,KAAM,CACtC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAAmC,CAC3C,OAAO,aAAe,CACxB,CACF,EAOa,EAAb,cAAyC,CAAa,CAAC,ECOjD,EAAY,QACZ,EAAmB,eACnB,EAAuB,mBACvB,EAAkB,cAClB,EAAiB,aACjB,EAAY,QACZ,EAAa,SACb,EAAa,SAMnB,SAAS,EAAY,EAAmE,CACtF,OAAO,OAAO,GAAS,YAAY,GAAiB,OAAQ,EAA4B,MAAS,QACnG,CAEA,SAAS,EAAc,EAA4B,CACjD,GAAI,CACF,IAAM,EAAI,IAAI,I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E,2IACF,EAIF,EAAO,cAAc,YAAY,CAAE,MAAK,KAAM,EAAkB,OAAM,EAAG,GAAG,CAC9E,CAEA,SAAS,EAAY,EAAuC,CAC1D,GAAI,EAAU,CACZ,EAAK,6CAA6C,EAElD,MACF,CAEA,GAAI,CAAC,GAAQ,cAAe,CAC1B,EAAK,qEAAqE,EAE1E,MACF,CAEK,GACH,EACE,8GACF,EAIF,EAAO,cAAc,YAAY,CAAE,SAAQ,KAAM,CAAqB,EAAG,GAAG,CAC9E,CAEA,SAAS,EAAY,EAAY,EAAmB,CAC9C,IAEJ,MAAc,CACN,KAAM,GACV,EACE,gBAAgB,EAAG,WAAW,EAAG,wIAEnC,CAEJ,CAAC,EAED,EAAY,GAAM,EAEd,GAAe,GAAQ,eAEzB,EAAO,cAAc,YAAY,CAAE,MAAK,KAAI,KAAM,CAAgB,EAAG,GAAG,EAE5E,CAEA,MAAO,CACL,IAAI,gBAAiB,CACnB,OAAO,EAAG,MACZ,EACA,UACA,IAAI,UAAW,CACb,OAAO,CACT,EACA,YACA,QACA,QACA,SACA,WACA,cACA,CAAC,OAAO,UAAW,CACjB,EAAQ,CACV,EACA,aACF,CACF"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){function t(){return e.querySelector(`iframe`)?.contentWindow??null}function n(e){window.dispatchEvent(new MessageEvent(`message`,{data:e,source:t()}))}return{fireCustom:(e,t=void 0)=>n({detail:t,event:e,type:`custom`}),fireError:(e,t)=>n({message:e,type:`error`,...t===void 0?{}:{stack:t}}),fireReady:()=>n({type:`ready`}),fireResize:e=>n({height:e,type:`resize`})}}exports.createSandboxTestHelpers=e;
2
+ //# sourceMappingURL=testing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.cjs","names":[],"sources":["../src/testing.ts"],"sourcesContent":["/**\n * Test utilities for code that integrates with @vielzeug/sandbox.\n *\n * Import from '@vielzeug/sandbox/testing' — not the main entry point.\n * These helpers encapsulate the postMessage protocol so tests don't\n * need to know internal message shapes.\n */\n\n/** Helpers for simulating sandbox→host messages in tests. */\nexport interface SandboxTestHelpers {\n /** Fire a 'ready' signal as if the bridge script executed. */\n fireReady(): void;\n /** Fire a 'custom' event as if sandbox code called window.__sandbox__.emit(). */\n fireCustom(event: string, detail?: unknown): void;\n /** Fire a 'resize' message as if the bridge ResizeObserver fired. */\n fireResize(height: number): void;\n /** Fire an 'error' message as if the sandbox caught an uncaught error. */\n fireError(message: string, stack?: string): void;\n}\n\n/**\n * Create test helpers bound to a specific sandbox container's iframe.\n *\n * @example\n * ```ts\n * const container = document.createElement('div');\n * document.body.appendChild(container);\n * const sandbox = createSandbox(container);\n * const helpers = createSandboxTestHelpers(container);\n *\n * sandbox.render('<p>test</p>');\n * helpers.fireReady();\n * await sandbox.ready;\n * ```\n */\nexport function createSandboxTestHelpers(container: HTMLElement): SandboxTestHelpers {\n function getSource(): Window | null {\n return (container.querySelector('iframe') as HTMLIFrameElement | null)?.contentWindow ?? null;\n }\n\n function fire(data: unknown): void {\n window.dispatchEvent(new MessageEvent('message', { data, source: getSource() }));\n }\n\n return {\n fireCustom: (event, detail = undefined) => fire({ detail, event, type: 'custom' }),\n fireError: (message, stack) => fire({ message, type: 'error', ...(stack !== undefined ? { stack } : {}) }),\n fireReady: () => fire({ type: 'ready' }),\n fireResize: (height) => fire({ height, type: 'resize' }),\n };\n}\n"],"mappings":"mEAmCA,SAAgB,EAAyB,EAA4C,CACnF,SAAS,GAA2B,CAClC,OAAQ,EAAU,cAAc,QAAQ,CAAC,EAA+B,eAAiB,IAC3F,CAEA,SAAS,EAAK,EAAqB,CACjC,OAAO,cAAc,IAAI,aAAa,UAAW,CAAE,OAAM,OAAQ,EAAU,CAAE,CAAC,CAAC,CACjF,CAEA,MAAO,CACL,YAAa,EAAO,EAAS,IAAA,KAAc,EAAK,CAAE,SAAQ,QAAO,KAAM,QAAS,CAAC,EACjF,WAAY,EAAS,IAAU,EAAK,CAAE,UAAS,KAAM,QAAS,GAAI,IAAU,IAAA,GAAwB,CAAC,EAAb,CAAE,OAAM,CAAQ,CAAC,EACzG,cAAiB,EAAK,CAAE,KAAM,OAAQ,CAAC,EACvC,WAAa,GAAW,EAAK,CAAE,SAAQ,KAAM,QAAS,CAAC,CACzD,CACF"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Test utilities for code that integrates with @vielzeug/sandbox.
3
+ *
4
+ * Import from '@vielzeug/sandbox/testing' — not the main entry point.
5
+ * These helpers encapsulate the postMessage protocol so tests don't
6
+ * need to know internal message shapes.
7
+ */
8
+ /** Helpers for simulating sandbox→host messages in tests. */
9
+ export interface SandboxTestHelpers {
10
+ /** Fire a 'ready' signal as if the bridge script executed. */
11
+ fireReady(): void;
12
+ /** Fire a 'custom' event as if sandbox code called window.__sandbox__.emit(). */
13
+ fireCustom(event: string, detail?: unknown): void;
14
+ /** Fire a 'resize' message as if the bridge ResizeObserver fired. */
15
+ fireResize(height: number): void;
16
+ /** Fire an 'error' message as if the sandbox caught an uncaught error. */
17
+ fireError(message: string, stack?: string): void;
18
+ }
19
+ /**
20
+ * Create test helpers bound to a specific sandbox container's iframe.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const container = document.createElement('div');
25
+ * document.body.appendChild(container);
26
+ * const sandbox = createSandbox(container);
27
+ * const helpers = createSandboxTestHelpers(container);
28
+ *
29
+ * sandbox.render('<p>test</p>');
30
+ * helpers.fireReady();
31
+ * await sandbox.ready;
32
+ * ```
33
+ */
34
+ export declare function createSandboxTestHelpers(container: HTMLElement): SandboxTestHelpers;
35
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,6DAA6D;AAC7D,MAAM,WAAW,kBAAkB;IACjC,8DAA8D;IAC9D,SAAS,IAAI,IAAI,CAAC;IAClB,iFAAiF;IACjF,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAClD,qEAAqE;IACrE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,0EAA0E;IAC1E,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClD;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,WAAW,GAAG,kBAAkB,CAenF"}
@@ -0,0 +1,33 @@
1
+ //#region src/testing.ts
2
+ function e(e) {
3
+ function t() {
4
+ return e.querySelector("iframe")?.contentWindow ?? null;
5
+ }
6
+ function n(e) {
7
+ window.dispatchEvent(new MessageEvent("message", {
8
+ data: e,
9
+ source: t()
10
+ }));
11
+ }
12
+ return {
13
+ fireCustom: (e, t = void 0) => n({
14
+ detail: t,
15
+ event: e,
16
+ type: "custom"
17
+ }),
18
+ fireError: (e, t) => n({
19
+ message: e,
20
+ type: "error",
21
+ ...t === void 0 ? {} : { stack: t }
22
+ }),
23
+ fireReady: () => n({ type: "ready" }),
24
+ fireResize: (e) => n({
25
+ height: e,
26
+ type: "resize"
27
+ })
28
+ };
29
+ }
30
+ //#endregion
31
+ export { e as createSandboxTestHelpers };
32
+
33
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/testing.ts"],"sourcesContent":["/**\n * Test utilities for code that integrates with @vielzeug/sandbox.\n *\n * Import from '@vielzeug/sandbox/testing' — not the main entry point.\n * These helpers encapsulate the postMessage protocol so tests don't\n * need to know internal message shapes.\n */\n\n/** Helpers for simulating sandbox→host messages in tests. */\nexport interface SandboxTestHelpers {\n /** Fire a 'ready' signal as if the bridge script executed. */\n fireReady(): void;\n /** Fire a 'custom' event as if sandbox code called window.__sandbox__.emit(). */\n fireCustom(event: string, detail?: unknown): void;\n /** Fire a 'resize' message as if the bridge ResizeObserver fired. */\n fireResize(height: number): void;\n /** Fire an 'error' message as if the sandbox caught an uncaught error. */\n fireError(message: string, stack?: string): void;\n}\n\n/**\n * Create test helpers bound to a specific sandbox container's iframe.\n *\n * @example\n * ```ts\n * const container = document.createElement('div');\n * document.body.appendChild(container);\n * const sandbox = createSandbox(container);\n * const helpers = createSandboxTestHelpers(container);\n *\n * sandbox.render('<p>test</p>');\n * helpers.fireReady();\n * await sandbox.ready;\n * ```\n */\nexport function createSandboxTestHelpers(container: HTMLElement): SandboxTestHelpers {\n function getSource(): Window | null {\n return (container.querySelector('iframe') as HTMLIFrameElement | null)?.contentWindow ?? null;\n }\n\n function fire(data: unknown): void {\n window.dispatchEvent(new MessageEvent('message', { data, source: getSource() }));\n }\n\n return {\n fireCustom: (event, detail = undefined) => fire({ detail, event, type: 'custom' }),\n fireError: (message, stack) => fire({ message, type: 'error', ...(stack !== undefined ? { stack } : {}) }),\n fireReady: () => fire({ type: 'ready' }),\n fireResize: (height) => fire({ height, type: 'resize' }),\n };\n}\n"],"mappings":";AAmCA,SAAgB,EAAyB,GAA4C;CACnF,SAAS,IAA2B;EAClC,OAAQ,EAAU,cAAc,QAAQ,CAAC,EAA+B,iBAAiB;CAC3F;CAEA,SAAS,EAAK,GAAqB;EACjC,OAAO,cAAc,IAAI,aAAa,WAAW;GAAE;GAAM,QAAQ,EAAU;EAAE,CAAC,CAAC;CACjF;CAEA,OAAO;EACL,aAAa,GAAO,IAAS,KAAA,MAAc,EAAK;GAAE;GAAQ;GAAO,MAAM;EAAS,CAAC;EACjF,YAAY,GAAS,MAAU,EAAK;GAAE;GAAS,MAAM;GAAS,GAAI,MAAU,KAAA,IAAwB,CAAC,IAAb,EAAE,SAAM;EAAQ,CAAC;EACzG,iBAAiB,EAAK,EAAE,MAAM,QAAQ,CAAC;EACvC,aAAa,MAAW,EAAK;GAAE;GAAQ,MAAM;EAAS,CAAC;CACzD;AACF"}
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Options for createSandbox, buildCsp, and buildDocument.
3
+ *
4
+ * All `allowed*Origins` fields whitelist CDN/external origins for their
5
+ * respective CSP directives. Origins from `scripts` URLs are extracted
6
+ * automatically and merged with `allowedScriptOrigins`.
7
+ *
8
+ * Use `namedStyles` to inject named `<style id="key">` blocks. Each block is
9
+ * individually hot-patchable via `sandbox.updateStyle(id, css)` without
10
+ * a full re-render.
11
+ */
12
+ export interface SandboxOptions {
13
+ /** Origins added to font-src. Default: 'none'. */
14
+ allowedFontOrigins?: string[];
15
+ /** Origins appended to img-src. data: is always included. */
16
+ allowedImageOrigins?: string[];
17
+ /** Origins appended to script-src alongside 'unsafe-inline'. Merged with origins from `scripts`. */
18
+ allowedScriptOrigins?: string[];
19
+ /** Origins appended to style-src alongside 'unsafe-inline'. */
20
+ allowedStyleOrigins?: string[];
21
+ /**
22
+ * BCP 47 language tag for the `<html lang="…">` attribute of the generated document.
23
+ * Defaults to `'en'`. Pass the primary language of the sandbox content for correct
24
+ * screen-reader behaviour.
25
+ * @example { lang: 'de' }
26
+ */
27
+ lang?: string;
28
+ /**
29
+ * Named CSS blocks injected as `<style id="key">` elements in the document `<head>`.
30
+ * Each entry is individually hot-patchable via `sandbox.updateStyle(id, css)`.
31
+ * Keys must be valid HTML id values.
32
+ */
33
+ namedStyles?: Record<string, string>;
34
+ /**
35
+ * A cryptographic nonce added to the bridge <script> tag and to `script-src` in the CSP.
36
+ * In CSP Level 3 browsers the nonce suppresses `'unsafe-inline'` — only the bridge script
37
+ * (which carries the nonce attribute) executes. `'unsafe-inline'` is retained for CSP Level 2
38
+ * fallback only.
39
+ * @example { nonce: crypto.randomUUID() }
40
+ */
41
+ nonce?: string;
42
+ /** External script URLs injected before user content. Origins are auto-added to script-src. */
43
+ scripts?: string[];
44
+ /**
45
+ * Title for the generated document, placed in `<title>` in `<head>`.
46
+ * Defaults to an empty string. Providing a title improves screen reader compatibility.
47
+ */
48
+ title?: string;
49
+ }
50
+ /** Named unsubscribe function returned by `onMessage`. */
51
+ export type Unsubscribe = () => void;
52
+ /**
53
+ * The bridge API available as `window.__sandbox__` inside sandbox documents.
54
+ *
55
+ * @example Ambient declaration for sandbox-side TypeScript:
56
+ * ```ts
57
+ * declare interface Window {
58
+ * __sandbox__: import('@vielzeug/sandbox').SandboxBridge;
59
+ * }
60
+ * ```
61
+ */
62
+ export interface SandboxBridge {
63
+ /** Emit a custom event to the host. Received via sandbox.onMessage() as { type: 'custom', event, detail }. */
64
+ emit(event: string, detail?: unknown): void;
65
+ /**
66
+ * Subscribe to state pushed via sandbox.setState()/setStateAll() for a specific key.
67
+ * The handler receives only the value for the matching key — filtering the raw
68
+ * `sandbox:state-update` CustomEvent is handled for you. Returns an unsubscribe function.
69
+ * @example
70
+ * ```ts
71
+ * const off = window.__sandbox__.onState('theme', (value) => {
72
+ * document.body.dataset.theme = String(value);
73
+ * });
74
+ * ```
75
+ */
76
+ onState(key: string, handler: (value: unknown) => void): Unsubscribe;
77
+ }
78
+ /**
79
+ * Detail payload of the `sandbox:state-update` CustomEvent dispatched inside sandbox
80
+ * documents whenever the host calls setState() or setStateAll(). Sandbox-side code can
81
+ * listen to this event directly — `window.__sandbox__.onState(key, handler)` wraps it
82
+ * for the common case of listening to a single key.
83
+ *
84
+ * @example Sandbox-side listener:
85
+ * ```ts
86
+ * document.addEventListener('sandbox:state-update', (e: CustomEvent<SandboxStateUpdateDetail>) => {
87
+ * console.log(e.detail.key, e.detail.value);
88
+ * });
89
+ * ```
90
+ */
91
+ export interface SandboxStateUpdateDetail {
92
+ key: string;
93
+ value: unknown;
94
+ }
95
+ /**
96
+ * Application-level messages the sandbox sends to the host via onMessage().
97
+ *
98
+ * 'ready' is an internal lifecycle signal — it resolves render() Promises and
99
+ * is never forwarded to onMessage() subscribers.
100
+ *
101
+ * @security All SandboxMessage data is untrusted — sandboxed code controls the payload.
102
+ * Never evaluate or execute message content on the host.
103
+ */
104
+ export type SandboxMessage = {
105
+ type: 'error';
106
+ message: string;
107
+ stack?: string;
108
+ } | {
109
+ type: 'custom';
110
+ event: string;
111
+ detail: unknown;
112
+ } | {
113
+ height: number;
114
+ type: 'resize';
115
+ };
116
+ /** Handle for a running sandbox instance returned by createSandbox(). */
117
+ export interface SandboxHandle {
118
+ /** `AbortSignal` aborted when `dispose()` is called. Use to tie async operations to this sandbox's lifetime. */
119
+ readonly disposalSignal: AbortSignal;
120
+ /** True once dispose() has been called. */
121
+ readonly disposed: boolean;
122
+ /**
123
+ * Resolves when the first sandbox document signals it is ready.
124
+ * Also resolves if the sandbox is disposed before the first render — check
125
+ * `sandbox.disposed` afterward if you need to distinguish the two cases.
126
+ * Does not reset on re-renders; use the Promise returned by render() for
127
+ * subsequent renders.
128
+ */
129
+ readonly ready: Promise<void>;
130
+ /** Tear down the sandbox — removes the iframe from the DOM and clears all listeners. */
131
+ dispose(): void;
132
+ /**
133
+ * Subscribe to application-level messages from the sandboxed document.
134
+ * Receives 'error', 'custom', and 'resize' messages. The 'ready' lifecycle
135
+ * signal is not forwarded — await the Promise returned by render() instead.
136
+ * Returns an Unsubscribe function. Returns a no-op if the sandbox is already disposed.
137
+ */
138
+ onMessage(handler: (msg: SandboxMessage) => void): Unsubscribe;
139
+ /**
140
+ * Incrementally update the body of the live sandbox document without a full page reset.
141
+ * Replaces `document.body.innerHTML` inside the iframe via postMessage — scripts,
142
+ * event listeners, and CSS state are preserved. The `ResizeObserver` fires automatically
143
+ * after the DOM update.
144
+ *
145
+ * Call after the first `render()` has resolved — warns in dev if the bridge is not yet ready.
146
+ * No-ops if disposed. Does NOT accept an AbortSignal — patches are instantaneous once sent.
147
+ */
148
+ patch(html: string): void;
149
+ /**
150
+ * Replace the entire sandbox document (full page reset). Creates the iframe lazily
151
+ * on the first call — no DOM is created until render() is invoked.
152
+ * Returns a Promise that resolves when the new document signals it is ready, or
153
+ * rejects with a SandboxTimeoutError if no 'ready' signal arrives within 5s — the
154
+ * document is likely missing the bridge script; use buildDocument() to generate
155
+ * documents that include it.
156
+ * If a second render() starts before the first resolves, the first Promise resolves
157
+ * (not rejects) immediately — the document simply navigated away.
158
+ * Warns in dev if html is empty. Pass a signal to skip the render if already aborted.
159
+ */
160
+ render(html: string, options?: {
161
+ signal?: AbortSignal;
162
+ }): Promise<void>;
163
+ /**
164
+ * Push multiple state values into the sandbox in a single postMessage.
165
+ * More efficient than calling setState() repeatedly for initial state setup.
166
+ * Warns in dev if called before render() resolves.
167
+ */
168
+ setStateAll(record: Record<string, unknown>): void;
169
+ /**
170
+ * Push a state value into the sandbox without re-rendering.
171
+ * Dispatches a `sandbox:state-update` CustomEvent on `document` inside the sandbox.
172
+ * Warns in dev if called before render() resolves.
173
+ */
174
+ setState(key: string, value: unknown): void;
175
+ /**
176
+ * Replace the CSS for a named style block without a full re-render.
177
+ * `id` must match a key in the `namedStyles` option passed to `createSandbox`.
178
+ * Updates both the live iframe and the baseline so the next render() uses the new CSS.
179
+ * No-ops if the sandbox is disposed. Safe to call before the first render —
180
+ * only the baseline is updated; the iframe patch is skipped until ready.
181
+ * Warns in dev if `id` is not a known namedStyles key.
182
+ */
183
+ updateStyle(id: string, css: string): void;
184
+ [Symbol.dispose](): void;
185
+ }
186
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,cAAc;IAC7B,kDAAkD;IAClD,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B,6DAA6D;IAC7D,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC/B,oGAAoG;IACpG,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,+DAA+D;IAC/D,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC/B;;;;;OAKG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;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AAI,CAAC;IAChB;;;;;OAKG;IACH,SAAS,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,IAAI,GAAG,WAAW,CAAC;IAC/D;;;;;;;;OAQG;IACH,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B;;;;;;;;;;OAUG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACxE;;;;OAIG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACnD;;;;OAIG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAC5C;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3C,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC;CAC1B"}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@vielzeug/sandbox",
3
+ "version": "1.2.0",
4
+ "description": "Sandboxed iframe runtime with a typed postMessage state bridge for safe execution of AI-generated UI",
5
+ "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "source": "./src/index.ts",
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.cjs"
18
+ },
19
+ "./testing": {
20
+ "source": "./src/testing.ts",
21
+ "types": "./dist/testing.d.ts",
22
+ "import": "./dist/testing.js",
23
+ "require": "./dist/testing.cjs"
24
+ }
25
+ },
26
+ "scripts": {
27
+ "build": "vite build && pnpm run build:bundle && pnpm run build:types",
28
+ "build:bundle": "vite build --config vite.bundle.config.ts",
29
+ "build:types": "tsc -p tsconfig.declarations.json",
30
+ "fix": "eslint --fix src",
31
+ "lint": "eslint src",
32
+ "prepublishOnly": "pnpm run build",
33
+ "test": "vitest"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org/"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^26.1.0",
41
+ "jsdom": "^29.1.1",
42
+ "typescript": "~6.0.3",
43
+ "vite": "^8.1.3",
44
+ "vitest": "^4.1.9"
45
+ }
46
+ }