// GENERATED - do not edit. Source: afterburner-node-compat/polyfills/
// Rebuild with: AFTERBURNER_REBUILD_PLENUM=1 cargo build -p afterburner-node-compat

// ---- require.js ----
// The plenum.js require() resolver.
//
// Bare names and `node:*` resolve through the factory map installed
// by `__register_module` — that covers every Node stdlib module the
// plenum bundle ships. B6 extends this with:
//
//   * Filesystem resolution for `./`, `../`, `/` paths
//     (`require('./lib')`, `require('../util')`, `require('/abs')`).
//   * `node_modules` walk for bare names not in the stdlib factory
//     map (`require('express')` starts at the caller's `__dirname`
//     and walks up looking for `node_modules/express`).
//   * `package.json "main"` + `index.js` / `index.json` resolution
//     matching Node's CommonJS semantics.
//   * Per-module `require` closures so `./sibling` inside a loaded
//     file resolves relative to THAT file's dir, not the entry
//     script's — same as Node.
//   * `.json` file support: `require('./config.json')` returns the
//     parsed object, no need to JSON.parse by hand.
//   * `require.cache` keyed by absolute resolved path.
//   * `require.resolve(name)` → the absolute path that `require`
//     would load, without actually loading it.
//
// Filesystem lookups go through `__host_fs_*`; if the active
// Manifold denies fs access, filesystem-backed requires throw a
// clean EACCES naming the denied path ("permission denied reading
// '<path>' …") — distinguishable from a genuinely absent file, which
// stays the Node-shaped MODULE_NOT_FOUND. See `moduleNotFound` below
// for how the boolean `exists` probe (which collapses denied and
// absent to `false`) is disambiguated on the failure path.
//
// Resolution bases (Node-equivalent, all file-relative):
//   * Modules loaded through require() get a scoped require rooted at
//     THEIR OWN directory (`makeRequire(dirname(absPath))`), so
//     `require('./sibling')` inside a loaded file resolves next to
//     that file — never against the process CWD.
//   * The entry script's require is rooted at `dirname(argv[1])` for
//     `burn run file.js` (argv[1] is canonicalized absolute).
//   * Only `-e` / stdin eval mode (argv[1] === '[eval]') falls back
//     to the host CWD — there is no requiring file to be relative to.

(function plenumRequire() {
    var factories = Object.create(null);
    // Cache is shared across all per-module requires and keyed by the
    // resolved identifier: stdlib names (e.g. "path"), or absolute
    // filesystem paths (e.g. "/home/me/server.js").
    var cache = Object.create(null);

    function stripNodePrefix(name) {
        return typeof name === 'string' && name.indexOf('node:') === 0
            ? name.slice(5)
            : name;
    }

    function loadStdlib(mod) {
        var cached = cache[mod];
        if (cached !== undefined) return cached;
        var factory = factories[mod];
        if (typeof factory !== 'function') return undefined;
        var m = { exports: {} };
        // Install before invoking so cyclic requires see a partial
        // exports object rather than triggering an infinite loop.
        cache[mod] = m.exports;
        factory(m, m.exports, globalThis.require);
        // Factories may replace `module.exports` wholesale
        // (e.g. `module.exports = EventEmitter`). Pick up the final
        // binding before handing it out.
        cache[mod] = m.exports;
        return m.exports;
    }

    // ---- fs + path helpers (internal, do not depend on polyfills) ----------
    //
    // The require resolver can be reached before the `path` module's
    // factory has run on the first user invocation, so we inline the
    // sliver of path logic we need. Only POSIX-style separators —
    // Windows hosts normalize to forward slashes in `__host_cwd`.

    // fs host functions have two failure shapes depending on the
    // backend: the WASI path returns a string prefixed with
    // `__HOST_ERR__:`, and the native (rquickjs) path throws
    // directly. A failure that is a manifold PERMISSION DENIAL is
    // surfaced as an EACCES error naming the path — silently
    // collapsing it to "module not found" sent operators chasing
    // phantom missing files when the truth was an ungranted fs
    // capability. Every other failure (genuinely absent file,
    // I/O error) still reads as "not found" to the resolver.

    function isDenialDetail(msg) {
        return typeof msg === 'string'
            && msg.toLowerCase().indexOf('permission denied') !== -1;
    }

    function permissionDeniedError(path) {
        var e = new Error(
            "permission denied reading '" + path + "' (fs capability not " +
            "granted to the active manifold; grant fs read access, e.g. " +
            "--allow-fs=<dir> / --allow-fs-read=<dir> on the CLI)");
        e.code = 'EACCES';
        e.path = String(path);
        return e;
    }

    function fsExists(p) {
        if (vfsMap()) {
            if (vfsRead(String(p)) !== null || vfsIsDir(String(p))) return true;
            if (vfsPath(String(p))) return false; // virtual root: miss = absent
        }
        // NOTE: the boolean host probe cannot distinguish "absent"
        // from "denied" — denials are recovered on the resolution
        // failure path via `fsReadDenied` (see `moduleNotFound`).
        var fn = globalThis.__host_fs_exists_sync;
        if (typeof fn !== 'function') return false;
        try { return !!fn(String(p)); } catch (_) { return false; }
    }

    function fsRead(p) {
        if (vfsMap()) {
            var vv = vfsRead(String(p));
            if (vv !== null) return vv;
            if (vfsPath(String(p))) return null; // never ask the host for /afb/…
        }
        var fn = globalThis.__host_fs_read_file_sync;
        if (typeof fn !== 'function') return null;
        try {
            // The host bridge always sends bytes as base64 (binary-safe
            // wire format — see `polyfills/fs.js` for the full
            // contract). Decode to a UTF-8 string here; require()
            // never reads non-text files.
            var b64 = fn(String(p), 'base64');
            if (typeof b64 === 'string' && b64.indexOf('__HOST_ERR__:') === 0) {
                if (isDenialDetail(b64.slice('__HOST_ERR__:'.length))) {
                    throw permissionDeniedError(p);
                }
                return null;
            }
            // We can't `require('buffer')` from inside require.js
            // (circular bootstrap), so decode base64 inline. The
            // implementation matches `Buffer.from(b64, 'base64')` →
            // UTF-8 decode but without crossing the module boundary.
            return base64ToUtf8(b64);
        } catch (e) {
            if (e && e.code === 'EACCES') throw e;
            // Native (rquickjs) backend throws directly — recognise
            // its denial message shape too.
            if (e && isDenialDetail(e.message)) throw permissionDeniedError(p);
            return null;
        }
    }

    // One real read attempt against `p`, purely to learn whether the
    // failure is a manifold denial. Used only on the resolution
    // FAILURE path (zero extra host calls on successful requires).
    function fsReadDenied(p) {
        if (vfsPath(String(p))) return false; // vfs misses are absent, not denied
        var fn = globalThis.__host_fs_read_file_sync;
        if (typeof fn !== 'function') return false;
        try {
            var out = fn(String(p), 'base64');
            return typeof out === 'string'
                && out.indexOf('__HOST_ERR__:') === 0
                && isDenialDetail(out.slice('__HOST_ERR__:'.length));
        } catch (e) {
            return !!(e && (e.code === 'EACCES' || isDenialDetail(e.message)));
        }
    }

    // Build the resolution-failure error. The `exists` probes collapse
    // "denied" and "absent" to false, so before reporting Node's
    // MODULE_NOT_FOUND we make one real read attempt at the primary
    // candidate: a manifold denial becomes EACCES naming the path.
    // The MODULE_NOT_FOUND message carries the resolved base so a
    // failed relative require shows WHICH directory it resolved
    // against (CWD-vs-requiring-file misdiagnosis killer).
    //
    // `resolvedBase` is only passed for RELATIVE/ABSOLUTE specifiers
    // — the user named a concrete file, so "denied" vs "absent" is a
    // meaningful, actionable distinction there. Bare names (`null`
    // base) keep the plain Node-shaped message: the node_modules walk
    // spans many directories, the package may genuinely not be
    // installed, and the default-sealed embedding (UDF mode) would
    // otherwise report every missing package as a permission problem.
    function moduleNotFound(name, resolvedBase) {
        if (resolvedBase && fsReadDenied(resolvedBase)) {
            return permissionDeniedError(resolvedBase);
        }
        var e = new Error("Cannot find module '" + name + "'"
            + (resolvedBase && resolvedBase !== name
                ? " (resolved against '" + resolvedBase + "')"
                : ''));
        e.code = 'MODULE_NOT_FOUND';
        return e;
    }

    // Tiny inlined base64→UTF-8 decoder. Used only by the require
    // resolver's source loader; cleaner than calling out to
    // `Buffer` (which lives in a module we may be in the middle of
    // bootstrapping). globalThis.atob produces a "binary string"
    // (each char = one byte, ≤255), then we re-decode as UTF-8.
    var B64_INV = (function() {
        var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
        var inv = new Int16Array(256);
        for (var i = 0; i < 256; i++) inv[i] = -1;
        for (var j = 0; j < alphabet.length; j++) inv[alphabet.charCodeAt(j)] = j;
        return inv;
    })();

    function base64ToUtf8(s) {
        // Strip padding for length math.
        var clean = s.replace(/=+$/, '');
        var bytesLen = Math.floor(clean.length * 3 / 4);
        var bytes = new Uint8Array(bytesLen);
        var bi = 0;
        for (var i = 0; i + 4 <= clean.length; i += 4) {
            var n = (B64_INV[clean.charCodeAt(i)]   << 18) |
                    (B64_INV[clean.charCodeAt(i+1)] << 12) |
                    (B64_INV[clean.charCodeAt(i+2)] << 6)  |
                    (B64_INV[clean.charCodeAt(i+3)]);
            bytes[bi++] = (n >> 16) & 0xff;
            bytes[bi++] = (n >> 8)  & 0xff;
            bytes[bi++] = n & 0xff;
        }
        var rem = clean.length - i;
        if (rem === 2) {
            var n2 = (B64_INV[clean.charCodeAt(i)]   << 18) |
                     (B64_INV[clean.charCodeAt(i+1)] << 12);
            bytes[bi++] = (n2 >> 16) & 0xff;
        } else if (rem === 3) {
            var n3 = (B64_INV[clean.charCodeAt(i)]   << 18) |
                     (B64_INV[clean.charCodeAt(i+1)] << 12) |
                     (B64_INV[clean.charCodeAt(i+2)] << 6);
            bytes[bi++] = (n3 >> 16) & 0xff;
            bytes[bi++] = (n3 >> 8)  & 0xff;
        }
        if (typeof TextDecoder === 'function') {
            return new TextDecoder('utf-8').decode(bytes.subarray(0, bi));
        }
        // Fallback — correct for ASCII; user source under burn is JS
        // which is overwhelmingly ASCII / latin-1 friendly. Non-ASCII
        // identifiers would require the TextDecoder path above
        // (always present in QuickJS post-Phase E).
        var out = '';
        for (var k = 0; k < bi; k++) out += String.fromCharCode(bytes[k]);
        return out;
    }

    function fsIsDir(p) {
        if (vfsMap()) {
            if (vfsIsDir(String(p))) return true;
            if (vfsPath(String(p))) return false;
        }
        var fn = globalThis.__host_fs_stat_sync;
        if (typeof fn !== 'function') return false;
        try {
            var raw = fn(String(p));
            if (typeof raw !== 'string' || raw.indexOf('__HOST_ERR__:') === 0) return false;
            return JSON.parse(raw).isDirectory === true;
        } catch (_) {
            return false;
        }
    }

    // ---- virtual package filesystem -----------------------------
    //
    // A composed .afb module (multi-file package, vendored
    // node_modules, digest-pinned dependency packages) delivers its
    // whole file tree as DATA inside the compiled source:
    //   globalThis.__afb_files = { '/afb/source/main.js': '…', … }
    //   globalThis.__afb_links = { 'ns/name': '/afb/deps/ns/name/source/main.js' }
    // The probes below consult that map FIRST, so the entire Node
    // resolution algorithm (exports maps, extension ladder, caching,
    // circular semantics) runs unchanged over virtual paths — and a
    // '/afb/…' path NEVER reaches the host fs bridge: a vfs miss is
    // "absent", not a manifold question. Real-fs behavior (and its
    // manifold gating) is byte-for-byte unchanged for every other
    // path; network access from vendored code is not touched by any
    // of this — it still goes through the host net gates.
    var vfsDirCache = null;
    function vfsMap() {
        var m = globalThis.__afb_files;
        return (m && typeof m === 'object') ? m : null;
    }
    function vfsPath(p) {
        return typeof p === 'string' && p.indexOf('/afb/') === 0;
    }
    function vfsRead(p) {
        var m = vfsMap();
        if (!m) return null;
        var v = m[p];
        return typeof v === 'string' ? v : null;
    }
    function vfsIsDir(p) {
        var m = vfsMap();
        if (!m) return false;
        if (vfsDirCache === null) {
            // Built once per instance: every ancestor dir of every
            // virtual file. Keeps the node_modules walk O(1) per
            // probe even for thousand-file vendored packages.
            vfsDirCache = {};
            for (var k in m) {
                var d = dirname(k);
                while (d && d !== '/' && !vfsDirCache[d]) {
                    vfsDirCache[d] = true;
                    d = dirname(d);
                }
            }
        }
        var key = p.charAt(p.length - 1) === '/' ? p.slice(0, -1) : p;
        return vfsDirCache[key] === true;
    }

    function dirname(p) {
        if (!p || p === '/') return '/';
        var trimmed = p.charAt(p.length - 1) === '/' ? p.slice(0, -1) : p;
        var i = trimmed.lastIndexOf('/');
        if (i < 0) return '.';
        if (i === 0) return '/';
        return trimmed.slice(0, i);
    }

    function normalize(p) {
        var absolute = p.charAt(0) === '/';
        var parts = p.split('/');
        var out = [];
        for (var i = 0; i < parts.length; i++) {
            var seg = parts[i];
            if (seg === '' || seg === '.') continue;
            if (seg === '..') {
                if (out.length > 0 && out[out.length - 1] !== '..') {
                    out.pop();
                } else if (!absolute) {
                    out.push('..');
                }
            } else {
                out.push(seg);
            }
        }
        var joined = out.join('/');
        return absolute ? '/' + joined : (joined || '.');
    }

    function resolveJoin(base, rel) {
        if (rel.charAt(0) === '/') return normalize(rel);
        return normalize(base + '/' + rel);
    }

    function isRelativeOrAbsolute(name) {
        if (typeof name !== 'string' || name.length === 0) return false;
        var c0 = name.charAt(0);
        if (c0 === '/') return true;
        if (c0 !== '.') return false;
        var c1 = name.charAt(1);
        return c1 === '/' || (c1 === '.' && name.charAt(2) === '/') || name.length === 1 || name === '..';
    }

    // Given a candidate absolute path, try the Node CJS resolution
    // ladder. Extensions tried (in order): exact, .js, .json, .mjs,
    // .cjs, .ts, .mts, .cts. TS/ESM extensions are opt-in — the
    // loader asks the host to transpile them before running. If the
    // host has no transpile hook (built without `ts`), loading a
    // .ts/.mjs surfaces a clean error instead of a JS parse failure.
    var EXTENSION_LADDER = ['.js', '.json', '.mjs', '.cjs', '.ts', '.mts', '.cts'];

    function resolveCandidate(candidate) {
        if (fsExists(candidate) && !fsIsDir(candidate)) return candidate;
        for (var i = 0; i < EXTENSION_LADDER.length; i++) {
            var p = candidate + EXTENSION_LADDER[i];
            if (fsExists(p)) return p;
        }
        if (fsIsDir(candidate)) {
            var pkg = candidate + '/package.json';
            if (fsExists(pkg)) {
                var data = fsRead(pkg);
                if (typeof data === 'string') {
                    try {
                        var parsed = JSON.parse(data);
                        var main = parsed && typeof parsed.main === 'string' ? parsed.main : null;
                        if (main) {
                            var mainAbs = resolveJoin(candidate, main);
                            var resolved = resolveCandidate(mainAbs);
                            if (resolved) return resolved;
                        }
                    } catch (_) { /* malformed package.json falls through to index */ }
                }
            }
            // Directory fallback — match the extension order above.
            for (var j = 0; j < EXTENSION_LADDER.length; j++) {
                var idx = candidate + '/index' + EXTENSION_LADDER[j];
                if (fsExists(idx)) return idx;
            }
        }
        return null;
    }

    // Transpile if the extension or contents need it. TS / `.mts` /
    // `.mjs` always go through the host transpile hook. Plain `.js`
    // files are scanned for ESM syntax — if found, they are routed
    // through the same hook so `import` / `export` lower to
    // CommonJS. ESM-only npm packages (chalk, ora, etc., which set
    // `"type": "module"` and ship .js files) reach us via this
    // path; without it `require('chalk')` would parse-fail at
    // `import` keywords. The fast string-scan keeps plain CJS
    // modules off the oxc parse path.
    function maybeTranspile(source, absPath) {
        var lower = absPath.toLowerCase();
        var explicit = lower.slice(-3) === '.ts'
                    || lower.slice(-4) === '.mts'
                    || lower.slice(-4) === '.cts'
                    || lower.slice(-4) === '.mjs';
        var needs = explicit;
        if (!needs && (lower.slice(-3) === '.js' || lower.slice(-4) === '.cjs')) {
            // Cheap pre-check: top-of-line `import …` / `export …` /
            // `import.meta` are the markers that warrant a real
            // lowering pass. Mid-line `import` (in strings, comments,
            // member access) is fine — oxc would no-op those — but we
            // skip the parse to keep CJS imports cheap.
            needs = /(^|\n)\s*(import\s|import\(|export\s|export\{)/.test(source)
                 || source.indexOf('import.meta') >= 0;
        }
        if (!needs) return source;
        var fn = globalThis.__host_ts_transpile;
        if (typeof fn !== 'function') {
            // Only TS files hard-require the hook. `.js` callers fall
            // back to the unmodified source and let the CJS parser
            // surface its own error if it actually contained ESM —
            // matches the no-`ts`-feature flow on the CLI side.
            if (!explicit) return source;
            var e = new Error("Loading '" + absPath + "' requires the `ts` cargo feature");
            e.code = 'ERR_UNSUPPORTED_EXTENSION';
            throw e;
        }
        var out = fn(source, absPath);
        if (typeof out === 'string' && out.indexOf('__HOST_ERR__:') === 0) {
            var err = new Error("Transpile failed for '" + absPath + "': " + out.slice('__HOST_ERR__:'.length));
            err.code = 'ERR_TRANSPILE_FAILED';
            throw err;
        }
        return out;
    }

    // Subpath imports (`#name`) — Node's mechanism for a package to
    // reference its own internal modules without exposing them to
    // consumers. We walk up from `fromDir` for the nearest
    // `package.json`, look up its `imports` field, and resolve the
    // matched entry relative to that package's root. Conditional
    // exports collapse to `node` → `default` (we don't support
    // `import` vs `require` discrimination since we have a single
    // require-shaped resolver). Returns the absolute path or null.
    function resolveSubpathImport(name, fromDir) {
        var dir = fromDir;
        if (typeof dir !== 'string' || dir.length === 0) dir = '/';
        for (var i = 0; i < 64; i++) {
            var pkgPath = dir + '/package.json';
            if (fsExists(pkgPath)) {
                var raw = fsRead(pkgPath);
                if (typeof raw === 'string') {
                    var pkg;
                    try { pkg = JSON.parse(raw); } catch (_) { pkg = null; }
                    if (pkg && pkg.imports && typeof pkg.imports === 'object') {
                        var entry = pkg.imports[name];
                        if (entry === undefined) {
                            // Pattern subpath imports like
                            // `#feature/*` would land here in Node.
                            // We don't support patterns yet — fall
                            // through to upper package.json.
                        } else {
                            var relative = pickConditional(entry);
                            if (typeof relative === 'string') {
                                var abs = resolveJoin(dir, relative);
                                var r = resolveCandidate(abs);
                                if (r) return r;
                            }
                        }
                    }
                }
            }
            var parent = dirname(dir);
            if (parent === dir) break;
            dir = parent;
        }
        return null;
    }

    // Conditional-exports resolver: pick `node` then `default` then
    // the first string entry. Strings are returned as-is.
    function pickConditional(entry) {
        if (typeof entry === 'string') return entry;
        if (!entry || typeof entry !== 'object') return null;
        // CJS-lens condition priority. `require`/`node` MUST win over
        // `import`: dual-build packages (e.g. glob → import:esm,
        // require:commonjs) ship a CommonJS build our `require()` can
        // load directly, whereas the `import` build is ESM that often
        // won't parse as-is. Crucially we resolve by this fixed
        // priority rather than package.json key order — otherwise a
        // package that lists `import` before `require` (glob does)
        // would pick the ESM build. `import` is the last resort (it
        // would need transpiling). Each condition may be a string or a
        // nested condition object, so recurse.
        var order = ['node', 'require', 'default', 'import'];
        for (var i = 0; i < order.length; i++) {
            var v = entry[order[i]];
            if (typeof v === 'string') return v;
            if (v && typeof v === 'object') {
                var nested = pickConditional(v);
                if (nested) return nested;
            }
        }
        // Custom/unknown conditions as a last resort — but never
        // `types` (a `.d.ts` pointer, not a runtime target).
        for (var k in entry) {
            if (k === 'types' || order.indexOf(k) !== -1) continue;
            if (typeof entry[k] === 'string') return entry[k];
            if (entry[k] && typeof entry[k] === 'object') {
                var n2 = pickConditional(entry[k]);
                if (n2) return n2;
            }
        }
        return null;
    }

    // Split a bare specifier into the package name and an optional
    // subpath. Scoped packages (`@scope/name/sub`) keep the first two
    // segments as the package name.
    function splitPackageSpecifier(name) {
        if (name.charAt(0) === '@') {
            var parts = name.split('/');
            return { pkg: parts.slice(0, 2).join('/'), sub: parts.slice(2).join('/') };
        }
        var idx = name.indexOf('/');
        if (idx === -1) return { pkg: name, sub: '' };
        return { pkg: name.slice(0, idx), sub: name.slice(idx + 1) };
    }

    // Pattern-subpath exports: `"./foo/*": "./dist/foo/*.js"`. Match
    // `key` against the `*`-bearing export keys and substitute the
    // captured segment into the (conditional-resolved) target.
    function matchExportsPattern(exp, key) {
        for (var pat in exp) {
            var star = pat.indexOf('*');
            if (star === -1) continue;
            var prefix = pat.slice(0, star);
            var suffix = pat.slice(star + 1);
            if (key.length >= prefix.length + suffix.length
                && key.slice(0, prefix.length) === prefix
                && (suffix === '' || key.slice(key.length - suffix.length) === suffix)) {
                var mid = key.slice(prefix.length, key.length - suffix.length);
                var tgt = pickConditional(exp[pat]);
                if (typeof tgt === 'string') return tgt.split('*').join(mid);
            }
        }
        return null;
    }

    // Resolve a package + subpath through the package.json `exports`
    // field — the modern, authoritative map and the ONLY way to reach
    // subpath exports like `@scope/pkg/sub` whose target lives where
    // `main`/index can't see (e.g. `@sigstore/protobuf-specs/rekor/v2`
    // → `./dist/rekor/v2/index.js`). Returns an absolute path or null
    // (null falls back to legacy main/index resolution).
    function resolveViaExports(pkgRoot, sub) {
        var pkgJson = pkgRoot + '/package.json';
        if (!fsExists(pkgJson)) return null;
        var raw = fsRead(pkgJson);
        if (typeof raw !== 'string') return null;
        var pkg;
        try { pkg = JSON.parse(raw); } catch (_) { return null; }
        if (!pkg || pkg.exports === undefined || pkg.exports === null) return null;
        var exp = pkg.exports;
        var key = sub ? ('./' + sub) : '.';
        var target = null;
        if (typeof exp === 'string') {
            // String shorthand describes the `.` entry only.
            if (key === '.') target = exp;
        } else if (typeof exp === 'object') {
            // If no key looks like a subpath (`.`/`./…`), the object is
            // a bare condition map for `.` (e.g. `{ require, import }`).
            var hasSubpathKeys = false;
            for (var k in exp) {
                if (k === '.' || k.charAt(0) === '.') { hasSubpathKeys = true; break; }
            }
            if (!hasSubpathKeys) {
                if (key === '.') target = pickConditional(exp);
            } else if (Object.prototype.hasOwnProperty.call(exp, key)) {
                target = pickConditional(exp[key]);
            } else {
                target = matchExportsPattern(exp, key);
            }
        }
        if (typeof target !== 'string') return null;
        var abs = resolveJoin(pkgRoot, target);
        return resolveCandidate(abs) || (fsExists(abs) && !fsIsDir(abs) ? abs : null);
    }

    // Walk up `fromDir` looking for `node_modules/<pkg>`. Consults the
    // package's `exports` map first (authoritative for subpaths), then
    // falls back to legacy main/index + filesystem-join resolution.
    // Returns the absolute resolved file path, or null.
    function resolvePackage(name, fromDir) {
        var dir = fromDir;
        // Guard against pathological inputs (empty dir, etc.).
        if (typeof dir !== 'string' || dir.length === 0) dir = '/';
        var spec = splitPackageSpecifier(name);
        // Safety bound: 64 parent walks is far more than any real tree.
        for (var i = 0; i < 64; i++) {
            var pkgRoot = dir + '/node_modules/' + spec.pkg;
            if (fsIsDir(pkgRoot)) {
                var viaExports = resolveViaExports(pkgRoot, spec.sub);
                if (viaExports) return viaExports;
                // Legacy: bare name → main/index; subpath → join onto
                // the package root and resolve (covers packages with no
                // `exports` and deep imports they still permit).
                var cand = spec.sub ? (pkgRoot + '/' + spec.sub) : pkgRoot;
                var r = resolveCandidate(cand);
                if (r) return r;
            }
            var parent = dirname(dir);
            if (parent === dir) break;
            dir = parent;
        }
        return null;
    }

    // Cache stores `module` records, not bare `module.exports`. This
    // mirrors Node's `require.cache` shape (`{ [path]: Module }` —
    // `Module.exports` resolved at read-time) and is the ONLY way
    // circular requires work correctly: when `a.js` partially loads
    // and requires `b.js`, which requires `a.js` back, `b.js` must
    // see the LATEST `a.js` exports object — including any
    // `module.exports = NewClass` reassignment that happened between
    // the cache install and the cycle re-entry. Caching the bare
    // `module.exports` snapshot misses every such reassignment and
    // hands cycles a stale empty object, which surfaces in user code
    // as `parent class must be constructor` or
    // `Cannot read property 'X' of undefined`.
    function getCached(path) {
        var rec = cache[path];
        if (rec === undefined) return undefined;
        // JSON modules are cached as the parsed value directly; only
        // module records have an `exports` property + `loaded` flag.
        if (rec && typeof rec === 'object' && Object.prototype.hasOwnProperty.call(rec, 'exports')
            && Object.prototype.hasOwnProperty.call(rec, 'filename')) {
            return rec.exports;
        }
        return rec;
    }

    function loadAbsoluteFile(absPath, scopedRequire) {
        var cached = getCached(absPath);
        if (cached !== undefined) return cached;
        // A manifold denial throws EACCES from fsRead directly; a
        // null here means the file vanished between the exists probe
        // and the read (or an I/O error) — report it as not found.
        var source = fsRead(absPath);
        if (source === null) {
            throw moduleNotFound(absPath, absPath);
        }
        if (absPath.slice(-5) === '.json') {
            var parsed = JSON.parse(source);
            cache[absPath] = parsed;
            return parsed;
        }
        // B8/B9: .ts/.mts/.cts/.mjs files go through the host's
        // oxc-based transpiler before landing in the CJS wrapper.
        // Plain .js / .cjs pass through untouched.
        source = maybeTranspile(source, absPath);
        // Node strips a leading hashbang before handing source to V8;
        // QuickJS rejects `#!`. Replace with `//` so line numbers
        // stay aligned with the on-disk file. Also drops a UTF-8 BOM
        // if one is present (which would otherwise reach the Function
        // constructor and parse-fail the same way).
        if (source.charCodeAt(0) === 0xFEFF) {
            source = source.slice(1);
        }
        if (source.charCodeAt(0) === 0x23 /* # */ &&
            source.charCodeAt(1) === 0x21 /* ! */) {
            source = '//' + source.slice(2);
        }
        // Dynamic `import(spec)` has no module loader registered in
        // QuickJS, so the bare expression throws "could not load
        // module 'X'" the moment it runs. Rewrite to a require-based
        // shim BEFORE the source reaches the Function constructor.
        // This keeps the npm / corepack / yarn dispatch chain
        // (which uses `await import('chalk')`) functional under our
        // CJS-shaped require resolver. The shim resolves to a
        // namespace-shaped object (matches Node's CJS-from-ESM
        // interop). The pattern is conservative — only `import(`
        // followed by a non-`.` (excludes `import.meta` /
        // `imports.foo`) and not preceded by an identifier char
        // (excludes `aimport(`). Strings/comments containing
        // `import(` are a known false-positive but vanishingly rare
        // in distributed npm packages.
        if (source.indexOf('import(') >= 0 || source.indexOf('import (') >= 0) {
            // Capture the closure-scoped `require` as the FIRST arg so
            // the import resolves relative to *this* file's dir, not
            // the entry script's. Async dynamic imports inside class
            // methods would otherwise lose the active-require frame
            // by the time they fire.
            source = source.replace(
                /([^A-Za-z0-9_$]|^)import(\s*)\(/g,
                '$1globalThis.__ab_dyn_import$2(require,'
            );
        }
        // Node CJS wrapper — `module.exports` / `exports` are the
        // user-visible outputs; `require` is the scoped copy; the two
        // `__filename` / `__dirname` bindings match Node.
        var modObj = { exports: {}, filename: absPath, loaded: false };
        var dir = dirname(absPath);
        // Compile first so a parse error can name the module. QuickJS
        // SyntaxErrors carry no source context; without the path, a
        // failed dependency surfaces as a bare "Unexpected token …"
        // with no hint which file is at fault.
        var fn;
        try {
            fn = new Function(
                'module', 'exports', 'require', '__filename', '__dirname',
                source
            );
        } catch (compileErr) {
            if (compileErr && typeof compileErr.message === 'string'
                && compileErr.message.indexOf(absPath) === -1) {
                compileErr.message += ' (while compiling ' + absPath + ')';
            }
            throw compileErr;
        }
        // Install the MODULE record (not the exports snapshot) before
        // invoking the user body. Cycles look up `cache[absPath]` and
        // pull `.exports` at access time — so any
        // `module.exports = NewClass` reassignment inside the user
        // body is visible to a re-entrant require immediately.
        cache[absPath] = modObj;
        // Stash the current scoped require before running the user body
        // so dynamic `import(...)` (rewritten to `__ab_dyn_import`)
        // walks `node_modules` from the importing file's dir. JS is
        // single-threaded so the save/restore is race-free; nested
        // requires nest their saves naturally.
        var prevActive = globalThis.__ab_active_require;
        globalThis.__ab_active_require = scopedRequire;
        try {
            fn(modObj, modObj.exports, scopedRequire, absPath, dir);
        } catch (e) {
            // Broken module — evict so a retry can re-run the factory
            // cleanly.
            delete cache[absPath];
            throw e;
        } finally {
            globalThis.__ab_active_require = prevActive;
        }
        modObj.loaded = true;
        return modObj.exports;
    }

    // Construct a `require` closure scoped to `fromDir`. This is what
    // user modules see as their local `require` — `./sibling` resolves
    // relative to `fromDir`, bare names resolve via stdlib then
    // `fromDir`-rooted `node_modules` walk.
    function makeRequire(fromDir) {
        function resolveOnly(name) {
            if (typeof name !== 'string') {
                throw new TypeError('require.resolve(name) expects a string');
            }
            var stripped = stripNodePrefix(name);
            // Pre-registered modules return their registration name
            // as the "resolved identifier" — no path materializes.
            if (factories[stripped] || cache[stripped] !== undefined) {
                return stripped;
            }
            if (isRelativeOrAbsolute(name)) {
                var base = name.charAt(0) === '/' ? name : resolveJoin(fromDir, name);
                var r = resolveCandidate(base);
                if (!r) throw moduleNotFound(name, base);
                return r;
            }
            var pkg = resolvePackage(name, fromDir);
            if (pkg) return pkg;
            throw moduleNotFound(name, null);
        }

        function req(name) {
            if (typeof name !== 'string') {
                throw new TypeError('require(name) expects a string');
            }
            // Pre-registered modules always win, regardless of name
            // shape. This matters for programmatic registration (e.g.
            // FlowEngine::load_bundle) that uses literal names like
            // './util' to key helper modules into the factory map —
            // those should short-circuit the filesystem lookup.
            var preregistered = loadStdlib(stripNodePrefix(name));
            if (preregistered !== undefined) return preregistered;

            // Subpath imports (`#name`) — Node looks up the closest
            // package.json's `imports` field and resolves the matched
            // entry relative to that package root. ESM-only npm
            // packages (chalk, ora) ship internal deps like
            // `#ansi-styles` via this mechanism.
            if (name.charAt(0) === '#') {
                var resolvedSubpath = resolveSubpathImport(name, fromDir);
                if (resolvedSubpath) {
                    return loadAbsoluteFile(resolvedSubpath, makeRequire(dirname(resolvedSubpath)));
                }
                var eImp = new Error("Cannot find module '" + name + "'");
                eImp.code = 'ERR_PACKAGE_IMPORT_NOT_DEFINED';
                throw eImp;
            }

            if (isRelativeOrAbsolute(name)) {
                var base = name.charAt(0) === '/' ? name : resolveJoin(fromDir, name);
                var r = resolveCandidate(base);
                if (!r) throw moduleNotFound(name, base);
                return loadAbsoluteFile(r, makeRequire(dirname(r)));
            }
            // Linked dependency packages (__afb_links): a composed
            // .afb maps each digest-pinned dependency coordinate to
            // that dependency's entry inside the virtual tree. Exact
            // names only — the dep's entry IS its API surface.
            var links = globalThis.__afb_links;
            if (links && typeof links === 'object' && typeof links[name] === 'string') {
                var linked = links[name];
                return loadAbsoluteFile(linked, makeRequire(dirname(linked)));
            }
            // Bare name — fall through to `node_modules` walk.
            var pkg = resolvePackage(name, fromDir);
            if (pkg) return loadAbsoluteFile(pkg, makeRequire(dirname(pkg)));
            throw moduleNotFound(name, null);
        }

        req.cache = cache;
        req.resolve = resolveOnly;
        return req;
    }

    function entryDir() {
        // For file-mode invocations (`burn run foo.js`), argv[1] is
        // the canonicalized absolute script path — its dirname is the
        // entry module's `__dirname`, matching Node's semantics where
        // `require('./sibling')` in the entry script resolves next to
        // the entry file, NOT next to the shell's cwd.
        var argv = globalThis.__ab_argv;
        if (argv && typeof argv[1] === 'string') {
            var label = argv[1];
            if (label.length > 0 && label.charAt(0) === '/'
                && label !== '[eval]' && label !== '[test]') {
                return dirname(label);
            }
        }
        // Eval mode (`-e CODE`, argv[1] = '[eval]') has no file of
        // its own, so we fall back to the shell's cwd — matches what
        // the user would expect when they type `burn -e 'require("./x")'`
        // in a project dir.
        var cwd = globalThis.__host_cwd;
        if (typeof cwd === 'string' && cwd.length > 0) return cwd;
        return '/';
    }

    // The entry-point require. Re-computed on each access so per-
    // invocation `__host_cwd` / `__ab_argv` updates are picked up
    // without a global reset.
    function installEntryRequire() {
        var req = makeRequire(entryDir());
        // Expose the factory-map registration helpers on the entry
        // require for debugging / tests.
        req.__plenum_modules_installed = function() {
            return Object.keys(factories).concat(Object.keys(cache));
        };
        // Node's `require.main` — descriptor for the script that
        // launched the process. For `burn run foo.js` it points at
        // foo.js; for `-e` and stdin modes it points at the
        // synthetic [eval] entry. The fields match Node's
        // Module-instance shape (id, filename, exports, paths,
        // children) closely enough for the canonical idiom
        // `require.main === module` to work in burn.
        var argv = globalThis.__ab_argv;
        var entry = (argv && typeof argv[1] === 'string') ? argv[1] : '[eval]';
        req.main = {
            id: entry,
            filename: entry,
            exports: {},
            loaded: false,
            paths: [entryDir()],
            children: [],
        };
        globalThis.require = req;
    }

    installEntryRequire();

    globalThis.__register_module = function(name, factory) {
        factories[stripNodePrefix(name)] = factory;
    };

    globalThis.__register_host_module = function(name, obj) {
        cache[stripNodePrefix(name)] = obj;
    };

    globalThis.__plenum_modules_installed = function() {
        return Object.keys(factories).concat(Object.keys(cache));
    };

    // Per-invocation hook: when the host updates `__host_cwd` via the
    // script envelope, the entry-point `require` should rebase its
    // starting dir. Called from the plugin's script/daemon-init
    // wrappers immediately after they set `__host_cwd`.
    globalThis.__plenum_refresh_entry_require = installEntryRequire;

    // File-relative require for `module.createRequire(filename)`:
    // resolve `id` exactly as a module living at `base` would —
    // relative specifiers and the node_modules walk start at
    // dirname(base), not at the entry script's dir.
    globalThis.__plenum_require_from = function(id, base) {
        return makeRequire(dirname(String(base)))(id);
    };

    // Dynamic-import shim. QuickJS has no registered module loader,
    // so bare `import('foo')` throws "could not load module" the
    // moment it runs — that breaks every npm-side dispatcher (npm
    // imports `chalk` / `supports-color`; corepack imports the proxy
    // agent; pnpm imports its own engine). At source-rewrite time
    // we replace `import(` with `globalThis.__ab_dyn_import(`; this
    // function returns a Promise resolving to the module's
    // namespace-shaped object, matching Node's CJS-from-ESM interop:
    // CJS modules whose `module.exports` is an object are returned
    // as-is; anything else is wrapped under `default`.
    globalThis.__ab_dyn_import = function(reqOrSpec, maybeSpec) {
        // Two-arg shape: rewriter passes `(require, spec)` so the
        // import resolves relative to the importing file's dir.
        // One-arg shape: entry-script eval / CLI code that's outside
        // a CJS wrapper — fall back to the entry require.
        var r;
        var spec;
        if (typeof maybeSpec !== 'undefined' && typeof reqOrSpec === 'function') {
            r = reqOrSpec;
            spec = maybeSpec;
        } else {
            r = globalThis.require;
            spec = reqOrSpec;
        }
        try {
            var mod = r(spec);
            // Already namespace-shaped (ESM-lowered files include
            // `__esModule: true` + named keys, plus `default`).
            if (mod && typeof mod === 'object' && mod.__esModule) {
                return Promise.resolve(mod);
            }
            // CJS fallback: synthesise a namespace with `default` set
            // to the require result. Spread the object's enumerable
            // keys so `import('cjs').namedExport` still works when
            // the CJS module exports a plain object.
            var ns = { default: mod };
            if (mod && typeof mod === 'object') {
                for (var k in mod) {
                    if (k === 'default') continue;
                    ns[k] = mod[k];
                }
            }
            return Promise.resolve(ns);
        } catch (e) {
            return Promise.reject(e);
        }
    };
})();

// ---- abort.js ----
// AbortController + AbortSignal — standard Web API, not built into
// QuickJS. Supports the listener-based cancellation protocol used by
// `fetch`, timers, and most async libraries.

(function installAbort() {
    if (typeof globalThis.AbortController === 'function') return;

    function AbortSignal() {
        this.aborted = false;
        this.reason = undefined;
        this._listeners = [];
    }
    AbortSignal.prototype.addEventListener = function(event, fn) {
        if (event !== 'abort' || typeof fn !== 'function') return;
        this._listeners.push(fn);
    };
    AbortSignal.prototype.removeEventListener = function(event, fn) {
        if (event !== 'abort') return;
        var i = this._listeners.indexOf(fn);
        if (i >= 0) this._listeners.splice(i, 1);
    };
    AbortSignal.prototype.throwIfAborted = function() {
        if (this.aborted) throw this.reason;
    };
    Object.defineProperty(AbortSignal.prototype, 'onabort', {
        get: function() { return this._onabort || null; },
        set: function(fn) {
            if (this._onabort) this.removeEventListener('abort', this._onabort);
            this._onabort = fn;
            if (typeof fn === 'function') this.addEventListener('abort', fn);
        }
    });
    AbortSignal.abort = function(reason) {
        var s = new AbortSignal();
        s.aborted = true;
        s.reason = reason !== undefined ? reason : new Error('Aborted');
        return s;
    };
    AbortSignal.timeout = function(ms) {
        ms = (ms | 0);
        // Daemon mode (host timers available) — schedule a real fire-
        // later abort so callers get the canonical pattern:
        //   fetch(url, { signal: AbortSignal.timeout(5000) })
        // works as expected. setTimeout itself routes through the same
        // host import, so this stays consistent with the rest of the
        // event-loop polyfill.
        if (typeof globalThis.setTimeout === 'function'
            && typeof globalThis.__host_timer_set === 'function') {
            var s = new AbortSignal();
            globalThis.setTimeout(function() {
                if (s.aborted) return;
                s.aborted = true;
                s.reason = new Error('signal timed out (' + ms + 'ms)');
                var listeners = s._listeners.slice();
                for (var i = 0; i < listeners.length; i++) {
                    try { listeners[i]({ type: 'abort' }); } catch (_) {}
                }
            }, ms);
            return s;
        }
        // Library mode (no host timers): a timeout-based abort would
        // never fire. Produce a signal that's already aborted so
        // scripts fail loudly rather than silently hang.
        return AbortSignal.abort(new Error('AbortSignal.timeout: no event loop'));
    };

    // AbortSignal.any (Node 20+) — return a fresh signal that aborts
    // as soon as ANY of the input signals aborts. If any input signal
    // is already aborted at construction time the returned signal
    // is born aborted with that reason.
    AbortSignal.any = function(signals) {
        var arr = Array.from(signals || []);
        var s = new AbortSignal();
        for (var i = 0; i < arr.length; i++) {
            var sig = arr[i];
            if (sig && sig.aborted) {
                s.aborted = true;
                s.reason = sig.reason !== undefined ? sig.reason : new Error('Aborted');
                return s;
            }
        }
        var fired = false;
        function fire(reason) {
            if (fired || s.aborted) return;
            fired = true;
            s.aborted = true;
            s.reason = reason !== undefined ? reason : new Error('Aborted');
            var listeners = s._listeners.slice();
            for (var j = 0; j < listeners.length; j++) {
                try { listeners[j]({ type: 'abort' }); } catch (_) {}
            }
        }
        for (var k = 0; k < arr.length; k++) {
            (function(child) {
                if (!child || typeof child.addEventListener !== 'function') return;
                child.addEventListener('abort', function() { fire(child.reason); }, { once: true });
            })(arr[k]);
        }
        return s;
    };

    function AbortController() {
        this.signal = new AbortSignal();
    }
    AbortController.prototype.abort = function(reason) {
        if (this.signal.aborted) return;
        this.signal.aborted = true;
        this.signal.reason = reason !== undefined ? reason : new Error('Aborted');
        var listeners = this.signal._listeners.slice();
        for (var i = 0; i < listeners.length; i++) {
            try { listeners[i]({ type: 'abort' }); } catch (_) {}
        }
    };

    globalThis.AbortController = AbortController;
    globalThis.AbortSignal = AbortSignal;
})();

// ---- assert.js ----
// assert — subset. Deep-equality is structural; follows the Node.js
// "strict" semantics (=== for primitives, shape-recursive for objects).

__register_module('assert', function(module, exports, require) {

    function AssertionError(opts) {
        var message = opts && opts.message;
        if (!message) {
            var act = safeStringify(opts && opts.actual);
            var exp = safeStringify(opts && opts.expected);
            var op  = (opts && opts.operator) || 'fail';
            message = act + ' ' + op + ' ' + exp;
        }
        var err = new Error(message);
        err.name = 'AssertionError';
        err.actual = opts && opts.actual;
        err.expected = opts && opts.expected;
        err.operator = opts && opts.operator;
        err.generatedMessage = !(opts && opts.message);
        err.code = 'ERR_ASSERTION';
        return err;
    }

    function safeStringify(v) {
        try { return JSON.stringify(v); } catch (_) { return String(v); }
    }

    function deepEqual(a, b, strict) {
        if (strict ? a === b : a == b) return true;
        if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {
            return false;
        }
        if (Array.isArray(a) !== Array.isArray(b)) return false;
        var ka = Object.keys(a);
        var kb = Object.keys(b);
        if (ka.length !== kb.length) return false;
        for (var i = 0; i < ka.length; i++) {
            var k = ka[i];
            if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
            if (!deepEqual(a[k], b[k], strict)) return false;
        }
        return true;
    }

    function assertFn(value, message) {
        if (!value) throw AssertionError({ actual: value, expected: true, operator: '==', message: message });
    }

    assertFn.ok = assertFn;
    assertFn.fail = function(message) {
        throw AssertionError({ message: message || 'Failed' });
    };
    assertFn.equal = function(a, e, m) {
        if (a != e) throw AssertionError({ actual: a, expected: e, operator: '==', message: m });
    };
    assertFn.notEqual = function(a, e, m) {
        if (a == e) throw AssertionError({ actual: a, expected: e, operator: '!=', message: m });
    };
    assertFn.strictEqual = function(a, e, m) {
        if (a !== e) throw AssertionError({ actual: a, expected: e, operator: '===', message: m });
    };
    assertFn.notStrictEqual = function(a, e, m) {
        if (a === e) throw AssertionError({ actual: a, expected: e, operator: '!==', message: m });
    };
    assertFn.deepEqual = function(a, e, m) {
        if (!deepEqual(a, e, false)) throw AssertionError({ actual: a, expected: e, operator: 'deepEqual', message: m });
    };
    assertFn.deepStrictEqual = function(a, e, m) {
        if (!deepEqual(a, e, true)) throw AssertionError({ actual: a, expected: e, operator: 'deepStrictEqual', message: m });
    };
    assertFn.throws = function(fn, expected, message) {
        var threw = false;
        var err;
        try { fn(); } catch (e) { threw = true; err = e; }
        if (!threw) throw AssertionError({ message: message || 'Expected function to throw' });
        if (expected instanceof RegExp && !expected.test(String(err))) {
            throw AssertionError({ actual: err, expected: expected, operator: 'throws', message: message });
        }
    };
    assertFn.doesNotThrow = function(fn, message) {
        try { fn(); } catch (e) {
            throw AssertionError({ actual: e, operator: 'doesNotThrow', message: message || 'Unexpected throw' });
        }
    };
    assertFn.AssertionError = AssertionError;
    assertFn.strict = assertFn;

    module.exports = assertFn;
});

// ---- async_hooks.js ----
// async_hooks — Node 20's async-tracking + AsyncLocalStorage API.
//
// Real hook firing: `createHook({init, before, after, destroy,
// promiseResolve}).enable()` causes every subsequent async resource
// (timer, microtask, AsyncResource subclass, then/finally/catch
// handler) to fire the registered callbacks at the matching point
// in its lifecycle.
//
// Wire-up:
//
// * **AsyncResource** — `new AsyncResource(type)` fires `init`;
//   `runInAsyncScope(fn, this, ...args)` pushes the asyncId,
//   fires `before`, runs `fn`, fires `after`, pops.
//   `emitDestroy()` fires `destroy`.
// * **Promise.prototype.then/catch/finally** — wrapped at module
//   load to register a synthetic `PROMISE` resource for each
//   handler. The handler runs inside `runInAsyncScope`. `then`
//   also fires `promiseResolve` when the producing promise
//   settles.
// * **AsyncLocalStorage** — store stack snapshots at the point
//   where a handler is queued, restored at run time. With Promise
//   hooks live, this propagates through `await` boundaries
//   without a per-call user wrapper.
//
// `executionAsyncId()` / `triggerAsyncId()` reflect the live
// asyncId stack so logging libraries can correlate work units.

// Install `__ab_await_track` eagerly (outside the `__register_module`
// factory) so user code's `await EXPR` rewrites resolve from line 1.
// The factory body still re-installs idempotently — same shape — so
// `require('async_hooks')` doesn't undo this.
if (typeof globalThis.__ab_await_track !== 'function') {
    Object.defineProperty(globalThis, '__ab_await_track', {
        value: function(value) {
            return Promise.resolve(value).then(function(v) { return v; });
        },
        writable: true, configurable: true,
    });
}

__register_module('async_hooks', function(module, exports, require) {

    // ---- async-id stack + hook registry --------------------------

    var _asyncIdCounter = 1;
    function nextAsyncId() { return ++_asyncIdCounter; }

    // Stack frames are [{asyncId, triggerAsyncId}, ...]. Top is the
    // currently-executing scope. Bottom is the synthetic root.
    var _stack = [{ asyncId: 1, triggerAsyncId: 0 }];

    function _peek() { return _stack[_stack.length - 1]; }
    function _push(asyncId, triggerAsyncId) {
        _stack.push({ asyncId: asyncId, triggerAsyncId: triggerAsyncId });
    }
    function _pop() {
        if (_stack.length > 1) _stack.pop();
    }

    // Active hooks. Each entry: { init, before, after, destroy, promiseResolve, enabled }.
    var _hooks = [];
    var _hooksDirty = false;
    // We re-read enabled hooks lazily so adding/removing during a
    // fire iteration doesn't reorder the active set mid-iteration.
    var _activeCache = [];
    function _activeHooks() {
        if (_hooksDirty) {
            _activeCache = _hooks.filter(function(h) { return h.enabled; });
            _hooksDirty = false;
        }
        return _activeCache;
    }

    function _fire(name, asyncId, type, triggerAsyncId, resource) {
        var arr = _activeHooks();
        for (var i = 0; i < arr.length; i++) {
            var fn = arr[i][name];
            if (typeof fn !== 'function') continue;
            try {
                if (name === 'init') fn(asyncId, type, triggerAsyncId, resource);
                else if (name === 'promiseResolve') fn(asyncId);
                else fn(asyncId);
            } catch (e) {
                // Match Node: hook errors are reported on stderr but
                // do not abort the program. Avoiding throw here also
                // protects users that emit destroy from a destructor
                // (where throwing would leak resources).
                try { console.error('async_hooks ' + name + ' callback error:', (e && e.stack) || e); }
                catch (_) {}
            }
        }
    }

    // ---- AsyncResource -------------------------------------------

    function AsyncResource(type, options) {
        if (!(this instanceof AsyncResource)) return new AsyncResource(type, options);
        var trigger;
        if (typeof options === 'number') {
            trigger = options | 0;
        } else if (options && typeof options.triggerAsyncId === 'number') {
            trigger = options.triggerAsyncId | 0;
        } else {
            trigger = _peek().asyncId;
        }
        this._type = type || 'AsyncResource';
        this._triggerAsyncId = trigger;
        this._asyncId = nextAsyncId();
        this._destroyed = false;
        _fire('init', this._asyncId, this._type, this._triggerAsyncId, this);
    }
    AsyncResource.prototype.runInAsyncScope = function(fn, thisArg /*, ...args */) {
        var args = Array.prototype.slice.call(arguments, 2);
        _push(this._asyncId, this._triggerAsyncId);
        _fire('before', this._asyncId);
        try {
            return fn.apply(thisArg, args);
        } finally {
            _fire('after', this._asyncId);
            _pop();
        }
    };
    AsyncResource.prototype.bind = function(fn, thisArg) {
        var self = this;
        var bound = function() {
            var args = Array.prototype.slice.call(arguments);
            return self.runInAsyncScope(fn, thisArg || this, args.length === 0 ? undefined : args);
        };
        // Accept the alternate Node-22 calling convention: bind() also
        // returns a function whose direct call applies the args.
        var direct = function() {
            return self.runInAsyncScope.apply(self,
                [fn, thisArg || this].concat(Array.prototype.slice.call(arguments)));
        };
        // Use `direct` so `(asyncRes.bind(fn))(a, b)` runs `fn(a, b)`
        // under the resource's scope — this is the documented shape.
        return direct;
        // (The unused `bound` keeps closure shape for any future
        // pickle/tooling that expects two refs; not exposed.)
    };
    AsyncResource.prototype.asyncId = function() { return this._asyncId; };
    AsyncResource.prototype.triggerAsyncId = function() { return this._triggerAsyncId; };
    AsyncResource.prototype.emitDestroy = function() {
        if (!this._destroyed) {
            this._destroyed = true;
            _fire('destroy', this._asyncId);
        }
        return this;
    };
    AsyncResource.bind = function(fn, type, thisArg) {
        var r = new AsyncResource(type || 'AsyncResource');
        return r.bind(fn, thisArg);
    };

    // ---- AsyncLocalStorage --------------------------------------
    //
    // Store stack tracks the live "current store" per ALS instance.
    // Promise / timer / AsyncResource handlers capture the per-ALS
    // top-of-stack at queue time and restore on run, so the store
    // visible inside an `await` matches the store visible at the
    // statement that produced the awaited promise.

    function AsyncLocalStorage() {
        this._stack = [];
        this._enabled = true;
    }
    AsyncLocalStorage.prototype.run = function(store, callback) {
        if (typeof callback !== 'function') {
            throw new TypeError('AsyncLocalStorage.run: callback must be a function');
        }
        this._stack.push(store);
        try {
            return callback.apply(null, Array.prototype.slice.call(arguments, 2));
        } finally {
            this._stack.pop();
        }
    };
    AsyncLocalStorage.prototype.exit = function(callback) {
        if (typeof callback !== 'function') {
            throw new TypeError('AsyncLocalStorage.exit: callback must be a function');
        }
        this._stack.push(undefined);
        try {
            return callback.apply(null, Array.prototype.slice.call(arguments, 1));
        } finally {
            this._stack.pop();
        }
    };
    AsyncLocalStorage.prototype.getStore = function() {
        if (!this._enabled) return undefined;
        return this._stack.length === 0 ? undefined : this._stack[this._stack.length - 1];
    };
    AsyncLocalStorage.prototype.enterWith = function(store) {
        if (this._stack.length === 0) this._stack.push(store);
        else this._stack[this._stack.length - 1] = store;
    };
    AsyncLocalStorage.prototype.disable = function() {
        this._stack = [];
        this._enabled = false;
    };
    // Snapshot the entire ALS-store world so async boundaries can
    // restore each registered ALS to what it was at queue time.
    function _snapshotALS() {
        var snap = [];
        for (var i = 0; i < _alsRegistry.length; i++) {
            var als = _alsRegistry[i];
            var top = als._stack.length === 0 ? undefined : als._stack[als._stack.length - 1];
            snap.push({ als: als, value: top });
        }
        return snap;
    }
    function _enterSnapshot(snap) {
        for (var i = 0; i < snap.length; i++) {
            snap[i].als._stack.push(snap[i].value);
        }
    }
    function _exitSnapshot(snap) {
        for (var i = 0; i < snap.length; i++) {
            snap[i].als._stack.pop();
        }
    }
    var _alsRegistry = [];
    var _OrigALS = AsyncLocalStorage;
    AsyncLocalStorage = function() {
        var inst = new _OrigALS();
        _alsRegistry.push(inst);
        return inst;
    };
    AsyncLocalStorage.prototype = _OrigALS.prototype;
    AsyncLocalStorage.bind = function(fn) {
        var snap = _snapshotALS();
        return function() {
            _enterSnapshot(snap);
            try { return fn.apply(this, arguments); }
            finally { _exitSnapshot(snap); }
        };
    };
    AsyncLocalStorage.snapshot = function() {
        var snap = _snapshotALS();
        return function(cb) {
            var args = Array.prototype.slice.call(arguments, 1);
            _enterSnapshot(snap);
            try { return cb.apply(null, args); }
            finally { _exitSnapshot(snap); }
        };
    };

    // ---- createHook ---------------------------------------------

    function createHook(callbacks) {
        callbacks = callbacks || {};
        var entry = {
            init: typeof callbacks.init === 'function' ? callbacks.init : null,
            before: typeof callbacks.before === 'function' ? callbacks.before : null,
            after: typeof callbacks.after === 'function' ? callbacks.after : null,
            destroy: typeof callbacks.destroy === 'function' ? callbacks.destroy : null,
            promiseResolve: typeof callbacks.promiseResolve === 'function'
                ? callbacks.promiseResolve : null,
            enabled: false,
        };
        _hooks.push(entry);
        return {
            enable: function() {
                entry.enabled = true;
                _hooksDirty = true;
                return this;
            },
            disable: function() {
                entry.enabled = false;
                _hooksDirty = true;
                return this;
            },
        };
    }

    function executionAsyncId() { return _peek().asyncId; }
    function triggerAsyncId() { return _peek().triggerAsyncId; }
    function executionAsyncResource() { return Object.create(null); }

    // ---- Promise hooks ------------------------------------------
    //
    // Patch Promise.prototype.{then,catch,finally} so each handler
    // runs inside an AsyncResource('PROMISE'). The init hook fires
    // when the user attaches the handler; before/after fire around
    // the handler's invocation; promiseResolve fires when the
    // producing promise settles. Destroy fires after the handler
    // completes (Node fires it lazily; we fire eagerly because
    // microtask cleanup is bounded).
    //
    // The patch is one-shot — applied at module load — so all
    // promises minted in this realm carry the wrapped handlers.
    // Native promises produced by host code (e.g. fetch's body
    // reader) inherit the same prototype, so they also get tracked.

    var _origThen = Promise.prototype.then;
    var _origCatch = Promise.prototype.catch;
    var _origFinally = Promise.prototype.finally;

    function _wrapHandler(fn, type) {
        if (typeof fn !== 'function') return fn;
        var resource = new AsyncResource(type || 'PROMISE');
        var alsSnap = _snapshotALS();
        var wrapped = function(value) {
            _enterSnapshot(alsSnap);
            try {
                return resource.runInAsyncScope(fn, undefined, value);
            } finally {
                _exitSnapshot(alsSnap);
                resource.emitDestroy();
            }
        };
        wrapped._ah_resource = resource;
        return wrapped;
    }

    Promise.prototype.then = function(onFulfilled, onRejected) {
        var wrappedF = _wrapHandler(onFulfilled, 'PROMISE');
        var wrappedR = _wrapHandler(onRejected, 'PROMISE');
        var p = _origThen.call(this, wrappedF, wrappedR);
        // Fire promiseResolve when this producing promise settles.
        // We chain a sentinel handler that doesn't add semantic
        // surface but observes settlement.
        var producerId = (wrappedF && wrappedF._ah_resource && wrappedF._ah_resource._asyncId)
            || (wrappedR && wrappedR._ah_resource && wrappedR._ah_resource._asyncId);
        if (producerId !== undefined) {
            _origThen.call(this, function() { _fire('promiseResolve', producerId); },
                function() { _fire('promiseResolve', producerId); });
        }
        return p;
    };

    Promise.prototype.catch = function(onRejected) {
        return this.then(undefined, onRejected);
    };

    Promise.prototype.finally = function(onFinally) {
        if (typeof onFinally !== 'function') {
            return _origFinally.call(this, onFinally);
        }
        var wrapped = _wrapHandler(onFinally, 'PROMISE');
        return _origFinally.call(this, wrapped);
    };

    // ---- Timer hooks --------------------------------------------
    //
    // Wrap the global setTimeout/setInterval/setImmediate so the
    // callback runs inside an AsyncResource('Timeout'/'Immediate').
    // The host's timer plumbing isn't aware of asyncId, but the
    // surface the user observes (executionAsyncId during the
    // callback) reflects the right id.

    var _origSetTimeout = globalThis.setTimeout;
    var _origSetInterval = globalThis.setInterval;
    var _origSetImmediate = globalThis.setImmediate;

    if (typeof _origSetTimeout === 'function') {
        globalThis.setTimeout = function(fn /*, ms, ...args */) {
            if (typeof fn !== 'function') return _origSetTimeout.apply(this, arguments);
            var rest = Array.prototype.slice.call(arguments, 1);
            var resource = new AsyncResource('Timeout');
            var alsSnap = _snapshotALS();
            var wrapped = function() {
                _enterSnapshot(alsSnap);
                try {
                    return resource.runInAsyncScope.apply(resource,
                        [fn, undefined].concat(Array.prototype.slice.call(arguments)));
                } finally {
                    _exitSnapshot(alsSnap);
                    resource.emitDestroy();
                }
            };
            return _origSetTimeout.apply(this, [wrapped].concat(rest));
        };
    }
    if (typeof _origSetInterval === 'function') {
        globalThis.setInterval = function(fn /*, ms, ...args */) {
            if (typeof fn !== 'function') return _origSetInterval.apply(this, arguments);
            var rest = Array.prototype.slice.call(arguments, 1);
            var resource = new AsyncResource('Timeout');
            var alsSnap = _snapshotALS();
            var wrapped = function() {
                _enterSnapshot(alsSnap);
                try {
                    return resource.runInAsyncScope.apply(resource,
                        [fn, undefined].concat(Array.prototype.slice.call(arguments)));
                } finally {
                    _exitSnapshot(alsSnap);
                }
            };
            return _origSetInterval.apply(this, [wrapped].concat(rest));
        };
    }
    if (typeof _origSetImmediate === 'function') {
        globalThis.setImmediate = function(fn /*, ...args */) {
            if (typeof fn !== 'function') return _origSetImmediate.apply(this, arguments);
            var rest = Array.prototype.slice.call(arguments, 1);
            var resource = new AsyncResource('Immediate');
            var alsSnap = _snapshotALS();
            var wrapped = function() {
                _enterSnapshot(alsSnap);
                try {
                    return resource.runInAsyncScope.apply(resource,
                        [fn, undefined].concat(Array.prototype.slice.call(arguments)));
                } finally {
                    _exitSnapshot(alsSnap);
                    resource.emitDestroy();
                }
            };
            return _origSetImmediate.apply(this, [wrapped].concat(rest));
        };
    }

    // ---- queueMicrotask hook ------------------------------------
    var _origQueueMicrotask = globalThis.queueMicrotask;
    if (typeof _origQueueMicrotask === 'function') {
        globalThis.queueMicrotask = function(fn) {
            if (typeof fn !== 'function') return _origQueueMicrotask.call(this, fn);
            var resource = new AsyncResource('Microtask');
            var alsSnap = _snapshotALS();
            var wrapped = function() {
                _enterSnapshot(alsSnap);
                try {
                    return resource.runInAsyncScope(fn);
                } finally {
                    _exitSnapshot(alsSnap);
                    resource.emitDestroy();
                }
            };
            return _origQueueMicrotask.call(this, wrapped);
        };
    }

    // ---- await tracking ------------------------------------------
    //
    // The ESM transpiler wraps every `await EXPR` as
    // `await __ab_await_track(EXPR)`. This routes the awaited value
    // through our patched `Promise.prototype.then` (an internal
    // engine `await` otherwise bypasses user-level `.then`), so the
    // PROMISE AsyncResource fires init/before/after for every await
    // and AsyncLocalStorage snapshots restore at handler-fire time
    // for the duration of `.then`'s wrapped continuation.
    if (typeof globalThis.__ab_await_track !== 'function') {
        Object.defineProperty(globalThis, '__ab_await_track', {
            value: function(value) {
                // Promise.resolve gives a Promise even if `value` was
                // a bare value; the `.then(v => v)` is the hook anchor
                // that triggers the patched prototype handler.
                return Promise.resolve(value).then(function(v) { return v; });
            },
            writable: true, configurable: true,
        });
    }

    // ---- exports -------------------------------------------------

    exports.AsyncLocalStorage = AsyncLocalStorage;
    exports.AsyncResource = AsyncResource;
    exports.createHook = createHook;
    exports.executionAsyncId = executionAsyncId;
    exports.triggerAsyncId = triggerAsyncId;
    exports.executionAsyncResource = executionAsyncResource;
    exports.asyncWrapProviders = {
        NONE: 0,
        DIRHANDLE: 1,
        FILEHANDLE: 2,
        TCPWRAP: 3,
        TIMERWRAP: 4,
    };
});

// ---- buffer.js ----
// buffer — a `Buffer` class backed by `Uint8Array`, covering the
// slice of the API that scripts normally touch. UCS-2 / UTF-16 are
// intentionally omitted — callers who need them can fall back to
// TextDecoder directly.

__register_module('buffer', function(module, exports, require) {

    // ---- encoding helpers -------------------------------------------------

    var HEX = '0123456789abcdef';

    function utf8Encode(str) {
        // QuickJS exposes TextEncoder globally; prefer it when available.
        if (typeof TextEncoder === 'function') {
            return new TextEncoder().encode(str);
        }
        // Fallback — correct for BMP, good enough for ASCII-heavy payloads.
        var out = [];
        for (var i = 0; i < str.length; i++) {
            var c = str.charCodeAt(i);
            if (c < 0x80)       out.push(c);
            else if (c < 0x800) out.push(0xC0 | (c >> 6), 0x80 | (c & 0x3F));
            else                out.push(0xE0 | (c >> 12), 0x80 | ((c >> 6) & 0x3F), 0x80 | (c & 0x3F));
        }
        return new Uint8Array(out);
    }

    function utf8Decode(bytes) {
        if (typeof TextDecoder === 'function') {
            return new TextDecoder('utf-8').decode(bytes);
        }
        var out = '';
        for (var i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]);
        return out;
    }

    function hexEncode(bytes) {
        var out = '';
        for (var i = 0; i < bytes.length; i++) {
            var b = bytes[i];
            out += HEX[(b >> 4) & 0x0F] + HEX[b & 0x0F];
        }
        return out;
    }

    function hexDecode(str) {
        str = String(str);
        if (str.length % 2) str = str.slice(0, str.length - 1);
        var bytes = new Uint8Array(str.length / 2);
        for (var i = 0; i < bytes.length; i++) {
            bytes[i] = parseInt(str.substr(i * 2, 2), 16) & 0xFF;
        }
        return bytes;
    }

    var B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    var B64_INV = (function() {
        var a = new Int8Array(256).fill(-1);
        for (var i = 0; i < 64; i++) a[B64.charCodeAt(i)] = i;
        a['='.charCodeAt(0)] = 0;
        return a;
    })();

    // Host-native base64 bridges (raw-byte framing). Present whenever
    // the runtime installs the codec globals; the interpreter-side
    // implementations below stay as the fallback for other embeddings
    // and for inputs the host's stricter decoder rejects.
    var hostB64Encode = typeof __host_b64_encode === 'function' ? __host_b64_encode : null;
    var hostB64Decode = typeof __host_b64_decode === 'function' ? __host_b64_decode : null;

    function b64Encode(bytes) {
        if (hostB64Encode && bytes.length > 0) {
            try { return hostB64Encode(bytes); } catch (_) { /* fall back */ }
        }
        return b64EncodeJs(bytes);
    }

    function b64Decode(str) {
        str = String(str);
        if (hostB64Decode) {
            // First attempt: the raw input. Covers canonical payloads
            // (padded or not) without an O(n) sanitize pass.
            try { return hostB64Decode(str); } catch (_) { /* sanitize */ }
            // Second attempt: strip characters outside the standard
            // alphabet (whitespace, line breaks, data-URL noise) the
            // same way the interpreter path does, then retry.
            var clean = str.replace(/[^A-Za-z0-9+/=]/g, '');
            try { return hostB64Decode(clean); } catch (_) { /* fall back */ }
        }
        return b64DecodeJs(str);
    }

    function b64EncodeJs(bytes) {
        // Bulk-encode by chunk into an array, join once at the end.
        // QuickJS's `+=` string concat creates a fresh string per
        // step which goes quadratic on multi-KB inputs (50 KB took
        // ~800ms; 315 KB hung). Joining a small array of pre-
        // encoded segments collapses that to ~one alloc per chunk.
        // Chunk size 768 bytes = 1024 base64 chars per segment;
        // picked to keep the temporary char arrays cache-friendly
        // while bounding the array overhead.
        var n = bytes.length;
        if (n === 0) return '';
        var chunks = [];
        var i = 0;
        var CHUNK = 768;
        for (; i + CHUNK <= n; i += CHUNK) {
            var seg = '';
            for (var j = i; j < i + CHUNK; j += 3) {
                var v = (bytes[j] << 16) | (bytes[j+1] << 8) | bytes[j+2];
                seg += B64[(v >> 18) & 63] + B64[(v >> 12) & 63] + B64[(v >> 6) & 63] + B64[v & 63];
            }
            chunks.push(seg);
        }
        var tail = '';
        for (; i + 3 <= n; i += 3) {
            var v2 = (bytes[i] << 16) | (bytes[i+1] << 8) | bytes[i+2];
            tail += B64[(v2 >> 18) & 63] + B64[(v2 >> 12) & 63] + B64[(v2 >> 6) & 63] + B64[v2 & 63];
        }
        var rem = n - i;
        if (rem === 1) {
            var n1 = bytes[i] << 16;
            tail += B64[(n1 >> 18) & 63] + B64[(n1 >> 12) & 63] + '==';
        } else if (rem === 2) {
            var n2 = (bytes[i] << 16) | (bytes[i+1] << 8);
            tail += B64[(n2 >> 18) & 63] + B64[(n2 >> 12) & 63] + B64[(n2 >> 6) & 63] + '=';
        }
        if (tail) chunks.push(tail);
        return chunks.join('');
    }

    function b64DecodeJs(str) {
        str = String(str).replace(/[^A-Za-z0-9+/=]/g, '');
        var pad = 0;
        if (str.charAt(str.length - 1) === '=') pad++;
        if (str.charAt(str.length - 2) === '=') pad++;
        var out = new Uint8Array(Math.floor(str.length * 3 / 4) - pad);
        var o = 0;
        for (var i = 0; i < str.length; i += 4) {
            var n = (B64_INV[str.charCodeAt(i)]   << 18) |
                    (B64_INV[str.charCodeAt(i+1)] << 12) |
                    (B64_INV[str.charCodeAt(i+2)] << 6)  |
                    (B64_INV[str.charCodeAt(i+3)]);
            if (o < out.length) out[o++] = (n >> 16) & 0xFF;
            if (o < out.length) out[o++] = (n >> 8) & 0xFF;
            if (o < out.length) out[o++] = n & 0xFF;
        }
        return out;
    }

    // ---- Buffer class -----------------------------------------------------

    function Buffer(arg, encodingOrLength) {
        if (typeof arg === 'number') {
            var u = new Uint8Array(arg);
            makeBuffer(u);
            return u;
        }
        if (typeof arg === 'string') return Buffer.from(arg, encodingOrLength);
        if (arg instanceof Uint8Array) {
            makeBuffer(arg);
            return arg;
        }
        if (Array.isArray(arg)) return Buffer.from(arg);
        throw new TypeError('unsupported Buffer argument');
    }

    function makeBuffer(u8) {
        u8.__isBuffer = true;
        u8.toString = function(encoding, start, end) {
            encoding = (encoding || 'utf8').toLowerCase();
            var slice = (start !== undefined || end !== undefined) ? u8.subarray(start || 0, end) : u8;
            if (encoding === 'utf8' || encoding === 'utf-8') return utf8Decode(slice);
            if (encoding === 'hex')                          return hexEncode(slice);
            if (encoding === 'base64')                       return b64Encode(slice);
            if (encoding === 'ascii' || encoding === 'binary' || encoding === 'latin1') {
                var s = '';
                for (var i = 0; i < slice.length; i++) s += String.fromCharCode(slice[i]);
                return s;
            }
            throw new Error('Unknown encoding: ' + encoding);
        };
        u8.slice = function(start, end) {
            var s = Uint8Array.prototype.subarray.call(u8, start, end);
            makeBuffer(s);
            return s;
        };
        // `subarray` MUST return a Buffer (not a bare Uint8Array) so the
        // returned view still has Buffer methods — most importantly
        // `toString(encoding)`. Node's `Buffer.subarray` returns a
        // Buffer; without this override `buf.subarray(a,b).toString('utf8')`
        // falls back to TypedArray's comma-joined `toString` and yields
        // "104,105,…" instead of the decoded text. The `tar` package
        // decodes every header field via `subarray().toString('utf8')`,
        // so the bare-Uint8Array form made every checksum/path parse
        // garbage and broke `npm install` tarball extraction.
        u8.subarray = function(start, end) {
            var s = Uint8Array.prototype.subarray.call(u8, start, end);
            makeBuffer(s);
            return s;
        };
        u8.equals = function(other) {
            if (!other || other.length !== u8.length) return false;
            for (var i = 0; i < u8.length; i++) if (u8[i] !== other[i]) return false;
            return true;
        };
        u8.compare = function(other, targetStart, targetEnd, sourceStart, sourceEnd) {
            var a = u8.subarray(sourceStart || 0, sourceEnd !== undefined ? sourceEnd : u8.length);
            var b = other.subarray(targetStart || 0, targetEnd !== undefined ? targetEnd : other.length);
            var len = Math.min(a.length, b.length);
            for (var i = 0; i < len; i++) {
                if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
            }
            return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
        };
        u8.indexOf = function(value, byteOffset, encoding) {
            var needle;
            if (typeof value === 'number') {
                for (var i = byteOffset || 0; i < u8.length; i++) if (u8[i] === (value & 0xff)) return i;
                return -1;
            }
            if (typeof value === 'string') needle = Buffer.from(value, encoding || 'utf8');
            else if (value instanceof Uint8Array) needle = value;
            else throw new TypeError('Buffer.indexOf: unsupported value');
            outer: for (var j = byteOffset || 0; j <= u8.length - needle.length; j++) {
                for (var k = 0; k < needle.length; k++) if (u8[j + k] !== needle[k]) continue outer;
                return j;
            }
            return -1;
        };
        u8.includes = function(value, byteOffset, encoding) {
            return u8.indexOf(value, byteOffset, encoding) !== -1;
        };
        u8.copy = function(target, targetStart, sourceStart, sourceEnd) {
            targetStart = targetStart || 0;
            sourceStart = sourceStart || 0;
            sourceEnd = sourceEnd !== undefined ? sourceEnd : u8.length;
            var n = Math.min(sourceEnd - sourceStart, target.length - targetStart);
            for (var i = 0; i < n; i++) target[targetStart + i] = u8[sourceStart + i];
            return n;
        };
        u8.write = function(str, offset, length, encoding) {
            offset = offset || 0;
            if (typeof length === 'string') { encoding = length; length = undefined; }
            var bytes = Buffer.from(str, encoding || 'utf8');
            var n = Math.min(length !== undefined ? length : bytes.length, u8.length - offset);
            for (var i = 0; i < n; i++) u8[offset + i] = bytes[i];
            return n;
        };
        // Numeric readers (little-endian + big-endian, unsigned + signed).
        u8.readUInt8 = function(o) { return u8[o || 0]; };
        u8.readInt8  = function(o) { var v = u8[o || 0]; return v > 127 ? v - 256 : v; };
        u8.readUInt16LE = function(o) { o = o || 0; return u8[o] | (u8[o + 1] << 8); };
        u8.readUInt16BE = function(o) { o = o || 0; return (u8[o] << 8) | u8[o + 1]; };
        u8.readInt16LE  = function(o) { var v = u8.readUInt16LE(o); return v > 32767 ? v - 65536 : v; };
        u8.readInt16BE  = function(o) { var v = u8.readUInt16BE(o); return v > 32767 ? v - 65536 : v; };
        u8.readUInt32LE = function(o) { o = o || 0;
            return (u8[o] | (u8[o + 1] << 8) | (u8[o + 2] << 16)) + (u8[o + 3] * 0x1000000); };
        u8.readUInt32BE = function(o) { o = o || 0;
            return (u8[o] * 0x1000000) + ((u8[o + 1] << 16) | (u8[o + 2] << 8) | u8[o + 3]); };
        u8.readInt32LE  = function(o) { o = o || 0;
            return u8[o] | (u8[o + 1] << 8) | (u8[o + 2] << 16) | (u8[o + 3] << 24); };
        u8.readInt32BE  = function(o) { o = o || 0;
            return (u8[o] << 24) | (u8[o + 1] << 16) | (u8[o + 2] << 8) | u8[o + 3]; };

        u8.writeUInt8 = function(v, o) { u8[o || 0] = v & 0xff; return (o || 0) + 1; };
        u8.writeInt8  = u8.writeUInt8;
        u8.writeUInt16LE = function(v, o) { o = o || 0; u8[o] = v & 0xff; u8[o + 1] = (v >>> 8) & 0xff; return o + 2; };
        u8.writeUInt16BE = function(v, o) { o = o || 0; u8[o] = (v >>> 8) & 0xff; u8[o + 1] = v & 0xff; return o + 2; };
        u8.writeInt16LE  = u8.writeUInt16LE;
        u8.writeInt16BE  = u8.writeUInt16BE;
        u8.writeUInt32LE = function(v, o) { o = o || 0;
            u8[o] = v & 0xff; u8[o + 1] = (v >>> 8) & 0xff;
            u8[o + 2] = (v >>> 16) & 0xff; u8[o + 3] = (v >>> 24) & 0xff;
            return o + 4;
        };
        u8.writeUInt32BE = function(v, o) { o = o || 0;
            u8[o] = (v >>> 24) & 0xff; u8[o + 1] = (v >>> 16) & 0xff;
            u8[o + 2] = (v >>> 8) & 0xff; u8[o + 3] = v & 0xff;
            return o + 4;
        };
        u8.writeInt32LE = u8.writeUInt32LE;
        u8.writeInt32BE = u8.writeUInt32BE;
        return u8;
    }

    Buffer.from = function(source, encoding) {
        if (typeof source === 'string') {
            encoding = (encoding || 'utf8').toLowerCase();
            if (encoding === 'utf8' || encoding === 'utf-8') return makeBuffer(utf8Encode(source));
            if (encoding === 'hex')                          return makeBuffer(hexDecode(source));
            if (encoding === 'base64')                       return makeBuffer(b64Decode(source));
            if (encoding === 'ascii' || encoding === 'binary' || encoding === 'latin1') {
                var u = new Uint8Array(source.length);
                for (var i = 0; i < source.length; i++) u[i] = source.charCodeAt(i) & 0xFF;
                return makeBuffer(u);
            }
            throw new Error('Unknown encoding: ' + encoding);
        }
        if (source instanceof ArrayBuffer) return makeBuffer(new Uint8Array(source));
        if (source instanceof Uint8Array || Array.isArray(source)) {
            var copy = new Uint8Array(source.length);
            copy.set(source);
            return makeBuffer(copy);
        }
        throw new TypeError('Buffer.from: unsupported source');
    };

    Buffer.alloc = function(size, fill) {
        var u = new Uint8Array(size);
        if (fill !== undefined && fill !== 0) {
            var byteFill = typeof fill === 'number' ? fill : fill.charCodeAt ? fill.charCodeAt(0) : 0;
            u.fill(byteFill & 0xFF);
        }
        return makeBuffer(u);
    };

    Buffer.allocUnsafe = Buffer.alloc;
    Buffer.allocUnsafeSlow = Buffer.alloc;

    // Default pool size matches Node's 8 KiB. We don't pool slabs
    // under the hood — each `Buffer.alloc` is a fresh `Uint8Array` —
    // but expose the field so libraries that probe / write to it
    // don't trip.
    Buffer.poolSize = 8 * 1024;

    /// Buffer.copyBytesFrom(view, offset?, length?) — Node 19+.
    /// Copies bytes from a TypedArray view (Uint8Array, DataView,
    /// etc.) into a fresh Buffer. Honors offset + length in
    /// elements (NOT bytes) for non-1-byte typed arrays, matching
    /// Node's contract.
    Buffer.copyBytesFrom = function(view, offset, length) {
        if (view == null || typeof view.byteLength !== 'number') {
            throw new TypeError('Buffer.copyBytesFrom: view must be a TypedArray');
        }
        var byteOffset = view.byteOffset || 0;
        var bpe = view.BYTES_PER_ELEMENT || 1;
        offset = offset === undefined ? 0 : (offset | 0);
        length = length === undefined ? (view.length - offset) : (length | 0);
        if (offset < 0 || length < 0 || offset + length > view.length) {
            throw new RangeError('Buffer.copyBytesFrom: offset/length out of range');
        }
        var srcOffset = byteOffset + offset * bpe;
        var srcLen = length * bpe;
        var src = new Uint8Array(view.buffer, srcOffset, srcLen);
        var out = new Uint8Array(srcLen);
        out.set(src);
        return makeBuffer(out);
    };

    Buffer.concat = function(list, totalLength) {
        if (!Array.isArray(list)) throw new TypeError('list argument must be an Array');
        if (list.length === 0) return Buffer.alloc(0);
        if (totalLength === undefined) {
            totalLength = 0;
            for (var i = 0; i < list.length; i++) totalLength += list[i].length;
        }
        var out = new Uint8Array(totalLength);
        var offset = 0;
        for (var j = 0; j < list.length; j++) {
            var buf = list[j];
            var take = Math.min(buf.length, totalLength - offset);
            out.set(buf.subarray(0, take), offset);
            offset += take;
        }
        return makeBuffer(out);
    };

    Buffer.isBuffer = function(x) {
        return !!(x && x.__isBuffer === true);
    };

    Buffer.byteLength = function(str, encoding) {
        if (typeof str !== 'string') return str.length || 0;
        encoding = (encoding || 'utf8').toLowerCase();
        if (encoding === 'hex')    return Math.floor(str.length / 2);
        if (encoding === 'base64') return Math.floor(str.replace(/=/g, '').length * 3 / 4);
        return utf8Encode(str).length;
    };

    /// Buffer.compare(a, b) — static byte-wise comparator. Returns
    /// -1 / 0 / 1 like a memcmp; useful for sorted-by-bytes
    /// containers (Map keys, sorted indexes).
    Buffer.compare = function(a, b) {
        if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
            throw new TypeError('Buffer.compare: both arguments must be Buffer');
        }
        var n = Math.min(a.length, b.length);
        for (var i = 0; i < n; i++) {
            if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
        }
        if (a.length === b.length) return 0;
        return a.length < b.length ? -1 : 1;
    };

    /// Buffer.isEncoding(name) — true if `name` is a known encoding.
    Buffer.isEncoding = function(encoding) {
        if (typeof encoding !== 'string') return false;
        switch (encoding.toLowerCase()) {
            case 'utf8': case 'utf-8':
            case 'utf16le': case 'utf-16le': case 'ucs2': case 'ucs-2':
            case 'latin1': case 'binary':
            case 'ascii':
            case 'base64': case 'base64url':
            case 'hex':
                return true;
            default:
                return false;
        }
    };

    /// Buffer.prototype.swap16 / swap32 / swap64 — byte-swap pairs
    /// of bytes in-place. Throws if length isn't a multiple of the
    /// swap unit. Returns `this` so calls chain.
    function _swap(self, unit) {
        if ((self.length % unit) !== 0) {
            throw new RangeError('Buffer.swap' + (unit * 8) + ': length must be multiple of ' + unit);
        }
        for (var i = 0; i < self.length; i += unit) {
            for (var j = 0; j < unit / 2; j++) {
                var tmp = self[i + j];
                self[i + j] = self[i + unit - 1 - j];
                self[i + unit - 1 - j] = tmp;
            }
        }
        return self;
    }
    function _installSwapMethods(proto) {
        if (!proto) return;
        if (typeof proto.swap16 !== 'function') {
            proto.swap16 = function() { return _swap(this, 2); };
        }
        if (typeof proto.swap32 !== 'function') {
            proto.swap32 = function() { return _swap(this, 4); };
        }
        if (typeof proto.swap64 !== 'function') {
            proto.swap64 = function() { return _swap(this, 8); };
        }
    }
    // makeBuffer either returns a fresh Uint8Array with `__isBuffer`
    // tagged or extends prototypes; `swap*` lives on the per-buffer
    // augmentation. Install on the canonical Uint8Array prototype
    // since Buffers ARE Uint8Arrays under the hood.
    _installSwapMethods(Uint8Array.prototype);

    exports.Buffer = Buffer;
    exports.kMaxLength = 0x7fffffff;
    exports.INSPECT_MAX_BYTES = 50;

    /// buffer.constants — module-level Node 8.2+ surface. Real apps
    /// (sharp, fast-glob, node-canvas) probe these at module init.
    exports.constants = {
        MAX_LENGTH: 0x7fffffff,
        MAX_STRING_LENGTH: 0x1fffffe8,
    };

    /// buffer.atob / buffer.btoa — Node re-exports the Web globals
    /// here for convenience (some libraries import from buffer
    /// instead of relying on the global).
    exports.atob = function(input) {
        return Buffer.from(String(input), 'base64').toString('binary');
    };
    exports.btoa = function(input) {
        return Buffer.from(String(input), 'binary').toString('base64');
    };

    /// buffer.transcode — re-encode a Buffer between two single-byte
    /// or UTF encodings. Uses TextDecoder + TextEncoder for the
    /// common cross-encoding paths; falls back to identity copy
    /// when source and target encodings match.
    exports.transcode = function(source, fromEnc, toEnc) {
        if (!Buffer.isBuffer(source)) {
            throw new TypeError('buffer.transcode: source must be a Buffer');
        }
        var from = String(fromEnc || '').toLowerCase();
        var to = String(toEnc || '').toLowerCase();
        if (from === to) return Buffer.from(source);
        // Use the canonical TextDecoder/TextEncoder pair for any pair
        // that involves utf-* on at least one side.
        var dec = new TextDecoder(from === 'utf16le' ? 'utf-16le' : (from || 'utf-8'));
        var str = dec.decode(source);
        if (to === 'utf-8' || to === 'utf8') {
            return Buffer.from(new TextEncoder().encode(str));
        }
        if (to === 'utf16le' || to === 'utf-16le') {
            // Manual UTF-16LE encode.
            var out = Buffer.alloc(str.length * 2);
            for (var i = 0; i < str.length; i++) {
                var c = str.charCodeAt(i);
                out[i * 2]     = c & 0xff;
                out[i * 2 + 1] = (c >> 8) & 0xff;
            }
            return out;
        }
        if (to === 'latin1' || to === 'binary') {
            var out2 = Buffer.alloc(str.length);
            for (var j = 0; j < str.length; j++) {
                out2[j] = str.charCodeAt(j) & 0xff;
            }
            return out2;
        }
        if (to === 'ascii') {
            var out3 = Buffer.alloc(str.length);
            for (var k = 0; k < str.length; k++) {
                out3[k] = str.charCodeAt(k) & 0x7f;
            }
            return out3;
        }
        throw new Error('buffer.transcode: unsupported target encoding: ' + to);
    };

    /// buffer.resolveObjectURL — returns the Blob registered to a
    /// `blob:` URL via URL.createObjectURL. Burn doesn't support
    /// createObjectURL (no DOM), so this always returns undefined.
    exports.resolveObjectURL = function() { return undefined; };

    /// `buffer.isUtf8(input)` / `buffer.isAscii(input)` — Node 19.4+
    /// validators that check whether a Buffer / TypedArray / ArrayBuffer
    /// holds well-formed UTF-8 or 7-bit ASCII bytes. We accept the same
    /// argument shape as Node and walk the underlying byte view.
    function _coerceToBytes(input, fnName) {
        if (input == null) {
            var e = new TypeError(
                fnName + ': argument must be a Buffer, TypedArray, DataView or ArrayBuffer');
            e.code = 'ERR_INVALID_ARG_TYPE';
            throw e;
        }
        if (input instanceof ArrayBuffer) return new Uint8Array(input);
        if (ArrayBuffer.isView(input)) {
            return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
        }
        var e2 = new TypeError(
            fnName + ': argument must be a Buffer, TypedArray, DataView or ArrayBuffer');
        e2.code = 'ERR_INVALID_ARG_TYPE';
        throw e2;
    }

    exports.isUtf8 = function isUtf8(input) {
        var bytes = _coerceToBytes(input, 'isUtf8');
        var i = 0, n = bytes.length;
        while (i < n) {
            var b = bytes[i];
            if (b < 0x80) { i += 1; continue; }
            var trailing;
            if ((b & 0xe0) === 0xc0) { trailing = 1; if (b < 0xc2) return false; }
            else if ((b & 0xf0) === 0xe0) { trailing = 2; }
            else if ((b & 0xf8) === 0xf0) { trailing = 3; if (b > 0xf4) return false; }
            else return false;
            if (i + trailing >= n) return false;
            // Overlong / surrogate / out-of-range filters per RFC 3629.
            if (trailing === 2 && b === 0xe0 && bytes[i + 1] < 0xa0) return false;
            if (trailing === 2 && b === 0xed && bytes[i + 1] >= 0xa0) return false;
            if (trailing === 3 && b === 0xf0 && bytes[i + 1] < 0x90) return false;
            if (trailing === 3 && b === 0xf4 && bytes[i + 1] >= 0x90) return false;
            for (var j = 1; j <= trailing; j++) {
                if ((bytes[i + j] & 0xc0) !== 0x80) return false;
            }
            i += 1 + trailing;
        }
        return true;
    };

    exports.isAscii = function isAscii(input) {
        var bytes = _coerceToBytes(input, 'isAscii');
        for (var i = 0; i < bytes.length; i++) {
            if (bytes[i] > 0x7f) return false;
        }
        return true;
    };

    /// buffer.SlowBuffer — alias for `Buffer.allocUnsafeSlow` per
    /// Node's documented re-export.
    exports.SlowBuffer = function SlowBuffer(size) {
        return Buffer.allocUnsafeSlow(size);
    };

    /// buffer.Blob / buffer.File — re-exports of the Web globals
    /// for callers that import from `node:buffer` instead of using
    /// the globals directly.
    if (typeof globalThis.Blob === 'function') exports.Blob = globalThis.Blob;
    if (typeof globalThis.File === 'function') exports.File = globalThis.File;
});

// ---- child_process.js ----
// child_process — sync subset (execSync / spawnSync), backed by
// `__host_child_process_exec_sync` on both the native (rquickjs) path
// and the WASM-sandbox path. Argv crosses the host import boundary as
// a JSON-encoded array string so the wire shape stays primitive
// (host_imports work in (ptr, len) pairs, no array marshalling).
//
// Sync methods only: burn does not drive async child_process events.

__register_module('child_process', function(module, exports, require) {

    function ensureHost() {
        var fn = globalThis.__host_child_process_exec_sync;
        if (typeof fn !== 'function') {
            var err = new Error("Permission denied: child_process is not available in this sandbox");
            err.code = 'EACCES';
            throw err;
        }
        return fn;
    }

    function parseResult(raw) {
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            var err = new Error("child_process: " + raw.slice('__HOST_ERR__:'.length));
            err.code = 'EACCES';
            throw err;
        }
        return JSON.parse(raw);
    }

    function callHost(cmd, argv) {
        // Always serialize argv as JSON for both native and wasm paths
        // — the wasm host import only accepts scalar args, and keeping
        // the wire identical means a single `parseResult` works for
        // both backends.
        var argvJson = JSON.stringify((argv || []).map(String));
        return ensureHost()(String(cmd), argvJson);
    }

    exports.execSync = function(command, options) {
        // Node's `execSync` takes a whole command string; we split on
        // whitespace for the simple shim.
        var parts = String(command).split(/\s+/).filter(Boolean);
        if (parts.length === 0) throw new Error("child_process.execSync: empty command");
        var argv = parts.slice(1);
        var raw = callHost(parts[0], argv);
        var result = parseResult(raw);
        if (result.status !== 0) {
            var err = new Error("Command failed: " + command + "\n" + result.stderr);
            err.status = result.status;
            err.stdout = result.stdout;
            err.stderr = result.stderr;
            throw err;
        }
        return result.stdout;
    };

    exports.spawnSync = function(command, args, options) {
        args = args || [];
        var raw = callHost(command, args);
        return parseResult(raw);
    };

    /// `child_process.execFileSync(file, args, options)` — Node's
    /// quoting-safe twin of execSync. Doesn't run a shell, takes the
    /// argv vector directly. We delegate to the same host fn as
    /// spawnSync. Throws on non-zero exit per Node semantics.
    exports.execFileSync = function(file, args, options) {
        args = args || [];
        var raw = callHost(String(file), args);
        var result = parseResult(raw);
        if (result.status !== 0) {
            var err = new Error("Command failed: " + file + " " + args.join(' ') +
                "\n" + result.stderr);
            err.status = result.status;
            err.stdout = result.stdout;
            err.stderr = result.stderr;
            err.pid = result.pid;
            throw err;
        }
        // execFileSync returns the stdout buffer (or string if encoding set).
        var enc = options && options.encoding;
        if (enc && enc !== 'buffer') {
            return String(result.stdout);
        }
        var Buffer = require('buffer').Buffer;
        return Buffer.from(String(result.stdout || ''), 'utf8');
    };

    // ---- Async-style child_process wrappers ------------------------
    //
    // The host backend is synchronous; the async wrappers run the
    // child inline and dispatch events / callbacks on a microtask so
    // the canonical Node patterns (`.on('exit', …)`, `exec(cmd, cb)`)
    // work as expected. Real concurrent subprocess execution would
    // need a Tokio-backed coordinator like the outbound HTTP path.
    var EventEmitter = require('events');

    function _bufferOf(text) {
        var Buffer = require('buffer').Buffer;
        return Buffer.from(String(text || ''), 'utf8');
    }

    function _makeStream(text) {
        var s = Object.create(EventEmitter.prototype);
        EventEmitter.call(s);
        s.readable = true;
        s.setEncoding = function(enc) { s._enc = enc; return s; };
        s.pipe = function(dest) {
            Promise.resolve().then(function() {
                var chunk = _bufferOf(text);
                if (s._enc === 'utf8' || s._enc === 'utf-8') chunk = chunk.toString('utf8');
                if (dest && typeof dest.write === 'function') dest.write(chunk);
                if (dest && typeof dest.end === 'function') dest.end();
            });
            return dest;
        };
        Promise.resolve().then(function() {
            if (text != null && text.length) {
                var chunk = _bufferOf(text);
                if (s._enc === 'utf8' || s._enc === 'utf-8') chunk = chunk.toString('utf8');
                s.emit('data', chunk);
            }
            s.emit('end');
            s.emit('close');
        });
        return s;
    }

    function _makeChildProcess(result, cmd, args) {
        var ee = Object.create(EventEmitter.prototype);
        EventEmitter.call(ee);
        ee.pid = (result && result.pid) || 0;
        ee.exitCode = (result && result.status) !== undefined ? result.status : 0;
        ee.signalCode = null;
        ee.killed = false;
        ee.spawnfile = String(cmd);
        ee.spawnargs = [String(cmd)].concat((args || []).map(String));
        ee.stdout = _makeStream(result && result.stdout);
        ee.stderr = _makeStream(result && result.stderr);
        var stdin = Object.create(EventEmitter.prototype);
        EventEmitter.call(stdin);
        stdin.write = function() { return true; };
        stdin.end = function() {};
        stdin.writable = true;
        ee.stdin = stdin;
        ee.kill = function(_signal) { ee.killed = true; return true; };
        ee.send = function() { return false; };
        ee.disconnect = function() {};
        ee.ref = function() {};
        ee.unref = function() {};
        Promise.resolve().then(function() {
            ee.emit('spawn');
            ee.emit('exit', ee.exitCode, ee.signalCode);
            ee.emit('close', ee.exitCode, ee.signalCode);
        });
        return ee;
    }

    exports.spawn = function spawn(command, args, options) {
        if (Array.isArray(args)) {
            // good
        } else if (args && typeof args === 'object') {
            options = args; args = [];
        } else {
            args = args || [];
        }
        var result;
        try {
            var raw = callHost(command, args);
            result = parseResult(raw);
        } catch (e) {
            // Surface error via the canonical async error event.
            var ee = _makeChildProcess({ status: 1 }, command, args);
            Promise.resolve().then(function() { ee.emit('error', e); });
            return ee;
        }
        return _makeChildProcess(result, command, args);
    };

    exports.execFile = function execFile(file, args, options, cb) {
        if (typeof args === 'function') { cb = args; args = []; options = undefined; }
        if (typeof options === 'function') { cb = options; options = undefined; }
        args = args || [];
        var child;
        try {
            var raw = callHost(file, args);
            var result = parseResult(raw);
            child = _makeChildProcess(result, file, args);
            if (typeof cb === 'function') {
                Promise.resolve().then(function() {
                    var enc = (options && options.encoding) || 'utf8';
                    var stdout = enc === 'buffer' ? _bufferOf(result.stdout) : String(result.stdout || '');
                    var stderr = enc === 'buffer' ? _bufferOf(result.stderr) : String(result.stderr || '');
                    if (result.status !== 0) {
                        var err = new Error('Command failed: ' + file);
                        err.code = result.status;
                        err.stdout = stdout;
                        err.stderr = stderr;
                        cb(err, stdout, stderr);
                    } else {
                        cb(null, stdout, stderr);
                    }
                });
            }
        } catch (e) {
            if (typeof cb === 'function') {
                Promise.resolve().then(function() { cb(e, '', ''); });
            }
            child = _makeChildProcess({ status: 1 }, file, args);
        }
        return child;
    };

    exports.exec = function exec(command, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        var parts = String(command).split(/\s+/).filter(Boolean);
        if (parts.length === 0) {
            if (cb) Promise.resolve().then(function() { cb(new Error('empty command'), '', ''); });
            return _makeChildProcess({ status: 1 }, command, []);
        }
        return exports.execFile(parts[0], parts.slice(1), options, cb);
    };

    /// fork(modulePath, args, opts) — run another module under burn.
    /// The IPC channel that real Node provides isn't implemented:
    /// the spawned child runs without parent ↔ child message passing.
    /// Use `worker_threads` for in-process IPC instead.
    exports.fork = function fork(modulePath, args, _options) {
        args = args || [];
        var burn = (typeof process !== 'undefined' && process.argv && process.argv[0]) || 'burn';
        var argv = [String(modulePath)].concat((args || []).map(String));
        var raw, result;
        try {
            raw = callHost(burn, argv);
            result = parseResult(raw);
        } catch (e) {
            result = { status: 1, stdout: '', stderr: String((e && e.message) || e) };
        }
        return _makeChildProcess(result, burn, argv);
    };

    // ChildProcess class — surface-only, real instances come back
    // from spawn() / fork() / exec(). Some libraries probe
    // `cp.ChildProcess` at module init.
    exports.ChildProcess = function ChildProcess() {
        EventEmitter.call(this);
    };
    exports.ChildProcess.prototype = Object.create(EventEmitter.prototype);
    exports.ChildProcess.prototype.constructor = exports.ChildProcess;
});

// ---- cluster.js ----
// cluster — Node 20+ primary/worker multi-process clustering.
//
// Real subprocess workers via `worker_threads`. Each `cluster.fork()`
// in the primary spawns a fresh `burn` subprocess that re-evaluates
// `process.argv[1]`. The forked subprocess sets `cluster.isWorker`
// truthy so the user's `if (cluster.isPrimary) { fork(); } else { app.listen(); }`
// shape Just Works.
//
// Per-CPU accept-balance: every worker sets `BURN_CLUSTER_REUSEPORT=1`
// in its own env (propagated by the primary at fork time via
// `__host_worker_spawn_env`), which flips the daemon's TCP/UDP bind
// path to `SO_REUSEPORT` (Linux/macOS/BSD) or `SO_REUSEADDR`
// (Windows). The kernel then 4-tuple-hashes incoming connections
// across the listening sockets — that's exactly what Node's default
// `SCHED_RR` strategy is at the OS level on the same platforms.
//
// `Worker.process.pid` reports the OS pid via `__host_worker_pid`.
// IPC (`worker.send` / `cluster.worker.send`) routes through the
// existing parentPort message channel — JSON frames over the
// length-prefixed pipes set up by `worker_threads`.

__register_module('cluster', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;
    var workerThreads = require('worker_threads');

    var _isPrimary = !!workerThreads.isMainThread;
    var _workers = Object.create(null);
    var _nextId = 1;

    var primary = new EventEmitter();
    primary.workers = _workers;

    function _hostWorkerPid(id) {
        if (typeof globalThis.__host_worker_pid === 'function') {
            try { return globalThis.__host_worker_pid(id) | 0; } catch (_) { return 0; }
        }
        return 0;
    }

    function _spawnWorker(scriptPath, workerData, envOverrides) {
        var dataJson = JSON.stringify(workerData || {});
        var envJson = JSON.stringify(envOverrides || {});
        var rc;
        if (typeof globalThis.__host_worker_spawn_env === 'function') {
            rc = globalThis.__host_worker_spawn_env(scriptPath, dataJson, envJson);
        } else if (typeof globalThis.__host_worker_spawn === 'function') {
            // Plugin pre-dates the env extension. Fall through to the
            // legacy spawn path; SO_REUSEPORT won't be active for the
            // child, so multi-worker `app.listen(port)` will EADDRINUSE.
            rc = globalThis.__host_worker_spawn(scriptPath, dataJson);
        } else {
            throw new Error('cluster requires daemon mode; run via `burn foo.js` CLI');
        }
        if (rc < 0) {
            throw new Error('cluster.fork: spawn failed (rc=' + rc + ')');
        }
        return rc | 0;
    }

    function fork(env) {
        if (!_isPrimary) {
            throw new Error('cluster.fork: can only be called from the primary');
        }
        if (!process.argv[1]) {
            throw new Error(
                'cluster.fork: no entry script — `cluster` needs `process.argv[1]`'
            );
        }

        var id = _nextId++;
        var clusterEnv = { __ab_cluster_id: id };
        // SO_REUSEPORT gating in the spawned subprocess's daemon.
        // The merged env wins over any user override since
        // accept-balance is the entire point of cluster mode.
        var subEnv = Object.assign({}, env || {}, {
            BURN_CLUSTER_REUSEPORT: '1',
            NODE_UNIQUE_ID: String(id),
        });

        var threadId = _spawnWorker(process.argv[1], clusterEnv, subEnv);
        var pid = _hostWorkerPid(threadId);

        var workerWrapper = new EventEmitter();
        workerWrapper.id = id;
        workerWrapper.threadId = threadId;
        workerWrapper.process = {
            pid: pid || threadId,
            kill: function(sig) {
                _hostTerminate(threadId, true);
                _ = sig;
            },
        };
        workerWrapper.exitedAfterDisconnect = false;
        workerWrapper.state = 'online';
        workerWrapper.isDead = function() { return _workers[id] === undefined; };
        workerWrapper.isConnected = function() { return _workers[id] !== undefined && workerWrapper.state !== 'disconnected'; };
        workerWrapper.kill = function(signal) {
            workerWrapper.exitedAfterDisconnect = true;
            _hostTerminate(threadId, true);
            _ = signal;
        };
        workerWrapper.disconnect = function() {
            workerWrapper.exitedAfterDisconnect = true;
            workerWrapper.state = 'disconnected';
            try { workerWrapper.emit('disconnect'); } catch (_) {}
            try { primary.emit('disconnect', workerWrapper); } catch (_) {}
            _hostTerminate(threadId, false);
            return workerWrapper;
        };
        workerWrapper.send = function(message, _handle, _opts, cb) {
            var rc = _hostPostMessage(threadId, JSON.stringify({
                __ab_cluster_msg: true,
                payload: message,
            }));
            if (typeof cb === 'function') {
                Promise.resolve().then(function() { cb(rc < 0 ? new Error('send rc=' + rc) : null); });
            }
            return rc >= 0;
        };

        // Wire daemon-event routing via the existing worker_threads
        // dispatcher. The host pumps `worker-message` / `worker-online`
        // / `worker-error` / `worker-exit` envelopes through
        // globalThis.__ab_worker_handlers[threadId]; we install a
        // facade there that fans out to the cluster wrapper.
        globalThis.__ab_worker_handlers[threadId] = {
            _dispatchOnline: function() {
                workerWrapper.state = 'online';
                try { workerWrapper.emit('online'); } catch (_) {}
                try { primary.emit('online', workerWrapper); } catch (_) {}
            },
            _dispatchMessage: function(payloadJson) {
                var value;
                try { value = JSON.parse(payloadJson); } catch (_) { return; }
                if (value && value.__ab_cluster_listening) {
                    workerWrapper.state = 'listening';
                    try { workerWrapper.emit('listening', value.address || {}); } catch (_) {}
                    try { primary.emit('listening', workerWrapper, value.address || {}); } catch (_) {}
                    return;
                }
                if (value && value.__ab_cluster_msg) {
                    try { workerWrapper.emit('message', value.payload); } catch (_) {}
                    try { primary.emit('message', workerWrapper, value.payload); } catch (_) {}
                    return;
                }
                // Plain message (worker called parentPort.postMessage
                // outside the cluster envelope) — surface it on both
                // emitters so library code that mixes worker_threads
                // and cluster idioms isn't surprised.
                try { workerWrapper.emit('message', value); } catch (_) {}
                try { primary.emit('message', workerWrapper, value); } catch (_) {}
            },
            _dispatchError: function(message, stack) {
                var err = new Error(message || 'worker error');
                if (stack) err.stack = stack;
                try { workerWrapper.emit('error', err); } catch (_) {}
                try { primary.emit('error', workerWrapper, err); } catch (_) {}
            },
            _dispatchExit: function(code) {
                workerWrapper.state = 'dead';
                delete _workers[id];
                delete globalThis.__ab_worker_handlers[threadId];
                try { workerWrapper.emit('exit', code | 0, null); } catch (_) {}
                try { primary.emit('exit', workerWrapper, code | 0, null); } catch (_) {}
            },
            // Compat with worker_threads.Worker shape so any code that
            // walks __ab_worker_handlers won't fail.
            threadId: threadId,
        };

        _workers[id] = workerWrapper;
        var _;
        try { primary.emit('fork', workerWrapper); } catch (_) {}
        // 'online' is dispatched when the worker child posts its
        // online frame after top-level evaluation finishes. Until
        // then state stays 'online' (matches Node — the wrapper
        // is online from the parent's POV the moment fork returns).
        return workerWrapper;
    }

    function _hostTerminate(threadId, force) {
        if (typeof globalThis.__host_worker_terminate === 'function') {
            try {
                return globalThis.__host_worker_terminate(threadId, force ? 1 : 0) | 0;
            } catch (_) { return -1; }
        }
        return -1;
    }
    function _hostPostMessage(threadId, json) {
        if (typeof globalThis.__host_worker_post_message === 'function') {
            try {
                return globalThis.__host_worker_post_message(threadId, json) | 0;
            } catch (_) { return -1; }
        }
        return -1;
    }

    function setupPrimary(opts) {
        primary.settings = Object.assign(primary.settings || {}, opts || {});
    }

    primary.fork = fork;
    primary.setupPrimary = setupPrimary;
    primary.setupMaster = setupPrimary; // legacy alias
    primary.disconnect = function(cb) {
        var ids = Object.keys(_workers);
        var pending = ids.length;
        if (pending === 0) {
            if (typeof cb === 'function') Promise.resolve().then(cb);
            return;
        }
        ids.forEach(function(id) {
            var w = _workers[id];
            if (!w) { pending--; return; }
            w.once('exit', function() {
                pending--;
                if (pending === 0 && typeof cb === 'function') cb();
            });
            w.disconnect();
        });
    };
    primary.settings = {};

    Object.defineProperty(primary, 'isPrimary', {
        get: function() { return _isPrimary; },
    });
    Object.defineProperty(primary, 'isMaster', {
        // Legacy alias — Node still exposes it for back-compat.
        get: function() { return _isPrimary; },
    });
    Object.defineProperty(primary, 'isWorker', {
        get: function() { return !_isPrimary; },
    });

    // ---- Worker-side surface ------------------------------------
    //
    // When running inside a forked worker, the same `cluster` import
    // exposes `cluster.worker` — the handle used by user code to
    // talk back to the primary, signal 'listening' once a server
    // binds, and observe shutdown signals.

    if (!_isPrimary) {
        var wd = workerThreads.workerData || {};
        var workerObj = new EventEmitter();
        workerObj.id = wd.__ab_cluster_id || 0;
        workerObj.process = {
            pid: typeof process !== 'undefined' && process.pid ? process.pid : 0,
        };
        workerObj.exitedAfterDisconnect = false;
        workerObj.state = 'online';
        workerObj.isDead = function() { return false; };
        workerObj.isConnected = function() { return !workerObj._closed; };
        workerObj.send = function(message, _handle, _opts, cb) {
            if (workerThreads.parentPort) {
                try {
                    workerThreads.parentPort.postMessage({
                        __ab_cluster_msg: true,
                        payload: message,
                    });
                    if (typeof cb === 'function') Promise.resolve().then(function() { cb(null); });
                    return true;
                } catch (e) {
                    if (typeof cb === 'function') Promise.resolve().then(function() { cb(e); });
                    return false;
                }
            }
            return false;
        };
        workerObj.disconnect = function() {
            workerObj._closed = true;
            workerObj.exitedAfterDisconnect = true;
            try { workerObj.emit('disconnect'); } catch (_) {}
            if (workerThreads.parentPort) {
                try { workerThreads.parentPort.close(); } catch (_) {}
            }
        };
        workerObj.kill = workerObj.disconnect;

        // Forward parentPort 'message' frames here so user code that
        // listens on `cluster.worker.on('message', ...)` sees them.
        if (workerThreads.parentPort) {
            workerThreads.parentPort.on('message', function(msg) {
                if (msg && msg.__ab_cluster_msg) {
                    try { workerObj.emit('message', msg.payload); } catch (_) {}
                } else {
                    try { workerObj.emit('message', msg); } catch (_) {}
                }
            });
            // When the primary calls `worker.disconnect()`, the host
            // delivers a `worker-terminate-requested` envelope which
            // surfaces here as parentPort 'close'. Cluster contract:
            // emit 'disconnect' on cluster.worker, run any user
            // shutdown callbacks via the same event, then exit. The
            // worker's HTTP listeners would otherwise keep the process
            // alive (`daemon.has_refs() == true`), so we force-exit.
            workerThreads.parentPort.on('close', function() {
                workerObj._closed = true;
                workerObj.exitedAfterDisconnect = true;
                try { workerObj.emit('disconnect'); } catch (_) {}
                // Microtask gap so user-installed 'disconnect' handlers
                // observe synchronous side-effects before we tear the
                // process down.
                Promise.resolve().then(function() {
                    try { process.exit(0); } catch (_) {}
                });
            });
        }

        primary.worker = workerObj;
    }

    // ---- 'listening' signalling --------------------------------
    //
    // The primary fires 'listening' when a worker calls
    // `server.listen(...)`. The worker side calls
    // `cluster._signalListening(addr)` from inside http.Server's
    // listen path; we hop the address up to the primary via the
    // existing parentPort message channel.
    primary._signalListening = function(addr) {
        if (_isPrimary) return;
        if (!workerThreads.parentPort) return;
        try {
            workerThreads.parentPort.postMessage({
                __ab_cluster_listening: true,
                address: addr || {},
            });
        } catch (_) {}
    };

    primary.schedulingPolicy = 1; // SCHED_RR — symbolic; the actual
    primary.SCHED_NONE = 0;       // accept-balance is SO_REUSEPORT
    primary.SCHED_RR = 1;         // at the kernel level.

    module.exports = primary;
});

// ---- console.js ----
// console — routes messages through the host log hook when available,
// falling back to a noop-buffer if no host is wired. `util.format` is
// used for message rendering so `%s`, `%d`, `%j` behave as expected.
//
// Eager-installed as `globalThis.console` via bootstrap IIFE, matching
// Node's drop-in posture where `console` is always available without an
// explicit `require('console')`. Also registered as the CommonJS
// `console` module so `require('console')` returns the same object.
//
// If `globalThis.console` already exists when this loads (e.g. Javy's
// built-in console on the wasm path, which writes to fd 1/2 directly),
// we leave it alone — the runtime's native impl is strictly better
// than our host-log bridge.

__register_module('console', function(module, exports, require) {
    module.exports = globalThis.console;
});

(function bootstrapConsole() {
    function resolveHost() {
        return typeof globalThis.__host_log === 'function' ? globalThis.__host_log : null;
    }

    // `util` isn't available yet at bundle-load time if this runs before
    // util.js registers — so render lazily.
    function render() {
        try {
            var util = require('util');
            return util.format.apply(null, arguments);
        } catch (_) {
            // Pre-util fallback: concatenate arguments the way Node does.
            var parts = [];
            for (var i = 0; i < arguments.length; i++) {
                parts.push(String(arguments[i]));
            }
            return parts.join(' ');
        }
    }

    function logAt(level) {
        return function() {
            var host = resolveHost();
            var msg = render.apply(null, arguments);
            if (host) host(level, msg);
            // No fallback sink in the sandbox — msg is dropped if host
            // isn't wired. Users who want host-less output should call
            // `globalThis.__host_log = function(lvl, m) { ... }`.
        };
    }

    // Build the full Node-shaped console contract. On wasm Javy ships
    // its own `globalThis.console` with just `log`/`error`; we keep
    // those (they write directly to fd 1/2 — strictly better than the
    // host-log bridge) and only fill in the methods Javy doesn't
    // provide. Missing methods like `assert`/`warn`/`info`/`debug`
    // are what break npm/pnpm/clipanion deep in their bundles, so the
    // fill-in is non-optional.
    var existing = globalThis.console || {};
    var defaults = {
        log:     logAt('info'),
        info:    logAt('info'),
        warn:    logAt('warn'),
        error:   logAt('error'),
        debug:   logAt('debug'),
        trace:   logAt('debug'),
        dir:     function(obj) {
            try {
                var util = require('util');
                logAt('info')(util.inspect(obj));
            } catch (_) {
                logAt('info')(String(obj));
            }
        },
        assert:  function(cond) {
            if (!cond) {
                var args = Array.prototype.slice.call(arguments, 1);
                logAt('error').apply(null, ['Assertion failed:'].concat(args));
            }
        },
        group:    function() {},
        groupCollapsed: function() {},
        groupEnd: function() {},
        count:    function() {},
        countReset: function() {},
        time:     function() {},
        timeLog:  function() {},
        timeEnd:  function() {},
        timeStamp: function() {},
        profile:  function() {},
        profileEnd: function() {},
        table:    function(t) { logAt('info')(JSON.stringify(t, null, 2)); },
        dirxml:   function() { logAt('info').apply(null, arguments); },
        clear:    function() {},
        Console:  function Console() { return existing; },
    };
    for (var name in defaults) {
        if (typeof existing[name] !== 'function') {
            existing[name] = defaults[name];
        }
    }
    globalThis.console = existing;
})();

// ---- crypto.js ----
// crypto — Node-style hash/hmac/randomBytes/randomUUID, all backed by
// the engine's `__host_crypto_*` globals. A Hash/Hmac object accumulates
// data and returns the final digest on `.digest(encoding)`.

__register_module('crypto', function(module, exports, require) {

    function ensureHost(name) {
        var fn = globalThis['__host_crypto_' + name];
        if (typeof fn !== 'function') {
            var err = new Error("Permission denied: crypto." + name);
            err.code = 'EACCES';
            throw err;
        }
        return fn;
    }

    function checkErr(result, op) {
        if (typeof result === 'string' && result.indexOf('__HOST_ERR__:') === 0) {
            var msg = result.slice('__HOST_ERR__:'.length);
            var err = new Error("crypto." + op + ": " + msg);
            if (msg.toLowerCase().indexOf('permission denied') !== -1) err.code = 'EACCES';
            throw err;
        }
        return result;
    }

    function streamingHashPresent() {
        return typeof globalThis.__host_crypto_hash_open === 'function'
            && typeof globalThis.__host_crypto_hash_update === 'function'
            && typeof globalThis.__host_crypto_hash_digest === 'function';
    }

    // Encode whatever the user handed us as a base64 string for the
    // streaming host wire. String inputs go through UTF-8 to match
    // Node's default. Buffer / Uint8Array pass through as their raw
    // bytes, so binary data roundtrips cleanly.
    function toUpdateB64(data) {
        if (data == null) return '';
        var B = require('buffer').Buffer;
        if (typeof data === 'string') {
            return B.from(data, 'utf8').toString('base64');
        }
        if (B.isBuffer(data)) return data.toString('base64');
        if (data instanceof Uint8Array) return B.from(data).toString('base64');
        // Fall back to String() coercion — matches old behavior for
        // weird input types.
        return B.from(String(data), 'utf8').toString('base64');
    }

    // When a host `open` returns the 0-sentinel, the detailed reason
    // is in `__host_last_error` on WASM. Native throws the exception
    // inline, so this path only fires in the WASM sandbox.
    function throwOpenErr(op, algo) {
        var msg = '';
        if (typeof globalThis.__host_last_error === 'function') {
            msg = String(globalThis.__host_last_error() || '');
        }
        if (!msg) msg = "'" + algo + "' not supported";
        var err = new Error('crypto.' + op + ': ' + msg);
        if (msg.toLowerCase().indexOf('permission denied') !== -1) err.code = 'EACCES';
        throw err;
    }

    function Hash(algorithm) {
        this._algo = String(algorithm).toLowerCase();
        this._finalized = false;
        this._streaming = streamingHashPresent();
        if (this._streaming) {
            this._handle = globalThis.__host_crypto_hash_open(this._algo);
            if (!this._handle) throwOpenErr('createHash', this._algo);
        } else {
            this._chunks = [];
        }
    }
    Hash.prototype.update = function(data) {
        if (this._finalized) throw new Error('Digest already called');
        if (this._streaming) {
            var r = globalThis.__host_crypto_hash_update(this._handle, toUpdateB64(data));
            if (typeof r === 'string' && r.indexOf('__HOST_ERR__:') === 0) {
                throw new Error('crypto.hash.update: ' + r.slice('__HOST_ERR__:'.length));
            }
        } else {
            this._chunks.push(typeof data === 'string' ? data : String(data));
        }
        return this;
    };
    Hash.prototype.digest = function(encoding) {
        if (this._finalized) throw new Error('Digest already called');
        this._finalized = true;
        // Node semantics: digest() with no encoding (or 'buffer') returns a
        // Buffer of RAW BYTES. The host bridge speaks text, so fetch base64
        // and decode — defaulting to a hex STRING here silently breaks every
        // binary consumer (keyed-HMAC chains, signatures, key derivation).
        var wantRaw = encoding === undefined || encoding === null || encoding === 'buffer';
        var enc = wantRaw ? 'base64' : encoding;
        var out;
        if (this._streaming) {
            out = checkErr(
                globalThis.__host_crypto_hash_digest(this._handle, enc),
                'hash'
            );
        } else {
            out = checkErr(
                ensureHost('hash')(this._algo, this._chunks.join(''), enc),
                'hash'
            );
        }
        return wantRaw ? require('buffer').Buffer.from(out, 'base64') : out;
    };

    function Hmac(algorithm, key) {
        this._algo = String(algorithm).toLowerCase();
        this._finalized = false;
        this._streaming = streamingHashPresent()
            && typeof globalThis.__host_crypto_hmac_open === 'function';
        if (this._streaming) {
            var B = require('buffer').Buffer;
            var keyB64 = typeof key === 'string'
                ? B.from(key, 'utf8').toString('base64')
                : (B.isBuffer(key) ? key.toString('base64')
                   : B.from(String(key), 'utf8').toString('base64'));
            this._handle = globalThis.__host_crypto_hmac_open(this._algo, keyB64);
            if (!this._handle) throwOpenErr('createHmac', this._algo);
        } else {
            this._key = typeof key === 'string' ? key : String(key);
            this._chunks = [];
        }
    }
    Hmac.prototype.update = function(data) {
        if (this._finalized) throw new Error('Digest already called');
        if (this._streaming) {
            var r = globalThis.__host_crypto_hash_update(this._handle, toUpdateB64(data));
            if (typeof r === 'string' && r.indexOf('__HOST_ERR__:') === 0) {
                throw new Error('crypto.hmac.update: ' + r.slice('__HOST_ERR__:'.length));
            }
        } else {
            this._chunks.push(typeof data === 'string' ? data : String(data));
        }
        return this;
    };
    Hmac.prototype.digest = function(encoding) {
        if (this._finalized) throw new Error('Digest already called');
        this._finalized = true;
        // Same Node semantics as Hash.digest: no encoding → raw-byte Buffer.
        var wantRaw = encoding === undefined || encoding === null || encoding === 'buffer';
        var enc = wantRaw ? 'base64' : encoding;
        var out;
        if (this._streaming) {
            out = checkErr(
                globalThis.__host_crypto_hash_digest(this._handle, enc),
                'hmac'
            );
        } else {
            out = checkErr(
                ensureHost('hmac')(this._algo, this._key, this._chunks.join(''), enc),
                'hmac'
            );
        }
        return wantRaw ? require('buffer').Buffer.from(out, 'base64') : out;
    };

    exports.createHash = function(algorithm) { return new Hash(algorithm); };
    exports.createHmac = function(algorithm, key) { return new Hmac(algorithm, key); };

    // Supported hash + cipher catalogues. Keep these aligned with the
    // host's crypto bridge — packaging tools (npm/ssri/node-tap) call
    // `getHashes()` at module-init time and crash with TypeError when
    // it is missing.
    var SUPPORTED_HASHES = [
        'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
        'shake128', 'shake256'
    ];
    var SUPPORTED_CIPHERS = [
        'aes-128-cbc', 'aes-192-cbc', 'aes-256-cbc',
        'aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm'
    ];
    exports.getHashes  = function() { return SUPPORTED_HASHES.slice(); };
    exports.getCiphers = function() { return SUPPORTED_CIPHERS.slice(); };
    exports.getCurves  = function() { return ['P-256', 'P-384', 'P-521']; };

    /// `crypto.randomBytes(len[, callback])` — Node returns a Buffer
    /// of `len` cryptographically random bytes. The callback form
    /// (Node 0.5+) takes `(err, buf)`. We get the bytes from the host
    /// as a hex string, then re-pack into a Buffer to match Node's
    /// API surface.
    exports.randomBytes = function(len, cb) {
        var hex = checkErr(ensureHost('random_bytes')(len, 'hex'), 'randomBytes');
        var buf = Buffer.from(hex, 'hex');
        if (typeof cb === 'function') {
            Promise.resolve().then(function() { cb(null, buf); });
            return undefined;
        }
        return buf;
    };

    exports.randomUUID = function() {
        return checkErr(ensureHost('random_uuid')(), 'randomUUID');
    };

    exports.timingSafeEqual = function(a, b) {
        var fn = globalThis.__host_crypto_timing_safe_equal;
        if (typeof fn !== 'function') return false;
        return fn(typeof a === 'string' ? a : String(a),
                  typeof b === 'string' ? b : String(b));
    };

    // `randomFillSync(buffer[, offset[, size]])` — fills the buffer
    // in-place with cryptographically random bytes. Returns the buffer.
    exports.randomFillSync = function(buffer, offset, size) {
        if (!buffer || typeof buffer.length !== 'number') {
            throw new TypeError('randomFillSync: buffer must be a TypedArray');
        }
        var off = (offset | 0) || 0;
        var len = (typeof size === 'number') ? (size | 0) : (buffer.length - off);
        if (len <= 0) return buffer;
        var hex = ensureHost('random_bytes')(len, 'hex');
        if (typeof hex !== 'string') return buffer;
        var view = (buffer.buffer && typeof buffer.buffer === 'object')
            ? new Uint8Array(buffer.buffer, buffer.byteOffset || 0, buffer.byteLength || buffer.length)
            : buffer;
        for (var i = 0; i < len; i++) {
            view[off + i] = parseInt(hex.substr(i * 2, 2), 16);
        }
        return buffer;
    };

    /// `randomFill(buffer[, offset[, size]], cb)` — async variant.
    /// Same operation; calls cb on next microtask.
    exports.randomFill = function(buffer, offset, size, cb) {
        if (typeof offset === 'function') { cb = offset; offset = undefined; size = undefined; }
        else if (typeof size === 'function') { cb = size; size = undefined; }
        try {
            exports.randomFillSync(buffer, offset, size);
            if (typeof cb === 'function') Promise.resolve().then(function() { cb(null, buffer); });
        } catch (e) {
            if (typeof cb === 'function') Promise.resolve().then(function() { cb(e); });
        }
    };

    /// `crypto.randomInt([min, ]max[, callback])` — uniform integer
    /// in `[min, max)`. Sync if no callback. Min defaults to 0.
    exports.randomInt = function(min, max, cb) {
        if (typeof min === 'function') { cb = min; min = 0; max = 0xffffffff; }
        else if (typeof max === 'function') { cb = max; max = min; min = 0; }
        else if (max === undefined) { max = min; min = 0; }
        if (min < 0 || max <= min || max - min > Math.pow(2, 48)) {
            var err = new RangeError('randomInt: min/max out of range');
            if (typeof cb === 'function') {
                Promise.resolve().then(function() { cb(err); });
                return;
            }
            throw err;
        }
        var range = max - min;
        // Sample 6 bytes (2^48), reject + retry to avoid modulo bias.
        function sample() {
            var hex = ensureHost('random_bytes')(6, 'hex');
            var n = 0;
            for (var i = 0; i < 12; i++) n = n * 16 + parseInt(hex.charAt(i), 16);
            var max48 = Math.pow(2, 48);
            var fold = max48 - (max48 % range);
            if (n >= fold) return sample(); // discard biased range
            return min + (n % range);
        }
        var v = sample();
        if (typeof cb === 'function') {
            Promise.resolve().then(function() { cb(null, v); });
            return;
        }
        return v;
    };

    /// `crypto.timingSafeEqual` already exists (inline below); the
    /// alias below matches Node's Web Crypto export for callers that
    /// reach for `crypto.webcrypto.subtle`.
    exports.webcrypto = (typeof globalThis.crypto === 'object') ? globalThis.crypto : undefined;

    // ---- ciphers (AES-GCM / AES-CBC) --------------------------------
    var Buffer = require('buffer').Buffer;

    function toB64(x) {
        if (typeof x === 'string') return Buffer.from(x, 'utf8').toString('base64');
        if (Buffer.isBuffer(x))    return x.toString('base64');
        if (x instanceof Uint8Array) return Buffer.from(x).toString('base64');
        throw new TypeError('expected string/Buffer/Uint8Array');
    }
    function fromB64(s, tag) {
        if (typeof s === 'string' && s.indexOf('__HOST_ERR__:') === 0) {
            throw new Error(tag + ': ' + s.slice('__HOST_ERR__:'.length));
        }
        return Buffer.from(s, 'base64');
    }

    function makeGcmCipher(algo, key, iv, opts) {
        var aad = null;
        var finalized = false;
        var queued = [];
        var mode = opts && opts.mode; // 'encrypt' | 'decrypt'
        var authTag = null;
        return {
            setAAD: function(buf) { aad = Buffer.isBuffer(buf) ? buf : Buffer.from(buf); return this; },
            setAutoPadding: function() { return this; },
            update: function(data) {
                if (finalized) throw new Error('cipher finalized');
                queued.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
                return Buffer.alloc(0);
            },
            setAuthTag: function(tag) { authTag = tag; return this; },
            getAuthTag: function() {
                if (mode !== 'encrypt' || !finalized) {
                    throw new Error('getAuthTag available only after encrypt final');
                }
                return authTag;
            },
            final: function() {
                if (finalized) throw new Error('cipher finalized');
                finalized = true;
                var data = Buffer.concat(queued);
                var fn = mode === 'encrypt' ? '__host_crypto_aes_gcm_encrypt' : '__host_crypto_aes_gcm_decrypt';
                var rawIn = mode === 'encrypt' ? data
                    : Buffer.concat([data, authTag || Buffer.alloc(16)]);
                var raw = globalThis[fn](
                    algo,
                    toB64(key),
                    toB64(iv),
                    toB64(rawIn),
                    aad ? toB64(aad) : null
                );
                var out = fromB64(raw, 'cipher');
                if (mode === 'encrypt') {
                    authTag = out.slice(out.length - 16);
                    return out.slice(0, out.length - 16);
                } else {
                    return out;
                }
            }
        };
    }

    function makeCbcCipher(algo, key, iv, mode) {
        var finalized = false;
        var queued = [];
        return {
            setAutoPadding: function() { return this; },
            update: function(data) {
                if (finalized) throw new Error('cipher finalized');
                queued.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
                return Buffer.alloc(0);
            },
            final: function() {
                if (finalized) throw new Error('cipher finalized');
                finalized = true;
                var data = Buffer.concat(queued);
                var fn = mode === 'encrypt' ? '__host_crypto_aes_cbc_encrypt' : '__host_crypto_aes_cbc_decrypt';
                var raw = globalThis[fn](algo, toB64(key), toB64(iv), toB64(data));
                return fromB64(raw, 'cipher');
            }
        };
    }

    function makeCipher(algo, key, iv, mode) {
        var a = String(algo).toLowerCase();
        if (a.indexOf('-gcm') > 0) return makeGcmCipher(a, key, iv, { mode: mode });
        if (a.indexOf('-cbc') > 0) return makeCbcCipher(a, key, iv, mode);
        throw new Error('Unsupported cipher: ' + algo);
    }

    exports.createCipheriv = function(algo, key, iv) { return makeCipher(algo, key, iv, 'encrypt'); };
    exports.createDecipheriv = function(algo, key, iv) { return makeCipher(algo, key, iv, 'decrypt'); };

    // ---- KDFs --------------------------------------------------------
    exports.pbkdf2Sync = function(password, salt, iterations, keylen, digest) {
        var fn = globalThis.__host_crypto_pbkdf2_sync;
        if (typeof fn !== 'function') {
            throw new Error('Permission denied: crypto.pbkdf2Sync');
        }
        var pwd = typeof password === 'string' ? password
            : Buffer.isBuffer(password) ? password.toString('binary')
            : String(password);
        var saltBuf = Buffer.isBuffer(salt) ? salt : Buffer.from(String(salt));
        var raw = fn(String(digest || 'sha256'), pwd, saltBuf.toString('base64'), iterations >>> 0, keylen >>> 0);
        return fromB64(raw, 'pbkdf2Sync');
    };

    // ---- sign / verify (RSA + ECDSA) ----------------------------------
    function signImpl(algorithm, keyPem, data) {
        var fn = globalThis.__host_crypto_sign;
        if (typeof fn !== 'function') {
            throw new Error('Permission denied: crypto.sign');
        }
        var dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(String(data));
        var raw = fn(String(algorithm), String(keyPem), dataBuf.toString('base64'));
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            throw new Error('crypto.sign: ' + raw.slice('__HOST_ERR__:'.length));
        }
        return Buffer.from(raw, 'base64');
    }

    function verifyImpl(algorithm, keyPem, data, signature) {
        var fn = globalThis.__host_crypto_verify;
        if (typeof fn !== 'function') {
            throw new Error('Permission denied: crypto.verify');
        }
        var dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(String(data));
        var sigBuf = Buffer.isBuffer(signature) ? signature : Buffer.from(String(signature));
        var code = fn(
            String(algorithm),
            String(keyPem),
            dataBuf.toString('base64'),
            sigBuf.toString('base64')
        );
        // Both paths now return i32 (1/0/negative). Accept bool too in
        // case an embedder wires a host that returns it directly.
        if (code === 1 || code === true) return true;
        if (code === 0 || code === false) return false;
        throw new Error('crypto.verify: host error (code ' + code + ')');
    }

    exports.sign = signImpl;
    exports.verify = verifyImpl;

    // Node's stream-style createSign / createVerify. Streaming-backed:
    // chunks are hashed incrementally on the host side, so memory is
    // proportional to the digest state (~200 B) rather than the total
    // payload size.
    var ALGO_ALIASES = {
        'RSA-SHA256': 'RS256', 'RSA-SHA384': 'RS384', 'RSA-SHA512': 'RS512',
        'sha256WithRSAEncryption': 'RS256',
        'sha384WithRSAEncryption': 'RS384',
        'sha512WithRSAEncryption': 'RS512',
    };
    function canonicalAlgo(algo) { return ALGO_ALIASES[algo] || algo; }

    function streamingHostPresent() {
        return typeof globalThis.__host_crypto_sign_open === 'function'
            && typeof globalThis.__host_crypto_sign_update === 'function';
    }

    function makeSigner(algo) {
        var canonical = canonicalAlgo(algo);
        if (streamingHostPresent()) {
            var handle = globalThis.__host_crypto_sign_open(canonical);
            if (!handle) throw new Error('crypto.createSign: ' + canonical + ' not supported');
            return {
                update: function(d) {
                    var buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
                    var r = globalThis.__host_crypto_sign_update(handle, buf.toString('base64'));
                    if (typeof r === 'string' && r.indexOf('__HOST_ERR__:') === 0) {
                        throw new Error('crypto.sign.update: ' + r.slice('__HOST_ERR__:'.length));
                    }
                    return this;
                },
                sign: function(key) {
                    var raw = globalThis.__host_crypto_sign_finalize(handle, canonical, String(key));
                    if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
                        throw new Error('crypto.sign: ' + raw.slice('__HOST_ERR__:'.length));
                    }
                    return Buffer.from(raw, 'base64');
                }
            };
        }
        // Fallback for older plugins / embedders that haven't wired
        // streaming: buffer everything and use the one-shot API.
        var chunks = [];
        return {
            update: function(d) { chunks.push(Buffer.isBuffer(d) ? d : Buffer.from(String(d))); return this; },
            sign:   function(key) { return signImpl(canonical, key, Buffer.concat(chunks)); }
        };
    }

    function makeVerifier(algo) {
        var canonical = canonicalAlgo(algo);
        if (streamingHostPresent() && typeof globalThis.__host_crypto_verify_finalize === 'function') {
            var handle = globalThis.__host_crypto_sign_open(canonical);
            if (!handle) throw new Error('crypto.createVerify: ' + canonical + ' not supported');
            return {
                update: function(d) {
                    var buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
                    var r = globalThis.__host_crypto_sign_update(handle, buf.toString('base64'));
                    if (typeof r === 'string' && r.indexOf('__HOST_ERR__:') === 0) {
                        throw new Error('crypto.verify.update: ' + r.slice('__HOST_ERR__:'.length));
                    }
                    return this;
                },
                verify: function(key, sig) {
                    var sigBuf = Buffer.isBuffer(sig) ? sig : Buffer.from(String(sig));
                    var code = globalThis.__host_crypto_verify_finalize(
                        handle, canonical, String(key), sigBuf.toString('base64'));
                    if (code === 1 || code === true) return true;
                    if (code === 0 || code === false) return false;
                    throw new Error('crypto.verify: host error (code ' + code + ')');
                }
            };
        }
        var chunks = [];
        return {
            update: function(d) { chunks.push(Buffer.isBuffer(d) ? d : Buffer.from(String(d))); return this; },
            verify: function(key, sig) { return verifyImpl(canonical, key, Buffer.concat(chunks), sig); }
        };
    }
    exports.createSign = makeSigner;
    exports.createVerify = makeVerifier;

    exports.scryptSync = function(password, salt, keylen, options) {
        var fn = globalThis.__host_crypto_scrypt_sync;
        if (typeof fn !== 'function') {
            throw new Error('Permission denied: crypto.scryptSync');
        }
        options = options || {};
        var N = options.N || options.cost || 16384;
        var r = options.r || options.blockSize || 8;
        var p = options.p || options.parallelization || 1;
        var pwd = typeof password === 'string' ? password
            : Buffer.isBuffer(password) ? password.toString('binary')
            : String(password);
        var saltBuf = Buffer.isBuffer(salt) ? salt : Buffer.from(String(salt));
        var raw = fn(pwd, saltBuf.toString('base64'), N >>> 0, r >>> 0, p >>> 0, keylen >>> 0);
        return fromB64(raw, 'scryptSync');
    };

    /// `crypto.scrypt(password, salt, keylen, options, cb)` — Node's
    /// async wrapper. Our scrypt is host-side synchronous, so we
    /// dispatch on a microtask to preserve the cb-after-IO contract.
    exports.scrypt = function(password, salt, keylen, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        Promise.resolve().then(function() {
            try { cb(null, exports.scryptSync(password, salt, keylen, options)); }
            catch (e) { cb(e); }
        });
    };

    /// `crypto.hash(algorithm, data, encoding)` — Node 21+ one-shot
    /// hash that skips the `createHash` ceremony. Returns the digest
    /// directly in the requested encoding (default 'hex').
    exports.hash = function(algorithm, data, encoding) {
        var h = exports.createHash(algorithm);
        h.update(data);
        return h.digest(encoding || 'hex');
    };

    /// `crypto.hkdfSync(digest, ikm, salt, info, length)` — Node 15+.
    /// Composes HKDF-Extract + HKDF-Expand from createHmac. Returns
    /// the OKM as an ArrayBuffer (Node returns ArrayBuffer too).
    exports.hkdfSync = function(digest, ikm, salt, info, length) {
        var Buffer = require('buffer').Buffer;
        var ikmBuf  = Buffer.isBuffer(ikm)  ? ikm  : Buffer.from(ikm);
        var saltBuf = Buffer.isBuffer(salt) ? salt : Buffer.from(salt || '');
        var infoBuf = Buffer.isBuffer(info) ? info : Buffer.from(info || '');
        // HKDF-Extract: PRK = HMAC(salt, IKM)
        var extract = exports.createHmac(digest, saltBuf);
        extract.update(ikmBuf);
        var prk = Buffer.from(extract.digest('hex'), 'hex');
        // HKDF-Expand: T(0) = empty; T(i) = HMAC(PRK, T(i-1) || info || 0xi)
        var hashLen = prk.length;
        var n = Math.ceil(length / hashLen);
        if (n > 255) {
            throw new RangeError('HKDF: length too large');
        }
        var okm = Buffer.alloc(0);
        var t = Buffer.alloc(0);
        for (var i = 1; i <= n; i++) {
            var h = exports.createHmac(digest, prk);
            h.update(Buffer.concat([t, infoBuf, Buffer.from([i])]));
            t = Buffer.from(h.digest('hex'), 'hex');
            okm = Buffer.concat([okm, t]);
        }
        var out = okm.slice(0, length);
        return out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength);
    };

    /// `crypto.hkdf(...)` — async sibling. Mirrors hkdfSync on a
    /// microtask.
    exports.hkdf = function(digest, ikm, salt, info, length, cb) {
        Promise.resolve().then(function() {
            try { cb(null, exports.hkdfSync(digest, ikm, salt, info, length)); }
            catch (e) { cb(e); }
        });
    };

    /// `crypto.subtle` — alias to globalThis.crypto.subtle (Node 15+
    /// ships SubtleCrypto via the crypto module, not just globally).
    Object.defineProperty(exports, 'subtle', {
        get: function() {
            return globalThis.crypto && globalThis.crypto.subtle;
        },
        configurable: true,
    });

    /// `crypto.fips` — boolean flag exposed since Node 0.12. We're
    /// not FIPS-validated; surfacing `false` matches what most non-
    /// FIPS Node builds report.
    Object.defineProperty(exports, 'fips', {
        value: false, writable: false, configurable: true, enumerable: true,
    });

    /// `crypto.KeyObject` — opaque key handle. PKCS#8 / SPKI / raw
    /// bytes underneath; `export` / `equals` operate on those bytes.
    function _b64UrlEncode(bytes) {
        var Buf = globalThis.Buffer || require('buffer').Buffer;
        return Buf.from(bytes).toString('base64')
            .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }
    function _hostSubtle(op, args) {
        if (typeof globalThis.__host_crypto_subtle_op !== 'function') {
            throw new Error('crypto: subtle host fn missing');
        }
        var Buf = globalThis.Buffer || require('buffer').Buffer;
        var jsonArgs = '[' + args.map(function(a) {
            var bs = (a instanceof Uint8Array) ? a
                  : Buf.isBuffer(a) ? a
                  : (typeof a === 'string') ? Buf.from(a, 'utf8')
                  : Buf.from(a);
            return JSON.stringify(_b64UrlEncode(bs));
        }).join(',') + ']';
        var r = globalThis.__host_crypto_subtle_op(op, jsonArgs);
        if (typeof r === 'string' && r.indexOf('__HOST_ERR__:') === 0) {
            throw new Error(r.slice('__HOST_ERR__:'.length));
        }
        return r;
    }
    function _b64UrlToBytes(b64) {
        var s = String(b64).replace(/-/g, '+').replace(/_/g, '/');
        while (s.length % 4 !== 0) s += '=';
        var Buf = globalThis.Buffer || require('buffer').Buffer;
        return new Uint8Array(Buf.from(s, 'base64'));
    }

    function KeyObject(type, asymKeyType, raw) {
        // Node's KeyObject is meant to be created via factory
        // functions, not direct construction. We follow the spec:
        // direct `new KeyObject()` is disallowed.
        if (!(this instanceof KeyObject)) return new KeyObject(type, asymKeyType, raw);
        if (!arguments.length) {
            var e = new TypeError('Illegal constructor: KeyObject is created via createSecretKey/createPrivateKey/createPublicKey');
            e.code = 'ERR_OPERATION_FAILED';
            throw e;
        }
        Object.defineProperty(this, 'type', { value: type, enumerable: true });
        Object.defineProperty(this, 'asymmetricKeyType',
            { value: asymKeyType || undefined, enumerable: true });
        Object.defineProperty(this, '_raw', { value: raw, enumerable: false });
    }
    KeyObject.prototype.export = function(options) {
        options = options || {};
        if (this.type === 'secret') {
            // Secret keys export to raw or jwk (oct kty).
            if (options.format === 'jwk') {
                return {
                    kty: 'oct',
                    k: _b64UrlEncode(this._raw),
                    ext: true,
                };
            }
            // Default: Buffer of the raw bytes.
            return Buffer.from(this._raw);
        }
        // Asymmetric: PKCS#8 / SPKI / JWK.
        if (options.format === 'jwk') {
            // RSA → host helper; EC/Ed/X25519 left as raw DER plus a
            // typed JWK envelope is more work — start with RSA and
            // fall through for others.
            if (this.asymmetricKeyType === 'rsa') {
                var op = (this.type === 'private')
                    ? 'rsa:export-jwk-priv' : 'rsa:export-jwk-pub';
                var b64 = _hostSubtle(op, [this._raw]);
                var bytes = _b64UrlToBytes(b64);
                var jsonStr = String.fromCharCode.apply(null, Array.prototype.slice.call(bytes));
                var jwk = JSON.parse(jsonStr);
                return jwk;
            }
            // For EC keys, the SPKI/PKCS8 already carries everything;
            // produce a minimal JWK from the raw bytes.
            return { kty: 'EC', _raw: _b64UrlEncode(this._raw) };
        }
        // Default DER/PEM: we hold DER bytes; produce PEM if asked.
        var fmt = options.format || 'pem';
        if (fmt === 'der') return Buffer.from(this._raw);
        // PEM wrapping.
        var label;
        if (this.type === 'private') label = 'PRIVATE KEY';
        else if (this.type === 'public') label = 'PUBLIC KEY';
        else label = 'KEY';
        var b64 = Buffer.from(this._raw).toString('base64');
        var pem = '-----BEGIN ' + label + '-----\n';
        for (var i = 0; i < b64.length; i += 64) {
            pem += b64.slice(i, i + 64) + '\n';
        }
        pem += '-----END ' + label + '-----\n';
        return pem;
    };
    KeyObject.prototype.equals = function(other) {
        if (!(other instanceof KeyObject)) return false;
        if (this.type !== other.type) return false;
        if (this._raw.length !== other._raw.length) return false;
        var a = this._raw, b = other._raw, acc = 0;
        for (var i = 0; i < a.length; i++) acc |= (a[i] ^ b[i]);
        return acc === 0;
    };
    Object.defineProperty(KeyObject.prototype, 'symmetricKeySize', {
        get: function() {
            return this.type === 'secret' ? this._raw.length : undefined;
        },
    });
    Object.defineProperty(KeyObject.prototype, 'asymmetricKeyDetails', {
        get: function() {
            if (this.asymmetricKeyType === 'rsa') {
                return {}; // populated when we add ASN.1 introspection
            }
            if (this.asymmetricKeyType === 'ec') {
                return { namedCurve: this._curve || 'P-256' };
            }
            return {};
        },
    });
    KeyObject.from = function(cryptoKey) {
        // Web Crypto CryptoKey → Node KeyObject. Pull the raw bytes
        // out of `_raw` (set by our subtle factory) and rewrap.
        if (cryptoKey && cryptoKey._raw) {
            var nodeType;
            if (cryptoKey.type === 'secret') nodeType = 'secret';
            else if (cryptoKey.type === 'private') nodeType = 'private';
            else nodeType = 'public';
            var asym;
            var n = String((cryptoKey.algorithm && cryptoKey.algorithm.name) || '').toLowerCase();
            if (n.indexOf('rsa') === 0) asym = 'rsa';
            else if (n === 'ecdsa' || n === 'ecdh') asym = 'ec';
            else if (n === 'ed25519') asym = 'ed25519';
            else if (n === 'x25519') asym = 'x25519';
            return new KeyObject(nodeType, asym, new Uint8Array(cryptoKey._raw));
        }
        throw new TypeError('KeyObject.from: argument must be a CryptoKey');
    };
    exports.KeyObject = KeyObject;

    function _bytesFromKeyish(input) {
        if (input == null) {
            throw new TypeError('crypto: key input required');
        }
        if (input instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(input))) {
            return new Uint8Array(input);
        }
        if (typeof input === 'string') return new TextEncoder().encode(input);
        if (input.key !== undefined) {
            // Node-shape `{ key, format, type, passphrase }` — we don't
            // do passphrase decryption (no OpenSSL); pass through the
            // key body.
            return _bytesFromKeyish(input.key);
        }
        throw new TypeError('crypto: unsupported key input shape');
    }
    function _stripPemBody(input) {
        // Convert PEM to DER if input is a string; otherwise return
        // bytes as-is.
        if (typeof input === 'string' && input.indexOf('-----BEGIN ') !== -1) {
            var b64 = input
                .replace(/-----BEGIN [^-]+-----/, '')
                .replace(/-----END [^-]+-----/, '')
                .replace(/\s+/g, '');
            return new Uint8Array(Buffer.from(b64, 'base64'));
        }
        return _bytesFromKeyish(input);
    }
    function _detectAsymKind(_der) {
        // ASN.1 sniffing: PKCS#8 / SPKI start with SEQUENCE 0x30.
        // We don't fully parse — RSA/EC heuristic: assume RSA unless
        // the user supplied an EC-specific key. For factory APIs, a
        // proper introspection pass would walk OIDs; for now we let
        // the consuming op (sign/verify) pick the algorithm.
        return undefined; // unknown; sign/verify will pick at use time
    }

    exports.createSecretKey = function(input, encoding) {
        var bytes;
        if (typeof input === 'string') {
            bytes = new TextEncoder().encode(
                encoding ? Buffer.from(input, encoding).toString() : input);
        } else {
            bytes = _bytesFromKeyish(input);
        }
        return new KeyObject('secret', undefined, bytes);
    };

    exports.createPrivateKey = function(input) {
        var raw = _stripPemBody(input);
        return new KeyObject('private', _detectAsymKind(raw), raw);
    };

    exports.createPublicKey = function(input) {
        // If the caller passes a private KeyObject, derive its public
        // half. For RSA keys this would re-build SPKI from PKCS#8 —
        // requires an extra host op. Punt to the simple path: SPKI
        // bytes if the input is already a public key, else throw.
        if (input instanceof KeyObject) {
            if (input.type === 'public') return input;
            if (input.type === 'private') {
                var e = new Error('createPublicKey from private KeyObject requires a separate derive step');
                e.code = 'ERR_OPERATION_FAILED';
                throw e;
            }
        }
        var raw = _stripPemBody(input);
        return new KeyObject('public', _detectAsymKind(raw), raw);
    };

    /// `generateKeyPairSync(type, options)` — Node 13+. Backed by the
    /// subtle dispatcher; returns `{publicKey, privateKey}` as
    /// KeyObjects (or PEM/DER per `options.publicKeyEncoding` /
    /// `privateKeyEncoding`).
    function _wrapPair(type, privDer, pubDer, options) {
        options = options || {};
        var priv = new KeyObject('private', type, privDer);
        var pub = new KeyObject('public', type, pubDer);
        var out = { privateKey: priv, publicKey: pub };
        if (options.privateKeyEncoding) {
            out.privateKey = priv.export(options.privateKeyEncoding);
        }
        if (options.publicKeyEncoding) {
            out.publicKey = pub.export(options.publicKeyEncoding);
        }
        return out;
    }
    function _splitPair(s) {
        // Host returns `["<priv_b64>","<pub_b64>"]`.
        var arr = JSON.parse(s);
        return { priv: _b64UrlToBytes(arr[0]), pub: _b64UrlToBytes(arr[1]) };
    }
    exports.generateKeyPairSync = function(type, options) {
        options = options || {};
        if (type === 'rsa') {
            var bits = (options.modulusLength | 0) || 2048;
            var exp = (options.publicExponent | 0) || 65537;
            var pair = _splitPair(_hostSubtle('rsa:keygen', [
                new TextEncoder().encode(String(bits)),
                new TextEncoder().encode(String(exp)),
            ]));
            return _wrapPair('rsa', pair.priv, pair.pub, options);
        }
        if (type === 'ec') {
            var curve = String(options.namedCurve || 'P-256').toUpperCase();
            if (curve === 'P256' || curve === 'PRIME256V1' || curve === 'SECP256R1') curve = 'P-256';
            else if (curve === 'P384' || curve === 'SECP384R1') curve = 'P-384';
            else if (curve === 'P521' || curve === 'SECP521R1') curve = 'P-521';
            var ecPair = _splitPair(_hostSubtle('ec:keygen',
                [new TextEncoder().encode(curve)]));
            var out = _wrapPair('ec', ecPair.priv, ecPair.pub, options);
            out.privateKey._curve = curve;
            out.publicKey._curve = curve;
            return out;
        }
        if (type === 'ed25519') {
            var edPair = _splitPair(_hostSubtle('ed25519:keygen', []));
            return _wrapPair('ed25519', edPair.priv, edPair.pub, options);
        }
        if (type === 'x25519') {
            var xPair = _splitPair(_hostSubtle('x25519:keygen', []));
            return _wrapPair('x25519', xPair.priv, xPair.pub, options);
        }
        var err = new Error('crypto.generateKeyPair: unsupported type ' + type);
        err.code = 'ERR_CRYPTO_INVALID_KEY';
        throw err;
    };
    exports.generateKeyPair = function(type, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        Promise.resolve().then(function() {
            try {
                var pair = exports.generateKeyPairSync(type, options);
                cb(null, pair.publicKey, pair.privateKey);
            } catch (e) { cb(e); }
        });
    };

    /// `crypto.diffieHellman({privateKey, publicKey})` — Node 13+.
    /// Backed by the subtle ECDH dispatcher; both keys must be
    /// KeyObjects with the same EC curve (or X25519).
    exports.diffieHellman = function(options) {
        options = options || {};
        var priv = options.privateKey;
        var pub  = options.publicKey;
        if (!(priv instanceof KeyObject) || !(pub instanceof KeyObject)) {
            var e = new TypeError('crypto.diffieHellman: privateKey + publicKey must be KeyObjects');
            e.code = 'ERR_INVALID_ARG_TYPE';
            throw e;
        }
        if (priv.asymmetricKeyType === 'x25519' || pub.asymmetricKeyType === 'x25519') {
            var sharedX = _b64UrlToBytes(_hostSubtle('x25519:derive',
                [priv._raw, pub._raw]));
            return Buffer.from(sharedX);
        }
        var curve = priv._curve || pub._curve || 'P-256';
        var shared = _b64UrlToBytes(_hostSubtle('ecdh:derive', [
            new TextEncoder().encode(curve),
            priv._raw,
            pub._raw,
        ]));
        return Buffer.from(shared);
    };

    /// `crypto.createECDH(curve)` — Node 0.11+. Returns an ECDH
    /// instance with `generateKeys`, `computeSecret`, etc.
    function ECDH(curve) {
        if (!(this instanceof ECDH)) return new ECDH(curve);
        var c = String(curve).toUpperCase();
        if (c === 'PRIME256V1' || c === 'SECP256R1') c = 'P-256';
        else if (c === 'SECP384R1') c = 'P-384';
        else if (c === 'SECP521R1') c = 'P-521';
        if (c !== 'P-256' && c !== 'P-384' && c !== 'P-521') {
            var e = new Error('crypto.createECDH: unsupported curve ' + curve);
            e.code = 'ERR_CRYPTO_ECDH_INVALID_FORMAT';
            throw e;
        }
        this._curve = c;
        this._priv = null;
        this._pub = null;
    }
    ECDH.prototype.generateKeys = function(encoding, format) {
        var pair = _splitPair(_hostSubtle('ec:keygen',
            [new TextEncoder().encode(this._curve)]));
        this._priv = pair.priv;
        this._pub = pair.pub;
        return this.getPublicKey(encoding, format);
    };
    ECDH.prototype.getPublicKey = function(encoding, _format) {
        var b = Buffer.from(this._pub || []);
        return encoding ? b.toString(encoding) : b;
    };
    ECDH.prototype.getPrivateKey = function(encoding) {
        var b = Buffer.from(this._priv || []);
        return encoding ? b.toString(encoding) : b;
    };
    ECDH.prototype.setPrivateKey = function(priv, encoding) {
        this._priv = encoding ? _bytesFromKeyish(Buffer.from(priv, encoding)) : _bytesFromKeyish(priv);
        return this;
    };
    ECDH.prototype.computeSecret = function(otherPub, inputEnc, outputEnc) {
        var pubBytes = inputEnc ? _bytesFromKeyish(Buffer.from(otherPub, inputEnc)) : _bytesFromKeyish(otherPub);
        if (!this._priv) {
            var e = new Error('createECDH: no private key — call generateKeys() first');
            e.code = 'ERR_CRYPTO_INCOMPATIBLE_KEY';
            throw e;
        }
        var shared = _b64UrlToBytes(_hostSubtle('ecdh:derive', [
            new TextEncoder().encode(this._curve),
            this._priv,
            pubBytes,
        ]));
        var b = Buffer.from(shared);
        return outputEnc ? b.toString(outputEnc) : b;
    };
    exports.createECDH = ECDH;
    exports.ECDH = ECDH;

    /// Classical Diffie-Hellman (`createDiffieHellman`,
    /// `createDiffieHellmanGroup`, `getDiffieHellman`). Modular
    /// arithmetic on big integers — host-side via the existing
    /// `crypto.generatePrime` / `crypto.checkPrime` machinery. We
    /// implement enough to make the canonical 2048-bit MODP groups
    /// (`modp14`, `modp15`, `modp16`) work for legacy code that
    /// still uses them.
    var _MODP_GROUPS = {
        // RFC 3526 §3 — 2048-bit MODP group (MODP14).
        modp14: {
            prime_hex: 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF',
            generator: 2,
        },
        modp15: {
            prime_hex: 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF',
            generator: 2,
        },
    };
    function DiffieHellmanGroup(name) {
        if (!(this instanceof DiffieHellmanGroup)) return new DiffieHellmanGroup(name);
        var g = _MODP_GROUPS[name];
        if (!g) {
            var e = new Error('crypto.getDiffieHellman: unknown group ' + name);
            e.code = 'ERR_CRYPTO_UNKNOWN_DH_GROUP';
            throw e;
        }
        this.name = name;
        this._prime = BigInt('0x' + g.prime_hex);
        this._generator = BigInt(g.generator);
        this._priv = null;
        this._pub = null;
    }
    function _bytesFromBigInt(n) {
        var hex = n.toString(16);
        if (hex.length % 2 !== 0) hex = '0' + hex;
        return new Uint8Array(Buffer.from(hex, 'hex'));
    }
    function _bigIntFromBytes(bytes) {
        var b = new Uint8Array(bytes);
        var hex = '';
        for (var i = 0; i < b.length; i++) hex += ('0' + b[i].toString(16)).slice(-2);
        return BigInt('0x' + (hex || '0'));
    }
    function _modPow(base, exp, mod) {
        // Standard square-and-multiply, BigInt-native.
        var result = 1n;
        base = base % mod;
        while (exp > 0n) {
            if (exp & 1n) result = (result * base) % mod;
            exp >>= 1n;
            base = (base * base) % mod;
        }
        return result;
    }
    DiffieHellmanGroup.prototype.generateKeys = function(encoding) {
        // Pick a random ~256-bit private exponent. Real OpenSSL uses
        // a 2 ≤ x < p-1 range; we approximate with 32 random bytes
        // which is well within the safe zone for 2048-bit primes.
        var rb = exports.randomBytes(32);
        this._priv = _bigIntFromBytes(rb) % (this._prime - 2n) + 2n;
        this._pub = _modPow(this._generator, this._priv, this._prime);
        return this.getPublicKey(encoding);
    };
    DiffieHellmanGroup.prototype.computeSecret = function(other, inputEnc, outputEnc) {
        if (!this._priv) {
            var e = new Error('DH.computeSecret: generateKeys() first');
            e.code = 'ERR_CRYPTO_INCOMPATIBLE_KEY';
            throw e;
        }
        var pubBytes = inputEnc ? _bytesFromKeyish(Buffer.from(other, inputEnc)) : _bytesFromKeyish(other);
        var pub = _bigIntFromBytes(pubBytes);
        var shared = _modPow(pub, this._priv, this._prime);
        var b = Buffer.from(_bytesFromBigInt(shared));
        return outputEnc ? b.toString(outputEnc) : b;
    };
    DiffieHellmanGroup.prototype.getPublicKey = function(encoding) {
        if (!this._pub) return null;
        var b = Buffer.from(_bytesFromBigInt(this._pub));
        return encoding ? b.toString(encoding) : b;
    };
    DiffieHellmanGroup.prototype.getPrivateKey = function(encoding) {
        if (!this._priv) return null;
        var b = Buffer.from(_bytesFromBigInt(this._priv));
        return encoding ? b.toString(encoding) : b;
    };
    DiffieHellmanGroup.prototype.getPrime = function(encoding) {
        var b = Buffer.from(_bytesFromBigInt(this._prime));
        return encoding ? b.toString(encoding) : b;
    };
    DiffieHellmanGroup.prototype.getGenerator = function(encoding) {
        var b = Buffer.from(_bytesFromBigInt(this._generator));
        return encoding ? b.toString(encoding) : b;
    };
    DiffieHellmanGroup.prototype.setPrivateKey = function(priv, encoding) {
        var bs = encoding ? _bytesFromKeyish(Buffer.from(priv, encoding)) : _bytesFromKeyish(priv);
        this._priv = _bigIntFromBytes(bs);
        this._pub = _modPow(this._generator, this._priv, this._prime);
        return this;
    };
    DiffieHellmanGroup.prototype.setPublicKey = function(pub, encoding) {
        var bs = encoding ? _bytesFromKeyish(Buffer.from(pub, encoding)) : _bytesFromKeyish(pub);
        this._pub = _bigIntFromBytes(bs);
        return this;
    };
    DiffieHellmanGroup.prototype.verifyError = 0;

    function DiffieHellman(prime, primeEncoding, generator, generatorEncoding) {
        if (!(this instanceof DiffieHellman)) {
            return new DiffieHellman(prime, primeEncoding, generator, generatorEncoding);
        }
        // Constructor with custom prime: prime can be a number (bit
        // length, generate one) or a Buffer/string (raw prime).
        if (typeof prime === 'number') {
            var bits = prime | 0;
            var hex = globalThis.__host_crypto_generate_prime
                ? globalThis.__host_crypto_generate_prime(bits, false)
                : null;
            if (typeof hex !== 'string' || hex.indexOf('__HOST_ERR__:') === 0) {
                var e = new Error('createDiffieHellman: failed to generate prime');
                e.code = 'ERR_CRYPTO_OPERATION_FAILED';
                throw e;
            }
            this._prime = BigInt('0x' + hex);
        } else {
            var pb = primeEncoding ? _bytesFromKeyish(Buffer.from(prime, primeEncoding))
                                   : _bytesFromKeyish(prime);
            this._prime = _bigIntFromBytes(pb);
        }
        if (generator == null) {
            this._generator = 2n;
        } else if (typeof generator === 'number') {
            this._generator = BigInt(generator);
        } else {
            var gb = generatorEncoding ? _bytesFromKeyish(Buffer.from(generator, generatorEncoding))
                                       : _bytesFromKeyish(generator);
            this._generator = _bigIntFromBytes(gb);
        }
        this._priv = null;
        this._pub = null;
        this.verifyError = 0;
    }
    DiffieHellman.prototype = Object.create(DiffieHellmanGroup.prototype);
    DiffieHellman.prototype.constructor = DiffieHellman;

    exports.createDiffieHellman = function(prime, primeEnc, generator, genEnc) {
        return new DiffieHellman(prime, primeEnc, generator, genEnc);
    };
    exports.createDiffieHellmanGroup = function(name) { return new DiffieHellmanGroup(name); };
    exports.getDiffieHellman = exports.createDiffieHellmanGroup;
    exports.DiffieHellman = DiffieHellman;
    exports.DiffieHellmanGroup = DiffieHellmanGroup;

    /// `X509Certificate` — Node 15.6+. Real cert parsing requires
    /// ASN.1 + X.509 walking. We surface a usable subset: parses the
    /// PEM/DER, exposes `.raw` (DER bytes), `.toString()` (PEM), and
    /// the most-probed subject/issuer/serialNumber/validFrom/validTo
    /// fields via a minimal-viable ASN.1 walk that pulls out the
    /// printable strings.
    function X509Certificate(input) {
        if (!(this instanceof X509Certificate)) return new X509Certificate(input);
        var der = _stripPemBody(input);
        Object.defineProperty(this, 'raw', { value: Buffer.from(der), enumerable: true });
        // Surface the bytes as a PEM toString() — most use sites care
        // only about round-tripping the on-disk cert.
        var b64 = Buffer.from(der).toString('base64');
        var pem = '-----BEGIN CERTIFICATE-----\n';
        for (var i = 0; i < b64.length; i += 64) pem += b64.slice(i, i + 64) + '\n';
        pem += '-----END CERTIFICATE-----\n';
        Object.defineProperty(this, '_pem', { value: pem, enumerable: false });
        // Best-effort ASN.1 string scan: walk the DER bytes pulling
        // every PrintableString / UTF8String / IA5String we find, in
        // order. The first two are subject/issuer in practice; later
        // ones are SAN dnsNames.
        var strings = [];
        var i2 = 0;
        while (i2 < der.length - 2) {
            var tag = der[i2], len = der[i2 + 1];
            if ((tag === 0x13 || tag === 0x0c || tag === 0x16) && len > 0 && len < 128
                && i2 + 2 + len <= der.length) {
                var s = '';
                for (var j = 0; j < len; j++) s += String.fromCharCode(der[i2 + 2 + j]);
                strings.push(s);
                i2 += 2 + len;
            } else {
                i2 += 1;
            }
        }
        Object.defineProperty(this, 'subject',
            { value: strings[1] ? 'CN=' + strings[1] : '', enumerable: true });
        Object.defineProperty(this, 'issuer',
            { value: strings[0] ? 'CN=' + strings[0] : '', enumerable: true });
        Object.defineProperty(this, 'subjectAltName',
            { value: strings.slice(2).join(', '), enumerable: true });
        // serialNumber / validFrom / validTo — without a full ASN.1
        // parser we can't pinpoint them; expose '' so probes don't
        // crash.
        Object.defineProperty(this, 'serialNumber', { value: '', enumerable: true });
        Object.defineProperty(this, 'validFrom', { value: '', enumerable: true });
        Object.defineProperty(this, 'validTo', { value: '', enumerable: true });
    }
    X509Certificate.prototype.toString = function() { return this._pem; };
    X509Certificate.prototype.toLegacyObject = function() {
        return {
            subject: this.subject,
            issuer: this.issuer,
            subjectaltname: this.subjectAltName,
            raw: this.raw,
        };
    };
    X509Certificate.prototype.toJSON = function() { return this._pem; };
    X509Certificate.prototype.checkHost = function() { return undefined; };
    X509Certificate.prototype.checkEmail = function() { return undefined; };
    X509Certificate.prototype.checkIP = function() { return undefined; };
    X509Certificate.prototype.checkIssued = function() { return false; };
    X509Certificate.prototype.checkPrivateKey = function() { return false; };
    X509Certificate.prototype.verify = function() { return false; };
    Object.defineProperty(X509Certificate.prototype, 'publicKey', {
        get: function() {
            // Public key extraction would need an ASN.1 walker we don't
            // ship; expose a KeyObject wrapping the raw DER so callers
            // that just want to ferry bytes around still work.
            return new KeyObject('public', undefined, new Uint8Array(this.raw));
        },
    });
    Object.defineProperty(X509Certificate.prototype, 'fingerprint', {
        get: function() {
            var h = exports.createHash('sha1');
            h.update(this.raw);
            return h.digest('hex').toUpperCase().match(/.{2}/g).join(':');
        },
    });
    Object.defineProperty(X509Certificate.prototype, 'fingerprint256', {
        get: function() {
            var h = exports.createHash('sha256');
            h.update(this.raw);
            return h.digest('hex').toUpperCase().match(/.{2}/g).join(':');
        },
    });
    Object.defineProperty(X509Certificate.prototype, 'fingerprint512', {
        get: function() {
            var h = exports.createHash('sha512');
            h.update(this.raw);
            return h.digest('hex').toUpperCase().match(/.{2}/g).join(':');
        },
    });
    exports.X509Certificate = X509Certificate;
    /// `crypto.checkPrimeSync(candidate, options?)` — Miller-Rabin
    /// primality test. Accepts `BigInt`, `number`, `Buffer` (BE bytes),
    /// `Uint8Array`. Node's `options.checks` is honoured (default 0 →
    /// host picks 40 rounds for ≤2^-80 false-positive probability).
    function _candidateToHex(c) {
        if (typeof c === 'bigint') {
            var s = c.toString(16);
            if (s.length % 2 !== 0) s = '0' + s;
            return s;
        }
        if (typeof c === 'number') {
            if (!Number.isFinite(c) || c < 0) return '00';
            var s2 = Math.floor(c).toString(16);
            if (s2.length % 2 !== 0) s2 = '0' + s2;
            return s2;
        }
        if (c instanceof ArrayBuffer) c = new Uint8Array(c);
        if (ArrayBuffer.isView(c) || c instanceof Uint8Array
            || (typeof Buffer !== 'undefined' && Buffer.isBuffer(c))) {
            var bytes = (typeof Buffer !== 'undefined' && Buffer.isBuffer(c))
                ? c : new Uint8Array(c.buffer, c.byteOffset, c.byteLength);
            var hex = '';
            for (var i = 0; i < bytes.length; i++) {
                hex += ('0' + bytes[i].toString(16)).slice(-2);
            }
            return hex || '00';
        }
        throw new TypeError('checkPrime: candidate must be number / BigInt / Buffer');
    }
    exports.checkPrimeSync = function(p, options) {
        var checks = (options && (options.checks | 0)) || 0;
        var hex = _candidateToHex(p);
        if (typeof globalThis.__host_crypto_check_prime !== 'function') {
            throw new Error('crypto.checkPrimeSync: host fn missing');
        }
        var r = globalThis.__host_crypto_check_prime(hex, checks);
        if (r < 0) throw new Error('checkPrime: host error code ' + r);
        return r === 1;
    };
    exports.checkPrime = function(p, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        Promise.resolve().then(function() {
            try { cb(null, exports.checkPrimeSync(p, options)); }
            catch (e) { cb(e); }
        });
    };
    /// `crypto.generatePrimeSync(size, options?)` — Generate a probable
    /// prime of `size` bits. `options.safe` requires `(p-1)/2` also
    /// prime. Returns BigInt by default (matches Node 15+).
    exports.generatePrimeSync = function(size, options) {
        if (typeof globalThis.__host_crypto_generate_prime !== 'function') {
            throw new Error('crypto.generatePrimeSync: host fn missing');
        }
        var safe = !!(options && options.safe);
        var hex = globalThis.__host_crypto_generate_prime(size | 0, safe);
        if (typeof hex === 'string' && hex.indexOf('__HOST_ERR__:') === 0) {
            throw new Error(hex.slice('__HOST_ERR__:'.length));
        }
        if (options && options.bigint === false) {
            // Buffer of BE bytes when the caller opts out of BigInt.
            return Buffer.from(hex, 'hex');
        }
        return BigInt('0x' + hex);
    };
    exports.generatePrime = function(size, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        Promise.resolve().then(function() {
            try { cb(null, exports.generatePrimeSync(size, options)); }
            catch (e) { cb(e); }
        });
    };
    exports.secureHeapUsed = function() {
        return { total: 0, min: 0, used: 0, utilization: 0 };
    };
    exports.setEngine = function(name, _flags) {
        var n = String(name || '').toLowerCase();
        if (n === '' || n === 'default' || n === 'dynamic') return;
        var e = new Error("burn doesn't link OpenSSL — we don't want to compromise");
        e.code = 'ERR_CRYPTO_ENGINE_UNKNOWN';
        throw e;
    };
    exports.setFips = function(enabled) {
        if (!enabled) return;
        var e = new Error("burn doesn't link OpenSSL — we don't want to compromise");
        e.code = 'ERR_CRYPTO_FIPS_UNAVAILABLE';
        throw e;
    };
    // Node's `crypto.getFips()` returns 1/0 (number); `crypto.fips`
    // is the boolean shorthand exposed since Node 0.12. Both are
    // false on non-FIPS Node builds — we mirror that exactly so
    // libraries that gate behaviour on either form see the same
    // answer as in stock Node.
    exports.getFips = function() { return 0; };
    Object.defineProperty(exports, 'fips', {
        get: function() { return false; },
        set: function(v) { exports.setFips(!!v); },
        enumerable: true,
        configurable: true,
    });

    // ---- crypto.constants -----------------------------------------
    //
    // Subset that real-world packages probe: OpenSSL flag bits + the
    // signing/padding scheme constants used by `crypto.sign` /
    // `subtle.sign` callers. Burn doesn't use these for gating
    // (the host-side rust-crypto crates encode the algorithm in the
    // call shape), but exposing them keeps `require('crypto').constants.RSA_PKCS1_PADDING`
    // probes from being `undefined` and crashing.
    exports.constants = {
        // SSL options
        SSL_OP_ALL: 0x80000bff,
        SSL_OP_NO_SSLv2: 0x01000000,
        SSL_OP_NO_SSLv3: 0x02000000,
        SSL_OP_NO_TLSv1: 0x04000000,
        SSL_OP_NO_TLSv1_1: 0x10000000,
        SSL_OP_NO_TLSv1_2: 0x08000000,
        SSL_OP_NO_TLSv1_3: 0x20000000,
        // RSA padding
        RSA_PKCS1_PADDING: 1,
        RSA_SSLV23_PADDING: 2,
        RSA_NO_PADDING: 3,
        RSA_PKCS1_OAEP_PADDING: 4,
        RSA_X931_PADDING: 5,
        RSA_PKCS1_PSS_PADDING: 6,
        // PSS salt
        RSA_PSS_SALTLEN_DIGEST: -1,
        RSA_PSS_SALTLEN_MAX_SIGN: -2,
        RSA_PSS_SALTLEN_AUTO: -2,
        // DH point formats
        POINT_CONVERSION_COMPRESSED: 2,
        POINT_CONVERSION_UNCOMPRESSED: 4,
        POINT_CONVERSION_HYBRID: 6,
        // Hash algorithms (for crypto.diffieHellman)
        ENGINE_METHOD_NONE: 0x00,
        ENGINE_METHOD_ALL: 0xffff,
        DH_CHECK_P_NOT_SAFE_PRIME: 2,
        DH_CHECK_P_NOT_PRIME: 1,
        DH_NOT_SUITABLE_GENERATOR: 8,
        DH_UNABLE_TO_CHECK_GENERATOR: 4,
        defaultCoreCipherList:
            'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:'
            + 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:'
            + 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384',
    };
});

// ---- dgram.js ----
// dgram — Node 20's UDP socket module. The host-side coordinator
// (`crates/afterburner-wasi/src/daemon_dgram.rs`) owns every
// `tokio::net::UdpSocket`; this polyfill is a thin EventEmitter
// façade. `dgram` requires daemon mode (the coordinator is tokio-
// backed); calling `bind` / `send` from library mode surfaces a clear
// `ERR_NO_DAEMON` rather than silently dropping packets.
//
// What works today: bind / address / send / close + `'listening'`
// and `'close'` events. Inbound `'message'` event delivery requires
// the CLI's daemon-event translator to route `dgram-message`
// envelopes through `__ab_dgram_handlers`; until that lands, sockets
// can be bound and used to *send* but won't observe inbound packets.

(function bootstrapDgramGlobals() {
    if (!globalThis.__ab_dgram_handlers) globalThis.__ab_dgram_handlers = {};
})();

__register_module('dgram', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;
    var Buffer = require('buffer').Buffer;

    function mapHostErrorCode(rc) {
        switch (rc) {
            case -1: return 'ENO_DAEMON';
            case -2: return 'EACCES';
            case -3: return 'EBADID';
            case -4: return 'EINVAL';
            case -5: return 'EINVAL';
            case -6: return 'EINVAL';
            default: return 'EOTHER';
        }
    }

    function makeError(rc, prefix) {
        var detail = '';
        if (typeof globalThis.__host_last_error === 'function') {
            detail = globalThis.__host_last_error();
        }
        var msg = detail ? (prefix + ': ' + detail) : prefix;
        var err = new Error(msg);
        err.code = mapHostErrorCode(rc);
        return err;
    }

    function Socket(opts) {
        EventEmitter.call(this);
        opts = opts || {};
        this.type = (typeof opts === 'string') ? opts : (opts.type || 'udp4');
        this._reuseAddr = !!opts.reuseAddr;
        this._ipv6Only = !!opts.ipv6Only;
        this._socketId = 0;
        this._bound = false;
        this._closed = false;
    }
    Socket.prototype = Object.create(EventEmitter.prototype);
    Socket.prototype.constructor = Socket;

    function ensureHost(name) {
        var fn = globalThis['__host_dgram_' + name];
        if (typeof fn !== 'function') {
            var err = new Error(
                'dgram.' + name + ': host coordinator not installed (daemon mode required)'
            );
            err.code = 'ERR_NO_DAEMON';
            throw err;
        }
        return fn;
    }

    Socket.prototype.bind = function(port, address, callback) {
        if (typeof port === 'function') { callback = port; port = 0; address = undefined; }
        else if (typeof address === 'function') { callback = address; address = undefined; }
        if (this._bound) {
            var bindErr = new Error('dgram.bind: socket already bound');
            bindErr.code = 'ERR_SOCKET_ALREADY_BOUND';
            if (typeof callback === 'function') {
                Promise.resolve().then(function() { callback(bindErr); });
            }
            throw bindErr;
        }
        port = port | 0;
        address = address || (this.type === 'udp6' ? '::' : '0.0.0.0');
        var fn;
        try { fn = ensureHost('bind'); }
        catch (e) {
            var self0 = this;
            Promise.resolve().then(function() { try { self0.emit('error', e); } catch (_) {} });
            if (typeof callback === 'function') Promise.resolve().then(function() { callback(e); });
            return this;
        }
        var rc = fn(String(address), port);
        if (rc < 0) {
            var err = makeError(rc, 'dgram.bind');
            var self = this;
            Promise.resolve().then(function() { try { self.emit('error', err); } catch (_) {} });
            if (typeof callback === 'function') Promise.resolve().then(function() { callback(err); });
            return this;
        }
        this._socketId = rc;
        this._bound = true;
        globalThis.__ab_dgram_handlers[this._socketId] = this;
        var self2 = this;
        Promise.resolve().then(function() {
            try { self2.emit('listening'); } catch (_) {}
            if (typeof callback === 'function') callback();
        });
        return this;
    };

    Socket.prototype.send = function(msg /*, [offset, length,] port, address, callback */) {
        var args = Array.prototype.slice.call(arguments, 1);
        var callback = (args.length && typeof args[args.length - 1] === 'function')
            ? args.pop() : null;
        // Argument shapes:
        //   send(msg, port[, address][, cb])
        //   send(msg, offset, length, port[, address][, cb])
        var port, address;
        if (args.length >= 3) {
            // (offset, length, port[, address])
            var offset = args[0] | 0;
            var length = args[1] | 0;
            port = args[2] | 0;
            address = args[3];
            if (typeof msg === 'string') msg = Buffer.from(msg, 'utf8');
            if (!Buffer.isBuffer(msg)) msg = Buffer.from(msg);
            msg = msg.slice(offset, offset + length);
        } else {
            // (port[, address])
            port = args[0] | 0;
            address = args[1];
            if (typeof msg === 'string') msg = Buffer.from(msg, 'utf8');
            if (!Buffer.isBuffer(msg)) msg = Buffer.from(msg);
        }
        address = address || (this.type === 'udp6' ? '::1' : '127.0.0.1');
        if (!this._bound) {
            // Implicit bind to ephemeral port — matches Node.
            try { this.bind(0); }
            catch (e) {
                if (callback) Promise.resolve().then(function() { callback(e); });
                return;
            }
        }
        var fn;
        try { fn = ensureHost('send'); }
        catch (e) {
            if (callback) Promise.resolve().then(function() { callback(e); });
            else throw e;
            return;
        }
        var b64 = msg.toString('base64');
        var rc = fn(this._socketId, String(address), port, b64);
        var self = this;
        if (rc < 0) {
            var err = makeError(rc, 'dgram.send');
            if (callback) Promise.resolve().then(function() { callback(err); });
            else Promise.resolve().then(function() {
                try { self.emit('error', err); } catch (_) {}
            });
            return;
        }
        if (callback) Promise.resolve().then(function() { callback(null, rc); });
    };

    Socket.prototype.close = function(callback) {
        if (this._closed) {
            if (typeof callback === 'function') Promise.resolve().then(function() { callback(); });
            return this;
        }
        this._closed = true;
        if (this._socketId) {
            try { ensureHost('close')(this._socketId); } catch (_) {}
            delete globalThis.__ab_dgram_handlers[this._socketId];
        }
        var self = this;
        Promise.resolve().then(function() {
            try { self.emit('close'); } catch (_) {}
            if (typeof callback === 'function') callback();
        });
        return this;
    };

    Socket.prototype.address = function() {
        if (!this._bound) {
            var e = new Error('Not running');
            e.code = 'ERR_SOCKET_DGRAM_NOT_RUNNING';
            throw e;
        }
        var fn;
        try { fn = ensureHost('address'); }
        catch (_) {
            return { address: '0.0.0.0', port: 0, family: this.type === 'udp6' ? 'IPv6' : 'IPv4' };
        }
        var raw = fn(this._socketId);
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            var err = new Error('dgram.address: ' + raw.slice('__HOST_ERR__:'.length));
            err.code = 'EOTHER';
            throw err;
        }
        try {
            var parsed = JSON.parse(raw);
            return {
                address: parsed.address,
                port: parsed.port,
                family: this.type === 'udp6' ? 'IPv6' : 'IPv4',
            };
        } catch (e) {
            var err2 = new Error('dgram.address: malformed host response');
            err2.code = 'EOTHER';
            throw err2;
        }
    };

    // Hook for the daemon-event dispatcher (not yet wired) to deliver
    // inbound 'message' events. The CLI's translator will call this
    // when a dgram-message envelope arrives.
    Socket.prototype._dispatchMessage = function(payloadB64, fromAddress, fromPort) {
        var msg;
        try { msg = Buffer.from(payloadB64, 'base64'); }
        catch (_) { return; }
        var rinfo = {
            address: fromAddress,
            port: fromPort,
            family: (fromAddress && fromAddress.indexOf(':') >= 0) ? 'IPv6' : 'IPv4',
            size: msg.length,
        };
        try { this.emit('message', msg, rinfo); } catch (_) {}
    };
    Socket.prototype._dispatchError = function(message) {
        var err = new Error(message || 'dgram error');
        err.code = 'EOTHER';
        try { this.emit('error', err); } catch (_) {}
    };

    // Unsupported / no-op options. UDP socket options below the
    // bind/send line aren't needed for the canonical use cases
    // (metrics push, request-response loops) and would expand the
    // host coordinator's surface for marginal value. They no-op so
    // libraries that defensively call them don't crash.
    Socket.prototype.connect = function() { throw notWired('connect'); };
    Socket.prototype.disconnect = function() { throw notWired('disconnect'); };
    Socket.prototype.remoteAddress = function() { throw notWired('remoteAddress'); };
    Socket.prototype.setBroadcast = function() {};
    Socket.prototype.setTTL = function() {};
    Socket.prototype.setMulticastTTL = function() {};
    Socket.prototype.setMulticastInterface = function() {};
    Socket.prototype.setMulticastLoopback = function() {};
    Socket.prototype.addMembership = function() {};
    Socket.prototype.dropMembership = function() {};
    Socket.prototype.addSourceSpecificMembership = function() {};
    Socket.prototype.dropSourceSpecificMembership = function() {};
    Socket.prototype.setRecvBufferSize = function() {};
    Socket.prototype.setSendBufferSize = function() {};
    Socket.prototype.getRecvBufferSize = function() { return 0; };
    Socket.prototype.getSendBufferSize = function() { return 0; };
    Socket.prototype.ref = function() { return this; };
    Socket.prototype.unref = function() { return this; };

    function notWired(name) {
        var e = new Error(
            'dgram.Socket.' + name + ' is not wired in burn — implementations focus '
            + 'on canonical bind/send use cases. File an issue if you need this.'
        );
        e.code = 'ERR_NOT_IMPLEMENTED';
        return e;
    }

    function createSocket(opts, callback) {
        var sock = new Socket(opts);
        if (typeof callback === 'function') sock.on('message', callback);
        return sock;
    }

    exports.createSocket = createSocket;
    exports.Socket = Socket;
});

// ---- dns.js ----
// dns — synchronous host-backed lookups, presented through Node's
// dual callback / promise API.
//
// API coverage:
//
//   dns.lookup(host[, opts], cb)        — A/AAAA via system resolver
//   dns.resolve(host[, rrtype], cb)     — dispatcher for record types
//   dns.resolve4 / resolve6             — A / AAAA arrays
//   dns.resolveMx                       — [{exchange, priority}]
//   dns.resolveTxt                      — [["fragment", ...], ...]
//   dns.resolveCname / resolveNs        — [hostname, ...]
//   dns.reverse(ip, cb)                 — PTR records
//   dns.promises.{lookup,resolve*,reverse}  — Promise-returning twins
//
// We have no event loop, so callbacks fire synchronously inside the
// resolver call; the Promise versions wrap the same result. The host
// applies a per-call timeout (`Manifold.http_timeout_ms`) so a hung
// resolver can never wedge the runtime.
//
// Error shape matches Node where it matters: `e.code` carries
// 'ENODATA' / 'ENOTFOUND' / 'EACCES' depending on what went wrong.
// The host-side `__HOST_ERR__:` prefix is unwrapped here so user
// callbacks see plain `Error` instances.

__register_module('dns', function(module, exports, require) {

    // ---- error wrapping --------------------------------------------

    function isHostErr(s) {
        return typeof s === 'string' && s.indexOf('__HOST_ERR__:') === 0;
    }

    function hostErrToError(s, hostname) {
        var msg = s.slice('__HOST_ERR__:'.length);
        var code;
        // Heuristic mapping — the host returns kind-tagged strings in
        // most paths. PermissionDenied → EACCES; everything else
        // (timeouts, NXDOMAIN, garbage records) → ENODATA.
        if (/PermissionDenied/i.test(msg) || /Permission denied/i.test(msg)) {
            code = 'EACCES';
        } else if (/timed out/i.test(msg)) {
            code = 'ETIMEOUT';
        } else if (/no result|no record/i.test(msg)) {
            code = 'ENODATA';
        } else {
            code = 'ENODATA';
        }
        var err = new Error('dns: ' + msg);
        err.code = code;
        err.hostname = hostname;
        return err;
    }

    // ---- core call helper ------------------------------------------

    function ensureHost(name) {
        var fn = globalThis[name];
        if (typeof fn !== 'function') {
            var err = new Error('Permission denied: ' + name + ' is not available');
            err.code = 'EACCES';
            throw err;
        }
        return fn;
    }

    /// Module-level + per-Resolver server overrides. Empty string =
    /// "use the system /etc/resolv.conf", which the host falls back to
    /// Cloudflare for if the file is missing. `setServers` and
    /// `Resolver.setServers` write through to these slots.
    var _moduleServersCsv = '';

    function callJsonResolver(hostFnName, hostname, serversCsv) {
        var fn = ensureHost(hostFnName);
        var raw = fn(String(hostname), String(serversCsv || ''));
        if (isHostErr(raw)) {
            throw hostErrToError(raw, hostname);
        }
        try {
            return JSON.parse(raw);
        } catch (e) {
            var err = new Error('dns: malformed host response: ' + e.message);
            err.code = 'EBADRESP';
            throw err;
        }
    }

    function callStringResolver(hostFnName, hostname) {
        var fn = ensureHost(hostFnName);
        var raw = fn(String(hostname));
        if (isHostErr(raw)) {
            throw hostErrToError(raw, hostname);
        }
        return raw;
    }

    function serversToCsv(arr) {
        if (!Array.isArray(arr)) return '';
        return arr.map(function(s) { return String(s).trim(); })
                  .filter(function(s) { return s.length > 0; })
                  .join(',');
    }

    // ---- callback / promise dual-shape glue ------------------------

    function dual(producer) {
        // Returns a function that accepts an optional trailing
        // callback. Without a callback it returns the value (sync —
        // matches the way Node's tests of the sync path run, since we
        // have no event loop). With a callback it invokes synchronously
        // with `(null, value)` or `(err)`.
        return function() {
            var args = Array.prototype.slice.call(arguments);
            var cb;
            if (args.length && typeof args[args.length - 1] === 'function') {
                cb = args.pop();
            }
            try {
                var v = producer.apply(null, args);
                if (cb) { cb(null, v); return; }
                return v;
            } catch (e) {
                if (cb) { cb(e); return; }
                throw e;
            }
        };
    }

    function promiseOf(producer) {
        return function() {
            var args = arguments;
            return new Promise(function(resolve, reject) {
                try { resolve(producer.apply(null, args)); }
                catch (e) { reject(e); }
            });
        };
    }

    // ---- lookup (A/AAAA dispatcher) --------------------------------

    function _lookupOne(hostname) {
        return {
            address: callStringResolver('__host_dns_lookup', hostname),
            family: 4, // host returns first IP; family detection lives in resolve4/6
        };
    }

    exports.lookup = function(hostname, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        if (typeof cb === 'function') {
            try {
                var r = _lookupOne(hostname);
                cb(null, r.address, r.family);
            } catch (e) { cb(e); }
            return;
        }
        return _lookupOne(hostname);
    };

    // ---- record-type-aware resolvers -------------------------------

    function makeArrayResolver(hostFnName) {
        return function(hostname, serversCsv) {
            var v = callJsonResolver(hostFnName, hostname, serversCsv);
            if (!Array.isArray(v)) {
                var err = new Error('dns: expected array from host');
                err.code = 'EBADRESP';
                throw err;
            }
            return v;
        };
    }

    /// Module-level resolvers — fall back to the module's setServers
    /// override (or system config when none is set).
    function moduleArrayResolver(hostFnName) {
        var inner = makeArrayResolver(hostFnName);
        return function(hostname) {
            return inner(hostname, _moduleServersCsv);
        };
    }

    var _resolve4 = moduleArrayResolver('__host_dns_resolve4');
    var _resolve6 = moduleArrayResolver('__host_dns_resolve6');
    var _resolveMx = moduleArrayResolver('__host_dns_resolve_mx');
    var _resolveTxt = moduleArrayResolver('__host_dns_resolve_txt');
    var _resolveCname = moduleArrayResolver('__host_dns_resolve_cname');
    var _resolveNs = moduleArrayResolver('__host_dns_resolve_ns');
    var _reverse = function(ip) {
        return moduleArrayResolver('__host_dns_reverse')(ip);
    };

    exports.resolve4 = dual(_resolve4);
    exports.resolve6 = dual(_resolve6);
    exports.resolveMx = dual(_resolveMx);
    exports.resolveTxt = dual(_resolveTxt);
    exports.resolveCname = dual(_resolveCname);
    exports.resolveNs = dual(_resolveNs);
    exports.reverse = dual(_reverse);

    /// `dns.resolveAny(host, cb)` — Node's catch-all that returns the
    /// union of A, AAAA, MX, TXT, CNAME, NS records as a tagged array.
    /// We compose it from the typed resolvers above; if a typed
    /// resolver fails we treat its slice as empty rather than aborting
    /// the whole probe (matches Node's behaviour where some record
    /// classes don't exist for a given host).
    exports.resolveAny = function(hostname, cb) {
        var pending = 6, errors = [], results = [];
        function done() {
            if (--pending !== 0) return;
            if (results.length === 0 && errors.length > 0) {
                if (cb) cb(errors[0]); return;
            }
            if (cb) cb(null, results);
        }
        function tryType(fn, mapper) {
            fn(hostname, function(err, list) {
                if (!err && Array.isArray(list)) {
                    list.forEach(function(item) { results.push(mapper(item)); });
                } else if (err) errors.push(err);
                done();
            });
        }
        tryType(exports.resolve4, function(v) { return { type: 'A', address: v, ttl: 0 }; });
        tryType(exports.resolve6, function(v) { return { type: 'AAAA', address: v, ttl: 0 }; });
        tryType(exports.resolveMx, function(v) {
            return { type: 'MX', priority: v.priority, exchange: v.exchange };
        });
        tryType(exports.resolveTxt, function(v) { return { type: 'TXT', entries: v }; });
        tryType(exports.resolveCname, function(v) { return { type: 'CNAME', value: v }; });
        tryType(exports.resolveNs, function(v) { return { type: 'NS', value: v }; });
    };

    /// `dns.resolveCaa(host, cb)` — DNS Certification-Authority-
    /// Authorization records. Node ships this since v15.0. Our
    /// underlying resolver doesn't have a CAA host fn, so we surface
    /// an empty list (callers typically loop through the records and
    /// treat missing CAA as "any CA may issue", which is correct).
    exports.resolveCaa = function(hostname, cb) {
        Promise.resolve().then(function() { if (cb) cb(null, []); });
    };

    exports.resolveSoa = function(hostname, cb) {
        var fn = globalThis.__host_dns_resolve_soa;
        if (typeof fn !== 'function') {
            var err = new Error('dns.resolveSoa: host fn unavailable');
            err.code = 'ENOSYS';
            if (cb) Promise.resolve().then(function() { cb(err); });
            else throw err;
            return;
        }
        Promise.resolve().then(function() {
            var raw = fn(String(hostname), _moduleServersCsv);
            if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
                if (cb) cb(new Error(raw.slice('__HOST_ERR__:'.length)));
                return;
            }
            try {
                var rec = JSON.parse(raw);
                if (cb) cb(null, rec);
            } catch (e) { if (cb) cb(e); }
        });
    };

    exports.resolveSrv = function(hostname, cb) {
        Promise.resolve().then(function() { if (cb) cb(null, []); });
    };
    exports.resolvePtr = function(hostname, cb) {
        exports.reverse(hostname, cb);
    };
    exports.resolveNaptr = function(hostname, cb) {
        Promise.resolve().then(function() { if (cb) cb(null, []); });
    };

    // resolve(hostname, [rrtype], cb) — Node's umbrella entry. Default
    // rrtype is 'A'. We dispatch into the typed resolvers.
    exports.resolve = function(hostname, rrtype, cb) {
        if (typeof rrtype === 'function') { cb = rrtype; rrtype = 'A'; }
        rrtype = String(rrtype || 'A').toUpperCase();
        var fn;
        switch (rrtype) {
            case 'A':     fn = _resolve4; break;
            case 'AAAA':  fn = _resolve6; break;
            case 'MX':    fn = _resolveMx; break;
            case 'TXT':   fn = _resolveTxt; break;
            case 'CNAME': fn = _resolveCname; break;
            case 'NS':    fn = _resolveNs; break;
            default:
                var err = new Error('dns.resolve: unsupported rrtype ' + rrtype);
                err.code = 'ENOTIMP';
                if (cb) { cb(err); return; }
                throw err;
        }
        if (typeof cb === 'function') {
            try { cb(null, fn(hostname)); }
            catch (e) { cb(e); }
            return;
        }
        return fn(hostname);
    };

    /// Per-instance Resolver. `setServers([...])` plumbs through to
    /// hickory's `ResolverConfig`: every method on this Resolver
    /// targets those upstream addresses instead of the system's
    /// `/etc/resolv.conf`. Each method is bound to the instance so
    /// the right server list is captured per call.
    function Resolver() {
        this._servers = [];
        this._serversCsv = '';
    }
    Resolver.prototype.setServers = function(servers) {
        if (!Array.isArray(servers)) {
            throw new TypeError('Resolver.setServers: argument must be an array');
        }
        // Validate each entry — Node's setServers rejects malformed
        // addresses up front rather than failing on the first lookup.
        for (var i = 0; i < servers.length; i++) {
            var s = servers[i];
            if (typeof s !== 'string') {
                throw new TypeError('Resolver.setServers: each server must be a string');
            }
        }
        this._servers = servers.slice();
        this._serversCsv = serversToCsv(this._servers);
    };
    Resolver.prototype.getServers = function() {
        return this._servers.slice();
    };
    Resolver.prototype.cancel = function() { /* no-op — calls are sync */ };

    /// Build a per-instance method that captures `this._serversCsv`
    /// and dispatches to the right host import via `makeArrayResolver`.
    function instanceArrayMethod(hostFnName) {
        var inner = makeArrayResolver(hostFnName);
        return dual(function(hostname) {
            // `this` is the Resolver instance.
            return inner(hostname, this._serversCsv);
        });
    }

    // Each Resolver method is its own dual()-wrapped fn so the
    // server list goes through to the host. We can't share with
    // the module-level resolvers because those use the global
    // `_moduleServersCsv`.
    Resolver.prototype.resolve4 = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb = args.length && typeof args[args.length - 1] === 'function' ? args.pop() : null;
        try {
            var v = makeArrayResolver('__host_dns_resolve4')(args[0], this._serversCsv);
            if (cb) { cb(null, v); return; }
            return v;
        } catch (e) {
            if (cb) { cb(e); return; }
            throw e;
        }
    };
    Resolver.prototype.resolve6 = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb = args.length && typeof args[args.length - 1] === 'function' ? args.pop() : null;
        try {
            var v = makeArrayResolver('__host_dns_resolve6')(args[0], this._serversCsv);
            if (cb) { cb(null, v); return; }
            return v;
        } catch (e) {
            if (cb) { cb(e); return; }
            throw e;
        }
    };
    Resolver.prototype.resolveMx = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb = args.length && typeof args[args.length - 1] === 'function' ? args.pop() : null;
        try {
            var v = makeArrayResolver('__host_dns_resolve_mx')(args[0], this._serversCsv);
            if (cb) { cb(null, v); return; }
            return v;
        } catch (e) {
            if (cb) { cb(e); return; }
            throw e;
        }
    };
    Resolver.prototype.resolveTxt = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb = args.length && typeof args[args.length - 1] === 'function' ? args.pop() : null;
        try {
            var v = makeArrayResolver('__host_dns_resolve_txt')(args[0], this._serversCsv);
            if (cb) { cb(null, v); return; }
            return v;
        } catch (e) {
            if (cb) { cb(e); return; }
            throw e;
        }
    };
    Resolver.prototype.resolveCname = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb = args.length && typeof args[args.length - 1] === 'function' ? args.pop() : null;
        try {
            var v = makeArrayResolver('__host_dns_resolve_cname')(args[0], this._serversCsv);
            if (cb) { cb(null, v); return; }
            return v;
        } catch (e) {
            if (cb) { cb(e); return; }
            throw e;
        }
    };
    Resolver.prototype.resolveNs = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb = args.length && typeof args[args.length - 1] === 'function' ? args.pop() : null;
        try {
            var v = makeArrayResolver('__host_dns_resolve_ns')(args[0], this._serversCsv);
            if (cb) { cb(null, v); return; }
            return v;
        } catch (e) {
            if (cb) { cb(e); return; }
            throw e;
        }
    };
    Resolver.prototype.reverse = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb = args.length && typeof args[args.length - 1] === 'function' ? args.pop() : null;
        try {
            var v = makeArrayResolver('__host_dns_reverse')(args[0], this._serversCsv);
            if (cb) { cb(null, v); return; }
            return v;
        } catch (e) {
            if (cb) { cb(e); return; }
            throw e;
        }
    };
    Resolver.prototype.resolve = function(hostname, rrtype, cb) {
        if (typeof rrtype === 'function') { cb = rrtype; rrtype = 'A'; }
        rrtype = String(rrtype || 'A').toUpperCase();
        var byType = {
            'A': this.resolve4, 'AAAA': this.resolve6, 'MX': this.resolveMx,
            'TXT': this.resolveTxt, 'CNAME': this.resolveCname, 'NS': this.resolveNs,
        };
        var fn = byType[rrtype];
        if (!fn) {
            var err = new Error('dns.resolve: unsupported rrtype ' + rrtype);
            err.code = 'ENOTIMP';
            if (cb) { cb(err); return; }
            throw err;
        }
        return fn.call(this, hostname, cb);
    };

    exports.Resolver = Resolver;

    // Module-level setServers / getServers — Node exposes these on
    // both the namespace and the Resolver class. They mutate the
    // shared `_moduleServersCsv` so the next module-level call uses
    // the new list.
    exports.setServers = function(servers) {
        if (!Array.isArray(servers)) {
            throw new TypeError('dns.setServers: argument must be an array');
        }
        _moduleServersCsv = serversToCsv(servers);
    };
    exports.getServers = function() {
        return _moduleServersCsv.length === 0 ? [] : _moduleServersCsv.split(',');
    };
    exports.setDefaultResultOrder = function(order) {
        // Stable accept; Node uses this for IPv4-first vs IPv6-first
        // ordering. With record-type-specific resolvers the option
        // is mostly cosmetic for the polyfill.
        var _ = order;
    };
    exports.getDefaultResultOrder = function() { return 'verbatim'; };

    // RR-type constants — surface so callers can do `dns.A`, etc.
    exports.A = 'A';
    exports.AAAA = 'AAAA';
    exports.MX = 'MX';
    exports.TXT = 'TXT';
    exports.CNAME = 'CNAME';
    exports.NS = 'NS';
    exports.PTR = 'PTR';

    // ---- Promises mirror -------------------------------------------

    exports.promises = {
        lookup: promiseOf(_lookupOne),
        resolve4: promiseOf(_resolve4),
        resolve6: promiseOf(_resolve6),
        resolveMx: promiseOf(_resolveMx),
        resolveTxt: promiseOf(_resolveTxt),
        resolveCname: promiseOf(_resolveCname),
        resolveNs: promiseOf(_resolveNs),
        reverse: promiseOf(_reverse),
        resolve: function(hostname, rrtype) {
            return new Promise(function(resolve, reject) {
                try {
                    exports.resolve(hostname, rrtype, function(err, v) {
                        if (err) reject(err); else resolve(v);
                    });
                } catch (e) { reject(e); }
            });
        },
        Resolver: Resolver,
    };
});

// ---- domain.js ----
// domain — deprecated since Node 4 but still imported by older
// libraries (winston < 3, some Express middleware). Real Node's
// `domain` is an error-handling boundary tied to the async stack;
// without an async stack we provide a synchronous shim that runs
// the callback inline and re-throws errors with a `domain`-like
// `'error'` event.

__register_module('domain', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;

    function Domain() {
        EventEmitter.call(this);
        this.members = [];
    }
    Domain.prototype = Object.create(EventEmitter.prototype);
    Domain.prototype.constructor = Domain;

    Domain.prototype.run = function(fn) {
        try {
            return fn();
        } catch (e) {
            try { this.emit('error', e); } catch (_) {}
            throw e;
        }
    };
    Domain.prototype.add = function(emitter) { this.members.push(emitter); return this; };
    Domain.prototype.remove = function(emitter) {
        var i = this.members.indexOf(emitter);
        if (i !== -1) this.members.splice(i, 1);
        return this;
    };
    Domain.prototype.bind = function(callback) {
        var self = this;
        return function() {
            try { return callback.apply(this, arguments); }
            catch (e) { try { self.emit('error', e); } catch (_) {} throw e; }
        };
    };
    Domain.prototype.intercept = function(callback) {
        var self = this;
        return function(err) {
            if (err) {
                try { self.emit('error', err); } catch (_) {}
                return;
            }
            try {
                return callback.apply(this, Array.prototype.slice.call(arguments, 1));
            } catch (e) {
                try { self.emit('error', e); } catch (_) {}
                throw e;
            }
        };
    };
    Domain.prototype.enter = function() {};
    Domain.prototype.exit = function() {};
    Domain.prototype.dispose = function() {};

    function create() { return new Domain(); }

    exports.create = create;
    exports.createDomain = create;
    exports.Domain = Domain;
    exports.active = null;
});

// ---- events.js ----
// events — a minimal EventEmitter with the APIs scripts actually use.

__register_module('events', function(module, exports, require) {

    function EventEmitter() {
        if (!(this instanceof EventEmitter)) return new EventEmitter();
        ensureEvents(this);
        this._maxListeners = undefined;
    }

    // Lazy-init for the `_events` bag. Real Node's EventEmitter does
    // the same thing: `init()` runs at constructor-call time, but
    // every accessor method also bails out cleanly when `_events`
    // wasn't yet allocated (treats absence as empty). The npm
    // pattern of `mixin(target, EventEmitter.prototype, false)` —
    // used by Express's `merge-descriptors` to graft EventEmitter
    // methods onto a plain `app` object without running the
    // constructor — depends on this. Without it, `app.on('mount',
    // cb)` throws `cannot read property 'mount' of undefined`
    // because `this._events` was never set.
    function ensureEvents(self) {
        if (!self._events) self._events = Object.create(null);
        return self._events;
    }

    EventEmitter.prototype.setMaxListeners = function(n) {
        this._maxListeners = n;
        return this;
    };
    EventEmitter.prototype.getMaxListeners = function() {
        return this._maxListeners === undefined ? 10 : this._maxListeners;
    };

    EventEmitter.prototype.on = function(name, fn) {
        if (typeof fn !== 'function') throw new TypeError('listener must be a function');
        var events = ensureEvents(this);
        var list = events[name];
        if (!list) events[name] = [fn];
        else list.push(fn);
        return this;
    };
    EventEmitter.prototype.addListener = EventEmitter.prototype.on;

    EventEmitter.prototype.once = function(name, fn) {
        if (typeof fn !== 'function') throw new TypeError('listener must be a function');
        var self = this;
        function wrapper() {
            self.removeListener(name, wrapper);
            fn.apply(self, arguments);
        }
        wrapper.listener = fn;
        return this.on(name, wrapper);
    };

    EventEmitter.prototype.removeListener = function(name, fn) {
        if (!this._events) return this;
        var list = this._events[name];
        if (!list) return this;
        for (var i = list.length - 1; i >= 0; i--) {
            if (list[i] === fn || list[i].listener === fn) {
                list.splice(i, 1);
                break;
            }
        }
        if (list.length === 0) delete this._events[name];
        return this;
    };
    EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

    EventEmitter.prototype.removeAllListeners = function(name) {
        if (name === undefined) this._events = Object.create(null);
        else if (this._events) delete this._events[name];
        return this;
    };

    EventEmitter.prototype.emit = function(name) {
        if (!this._events) return name === 'error' ? false : false;
        var list = this._events[name];
        if (!list) return name === 'error';
        // Copy before iterating — listeners may mutate the list.
        var copy = list.slice();
        var args = new Array(arguments.length - 1);
        for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i];
        for (var j = 0; j < copy.length; j++) copy[j].apply(this, args);
        return true;
    };

    EventEmitter.prototype.listeners = function(name) {
        if (!this._events) return [];
        var list = this._events[name];
        return list ? list.slice() : [];
    };

    EventEmitter.prototype.listenerCount = function(name) {
        if (!this._events) return 0;
        var list = this._events[name];
        return list ? list.length : 0;
    };

    EventEmitter.prototype.eventNames = function() {
        return this._events ? Object.keys(this._events) : [];
    };

    EventEmitter.EventEmitter = EventEmitter;
    EventEmitter.defaultMaxListeners = 10;
    EventEmitter.captureRejectionSymbol = Symbol.for('nodejs.rejection');
    EventEmitter.errorMonitor = Symbol.for('events.errorMonitor');
    EventEmitter.captureRejections = false;

    /// events.once(emitter, name, opts?) — resolves with the args of
    /// the first emitted event of the given name. Rejects on 'error'
    /// (unless `name === 'error'`) or signal abort.
    EventEmitter.once = function(emitter, name, options) {
        return new Promise(function(resolve, reject) {
            var signal = options && options.signal;
            if (signal && signal.aborted) {
                return reject(signal.reason || new Error('Aborted'));
            }
            function onEvent() {
                cleanup();
                resolve(Array.prototype.slice.call(arguments));
            }
            function onError(err) { cleanup(); reject(err); }
            function onAbort() {
                cleanup();
                reject(signal.reason || new Error('Aborted'));
            }
            function cleanup() {
                emitter.removeListener(name, onEvent);
                if (name !== 'error') emitter.removeListener('error', onError);
                if (signal && signal.removeEventListener) {
                    signal.removeEventListener('abort', onAbort);
                }
            }
            emitter.once(name, onEvent);
            if (name !== 'error') emitter.once('error', onError);
            if (signal && signal.addEventListener) {
                signal.addEventListener('abort', onAbort, { once: true });
            }
        });
    };

    /// events.on(emitter, name, opts?) — async iterator yielding the
    /// args of every emitted `name` event until abort or 'error'.
    EventEmitter.on = function(emitter, name, options) {
        var signal = options && options.signal;
        var queue = [];
        var waiters = [];
        var done = false;
        var err = null;
        function push(args) {
            if (done) return;
            if (waiters.length) waiters.shift()({ value: args, done: false });
            else queue.push(args);
        }
        function flushDone() {
            done = true;
            while (waiters.length) {
                var w = waiters.shift();
                if (err) w(Promise.reject(err));
                else w({ value: undefined, done: true });
            }
        }
        function onEvent() { push(Array.prototype.slice.call(arguments)); }
        function onError(e) { err = e; flushDone(); cleanup(); }
        function onAbort() { err = signal.reason || new Error('Aborted'); flushDone(); cleanup(); }
        function cleanup() {
            emitter.removeListener(name, onEvent);
            if (name !== 'error') emitter.removeListener('error', onError);
            if (signal && signal.removeEventListener) {
                signal.removeEventListener('abort', onAbort);
            }
        }
        emitter.on(name, onEvent);
        if (name !== 'error') emitter.on('error', onError);
        if (signal) {
            if (signal.aborted) onAbort();
            else if (signal.addEventListener) signal.addEventListener('abort', onAbort, { once: true });
        }
        return {
            [Symbol.asyncIterator]: function() { return this; },
            next: function() {
                if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
                if (done) return err ? Promise.reject(err) : Promise.resolve({ value: undefined, done: true });
                return new Promise(function(resolve) { waiters.push(resolve); });
            },
            return: function(v) {
                done = true; cleanup();
                return Promise.resolve({ value: v, done: true });
            },
        };
    };

    EventEmitter.getEventListeners = function(target, name) {
        if (target && typeof target.listeners === 'function') return target.listeners(name);
        if (target && target._events && Array.isArray(target._events[name])) {
            return target._events[name].slice();
        }
        return [];
    };

    EventEmitter.setMaxListeners = function(n) {
        var args = Array.prototype.slice.call(arguments, 1);
        if (args.length === 0) {
            EventEmitter.defaultMaxListeners = n | 0;
            return;
        }
        for (var i = 0; i < args.length; i++) {
            if (args[i] && typeof args[i].setMaxListeners === 'function') {
                args[i].setMaxListeners(n);
            }
        }
    };
    EventEmitter.getMaxListeners = function(emitter) {
        return (emitter && typeof emitter.getMaxListeners === 'function')
            ? emitter.getMaxListeners()
            : EventEmitter.defaultMaxListeners;
    };
    EventEmitter.listenerCount = function(emitter, name) {
        return (emitter && typeof emitter.listenerCount === 'function')
            ? emitter.listenerCount(name)
            : 0;
    };

    /// `events.addAbortListener(signal, listener)` — Node 20+. Adds an
    /// abort listener and returns a disposable handle (with
    /// `Symbol.dispose`) that removes it. If the signal is already
    /// aborted, the listener fires synchronously on a microtask.
    EventEmitter.addAbortListener = function(signal, listener) {
        if (!signal || typeof listener !== 'function') {
            var e = new TypeError('events.addAbortListener: invalid arguments');
            e.code = 'ERR_INVALID_ARG_TYPE';
            throw e;
        }
        function fire(ev) { try { listener(ev); } catch (_) {} }
        if (signal.aborted) {
            Promise.resolve().then(function() { fire({ type: 'abort' }); });
        } else if (typeof signal.addEventListener === 'function') {
            signal.addEventListener('abort', fire, { once: true });
        } else if (typeof signal.once === 'function') {
            signal.once('abort', fire);
        }
        var disposer = {
            [Symbol.dispose || Symbol.for('Symbol.dispose')]: function() {
                if (typeof signal.removeEventListener === 'function') {
                    signal.removeEventListener('abort', fire);
                } else if (typeof signal.off === 'function') {
                    signal.off('abort', fire);
                }
            },
        };
        return disposer;
    };

    /// `EventEmitterAsyncResource` — Node 17.4+. EventEmitter that
    /// runs every emit() inside an `AsyncResource` scope so
    /// `AsyncLocalStorage` propagates through listeners. We sit on
    /// top of `async_hooks.AsyncResource` (already polyfilled).
    function EventEmitterAsyncResource(options) {
        EventEmitter.call(this, options);
        var ah = require('async_hooks');
        var name = (options && options.name) || 'EventEmitterAsyncResource';
        var triggerAsyncId = options && options.triggerAsyncId;
        var requireManualDestroy = options && options.requireManualDestroy;
        this._asyncResource = new ah.AsyncResource(name, {
            triggerAsyncId: triggerAsyncId,
            requireManualDestroy: requireManualDestroy,
        });
    }
    EventEmitterAsyncResource.prototype = Object.create(EventEmitter.prototype);
    EventEmitterAsyncResource.prototype.constructor = EventEmitterAsyncResource;

    EventEmitterAsyncResource.prototype.emit = function() {
        var args = arguments;
        var self = this;
        var ar = this._asyncResource;
        // `runInAsyncScope` invokes its callback inside the AsyncResource
        // — listeners run with the right async ID for ALS to propagate.
        return ar.runInAsyncScope(function() {
            return EventEmitter.prototype.emit.apply(self, args);
        });
    };
    EventEmitterAsyncResource.prototype.emitDestroy = function() {
        return this._asyncResource.emitDestroy();
    };
    Object.defineProperty(EventEmitterAsyncResource.prototype, 'asyncId', {
        get: function() { return this._asyncResource.asyncId(); },
    });
    Object.defineProperty(EventEmitterAsyncResource.prototype, 'triggerAsyncId', {
        get: function() { return this._asyncResource.triggerAsyncId(); },
    });
    Object.defineProperty(EventEmitterAsyncResource.prototype, 'asyncResource', {
        get: function() { return this._asyncResource; },
    });

    // Re-export the static helpers on the module object too — Node
    // exposes them as both `EventEmitter.once` and
    // `require('events').once`.
    module.exports = EventEmitter;
    module.exports.once = EventEmitter.once;
    module.exports.on = EventEmitter.on;
    module.exports.getEventListeners = EventEmitter.getEventListeners;
    module.exports.setMaxListeners = EventEmitter.setMaxListeners;
    module.exports.getMaxListeners = EventEmitter.getMaxListeners;
    module.exports.listenerCount = EventEmitter.listenerCount;
    module.exports.addAbortListener = EventEmitter.addAbortListener;
    module.exports.captureRejectionSymbol = EventEmitter.captureRejectionSymbol;
    module.exports.errorMonitor = EventEmitter.errorMonitor;
    module.exports.captureRejections = EventEmitter.captureRejections;
    module.exports.defaultMaxListeners = EventEmitter.defaultMaxListeners;
    module.exports.EventEmitter = EventEmitter;
    module.exports.EventEmitterAsyncResource = EventEmitterAsyncResource;
});

// ---- fetch.js ----
// fetch / Request / Response / Headers — Web API, synchronous under
// the hood (our http host is sync) but Promise-wrapped to match the
// standard interface.

(function installFetch() {
    if (typeof globalThis.fetch === 'function') return;

    function Headers(init) {
        this._m = Object.create(null);
        if (!init) return;
        if (init instanceof Headers) {
            for (var k in init._m) this._m[k] = init._m[k];
            return;
        }
        if (Array.isArray(init)) {
            for (var i = 0; i < init.length; i++) this.set(init[i][0], init[i][1]);
            return;
        }
        var keys = Object.keys(init);
        for (var j = 0; j < keys.length; j++) this.set(keys[j], init[keys[j]]);
    }
    Headers.prototype.get = function(k)       { return this._m[String(k).toLowerCase()] || null; };
    Headers.prototype.has = function(k)       { return String(k).toLowerCase() in this._m; };
    Headers.prototype.set = function(k, v)    { this._m[String(k).toLowerCase()] = String(v); };
    Headers.prototype.append = function(k, v) {
        var key = String(k).toLowerCase();
        this._m[key] = (this._m[key] ? this._m[key] + ', ' : '') + String(v);
    };
    Headers.prototype['delete'] = function(k) { delete this._m[String(k).toLowerCase()]; };
    Headers.prototype.forEach = function(cb)  {
        var keys = Object.keys(this._m);
        for (var i = 0; i < keys.length; i++) cb(this._m[keys[i]], keys[i], this);
    };
    Headers.prototype.entries = function() {
        var keys = Object.keys(this._m);
        var self = this;
        var i = 0;
        return { next: function() {
            if (i >= keys.length) return { done: true };
            var k = keys[i++];
            return { value: [k, self._m[k]], done: false };
        } };
    };
    Headers.prototype.keys = function() {
        var keys = Object.keys(this._m);
        var i = 0;
        return { next: function() {
            if (i >= keys.length) return { done: true };
            return { value: keys[i++], done: false };
        } };
    };
    Headers.prototype.values = function() {
        var keys = Object.keys(this._m);
        var self = this;
        var i = 0;
        return { next: function() {
            if (i >= keys.length) return { done: true };
            return { value: self._m[keys[i++]], done: false };
        } };
    };
    Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
    /// Headers.prototype.getSetCookie — Node 19+. Returns each
    /// Set-Cookie header as a separate array entry. Our internal
    /// storage joins same-name headers with `, `; Set-Cookie is
    /// the one header where that join is wrong per spec, but we
    /// recover by splitting on the canonical separator.
    Headers.prototype.getSetCookie = function() {
        var raw = this._m['set-cookie'];
        if (!raw) return [];
        // Split on `, ` only when the next chunk looks like a new
        // cookie name (matches `[A-Za-z0-9!#$%&'*+\-.^_`|~]+=`).
        // Single-cookie value may contain `, ` inside `Expires=...`
        // weekday names — naive split would corrupt those.
        var parts = [];
        var cur = '';
        var i = 0;
        while (i < raw.length) {
            if (raw[i] === ',' && raw[i + 1] === ' ') {
                // Lookahead: does what's next look like NAME= ?
                var j = i + 2;
                var k = j;
                while (k < raw.length && /[A-Za-z0-9!#$%&'*+\-.^_`|~]/.test(raw[k])) k++;
                if (k > j && raw[k] === '=') {
                    parts.push(cur);
                    cur = '';
                    i = j;
                    continue;
                }
            }
            cur += raw[i++];
        }
        if (cur) parts.push(cur);
        return parts;
    };

    function Request(url, init) {
        init = init || {};
        // If a Request instance is passed in, copy its fields then
        // overlay the init (matching the spec's `new Request(req,
        // {...})` cloning shape).
        if (url && typeof url === 'object' && url instanceof Request) {
            this.url = url.url;
            this.method = url.method;
            this.headers = new Headers(url.headers);
            this.body = url.body;
            this._bodyBytes = url._bodyBytes || null;
            this.signal = url.signal;
            this.redirect = url.redirect;
            this.cache = url.cache;
            this.credentials = url.credentials;
            this.mode = url.mode;
            this.referrer = url.referrer;
            this.referrerPolicy = url.referrerPolicy;
            this.integrity = url.integrity;
            this.keepalive = url.keepalive;
        } else {
            this.url = String(url);
            this.method = 'GET';
            this.headers = new Headers();
            this.body = null;
            this._bodyBytes = null;
            this.signal = null;
            this.redirect = 'follow';
            this.cache = 'default';
            this.credentials = 'same-origin';
            this.mode = 'cors';
            this.referrer = '';
            this.referrerPolicy = '';
            this.integrity = '';
            this.keepalive = false;
        }
        // Apply init overlays on top.
        if (init.method) this.method = String(init.method).toUpperCase();
        if (init.headers) this.headers = new Headers(init.headers);
        if (init.body != null) {
            // Binary BodyInit (ArrayBuffer / TypedArray / Buffer) must NOT
            // be stringified — `String(uint8array)` yields "0,97,115,…".
            // Keep the exact bytes; the send path frames them as base64
            // for the host, which decodes and sends the original bytes.
            var _b = init.body;
            if (typeof ArrayBuffer !== 'undefined' && _b instanceof ArrayBuffer) {
                this._bodyBytes = new Uint8Array(_b.slice(0));
                this.body = null;
            } else if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(_b)) {
                this._bodyBytes = new Uint8Array(
                    _b.buffer.slice(_b.byteOffset, _b.byteOffset + _b.byteLength));
                this.body = null;
            } else {
                this._bodyBytes = null;
                this.body = String(_b);
            }
        }
        if (init.signal !== undefined) this.signal = init.signal;
        if (init.redirect) this.redirect = init.redirect;
        if (init.cache) this.cache = init.cache;
        if (init.credentials) this.credentials = init.credentials;
        if (init.mode) this.mode = init.mode;
        if (init.referrer != null) this.referrer = String(init.referrer);
        if (init.referrerPolicy) this.referrerPolicy = init.referrerPolicy;
        if (init.integrity) this.integrity = init.integrity;
        if (init.keepalive !== undefined) this.keepalive = !!init.keepalive;
    }
    Request.prototype.clone = function() { return new Request(this); };
    Request.prototype.text = function() {
        if (this._bodyBytes) {
            var Buffer = require('buffer').Buffer;
            return Promise.resolve(Buffer.from(this._bodyBytes).toString('utf8'));
        }
        return Promise.resolve(this.body != null ? String(this.body) : '');
    };
    Request.prototype.json = function() {
        return this.text().then(function(s) { return JSON.parse(s); });
    };
    Request.prototype.arrayBuffer = function() {
        if (this._bodyBytes) {
            return Promise.resolve(this._bodyBytes.buffer.slice(
                this._bodyBytes.byteOffset,
                this._bodyBytes.byteOffset + this._bodyBytes.byteLength));
        }
        var Buffer = require('buffer').Buffer;
        var s = this.body != null ? String(this.body) : '';
        return Promise.resolve(Buffer.from(s, 'utf8').buffer);
    };
    Request.prototype.bytes = function() {
        return this.arrayBuffer().then(function(ab) { return new Uint8Array(ab); });
    };
    Request.prototype.blob = function() {
        var ct = (this.headers && this.headers.get && this.headers.get('content-type')) || '';
        return this.arrayBuffer().then(function(ab) { return new Blob([ab], { type: ct }); });
    };

    function Response(body, init) {
        init = init || {};
        // Body storage: prefer `_bodyB64` (authoritative raw bytes)
        // for any binary input, fall back to `_bodyText` for strings.
        // `String(uint8array)` yields `"0,97,115,…"` and corrupts
        // downstream binary consumers (e.g. `WebAssembly.instantiateStreaming(new Response(bytes))`),
        // so detect ArrayBuffer / TypedArray / Buffer up-front and
        // base64-encode the raw bytes.
        this._bodyText = '';
        this._bodyB64 = init.bodyB64 || null;
        this._bodyStream = null;
        if (body != null && this._bodyB64 === null) {
            var Buf = globalThis.Buffer || require('buffer').Buffer;
            if (typeof body === 'object' && typeof body.getReader === 'function') {
                // ReadableStream BodyInit - the `new Response(res.body, res)`
                // rebuild every fetch-based framework does (Hono, itty, ...).
                // Our own lazy streams carry the original bytes as hints, so
                // rebuilding from them is a SYNC copy; a foreign stream is
                // kept and drained on first read.
                if (body._afbB64 !== undefined || body._afbText !== undefined) {
                    this._bodyB64 = body._afbB64 != null ? body._afbB64 : null;
                    this._bodyText = body._afbText != null ? body._afbText : '';
                } else {
                    this._bodyStream = body;
                }
            } else if (body instanceof ArrayBuffer) {
                this._bodyB64 = Buf.from(new Uint8Array(body)).toString('base64');
            } else if (ArrayBuffer.isView(body)) {
                // Uint8Array / DataView / other typed arrays — copy the
                // underlying bytes (respecting byteOffset / length).
                var u8 = new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
                this._bodyB64 = Buf.from(u8).toString('base64');
            } else if (Buf.isBuffer && Buf.isBuffer(body)) {
                this._bodyB64 = body.toString('base64');
            } else {
                this._bodyText = String(body);
            }
        }
        this.status = init.status !== undefined ? init.status : 200;
        this.statusText = init.statusText || '';
        this.ok = this.status >= 200 && this.status < 300;
        this.headers = new Headers(init.headers);
        this.url = init.url || '';
        this.bodyUsed = false;
    }
    /// Drain a foreign ReadableStream body into one Buffer.
    function drainStream(stream) {
        var Buffer = require('buffer').Buffer;
        var reader = stream.getReader();
        var chunks = [];
        function pump() {
            return reader.read().then(function(r) {
                if (r.done) return Buffer.concat(chunks.map(function(c) {
                    return Buffer.isBuffer(c) ? c
                        : ArrayBuffer.isView(c) ? Buffer.from(c.buffer, c.byteOffset, c.byteLength)
                        : Buffer.from(String(c), 'utf8');
                }));
                if (r.value != null) chunks.push(r.value);
                return pump();
            });
        }
        return pump();
    }
    Response.prototype.text = function() {
        if (this.bodyUsed) return Promise.reject(new TypeError('Body already consumed'));
        this.bodyUsed = true;
        if (this._bodyStream) {
            return drainStream(this._bodyStream).then(function(buf) { return buf.toString('utf8'); });
        }
        // Decode base64 → utf8 when binary bytes are authoritative so
        // text() sees proper decoded characters rather than the lossy
        // roundtrip.
        if (this._bodyB64 !== null) {
            var Buffer = require('buffer').Buffer;
            return Promise.resolve(Buffer.from(this._bodyB64, 'base64').toString('utf8'));
        }
        return Promise.resolve(this._bodyText);
    };
    Response.prototype.json = function() {
        return this.text().then(function(s) { return JSON.parse(s); });
    };
    Response.prototype.arrayBuffer = function() {
        if (this.bodyUsed) return Promise.reject(new TypeError('Body already consumed'));
        this.bodyUsed = true;
        if (this._bodyStream) {
            return drainStream(this._bodyStream).then(function(buf) {
                return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
            });
        }
        var Buffer = require('buffer').Buffer;
        // `bodyB64` roundtrips binary losslessly; fall back to utf8
        // encode of the text view when the host didn't provide it.
        if (this._bodyB64 !== null) {
            var buf = Buffer.from(this._bodyB64, 'base64');
            return Promise.resolve(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length));
        }
        return Promise.resolve(Buffer.from(this._bodyText, 'utf8').buffer);
    };
    /// Spec accessor: `res.body` is a ReadableStream of the payload (null
    /// when there is none). Built lazily over the stored bytes and tagged
    /// with `_afbB64`/`_afbText` hints so `new Response(res.body, res)`
    /// rebuilds SYNCHRONOUSLY from the original data instead of an async
    /// drain. Accessing `body` does not consume; reading does.
    Object.defineProperty(Response.prototype, 'body', {
        configurable: true,
        get: function() {
            if (this._bodyStream) return this._bodyStream;
            if (this._bodyB64 === null && this._bodyText === '') return null;
            if (!this._afbBodyOut) {
                var b64 = this._bodyB64;
                var text = this._bodyText;
                var bytes = function() {
                    var Buffer = require('buffer').Buffer;
                    var buf = b64 !== null ? Buffer.from(b64, 'base64') : Buffer.from(text, 'utf8');
                    return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
                };
                var rs;
                if (typeof ReadableStream === 'function') {
                    rs = new ReadableStream({
                        start: function(c) { c.enqueue(bytes()); c.close(); }
                    });
                } else {
                    // Minimal duck-typed reader for hosts without streams.
                    rs = { getReader: function() {
                        var done = false;
                        return {
                            read: function() {
                                if (done) return Promise.resolve({ done: true, value: undefined });
                                done = true;
                                return Promise.resolve({ done: false, value: bytes() });
                            },
                            releaseLock: function() {},
                            cancel: function() { return Promise.resolve(); }
                        };
                    } };
                }
                rs._afbB64 = b64;
                rs._afbText = text;
                this._afbBodyOut = rs;
            }
            return this._afbBodyOut;
        }
    });

    /// `Response.prototype.bytes()` — Node 22+ shortcut that returns
    /// a Uint8Array view of the body. Avoids the arrayBuffer ↔ view
    /// round-trip dance for the common "give me bytes" case.
    Response.prototype.bytes = function() {
        return this.arrayBuffer().then(function(ab) { return new Uint8Array(ab); });
    };
    Response.prototype.blob = function() {
        var ct = (this.headers && this.headers.get && this.headers.get('content-type')) || '';
        return this.arrayBuffer().then(function(ab) {
            return new Blob([ab], { type: ct });
        });
    };
    Response.prototype.formData = function() {
        var ct = (this.headers && this.headers.get && this.headers.get('content-type')) || '';
        if (ct.indexOf('application/x-www-form-urlencoded') === -1 &&
            ct.indexOf('multipart/form-data') === -1) {
            return Promise.reject(new TypeError(
                'Response.formData: Content-Type is not application/x-www-form-urlencoded or multipart/form-data'));
        }
        return this.text().then(function(s) {
            var fd = new FormData();
            var sp = new URLSearchParams(s);
            sp.forEach(function(v, k) { fd.append(k, v); });
            return fd;
        });
    };
    Response.prototype.clone = function() {
        var r = new Response(this._bodyText, {
            status: this.status,
            statusText: this.statusText,
            headers: this.headers,
            url: this.url,
            bodyB64: this._bodyB64,
        });
        return r;
    };
    /// Response.json(data, init) — Node 18.0+. Serialises `data` and
    /// returns a Response with `Content-Type: application/json`.
    Response.json = function(data, init) {
        init = init || {};
        var headers = new Headers(init.headers || {});
        if (!headers.has('content-type')) {
            headers.set('content-type', 'application/json');
        }
        return new Response(JSON.stringify(data), {
            status: init.status,
            statusText: init.statusText,
            headers: headers,
            url: init.url,
        });
    };
    /// Response.error() — Node 18.0+. Synthesises a network-error
    /// response: status 0, empty body, type 'error'.
    Response.error = function() {
        var r = new Response('', { status: 0, statusText: '' });
        r.type = 'error';
        return r;
    };
    /// Response.redirect(url, status) — Node 18.0+. Returns a Response
    /// with the URL in `Location:` and the given redirect status.
    Response.redirect = function(url, status) {
        status = status || 302;
        if (status < 300 || status >= 400) {
            throw new RangeError('Response.redirect: invalid status ' + status);
        }
        return new Response('', {
            status: status,
            headers: { Location: String(url) },
        });
    };

    function fetch(input, init) {
        var req = input instanceof Request ? input : new Request(input, init);
        if (req.signal && req.signal.aborted) {
            return Promise.reject(req.signal.reason || new Error('Aborted'));
        }
        // Resolve `blob:burn/...` URLs against the local blob URL
        // registry (populated by `URL.createObjectURL(blob)`). No
        // network capability needed since the bytes are already
        // in-memory.
        if (req.url && req.url.indexOf('blob:') === 0
            && typeof globalThis.__ab_resolve_blob_url === 'function') {
            var blob = globalThis.__ab_resolve_blob_url(req.url);
            if (!blob) {
                return Promise.reject(new TypeError(
                    'fetch: blob URL ' + req.url + ' has been revoked or never existed'
                ));
            }
            return blob.arrayBuffer().then(function(buf) {
                var bytes = new Uint8Array(buf);
                var b64;
                try {
                    var Buf = globalThis.Buffer || require('buffer').Buffer;
                    b64 = Buf.from(bytes).toString('base64');
                } catch (_) { b64 = null; }
                var resp = new Response('', {
                    status: 200,
                    url: req.url,
                    bodyB64: b64,
                });
                if (blob.type) {
                    resp.headers.set('content-type', blob.type);
                }
                return resp;
            });
        }
        if (typeof globalThis.__host_http_request !== 'function') {
            return Promise.reject(new Error('fetch: net capability not granted'));
        }
        var raw;
        if (typeof globalThis.__host_http_request_v2 === 'function') {
            // v2: request headers travel with the request (the legacy
            // import drops them) and the body — string or binary — is
            // base64-framed so the host sends the exact original bytes.
            var BufB = globalThis.Buffer || require('buffer').Buffer;
            var bodyB64 = '';
            if (req._bodyBytes && req._bodyBytes.length) {
                bodyB64 = BufB.from(req._bodyBytes).toString('base64');
            } else if (req.body != null && req.body !== '') {
                bodyB64 = BufB.from(String(req.body), 'utf8').toString('base64');
            }
            raw = globalThis.__host_http_request_v2(
                req.method, req.url, JSON.stringify(req.headers._m), bodyB64);
        } else if (req._bodyBytes && req._bodyBytes.length) {
            return Promise.reject(new Error(
                'fetch: this host does not support binary request bodies'));
        } else {
            raw = globalThis.__host_http_request(req.method, req.url, req.body);
        }
        var parsed;
        try { parsed = JSON.parse(raw); }
        catch (e) { return Promise.reject(new Error('fetch: malformed host response: ' + e.message)); }
        if (typeof parsed.body === 'string' && parsed.body.indexOf('__HOST_ERR__:') === 0) {
            return Promise.reject(new Error('fetch: ' + parsed.body.slice('__HOST_ERR__:'.length)));
        }
        var resp = new Response(parsed.body, {
            status: parsed.status,
            url: req.url,
            bodyB64: parsed.body_b64 || null,
        });
        return Promise.resolve(resp);
    }

    globalThis.fetch = fetch;
    globalThis.Headers = Headers;
    globalThis.Request = Request;
    globalThis.Response = Response;
})();

// ---- fs.js ----
// fs — thin glue over the __host_fs_* globals installed by the engine.
// Every method throws if the host global isn't present (meaning the
// engine didn't wire fs, usually because Manifold::fs == None).
//
// The WASM plugin signals host-side errors by returning a string that
// starts with "__HOST_ERR__:" — we check for that prefix and rethrow.

__register_module('fs', function(module, exports, require) {

    function requireHost(name) {
        var fn = globalThis['__host_fs_' + name];
        if (typeof fn !== 'function') {
            var err = new Error("Permission denied: fs." + name + " is not available");
            err.code = 'EACCES';
            throw err;
        }
        return fn;
    }

    // Map a host error message to the Node.js errno `code`. The host
    // surfaces raw `std::io::Error` text, which carries BOTH a human
    // phrase ("No such file or directory") and an "(os error N)"
    // suffix; we match either form. Getting `code` right is load-
    // bearing: cacache (npm's content-addressable cache) treats a
    // missing content file as a cache MISS only when
    // `err.code === 'ENOENT'` — otherwise it rethrows the failed
    // `stat` as fatal and the entire `npm install` aborts on a cold
    // cache. tar/mkdirp similarly branch on 'EEXIST'/'ENOTDIR'/etc.
    // The "(os error N)" forms are matched WITH their parens so that
    // "(os error 2)" can't accidentally match "(os error 20/21)".
    function hostErrCode(lower) {
        if (lower.indexOf('permission denied') !== -1 || lower.indexOf('(os error 13)') !== -1) return 'EACCES';
        if (lower.indexOf('operation not permitted') !== -1 || lower.indexOf('(os error 1)') !== -1) return 'EPERM';
        if (lower.indexOf('no such file or directory') !== -1 || lower.indexOf('not found') !== -1 || lower.indexOf('(os error 2)') !== -1) return 'ENOENT';
        if (lower.indexOf('file exists') !== -1 || lower.indexOf('already exists') !== -1 || lower.indexOf('(os error 17)') !== -1) return 'EEXIST';
        if (lower.indexOf('not a directory') !== -1 || lower.indexOf('(os error 20)') !== -1) return 'ENOTDIR';
        if (lower.indexOf('is a directory') !== -1 || lower.indexOf('(os error 21)') !== -1) return 'EISDIR';
        if (lower.indexOf('directory not empty') !== -1 || lower.indexOf('(os error 39)') !== -1) return 'ENOTEMPTY';
        return undefined;
    }
    var HOST_ERRNO = { EPERM: -1, ENOENT: -2, EACCES: -13, EEXIST: -17, ENOTDIR: -20, EISDIR: -21, ENOTEMPTY: -39 };

    function checkHostError(result, op) {
        if (typeof result === 'string' && result.indexOf('__HOST_ERR__:') === 0) {
            var msg = result.slice('__HOST_ERR__:'.length);
            var err = new Error("fs." + op + ": " + msg);
            var code = hostErrCode(msg.toLowerCase());
            if (code) {
                err.code = code;
                err.errno = HOST_ERRNO[code];
            }
            throw err;
        }
        return result;
    }

    // Match Node.js exactly: the host bridge always sends bytes as
    // base64 (binary-safe wire format). The polyfill decodes and
    // converts based on the caller's encoding choice.
    //
    //   fs.readFileSync(path)              → Buffer        (Node default)
    //   fs.readFileSync(path, 'utf8')      → string
    //   fs.readFileSync(path, {encoding})  → string
    //   fs.readFileSync(path, {encoding: null}) → Buffer
    var BufferLazy;
    function bufferModule() {
        if (!BufferLazy) BufferLazy = require('buffer').Buffer;
        return BufferLazy;
    }

    function pickEncoding(options) {
        if (typeof options === 'string') return options;
        if (options && typeof options === 'object') {
            // Node treats `encoding: null` as "give me a Buffer".
            return options.encoding === undefined ? undefined : options.encoding;
        }
        return undefined;
    }

    exports.readFileSync = function(path, options) {
        var encoding = pickEncoding(options);
        // The encoding hint goes to the host so native (rquickjs)
        // bindings can short-circuit if they want; the WASM path
        // ignores it and always returns base64. Either way the
        // decode below is the source of truth.
        var b64 = requireHost('read_file_sync')(String(path), 'base64');
        b64 = checkHostError(b64, 'readFileSync');
        var Buffer = bufferModule();
        var buf = Buffer.from(b64, 'base64');
        if (encoding == null) return buf;
        return buf.toString(encoding);
    };

    exports.writeFileSync = function(path, data, options) {
        var encoding = pickEncoding(options);
        var Buffer = bufferModule();
        var bytes;
        if (Buffer.isBuffer(data)) {
            bytes = data;
        } else if (data instanceof Uint8Array) {
            bytes = Buffer.from(data);
        } else if (typeof data === 'string') {
            bytes = Buffer.from(data, encoding || 'utf8');
        } else {
            throw new TypeError('fs.writeFileSync: data must be Buffer, Uint8Array, or string');
        }
        var b64 = bytes.toString('base64');
        // Pass 'base64' through as the encoding hint (the WASM bridge
        // reads bytes from memory either way; this just keeps the
        // 3-arg shape stable for the native binding).
        var out = requireHost('write_file_sync')(String(path), b64, 'base64');
        checkHostError(out, 'writeFileSync');
    };

    exports.existsSync = function(path) {
        var fn = globalThis.__host_fs_exists_sync;
        return typeof fn === 'function' ? fn(String(path)) : false;
    };

    // Fully fleshed-out Stats object. Node's `Stats` exposes seven
    // type-test methods (isFile / isDirectory / isSymbolicLink /
    // isBlockDevice / isCharacterDevice / isSocket / isFIFO) plus a
    // handful of mode/ino/size/mtime/atime/ctime/birthtime fields and
    // their `*Ms` counterparts. Libraries like path-scurry and chokidar
    // call `entToType(s)` over every field; missing methods crash with
    // "not a function" deep in their walkers. The host gives us file/
    // directory bits via `stat_sync`; everything else is `false` (we
    // don't surface block/char/socket/fifo through the bridge today).
    function shapeStats(parsed) {
        var s = parsed || {};
        s.isFile             = wrapBool(!!s.isFile);
        s.isDirectory        = wrapBool(!!s.isDirectory);
        s.isSymbolicLink     = wrapBool(!!s.isSymbolicLink);
        s.isBlockDevice      = wrapBool(!!s.isBlockDevice);
        s.isCharacterDevice  = wrapBool(!!s.isCharacterDevice);
        s.isSocket           = wrapBool(!!s.isSocket);
        s.isFIFO             = wrapBool(!!s.isFIFO);
        if (typeof s.mode  !== 'number') s.mode  = s.isDirectory() ? 0o040755 : 0o100644;
        if (typeof s.size  !== 'number') s.size  = 0;
        if (typeof s.ino   !== 'number') s.ino   = 0;
        if (typeof s.dev   !== 'number') s.dev   = 0;
        if (typeof s.nlink !== 'number') s.nlink = 1;
        if (typeof s.uid   !== 'number') s.uid   = 0;
        if (typeof s.gid   !== 'number') s.gid   = 0;
        if (typeof s.rdev  !== 'number') s.rdev  = 0;
        if (typeof s.blksize !== 'number') s.blksize = 4096;
        if (typeof s.blocks  !== 'number') s.blocks  = Math.ceil(s.size / 512);
        // Time fields. Node exposes both `ms` numeric and Date-shaped.
        var nowMs = (typeof s.mtimeMs === 'number') ? s.mtimeMs : Date.now();
        if (typeof s.atimeMs !== 'number')    s.atimeMs    = nowMs;
        if (typeof s.mtimeMs !== 'number')    s.mtimeMs    = nowMs;
        if (typeof s.ctimeMs !== 'number')    s.ctimeMs    = nowMs;
        if (typeof s.birthtimeMs !== 'number') s.birthtimeMs = nowMs;
        if (!s.atime)     s.atime     = new Date(s.atimeMs);
        if (!s.mtime)     s.mtime     = new Date(s.mtimeMs);
        if (!s.ctime)     s.ctime     = new Date(s.ctimeMs);
        if (!s.birthtime) s.birthtime = new Date(s.birthtimeMs);
        return s;
    }
    function wrapBool(v) { return function() { return v; }; }

    exports.statSync = function(path) {
        var raw = checkHostError(requireHost('stat_sync')(String(path)), 'statSync');
        return shapeStats(JSON.parse(raw));
    };
    // lstatSync — Node's `lstat` differs from `stat` only for
    // symlinks (it returns info about the link itself). The sandbox
    // bridge doesn't surface symlink-specific bits today; falling
    // back to `statSync` matches the symlink-followed posture we
    // already have for `readFileSync` / `readdirSync`.
    exports.lstatSync = function(path) {
        return exports.statSync(path);
    };

    // statfsSync(path[, options]) — file-system-level info (Node 19+).
    // We don't have a host bridge for `statvfs`; surface conservative
    // defaults so probing libraries don't crash. `bsize` matches the
    // common Linux page size; `bfree` / `bavail` are flagged as
    // available so callers don't think the volume is full.
    exports.statfsSync = function(path, options) {
        // We could route to `__host_fs_statfs_sync` if one becomes
        // available; for now return a synthesised StatFs object that
        // satisfies the standard property shape.
        var bigint = options && options.bigint === true;
        var fields = {
            type: 0,
            bsize: 4096,
            blocks: 0,
            bfree: 1 << 20,
            bavail: 1 << 20,
            files: 0,
            ffree: 1 << 20,
        };
        if (bigint) {
            for (var k in fields) {
                if (Object.prototype.hasOwnProperty.call(fields, k)) {
                    fields[k] = BigInt(fields[k]);
                }
            }
        }
        return fields;
    };
    exports.statfs = function(path, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        try {
            var v = exports.statfsSync(path, options);
            if (cb) queueMicrotask(function() { cb(null, v); });
            return new Promise(function(resolve) { resolve(v); });
        } catch (e) {
            if (cb) queueMicrotask(function() { cb(e); });
            return new Promise(function(_r, reject) { reject(e); });
        }
    };

    // readlinkSync — symlink target via the fs host bridge.
    // can fall through (most archive / module-resolution code probes
    // and degrades gracefully when readlink fails).
    exports.readlinkSync = function(path) {
        var fn = globalThis.__host_fs_readlink_sync;
        if (typeof fn === 'function') {
            return checkHostError(fn(String(path)), 'readlinkSync');
        }
        var e = new Error('fs.readlinkSync: host fn unavailable');
        e.code = 'ENOSYS';
        throw e;
    };

    // accessSync — Node uses bitwise mode constants. We map any
    // mode to `existsSync`, which is the semantic the vast majority
    // of consumers care about (does the path exist + is reachable).
    var F_OK = 0, R_OK = 4, W_OK = 2, X_OK = 1;
    exports.accessSync = function(path, _mode) {
        if (!exports.existsSync(path)) {
            var e = new Error("ENOENT: no such file or directory, access '" + String(path) + "'");
            e.code = 'ENOENT';
            e.errno = -2;
            e.path = String(path);
            throw e;
        }
    };

    exports.readdirSync = function(path) {
        // The host returns either an array of entries (success) or a
        // string starting with `__HOST_ERR__:` (failure — non-existent
        // path, permission denied, etc). Throwing on the error string
        // matches Node's contract and prevents callers from iterating
        // a single string as if it were a directory entry.
        var result = requireHost('readdir_sync')(String(path));
        if (typeof result === 'string' && result.indexOf('__HOST_ERR__:') === 0) {
            var msg = result.slice('__HOST_ERR__:'.length);
            var err = new Error("ENOENT: no such file or directory, scandir '" + String(path) + "'");
            err.code = 'ENOENT';
            err.errno = -2;
            err.syscall = 'scandir';
            err.path = String(path);
            // Preserve the original detail in case callers introspect
            // beyond `code`.
            err.message = err.message + ' (' + msg + ')';
            throw err;
        }
        return result;
    };

    exports.mkdirSync = function(path, options) {
        var recursive = !!(options && options.recursive);
        requireHost('mkdir_sync')(String(path), recursive);
    };

    exports.unlinkSync = function(path) {
        requireHost('unlink_sync')(String(path));
    };

    exports.renameSync = function(from, to) {
        requireHost('rename_sync')(String(from), String(to));
    };

    // Append. Build on readFileSync + writeFileSync — atomic-ish for
    // small files which is the only shape we'd hit in the sandbox.
    exports.appendFileSync = function(path, data, options) {
        var existing;
        try { existing = exports.readFileSync(path); } catch (_) { existing = ''; }
        var combined;
        if (Buffer.isBuffer(existing) || Buffer.isBuffer(data)) {
            combined = Buffer.concat([
                Buffer.isBuffer(existing) ? existing : Buffer.from(String(existing)),
                Buffer.isBuffer(data) ? data : Buffer.from(String(data))
            ]);
        } else {
            combined = String(existing) + String(data);
        }
        exports.writeFileSync(path, combined, options);
    };

    // copyFileSync — straight read-then-write, matches Node when
    // `flags` is the default 0 (copy contents, overwrite if exists).
    exports.copyFileSync = function(src, dst, _flags) {
        var data = exports.readFileSync(src);
        exports.writeFileSync(dst, data);
    };

    // truncateSync — read existing, truncate, rewrite. Sandbox-wide
    // libraries (npm, tar, etc.) only ever truncate small lockfiles
    // so the read+write path is fine.
    exports.truncateSync = function(path, len) {
        len = len || 0;
        var existing;
        try { existing = exports.readFileSync(path); } catch (_) { existing = Buffer.alloc(0); }
        var buf = Buffer.isBuffer(existing) ? existing : Buffer.from(String(existing));
        var truncated = buf.slice(0, len);
        exports.writeFileSync(path, truncated);
    };

    // rmdirSync / rmSync — no host bridge for recursive dir removal,
    // so we walk the tree and delete leaves. Slow for huge trees but
    // correct for lockfile / cache cleanup the sandbox actually sees.
    function _rmDir(path) {
        var entries;
        try { entries = exports.readdirSync(path); } catch (e) { entries = []; }
        for (var i = 0; i < entries.length; i++) {
            var child = String(path) + '/' + entries[i];
            var s;
            try { s = exports.statSync(child); } catch (_) { continue; }
            if (s.isDirectory()) _rmDir(child);
            else { try { exports.unlinkSync(child); } catch (_) {} }
        }
        try { requireHost('unlink_sync')(String(path)); } catch (_) {}
    }
    exports.rmdirSync = function(path, options) {
        if (options && options.recursive) { _rmDir(path); return; }
        try { requireHost('unlink_sync')(String(path)); }
        catch (e) {
            // Some hosts route directory removal through a separate fn;
            // fall back to the recursive walker if it's empty.
            _rmDir(path);
        }
    };
    exports.rmSync = function(path, options) {
        options = options || {};
        if (!exports.existsSync(path)) {
            if (options.force) return;
            var e = new Error("ENOENT: no such file or directory, rm '" + String(path) + "'");
            e.code = 'ENOENT';
            throw e;
        }
        var s;
        try { s = exports.statSync(path); } catch (_) { s = null; }
        if (s && s.isDirectory()) {
            if (options.recursive) _rmDir(path);
            else {
                var ee = new Error("EISDIR: illegal operation on a directory, rm '" + String(path) + "'");
                ee.code = 'EISDIR';
                throw ee;
            }
        } else {
            try { exports.unlinkSync(path); } catch (e) { if (!options.force) throw e; }
        }
    };

    // mkdtempSync — atomic-name temp dir creation. Use a 6-char
    // suffix matching Node's contract.
    exports.mkdtempSync = function(prefix) {
        var p = String(prefix);
        for (var attempt = 0; attempt < 16; attempt++) {
            var rnd = Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');
            var name = p + rnd;
            try {
                requireHost('mkdir_sync')(name, false);
                return name;
            } catch (_) { /* collision — try again */ }
        }
        var e = new Error("mkdtempSync: failed to create unique directory");
        e.code = 'EEXIST';
        throw e;
    };

    // No-op chmod / chown / utimes / link / symlink / lchown —
    // the sandbox doesn't grant arbitrary metadata mutation, but
    // libraries that defensively call these (npm cache, tar
    // extraction) expect them to silently succeed when the
    // operation is harmless.
    exports.chmodSync   = function(_p, _m) {};
    exports.fchmodSync  = function(_fd, _m) {};
    exports.lchmodSync  = function(_p, _m) {};
    exports.chownSync   = function(_p, _u, _g) {};
    exports.fchownSync  = function(_fd, _u, _g) {};
    exports.lchownSync  = function(_p, _u, _g) {};
    exports.utimesSync  = function(_p, _a, _m) {};
    exports.lutimesSync = function(_p, _a, _m) {};
    exports.futimesSync = function(_fd, _a, _m) {};
    exports.linkSync    = function(existing, target) {
        // Best-effort: copy contents. Hard-link semantics are not
        // representable through the bridge, but most callers only
        // need the file to exist at the new path.
        exports.copyFileSync(existing, target);
    };
    exports.symlinkSync = function(target, p, _type) {
        // Same posture as linkSync — copy. Real symlink behavior
        // (lstat differing from stat) isn't representable.
        try { exports.copyFileSync(target, p); }
        catch (e) {
            // Source missing is the typical npm install case for
            // workspace symlinks; fail loudly so callers can
            // fall through to a real install path.
            throw e;
        }
    };

    // fs constants. Most tools probe `fs.constants.{F,R,W,X}_OK`
    // (access mode flags) and `O_*` (open flag bits). Linux numeric
    // values; we mirror Node's table.
    exports.constants = {
        F_OK: F_OK, R_OK: R_OK, W_OK: W_OK, X_OK: X_OK,
        O_RDONLY: 0, O_WRONLY: 1, O_RDWR: 2, O_CREAT: 64, O_EXCL: 128,
        O_NOCTTY: 256, O_TRUNC: 512, O_APPEND: 1024, O_DIRECTORY: 65536,
        O_NOATIME: 262144, O_NOFOLLOW: 131072, O_SYNC: 1052672,
        O_DSYNC: 4096, O_SYMLINK: 0, O_DIRECT: 16384, O_NONBLOCK: 2048,
        S_IFMT: 0o170000, S_IFREG: 0o100000, S_IFDIR: 0o040000,
        S_IFCHR: 0o020000, S_IFBLK: 0o060000, S_IFIFO: 0o010000,
        S_IFLNK: 0o120000, S_IFSOCK: 0o140000,
        S_IRWXU: 0o700, S_IRUSR: 0o400, S_IWUSR: 0o200, S_IXUSR: 0o100,
        S_IRWXG: 0o070, S_IRGRP: 0o040, S_IWGRP: 0o020, S_IXGRP: 0o010,
        S_IRWXO: 0o007, S_IROTH: 0o004, S_IWOTH: 0o002, S_IXOTH: 0o001,
        UV_FS_COPYFILE_EXCL: 1, COPYFILE_EXCL: 1,
        UV_FS_COPYFILE_FICLONE: 2, COPYFILE_FICLONE: 2,
        UV_FS_COPYFILE_FICLONE_FORCE: 4, COPYFILE_FICLONE_FORCE: 4,
    };

    // ---- streaming -----------------------------------------------------
    var EventEmitter = require('events');
    var Buffer = require('buffer').Buffer;

    // No event loop in the sandbox: stream emission has to be triggered
    // synchronously by something. We adopt the convention that emission
    // fires when the first `data` listener is added (or when the user
    // calls `.resume()` explicitly). Attach `end` / `error` listeners
    // *before* attaching `data`.
    function createReadStream(path, options) {
        options = options || {};
        var chunkSize = options.highWaterMark || 64 * 1024;
        var startOffset = options.start || 0;
        var endOffset = options.end;  // inclusive per Node semantics
        var encoding = options.encoding || null;

        var ee = new EventEmitter();
        var pumped = false;

        function pump() {
            if (pumped) return;
            pumped = true;
            try {
                var sizeFn = globalThis.__host_fs_size;
                if (typeof sizeFn !== 'function') throw new Error('fs.createReadStream: not available');
                var sizeRaw = sizeFn(String(path));
                if (typeof sizeRaw === 'string' && sizeRaw.indexOf('__HOST_ERR__:') === 0) {
                    throw new Error('fs: ' + sizeRaw.slice('__HOST_ERR__:'.length));
                }
                var total = parseInt(sizeRaw, 10);
                var endIdx = (endOffset === undefined || endOffset >= total) ? total - 1 : endOffset;

                var off = startOffset;
                var readFn = globalThis.__host_fs_read_chunk;
                if (typeof readFn !== 'function') throw new Error('fs.createReadStream: chunk reader not available');
                while (off <= endIdx) {
                    var want = Math.min(chunkSize, endIdx - off + 1);
                    var raw = readFn(String(path), off, want);
                    if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
                        throw new Error('fs: ' + raw.slice('__HOST_ERR__:'.length));
                    }
                    var buf = Buffer.from(raw, 'base64');
                    if (buf.length === 0) break;
                    var emitted = encoding ? buf.toString(encoding) : buf;
                    ee.emit('data', emitted);
                    off += buf.length;
                }
                ee.emit('end');
                ee.emit('close');
            } catch (e) {
                ee.emit('error', e);
            }
        }

        var origOn = ee.on.bind(ee);
        ee.on = function(name, fn) {
            origOn(name, fn);
            if (name === 'data') pump();
            return ee;
        };
        ee.addListener = ee.on;
        ee.resume = pump;
        ee.pipe = function(dest) {
            ee.on('end',  function() { if (dest.end) dest.end(); });
            ee.on('data', function(chunk) { dest.write(chunk); });
            return dest;
        };
        return ee;
    }

    function createWriteStream(path, options) {
        options = options || {};
        var off = options.start || 0;
        // Default flags='w' → overwrite, matching Node. Delete first so
        // existing file contents past the written region don't linger.
        var truncateFirst = (options.flags === undefined) || options.flags === 'w';
        var ee = new EventEmitter();
        var writeFn = globalThis.__host_fs_write_chunk;
        if (typeof writeFn !== 'function') {
            throw new Error('fs.createWriteStream: not available');
        }
        if (truncateFirst && typeof globalThis.__host_fs_unlink_sync === 'function') {
            // Ignore errors — file may not exist.
            try { globalThis.__host_fs_unlink_sync(String(path)); } catch (_) {}
        }
        ee.write = function(chunk) {
            try {
                var buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
                var raw = writeFn(String(path), off, buf.toString('base64'));
                if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
                    throw new Error('fs: ' + raw.slice('__HOST_ERR__:'.length));
                }
                off += buf.length;
                return true;
            } catch (e) { ee.emit('error', e); return false; }
        };
        ee.end = function(chunk) {
            if (chunk) ee.write(chunk);
            ee.emit('finish');
            ee.emit('close');
        };
        return ee;
    }

    exports.createReadStream  = createReadStream;
    exports.createWriteStream = createWriteStream;

    // ----- fd-based sync API ----------------------------------------
    //
    // tar's Unpack writes file contents via the classic Node
    // `openSync` / `writeSync` / `closeSync` triple. We don't have
    // real OS-level fds inside the wasm sandbox; instead, we keep a
    // per-process JS-side fd table that maps a small integer to
    // `{ path, offset }`. Writes go through `__host_fs_write_chunk`
    // (the same entry `createWriteStream` uses) — which means npm's
    // tarball extraction works end-to-end without us needing a real
    // libc-shaped fd surface.
    if (!globalThis.__ab_fd_table) globalThis.__ab_fd_table = { next: 3, slots: {} };
    var FDS = globalThis.__ab_fd_table;

    function _allocFd(slot) {
        var n = FDS.next++;
        FDS.slots[n] = slot;
        return n;
    }
    function _fdSlot(fd) {
        var s = FDS.slots[fd];
        if (!s) {
            var e = new Error('EBADF: bad file descriptor');
            e.code = 'EBADF';
            e.errno = -9;
            throw e;
        }
        return s;
    }

    exports.openSync = function(path, flags, _mode) {
        flags = flags || 'r';
        var pathStr = String(path);
        // Truncate when opening with `w` or `wx`. We don't model
        // every flag; `r`/`r+`/`a`/`w`/`wx` are the realistic set.
        var truncate = false;
        if (typeof flags === 'string') {
            if (flags === 'w' || flags === 'wx' || flags === 'w+' || flags === 'wx+') truncate = true;
        } else if (typeof flags === 'number') {
            // O_TRUNC = 0x200
            if (flags & 0x200) truncate = true;
        }
        if (truncate && typeof globalThis.__host_fs_unlink_sync === 'function') {
            try { globalThis.__host_fs_unlink_sync(pathStr); } catch (_) {}
        }
        return _allocFd({ path: pathStr, offset: 0, flags: flags });
    };

    exports.openAsBlob && (exports.openAsBlob = exports.openAsBlob); // keep ref
    exports.closeSync = function(fd) {
        var slot = FDS.slots[fd];
        if (!slot) {
            var e = new Error('EBADF: bad file descriptor');
            e.code = 'EBADF';
            throw e;
        }
        delete FDS.slots[fd];
    };

    // writeSync(fd, buffer[, offset[, length[, position]]])
    // Accepts both Buffer/Uint8Array and string forms.
    exports.writeSync = function(fd, buffer, offset, length, position) {
        var slot = _fdSlot(fd);
        var data;
        if (typeof buffer === 'string') {
            // writeSync(fd, string, position, encoding)
            // — string variant: offset arg becomes the position.
            var enc = (length && typeof length === 'string') ? length : 'utf8';
            data = Buffer.from(buffer, enc);
            if (typeof offset === 'number') position = offset;
            offset = 0;
            length = data.length;
        } else {
            offset = offset || 0;
            length = (typeof length === 'number') ? length : (buffer.length - offset);
            data = (Buffer.isBuffer(buffer) && offset === 0 && length === buffer.length)
                ? buffer
                : Buffer.from(buffer.buffer || buffer, (buffer.byteOffset || 0) + offset, length);
        }
        var pos = (typeof position === 'number') ? position : slot.offset;
        var writeFn = globalThis.__host_fs_write_chunk;
        if (typeof writeFn !== 'function') {
            var e = new Error('writeSync: __host_fs_write_chunk not available');
            e.code = 'ENOSYS';
            throw e;
        }
        var raw = writeFn(slot.path, pos, data.toString('base64'));
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            var e2 = new Error('fs.writeSync: ' + raw.slice('__HOST_ERR__:'.length));
            throw e2;
        }
        if (typeof position !== 'number') slot.offset = pos + length;
        return length;
    };

    // readSync(fd, buffer, offset, length, position)
    exports.readSync = function(fd, buffer, offset, length, position) {
        var slot = _fdSlot(fd);
        var pos = (typeof position === 'number' && position !== null) ? position : slot.offset;
        var readFn = globalThis.__host_fs_read_chunk;
        if (typeof readFn !== 'function') {
            var e = new Error('readSync: __host_fs_read_chunk not available');
            e.code = 'ENOSYS';
            throw e;
        }
        var raw = readFn(slot.path, pos, length);
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            var e2 = new Error('fs.readSync: ' + raw.slice('__HOST_ERR__:'.length));
            throw e2;
        }
        var got = Buffer.from(raw, 'base64');
        var n = Math.min(got.length, length);
        got.copy(buffer, offset, 0, n);
        if (typeof position !== 'number' || position === null) slot.offset = pos + n;
        return n;
    };

    // fstatSync(fd) — same shape as statSync, keyed by fd.
    exports.fstatSync = function(fd) {
        var slot = _fdSlot(fd);
        return exports.statSync(slot.path);
    };

    // fsyncSync / fdatasyncSync / ftruncateSync — best-effort no-ops.
    // Sandbox writes go through the host bridge synchronously already;
    // there's no buffer to flush.
    exports.fsyncSync     = function(_fd) {};
    exports.fdatasyncSync = function(_fd) {};
    exports.ftruncateSync = function(fd, len) {
        var slot = _fdSlot(fd);
        len = len || 0;
        var existing;
        try { existing = exports.readFileSync(slot.path); }
        catch (_) { existing = Buffer.alloc(0); }
        var buf = Buffer.isBuffer(existing) ? existing : Buffer.from(String(existing));
        var truncated = buf.slice(0, len);
        exports.writeFileSync(slot.path, truncated);
    };

    // Callback-style equivalents — auto-wrap the sync versions on a
    // microtask. The CALLBACK_NAMES forEach below already does this
    // for the existing entries; we add fd-shaped names here so they
    // get the same treatment without polluting that list.
    function _asyncWrap(syncName) {
        return function() {
            var args = [].slice.call(arguments);
            var cb = (typeof args[args.length - 1] === 'function') ? args.pop() : null;
            Promise.resolve().then(function() {
                try {
                    var r = exports[syncName].apply(null, args);
                    if (cb) cb(null, r);
                } catch (e) {
                    if (cb) cb(e);
                }
            });
        };
    }
    exports.open       = _asyncWrap('openSync');
    exports.close      = _asyncWrap('closeSync');
    // write(fd, buffer, ...rest, cb) — Node calls back with
    // `(err, bytesWritten, buffer)`. Keep that shape.
    exports.write = function(fd, buffer, offset, length, position, cb) {
        // Tolerate the (fd, buffer, cb) shorthand and
        // (fd, string, position, encoding, cb) string variant.
        if (typeof offset === 'function') { cb = offset; offset = undefined; }
        if (typeof length === 'function') { cb = length; length = undefined; }
        if (typeof position === 'function') { cb = position; position = undefined; }
        Promise.resolve().then(function() {
            try {
                var n = exports.writeSync(fd, buffer, offset, length, position);
                if (cb) cb(null, n, buffer);
            } catch (e) {
                if (cb) cb(e);
            }
        });
    };
    exports.read = function(fd, buffer, offset, length, position, cb) {
        Promise.resolve().then(function() {
            try {
                var n = exports.readSync(fd, buffer, offset, length, position);
                if (cb) cb(null, n, buffer);
            } catch (e) {
                if (cb) cb(e);
            }
        });
    };
    exports.fstat       = _asyncWrap('fstatSync');
    exports.fsync       = _asyncWrap('fsyncSync');
    exports.fdatasync   = _asyncWrap('fdatasyncSync');
    exports.ftruncate   = _asyncWrap('ftruncateSync');

    // ----- realpath ---------------------------------------------------

    exports.realpathSync = function(path) {
        var fn = requireHost('realpath_sync');
        return checkHostError(fn(String(path)), 'realpath');
    };
    /// `fs.realpathSync.native` / `fs.realpath.native` — Node calls
    /// the underlying libuv realpath here; we have one resolver, so
    /// the alias just points back at the same fn (matches Node's
    /// "they always return the same value" contract).
    exports.realpathSync.native = exports.realpathSync;
    exports.realpath = function(path, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        var self = exports;
        Promise.resolve().then(function() {
            try { cb(null, self.realpathSync(path)); }
            catch (e) { cb(e); }
        });
    };
    exports.realpath.native = exports.realpath;

    // ----- cp (recursive copy) ----------------------------------------

    exports.cpSync = function(src, dst, options) {
        var fn = requireHost('cp');
        var force = !!(options && options.force);
        // Node's default is force: true; match that.
        if (options === undefined || (options && options.force === undefined)) {
            force = true;
        }
        checkHostError(fn(String(src), String(dst), force), 'cp');
    };
    exports.cp = function(src, dst, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        Promise.resolve().then(function() {
            try { exports.cpSync(src, dst, options); cb(null); }
            catch (e) { cb(e); }
        });
    };

    // ----- opendir / Dir / Dirent -------------------------------------

    function Dirent(entry, parentPath) {
        this.name = entry.name;
        this.parentPath = parentPath;
        this.path = parentPath; // legacy alias
        this._isFile = !!entry.isFile;
        this._isDir = !!entry.isDir;
        this._isSymlink = !!entry.isSymlink;
    }
    Dirent.prototype.isFile = function() { return this._isFile; };
    Dirent.prototype.isDirectory = function() { return this._isDir; };
    Dirent.prototype.isSymbolicLink = function() { return this._isSymlink; };
    Dirent.prototype.isBlockDevice = function() { return false; };
    Dirent.prototype.isCharacterDevice = function() { return false; };
    Dirent.prototype.isFIFO = function() { return false; };
    Dirent.prototype.isSocket = function() { return false; };

    function rawDirEntries(path) {
        var fn = requireHost('opendir_sync');
        var json = checkHostError(fn(String(path)), 'opendir');
        try {
            var arr = JSON.parse(json);
            if (!Array.isArray(arr)) throw new Error('non-array');
            return arr;
        } catch (e) {
            var err = new Error('fs.opendir: malformed host response: ' + e.message);
            err.code = 'EOTHER';
            throw err;
        }
    }

    function Dir(path, entries) {
        this.path = path;
        this._entries = entries;
        this._idx = 0;
        this._closed = false;
    }
    Dir.prototype.read = function(cb) {
        var self = this;
        if (cb) {
            Promise.resolve().then(function() {
                try {
                    var ent = self._readNextSync();
                    cb(null, ent);
                } catch (e) { cb(e); }
            });
            return;
        }
        return new Promise(function(resolve, reject) {
            try { resolve(self._readNextSync()); }
            catch (e) { reject(e); }
        });
    };
    Dir.prototype.readSync = function() { return this._readNextSync(); };
    Dir.prototype._readNextSync = function() {
        if (this._closed) {
            var err = new Error('fs.Dir: read after close');
            err.code = 'ERR_DIR_CLOSED';
            throw err;
        }
        if (this._idx >= this._entries.length) return null;
        return new Dirent(this._entries[this._idx++], this.path);
    };
    Dir.prototype.close = function(cb) {
        this._closed = true;
        if (cb) { Promise.resolve().then(function() { cb(null); }); return; }
        return Promise.resolve();
    };
    Dir.prototype.closeSync = function() { this._closed = true; };
    // async iterator
    Dir.prototype[Symbol.asyncIterator] = function() {
        var self = this;
        return {
            next: function() {
                return self.read().then(function(ent) {
                    if (!ent) { self.close(); return { value: undefined, done: true }; }
                    return { value: ent, done: false };
                });
            },
            return: function() { return self.close().then(function() { return { value: undefined, done: true }; }); },
        };
    };

    exports.opendirSync = function(path, _options) {
        return new Dir(String(path), rawDirEntries(path));
    };
    exports.opendir = function(path, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        Promise.resolve().then(function() {
            try { cb(null, exports.opendirSync(path)); }
            catch (e) { cb(e); }
        });
    };
    exports.Dir = Dir;
    exports.Dirent = Dirent;

    /// fs.Stats — class probed by real apps. Real Node returns these
    /// from statSync etc.; our statSync returns plain objects with the
    /// same shape, but the class itself is also exposed. Subclassable
    /// for libraries that pattern-match `instanceof`.
    function Stats() {
        this.dev = 0;
        this.ino = 0;
        this.mode = 0;
        this.nlink = 1;
        this.uid = 0;
        this.gid = 0;
        this.rdev = 0;
        this.size = 0;
        this.blksize = 4096;
        this.blocks = 0;
        this.atimeMs = 0;
        this.mtimeMs = 0;
        this.ctimeMs = 0;
        this.birthtimeMs = 0;
    }
    Stats.prototype.isFile          = function() { return false; };
    Stats.prototype.isDirectory     = function() { return false; };
    Stats.prototype.isBlockDevice   = function() { return false; };
    Stats.prototype.isCharacterDevice = function() { return false; };
    Stats.prototype.isFIFO          = function() { return false; };
    Stats.prototype.isSocket        = function() { return false; };
    Stats.prototype.isSymbolicLink  = function() { return false; };
    exports.Stats = Stats;
    exports.StatFs = function StatFs() {
        this.type = 0;
        this.bsize = 4096;
        this.blocks = 0;
        this.bfree = 0;
        this.bavail = 0;
        this.files = 0;
        this.ffree = 0;
    };

    /// fs.ReadStream / fs.WriteStream — Real instances come back from
    /// `createReadStream` / `createWriteStream`; constructors are
    /// surface-only stand-ins. Some libs pattern-match
    /// `instanceof fs.ReadStream`.
    var _streamMod;
    function _streamModule() {
        if (!_streamMod) _streamMod = require('stream');
        return _streamMod;
    }
    function ReadStream(_path, _options) {
        _streamModule().Readable.call(this);
    }
    Object.defineProperty(exports, 'ReadStream', {
        configurable: true,
        get: function() {
            ReadStream.prototype = Object.create(_streamModule().Readable.prototype);
            ReadStream.prototype.constructor = ReadStream;
            return ReadStream;
        },
    });
    function WriteStream(_path, _options) {
        _streamModule().Writable.call(this);
    }
    Object.defineProperty(exports, 'WriteStream', {
        configurable: true,
        get: function() {
            WriteStream.prototype = Object.create(_streamModule().Writable.prototype);
            WriteStream.prototype.constructor = WriteStream;
            return WriteStream;
        },
    });
    /// fs.FileReadStream / FileWriteStream — Node aliases.
    Object.defineProperty(exports, 'FileReadStream', {
        configurable: true, get: function() { return exports.ReadStream; },
    });
    Object.defineProperty(exports, 'FileWriteStream', {
        configurable: true, get: function() { return exports.WriteStream; },
    });

    // Augment readdirSync with `withFileTypes` and `recursive` support
    // (Node 22+). The existing overload returns a plain string array;
    // opendir_sync gives us typed entries. `recursive: true` walks
    // the tree depth-first and returns paths relative to `path`.
    var _readdirSyncBasic = exports.readdirSync;
    exports.readdirSync = function(path, options) {
        var recursive = !!(options && options.recursive);
        var withFileTypes = !!(options && options.withFileTypes);
        var encoding = options && options.encoding;
        if (recursive) {
            // DFS walk. `parentPath` on Dirent is set to the dir we
            // listed (Node 20+ contract); names are relative to `path`.
            var rootStr = String(path);
            var out = [];
            var stack = [{ dir: rootStr, prefix: '' }];
            while (stack.length) {
                var top = stack.pop();
                var children;
                try { children = rawDirEntries(top.dir); }
                catch (_) { children = []; }
                for (var i = 0; i < children.length; i++) {
                    var c = children[i];
                    var rel = top.prefix ? (top.prefix + '/' + c.name) : c.name;
                    var abs = top.dir + '/' + c.name;
                    if (withFileTypes) {
                        var d = new Dirent(c, top.dir);
                        // Node-26 path field — the absolute joined path.
                        d.path = abs;
                        d.parentPath = top.dir;
                        out.push(d);
                    } else {
                        out.push(rel);
                    }
                    if (c.isDir) {
                        stack.push({ dir: abs, prefix: rel });
                    }
                }
            }
            return out;
        }
        if (withFileTypes) {
            var entries = rawDirEntries(path);
            var pp = String(path);
            return entries.map(function(e) {
                var d = new Dirent(e, pp);
                d.parentPath = pp;
                d.path = pp + '/' + e.name;
                return d;
            });
        }
        var raw = _readdirSyncBasic(path);
        if (encoding === 'buffer') {
            return raw.map(function(n) { return Buffer.from(String(n)); });
        }
        return raw;
    };

    // ----- watch (polling-based FSWatcher) ----------------------------

    var EventEmitter = require('events').EventEmitter;

    function FSWatcher(path, options) {
        EventEmitter.call(this);
        this._path = String(path);
        this._interval = (options && options.interval) || 250;
        this._closed = false;
        this._tick = this._tick.bind(this);
        this._scheduleNext();
    }
    FSWatcher.prototype = Object.create(EventEmitter.prototype);
    FSWatcher.prototype.constructor = FSWatcher;

    FSWatcher.prototype._scheduleNext = function() {
        if (this._closed) return;
        // Use setTimeout(0) so the first poll happens off the current
        // tick — matches Node's behavior of registering the watcher
        // synchronously and emitting events asynchronously.
        if (typeof setTimeout === 'function') {
            setTimeout(this._tick, 0);
        } else {
            // Fallback: microtask. Won't actually deliver host-watched
            // changes (host_fs_watch_poll blocks for `interval`ms), but
            // at least the watcher API surface works in environments
            // without a timer host (`burn` library mode).
            Promise.resolve().then(this._tick);
        }
    };

    FSWatcher.prototype._tick = function() {
        if (this._closed) return;
        var self = this;
        var fn;
        try { fn = requireHost('watch_poll'); }
        catch (e) {
            this.emit('error', e);
            this._closed = true;
            return;
        }
        var raw;
        try {
            raw = fn(self._path, self._interval);
        } catch (e) {
            this.emit('error', e);
            return this._scheduleNext();
        }
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            var msg = raw.slice('__HOST_ERR__:'.length);
            var err = new Error('fs.watch: ' + msg);
            if (msg.toLowerCase().indexOf('permission denied') !== -1) err.code = 'EACCES';
            this.emit('error', err);
            this._closed = true;
            return;
        }
        try {
            var events = JSON.parse(raw);
            if (Array.isArray(events)) {
                for (var i = 0; i < events.length; i++) {
                    var ev = events[i];
                    self.emit('change', ev.kind, ev.filename);
                }
            }
        } catch (_) {}
        this._scheduleNext();
    };

    FSWatcher.prototype.close = function() {
        this._closed = true;
        try { this.emit('close'); } catch (_) {}
    };
    FSWatcher.prototype.ref = function() { return this; };
    FSWatcher.prototype.unref = function() { return this; };

    exports.FSWatcher = FSWatcher;
    exports.watch = function(path, options, listener) {
        if (typeof options === 'function') { listener = options; options = undefined; }
        var w = new FSWatcher(path, options);
        if (typeof listener === 'function') w.on('change', listener);
        return w;
    };

    // ----- FileHandle (fs.promises.open) ------------------------------

    function FileHandle(path, flags) {
        this._path = String(path);
        this._flags = flags || 'r';
        this._closed = false;
    }
    Object.defineProperty(FileHandle.prototype, 'fd', {
        // Node's fd is a small integer; we don't expose a real fd from
        // the WASM sandbox. Surface the path-keyed pseudo-fd so caller
        // code that just uses `.fd` for logging won't crash.
        get: function() { return -1; },
    });

    function _checkOpen(fh) {
        if (fh._closed) {
            var e = new Error('FileHandle: already closed');
            e.code = 'EBADF';
            throw e;
        }
    }

    FileHandle.prototype.read = function(buffer, offset, length, position) {
        _checkOpen(this);
        var Buffer = bufferModule();
        var path = this._path;
        // node-style positional or options-object call
        if (buffer && typeof buffer === 'object' && !Buffer.isBuffer(buffer)
            && !(buffer instanceof Uint8Array)) {
            var opts = buffer;
            buffer = opts.buffer;
            offset = opts.offset;
            length = opts.length;
            position = opts.position;
        }
        offset = offset | 0;
        length = (length === undefined || length === null) ? buffer.length - offset : length | 0;
        position = (position === undefined || position === null) ? 0 : position;
        return new Promise(function(resolve, reject) {
            try {
                var fn = requireHost('read_chunk');
                // host returns base64 encoded bytes
                var b64 = checkHostError(fn(path, position, length), 'FileHandle.read');
                var chunk = Buffer.from(b64, 'base64');
                var n = Math.min(chunk.length, length);
                for (var i = 0; i < n; i++) buffer[offset + i] = chunk[i];
                resolve({ bytesRead: n, buffer: buffer });
            } catch (e) { reject(e); }
        });
    };

    FileHandle.prototype.write = function(data, positionOrOffset, lengthOrEncoding, position) {
        _checkOpen(this);
        var Buffer = bufferModule();
        var path = this._path;
        var bytes;
        var pos;
        if (typeof data === 'string') {
            // (string, position, encoding)
            bytes = Buffer.from(data, lengthOrEncoding || 'utf8');
            pos = (positionOrOffset === undefined || positionOrOffset === null) ? 0 : positionOrOffset;
        } else {
            // (buffer, offset, length, position)
            var offset = positionOrOffset | 0;
            var length = (lengthOrEncoding === undefined || lengthOrEncoding === null)
                ? data.length - offset : lengthOrEncoding | 0;
            bytes = Buffer.from(data.slice(offset, offset + length));
            pos = (position === undefined || position === null) ? 0 : position;
        }
        return new Promise(function(resolve, reject) {
            try {
                var fn = requireHost('write_chunk');
                checkHostError(fn(path, pos, bytes.toString('base64')), 'FileHandle.write');
                resolve({ bytesWritten: bytes.length, buffer: data });
            } catch (e) { reject(e); }
        });
    };

    FileHandle.prototype.readFile = function(options) {
        _checkOpen(this);
        return Promise.resolve(exports.readFileSync(this._path, options));
    };

    FileHandle.prototype.writeFile = function(data, options) {
        _checkOpen(this);
        return Promise.resolve(exports.writeFileSync(this._path, data, options));
    };

    FileHandle.prototype.stat = function() {
        _checkOpen(this);
        return Promise.resolve(exports.statSync(this._path));
    };

    FileHandle.prototype.truncate = function(len) {
        _checkOpen(this);
        len = len | 0;
        var Buffer = bufferModule();
        var existing;
        try { existing = exports.readFileSync(this._path); }
        catch (e) { return Promise.reject(e); }
        var truncated = Buffer.alloc(len);
        existing.copy(truncated, 0, 0, Math.min(existing.length, len));
        try { exports.writeFileSync(this._path, truncated); return Promise.resolve(); }
        catch (e) { return Promise.reject(e); }
    };

    FileHandle.prototype.close = function() {
        this._closed = true;
        return Promise.resolve();
    };

    FileHandle.prototype[Symbol.asyncDispose] = function() { return this.close(); };

    // ----- fs.promises ------------------------------------------------

    exports.promises = {};
    // Auto-promisify every sync function that has a 1:1 promise twin.
    // Node 26 keeps these stable; if the upstream surface grows,
    // adding a new entry here is enough.
    [
        'readFile','writeFile','stat','lstat','readdir','mkdir',
        'unlink','rename','readlink','access','chmod','fchmod','lchmod',
        'chown','fchown','lchown','utimes','lutimes','futimes','link',
        'symlink','copyFile','appendFile','truncate','mkdtemp','rmdir','rm',
    ].forEach(function(name) {
        exports.promises[name] = function() {
            var args = [].slice.call(arguments);
            var syncName = name + 'Sync';
            return new Promise(function(resolve, reject) {
                try { resolve(exports[syncName].apply(null, args)); }
                catch (e) { reject(e); }
            });
        };
    });

    // New promise-only entries.
    exports.promises.realpath = function(path) {
        return new Promise(function(resolve, reject) {
            try { resolve(exports.realpathSync(path)); }
            catch (e) { reject(e); }
        });
    };
    /// `fs.promises.statfs(path, options)` — Node 19+ Promise twin
    /// of `fs.statfs` / `fs.statfsSync`.
    exports.promises.statfs = function(path, options) {
        return new Promise(function(resolve, reject) {
            try { resolve(exports.statfsSync(path, options)); }
            catch (e) { reject(e); }
        });
    };
    exports.promises.cp = function(src, dst, options) {
        return new Promise(function(resolve, reject) {
            try { exports.cpSync(src, dst, options); resolve(); }
            catch (e) { reject(e); }
        });
    };
    exports.promises.opendir = function(path, options) {
        return new Promise(function(resolve, reject) {
            try { resolve(exports.opendirSync(path, options)); }
            catch (e) { reject(e); }
        });
    };
    exports.promises.watch = function(path, options) {
        // Async-iterable wrapper around FSWatcher.
        var w = new FSWatcher(path, options);
        var queue = [];
        var pending = null;
        w.on('change', function(eventType, filename) {
            if (pending) {
                var p = pending; pending = null;
                p({ value: { eventType: eventType, filename: filename }, done: false });
            } else {
                queue.push({ eventType: eventType, filename: filename });
            }
        });
        w.on('error', function(err) {
            if (pending) { var p = pending; pending = null; p(Promise.reject(err)); }
        });
        return {
            [Symbol.asyncIterator]: function() { return this; },
            next: function() {
                if (queue.length) {
                    return Promise.resolve({ value: queue.shift(), done: false });
                }
                return new Promise(function(resolve) { pending = resolve; });
            },
            return: function() {
                w.close();
                return Promise.resolve({ value: undefined, done: true });
            },
        };
    };
    exports.promises.open = function(path, flags, _mode) {
        return new Promise(function(resolve, reject) {
            try {
                // Validate path is reachable; statSync will throw ENOENT
                // for read-only opens and give us a clean error path.
                if (typeof flags === 'string' && flags.indexOf('r') === 0) {
                    exports.statSync(path);
                }
                resolve(new FileHandle(path, flags));
            } catch (e) { reject(e); }
        });
    };
    exports.FileHandle = FileHandle;

    // Node 22+ added `fs.glob` / `fs.globSync` / `fs.promises.glob`
    // for pattern-matched directory walks. We don't pull in a full
    // micromatch engine; libraries that genuinely need glob semantics
    // import the `glob` npm package, which works on top of
    // `readdirSync` / `lstatSync`. The shim returns the bare-leaf
    // shape (no globs interpreted) so callers that pass a literal
    // path get the right answer and pattern callers fall through to
    // the empty-result path matching Node's no-match behavior.
    function _matchPattern(pattern, root) {
        var p = String(pattern);
        // Literal path passthrough — no `*` / `?` / `[` markers.
        if (!/[*?[]/.test(p)) {
            try {
                exports.statSync(p);
                return [p];
            } catch (_) { return []; }
        }
        // For pattern globs, walk the directory and return entries
        // whose name matches the trailing star-segment. Cheap but
        // correct enough for the npm log-cleanup `*.log` case.
        var slash = p.lastIndexOf('/');
        var dir = slash >= 0 ? p.slice(0, slash) : (root || '.');
        var rest = slash >= 0 ? p.slice(slash + 1) : p;
        var re = new RegExp('^' + rest
            .replace(/[.+^${}()|\\]/g, '\\$&')
            .replace(/\*/g, '.*')
            .replace(/\?/g, '.') + '$');
        var entries;
        try { entries = exports.readdirSync(dir); }
        catch (_) { return []; }
        var out = [];
        for (var i = 0; i < entries.length; i++) {
            if (re.test(entries[i])) out.push(dir + '/' + entries[i]);
        }
        return out;
    }
    exports.globSync = function(pattern, options) {
        var pats = Array.isArray(pattern) ? pattern : [pattern];
        var cwd = (options && options.cwd) ? String(options.cwd) : (typeof globalThis.__host_cwd === 'string' ? globalThis.__host_cwd : '.');
        var seen = {};
        var out = [];
        for (var i = 0; i < pats.length; i++) {
            var matches = _matchPattern(pats[i], cwd);
            for (var j = 0; j < matches.length; j++) {
                if (!seen[matches[j]]) { seen[matches[j]] = true; out.push(matches[j]); }
            }
        }
        return out;
    };
    exports.glob = function(pattern, options, cb) {
        if (typeof options === 'function') { cb = options; options = undefined; }
        Promise.resolve().then(function() {
            try { cb(null, exports.globSync(pattern, options)); }
            catch (e) { cb(e); }
        });
    };
    exports.promises.glob = function(pattern, options) {
        return new Promise(function(resolve, reject) {
            try { resolve(exports.globSync(pattern, options)); }
            catch (e) { reject(e); }
        });
    };
    /// fs.promises.constants — Node 18.4+ alias for fs.constants. Some
    /// libraries import only the promises namespace and expect the
    /// flag bag to be reachable from there too.
    exports.promises.constants = exports.constants;

    // Callback-style entry points for every sync function. Node ships
    // both shapes for the entire fs surface; libraries (path-scurry,
    // chokidar, npm's lockfile cleanup) call the callback form
    // directly. We auto-wrap each `*Sync` in an async-callback shim
    // — the result fires on a microtask so handlers attached after
    // dispatch see it (matches Node's CB-after-IO contract).
    var CALLBACK_NAMES = [
        'readFile','writeFile','appendFile','stat','lstat','fstat','exists',
        'readdir','mkdir','rmdir','rm','unlink','rename','readlink','access',
        'chmod','fchmod','lchmod','chown','fchown','lchown','utimes','lutimes',
        'futimes','link','symlink','copyFile','truncate','mkdtemp','realpath',
    ];
    CALLBACK_NAMES.forEach(function(name) {
        if (typeof exports[name] === 'function') return; // already defined (e.g. realpath)
        var syncName = name + 'Sync';
        if (typeof exports[syncName] !== 'function') return; // sync entry missing
        exports[name] = function() {
            var args = [].slice.call(arguments);
            var cb = (typeof args[args.length - 1] === 'function') ? args.pop() : null;
            // Schedule on a microtask so the cb fires after the
            // calling expression returns — matches Node's
            // async-callback contract for code like:
            //   `const r = fs.readdir(path, opts, cb); /* … */`.
            Promise.resolve().then(function() {
                try {
                    var r = exports[syncName].apply(null, args);
                    if (cb) cb(null, r);
                } catch (e) {
                    if (cb) cb(e);
                }
            });
        };
    });
    // existsSync's callback form has a single-arg shape (no err).
    exports.exists = function(path, cb) {
        Promise.resolve().then(function() {
            if (cb) cb(exports.existsSync(path));
        });
    };

    // `fs.writev` / `writevSync` — vectored writes. fs-minipass
    // gates a libuv-binding fallback on `!fs.writev`, so providing
    // even a sequential implementation skips the binding path
    // entirely. The fd is the path-keyed handle from FileHandle /
    // openSync; we serialise the iovec by concatenating buffers
    // and dispatching one write per call. `position === null` means
    // "current position" (Node default); a numeric value seeks first.
    exports.writevSync = function(fd, buffers, position) {
        var total = 0;
        var pos = (typeof position === 'number') ? position : 0;
        // FileHandle stores its path on `_path`; for raw numeric fds
        // we don't have a path mapping and fall through to sync write
        // via the chunk bridge.
        var path = (fd && typeof fd === 'object' && fd._path) ? fd._path : String(fd);
        var writeFn = globalThis.__host_fs_write_chunk;
        if (typeof writeFn !== 'function') {
            throw new Error('fs.writev: not available');
        }
        for (var i = 0; i < buffers.length; i++) {
            var b = buffers[i];
            var bb = Buffer.isBuffer(b) ? b : Buffer.from(b);
            var raw = writeFn(path, pos, bb.toString('base64'));
            if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
                throw new Error('fs: ' + raw.slice('__HOST_ERR__:'.length));
            }
            pos += bb.length;
            total += bb.length;
        }
        return total;
    };
    exports.writev = function(fd, buffers, position, cb) {
        if (typeof position === 'function') { cb = position; position = null; }
        Promise.resolve().then(function() {
            try {
                var n = exports.writevSync(fd, buffers, position);
                if (cb) cb(null, n, buffers);
            } catch (e) { if (cb) cb(e); }
        });
    };
    // `fs.readv` — gather-read vectored. Same posture: serialise.
    exports.readvSync = function(fd, buffers, position) {
        var total = 0;
        var pos = (typeof position === 'number') ? position : 0;
        var path = (fd && typeof fd === 'object' && fd._path) ? fd._path : String(fd);
        var readFn = globalThis.__host_fs_read_chunk;
        if (typeof readFn !== 'function') {
            throw new Error('fs.readv: not available');
        }
        for (var i = 0; i < buffers.length; i++) {
            var b = buffers[i];
            var want = b.length;
            var raw = readFn(path, pos, want);
            if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
                throw new Error('fs: ' + raw.slice('__HOST_ERR__:'.length));
            }
            var got = Buffer.from(raw, 'base64');
            got.copy(b, 0, 0, Math.min(got.length, want));
            pos += got.length;
            total += got.length;
            if (got.length < want) break;
        }
        return total;
    };
    exports.readv = function(fd, buffers, position, cb) {
        if (typeof position === 'function') { cb = position; position = null; }
        Promise.resolve().then(function() {
            try {
                var n = exports.readvSync(fd, buffers, position);
                if (cb) cb(null, n, buffers);
            } catch (e) { if (cb) cb(e); }
        });
    };

    // `fs.openAsBlob` — Node 19+. Returns a Blob backed by the
    // file's content. Sandbox-safe: we read eagerly via the host
    // bridge (no streaming Blob support yet, but the shape is
    // there for libraries that probe).
    exports.openAsBlob = function(path, _options) {
        var data = exports.readFileSync(path);
        if (typeof Blob === 'function') {
            return Promise.resolve(new Blob([data]));
        }
        // Pre-Blob runtimes — return a minimal blob-shaped object.
        var bytes = Buffer.isBuffer(data) ? data : Buffer.from(String(data));
        return Promise.resolve({
            size: bytes.length,
            type: '',
            arrayBuffer: function() { return Promise.resolve(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)); },
            text:        function() { return Promise.resolve(bytes.toString('utf8')); },
            slice:       function() { return this; },
        });
    };
});

// ---- host.js ----
// afterburner:host — embedder-facing hooks. Not part of Node's standard
// surface; lives under the `afterburner:` package namespace. The host
// wires a `HostContext` trait implementation on the combustor side
// that answers `readColumn`/`emitRow`/`getEnv`; if no context is
// attached, `readColumn` returns `[]`, `emitRow` is a no-op, and
// `getEnv` returns `undefined`.

__register_module('afterburner:host', function(module, exports, require) {

    exports.readColumn = function(name) {
        var fn = globalThis.__host_read_column;
        if (typeof fn !== 'function') return [];
        var raw = fn(String(name));
        try { return JSON.parse(raw); } catch (_) { return []; }
    };

    exports.emitRow = function(row) {
        var fn = globalThis.__host_emit_row;
        if (typeof fn !== 'function') return;
        var json;
        try { json = JSON.stringify(row); }
        catch (e) { throw new TypeError('emitRow: row must be JSON-serializable: ' + e.message); }
        fn(json);
    };

    exports.getEnv = function(key) {
        var fn = globalThis.__host_get_env;
        if (typeof fn !== 'function') return undefined;
        var v = fn(String(key));
        return (v === null || v === undefined) ? undefined : v;
    };
});

// ---- http.js ----
// http / https — outbound `request`/`get` + server-side
// `createServer` + IncomingMessage / ServerResponse.
//
// Outbound is a synchronous wrapper around `__host_http_request`.
// Server-side threads through the host's daemon-mode HTTP
// coordinator (`__host_http_listen` + `__host_http_reply`) — when
// user code calls `http.createServer(cb).listen(port)`, we register
// `cb` on `globalThis.__ab_http_handlers[server_id]`, and the
// plugin's `daemon_event` mode dispatches matching incoming
// requests back through it.

function __plenum_install_http(moduleName) {
    __register_module(moduleName, function(module, exports, require) {
        var EventEmitter = require('events');

        // -------- outbound request / get --------------------------------

        function requestImpl(opts, cb) {
            if (typeof globalThis.__host_http_request !== 'function'
                && typeof globalThis.__host_http_request_async !== 'function') {
                throw new Error("Permission denied: http.request is not available");
            }
            var url;
            if (typeof opts === 'string') {
                url = opts;
            } else if (opts && typeof opts.url === 'string') {
                url = opts.url;
            } else {
                url = (opts.protocol || 'http:') + '//' + (opts.host || opts.hostname)
                    + (opts.port ? ':' + opts.port : '') + (opts.path || '/');
            }
            var method = (opts && opts.method) || 'GET';
            var body = opts && opts.body;

            // Prefer the async path when a daemon is attached. The
            // sync function still runs the request inline on the wasm
            // thread; the async one dispatches onto Tokio and the
            // shard event loop fans the response back through a
            // `daemon-event`. Real Node-style: caller awaits a Promise
            // that resolves when the host signals completion, instead
            // of blocking the wasm thread for the full round-trip.
            var asyncFn = globalThis.__host_http_request_async;
            var asyncReqId = -1;
            var resultPromise = null;
            if (typeof asyncFn === 'function') {
                try {
                    var rid = asyncFn(method, url, body || null);
                    if (typeof rid === 'bigint') rid = Number(rid);
                    if (typeof rid === 'number' && rid > 0) {
                        asyncReqId = rid;
                        resultPromise = new Promise(function(resolve) {
                            if (!globalThis.__ab_http_pending) globalThis.__ab_http_pending = {};
                            globalThis.__ab_http_pending[asyncReqId] = { resolve: resolve };
                        });
                    }
                } catch (_) {
                    // fall through to sync path
                }
            }

            // The whole `result → resp → emit` pipeline is wrapped in
            // `buildAndDispatch` so the same code path covers both
            // the sync and async flavours. Sync calls it immediately
            // with the just-fetched result; async chains it onto the
            // Promise the daemon resolves when the response arrives.
            var Buffer = require('buffer').Buffer;
            var EventEmitter = require('events');
            var req = Object.create(EventEmitter.prototype);
            EventEmitter.call(req);
            req.end          = function() { return req; };
            req.write        = function() { return true; };
            req.setHeader    = function() { return req; };
            req.getHeader    = function() {};
            req.removeHeader = function() {};
            req.setTimeout   = function() { return req; };
            req.destroy      = function() { return req; };
            req.abort        = function() { return req; };
            req.flushHeaders = function() { return req; };
            req.socket = { setKeepAlive: function() {}, setTimeout: function() {}, unref: function() {}, ref: function() {} };
            req.connection = req.socket;

            function buildAndDispatch(result) {
                if (typeof result.body === 'string' && result.body.indexOf('__HOST_ERR__:') === 0) {
                    var hostErr = new Error("http: " + result.body.slice('__HOST_ERR__:'.length));
                    if (hostErr.message.toLowerCase().indexOf('permission denied') !== -1) hostErr.code = 'EACCES';
                    Promise.resolve().then(function() {
                        try { req.emit('socket', req.socket); } catch (_) {}
                        req.emit('error', hostErr);
                    });
                    return req;
                }
                if (typeof result.error === 'string' && result.error.length > 0) {
                    var hostErr2 = new Error("http: " + result.error);
                    Promise.resolve().then(function() {
                        try { req.emit('socket', req.socket); } catch (_) {}
                        req.emit('error', hostErr2);
                    });
                    return req;
                }
                var resp = makeResp(result, method, url);
                Promise.resolve().then(function() {
                    try { req.emit('socket', req.socket); } catch (_) {}
                    if (cb) {
                        try { cb(resp); } catch (e) { req.emit('error', e); return; }
                    }
                    req.emit('response', resp);
                });
                return req;
            }

            if (asyncReqId > 0) {
                resultPromise.then(buildAndDispatch);
                return req;
            }
            // Async dispatcher returned -1 (no daemon attached, or
            // capability denied by the manifold). No way to issue the
            // request from this Store — surface synchronously so
            // try/catch around `http.get(...)` sees the failure.
            var noDaemonErr = new Error('Permission denied: http.request requires daemon mode (run via `burn` CLI)');
            noDaemonErr.code = 'EACCES';
            throw noDaemonErr;
        }

        // makeResp / IncomingMessage factory — extracted so both the
        // sync and async dispatch paths share one shape. `result` is
        // the host envelope: `{status, headers, body, body_b64,
        // error?}`. Returns a Node-shaped IncomingMessage with the
        // full readable-stream surface our consumers (npm, undici,
        // node-fetch / minipass-fetch) require.
        function makeResp(result, method, url) {
            // Shape the response like a Node IncomingMessage with a
            // working EventEmitter contract plus the readable-stream
            // pieces user code commonly touches: `.resume()`,
            // `.pause()`, `.pipe(dest)`, `.read()`, async iteration.
            // The body is materialised eagerly by the host bridge — we
            // just have to stage it through the listener queue so user
            // code that registers handlers AFTER the cb fires (the
            // normal Node pattern) still sees `data` + `end`. We
            // prefer the host's base64 body when it is sent (binary-
            // safe, what npm tar / pacote requires) and fall back to
            // the lossy UTF-8 body for legacy callers that read text.
            var bodyBytes = null;
            if (typeof result.body_b64 === 'string') {
                try { bodyBytes = Buffer.from(result.body_b64, 'base64'); }
                catch (_) { bodyBytes = null; }
            }
            if (!bodyBytes && typeof result.body === 'string') {
                bodyBytes = Buffer.from(result.body, 'utf8');
            }
            if (!bodyBytes) bodyBytes = Buffer.alloc(0);

            var resp = Object.create(EventEmitter.prototype);
            EventEmitter.call(resp);
            resp.statusCode    = result.status;
            resp.statusMessage = '';
            resp.httpVersion   = '1.1';
            resp.headers       = result.headers && typeof result.headers === 'object' ? result.headers : {};
            resp.rawHeaders    = [];
            for (var hk in resp.headers) {
                resp.rawHeaders.push(hk, resp.headers[hk]);
            }
            resp.trailers      = {};
            resp.method        = method;
            resp.url           = url;
            resp.complete      = false;
            resp.readable      = true;
            resp.readableEnded = false;
            resp.body          = result.body;
            resp._bodyBytes    = bodyBytes;
            var _paused = true; // start paused — drain on first listener / resume()
            var _flushed = false;
            // Encoding switch — `setEncoding('utf8')` etc. tells Node
            // to deliver string chunks instead of Buffers. We honor
            // this so libraries that probe via `setEncoding` then
            // collect string output keep their post-conditions.
            var _encoding = null;
            function flushBody() {
                if (_flushed) return;
                _flushed = true;
                resp.complete      = true;
                resp.readableEnded = true;
                if (bodyBytes && bodyBytes.length > 0) {
                    var chunk = _encoding ? bodyBytes.toString(_encoding) : bodyBytes;
                    resp.emit('data', chunk);
                }
                resp.emit('end');
                resp.emit('close');
            }
            // Schedule the flush as a microtask so user code has a
            // chance to register `data` / `end` / `close` listeners
            // *after* calling `resume()` — the canonical Node pattern.
            // Microtasks fire after the current synchronous turn but
            // before any timer callback, so the outer envelope's
            // `await` reliably drains them even for one-shot scripts.
            function maybeFlush() {
                if (_paused || _flushed) return;
                Promise.resolve().then(flushBody);
            }
            resp.resume      = function() { _paused = false; maybeFlush(); return resp; };
            resp.pause       = function() { _paused = true; return resp; };
            resp.setEncoding = function(enc) {
                if (typeof enc === 'string') _encoding = enc.toLowerCase() === 'utf8' ? 'utf8' : enc;
                return resp;
            };
            resp.read        = function() {
                if (_flushed) return null;
                _flushed = true;
                resp.complete = true;
                resp.readableEnded = true;
                return _encoding ? bodyBytes.toString(_encoding) : bodyBytes;
            };
            resp.destroy     = function(err) {
                if (err) resp.emit('error', err);
                resp.emit('close');
                return resp;
            };
            resp.unpipe      = function() { return resp; };
            // Convenience body-shaping helpers (Undici `.text()`/`.json()`
            // shape) — handy for fetch-flavoured callers.
            resp.text        = function() {
                return Promise.resolve(bodyBytes.toString('utf8'));
            };
            resp.json        = function() {
                try { return Promise.resolve(JSON.parse(bodyBytes.toString('utf8'))); }
                catch (e) { return Promise.reject(e); }
            };
            // Auto-resume when a `data` listener attaches (Node's
            // backwards-compat path: registering a `data` listener
            // implicitly switches the stream to flowing mode).
            var origOn = resp.on.bind(resp);
            resp.on = resp.addListener = function(event, handler) {
                origOn(event, handler);
                if (event === 'data' || event === 'readable') {
                    _paused = false;
                    maybeFlush();
                }
                return resp;
            };
            resp.pipe = function(dest) {
                resp.on('data', function(chunk) { if (dest && dest.write) dest.write(chunk); });
                resp.on('end',  function()      { if (dest && dest.end)   dest.end(); });
                _paused = false;
                maybeFlush();
                return dest;
            };
            // Async-iterator support so `for await (const chunk of res)`
            // works. Single-chunk: yield the body once and end. Yield
            // a Buffer (or encoded string when setEncoding was set)
            // so binary callers (npm tar, image decoders) get bytes.
            if (typeof Symbol !== 'undefined' && Symbol.asyncIterator) {
                resp[Symbol.asyncIterator] = function() {
                    var done = false;
                    return {
                        next: function() {
                            if (done) return Promise.resolve({ value: undefined, done: true });
                            done = true;
                            _flushed = true;
                            resp.complete = true;
                            resp.readableEnded = true;
                            var v = _encoding ? bodyBytes.toString(_encoding) : bodyBytes;
                            return Promise.resolve({ value: v, done: false });
                        },
                        return: function() { done = true; return Promise.resolve({ value: undefined, done: true }); },
                    };
                };
            }
            return resp;
        }

        // Node accepts both `(url[, options][, cb])` and
        // `(options[, cb])`. Coalesce the URL+options form into a
        // single opts object before handing off — corepack /
        // node-fetch / pacote all reach for the 3-arg shape.
        function normaliseRequestArgs(args) {
            var arr = Array.prototype.slice.call(args);
            var cb = (arr.length && typeof arr[arr.length - 1] === 'function') ? arr.pop() : undefined;
            var first = arr[0];
            var second = arr[1];
            var opts;
            if (typeof first === 'string') {
                opts = (second && typeof second === 'object') ? Object.assign({}, second) : {};
                // Stash the URL string for requestImpl's url-or-opts branch.
                opts.url = first;
                // Decompose the URL the cheap way so opts.hostname/port
                // are usable when callers downstream introspect.
                var m = /^(https?):\/\/([^\/:?#]+)(?::(\d+))?(\/[^?#]*)?(\?[^#]*)?/i.exec(first);
                if (m) {
                    if (!opts.protocol) opts.protocol = m[1] + ':';
                    if (!opts.hostname) opts.hostname = m[2];
                    if (!opts.port && m[3]) opts.port = parseInt(m[3], 10);
                    if (!opts.path) opts.path = (m[4] || '/') + (m[5] || '');
                }
            } else {
                opts = first || {};
            }
            return { opts: opts, cb: cb };
        }
        exports.request = function() {
            var n = normaliseRequestArgs(arguments);
            return requestImpl(n.opts, n.cb);
        };
        exports.get = function() {
            var n = normaliseRequestArgs(arguments);
            // Node's `get` auto-ends the request and forces GET.
            if (n.opts && typeof n.opts === 'object') n.opts.method = n.opts.method || 'GET';
            return requestImpl(n.opts, n.cb);
        };

        // -------- server-side createServer ------------------------------

        function createServer(optionsOrListener, maybeListener) {
            // Node signature: createServer([options], [requestListener]).
            var requestListener = typeof optionsOrListener === 'function'
                ? optionsOrListener
                : maybeListener;
            var server = Object.create(EventEmitter.prototype);
            EventEmitter.call(server);

            if (typeof requestListener === 'function') {
                server.on('request', requestListener);
            }

            // Timeout knobs frameworks set unconditionally at construction
            // (fastify, express). Accepted and recorded; the daemon's own
            // request timeout governs actual enforcement.
            server.timeout = 0;
            server.setTimeout = function(ms, cb) {
                server.timeout = ms || 0;
                if (typeof cb === 'function') server.on('timeout', cb);
                return server;
            };

            server.listen = function(portOrOpts, hostOrBacklogOrCb, backlogOrCb, cbArg) {
                // `.listen(port, [host], [backlog], [cb])` and
                // `.listen({port, host, backlog}, [cb])` — both shapes.
                var port;
                var cb;
                if (portOrOpts && typeof portOrOpts === 'object') {
                    port = portOrOpts.port;
                    cb = hostOrBacklogOrCb;
                } else {
                    port = portOrOpts;
                    if (typeof hostOrBacklogOrCb === 'function') cb = hostOrBacklogOrCb;
                    else if (typeof backlogOrCb === 'function') cb = backlogOrCb;
                    else if (typeof cbArg === 'function')       cb = cbArg;
                }
                if (typeof port !== 'number') {
                    throw new TypeError('http.listen: port must be a number');
                }
                if (typeof globalThis.__host_http_listen !== 'function') {
                    // Library one-shot / no daemon — surface as an
                    // async error event rather than a synchronous
                    // throw so `server.on('error', …)` catches it,
                    // matching Node's listen-failure contract.
                    queueMicrotask(function() {
                        var e = new Error('http.listen requires daemon mode (run via `burn` CLI)');
                        e.code = 'EACCES';
                        server.emit('error', e);
                    });
                    return server;
                }
                // Node semantics: a SECOND `.listen(port)` on the same
                // port within the SAME process emits EADDRINUSE on the
                // second Server. The multi-shard daemon's shared-listener
                // mode collapses cross-shard rejoins onto the first
                // server_id, which is correct for multi-shard init; but
                // a within-process re-listen has to fail. We track per-
                // process port ownership in JS so the second call to
                // `.listen(port)` from the same Store emits 'error' /
                // EADDRINUSE without touching the host arbiter.
                if (!globalThis.__ab_http_ports_owned) globalThis.__ab_http_ports_owned = {};
                if (Object.prototype.hasOwnProperty.call(globalThis.__ab_http_ports_owned, port)) {
                    queueMicrotask(function() {
                        var err = new Error('listen EADDRINUSE: address already in use :::' + port);
                        err.code = 'EADDRINUSE';
                        err.port = port;
                        server.emit('error', err);
                    });
                    return server;
                }
                var id = globalThis.__host_http_listen(port);
                if (id <= 0) {
                    // B2b: -1 = no daemon (EACCES), -2 = EADDRINUSE,
                    // -3 = other IO, -4 = manifold listen denial
                    // (EACCES with the host's permission-denied
                    // detail). Node emits 'error' async — we match so
                    // `server.on('error', …)` handlers run.
                    queueMicrotask(function() {
                        var msg = 'http.listen failed (code ' + id + ')';
                        if (id === -4 && typeof globalThis.__host_last_error === 'function') {
                            try {
                                var detail = globalThis.__host_last_error();
                                if (detail) msg = 'http.listen: ' + detail;
                            } catch (_) {}
                        }
                        var err = new Error(msg);
                        if (id === -1 || id === -4) err.code = 'EACCES';
                        else if (id === -2) err.code = 'EADDRINUSE';
                        else err.code = 'EIO';
                        err.port = port;
                        server.emit('error', err);
                    });
                    return server;
                }
                globalThis.__ab_http_ports_owned[port] = id;
                server._serverId = id;
                server._port = port;

                if (!globalThis.__ab_http_handlers) globalThis.__ab_http_handlers = {};
                globalThis.__ab_http_handlers[id] = function(req, res) {
                    server.emit('request', req, res);
                };

                if (cb) {
                    // Node fires the listen callback async — we match
                    // with queueMicrotask so userland observing order
                    // doesn't diverge.
                    queueMicrotask(function() { cb(); });
                }
                server.emit('listening');

                // Cluster-worker hook: forward the listening address to
                // the primary so `cluster.on('listening', ...)` fires
                // on the primary side. No-op in non-cluster mode and
                // in the primary itself.
                try {
                    var _cluster = globalThis.__ab_require_cached_cluster;
                    if (typeof _cluster === 'undefined') {
                        _cluster = require('cluster');
                        globalThis.__ab_require_cached_cluster = _cluster;
                    }
                    if (_cluster && _cluster.isWorker && typeof _cluster._signalListening === 'function') {
                        _cluster._signalListening({
                            address: '127.0.0.1',
                            port: port,
                            family: 'IPv4',
                        });
                    }
                } catch (_) {}
                return server;
            };

            server.close = function(cb) {
                var id = server._serverId;
                if (id && globalThis.__ab_http_handlers) {
                    delete globalThis.__ab_http_handlers[id];
                }
                // Release the per-process port ownership so a fresh
                // `.listen(port)` on the same port succeeds. Match-on-
                // id to avoid clearing ownership a sibling Server holds
                // (shared-listener mode in multi-shard pools).
                if (
                    server._port != null
                    && globalThis.__ab_http_ports_owned
                    && globalThis.__ab_http_ports_owned[server._port] === id
                ) {
                    delete globalThis.__ab_http_ports_owned[server._port];
                }
                // B2b: release the port so a subsequent `.listen(port)`
                // on the same port succeeds. No-op if the host import
                // isn't installed (library/no-daemon path).
                if (id && typeof globalThis.__host_http_close === 'function') {
                    globalThis.__host_http_close(id);
                }
                server._serverId = undefined;
                if (cb) queueMicrotask(function() { cb(); });
                server.emit('close');
                return server;
            };

            // Address info stub — Node exposes server.address() returning
            // `{port, family, address}` post-listen.
            server.address = function() {
                if (!server._serverId) return null;
                return { port: server._port, family: 'IPv4', address: '0.0.0.0' };
            };

            // Symbol.asyncDispose (Node 20+) — `await using server =
            // http.createServer(...)` calls this when the binding
            // leaves the enclosing block. Wraps `close()` in a Promise.
            server[Symbol.asyncDispose] = function() {
                return new Promise(function(resolve) {
                    server.close(function() { resolve(); });
                });
            };

            return server;
        }

        exports.createServer = createServer;

        // Install the daemon-event dispatcher's `req`/`res` builder on
        // globalThis so the plugin's JS dispatcher (see
        // `afterburner-plugin/src/modes/daemon_event.rs`) can find it
        // regardless of module-load order within user code.
        globalThis.__ab_build_reqres = function(ev) {
            return {
                req: __ab_make_incoming_message(ev.req || {}),
                res: __ab_make_server_response(ev.req_id || 0)
            };
        };

        function __ab_make_incoming_message(reqData) {
            var msg = Object.create(EventEmitter.prototype);
            EventEmitter.call(msg);
            msg.method = reqData.method || 'GET';
            msg.url = reqData.url || '/';
            msg.headers = reqData.headers || {};
            msg.httpVersion = reqData.httpVersion || '1.1';
            // Stream-ish: body arrives as one chunk then 'end'. Deliver in
            // a microtask so listeners attached synchronously after the
            // handler starts still see the data event.
            //
            // Chunk type matters: real Node `IncomingMessage` emits
            // `Buffer`s unless `setEncoding` was called. body-parser /
            // multer / busboy all collect chunks then call
            // `Buffer.concat(chunks)` at `'end'`, which throws if any
            // chunk is a string. Wrap string bodies as Buffer; pass
            // through already-binary inputs.
            var body = reqData.body;
            var delivered = false;
            function deliver() {
                if (delivered) return;
                delivered = true;
                if (body !== undefined && body !== null && body !== '') {
                    var Buf = require('buffer').Buffer;
                    var chunk;
                    if (typeof body === 'string') {
                        chunk = Buf.from(body, 'utf8');
                    } else if (Buf.isBuffer && Buf.isBuffer(body)) {
                        chunk = body;
                    } else if (body && typeof body.byteLength === 'number') {
                        // ArrayBuffer / TypedArray — wrap as Buffer
                        // (zero-copy in real Node; copy here for
                        // simplicity since we're already in user-mode
                        // QuickJS).
                        chunk = Buf.from(body);
                    } else {
                        chunk = Buf.from(String(body), 'utf8');
                    }
                    msg.emit('data', chunk);
                }
                msg.emit('end');
            }
            msg._deliver = deliver;
            queueMicrotask(deliver);

            // Convenience: req.text() / req.json() so handlers that want
            // the body in one shot don't need to wire data/end manually.
            msg.text = function() { return Promise.resolve(body); };
            msg.json = function() {
                return new Promise(function(resolve, reject) {
                    try { resolve(JSON.parse(body)); } catch (e) { reject(e); }
                });
            };
            return msg;
        }

        function __ab_make_server_response(reqId) {
            var res = Object.create(EventEmitter.prototype);
            EventEmitter.call(res);
            res.statusCode = 200;
            res.statusMessage = undefined;
            res._headers = {};
            res._buffered = '';
            res.writableEnded = false;
            res.headersSent = false;

            res.setHeader = function(name, value) {
                res._headers[String(name).toLowerCase()] = String(value);
                return res;
            };
            res.getHeader = function(name) {
                return res._headers[String(name).toLowerCase()];
            };
            res.hasHeader = function(name) {
                return Object.prototype.hasOwnProperty.call(
                    res._headers, String(name).toLowerCase()
                );
            };
            res.removeHeader = function(name) {
                delete res._headers[String(name).toLowerCase()];
            };
            res.writeHead = function(status, messageOrHeaders, maybeHeaders) {
                res.statusCode = status;
                var headers;
                if (typeof messageOrHeaders === 'string') {
                    res.statusMessage = messageOrHeaders;
                    headers = maybeHeaders;
                } else {
                    headers = messageOrHeaders;
                }
                if (headers) {
                    Object.keys(headers).forEach(function(k) {
                        res.setHeader(k, headers[k]);
                    });
                }
                return res;
            };
            res.write = function(chunk) {
                if (res.writableEnded) throw new Error('write after end');
                res._buffered += chunk != null ? String(chunk) : '';
                return true;
            };
            res.end = function(chunk) {
                if (res.writableEnded) return;
                if (chunk != null) res._buffered += String(chunk);
                res.writableEnded = true;
                var payload = {
                    status: res.statusCode,
                    headers: res._headers,
                    body: res._buffered
                };
                if (typeof globalThis.__host_http_reply === 'function') {
                    globalThis.__host_http_reply(Number(reqId), JSON.stringify(payload));
                }
                res.emit('finish');
                res.emit('close');
            };

            return res;
        }

        // Expose the helpers on the http module too so tests and
        // advanced consumers can build req/res directly if they need
        // to.
        exports._makeIncomingMessage = __ab_make_incoming_message;
        exports._makeServerResponse  = __ab_make_server_response;

        // `http.METHODS` — sorted, frozen array of every HTTP method
        // Node recognises. Express 5's `lib/utils.js` does
        // `const { METHODS } = require('node:http')` at module load
        // and crashes with `cannot read property 'map' of undefined`
        // when the export is missing. The set below matches Node 22's
        // exposed list.
        exports.METHODS = Object.freeze([
            'ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET',
            'HEAD', 'LINK', 'LOCK', 'M-SEARCH', 'MERGE', 'MKACTIVITY',
            'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH',
            'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND',
            'REPORT', 'SEARCH', 'SOURCE', 'SUBSCRIBE', 'TRACE', 'UNBIND',
            'UNLINK', 'UNLOCK', 'UNSUBSCRIBE',
        ]);

        // `http.STATUS_CODES` — { numeric-status: reason-phrase } map.
        // Used by `finalhandler`, body-parser error responses, and any
        // npm package that maps status numbers to default text. Node's
        // own list is the IANA-registered set; we ship the same.
        exports.STATUS_CODES = {
            100: 'Continue', 101: 'Switching Protocols', 102: 'Processing',
            103: 'Early Hints',
            200: 'OK', 201: 'Created', 202: 'Accepted',
            203: 'Non-Authoritative Information', 204: 'No Content',
            205: 'Reset Content', 206: 'Partial Content',
            207: 'Multi-Status', 208: 'Already Reported', 226: 'IM Used',
            300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found',
            303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy',
            307: 'Temporary Redirect', 308: 'Permanent Redirect',
            400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required',
            403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed',
            406: 'Not Acceptable', 407: 'Proxy Authentication Required',
            408: 'Request Timeout', 409: 'Conflict', 410: 'Gone',
            411: 'Length Required', 412: 'Precondition Failed',
            413: 'Payload Too Large', 414: 'URI Too Long',
            415: 'Unsupported Media Type', 416: 'Range Not Satisfiable',
            417: 'Expectation Failed', 418: "I'm a Teapot",
            421: 'Misdirected Request', 422: 'Unprocessable Entity',
            423: 'Locked', 424: 'Failed Dependency', 425: 'Too Early',
            426: 'Upgrade Required', 428: 'Precondition Required',
            429: 'Too Many Requests', 431: 'Request Header Fields Too Large',
            451: 'Unavailable For Legal Reasons',
            500: 'Internal Server Error', 501: 'Not Implemented',
            502: 'Bad Gateway', 503: 'Service Unavailable',
            504: 'Gateway Timeout', 505: 'HTTP Version Not Supported',
            506: 'Variant Also Negotiates', 507: 'Insufficient Storage',
            508: 'Loop Detected', 509: 'Bandwidth Limit Exceeded',
            510: 'Not Extended', 511: 'Network Authentication Required',
        };

        // Minimal Server/IncomingMessage/ServerResponse constructors.
        // The prototypes inherit from `EventEmitter.prototype` so npm
        // packages that walk `Object.getPrototypeOf(req)` (Express's
        // `setPrototypeOf(req, app.request)` lands the prototype on
        // top of `http.IncomingMessage.prototype`) still find the
        // EventEmitter methods (`on`, `emit`, `once`, `removeListener`).
        // Without the inheritance, Express's request loses `.on` after
        // its init middleware re-roots the prototype chain, and
        // `body-parser`'s `raw-body` throws "argument stream must be
        // a stream".
        //
        // The constructors themselves are not callable — instances
        // come from the `_make*` factories. The classes exist for
        // `instanceof` checks and for npm consumers that read
        // `http.IncomingMessage.prototype`.
        /// `new http.Server([options][, requestListener])` — direct
        /// construction. Equivalent to `http.createServer(options, listener)`
        /// in shape; library code that does `class S extends http.Server`
        /// + `super()` lands here.
        exports.Server = function Server(options, requestListener) {
            if (!(this instanceof exports.Server)) {
                return new exports.Server(options, requestListener);
            }
            if (typeof options === 'function') {
                requestListener = options;
                options = undefined;
            }
            EventEmitter.call(this);
            this._options = options || {};
            this._listening = false;
            this._serverId = undefined;
            this.timeout = (this._options.timeout | 0) || 0;
            this.keepAliveTimeout = 5000;
            this.headersTimeout = 60000;
            this.requestTimeout = 0;
            if (typeof requestListener === 'function') {
                this.on('request', requestListener);
            }
        };
        exports.Server.prototype = Object.create(EventEmitter.prototype);
        exports.Server.prototype.constructor = exports.Server;
        exports.Server.prototype.listen = function() {
            // Forward through to the createServer pipeline by
            // constructing a sibling and re-emitting events back. This
            // is the cleanest way to keep both the direct-construct
            // and createServer paths going through the same daemon
            // listener bookkeeping.
            var inner = exports.createServer();
            var self = this;
            inner.on('request', function(req, res) { self.emit('request', req, res); });
            inner.on('listening', function() { self._listening = true; self.emit('listening'); });
            inner.on('close',     function() { self._listening = false; self.emit('close'); });
            inner.on('error',     function(e) { self.emit('error', e); });
            this._inner = inner;
            inner.listen.apply(inner, arguments);
            return this;
        };
        exports.Server.prototype.close = function(cb) {
            if (this._inner) return this._inner.close(cb);
            if (typeof cb === 'function') Promise.resolve().then(cb);
        };
        exports.Server.prototype.address = function() {
            return this._inner && this._inner.address ? this._inner.address() : null;
        };
        exports.Server.prototype.setTimeout = function(ms, cb) {
            this.timeout = ms | 0;
            if (typeof cb === 'function') this.on('timeout', cb);
            return this;
        };

        /// `new http.IncomingMessage(socket)` — direct construction.
        /// Real Node uses this for testing + subclassing; we produce
        /// a fresh request shape backed by the same factory the
        /// daemon dispatcher uses.
        exports.IncomingMessage = function IncomingMessage(socket) {
            if (!(this instanceof exports.IncomingMessage)) {
                return new exports.IncomingMessage(socket);
            }
            EventEmitter.call(this);
            this.socket = socket || null;
            this.connection = socket || null;
            this.httpVersion = '1.1';
            this.httpVersionMajor = 1;
            this.httpVersionMinor = 1;
            this.complete = false;
            this.headers = {};
            this.rawHeaders = [];
            this.trailers = {};
            this.rawTrailers = [];
            this.aborted = false;
            this.method = 'GET';
            this.url = '/';
            this.statusCode = null;
            this.statusMessage = null;
        };
        exports.IncomingMessage.prototype = Object.create(EventEmitter.prototype);
        exports.IncomingMessage.prototype.constructor = exports.IncomingMessage;
        exports.IncomingMessage.prototype.setTimeout = function(_ms, cb) {
            if (typeof cb === 'function') this.on('timeout', cb);
            return this;
        };
        exports.IncomingMessage.prototype.destroy = function(err) {
            this.aborted = true;
            var self = this;
            Promise.resolve().then(function() {
                if (err) self.emit('error', err);
                self.emit('close');
            });
        };

        /// `new http.ServerResponse(req)` — direct construction.
        /// Used for testing handlers in isolation. Tracks status,
        /// headers, body chunks; `end()` resolves a `_completion`
        /// Promise so test code can `await` the response.
        exports.ServerResponse = function ServerResponse(req) {
            if (!(this instanceof exports.ServerResponse)) {
                return new exports.ServerResponse(req);
            }
            EventEmitter.call(this);
            this.req = req || null;
            this.statusCode = 200;
            this.statusMessage = '';
            this.sendDate = true;
            this.finished = false;
            this.writableEnded = false;
            this.writableFinished = false;
            this.headersSent = false;
            this._headers = {};
            this._chunks = [];
        };
        exports.ServerResponse.prototype = Object.create(EventEmitter.prototype);
        exports.ServerResponse.prototype.constructor = exports.ServerResponse;
        exports.ServerResponse.prototype.setHeader = function(k, v) {
            this._headers[String(k).toLowerCase()] = v;
            return this;
        };
        exports.ServerResponse.prototype.getHeader = function(k) {
            return this._headers[String(k).toLowerCase()];
        };
        exports.ServerResponse.prototype.getHeaders = function() {
            return Object.assign({}, this._headers);
        };
        exports.ServerResponse.prototype.removeHeader = function(k) {
            delete this._headers[String(k).toLowerCase()];
        };
        exports.ServerResponse.prototype.hasHeader = function(k) {
            return Object.prototype.hasOwnProperty.call(this._headers, String(k).toLowerCase());
        };
        // Socket plumbing for response-capture harnesses (light-my-request
        // hands the response a throwaway Writable). We only track the
        // reference; actual bytes flow through write()/end() above.
        exports.ServerResponse.prototype.assignSocket = function(socket) {
            this.socket = socket;
            this.connection = socket;
            return this;
        };
        exports.ServerResponse.prototype.detachSocket = function(_socket) {
            this.socket = null;
            this.connection = null;
            return this;
        };
        exports.ServerResponse.prototype.flushHeaders = function() {
            this.headersSent = true;
        };
        exports.ServerResponse.prototype.writeHead = function(status, statusMsg, headers) {
            this.statusCode = status | 0;
            if (typeof statusMsg === 'string') {
                this.statusMessage = statusMsg;
            } else if (statusMsg && typeof statusMsg === 'object') {
                headers = statusMsg;
            }
            if (headers) {
                var keys = Object.keys(headers);
                for (var i = 0; i < keys.length; i++) {
                    this.setHeader(keys[i], headers[keys[i]]);
                }
            }
            this.headersSent = true;
            return this;
        };
        exports.ServerResponse.prototype.write = function(chunk, _enc, cb) {
            if (chunk != null) this._chunks.push(chunk);
            if (typeof cb === 'function') Promise.resolve().then(cb);
            return true;
        };
        exports.ServerResponse.prototype.end = function(chunk, _enc, cb) {
            if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
            if (chunk != null) this._chunks.push(chunk);
            this.finished = true;
            this.writableEnded = true;
            this.writableFinished = true;
            var self = this;
            Promise.resolve().then(function() {
                self.emit('finish');
                self.emit('close');
                if (typeof cb === 'function') cb();
            });
            return this;
        };
        exports.ServerResponse.prototype.addTrailers = function(headers) {
            this._trailers = Object.assign(this._trailers || {}, headers);
        };
        exports.ServerResponse.prototype.setTimeout = function(_ms, cb) {
            if (typeof cb === 'function') this.on('timeout', cb);
            return this;
        };
        exports.ServerResponse.prototype.flushHeaders = function() {
            this.headersSent = true;
        };

        // `http.Agent` / `https.Agent` — minimal constructable stand-ins.
        // npm's @npmcli/agent and many keep-alive helpers do
        // `class MyAgent extends http.Agent { ... }` at module-init time.
        // Without a real constructor here that fails QuickJS's
        // "parent class must be constructor" guard before any user
        // logic runs. We don't pool sockets (host bridge owns
        // connections); the class exists so subclasses can
        // instantiate.
        function Agent(opts) {
            EventEmitter.call(this);
            this.options    = opts || {};
            this.keepAlive  = !!(this.options.keepAlive);
            this.maxSockets = this.options.maxSockets || Infinity;
            this.maxFreeSockets = this.options.maxFreeSockets || 256;
            this.requests   = {};
            this.sockets    = {};
            this.freeSockets = {};
            this.protocol   = (moduleName === 'https') ? 'https:' : 'http:';
        }
        Agent.prototype = Object.create(EventEmitter.prototype);
        Agent.prototype.constructor = Agent;
        Agent.prototype.addRequest    = function() {};
        Agent.prototype.createConnection = function() { return null; };
        Agent.prototype.keepSocketAlive  = function() { return false; };
        Agent.prototype.reuseSocket      = function() {};
        Agent.prototype.destroy          = function() {};
        Agent.prototype.getName          = function() { return 'afterburner-agent'; };
        exports.Agent = Agent;
        // The default global agent (Node exposes it; libraries pass it
        // around). Single instance, idempotent across requires.
        if (!globalThis.__plenum_default_agents) globalThis.__plenum_default_agents = {};
        if (!globalThis.__plenum_default_agents[moduleName]) {
            globalThis.__plenum_default_agents[moduleName] = new Agent({ keepAlive: false });
        }
        exports.globalAgent = globalThis.__plenum_default_agents[moduleName];

        /// `new http.ClientRequest(options[, callback])` — direct
        /// construction routes through `http.request` so all the
        /// same daemon plumbing applies. Returns the live request
        /// object (extends EventEmitter); `.end()` flushes the body.
        function ClientRequest(options, callback) {
            if (!(this instanceof ClientRequest)) {
                return new ClientRequest(options, callback);
            }
            EventEmitter.call(this);
            // Defer to http.request which already speaks the daemon
            // protocol. We forward all events back so listeners on
            // the bare `new ClientRequest(...)` see them.
            var inner = exports.request(options, callback);
            var self = this;
            ['response','abort','close','connect','continue','error','finish',
             'information','socket','timeout','upgrade'].forEach(function(ev) {
                inner.on(ev, function() {
                    var args = Array.prototype.slice.call(arguments);
                    args.unshift(ev);
                    self.emit.apply(self, args);
                });
            });
            this._inner = inner;
            this.aborted = false;
            this.finished = false;
            this.path = (options && options.path) || '/';
            this.method = (options && options.method) || 'GET';
        }
        ClientRequest.prototype = Object.create(EventEmitter.prototype);
        ClientRequest.prototype.constructor = ClientRequest;
        ClientRequest.prototype.write = function(chunk, enc, cb) {
            return this._inner.write(chunk, enc, cb);
        };
        ClientRequest.prototype.end = function(chunk, enc, cb) {
            this.finished = true;
            return this._inner.end(chunk, enc, cb);
        };
        ClientRequest.prototype.abort = function() {
            this.aborted = true;
            if (typeof this._inner.abort === 'function') this._inner.abort();
            else if (typeof this._inner.destroy === 'function') this._inner.destroy();
        };
        ClientRequest.prototype.destroy = function(err) {
            this.aborted = true;
            if (typeof this._inner.destroy === 'function') this._inner.destroy(err);
        };
        ClientRequest.prototype.setTimeout = function(ms, cb) {
            if (typeof this._inner.setTimeout === 'function') this._inner.setTimeout(ms, cb);
            return this;
        };
        ClientRequest.prototype.setHeader = function(k, v) {
            if (typeof this._inner.setHeader === 'function') this._inner.setHeader(k, v);
            return this;
        };
        ClientRequest.prototype.getHeader = function(k) {
            return this._inner.getHeader && this._inner.getHeader(k);
        };
        ClientRequest.prototype.removeHeader = function(k) {
            if (typeof this._inner.removeHeader === 'function') this._inner.removeHeader(k);
        };
        exports.ClientRequest = ClientRequest;

        // OutgoingMessage — base class some libs subclass.
        function OutgoingMessage() { EventEmitter.call(this); }
        OutgoingMessage.prototype = Object.create(EventEmitter.prototype);
        OutgoingMessage.prototype.constructor = OutgoingMessage;
        OutgoingMessage.prototype.setHeader = function() {};
        OutgoingMessage.prototype.getHeader = function() {};
        OutgoingMessage.prototype.removeHeader = function() {};
        OutgoingMessage.prototype.write = function() { return true; };
        OutgoingMessage.prototype.end = function() {};
        exports.OutgoingMessage = OutgoingMessage;

        // Maximum number of sockets allowed per host — Node default is
        // Infinity, but some libraries read it. Match Node.
        exports.maxHeaderSize = 16384;

        /// `http.validateHeaderName(name)` — Node 14.3+ guard. Throws
        /// ERR_INVALID_HTTP_TOKEN for non-RFC 7230 token chars.
        exports.validateHeaderName = function(name) {
            if (typeof name !== 'string' || name.length === 0) {
                var e = new TypeError('Header name must be a non-empty string');
                e.code = 'ERR_INVALID_HTTP_TOKEN';
                throw e;
            }
            // RFC 7230 token: !#$%&'*+-.^_`|~ + alnum
            for (var i = 0; i < name.length; i++) {
                var c = name.charCodeAt(i);
                var ok = (c === 33 || (c >= 35 && c <= 39) || c === 42 || c === 43 ||
                          c === 45 || c === 46 || (c >= 48 && c <= 57) ||
                          (c >= 65 && c <= 90) || c === 94 || c === 95 || c === 96 ||
                          (c >= 97 && c <= 122) || c === 124 || c === 126);
                if (!ok) {
                    var e2 = new TypeError(
                        'Invalid character in header name "' + name + '"');
                    e2.code = 'ERR_INVALID_HTTP_TOKEN';
                    throw e2;
                }
            }
        };

        /// `http.validateHeaderValue(name, value)` — Node 14.3+ guard.
        /// Throws ERR_HTTP_INVALID_HEADER_VALUE for undefined or
        /// values containing CR/LF/NUL.
        exports.validateHeaderValue = function(name, value) {
            if (value === undefined) {
                var e = new TypeError(
                    'Invalid value "undefined" for header "' + name + '"');
                e.code = 'ERR_HTTP_INVALID_HEADER_VALUE';
                throw e;
            }
            var s = String(value);
            for (var i = 0; i < s.length; i++) {
                var c = s.charCodeAt(i);
                if (c === 0 || c === 10 || c === 13) {
                    var e2 = new TypeError(
                        'Invalid character in header content ["' + name + '"]');
                    e2.code = 'ERR_INVALID_CHAR';
                    throw e2;
                }
            }
        };

        /// `http.setMaxIdleHTTPParsers(n)` — Node 18.8+. Limits the
        /// HTTP parser cache. We don't pool parsers, so this is a
        /// stored-but-unused tunable for Node-shaped probes.
        var _maxIdleHttpParsers = 1000;
        exports.setMaxIdleHTTPParsers = function(n) {
            if (typeof n !== 'number' || n < 1) {
                var e = new RangeError('setMaxIdleHTTPParsers: n must be >= 1');
                e.code = 'ERR_OUT_OF_RANGE';
                throw e;
            }
            _maxIdleHttpParsers = n | 0;
        };

        /// `http.WebSocket` — Node 22+ alias to the global WebSocket
        /// constructor for libraries that expect to import it from the
        /// http module.
        if (typeof globalThis.WebSocket === 'function') {
            exports.WebSocket = globalThis.WebSocket;
        }
    });
}
__plenum_install_http('http');
__plenum_install_http('https');

// ---- http2.js ----
// http2 — Node 20's HTTP/2 module. We wire the client-side API
// (`connect` → `session.request` → stream events) against the host's
// async HTTP outbound (the same path fetch / http.request use).
// Real HTTP/2 frame negotiation happens at the host layer when the
// server supports h2 ALPN; from JS the multiplexing-vs-h1 distinction
// is invisible — the same `:method` / `:path` / `:scheme` /
// `:authority` pseudo-headers translate to a normal HTTP request.
// Server-side http2 (`createSecureServer().listen()`) still surfaces
// `ERR_HTTP2_NOT_IMPLEMENTED` until the host gains an h2 listener;
// most workloads call http2 as a CLIENT, so the surface most code
// hits is now real.

__register_module('http2', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;
    var Buffer = require('buffer').Buffer;
    // The HTTP daemon's auto-protocol listener serves both H1 and H2
    // over the same socket — hyper's auto Builder inspects the H2
    // connection preface and routes accordingly. Server-side http2
    // therefore reuses the http.createServer pipeline; the JS API
    // exposes both `'request'` (Node compat) and `'stream'` (h2-shape)
    // events for the same incoming request.
    var http = require('http');

    function _parseAuthority(authority) {
        try {
            var u = new URL(String(authority));
            return { scheme: u.protocol.replace(':', ''), host: u.hostname, port: u.port };
        } catch (_) {
            var s = String(authority || '');
            var c = s.lastIndexOf(':');
            if (c >= 0 && s.indexOf('://') < 0) {
                return { scheme: 'https', host: s.slice(0, c), port: s.slice(c + 1) };
            }
            return { scheme: 'https', host: s, port: '' };
        }
    }

    // ---- ClientHttp2Stream — bidirectional stream-like ------------
    //
    // Real h2 streams support flow-control and trailers; for the
    // common "send headers + body, read response" pattern we model
    // each as an EventEmitter with `write` / `end` (request body)
    // and emit `response` (with headers) → `data` chunks → `end`.
    function ClientHttp2Stream(session, headers, options) {
        EventEmitter.call(this);
        this._session = session;
        this._headers = headers;
        this._options = options || {};
        this._reqBody = [];
        this._ended = false;
        this._destroyed = false;
        this.id = session._nextStreamId();
        this.session = session;
        this.aborted = false;
        this.closed = false;
        this.pending = true;
        var self = this;
        Promise.resolve().then(function() { self._dispatch(); });
    }
    ClientHttp2Stream.prototype = Object.create(EventEmitter.prototype);
    ClientHttp2Stream.prototype.constructor = ClientHttp2Stream;
    ClientHttp2Stream.prototype.write = function(chunk, _enc, cb) {
        if (this._destroyed) {
            if (typeof cb === 'function') cb(new Error('stream destroyed'));
            return false;
        }
        if (chunk != null) {
            this._reqBody.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
        }
        if (typeof cb === 'function') Promise.resolve().then(cb);
        return true;
    };
    ClientHttp2Stream.prototype.end = function(chunk, _enc, cb) {
        if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
        if (chunk !== undefined) this.write(chunk);
        this._ended = true;
        if (typeof cb === 'function') Promise.resolve().then(cb);
        return this;
    };
    ClientHttp2Stream.prototype.close = function(_code, cb) {
        this.closed = true;
        this._destroyed = true;
        if (typeof cb === 'function') Promise.resolve().then(cb);
    };
    ClientHttp2Stream.prototype.destroy = function(err) {
        if (this._destroyed) return;
        this._destroyed = true;
        this.aborted = !!err;
        var self = this;
        Promise.resolve().then(function() {
            if (err) self.emit('error', err);
            self.emit('close');
        });
    };
    ClientHttp2Stream.prototype.setTimeout = function() { return this; };
    ClientHttp2Stream.prototype.priority = function() {};
    ClientHttp2Stream.prototype.sendTrailers = function() {};

    ClientHttp2Stream.prototype._dispatch = function() {
        var self = this;
        var auth = this._session._parsedAuthority;
        var path = this._headers[':path'] || '/';
        var method = (this._headers[':method'] || 'GET').toUpperCase();
        var scheme = this._headers[':scheme'] || auth.scheme || 'https';
        var url = scheme + '://' + auth.host + (auth.port ? ':' + auth.port : '') + path;

        // Strip pseudo-headers; keep the rest as request headers.
        var reqHeaders = {};
        var keys = Object.keys(this._headers);
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            if (k.charAt(0) !== ':') reqHeaders[k] = this._headers[k];
        }
        var body = this._reqBody.length ? Buffer.concat(this._reqBody).toString('utf8') : null;

        var asyncFn = globalThis.__host_http_request_async;
        var syncFn = globalThis.__host_http_request;
        if (typeof asyncFn !== 'function' && typeof syncFn !== 'function') {
            self.emit('error', new Error('http2: net capability not granted'));
            return;
        }

        function dispatchResponse(result) {
            self.pending = false;
            var responseHeaders = Object.assign({}, result.headers || {});
            responseHeaders[':status'] = result.status;
            self.emit('response', responseHeaders, 0);
            self.emit('headers', responseHeaders, 0);
            var bytes = null;
            if (typeof result.body_b64 === 'string' && result.body_b64.length) {
                bytes = Buffer.from(result.body_b64, 'base64');
            } else if (typeof result.body === 'string') {
                bytes = Buffer.from(result.body, 'utf8');
            } else {
                bytes = Buffer.alloc(0);
            }
            if (bytes.length) self.emit('data', bytes);
            self.emit('end');
            self.emit('close');
        }

        if (typeof asyncFn === 'function') {
            try {
                var rid = asyncFn(method, url, body || null);
                if (typeof rid === 'bigint') rid = Number(rid);
                if (typeof rid === 'number' && rid > 0) {
                    if (!globalThis.__ab_http_pending) globalThis.__ab_http_pending = {};
                    globalThis.__ab_http_pending[rid] = {
                        resolve: function(result) { dispatchResponse(result); },
                    };
                    return;
                }
            } catch (_) {}
        }
        try {
            var rawSync = syncFn(method, url, body || null);
            var resultSync = JSON.parse(rawSync);
            if (typeof resultSync.body === 'string' && resultSync.body.indexOf('__HOST_ERR__:') === 0) {
                self.emit('error', new Error('http2: ' + resultSync.body.slice('__HOST_ERR__:'.length)));
                return;
            }
            dispatchResponse(resultSync);
        } catch (e) {
            self.emit('error', e);
        }
    };

    // ---- ClientHttp2Session ---------------------------------------

    function ClientHttp2Session(authority, _options) {
        EventEmitter.call(this);
        this.closed = false;
        this.destroyed = false;
        this.alpnProtocol = 'h2';
        this.connecting = false;
        this._streamIdCounter = 0;
        this.authority = authority;
        this._parsedAuthority = _parseAuthority(authority);
        var self = this;
        Promise.resolve().then(function() {
            if (!self.destroyed) self.emit('connect', self, /* socket */ null);
        });
    }
    ClientHttp2Session.prototype = Object.create(EventEmitter.prototype);
    ClientHttp2Session.prototype.constructor = ClientHttp2Session;
    ClientHttp2Session.prototype._nextStreamId = function() {
        this._streamIdCounter += 2; // h2 client uses odd ids
        return this._streamIdCounter - 1;
    };
    ClientHttp2Session.prototype.request = function(headers, options) {
        if (this.destroyed) throw new Error('http2: session destroyed');
        return new ClientHttp2Stream(this, headers || {}, options);
    };
    ClientHttp2Session.prototype.close = function(cb) {
        this.closed = true;
        if (typeof cb === 'function') Promise.resolve().then(cb);
    };
    ClientHttp2Session.prototype.destroy = function(err) {
        this.destroyed = true;
        var self = this;
        Promise.resolve().then(function() {
            if (err) self.emit('error', err);
            self.emit('close');
        });
    };
    ClientHttp2Session.prototype.ping = function(payload, callback) {
        if (typeof payload === 'function') { callback = payload; payload = undefined; }
        if (typeof callback === 'function') {
            Promise.resolve().then(function() {
                callback(null, 0, payload || Buffer.alloc(8));
            });
        }
        return true;
    };
    ClientHttp2Session.prototype.settings = function(_settings, cb) {
        if (typeof cb === 'function') Promise.resolve().then(cb);
    };
    ClientHttp2Session.prototype.setTimeout = function() { return this; };
    ClientHttp2Session.prototype.unref = function() { return this; };
    ClientHttp2Session.prototype.ref = function() { return this; };
    Object.defineProperty(ClientHttp2Session.prototype, 'state', {
        get: function() { return { effectiveLocalWindowSize: 65535 }; },
    });

    function connect(authority, options, listener) {
        if (typeof options === 'function') { listener = options; options = undefined; }
        var session = new ClientHttp2Session(authority, options);
        if (typeof listener === 'function') session.on('connect', listener);
        return session;
    }

    // ---- Server side ----------------------------------------------
    //
    // Each Http2Server wraps a real http.Server. Node distinguishes
    // `'request'` (h1-shape `(req, res)`) from `'stream'` (h2-shape
    // `(stream, headers, flags)`). We emit both: the user can attach
    // listeners to either and get the right shape. Callbacks passed
    // to createServer / createSecureServer are wired to `'request'`
    // (Node's default).

    function ServerHttp2Stream(req, res) {
        EventEmitter.call(this);
        this._req = req;
        this._res = res;
        this.id = (ServerHttp2Stream._nextId = (ServerHttp2Stream._nextId || 1) + 2);
        this.aborted = false;
        this.closed = false;
        this.session = null;
        this.pending = false;
        var self = this;
        // Pipe the incoming body into the stream's data/end emitter
        // so user code that consumes the stream as an EventEmitter
        // sees the same bytes the http req would.
        req.on('data', function(chunk) { self.emit('data', chunk); });
        req.on('end', function() { self.emit('end'); });
        req.on('error', function(err) { self.emit('error', err); });
    }
    ServerHttp2Stream.prototype = Object.create(EventEmitter.prototype);
    ServerHttp2Stream.prototype.constructor = ServerHttp2Stream;
    ServerHttp2Stream.prototype.respond = function(headers, _options) {
        var status = headers && headers[':status'] ? headers[':status'] : 200;
        var sendHeaders = {};
        if (headers) {
            var keys = Object.keys(headers);
            for (var i = 0; i < keys.length; i++) {
                var k = keys[i];
                if (k.charAt(0) !== ':') sendHeaders[k] = headers[k];
            }
        }
        this._res.writeHead(status, sendHeaders);
    };
    ServerHttp2Stream.prototype.write = function(chunk, enc, cb) {
        return this._res.write(chunk, enc, cb);
    };
    ServerHttp2Stream.prototype.end = function(chunk, enc, cb) {
        return this._res.end(chunk, enc, cb);
    };
    ServerHttp2Stream.prototype.close = function(_code, cb) {
        this.closed = true;
        try { this._res.end(); } catch (_) {}
        if (typeof cb === 'function') Promise.resolve().then(cb);
    };
    ServerHttp2Stream.prototype.setTimeout = function(ms, cb) {
        if (this._res && typeof this._res.setTimeout === 'function') {
            this._res.setTimeout(ms, cb);
        }
        return this;
    };
    ServerHttp2Stream.prototype.priority = function(_options) {
        // RFC 9218 (Extensible Prioritization Scheme for HTTP) — h3
        // expresses priorities via the `priority` header. We forward
        // the urgency/incremental signals as that header so Node code
        // setting priorities still produces wire-visible output.
        var opts = _options || {};
        var urgency = (opts.weight != null) ? opts.weight | 0 : 16;
        var incremental = !!opts.exclusive ? '?1' : '?0';
        try {
            this._res.setHeader('priority',
                'u=' + urgency + ', i=' + incremental);
        } catch (_) {}
    };
    ServerHttp2Stream.prototype.sendTrailers = function(headers) {
        // Trailers are headers sent after the body. Node exposes
        // `res.addTrailers(headers)` on the underlying ServerResponse;
        // route through that so they actually land on the wire.
        if (!headers) return;
        if (typeof this._res.addTrailers === 'function') {
            this._res.addTrailers(headers);
            return;
        }
        // Last-resort: write them as a final chunk in
        // `key: value\r\n` form before end. Spec-incorrect but
        // produces visible bytes rather than dropping them.
        var keys = Object.keys(headers);
        var lines = '';
        for (var i = 0; i < keys.length; i++) {
            lines += keys[i] + ': ' + headers[keys[i]] + '\r\n';
        }
        if (lines) this._res.write(lines);
    };
    ServerHttp2Stream.prototype.respondWithFile = function(path, headers, options) {
        var self = this;
        var fs = require('fs');
        options = options || {};
        var stat;
        try {
            stat = fs.statSync(path);
        } catch (e) {
            // Run the optional `onError` per Node spec, then close
            // the stream with a 404.
            if (typeof options.onError === 'function') {
                try { options.onError(e); } catch (_) {}
            }
            self.respond({ ':status': 404 });
            self.end();
            return;
        }
        // Node disallows directories for respondWithFile per docs.
        if (stat.isDirectory && stat.isDirectory()) {
            var err = new Error('http2: respondWithFile path is a directory');
            err.code = 'ERR_HTTP2_SEND_FILE';
            if (typeof options.onError === 'function') options.onError(err);
            else self.emit('error', err);
            return;
        }

        var send = headers ? Object.assign({}, headers) : {};
        // Avoid colon-prefixed pseudo-headers leaking into a normal
        // response — strip them defensively.
        Object.keys(send).forEach(function(k) {
            if (k.charAt(0) === ':') delete send[k];
        });
        // Honour Node's offset/length window if the caller asked for
        // a partial-body send.
        var offset = (options.offset | 0) || 0;
        var length = options.length != null
            ? Math.min(options.length | 0, Math.max(0, stat.size - offset))
            : Math.max(0, stat.size - offset);
        if (send['content-length'] == null && send['Content-Length'] == null) {
            send['content-length'] = String(length);
        }
        if (send['last-modified'] == null && send['Last-Modified'] == null
            && stat.mtime instanceof Date) {
            send['last-modified'] = stat.mtime.toUTCString();
        }
        var status = (headers && (headers[':status'] || headers.status)) || 200;
        self.respond(Object.assign({ ':status': status }, send));

        if (length === 0) {
            self.end();
            return;
        }
        // Stream the file in 64 KiB chunks so we don't fault on
        // large bodies. fs.createReadStream supports start/end
        // (inclusive) which maps to offset/length here.
        var stream = fs.createReadStream(path, {
            start: offset,
            end: offset + length - 1,
            highWaterMark: 64 * 1024,
        });
        stream.on('data', function(chunk) { self.write(chunk); });
        stream.on('end', function() { self.end(); });
        stream.on('error', function(e) {
            if (typeof options.onError === 'function') options.onError(e);
            else self.emit('error', e);
            try { self.end(); } catch (_) {}
        });
    };

    function _h1ReqToH2Headers(req) {
        var h = {};
        h[':method'] = req.method;
        h[':path']   = req.url;
        h[':scheme'] = (req.socket && req.socket.encrypted) ? 'https' : 'http';
        h[':authority'] = req.headers && req.headers.host
            ? req.headers.host
            : ((req.connection && req.connection.localAddress) || 'localhost');
        if (req.headers) {
            var keys = Object.keys(req.headers);
            for (var i = 0; i < keys.length; i++) {
                var k = keys[i].toLowerCase();
                if (k === 'host') continue; // already in :authority
                h[k] = req.headers[keys[i]];
            }
        }
        return h;
    }

    function Http2Server(options) {
        EventEmitter.call(this);
        this._options = options || {};
        var self = this;
        // Underlying h1-shape server — daemon serves H2 transparently
        // when the client speaks h2 over the auto-builder listener.
        this._inner = http.createServer(function(req, res) {
            // Always emit 'request' (h1 shape) for compat. If anyone
            // listens to 'stream', also build the h2 shape.
            self.emit('request', req, res);
            if (self.listenerCount('stream') > 0) {
                var headers = _h1ReqToH2Headers(req);
                var stream = new ServerHttp2Stream(req, res);
                self.emit('stream', stream, headers, 0);
            }
        });
        // Re-emit underlying lifecycle events so callers that wait
        // for `'listening'` etc. don't miss them.
        this._inner.on('listening', function() { self.emit('listening'); });
        this._inner.on('close', function() { self.emit('close'); });
        this._inner.on('error', function(e) { self.emit('error', e); });
    }
    Http2Server.prototype = Object.create(EventEmitter.prototype);
    Http2Server.prototype.constructor = Http2Server;
    Http2Server.prototype.listen = function() {
        // Forward the same arguments — `(port[, host[, backlog]][, cb])`.
        this._inner.listen.apply(this._inner, arguments);
        return this;
    };
    Http2Server.prototype.close = function(cb) {
        return this._inner.close(cb);
    };
    Http2Server.prototype.address = function() {
        return this._inner.address ? this._inner.address() : null;
    };
    Http2Server.prototype.setTimeout = function(ms, cb) {
        if (this._inner.setTimeout) this._inner.setTimeout(ms, cb);
        return this;
    };
    Http2Server.prototype.ref = function() {
        if (this._inner.ref) this._inner.ref();
        return this;
    };
    Http2Server.prototype.unref = function() {
        if (this._inner.unref) this._inner.unref();
        return this;
    };

    function createServer(options, onRequest) {
        if (typeof options === 'function') { onRequest = options; options = undefined; }
        var srv = new Http2Server(options);
        if (typeof onRequest === 'function') srv.on('request', onRequest);
        return srv;
    }
    function createSecureServer(options, onRequest) {
        // Burn's daemon does TLS termination separately; the same
        // h2-or-h1 auto-negotiation runs on the cleartext socket.
        // Real TLS H2 will plumb through daemon_tls's ALPN once the
        // tls server adopts hyper-util's Builder.
        return createServer(options, onRequest);
    }

    // ---- constants ------------------------------------------------

    var constants = {
        NGHTTP2_NO_ERROR: 0,
        NGHTTP2_PROTOCOL_ERROR: 1,
        NGHTTP2_INTERNAL_ERROR: 2,
        NGHTTP2_FLOW_CONTROL_ERROR: 3,
        NGHTTP2_SETTINGS_TIMEOUT: 4,
        NGHTTP2_STREAM_CLOSED: 5,
        NGHTTP2_FRAME_SIZE_ERROR: 6,
        NGHTTP2_REFUSED_STREAM: 7,
        NGHTTP2_CANCEL: 8,
        NGHTTP2_COMPRESSION_ERROR: 9,
        NGHTTP2_CONNECT_ERROR: 10,
        NGHTTP2_ENHANCE_YOUR_CALM: 11,
        NGHTTP2_INADEQUATE_SECURITY: 12,
        NGHTTP2_HTTP_1_1_REQUIRED: 13,
        HTTP2_HEADER_AUTHORITY: ':authority',
        HTTP2_HEADER_METHOD: ':method',
        HTTP2_HEADER_PATH: ':path',
        HTTP2_HEADER_SCHEME: ':scheme',
        HTTP2_HEADER_STATUS: ':status',
        HTTP2_HEADER_PROTOCOL: ':protocol',
        HTTP2_METHOD_GET: 'GET',
        HTTP2_METHOD_POST: 'POST',
        HTTP2_METHOD_DELETE: 'DELETE',
        HTTP2_METHOD_PUT: 'PUT',
        HTTP2_METHOD_HEAD: 'HEAD',
        HTTP2_METHOD_OPTIONS: 'OPTIONS',
        HTTP2_METHOD_PATCH: 'PATCH',
    };

    function getDefaultSettings() {
        return {
            headerTableSize: 4096,
            enablePush: true,
            initialWindowSize: 65535,
            maxFrameSize: 16384,
            maxConcurrentStreams: 4294967295,
            maxHeaderListSize: 65535,
            maxHeaderSize: 65535,
        };
    }
    function getPackedSettings() { return Buffer.alloc(0); }
    function getUnpackedSettings() { return getDefaultSettings(); }
    function performServerHandshake() { return createServer(); }
    var SENSITIVE_HEADERS = Symbol.for('http2.sensitiveHeaders');

    exports.connect = connect;
    exports.createServer = createServer;
    exports.createSecureServer = createSecureServer;
    exports.constants = constants;
    exports.Http2Session = ClientHttp2Session;
    exports.ClientHttp2Session = ClientHttp2Session;
    exports.ServerHttp2Session = ClientHttp2Session;
    exports.Http2Stream = ClientHttp2Stream;
    exports.ClientHttp2Stream = ClientHttp2Stream;
    // Http2ServerRequest / Http2ServerResponse — Node exposes these
    // class shapes; we route through the underlying http req/res
    // instances which already have the right surface.
    exports.Http2ServerRequest = http.IncomingMessage || function() {};
    exports.Http2ServerResponse = http.ServerResponse || function() {};
    exports.ServerHttp2Stream = ServerHttp2Stream;
    exports.Http2Server = Http2Server;
    exports.getDefaultSettings = getDefaultSettings;
    exports.getPackedSettings = getPackedSettings;
    exports.getUnpackedSettings = getUnpackedSettings;
    exports.performServerHandshake = performServerHandshake;
    exports.sensitiveHeaders = SENSITIVE_HEADERS;
});

// ---- inspector.js ----
// inspector — Chrome DevTools Protocol bridge.
//
// Two surfaces: an in-process `Session` (`session.post(method, params)`)
// that routes CDP commands through a local dispatcher with no external
// debugger required, and `inspector.open(port)` which boots a real
// HTTP+WebSocket listener on the host (axum-backed) so external tools
// like Chrome DevTools / VS Code can connect over `ws://`. Both share
// the same dispatcher table — a method handled by the in-process
// session is also reachable from a WebSocket client.
//
// CDP coverage in this build:
//
// | Domain     | Methods                                           |
// |------------|---------------------------------------------------|
// | Runtime    | enable, disable, evaluate, runScript,             |
// |            | compileScript, releaseObject, getProperties,      |
// |            | runIfWaitingForDebugger                           |
// | Debugger   | enable, disable, scriptSource, setBreakpointsActive,|
// |            | resume, getScriptSource                           |
// | HeapProfiler | enable, disable, takeHeapSnapshot,             |
// |            | collectGarbage                                    |
// | Profiler   | enable, disable, start, stop, setSamplingInterval |
// | Inspector  | enable                                            |
// | Page       | enable                                            |
//
// Engine-ceiling: full breakpoint stepping requires a QuickJS debug
// hook the upstream engine doesn't expose. `Debugger.setBreakpointByUrl`
// returns `ERR_INSPECTOR_NOT_SUPPORTED_ON_BURN` so callers fail fast
// rather than silently never hitting a breakpoint.

__register_module('inspector', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;

    var _opened = false;
    var _port = 9229;
    var _host = '127.0.0.1';
    var _wsPath = null;
    var _scriptIdCounter = 1;
    var _scriptsById = Object.create(null);
    var _scriptsByUrl = Object.create(null);
    var _executionContextId = 1;
    var _profilerActive = false;
    var _profilerSamples = null;
    var _profilerStartedAt = 0;
    var _profilerSamplingIntervalUs = 1000;

    // ---- Real CDP method table ----------------------------------

    var methods = Object.create(null);

    function registerMethod(name, handler) {
        methods[name] = handler;
    }

    // ---- Runtime ------------------------------------------------

    registerMethod('Runtime.enable', function(_params, _ctx) {
        _ctx.notify('Runtime.executionContextCreated', {
            context: {
                id: _executionContextId,
                origin: '',
                name: 'burn',
                uniqueId: 'burn-' + _executionContextId,
                auxData: {
                    isDefault: true,
                    type: 'default',
                    frameId: 'burn-frame',
                },
            },
        });
        return {};
    });

    registerMethod('Runtime.disable', function() { return {}; });

    registerMethod('Runtime.runIfWaitingForDebugger', function() { return {}; });

    registerMethod('Runtime.evaluate', function(params, _ctx) {
        var expr = (params && params.expression) || '';
        return _evalAndPackage(expr, params || {});
    });

    registerMethod('Runtime.runScript', function(params, _ctx) {
        var src = '';
        if (params && params.scriptId && _scriptsById[params.scriptId]) {
            src = _scriptsById[params.scriptId].source;
        }
        return _evalAndPackage(src, params || {});
    });

    registerMethod('Runtime.compileScript', function(params, _ctx) {
        var src = (params && params.expression) || '';
        var url = (params && params.sourceURL) || '';
        var sid = String(_scriptIdCounter++);
        var entry = { source: src, url: url };
        _scriptsById[sid] = entry;
        if (url) _scriptsByUrl[url] = sid;
        // Pre-flight: try parse via Function() so we surface compile
        // errors right here rather than later at runScript time.
        try {
            new Function(src);
        } catch (e) {
            return {
                exceptionDetails: _wrapException(e),
            };
        }
        return { scriptId: sid };
    });

    registerMethod('Runtime.releaseObject', function() { return {}; });
    registerMethod('Runtime.releaseObjectGroup', function() { return {}; });

    registerMethod('Runtime.getProperties', function(params, _ctx) {
        var oid = (params && params.objectId) || '';
        var ref = _objectTable[oid];
        if (!ref) return { result: [] };
        var props = [];
        try {
            var keys = Object.getOwnPropertyNames(ref);
            for (var i = 0; i < keys.length && i < 256; i++) {
                var k = keys[i];
                var d = Object.getOwnPropertyDescriptor(ref, k) || {};
                props.push({
                    name: k,
                    configurable: !!d.configurable,
                    enumerable: !!d.enumerable,
                    writable: !!d.writable,
                    value: d.value === undefined ? undefined : _packValue(d.value),
                });
            }
        } catch (_) {}
        return { result: props };
    });

    // ---- Debugger -----------------------------------------------

    registerMethod('Debugger.enable', function(_params, _ctx) {
        // Replay scriptParsed for everything compiled so far so the
        // attaching client sees the existing world.
        var ids = Object.keys(_scriptsById);
        for (var i = 0; i < ids.length; i++) {
            var s = _scriptsById[ids[i]];
            _ctx.notify('Debugger.scriptParsed', {
                scriptId: ids[i],
                url: s.url || '',
                startLine: 0,
                startColumn: 0,
                endLine: 0,
                endColumn: s.source ? s.source.length : 0,
                executionContextId: _executionContextId,
                hash: '',
                isLiveEdit: false,
                sourceMapURL: '',
                hasSourceURL: !!s.url,
                isModule: false,
                length: s.source ? s.source.length : 0,
            });
        }
        return { debuggerId: 'burn-debugger' };
    });
    registerMethod('Debugger.disable', function() { return {}; });
    registerMethod('Debugger.setBreakpointsActive', function() { return {}; });
    registerMethod('Debugger.setSkipAllPauses', function() { return {}; });
    registerMethod('Debugger.setPauseOnExceptions', function() { return {}; });
    registerMethod('Debugger.resume', function() { return {}; });
    registerMethod('Debugger.getScriptSource', function(params) {
        var sid = (params && params.scriptId) || '';
        var entry = _scriptsById[sid];
        if (!entry) {
            var err = new Error('Debugger.getScriptSource: unknown scriptId ' + sid);
            err.code = 'ERR_INSPECTOR_COMMAND_FAILED';
            throw err;
        }
        return { scriptSource: entry.source || '' };
    });
    /// Real breakpoint registration backed by source-level statement
    /// instrumentation in the transpiler (`BURN_DEBUGGER_INSTRUMENT=1`).
    /// Each registered breakpoint goes into `_breakpoints` keyed by
    /// `urlPattern + ':' + lineNumber`. The transpiler-injected
    /// `__ab_brk(file, line, col)` check consults this table on every
    /// statement; when a hit is detected, it calls
    /// `__host_inspector_pause` which blocks the JS shard until the
    /// connected DevTools client sends Debugger.resume.
    registerMethod('Debugger.setBreakpointByUrl', function(params, _ctx) {
        var url = (params && params.url) || (params && params.urlRegex) || '';
        var line = (params && params.lineNumber) | 0;
        var col = (params && params.columnNumber) | 0;
        var id = 'burn-bp-' + (++_bpIdCounter);
        _breakpoints[id] = { url: url, line: line, col: col };
        return {
            breakpointId: id,
            locations: [{
                scriptId: '0',
                lineNumber: line,
                columnNumber: col,
            }],
        };
    });
    registerMethod('Debugger.removeBreakpoint', function(params) {
        var id = (params && params.breakpointId) || '';
        delete _breakpoints[id];
        return {};
    });
    var _breakpoints = Object.create(null);
    var _bpIdCounter = 0;
    /// Called from the transpiler-injected `__ab_brk` checks. Looks
    /// up the source location in the active breakpoint table and, if
    /// a match exists, fires the `Debugger.paused` notification then
    /// blocks via `__host_inspector_pause`. Returns the step-kind
    /// code the WS client sent back (0=resume, 1=stepOver, etc.).
    function _checkBreakpoint(file, line, col) {
        var keys = Object.keys(_breakpoints);
        for (var i = 0; i < keys.length; i++) {
            var bp = _breakpoints[keys[i]];
            if (bp.line !== line) continue;
            // URL match — substring or regex. Most DevTools clients
            // pass a fully-qualified `file://...` URL; we match on
            // the trailing path because our file refs are bare paths.
            if (bp.url && bp.url.length > 0 && file.indexOf(bp.url) < 0
                && bp.url.indexOf(file) < 0) {
                continue;
            }
            // Hit.
            var stack;
            try { throw new Error('__brk_stack__'); }
            catch (e) { stack = e.stack || ''; }
            // Notify all sessions.
            if (typeof globalThis.__host_inspector_send === 'function') {
                var note = JSON.stringify({
                    method: 'Debugger.paused',
                    params: {
                        callFrames: [{
                            callFrameId: '0',
                            functionName: '<anonymous>',
                            location: { scriptId: '0', lineNumber: line, columnNumber: col },
                            url: file,
                            scopeChain: [],
                            this: { type: 'object', subtype: 'null' },
                        }],
                        reason: 'other',
                        hitBreakpoints: [keys[i]],
                    },
                });
                try { globalThis.__host_inspector_send(0, note); } catch (_) {}
            }
            if (typeof globalThis.__host_inspector_pause === 'function') {
                return globalThis.__host_inspector_pause() | 0;
            }
            return 0;
        }
        return -1;
    }
    // Global the transpiler-injected probes call.
    globalThis.__ab_brk = function(file, line, col) {
        // Fast path: skip the per-statement work when no breakpoints
        // are registered. Hot loops in non-debugger runs cost one
        // property read + one Object.keys length check.
        if (Object.keys(_breakpoints).length === 0) return;
        _checkBreakpoint(String(file), line | 0, col | 0);
    };

    registerMethod('Debugger.resume', function() { return {}; });
    registerMethod('Debugger.stepOver', function() { return {}; });
    registerMethod('Debugger.stepInto', function() { return {}; });
    registerMethod('Debugger.stepOut', function() { return {}; });

    // ---- HeapProfiler -------------------------------------------

    registerMethod('HeapProfiler.enable', function() { return {}; });
    registerMethod('HeapProfiler.disable', function() { return {}; });
    registerMethod('HeapProfiler.collectGarbage', function() {
        // QuickJS GC is automatic; expose what we can.
        if (typeof globalThis.gc === 'function') {
            try { globalThis.gc(); } catch (_) {}
        }
        return {};
    });

    registerMethod('HeapProfiler.takeHeapSnapshot', function(_params, _ctx) {
        var v8 = require('v8');
        var stream = v8.getHeapSnapshot();
        var chunks = [];
        // The current getHeapSnapshot impl emits one big chunk
        // synchronously via setImmediate. Drain into a buffer; the
        // `addHeapSnapshotChunk` event is the CDP-wire shape.
        return new Promise(function(resolve) {
            stream.on('data', function(buf) {
                chunks.push(buf.toString('utf8'));
            });
            stream.on('end', function() {
                var full = chunks.join('');
                // CDP clients expect the snapshot in fixed-size chunks
                // delivered as `HeapProfiler.addHeapSnapshotChunk`
                // notifications, with the final return value being
                // `{}`. We use 64 KiB pages — small enough that
                // DevTools' progress UI updates smoothly, large
                // enough to keep the count of frames bounded.
                var pageSize = 64 * 1024;
                for (var i = 0; i < full.length; i += pageSize) {
                    _ctx.notify('HeapProfiler.addHeapSnapshotChunk', {
                        chunk: full.slice(i, Math.min(full.length, i + pageSize)),
                    });
                }
                _ctx.notify('HeapProfiler.reportHeapSnapshotProgress', {
                    done: full.length,
                    total: full.length,
                    finished: true,
                });
                resolve({});
            });
        });
    });

    // ---- Profiler -----------------------------------------------

    registerMethod('Profiler.enable', function() { return {}; });
    registerMethod('Profiler.disable', function() { return {}; });

    registerMethod('Profiler.setSamplingInterval', function(params) {
        var us = (params && params.interval) || 1000;
        _profilerSamplingIntervalUs = us;
        return {};
    });

    registerMethod('Profiler.start', function() {
        _profilerActive = true;
        _profilerSamples = [];
        _profilerStartedAt = (Date.now() * 1000) | 0;
        // Sample the call stack on each Promise microtask drain. We
        // can't pre-empt sync code from JS, so on a busy synchronous
        // loop the sample count stays low — that's intrinsic to a
        // userland-hosted profiler. The frames recovered from
        // `Error.stack` are the CDP-wire `CallFrame` payload.
        _profilerSampleScheduler();
        return {};
    });

    registerMethod('Profiler.stop', function() {
        _profilerActive = false;
        var endedAt = (Date.now() * 1000) | 0;
        var samples = _profilerSamples || [];
        _profilerSamples = null;
        // Build a CDP `Profile` value. Nodes are the unique frames
        // observed; samples is the index per tick; timeDeltas is
        // microseconds since the previous sample. Root node id 1.
        var nodes = [{
            id: 1,
            callFrame: { functionName: '(root)', scriptId: '0', url: '', lineNumber: -1, columnNumber: -1 },
            hitCount: 0,
            children: [],
        }];
        var nodeIndex = Object.create(null);
        nodeIndex['(root)|0'] = 1;
        var nextNodeId = 2;
        var sampleIds = [];
        var timeDeltas = [];
        var prevTs = _profilerStartedAt;
        for (var i = 0; i < samples.length; i++) {
            var frame = samples[i].frame || '(anonymous)';
            var key = frame + '|' + i;
            var id = nodeIndex[frame] || (nodeIndex[frame] = nextNodeId++);
            if (!nodes[id - 1]) {
                nodes.push({
                    id: id,
                    callFrame: { functionName: frame, scriptId: '0', url: '', lineNumber: -1, columnNumber: -1 },
                    hitCount: 0,
                    children: [],
                });
            }
            nodes[id - 1].hitCount++;
            sampleIds.push(id);
            var ts = samples[i].ts;
            timeDeltas.push(Math.max(0, ts - prevTs));
            prevTs = ts;
        }
        return {
            profile: {
                nodes: nodes,
                samples: sampleIds,
                timeDeltas: timeDeltas,
                startTime: _profilerStartedAt,
                endTime: endedAt,
            },
        };
    });

    function _profilerSampleScheduler() {
        if (!_profilerActive) return;
        Promise.resolve().then(function() {
            if (!_profilerActive) return;
            var stack;
            try {
                throw new Error('__profile_sample__');
            } catch (e) {
                stack = e.stack || '';
            }
            // First non-internal frame name.
            var frame = '(anonymous)';
            var lines = (stack || '').split('\n');
            for (var i = 1; i < lines.length; i++) {
                var line = lines[i].trim();
                if (line && line.indexOf('__profile_sample__') < 0
                    && line.indexOf('_profilerSampleScheduler') < 0) {
                    var m = line.match(/at\s+([^\s(]+)/);
                    if (m && m[1] && m[1] !== 'Promise.then') {
                        frame = m[1];
                        break;
                    }
                }
            }
            _profilerSamples.push({ frame: frame, ts: (Date.now() * 1000) | 0 });
            // Re-arm. The scheduler runs at microtask cadence; tighter
            // than `setInterval` and bounded only by the loop's pulse.
            _profilerSampleScheduler();
        });
    }

    // ---- Inspector / Page ---------------------------------------

    registerMethod('Inspector.enable', function() { return {}; });
    registerMethod('Page.enable', function() { return {}; });
    registerMethod('Network.enable', function() { return {}; });

    // ---- Object table -------------------------------------------
    //
    // Eval results that aren't primitives get a synthetic ID so a
    // subsequent `Runtime.getProperties({objectId})` can introspect
    // them. Bounded to 1024 live entries — older ones recycle.

    var _objectTable = Object.create(null);
    var _objectTableIds = [];
    var _objectIdCounter = 1;
    var _OBJECT_TABLE_CAP = 1024;

    function _registerObject(value) {
        var id = '{"injectedScriptId":1,"id":' + (_objectIdCounter++) + '}';
        _objectTable[id] = value;
        _objectTableIds.push(id);
        if (_objectTableIds.length > _OBJECT_TABLE_CAP) {
            var stale = _objectTableIds.shift();
            delete _objectTable[stale];
        }
        return id;
    }

    function _typeOf(v) {
        if (v === null) return 'object';
        if (Array.isArray(v)) return 'object';
        return typeof v;
    }

    function _subtypeOf(v) {
        if (v === null) return 'null';
        if (Array.isArray(v)) return 'array';
        if (v instanceof Error) return 'error';
        if (v instanceof RegExp) return 'regexp';
        if (v instanceof Date) return 'date';
        if (v instanceof Map) return 'map';
        if (v instanceof Set) return 'set';
        if (v instanceof Promise) return 'promise';
        return undefined;
    }

    function _packValue(v) {
        var ty = _typeOf(v);
        var sub = _subtypeOf(v);
        if (ty === 'undefined') return { type: 'undefined' };
        if (v === null) return { type: 'object', subtype: 'null', value: null };
        if (ty === 'boolean' || ty === 'number' || ty === 'string') {
            return { type: ty, value: v };
        }
        if (ty === 'bigint') return { type: 'bigint', unserializableValue: String(v) + 'n' };
        if (ty === 'symbol') return { type: 'symbol', description: String(v) };
        if (ty === 'function') {
            return {
                type: 'function',
                className: 'Function',
                description: (function() {
                    try { return v.toString().slice(0, 200); } catch (_) { return 'function'; }
                })(),
                objectId: _registerObject(v),
            };
        }
        // Object / array / error / etc.
        var desc = '';
        try { desc = String(v); } catch (_) { desc = 'Object'; }
        return {
            type: 'object',
            subtype: sub,
            className: (v && v.constructor && v.constructor.name) || 'Object',
            description: desc,
            objectId: _registerObject(v),
        };
    }

    function _wrapException(e) {
        return {
            exceptionId: 0,
            text: 'Uncaught',
            lineNumber: 0,
            columnNumber: 0,
            scriptId: '0',
            exception: _packValue(e && e.message ? new Error(e.message) : e),
        };
    }

    function _evalAndPackage(expr, params) {
        var result;
        var exception = null;
        try {
            // (0, eval) is the canonical idiom for indirect global eval.
            result = (0, eval)(expr);
            // If returnByValue is requested, send the literal value.
            if (params && params.returnByValue) {
                try {
                    JSON.stringify(result);
                    return { result: { type: _typeOf(result), value: result } };
                } catch (_) { /* fall through to packed form */ }
            }
        } catch (e) {
            exception = _wrapException(e);
        }
        if (exception) return { exceptionDetails: exception, result: { type: 'object', subtype: 'error' } };
        return { result: _packValue(result) };
    }

    // ---- Session class ------------------------------------------

    function Session() {
        EventEmitter.call(this);
        this._connected = false;
        this._pendingId = 1;
    }
    Session.prototype = Object.create(EventEmitter.prototype);
    Session.prototype.constructor = Session;

    Session.prototype.connect = function() {
        this._connected = true;
        return this;
    };
    Session.prototype.connectToMainThread = function() { return this.connect(); };
    Session.prototype.disconnect = function() {
        this._connected = false;
        return this;
    };

    Session.prototype.post = function(method, params, callback) {
        if (typeof params === 'function') { callback = params; params = undefined; }
        if (!this._connected) {
            var err = new Error("Session is not connected (call .connect() first)");
            err.code = 'ERR_INSPECTOR_NOT_CONNECTED';
            if (typeof callback === 'function') {
                Promise.resolve().then(function() { callback(err); });
                return;
            }
            throw err;
        }
        var self = this;
        var ctx = {
            notify: function(notifMethod, notifParams) {
                try { self.emit(notifMethod, { method: notifMethod, params: notifParams }); }
                catch (_) {}
                try { self.emit('inspectorNotification', { method: notifMethod, params: notifParams }); }
                catch (_) {}
            },
        };
        var handler = methods[method];
        if (!handler) {
            var nerr = new Error("Inspector method '" + method + "' is not implemented");
            nerr.code = 'ERR_INSPECTOR_COMMAND_UNKNOWN';
            if (typeof callback === 'function') {
                Promise.resolve().then(function() { callback(nerr); });
                return;
            }
            throw nerr;
        }
        var rv;
        try {
            rv = handler(params || {}, ctx);
        } catch (e) {
            if (typeof callback === 'function') {
                Promise.resolve().then(function() { callback(e); });
                return;
            }
            throw e;
        }
        // Handler may return a Promise; resolve before invoking cb.
        if (rv && typeof rv.then === 'function') {
            rv.then(
                function(value) { if (typeof callback === 'function') callback(null, value); },
                function(err) { if (typeof callback === 'function') callback(err); }
            );
        } else if (typeof callback === 'function') {
            Promise.resolve().then(function() { callback(null, rv); });
        }
    };

    // ---- WebSocket-side dispatch (host integration) -------------
    //
    // The host pumps `{kind:"inspector-cmd"}` daemon-event envelopes
    // here when an external CDP client sends a frame. We dispatch
    // through the same `methods` table and reply via __host_inspector_send.

    function _dispatchExternal(sessionKey, id, method, params) {
        var ctx = {
            notify: function(notifMethod, notifParams) {
                _hostSend(sessionKey, {
                    method: notifMethod,
                    params: notifParams,
                });
            },
        };
        var handler = methods[method];
        if (!handler) {
            _hostSend(sessionKey, {
                id: id,
                error: { code: -32601, message: "Method not found: " + method },
            });
            return;
        }
        var rv;
        try { rv = handler(params || {}, ctx); }
        catch (e) {
            _hostSend(sessionKey, {
                id: id,
                error: {
                    code: -32000,
                    message: (e && e.message) || String(e),
                },
            });
            return;
        }
        var send = function(result) {
            _hostSend(sessionKey, { id: id, result: result || {} });
        };
        if (rv && typeof rv.then === 'function') {
            rv.then(send, function(e) {
                _hostSend(sessionKey, {
                    id: id,
                    error: {
                        code: -32000,
                        message: (e && e.message) || String(e),
                    },
                });
            });
        } else {
            send(rv);
        }
    }

    function _hostSend(sessionKey, msg) {
        if (typeof globalThis.__host_inspector_send !== 'function') return;
        try {
            globalThis.__host_inspector_send(sessionKey, JSON.stringify(msg));
        } catch (_) {}
    }

    // Surface the dispatcher so the daemon-event handler can call us.
    globalThis.__ab_inspector_dispatch = _dispatchExternal;

    // ---- inspector.open / close / url ---------------------------

    function open(port, host /*, wait */) {
        if (typeof port === 'number') _port = port;
        if (typeof host === 'string') _host = host;
        if (typeof globalThis.__host_inspector_open !== 'function') {
            // No daemon — keep the surface working but mark closed.
            // Calls to Session.post still work in-process.
            _opened = false;
            _wsPath = null;
            return;
        }
        var rc = globalThis.__host_inspector_open(_port);
        if (rc < 0) {
            var err = new Error('inspector.open: failed (rc=' + rc + ')');
            err.code = 'ERR_INSPECTOR_NOT_AVAILABLE';
            throw err;
        }
        _opened = true;
        // The host returns the actual bound port (rc > 0). Use it
        // — port=0 is a valid request to bind ephemeral.
        if (rc > 0 && rc < 65536) _port = rc;
        _wsPath = '/devtools/page/burn-' + _port;
    }

    function close() {
        if (typeof globalThis.__host_inspector_close === 'function') {
            try { globalThis.__host_inspector_close(); } catch (_) {}
        }
        _opened = false;
        _wsPath = null;
    }

    function url() {
        if (!_opened) return undefined;
        return 'ws://' + _host + ':' + _port + _wsPath;
    }

    function waitForDebugger() {
        // Real Node blocks until Debugger.enable + runIfWaitingForDebugger
        // arrives. The sandboxed model never receives one in offline
        // mode; we surface this as a no-op so callers don't deadlock.
        // External CDP clients that connect via inspector.open() can
        // call Runtime.runIfWaitingForDebugger via the WebSocket which
        // will resolve any pending session.
    }

    exports.open = open;
    exports.close = close;
    exports.url = url;
    exports.waitForDebugger = waitForDebugger;
    exports.console = globalThis.console || { log: function() {} };
    exports.Session = Session;
    exports.Network = {
        requestWillBeSent: function() {},
        responseReceived: function() {},
        loadingFinished: function() {},
        loadingFailed: function() {},
    };
});

// ---- module.js ----
// module — Node 20's introspection for the module loader. Real Node
// exposes this so callers can do `Module.builtinModules`,
// `Module.createRequire(filename)`, etc.

__register_module('module', function(module, exports, require) {

    /// Every Node-built-in name that has a polyfill registered with
    /// the require resolver. Updated when new polyfills land.
    var BUILTINS = [
        'assert', 'async_hooks', 'buffer', 'child_process', 'cluster',
        'console', 'constants', 'crypto', 'dgram', 'dns', 'dns/promises',
        'domain', 'events', 'fs', 'fs/promises', 'http', 'http2', 'https',
        'inspector', 'module', 'net', 'os', 'path', 'path/posix',
        'path/win32', 'perf_hooks', 'process', 'punycode', 'querystring',
        'readline', 'repl', 'stream', 'stream/promises', 'stream/web',
        'string_decoder', 'sys', 'timers', 'timers/promises', 'tls',
        'trace_events', 'tty', 'url', 'util', 'util/types', 'v8', 'vm',
        'wasi', 'worker_threads', 'zlib',
    ];

    /// Burn's `require` is set up at `require.js` bootstrap; callers
    /// asking for a require-from-elsewhere (`createRequire(__filename)`)
    /// get the same object — paths are interpreted from the supplied
    /// filename.
    function createRequire(filename) {
        // Real Node returns a function with `.cache`, `.resolve`, etc.
        // attached. The global require already has those (see
        // require.js). We bind a local proxy that uses `filename`
        // as the resolution base.
        if (typeof filename !== 'string' && !(filename && typeof filename.toString === 'function')) {
            throw new TypeError(
                'module.createRequire: filename must be a string or URL'
            );
        }
        var base = String(filename);
        // Strip `file://` prefix if a URL was passed.
        if (base.indexOf('file://') === 0) base = base.slice(7);

        function localRequire(id) {
            // Defer to the global require with a `from` hint. The
            // require resolver in `require.js` understands this hint.
            if (typeof globalThis.__plenum_require_from === 'function') {
                return globalThis.__plenum_require_from(id, base);
            }
            return globalThis.require(id);
        }
        localRequire.resolve = function(id) {
            if (globalThis.require && globalThis.require.resolve) {
                return globalThis.require.resolve(id);
            }
            return id;
        };
        localRequire.cache = (globalThis.require && globalThis.require.cache) || {};
        localRequire.extensions = (globalThis.require && globalThis.require.extensions) || {};
        localRequire.main = (globalThis.require && globalThis.require.main) || undefined;
        return localRequire;
    }

    function isBuiltin(name) {
        if (typeof name !== 'string') return false;
        var bare = name.indexOf('node:') === 0 ? name.slice(5) : name;
        return BUILTINS.indexOf(bare) !== -1;
    }

    /// `module.register(specifier, parent, opts)` — Node 20+
    /// customization hooks. Loads the specifier in the current realm,
    /// reads its `resolve` / `load` named exports, and appends them
    /// to a global hook chain (`globalThis.__ab_module_hooks`) that
    /// the require resolver consults in registration order before
    /// falling back to its built-in resolution. Burn doesn't isolate
    /// hooks in a worker thread (Node uses a worker for isolation);
    /// the hook runs in the same realm. Pass `data` via `opts.data`
    /// — it's threaded through to the hook on first init.
    function register(specifier, parentURL, opts) {
        if (typeof specifier !== 'string') {
            throw Object.assign(
                new TypeError('module.register: specifier must be a string'),
                { code: 'ERR_INVALID_ARG_TYPE' }
            );
        }
        // Resolve relative to the current require's module context
        // when parentURL is provided as a string URL or path.
        var loaded;
        try {
            loaded = require(specifier);
        } catch (e) {
            throw Object.assign(
                new Error("module.register: failed to load '" + specifier + "': " + (e && e.message)),
                { code: 'ERR_MODULE_REGISTER_FAILED' }
            );
        }
        if (!globalThis.__ab_module_hooks) {
            globalThis.__ab_module_hooks = { hooks: [], data: [] };
        }
        var data = (opts && opts.data) ? opts.data : undefined;
        globalThis.__ab_module_hooks.hooks.push({
            specifier: specifier,
            parentURL: parentURL,
            resolve: typeof loaded.resolve === 'function' ? loaded.resolve : null,
            load: typeof loaded.load === 'function' ? loaded.load : null,
            initialize: typeof loaded.initialize === 'function' ? loaded.initialize : null,
            data: data,
        });
        // Run the hook's `initialize(data)` once at register time, per
        // Node's contract.
        if (typeof loaded.initialize === 'function') {
            try { loaded.initialize(data); } catch (_) {}
        }
        return undefined;
    }
    function getSourceMapsSupport() {
        return {
            enabled: !!globalThis.__ab_source_maps_enabled,
            nodeModules: false,
            generatedCode: !!globalThis.__ab_source_maps_enabled,
        };
    }
    function setSourceMapsSupport(enabled, _opts) {
        globalThis.__ab_source_maps_enabled = !!enabled;
    }
    function findSourceMap(filepath) {
        // Best-effort lookup of an inline source map embedded in the
        // file as `//# sourceMappingURL=data:application/json;base64,...`.
        try {
            var fs = require('fs');
            var src = fs.readFileSync(filepath, 'utf8');
            var idx = src.lastIndexOf('//# sourceMappingURL=data:application/json');
            if (idx < 0) return undefined;
            var line = src.slice(idx);
            var b64 = line.match(/base64,([A-Za-z0-9+/=]+)/);
            if (!b64) return undefined;
            var json = Buffer.from(b64[1], 'base64').toString('utf8');
            return { payload: JSON.parse(json), file: filepath };
        } catch (_) { return undefined; }
    }

    function syncBuiltinESMExports() { /* no-op */ }
    function enableCompileCache() { return { status: 'disabled' }; }
    function flushCompileCache() {}
    function getCompileCacheDir() { return undefined; }

    function Module(id, parent) {
        this.id = id || '';
        this.path = '';
        this.exports = {};
        this.filename = id || '';
        this.loaded = false;
        this.children = [];
        this.parent = parent || null;
    }
    Module.prototype.require = function(id) { return require(id); };
    Module.prototype.load = function(filename) {
        // Run the file as a module — corepack's `loadMainModule` does
        // `module.load(modulePath)` to run the entry script. We
        // delegate to the require resolver and copy the resulting
        // exports onto this Module instance so callers that read
        // `module.exports` after `load()` see the right shape.
        if (filename) {
            this.filename = filename;
            this.id = filename;
        }
        try {
            var loaded = require(this.filename || this.id);
            if (loaded !== undefined) this.exports = loaded;
        } finally {
            this.loaded = true;
        }
    };
    Module._cache = (globalThis.require && globalThis.require.cache) || {};
    Module._pathCache = {};
    Module._extensions = {
        '.js': function() {},
        '.json': function() {},
    };
    // `module._resolveFilename(spec, parent, isMain, options)` — burn's
    // resolver doesn't expose a separate resolve step; we approximate
    // by best-effort: absolute paths return as-is, relative paths
    // resolve against the parent's filename, bare names go through
    // `require.resolve` (which exists when the entry-script wrapper
    // is in scope).
    Module._resolveFilename = function(spec, parent, _isMain, _options) {
        if (typeof spec !== 'string') return String(spec);
        if (spec.charAt(0) === '/' || /^[A-Za-z]:[\\/]/.test(spec)) return spec;
        if (typeof require !== 'undefined' && typeof require.resolve === 'function') {
            try { return require.resolve(spec); } catch (_) {}
        }
        if (parent && parent.filename) {
            var base = parent.filename.replace(/\/[^/]*$/, '');
            return base + '/' + spec;
        }
        return spec;
    };
    // `module._nodeModulePaths(dir)` — list of `node_modules` candidate
    // directories from `dir` up to the filesystem root. Matches
    // Node's behavior; npm / pnpm / corepack use this to walk up.
    Module._nodeModulePaths = function(from) {
        var paths = [];
        var d = String(from || '/');
        while (true) {
            paths.push(d.replace(/\/$/, '') + '/node_modules');
            if (d === '/' || d === '' || /^[A-Za-z]:[\\/]?$/.test(d)) break;
            var parent = d.replace(/\/[^/]*$/, '');
            if (parent === d) break;
            d = parent || '/';
        }
        return paths;
    };
    Module.wrap = function(script) {
        return '(function (exports, require, module, __filename, __dirname) { ' +
               script + '\n});';
    };
    Module.wrapper = [
        '(function (exports, require, module, __filename, __dirname) { ',
        '\n});',
    ];
    Module.builtinModules = BUILTINS.slice();
    Module.createRequire = createRequire;
    Module.isBuiltin = isBuiltin;
    Module.runMain = function() {};
    Module.register = register;
    Module.getSourceMapsSupport = getSourceMapsSupport;
    Module.setSourceMapsSupport = setSourceMapsSupport;
    Module.findSourceMap = findSourceMap;
    Module.syncBuiltinESMExports = syncBuiltinESMExports;
    Module.enableCompileCache = enableCompileCache;
    Module.flushCompileCache = flushCompileCache;
    Module.getCompileCacheDir = getCompileCacheDir;
    Module.SourceMap = function SourceMap() {};
    Module.findPackageJSON = function() { return undefined; };
    Module.constants = {
        compileCacheStatus: { ENABLED: 1, ALREADY_ENABLED: 2, FAILED: 0, DISABLED: 0 },
    };

    exports = Module;
    exports.builtinModules = BUILTINS.slice();
    exports.createRequire = createRequire;
    exports.isBuiltin = isBuiltin;
    exports.Module = Module;
    exports.register = register;
    exports.getSourceMapsSupport = getSourceMapsSupport;
    exports.setSourceMapsSupport = setSourceMapsSupport;
    exports.findSourceMap = findSourceMap;
    exports.syncBuiltinESMExports = syncBuiltinESMExports;
    exports.enableCompileCache = enableCompileCache;
    exports.flushCompileCache = flushCompileCache;
    exports.getCompileCacheDir = getCompileCacheDir;
    exports.runMain = Module.runMain;
    exports.SourceMap = Module.SourceMap;
    exports.findPackageJSON = Module.findPackageJSON;
    exports.constants = Module.constants;

    module.exports = Module;
});

// ---- net.js ----
// net — raw TCP polyfill (B7).
//
// `Socket` is the JS-side façade for a host-owned `tokio::TcpStream`.
// Operations cross into Rust via `__host_net_*` imports; inbound
// bytes / lifecycle events arrive via the daemon-event dispatcher
// as `{kind:"net-..."}` envelopes. The dispatcher routes them
// through `__ab_net_handlers[conn_id]` and
// `__ab_net_server_handlers[server_id]`.
//
// API coverage (minimum-viable for real DB drivers):
//
//   net.connect / net.createConnection
//     ({port, host}[, listener])
//     (port[, host][, listener])
//   socket.{write, end, destroy, setNoDelay, setKeepAlive, setTimeout,
//           address, remoteAddress, remotePort, localAddress, localPort,
//           bytesRead, bytesWritten, destroyed, connecting, readable,
//           writable, pause, resume, on('data'|'end'|'close'|'error'|
//           'connect'|'drain'|'timeout')}
//   net.createServer([options][, connectionListener])
//   server.{listen, close, address, getConnections,
//            on('listening'|'connection'|'close'|'error')}
//   net.{isIP, isIPv4, isIPv6}
//
// Deferred (will throw a clear error if used):
//   - Unix-domain sockets (path-based listen/connect)
//   - net.BlockList
//   - socket.setEncoding (callers should decode bytes themselves)
//   - allowHalfOpen option on Server (always allowed by default)

(function bootstrapNetGlobals() {
    if (!globalThis.__ab_net_handlers) globalThis.__ab_net_handlers = {};
    if (!globalThis.__ab_net_server_handlers) globalThis.__ab_net_server_handlers = {};
})();

__register_module('net', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;
    var Buffer = require('buffer').Buffer;

    // ----- error mapping --------------------------------------------

    function mapHostErrorCode(rc) {
        switch (rc) {
            case -1: return 'ENO_DAEMON';
            case -2: return 'EACCES';
            case -3: return 'ENOTFOUND';
            case -4: return 'EINVAL';
            case -5: return 'EINVAL';
            case -6: return 'EINVAL';
            default: return 'EOTHER';
        }
    }

    function makeError(rc, prefix) {
        var detail = '';
        if (typeof globalThis.__host_last_error === 'function') {
            detail = globalThis.__host_last_error();
        }
        var code = mapHostErrorCode(rc);
        var e = new Error(prefix + ': ' + (detail || ('rc=' + rc)));
        e.code = code;
        return e;
    }

    // ----- Socket ----------------------------------------------------

    function Socket(opts) {
        if (!(this instanceof Socket)) return new Socket(opts);
        EventEmitter.call(this);
        opts = opts || {};

        // Internal state
        this._connId = 0;            // 0 until connect / accept binds it
        this._connecting = false;
        this._destroyed = false;
        // Separate from `_destroyed` so the host's terminal Close event
        // can still emit `'close'` after a user-initiated destroy(). The
        // destroy path flips `_destroyed` synchronously to make
        // `socket.destroyed === true` observable from inside the
        // 'close' listener (Node-compat).
        this._closeEmitted = false;
        this._readable = true;
        this._writable = true;
        this._encoding = null;       // null = emit Buffer; set via setEncoding
        this._wantsDrain = false;    // true after write() returned false
        this._pendingHWM = 64 * 1024;
        this.bytesRead = 0;
        this.bytesWritten = 0;
        this.remoteAddress = undefined;
        this.remotePort = undefined;
        this.remoteFamily = undefined;
        this.localAddress = undefined;
        this.localPort = undefined;

        this._timeoutMs = 0;
        this._timeoutHandle = null;

        // Ready-state mirrors Node's. Set as connect/end/close fire.
        this.readyState = 'opening';
    }
    Socket.prototype = Object.create(EventEmitter.prototype);
    Socket.prototype.constructor = Socket;

    // Internal: bind a host-allocated conn_id to this socket and
    // register so daemon-event dispatch can find us.
    Socket.prototype._attach = function(connId) {
        if (this._connId) {
            // Should never happen unless a caller reuses a Socket.
            throw new Error('net.Socket already attached to conn ' + this._connId);
        }
        this._connId = connId | 0;
        globalThis.__ab_net_handlers[this._connId] = this;
    };

    Socket.prototype._dispatchConnect = function(local, remote) {
        this._connecting = false;
        this.readyState = 'open';
        this.localAddress = local && local.address;
        this.localPort = local && local.port;
        this.remoteAddress = remote && remote.address;
        this.remotePort = remote && remote.port;
        this.remoteFamily = remote && remote.family;
        this._resetTimeout();
        try { this.emit('connect'); } catch (_) {}
        try { this.emit('ready'); } catch (_) {}
    };

    Socket.prototype._dispatchData = function(payloadB64) {
        if (this._destroyed || !this._readable) return;
        this._resetTimeout();
        var bytes;
        try {
            bytes = Buffer.from(payloadB64, 'base64');
        } catch (_) {
            return;
        }
        this.bytesRead += bytes.length;
        // Honour `setEncoding`: when an encoding has been set, decode
        // the chunk before emitting and the 'data' listener gets a
        // string. Otherwise pass the Buffer through.
        var chunk = this._encoding
            ? bytes.toString(this._encoding)
            : bytes;
        try { this.emit('data', chunk); } catch (_) {}
    };

    Socket.prototype._dispatchEnd = function() {
        if (!this._readable) return;
        this._readable = false;
        this.readyState = this._writable ? 'writeOnly' : 'closed';
        try { this.emit('end'); } catch (_) {}
    };

    Socket.prototype._dispatchDrain = function() {
        if (!this._wantsDrain) return;
        this._wantsDrain = false;
        try { this.emit('drain'); } catch (_) {}
    };

    Socket.prototype._dispatchError = function(message, code) {
        var e = new Error(message || 'net error');
        e.code = code || 'EOTHER';
        try { this.emit('error', e); } catch (_) {}
    };

    Socket.prototype._dispatchClose = function(hadError) {
        if (this._closeEmitted) return;
        this._closeEmitted = true;
        this._destroyed = true;
        this._readable = false;
        this._writable = false;
        this.readyState = 'closed';
        this._clearTimeout();
        try { this.emit('close', !!hadError); } catch (_) {}
        if (this._connId) {
            delete globalThis.__ab_net_handlers[this._connId];
        }
    };

    Socket.prototype.connect = function() {
        // connect(port, host?, cb?) | connect({port, host}, cb?)
        var args = Array.prototype.slice.call(arguments);
        var opts;
        var cb;
        if (args.length && typeof args[args.length - 1] === 'function') {
            cb = args.pop();
        }
        if (args.length === 1 && typeof args[0] === 'object' && args[0]) {
            opts = args[0];
        } else {
            opts = { port: args[0], host: args[1] };
        }
        var port = opts.port | 0;
        var host = opts.host || '127.0.0.1';
        if (!port || port < 1 || port > 65535) {
            throw new RangeError('net.connect: port out of range: ' + opts.port);
        }
        this._connecting = true;
        this.readyState = 'opening';
        var rc = globalThis.__host_net_connect(String(host), port);
        if (rc < 0) {
            var err = makeError(rc, 'net.connect');
            // Defer the error event to a microtask so handlers added
            // after connect() (the typical pattern) still fire.
            var self = this;
            Promise.resolve().then(function() {
                self._connecting = false;
                self._destroyed = true;
                self.readyState = 'closed';
                try { self.emit('error', err); } catch (_) {}
                try { self.emit('close', true); } catch (_) {}
            });
            return this;
        }
        this._attach(rc);
        if (cb) this.once('connect', cb);
        return this;
    };

    Socket.prototype.write = function(data, encoding, cb) {
        if (this._destroyed || !this._writable) {
            if (cb) Promise.resolve().then(function() { cb(new Error('not writable')); });
            return false;
        }
        if (typeof encoding === 'function') { cb = encoding; encoding = undefined; }

        var b64;
        if (Buffer.isBuffer(data)) {
            b64 = data.toString('base64');
        } else if (typeof data === 'string') {
            b64 = Buffer.from(data, encoding || 'utf8').toString('base64');
        } else if (data instanceof Uint8Array) {
            b64 = Buffer.from(data).toString('base64');
        } else {
            var t = typeof data;
            throw new TypeError('net.Socket.write: unsupported chunk type ' + t);
        }

        var rc = globalThis.__host_net_write(this._connId, b64);
        if (rc < 0) {
            var err = makeError(rc, 'net.write');
            if (cb) cb(err);
            try { this.emit('error', err); } catch (_) {}
            return false;
        }
        // bytesWritten counts the raw bytes, not the base64 string.
        var n = Buffer.isBuffer(data) ? data.length :
                (typeof data === 'string' ? Buffer.byteLength(data, encoding || 'utf8') :
                 (data && data.length) || 0);
        this.bytesWritten += n;
        this._resetTimeout();
        if (cb) Promise.resolve().then(cb);

        var pending = globalThis.__host_net_pending(this._connId) | 0;
        if (pending >= this._pendingHWM) {
            this._wantsDrain = true;
            return false;
        }
        return true;
    };

    Socket.prototype.end = function(data, encoding, cb) {
        if (typeof data === 'function') { cb = data; data = undefined; encoding = undefined; }
        else if (typeof encoding === 'function') { cb = encoding; encoding = undefined; }
        if (data !== undefined && data !== null) {
            this.write(data, encoding);
        }
        this._writable = false;
        if (this._connId && !this._destroyed) {
            globalThis.__host_net_end(this._connId);
        }
        if (cb) this.once('close', cb);
        return this;
    };

    Socket.prototype.destroy = function(err) {
        if (this._destroyed) return this;
        this._destroyed = true;
        this._readable = false;
        this._writable = false;
        if (this._connId) {
            globalThis.__host_net_destroy(this._connId);
        }
        if (err) {
            try { this.emit('error', err); } catch (_) {}
        }
        return this;
    };

    Socket.prototype.setNoDelay = function(enable) {
        if (this._connId) {
            globalThis.__host_net_set_no_delay(this._connId, enable === false ? 0 : 1);
        }
        return this;
    };

    Socket.prototype.setKeepAlive = function(enable, initialDelay) {
        if (this._connId) {
            globalThis.__host_net_set_keep_alive(
                this._connId,
                enable ? 1 : 0,
                (initialDelay | 0) || 0
            );
        }
        return this;
    };

    Socket.prototype.setTimeout = function(timeout, cb) {
        this._timeoutMs = timeout | 0;
        if (cb) this.on('timeout', cb);
        this._resetTimeout();
        return this;
    };

    Socket.prototype._resetTimeout = function() {
        this._clearTimeout();
        if (this._timeoutMs > 0) {
            var self = this;
            this._timeoutHandle = setTimeout(function() {
                try { self.emit('timeout'); } catch (_) {}
            }, this._timeoutMs);
        }
    };

    Socket.prototype._clearTimeout = function() {
        if (this._timeoutHandle) {
            clearTimeout(this._timeoutHandle);
            this._timeoutHandle = null;
        }
    };

    Socket.prototype.address = function() {
        if (!this.localAddress) return {};
        return {
            address: this.localAddress,
            family: this.remoteFamily ||
                    (String(this.localAddress || '').indexOf(':') >= 0 ? 'IPv6' : 'IPv4'),
            port: this.localPort,
        };
    };

    Socket.prototype.pause = function() {
        // Backpressure on the read side isn't wired in this minimum
        // subset — host always pumps. This is a no-op so callers that
        // call .pause() defensively don't crash.
        return this;
    };
    Socket.prototype.resume = function() { return this; };
    Socket.prototype.ref = function() { return this; };
    Socket.prototype.unref = function() { return this; };
    Socket.prototype.setEncoding = function(encoding) {
        // Buffer.toString validates the encoding name; preserving null
        // / undefined to "reset to Buffer" matches Node's contract.
        if (encoding == null) {
            this._encoding = null;
            return this;
        }
        // Sniff support up front so the first chunk doesn't surprise
        // user code at runtime.
        Buffer.from('').toString(encoding);
        this._encoding = encoding;
        return this;
    };

    Object.defineProperty(Socket.prototype, 'destroyed', {
        get: function() { return this._destroyed; },
    });
    Object.defineProperty(Socket.prototype, 'connecting', {
        get: function() { return this._connecting; },
    });
    Object.defineProperty(Socket.prototype, 'readable', {
        get: function() { return this._readable; },
    });
    Object.defineProperty(Socket.prototype, 'writable', {
        get: function() { return this._writable; },
    });
    Object.defineProperty(Socket.prototype, 'pending', {
        get: function() {
            if (!this._connId) return 0;
            return globalThis.__host_net_pending(this._connId) | 0;
        },
    });

    // ----- Server ----------------------------------------------------

    function Server(opts, connectionListener) {
        if (!(this instanceof Server)) return new Server(opts, connectionListener);
        EventEmitter.call(this);
        if (typeof opts === 'function') {
            connectionListener = opts;
            opts = {};
        }
        this._serverId = 0;
        this._listening = false;
        this._closed = false;
        this._port = 0;
        this._host = '';
        this._connections = new Set();
        if (connectionListener) this.on('connection', connectionListener);
    }
    Server.prototype = Object.create(EventEmitter.prototype);
    Server.prototype.constructor = Server;

    Server.prototype.listen = function() {
        // listen(port[, host][, backlog][, cb])
        // listen({port, host, backlog}[, cb])
        // listen(cb) — port 0
        var args = Array.prototype.slice.call(arguments);
        var cb;
        if (args.length && typeof args[args.length - 1] === 'function') {
            cb = args.pop();
        }
        var opts;
        if (args.length === 1 && typeof args[0] === 'object' && args[0]) {
            opts = args[0];
        } else if (args.length === 0) {
            opts = { port: 0 };
        } else {
            opts = { port: args[0], host: args[1] };
        }
        var port = opts.port | 0;
        var host = opts.host || '0.0.0.0';
        if (port < 0 || port > 65535) {
            throw new RangeError('net.listen: port out of range: ' + opts.port);
        }
        var rc = globalThis.__host_net_listen(String(host), port);
        if (rc < 0) {
            var err = makeError(rc, 'net.listen');
            var self = this;
            Promise.resolve().then(function() {
                try { self.emit('error', err); } catch (_) {}
            });
            return this;
        }
        this._serverId = rc | 0;
        this._port = port;
        this._host = host;
        globalThis.__ab_net_server_handlers[this._serverId] = this;
        if (cb) this.once('listening', cb);
        return this;
    };

    Server.prototype.address = function() {
        if (!this._listening) return null;
        return {
            address: this._host,
            family: this._host.indexOf(':') >= 0 ? 'IPv6' : 'IPv4',
            port: this._port,
        };
    };

    Server.prototype.close = function(cb) {
        if (this._closed) {
            if (cb) Promise.resolve().then(function() { cb(); });
            return this;
        }
        this._closed = true;
        if (this._serverId) {
            globalThis.__host_net_close_server(this._serverId);
            delete globalThis.__ab_net_server_handlers[this._serverId];
        }
        var self = this;
        Promise.resolve().then(function() {
            self._listening = false;
            try { self.emit('close'); } catch (_) {}
            if (cb) cb();
        });
        return this;
    };

    Server.prototype.getConnections = function(cb) {
        var n = this._connections.size;
        Promise.resolve().then(function() { cb(null, n); });
        return this;
    };

    Server.prototype.ref = function() { return this; };
    Server.prototype.unref = function() { return this; };

    Server.prototype._dispatchListening = function(port) {
        this._listening = true;
        this._port = (port | 0) || this._port;
        try { this.emit('listening'); } catch (_) {}
    };

    Server.prototype._dispatchConnection = function(connId, local, remote) {
        var sock = new Socket();
        sock._attach(connId | 0);
        sock._connecting = false;
        sock.readyState = 'open';
        sock.localAddress = local && local.address;
        sock.localPort = local && local.port;
        sock.remoteAddress = remote && remote.address;
        sock.remotePort = remote && remote.port;
        sock.remoteFamily = remote && remote.family;
        var self = this;
        this._connections.add(sock);
        sock.once('close', function() { self._connections.delete(sock); });
        try { this.emit('connection', sock); } catch (_) {}
    };

    Server.prototype._dispatchServerError = function(message) {
        var err = new Error(message || 'net.Server error');
        err.code = 'EOTHER';
        try { this.emit('error', err); } catch (_) {}
    };

    Object.defineProperty(Server.prototype, 'listening', {
        get: function() { return this._listening; },
    });

    // ----- Top-level helpers -----------------------------------------

    function connect() {
        var s = new Socket();
        return s.connect.apply(s, arguments);
    }

    function createServer(opts, listener) {
        return new Server(opts, listener);
    }

    function isIPv4(s) {
        if (typeof s !== 'string') return false;
        var parts = s.split('.');
        if (parts.length !== 4) return false;
        for (var i = 0; i < 4; i++) {
            var p = parts[i];
            if (!/^\d+$/.test(p)) return false;
            var n = parseInt(p, 10);
            if (n < 0 || n > 255) return false;
            if (p.length > 1 && p[0] === '0') return false;
        }
        return true;
    }

    function isIPv6(s) {
        if (typeof s !== 'string' || s.length === 0) return false;
        // Reject obvious junk before letting the regex chew on it.
        if (s.indexOf(' ') >= 0) return false;
        // Permissive match — covers full, compressed (`::`), and
        // IPv4-mapped (`::ffff:1.2.3.4`) forms. Doesn't enforce the
        // single-`::` rule rigorously but that's good enough for the
        // standard library's `isIP` contract.
        var ipv4Tail = '(?:\\d{1,3}\\.){3}\\d{1,3}';
        var hex = '[0-9a-fA-F]{1,4}';
        var regex = new RegExp(
            '^(?:' +
                '(?:' + hex + ':){7}' + hex +                              // 8 groups
                '|(?:' + hex + ':){1,7}:' +                                // ::-prefix
                '|(?:' + hex + ':){1,6}:' + hex +
                '|(?:' + hex + ':){1,5}(?::' + hex + '){1,2}' +
                '|(?:' + hex + ':){1,4}(?::' + hex + '){1,3}' +
                '|(?:' + hex + ':){1,3}(?::' + hex + '){1,4}' +
                '|(?:' + hex + ':){1,2}(?::' + hex + '){1,5}' +
                '|' + hex + ':(?::' + hex + '){1,6}' +
                '|:(?::' + hex + '){1,7}' +
                '|::' +
                '|(?:' + hex + ':){6}' + ipv4Tail +
                '|::(?:' + hex + ':){0,5}' + ipv4Tail +
            ')$'
        );
        return regex.test(s);
    }

    function isIP(s) {
        if (isIPv4(s)) return 4;
        if (isIPv6(s)) return 6;
        return 0;
    }

    // ---- net.BlockList (Node 15+) -----------------------------
    //
    // A list of IP rules with `addAddress` / `addRange` / `addSubnet`
    // and a `check(addr)` that returns true if the address matches.
    // Pure-JS — used by Node apps to gate accepted connections.
    function _ipv4ToInt(s) {
        var p = s.split('.');
        if (p.length !== 4) return -1;
        var n = 0;
        for (var i = 0; i < 4; i++) {
            var b = parseInt(p[i], 10);
            if (!(b >= 0 && b <= 255)) return -1;
            n = (n * 256) + b;
        }
        return n;
    }
    function BlockList() {
        if (!(this instanceof BlockList)) return new BlockList();
        this._rules = [];
    }
    BlockList.prototype.addAddress = function(address, family) {
        family = family || 'ipv4';
        this._rules.push({ kind: 'address', address: String(address), family: family });
    };
    BlockList.prototype.addRange = function(start, end, family) {
        family = family || 'ipv4';
        this._rules.push({ kind: 'range', start: String(start), end: String(end), family: family });
    };
    BlockList.prototype.addSubnet = function(network, prefix, family) {
        family = family || 'ipv4';
        this._rules.push({ kind: 'subnet', network: String(network), prefix: prefix | 0, family: family });
    };
    BlockList.prototype.check = function(address, family) {
        family = family || (isIPv6(address) ? 'ipv6' : 'ipv4');
        var addrStr = String(address);
        for (var i = 0; i < this._rules.length; i++) {
            var r = this._rules[i];
            if (r.family !== family) continue;
            if (r.kind === 'address' && r.address === addrStr) return true;
            if (family === 'ipv4') {
                var n = _ipv4ToInt(addrStr);
                if (n < 0) continue;
                if (r.kind === 'range') {
                    var lo = _ipv4ToInt(r.start), hi = _ipv4ToInt(r.end);
                    if (lo >= 0 && hi >= 0 && n >= lo && n <= hi) return true;
                } else if (r.kind === 'subnet') {
                    var net = _ipv4ToInt(r.network);
                    if (net < 0 || r.prefix < 0 || r.prefix > 32) continue;
                    var mask = r.prefix === 0 ? 0 : (~0 << (32 - r.prefix)) >>> 0;
                    if ((n & mask) === (net & mask)) return true;
                }
            }
            // IPv6 subnet/range matching is string-prefix only here.
            // Real workloads rarely use BlockList for IPv6; expand
            // when a concrete need surfaces.
        }
        return false;
    };
    Object.defineProperty(BlockList.prototype, 'rules', {
        get: function() {
            return this._rules.map(function(r) {
                if (r.kind === 'address') return 'Address: ' + r.family.toUpperCase() + ' ' + r.address;
                if (r.kind === 'range') return 'Range: ' + r.family.toUpperCase() + ' ' + r.start + '-' + r.end;
                return 'Subnet: ' + r.family.toUpperCase() + ' ' + r.network + '/' + r.prefix;
            });
        },
    });

    // ---- net.SocketAddress (Node 15+) -------------------------
    //
    // Immutable address record. In Node it's a transferable across
    // workers; here it's a value-object with the same shape.
    function SocketAddress(options) {
        if (!(this instanceof SocketAddress)) return new SocketAddress(options);
        options = options || {};
        Object.defineProperty(this, 'address', { value: String(options.address || '127.0.0.1'), enumerable: true });
        Object.defineProperty(this, 'port', { value: (options.port | 0) || 0, enumerable: true });
        Object.defineProperty(this, 'family', { value: String(options.family || 'ipv4').toLowerCase(), enumerable: true });
        Object.defineProperty(this, 'flowlabel', { value: (options.flowlabel | 0) || 0, enumerable: true });
    }
    SocketAddress.parse = function(input) {
        if (typeof input !== 'string') return undefined;
        var s = input.trim();
        if (s[0] === '[') {
            var rb = s.indexOf(']');
            if (rb < 0) return undefined;
            var addr = s.slice(1, rb);
            var rest = s.slice(rb + 1);
            var port = rest[0] === ':' ? parseInt(rest.slice(1), 10) : 0;
            return new SocketAddress({ address: addr, port: port, family: 'ipv6' });
        }
        if (isIPv6(s)) return new SocketAddress({ address: s, family: 'ipv6' });
        var c = s.lastIndexOf(':');
        if (c >= 0) {
            return new SocketAddress({ address: s.slice(0, c), port: parseInt(s.slice(c + 1), 10) || 0 });
        }
        return new SocketAddress({ address: s });
    };

    exports.Socket = Socket;
    exports.Server = Server;
    exports.createConnection = connect;
    exports.connect = connect;
    exports.createServer = createServer;
    exports.isIP = isIP;
    exports.isIPv4 = isIPv4;
    exports.isIPv6 = isIPv6;
    exports.BlockList = BlockList;
    exports.SocketAddress = SocketAddress;
});

// ---- node_subpaths.js ----
// Node exposes several "X/promises" paths (and other sub-module
// shapes) as separate require targets. They're thin re-exports of a
// property on the parent module. Registering them here — in a file
// that lexically sorts after the parents — lets `require('node:fs/promises')`
// behave exactly like `require('fs').promises`, matching Node so
// drop-in scripts don't trip on the difference.

// fs/promises → re-export of fs.promises (set in fs.js).
__register_module('fs/promises', function(module, exports, require) {
    module.exports = require('fs').promises;
});

// dns/promises → re-export of dns.promises (set in dns.js).
__register_module('dns/promises', function(module, exports, require) {
    module.exports = require('dns').promises;
});

// stream/promises — Node exposes Promise-returning versions of
// `pipeline` and `finished`. The core `stream` module's sync-callback
// versions are in stream.js; we wrap them here.
__register_module('stream/promises', function(module, exports, require) {
    var stream = require('stream');
    module.exports = {
        pipeline: function() {
            var args = [].slice.call(arguments);
            return new Promise(function(resolve, reject) {
                args.push(function(err, val) { err ? reject(err) : resolve(val); });
                try { stream.pipeline.apply(null, args); } catch (e) { reject(e); }
            });
        },
        finished: function(s, opts) {
            return new Promise(function(resolve, reject) {
                stream.finished(s, opts || {}, function(err) {
                    err ? reject(err) : resolve();
                });
            });
        },
    };
});

// timers/promises — Node exposes Promise-returning delays.
// `setInterval` is documented as an async iterator; we stub it with a
// clear "not implemented" error until a consumer surfaces a need.
// util/types — Node 20's `is*` type-guard helpers. Most production
// code uses these for fast type checks (`util.types.isUint8Array`,
// `isPromise`, `isProxy`, etc.). The pure-JS implementations below
// don't need host-side support.
__register_module('util/types', function(module, exports, require) {
    var Buffer = require('buffer').Buffer;

    function isPromise(v) {
        return !!v && (typeof v === 'object' || typeof v === 'function')
            && typeof v.then === 'function';
    }

    function isAnyArrayBuffer(v) {
        return v instanceof ArrayBuffer ||
            (typeof SharedArrayBuffer !== 'undefined' && v instanceof SharedArrayBuffer);
    }

    function isTypedArray(v) {
        return ArrayBuffer.isView(v) && !(v instanceof DataView);
    }

    function makeTypedCheck(ctor) {
        return function(v) {
            return typeof ctor !== 'undefined' && v instanceof ctor;
        };
    }

    module.exports = {
        isPromise: isPromise,
        isAnyArrayBuffer: isAnyArrayBuffer,
        isArrayBuffer: function(v) { return v instanceof ArrayBuffer; },
        isSharedArrayBuffer: function(v) {
            return typeof SharedArrayBuffer !== 'undefined' && v instanceof SharedArrayBuffer;
        },
        isAsyncFunction: function(v) {
            // QuickJS's `AsyncFunction` constructor isn't a global;
            // fall back to the toString tag, which marks async fns
            // distinctively in any spec-compliant engine.
            return typeof v === 'function' &&
                Object.prototype.toString.call(v) === '[object AsyncFunction]';
        },
        isGeneratorFunction: function(v) {
            return typeof v === 'function' &&
                Object.prototype.toString.call(v) === '[object GeneratorFunction]';
        },
        isGeneratorObject: function(v) {
            return !!v && Object.prototype.toString.call(v) === '[object Generator]';
        },
        isMap: function(v) { return v instanceof Map; },
        isSet: function(v) { return v instanceof Set; },
        isMapIterator: function(v) {
            return !!v && Object.prototype.toString.call(v) === '[object Map Iterator]';
        },
        isSetIterator: function(v) {
            return !!v && Object.prototype.toString.call(v) === '[object Set Iterator]';
        },
        isWeakMap: function(v) { return v instanceof WeakMap; },
        isWeakSet: function(v) { return v instanceof WeakSet; },
        isPromise: isPromise,
        isProxy: function() { return false; }, // Proxies are transparent — can't detect from JS
        isRegExp: function(v) { return v instanceof RegExp; },
        isDate: function(v) { return v instanceof Date; },
        isError: function(v) { return v instanceof Error; },
        isSymbol: function(v) { return typeof v === 'symbol'; },
        isStringObject: function(v) { return typeof v === 'object' && v instanceof String; },
        isNumberObject: function(v) { return typeof v === 'object' && v instanceof Number; },
        isBooleanObject: function(v) { return typeof v === 'object' && v instanceof Boolean; },
        isBigIntObject: function(v) {
            return typeof v === 'object' && v !== null && Object.prototype.toString.call(v) === '[object BigInt]';
        },
        isBoxedPrimitive: function(v) {
            return v instanceof String || v instanceof Number || v instanceof Boolean ||
                (typeof v === 'object' && Object.prototype.toString.call(v) === '[object BigInt]');
        },
        isModuleNamespaceObject: function() { return false; },
        isExternal: function() { return false; },
        isArgumentsObject: function(v) {
            return !!v && Object.prototype.toString.call(v) === '[object Arguments]';
        },
        isArrayBufferView: function(v) { return ArrayBuffer.isView(v); },
        isDataView: function(v) { return v instanceof DataView; },
        isTypedArray: isTypedArray,
        isUint8Array: function(v) { return v instanceof Uint8Array; },
        isUint8ClampedArray: makeTypedCheck(typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : null),
        isUint16Array: function(v) { return v instanceof Uint16Array; },
        isUint32Array: function(v) { return v instanceof Uint32Array; },
        isInt8Array: function(v) { return v instanceof Int8Array; },
        isInt16Array: function(v) { return v instanceof Int16Array; },
        isInt32Array: function(v) { return v instanceof Int32Array; },
        isFloat32Array: function(v) { return v instanceof Float32Array; },
        isFloat64Array: function(v) { return v instanceof Float64Array; },
        isBigInt64Array: makeTypedCheck(typeof BigInt64Array !== 'undefined' ? BigInt64Array : null),
        isBigUint64Array: makeTypedCheck(typeof BigUint64Array !== 'undefined' ? BigUint64Array : null),
        isNativeError: function(v) { return v instanceof Error; },
        isKeyObject: function() { return false; },
        isCryptoKey: function() { return false; },
    };
});

// stream/web — Node 20's WHATWG streams (ReadableStream, WritableStream,
// TransformStream). QuickJS has the spec types as globals; we just
// re-export them under the Node module path so `import { ReadableStream }
// from 'stream/web'` works.
__register_module('stream/web', function(module, exports, require) {
    function notSupported(name) {
        return function() {
            throw new Error('stream/web.' + name + ' is not available in burn yet');
        };
    }
    module.exports = {
        ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : notSupported('ReadableStream'),
        ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader !== 'undefined' ? ReadableStreamDefaultReader : notSupported('ReadableStreamDefaultReader'),
        ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader !== 'undefined' ? ReadableStreamBYOBReader : notSupported('ReadableStreamBYOBReader'),
        WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : notSupported('WritableStream'),
        WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter !== 'undefined' ? WritableStreamDefaultWriter : notSupported('WritableStreamDefaultWriter'),
        TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : notSupported('TransformStream'),
        ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy !== 'undefined' ? ByteLengthQueuingStrategy : notSupported('ByteLengthQueuingStrategy'),
        CountQueuingStrategy: typeof CountQueuingStrategy !== 'undefined' ? CountQueuingStrategy : notSupported('CountQueuingStrategy'),
        TextEncoderStream: typeof TextEncoderStream !== 'undefined' ? TextEncoderStream : notSupported('TextEncoderStream'),
        TextDecoderStream: typeof TextDecoderStream !== 'undefined' ? TextDecoderStream : notSupported('TextDecoderStream'),
        CompressionStream: typeof CompressionStream !== 'undefined' ? CompressionStream : notSupported('CompressionStream'),
        DecompressionStream: typeof DecompressionStream !== 'undefined' ? DecompressionStream : notSupported('DecompressionStream'),
    };
});

// constants — Node 20 exposes a flat namespace of POSIX-ish numeric
// constants (errno values, file modes, etc.) under `require('constants')`.
// Most callers grab a single value (`require('constants').O_RDONLY`),
// so a shallow flat object is enough.
__register_module('constants', function(module, exports, require) {
    var fs = require('fs');
    var os = require('os');
    var crypto = require('crypto');
    var c = {};
    if (fs && fs.constants) Object.assign(c, fs.constants);
    if (os && os.constants) {
        if (os.constants.errno) Object.assign(c, os.constants.errno);
        if (os.constants.signals) Object.assign(c, os.constants.signals);
    }
    if (crypto && crypto.constants) Object.assign(c, crypto.constants);
    module.exports = c;
});

// sys — historical alias for `util` (deprecated in Node 0.x but
// still imported by some older libraries that haven't been touched
// since). Identical surface to `util`.
__register_module('sys', function(module, exports, require) {
    module.exports = require('util');
});

// path/posix and path/win32 — Node exposes POSIX and Win32 path
// implementations as separate require targets in addition to
// `path.posix` / `path.win32`.
__register_module('path/posix', function(module, exports, require) {
    module.exports = require('path').posix || require('path');
});
__register_module('path/win32', function(module, exports, require) {
    module.exports = require('path').win32 || require('path');
});

// readline/promises — Promise-returning Readline. Node 17+. Wraps
// the callback Interface; we expose `question` returning a Promise.
__register_module('readline/promises', function(module, exports, require) {
    var rl = require('readline');
    function createInterface(opts) {
        var iface = rl.createInterface(opts);
        var origQuestion = iface.question.bind(iface);
        iface.question = function(prompt, options) {
            options = options || {};
            return new Promise(function(resolve, reject) {
                if (options.signal && options.signal.aborted) {
                    return reject(new Error('aborted'));
                }
                origQuestion(prompt, function(answer) { resolve(answer); });
                if (options.signal) {
                    options.signal.addEventListener('abort', function() {
                        reject(new Error('aborted'));
                    });
                }
            });
        };
        return iface;
    }
    module.exports = Object.assign({}, rl, {
        createInterface: createInterface,
        Interface: rl.Interface,
    });
});

// inspector/promises — Node 19+. The Session class with promise-style
// `post` / `connect`. We expose the same shape but every call rejects
// with ERR_NOT_SUPPORTED_IN_SANDBOX — V8's inspector requires direct
// engine access we cannot provide through wasm.
__register_module('inspector/promises', function(module, exports, require) {
    var inspector = require('inspector');
    function rej(name) {
        return Promise.reject(Object.assign(
            new Error('inspector.' + name + ' not available in sandbox'),
            { code: 'ERR_NOT_SUPPORTED_IN_SANDBOX' }
        ));
    }
    function Session() { inspector.Session.call(this); }
    Session.prototype = Object.create(inspector.Session.prototype || Object.prototype);
    Session.prototype.connect = function() { return rej('connect'); };
    Session.prototype.connectToMainThread = function() { return rej('connectToMainThread'); };
    Session.prototype.disconnect = function() { return Promise.resolve(); };
    Session.prototype.post = function() { return rej('post'); };
    module.exports = Object.assign({}, inspector, { Session: Session });
});

// stream/consumers — Node 16.7+. Async helpers that drain a readable
// stream and return its full contents. Implementation collects every
// chunk via async-iteration and concatenates Buffer/Uint8Array bytes
// or string segments.
__register_module('stream/consumers', function(module, exports, require) {
    function collect(stream) {
        return (async function() {
            var chunks = [];
            for await (var chunk of stream) chunks.push(chunk);
            if (chunks.length === 0) {
                var Buf0 = globalThis.Buffer;
                return Buf0 ? Buf0.alloc(0) : new Uint8Array(0);
            }
            var Buf = globalThis.Buffer;
            if (Buf && Buf.isBuffer && Buf.isBuffer(chunks[0])) return Buf.concat(chunks);
            if (chunks[0] instanceof Uint8Array) {
                var total = 0;
                for (var i = 0; i < chunks.length; i++) total += chunks[i].length;
                var out = new Uint8Array(total);
                var off = 0;
                for (var j = 0; j < chunks.length; j++) {
                    out.set(chunks[j], off); off += chunks[j].length;
                }
                return out;
            }
            return chunks.map(String).join('');
        })();
    }
    module.exports = {
        text: function(stream) {
            return collect(stream).then(function(b) {
                if (typeof b === 'string') return b;
                if (globalThis.Buffer && globalThis.Buffer.isBuffer && globalThis.Buffer.isBuffer(b))
                    return b.toString('utf8');
                return new globalThis.TextDecoder().decode(b);
            });
        },
        json: function(stream) {
            return module.exports.text(stream).then(JSON.parse);
        },
        arrayBuffer: function(stream) {
            return collect(stream).then(function(b) {
                if (b instanceof Uint8Array)
                    return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
                if (typeof b === 'string')
                    return new globalThis.TextEncoder().encode(b).buffer;
                return new ArrayBuffer(0);
            });
        },
        buffer: function(stream) {
            return collect(stream).then(function(b) {
                var Buf = globalThis.Buffer;
                if (Buf && Buf.isBuffer && Buf.isBuffer(b)) return b;
                if (b instanceof Uint8Array) return Buf ? Buf.from(b) : b;
                return Buf ? Buf.from(String(b), 'utf8')
                           : new globalThis.TextEncoder().encode(b);
            });
        },
        blob: function(stream) {
            return collect(stream).then(function(b) {
                return new globalThis.Blob([b]);
            });
        },
    };
});

// diagnostics_channel — Node 16+. Pub/sub for in-process tracing.
// Same-realm impl: channels keyed by name on a global registry,
// `publish` broadcasts to every subscriber synchronously (matches
// Node's contract — async work belongs in subscribers if needed).
__register_module('diagnostics_channel', function(module, exports, require) {
    if (!globalThis.__plenum_diag_channels) globalThis.__plenum_diag_channels = {};
    var registry = globalThis.__plenum_diag_channels;

    function Channel(name) {
        this.name = name;
        this._subs = [];
    }
    Channel.prototype.publish = function(message) {
        for (var i = 0; i < this._subs.length; i++) {
            try { this._subs[i](message, this.name); }
            catch (_) { /* spec: swallow per subscriber */ }
        }
    };
    Channel.prototype.subscribe = function(onMessage) {
        if (typeof onMessage !== 'function') throw new TypeError('onMessage must be a function');
        this._subs.push(onMessage);
    };
    Channel.prototype.unsubscribe = function(onMessage) {
        var i = this._subs.indexOf(onMessage);
        if (i === -1) return false;
        this._subs.splice(i, 1);
        return true;
    };
    Object.defineProperty(Channel.prototype, 'hasSubscribers', {
        get: function() { return this._subs.length > 0; },
    });
    Channel.prototype.bindStore = function() {};
    Channel.prototype.runStores = function(_data, fn, ctx) { return fn.call(ctx); };

    function channel(name) {
        var n = String(name);
        if (!registry[n]) registry[n] = new Channel(n);
        return registry[n];
    }
    function subscribe(name, onMessage) { channel(name).subscribe(onMessage); }
    function unsubscribe(name, onMessage) { return channel(name).unsubscribe(onMessage); }
    function hasSubscribers(name) { return channel(name).hasSubscribers; }

    function tracingChannel(prefix) {
        var p = (typeof prefix === 'string') ? prefix : 'tracing';
        return {
            start: channel(p + ':start'),
            end: channel(p + ':end'),
            asyncStart: channel(p + ':asyncStart'),
            asyncEnd: channel(p + ':asyncEnd'),
            error: channel(p + ':error'),
            traceSync: function(fn, ctx, _store, _thisArg, args) {
                this.start.publish({ self: ctx, args: args });
                try {
                    var r = fn.apply(ctx, args || []);
                    this.end.publish({ self: ctx, result: r });
                    return r;
                } catch (e) {
                    this.error.publish({ self: ctx, error: e });
                    throw e;
                }
            },
        };
    }

    module.exports = {
        Channel: Channel,
        channel: channel,
        subscribe: subscribe,
        unsubscribe: unsubscribe,
        hasSubscribers: hasSubscribers,
        tracingChannel: tracingChannel,
    };
});

// node:test / node:test/reporters — Node 18+ built-in test runner.
// Real runner: collects describe/it/before/after/beforeEach/afterEach
// blocks, runs them with proper nesting + async support, tracks
// pass / fail / skip / todo counts, and emits a TAP-shaped summary
// to stdout when any tests were registered. Reporter modules at
// `node:test/reporters` provide the `spec` / `tap` / `dot` / `junit`
// / `lcov` exports as Transform streams that pass-through (the
// runner already emits the right shape).
__register_module('test', function(module, exports, require) {
    // Suite tree is built on first describe()/it() call. Each suite
    // holds its own before/after hooks + child suites + tests; the
    // run is triggered on a microtask after the script body settles
    // so test files don't need an explicit `await test.run()`.
    var ROOT = { name: '<root>', children: [], tests: [], hooks: {
        before: [], after: [], beforeEach: [], afterEach: [],
    } };
    var current = ROOT;
    var runScheduled = false;

    function newSuite(name) {
        return { name: name, children: [], tests: [],
                 hooks: { before: [], after: [], beforeEach: [], afterEach: [] } };
    }
    function scheduleRun() {
        if (runScheduled) return;
        runScheduled = true;
        Promise.resolve().then(function() {
            // Avoid running when imported but no tests registered
            // (libraries that conditionally `require('node:test')`
            // for in-source tests).
            if (ROOT.tests.length === 0 && ROOT.children.length === 0) return;
            runSuite(ROOT, '').then(function(stats) {
                if (typeof process !== 'undefined' && typeof process.stdout !== 'undefined') {
                    var line = '\n# tests: ' + stats.total + '\n# pass: ' + stats.pass +
                               '\n# fail: ' + stats.fail + '\n# skip: ' + stats.skip + '\n';
                    if (typeof process.stdout.write === 'function') process.stdout.write(line);
                    else console.log(line);
                }
                if (stats.fail > 0 && typeof process !== 'undefined' && typeof process.exit === 'function') {
                    process.exit(1);
                }
            });
        });
    }

    function describe(name, _opts, fn) {
        if (typeof _opts === 'function') { fn = _opts; _opts = undefined; }
        var suite = newSuite(typeof name === 'string' ? name : '<suite>');
        current.children.push(suite);
        var prev = current;
        current = suite;
        try { if (typeof fn === 'function') fn(); } finally { current = prev; }
        scheduleRun();
    }
    function it(name, _opts, fn) {
        if (typeof _opts === 'function') { fn = _opts; _opts = undefined; }
        var skip = !!(_opts && _opts.skip);
        var todo = !!(_opts && _opts.todo);
        current.tests.push({
            name: typeof name === 'string' ? name : '<test>',
            fn: fn, skip: skip, todo: todo,
        });
        scheduleRun();
    }
    function before(fn)     { current.hooks.before.push(fn); }
    function after(fn)      { current.hooks.after.push(fn); }
    function beforeEach(fn) { current.hooks.beforeEach.push(fn); }
    function afterEach(fn)  { current.hooks.afterEach.push(fn); }

    // The default export `test()` is both the function form AND the
    // namespace. Calling it adds a leaf test at the current scope.
    function test(name, _opts, fn) {
        if (typeof name === 'function') { fn = name; name = '<anonymous>'; }
        if (typeof _opts === 'function') { fn = _opts; _opts = undefined; }
        var skip = !!(_opts && _opts.skip);
        var todo = !!(_opts && _opts.todo);
        current.tests.push({
            name: typeof name === 'string' ? name : '<test>',
            fn: fn, skip: skip, todo: todo,
        });
        scheduleRun();
        // Return a settled Promise so `await test(...)` is well-formed.
        return Promise.resolve();
    }

    async function callHooks(hooks) {
        for (var i = 0; i < hooks.length; i++) {
            try { await hooks[i](); } catch (_) {}
        }
    }
    async function runSuite(suite, indent) {
        var stats = { total: 0, pass: 0, fail: 0, skip: 0 };
        if (suite !== ROOT && suite.name !== '<root>' && typeof process !== 'undefined') {
            console.log(indent + '# Subtest: ' + suite.name);
        }
        await callHooks(suite.hooks.before);
        for (var ti = 0; ti < suite.tests.length; ti++) {
            var t = suite.tests[ti];
            stats.total++;
            if (t.skip) {
                stats.skip++;
                console.log(indent + 'ok ' + stats.total + ' - ' + t.name + ' # SKIP');
                continue;
            }
            if (t.todo) {
                console.log(indent + 'ok ' + stats.total + ' - ' + t.name + ' # TODO');
                continue;
            }
            await callHooks(suite.hooks.beforeEach);
            var ok = true;
            var errMsg = null;
            try { if (typeof t.fn === 'function') await t.fn({ name: t.name }); }
            catch (e) { ok = false; errMsg = (e && e.message) || String(e); }
            await callHooks(suite.hooks.afterEach);
            if (ok) {
                stats.pass++;
                console.log(indent + 'ok ' + stats.total + ' - ' + t.name);
            } else {
                stats.fail++;
                console.log(indent + 'not ok ' + stats.total + ' - ' + t.name);
                if (errMsg) {
                    console.log(indent + '  ---');
                    console.log(indent + '  message: "' + errMsg.replace(/"/g, '\\"') + '"');
                    console.log(indent + '  ...');
                }
            }
        }
        for (var ci = 0; ci < suite.children.length; ci++) {
            var sub = await runSuite(suite.children[ci], indent + '    ');
            stats.total += sub.total;
            stats.pass  += sub.pass;
            stats.fail  += sub.fail;
            stats.skip  += sub.skip;
        }
        await callHooks(suite.hooks.after);
        return stats;
    }

    test.describe = describe;
    test.it = it;
    test.suite = describe;
    test.test = test;
    test.before = before;
    test.after = after;
    test.beforeEach = beforeEach;
    test.afterEach = afterEach;
    test.skip = function(name, fn) { return it(name, { skip: true }, fn); };
    test.todo = function(name, fn) { return it(name, { todo: true }, fn); };
    test.only = function(name, fn) { return it(name, fn); };
    test.run = function() {
        // Async iterator over a snapshot of the current suite tree.
        // Most consumers only check `Symbol.asyncIterator`; we yield
        // one event per test as it runs.
        var done = false;
        return { [Symbol.asyncIterator]: function() {
            return { next: function() {
                if (done) return Promise.resolve({ value: undefined, done: true });
                done = true;
                return runSuite(ROOT, '').then(function(stats) {
                    return { value: { type: 'test:summary', data: stats }, done: false };
                });
            } };
        } };
    };
    /// MockFunctionContext (Node 19.1+) — the per-call record that
    /// `mock.fn` gives back. We track calls in an array so libraries
    /// that probe for `ctx.calls.length`, `ctx.callCount()`, or
    /// `ctx.resetCalls()` work even if the actual mock invocation is
    /// a no-op.
    function MockFunctionContext() {
        this.calls = [];
    }
    MockFunctionContext.prototype.callCount = function() {
        return this.calls.length;
    };
    MockFunctionContext.prototype.resetCalls = function() {
        this.calls = [];
    };
    MockFunctionContext.prototype.restore = function() {};
    MockFunctionContext.prototype.mockImplementation = function() {};
    MockFunctionContext.prototype.mockImplementationOnce = function() {};

    /// MockTracker (Node 19.1+) — the registry returned as `test.mock`.
    /// Real Node tracks every mock created so `restoreAll` can undo
    /// them. Our mocks are no-ops, but we keep the same shape so
    /// `mockTracker.fn().mock.calls` works.
    function MockTracker() {}
    MockTracker.prototype.fn = function(impl) {
        var fn = function() {
            fn.mock.calls.push({
                arguments: Array.prototype.slice.call(arguments),
                this: this, result: undefined, error: undefined,
            });
            return typeof impl === 'function' ? impl.apply(this, arguments) : undefined;
        };
        fn.mock = new MockFunctionContext();
        return fn;
    };
    MockTracker.prototype.method = function() { return function() {}; };
    MockTracker.prototype.getter = function() {};
    MockTracker.prototype.setter = function() {};
    MockTracker.prototype.module = function() {};
    MockTracker.prototype.restoreAll = function() {};
    MockTracker.prototype.reset = function() {};
    Object.defineProperty(MockTracker.prototype, 'timers', {
        get: function() {
            return {
                enable: function() {}, reset: function() {}, tick: function() {},
                runAll: function() {}, setTime: function() {},
            };
        },
    });

    test.mock = new MockTracker();
    test.MockFunctionContext = MockFunctionContext;
    test.MockTracker = MockTracker;

    /// `test.snapshot` (Node 22.3+) — namespace for snapshot config.
    /// We expose `setResolveSnapshotPath` / `setDefaultSnapshotSerializers`
    /// as no-op setters so snapshot-using suites can register their
    /// preferences without crashing.
    test.snapshot = {
        setResolveSnapshotPath: function() {},
        setDefaultSnapshotSerializers: function() {},
    };

    // Dual surface: `import test from 'node:test'` / `require('node:test')`
    // both yield the function-with-namespace shape. Named exports also
    // exposed for `import { describe, it, ... } from 'node:test'`.
    module.exports = test;
    module.exports.default = test;
    Object.assign(module.exports, {
        describe: describe, it: it, suite: describe, test: test,
        before: before, after: after, beforeEach: beforeEach, afterEach: afterEach,
        skip: test.skip, todo: test.todo, only: test.only,
        run: test.run, mock: test.mock,
        MockFunctionContext: MockFunctionContext, MockTracker: MockTracker,
        snapshot: test.snapshot,
    });
});

// node:sqlite — Node 22+ built-in SQLite. Distinct module from the
// `shadow-sqlite3` L3 shadow (which mimics the `sqlite3` npm
// package's callback API). Shares the same `__host_shadow_sqlite3_*`
// host fns underneath.
__register_module('sqlite', function(module, exports, require) {
    function ensureHost(name) {
        var fn = globalThis[name];
        if (typeof fn !== 'function') {
            throw Object.assign(
                new Error('node:sqlite not available: rebuild burn with `shadow-sqlite3`'),
                { code: 'ERR_FEATURE_UNAVAILABLE' }
            );
        }
        return fn;
    }
    function lastError() {
        var fn = globalThis.__host_last_error;
        return typeof fn === 'function' ? fn() : '';
    }
    function checkErrPrefix(raw, op) {
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            throw Object.assign(
                new Error('sqlite.' + op + ': ' + raw.slice('__HOST_ERR__:'.length)),
                { code: 'SQLITE_ERROR' }
            );
        }
        return raw;
    }

    function StatementSync(db, sql) {
        this._db = db;
        this._sql = sql;
        this._returnsExpected = /^\s*(select|with|pragma|values)\b/i.test(sql);
    }
    StatementSync.prototype.run = function() {
        if (this._db._closed) throw new Error('database is closed');
        var args = JSON.stringify([].slice.call(arguments));
        var fn = ensureHost('__host_shadow_sqlite3_run');
        var raw = fn(this._db._id, this._sql, args);
        var resp = checkErrPrefix(raw, 'run');
        var parsed = (typeof resp === 'string' && resp.length) ? JSON.parse(resp) : {};
        return {
            changes: parsed.changes || 0,
            lastInsertRowid: parsed.lastInsertRowid || parsed.lastID || 0,
        };
    };
    StatementSync.prototype.get = function() {
        if (this._db._closed) throw new Error('database is closed');
        var args = JSON.stringify([].slice.call(arguments));
        var fn = ensureHost('__host_shadow_sqlite3_get');
        var raw = checkErrPrefix(fn(this._db._id, this._sql, args), 'get');
        return (typeof raw === 'string' && raw.length) ? JSON.parse(raw) : undefined;
    };
    StatementSync.prototype.all = function() {
        if (this._db._closed) throw new Error('database is closed');
        var args = JSON.stringify([].slice.call(arguments));
        var fn = ensureHost('__host_shadow_sqlite3_all');
        var raw = checkErrPrefix(fn(this._db._id, this._sql, args), 'all');
        return (typeof raw === 'string' && raw.length) ? JSON.parse(raw) : [];
    };
    StatementSync.prototype.iterate = function() {
        return this.all.apply(this, arguments)[Symbol.iterator]();
    };
    StatementSync.prototype.finalize = function() { /* no-op */ };
    StatementSync.prototype.expandedSQL = function() { return this._sql; };
    StatementSync.prototype.sourceSQL = function() { return this._sql; };
    StatementSync.prototype.setReadBigInts = function() { return this; };
    StatementSync.prototype.setAllowBareNamedParameters = function() { return this; };

    function DatabaseSync(filename, options) {
        if (!(this instanceof DatabaseSync)) return new DatabaseSync(filename, options);
        var open = ensureHost('__host_shadow_sqlite3_open');
        var path = String(filename || ':memory:');
        var id = open(path);
        if (id < 0) {
            throw Object.assign(
                new Error('sqlite.DatabaseSync: ' + (lastError() || 'open failed')),
                { code: 'SQLITE_CANTOPEN' }
            );
        }
        this._id = id;
        this._closed = false;
        this.location = path;
        if (options && options.open === false) {
            // Spec: caller calls .open() later. For simplicity we keep
            // the connection open; .open() is then a no-op.
        }
    }
    DatabaseSync.prototype.exec = function(sql) {
        if (this._closed) throw new Error('database is closed');
        var fn = ensureHost('__host_shadow_sqlite3_exec');
        var raw = checkErrPrefix(fn(this._id, String(sql)), 'exec');
        var _ = raw; // discard
    };
    DatabaseSync.prototype.prepare = function(sql) {
        return new StatementSync(this, String(sql));
    };
    DatabaseSync.prototype.close = function() {
        if (this._closed) return;
        var fn = ensureHost('__host_shadow_sqlite3_close');
        try { fn(this._id); } catch (_) {}
        this._closed = true;
        this._id = -1;
    };
    DatabaseSync.prototype.open = function() { /* idempotent in our model */ };
    DatabaseSync.prototype.isOpen = function() { return !this._closed; };
    DatabaseSync.prototype.isTransaction = function() { return false; };
    DatabaseSync.prototype[Symbol.dispose] = DatabaseSync.prototype.close;

    var SQLITE_CONSTANTS = {
        SQLITE_CHANGESET_OMIT: 0,
        SQLITE_CHANGESET_REPLACE: 1,
        SQLITE_CHANGESET_ABORT: 2,
        SQLITE_CHANGESET_DATA: 1,
        SQLITE_CHANGESET_NOTFOUND: 2,
        SQLITE_CHANGESET_CONFLICT: 3,
        SQLITE_CHANGESET_CONSTRAINT: 4,
        SQLITE_CHANGESET_FOREIGN_KEY: 5,
    };

    module.exports = {
        DatabaseSync: DatabaseSync,
        StatementSync: StatementSync,
        constants: SQLITE_CONSTANTS,
        // The Node 22 surface puts changeset constants directly on the
        // module — many libraries import them as named exports.
        SQLITE_CHANGESET_OMIT: SQLITE_CONSTANTS.SQLITE_CHANGESET_OMIT,
        SQLITE_CHANGESET_REPLACE: SQLITE_CONSTANTS.SQLITE_CHANGESET_REPLACE,
        SQLITE_CHANGESET_ABORT: SQLITE_CONSTANTS.SQLITE_CHANGESET_ABORT,
        SQLITE_CHANGESET_DATA: SQLITE_CONSTANTS.SQLITE_CHANGESET_DATA,
        SQLITE_CHANGESET_NOTFOUND: SQLITE_CONSTANTS.SQLITE_CHANGESET_NOTFOUND,
        SQLITE_CHANGESET_CONFLICT: SQLITE_CONSTANTS.SQLITE_CHANGESET_CONFLICT,
        SQLITE_CHANGESET_CONSTRAINT: SQLITE_CONSTANTS.SQLITE_CHANGESET_CONSTRAINT,
        SQLITE_CHANGESET_FOREIGN_KEY: SQLITE_CONSTANTS.SQLITE_CHANGESET_FOREIGN_KEY,
        /// `sqlite.backup(sourceDb, destPath, options?)` — Node 22+
        /// online backup. We implement it via a sequence of SQL
        /// statements that drive SQLite's `VACUUM INTO` semantics
        /// (atomic snapshot to a file path). For an in-memory source
        /// DB this writes the snapshot to disk; for a file source it
        /// produces a consistent copy at `destPath`. Returns a
        /// Promise that resolves to the number of pages copied.
        backup: function(sourceDb, destPath, options) {
            options = options || {};
            return new Promise(function(resolve, reject) {
                try {
                    if (!sourceDb || typeof sourceDb.exec !== 'function') {
                        throw new TypeError('sqlite.backup: source must be a DatabaseSync');
                    }
                    var quoted = "'" + String(destPath).replace(/'/g, "''") + "'";
                    sourceDb.exec('VACUUM INTO ' + quoted);
                    // Page count from the source so callers can assert
                    // a non-zero copy occurred. Fallback to 1 if the
                    // pragma isn't reachable.
                    var pages = 1;
                    try {
                        var stmt = sourceDb.prepare('PRAGMA page_count');
                        var row = stmt.get();
                        pages = (row && (row.page_count | 0)) || 1;
                        if (typeof stmt.finalize === 'function') stmt.finalize();
                    } catch (_) {}
                    if (typeof options.progress === 'function') {
                        try { options.progress({ totalPages: pages, remainingPages: 0 }); }
                        catch (_) {}
                    }
                    resolve(pages);
                } catch (e) { reject(e); }
            });
        },
    };
});

__register_module('test/reporters', function(module, exports, require) {
    var stream = require('stream');
    function passthrough() {
        return new stream.Transform({
            transform: function(chunk, _enc, cb) { cb(null, chunk); },
        });
    }
    // Each reporter is a Transform stream that node:test pipes its
    // event stream into. The runner already emits TAP-shaped lines
    // to stdout; these objects are pass-throughs so user pipelines
    // (`node --test --test-reporter=spec` etc.) compose without
    // crashing. Format-conversion lands when a real consumer needs it.
    module.exports = {
        spec: passthrough,
        tap: passthrough,
        dot: passthrough,
        junit: passthrough,
        lcov: passthrough,
    };
});

// sea (Single Executable Applications) — Node 21+. The sandbox is a
// sealed runtime, so SEA assets aren't applicable. Surface the API
// but report `isSea() === false` so callers fall through to their
// non-SEA path.
__register_module('sea', function(module, exports, require) {
    function notInSea(name) {
        return function() {
            throw Object.assign(
                new Error('sea.' + name + ': not running as SEA'),
                { code: 'ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION' }
            );
        };
    }
    module.exports = {
        isSea: function() { return false; },
        getAsset: notInSea('getAsset'),
        getAssetAsBlob: notInSea('getAssetAsBlob'),
        getRawAsset: notInSea('getRawAsset'),
    };
});

__register_module('timers/promises', function(module, exports, require) {
    module.exports = {
        setTimeout: function(ms, value, opts) {
            var signal = opts && opts.signal;
            return new Promise(function(resolve, reject) {
                if (signal && signal.aborted) {
                    return reject(new Error('The operation was aborted'));
                }
                var t = setTimeout(function() { resolve(value); }, ms);
                if (signal) {
                    signal.addEventListener('abort', function() {
                        clearTimeout(t);
                        reject(new Error('The operation was aborted'));
                    });
                }
            });
        },
        setImmediate: function(value, opts) {
            var signal = opts && opts.signal;
            return new Promise(function(resolve, reject) {
                if (signal && signal.aborted) {
                    return reject(new Error('The operation was aborted'));
                }
                setImmediate(function() { resolve(value); });
            });
        },
        // AsyncIterator surface for `setInterval(ms)` — yields one
        // value per interval until the abort signal fires (or
        // forever, if no signal).
        setInterval: function(ms, value, opts) {
            var signal = opts && opts.signal;
            return {
                [Symbol.asyncIterator]: function() {
                    var done = false;
                    if (signal) {
                        signal.addEventListener('abort', function() { done = true; }, { once: true });
                    }
                    return {
                        next: function() {
                            if (done) return Promise.resolve({ value: undefined, done: true });
                            return new Promise(function(resolve) {
                                setTimeout(function() {
                                    if (done) resolve({ value: undefined, done: true });
                                    else resolve({ value: value, done: false });
                                }, ms);
                            });
                        },
                        return: function() {
                            done = true;
                            return Promise.resolve({ value: undefined, done: true });
                        },
                    };
                },
            };
        },
        // timers/promises.scheduler — Node 18+. wait(ms[, opts])
        // promises a delay-then-resolve; yield() collapses to a
        // microtask so cooperative scheduling works.
        scheduler: {
            wait: function(ms, opts) {
                var signal = opts && opts.signal;
                return new Promise(function(resolve, reject) {
                    if (signal && signal.aborted) {
                        return reject(signal.reason || new Error('Aborted'));
                    }
                    var t = setTimeout(function() { resolve(); }, ms | 0);
                    if (signal) {
                        signal.addEventListener('abort', function() {
                            clearTimeout(t);
                            reject(signal.reason || new Error('Aborted'));
                        }, { once: true });
                    }
                });
            },
            yield: function() { return new Promise(function(r) { queueMicrotask(r); }); },
        },
    };
});

// ---- os.js ----
// os — trivially backed by host globals. No Manifold gating.

__register_module('os', function(module, exports, require) {

    function fallback(name, def) {
        var fn = globalThis['__host_os_' + name];
        return typeof fn === 'function' ? fn() : def;
    }

    exports.platform  = function() { return fallback('platform',  'linux'); };
    exports.arch      = function() { return fallback('arch',      'x64'); };
    exports.hostname  = function() { return fallback('hostname',  'afterburner'); };
    exports.tmpdir    = function() { return fallback('tmpdir',    '/tmp'); };
    exports.homedir   = function() { return fallback('home_dir',  '/'); };
    exports.cpus      = function() {
        var n = fallback('cpus', 1);
        var out = [];
        for (var i = 0; i < n; i++) out.push({ model: 'afterburner', speed: 0 });
        return out;
    };
    /// os.availableParallelism (Node 19+) — number of logical CPUs
    /// the process can use for parallel work. Same value as cpus().length.
    exports.availableParallelism = function() {
        return fallback('cpus', 1);
    };
    exports.totalmem  = function() { return 0; };
    exports.freemem   = function() { return 0; };
    exports.uptime    = function() { return 0; };
    exports.EOL       = '\n';
    exports.type      = function() { return 'Linux'; };
    exports.release   = function() { return '0.0.0-afterburner'; };
    exports.endianness = function() { return 'LE'; };

    // Node's `os.constants`. Packagers (npm @npmcli/fs, fs-extra, pacote)
    // destructure `os.constants.errno.{EEXIST,ENOENT,…}` at module-init
    // time. Missing the table makes the destructure throw `Cannot
    // convert undefined or null to object`, which surfaces as an
    // unrelated-looking failure deep in npm's polyfill chain. Linux x86_64
    // numeric values, matched against Node's own table — they're a
    // fixed kernel ABI on Linux and the constants are read by name in
    // every script we've seen, so the numeric mismatch on other
    // platforms is harmless.
    var ERRNO = {
        E2BIG: 7, EACCES: 13, EADDRINUSE: 98, EADDRNOTAVAIL: 99,
        EAFNOSUPPORT: 97, EAGAIN: 11, EALREADY: 114, EBADF: 9, EBADMSG: 74,
        EBUSY: 16, ECANCELED: 125, ECHILD: 10, ECONNABORTED: 103,
        ECONNREFUSED: 111, ECONNRESET: 104, EDEADLK: 35, EDESTADDRREQ: 89,
        EDOM: 33, EDQUOT: 122, EEXIST: 17, EFAULT: 14, EFBIG: 27,
        EHOSTUNREACH: 113, EIDRM: 43, EILSEQ: 84, EINPROGRESS: 115,
        EINTR: 4, EINVAL: 22, EIO: 5, EISCONN: 106, EISDIR: 21, ELOOP: 40,
        EMFILE: 24, EMLINK: 31, EMSGSIZE: 90, EMULTIHOP: 72, ENAMETOOLONG: 36,
        ENETDOWN: 100, ENETRESET: 102, ENETUNREACH: 101, ENFILE: 23,
        ENOBUFS: 105, ENODATA: 61, ENODEV: 19, ENOENT: 2, ENOEXEC: 8,
        ENOLCK: 37, ENOLINK: 67, ENOMEM: 12, ENOMSG: 42, ENOPROTOOPT: 92,
        ENOSPC: 28, ENOSR: 63, ENOSTR: 60, ENOSYS: 38, ENOTCONN: 107,
        ENOTDIR: 20, ENOTEMPTY: 39, ENOTSOCK: 88, ENOTSUP: 95, ENOTTY: 25,
        ENXIO: 6, EOPNOTSUPP: 95, EOVERFLOW: 75, EPERM: 1, EPIPE: 32,
        EPROTO: 71, EPROTONOSUPPORT: 93, EPROTOTYPE: 91, ERANGE: 34,
        EROFS: 30, ESPIPE: 29, ESRCH: 3, ESTALE: 116, ETIME: 62,
        ETIMEDOUT: 110, ETXTBSY: 26, EWOULDBLOCK: 11, EXDEV: 18,
    };
    var SIGNALS = {
        SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGILL: 4, SIGTRAP: 5, SIGABRT: 6,
        SIGIOT: 6, SIGBUS: 7, SIGFPE: 8, SIGKILL: 9, SIGUSR1: 10, SIGSEGV: 11,
        SIGUSR2: 12, SIGPIPE: 13, SIGALRM: 14, SIGTERM: 15, SIGCHLD: 17,
        SIGSTKFLT: 16, SIGCONT: 18, SIGSTOP: 19, SIGTSTP: 20, SIGTTIN: 21,
        SIGTTOU: 22, SIGURG: 23, SIGXCPU: 24, SIGXFSZ: 25, SIGVTALRM: 26,
        SIGPROF: 27, SIGWINCH: 28, SIGIO: 29, SIGPOLL: 29, SIGPWR: 30,
        SIGSYS: 31, SIGUNUSED: 31,
    };
    var PRIORITY = {
        PRIORITY_LOW: 19, PRIORITY_BELOW_NORMAL: 10, PRIORITY_NORMAL: 0,
        PRIORITY_ABOVE_NORMAL: -7, PRIORITY_HIGH: -14, PRIORITY_HIGHEST: -20,
    };
    exports.constants = {
        UV_UDP_REUSEADDR: 4,
        dlopen: { RTLD_LAZY: 1, RTLD_NOW: 2, RTLD_GLOBAL: 256, RTLD_LOCAL: 0, RTLD_DEEPBIND: 8 },
        errno: ERRNO,
        signals: SIGNALS,
        priority: PRIORITY,
    };

    // os.networkInterfaces(): Node exposes a per-interface object map.
    // npm's `npm-pick-manifest` calls it during prefix detection. Empty
    // map is the right "no enumerable interfaces" answer when we don't
    // surface them through the host bridge.
    exports.networkInterfaces = function() { return {}; };
    exports.userInfo = function(opts) {
        var enc = (opts && opts.encoding) || 'utf8';
        return {
            username: 'afterburner',
            uid: -1,
            gid: -1,
            shell: null,
            homedir: exports.homedir(),
        };
    };
    exports.loadavg     = function() { return [0, 0, 0]; };
    exports.machine     = function() { return fallback('arch', 'x86_64'); };
    exports.version     = function() { return exports.release(); };
    exports.devNull     = '/dev/null';
});

// ---- path.js ----
// path — POSIX subset. Good enough for the overwhelming majority of
// server-side and ETL scripts; the sandbox uses posix paths so win32
// semantics aren't part of this surface.

__register_module('path', function(module, exports, require) {
    var SEP = '/';

    function assertString(x) {
        if (typeof x !== 'string') {
            throw new TypeError("Path must be a string. Received " + typeof x);
        }
    }

    // Collapse `.`, `..`, and redundant separators. Mirrors Node's
    // `normalizeString` helper without bothering to distinguish win32.
    function normalizeString(path, allowAboveRoot) {
        var res = '';
        var lastSegmentLength = 0;
        var lastSlash = -1;
        var dots = 0;
        var code;
        for (var i = 0; i <= path.length; ++i) {
            if (i < path.length) code = path.charCodeAt(i);
            else if (code === 47) break;
            else code = 47;

            if (code === 47) { // '/'
                if (lastSlash === i - 1 || dots === 1) {
                    // no-op
                } else if (lastSlash !== i - 1 && dots === 2) {
                    if (res.length < 2 || lastSegmentLength !== 2 ||
                        res.charCodeAt(res.length - 1) !== 46 ||
                        res.charCodeAt(res.length - 2) !== 46) {
                        if (res.length > 2) {
                            var lastSlashIndex = res.lastIndexOf('/');
                            if (lastSlashIndex === -1) {
                                res = '';
                                lastSegmentLength = 0;
                            } else {
                                res = res.slice(0, lastSlashIndex);
                                lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
                            }
                            lastSlash = i;
                            dots = 0;
                            continue;
                        } else if (res.length === 2 || res.length === 1) {
                            res = '';
                            lastSegmentLength = 0;
                            lastSlash = i;
                            dots = 0;
                            continue;
                        }
                    }
                    if (allowAboveRoot) {
                        if (res.length > 0) res += '/..';
                        else res = '..';
                        lastSegmentLength = 2;
                    }
                } else {
                    if (res.length > 0) res += '/' + path.slice(lastSlash + 1, i);
                    else res = path.slice(lastSlash + 1, i);
                    lastSegmentLength = i - lastSlash - 1;
                }
                lastSlash = i;
                dots = 0;
            } else if (code === 46 && dots !== -1) {
                ++dots;
            } else {
                dots = -1;
            }
        }
        return res;
    }

    exports.sep = SEP;
    exports.delimiter = ':';

    exports.normalize = function(p) {
        assertString(p);
        if (p.length === 0) return '.';
        var isAbs = p.charCodeAt(0) === 47;
        var trailingSep = p.charCodeAt(p.length - 1) === 47;
        p = normalizeString(p, !isAbs);
        if (p.length === 0 && !isAbs) p = '.';
        if (p.length > 0 && trailingSep) p += '/';
        return isAbs ? '/' + p : p;
    };

    exports.isAbsolute = function(p) {
        assertString(p);
        return p.length > 0 && p.charCodeAt(0) === 47;
    };

    exports.join = function() {
        if (arguments.length === 0) return '.';
        var joined;
        for (var i = 0; i < arguments.length; ++i) {
            var arg = arguments[i];
            assertString(arg);
            if (arg.length > 0) {
                if (joined === undefined) joined = arg;
                else joined += '/' + arg;
            }
        }
        if (joined === undefined) return '.';
        return exports.normalize(joined);
    };

    exports.resolve = function() {
        var resolved = '';
        var resolvedAbsolute = false;
        for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
            var p = (i >= 0) ? arguments[i] : '/';
            assertString(p);
            if (p.length === 0) continue;
            resolved = p + '/' + resolved;
            resolvedAbsolute = p.charCodeAt(0) === 47;
        }
        resolved = normalizeString(resolved, !resolvedAbsolute);
        if (resolvedAbsolute) return '/' + resolved;
        return resolved.length > 0 ? resolved : '.';
    };

    exports.dirname = function(p) {
        assertString(p);
        if (p.length === 0) return '.';
        var hasRoot = p.charCodeAt(0) === 47;
        var end = -1;
        var matchedSlash = true;
        for (var i = p.length - 1; i >= 1; --i) {
            if (p.charCodeAt(i) === 47) {
                if (!matchedSlash) { end = i; break; }
            } else {
                matchedSlash = false;
            }
        }
        if (end === -1) return hasRoot ? '/' : '.';
        if (hasRoot && end === 1) return '//';
        return p.slice(0, end);
    };

    // path.relative(from, to) — express the relative path from one
    // absolute path to another. arborist's `relpath`, every workspace
    // resolver, every test runner, and most build tools depend on
    // this. Algorithm matches Node's implementation: resolve both
    // arguments, find the common prefix, walk back from `from` and
    // forward to `to`.
    exports.relative = function(from, to) {
        assertString(from);
        assertString(to);
        if (from === to) return '';
        from = exports.resolve(from);
        to = exports.resolve(to);
        if (from === to) return '';
        // Trim leading slashes for the segment scan; we know both are
        // absolute after `resolve`.
        var fromSegs = from.slice(1).split('/').filter(function(s) { return s.length; });
        var toSegs = to.slice(1).split('/').filter(function(s) { return s.length; });
        var common = 0;
        var max = Math.min(fromSegs.length, toSegs.length);
        while (common < max && fromSegs[common] === toSegs[common]) common++;
        var up = fromSegs.length - common;
        var rest = toSegs.slice(common);
        var out = [];
        for (var i = 0; i < up; i++) out.push('..');
        for (var j = 0; j < rest.length; j++) out.push(rest[j]);
        return out.join('/') || '.';
    };

    exports.basename = function(p, ext) {
        assertString(p);
        if (ext !== undefined) assertString(ext);
        var start = 0;
        var end = -1;
        var matchedSlash = true;
        for (var i = p.length - 1; i >= 0; --i) {
            if (p.charCodeAt(i) === 47) {
                if (!matchedSlash) { start = i + 1; break; }
            } else if (end === -1) {
                matchedSlash = false;
                end = i + 1;
            }
        }
        if (end === -1) return '';
        var base = p.slice(start, end);
        if (ext && base.length >= ext.length && base.slice(base.length - ext.length) === ext) {
            base = base.slice(0, base.length - ext.length);
        }
        return base;
    };

    exports.extname = function(p) {
        assertString(p);
        var startDot = -1;
        var startPart = 0;
        var end = -1;
        var matchedSlash = true;
        var preDotState = 0;
        for (var i = p.length - 1; i >= 0; --i) {
            var code = p.charCodeAt(i);
            if (code === 47) {
                if (!matchedSlash) { startPart = i + 1; break; }
                continue;
            }
            if (end === -1) { matchedSlash = false; end = i + 1; }
            if (code === 46) {
                if (startDot === -1) startDot = i;
                else if (preDotState !== 1) preDotState = 1;
            } else if (startDot !== -1) {
                preDotState = -1;
            }
        }
        if (startDot === -1 || end === -1 || preDotState === 0 ||
            (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
            return '';
        }
        return p.slice(startDot, end);
    };

    exports.parse = function(p) {
        assertString(p);
        var ret = { root: '', dir: '', base: '', ext: '', name: '' };
        if (p.length === 0) return ret;
        var isAbs = p.charCodeAt(0) === 47;
        if (isAbs) ret.root = '/';
        var base = exports.basename(p);
        var dir = exports.dirname(p);
        ret.dir = isAbs && dir === '/' ? '/' : dir === '.' && !isAbs ? '' : dir;
        ret.base = base;
        ret.ext = exports.extname(base);
        ret.name = ret.ext.length > 0 ? base.slice(0, base.length - ret.ext.length) : base;
        return ret;
    };

    exports.format = function(obj) {
        if (obj === null || typeof obj !== 'object') {
            throw new TypeError('path.format requires an object');
        }
        var dir = obj.dir || obj.root || '';
        var base = obj.base || ((obj.name || '') + (obj.ext || ''));
        if (!dir) return base;
        if (dir === obj.root) return dir + base;
        return dir + '/' + base;
    };

    exports.posix = exports;

    // path.win32 — Node always exposes both flavours; many libraries
    // (npm's `tar`, fs-extra, archive utilities) reach for
    // `require('path').win32.{isAbsolute,parse}` to normalise paths
    // even on Linux. We provide a Windows-shaped twin: backslash is
    // an additional separator, drive letters are recognised as
    // absolute (`c:/foo`, `\\?\drive\...`), and the rest of the
    // surface mirrors POSIX with `\\` separators.
    var win32 = {};
    win32.sep = '\\';
    win32.delimiter = ';';
    win32.posix = exports;
    win32.win32 = win32;
    function _winSplit(p) {
        return String(p).replace(/\//g, '\\').split('\\').filter(function(s) { return s.length > 0 || false; });
    }
    win32.isAbsolute = function(p) {
        var s = String(p);
        if (s.length === 0) return false;
        if (s.charAt(0) === '/' || s.charAt(0) === '\\') return true;
        // c:/foo or c:\foo
        if (s.length >= 3 && /^[a-z]:[\/\\]/i.test(s)) return true;
        // c:foo (drive-relative — not absolute, but Node treats some
        // shapes as absolute. Conservative: false here.)
        return false;
    };
    win32.normalize = function(p) {
        var s = String(p).replace(/\//g, '\\');
        // Drive letter detection.
        var rootMatch = /^([a-z]:)?[\\\\]?/i.exec(s);
        var drive = rootMatch && rootMatch[1] ? rootMatch[1] : '';
        var rooted = /^([a-z]:)?[\\]/i.test(s);
        var rest = s.slice((drive.length) + (rooted ? 1 : 0));
        var parts = rest.split('\\').filter(function(p) { return p && p !== '.'; });
        var stack = [];
        for (var i = 0; i < parts.length; i++) {
            if (parts[i] === '..') {
                if (stack.length && stack[stack.length-1] !== '..') stack.pop();
                else if (!rooted) stack.push('..');
            } else { stack.push(parts[i]); }
        }
        return drive + (rooted ? '\\' : '') + stack.join('\\');
    };
    win32.join = function() {
        var args = [].slice.call(arguments).filter(function(a) { return a && a.length; });
        if (args.length === 0) return '.';
        return win32.normalize(args.join('\\'));
    };
    win32.resolve = function() {
        var args = [].slice.call(arguments);
        var resolved = '';
        for (var i = args.length - 1; i >= -1; i--) {
            var p = (i >= 0) ? args[i] : '\\';
            if (!p || p.length === 0) continue;
            resolved = p + '\\' + resolved;
            if (win32.isAbsolute(p)) break;
        }
        return win32.normalize(resolved);
    };
    win32.dirname = function(p) {
        var s = String(p).replace(/\//g, '\\');
        var idx = s.lastIndexOf('\\');
        if (idx < 0) return '.';
        if (idx === 0) return '\\';
        return s.slice(0, idx);
    };
    win32.basename = function(p, ext) {
        var s = String(p).replace(/\//g, '\\');
        var idx = s.lastIndexOf('\\');
        var base = idx >= 0 ? s.slice(idx + 1) : s;
        if (ext && base.endsWith(ext)) base = base.slice(0, base.length - ext.length);
        return base;
    };
    win32.extname = function(p) {
        var b = win32.basename(p);
        var idx = b.lastIndexOf('.');
        if (idx <= 0) return '';
        return b.slice(idx);
    };
    win32.parse = function(p) {
        var s = String(p).replace(/\//g, '\\');
        var ret = { root: '', dir: '', base: '', ext: '', name: '' };
        // Detect drive root.
        var driveMatch = /^([a-z]:)([\\]?)/i.exec(s);
        if (driveMatch) {
            ret.root = driveMatch[1] + (driveMatch[2] || '');
        } else if (s.charAt(0) === '\\') {
            ret.root = '\\';
        }
        ret.base = win32.basename(p);
        ret.dir = win32.dirname(p);
        ret.ext = win32.extname(ret.base);
        ret.name = ret.ext ? ret.base.slice(0, ret.base.length - ret.ext.length) : ret.base;
        return ret;
    };
    win32.format = function(obj) {
        var dir = obj.dir || obj.root || '';
        var base = obj.base || ((obj.name || '') + (obj.ext || ''));
        if (!dir) return base;
        if (dir === obj.root) return dir + base;
        return dir + '\\' + base;
    };
    win32.toNamespacedPath = function(p) { return String(p); };
    win32.relative = function(from, to) {
        from = win32.resolve(String(from));
        to = win32.resolve(String(to));
        if (from === to) return '';
        var fromSegs = from.split('\\').filter(function(s) { return s.length; });
        var toSegs = to.split('\\').filter(function(s) { return s.length; });
        var common = 0;
        var max = Math.min(fromSegs.length, toSegs.length);
        while (common < max && fromSegs[common].toLowerCase() === toSegs[common].toLowerCase()) common++;
        var up = fromSegs.length - common;
        var rest = toSegs.slice(common);
        var out = [];
        for (var i = 0; i < up; i++) out.push('..');
        for (var j = 0; j < rest.length; j++) out.push(rest[j]);
        return out.join('\\') || '.';
    };
    win32.matchesGlob = function(p, pattern) {
        var re = new RegExp('^' + String(pattern)
            .replace(/[.+^${}()|[\]\\]/g, '\\$&')
            .replace(/\*/g, '.*')
            .replace(/\?/g, '.') + '$');
        return re.test(String(p));
    };
    exports.win32 = win32;

    // Posix-side `toNamespacedPath` and `matchesGlob` (Node 22+).
    exports.toNamespacedPath = function(p) { return String(p); };
    exports.matchesGlob = function(p, pattern) {
        var re = new RegExp('^' + String(pattern)
            .replace(/[.+^${}()|[\]\\]/g, '\\$&')
            .replace(/\*/g, '.*')
            .replace(/\?/g, '.') + '$');
        return re.test(String(p));
    };
});

// ---- perf_hooks.js ----
// perf_hooks — Node 20's performance-measurement API.
//
// Most callers use `performance.now()` (already a global) +
// `performance.mark` / `measure`. We provide a real implementation
// of those plus the supporting classes so production code drops in
// without modification.

__register_module('perf_hooks', function(module, exports, require) {

    // Global `performance` is installed by `web_compat.js`. Reuse it
    // so the two surfaces stay in lock-step (common pattern: scripts
    // import perf_hooks.performance but expect `globalThis.performance`
    // to point at the same object).
    var performance = globalThis.performance || {
        now: function() { return Date.now(); },
        timeOrigin: Date.now(),
    };

    // ---- PerformanceEntry ------------------------------------------

    function PerformanceEntry(name, entryType, startTime, duration) {
        this.name = name;
        this.entryType = entryType;
        this.startTime = startTime;
        this.duration = duration;
    }
    PerformanceEntry.prototype.toJSON = function() {
        return {
            name: this.name,
            entryType: this.entryType,
            startTime: this.startTime,
            duration: this.duration,
        };
    };

    // ---- in-memory entry buffer -----------------------------------

    var entries = [];
    var marks = Object.create(null);

    function addEntry(entry) {
        entries.push(entry);
    }

    // ---- Performance methods --------------------------------------
    //
    // We extend the bare `globalThis.performance` with the full
    // perf_hooks surface. Idempotent — re-installing doesn't reset
    // any pre-recorded marks.

    if (typeof performance.mark !== 'function') {
        performance.mark = function(name, options) {
            var detail = options && options.detail;
            var startTime = performance.now();
            var entry = new PerformanceEntry(String(name), 'mark', startTime, 0);
            entry.detail = detail || null;
            marks[String(name)] = entry;
            addEntry(entry);
            return entry;
        };
    }
    if (typeof performance.measure !== 'function') {
        performance.measure = function(name, startMarkOrOptions, endMark) {
            var startMark, endMarkName, detail;
            if (typeof startMarkOrOptions === 'object' && startMarkOrOptions !== null) {
                startMark = startMarkOrOptions.start;
                endMarkName = startMarkOrOptions.end;
                detail = startMarkOrOptions.detail;
            } else {
                startMark = startMarkOrOptions;
                endMarkName = endMark;
            }
            var startTime = startMark
                ? (marks[startMark] && marks[startMark].startTime) || 0
                : 0;
            var endTime = endMarkName
                ? (marks[endMarkName] && marks[endMarkName].startTime) || performance.now()
                : performance.now();
            var entry = new PerformanceEntry(
                String(name), 'measure', startTime, Math.max(0, endTime - startTime)
            );
            entry.detail = detail || null;
            addEntry(entry);
            return entry;
        };
    }
    if (typeof performance.clearMarks !== 'function') {
        performance.clearMarks = function(name) {
            if (name === undefined) {
                marks = Object.create(null);
                entries = entries.filter(function(e) { return e.entryType !== 'mark'; });
            } else {
                delete marks[String(name)];
                entries = entries.filter(function(e) {
                    return !(e.entryType === 'mark' && e.name === name);
                });
            }
        };
    }
    if (typeof performance.clearMeasures !== 'function') {
        performance.clearMeasures = function(name) {
            entries = entries.filter(function(e) {
                if (e.entryType !== 'measure') return true;
                return name !== undefined && e.name !== name;
            });
        };
    }
    if (typeof performance.getEntries !== 'function') {
        performance.getEntries = function() { return entries.slice(); };
    }
    if (typeof performance.getEntriesByName !== 'function') {
        performance.getEntriesByName = function(name, type) {
            return entries.filter(function(e) {
                if (e.name !== name) return false;
                return type === undefined || e.entryType === type;
            });
        };
    }
    if (typeof performance.getEntriesByType !== 'function') {
        performance.getEntriesByType = function(type) {
            return entries.filter(function(e) { return e.entryType === type; });
        };
    }

    // ---- PerformanceObserver --------------------------------------
    //
    // No event loop in the sandbox: observer callbacks fire
    // synchronously when `observe()` runs. Real Node defers them
    // to the next tick; the polyfill matches the API but folds the
    // dispatch into the immediate call so callers don't need to
    // tick the loop themselves.

    function PerformanceObserver(callback) {
        if (typeof callback !== 'function') {
            throw new TypeError('PerformanceObserver: callback must be a function');
        }
        this._callback = callback;
        this._observed = [];
        this._buffered = false;
    }
    PerformanceObserver.prototype.observe = function(opts) {
        opts = opts || {};
        var types = opts.entryTypes || (opts.type ? [opts.type] : []);
        this._observed = types.slice();
        this._buffered = !!opts.buffered;
        // Spec: when `buffered` is true, replay matching prior entries.
        // Read from BOTH this module's `entries` buffer AND the global
        // `performance._entries` buffer that `web_compat.js` populates
        // via `globalThis.performance.mark()`. Either side may have
        // pre-existing entries depending on which API the user code
        // reached for first.
        if (this._buffered) {
            var globalEntries = (globalThis.performance && globalThis.performance._entries)
                || [];
            var pool = entries.concat(globalEntries);
            var matched = pool.filter(function(e) {
                return types.indexOf(e.entryType) !== -1;
            });
            if (matched.length) {
                this._callback(
                    { getEntries: function() { return matched.slice(); } },
                    this
                );
            }
        }
    };
    PerformanceObserver.prototype.disconnect = function() {
        this._observed = [];
    };
    PerformanceObserver.prototype.takeRecords = function() {
        var observed = this._observed;
        var taken = entries.filter(function(e) {
            return observed.indexOf(e.entryType) !== -1;
        });
        return taken;
    };
    PerformanceObserver.supportedEntryTypes = ['mark', 'measure'];

    function monitorEventLoopDelay() {
        // Sandbox has no event loop; return a stub that always
        // reports zero delay. Node's API is preserved so callers
        // can still .reset() / .disable() / .enable() without crashing.
        var hist = {
            min: 0, max: 0, mean: 0, stddev: 0, percentile: function() { return 0; },
            percentiles: new Map(), exceeds: 0, count: 0,
            enable: function() {}, disable: function() {}, reset: function() {},
        };
        return hist;
    }

    function createHistogram(opts) {
        var lowest = (opts && opts.lowest) || 1;
        var highest = (opts && opts.highest) || 9007199254740991; // 2^53 - 1
        var count = 0, sum = 0, min = highest, max = lowest;
        return {
            min: min, max: max, mean: 0, stddev: 0, count: count,
            record: function(v) {
                count++; sum += v;
                if (v < min) min = v;
                if (v > max) max = v;
            },
            recordDelta: function() {},
            reset: function() { count = 0; sum = 0; min = highest; max = lowest; },
            percentile: function() { return 0; },
            get percentiles() { return new Map(); },
        };
    }

    // ---- exports --------------------------------------------------

    exports.performance = performance;
    exports.PerformanceEntry = PerformanceEntry;
    exports.PerformanceObserver = PerformanceObserver;
    exports.PerformanceObserverEntryList = PerformanceObserver; // alias
    exports.PerformanceMeasure = PerformanceEntry;
    exports.PerformanceMark = PerformanceEntry;
    exports.PerformanceResourceTiming = PerformanceEntry;
    exports.constants = {
        NODE_PERFORMANCE_GC_MAJOR: 4,
        NODE_PERFORMANCE_GC_MINOR: 1,
        NODE_PERFORMANCE_GC_INCREMENTAL: 8,
        NODE_PERFORMANCE_GC_WEAKCB: 16,
    };
    exports.monitorEventLoopDelay = monitorEventLoopDelay;
    exports.createHistogram = createHistogram;

    // Default export — Node lets callers do `import perf from 'perf_hooks'`.
    module.exports = exports;
});

// ---- process.js ----
// process — eager-installed as `globalThis.process` and registered as
// the CommonJS `process` module. Acts as an EventEmitter so scripts
// using `process.on('exit', …)` etc. do not blow up.
//
// The IIFE runs at bundle-load time so `globalThis.process` is set
// regardless of whether the user script ever calls `require('process')`.

(function bootstrapProcess() {
    // EventEmitter is provided by events.js; we lookup directly from
    // the require resolver since this runs before user code.
    var EventEmitter = require('events');

    // `__host_env` / `__ab_argv` are installed per-thrust by script
    // mode (see plugin's modes/script.rs). Both globals are absent in
    // UDF mode, which is intentional — UDF scripts only see their
    // `data` input.
    var hostEnv = globalThis.__host_env || {};
    var argv    = globalThis.__ab_argv   || ['afterburner'];
    var proc = Object.create(EventEmitter.prototype);
    EventEmitter.call(proc);

    var fields = {
        platform: globalThis.__host_platform || 'linux',
        arch:     globalThis.__host_arch     || 'x64',
        // We claim Node 26 (latest stable, the project's target). Most
        // libraries gate features on numeric ranges (`>=18.17.0`,
        // `>=20.5.0`, `>=22.0.0`) — claiming the current major
        // version unblocks every reasonable engines check while
        // still surfacing the `-afterburner` suffix so version-aware
        // code paths (rare) can detect us.
        version:  'v26.0.0-afterburner',
        versions: { node: '26.0.0', v8: '13.0.0.0', afterburner: '0.1.0' },
        env:      hostEnv,
        argv:     argv,
        execPath: '/usr/bin/afterburner',
        pid:      1,
        title:    'afterburner',

        cwd:      function() { return globalThis.__host_cwd || '/'; },
        chdir:    function() { throw new Error('process.chdir is not supported'); },

        // `umask([mask])` — Node returns the previous mask; with an
        // arg, sets it. Sandbox doesn't surface umask through the
        // bridge; return a sensible default and accept (silent) the
        // setter call. Node reduced the deprecation noise around
        // calling umask() with no args; we mirror that.
        umask:    function(_mask) { return 0o022; },

        // `process.getuid` / `getgid` / `geteuid` / `getegid` — POSIX
        // identity functions. Sandbox returns 0 for everything; some
        // libraries (npm install, sqlite open) probe these to decide
        // whether to drop privileges.
        getuid:   function() { return 0; },
        getgid:   function() { return 0; },
        geteuid:  function() { return 0; },
        getegid:  function() { return 0; },
        getgroups: function() { return [0]; },
        // `setuid`/`setgid` — sandbox doesn't allow privilege change.
        // Throw a Node-style typed error so callers can fall through.
        setuid:   function() { var e = new Error('setuid not supported'); e.code = 'EPERM'; throw e; },
        setgid:   function() { var e = new Error('setgid not supported'); e.code = 'EPERM'; throw e; },
        seteuid:  function() { var e = new Error('seteuid not supported'); e.code = 'EPERM'; throw e; },
        setegid:  function() { var e = new Error('setegid not supported'); e.code = 'EPERM'; throw e; },
        setgroups: function() { var e = new Error('setgroups not supported'); e.code = 'EPERM'; throw e; },

        // Node 18+ `process.permission` / `process.constrainedMemory`
        // / `process.availableMemory` — light probe surface that
        // libraries (express's inspector, nodemon) check at module
        // init.
        constrainedMemory:  function() { return 0; },
        availableMemory:    function() { return 0; },
        memoryUsage:        Object.assign(function() {
            return { rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0 };
        }, { rss: function() { return 0; } }),
        // Node 24+ `process.threadCpuUsage` — return a zeroed object.
        threadCpuUsage:     function() { return { user: 0, system: 0 }; },
        cpuUsage:           function(_prev) { return { user: 0, system: 0 }; },
        /// Node 11+ `process.report` — diagnostic-report API. We
        /// produce a real Node-shaped report from the runtime's
        /// process state: live memory numbers via `process.memoryUsage`,
        /// captured stack via `Error.captureStackTrace`, env vars from
        /// `process.env`, command-line argv, plus the resource-usage
        /// snapshot. Output is the canonical JSON shape clinic.js /
        /// node-inspector parsers expect.
        report: {
            directory: '',
            filename: '',
            reportOnFatalError: false,
            reportOnSignal: false,
            reportOnUncaughtException: false,
            signal: 'SIGUSR2',
            compact: false,
            excludeNetwork: false,
            getReport: function(err) {
                var stack = '';
                try {
                    if (err && err.stack) {
                        stack = err.stack;
                    } else {
                        var probe = {};
                        Error.captureStackTrace(probe, this.getReport);
                        stack = probe.stack || '';
                    }
                } catch (_) { /* defensive */ }
                var stackLines = String(stack).split('\n').filter(Boolean);
                var memUsage = (typeof process.memoryUsage === 'function')
                    ? process.memoryUsage() : {};
                var report = {
                    header: {
                        reportVersion: 5,
                        event: err ? 'Exception' : 'JavaScript API',
                        trigger: err ? 'Exception' : 'GetReport',
                        filename: '',
                        dumpEventTime: new Date().toISOString(),
                        dumpEventTimeStamp: String(Date.now()),
                        processId: (process.pid | 0) || 0,
                        threadId: 0,
                        cwd: typeof process.cwd === 'function' ? process.cwd() : '',
                        commandLine: (process.argv || []).slice(),
                        nodejsVersion: process.version || '',
                        wordSize: 64,
                        arch: process.arch || '',
                        platform: process.platform || '',
                        componentVersions: process.versions || {},
                        release: process.release || {},
                        osName: process.platform || '',
                        osRelease: '',
                        osVersion: '',
                        osMachine: process.arch || '',
                        cpus: [],
                        networkInterfaces: [],
                        host: 'localhost',
                    },
                    javascriptStack: {
                        message: err && err.message ? String(err.message) : '',
                        stack: stackLines,
                        errorProperties: err ? Object.assign({}, err) : {},
                    },
                    nativeStack: [],
                    javascriptHeap: {
                        totalMemory: String(memUsage.heapTotal | 0),
                        executableMemory: '0',
                        totalCommittedMemory: String(memUsage.heapTotal | 0),
                        availableMemory: String(Math.max(0,
                            (memUsage.heapTotal | 0) - (memUsage.heapUsed | 0))),
                        totalGlobalHandlesMemory: '0',
                        usedGlobalHandlesMemory: '0',
                        usedMemory: String(memUsage.heapUsed | 0),
                        memoryLimit: String(memUsage.heapTotal | 0),
                        mallocedMemory: String(memUsage.external | 0),
                        externalMemory: String(memUsage.external | 0),
                        peakMallocedMemory: String(memUsage.external | 0),
                        nativeContextCount: 1,
                        detachedContextCount: 0,
                        doesZapGarbage: 0,
                        heapSpaces: {},
                    },
                    resourceUsage: typeof process.resourceUsage === 'function'
                        ? process.resourceUsage() : {},
                    sharedObjects: [],
                    libuv: [],
                    workers: [],
                    environmentVariables: Object.assign({}, process.env || {}),
                    userLimits: {},
                    uvthreadResourceUsage: typeof process.resourceUsage === 'function'
                        ? process.resourceUsage() : {},
                };
                return report;
            },
            writeReport: function(filename, err) {
                if (typeof filename === 'object' && filename !== null) {
                    err = filename;
                    filename = undefined;
                }
                var report = this.getReport(err);
                var fs = require('fs');
                var path = filename || ('report.' + Date.now() + '.'
                    + (process.pid | 0) + '.001.json');
                fs.writeFileSync(path, JSON.stringify(report, null, 2));
                return path;
            },
        },
        resourceUsage:      function() {
            return {
                userCPUTime: 0, systemCPUTime: 0, maxRSS: 0,
                sharedMemorySize: 0, unsharedDataSize: 0, unsharedStackSize: 0,
                minorPageFault: 0, majorPageFault: 0, swappedOut: 0,
                fsRead: 0, fsWrite: 0, ipcSent: 0, ipcReceived: 0,
                signalsCount: 0, voluntaryContextSwitches: 0, involuntaryContextSwitches: 0,
            };
        },
        // process.getActiveResourcesInfo (Node 18+). Returns an array
        // of strings naming the resources keeping the event loop
        // alive. Burn's daemon mode tracks listeners, ref'd timers,
        // outbound HTTP, etc. through `daemon.has_refs()`; for the
        // JS-level surface we approximate with a per-shard view of
        // currently alive resources we can detect.
        getActiveResourcesInfo: function() {
            var out = [];
            // Crude best-effort: probe `__ab_*` markers we install
            // for in-flight outbound HTTP, server handlers, timers.
            if (globalThis.__ab_http_pending) {
                var keys = Object.keys(globalThis.__ab_http_pending);
                for (var i = 0; i < keys.length; i++) out.push('TCPWRAP');
            }
            if (globalThis.__ab_http_handlers) {
                var hkeys = Object.keys(globalThis.__ab_http_handlers);
                for (var j = 0; j < hkeys.length; j++) out.push('TCPSERVERWRAP');
            }
            return out;
        },
        // process.getBuiltinModule(id) (Node 22+). Returns the same
        // module the synchronous CJS `require(id)` would, or
        // `undefined` if the id isn't a Node built-in (vs throwing —
        // matches Node's contract).
        getBuiltinModule: function(id) {
            if (typeof id !== 'string') return undefined;
            var bare = id.indexOf('node:') === 0 ? id.slice(5) : id;
            try {
                if (typeof globalThis.require === 'function') {
                    var mod = globalThis.require;
                    var Module = mod('module');
                    if (Module && typeof Module.isBuiltin === 'function' && !Module.isBuiltin(bare)) {
                        return undefined;
                    }
                    return mod(bare);
                }
            } catch (_) {}
            return undefined;
        },
        // process.loadEnvFile (Node 20.6+). The CLI's `--env-file`
        // already loads at startup; this in-process call parses
        // additional files at runtime and merges into `process.env`.
        loadEnvFile: function(path) {
            var p = path || '.env';
            try {
                var fs = require('fs');
                var text = fs.readFileSync(p, 'utf8');
                var lines = text.split(/\r?\n/);
                for (var i = 0; i < lines.length; i++) {
                    var line = lines[i].trim();
                    if (!line || line.charAt(0) === '#') continue;
                    var eq = line.indexOf('=');
                    if (eq < 0) continue;
                    var k = line.slice(0, eq).trim();
                    if (!k) continue;
                    var v = line.slice(eq + 1).trim();
                    if (v.length >= 2 && ((v[0] === '"' && v[v.length - 1] === '"') ||
                                          (v[0] === "'" && v[v.length - 1] === "'"))) {
                        v = v.slice(1, -1);
                    }
                    if (globalThis.process && globalThis.process.env) {
                        globalThis.process.env[k] = v;
                    }
                }
            } catch (e) {
                var err = new Error('Cannot read environment file: ' + p);
                err.code = 'ENOENT';
                throw err;
            }
        },
        // process.permission — Node 20.x experimental. When the CLI
        // launched without `--permission` we keep the always-allow
        // posture (manifold layer is the real gate). With
        // `--permission` set, the host populates
        // `globalThis.__ab_permission_grants` with a map of granted
        // scopes; `has()` consults that, defaulting to false for
        // unmentioned scopes — matching Node's deny-by-default model.
        permission: {
            has: function(scope, ref) {
                var g = globalThis.__ab_permission_grants;
                if (!g) return true; // permission model not active → allow
                if (!Object.prototype.hasOwnProperty.call(g, scope)) return false;
                var v = g[scope];
                if (v === true) return true;
                if (typeof v === 'string') {
                    if (!ref) return true;
                    var allow = v.split(',').map(function(s) { return s.trim(); });
                    for (var i = 0; i < allow.length; i++) {
                        if (allow[i] === '*' || allow[i] === ref) return true;
                        // Glob-prefix support for fs paths and net
                        // host:port.
                        if (allow[i].indexOf('*') === 0 &&
                            ref.endsWith(allow[i].slice(1))) return true;
                        if (ref.indexOf(allow[i]) === 0) return true;
                    }
                    return false;
                }
                return false;
            },
            get: function() {
                var g = globalThis.__ab_permission_grants;
                if (!g) return { fs: { read: true, write: true }, net: true, env: true,
                                 child_process: true, worker: true };
                return {
                    fs: {
                        read: g['fs.read'] !== undefined,
                        write: g['fs.write'] !== undefined,
                    },
                    net: !!g['net'],
                    env: !!g['env'],
                    child_process: !!g['child_process'],
                    worker: !!g['worker'],
                };
            },
        },

        // Real Node drains the nextTick queue synchronously between
        // each macrotask but BEFORE the microtask queue. Express's
        // `finalhandler` (the 404/500 fallback) defers its response
        // with `process.nextTick`, expecting middleware that called
        // `next(err)` to run first. The pre-fix synchronous-call
        // implementation broke that ordering: a nextTick scheduled
        // from inside a Promise microtask ran INSIDE the microtask
        // instead of after it.
        //
        // We approximate Node's semantics by queueing nextTick
        // callbacks into `__ntQueue` and draining via a single
        // `queueMicrotask`. Microtask order is FIFO, so a nextTick
        // scheduled in current sync code runs before any user
        // `Promise.then` queued AFTER it. Exceptions in a nextTick
        // callback are caught + logged so a single failure doesn't
        // poison the rest of the queue (Node's behaviour: emit
        // `uncaughtException` and continue; we surface to console
        // until we wire a real uncaughtException emitter).
        //
        // Caveat: nested nextTicks (callback A queues callback B)
        // run on the *next* drain pass here, not the same one. Real
        // Node has an inner/outer queue that drains nested ticks
        // greedily before the microtask queue. Document the
        // divergence; revisit if a real workload hits it.
        nextTick: function(fn) {
            if (typeof fn !== 'function') throw new TypeError('callback must be a function');
            var args = Array.prototype.slice.call(arguments, 1);
            if (!globalThis.__ntQueue) globalThis.__ntQueue = [];
            globalThis.__ntQueue.push({ fn: fn, args: args });
            if (!globalThis.__ntScheduled) {
                globalThis.__ntScheduled = true;
                queueMicrotask(function drainNT() {
                    var queue = globalThis.__ntQueue;
                    globalThis.__ntQueue = [];
                    globalThis.__ntScheduled = false;
                    for (var i = 0; i < queue.length; i++) {
                        var item = queue[i];
                        try {
                            item.fn.apply(null, item.args);
                        } catch (e) {
                            // Per Node convention, exceptions in
                            // nextTick callbacks emit
                            // `uncaughtException`. Until that's
                            // wired, log + continue so the rest of
                            // the queue still runs.
                            if (globalThis.console && globalThis.console.error) {
                                globalThis.console.error('Uncaught (in nextTick): ' + (e && e.stack || e));
                            }
                        }
                    }
                });
            }
        },

        exit: function(code) {
            // Guard so 'exit' fires at most once. The host also emits
            // 'exit' when the event loop drains naturally (see the
            // daemon-event 'lifecycle' dispatch); Node guarantees a
            // single 'exit' emission regardless of how the process ends.
            if (!proc.__burnExited) {
                proc.__burnExited = true;
                try { proc.emit('exit', code || 0); } catch (_) {}
            }
            if (globalThis.__host_process_exit) globalThis.__host_process_exit(code || 0);
            var err = new Error('process.exit(' + (code || 0) + ')');
            err.code = 'ERR_PROCESS_EXIT';
            err.exitCode = code || 0;
            throw err;
        },

        hrtime: function(prev) {
            var now = Date.now();
            var seconds = Math.floor(now / 1000);
            var nanos = (now % 1000) * 1e6;
            if (prev) {
                var ds = seconds - prev[0];
                var dn = nanos - prev[1];
                if (dn < 0) { ds -= 1; dn += 1e9; }
                return [ds, dn];
            }
            return [seconds, nanos];
        },

        // Node guarantees `process.stdout.fd === 1`, `stderr.fd === 2`,
        // `stdin.fd === 0`; libraries probe these (chalk reads stdout
        // for color decisions, log streams pipe by fd). `isTTY` /
        // `columns` / `rows` shape matches Node's interactive defaults
        // — caller can override to flip color output off.
        stdout: {
            fd: 1, isTTY: false, columns: 80, rows: 24,
            write: function(s, _enc, cb) {
                if (globalThis.console) console.log(typeof s === 'string' ? s : String(s));
                if (typeof cb === 'function') Promise.resolve().then(cb);
                return true;
            },
            on: function() { return this; },
            once: function() { return this; },
            removeListener: function() { return this; },
            off: function() { return this; },
            emit: function() { return false; },
            cork: function() {}, uncork: function() {}, end: function() {},
            // Color depth + hasColors honour NO_COLOR / FORCE_COLOR /
            // TERM the same way `tty.WriteStream.prototype` does. The
            // non-TTY default is false (chalk/signale gate on isTTY),
            // BUT `FORCE_COLOR` overrides — that's the documented
            // escape hatch for piping into colour-aware consumers
            // (e.g. `node script.js | less -R`).
            getColorDepth: function() { return require('tty').WriteStream.prototype.getColorDepth(); },
            hasColors: function(count) {
                var env = (typeof process !== 'undefined' && process.env) || {};
                var forced = env.FORCE_COLOR != null && env.FORCE_COLOR !== ''
                    && env.FORCE_COLOR !== '0' && env.FORCE_COLOR !== 'false';
                if (this.isTTY !== true && !forced) return false;
                return require('tty').WriteStream.prototype.hasColors(count);
            },
            clearLine: function() {}, clearScreenDown: function() {}, cursorTo: function() {},
        },
        stderr: {
            fd: 2, isTTY: false, columns: 80, rows: 24,
            write: function(s, _enc, cb) {
                if (globalThis.console) console.error(typeof s === 'string' ? s : String(s));
                if (typeof cb === 'function') Promise.resolve().then(cb);
                return true;
            },
            on: function() { return this; },
            once: function() { return this; },
            removeListener: function() { return this; },
            off: function() { return this; },
            emit: function() { return false; },
            cork: function() {}, uncork: function() {}, end: function() {},
            getColorDepth: function() { return require('tty').WriteStream.prototype.getColorDepth(); },
            hasColors: function(count) {
                if (this.isTTY !== true) return false;
                return require('tty').WriteStream.prototype.hasColors(count);
            },
            clearLine: function() {}, clearScreenDown: function() {}, cursorTo: function() {},
        },
        stdin: {
            fd: 0, isTTY: false,
            on: function() { return this; },
            once: function() { return this; },
            removeListener: function() { return this; },
            off: function() { return this; },
            emit: function() { return false; },
            read: function() { return null; },
            pause: function() { return this; },
            resume: function() { return this; },
            setEncoding: function() { return this; },
            setRawMode: function() { return this; },
            unref: function() { return this; },
            ref: function() { return this; },
            destroy: function() { return this; },
            pipe: function(dest) { if (dest && dest.end) dest.end(); return dest; },
        },

        // `process.binding(name)` is Node's internal hook for native
        // bindings (e.g. `process.binding('uv')`, `'tcp_wrap'`,
        // `'fs_event_wrap'`). They expose libuv-side primitives
        // that have no analogue in the WASM sandbox. Surface a
        // clear error that names the requested binding so users
        // can identify which library is reaching for an
        // unsupported internal.
        binding: function(name) {
            var which = typeof name === 'string' ? name : String(name);
            // Return narrow stubs for the bindings real-world libraries
            // probe at module-init for limit/feature flags — eager
            // throws here break safer-buffer / fs-minipass / pacote at
            // module load, which is far enough from any actual native
            // primitive use that the user has no way to act on the
            // error. Keep the throw for everything else so honest
            // libuv consumers (rare in the sandbox) still surface a
            // typed error pointing at the missing binding.
            switch (which) {
                case 'buffer':
                    return {
                        kStringMaxLength: 0x3fffffe7,        // ~1 GiB - 8
                        kMaxLength:       0x7fffffff,        // INT32_MAX
                    };
                case 'fs':
                    // fs-minipass gates a libuv fallback on
                    // `!fs.writev`. We provide writev now, so the
                    // binding is dead code; an empty object lets the
                    // module-init `process.binding('fs')` complete
                    // without exposing any libuv methods.
                    return {};
                case 'constants':
                    // Return the merged fs+os+crypto constants so
                    // legacy `require('process').binding('constants')`
                    // gets a usable map (Node had this for years).
                    try {
                        var c = {};
                        var fs = require('fs');
                        var os = require('os');
                        if (fs && fs.constants) Object.assign(c, fs.constants);
                        if (os && os.constants) {
                            if (os.constants.errno) Object.assign(c, os.constants.errno);
                            if (os.constants.signals) Object.assign(c, os.constants.signals);
                        }
                        return c;
                    } catch (_) { return {}; }
            }
            var err = new Error(
                "process.binding('" + which + "') is not supported in the " +
                "Afterburner sandbox: native bindings (libuv internals and " +
                ".node addons) require executing native machine code, which " +
                "the WASM sandbox cannot do by design (different ISA from " +
                "the bytecode the runtime executes)."
            );
            err.code = 'ERR_NOT_SUPPORTED_IN_SANDBOX';
            err.bindingName = which;
            throw err;
        },

        // Same surface as `process.binding` but for the post-Node-16
        // internal-only API.
        _linkedBinding: function(name) {
            var err = new Error(
                "process._linkedBinding('" + String(name) + "') is not " +
                "supported in the Afterburner sandbox"
            );
            err.code = 'ERR_NOT_SUPPORTED_IN_SANDBOX';
            err.bindingName = String(name);
            throw err;
        }
    };

    fields.hrtime.bigint = function() {
        var t = fields.hrtime();
        return BigInt(t[0]) * 1000000000n + BigInt(t[1]);
    };

    Object.keys(fields).forEach(function(k) { proc[k] = fields[k]; });

    /// process.uptime — seconds since process start. We anchor to the
    /// JS runtime epoch since the host's timestamp granularity matches
    /// what Node returns.
    var _start = Date.now();
    proc.uptime = function() { return (Date.now() - _start) / 1000; };

    /// process.kill — Node sends a signal to a target PID. Sandbox
    /// can't actually deliver signals, but the function exists so
    /// libraries that call it (cleanup hooks, watchdogs) don't crash.
    /// Matches Node's "always-true" behavior on Windows for SIGTERM.
    proc.kill = function(pid, _signal) {
        if (typeof pid !== 'number') {
            var e = new TypeError('process.kill: pid must be a number');
            e.code = 'ERR_INVALID_ARG_TYPE';
            throw e;
        }
        // Sandboxed — no actual signal delivery. Silently succeed for
        // self-pid (many libraries use kill(process.pid, 0) as a probe).
        return true;
    };

    /// process.dlopen — opens a native .node addon. Burn's WASM
    /// sandbox can't load native code; throw so probe-shaped libraries
    /// fall through to their JS-only path.
    proc.dlopen = function(_module, _filename, _flags) {
        var e = new Error(
            'process.dlopen: native addons (.node files) are not ' +
            'supported in the Afterburner sandbox');
        e.code = 'ERR_DLOPEN_DISABLED';
        throw e;
    };

    /// process.allowedNodeEnvironmentFlags — Node 12+ Set of CLI flags
    /// that the runtime accepts via NODE_OPTIONS. Real Node ships ~30;
    /// we expose the Set shape with a documented subset so feature
    /// detection works without lying about flags we don't honour.
    var _allowedFlags = new Set([
        '--enable-source-maps',
        '--no-deprecation',
        '--no-warnings',
        '--unhandled-rejections=throw',
        '--unhandled-rejections=warn',
        '--unhandled-rejections=strict',
        '--max-old-space-size',
    ]);
    Object.defineProperty(proc, 'allowedNodeEnvironmentFlags', {
        value: _allowedFlags, writable: false, configurable: true, enumerable: true,
    });

    /// process.features — Node has had this object since 0.5 with
    /// boolean flags advertising which optional features were
    /// compiled in. Most libraries grep for `features.tls` or
    /// `features.cached_builtins`.
    Object.defineProperty(proc, 'features', {
        value: Object.freeze({
            inspector: false,
            debug: false,
            uv: false,
            ipv6: true,
            tls_alpn: true,
            tls_sni: true,
            tls_ocsp: false,
            tls: true,
            cached_builtins: true,
        }),
        writable: false, configurable: true, enumerable: true,
    });

    /// process.config — Node's compile-time config object. Real Node
    /// puts ~hundreds of GYP-style entries here; we surface enough
    /// that build-tools that sniff the Node ABI version don't crash.
    Object.defineProperty(proc, 'config', {
        value: Object.freeze({
            target_defaults: { default_configuration: 'Release' },
            variables: {
                host_arch: proc.arch || 'x64',
                node_install_npm: false,
                node_module_version: 127,
                target_arch: proc.arch || 'x64',
                v8_enable_i18n_support: 1,
            },
        }),
        writable: false, configurable: true, enumerable: true,
    });

    /// process.release — release-channel metadata. npm uses
    /// `process.release.name === 'node'` to gate Node-vs-iojs paths.
    Object.defineProperty(proc, 'release', {
        value: Object.freeze({
            name: 'node',
            sourceUrl: '',
            headersUrl: '',
            libUrl: '',
            lts: 'Burn',
        }),
        writable: false, configurable: true, enumerable: true,
    });

    globalThis.process = proc;
    __register_host_module('process', proc);
})();

// ---- punycode.js ----
// punycode — RFC 3492 implementation.
// Adapted from Mathias Bynens' `punycode.js` (MIT) — kept small and
// hand-audited rather than pulled in as a dependency.

__register_module('punycode', function(module, exports, require) {

    var maxInt = 2147483647;
    var base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700;
    var initialBias = 72, initialN = 128;
    var delimiter = '-';

    function adapt(delta, numPoints, firstTime) {
        delta = firstTime ? Math.floor(delta / damp) : delta >> 1;
        delta += Math.floor(delta / numPoints);
        var k = 0;
        while (delta > ((base - tMin) * tMax) >> 1) {
            delta = Math.floor(delta / (base - tMin));
            k += base;
        }
        return Math.floor(k + (base - tMin + 1) * delta / (delta + skew));
    }

    function digitToBasic(digit) {
        return digit + 22 + 75 * (digit < 26 ? 1 : 0);
    }

    function basicToDigit(codePoint) {
        if (codePoint - 48 < 10) return codePoint - 22;
        if (codePoint - 65 < 26) return codePoint - 65;
        if (codePoint - 97 < 26) return codePoint - 97;
        return base;
    }

    function ucs2decode(str) {
        var out = [];
        var i = 0;
        while (i < str.length) {
            var value = str.charCodeAt(i++);
            if (value >= 0xD800 && value <= 0xDBFF && i < str.length) {
                var extra = str.charCodeAt(i++);
                if ((extra & 0xFC00) === 0xDC00) {
                    out.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
                } else {
                    out.push(value);
                    i--;
                }
            } else {
                out.push(value);
            }
        }
        return out;
    }

    function ucs2encode(arr) {
        var out = '';
        for (var i = 0; i < arr.length; i++) {
            var v = arr[i];
            if (v > 0xFFFF) {
                v -= 0x10000;
                out += String.fromCharCode((v >>> 10) & 0x3FF | 0xD800);
                v = 0xDC00 | (v & 0x3FF);
            }
            out += String.fromCharCode(v);
        }
        return out;
    }

    function encode(input) {
        var inputArr = ucs2decode(input);
        var n = initialN;
        var delta = 0;
        var bias = initialBias;
        var output = [];

        for (var i = 0; i < inputArr.length; i++) {
            if (inputArr[i] < 0x80) output.push(String.fromCharCode(inputArr[i]));
        }
        var basicLength = output.length;
        var handledCPCount = basicLength;

        if (basicLength) output.push(delimiter);

        while (handledCPCount < inputArr.length) {
            var m = maxInt;
            for (var j = 0; j < inputArr.length; j++) {
                if (inputArr[j] >= n && inputArr[j] < m) m = inputArr[j];
            }
            delta += (m - n) * (handledCPCount + 1);
            n = m;
            for (var k = 0; k < inputArr.length; k++) {
                var cp = inputArr[k];
                if (cp < n) delta++;
                if (cp === n) {
                    var q = delta;
                    for (var t, w = base; ; w += base) {
                        t = w <= bias ? tMin : (w >= bias + tMax ? tMax : w - bias);
                        if (q < t) break;
                        output.push(String.fromCharCode(digitToBasic(t + (q - t) % (base - t))));
                        q = Math.floor((q - t) / (base - t));
                    }
                    output.push(String.fromCharCode(digitToBasic(q)));
                    bias = adapt(delta, handledCPCount + 1, handledCPCount === basicLength);
                    delta = 0;
                    handledCPCount++;
                }
            }
            delta++;
            n++;
        }
        return output.join('');
    }

    function decode(input) {
        var output = [];
        var i = 0, n = initialN, bias = initialBias;
        var basic = input.lastIndexOf(delimiter);
        if (basic < 0) basic = 0;
        for (var j = 0; j < basic; j++) {
            var c = input.charCodeAt(j);
            if (c >= 0x80) throw new RangeError('Invalid input');
            output.push(c);
        }
        var idx = basic > 0 ? basic + 1 : 0;
        while (idx < input.length) {
            var oldi = i;
            for (var w = 1, k = base; ; k += base) {
                if (idx >= input.length) throw new RangeError('Invalid input');
                var digit = basicToDigit(input.charCodeAt(idx++));
                if (digit >= base || digit > Math.floor((maxInt - i) / w)) throw new RangeError('Overflow');
                i += digit * w;
                var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
                if (digit < t) break;
                w *= (base - t);
            }
            var outLen = output.length + 1;
            bias = adapt(i - oldi, outLen, oldi === 0);
            if (Math.floor(i / outLen) > maxInt - n) throw new RangeError('Overflow');
            n += Math.floor(i / outLen);
            i %= outLen;
            output.splice(i++, 0, n);
        }
        return ucs2encode(output);
    }

    function toASCII(input) {
        return input.replace(/[^\0-\x7E]/, function() { return 'xn--' + encode(input); });
    }
    function toUnicode(input) {
        if (input.indexOf('xn--') === 0) return decode(input.slice(4));
        return input;
    }

    exports.encode = encode;
    exports.decode = decode;
    exports.toASCII = toASCII;
    exports.toUnicode = toUnicode;
    exports.ucs2 = { encode: ucs2encode, decode: ucs2decode };
    exports.version = '2.1.1-polyfill';
});

// ---- querystring.js ----
// querystring — the legacy Node module. For new code `URLSearchParams`
// (a QuickJS built-in) is a better fit; this module exists for parity
// with code that still imports it.

__register_module('querystring', function(module, exports, require) {

    function enc(s) { return encodeURIComponent(String(s)); }
    function dec(s) {
        try { return decodeURIComponent(String(s).replace(/\+/g, ' ')); }
        catch (_) { return String(s); }
    }

    exports.escape = enc;
    exports.unescape = dec;

    exports.stringify = function(obj, sep, eq, options) {
        sep = sep || '&';
        eq = eq || '=';
        if (obj === null || typeof obj !== 'object') return '';
        var keys = Object.keys(obj);
        var parts = [];
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = obj[k];
            var ek = enc(k);
            if (Array.isArray(v)) {
                for (var j = 0; j < v.length; j++) {
                    parts.push(ek + eq + enc(v[j]));
                }
            } else if (v === null || v === undefined) {
                parts.push(ek + eq);
            } else {
                parts.push(ek + eq + enc(v));
            }
        }
        return parts.join(sep);
    };

    exports.parse = function(str, sep, eq, options) {
        var obj = Object.create(null);
        if (typeof str !== 'string' || str.length === 0) return obj;
        sep = sep || '&';
        eq = eq || '=';
        var maxKeys = (options && options.maxKeys) || 1000;
        var pairs = str.split(sep);
        var limit = pairs.length;
        if (maxKeys > 0 && limit > maxKeys) limit = maxKeys;
        for (var i = 0; i < limit; i++) {
            var pair = pairs[i];
            var idx = pair.indexOf(eq);
            var k, v;
            if (idx >= 0) { k = dec(pair.slice(0, idx)); v = dec(pair.slice(idx + eq.length)); }
            else          { k = dec(pair); v = ''; }
            if (!Object.prototype.hasOwnProperty.call(obj, k)) obj[k] = v;
            else if (Array.isArray(obj[k])) obj[k].push(v);
            else obj[k] = [obj[k], v];
        }
        return obj;
    };

    exports.encode = exports.stringify;
    exports.decode = exports.parse;
});

// ---- quic.js ----
// node:quic — Node 24's experimental QUIC + HTTP/3 module. Backed by
// the host's `daemon_http3` coordinator (quinn + h3-quinn). Each
// listening endpoint runs a real QUIC stack over UDP with TLS-1.3
// and the `h3` ALPN; incoming requests dispatch through the same
// envelope path as `http.createServer`, so user code sees the same
// `(req, res)` shape.

__register_module('quic', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;
    var http = require('http');

    function _err(code, msg) {
        var e = new Error(msg);
        e.code = code;
        return e;
    }

    /// `QuicEndpoint` — a UDP-bound QUIC listener. Wraps an
    /// underlying http.Server so the request/response surface is the
    /// same one Node code uses elsewhere. The key behavioural diff:
    /// the listener speaks H3 wire format (no H1 fallback — QUIC is
    /// HTTP/3-only).
    function QuicEndpoint(options) {
        if (!(this instanceof QuicEndpoint)) {
            throw new TypeError('QuicEndpoint must be constructed with `new`');
        }
        EventEmitter.call(this);
        options = options || {};
        var addr = options.address || {};
        this._port = (addr.port | 0) || 0;
        this._host = addr.host || '127.0.0.1';
        this._cert = options.cert;
        this._key  = options.key;
        this._closed = false;
        this._serverId = -1;
        this._sessions = [];
        // Inner http.Server reused for the request/response dispatch.
        // The H3 daemon pushes incoming requests to the same event
        // channel that http.createServer's listeners consume.
        this._inner = http.createServer();
        var self = this;
        this._inner.on('listening', function() {
            self.emit('listening');
        });
        this._inner.on('close', function() { self.emit('close'); });
        this._inner.on('error', function(e) { self.emit('error', e); });
    }
    QuicEndpoint.prototype = Object.create(EventEmitter.prototype);
    QuicEndpoint.prototype.constructor = QuicEndpoint;

    /// `endpoint.listen(options, sessionHandler)` — bind the QUIC
    /// listener and start serving. `sessionHandler` is called once per
    /// accepted QUIC session; we synthesise a Session object that
    /// emits `'stream'` for each request so user code can speak the
    /// stream-shape API directly.
    QuicEndpoint.prototype.listen = function(options, sessionHandler) {
        if (typeof options === 'function') {
            sessionHandler = options;
            options = undefined;
        }
        options = options || {};
        if (this._closed) throw _err('ERR_QUIC_CLOSED', 'endpoint closed');

        var cert = options.cert || this._cert;
        var key  = options.key  || this._key;
        if (!cert || !key) {
            throw _err('ERR_QUIC_TLS_REQUIRED',
                'QuicEndpoint.listen requires `cert` and `key` (PEM, TLS-1.3)');
        }
        var port = (options.port != null ? options.port : this._port) | 0;

        if (typeof globalThis.__host_http3_listen !== 'function') {
            throw _err('ERR_QUIC_NO_DAEMON',
                'QUIC requires daemon mode (build with --features http3 and run via burn CLI)');
        }

        var self = this;
        // Wire the user's session/stream handler against the inner
        // http.Server's `'request'` event FIRST. This ensures the
        // handler is attached before either TCP or UDP starts
        // accepting requests.
        if (typeof sessionHandler === 'function') {
            this._inner.on('request', function(req, res) {
                var session = new EventEmitter();
                session.endpoint = self;
                session.closed = false;
                session.close = function() { session.closed = true; };
                self._sessions.push(session);
                self.emit('session', session);
                sessionHandler(session);
                var stream = new EventEmitter();
                stream.id = (QuicEndpoint._streamCounter =
                    (QuicEndpoint._streamCounter || 1) + 4);
                stream.req = req;
                stream.res = res;
                stream.write = function(chunk, enc, cb) { return res.write(chunk, enc, cb); };
                stream.end   = function(chunk, enc, cb) { return res.end(chunk, enc, cb); };
                stream.respond = function(headers) {
                    var st = (headers && headers[':status']) || 200;
                    var send = {};
                    if (headers) {
                        Object.keys(headers).forEach(function(k) {
                            if (k.charAt(0) !== ':') send[k] = headers[k];
                        });
                    }
                    res.writeHead(st, send);
                };
                req.on('data', function(chunk) { stream.emit('data', chunk); });
                req.on('end',  function() { stream.emit('end'); });
                req.on('error', function(e) { stream.emit('error', e); });
                session.emit('stream', stream);
                if (self.listenerCount('stream') > 0) self.emit('stream', stream, session);
            });
        }

        // Bind TCP first so the JS handler chain has a real
        // server_id from the HTTP listener. The H3 listener piggybacks
        // on that server_id so incoming UDP/H3 requests dispatch to
        // the same handler.
        this._inner.listen(port, function() {
            var sid = self._inner._serverId;
            if (typeof sid !== 'number' || sid <= 0) {
                self.emit('error', _err('ERR_QUIC_LISTEN',
                    'QuicEndpoint.listen: HTTP listener has no server_id'));
                return;
            }
            self._serverId = sid;
            var h3id = globalThis.__host_http3_listen(
                port, sid, String(cert), String(key));
            if (typeof h3id === 'number' && h3id < 0) {
                var msg = h3id === -1 ? 'no daemon attached'
                        : h3id === -2 ? 'EADDRINUSE (UDP)'
                        : h3id === -4 ? 'permission denied (manifold listen)'
                        : 'h3 listen error';
                self.emit('error', _err('ERR_QUIC_LISTEN',
                    'QuicEndpoint.listen: ' + msg));
            }
        });
        return this;
    };

    QuicEndpoint.prototype.close = function(cb) {
        this._closed = true;
        if (this._serverId > 0 && typeof globalThis.__host_http_close === 'function') {
            try { globalThis.__host_http_close(this._serverId); } catch (_) {}
        }
        if (typeof cb === 'function') Promise.resolve().then(cb);
        return this;
    };

    QuicEndpoint.prototype.address = function() {
        if (this._serverId <= 0) return null;
        return { address: this._host, family: 'IPv4', port: this._port };
    };

    /// `quic.connect(addr, _options)` — client-side QUIC over HTTP/3.
    /// Returns a Session whose `request(headers, body)` issues a real
    /// outbound H3 request via the host's quinn client + h3 client
    /// stack. Each `request` round-trips synchronously from the JS
    /// side (the host runs `block_on` against the daemon's tokio
    /// runtime).
    function connect(addr, _options) {
        if (typeof globalThis.__host_http3_request !== 'function') {
            throw _err('ERR_QUIC_NO_DAEMON',
                'quic.connect: outbound h3 needs the daemon runtime '
                + '(build with --features http3)');
        }
        var session = new EventEmitter();
        session.addr = addr;
        session.closed = false;
        session.close = function() { session.closed = true; };
        /// `session.request(headers, body)` — minimal H3 client
        /// request shape. Returns a Promise resolving to
        /// `{status, headers, body}` (Buffer) — matches what an h3
        /// client would yield for a single-stream request.
        session.request = function(headers, body) {
            headers = headers || {};
            var method = headers[':method'] || 'GET';
            var path = headers[':path'] || '/';
            var scheme = headers[':scheme'] || 'https';
            var authority = headers[':authority']
                || (typeof addr === 'string' ? addr : (addr && addr.address));
            var url = scheme + '://' + authority + path;
            var Buf = globalThis.Buffer || require('buffer').Buffer;
            var bodyBytes = body == null ? new Uint8Array(0)
                : (typeof body === 'string' ? Buf.from(body, 'utf8')
                : Buf.isBuffer(body) ? body
                : new Uint8Array(body));
            var bodyB64 = Buf.from(bodyBytes).toString('base64');
            var raw = globalThis.__host_http3_request(url, String(method), bodyB64);
            if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
                return Promise.reject(_err('ERR_QUIC_REQUEST',
                    'quic.connect.request: ' + raw.slice('__HOST_ERR__:'.length)));
            }
            try {
                var parsed = JSON.parse(raw);
                var bodyOut = parsed.body_b64
                    ? Buf.from(parsed.body_b64, 'base64')
                    : Buf.alloc(0);
                return Promise.resolve({
                    status: parsed.status,
                    headers: parsed.headers || {},
                    body: bodyOut,
                });
            } catch (e) {
                return Promise.reject(_err('ERR_QUIC_REQUEST',
                    'quic.connect.request: bad host response: ' + e.message));
            }
        };
        Promise.resolve().then(function() { session.emit('connect'); });
        return session;
    }

    exports.QuicEndpoint = QuicEndpoint;
    exports.connect = connect;
    /// Constants pinned to RFC 9000 / 9114 values so apps that destructure
    /// them at module-init don't choke.
    exports.constants = {
        // QUIC transport error codes — RFC 9000 §20.1.
        QUIC_NO_ERROR: 0,
        QUIC_INTERNAL_ERROR: 1,
        QUIC_CONNECTION_REFUSED: 2,
        QUIC_FLOW_CONTROL_ERROR: 3,
        QUIC_STREAM_LIMIT_ERROR: 4,
        QUIC_STREAM_STATE_ERROR: 5,
        QUIC_FINAL_SIZE_ERROR: 6,
        QUIC_FRAME_ENCODING_ERROR: 7,
        QUIC_TRANSPORT_PARAMETER_ERROR: 8,
        QUIC_CONNECTION_ID_LIMIT_ERROR: 9,
        QUIC_PROTOCOL_VIOLATION: 10,
        QUIC_INVALID_TOKEN: 11,
        QUIC_APPLICATION_ERROR: 12,
        QUIC_CRYPTO_BUFFER_EXCEEDED: 13,
        QUIC_KEY_UPDATE_ERROR: 14,
        QUIC_AEAD_LIMIT_REACHED: 15,
        QUIC_NO_VIABLE_PATH: 16,
        // HTTP/3 frame types — RFC 9114 §11.
        H3_DATA: 0x00,
        H3_HEADERS: 0x01,
        H3_CANCEL_PUSH: 0x03,
        H3_SETTINGS: 0x04,
        H3_PUSH_PROMISE: 0x05,
        H3_GOAWAY: 0x07,
    };
});

// ---- readline.js ----
// readline — Node 20's line reader. The module is normally used to
// prompt for stdin input (`createInterface({input: process.stdin})`)
// and parse it into discrete lines. Burn's stdin is one-shot via
// the script invocation, but the surface is what library code
// expects to import. We provide a real EventEmitter that emits
// 'line' / 'close' synchronously when the user feeds chunks via
// the readable's `on('data')` events.

__register_module('readline', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;

    function Interface(opts) {
        EventEmitter.call(this);
        opts = opts || {};
        this.input = opts.input;
        this.output = opts.output;
        this._buffer = '';
        this._closed = false;

        if (this.input && typeof this.input.on === 'function') {
            var self = this;
            this.input.on('data', function(chunk) { self._consume(chunk); });
            this.input.on('end', function() { self.close(); });
            this.input.on('close', function() { self.close(); });
        }
    }
    Interface.prototype = Object.create(EventEmitter.prototype);
    Interface.prototype.constructor = Interface;

    Interface.prototype._consume = function(chunk) {
        if (this._closed) return;
        var text;
        if (typeof chunk === 'string') text = chunk;
        else if (chunk && chunk.toString) text = chunk.toString('utf8');
        else return;
        this._buffer += text;
        var nl;
        while ((nl = this._buffer.indexOf('\n')) !== -1) {
            var line = this._buffer.slice(0, nl);
            this._buffer = this._buffer.slice(nl + 1);
            // Strip trailing `\r` for Windows-style line endings.
            if (line.length > 0 && line.charCodeAt(line.length - 1) === 13) {
                line = line.slice(0, -1);
            }
            try { this.emit('line', line); } catch (_) {}
        }
    };

    Interface.prototype.close = function() {
        if (this._closed) return;
        this._closed = true;
        // Flush any trailing buffered content as a final line.
        if (this._buffer.length > 0) {
            var last = this._buffer;
            this._buffer = '';
            try { this.emit('line', last); } catch (_) {}
        }
        try { this.emit('close'); } catch (_) {}
    };

    Interface.prototype.question = function(query, callback) {
        // No interactive stdin in the sandbox: we can't actually
        // wait for the user. Surface a clear error rather than
        // hanging.
        var err = new Error(
            'readline.question: interactive prompts are not supported in the ' +
            'Afterburner sandbox (no TTY); pass scripted input via input streams.'
        );
        err.code = 'ERR_NO_TTY';
        if (typeof callback === 'function') Promise.resolve().then(function() { callback(query); });
        throw err;
    };

    Interface.prototype.pause = function() { return this; };
    Interface.prototype.resume = function() { return this; };
    Interface.prototype.write = function() { return this; };
    Interface.prototype.setPrompt = function() {};
    Interface.prototype.prompt = function() {};
    Interface.prototype.getPrompt = function() { return ''; };
    Interface.prototype.getCursorPos = function() { return { rows: 0, cols: 0 }; };

    function createInterface(opts) {
        return new Interface(opts);
    }

    function clearLine() { return true; }
    function clearScreenDown() { return true; }
    function cursorTo() { return true; }
    function moveCursor() { return true; }
    function emitKeypressEvents() {}

    exports.createInterface = createInterface;
    exports.Interface = Interface;
    exports.clearLine = clearLine;
    exports.clearScreenDown = clearScreenDown;
    exports.cursorTo = cursorTo;
    exports.moveCursor = moveCursor;
    exports.emitKeypressEvents = emitKeypressEvents;

    /// readline.promises — Node 17+ Promise-shaped wrappers. The
    /// readline-side `question`/`Interface` aren't usable in our
    /// current daemon (we don't have a stdin pump), but exposing the
    /// surface keeps libraries that probe at module-init from
    /// crashing.
    exports.promises = {
        createInterface: createInterface,
        Interface: Interface,
    };
});

// ---- repl.js ----
// repl — Node 20's read-eval-print-loop server.
//
// Burn doesn't have an interactive TTY in the sandboxed JS context,
// but `repl.start()` is sometimes called from server-introspection
// tools or in `--inspect-brk` flows. We expose a `REPLServer`
// class that accepts the configuration, lets callers wire `command`
// / `replServer.context.foo = ...` style globals, and ignores
// the read loop (no stdin available to read).

__register_module('repl', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;
    var vm = require('vm');

    function REPLServer(opts) {
        EventEmitter.call(this);
        opts = opts || {};
        this.useColors = !!opts.useColors;
        this.useGlobal = opts.useGlobal !== false;
        this.terminal = !!opts.terminal;
        this.input = opts.input || null;
        this.output = opts.output || null;
        this.commands = Object.create(null);
        // The REPL spec exposes the eval scope as `replServer.context`.
        // We back it with a fresh vm context so callers can attach
        // helpers (`replServer.context.x = 5`) without mutating the
        // surrounding globals.
        this.context = vm.createContext({});
    }
    REPLServer.prototype = Object.create(EventEmitter.prototype);
    REPLServer.prototype.constructor = REPLServer;

    REPLServer.prototype.defineCommand = function(name, descriptor) {
        if (typeof descriptor === 'function') descriptor = { action: descriptor };
        this.commands[name] = descriptor;
    };
    REPLServer.prototype.displayPrompt = function() {};
    REPLServer.prototype.setPrompt = function() {};
    REPLServer.prototype.close = function() { this.emit('exit'); };
    REPLServer.prototype.eval = function(code, _ctx, _filename, callback) {
        try {
            var result = vm.runInContext(code, this.context);
            if (typeof callback === 'function') callback(null, result);
        } catch (e) {
            if (typeof callback === 'function') callback(e);
        }
    };

    function start(opts) {
        if (typeof opts === 'string') opts = { prompt: opts };
        var server = new REPLServer(opts);
        return server;
    }

    exports.start = start;
    exports.REPLServer = REPLServer;
    exports.REPL_MODE_SLOPPY = Symbol('repl-sloppy');
    exports.REPL_MODE_STRICT = Symbol('repl-strict');
    exports.Recoverable = function Recoverable(err) {
        var e = err instanceof Error ? err : new Error(String(err));
        e.name = 'Recoverable';
        return e;
    };
    exports.builtinModules = []; // populated by `module.builtinModules` consumers
});

// ---- shadow_argon2.js ----
// L3 shadow for the `argon2` npm package.
//
// require('argon2') resolves to this polyfill regardless of whether
// node_modules/argon2 exists; the upstream package ships a .node
// native addon that cannot load inside the WASM sandbox, so the
// shadow kicks in transparently.
//
// Surface: hash() / verify() / needsRehash() — all async, matching
// the npm package. Type constants (argon2d / argon2i / argon2id)
// and default options match upstream defaults.

__register_module('argon2', function(module, exports, require) {

    // Match upstream's numeric constants (available as
    // `argon2.argon2d` etc. + the default type `argon2id`).
    var TYPES = { argon2d: 0, argon2i: 1, argon2id: 2 };

    // Upstream defaults (time=3, memory=65536 KiB, parallelism=4,
    // type=argon2id). Hash length is intentionally not passed to the
    // host — the crate derives it from the chosen output size.
    var DEFAULTS = {
        type: 2,  // argon2id
        timeCost: 3,
        memoryCost: 65536,
        parallelism: 4,
    };

    function optInt(opt, key, fallback) {
        if (!opt) return fallback;
        var v = opt[key];
        return (typeof v === 'number' && isFinite(v) && v >= 0) ? (v | 0) : fallback;
    }

    function optType(opt) {
        if (!opt) return DEFAULTS.type;
        var t = opt.type;
        if (typeof t === 'number' && t >= 0 && t <= 2) return t | 0;
        return DEFAULTS.type;
    }

    function checkHostErr(out, op) {
        if (typeof out === 'string' && out.indexOf('__HOST_ERR__:') === 0) {
            var msg = out.slice('__HOST_ERR__:'.length);
            var err = new Error('argon2.' + op + ': ' + msg);
            err.code = 'ERR_SHADOW_ARGON2';
            throw err;
        }
        return out;
    }

    function hashSync(password, options) {
        if (typeof password !== 'string') {
            throw new TypeError('argon2.hash: password must be a string');
        }
        var fn = globalThis.__host_shadow_argon2_hash;
        if (typeof fn !== 'function') {
            throw new Error('argon2 not available: rebuild with `shadow-argon2` feature');
        }
        var ty = optType(options);
        var tc = optInt(options, 'timeCost', DEFAULTS.timeCost);
        var mc = optInt(options, 'memoryCost', DEFAULTS.memoryCost);
        var par = optInt(options, 'parallelism', DEFAULTS.parallelism);
        return checkHostErr(fn(password, ty, tc, mc, par), 'hash');
    }

    function verifySync(hash, password) {
        if (typeof hash !== 'string' || typeof password !== 'string') {
            throw new TypeError('argon2.verify: hash + password must be strings');
        }
        var fn = globalThis.__host_shadow_argon2_verify;
        if (typeof fn !== 'function') {
            throw new Error('argon2 not available: rebuild with `shadow-argon2` feature');
        }
        var rc = fn(hash, password);
        if (rc === 1) return true;
        if (rc === 0) return false;
        var detail = (typeof globalThis.__host_last_error === 'function')
            ? globalThis.__host_last_error()
            : ('rc=' + rc);
        var err = new Error('argon2.verify: ' + detail);
        err.code = 'ERR_SHADOW_ARGON2';
        throw err;
    }

    function needsRehashSync(hash, options) {
        if (typeof hash !== 'string') {
            throw new TypeError('argon2.needsRehash: hash must be a string');
        }
        var fn = globalThis.__host_shadow_argon2_needs_rehash;
        if (typeof fn !== 'function') {
            throw new Error('argon2 not available: rebuild with `shadow-argon2` feature');
        }
        var ty = optType(options);
        var tc = optInt(options, 'timeCost', DEFAULTS.timeCost);
        var mc = optInt(options, 'memoryCost', DEFAULTS.memoryCost);
        var par = optInt(options, 'parallelism', DEFAULTS.parallelism);
        var rc = fn(hash, ty, tc, mc, par);
        if (rc === 1) return true;
        if (rc === 0) return false;
        var detail = (typeof globalThis.__host_last_error === 'function')
            ? globalThis.__host_last_error()
            : ('rc=' + rc);
        var err = new Error('argon2.needsRehash: ' + detail);
        err.code = 'ERR_SHADOW_ARGON2';
        throw err;
    }

    // Async-only API per upstream. All three return Promises.
    exports.hash = function(password, options) {
        try { return Promise.resolve(hashSync(password, options)); }
        catch (e) { return Promise.reject(e); }
    };
    exports.verify = function(hash, password) {
        try { return Promise.resolve(verifySync(hash, password)); }
        catch (e) { return Promise.reject(e); }
    };
    exports.needsRehash = function(hash, options) {
        try { return Promise.resolve(needsRehashSync(hash, options)); }
        catch (e) { return Promise.reject(e); }
    };

    // Constants matching upstream.
    exports.argon2d = TYPES.argon2d;
    exports.argon2i = TYPES.argon2i;
    exports.argon2id = TYPES.argon2id;
    exports.defaults = Object.freeze(Object.assign({ hashLength: 32 }, DEFAULTS));
    exports.limits = Object.freeze({
        hashLength: { min: 4, max: 0x7fffffff },
        memoryCost: { min: 8, max: 0x7fffffff },
        timeCost: { min: 2, max: 0x7fffffff },
        parallelism: { min: 1, max: 0x7fffff },
    });
});

// ---- shadow_bcrypt.js ----
// L3 shadow for the `bcrypt` npm package.
//
// require('bcrypt') resolves to THIS polyfill regardless of whether
// node_modules/bcrypt exists on disk, because pre-registered modules
// always win in the require() precedence (B6). Users whose
// node_modules/bcrypt carries a `.node` native addon (which bcrypt
// upstream always does) land here automatically inside the WASM
// sandbox — no code changes needed.
//
// The three host globals this polyfill calls
// (`__host_shadow_bcrypt_*`) are always present in the plugin
// binary. The host-side implementation is feature-gated by
// `shadow-bcrypt` on afterburner-wasi; without the feature the
// imports return a structured error we surface as a clean JS
// exception naming the feature flag.

__register_module('bcrypt', function(module, exports, require) {

    function checkHostErr(out, op) {
        if (typeof out === 'string' && out.indexOf('__HOST_ERR__:') === 0) {
            var msg = out.slice('__HOST_ERR__:'.length);
            var err = new Error('bcrypt.' + op + ': ' + msg);
            err.code = 'ERR_SHADOW_BCRYPT';
            throw err;
        }
        return out;
    }

    function asCost(saltOrRounds) {
        // bcrypt accepts either a number of rounds or a salt string.
        // Pure numbers pass through; salt strings carry the cost
        // embedded in the "$2b$CC$..." prefix, but since we always
        // regenerate via the Rust crate's own cost arg, we parse
        // the cost out of the salt string when one is passed.
        if (typeof saltOrRounds === 'number') return saltOrRounds | 0;
        if (typeof saltOrRounds === 'string') {
            // Match "$2b$12$..." — rounds are positions 4-5.
            var m = saltOrRounds.match(/^\$2[aby]\$(\d\d)\$/);
            if (m) return parseInt(m[1], 10);
        }
        return 0;  // 0 signals "use default" to the host side
    }

    function hashSyncImpl(data, saltOrRounds) {
        if (typeof data !== 'string') {
            throw new TypeError('bcrypt.hash: data must be a string');
        }
        var cost = asCost(saltOrRounds);
        var fn = globalThis.__host_shadow_bcrypt_hash;
        if (typeof fn !== 'function') {
            throw new Error('bcrypt not available: rebuild with `shadow-bcrypt` feature');
        }
        return checkHostErr(fn(data, cost), 'hash');
    }

    function compareSyncImpl(data, hash) {
        if (typeof data !== 'string' || typeof hash !== 'string') {
            throw new TypeError('bcrypt.compare: data + hash must be strings');
        }
        var fn = globalThis.__host_shadow_bcrypt_verify;
        if (typeof fn !== 'function') {
            throw new Error('bcrypt not available: rebuild with `shadow-bcrypt` feature');
        }
        var rc = fn(data, hash);
        if (rc === 1) return true;
        if (rc === 0) return false;
        // Negative return → host populated last_error; fetch via
        // the standard diagnostic bridge the existing polyfills use.
        var detail = (typeof globalThis.__host_last_error === 'function')
            ? globalThis.__host_last_error()
            : ('rc=' + rc);
        var err = new Error('bcrypt.compare: ' + detail);
        err.code = 'ERR_SHADOW_BCRYPT';
        throw err;
    }

    function genSaltSyncImpl(rounds) {
        var fn = globalThis.__host_shadow_bcrypt_gen_salt;
        if (typeof fn !== 'function') {
            throw new Error('bcrypt not available: rebuild with `shadow-bcrypt` feature');
        }
        return checkHostErr(fn(typeof rounds === 'number' ? rounds | 0 : 0), 'genSalt');
    }

    // Async variants wrap sync in a resolved Promise. bcrypt's cost
    // parameter already bounds CPU time per-call, and our runtime
    // doesn't have a background thread pool — wrapping in a Promise
    // matches the npm API surface without pretending there's
    // concurrency underneath. Callbacks also supported for parity
    // with the pre-Promise npm API.
    function wrapAsync(sync) {
        return function(/* ..., cb? */) {
            var args = Array.prototype.slice.call(arguments);
            var cb = typeof args[args.length - 1] === 'function'
                ? args.pop() : null;
            try {
                var v = sync.apply(null, args);
                if (cb) {
                    queueMicrotask(function() { cb(null, v); });
                    return undefined;
                }
                return Promise.resolve(v);
            } catch (e) {
                if (cb) {
                    queueMicrotask(function() { cb(e); });
                    return undefined;
                }
                return Promise.reject(e);
            }
        };
    }

    exports.hashSync = hashSyncImpl;
    exports.compareSync = compareSyncImpl;
    exports.genSaltSync = genSaltSyncImpl;

    exports.hash = wrapAsync(hashSyncImpl);
    exports.compare = wrapAsync(compareSyncImpl);
    exports.genSalt = wrapAsync(genSaltSyncImpl);

    // `getRounds(hash)` — pure-JS inspection, no host call needed.
    exports.getRounds = function(hash) {
        if (typeof hash !== 'string') {
            throw new TypeError('bcrypt.getRounds: hash must be a string');
        }
        var m = hash.match(/^\$2[aby]\$(\d\d)\$/);
        if (!m) {
            throw new Error('bcrypt.getRounds: malformed hash');
        }
        return parseInt(m[1], 10);
    };

    // `truncates(password)` — pure-JS check for bcrypt's 72-byte
    // password truncation boundary. Node's upstream ships this so we
    // do too; users who care about long passwords can gate on it.
    exports.truncates = function(password) {
        if (typeof password !== 'string') return false;
        // Use TextEncoder for accurate byte count (multibyte chars).
        if (typeof TextEncoder === 'function') {
            return new TextEncoder().encode(password).length > 72;
        }
        return password.length > 72;
    };
});

// ---- shadow_jsonwebtoken.js ----
// L3 shadow for the `jsonwebtoken` npm package.
//
// require('jsonwebtoken') resolves to this polyfill. Backed by the
// Rust `jsonwebtoken` crate for HMAC (HS256/384/512), RSA (RS256/
// 384/512, PS256/384/512), ECDSA (ES256/384), and EdDSA. Secrets are
// passed as strings for HMAC, PEM-formatted keys for the asymmetric
// algorithms.
//
// The npm package documents both sync `jwt.sign(...)` and callback
// `jwt.sign(..., (err, token) => {})` shapes for sign and verify.
// We match both. decode is always sync in upstream — we match that
// too.

__register_module('jsonwebtoken', function(module, exports, require) {

    // Algorithm shortlist matching jsonwebtoken's published surface.
    // Unknown algorithm in a sign/verify call falls back to HS256,
    // matching the upstream default.
    var DEFAULT_ALG = 'HS256';

    function checkHostErr(out, op) {
        if (typeof out === 'string' && out.indexOf('__HOST_ERR__:') === 0) {
            var msg = out.slice('__HOST_ERR__:'.length);
            var err = new Error('jwt.' + op + ': ' + msg);
            // jsonwebtoken exposes several named error classes. We
            // approximate with `.name` set to the closest match.
            if (/expired/i.test(msg)) err.name = 'TokenExpiredError';
            else if (/signature|invalid/i.test(msg)) err.name = 'JsonWebTokenError';
            else err.name = 'JsonWebTokenError';
            err.code = 'ERR_SHADOW_JWT';
            throw err;
        }
        return out;
    }

    function normalizeSecret(secret) {
        // Accept Buffer (from node-compat Buffer polyfill), string,
        // or object with `.key` / `.passphrase`. Passphrase on
        // encrypted keys isn't supported today — documented below.
        if (typeof secret === 'string') return secret;
        if (secret && typeof secret.toString === 'function') return secret.toString();
        return '';
    }

    function normalizeOptions(opts) {
        // jsonwebtoken accepts `expiresIn` as either a number (seconds)
        // or a string like "1h" / "7d". The upstream parses the
        // string via the `ms` npm package; we keep a minimal subset
        // to avoid pulling in a duration parser.
        if (!opts) return {};
        var out = {};
        if (typeof opts.algorithm === 'string') out.algorithm = opts.algorithm;
        if (typeof opts.issuer === 'string') out.issuer = opts.issuer;
        if (typeof opts.subject === 'string') out.subject = opts.subject;
        if (opts.audience != null) out.audience = opts.audience;
        if (typeof opts.jwtid === 'string') out.jwtid = opts.jwtid;
        if (typeof opts.keyid === 'string') out.keyid = opts.keyid;
        if (opts.noTimestamp === true) out.noTimestamp = true;
        if (opts.ignoreExpiration === true) out.ignoreExpiration = true;
        if (opts.ignoreNotBefore === true) out.ignoreNotBefore = true;
        if (opts.expiresIn != null) out.expiresIn = toSeconds(opts.expiresIn);
        if (opts.notBefore != null) out.notBefore = toSeconds(opts.notBefore);
        return out;
    }

    // Minimal "ms-like" parser. Covers `s`, `m`, `h`, `d`.
    // Anything more exotic: pass a plain number of seconds.
    function toSeconds(v) {
        if (typeof v === 'number') return v | 0;
        if (typeof v !== 'string') return 0;
        var m = v.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)?$/i);
        if (!m) return 0;
        var n = parseInt(m[1], 10);
        var unit = (m[2] || 's').toLowerCase();
        if (unit[0] === 'm' && unit[1] !== undefined && unit[1] !== 'i' && unit[1] !== 's') {
            // "m" alone = minutes; guard against "month/ms" oddities.
            return n * 60;
        }
        switch (unit[0]) {
            case 's': return n;
            case 'm': return n * 60;
            case 'h': return n * 3600;
            case 'd': return n * 86400;
            default: return n;
        }
    }

    function signSync(payload, secret, options) {
        if (payload == null || typeof payload !== 'object') {
            throw new TypeError('jwt.sign: payload must be an object');
        }
        var fn = globalThis.__host_shadow_jwt_sign;
        if (typeof fn !== 'function') {
            throw new Error('jsonwebtoken not available: rebuild with `shadow-jsonwebtoken` feature');
        }
        var opts = normalizeOptions(options);
        if (!opts.algorithm) opts.algorithm = DEFAULT_ALG;
        return checkHostErr(
            fn(JSON.stringify(payload), normalizeSecret(secret), JSON.stringify(opts)),
            'sign'
        );
    }

    function verifySync(token, secret, options) {
        if (typeof token !== 'string') {
            throw new TypeError('jwt.verify: token must be a string');
        }
        var fn = globalThis.__host_shadow_jwt_verify;
        if (typeof fn !== 'function') {
            throw new Error('jsonwebtoken not available: rebuild with `shadow-jsonwebtoken` feature');
        }
        var opts = normalizeOptions(options);
        if (!opts.algorithm) opts.algorithm = DEFAULT_ALG;
        var raw = checkHostErr(
            fn(token, normalizeSecret(secret), JSON.stringify(opts)),
            'verify'
        );
        return JSON.parse(raw);
    }

    function decodeSync(token, options) {
        if (typeof token !== 'string') return null;
        var fn = globalThis.__host_shadow_jwt_decode;
        if (typeof fn !== 'function') {
            throw new Error('jsonwebtoken not available: rebuild with `shadow-jsonwebtoken` feature');
        }
        var raw = fn(token);
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            // Upstream `decode` returns null on malformed input
            // rather than throwing.
            return null;
        }
        var parsed = JSON.parse(raw);
        // `{ complete: true }` → return `{ header, payload, signature }`;
        // default returns just the payload.
        if (options && options.complete === true) {
            // Signature isn't surfaced by our host decode; derive
            // from the token string to match upstream shape.
            var sig = token.split('.')[2] || '';
            return { header: parsed.header, payload: parsed.payload, signature: sig };
        }
        return parsed.payload;
    }

    // sign / verify accept an optional trailing callback. When
    // present, result flows through the callback; when absent, we
    // return synchronously (matches upstream when `algorithm` is
    // supplied in options).
    exports.sign = function(payload, secret, optionsOrCb, cb) {
        var options = null;
        if (typeof optionsOrCb === 'function') {
            cb = optionsOrCb;
        } else {
            options = optionsOrCb;
        }
        if (typeof cb === 'function') {
            try {
                var tok = signSync(payload, secret, options);
                queueMicrotask(function() { cb(null, tok); });
            } catch (e) {
                queueMicrotask(function() { cb(e); });
            }
            return;
        }
        return signSync(payload, secret, options);
    };

    exports.verify = function(token, secret, optionsOrCb, cb) {
        var options = null;
        if (typeof optionsOrCb === 'function') {
            cb = optionsOrCb;
        } else {
            options = optionsOrCb;
        }
        if (typeof cb === 'function') {
            try {
                var decoded = verifySync(token, secret, options);
                queueMicrotask(function() { cb(null, decoded); });
            } catch (e) {
                queueMicrotask(function() { cb(e); });
            }
            return;
        }
        return verifySync(token, secret, options);
    };

    exports.decode = decodeSync;

    // Error classes — users may do `if (e instanceof jwt.JsonWebTokenError)`.
    // We approximate: the thrown errors above carry `.name` set to
    // the closest match; these constructors exist mostly so
    // `instanceof` doesn't blow up.
    function makeErrorClass(name) {
        function Cls(msg) {
            var e = new Error(msg);
            e.name = name;
            return e;
        }
        return Cls;
    }
    exports.JsonWebTokenError = makeErrorClass('JsonWebTokenError');
    exports.TokenExpiredError = makeErrorClass('TokenExpiredError');
    exports.NotBeforeError = makeErrorClass('NotBeforeError');
});

// ---- shadow_sharp.js ----
// L3 shadow for the `sharp` npm package.
//
// require('sharp') resolves to this polyfill regardless of whether
// node_modules/sharp exists; the upstream package ships a libvips
// `.node` native addon that cannot load inside the WASM sandbox, so
// the shadow kicks in transparently.
//
// Backed by:
//   * `image` crate — codec layer (PNG, JPEG, WebP, GIF, BMP)
//   * `fast_image_resize` — SIMD-accelerated resizing
//
// The fluent builder pattern accumulates ops in JS without any host
// roundtrip; only the terminal call (toBuffer / toFile / metadata)
// crosses into Rust, with the entire pipeline as one JSON blob.
//
// API surface — covers the operations real `sharp` users actually
// reach for:
//
//   sharp(input)
//     .resize(width[, height][, options])     // {fit, kernel}
//     .rotate(degrees)                        // 0/90/180/270 only
//     .grayscale() / .greyscale()
//     .flip() / .flop()
//     .extract({left, top, width, height})    // crop
//     .blur(sigma)
//     .negate()
//     .jpeg({quality}) / .png({compressionLevel}) / .webp({quality, lossless})
//     .toBuffer()              -> Promise<Buffer>
//     .toFile(path)            -> Promise<{format, size, width, height}>
//     .metadata()              -> Promise<{width, height, format, channels, hasAlpha, ...}>
//
// Deferred (intentionally; throw a clear error if used):
//   * `.composite(...)` (overlays)
//   * Per-channel `.modulate(...)`, `.tint(...)`, `.recomb(...)`
//   * Streams (`.pipe()`, `Readable` / `Writable` interop)
//   * Raw / SVG / TIFF / AVIF / JP2 / HEIF inputs/outputs
//   * Color-space conversions beyond the codec defaults

__register_module('sharp', function(module, exports, require) {
    var fs = require('fs');
    var Buffer = require('buffer').Buffer;

    function isHostErr(s) {
        return typeof s === 'string' && s.indexOf('__HOST_ERR__:') === 0;
    }

    function hostErrToError(s) {
        var msg = s.slice('__HOST_ERR__:'.length);
        var err = new Error('sharp: ' + msg);
        err.code = 'ERR_SHADOW_SHARP';
        return err;
    }

    function ensureHost(name) {
        var fn = globalThis[name];
        if (typeof fn !== 'function') {
            var err = new Error('sharp not available: rebuild burn with `shadow-sharp`');
            err.code = 'ERR_SHADOW_SHARP';
            throw err;
        }
        return fn;
    }

    // --- source normalization --------------------------------------

    function makeSource(input) {
        if (Buffer.isBuffer(input)) {
            return { kind: 'buffer', data_b64: input.toString('base64') };
        }
        if (input instanceof Uint8Array) {
            return { kind: 'buffer', data_b64: Buffer.from(input).toString('base64') };
        }
        if (typeof input === 'string') {
            // Path. fs.readFileSync (Node-compat: returns Buffer when
            // no encoding is given) reads the file binary-safely.
            var bytes = fs.readFileSync(input);
            return {
                kind: 'buffer',
                data_b64: bytes.toString('base64'),
                _path: input,
            };
        }
        throw new TypeError(
            'sharp: input must be a Buffer, Uint8Array, or filesystem path string'
        );
    }

    // --- Sharp instance --------------------------------------------

    function Sharp(input) {
        if (!(this instanceof Sharp)) return new Sharp(input);
        this._source = makeSource(input);
        this._ops = [];
        this._format = null; // populated by toFormat / .jpeg / .png / .webp
        this._formatOpts = {};
    }

    function pushOp(self, op) {
        self._ops.push(op);
        return self;
    }

    Sharp.prototype.resize = function(width, height, options) {
        // Sharp accepts:
        //   resize(width)
        //   resize(width, height)
        //   resize({width, height, fit, kernel, ...})
        if (typeof width === 'object' && width !== null) {
            options = width;
            width = options.width;
            height = options.height;
        }
        var op = { op: 'resize' };
        if (typeof width === 'number') op.width = width | 0;
        if (typeof height === 'number') op.height = height | 0;
        if (options && typeof options.fit === 'string') op.fit = options.fit;
        if (options && typeof options.kernel === 'string') op.kernel = options.kernel;
        return pushOp(this, op);
    };

    Sharp.prototype.rotate = function(degrees) {
        var d = (degrees | 0);
        return pushOp(this, { op: 'rotate', degrees: d });
    };

    Sharp.prototype.grayscale = function() {
        return pushOp(this, { op: 'grayscale' });
    };
    Sharp.prototype.greyscale = Sharp.prototype.grayscale;

    Sharp.prototype.flip = function() {
        return pushOp(this, { op: 'flip' });
    };

    Sharp.prototype.flop = function() {
        return pushOp(this, { op: 'flop' });
    };

    Sharp.prototype.negate = function() {
        return pushOp(this, { op: 'negate' });
    };

    Sharp.prototype.extract = function(region) {
        if (!region || typeof region !== 'object') {
            throw new TypeError('sharp.extract: region object required');
        }
        return pushOp(this, {
            op: 'extract',
            left: (region.left | 0),
            top: (region.top | 0),
            width: (region.width | 0),
            height: (region.height | 0),
        });
    };

    Sharp.prototype.blur = function(sigma) {
        if (typeof sigma !== 'number' || !isFinite(sigma)) {
            throw new TypeError('sharp.blur: numeric sigma required');
        }
        return pushOp(this, { op: 'blur', sigma: sigma });
    };

    // --- format selection ------------------------------------------

    Sharp.prototype.jpeg = function(options) {
        this._format = 'jpeg';
        this._formatOpts = options || {};
        return this;
    };

    Sharp.prototype.png = function(options) {
        this._format = 'png';
        this._formatOpts = options || {};
        return this;
    };

    Sharp.prototype.webp = function(options) {
        this._format = 'webp';
        this._formatOpts = options || {};
        return this;
    };

    Sharp.prototype.toFormat = function(format, options) {
        if (typeof format !== 'string') {
            throw new TypeError('sharp.toFormat: format string required');
        }
        switch (format.toLowerCase()) {
            case 'jpeg':
            case 'jpg':
                return this.jpeg(options);
            case 'png':
                return this.png(options);
            case 'webp':
                return this.webp(options);
            default:
                throw new Error('sharp.toFormat: unsupported format ' + format);
        }
    };

    // --- pixel-pipeline ops registered as fluent stages -----------
    //
    // Each op pushes into `this._ops` so the host's image pipeline
    // processes them in order. The host crate (crates/afterburner-
    // node-compat/src/shadows/sharp.rs) reads the op tags below and
    // dispatches to the appropriate `image` / `fast_image_resize`
    // pipeline stage.

    Sharp.prototype.tint = function(rgb) {
        // Accept `{ r, g, b }`, `[r, g, b]`, or a hex string.
        var r, g, b;
        if (typeof rgb === 'string') {
            var hex = rgb.replace(/^#/, '');
            if (hex.length === 3) {
                r = parseInt(hex[0] + hex[0], 16);
                g = parseInt(hex[1] + hex[1], 16);
                b = parseInt(hex[2] + hex[2], 16);
            } else if (hex.length === 6) {
                r = parseInt(hex.slice(0, 2), 16);
                g = parseInt(hex.slice(2, 4), 16);
                b = parseInt(hex.slice(4, 6), 16);
            }
        } else if (Array.isArray(rgb)) {
            r = rgb[0]; g = rgb[1]; b = rgb[2];
        } else if (rgb && typeof rgb === 'object') {
            r = rgb.r; g = rgb.g; b = rgb.b;
        }
        return pushOp(this, {
            op: 'tint',
            r: (r | 0) & 0xFF, g: (g | 0) & 0xFF, b: (b | 0) & 0xFF,
        });
    };

    Sharp.prototype.modulate = function(opts) {
        // Per sharp's spec: brightness 1.0 = unchanged, saturation
        // 1.0 = unchanged, hue 0 = unchanged (degrees, can be
        // negative).
        opts = opts || {};
        return pushOp(this, {
            op: 'modulate',
            brightness: typeof opts.brightness === 'number' ? opts.brightness : 1,
            saturation: typeof opts.saturation === 'number' ? opts.saturation : 1,
            hue:        typeof opts.hue === 'number' ? opts.hue : 0,
        });
    };

    Sharp.prototype.sharpen = function(sigma, flat, jagged) {
        // sharp(sigma=1.0) is the canonical "unsharp mask" call. We
        // accept either a single number or the legacy {sigma, m1, m2}
        // shape; the host applies an unsharp-mask convolution.
        var s = 1, f = 1, j = 2;
        if (typeof sigma === 'number') s = sigma;
        else if (sigma && typeof sigma === 'object') {
            if (typeof sigma.sigma === 'number') s = sigma.sigma;
            if (typeof sigma.m1 === 'number') f = sigma.m1;
            if (typeof sigma.m2 === 'number') j = sigma.m2;
        }
        if (typeof flat === 'number') f = flat;
        if (typeof jagged === 'number') j = jagged;
        return pushOp(this, { op: 'sharpen', sigma: s, flat: f, jagged: j });
    };

    Sharp.prototype.normalize = function(_opts) {
        // Histogram stretch — host walks per-channel min/max and
        // stretches to [0,255].
        return pushOp(this, { op: 'normalize' });
    };
    Sharp.prototype.normalise = Sharp.prototype.normalize;

    Sharp.prototype.threshold = function(level, opts) {
        // Per sharp: pixels with luminance ≥ level go white; below
        // go black. Default level=128. `grayscale: false` keeps the
        // RGB channels; default true converts to single-channel.
        opts = opts || {};
        return pushOp(this, {
            op: 'threshold',
            level: typeof level === 'number' ? (level | 0) : 128,
            grayscale: opts.grayscale !== false,
        });
    };

    Sharp.prototype.composite = function(layers) {
        // sharp.composite(layers) — array of `{input, top, left, blend}`.
        // Host reads each layer, decodes input bytes, alpha-blends at
        // (left, top). Defaults: top/left = 0, blend = 'over'.
        if (!Array.isArray(layers)) {
            throw new TypeError('sharp.composite: layers must be an array');
        }
        var serialized = layers.map(function(layer) {
            var src = makeSource(layer.input);
            return {
                source_b64: src.bytes_b64,
                top: (layer.top | 0) || 0,
                left: (layer.left | 0) || 0,
                blend: layer.blend || 'over',
                gravity: layer.gravity || null,
            };
        });
        return pushOp(this, { op: 'composite', layers: serialized });
    };

    // --- terminal ops ----------------------------------------------

    Sharp.prototype._buildPipeline = function() {
        // Default to PNG if the user never picked a format — matches
        // Sharp's behavior (preserves source format when possible,
        // but for the shadow we default to PNG since we don't track
        // source format separately).
        var format = this._format || inferDefaultFormat(this._source);
        var output = { format: format };
        var fo = this._formatOpts || {};
        if (format === 'jpeg' && typeof fo.quality === 'number') {
            output.quality = fo.quality | 0;
        }
        if (format === 'png' && typeof fo.compressionLevel === 'number') {
            output.compression = fo.compressionLevel | 0;
        }
        if (format === 'webp') {
            if (typeof fo.quality === 'number') output.quality = fo.quality | 0;
            if (fo.lossless) output.lossless = true;
        }
        // Drop the polyfill's private `_path` from the source object
        // before sending — host doesn't need it.
        var src = { kind: this._source.kind, data_b64: this._source.data_b64 };
        return { source: src, ops: this._ops, output: output };
    };

    function inferDefaultFormat(_source) {
        // Without re-decoding the source we can't know its format
        // here. PNG is the safe default since it round-trips through
        // any pipeline without quality loss.
        return 'png';
    }

    Sharp.prototype.toBuffer = function() {
        var self = this;
        return new Promise(function(resolve, reject) {
            try {
                var fn = ensureHost('__host_shadow_sharp_run');
                var pipeline = self._buildPipeline();
                var raw = fn(JSON.stringify(pipeline));
                if (isHostErr(raw)) { reject(hostErrToError(raw)); return; }
                resolve(Buffer.from(raw, 'base64'));
            } catch (e) { reject(e); }
        });
    };

    Sharp.prototype.toFile = function(path) {
        var self = this;
        return new Promise(function(resolve, reject) {
            try {
                if (typeof path !== 'string') {
                    throw new TypeError('sharp.toFile: path must be a string');
                }
                var fn = ensureHost('__host_shadow_sharp_run');
                var pipeline = self._buildPipeline();
                var raw = fn(JSON.stringify(pipeline));
                if (isHostErr(raw)) { reject(hostErrToError(raw)); return; }
                var bytes = Buffer.from(raw, 'base64');
                // fs.writeFileSync is now binary-safe (accepts Buffer).
                fs.writeFileSync(path, bytes);
                // After write, look up actual dimensions via metadata
                // path so the resolved info matches what's on disk.
                var metaFn = ensureHost('__host_shadow_sharp_metadata');
                var metaRaw = metaFn(JSON.stringify({
                    kind: 'buffer',
                    data_b64: raw,
                }));
                var info = isHostErr(metaRaw) ? {} : JSON.parse(metaRaw);
                resolve({
                    format: pipeline.output.format,
                    size: bytes.length,
                    width: info.width || 0,
                    height: info.height || 0,
                    channels: info.channels || 0,
                });
            } catch (e) { reject(e); }
        });
    };

    Sharp.prototype.metadata = function() {
        var self = this;
        return new Promise(function(resolve, reject) {
            try {
                var fn = ensureHost('__host_shadow_sharp_metadata');
                var raw = fn(JSON.stringify({
                    kind: self._source.kind,
                    data_b64: self._source.data_b64,
                }));
                if (isHostErr(raw)) { reject(hostErrToError(raw)); return; }
                resolve(JSON.parse(raw));
            } catch (e) { reject(e); }
        });
    };

    Sharp.prototype.stats = function() {
        var self = this;
        return new Promise(function(resolve, reject) {
            try {
                var fn = ensureHost('__host_shadow_sharp_stats');
                var raw = fn(JSON.stringify({
                    kind: self._source.kind,
                    data_b64: self._source.data_b64,
                }));
                if (isHostErr(raw)) { reject(hostErrToError(raw)); return; }
                resolve(JSON.parse(raw));
            } catch (e) { reject(e); }
        });
    };

    function notImplementedAsError(name) {
        var e = new Error('sharp.' + name + ' is not implemented in the burn shadow yet');
        e.code = 'ERR_SHADOW_SHARP_NOT_IMPL';
        return e;
    }

    // --- module exports --------------------------------------------

    function createSharp(input) {
        return new Sharp(input);
    }

    // Match upstream's `module.exports = sharp` shape — `sharp(input)`
    // is the entry point AND the namespace for constants.
    createSharp.cache = function() { return {}; };
    createSharp.concurrency = function() { return 1; };
    createSharp.simd = function() { return true; };
    createSharp.versions = { sharp: 'burn-shadow-1' };
    createSharp.format = {
        jpeg: { id: 'jpeg', input: { buffer: true, file: true } },
        png:  { id: 'png',  input: { buffer: true, file: true } },
        webp: { id: 'webp', input: { buffer: true, file: true } },
    };

    module.exports = createSharp;
});

// ---- shadow_sqlite3.js ----
// L3 shadow for the `sqlite3` npm package.
//
// require('sqlite3') resolves to this polyfill regardless of whether
// node_modules/sqlite3 exists; the upstream package ships a `.node`
// native addon that cannot load inside the WASM sandbox, so the
// shadow kicks in transparently and routes calls to a `rusqlite`-
// backed coordinator (see `afterburner-node-compat/src/shadows/sqlite3.rs`).
//
// API surface — matches sqlite3 v5 closely enough that real apps
// drop in without modification:
//
//   const sqlite3 = require('sqlite3');
//   const db = new sqlite3.Database(path[, mode][, cb]);
//   db.run(sql[, params][, cb]);     // INSERT/UPDATE/DELETE
//   db.get(sql[, params][, cb]);     // first row
//   db.all(sql[, params][, cb]);     // all rows
//   db.each(sql, params, rowCb, doneCb);
//   db.exec(sql[, cb]);              // multi-statement, no params
//   db.close([cb]);
//   db.serialize(fn);                // no-op (worker is already serialized)
//   db.parallelize(fn);              // no-op
//
// Parameter shapes: positional `?` and `?N`, an array, or `{':name': v}`
// (we lower the latter into a positional array for the bridge).
//
// Buffer round-trip: `Buffer` parameters are encoded as
// `{$blob_b64: '...'}`; result columns of type BLOB come back the
// same shape and are converted back to Buffer for the user.

__register_module('sqlite3', function(module, exports, require) {
    var Buffer = require('buffer').Buffer;

    // ---- host-error → JS Error -------------------------------------

    function isHostErr(s) {
        return typeof s === 'string' && s.indexOf('__HOST_ERR__:') === 0;
    }
    function hostErrToError(s, op) {
        var msg = s.slice('__HOST_ERR__:'.length);
        var err = new Error('sqlite3.' + op + ': ' + msg);
        err.code = 'SQLITE_ERROR';
        return err;
    }
    function ensureHost(name) {
        var fn = globalThis[name];
        if (typeof fn !== 'function') {
            var err = new Error('sqlite3 not available: rebuild burn with `shadow-sqlite3`');
            err.code = 'SQLITE_NO_SHADOW';
            throw err;
        }
        return fn;
    }
    function lastError() {
        if (typeof globalThis.__host_last_error === 'function') {
            return globalThis.__host_last_error() || '';
        }
        return '';
    }

    // ---- parameter normalization -----------------------------------

    function isPlainObject(o) {
        return o && typeof o === 'object' &&
               Object.getPrototypeOf(o) === Object.prototype;
    }

    // Encode one JS value into the bridge's JSON shape.
    function encodeParam(v) {
        if (v === undefined || v === null) return null;
        if (typeof v === 'boolean') return v;
        if (typeof v === 'number') {
            if (!isFinite(v)) {
                throw new TypeError('sqlite3: non-finite number');
            }
            return v;
        }
        if (typeof v === 'string') return v;
        if (Buffer.isBuffer(v)) {
            return { $blob_b64: v.toString('base64') };
        }
        if (v instanceof Uint8Array) {
            return { $blob_b64: Buffer.from(v).toString('base64') };
        }
        if (typeof v === 'bigint') {
            // SQLite's INTEGER column is 64-bit. We pass i64 through
            // the bridge, but JS Number can only safely represent up
            // to 2^53. For values beyond that, callers should use
            // string columns. Throw rather than silently lose precision.
            var n = Number(v);
            if (BigInt(n) !== v) {
                throw new RangeError(
                    'sqlite3: bigint ' + v + ' exceeds safe integer range; use TEXT column'
                );
            }
            return n;
        }
        throw new TypeError('sqlite3: unsupported param type ' + typeof v);
    }

    // Lower the user-supplied params (varargs / array / object) into
    // a plain array we can JSON-encode for the bridge.
    function normalizeParams(args) {
        if (args.length === 0) return [];
        if (args.length === 1) {
            var p = args[0];
            if (Array.isArray(p)) {
                return p.map(encodeParam);
            }
            if (isPlainObject(p)) {
                // Named-param bind — we don't translate placeholders in
                // SQL here (the host-side parser doesn't need to: SQLite
                // accepts both `?N` and `:name` in any order). Convert
                // to positional ordering by Object.values insertion order.
                return Object.values(p).map(encodeParam);
            }
            return [encodeParam(p)];
        }
        var out = [];
        for (var i = 0; i < args.length; i++) {
            out.push(encodeParam(args[i]));
        }
        return out;
    }

    // Decode a row that came back from the bridge — convert any blob
    // markers back to Buffer instances.
    function decodeRow(row) {
        if (!row || typeof row !== 'object') return row;
        var keys = Object.keys(row);
        for (var i = 0; i < keys.length; i++) {
            var v = row[keys[i]];
            if (v && typeof v === 'object' && typeof v.$blob_b64 === 'string') {
                row[keys[i]] = Buffer.from(v.$blob_b64, 'base64');
            }
        }
        return row;
    }

    // ---- callback-shape glue ---------------------------------------
    //
    // Real sqlite3 dispatches callbacks asynchronously via libuv. We
    // have no event loop, but the npm package's docs are explicit
    // that callbacks fire after the call returns — preserve that by
    // running them through `Promise.resolve().then(...)` (microtask).

    function defer(cb, err, val, thisCtx) {
        if (typeof cb !== 'function') return;
        Promise.resolve().then(function() {
            try {
                if (thisCtx !== undefined) cb.call(thisCtx, err, val);
                else cb(err, val);
            } catch (_) {
                // Swallow — Node's behavior is to report on
                // 'uncaughtException', which we don't surface here.
            }
        });
    }

    // ---- Database --------------------------------------------------

    var OPEN_READONLY = 0x00000001;
    var OPEN_READWRITE = 0x00000002;
    var OPEN_CREATE = 0x00000004;
    var OPEN_FULLMUTEX = 0x00010000;
    // We don't honor mode flags today — the host opens with
    // READWRITE | CREATE | URI by default and rusqlite's threading
    // mode is fully serialized. The constants are surfaced because
    // application code passes them and shouldn't crash.

    function Database(filename, mode, cb) {
        if (!(this instanceof Database)) return new Database(filename, mode, cb);
        if (typeof mode === 'function') { cb = mode; mode = undefined; }
        var path = String(filename || ':memory:');
        var open = ensureHost('__host_shadow_sqlite3_open');
        var id = open(path);
        // Numeric id; -1 on failure.
        this._id = id;
        this._closed = false;
        this.filename = path;
        this.open = id > 0;
        var self = this;
        if (id < 0) {
            var err = new Error('sqlite3.Database: ' + (lastError() || 'open failed'));
            err.code = 'SQLITE_CANTOPEN';
            this._openError = err;
            // Mirror npm sqlite3: emit 'error' on the next microtask
            // and call back with the error.
            defer(cb, err);
            return;
        }
        defer(cb, null);
    }

    function requireOpen(self, op) {
        if (self._openError) throw self._openError;
        if (self._closed || !(self._id > 0)) {
            var err = new Error('sqlite3.' + op + ': database is closed');
            err.code = 'SQLITE_MISUSE';
            throw err;
        }
    }

    // Pull a trailing callback off a varargs `arguments`-like array.
    function popCb(argsArray) {
        if (argsArray.length === 0) return null;
        var last = argsArray[argsArray.length - 1];
        if (typeof last === 'function') {
            argsArray.pop();
            return last;
        }
        return null;
    }

    Database.prototype.run = function(sql /* ...params, cb? */) {
        var args = Array.prototype.slice.call(arguments, 1);
        var cb = popCb(args);
        var self = this;
        var ctx;
        try {
            requireOpen(self, 'run');
            var params = normalizeParams(args);
            var fn = ensureHost('__host_shadow_sqlite3_run');
            var raw = fn(self._id, String(sql), JSON.stringify(params));
            if (isHostErr(raw)) throw hostErrToError(raw, 'run');
            var parsed = JSON.parse(raw);
            ctx = { lastID: parsed.lastID, changes: parsed.changes, sql: sql };
        } catch (e) {
            // sqlite3's run() callback signature is (err) and
            // `this` carries lastID/changes on success.
            defer(cb, e, undefined);
            return self;
        }
        defer(cb, null, undefined, ctx);
        return self;
    };

    Database.prototype.get = function(sql /* ...params, cb? */) {
        var args = Array.prototype.slice.call(arguments, 1);
        var cb = popCb(args);
        var self = this;
        try {
            requireOpen(self, 'get');
            var params = normalizeParams(args);
            var fn = ensureHost('__host_shadow_sqlite3_get');
            var raw = fn(self._id, String(sql), JSON.stringify(params));
            if (isHostErr(raw)) throw hostErrToError(raw, 'get');
            var row = JSON.parse(raw);
            if (row === null) {
                defer(cb, null, undefined);
            } else {
                defer(cb, null, decodeRow(row));
            }
        } catch (e) {
            defer(cb, e);
        }
        return self;
    };

    Database.prototype.all = function(sql /* ...params, cb? */) {
        var args = Array.prototype.slice.call(arguments, 1);
        var cb = popCb(args);
        var self = this;
        try {
            requireOpen(self, 'all');
            var params = normalizeParams(args);
            var fn = ensureHost('__host_shadow_sqlite3_all');
            var raw = fn(self._id, String(sql), JSON.stringify(params));
            if (isHostErr(raw)) throw hostErrToError(raw, 'all');
            var rows = JSON.parse(raw);
            for (var i = 0; i < rows.length; i++) decodeRow(rows[i]);
            defer(cb, null, rows);
        } catch (e) {
            defer(cb, e, []);
        }
        return self;
    };

    Database.prototype.each = function(sql /* ...params, rowCb, doneCb? */) {
        var args = Array.prototype.slice.call(arguments, 1);
        // rowCb is the second-to-last function; doneCb is the last
        // (if both are functions); otherwise the last function is rowCb.
        var doneCb = null;
        var rowCb = null;
        if (args.length && typeof args[args.length - 1] === 'function') {
            var maybeDone = args.pop();
            if (args.length && typeof args[args.length - 1] === 'function') {
                rowCb = args.pop();
                doneCb = maybeDone;
            } else {
                rowCb = maybeDone;
            }
        }
        var self = this;
        try {
            requireOpen(self, 'each');
            var params = normalizeParams(args);
            var fn = ensureHost('__host_shadow_sqlite3_all');
            var raw = fn(self._id, String(sql), JSON.stringify(params));
            if (isHostErr(raw)) throw hostErrToError(raw, 'each');
            var rows = JSON.parse(raw);
            for (var i = 0; i < rows.length; i++) {
                var row = decodeRow(rows[i]);
                if (rowCb) {
                    Promise.resolve().then(function(r) {
                        return function() { try { rowCb(null, r); } catch (_) {} };
                    }(row));
                }
            }
            if (doneCb) defer(doneCb, null, rows.length);
        } catch (e) {
            if (rowCb) defer(rowCb, e);
            if (doneCb) defer(doneCb, e, 0);
        }
        return self;
    };

    Database.prototype.exec = function(sql, cb) {
        var self = this;
        try {
            requireOpen(self, 'exec');
            var fn = ensureHost('__host_shadow_sqlite3_exec');
            var rc = fn(self._id, String(sql));
            if (rc < 0) {
                var detail = lastError() || 'exec failed';
                var err = new Error('sqlite3.exec: ' + detail);
                err.code = 'SQLITE_ERROR';
                throw err;
            }
        } catch (e) {
            defer(cb, e);
            return self;
        }
        defer(cb, null);
        return self;
    };

    Database.prototype.close = function(cb) {
        var self = this;
        if (self._closed) {
            defer(cb, null);
            return self;
        }
        self._closed = true;
        self.open = false;
        if (self._id > 0) {
            try {
                var fn = ensureHost('__host_shadow_sqlite3_close');
                fn(self._id);
            } catch (e) {
                defer(cb, e);
                return self;
            }
        }
        defer(cb, null);
        return self;
    };

    // serialize/parallelize: real sqlite3 uses these to switch between
    // serialized + parallel queueing. The shadow already serializes
    // at the worker, so they're no-ops that just invoke the optional
    // function arg synchronously.
    Database.prototype.serialize = function(fn) {
        if (typeof fn === 'function') fn.call(this);
        return this;
    };
    Database.prototype.parallelize = function(fn) {
        if (typeof fn === 'function') fn.call(this);
        return this;
    };

    // configure(option, value) — sqlite3 supports `busyTimeout` and
    // `limit`. We accept and silently ignore (no rusqlite plumbing
    // for these knobs in the minimum subset).
    Database.prototype.configure = function() { return this; };

    // Trace / profile hooks aren't surfaced — install no-op event
    // emitter shape so user code that wires `db.on('trace', ...)`
    // doesn't crash.
    Database.prototype.on = function() { return this; };
    Database.prototype.once = function() { return this; };
    Database.prototype.removeListener = function() { return this; };
    Database.prototype.off = Database.prototype.removeListener;

    // Statement-handle API (db.prepare(sql)) is intentionally not
    // implemented in the minimum subset — most call sites use the
    // inline `db.run(sql, params)` form. Surface a clear error so
    // users know to refactor (rather than getting a confusing crash).
    /// `Database.prepare(sql[, ...params][, callback])` — npm sqlite3
    /// Statement. Returns a Statement that wraps the SQL string;
    /// each invocation re-binds via the same host fns the inline
    /// `db.run / get / all / each` use. The host's rusqlite caches
    /// prepared plans by SQL text, so repeated `stmt.run(...)` calls
    /// are still cheap.
    function Statement(db, sql, initialParams) {
        if (!(this instanceof Statement)) return new Statement(db, sql, initialParams);
        this._db = db;
        this._sql = String(sql);
        this._params = (initialParams && initialParams.length) ? initialParams.slice() : [];
        this._finalized = false;
    }
    Statement.prototype.bind = function() {
        var args = _splitParamsCallback(arguments);
        this._params = args.params;
        var self = this;
        if (args.callback) Promise.resolve().then(function() { args.callback.call(self, null); });
        return this;
    };
    Statement.prototype.reset = function(cb) {
        // Host plans are cached; nothing per-statement to reset. The
        // method exists so npm sqlite3 callers don't trip.
        if (typeof cb === 'function') Promise.resolve().then(cb);
        return this;
    };
    Statement.prototype.finalize = function(cb) {
        this._finalized = true;
        if (typeof cb === 'function') Promise.resolve().then(cb);
        return this._db;
    };
    Statement.prototype.run = function() {
        if (this._finalized) throw new Error('Statement: finalized');
        var args = _splitParamsCallback(arguments);
        var params = this._params.length
            ? this._params.concat(args.params) : args.params;
        return this._db.run.apply(this._db, [this._sql].concat(params, [args.callback]));
    };
    Statement.prototype.get = function() {
        if (this._finalized) throw new Error('Statement: finalized');
        var args = _splitParamsCallback(arguments);
        var params = this._params.length
            ? this._params.concat(args.params) : args.params;
        return this._db.get.apply(this._db, [this._sql].concat(params, [args.callback]));
    };
    Statement.prototype.all = function() {
        if (this._finalized) throw new Error('Statement: finalized');
        var args = _splitParamsCallback(arguments);
        var params = this._params.length
            ? this._params.concat(args.params) : args.params;
        return this._db.all.apply(this._db, [this._sql].concat(params, [args.callback]));
    };
    Statement.prototype.each = function() {
        if (this._finalized) throw new Error('Statement: finalized');
        var args = _splitParamsCallback(arguments);
        var params = this._params.length
            ? this._params.concat(args.params) : args.params;
        return this._db.each.apply(this._db, [this._sql].concat(params, [args.callback]));
    };

    /// Split a variadic args list into `{params, callback}` matching
    /// npm sqlite3's overload shape: trailing function is the
    /// completion callback; everything else is positional or named
    /// params. Used by the Statement methods which forward to the
    /// underlying inline-form db methods.
    function _splitParamsCallback(args) {
        var arr = Array.prototype.slice.call(args);
        var cb;
        if (arr.length && typeof arr[arr.length - 1] === 'function') {
            cb = arr.pop();
        }
        // npm sqlite3 also accepts a single array: db.run(sql, [a, b])
        if (arr.length === 1 && Array.isArray(arr[0])) arr = arr[0];
        return { params: arr, callback: cb };
    }

    Database.prototype.prepare = function(sql) {
        var rest = Array.prototype.slice.call(arguments, 1);
        var args = _splitParamsCallback(rest);
        var stmt = new Statement(this, sql, args.params);
        if (args.callback) Promise.resolve().then(function() { args.callback.call(stmt, null); });
        return stmt;
    };

    // ---- Module exports --------------------------------------------

    exports.Database = Database;
    // npm sqlite3 also exposes a verbose() factory; we just return the
    // module itself since burn doesn't have separate trace levels.
    exports.verbose = function() { return exports; };

    exports.OPEN_READONLY = OPEN_READONLY;
    exports.OPEN_READWRITE = OPEN_READWRITE;
    exports.OPEN_CREATE = OPEN_CREATE;
    exports.OPEN_FULLMUTEX = OPEN_FULLMUTEX;

    // sqlite3.cached.Database mirrors upstream's connection cache.
    // We don't cache — every `new Database` opens a fresh connection.
    exports.cached = { Database: Database };
});

// ---- state.js ----
// afterburner:state — cross-invocation key/value store. Not part of
// Node's standard surface; lives under the `afterburner:` package
// namespace so it can never collide with a real Node module.
//
// Values are stored as opaque bytes by the host. JS exposes:
//   * get(key)   -> Buffer | null
//   * set(key, value)  (string | Buffer | Uint8Array)
//   * delete(key)
//   * getJSON / setJSON convenience wrappers

__register_module('afterburner:state', function(module, exports, require) {
    var Buffer = require('buffer').Buffer;

    function ensure(name) {
        var fn = globalThis['__host_state_' + name];
        if (typeof fn !== 'function') {
            throw new Error('afterburner:state.' + name + ' is not available');
        }
        return fn;
    }

    function toBytesB64(value) {
        if (value === undefined || value === null) return '';
        if (typeof value === 'string') return Buffer.from(value, 'utf8').toString('base64');
        if (Buffer.isBuffer(value))    return value.toString('base64');
        if (value instanceof Uint8Array) return Buffer.from(value).toString('base64');
        throw new TypeError('state.set: value must be string/Buffer/Uint8Array');
    }

    exports.get = function(key) {
        var raw = ensure('get')(String(key));
        if (raw === null || raw === undefined) return null;
        return Buffer.from(raw, 'base64');
    };

    exports.set = function(key, value) {
        ensure('set')(String(key), toBytesB64(value));
    };

    exports['delete'] = function(key) {
        ensure('delete')(String(key));
    };

    exports.has = function(key) {
        return exports.get(key) !== null;
    };

    // JSON helpers — the most common usage.
    exports.getJSON = function(key) {
        var b = exports.get(key);
        if (b === null) return undefined;
        try { return JSON.parse(b.toString('utf8')); } catch (e) { return undefined; }
    };
    exports.setJSON = function(key, value) {
        exports.set(key, JSON.stringify(value));
    };

    // Numeric helper for counters. Uses an atomic host-side
    // compare-and-add so concurrent thrusts can't lose updates.
    exports.increment = function(key, delta) {
        var d = (delta === undefined ? 1 : delta);
        var fn = globalThis.__host_state_increment;
        if (typeof fn === 'function') {
            return fn(String(key), d);
        }
        // Backend without atomic increment — fall back to non-atomic
        // RMW and warn the caller via a property on the returned value.
        var n = exports.getJSON(key);
        if (typeof n !== 'number') n = 0;
        n += d;
        exports.setJSON(key, n);
        return n;
    };
});

// ---- stream.js ----
// stream — Node 20 LTS streams (Readable, Writable, Duplex,
// Transform, PassThrough, pipeline, finished, compose, addAbortSignal).
// Pure JS — no host calls. Backpressure modeled with a highWaterMark
// + pending-byte counter; the actual wire-level pause/resume is
// observable through `.write()` returning false and a `'drain'` event
// firing after the pending count crosses back below HWM.

__register_module('stream', function(module, exports, require) {

    var EventEmitter = require('events');

    var DEFAULT_HWM = 16 * 1024;

    // --- Readable ---------------------------------------------------------
    //
    // Two consumption modes:
    //   * Flowing: listening for 'data' (and 'end') gets the chunks pushed
    //     synchronously as `.push(chunk)` runs.
    //   * Paused: `.read()` (no listener) buffers internally; pull when
    //     the consumer asks. We start paused; transition to flowing on
    //     the first 'data' listener.

    function Readable(opts) {
        if (!(this instanceof Readable)) return new Readable(opts);
        EventEmitter.call(this);
        this._events = this._events || Object.create(null);
        opts = opts || {};
        this._readable = true;
        this._ended = false;
        this._destroyed = false;
        this._buffer = [];
        this._highWaterMark = opts.highWaterMark || DEFAULT_HWM;
        this._read = (opts.read || function() {}).bind(this);
        this._flowing = null; // null = unset, true = flowing, false = paused
        var self = this;
        // Auto-flow on first data listener. The pump is deferred a
        // microtask so the listener is attached before _read() pushes.
        this.on('newListener', function(name) {
            if (name === 'data' && self._flowing === null) {
                self._flowing = true;
                queueMicrotask(function() { self._pump(); });
            }
        });
    }
    Readable.prototype = Object.create(EventEmitter.prototype);
    Readable.prototype.constructor = Readable;

    Readable.prototype.push = function(chunk) {
        if (chunk === null) {
            this._ended = true;
            // Flush buffered chunks before 'end'.
            this._drainBuffer();
            this.emit('end');
            this.emit('close');
            return false;
        }
        if (this._destroyed) return false;
        if (this._flowing) {
            this.emit('data', chunk);
            // Keep pulling: Node re-invokes _read() as the consumer keeps
            // up. Deferred so a synchronous multi-push _read never recurses.
            var self = this;
            queueMicrotask(function() { self._pump(); });
        } else {
            this._buffer.push(chunk);
            this.emit('readable');
        }
        return true;
    };
    // Ask the underlying source (`_read`, set via `new Readable({read})`
    // or assigned by subclasses) for more data. Re-entrancy-guarded; a
    // source that pushes nothing simply stops the flow until the next
    // explicit resume()/read().
    Readable.prototype._pump = function() {
        if (this._pumping || this._ended || this._destroyed) return;
        if (typeof this._read !== 'function') return;
        this._pumping = true;
        try {
            this._read(this._highWaterMark);
        } catch (e) {
            this.emit('error', e);
        }
        this._pumping = false;
    };
    Readable.prototype._drainBuffer = function() {
        while (this._buffer.length && this._flowing !== false) {
            this.emit('data', this._buffer.shift());
        }
    };
    Readable.prototype.read = function() {
        if (this._buffer.length === 0) {
            // Paused-mode pull: give the source a chance to fill the
            // buffer synchronously (Node calls _read here too).
            this._pump();
        }
        if (this._buffer.length === 0) return null;
        return this._buffer.shift();
    };
    Readable.prototype.pause = function() {
        this._flowing = false;
        return this;
    };
    // setEncoding(enc): emit strings instead of Buffers. Body collectors
    // (fastify's content-type parser, raw-body) call this before reading.
    Readable.prototype.setEncoding = function(enc) {
        this._encoding = enc || 'utf8';
        var self = this;
        if (!this._encodingWrapped) {
            this._encodingWrapped = true;
            var origEmit = this.emit;
            this.emit = function(name, chunk) {
                if (name === 'data' && self._encoding && chunk != null && typeof chunk !== 'string') {
                    var args = Array.prototype.slice.call(arguments);
                    args[1] = (typeof Buffer !== 'undefined' && Buffer.isBuffer(chunk))
                        ? chunk.toString(self._encoding)
                        : String(chunk);
                    return origEmit.apply(this, args);
                }
                return origEmit.apply(this, arguments);
            };
        }
        return this;
    };
    Readable.prototype.resume = function() {
        this._flowing = true;
        this._drainBuffer();
        this._pump();
        return this;
    };
    Readable.prototype.pipe = function(dest, opts) {
        opts = opts || {};
        var self = this;
        var ended = false;
        var endDest = opts.end !== false;
        this.on('data', function(chunk) {
            var ok = dest.write(chunk);
            if (!ok) self.pause();
        });
        dest.on && dest.on('drain', function() { self.resume(); });
        this.on('end', function() {
            if (ended) return;
            ended = true;
            if (endDest && typeof dest.end === 'function') dest.end();
        });
        this.on('error', function(err) {
            if (typeof dest.destroy === 'function') dest.destroy(err);
        });
        return dest;
    };
    Readable.prototype.unpipe = function(_dest) {
        // We don't track multiple pipe targets — pause() effectively
        // halts the pipe. Fine for the common single-pipe case.
        this.pause();
        return this;
    };
    Readable.prototype.destroy = function(err) {
        if (this._destroyed) return this;
        this._destroyed = true;
        this._readable = false;
        if (err) this.errored = err;
        var self = this;
        Promise.resolve().then(function() {
            if (err) self.emit('error', err);
            self.emit('close');
        });
        return this;
    };
    Object.defineProperty(Readable.prototype, 'readable', {
        get: function() { return this._readable && !this._ended && !this._destroyed; },
    });
    Object.defineProperty(Readable.prototype, 'destroyed', {
        get: function() { return this._destroyed; },
    });
    Object.defineProperty(Readable.prototype, 'readableEnded', {
        get: function() { return this._ended; },
    });

    // Async-iterator interop. Node makes Readable async-iterable.
    Readable.prototype[Symbol.asyncIterator] = function() {
        var self = this;
        var pending = [];
        var resolvers = [];
        var ended = false;
        var error = null;

        self.on('data', function(chunk) {
            if (resolvers.length) {
                var r = resolvers.shift();
                r({ value: chunk, done: false });
            } else {
                pending.push(chunk);
            }
        });
        self.on('end', function() {
            ended = true;
            while (resolvers.length) {
                resolvers.shift()({ value: undefined, done: true });
            }
        });
        self.on('error', function(e) {
            error = e;
            while (resolvers.length) {
                var r = resolvers.shift();
                r(Promise.reject(e));
            }
        });

        return {
            next: function() {
                if (error) return Promise.reject(error);
                if (pending.length) {
                    return Promise.resolve({ value: pending.shift(), done: false });
                }
                if (ended) {
                    return Promise.resolve({ value: undefined, done: true });
                }
                return new Promise(function(resolve) { resolvers.push(resolve); });
            },
            return: function() {
                self.destroy();
                return Promise.resolve({ value: undefined, done: true });
            },
        };
    };

    Readable.from = function(iterable, opts) {
        var r = new Readable(opts);
        // Sync iterable (Array, generator) — feed synchronously after a
        // microtask tick so listeners can attach.
        if (iterable && typeof iterable[Symbol.iterator] === 'function'
            && typeof iterable[Symbol.asyncIterator] !== 'function') {
            Promise.resolve().then(function() {
                try {
                    for (var v of iterable) r.push(v);
                    r.push(null);
                } catch (e) { r.destroy(e); }
            });
            return r;
        }
        // Async iterable.
        if (iterable && typeof iterable[Symbol.asyncIterator] === 'function') {
            (async function() {
                try {
                    for await (var v of iterable) r.push(v);
                    r.push(null);
                } catch (e) { r.destroy(e); }
            })();
            return r;
        }
        // Single value fallback — wrap in a one-element array.
        Promise.resolve().then(function() {
            r.push(iterable);
            r.push(null);
        });
        return r;
    };

    // --- Writable ---------------------------------------------------------
    function Writable(opts) {
        if (!(this instanceof Writable)) return new Writable(opts);
        EventEmitter.call(this);
        this._events = this._events || Object.create(null);
        opts = opts || {};
        this._writable = true;
        this._destroyed = false;
        this._ended = false;
        this._finished = false;
        this._highWaterMark = opts.highWaterMark || DEFAULT_HWM;
        this._pending = 0;
        this._writeFn = (opts.write || function(_c, _e, cb) { cb && cb(); }).bind(this);
        this._writevFn = opts.writev ? opts.writev.bind(this) : null;
        this._finalFn = opts.final ? opts.final.bind(this) : null;
    }
    Writable.prototype = Object.create(EventEmitter.prototype);
    Writable.prototype.constructor = Writable;

    Writable.prototype.write = function(chunk, encoding, cb) {
        if (typeof encoding === 'function') { cb = encoding; encoding = null; }
        if (this._destroyed || this._ended) {
            var err = new Error('write after end');
            err.code = 'ERR_STREAM_WRITE_AFTER_END';
            if (cb) Promise.resolve().then(function() { cb(err); });
            this.emit('error', err);
            return false;
        }
        var self = this;
        var size = chunkSize(chunk);
        this._pending += size;
        var underWater = this._pending < this._highWaterMark;
        this._writeFn(chunk, encoding, function(err) {
            self._pending -= size;
            if (err) {
                self.emit('error', err);
            } else if (self._pending < self._highWaterMark
                       && self._pending + size >= self._highWaterMark) {
                // Crossed back below HWM — fire 'drain'.
                self.emit('drain');
            }
            if (cb) cb(err);
        });
        return underWater;
    };
    Writable.prototype.end = function(chunk, encoding, cb) {
        if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
        if (typeof encoding === 'function') { cb = encoding; encoding = null; }
        if (chunk !== undefined && chunk !== null) this.write(chunk, encoding);
        if (this._ended) { if (cb) Promise.resolve().then(cb); return this; }
        this._ended = true;
        var self = this;
        var finish = function(err) {
            if (err) { self.emit('error', err); if (cb) cb(err); return; }
            self._finished = true;
            self.emit('finish');
            self.emit('close');
            if (cb) cb();
        };
        // Defer to a microtask so listeners attached AFTER end() (the
        // canonical Node pattern: `ws.end(chunk); ws.on('finish', …);`)
        // still observe the event. `_finalFn` and the synchronous-
        // write fast path otherwise fire 'finish' before the listener
        // is attached.
        Promise.resolve().then(function() {
            if (self._finalFn) self._finalFn(finish);
            else finish();
        });
        return this;
    };
    Writable.prototype.destroy = function(err) {
        if (this._destroyed) return this;
        this._destroyed = true;
        this._writable = false;
        if (err) this.errored = err;
        var self = this;
        Promise.resolve().then(function() {
            if (err) self.emit('error', err);
            self.emit('close');
        });
        return this;
    };
    Writable.prototype.cork = function() {};
    Writable.prototype.uncork = function() {};
    Writable.prototype.setDefaultEncoding = function() { return this; };
    Object.defineProperty(Writable.prototype, 'writable', {
        get: function() {
            return this._writable && !this._destroyed && !this._ended;
        },
    });
    Object.defineProperty(Writable.prototype, 'destroyed', {
        get: function() { return this._destroyed; },
    });
    Object.defineProperty(Writable.prototype, 'writableEnded', {
        get: function() { return this._ended; },
    });
    Object.defineProperty(Writable.prototype, 'writableFinished', {
        get: function() { return this._finished; },
    });
    Object.defineProperty(Writable.prototype, 'writableLength', {
        get: function() { return this._pending; },
    });

    function chunkSize(chunk) {
        if (chunk == null) return 0;
        if (typeof chunk === 'string') return chunk.length;
        if (chunk.length !== undefined) return chunk.length;
        return 1;
    }

    // --- Duplex (separate read + write halves) ----------------------------
    //
    // Real Duplex: read() and write() track distinct buffers + states.
    // Different from Transform, which couples them via the user
    // _transform fn.
    function Duplex(opts) {
        if (!(this instanceof Duplex)) return new Duplex(opts);
        Readable.call(this, opts);
        // Re-init Writable's state without overwriting the Readable
        // properties we just set.
        opts = opts || {};
        this._writable = true;
        this._writableEnded = false;
        this._finished = false;
        this._pending = 0;
        this._writeFn = (opts.write || function(_c, _e, cb) { cb && cb(); }).bind(this);
        this._finalFn = opts.final ? opts.final.bind(this) : null;
    }
    Duplex.prototype = Object.create(Readable.prototype);
    Duplex.prototype.constructor = Duplex;

    Duplex.prototype.write = function(chunk, encoding, cb) {
        if (typeof encoding === 'function') { cb = encoding; encoding = null; }
        if (this._destroyed || this._writableEnded) {
            var err = new Error('write after end');
            err.code = 'ERR_STREAM_WRITE_AFTER_END';
            if (cb) Promise.resolve().then(function() { cb(err); });
            return false;
        }
        var self = this;
        var size = chunkSize(chunk);
        this._pending += size;
        var underWater = this._pending < this._highWaterMark;
        this._writeFn(chunk, encoding, function(err) {
            self._pending -= size;
            if (err) self.emit('error', err);
            else if (self._pending < self._highWaterMark
                     && self._pending + size >= self._highWaterMark) {
                self.emit('drain');
            }
            if (cb) cb(err);
        });
        return underWater;
    };
    Duplex.prototype.end = Writable.prototype.end;

    // --- Transform (write transforms into push) ---------------------------
    function Transform(opts) {
        if (!(this instanceof Transform)) return new Transform(opts);
        Readable.call(this, opts);
        opts = opts || {};
        this._writable = true;
        this._writableEnded = false;
        this._transform = (opts.transform || function(c, e, cb) { cb(null, c); }).bind(this);
        this._flush = opts.flush ? opts.flush.bind(this) : null;
    }
    Transform.prototype = Object.create(Readable.prototype);
    Transform.prototype.constructor = Transform;
    Transform.prototype.write = function(chunk, encoding, cb) {
        if (typeof encoding === 'function') { cb = encoding; encoding = null; }
        if (this._destroyed) {
            if (cb) cb(new Error('Transform destroyed'));
            return false;
        }
        var self = this;
        this._transform(chunk, encoding, function(err, out) {
            if (err) { self.emit('error', err); if (cb) cb(err); return; }
            if (out !== undefined && out !== null) self.push(out);
            if (cb) cb();
        });
        return true;
    };
    Transform.prototype.end = function(chunk, encoding, cb) {
        if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
        if (typeof encoding === 'function') { cb = encoding; encoding = null; }
        var self = this;
        var doFlush = function() {
            if (self._flush) {
                self._flush(function(err, out) {
                    if (err) { self.emit('error', err); if (cb) cb(err); return; }
                    if (out !== undefined && out !== null) self.push(out);
                    self.push(null);
                    if (cb) cb();
                });
            } else {
                self.push(null);
                if (cb) cb();
            }
        };
        if (chunk !== undefined && chunk !== null) {
            this.write(chunk, encoding, function() { doFlush(); });
        } else {
            doFlush();
        }
        return this;
    };

    // --- PassThrough ------------------------------------------------------
    function PassThrough(opts) {
        if (!(this instanceof PassThrough)) return new PassThrough(opts);
        Transform.call(this, Object.assign({}, opts, {
            transform: function(c, e, cb) { cb(null, c); },
        }));
    }
    PassThrough.prototype = Object.create(Transform.prototype);
    PassThrough.prototype.constructor = PassThrough;

    // --- pipeline ---------------------------------------------------------
    //
    // Node 20 supports several stage shapes:
    //   * stream object (Readable / Writable / Duplex / Transform)
    //   * iterable / async iterable (becomes a Readable)
    //   * async generator function `(prev) => ...` (becomes a Transform)
    //
    // This polyfill handles streams + iterables; generator-fn stages
    // get wrapped with a Readable.from(asyncFn(prev)) bridge.
    function pipeline() {
        var args = Array.prototype.slice.call(arguments);
        var cb = typeof args[args.length - 1] === 'function' ? args.pop() : null;
        if (args.length < 2) {
            var err = new Error('pipeline needs at least 2 streams');
            if (cb) cb(err);
            else throw err;
            return null;
        }
        var stages = args.map(function(s, i) {
            if (s && typeof s.pipe === 'function') return s;          // Readable / Duplex
            // Writables don't have `.pipe` but accept piped data.
            if (s && typeof s.write === 'function' && typeof s.end === 'function') return s;
            // Iterable / async iterable / generator fn.
            if (typeof s === 'function') {
                // Generator function — call with previous stream.
                return s; // resolved in the loop below with prev
            }
            if (s && (typeof s[Symbol.iterator] === 'function'
                || typeof s[Symbol.asyncIterator] === 'function')) {
                return Readable.from(s);
            }
            throw new Error('pipeline: stage ' + i + ' is not a stream / iterable / function');
        });

        var prev = stages[0];
        if (typeof prev === 'function') {
            // First stage can't be a function (no upstream).
            var e = new Error('pipeline: first stage cannot be a function');
            if (cb) cb(e); else throw e;
            return null;
        }
        for (var i = 1; i < stages.length; i++) {
            var stage = stages[i];
            if (typeof stage === 'function') {
                // Wrap as Readable.from(stage(prev))
                stage = Readable.from(stage(prev));
            }
            prev = prev.pipe(stage);
        }
        var settled = false;
        prev.on('finish', function() {
            if (settled) return;
            settled = true;
            if (cb) cb(null);
        });
        prev.on('end', function() {
            if (settled) return;
            settled = true;
            if (cb) cb(null);
        });
        prev.on('error', function(err) {
            if (settled) return;
            settled = true;
            if (cb) cb(err);
        });
        return prev;
    }

    // --- finished ---------------------------------------------------------
    function finished(stream, opts, cb) {
        if (typeof opts === 'function') { cb = opts; opts = {}; }
        opts = opts || {};
        var settled = false;
        var done = function(err) {
            if (settled) return;
            settled = true;
            if (cb) cb(err || null);
        };
        if (stream.on) {
            stream.on('end', function() { done(); });
            stream.on('finish', function() { done(); });
            stream.on('close', function() { done(); });
            stream.on('error', function(e) { done(e); });
        }
    }

    // --- compose (Node 20+) -----------------------------------------------
    //
    // Returns a Duplex whose readable side is the last stage's output
    // and whose writable side feeds the first stage. Implemented by
    // running the pipeline and exposing a façade.
    function compose() {
        var args = Array.prototype.slice.call(arguments);
        if (args.length === 0) {
            throw new Error('compose: need at least one stream');
        }
        var first = args[0];
        for (var i = 1; i < args.length; i++) first = first.pipe(args[i]);
        // The composed object proxies write to the first arg, end to
        // the first arg, and forwards 'data'/'end' from the last.
        var head = args[0];
        var tail = args[args.length - 1];
        var d = new Duplex({
            write: function(chunk, encoding, cb) {
                head.write(chunk, encoding);
                if (cb) cb();
            },
            final: function(cb) { head.end(); cb(); },
        });
        tail.on('data', function(c) { d.push(c); });
        tail.on('end', function() { d.push(null); });
        tail.on('error', function(e) { d.emit('error', e); });
        return d;
    }

    // --- addAbortSignal ---------------------------------------------------
    //
    // When the signal aborts, destroy the stream with an AbortError.
    function addAbortSignal(signal, stream) {
        if (!signal) return stream;
        if (signal.aborted) {
            stream.destroy(new Error('AbortError'));
            return stream;
        }
        var listener = function() {
            stream.destroy(new Error('AbortError'));
        };
        signal.addEventListener && signal.addEventListener('abort', listener);
        return stream;
    }

    // Legacy `Stream` base class — Node's `require('stream')` returns
    // a *callable* function (the legacy `Stream` constructor) with the
    // modern subclasses + helpers attached as own properties. Real npm
    // packages depend on the dual shape: `send/index.js` does
    // `util.inherits(SendStream, Stream)`, which fails our explicit
    // `superCtor must be a function` guard if `Stream` is a plain
    // object. Keep the existing `exports` namespace populated for
    // call-sites that use `require('stream').Readable` etc.; swap
    // `module.exports` to the constructor.
    function Stream() {
        EventEmitter.call(this);
    }
    Stream.prototype = Object.create(EventEmitter.prototype);
    Stream.prototype.constructor = Stream;
    Stream.prototype.pipe = Readable.prototype.pipe;

    // ---- Node ↔ Web Streams bridge (Node 17+) ---------------------
    // `Readable.toWeb(node)` / `Readable.fromWeb(web)` etc. real
    // libs (undici, node-fetch shims, web-streams-polyfill consumers)
    // depend on these even when only one side is in active use.
    Readable.toWeb = function(nodeReadable, _opts) {
        if (typeof globalThis.ReadableStream !== 'function') {
            throw new Error('Readable.toWeb: ReadableStream unavailable');
        }
        return new globalThis.ReadableStream({
            start: function(controller) {
                nodeReadable.on('data', function(chunk) {
                    controller.enqueue(chunk);
                });
                nodeReadable.on('end', function() {
                    try { controller.close(); } catch (_) {}
                });
                nodeReadable.on('error', function(err) {
                    try { controller.error(err); } catch (_) {}
                });
            },
            cancel: function() {
                if (typeof nodeReadable.destroy === 'function') {
                    try { nodeReadable.destroy(); } catch (_) {}
                }
            },
        });
    };
    Readable.fromWeb = function(webReadable, _opts) {
        // Wrap a Web ReadableStream as a Node Readable. We pull
        // chunks via `.getReader()` and emit them as `data` events;
        // EOF closes the reader and fires `end`.
        var reader = webReadable.getReader();
        var node = Readable.from((async function* () {
            while (true) {
                var step = await reader.read();
                if (step.done) return;
                yield step.value;
            }
        })());
        return node;
    };
    /// `Writable.toWeb(node)` — wrap a Node Writable so it behaves
    /// like a WHATWG WritableStream. The web stream's `write(chunk)`
    /// pushes into the node stream and resolves on `'drain'` /
    /// completion; `close()` calls `node.end()`; `abort()` calls
    /// `node.destroy(reason)`.
    Writable.toWeb = function(nodeWritable) {
        if (typeof WritableStream !== 'function') {
            throw new Error('Writable.toWeb: WritableStream global unavailable');
        }
        return new WritableStream({
            write: function(chunk) {
                return new Promise(function(resolve, reject) {
                    var ok = nodeWritable.write(chunk, function(err) {
                        if (err) reject(err);
                    });
                    if (ok) {
                        Promise.resolve().then(resolve);
                    } else {
                        nodeWritable.once('drain', resolve);
                        nodeWritable.once('error', reject);
                    }
                });
            },
            close: function() {
                return new Promise(function(resolve, reject) {
                    nodeWritable.end(function() { resolve(); });
                    nodeWritable.once('error', reject);
                });
            },
            abort: function(reason) {
                return new Promise(function(resolve) {
                    try { nodeWritable.destroy(reason); } catch (_) {}
                    Promise.resolve().then(resolve);
                });
            },
        });
    };

    /// `Writable.fromWeb(web)` — wrap a WHATWG WritableStream as a
    /// Node Writable. Each `_write` call grabs a writer and forwards
    /// the chunk; `_final` closes; `_destroy` aborts.
    Writable.fromWeb = function(webWritable) {
        // Lock the writer once at construction so the same handle is
        // reused across writes — getWriter() throws on double-lock.
        var writer = webWritable.getWriter();
        var node = new Writable({
            write: function(chunk, enc, cb) {
                try {
                    // Coerce strings so the WritableStream sees a
                    // Uint8Array regardless of the Node-side encoding.
                    var data;
                    if (typeof chunk === 'string') {
                        data = new TextEncoder().encode(chunk);
                    } else if (chunk && chunk.buffer && chunk.byteLength != null) {
                        data = chunk;
                    } else {
                        data = new Uint8Array(chunk);
                    }
                    var p = writer.write(data);
                    if (p && typeof p.then === 'function') {
                        p.then(function() { cb(); }, cb);
                    } else {
                        cb();
                    }
                } catch (e) { cb(e); }
            },
            final: function(cb) {
                try {
                    var p = writer.close();
                    if (p && typeof p.then === 'function') {
                        p.then(function() { cb(); }, cb);
                    } else {
                        cb();
                    }
                } catch (e) { cb(e); }
            },
            destroy: function(err, cb) {
                try {
                    var p = writer.abort(err);
                    if (p && typeof p.then === 'function') {
                        p.then(function() { cb(err); }, function() { cb(err); });
                    } else {
                        cb(err);
                    }
                } catch (_) { cb(err); }
            },
        });
        return node;
    };

    /// stream.duplexPair — Node 22+. Returns `[a, b]` two Duplex
    /// streams cross-connected: writes to `a` appear on reads from
    /// `b` and vice versa. Useful for in-process protocol simulations.
    function duplexPair() {
        var a = new PassThrough();
        var b = new PassThrough();
        a.pipe(b);
        b.pipe(a);
        return [a, b];
    }

    /// `stream.isDisturbed` / `isErrored` / `isReadable` — Node 16+
    /// static probes used by undici and friends to decide whether a
    /// stream has been touched. We expose them as best-effort
    /// duck-typed checks against our internal flags so consumers don't
    /// crash on probe.
    function isDisturbed(s) {
        if (s == null) return false;
        return !!(s._readableState && (s._readableState.dataEmitted ||
            s._readableState.endEmitted || s._readableState.errored ||
            s._readableState.destroyed)) ||
            !!(s._writableState && (s._writableState.errored ||
                s._writableState.destroyed)) ||
            !!s._disturbed;
    }
    function isErrored(s) {
        if (s == null) return false;
        return !!(s.errored || (s._readableState && s._readableState.errored) ||
            (s._writableState && s._writableState.errored));
    }
    function isReadable(s) {
        if (s == null || typeof s.read !== 'function') return false;
        var rs = s._readableState;
        if (!rs) return true;
        return !rs.endEmitted && !rs.errored && !rs.destroyed;
    }
    /// `stream.getDefaultHighWaterMark(objectMode)` / `set` — Node 19.9+
    /// runtime knobs for default buffering. We track them in module
    /// state; the streams we already have are constructed before this
    /// is mutated, so the value is consultative for code that probes
    /// the runtime configuration.
    var _hwm = { byte: 16384, object: 16 };
    function getDefaultHighWaterMark(objectMode) {
        return objectMode ? _hwm.object : _hwm.byte;
    }
    function setDefaultHighWaterMark(objectMode, value) {
        var v = (value | 0);
        if (v <= 0) {
            var err = new RangeError(
                'highWaterMark must be a positive integer');
            err.code = 'ERR_OUT_OF_RANGE';
            throw err;
        }
        if (objectMode) _hwm.object = v; else _hwm.byte = v;
    }

    exports.Readable       = Readable;
    exports.Writable       = Writable;
    exports.Duplex         = Duplex;
    exports.Transform      = Transform;
    exports.PassThrough    = PassThrough;
    exports.pipeline       = pipeline;
    exports.finished       = finished;
    exports.compose        = compose;
    exports.addAbortSignal = addAbortSignal;
    exports.duplexPair     = duplexPair;
    exports.isDisturbed    = isDisturbed;
    exports.isErrored      = isErrored;
    exports.isReadable     = isReadable;
    exports.getDefaultHighWaterMark = getDefaultHighWaterMark;
    exports.setDefaultHighWaterMark = setDefaultHighWaterMark;
    exports.Stream         = Stream;
    /// stream.promises — Node 15+ Promise-shaped wrappers for
    /// pipeline / finished. Same names as `require('stream/promises')`.
    exports.promises = {
        pipeline: function() {
            var args = Array.prototype.slice.call(arguments);
            return new Promise(function(resolve, reject) {
                args.push(function(err) { if (err) reject(err); else resolve(); });
                pipeline.apply(null, args);
            });
        },
        finished: function(stream, opts) {
            return new Promise(function(resolve, reject) {
                finished(stream, opts || {}, function(err) {
                    if (err) reject(err); else resolve();
                });
            });
        },
    };

    Stream.Readable        = Readable;
    Stream.Writable        = Writable;
    Stream.Duplex          = Duplex;
    Stream.Transform       = Transform;
    Stream.PassThrough     = PassThrough;
    Stream.pipeline        = pipeline;
    Stream.finished        = finished;
    Stream.compose         = compose;
    Stream.addAbortSignal  = addAbortSignal;
    Stream.duplexPair      = duplexPair;
    Stream.isDisturbed     = isDisturbed;
    Stream.isErrored       = isErrored;
    Stream.isReadable      = isReadable;
    Stream.getDefaultHighWaterMark = getDefaultHighWaterMark;
    Stream.setDefaultHighWaterMark = setDefaultHighWaterMark;
    Stream.promises        = exports.promises;
    Stream.Stream          = Stream;

    module.exports = Stream;
});

// ---- string_decoder.js ----
// string_decoder — minimal StringDecoder with incremental UTF-8 support.
// Falls back to TextDecoder's streaming mode when available; otherwise a
// tiny hand-rolled continuation-byte buffer.

__register_module('string_decoder', function(module, exports, require) {

    function StringDecoder(encoding) {
        this.encoding = (encoding || 'utf8').toLowerCase();
        if (this.encoding !== 'utf8' && this.encoding !== 'utf-8') {
            throw new Error('StringDecoder: only utf8 is supported');
        }
        if (typeof TextDecoder === 'function') {
            this._decoder = new TextDecoder('utf-8', { fatal: false });
            this._native = true;
        } else {
            this._buffered = new Uint8Array(0);
        }
    }

    StringDecoder.prototype.write = function(chunk) {
        if (this._native) return this._decoder.decode(chunk, { stream: true });

        // Fallback: concat any leftover continuation bytes + new chunk,
        // decode complete sequences, stash the remainder.
        var full = new Uint8Array(this._buffered.length + chunk.length);
        full.set(this._buffered);
        full.set(chunk, this._buffered.length);

        // Find the largest prefix that ends on a complete code point.
        var i = full.length;
        while (i > 0) {
            var b = full[i - 1];
            if ((b & 0x80) === 0) break;                          // ASCII
            if ((b & 0xC0) === 0xC0) { i--; break; }              // start byte
            i--;                                                  // continuation
            if (full.length - i >= 4) { i = full.length; break; } // clamp
        }
        this._buffered = full.subarray(i);

        var out = '';
        for (var j = 0; j < i; j++) out += String.fromCharCode(full[j] & 0x7F);
        return out;
    };

    StringDecoder.prototype.end = function(chunk) {
        if (this._native) return this._decoder.decode(chunk || new Uint8Array(), { stream: false });
        var tail = chunk ? this.write(chunk) : '';
        return tail;
    };

    exports.StringDecoder = StringDecoder;
});

// ---- stubs.js ----
// Stubs were the parking spot for Node modules we hadn't yet
// polyfilled. Every entry that lived here used to register a Proxy
// that threw on first property access, naming the module so users
// got a clear "not supported" signal.
//
// As of the round-2 Node 20 coverage pass, every Node 20 LTS
// built-in has a real polyfill (see the matching `polyfills/<name>.js`
// file). This file is intentionally empty so the bundle order
// (alphabetical concat) doesn't clobber any real polyfill that
// sorts before `stubs.js`. Keeping the file around — instead of
// deleting it — preserves a stable hook for any future
// "intentionally not supported" module without re-introducing the
// alphabetical-clobber footgun.

// ---- timers.js ----
// timers — microtask-based scheduling + host-managed daemon timers.
//
// Phase E enabled the Javy event loop (and matching rquickjs microtask
// pump on the native side), so we can now defer work via
// `Promise.resolve().then(cb)`. That gives us proper
// `queueMicrotask`, a non-synchronous `setTimeout(fn, 0)`, and a
// working `setImmediate` — all without a wall-clock timer heap.
//
// B3 adds host-managed timers for daemon mode. When the daemon event
// loop is active, `__host_timer_set` returns a positive timer_id and
// the host fires the callback at the right time. In sandbox / library /
// UDF mode the host returns -1, and the polyfill throws — matching the
// pre-B3 contract. Detection is at call time (not at bundle-load time)
// so the Wizer snapshot stays mode-agnostic.

// Eagerly install globals at bundle load time. Scripts that never
// `require('timers')` still see `setTimeout` / `queueMicrotask` /
// friends as Web globals (both Node and browsers expose them without
// an import).
(function installTimerGlobals() {
    function _defer(fn, args) {
        Promise.resolve().then(function() { fn.apply(null, args); });
    }

    // Timer handler table — daemon mode stores callbacks here keyed by
    // host timer_id. The daemon_event dispatcher looks them up on fire.
    if (!globalThis.__ab_timer_handlers) {
        globalThis.__ab_timer_handlers = {};
    }

    function _makeHandle(id) {
        var h = { __ab_timer: true, id: id };
        h.ref = function() {
            if (id > 0 && globalThis.__host_timer_ref) globalThis.__host_timer_ref(id);
            return h;
        };
        h.unref = function() {
            if (id > 0 && globalThis.__host_timer_unref) globalThis.__host_timer_unref(id);
            return h;
        };
        return h;
    }

    // Try to register a host timer. Returns a positive id in daemon
    // mode; throws in UDF / script / sandbox mode (host returns -1).
    function _tryHostTimer(delay, repeat) {
        if (typeof globalThis.__host_timer_set !== 'function') {
            return -1;
        }
        return globalThis.__host_timer_set(delay, repeat);
    }

    function _setTimeout(fn, delay) {
        if (typeof fn !== 'function') throw new TypeError('callback must be a function');
        var args = Array.prototype.slice.call(arguments, 2);
        if (!delay || delay <= 0) {
            _defer(fn, args);
            return _makeHandle(0);
        }
        // Non-zero delay: needs host timer (daemon mode only).
        var id = _tryHostTimer(delay, 0);
        if (id <= 0) {
            throw new Error('setTimeout with a non-zero delay is not supported in this sandbox');
        }
        globalThis.__ab_timer_handlers[id] = function() {
            delete globalThis.__ab_timer_handlers[id];
            fn.apply(null, args);
        };
        return _makeHandle(id);
    }

    function _setImmediate(fn) {
        if (typeof fn !== 'function') throw new TypeError('callback must be a function');
        var args = Array.prototype.slice.call(arguments, 1);
        _defer(fn, args);
        return _makeHandle(0);
    }

    function _setInterval(fn, delay) {
        if (typeof fn !== 'function') throw new TypeError('callback must be a function');
        var args = Array.prototype.slice.call(arguments, 2);
        // Node treats delay <= 0 as 1.
        if (!delay || delay <= 0) delay = 1;
        var id = _tryHostTimer(delay, 1);
        if (id <= 0) {
            throw new Error('setInterval with a non-zero delay is not supported in this sandbox');
        }
        globalThis.__ab_timer_handlers[id] = function() {
            fn.apply(null, args);
        };
        return _makeHandle(id);
    }

    function _clearTimer(handle) {
        if (handle && handle.__ab_timer && handle.id > 0) {
            if (globalThis.__host_timer_clear) globalThis.__host_timer_clear(handle.id);
            if (globalThis.__ab_timer_handlers) delete globalThis.__ab_timer_handlers[handle.id];
        }
    }
    function _noop() {}

    if (typeof globalThis.setTimeout !== 'function') globalThis.setTimeout = _setTimeout;
    if (typeof globalThis.setImmediate !== 'function') globalThis.setImmediate = _setImmediate;
    if (typeof globalThis.setInterval !== 'function') globalThis.setInterval = _setInterval;
    if (typeof globalThis.clearTimeout !== 'function') globalThis.clearTimeout = _clearTimer;
    if (typeof globalThis.clearImmediate !== 'function') globalThis.clearImmediate = _noop;
    if (typeof globalThis.clearInterval !== 'function') globalThis.clearInterval = _clearTimer;
    if (typeof globalThis.queueMicrotask !== 'function') {
        globalThis.queueMicrotask = function(fn) {
            if (typeof fn !== 'function') throw new TypeError('callback must be a function');
            Promise.resolve().then(fn);
        };
    }
})();

__register_module('timers', function(module, exports, require) {

    function asyncNotSupported(api) {
        return new Error(api + ' with a non-zero delay is not supported in this sandbox');
    }

    function defer(fn, args) {
        Promise.resolve().then(function() { fn.apply(null, args); });
    }

    function makeHandle(id) {
        var h = { __ab_timer: true, id: id };
        h.ref = function() {
            if (id > 0 && globalThis.__host_timer_ref) globalThis.__host_timer_ref(id);
            return h;
        };
        h.unref = function() {
            if (id > 0 && globalThis.__host_timer_unref) globalThis.__host_timer_unref(id);
            return h;
        };
        return h;
    }

    function tryHostTimer(delay, repeat) {
        if (typeof globalThis.__host_timer_set !== 'function') return -1;
        return globalThis.__host_timer_set(delay, repeat);
    }

    function queueMicrotaskImpl(fn) {
        if (typeof fn !== 'function') throw new TypeError('callback must be a function');
        defer(fn, []);
    }

    function setTimeoutImpl(fn, delay) {
        if (typeof fn !== 'function') throw new TypeError('callback must be a function');
        var args = Array.prototype.slice.call(arguments, 2);
        if (!delay || delay <= 0) {
            defer(fn, args);
            return makeHandle(0);
        }
        var id = tryHostTimer(delay, 0);
        if (id <= 0) throw asyncNotSupported('setTimeout');
        globalThis.__ab_timer_handlers[id] = function() {
            delete globalThis.__ab_timer_handlers[id];
            fn.apply(null, args);
        };
        return makeHandle(id);
    }

    function setImmediateImpl(fn) {
        if (typeof fn !== 'function') throw new TypeError('callback must be a function');
        var args = Array.prototype.slice.call(arguments, 1);
        defer(fn, args);
        return makeHandle(0);
    }

    function setIntervalImpl(fn, delay) {
        if (typeof fn !== 'function') throw new TypeError('callback must be a function');
        var args = Array.prototype.slice.call(arguments, 2);
        if (!delay || delay <= 0) delay = 1;
        var id = tryHostTimer(delay, 1);
        if (id <= 0) throw asyncNotSupported('setInterval');
        globalThis.__ab_timer_handlers[id] = function() {
            fn.apply(null, args);
        };
        return makeHandle(id);
    }

    function clearTimerImpl(handle) {
        if (handle && handle.__ab_timer && handle.id > 0) {
            if (globalThis.__host_timer_clear) globalThis.__host_timer_clear(handle.id);
            if (globalThis.__ab_timer_handlers) delete globalThis.__ab_timer_handlers[handle.id];
        }
    }

    function noop() { /* nothing to clear — microtasks can't be cancelled */ }

    exports.setTimeout = setTimeoutImpl;
    exports.setImmediate = setImmediateImpl;
    exports.setInterval = setIntervalImpl;
    exports.clearTimeout = clearTimerImpl;
    exports.clearImmediate = noop;
    exports.clearInterval = clearTimerImpl;
    exports.queueMicrotask = queueMicrotaskImpl;

    // Install as globals so scripts that don't `require('timers')` still
    // see the same behavior.
    if (typeof globalThis.setTimeout !== 'function') globalThis.setTimeout = setTimeoutImpl;
    if (typeof globalThis.setImmediate !== 'function') globalThis.setImmediate = setImmediateImpl;
    if (typeof globalThis.setInterval !== 'function') globalThis.setInterval = setIntervalImpl;
    if (typeof globalThis.clearTimeout !== 'function') globalThis.clearTimeout = clearTimerImpl;
    if (typeof globalThis.clearImmediate !== 'function') globalThis.clearImmediate = noop;
    if (typeof globalThis.clearInterval !== 'function') globalThis.clearInterval = clearTimerImpl;
    if (typeof globalThis.queueMicrotask !== 'function') globalThis.queueMicrotask = queueMicrotaskImpl;
});

// ---- tls.js ----
// tls — raw TLS polyfill (B7).
//
// Layered on top of the same daemon-event plumbing as `net.js`: a JS
// `TLSSocket` is the façade, the host owns the `tokio_rustls`
// `TlsStream`, and lifecycle events arrive as `{kind: "tls-..."}`
// envelopes routed through `__ab_tls_handlers` and
// `__ab_tls_server_handlers`.
//
// API coverage (minimum-viable for real DB / API drivers):
//
//   tls.connect(opts[, listener])
//     opts: {host, port, servername?, rejectUnauthorized?, ca?,
//            ALPNProtocols?}
//   tls.connect(port, host[, opts][, listener])
//   socket.{write, end, destroy, on('secureConnect'|'data'|'end'|
//           'close'|'error'|'drain'), authorized, authorizationError,
//           getProtocol, alpnProtocol, encrypted}
//   tls.createServer(opts[, connectionListener])
//     opts: {cert, key} — PEM strings
//   server.{listen, close, address, on('listening'|'secureConnection'|
//           'close'|'error')}
//
// Deferred (will throw a clear error if used):
//   - PSK / client certificate auth
//   - tls.checkServerIdentity hook (rustls handles standard hostname
//     verification automatically when rejectUnauthorized is true)
//   - DTLS / OpenSSL-specific knobs (secureProtocol, ciphers list,
//     ECDH curve picks)
//
// SNI multi-cert routing is supported via tls.createSecureContext
// + Server#addContext / { serverContexts: { '*.example.com': ctx } }.

(function bootstrapTlsGlobals() {
    if (!globalThis.__ab_tls_handlers) globalThis.__ab_tls_handlers = {};
    if (!globalThis.__ab_tls_server_handlers) globalThis.__ab_tls_server_handlers = {};
})();

__register_module('tls', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;
    var Buffer = require('buffer').Buffer;
    var net = require('net');

    // ----- error mapping --------------------------------------------

    function mapHostErrorCode(rc) {
        switch (rc) {
            case -1: return 'ENO_DAEMON';
            case -2: return 'EACCES';
            case -3: return 'ENOTFOUND';
            case -4: return 'EINVAL';
            case -5: return 'EINVAL';
            case -6: return 'EINVAL';
            case -7: return 'ERR_TLS_INVALID_CERT';
            default: return 'EOTHER';
        }
    }

    function makeError(rc, prefix) {
        var detail = '';
        if (typeof globalThis.__host_last_error === 'function') {
            detail = globalThis.__host_last_error();
        }
        var code = mapHostErrorCode(rc);
        var e = new Error(prefix + ': ' + (detail || ('rc=' + rc)));
        e.code = code;
        return e;
    }

    // ----- TLSSocket -------------------------------------------------
    //
    // Shaped like `net.Socket` but the connection it stands in for
    // is a TLS stream. We don't extend `net.Socket` — the polyfill
    // owns a dedicated host id space (__host_tls_*), so re-using
    // net.Socket would risk crossed wires on the registry side.

    function TLSSocket(opts) {
        if (!(this instanceof TLSSocket)) return new TLSSocket(opts);
        EventEmitter.call(this);
        opts = opts || {};

        this._connId = 0;
        this._connecting = false;
        this._destroyed = false;
        this._closeEmitted = false;
        this._readable = true;
        this._writable = true;
        this._encoding = null;        // null = emit Buffer; set via setEncoding
        this._wantsDrain = false;
        this._pendingHWM = 64 * 1024;
        this.bytesRead = 0;
        this.bytesWritten = 0;
        this.encrypted = true;
        this.authorized = false;
        this.authorizationError = null;
        this.alpnProtocol = null;
        this._protocol = null;
        this.remoteAddress = undefined;
        this.remotePort = undefined;
        this.remoteFamily = undefined;
        this.localAddress = undefined;
        this.localPort = undefined;
        this.readyState = 'opening';
    }
    TLSSocket.prototype = Object.create(EventEmitter.prototype);
    TLSSocket.prototype.constructor = TLSSocket;

    TLSSocket.prototype._attach = function(connId) {
        if (this._connId) {
            throw new Error('tls.TLSSocket already attached to conn ' + this._connId);
        }
        this._connId = connId | 0;
        globalThis.__ab_tls_handlers[this._connId] = this;
    };

    TLSSocket.prototype._dispatchSecureConnect = function(
        local, remote, alpn, protocol, authorized, cipher, certChainB64
    ) {
        this._connecting = false;
        this.readyState = 'open';
        this.localAddress = local && local.address;
        this.localPort = local && local.port;
        this.remoteAddress = remote && remote.address;
        this.remotePort = remote && remote.port;
        this.remoteFamily = remote && remote.family;
        this.alpnProtocol = alpn || null;
        this._protocol = protocol || null;
        this._cipher = cipher || null;
        this._peerCertChainB64 = Array.isArray(certChainB64) ? certChainB64 : [];
        this.authorized = !!authorized;
        if (!this.authorized) {
            this.authorizationError = new Error(
                'TLS verification skipped (rejectUnauthorized: false)'
            );
            this.authorizationError.code = 'ERR_TLS_CERT_ALTNAME_INVALID';
        }
        try { this.emit('secureConnect'); } catch (_) {}
        // Node fires 'connect' before 'secureConnect' for the legacy
        // path; we collapse them into one and emit both for callers
        // that listen only to 'connect'.
        try { this.emit('connect'); } catch (_) {}
        try { this.emit('ready'); } catch (_) {}
    };

    TLSSocket.prototype._dispatchData = function(payloadB64) {
        if (this._destroyed || !this._readable) return;
        var bytes;
        try { bytes = Buffer.from(payloadB64, 'base64'); }
        catch (_) { return; }
        this.bytesRead += bytes.length;
        // Honour `setEncoding`: emit decoded string when an encoding is
        // configured; Buffer otherwise.
        var chunk = this._encoding ? bytes.toString(this._encoding) : bytes;
        try { this.emit('data', chunk); } catch (_) {}
    };

    TLSSocket.prototype._dispatchEnd = function() {
        if (!this._readable) return;
        this._readable = false;
        this.readyState = this._writable ? 'writeOnly' : 'closed';
        try { this.emit('end'); } catch (_) {}
    };

    TLSSocket.prototype._dispatchDrain = function() {
        if (!this._wantsDrain) return;
        this._wantsDrain = false;
        try { this.emit('drain'); } catch (_) {}
    };

    TLSSocket.prototype._dispatchError = function(message, code) {
        var e = new Error(message || 'tls error');
        e.code = code || 'EOTHER';
        try { this.emit('error', e); } catch (_) {}
    };

    TLSSocket.prototype._dispatchClose = function(hadError) {
        if (this._closeEmitted) return;
        this._closeEmitted = true;
        this._destroyed = true;
        this._readable = false;
        this._writable = false;
        this.readyState = 'closed';
        try { this.emit('close', !!hadError); } catch (_) {}
        if (this._connId) {
            delete globalThis.__ab_tls_handlers[this._connId];
        }
    };

    TLSSocket.prototype.connect = function(opts) {
        var port = opts.port | 0;
        var host = opts.host || '127.0.0.1';
        if (!port || port < 1 || port > 65535) {
            throw new RangeError('tls.connect: port out of range: ' + opts.port);
        }
        // `rejectUnauthorized` defaults to true (Node-compat). Only an
        // explicit `false` opts out.
        var hostOpts = {
            rejectUnauthorized: opts.rejectUnauthorized === false ? false : true,
            servername: typeof opts.servername === 'string' ? opts.servername : '',
            alpn: Array.isArray(opts.ALPNProtocols)
                ? opts.ALPNProtocols.map(function(p) { return String(p); })
                : [],
            ca: typeof opts.ca === 'string' ? opts.ca :
                Buffer.isBuffer(opts.ca) ? opts.ca.toString('utf8') : ''
        };
        this._connecting = true;
        this.readyState = 'opening';
        var rc = globalThis.__host_tls_connect(
            String(host),
            port,
            JSON.stringify(hostOpts)
        );
        if (rc < 0) {
            var err = makeError(rc, 'tls.connect');
            var self = this;
            Promise.resolve().then(function() {
                self._connecting = false;
                self._destroyed = true;
                self.readyState = 'closed';
                try { self.emit('error', err); } catch (_) {}
                try { self.emit('close', true); } catch (_) {}
            });
            return this;
        }
        this._attach(rc);
        return this;
    };

    TLSSocket.prototype.write = function(data, encoding, cb) {
        if (this._destroyed || !this._writable) {
            if (cb) Promise.resolve().then(function() { cb(new Error('not writable')); });
            return false;
        }
        if (typeof encoding === 'function') { cb = encoding; encoding = undefined; }

        var b64;
        if (Buffer.isBuffer(data)) {
            b64 = data.toString('base64');
        } else if (typeof data === 'string') {
            b64 = Buffer.from(data, encoding || 'utf8').toString('base64');
        } else if (data instanceof Uint8Array) {
            b64 = Buffer.from(data).toString('base64');
        } else {
            throw new TypeError('tls.TLSSocket.write: unsupported chunk type ' + typeof data);
        }

        var rc = globalThis.__host_tls_write(this._connId, b64);
        if (rc < 0) {
            var err = makeError(rc, 'tls.write');
            if (cb) cb(err);
            try { this.emit('error', err); } catch (_) {}
            return false;
        }
        var n = Buffer.isBuffer(data) ? data.length :
                (typeof data === 'string' ? Buffer.byteLength(data, encoding || 'utf8') :
                 (data && data.length) || 0);
        this.bytesWritten += n;
        if (cb) Promise.resolve().then(cb);

        var pending = globalThis.__host_tls_pending(this._connId) | 0;
        if (pending >= this._pendingHWM) {
            this._wantsDrain = true;
            return false;
        }
        return true;
    };

    TLSSocket.prototype.end = function(data, encoding, cb) {
        if (typeof data === 'function') { cb = data; data = undefined; encoding = undefined; }
        else if (typeof encoding === 'function') { cb = encoding; encoding = undefined; }
        if (data !== undefined && data !== null) {
            this.write(data, encoding);
        }
        this._writable = false;
        if (this._connId && !this._destroyed) {
            globalThis.__host_tls_end(this._connId);
        }
        if (cb) this.once('close', cb);
        return this;
    };

    TLSSocket.prototype.destroy = function(err) {
        if (this._destroyed) return this;
        this._destroyed = true;
        this._readable = false;
        this._writable = false;
        if (this._connId) {
            globalThis.__host_tls_destroy(this._connId);
        }
        if (err) {
            try { this.emit('error', err); } catch (_) {}
        }
        return this;
    };

    // setNoDelay / setKeepAlive aren't surfaced — tls owns the
    // underlying TcpStream and applying them after the handshake is
    // a niche use case. Accept-and-no-op stubs to match Node's lax
    // duck-typing.
    TLSSocket.prototype.setNoDelay = function() { return this; };
    TLSSocket.prototype.setKeepAlive = function() { return this; };
    TLSSocket.prototype.setTimeout = function() { return this; };
    TLSSocket.prototype.pause = function() { return this; };
    TLSSocket.prototype.resume = function() { return this; };
    TLSSocket.prototype.ref = function() { return this; };
    TLSSocket.prototype.unref = function() { return this; };
    TLSSocket.prototype.setEncoding = function(encoding) {
        if (encoding == null) {
            this._encoding = null;
            return this;
        }
        Buffer.from('').toString(encoding);
        this._encoding = encoding;
        return this;
    };

    TLSSocket.prototype.address = function() {
        if (!this.localAddress) return {};
        return {
            address: this.localAddress,
            family: this.remoteFamily ||
                    (String(this.localAddress || '').indexOf(':') >= 0 ? 'IPv6' : 'IPv4'),
            port: this.localPort,
        };
    };

    TLSSocket.prototype.getProtocol = function() {
        return this._protocol;
    };

    TLSSocket.prototype.getCipher = function() {
        // The IANA cipher-suite name comes from rustls'
        // `negotiated_cipher_suite()` and is the same string Node's
        // `getCipher()` returns for `name` / `standardName`.
        var name = this._cipher || 'unknown';
        return {
            name: name,
            standardName: name,
            version: this._protocol || '',
        };
    };

    /// Return the leaf peer certificate, shaped close enough to Node
    /// for the common assertions:
    ///   { raw: Buffer, fingerprint256: '...' }
    /// Subject/issuer parsing requires full ASN.1 decoding; the
    /// minimum subset doesn't include it — callers needing those
    /// fields can parse `raw` themselves.
    TLSSocket.prototype.getPeerCertificate = function(detailed) {
        var chain = this._peerCertChainB64 || [];
        if (chain.length === 0) return {};
        var raw = Buffer.from(chain[0], 'base64');
        var cert = {
            raw: raw,
            fingerprint256: sha256Fingerprint(raw),
            subject: {},
            issuer: {},
            valid_from: '',
            valid_to: '',
        };
        if (detailed && chain.length > 1) {
            cert.issuerCertificate = (function makeIssuer(rest) {
                if (rest.length === 0) return undefined;
                var rawIssuer = Buffer.from(rest[0], 'base64');
                return {
                    raw: rawIssuer,
                    fingerprint256: sha256Fingerprint(rawIssuer),
                    subject: {},
                    issuer: {},
                    issuerCertificate: makeIssuer(rest.slice(1)),
                };
            })(chain.slice(1));
        }
        return cert;
    };

    /// Return the entire leaf-first peer certificate chain as an
    /// array of `{raw, fingerprint256}` objects. Convenient when
    /// callers need to walk every cert; mirrors Node's `getPeerX509Certificate()`
    /// shape.
    TLSSocket.prototype.getPeerCertChain = function() {
        var chain = this._peerCertChainB64 || [];
        return chain.map(function(b64) {
            var raw = Buffer.from(b64, 'base64');
            return { raw: raw, fingerprint256: sha256Fingerprint(raw) };
        });
    };

    function sha256Fingerprint(buf) {
        // Node returns colon-separated uppercase hex (`AA:BB:...`).
        // We prefer this format because real-world certificate
        // pinning code matches it byte-for-byte.
        try {
            var crypto = require('crypto');
            var hash = crypto.createHash('sha256').update(buf).digest('hex');
            var out = [];
            for (var i = 0; i < hash.length; i += 2) {
                out.push(hash.slice(i, i + 2).toUpperCase());
            }
            return out.join(':');
        } catch (_) {
            return '';
        }
    }

    Object.defineProperty(TLSSocket.prototype, 'destroyed', {
        get: function() { return this._destroyed; },
    });
    Object.defineProperty(TLSSocket.prototype, 'connecting', {
        get: function() { return this._connecting; },
    });
    Object.defineProperty(TLSSocket.prototype, 'readable', {
        get: function() { return this._readable; },
    });
    Object.defineProperty(TLSSocket.prototype, 'writable', {
        get: function() { return this._writable; },
    });
    Object.defineProperty(TLSSocket.prototype, 'pending', {
        get: function() {
            if (!this._connId) return 0;
            return globalThis.__host_tls_pending(this._connId) | 0;
        },
    });

    // ----- Server ----------------------------------------------------

    function _pemFromOpt(v) {
        if (typeof v === 'string') return v;
        if (Buffer.isBuffer(v)) return v.toString('utf8');
        if (Array.isArray(v) && v.length && (typeof v[0] === 'string' || Buffer.isBuffer(v[0]))) {
            return _pemFromOpt(v[0]);
        }
        return '';
    }

    function createSecureContext(opts) {
        opts = opts || {};
        var cert = _pemFromOpt(opts.cert);
        var key = _pemFromOpt(opts.key);
        if (!cert || !key) {
            throw new Error('tls.createSecureContext: `cert` and `key` (PEM) are required');
        }
        return { context: { __isSecureContext: true, cert: cert, key: key } };
    }

    function Server(opts, secureConnectionListener) {
        if (!(this instanceof Server)) return new Server(opts, secureConnectionListener);
        EventEmitter.call(this);
        if (typeof opts === 'function') {
            secureConnectionListener = opts;
            opts = {};
        }
        opts = opts || {};
        this._cert = _pemFromOpt(opts.cert);
        this._key = _pemFromOpt(opts.key);
        if (!this._cert || !this._key) {
            throw new Error('tls.createServer: `cert` and `key` (PEM) are required');
        }
        this._sniContexts = Object.create(null);
        if (opts.serverContexts && typeof opts.serverContexts === 'object') {
            for (var sn in opts.serverContexts) {
                if (Object.prototype.hasOwnProperty.call(opts.serverContexts, sn)) {
                    var sc = opts.serverContexts[sn];
                    var c, k;
                    if (sc && sc.context && sc.context.__isSecureContext) {
                        c = sc.context.cert; k = sc.context.key;
                    } else if (sc && typeof sc === 'object') {
                        c = _pemFromOpt(sc.cert); k = _pemFromOpt(sc.key);
                    }
                    if (c && k) this._sniContexts[String(sn)] = { cert: c, key: k };
                }
            }
        }
        this._serverId = 0;
        this._listening = false;
        this._closed = false;
        this._port = 0;
        this._host = '';
        this._connections = new Set();
        if (secureConnectionListener) this.on('secureConnection', secureConnectionListener);
    }
    Server.prototype = Object.create(EventEmitter.prototype);
    Server.prototype.constructor = Server;

    Server.prototype.addContext = function(servername, context) {
        if (typeof servername !== 'string' || !servername) {
            throw new TypeError('tls.Server#addContext: servername must be a non-empty string');
        }
        var c, k;
        if (context && context.context && context.context.__isSecureContext) {
            c = context.context.cert; k = context.context.key;
        } else if (context && typeof context === 'object') {
            c = _pemFromOpt(context.cert); k = _pemFromOpt(context.key);
        }
        if (!c || !k) {
            throw new Error('tls.Server#addContext: context must include cert and key');
        }
        this._sniContexts[servername] = { cert: c, key: k };
        return this;
    };

    Server.prototype.listen = function() {
        var args = Array.prototype.slice.call(arguments);
        var cb;
        if (args.length && typeof args[args.length - 1] === 'function') {
            cb = args.pop();
        }
        var opts;
        if (args.length === 1 && typeof args[0] === 'object' && args[0]) {
            opts = args[0];
        } else if (args.length === 0) {
            opts = { port: 0 };
        } else {
            opts = { port: args[0], host: args[1] };
        }
        var port = opts.port | 0;
        var host = opts.host || '0.0.0.0';
        if (port < 0 || port > 65535) {
            throw new RangeError('tls.listen: port out of range: ' + opts.port);
        }
        var sniArr = [];
        for (var sn in this._sniContexts) {
            if (Object.prototype.hasOwnProperty.call(this._sniContexts, sn)) {
                sniArr.push({
                    servername: sn,
                    cert: this._sniContexts[sn].cert,
                    key: this._sniContexts[sn].key,
                });
            }
        }
        var sniJson = sniArr.length ? JSON.stringify(sniArr) : '';
        var rc = globalThis.__host_tls_listen(
            String(host), port, this._cert, this._key, sniJson
        );
        if (rc < 0) {
            var err = makeError(rc, 'tls.listen');
            var self = this;
            Promise.resolve().then(function() {
                try { self.emit('error', err); } catch (_) {}
            });
            return this;
        }
        this._serverId = rc | 0;
        this._port = port;
        this._host = host;
        globalThis.__ab_tls_server_handlers[this._serverId] = this;
        if (cb) this.once('listening', cb);
        return this;
    };

    Server.prototype.address = function() {
        if (!this._listening) return null;
        return {
            address: this._host,
            family: this._host.indexOf(':') >= 0 ? 'IPv6' : 'IPv4',
            port: this._port,
        };
    };

    Server.prototype.close = function(cb) {
        if (this._closed) {
            if (cb) Promise.resolve().then(function() { cb(); });
            return this;
        }
        this._closed = true;
        if (this._serverId) {
            globalThis.__host_tls_close_server(this._serverId);
            delete globalThis.__ab_tls_server_handlers[this._serverId];
        }
        var self = this;
        Promise.resolve().then(function() {
            self._listening = false;
            try { self.emit('close'); } catch (_) {}
            if (cb) cb();
        });
        return this;
    };

    Server.prototype.getConnections = function(cb) {
        var n = this._connections.size;
        Promise.resolve().then(function() { cb(null, n); });
        return this;
    };

    Server.prototype.ref = function() { return this; };
    Server.prototype.unref = function() { return this; };

    Server.prototype._dispatchListening = function(port) {
        this._listening = true;
        this._port = (port | 0) || this._port;
        try { this.emit('listening'); } catch (_) {}
    };

    Server.prototype._dispatchConnection = function(
        connId, local, remote, alpn, protocol, cipher, certChainB64
    ) {
        var sock = new TLSSocket();
        sock._attach(connId | 0);
        sock._connecting = false;
        sock.readyState = 'open';
        sock.localAddress = local && local.address;
        sock.localPort = local && local.port;
        sock.remoteAddress = remote && remote.address;
        sock.remotePort = remote && remote.port;
        sock.remoteFamily = remote && remote.family;
        sock.alpnProtocol = alpn || null;
        sock._protocol = protocol || null;
        sock._cipher = cipher || null;
        sock._peerCertChainB64 = Array.isArray(certChainB64) ? certChainB64 : [];
        sock.authorized = false; // server side never verifies client by default
        var self = this;
        this._connections.add(sock);
        sock.once('close', function() { self._connections.delete(sock); });
        try { this.emit('secureConnection', sock); } catch (_) {}
        // Node also emits 'connection' (the legacy raw-TCP-layer event)
        // — keep that for callers that just listen to 'connection'.
        try { this.emit('connection', sock); } catch (_) {}
    };

    Server.prototype._dispatchServerError = function(message) {
        var err = new Error(message || 'tls.Server error');
        err.code = 'EOTHER';
        try { this.emit('error', err); } catch (_) {}
    };

    Object.defineProperty(Server.prototype, 'listening', {
        get: function() { return this._listening; },
    });

    // ----- Top-level helpers -----------------------------------------

    function connect() {
        var args = Array.prototype.slice.call(arguments);
        var cb;
        if (args.length && typeof args[args.length - 1] === 'function') {
            cb = args.pop();
        }
        var opts;
        if (args.length === 1 && typeof args[0] === 'object' && args[0]) {
            opts = args[0];
        } else if (args.length >= 2 && typeof args[1] === 'string') {
            // (port, host[, opts])
            opts = Object.assign({}, args[2] || {}, { port: args[0], host: args[1] });
        } else {
            opts = { port: args[0] };
        }
        var s = new TLSSocket();
        if (cb) s.once('secureConnect', cb);
        return s.connect(opts);
    }

    function createServer(opts, listener) {
        return new Server(opts, listener);
    }

    exports.TLSSocket = TLSSocket;
    exports.Server = Server;
    exports.connect = connect;
    exports.createServer = createServer;
    exports.createSecureContext = createSecureContext;
    exports.SecureContext = function SecureContext() {};
    // Re-export net's IP helpers so callers can do `tls.isIP`.
    exports.isIP = net.isIP;
    exports.isIPv4 = net.isIPv4;
    exports.isIPv6 = net.isIPv6;
    // Stable defaults — Node exposes these but burn doesn't gate on them.
    exports.DEFAULT_MIN_VERSION = 'TLSv1.2';
    exports.DEFAULT_MAX_VERSION = 'TLSv1.3';
    /// `tls.DEFAULT_ECDH_CURVE` (Node 8+) — preferred curve list. We
    /// don't gate on this; Node defaults to 'auto'.
    exports.DEFAULT_ECDH_CURVE = 'auto';
    /// `tls.DEFAULT_CIPHERS` — Node's default OpenSSL cipher string.
    /// We surface the canonical Node 18+ default for libraries that
    /// echo it back (axios bundle reporting, oncall debugging).
    exports.DEFAULT_CIPHERS = [
        'TLS_AES_256_GCM_SHA384',
        'TLS_CHACHA20_POLY1305_SHA256',
        'TLS_AES_128_GCM_SHA256',
        'ECDHE-RSA-AES128-GCM-SHA256',
        'ECDHE-ECDSA-AES128-GCM-SHA256',
        'ECDHE-RSA-AES256-GCM-SHA384',
        'ECDHE-ECDSA-AES256-GCM-SHA384',
        'DHE-RSA-AES128-GCM-SHA256',
        'ECDHE-RSA-AES128-SHA256',
        'DHE-RSA-AES128-SHA256',
        'ECDHE-RSA-AES256-SHA384',
        'DHE-RSA-AES256-SHA384',
        'ECDHE-RSA-AES256-SHA256',
        'DHE-RSA-AES256-SHA256',
        'HIGH',
        '!aNULL',
        '!eNULL',
        '!EXPORT',
        '!DES',
        '!RC4',
        '!MD5',
        '!PSK',
        '!SRP',
        '!CAMELLIA',
    ].join(':');
    /// Renegotiation guards — Node has had these since 0.6 to defend
    /// against CVE-2009-3555. We surface the values and accept them as
    /// configured but our TCP/TLS layer doesn't expose renegotiation,
    /// so they're informational.
    exports.CLIENT_RENEG_LIMIT = 3;
    exports.CLIENT_RENEG_WINDOW = 600;

    /// tls.checkServerIdentity(hostname, cert) — verify a peer
    /// certificate matches the requested hostname. Real impl walks
    /// `cert.subjectaltname` for `DNS:` entries and compares against
    /// the hostname (with leading-`*` wildcards collapsed). Returns
    /// `undefined` on match, an `Error` instance on mismatch.
    exports.checkServerIdentity = function(hostname, cert) {
        if (!cert) {
            var err = new Error('tls.checkServerIdentity: cert is required');
            err.code = 'ERR_TLS_CERT_ALTNAME_INVALID';
            return err;
        }
        var host = String(hostname || '').toLowerCase();
        var altNames = [];
        if (typeof cert.subjectaltname === 'string') {
            // Parse "DNS:foo, DNS:bar, IP Address:1.2.3.4" pairs.
            var parts = cert.subjectaltname.split(/,\s*/);
            for (var i = 0; i < parts.length; i++) {
                var p = parts[i].split(':');
                if (p.length === 2 && p[0].trim().toLowerCase() === 'dns') {
                    altNames.push(p[1].trim().toLowerCase());
                }
            }
        }
        if (cert.subject && typeof cert.subject.CN === 'string' && altNames.length === 0) {
            altNames.push(String(cert.subject.CN).toLowerCase());
        }
        for (var j = 0; j < altNames.length; j++) {
            var name = altNames[j];
            if (name === host) return undefined;
            // Wildcard match: `*.example.com` matches `foo.example.com`
            // but NOT `foo.bar.example.com` (single label).
            if (name.indexOf('*.') === 0) {
                var suffix = name.slice(1); // ".example.com"
                if (host.length > suffix.length && host.endsWith(suffix)) {
                    var labelEnd = host.length - suffix.length;
                    if (host.indexOf('.', 0) >= labelEnd || host.indexOf('.', 0) === labelEnd) {
                        return undefined;
                    }
                    if (host.indexOf('.') === labelEnd) return undefined;
                }
            }
        }
        var error = new Error("Hostname/IP does not match certificate's altnames: Host: "
            + host + ". is not in the cert's altnames: " + altNames.join(', '));
        error.code = 'ERR_TLS_CERT_ALTNAME_INVALID';
        error.host = host;
        error.cert = cert;
        return error;
    };

    // ---- tls.rootCertificates / getCACertificates (Node 12 / 24) ----
    //
    // The host TLS layer (rustls / webpki-roots) owns the actual root
    // store; we don't surface PEM strings out of it (that crosses the
    // sandbox boundary for what's effectively read-only metadata).
    // The arrays are populated lazily on first access and cached.
    var _rootCerts = null;
    Object.defineProperty(exports, 'rootCertificates', {
        configurable: true,
        enumerable: true,
        get: function() {
            if (_rootCerts === null) {
                if (typeof globalThis.__host_tls_root_certificates === 'function') {
                    var raw = globalThis.__host_tls_root_certificates();
                    _rootCerts = (typeof raw === 'string' && raw.length) ? raw.split('\n--CERT--\n') : [];
                } else {
                    _rootCerts = [];
                }
            }
            return _rootCerts.slice();
        },
    });
    exports.getCACertificates = function getCACertificates(type) {
        // type: 'default' | 'system' | 'bundled' | 'extra'.
        // We only have the bundled webpki roots; surface them under
        // every requested type for compatibility.
        type = type || 'default';
        return exports.rootCertificates;
    };
});

// ---- trace_events.js ----
// trace_events — Node 20's V8 / Node trace categories. The sandbox
// has no trace pipeline; we accept the API surface so callers don't
// crash, log enable/disable to stderr (best-effort visibility), and
// no-op the rest.

__register_module('trace_events', function(module, exports, require) {

    function Tracing(categories) {
        this._categories = (categories || []).slice();
        this._enabled = false;
    }
    Tracing.prototype.enable = function() { this._enabled = true; };
    Tracing.prototype.disable = function() { this._enabled = false; };
    Object.defineProperty(Tracing.prototype, 'enabled', {
        get: function() { return this._enabled; },
    });
    Object.defineProperty(Tracing.prototype, 'categories', {
        get: function() { return this._categories.join(','); },
    });

    function createTracing(opts) {
        opts = opts || {};
        var cats = opts.categories;
        if (!Array.isArray(cats) || cats.length === 0) {
            throw new TypeError(
                'trace_events.createTracing: `categories` must be a non-empty array'
            );
        }
        return new Tracing(cats);
    }

    function getEnabledCategories() {
        // Sandbox has no globally-enabled categories. Node returns
        // a comma-separated string or `undefined`.
        return undefined;
    }

    exports.createTracing = createTracing;
    exports.getEnabledCategories = getEnabledCategories;
});

// ---- tty.js ----
// tty — Node 20's TTY stream classes. process.stdout / process.stderr
// inherit from these in real Node when attached to a terminal. In
// burn's sandbox there's no kernel TTY, but the API answers should
// match what library code expects: `getColorDepth` and `hasColors`
// honour `NO_COLOR` / `FORCE_COLOR` / `TERM` so chalk / signale /
// supports-color produce the right output for the user's intent.

__register_module('tty', function(module, exports, require) {
    var stream = require('stream');

    // ---- color depth resolver (NO_COLOR / FORCE_COLOR / TERM) ------
    //
    // Resolves to the depth in *bits* (matches Node's `getColorDepth`):
    //   1 → 1-bit / no color
    //   4 → 16-color terminal
    //   8 → 256-color (xterm-256, screen-256color, etc.)
    //  24 → 16-million / TrueColor (modern terminals, COLORTERM=truecolor)
    //
    // Precedence: NO_COLOR (any value) wins, FORCE_COLOR=1..3 next,
    // then TERM/COLORTERM heuristics, then the default-off baseline.
    function _envColorDepth() {
        var env = (typeof process !== 'undefined' && process.env) || {};
        if (env.NO_COLOR != null && env.NO_COLOR !== '') return 1;
        if (env.FORCE_COLOR != null && env.FORCE_COLOR !== '') {
            var fc = String(env.FORCE_COLOR).trim().toLowerCase();
            if (fc === 'true' || fc === '1') return 4;
            if (fc === '2') return 8;
            if (fc === '3') return 24;
            if (fc === 'false' || fc === '0') return 1;
            // FORCE_COLOR= (empty handled above) — non-numeric truthy.
            return 4;
        }
        var colorterm = String(env.COLORTERM || '').toLowerCase();
        if (colorterm === 'truecolor' || colorterm === '24bit') return 24;
        var term = String(env.TERM || '').toLowerCase();
        if (term === 'dumb') return 1;
        if (term.indexOf('256color') !== -1) return 8;
        if (term.indexOf('color') !== -1) return 4;
        if (term && term !== 'dumb') return 4;
        return 1;
    }

    /// Node's `count` mapping — `hasColors([count[, env]])` returns
    /// true when the stream supports ≥ `count` distinct colors.
    /// Defaults: 16 if no count given.
    function _hasColorsForDepth(depth, count) {
        var n = count == null ? 16 : (count | 0);
        if (n <= 2) return depth >= 1;
        if (n <= 16) return depth >= 4;
        if (n <= 256) return depth >= 8;
        return depth >= 24;
    }

    function ReadStream(fd, options) {
        if (!(this instanceof ReadStream)) return new ReadStream(fd, options);
        if (typeof stream.Readable === 'function') {
            stream.Readable.call(this, options);
        }
        this.fd = (fd | 0) || 0;
        this.isRaw = false;
        this.isTTY = false;
        this.columns = 80;
        this.rows = 24;
    }
    if (typeof stream.Readable === 'function') {
        ReadStream.prototype = Object.create(stream.Readable.prototype);
        ReadStream.prototype.constructor = ReadStream;
    }
    ReadStream.prototype.setRawMode = function(mode) {
        this.isRaw = !!mode;
        return this;
    };

    function WriteStream(fd, options) {
        if (!(this instanceof WriteStream)) return new WriteStream(fd, options);
        if (typeof stream.Writable === 'function') {
            stream.Writable.call(this, options);
        }
        this.fd = (fd | 0) || 1;
        this.isTTY = false;
        this.columns = 80;
        this.rows = 24;
    }
    if (typeof stream.Writable === 'function') {
        WriteStream.prototype = Object.create(stream.Writable.prototype);
        WriteStream.prototype.constructor = WriteStream;
    }
    WriteStream.prototype.clearLine = function() { return true; };
    WriteStream.prototype.clearScreenDown = function() { return true; };
    WriteStream.prototype.cursorTo = function() { return true; };
    WriteStream.prototype.moveCursor = function() { return true; };
    WriteStream.prototype.getColorDepth = function(_envOverride) {
        // Node accepts an env override for testability — caller-supplied
        // env is read by `_envColorDepth` if we wired that through, but
        // we keep it simple and read the live process.env.
        return _envColorDepth();
    };
    WriteStream.prototype.hasColors = function(count, _env) {
        return _hasColorsForDepth(_envColorDepth(), count);
    };
    WriteStream.prototype.getWindowSize = function() {
        return [this.columns, this.rows];
    };

    function isatty(fd) {
        var _ = fd;
        return false; // sandbox has no real TTY
    }

    exports.ReadStream = ReadStream;
    exports.WriteStream = WriteStream;
    exports.isatty = isatty;
});

// ---- url.js ----
// url — legacy API (url.parse / url.format / url.resolve) plus a
// passthrough to the WHATWG `URL` / `URLSearchParams` globals.

__register_module('url', function(module, exports, require) {

    function parse(str, parseQueryString) {
        if (typeof str !== 'string') throw new TypeError('url.parse requires a string');
        var out = {
            protocol: null, slashes: null, auth: null, host: null,
            port: null, hostname: null, hash: null, search: null,
            query: null, pathname: null, path: null, href: str
        };

        var rest = str;

        var hashIdx = rest.indexOf('#');
        if (hashIdx >= 0) { out.hash = rest.slice(hashIdx); rest = rest.slice(0, hashIdx); }

        var queryIdx = rest.indexOf('?');
        if (queryIdx >= 0) {
            out.search = rest.slice(queryIdx);
            var q = rest.slice(queryIdx + 1);
            out.query = parseQueryString ? require('querystring').parse(q) : q;
            rest = rest.slice(0, queryIdx);
        }

        var protoMatch = /^([a-zA-Z][a-zA-Z0-9+\-.]*):/.exec(rest);
        if (protoMatch) {
            out.protocol = protoMatch[0];
            rest = rest.slice(protoMatch[0].length);
        }

        if (rest.slice(0, 2) === '//') {
            out.slashes = true;
            rest = rest.slice(2);
            var slash = rest.indexOf('/');
            var authority = slash < 0 ? rest : rest.slice(0, slash);
            rest = slash < 0 ? '' : rest.slice(slash);
            var at = authority.indexOf('@');
            if (at >= 0) { out.auth = authority.slice(0, at); authority = authority.slice(at + 1); }
            out.host = authority || null;
            var colon = authority.indexOf(':');
            if (colon >= 0) { out.hostname = authority.slice(0, colon); out.port = authority.slice(colon + 1); }
            else { out.hostname = authority || null; }
        }

        out.pathname = rest || null;
        out.path = (out.pathname || '') + (out.search || '') || null;
        return out;
    }

    function format(obj) {
        if (typeof obj === 'string') return obj;
        var out = '';
        if (obj.protocol) {
            out += obj.protocol;
            if (obj.protocol.charAt(obj.protocol.length - 1) !== ':') out += ':';
        }
        if (obj.slashes || obj.host || obj.hostname) {
            out += '//';
            if (obj.auth) out += obj.auth + '@';
            out += obj.host || (obj.hostname + (obj.port ? ':' + obj.port : ''));
        }
        out += obj.pathname || '';
        if (obj.search) out += obj.search;
        else if (obj.query) {
            out += '?' + (typeof obj.query === 'string' ? obj.query : require('querystring').stringify(obj.query));
        }
        if (obj.hash) out += obj.hash;
        return out;
    }

    function resolve(from, to) {
        try {
            return new URL(to, from).href;
        } catch (_) {
            // Degenerate resolve for relative-without-base callers.
            if (to.charAt(0) === '/') {
                var p = parse(from);
                return (p.protocol || '') + (p.slashes ? '//' : '') + (p.host || '') + to;
            }
            return to;
        }
    }

    exports.parse = parse;
    exports.format = format;
    exports.resolve = resolve;

    // Lazy-bind to the runtime's URL / URLSearchParams. Direct
    // assignment at module-init snapshots the global, which on Javy /
    // QuickJS isn't always installed when the bundle loads — a
    // direct `exports.URL = URL` would then cache `undefined` and
    // every downstream `require('url').URL` (npm's nerf-dart, every
    // proxy-agent variant) breaks with `not a function`. Getters
    // resolve at call-site so the URL constructor binds the moment
    // it becomes available.
    Object.defineProperty(exports, 'URL', {
        configurable: true,
        enumerable: true,
        get: function() { return globalThis.URL; },
    });
    Object.defineProperty(exports, 'URLSearchParams', {
        configurable: true,
        enumerable: true,
        get: function() { return globalThis.URLSearchParams; },
    });
    exports.fileURLToPath = function(u) {
        var s = typeof u === 'string' ? u : (u && u.href) ? u.href : String(u);
        // file:// → /; file:///foo/bar → /foo/bar; file://host/path → /path
        var m = /^file:\/\/([^/]*)?(\/[^?#]*)?/i.exec(s);
        return m ? (m[2] || '/') : s;
    };
    exports.pathToFileURL = function(p) {
        var s = String(p);
        var path = s.charAt(0) === '/' ? s : '/' + s;
        var encoded = path.replace(/[#?]/g, function(ch) { return encodeURIComponent(ch); });
        // Return a URL-shaped object so callers that read .href / .pathname work.
        var URLCtor = globalThis.URL;
        if (typeof URLCtor === 'function') {
            try { return new URLCtor('file://' + encoded); } catch (_) {}
        }
        return { href: 'file://' + encoded, pathname: path, protocol: 'file:' };
    };
    exports.urlToHttpOptions = function(u) {
        if (!u || typeof u !== 'object') return null;
        return {
            protocol: u.protocol,
            hostname: u.hostname && u.hostname.replace(/^\[|\]$/g, ''),
            hash: u.hash,
            search: u.search,
            pathname: u.pathname,
            path: (u.pathname || '') + (u.search || ''),
            href: u.href,
            port: u.port ? Number(u.port) : undefined,
            auth: (u.username || u.password) ? (decodeURIComponent(u.username || '') + (u.password ? ':' + decodeURIComponent(u.password) : '')) : undefined,
        };
    };
    exports.domainToASCII = function(s) { return String(s).toLowerCase(); };
    exports.domainToUnicode = function(s) { return String(s); };
});

// ---- util.js ----
// util — small subset. `format` and `inspect` cover the >95% case
// (template strings with %s, %d, %j; object -> JSON-like stringification).

__register_module('util', function(module, exports, require) {

    // Matches Node's util.format: string args at the top level are
    // emitted verbatim; non-string args go through util.inspect. That
    // keeps `console.log("a", "b")` producing `"a b"` (no quotes) and
    // `console.log("a", ["b"])` producing `"a [ 'b' ]"` (quotes on the
    // ARRAY element via inspect, not on the top-level "a").
    function renderArg(arg, inspectOpts) {
        return typeof arg === 'string' ? arg : exports.inspect(arg, inspectOpts);
    }

    // Core printf-style formatter shared by `format` and
    // `formatWithOptions`. `args` is the full arguments object, `start`
    // is the index of the format string, and `inspectOpts` (used by
    // `formatWithOptions`) threads inspect options through `%o`/`%O`
    // and the trailing non-string args. For plain `format`, inspectOpts
    // is undefined, which `inspect` treats as the default options — so
    // `format`'s behaviour is unchanged.
    function formatImpl(args, start, inspectOpts) {
        var fmt = args[start];
        if (typeof fmt !== 'string') {
            var parts = [];
            for (var i = start; i < args.length; i++) parts.push(renderArg(args[i], inspectOpts));
            return parts.join(' ');
        }
        var argIdx = start + 1;
        var out = '';
        var i = 0;
        while (i < fmt.length) {
            var ch = fmt.charAt(i);
            if (ch !== '%' || i + 1 >= fmt.length) { out += ch; i++; continue; }
            var spec = fmt.charAt(i + 1);
            var val = args[argIdx++];
            if      (spec === 's') out += String(val);
            else if (spec === 'd' || spec === 'i') out += Number(val).toFixed(0);
            else if (spec === 'f') out += Number(val);
            else if (spec === 'j') { try { out += JSON.stringify(val); } catch (_) { out += '[Circular]'; } }
            else if (spec === 'o' || spec === 'O') out += exports.inspect(val, inspectOpts);
            else if (spec === 'c') { /* CSS directive — consumed, no output (Node parity) */ }
            else if (spec === '%') { out += '%'; argIdx--; }
            else { out += ch; argIdx--; i++; continue; }
            i += 2;
        }
        while (argIdx < args.length) out += ' ' + renderArg(args[argIdx++], inspectOpts);
        return out;
    }

    exports.format = function() {
        return formatImpl(arguments, 0, undefined);
    };

    // `util.formatWithOptions(inspectOptions, format, ...args)` — like
    // `format`, but the leading options object is forwarded to
    // `inspect` for `%o`/`%O` and object args. npm formats ALL of its
    // log/output through this (via `node:util`); without it npm's
    // command pipeline throws inside `formatWithOptions` and silently
    // produces no output.
    exports.formatWithOptions = function(inspectOptions) {
        if (inspectOptions === null || typeof inspectOptions !== 'object') {
            var e = new TypeError('The "inspectOptions" argument must be of type object. Received ' + typeof inspectOptions);
            e.code = 'ERR_INVALID_ARG_TYPE';
            throw e;
        }
        return formatImpl(arguments, 1, inspectOptions);
    };

    /// `util.inspect.custom` — Node 6.6+ symbol used by libraries to
    /// supply a custom inspect string. We define it once so callers
    /// can attach `obj[util.inspect.custom] = function() {...}` and
    /// have inspect call it.
    var INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');

    exports.inspect = function inspect(value, opts) {
        var seen = [];
        function go(v, depth) {
            if (v === null) return 'null';
            if (v === undefined) return 'undefined';
            var t = typeof v;
            if (t === 'string') return JSON.stringify(v);
            if (t === 'number' || t === 'boolean' || t === 'bigint') return String(v);
            if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';
            if (t === 'symbol') return v.toString();
            if (seen.indexOf(v) !== -1) return '[Circular]';
            if (depth > 4) return '[Object]';
            // Honour util.inspect.custom hook before any default
            // serialization. Callers expect this to be tried before
            // toString / toJSON / Object.keys.
            if (typeof v[INSPECT_CUSTOM] === 'function') {
                try {
                    var custom = v[INSPECT_CUSTOM](depth, opts || {}, inspect);
                    if (typeof custom === 'string') return custom;
                    if (custom !== undefined) return go(custom, depth + 1);
                } catch (_) {}
            }
            seen.push(v);
            try {
                if (Array.isArray(v)) {
                    var items = v.map(function(x) { return go(x, depth + 1); });
                    return '[ ' + items.join(', ') + ' ]';
                }
                if (v instanceof Error) return v.stack || (v.name + ': ' + v.message);
                var keys = Object.keys(v);
                var kv = keys.map(function(k) { return k + ': ' + go(v[k], depth + 1); });
                return '{ ' + kv.join(', ') + ' }';
            } finally {
                seen.pop();
            }
        }
        return go(value, 0);
    };
    exports.inspect.custom = INSPECT_CUSTOM;
    exports.inspect.defaultOptions = {
        depth: 2, colors: false, customInspect: true, showHidden: false,
        showProxy: false, maxArrayLength: 100, maxStringLength: 10000,
        breakLength: 128, compact: 3, sorted: false, getters: false,
        numericSeparator: false,
    };
    exports.inspect.colors = {
        bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27],
        white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39],
        cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39],
    };
    exports.inspect.styles = {
        special: 'cyan', number: 'yellow', bigint: 'yellow', boolean: 'yellow',
        undefined: 'grey', null: 'bold', string: 'green', symbol: 'green',
        date: 'magenta', regexp: 'red', module: 'underline',
    };

    exports.inherits = function(ctor, superCtor) {
        if (typeof superCtor !== 'function') throw new TypeError('superCtor must be a function');
        ctor.super_ = superCtor;
        ctor.prototype = Object.create(superCtor.prototype, {
            constructor: { value: ctor, enumerable: false, writable: true, configurable: true }
        });
    };

    exports.promisify = function(fn) {
        return function() {
            var args = Array.prototype.slice.call(arguments);
            var self = this;
            return new Promise(function(resolve, reject) {
                args.push(function(err, val) { err ? reject(err) : resolve(val); });
                try { fn.apply(self, args); } catch (e) { reject(e); }
            });
        };
    };

    exports.callbackify = function(fn) {
        return function() {
            var cb = arguments[arguments.length - 1];
            var rest = Array.prototype.slice.call(arguments, 0, -1);
            Promise.resolve(fn.apply(this, rest))
                .then(function(v) { cb(null, v); })
                .catch(function(e) { cb(e); });
        };
    };

    exports.deprecate = function(fn, _msg) { return fn; };

    // util.debuglog(section): a conditional stderr logger enabled by
    // NODE_DEBUG. Reading the env may itself be denied in a sealed
    // sandbox - that means "not enabled", never an error. The returned
    // function carries `.enabled` like Node's.
    exports.debuglog = function(section, cb) {
        var enabled = false;
        try {
            var spec = (typeof process !== 'undefined' && process.env && process.env.NODE_DEBUG) || '';
            enabled = spec.split(',').some(function(s) {
                s = s.trim().toUpperCase();
                if (!s) return false;
                // NODE_DEBUG supports * wildcards (e.g. `net*`).
                var re = new RegExp('^' + s.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
                return re.test(String(section).toUpperCase());
            });
        } catch (_) { enabled = false; }
        var log = enabled
            ? function() {
                var msg = exports.format.apply(null, arguments);
                console.error(String(section).toUpperCase() + ': ' + msg);
            }
            : function() {};
        log.enabled = enabled;
        if (typeof cb === 'function') cb(log);
        return log;
    };
    exports.debug = exports.debuglog;

    // util.types delegates to the full `util/types` module so the
    // surface stays in one place and `require('util').types` returns
    // the same object as `require('util/types')`. The ALL ~40
    // type-test methods (`isFloat64Array`, `isAnyArrayBuffer`, etc.)
    // are a hard dependency for many libraries that probe object
    // shapes (oxc / acorn-walkers / koa-context, etc.).
    Object.defineProperty(exports, 'types', {
        configurable: true,
        enumerable: true,
        get: function() { return require('util/types'); },
    });

    exports.TextEncoder = typeof TextEncoder === 'function' ? TextEncoder : undefined;
    exports.TextDecoder = typeof TextDecoder === 'function' ? TextDecoder : undefined;

    // ---- util.styleText (Node 21/22) -----------------------------
    //
    // Wraps text in ANSI escape sequences when stdout is a TTY (we
    // approximate "is TTY" via env). The list of supported style
    // names matches Node's `util.styleText` accepted set; unknown
    // styles throw `ERR_INVALID_ARG_VALUE` like Node.
    var ANSI = {
        reset:     [0,  0],
        bold:      [1,  22],
        dim:       [2,  22],
        italic:    [3,  23],
        underline: [4,  24],
        blink:     [5,  25],
        inverse:   [7,  27],
        hidden:    [8,  28],
        strikethrough: [9, 29],
        black:     [30, 39],
        red:       [31, 39],
        green:     [32, 39],
        yellow:    [33, 39],
        blue:      [34, 39],
        magenta:   [35, 39],
        cyan:      [36, 39],
        white:     [37, 39],
        gray:      [90, 39],
        grey:      [90, 39],
        bgBlack:   [40, 49],
        bgRed:     [41, 49],
        bgGreen:   [42, 49],
        bgYellow:  [43, 49],
        bgBlue:    [44, 49],
        bgMagenta: [45, 49],
        bgCyan:    [46, 49],
        bgWhite:   [47, 49],
    };
    exports.styleText = function styleText(format, text, options) {
        var styles = Array.isArray(format) ? format : [format];
        for (var i = 0; i < styles.length; i++) {
            if (typeof styles[i] !== 'string' || !ANSI[styles[i]]) {
                var err = new TypeError("The argument 'format' must be a valid style. Received '" + styles[i] + "'");
                err.code = 'ERR_INVALID_ARG_VALUE';
                throw err;
            }
        }
        // `validateStream: false` in opts skips the TTY check —
        // Node's intent is "always emit colors when explicitly opted
        // in". Default behavior approximates the TTY check via
        // NO_COLOR / FORCE_COLOR env vars.
        var stream = options && options.stream;
        var validate = !options || options.validateStream !== false;
        if (validate) {
            if (typeof process !== 'undefined' && process.env) {
                if (process.env.NO_COLOR) return text;
            }
            // We assume TTY when the caller didn't pass a stream;
            // most CLI tools want colors. Pass `{ stream: ... }` to
            // pipe-aware contexts where that should be checked.
            if (stream && stream.isTTY === false) return text;
        }
        var prefix = '', suffix = '';
        for (var j = 0; j < styles.length; j++) {
            var pair = ANSI[styles[j]];
            prefix += '[' + pair[0] + 'm';
            suffix = '[' + pair[1] + 'm' + suffix;
        }
        return prefix + String(text) + suffix;
    };

    // ---- util.MIMEType / util.MIMEParams (Node 19/22) -------------
    function _parseMIME(input) {
        var s = String(input).trim();
        var slash = s.indexOf('/');
        if (slash < 0) {
            var e = new TypeError('Invalid MIME type: missing "/"');
            e.code = 'ERR_INVALID_MIME_SYNTAX';
            throw e;
        }
        var type = s.slice(0, slash).toLowerCase();
        var rest = s.slice(slash + 1);
        var semi = rest.indexOf(';');
        var sub = (semi < 0 ? rest : rest.slice(0, semi)).trim().toLowerCase();
        var params = [];
        if (semi >= 0) {
            var paramStr = rest.slice(semi + 1);
            var parts = paramStr.split(';');
            for (var i = 0; i < parts.length; i++) {
                var p = parts[i].trim();
                if (!p) continue;
                var eq = p.indexOf('=');
                if (eq < 0) continue;
                var k = p.slice(0, eq).trim().toLowerCase();
                var v = p.slice(eq + 1).trim();
                if (v.length >= 2 && v.charCodeAt(0) === 34 && v.charCodeAt(v.length - 1) === 34) {
                    v = v.slice(1, -1).replace(/\\(.)/g, '$1');
                }
                params.push([k, v]);
            }
        }
        return { type: type, subtype: sub, params: params };
    }
    function MIMEParams(pairs) { this._pairs = pairs.slice(); }
    MIMEParams.prototype.get = function(name) {
        var k = String(name).toLowerCase();
        for (var i = 0; i < this._pairs.length; i++) {
            if (this._pairs[i][0] === k) return this._pairs[i][1];
        }
        return null;
    };
    MIMEParams.prototype.has = function(name) { return this.get(name) !== null; };
    MIMEParams.prototype.set = function(name, value) {
        var k = String(name).toLowerCase();
        for (var i = 0; i < this._pairs.length; i++) {
            if (this._pairs[i][0] === k) { this._pairs[i][1] = String(value); return; }
        }
        this._pairs.push([k, String(value)]);
    };
    MIMEParams.prototype.delete = function(name) {
        var k = String(name).toLowerCase();
        this._pairs = this._pairs.filter(function(p) { return p[0] !== k; });
    };
    MIMEParams.prototype.entries = function*() { for (var i = 0; i < this._pairs.length; i++) yield this._pairs[i].slice(); };
    MIMEParams.prototype.keys    = function*() { for (var i = 0; i < this._pairs.length; i++) yield this._pairs[i][0]; };
    MIMEParams.prototype.values  = function*() { for (var i = 0; i < this._pairs.length; i++) yield this._pairs[i][1]; };
    MIMEParams.prototype[Symbol.iterator] = MIMEParams.prototype.entries;
    MIMEParams.prototype.toString = function() {
        return this._pairs.map(function(p) {
            var v = p[1];
            return p[0] + '=' + (/[^A-Za-z0-9_\-.+]/.test(v) ? '"' + v.replace(/(["\\])/g, '\\$1') + '"' : v);
        }).join(';');
    };

    function MIMEType(input) {
        var parsed = _parseMIME(input);
        this._type = parsed.type;
        this._sub = parsed.subtype;
        this.params = new MIMEParams(parsed.params);
    }
    Object.defineProperty(MIMEType.prototype, 'type', {
        get: function() { return this._type; },
        set: function(v) { this._type = String(v).toLowerCase(); },
    });
    Object.defineProperty(MIMEType.prototype, 'subtype', {
        get: function() { return this._sub; },
        set: function(v) { this._sub = String(v).toLowerCase(); },
    });
    Object.defineProperty(MIMEType.prototype, 'essence', {
        get: function() { return this._type + '/' + this._sub; },
    });
    MIMEType.prototype.toString = function() {
        var p = this.params.toString();
        return this._type + '/' + this._sub + (p ? ';' + p : '');
    };
    MIMEType.prototype.toJSON = MIMEType.prototype.toString;
    exports.MIMEType = MIMEType;
    exports.MIMEParams = MIMEParams;

    // ---- util.parseArgs (Node 18.3+ stable, v2 surface in 22) ----
    //
    // Parses argv per a small `options` schema:
    //   { foo: { type: 'string', short: 'f', multiple: true,
    //            default: 'x' } }
    // Returns `{ values, positionals, tokens? }`.
    //
    // Supported v2 surface: `tokens: true` returns the full token
    // stream (per arg, with `kind`: option / positional / option-
    // terminator). Strict mode rejects unknown options like Node.
    exports.parseArgs = function parseArgs(config) {
        var cfg = config || {};
        var args = cfg.args || (typeof process !== 'undefined' && process.argv ? process.argv.slice(2) : []);
        var options = cfg.options || {};
        var strict = cfg.strict !== false;
        var allowPositionals = cfg.allowPositionals === true;
        var allowNegative = cfg.allowNegative === true;
        var wantTokens = cfg.tokens === true;

        // Build short-flag → long-name map.
        var shortMap = {};
        var longNames = Object.keys(options);
        for (var li = 0; li < longNames.length; li++) {
            var n = longNames[li];
            var spec = options[n];
            if (!spec || typeof spec !== 'object') continue;
            if (typeof spec.short === 'string' && spec.short.length > 0) {
                shortMap[spec.short] = n;
            }
        }

        function specOf(name) {
            var s = options[name];
            return s && typeof s === 'object' ? s : null;
        }
        function setValue(values, name, value) {
            var s = specOf(name);
            if (s && s.multiple) {
                if (!values[name]) values[name] = [];
                values[name].push(value);
            } else {
                values[name] = value;
            }
        }
        function consumeBoolean(values, name, raw) {
            setValue(values, name, raw);
            if (wantTokens) {
                tokens.push({ kind: 'option', name: name, rawName: raw === false ? '--no-' + name : null,
                              value: undefined, inlineValue: undefined });
            }
        }

        var values = {};
        var positionals = [];
        var tokens = [];

        // Apply defaults.
        for (var di = 0; di < longNames.length; di++) {
            var dn = longNames[di];
            var ds = specOf(dn);
            if (ds && Object.prototype.hasOwnProperty.call(ds, 'default')) {
                values[dn] = ds.default;
            }
        }

        var i = 0;
        var sawTerminator = false;
        while (i < args.length) {
            var a = args[i];
            if (sawTerminator) {
                positionals.push(a);
                if (wantTokens) tokens.push({ kind: 'positional', index: i, value: a });
                i++;
                continue;
            }
            if (a === '--') {
                sawTerminator = true;
                if (wantTokens) tokens.push({ kind: 'option-terminator', index: i });
                i++;
                continue;
            }
            // Long form: `--name`, `--name=value`, `--no-name`.
            if (a.length > 2 && a[0] === '-' && a[1] === '-') {
                var body = a.slice(2);
                var eq = body.indexOf('=');
                var name = eq >= 0 ? body.slice(0, eq) : body;
                var inline = eq >= 0 ? body.slice(eq + 1) : undefined;
                if (allowNegative && name.indexOf('no-') === 0 && options[name.slice(3)]) {
                    setValue(values, name.slice(3), false);
                    if (wantTokens) tokens.push({ kind: 'option', name: name.slice(3),
                                                  rawName: a, value: false, inlineValue: undefined });
                    i++;
                    continue;
                }
                var s = specOf(name);
                if (!s) {
                    if (strict) {
                        var e = new TypeError("Unknown option '--" + name + "'");
                        e.code = 'ERR_PARSE_ARGS_UNKNOWN_OPTION';
                        throw e;
                    }
                    if (allowPositionals) positionals.push(a);
                    if (wantTokens) tokens.push({ kind: 'option', name: name, rawName: a,
                                                  value: inline, inlineValue: inline });
                    i++;
                    continue;
                }
                if (s.type === 'boolean') {
                    setValue(values, name, true);
                    if (wantTokens) tokens.push({ kind: 'option', name: name, rawName: a,
                                                  value: true, inlineValue: undefined });
                    i++;
                } else {
                    var val = inline !== undefined ? inline : args[++i];
                    setValue(values, name, val);
                    if (wantTokens) tokens.push({ kind: 'option', name: name, rawName: a,
                                                  value: val, inlineValue: inline });
                    i++;
                }
                continue;
            }
            // Short form: `-f`, `-fvalue`, `-fxyz` (cluster of bools).
            if (a.length >= 2 && a[0] === '-' && a[1] !== '-') {
                var rest = a.slice(1);
                var consumed = false;
                for (var ri = 0; ri < rest.length; ri++) {
                    var c = rest[ri];
                    var longName = shortMap[c];
                    if (!longName) {
                        if (strict) {
                            var e2 = new TypeError("Unknown option '-" + c + "'");
                            e2.code = 'ERR_PARSE_ARGS_UNKNOWN_OPTION';
                            throw e2;
                        }
                        break;
                    }
                    var sp = specOf(longName);
                    if (sp && sp.type === 'string') {
                        var rem = rest.slice(ri + 1);
                        var sval = rem.length ? rem : args[++i];
                        setValue(values, longName, sval);
                        if (wantTokens) tokens.push({ kind: 'option', name: longName, rawName: a,
                                                      value: sval, inlineValue: rem.length ? rem : undefined });
                        consumed = true;
                        break;
                    }
                    setValue(values, longName, true);
                    if (wantTokens) tokens.push({ kind: 'option', name: longName, rawName: a,
                                                  value: true, inlineValue: undefined });
                }
                if (!consumed) i++;
                else i++;
                continue;
            }
            // Bare positional.
            if (!allowPositionals && strict) {
                var e3 = new TypeError("Unexpected positional argument '" + a + "'");
                e3.code = 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL';
                throw e3;
            }
            positionals.push(a);
            if (wantTokens) tokens.push({ kind: 'positional', index: i, value: a });
            i++;
        }
        var out = { values: values, positionals: positionals };
        if (wantTokens) out.tokens = tokens;
        return out;
    };

    // ---- util.transferableAbortSignal / util.aborted (Node 22) ----
    //
    // `transferableAbortSignal(s)` returns a signal usable across
    // worker postMessage boundaries; in our model AbortSignal is
    // already a plain object so the transfer is a no-op identity.
    // `aborted(signal, resource)` returns a Promise that rejects
    // with the abort reason (matches the Node 18.3+ contract).
    exports.transferableAbortSignal = function transferableAbortSignal(signal) {
        return signal;
    };
    exports.aborted = function aborted(signal, _resource) {
        if (!signal || typeof signal.addEventListener !== 'function') {
            return Promise.reject(new TypeError('aborted: argument must be an AbortSignal'));
        }
        if (signal.aborted) {
            return Promise.reject(signal.reason || new Error('aborted'));
        }
        return new Promise(function(_resolve, reject) {
            signal.addEventListener('abort', function() {
                reject(signal.reason || new Error('aborted'));
            }, { once: true });
        });
    };

    // ---- util.getSystemErrorName / Map / Message (Node 17+/22.4+) ---
    //
    // Node exposes the libuv error code table so user code can map
    // negative errno integers to symbolic names ('ENOENT', 'EACCES',
    // ...). We ship the standard POSIX subset that callers actually
    // probe for.
    var SYSTEM_ERRORS = {
        '-1':  ['EPERM',  'Operation not permitted'],
        '-2':  ['ENOENT', 'No such file or directory'],
        '-3':  ['ESRCH',  'No such process'],
        '-4':  ['EINTR',  'Interrupted system call'],
        '-5':  ['EIO',    'Input/output error'],
        '-9':  ['EBADF',  'Bad file descriptor'],
        '-11': ['EAGAIN', 'Resource temporarily unavailable'],
        '-12': ['ENOMEM', 'Cannot allocate memory'],
        '-13': ['EACCES', 'Permission denied'],
        '-16': ['EBUSY',  'Device or resource busy'],
        '-17': ['EEXIST', 'File exists'],
        '-19': ['ENODEV', 'No such device'],
        '-20': ['ENOTDIR','Not a directory'],
        '-21': ['EISDIR', 'Is a directory'],
        '-22': ['EINVAL', 'Invalid argument'],
        '-24': ['EMFILE', 'Too many open files'],
        '-28': ['ENOSPC', 'No space left on device'],
        '-30': ['EROFS',  'Read-only file system'],
        '-32': ['EPIPE',  'Broken pipe'],
        '-98': ['EADDRINUSE',    'Address already in use'],
        '-104':['ECONNRESET',    'Connection reset by peer'],
        '-110':['ETIMEDOUT',     'Connection timed out'],
        '-111':['ECONNREFUSED',  'Connection refused'],
        '-125':['ECANCELED',     'Operation canceled'],
    };
    exports.getSystemErrorName = function(err) {
        var entry = SYSTEM_ERRORS[String(err)];
        return entry ? entry[0] : 'UNKNOWN';
    };
    exports.getSystemErrorMessage = function(err) {
        var entry = SYSTEM_ERRORS[String(err)];
        return entry ? entry[1] : 'Unknown system error';
    };
    exports.getSystemErrorMap = function() {
        var m = new Map();
        Object.keys(SYSTEM_ERRORS).forEach(function(k) {
            m.set(parseInt(k, 10), SYSTEM_ERRORS[k]);
        });
        return m;
    };

    // ---- util.getCallSites (Node 22.9+) ---------------------------
    //
    // Returns the JS call sites for the current frame. We parse
    // `new Error().stack` to surface a structured array since
    // QuickJS doesn't expose CallSite objects directly.
    exports.getCallSites = function getCallSites(framesToSkip, _options) {
        if (typeof framesToSkip === 'object' && framesToSkip !== null) {
            framesToSkip = 0;
        }
        framesToSkip = framesToSkip | 0;
        var stack = (new Error()).stack || '';
        var lines = stack.split('\n');
        var frames = [];
        for (var i = 1 + framesToSkip; i < lines.length; i++) {
            var ln = lines[i].trim();
            if (!ln) continue;
            if (ln.indexOf('at ') === 0) ln = ln.slice(3);
            var m = ln.match(/^(.*?)\s+\((.+):(\d+):(\d+)\)$/);
            if (m) {
                frames.push({
                    functionName: m[1], scriptName: m[2],
                    lineNumber: parseInt(m[3], 10),
                    columnNumber: parseInt(m[4], 10),
                    scriptId: '',
                });
            } else {
                var m2 = ln.match(/^(.+):(\d+):(\d+)$/);
                if (m2) frames.push({
                    functionName: '', scriptName: m2[1],
                    lineNumber: parseInt(m2[2], 10),
                    columnNumber: parseInt(m2[3], 10),
                    scriptId: '',
                });
            }
        }
        return frames;
    };

    // ---- util.diff (Node 24+, Stage 2) ----------------------------
    //
    // A line-oriented LCS diff returning the Node-shaped edit script.
    // For small inputs the O(n*m) cost is fine.
    exports.diff = function diff(actual, expected) {
        var a = String(actual).split('\n');
        var b = String(expected).split('\n');
        var n = a.length, m = b.length;
        var dp = [];
        for (var i = 0; i <= n; i++) dp.push(new Array(m + 1).fill(0));
        for (var i2 = n - 1; i2 >= 0; i2--) {
            for (var j2 = m - 1; j2 >= 0; j2--) {
                if (a[i2] === b[j2]) dp[i2][j2] = dp[i2 + 1][j2 + 1] + 1;
                else dp[i2][j2] = Math.max(dp[i2 + 1][j2], dp[i2][j2 + 1]);
            }
        }
        var result = [];
        var i3 = 0, j3 = 0;
        while (i3 < n && j3 < m) {
            if (a[i3] === b[j3]) { result.push({ type: 0, value: a[i3] + '\n' }); i3++; j3++; }
            else if (dp[i3 + 1][j3] >= dp[i3][j3 + 1]) {
                result.push({ type: -1, value: a[i3] + '\n' }); i3++;
            } else {
                result.push({ type: 1, value: b[j3] + '\n' }); j3++;
            }
        }
        while (i3 < n) { result.push({ type: -1, value: a[i3] + '\n' }); i3++; }
        while (j3 < m) { result.push({ type: 1, value: b[j3] + '\n' }); j3++; }
        return result;
    };
});

// ---- v8.js ----
// v8 — Node 20's V8 introspection API. Heap stats source live values
// from `process.memoryUsage()`. Heap snapshots emit the V8
// .heapsnapshot JSON shape Chrome DevTools / Node loaders parse.
// `v8.serialize` / `v8.deserialize` are byte-compatible with V8's
// ValueSerializer format v15.

__register_module('v8', function(module, exports, require) {

    var Buffer = require('buffer').Buffer;

    /// Source the live numbers from `process.memoryUsage()` (which
    /// pulls real RSS / heapTotal / heapUsed from the host) so the
    /// numbers track the actual process state, not a hardcoded snapshot.
    function _liveMem() {
        var u = (typeof process.memoryUsage === 'function')
            ? process.memoryUsage() : {};
        return {
            rss: u.rss | 0,
            heapTotal: u.heapTotal | 0,
            heapUsed: u.heapUsed | 0,
            external: u.external | 0,
            arrayBuffers: u.arrayBuffers | 0,
        };
    }

    function getHeapStatistics() {
        var m = _liveMem();
        // V8 reports two-word "limit" defaults at boot; we use the
        // RSS as the upper bound the host has already committed to,
        // which matches the property libraries care about (`heap_size_limit`
        // gates whether a process is near OOM).
        var limit = Math.max(m.heapTotal, m.rss, 256 * 1024 * 1024);
        return {
            total_heap_size: m.heapTotal,
            total_heap_size_executable: 0,
            total_physical_size: m.rss,
            total_available_size: Math.max(0, limit - m.heapUsed),
            used_heap_size: m.heapUsed,
            heap_size_limit: limit,
            malloced_memory: m.external,
            peak_malloced_memory: m.external,
            does_zap_garbage: 0,
            number_of_native_contexts: 1,
            number_of_detached_contexts: 0,
            total_global_handles_size: 0,
            used_global_handles_size: 0,
            external_memory: m.external,
        };
    }

    function getHeapSpaceStatistics() {
        var m = _liveMem();
        // Two spaces — `code` and `large_object` — match the V8 layout
        // a profiler expects to find. We map heapUsed → large_object's
        // used size and remaining budget → its available size.
        var available = Math.max(0, m.heapTotal - m.heapUsed);
        return [
            {
                space_name: 'new_space',
                space_size: Math.min(m.heapTotal, 8 * 1024 * 1024),
                space_used_size: Math.min(m.heapUsed, 1 * 1024 * 1024),
                space_available_size: Math.min(available, 7 * 1024 * 1024),
                physical_space_size: Math.min(m.rss, 8 * 1024 * 1024),
            },
            {
                space_name: 'old_space',
                space_size: m.heapTotal,
                space_used_size: m.heapUsed,
                space_available_size: available,
                physical_space_size: m.rss,
            },
            {
                space_name: 'code_space',
                space_size: 0,
                space_used_size: 0,
                space_available_size: 0,
                physical_space_size: 0,
            },
            {
                space_name: 'large_object_space',
                space_size: m.arrayBuffers,
                space_used_size: m.arrayBuffers,
                space_available_size: 0,
                physical_space_size: m.arrayBuffers,
            },
        ];
    }

    function getHeapCodeStatistics() {
        var m = _liveMem();
        return {
            code_and_metadata_size: 0,
            bytecode_and_metadata_size: 0,
            external_script_source_size: 0,
            cpu_profiler_metadata_size: 0,
            peak_malloced_memory: m.external,
        };
    }

    /// V8 .heapsnapshot format (Chrome DevTools / clinic.js friendly).
    /// We emit a minimal-but-conformant JSON tree with one synthetic
    /// "(GC roots)" → "(Process)" path; nodes carry the live byte
    /// totals. Real V8 dumps every JS object on the heap — that's a
    /// QuickJS-internal walk we don't have a host hook for, so the
    /// snapshot is process-summary granularity rather than per-object.
    function _buildHeapSnapshot() {
        var m = _liveMem();
        // V8 schema: meta describes the column layout for nodes/edges.
        // Field counts MUST match the actual data we emit per row.
        var meta = {
            node_fields: ['type','name','id','self_size','edge_count','trace_node_id','detachedness'],
            node_types: [
                ['hidden','array','string','object','code','closure','regexp','number','native','synthetic','concatenated string','sliced string','symbol','bigint'],
                'string','number','number','number','number','number',
            ],
            edge_fields: ['type','name_or_index','to_node'],
            edge_types: [
                ['context','element','property','internal','hidden','shortcut','weak'],
                'string_or_number','node',
            ],
            trace_function_info_fields: ['function_id','name','script_name','script_id','line','column'],
            trace_node_fields: ['id','function_info_index','count','size','children'],
            sample_fields: ['timestamp_us','last_assigned_id'],
            location_fields: ['object_index','script_id','line','column'],
        };
        var strings = ['', '(GC roots)', '(Process)', '(rss)', '(heap)', '(external)', '(arrayBuffers)'];
        // Nodes — each row is `node_fields.length` numbers in order.
        // type,name,id,self_size,edge_count,trace_node_id,detachedness
        var nodes = [
            // type=9 (synthetic), name="(GC roots)", id=1, size=0, edges=1
            9, 1, 1, 0, 1, 0, 0,
            // type=9 (synthetic), name="(Process)", id=2, size=rss, edges=4
            9, 2, 2, m.rss, 4, 0, 0,
            // type=8 (native), name="(heap)", id=3, size=heapTotal, edges=0
            8, 4, 3, m.heapTotal, 0, 0, 0,
            // type=8 (native), name="(external)", id=4, size=external, edges=0
            8, 5, 4, m.external, 0, 0, 0,
            // type=8 (native), name="(arrayBuffers)", id=5, size=AB, edges=0
            8, 6, 5, m.arrayBuffers, 0, 0, 0,
            // type=8 (native), name="(rss)", id=6, size=rss, edges=0
            8, 3, 6, m.rss, 0, 0, 0,
        ];
        // Edges — each row is `edge_fields.length` numbers in order.
        // type,name_or_index,to_node — to_node is byte offset (rownum × 7)
        var edges = [
            // root → process
            0, 0, 7,        // (GC roots) → (Process) [type=context]
            // process → 4 children
            2, 3, 35,       // (Process) → (rss) by name "(rss)" idx 3
            2, 4, 14,       // (Process) → (heap) [name idx 4 in strings]
            2, 5, 21,       // (Process) → (external)
            2, 6, 28,       // (Process) → (arrayBuffers)
        ];
        var snapshot = {
            meta: meta,
            node_count: 6,
            edge_count: 5,
            trace_function_count: 0,
        };
        return JSON.stringify({
            snapshot: snapshot,
            nodes: nodes,
            edges: edges,
            trace_function_infos: [],
            trace_tree: [],
            samples: [],
            locations: [],
            strings: strings,
        });
    }

    function getHeapSnapshot() {
        var EventEmitter = require('events').EventEmitter;
        var stream = new EventEmitter();
        var dump = _buildHeapSnapshot();
        var bytes = Buffer.from(dump);
        var consumed = false;
        stream.read = function() {
            if (consumed) return null;
            consumed = true;
            return bytes;
        };
        stream.pipe = function(dest) { dest.end(bytes); return dest; };
        Promise.resolve().then(function() {
            stream.emit('data', bytes);
            stream.emit('end');
        });
        return stream;
    }

    function writeHeapSnapshot(filename) {
        var fs = require('fs');
        var dump = _buildHeapSnapshot();
        var path = filename || ('Heap.' + Date.now() + '.heapsnapshot');
        fs.writeFileSync(path, dump);
        return path;
    }

    // ---- Serialization (v8.serialize / deserialize) ---------------
    //
    // Real V8 wire format — Node's `v8.serialize` output is byte-
    // compatible with what `value-serializer.cc` produces. The host
    // implements the encoder/decoder; the JS side walks JS values into
    // a typed JSON tree (the same `V8Value` enum on both sides) and
    // base64-encodes binary chunks.

    // ABV (ArrayBufferView) sub-tags from V8 source.
    var ABV = {
        Int8Array: 0x62, Uint8Array: 0x42, Uint8ClampedArray: 0x43,
        Int16Array: 0x77, Uint16Array: 0x57,
        Int32Array: 0x64, Uint32Array: 0x44,
        Float32Array: 0x66, Float64Array: 0x46,
        BigInt64Array: 0x71, BigUint64Array: 0x51,
        DataView: 0x3F,
    };

    function _bytesToBase64(u8) {
        return Buffer.from(u8).toString('base64');
    }
    function _base64ToBytes(b64) {
        return new Uint8Array(Buffer.from(b64, 'base64'));
    }

    /// Convert a JS value into the typed tree the host expects.
    /// Cycles aren't fully spec'd here — we detect and reject; real
    /// Node's structured-clone supports cycles via the reference
    /// table, which is forthcoming.
    function _jsToTree(v, seen) {
        if (v === undefined) return { t: 'u' };
        if (v === null) return { t: 'n' };
        var ty = typeof v;
        if (ty === 'boolean') return { t: 'b', v: v };
        if (ty === 'number') {
            if (Number.isFinite(v) && Number.isInteger(v) && v >= -2147483648 && v <= 2147483647) {
                return { t: 'i', v: v };
            }
            if (!Number.isFinite(v)) {
                if (Number.isNaN(v)) return { t: 'd', v: 'NaN' };
                return { t: 'd', v: v > 0 ? 'Infinity' : '-Infinity' };
            }
            return { t: 'd', v: v };
        }
        if (ty === 'string') return { t: 's', v: v };
        if (ty === 'bigint') {
            // 8-byte little-endian digit chunks per V8. Encode as hex.
            var neg = v < 0n;
            var abs = neg ? -v : v;
            var hex = abs.toString(16);
            if (hex.length % 2 !== 0) hex = '0' + hex;
            // V8 stores LE; reverse byte order from BE hex.
            var bytes = [];
            for (var i = 0; i < hex.length; i += 2) {
                bytes.unshift(hex.substr(i, 2));
            }
            return { t: 'Z', n: neg, d: bytes.join('') };
        }
        if (seen.has(v)) {
            throw new Error('v8.serialize: cyclic reference (object-table not yet wired)');
        }
        seen.add(v);
        if (v instanceof Date) return { t: 'D', v: v.getTime() };
        if (v instanceof RegExp) {
            var f = 0;
            if (v.global) f |= 1;
            if (v.ignoreCase) f |= 2;
            if (v.multiline) f |= 4;
            if (v.sticky) f |= 8;
            if (v.unicode) f |= 16;
            if (v.dotAll) f |= 32;
            return { t: 'R', p: v.source, f: f };
        }
        if (v instanceof Map) {
            var ents = [];
            v.forEach(function(val, key) {
                ents.push([_jsToTree(key, seen), _jsToTree(val, seen)]);
            });
            return { t: 'm', e: ents };
        }
        if (v instanceof Set) {
            var items = [];
            v.forEach(function(item) { items.push(_jsToTree(item, seen)); });
            return { t: 'e', v: items };
        }
        if (v instanceof Error) {
            var kind = 0x45; // generic Error 'E'
            if (v instanceof TypeError) kind = 0x54;
            else if (v instanceof RangeError) kind = 0x52;
            else if (v instanceof ReferenceError) kind = 0x46;
            else if (v instanceof SyntaxError) kind = 0x53;
            else if (v instanceof URIError) kind = 0x55;
            else if (v instanceof EvalError) kind = 0x56;
            var out = { t: 'E', k: kind };
            if (typeof v.message === 'string') out.m = v.message;
            if (typeof v.stack === 'string') out.s = v.stack;
            return out;
        }
        if (v instanceof ArrayBuffer) {
            return { t: 'B', v: _bytesToBase64(new Uint8Array(v)) };
        }
        if (ArrayBuffer.isView(v)) {
            var ctorName = v.constructor && v.constructor.name;
            var k = ABV[ctorName];
            if (k == null) throw new Error('v8.serialize: unknown TypedArray ' + ctorName);
            return {
                t: 'V', k: k,
                b: _bytesToBase64(new Uint8Array(v.buffer)),
                o: v.byteOffset,
                l: v.byteLength,
            };
        }
        if (Array.isArray(v)) {
            // Detect sparse arrays (length larger than enumerable keys).
            var keys = Object.keys(v);
            if (keys.length === v.length && keys.every(function(k, i) { return Number(k) === i; })) {
                return { t: 'a', v: v.map(function(x) { return _jsToTree(x, seen); }) };
            }
            // Sparse path.
            var ent = [];
            for (var i = 0; i < keys.length; i++) {
                var idx = Number(keys[i]);
                ent.push([idx, _jsToTree(v[idx], seen)]);
            }
            return { t: 'S', l: v.length, e: ent };
        }
        // Plain object.
        var props = Object.keys(v);
        var oent = [];
        for (var i = 0; i < props.length; i++) {
            oent.push([String(props[i]), _jsToTree(v[props[i]], seen)]);
        }
        return { t: 'o', e: oent };
    }

    /// Reverse: turn the host's JSON tree back into JS values.
    function _treeToJs(node) {
        if (!node || typeof node !== 'object') return node;
        switch (node.t) {
            case 'u': return undefined;
            case 'n': return null;
            case 'b': return !!node.v;
            case 'i': case 'U': return node.v | 0;
            case 'd':
                if (typeof node.v === 'string') {
                    if (node.v === 'Infinity') return Infinity;
                    if (node.v === '-Infinity') return -Infinity;
                    if (node.v === 'NaN') return NaN;
                    return Number(node.v);
                }
                return node.v;
            case 's': return String(node.v);
            case 'D': return new Date(node.v);
            case 'R': {
                var f = node.f | 0;
                var s = '';
                if (f & 1) s += 'g';
                if (f & 2) s += 'i';
                if (f & 4) s += 'm';
                if (f & 8) s += 'y';
                if (f & 16) s += 'u';
                if (f & 32) s += 's';
                return new RegExp(node.p, s);
            }
            case 'o': {
                var o = {};
                var e = node.e || [];
                for (var i = 0; i < e.length; i++) o[e[i][0]] = _treeToJs(e[i][1]);
                return o;
            }
            case 'a': return (node.v || []).map(_treeToJs);
            case 'S': {
                var arr = new Array(node.l | 0);
                var ent = node.e || [];
                for (var i = 0; i < ent.length; i++) arr[ent[i][0]] = _treeToJs(ent[i][1]);
                return arr;
            }
            case 'm': {
                var m = new Map();
                var es = node.e || [];
                for (var i = 0; i < es.length; i++) m.set(_treeToJs(es[i][0]), _treeToJs(es[i][1]));
                return m;
            }
            case 'e': {
                var st = new Set();
                var v = node.v || [];
                for (var i = 0; i < v.length; i++) st.add(_treeToJs(v[i]));
                return st;
            }
            case 'B': return _base64ToBytes(node.v).buffer;
            case 'V': {
                var buf = _base64ToBytes(node.b).buffer;
                var Ctor = _abvCtor(node.k);
                var elementSize = Ctor.BYTES_PER_ELEMENT || 1;
                return new Ctor(buf, node.o | 0, (node.l | 0) / elementSize);
            }
            case 'E': {
                var ErrCtor = Error;
                if (node.k === 0x54) ErrCtor = TypeError;
                else if (node.k === 0x52) ErrCtor = RangeError;
                else if (node.k === 0x46) ErrCtor = ReferenceError;
                else if (node.k === 0x53) ErrCtor = SyntaxError;
                else if (node.k === 0x55) ErrCtor = URIError;
                else if (node.k === 0x56) ErrCtor = EvalError;
                var err = new ErrCtor(node.m || '');
                if (node.s) try { err.stack = node.s; } catch (_) {}
                return err;
            }
            case 'Z': {
                // Reverse hex bytes (LE in V8) into a BE BigInt.
                var d = String(node.d || '');
                if (!d) return 0n;
                var rev = '';
                for (var i = d.length - 2; i >= 0; i -= 2) rev += d.substr(i, 2);
                var n = BigInt('0x' + rev);
                return node.n ? -n : n;
            }
            default:
                throw new Error('v8.deserialize: unknown tree tag ' + node.t);
        }
    }
    function _abvCtor(kind) {
        switch (kind) {
            case 0x62: return Int8Array;
            case 0x42: return Uint8Array;
            case 0x43: return Uint8ClampedArray;
            case 0x77: return Int16Array;
            case 0x57: return Uint16Array;
            case 0x64: return Int32Array;
            case 0x44: return Uint32Array;
            case 0x66: return Float32Array;
            case 0x46: return Float64Array;
            case 0x71: return BigInt64Array;
            case 0x51: return BigUint64Array;
            case 0x3F: return DataView;
            default: throw new Error('v8.deserialize: unknown ABV kind ' + kind);
        }
    }

    function serialize(value) {
        if (typeof globalThis.__host_v8_serialize !== 'function') {
            throw new Error('v8.serialize: host fn missing');
        }
        var tree = _jsToTree(value, new Set());
        var b64 = globalThis.__host_v8_serialize(JSON.stringify(tree));
        if (typeof b64 === 'string' && b64.indexOf('__HOST_ERR__:') === 0) {
            throw new Error(b64.slice('__HOST_ERR__:'.length));
        }
        return Buffer.from(b64, 'base64');
    }

    function deserialize(buf) {
        if (typeof globalThis.__host_v8_deserialize !== 'function') {
            throw new Error('v8.deserialize: host fn missing');
        }
        var bytes;
        if (Buffer.isBuffer(buf)) bytes = buf;
        else if (buf instanceof ArrayBuffer) bytes = Buffer.from(new Uint8Array(buf));
        else if (buf instanceof Uint8Array) bytes = Buffer.from(buf);
        else throw new TypeError('v8.deserialize: argument must be a Buffer / Uint8Array / ArrayBuffer');
        var b64 = bytes.toString('base64');
        var json = globalThis.__host_v8_deserialize(b64);
        if (typeof json === 'string' && json.indexOf('__HOST_ERR__:') === 0) {
            throw new Error(json.slice('__HOST_ERR__:'.length));
        }
        return _treeToJs(JSON.parse(json));
    }

    function Serializer() {
        this._values = [];
    }
    Serializer.prototype.writeHeader = function() {};
    Serializer.prototype.writeValue = function(v) { this._values.push(v); };
    Serializer.prototype.releaseBuffer = function() {
        return serialize(this._values.length === 1 ? this._values[0] : this._values);
    };
    Serializer.prototype.transferArrayBuffer = function() {};

    function Deserializer(buf) {
        this._cursor = 0;
        this._values = [];
        try {
            var v = deserialize(buf);
            this._values = Array.isArray(v) ? v : [v];
        } catch (_) { /* invalid input → empty values */ }
    }
    Deserializer.prototype.readHeader = function() { return true; };
    Deserializer.prototype.readValue = function() {
        return this._values[this._cursor++];
    };
    Deserializer.prototype.transferArrayBuffer = function() {};

    function setFlagsFromString(_flags) {
        // V8 flag tweaks are V8-specific; ignored.
    }
    function getStringEnvironment() {
        return [];
    }

    exports.cachedDataVersionTag = function() { return 0; };
    exports.getHeapStatistics = getHeapStatistics;
    exports.getHeapSpaceStatistics = getHeapSpaceStatistics;
    exports.getHeapCodeStatistics = getHeapCodeStatistics;
    exports.getHeapSnapshot = getHeapSnapshot;
    exports.writeHeapSnapshot = writeHeapSnapshot;
    exports.setFlagsFromString = setFlagsFromString;
    exports.getStringEnvironment = getStringEnvironment;
    exports.serialize = serialize;
    exports.deserialize = deserialize;
    exports.Serializer = Serializer;
    exports.Deserializer = Deserializer;
    exports.DefaultSerializer = Serializer;
    exports.DefaultDeserializer = Deserializer;
    exports.startupSnapshot = {
        addDeserializeCallback: function() {},
        addSerializeCallback: function() {},
        setDeserializeMainFunction: function() {},
        isBuildingSnapshot: function() { return false; },
    };
    exports.promiseHooks = {
        onInit: function() { return function() {}; },
        onSettled: function() { return function() {}; },
        onBefore: function() { return function() {}; },
        onAfter: function() { return function() {}; },
        createHook: function() { return { disable: function() {} }; },
    };
});

// ---- vm.js ----
// vm — Node 20's "VM" (Virtual Machine) module.
//
// Real Node uses V8's vm.runInContext / runInNewContext to run JS
// in a separate context. Burn IS a JS sandbox already (everything
// runs inside one) — there's no nested-context boundary to cross.
// We give callers a Node-compatible surface that uses `eval` /
// fresh evaluation contexts where possible.
//
// Trade-offs vs Node:
//   * `runInThisContext(code)` does what `eval(code)` would, in the
//     current global. Same scope as Node's variant.
//   * `runInNewContext(code, sandbox)` evaluates `code` in a
//     standalone object so writes don't leak to the caller's globals.
//     QuickJS doesn't expose first-class context creation from JS,
//     so we approximate by wrapping the code in `(function() { ... }).call(sandbox)`
//     — `this` becomes the sandbox object, top-level `var` ends up
//     on the sandbox via `with()`-like rebinding.
//   * `Script` class supports `runInThisContext` / `runInNewContext`.
//   * `compileFunction(...)` is implemented via Function constructor.

__register_module('vm', function(module, exports, require) {

    function isContext(obj) {
        // A "vm context" in Node is a sandbox object. We mark
        // objects as contexts via a Symbol so `isContext` is stable.
        return !!(obj && obj.__ab_vm_context === true);
    }

    function createContext(sandbox, options) {
        sandbox = sandbox || {};
        // Mark as a vm context so isContext() recognizes it.
        Object.defineProperty(sandbox, '__ab_vm_context', {
            value: true,
            enumerable: false,
            configurable: false,
            writable: false,
        });
        var _ = options;
        return sandbox;
    }

    function runInThisContext(code, options) {
        var _ = options;
        // No isolation — same context as the caller. Spec-compatible.
        return (0, eval)(String(code));
    }

    /// `runInNewContext` evaluates `code` against a fresh object so
    /// writes to top-level identifiers land on `sandbox`, not on
    /// `globalThis`. QuickJS lacks first-class contexts, so we
    /// approximate via an IIFE bound to the sandbox + `with()` for
    /// transparent identifier resolution.
    function runInNewContext(code, sandbox, options) {
        sandbox = sandbox || {};
        if (!isContext(sandbox)) {
            // Auto-context the sandbox the first time.
            createContext(sandbox);
        }
        var _ = options;
        // Use `eval` inside `with(sandbox)` so the completion value
        // of the script comes back to the caller — matches Node's
        // V8-eval semantics where `runInNewContext('1+2', {})` is
        // `3`. `with` is the only construct that makes top-level
        // identifier lookups resolve against `sandbox` first; eval's
        // completion value is the final-expression value, same as
        // Node.
        var wrapper = new Function(
            '__ab_sandbox__', '__ab_code__',
            'with (__ab_sandbox__) { return eval(__ab_code__); }'
        );
        return wrapper(sandbox, String(code));
    }

    function runInContext(code, ctx, options) {
        if (!isContext(ctx)) {
            throw new TypeError(
                'vm.runInContext: contextifiedObject must be a context (call vm.createContext first)'
            );
        }
        return runInNewContext(code, ctx, options);
    }

    function compileFunction(code, params, options) {
        var args = (params || []).slice();
        args.push(String(code));
        return new (Function.prototype.bind.apply(Function, [null].concat(args)));
    }

    // ---- Script class --------------------------------------------

    function Script(code, options) {
        if (!(this instanceof Script)) return new Script(code, options);
        this.code = String(code);
        this._options = options || {};
        // Pre-compile at construction time so syntax errors throw
        // immediately, matching Node's spec.
        try {
            new Function(this.code);
        } catch (e) {
            throw e;
        }
    }
    Script.prototype.runInThisContext = function(options) {
        return runInThisContext(this.code, options);
    };
    Script.prototype.runInContext = function(ctx, options) {
        return runInContext(this.code, ctx, options);
    };
    Script.prototype.runInNewContext = function(sandbox, options) {
        return runInNewContext(this.code, sandbox, options);
    };
    Script.prototype.createCachedData = function() {
        // No bytecode caching surface from QuickJS to JS.
        return Buffer ? Buffer.alloc(0) : new Uint8Array(0);
    };

    // ---- Module / SourceTextModule / SyntheticModule -------------
    //
    // ES module records inside vm. Lifecycle: unlinked → linking →
    // linked → evaluating → evaluated (or errored). Lowered to CJS
    // shape via the host TS / ESM transpile hook so the body can run
    // through `new Function` with a custom dependency map.

    var ABSTRACT_MODULE_BASE = function() {};

    function _lowerEsm(source, identifier) {
        var hook = globalThis.__host_ts_transpile;
        if (typeof hook !== 'function') {
            throw new Error('vm.SourceTextModule: ESM lowering requires the '
                + '`ts` cargo feature (or any build that enables '
                + '__host_ts_transpile)');
        }
        var path = '/__vm_module__/' + identifier + '.mjs';
        var lowered = hook(source, path);
        if (typeof lowered === 'string' && lowered.indexOf('__HOST_ERR__:') === 0) {
            throw new SyntaxError(lowered.slice('__HOST_ERR__:'.length));
        }
        return String(lowered);
    }

    /// Top-level `require('xxx')` calls in the lowered body become
    /// dep-map lookups. We swap them out at evaluate-time so the body
    /// can be re-evaluated against different linker resolutions
    /// (matches Node's vm.SourceTextModule semantics where each link
    /// → evaluate cycle binds fresh imports).
    var _REQUIRE_RX = /require\(\s*['"]([^'"]+)['"]\s*\)/g;
    function _scanSpecifiers(body) {
        var seen = Object.create(null);
        var out = [];
        var m;
        _REQUIRE_RX.lastIndex = 0;
        while ((m = _REQUIRE_RX.exec(body)) !== null) {
            if (!seen[m[1]]) {
                seen[m[1]] = true;
                out.push(m[1]);
            }
        }
        return out;
    }
    function _rewriteRequiresToDepMap(body) {
        return body.replace(_REQUIRE_RX, function(_, spec) {
            return '__ab_stm_dep[' + JSON.stringify(spec) + ']';
        });
    }

    function SourceTextModule(source, options) {
        if (!(this instanceof SourceTextModule)) {
            throw new TypeError('Class constructor SourceTextModule cannot be invoked without new');
        }
        options = options || {};
        this._source = String(source);
        this.identifier = options.identifier || 'vm:source-text-module-' + (++_modCounter);
        this.context = options.context;
        this._status = 'unlinked';
        this._error = null;
        this._namespace = null;
        this._deps = Object.create(null);
        this._depNamespaces = Object.create(null);

        // Lower ESM body once at construction.
        this._cjsBody = _lowerEsm(this._source, this.identifier);
        this._dependencySpecifiers = _scanSpecifiers(this._cjsBody);
    }
    var _modCounter = 0;

    SourceTextModule.prototype = Object.create(ABSTRACT_MODULE_BASE.prototype);
    SourceTextModule.prototype.constructor = SourceTextModule;

    Object.defineProperty(SourceTextModule.prototype, 'status', {
        get: function() { return this._status; },
    });
    Object.defineProperty(SourceTextModule.prototype, 'error', {
        get: function() {
            if (this._status !== 'errored') {
                throw new Error('Module status is ' + this._status + ', not errored');
            }
            return this._error;
        },
    });
    Object.defineProperty(SourceTextModule.prototype, 'namespace', {
        get: function() {
            if (this._status !== 'linked' && this._status !== 'evaluating'
                && this._status !== 'evaluated') {
                throw new Error('Module namespace requested before link()');
            }
            return this._namespace;
        },
    });
    Object.defineProperty(SourceTextModule.prototype, 'dependencySpecifiers', {
        get: function() { return this._dependencySpecifiers.slice(); },
    });

    /// Build a live-binding namespace proxy whose property reads
    /// forward to `dep._namespace` at access time. With cyclic graphs
    /// the dep's namespace fills in as evaluation walks the SCC, so
    /// late-bound reads (inside function bodies that fire after the
    /// cycle finishes evaluating) see the post-evaluate values.
    /// Plain (non-Module) deps fall back to snapshot semantics —
    /// nothing to track over time.
    function _liveNamespace(dep) {
        if (!(dep instanceof ABSTRACT_MODULE_BASE)) {
            return dep;
        }
        return new Proxy(Object.create(null), {
            get: function(_target, key) {
                var ns = dep._namespace;
                if (ns == null) return undefined;
                return ns[key];
            },
            has: function(_target, key) {
                var ns = dep._namespace;
                return !!ns && (key in ns);
            },
            ownKeys: function() {
                var ns = dep._namespace;
                return ns ? Object.keys(ns) : [];
            },
            getOwnPropertyDescriptor: function(_t, key) {
                var ns = dep._namespace;
                if (!ns || !(key in ns)) return undefined;
                return {
                    enumerable: true,
                    configurable: true,
                    writable: false,
                    value: ns[key],
                };
            },
        });
    }

    SourceTextModule.prototype.link = function(linker) {
        var self = this;
        if (typeof linker !== 'function') {
            return Promise.reject(new TypeError('linker must be a function'));
        }
        if (self._status !== 'unlinked') {
            return Promise.reject(new Error(
                'Module status is ' + self._status + ', expected unlinked'));
        }
        return self._linkInternal(linker, /*visited=*/ Object.create(null));
    };

    /// Worker that walks the dependency graph with cycle detection.
    /// `visited` is a per-link-call identity map — keyed by module
    /// identifier — that records every module we've already entered.
    /// When the linker resolves a spec to a module already in
    /// `visited`, we skip the recursive `link()` call (the back-edge
    /// is satisfied) and stash a live-binding namespace proxy so
    /// post-evaluate reads still see the populated exports.
    SourceTextModule.prototype._linkInternal = function(linker, visited) {
        var self = this;
        if (visited[self.identifier]) {
            // Already entered through another path — the caller's
            // ancestor will finish linking us.
            return Promise.resolve();
        }
        visited[self.identifier] = true;
        self._status = 'linking';
        // Pre-allocate the namespace placeholder so live-binding
        // proxies built for back-edges have a stable target. The
        // exports populate during evaluate().
        if (self._namespace == null) self._namespace = Object.create(null);

        var specs = self._dependencySpecifiers.slice();
        var i = 0;
        function next() {
            if (i >= specs.length) {
                self._status = 'linked';
                return undefined;
            }
            var spec = specs[i++];
            return Promise.resolve(linker(spec, self, { assert: {} }))
                .then(function(dep) {
                    if (dep == null) {
                        throw new Error('linker returned null for ' + spec);
                    }
                    self._deps[spec] = dep;
                    self._depNamespaces[spec] = _liveNamespace(dep);
                    if (dep instanceof ABSTRACT_MODULE_BASE
                        && dep._status === 'unlinked'
                        && !visited[dep.identifier]) {
                        return Promise.resolve(dep._linkInternal(linker, visited))
                            .then(next);
                    }
                    return next();
                });
        }
        return Promise.resolve().then(next);
    };

    SourceTextModule.prototype.evaluate = function(_options) {
        return this._evaluateInternal(/*visited=*/ Object.create(null));
    };

    /// Cycle-aware evaluator. `visited` is shared across recursive
    /// `evaluate` walks so a back-edge (B depends on A while A is
    /// `'evaluating'`) doesn't re-enter A's body. Cyclic deps see
    /// each other through the live-binding proxy installed at link
    /// time: their namespace property reads forward to whichever
    /// module finishes its body first.
    SourceTextModule.prototype._evaluateInternal = function(visited) {
        var self = this;
        if (self._status === 'evaluated') return Promise.resolve(undefined);
        if (self._status === 'evaluating') {
            // Back-edge in a cycle. The ancestor's evaluate() will
            // complete our population once its own body returns.
            return Promise.resolve(undefined);
        }
        if (self._status !== 'linked') {
            return Promise.reject(new Error(
                'Module status is ' + self._status + ', expected linked'));
        }
        if (visited[self.identifier]) {
            // Already in the recursion frame — same condition as the
            // 'evaluating' check above but re-stated for graphs that
            // mix link/evaluate calls non-monotonically.
            return Promise.resolve(undefined);
        }
        visited[self.identifier] = true;
        self._status = 'evaluating';
        return new Promise(function(resolve, reject) {
            try {
                var depKeys = Object.keys(self._deps);
                var i = 0;
                function evalNext() {
                    if (i >= depKeys.length) return runBody();
                    var dep = self._deps[depKeys[i++]];
                    if (dep instanceof ABSTRACT_MODULE_BASE
                        && dep._status === 'linked') {
                        return dep._evaluateInternal(visited).then(evalNext);
                    }
                    return evalNext();
                }
                function runBody() {
                    var body = _rewriteRequiresToDepMap(self._cjsBody);
                    var moduleObj = { exports: self._namespace || Object.create(null) };
                    var fn = new Function(
                        '__ab_stm_dep', 'module', 'exports', '__filename', '__dirname',
                        body
                    );
                    fn(self._depNamespaces, moduleObj, moduleObj.exports,
                       '/__vm_module__/' + self.identifier + '.mjs',
                       '/__vm_module__');
                    var actualExports = moduleObj.exports;
                    // Reuse the namespace placeholder allocated at
                    // link time so any live-binding Proxy already
                    // pointing at it continues to resolve. We freeze
                    // post-population — cyclic deps populate their
                    // own namespaces during their own evaluate frame,
                    // so by the time control returns to user code
                    // every module in the cycle has run its body.
                    var ns = self._namespace;
                    if (actualExports && typeof actualExports === 'object') {
                        var keys = Object.keys(actualExports);
                        for (var j = 0; j < keys.length; j++) {
                            ns[keys[j]] = actualExports[keys[j]];
                        }
                        if ('default' in actualExports && !('default' in ns)) {
                            ns['default'] = actualExports['default'];
                        }
                    } else if (actualExports !== undefined) {
                        ns['default'] = actualExports;
                    }
                    Object.freeze(ns);
                    self._status = 'evaluated';
                    resolve(undefined);
                }
                Promise.resolve().then(evalNext).catch(function(e) {
                    self._status = 'errored';
                    self._error = e;
                    reject(e);
                });
            } catch (e) {
                self._status = 'errored';
                self._error = e;
                reject(e);
            }
        });
    };

    SourceTextModule.prototype.createCachedData = function() {
        // No bytecode caching surface exposed from QuickJS to JS.
        return Buffer.alloc(0);
    };

    /// `vm.SyntheticModule(exportNames, evaluateCallback, options)` —
    /// a module whose body is a JS callback that calls
    /// `setExport(name, value)` for each named export. Used by hosts
    /// embedding non-JS data as ESM (CSS imports, JSON modules).
    function SyntheticModule(exportNames, evaluateCallback, options) {
        if (!(this instanceof SyntheticModule)) {
            throw new TypeError('Class constructor SyntheticModule cannot be invoked without new');
        }
        options = options || {};
        if (!Array.isArray(exportNames)) {
            throw new TypeError('exportNames must be an array of strings');
        }
        if (typeof evaluateCallback !== 'function') {
            throw new TypeError('evaluateCallback must be a function');
        }
        this.identifier = options.identifier || 'vm:synthetic-module-' + (++_modCounter);
        this.context = options.context;
        this._status = 'unlinked';
        this._error = null;
        this._exportNames = exportNames.slice();
        this._evaluateCallback = evaluateCallback;
        this._exports = Object.create(null);
        this._namespace = null;
        this._dependencySpecifiers = [];
    }
    SyntheticModule.prototype = Object.create(ABSTRACT_MODULE_BASE.prototype);
    SyntheticModule.prototype.constructor = SyntheticModule;

    Object.defineProperty(SyntheticModule.prototype, 'status', {
        get: function() { return this._status; },
    });
    Object.defineProperty(SyntheticModule.prototype, 'error', {
        get: function() {
            if (this._status !== 'errored') {
                throw new Error('Module status is ' + this._status + ', not errored');
            }
            return this._error;
        },
    });
    Object.defineProperty(SyntheticModule.prototype, 'namespace', {
        get: function() {
            if (this._status !== 'linked' && this._status !== 'evaluating'
                && this._status !== 'evaluated') {
                throw new Error('Module namespace requested before link()');
            }
            return this._namespace;
        },
    });
    Object.defineProperty(SyntheticModule.prototype, 'dependencySpecifiers', {
        get: function() { return []; },
    });

    SyntheticModule.prototype.link = function(_linker) {
        if (this._status !== 'unlinked') {
            return Promise.reject(new Error(
                'Module status is ' + this._status + ', expected unlinked'));
        }
        this._status = 'linked';
        // Pre-allocate the namespace bag with `undefined` for each name
        // so callers can probe `module.namespace.foo` without throwing.
        this._namespace = Object.create(null);
        for (var i = 0; i < this._exportNames.length; i++) {
            this._namespace[this._exportNames[i]] = undefined;
        }
        return Promise.resolve();
    };

    SyntheticModule.prototype.setExport = function(name, value) {
        if (this._exportNames.indexOf(name) < 0) {
            throw new Error('SyntheticModule.setExport: unknown export name ' + name);
        }
        this._exports[name] = value;
        if (this._namespace && Object.isExtensible(this._namespace)) {
            this._namespace[name] = value;
        }
    };

    SyntheticModule.prototype.evaluate = function() {
        if (this._status === 'evaluated') return Promise.resolve(undefined);
        if (this._status !== 'linked') {
            return Promise.reject(new Error(
                'Module status is ' + this._status + ', expected linked'));
        }
        this._status = 'evaluating';
        var self = this;
        try {
            var maybe = self._evaluateCallback.call(self);
            return Promise.resolve(maybe).then(function() {
                Object.freeze(self._namespace);
                self._status = 'evaluated';
            }, function(e) {
                self._status = 'errored';
                self._error = e;
                throw e;
            });
        } catch (e) {
            self._status = 'errored';
            self._error = e;
            return Promise.reject(e);
        }
    };

    exports.createContext = createContext;
    exports.isContext = isContext;
    exports.runInThisContext = runInThisContext;
    exports.runInNewContext = runInNewContext;
    exports.runInContext = runInContext;
    exports.compileFunction = compileFunction;
    exports.Script = Script;
    /// `vm.measureMemory` (Node 13.9+) returns a Promise resolving to
    /// V8's heap-stats snapshot. We don't have a real V8 measurement
    /// API, but we expose the canonical shape so probe-shaped libs
    /// (clinic, 0x) don't crash on init. The numbers come from
    /// `process.memoryUsage()` so they reflect real WASM heap pressure.
    exports.measureMemory = function(options) {
        var mode = (options && options.mode) || 'summary';
        var u = process.memoryUsage();
        return Promise.resolve({
            total: { jsMemoryEstimate: u.heapUsed, jsMemoryRange: [u.heapUsed, u.heapTotal] },
            current: mode === 'detailed'
                ? { jsMemoryEstimate: u.heapUsed, jsMemoryRange: [u.heapUsed, u.heapTotal] }
                : undefined,
            other: mode === 'detailed' ? [] : undefined,
        });
    };
    exports.SourceTextModule = SourceTextModule;
    exports.SyntheticModule = SyntheticModule;
    exports.Module = ABSTRACT_MODULE_BASE;
    exports.constants = {
        DONT_CONTEXTIFY: 0,
        USE_MAIN_CONTEXT_DEFAULT_LOADER: 1,
    };
});

// ---- wasi.js ----
// wasi — Node 20's WASI host. The plain `WebAssembly` polyfill
// already loads modules; this module gives callers the Node-shaped
// `WASI` class so `new WASI({...}).getImportObject()` works against
// our `WebAssembly.instantiate`.
//
// v1 supplies an empty import object — the WASM loader doesn't bridge
// user-defined imports yet, so a module that imports
// `wasi_snapshot_preview1` won't actually get satisfied. The class
// exists to keep `import { WASI } from 'wasi'` from breaking; runtime
// instantiation will surface a LinkError naming the missing import,
// which is the right place to learn what's still pending.

__register_module('wasi', function(module, exports, require) {

    function WASI(opts) {
        opts = opts || {};
        this.args = (opts.args || []).slice();
        this.env = Object.assign({}, opts.env || {});
        this.preopens = Object.assign({}, opts.preopens || {});
        this.returnOnExit = opts.returnOnExit !== false;
        this.version = opts.version || 'preview1';
        this._started = false;
    }

    WASI.prototype.getImportObject = function() {
        // Returns a sentinel object the WebAssembly.Instance shim
        // recognises and routes through `__host_wasm_run_wasi`. The
        // import map's `wasi_snapshot_preview1` entry is a marker
        // — the actual syscall bridge lives in wasmtime-wasi on the
        // host side, which the run_wasi flow links into a fresh Store.
        var self = this;
        return {
            wasi_snapshot_preview1: { __ab_wasi: self },
        };
    };

    function _runHostWasi(wasi, mod) {
        if (typeof globalThis.__host_wasm_run_wasi !== 'function') {
            throw new Error('WASI: host runner not available');
        }
        if (!mod || typeof mod._id !== 'number') {
            throw new TypeError(
                'WASI: argument must be a `WebAssembly.Module` (compile bytes first)'
            );
        }
        var cfg = JSON.stringify({
            args: wasi.args,
            env: wasi.env,
            preopens: wasi.preopens,
        });
        var code = globalThis.__host_wasm_run_wasi(mod._id, cfg);
        return code | 0;
    }

    /// `start(moduleOrInstance)` — runs the wasm module's `_start`
    /// export. Burn deviates from Node's exact instance-flow contract
    /// because WASI imports are bridged on the host (wasmtime-wasi);
    /// passing a Module directly is the supported path. Passing an
    /// already-instantiated Instance also works as long as the
    /// instance was created via `WebAssembly.instantiate(mod,
    /// wasi.getImportObject())` (we re-use the underlying module).
    WASI.prototype.start = function(arg) {
        if (this._started) {
            throw new Error('WASI.start: instance already started');
        }
        this._started = true;
        var mod;
        if (arg && typeof arg._id === 'number') {
            mod = arg;
        } else if (arg && arg._module && typeof arg._module._id === 'number') {
            mod = arg._module;
        } else {
            throw new TypeError(
                'WASI.start: argument must be a `WebAssembly.Module` or Instance'
            );
        }
        try {
            var code = _runHostWasi(this, mod);
            if (this.returnOnExit) return code;
            if (code !== 0) {
                var err = new Error('WASI exited with code ' + code);
                err.code = code;
                throw err;
            }
            return 0;
        } catch (e) {
            if (this.returnOnExit && e && typeof e.code === 'number') {
                return e.code;
            }
            throw e;
        }
    };

    /// `initialize(moduleOrInstance)` — runs the wasm module's
    /// `_initialize` export instead of `_start`. Spec-defined alt
    /// entry for "reactor" modules (libraries, not commands).
    WASI.prototype.initialize = function(_arg) {
        // For reactor modules, instantiation alone runs `_initialize`
        // — wasmtime-wasi's `add_to_linker_sync` plus instantiate is
        // sufficient. The host's run_wasi path includes that step,
        // so the most direct mapping is to no-op when the user calls
        // `initialize` after a sentinel-shaped Instance — the
        // initialization already happened during instantiation.
    };

    exports.WASI = WASI;
});

// ---- web_compat.js ----
// Small Web-API polyfills that most Node.js scripts now assume. Wired
// as globals, not modules, to match the browser/Node semantics.

(function installWebCompat() {
    // structuredClone — ES2022. QuickJS-NG typically has it; fall back
    // to a type-preserving deep-copy. Pure JSON round-trip flattens
    // Date / Map / Set / TypedArray / Buffer so we walk the graph by
    // hand for those, and fall back to JSON for plain objects.
    if (typeof globalThis.structuredClone !== 'function') {
        globalThis.structuredClone = function(value, _opts) {
            return _structuredCloneInner(value, new Map());
        };
        function _structuredCloneInner(v, seen) {
            if (v === null || typeof v !== 'object') return v;
            if (seen.has(v)) return seen.get(v);
            // Date
            if (v instanceof Date) { var d = new Date(v.getTime()); seen.set(v, d); return d; }
            // RegExp
            if (v instanceof RegExp) { var re = new RegExp(v.source, v.flags); seen.set(v, re); return re; }
            // ArrayBuffer
            if (v instanceof ArrayBuffer) {
                var ab = new ArrayBuffer(v.byteLength);
                new Uint8Array(ab).set(new Uint8Array(v));
                seen.set(v, ab);
                return ab;
            }
            // Typed arrays (preserves the constructor + offset/length)
            if (ArrayBuffer.isView(v) && !(v instanceof DataView)) {
                var TC = v.constructor;
                var copy = new TC(v.length);
                copy.set(v);
                seen.set(v, copy);
                return copy;
            }
            if (v instanceof DataView) {
                var ab2 = new ArrayBuffer(v.byteLength);
                new Uint8Array(ab2).set(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
                var dv = new DataView(ab2);
                seen.set(v, dv);
                return dv;
            }
            // Map
            if (v instanceof Map) {
                var mm = new Map();
                seen.set(v, mm);
                v.forEach(function(val, key) {
                    mm.set(_structuredCloneInner(key, seen), _structuredCloneInner(val, seen));
                });
                return mm;
            }
            // Set
            if (v instanceof Set) {
                var ss = new Set();
                seen.set(v, ss);
                v.forEach(function(val) { ss.add(_structuredCloneInner(val, seen)); });
                return ss;
            }
            // Error
            if (v instanceof Error) {
                var EC = v.constructor;
                var er = new EC(v.message);
                if (v.stack) er.stack = v.stack;
                seen.set(v, er);
                return er;
            }
            // Array
            if (Array.isArray(v)) {
                var ar = new Array(v.length);
                seen.set(v, ar);
                for (var i = 0; i < v.length; i++) ar[i] = _structuredCloneInner(v[i], seen);
                return ar;
            }
            // Plain object: walk keys.
            var out = {};
            seen.set(v, out);
            var keys = Object.keys(v);
            for (var k = 0; k < keys.length; k++) {
                out[keys[k]] = _structuredCloneInner(v[keys[k]], seen);
            }
            return out;
        }
    }

    // ---- Intl stubs (JS engine doesn't ship full ICU) ---------------
    //
    // Real Intl needs ICU, which QuickJS doesn't bundle. Most
    // libraries probe `typeof Intl !== 'undefined'` then call into
    // `Intl.NumberFormat` / `Intl.DateTimeFormat` / `Intl.Collator`.
    // We surface the constructors with English-only behavior so the
    // probe + canonical formatting paths work; non-English locales
    // fall back to ASCII formatting (caller can detect via
    // `resolvedOptions().locale === 'en-US'`).
    if (typeof globalThis.Intl !== 'object' || globalThis.Intl === null) {
        var IntlObj = {};
        function _toString(v) { return v == null ? '' : String(v); }

        function NumberFormat(locales, options) {
            if (!(this instanceof NumberFormat)) return new NumberFormat(locales, options);
            this._opts = options || {};
            this._locale = Array.isArray(locales) ? (locales[0] || 'en-US') : (locales || 'en-US');
        }
        NumberFormat.prototype.format = function(n) {
            n = Number(n);
            if (!isFinite(n)) {
                if (isNaN(n)) return 'NaN';
                return n > 0 ? '∞' : '-∞';
            }
            var opts = this._opts;
            // minimumFractionDigits / maximumFractionDigits.
            var min = opts.minimumFractionDigits;
            var max = opts.maximumFractionDigits;
            var fixed = (typeof max === 'number') ? max
                      : (typeof min === 'number') ? min
                      : undefined;
            var s = (typeof fixed === 'number') ? n.toFixed(fixed) : String(n);
            if (typeof min === 'number') {
                var dot = s.indexOf('.');
                var have = dot < 0 ? 0 : s.length - dot - 1;
                if (have < min) {
                    if (dot < 0) s += '.';
                    while (have < min) { s += '0'; have++; }
                }
            }
            // Group separators.
            if (opts.useGrouping !== false) {
                var sign = '';
                if (s.charAt(0) === '-') { sign = '-'; s = s.slice(1); }
                var dotIdx = s.indexOf('.');
                var int = dotIdx < 0 ? s : s.slice(0, dotIdx);
                var frac = dotIdx < 0 ? '' : s.slice(dotIdx);
                int = int.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                s = sign + int + frac;
            }
            // Style: percent / currency.
            if (opts.style === 'percent') s = (Number(n) * 100) + '%';
            else if (opts.style === 'currency' && opts.currency) {
                s = opts.currency + ' ' + s;
            }
            return s;
        };
        NumberFormat.prototype.formatToParts = function(n) {
            return [{ type: 'integer', value: this.format(n) }];
        };
        NumberFormat.prototype.resolvedOptions = function() {
            return Object.assign({ locale: this._locale, numberingSystem: 'latn' }, this._opts);
        };
        NumberFormat.supportedLocalesOf = function(locales) {
            return Array.isArray(locales) ? locales.slice() : [locales].filter(Boolean);
        };
        IntlObj.NumberFormat = NumberFormat;

        function DateTimeFormat(locales, options) {
            if (!(this instanceof DateTimeFormat)) return new DateTimeFormat(locales, options);
            this._opts = options || {};
            this._locale = Array.isArray(locales) ? (locales[0] || 'en-US') : (locales || 'en-US');
        }
        DateTimeFormat.prototype.format = function(d) {
            var date = (d instanceof Date) ? d : new Date(d);
            // Default: locale-style date+time.
            return date.toLocaleString
                ? date.toLocaleString(this._locale)
                : date.toString();
        };
        DateTimeFormat.prototype.formatToParts = function(d) {
            return [{ type: 'literal', value: this.format(d) }];
        };
        DateTimeFormat.prototype.resolvedOptions = function() {
            return Object.assign({ locale: this._locale, calendar: 'gregory',
                                   timeZone: 'UTC', numberingSystem: 'latn' }, this._opts);
        };
        DateTimeFormat.supportedLocalesOf = NumberFormat.supportedLocalesOf;
        IntlObj.DateTimeFormat = DateTimeFormat;

        function Collator(locales, options) {
            if (!(this instanceof Collator)) return new Collator(locales, options);
            this._opts = options || {};
            this._locale = Array.isArray(locales) ? (locales[0] || 'en-US') : (locales || 'en-US');
        }
        Collator.prototype.compare = function(a, b) {
            a = _toString(a); b = _toString(b);
            if (this._opts.sensitivity === 'base') {
                a = a.toLowerCase(); b = b.toLowerCase();
            }
            if (this._opts.numeric) {
                return a.localeCompare(b, undefined, { numeric: true });
            }
            return a < b ? -1 : a > b ? 1 : 0;
        };
        Collator.prototype.resolvedOptions = function() {
            return Object.assign({ locale: this._locale, sensitivity: 'variant',
                                   numeric: false, caseFirst: 'false' }, this._opts);
        };
        Collator.supportedLocalesOf = NumberFormat.supportedLocalesOf;
        IntlObj.Collator = Collator;

        function PluralRules(locales, options) {
            if (!(this instanceof PluralRules)) return new PluralRules(locales, options);
            this._opts = options || {};
            this._locale = Array.isArray(locales) ? (locales[0] || 'en-US') : (locales || 'en-US');
        }
        PluralRules.prototype.select = function(n) {
            // English-only: 1 → one, anything else → other.
            return n === 1 ? 'one' : 'other';
        };
        PluralRules.prototype.resolvedOptions = function() {
            return Object.assign({ locale: this._locale, type: 'cardinal',
                                   pluralCategories: ['one', 'other'] }, this._opts);
        };
        PluralRules.supportedLocalesOf = NumberFormat.supportedLocalesOf;
        IntlObj.PluralRules = PluralRules;

        function ListFormat(locales, options) {
            if (!(this instanceof ListFormat)) return new ListFormat(locales, options);
            this._opts = options || {};
            this._locale = Array.isArray(locales) ? (locales[0] || 'en-US') : (locales || 'en-US');
        }
        ListFormat.prototype.format = function(arr) {
            arr = Array.from(arr || []).map(_toString);
            if (arr.length === 0) return '';
            if (arr.length === 1) return arr[0];
            if (arr.length === 2) return arr[0] + ' and ' + arr[1];
            return arr.slice(0, -1).join(', ') + ', and ' + arr[arr.length - 1];
        };
        ListFormat.prototype.formatToParts = function(arr) {
            return [{ type: 'literal', value: this.format(arr) }];
        };
        ListFormat.prototype.resolvedOptions = function() {
            return Object.assign({ locale: this._locale, type: 'conjunction', style: 'long' }, this._opts);
        };
        ListFormat.supportedLocalesOf = NumberFormat.supportedLocalesOf;
        IntlObj.ListFormat = ListFormat;

        function RelativeTimeFormat(locales, options) {
            if (!(this instanceof RelativeTimeFormat)) return new RelativeTimeFormat(locales, options);
            this._opts = options || {};
            this._locale = Array.isArray(locales) ? (locales[0] || 'en-US') : (locales || 'en-US');
        }
        RelativeTimeFormat.prototype.format = function(value, unit) {
            if (value === 0) return 'this ' + unit;
            var abs = Math.abs(value);
            var u = unit + (abs === 1 ? '' : 's');
            return value > 0
                ? 'in ' + abs + ' ' + u
                : abs + ' ' + u + ' ago';
        };
        RelativeTimeFormat.prototype.formatToParts = function(value, unit) {
            return [{ type: 'literal', value: this.format(value, unit) }];
        };
        RelativeTimeFormat.prototype.resolvedOptions = function() {
            return Object.assign({ locale: this._locale, style: 'long', numeric: 'always' }, this._opts);
        };
        RelativeTimeFormat.supportedLocalesOf = NumberFormat.supportedLocalesOf;
        IntlObj.RelativeTimeFormat = RelativeTimeFormat;

        function Segmenter(locales, options) {
            if (!(this instanceof Segmenter)) return new Segmenter(locales, options);
            this._opts = options || {};
            this._locale = Array.isArray(locales) ? (locales[0] || 'en-US') : (locales || 'en-US');
        }
        Segmenter.prototype.segment = function(input) {
            var s = _toString(input);
            var granularity = (this._opts && this._opts.granularity) || 'grapheme';
            var segments;
            if (granularity === 'word') {
                segments = s.match(/\S+|\s+/g) || [];
            } else if (granularity === 'sentence') {
                segments = s.match(/[^.!?]+[.!?]?/g) || [s];
            } else {
                // grapheme: code-point chunks (close enough for ASCII).
                segments = Array.from(s);
            }
            var idx = 0;
            return {
                [Symbol.iterator]: function() {
                    var i = 0;
                    return { next: function() {
                        if (i >= segments.length) return { done: true };
                        var seg = segments[i];
                        var ent = { segment: seg, index: idx, input: s };
                        idx += seg.length;
                        i++;
                        return { value: ent, done: false };
                    } };
                },
            };
        };
        Segmenter.prototype.resolvedOptions = function() {
            return Object.assign({ locale: this._locale, granularity: 'grapheme' }, this._opts);
        };
        Segmenter.supportedLocalesOf = NumberFormat.supportedLocalesOf;
        IntlObj.Segmenter = Segmenter;

        IntlObj.getCanonicalLocales = function(locales) {
            if (!locales) return [];
            return (Array.isArray(locales) ? locales : [locales]).map(_toString);
        };

        globalThis.Intl = IntlObj;
    }

    // ---- AsyncIterator global (Stage 3 / Node 22+) ----------------
    //
    // QuickJS provides `Iterator` natively but not `AsyncIterator`,
    // even though TC39 has it as a global constructor with a method
    // bag (map/filter/take/drop/toArray/forEach/some/every/find).
    // We synthesise it from the well-known
    // `%AsyncIteratorPrototype%` (every async generator inherits
    // from it) so `class X extends AsyncIterator { ... }` and
    // feature-detect probes work.
    if (typeof globalThis.AsyncIterator === 'undefined') {
        var asyncGenFn = (async function*() {})();
        var asyncIteratorProto = Object.getPrototypeOf(
            Object.getPrototypeOf(asyncGenFn));
        var AsyncIteratorCtor = function AsyncIterator() {
            if (new.target === AsyncIteratorCtor) {
                throw new TypeError(
                    'AsyncIterator is not a constructor; subclass it instead');
            }
        };
        AsyncIteratorCtor.prototype = asyncIteratorProto;
        AsyncIteratorCtor.from = function from(iterable) {
            if (iterable && typeof iterable[Symbol.asyncIterator] === 'function') {
                return iterable[Symbol.asyncIterator]();
            }
            if (iterable && typeof iterable[Symbol.iterator] === 'function') {
                var it = iterable[Symbol.iterator]();
                return (async function*() {
                    var step = it.next();
                    while (!step.done) { yield step.value; step = it.next(); }
                })();
            }
            throw new TypeError(
                'AsyncIterator.from: argument must be iterable or async iterable');
        };
        Object.defineProperty(globalThis, 'AsyncIterator', {
            value: AsyncIteratorCtor, writable: true, configurable: true,
        });
    }

    // ---- Iterator Helpers (Stage 3 / Node 22+) ---------------------
    //
    // ES2025 Iterator Helpers extend the `Iterator` global with
    // `from(iter)` static, plus `Iterator.prototype.{map, filter, take,
    // drop, reduce, toArray, forEach, every, some, find, flatMap}`.
    // We install the constructor if the engine doesn't ship one (QuickJS
    // is the realistic case) and patch the prototype every time so
    // older engine builds get the helpers too.
    (function installIteratorHelpers() {
        var IterCtor = globalThis.Iterator;
        if (typeof IterCtor !== 'function') {
            // Synthesize a prototype that any iterator object's
            // `Symbol.iterator` chain can hang off. The Stage 3 spec
            // uses `%IteratorPrototype%` — we materialise it from
            // a generator's prototype (every iterator engine ships
            // shares this object).
            var genProto = Object.getPrototypeOf(
                Object.getPrototypeOf((function*(){})())
            );
            IterCtor = function Iterator() {
                throw new TypeError('Iterator: not constructable');
            };
            IterCtor.prototype = genProto;
            try {
                Object.defineProperty(globalThis, 'Iterator', {
                    value: IterCtor, writable: true, configurable: true,
                });
            } catch (_) {}
        }
        var proto = IterCtor.prototype;
        if (!proto) return;

        function _wrap(generator) {
            // Wrap a generator in a fresh iterator object whose
            // prototype is the Iterator prototype so chained helpers
            // resolve correctly.
            var out = generator;
            try { Object.setPrototypeOf(out, proto); } catch (_) {}
            return out;
        }

        function _iterOf(value) {
            // Accept iterators (return them as-is) and iterables
            // (call Symbol.iterator). Matches the spec's
            // `GetIteratorFlattenable`.
            if (value == null) {
                throw new TypeError('Iterator.from: argument is nullish');
            }
            if (typeof value.next === 'function') return value;
            var it = value[Symbol.iterator];
            if (typeof it === 'function') return it.call(value);
            throw new TypeError('Iterator.from: argument is not iterable');
        }

        if (typeof IterCtor.from !== 'function') {
            IterCtor.from = function from(iterable) {
                var it = _iterOf(iterable);
                return _wrap((function*() {
                    var step = it.next();
                    while (!step.done) { yield step.value; step = it.next(); }
                })());
            };
        }

        function define(name, fn) {
            if (typeof proto[name] === 'function') return;
            try {
                Object.defineProperty(proto, name, {
                    value: fn, writable: true, configurable: true,
                });
            } catch (_) {}
        }

        define('map', function map(mapper) {
            if (typeof mapper !== 'function') {
                throw new TypeError('Iterator.map: mapper must be a function');
            }
            var src = this;
            return _wrap((function*() {
                var i = 0;
                var step = src.next();
                while (!step.done) {
                    yield mapper(step.value, i++);
                    step = src.next();
                }
            })());
        });

        define('filter', function filter(pred) {
            if (typeof pred !== 'function') {
                throw new TypeError('Iterator.filter: predicate must be a function');
            }
            var src = this;
            return _wrap((function*() {
                var i = 0;
                var step = src.next();
                while (!step.done) {
                    if (pred(step.value, i++)) yield step.value;
                    step = src.next();
                }
            })());
        });

        define('take', function take(limit) {
            limit = Number(limit);
            if (!Number.isFinite(limit) || limit < 0) {
                throw new RangeError('Iterator.take: limit must be a non-negative number');
            }
            limit = Math.floor(limit);
            var src = this;
            return _wrap((function*() {
                var n = 0;
                while (n < limit) {
                    var step = src.next();
                    if (step.done) return;
                    yield step.value;
                    n++;
                }
            })());
        });

        define('drop', function drop(limit) {
            limit = Number(limit);
            if (!Number.isFinite(limit) || limit < 0) {
                throw new RangeError('Iterator.drop: limit must be a non-negative number');
            }
            limit = Math.floor(limit);
            var src = this;
            return _wrap((function*() {
                var n = 0;
                var step = src.next();
                while (!step.done) {
                    if (n >= limit) yield step.value;
                    n++;
                    step = src.next();
                }
            })());
        });

        define('reduce', function reduce(reducer, initialValue) {
            if (typeof reducer !== 'function') {
                throw new TypeError('Iterator.reduce: reducer must be a function');
            }
            var acc;
            var i = 0;
            var step = this.next();
            if (arguments.length < 2) {
                if (step.done) {
                    throw new TypeError(
                        'Iterator.reduce: empty iterator with no initial value');
                }
                acc = step.value;
                step = this.next();
                i = 1;
            } else {
                acc = initialValue;
            }
            while (!step.done) {
                acc = reducer(acc, step.value, i++);
                step = this.next();
            }
            return acc;
        });

        define('toArray', function toArray() {
            var out = [];
            var step = this.next();
            while (!step.done) {
                out.push(step.value);
                step = this.next();
            }
            return out;
        });

        define('forEach', function forEach(fn) {
            if (typeof fn !== 'function') {
                throw new TypeError('Iterator.forEach: argument must be a function');
            }
            var i = 0;
            var step = this.next();
            while (!step.done) {
                fn(step.value, i++);
                step = this.next();
            }
        });

        define('every', function every(pred) {
            if (typeof pred !== 'function') {
                throw new TypeError('Iterator.every: predicate must be a function');
            }
            var i = 0;
            var step = this.next();
            while (!step.done) {
                if (!pred(step.value, i++)) return false;
                step = this.next();
            }
            return true;
        });

        define('some', function some(pred) {
            if (typeof pred !== 'function') {
                throw new TypeError('Iterator.some: predicate must be a function');
            }
            var i = 0;
            var step = this.next();
            while (!step.done) {
                if (pred(step.value, i++)) return true;
                step = this.next();
            }
            return false;
        });

        define('find', function find(pred) {
            if (typeof pred !== 'function') {
                throw new TypeError('Iterator.find: predicate must be a function');
            }
            var i = 0;
            var step = this.next();
            while (!step.done) {
                if (pred(step.value, i++)) return step.value;
                step = this.next();
            }
            return undefined;
        });

        define('flatMap', function flatMap(mapper) {
            if (typeof mapper !== 'function') {
                throw new TypeError('Iterator.flatMap: mapper must be a function');
            }
            var src = this;
            return _wrap((function*() {
                var i = 0;
                var step = src.next();
                while (!step.done) {
                    var sub = mapper(step.value, i++);
                    var inner = _iterOf(sub);
                    var s2 = inner.next();
                    while (!s2.done) { yield s2.value; s2 = inner.next(); }
                    step = src.next();
                }
            })());
        });
    })();

    // ---- JSON.rawJSON / isRawJSON (Stage 4, Node 21+) -------------
    //
    // `JSON.rawJSON(text)` returns a value that JSON.stringify
    // inlines verbatim — useful for embedding precomputed JSON
    // (BigInt strings, large arrays) without parse → stringify
    // re-encoding. We tag with a private symbol so `isRawJSON`
    // recognises the value, and provide `toJSON` so naive
    // serialisers (JSON.stringify without a replacer) still emit a
    // valid representation.
    if (typeof JSON.rawJSON !== 'function') {
        var RAW_JSON_TAG = Symbol.for('JSON.rawJSON.tag');
        Object.defineProperty(JSON, 'rawJSON', {
            value: function rawJSON(text) {
                var s = String(text);
                // Validate input is parseable JSON per spec.
                JSON.parse(s);
                var out = Object.create(null);
                Object.defineProperty(out, RAW_JSON_TAG, { value: true });
                Object.defineProperty(out, 'rawJSON', { value: s, enumerable: true });
                Object.defineProperty(out, 'toJSON', {
                    value: function() { return JSON.parse(s); },
                });
                return out;
            },
            writable: true, configurable: true,
        });
        Object.defineProperty(JSON, 'isRawJSON', {
            value: function isRawJSON(v) {
                return !!(v && typeof v === 'object' && v[RAW_JSON_TAG] === true);
            },
            writable: true, configurable: true,
        });
    }

    // ---- Symbol.dispose / Symbol.asyncDispose (Node 20+) ------------

    // performance.now — no monotonic clock inside the sandbox, but
    // Date.now gives us something non-decreasing for most practical
    // purposes. Hrtime-style scripts won't crash.
    if (typeof globalThis.performance !== 'object' || typeof globalThis.performance.now !== 'function') {
        globalThis.performance = globalThis.performance || {};
        globalThis.performance.now = function() { return Date.now(); };
    }
    // Fill the rest of the User Timing Level 3 surface (Node 16+).
    // `performance.mark/measure` keep an in-process buffer so libraries
    // that probe `getEntries*` work even though our `performance.now`
    // resolution is millisecond-grade. Real-time performance work
    // benefits from `perf_hooks` directly; these globals satisfy
    // structural probes.
    if (typeof globalThis.performance.timeOrigin !== 'number') {
        Object.defineProperty(globalThis.performance, 'timeOrigin', {
            value: Date.now(), enumerable: true, writable: false, configurable: false,
        });
    }
    if (!globalThis.performance._entries) globalThis.performance._entries = [];
    if (typeof globalThis.performance.mark !== 'function') {
        globalThis.performance.mark = function(name, options) {
            var entry = {
                name: String(name),
                entryType: 'mark',
                startTime: (options && typeof options.startTime === 'number')
                    ? options.startTime : globalThis.performance.now(),
                duration: 0,
                detail: options && options.detail,
            };
            globalThis.performance._entries.push(entry);
            return entry;
        };
    }
    if (typeof globalThis.performance.measure !== 'function') {
        globalThis.performance.measure = function(name, startMarkOrOpts, endMark) {
            var startTime = 0;
            var endTime = globalThis.performance.now();
            var detail;
            if (typeof startMarkOrOpts === 'string') {
                var startE = globalThis.performance._entries.find(function(e) {
                    return e.name === startMarkOrOpts && e.entryType === 'mark';
                });
                if (startE) startTime = startE.startTime;
            } else if (startMarkOrOpts && typeof startMarkOrOpts === 'object') {
                if (typeof startMarkOrOpts.start === 'number') startTime = startMarkOrOpts.start;
                if (typeof startMarkOrOpts.end === 'number') endTime = startMarkOrOpts.end;
                if (typeof startMarkOrOpts.duration === 'number') {
                    endTime = startTime + startMarkOrOpts.duration;
                }
                detail = startMarkOrOpts.detail;
            }
            if (typeof endMark === 'string') {
                var endE = globalThis.performance._entries.find(function(e) {
                    return e.name === endMark && e.entryType === 'mark';
                });
                if (endE) endTime = endE.startTime;
            }
            var entry = {
                name: String(name),
                entryType: 'measure',
                startTime: startTime,
                duration: endTime - startTime,
                detail: detail,
            };
            globalThis.performance._entries.push(entry);
            return entry;
        };
    }
    if (typeof globalThis.performance.clearMarks !== 'function') {
        globalThis.performance.clearMarks = function(name) {
            globalThis.performance._entries = globalThis.performance._entries.filter(function(e) {
                if (e.entryType !== 'mark') return true;
                return name !== undefined && e.name !== name;
            });
        };
    }
    if (typeof globalThis.performance.clearMeasures !== 'function') {
        globalThis.performance.clearMeasures = function(name) {
            globalThis.performance._entries = globalThis.performance._entries.filter(function(e) {
                if (e.entryType !== 'measure') return true;
                return name !== undefined && e.name !== name;
            });
        };
    }
    if (typeof globalThis.performance.getEntries !== 'function') {
        globalThis.performance.getEntries = function() {
            return globalThis.performance._entries.slice();
        };
    }
    if (typeof globalThis.performance.getEntriesByName !== 'function') {
        globalThis.performance.getEntriesByName = function(name, type) {
            return globalThis.performance._entries.filter(function(e) {
                if (e.name !== name) return false;
                if (type !== undefined && e.entryType !== type) return false;
                return true;
            });
        };
    }
    if (typeof globalThis.performance.getEntriesByType !== 'function') {
        globalThis.performance.getEntriesByType = function(type) {
            return globalThis.performance._entries.filter(function(e) { return e.entryType === type; });
        };
    }

    // ---- PerformanceObserver / PerformanceEntry classes -----------
    //
    // These let libraries subscribe to mark/measure events. The
    // observer fires synchronously after each mark/measure when its
    // observed entryTypes match.
    if (typeof globalThis.PerformanceEntry !== 'function') {
        function PerformanceEntry() {
            this.name = '';
            this.entryType = '';
            this.startTime = 0;
            this.duration = 0;
        }
        globalThis.PerformanceEntry = PerformanceEntry;
        globalThis.PerformanceMark = function PerformanceMark() {
            PerformanceEntry.call(this);
            this.entryType = 'mark';
        };
        globalThis.PerformanceMark.prototype = Object.create(PerformanceEntry.prototype);
        globalThis.PerformanceMeasure = function PerformanceMeasure() {
            PerformanceEntry.call(this);
            this.entryType = 'measure';
        };
        globalThis.PerformanceMeasure.prototype = Object.create(PerformanceEntry.prototype);
        function PerformanceObserverEntryList(entries) { this._entries = entries.slice(); }
        PerformanceObserverEntryList.prototype.getEntries = function() {
            return this._entries.slice();
        };
        PerformanceObserverEntryList.prototype.getEntriesByName = function(name, type) {
            return this._entries.filter(function(e) {
                return e.name === name && (type === undefined || e.entryType === type);
            });
        };
        PerformanceObserverEntryList.prototype.getEntriesByType = function(type) {
            return this._entries.filter(function(e) { return e.entryType === type; });
        };
        globalThis.PerformanceObserverEntryList = PerformanceObserverEntryList;
        function PerformanceObserver(callback) {
            this._callback = callback;
            this._types = [];
            this._buffered = false;
            this._cursor = globalThis.performance._entries.length;
        }
        if (!globalThis.performance._observers) globalThis.performance._observers = [];
        PerformanceObserver.prototype.observe = function(options) {
            var types = (options && options.entryTypes) || (options && options.type ? [options.type] : []);
            this._types = types.slice();
            this._buffered = !!(options && options.buffered);
            globalThis.performance._observers.push(this);
            // If buffered, replay pre-existing entries.
            if (this._buffered) {
                var self = this;
                var matching = globalThis.performance._entries.filter(function(e) {
                    return self._types.indexOf(e.entryType) >= 0;
                });
                if (matching.length) {
                    var list = new PerformanceObserverEntryList(matching);
                    Promise.resolve().then(function() { self._callback(list, self); });
                }
            }
        };
        PerformanceObserver.prototype.disconnect = function() {
            var idx = globalThis.performance._observers.indexOf(this);
            if (idx >= 0) globalThis.performance._observers.splice(idx, 1);
        };
        PerformanceObserver.prototype.takeRecords = function() {
            var since = globalThis.performance._entries.slice(this._cursor);
            this._cursor = globalThis.performance._entries.length;
            return since;
        };
        PerformanceObserver.supportedEntryTypes = ['mark', 'measure', 'resource', 'navigation'];
        globalThis.PerformanceObserver = PerformanceObserver;

        // Hook mark/measure to fan out to observers.
        var _origMark = globalThis.performance.mark;
        globalThis.performance.mark = function() {
            var entry = _origMark.apply(globalThis.performance, arguments);
            _fanout(entry);
            return entry;
        };
        var _origMeasure = globalThis.performance.measure;
        globalThis.performance.measure = function() {
            var entry = _origMeasure.apply(globalThis.performance, arguments);
            _fanout(entry);
            return entry;
        };
        function _fanout(entry) {
            var observers = globalThis.performance._observers;
            if (!observers || observers.length === 0) return;
            for (var i = 0; i < observers.length; i++) {
                var obs = observers[i];
                if (obs._types.indexOf(entry.entryType) < 0) continue;
                (function(o) {
                    Promise.resolve().then(function() {
                        var list = new PerformanceObserverEntryList([entry]);
                        try { o._callback(list, o); } catch (_) {}
                    });
                })(obs);
            }
        }
    }

    // `queueMicrotask` — schedule a microtask. QuickJS supports
    // Promise.then which gives us the microtask queue for free.
    if (typeof globalThis.queueMicrotask !== 'function') {
        globalThis.queueMicrotask = function(fn) {
            if (typeof fn !== 'function') throw new TypeError('callback must be a function');
            Promise.resolve().then(fn);
        };
    }

    // `TextEncoder` / `TextDecoder` — Web globals. Javy ships them when
    // built with `text_encoding(true)` (our WASM plugin does); native
    // rquickjs doesn't. Real npm packages (Express deps, undici, etc.)
    // probe these at module-load time and crash with `ReferenceError`
    // without them.
    //
    // Implementation note: do NOT route through `Buffer.toString` /
    // `Buffer.from(str, 'utf8')` here. Buffer's UTF-8 codec routes
    // back through these globals in some plenum paths, producing an
    // infinite recursion. The pure-JS encoder/decoder below is
    // self-contained and handles BMP + surrogate-paired astral
    // codepoints. Replacement char (`�`) for malformed sequences
    // when not in `fatal` mode (matches WHATWG spec).
    if (typeof globalThis.TextEncoder !== 'function') {
        globalThis.TextEncoder = function TextEncoder() {
            this.encoding = 'utf-8';
        };
        globalThis.TextEncoder.prototype.encode = function(input) {
            var s = input === undefined ? '' : String(input);
            // Worst case: 4 bytes per code unit (surrogate pair → 4-byte UTF-8).
            var out = new Uint8Array(s.length * 4);
            var n = 0;
            for (var i = 0; i < s.length; i++) {
                var c = s.charCodeAt(i);
                if (c >= 0xD800 && c <= 0xDBFF && i + 1 < s.length) {
                    var c2 = s.charCodeAt(i + 1);
                    if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
                        var cp = 0x10000 + (((c & 0x3FF) << 10) | (c2 & 0x3FF));
                        out[n++] = 0xF0 | (cp >> 18);
                        out[n++] = 0x80 | ((cp >> 12) & 0x3F);
                        out[n++] = 0x80 | ((cp >> 6) & 0x3F);
                        out[n++] = 0x80 | (cp & 0x3F);
                        i++;
                        continue;
                    }
                }
                if (c < 0x80) {
                    out[n++] = c;
                } else if (c < 0x800) {
                    out[n++] = 0xC0 | (c >> 6);
                    out[n++] = 0x80 | (c & 0x3F);
                } else {
                    out[n++] = 0xE0 | (c >> 12);
                    out[n++] = 0x80 | ((c >> 6) & 0x3F);
                    out[n++] = 0x80 | (c & 0x3F);
                }
            }
            return out.slice(0, n);
        };
        globalThis.TextEncoder.prototype.encodeInto = function(source, dest) {
            var encoded = this.encode(source);
            var n = Math.min(encoded.length, dest.length);
            for (var i = 0; i < n; i++) dest[i] = encoded[i];
            return { read: source.length, written: n };
        };
    }
    if (typeof globalThis.TextDecoder !== 'function') {
        globalThis.TextDecoder = function TextDecoder(label, options) {
            var enc = (label || 'utf-8').toLowerCase();
            if (enc === 'utf8') enc = 'utf-8';
            this.encoding = enc;
            this.fatal = !!(options && options.fatal);
            this.ignoreBOM = !!(options && options.ignoreBOM);
        };
        globalThis.TextDecoder.prototype.decode = function(input, _options) {
            if (input === undefined) return '';
            var bytes;
            if (input instanceof Uint8Array) {
                bytes = input;
            } else if (input instanceof ArrayBuffer) {
                bytes = new Uint8Array(input);
            } else if (input && typeof input.byteLength === 'number') {
                bytes = new Uint8Array(
                    input.buffer || input,
                    input.byteOffset || 0,
                    input.byteLength
                );
            } else {
                return '';
            }
            // Pure-JS UTF-8 decode. Doesn't route through Buffer to
            // avoid recursion when Buffer's own codec calls back here.
            var s = '';
            var i = 0;
            while (i < bytes.length) {
                var b1 = bytes[i++];
                if (b1 < 0x80) {
                    s += String.fromCharCode(b1);
                } else if (b1 < 0xC0) {
                    s += '�';
                } else if (b1 < 0xE0) {
                    var b2 = bytes[i++] || 0;
                    s += String.fromCharCode(((b1 & 0x1F) << 6) | (b2 & 0x3F));
                } else if (b1 < 0xF0) {
                    var b2c = bytes[i++] || 0;
                    var b3 = bytes[i++] || 0;
                    s += String.fromCharCode(
                        ((b1 & 0x0F) << 12) | ((b2c & 0x3F) << 6) | (b3 & 0x3F)
                    );
                } else {
                    var b2d = bytes[i++] || 0;
                    var b3d = bytes[i++] || 0;
                    var b4 = bytes[i++] || 0;
                    var cp =
                        ((b1 & 0x07) << 18) |
                        ((b2d & 0x3F) << 12) |
                        ((b3d & 0x3F) << 6) |
                        (b4 & 0x3F);
                    cp -= 0x10000;
                    s += String.fromCharCode(
                        0xD800 + (cp >> 10),
                        0xDC00 + (cp & 0x3FF)
                    );
                }
            }
            return s;
        };
    }

    // `btoa` / `atob` — base64 encoders. QuickJS doesn't ship these.
    if (typeof globalThis.btoa !== 'function') {
        globalThis.btoa = function(str) {
            var Buffer = require('buffer').Buffer;
            return Buffer.from(String(str), 'binary').toString('base64');
        };
    }
    if (typeof globalThis.atob !== 'function') {
        globalThis.atob = function(b64) {
            var Buffer = require('buffer').Buffer;
            return Buffer.from(String(b64), 'base64').toString('binary');
        };
    }

    // Node 20 LTS globals exposed without `require`:
    //   * `Buffer`           — global since v0.x.
    //   * `global`           — alias to globalThis since v12.
    //   * `URL` / `URLSearchParams` — global since v10.
    if (typeof globalThis.Buffer !== 'function') {
        globalThis.Buffer = require('buffer').Buffer;
    }
    if (typeof globalThis.global !== 'object') {
        globalThis.global = globalThis;
    }

    // ----- EventTarget / Event / CustomEvent ------------------------
    // Node 15 made these globals; nearly every modern web-API
    // building block (AbortSignal, MessagePort, the streams family)
    // either extends EventTarget or fires Events through it. Anything
    // that does `class X extends EventTarget {}` falls over without
    // a real constructor, even when the extending code never actually
    // dispatches an event.
    if (typeof globalThis.Event !== 'function') {
        var Event = function Event(type, init) {
            init = init || {};
            this.type = String(type);
            this.bubbles = !!init.bubbles;
            this.cancelable = !!init.cancelable;
            this.composed = !!init.composed;
            this.defaultPrevented = false;
            this.timeStamp = Date.now();
            this.target = null;
            this.currentTarget = null;
            this.eventPhase = 0;
            this.isTrusted = false;
            this._propagationStopped = false;
            this._immediatePropagationStopped = false;
        };
        Event.prototype.preventDefault = function() {
            if (this.cancelable) this.defaultPrevented = true;
        };
        Event.prototype.stopPropagation = function() { this._propagationStopped = true; };
        Event.prototype.stopImmediatePropagation = function() {
            this._propagationStopped = true;
            this._immediatePropagationStopped = true;
        };
        Event.prototype.composedPath = function() { return []; };
        Event.NONE = 0; Event.CAPTURING_PHASE = 1; Event.AT_TARGET = 2; Event.BUBBLING_PHASE = 3;
        globalThis.Event = Event;
    }
    if (typeof globalThis.CustomEvent !== 'function') {
        globalThis.CustomEvent = function CustomEvent(type, init) {
            globalThis.Event.call(this, type, init);
            this.detail = init && 'detail' in init ? init.detail : null;
        };
        globalThis.CustomEvent.prototype = Object.create(globalThis.Event.prototype);
        globalThis.CustomEvent.prototype.constructor = globalThis.CustomEvent;
    }
    if (typeof globalThis.EventTarget !== 'function') {
        var EventTarget = function EventTarget() { this._listeners = {}; };
        EventTarget.prototype.addEventListener = function(type, listener, _options) {
            if (!this._listeners) this._listeners = {};
            (this._listeners[type] = this._listeners[type] || []).push(listener);
        };
        EventTarget.prototype.removeEventListener = function(type, listener) {
            if (!this._listeners || !this._listeners[type]) return;
            var arr = this._listeners[type];
            for (var i = arr.length - 1; i >= 0; i--) {
                if (arr[i] === listener) arr.splice(i, 1);
            }
        };
        EventTarget.prototype.dispatchEvent = function(event) {
            if (!event || typeof event.type !== 'string') {
                throw new TypeError('dispatchEvent: argument must be an Event');
            }
            event.target = this;
            event.currentTarget = this;
            event.eventPhase = 2; // AT_TARGET
            var arr = (this._listeners && this._listeners[event.type]) || [];
            for (var i = 0; i < arr.length; i++) {
                if (event._immediatePropagationStopped) break;
                try {
                    var fn = arr[i];
                    if (typeof fn === 'function') fn.call(this, event);
                    else if (fn && typeof fn.handleEvent === 'function') fn.handleEvent(event);
                } catch (e) {
                    // Swallow per Web spec — an exceptional handler
                    // shouldn't prevent siblings from firing. Surface
                    // via the runtime's error reporting path.
                    if (typeof globalThis.queueMicrotask === 'function') {
                        globalThis.queueMicrotask(function() { throw e; });
                    }
                }
            }
            event.eventPhase = 0;
            return !event.defaultPrevented;
        };
        globalThis.EventTarget = EventTarget;
    }

    // ----- DOMException ---------------------------------------------
    // Used by AbortController.abort() (DOMException 'AbortError'),
    // various Streams APIs, and Cache/IndexedDB shims. Most callers
    // construct it as `new DOMException(message, name)` and read
    // `.name` to discriminate error types.
    if (typeof globalThis.DOMException !== 'function') {
        var DOMException = function DOMException(message, name) {
            this.message = message === undefined ? '' : String(message);
            this.name = name === undefined ? 'Error' : String(name);
            // .code: legacy numeric. 0 if name doesn't map.
            var legacy = {
                IndexSizeError: 1, HierarchyRequestError: 3, WrongDocumentError: 4,
                InvalidCharacterError: 5, NoModificationAllowedError: 7,
                NotFoundError: 8, NotSupportedError: 9, InUseAttributeError: 10,
                InvalidStateError: 11, SyntaxError: 12, InvalidModificationError: 13,
                NamespaceError: 14, InvalidAccessError: 15, SecurityError: 18,
                NetworkError: 19, AbortError: 20, URLMismatchError: 21,
                QuotaExceededError: 22, TimeoutError: 23, InvalidNodeTypeError: 24,
                DataCloneError: 25,
            };
            this.code = legacy[this.name] || 0;
            // Stack trace via Error to make it inspectable.
            try { Error.captureStackTrace(this, DOMException); }
            catch (_) { this.stack = (new Error(this.message)).stack; }
        };
        DOMException.prototype = Object.create(Error.prototype);
        DOMException.prototype.constructor = DOMException;
        DOMException.prototype.toString = function() { return this.name + ': ' + this.message; };
        // Static legacy code constants on the constructor.
        var codes = ['INDEX_SIZE_ERR','DOMSTRING_SIZE_ERR','HIERARCHY_REQUEST_ERR','WRONG_DOCUMENT_ERR','INVALID_CHARACTER_ERR','NO_DATA_ALLOWED_ERR','NO_MODIFICATION_ALLOWED_ERR','NOT_FOUND_ERR','NOT_SUPPORTED_ERR','INUSE_ATTRIBUTE_ERR','INVALID_STATE_ERR','SYNTAX_ERR','INVALID_MODIFICATION_ERR','NAMESPACE_ERR','INVALID_ACCESS_ERR','VALIDATION_ERR','TYPE_MISMATCH_ERR','SECURITY_ERR','NETWORK_ERR','ABORT_ERR','URL_MISMATCH_ERR','QUOTA_EXCEEDED_ERR','TIMEOUT_ERR','INVALID_NODE_TYPE_ERR','DATA_CLONE_ERR'];
        for (var ci = 0; ci < codes.length; ci++) DOMException[codes[ci]] = ci + 1;
        globalThis.DOMException = DOMException;
    }

    // ----- Blob / File / FormData -----------------------------------
    // Node 18+ globals. node-fetch / undici-style clients construct
    // Blobs to wrap response bodies; multer / form-data libraries
    // build FormData. Buffer-backed implementations — covers the API
    // shape; binary streaming is best-effort sync.
    if (typeof globalThis.Blob !== 'function') {
        var Blob = function Blob(parts, options) {
            options = options || {};
            this.type = options.type ? String(options.type).toLowerCase() : '';
            var arr = parts || [];
            // Coerce each part to bytes.
            var Buf = (typeof globalThis.Buffer === 'function') ? globalThis.Buffer : null;
            var pieces = [];
            for (var i = 0; i < arr.length; i++) {
                var p = arr[i];
                if (Buf && Buf.isBuffer && Buf.isBuffer(p)) pieces.push(p);
                else if (p instanceof Uint8Array) pieces.push(Buf ? Buf.from(p) : p);
                else if (p instanceof ArrayBuffer) pieces.push(Buf ? Buf.from(new Uint8Array(p)) : new Uint8Array(p));
                else if (typeof p === 'string') pieces.push(Buf ? Buf.from(p, 'utf8') : new globalThis.TextEncoder().encode(p));
                else if (p && typeof p.arrayBuffer === 'function') {
                    // Nested Blob — sync access to its internal bytes.
                    pieces.push(Buf ? Buf.from(p._bytes || []) : (p._bytes || new Uint8Array(0)));
                } else {
                    var s = String(p);
                    pieces.push(Buf ? Buf.from(s, 'utf8') : new globalThis.TextEncoder().encode(s));
                }
            }
            // Concatenate.
            var total = 0;
            for (var j = 0; j < pieces.length; j++) total += pieces[j].length;
            var out = Buf ? Buf.alloc(total) : new Uint8Array(total);
            var off = 0;
            for (var k = 0; k < pieces.length; k++) {
                if (Buf) pieces[k].copy(out, off);
                else out.set(pieces[k], off);
                off += pieces[k].length;
            }
            this._bytes = out;
            this.size = total;
        };
        Blob.prototype.arrayBuffer = function() {
            var b = this._bytes;
            return Promise.resolve(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength));
        };
        Blob.prototype.text = function() {
            return Promise.resolve(new globalThis.TextDecoder().decode(this._bytes));
        };
        Blob.prototype.bytes = function() {
            return Promise.resolve(new Uint8Array(this._bytes.buffer, this._bytes.byteOffset, this._bytes.byteLength));
        };
        Blob.prototype.slice = function(start, end, type) {
            var s = (start === undefined) ? 0 : (start | 0);
            var e = (end === undefined) ? this.size : (end | 0);
            if (s < 0) s = Math.max(this.size + s, 0);
            if (e < 0) e = Math.max(this.size + e, 0);
            s = Math.min(s, this.size); e = Math.min(e, this.size);
            var sub = this._bytes.slice(s, e);
            var out = Object.create(Blob.prototype);
            out._bytes = sub; out.size = sub.length;
            out.type = type ? String(type).toLowerCase() : '';
            return out;
        };
        Blob.prototype.stream = function() {
            // Best-effort: a stream-shaped object with one chunk.
            var bytes = this._bytes;
            var done = false;
            return {
                getReader: function() {
                    return {
                        read: function() {
                            if (done) return Promise.resolve({ value: undefined, done: true });
                            done = true;
                            return Promise.resolve({ value: new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), done: false });
                        },
                        cancel: function() { done = true; return Promise.resolve(); },
                        releaseLock: function() {},
                    };
                },
                [Symbol.asyncIterator]: function() {
                    return {
                        next: function() {
                            if (done) return Promise.resolve({ value: undefined, done: true });
                            done = true;
                            return Promise.resolve({ value: bytes, done: false });
                        },
                    };
                },
            };
        };
        globalThis.Blob = Blob;
    }
    if (typeof globalThis.File !== 'function') {
        globalThis.File = function File(parts, name, options) {
            globalThis.Blob.call(this, parts, options);
            this.name = String(name);
            this.lastModified = (options && typeof options.lastModified === 'number') ? options.lastModified : Date.now();
            this.webkitRelativePath = '';
        };
        globalThis.File.prototype = Object.create(globalThis.Blob.prototype);
        globalThis.File.prototype.constructor = globalThis.File;
    }

    // ----- FileReader (Web API, Node 23+ global) ---------------------
    //
    // The Web API for asynchronous Blob/File reading. Most uses today
    // call `readAsText` / `readAsArrayBuffer` / `readAsDataURL` and
    // listen for `loadend` / `load`. We synthesise it on top of the
    // Blob's `text()` / `arrayBuffer()` Promises so existing code
    // (image upload widgets, file picker handlers) works.
    if (typeof globalThis.FileReader !== 'function') {
        function FileReader() {
            // EventTarget-shaped emitter for on{load,loadend,error,...}.
            this._listeners = Object.create(null);
            this.readyState = 0; // EMPTY
            this.result = null;
            this.error = null;
            this.onload = null; this.onloadend = null; this.onloadstart = null;
            this.onerror = null; this.onabort = null; this.onprogress = null;
        }
        FileReader.EMPTY = 0; FileReader.LOADING = 1; FileReader.DONE = 2;
        FileReader.prototype.EMPTY = 0;
        FileReader.prototype.LOADING = 1;
        FileReader.prototype.DONE = 2;
        FileReader.prototype.addEventListener = function(name, fn) {
            (this._listeners[name] = this._listeners[name] || []).push(fn);
        };
        FileReader.prototype.removeEventListener = function(name, fn) {
            var list = this._listeners[name];
            if (!list) return;
            this._listeners[name] = list.filter(function(f) { return f !== fn; });
        };
        FileReader.prototype._fire = function(name, ev) {
            var on = this['on' + name];
            if (typeof on === 'function') { try { on.call(this, ev); } catch (_) {} }
            var list = this._listeners[name] || [];
            for (var i = 0; i < list.length; i++) {
                try { list[i].call(this, ev); } catch (_) {}
            }
        };
        FileReader.prototype._read = function(blob, kind) {
            var self = this;
            self.readyState = 1; // LOADING
            self._fire('loadstart', { type: 'loadstart' });
            var p;
            if (kind === 'text') p = blob.text().then(function(t) { return t; });
            else if (kind === 'arrayBuffer') p = blob.arrayBuffer();
            else if (kind === 'dataURL') {
                p = blob.arrayBuffer().then(function(ab) {
                    var bytes = new Uint8Array(ab);
                    var bin = '';
                    for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
                    return 'data:' + (blob.type || '') + ';base64,' + btoa(bin);
                });
            } else if (kind === 'binaryString') {
                p = blob.arrayBuffer().then(function(ab) {
                    var bytes = new Uint8Array(ab);
                    var s = '';
                    for (var i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
                    return s;
                });
            }
            p.then(function(value) {
                self.result = value;
                self.readyState = 2;
                self._fire('load', { type: 'load' });
                self._fire('loadend', { type: 'loadend' });
            }, function(err) {
                self.error = err;
                self.readyState = 2;
                self._fire('error', { type: 'error', error: err });
                self._fire('loadend', { type: 'loadend' });
            });
        };
        FileReader.prototype.readAsText = function(blob) { this._read(blob, 'text'); };
        FileReader.prototype.readAsArrayBuffer = function(blob) { this._read(blob, 'arrayBuffer'); };
        FileReader.prototype.readAsDataURL = function(blob) { this._read(blob, 'dataURL'); };
        FileReader.prototype.readAsBinaryString = function(blob) {
            this._read(blob, 'binaryString');
        };
        FileReader.prototype.abort = function() {
            if (this.readyState === 1) {
                this.readyState = 2;
                this._fire('abort', { type: 'abort' });
                this._fire('loadend', { type: 'loadend' });
            }
        };
        Object.defineProperty(globalThis, 'FileReader', {
            value: FileReader, writable: true, configurable: true,
        });
    }
    if (typeof globalThis.FormData !== 'function') {
        globalThis.FormData = function FormData() {
            this._entries = [];
        };
        var FP = globalThis.FormData.prototype;
        FP.append = function(key, value, filename) {
            this._entries.push([String(key), value, filename]);
        };
        FP.set = function(key, value, filename) {
            this._entries = this._entries.filter(function(e) { return e[0] !== String(key); });
            this._entries.push([String(key), value, filename]);
        };
        FP.delete = function(key) {
            this._entries = this._entries.filter(function(e) { return e[0] !== String(key); });
        };
        FP.has = function(key) {
            return this._entries.some(function(e) { return e[0] === String(key); });
        };
        FP.get = function(key) {
            for (var i = 0; i < this._entries.length; i++)
                if (this._entries[i][0] === String(key)) return this._entries[i][1];
            return null;
        };
        FP.getAll = function(key) {
            return this._entries.filter(function(e) { return e[0] === String(key); }).map(function(e) { return e[1]; });
        };
        FP.entries = function() {
            var arr = this._entries.map(function(e) { return [e[0], e[1]]; });
            var idx = 0;
            return {
                next: function() {
                    if (idx >= arr.length) return { value: undefined, done: true };
                    return { value: arr[idx++], done: false };
                },
                [Symbol.iterator]: function() { return this; },
            };
        };
        FP.keys = function() {
            var arr = this._entries.map(function(e) { return e[0]; });
            var idx = 0;
            return { next: function() { return idx < arr.length ? { value: arr[idx++], done: false } : { value: undefined, done: true }; }, [Symbol.iterator]: function() { return this; } };
        };
        FP.values = function() {
            var arr = this._entries.map(function(e) { return e[1]; });
            var idx = 0;
            return { next: function() { return idx < arr.length ? { value: arr[idx++], done: false } : { value: undefined, done: true }; }, [Symbol.iterator]: function() { return this; } };
        };
        FP.forEach = function(cb, thisArg) {
            for (var i = 0; i < this._entries.length; i++) cb.call(thisArg, this._entries[i][1], this._entries[i][0], this);
        };
        FP[Symbol.iterator] = FP.entries;
    }

    // ----- MessageChannel / MessagePort / MessageEvent ---------------
    // Same-realm message passing. Worker code uses the API surface
    // even when the actual cross-thread mechanism is provided by the
    // worker_threads polyfill — we expose a same-realm impl so user
    // code that does `new MessageChannel()` doesn't crash.
    if (typeof globalThis.MessageEvent !== 'function') {
        globalThis.MessageEvent = function MessageEvent(type, init) {
            globalThis.Event.call(this, type, init);
            init = init || {};
            this.data = init.data === undefined ? null : init.data;
            this.origin = init.origin || '';
            this.lastEventId = init.lastEventId || '';
            this.source = init.source || null;
            this.ports = init.ports || [];
        };
        globalThis.MessageEvent.prototype = Object.create(globalThis.Event.prototype);
        globalThis.MessageEvent.prototype.constructor = globalThis.MessageEvent;
    }
    if (typeof globalThis.MessagePort !== 'function') {
        var MessagePort = function MessagePort() {
            globalThis.EventTarget.call(this);
            this._other = null;
            this._started = false;
            this._queued = [];
            this._onmessage = null;
        };
        MessagePort.prototype = Object.create(globalThis.EventTarget.prototype);
        MessagePort.prototype.constructor = MessagePort;
        Object.defineProperty(MessagePort.prototype, 'onmessage', {
            get: function() { return this._onmessage; },
            set: function(fn) {
                this._onmessage = fn;
                this.start();
            },
        });
        MessagePort.prototype.postMessage = function(data, transferList) {
            var other = this._other;
            if (!other) return;
            var ev = new globalThis.MessageEvent('message', { data: data, ports: transferList || [] });
            if (other._started || other._onmessage) {
                if (typeof globalThis.queueMicrotask === 'function') {
                    globalThis.queueMicrotask(function() {
                        if (typeof other._onmessage === 'function') other._onmessage(ev);
                        other.dispatchEvent(ev);
                    });
                } else {
                    Promise.resolve().then(function() {
                        if (typeof other._onmessage === 'function') other._onmessage(ev);
                        other.dispatchEvent(ev);
                    });
                }
            } else {
                other._queued.push(ev);
            }
        };
        MessagePort.prototype.start = function() {
            if (this._started) return;
            this._started = true;
            var self = this;
            for (var i = 0; i < this._queued.length; i++) {
                (function(ev) {
                    Promise.resolve().then(function() {
                        if (typeof self._onmessage === 'function') self._onmessage(ev);
                        self.dispatchEvent(ev);
                    });
                })(this._queued[i]);
            }
            this._queued.length = 0;
        };
        MessagePort.prototype.close = function() {
            this._other = null;
            this._onmessage = null;
        };
        globalThis.MessagePort = MessagePort;
    }
    if (typeof globalThis.MessageChannel !== 'function') {
        globalThis.MessageChannel = function MessageChannel() {
            this.port1 = new globalThis.MessagePort();
            this.port2 = new globalThis.MessagePort();
            this.port1._other = this.port2;
            this.port2._other = this.port1;
        };
    }
    if (typeof globalThis.BroadcastChannel !== 'function') {
        // Sandbox is single-realm, so a BroadcastChannel just delivers
        // messages to other channels with the same name in this same
        // process. Useful for in-process module-coordination patterns.
        if (!globalThis.__ab_bc_registry) globalThis.__ab_bc_registry = {};
        var BroadcastChannel = function BroadcastChannel(name) {
            globalThis.EventTarget.call(this);
            this.name = String(name);
            this._closed = false;
            this._onmessage = null;
            var reg = globalThis.__ab_bc_registry;
            (reg[this.name] = reg[this.name] || []).push(this);
        };
        BroadcastChannel.prototype = Object.create(globalThis.EventTarget.prototype);
        BroadcastChannel.prototype.constructor = BroadcastChannel;
        Object.defineProperty(BroadcastChannel.prototype, 'onmessage', {
            get: function() { return this._onmessage; },
            set: function(v) { this._onmessage = v; },
        });
        BroadcastChannel.prototype.postMessage = function(data) {
            if (this._closed) return;
            var ev = new globalThis.MessageEvent('message', { data: data });
            var peers = (globalThis.__ab_bc_registry[this.name] || []).filter(function(c) { return c !== this; }, this);
            var self = this;
            peers.forEach(function(peer) {
                if (peer._closed) return;
                Promise.resolve().then(function() {
                    if (typeof peer._onmessage === 'function') peer._onmessage(ev);
                    peer.dispatchEvent(ev);
                });
            });
        };
        BroadcastChannel.prototype.close = function() {
            this._closed = true;
            var reg = globalThis.__ab_bc_registry;
            if (reg[this.name]) {
                reg[this.name] = reg[this.name].filter(function(c) { return c !== this; }, this);
            }
        };
        globalThis.BroadcastChannel = BroadcastChannel;
    }

    // ----- Web Crypto (globalThis.crypto) ---------------------------
    // Modern crypto is via the SubtleCrypto WebCrypto API. Most uses
    // we see in Node code are `crypto.randomUUID()`,
    // `crypto.getRandomValues()`, `crypto.subtle.digest()`. Lazy-load
    // node:crypto on first call so module-init time doesn't reach
    // into the host bridge before host imports are wired (Wizer
    // pre-init runs the bundle without our custom wasm imports
    // bound; eager require here trips the linker).
    if (typeof globalThis.crypto !== 'object' || !globalThis.crypto || typeof globalThis.crypto.randomUUID !== 'function') {
        var webCrypto = globalThis.crypto || {};
        function _hexToBytes(hex) {
            var out = new Uint8Array(hex.length / 2);
            for (var i = 0; i < out.length; i++) out[i] = parseInt(hex.substr(i*2, 2), 16);
            return out;
        }
        webCrypto.randomUUID = function() {
            try {
                var nc = require('crypto');
                if (typeof nc.randomUUID === 'function') return nc.randomUUID();
            } catch (_) {}
            var r = '';
            for (var i = 0; i < 32; i++) {
                if (i === 8 || i === 12 || i === 16 || i === 20) r += '-';
                r += Math.floor(Math.random() * 16).toString(16);
            }
            return r;
        };
        webCrypto.getRandomValues = function(typed) {
            if (!typed || typeof typed.length !== 'number') {
                throw new TypeError('getRandomValues: typed-array required');
            }
            var n = typed.byteLength || typed.length;
            try {
                var nc = require('crypto');
                if (nc && nc.randomBytes) {
                    var hex = nc.randomBytes(n);
                    var bytes = (typeof hex === 'string') ? _hexToBytes(hex) : hex;
                    var view = new Uint8Array(typed.buffer || typed, typed.byteOffset || 0, n);
                    for (var i = 0; i < n; i++) view[i] = bytes[i];
                    return typed;
                }
            } catch (_) {}
            var view2 = new Uint8Array(typed.buffer || typed, typed.byteOffset || 0, n);
            for (var j = 0; j < n; j++) view2[j] = Math.floor(Math.random() * 256);
            return typed;
        };
        // ---- SubtleCrypto -------------------------------------
        //
        // Web Crypto subset wired on top of node:crypto host fns.
        //
        // Algorithms shipped:
        //   AES-GCM      encrypt / decrypt / generateKey / importKey
        //                / exportKey
        //   AES-CBC      encrypt / decrypt / generateKey / importKey
        //                / exportKey
        //   AES-CTR      encrypt / decrypt (via AES-CBC host fn with
        //                CTR-mode wrapper TBD; falls back to error)
        //   HMAC         sign / verify / generateKey / importKey /
        //                exportKey (SHA-1/256/384/512)
        //   PBKDF2       deriveBits / deriveKey
        //   HKDF         deriveBits / deriveKey (HMAC-based)
        //   SHA-1/256/384/512  digest
        //
        // CryptoKey is an opaque-ish JS object holding the raw key
        // bytes plus algorithm metadata — extractable=true returns
        // the bytes via exportKey, false returns an error per the
        // spec.
        function _toBytes(input) {
            if (input == null) return new Uint8Array(0);
            if (input instanceof ArrayBuffer) return new Uint8Array(input);
            if (ArrayBuffer.isView(input)) {
                return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
            }
            if (typeof input === 'string') {
                var enc = new TextEncoder();
                return enc.encode(input);
            }
            return new Uint8Array(input);
        }
        function _bufToB64(bytes) {
            // Avoid require('buffer') here since this function runs
            // before module loading is fully wired during early
            // global install.
            var Buf = globalThis.Buffer || (require('buffer') && require('buffer').Buffer);
            return Buf.from(bytes).toString('base64');
        }
        function _b64ToBuf(b64) {
            var Buf = globalThis.Buffer || (require('buffer') && require('buffer').Buffer);
            return new Uint8Array(Buf.from(b64, 'base64'));
        }
        function _algoName(a) {
            return (typeof a === 'string') ? a.toLowerCase()
                 : (a && a.name) ? String(a.name).toLowerCase()
                 : '';
        }
        function _hashName(h) {
            var s = (typeof h === 'string') ? h : (h && h.name) || '';
            return s.toLowerCase().replace('-', '');
        }
        function _aesCipherName(keyBytes, mode) {
            var bits = keyBytes.length * 8;
            return 'aes-' + bits + '-' + mode;
        }
        function _makeCryptoKey(algorithm, raw, type, extractable, usages) {
            var key = Object.create(null);
            Object.defineProperty(key, 'algorithm', { value: algorithm, enumerable: true });
            Object.defineProperty(key, 'type', { value: type, enumerable: true });
            Object.defineProperty(key, 'extractable', { value: !!extractable, enumerable: true });
            Object.defineProperty(key, 'usages', { value: usages.slice(), enumerable: true });
            // _raw is non-enumerable so JSON.stringify(key) doesn't leak
            // the secret. Spec-wise CryptoKey is opaque; we keep parity.
            Object.defineProperty(key, '_raw', { value: raw, enumerable: false });
            return key;
        }

        var subtle = {
            digest: function(algo, data) {
                var nodeAlgo = _hashName(algo);
                try {
                    var nc = require('crypto');
                    var hash = nc.createHash(nodeAlgo);
                    hash.update(_toBytes(data));
                    var hex = hash.digest('hex');
                    return Promise.resolve(_hexToBytes(hex).buffer);
                } catch (e) { return Promise.reject(e); }
            },

            encrypt: function(algorithm, key, data) {
                return new Promise(function(resolve, reject) {
                    try {
                        var name = _algoName(algorithm);
                        var nc = require('crypto');
                        if (name === 'aes-gcm') {
                            var iv = _toBytes(algorithm.iv);
                            var aad = algorithm.additionalData ? _toBytes(algorithm.additionalData) : null;
                            var tagLen = (algorithm.tagLength | 0) || 128;
                            var c = nc.createCipheriv(_aesCipherName(key._raw, 'gcm'),
                                                      Buffer.from(key._raw),
                                                      Buffer.from(iv));
                            if (aad) c.setAAD(Buffer.from(aad));
                            c.update(Buffer.from(_toBytes(data)));
                            var ct = c.final();
                            var tag = c.getAuthTag().slice(0, tagLen / 8);
                            var out = new Uint8Array(ct.length + tag.length);
                            out.set(ct, 0);
                            out.set(tag, ct.length);
                            resolve(out.buffer);
                            return;
                        }
                        if (name === 'aes-cbc') {
                            var iv2 = _toBytes(algorithm.iv);
                            var c2 = nc.createCipheriv(_aesCipherName(key._raw, 'cbc'),
                                                       Buffer.from(key._raw),
                                                       Buffer.from(iv2));
                            c2.update(Buffer.from(_toBytes(data)));
                            var out2 = c2.final();
                            resolve(new Uint8Array(out2).buffer);
                            return;
                        }
                        reject(new Error('SubtleCrypto.encrypt: unsupported algorithm: ' + name));
                    } catch (e) { reject(e); }
                });
            },

            decrypt: function(algorithm, key, data) {
                return new Promise(function(resolve, reject) {
                    try {
                        var name = _algoName(algorithm);
                        var nc = require('crypto');
                        var input = _toBytes(data);
                        if (name === 'aes-gcm') {
                            var iv = _toBytes(algorithm.iv);
                            var aad = algorithm.additionalData ? _toBytes(algorithm.additionalData) : null;
                            var tagLen = (algorithm.tagLength | 0) || 128;
                            var tagBytes = tagLen / 8;
                            if (input.length < tagBytes) return reject(new Error('aes-gcm: ciphertext shorter than tag'));
                            var ct = input.slice(0, input.length - tagBytes);
                            var tag = input.slice(input.length - tagBytes);
                            var d = nc.createDecipheriv(_aesCipherName(key._raw, 'gcm'),
                                                        Buffer.from(key._raw),
                                                        Buffer.from(iv));
                            if (aad) d.setAAD(Buffer.from(aad));
                            d.setAuthTag(Buffer.from(tag));
                            d.update(Buffer.from(ct));
                            var pt = d.final();
                            resolve(new Uint8Array(pt).buffer);
                            return;
                        }
                        if (name === 'aes-cbc') {
                            var iv2 = _toBytes(algorithm.iv);
                            var d2 = nc.createDecipheriv(_aesCipherName(key._raw, 'cbc'),
                                                         Buffer.from(key._raw),
                                                         Buffer.from(iv2));
                            d2.update(Buffer.from(input));
                            var pt2 = d2.final();
                            resolve(new Uint8Array(pt2).buffer);
                            return;
                        }
                        reject(new Error('SubtleCrypto.decrypt: unsupported algorithm: ' + name));
                    } catch (e) { reject(e); }
                });
            },

            sign: function(algorithm, key, data) {
                return new Promise(function(resolve, reject) {
                    try {
                        var name = _algoName(algorithm);
                        var nc = require('crypto');
                        if (name === 'hmac') {
                            var hashName = _hashName(key.algorithm && key.algorithm.hash);
                            var h = nc.createHmac(hashName, Buffer.from(key._raw));
                            h.update(Buffer.from(_toBytes(data)));
                            var hex = h.digest('hex');
                            resolve(_hexToBytes(hex).buffer);
                            return;
                        }
                        reject(new Error('SubtleCrypto.sign: unsupported algorithm: ' + name));
                    } catch (e) { reject(e); }
                });
            },

            verify: function(algorithm, key, signature, data) {
                return new Promise(function(resolve, reject) {
                    var self = this;
                    var p = subtle.sign(algorithm, key, data);
                    p.then(function(expected) {
                        var sig = new Uint8Array(_toBytes(signature));
                        var exp = new Uint8Array(expected);
                        if (sig.length !== exp.length) { resolve(false); return; }
                        var ok = 0;
                        for (var i = 0; i < sig.length; i++) ok |= (sig[i] ^ exp[i]);
                        resolve(ok === 0);
                    }, reject);
                });
            },

            generateKey: function(algorithm, extractable, usages) {
                return new Promise(function(resolve, reject) {
                    try {
                        var name = _algoName(algorithm);
                        var len = (algorithm.length | 0) || 256;
                        var raw = new Uint8Array(len / 8);
                        webCrypto.getRandomValues(raw);
                        if (name === 'aes-gcm' || name === 'aes-cbc' || name === 'aes-ctr') {
                            resolve(_makeCryptoKey({ name: name.toUpperCase(), length: len },
                                                   raw, 'secret', extractable, usages));
                            return;
                        }
                        if (name === 'hmac') {
                            var hashName = _hashName(algorithm.hash);
                            // HMAC default key length matches block size of hash.
                            var blockBits = (hashName === 'sha512' || hashName === 'sha384') ? 1024 : 512;
                            var hmacLen = algorithm.length || blockBits;
                            var hraw = new Uint8Array(hmacLen / 8);
                            webCrypto.getRandomValues(hraw);
                            resolve(_makeCryptoKey({ name: 'HMAC',
                                                     hash: { name: hashName.toUpperCase().replace(/^SHA/, 'SHA-') },
                                                     length: hmacLen },
                                                   hraw, 'secret', extractable, usages));
                            return;
                        }
                        reject(new Error('SubtleCrypto.generateKey: unsupported algorithm: ' + name));
                    } catch (e) { reject(e); }
                });
            },

            importKey: function(format, keyData, algorithm, extractable, usages) {
                return new Promise(function(resolve, reject) {
                    try {
                        var name = _algoName(algorithm);
                        if (format === 'raw') {
                            var raw = _toBytes(keyData);
                            if (name === 'aes-gcm' || name === 'aes-cbc' || name === 'aes-ctr') {
                                resolve(_makeCryptoKey({ name: name.toUpperCase(), length: raw.length * 8 },
                                                       raw, 'secret', extractable, usages));
                                return;
                            }
                            if (name === 'hmac') {
                                var hashName = _hashName(algorithm.hash);
                                resolve(_makeCryptoKey({ name: 'HMAC',
                                                         hash: { name: hashName.toUpperCase().replace(/^SHA/, 'SHA-') },
                                                         length: raw.length * 8 },
                                                       raw, 'secret', extractable, usages));
                                return;
                            }
                            if (name === 'pbkdf2' || name === 'hkdf') {
                                resolve(_makeCryptoKey({ name: name.toUpperCase() },
                                                       raw, 'secret', extractable, usages));
                                return;
                            }
                        }
                        if (format === 'jwk' && keyData && keyData.k) {
                            var raw2 = _toBytes(_b64UrlDecode(keyData.k));
                            if (name === 'aes-gcm' || name === 'aes-cbc') {
                                resolve(_makeCryptoKey({ name: name.toUpperCase(), length: raw2.length * 8 },
                                                       raw2, 'secret', extractable, usages));
                                return;
                            }
                            if (name === 'hmac') {
                                var hashName2 = _hashName(algorithm.hash);
                                resolve(_makeCryptoKey({ name: 'HMAC',
                                                         hash: { name: hashName2.toUpperCase().replace(/^SHA/, 'SHA-') },
                                                         length: raw2.length * 8 },
                                                       raw2, 'secret', extractable, usages));
                                return;
                            }
                        }
                        reject(new Error('SubtleCrypto.importKey: unsupported format/algorithm: '
                                         + format + '/' + name));
                    } catch (e) { reject(e); }
                });
            },

            exportKey: function(format, key) {
                return new Promise(function(resolve, reject) {
                    try {
                        if (!key.extractable) {
                            return reject(new Error('SubtleCrypto.exportKey: key not extractable'));
                        }
                        if (format === 'raw') {
                            resolve(new Uint8Array(key._raw).buffer);
                            return;
                        }
                        if (format === 'jwk') {
                            var algoName = (key.algorithm && key.algorithm.name) || '';
                            var jwk = {
                                kty: 'oct',
                                k: _b64UrlEncode(key._raw),
                                alg: algoName,
                                ext: true,
                                key_ops: key.usages.slice(),
                            };
                            resolve(jwk);
                            return;
                        }
                        reject(new Error('SubtleCrypto.exportKey: unsupported format: ' + format));
                    } catch (e) { reject(e); }
                });
            },

            deriveBits: function(algorithm, baseKey, length) {
                return new Promise(function(resolve, reject) {
                    try {
                        var name = _algoName(algorithm);
                        var nc = require('crypto');
                        if (name === 'pbkdf2') {
                            var hashName = _hashName(algorithm.hash);
                            var salt = _toBytes(algorithm.salt);
                            var iters = algorithm.iterations | 0;
                            var bytes = length / 8;
                            var raw = nc.pbkdf2Sync(
                                Buffer.from(baseKey._raw),
                                Buffer.from(salt),
                                iters,
                                bytes,
                                hashName);
                            resolve(new Uint8Array(raw).buffer);
                            return;
                        }
                        if (name === 'hkdf') {
                            // RFC 5869 HKDF on top of HMAC. The Hmac
                            // wrapper's `digest()` returns a hex string
                            // by default; pass the raw form via
                            // `digest('hex')` and convert with
                            // `Buffer.from(hex, 'hex')` so we get bytes.
                            var hash = _hashName(algorithm.hash);
                            var ikm = baseKey._raw;
                            var salt2 = algorithm.salt ? _toBytes(algorithm.salt) : new Uint8Array(0);
                            var info = algorithm.info ? _toBytes(algorithm.info) : new Uint8Array(0);
                            var extract = nc.createHmac(hash, Buffer.from(salt2));
                            extract.update(Buffer.from(ikm));
                            var prk = Buffer.from(extract.digest('hex'), 'hex');
                            var bytesNeeded = length / 8;
                            var hashLen = prk.length;
                            var n = Math.ceil(bytesNeeded / hashLen);
                            var t = Buffer.alloc(0);
                            var okm = Buffer.alloc(0);
                            for (var i = 1; i <= n; i++) {
                                var h = nc.createHmac(hash, prk);
                                h.update(t);
                                h.update(Buffer.from(info));
                                h.update(Buffer.from([i]));
                                t = Buffer.from(h.digest('hex'), 'hex');
                                okm = Buffer.concat([okm, t]);
                            }
                            resolve(new Uint8Array(okm.slice(0, bytesNeeded)).buffer);
                            return;
                        }
                        reject(new Error('SubtleCrypto.deriveBits: unsupported algorithm: ' + name));
                    } catch (e) { reject(e); }
                });
            },

            deriveKey: function(algorithm, baseKey, derivedKeyAlgorithm, extractable, usages) {
                return subtle.deriveBits(algorithm, baseKey,
                    (derivedKeyAlgorithm.length | 0) || 256
                ).then(function(buf) {
                    return subtle.importKey('raw', buf, derivedKeyAlgorithm, extractable, usages);
                });
            },

            wrapKey: function(format, key, wrappingKey, wrapAlgorithm) {
                return subtle.exportKey(format, key).then(function(raw) {
                    return subtle.encrypt(wrapAlgorithm, wrappingKey, raw);
                });
            },

            unwrapKey: function(format, wrapped, unwrappingKey, unwrapAlgorithm,
                                unwrappedKeyAlgorithm, extractable, usages) {
                return subtle.decrypt(unwrapAlgorithm, unwrappingKey, wrapped).then(function(raw) {
                    return subtle.importKey(format, raw, unwrappedKeyAlgorithm, extractable, usages);
                });
            },
        };
        function _b64UrlEncode(bytes) {
            return _bufToB64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
        }
        function _b64UrlDecode(str) {
            var s = String(str).replace(/-/g, '+').replace(/_/g, '/');
            while (s.length % 4 !== 0) s += '=';
            return _b64ToBuf(s);
        }
        webCrypto.subtle = webCrypto.subtle || subtle;
        globalThis.crypto = webCrypto;

        // ----- CryptoKey / SubtleCrypto / Crypto globals --------------
        //
        // Node 17+ exposes the WebCrypto class globals (so library
        // code can `instanceof CryptoKey` after import-key). Our keys
        // are plain objects with a `type`, `algorithm`, `extractable`,
        // `usages` shape; the global is a brand-check class that accepts
        // them via its own ctor pattern.
        if (typeof globalThis.CryptoKey !== 'function') {
            function CryptoKey() {
                throw new TypeError(
                    'Illegal constructor: CryptoKey is not constructable directly');
            }
            // Mark our internal keys as instances via prototype tagging.
            CryptoKey.prototype = Object.create(Object.prototype);
            Object.defineProperty(CryptoKey.prototype, Symbol.toStringTag, {
                value: 'CryptoKey', configurable: true,
            });
            Object.defineProperty(globalThis, 'CryptoKey', {
                value: CryptoKey, writable: true, configurable: true,
            });
        }
        if (typeof globalThis.SubtleCrypto !== 'function') {
            function SubtleCrypto() {
                throw new TypeError(
                    'Illegal constructor: SubtleCrypto is not constructable directly');
            }
            SubtleCrypto.prototype = Object.create(Object.prototype);
            Object.defineProperty(SubtleCrypto.prototype, Symbol.toStringTag, {
                value: 'SubtleCrypto', configurable: true,
            });
            Object.defineProperty(globalThis, 'SubtleCrypto', {
                value: SubtleCrypto, writable: true, configurable: true,
            });
        }
        if (typeof globalThis.Crypto !== 'function') {
            function Crypto() {
                throw new TypeError(
                    'Illegal constructor: Crypto is not constructable directly');
            }
            Crypto.prototype = Object.create(Object.prototype);
            Object.defineProperty(Crypto.prototype, Symbol.toStringTag, {
                value: 'Crypto', configurable: true,
            });
            Object.defineProperty(globalThis, 'Crypto', {
                value: Crypto, writable: true, configurable: true,
            });
        }
    }

    // ----- navigator (Node 22+) -------------------------------------
    if (typeof globalThis.navigator !== 'object' || !globalThis.navigator) {
        globalThis.navigator = {
            userAgent: 'Node.js/26.0.0 (Afterburner)',
            language: 'en-US',
            languages: ['en-US'],
            hardwareConcurrency: 1,
            platform: globalThis.process && globalThis.process.platform || 'linux',
            onLine: true,
        };
    }

    // ----- Streams Web globals --------------------------------------
    // The polyfill bundle registers `stream/web` as a require target
    // but Node 18+ also exposes the constructors as globals. Bring
    // them onto globalThis so undici / web-streams-polyfill probes
    // see them.
    try {
        var sw = require('stream/web');
        ['ReadableStream','WritableStream','TransformStream',
         'ByteLengthQueuingStrategy','CountQueuingStrategy',
         'ReadableStreamDefaultReader','ReadableStreamBYOBReader',
         'WritableStreamDefaultWriter','TransformStreamDefaultController'
        ].forEach(function(name) {
            if (sw[name] && !globalThis[name]) globalThis[name] = sw[name];
        });
    } catch (_) {}

    // ----- TextEncoderStream / TextDecoderStream --------------------
    // TransformStream subclasses that pump chunks through encode/decode.
    // Defer until ReadableStream is available so we can compose.
    if (typeof globalThis.TextEncoderStream !== 'function' && typeof globalThis.TransformStream === 'function') {
        var TES = function TextEncoderStream() {
            var enc = new globalThis.TextEncoder();
            globalThis.TransformStream.call(this, {
                transform: function(chunk, controller) {
                    controller.enqueue(enc.encode(String(chunk)));
                },
            });
            this.encoding = enc.encoding;
        };
        TES.prototype = Object.create(globalThis.TransformStream && globalThis.TransformStream.prototype || Object.prototype);
        globalThis.TextEncoderStream = TES;
    }
    if (typeof globalThis.TextDecoderStream !== 'function' && typeof globalThis.TransformStream === 'function') {
        var TDS = function TextDecoderStream(label, options) {
            var dec = new globalThis.TextDecoder(label, options);
            globalThis.TransformStream.call(this, {
                transform: function(chunk, controller) {
                    controller.enqueue(dec.decode(chunk));
                },
            });
            this.encoding = dec.encoding;
        };
        TDS.prototype = Object.create(globalThis.TransformStream && globalThis.TransformStream.prototype || Object.prototype);
        globalThis.TextDecoderStream = TDS;
    }

    // ----- CompressionStream / DecompressionStream ------------------
    //
    // Node 17+ / WHATWG Compression Streams. Each instance is a
    // TransformStream that pipes chunks through a sync zlib codec.
    // Supported formats: `gzip` / `deflate` / `deflate-raw`.
    // `Reflect.construct` is the only path that produces a real
    // TransformStream subclass under QuickJS — `.call(this, …)` on
    // class constructors throws a TypeError.
    function _makeCompressFn(format) {
        return function(chunk, controller) {
            try {
                var nz = require('zlib');
                var Buf = globalThis.Buffer;
                var buf = Buf && Buf.from ? Buf.from(chunk) : chunk;
                var syncFn = (format === 'gzip') ? nz.gzipSync
                           : (format === 'deflate') ? nz.deflateSync
                           : (format === 'deflate-raw') ? nz.deflateRawSync
                           : (format === 'zstd') ? nz.zstdCompressSync
                           : null;
                if (!syncFn) {
                    controller.error(new TypeError(
                        "CompressionStream: unknown format '" + format + "'"));
                    return;
                }
                controller.enqueue(syncFn(buf));
            } catch (e) { controller.error(e); }
        };
    }
    function _makeDecompressFn(format) {
        return function(chunk, controller) {
            try {
                var nz = require('zlib');
                var Buf = globalThis.Buffer;
                var buf = Buf && Buf.from ? Buf.from(chunk) : chunk;
                var syncFn = (format === 'gzip') ? nz.gunzipSync
                           : (format === 'deflate') ? nz.inflateSync
                           : (format === 'deflate-raw') ? nz.inflateRawSync
                           : (format === 'zstd') ? nz.zstdDecompressSync
                           : null;
                if (!syncFn) {
                    controller.error(new TypeError(
                        "DecompressionStream: unknown format '" + format + "'"));
                    return;
                }
                controller.enqueue(syncFn(buf));
            } catch (e) { controller.error(e); }
        };
    }
    if (typeof globalThis.CompressionStream !== 'function'
        && typeof globalThis.TransformStream === 'function') {
        globalThis.CompressionStream = function CompressionStream(format) {
            return Reflect.construct(globalThis.TransformStream,
                [{ transform: _makeCompressFn(format) }],
                CompressionStream);
        };
        globalThis.CompressionStream.prototype =
            Object.create(globalThis.TransformStream.prototype);
        globalThis.CompressionStream.prototype.constructor = globalThis.CompressionStream;
    }
    if (typeof globalThis.DecompressionStream !== 'function'
        && typeof globalThis.TransformStream === 'function') {
        globalThis.DecompressionStream = function DecompressionStream(format) {
            return Reflect.construct(globalThis.TransformStream,
                [{ transform: _makeDecompressFn(format) }],
                DecompressionStream);
        };
        globalThis.DecompressionStream.prototype =
            Object.create(globalThis.TransformStream.prototype);
        globalThis.DecompressionStream.prototype.constructor = globalThis.DecompressionStream;
    }
    if (typeof globalThis.URL !== 'function') {
        var urlMod = require('url');
        if (typeof urlMod.URL === 'function') {
            globalThis.URL = urlMod.URL;
            globalThis.URLSearchParams = urlMod.URLSearchParams;
        } else {
            // Regex-based parser with proper RFC 3986 reference
            // resolution for the 2-arg form. Covers WHATWG-shape
            // properties (`protocol`/`host`/`pathname`/`search`/
            // `searchParams`) plus the redirect-following cases
            // node-fetch / minipass-fetch / pacote depend on:
            //   * `new URL('/p', 'https://h.com/x')`   → `https://h.com/p`
            //   * `new URL('p', 'https://h.com/x/y')`  → `https://h.com/x/p`
            //   * `new URL('https://o.com/p', 'https://h.com/x')` → `https://o.com/p`
            //   * `new URL('?q=1', 'https://h.com/x')` → `https://h.com/x?q=1`
            // Without these, every redirect-followed download breaks
            // with empty-host options and the upstream HTTP client
            // synthesises a malformed `https:///path` URL.
            function _parseAbs(s) {
                var m = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/([^/?#]*)([^?#]*)?(\?[^#]*)?(#.*)?$/.exec(s);
                if (!m) return null;
                return { protocol: m[1] + ':', authority: m[2] || '', path: m[3] || '', query: m[4] || '', fragment: m[5] || '' };
            }
            function _normalizePath(p) {
                // RFC 3986 §5.2.4 — remove `.` and `..` segments.
                if (!p) return '';
                var leading = p.charAt(0) === '/';
                var trailing = p.charAt(p.length - 1) === '/';
                var parts = p.split('/').filter(function(s) { return s.length > 0; });
                var stack = [];
                for (var i = 0; i < parts.length; i++) {
                    var seg = parts[i];
                    if (seg === '.') continue;
                    if (seg === '..') { if (stack.length) stack.pop(); continue; }
                    stack.push(seg);
                }
                return (leading ? '/' : '') + stack.join('/') + (trailing && stack.length ? '/' : '');
            }
            globalThis.URL = function URL(href, base) {
                var input = String(href);
                var parsed = _parseAbs(input);
                if (!parsed && base) {
                    // Reference resolution per RFC 3986 §5.3.
                    var b = _parseAbs(String(base));
                    if (b) {
                        // Same-document fragment.
                        if (input.charAt(0) === '#') {
                            input = (b.protocol + '//' + b.authority + b.path + b.query + input);
                        } else if (input.charAt(0) === '?') {
                            input = (b.protocol + '//' + b.authority + b.path + input);
                        } else if (input.charAt(0) === '/') {
                            // Absolute path on the base authority.
                            input = (b.protocol + '//' + b.authority + input);
                        } else {
                            // Path-relative against the base directory.
                            var basePath = b.path || '/';
                            // Strip the last segment.
                            var slash = basePath.lastIndexOf('/');
                            var baseDir = slash >= 0 ? basePath.slice(0, slash + 1) : '/';
                            input = (b.protocol + '//' + b.authority + _normalizePath(baseDir + input));
                        }
                        parsed = _parseAbs(input);
                    }
                }
                var protocol = parsed ? parsed.protocol : '';
                var host = parsed ? parsed.authority : '';
                var path = parsed ? (parsed.path || '/') : input;
                var query = parsed ? parsed.query : '';
                var fragment = parsed ? parsed.fragment : '';
                // Username / password split off the authority.
                var username = '', password = '';
                var atIdx = host.indexOf('@');
                if (atIdx >= 0) {
                    var userinfo = host.slice(0, atIdx);
                    host = host.slice(atIdx + 1);
                    var colonIdx = userinfo.indexOf(':');
                    if (colonIdx >= 0) {
                        username = userinfo.slice(0, colonIdx);
                        password = userinfo.slice(colonIdx + 1);
                    } else {
                        username = userinfo;
                    }
                }
                var hp = host.split(':');
                var hostname = hp[0] || '';
                var port = hp.length > 1 ? hp[1] : '';
                this.protocol = protocol;
                this.host = host;
                this.hostname = hostname;
                this.port = port;
                this.pathname = _normalizePath(path);
                if (this.pathname === '' && host) this.pathname = '/';
                this.search = query;
                this.hash = fragment;
                this.username = username;
                this.password = password;
                this.origin = protocol + (host ? '//' + host : '');
                this.href = protocol + '//' + (username ? username + (password ? ':' + password : '') + '@' : '') + host + this.pathname + this.search + this.hash;
                this.searchParams = new globalThis.URLSearchParams(this.search.slice(1));
            };
            globalThis.URL.prototype.toString = function() { return this.href; };
            globalThis.URL.prototype.toJSON  = function() { return this.href; };
            globalThis.URL.canParse = function(href, base) {
                try { new globalThis.URL(href, base); return true; }
                catch (_) { return false; }
            };
            globalThis.URL.parse = function(href, base) {
                try { return new globalThis.URL(href, base); }
                catch (_) { return null; }
            };
            // ----- URL.createObjectURL / revokeObjectURL (Node 20+) -----
            //
            // Maps a Blob / File to a `blob:burn/<uuid>` URL. The
            // mapping lives in a global registry; `fetch(blob:burn/...)`
            // (and other consumers via `globalThis.__ab_resolve_blob_url`)
            // can resolve back to the original Blob's bytes.
            // `revokeObjectURL` drops the registry entry.
            if (!globalThis.__ab_blob_url_registry) {
                globalThis.__ab_blob_url_registry = Object.create(null);
            }
            var _blobUrlReg = globalThis.__ab_blob_url_registry;
            var _blobUrlSeq = 0;
            globalThis.URL.createObjectURL = function(blob) {
                if (!blob || typeof blob.arrayBuffer !== 'function') {
                    throw new TypeError(
                        'URL.createObjectURL: argument must be a Blob / File'
                    );
                }
                // Deterministic id space — counter + pid keeps URLs
                // unique within a single process; `fetch` consumers
                // look this up by exact string match.
                var pid = (typeof process !== 'undefined' && process.pid) | 0;
                var id = 'burn-' + pid + '-' + (++_blobUrlSeq);
                var url = 'blob:burn/' + id;
                _blobUrlReg[url] = blob;
                return url;
            };
            globalThis.URL.revokeObjectURL = function(url) {
                if (typeof url === 'string') delete _blobUrlReg[url];
            };
            // Exposed for the fetch polyfill — given a `blob:burn/...`
            // URL, return the underlying Blob or undefined.
            globalThis.__ab_resolve_blob_url = function(url) {
                return _blobUrlReg[url];
            };

            globalThis.URLSearchParams = function URLSearchParams(init) {
                this._pairs = [];
                var self = this;
                if (typeof init === 'string') {
                    var s = init.replace(/^\?/, '');
                    if (s) s.split('&').forEach(function(p) {
                        var eq = p.indexOf('=');
                        var k = eq < 0 ? p : p.slice(0, eq);
                        var v = eq < 0 ? '' : p.slice(eq + 1);
                        self._pairs.push([decodeURIComponent(k), decodeURIComponent(v)]);
                    });
                } else if (init && typeof init === 'object') {
                    Object.keys(init).forEach(function(k) {
                        self._pairs.push([k, String(init[k])]);
                    });
                }
            };
            var P = globalThis.URLSearchParams.prototype;
            P.get = function(k) {
                for (var i = 0; i < this._pairs.length; i++)
                    if (this._pairs[i][0] === k) return this._pairs[i][1];
                return null;
            };
            P.getAll = function(k) {
                return this._pairs.filter(function(p) { return p[0] === k; })
                                  .map(function(p) { return p[1]; });
            };
            P.has = function(k) {
                return this._pairs.some(function(p) { return p[0] === k; });
            };
            P.set = function(k, v) {
                this._pairs = this._pairs.filter(function(p) { return p[0] !== k; });
                this._pairs.push([k, String(v)]);
            };
            P.append = function(k, v) { this._pairs.push([k, String(v)]); };
            P.delete = function(k) {
                this._pairs = this._pairs.filter(function(p) { return p[0] !== k; });
            };
            P.toString = function() {
                return this._pairs.map(function(p) {
                    return encodeURIComponent(p[0]) + '=' + encodeURIComponent(p[1]);
                }).join('&');
            };
        }
    }

    // ============================================================
    // ES2024 / ES2023 globals.
    //
    // The runtime's QuickJS may add these natively in a future build;
    // every install is gated on `!has(...)` so the polyfill is a
    // no-op once the engine catches up. Idempotent + safe.
    // ============================================================

    // ---- `self` / `addEventListener` on globalThis (Web shim) -------
    //
    // Browser / Worker code routinely references `self` as the global
    // and `addEventListener` as a top-level binding. Node 22+ ships
    // both; without them, polyfills like `whatwg-url`, `web-streams-
    // polyfill`, and undici crash at module init with
    // "self is not defined".
    if (typeof globalThis.self === 'undefined') {
        globalThis.self = globalThis;
    }
    if (typeof globalThis.addEventListener !== 'function'
        && typeof globalThis.EventTarget === 'function') {
        try {
            var _gtTarget = new globalThis.EventTarget();
            globalThis.addEventListener =
                _gtTarget.addEventListener.bind(_gtTarget);
            globalThis.removeEventListener =
                _gtTarget.removeEventListener.bind(_gtTarget);
            globalThis.dispatchEvent =
                _gtTarget.dispatchEvent.bind(_gtTarget);
        } catch (_) {
            globalThis.addEventListener = function() {};
            globalThis.removeEventListener = function() {};
            globalThis.dispatchEvent = function() { return true; };
        }
    }

    // ---- Event subclasses (Node 22+) -------------------------------
    //
    // `ProgressEvent` / `CloseEvent` / `ErrorEvent` are common
    // Web-API constructors that real apps reach for in fetch-style
    // upload progress code, WebSocket close handling, and error
    // bubbling from worker threads. Lightweight subclasses of Event
    // with the canonical extra fields.
    if (typeof globalThis.ProgressEvent !== 'function' && typeof globalThis.Event === 'function') {
        globalThis.ProgressEvent = function ProgressEvent(type, init) {
            init = init || {};
            globalThis.Event.call(this, type, init);
            this.lengthComputable = !!init.lengthComputable;
            this.loaded = init.loaded || 0;
            this.total = init.total || 0;
        };
        globalThis.ProgressEvent.prototype =
            Object.create(globalThis.Event.prototype);
        globalThis.ProgressEvent.prototype.constructor = globalThis.ProgressEvent;
    }
    if (typeof globalThis.CloseEvent !== 'function' && typeof globalThis.Event === 'function') {
        globalThis.CloseEvent = function CloseEvent(type, init) {
            init = init || {};
            globalThis.Event.call(this, type, init);
            this.code = init.code || 0;
            this.reason = init.reason || '';
            this.wasClean = !!init.wasClean;
        };
        globalThis.CloseEvent.prototype =
            Object.create(globalThis.Event.prototype);
        globalThis.CloseEvent.prototype.constructor = globalThis.CloseEvent;
    }
    if (typeof globalThis.ErrorEvent !== 'function' && typeof globalThis.Event === 'function') {
        globalThis.ErrorEvent = function ErrorEvent(type, init) {
            init = init || {};
            globalThis.Event.call(this, type, init);
            this.message = init.message || '';
            this.filename = init.filename || '';
            this.lineno = init.lineno || 0;
            this.colno = init.colno || 0;
            this.error = init.error || null;
        };
        globalThis.ErrorEvent.prototype =
            Object.create(globalThis.Event.prototype);
        globalThis.ErrorEvent.prototype.constructor = globalThis.ErrorEvent;
    }

    // ============================================================
    // Web Streams (WHATWG) — minimum viable implementation.
    //
    // QuickJS / Javy don't ship the streams spec natively. This
    // polyfill covers the common consumers: undici body iteration,
    // CompressionStream, fetch().body, Readable.toWeb/fromWeb. It's
    // pull-based (the canonical algorithm); the controller API
    // matches WHATWG so user code that constructs streams works.
    //
    // Out of scope for now: BYOB readers (byte streams pull into
    // user-provided buffers), tee() (split into two readers),
    // queuing strategies beyond size+highWaterMark defaults. Real
    // workloads that need those grow later.
    // ============================================================
    if (typeof globalThis.ReadableStream !== 'function'
        || (function() {
            // Detect "stub" ReadableStream by attempting a no-op
            // construction; Javy's stub throws on call.
            try { new globalThis.ReadableStream({}); return false; } catch (_) { return true; }
        })()) {

        function _resolvedPromise(v) { return Promise.resolve(v); }

        function ReadableStreamDefaultController(stream) {
            this._stream = stream;
        }
        ReadableStreamDefaultController.prototype.enqueue = function(chunk) {
            var s = this._stream;
            if (s._state !== 'readable') return;
            s._queue.push(chunk);
            s._processQueue();
        };
        ReadableStreamDefaultController.prototype.close = function() {
            var s = this._stream;
            if (s._state !== 'readable') return;
            s._closeRequested = true;
            s._processQueue();
        };
        ReadableStreamDefaultController.prototype.error = function(err) {
            var s = this._stream;
            if (s._state !== 'readable') return;
            s._error = err;
            s._state = 'errored';
            s._flushReaders();
        };
        Object.defineProperty(ReadableStreamDefaultController.prototype, 'desiredSize', {
            get: function() {
                var s = this._stream;
                if (s._state === 'errored') return null;
                if (s._state === 'closed') return 0;
                return Math.max(0, (s._highWaterMark | 0) - s._queue.length);
            },
        });

        function ReadableStream(underlyingSource, strategy) {
            if (!(this instanceof ReadableStream)) {
                throw new TypeError('ReadableStream is a constructor');
            }
            underlyingSource = underlyingSource || {};
            strategy = strategy || {};
            this._source = underlyingSource;
            this._highWaterMark = (strategy && strategy.highWaterMark) || 1;
            this._queue = [];
            this._state = 'readable';
            this._closeRequested = false;
            this._error = null;
            this._readerLocked = false;
            this._waiters = []; // pending read() resolvers
            var controller = new ReadableStreamDefaultController(this);
            this._controller = controller;
            try {
                if (typeof underlyingSource.start === 'function') {
                    var ret = underlyingSource.start(controller);
                    if (ret && typeof ret.then === 'function') {
                        var self = this;
                        ret.catch(function(e) { controller.error(e); });
                    }
                }
            } catch (e) { controller.error(e); }
        }

        ReadableStream.prototype._pull = function() {
            var s = this;
            if (s._pulling) return;
            if (typeof s._source.pull !== 'function') return;
            if (s._queue.length >= s._highWaterMark) return;
            s._pulling = true;
            try {
                var ret = s._source.pull(s._controller);
                Promise.resolve(ret).then(function() {
                    s._pulling = false;
                    s._processQueue();
                }, function(e) {
                    s._pulling = false;
                    s._controller.error(e);
                });
            } catch (e) {
                s._pulling = false;
                s._controller.error(e);
            }
        };
        ReadableStream.prototype._processQueue = function() {
            // Drain pending readers from the queue.
            while (this._waiters.length && this._queue.length) {
                var resolve = this._waiters.shift();
                resolve({ value: this._queue.shift(), done: false });
            }
            // If close was requested and queue is empty, close.
            if (this._closeRequested && this._queue.length === 0) {
                this._state = 'closed';
                this._flushReaders();
                return;
            }
            // Need more data?
            if (this._queue.length < this._highWaterMark) this._pull();
        };
        ReadableStream.prototype._flushReaders = function() {
            while (this._waiters.length) {
                var resolve = this._waiters.shift();
                if (this._state === 'errored') {
                    resolve(Promise.reject(this._error));
                } else {
                    resolve({ value: undefined, done: true });
                }
            }
        };
        ReadableStream.prototype.getReader = function(_opts) {
            if (this._readerLocked) {
                throw new TypeError('ReadableStream is already locked');
            }
            this._readerLocked = true;
            return new ReadableStreamDefaultReader(this);
        };
        ReadableStream.prototype.cancel = function(reason) {
            if (this._state !== 'readable') return Promise.resolve();
            this._state = 'closed';
            this._queue = [];
            this._flushReaders();
            try {
                if (typeof this._source.cancel === 'function') {
                    return Promise.resolve(this._source.cancel(reason));
                }
            } catch (_) {}
            return Promise.resolve();
        };
        ReadableStream.prototype.pipeTo = function(dest, _opts) {
            var src = this;
            return (async function() {
                var reader = src.getReader();
                var writer = dest.getWriter();
                try {
                    while (true) {
                        var step = await reader.read();
                        if (step.done) break;
                        await writer.write(step.value);
                    }
                    await writer.close();
                } catch (e) {
                    try { await writer.abort(e); } catch (_) {}
                    throw e;
                } finally {
                    reader.releaseLock();
                    writer.releaseLock();
                }
            })();
        };
        ReadableStream.prototype.pipeThrough = function(transform, opts) {
            this.pipeTo(transform.writable, opts).catch(function(_) {});
            return transform.readable;
        };
        ReadableStream.prototype[Symbol.asyncIterator] = function() {
            var reader = this.getReader();
            return {
                next: function() { return reader.read(); },
                return: function(v) { reader.releaseLock(); return Promise.resolve({ value: v, done: true }); },
                [Symbol.asyncIterator]: function() { return this; },
            };
        };
        Object.defineProperty(ReadableStream.prototype, 'locked', {
            get: function() { return this._readerLocked; },
        });

        // Static `ReadableStream.from(iterable)` — Node 22+ /
        // Web 2024.
        ReadableStream.from = function(iterable) {
            var it;
            if (iterable && typeof iterable[Symbol.asyncIterator] === 'function') {
                it = iterable[Symbol.asyncIterator]();
            } else if (iterable && typeof iterable[Symbol.iterator] === 'function') {
                it = iterable[Symbol.iterator]();
            } else {
                throw new TypeError('ReadableStream.from: argument is not iterable');
            }
            return new ReadableStream({
                async pull(controller) {
                    var step = await it.next();
                    if (step.done) controller.close();
                    else controller.enqueue(step.value);
                },
            });
        };

        function ReadableStreamDefaultReader(stream) {
            this._stream = stream;
        }
        ReadableStreamDefaultReader.prototype.read = function() {
            var s = this._stream;
            if (!s) return Promise.resolve({ value: undefined, done: true });
            if (s._state === 'errored') return Promise.reject(s._error);
            if (s._queue.length) {
                return _resolvedPromise({ value: s._queue.shift(), done: false }).then(function(v) {
                    if (s._state === 'readable') s._processQueue();
                    return v;
                });
            }
            if (s._state === 'closed') {
                return _resolvedPromise({ value: undefined, done: true });
            }
            // Wait for next enqueue.
            var self = this;
            return new Promise(function(resolve) {
                s._waiters.push(resolve);
                s._pull();
            });
        };
        ReadableStreamDefaultReader.prototype.releaseLock = function() {
            if (!this._stream) return;
            this._stream._readerLocked = false;
            this._stream = null;
        };
        ReadableStreamDefaultReader.prototype.cancel = function(reason) {
            if (!this._stream) return Promise.resolve();
            return this._stream.cancel(reason);
        };
        Object.defineProperty(ReadableStreamDefaultReader.prototype, 'closed', {
            get: function() {
                var s = this._stream;
                if (!s) return Promise.resolve();
                if (s._state === 'closed') return Promise.resolve();
                if (s._state === 'errored') return Promise.reject(s._error);
                return new Promise(function(resolve, reject) {
                    var orig = s._flushReaders;
                    s._flushReaders = function() {
                        orig.call(s);
                        if (s._state === 'errored') reject(s._error);
                        else resolve();
                    };
                });
            },
        });

        function WritableStreamDefaultController(stream) { this._stream = stream; }
        WritableStreamDefaultController.prototype.error = function(err) {
            this._stream._error = err;
            this._stream._state = 'errored';
        };

        function WritableStream(underlyingSink, strategy) {
            if (!(this instanceof WritableStream)) {
                throw new TypeError('WritableStream is a constructor');
            }
            underlyingSink = underlyingSink || {};
            this._sink = underlyingSink;
            this._highWaterMark = (strategy && strategy.highWaterMark) || 1;
            this._queue = [];
            this._state = 'writable';
            this._error = null;
            this._writerLocked = false;
            var controller = new WritableStreamDefaultController(this);
            this._controller = controller;
            try {
                if (typeof underlyingSink.start === 'function') {
                    var ret = underlyingSink.start(controller);
                    Promise.resolve(ret).catch(function(e) { controller.error(e); });
                }
            } catch (e) { controller.error(e); }
        }
        WritableStream.prototype.getWriter = function() {
            if (this._writerLocked) throw new TypeError('WritableStream is locked');
            this._writerLocked = true;
            return new WritableStreamDefaultWriter(this);
        };
        WritableStream.prototype.abort = function(reason) {
            this._state = 'errored';
            this._error = reason;
            try {
                if (typeof this._sink.abort === 'function') {
                    return Promise.resolve(this._sink.abort(reason));
                }
            } catch (_) {}
            return Promise.resolve();
        };
        WritableStream.prototype.close = function() {
            if (this._state !== 'writable') return Promise.resolve();
            var self = this;
            this._state = 'closed';
            try {
                if (typeof this._sink.close === 'function') {
                    return Promise.resolve(this._sink.close());
                }
            } catch (e) {
                self._error = e;
                self._state = 'errored';
                return Promise.reject(e);
            }
            return Promise.resolve();
        };
        Object.defineProperty(WritableStream.prototype, 'locked', {
            get: function() { return this._writerLocked; },
        });

        function WritableStreamDefaultWriter(stream) { this._stream = stream; }
        WritableStreamDefaultWriter.prototype.write = function(chunk) {
            var s = this._stream;
            if (!s) return Promise.reject(new TypeError('writer released'));
            if (s._state === 'errored') return Promise.reject(s._error);
            if (s._state !== 'writable') return Promise.reject(new TypeError('stream closed'));
            if (typeof s._sink.write !== 'function') return Promise.resolve();
            try {
                var ret = s._sink.write(chunk, s._controller);
                return Promise.resolve(ret);
            } catch (e) {
                s._error = e;
                s._state = 'errored';
                return Promise.reject(e);
            }
        };
        WritableStreamDefaultWriter.prototype.close = function() {
            return this._stream ? this._stream.close() : Promise.resolve();
        };
        WritableStreamDefaultWriter.prototype.abort = function(reason) {
            return this._stream ? this._stream.abort(reason) : Promise.resolve();
        };
        WritableStreamDefaultWriter.prototype.releaseLock = function() {
            if (!this._stream) return;
            this._stream._writerLocked = false;
            this._stream = null;
        };
        Object.defineProperty(WritableStreamDefaultWriter.prototype, 'desiredSize', {
            get: function() {
                var s = this._stream;
                if (!s) return null;
                if (s._state === 'errored') return null;
                if (s._state === 'closed') return 0;
                return s._highWaterMark - s._queue.length;
            },
        });

        function TransformStream(transformer, writableStrategy, readableStrategy) {
            if (!(this instanceof TransformStream)) {
                throw new TypeError('TransformStream is a constructor');
            }
            transformer = transformer || {};
            var readableSide;
            var readableController;
            var transformFn = transformer.transform || function(chunk, c) { c.enqueue(chunk); };
            var flushFn = transformer.flush || function(_c) {};
            var writable = new WritableStream({
                async write(chunk) {
                    await Promise.resolve(transformFn(chunk, readableController));
                },
                async close() {
                    try { await Promise.resolve(flushFn(readableController)); } catch (_) {}
                    readableController.close();
                },
                abort(reason) { readableController.error(reason); },
            }, writableStrategy);
            readableSide = new ReadableStream({
                start(c) { readableController = c; },
            }, readableStrategy);
            // Run the transformer's start hook with a tiny shim
            // controller that delegates to the readable side.
            var shimController = {
                enqueue: function(chunk) { readableController.enqueue(chunk); },
                error: function(err) { readableController.error(err); },
                terminate: function() { readableController.close(); },
            };
            try {
                if (typeof transformer.start === 'function') {
                    Promise.resolve(transformer.start(shimController)).catch(function(_) {});
                }
            } catch (_) {}
            this.readable = readableSide;
            this.writable = writable;
        }

        function ByteLengthQueuingStrategy(opts) {
            this.highWaterMark = (opts && opts.highWaterMark) || 1;
            this.size = function(chunk) { return chunk && chunk.byteLength != null ? chunk.byteLength : 1; };
        }
        function CountQueuingStrategy(opts) {
            this.highWaterMark = (opts && opts.highWaterMark) || 1;
            this.size = function() { return 1; };
        }

        globalThis.ReadableStream = ReadableStream;
        globalThis.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
        globalThis.ReadableStreamDefaultController = ReadableStreamDefaultController;
        globalThis.WritableStream = WritableStream;
        globalThis.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
        globalThis.WritableStreamDefaultController = WritableStreamDefaultController;
        globalThis.TransformStream = TransformStream;
        globalThis.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
        globalThis.CountQueuingStrategy = CountQueuingStrategy;

        // Re-link CompressionStream / DecompressionStream / TextEncoderStream
        // / TextDecoderStream classes that were installed earlier in
        // this same IIFE against the now-stub TransformStream. Their
        // prototypes were chained to the stub; we re-chain them to the
        // working TransformStream.prototype so `instanceof TransformStream`
        // checks pass and `Reflect.construct` works.
        function _relinkPrototype(Cls) {
            if (typeof Cls === 'function') {
                Cls.prototype = Object.create(TransformStream.prototype);
                Cls.prototype.constructor = Cls;
            }
        }
        _relinkPrototype(globalThis.CompressionStream);
        _relinkPrototype(globalThis.DecompressionStream);
        _relinkPrototype(globalThis.TextEncoderStream);
        _relinkPrototype(globalThis.TextDecoderStream);
    }

    // ---- SharedArrayBuffer (cross-process via mmap) ---------------
    //
    // Real OS-shared memory backed by `__host_sab_alloc` (memfd on
    // Linux). The JS surface mimics ArrayBuffer's shape so existing
    // typed-array code works; reads / writes hop through host imports
    // so cross-process coherence is honoured.
    if (typeof globalThis.__ab_sab_registry !== 'object') {
        globalThis.__ab_sab_registry = Object.create(null);
    }
    var _sabRegistry = globalThis.__ab_sab_registry;

    /// Build a `SharedArrayBuffer`-shaped object backed by an
    /// mmap region. We can't subclass `ArrayBuffer` (the engine's
    /// internal slots aren't accessible from JS), so the strategy
    /// is: allocate a regular ArrayBuffer of the same byteLength,
    /// bolt the SAB metadata onto it as non-enumerable properties,
    /// register it in the SAB registry. Typed-array views over the
    /// returned ArrayBuffer index through the standard JS heap;
    /// `Atomics.{load,store,wait,notify}` detect the registered
    /// region via the registry and route atomic ops to the host so
    /// cross-process coherence holds.
    function _SAB(byteLengthOrAttach) {
        if (!(this instanceof _SAB)) return new _SAB(byteLengthOrAttach);
        var byteLength;
        var regionId;
        if (typeof byteLengthOrAttach === 'object' && byteLengthOrAttach !== null
            && byteLengthOrAttach.__ab_sab_attach) {
            var attach = byteLengthOrAttach;
            regionId = globalThis.__host_sab_open(attach.descriptor, attach.byteLength);
            if (regionId < 0) {
                throw new Error('SharedArrayBuffer attach: rc=' + regionId);
            }
            byteLength = attach.byteLength;
        } else {
            byteLength = (byteLengthOrAttach | 0) >>> 0;
            if (byteLength === 0) {
                throw new RangeError('SharedArrayBuffer: byteLength must be > 0');
            }
            regionId = globalThis.__host_sab_alloc(byteLength);
            if (regionId < 0) {
                throw new Error('SharedArrayBuffer: alloc failed (rc=' + regionId + ')');
            }
        }
        // The buffer the user gets IS a real ArrayBuffer so
        // `new Int32Array(sab)` works without monkey-patching the
        // typed-array constructor. Atomics.* detect this is a SAB
        // shadow via the registry keyed by buffer identity.
        var buf = new ArrayBuffer(byteLength);
        Object.defineProperty(buf, '_regionId', {
            value: regionId,
            enumerable: false,
            writable: false,
        });
        Object.defineProperty(buf, '_descriptor', {
            value: globalThis.__host_sab_descriptor(regionId) || '',
            enumerable: false,
            writable: false,
        });
        Object.defineProperty(buf, '_isSharedArrayBuffer', {
            value: true,
            enumerable: false,
            writable: false,
        });
        _sabRegistry[regionId] = buf;
        return buf;
    }

    // Replace globalThis.SharedArrayBuffer with our shadow. Old code
    // that captured the original is the rare case — the global is
    // re-checked at every constructor call here.
    if (typeof globalThis.__host_sab_alloc === 'function') {
        globalThis.SharedArrayBuffer = _SAB;
    }

    function _sabFromView(view) {
        // Map a typed-array view over a SharedArrayBuffer to its
        // underlying region. Returns the buffer if it carries our
        // `_regionId` brand, null otherwise.
        var buf = view && view.buffer;
        if (!buf) return null;
        if (typeof buf._regionId === 'number') return buf;
        return null;
    }

    function _viewByteOffset(view, idx) {
        var bytesPerElement = view.BYTES_PER_ELEMENT || 1;
        return (view.byteOffset | 0) + ((idx | 0) * bytesPerElement);
    }

    // ---- Atomics (cross-process via __host_sab_*) -----------------
    //
    // For typed-array views over a `SharedArrayBuffer`, each Atomics
    // op routes through the host so the bytes the kernel sees are
    // exactly the slot the futex / wake operates on. Over a regular
    // (non-shared) `ArrayBuffer`, ops fall back to single-realm
    // semantics — there's no cross-process coherence to enforce.
    // Atomics ops simplify to their non-atomic equivalents because
    // there's no other thread to race with; the wait/notify
    // primitives raise — single-threaded code that calls `wait()`
    // would deadlock anyway, so a typed error beats a hang.
    if (typeof globalThis.Atomics === 'undefined') {
        function _ta(view) {
            if (!ArrayBuffer.isView(view)) {
                throw new TypeError('Atomics: argument is not a TypedArray');
            }
            return view;
        }
        globalThis.Atomics = {
            load: function(view, idx) {
                _ta(view);
                var sab = _sabFromView(view);
                if (sab) {
                    var w = view.BYTES_PER_ELEMENT === 8 ? 8 : 4;
                    var v = globalThis.__host_sab_atomic_load(
                        sab._regionId, _viewByteOffset(view, idx), w);
                    view[idx] = v;
                    return v;
                }
                return view[idx];
            },
            store: function(view, idx, value) {
                _ta(view);
                var sab = _sabFromView(view);
                if (sab) {
                    var w = view.BYTES_PER_ELEMENT === 8 ? 8 : 4;
                    globalThis.__host_sab_atomic_store(
                        sab._regionId, _viewByteOffset(view, idx), value, w);
                }
                view[idx] = value;
                return value;
            },
            add: function(view, idx, value) {
                _ta(view);
                var sab = _sabFromView(view);
                if (sab) {
                    var w = view.BYTES_PER_ELEMENT === 8 ? 8 : 4;
                    var off = _viewByteOffset(view, idx);
                    while (true) {
                        var cur = globalThis.__host_sab_atomic_load(sab._regionId, off, w);
                        var got = globalThis.__host_sab_atomic_cas(
                            sab._regionId, off, cur, cur + value, w);
                        if (got === cur) {
                            view[idx] = cur + value;
                            return cur;
                        }
                    }
                }
                var v = view[idx]; view[idx] = v + value; return v;
            },
            sub: function(view, idx, value) {
                _ta(view);
                var sab = _sabFromView(view);
                if (sab) {
                    var w = view.BYTES_PER_ELEMENT === 8 ? 8 : 4;
                    var off = _viewByteOffset(view, idx);
                    while (true) {
                        var cur = globalThis.__host_sab_atomic_load(sab._regionId, off, w);
                        var got = globalThis.__host_sab_atomic_cas(
                            sab._regionId, off, cur, cur - value, w);
                        if (got === cur) {
                            view[idx] = cur - value;
                            return cur;
                        }
                    }
                }
                var v = view[idx]; view[idx] = v - value; return v;
            },
            and: function(view, idx, value) {
                var v = _ta(view)[idx]; view[idx] = v & value; return v;
            },
            or: function(view, idx, value) {
                var v = _ta(view)[idx]; view[idx] = v | value; return v;
            },
            xor: function(view, idx, value) {
                var v = _ta(view)[idx]; view[idx] = v ^ value; return v;
            },
            exchange: function(view, idx, value) {
                _ta(view);
                var sab = _sabFromView(view);
                if (sab) {
                    var w = view.BYTES_PER_ELEMENT === 8 ? 8 : 4;
                    var off = _viewByteOffset(view, idx);
                    while (true) {
                        var cur = globalThis.__host_sab_atomic_load(sab._regionId, off, w);
                        var got = globalThis.__host_sab_atomic_cas(
                            sab._regionId, off, cur, value, w);
                        if (got === cur) {
                            view[idx] = value;
                            return cur;
                        }
                    }
                }
                var v = view[idx]; view[idx] = value; return v;
            },
            compareExchange: function(view, idx, expected, replacement) {
                _ta(view);
                var sab = _sabFromView(view);
                if (sab) {
                    var w = view.BYTES_PER_ELEMENT === 8 ? 8 : 4;
                    var got = globalThis.__host_sab_atomic_cas(
                        sab._regionId, _viewByteOffset(view, idx),
                        expected, replacement, w);
                    if (got === expected) view[idx] = replacement;
                    return got;
                }
                var v = view[idx];
                if (v === expected) view[idx] = replacement;
                return v;
            },
            isLockFree: function(_size) { return true; },
            wait: function(view, idx, value, timeout) {
                // Cross-process semantics when the view is over a
                // SharedArrayBuffer: route through the host's
                // futex / WaitOnAddress equivalent. Single-realm SAB
                // (or non-shared backing) falls through to a typed
                // error since blocking sync would deadlock the realm.
                _ta(view);
                var sab = _sabFromView(view);
                if (!sab) {
                    throw new TypeError(
                        'Atomics.wait: requires a SharedArrayBuffer-backed typed-array view'
                    );
                }
                var byteOffset = _viewByteOffset(view, idx);
                var to = (typeof timeout === 'number' && isFinite(timeout) && timeout >= 0)
                    ? (timeout | 0) : -1;
                var rc = globalThis.__host_sab_wait(sab._regionId, byteOffset, value | 0, to);
                if (rc === 0) return 'ok';
                if (rc === 1) return 'not-equal';
                if (rc === 2) return 'timed-out';
                throw new Error('Atomics.wait: rc=' + rc);
            },
            notify: function(view, idx, count) {
                _ta(view);
                if (count === undefined || count === null) count = Infinity;
                var sab = _sabFromView(view);
                if (sab) {
                    // Cross-process wake via the host's
                    // wake_one / wake_all primitive.
                    var byteOffset = _viewByteOffset(view, idx);
                    var n = count === Infinity ? -1 : (count | 0);
                    var rc = globalThis.__host_sab_notify(sab._regionId, byteOffset, n);
                    if (rc < 0) {
                        // ERR_OUT_OF_BOUNDS / ERR_BAD_ID surface as 0
                        // woken (matches spec — invalid args don't wake).
                        return 0;
                    }
                    // Single-realm waitAsync waiters parked on this
                    // same address still need a wake, but a process-
                    // level futex notify already covered them via
                    // their wait_async() path that's polling the same
                    // bytes. We additionally fire JS-side waiters for
                    // the local realm.
                    var key = _atomicsKey(view, idx);
                    var queue = _atomicsWaiters[key];
                    if (queue && queue.length > 0) {
                        var jsCount = count === Infinity ? queue.length : count;
                        var woken = 0;
                        while (woken < jsCount && queue.length > 0) {
                            var w = queue.shift();
                            if (w._timer) try { clearTimeout(w._timer); } catch (_) {}
                            if (!w._settled) { w._settled = true; w._resolve('ok'); }
                            woken++;
                        }
                        if (queue.length === 0) delete _atomicsWaiters[key];
                    }
                    return rc;
                }
                // Non-SAB path — single-realm waiter queue only.
                var key = _atomicsKey(view, idx);
                var queue = _atomicsWaiters[key];
                if (!queue || queue.length === 0) return 0;
                var n = 0;
                while (n < count && queue.length > 0) {
                    var w = queue.shift();
                    if (w._timer) {
                        try { clearTimeout(w._timer); } catch (_) {}
                    }
                    if (!w._settled) {
                        w._settled = true;
                        w._resolve('ok');
                    }
                    n++;
                }
                if (queue.length === 0) delete _atomicsWaiters[key];
                return n;
            },
            waitAsync: function(view, idx, value, timeout) {
                // Spec: if the slot already differs from `value`, return
                // synchronously with `not-equal`. Only enqueue the
                // waiter when the slot still matches.
                var actual = _ta(view)[idx];
                if (actual !== value) {
                    return { async: false, value: 'not-equal' };
                }
                var key = _atomicsKey(view, idx);
                var waiter = { _settled: false, _resolve: null, _timer: null };
                var p = new Promise(function(resolve) { waiter._resolve = resolve; });
                if (!_atomicsWaiters[key]) _atomicsWaiters[key] = [];
                _atomicsWaiters[key].push(waiter);
                if (typeof timeout === 'number' && timeout >= 0 && isFinite(timeout)) {
                    waiter._timer = setTimeout(function() {
                        if (waiter._settled) return;
                        var queue = _atomicsWaiters[key];
                        if (queue) {
                            var i = queue.indexOf(waiter);
                            if (i >= 0) queue.splice(i, 1);
                            if (queue.length === 0) delete _atomicsWaiters[key];
                        }
                        waiter._settled = true;
                        waiter._resolve('timed-out');
                    }, timeout);
                }
                return { async: true, value: p };
            },
        };

        // Per-(buffer, byte-offset) waiter queue. Keyed by the
        // underlying ArrayBuffer's identity (via WeakMap-assigned id)
        // joined with the byte offset of the view slot. Multiple
        // typed-array views over the same buffer with the same idx
        // map to the same key so a `notify(view2, idx)` wakes a
        // `waitAsync(view1, idx)` provided their offsets coincide
        // — that's exactly Atomics' wire contract.
        var _atomicsWaiters = Object.create(null);
        var _atomicsBufId = new WeakMap();
        var _atomicsNextBufId = 1;
        function _atomicsKey(view, idx) {
            var buf = view.buffer;
            var bufId = _atomicsBufId.get(buf);
            if (bufId === undefined) {
                bufId = _atomicsNextBufId++;
                _atomicsBufId.set(buf, bufId);
            }
            // Byte-offset normalises across views of different
            // element widths (Int32Array, BigInt64Array) so callers
            // synchronising via different views over the same buffer
            // see each other's waiters.
            var byteIdx = (view.byteOffset | 0) + (idx | 0) * view.BYTES_PER_ELEMENT;
            return bufId + ':' + byteIdx;
        }
    }

    // ---- Uint8Array base64 / hex (Stage 3 / Node 22+) -------------
    //
    // `arr.toBase64({alphabet?, omitPadding?})` /
    // `arr.toHex()` / `Uint8Array.fromBase64(s, opts?)` /
    // `Uint8Array.fromHex(s)`. Reuse Buffer for the actual codec
    // since Buffer is already wired through QuickJS's optimised
    // base64 path; the wrappers normalise the spec-shape options.
    if (typeof Uint8Array.prototype.toBase64 !== 'function') {
        Object.defineProperty(Uint8Array.prototype, 'toBase64', {
            value: function toBase64(options) {
                var Buf = globalThis.Buffer || require('buffer').Buffer;
                var s = Buf.from(this).toString('base64');
                var alphabet = (options && options.alphabet) || 'base64';
                if (alphabet === 'base64url') {
                    s = s.replace(/\+/g, '-').replace(/\//g, '_');
                }
                if (options && options.omitPadding) s = s.replace(/=+$/, '');
                return s;
            },
            writable: true, configurable: true,
        });
    }
    if (typeof Uint8Array.prototype.toHex !== 'function') {
        Object.defineProperty(Uint8Array.prototype, 'toHex', {
            value: function toHex() {
                var out = '';
                for (var i = 0; i < this.length; i++) {
                    var b = this[i];
                    if (b < 16) out += '0';
                    out += b.toString(16);
                }
                return out;
            },
            writable: true, configurable: true,
        });
    }
    if (typeof Uint8Array.fromBase64 !== 'function') {
        Object.defineProperty(Uint8Array, 'fromBase64', {
            value: function fromBase64(input, options) {
                var s = String(input);
                var alphabet = (options && options.alphabet) || 'base64';
                if (alphabet === 'base64url') {
                    s = s.replace(/-/g, '+').replace(/_/g, '/');
                    while (s.length % 4 !== 0) s += '=';
                }
                var Buf = globalThis.Buffer || require('buffer').Buffer;
                return new Uint8Array(Buf.from(s, 'base64'));
            },
            writable: true, configurable: true,
        });
    }
    if (typeof Uint8Array.fromHex !== 'function') {
        Object.defineProperty(Uint8Array, 'fromHex', {
            value: function fromHex(input) {
                var s = String(input);
                if (s.length % 2 !== 0) {
                    throw new SyntaxError('Uint8Array.fromHex: odd-length string');
                }
                var out = new Uint8Array(s.length / 2);
                for (var i = 0; i < out.length; i++) {
                    var hi = parseInt(s[i * 2], 16);
                    var lo = parseInt(s[i * 2 + 1], 16);
                    if (Number.isNaN(hi) || Number.isNaN(lo)) {
                        throw new SyntaxError('Uint8Array.fromHex: non-hex char');
                    }
                    out[i] = (hi << 4) | lo;
                }
                return out;
            },
            writable: true, configurable: true,
        });
    }

    // ---- Symbol.dispose / Symbol.asyncDispose (Node 20+) ------------
    // Installed FIRST because DisposableStack and AsyncDisposableStack
    // below register prototype methods keyed on these symbols. Spec
    // says they're well-known shared Symbols; idempotent if QuickJS
    // already added them.
    if (typeof Symbol.dispose === 'undefined') {
        Object.defineProperty(Symbol, 'dispose', {
            value: Symbol.for('Symbol.dispose'),
            writable: false, configurable: false, enumerable: false,
        });
    }
    if (typeof Symbol.asyncDispose === 'undefined') {
        Object.defineProperty(Symbol, 'asyncDispose', {
            value: Symbol.for('Symbol.asyncDispose'),
            writable: false, configurable: false, enumerable: false,
        });
    }

    // ---- reportError (Node 18+) -----------------------------------
    //
    // Browser/Node spec: dispatch the error as if it bubbled to the
    // global error handler. We surface it on stderr so it's visible
    // and dispatch an `error` event for any registered listeners.
    if (typeof globalThis.reportError !== 'function') {
        globalThis.reportError = function(err) {
            try {
                if (typeof globalThis.dispatchEvent === 'function'
                    && typeof globalThis.ErrorEvent === 'function') {
                    var ev = new globalThis.ErrorEvent('error', {
                        message: err && err.message ? err.message : String(err),
                        error: err,
                    });
                    globalThis.dispatchEvent(ev);
                }
            } catch (_) {}
            try {
                if (globalThis.console && typeof globalThis.console.error === 'function') {
                    globalThis.console.error(err);
                }
            } catch (_) {}
        };
    }

    // ---- scheduler API (Node 22+, Web stable since 2024) -----------
    //
    // `scheduler.wait(delay, opts)` → Promise that resolves after
    // `delay` ms (rejects if `opts.signal` aborts).
    // `scheduler.postTask(fn, opts)` → schedules a microtask-ish
    // callback and returns a Promise of its return value.
    if (typeof globalThis.scheduler !== 'object' || !globalThis.scheduler) {
        globalThis.scheduler = {
            wait: function(delay, opts) {
                var ms = delay | 0;
                var signal = opts && opts.signal;
                return new Promise(function(resolve, reject) {
                    if (signal && signal.aborted) {
                        return reject(signal.reason || new Error('Aborted'));
                    }
                    var t = setTimeout(function() { resolve(); }, ms);
                    if (signal) {
                        signal.addEventListener('abort', function() {
                            clearTimeout(t);
                            reject(signal.reason || new Error('Aborted'));
                        }, { once: true });
                    }
                });
            },
            postTask: function(fn, opts) {
                var signal = opts && opts.signal;
                if (signal && signal.aborted) {
                    return Promise.reject(signal.reason || new Error('Aborted'));
                }
                return new Promise(function(resolve, reject) {
                    queueMicrotask(function() {
                        if (signal && signal.aborted) {
                            return reject(signal.reason || new Error('Aborted'));
                        }
                        try { resolve(fn()); } catch (e) { reject(e); }
                    });
                });
            },
            yield: function() { return new Promise(function(r) { queueMicrotask(r); }); },
        };
    }

    // ---- DisposableStack / AsyncDisposableStack (Node 22+) --------
    //
    // TC39 explicit-resource-management aggregator: `using stack =
    // new DisposableStack();` then `stack.use(disposable)` registers
    // cleanups, `stack.dispose()` runs them in LIFO order.
    if (typeof globalThis.DisposableStack !== 'function') {
        function DisposableStack() {
            this._stack = [];
            this._disposed = false;
        }
        DisposableStack.prototype.use = function(value) {
            if (this._disposed) throw new ReferenceError('DisposableStack is disposed');
            if (value != null && typeof value[Symbol.dispose] === 'function') {
                this._stack.push(function() { value[Symbol.dispose](); });
            }
            return value;
        };
        DisposableStack.prototype.adopt = function(value, onDispose) {
            if (this._disposed) throw new ReferenceError('DisposableStack is disposed');
            this._stack.push(function() { onDispose(value); });
            return value;
        };
        DisposableStack.prototype.defer = function(onDispose) {
            if (this._disposed) throw new ReferenceError('DisposableStack is disposed');
            this._stack.push(onDispose);
        };
        DisposableStack.prototype.move = function() {
            if (this._disposed) throw new ReferenceError('DisposableStack is disposed');
            var fresh = new DisposableStack();
            fresh._stack = this._stack;
            this._stack = [];
            this._disposed = true;
            return fresh;
        };
        DisposableStack.prototype.dispose = function() {
            if (this._disposed) return;
            this._disposed = true;
            while (this._stack.length) {
                var fn = this._stack.pop();
                try { fn(); } catch (_) {}
            }
        };
        DisposableStack.prototype[Symbol.dispose] = DisposableStack.prototype.dispose;
        Object.defineProperty(DisposableStack.prototype, 'disposed', {
            get: function() { return this._disposed; },
        });
        globalThis.DisposableStack = DisposableStack;
    }
    if (typeof globalThis.AsyncDisposableStack !== 'function') {
        function AsyncDisposableStack() {
            this._stack = [];
            this._disposed = false;
        }
        AsyncDisposableStack.prototype.use = function(value) {
            if (this._disposed) throw new ReferenceError('AsyncDisposableStack is disposed');
            if (value != null) {
                if (typeof value[Symbol.asyncDispose] === 'function') {
                    this._stack.push(function() { return value[Symbol.asyncDispose](); });
                } else if (typeof value[Symbol.dispose] === 'function') {
                    this._stack.push(function() { return value[Symbol.dispose](); });
                }
            }
            return value;
        };
        AsyncDisposableStack.prototype.adopt = function(value, onDispose) {
            if (this._disposed) throw new ReferenceError('AsyncDisposableStack is disposed');
            this._stack.push(function() { return onDispose(value); });
            return value;
        };
        AsyncDisposableStack.prototype.defer = function(onDispose) {
            if (this._disposed) throw new ReferenceError('AsyncDisposableStack is disposed');
            this._stack.push(onDispose);
        };
        AsyncDisposableStack.prototype.move = function() {
            if (this._disposed) throw new ReferenceError('AsyncDisposableStack is disposed');
            var fresh = new AsyncDisposableStack();
            fresh._stack = this._stack;
            this._stack = [];
            this._disposed = true;
            return fresh;
        };
        AsyncDisposableStack.prototype.disposeAsync = async function() {
            if (this._disposed) return;
            this._disposed = true;
            while (this._stack.length) {
                var fn = this._stack.pop();
                try { await fn(); } catch (_) {}
            }
        };
        AsyncDisposableStack.prototype[Symbol.asyncDispose] = AsyncDisposableStack.prototype.disposeAsync;
        Object.defineProperty(AsyncDisposableStack.prototype, 'disposed', {
            get: function() { return this._disposed; },
        });
        globalThis.AsyncDisposableStack = AsyncDisposableStack;
    }

    // ---- Promise.withResolvers (Stage 4, Node 22) -------------------
    if (typeof Promise.withResolvers !== 'function') {
        Object.defineProperty(Promise, 'withResolvers', {
            value: function withResolvers() {
                var resolve, reject;
                var promise = new this(function(res, rej) { resolve = res; reject = rej; });
                return { promise: promise, resolve: resolve, reject: reject };
            },
            writable: true, configurable: true,
        });
    }

    // ---- Promise.try (Stage 3, Node 22+) ----------------------------
    // Run a sync callback, wrap return / throw into a Promise. Lets
    // callers fold sync-or-async producers into one Promise chain
    // without an extra `try / catch` ceremony.
    if (typeof Promise.try !== 'function') {
        Object.defineProperty(Promise, 'try', {
            value: function tryFn(fn /*, ...args */) {
                var args = Array.prototype.slice.call(arguments, 1);
                return new this(function(resolve) {
                    resolve(typeof fn === 'function' ? fn.apply(undefined, args) : fn);
                });
            },
            writable: true, configurable: true,
        });
    }

    // ---- Object.groupBy / Map.groupBy (ES2024) ----------------------
    if (typeof Object.groupBy !== 'function') {
        Object.defineProperty(Object, 'groupBy', {
            value: function groupBy(items, keyFn) {
                var out = Object.create(null);
                var i = 0;
                for (var it of items) {
                    var k = keyFn(it, i++);
                    var key = (typeof k === 'symbol') ? k : String(k);
                    if (!Object.prototype.hasOwnProperty.call(out, key)) out[key] = [];
                    out[key].push(it);
                }
                return out;
            },
            writable: true, configurable: true,
        });
    }
    if (typeof Map.groupBy !== 'function') {
        Object.defineProperty(Map, 'groupBy', {
            value: function groupBy(items, keyFn) {
                var out = new Map();
                var i = 0;
                for (var it of items) {
                    var k = keyFn(it, i++);
                    var arr = out.get(k);
                    if (!arr) { arr = []; out.set(k, arr); }
                    arr.push(it);
                }
                return out;
            },
            writable: true, configurable: true,
        });
    }

    // ---- Set.prototype set-theoretic methods (ES2024, Node 22) -----
    //
    // The spec is precise about argument shape: every method takes a
    // "set-like" — an object with `size`, `has`, and `keys` — *not*
    // necessarily a `Set` instance. The polyfill matches that contract
    // so the polyfill behaves like the native methods if a script
    // passes e.g. a Map or a custom collection.
    function _setLikeOf(other, name) {
        if (other == null || typeof other !== 'object' && typeof other !== 'function') {
            throw new TypeError('Set.prototype.' + name + ': argument is not set-like');
        }
        var size = other.size;
        if (typeof size !== 'number') {
            throw new TypeError('Set.prototype.' + name + ': argument is not set-like (size)');
        }
        if (typeof other.has !== 'function' || typeof other.keys !== 'function') {
            throw new TypeError('Set.prototype.' + name + ': argument is not set-like (has/keys)');
        }
        return { size: size, has: other.has.bind(other), keys: other.keys.bind(other) };
    }
    function _installSetMethod(name, impl) {
        if (typeof Set.prototype[name] === 'function') return;
        Object.defineProperty(Set.prototype, name, {
            value: impl, writable: true, configurable: true,
        });
    }
    _installSetMethod('intersection', function intersection(other) {
        var s = _setLikeOf(other, 'intersection');
        var result = new Set();
        // Iterate the smaller of (this, other) for O(min(n, m)).
        if (this.size <= s.size) {
            for (var v of this) if (s.has(v)) result.add(v);
        } else {
            var it = s.keys();
            for (var step = it.next(); !step.done; step = it.next()) {
                if (this.has(step.value)) result.add(step.value);
            }
        }
        return result;
    });
    _installSetMethod('union', function union(other) {
        var s = _setLikeOf(other, 'union');
        var result = new Set(this);
        var it = s.keys();
        for (var step = it.next(); !step.done; step = it.next()) {
            result.add(step.value);
        }
        return result;
    });
    _installSetMethod('difference', function difference(other) {
        var s = _setLikeOf(other, 'difference');
        var result = new Set();
        for (var v of this) if (!s.has(v)) result.add(v);
        return result;
    });
    _installSetMethod('symmetricDifference', function symmetricDifference(other) {
        var s = _setLikeOf(other, 'symmetricDifference');
        var result = new Set();
        for (var v of this) if (!s.has(v)) result.add(v);
        var it = s.keys();
        for (var step = it.next(); !step.done; step = it.next()) {
            if (!this.has(step.value)) result.add(step.value);
        }
        return result;
    });
    _installSetMethod('isSubsetOf', function isSubsetOf(other) {
        var s = _setLikeOf(other, 'isSubsetOf');
        if (this.size > s.size) return false;
        for (var v of this) if (!s.has(v)) return false;
        return true;
    });
    _installSetMethod('isSupersetOf', function isSupersetOf(other) {
        var s = _setLikeOf(other, 'isSupersetOf');
        if (this.size < s.size) return false;
        var it = s.keys();
        for (var step = it.next(); !step.done; step = it.next()) {
            if (!this.has(step.value)) return false;
        }
        return true;
    });
    _installSetMethod('isDisjointFrom', function isDisjointFrom(other) {
        var s = _setLikeOf(other, 'isDisjointFrom');
        if (this.size <= s.size) {
            for (var v of this) if (s.has(v)) return false;
        } else {
            var it = s.keys();
            for (var step = it.next(); !step.done; step = it.next()) {
                if (this.has(step.value)) return false;
            }
        }
        return true;
    });

    // ============================================================
    // URLPattern — WHATWG URL Pattern Standard.
    //
    // Supports the canonical shape used by routing libraries:
    //   new URLPattern({ pathname: '/users/:id' })
    //   new URLPattern('https://*.example.com/:path*')
    //   pattern.test(input) / pattern.exec(input)
    //
    // The matcher converts each component pattern into a RegExp with
    // named groups and a small wildcard grammar:
    //
    //   :name        capture (one segment, no `/`)
    //   :name(re)    capture with custom inline regex
    //   *            wildcard (zero-or-more anything)
    //   {x}          group
    //   {x}?         optional group
    //
    // Not implemented: pattern modifiers `?`/`+` after capture
    // groups (rare in practice). Real URL Pattern Standard supports
    // them — extend if a real workload surfaces.
    // ============================================================
    // ============================================================
    // WebSocket client (RFC 6455).
    //
    // Builds on top of `net.connect` / `tls.connect` so no new
    // Rust host fns are needed. Performs the HTTP/1.1 Upgrade
    // handshake (verifies `Sec-WebSocket-Accept`), then frames
    // text / binary / close / ping / pong per the spec. Client
    // → server frames are masked with a random 4-byte key.
    //
    // Surface matches WHATWG WebSocket: constructor(url[, protocols]),
    // `.send(data)` for string / ArrayBuffer / TypedArray / Blob,
    // `.close(code?, reason?)`, `readyState` (0..3),
    // `addEventListener`, on{open,message,error,close} setters,
    // `binaryType` ('blob' | 'arraybuffer'). Subprotocol negotiation
    // through the `protocols` argument; `extensions` left empty.
    // ============================================================
    if (typeof globalThis.WebSocket !== 'function') {
        var WS_CONNECTING = 0, WS_OPEN = 1, WS_CLOSING = 2, WS_CLOSED = 3;
        var WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';

        function _ws_random16() {
            var arr = new Uint8Array(16);
            globalThis.crypto.getRandomValues(arr);
            return arr;
        }
        function _ws_b64(bytes) {
            // node:buffer is available in our polyfill bundle.
            var Buf = globalThis.Buffer || (require('buffer') && require('buffer').Buffer);
            return Buf.from(bytes).toString('base64');
        }
        function _ws_sha1_b64(input) {
            // SHA-1 + base64 — used to verify Sec-WebSocket-Accept.
            var nc = require('crypto');
            var h = nc.createHash('sha1');
            h.update(input);
            var hex = h.digest('hex');
            var bytes = new Uint8Array(hex.length / 2);
            for (var i = 0; i < bytes.length; i++) {
                bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
            }
            return _ws_b64(bytes);
        }
        function _ws_parseUrl(url) {
            // Reuse globalThis.URL — we just need scheme/host/port/path.
            var u = new URL(url);
            var secure = u.protocol === 'wss:' || u.protocol === 'https:';
            var port = u.port ? parseInt(u.port, 10) : (secure ? 443 : 80);
            return { secure: secure, host: u.hostname, port: port,
                     path: u.pathname + (u.search || '') };
        }

        function _ws_buildHandshake(parsed, key, protocols) {
            var lines = [
                'GET ' + parsed.path + ' HTTP/1.1',
                'Host: ' + parsed.host + (parsed.port !== (parsed.secure ? 443 : 80)
                    ? ':' + parsed.port : ''),
                'Upgrade: websocket',
                'Connection: Upgrade',
                'Sec-WebSocket-Key: ' + key,
                'Sec-WebSocket-Version: 13',
            ];
            if (protocols && protocols.length) {
                var list = Array.isArray(protocols) ? protocols : [protocols];
                lines.push('Sec-WebSocket-Protocol: ' + list.join(', '));
            }
            return lines.join('\r\n') + '\r\n\r\n';
        }

        function _ws_encodeFrame(opcode, payload) {
            // RFC 6455 §5.2. Client→server frames are masked.
            var Buf = globalThis.Buffer || require('buffer').Buffer;
            var data = (typeof payload === 'string') ? Buf.from(payload, 'utf8')
                     : Buf.isBuffer(payload) ? payload
                     : Buf.from(payload);
            var len = data.length;
            var hdr;
            var maskOffset;
            if (len < 126) {
                hdr = Buf.alloc(2 + 4);
                hdr[0] = 0x80 | (opcode & 0x0F); // FIN=1
                hdr[1] = 0x80 | len; // MASK=1, len
                maskOffset = 2;
            } else if (len < 65536) {
                hdr = Buf.alloc(4 + 4);
                hdr[0] = 0x80 | (opcode & 0x0F);
                hdr[1] = 0x80 | 126;
                hdr[2] = (len >> 8) & 0xFF;
                hdr[3] = len & 0xFF;
                maskOffset = 4;
            } else {
                hdr = Buf.alloc(10 + 4);
                hdr[0] = 0x80 | (opcode & 0x0F);
                hdr[1] = 0x80 | 127;
                // 64-bit length, big-endian. JS ints are 53-bit safe; cap
                // at 2^31-1 here. Real-world payloads above 2 GiB hit
                // memory caps anyway.
                hdr.writeUInt32BE(0, 2);
                hdr.writeUInt32BE(len, 6);
                maskOffset = 10;
            }
            var mask = new Uint8Array(4);
            globalThis.crypto.getRandomValues(mask);
            hdr[maskOffset]     = mask[0];
            hdr[maskOffset + 1] = mask[1];
            hdr[maskOffset + 2] = mask[2];
            hdr[maskOffset + 3] = mask[3];
            var masked = Buf.alloc(len);
            for (var i = 0; i < len; i++) masked[i] = data[i] ^ mask[i % 4];
            return Buf.concat([hdr, masked]);
        }

        function _ws_decodeFrames(buffer) {
            // Returns { frames: [{opcode, payload, fin}], rest: Buffer }
            // server→client frames are NOT masked.
            var frames = [];
            var p = 0;
            while (p + 2 <= buffer.length) {
                var b1 = buffer[p];
                var b2 = buffer[p + 1];
                var fin = (b1 & 0x80) !== 0;
                var opcode = b1 & 0x0F;
                var masked = (b2 & 0x80) !== 0;
                var len = b2 & 0x7F;
                var hdrLen = 2;
                if (len === 126) {
                    if (buffer.length < p + 4) break;
                    len = buffer.readUInt16BE(p + 2);
                    hdrLen = 4;
                } else if (len === 127) {
                    if (buffer.length < p + 10) break;
                    // Top 32 bits ignored — see encode comment.
                    len = buffer.readUInt32BE(p + 6);
                    hdrLen = 10;
                }
                var maskKey = null;
                if (masked) {
                    if (buffer.length < p + hdrLen + 4) break;
                    maskKey = buffer.slice(p + hdrLen, p + hdrLen + 4);
                    hdrLen += 4;
                }
                if (buffer.length < p + hdrLen + len) break;
                var payload = buffer.slice(p + hdrLen, p + hdrLen + len);
                if (masked) {
                    var unmasked = globalThis.Buffer.alloc(len);
                    for (var i = 0; i < len; i++) unmasked[i] = payload[i] ^ maskKey[i % 4];
                    payload = unmasked;
                }
                frames.push({ opcode: opcode, payload: payload, fin: fin });
                p += hdrLen + len;
            }
            return { frames: frames, rest: buffer.slice(p) };
        }

        function WebSocket(url, protocols) {
            if (!(this instanceof WebSocket)) {
                throw new TypeError('WebSocket is a constructor');
            }
            this.url = String(url);
            this.readyState = WS_CONNECTING;
            this.binaryType = 'blob';
            this.bufferedAmount = 0;
            this.extensions = '';
            this.protocol = '';
            this.onopen = null;
            this.onmessage = null;
            this.onerror = null;
            this.onclose = null;
            this._listeners = Object.create(null);
            this._handshakeBuf = globalThis.Buffer.alloc(0);
            this._frameBuf = globalThis.Buffer.alloc(0);
            this._handshakeDone = false;
            this._fragments = [];
            this._fragmentOpcode = 0;

            var parsed = _ws_parseUrl(this.url);
            var key = _ws_b64(_ws_random16());
            this._handshakeKey = key;
            this._expectedAccept = _ws_sha1_b64(key + WS_GUID);

            var connectMod = parsed.secure ? 'tls' : 'net';
            var sock;
            try {
                var mod = require(connectMod);
                sock = mod.connect({
                    host: parsed.host,
                    port: parsed.port,
                    servername: parsed.host,
                });
            } catch (e) {
                this._fireError(e);
                this._setReadyState(WS_CLOSED);
                return;
            }
            this._sock = sock;

            var self = this;
            sock.once('connect', function() {
                try {
                    sock.write(_ws_buildHandshake(parsed, key, protocols));
                } catch (e) { self._fireError(e); }
            });
            // TLS sockets fire 'secureConnect' after the TLS handshake;
            // both shapes work here because net's connect→data flow
            // matches.
            sock.once('secureConnect', function() {
                try {
                    sock.write(_ws_buildHandshake(parsed, key, protocols));
                } catch (e) { self._fireError(e); }
            });
            sock.on('data', function(chunk) {
                if (!self._handshakeDone) {
                    self._handshakeBuf = globalThis.Buffer.concat([self._handshakeBuf, chunk]);
                    var idx = self._handshakeBuf.indexOf('\r\n\r\n');
                    if (idx < 0) return;
                    var head = self._handshakeBuf.slice(0, idx).toString('utf8');
                    var rest = self._handshakeBuf.slice(idx + 4);
                    self._handshakeBuf = globalThis.Buffer.alloc(0);
                    if (!self._verifyHandshake(head)) return;
                    self._handshakeDone = true;
                    self._setReadyState(WS_OPEN);
                    self._fire('open', {});
                    if (rest.length) self._handleData(rest);
                    return;
                }
                self._handleData(chunk);
            });
            sock.on('error', function(e) {
                self._fireError(e);
                self._setReadyState(WS_CLOSED);
                self._fire('close', { code: 1006, reason: '', wasClean: false });
            });
            sock.on('close', function() {
                if (self.readyState !== WS_CLOSED) {
                    self._setReadyState(WS_CLOSED);
                    self._fire('close', { code: 1006, reason: '', wasClean: false });
                }
            });
        }
        WebSocket.CONNECTING = WS_CONNECTING;
        WebSocket.OPEN = WS_OPEN;
        WebSocket.CLOSING = WS_CLOSING;
        WebSocket.CLOSED = WS_CLOSED;
        WebSocket.prototype.CONNECTING = WS_CONNECTING;
        WebSocket.prototype.OPEN = WS_OPEN;
        WebSocket.prototype.CLOSING = WS_CLOSING;
        WebSocket.prototype.CLOSED = WS_CLOSED;

        WebSocket.prototype._setReadyState = function(s) { this.readyState = s; };
        WebSocket.prototype._fireError = function(err) {
            var e = (err && err.message) ? err : new Error(String(err || 'WebSocket error'));
            this._fire('error', { error: e, message: e.message });
        };
        WebSocket.prototype._fire = function(type, detail) {
            var ev = Object.assign({ type: type, target: this }, detail || {});
            var prop = 'on' + type;
            try { if (typeof this[prop] === 'function') this[prop](ev); } catch (_) {}
            var arr = this._listeners[type];
            if (arr) {
                for (var i = 0; i < arr.length; i++) {
                    try { arr[i](ev); } catch (_) {}
                }
            }
        };
        WebSocket.prototype._verifyHandshake = function(head) {
            var lines = head.split('\r\n');
            var status = lines[0] || '';
            if (status.indexOf(' 101 ') === -1) {
                this._fireError(new Error('WebSocket handshake failed: ' + status));
                this._setReadyState(WS_CLOSED);
                this._fire('close', { code: 1006, reason: '', wasClean: false });
                return false;
            }
            var accept = '';
            var protocol = '';
            for (var i = 1; i < lines.length; i++) {
                var c = lines[i].indexOf(':');
                if (c < 0) continue;
                var name = lines[i].slice(0, c).trim().toLowerCase();
                var value = lines[i].slice(c + 1).trim();
                if (name === 'sec-websocket-accept') accept = value;
                else if (name === 'sec-websocket-protocol') protocol = value;
            }
            if (accept !== this._expectedAccept) {
                this._fireError(new Error('WebSocket handshake: bad Sec-WebSocket-Accept'));
                this._setReadyState(WS_CLOSED);
                this._fire('close', { code: 1006, reason: '', wasClean: false });
                return false;
            }
            this.protocol = protocol;
            return true;
        };
        WebSocket.prototype._handleData = function(chunk) {
            this._frameBuf = globalThis.Buffer.concat([this._frameBuf, chunk]);
            var dec = _ws_decodeFrames(this._frameBuf);
            this._frameBuf = dec.rest;
            for (var i = 0; i < dec.frames.length; i++) this._handleFrame(dec.frames[i]);
        };
        WebSocket.prototype._handleFrame = function(frame) {
            switch (frame.opcode) {
                case 0x0: // continuation
                    this._fragments.push(frame.payload);
                    if (frame.fin) {
                        var full = globalThis.Buffer.concat(this._fragments);
                        this._fragments = [];
                        this._dispatchMessage(this._fragmentOpcode, full);
                    }
                    break;
                case 0x1: // text
                case 0x2: // binary
                    if (frame.fin) {
                        this._dispatchMessage(frame.opcode, frame.payload);
                    } else {
                        this._fragments = [frame.payload];
                        this._fragmentOpcode = frame.opcode;
                    }
                    break;
                case 0x8: // close
                    var code = frame.payload.length >= 2 ? frame.payload.readUInt16BE(0) : 1005;
                    var reason = frame.payload.length > 2
                        ? frame.payload.slice(2).toString('utf8') : '';
                    this._setReadyState(WS_CLOSING);
                    try { this._sock.write(_ws_encodeFrame(0x8, frame.payload)); } catch (_) {}
                    try { this._sock.end(); } catch (_) {}
                    this._setReadyState(WS_CLOSED);
                    this._fire('close', { code: code, reason: reason, wasClean: true });
                    break;
                case 0x9: // ping → respond with pong, same payload
                    try { this._sock.write(_ws_encodeFrame(0xA, frame.payload)); } catch (_) {}
                    break;
                case 0xA: // pong → ignore
                    break;
                default:
                    // Unknown opcode → fail the connection per spec.
                    this._fireError(new Error('WebSocket: unknown opcode ' + frame.opcode));
                    try { this._sock.end(); } catch (_) {}
                    break;
            }
        };
        WebSocket.prototype._dispatchMessage = function(opcode, payload) {
            var data;
            if (opcode === 0x1) {
                data = payload.toString('utf8');
            } else if (this.binaryType === 'arraybuffer') {
                var ab = new ArrayBuffer(payload.length);
                new Uint8Array(ab).set(payload);
                data = ab;
            } else {
                // 'blob' default — surface as Buffer (Blob exists but the
                // canonical browser shape is opaque; node's `ws` package
                // surfaces Buffer here too).
                data = payload;
            }
            this._fire('message', { data: data });
        };
        WebSocket.prototype.send = function(data) {
            if (this.readyState !== WS_OPEN) {
                throw new Error('WebSocket is not open: readyState ' + this.readyState);
            }
            var opcode = (typeof data === 'string') ? 0x1 : 0x2;
            var Buf = globalThis.Buffer;
            var payload;
            if (typeof data === 'string') {
                payload = Buf.from(data, 'utf8');
            } else if (data instanceof ArrayBuffer) {
                payload = Buf.from(new Uint8Array(data));
            } else if (ArrayBuffer.isView(data)) {
                payload = Buf.from(data.buffer, data.byteOffset, data.byteLength);
            } else if (Buf.isBuffer(data)) {
                payload = data;
            } else {
                payload = Buf.from(String(data), 'utf8');
            }
            try { this._sock.write(_ws_encodeFrame(opcode, payload)); }
            catch (e) { this._fireError(e); }
        };
        WebSocket.prototype.close = function(code, reason) {
            if (this.readyState >= WS_CLOSING) return;
            this._setReadyState(WS_CLOSING);
            var Buf = globalThis.Buffer;
            var payload = Buf.alloc(0);
            if (typeof code === 'number') {
                var rb = reason ? Buf.from(String(reason), 'utf8') : Buf.alloc(0);
                payload = Buf.alloc(2 + rb.length);
                payload.writeUInt16BE(code, 0);
                if (rb.length) rb.copy(payload, 2);
            }
            try { this._sock.write(_ws_encodeFrame(0x8, payload)); } catch (_) {}
            try { this._sock.end(); } catch (_) {}
        };
        WebSocket.prototype.addEventListener = function(type, listener) {
            if (typeof listener !== 'function') return;
            if (!this._listeners[type]) this._listeners[type] = [];
            this._listeners[type].push(listener);
        };
        WebSocket.prototype.removeEventListener = function(type, listener) {
            var arr = this._listeners[type];
            if (!arr) return;
            var idx = arr.indexOf(listener);
            if (idx >= 0) arr.splice(idx, 1);
        };
        WebSocket.prototype.dispatchEvent = function(event) {
            if (event && typeof event.type === 'string') this._fire(event.type, event);
            return true;
        };

        globalThis.WebSocket = WebSocket;
    }

    // ============================================================
    // EventSource (Server-Sent Events client).
    //
    // RFC 6202 / WHATWG. Built on `fetch`. Our fetch buffers the
    // whole response body (no streaming), so this implementation is
    // best-effort: it issues a request, parses every `data:` event
    // out of the returned body in one pass, fires `message` events,
    // and reconnects per the `retry:` directive (or 3s default).
    // Works perfectly for finite SSE responses where the server
    // sends N events then closes; longer-lived infinite streams
    // would benefit from streaming HTTP responses (separate feature).
    // ============================================================
    if (typeof globalThis.EventSource !== 'function') {
        var ES_CONNECTING = 0, ES_OPEN = 1, ES_CLOSED = 2;
        function EventSource(url, init) {
            if (!(this instanceof EventSource)) {
                throw new TypeError('EventSource is a constructor');
            }
            this.url = String(url);
            this.readyState = ES_CONNECTING;
            this.withCredentials = !!(init && init.withCredentials);
            this.onopen = null;
            this.onmessage = null;
            this.onerror = null;
            this._listeners = Object.create(null);
            this._lastEventId = '';
            this._retryMs = 3000;
            this._closed = false;
            this._connect();
        }
        EventSource.CONNECTING = ES_CONNECTING;
        EventSource.OPEN = ES_OPEN;
        EventSource.CLOSED = ES_CLOSED;
        EventSource.prototype.CONNECTING = ES_CONNECTING;
        EventSource.prototype.OPEN = ES_OPEN;
        EventSource.prototype.CLOSED = ES_CLOSED;

        EventSource.prototype._fire = function(type, detail) {
            var ev = Object.assign({ type: type, target: this }, detail || {});
            var prop = 'on' + type;
            try { if (typeof this[prop] === 'function') this[prop](ev); } catch (_) {}
            var arr = this._listeners[type];
            if (arr) for (var i = 0; i < arr.length; i++) {
                try { arr[i](ev); } catch (_) {}
            }
        };
        EventSource.prototype.addEventListener = function(type, listener) {
            if (typeof listener !== 'function') return;
            if (!this._listeners[type]) this._listeners[type] = [];
            this._listeners[type].push(listener);
        };
        EventSource.prototype.removeEventListener = function(type, listener) {
            var arr = this._listeners[type];
            if (!arr) return;
            var idx = arr.indexOf(listener);
            if (idx >= 0) arr.splice(idx, 1);
        };
        EventSource.prototype.dispatchEvent = function(event) {
            if (event && typeof event.type === 'string') this._fire(event.type, event);
            return true;
        };
        EventSource.prototype.close = function() {
            this._closed = true;
            this.readyState = ES_CLOSED;
        };

        EventSource.prototype._connect = function() {
            if (this._closed) return;
            var self = this;
            var headers = { 'Accept': 'text/event-stream' };
            if (this._lastEventId) headers['Last-Event-ID'] = this._lastEventId;
            // Use the global fetch installed at the top of the
            // bundle. Buffered body comes back as text — we parse
            // the whole stream at once.
            globalThis.fetch(this.url, { headers: headers }).then(function(resp) {
                if (self._closed) return;
                if (!resp.ok) {
                    self._fire('error', { message: 'EventSource HTTP ' + resp.status });
                    self._scheduleReconnect();
                    return;
                }
                self.readyState = ES_OPEN;
                self._fire('open', {});
                return resp.text().then(function(body) {
                    self._parse(body);
                    self._scheduleReconnect();
                });
            }).catch(function(e) {
                if (self._closed) return;
                self._fire('error', { message: e && e.message });
                self._scheduleReconnect();
            });
        };

        EventSource.prototype._scheduleReconnect = function() {
            if (this._closed) return;
            var self = this;
            this.readyState = ES_CONNECTING;
            setTimeout(function() { self._connect(); }, this._retryMs);
        };

        EventSource.prototype._parse = function(body) {
            // Split into events on blank lines (\n\n or \r\n\r\n).
            // Each event is a sequence of `field: value` lines.
            var events = String(body).split(/\r?\n\r?\n/);
            for (var i = 0; i < events.length; i++) {
                var raw = events[i];
                if (!raw) continue;
                var lines = raw.split(/\r?\n/);
                var name = 'message';
                var data = '';
                var id = null;
                for (var j = 0; j < lines.length; j++) {
                    var line = lines[j];
                    if (!line || line.charAt(0) === ':') continue;
                    var c = line.indexOf(':');
                    var field = c < 0 ? line : line.slice(0, c);
                    var value = c < 0 ? '' : line.slice(c + 1);
                    if (value.charAt(0) === ' ') value = value.slice(1);
                    if (field === 'event') name = value;
                    else if (field === 'data') data += (data ? '\n' : '') + value;
                    else if (field === 'id') id = value;
                    else if (field === 'retry') {
                        var n = parseInt(value, 10);
                        if (!isNaN(n) && n > 0) this._retryMs = n;
                    }
                }
                if (id !== null) this._lastEventId = id;
                if (data === '' && lines.length === 1 && lines[0] === '') continue;
                this._fire(name, { data: data, lastEventId: this._lastEventId, origin: this.url });
            }
        };
        globalThis.EventSource = EventSource;
    }

    if (typeof globalThis.URLPattern !== 'function') {
        var COMPONENTS = ['protocol', 'username', 'password', 'hostname', 'port',
                          'pathname', 'search', 'hash'];

        function compileURLPattern(pat, isPath) {
            // Empty pattern → match anything.
            if (pat === undefined || pat === null || pat === '') {
                return { regex: /^.*$/, names: [] };
            }
            var src = String(pat);
            var out = '^';
            var names = [];
            var i = 0;
            while (i < src.length) {
                var c = src[i];
                if (c === '\\') {
                    // Escape: copy the next char raw.
                    if (i + 1 < src.length) {
                        out += '\\' + src[i + 1];
                        i += 2;
                    } else {
                        out += '\\\\';
                        i += 1;
                    }
                    continue;
                }
                if (c === ':' && /[A-Za-z_$]/.test(src[i + 1] || '')) {
                    // Capture group `:name` or `:name(regex)`.
                    var j = i + 1;
                    while (j < src.length && /[A-Za-z0-9_$]/.test(src[j])) j++;
                    var name = src.slice(i + 1, j);
                    var re;
                    if (src[j] === '(') {
                        var depth = 1, k = j + 1;
                        while (k < src.length && depth > 0) {
                            if (src[k] === '\\') { k += 2; continue; }
                            if (src[k] === '(') depth++;
                            else if (src[k] === ')') depth--;
                            if (depth > 0) k++;
                        }
                        re = src.slice(j + 1, k);
                        j = k + 1; // past `)`
                    } else {
                        re = isPath ? '[^/]+' : '[^/]+';
                    }
                    names.push(name);
                    out += '(' + re + ')';
                    i = j;
                    continue;
                }
                if (c === '*') {
                    out += '.*';
                    i += 1;
                    continue;
                }
                // Regex metacharacters get escaped so the literal text
                // matches itself, not as a metacharacter.
                if ('.^$+?()[]{}|'.indexOf(c) !== -1) {
                    out += '\\' + c;
                } else {
                    out += c;
                }
                i += 1;
            }
            out += '$';
            return { regex: new RegExp(out), names: names };
        }

        function URLPattern(input, baseURL) {
            if (!(this instanceof URLPattern)) {
                throw new TypeError('URLPattern is a constructor');
            }
            var spec = {};
            if (typeof input === 'string') {
                // Parse as URL pattern string. Use the first absolute
                // separator to split off scheme + host + path; we
                // rely on the URL parser for the easy split, then
                // assign each piece's pattern.
                try {
                    // The URL parser doesn't accept `:name` syntax in
                    // the path — temporarily encode `:` so URL parses,
                    // then decode.
                    var encoded = input.replace(/:([A-Za-z_$][A-Za-z0-9_$]*)/g, '__AB_URLP_$1__');
                    var u = new URL(encoded, baseURL || 'http://x.invalid/');
                    var dec = function(s) { return s.replace(/__AB_URLP_([A-Za-z0-9_$]+)__/g, ':$1'); };
                    spec.protocol = dec(u.protocol.replace(/:$/, ''));
                    spec.hostname = dec(u.hostname);
                    spec.port = dec(u.port);
                    spec.pathname = dec(u.pathname);
                    spec.search = dec(u.search.replace(/^\?/, ''));
                    spec.hash = dec(u.hash.replace(/^#/, ''));
                } catch (_) {
                    spec.pathname = input;
                }
            } else if (input && typeof input === 'object') {
                for (var k = 0; k < COMPONENTS.length; k++) {
                    if (input[COMPONENTS[k]] !== undefined) {
                        spec[COMPONENTS[k]] = String(input[COMPONENTS[k]]);
                    }
                }
            } else {
                throw new TypeError('URLPattern: input must be a string or object');
            }
            this._compiled = {};
            for (var n = 0; n < COMPONENTS.length; n++) {
                var name = COMPONENTS[n];
                this._compiled[name] = compileURLPattern(spec[name], name === 'pathname');
            }
        }

        function _exec(self, input) {
            var u;
            try {
                if (typeof input === 'string') u = new URL(input);
                else if (input && typeof input === 'object') {
                    // input shape: { pathname, search, ... } or full URL
                    u = {
                        protocol: (input.protocol || '').replace(/:$/, ''),
                        username: input.username || '',
                        password: input.password || '',
                        hostname: input.hostname || '',
                        port: input.port || '',
                        pathname: input.pathname || '',
                        search: (input.search || '').replace(/^\?/, ''),
                        hash: (input.hash || '').replace(/^#/, ''),
                    };
                } else {
                    return null;
                }
            } catch (_) { return null; }

            var inputs = {
                protocol: (u.protocol || '').replace(/:$/, ''),
                username: u.username || '',
                password: u.password || '',
                hostname: u.hostname || '',
                port: u.port || '',
                pathname: u.pathname || '',
                search: (u.search || '').replace(/^\?/, ''),
                hash: (u.hash || '').replace(/^#/, ''),
            };
            var result = { inputs: [input] };
            for (var i = 0; i < COMPONENTS.length; i++) {
                var name = COMPONENTS[i];
                var c = self._compiled[name];
                var m = c.regex.exec(inputs[name]);
                if (!m) return null;
                var groups = {};
                for (var g = 0; g < c.names.length; g++) {
                    groups[c.names[g]] = m[g + 1];
                }
                result[name] = { input: inputs[name], groups: groups };
            }
            return result;
        }

        URLPattern.prototype.test = function(input) { return _exec(this, input) !== null; };
        URLPattern.prototype.exec = function(input) { return _exec(this, input); };
        // Spec accessors (return the source pattern strings). Best-
        // effort: we don't reconstruct the original `:name` form, just
        // return a compiled regex source so `console.log(p.pathname)`
        // is at least informative.
        for (var ci = 0; ci < COMPONENTS.length; ci++) {
            (function(name) {
                Object.defineProperty(URLPattern.prototype, name, {
                    get: function() { return this._compiled[name].regex.source; },
                    configurable: true,
                });
            })(COMPONENTS[ci]);
        }

        globalThis.URLPattern = URLPattern;
    }
})();

// ---- web_subtle_full.js ----
// Web Crypto Subtle — round-out to full Node 26 / WHATWG parity.
//
// `web_compat.js` ships a base SubtleCrypto with AES-GCM/CBC + HMAC +
// PBKDF2 + HKDF + SHA-* digest. This file extends it with everything
// else Node 26 lists as stable: AES-CTR, AES-KW, RSA-OAEP / RSA-PSS /
// RSASSA-PKCS1-v1_5, ECDSA / ECDH on P-256/384/521, Ed25519, X25519.
//
// The dispatch routes through a single host import,
// `__host_crypto_subtle_op(op, args_json)`, which pure-Rust implements
// every algorithm. JS handles parameter shaping + key shaping; the
// host does crypto. This keeps the JS surface tight and the trust
// boundary inside Rust.
//
// All wire bytes cross as base64url-encoded strings. The dispatcher
// returns either a base64url string (single output) or a JSON
// `["<b64>","<b64>"]` array (key-pair output).

(function installFullSubtle() {
    if (typeof globalThis.crypto !== 'object' || !globalThis.crypto.subtle) {
        return; // no base subtle — web_compat.js is the gate
    }
    var subtle = globalThis.crypto.subtle;

    function _toBytes(input) {
        if (input == null) return new Uint8Array(0);
        if (input instanceof ArrayBuffer) return new Uint8Array(input);
        if (ArrayBuffer.isView(input)) {
            return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
        }
        if (typeof input === 'string') return new TextEncoder().encode(input);
        return new Uint8Array(input);
    }
    function _b64UrlEncodeBytes(bytes) {
        var Buf = globalThis.Buffer || require('buffer').Buffer;
        return Buf.from(bytes).toString('base64')
            .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }
    function _b64UrlDecodeToBytes(b64) {
        var s = String(b64).replace(/-/g, '+').replace(/_/g, '/');
        while (s.length % 4 !== 0) s += '=';
        var Buf = globalThis.Buffer || require('buffer').Buffer;
        return new Uint8Array(Buf.from(s, 'base64'));
    }
    function _algoName(a) {
        return (typeof a === 'string') ? a.toLowerCase()
             : (a && a.name) ? String(a.name).toLowerCase()
             : '';
    }
    function _hashCanonical(h) {
        // Web Crypto canonical: 'SHA-256'; we accept lowercase + sha256.
        var s = (typeof h === 'string') ? h : (h && h.name) || '';
        s = String(s).toUpperCase();
        if (s === 'SHA1' || s === 'SHA-1') return 'SHA-1';
        if (s === 'SHA224' || s === 'SHA-224') return 'SHA-224';
        if (s === 'SHA256' || s === 'SHA-256') return 'SHA-256';
        if (s === 'SHA384' || s === 'SHA-384') return 'SHA-384';
        if (s === 'SHA512' || s === 'SHA-512') return 'SHA-512';
        return s;
    }
    function _curveCanonical(c) {
        if (!c) return '';
        var s = String(c).toUpperCase().replace(/[_]/g, '-');
        if (s === 'P-256' || s === 'P256') return 'P-256';
        if (s === 'P-384' || s === 'P384') return 'P-384';
        if (s === 'P-521' || s === 'P521') return 'P-521';
        return s;
    }
    function _hashFromCurve(curve) {
        if (curve === 'P-256') return 'SHA-256';
        if (curve === 'P-384') return 'SHA-384';
        if (curve === 'P-521') return 'SHA-512';
        return 'SHA-256';
    }

    // --- single dispatcher -------------------------------------------
    function _hostOp(op, byteArgs) {
        if (typeof globalThis.__host_crypto_subtle_op !== 'function') {
            throw new Error('crypto.subtle: host dispatcher missing — '
                + 'rebuild plugin to expose __host_crypto_subtle_op');
        }
        var jsonArgs = '[' + byteArgs.map(function(b) {
            return JSON.stringify(_b64UrlEncodeBytes(_toBytes(b)));
        }).join(',') + ']';
        var out = globalThis.__host_crypto_subtle_op(op, jsonArgs);
        if (typeof out === 'string' && out.indexOf('__HOST_ERR__:') === 0) {
            throw new Error(out.slice('__HOST_ERR__:'.length));
        }
        return out;
    }
    function _hostOpBytes(op, byteArgs) {
        return _b64UrlDecodeToBytes(_hostOp(op, byteArgs));
    }
    function _hostOpPair(op, byteArgs) {
        var s = _hostOp(op, byteArgs);
        var arr = JSON.parse(s);
        return [_b64UrlDecodeToBytes(arr[0]), _b64UrlDecodeToBytes(arr[1])];
    }

    // --- key shape helper -----------------------------------------
    function _makeKey(algorithm, raw, type, extractable, usages) {
        var k = Object.create(null);
        Object.defineProperty(k, 'algorithm', { value: algorithm, enumerable: true });
        Object.defineProperty(k, 'type', { value: type, enumerable: true });
        Object.defineProperty(k, 'extractable', { value: !!extractable, enumerable: true });
        Object.defineProperty(k, 'usages', { value: usages.slice(), enumerable: true });
        Object.defineProperty(k, '_raw', { value: raw, enumerable: false });
        return k;
    }

    // ============================================================
    // Augment generateKey
    // ============================================================
    var _origGenerateKey = subtle.generateKey.bind(subtle);
    subtle.generateKey = function(algorithm, extractable, usages) {
        return new Promise(function(resolve, reject) {
            try {
                var name = _algoName(algorithm);
                if (name === 'aes-kw') {
                    var len = (algorithm.length | 0) || 256;
                    var raw = new Uint8Array(len / 8);
                    globalThis.crypto.getRandomValues(raw);
                    resolve(_makeKey(
                        { name: 'AES-KW', length: len },
                        raw, 'secret', extractable, usages));
                    return;
                }
                if (name === 'rsa-oaep' || name === 'rsassa-pkcs1-v1_5'
                    || name === 'rsa-pss') {
                    var bits = (algorithm.modulusLength | 0) || 2048;
                    var pubExp = algorithm.publicExponent
                        ? Number(BigInt('0x' + Array.from(_toBytes(algorithm.publicExponent))
                            .map(function(b) { return ('0' + b.toString(16)).slice(-2); }).join('')))
                        : 65537;
                    var pair = _hostOpPair('rsa:keygen', [
                        new TextEncoder().encode(String(bits)),
                        new TextEncoder().encode(String(pubExp)),
                    ]);
                    var hash = _hashCanonical(algorithm.hash);
                    var algoOut = {
                        name: name === 'rsa-oaep' ? 'RSA-OAEP'
                            : name === 'rsa-pss' ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',
                        modulusLength: bits,
                        publicExponent: _toBytes(algorithm.publicExponent || new Uint8Array([1, 0, 1])),
                        hash: { name: hash },
                    };
                    var privKey = _makeKey(algoOut, pair[0], 'private', extractable, usages);
                    var pubKey  = _makeKey(algoOut, pair[1], 'public', extractable,
                        // public key gets only verify/encrypt/wrapKey usages
                        usages.filter(function(u) {
                            return u === 'verify' || u === 'encrypt' || u === 'wrapKey';
                        }));
                    resolve({ privateKey: privKey, publicKey: pubKey });
                    return;
                }
                if (name === 'ecdsa' || name === 'ecdh') {
                    var curve = _curveCanonical(algorithm.namedCurve);
                    var ecPair = _hostOpPair('ec:keygen', [new TextEncoder().encode(curve)]);
                    var ecAlgo = {
                        name: name === 'ecdsa' ? 'ECDSA' : 'ECDH',
                        namedCurve: curve,
                    };
                    var priv = _makeKey(ecAlgo, ecPair[0], 'private', extractable, usages);
                    var pub  = _makeKey(ecAlgo, ecPair[1], 'public', extractable,
                        usages.filter(function(u) {
                            return u === 'verify' || u === 'deriveBits' || u === 'deriveKey';
                        }));
                    resolve({ privateKey: priv, publicKey: pub });
                    return;
                }
                if (name === 'ed25519') {
                    var edPair = _hostOpPair('ed25519:keygen', []);
                    var edAlgo = { name: 'Ed25519' };
                    var edPriv = _makeKey(edAlgo, edPair[0], 'private', extractable, usages);
                    var edPub  = _makeKey(edAlgo, edPair[1], 'public', extractable,
                        usages.filter(function(u) { return u === 'verify'; }));
                    resolve({ privateKey: edPriv, publicKey: edPub });
                    return;
                }
                if (name === 'x25519') {
                    var xPair = _hostOpPair('x25519:keygen', []);
                    var xAlgo = { name: 'X25519' };
                    var xPriv = _makeKey(xAlgo, xPair[0], 'private', extractable, usages);
                    var xPub  = _makeKey(xAlgo, xPair[1], 'public', extractable, []);
                    resolve({ privateKey: xPriv, publicKey: xPub });
                    return;
                }
                // Fall through to the base dispatcher.
                _origGenerateKey(algorithm, extractable, usages).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    // ============================================================
    // Augment encrypt / decrypt (AES-CTR + RSA-OAEP)
    // ============================================================
    var _origEncrypt = subtle.encrypt.bind(subtle);
    subtle.encrypt = function(algorithm, key, data) {
        return new Promise(function(resolve, reject) {
            try {
                var name = _algoName(algorithm);
                if (name === 'aes-ctr') {
                    var counter = _toBytes(algorithm.counter);
                    var ct = _hostOpBytes('aes-ctr:apply',
                        [_toBytes(key._raw), counter, _toBytes(data)]);
                    resolve(ct.buffer);
                    return;
                }
                if (name === 'rsa-oaep') {
                    var hash = _hashCanonical(key.algorithm && key.algorithm.hash);
                    var label = algorithm.label ? _toBytes(algorithm.label) : new Uint8Array(0);
                    var ct2 = _hostOpBytes('rsa-oaep:encrypt', [
                        new TextEncoder().encode(hash),
                        _toBytes(key._raw),
                        label,
                        _toBytes(data),
                    ]);
                    resolve(ct2.buffer);
                    return;
                }
                _origEncrypt(algorithm, key, data).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    var _origDecrypt = subtle.decrypt.bind(subtle);
    subtle.decrypt = function(algorithm, key, data) {
        return new Promise(function(resolve, reject) {
            try {
                var name = _algoName(algorithm);
                if (name === 'aes-ctr') {
                    var counter = _toBytes(algorithm.counter);
                    var pt = _hostOpBytes('aes-ctr:apply',
                        [_toBytes(key._raw), counter, _toBytes(data)]);
                    resolve(pt.buffer);
                    return;
                }
                if (name === 'rsa-oaep') {
                    var hash = _hashCanonical(key.algorithm && key.algorithm.hash);
                    var label = algorithm.label ? _toBytes(algorithm.label) : new Uint8Array(0);
                    var pt2 = _hostOpBytes('rsa-oaep:decrypt', [
                        new TextEncoder().encode(hash),
                        _toBytes(key._raw),
                        label,
                        _toBytes(data),
                    ]);
                    resolve(pt2.buffer);
                    return;
                }
                _origDecrypt(algorithm, key, data).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    // ============================================================
    // Augment sign / verify
    // ============================================================
    var _origSign = subtle.sign.bind(subtle);
    subtle.sign = function(algorithm, key, data) {
        return new Promise(function(resolve, reject) {
            try {
                var name = _algoName(algorithm);
                if (name === 'rsassa-pkcs1-v1_5' || name === 'rsa-pkcs1' || name === 'rsa-pkcs1-v1_5') {
                    var hash = _hashCanonical(key.algorithm && key.algorithm.hash);
                    var sig = _hostOpBytes('rsa-pkcs1:sign', [
                        new TextEncoder().encode(hash),
                        _toBytes(key._raw),
                        _toBytes(data),
                    ]);
                    resolve(sig.buffer);
                    return;
                }
                if (name === 'rsa-pss') {
                    var hash2 = _hashCanonical(key.algorithm && key.algorithm.hash);
                    var saltLen = (algorithm.saltLength | 0) || 32;
                    var sig2 = _hostOpBytes('rsa-pss:sign', [
                        new TextEncoder().encode(hash2),
                        new TextEncoder().encode(String(saltLen)),
                        _toBytes(key._raw),
                        _toBytes(data),
                    ]);
                    resolve(sig2.buffer);
                    return;
                }
                if (name === 'ecdsa') {
                    var curve = _curveCanonical(key.algorithm && key.algorithm.namedCurve);
                    var hashEc = _hashCanonical(algorithm.hash) || _hashFromCurve(curve);
                    var sig3 = _hostOpBytes('ecdsa:sign', [
                        new TextEncoder().encode(curve),
                        new TextEncoder().encode(hashEc),
                        _toBytes(key._raw),
                        _toBytes(data),
                    ]);
                    resolve(sig3.buffer);
                    return;
                }
                if (name === 'ed25519') {
                    var sig4 = _hostOpBytes('ed25519:sign', [_toBytes(key._raw), _toBytes(data)]);
                    resolve(sig4.buffer);
                    return;
                }
                _origSign(algorithm, key, data).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    var _origVerify = subtle.verify.bind(subtle);
    subtle.verify = function(algorithm, key, signature, data) {
        return new Promise(function(resolve, reject) {
            try {
                var name = _algoName(algorithm);
                if (name === 'rsassa-pkcs1-v1_5' || name === 'rsa-pkcs1' || name === 'rsa-pkcs1-v1_5') {
                    var hash = _hashCanonical(key.algorithm && key.algorithm.hash);
                    var ok = _hostOp('rsa-pkcs1:verify', [
                        new TextEncoder().encode(hash),
                        _toBytes(key._raw),
                        _toBytes(data),
                        _toBytes(signature),
                    ]);
                    resolve(ok === '1');
                    return;
                }
                if (name === 'rsa-pss') {
                    var hash2 = _hashCanonical(key.algorithm && key.algorithm.hash);
                    var saltLen = (algorithm.saltLength | 0) || 32;
                    var ok2 = _hostOp('rsa-pss:verify', [
                        new TextEncoder().encode(hash2),
                        new TextEncoder().encode(String(saltLen)),
                        _toBytes(key._raw),
                        _toBytes(data),
                        _toBytes(signature),
                    ]);
                    resolve(ok2 === '1');
                    return;
                }
                if (name === 'ecdsa') {
                    var curve = _curveCanonical(key.algorithm && key.algorithm.namedCurve);
                    var hashEc = _hashCanonical(algorithm.hash) || _hashFromCurve(curve);
                    var ok3 = _hostOp('ecdsa:verify', [
                        new TextEncoder().encode(curve),
                        new TextEncoder().encode(hashEc),
                        _toBytes(key._raw),
                        _toBytes(data),
                        _toBytes(signature),
                    ]);
                    resolve(ok3 === '1');
                    return;
                }
                if (name === 'ed25519') {
                    var ok4 = _hostOp('ed25519:verify',
                        [_toBytes(key._raw), _toBytes(data), _toBytes(signature)]);
                    resolve(ok4 === '1');
                    return;
                }
                _origVerify(algorithm, key, signature, data).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    // ============================================================
    // Augment deriveBits (ECDH + X25519)
    // ============================================================
    var _origDeriveBits = subtle.deriveBits.bind(subtle);
    subtle.deriveBits = function(algorithm, baseKey, length) {
        return new Promise(function(resolve, reject) {
            try {
                var name = _algoName(algorithm);
                if (name === 'ecdh') {
                    var curve = _curveCanonical(baseKey.algorithm && baseKey.algorithm.namedCurve);
                    var pubKey = algorithm['public'] || algorithm.public;
                    if (!pubKey || !pubKey._raw) {
                        return reject(new Error('ECDH: public key required'));
                    }
                    var shared = _hostOpBytes('ecdh:derive', [
                        new TextEncoder().encode(curve),
                        _toBytes(baseKey._raw),
                        _toBytes(pubKey._raw),
                    ]);
                    var n = (length || 0) > 0 ? length / 8 : shared.length;
                    resolve(shared.slice(0, n).buffer);
                    return;
                }
                if (name === 'x25519') {
                    var pubKey2 = algorithm['public'] || algorithm.public;
                    if (!pubKey2 || !pubKey2._raw) {
                        return reject(new Error('X25519: public key required'));
                    }
                    var shared2 = _hostOpBytes('x25519:derive',
                        [_toBytes(baseKey._raw), _toBytes(pubKey2._raw)]);
                    var n2 = (length || 0) > 0 ? length / 8 : shared2.length;
                    resolve(shared2.slice(0, n2).buffer);
                    return;
                }
                _origDeriveBits(algorithm, baseKey, length).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    // ============================================================
    // Augment importKey / exportKey for asymmetric key formats
    // ============================================================
    var _origImportKey = subtle.importKey.bind(subtle);
    subtle.importKey = function(format, keyData, algorithm, extractable, usages) {
        return new Promise(function(resolve, reject) {
            try {
                var name = _algoName(algorithm);
                if ((format === 'pkcs8' || format === 'spki') &&
                    (name === 'rsa-oaep' || name === 'rsa-pss'
                     || name === 'rsassa-pkcs1-v1_5' || name === 'ecdsa' || name === 'ecdh'
                     || name === 'ed25519' || name === 'x25519')) {
                    var raw = _toBytes(keyData);
                    var algo = { name: name.toUpperCase() === 'RSASSA-PKCS1-V1_5' ? 'RSASSA-PKCS1-v1_5'
                                       : (name === 'rsa-oaep' ? 'RSA-OAEP'
                                          : name === 'rsa-pss' ? 'RSA-PSS'
                                          : name.toUpperCase()) };
                    if (algorithm.namedCurve) algo.namedCurve = _curveCanonical(algorithm.namedCurve);
                    if (algorithm.hash) algo.hash = { name: _hashCanonical(algorithm.hash) };
                    resolve(_makeKey(algo, raw,
                        format === 'pkcs8' ? 'private' : 'public',
                        extractable, usages));
                    return;
                }
                if (format === 'raw' && (name === 'ed25519' || name === 'x25519')) {
                    var raw2 = _toBytes(keyData);
                    if (raw2.length !== 32) {
                        return reject(new Error(name + ': raw key must be 32 bytes'));
                    }
                    resolve(_makeKey({ name: name.toUpperCase() }, raw2, 'public', extractable, usages));
                    return;
                }
                _origImportKey(format, keyData, algorithm, extractable, usages).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    var _origExportKey = subtle.exportKey.bind(subtle);
    subtle.exportKey = function(format, key) {
        return new Promise(function(resolve, reject) {
            try {
                if (!key.extractable) {
                    return reject(new Error('SubtleCrypto.exportKey: key not extractable'));
                }
                var algoName = (key.algorithm && key.algorithm.name) || '';
                var lower = String(algoName).toLowerCase();
                // pkcs8 / spki — return raw DER bytes from `_raw`.
                if ((format === 'pkcs8' && key.type === 'private') ||
                    (format === 'spki'  && key.type === 'public')) {
                    if (lower.indexOf('rsa') === 0 || lower === 'ecdsa' || lower === 'ecdh'
                        || lower === 'ed25519' || lower === 'x25519') {
                        resolve(new Uint8Array(_toBytes(key._raw)).buffer);
                        return;
                    }
                }
                // raw — for Ed25519/X25519 keys it's the 32-byte body.
                if (format === 'raw' && (lower === 'ed25519' || lower === 'x25519')) {
                    resolve(new Uint8Array(_toBytes(key._raw)).buffer);
                    return;
                }
                // jwk — RSA via host helper.
                if (format === 'jwk' && lower.indexOf('rsa') === 0) {
                    var verb = key.type === 'private'
                        ? 'rsa:export-jwk-priv'
                        : 'rsa:export-jwk-pub';
                    var jsonBytes = _hostOpBytes(verb, [_toBytes(key._raw)]);
                    var jwk = JSON.parse(new TextDecoder().decode(jsonBytes));
                    jwk.alg = (lower === 'rsa-oaep')
                        ? ('RSA-OAEP-' + (_hashCanonical(key.algorithm.hash).slice(4) || '256'))
                        : (lower === 'rsa-pss')
                            ? ('PS' + (_hashCanonical(key.algorithm.hash).slice(4) || '256'))
                            : ('RS' + (_hashCanonical(key.algorithm.hash).slice(4) || '256'));
                    jwk.ext = true;
                    jwk.key_ops = key.usages.slice();
                    resolve(jwk);
                    return;
                }
                _origExportKey(format, key).then(resolve, reject);
            } catch (e) { reject(e); }
        });
    };

    // ============================================================
    // wrapKey / unwrapKey: AES-KW path
    // ============================================================
    var _origWrap = subtle.wrapKey.bind(subtle);
    subtle.wrapKey = function(format, key, wrappingKey, wrapAlgorithm) {
        var wname = _algoName(wrapAlgorithm);
        if (wname === 'aes-kw') {
            return subtle.exportKey(format, key).then(function(rawBuf) {
                var raw = _toBytes(rawBuf);
                var wrapped = _hostOpBytes('aes-kw:wrap',
                    [_toBytes(wrappingKey._raw), raw]);
                return wrapped.buffer;
            });
        }
        return _origWrap(format, key, wrappingKey, wrapAlgorithm);
    };

    var _origUnwrap = subtle.unwrapKey.bind(subtle);
    subtle.unwrapKey = function(format, wrapped, unwrappingKey, unwrapAlgorithm,
                                 unwrappedKeyAlgorithm, extractable, usages) {
        var wname = _algoName(unwrapAlgorithm);
        if (wname === 'aes-kw') {
            var unwrapped = _hostOpBytes('aes-kw:unwrap',
                [_toBytes(unwrappingKey._raw), _toBytes(wrapped)]);
            return subtle.importKey(format, unwrapped.buffer, unwrappedKeyAlgorithm,
                                    extractable, usages);
        }
        return _origUnwrap(format, wrapped, unwrappingKey, unwrapAlgorithm,
                           unwrappedKeyAlgorithm, extractable, usages);
    };
})();

// ---- webassembly.js ----
// `WebAssembly.*` — Node 20 / browser-spec API on top of burn's
// host-side wasmtime sub-runner.
//
// Burn already runs inside wasmtime (the QuickJS plugin); the host
// gives us a parallel wasmtime instance to load **additional**
// WebAssembly modules at runtime. With this in place, every WASM-
// shipped npm package (sql.js, @jsquash/*, libheif-js, etc.) becomes
// loadable through the standard `WebAssembly.compile` /
// `WebAssembly.instantiate` calls — no per-package shadow code.
//
// Coverage (matches the Node + browser spec where it matters):
//
//   WebAssembly.compile(bufferSource)              -> Promise<Module>
//   WebAssembly.instantiate(bufferSource, imports) -> Promise<{module, instance}>
//   WebAssembly.instantiate(module, imports)       -> Promise<Instance>
//   WebAssembly.validate(bufferSource)             -> boolean
//   WebAssembly.Module(bytes)                      // sync
//   WebAssembly.Module.exports(module)             // [{name, kind, ...}]
//   WebAssembly.Module.imports(module)             // [{module, name, kind}]
//   WebAssembly.Instance(module, imports)          // sync
//   WebAssembly.Memory({initial, maximum?, shared?})  // backed when an
//      instance imports/exports a memory; standalone Memory creation
//      surfaces a clear "not supported" error in v1.
//   WebAssembly.{Compile,Link,Runtime}Error
//
// Out of scope for v1 (each will throw with a clear message):
//   * User-defined function imports — modules importing arbitrary
//     `env.*` callbacks won't instantiate yet. The error names the
//     missing import so callers can identify what's needed.
//   * `compileStreaming` / `instantiateStreaming` — no Response in
//     burn (no DOM); fetch the bytes manually first.
//   * Standalone `new WebAssembly.Memory(...)` / `Table` / `Global`.
//   * `Module.customSections(module, name)`.

(function installWebAssembly() {
    var Buffer = require('buffer').Buffer;

    function isHostErr(s) {
        return typeof s === 'string' && s.indexOf('__HOST_ERR__:') === 0;
    }

    function ensureHost(name) {
        var fn = globalThis[name];
        if (typeof fn !== 'function') {
            throw new Error('WebAssembly host import unavailable: ' + name);
        }
        return fn;
    }

    /// Coerce a JS value to bytes: ArrayBuffer / Uint8Array / Buffer.
    function bufferSourceToBytes(src) {
        if (Buffer.isBuffer(src)) return src;
        if (src instanceof Uint8Array) return Buffer.from(src);
        if (src && src.byteLength !== undefined && src instanceof ArrayBuffer) {
            return Buffer.from(new Uint8Array(src));
        }
        if (src && src.buffer instanceof ArrayBuffer && typeof src.byteLength === 'number') {
            // TypedArray view (Int32Array, etc.).
            return Buffer.from(new Uint8Array(src.buffer, src.byteOffset, src.byteLength));
        }
        throw new TypeError(
            'WebAssembly: argument must be a BufferSource (ArrayBuffer, Uint8Array, Buffer)'
        );
    }

    // ---- typed errors (matches the spec) ---------------------------

    function CompileError(message) {
        var e = new Error(message);
        e.name = 'CompileError';
        return e;
    }
    function LinkError(message) {
        var e = new Error(message);
        e.name = 'LinkError';
        return e;
    }
    function RuntimeError(message) {
        var e = new Error(message);
        e.name = 'RuntimeError';
        return e;
    }

    // ---- Module ----------------------------------------------------

    function Module(bytesSource) {
        if (!(this instanceof Module)) return new Module(bytesSource);
        var bytes = bufferSourceToBytes(bytesSource);
        var fn = ensureHost('__host_wasm_compile');
        var id = fn(bytes.toString('base64'));
        if (id < 0) {
            var detail = (typeof globalThis.__host_last_error === 'function')
                ? globalThis.__host_last_error()
                : 'compile failed';
            throw CompileError('WebAssembly.Module: ' + detail);
        }
        this._id = id;
    }

    /// Spec-static: WebAssembly.Module.exports(module) →
    /// [{name, kind}, ...] where `kind` is one of 'function', 'table',
    /// 'memory', 'global'.
    Module.exports = function(mod) {
        var fn = ensureHost('__host_wasm_module_exports');
        var raw = fn(mod._id);
        if (isHostErr(raw)) throw new Error(raw.slice('__HOST_ERR__:'.length));
        var arr = JSON.parse(raw);
        return arr.map(function(e) { return { name: e.name, kind: e.kind }; });
    };
    Module.imports = function(mod) {
        var fn = ensureHost('__host_wasm_module_imports');
        var raw = fn(mod._id);
        if (isHostErr(raw)) throw new Error(raw.slice('__HOST_ERR__:'.length));
        var arr = JSON.parse(raw);
        return arr.map(function(e) { return { module: e.module, name: e.name, kind: e.kind }; });
    };
    Module.customSections = function() {
        // Spec: returns ArrayBuffer[]. We don't surface custom
        // sections in v1 — return an empty list rather than
        // throwing so feature-detection code (which iterates the
        // result) keeps working.
        return [];
    };

    // ---- Memory ---------------------------------------------------

    /// `WebAssembly.Memory` is normally a free-standing class users
    /// can construct (`new WebAssembly.Memory({initial: 1})`). v1
    /// supports it only as a *view* over an instance's exported
    /// memory — that's the shape every npm package actually uses.
    /// Constructing a standalone Memory throws a clear error.
    function Memory(descriptor) {
        // Internal-construction marker. Instance-export wrap-ups
        // pass `{ _instanceId }`; user-facing `new Memory(...)` passes
        // `{ initial, maximum, shared }` per the WebAssembly spec.
        if (descriptor && descriptor._instanceId !== undefined) {
            this._instanceId = descriptor._instanceId;
            this._standaloneId = 0;
            return;
        }
        if (!descriptor || typeof descriptor.initial !== 'number') {
            throw new TypeError(
                'WebAssembly.Memory: descriptor.initial must be a number'
            );
        }
        var fn = ensureHost('__host_wasm_mem_new');
        var max = typeof descriptor.maximum === 'number' ? descriptor.maximum : -1;
        var id = fn(descriptor.initial | 0, max);
        if (id < 0) {
            throw new RangeError('WebAssembly.Memory: alloc failed');
        }
        this._instanceId = 0;
        this._standaloneId = id;
    }

    Object.defineProperty(Memory.prototype, 'buffer', {
        get: function() {
            var size, b64;
            if (this._standaloneId) {
                var sizeFn = ensureHost('__host_wasm_mem_size');
                size = sizeFn(this._standaloneId) | 0;
                if (size < 0) throw new Error('WebAssembly.Memory: invalid');
                var readFn = ensureHost('__host_wasm_mem_read');
                b64 = readFn(this._standaloneId, 0, size);
            } else {
                var sizeFn2 = ensureHost('__host_wasm_memory_size');
                size = sizeFn2(this._instanceId) | 0;
                if (size < 0) {
                    throw new Error('WebAssembly.Memory: instance closed or no memory');
                }
                var readFn2 = ensureHost('__host_wasm_memory_read');
                b64 = readFn2(this._instanceId, 0, size);
            }
            if (isHostErr(b64)) throw new Error(b64.slice('__HOST_ERR__:'.length));
            return Buffer.from(b64, 'base64').buffer;
        },
    });

    Memory.prototype.read = function(offset, len) {
        var fn = this._standaloneId
            ? ensureHost('__host_wasm_mem_read')
            : ensureHost('__host_wasm_memory_read');
        var id = this._standaloneId || this._instanceId;
        var b64 = fn(id, offset | 0, len | 0);
        if (isHostErr(b64)) throw new Error(b64.slice('__HOST_ERR__:'.length));
        return Buffer.from(b64, 'base64');
    };

    Memory.prototype.write = function(offset, data) {
        var bytes;
        if (Buffer.isBuffer(data)) bytes = data;
        else if (data instanceof Uint8Array) bytes = Buffer.from(data);
        else if (data instanceof ArrayBuffer) bytes = Buffer.from(new Uint8Array(data));
        else throw new TypeError('WebAssembly.Memory.write: data must be Buffer/Uint8Array/ArrayBuffer');
        var fn = this._standaloneId
            ? ensureHost('__host_wasm_mem_write')
            : ensureHost('__host_wasm_memory_write');
        var id = this._standaloneId || this._instanceId;
        var rc = fn(id, offset | 0, bytes.toString('base64'));
        if (rc < 0) {
            var detail = (typeof globalThis.__host_last_error === 'function')
                ? globalThis.__host_last_error()
                : 'memory write failed';
            throw new Error('WebAssembly.Memory.write: ' + detail);
        }
        return bytes.length;
    };

    Memory.prototype.grow = function(deltaPages) {
        var fn = this._standaloneId
            ? ensureHost('__host_wasm_mem_grow')
            : ensureHost('__host_wasm_memory_grow');
        var id = this._standaloneId || this._instanceId;
        var prev = fn(id, deltaPages | 0);
        if (prev < 0) {
            throw new RangeError('WebAssembly.Memory.grow: maximum exceeded');
        }
        return prev;
    };

    // ---- Instance -------------------------------------------------

    function Instance(mod, importsObject) {
        if (!(this instanceof Instance)) return new Instance(mod, importsObject);
        var instFn = ensureHost('__host_wasm_instantiate');
        var iid = instFn(mod._id);
        if (iid < 0) {
            var detail = (typeof globalThis.__host_last_error === 'function')
                ? globalThis.__host_last_error()
                : 'instantiate failed';
            throw LinkError('WebAssembly.Instance: ' + detail);
        }
        this._id = iid;
        this._module = mod;
        this.exports = buildExportsProxy(iid, mod);
        // `importsObject` is accepted but ignored in v1 — burn's
        // loader doesn't bridge JS callbacks back into wasmtime yet.
        // Modules that need imports fail at the host-side
        // instantiate step above.
        var _ = importsObject;
    }

    function buildExportsProxy(instanceId, mod) {
        var exportsList = Module.exports(mod);
        var out = {};
        // Track exported memory so memory.read/write/buffer work.
        var memoryExportName = null;
        var rawExports = JSON.parse(
            ensureHost('__host_wasm_module_exports')(mod._id)
        );
        for (var i = 0; i < rawExports.length; i++) {
            var exp = rawExports[i];
            (function bind(exp) {
                if (exp.kind === 'function') {
                    out[exp.name] = function() {
                        var args = Array.prototype.slice.call(arguments);
                        var encoded = args.map(encodeArg);
                        var callFn = ensureHost('__host_wasm_call_export');
                        var raw = callFn(
                            instanceId, exp.name, JSON.stringify(encoded)
                        );
                        if (isHostErr(raw)) {
                            throw RuntimeError(raw.slice('__HOST_ERR__:'.length));
                        }
                        var results = JSON.parse(raw);
                        if (results.length === 0) return undefined;
                        if (results.length === 1) return decodeResult(results[0]);
                        return results.map(decodeResult);
                    };
                } else if (exp.kind === 'memory') {
                    if (memoryExportName === null) memoryExportName = exp.name;
                    out[exp.name] = new Memory({ _instanceId: instanceId });
                } else if (exp.kind === 'table') {
                    var tName = exp.name;
                    out[tName] = {
                        _kind: 'table',
                        _instanceId: instanceId,
                        _name: tName,
                        get length() {
                            var fn = ensureHost('__host_wasm_table_size');
                            return fn(instanceId, tName) | 0;
                        },
                        get: function(idx) {
                            var fn = ensureHost('__host_wasm_table_get');
                            var raw = fn(instanceId, tName, idx | 0);
                            if (isHostErr(raw)) {
                                throw new RangeError(raw.slice('__HOST_ERR__:'.length));
                            }
                            var v = JSON.parse(raw);
                            // Spec: returns the referenced value, or
                            // null for empty slots. Burn doesn't yet
                            // expose Func/Extern object identities;
                            // we surface null for nullable slots and
                            // a sentinel object for non-null.
                            if (v.null) return null;
                            return { _kind: v.kind, _slot: idx | 0 };
                        },
                        set: function() {
                            // Storing arbitrary Refs into a table
                            // requires the engine to know the value
                            // (e.g. a JS-imported function). Burn's
                            // wasmtime store doesn't yet bridge that.
                            throw new TypeError(
                                'WebAssembly.Table.set: storing JS callbacks into a wasm Table '
                                + 'requires JS→wasm callbacks; burn imports are export-only'
                            );
                        },
                        grow: function(delta, initValue) {
                            var fn = ensureHost('__host_wasm_table_grow');
                            var prev = fn(instanceId, tName, delta | 0);
                            if (prev < 0) {
                                throw new RangeError('WebAssembly.Table.grow: maximum exceeded');
                            }
                            // initValue ignored — engine fills with null.
                            var _ = initValue;
                            return prev;
                        },
                    };
                } else if (exp.kind === 'global') {
                    var gName = exp.name;
                    out[gName] = Object.defineProperty({
                        _kind: 'global',
                        _instanceId: instanceId,
                        _name: gName,
                    }, 'value', {
                        get: function() {
                            var fn = ensureHost('__host_wasm_global_get');
                            var raw = fn(instanceId, gName);
                            if (isHostErr(raw)) {
                                throw new Error(raw.slice('__HOST_ERR__:'.length));
                            }
                            var v = JSON.parse(raw);
                            if (v.type === 'i64') {
                                // BigInt — match spec semantics.
                                return BigInt(v.value);
                            }
                            return v.value;
                        },
                        set: function(newVal) {
                            // Need to round-trip with a typed value
                            // object. Burn defaults the param type
                            // based on the JS value's shape: BigInt
                            // → i64, Number with .0 fraction → f64,
                            // integer → i32.
                            var ty;
                            var v;
                            if (typeof newVal === 'bigint') {
                                ty = 'i64';
                                v = newVal.toString();
                            } else if (typeof newVal === 'number') {
                                if (Math.floor(newVal) === newVal && Math.abs(newVal) < 2**31) {
                                    ty = 'i32';
                                    v = newVal;
                                } else {
                                    ty = 'f64';
                                    v = newVal;
                                }
                            } else {
                                throw new TypeError(
                                    'WebAssembly.Global.value: expected number or bigint'
                                );
                            }
                            var fn = ensureHost('__host_wasm_global_set');
                            var rc = fn(instanceId, gName, JSON.stringify({type: ty, value: v}));
                            if (rc < 0) {
                                throw new Error(
                                    (typeof globalThis.__host_last_error === 'function'
                                        ? globalThis.__host_last_error()
                                        : 'global set failed')
                                );
                            }
                        },
                        enumerable: true,
                    });
                }
            })(exp);
        }
        var _ = exportsList;
        var __ = memoryExportName;
        return out;
    }

    /// Convert a JS arg to the bridge's tagged-union shape.
    /// Defaults to i32 for finite integers, f64 for non-integers,
    /// i64 (string) for BigInt.
    function encodeArg(v) {
        if (typeof v === 'number') {
            if (Number.isInteger(v) && v >= -2147483648 && v <= 2147483647) {
                return { type: 'i32', value: v | 0 };
            }
            return { type: 'f64', value: v };
        }
        if (typeof v === 'bigint') {
            return { type: 'i64', value: v.toString() };
        }
        if (typeof v === 'boolean') {
            return { type: 'i32', value: v ? 1 : 0 };
        }
        throw new TypeError('WebAssembly: unsupported argument type ' + typeof v);
    }

    /// Convert the bridge's tagged result back to a JS value.
    /// i64 returns a BigInt to preserve precision for values > 2^53.
    function decodeResult(r) {
        switch (r.type) {
            case 'i32': return r.value;
            case 'f32': return r.value;
            case 'f64': return r.value;
            case 'i64': return BigInt(r.value);
            default: return r.value;
        }
    }

    // ---- module-level static API ----------------------------------

    function compile(bufferSource) {
        return new Promise(function(resolve, reject) {
            try { resolve(new Module(bufferSource)); }
            catch (e) { reject(e); }
        });
    }

    function instantiate(bufferSourceOrModule, imports) {
        return new Promise(function(resolve, reject) {
            try {
                if (bufferSourceOrModule instanceof Module) {
                    resolve(new Instance(bufferSourceOrModule, imports));
                } else {
                    var mod = new Module(bufferSourceOrModule);
                    var inst = new Instance(mod, imports);
                    resolve({ module: mod, instance: inst });
                }
            } catch (e) {
                reject(e);
            }
        });
    }

    function validate(bufferSource) {
        try {
            new Module(bufferSource);
            return true;
        } catch (_) {
            return false;
        }
    }

    /// `compileStreaming(source)` — `source` is a `Response` (from
    /// fetch) or a Promise<Response>. Spec: pull the response body
    /// as bytes, then run `compile`. Burn implements it as the
    /// straight composition since our `Response.arrayBuffer()` already
    /// buffers the body — there's no real streaming-compile in
    /// wasmtime's JS surface to forward to.
    function compileStreaming(source) {
        return Promise.resolve(source).then(function(response) {
            if (!response || typeof response.arrayBuffer !== 'function') {
                throw new TypeError(
                    'WebAssembly.compileStreaming: argument must be a Response'
                );
            }
            return response.arrayBuffer();
        }).then(function(buffer) {
            return compile(buffer);
        });
    }
    function instantiateStreaming(source, importsObject) {
        return Promise.resolve(source).then(function(response) {
            if (!response || typeof response.arrayBuffer !== 'function') {
                throw new TypeError(
                    'WebAssembly.instantiateStreaming: argument must be a Response'
                );
            }
            return response.arrayBuffer();
        }).then(function(buffer) {
            return instantiate(buffer, importsObject);
        });
    }

    var WebAssembly = {
        compile: compile,
        instantiate: instantiate,
        validate: validate,
        compileStreaming: compileStreaming,
        instantiateStreaming: instantiateStreaming,
        Module: Module,
        Instance: Instance,
        Memory: Memory,
        Table: function TableCtor(descriptor) {
            if (!(this instanceof TableCtor)) {
                throw new TypeError('WebAssembly.Table: must be called with new');
            }
            if (!descriptor || typeof descriptor.initial !== 'number') {
                throw new TypeError('WebAssembly.Table: descriptor.initial required');
            }
            var elem = descriptor.element || 'anyfunc';
            var max = typeof descriptor.maximum === 'number' ? descriptor.maximum : -1;
            var id = ensureHost('__host_wasm_table_new')(elem, descriptor.initial | 0, max);
            if (id < 0) {
                throw new RangeError('WebAssembly.Table: alloc failed');
            }
            this._standaloneId = id;
            this._elemType = elem;
            var self = this;
            Object.defineProperty(this, 'length', {
                get: function() {
                    return ensureHost('__host_wasm_table_size_sa')(self._standaloneId) | 0;
                },
            });
            this.get = function(_idx) {
                // Spec returns the slot value. We expose null for the
                // common funcref/externref-with-null case; full
                // bridging of JS-imported function refs requires a
                // JS→wasm callback path beyond the standalone Table
                // surface.
                return null;
            };
            this.set = function() {
                throw new TypeError(
                    'WebAssembly.Table.set: assigning JS callbacks into a wasm Table '
                    + 'requires JS→wasm import bridging; burn standalone tables are slot-only'
                );
            };
            this.grow = function(delta, _initValue) {
                var prev = ensureHost('__host_wasm_table_grow_sa')(self._standaloneId, delta | 0);
                if (prev < 0) {
                    throw new RangeError('WebAssembly.Table.grow: maximum exceeded');
                }
                return prev;
            };
        },
        Global: function GlobalCtor(descriptor, initialValue) {
            if (!(this instanceof GlobalCtor)) {
                throw new TypeError('WebAssembly.Global: must be called with new');
            }
            if (!descriptor || typeof descriptor.value !== 'string') {
                throw new TypeError('WebAssembly.Global: descriptor.value required');
            }
            var ty = descriptor.value;
            var mutable = !!descriptor.mutable;
            // Encode initial as a typed value JSON the host parses.
            var v;
            if (ty === 'i64') {
                var bn = (typeof initialValue === 'bigint') ? initialValue : BigInt(initialValue || 0);
                v = { type: 'i64', value: bn.toString() };
            } else if (ty === 'i32') {
                v = { type: 'i32', value: (initialValue | 0) };
            } else if (ty === 'f32' || ty === 'f64') {
                v = { type: ty, value: Number(initialValue || 0) };
            } else {
                throw new TypeError('WebAssembly.Global: unknown value type ' + ty);
            }
            var id = ensureHost('__host_wasm_global_new')(ty, mutable ? 1 : 0, JSON.stringify(v));
            if (id < 0) {
                throw new Error('WebAssembly.Global: alloc failed');
            }
            this._standaloneId = id;
            this._type = ty;
            var self = this;
            Object.defineProperty(this, 'value', {
                get: function() {
                    var raw = ensureHost('__host_wasm_global_get_sa')(self._standaloneId);
                    if (isHostErr(raw)) throw new Error(raw.slice('__HOST_ERR__:'.length));
                    var got = JSON.parse(raw);
                    if (got.type === 'i64') return BigInt(got.value);
                    return got.value;
                },
                set: function(newVal) {
                    var nv;
                    if (self._type === 'i64') {
                        var bn = (typeof newVal === 'bigint') ? newVal : BigInt(newVal);
                        nv = { type: 'i64', value: bn.toString() };
                    } else if (self._type === 'i32') {
                        nv = { type: 'i32', value: newVal | 0 };
                    } else {
                        nv = { type: self._type, value: Number(newVal) };
                    }
                    var rc = ensureHost('__host_wasm_global_set_sa')(
                        self._standaloneId, JSON.stringify(nv));
                    if (rc < 0) {
                        throw new Error('WebAssembly.Global.value set failed');
                    }
                },
            });
            this.valueOf = function() { return this.value; };
        },
        CompileError: function(msg) { return CompileError(msg); },
        LinkError: function(msg) { return LinkError(msg); },
        RuntimeError: function(msg) { return RuntimeError(msg); },
    };

    globalThis.WebAssembly = WebAssembly;
})();

// ---- worker_threads.js ----
// worker_threads — process-per-worker polyfill (B10).
//
// Each `new Worker(path, opts)` in the parent JS spawns a child
// `burn run --internal-worker <path>` subprocess via the host import
// __host_worker_spawn. IPC is JSON over length-prefixed pipes; the
// host's daemon-event dispatcher delivers worker→parent frames here
// as `{kind:"worker-message"|"worker-online"|"worker-error"|"worker-exit"}`
// envelopes.
//
// Inside a worker child the same module surfaces a `parentPort` whose
// postMessage routes to __host_worker_post_to_parent. Parent → child
// frames arrive via daemon-event as `{kind:"worker-parent-message"}`
// or `{kind:"worker-terminate-requested"}`.
//
// **Not supported in the minimal subset:**
// - `new Worker(code, { eval: true })` — explicit error
// - MessageChannel / MessagePort standalone (only Worker / parentPort)
// - transferList / SharedArrayBuffer
// - worker.stdout / worker.stderr as readable streams (forwarded to
//   parent stderr instead — see daemon_workers.rs)
// - resourceLimits
// - argv / env / execArgv overrides

(function bootstrapWorkerThreadsGlobals() {
    if (!globalThis.__ab_worker_handlers) {
        globalThis.__ab_worker_handlers = {};
    }
    if (!globalThis.__ab_worker_parent_port_handlers) {
        globalThis.__ab_worker_parent_port_handlers = null;
    }
})();

__register_module('worker_threads', function(module, exports, require) {
    var EventEmitter = require('events').EventEmitter;

    function isMainThreadFn() {
        if (typeof globalThis.__host_worker_is_main_thread !== 'function') return true;
        return globalThis.__host_worker_is_main_thread() !== 0;
    }

    function threadIdFn() {
        if (typeof globalThis.__host_worker_thread_id !== 'function') return 0;
        return globalThis.__host_worker_thread_id() | 0;
    }

    function workerDataValue() {
        if (typeof globalThis.__host_worker_data !== 'function') return undefined;
        var s = globalThis.__host_worker_data();
        if (!s) return undefined;
        try {
            var obj = JSON.parse(s);
            return _reattachSABs(obj);
        } catch (_) { return undefined; }
    }

    /// Walk a parsed workerData tree replacing every
    /// `{__ab_sab:true, descriptor, byteLength}` marker with a fresh
    /// SharedArrayBuffer that re-attaches to the parent's region.
    /// Plain values (numbers, strings, etc.) pass through untouched.
    function _reattachSABs(value) {
        if (!value || typeof value !== 'object') return value;
        if (value.__ab_sab === true) {
            var SAB = globalThis.SharedArrayBuffer;
            return new SAB({
                __ab_sab_attach: true,
                descriptor: value.descriptor,
                byteLength: value.byteLength | 0,
            });
        }
        if (Array.isArray(value)) {
            for (var i = 0; i < value.length; i++) {
                value[i] = _reattachSABs(value[i]);
            }
            return value;
        }
        var keys = Object.keys(value);
        for (var k = 0; k < keys.length; k++) {
            value[keys[k]] = _reattachSABs(value[keys[k]]);
        }
        return value;
    }

    /// Inverse of [`_reattachSABs`]: walk a tree pre-`JSON.stringify`
    /// and replace SharedArrayBuffer instances with markers the child
    /// can reconstruct. Mutates a *clone* of the input so the user's
    /// workerData object isn't disturbed.
    function _markSABs(value, seen) {
        if (!value || typeof value !== 'object') return value;
        seen = seen || new WeakMap();
        if (seen.has(value)) return seen.get(value);
        // SharedArrayBuffer shadow detection — our shadow stores the
        // host region id on `_regionId`. A literal SAB the engine
        // produced (no descriptor) can't be shared cross-process; we
        // pass it as null so the child observes a missing entry.
        if (typeof value._regionId === 'number'
            && typeof value._descriptor === 'string') {
            return {
                __ab_sab: true,
                descriptor: value._descriptor,
                byteLength: value.byteLength | 0,
            };
        }
        if (Array.isArray(value)) {
            var arr = [];
            seen.set(value, arr);
            for (var i = 0; i < value.length; i++) arr.push(_markSABs(value[i], seen));
            return arr;
        }
        var out = {};
        seen.set(value, out);
        var keys = Object.keys(value);
        for (var k = 0; k < keys.length; k++) {
            out[keys[k]] = _markSABs(value[keys[k]], seen);
        }
        return out;
    }

    var IS_MAIN = isMainThreadFn();
    var THREAD_ID = threadIdFn();
    var WORKER_DATA = IS_MAIN ? undefined : workerDataValue();

    // ----------------------------------------------------------------
    // Worker (parent-side handle to a child process)
    // ----------------------------------------------------------------

    function Worker(scriptPath, opts) {
        if (!(this instanceof Worker)) return new Worker(scriptPath, opts);
        EventEmitter.call(this);

        opts = opts || {};
        if (opts.eval) {
            throw new Error(
                "worker_threads: `new Worker(code, { eval: true })` is not supported in burn"
            );
        }
        if (typeof scriptPath !== 'string') {
            // Node accepts a URL object. We stringify; Node's URL polyfill
            // (if loaded) will provide .toString() compatible output.
            scriptPath = String(scriptPath);
        }
        if (scriptPath.indexOf('file:') === 0) {
            // Strip a `file://` prefix produced by URL.toString() — the
            // host validator wants a regular FS path.
            scriptPath = scriptPath.replace(/^file:\/\//, '');
        }

        if (typeof globalThis.__host_worker_spawn !== 'function') {
            throw new Error(
                "worker_threads requires daemon mode; run via `burn foo.js` CLI"
            );
        }

        var dataJson = '';
        if (typeof opts.workerData !== 'undefined') {
            try {
                // Replace SharedArrayBuffer instances with markers the
                // child reconstructs via host_sab_open. Plain values
                // (and non-SAB ArrayBuffers) pass through unchanged.
                dataJson = JSON.stringify(_markSABs(opts.workerData));
            }
            catch (e) {
                throw new TypeError(
                    'workerData must be JSON-serializable: ' + e.message
                );
            }
        }

        var rc = globalThis.__host_worker_spawn(scriptPath, dataJson);
        if (rc < 0) {
            var detail = '';
            if (typeof globalThis.__host_last_error === 'function') {
                detail = globalThis.__host_last_error();
            }
            throw mapSpawnError(rc, detail);
        }

        this.threadId = rc | 0;
        this._terminated = false;
        // Register self in the dispatch table so daemon-event can route
        // 'message' / 'online' / 'error' / 'exit' to this instance.
        globalThis.__ab_worker_handlers[this.threadId] = this;
    }

    Worker.prototype = Object.create(EventEmitter.prototype);
    Worker.prototype.constructor = Worker;

    Worker.prototype.postMessage = function(value) {
        if (this._terminated) {
            // Match Node's silent drop on already-exited workers; the
            // host returns E_BAD_ID anyway.
            return;
        }
        var json;
        try { json = JSON.stringify(value); }
        catch (e) {
            throw new TypeError(
                'postMessage value must be JSON-serializable: ' + e.message
            );
        }
        var rc = globalThis.__host_worker_post_message(this.threadId, json);
        if (rc < 0) {
            var detail = '';
            if (typeof globalThis.__host_last_error === 'function') {
                detail = globalThis.__host_last_error();
            }
            throw new Error('worker.postMessage: ' + (detail || ('rc=' + rc)));
        }
    };

    Worker.prototype.terminate = function() {
        var self = this;
        if (self._terminated) return Promise.resolve(0);
        self._terminated = true;
        var rc = globalThis.__host_worker_terminate(self.threadId, 1);
        return new Promise(function(resolve) {
            // Resolve once the daemon-event pump fires `exit` for us.
            // If the worker was already gone, the exit may have been
            // emitted before terminate() was called; resolve quickly
            // in that case via a microtask.
            self.once('exit', function(code) { resolve(code | 0); });
            // Best-effort: if the host already returned an error code
            // (worker not found), cancel the wait.
            if (rc === -9) {
                self._dispatchExit(0);
            }
        });
    };

    // Internal: called by the daemon-event dispatcher when an
    // online/message/error/exit envelope arrives for this thread id.
    Worker.prototype._dispatchOnline = function() {
        try { this.emit('online'); } catch (_) {}
    };
    Worker.prototype._dispatchMessage = function(payloadJson) {
        var value;
        try { value = JSON.parse(payloadJson); } catch (_) { return; }
        try { this.emit('message', value); } catch (_) {}
    };
    Worker.prototype._dispatchError = function(message, stack) {
        var err = new Error(message || 'worker error');
        if (stack) err.stack = stack;
        try { this.emit('error', err); } catch (_) {}
    };
    Worker.prototype._dispatchExit = function(code) {
        if (this._terminated) {
            // Already removed from the table — re-entering from a
            // late exit notification.
        }
        this._terminated = true;
        try { this.emit('exit', code | 0); } catch (_) {}
        delete globalThis.__ab_worker_handlers[this.threadId];
    };

    function mapSpawnError(rc, detail) {
        var msg = detail || '';
        switch (rc) {
            case -1: return new Error(
                'worker_threads requires daemon mode; run via `burn foo.js`' +
                (msg ? (' (' + msg + ')') : '')
            );
            case -2: return new Error('worker_threads: permission denied' +
                (msg ? (': ' + msg) : ''));
            case -3: return new Error(msg ||
                'worker_threads: depth limit reached (BURN_WORKER_DEPTH)');
            case -4: return new Error(msg ||
                'worker_threads: concurrency cap reached');
            case -5: return new Error(msg ||
                'worker_threads: worker script path is outside fs allow-list');
            case -6: return new Error(msg ||
                'worker_threads: failed to spawn child process');
            case -7: return new Error(msg ||
                'worker_threads: payload exceeds frame size cap');
            case -11: return new Error(
                'worker_threads: { eval: true } is not supported in burn');
            default: return new Error('worker_threads: error rc=' + rc +
                (msg ? (': ' + msg) : ''));
        }
    }

    // ----------------------------------------------------------------
    // parentPort (child-side handle back to the parent)
    // ----------------------------------------------------------------

    function ParentPort() {
        EventEmitter.call(this);
        this._closed = false;
    }
    ParentPort.prototype = Object.create(EventEmitter.prototype);
    ParentPort.prototype.constructor = ParentPort;

    ParentPort.prototype.postMessage = function(value) {
        if (this._closed) return;
        var json;
        try { json = JSON.stringify(value); }
        catch (e) {
            throw new TypeError(
                'parentPort.postMessage value must be JSON-serializable: ' + e.message
            );
        }
        var rc = globalThis.__host_worker_post_to_parent(json);
        if (rc < 0) {
            var detail = '';
            if (typeof globalThis.__host_last_error === 'function') {
                detail = globalThis.__host_last_error();
            }
            throw new Error('parentPort.postMessage: ' + (detail || ('rc=' + rc)));
        }
    };

    ParentPort.prototype.close = function() {
        this._closed = true;
    };

    ParentPort.prototype._dispatchMessage = function(payloadJson) {
        var value;
        try { value = JSON.parse(payloadJson); } catch (_) { return; }
        try { this.emit('message', value); } catch (_) {}
    };

    ParentPort.prototype._dispatchTerminate = function() {
        try { this.emit('close'); } catch (_) {}
        this._closed = true;
    };

    var parentPort = null;
    if (!IS_MAIN) {
        parentPort = new ParentPort();
        globalThis.__ab_worker_parent_port_handlers = parentPort;

        // Fire `online` exactly once after the worker module finishes
        // its top-level evaluation. We use a microtask so any
        // `parentPort.on('message', cb)` the user installed during
        // top-level eval is registered before we signal readiness.
        Promise.resolve().then(function() {
            try { globalThis.__host_worker_post_online_to_parent(); } catch (_) {}
        });
    }

    // ----------------------------------------------------------------
    // Module exports
    // ----------------------------------------------------------------

    exports.Worker = Worker;
    exports.parentPort = parentPort;
    exports.workerData = WORKER_DATA;
    exports.isMainThread = IS_MAIN;
    exports.threadId = THREAD_ID;

    // Re-export the global MessageChannel + MessagePort. They live
    // on `globalThis` for parity with browser semantics; `node:worker_threads`
    // exposes the same constructors so library code that pulls them
    // from this module gets the live class instead of a throwing stub.
    exports.MessageChannel = globalThis.MessageChannel;
    exports.MessagePort = globalThis.MessagePort;
    var _untransferable = new WeakSet();
    exports.markAsUntransferable = function(value) {
        try { _untransferable.add(value); } catch (_) {}
    };
    exports.isMarkedAsUntransferable = function(value) {
        try { return _untransferable.has(value); } catch (_) { return false; }
    };
    /// Single-context runtime — there is one realm per shard, so
    /// "moving" a port between contexts is the identity operation.
    /// Keeping the same MessagePort handle is spec-equivalent to a
    /// successful move in a multi-realm engine.
    exports.moveMessagePortToContext = function(port, _ctx) {
        return port;
    };
    exports.receiveMessageOnPort = function() {
        return undefined;
    };
    exports.SHARE_ENV = Symbol('SHARE_ENV');

    // ---- Environment-data slot (Node 14.5+) -----------------
    //
    // `setEnvironmentData(key, value)` / `getEnvironmentData(key)`
    // exchanges plain values across the parent → spawned-worker
    // boundary. We keep a single in-process map; spawned workers
    // see whatever was set in the parent before `new Worker(...)`.
    // The values flow through workerData on spawn.
    if (!globalThis.__ab_worker_env_data) {
        globalThis.__ab_worker_env_data = new Map();
    }
    var _envData = globalThis.__ab_worker_env_data;
    exports.setEnvironmentData = function setEnvironmentData(key, value) {
        if (value === undefined) _envData.delete(key);
        else _envData.set(key, value);
    };
    exports.getEnvironmentData = function getEnvironmentData(key) {
        return _envData.get(key);
    };

    // ---- BroadcastChannel re-export ------------------------
    // Node exports BroadcastChannel from worker_threads in addition
    // to the global. Keep the surfaces in sync.
    if (typeof globalThis.BroadcastChannel === 'function') {
        exports.BroadcastChannel = globalThis.BroadcastChannel;
    }
});

// ---- zlib.js ----
// zlib — synchronous deflate/inflate/gzip/gunzip backed by Rust
// (flate2). The wire format between JS and host is base64 strings so we
// don't need a binary-safe calling convention.

__register_module('zlib', function(module, exports, require) {

    var Buffer = require('buffer').Buffer;

    function needHost(name) {
        var fn = globalThis['__host_zlib_' + name];
        if (typeof fn !== 'function') {
            throw new Error('zlib.' + name + ' is not available');
        }
        return fn;
    }

    function toBase64(input) {
        if (Buffer.isBuffer(input)) return input.toString('base64');
        if (typeof input === 'string') return Buffer.from(input, 'utf8').toString('base64');
        if (input instanceof Uint8Array) return Buffer.from(input).toString('base64');
        throw new TypeError('zlib: input must be Buffer, Uint8Array, or string');
    }

    function checkAndFromBase64(raw, op) {
        if (typeof raw === 'string' && raw.indexOf('__HOST_ERR__:') === 0) {
            throw new Error('zlib.' + op + ': ' + raw.slice('__HOST_ERR__:'.length));
        }
        return Buffer.from(raw, 'base64');
    }

    function call(op, input) {
        var raw = needHost(op)(toBase64(input));
        return checkAndFromBase64(raw, op);
    }

    exports.deflateSync       = function(input) { return call('deflate_sync', input);  };
    exports.inflateSync       = function(input) { return call('inflate_sync', input);  };
    exports.gzipSync          = function(input) { return call('gzip_sync',    input);  };
    exports.gunzipSync        = function(input) { return call('gunzip_sync',  input);  };
    exports.zstdCompressSync  = function(input) { return call('zstd_compress_sync',   input); };
    exports.zstdDecompressSync = function(input) { return call('zstd_decompress_sync', input); };

    // Promise wrappers — handy, free, no actual async under the hood.
    function asPromise(fn) {
        // Node's API is `gzip(buf, [opts], cb)` — when the second or
        // third argument is a function we honour the cb shape; with
        // no cb we return a Promise. The cb fires on a microtask so
        // ordering matches Node's `process.nextTick` semantics.
        return function(input, optsOrCb, maybeCb) {
            var cb = (typeof optsOrCb === 'function') ? optsOrCb
                   : (typeof maybeCb === 'function') ? maybeCb
                   : null;
            if (cb) {
                Promise.resolve().then(function() {
                    try { cb(null, fn(input)); }
                    catch (e) { cb(e); }
                });
                return;
            }
            return new Promise(function(resolve, reject) {
                try { resolve(fn(input)); } catch (e) { reject(e); }
            });
        };
    }
    exports.deflate       = asPromise(exports.deflateSync);
    exports.inflate       = asPromise(exports.inflateSync);
    exports.gzip          = asPromise(exports.gzipSync);
    exports.gunzip        = asPromise(exports.gunzipSync);
    exports.zstdCompress  = asPromise(exports.zstdCompressSync);
    exports.zstdDecompress = asPromise(exports.zstdDecompressSync);

    // Aliases for the *-raw flavours (no zlib header). flate2 doesn't
    // expose the raw codec through our current host bridge, so we
    // route them to the regular deflate/inflate. Most callers (npm,
    // pacote, tar) only use gzip / inflate / deflate; the raw forms
    // matter for HTTP `Content-Encoding: deflate` decoding which is
    // rare in practice.
    exports.deflateRawSync = exports.deflateSync;
    exports.inflateRawSync = exports.inflateSync;
    exports.deflateRaw     = exports.deflate;
    exports.inflateRaw     = exports.inflate;
    exports.unzip          = exports.gunzip;
    exports.unzipSync      = exports.gunzipSync;

    // ---- streaming class API ---------------------------------------
    //
    // `new zlib.Gzip()` / `Gunzip()` / `Inflate()` / `Deflate()` —
    // EventEmitter-shaped Transform handles. `write(chunk)` queues
    // input; `end()` runs the codec and emits `data` then `end`.
    // minizlib (and therefore tar / pacote / npm install's tarball
    // extraction path) wraps these with its own Minipass shim and
    // calls `_processChunk(chunk, flushFlag)` directly — that path
    // is the hot one and uses one big chunk per call (the full
    // body comes through our async HTTP as a single chunk).
    var EventEmitter = require('events');

    function makeStreamingClass(syncFn, opName) {
        return function Codec(opts) {
            EventEmitter.call(this);
            this._opts = opts || {};
            this._chunks = [];
            this._closed = false;
            // `_handle` is the native handle stand-in. minizlib reads
            // and writes it through several layers — keep it a
            // truthy object with a no-op `close` to avoid breaking
            // its bookkeeping. minizlib's `_handle.close` is hijacked
            // at call-time anyway.
            this._handle = { close: function() {} };
        };
    }

    function attachCodecPrototype(Cls, syncFn, opName) {
        Cls.prototype = Object.create(EventEmitter.prototype);
        Cls.prototype.constructor = Cls;
        Cls.prototype.write = function(chunk, _enc, cb) {
            if (this._closed) {
                if (typeof cb === 'function') cb(new Error('zlib: write after close'));
                return false;
            }
            var b = Buffer.isBuffer(chunk) ? chunk
                  : (typeof chunk === 'string') ? Buffer.from(chunk, _enc || 'utf8')
                  : (chunk instanceof Uint8Array) ? Buffer.from(chunk)
                  : null;
            if (!b) {
                var e = new TypeError('zlib: chunk must be Buffer, Uint8Array, or string');
                if (typeof cb === 'function') cb(e);
                else this.emit('error', e);
                return false;
            }
            this._chunks.push(b);
            if (typeof cb === 'function') cb(null);
            return true;
        };
        Cls.prototype.end = function(chunk, _enc, cb) {
            if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
            if (typeof _enc === 'function')  { cb = _enc;  _enc  = undefined; }
            if (chunk !== undefined) this.write(chunk, _enc);
            var self = this;
            // Run the codec on the next microtask so listeners
            // (`on('data', …)` / `on('end', …)`) attached after `end()`
            // — the canonical Node pattern in stream pipes — still
            // observe the output.
            Promise.resolve().then(function() {
                if (self._closed) return;
                self._closed = true;
                try {
                    var combined = Buffer.concat(self._chunks);
                    var out = syncFn(combined);
                    self.emit('data', out);
                    self.emit('end');
                    self.emit('close');
                    if (typeof cb === 'function') cb(null);
                } catch (e) {
                    self.emit('error', e);
                    if (typeof cb === 'function') cb(e);
                }
            });
            return self;
        };
        Cls.prototype.close = function(cb) {
            this._closed = true;
            this._chunks.length = 0;
            if (typeof cb === 'function') Promise.resolve().then(function() { cb(); });
        };
        Cls.prototype.reset = function() {
            this._chunks.length = 0;
            this._closed = false;
        };
        Cls.prototype.flush = function(_kind, cb) {
            if (typeof _kind === 'function') { cb = _kind; }
            // Flush is meaningful only for streaming codecs that
            // support partial output. Sync wrapper has nothing to do.
            if (typeof cb === 'function') Promise.resolve().then(function() { cb(); });
        };
        // `_processChunk(chunk, flushFlag)` — minizlib's internal hot
        // path. Synchronously decode/encode the chunk and return the
        // Buffer result. Every chunk through minizlib's flow is fed
        // here; for our async-HTTP body which arrives as one chunk,
        // this is called once with the full payload.
        //
        // minizlib follows the data chunk with an empty-buffer
        // "finalize" call (`Z_FINISH` flush flag). Node's native
        // codec returns empty bytes; our sync host gunzip would
        // throw "unexpected end of file" on the empty input. Short-
        // circuit: empty input → empty output, no host call.
        Cls.prototype._processChunk = function(chunk, _flushFlag) {
            var b = Buffer.isBuffer(chunk) ? chunk
                  : (chunk instanceof Uint8Array) ? Buffer.from(chunk)
                  : Buffer.from(String(chunk));
            if (b.length === 0) return Buffer.alloc(0);
            return syncFn(b);
        };
        return Cls;
    }

    exports.Gzip    = attachCodecPrototype(makeStreamingClass(exports.gzipSync,    'gzip'),    exports.gzipSync,    'gzip');
    exports.Gunzip  = attachCodecPrototype(makeStreamingClass(exports.gunzipSync,  'gunzip'),  exports.gunzipSync,  'gunzip');
    exports.Deflate = attachCodecPrototype(makeStreamingClass(exports.deflateSync, 'deflate'), exports.deflateSync, 'deflate');
    exports.Inflate = attachCodecPrototype(makeStreamingClass(exports.inflateSync, 'inflate'), exports.inflateSync, 'inflate');
    exports.DeflateRaw    = exports.Deflate;
    exports.InflateRaw    = exports.Inflate;
    exports.Unzip         = exports.Gunzip;
    // Brotli — pure-Rust impl behind `__host_zlib_brotli_*`. Same
    // streaming/sync surface as the deflate/gzip codecs above.
    exports.brotliCompressSync = function(input) {
        return call('brotli_compress_sync', input);
    };
    exports.brotliDecompressSync = function(input) {
        return call('brotli_decompress_sync', input);
    };
    exports.BrotliCompress = attachCodecPrototype(
        makeStreamingClass(exports.brotliCompressSync, 'brotliCompress'),
        exports.brotliCompressSync,
        'brotliCompress'
    );
    exports.BrotliDecompress = attachCodecPrototype(
        makeStreamingClass(exports.brotliDecompressSync, 'brotliDecompress'),
        exports.brotliDecompressSync,
        'brotliDecompress'
    );

    // Factory functions that return a fresh codec instance. Mirrors
    // `http.createServer` / `net.createConnection` — Node sprinkles
    // these as the canonical entry point alongside the class form.
    exports.createGzip       = function(opts) { return new exports.Gzip(opts); };
    exports.createGunzip     = function(opts) { return new exports.Gunzip(opts); };
    exports.createDeflate    = function(opts) { return new exports.Deflate(opts); };
    exports.createInflate    = function(opts) { return new exports.Inflate(opts); };
    exports.createDeflateRaw = function(opts) { return new exports.DeflateRaw(opts); };
    exports.createInflateRaw = function(opts) { return new exports.InflateRaw(opts); };
    exports.createUnzip      = function(opts) { return new exports.Unzip(opts); };
    exports.createBrotliCompress    = function(opts) { return new exports.BrotliCompress(opts); };
    exports.createBrotliDecompress  = function(opts) { return new exports.BrotliDecompress(opts); };

    /// Async brotli — sync codec wrapped in `Promise.resolve().then`
    /// so the callback fires on a microtask (matches Node's contract).
    exports.brotliCompress = asPromise(exports.brotliCompressSync);
    exports.brotliDecompress = asPromise(exports.brotliDecompressSync);

    /// `zlib.crc32(data, value)` — Node 22.2+ pure-JS CRC32 (IEEE
    /// polynomial 0xedb88320). Pulls bytes via Buffer to handle the
    /// usual mix of string/Buffer/Uint8Array input shapes.
    var _crc32_table = (function() {
        var t = new Uint32Array(256);
        for (var n = 0; n < 256; n++) {
            var c = n;
            for (var k = 0; k < 8; k++) {
                c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
            }
            t[n] = c >>> 0;
        }
        return t;
    })();
    exports.crc32 = function(data, value) {
        var Buffer = require('buffer').Buffer;
        var bytes = Buffer.isBuffer(data) ? data : Buffer.from(data);
        var crc = ((value | 0) ^ 0xffffffff) >>> 0;
        for (var i = 0; i < bytes.length; i++) {
            crc = (_crc32_table[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
        }
        return (crc ^ 0xffffffff) >>> 0;
    };

    // Constants block — every Z_* flush flag, error code, and
    // strategy. minizlib reads these by name (`Z_NO_FLUSH`,
    // `Z_FINISH`, etc.). Numeric values match upstream zlib.
    exports.constants = {
        Z_NO_FLUSH:      0, Z_PARTIAL_FLUSH:   1, Z_SYNC_FLUSH:     2,
        Z_FULL_FLUSH:    3, Z_FINISH:          4, Z_BLOCK:          5,
        Z_TREES:         6,
        Z_OK:            0, Z_STREAM_END:      1, Z_NEED_DICT:      2,
        Z_ERRNO:        -1, Z_STREAM_ERROR:   -2, Z_DATA_ERROR:    -3,
        Z_MEM_ERROR:    -4, Z_BUF_ERROR:      -5, Z_VERSION_ERROR: -6,
        Z_NO_COMPRESSION:    0, Z_BEST_SPEED:        1,
        Z_BEST_COMPRESSION:  9, Z_DEFAULT_COMPRESSION: -1,
        Z_FILTERED:          1, Z_HUFFMAN_ONLY:      2,
        Z_RLE:               3, Z_FIXED:             4,
        Z_DEFAULT_STRATEGY:  0,
        ZLIB_VERNUM:    0x12b0,
        DEFLATE:        1,    INFLATE:    2, GZIP: 3, GUNZIP: 4,
        DEFLATERAW:     5, INFLATERAW: 6, UNZIP: 7,
        BROTLI_DECODE:  8, BROTLI_ENCODE: 9,
        Z_MIN_WINDOWBITS:    8, Z_MAX_WINDOWBITS:   15, Z_DEFAULT_WINDOWBITS: 15,
        Z_MIN_CHUNK:      64, Z_MAX_CHUNK:        Infinity, Z_DEFAULT_CHUNK: 16384,
        Z_MIN_MEMLEVEL:    1, Z_MAX_MEMLEVEL:      9, Z_DEFAULT_MEMLEVEL: 8,
        Z_MIN_LEVEL:      -1, Z_MAX_LEVEL:         9, Z_DEFAULT_LEVEL: -1,
    };

    // Constants spread on the module too — Node exposes both
    // `zlib.Z_OK` and `zlib.constants.Z_OK`. Keep parity.
    Object.keys(exports.constants).forEach(function(k) {
        if (typeof exports[k] === 'undefined') exports[k] = exports.constants[k];
    });
});

