From ea63ebd24babe9d8cb7ee215e9d65a56acf2bab5 Mon Sep 17 00:00:00 2001 From: Mendy Berger <12537668+MendyBerger@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:50:34 -0500 Subject: [PATCH 1/4] test(std): run WinterTC tests inside componentize-qjs components --- packages/jco-std/test/wintertc/abort.test.ts | 224 + packages/jco-std/test/wintertc/base64.test.ts | 55 + packages/jco-std/test/wintertc/blob.test.ts | 227 + .../test/wintertc/component/.gitignore | 2 + .../jco-std/test/wintertc/component/driver.ts | 806 + .../test/wintertc/component/harness/equals.ts | 409 + .../test/wintertc/component/harness/expect.ts | 410 + .../test/wintertc/component/harness/format.ts | 168 + .../test/wintertc/component/harness/host.ts | 172 + .../test/wintertc/component/harness/main.ts | 40 + .../test/wintertc/component/harness/vitest.ts | 704 + .../test/wintertc/component/peer-client.ts | 322 + .../jco-std/test/wintertc/component/peer.ts | 369 + .../test/wintertc/component/sample.test.ts | 87 + .../test/wintertc/component/wit/world.wit | 15 + .../jco-std/test/wintertc/compression.test.ts | 207 + .../jco-std/test/wintertc/e2e-qjs.test.ts | 463 + .../test/wintertc/e2e-qjs/basic/app.ts | 5 + .../test/wintertc/e2e-qjs/basic/checks.ts | 137 + .../jco-std/test/wintertc/e2e-qjs/build.mjs | 245 + .../jco-std/test/wintertc/e2e-qjs/command.ts | 46 + .../test/wintertc/e2e-qjs/composed/app.ts | 100 + .../jco-std/test/wintertc/e2e-qjs/fail/app.ts | 15 + .../jco-std/test/wintertc/e2e-qjs/http/app.ts | 146 + .../jco-std/test/wintertc/e2e-qjs/serve.ts | 121 + .../test/wintertc/e2e-qjs/wit/world.wit | 26 + .../jco-std/test/wintertc/encoding.test.ts | 87 + packages/jco-std/test/wintertc/events.test.ts | 398 + packages/jco-std/test/wintertc/fetch.test.ts | 209 + .../jco-std/test/wintertc/form-data.test.ts | 171 + .../jco-std/test/wintertc/headers.test.ts | 186 + .../jco-std/test/wintertc/host-backed.test.ts | 247 + .../test/wintertc/legacy-encoding.test.ts | 77 + .../jco-std/test/wintertc/messaging.test.ts | 83 + .../jco-std/test/wintertc/request.test.ts | 213 + .../jco-std/test/wintertc/response.test.ts | 163 + .../jco-std/test/wintertc/streams.test.ts | 746 + .../test/wintertc/subtle-crypto.test.ts | 1040 + packages/jco-std/test/wintertc/timers.test.ts | 181 + .../jco-std/test/wintertc/url-pattern.test.ts | 115 + .../test/wintertc/url-search-params.test.ts | 179 + packages/jco-std/test/wintertc/url.test.ts | 149 + packages/jco-std/test/wintertc/vitest.ts | 65 + packages/jco-std/test/wintertc/wpt.test.ts | 296 + packages/jco-std/test/wintertc/wpt/.gitignore | 2 + packages/jco-std/test/wintertc/wpt/areas.ts | 185 + .../test/wintertc/wpt/component/build.ts | 437 + .../test/wintertc/wpt/component/host.ts | 197 + .../test/wintertc/wpt/component/isolation.ts | 228 + .../test/wintertc/wpt/component/protocol.ts | 72 + .../test/wintertc/wpt/component/runner.ts | 581 + .../wpt/component/wasi-environment.d.ts | 8 + .../test/wintertc/wpt/component/wit/world.wit | 16 + .../wintertc/wpt/expectations/compression.ts | 184 + .../test/wintertc/wpt/expectations/console.ts | 13 + .../wintertc/wpt/expectations/dom-abort.ts | 10 + .../wintertc/wpt/expectations/dom-events.ts | 18 + .../wintertc/wpt/expectations/encoding.ts | 366 + .../wpt/expectations/fetch-api-basic.ts | 413 + .../wpt/expectations/fetch-api-body.ts | 23 + .../wpt/expectations/fetch-api-headers.ts | 223 + .../wpt/expectations/fetch-api-request.ts | 346 + .../wpt/expectations/fetch-api-response.ts | 67 + .../test/wintertc/wpt/expectations/fileapi.ts | 296 + .../test/wintertc/wpt/expectations/hr-time.ts | 20 + .../wintertc/wpt/expectations/html-atob.ts | 10 + .../expectations/html-microtask-queuing.ts | 12 + .../wintertc/wpt/expectations/html-timers.ts | 19 + .../test/wintertc/wpt/expectations/streams.ts | 200 + .../test/wintertc/wpt/expectations/url.ts | 964 + .../wintertc/wpt/expectations/urlpattern.ts | 96 + .../wintertc/wpt/expectations/webcrypto.ts | 22341 ++++++++++++++++ .../wintertc/wpt/expectations/webmessaging.ts | 170 + .../wintertc/wpt/expectations/xhr-formdata.ts | 15 + packages/jco-std/test/wintertc/wpt/globals.ts | 74 + packages/jco-std/test/wintertc/wpt/run.ts | 609 + packages/jco-std/test/wintertc/wpt/types.ts | 59 + 77 files changed, 38400 insertions(+) create mode 100644 packages/jco-std/test/wintertc/abort.test.ts create mode 100644 packages/jco-std/test/wintertc/base64.test.ts create mode 100644 packages/jco-std/test/wintertc/blob.test.ts create mode 100644 packages/jco-std/test/wintertc/component/.gitignore create mode 100644 packages/jco-std/test/wintertc/component/driver.ts create mode 100644 packages/jco-std/test/wintertc/component/harness/equals.ts create mode 100644 packages/jco-std/test/wintertc/component/harness/expect.ts create mode 100644 packages/jco-std/test/wintertc/component/harness/format.ts create mode 100644 packages/jco-std/test/wintertc/component/harness/host.ts create mode 100644 packages/jco-std/test/wintertc/component/harness/main.ts create mode 100644 packages/jco-std/test/wintertc/component/harness/vitest.ts create mode 100644 packages/jco-std/test/wintertc/component/peer-client.ts create mode 100644 packages/jco-std/test/wintertc/component/peer.ts create mode 100644 packages/jco-std/test/wintertc/component/sample.test.ts create mode 100644 packages/jco-std/test/wintertc/component/wit/world.wit create mode 100644 packages/jco-std/test/wintertc/compression.test.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs.test.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/basic/app.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/basic/checks.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/build.mjs create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/command.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/composed/app.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/fail/app.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/http/app.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/serve.ts create mode 100644 packages/jco-std/test/wintertc/e2e-qjs/wit/world.wit create mode 100644 packages/jco-std/test/wintertc/encoding.test.ts create mode 100644 packages/jco-std/test/wintertc/events.test.ts create mode 100644 packages/jco-std/test/wintertc/fetch.test.ts create mode 100644 packages/jco-std/test/wintertc/form-data.test.ts create mode 100644 packages/jco-std/test/wintertc/headers.test.ts create mode 100644 packages/jco-std/test/wintertc/host-backed.test.ts create mode 100644 packages/jco-std/test/wintertc/legacy-encoding.test.ts create mode 100644 packages/jco-std/test/wintertc/messaging.test.ts create mode 100644 packages/jco-std/test/wintertc/request.test.ts create mode 100644 packages/jco-std/test/wintertc/response.test.ts create mode 100644 packages/jco-std/test/wintertc/streams.test.ts create mode 100644 packages/jco-std/test/wintertc/subtle-crypto.test.ts create mode 100644 packages/jco-std/test/wintertc/timers.test.ts create mode 100644 packages/jco-std/test/wintertc/url-pattern.test.ts create mode 100644 packages/jco-std/test/wintertc/url-search-params.test.ts create mode 100644 packages/jco-std/test/wintertc/url.test.ts create mode 100644 packages/jco-std/test/wintertc/vitest.ts create mode 100644 packages/jco-std/test/wintertc/wpt.test.ts create mode 100644 packages/jco-std/test/wintertc/wpt/.gitignore create mode 100644 packages/jco-std/test/wintertc/wpt/areas.ts create mode 100644 packages/jco-std/test/wintertc/wpt/component/build.ts create mode 100644 packages/jco-std/test/wintertc/wpt/component/host.ts create mode 100644 packages/jco-std/test/wintertc/wpt/component/isolation.ts create mode 100644 packages/jco-std/test/wintertc/wpt/component/protocol.ts create mode 100644 packages/jco-std/test/wintertc/wpt/component/runner.ts create mode 100644 packages/jco-std/test/wintertc/wpt/component/wasi-environment.d.ts create mode 100644 packages/jco-std/test/wintertc/wpt/component/wit/world.wit create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/compression.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/console.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/dom-abort.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/dom-events.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/encoding.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/fetch-api-basic.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/fetch-api-body.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/fetch-api-headers.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/fetch-api-request.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/fetch-api-response.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/fileapi.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/hr-time.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/html-atob.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/html-microtask-queuing.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/html-timers.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/streams.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/url.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/urlpattern.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/webcrypto.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/webmessaging.ts create mode 100644 packages/jco-std/test/wintertc/wpt/expectations/xhr-formdata.ts create mode 100644 packages/jco-std/test/wintertc/wpt/globals.ts create mode 100644 packages/jco-std/test/wintertc/wpt/run.ts create mode 100644 packages/jco-std/test/wintertc/wpt/types.ts diff --git a/packages/jco-std/test/wintertc/abort.test.ts b/packages/jco-std/test/wintertc/abort.test.ts new file mode 100644 index 000000000..e904cc548 --- /dev/null +++ b/packages/jco-std/test/wintertc/abort.test.ts @@ -0,0 +1,224 @@ +import { describe, expect, test } from "vitest"; + +import { AbortController, AbortSignal } from "../../src/wintertc/abort.js"; +import { DOMException } from "../../src/wintertc/dom-exception.js"; +import { Event } from "../../src/wintertc/events.js"; +import { setTimeout } from "../../src/wintertc/timers.js"; + +describe("AbortController", () => { + test("aborts with a default AbortError", () => { + const controller = new AbortController(); + const signal = controller.signal; + const events: Event[] = []; + signal.addEventListener("abort", (event) => events.push(event)); + expect(signal.aborted).toBe(false); + expect(signal.reason).toBe(undefined); + signal.throwIfAborted(); + + controller.abort(); + expect(signal.aborted).toBe(true); + expect(signal.reason).toBeInstanceOf(DOMException); + expect(reasonName(signal)).toBe("AbortError"); + expect(events.length).toBe(1); + expect(events[0]?.isTrusted).toBe(true); + expect(() => signal.throwIfAborted()).toThrow(signal.reason as Error); + + controller.abort(new Error("again")); + expect(events.length).toBe(1); + expect(reasonName(signal)).toBe("AbortError"); + }); + + test("reasons are any value, kept as given", () => { + for (const reason of ["text", 42, null, { custom: true }]) { + const controller = new AbortController(); + controller.abort(reason); + expect(controller.signal.reason).toBe(reason); + let thrown: unknown = undefined; + try { + controller.signal.throwIfAborted(); + } catch (e) { + thrown = e; + } + expect(thrown).toBe(reason); + } + }); + + test("signals can't be constructed directly", () => { + const construct = AbortSignal as unknown as new () => AbortSignal; + expect(() => new construct()).toThrow(TypeError); + }); + + test("Symbol.toStringTag", () => { + const controller = new AbortController(); + expect(Object.prototype.toString.call(controller)).toBe("[object AbortController]"); + expect(Object.prototype.toString.call(controller.signal)).toBe("[object AbortSignal]"); + }); + + test("onabort runs with a custom reason", () => { + const controller = new AbortController(); + const reason = new Error("why"); + let seen: unknown; + controller.signal.onabort = (): void => { + seen = controller.signal.reason; + }; + expect(typeof controller.signal.onabort).toBe("function"); + controller.abort(reason); + expect(seen).toBe(reason); + }); +}); + +describe("AbortSignal statics", () => { + test("abort() returns an aborted signal", () => { + const reason = new Error("r"); + expect(AbortSignal.abort(reason).reason).toBe(reason); + expect(reasonName(AbortSignal.abort())).toBe("AbortError"); + expect(AbortSignal.abort("str").reason).toBe("str"); + }); + + test("timeout() aborts with TimeoutError", async () => { + const signal = AbortSignal.timeout(5); + expect(signal.aborted).toBe(false); + await new Promise((resolve) => signal.addEventListener("abort", () => resolve())); + expect(reasonName(signal)).toBe("TimeoutError"); + expect(() => AbortSignal.timeout(-1)).toThrow(TypeError); + }); + + test("any() follows the first source to abort and detaches", () => { + const a = new AbortController(); + const b = new AbortController(); + const any = AbortSignal.any([a.signal, b.signal]); + const nested = AbortSignal.any([any]); + const order: string[] = []; + a.signal.addEventListener("abort", () => order.push("a")); + any.addEventListener("abort", () => order.push("any")); + nested.addEventListener("abort", () => order.push("nested")); + const reason = new Error("b"); + b.abort(reason); + expect(any.reason).toBe(reason); + expect(nested.reason).toBe(reason); + expect(order).toEqual(["any", "nested"]); + a.abort(); + expect(order).toEqual(["any", "nested", "a"]); + expect(any.reason).toBe(reason); + + const already = AbortSignal.any([AbortSignal.abort(reason)]); + expect(already.aborted).toBe(true); + expect(already.reason).toBe(reason); + }); + + test("any() takes any iterable of signals", () => { + const a = new AbortController(); + const any = AbortSignal.any(new Set([a.signal, a.signal])); + a.abort("why"); + expect(any.reason).toBe("why"); + + const any2 = AbortSignal.any as unknown as (signals: unknown) => AbortSignal; + expect(() => any2([{}])).toThrow(TypeError); + expect(() => any2(5)).toThrow(TypeError); + expect(AbortSignal.any([]).aborted).toBe(false); + }); +}); + +describe("AbortSignal.any() and garbage collection", () => { + /** + * Let the current job end, so weak references made in it may be cleared, then collect. + * + * QuickJS frees objects by reference counting as soon as they are unreachable, and runs its + * cycle collector once enough has been allocated; allocating cyclic garbage triggers it, since + * componentize-qjs exposes no `gc()`. + * + * @returns Resolves after the collections. + */ + async function collect(): Promise { + for (let i = 0; i < 3; i++) { + await new Promise((resolve) => setTimeout(resolve, 0)); + for (let j = 0; j < 100_000; j++) { + const a: { b?: object } = {}; + a.b = { a }; + } + } + } + + test("an unobserved dependent is not kept alive by its source", async () => { + const source = new AbortController(); + const ref = (() => new WeakRef(AbortSignal.any([source.signal])))(); + await collect(); + expect(ref.deref()).toBe(undefined); + source.abort(); + }); + + test("an observed dependent is kept alive while its source lives", async () => { + const source = new AbortController(); + let fired = 0; + (() => { + AbortSignal.any([source.signal]).addEventListener("abort", () => fired++); + })(); + let handlerFired = 0; + (() => { + AbortSignal.any([source.signal]).onabort = (): void => { + handlerFired++; + }; + })(); + await collect(); + source.abort(); + expect(fired).toBe(1); + expect(handlerFired).toBe(1); + }); + + test("a dependent is released once nothing observes it", async () => { + const source = new AbortController(); + const ref = (() => { + const dependent = AbortSignal.any([source.signal]); + const listener = (): void => {}; + dependent.addEventListener("abort", listener); + dependent.removeEventListener("abort", listener); + return new WeakRef(dependent); + })(); + await collect(); + expect(ref.deref()).toBe(undefined); + }); + + test("a dependent does not keep its sources alive", async () => { + const holder: { dependent: AbortSignal | null } = { dependent: null }; + const ref = (() => { + const source = new AbortController(); + holder.dependent = AbortSignal.any([source.signal]); + return new WeakRef(source.signal); + })(); + await collect(); + expect(ref.deref()).toBe(undefined); + // `any()` of a dependent whose sources were collected never aborts. + const dependent = holder.dependent; + expect(dependent).not.toBe(null); + if (dependent !== null) { + expect(AbortSignal.any([dependent]).aborted).toBe(false); + } + }); +}); + +/** + * The `name` of an aborted signal's reason, when it is an `Error`. + * + * @param signal - The signal. + * @returns The name, or `undefined`. + */ +function reasonName(signal: AbortSignal): string | undefined { + const reason = signal.reason; + return reason instanceof Error ? reason.name : undefined; +} + +describe("AbortSignal.timeout(0)", () => { + test("aborts after promise jobs that were already queued", async () => { + const log: string[] = []; + const signal = AbortSignal.timeout(0); + signal.addEventListener("abort", () => log.push("abort")); + let chain = Promise.resolve(); + for (let i = 0; i < 20; i++) { + chain = chain.then(() => { + log.push(String(i)); + }); + } + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(log.indexOf("abort")).toBe(20); + }); +}); diff --git a/packages/jco-std/test/wintertc/base64.test.ts b/packages/jco-std/test/wintertc/base64.test.ts new file mode 100644 index 000000000..2c579c9ed --- /dev/null +++ b/packages/jco-std/test/wintertc/base64.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, test } from "vitest"; + +import { atob, btoa } from "../../src/wintertc/base64.js"; +import { DOMException } from "../../src/wintertc/dom-exception.js"; + +describe("btoa", () => { + test("encodes binary strings with padding", () => { + expect(btoa("")).toBe(""); + expect(btoa("f")).toBe("Zg=="); + expect(btoa("fo")).toBe("Zm8="); + expect(btoa("foo")).toBe("Zm9v"); + expect(btoa("ÿ\u0000")).toBe("/wA="); + }); + + test("rejects code units above 0xFF", () => { + let error: Error | null = null; + try { + btoa("€"); + } catch (e) { + error = e as Error; + } + expect(error).toBeInstanceOf(DOMException); + expect(error?.name).toBe("InvalidCharacterError"); + }); +}); + +describe("atob", () => { + test("forgiving-base64 decode", () => { + expect(atob("Zm9v")).toBe("foo"); + expect(atob("Zg")).toBe("f"); + expect(atob(" Z m 8 = \n")).toBe("fo"); + expect(atob("/wA=")).toBe("ÿ\u0000"); + expect(atob("")).toBe(""); + }); + + test("rejects malformed input", () => { + for (const input of ["Z", "Zg=", "Zm9v=", "Z===", "Zm9v!", "Zg==Zg=="]) { + expect(() => atob(input), input).toThrow(DOMException); + } + }); + + test("converts arguments to strings as WebIDL does", () => { + expect(btoa(12 as unknown as string)).toBe("MTI="); + expect(atob(null as unknown as string)).toBe("\x9e\xe9e"); + expect(() => btoa(Symbol("s") as unknown as string)).toThrow(TypeError); + }); + + test("round trips every byte", () => { + let all = ""; + for (let i = 0; i < 256; i++) { + all += String.fromCodePoint(i); + } + expect(atob(btoa(all))).toBe(all); + }); +}); diff --git a/packages/jco-std/test/wintertc/blob.test.ts b/packages/jco-std/test/wintertc/blob.test.ts new file mode 100644 index 000000000..c1674e40d --- /dev/null +++ b/packages/jco-std/test/wintertc/blob.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, test } from "vitest"; + +import { Blob, File } from "../../src/wintertc/blob.js"; +import type { ReadableStream } from "../../src/wintertc/streams/index.js"; + +/** + * Read a byte stream to one array. + * + * @param stream - The stream. + * @returns The bytes. + */ +async function readBytes(stream: ReadableStream): Promise { + const reader = stream.getReader(); + const bytes: number[] = []; + for (;;) { + const result = await reader.read(); + if (result.done) { + return bytes; + } + for (const byte of result.value as Uint8Array) { + bytes.push(byte); + } + } +} + +describe("Blob", () => { + test("concatenates strings and bytes", async () => { + const blob = new Blob(["ab", new Uint8Array([0x63]), "é"]); + expect(blob.size).toBe(5); + expect(await blob.text()).toBe("abcé"); + expect(Array.from(await blob.bytes())).toEqual([0x61, 0x62, 0x63, 0xc3, 0xa9]); + expect(new Uint8Array(await blob.arrayBuffer()).byteLength).toBe(5); + }); + + test("accepts ArrayBuffers and Blobs as parts", async () => { + const inner = new Blob(["xy"]); + expect(await new Blob([inner, "z"]).text()).toBe("xyz"); + expect(await new Blob([new Uint8Array([0x41, 0x42]).buffer, "C"]).text()).toBe("ABC"); + }); + + test("copies its parts", async () => { + const bytes = new Uint8Array([1, 2]); + const blob = new Blob([bytes]); + bytes[0] = 9; + expect(Array.from(await blob.bytes())).toEqual([1, 2]); + }); + + test("empty blob", async () => { + const blob = new Blob(); + expect(blob.size).toBe(0); + expect(blob.type).toBe(""); + expect(await blob.text()).toBe(""); + }); + + test("normalises type", () => { + expect(new Blob([], { type: "Text/HTML" }).type).toBe("text/html"); + expect(new Blob([], { type: "text/é" }).type).toBe(""); + expect(new Blob([], { type: "a\u0000b" }).type).toBe(""); + }); + + test("endings", async () => { + expect(await new Blob(["a\r\nb\rc\n"], { endings: "native" }).text()).toBe("a\nb\nc\n"); + expect(await new Blob(["a\r\nb"], { endings: "transparent" }).text()).toBe("a\r\nb"); + expect(() => new Blob([], { endings: "bogus" as "native" })).toThrow(TypeError); + }); + + test("slice with positive, negative and clamped positions", async () => { + const blob = new Blob(["abcdef"], { type: "text/plain" }); + expect(await blob.slice(1, 3).text()).toBe("bc"); + expect(await blob.slice(-2).text()).toBe("ef"); + expect(await blob.slice(-100, 100).text()).toBe("abcdef"); + expect(await blob.slice(4, 2).text()).toBe(""); + expect(blob.slice(0, 1).type).toBe(""); + expect(blob.slice(0, 1, "Foo/Bar").type).toBe("foo/bar"); + expect(await blob.slice(1, 5).slice(1, 3).text()).toBe("cd"); + }); + + test("stream() yields the contents, in chunks of at most 64 KiB", async () => { + const big = new Uint8Array(150000); + for (let i = 0; i < big.length; i++) { + big[i] = i & 0xff; + } + const blob = new Blob([big]); + const bytes = await readBytes(blob.stream()); + expect(bytes.length).toBe(150000); + expect(bytes[149999]).toBe(149999 & 0xff); + const reader = blob.stream().getReader(); + expect(((await reader.read()).value as Uint8Array).byteLength).toBe(65536); + }); + + test("stream() supports BYOB readers and leaves the blob intact", async () => { + const blob = new Blob(["hello"]); + const reader = blob.stream().getReader({ mode: "byob" }); + const result = await reader.read(new Uint8Array(3)); + expect(Array.from(result.value as Uint8Array)).toEqual([0x68, 0x65, 0x6c]); + expect(await blob.text()).toBe("hello"); + }); + + test("textStream() decodes the contents as UTF-8", async () => { + const reader = new Blob(["h\u00e9llo"], { type: "text/plain;charset=latin1" }) + .textStream() + .getReader(); + let text = ""; + for (;;) { + const result = await reader.read(); + if (result.done) { + break; + } + text += result.value; + } + expect(text).toBe("h\u00e9llo"); + }); + + test("slice positions use WebIDL [Clamp] rounding", async () => { + const blob = new Blob(["abcd"]); + expect(await blob.slice(1.5).text()).toBe("cd"); + expect(await blob.slice(2.5).text()).toBe("cd"); + expect(await blob.slice(0, 0.5).text()).toBe(""); + }); + + test("detached buffers count as empty parts", async () => { + const buffer = new ArrayBuffer(4); + const view = new Uint8Array(buffer, 1, 2); + // Detach it (componentize-qjs has no `structuredClone`, but has `ArrayBuffer#transfer`). + (buffer as ArrayBuffer & { transfer(): ArrayBuffer }).transfer(); + expect(buffer.byteLength).toBe(0); + expect(await new Blob([buffer, "x", view]).text()).toBe("x"); + }); + + test("rejects a non-object options bag", () => { + expect(() => new Blob([], 123 as unknown as { type: string })).toThrow(TypeError); + }); + + test("accepts any iterable as blobParts", async () => { + /** + * Yield mixed parts. + * + * @returns The parts. + */ + function* parts(): Generator { + yield "a"; + yield new Uint8Array([0x62]); + } + expect(await new Blob(parts()).text()).toBe("ab"); + expect(await new Blob(new Set(["x", "y"])).text()).toBe("xy"); + // A String object is iterable: each character is one part. + expect(await new Blob(new String("hi") as unknown as string[]).text()).toBe("hi"); + }); + + test("converts other parts to scalar value strings", async () => { + expect(await new Blob([12 as unknown as string, "\uD800"]).text()).toBe("12\uFFFD"); + expect(() => new Blob([Symbol("s") as unknown as string])).toThrow(TypeError); + }); + + test("rejects a blobParts that isn't an iterable object", () => { + expect(() => new Blob("abc" as unknown as string[])).toThrow(TypeError); + expect(() => new Blob({} as unknown as string[])).toThrow(TypeError); + expect(() => new Blob(null as unknown as string[])).toThrow(TypeError); + }); + + test("has a toStringTag", () => { + expect(Object.prototype.toString.call(new Blob())).toBe("[object Blob]"); + }); +}); + +describe("File", () => { + test("has a name, type and lastModified", async () => { + const file = new File(["data"], "a.txt", { type: "text/plain", lastModified: 1234 }); + expect(file).toBeInstanceOf(Blob); + expect(file.name).toBe("a.txt"); + expect(file.type).toBe("text/plain"); + expect(file.lastModified).toBe(1234); + expect(await file.text()).toBe("data"); + expect(file.slice(0, 2)).not.toBeInstanceOf(File); + }); + + test("lastModified defaults to the wall clock", () => { + const before = Date.now(); + const file = new File([], "x"); + expect(file.lastModified).toBeGreaterThanOrEqual(before); + expect(file.lastModified).toBeLessThanOrEqual(Date.now()); + expect(Number.isInteger(file.lastModified)).toBe(true); + }); + + test("converts its arguments in order", () => { + const order: string[] = []; + const bits = { + *[Symbol.iterator](): Generator { + order.push("bits"); + yield "x"; + }, + }; + const name = { + toString(): string { + order.push("name"); + return "n"; + }, + }; + const options = { + get endings(): "transparent" { + order.push("endings"); + return "transparent"; + }, + get type(): string { + order.push("type"); + return ""; + }, + get lastModified(): number { + order.push("lastModified"); + return 1; + }, + }; + const file = new File(bits, name as unknown as string, options); + expect(order).toEqual(["bits", "name", "endings", "type", "lastModified"]); + expect(file.name).toBe("n"); + }); + + test("has a toStringTag", () => { + expect(Object.prototype.toString.call(new File([], "x", { lastModified: 0 }))).toBe( + "[object File]", + ); + }); + + test("requires a name", () => { + expect(() => new (File as unknown as new (bits: string[]) => File)(["x"])).toThrow(TypeError); + }); +}); diff --git a/packages/jco-std/test/wintertc/component/.gitignore b/packages/jco-std/test/wintertc/component/.gitignore new file mode 100644 index 000000000..3508513c5 --- /dev/null +++ b/packages/jco-std/test/wintertc/component/.gitignore @@ -0,0 +1,2 @@ +# Bundles, WIT and components built by driver.ts +.build/ diff --git a/packages/jco-std/test/wintertc/component/driver.ts b/packages/jco-std/test/wintertc/component/driver.ts new file mode 100644 index 000000000..0193e63de --- /dev/null +++ b/packages/jco-std/test/wintertc/component/driver.ts @@ -0,0 +1,806 @@ +/** + * Builds a unit test file into a WASI 0.3 component, runs it under wasmtime and registers its + * results as vitest tests. + * + * Build, per test file: + * + * 1. bundle the file with Rolldown into one ES module, with `vitest` aliased to the in-component + * harness (`harness/vitest.ts`) and the harness's `wasi:cli/run` export (`harness/main.ts`) + * added; `wasi:*` and `jco:*` imports stay external; + * 2. `jco componentize --backend quickjs` it against `wit/world.wit`; + * 3. `wac plug` the Rust components (`wasm/wintertc-*.wasm`) for the `jco:wintertc` interfaces + * the component imports. + * + * Builds are cached in `.build/` by a hash of the bundle, the WIT and the tool versions (and, for + * the composed component, of the Rust components), so a rerun only bundles. + * + * Each run gets its own Node peer (`peer.ts`): an HTTP server whose URLs are passed in the + * component's environment and which receives the component's output as it arrives, for tests that + * need Node (interoperability checks, scripted HTTP exchanges, reading their own stdout). + * + * The component prints one `RESULT_PREFIX` line per result (see `harness/main.ts`), which + * `registerComponentTests` turns into one vitest test each, nested in `describe` blocks as in the + * test file. + */ +import { spawn } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import { existsSync, readFileSync, statSync } from "node:fs"; +import { cp, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { basename, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { rolldown } from "rolldown"; + +import { startPeer } from "./peer.ts"; + +// @ts-expect-error -- plain JavaScript build script without declarations +import { WASM_DIR, findJco, hasCommand } from "../e2e-qjs/build.mjs"; + +/** This directory. */ +const COMPONENT_DIR = fileURLToPath(new URL(".", import.meta.url)); + +/** The jco-std package directory. */ +const PACKAGE_DIR = join(COMPONENT_DIR, "..", "..", ".."); + +/** The repository root. */ +const REPO_DIR = join(PACKAGE_DIR, "..", ".."); + +/** The in-component harness. */ +const HARNESS_DIR = join(COMPONENT_DIR, "harness"); + +/** Where builds are cached. */ +const BUILD_DIR = join(COMPONENT_DIR, ".build"); + +/** WASI 0.3.0 WIT shipped with jco. */ +const WASI_WIT_DIR = join(REPO_DIR, "packages", "jco", "lib", "wit", "builtin", "0.3.0"); + +/** The `jco:wintertc` WIT. */ +const WINTERTC_WIT_DIR = join(PACKAGE_DIR, "wit", "wintertc-0.1.0"); + +/** The world the test components target. */ +const WORLD_WIT = join(COMPONENT_DIR, "wit", "world.wit"); + +/** Starts every result line; must match `harness/main.ts`. */ +const RESULT_PREFIX = "##wintertc-test## "; + +/** Rust components a test component may import. */ +const RUST_COMPONENTS = ["url", "compression", "encoding", "urlpattern", "crypto"]; + +/** Flags that run a WASI 0.3 command with outgoing HTTP in wasmtime 51. */ +const WASMTIME_FLAGS = [ + "run", + "-S", + "p3=y,http=y,inherit-network=y", + "-W", + "component-model-async=y", +]; + +/** A built test component. */ +export interface BuiltComponent { + /** The bundled ES module. */ + bundle: string; + /** The component before plugging. */ + component: string; + /** The component with the Rust components plugged in; the one to run. */ + composed: string; + /** The `jco:wintertc` interfaces plugged in. */ + plugged: string[]; +} + +/** One result line, as written by `harness/main.ts`. */ +export interface TestReport { + type: "test" | "hook"; + path: string[]; + name: string; + state: "pass" | "fail" | "skip" | "todo"; + duration: number; + error?: ReportedError; +} + +/** A failure, as serialized by the harness. */ +export interface ReportedError { + name: string; + message: string; + stack?: string; + actual?: string; + expected?: string; +} + +/** The outcome of running a test component. */ +export interface RunOutcome { + /** The results, in order. */ + reports: TestReport[]; + /** Whether the harness finished (printed its `done` line). */ + finished: boolean; + /** Why the harness itself failed, if it did. */ + crash: string | null; + /** The exit code (`null` if killed). */ + code: number | null; + /** stdout without the result lines. */ + stdout: string; + stderr: string; +} + +/** Options for running a test component. */ +export interface RunOptions { + /** Environment variables for the component. */ + env?: Record; + /** Kill wasmtime after this many milliseconds (default 120 000). */ + timeout?: number; + /** Receives the component's output as it arrives. */ + onOutput?: (target: "stdout" | "stderr", text: string) => void; +} + +/** + * SHA-256 of some strings or buffers, hex. + * + * @param parts - What to hash. + * @returns The digest. + */ +function hash(...parts: (string | Uint8Array)[]): string { + const digest = createHash("sha256"); + for (const part of parts) { + digest.update(part); + digest.update("\0"); + } + return digest.digest("hex"); +} + +/** + * Why component tests can't run here, or `null` if they can. + * + * @returns The reason, or `null`. + */ +export function skipReason(): string | null { + const missing: string[] = []; + if (!hasCommand("wasmtime")) { + missing.push("wasmtime 51 or later"); + } + for (const command of ["wac", "wasm-tools"]) { + if (!hasCommand(command)) { + missing.push(command); + } + } + if (findJco() === null) { + missing.push("jco 1.42+ (set JCO_BIN)"); + } + const absent = RUST_COMPONENTS.filter( + (name) => !existsSync(join(WASM_DIR, `wintertc-${name}.wasm`)), + ); + if (absent.length > 0) { + missing.push( + `wasm/wintertc-{${absent.join(",")}}.wasm (run node scripts/build-wintertc-components.mjs)`, + ); + } + return missing.length === 0 ? null : `missing ${missing.join(", ")}`; +} + +/** The result of a finished process. */ +interface ProcessResult { + code: number | null; + stdout: string; + stderr: string; +} + +/** + * Run a command to completion. + * + * @param command - The program. + * @param args - Its arguments. + * @param timeout - Kill it after this many milliseconds. + * @returns Its exit code and output. + */ +function runProcess( + command: string, + args: string[], + timeout: number, + onOutput?: (target: "stdout" | "stderr", text: string) => void, +): Promise { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + stdout.push(Buffer.from(chunk)); + onOutput?.("stdout", chunk); + }); + child.stderr.on("data", (chunk: string) => { + stderr.push(Buffer.from(chunk)); + onOutput?.("stderr", chunk); + }); + const timer = setTimeout(() => child.kill("SIGKILL"), timeout); + child.on("error", (error) => { + clearTimeout(timer); + reject(error); + }); + child.on("close", (code) => { + clearTimeout(timer); + resolve({ + code, + stdout: Buffer.concat(stdout).toString("utf8"), + stderr: Buffer.concat(stderr).toString("utf8"), + }); + }); + }); +} + +/** + * Run a build step and fail with its output if it fails. + * + * @param command - The program. + * @param args - Its arguments. + * @returns Its stdout. + */ +async function step(command: string, args: string[]): Promise { + const result = await runProcess(command, args, 600_000); + if (result.code !== 0) { + throw new Error( + `${command} ${args.join(" ")} failed (${String(result.code)}):\n${result.stdout}${result.stderr}`, + ); + } + return result.stdout; +} + +/** + * Write a file atomically: to a temporary name, then renamed, so concurrent builds never see a + * partial file. + * + * @param path - The destination. + * @param write - Writes the file at the temporary path it is given. + * @returns A promise that settles once the file is in place. + */ +async function writeAtomically( + path: string, + write: (temporary: string) => Promise, +): Promise { + const temporary = `${path}.${randomBytes(6).toString("hex")}.tmp`; + try { + await write(temporary); + await rename(temporary, path); + } finally { + await rm(temporary, { recursive: true, force: true }); + } +} + +/** + * Every file under a directory, sorted, as `[relative path, contents]`. + * + * @param dir - The directory. + * @param prefix - Prefix for the relative paths. + * @returns The files. + */ +async function treeContents(dir: string, prefix = ""): Promise<[string, Buffer][]> { + const files: [string, Buffer][] = []; + for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => + a.name.localeCompare(b.name), + )) { + const path = join(dir, entry.name); + if (entry.isDirectory()) { + files.push(...(await treeContents(path, `${prefix}${entry.name}/`))); + } else { + files.push([`${prefix}${entry.name}`, await readFile(path)]); + } + } + return files; +} + +/** + * Assemble the WIT package (the world plus its dependencies) once per content hash. + * + * @returns The WIT directory and its content hash. + */ +async function prepareWit(): Promise<{ dir: string; key: string }> { + const wasi = await treeContents(WASI_WIT_DIR); + const wintertc = await treeContents(WINTERTC_WIT_DIR); + const world = await readFile(WORLD_WIT); + const key = hash(world, ...[...wasi, ...wintertc].flat()).slice(0, 16); + const dir = join(BUILD_DIR, `wit-${key}`); + if (!existsSync(dir)) { + await mkdir(BUILD_DIR, { recursive: true }); + await writeAtomically(dir, async (temporary) => { + await mkdir(join(temporary, "deps"), { recursive: true }); + await cp(WORLD_WIT, join(temporary, "world.wit")); + for (const name of await readdir(WASI_WIT_DIR)) { + await cp(join(WASI_WIT_DIR, name), join(temporary, "deps", name), { recursive: true }); + } + await cp(WINTERTC_WIT_DIR, join(temporary, "deps", "jco-wintertc"), { recursive: true }); + }).catch((error: unknown) => { + // Another worker may have created it first. + if (!existsSync(dir)) { + throw error; + } + }); + } + return { dir, key }; +} + +/** + * What identifies the componentize toolchain: jco's CLI file and package manifest. + * + * @param jco - Path to `jco.js`. + * @returns A fingerprint. + */ +function toolchainFingerprint(jco: string): string { + const stats = statSync(jco); + const manifest = join(dirname(dirname(jco)), "package.json"); + return hash( + jco, + String(stats.size), + String(stats.mtimeMs), + existsSync(manifest) ? readFileSync(manifest) : "", + ); +} + +/** A bundled test file. */ +interface Bundle { + code: string; + map: string; +} + +/** + * Bundle a test file with the harness into one ES module. + * + * @param testFile - The test file. + * @returns The code and its source map. + */ +async function bundleTestFile(testFile: string): Promise { + const entry = `\0wintertc-unit-entry:${testFile}`; + const build = await rolldown({ + input: entry, + platform: "neutral", + external: (id) => /^(wasi|jco):/.test(id), + resolve: { + alias: { vitest: join(HARNESS_DIR, "vitest.ts") }, + // The sources import `.ts` files by their `.js` names. + extensionAlias: { ".js": [".ts", ".js"] }, + }, + // An external import whose bindings are all unused is dropped, so the component doesn't + // import it. + treeshake: { moduleSideEffects: (_id, external) => !external }, + plugins: [ + { + name: "wintertc-unit-entry", + resolveId(id) { + return id === entry ? entry : null; + }, + load(id) { + if (id !== entry) { + return null; + } + // The test file registers its tests; the harness exports `wasi:cli/run`. + return [ + `import ${JSON.stringify(testFile)};`, + `export { run } from ${JSON.stringify(join(HARNESS_DIR, "main.ts"))};`, + ].join("\n"); + }, + }, + ], + }); + try { + // Named as if in `BUILD_DIR`, so the map's sources are relative to it. + const { output } = await build.generate({ + file: join(BUILD_DIR, "bundle.js"), + format: "esm", + sourcemap: true, + // One module: dynamic imports in tests are inlined. + codeSplitting: false, + }); + const [chunk] = output; + return { code: chunk.code, map: chunk.map === null ? "" : chunk.map.toString() }; + } finally { + await build.close(); + } +} + +/** + * The `jco:wintertc` interfaces a component imports. + * + * @param component - The component file. + * @returns Interface names, such as `url`. + */ +async function wintertcImports(component: string): Promise { + const wit = await step("wasm-tools", ["component", "wit", component]); + const names = new Set(); + for (const match of wit.matchAll(/import jco:wintertc\/([a-z-]+)@0\.1\.0;/g)) { + names.add(match[1] ?? ""); + } + return [...names].sort(); +} + +/** + * Build (or reuse) the component for a test file. + * + * @param testFile - Absolute path of the test file. + * @returns The built component. + */ +export async function buildTestComponent(testFile: string): Promise { + const jco = findJco() as string | null; + if (jco === null) { + throw new Error("no jco 1.42+ found; set JCO_BIN to jco.js"); + } + const wit = await prepareWit(); + const { code, map } = await bundleTestFile(testFile); + const key = hash(code, wit.key, toolchainFingerprint(jco)).slice(0, 24); + const prefix = `${basename(testFile).replace(/\.test\.ts$/, "")}-`; + const dir = join(BUILD_DIR, `${prefix}${key}`); + await mkdir(dir, { recursive: true }); + + // Drop this file's older builds. + for (const name of await readdir(BUILD_DIR)) { + if ( + name.startsWith(prefix) && + /^[0-9a-f]{24}$/.test(name.slice(prefix.length)) && + join(BUILD_DIR, name) !== dir + ) { + await rm(join(BUILD_DIR, name), { recursive: true, force: true }); + } + } + + // Bundle and unplugged component, cached by the bundle's hash. + const bundle = join(dir, "bundle.js"); + const component = join(dir, "component.wasm"); + if (!existsSync(component)) { + await writeFile(bundle, code); + await writeFile(`${bundle}.map`, map); + await writeAtomically(component, (temporary) => + step(process.execPath, [ + jco, + "componentize", + bundle, + "--backend", + "quickjs", + "-w", + wit.dir, + "-n", + "unit", + "-o", + temporary, + ]).then(() => undefined), + ); + } + + // Composed component, cached by the Rust components' contents too. + const plugged = await wintertcImports(component); + const plugs = plugged.map((name) => join(WASM_DIR as string, `wintertc-${name}.wasm`)); + const plugKey = hash(...plugs.map((path) => readFileSync(path))).slice(0, 16); + const composed = join(dir, `composed-${plugKey}.wasm`); + if (!existsSync(composed)) { + await writeAtomically(composed, (temporary) => + step("wac", [ + "plug", + component, + ...plugs.flatMap((path) => ["--plug", path]), + "-o", + temporary, + ]).then(() => undefined), + ); + } + return { bundle, component, composed, plugged }; +} + +/** + * Split a component's stdout into result lines and other output. + * + * @param stdout - The output. + * @returns The results, whether the harness finished, why it crashed, and the other output. + */ +export function parseOutput(stdout: string): { + reports: TestReport[]; + finished: boolean; + crash: string | null; + other: string; +} { + const reports: TestReport[] = []; + let finished = false; + let crash: string | null = null; + const other: string[] = []; + for (const line of stdout.split("\n")) { + const at = line.indexOf(RESULT_PREFIX); + if (at === -1) { + other.push(line); + continue; + } + if (at > 0) { + other.push(line.slice(0, at)); + } + const record = JSON.parse(line.slice(at + RESULT_PREFIX.length)) as { + type: string; + message?: string; + stack?: string; + }; + if (record.type === "done") { + finished = true; + } else if (record.type === "crash") { + crash = `${record.message ?? ""}\n${record.stack ?? ""}`; + } else { + reports.push(record as TestReport); + } + } + return { reports, finished, crash, other: other.join("\n").trim() }; +} + +/** + * Run a built test component under wasmtime. + * + * @param composed - The composed component. + * @param options - Environment and time limit. + * @returns The results. + */ +export async function runTestComponent( + composed: string, + options: RunOptions = {}, +): Promise { + const env = Object.entries(options.env ?? {}).flatMap(([name, value]) => [ + "--env", + `${name}=${value}`, + ]); + const result = await runProcess( + "wasmtime", + [...WASMTIME_FLAGS, ...env, composed], + options.timeout ?? 120_000, + options.onOutput, + ); + const parsed = parseOutput(result.stdout); + return { + reports: parsed.reports, + finished: parsed.finished, + crash: parsed.crash, + code: result.code, + stdout: parsed.other, + stderr: result.stderr, + }; +} + +/** Decoded source map: per generated line, segments of [column, source, line, column]. */ +interface DecodedMap { + sources: string[]; + lines: number[][][]; +} + +/** Base64 digit values for VLQ decoding. */ +const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/** + * Decode a source map's `mappings` (absolute values, 0-based). + * + * @param map - The source map JSON. + * @param mapDir - The directory the map's `sources` are relative to. + * @returns The decoded map. + */ +function decodeSourceMap(map: string, mapDir: string): DecodedMap { + const parsed = JSON.parse(map) as { sources: string[]; sourceRoot?: string; mappings: string }; + const sources = parsed.sources.map((source) => + source.startsWith("/") ? source : join(mapDir, parsed.sourceRoot ?? "", source), + ); + const state = [0, 0, 0, 0]; + const lines = parsed.mappings.split(";").map((line) => { + state[0] = 0; + return line + .split(",") + .filter((segment) => segment !== "") + .map((segment) => { + const values: number[] = []; + let value = 0; + let shift = 0; + for (const char of segment) { + const digit = BASE64.indexOf(char); + value += (digit & 31) << shift; + if (digit & 32) { + shift += 5; + } else { + values.push(value & 1 ? -(value >>> 1) : value >>> 1); + value = 0; + shift = 0; + } + } + values.forEach((delta, index) => { + state[index] = (state[index] ?? 0) + delta; + }); + return state.slice(0, Math.max(values.length, 1)); + }); + }); + return { sources, lines }; +} + +/** + * Rewrite stack frames that point into the bundle to the original sources. + * + * @param stack - The stack from the component. + * @param map - The bundle's decoded source map, if any. + * @param bundle - The bundle's path, used in the rewritten frames when unmapped. + * @returns The rewritten frames (without the first, message line). + */ +function mapStack(stack: string, map: DecodedMap | null, bundle: string): string { + return ( + stack + .split("\n") + .filter((line) => /^\s*at /.test(line)) + .map((line) => + line.replace( + /\(?([^\s()]*?):(\d+)(?::(\d+))?\)?$/, + (whole, _file: string, lineText: string, columnText: string | undefined) => { + const line0 = Number(lineText) - 1; + const column0 = Number(columnText ?? "1") - 1; + const segments = map?.lines[line0]; + if (map === null || segments === undefined) { + return `(${bundle}:${lineText}:${columnText ?? "1"})`; + } + let best: number[] | undefined; + for (const segment of segments) { + if ((segment[0] ?? 0) <= column0 && segment.length >= 4) { + best = segment; + } + } + if (best === undefined) { + return whole; + } + return `(${map.sources[best[1] ?? 0] ?? bundle}:${(best[2] ?? 0) + 1}:${(best[3] ?? 0) + 1})`; + }, + ), + ) + // Harness frames are noise in a test failure. + .filter((line) => !line.includes(HARNESS_DIR)) + .join("\n") + ); +} + +/** An error rebuilt from a component's report, with the fields vitest uses for diffs. */ +class ComponentTestError extends Error { + actual?: string; + expected?: string; +} + +/** + * Turn a reported error into an `Error` for vitest. + * + * @param reported - The reported error. + * @param map - The bundle's decoded source map, if any. + * @param bundle - The bundle's path. + * @returns The error. + */ +function toError( + reported: ReportedError, + map: DecodedMap | null, + bundle: string, +): ComponentTestError { + const error = new ComponentTestError(reported.message); + error.name = reported.name; + error.stack = `${reported.name}: ${reported.message}\n${mapStack(reported.stack ?? "", map, bundle)}`; + if (reported.actual !== undefined && reported.expected !== undefined) { + error.actual = reported.actual; + error.expected = reported.expected; + } + return error; +} + +/** Results grouped by `describe` path, in the order they were reported. */ +interface ReportTree { + suites: Map; + /** Tests and failed hooks, and the order of suites among them. */ + items: (TestReport | { suite: string })[]; +} + +/** + * Group results by their `describe` path. + * + * @param reports - The results. + * @returns The tree. + */ +function groupReports(reports: TestReport[]): ReportTree { + const root: ReportTree = { suites: new Map(), items: [] }; + for (const report of reports) { + let node = root; + for (const name of report.path) { + let child = node.suites.get(name); + if (child === undefined) { + child = { suites: new Map(), items: [] }; + node.suites.set(name, child); + node.items.push({ suite: name }); + } + node = child; + } + node.items.push(report); + } + return root; +} + +/** + * Build and run a unit test file's component, then register one vitest test per result. Called + * from the module that the vitest config substitutes for the test file. + * + * @param testFile - Absolute path of the test file. + * @param options - How to run the component. + * @returns A promise that settles once the tests are registered. + */ +export async function registerComponentTests( + testFile: string, + options: RunOptions = {}, +): Promise { + const { describe, test } = await import("vitest"); + const reason = skipReason(); + if (reason !== null && process.env.WINTERTC_REQUIRE_TOOLS) { + throw new Error(`component tests can't run (WINTERTC_REQUIRE_TOOLS): ${reason}`); + } + if (reason !== null) { + test.skip(`component tests (skipped: ${reason})`); + return; + } + + let built: BuiltComponent; + let outcome: RunOutcome; + try { + built = await buildTestComponent(testFile); + // The component reaches the Node peer (see `peer.ts`) at the URLs in its environment. + const peer = await startPeer(); + try { + outcome = await runTestComponent(built.composed, { + ...options, + env: { ...peer.env, ...options.env }, + onOutput: (target, text) => peer.appendOutput(target, text), + }); + } finally { + await peer.close(); + } + } catch (error) { + test("build and run the test component", () => { + throw error; + }); + return; + } + + const mapFile = `${built.bundle}.map`; + // The map's sources are relative to `BUILD_DIR` (see `bundleTestFile`). + const map = existsSync(mapFile) + ? decodeSourceMap(readFileSync(mapFile, "utf8"), BUILD_DIR) + : null; + + /** + * Register a group of results. + * + * @param node - The group. + */ + const register = (node: ReportTree): void => { + for (const item of node.items) { + if ("suite" in item) { + const child = node.suites.get(item.suite); + if (child !== undefined) { + describe(item.suite, () => register(child)); + } + continue; + } + const name = item.type === "hook" ? `${item.name} hook` : item.name; + if (item.state === "skip") { + test.skip(name); + } else if (item.state === "todo") { + test.todo(name); + } else { + const error = item.error === undefined ? null : toError(item.error, map, built.bundle); + test(name, () => { + if (error !== null) { + throw error; + } + }); + } + } + }; + register(groupReports(outcome.reports)); + + // The harness itself must finish: a trap or a hang loses the remaining results. + if (!outcome.finished || outcome.crash !== null) { + test("the test component ran to completion", () => { + throw new Error( + [ + `wasmtime exited with ${String(outcome.code)} before the harness finished`, + outcome.crash === null ? "" : `harness error: ${outcome.crash}`, + outcome.stderr === "" ? "" : `stderr:\n${outcome.stderr}`, + outcome.stdout === "" ? "" : `stdout:\n${outcome.stdout}`, + `component: ${built.composed}`, + ] + .filter((part) => part !== "") + .join("\n"), + ); + }); + } +} diff --git a/packages/jco-std/test/wintertc/component/harness/equals.ts b/packages/jco-std/test/wintertc/component/harness/equals.ts new file mode 100644 index 000000000..b973b06bc --- /dev/null +++ b/packages/jco-std/test/wintertc/component/harness/equals.ts @@ -0,0 +1,409 @@ +/** + * Deep equality for `toEqual`, `toStrictEqual` and `toMatchObject`, following the rules of + * vitest's `equals`: primitives compare with `Object.is`, objects of different kinds never match, + * iterables compare by their elements, and `toEqual` ignores properties that are `undefined`. + */ +import { AsymmetricMatcher, format } from "./format.js"; + +export { AsymmetricMatcher }; + +/** How strictly to compare. */ +export interface EqualityOptions { + /** `toStrictEqual`: compare constructors and `undefined` properties. */ + strict: boolean; + /** `toMatchObject`: objects in `expected` need only be a subset of `actual`. */ + subset: boolean; +} + +/** + * Whether two values are deeply equal. + * + * @param actual - The value under test. + * @param expected - The expected value; may contain asymmetric matchers. + * @param options - How strictly to compare. + * @returns Whether they are equal. + */ +export function equals(actual: unknown, expected: unknown, options: EqualityOptions): boolean { + return equalValues(actual, expected, options, [], []); +} + +/** + * `Object.prototype.toString` of a value, for example `[object Map]`. + * + * @param value - The value. + * @returns Its class tag. + */ +function tag(value: unknown): string { + return Object.prototype.toString.call(value); +} + +/** + * Own enumerable string and symbol keys. + * + * @param object - The object. + * @returns Its keys. + */ +function ownKeys(object: object): (string | symbol)[] { + return [ + ...Object.keys(object), + ...Object.getOwnPropertySymbols(object).filter((key) => + Object.prototype.propertyIsEnumerable.call(object, key), + ), + ]; +} + +/** + * The deep comparison, tracking the objects being compared to stop at cycles. + * + * @param actual - The value under test. + * @param expected - The expected value. + * @param options - How strictly to compare. + * @param actualSeen - Objects of `actual` being compared. + * @param expectedSeen - Objects of `expected` being compared. + * @returns Whether they are equal. + */ +function equalValues( + actual: unknown, + expected: unknown, + options: EqualityOptions, + actualSeen: unknown[], + expectedSeen: unknown[], +): boolean { + if (expected instanceof AsymmetricMatcher) { + return expected.matches(actual); + } + if (actual instanceof AsymmetricMatcher) { + return actual.matches(expected); + } + if (Object.is(actual, expected)) { + return true; + } + if ( + typeof actual !== "object" || + typeof expected !== "object" || + actual === null || + expected === null + ) { + return false; + } + // `toMatchObject` with a plain object checks only that object's properties, whatever `actual` is. + if (options.subset && !Array.isArray(expected) && isPlainObject(expected)) { + return equalProperties(actual, expected, options, (left, right) => + equalValues(left, right, options, [...actualSeen, actual], [...expectedSeen, expected]), + ); + } + if (tag(actual) !== tag(expected)) { + return false; + } + + // Cycles: equal if both sides are at the same point in their cycle. + const seenAt = actualSeen.indexOf(actual); + if (seenAt !== -1) { + return expectedSeen[seenAt] === expected; + } + const nextActual = [...actualSeen, actual]; + const nextExpected = [...expectedSeen, expected]; + const recurse = (left: unknown, right: unknown): boolean => + equalValues(left, right, options, nextActual, nextExpected); + + if (options.strict && Object.getPrototypeOf(actual) !== Object.getPrototypeOf(expected)) { + return false; + } + if (actual instanceof Date && expected instanceof Date) { + return Object.is(actual.getTime(), expected.getTime()); + } + if (actual instanceof RegExp && expected instanceof RegExp) { + return actual.source === expected.source && actual.flags === expected.flags; + } + if (actual instanceof Error && expected instanceof Error) { + if (actual.name !== expected.name || actual.message !== expected.message) { + return false; + } + } + if (actual instanceof ArrayBuffer && expected instanceof ArrayBuffer) { + return recurse(new Uint8Array(actual), new Uint8Array(expected)); + } + if (actual instanceof DataView && expected instanceof DataView) { + return recurse( + new Uint8Array(actual.buffer, actual.byteOffset, actual.byteLength), + new Uint8Array(expected.buffer, expected.byteOffset, expected.byteLength), + ); + } + if (Array.isArray(actual) && Array.isArray(expected)) { + if (actual.length !== expected.length) { + return false; + } + for (let i = 0; i < expected.length; i++) { + if (options.strict && i in actual !== i in expected) { + return false; + } + if (!recurse(actual[i], expected[i])) { + return false; + } + } + return true; + } + if (ArrayBuffer.isView(actual) && ArrayBuffer.isView(expected)) { + const left = actual as unknown as ArrayLike; + const right = expected as unknown as ArrayLike; + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < right.length; i++) { + if (!Object.is(left[i], right[i])) { + return false; + } + } + return true; + } + if (actual instanceof Set && expected instanceof Set) { + if (actual.size !== expected.size) { + return false; + } + for (const value of expected) { + if (!actual.has(value) && ![...actual].some((candidate) => recurse(candidate, value))) { + return false; + } + } + return true; + } + if (actual instanceof Map && expected instanceof Map) { + if (actual.size !== expected.size) { + return false; + } + for (const [key, value] of expected) { + if (actual.has(key)) { + if (!recurse(actual.get(key), value)) { + return false; + } + continue; + } + const match = [...actual].some( + ([candidateKey, candidate]) => recurse(candidateKey, key) && recurse(candidate, value), + ); + if (!match) { + return false; + } + } + return true; + } + + // Other iterables compare by their elements (and then by their own properties, below). + if (!options.subset && isIterable(actual) && isIterable(expected)) { + if (Object.getPrototypeOf(actual) !== Object.getPrototypeOf(expected)) { + return false; + } + const left = [...actual]; + const right = [...expected]; + if (!recurse(left, right)) { + return false; + } + } + + return equalProperties(actual, expected, options, recurse); +} + +/** + * Whether an object is a plain object (its prototype is `Object.prototype` or `null`). + * + * @param value - The object. + * @returns Whether it is plain. + */ +function isPlainObject(value: object): boolean { + const proto: unknown = Object.getPrototypeOf(value); + return proto === null || proto === Object.prototype; +} + +/** + * Whether an object has a synchronous iterator. + * + * @param value - The object. + * @returns Whether it is iterable. + */ +function isIterable(value: object): value is Iterable { + return typeof (value as { [Symbol.iterator]?: unknown })[Symbol.iterator] === "function"; +} + +/** + * Compare own enumerable properties. + * + * @param actual - The object under test. + * @param expected - The expected object. + * @param options - How strictly to compare. + * @param recurse - Compares nested values. + * @returns Whether the properties match. + */ +function equalProperties( + actual: object, + expected: object, + options: EqualityOptions, + recurse: (left: unknown, right: unknown) => boolean, +): boolean { + const actualRecord = actual as Record; + const expectedRecord = expected as Record; + if (options.subset) { + // `toMatchObject` looks properties up through the prototype chain, so `{ name: "TypeError" }` + // matches an error. + return ownKeys(expected).every( + (key) => key in actual && recurse(actualRecord[key], expectedRecord[key]), + ); + } + const relevant = ( + object: object, + record: Record, + ): (string | symbol)[] => + ownKeys(object).filter((key) => options.strict || record[key] !== undefined); + const actualKeys = relevant(actual, actualRecord); + const expectedKeys = relevant(expected, expectedRecord); + if (actualKeys.length !== expectedKeys.length) { + return false; + } + return expectedKeys.every( + (key) => + Object.prototype.hasOwnProperty.call(actual, key) && + recurse(actualRecord[key], expectedRecord[key]), + ); +} + +/** `expect.stringMatching(pattern)`. */ +export class StringMatching extends AsymmetricMatcher { + readonly #pattern: RegExp; + + /** + * @param pattern - A regular expression, or a string to build one from. + */ + constructor(pattern: RegExp | string) { + super(); + this.#pattern = typeof pattern === "string" ? new RegExp(pattern) : pattern; + } + + matches(actual: unknown): boolean { + return typeof actual === "string" && this.#pattern.test(actual); + } + + describe(): string { + return `StringMatching ${String(this.#pattern)}`; + } +} + +/** `expect.stringContaining(text)`. */ +export class StringContaining extends AsymmetricMatcher { + readonly #text: string; + + /** + * @param text - The substring. + */ + constructor(text: string) { + super(); + this.#text = text; + } + + matches(actual: unknown): boolean { + return typeof actual === "string" && actual.includes(this.#text); + } + + describe(): string { + return `StringContaining ${JSON.stringify(this.#text)}`; + } +} + +/** `expect.any(Class)`. */ +export class AnyOf extends AsymmetricMatcher { + readonly #type: unknown; + + /** + * @param type - A constructor such as `String` or `Uint8Array`. + */ + constructor(type: unknown) { + super(); + this.#type = type; + } + + matches(actual: unknown): boolean { + switch (this.#type) { + case String: + return typeof actual === "string" || actual instanceof String; + case Number: + return typeof actual === "number" || actual instanceof Number; + case Boolean: + return typeof actual === "boolean" || actual instanceof Boolean; + case BigInt: + return typeof actual === "bigint"; + case Symbol: + return typeof actual === "symbol"; + case Function: + return typeof actual === "function"; + case Object: + return typeof actual === "object" && actual !== null; + default: + return typeof this.#type === "function" && actual instanceof this.#type; + } + } + + describe(): string { + const name = (this.#type as { name?: string } | null)?.name; + return `Any<${name ?? format(this.#type)}>`; + } +} + +/** `expect.anything()`. */ +export class Anything extends AsymmetricMatcher { + matches(actual: unknown): boolean { + return actual !== null && actual !== undefined; + } + + describe(): string { + return "Anything"; + } +} + +/** `expect.objectContaining(object)`. */ +export class ObjectContaining extends AsymmetricMatcher { + readonly #expected: object; + + /** + * @param expected - The properties to look for. + */ + constructor(expected: object) { + super(); + this.#expected = expected; + } + + matches(actual: unknown): boolean { + return ( + typeof actual === "object" && + actual !== null && + equals(actual, this.#expected, { strict: false, subset: true }) + ); + } + + describe(): string { + return `ObjectContaining ${format(this.#expected)}`; + } +} + +/** `expect.arrayContaining(array)`. */ +export class ArrayContaining extends AsymmetricMatcher { + readonly #expected: unknown[]; + + /** + * @param expected - The elements to look for. + */ + constructor(expected: unknown[]) { + super(); + this.#expected = expected; + } + + matches(actual: unknown): boolean { + return ( + Array.isArray(actual) && + this.#expected.every((item) => + actual.some((candidate) => equals(candidate, item, { strict: false, subset: false })), + ) + ); + } + + describe(): string { + return `ArrayContaining ${format(this.#expected)}`; + } +} diff --git a/packages/jco-std/test/wintertc/component/harness/expect.ts b/packages/jco-std/test/wintertc/component/harness/expect.ts new file mode 100644 index 000000000..229dea8ad --- /dev/null +++ b/packages/jco-std/test/wintertc/component/harness/expect.ts @@ -0,0 +1,410 @@ +/** + * `expect`: the matchers of vitest's `expect` that the unit tests use, with `.not`, `.resolves`, + * `.rejects`, `expect.poll` and the common asymmetric matchers. + */ +import { + AnyOf, + Anything, + ArrayContaining, + AsymmetricMatcher, + ObjectContaining, + StringContaining, + StringMatching, + equals, +} from "./equals.js"; +import { format } from "./format.js"; +import { sleep } from "./host.js"; + +/** A failed assertion; `actual` and `expected` are printed values, for the driver's diff. */ +export class AssertionError extends Error { + readonly actual: string | undefined; + readonly expected: string | undefined; + + /** + * @param message - What failed. + * @param actual - The value under test, printed. + * @param expected - The expected value, printed. + */ + constructor(message: string, actual?: string, expected?: string) { + super(message); + this.name = "AssertionError"; + this.actual = actual; + this.expected = expected; + } +} + +/** What a matcher found. */ +interface MatchResult { + /** Whether the value matched (before `.not` is applied). */ + pass: boolean; + /** Describes the check, for example `"to be 3"`; prefixed with `"expected "`. */ + description: string; + /** The expected value for a diff, if one makes sense. */ + expected?: unknown; +} + +/** How a matcher receives the value under test. */ +interface MatchContext { + /** The value: the `expect` argument, or what the promise settled with. */ + received: unknown; + /** Whether the value is a rejection reason (`.rejects`), so `toThrow` uses it as the error. */ + rejected: boolean; +} + +/** A matcher implementation. */ +type Matcher = (context: MatchContext, ...args: unknown[]) => MatchResult; + +/** + * What a function threw, or that it didn't throw. + * + * @param context - The matcher context. + * @returns The thrown value, if any. + */ +function thrownBy(context: MatchContext): { threw: boolean; error: unknown } { + if (context.rejected) { + return { threw: true, error: context.received }; + } + if (typeof context.received !== "function") { + throw new AssertionError(`expected a function to call, got ${format(context.received)}`); + } + try { + (context.received as () => unknown)(); + } catch (error) { + return { threw: true, error }; + } + return { threw: false, error: undefined }; +} + +/** + * The message of a thrown value. + * + * @param error - The thrown value. + * @returns Its `message`, or the value as a string. + */ +function messageOf(error: unknown): string { + if (typeof error === "object" && error !== null && "message" in error) { + return String((error as { message: unknown }).message); + } + return String(error); +} + +/** + * Compare two numbers or bigints with an operator. + * + * @param name - The operator's description. + * @param compare - The comparison. + * @returns The matcher. + */ +function numeric( + name: string, + compare: (left: number | bigint, right: number | bigint) => boolean, +): Matcher { + return ({ received }, expected) => { + if ( + (typeof received !== "number" && typeof received !== "bigint") || + (typeof expected !== "number" && typeof expected !== "bigint") + ) { + throw new AssertionError( + `${name}: expected numbers, got ${format(received)} and ${format(expected)}`, + ); + } + return { pass: compare(received, expected), description: `${name} ${format(expected)}` }; + }; +} + +/** + * Look up a property path such as `"a.b"` or `["a", "b"]`. + * + * @param object - The object. + * @param path - The path. + * @returns Whether every step exists, and the value found. + */ +function propertyAt(object: unknown, path: unknown): { found: boolean; value: unknown } { + const steps = Array.isArray(path) ? path.map(String) : String(path).split("."); + let current = object; + for (const step of steps) { + if (current === null || current === undefined || !(step in Object(current))) { + return { found: false, value: undefined }; + } + current = (current as Record)[step]; + } + return { found: true, value: current }; +} + +/** The matchers, by name. */ +const MATCHERS: Record = { + toBe: ({ received }, expected) => ({ + pass: Object.is(received, expected), + description: `to be ${format(expected)} // Object.is equality`, + expected, + }), + toEqual: ({ received }, expected) => ({ + pass: equals(received, expected, { strict: false, subset: false }), + description: `to deeply equal ${format(expected)}`, + expected, + }), + toStrictEqual: ({ received }, expected) => ({ + pass: equals(received, expected, { strict: true, subset: false }), + description: `to strictly equal ${format(expected)}`, + expected, + }), + toMatchObject: ({ received }, expected) => ({ + pass: + typeof received === "object" && + received !== null && + equals(received, expected, { strict: false, subset: true }), + description: `to match object ${format(expected)}`, + expected, + }), + toBeNull: ({ received }) => ({ pass: received === null, description: "to be null" }), + toBeUndefined: ({ received }) => ({ + pass: received === undefined, + description: "to be undefined", + }), + toBeDefined: ({ received }) => ({ pass: received !== undefined, description: "to be defined" }), + toBeTruthy: ({ received }) => ({ pass: Boolean(received), description: "to be truthy" }), + toBeFalsy: ({ received }) => ({ pass: !received, description: "to be falsy" }), + toBeNaN: ({ received }) => ({ pass: Number.isNaN(received), description: "to be NaN" }), + toBeInstanceOf: ({ received }, type) => ({ + pass: typeof type === "function" && received instanceof type, + description: `to be an instance of ${(type as { name?: string } | null)?.name ?? format(type)}`, + }), + toBeTypeOf: ({ received }, type) => ({ + pass: typeof received === type, + description: `to be type of ${format(type)}`, + }), + toBeGreaterThan: numeric("to be greater than", (left, right) => left > right), + toBeGreaterThanOrEqual: numeric("to be greater than or equal to", (left, right) => left >= right), + toBeLessThan: numeric("to be less than", (left, right) => left < right), + toBeLessThanOrEqual: numeric("to be less than or equal to", (left, right) => left <= right), + toBeCloseTo: ({ received }, expected, digits = 2) => ({ + pass: Math.abs(Number(received) - Number(expected)) < 10 ** -Number(digits) / 2, + description: `to be close to ${format(expected)} (${String(digits)} digits)`, + }), + toMatch: ({ received }, pattern) => ({ + pass: + typeof received === "string" && + (pattern instanceof RegExp ? pattern.test(received) : received.includes(String(pattern))), + description: `to match ${format(pattern)}`, + }), + toContain: ({ received }, item) => { + let pass = false; + if (typeof received === "string") { + pass = received.includes(String(item)); + } else if (received !== null && typeof received === "object" && Symbol.iterator in received) { + pass = [...(received as Iterable)].some((candidate) => candidate === item); + } + return { pass, description: `to contain ${format(item)}` }; + }, + toContainEqual: ({ received }, item) => ({ + pass: [...(received as Iterable)].some((candidate) => + equals(candidate, item, { strict: false, subset: false }), + ), + description: `to contain equal ${format(item)}`, + }), + toHaveLength: ({ received }, length) => ({ + pass: (received as { length?: unknown } | null)?.length === length, + description: `to have length ${format(length)}`, + expected: length, + }), + toHaveProperty: ({ received }, ...args) => { + const [path, value] = args; + const { found, value: actual } = propertyAt(received, path); + const checkValue = args.length > 1; + return { + pass: found && (!checkValue || equals(actual, value, { strict: false, subset: false })), + description: `to have property ${format(path)}${checkValue ? ` with value ${format(value)}` : ""}`, + }; + }, + toThrow: (context, expected) => { + const { threw, error } = thrownBy(context); + if (!threw) { + return { + pass: false, + description: `to throw${expected === undefined ? "" : ` ${format(expected)}`}`, + }; + } + let pass = true; + if (typeof expected === "string") { + pass = messageOf(error).includes(expected); + } else if (expected instanceof RegExp) { + pass = expected.test(messageOf(error)); + } else if (typeof expected === "function") { + pass = error instanceof expected; + } else if (expected instanceof AsymmetricMatcher) { + pass = expected.matches(error); + } else if (expected instanceof Error) { + pass = messageOf(error) === expected.message; + } else if (typeof expected === "object" && expected !== null) { + pass = equals(error, expected, { strict: false, subset: true }); + } + const name = typeof expected === "function" ? (expected as { name?: string }).name : undefined; + return { + pass, + description: `to throw ${name ?? format(expected)}, threw ${format(error)}`, + }; + }, +}; +MATCHERS.toThrowError = MATCHERS.toThrow as Matcher; + +/** The matchers, as `expect(value)` returns them. */ +export type Assertion = Record unknown> & { + readonly not: Assertion; + readonly resolves: Assertion; + readonly rejects: Assertion; +}; + +/** How an assertion gets its value. */ +type Mode = "sync" | "resolves" | "rejects"; + +/** + * Apply a matcher and throw if it fails. + * + * @param name - The matcher's name. + * @param context - The value under test. + * @param negated - Whether `.not` was used. + * @param args - The matcher's arguments. + * @param message - The custom message passed to `expect`, if any. + */ +function check( + name: string, + context: MatchContext, + negated: boolean, + args: unknown[], + message: string | undefined, +): void { + const matcher = MATCHERS[name]; + if (matcher === undefined) { + throw new TypeError(`expect(…).${name} is not supported by the component test harness`); + } + const result = matcher(context, ...args); + if (result.pass === negated) { + const printed = context.rejected + ? `promise rejecting with ${format(context.received)}` + : format(context.received); + const text = `expected ${printed} ${negated ? "not " : ""}${result.description}`; + const diff = !negated && "expected" in result; + throw new AssertionError( + message === undefined ? text : `${message}: ${text}`, + diff ? format(context.received) : undefined, + diff ? format(result.expected) : undefined, + ); + } +} + +/** + * Build the matcher object for a value. + * + * @param received - The value under test. + * @param negated - Whether `.not` was used. + * @param mode - Whether the value is used as is or awaited. + * @param message - The custom message passed to `expect`, if any. + * @returns The assertion. + */ +function assertion( + received: unknown, + negated: boolean, + mode: Mode, + message: string | undefined, +): Assertion { + const target = {} as Assertion; + for (const name of Object.keys(MATCHERS)) { + target[name] = (...args: unknown[]): unknown => { + if (mode === "sync") { + check(name, { received, rejected: false }, negated, args, message); + return undefined; + } + return Promise.resolve(received).then( + (value) => { + if (mode === "rejects") { + throw new AssertionError( + `expected promise to reject, it resolved with ${format(value)}`, + ); + } + check(name, { received: value, rejected: false }, negated, args, message); + }, + (reason: unknown) => { + if (mode === "resolves") { + throw new AssertionError( + `expected promise to resolve, it rejected with ${format(reason)}`, + ); + } + check(name, { received: reason, rejected: true }, negated, args, message); + }, + ); + }; + } + Object.defineProperties(target, { + not: { get: () => assertion(received, !negated, mode, message) }, + resolves: { get: () => assertion(received, negated, "resolves", message) }, + rejects: { get: () => assertion(received, negated, "rejects", message) }, + }); + return target; +} + +/** Options of `expect.poll`. */ +interface PollOptions { + /** How long to keep trying, in milliseconds (default 1000). */ + timeout?: number; + /** How long to wait between tries, in milliseconds (default 50). */ + interval?: number; +} + +/** + * `expect.poll(fn)`: matchers that call `fn` until the assertion passes or the timeout elapses. + * + * @param poll - Produces the value (may return a promise). + * @param options - Timeout and interval. + * @param negated - Whether `.not` was used. + * @returns The assertion; every matcher returns a promise. + */ +function pollAssertion(poll: () => unknown, options: PollOptions = {}, negated = false): Assertion { + const timeout = options.timeout ?? 1000; + const interval = options.interval ?? 50; + const target = {} as Assertion; + for (const name of Object.keys(MATCHERS)) { + target[name] = async (...args: unknown[]): Promise => { + let waited = 0; + for (;;) { + try { + check(name, { received: await poll(), rejected: false }, negated, args, undefined); + return; + } catch (error) { + if (waited >= timeout) { + throw error; + } + } + await sleep(interval).done; + waited += interval; + } + }; + } + Object.defineProperty(target, "not", { get: () => pollAssertion(poll, options, !negated) }); + return target; +} + +/** The `expect` function and its static helpers. */ +export interface Expect { + (received: unknown, message?: string): Assertion; + poll(poll: () => unknown, options?: PollOptions): Assertion; + stringMatching(pattern: RegExp | string): AsymmetricMatcher; + stringContaining(text: string): AsymmetricMatcher; + any(type: unknown): AsymmetricMatcher; + anything(): AsymmetricMatcher; + objectContaining(object: object): AsymmetricMatcher; + arrayContaining(array: unknown[]): AsymmetricMatcher; +} + +/** vitest's `expect`. */ +export const expect: Expect = Object.assign( + (received: unknown, message?: string): Assertion => assertion(received, false, "sync", message), + { + poll: (poll: () => unknown, options?: PollOptions): Assertion => pollAssertion(poll, options), + stringMatching: (pattern: RegExp | string): AsymmetricMatcher => new StringMatching(pattern), + stringContaining: (text: string): AsymmetricMatcher => new StringContaining(text), + any: (type: unknown): AsymmetricMatcher => new AnyOf(type), + anything: (): AsymmetricMatcher => new Anything(), + objectContaining: (object: object): AsymmetricMatcher => new ObjectContaining(object), + arrayContaining: (array: unknown[]): AsymmetricMatcher => new ArrayContaining(array), + }, +); diff --git a/packages/jco-std/test/wintertc/component/harness/format.ts b/packages/jco-std/test/wintertc/component/harness/format.ts new file mode 100644 index 000000000..6771716db --- /dev/null +++ b/packages/jco-std/test/wintertc/component/harness/format.ts @@ -0,0 +1,168 @@ +/** + * A compact pretty-printer for assertion messages, in the spirit of vitest's `stringify`. + */ + +/** A matcher like `expect.stringMatching(…)` that can stand in for a value. */ +export abstract class AsymmetricMatcher { + /** + * Whether `actual` matches. + * + * @param actual - The value being compared. + * @returns Whether it matches. + */ + abstract matches(actual: unknown): boolean; + + /** + * How the matcher is printed. + * + * @returns Its description. + */ + abstract describe(): string; +} + +/** How deep nested values are printed before being elided. */ +const MAX_DEPTH = 4; + +/** How many entries of an array, object, map or set are printed before being elided. */ +const MAX_ENTRIES = 30; + +/** + * Print a value for an assertion message. + * + * @param value - Any value. + * @returns Its description. + */ +export function format(value: unknown): string { + return formatValue(value, 0, []); +} + +/** + * The name of an object's constructor, or `"Object"`. + * + * @param value - The object. + * @returns The name. + */ +function constructorName(value: object): string { + const proto: unknown = Object.getPrototypeOf(value); + if (proto === null) { + return "Object"; + } + const ctor = (proto as { constructor?: { name?: unknown } }).constructor; + return typeof ctor?.name === "string" && ctor.name !== "" ? ctor.name : "Object"; +} + +/** + * Print a list of entries with a prefix, eliding past `MAX_ENTRIES`. + * + * @param prefix - Printed before the brackets, for example `"Map "`. + * @param open - The opening bracket. + * @param close - The closing bracket. + * @param entries - The printed entries. + * @param total - How many entries there are in all. + * @returns The printed list. + */ +function list( + prefix: string, + open: string, + close: string, + entries: string[], + total: number, +): string { + const shown = total > entries.length ? [...entries, `… ${total - entries.length} more`] : entries; + return shown.length === 0 + ? `${prefix}${open}${close}` + : `${prefix}${open} ${shown.join(", ")} ${close}`; +} + +/** + * Print one value. + * + * @param value - The value. + * @param depth - Current nesting depth. + * @param seen - Objects being printed, to detect cycles. + * @returns Its description. + */ +function formatValue(value: unknown, depth: number, seen: object[]): string { + switch (typeof value) { + case "string": + return JSON.stringify(value); + case "number": + return Object.is(value, -0) ? "-0" : String(value); + case "bigint": + return `${value}n`; + case "symbol": + return value.toString(); + case "undefined": + return "undefined"; + case "boolean": + return String(value); + case "function": + return `[Function ${value.name || "anonymous"}]`; + default: + break; + } + if (value === null) { + return "null"; + } + + if (value instanceof AsymmetricMatcher) { + return value.describe(); + } + const object = value as object; + if (seen.includes(object)) { + return "[Circular]"; + } + const name = constructorName(object); + if (value instanceof Error) { + return `[${value.name}: ${value.message}]`; + } + if (value instanceof Date) { + return `Date(${Number.isNaN(value.getTime()) ? "Invalid" : value.toISOString()})`; + } + if (value instanceof RegExp) { + return String(value); + } + if (depth >= MAX_DEPTH) { + return `[${name}]`; + } + + const inner = [...seen, object]; + const item = (entry: unknown): string => formatValue(entry, depth + 1, inner); + if (Array.isArray(value)) { + return list("", "[", "]", value.slice(0, MAX_ENTRIES).map(item), value.length); + } + if (ArrayBuffer.isView(value) && !(value instanceof DataView)) { + const elements = Array.from(value as unknown as ArrayLike); + return list(`${name} `, "[", "]", elements.slice(0, MAX_ENTRIES).map(item), elements.length); + } + if (value instanceof ArrayBuffer) { + const bytes = Array.from(new Uint8Array(value)); + return list("ArrayBuffer ", "[", "]", bytes.slice(0, MAX_ENTRIES).map(item), bytes.length); + } + if (value instanceof Map) { + const entries = [...value] + .slice(0, MAX_ENTRIES) + .map(([key, entry]) => `${item(key)} => ${item(entry)}`); + return list("Map ", "{", "}", entries, value.size); + } + if (value instanceof Set) { + return list("Set ", "{", "}", [...value].slice(0, MAX_ENTRIES).map(item), value.size); + } + + const keys: (string | symbol)[] = [ + ...Object.keys(object), + ...Object.getOwnPropertySymbols(object).filter((key) => + Object.prototype.propertyIsEnumerable.call(object, key), + ), + ]; + const entries = keys.slice(0, MAX_ENTRIES).map((key) => { + const label = + typeof key === "symbol" + ? `[${key.toString()}]` + : /^[A-Za-z_$][\w$]*$/.test(key) + ? key + : JSON.stringify(key); + return `${label}: ${item((object as Record)[key])}`; + }); + return list(name === "Object" ? "" : `${name} `, "{", "}", entries, keys.length); +} diff --git a/packages/jco-std/test/wintertc/component/harness/host.ts b/packages/jco-std/test/wintertc/component/harness/host.ts new file mode 100644 index 000000000..06c13c340 --- /dev/null +++ b/packages/jco-std/test/wintertc/component/harness/host.ts @@ -0,0 +1,172 @@ +/** + * The harness's own use of WASI: writing result lines to stdout, reading the monotonic clock and + * sleeping. It talks to `wasi:*@0.3.0` directly so that it doesn't depend on the APIs under test. + * + * The harness only runs inside componentize-qjs components, so it uses componentize-qjs's + * conventions: a `stream` argument is an async iterable of `Uint8Array` chunks, a returned + * future is read with `read()`, and an async import call's promise has `cancel()`. + */ +import { now, waitFor } from "wasi:clocks/monotonic-clock@0.3.0"; +import { writeViaStream } from "wasi:cli/stdout@0.3.0"; + +/** Nanoseconds per millisecond. */ +const NS_PER_MS = 1_000_000; + +/** A future under componentize-qjs. */ +interface QjsFuture { + read(): Promise; +} + +/** + * Milliseconds on the monotonic clock, from an arbitrary origin. + * + * @returns The current reading. + */ +export function monotonicMs(): number { + return Number(now()) / NS_PER_MS; +} + +/** A sleep that can be cancelled. */ +export interface Sleep { + /** Settles after the delay; never settles once cancelled. */ + readonly done: Promise; + /** Cancel the host wait. */ + cancel(): void; +} + +/** + * Sleep on `wasi:clocks/monotonic-clock.wait-for`. + * + * @param ms - The delay in milliseconds. + * @returns The pending sleep. + */ +export function sleep(ms: number): Sleep { + const call = waitFor(BigInt(Math.max(0, Math.ceil(ms * NS_PER_MS)))); + let cancelled = false; + const done = new Promise((resolve) => { + call.then( + () => { + if (!cancelled) { + resolve(); + } + }, + () => undefined, + ); + }); + return { + done, + cancel(): void { + if (cancelled) { + return; + } + cancelled = true; + (call as { cancel?(): void }).cancel?.(); + }, + }; +} + +/** + * Encode a string as UTF-8, replacing lone surrogates with U+FFFD. The harness can't rely on the + * `TextEncoder` under test. + * + * @param text - The string. + * @returns Its UTF-8 bytes. + */ +export function utf8Encode(text: string): Uint8Array { + const bytes: number[] = []; + for (let i = 0; i < text.length; i++) { + let code = text.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) { + const low = text.charCodeAt(i + 1); + if (low >= 0xdc00 && low <= 0xdfff) { + code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00); + i++; + } + } + if (code >= 0xd800 && code <= 0xdfff) { + code = 0xfffd; + } + if (code < 0x80) { + bytes.push(code); + } else if (code < 0x800) { + bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)); + } else if (code < 0x10000) { + bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f)); + } else { + bytes.push( + 0xf0 | (code >> 18), + 0x80 | ((code >> 12) & 0x3f), + 0x80 | ((code >> 6) & 0x3f), + 0x80 | (code & 0x3f), + ); + } + } + return Uint8Array.from(bytes); +} + +/** + * Lines written to stdout through one `write-via-stream` call. Each line is one chunk, so it + * isn't interleaved with output that the code under test writes through its own stream. + */ +export class StdoutLines { + #queue: Uint8Array[] = []; + #closed: boolean = false; + #wake: (() => void) | null = null; + #result: Promise | null = null; + + /** + * Queue a line, opening the stream on first use. Must be called during an export call. + * + * @param line - The line, without its newline. + */ + write(line: string): void { + if (this.#closed) { + return; + } + this.#queue.push(utf8Encode(`${line}\n`)); + if (this.#result === null) { + const future = writeViaStream(this.#chunks() as unknown as AsyncIterable); + this.#result = (future as unknown as QjsFuture).read().catch(() => undefined); + } + this.#notify(); + } + + /** + * End the stream and wait until the host has taken every line. + * + * @returns A promise that settles once the output is written. + */ + async close(): Promise { + this.#closed = true; + this.#notify(); + await this.#result; + } + + /** Wake the chunk generator if it is waiting. */ + #notify(): void { + const wake = this.#wake; + this.#wake = null; + wake?.(); + } + + /** + * The stream's chunks: queued lines until `close`. + * + * @yields Each line's bytes. + */ + async *#chunks(): AsyncGenerator { + for (;;) { + const next = this.#queue.shift(); + if (next !== undefined) { + yield next; + continue; + } + if (this.#closed) { + return; + } + await new Promise((resolve) => { + this.#wake = resolve; + }); + } + } +} diff --git a/packages/jco-std/test/wintertc/component/harness/main.ts b/packages/jco-std/test/wintertc/component/harness/main.ts new file mode 100644 index 000000000..bf9830060 --- /dev/null +++ b/packages/jco-std/test/wintertc/component/harness/main.ts @@ -0,0 +1,40 @@ +/** + * The test component's `wasi:cli/run@0.3.0` export: runs the registered tests and writes one + * result line per test to stdout, `RESULT_PREFIX` followed by a JSON `TestReport`, then a final + * line `RESULT_PREFIX` followed by `{"type":"done",…}`. The run fails (exit status 1) when a test + * or hook failed. + */ +import { StdoutLines } from "./host.js"; +import { runTests } from "./vitest.js"; + +/** Starts every line the driver parses. */ +export const RESULT_PREFIX = "##wintertc-test## "; + +/** The `wasi:cli/run` interface. */ +export const run: { run(): Promise } = { + async run(): Promise { + const output = new StdoutLines(); + let failed = 0; + try { + failed = await runTests((result) => output.write(RESULT_PREFIX + JSON.stringify(result))); + output.write(RESULT_PREFIX + JSON.stringify({ type: "done", failed })); + } catch (error) { + failed++; + output.write( + RESULT_PREFIX + + JSON.stringify({ + type: "crash", + message: String(error), + stack: (error as { stack?: unknown } | null)?.stack, + }), + ); + } + // The process ends when `run` returns, so wait until the host has taken every line. + await output.close(); + if (failed > 0) { + // `run` returns `result` with no error payload, which componentize-qjs lowers from a thrown + // `undefined`. + throw undefined; + } + }, +}; diff --git a/packages/jco-std/test/wintertc/component/harness/vitest.ts b/packages/jco-std/test/wintertc/component/harness/vitest.ts new file mode 100644 index 000000000..748d8e8a7 --- /dev/null +++ b/packages/jco-std/test/wintertc/component/harness/vitest.ts @@ -0,0 +1,704 @@ +/** + * The part of vitest's API that the WinterTC unit tests use, for running them inside a component. + * Test files import it as `vitest` (the driver aliases the module when bundling). + * + * Registration works as in vitest, except that `describe` bodies run when the tests run (in the + * `wasi:cli/run` export call), not when the module is evaluated: componentize-qjs evaluates the + * module at build time and snapshots the result, so code that calls imports must not run then. + * + * `runTests` runs every registered test in order, each hook and test with a time limit, and calls + * `report` once per test (and once per failing hook or `describe` body). + */ +import { AssertionError, expect } from "./expect.js"; +import { format } from "./format.js"; +import { monotonicMs, sleep } from "./host.js"; + +export { expect }; + +/** Default time limit for a test or hook, in milliseconds. */ +const DEFAULT_TIMEOUT = 10_000; + +/** A test body or hook. */ +type TestFunction = (context: TestContext) => unknown; + +/** A hook; `beforeAll` and `beforeEach` may return a cleanup function. */ +type HookFunction = () => unknown; + +/** What a test body receives. */ +export interface TestContext { + /** The `expect` function. */ + expect: typeof expect; + /** Skip the test from inside it. */ + skip(note?: string): never; +} + +/** How a test or suite was registered. */ +type Mode = "run" | "skip" | "only" | "todo"; + +/** A registered test. */ +interface TestEntry { + readonly kind: "test"; + readonly name: string; + readonly fn: TestFunction | undefined; + readonly mode: Mode; + readonly timeout: number; +} + +/** A registered `describe` block. */ +interface SuiteEntry { + readonly kind: "suite"; + readonly name: string; + /** The body, run when tests are collected; `undefined` for the root. */ + readonly fn: (() => unknown) | undefined; + readonly mode: Mode; + readonly children: (TestEntry | SuiteEntry)[]; + readonly beforeAll: { fn: HookFunction; timeout: number }[]; + readonly afterAll: { fn: HookFunction; timeout: number }[]; + readonly beforeEach: { fn: HookFunction; timeout: number }[]; + readonly afterEach: { fn: HookFunction; timeout: number }[]; +} + +/** One result, as reported to the driver. */ +export interface TestReport { + /** `test` for a test; `hook` for a failed hook or `describe` body outside a test. */ + readonly type: "test" | "hook"; + /** Names of the enclosing `describe` blocks, outermost first. */ + readonly path: string[]; + readonly name: string; + readonly state: "pass" | "fail" | "skip" | "todo"; + /** Milliseconds spent in the test and its `beforeEach`/`afterEach` hooks. */ + readonly duration: number; + readonly error?: ReportedError; +} + +/** A failure, serialized for the driver. */ +export interface ReportedError { + readonly name: string; + readonly message: string; + readonly stack?: string; + /** Printed value under test, for a diff. */ + readonly actual?: string; + /** Printed expected value, for a diff. */ + readonly expected?: string; +} + +/** + * Create an empty suite. + * + * @param name - The `describe` name. + * @param fn - Its body. + * @param mode - How it was registered. + * @returns The suite. + */ +function createSuite(name: string, fn: (() => unknown) | undefined, mode: Mode): SuiteEntry { + return { + kind: "suite", + name, + fn, + mode, + children: [], + beforeAll: [], + afterAll: [], + beforeEach: [], + afterEach: [], + }; +} + +/** The file's top-level suite. */ +const root: SuiteEntry = createSuite("", undefined, "run"); + +/** The suite that registrations go to. */ +let current: SuiteEntry = root; + +/** Thrown by `context.skip()`. */ +class SkipSignal extends Error {} + +/** + * Read a timeout argument: a number, or an options object with `timeout`. + * + * @param options - The argument. + * @returns The timeout in milliseconds. + */ +function timeoutOf(options: unknown): number { + if (typeof options === "number") { + return options; + } + if ( + typeof options === "object" && + options !== null && + typeof (options as { timeout?: unknown }).timeout === "number" + ) { + return (options as { timeout: number }).timeout; + } + return DEFAULT_TIMEOUT; +} + +/** + * Format a `.each` name: printf-style placeholders take the case's arguments in order, and + * `$name` takes a property of an object case. + * + * @param template - The name template. + * @param args - The case's arguments. + * @param index - The case's index, for `%#`. + * @returns The name. + */ +function formatName(template: string, args: unknown[], index: number): string { + let next = 0; + let name = template.replace(/%[sdifjoOp#%]/g, (placeholder) => { + if (placeholder === "%%") { + return "%"; + } + if (placeholder === "%#") { + return String(index); + } + const value = args[next++]; + switch (placeholder) { + case "%s": + return typeof value === "string" ? value : format(value); + case "%d": + case "%i": + return String(placeholder === "%i" ? Math.trunc(Number(value)) : Number(value)); + case "%f": + return String(Number(value)); + case "%j": + return JSON.stringify(value); + default: + return format(value); + } + }); + const [first] = args; + if (args.length === 1 && typeof first === "object" && first !== null) { + name = name.replace(/\$([\w.]+)/g, (match, key: string) => { + const value = key + .split(".") + .reduce( + (object, step) => (object as Record | null)?.[step], + first, + ); + return value === undefined && !(key in first) + ? match + : typeof value === "string" + ? value + : format(value); + }); + } + return name; +} + +/** + * The arguments a `.each` case passes: an array case is spread, anything else is passed as is. + * + * @param item - The case. + * @returns The arguments. + */ +function eachArgs(item: unknown): unknown[] { + return Array.isArray(item) ? item : [item]; +} + +/** Registers tests, with the `.skip`/`.only`/`.todo`/`.skipIf`/`.runIf`/`.each` variants. */ +export interface TestApi { + (name: string, fn?: TestFunction, options?: number | { timeout?: number }): void; + skip(name: string, fn?: TestFunction, options?: number | { timeout?: number }): void; + only(name: string, fn?: TestFunction, options?: number | { timeout?: number }): void; + todo(name: string): void; + skipIf(condition: unknown): TestApi; + runIf(condition: unknown): TestApi; + each( + cases: readonly unknown[], + ): ( + name: string, + fn: (...args: never[]) => unknown, + options?: number | { timeout?: number }, + ) => void; +} + +/** Registers `describe` blocks, with the same variants as `test`. */ +export interface DescribeApi { + (name: string, fn: () => unknown): void; + skip(name: string, fn: () => unknown): void; + only(name: string, fn: () => unknown): void; + todo(name: string): void; + skipIf(condition: unknown): DescribeApi; + runIf(condition: unknown): DescribeApi; + each(cases: readonly unknown[]): (name: string, fn: (...args: never[]) => unknown) => void; +} + +/** + * Build `test` (or `it`) for a default mode. + * + * @param mode - The mode of tests registered through it. + * @returns The API. + */ +function createTestApi(mode: Mode): TestApi { + const add = ( + entryMode: Mode, + name: string, + fn: TestFunction | undefined, + options: unknown, + ): void => { + current.children.push({ + kind: "test", + name, + fn, + mode: fn === undefined ? "todo" : entryMode, + timeout: timeoutOf(options), + }); + }; + return Object.assign( + (name: string, fn?: TestFunction, options?: number | { timeout?: number }) => + add(mode, name, fn, options), + { + skip: (name: string, fn?: TestFunction, options?: number | { timeout?: number }) => + add("skip", name, fn, options), + only: (name: string, fn?: TestFunction, options?: number | { timeout?: number }) => + add("only", name, fn, options), + todo: (name: string) => add("todo", name, undefined, undefined), + skipIf: (condition: unknown) => createTestApi(condition ? "skip" : mode), + runIf: (condition: unknown) => createTestApi(condition ? mode : "skip"), + each: + (cases: readonly unknown[]) => + ( + name: string, + fn: (...args: never[]) => unknown, + options?: number | { timeout?: number }, + ): void => { + cases.forEach((item, index) => { + const args = eachArgs(item); + add( + mode, + formatName(name, args, index), + () => (fn as (...values: unknown[]) => unknown)(...args), + options, + ); + }); + }, + }, + ); +} + +/** + * Build `describe` for a default mode. + * + * @param mode - The mode of suites registered through it. + * @returns The API. + */ +function createDescribeApi(mode: Mode): DescribeApi { + const add = (entryMode: Mode, name: string, fn: (() => unknown) | undefined): void => { + current.children.push(createSuite(name, fn, fn === undefined ? "todo" : entryMode)); + }; + return Object.assign((name: string, fn: () => unknown) => add(mode, name, fn), { + skip: (name: string, fn: () => unknown) => add("skip", name, fn), + only: (name: string, fn: () => unknown) => add("only", name, fn), + todo: (name: string) => add("todo", name, undefined), + skipIf: (condition: unknown) => createDescribeApi(condition ? "skip" : mode), + runIf: (condition: unknown) => createDescribeApi(condition ? mode : "skip"), + each: + (cases: readonly unknown[]) => + (name: string, fn: (...args: never[]) => unknown): void => { + cases.forEach((item, index) => { + const args = eachArgs(item); + add(mode, formatName(name, args, index), () => + (fn as (...values: unknown[]) => unknown)(...args), + ); + }); + }, + }); +} + +/** vitest's `test`. */ +export const test: TestApi = createTestApi("run"); + +/** vitest's `it`. */ +export const it: TestApi = test; + +/** vitest's `describe`. */ +export const describe: DescribeApi = createDescribeApi("run"); + +/** + * vitest's `beforeAll`. + * + * @param fn - The hook; may return a cleanup function, run after the suite. + * @param timeout - Time limit in milliseconds. + */ +export function beforeAll(fn: HookFunction, timeout?: number): void { + current.beforeAll.push({ fn, timeout: timeout ?? DEFAULT_TIMEOUT }); +} + +/** + * vitest's `afterAll`. + * + * @param fn - The hook. + * @param timeout - Time limit in milliseconds. + */ +export function afterAll(fn: HookFunction, timeout?: number): void { + current.afterAll.push({ fn, timeout: timeout ?? DEFAULT_TIMEOUT }); +} + +/** + * vitest's `beforeEach`. + * + * @param fn - The hook; may return a cleanup function, run after the test. + * @param timeout - Time limit in milliseconds. + */ +export function beforeEach(fn: HookFunction, timeout?: number): void { + current.beforeEach.push({ fn, timeout: timeout ?? DEFAULT_TIMEOUT }); +} + +/** + * vitest's `afterEach`. + * + * @param fn - The hook. + * @param timeout - Time limit in milliseconds. + */ +export function afterEach(fn: HookFunction, timeout?: number): void { + current.afterEach.push({ fn, timeout: timeout ?? DEFAULT_TIMEOUT }); +} + +/** + * Serialize a thrown value. + * + * @param error - The thrown value. + * @returns Its report. + */ +function serializeError(error: unknown): ReportedError { + if (error instanceof Error) { + const extra = + error instanceof AssertionError ? { actual: error.actual, expected: error.expected } : {}; + let message = error.message; + if (error.cause !== undefined) { + message += `\ncause: ${error.cause instanceof Error ? `${error.cause.name}: ${error.cause.message}` : format(error.cause)}`; + } + return { name: error.name, message, stack: error.stack, ...extra }; + } + return { name: "Error", message: `thrown: ${format(error)}` }; +} + +/** + * Run a function with a time limit. + * + * @param fn - The function. + * @param timeout - The limit in milliseconds. + * @param label - What is running, for the error message. + * @returns What the function returned. + */ +async function withTimeout( + fn: () => T | Promise, + timeout: number, + label: string, +): Promise { + const timer = sleep(timeout); + try { + return await Promise.race([ + Promise.resolve().then(fn), + timer.done.then((): never => { + throw new Error(`${label} timed out in ${timeout}ms`); + }), + ]); + } finally { + timer.cancel(); + } +} + +/** + * Run a suite's `describe` body and those of the suites it registers. + * + * @param suite - The suite. + * @param path - Names of the enclosing suites. + * @param report - Receives collection failures. + * @returns A promise that settles once collected. + */ +async function collect( + suite: SuiteEntry, + path: string[], + report: (result: TestReport) => void, +): Promise { + for (const child of suite.children) { + if (child.kind !== "suite" || child.fn === undefined) { + continue; + } + const previous = current; + current = child; + try { + await child.fn(); + } catch (error) { + report({ + type: "hook", + path: [...path, child.name], + name: "describe", + state: "fail", + duration: 0, + error: serializeError(error), + }); + } finally { + current = previous; + } + await collect(child, [...path, child.name], report); + } +} + +/** + * Whether a suite contains a `.only` test or suite. + * + * @param suite - The suite. + * @returns Whether it does. + */ +function containsOnly(suite: SuiteEntry): boolean { + return suite.children.some( + (child) => child.mode === "only" || (child.kind === "suite" && containsOnly(child)), + ); +} + +/** Runs the collected tests. */ +class Runner { + readonly #report: (result: TestReport) => void; + /** Whether the file uses `.only`, so unmarked tests are skipped; set after collection. */ + onlyMode: boolean = false; + failed: number = 0; + + /** + * @param report - Receives each result. + */ + constructor(report: (result: TestReport) => void) { + this.#report = report; + } + + /** + * Report a result, counting failures. + * + * @param result - The result. + */ + report(result: TestReport): void { + if (result.state === "fail") { + this.failed++; + } + this.#report(result); + } + + /** + * Report every test in a suite with the same state, without running anything. + * + * @param suite - The suite. + * @param path - Its path, including its own name. + * @param state - The state. + * @param error - The error, for failures. + */ + reportAll( + suite: SuiteEntry, + path: string[], + state: "skip" | "fail", + error?: ReportedError, + ): void { + for (const child of suite.children) { + if (child.kind === "suite") { + this.reportAll(child, [...path, child.name], state, error); + } else { + this.report({ + type: "test", + path, + name: child.name, + state: child.mode === "todo" ? "todo" : state, + duration: 0, + error, + }); + } + } + } + + /** + * Whether a test or suite runs, given whether an enclosing suite is `.only`. + * + * @param entry - The test or suite. + * @param underOnly - Whether an enclosing suite is `.only`. + * @returns Whether it runs. + */ + #selected(entry: TestEntry | SuiteEntry, underOnly: boolean): boolean { + if (entry.mode === "skip" || entry.mode === "todo") { + return false; + } + if (!this.onlyMode || underOnly || entry.mode === "only") { + return true; + } + return entry.kind === "suite" && containsOnly(entry); + } + + /** + * Run a suite: its `beforeAll` hooks, its children, then its `afterAll` hooks. + * + * @param suite - The suite. + * @param path - Its path, including its own name (empty for the root). + * @param chain - The suites from the root to this one, for `beforeEach`/`afterEach`. + * @param underOnly - Whether an enclosing suite is `.only`. + * @returns A promise that settles once the suite has run. + */ + async runSuite( + suite: SuiteEntry, + path: string[], + chain: SuiteEntry[], + underOnly: boolean, + ): Promise { + const inOnly = underOnly || suite.mode === "only"; + const runnable = suite.children.filter((child) => this.#selected(child, inOnly)); + if (runnable.length === 0) { + this.reportAll(suite, path, "skip"); + return; + } + + // `beforeAll` hooks; a failure fails every test in the suite. + const cleanups: HookFunction[] = []; + for (const hook of suite.beforeAll) { + try { + const cleanup = await withTimeout(hook.fn, hook.timeout, "beforeAll hook"); + if (typeof cleanup === "function") { + cleanups.unshift(cleanup as HookFunction); + } + } catch (error) { + this.reportAll(suite, path, "fail", serializeError(error)); + await this.#afterAll(suite, path, cleanups); + return; + } + } + + for (const child of suite.children) { + const childPath = child.kind === "suite" ? [...path, child.name] : path; + if (!this.#selected(child, inOnly)) { + if (child.kind === "suite") { + this.reportAll(child, childPath, "skip"); + } else { + this.report({ + type: "test", + path, + name: child.name, + state: child.mode === "todo" ? "todo" : "skip", + duration: 0, + }); + } + } else if (child.kind === "suite") { + await this.runSuite(child, childPath, [...chain, child], inOnly); + } else { + await this.#runTest(child, path, chain); + } + } + + await this.#afterAll(suite, path, cleanups); + } + + /** + * Run `beforeAll` cleanups and `afterAll` hooks, reporting failures. + * + * @param suite - The suite. + * @param path - Its path. + * @param cleanups - Cleanups returned by `beforeAll` hooks, innermost first. + * @returns A promise that settles once they have run. + */ + async #afterAll(suite: SuiteEntry, path: string[], cleanups: HookFunction[]): Promise { + const hooks = [...cleanups.map((fn) => ({ fn, timeout: DEFAULT_TIMEOUT })), ...suite.afterAll]; + for (const hook of hooks) { + try { + await withTimeout(hook.fn, hook.timeout, "afterAll hook"); + } catch (error) { + this.report({ + type: "hook", + path, + name: "afterAll", + state: "fail", + duration: 0, + error: serializeError(error), + }); + } + } + } + + /** + * Run one test with the `beforeEach` and `afterEach` hooks of its suites. + * + * @param entry - The test. + * @param path - Its suites' names. + * @param chain - Its suites, outermost first. + * @returns A promise that settles once the test has run. + */ + async #runTest(entry: TestEntry, path: string[], chain: SuiteEntry[]): Promise { + const start = monotonicMs(); + let error: unknown = undefined; + let failed = false; + let skipped = false; + const fail = (thrown: unknown): void => { + if (thrown instanceof SkipSignal) { + skipped = true; + } else if (!failed) { + failed = true; + error = thrown; + } + }; + + // `beforeEach` from the outermost suite in, then the test, then cleanups and `afterEach` from + // the innermost suite out, which run even if the test failed. + const cleanups: HookFunction[] = []; + try { + for (const suite of chain) { + for (const hook of suite.beforeEach) { + const cleanup = await withTimeout(hook.fn, hook.timeout, "beforeEach hook"); + if (typeof cleanup === "function") { + cleanups.unshift(cleanup as HookFunction); + } + } + } + const context: TestContext = { + expect, + skip(): never { + throw new SkipSignal(); + }, + }; + const body = entry.fn; + if (body !== undefined) { + await withTimeout(() => body(context), entry.timeout, "test"); + } + } catch (thrown) { + fail(thrown); + } + const afterHooks = [ + ...cleanups.map((fn) => ({ fn, timeout: DEFAULT_TIMEOUT })), + ...[...chain].reverse().flatMap((suite) => suite.afterEach), + ]; + for (const hook of afterHooks) { + try { + await withTimeout(hook.fn, hook.timeout, "afterEach hook"); + } catch (thrown) { + fail(thrown); + } + } + + const duration = monotonicMs() - start; + if (failed) { + this.report({ + type: "test", + path, + name: entry.name, + state: "fail", + duration, + error: serializeError(error), + }); + } else { + this.report({ + type: "test", + path, + name: entry.name, + state: skipped ? "skip" : "pass", + duration, + }); + } + } +} + +/** + * Collect and run every registered test. + * + * @param report - Receives each result as soon as it is known. + * @returns The number of failures (failed tests and failed hooks). + */ +export async function runTests(report: (result: TestReport) => void): Promise { + const runner = new Runner(report); + await collect(root, [], (result) => runner.report(result)); + runner.onlyMode = containsOnly(root); + await runner.runSuite(root, [], [root], false); + return runner.failed; +} diff --git a/packages/jco-std/test/wintertc/component/peer-client.ts b/packages/jco-std/test/wintertc/component/peer-client.ts new file mode 100644 index 000000000..dad6a68a6 --- /dev/null +++ b/packages/jco-std/test/wintertc/component/peer-client.ts @@ -0,0 +1,322 @@ +/** + * In-component access to the Node peer that the driver starts (see `peer.ts`): its URLs, Node's + * `crypto.subtle` and `node:zlib`, scripted HTTP exchanges for `fetch` tests, and the component's + * own stdout and stderr. + * + * Every call goes through `fetch`, so tests that import this module test `fetch` too. + */ +import { getEnvironment } from "wasi:cli/environment@0.3.0"; + +import { atob, btoa } from "../../../src/wintertc/base64.js"; +import { console, flushOutput } from "../../../src/wintertc/console.js"; +import { fetch } from "../../../src/wintertc/fetch.js"; + +/** + * An environment variable of the component. + * + * @param name - Its name. + * @returns Its value. + * @throws `Error` when it isn't set. + */ +function env(name: string): string { + for (const [key, value] of getEnvironment()) { + if (key === name) { + return value; + } + } + throw new Error(`${name} is not set; run this test through the component driver`); +} + +/** + * The peer's base URL (no trailing slash). + * + * @param origin - `"primary"`, or `"other"` for the second port (a different origin). + * @returns The URL, such as `http://127.0.0.1:1234`. + */ +export function peerUrl(origin: "primary" | "other" = "primary"): string { + return env(origin === "other" ? "WINTERTC_PEER_OTHER" : "WINTERTC_PEER"); +} + +/** + * Base64 of some bytes. + * + * @param bytes - The bytes. + * @returns Their base64. + */ +function toBase64(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary); +} + +/** + * Bytes from base64. + * + * @param text - The base64. + * @returns The bytes. + */ +function fromBase64(text: string): Uint8Array { + const binary = atob(text); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} + +/** A Node `CryptoKey`, held by the peer. */ +export class NodeKey { + readonly id: number; + readonly type: string; + readonly extractable: boolean; + readonly algorithm: unknown; + readonly usages: string[]; + + /** + * @param id - The peer's id for the key. + * @param type - `"secret"`, `"public"` or `"private"`. + * @param extractable - Whether it can be exported. + * @param algorithm - Its algorithm. + * @param usages - Its usages. + */ + constructor( + id: number, + type: string, + extractable: boolean, + algorithm: unknown, + usages: string[], + ) { + this.id = id; + this.type = type; + this.extractable = extractable; + this.algorithm = algorithm; + this.usages = usages; + } +} + +/** + * Encode a value for the peer: bytes as `{ $b }`, Node keys as `{ $k }`. + * + * @param value - The value. + * @returns The JSON value. + */ +function encode(value: unknown): unknown { + if (value instanceof NodeKey) { + return { $k: value.id }; + } + if (value instanceof ArrayBuffer) { + return { $b: toBase64(new Uint8Array(value)) }; + } + if (ArrayBuffer.isView(value)) { + return { $b: toBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) }; + } + if (Array.isArray(value)) { + return value.map(encode); + } + if (typeof value === "object" && value !== null) { + return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, encode(item)])); + } + return value; +} + +/** + * Decode a value from the peer: `{ $b }` as an `ArrayBuffer`, `{ $k }` as a `NodeKey`. + * + * @param value - The JSON value. + * @returns The value. + */ +function decode(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(decode); + } + if (typeof value !== "object" || value === null) { + return value; + } + const record = value as Record; + if (typeof record.$b === "string") { + return fromBase64(record.$b).buffer; + } + if (typeof record.$k === "number") { + return new NodeKey( + record.$k, + String(record.type), + record.extractable === true, + record.algorithm, + record.usages as string[], + ); + } + return Object.fromEntries(Object.entries(record).map(([name, item]) => [name, decode(item)])); +} + +/** + * Call a method of Node's `crypto.subtle`. + * + * @param method - The method, such as `"sign"`. + * @param args - Its arguments; Node keys are `NodeKey`s. + * @returns Its result; `ArrayBuffer`s, `NodeKey`s, JWKs and key pairs come back as such. + */ +async function callSubtle(method: string, args: unknown[]): Promise { + const response = await fetch(`${peerUrl()}/subtle`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ method, args: encode(args) }), + }); + const reply = JSON.parse(await response.text()) as { ok?: unknown; error?: string }; + if (reply.error !== undefined) { + throw new Error(`Node's crypto.subtle.${method} failed: ${reply.error}`); + } + return decode(reply.ok); +} + +/** + * Node's `crypto.subtle`, called through the peer. Typed as the DOM's `SubtleCrypto`; its keys are + * `NodeKey`s, which only this object accepts. + */ +export const nodeSubtle: globalThis.SubtleCrypto = new Proxy( + {}, + { + get(_target, method): unknown { + return typeof method === "string" + ? (...args: unknown[]) => callSubtle(method, args) + : undefined; + }, + }, +) as globalThis.SubtleCrypto; + +/** + * Run a `node:zlib` sync function in the peer. + * + * @param fn - The function, such as `"gzipSync"`. + * @param input - Its input. + * @returns Its output. + */ +export async function nodeZlib(fn: string, input: Uint8Array): Promise { + const response = await fetch(`${peerUrl()}/zlib/${fn}`, { method: "POST", body: input }); + if (response.status !== 200) { + throw new Error(`zlib.${fn} failed: ${await response.text()}`); + } + return new Uint8Array(await response.arrayBuffer()); +} + +/** A scripted reply for an exchange with the peer. */ +export interface ScriptedReply { + status: number; + headers?: [string, string][]; + body?: string | null; + /** Never answer. */ + hang?: boolean; + /** Send the body but never end it. */ + keepOpen?: boolean; +} + +/** A request the peer recorded. */ +export interface SeenRequest { + method: string; + /** Path and query, relative to the script's base URL. */ + path: string; + /** Whether it arrived at the other origin. */ + port: number; + /** Request headers, without transport headers (`host`, `content-length`, …). */ + headers: [string, string][]; + body: string; +} + +/** Counts scripts, for unique ids. */ +let scriptCount = 0; + +/** A scripted exchange: requests under `base` are answered from `replies` and recorded. */ +export class Script { + readonly id: string; + + /** + * @param id - The script's id. + */ + constructor(id: string) { + this.id = id; + } + + /** + * The base URL of the script's exchanges. + * + * @param origin - Which of the peer's two origins. + * @returns The URL, without a trailing slash. + */ + base(origin: "primary" | "other" = "primary"): string { + return `${peerUrl(origin)}/s/${this.id}`; + } + + /** + * The requests recorded so far. + * + * @returns The requests, in order. + */ + async seen(): Promise { + const response = await fetch(`${peerUrl()}/seen/${this.id}`); + return JSON.parse(await response.text()) as SeenRequest[]; + } +} + +/** + * Start a scripted exchange with the peer. + * + * @param replies - The replies, in order, or a function that makes them from the script (for + * replies that refer to its URLs). + * @returns The script. + */ +export async function script( + replies: ScriptedReply[] | ((script: Script) => ScriptedReply[]), +): Promise