diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5513256..2f00dbc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,11 +1,11 @@ # Continuous integration for the Rust crate, the Wasm bindings and the # npm package. # -# First, build-wasm checks the Rust lints, the docs, the crate archive and the -# Wasm target on Linux, then uploads pkg/. In parallel, msrv checks -# rust-version from Cargo.toml. Next, check-os builds the native library, -# compiles TypeScript and checks the npm archives on Linux, macOS and Windows. -# Last, verify reports one status check for branch protection. +# First, build-wasm checks the lints, Biome, the docs, the crate archive, the +# Wasm target and TypeScript on Linux, then uploads pkg/. In parallel, msrv +# checks rust-version from Cargo.toml. Next, check-os builds the native +# library, compiles TypeScript and checks the npm archives on Linux, macOS and +# Windows. Last, verify reports one status check for branch protection. name: CI on: @@ -34,15 +34,18 @@ jobs: - uses: ./.github/actions/setup-wasm with: components: rustfmt, clippy - node-cache: "" - run: cargo fmt --check - run: cargo clippy --locked --lib -- -D warnings - run: cargo doc --locked --no-deps env: RUSTDOCFLAGS: "-D warnings" - run: cargo package --locked + - run: npm ci + - run: npm run lint + - run: npm run format:check - run: npm run check:wasm - run: npm run build:wasm + - run: npm run typecheck # Upload the built pkg/ files for the cross-OS matrix. - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/AGENTS.md b/AGENTS.md index c7c1ba7..0887c67 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,15 +116,28 @@ Remove-Item Env:RUSTDOCFLAGS In `cmd.exe` on Windows, use `set "RUSTDOCFLAGS=-D warnings"` before the doc commands and `set "RUSTDOCFLAGS="` after them. +If you change TypeScript, JSON, YAML or Markdown files, also check the +lints and the format: + +```sh +npm ci +npm run lint +npm run format:check +``` + If you change the Wasm or TypeScript code, also run these commands. `npm run check:wasm` runs Clippy and rustdoc in release mode for `wasm32-unknown-unknown`. `npm run build` compiles `src/wasm.rs` and `src/index.ts`. `npm run verify:pack` runs `npm run build` one time and -checks the `tunelet` and `@bytelandtechnology/tunelet` archives: +checks the `tunelet` and `@bytelandtechnology/tunelet` archives. Run +`npm run build:wasm` before `npm run typecheck` so `pkg/tunelet.d.ts` +exists: ```sh npm ci npm run check:wasm +npm run build:wasm +npm run typecheck npm run verify:pack ``` @@ -133,10 +146,10 @@ npm run verify:pack `npm run build:ts` before `npm run verify:pack -- --ignore-scripts`. - `.github/workflows/ci.yml` runs on each pull request and each push to `main`. - `build-wasm` checks the format, Clippy, rustdoc, the crate archive and - `check:wasm` on `ubuntu-latest`, then builds and uploads `pkg/`. `check-os` - runs on `ubuntu-latest`, `macos-latest` and `windows-latest` with isolated - failures (`fail-fast: false`). Each runner builds `libtunelet.so`, + `build-wasm` checks the format, Clippy, rustdoc, the crate archive, Biome, + `check:wasm` and `typecheck` on `ubuntu-latest`, then uploads `pkg/`. + `check-os` runs on `ubuntu-latest`, `macos-latest` and `windows-latest` with + isolated failures (`fail-fast: false`). Each runner builds `libtunelet.so`, `libtunelet.dylib` or `tunelet.dll`, compiles TypeScript and runs `npm run verify:pack -- --ignore-scripts`. `msrv` checks `rust-version` from `Cargo.toml` on `ubuntu-latest`. `verify` reports the combined status for diff --git a/README.md b/README.md index a06715f..5ff07c4 100644 --- a/README.md +++ b/README.md @@ -289,37 +289,37 @@ processor.process(&input, &mut output, &events)?; `ControlEvent::Parameter` accepts these `ParameterControl` variants. All ranges are inclusive, and `f32` values must be finite. -| Variant | TypeScript `type` | Configuration field | Range | -| ----------------------------- | ------------------------------- | --------------------------------------- | ----------------- | -| `PunchGainDb` | `"punchGainDb"` | `punch.gain_db` | `-96..=12` dB | -| `PunchImpact` | `"punchImpact"` | `punch.impact` | `0..=1` | -| `PunchCeilingDb` | `"punchCeilingDb"` | `punch.ceiling_db` | `-96..=0` dBFS | -| `PunchAttackMs` | `"punchAttackMs"` | `punch.attack_ms` | `0.01..=5000` ms | -| `WarmDriveDb` | `"warmDriveDb"` | `warm.drive_db` | `0..=6` dB | -| `PitchThreshold` | `"pitchThreshold"` | `resynthesis.pitch.threshold` | `0.002..=0.2` | -| `RetuneMs` | `"retuneMs"` | `resynthesis.correction.retune_ms` | `0..=400` ms | -| `Humanize` | `"humanize"` | `resynthesis.correction.humanize` | `0..=1` | -| `FlexTune` | `"flexTune"` | `resynthesis.correction.flex_tune` | `0..=1` | -| `PitchRatio` | `"pitchRatio"` | `resynthesis.pitch_ratio` | `0.25..=4` | -| `FormantWidth` | `"formantWidth"` | `resynthesis.formant.width` | `0.5..=2` | -| `FormantStretch` | `"formantStretch"` | `resynthesis.formant.stretch` | `0.5..=2` | -| `FormantAspirationMix` | `"formantAspirationMix"` | `resynthesis.formant.aspiration_mix` | `0..=1` | -| `FormantAspirationCutoffHz` | `"formantAspirationCutoffHz"` | `resynthesis.formant.aspiration_cutoff_hz` | `500..=10000` Hz | -| `ChoirVoices` | `"choirVoices"` | `resynthesis.choir_voices` | `1..=16` | -| `ChoirDetune` | `"choirDetune"` | `resynthesis.choir_detune` | `10..=100` | -| `ChoirDelay` | `"choirDelay"` | `resynthesis.choir_delay` | `20..=200` | -| `ChoirSpreadPercent` | `"choirSpreadPercent"` | `resynthesis.choir_spread_percent` | `0..=100`% | -| `HarmonyRegisterPercent` | `"harmonyRegisterPercent"` | `resynthesis.harmony.register_percent` | `0..=100`% | -| `HarmonyVoicingSpreadPercent` | `"harmonyVoicingSpreadPercent"` | `resynthesis.harmony.voicing_spread_percent` | `0..=100`% | -| `HarmonyPortamentoMs` | `"harmonyPortamentoMs"` | `resynthesis.harmony.portamento_ms` | `0..=10000` ms | -| `HarmonyVoices` | `"harmonyVoices"` | `resynthesis.harmony.voices` | `0..=4` | -| `HarmonyGain` | `"harmonyGain"` | `resynthesis.harmony_gain` | `0..=1` | -| `HarmonicModulation` | `"harmonicModulation"` | `resynthesis.harmonic_modulation` | `0..=24` | -| `DryMix` | `"dryMix"` | `resynthesis.dry_mix` | `0..=1` | -| `ReverbMix` | `"reverbMix"` | `reverb.mix` | `0..=1` | -| `ReverbDiffusion` | `"reverbDiffusion"` | `reverb.diffusion` | `0..=1` | -| `ReverbDecay` | `"reverbDecay"` | `reverb.decay` | `0..=1` | -| `ReverbBrightnessHz` | `"reverbBrightnessHz"` | `reverb.brightness_hz` | `80..=20000` Hz | +| Variant | TypeScript `type` | Configuration field | Range | +| ----------------------------- | ------------------------------- | -------------------------------------------- | ---------------- | +| `PunchGainDb` | `"punchGainDb"` | `punch.gain_db` | `-96..=12` dB | +| `PunchImpact` | `"punchImpact"` | `punch.impact` | `0..=1` | +| `PunchCeilingDb` | `"punchCeilingDb"` | `punch.ceiling_db` | `-96..=0` dBFS | +| `PunchAttackMs` | `"punchAttackMs"` | `punch.attack_ms` | `0.01..=5000` ms | +| `WarmDriveDb` | `"warmDriveDb"` | `warm.drive_db` | `0..=6` dB | +| `PitchThreshold` | `"pitchThreshold"` | `resynthesis.pitch.threshold` | `0.002..=0.2` | +| `RetuneMs` | `"retuneMs"` | `resynthesis.correction.retune_ms` | `0..=400` ms | +| `Humanize` | `"humanize"` | `resynthesis.correction.humanize` | `0..=1` | +| `FlexTune` | `"flexTune"` | `resynthesis.correction.flex_tune` | `0..=1` | +| `PitchRatio` | `"pitchRatio"` | `resynthesis.pitch_ratio` | `0.25..=4` | +| `FormantWidth` | `"formantWidth"` | `resynthesis.formant.width` | `0.5..=2` | +| `FormantStretch` | `"formantStretch"` | `resynthesis.formant.stretch` | `0.5..=2` | +| `FormantAspirationMix` | `"formantAspirationMix"` | `resynthesis.formant.aspiration_mix` | `0..=1` | +| `FormantAspirationCutoffHz` | `"formantAspirationCutoffHz"` | `resynthesis.formant.aspiration_cutoff_hz` | `500..=10000` Hz | +| `ChoirVoices` | `"choirVoices"` | `resynthesis.choir_voices` | `1..=16` | +| `ChoirDetune` | `"choirDetune"` | `resynthesis.choir_detune` | `10..=100` | +| `ChoirDelay` | `"choirDelay"` | `resynthesis.choir_delay` | `20..=200` | +| `ChoirSpreadPercent` | `"choirSpreadPercent"` | `resynthesis.choir_spread_percent` | `0..=100`% | +| `HarmonyRegisterPercent` | `"harmonyRegisterPercent"` | `resynthesis.harmony.register_percent` | `0..=100`% | +| `HarmonyVoicingSpreadPercent` | `"harmonyVoicingSpreadPercent"` | `resynthesis.harmony.voicing_spread_percent` | `0..=100`% | +| `HarmonyPortamentoMs` | `"harmonyPortamentoMs"` | `resynthesis.harmony.portamento_ms` | `0..=10000` ms | +| `HarmonyVoices` | `"harmonyVoices"` | `resynthesis.harmony.voices` | `0..=4` | +| `HarmonyGain` | `"harmonyGain"` | `resynthesis.harmony_gain` | `0..=1` | +| `HarmonicModulation` | `"harmonicModulation"` | `resynthesis.harmonic_modulation` | `0..=24` | +| `DryMix` | `"dryMix"` | `resynthesis.dry_mix` | `0..=1` | +| `ReverbMix` | `"reverbMix"` | `reverb.mix` | `0..=1` | +| `ReverbDiffusion` | `"reverbDiffusion"` | `reverb.diffusion` | `0..=1` | +| `ReverbDecay` | `"reverbDecay"` | `reverb.decay` | `0..=1` | +| `ReverbBrightnessHz` | `"reverbBrightnessHz"` | `reverb.brightness_hz` | `80..=20000` Hz | ## Lifecycle diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..e9b6500 --- /dev/null +++ b/biome.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.6.8/schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "files": { + "ignoreUnknown": true, + "includes": ["**", "!CHANGELOG.md", "!package-lock.json"] + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "indentWidth": 2 + }, + "linter": { + "enabled": true, + "rules": { + "preset": "recommended" + } + }, + "javascript": { + "formatter": { + "quoteStyle": "double" + } + }, + "assist": { + "enabled": false + } +} diff --git a/package-lock.json b/package-lock.json index 42eeddf..a2a7fba 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,222 @@ "version": "0.3.4", "license": "MIT", "devDependencies": { + "@biomejs/biome": "^2.6.8", "@types/node": "^24.19.2", "typescript": "^7.0.2" } }, + "node_modules/@biomejs/biome": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.8.tgz", + "integrity": "sha512-kqZUFvX6/aYQOmzfRN5ANcfNS9wLH4aHLWWP/dQKyhRZVoA6rdWszA7DGugFcxPbMiznUyVYyukVl+ExZN4PQA==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-android-arm64": "2.6.8", + "@biomejs/cli-android-x64": "2.6.8", + "@biomejs/cli-darwin-arm64": "2.6.8", + "@biomejs/cli-darwin-x64": "2.6.8", + "@biomejs/cli-linux-arm64": "2.6.8", + "@biomejs/cli-linux-arm64-musl": "2.6.8", + "@biomejs/cli-linux-x64": "2.6.8", + "@biomejs/cli-linux-x64-musl": "2.6.8", + "@biomejs/cli-win32-arm64": "2.6.8", + "@biomejs/cli-win32-x64": "2.6.8" + } + }, + "node_modules/@biomejs/cli-android-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.8.tgz", + "integrity": "sha512-X4JKPLK85kfUTwuuaORFplnBfGjKkp62PsFhhcL7F/Tpltc7pyUofjlkkMnlZZLWsifFl7LNB8ngVrwJg1uo1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-android-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.8.tgz", + "integrity": "sha512-C3Hk485vl+deEj53K08+SYYelPIPkdSZL3qHuD31Xi+qydVa4q2ze+aCYo1k3iJGWtvWtjHaGkDh7S2sX6wk8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.8.tgz", + "integrity": "sha512-DHyj+JnRHcn4YdvpiqgTFZMYKSPELMCfFpNNlEuu1L8DKTGXhzW7raIwdsbo2Ie9nCljQLAQkVWQk/mwM0ueiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.8.tgz", + "integrity": "sha512-QWWUPjlA0RnkkgYnFLUHZu+RrDc0FdK0A+wEPA+dENQJwsuSHMH89lspnAw2QUWWc9VHyfluGx1Xmp6Y2GZi8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.8.tgz", + "integrity": "sha512-0Bjim8lKwnrvXUHoI4k3Tb51BjoiLEwDnovCI8nSzkk6wj3dShiuAjrx6+X0Hjf4ejR1sRZgTQiSDHlpy9vB7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.8.tgz", + "integrity": "sha512-WB9PhOitX+bRc0G3+GNJGlvbKoWn3JoB9z4E04JQizIC9aPCQyIvwvWG7QZHxw6k20Fi+dHLmZ2fSEmBa9HqiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.8.tgz", + "integrity": "sha512-XIk3pLQT56I6Tti+u0DF8FtSNXjCMTPbxVTzfJ9cS2t1ImVKvrqV5b52GuEaJg6/wuiXvz0sjfb5saB4TPRjzA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.8.tgz", + "integrity": "sha512-64Yzo+J4fEk7Kf9SMnVdVxC+Y2A2e/L86QTP9JjGQ57lsddyELLpbBcNMxSJggre2T1AvISwwSrOApkBAHDqNA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.8.tgz", + "integrity": "sha512-ezjCEZzHIWE2pdh83a7zLVcAAcDaERcTcvfA7uWlxqz/1CuDxgtfO19pDg9B6YY4wKYIDvYBw2QCMnqIshSwmw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.8.tgz", + "integrity": "sha512-cD6HvGczZUiAYsY8s2TxxXj2AHFzEdMomvVJfEjzOjBM45nGqIDfBpbtvwGQzDCN8X2yKKk9u1jnDZisT2nxIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, "node_modules/@types/node": { "version": "24.19.2", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", diff --git a/package.json b/package.json index 7718ec4..5ceb870 100644 --- a/package.json +++ b/package.json @@ -34,11 +34,15 @@ "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node scripts/postbuild-wasm.mjs && node scripts/normalize-jsdoc.mjs", "build:ts": "tsc", "check:wasm": "cargo clippy --locked --release --lib --target wasm32-unknown-unknown --features wasm -- -D warnings && cargo rustdoc --locked --release --lib --target wasm32-unknown-unknown --features wasm -- -D warnings", + "lint": "biome lint --error-on-warnings .", + "format:check": "biome format .", + "typecheck": "tsc --noEmit", "prepack": "npm run build", "prepare": "git config core.hooksPath .githooks || true", "verify:pack": "node scripts/verify-pack.mjs" }, "devDependencies": { + "@biomejs/biome": "^2.6.8", "@types/node": "^24.19.2", "typescript": "^7.0.2" } diff --git a/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index 0f6a77f..a08ee13 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -261,7 +261,9 @@ function normalizeBlock(block, filePath) { const rebuiltLines = normalized .split("\n") - .map((line) => (line.length === 0 ? `${starPrefix}*` : `${starPrefix}* ${line}`)); + .map((line) => + line.length === 0 ? `${starPrefix}*` : `${starPrefix}* ${line}`, + ); return [`/**`, ...rebuiltLines, `${starPrefix}*/`].join("\n"); } diff --git a/scripts/postbuild-wasm.mjs b/scripts/postbuild-wasm.mjs index 070d80d..7744697 100644 --- a/scripts/postbuild-wasm.mjs +++ b/scripts/postbuild-wasm.mjs @@ -205,7 +205,10 @@ export function sanitizeDeclarations(rawSource) { return newline === "\r\n" ? content.replace(/\n/g, "\r\n") : content; } -if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { +if ( + process.argv[1] && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { fs.rmSync(gitignorePath, { force: true }); if (!fs.existsSync(dtsPath)) { throw new Error(`Declaration file was not found at ${dtsPath}`); diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..c94e081 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -285,11 +285,11 @@ function verifyRuntimeImport(consumerDir, packageName) { "", "const packageName = process.argv[2];", "const require = createRequire(import.meta.url);", - "const pkgWasmSubpath = `${packageName}/pkg/tunelet_bg.wasm`;", - "const rootWasmSubpath = `${packageName}/tunelet_bg.wasm`;", + 'const pkgWasmSubpath = packageName + "/pkg/tunelet_bg.wasm";', + 'const rootWasmSubpath = packageName + "/tunelet_bg.wasm";', "const resolvedPkgWasm = import.meta.resolve(pkgWasmSubpath);", "const resolvedRootWasm = import.meta.resolve(rootWasmSubpath);", - 'assert.match(resolvedPkgWasm, /^file:/);', + "assert.match(resolvedPkgWasm, /^file:/);", "assert.equal(resolvedPkgWasm, resolvedRootWasm);", "const wasmFilePath = fileURLToPath(resolvedPkgWasm);", "assert.ok(fs.statSync(wasmFilePath).isFile());", @@ -297,7 +297,7 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.equal(require.resolve(rootWasmSubpath), wasmFilePath);", "", "const rootModule = await import(packageName);", - "const wasmModule = await import(`${packageName}/wasm`);", + 'const wasmModule = await import(packageName + "/wasm");', "", 'assert.equal(typeof rootModule.loadTunelet, "function");', "assert.equal(rootModule.default, rootModule.loadTunelet);", @@ -321,7 +321,7 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", - " assert.equal(typeof processor.controlActivity().choirVoices, \"boolean\");", + ' assert.equal(typeof processor.controlActivity().choirVoices, "boolean");', " const initialTelemetry = processor.telemetry();", " assert.ok(initialTelemetry.voiceRatios instanceof Float32Array);", " assert.ok(initialTelemetry.voiceGains instanceof Float32Array);", @@ -373,7 +373,7 @@ function verifyRuntimeImport(consumerDir, packageName) { " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", - ' processor.process(input, left, right, [', + " processor.process(input, left, right, [", ' { offset: 0, event: { type: "parameter", value: { type: "dryMix", value: 0.25 } } },', ' { offset: 0, event: { type: "parameter", value: { type: "humanize", value: 0.5 } } },', ' { offset: 0, event: { type: "parameter", value: { type: "flexTune", value: 0.25 } } },', @@ -451,7 +451,7 @@ function verifyRuntimeImport(consumerDir, packageName) { " const reboundInput = views.input;", " reboundInput.fill(0.25, 0, 64);", " inputF32.fill(0.25, 0, 64);", - " const gainEvents = [{ offset: 0, event: { type: \"outputGain\", value: 0.75 } }];", + ' const gainEvents = [{ offset: 0, event: { type: "outputGain", value: 0.75 } }];', " f32Processor.processF32InPlace(64, gainEvents);", " copiedF32Processor.processF32(", " inputF32.subarray(0, 64),", @@ -483,7 +483,7 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.throws(() => f32Processor.processF32InPlace(-1));", " assert.throws(() => f32Processor.processF32InPlace(1.5));", " assert.throws(() =>", - " f32Processor.processF32InPlace(64, [{ offset: 64, event: { type: \"reset\" } }]),", + ' f32Processor.processF32InPlace(64, [{ offset: 64, event: { type: "reset" } }]),', " );", " assert.equal(f32Processor.feedback().processedFrames, framesBeforeError);", " assert.equal(views.left[0], savedLeft0);", @@ -576,9 +576,9 @@ function verifyRuntimeImport(consumerDir, packageName) { 'import assert from "node:assert/strict";', "", "const packageName = process.argv[2];", - "const wasmHref = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + 'const wasmHref = import.meta.resolve(packageName + "/pkg/tunelet_bg.wasm");', 'assert.equal(typeof wasmHref, "string");', - 'assert.match(wasmHref, /^file:/);', + "assert.match(wasmHref, /^file:/);", "const { loadTunelet, Tunelet } = await import(packageName);", "const exportsFromString = await loadTunelet(wasmHref);", "assert.ok(exportsFromString);", @@ -604,7 +604,7 @@ function verifyRuntimeImport(consumerDir, packageName) { 'import assert from "node:assert/strict";', "", "const packageName = process.argv[2];", - "const wasmHref = import.meta.resolve(`${packageName}/tunelet_bg.wasm`);", + 'const wasmHref = import.meta.resolve(packageName + "/tunelet_bg.wasm");', 'const crossRealmUrl = { href: wasmHref, protocol: "file:" };', "assert.equal(crossRealmUrl instanceof URL, false);", "const { loadTunelet, Tunelet } = await import(packageName);", @@ -635,9 +635,9 @@ function verifyRuntimeImport(consumerDir, packageName) { "", "const packageName = process.argv[2];", "const wasmBytes = fs.readFileSync(", - " fileURLToPath(import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`)),", + ' fileURLToPath(import.meta.resolve(packageName + "/pkg/tunelet_bg.wasm")),', ");", - "const wasmModule = await import(`${packageName}/wasm`);", + 'const wasmModule = await import(packageName + "/wasm");', "const exportsFromInit = await wasmModule.default({", " module_or_path: wasmBytes,", "});", @@ -667,7 +667,7 @@ function verifyRuntimeImport(consumerDir, packageName) { "", "const packageName = process.argv[2];", "const wasmBytes = fs.readFileSync(", - " fileURLToPath(import.meta.resolve(`${packageName}/tunelet_bg.wasm`)),", + ' fileURLToPath(import.meta.resolve(packageName + "/tunelet_bg.wasm")),', ");", "const { initSync, Tunelet } = await import(packageName);", "const exportsFromSync = initSync({ module: wasmBytes });", @@ -700,9 +700,9 @@ function verifyRuntimeImport(consumerDir, packageName) { "", "const packageName = process.argv[2];", "const wasmBytes = fs.readFileSync(", - " fileURLToPath(import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`)),", + ' fileURLToPath(import.meta.resolve(packageName + "/pkg/tunelet_bg.wasm")),', ");", - "const wasmModule = await import(`${packageName}/wasm`);", + 'const wasmModule = await import(packageName + "/wasm");', "const exportsFromSync = wasmModule.initSync({ module: wasmBytes });", "assert.ok(exportsFromSync);", "const processor = new wasmModule.Tunelet(48000, 128);", @@ -1181,20 +1181,53 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { ); const fallibleSignatures = [ - ["config", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+config\(\): ProcessorConfig;/], - ["controlActivity", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+controlActivity\(\): ControlActivity;/], - ["drainMono", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+drainMono\(audio: Int16Array\): number;/], - ["drain", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+drain\(left: Int16Array, right: Int16Array\): number;/], + [ + "config", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+config\(\): ProcessorConfig;/, + ], + [ + "controlActivity", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+controlActivity\(\): ControlActivity;/, + ], + [ + "drainMono", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+drainMono\(audio: Int16Array\): number;/, + ], + [ + "drain", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+drain\(left: Int16Array, right: Int16Array\): number;/, + ], ["feedback", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+feedback\(\): Feedback;/], - ["formantEnvelope", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+formantEnvelope\([^)]*\): boolean;/], + [ + "formantEnvelope", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+formantEnvelope\([^)]*\): boolean;/, + ], ["constructor", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+constructor\([^)]*\);/], - ["processMono", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+processMono\([^)]*\): void;/], + [ + "processMono", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+processMono\([^)]*\): void;/, + ], ["process", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+process\([^)]*\): void;/], - ["setConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+setConfig\(config: ProcessorConfig\): void;/], - ["takeFeedback", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeFeedback\(\): Feedback;/], - ["takeTelemetry", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeTelemetry\(\): Telemetry;/], - ["telemetry", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+telemetry\(\): Telemetry;/], - ["defaultConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function defaultConfig\(\): ProcessorConfig;/], + [ + "setConfig", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+setConfig\(config: ProcessorConfig\): void;/, + ], + [ + "takeFeedback", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeFeedback\(\): Feedback;/, + ], + [ + "takeTelemetry", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeTelemetry\(\): Telemetry;/, + ], + [ + "telemetry", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+telemetry\(\): Telemetry;/, + ], + [ + "defaultConfig", + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function defaultConfig\(\): ProcessorConfig;/, + ], ]; for (const [label, pattern] of fallibleSignatures) { const doc = extractMemberJsDoc(dts, pattern, label); @@ -1205,14 +1238,19 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export interface ControlActivity \{([\s\S]*?)\n\}/.exec( dts, ); - assert.ok(controlActivityInterfaceMatch, "Expected ControlActivity interface"); + assert.ok( + controlActivityInterfaceMatch, + "Expected ControlActivity interface", + ); const controlActivityDoc = extractJsDocBlocks( controlActivityInterfaceMatch[1], )[0].replace(/\s+/g, " "); assert.ok(controlActivityDoc.includes("`ProcessorConfig`")); assert.ok(controlActivityDoc.includes("`Tunelet.controlActivity`")); assert.ok( - controlActivityInterfaceMatch[2].includes("`ResynthesisConfig.choirVoices`"), + controlActivityInterfaceMatch[2].includes( + "`ResynthesisConfig.choirVoices`", + ), ); assert.ok( controlActivityInterfaceMatch[2].includes("`HarmonyConfig.source`"), @@ -1378,16 +1416,16 @@ async function verifyHttpLoaders(consumerDir, packageName) { "", 'if (mode === "http-404-retry") {', " await assert.rejects(", - " () => rootModule.loadTunelet(`${baseUrl}/missing.wasm`),", + ' () => rootModule.loadTunelet(baseUrl + "/missing.wasm"),', " /404/,", " );", - " const wasmExports = await rootModule.loadTunelet(`${baseUrl}/tunelet.wasm`);", + ' const wasmExports = await rootModule.loadTunelet(baseUrl + "/tunelet.wasm");', " assert.ok(wasmExports);", - " const cachedExports = await rootModule.loadTunelet(`${baseUrl}/missing.wasm`);", + ' const cachedExports = await rootModule.loadTunelet(baseUrl + "/missing.wasm");', " assert.equal(cachedExports, wasmExports);", " verifyPcmBlock(rootModule);", '} else if (mode === "http-response-wasm") {', - " const response = await fetch(`${baseUrl}/tunelet.wasm`);", + ' const response = await fetch(baseUrl + "/tunelet.wasm");', " assert.equal(response.ok, true);", ' assert.equal(response.headers.get("Content-Type"), "application/wasm");', " const originalStreaming = WebAssembly.instantiateStreaming;", @@ -1420,7 +1458,7 @@ async function verifyHttpLoaders(consumerDir, packageName) { " assert.equal(warnings.length, 0);", " verifyPcmBlock(rootModule);", '} else if (mode === "http-response-octet-stream") {', - " const response = await fetch(`${baseUrl}/octet-stream.wasm`);", + ' const response = await fetch(baseUrl + "/octet-stream.wasm");', " assert.equal(response.ok, true);", ' assert.equal(response.headers.get("Content-Type"), "application/octet-stream");', " const originalStreaming = WebAssembly.instantiateStreaming;", @@ -1461,7 +1499,7 @@ async function verifyHttpLoaders(consumerDir, packageName) { " assert.match(String(warnings[0][0]), /application\\/wasm/);", " verifyPcmBlock(rootModule);", "} else {", - " throw new Error(`Unknown HTTP loader mode: ${mode}`);", + ' throw new Error("Unknown HTTP loader mode: " + mode);', "}", "", ].join("\n"), diff --git a/src/index.ts b/src/index.ts index 4f6e6e1..b849746 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,13 @@ import type { InitInput, InitOutput, Tunelet } from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; +interface CachedAudioViews { + readonly buffer: ArrayBuffer; + readonly input: Float32Array; + readonly left: Float32Array; + readonly right: Float32Array; +} + /** * Cached `Float32Array` views over the in-place `Tunelet` buffers in Wasm * linear memory. @@ -28,14 +35,12 @@ export * from "../pkg/tunelet.js"; * after `processor.free()`. */ export class TuneletAudioViews { + declare [Symbol.dispose]: () => void; private readonly memory: InitOutput["memory"]; private processor: Tunelet | null; /** The fixed frame capacity of `input`, `left` and `right`. */ readonly maxBlockFrames: number; - private cachedBuffer: ArrayBuffer | null = null; - private inputView: Float32Array | null = null; - private leftView: Float32Array | null = null; - private rightView: Float32Array | null = null; + private cachedViews: CachedAudioViews | null = null; /** * Binds `Float32Array` views for `processor` over `memory`. @@ -61,8 +66,7 @@ export class TuneletAudioViews { * If `memory.buffer` changed, this getter refreshes all three views first. */ get input(): Float32Array { - this.refresh(); - return this.inputView!; + return this.syncViews().input; } /** @@ -71,8 +75,7 @@ export class TuneletAudioViews { * If `memory.buffer` changed, this getter refreshes all three views first. */ get left(): Float32Array { - this.refresh(); - return this.leftView!; + return this.syncViews().left; } /** @@ -81,8 +84,7 @@ export class TuneletAudioViews { * If `memory.buffer` changed, this getter refreshes all three views first. */ get right(): Float32Array { - this.refresh(); - return this.rightView!; + return this.syncViews().right; } /** @@ -90,40 +92,40 @@ export class TuneletAudioViews { * from `memory.buffer`. */ refresh(): void { + this.syncViews(); + } + + private syncViews(): CachedAudioViews { const processor = this.processor; if (processor === null) { throw new Error("TuneletAudioViews is disposed"); } const buffer = this.memory.buffer; - if (this.cachedBuffer !== buffer) { - const frames = this.maxBlockFrames; - const inputPtr = processor.inputF32Ptr; - const leftPtr = processor.leftF32Ptr; - const rightPtr = processor.rightF32Ptr; - const input = new Float32Array(buffer, inputPtr, frames); - const left = new Float32Array(buffer, leftPtr, frames); - const right = new Float32Array(buffer, rightPtr, frames); - this.inputView = input; - this.leftView = left; - this.rightView = right; - this.cachedBuffer = buffer; + const cached = this.cachedViews; + if (cached !== null && cached.buffer === buffer) { + return cached; } + const frames = this.maxBlockFrames; + const inputPtr = processor.inputF32Ptr; + const leftPtr = processor.leftF32Ptr; + const rightPtr = processor.rightF32Ptr; + const next: CachedAudioViews = { + buffer, + input: new Float32Array(buffer, inputPtr, frames), + left: new Float32Array(buffer, leftPtr, frames), + right: new Float32Array(buffer, rightPtr, frames), + }; + this.cachedViews = next; + return next; } /** Clears the cached `ArrayBuffer`, `Float32Array` views and processor link. */ dispose(): void { this.processor = null; - this.cachedBuffer = null; - this.inputView = null; - this.leftView = null; - this.rightView = null; + this.cachedViews = null; } } -export interface TuneletAudioViews { - [Symbol.dispose](): void; -} - if (Symbol.dispose) { TuneletAudioViews.prototype[Symbol.dispose] = TuneletAudioViews.prototype.dispose; diff --git a/tsconfig.json b/tsconfig.json index aca9250..4e27641 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,7 +6,12 @@ "lib": ["ES2020"], "types": ["node"], "strict": true, + "verbatimModuleSyntax": true, + "isolatedDeclarations": true, + "noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": true, + "noUnusedLocals": true, + "noUnusedParameters": true, "declaration": true, "noEmitOnError": true, "rootDir": "src",