From ff5d11cf3ea8af35d1448f1527c8935c540d7a37 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:54:20 +0000 Subject: [PATCH] fix(npm): curate TypeScript declarations with Wasm parity - Add portable TypeScript facades in src/types.ts and src/wasm.ts - Decode undefined HarmonyConfig.voices to 4 in the Wasm bindings - Route ./wasm through ./dist/wasm.js and ./dist/wasm.d.ts - Export ./pkg/tunelet_bg.wasm and ./tunelet_bg.wasm in package.json - Read file: URL strings and cross-realm URLs in loadTunelet - Verify type parity, strict tsc profiles and esbuild in verify:pack --- README.md | 12 +- package-lock.json | 485 +++++++++++++++++++++++++++++ package.json | 9 +- scripts/verify-pack.mjs | 656 +++++++++++++++++++++++++++++++++++----- src/harmony.rs | 17 +- src/index.ts | 67 ++-- src/types.ts | 573 +++++++++++++++++++++++++++++++++++ src/wasm.ts | 78 +++++ tsconfig.json | 3 +- 9 files changed, 1795 insertions(+), 105 deletions(-) create mode 100644 src/types.ts create mode 100644 src/wasm.ts diff --git a/README.md b/README.md index 83a8f47..2bbb617 100644 --- a/README.md +++ b/README.md @@ -382,16 +382,16 @@ and you can try again. A Node.js file error goes to the caller. For a custom asset location, give one of these sources to `loadTunelet(source)`: -- A URL. -- A fetch Response. +- A URL or a URL string. +- A fetch Request or Response. - A byte buffer. - A compiled `WebAssembly.Module`. - A promise for one of these. -For a Node.js `file:` source, use a URL object. A string source obeys fetch -rules. The first concurrent call selects the source. Later arguments do not -replace an initialized module. A custom binary must match the generated -bindings. +In Node.js, `loadTunelet` reads `file:` URL strings and `file:` URL objects +from disk. Other string sources obey fetch rules. The first concurrent call +selects the source. Later arguments do not replace an initialized module. A +custom binary must match the generated bindings. The package root also exports `loadTunelet` as its default export. For direct control of Wasm initialization, `tunelet/wasm` gives the generated default diff --git a/package-lock.json b/package-lock.json index ebb3bac..07bb47e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,9 +10,452 @@ "license": "MIT", "devDependencies": { "@types/node": "^22.20.5", + "esbuild": "^0.28.2", "typescript": "^7.0.2" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@types/node": { "version": "22.20.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", @@ -363,6 +806,48 @@ "node": ">=16.20.0" } }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, "node_modules/typescript": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", diff --git a/package.json b/package.json index 8c201f6..de19493 100644 --- a/package.json +++ b/package.json @@ -16,9 +16,11 @@ "import": "./dist/index.js" }, "./wasm": { - "types": "./pkg/tunelet.d.ts", - "import": "./pkg/tunelet.js" - } + "types": "./dist/wasm.d.ts", + "import": "./dist/wasm.js" + }, + "./pkg/tunelet_bg.wasm": "./pkg/tunelet_bg.wasm", + "./tunelet_bg.wasm": "./pkg/tunelet_bg.wasm" }, "files": [ "dist", @@ -37,6 +39,7 @@ }, "devDependencies": { "@types/node": "^22.20.5", + "esbuild": "^0.28.2", "typescript": "^7.0.2" } } diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..fd6713a 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -1,29 +1,49 @@ /** - * This script packs the npm archive, checks its eight files, runs - * `loadTunelet()` and checks the TypeScript declarations. + * This script packs the npm archive, checks its twelve files, verifies + * bidirectional parity with `pkg/tunelet.d.ts`, runs `loadTunelet()` and + * bundler checks, and compiles four consumer TypeScript profiles. */ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import * as esbuild from "esbuild"; const EXPECTED_ARCHIVE_PATHS = [ "package/LICENSE", "package/README.md", "package/dist/index.d.ts", "package/dist/index.js", + "package/dist/types.d.ts", + "package/dist/types.js", + "package/dist/wasm.d.ts", + "package/dist/wasm.js", "package/package.json", "package/pkg/tunelet.d.ts", "package/pkg/tunelet.js", "package/pkg/tunelet_bg.wasm", ]; +const FORBIDDEN_DECLARATION_TOKENS = [ + "../pkg/tunelet.js", + "../pkg/tunelet.d.ts", + "Symbol.dispose", + "RequestInfo", + "BufferSource", + "WebAssembly", + "__wbg_", + "__wbindgen_", + "declare global", + "/// ` and fail on any compiler diagnostic. */ +function runTscProject(tsconfigPath, cwd) { + execFileSync(process.execPath, [tscBin, "-p", tsconfigPath], { + cwd, + stdio: "inherit", + }); +} + /** Run `npm pack` without a shell and return the relative archive path. */ function packArchive(packDir) { const npmExecPath = process.env.npm_execpath; @@ -86,7 +123,7 @@ function packArchive(packDir) { return path.posix.join("pack", archives[0]); } -/** Check that the archive contains only the eight expected files. */ +/** Check that the archive contains only the twelve expected files. */ function verifyArchiveEntries(tempDir, relativeArchivePath) { const rawList = execFileSync("tar", ["-tzf", relativeArchivePath], { cwd: tempDir, @@ -143,17 +180,168 @@ function installArchive( type: "module", }), ); + + return installedDir; +} + +/** Check that public `dist/*.d.ts` files expose no generated or host leaks. */ +function verifyDeclarationPortability(installedDir) { + for (const relativeFile of [ + "dist/index.d.ts", + "dist/wasm.d.ts", + "dist/types.d.ts", + ]) { + const content = fs.readFileSync( + path.join(installedDir, relativeFile), + "utf8", + ); + for (const token of FORBIDDEN_DECLARATION_TOKENS) { + assert.equal( + content.includes(token), + false, + `Unexpected token "${token}" in ${relativeFile}`, + ); + } + } +} + +/** Check bidirectional assignability between `src/types.ts` and `pkg/tunelet.d.ts`. */ +function verifyTypeParity(tempDir) { + const parityDir = path.join(tempDir, "parity"); + fs.mkdirSync(parityDir); + + fs.writeFileSync( + path.join(parityDir, "package.json"), + JSON.stringify({ + name: "tunelet-type-parity", + private: true, + type: "module", + }), + ); + + const srcTypesSpec = toRelativeModuleSpecifier( + parityDir, + path.join(repoRoot, "src", "types.ts"), + ); + const srcWasmSpec = toRelativeModuleSpecifier( + parityDir, + path.join(repoRoot, "src", "wasm.ts"), + ); + const pkgSpec = toRelativeModuleSpecifier( + parityDir, + path.join(repoRoot, "pkg", "tunelet.js"), + ); + + const parityTsPath = path.join(parityDir, "check-parity.ts"); + fs.writeFileSync( + parityTsPath, + [ + `import type * as Curated from ${JSON.stringify(srcTypesSpec)};`, + `import { defaultConfig as curatedDefaultConfig } from ${JSON.stringify(srcWasmSpec)};`, + `import type * as Pkg from ${JSON.stringify(pkgSpec)};`, + `import { defaultConfig as pkgDefaultConfig } from ${JSON.stringify(pkgSpec)};`, + "", + "type AssertTrue = T;", + "type IsAssignable = [From] extends [To] ? true : false;", + "type RequiredKeys = {", + " [K in keyof T]-?: {} extends Pick ? never : K;", + "}[keyof T];", + "type ExactObjectParity = [", + " IsAssignable,", + " IsAssignable,", + " IsAssignable, never>,", + " IsAssignable, never>,", + " IsAssignable, RequiredKeys>, never>,", + " IsAssignable, RequiredKeys>, never>,", + "] extends [true, true, true, true, true, true]", + " ? true", + " : false;", + "type ExactTypeParity = [", + " IsAssignable,", + " IsAssignable,", + "] extends [true, true]", + " ? true", + " : false;", + "", + "export type ParityChecks = [", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>>,", + " AssertTrue, ConstructorParameters>>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + " AssertTrue>,", + "];", + "", + ].join("\n"), + ); + + const tsconfigPath = path.join(parityDir, "tsconfig.json"); + fs.writeFileSync( + tsconfigPath, + JSON.stringify({ + compilerOptions: { + target: "ES2020", + lib: ["ES2020", "ESNext.Disposable", "DOM"], + module: "NodeNext", + moduleResolution: "NodeNext", + allowImportingTsExtensions: true, + types: [], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + noEmit: true, + }, + files: [parityTsPath], + }), + ); + + runTscProject(tsconfigPath, parityDir); } -/** Import the installed package in Node.js and process one audio block. */ -function verifyRuntimeImport(consumerDir, packageName) { +/** Check runtime imports, `{ voices: undefined }`, `.wasm` subpaths and `file:` URLs. */ +function verifyRuntimeImport(consumerDir, installedDir, packageName) { + const expectedWasmUrl = pathToFileURL( + path.join(installedDir, "pkg", "tunelet_bg.wasm"), + ).href; + const checkPath = path.join(consumerDir, "check.mjs"); fs.writeFileSync( checkPath, [ 'import assert from "node:assert/strict";', "", - "const packageName = process.argv[2];", + "const [packageName, expectedWasmUrl] = process.argv.slice(2);", + "const pkgWasmUrl = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + "const shortWasmUrl = import.meta.resolve(`${packageName}/tunelet_bg.wasm`);", + "assert.equal(pkgWasmUrl, expectedWasmUrl);", + "assert.equal(shortWasmUrl, expectedWasmUrl);", + "", "const rootModule = await import(packageName);", "const wasmModule = await import(`${packageName}/wasm`);", "", @@ -164,17 +352,72 @@ function verifyRuntimeImport(consumerDir, packageName) { 'assert.equal(typeof rootModule.defaultConfig, "function");', 'assert.equal(typeof wasmModule.default, "function");', 'assert.equal(typeof wasmModule.initSync, "function");', + "assert.equal(wasmModule.Tunelet, rootModule.Tunelet);", + "assert.equal(wasmModule.defaultConfig, rootModule.defaultConfig);", "", "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", + "assert.ok(wasmExports.memory);", "", - "const config = rootModule.defaultConfig();", - "const processor = new rootModule.Tunelet(48000, 128, config);", + "function withHarmonyVoices(config, voices) {", + " return {", + " ...config,", + " resynthesis: {", + " ...config.resynthesis,", + " harmony: {", + " ...config.resynthesis.harmony,", + " voices,", + " },", + " },", + " };", + "}", + "", + "const baseConfig = rootModule.defaultConfig();", + "const processor = new rootModule.Tunelet(", + " 48000,", + " 128,", + " withHarmonyVoices(baseConfig, undefined),", + ");", "try {", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + "", + " processor.setConfig(withHarmonyVoices(processor.config(), 1));", + " assert.equal(processor.config().resynthesis.harmony.voices, 1);", + "", + " processor.setConfig(withHarmonyVoices(processor.config(), undefined));", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + "", " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", " processor.process(input, left, right);", + "", + " processor.setConfig(withHarmonyVoices(processor.config(), 2));", + " assert.equal(processor.config().resynthesis.harmony.voices, 2);", + " const mono = new Int16Array(128);", + " processor.processMono(mono, [", + " {", + " offset: 0,", + " event: {", + ' type: "resynthesis",', + " value: withHarmonyVoices(processor.config(), undefined).resynthesis,", + " },", + " },", + " ]);", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + "", + " processor.setConfig(withHarmonyVoices(processor.config(), 3));", + " assert.equal(processor.config().resynthesis.harmony.voices, 3);", + " processor.processMono(mono, [", + " {", + " offset: 0,", + " event: {", + ' type: "configure",', + " value: withHarmonyVoices(processor.config(), undefined),", + " },", + " },", + " ]);", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", "} finally {", " processor.free();", "}", @@ -182,81 +425,348 @@ function verifyRuntimeImport(consumerDir, packageName) { ].join("\n"), ); - execFileSync(process.execPath, [checkPath, packageName], { + execFileSync(process.execPath, [checkPath, packageName, expectedWasmUrl], { cwd: consumerDir, stdio: "inherit", }); -} -/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ -function verifyTypeDeclarations(consumerDir, packageName) { - const checkTsPath = path.join(consumerDir, "check.ts"); - const pkgLiteral = JSON.stringify(packageName); - const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + const fileUrlCheckPath = path.join(consumerDir, "check-file-source.mjs"); fs.writeFileSync( - checkTsPath, + fileUrlCheckPath, [ - "import loadTunelet, {", - " defaultConfig,", - " initSync as rootInitSync,", - " loadTunelet as namedLoadTunelet,", - " Tunelet,", - " type ProcessorConfig,", - `} from ${pkgLiteral};`, - "import init, {", - " initSync as wasmInitSync,", - " type InitInput,", - " type InitOutput,", - `} from ${wasmLiteral};`, + 'import assert from "node:assert/strict";', + 'import vm from "node:vm";', "", - "export async function verifyTypes(source?: InitInput): Promise {", - " const exportsFromRoot: InitOutput = await loadTunelet(source);", - " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", - " const exportsFromWasm: InitOutput = await init(source);", - " const config: ProcessorConfig = defaultConfig();", - " const processor = new Tunelet(48000, 128, config);", - " const input = new Int16Array(128);", - " const left = new Int16Array(128);", - " const right = new Int16Array(128);", - " processor.process(input, left, right);", + "const [packageName, mode] = process.argv.slice(2);", + "const { loadTunelet, Tunelet } = await import(packageName);", + "", + "let source;", + 'if (mode === "pkg-subpath-string") {', + " source = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + ' assert.equal(typeof source, "string");', + ' assert.equal(source.startsWith("file:"), true);', + '} else if (mode === "short-subpath-string") {', + " source = import.meta.resolve(`${packageName}/tunelet_bg.wasm`);", + ' assert.equal(typeof source, "string");', + ' assert.equal(source.startsWith("file:"), true);', + '} else if (mode === "cross-realm-url") {', + " const href = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + ' source = vm.runInNewContext(\'({ protocol: "file:", href })\', { href });', + " assert.equal(source instanceof URL, false);", + "} else {", + " throw new Error(`Unknown mode: ${mode}`);", + "}", + "", + "const exportsOut = await loadTunelet(source);", + "assert.ok(exportsOut.memory);", + "const processor = new Tunelet(48000, 64);", + "try {", + " const mono = new Int16Array(64);", + " processor.processMono(mono);", + "} finally {", " processor.free();", - " void rootInitSync;", - " void wasmInitSync;", - " void exportsFromRoot;", - " void exportsFromNamed;", - " void exportsFromWasm;", "}", "", ].join("\n"), ); - const tscBin = path.join( - repoRoot, - "node_modules", - "typescript", - "bin", - "tsc", - ); - execFileSync( - process.execPath, + for (const mode of [ + "pkg-subpath-string", + "short-subpath-string", + "cross-realm-url", + ]) { + execFileSync(process.execPath, [fileUrlCheckPath, packageName, mode], { + cwd: consumerDir, + stdio: "inherit", + }); + } +} + +/** Check that `esbuild` resolves `.`, `./wasm`, and both `.wasm` subpaths. */ +async function verifyBundlerResolution(consumerDir, installedDir, packageName) { + const bundleDir = path.join(consumerDir, "bundle"); + const outDir = path.join(bundleDir, "out"); + fs.mkdirSync(bundleDir); + + const entryPath = path.join(bundleDir, "entry.js"); + fs.writeFileSync( + entryPath, [ - tscBin, - "--noEmit", - "--module", - "NodeNext", - "--moduleResolution", - "NodeNext", - "--target", - "ES2020", - "--lib", - "ES2020,ESNext.Disposable,DOM", - "--strict", - checkTsPath, - ], - { cwd: consumerDir, stdio: "inherit" }, + `import loadTunelet, { Tunelet, defaultConfig } from ${JSON.stringify(packageName)};`, + `import initWasm, { initSync } from ${JSON.stringify(`${packageName}/wasm`)};`, + `import pkgWasmAsset from ${JSON.stringify(`${packageName}/pkg/tunelet_bg.wasm`)};`, + `import shortWasmAsset from ${JSON.stringify(`${packageName}/tunelet_bg.wasm`)};`, + "", + "export { loadTunelet, Tunelet, defaultConfig, initWasm, initSync, pkgWasmAsset, shortWasmAsset };", + "", + ].join("\n"), + ); + + const result = await esbuild.build({ + absWorkingDir: consumerDir, + entryPoints: [entryPath], + bundle: true, + format: "esm", + platform: "browser", + outdir: outDir, + loader: { ".wasm": "file" }, + metafile: true, + logLevel: "silent", + }); + + const expectedWasmReal = fs.realpathSync( + path.join(installedDir, "pkg", "tunelet_bg.wasm"), + ); + const entryImports = result.metafile.inputs["bundle/entry.js"].imports.map( + (entry) => fs.realpathSync(path.resolve(consumerDir, entry.path)), + ); + const wasmImportCount = entryImports.filter( + (resolvedPath) => resolvedPath === expectedWasmReal, + ).length; + assert.equal( + wasmImportCount, + 2, + "Expected esbuild to resolve both .wasm subpaths to pkg/tunelet_bg.wasm", + ); + + const emittedFiles = fs.readdirSync(outDir); + assert.ok( + emittedFiles.some((file) => file.endsWith(".wasm")), + "Expected esbuild to emit a .wasm asset", + ); + assert.ok( + emittedFiles.includes("entry.js"), + "Expected esbuild to emit entry.js", ); } +/** Check four consumer `tsc --strict --exactOptionalPropertyTypes` profiles. */ +function verifyTypeDeclarations(consumerDir, packageName) { + const pkgLiteral = JSON.stringify(packageName); + const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + const nodeTypesRoot = path.join(repoRoot, "node_modules", "@types"); + + const sharedPortableSource = [ + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " loadTunelet as namedLoadTunelet,", + " Tunelet,", + " type Feedback,", + " type HarmonyConfig,", + " type InitInput,", + " type InitOutput,", + " type ProcessorConfig,", + " type SyncInitInput,", + " type Telemetry,", + " type TimedEvent,", + " type WasmInitInput,", + " type WasmInitOutput,", + " type WasmSyncInitInput,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " Tunelet as WasmTunelet,", + " type Tunelet as WasmTuneletType,", + " type WasmInitInput as SubpathInitInput,", + " type WasmInitOutput as SubpathInitOutput,", + "} from " + wasmLiteral + ";", + "", + "export async function verifyPortable(", + " source?: WasmInitInput,", + " compatSource?: InitInput,", + " syncSource?: WasmSyncInitInput,", + " compatSync?: SyncInitInput,", + "): Promise {", + " const exportsFromRoot: WasmInitOutput = await loadTunelet(source);", + " const exportsFromNamed: InitOutput = await namedLoadTunelet(compatSource);", + " const exportsFromFileString: WasmInitOutput = await loadTunelet(", + ' "file:///tmp/tunelet_bg.wasm",', + " );", + " const exportsFromUrlLike: WasmInitOutput = await loadTunelet({", + ' href: "file:///tmp/tunelet_bg.wasm",', + ' protocol: "file:",', + " });", + " const subpathInput: SubpathInitInput | undefined = source;", + " const exportsFromWasm: SubpathInitOutput = await init(subpathInput);", + " if (syncSource !== undefined) {", + " const syncOut: WasmInitOutput = rootInitSync({ module: syncSource });", + " void syncOut;", + " }", + " if (compatSync !== undefined) {", + " const syncOut2: InitOutput = wasmInitSync(compatSync);", + " void syncOut2;", + " }", + " const config: ProcessorConfig = defaultConfig();", + " const harmonyWithUndefined: HarmonyConfig = {", + " ...config.resynthesis.harmony,", + " voices: undefined,", + " };", + " const nextConfig: ProcessorConfig = {", + " ...config,", + " resynthesis: {", + " ...config.resynthesis,", + " harmony: harmonyWithUndefined,", + " },", + " };", + " const processor: Tunelet = new Tunelet(48000, 128, nextConfig);", + " const wasmProcessor: WasmTuneletType = new WasmTunelet(48000, 128, nextConfig);", + " const input = new Int16Array(128);", + " const left = new Int16Array(128);", + " const right = new Int16Array(128);", + " const events: TimedEvent[] = [", + " {", + " offset: 0,", + " event: {", + ' type: "resynthesis",', + " value: nextConfig.resynthesis,", + " },", + " },", + " ];", + " processor.process(input, left, right, events);", + " processor.processMono(input, events);", + " const feedback: Feedback = processor.feedback();", + " const telemetry: Telemetry = processor.telemetry();", + " processor.free();", + " wasmProcessor.free();", + " void exportsFromRoot;", + " void exportsFromNamed;", + " void exportsFromFileString;", + " void exportsFromUrlLike;", + " void exportsFromWasm;", + " void feedback;", + " void telemetry;", + "}", + "", + ].join("\n"); + + const profiles = [ + { + name: "node", + compilerOptions: { + target: "ES2022", + lib: ["ES2023"], + module: "NodeNext", + moduleResolution: "NodeNext", + typeRoots: [nodeTypesRoot], + types: ["node"], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + noEmit: true, + }, + source: [ + sharedPortableSource, + "export async function verifyNodeHost(): Promise {", + ' const fileUrl = new URL("file:///tmp/tunelet_bg.wasm");', + " await loadTunelet(fileUrl);", + " await loadTunelet(Buffer.alloc(8));", + " wasmInitSync({ module: Buffer.alloc(8) });", + "}", + "", + ].join("\n"), + }, + { + name: "es2023", + compilerOptions: { + target: "ES2023", + lib: ["ES2023"], + module: "NodeNext", + moduleResolution: "NodeNext", + types: [], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + noEmit: true, + }, + source: [ + sharedPortableSource, + "export async function verifyPureEs2023(): Promise {", + " await loadTunelet(new Uint8Array(8));", + " wasmInitSync({ module: new ArrayBuffer(8) });", + "}", + "", + ].join("\n"), + }, + { + name: "dom", + compilerOptions: { + target: "ES2022", + lib: ["ES2022", "DOM"], + module: "ES2022", + moduleResolution: "Bundler", + types: [], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + noEmit: true, + }, + source: [ + sharedPortableSource, + "export async function verifyDomHost(", + " compiled: WebAssembly.Module,", + "): Promise {", + ' await loadTunelet(fetch("/tunelet_bg.wasm"));', + ' await loadTunelet(new Request("/tunelet_bg.wasm"));', + ' await loadTunelet(new URL("/tunelet_bg.wasm", location.href));', + " await loadTunelet(compiled);", + " wasmInitSync({ module: compiled });", + "}", + "", + ].join("\n"), + }, + { + name: "webworker", + compilerOptions: { + target: "ES2022", + lib: ["ES2022", "WebWorker"], + module: "ES2022", + moduleResolution: "Bundler", + types: [], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + noEmit: true, + }, + source: [ + sharedPortableSource, + "export async function verifyWebWorkerHost(", + " compiled: WebAssembly.Module,", + "): Promise {", + " const out: SubpathInitOutput = wasmInitSync({ module: compiled });", + ' await init(fetch("/tunelet_bg.wasm"));', + " const workletEngine: WasmTuneletType = new WasmTunelet(48000, 128);", + " workletEngine.free();", + " void out;", + "}", + "", + ].join("\n"), + }, + ]; + + const profilesRoot = path.join(consumerDir, "profiles"); + fs.mkdirSync(profilesRoot); + + for (const profile of profiles) { + const profileDir = path.join(profilesRoot, profile.name); + fs.mkdirSync(profileDir); + + const checkTsPath = path.join(profileDir, "check.ts"); + const tsconfigPath = path.join(profileDir, "tsconfig.json"); + + fs.writeFileSync(checkTsPath, profile.source); + fs.writeFileSync( + tsconfigPath, + JSON.stringify({ + compilerOptions: profile.compilerOptions, + files: [checkTsPath], + }), + ); + + runTscProject(tsconfigPath, profileDir); + } +} + const packageName = readPackageName(); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "tunelet-verify-pack-")); @@ -268,8 +778,16 @@ try { const relativeArchivePath = packArchive(packDir); verifyArchiveEntries(tempDir, relativeArchivePath); - installArchive(tempDir, relativeArchivePath, consumerDir, packageName); - verifyRuntimeImport(consumerDir, packageName); + const installedDir = installArchive( + tempDir, + relativeArchivePath, + consumerDir, + packageName, + ); + verifyDeclarationPortability(installedDir); + verifyTypeParity(tempDir); + verifyRuntimeImport(consumerDir, installedDir, packageName); + await verifyBundlerResolution(consumerDir, installedDir, packageName); verifyTypeDeclarations(consumerDir, packageName); } finally { fs.rmSync(tempDir, { recursive: true, force: true }); diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..8cf3ca3 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -320,12 +320,12 @@ pub struct HarmonyConfig { /// The default is 4. [`HarmonySource::FixedInterval`] and /// [`HarmonySource::SmartInterval`] use the first `voices` voices. The /// other voices release with the usual gain envelope. The chord and MIDI - /// sources ignore this field. In JavaScript, the field is optional and - /// a missing value gives the default. + /// sources ignore this field. In JavaScript, the field is optional. If it + /// is absent or `undefined`, the value is 4. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - serde(default = "default_voices"), - tsify(optional) + serde(default = "default_voices", deserialize_with = "deserialize_voices"), + tsify(optional, type = "number | undefined") )] pub voices: u8, } @@ -336,6 +336,15 @@ fn default_voices() -> u8 { HARMONY_VOICES as u8 } +/// Decodes an optional count of interval voices and maps `undefined` to 4. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_voices<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + Ok( + as serde::Deserialize>::deserialize(deserializer)? + .unwrap_or_else(default_voices), + ) +} + impl Default for HarmonyConfig { fn default() -> Self { Self { diff --git a/src/index.ts b/src/index.ts index 8526d77..0180144 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,18 +2,18 @@ * The shared ESM entry point for browsers and Node.js. * * Call `loadTunelet()` before you construct processors or read the default - * configuration. Both environments use the same generated bindings and the - * same Wasm binary. This module re-exports all named exports of the module - * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, event and feedback types. + * configuration. Both environments use the same Wasm binary and the same + * portable TypeScript declarations, which include `Tunelet`, `defaultConfig`, + * `initSync` and the configuration, event, feedback and telemetry types. */ -import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import init from "./wasm.js"; +import type { WasmInitInput, WasmInitOutput } from "./types.js"; -export * from "../pkg/tunelet.js"; +export type * from "./types.js"; +export { Tunelet, defaultConfig, initSync } from "./wasm.js"; /** The shared initialization promise, which a failure clears. */ -let initialization: Promise | undefined; +let initialization: Promise | undefined; /** * Initializes the Wasm module one time for this imported package instance. @@ -21,19 +21,20 @@ let initialization: Promise | undefined; * If you give no argument, the function finds the packaged binary relative to * this module. Node.js reads a `file:` URL, and browsers fetch the served * asset. An import of the package does not load Wasm. In browsers, serve the - * assets over HTTP(S), or give the bytes or a compiled module as the source. + * assets over HTTP(S), or give the bytes or a precompiled module as the + * source. * * For a custom deployment, you can give one of these sources: * - * - A URL. - * - A fetch Response. - * - A byte buffer (BufferSource). - * - A compiled WebAssembly.Module. + * - A URL or a URL string. + * - A fetch Request or Response. + * - An ArrayBuffer or an ArrayBufferView. + * - A precompiled Wasm module. * - A promise for one of these. * - * A string source obeys fetch rules. For a Node.js `file:` source, use a - * URL object. A compiled module must use imports that agree with the packaged - * bindings. + * In Node.js, `loadTunelet` reads `file:` URL strings and `file:` URL objects + * from disk. Other string sources obey fetch rules. A precompiled module must + * use imports that agree with the packaged bindings. * * Concurrent calls share one promise, and the first call selects the source. * After a successful initialization, later calls use it again and do not load @@ -48,8 +49,8 @@ let initialization: Promise | undefined; * for processors. */ export function loadTunelet( - source?: InitInput | Promise, -): Promise { + source?: WasmInitInput | Promise, +): Promise { initialization ??= initialize(source).catch((error: unknown) => { initialization = undefined; throw error; @@ -57,16 +58,38 @@ export function loadTunelet( return initialization; } +/** Converts a `file:` URL string or `file:` URL object into a host `URL`. */ +function toFileUrl(input: WasmInitInput): URL | undefined { + if (typeof input === "string") { + return /^file:/i.test(input) ? new URL(input) : undefined; + } + if (input instanceof URL) { + return input.protocol === "file:" ? input : undefined; + } + if ( + typeof input === "object" && + input !== null && + "protocol" in input && + input.protocol === "file:" && + "href" in input && + typeof input.href === "string" + ) { + return new URL(input.href); + } + return undefined; +} + /** Awaits the source one time, then initializes the Wasm module from it. */ async function initialize( - source: InitInput | Promise | undefined, -): Promise { + source: WasmInitInput | Promise | undefined, +): Promise { const input = source === undefined ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) : await source; - if (input instanceof URL && input.protocol === "file:") { + const fileUrl = toFileUrl(input); + if (fileUrl !== undefined) { // Keep the Node.js built-in module out of browser bundles. TypeScript // removes the type-only import. The runtime import runs only for `file:` // URLs. @@ -74,7 +97,7 @@ async function initialize( const fs: typeof import("node:fs/promises") = await import( /* webpackIgnore: true */ /* @vite-ignore */ moduleName ); - return init({ module_or_path: await fs.readFile(input) }); + return init({ module_or_path: await fs.readFile(fileUrl) }); } return init({ module_or_path: input }); diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..2055ee8 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,573 @@ +/** + * Portable TypeScript declarations for `tunelet` and `tunelet/wasm`. + * + * These declarations use only standard ECMAScript types and structural + * interfaces. They do not depend on browser, worker, Node.js or disposable + * global libraries. + */ + +/** The method that resynthesis uses to render its voices. */ +export type MultiVoiceMode = "choir" | "harmony"; + +/** One of the twelve notes in an octave. */ +export type PitchClass = + | "c" + | "cSharp" + | "d" + | "dSharp" + | "e" + | "f" + | "fSharp" + | "g" + | "gSharp" + | "a" + | "aSharp" + | "b"; + +/** A scale for pitch-class correction masks. */ +export type CorrectionScale = "major" | "minor" | "chromatic"; + +/** + * The permitted correction pitch classes, in the order C, C#, D, D#, E, F, + * F#, G, G#, A, A#, B. + * + * A `true` flag enables that pitch class in all octaves. All combinations of + * flags are valid. If the mask has no `true` flags, the correction ratio + * moves toward unity with the configured retune half-life. + */ +export type NoteMask = [ + boolean, + boolean, + boolean, + boolean, + boolean, + boolean, + boolean, + boolean, + boolean, + boolean, + boolean, + boolean, +]; + +/** + * The source of target periods for the four harmony voices. + * + * The default is `"midiChannels"`. Static interval and chord sources use the + * related `HarmonyConfig` fields. MIDI sources use `ControlEvent` values with + * `type: "midi"`. Validation always checks all fields. + */ +export type HarmonySource = + | "fixedInterval" + | "smartInterval" + | "chordByDegree" + | "chordByName" + | "chordViaMidi" + | "midiOmni" + | "midiChannels"; + +/** The scale that smart intervals and chords by degree use. */ +export type HarmonyScale = + | "major" + | "majorWithoutSeventh" + | "majorFlatSeventh" + | "minor" + | "harmonicMinor" + | "minorNaturalSixth" + | "minorMajorSeventh"; + +/** + * A named chord for `"chordByName"`. + * + * Triads use three voices. Seventh and sixth chords use four voices. + */ +export type ChordName = + | "major" + | "majorSixth" + | "majorSeventh" + | "majorSeventhSuspendedFourth" + | "minor" + | "minorSixth" + | "minorSeventh" + | "minorSeventhFlatFifth" + | "diminished" + | "diminishedSeventh" + | "dominantSeventh" + | "dominantSeventhFlatFifth" + | "augmented" + | "augmentedSeventh" + | "suspendedFourth" + | "suspendedSecond" + | "suspendedSeventh"; + +/** + * A diatonic chord with its root on a degree of the selected `HarmonyScale`. + * + * The default is `"i"`. + */ +export type ChordDegree = + | "i" + | "ii" + | "iiSeventh" + | "iii" + | "iiiSeventh" + | "iv" + | "ivSeventh" + | "v" + | "vSeventh" + | "vi" + | "viSeventh" + | "vii" + | "viiSeventh"; + +/** + * The chord inversion raises the lowest chord tones by one octave. + * + * The inversion applies only to named chords and degree chords. The default + * is `"root"`. + */ +export type Inversion = "root" | "first" | "second"; + +/** + * The echo or reverberation network. + * + * The default is `"echo"`. All modes share one delay buffer. + */ +export type ReverbMode = + | "echo" + | "schroeder" + | "smallRoom" + | "binaural" + | "mediumHall" + | "largeHall"; + +/** + * The input gain and the transient enhancement with arctangent saturation. + * + * Punch operates before Warm and before pitch detection. When Punch is + * disabled, it does not process audio, and its state does not change. + */ +export interface PunchConfig { + /** Enables this input stage. The default is `false`. */ + enabled: boolean; + /** The input gain in decibels, -96..=12. The default is 0 dB. */ + gainDb: number; + /** The transient emphasis without a unit, 0..=1. The default is 0.5. */ + impact: number; + /** The output ceiling of the saturation in dBFS, -96..=0. The default is -3 dBFS. */ + ceilingDb: number; + /** The attack half-life of the peak follower in milliseconds, 0.01..=5000. The default is 10 ms. */ + attackMs: number; +} + +/** + * Asymmetric input saturation, followed by a 50 Hz high-pass filter. + * + * Warm operates after Punch and before pitch detection. + */ +export interface WarmConfig { + /** Enables the saturation stage. The default is `false`. */ + enabled: boolean; + /** The drive in decibels, 0..=6. The default is 3 dB. */ + driveDb: number; +} + +/** The acquisition sensitivity and the bounds for pitch reports to the host. */ +export interface PitchConfig { + /** The normalized cycle-difference threshold for acquisition, 0.002..=0.2. The default is 0.1. */ + threshold: number; + /** The lower bound of the feedback in hertz, 40..=2000. The default is 40. It must be less than `maxFrequencyHz`. */ + minFrequencyHz: number; + /** The upper bound of the feedback in hertz, 40..=2000. The default is 1100. It must be greater than `minFrequencyHz`. */ + maxFrequencyHz: number; +} + +/** The controls for pitch-class correction in the period domain. */ +export interface CorrectionConfig { + /** Enables the selection of correction targets. The default is `true`. */ + enabled: boolean; + /** The configured target pitch classes. The default enables all twelve classes. */ + notes: NoteMask; + /** The half-life of the ratio smoothing in milliseconds, 0..=400. The default is 0. */ + retuneMs: number; +} + +/** The controls for vocal-tract changes and synthesized aspiration. */ +export interface FormantConfig { + /** Enables formant analysis and synthesis. The default is `false`. */ + enabled: boolean; + /** The vocal-tract width factor, 0.5..=2. The default is 1. */ + width: number; + /** The vocal-tract length factor, 0.5..=2. The default is 1. */ + stretch: number; + /** The aspiration level, 0..=1, without a unit. The default is 0. */ + aspirationMix: number; + /** The high-pass cutoff for aspiration in hertz, 500..=10000. The default is 4000. */ + aspirationCutoffHz: number; +} + +/** The configuration of four harmony voices that follow intervals, chords or MIDI. */ +export interface HarmonyConfig { + /** The pitch source. The default is `"midiChannels"`. */ + source: HarmonySource; + /** The pitch class of the tonic. The default is `"c"`. */ + key: PitchClass; + /** The scale for smart intervals and degree chords. The default is `"major"`. */ + scale: HarmonyScale; + /** Four fixed semitone offsets, each in -24..=24. The default is `[0, 0, 0, 0]`. */ + chromaticIntervals: [number, number, number, number]; + /** Four offsets in scale steps, each in -14..=14. The default is `[0, 0, 0, 0]`. */ + diatonicIntervals: [number, number, number, number]; + /** The named chord for `"chordByName"`. The default is `"major"`. */ + chord: ChordName; + /** The chord on a scale degree for `"chordByDegree"`. The default is `"i"`. */ + degree: ChordDegree; + /** The inversion for named chords and degree chords. The default is `"root"`. */ + inversion: Inversion; + /** The chord register from low to high, 0..=100%. The default is 50%. */ + registerPercent: number; + /** The chord voicing spread from close to open, 0..=100%. The default is 0%. */ + voicingSpreadPercent: number; + /** The half-life of the target-period glide in milliseconds, 0..=10000. The default is 0. */ + portamentoMs: number; + /** + * The number of voices that sound in the interval sources, 0..=4. + * + * This field is optional. If it is absent or `undefined`, the value is 4. + */ + voices?: number | undefined; +} + +/** + * The controls for pitch correction, pitch shift, voice arrangement and + * formants. + */ +export interface ResynthesisConfig { + /** The acquisition sensitivity and the pitch report bounds. */ + pitch: PitchConfig; + /** The target notes and the retune time. */ + correction: CorrectionConfig; + /** The pitch multiplier, 0.25..=4. The default is 1. */ + pitchRatio: number; + /** The vocal-tract changes and aspiration. */ + formant: FormantConfig; + /** The voice arrangement. The default is `"choir"`. */ + mode: MultiVoiceMode; + /** The total number of choir voices, with the lead voice, 1..=16. The default is 1. */ + choirVoices: number; + /** The drift control for secondary voices, 10..=100, without a unit. The default is 50. */ + choirDetune: number; + /** The scale of the choir delay table, 20..=200, without a unit. The default is 60. */ + choirDelay: number; + /** The stereo width of the choir, 0..=100%. The default is 100%. */ + choirSpreadPercent: number; + /** Enables a stereo pan for each voice. The default is `false`. */ + stereoOutput: boolean; + /** The controls for the four harmony voices. */ + harmony: HarmonyConfig; + /** The linear gain of the four harmony voices, 0..=1. The default is 0.5. */ + harmonyGain: number; + /** The modulation depth, 0..=24, without a unit. The default is 0. */ + harmonicModulation: number; + /** The dry fraction at the resynthesis stage, 0..=1. The default is 0. */ + dryMix: number; + /** The 64-bit seed for choir drift and aspiration. The default is `0x1234_abcd`. */ + randomSeed: bigint; +} + +/** Reverse playback of recent stereo audio in repeated loops with fades. */ +export interface AlienConfig { + /** Selects reversed playback instead of the direct input. The default is `false`. */ + enabled: boolean; + /** The loop length in frames, 1..=96000. The default is 95,999. */ + loopFrames: number; +} + +/** The reverb after Alien, with controls for the network, the wet mix and the decay. */ +export interface ReverbConfig { + /** Enables the selected network. The default is `false`. */ + enabled: boolean; + /** The topology of the delay network. The default is `"echo"`. */ + mode: ReverbMode; + /** The wet fraction, 0..=1. The default is 0.5. */ + mix: number; + /** The diffusion control without a unit, 0..=1. The default is 0.5. */ + diffusion: number; + /** The feedback control without a unit, 0..=1. The default is 0.6. */ + decay: number; + /** The low-pass cutoff in hertz for damped paths, 80..=20000. The default is 4000 Hz. */ + brightnessHz: number; +} + +/** The settings for the complete signal chain, in the order of the stages. */ +export interface ProcessorConfig { + /** The input dynamics and saturation stage, which applies first. */ + punch: PunchConfig; + /** The asymmetric saturation stage after Punch. */ + warm: WarmConfig; + /** The stage for pitch analysis, correction, voice resynthesis and formants. */ + resynthesis: ResynthesisConfig; + /** The reverse-loop effect after resynthesis. */ + alien: AlienConfig; + /** The echo or reverberation stage after Alien. */ + reverb: ReverbConfig; + /** The linear gain after all effects, 0..=64. The default is 1. */ + outputGain: number; +} + +/** The supported MIDI note controls, with zero-based channel numbers. */ +export type MidiEvent = + | { type: "noteOn"; channel: number; note: number; velocity: number } + | { type: "noteOff"; channel: number; note: number } + | { type: "allNotesOff" }; + +/** A configuration or MIDI control that applies before a frame in the block. */ +export type ControlEvent = + | { type: "configure"; value: ProcessorConfig } + | { type: "resynthesis"; value: ResynthesisConfig } + | { type: "punch"; value: PunchConfig } + | { type: "warm"; value: WarmConfig } + | { type: "alien"; value: AlienConfig } + | { type: "reverb"; value: ReverbConfig } + | { type: "outputGain"; value: number } + | { type: "midi"; value: MidiEvent } + | { type: "correctionMidi"; value: MidiEvent } + | { type: "reset" }; + +/** + * A control that applies immediately before the zero-based input frame + * `offset`. + */ +export interface TimedEvent { + /** The frame offset in the block. */ + offset: number; + /** The control change. */ + event: ControlEvent; +} + +/** The events for one call that processes audio (`TimedEvent[]`). */ +export type BlockEvents = TimedEvent[]; + +/** A snapshot of the pitch analysis and the output level. */ +export interface Feedback { + /** The pitch-correction ratio from the last processed frame, where 1 is unity. */ + resampleRatio: number; + /** The reported input pitch period in samples. */ + periodSamples: number; + /** The reported input pitch frequency in hertz. */ + frequencyHz: number; + /** The correction target or the input pitch as a MIDI note, or `undefined` if `voiced` is `false`. */ + targetMidiNote: number | undefined; + /** `true` if the current pitch estimate is positive and inside the report bounds. */ + voiced: boolean; + /** The largest absolute clipped stereo sample in the window, divided by 32768. */ + peakLevel: number; + /** The number of frames processed since construction or the last reset. */ + processedFrames: bigint; + /** The nominal resynthesis latency in frames. */ + latencyFrames: number; +} + +/** A snapshot of the voices, the levels and the effect state for meters and displays. */ +export interface Telemetry { + /** The number of frames processed since construction or the last reset. */ + processedFrames: bigint; + /** The largest absolute input sample in the window, divided by 32768. */ + inputPeak: number; + /** The largest absolute clipped sample of the left and right output in the window, divided by 32768. */ + outputPeak: [number, number]; + /** The largest absolute wet contribution of the reverb in the window. */ + reverbWetPeak: number; + /** How periodic the tracked input is, in 0..=1. */ + clarity: number; + /** `true` while the pitch tracker follows a period. */ + tracking: boolean; + /** The number of valid entries in `voiceRatios` and `voiceGains`. */ + voiceCount: number; + /** The pitch ratio of each voice on the last frame, where 1 is the input pitch. */ + voiceRatios: [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + ]; + /** The linear gain of each voice, in the order of `voiceRatios`. */ + voiceGains: [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + ]; + /** The current drive of Punch, divided by its base drive. */ + punchGain: number; + /** The linear gain that Warm applies before its saturation curve and removes after it. */ + warmGain: number; + /** The length of the Alien loop in frames. */ + alienLoopFrames: number; + /** The current frame in the Alien loop. */ + alienPhaseFrames: number; + /** The count of formant analyses since construction, which wraps at `2^32`. */ + formantGeneration: number; +} + +/** A stateful 16-bit PCM processor instance. */ +export interface TuneletInstance { + /** Releases the Wasm memory of this processor instance. */ + free(): void; + /** Starts a finite tail budget and returns its frame count as a number. */ + beginDrain(): number; + /** Returns a copy of the active configuration as a new JavaScript object. */ + config(): ProcessorConfig; + /** Renders a mono tail block and returns its frame count. */ + drainMono(audio: Int16Array): number; + /** Renders stereo tail frames into `Int16Array` buffers of equal length. */ + drain(left: Int16Array, right: Int16Array): number; + /** Returns a new feedback object and does not clear the peak window. */ + feedback(): Feedback; + /** Writes the formant envelopes of the current model into two `Float32Array` buffers of equal length. */ + formantEnvelope( + max_frequency_hz: number, + input: Float32Array, + output: Float32Array, + ): boolean; + /** Replaces the audio in a mono `Int16Array` with the stereo downmix. */ + processMono(audio: Int16Array, events?: BlockEvents | null): void; + /** Processes mono input into left and right `Int16Array` buffers of equal length. */ + process( + input: Int16Array, + left: Int16Array, + right: Int16Array, + events?: BlockEvents | null, + ): void; + /** Resets the audio histories and feedback, as the native processor does. */ + reset(): void; + /** Decodes and validates a configuration, then replaces the complete configuration with it. */ + setConfig(config: ProcessorConfig): void; + /** Returns the tail budget of the current configuration. */ + tailFrames(): number; + /** Returns the feedback and clears only the stereo peak window. */ + takeFeedback(): Feedback; + /** Returns the telemetry and clears only its three peak windows. */ + takeTelemetry(): Telemetry; + /** Returns a new telemetry object and does not clear its peak windows. */ + telemetry(): Telemetry; + /** The nominal resynthesis latency: 1,593 frames at both sample rates. */ + readonly latencyFrames: number; + /** The maximum frame count for each call that processes or drains audio. */ + readonly maxBlockFrames: number; + /** The sample rate of the input and the output in hertz. */ + readonly sampleRate: number; +} + +/** A stateful 16-bit PCM processor instance. */ +export type Tunelet = TuneletInstance; + +/** The constructor interface of the `Tunelet` class. */ +export interface TuneletConstructor { + readonly prototype: Tunelet; + /** + * Prepares a processor and its reusable PCM buffers. + * + * `sample_rate` must be 44100 or 48000. `max_block_frames` must be an + * integer in 1..=4294967295. If you omit `config`, the processor uses the + * default configuration. + */ + new ( + sample_rate: number, + max_block_frames: number, + config?: ProcessorConfig | null, + ): Tunelet; +} + +/** A structural URL object with a protocol and a full `href` string. */ +export interface WasmUrlLike { + readonly href: string; + readonly protocol: string; +} + +/** A structural fetch `Request` object. */ +export interface WasmRequestLike { + readonly url: string; + readonly headers: unknown; +} + +/** A structural fetch `Response` object. */ +export interface WasmResponseLike { + readonly ok: boolean; + readonly status: number; + arrayBuffer(): Promise; +} + +/** + * A structural guard for a precompiled Wasm module object. + * + * Host `Module` interfaces have no own properties. The excluded keys reject + * URLs, fetch objects, promises and option wrappers. + */ +export interface WasmCompiledModule { + readonly href?: never; + readonly module?: never; + readonly module_or_path?: never; + readonly then?: never; + readonly url?: never; +} + +/** Raw Wasm bytes in an `ArrayBuffer` or a typed view. */ +export type WasmByteSource = ArrayBufferLike | ArrayBufferView; + +/** A synchronous Wasm source: raw bytes or a precompiled module object. */ +export type WasmSyncInitInput = WasmByteSource | (object & WasmCompiledModule); + +/** + * An asynchronous Wasm source: a URL string, a URL object, a fetch request or + * response, raw bytes or a precompiled module object. + */ +export type WasmInitInput = + | string + | WasmUrlLike + | WasmRequestLike + | WasmResponseLike + | WasmSyncInitInput; + +/** Linear Wasm memory exported by an initialized module instance. */ +export interface WasmMemory { + readonly buffer: ArrayBufferLike; +} + +/** The public exports of an initialized Wasm instance. */ +export interface WasmInitOutput { + readonly memory: WasmMemory; +} + +/** Alias of `WasmSyncInitInput` for compatibility. */ +export type SyncInitInput = WasmSyncInitInput; + +/** Alias of `WasmInitInput` for compatibility. */ +export type InitInput = WasmInitInput; + +/** Alias of `WasmInitOutput` for compatibility. */ +export type InitOutput = WasmInitOutput; diff --git a/src/wasm.ts b/src/wasm.ts new file mode 100644 index 0000000..73486c1 --- /dev/null +++ b/src/wasm.ts @@ -0,0 +1,78 @@ +/** + * The direct Wasm initialization entry point (`tunelet/wasm`). + * + * Use this subpath in workers or AudioWorklet processors when you initialize + * the Wasm binary directly with `initSync` or the default initializer. + */ +import rawInit, { + Tunelet as RawTunelet, + defaultConfig as rawDefaultConfig, + initSync as rawInitSync, +} from "../pkg/tunelet.js"; +import type { + ProcessorConfig, + TuneletConstructor, + TuneletInstance, + WasmInitInput, + WasmInitOutput, + WasmSyncInitInput, +} from "./types.js"; + +export type * from "./types.js"; + +/** A stateful 16-bit PCM processor instance. */ +export type Tunelet = TuneletInstance; + +/** A stateful 16-bit PCM processor class. */ +export const Tunelet: TuneletConstructor = RawTunelet; + +/** + * Returns a complete, independent default configuration for JavaScript. + * + * Change its fields and give it to `Tunelet` or to `setConfig`. + */ +export const defaultConfig: () => ProcessorConfig = rawDefaultConfig; + +/** + * Instantiates the Wasm module synchronously from raw bytes or a precompiled + * module object. + */ +export function initSync( + module: { readonly module: WasmSyncInitInput } | WasmSyncInitInput, +): WasmInitOutput { + return ( + rawInitSync as ( + input: { readonly module: WasmSyncInitInput } | WasmSyncInitInput, + ) => WasmInitOutput + )(module); +} + +/** + * Initializes the Wasm module asynchronously from a URL, fetch object, raw + * bytes or precompiled module object. + */ +export default function init( + module_or_path?: + | { + readonly module_or_path?: + | WasmInitInput + | Promise + | undefined; + } + | WasmInitInput + | Promise, +): Promise { + return ( + rawInit as ( + input?: + | { + readonly module_or_path?: + | WasmInitInput + | Promise + | undefined; + } + | WasmInitInput + | Promise, + ) => Promise + )(module_or_path); +} diff --git a/tsconfig.json b/tsconfig.json index 27aa560..f939c05 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,10 +6,11 @@ "lib": ["ES2020", "ESNext.Disposable", "DOM"], "types": ["node"], "strict": true, + "exactOptionalPropertyTypes": true, "declaration": true, "noEmitOnError": true, "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": ["src/index.ts", "src/types.ts", "src/wasm.ts"] }