Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 40 additions & 33 deletions js/common/worklet.test.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,61 @@
import { expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { connect } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { build, createServer } from "vite";
import type { EmittedAsset, EmittedFile, PluginContext } from "rolldown";
import { createServer, type MinimalPluginContextWithoutEnvironment, type ResolvedConfig } from "vite";
import { worklet } from "./vite-plugin-worklet";

// A library build must never reference its worklets through import.meta.url: esbuild, Rollup, and Bun
// consumers drop that asset (a 404), and an esbuild IIFE throws at load. The blob stays the default,
// loaded lazily, with the hostable file emitted beside it.
//
// A bundler child process would outlive `vite build` and be reaped by init, so its CPU escapes the
// build's accounting and it lingers after the build.
//
// One build of a one-line worklet: the plugin's output doesn't depend on what the worklet imports, and
// bundling a real package graph costs over a CPU-second. The package builds bundle the real worklets.
test("library builds load worklets from a lazy blob or a hosted base, leaving no child process", async () => {
// No bundler child may outlive the plugin's compile and escape its CPU accounting. Check the load
// hooks with the real in-process compiler here; full Vite library output and build-lifecycle checks
// run nightly in test/worklet/matrix.ts on the real worklets.
test("worklet modules load a lazy blob or a hosted script, leaving no child process", async () => {
const dir = mkdtempSync(join(tmpdir(), "worklet-"));
const outDir = join(dir, "dist");
try {
writeFileSync(join(dir, "render.ts"), `registerProcessor("render", class extends AudioWorkletProcessor {});\n`);
writeFileSync(join(dir, "index.ts"), `export { default } from "./render.ts?worklet";\n`);

await build({
configFile: false,
logLevel: "silent",
plugins: [worklet()],
build: { outDir, minify: false, lib: { entry: join(dir, "index.ts"), formats: ["es"] } },
});

expect(readdirSync(join(outDir, "assets"))).toEqual(["render.js"]);

const chunks = readdirSync(outDir).filter((name) => name.endsWith(".js"));
const code = new Map(chunks.map((name) => [name, readFileSync(join(outDir, name), "utf8")]));
for (const text of code.values()) expect(text).not.toContain("import.meta.url");
const path = join(dir, "render.ts");
writeFileSync(path, `registerProcessor("render", class extends AudioWorkletProcessor {});\n`);
const plugin = worklet();
if (typeof plugin.configResolved !== "function" || typeof plugin.load !== "function")
throw new Error("worklet hooks must be functions");
await plugin.configResolved.call(
{} as MinimalPluginContextWithoutEnvironment,
{ command: "build" } as ResolvedConfig,
);
const assets: EmittedAsset[] = [];
const context = {
emitFile(file: EmittedFile) {
if (file.type !== "asset") throw new Error("worklet must emit an asset");
assets.push(file);
return "hosted";
},
addWatchFile(_path: string) {},
} as PluginContext;
const entry = await plugin.load.call(context, `${path}?worklet`);
const blob = await plugin.load.call(context, `${path}?worklet-blob`);

const blob = chunks.filter((name) => code.get(name)?.includes("createObjectURL"));
expect(blob).toHaveLength(1);
const entry = chunks
.filter((name) => !blob.includes(name))
.map((name) => code.get(name))
.join("\n");
expect(entry).toContain(`import("./${blob[0]}")`);
expect(entry).toContain(`new URL("render.js", `);
expect(assets).toHaveLength(1);
expect(assets[0].fileName).toBe("assets/render.js");
expect(assets[0].source).toContain("registerProcessor");
expect(entry).not.toContain("import.meta.url");
expect(blob).not.toContain("import.meta.url");
expect(entry).not.toContain("createObjectURL");
expect(blob).toContain("URL.createObjectURL");
expect(blob).toContain(JSON.stringify(assets[0].source));
expect(entry).toContain(`import(${JSON.stringify(`${path}?worklet-blob`)})`);
expect(entry).toContain(`new URL("render.js", base)`);
} finally {
rmSync(dir, { recursive: true, force: true });
}

expect(spawnSync("pgrep", ["-l", "-P", String(process.pid)], { encoding: "utf8" }).stdout).toBe("");
const children = spawnSync("pgrep", ["-l", "-P", String(process.pid)], { encoding: "utf8" });
expect(children.stdout).toBe("");
expect(children.status).toBe(1);
});

// A page that calls assets() in dev fetches the same path a build emits, so the dev server serves it.
Expand Down
1 change: 0 additions & 1 deletion quest/m0/test-flakes-2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ Public API: none. Wire: none.
- [IETF22 fallback](/quest/m0/test-flakes-2/ietf22-fallback.md) - an IETF22 browser viewer follows a fallback within the media lane's bound, keeping its session and its audio
- [Browser buffering and Firefox audio-tone tests pass under load](/quest/m0/test-flakes-2/browser-media-flakes.md) - the two `harness.browser.ts` buffering tests and the Firefox player's audio-tone checks pass reliably in Interop and Nightly, each fixed at its cause under the epic's rules
- [moq-transcode's live multi-rung test survives load](/quest/m0/test-flakes-2/transcode-multi-rung.md) - `live_multi_rung` stops failing queue batches with a cancelled rung group
- [The JS worklet library-build test survives load](/quest/m0/test-flakes-2/js-worklet-build.md) - the lazy-blob worklet build test stops timing out at bun's 5 seconds
- [The scheduled macOS WebSocket version test completes reliably](/quest/m0/test-flakes-2/macos-websocket.md) - fix the scheduled timeout while preserving newest-version negotiation assertions
- [@moq/net's lite subscribe tests wait for the whole request](/quest/m0/test-flakes-2/js-subscribe-fixture.md) - the three lite subscribe-with-track cases pass under forced yields
- [Concurrent PulseAudio harness runs don't share a D-Bus name](/quest/m0/test-flakes-2/pulse-dbus.md) - parallel media runs no longer collide on `org.PulseAudio1`
Expand Down
37 changes: 0 additions & 37 deletions quest/m0/test-flakes-2/js-worklet-build.md

This file was deleted.

26 changes: 25 additions & 1 deletion test/worklet/matrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// uses blob: URLs with no CSP, and hosted mode serves the copied assets under a strict CSP. A control
// run of blob: URLs under that CSP must fail, proving the CSP applies. The bundlers are pinned in this
// package's manifest, so the lockfile decides their versions.
import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { cpSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { chromium } from "playwright";
Expand Down Expand Up @@ -44,6 +46,28 @@ try {
plugins: [worklet()],
build: { outDir: lib, lib: { entry: join(root, "lib.js"), formats: ["es"], fileName: "index" } },
});
// Check the completed Vite build before consumer bundlers or Chromium can spawn children.
const children = spawnSync("pgrep", ["-l", "-P", String(process.pid)], { encoding: "utf8" });
assert.equal(children.status, 1, children.error?.message ?? (children.stdout || children.stderr));
assert.deepEqual(readdirSync(join(lib, "assets")).sort(), [
"capture-worker.js",
"capture-worklet.js",
"render-worklet.js",
]);
const chunks = readdirSync(lib)
.filter((name) => name.endsWith(".js"))
.map((name) => ({ name, code: readFileSync(join(lib, name), "utf8") }));
for (const { code } of chunks) assert.ok(!code.includes("import.meta.url"));
const blobs = chunks.filter(({ code }) => code.includes("createObjectURL"));
assert.equal(blobs.length, 3);
const entry = chunks
.filter((chunk) => !blobs.includes(chunk))
.map(({ code }) => code)
.join("\n");
for (const { name } of blobs) assert.ok(entry.includes(`import("./${name}")`));
for (const name of ["render-worklet", "capture-worklet", "capture-worker"])
assert.ok(entry.includes(`new URL("${name}.js", `));
console.log("library build: lazy blobs, hosted assets, no child process");
writeFileSync(
join(lib, "package.json"),
JSON.stringify({ name: "worklet-lib", type: "module", exports: "./index.js" }),
Expand Down
Loading