From f8690d917518cb9960251eaf71d649377d283dcb Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 26 Oct 2026 16:04:22 +0900 Subject: [PATCH 1/2] Verify existing API scenarios and fix crypto and filesystem parity --- demo/tests/experiments/node-compat/README.md | 33 +- .../experiments/node-compat/api-test-map.mjs | 185 ++++ .../node-compat/api-test-map.test.mjs | 109 +++ .../node-compat/api-test-operations.json | 827 ++++++++++++++++++ .../node-compat/expansion-contracts.probe.mjs | 16 +- .../node-compat/expansion-native.mjs | 10 +- src/compat/console/forwarding.spec.ts | 69 ++ src/compat/crypto/coverage.spec.mjs | 370 ++++++++ src/compat/crypto/keys.ts | 8 +- src/compat/crypto/native-crypto.ts | 4 + .../diagnostics-channel/coverage.spec.mjs | 82 ++ src/compat/dns/coverage.spec.mjs | 58 ++ src/compat/expansion/index.spec.mjs | 15 + src/compat/fs/coverage.spec.mjs | 357 ++++++++ src/compat/fs/file-handle.ts | 33 +- src/compat/fs/index.ts | 16 + src/compat/fs/io.ts | 5 +- src/compat/http/coverage.spec.mjs | 31 + src/compat/util/coverage.spec.mjs | 108 +++ src/compat/zlib/coverage.spec.mjs | 283 ++++++ vitest.config.ts | 1 + 21 files changed, 2603 insertions(+), 17 deletions(-) create mode 100644 demo/tests/experiments/node-compat/api-test-map.mjs create mode 100644 demo/tests/experiments/node-compat/api-test-map.test.mjs create mode 100644 demo/tests/experiments/node-compat/api-test-operations.json create mode 100644 src/compat/console/forwarding.spec.ts create mode 100644 src/compat/crypto/coverage.spec.mjs create mode 100644 src/compat/diagnostics-channel/coverage.spec.mjs create mode 100644 src/compat/dns/coverage.spec.mjs create mode 100644 src/compat/fs/coverage.spec.mjs create mode 100644 src/compat/http/coverage.spec.mjs create mode 100644 src/compat/util/coverage.spec.mjs create mode 100644 src/compat/zlib/coverage.spec.mjs diff --git a/demo/tests/experiments/node-compat/README.md b/demo/tests/experiments/node-compat/README.md index 859909c..7e31810 100644 --- a/demo/tests/experiments/node-compat/README.md +++ b/demo/tests/experiments/node-compat/README.md @@ -38,7 +38,12 @@ from individual case and socket deadlines. `NODE_COMPAT_CASES=name,otherName` filters shared cases for diagnosis. It does not filter native network rows, and a filtered run is not full acceptance. Native -`stage:complete` means all observations were collected; exact assertions run +filtered runs read the matching `targeted/expansion-contracts-workerd.json`; +run the public comparison with the same filter first. Every native case checks +the SHA-256 of its function source against the oracle record, so editing a case +requires regenerating its baseline. + +Native `stage:complete` means all observations were collected; exact assertions run subsequently and may still fail. Current TLS and WebSocket implementation gaps remain failures, not skipped or accepted differences. The reports, generated harness, compiled hash and workerd baseline live under @@ -49,3 +54,29 @@ The narrowly approved attachment size-accounting boundary is documented in the `node --test demo/tests/experiments/node-compat/websocket-attachment-boundary.probe.mjs` to reproduce its pinned Workers observations. This reference probe does not certify the candidate or exempt network failures from acceptance. + +## API and test mapping + +`api-test-operations.json` maps reviewed operation scenarios to named contracts +and execution targets. It distinguishes host-forwarding unit tests from shared +behavior and expected-rejection comparisons. It is test metadata, not a record +that a particular candidate passed. Keep execution logs and package/source hashes +in generated artifacts and PR evidence. + +```sh +node demo/tests/experiments/node-compat/api-test-map.mjs --write +node --test demo/tests/experiments/node-compat/api-test-map.test.mjs +``` + +The generated `artifacts/validation/existing-api-coverage/api-test-map.json` +lists every pinned module/export and source references to adjacent cases and +fixtures. These token matches are navigation candidates, not verified behavioral +coverage: dynamic calls may lack a literal reference, while a namespace assertion +may contain an API name without calling it. Use the reviewed operation rows and +actual assertions to establish scope. The guard checks inventory retention, +named-case existence, shared-runner or unit-runner registration, API references +and target names. It cannot establish semantic coverage or replace review. + +Missing APIs and documented engine/host boundaries remain separate from test +gaps. A passing finite scenario does not certify all options, states or the entire +module; retain the whole-module acceptance gate in `CONTRIBUTING.md`. diff --git a/demo/tests/experiments/node-compat/api-test-map.mjs b/demo/tests/experiments/node-compat/api-test-map.mjs new file mode 100644 index 0000000..5997ae6 --- /dev/null +++ b/demo/tests/experiments/node-compat/api-test-map.mjs @@ -0,0 +1,185 @@ +import fs from "node:fs"; +import path from "node:path"; +import { parse } from "@babel/parser"; +import { fileURLToPath } from "node:url"; +const root = fileURLToPath(new URL("../../../..", import.meta.url)); +const read = (file) => fs.readFileSync(path.resolve(root, file), "utf8"); +const base = JSON.parse( + read("demo/tests/experiments/node-compat/exports.json"), +); +const types = JSON.parse( + read("demo/tests/experiments/node-compat/export-types.json"), +); +const reviewed = JSON.parse( + read("demo/tests/experiments/node-compat/api-test-operations.json"), +); +const gaps = JSON.parse( + read("demo/tests/experiments/node-compat/surface-gaps.json"), +); +const shared = read("src/tooling/shared.ts"); +const entries = Object.fromEntries( + [ + ...shared + .slice( + shared.indexOf("const builtins:"), + shared.indexOf("function builtinAliases"), + ) + .matchAll(/\[\s*"([^"]+)",\s*"([^"]+)"/g), + ].map(([, name, entry]) => [ + name.replace(/^node:/, ""), + "src/compat/" + entry.replace(/\.(c?js)$/, ".ts"), + ]), +); +const inventory = { + modules: Object.keys(base.modules).map((module) => ({ + module, + entry: entries[module], + })), +}; +const walk = (d) => + fs + .readdirSync(path.resolve(root, d), { withFileTypes: true }) + .flatMap((x) => + x.isDirectory() ? walk(path.join(d, x.name)) : [path.join(d, x.name)], + ); +const cases = []; +for (const file of walk("src/compat").filter((x) => + /\.(spec|fixture)\.[cm]?[jt]s$/.test(x), +)) { + const source = read(file), + tree = parse(source, { + sourceType: "module", + plugins: ["typescript", "explicitResourceManagement"], + }); + const name = (n) => n?.key?.name ?? n?.key?.value ?? n?.id?.name; + const add = (id, node, kind) => + cases.push({ + id: file + "#" + id, + file, + name: id, + kind, + code: source.slice(node.start, node.end), + }); + const visit = (n) => { + if (!n || typeof n !== "object") return; + if ( + n.type === "ObjectProperty" && + name(n) === "cases" && + n.value.type === "ObjectExpression" + ) + for (const p of n.value.properties) + if (name(p)) add(name(p), p, "contract"); + if ( + n.type === "VariableDeclarator" && + n.init?.type === "ObjectExpression" + ) { + if (/Cases$/.test(name(n))) { + for (const p of n.init.properties) + if (name(p)) add(name(p), p, "comparison"); + } else if (n.init.properties.some((p) => name(p) === "test")) + add(name(n), n.init, "fixture"); + } + if ( + n.type === "CallExpression" && + ["test", "it"].includes(source.slice(n.callee.start, n.callee.end)) && + n.arguments[0]?.type === "StringLiteral" + ) + add(n.arguments[0].value, n, "unit"); + for (const [k, v] of Object.entries(n)) + if (k !== "loc") { + if (Array.isArray(v)) v.forEach(visit); + else if (v && typeof v === "object") visit(v); + } + }; + visit(tree); +} +const special = { + "fs/promises": "fs", + "path/posix": "path", + "path/win32": "path", + "util/types": "util", + _tls_wrap: "tls", + _stream_wrap: "tls", +}; +const inputName = { + fs: "fs", + crypto: "crypto", + zlib: "zlib", + util: "util", + sys: "sys", + "util/types": "types", + tls: "tls", + http: "http", + process: "process", + console: "console", + module: "module", + stream: "classicStreams", + "stream/web": "streams", + _http_common: "httpCommon", + _http_outgoing: "httpOutgoing", + _http_server: "httpServer", +}; +const rows = []; +for (const m of inventory.modules) { + const owner = special[m.module] + ? inventory.modules.find((x) => x.module === special[m.module]) + : m; + const dir = path.dirname(owner.entry); + let selected = cases.filter((c) => c.file.startsWith(dir + "/")); + if (inputName[m.module]) + selected.push( + ...cases.filter( + (c) => + c.file.includes("/expansion/") && + new RegExp("\\b" + inputName[m.module] + "\\b").test( + c.code.slice(0, c.code.indexOf("})") + 2), + ), + ), + ); + const entries = base.modules[m.module].map((exp) => { + const escaped = exp.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const matched = selected.filter((c) => + new RegExp("\\b" + escaped + "\\b").test(c.code), + ); + return { + name: exp, + type: types.modules[m.module][exp], + surfaceTest: "demo/tests/experiments/node-compat/local-surface.test.mjs", + missingInPinnedSurfaceAudit: + gaps.common[m.module]?.missing?.includes(exp) ?? false, + reviewedOperations: reviewed.operations + .filter( + (operation) => + operation.modules.includes(m.module) && + operation.apis.some( + (api) => api === exp || api.startsWith(exp + "."), + ), + ) + .map((operation) => operation.id), + cases: matched.map((c) => c.id), + }; + }); + rows.push({ module: m.module, entry: m.entry, exports: entries }); +} +export const referenceIndex = { + scope: + "Source reference index, not behavioral coverage certification. Token matches are navigation candidates; reviewed operation rows are in api-test-operations.json. Every export also has the name/type inventory audit in local-surface.test.mjs.", + profile: base.profile, + modules: rows, + cases: cases.map(({ code, ...c }) => c), +}; +if (process.argv.includes("--write")) { + fs.mkdirSync( + path.resolve(root, "artifacts/validation/existing-api-coverage"), + { + recursive: true, + }, + ); + fs.writeFileSync( + path.resolve( + root, + "artifacts/validation/existing-api-coverage/api-test-map.json", + ), + JSON.stringify(referenceIndex, null, 2) + "\n", + ); +} diff --git a/demo/tests/experiments/node-compat/api-test-map.test.mjs b/demo/tests/experiments/node-compat/api-test-map.test.mjs new file mode 100644 index 0000000..92d106e --- /dev/null +++ b/demo/tests/experiments/node-compat/api-test-map.test.mjs @@ -0,0 +1,109 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { referenceIndex } from "./api-test-map.mjs"; +import { eventCases } from "../../../../src/compat/expansion/index.spec.mjs"; +const operations = JSON.parse( + await readFile(new URL("api-test-operations.json", import.meta.url), "utf8"), +); +const exports = JSON.parse( + await readFile(new URL("exports.json", import.meta.url), "utf8"), +); + +test("API reference index retains every pinned module and export without implying behavior coverage", () => { + assert.deepEqual(referenceIndex.profile, exports.profile); + assert.deepEqual( + referenceIndex.modules.map((m) => m.module), + Object.keys(exports.modules), + ); + const ids = new Set(referenceIndex.cases.map((c) => c.id)); + for (const module of referenceIndex.modules) { + assert.deepEqual( + module.exports.map((e) => e.name), + exports.modules[module.module], + ); + for (const entry of module.exports) + for (const id of entry.cases) assert.ok(ids.has(id), id); + } + assert.match(referenceIndex.scope, /not behavioral coverage/); +}); + +test("reviewed operation rows refer to registered named tests and valid API targets", async () => { + assert.deepEqual(operations.profile, exports.profile); + const ids = new Set(); + for (const operation of operations.operations) { + assert.ok(!ids.has(operation.id), operation.id); + ids.add(operation.id); + for (const module of operation.modules) + assert.ok(exports.modules[module], module); + const id = operation.test.file + "#" + operation.test.case; + assert.ok( + referenceIndex.cases.some((c) => c.id === id), + "Missing named contract: " + id, + ); + assert.ok( + operation.apis.length && + operation.scenarios.length && + operation.targets.length, + operation.id, + ); + for (const api of operation.apis) { + const receiver = api.split(".")[0]; + assert.ok( + operation.modules.some((module) => + exports.modules[module].includes(receiver), + ) || operation.receivers?.[receiver], + `Unknown API: ${operation.id}/${api}`, + ); + } + const allowed = new Set([ + "unit", + "workerd", + ...["esbuild", "vite"].flatMap((build) => + ["chromium", "webkit"].flatMap((engine) => + ["page", "worker"].map((mode) => `${build}/${engine}/${mode}`), + ), + ), + ...["ios", "android"].flatMap((platform) => + ["page", "worker"].map((mode) => `${platform}/${mode}`), + ), + ]); + for (const target of operation.targets) + assert.ok(allowed.has(target), `Unknown target: ${target}`); + if (operation.targets.includes("workerd")) { + const owner = await import( + new URL("../../../../" + operation.test.file, import.meta.url) + ); + const owned = Object.values(owner).find( + (value) => typeof value?.[operation.test.case] === "function", + )?.[operation.test.case]; + assert.equal(typeof owned, "function", id); + assert.equal( + eventCases[operation.test.case], + owned, + `Contract is not registered in the shared public/native runner: ${id}`, + ); + for (const target of [ + "ios/page", + "ios/worker", + "android/page", + "android/worker", + ]) + assert.ok( + operation.targets.includes(target), + `Missing native target: ${id}/${target}`, + ); + } else { + const configuration = await readFile( + new URL("../../../../vitest.config.ts", import.meta.url), + "utf8", + ); + assert.ok( + configuration.includes(JSON.stringify(operation.test.file)), + `Unit case is not registered: ${id}`, + ); + } + } + for (const limitation of operations.remainingBoundaries) + assert.ok(["Not implemented", "In progress"].includes(limitation.status)); +}); diff --git a/demo/tests/experiments/node-compat/api-test-operations.json b/demo/tests/experiments/node-compat/api-test-operations.json new file mode 100644 index 0000000..fa815b3 --- /dev/null +++ b/demo/tests/experiments/node-compat/api-test-operations.json @@ -0,0 +1,827 @@ +{ + "scope": "Reviewed operation-to-contract mappings. A mapped case is not proof of execution or exhaustive module compatibility. Run evidence is kept in artifacts with source/package hashes; known missing APIs and engine/host boundaries remain In progress.", + "profile": { + "compatibilityDate": "2026-10-17", + "workerd": "1.20261012.1" + }, + "operations": [ + { + "id": "crypto-signature-callbacks", + "modules": ["crypto"], + "apis": ["sign", "verify"], + "test": { + "file": "src/compat/crypto/coverage.spec.mjs", + "case": "cryptoSignatureCallbacks", + "kind": "behavior" + }, + "scenarios": [ + "Ed25519 success and false verification", + "invalid digest/data/signature/key", + "synchronous throw versus callback, return and microtask order, bounded callback completion" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "crypto-ecdh-input", + "modules": ["crypto"], + "apis": [ + "createECDH", + "ECDH.convertKey", + "ECDH.prototype.setPrivateKey", + "ECDH.prototype.computeSecret", + "ECDH.prototype.getPrivateKey", + "ECDH.prototype.getPublicKey" + ], + "test": { + "file": "src/compat/crypto/coverage.spec.mjs", + "case": "cryptoEcdhInputCoverage", + "kind": "behavior" + }, + "scenarios": [ + "prime256v1 typed/DataView subranges", + "shadowed buffer/byteOffset/byteLength", + "detached views and invalid ArrayBuffer", + "failed private-key update preserves state" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "crypto-random-callbacks", + "modules": ["crypto"], + "apis": ["randomInt", "randomUUID"], + "test": { + "file": "src/compat/crypto/coverage.spec.mjs", + "case": "cryptoRandomCallbackCoverage", + "kind": "behavior" + }, + "scenarios": [ + "max-only and min/max overloads", + "invalid range/width/null", + "disableEntropyCache validation and getter access" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "crypto-secret-key-callbacks", + "modules": ["crypto"], + "apis": ["generateKey", "generateKeySync"], + "test": { + "file": "src/compat/crypto/coverage.spec.mjs", + "case": "cryptoSecretKeyCallbackCoverage", + "kind": "behavior" + }, + "scenarios": [ + "HMAC nine-bit key success", + "invalid type/HMAC/AES/null options", + "length getter evaluated once", + "callback and microtask order" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "fs-read-overloads", + "modules": ["fs", "fs/promises"], + "apis": ["FileHandle.read"], + "test": { + "file": "src/compat/fs/coverage.spec.mjs", + "case": "fsReadOverloadCoverage", + "kind": "behavior" + }, + "scenarios": [ + "default allocation", + "options and buffer/options override", + "getter order and invalid offset/position precedence", + "buffer identity and mutation" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ], + "receivers": { + "FileHandle": "fs.promises.open() result" + } + }, + { + "id": "fs-vector-views", + "modules": ["fs", "fs/promises"], + "apis": [ + "readv", + "readvSync", + "writev", + "writevSync", + "FileHandle.readv", + "FileHandle.writev" + ], + "test": { + "file": "src/compat/fs/coverage.spec.mjs", + "case": "fsVectorCoverage", + "kind": "behavior" + }, + "scenarios": [ + "typed/DataView subranges and empty view", + "shadow byteLength and detached view", + "null and explicit position, subsequent descriptor cursor", + "returned array identity and file contents" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ], + "receivers": { + "FileHandle": "fs.promises.open() result" + } + }, + { + "id": "fs-web-stream-lifetime", + "modules": ["fs", "fs/promises"], + "apis": ["FileHandle.readableWebStream", "FileHandle.close"], + "test": { + "file": "src/compat/fs/coverage.spec.mjs", + "case": "fsWebStreamCoverage", + "kind": "behavior" + }, + "scenarios": [ + "zero/nonzero BYOB offset", + "EOF/cancel/external close with autoClose true/false", + "pending read settlement, close count and retained handle", + "cleanup errors and timeout failure preservation" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ], + "receivers": { + "FileHandle": "fs.promises.open() result" + } + }, + { + "id": "fs-export-constructors", + "modules": ["fs", "fs/promises"], + "apis": ["Dir", "Stats", "promises.watch"], + "test": { + "file": "src/compat/fs/coverage.spec.mjs", + "case": "fsExportCoverage", + "kind": "behavior" + }, + "scenarios": [ + "missing Dir handle and empty directory", + "Stats illegal constructor", + "promise watch expected rejection" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "zlib-output-limit", + "modules": ["zlib"], + "apis": [ + "gunzip", + "inflate", + "inflateRaw", + "unzip", + "brotliDecompress", + "zstdDecompress", + "gunzipSync", + "inflateSync", + "inflateRawSync", + "unzipSync", + "brotliDecompressSync", + "zstdDecompressSync" + ], + "test": { + "file": "src/compat/zlib/coverage.spec.mjs", + "case": "zlibOutputLimitCoverage", + "kind": "behavior" + }, + "scenarios": [ + "65-byte decoded payload at limits 64/65/66, chunkSize 64", + "sync/callback and info forms", + "callback count, cleanup and recovery after failure" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "zlib-strategy-transitions", + "modules": ["zlib"], + "apis": ["Deflate.prototype.params", "DeflateRaw.prototype.params"], + "test": { + "file": "src/compat/zlib/coverage.spec.mjs", + "case": "zlibStrategyCoverage", + "kind": "behavior" + }, + "scenarios": [ + "pending output with HUFFMAN_ONLY and RLE strategy transitions", + "invalid strategy followed by successful write", + "callback order, errors, byte counters and decoded payload" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "zlib-configured-reset", + "modules": ["zlib"], + "apis": [ + "Deflate.prototype.reset", + "Inflate.prototype.reset", + "BrotliCompress.prototype.reset", + "BrotliDecompress.prototype.reset", + "ZstdCompress.prototype.reset", + "ZstdDecompress.prototype.reset" + ], + "test": { + "file": "src/compat/zlib/coverage.spec.mjs", + "case": "zlibResetCoverage", + "kind": "behavior" + }, + "scenarios": [ + "dictionary/nondefault encoder configuration", + "complete first frame and post-reset second frame", + "partial decoder frame followed by reset", + "first phase output and reachedReset state recorded" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "zlib-factories", + "modules": ["zlib"], + "apis": [ + "createDeflate", + "createDeflateRaw", + "createGzip", + "createInflate", + "createInflateRaw", + "createGunzip", + "createUnzip", + "createBrotliCompress", + "createBrotliDecompress", + "createZstdCompress", + "createZstdDecompress", + "constants", + "codes", + "BROTLI_DECODE", + "BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES", + "BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP", + "BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES", + "BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1", + "BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2", + "BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS", + "BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET", + "BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1", + "BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2", + "BROTLI_DECODER_ERROR_FORMAT_CL_SPACE", + "BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT", + "BROTLI_DECODER_ERROR_FORMAT_DICTIONARY", + "BROTLI_DECODER_ERROR_FORMAT_DISTANCE", + "BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE", + "BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE", + "BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE", + "BROTLI_DECODER_ERROR_FORMAT_PADDING_1", + "BROTLI_DECODER_ERROR_FORMAT_PADDING_2", + "BROTLI_DECODER_ERROR_FORMAT_RESERVED", + "BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET", + "BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME", + "BROTLI_DECODER_ERROR_FORMAT_TRANSFORM", + "BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS", + "BROTLI_DECODER_ERROR_INVALID_ARGUMENTS", + "BROTLI_DECODER_ERROR_UNREACHABLE", + "BROTLI_DECODER_NEEDS_MORE_INPUT", + "BROTLI_DECODER_NEEDS_MORE_OUTPUT", + "BROTLI_DECODER_NO_ERROR", + "BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION", + "BROTLI_DECODER_PARAM_LARGE_WINDOW", + "BROTLI_DECODER_RESULT_ERROR", + "BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT", + "BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT", + "BROTLI_DECODER_RESULT_SUCCESS", + "BROTLI_DECODER_SUCCESS", + "BROTLI_DEFAULT_MODE", + "BROTLI_DEFAULT_QUALITY", + "BROTLI_DEFAULT_WINDOW", + "BROTLI_ENCODE", + "BROTLI_LARGE_MAX_WINDOW_BITS", + "BROTLI_MAX_INPUT_BLOCK_BITS", + "BROTLI_MAX_QUALITY", + "BROTLI_MAX_WINDOW_BITS", + "BROTLI_MIN_INPUT_BLOCK_BITS", + "BROTLI_MIN_QUALITY", + "BROTLI_MIN_WINDOW_BITS", + "BROTLI_MODE_FONT", + "BROTLI_MODE_GENERIC", + "BROTLI_MODE_TEXT", + "BROTLI_OPERATION_EMIT_METADATA", + "BROTLI_OPERATION_FINISH", + "BROTLI_OPERATION_FLUSH", + "BROTLI_OPERATION_PROCESS", + "BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING", + "BROTLI_PARAM_LARGE_WINDOW", + "BROTLI_PARAM_LGBLOCK", + "BROTLI_PARAM_LGWIN", + "BROTLI_PARAM_MODE", + "BROTLI_PARAM_NDIRECT", + "BROTLI_PARAM_NPOSTFIX", + "BROTLI_PARAM_QUALITY", + "DEFLATE", + "DEFLATERAW", + "GUNZIP", + "GZIP", + "INFLATE", + "INFLATERAW", + "UNZIP", + "ZLIB_VERNUM", + "ZSTD_COMPRESS", + "ZSTD_DECODE", + "ZSTD_DECOMPRESS", + "ZSTD_ENCODE", + "ZSTD_error_GENERIC", + "ZSTD_error_checksum_wrong", + "ZSTD_error_corruption_detected", + "ZSTD_error_dictionaryCreation_failed", + "ZSTD_error_dictionary_corrupted", + "ZSTD_error_dictionary_wrong", + "ZSTD_error_dstBuffer_null", + "ZSTD_error_dstSize_tooSmall", + "ZSTD_error_frameParameter_unsupported", + "ZSTD_error_frameParameter_windowTooLarge", + "ZSTD_error_init_missing", + "ZSTD_error_literals_headerWrong", + "ZSTD_error_maxSymbolValue_tooLarge", + "ZSTD_error_maxSymbolValue_tooSmall", + "ZSTD_error_memory_allocation", + "ZSTD_error_noForwardProgress_destFull", + "ZSTD_error_noForwardProgress_inputEmpty", + "ZSTD_error_no_error", + "ZSTD_error_parameter_combination_unsupported", + "ZSTD_error_parameter_outOfBound", + "ZSTD_error_parameter_unsupported", + "ZSTD_error_prefix_unknown", + "ZSTD_error_srcSize_wrong", + "ZSTD_error_stabilityCondition_notRespected", + "ZSTD_error_stage_wrong", + "ZSTD_error_tableLog_tooLarge", + "ZSTD_error_version_unsupported", + "ZSTD_error_workSpace_tooSmall", + "Z_BEST_COMPRESSION", + "Z_BEST_SPEED", + "Z_BLOCK", + "Z_BUF_ERROR", + "Z_DATA_ERROR", + "Z_DEFAULT_CHUNK", + "Z_DEFAULT_COMPRESSION", + "Z_DEFAULT_LEVEL", + "Z_DEFAULT_MEMLEVEL", + "Z_DEFAULT_STRATEGY", + "Z_DEFAULT_WINDOWBITS", + "Z_ERRNO", + "Z_FILTERED", + "Z_FINISH", + "Z_FIXED", + "Z_FULL_FLUSH", + "Z_HUFFMAN_ONLY", + "Z_MAX_CHUNK", + "Z_MAX_LEVEL", + "Z_MAX_MEMLEVEL", + "Z_MAX_WINDOWBITS", + "Z_MEM_ERROR", + "Z_MIN_CHUNK", + "Z_MIN_LEVEL", + "Z_MIN_MEMLEVEL", + "Z_MIN_WINDOWBITS", + "Z_NEED_DICT", + "Z_NO_COMPRESSION", + "Z_NO_FLUSH", + "Z_OK", + "Z_PARTIAL_FLUSH", + "Z_RLE", + "Z_STREAM_END", + "Z_STREAM_ERROR", + "Z_SYNC_FLUSH", + "Z_VERSION_ERROR" + ], + "test": { + "file": "src/compat/zlib/coverage.spec.mjs", + "case": "zlibFactoryCoverage", + "kind": "behavior" + }, + "scenarios": [ + "constructor identity, initial readable/writable state and byte counter", + "factory product cleanup; codec payload behavior has separate rows", + "all numeric named exports, constants and codes values against pinned Workers" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "http-header-validation", + "modules": ["http", "_http_outgoing"], + "apis": ["validateHeaderName", "validateHeaderValue"], + "test": { + "file": "src/compat/http/coverage.spec.mjs", + "case": "httpHeaderValidatorCoverage", + "kind": "behavior" + }, + "scenarios": [ + "alias identity", + "valid and invalid names/values, return, error name/code/message" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "module-preload-stub", + "modules": ["module"], + "apis": ["_preloadModules"], + "test": { + "file": "src/compat/expansion/index.spec.mjs", + "case": "moduleMetadata", + "kind": "expected-rejection" + }, + "scenarios": ["expected Workers unsupported operation"], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "util-ordinary-predicates", + "modules": ["util", "sys", "util/types"], + "apis": [ + "isAnyArrayBuffer", + "isArray", + "isArrayBuffer", + "isArrayBufferView", + "isBigInt64Array", + "isBigIntObject", + "isBigUint64Array", + "isBoolean", + "isBooleanObject", + "isBoxedPrimitive", + "isBuffer", + "isDataView", + "isDate", + "isError", + "isFloat32Array", + "isFloat64Array", + "isFunction", + "isInt16Array", + "isInt32Array", + "isInt8Array", + "isMap", + "isNativeError", + "isNull", + "isNullOrUndefined", + "isNumber", + "isNumberObject", + "isObject", + "isPrimitive", + "isRegExp", + "isSet", + "isString", + "isStringObject", + "isSymbol", + "isSymbolObject", + "isTypedArray", + "isUint16Array", + "isUint32Array", + "isUint8Array", + "isUint8ClampedArray", + "isUndefined", + "isWeakMap", + "isWeakSet" + ], + "test": { + "file": "src/compat/util/coverage.spec.mjs", + "case": "utilPredicateCoverage", + "kind": "behavior" + }, + "scenarios": [ + "35 ordinary values across legacy and brand predicate families", + "engine-private brands and engine-dependent availability are not certified" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "console-forwarding", + "modules": ["console"], + "apis": [ + "log", + "info", + "debug", + "warn", + "error", + "dir", + "time", + "timeEnd", + "timeLog", + "trace", + "assert", + "clear", + "count", + "countReset", + "group", + "groupEnd", + "table", + "dirxml", + "groupCollapsed", + "profile", + "profileEnd", + "timeStamp" + ], + "test": { + "file": "src/compat/console/forwarding.spec.ts", + "case": "console methods retain their host receiver and arguments after import", + "kind": "host-forwarding" + }, + "scenarios": [ + "captured host binding, receiver and argument identity", + "prototype/default wiring", + "host-rendered text is outside this forwarding test" + ], + "targets": ["unit"] + }, + { + "id": "dns-callback-failure", + "modules": ["dns", "dns/promises"], + "apis": ["resolve4", "Resolver.prototype.resolve4"], + "test": { + "file": "src/compat/dns/coverage.spec.mjs", + "case": "dnsCallbackFailureCoverage", + "kind": "behavior" + }, + "scenarios": [ + "HTTP 500/network throw/missing answers", + "module and Resolver callback errors agree with promise error fields", + "undefined return and asynchronous single callback in observed task window" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ] + }, + { + "id": "diagnostics-callback-control-flow", + "modules": ["diagnostics_channel"], + "apis": ["TracingChannel.prototype.traceCallback"], + "test": { + "file": "src/compat/diagnostics-channel/coverage.spec.mjs", + "case": "diagnosticsCallbackCoverage", + "kind": "behavior" + }, + "scenarios": [ + "error callback, function throw, callback throw and deferred callback", + "event order, error identity and return value", + "callback receiver and bound AsyncLocalStorage", + "unsubscribe/unbind cleanup" + ], + "targets": [ + "workerd", + "esbuild/chromium/page", + "esbuild/chromium/worker", + "esbuild/webkit/page", + "esbuild/webkit/worker", + "vite/chromium/page", + "vite/chromium/worker", + "vite/webkit/page", + "vite/webkit/worker", + "ios/page", + "ios/worker", + "android/page", + "android/worker" + ], + "receivers": { + "TracingChannel": "diagnostics_channel.tracingChannel() result" + } + } + ], + "remainingBoundaries": [ + { + "modules": ["process"], + "apis": ["abort", "reallyExit", "getBuiltinModule"], + "status": "Not implemented", + "reference": "docs/compatibility.md" + }, + { + "modules": ["util", "sys"], + "apis": ["getCallSite", "getCallSites"], + "status": "Not implemented", + "reference": "src/compat/util/README.md" + }, + { + "modules": [ + "util/types", + "async_hooks", + "process", + "worker_threads", + "console", + "module" + ], + "status": "In progress", + "reference": "docs/compatibility.md", + "reason": "Engine-private brands, native async context, termination, host event/logging behavior and executable module loading are not waived by these finite contracts." + } + ] +} diff --git a/demo/tests/experiments/node-compat/expansion-contracts.probe.mjs b/demo/tests/experiments/node-compat/expansion-contracts.probe.mjs index eedc8a9..6aed4c0 100644 --- a/demo/tests/experiments/node-compat/expansion-contracts.probe.mjs +++ b/demo/tests/experiments/node-compat/expansion-contracts.probe.mjs @@ -4,6 +4,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readFile, mkdir, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; +import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; import { build } from "esbuild"; import { chromium, webkit } from "@playwright/test"; @@ -104,7 +105,20 @@ const output = new URL( await mkdir(output, { recursive: true }); await writeFile( new URL("expansion-contracts-workerd.json", output), - JSON.stringify({ profile, results: baseline }, null, 2) + "\n", + JSON.stringify( + { + profile, + sources: Object.fromEntries( + Object.entries(eventCases).map(([name, fn]) => [ + name, + createHash("sha256").update(fn.toString()).digest("hex"), + ]), + ), + results: baseline, + }, + null, + 2, + ) + "\n", ); const compiled = await build({ absWorkingDir: root, diff --git a/demo/tests/experiments/node-compat/expansion-native.mjs b/demo/tests/experiments/node-compat/expansion-native.mjs index 5171d40..e1b3b31 100644 --- a/demo/tests/experiments/node-compat/expansion-native.mjs +++ b/demo/tests/experiments/node-compat/expansion-native.mjs @@ -35,7 +35,9 @@ const root = fileURLToPath(new URL("../../../..", import.meta.url)); const baseline = JSON.parse( await readFile( new URL( - "../../../artifacts/node-inventory/expansion-contracts-workerd.json", + requestedCases + ? "../../../artifacts/node-inventory/targeted/expansion-contracts-workerd.json" + : "../../../artifacts/node-inventory/expansion-contracts-workerd.json", import.meta.url, ), "utf8", @@ -56,6 +58,12 @@ if (requestedCases) ); assert.deepEqual(baseline.profile, profile); assert.deepEqual(Object.keys(baseline.results), Object.keys(eventCases)); +for (const [name, fn] of Object.entries(eventCases)) + assert.equal( + baseline.sources?.[name], + createHash("sha256").update(fn.toString()).digest("hex"), + `Stale Workers contract: ${name}; rerun the matching public comparison`, + ); const artifacts = fileURLToPath( new URL( `../../../artifacts/node-inventory/native-expansion/${platform}/`, diff --git a/src/compat/console/forwarding.spec.ts b/src/compat/console/forwarding.spec.ts new file mode 100644 index 0000000..79d22cc --- /dev/null +++ b/src/compat/console/forwarding.spec.ts @@ -0,0 +1,69 @@ +import { test, expect, vi } from "vitest"; + +test("console methods retain their host receiver and arguments after import", async () => { + const names = [ + "log", + "info", + "debug", + "warn", + "error", + "dir", + "time", + "timeEnd", + "timeLog", + "trace", + "assert", + "clear", + "count", + "countReset", + "group", + "groupEnd", + "table", + "dirxml", + "groupCollapsed", + "profile", + "profileEnd", + "timeStamp", + ] as const; + const descriptors = Object.getOwnPropertyDescriptors(globalThis.console); + const seen: { name: string; receiver: unknown; args: unknown[] }[] = []; + try { + for (const name of names) + Object.defineProperty(console, name, { + configurable: true, + writable: true, + value: function (this: unknown, ...args: unknown[]) { + seen.push({ name, receiver: this, args }); + }, + }); + vi.resetModules(); + const api = await import("./index.js"); + for (const name of names) { + // Captured binding must not be replaced by later mutation of the host. + Object.defineProperty(console, name, { + configurable: true, + writable: true, + value: () => { + throw Error("late host lookup"); + }, + }); + const payload = { name }; + expect(Reflect.apply(api[name], {}, ["%s", payload, 3])).toBeUndefined(); + const event = seen.pop(); + expect(event).toEqual({ + name, + receiver: console, + args: ["%s", payload, 3], + }); + expect(event!.args[1]).toBe(payload); + expect(api.Console.prototype[name]).toBe(api[name]); + } + expect(api.default).toBe(console); + } finally { + for (const name of Reflect.ownKeys(console)) + if (!Object.hasOwn(descriptors, name)) + Reflect.deleteProperty(console, name); + Object.defineProperties(console, descriptors); + vi.resetModules(); + } +}); diff --git a/src/compat/crypto/coverage.spec.mjs b/src/compat/crypto/coverage.spec.mjs new file mode 100644 index 0000000..8737b8d --- /dev/null +++ b/src/compat/crypto/coverage.spec.mjs @@ -0,0 +1,370 @@ +// Shared operation-level comparisons. Every function is self-contained so the +// same source runs in pinned workerd and through the public/native package. +export const cryptoCoverageCases = { + cryptoSignatureCallbacks: async function ({ crypto: c }) { + const { privateKey, publicKey } = c.generateKeyPairSync("ed25519"); + const data = new Uint8Array([1, 2, 3]); + const signature = c.sign(null, data, privateKey); + const results = {}; + for (const name of [ + "sign", + "verifyTrue", + "verifyFalse", + "signDigest", + "verifyDigest", + "signData", + "verifySignature", + "missingKey", + ]) { + const order = [], + callbacks = []; + let settleCallback; + const settled = new Promise((resolve) => { + settleCallback = resolve; + }); + const error = (e) => ({ + name: e.name, + code: e.code ?? null, + message: e.message, + }); + const callback = (e, value) => { + settleCallback(); + order.push("callback"); + callbacks.push( + e + ? { error: error(e) } + : { + value: + typeof value === "boolean" + ? value + : c.verify(null, data, publicKey, value), + }, + ); + }; + let returned, thrown; + try { + if (name === "sign") + returned = c.sign(null, data, privateKey, callback); + if (name === "verifyTrue") + returned = c.verify(null, data, publicKey, signature, callback); + if (name === "verifyFalse") + returned = c.verify( + null, + new Uint8Array([4]), + publicKey, + signature, + callback, + ); + if (name === "signDigest") + returned = c.sign("not-a-digest", data, privateKey, callback); + if (name === "verifyDigest") + returned = c.verify( + "not-a-digest", + data, + publicKey, + signature, + callback, + ); + if (name === "signData") + returned = c.sign(null, {}, privateKey, callback); + if (name === "verifySignature") + returned = c.verify(null, data, publicKey, {}, callback); + if (name === "missingKey") + returned = c.sign(null, data, undefined, callback); + } catch (e) { + thrown = error(e); + order.push("throw"); + } + order.push("returned"); + queueMicrotask(() => order.push("microtask")); + if (!thrown && name !== "nullOverload") { + let timer; + try { + await Promise.race([ + settled, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error("callback did not settle: " + name)), + 2000, + ); + }), + ]); + } finally { + clearTimeout(timer); + } + } + // Observe duplicates through the next task; this is a bounded scheduling check. + await new Promise((resolve) => setTimeout(resolve, 0)); + results[name] = { + order, + callbacks, + returnedUndefined: returned === undefined, + thrown: thrown ?? null, + }; + } + return results; + }, + cryptoEcdhInputCoverage: function ({ crypto: c }) { + const left = c.createECDH("prime256v1"), + right = c.createECDH("prime256v1"); + left.setPrivateKey(new Uint8Array([1])); + right.setPrivateKey(new Uint8Array([2])); + const peer = right.getPublicKey(), + results = {}; + const attempt = (fn) => { + try { + return { value: fn() }; + } catch (e) { + return { + error: { name: e.name, code: e.code ?? null, message: e.message }, + }; + } + }; + const hex = (view) => + Array.from(view, (x) => x.toString(16).padStart(2, "0")).join(""); + for (const operation of ["setPrivateKey", "computeSecret", "convertKey"]) { + const bytes = operation === "setPrivateKey" ? new Uint8Array([2]) : peer; + const invoke = (input) => { + if (operation === "setPrivateKey") { + left.setPrivateKey(input); + return hex(left.getPublicKey()); + } + if (operation === "computeSecret") + return hex(left.computeSecret(input)); + return hex(c.ECDH.convertKey(input, "prime256v1")); + }; + for (const kind of ["typed", "dataView"]) + for (const shadow of [ + "none", + "buffer", + "byteOffset", + "byteLength", + "detached", + ]) { + left.setPrivateKey(new Uint8Array([1])); + const backing = new Uint8Array(bytes.length + 4); + backing.set(bytes, 2); + const view = + kind === "typed" + ? new Uint8Array(backing.buffer, 2, bytes.length) + : new DataView(backing.buffer, 2, bytes.length); + let reads = 0; + if (!["none", "detached"].includes(shadow)) + Object.defineProperty(view, shadow, { + get() { + reads++; + throw new Error("shadow " + shadow); + }, + }); + if (shadow === "detached") + structuredClone(backing.buffer, { transfer: [backing.buffer] }); + const result = attempt(() => invoke(view)); + results[`${operation}/${kind}/${shadow}`] = { + ...result, + reads, + state: hex(left.getPublicKey()), + }; + } + left.setPrivateKey(new Uint8Array([1])); + results[operation + "/arrayBuffer"] = attempt(() => + invoke(Uint8Array.from(bytes).buffer), + ); + } + for (const invalid of [new Uint8Array([0]), new Uint8Array(32).fill(255)]) { + left.setPrivateKey(new Uint8Array([1])); + results["failedSet/" + hex(invalid)] = { + result: attempt(() => left.setPrivateKey(invalid) && true), + privateKey: hex(left.getPrivateKey()), + publicKey: hex(left.getPublicKey()), + secret: hex(left.computeSecret(peer)), + }; + } + return results; + }, + cryptoRandomCallbackCoverage: async function ({ crypto: c }) { + const results = {}; + for (const name of [ + "negative", + "maxOnly", + "invalidRange", + "tooWide", + "nullOverload", + ]) { + const order = [], + callbacks = []; + let settleCallback; + const settled = new Promise((resolve) => { + settleCallback = resolve; + }); + const error = (e) => ({ + name: e.name, + code: e.code ?? null, + message: e.message, + }); + const callback = (e, value) => { + settleCallback(); + order.push("callback"); + callbacks.push(e ? { error: error(e) } : { value }); + }; + let returned, thrown; + try { + if (name === "negative") returned = c.randomInt(-1, 0, callback); + if (name === "maxOnly") returned = c.randomInt(1, callback); + if (name === "invalidRange") returned = c.randomInt(1, 1, callback); + if (name === "tooWide") returned = c.randomInt(0, 2 ** 48, callback); + if (name === "nullOverload") returned = c.randomInt(1, null); + } catch (e) { + thrown = error(e); + order.push("throw"); + } + order.push("returned"); + queueMicrotask(() => order.push("microtask")); + if (!thrown && name !== "nullOverload") { + let timer; + try { + await Promise.race([ + settled, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error("callback did not settle: " + name)), + 2000, + ); + }), + ]); + } finally { + clearTimeout(timer); + } + } + // Observe duplicates through the next task; this is a bounded scheduling check. + await new Promise((resolve) => setTimeout(resolve, 0)); + results[name] = { + order, + callbacks, + returnedUndefined: returned === undefined, + thrown: thrown ?? null, + }; + } + const uuid = []; + for (const kind of [ + "undefined", + "empty", + "true", + "false", + "null", + "invalid", + "getter", + "throwingGetter", + ]) { + let reads = 0; + const options = + kind === "undefined" + ? undefined + : kind === "null" + ? null + : kind === "empty" + ? {} + : { + get disableEntropyCache() { + reads++; + if (kind === "throwingGetter") + throw new Error("uuid getter"); + return kind === "invalid" ? 1 : kind !== "false"; + }, + }; + let result; + try { + const value = c.randomUUID(options); + result = { + valid: + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test( + value, + ), + }; + } catch (e) { + result = { + error: { name: e.name, code: e.code ?? null, message: e.message }, + }; + } + uuid.push({ kind, reads, ...result }); + } + return { results, uuid }; + }, + cryptoSecretKeyCallbackCoverage: async function ({ crypto: c }) { + const results = {}; + for (const [name, type, options] of [ + ["type", "bad", { length: 9 }], + ["hmacZero", "hmac", { length: 0 }], + ["aesLength", "aes", { length: 129 }], + ["null", "hmac", null], + ["valid", "hmac", { length: 9 }], + ]) { + const order = [], + callbacks = []; + let settleCallback; + const settled = new Promise((resolve) => { + settleCallback = resolve; + }); + const error = (e) => ({ + name: e.name, + code: e.code ?? null, + message: e.message, + }); + let thrown, returned; + try { + returned = c.generateKey(type, options, (e, key) => { + settleCallback(); + order.push("callback"); + callbacks.push( + e + ? { error: error(e) } + : { type: key.type, bytes: key.export().length }, + ); + }); + } catch (e) { + thrown = error(e); + order.push("throw"); + } + order.push("returned"); + queueMicrotask(() => order.push("microtask")); + if (!thrown && name !== "nullOverload") { + let timer; + try { + await Promise.race([ + settled, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error("callback did not settle: " + name)), + 2000, + ); + }), + ]); + } finally { + clearTimeout(timer); + } + } + // Observe duplicates through the next task; this is a bounded scheduling check. + await new Promise((resolve) => setTimeout(resolve, 0)); + results[name] = { + order, + callbacks, + returnedUndefined: returned === undefined, + thrown: thrown ?? null, + }; + } + let reads = 0; + try { + const key = c.generateKeySync("hmac", { + get length() { + return ++reads === 1 ? 9 : 16; + }, + }); + results.getter = { reads, bytes: key.export().length }; + } catch (e) { + results.getter = { + reads, + error: { name: e.name, code: e.code ?? null, message: e.message }, + }; + } + return results; + }, +}; diff --git a/src/compat/crypto/keys.ts b/src/compat/crypto/keys.ts index 53662bc..7addb10 100644 --- a/src/compat/crypto/keys.ts +++ b/src/compat/crypto/keys.ts @@ -315,10 +315,10 @@ export function generateKeySync( ): SecretKeyObject { validateOneOf(type, "type", ["hmac", "aes"]); validateObject(options, "options"); - if (type === "hmac") - validateInteger(options.length, "options.length", 8, 65536); - else validateOneOf(options.length, "options.length", [128, 192, 256]); - const material = new Uint8Array(Math.floor(options.length / 8)); + const { length } = options; + if (type === "hmac") validateInteger(length, "options.length", 8, 65536); + else validateOneOf(length, "options.length", [128, 192, 256]); + const material = new Uint8Array(Math.floor(length / 8)); globalThis.crypto.getRandomValues(material); return createSecretKey(material); } diff --git a/src/compat/crypto/native-crypto.ts b/src/compat/crypto/native-crypto.ts index 1b0a09f..ac447a3 100644 --- a/src/compat/crypto/native-crypto.ts +++ b/src/compat/crypto/native-crypto.ts @@ -1,5 +1,6 @@ import binary from "./native-crypto.wasm"; import { aliases } from "./digests.js"; +import { viewBytes } from "../../shared/buffer-source.js"; type API = Record any> & { memory: WebAssembly.Memory; }; @@ -490,12 +491,14 @@ export class NativeECDH { return result(api); } setPrivateKey(data: Uint8Array) { + data = viewBytes(data); inputs([data], (api, [p]) => { if (!api.wk_ec_set_private(this.pointer, p, data.byteLength)) throw new Error("Private key is not valid for specified curve."); }); } computeSecret(data: Uint8Array) { + data = viewBytes(data); return inputs([data], (api, [p]) => { const status = api.wk_ec_secret(this.pointer, p, data.byteLength); if (status !== 1) @@ -510,6 +513,7 @@ export class NativeECDH { }); } static convertKey(data: Uint8Array, curve: string, format: string) { + data = viewBytes(data); if (!data.byteLength) return new Uint8Array(); const key = new NativeECDH(curve); try { diff --git a/src/compat/diagnostics-channel/coverage.spec.mjs b/src/compat/diagnostics-channel/coverage.spec.mjs new file mode 100644 index 0000000..e9a5dce --- /dev/null +++ b/src/compat/diagnostics-channel/coverage.spec.mjs @@ -0,0 +1,82 @@ +export const diagnosticsCoverageCases = { + diagnosticsCallbackCoverage: async function () { + const d = await import("node:diagnostics_channel"), + { AsyncLocalStorage } = await import("node:async_hooks"), + out = {}; + for (const mode of ["error", "throw", "callbackThrow", "async"]) { + const channel = d.tracingChannel("coverage-" + mode), + context = {}, + marker = Error(mode), + store = new AsyncLocalStorage(), + receiver = {}, + events = []; + const subscriptions = Object.fromEntries( + ["start", "end", "error", "asyncStart", "asyncEnd"].map((name) => [ + name, + () => events.push(name), + ]), + ); + channel.subscribe(subscriptions); + channel.asyncStart.bindStore(store, () => marker); + let timer, settle; + const settled = new Promise((resolve) => { + settle = resolve; + }); + try { + let thrown, result, callback; + try { + result = channel.traceCallback( + (cb) => { + if (mode === "throw") throw marker; + if (mode === "async") + queueMicrotask(() => cb.call(receiver, null, 4)); + else cb.call(receiver, mode === "error" ? marker : null, 4); + return 8; + }, + 0, + context, + null, + function (error, value) { + callback = { + receiver: this === receiver, + store: store.getStore() === marker, + error: error === marker, + value, + }; + events.push("callback"); + settle(); + if (mode === "callbackThrow") throw marker; + }, + ); + } catch (e) { + thrown = e; + } + const immediate = events.slice(); + if (mode === "async") + await Promise.race([ + settled, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(Error("trace callback did not settle")), + 2000, + ); + }), + ]); + out[mode] = { + immediate, + events, + result: result ?? null, + thrown: thrown === marker, + contextError: context.error === marker, + contextResult: context.result ?? null, + callback: callback ?? null, + }; + } finally { + clearTimeout(timer); + channel.asyncStart.unbindStore(store); + channel.unsubscribe(subscriptions); + } + } + return out; + }, +}; diff --git a/src/compat/dns/coverage.spec.mjs b/src/compat/dns/coverage.spec.mjs new file mode 100644 index 0000000..f5b774e --- /dev/null +++ b/src/compat/dns/coverage.spec.mjs @@ -0,0 +1,58 @@ +export const dnsCoverageCases = { + dnsCallbackFailureCoverage: async function () { + const dns = await import("node:dns"), + out = {}, + original = globalThis.fetch; + try { + for (const mode of ["http", "network", "missing"]) + for (const route of ["module", "resolver"]) { + globalThis.fetch = async () => { + if (mode === "network") throw Error("network"); + if (mode === "http") return new Response("", { status: 500 }); + return Response.json({ Question: [{}] }); + }; + const api = route === "module" ? dns : new dns.Resolver(), + order = [], + calls = []; + let timer, returned; + try { + await new Promise((resolve, reject) => { + timer = setTimeout( + () => reject(Error("DNS callback did not settle")), + 2000, + ); + returned = api.resolve4("fixture.test", (error, value) => { + order.push("callback"); + calls.push({ + error: error + ? { + name: error.name, + code: error.code ?? null, + message: error.message, + hostname: error.hostname, + syscall: error.syscall, + errno: error.errno ?? null, + } + : null, + valuePresent: value !== undefined, + }); + resolve(); + }); + order.push("returned"); + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + out[mode + "/" + route] = { + order, + calls, + returnedUndefined: returned === undefined, + }; + } finally { + clearTimeout(timer); + } + } + } finally { + globalThis.fetch = original; + } + return out; + }, +}; diff --git a/src/compat/expansion/index.spec.mjs b/src/compat/expansion/index.spec.mjs index ee0e8f6..9b495ab 100644 --- a/src/compat/expansion/index.spec.mjs +++ b/src/compat/expansion/index.spec.mjs @@ -1,4 +1,18 @@ +import { cryptoCoverageCases } from "../crypto/coverage.spec.mjs"; +import { fsCoverageCases } from "../fs/coverage.spec.mjs"; +import { zlibCoverageCases } from "../zlib/coverage.spec.mjs"; +import { utilCoverageCases } from "../util/coverage.spec.mjs"; +import { httpCoverageCases } from "../http/coverage.spec.mjs"; +import { dnsCoverageCases } from "../dns/coverage.spec.mjs"; +import { diagnosticsCoverageCases } from "../diagnostics-channel/coverage.spec.mjs"; export const eventCases = { + ...cryptoCoverageCases, + ...fsCoverageCases, + ...zlibCoverageCases, + ...utilCoverageCases, + ...httpCoverageCases, + ...dnsCoverageCases, + ...diagnosticsCoverageCases, httpEndBodyStates: async function ({ http: h, cloudflareNode: n }) { const out = {}; for (const [id, chunk] of [ @@ -7160,6 +7174,7 @@ export const eventCases = { "_debug", "_findPath", "_initPaths", + "_preloadModules", "_load", "_resolveFilename", "_resolveLookupPaths", diff --git a/src/compat/fs/coverage.spec.mjs b/src/compat/fs/coverage.spec.mjs new file mode 100644 index 0000000..b3870dc --- /dev/null +++ b/src/compat/fs/coverage.spec.mjs @@ -0,0 +1,357 @@ +// Functions are serialized into the same Workers and public-package runners. +export const fsCoverageCases = { + fsExportCoverage: async function ({ fs }) { + const out = {}; + for (const [name, fn] of [ + ["DirMissing", () => new fs.Dir()], + [ + "DirEmpty", + () => { + const dir = new fs.Dir([], "/tmp", {}); + try { + return { path: dir.path, empty: dir.readSync() === null }; + } finally { + dir.closeSync(); + } + }, + ], + [ + "Stats", + () => { + const stat = new fs.Stats(); + return Object.fromEntries( + [ + "isFile", + "isDirectory", + "isSymbolicLink", + "isBlockDevice", + "isCharacterDevice", + "isFIFO", + "isSocket", + ].map((name) => [name, stat[name]()]), + ); + }, + ], + ["StatsCall", () => fs.Stats()], + ["StatsPrototypeConstructor", () => new fs.Stats.prototype.constructor()], + [ + "StatsIdentity", + () => { + const path = "/tmp/stats-export-coverage"; + fs.writeFileSync(path, "abc"); + try { + const stat = fs.statSync(path); + let error; + try { + new stat.constructor(); + } catch (e) { + error = { + name: e.name, + code: e.code ?? null, + message: e.message, + }; + } + return { + prototypeConstructor: fs.Stats.prototype.constructor === fs.Stats, + constructor: stat.constructor === fs.Stats, + instance: stat instanceof fs.Stats, + prototype: Object.getPrototypeOf(stat) === fs.Stats.prototype, + error, + }; + } finally { + fs.unlinkSync(path); + } + }, + ], + ["watch", () => fs.promises.watch("/tmp")], + ]) { + try { + out[name] = { value: await fn() }; + } catch (e) { + out[name] = { + error: { name: e.name, code: e.code ?? null, message: e.message }, + }; + } + } + return out; + }, + fsReadOverloadCoverage: async function ({ fs }) { + const path = "/tmp/read-overload-coverage"; + fs.writeFileSync(path, "abcdef"); + const out = {}; + try { + for (const name of [ + "default", + "options", + "override", + "getters", + "invalid", + ]) { + const h = await fs.promises.open(path, "r"); + try { + const a = new Uint8Array(5), + b = new Uint8Array(5), + trace = []; + let phase = "call"; + try { + let pending; + if (name === "default") pending = h.read(); + if (name === "options") + pending = h.read({ + buffer: a, + offset: 1, + length: 2, + position: 0, + }); + if (name === "override") + pending = h.read(a, { + buffer: b, + offset: 1, + length: 2, + position: 0, + }); + if (name === "invalid") + pending = h.read({ buffer: a, offset: -1, position: -2 }); + if (name === "getters") + pending = h.read({ + get buffer() { + trace.push("buffer"); + return a; + }, + get offset() { + trace.push("offset"); + return 1; + }, + get length() { + trace.push("length"); + return 2; + }, + get position() { + trace.push("position"); + return 0; + }, + }); + phase = "await"; + const r = await pending; + out[name] = { + count: r.bytesRead, + length: r.buffer.length, + bytes: Array.from(r.buffer.subarray(0, 8)), + sameA: r.buffer === a, + sameB: r.buffer === b, + }; + } catch (e) { + out[name] = { + phase, + error: { name: e.name, code: e.code ?? null, message: e.message }, + }; + } + out[name] = { + ...out[name], + a: Array.from(a), + b: Array.from(b), + trace, + }; + } finally { + await h.close(); + } + } + } finally { + fs.unlinkSync(path); + } + return out; + }, + fsVectorCoverage: async function ({ fs }) { + const path = "/tmp/vector-coverage", + out = {}; + try { + for (const operation of ["readv", "writev"]) + for (const mode of ["sync", "callback", "handle"]) + for (const position of [null, 1]) + for (const kind of ["views", "shadow", "detached"]) { + fs.writeFileSync(path, "abcdef"); + const a = new Uint8Array([88, 65, 66, 88]), + b = new Uint8Array([88, 67, 68, 88]); + const view = a.subarray(1, 3); + const buffers = + kind === "views" + ? [view, new DataView(b.buffer, 1, 2), new Uint8Array()] + : [view]; + if (kind === "shadow") + Object.defineProperty(view, "byteLength", { value: 0 }); + if (kind === "detached") + structuredClone(a.buffer, { transfer: [a.buffer] }); + const h = + mode === "handle" ? await fs.promises.open(path, "r+") : null; + const fd = h ? h.fd : fs.openSync(path, "r+"); + try { + let result; + try { + if (mode === "sync") + result = { + count: fs[operation + "Sync"](fd, buffers, position), + }; + if (mode === "callback") + result = await new Promise((resolve) => + fs[operation]( + fd, + buffers, + position, + (e, count, returned) => + resolve( + e + ? { + error: { + name: e.name, + code: e.code ?? null, + message: e.message, + }, + } + : { count, same: returned === buffers }, + ), + ), + ); + if (mode === "handle") { + const r = await h[operation](buffers, position); + result = { + count: r.bytesRead ?? r.bytesWritten, + same: r.buffers === buffers, + }; + } + } catch (e) { + result = { + error: { + name: e.name, + code: e.code ?? null, + message: e.message, + }, + }; + } + const next = new Uint8Array(1); + const count = fs.readSync(fd, next, 0, 1, null); + out[[operation, mode, position, kind].join("/")] = { + ...result, + a: a.buffer.byteLength ? Array.from(a) : [], + b: Array.from(b), + next: Array.from(next), + nextCount: count, + file: fs.readFileSync(path, "utf8"), + }; + } finally { + if (h) await h.close(); + else fs.closeSync(fd); + } + } + } finally { + fs.unlinkSync(path); + } + return out; + }, + fsWebStreamCoverage: async function ({ fs }) { + const path = "/tmp/webstream-coverage", + out = {}; + fs.writeFileSync(path, "abcdef"); + const bounded = async (p) => { + let timer; + try { + return await Promise.race([ + p, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error("read did not settle")), + 2000, + ); + }), + ]); + } finally { + clearTimeout(timer); + } + }; + try { + for (const autoClose of [true, false]) + for (const action of ["eof", "cancel", "close"]) + for (const offset of [0, 2]) { + const row = autoClose + "/" + action + "/" + offset; + const h = await fs.promises.open(path, "r"); + let closes = 0; + h.on("close", () => closes++); + const reader = h + .readableWebStream({ autoClose }) + .getReader({ mode: "byob" }), + reads = []; + try { + const first = bounded( + reader.read(new Uint8Array(new ArrayBuffer(10), offset, 3)), + ); + first.catch(() => {}); + if (action === "close") await h.close(); + const capture = (r) => ({ + done: r.done, + bytes: Array.from(r.value ?? []), + offset: r.value?.byteOffset ?? null, + length: r.value?.byteLength ?? null, + }); + reads.push(capture(await bounded(first))); + if (action === "cancel") await reader.cancel("stop"); + if (action === "eof") + for (let i = 0; i < 8; i++) { + const r = await bounded(reader.read(new Uint8Array(3))); + reads.push(capture(r)); + if (r.done) break; + if (i === 7) throw new Error("EOF not reached"); + } + out[row] = { + reads, + closes, + open: typeof h.fd === "number", + }; + if (!autoClose && action !== "close") { + const r = await h.read(new Uint8Array(1)); + out[row].remaining = r.bytesRead; + out[row].size = (await h.stat()).size; + } + } catch (e) { + if ( + e.message === "read did not settle" || + e.message === "EOF not reached" + ) + throw new Error(row + ": " + e.message); + out[row] = { + reads, + closes, + open: typeof h.fd === "number", + error: { + name: e.name, + code: e.code ?? null, + message: e.message, + }, + }; + } finally { + const cleanup = []; + try { + reader.releaseLock(); + } catch (e) { + cleanup.push({ + name: e.name, + code: e.code ?? null, + message: e.message, + }); + } + try { + if (typeof h.fd === "number") await h.close(); + } catch (e) { + cleanup.push({ + name: e.name, + code: e.code ?? null, + message: e.message, + }); + } + if (out[row]) out[row].cleanup = cleanup; + } + } + } finally { + fs.unlinkSync(path); + } + return out; + }, +}; diff --git a/src/compat/fs/file-handle.ts b/src/compat/fs/file-handle.ts index 4e7aee5..e0bb08d 100644 --- a/src/compat/fs/file-handle.ts +++ b/src/compat/fs/file-handle.ts @@ -276,11 +276,18 @@ export class FileHandle extends EventEmitter { const handle = this; const read = this.read.bind(this); let controller: ReadableByteStreamController, - ended = false; + ended = false, + failed = false, + closingAtEof = false; const finish = () => { + if (failed) throw new TypeError("This ReadableStream is closed."); + if (ended && !closingAtEof) + throw new TypeError("This ReadableStream is closed."); if (!ended) { ended = true; + const request = controller.byobRequest; controller.close(); + request?.respond(0); } }; const stream = new ReadableStream({ @@ -292,16 +299,26 @@ export class FileHandle extends EventEmitter { async pull(c) { const request = c.byobRequest!, view = request.view!; - const { bytesRead } = await read( - view, - view.byteOffset, - view.byteLength, - ); + let bytesRead: number; + try { + ({ bytesRead } = await read(view, view.byteOffset, view.byteLength)); + } catch (error) { + failed = true; + throw error; + } + if (ended) return; if (bytesRead === 0) { finish(); - if (autoClose) await handle.close(); + if (autoClose) { + closingAtEof = true; + try { + await handle.close(); + } finally { + closingAtEof = false; + } + } } - request.respond(bytesRead); + if (!ended) request.respond(bytesRead); }, async cancel() { ended = true; diff --git a/src/compat/fs/index.ts b/src/compat/fs/index.ts index 20e62a6..0c64b98 100644 --- a/src/compat/fs/index.ts +++ b/src/compat/fs/index.ts @@ -43,6 +43,22 @@ const reads = new Set([ "existsSync", ]); const api: any = { ...temporary }; +// Stats values are produced by the filesystem; Workers forbids public construction. +api.Stats = new Proxy(api.Stats, { + construct() { + throw new TypeError("Illegal constructor"); + }, + apply() { + throw new TypeError( + "Class constructor Stats cannot be invoked without 'new'", + ); + }, +}); +Object.defineProperty(api.Stats.prototype, "constructor", { + value: api.Stats, + configurable: true, + writable: true, +}); for (const name of Object.keys(api)) if (typeof api[name] === "function" && /^[a-z]/.test(name)) api[name] = (...args: any[]) => temporary[name](...args); diff --git a/src/compat/fs/io.ts b/src/compat/fs/io.ts index a0e175b..8a0afe6 100644 --- a/src/compat/fs/io.ts +++ b/src/compat/fs/io.ts @@ -181,11 +181,12 @@ export function installIo(api: any, promises: any) { (fd: number, buffers: any[], position: any) => { let count = 0; for (const buffer of buffers) { + const bytes = viewBytes(buffer); const size = api[name === "readv" ? "readSync" : "writeSync"]( fd, - buffer, + bytes, 0, - buffer.byteLength, + bytes.byteLength, position === null ? null : Number(position) + count, ); count += size; diff --git a/src/compat/http/coverage.spec.mjs b/src/compat/http/coverage.spec.mjs new file mode 100644 index 0000000..72da272 --- /dev/null +++ b/src/compat/http/coverage.spec.mjs @@ -0,0 +1,31 @@ +export const httpCoverageCases = { + httpHeaderValidatorCoverage: function ({ http, httpOutgoing }) { + const out = { + identity: [ + http.validateHeaderName === httpOutgoing.validateHeaderName, + http.validateHeaderValue === httpOutgoing.validateHeaderValue, + ], + }; + for (const name of ["validateHeaderName", "validateHeaderValue"]) + for (const [index, args] of (name === "validateHeaderName" + ? [["x-test"], [""], ["x\n"], [null], [42]] + : [ + ["x-test", "ok"], + ["x-test", undefined], + ["x-test", "a\nb"], + ["x-test", 3], + ["x-test", null], + ] + ).entries()) { + const id = name + "/" + index; + try { + out[id] = { returnedUndefined: http[name](...args) === undefined }; + } catch (e) { + out[id] = { + error: { name: e.name, code: e.code ?? null, message: e.message }, + }; + } + } + return out; + }, +}; diff --git a/src/compat/util/coverage.spec.mjs b/src/compat/util/coverage.spec.mjs new file mode 100644 index 0000000..069ac79 --- /dev/null +++ b/src/compat/util/coverage.spec.mjs @@ -0,0 +1,108 @@ +export const utilCoverageCases = { + utilPredicateCoverage: function ({ util, types }) { + const values = { + undefined: undefined, + null: null, + boolean: true, + number: 3, + string: "s", + symbol: Symbol("s"), + bigint: 3n, + array: [], + object: {}, + fn: () => {}, + date: new Date(0), + regexp: /x/, + error: new Error("x"), + map: new Map(), + set: new Set(), + weakMap: new WeakMap(), + weakSet: new WeakSet(), + arrayBuffer: new ArrayBuffer(4), + dataView: new DataView(new ArrayBuffer(4)), + boxedNumber: Object(3), + boxedString: Object("s"), + boxedBoolean: Object(true), + boxedBigint: Object(3n), + boxedSymbol: Object(Symbol("s")), + }; + for (const name of [ + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "Int8Array", + "Int16Array", + "Int32Array", + "Float32Array", + "Float64Array", + "BigInt64Array", + "BigUint64Array", + ]) + values[name] = new globalThis[name](2); + const out = {}; + for (const [api, names] of [ + [ + util, + [ + "isArray", + "isBoolean", + "isBuffer", + "isFunction", + "isNull", + "isNumber", + "isRegExp", + "isString", + "isSymbol", + "isUndefined", + "isPrimitive", + "isObject", + "isNullOrUndefined", + "isError", + ], + ], + [ + types, + [ + "isDate", + "isRegExp", + "isNativeError", + "isTypedArray", + "isArrayBufferView", + "isUint8Array", + "isUint8ClampedArray", + "isUint16Array", + "isUint32Array", + "isInt8Array", + "isInt16Array", + "isInt32Array", + "isFloat32Array", + "isFloat64Array", + "isBigInt64Array", + "isBigUint64Array", + "isMap", + "isSet", + "isWeakMap", + "isWeakSet", + "isArrayBuffer", + "isDataView", + "isNumberObject", + "isStringObject", + "isBooleanObject", + "isBigIntObject", + "isSymbolObject", + "isBoxedPrimitive", + "isAnyArrayBuffer", + ], + ], + ]) + for (const name of names) + out[(api === util ? "util/" : "types/") + name] = Object.fromEntries( + Object.entries(values).map(([kind, value]) => [ + kind, + api[name](value), + ]), + ); + return out; + }, +}; diff --git a/src/compat/zlib/coverage.spec.mjs b/src/compat/zlib/coverage.spec.mjs new file mode 100644 index 0000000..c077086 --- /dev/null +++ b/src/compat/zlib/coverage.spec.mjs @@ -0,0 +1,283 @@ +// Shared pinned-Workers comparisons; functions must remain self-contained. +export const zlibCoverageCases = { + zlibFactoryCoverage: async function ({ zlib: z }) { + const out = { + constants: z.constants, + codes: z.codes, + numericExports: Object.fromEntries( + Object.entries(z).filter(([, value]) => typeof value === "number"), + ), + }; + for (const name of [ + "Deflate", + "DeflateRaw", + "Gzip", + "Inflate", + "InflateRaw", + "Gunzip", + "Unzip", + "BrotliCompress", + "BrotliDecompress", + "ZstdCompress", + "ZstdDecompress", + ]) { + const stream = z["create" + name](); + try { + out[name] = { + instance: stream instanceof z[name], + readable: stream.readable, + writable: stream.writable, + bytesWritten: stream.bytesWritten, + }; + } finally { + stream.destroy(); + } + } + return out; + }, + zlibOutputLimitCoverage: async function ({ zlib: z }) { + const input = Uint8Array.from({ length: 65 }, (_, i) => i), + out = {}; + for (const [encode, decode] of [ + ["gzip", "gunzip"], + ["deflate", "inflate"], + ["deflateRaw", "inflateRaw"], + ["gzip", "unzip"], + ["brotliCompress", "brotliDecompress"], + ["zstdCompress", "zstdDecompress"], + ]) { + const packed = z[encode + "Sync"](input); + for (const limit of [64, 65, 66]) + for (const mode of ["sync", "info", "callback", "callbackInfo"]) { + const options = { + maxOutputLength: limit, + chunkSize: 64, + info: mode === "info" || mode === "callbackInfo", + }; + const capture = (value) => + options.info + ? { + bytes: Array.from(value.buffer), + closed: value.engine._closed, + } + : { bytes: Array.from(value) }; + let result, + calls = 0; + try { + if (mode.startsWith("callback")) { + result = await new Promise((resolve) => + z[decode](packed, options, (e, value) => { + calls++; + resolve( + e + ? { + error: { name: e.name, code: e.code ?? null }, + valuePresent: value !== undefined, + } + : capture(value), + ); + }), + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + } else result = capture(z[decode + "Sync"](packed, options)); + } catch (e) { + result = { error: { name: e.name, code: e.code ?? null } }; + } + out[[decode, limit, mode].join("/")] = { + ...result, + calls, + recovered: Array.from(z[decode + "Sync"](packed)), + }; + } + } + return out; + }, + zlibStrategyCoverage: async function ({ zlib: z }) { + const out = {}; + for (const name of ["Deflate", "DeflateRaw"]) { + const stream = new z[name]({ chunkSize: 64 }), + chunks = [], + order = []; + const done = new Promise((resolve, reject) => { + stream.on("data", (c) => chunks.push(c)); + stream.on("error", reject); + stream.on("end", resolve); + }); + done.catch(() => {}); + const callbackErrors = []; + try { + const a = Uint8Array.from( + { length: 4096 }, + (_, i) => (i * i + Math.floor(i / 37)) % 256, + ), + b = new Uint8Array(2048).fill(65), + c = Uint8Array.from({ length: 1024 }, (_, i) => i % 17); + stream.write(a, (e) => { + order.push("writeA"); + if (e) callbackErrors.push({ name: e.name, code: e.code ?? null }); + }); + await new Promise((resolve, reject) => + stream.params(1, z.constants.Z_HUFFMAN_ONLY, (e) => { + order.push("paramsA"); + e ? reject(e) : resolve(); + }), + ); + stream.write(b, (e) => { + order.push("writeB"); + if (e) callbackErrors.push({ name: e.name, code: e.code ?? null }); + }); + await new Promise((resolve, reject) => + stream.params(9, z.constants.Z_RLE, (e) => { + order.push("paramsB"); + e ? reject(e) : resolve(); + }), + ); + let invalid; + try { + stream.params(1, -1, () => order.push("invalidCallback")); + } catch (e) { + invalid = { name: e.name, code: e.code ?? null }; + } + stream.end(c, (e) => { + order.push("endCallback"); + if (e) callbackErrors.push({ name: e.name, code: e.code ?? null }); + }); + await done; + const packed = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); + let offset = 0; + for (const chunk of chunks) { + packed.set(chunk, offset); + offset += chunk.length; + } + const decoded = + z[name === "Deflate" ? "inflateSync" : "inflateRawSync"](packed); + const expected = [...a, ...b, ...c]; + out[name] = { + order, + callbackErrors, + invalid, + bytesWritten: stream.bytesWritten, + length: decoded.length, + equal: + decoded.length === expected.length && + Array.from(decoded).every((v, i) => v === expected[i]), + }; + } finally { + stream.destroy(); + } + } + return out; + }, + zlibResetCoverage: async function ({ zlib: z }) { + const out = {}, + dictionary = new TextEncoder().encode("shared dictionary repeated words"); + for (const [encode, decode, options, flush] of [ + ["Deflate", "Inflate", { dictionary }, z.constants.Z_FINISH], + [ + "BrotliCompress", + "BrotliDecompress", + { params: { [z.constants.BROTLI_PARAM_QUALITY]: 2 } }, + z.constants.BROTLI_OPERATION_FINISH, + ], + [ + "ZstdCompress", + "ZstdDecompress", + { params: { [z.constants.ZSTD_c_compressionLevel]: 2 } }, + z.constants.ZSTD_e_end, + ], + ]) { + const input = new TextEncoder().encode( + "shared dictionary repeated words + payload", + ); + for (const direction of ["encode", "decode", "partial"]) { + const name = direction === "encode" ? encode : decode; + const opts = + direction === "encode" || decode === "Inflate" ? options : {}; + const stream = new z[name](opts), + chunks = []; + let failure, + firstPhase, + phase = "firstWrite", + reachedReset = false; + stream.on("data", (chunk) => chunks.push(chunk)); + stream.on("error", (e) => { + failure = e; + }); + const write = (bytes) => + new Promise((resolve, reject) => + stream.write(bytes, (e) => (e ? reject(e) : resolve())), + ); + const packed = z[encode[0].toLowerCase() + encode.slice(1) + "Sync"]( + input, + options, + ); + const collect = () => { + const all = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); + let offset = 0; + for (const c of chunks) { + all.set(c, offset); + offset += c.length; + } + return all; + }; + try { + await write( + direction === "encode" + ? input + : direction === "partial" + ? packed.subarray(0, 2) + : packed, + ); + if (direction === "encode") + await new Promise((resolve, reject) => + stream.flush(flush, (e) => (e ? reject(e) : resolve())), + ); + firstPhase = Array.from( + direction === "encode" + ? z[decode[0].toLowerCase() + decode.slice(1) + "Sync"]( + collect(), + decode === "Inflate" ? options : {}, + ) + : collect(), + ); + phase = "reset"; + stream.reset(); + reachedReset = true; + phase = "secondWrite"; + chunks.length = 0; + await new Promise((resolve, reject) => { + stream.once("end", resolve); + stream.once("error", reject); + stream.end(direction === "encode" ? input : packed); + }); + const bytes = + direction === "encode" + ? z[decode[0].toLowerCase() + decode.slice(1) + "Sync"]( + collect(), + decode === "Inflate" ? options : {}, + ) + : collect(); + out[name + "/" + direction] = { + firstPhase, + reachedReset, + bytes: Array.from(bytes), + bytesWritten: stream.bytesWritten, + error: failure + ? { name: failure.name, code: failure.code ?? null } + : null, + }; + } catch (e) { + out[name + "/" + direction] = { + phase, + reachedReset, + firstPhase, + error: { name: e.name, code: e.code ?? null, message: e.message }, + }; + } finally { + stream.destroy(); + } + } + } + return out; + }, +}; diff --git a/vitest.config.ts b/vitest.config.ts index ee8bd7b..eb7b4a7 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -57,6 +57,7 @@ export default defineConfig({ "src/shared/globals/web.spec.ts", "src/browser/abort/installation.spec.ts", "src/compat/buffer/installation.spec.ts", + "src/compat/console/forwarding.spec.ts", "src/compat/timers/installation.spec.ts", "src/compat/url/installation.spec.ts", "src/compat/url/interop.spec.ts", From b84ffcdf472bb66f65547cdbd326c5b744fa8ce6 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 26 Oct 2026 17:54:52 +0900 Subject: [PATCH 2/2] Define remote-first release acceptance and align 0.1.7 onboarding --- CONTRIBUTING.md | 58 +++++++++++++++++++++++------ README.md | 4 +- demo/tests/README.md | 23 ++++++++++++ docs/build-setup.md | 15 +++++++- docs/compatibility.md | 11 +++--- docs/integration.md | 8 ++-- docs/native-embedding.md | 40 +++++++++----------- tests/unit/execution-policy.test.ts | 27 ++++++++++++++ tests/unit/remote-worker.test.ts | 15 ++++++++ 9 files changed, 155 insertions(+), 46 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0e0e20d..6f23558 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,14 +6,49 @@ Run `npm run format` from the repository root before submitting changes. `npm ru ## Complete compatibility units only -New compatibility implementations must be completed before merge or release unless an explicitly authorized release exception applies. A useful subset, a working framework demo, or passing tests for selected methods does not establish whole-module completion. Release exceptions cover [the current PR #72 candidate](#pr-72-scoped-release-exception) and existing implementations in [0.1.0 Preview and its explicitly authorized 0.1.1, 0.1.2, 0.1.3 and 0.1.4 follow-ups](#010-preview-exception). +Product release readiness follows the remote-first application gate below. +Whole-module completion remains a separate claim: a working application or selected +method tests must never promote an incomplete module to **Complete**. -For Node.js compatibility, the acceptance unit is a module, including its Workers +For Node.js compatibility, the completion unit is a module, including its Workers exports, subpaths and observable behavior. For a binding or Web API, define the -named API unit before implementation. Do not redefine the unit around the methods -that happen to work. Large units may be developed in several commits or draft PRs, -but incomplete implementation PRs must not be merged into main unless covered by -an explicitly authorized release exception. +named API unit before implementation. Do not redefine it around methods that work. + +## Remote-first application release gate + +The primary supported workflow builds an existing Workers application into a +mobile app while executing server requests on its deployed Worker. The maintainer +has authorized this release policy starting with 0.1.7. Existing incomplete local +compatibility implementations may ship with their **In progress**, **Unverified** +or **Not implemented** status retained. Full Node parity is not a product release +prerequisite. Historical version exceptions below describe earlier releases. + +A release requires all of the following: + +- The declared framework profiles build through public Vite/esbuild tooling and + an independently installed npm tarball. Remote-only server dependencies and + secrets stay outside client bundles and source maps; the Cloudflare build is + preserved. +- Remote selection happens before application execution. Unknown or unsupported + server graphs may remain wholly remote. Never retry a failed local mutation on + the server, or silently queue/retry a remote mutation after a transport failure. +- Required application scenarios pass on iOS simulator and Android emulator, + covering the applicable navigation/forms, remote data assertions, sessions, + streaming, cancellation and lifecycle contracts. Physical devices are not a + release prerequisite. State the tested versions and host-specific boundaries. +- The candidate passes existing regression, public types/imports, package, + native embedding and required CI checks. Known failures in required scenarios + must be fixed, not renamed as unfinished work. Evidence must match the candidate. +- Manager and independent acceptance reviews have no required changes. Record + evidence in the PR/generated artifacts. Documentation provides matching npm, + SwiftPM and Maven dependencies, reproduction commands and known exclusions. +- Client initialization failures cannot be repaired by server dispatch. Keep + Better Auth origin restrictions, WebAuthn and unsupported HTTP upgrades visible; + no universal authentication, arbitrary framework-version or offline guarantee. + +Use [build setup](docs/build-setup.md), [framework limits](docs/compatibility.md) +and [native dependency setup](docs/native-embedding.md#dependency-setup) to define +supported profiles. API completion work continues independently of releases. The target is Cloudflare Workers, not every API available in a Node.js process. Pin the workerd version, compatibility date and flags. An operation unsupported @@ -35,7 +70,7 @@ CORS, headers, cookies, redirects, streaming and cancellation must not be exclud ## Acceptance gate -A compatibility implementation is ready to merge only when all of these are true: +A compatibility unit may be marked **Complete** only when all of these are true: - The baseline's exports, subpaths, signatures and relevant prototype methods have been inventoried, with no unresolved coverage decisions. @@ -64,11 +99,10 @@ Only then may the inventory say **Complete**. Until then, use **In progress**, ## Work in progress -Except for an explicitly authorized release exception, keep incomplete compatibility work on a development branch or draft PR. Do not -activate it in a merged build alias, public export or default runtime path, and do -not ship it behind an experimental flag as a substitute for finishing it. Design -notes and reproducible experiments can be reviewed independently without adding -unfinished production behavior. +Keep unfinished new API work on a development branch or draft PR until its +claimed scenarios satisfy the release gate. Existing incomplete compatibility may +ship under the remote-first policy, with its limitations retained. An experimental +flag or successful namespace import does not establish behavioral completion. ### PR #72 scoped release exception diff --git a/README.md b/README.md index 9400e4a..8b0af41 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ Install the package in your web project, then follow the [complete mobile setup](docs/integration.md#workflow): ```sh -npm install --save-exact cf-workers-native@0.1.5 +npm install --save-exact cf-workers-native@0.1.7 ``` Installation alone does not generate a mobile project. The guide covers adding @@ -84,7 +84,7 @@ Open your application repository and give your assistant this prompt: ```text Read https://github.com/rdlabo-dev/cf-workers-native/blob/main/docs/integration.md. -Add an iOS and Android version of this Workers web app using cf-workers-native@0.1.5 +Add an iOS and Android version of this Workers web app using cf-workers-native@0.1.7 and Capacitor. Preserve the existing pages, backend and Cloudflare deployment configuration. Use an existing test Worker for cloud-backed requests; ask before any cloud deployment. Start by verifying one page, navigation and a form or data action on a simulator/emulator. diff --git a/demo/tests/README.md b/demo/tests/README.md index dd1176a..ef649b0 100644 --- a/demo/tests/README.md +++ b/demo/tests/README.md @@ -63,6 +63,29 @@ See their READMEs for commands, prerequisites and evidence limits. ## Capacitor native checks +### Remote-first release coverage + +The product gate is defined in [CONTRIBUTING](../../CONTRIBUTING.md#remote-first-application-release-gate). +Use these existing suites together; no single smoke test certifies an application +or whole-module Node compatibility. Commands below run from `demo/` unless noted. + +| Release contract | Verification entry | +| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| Server-only dependency exclusion; pre-execution selection; failed mutations are not replayed | Root `npm test` (`execution-policy`, `remote-worker`, binding/build suites) | +| Public package imports, types and independent Vite/esbuild consumer | Root `npm run typecheck` and `npm run test:package` | +| Hono / Workers Express builds and page behavior | `npm run test:browser`, `npm run test:build-tools`; packaged native rendering below on both platforms | +| Void React Pages hydration, navigation and D1 action | `npm run test:void`, `npm run test:void:routes`; [Void native fixture](void/native.test.mjs) | +| OpenNext public assets, remote protocol/session/form behavior and lifecycle | `npm run test:opennext`, `npm run test:opennext:split`; [OpenNext fixture](upstream/opennext/README.md) | +| D1/R2 backed application operations | [0bin](upstream/0bin/README.md), [FlareDrive](upstream/flaredrive/README.md), and binding suites | +| Native cookies, redirects, streaming, cancellation and restart | Packaged native rendering and native networking procedures below | +| Standalone iOS / Android installation and lifecycle | Native embedding workflow and independent consumers above | + +Record exact source/package revisions and platform results in generated artifacts +and the PR. Browser results do not replace native transport results. Local workerd +database assertions do not certify every deployed Cloudflare service. Keep upstream +authentication restrictions, passkeys, arbitrary version skew and unsupported +upgrade transport outside the supported profile until their own acceptance passes. + Prepare a test app in Capacitor's ordinary `dist/` directory, then sync and run: ```sh diff --git a/docs/build-setup.md b/docs/build-setup.md index 50a59cc..36f59bd 100644 --- a/docs/build-setup.md +++ b/docs/build-setup.md @@ -31,7 +31,7 @@ application's runtime import changes; Worker source and execution options are sh | Android | `workersAndroid` from `cf-workers-native/android` | [Existing Android app](native-embedding.md#android) | | Capacitor | `workersCapacitor` from `cf-workers-native/capacitor` | [Capacitor app](integration.md) | -Use `cf-workers-native@0.1.5` with matching +Use `cf-workers-native@0.1.7` with matching native dependencies; see [dependency setup](native-embedding.md#dependency-setup). Build the corresponding entry for each target, then package the entire output directory. Existing Capacitor examples below use `workersCapacitor`; the same @@ -39,6 +39,19 @@ options apply to `workersIOS` and `workersAndroid` in their SDK hosts. ## Frameworks +For the first mobile build, keep the default network execution and configure the +deployed Worker's HTTPS URL. Unsupported server APIs can stay on that Worker; +they do not need local polyfills. A client-side library that rejects the WebView +origin before sending a request still needs an integration change. Remote dispatch +does not repair that client initialization failure. + +Network execution requires connectivity. A failed mutation is reported to the +caller without automatic replay. Route selection happens before a local handler +runs; a local exception never causes the request to be retried remotely. If an +optional local route cannot be safely split, keep the whole Worker remote and +inspect the generated binding report. Explicit `execution: "local"` requires its +own supported API profile and does not opt into this fallback. + The following integrations have examples and verification evidence. Support is scoped to the execution paths described here; see the [compatibility limits](compatibility.md) for API and application restrictions. diff --git a/docs/compatibility.md b/docs/compatibility.md index 1668226..163a93b 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -5,14 +5,17 @@ profile uses workerd `1.20261012.1`, compatibility date `2026-10-17`, without additional flags. Other dates and flags are not covered by this profile. The WebView does not contain workerd or V8; iOS uses its own JavaScript engine. -The earlier `workers-capacitor` package releases 0.1.0 Preview and the explicitly authorized 0.1.1 Preview follow-up include existing compatibility implementations with the limits below under a [version-specific release exception](../CONTRIBUTING.md#010-preview-exception). The explicitly authorized `cf-workers-native@0.1.4` retains the documented limitations under its [release exception](../CONTRIBUTING.md#014-follow-up). Inclusion is not a claim of complete Workers or Node.js compatibility. +Releases use the [remote-first application gate](../CONTRIBUTING.md#remote-first-application-release-gate). +The default network policy keeps server implementation on the deployed Worker. +A verified mobile application does not establish complete Workers or Node.js +compatibility. Local API completion continues independently with the limits below. ## Native hosts | Host | Scope | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| iOS embedding | 0.1.5 `WorkersIOS` SwiftPM product for UIKit/SwiftUI. Close before removing a UIKit controller; SwiftUI dismantling closes automatically. | -| Android embedding | Maven Central SDK `io.github.rdlabo:cf-workers-native-android:0.1.2`. Requires WebView `MULTI_PROFILE`; one SDK screen at a time, with persistent SDK cookies isolated from host cookies. | +| iOS embedding | 0.1.7 `WorkersIOS` SwiftPM product for UIKit/SwiftUI. Close before removing a UIKit controller; SwiftUI dismantling closes automatically. | +| Android embedding | Maven Central SDK `io.github.rdlabo:cf-workers-native-android:0.1.7`. Requires WebView `MULTI_PROFILE`; one SDK screen at a time, with persistent SDK cookies isolated from host cookies. | | Capacitor | Existing Capacitor 8 integration, verified with 8.5.3; use this path for general native plugins. | The npm Preview uses the name `cf-workers-native`; use the exact version @@ -27,8 +30,6 @@ and [verification scope](native-embedding.md#verification) for host-specific evi Whole-Node compatibility is incomplete. Importing a module successfully does not establish equivalent methods, validation, state, scheduling or engine behavior. -The current PR #72 candidate is being validated for one release under an -[explicit scoped exception](../CONTRIBUTING.md#pr-72-scoped-release-exception). Whole-module status remains **In progress**, including modules whose existing contracts pass. Release validation covers the implemented scenarios; it does not certify untested operations. Missing APIs, known differences and unverified diff --git a/docs/integration.md b/docs/integration.md index f77b66c..f03ef0b 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -87,7 +87,7 @@ For the Vite example below, install `vite@7` as a dev dependency if it is not al Set the application's own ID/name and `webDir: "www"`. Use Swift Package Manager for iOS; this library does not include CocoaPods integration. Install the npm Preview using its exact version. The `latest` tag includes 0.x Preview releases: ```sh -npm install --save-exact cf-workers-native@0.1.5 +npm install --save-exact cf-workers-native@0.1.7 ``` For a source build instead, create a package tarball from a checkout of this repository: @@ -98,7 +98,7 @@ npm install npm pack # In the application package: -npm install /path/to/cf-workers-native/cf-workers-native-0.1.5.tgz +npm install /path/to/cf-workers-native/cf-workers-native-0.1.7.tgz ``` `npm pack` runs the SDK build through `prepack`. Install the generated tarball rather than the checkout directory: directory installs can create a symlink back to the SDK tree, including a recursive path when the app lives inside that checkout. The tarball filename above uses the current source version. @@ -107,11 +107,11 @@ The installed package is named `cf-workers-native`; the checkout directory can r ### Migrating from the old npm package -If your application already depends on `workers-capacitor`, remove it before installing the renamed package. Keeping both dependencies can make Capacitor discover and register the same native plugin twice. In the application package, using 0.1.5: +If your application already depends on `workers-capacitor`, remove it before installing the renamed package. Keeping both dependencies can make Capacitor discover and register the same native plugin twice. In the application package, using 0.1.7: ```sh npm uninstall workers-capacitor -npm install --save-exact cf-workers-native@0.1.5 +npm install --save-exact cf-workers-native@0.1.7 ``` Change runtime imports from `workers-capacitor` to `cf-workers-native/capacitor`, and change other package subpaths to the `cf-workers-native` prefix. Rebuild the application's mobile web assets with its existing build command, then run `npx cap sync` to regenerate native plugin dependencies. New applications use the installation steps above directly. diff --git a/docs/native-embedding.md b/docs/native-embedding.md index 31b3b3c..f4ab4e7 100644 --- a/docs/native-embedding.md +++ b/docs/native-embedding.md @@ -12,10 +12,9 @@ You will build the web assets in your web project, add the native SDK to your app, then open and close a Workers screen through its native API. The SDK resolves Capacitor internally; your native app does not need Capacitor configuration or CLI commands. -**0.1.5:** install `cf-workers-native@0.1.5` with matching +**0.1.7:** install `cf-workers-native@0.1.7` with matching [native dependencies](#dependency-setup). Android requires WebView `MULTI_PROFILE` -support. The previously published Maven `0.1.2` SDK does not include the -0.1.5 TLS upgrade bridge; see the Android version boundary below. +support. Use the same release for JavaScript and the native SDK. ## Shared web build @@ -91,19 +90,18 @@ entries are subpath imports, not separate npm packages. There is no bare package Install the npm Preview in the web project. The `latest` tag includes 0.x Preview releases: ```sh -npm install --save-exact cf-workers-native@0.1.5 +npm install --save-exact cf-workers-native@0.1.7 ``` -Use the dependency set below. npm 0.1.5 and SwiftPM `v0.1.5` share the release +Use the dependency set below. npm 0.1.7 and SwiftPM `v0.1.7` share the release commit. For Capacitor, npm includes the matching Android native implementation. -The separately published Maven 0.1.2 artifact predates the 0.1.5 TLS upgrade -bridge; do not treat it as the matching native SDK for all 0.1.5 features: +The standalone Android SDK is published separately to Maven Central for the same version: -| Component | Dependency | -| ---------- | ------------------------------------------------------------------------------------------------------------- | -| JavaScript | `cf-workers-native@0.1.5` | -| iOS | SwiftPM tag `v0.1.5`, product `WorkersIOS` | -| Android | Matching `v0.1.5` native sources via local publication; Maven Central `0.1.2` predates the TLS upgrade bridge | +| Component | Dependency | +| ---------- | -------------------------------------------------- | +| JavaScript | `cf-workers-native@0.1.7` | +| iOS | SwiftPM tag `v0.1.7`, product `WorkersIOS` | +| Android | `io.github.rdlabo:cf-workers-native-android:0.1.7` | For local SDK development, create a JavaScript package tarball from the matching checkout: @@ -113,7 +111,7 @@ npm install npm pack # In the web project: -npm install /path/to/cf-workers-native/cf-workers-native-0.1.5.tgz +npm install /path/to/cf-workers-native/cf-workers-native-0.1.7.tgz ``` `npm pack` runs the build through `prepack`; the filename above uses the current @@ -130,7 +128,7 @@ The source checkout's npm and build tools belong in the web build or CI. ## iOS Add `https://github.com/rdlabo-dev/cf-workers-native` as a Swift package pinned to -tag `v0.1.5` for npm 0.1.5 (or the matching revision for a source build), and select the `WorkersIOS` product. The existing `v0.1.2` tag predates the package rename; use `v0.1.5` for this release. Use Xcode 26 / +tag `v0.1.7` for npm 0.1.7 (or the matching revision for a source build), and select the `WorkersIOS` product. The existing `v0.1.2` tag predates the package rename; use `v0.1.7` for this release. Use Xcode 26 / Swift 6.2 or newer, as required by the native dependency toolchain. Add your generated assets as a folder resource, for example `WorkerWeb`, then create the controller from that directory on the main actor: @@ -174,19 +172,17 @@ from JavaScript. Explicit closure cancels the pending startup notification. Add the SDK's Android Maven publication to your app's dependencies and include the generated web directory under `src/main/assets/`, for example `worker-web`. The publication resolves Capacitor and its other native dependencies. -The previously published Maven coordinate is `io.github.rdlabo:cf-workers-native-android:0.1.2`. -This is the previously published SDK, not the matching Android native code for -npm 0.1.5. In particular, it does not include the new same-connection TLS upgrade -bridge. For the current implementation, use the Android native sources from the -matching release with the local publication workflow in [development](development.md#android-maven-publication), -or use Capacitor, which installs those sources from npm. +Use `io.github.rdlabo:cf-workers-native-android:0.1.7` with npm 0.1.7. +Older Maven artifacts are not substitutes for the matching native bridge. +For local SDK development, use the matching source revision and the +[local publication workflow](development.md#android-maven-publication). Use Java 21 and Android SDK 36, with `ANDROID_HOME` pointing to the installed SDK. Include `google()` and `mavenCentral()` in your app's dependency repositories. -For an application deliberately retaining that older SDK, the Groovy dependency is: +The Groovy dependency is: ```groovy dependencies { - implementation 'io.github.rdlabo:cf-workers-native-android:0.1.2' + implementation 'io.github.rdlabo:cf-workers-native-android:0.1.7' } android { compileOptions { diff --git a/tests/unit/execution-policy.test.ts b/tests/unit/execution-policy.test.ts index bf8a42c..48c7c53 100644 --- a/tests/unit/execution-policy.test.ts +++ b/tests/unit/execution-policy.test.ts @@ -77,6 +77,33 @@ it("network emits no Worker implementation", async () => { { kv_namespaces: [{ binding: "KV" }], assets: { directory: "public" } }, ); }); +it.each([undefined, "network"] as const)( + "remote execution does not resolve or evaluate server-only dependencies: %s", + async (execution) => { + await fixture( + { execution }, + async (graph) => { + const result = await graph.get(); + expect(result.requiresRemote).toBe(true); + expect(result.local + result.selector).not.toMatch( + /missing-server-sdk|SERVER_SECRET_CANARY|node:child_process/, + ); + const { needsRemote } = await load(result.selector); + for (const method of ["GET", "POST", "DELETE"]) + expect( + await needsRemote( + new Request("https://local.invalid/items", { method }), + ), + ).toBe(true); + await load(result.local); + }, + `import sdk from 'missing-server-sdk'; + import { spawn } from 'node:child_process'; + throw new Error('SERVER_SECRET_CANARY'); + export default { fetch() { return sdk(spawn); } };`, + ); + }, +); it("route selection grants dependency distribution only to selected methods and routes", async () => { await fixture( { diff --git a/tests/unit/remote-worker.test.ts b/tests/unit/remote-worker.test.ts index 96c993a..73d0014 100644 --- a/tests/unit/remote-worker.test.ts +++ b/tests/unit/remote-worker.test.ts @@ -33,6 +33,21 @@ function setup( return { runtime, handler, send }; } for (const prefer of ["direct", "worker"] as const) { + it(`${prefer}: a failed remote mutation is neither retried nor executed locally`, async () => { + const send = vi.fn(async (_request: Request): Promise => { + throw new TypeError("Connection lost after sending"); + }); + const { runtime, handler } = setup(prefer, undefined, send); + await runtime.ready; + await expect( + runtime.fetch("https://same.example/api/items", { + method: "POST", + body: "mutation", + }), + ).rejects.toThrow("Connection lost after sending"); + expect(send).toHaveBeenCalledTimes(1); + expect(handler.fetch).not.toHaveBeenCalled(); + }); it(`${prefer}: sends remote routes before user code, reusing the existing HTTP request`, async () => { let token = "first"; const getToken = vi.fn(() => token);