From c1dc3b3d07adaa3bf75d5d7f9efa62a03672ca9c 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 04:14:06 +0000 Subject: [PATCH] feat(npm): add conditional Node.js and browser package entries - Split src/index.ts into src/node.ts, src/browser.ts and src/shared.ts - Export conditional node and default entries and .wasm subpaths - Sanitize pkg/tunelet.d.ts in scripts/postbuild-wasm.mjs - Accept file: strings, cross-realm URLs and flat bundles in Node.js - Decode undefined HarmonyConfig.voices as 4 for strict TypeScript - Verify archive files, runtime loaders and four tsc profiles --- README.md | 54 ++-- package.json | 22 +- scripts/postbuild-wasm.mjs | 107 +++++++ scripts/verify-pack.mjs | 571 ++++++++++++++++++++++++++++++++----- src/browser.ts | 56 ++++ src/harmony.rs | 19 +- src/index.ts | 84 ------ src/node.ts | 166 +++++++++++ src/shared.ts | 41 +++ tsconfig.json | 5 +- 10 files changed, 933 insertions(+), 192 deletions(-) create mode 100644 scripts/postbuild-wasm.mjs create mode 100644 src/browser.ts delete mode 100644 src/index.ts create mode 100644 src/node.ts create mode 100644 src/shared.ts diff --git a/README.md b/README.md index 83a8f47..aaf8f35 100644 --- a/README.md +++ b/README.md @@ -359,12 +359,13 @@ For `wasm32-unknown-unknown`, the optional `wasm` feature of the crate gives JavaScript bindings and generated TypeScript declarations. The npm package contains these bindings. -The npm package is one ES module for both browsers and Node.js. It contains -these items: +The npm package gives conditional ES module entries for Node.js and browsers. +It contains these items: - One Wasm binary. - The generated bindings. -- A shared `loadTunelet` entry point. +- Conditional `node` (`dist/node.js`) and `default` (`dist/browser.js`) + `loadTunelet` entries with the same API. ### Load the module @@ -372,41 +373,46 @@ Both environments use the same imports and the same initialization call. An import of the package does not load the binary. Call `loadTunelet()` before you use `Tunelet` or `defaultConfig()`. -- Node.js reads the packaged binary from a file URL relative to the module. -- Browsers fetch the served Wasm asset. +- Node.js reads `../pkg/tunelet_bg.wasm` relative to `dist/node.js`. If a + bundler moves the entry, Node.js resolves `pkg/tunelet_bg.wasm` from the + installed package. +- Browsers use `dist/browser.js` and fetch the served Wasm asset without + Node.js imports. Concurrent calls share one initialization promise. The package keeps the result of a successful initialization. If a load fails, the promise rejects, -and you can try again. A Node.js file error goes to the caller. +and you can try again. File, network and Wasm errors go to the caller. For a custom asset location, give one of these sources to `loadTunelet(source)`: -- A URL. -- A fetch Response. +- A URL or 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(source)` reads `file:` URL objects and `file:` URL +strings 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 -initializer and `initSync`. The package root re-exports `initSync` too. Use -only one initialization entry point for each module instance. The package -gives only ESM exports. CommonJS applications can use `await import("tunelet")`. +initializer and `initSync`. The package also exports +`tunelet/pkg/tunelet_bg.wasm` and `tunelet/tunelet_bg.wasm` for asset +resolution. The package root re-exports `initSync` too. Use only one +initialization entry point for each module instance. The package gives only +ESM exports. CommonJS applications can use `await import("tunelet")`. ### Deployment Browser bundlers must keep or emit the Wasm asset that -`new URL(..., import.meta.url)` refers to. For a browser deployment without a -bundler, do these steps: +`new URL(..., import.meta.url)` refers to, or resolve `tunelet/tunelet_bg.wasm`. +For a browser deployment without a bundler, do these steps: 1. Serve `dist/` and `pkg/`, and keep their relative layout. -2. Map the `tunelet` import to `dist/index.js`, or import that URL directly. +2. Map the `tunelet` import to `dist/browser.js`, or import that URL directly. Serve the assets over HTTP(S). The package does not support a local `file:` page that opens the JavaScript. @@ -452,9 +458,9 @@ and show enums as string literals. To change the configuration, do these steps: If a required field is absent or a value is not valid, the call throws a JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust -types. +to 4 if it is absent or `undefined`. The conversion ignores extra object +properties. The generated declarations contain the parameter documentation +from the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use @@ -558,7 +564,7 @@ npm pack ``` `npm run check:wasm` runs Clippy and rustdoc for `wasm32-unknown-unknown`. -`npm pack` builds the Wasm bindings and the TypeScript entry point. Then it +`npm pack` builds the Wasm bindings and the TypeScript entries. Then it creates `tunelet-.tgz`. To use this archive in a browser project or a Node.js project, install it with this command: @@ -567,10 +573,10 @@ npm install /path/to/tunelet-.tgz ``` To build without an archive, run `npm run build`. The build writes one -`web`-target binding into `pkg/` and the shared entry into `dist/`. Git +`web`-target binding into `pkg/` and the package entries into `dist/`. Git ignores both directories. The archive contains only these items: -- The runtime entry. +- The runtime entries. - The declarations. - The bindings. - The binary. diff --git a/package.json b/package.json index 8c201f6..b3b0b27 100644 --- a/package.json +++ b/package.json @@ -8,17 +8,25 @@ "url": "git+https://github.com/ByteLandTechnology/tunelet.git" }, "type": "module", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", + "main": "./dist/browser.js", + "types": "./dist/browser.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.js" + "node": { + "types": "./dist/node.d.ts", + "default": "./dist/node.js" + }, + "default": { + "types": "./dist/browser.d.ts", + "default": "./dist/browser.js" + } }, "./wasm": { "types": "./pkg/tunelet.d.ts", "import": "./pkg/tunelet.js" - } + }, + "./pkg/tunelet_bg.wasm": "./pkg/tunelet_bg.wasm", + "./tunelet_bg.wasm": "./pkg/tunelet_bg.wasm" }, "files": [ "dist", @@ -29,8 +37,8 @@ "sideEffects": false, "scripts": { "build": "npm run build:wasm && npm run build:ts", - "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('pkg/.gitignore', { force: true })\"", - "build:ts": "tsc", + "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node scripts/postbuild-wasm.mjs", + "build:ts": "node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('dist', { recursive: true, force: true })\" && tsc", "check:wasm": "cargo clippy --locked --lib --target wasm32-unknown-unknown --features wasm -- -D warnings && cargo doc --locked --no-deps --target wasm32-unknown-unknown --features wasm", "prepack": "npm run build", "verify:pack": "node scripts/verify-pack.mjs" diff --git a/scripts/postbuild-wasm.mjs b/scripts/postbuild-wasm.mjs new file mode 100644 index 0000000..1c04ba7 --- /dev/null +++ b/scripts/postbuild-wasm.mjs @@ -0,0 +1,107 @@ +/** + * Removes `pkg/.gitignore` and replaces ambient `DOM`, `WebAssembly` and + * `Symbol.dispose` declarations in `pkg/tunelet.d.ts`. + */ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const pkgDir = fileURLToPath(new URL("../pkg", import.meta.url)); +const gitignorePath = path.join(pkgDir, ".gitignore"); +const declarationsPath = path.join(pkgDir, "tunelet.d.ts"); + +fs.rmSync(gitignorePath, { force: true }); + +const STRUCTURAL_WASM_TYPES = [ + "type WasmBufferSource = ArrayBuffer | ArrayBufferView;", + "interface WasmUrl {", + " readonly href: string;", + " readonly protocol: string;", + "}", + "interface WasmRequest {", + " readonly url: string;", + " arrayBuffer(): Promise;", + "}", + "interface WasmResponse {", + " readonly ok: boolean;", + " readonly status: number;", + " readonly statusText: string;", + " readonly url: string;", + " arrayBuffer(): Promise;", + "}", + "interface WasmMemory {", + " readonly buffer: ArrayBuffer;", + " grow(delta: number): number;", + "}", + "interface WasmTable {", + " readonly length: number;", + " get(index: number): any;", + " grow(delta: number, value?: any): number;", + " set(index: number, value?: any): void;", + "}", + "type WasmModule = object;", + "export type InitInput = string | WasmRequest | WasmUrl | WasmResponse | WasmBufferSource | WasmModule;", +].join("\n"); + +/** Replaces one required pattern in `source` and checks that it matched. */ +function replaceRequired(source, pattern, replacement, label) { + assert.match(source, pattern, `Expected ${label} in pkg/tunelet.d.ts`); + return source.replace(pattern, replacement); +} + +let declarations = fs.readFileSync(declarationsPath, "utf8"); + +declarations = replaceRequired( + declarations, + /^[ \t]*\[Symbol\.dispose\]\(\): void;\r?\n/m, + "", + "[Symbol.dispose](): void", +); +declarations = replaceRequired( + declarations, + /^export type InitInput = RequestInfo \| URL \| Response \| BufferSource \| WebAssembly\.Module;$/m, + STRUCTURAL_WASM_TYPES, + "InitInput declaration", +); +declarations = replaceRequired( + declarations, + /^([ \t]*readonly memory: )WebAssembly\.Memory;$/m, + "$1WasmMemory;", + "InitOutput.memory declaration", +); +declarations = replaceRequired( + declarations, + /^([ \t]*readonly __wbindgen_externrefs: )WebAssembly\.Table;$/m, + "$1WasmTable;", + "InitOutput.__wbindgen_externrefs declaration", +); +declarations = replaceRequired( + declarations, + /^export type SyncInitInput = BufferSource \| WebAssembly\.Module;$/m, + "export type SyncInitInput = WasmBufferSource | WasmModule;", + "SyncInitInput declaration", +); + +const withoutComments = declarations + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/\/\/.*$/gm, ""); + +for (const forbidden of [ + /Symbol\.dispose/, + /\bWebAssembly\b/, + /\bRequestInfo\b/, + /\bBufferSource\b/, + /\bResponse\b/, + /\bURL\b/, + /\bdeclare\s+global\b/, + /\/\/\/\s* rootModule.loadTunelet(absentUrl));", + "", + "const fileString = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + 'assert.match(fileString, /^file:/);', + "await rootModule.loadTunelet(fileString);", + "const processor = new rootModule.Tunelet(48000, 64);", + "try {", + " assert.equal(processor.sampleRate, 48000);", "} finally {", " processor.free();", "}", + ], + [packageName], + ); + + runNodeCheck( + consumerDir, + "check-cross-realm-url.mjs", + [ + 'import assert from "node:assert/strict";', "", - ].join("\n"), + "const packageName = process.argv[2];", + "const rootModule = await import(packageName);", + "const href = import.meta.resolve(`${packageName}/tunelet_bg.wasm`);", + 'const crossRealmUrl = { href, protocol: "file:" };', + "assert.equal(crossRealmUrl instanceof URL, false);", + "await rootModule.loadTunelet(crossRealmUrl);", + "assert.equal(rootModule.defaultConfig().resynthesis.harmony.voices, 4);", + ], + [packageName], + ); + + const relocatedDir = path.join(consumerDir, "relocated"); + fs.mkdirSync(path.join(relocatedDir, "dist"), { recursive: true }); + fs.mkdirSync(path.join(relocatedDir, "pkg"), { recursive: true }); + for (const file of ["node.js", "shared.js"]) { + fs.copyFileSync( + path.join(installedDir, "dist", file), + path.join(relocatedDir, "dist", file), + ); + } + fs.copyFileSync( + path.join(installedDir, "pkg", "tunelet.js"), + path.join(relocatedDir, "pkg", "tunelet.js"), + ); + + const flatBundlePath = path.join(consumerDir, "flat-node-bundle.mjs"); + const wasmGlue = fs + .readFileSync(path.join(installedDir, "pkg", "tunelet.js"), "utf8") + .replace( + "export { initSync, __wbg_init as default };", + "const init = __wbg_init;\nexport { initSync };", + ); + const sharedGlue = fs + .readFileSync(path.join(installedDir, "dist", "shared.js"), "utf8") + .replace(/^import init from "\.\.\/pkg\/tunelet\.js";\r?\n/m, "") + .replace(/^export \{ init \};\r?\n/m, "") + .replace(/^export function loadOnce\(/m, "function loadOnce("); + const nodeGlue = fs + .readFileSync(path.join(installedDir, "dist", "node.js"), "utf8") + .replace(/^import \{ init, loadOnce \} from "\.\/shared\.js";\r?\n/m, "") + .replace(/^export \* from "\.\.\/pkg\/tunelet\.js";\r?\n/m, ""); + fs.writeFileSync( + flatBundlePath, + `${wasmGlue}\n${sharedGlue}\n${nodeGlue}\n`, + "utf8", ); - execFileSync(process.execPath, [checkPath, packageName], { + runNodeCheck(consumerDir, "check-flat-bundle.mjs", [ + 'import assert from "node:assert/strict";', + 'import * as relocated from "./relocated/dist/node.js";', + "", + "await relocated.loadTunelet();", + "assert.equal(relocated.defaultConfig().resynthesis.harmony.voices, 4);", + ]); + + runNodeCheck(consumerDir, "check-inlined-flat-bundle.mjs", [ + 'import assert from "node:assert/strict";', + 'import * as flatBundle from "./flat-node-bundle.mjs";', + "", + "await flatBundle.loadTunelet();", + "const processor = new flatBundle.Tunelet(48000, 64);", + "try {", + " const audio = new Int16Array(64);", + " processor.processMono(audio);", + "} finally {", + " processor.free();", + "}", + ]); + + const corruptDir = path.join(consumerDir, "corrupt"); + fs.mkdirSync(path.join(corruptDir, "dist"), { recursive: true }); + fs.mkdirSync(path.join(corruptDir, "pkg"), { recursive: true }); + for (const file of ["node.js", "shared.js"]) { + fs.copyFileSync( + path.join(installedDir, "dist", file), + path.join(corruptDir, "dist", file), + ); + } + fs.copyFileSync( + path.join(installedDir, "pkg", "tunelet.js"), + path.join(corruptDir, "pkg", "tunelet.js"), + ); + fs.writeFileSync( + path.join(corruptDir, "pkg", "tunelet_bg.wasm"), + Uint8Array.of(0, 97, 115, 109, 99), + ); + + runNodeCheck(consumerDir, "check-corrupt-wasm.mjs", [ + 'import assert from "node:assert/strict";', + 'import * as corrupt from "./corrupt/dist/node.js";', + "", + "await assert.rejects(() => corrupt.loadTunelet(), WebAssembly.CompileError);", + ]); +} + +/** Run `tsc` with a strict profile configuration and zero `skipLibCheck`. */ +function runTscProfile(consumerDir, tscBin, profileName, compilerOptions, code) { + const tsPath = path.join(consumerDir, `check-${profileName}.ts`); + const configPath = path.join(consumerDir, `tsconfig.${profileName}.json`); + fs.writeFileSync(tsPath, `${code.join("\n")}\n`, "utf8"); + fs.writeFileSync( + configPath, + JSON.stringify( + { + compilerOptions: { + strict: true, + exactOptionalPropertyTypes: true, + noEmit: true, + ...compilerOptions, + }, + files: [tsPath], + }, + null, + 2, + ), + "utf8", + ); + execFileSync(process.execPath, [tscBin, "-p", configPath], { cwd: consumerDir, stdio: "inherit", }); } -/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ +/** Check strict TypeScript resolution across Node, ES2023, DOM and WebWorker. */ function verifyTypeDeclarations(consumerDir, packageName) { - const checkTsPath = path.join(consumerDir, "check.ts"); const pkgLiteral = JSON.stringify(packageName); const wasmLiteral = JSON.stringify(`${packageName}/wasm`); - fs.writeFileSync( - checkTsPath, - [ - "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};`, - "", - "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);", - " processor.free();", - " void rootInitSync;", - " void wasmInitSync;", - " void exportsFromRoot;", - " void exportsFromNamed;", - " void exportsFromWasm;", - "}", - "", - ].join("\n"), - ); - const tscBin = path.join( repoRoot, "node_modules", @@ -237,23 +508,175 @@ function verifyTypeDeclarations(consumerDir, packageName) { "bin", "tsc", ); - execFileSync( - process.execPath, + const nodeTypesPath = path.join(repoRoot, "node_modules", "@types", "node"); + + const sharedAssertions = [ + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " loadTunelet as namedLoadTunelet,", + " Tunelet,", + " type HarmonyConfig,", + " type ProcessorConfig,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + `} from ${wasmLiteral};`, + "", + "export async function verifyShared(", + " source?: InitInput,", + " optionalVoices?: number,", + "): Promise {", + " const exportsFromRoot: InitOutput = await loadTunelet(source);", + " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", + " const exportsFromWasm: InitOutput = await init(source);", + " const config: ProcessorConfig = defaultConfig();", + " const harmony: HarmonyConfig = {", + " ...config.resynthesis.harmony,", + " voices: optionalVoices,", + " };", + " config.resynthesis.harmony = harmony;", + " config.resynthesis.harmony.voices = undefined;", + " const processor = new Tunelet(48000, 128, config);", + " const input = new Int16Array(128);", + " const left = new Int16Array(128);", + " const right = new Int16Array(128);", + " processor.setConfig(config);", + " processor.process(input, left, right);", + " processor.processMono(input, [", + " {", + " offset: 0,", + " event: {", + ' type: "resynthesis",', + " value: {", + " ...config.resynthesis,", + " harmony: {", + " ...config.resynthesis.harmony,", + " voices: optionalVoices,", + " },", + " },", + " },", + " },", + " ]);", + " processor.free();", + " void rootInitSync(new Uint8Array(8));", + " void wasmInitSync({ module: new ArrayBuffer(8) });", + " void exportsFromRoot.memory.buffer;", + " void exportsFromNamed;", + " void exportsFromWasm;", + "}", + ]; + + runTscProfile( + consumerDir, + tscBin, + "node", + { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2022"], + types: [nodeTypesPath], + }, + [ + ...sharedAssertions, + "", + "export async function verifyNodeInputs(): Promise {", + ' await loadTunelet("file:///tmp/tunelet_bg.wasm");', + ' await loadTunelet(new URL("file:///tmp/tunelet_bg.wasm"));', + " await loadTunelet(Buffer.alloc(8));", + "}", + ], + ); + + runTscProfile( + consumerDir, + tscBin, + "es2023-bundler", + { + target: "ES2022", + module: "ES2022", + moduleResolution: "Bundler", + lib: ["ES2023"], + types: [], + }, + [ + ...sharedAssertions, + "", + "export async function verifyEs2023Inputs(): Promise {", + ' await loadTunelet("https://example.com/tunelet_bg.wasm");', + " await loadTunelet(new Uint8Array(8));", + " await loadTunelet(new ArrayBuffer(8));", + "}", + ], + ); + + runTscProfile( + consumerDir, + tscBin, + "es2023-nodenext", + { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2023"], + types: [], + }, + sharedAssertions, + ); + + runTscProfile( + consumerDir, + tscBin, + "dom", + { + target: "ES2022", + module: "ES2022", + moduleResolution: "Bundler", + lib: ["ES2022", "DOM"], + types: [], + }, [ - tscBin, - "--noEmit", - "--module", - "NodeNext", - "--moduleResolution", - "NodeNext", - "--target", - "ES2020", - "--lib", - "ES2020,ESNext.Disposable,DOM", - "--strict", - checkTsPath, + ...sharedAssertions, + "", + "export async function verifyDomInputs(", + " compiled: WebAssembly.Module,", + "): Promise {", + ' await loadTunelet(new URL("./tunelet_bg.wasm", import.meta.url));', + ' await loadTunelet(new Request("https://example.com/tunelet_bg.wasm"));', + ' await loadTunelet(fetch("https://example.com/tunelet_bg.wasm"));', + " await loadTunelet(compiled);", + " void rootInitSync({ module: compiled });", + "}", + ], + ); + + runTscProfile( + consumerDir, + tscBin, + "webworker", + { + target: "ES2022", + module: "ES2022", + moduleResolution: "Bundler", + lib: ["ES2022", "WebWorker"], + types: [], + }, + [ + ...sharedAssertions, + "", + "export async function verifyWorkerInputs(", + " compiled: WebAssembly.Module,", + "): Promise {", + ' await loadTunelet(new URL("./tunelet_bg.wasm", self.location.href));', + ' await loadTunelet(new Request("https://example.com/tunelet_bg.wasm"));', + ' await loadTunelet(fetch("https://example.com/tunelet_bg.wasm"));', + " await loadTunelet(compiled);", + " void rootInitSync({ module: compiled });", + "}", ], - { cwd: consumerDir, stdio: "inherit" }, ); } @@ -268,8 +691,14 @@ try { const relativeArchivePath = packArchive(packDir); verifyArchiveEntries(tempDir, relativeArchivePath); - installArchive(tempDir, relativeArchivePath, consumerDir, packageName); - verifyRuntimeImport(consumerDir, packageName); + const installedDir = installArchive( + tempDir, + relativeArchivePath, + consumerDir, + packageName, + ); + verifyInstalledFiles(installedDir); + verifyRuntimeImport(consumerDir, installedDir, packageName); verifyTypeDeclarations(consumerDir, packageName); } finally { fs.rmSync(tempDir, { recursive: true, force: true }); diff --git a/src/browser.ts b/src/browser.ts new file mode 100644 index 0000000..0de17aa --- /dev/null +++ b/src/browser.ts @@ -0,0 +1,56 @@ +/** + * The ESM entry point for browsers, workers and bundlers. + * + * Call `loadTunelet()` before you construct processors or read the default + * configuration. 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. + */ +import { init, loadOnce } from "./shared.js"; +import type { InitInput, InitOutput } from "./shared.js"; + +export * from "../pkg/tunelet.js"; + +/** + * Initializes the Wasm module one time for this imported package instance. + * + * If you give no argument, the function fetches the packaged binary relative + * to this module. An import of the package does not load Wasm. Serve the + * assets over HTTP(S), or give the bytes or a compiled module as the source. + * + * For a custom deployment, you can give one of these sources: + * + * - A URL or URL string. + * - A fetch Request or Response. + * - A byte buffer (ArrayBuffer or ArrayBufferView). + * - A compiled WebAssembly.Module. + * - A promise for one of these. + * + * A compiled 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 + * Wasm again, whatever their arguments are. If an attempt fails, the promise + * rejects and the function clears the cached promise. Then you can try again. + * Network and Wasm errors go to the caller. The function does not try a + * different load method after an error. + * + * @param source The optional Wasm source. The default is the binary in this + * package. + * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class + * for processors. + */ +export function loadTunelet( + source?: InitInput | Promise, +): Promise { + return loadOnce(source, (resolved) => { + const input = + resolved === undefined + ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) + : resolved; + return init({ module_or_path: input }); + }); +} + +/** The default export is the same function as `loadTunelet`. */ +export default loadTunelet; diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..6cfa8b6 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 + /// the field is absent or `undefined`, it gets the default. #[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,17 @@ fn default_voices() -> u8 { HARMONY_VOICES as u8 } +/// Decodes an optional interval voice count, where `undefined` gives the +/// default. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_voices<'de, D>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, +{ + use serde::Deserialize; + Ok(Option::::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 deleted file mode 100644 index 8526d77..0000000 --- a/src/index.ts +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 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. - */ -import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; - -export * from "../pkg/tunelet.js"; - -/** The shared initialization promise, which a failure clears. */ -let initialization: Promise | undefined; - -/** - * Initializes the Wasm module one time for this imported package instance. - * - * 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. - * - * 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 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. - * - * 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 - * Wasm again, whatever their arguments are. If an attempt fails, the promise - * rejects and the function clears the cached promise. Then you can try again. - * File, network and Wasm errors go to the caller. The function does not try a - * different load method after an error. - * - * @param source The optional Wasm source. The default is the binary in this - * package. - * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class - * for processors. - */ -export function loadTunelet( - source?: InitInput | Promise, -): Promise { - initialization ??= initialize(source).catch((error: unknown) => { - initialization = undefined; - throw error; - }); - return initialization; -} - -/** Awaits the source one time, then initializes the Wasm module from it. */ -async function initialize( - source: InitInput | 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:") { - // 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. - const moduleName = "node:fs/promises"; - 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: input }); -} - -/** The default export is the same function as `loadTunelet`. */ -export default loadTunelet; diff --git a/src/node.ts b/src/node.ts new file mode 100644 index 0000000..2dd7bb5 --- /dev/null +++ b/src/node.ts @@ -0,0 +1,166 @@ +/** + * The ESM entry point for Node.js. + * + * Call `loadTunelet()` before you construct processors or read the default + * configuration. 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. + */ +import { readFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import { init, loadOnce } from "./shared.js"; +import type { InitInput, InitOutput } from "./shared.js"; + +export * from "../pkg/tunelet.js"; + +/** Package subpaths for bundled Node.js scripts without `../pkg/`. */ +const PACKAGE_WASM_SPECIFIERS = [ + "tunelet/pkg/tunelet_bg.wasm", + "@bytelandtechnology/tunelet/pkg/tunelet_bg.wasm", +] as const; + +/** + * Initializes the Wasm module one time for this imported package instance. + * + * If you give no argument, the function reads the packaged binary relative to + * this module. If a bundler moves this module and `../pkg/tunelet_bg.wasm` is + * absent, the function resolves `pkg/tunelet_bg.wasm` from the installed + * package. An import of the package does not load Wasm. + * + * For a custom deployment, you can give one of these sources: + * + * - A URL or URL string, which includes `file:` URLs. + * - A fetch Request or Response. + * - A byte buffer (ArrayBuffer or ArrayBufferView). + * - A compiled WebAssembly.Module. + * - A promise for one of these. + * + * Non-`file:` string sources obey fetch rules. A compiled 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 + * Wasm again, whatever their arguments are. If an attempt fails, the promise + * rejects and the function clears the cached promise. Then you can try again. + * File, network and Wasm errors go to the caller. The function does not try a + * different load method after Wasm corruption or an invalid explicit source. + * + * @param source The optional Wasm source. The default is the binary in this + * package. + * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class + * for processors. + */ +export function loadTunelet( + source?: InitInput | Promise, +): Promise { + return loadOnce(source, initializeNode); +} + +/** Loads the default binary or an explicit Node.js or fetch source. */ +async function initializeNode( + source: InitInput | undefined, +): Promise { + if (source === undefined) { + return init({ module_or_path: await readDefaultWasm() }); + } + + if (typeof source === "string") { + if (/^file:/i.test(source)) { + return init({ module_or_path: await readFile(new URL(source)) }); + } + return init({ module_or_path: source }); + } + + if (isUrlLike(source)) { + const url = source instanceof URL ? source : new URL(source.href); + if (url.protocol === "file:") { + return init({ module_or_path: await readFile(url) }); + } + return init({ module_or_path: url }); + } + + return init({ module_or_path: source }); +} + +/** + * Reads `../pkg/tunelet_bg.wasm` first, or resolves the installed package + * binary if the relative path is absent. + */ +async function readDefaultWasm(): Promise { + let absentError: unknown; + if (typeof import.meta.url === "string") { + try { + return await readFile(new URL("../pkg/tunelet_bg.wasm", import.meta.url)); + } catch (error: unknown) { + if (!hasErrorCode(error, "ENOENT") && !hasErrorCode(error, "ENOTDIR")) { + throw error; + } + absentError = error; + } + } + + const baseUrl = + typeof import.meta.url === "string" + ? import.meta.url + : pathToFileURL(`${process.cwd()}/`).href; + const nodeRequire = createRequire(baseUrl); + + for (const specifier of PACKAGE_WASM_SPECIFIERS) { + let resolvedPath: string; + try { + resolvedPath = nodeRequire.resolve(specifier); + } catch (error: unknown) { + if ( + hasErrorCode(error, "MODULE_NOT_FOUND") || + hasErrorCode(error, "ERR_MODULE_NOT_FOUND") + ) { + continue; + } + throw error; + } + return readFile(resolvedPath); + } + + if (absentError !== undefined) { + throw absentError; + } + throw new Error("Cannot find the packaged tunelet_bg.wasm binary."); +} + +/** Checks if an object is a native `URL` or a cross-realm `URL` instance. */ +function isUrlLike( + value: unknown, +): value is { readonly href: string; readonly protocol: string } { + if (value instanceof URL) { + return true; + } + if ( + typeof value !== "object" || + value === null || + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer + ) { + return false; + } + const candidate = value as { + readonly href?: unknown; + readonly protocol?: unknown; + }; + return ( + typeof candidate.href === "string" && typeof candidate.protocol === "string" + ); +} + +/** Checks if an error object has a specific Node.js `code` string. */ +function hasErrorCode(error: unknown, code: string): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error as { readonly code?: unknown }).code === code + ); +} + +/** The default export is the same function as `loadTunelet`. */ +export default loadTunelet; diff --git a/src/shared.ts b/src/shared.ts new file mode 100644 index 0000000..9eaf8a1 --- /dev/null +++ b/src/shared.ts @@ -0,0 +1,41 @@ +/** + * Shared Wasm bindings and initialization state for the package entries. + */ +import init from "../pkg/tunelet.js"; +import type { InitInput, InitOutput } from "../pkg/tunelet.js"; + +export { init }; +export type { InitInput, InitOutput }; + +/** The shared initialization promise, which a failure clears. */ +let initialization: Promise | undefined; + +/** + * Runs one shared initialization attempt and clears the cached promise if the + * attempt fails. + */ +export function loadOnce( + source: InitInput | Promise | undefined, + load: (source: InitInput | undefined) => Promise, +): Promise { + initialization ??= resolveAndLoad(source, load).catch((error: unknown) => { + initialization = undefined; + throw error; + }); + return initialization; +} + +/** Awaits an explicit source, rejects `undefined` results and loads Wasm. */ +async function resolveAndLoad( + source: InitInput | Promise | undefined, + load: (source: InitInput | undefined) => Promise, +): Promise { + if (source === undefined) { + return load(undefined); + } + const resolved = await source; + if (resolved === undefined) { + throw new TypeError("The Wasm source must not be undefined."); + } + return load(resolved); +} diff --git a/tsconfig.json b/tsconfig.json index 27aa560..8410e09 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,13 +3,14 @@ "target": "ES2020", "module": "NodeNext", "moduleResolution": "NodeNext", - "lib": ["ES2020", "ESNext.Disposable", "DOM"], + "lib": ["ES2020"], "types": ["node"], "strict": true, + "exactOptionalPropertyTypes": true, "declaration": true, "noEmitOnError": true, "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": ["src/browser.ts", "src/node.ts", "src/shared.ts"] }