Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
/* ──────────────────────────────────────────────────────────────
INLINE WORKER – “file:// edition”
(gzip → text) ES-MODULE – no DOM dependencies
----------------------------------------------------------------
Added / kept
• global URL REGISTRYistry (all inline-generated blob: URLs)
• single beforeunload gc/release for every stub
• lazy-promise helpers (blob / url)
• explicit dispose()
────────────────────────────────────────────────────────────────*/
const filePath = '$__WORKER_PATH__'; // ↖ used only if you want
// fetch-redirect support
let GZ_B64_SRC = `$__WORKER_B64_GZ__`; // ← injected at build-time
/*─────────────────────────────────────────────────────────────────────
❶ Global REGISTRYistry & single beforeunload hook
─────────────────────────────────────────────────────────────────────*/
const REGISTRY = globalThis[
Symbol.for('__INLINE_WORKER_URL_REGISTRYISTRY__')
] ||= new Map(); // filePath? → blobURL
const BOOT = Symbol.for('__INLINE_WORKER_BOOTSTRAPPED__');
if (!globalThis[BOOT]) {
globalThis[BOOT] = true;
/* optional fetch-redirect (skip if not needed) */
const origFetch = globalThis.fetch?.bind(globalThis);
if (origFetch) {
globalThis.fetch = (req, init) => {
const url =
typeof req === 'string' ? req
: req instanceof Request ? req.url
: req instanceof URL ? req.href
: '';
for (const [p, blobURL] of REGISTRY)
if (url.endsWith(p)) return origFetch(blobURL, init);
return origFetch(req, init);
};
}
/* global release */
addEventListener('beforeunload', () => {
for (const u of REGISTRY.values()) URL.revokeObjectURL(u);
REGISTRY.clear();
});
}
/*─────────────────────────────────────────────────────────────────────
❷ Payload guards / helpers
─────────────────────────────────────────────────────────────────────*/
GZ_B64_SRC = GZ_B64_SRC?.trim();
if (!GZ_B64_SRC || GZ_B64_SRC[0] === '$') {
throw new Error('Inline worker payload missing');
}
const b64ToU8 = b64 => {
const bin = atob(b64);
return Uint8Array.from({ length: bin.length }, (_, i) => bin.charCodeAt(i));
};
const asStream = u8 => new ReadableStream({
start(c) { c.enqueue(u8); c.close(); }
});
/*─────────────────────────────────────────────────────────────────────
❸ Main promise – “workerReady”
─────────────────────────────────────────────────────────────────────*/
export const workerReady = (async () => {
const compressed = b64ToU8(GZ_B64_SRC);
const stream = 'DecompressionStream' in globalThis
? asStream(compressed).pipeThrough(new DecompressionStream('gzip'))
: asStream(
(await import(
'https://cdn.jsdelivr.net/npm/fflate@0.8.0/esm/browser.js'
)).gunzipSync(compressed)
);
const workerCode = await new Response(stream).text();
/* GC-hints */
GZ_B64_SRC = undefined;
compressed.fill(0);
/* ── lazy memoised helpers ─────────────────────────── */
let blobP, urlP;
const workerBlobPromise = () =>
blobP ||= Promise.resolve(
new Blob([workerCode], { type: 'application/javascript' })
);
const workerURLPromise = () =>
urlP ||= (async () => {
const url = URL.createObjectURL(await workerBlobPromise());
if (filePath) REGISTRY.set(filePath, url);
return url;
})();
/* quick one-shot helper: spawn() */
const spawn = async (opts = {}) =>
new Worker(await workerURLPromise(), opts);
const disposeURL = () => {
const url = REGISTRY.get(filePath);
if (url) {
URL.revokeObjectURL(url);
REGISTRY.delete(filePath);
}
}
return { workerCode, workerBlobPromise, workerURLPromise, spawn, disposeURL };
})();
export default workerReady;
the two stub dup many code. help refactor the common things out into another importable module usable by both. goal is to DRY.
Of course. This is an excellent candidate for refactoring. The two stubs share a significant amount of boilerplate for bootstrapping, payload decoding, and decompression.
Here's a refactoring that extracts the common logic into a shared library module, inline_asset.lib.mjs, which is then imported by the two leaner stub files.
inline_asset.lib.mjsThis new file will contain all the duplicated logic: the global registry setup, fetch interception, beforeunload cleanup, payload validation, and the decompression pipeline.
/* ──────────────────────────────────────────────────────────────
INLINE WASM – “file:// edition”
(gzip → bytes) ES-MODULE – no DOM dependencies
----------------------------------------------------------------
Added / kept
• global fetch-redirect registry
• compile-streaming + fallback
• isWasmReady flag, sync/async helpers, releaseWasm()
────────────────────────────────────────────────────────────────*/
const filePath = '$__WASM_PATH__'; // injected at build-time
let GZ_B64_SRC = `$__WASM_B64_GZ__`; // ← injected at build-time
// global registry shared by all inline stubs
const REGISTRY = globalThis[
Symbol.for('__INLINE_WASM_FETCH_REGISTRY__')
] ||= new Map(); // filePath → blob:
// ONE flag → has bootstrap run?
const BOOT = Symbol.for('__INLINE_WASM_BOOTSTRAPPED__');
if (!globalThis[BOOT]) {
globalThis[BOOT] = true;
/* fetch redirect --------------------------------------------------- */
const origFetch = globalThis.fetch.bind(globalThis);
globalThis.fetch = (req, init) => {
const url =
typeof req === 'string' ? req
: req instanceof Request ? req.url
: req instanceof URL ? req.href
: '';
for (const [path, blobURL] of REGISTRY)
if (url.endsWith(path)) return origFetch(blobURL, init);
return origFetch(req, init);
};
/* beforeunload cleanup --------------------------------------------- */
addEventListener('beforeunload', () => {
for (const u of REGISTRY.values()) URL.revokeObjectURL(u);
REGISTRY.clear();
});
}
/*─────────────────────────────────────────────────────────────────────
gzip-base64 payload
─────────────────────────────────────────────────────────────────────*/
GZ_B64_SRC = GZ_B64_SRC?.trim();
if (!GZ_B64_SRC || GZ_B64_SRC[0] === '$') {
throw new Error('Inline WASM payload missing');
}
/* helpers */
const b64ToU8 = b64 => {
const bin = atob(b64);
return Uint8Array.from({ length: bin.length }, (_, i) => bin.charCodeAt(i));
};
const asStream = u8 => new ReadableStream({
start(c) { c.enqueue(u8); c.close(); }
});
/* main promise */
export const wasmReady = (async () => {
const compressed = b64ToU8(GZ_B64_SRC);
const stream = 'DecompressionStream' in globalThis
? asStream(compressed).pipeThrough(new DecompressionStream('gzip'))
: asStream(
(await import(
'https://cdn.jsdelivr.net/npm/fflate@0.8.0/esm/browser.js'
)).gunzipSync(compressed)
);
const wasmBuffer = await new Response(stream).arrayBuffer();
// GC-hints
GZ_B64_SRC = undefined;
compressed.fill(0);
/* lazy helpers (memoised) */
let blobP, urlP, modP;
const wasmBlobPromise = () =>
blobP ||= Promise.resolve(new Blob([wasmBuffer], { type: 'application/wasm' }));
const wasmURLPromise = () =>
urlP ||= (async () => {
const url = URL.createObjectURL(await wasmBlobPromise());
if (filePath) REGISTRY.set(filePath, url);
return url;
})();
const modulePromise = () => modP ||= WebAssembly.compile(wasmBuffer);
const instantiate = async (imports = {}) => {
const module = await modulePromise();
return { module, instance: new WebAssembly.Instance(module, imports) };
};
const disposeURL = () => {
const url = REGISTRY.get(filePath);
if (url) {
URL.revokeObjectURL(url);
REGISTRY.delete(filePath);
}
}
return { wasmBuffer, wasmBlobPromise, wasmURLPromise, modulePromise, instantiate, disposeURL };
})();
export default wasmReady;
/* ──────────────────────────────────────────────────────────────
INLINE ASSET – SHARED LIBRARY
----------------------------------------------------------------
Handles common logic for inline assets (Wasm, Workers, etc.)
• Global registry for blob: URLs
• One-time bootstrap for fetch-interception & cleanup
• Payload validation and decompression (gzip → stream)
• Factory for creating common asset helpers (blob, url, dispose)
────────────────────────────────────────────────────────────────*/
/* ----------------------------------------------------------------
❶ Global Registry & One-Time Bootstrap
------------------------------------------------------------------- */
const REGISTRY = globalThis[
Symbol.for('__INLINE_ASSET_REGISTRY__')
] ||= new Map();
const BOOT = Symbol.for('__INLINE_ASSET_BOOTSTRAPPED__');
/**
* Sets up global fetch interception and beforeunload cleanup.
* This function is idempotent and only runs its setup logic once.
*/
export function bootstrap() {
if (globalThis[BOOT]) return;
globalThis[BOOT] = true;
/* fetch redirect */
const origFetch = globalThis.fetch?.bind(globalThis);
if (origFetch) {
globalThis.fetch = (req, init) => {
const url =
typeof req === 'string' ? req
: req instanceof Request ? req.url
: req instanceof URL ? req.href
: '';
for (const [p, blobURL] of REGISTRY)
if (url.endsWith(p)) return origFetch(blobURL, init);
return origFetch(req, init);
};
}
/* global release */
addEventListener('beforeunload', () => {
for (const u of REGISTRY.values()) URL.revokeObjectURL(u);
REGISTRY.clear();
});
}
/* ----------------------------------------------------------------
❷ Payload Processing
------------------------------------------------------------------- */
/**
* Validates the gzipped base64 payload string.
* @param {string | undefined} b64_gz_src - The source string.
* @param {string} assetType - The name of the asset for error messages (e.g., 'Worker', 'WASM').
*/
export function checkPayload(b64_gz_src, assetType = 'Asset') {
if (!b64_gz_src || b64_gz_src.trim()[0] === '$') {
throw new Error(`Inline ${assetType} payload missing or not replaced`);
}
}
const b64ToU8 = b64 => {
const bin = atob(b64);
return Uint8Array.from({ length: bin.length }, (_, i) => bin.charCodeAt(i));
};
const asStream = u8 => new ReadableStream({
start(c) { c.enqueue(u8); c.close(); }
});
/**
* Decompresses a gzipped base64 string into a ReadableStream.
* @param {string} b64_gz_src - The gzipped base64 source.
* @returns {Promise<ReadableStream>} A promise that resolves to the decompressed stream.
*/
export async function decompressStream(b64_gz_src) {
const compressed = b64ToU8(b64_gz_src);
const stream = 'DecompressionStream' in globalThis
? asStream(compressed).pipeThrough(new DecompressionStream('gzip'))
: asStream(
(await import(
'https://cdn.jsdelivr.net/npm/fflate@0.8.0/esm/browser.js'
)).gunzipSync(compressed)
);
// Hint to GC that the large compressed array is no longer needed.
compressed.fill(0);
return stream;
}
/* ----------------------------------------------------------------
❸ Asset Helper Factory
------------------------------------------------------------------- */
/**
* Creates a set of memoized helper functions for a processed asset.
* @param {{data: BlobPart, filePath: string, mimeType: string}} options
* @returns {{
* blobPromise: () => Promise<Blob>,
* urlPromise: () => Promise<string>,
* disposeURL: () => void
* }}
*/
export function createAssetHelpers({ data, filePath, mimeType }) {
let blobP, urlP;
const blobPromise = () =>
blobP ||= Promise.resolve(new Blob([data], { type: mimeType }));
const urlPromise = () =>
urlP ||= (async () => {
const url = URL.createObjectURL(await blobPromise());
if (filePath) REGISTRY.set(filePath, url);
return url;
})();
const disposeURL = () => {
const url = REGISTRY.get(filePath);
if (url) {
URL.revokeObjectURL(url);
REGISTRY.delete(filePath);
}
};
return { blobPromise, urlPromise, disposeURL };
}
Now, worker_inline.stub.mjs becomes much simpler. It just orchestrates the calls to the shared library.
/* ──────────────────────────────────────────────────────────────
INLINE WORKER – “file:// edition” (Refactored)
────────────────────────────────────────────────────────────────*/
import { bootstrap, checkPayload, decompressStream, createAssetHelpers } from './inline_asset.lib.mjs';
const filePath = '$__WORKER_PATH__';
let GZ_B64_SRC = `$__WORKER_B64_GZ__`;
// ❶ Set up global hooks (idempotent)
bootstrap();
// ❷ Validate payload
checkPayload(GZ_B64_SRC, 'Worker');
// ❸ Main promise – “workerReady”
export const workerReady = (async () => {
// Decompress the payload into a stream
const stream = await decompressStream(GZ_B64_SRC);
GZ_B64_SRC = undefined; // GC hint
// WORKER-SPECIFIC: get the code as text
const workerCode = await new Response(stream).text();
// Create common helpers (blob, url, dispose)
const {
blobPromise: workerBlobPromise,
urlPromise: workerURLPromise,
disposeURL
} = createAssetHelpers({
data: workerCode,
filePath,
mimeType: 'application/javascript',
});
// WORKER-SPECIFIC: add the spawn() helper
const spawn = async (opts = {}) =>
new Worker(await workerURLPromise(), opts);
// Expose all helpers
return { workerCode, workerBlobPromise, workerURLPromise, spawn, disposeURL };
})();
export default workerReady;
Similarly, wasm_inline.stub.mjs is significantly trimmed down.
/* ──────────────────────────────────────────────────────────────
INLINE WASM – “file:// edition” (Refactored)
────────────────────────────────────────────────────────────────*/
import { bootstrap, checkPayload, decompressStream, createAssetHelpers } from './inline_asset.lib.mjs';
const filePath = '$__WASM_PATH__';
let GZ_B64_SRC = `$__WASM_B64_GZ__`;
// ❶ Set up global hooks (idempotent)
bootstrap();
// ❷ Validate payload
checkPayload(GZ_B64_SRC, 'WASM');
// ❸ Main promise – “wasmReady”
export const wasmReady = (async () => {
// Decompress the payload into a stream
const stream = await decompressStream(GZ_B64_SRC);
GZ_B64_SRC = undefined; // GC hint
// WASM-SPECIFIC: get the data as an ArrayBuffer
const wasmBuffer = await new Response(stream).arrayBuffer();
// Create common helpers (blob, url, dispose)
const {
blobPromise: wasmBlobPromise,
urlPromise: wasmURLPromise,
disposeURL
} = createAssetHelpers({
data: wasmBuffer,
filePath,
mimeType: 'application/wasm',
});
// WASM-SPECIFIC: add compilation and instantiation helpers
let modP;
const modulePromise = () => modP ||= WebAssembly.compile(wasmBuffer);
const instantiate = async (imports = {}) => {
const module = await modulePromise();
return { module, instance: new WebAssembly.Instance(module, imports) };
};
// Expose all helpers
return { wasmBuffer, wasmBlobPromise, wasmURLPromise, modulePromise, instantiate, disposeURL };
})();
export default wasmReady;
inline_asset.lib.mjs).spawn vs. instantiate).fflate), you only need to edit inline_asset.lib.mjs. Both the worker and wasm stubs will benefit automatically.createAssetHelpers factory makes the creation of the Blob/URL helpers explicit and clean.