From 34b0bd5f2807f5f1fedd9f851e4ed3969c9984d8 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 25 Oct 2026 09:05:51 -0700 Subject: [PATCH 1/5] chore(quest): claim quest/m1/api-extractor-checks.md Quest-Claim: 1100d1eefed49159 From f0f4be346803625e2079aaff826b5af0b9854ce4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 25 Oct 2026 09:13:43 -0700 Subject: [PATCH 2/5] chore(js): checkpoint strict API Extractor validation Enable strict extractor diagnostics, define the shared module tag, and exercise declaration failures. External dependency resolution remains a maintainer decision; workspace migration and checker removal are incomplete. Co-Authored-By: GPT-6 --- js/common/api.test.ts | 61 ++++++++++++++++++++++++++++++++ js/common/api.ts | 35 +++++++++++------- js/common/tsdoc.json | 6 ++++ quest/m1/api-extractor-checks.md | 20 +++++++++++ sh/js/workspace.py | 2 +- 5 files changed, 110 insertions(+), 14 deletions(-) create mode 100644 js/common/api.test.ts create mode 100644 js/common/tsdoc.json diff --git a/js/common/api.test.ts b/js/common/api.test.ts new file mode 100644 index 00000000000..2d5d63a87ef --- /dev/null +++ b/js/common/api.test.ts @@ -0,0 +1,61 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { checkReports } from "./api.ts"; + +const directories: string[] = []; +const previousMode = process.env.MOQ_API_REPORT; + +afterEach(() => { + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true }); + if (previousMode === undefined) delete process.env.MOQ_API_REPORT; + else process.env.MOQ_API_REPORT = previousMode; +}); + +function fixture(body: string): string { + const directory = mkdtempSync(join(tmpdir(), "moq-api-test-")); + directories.push(directory); + mkdirSync(join(directory, "dist")); + writeFileSync( + join(directory, "dist/package.json"), + JSON.stringify({ name: "@moq/example", version: "0.0.0", exports: { ".": { types: "./index.d.ts" } } }), + ); + writeFileSync(join(directory, "dist/index.d.ts"), `/**\n * A package summary.\n * @module\n */\n${body}`); + process.env.MOQ_API_REPORT = "update"; + return directory; +} + +test("a documented public declaration produces a report with the shared module tag", () => { + const directory = fixture("/** Read a value.\n * @public\n */\nexport declare function read(): string;\n"); + checkReports(directory); + expect(readFileSync(join(directory, "api/index.api.md"), "utf8")).toContain("export function read(): string;"); +}); + +test("a public signature cannot depend on a declaration absent from its entrypoint", () => { + const directory = fixture('export { read } from "./access";\n'); + writeFileSync( + join(directory, "dist/access.d.ts"), + `/** Input to a read.\n * @public\n */ +export interface AccessInput { +/** The path to read. */ +path: string; +} +/** Read a value.\n * @public\n */ +export declare function read(input: AccessInput): string; +`, + ); + expect(() => checkReports(directory)).toThrow("API Extractor failed"); +}); + +test("a stripped declaration cannot remain in a public signature", () => { + const directory = fixture(`/** Read a value.\n * @public\n */ +export declare function read(input: AccessInput): string; +`); + expect(() => checkReports(directory)).toThrow(); +}); + +test("a public declaration needs a summary, even with a release tag", () => { + const directory = fixture("/** @public */\nexport declare function read(): string;\n"); + expect(() => checkReports(directory)).toThrow("API Extractor failed"); +}); diff --git a/js/common/api.ts b/js/common/api.ts index a871a3e1b6f..f6e409a1d0d 100644 --- a/js/common/api.ts +++ b/js/common/api.ts @@ -42,7 +42,14 @@ function reports(dist: string): Map { try { const root = join(work, "package"); cpSync(dist, root, { recursive: true }); - rewriteExternalNamespaces(root); + writeFileSync( + join(root, "tsdoc.json"), + JSON.stringify({ + $schema: "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + extends: [join(import.meta.dir, "tsdoc.json")], + }), + ); + prepareDeclarations(root); const folder = join(work, "reports"); mkdirSync(folder); @@ -61,16 +68,18 @@ function reports(dist: string): Map { } } -// API Extractor cannot follow `export * as X from ""`, which every entrypoint uses to -// re-export its dependencies, but reads the equivalent import-then-export form. -function rewriteExternalNamespaces(root: string) { +// Keep JSR's module tag and expose its summary to API Extractor. External namespace +// re-exports need the equivalent import-then-export form for API Extractor to follow them. +function prepareDeclarations(root: string) { for (const rel of new Bun.Glob("**/*.d.ts").scanSync(root)) { const file = join(root, rel); const body = readFileSync(file, "utf8"); - const next = body.replace( - /^export \* as ([A-Za-z_$][\w$]*) from "([^."][^"]*)";$/gm, - 'import * as $1 from "$2";\nexport { $1 };', - ); + const next = body + .replace(/^(\s*\* @module)\s*$/gm, "$1\n * @packageDocumentation") + .replace( + /^export \* as ([A-Za-z_$][\w$]*) from "([^."][^"]*)";$/gm, + 'import * as $1 from "$2";\nexport { $1 };', + ); if (next !== body) writeFileSync(file, next); } } @@ -89,6 +98,7 @@ function extract(root: string, entrypoint: string, folder: string, entry: string moduleResolution: "bundler", lib: ["esnext", "dom"], strict: true, + types: [], }, files: [entrypoint], }, @@ -105,12 +115,11 @@ function extract(root: string, entrypoint: string, folder: string, entry: string docModel: { enabled: false }, dtsRollup: { enabled: false }, tsdocMetadata: { enabled: false }, - // The report is the output. Its findings about doc comments and unresolved - // dependencies are left to the build's own declaration checks. + // Validate the same declarations that produce the committed report. messages: { - compilerMessageReporting: { default: { logLevel: ExtractorLogLevel.None } }, - extractorMessageReporting: { default: { logLevel: ExtractorLogLevel.None } }, - tsdocMessageReporting: { default: { logLevel: ExtractorLogLevel.None } }, + compilerMessageReporting: { default: { logLevel: ExtractorLogLevel.Error } }, + extractorMessageReporting: { default: { logLevel: ExtractorLogLevel.Error } }, + tsdocMessageReporting: { default: { logLevel: ExtractorLogLevel.Error } }, }, }, configObjectFullPath: join(root, "api-extractor.json"), diff --git a/js/common/tsdoc.json b/js/common/tsdoc.json new file mode 100644 index 00000000000..e97296ba9fd --- /dev/null +++ b/js/common/tsdoc.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "extends": ["@microsoft/api-extractor/extends/tsdoc-base.json"], + "tagDefinitions": [{ "tagName": "@module", "syntaxKind": "modifier" }], + "supportForTags": { "@module": true } +} diff --git a/quest/m1/api-extractor-checks.md b/quest/m1/api-extractor-checks.md index ae90218cd1a..05a61d0633f 100644 --- a/quest/m1/api-extractor-checks.md +++ b/quest/m1/api-extractor-checks.md @@ -33,6 +33,26 @@ Decided 2026-10-23 (maintainer interview): and dropping an export's doc comment must each fail `just check`. - Rust is a non-goal: docs.rs and cargo-semver-checks cover it. +Implementation checkpoint: strict compiler, extractor, and TSDoc messages are +wired into the shared report configuration. The JSR `@module` tag is defined +and translated to `@packageDocumentation` in the isolated declaration copy; +focused fixtures cover missing exports, stripped names, and undocumented +exports. The old checkers remain until the replacement can pass the workspace. + +Open decision: the isolated copy intentionally cannot resolve external +packages, so strict compiler diagnostics reject every bare dependency import +with TS2307. Choose whether to preserve isolation with narrowly scoped external +module diagnostics, or resolve declared dependency types without relying on +sibling packages having been built. The former keeps today's independent +reports and is the smaller change, but makes the unresolved-declaration check +explicitly local to the package. No diagnostic exception is implemented yet. + +Remaining after that decision: migrate existing release tags and TSDoc syntax, +replace private-helper `typeof` references in public static method bags with +explicit signatures, fix any other exposed public declarations without +expanding exports unnecessarily, remove `docs.ts` and `declarations.ts` with +their superseded tests, and pass `just check` and `just ci`. + ## Related - [Generated JS API reference](/quest/m1/js-api-reference.md) - renders the doc model from the same config diff --git a/sh/js/workspace.py b/sh/js/workspace.py index 1c04f45acfa..cb0e29ff011 100644 --- a/sh/js/workspace.py +++ b/sh/js/workspace.py @@ -144,7 +144,7 @@ def scripts(verb): command("bun", "install", "--frozen-lockfile") if action == "test": command("python3", "sh/js/playwright.test.py") - command("bun", "test", "js/common/declarations.test.ts", "js/common/deps.test.ts", + command("bun", "test", "js/common/api.test.ts", "js/common/declarations.test.ts", "js/common/deps.test.ts", "js/common/docs.test.ts", "js/common/worklet.test.ts", "js/common/release.test.ts") scripts("test") return From bba142fdf70fa2a11d3399fb29c8a8e222cfcadc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 25 Oct 2026 16:21:46 -0700 Subject: [PATCH 3/5] chore(js): check declarations against declared dependencies with API Extractor Link each package's declared dependencies into the isolated dist copy so API Extractor resolves their types, with workspace siblings resolving to source. Accept a forgotten export only when another entrypoint or a rename makes it nameable, migrate the findings, and delete the hand-rolled declarations and docs checkers. Record the maintainer's decision in the quest Plan. Co-Authored-By: Claude Opus 5.5 --- js/auth/api/index.api.md | 1 - js/auth/src/claims.ts | 2 +- js/auth/src/set.ts | 2 +- js/clock/api/index.api.md | 1 - js/common/api.test.ts | 97 +++-- js/common/api.ts | 279 +++++++++++++-- js/common/declarations.test.ts | 114 ------ js/common/declarations.ts | 256 -------------- js/common/docs.test.ts | 361 ------------------- js/common/docs.ts | 449 ------------------------ js/common/package.ts | 39 +- js/flate/api/index.api.md | 3 +- js/flate/src/snapshot/consumer.ts | 1 + js/flate/src/snapshot/producer.ts | 2 + js/flate/src/stream/consumer.ts | 1 + js/flate/src/stream/producer.ts | 2 + js/hang/api/catalog.api.md | 1 - js/hang/api/cmaf.api.md | 1 - js/hang/api/container.api.md | 2 +- js/hang/api/index.api.md | 137 +------- js/hang/api/util.api.md | 7 +- js/hang/src/container/types.ts | 12 +- js/hang/src/timeline.ts | 5 + js/json/api/index.api.md | 17 +- js/json/src/snapshot/consumer.ts | 1 + js/json/src/snapshot/encoder.ts | 34 +- js/json/src/snapshot/producer.ts | 1 + js/json/src/stream/consumer.ts | 1 + js/json/src/stream/producer.ts | 1 + js/json/src/window/consumer.ts | 4 +- js/json/src/window/decoder.ts | 4 +- js/json/src/window/index.ts | 2 +- js/libav/api/index.api.md | 1 - js/loc/api/index.api.md | 1 - js/moq-boy/api/element.api.md | 7 +- js/moq-boy/api/index.api.md | 7 +- js/moq-boy/src/element.tsx | 14 +- js/msf/api/index.api.md | 1 - js/net/api/index.api.md | 488 ++++---------------------- js/net/api/zod.api.md | 21 +- js/net/src/announce.ts | 2 +- js/net/src/broadcast.ts | 6 +- js/net/src/connection/accept.ts | 3 +- js/net/src/connection/connect.ts | 3 +- js/net/src/connection/established.ts | 2 +- js/net/src/connection/pool.ts | 5 +- js/net/src/hop.ts | 2 +- js/net/src/origin.ts | 11 +- js/pattern/api/index.api.md | 1 - js/pattern/src/index.ts | 1 + js/publish/api/element.api.md | 17 +- js/publish/api/index.api.md | 101 ++---- js/publish/api/support-element.api.md | 1 - js/publish/api/support.api.md | 1 - js/publish/api/ui.api.md | 1 - js/publish/src/audio/capture.ts | 3 +- js/publish/src/audio/encoder.ts | 3 +- js/publish/src/audio/index.ts | 1 + js/publish/src/audio/types.ts | 17 +- js/publish/src/element.ts | 10 +- js/publish/src/index.ts | 1 + js/publish/src/preview.ts | 3 +- js/publish/src/source/camera.ts | 3 +- js/publish/src/source/device.ts | 3 +- js/publish/src/source/file.ts | 3 +- js/publish/src/source/microphone.ts | 3 +- js/publish/src/source/screen.ts | 3 +- js/publish/src/support/element.ts | 1 + js/publish/src/ui/element.ts | 2 + js/publish/src/video/capture.ts | 3 +- js/publish/src/video/encoder.ts | 41 ++- js/publish/src/video/types.ts | 11 + js/qmux/api/index.api.md | 12 +- js/qmux/src/index.ts | 19 +- js/qmux/src/session.ts | 17 +- js/qmux/src/web-socket-stream.ts | 23 ++ js/room/api/index.api.md | 8 +- js/room/src/index.ts | 3 + js/room/src/metadata.ts | 7 +- js/signals/api/dom.api.md | 9 +- js/signals/api/index.api.md | 11 +- js/signals/api/react.api.md | 1 - js/signals/api/solid.api.md | 1 - js/signals/src/dom.ts | 3 +- js/signals/src/index.ts | 49 ++- js/ui/api/index.api.md | 7 +- js/ui/src/support.ts | 10 +- js/video/api/index.api.md | 1 - js/watch/api/element.api.md | 27 +- js/watch/api/index.api.md | 93 ++--- js/watch/api/support-element.api.md | 1 - js/watch/api/support.api.md | 1 - js/watch/api/ui.api.md | 1 - js/watch/src/audio/decoder.ts | 4 +- js/watch/src/audio/emitter.ts | 3 +- js/watch/src/audio/source.ts | 3 +- js/watch/src/broadcast.ts | 26 +- js/watch/src/element.ts | 10 +- js/watch/src/player.ts | 16 +- js/watch/src/support/element.ts | 1 + js/watch/src/sync.ts | 3 +- js/watch/src/text/source.ts | 3 +- js/watch/src/ui/element.ts | 2 + js/watch/src/video/decoder.ts | 4 +- js/watch/src/video/source.ts | 3 +- quest/m1/api-extractor-checks.md | 39 +- quest/m2/audit-docs.md | 9 +- sh/js/workspace.py | 4 +- 108 files changed, 881 insertions(+), 2201 deletions(-) delete mode 100644 js/common/declarations.test.ts delete mode 100644 js/common/declarations.ts delete mode 100644 js/common/docs.test.ts delete mode 100644 js/common/docs.ts diff --git a/js/auth/api/index.api.md b/js/auth/api/index.api.md index f969aecddff..c72698dcff5 100644 --- a/js/auth/api/index.api.md +++ b/js/auth/api/index.api.md @@ -791,5 +791,4 @@ function verify(key: PublicKey | SymmetricKey, token: string): Promise; function verify_2(set: KeySet, token: string): Promise; - ``` diff --git a/js/auth/src/claims.ts b/js/auth/src/claims.ts index 29528bf5df7..d18d5dc8cbb 100644 --- a/js/auth/src/claims.ts +++ b/js/auth/src/claims.ts @@ -143,7 +143,7 @@ export interface Permissions { * * - `path` extends the root (root `demo`, path `demo/room`), so the extra `room` * narrows each pattern and drops the ones outside it. - * - `path` is a parent of the root (root `demo`, path ``), so `demo` is prepended to + * - `path` is a parent of the root (root `demo`, empty path), so `demo` is prepended to * each pattern to keep it anchored where the token points. * * Matching is segment-aware, so a root of `foo` does not cover `foobar`. Slashes at diff --git a/js/auth/src/set.ts b/js/auth/src/set.ts index e15d23c9665..7472f135dc5 100644 --- a/js/auth/src/set.ts +++ b/js/auth/src/set.ts @@ -15,7 +15,7 @@ import { Key, KeySchema, type PublicKey } from "./key.ts"; /** * A JWK Set. * - * See . + * See {@link https://datatracker.ietf.org/doc/html/rfc7517#section-5 | RFC 7517, section 5}. */ export const KeySetSchema = z.object({ /** The keys in the set, in preference order. */ diff --git a/js/clock/api/index.api.md b/js/clock/api/index.api.md index 544569a94b2..473fd991e2f 100644 --- a/js/clock/api/index.api.md +++ b/js/clock/api/index.api.md @@ -139,5 +139,4 @@ export const Wall: ((unixMillis: number) => Wall) & { export function wall(): Wall; - ``` diff --git a/js/common/api.test.ts b/js/common/api.test.ts index 2d5d63a87ef..7a0c00f1f0f 100644 --- a/js/common/api.test.ts +++ b/js/common/api.test.ts @@ -1,7 +1,7 @@ import { afterEach, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { checkReports } from "./api.ts"; const directories: string[] = []; @@ -13,49 +13,92 @@ afterEach(() => { else process.env.MOQ_API_REPORT = previousMode; }); -function fixture(body: string): string { +const summary = "/**\n * A package summary.\n * @module\n */\n"; + +function fixture(files: Record, manifest: Record = {}): string { const directory = mkdtempSync(join(tmpdir(), "moq-api-test-")); directories.push(directory); - mkdirSync(join(directory, "dist")); - writeFileSync( - join(directory, "dist/package.json"), - JSON.stringify({ name: "@moq/example", version: "0.0.0", exports: { ".": { types: "./index.d.ts" } } }), - ); - writeFileSync(join(directory, "dist/index.d.ts"), `/**\n * A package summary.\n * @module\n */\n${body}`); + const all: Record = { + "dist/package.json": JSON.stringify({ + name: "@moq/example", + version: "0.0.0", + exports: { ".": { types: "./index.d.ts" } }, + ...manifest, + }), + ...files, + }; + for (const [path, body] of Object.entries(all)) { + mkdirSync(dirname(join(directory, path)), { recursive: true }); + writeFileSync(join(directory, path), body); + } process.env.MOQ_API_REPORT = "update"; return directory; } -test("a documented public declaration produces a report with the shared module tag", () => { - const directory = fixture("/** Read a value.\n * @public\n */\nexport declare function read(): string;\n"); +test("a documented declaration produces a report", () => { + const directory = fixture({ + "dist/index.d.ts": `${summary}/** Read a value. */\nexport declare function read(): string;\n`, + }); checkReports(directory); expect(readFileSync(join(directory, "api/index.api.md"), "utf8")).toContain("export function read(): string;"); }); -test("a public signature cannot depend on a declaration absent from its entrypoint", () => { - const directory = fixture('export { read } from "./access";\n'); - writeFileSync( - join(directory, "dist/access.d.ts"), - `/** Input to a read.\n * @public\n */ +test("a declaration needs a summary", () => { + // The module summary would document a declaration directly after it. + const directory = fixture({ + "dist/index.d.ts": `${summary}/** Write a value. */\nexport declare function write(): void;\nexport declare function read(): string;\n`, + }); + expect(() => checkReports(directory)).toThrow("API Extractor failed"); +}); + +test("a signature cannot depend on a declaration no entrypoint exports", () => { + const directory = fixture({ + "dist/index.d.ts": `${summary}export { read } from "./access";\n`, + "dist/access.d.ts": `/** Input to a read. */ export interface AccessInput { -/** The path to read. */ -path: string; + /** The path to read. */ + path: string; } -/** Read a value.\n * @public\n */ +/** Read a value. */ export declare function read(input: AccessInput): string; `, - ); + }); expect(() => checkReports(directory)).toThrow("API Extractor failed"); }); -test("a stripped declaration cannot remain in a public signature", () => { - const directory = fixture(`/** Read a value.\n * @public\n */ -export declare function read(input: AccessInput): string; -`); - expect(() => checkReports(directory)).toThrow(); +test("a signature may use a declaration another entrypoint exports, or one it renames", () => { + const directory = fixture( + { + "dist/index.d.ts": `${summary}export { type AccessInput } from "./access";\n`, + "dist/access.d.ts": `/** Input to a read. */ +export interface AccessInput { + /** The path to read. */ + path: string; +} +/** Parse an input. */ +declare function parse(text: string): AccessInput; +/** Reads values. */ +export declare class Reader { + /** Read a value. */ + read(input: AccessInput): string; + /** Parse an input. */ + static parse: typeof parse; +} +`, + "dist/reader.d.ts": `${summary}export { Reader } from "./access";\n`, + }, + { exports: { ".": { types: "./index.d.ts" }, "./reader": { types: "./reader.d.ts" } } }, + ); + checkReports(directory); + expect(readFileSync(join(directory, "api/reader.api.md"), "utf8")).toContain("static parse: typeof parse;"); }); -test("a public declaration needs a summary, even with a release tag", () => { - const directory = fixture("/** @public */\nexport declare function read(): string;\n"); - expect(() => checkReports(directory)).toThrow("API Extractor failed"); +test("a declaration resolves types from declared dependencies only", () => { + const files = { + "node_modules/dep/package.json": JSON.stringify({ name: "dep", version: "0.0.0", types: "./index.d.ts" }), + "node_modules/dep/index.d.ts": "export interface Value {\n\tvalue: string;\n}\n", + "dist/index.d.ts": `${summary}import type { Value } from "dep";\n/** Read a value. */\nexport declare function read(): Value;\n`, + }; + checkReports(fixture(files, { dependencies: { dep: "^0.0.0" } })); + expect(() => checkReports(fixture(files))).toThrow("API Extractor failed"); }); diff --git a/js/common/api.ts b/js/common/api.ts index f6e409a1d0d..90b9edab4ce 100644 --- a/js/common/api.ts +++ b/js/common/api.ts @@ -1,13 +1,26 @@ // The API Extractor setup every `@moq/*` package shares: one report per `exports` entrypoint, -// committed beside the package and diffed by the release gate. +// committed beside the package and diffed by the release gate, with every message an error. // -// The built `dist/` is analyzed in a copy outside the repository, where no `node_modules` -// resolves its imports, so a package's report never depends on whether its dependencies are built. +// The built `dist/` is analyzed in a copy outside the repository whose `node_modules` holds only +// the dependencies its manifest declares, as a consumer's install would. A workspace dependency +// resolves to its source, so a package's report never depends on whether its dependencies are built. -import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { Extractor, ExtractorConfig, ExtractorLogLevel } from "@microsoft/api-extractor"; +import { dirname, join, relative, resolve } from "node:path"; +import { CompilerState, Extractor, ExtractorConfig, ExtractorLogLevel } from "@microsoft/api-extractor"; /** * Compare the built package in `dir` with its committed reports in `api/`, exiting on a @@ -15,7 +28,7 @@ import { Extractor, ExtractorConfig, ExtractorLogLevel } from "@microsoft/api-ex */ export function checkReports(dir: string) { const folder = join(dir, "api"); - const current = reports(join(dir, "dist")); + const current = reports(resolve(dir)); const committed = existsSync(folder) ? readdirSync(folder).filter((file) => file.endsWith(".api.md")) : []; const stale = [...new Set([...current.keys(), ...committed])].filter((file) => { const path = join(folder, file); @@ -36,12 +49,12 @@ export function checkReports(dir: string) { } } -/** Every entrypoint's API report for the built package in `dist`, by file name such as `index.api.md`. */ -function reports(dist: string): Map { +/** Every entrypoint's API report for the package built in `dir`, by file name such as `index.api.md`. */ +function reports(dir: string): Map { const work = mkdtempSync(join(tmpdir(), "moq-api-")); try { const root = join(work, "package"); - cpSync(dist, root, { recursive: true }); + cpSync(join(dir, "dist"), root, { recursive: true }); writeFileSync( join(root, "tsdoc.json"), JSON.stringify({ @@ -50,17 +63,34 @@ function reports(dist: string): Map { }), ); prepareDeclarations(root); + + const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); + linkDependencies(dir, root, manifest); + const folder = join(work, "reports"); mkdirSync(folder); - const found = new Map(); - const exports: Record = - JSON.parse(readFileSync(join(root, "package.json"), "utf8")).exports ?? {}; - for (const [subpath, target] of Object.entries(exports)) { - const types = (target as { types?: string }).types; - if (!types) continue; + const entries = Object.entries<{ types?: string }>(manifest.exports ?? {}).flatMap(([subpath, target]) => { + if (!target.types) return []; const entry = subpath === "." ? "index" : subpath.replace(/^\.\//, "").replaceAll("/", "-"); - found.set(`${entry}.api.md`, extract(root, join(root, types), folder, entry)); + const entrypoint = join(root, target.types); + return [{ entry, entrypoint, config: configure(root, entrypoint, folder, entry) }]; + }); + const [first] = entries; + if (!first) return new Map(); + + // One program serves every entrypoint, so the dependencies are type-checked once. + const compilerState = CompilerState.create(first.config, { + additionalEntryPoints: entries.map(({ entrypoint }) => entrypoint), + }); + const named = nameable( + compilerState.program, + entries.map(({ entrypoint }) => entrypoint), + ); + + const found = new Map(); + for (const { entry, config } of entries) { + found.set(`${entry}.api.md`, extract(root, config, compilerState, named, folder, entry)); } return found; } finally { @@ -68,8 +98,173 @@ function reports(dist: string): Map { } } -// Keep JSR's module tag and expose its summary to API Extractor. External namespace -// re-exports need the equivalent import-then-export form for API Extractor to follow them. +// Install each declared dependency where the copy resolves it, linked to the workspace's own +// install. Anything undeclared stays unresolvable, as it is for a consumer. +function linkDependencies(dir: string, root: string, manifest: Record | undefined>) { + const names = new Set( + ["dependencies", "peerDependencies", "optionalDependencies"].flatMap((field) => + Object.keys(manifest[field] ?? {}), + ), + ); + for (const name of names) { + const installed = installation(dir, name); + if (!installed) throw new Error(`${name} is declared but not installed`); + const link = join(root, "node_modules", name); + mkdirSync(dirname(link), { recursive: true }); + symlinkSync(realpathSync(installed), link, "dir"); + } +} + +// Where Node resolves the package `name` from `dir`. +function installation(dir: string, name: string): string | undefined { + for (let at = dir; ; at = dirname(at)) { + const candidate = join(at, "node_modules", name); + if (existsSync(candidate)) return candidate; + if (dirname(at) === at) return undefined; + } +} + +type Program = CompilerState["program"]; +type Checker = ReturnType; +type Node = Parameters[0]; +type Symbol = NonNullable>; + +// The TypeScript that API Extractor bundles and built the program with. +const ts: { + SymbolFlags: { Alias: number; Namespace: number }; + SyntaxKind: Record< + | "Identifier" + | "SourceFile" + | "TypeAliasDeclaration" + | "PropertySignature" + | "PropertyDeclaration" + | "VariableDeclaration" + | "TypeReference" + | "TypeQuery", + number + >; +} = createRequire(import.meta.resolve("@microsoft/api-extractor"))("typescript"); + +// What a name resolves to, through any imports. +function target(checker: Checker, symbol: Symbol): Symbol { + return symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol; +} + +// The declaration a declaration only renames: a type alias of a type (`type A = B`), or a property +// or variable holding a value (`static parse: typeof parse`), which is then reachable by the new name. +function renamed(checker: Checker, node: Node): Symbol | undefined { + const { type } = node as Node & { type?: Node }; + if (!type) return undefined; + const { typeArguments, typeName, exprName } = type as Node & { + typeArguments?: unknown; + typeName?: Node; + exprName?: Node; + }; + let name: Node | undefined; + if (node.kind === ts.SyntaxKind.TypeAliasDeclaration && type.kind === ts.SyntaxKind.TypeReference) { + name = typeName; + } else if ( + [ + ts.SyntaxKind.PropertySignature, + ts.SyntaxKind.PropertyDeclaration, + ts.SyntaxKind.VariableDeclaration, + ].includes(node.kind) && + type.kind === ts.SyntaxKind.TypeQuery + ) { + name = exprName; + } + const symbol = name && !typeArguments ? checker.getSymbolAtLocation(name) : undefined; + return symbol && target(checker, symbol); +} + +/** + * Every declaration a consumer can name from one of `entrypoints`: an export, a namespace member, + * or a declaration one of those renames, such as a class's `static parse: typeof parse`. + */ +function nameable(program: Program, entrypoints: string[]): Set { + const checker = program.getTypeChecker(); + const found = new Set(); + const add = (symbol: Symbol) => { + if (found.has(symbol)) return; + found.add(symbol); + if (symbol.flags & ts.SymbolFlags.Namespace) { + for (const exported of checker.getExportsOfModule(symbol)) add(target(checker, exported)); + } + const visit = (node: Node) => { + const symbol = renamed(checker, node); + if (symbol) add(symbol); + node.getChildren().forEach(visit); + }; + for (const declaration of symbol.declarations ?? []) { + // A module's declaration is its file, whose exports are added above. + if (declaration.kind !== ts.SyntaxKind.SourceFile) visit(declaration); + } + }; + + for (const entrypoint of entrypoints) { + const file = program.getSourceFile(entrypoint); + const module = file && checker.getSymbolAtLocation(file); + if (!module) throw new Error(`${entrypoint} is not a module`); + add(module); + } + return found; +} + +/** + * Whether everything in this package named `name` that the declaration starting at `line` and + * `column` of `path` references is in `named`. API Extractor locates a forgotten export at the declaration that + * references it, and names it as emitted, with a suffix such as `_2` when the name is taken, so + * every candidate must be nameable. + */ +function nameableReference( + program: Program, + root: string, + named: Set, + path: string, + line: number, + column: number, + name: string, +): boolean { + const file = program.getSourceFile(path); + if (!file) return false; + const start = file.getPositionOfLineAndCharacter(line - 1, column - 1); + const checker = program.getTypeChecker(); + const base = name.replace(/_\d+$/, ""); + + // The outermost node starting there is the declaration. + let declaration: Node | undefined; + for (let node: Node = file; !declaration; ) { + const child: Node | undefined = node + .getChildren() + .find((child) => child.getStart() <= start && start < child.end); + if (!child) return false; + if (child.getStart() === start) declaration = child; + node = child; + } + + // A declaration is named for itself, or an imported module for its local name, and an import + // may rename either. + const candidates = new Set(); + const visit = (node: Node) => { + // A member's own name is a declaration, not a reference. + if (node.kind === ts.SyntaxKind.Identifier && (node.parent as Node & { name?: Node }).name !== node) { + const symbol = checker.getSymbolAtLocation(node); + const resolved = symbol && target(checker, symbol); + // API Extractor never asks to export another package's declaration. + const local = resolved?.declarations?.some( + (d) => !relative(root, d.getSourceFile().fileName).startsWith(".."), + ); + if (resolved && local && (resolved.name === base || node.getText() === base)) candidates.add(resolved); + } + node.getChildren().forEach(visit); + }; + visit(declaration); + return candidates.size > 0 && [...candidates].every((symbol) => named.has(symbol)); +} + +// Keep JSR's module tag and expose its summary to API Extractor. A namespace re-export becomes +// the equivalent import-then-export: API Extractor cannot follow one from another package, and +// makes each one within the package a new namespace, distinct from the one its own files import. function prepareDeclarations(root: string) { for (const rel of new Bun.Glob("**/*.d.ts").scanSync(root)) { const file = join(root, rel); @@ -77,15 +272,15 @@ function prepareDeclarations(root: string) { const next = body .replace(/^(\s*\* @module)\s*$/gm, "$1\n * @packageDocumentation") .replace( - /^export \* as ([A-Za-z_$][\w$]*) from "([^."][^"]*)";$/gm, + /^export \* as ([A-Za-z_$][\w$]*) from "([^"]+)";$/gm, 'import * as $1 from "$2";\nexport { $1 };', ); if (next !== body) writeFileSync(file, next); } } -function extract(root: string, entrypoint: string, folder: string, entry: string): string { - const config = ExtractorConfig.prepare({ +function configure(root: string, entrypoint: string, folder: string, entry: string): ExtractorConfig { + return ExtractorConfig.prepare({ configObject: { projectFolder: root, newlineKind: "lf", @@ -115,22 +310,58 @@ function extract(root: string, entrypoint: string, folder: string, entry: string docModel: { enabled: false }, dtsRollup: { enabled: false }, tsdocMetadata: { enabled: false }, - // Validate the same declarations that produce the committed report. messages: { compilerMessageReporting: { default: { logLevel: ExtractorLogLevel.Error } }, - extractorMessageReporting: { default: { logLevel: ExtractorLogLevel.Error } }, + extractorMessageReporting: { + default: { logLevel: ExtractorLogLevel.Error }, + // `@internal` and `stripInternal` are the only visibility tier, so every + // declaration left is public without a tag. + "ae-missing-release-tag": { logLevel: ExtractorLogLevel.None }, + // JSR renders the docs and resolves a link in the comment's own scope, such as a + // sibling member; API Extractor resolves one only from the entrypoint's exports. + "ae-unresolved-link": { logLevel: ExtractorLogLevel.None }, + }, tsdocMessageReporting: { default: { logLevel: ExtractorLogLevel.Error } }, }, }, configObjectFullPath: join(root, "api-extractor.json"), packageJsonFullPath: join(root, "package.json"), }); +} +function extract( + root: string, + config: ExtractorConfig, + compilerState: CompilerState, + named: Set, + folder: string, + entry: string, +): string { // localBuild writes the report into the scratch folder instead of failing because it is new, // and the console chatter about that is suppressed; errors still fail the result. const result = Extractor.invoke(config, { localBuild: true, + compilerState, messageCallback: (message) => { + const path = message.sourceFilePath; + // A dependency's own declarations are checked by its own build; compiled here only for + // their types, they answer to this package's compiler options, not their own. + if (path && relative(root, path).startsWith("..")) message.logLevel = ExtractorLogLevel.None; + // API Extractor wants each declaration a signature uses exported from this entrypoint, + // but a consumer only needs to name it: from another entrypoint, such as a subpath's + // from the package root, or through a rename, such as `Connection.Props`. + const name = message.text.match(/^The symbol "(.+)" needs to be exported/)?.[1]; + const { sourceFileLine: line, sourceFileColumn: column } = message; + if ( + message.messageId === "ae-forgotten-export" && + path && + name && + line && + column && + nameableReference(compilerState.program, root, named, path, line, column, name) + ) { + message.logLevel = ExtractorLogLevel.None; + } if (message.logLevel !== ExtractorLogLevel.Error) message.handled = true; }, }); diff --git a/js/common/declarations.test.ts b/js/common/declarations.test.ts deleted file mode 100644 index 25129af1e5e..00000000000 --- a/js/common/declarations.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { expect, test } from "bun:test"; -import { problems } from "./declarations"; - -const root = "/dist"; - -test("an import of a stripped export is reported", () => { - const files = new Map([ - ["/dist/reload.d.ts", "export declare class Reload {}\n"], - ["/dist/index.d.ts", 'import { ReloadDelay } from "./reload.js";\nexport declare const delay: ReloadDelay;\n'], - ]); - expect(problems(root, files)).toEqual([ - "index.d.ts: imports ReloadDelay from ./reload.js, which does not export it", - ]); -}); - -test("an import of a file with no declarations is reported", () => { - const files = new Map([["/dist/index.d.ts", 'import type { Mock } from "./mock.ts";\n']]); - expect(problems(root, files)).toEqual(["index.d.ts: imports ./mock.ts, which emitted no declarations"]); -}); - -test("names re-exported through a star, an alias, a default, or a directory index resolve", () => { - const files = new Map([ - ["/dist/inner.d.ts", "export interface Delay {}\ndeclare const status = 1;\nexport { status as Status };\n"], - ["/dist/outer/index.d.ts", 'export * from "../inner.js";\n'], - ["/dist/element.d.ts", "export default class Element {}\n"], - ["/dist/page.d.ts", 'import { Delay } from "./outer";\nimport { Status } from ".";\n'], - [ - "/dist/index.d.ts", - 'export * from "./outer";\nexport type { default as Element } from "./element.tsx";\nimport { type Delay, Status as S } from "./outer/index.ts";\nimport { Other } from "@moq/other";\nimport icon from "./icon.svg?raw";\n', - ], - ]); - expect(problems(root, files)).toEqual([]); -}); - -test("a default import of a module without a default export is reported", () => { - const files = new Map([ - ["/dist/element.d.ts", "export declare class Element {}\n"], - ["/dist/index.d.ts", 'import type Element from "./element.js";\nexport { Element };\n'], - ]); - expect(problems(root, files)).toEqual(["index.d.ts: imports default from ./element.js, which does not export it"]); -}); - -test("type-only star re-exports, const enums, and let declarations resolve", () => { - const files = new Map([ - ["/dist/types.d.ts", "export declare const enum State { Open }\nexport declare let value: number;\n"], - ["/dist/outer.d.ts", 'export type * from "./types.js";\n'], - ["/dist/index.d.ts", 'import type { State, value } from "./outer.js";\n'], - ]); - expect(problems(root, files)).toEqual([]); -}); - -test("an extensionless import resolves to the file before a directory index", () => { - const files = new Map([ - ["/dist/foo.d.ts", "export declare const value: number;\n"], - ["/dist/foo/index.d.ts", "export declare const other: number;\n"], - ["/dist/index.d.ts", 'import { value } from "./foo";\n'], - ]); - expect(problems(root, files)).toEqual([]); -}); - -test("a trailing slash resolves to the directory index over a file", () => { - const files = new Map([ - ["/dist/foo.d.ts", "export declare const value: number;\n"], - ["/dist/foo/index.d.ts", "export declare const other: number;\n"], - ["/dist/index.d.ts", 'import { other } from "./foo/";\n'], - ]); - expect(problems(root, files)).toEqual([]); -}); - -test("a name its source declares but the declarations strip is reported", () => { - const source = { - path: "/src/access.ts", - text: [ - 'import { Patterns } from "@moq/pattern";', - "/** @internal */ type Input = string | Patterns;", - "/** @internal */ const defaults = {};", - "/** @internal */ class Base {}", - "export const Schema = transform();", - "export class Access extends Base { static defaults: typeof defaults; }", - ].join("\n"), - }; - const files = new Map([ - [ - "/dist/access.d.ts", - 'import { Patterns } from "@moq/pattern";\nexport declare const Schema: Transform;\nexport declare class Access extends Base {\n static defaults: typeof defaults.value;\n}\n', - ], - ]); - expect(problems(root, files, new Map([["/dist/access.d.ts", source]]))).toEqual([ - "access.d.ts: references Input, which its declarations do not declare", - "access.d.ts: references Base, which its declarations do not declare", - "access.d.ts: references defaults, which its declarations do not declare", - ]); -}); - -test("globals, type parameters, and names the declarations keep resolve", () => { - const source = { - path: "/src/element.tsx", - text: [ - 'import type { Track } from "./track.ts";', - "type Key = string;", - "function Render(props: { value: T }) { return
{String(props.value)}
; }", - "export type Map = { [P in Key]: K extends Promise ? U : Track };", - "export { Render };", - ].join("\n"), - }; - const files = new Map([ - [ - "/dist/element.d.ts", - 'import type { Track } from "./track.ts";\ntype Key = string;\ndeclare function Render(props: { value: T }): HTMLElement;\nexport type Map = { [P in Key]: K extends Promise ? U : Track };\nexport { Render };\n', - ], - ["/dist/track.d.ts", "export interface Track {}\n"], - ]); - expect(problems(root, files, new Map([["/dist/element.d.ts", source]]))).toEqual([]); -}); diff --git a/js/common/declarations.ts b/js/common/declarations.ts deleted file mode 100644 index f361dc4bf17..00000000000 --- a/js/common/declarations.ts +++ /dev/null @@ -1,256 +0,0 @@ -// Checks a package's emitted `.d.ts` files for names that no longer resolve. -// -// `stripInternal` drops an `@internal` declaration but leaves every reference to it: an import in -// another file, which then names an export its target lacks, or a type in the same file, which -// then names nothing. A published consumer sees a broken type either way. Only declaration emit -// shows this, which is why it runs over `dist/` after the build rather than as a test that would -// have to run the compiler again. - -import { dirname, extname, join, relative, resolve } from "node:path"; -import { type ParserPlugin, parse } from "@babel/parser"; - -type Statement = ReturnType["program"]["body"][number]; -type Declaration = Extract["declaration"]; -type DefaultDeclaration = Extract["declaration"]; - -type FileExports = { - names: Set; - stars: string[]; - imports: Array<{ specifier: string; names: string[] }>; - // Every module-scope name, exported or not, including imports. - bound: Set; - // Every name the file looks up at module scope. - referenced: Set; -}; - -/** The TypeScript a declaration file was emitted from. */ -export type Source = { path: string; text: string }; - -/** - * Every import in `files` (path to `.d.ts` source) that its relative target does not export, and - * every name a file references without declaring that its source in `sources` (keyed like `files`) - * declares at module scope. - * - * A name its source does not declare either is a global, so only the source can tell a stripped - * declaration from one the declarations rightly leave to the environment. - */ -export function problems(root: string, files: Map, sources = new Map()): string[] { - const parsed = new Map(); - for (const [file, source] of files) { - parsed.set(file, fileExports(source)); - } - - const found: string[] = []; - for (const [file, info] of parsed) { - const source = sources.get(file); - if (source) { - const plugins: ParserPlugin[] = extname(source.path) === ".tsx" ? ["typescript", "jsx"] : ["typescript"]; - const declaredBySource = bindings(parse(source.text, { sourceType: "module", plugins }).program.body); - for (const name of info.referenced) { - if (declaredBySource.has(name) && !info.bound.has(name)) { - found.push(`${relative(root, file)}: references ${name}, which its declarations do not declare`); - } - } - } - - for (const { specifier, names } of info.imports) { - const target = dtsPath(parsed, file, specifier); - if (!target) continue; - - if (!parsed.has(target)) { - found.push(`${relative(root, file)}: imports ${specifier}, which emitted no declarations`); - continue; - } - - for (const name of names) { - if (!exported(parsed, target, name)) { - found.push(`${relative(root, file)}: imports ${name} from ${specifier}, which does not export it`); - } - } - } - } - return found; -} - -/** - * The declaration file a relative specifier resolves to: the file itself, else a directory index. - * - * Undefined for a package specifier, which resolves outside the package, and for an asset - * (`./icon.svg?raw`), which the bundler types. - */ -export function dtsPath(files: Map, from: string, specifier: string): string | undefined { - if (!specifier.startsWith(".")) return undefined; - const ext = extname(specifier); - if (ext && !/^\.(js|jsx|ts|tsx)$/.test(ext)) return undefined; - const base = resolve(dirname(from), specifier).replace(/\.(js|jsx|ts|tsx)$/, ""); - const file = `${base}.d.ts`; - const index = join(base, "index.d.ts"); - // A trailing slash names the directory, so only its index can match. - if (specifier.endsWith("/")) return index; - return files.has(file) || !files.has(index) ? file : index; -} - -function exported(files: Map, file: string, name: string, seen = new Set()): boolean { - if (seen.has(file)) return false; - seen.add(file); - - const info = files.get(file); - if (!info) return false; - if (info.names.has(name)) return true; - - for (const specifier of info.stars) { - const target = dtsPath(files, file, specifier); - if (target && exported(files, target, name, seen)) return true; - } - return false; -} - -function fileExports(source: string): FileExports { - const names = new Set(); - const stars: string[] = []; - const imports: Array<{ specifier: string; names: string[] }> = []; - - const ast = parse(source, { sourceType: "module", plugins: [["typescript", { dts: true }]] }); - for (const statement of ast.program.body) { - switch (statement.type) { - case "ImportDeclaration": - if (statement.specifiers.length === 0) break; - imports.push({ - specifier: statement.source.value, - names: statement.specifiers.flatMap((s) => { - if (s.type === "ImportDefaultSpecifier") return ["default"]; - if (s.type === "ImportSpecifier") return [moduleName(s.imported)]; - return []; - }), - }); - break; - case "ExportNamedDeclaration": { - const imported: string[] = []; - for (const s of statement.specifiers) { - names.add(moduleName(s.exported)); - if (s.type === "ExportSpecifier") imported.push(moduleName(s.local)); - } - if (statement.source) imports.push({ specifier: statement.source.value, names: imported }); - for (const name of declared(statement.declaration)) names.add(name); - break; - } - case "ExportAllDeclaration": - stars.push(statement.source.value); - break; - case "ExportDefaultDeclaration": - names.add("default"); - break; - } - } - - return { names, stars, imports, bound: bindings(ast.program.body), referenced: references(ast.program.body) }; -} - -// The names a module declares or imports at its top level. -function bindings(body: Statement[]): Set { - const names = new Set(); - for (const statement of body) { - switch (statement.type) { - case "ImportDeclaration": - for (const s of statement.specifiers) names.add(s.local.name); - break; - case "TSImportEqualsDeclaration": - names.add(statement.id.name); - break; - case "ExportNamedDeclaration": - case "ExportDefaultDeclaration": - for (const name of declared(statement.declaration)) names.add(name); - break; - default: - for (const name of declared(statement)) names.add(name); - } - } - return names; -} - -// The leftmost identifier of every name the AST looks up in its enclosing scope: type references, -// `typeof` queries, heritage clauses, computed keys, and local re-exports. Type parameters are -// excluded file-wide, so a stripped name that shares a type parameter's name goes unnoticed. -function references(body: Statement[]): Set { - const found = new Set(); - const parameters = new Set(); - - const lookup = (node: unknown, into = found) => { - const name = leftmost(node); - if (name) into.add(name); - }; - - const walk = (node: unknown) => { - if (Array.isArray(node)) { - for (const child of node) walk(child); - return; - } - if (!node || typeof node !== "object" || !("type" in node)) return; - const n = node as Record; - - switch (n.type) { - case "TSTypeReference": - lookup(n.typeName); - break; - case "TSTypeQuery": - lookup(n.exprName); - break; - case "TSInterfaceHeritage": - case "TSClassImplements": - lookup(n.expression); - break; - case "ClassDeclaration": - lookup(n.superClass); - break; - case "ExportNamedDeclaration": - if (!n.source) for (const s of n.specifiers as Array<{ local: unknown }>) lookup(s.local); - break; - case "ExportDefaultDeclaration": - lookup(n.declaration); - break; - case "TSTypeParameter": - lookup(n.name, parameters); - break; - case "TSMappedType": - lookup(n.key, parameters); - break; - } - if (n.computed) lookup(n.key); - - for (const [key, value] of Object.entries(n)) { - if (key === "loc" || key.endsWith("Comments")) continue; - walk(value); - } - }; - walk(body); - - for (const name of parameters) found.delete(name); - return found; -} - -// The identifier a qualified name, member expression, or plain identifier starts with. -function leftmost(node: unknown): string | undefined { - if (!node || typeof node !== "object" || !("type" in node)) return undefined; - const n = node as Record; - if (n.type === "Identifier") return n.name as string; - if (n.type === "TSQualifiedName") return leftmost(n.left); - if (n.type === "MemberExpression") return leftmost(n.object); - return undefined; -} - -/** The name an import or export specifier spells, as an identifier or a string. */ -export function moduleName( - node: { type: "Identifier"; name: string } | { type: "StringLiteral"; value: string }, -): string { - return node.type === "Identifier" ? node.name : node.value; -} - -// The names a declaration statement introduces. -function declared(declaration: Statement | Declaration | DefaultDeclaration | null | undefined): string[] { - if (!declaration) return []; - if (declaration.type === "VariableDeclaration") { - return declaration.declarations.flatMap((d) => (d.id.type === "Identifier" ? [d.id.name] : [])); - } - if (!("id" in declaration) || !declaration.id) return []; - return declaration.id.type === "Identifier" ? [declaration.id.name] : []; -} diff --git a/js/common/docs.test.ts b/js/common/docs.test.ts deleted file mode 100644 index 3659e67d03c..00000000000 --- a/js/common/docs.test.ts +++ /dev/null @@ -1,361 +0,0 @@ -import { expect, test } from "bun:test"; -import { undocumented } from "./docs"; - -const root = "/dist"; - -// Each entrypoint gets the `@module` block it needs, so a test covers only what it names. -function check(files: Record, entrypoints = ["/dist/index.d.ts"]): string[] { - const described = Object.entries(files).map(([file, source]): [string, string] => - entrypoints.includes(file) ? [file, `/** Test. @module */\n\n${source}`] : [file, source], - ); - return undocumented(root, new Map(described), entrypoints); -} - -test("an entrypoint without a module block is reported", () => { - const found = undocumented( - root, - new Map([["/dist/index.d.ts", "/** Documented. */\nexport declare const a: number;\n"]]), - ["/dist/index.d.ts"], - ); - expect(found).toEqual(["index.d.ts: no @module block"]); -}); - -test("members inherited through a namespace import are checked", () => { - const found = check({ - "/dist/base.d.ts": "/** Documented. */\nexport declare class Parent {\n run(): void;\n}\n", - "/dist/index.d.ts": - 'import * as base from "./base";\n/** Documented. */\nexport declare class Derived extends base.Parent {}\n', - }); - expect(found).toEqual(["base.d.ts: Parent.run"]); -}); - -test("an undocumented export and class member are reported", () => { - const found = check({ - "/dist/index.d.ts": [ - "export declare const value: number;", - "/** Documented. */", - "export declare class Thing {", - " #private;", - " /** Documented. */", - " readonly name: string;", - " close(): void;", - "}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: value", "index.d.ts: Thing.close"]); -}); - -test("a line comment or an empty block is not a doc comment", () => { - const found = check({ - "/dist/index.d.ts": "// Not a doc.\nexport declare const a: number;\n/** */\nexport declare const b: number;\n", - }); - expect(found).toEqual(["index.d.ts: a", "index.d.ts: b"]); -}); - -test("re-exports resolve through stars, namespaces, aliases, imports, and defaults", () => { - const found = check({ - "/dist/inner.d.ts": - "/** Documented. */\nexport declare function documented(): void;\nexport declare function bare(): void;\n", - "/dist/ns/index.d.ts": "export type Hidden = number;\n", - "/dist/element.d.ts": "/** Documented. */\nexport default class Element {\n get url(): string;\n}\n", - "/dist/local.d.ts": "declare const local: number;\nexport { local as renamed };\n", - "/dist/index.d.ts": [ - 'export * from "./inner.js";', - "/** Documented. */", - 'export * as Ns from "./ns";', - 'export { default as Element } from "./element.ts";', - 'export { renamed } from "./local";', - 'import { documented } from "./inner";', - "export { documented as again };", - "/** Documented. */", - 'export * as External from "@moq/other";', - 'export { Other } from "@moq/other";', - ].join("\n"), - }); - expect(found).toEqual([ - "ns/index.d.ts: Ns.Hidden", - "element.d.ts: Element.url", - "local.d.ts: renamed", - "inner.d.ts: bare", - ]); -}); - -test("only the public surface needs docs", () => { - const found = check({ - "/dist/internal.d.ts": "export declare const unexported: number;\n", - "/dist/index.d.ts": [ - 'import "./internal";', - "/** Documented. */", - "export declare class Element extends HTMLElement {", - " #private;", - " private secret;", - " protected hook(): void;", - " static observedAttributes: string[];", - " constructor();", - " connectedCallback(): void;", - " readonly [BRAND] = true;", - " [key: string]: unknown;", - "}", - ].join("\n"), - }); - expect(found).toEqual([]); -}); - -test("members inherited from an unexported package class are checked", () => { - const found = check({ - "/dist/base.d.ts": "export declare class Base {\n run(): void;\n}\n", - "/dist/index.d.ts": [ - 'import { Base } from "./base";', - "/** Documented. */", - "export declare class Thing extends Base {}", - "/** Documented. */", - "export declare class Failure extends Error {}", - ].join("\n"), - }); - expect(found).toEqual(["base.d.ts: Base", "base.d.ts: Base.run"]); -}); - -test("members inherited from a class in a declared namespace are checked", () => { - const found = check({ - "/dist/index.d.ts": [ - "declare namespace Hidden {", - " class Parent {", - " run(): void;", - " }", - "}", - "/** Documented. */", - "export declare class Derived extends Hidden.Parent {}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: Hidden.Parent", "index.d.ts: Hidden.Parent.run"]); -}); - -test("members inherited through nested namespaces are checked", () => { - const found = check({ - "/dist/base.d.ts": "export declare namespace Inner {\n class Parent {\n run(): void;\n }\n}\n", - "/dist/index.d.ts": - 'import * as ns from "./base";\n/** Documented. */\nexport declare class Derived extends ns.Inner.Parent {}\n', - }); - expect(found).toEqual(["base.d.ts: Inner.Parent", "base.d.ts: Inner.Parent.run"]); -}); - -test("a dotted namespace is checked like a nested one", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare namespace Outer.Inner {", - " class Parent {", - " run(): void;", - " }", - "}", - "/** Documented. */", - "export declare class Derived extends Outer.Inner.Parent {}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: Outer.Inner.Parent", "index.d.ts: Outer.Inner.Parent.run"]); -}); - -test("only a block above the first statement is the module block", () => { - const source = - "/** Documented. */\nexport declare const a: number;\n/** Mentions @module. */\nexport declare const b: number;\n"; - const found = undocumented(root, new Map([["/dist/index.d.ts", source]]), ["/dist/index.d.ts"]); - expect(found).toEqual(["index.d.ts: no @module block"]); -}); - -test("a type-only star is checked like a value star", () => { - const found = check({ - "/dist/inner.d.ts": "export declare const value: number;\nexport type Shape = number;\n", - "/dist/index.d.ts": 'export type * from "./inner";\n', - }); - expect(found).toEqual(["inner.d.ts: value", "inner.d.ts: Shape"]); -}); - -test("an extensionless specifier prefers the file over a directory index", () => { - const found = check({ - "/dist/foo.d.ts": "export declare const file: number;\n", - "/dist/foo/index.d.ts": "export declare const index: number;\n", - "/dist/index.d.ts": 'export * from "./foo";\n', - }); - expect(found).toEqual(["foo.d.ts: file"]); -}); - -test("a namespace re-export needs its own doc, whichever package it names", () => { - const found = check({ - "/dist/ns.d.ts": "/** Documented. */\nexport declare const value: number;\n", - "/dist/index.d.ts": 'export * as Local from "./ns";\nexport * as External from "@moq/other";\n', - }); - expect(found).toEqual(["index.d.ts: Local", "index.d.ts: External"]); -}); - -test("a well-known symbol member needs a doc, unlike a brand", () => { - const found = check({ - "/dist/index.d.ts": - "/** Documented. */\nexport declare class Handle {\n readonly [BRAND] = true;\n [Symbol.dispose](): void;\n}\n", - }); - expect(found).toEqual(["index.d.ts: Handle.[Symbol.dispose]"]); -}); - -test("a type-only namespace re-export is checked like a value one", () => { - const found = check({ - "/dist/inner.d.ts": "export declare const value: number;\nexport type Shape = number;\n", - "/dist/index.d.ts": '/** Documented. */\nexport type * as Types from "./inner";\n', - }); - expect(found).toEqual(["inner.d.ts: Types.value", "inner.d.ts: Types.Shape"]); -}); - -test("an explicit export shadows the same name from a star", () => { - const found = check({ - "/dist/inner.d.ts": "export declare const name: number;\n", - "/dist/index.d.ts": '/** Documented. */\nexport declare const name: number;\nexport * from "./inner";\n', - }); - expect(found).toEqual([]); -}); - -test("a named default declaration is also exported by its name", () => { - const found = check({ - "/dist/index.d.ts": "/** Documented. */\nexport default class Thing {}\nexport { Thing };\n", - }); - expect(found).toEqual([]); -}); - -test("a module block does not document the statement after it", () => { - const found = check({ - "/dist/index.d.ts": "/**\n * The package.\n *\n * @module\n */\nexport declare const first: number;\n", - }); - expect(found).toEqual(["index.d.ts: first"]); -}); - -test("a literal computed key is an ordinary member", () => { - const found = check({ - "/dist/index.d.ts": - '/** Documented. */\nexport declare class Thing {\n ["parse"](): void;\n [42]: string;\n}\n', - }); - expect(found).toEqual(["index.d.ts: Thing.parse", "index.d.ts: Thing.42"]); -}); - -test("a star re-export skips the default export", () => { - const found = check({ - "/dist/inner.d.ts": "export default class Hidden {}\n/** Documented. */\nexport declare const shown: number;\n", - "/dist/index.d.ts": 'export * from "./inner";\n', - }); - expect(found).toEqual([]); -}); - -test("custom element reactions are exempt only on an element", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare class Hooks {", - " connectedCallback(): void;", - "}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: Hooks.connectedCallback"]); -}); - -test("a namespace merged with a class has its members checked", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare class Producer {}", - "export declare namespace Producer {", - " /** Documented. */", - " type Config = number;", - " type Bare = string;", - " class Inner {", - " run(): void;", - " }", - "}", - ].join("\n"), - }); - expect(found).toEqual([ - "index.d.ts: Producer.Bare", - "index.d.ts: Producer.Inner", - "index.d.ts: Producer.Inner.run", - ]); -}); - -test("one documented overload or accessor covers the name", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare function parse(text: string): number;", - "export declare function parse(text: string, radix: number): number;", - "/** Documented. */", - "export declare class Thing {", - " /** Documented. */", - " get value(): number;", - " set value(v: number);", - "}", - ].join("\n"), - }); - expect(found).toEqual([]); -}); - -test("a re-export of a missing name fails loudly", () => { - expect(() => check({ "/dist/a.d.ts": "", "/dist/index.d.ts": 'export { gone } from "./a";\n' })).toThrow( - "index.d.ts: ./a does not export gone", - ); -}); - -test("an export marker in a namespace hides its unexported members", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare namespace Ns {", - " function helper(): void;", - " /** Documented. */", - " export function run(): void;", - " export function bare(): void;", - " export {};", - "}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: Ns.bare"]); -}); - -test("an interface merged into a class has its members checked", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare class Thing {}", - "export interface Thing {", - " /** Documented. */", - " name: string;", - " run(): void;", - "}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: Thing.run"]); -}); - -test("a static member does not document the instance member of the same name", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare class Thing {", - " /** Documented. */", - " static create(): Thing;", - " create(): void;", - "}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: Thing.create"]); -}); - -test("members inherited from an unexported sibling in a namespace are checked", () => { - const found = check({ - "/dist/index.d.ts": [ - "/** Documented. */", - "export declare namespace Ns {", - " class Base {", - " run(): void;", - " }", - " /** Documented. */", - " export class Public extends Base {}", - " export {};", - "}", - ].join("\n"), - }); - expect(found).toEqual(["index.d.ts: Ns.Base", "index.d.ts: Ns.Base.run"]); -}); diff --git a/js/common/docs.ts b/js/common/docs.ts deleted file mode 100644 index c2d29cefbe5..00000000000 --- a/js/common/docs.ts +++ /dev/null @@ -1,449 +0,0 @@ -// Checks that a package's public surface carries doc comments. -// -// It walks the emitted `.d.ts` files from each entrypoint through their re-export chains, so it -// sees what a consumer can import rather than every `export` in a file, and `stripInternal` has -// already dropped the `@internal` symbols. TypeScript 7 has no stable compiler API and TypeDoc -// does not support it, so this parses declarations the same way `declarations.ts` does. - -import { relative } from "node:path"; -import { parse } from "@babel/parser"; -import { dtsPath, moduleName } from "./declarations.ts"; - -type Program = ReturnType["program"]; -type Node = Program["body"][number]; -type Comment = { type: string; value: string; end?: number }; - -type Binding = - | { kind: "local"; name: string } - | { kind: "import"; specifier: string; name: string } - // `documented` is set for an `export * as Name`, whose own statement carries the doc. - | { kind: "namespace"; specifier: string; documented?: boolean }; - -// A name's declarations, each with the statement that carries its comments. -type Declarations = Array<{ statement: Node; declaration: Node }>; - -type Module = { - // Top-level declarations by name. - locals: Map; - imports: Map; - exports: Map; - // `export *` targets. A type-only one counts too: `typeof` reaches its values. - stars: string[]; - // Where the first statement starts; a `@module` block above it documents the module. - header: number; - // Whether the file carries a `@module` block, which an entrypoint needs. - described: boolean; -}; - -/** Every exported symbol, or public member of an exported class, reachable from `entrypoints` without a doc comment. */ -export function undocumented(root: string, files: Map, entrypoints: string[]): string[] { - const modules = new Map(); - const load = (file: string): Module => { - let module = modules.get(file); - if (!module) { - const source = files.get(file); - if (source === undefined) throw new Error(`${relative(root, file)}: no such declaration file`); - module = parseModule(source); - modules.set(file, module); - } - return module; - }; - - const found: string[] = []; - const seen = new Set(); - const aliases = new Set(); - - // Report each declaration once, under the first public name that reaches it. - // A declaration reached by local path, with the namespaces enclosing it. - type Named = { key: string; file: string; name: string; declarations: Declarations; scopes: Named[] }; - - const visit = (file: string, path: string, binding: Binding) => { - // The `export * as Name` statement is what a consumer sees, whichever package it names. - if (binding.kind === "namespace" && binding.documented === false && !aliases.has(binding)) { - aliases.add(binding); - found.push(`${relative(root, file)}: ${path}`); - } - const resolved = resolveBinding(file, binding); - if (!resolved) return; - if (resolved.kind === "namespace") { - const key = `${resolved.file}#*`; - if (seen.has(key)) return; - seen.add(key); - walk(resolved.file, `${path}.`); - return; - } - - const declarations = load(resolved.file).locals.get(resolved.name); - if (!declarations) throw new Error(`${relative(root, resolved.file)}: cannot find ${resolved.name}`); - const key = `${resolved.file}#${resolved.name}`; - if (seen.has(key)) return; - seen.add(key); - check(resolved.file, path, key, declarations); - }; - - // Check one name's declarations, the public members of a class and of the package's classes it - // extends, and everything a namespace declares, since an ambient namespace exports all of it. - // `key` names the declaration by file and local path, so each is reported once; `scopes` are - // the namespaces enclosing it, innermost last. - const check = (file: string, path: string, key: string, declarations: Declarations, scopes: Named[] = []) => { - const where = relative(root, file); - const header = load(file).header; - if (!declarations.some(({ statement }) => documented(statement, header))) found.push(`${where}: ${path}`); - - // Keyed apart for static and instance members of the same name; overloads and accessor - // pairs share a key, and one documented declaration covers them all. - const members = new Map(); - const member = (node: unknown, element: boolean) => { - const name = memberName(node, element); - if (name === undefined) return; - const id = `${(node as { static?: boolean }).static ? "static " : ""}${name}`; - const ok = members.get(id)?.ok || documented(node as { leadingComments?: Comment[] | null }, header); - members.set(id, { name, ok }); - }; - const isClass = declarations.some(({ declaration }) => declaration.type === "ClassDeclaration"); - for (const { declaration } of declarations) { - // An interface merged into a class adds members to its instances. - if (isClass && declaration.type === "TSInterfaceDeclaration") { - for (const node of declaration.body.body) member(node, false); - } - if (declaration.type === "ClassDeclaration") { - const superClass = declaration.superClass; - const base = resolveClass(file, superClass, scopes); - if (base && "key" in base && !seen.has(base.key)) { - seen.add(base.key); - check(base.file, base.name, base.key, base.declarations, base.scopes); - } - const element = isElement(superClass); - for (const node of declaration.body.body) member(node, element); - } - } - for (const { name, ok } of members.values()) { - if (!ok) found.push(`${where}: ${path}.${name}`); - } - const scope = { key, file, name: key.slice(key.indexOf("#") + 1), declarations, scopes }; - for (const [name, list] of namespaceMembers(declarations)) { - const nested = `${key}.${name}`; - if (seen.has(nested)) continue; - seen.add(nested); - check(file, `${path}.${name}`, nested, list, [...scopes, scope]); - } - }; - - // What a superclass expression names: a module through a namespace import, or a package - // declaration reached by name or through any depth of namespaces (`ns.Inner.Parent`). - // Undefined for a global or another package's class. A bare name resolves in the enclosing - // namespaces first, which see their unexported members too. - const resolveClass = ( - file: string, - expression: unknown, - scopes: Named[], - ): Named | { module: string } | undefined => { - const local = (base: ReturnType): Named | { module: string } | undefined => { - if (base?.kind === "namespace") return { module: base.file }; - const declarations = base ? load(base.file).locals.get(base.name) : undefined; - if (!base || !declarations) return undefined; - return { key: `${base.file}#${base.name}`, file: base.file, name: base.name, declarations, scopes: [] }; - }; - const member = (owner: Named, name: string, all: boolean): Named | undefined => { - const declarations = namespaceMembers(owner.declarations, all).get(name); - if (!declarations) return undefined; - const local = `${owner.name}.${name}`; - const scopes = [...owner.scopes, owner]; - return { key: `${owner.file}#${local}`, file: owner.file, name: local, declarations, scopes }; - }; - const node = expression as { type: string; name?: string; object?: unknown; property?: unknown } | null; - if (node?.type === "Identifier" && node.name) { - for (const scope of scopes.toReversed()) { - const found = member(scope, node.name, true); - if (found) return found; - } - return local(resolveBinding(file, { kind: "local", name: node.name })); - } - - const property = node?.property as { type: string; name: string } | undefined; - if (node?.type !== "MemberExpression" || property?.type !== "Identifier") return undefined; - const owner = resolveClass(file, node.object, scopes); - if (!owner) return undefined; - if ("module" in owner) { - const next = findExport(owner.module, property.name, new Set()); - return next ? local(resolveBinding(next.file, next.binding)) : undefined; - } - return member(owner, property.name, false); - }; - - // Follow a binding to the file and local name that declares it; undefined for another package. - const resolveBinding = ( - file: string, - binding: Binding, - chain = new Set(), - ): { kind: "local"; file: string; name: string } | { kind: "namespace"; file: string } | undefined => { - if (binding.kind === "local") { - const imported = load(file).imports.get(binding.name); - if (imported) return resolveBinding(file, imported, chain); - return { kind: "local", file, name: binding.name }; - } - const target = dtsPath(files, file, binding.specifier); - if (!target) return undefined; - if (binding.kind === "namespace") return { kind: "namespace", file: target }; - const next = findExport(target, binding.name, chain); - if (!next) throw new Error(`${relative(root, file)}: ${binding.specifier} does not export ${binding.name}`); - return resolveBinding(next.file, next.binding, chain); - }; - - const findExport = ( - file: string, - name: string, - chain: Set, - ): { file: string; binding: Binding } | undefined => { - const key = `${file}#${name}`; - if (chain.has(key)) return undefined; - chain.add(key); - - const module = load(file); - const binding = module.exports.get(name); - if (binding) return { file, binding }; - if (name === "default") return undefined; - for (const specifier of module.stars) { - const target = dtsPath(files, file, specifier); - if (!target) continue; - const found = findExport(target, name, chain); - if (found) return found; - } - return undefined; - }; - - // `export *` never re-exports a default, nor a name the re-exporting module exports itself. - // `chain` holds only the active path, so a module reached again under different shadowing is - // walked again; `seen` stops repeats. - const walk = (file: string, prefix: string, chain = new Set(), hidden?: Set) => { - if (chain.has(file)) return; - chain.add(file); - const module = load(file); - for (const [name, binding] of module.exports) { - if (!hidden?.has(name)) visit(file, prefix + name, binding); - } - const shadowed = new Set([...(hidden ?? ["default"]), ...module.exports.keys()]); - for (const specifier of module.stars) { - const target = dtsPath(files, file, specifier); - if (target) walk(target, prefix, chain, shadowed); - } - chain.delete(file); - }; - - for (const entrypoint of entrypoints) { - if (!load(entrypoint).described) found.push(`${relative(root, entrypoint)}: no @module block`); - walk(entrypoint, ""); - } - return found; -} - -function parseModule(source: string): Module { - const module: Module = { - locals: new Map(), - imports: new Map(), - exports: new Map(), - stars: [], - header: 0, - described: false, - }; - const declare = (name: string, statement: Node, declaration: Node) => { - const list = module.locals.get(name) ?? []; - list.push({ statement, declaration }); - module.locals.set(name, list); - }; - - const ast = parse(source, { sourceType: "module", plugins: [["typescript", { dts: true }], "jsx"] }); - module.header = ast.program.body[0]?.start ?? Number.POSITIVE_INFINITY; - module.described = (ast.comments ?? []).some((c) => isModuleBlock(c, module.header)); - for (const statement of ast.program.body) { - switch (statement.type) { - case "ImportDeclaration": - for (const s of statement.specifiers) { - const specifier = statement.source.value; - if (s.type === "ImportNamespaceSpecifier") { - module.imports.set(s.local.name, { kind: "namespace", specifier }); - } else { - const name = s.type === "ImportDefaultSpecifier" ? "default" : moduleName(s.imported); - module.imports.set(s.local.name, { kind: "import", specifier, name }); - } - } - break; - case "ExportNamedDeclaration": - for (const s of statement.specifiers) { - const exported = moduleName(s.exported); - if (s.type === "ExportNamespaceSpecifier") { - if (statement.source) - module.exports.set(exported, { - kind: "namespace", - specifier: statement.source.value, - documented: documented(statement, module.header), - }); - } else if (s.type === "ExportSpecifier") { - const name = moduleName(s.local); - module.exports.set( - exported, - statement.source - ? { kind: "import", specifier: statement.source.value, name } - : { kind: "local", name }, - ); - } - } - for (const name of declared(statement.declaration)) { - declare(name, statement, statement.declaration as Node); - module.exports.set(name, { kind: "local", name }); - } - break; - case "ExportAllDeclaration": - module.stars.push(statement.source.value); - break; - case "ExportDefaultDeclaration": { - const declaration = statement.declaration; - // A named default declaration also binds its name, which an `export { Name }` can use. - const id = (declaration as { id?: { type: string; name: string } | null }).id; - const name = - declaration.type === "Identifier" - ? declaration.name - : id?.type === "Identifier" - ? id.name - : "default"; - if (declaration.type !== "Identifier") declare(name, statement, declaration as Node); - module.exports.set("default", { kind: "local", name }); - break; - } - default: - for (const name of declared(statement)) declare(name, statement, statement); - } - } - return module; -} - -// What an ambient namespace among `declarations` exports, by name, or with `all` everything it -// declares, as seen from inside it. -function namespaceMembers(declarations: Declarations, all = false): Map { - const members = new Map(); - for (const { statement: outer, declaration } of declarations) { - if (declaration.type !== "TSModuleDeclaration" || declaration.body.type !== "TSModuleBlock") continue; - // `namespace Outer.Inner { ... }` declares `Inner` inside `Outer`, with the same body. - const names = path(declaration.id); - if (names.length > 1) { - const inner = { ...declaration, id: qualified(names.slice(1)) } as Node; - const list = members.get(names[1]) ?? []; - list.push({ statement: outer, declaration: inner }); - members.set(names[1], list); - continue; - } - // Every member of an ambient namespace is exported, unless an `export {}` marker says only - // the `export`ed ones are, as declaration emit writes when it keeps a private helper. - const body = declaration.body.body; - const explicit = body.some( - (s) => s.type === "ExportNamedDeclaration" && !s.declaration && !s.source && s.specifiers.length === 0, - ); - for (const statement of body) { - if (explicit && !all && statement.type !== "ExportNamedDeclaration") continue; - const inner = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement; - for (const name of declared(inner)) { - const list = members.get(name) ?? []; - list.push({ statement, declaration: inner as Node }); - members.set(name, list); - } - } - } - return members; -} - -// A `@module` doc block above a file's first statement, which documents the module. -function isModuleBlock(c: Comment, header: number): boolean { - return c.type === "CommentBlock" && (c.end ?? 0) <= header && /^\*[\s\S]*@module\b/.test(c.value); -} - -// A doc comment is a non-empty `/** */` block before the node, other than the file's module block. -function documented(node: { leadingComments?: Comment[] | null }, header: number): boolean { - return (node.leadingComments ?? []).some( - (c) => c.type === "CommentBlock" && /^\*[\s*]*[^\s*/]/.test(c.value) && !isModuleBlock(c, header), - ); -} - -// Custom element reactions: on an element, the browser calls them and the HTML spec documents them. -const REACTIONS = new Set([ - "observedAttributes", - "connectedCallback", - "disconnectedCallback", - "adoptedCallback", - "connectedMoveCallback", - "attributeChangedCallback", -]); - -// Whether a class extends an element class such as `HTMLElement`, by its name. -function isElement(superClass: unknown): boolean { - const node = superClass as { type: string; name?: string; property?: { name?: string } } | null | undefined; - const name = node?.type === "MemberExpression" ? node.property?.name : node?.name; - return name !== undefined && /Element$/.test(name); -} - -// The name of a class member a consumer can use, or undefined for one that needs no doc: -// constructors, private and protected members, `#private`, an element's custom element -// reactions, and members keyed by a symbol other than a well-known one, such as brands. -function memberName(member: unknown, element: boolean): string | undefined { - const m = member as { - type: string; - kind?: string; - computed?: boolean; - accessibility?: string; - key?: { - type: string; - name?: string; - value?: unknown; - object?: { type: string; name?: string }; - property?: { type: string; name?: string }; - }; - }; - if (m.type === "ClassPrivateProperty" || m.type === "ClassPrivateMethod") return undefined; - if (m.type === "TSIndexSignature" || m.type === "StaticBlock") return undefined; - if (m.kind === "constructor") return undefined; - if (m.accessibility === "private" || m.accessibility === "protected") return undefined; - if (!m.key) return undefined; - let name: string | undefined; - if (m.key.type === "Identifier" && !m.computed) name = m.key.name; - else if (m.key.type === "StringLiteral" || m.key.type === "NumericLiteral") name = String(m.key.value); - // A well-known symbol (`[Symbol.dispose]`) is a protocol a consumer uses, unlike a private brand. - else if (m.key.type === "MemberExpression" && m.key.object?.name === "Symbol" && m.key.property?.name) { - name = `[Symbol.${m.key.property.name}]`; - } - return name === undefined || (element && REACTIONS.has(name)) ? undefined : name; -} - -// The names a declaration statement introduces. -function declared(declaration: unknown): string[] { - const d = declaration as - | { - type: string; - id?: { type: string; name?: string } | null; - declarations?: Array<{ id: { type: string; name?: string } }>; - } - | null - | undefined; - if (!d) return []; - if (d.type === "VariableDeclaration") { - return (d.declarations ?? []).flatMap((v) => (v.id.type === "Identifier" && v.id.name ? [v.id.name] : [])); - } - if (!/Declaration$|^TSDeclareFunction$/.test(d.type)) return []; - if (d.type === "TSModuleDeclaration") return path(d.id).slice(0, 1); - return d.id?.type === "Identifier" && d.id.name ? [d.id.name] : []; -} - -// The names of a dotted namespace id (`Outer.Inner`), outermost first; empty for a string id. -function path(id: unknown): string[] { - const node = id as { type: string; name?: string; left?: unknown; right?: unknown } | null | undefined; - if (node?.type === "Identifier" && node.name) return [node.name]; - if (node?.type === "TSQualifiedName") return [...path(node.left), ...path(node.right)]; - return []; -} - -// A dotted namespace id from its names, the inverse of {@link path}. -function qualified(names: string[]): unknown { - const [first, ...rest] = names; - return rest.reduce( - (left, name) => ({ type: "TSQualifiedName", left, right: { type: "Identifier", name } }), - { type: "Identifier", name: first }, - ); -} diff --git a/js/common/package.ts b/js/common/package.ts index 08af7f4da5b..1f651f83b8b 100644 --- a/js/common/package.ts +++ b/js/common/package.ts @@ -3,12 +3,10 @@ // Split from release.ts to allow building packages without publishing import { copyFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; -import { basename, dirname, join, resolve } from "node:path"; +import { basename, join, resolve } from "node:path"; import { publint } from "publint"; import { formatMessage } from "publint/utils"; import { checkReports } from "./api.ts"; -import { problems, type Source } from "./declarations.ts"; -import { undocumented } from "./docs.ts"; console.log("✍️ Rewriting package.json..."); const pkg = JSON.parse(readFileSync("package.json", "utf8")); @@ -145,41 +143,8 @@ if (messages.length > 0) { process.exit(1); } -console.log("🔍 Checking declaration names..."); -const declarations = new Map(); -const sources = new Map(); -for (const rel of new Bun.Glob("**/*.d.ts").scanSync("dist")) { - const file = resolve("dist", rel); - declarations.set(file, readFileSync(file, "utf8")); - - // A declaration copied rather than emitted has no map, and no source to compare against. - const map = `${file}.map`; - if (!existsSync(map)) continue; - const [source] = JSON.parse(readFileSync(map, "utf8")).sources as string[]; - if (!source) continue; - const path = resolve(dirname(map), source); - sources.set(file, { path, text: readFileSync(path, "utf8") }); -} -const unresolved = problems(resolve("dist"), declarations, sources); -if (unresolved.length > 0) { - for (const problem of unresolved) console.error(problem); - process.exit(1); -} - if (published) { - console.log("🔍 Checking doc comments..."); - const entrypoints = Object.values(pkg.exports ?? {}).flatMap((value) => { - const types = (value as { types?: string }).types; - return types ? [resolve("dist", types)] : []; - }); - const missing = undocumented(resolve("dist"), declarations, entrypoints); - if (missing.length > 0) { - console.error("Add a /** */ doc comment to each exported symbol and public class member:"); - for (const problem of missing) console.error(` dist/${problem}`); - process.exit(1); - } - - console.log("🔍 Checking API reports..."); + console.log("🔍 Checking declarations and API reports..."); checkReports("."); } diff --git a/js/flate/api/index.api.md b/js/flate/api/index.api.md index e1f38464cef..0ede5b55b84 100644 --- a/js/flate/api/index.api.md +++ b/js/flate/api/index.api.md @@ -98,6 +98,7 @@ declare namespace Snapshot { Producer } } +export { Snapshot } declare namespace Stream { export { @@ -107,6 +108,6 @@ declare namespace Stream { Producer_2 as Producer } } - +export { Stream } ``` diff --git a/js/flate/src/snapshot/consumer.ts b/js/flate/src/snapshot/consumer.ts index fe2258f2e99..e2dea1656f8 100644 --- a/js/flate/src/snapshot/consumer.ts +++ b/js/flate/src/snapshot/consumer.ts @@ -122,6 +122,7 @@ export class Consumer { } } +/** Types for {@link Consumer}. */ export namespace Consumer { /** Snapshot consumer options, including the source track. */ export type Config = CodecConfig & { track: Moq.Track.Subscriber }; diff --git a/js/flate/src/snapshot/producer.ts b/js/flate/src/snapshot/producer.ts index c9c8e6250c5..170f9f90545 100644 --- a/js/flate/src/snapshot/producer.ts +++ b/js/flate/src/snapshot/producer.ts @@ -71,8 +71,10 @@ export class Producer { } } +/** Producer options, including the destination track. */ type Init = Config & { track: Moq.Track.Producer }; +/** Types for {@link Producer}. */ export namespace Producer { /** Snapshot producer options, including the destination track. */ export type Config = Init; diff --git a/js/flate/src/stream/consumer.ts b/js/flate/src/stream/consumer.ts index ef878d8d2ac..14591752dff 100644 --- a/js/flate/src/stream/consumer.ts +++ b/js/flate/src/stream/consumer.ts @@ -145,6 +145,7 @@ export class Consumer { } } +/** Types for {@link Consumer}. */ export namespace Consumer { /** Stream consumer options, including the source track. */ export type Config = CodecConfig & { track: Moq.Track.Subscriber }; diff --git a/js/flate/src/stream/producer.ts b/js/flate/src/stream/producer.ts index fb023d26d98..02098507f7f 100644 --- a/js/flate/src/stream/producer.ts +++ b/js/flate/src/stream/producer.ts @@ -106,8 +106,10 @@ export class Producer { } } +/** Producer options, including the destination track. */ type Init = Config & { track: Moq.Track.Producer }; +/** Types for {@link Producer}. */ export namespace Producer { /** Stream producer options, including the destination track. */ export type Config = Init; diff --git a/js/hang/api/catalog.api.md b/js/hang/api/catalog.api.md index ed5ed88b5ac..7ffe7a5b253 100644 --- a/js/hang/api/catalog.api.md +++ b/js/hang/api/catalog.api.md @@ -1667,5 +1667,4 @@ export function wallClockTime(clock: Clock, pts: number, ptsTimescale: number): export function watch(broadcast: Moq.Broadcast.Consumer): AsyncIterable; - ``` diff --git a/js/hang/api/cmaf.api.md b/js/hang/api/cmaf.api.md index e085c62f39f..869efeb8299 100644 --- a/js/hang/api/cmaf.api.md +++ b/js/hang/api/cmaf.api.md @@ -46,5 +46,4 @@ export interface Sample { timestamp: number; } - ``` diff --git a/js/hang/api/container.api.md b/js/hang/api/container.api.md index b95f1f7cad2..7c3b28e0ce3 100644 --- a/js/hang/api/container.api.md +++ b/js/hang/api/container.api.md @@ -107,6 +107,7 @@ declare namespace Legacy { Producer } } +export { Legacy } export { Loc } @@ -270,5 +271,4 @@ const VideoConfigSchema: z.ZodMiniObject<{ delay: z.ZodMiniOptional, "u53", "out">, z.ZodMiniTransform<(number & z.$brand<"u53">) | undefined, number & z.$brand<"u53">>>>; }, z.core.$strip>; - ``` diff --git a/js/hang/api/index.api.md b/js/hang/api/index.api.md index baa73f62779..678fccc1e7c 100644 --- a/js/hang/api/index.api.md +++ b/js/hang/api/index.api.md @@ -367,97 +367,7 @@ declare namespace Catalog { Track } } - -declare namespace Catalog_2 { - export { - Audio_2 as Audio, - Video, - AudioConfig, - AudioConfigSchema, - AudioSchema, - Color, - Projection, - VideoConfig, - ColorSchema, - ProjectionSchema, - VideoConfigSchema, - VideoSchema, - MOQ_EPOCH_UNIX_MILLIS, - ARCHIVE_VERSION, - ArchiveSchema, - Archive, - BinaryConfigSchema, - BinarySchema, - Binary, - BinaryConfig, - wallClockTime, - ClockSchema, - Clock, - compressionSupported, - KnownCompression, - CompressionSchema, - Compression, - containerSupported, - UnknownContainerSchema, - ContainerSchema, - Container_2 as Container, - CmafContainer, - EchoSchema, - Echo_2 as Echo, - detectFormat, - TRACK, - TRACK_COMPRESSED, - FORMATS, - Format, - DEFAULT_FORMAT, - hexSchema, - Hex, - u8, - u53, - u8Schema, - U8, - u53Schema, - U53, - nonzeroU53Schema, - JsonConfigSchema, - JsonSchema, - Json, - JsonConfig, - modeSupported, - KnownMode, - ModeSchema, - Mode, - RelativeBroadcastSchema, - RelativeBroadcast, - EpochSchema, - ReferenceEpoch, - PRIORITY, - checkRenditions, - encode, - checkResolvable, - watch, - VERSION, - UnsupportedVersion, - RootSchema, - Root, - MAX_RENDITIONS, - TooManyRenditions, - DuplicateRendition, - EscapingBroadcast, - StatsSchema, - Stats_2 as Stats, - TextFormatSchema, - TextRoleSchema, - TextConfigSchema, - TextSchema, - Text_2 as Text, - TextConfig, - TextRole, - track, - TrackSchema, - Track - } -} +export { Catalog } function checkRenditions(root: Root): Root; @@ -536,7 +446,7 @@ class Consumer_2 implements AsyncIterable { [Symbol.asyncIterator](): AsyncIterator; close(): void; next(): Promise; - static subscribe(broadcast: Net.Broadcast.Consumer, archive: Catalog_2.Archive, track: string): Consumer_2; + static subscribe(broadcast: Net.Broadcast.Consumer, archive: Catalog.Archive, track: string): Consumer_2; } interface ConsumerProps { @@ -562,6 +472,7 @@ declare namespace Container { BufferedRanges } } +export { Container } type Container_2 = z.infer; @@ -611,23 +522,10 @@ declare namespace Echo { TRACK_2 as TRACK } } +export { Echo } type Echo_2 = z.infer; -declare namespace Echo_3 { - export { - isEcho, - ArrivalSchema, - Arrival, - RenditionSchema, - Rendition, - SnapshotSchema, - Snapshot, - SUFFIX, - TRACK_2 as TRACK - } -} - const EchoSchema: z.ZodMiniObject<{ path: z.ZodMiniType>; }, z.core.$strip>; @@ -710,6 +608,7 @@ declare namespace Health { Health_2 as Health } } +export { Health } interface Health_2 { interval?: number; @@ -802,7 +701,7 @@ interface Observer { path: Path.Valid; } -interface Position_2 { +interface Position { frame?: number; group: number; } @@ -841,7 +740,7 @@ const ProjectionSchema: z.ZodMiniUnion>]>; -function publisher(sample: Sample, thresholds?: Thresholds): Health_2; +function publisher(sample: Sample, thresholds?: Thresholds): Health_2; function ranked(renditions: Record): [string, AudioConfig][]; @@ -885,11 +784,11 @@ interface ReceivedFrame extends Frame { interface Record_2 { duration?: number; - end: Position_2; + end: Position; keyframe?: boolean; pts?: number; sequence: number; - start: Position_2; + start: Position; } type ReferenceEpoch = string & { @@ -1624,20 +1523,10 @@ declare namespace Stats { Snapshot_2 as Snapshot } } +export { Stats } type Stats_2 = z.infer; -declare namespace Stats_3 { - export { - TransportSchema, - Transport, - RenditionSchema_2 as RenditionSchema, - Rendition_2 as Rendition, - SnapshotSchema_2 as SnapshotSchema, - Snapshot_2 as Snapshot - } -} - const StatsSchema: z.ZodMiniObject<{ track: z.ZodMiniString; }, z.core.$strip>; @@ -1739,7 +1628,7 @@ interface Thresholds { declare namespace Timeline { export { - Position_2 as Position, + Position, Record_2 as Record, SUFFIX_2 as SUFFIX, Entry, @@ -1747,6 +1636,7 @@ declare namespace Timeline { Consumer_2 as Consumer } } +export { Timeline } class TooManyRenditions extends Error { constructor(count: number); @@ -2303,11 +2193,10 @@ const VideoSchema: z.ZodMiniUnion>]>; -function viewer(sample: Sample, thresholds?: Thresholds): Health_2; +function viewer(sample: Sample, thresholds?: Thresholds): Health_2; function wallClockTime(clock: Clock, pts: number, ptsTimescale: number): Date; function watch(broadcast: Net.Broadcast.Consumer): AsyncIterable; - ``` diff --git a/js/hang/api/util.api.md b/js/hang/api/util.api.md index 329df704696..771a1e6a32a 100644 --- a/js/hang/api/util.api.md +++ b/js/hang/api/util.api.md @@ -16,6 +16,7 @@ declare namespace Aac { SAMPLE_RATES } } +export { Aac } function audioSpecificConfig(sampleRate: number, channelCount: number): Uint8Array; @@ -28,6 +29,7 @@ declare namespace Gesture { unlock } } +export { Gesture } declare namespace Hacks { export { @@ -36,6 +38,7 @@ declare namespace Hacks { isSafari } } +export { Hacks } declare namespace Hex { export { @@ -43,6 +46,7 @@ declare namespace Hex { fromBytes } } +export { Hex } const isChrome: boolean; @@ -55,6 +59,7 @@ declare namespace Libav { polyfill } } +export { Libav } function objectType(codec: string): 2 | 5 | 29 | undefined; @@ -70,6 +75,7 @@ declare namespace Opus { SAMPLE_RATES_2 as SAMPLE_RATES } } +export { Opus } function packetSamples(packet: Uint8Array): number | undefined; @@ -97,5 +103,4 @@ function unlock(effect: Effect, context: AudioContext): Getter; const WARMUP = 80; - ``` diff --git a/js/hang/src/container/types.ts b/js/hang/src/container/types.ts index 3bad828fe05..e6d7edd3f4c 100644 --- a/js/hang/src/container/types.ts +++ b/js/hang/src/container/types.ts @@ -9,11 +9,13 @@ export interface Frame { /** Whether this frame opens a group, or is a video keyframe. Audio carries it only on a group start. */ keyframe: boolean; - // How long this frame occupies the presentation timeline. CMAF carries a - // per-sample duration; Legacy and LOC report later endpoints through Consumer.next().end. - // The consumer adds it to `timestamp` to learn how far a group has presented, - // so it can advance to a newer group as soon as the gap is covered instead of - // waiting out the max delay budget. + /** + * How long this frame occupies the presentation timeline. CMAF carries a + * per-sample duration; Legacy and LOC report later endpoints through Consumer.next().end. + * The consumer adds it to `timestamp` to learn how far a group has presented, + * so it can advance to a newer group as soon as the gap is covered instead of + * waiting out the max delay budget. + */ duration?: Micro; } diff --git a/js/hang/src/timeline.ts b/js/hang/src/timeline.ts index e9e6e1c4acf..c4284007ce6 100644 --- a/js/hang/src/timeline.ts +++ b/js/hang/src/timeline.ts @@ -19,6 +19,7 @@ import { u53Schema } from "./catalog"; /** A frame position within a track: frame `frame` of group `group`. */ export interface Position { + /** The group sequence. */ group: number; /** Omitted when zero, so a position at a group start reads as just the group. */ frame?: number; @@ -33,9 +34,13 @@ export interface Position { export interface Record { /** The record's number, consecutive within its track's timeline. */ sequence: number; + /** The presentation timestamp of the span's first frame. */ pts?: number; + /** How long the span plays. */ duration?: number; + /** The span's first frame. */ start: Position; + /** The position just past the span's last frame. */ end: Position; /** Whether the span starts with a keyframe. Omitted when true (the default). */ keyframe?: boolean; diff --git a/js/json/api/index.api.md b/js/json/api/index.api.md index d1ec1d315e6..c1eb5eba34f 100644 --- a/js/json/api/index.api.md +++ b/js/json/api/index.api.md @@ -61,14 +61,10 @@ class Consumer_3 { get offset(): number; } -type ConsumerConfig = ConsumerConfig_2 & { +type ConsumerConfig = DecoderConfig & { track: Moq.Track.Subscriber; }; -interface ConsumerConfig_2 { - compression?: boolean; -} - class Decoder { constructor(config?: Pick, "schema" | "compression">); decode(): T | undefined; @@ -84,12 +80,16 @@ class Decoder_2 { } class Decoder_3 { - constructor(config?: ConsumerConfig_2); + constructor(config?: DecoderConfig); group(): Group; next(): Event_2 | undefined; get offset(): number; } +interface DecoderConfig { + compression?: boolean; +} + export function deepEqual(a: unknown, b: unknown): boolean; export class Desync extends Error { @@ -232,6 +232,7 @@ declare namespace Snapshot { Producer } } +export { Snapshot } interface Span { end: number; @@ -250,12 +251,14 @@ declare namespace Stream { Producer_2 as Producer } } +export { Stream } declare namespace Window_2 { export { Consumer_3 as Consumer, ConsumerConfig, Decoder_3 as Decoder, + DecoderConfig, Event_2 as Event, Group, Span, @@ -267,6 +270,6 @@ declare namespace Window_2 { ProducerConfig } } - +export { Window_2 as Window } ``` diff --git a/js/json/src/snapshot/consumer.ts b/js/json/src/snapshot/consumer.ts index 240508c214b..30faf62b581 100644 --- a/js/json/src/snapshot/consumer.ts +++ b/js/json/src/snapshot/consumer.ts @@ -134,6 +134,7 @@ export class Consumer { } } +/** Types for {@link Consumer}. */ export namespace Consumer { /** Snapshot consumer options, including the source track. */ export type Config = Pick, "schema" | "compression"> & { diff --git a/js/json/src/snapshot/encoder.ts b/js/json/src/snapshot/encoder.ts index bfd41a977d3..1bca1ae6458 100644 --- a/js/json/src/snapshot/encoder.ts +++ b/js/json/src/snapshot/encoder.ts @@ -11,26 +11,32 @@ const MAX_DELTA_FRAMES = 256; /** Options shared by an {@link Encoder} and the {@link Producer} that wraps one. */ export interface Config { - // Encode changes as deltas (merge patches) against the group's snapshot. `false` encodes every - // change as a new snapshot in its own group. - // - // A group of deltas runs until a joiner wants a fresh one, judged by the track's `refresh` ratio - // (see {@link Encoder.snapshot}), or until it reaches the frame or byte cap. - // - // Defaults to `true`. + /** + * Encode changes as deltas (merge patches) against the group's snapshot. `false` encodes every + * change as a new snapshot in its own group. + * + * A group of deltas runs until a joiner wants a fresh one, judged by the track's `refresh` ratio + * (see {@link Encoder.snapshot}), or until it reaches the frame or byte cap. + * + * Defaults to `true`. + */ deltas?: boolean; - // Optional zod schema used to validate each value before publishing. + /** Optional zod schema used to validate each value before publishing. */ schema?: z.ZodMiniType; - // Starting value for {@link Producer.mutate} before anything has been published. Required to - // mutate a producer that hasn't published yet (e.g. a fresh catalog); ignored once a value exists. + /** + * Starting value for {@link Producer.mutate} before anything has been published. Required to + * mutate a producer that hasn't published yet (e.g. a fresh catalog); ignored once a value exists. + */ initial?: T; - // Compress each group as one sync-flushed `deflate-raw` (RFC 1951) stream, so deltas reuse the - // snapshot as context and shrink sharply. Interoperable with the Rust `moq-json` producer. - // `"none"`/unset (the default) writes plaintext JSON frames. A {@link Decoder} reading them - // must set the same {@link compression}. + /** + * Compress each group as one sync-flushed `deflate-raw` (RFC 1951) stream, so deltas reuse the + * snapshot as context and shrink sharply. Interoperable with the Rust `moq-json` producer. + * `"none"`/unset (the default) writes plaintext JSON frames. A {@link Decoder} reading them + * must set the same {@link compression}. + */ compression?: Compression; /** diff --git a/js/json/src/snapshot/producer.ts b/js/json/src/snapshot/producer.ts index 638c40e59ad..30d7d1a0582 100644 --- a/js/json/src/snapshot/producer.ts +++ b/js/json/src/snapshot/producer.ts @@ -197,6 +197,7 @@ export class Producer { } } +/** Types for {@link Producer}. */ export namespace Producer { /** Snapshot producer options, including the destination track. */ export type Config = CodecConfig & { track: Moq.Track.Producer }; diff --git a/js/json/src/stream/consumer.ts b/js/json/src/stream/consumer.ts index 9da7f30b7f8..e8263fd016c 100644 --- a/js/json/src/stream/consumer.ts +++ b/js/json/src/stream/consumer.ts @@ -81,6 +81,7 @@ export class Consumer { } } +/** Types for {@link Consumer}. */ export namespace Consumer { /** Stream consumer options, including the source track. */ export type Config = CodecConfig & { track: Moq.Track.Subscriber }; diff --git a/js/json/src/stream/producer.ts b/js/json/src/stream/producer.ts index be17354c7df..dc870763a2f 100644 --- a/js/json/src/stream/producer.ts +++ b/js/json/src/stream/producer.ts @@ -100,6 +100,7 @@ export class Producer { } } +/** Types for {@link Producer}. */ export namespace Producer { /** Stream producer options, including the destination track. */ export type Config = CodecConfig & { track: Moq.Track.Producer }; diff --git a/js/json/src/window/consumer.ts b/js/json/src/window/consumer.ts index e2f1ad484b4..2590b4a3377 100644 --- a/js/json/src/window/consumer.ts +++ b/js/json/src/window/consumer.ts @@ -1,9 +1,9 @@ import * as Moq from "@moq/net"; -import { type ConsumerConfig as CodecConfig, Decoder, type Event, type Group } from "./decoder.ts"; +import { Decoder, type DecoderConfig, type Event, type Group } from "./decoder.ts"; /** Window consumer options, including the source track. */ -export type ConsumerConfig = CodecConfig & { track: Moq.Track.Subscriber }; +export type ConsumerConfig = DecoderConfig & { track: Moq.Track.Subscriber }; // A group that ended early rather than failing: the next one restates the window, so a gap is // something to resync from. Old and Evicted are how the publisher says it dropped a group it was diff --git a/js/json/src/window/decoder.ts b/js/json/src/window/decoder.ts index 5a2023dbc44..43e47c08784 100644 --- a/js/json/src/window/decoder.ts +++ b/js/json/src/window/decoder.ts @@ -17,7 +17,7 @@ function index(value: unknown, label: string): number { } /** Options for a {@link Decoder}. */ -export interface ConsumerConfig { +export interface DecoderConfig { /** Read frames written with `Config.compression` on. Defaults to `false`. */ compression?: boolean; } @@ -73,7 +73,7 @@ export class Decoder { #events: Queued[] = []; #nextEvent = 0; - constructor(config: ConsumerConfig = {}) { + constructor(config: DecoderConfig = {}) { this.#compress = config.compression ?? false; } diff --git a/js/json/src/window/index.ts b/js/json/src/window/index.ts index ed8260a6c5d..fbf00b52fab 100644 --- a/js/json/src/window/index.ts +++ b/js/json/src/window/index.ts @@ -37,6 +37,6 @@ */ export { Consumer, type ConsumerConfig } from "./consumer.ts"; -export { Decoder, type Event, type Group, type Span } from "./decoder.ts"; +export { Decoder, type DecoderConfig, type Event, type Group, type Span } from "./decoder.ts"; export { type Config, type Encoded, Encoder, type Pending } from "./encoder.ts"; export { Producer, type ProducerConfig } from "./producer.ts"; diff --git a/js/libav/api/index.api.md b/js/libav/api/index.api.md index 6ccbb25d355..55f5278b82e 100644 --- a/js/libav/api/index.api.md +++ b/js/libav/api/index.api.md @@ -9,5 +9,4 @@ import type { LibAVWrapper } from '@libav.js/types'; const LibAV: LibAVWrapper; export default LibAV; - ``` diff --git a/js/loc/api/index.api.md b/js/loc/api/index.api.md index df59fa2c3f3..32d5fb840f8 100644 --- a/js/loc/api/index.api.md +++ b/js/loc/api/index.api.md @@ -19,5 +19,4 @@ export interface Frame { timestamp: Micro; } - ``` diff --git a/js/moq-boy/api/element.api.md b/js/moq-boy/api/element.api.md index bba24fd091e..037654969bd 100644 --- a/js/moq-boy/api/element.api.md +++ b/js/moq-boy/api/element.api.md @@ -57,13 +57,13 @@ interface GameConfig { class MoqBoy extends HTMLElement { constructor(); - attributeChangedCallback(name: Observed, _oldValue: string | null, newValue: string | null): void; + attributeChangedCallback(name: (typeof OBSERVED)[number], _oldValue: string | null, newValue: string | null): void; connectedCallback(): void; readonly connection: Moq.Connection; disconnectedCallback(): void; readonly expanded: Moq.Signals.Signal; readonly games: Moq.Signals.Signal>; - static observedAttributes: readonly ["url", "prefix", "prefix-game", "prefix-viewer"]; + static observedAttributes: typeof OBSERVED; readonly origin: Moq.Origin.Producer; get prefixGame(): string; set prefixGame(value: string); @@ -78,7 +78,4 @@ export default MoqBoy; const OBSERVED: readonly ["url", "prefix", "prefix-game", "prefix-viewer"]; -type Observed = (typeof OBSERVED)[number]; - - ``` diff --git a/js/moq-boy/api/index.api.md b/js/moq-boy/api/index.api.md index 9df06dc8115..fa084bc1e15 100644 --- a/js/moq-boy/api/index.api.md +++ b/js/moq-boy/api/index.api.md @@ -88,13 +88,13 @@ export { Moq } export class MoqBoy extends HTMLElement { constructor(); - attributeChangedCallback(name: Observed, _oldValue: string | null, newValue: string | null): void; + attributeChangedCallback(name: (typeof OBSERVED)[number], _oldValue: string | null, newValue: string | null): void; connectedCallback(): void; readonly connection: Moq.Connection; disconnectedCallback(): void; readonly expanded: Moq.Signals.Signal; readonly games: Moq.Signals.Signal>; - static observedAttributes: readonly ["url", "prefix", "prefix-game", "prefix-viewer"]; + static observedAttributes: typeof OBSERVED; readonly origin: Moq.Origin.Producer; get prefixGame(): string; set prefixGame(value: string); @@ -108,9 +108,6 @@ export class MoqBoy extends HTMLElement { const OBSERVED: readonly ["url", "prefix", "prefix-game", "prefix-viewer"]; -type Observed = (typeof OBSERVED)[number]; - export { Watch } - ``` diff --git a/js/moq-boy/src/element.tsx b/js/moq-boy/src/element.tsx index a0c9c0ba93b..26580a43482 100644 --- a/js/moq-boy/src/element.tsx +++ b/js/moq-boy/src/element.tsx @@ -12,8 +12,8 @@ import type { GameConfig } from "./game.ts"; import { Game } from "./game.ts"; import { BoyUI } from "./ui/element.tsx"; +/** The attributes the element observes. */ const OBSERVED = ["url", "prefix", "prefix-game", "prefix-viewer"] as const; -type Observed = (typeof OBSERVED)[number]; const DEFAULT_PREFIX = "boy"; @@ -26,11 +26,12 @@ const cleanup = new FinalizationRegistry((signals) => signal * Attributes: * - `url` — MoQ relay URL * - `prefix` — Base path prefix (default: "boy"). Derives prefix-game and prefix-viewer. - * - `prefix-game` — Path prefix for game broadcasts (default: "{prefix}/game") - * - `prefix-viewer` — Path prefix for viewer broadcasts (default: "{prefix}/viewer") + * - `prefix-game` — Path prefix for game broadcasts (default: `{prefix}/game`) + * - `prefix-viewer` — Path prefix for viewer broadcasts (default: `{prefix}/viewer`) */ export default class MoqBoy extends HTMLElement { - static observedAttributes = OBSERVED; + /** The attributes the browser reports changes to. */ + static observedAttributes: typeof OBSERVED = OBSERVED; /** The relay connection, shared by every game. */ readonly connection: Moq.Connection; @@ -69,6 +70,7 @@ export default class MoqBoy extends HTMLElement { this.#signals.run(this.#runDiscovery.bind(this)); } + /** Called by the browser when the element joins a document. */ connectedCallback() { this.#enabled.set(true); @@ -77,13 +79,15 @@ export default class MoqBoy extends HTMLElement { this.#dispose = render(() => , shadow); } + /** Called by the browser when the element leaves its document. */ disconnectedCallback() { this.#enabled.set(false); this.#dispose?.(); this.#dispose = undefined; } - attributeChangedCallback(name: Observed, _oldValue: string | null, newValue: string | null) { + /** Called by the browser when an observed attribute changes. */ + attributeChangedCallback(name: (typeof OBSERVED)[number], _oldValue: string | null, newValue: string | null) { switch (name) { case "url": this.connection.url.set(newValue ? new URL(newValue) : undefined); diff --git a/js/msf/api/index.api.md b/js/msf/api/index.api.md index 3c7e93f22ac..646ea72ea04 100644 --- a/js/msf/api/index.api.md +++ b/js/msf/api/index.api.md @@ -118,5 +118,4 @@ export const TrackSchema: z.ZodMiniObject<{ export const VERSION = "draft-01"; - ``` diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index f3c73cf771b..fa0b9784582 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -20,8 +20,8 @@ import * as z from 'zod/mini'; function accept(input: AcceptProps): Promise; interface AcceptProps { - consume?: Producer_5; - extensions?: Extensions.Extensions; + consume?: Producer_4; + extensions?: Extensions; implementation?: string; publish?: Consumer_5; transport: WebTransport; @@ -36,39 +36,22 @@ class Allocator implements Handle_2 { static unlimited(): Allocator; } -const ALPN: { - readonly DRAFT_14: "moq-00"; - readonly DRAFT_15: "moqt-15"; - readonly DRAFT_16: "moqt-16"; - readonly DRAFT_17: "moqt-17"; - readonly DRAFT_18: "moqt-18"; - readonly DRAFT_22: "moqt-22"; -}; - declare namespace Announce { export { Announce_2 as Announce, Consumer, - Event_2 as Event + Event_2 as Event, + Options } } +export { Announce } interface Announce_2 { - captures: Path_2.Pattern[] | undefined; - prefix: Path_2.Valid; + captures: Path.Pattern[] | undefined; + prefix: Path.Valid; route: Route; } -declare namespace Announce_3 { - export { - Announce_2 as Announce, - Event_2 as Event, - Options, - Producer_4 as Producer, - Consumer - } -} - declare namespace Auth { export { Duplicate, @@ -78,6 +61,7 @@ declare namespace Auth { Auth_2 as Auth } } +export { Auth } interface Auth_2 { close(): void; @@ -85,22 +69,6 @@ interface Auth_2 { readonly grant: Getter; } -declare namespace Auth_3 { - export { - - } -} - -declare namespace Auth_4 { - export { - Duplicate, - Handle, - Unsupported, - Grant, - Auth_2 as Auth - } -} - declare namespace Bandwidth { export { Allocator, @@ -108,6 +76,7 @@ declare namespace Bandwidth { Reservation } } +export { Bandwidth } type Bound = { included: number; @@ -125,15 +94,7 @@ declare namespace Broadcast { Consumer_4 as Consumer } } - -declare namespace Broadcast_2 { - export { - Tracks, - TracksEvent, - Producer_3 as Producer, - Consumer_4 as Consumer - } -} +export { Broadcast } interface CertificateHash { algorithm?: "sha-256"; @@ -142,31 +103,13 @@ interface CertificateHash { function certificateHash(cert: string | BufferSource): Promise>; -class ClientSetup { - constructor(input: { - versions: number[]; - parameters?: SetupOptions; - }); - static decode(r: Reader, version: IetfVersion): Promise; - encode(w: Writer, version: IetfVersion): Promise; - static id: number; - parameters: SetupOptions; - versions: number[]; -} - -declare namespace Cluster { - export { - - } -} - function connect(input: ConnectProps): Promise; export class Connection { constructor(props?: ConnectionProps); static readonly accept: typeof accept; - announced(scope?: Path_2.Pattern, options?: Announce_3.Options): Announce_3.Consumer; - readonly auth: Getter; + announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; + readonly auth: Getter; readonly bandwidth: Getter; static readonly certificateHash: typeof certificateHash; close(abort?: Error): void; @@ -175,7 +118,7 @@ export class Connection { enabled: Signal; readonly error: Getter; static readonly isWebTransportSupported: typeof isWebTransportSupported; - readonly origin: Getter; + readonly origin: Getter; readonly probe: Getter; stats(): Promise; readonly status: Getter; @@ -190,7 +133,7 @@ export namespace Connection { export type CertificateHash = CertificateHash; export type ConnectProps = ConnectProps; export type Established = Established; - export type Extensions = Extensions_2; + export type Extensions = Extensions; export type Goaway = GoawayProps; export type Probe = Probe; export type Props = ConnectionProps; @@ -203,11 +146,11 @@ export namespace Connection { } interface ConnectionProps { - consume?: Origin_3.Producer; + consume?: Origin_2.Producer; delay?: ReloadDelay; enabled?: boolean | Signal; goaway?: GoawayProps; - publish?: Origin_3.Consumer; + publish?: Origin_2.Consumer; share?: boolean; signal?: never; timeout?: Milli; @@ -219,9 +162,9 @@ interface ConnectionProps { } interface ConnectProps { - auth?: Auth_4.Handle; - consume?: Producer_5; - extensions?: Extensions.Extensions; + auth?: Auth.Handle; + consume?: Producer_4; + extensions?: Extensions; implementation?: string; publish?: Consumer_5; signal?: AbortSignal; @@ -279,18 +222,18 @@ class Consumer_4 { clone(): Consumer_4; close(): void; get closed(): GetPromise; - get epoch(): Epoch_2.Valid | undefined; - get path(): Path_2.Valid; + get epoch(): Epoch.Valid | undefined; + get path(): Path.Valid; protected shareState(): never; - track(name: string): track.Consumer; + track(name: string): Track.Consumer; tracks(): Tracks; } class Consumer_5 { - announced(scope?: Path_2.Pattern, options?: Announce_3.Options): Announce_3.Consumer; + announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; get closed(): GetPromise; get discovery(): Getter; - request(path: Path_2.Valid, options?: RequestOptions): Requesting; + request(path: Path.Valid, options?: RequestOptions): Requesting; } type Cost = bigint; @@ -299,22 +242,6 @@ const Cost: { zero: bigint; }; -class Cursor { - constructor(buffer: Uint8Array, version: StreamVersion); - bool(): boolean; - exact(size: number, decode: (c: Cursor) => T): T; - get offset(): number; - read(size: number): Uint8Array; - get remaining(): number; - string(): string; - u16(): number; - u53(): number; - u62(): bigint; - u8(): number; - varint(): U64; - readonly version: StreamVersion; -} - interface Datagram { payload: Uint8Array; sequence: number; @@ -348,7 +275,7 @@ class Duplicate extends Error { class Dynamic { close(): void; - readonly prefix: Path_2.Valid; + readonly prefix: Path.Valid; requested(): AsyncIterableIterator; get route(): Route; } @@ -373,21 +300,7 @@ declare namespace Epoch { Valid_2 as Valid } } - -declare namespace Epoch_2 { - export { - parse, - mint, - time, - Valid_2 as Valid - } -} - -declare namespace Epoch_3 { - export { - - } -} +export { Epoch } declare namespace Error_2 { export { @@ -405,11 +318,12 @@ declare namespace Error_2 { TooFarBehind } } +export { Error_2 as Error } interface Established { abort(): void; - announced(scope?: Path_2.Pattern, options?: Announce_3.Options): Announce_3.Consumer; - readonly auth: Auth_4.Handle; + announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; + readonly auth: Auth.Handle; close(): Promise; closed: Promise; readonly peerImplementation: Promise; @@ -424,16 +338,7 @@ type Event_2 = { kind: "start" | "update" | "restart" | "end"; } & Announce_2; -declare namespace Extensions { - export { - offered, - intoSetup, - Extensions_2 as Extensions, - Offered - } -} - -interface Extensions_2 { +interface Extensions { auth?: boolean; epoch?: boolean; solicit?: boolean; @@ -465,8 +370,8 @@ interface GoawayProps { interface Grant { expires?: number; - publish: Path_2.Patterns; - subscribe: Path_2.Patterns; + publish: Path.Patterns; + subscribe: Path.Patterns; } declare namespace Group { @@ -481,6 +386,7 @@ declare namespace Group { Consumer_2 as Consumer } } +export { Group } interface Groups { end?: Bound; @@ -510,27 +416,6 @@ type Hop = z.infer; const HopSchema: z.core.$ZodBranded, "Hop", "out">; -declare namespace Ietf { - export { - Auth_3 as Auth, - Cluster, - Epoch_3 as Epoch, - Setup, - ClientSetup, - ServerSetup, - initialMaxRequestId, - SetupOption, - REQUEST_WINDOW, - SetupOptions, - versionName, - Version, - ALPN, - IetfVersion - } -} - -type IetfVersion = typeof Version.DRAFT_14 | typeof Version.DRAFT_15 | typeof Version.DRAFT_16 | typeof Version.DRAFT_17 | typeof Version.DRAFT_18 | typeof Version.DRAFT_22; - export const IMPLEMENTATION: string; interface Info { @@ -547,10 +432,6 @@ interface Info_2 { function infoDefaults(info?: Partial): Info; -function initialMaxRequestId(peerClient: boolean, window?: bigint): bigint; - -function intoSetup(params: Ietf.SetupOptions, extensions: Offered, version: Ietf.IetfVersion): void; - function isAnonymous(route: Route): boolean; function isWebTransportSupported(): boolean; @@ -585,17 +466,6 @@ class NotFound extends Stream { }); } -type Offered = Required; - -function offered(extensions?: Extensions_2): Offered; - -interface OpenOptions { - sendOrder?: number; - timeout?: number | null; - version: StreamVersion; - waitUntilAvailable?: boolean; -} - interface Options { hidden?: boolean; } @@ -605,10 +475,10 @@ type Order = "ascending" | "descending"; class Ordered { close(abort?: Error): void; get closed(): GetPromise; - end(): Position_2 | undefined; - finished(): Promise; + end(): Position | undefined; + finished(): Promise; info(): Promise; - largest(): Promise; + largest(): Promise; readonly name: string; nextGroup(): Promise; readBool(): Promise; @@ -630,27 +500,11 @@ declare namespace Origin_2 { Cost, Hop, Route, + HopSchema, isAnonymous, Table, RequestOptions, - Producer_5 as Producer, - Requesting, - Consumer_5 as Consumer, - Dynamic, - Request_3 as Request, - Prepared - } -} - -declare namespace Origin_3 { - export { - Cost, - Hop, - Route, - isAnonymous, - Table, - RequestOptions, - Producer_5 as Producer, + Producer_4 as Producer, Requesting, Consumer_5 as Consumer, Dynamic, @@ -658,6 +512,7 @@ declare namespace Origin_3 { Prepared } } +export { Origin_2 as Origin } function parse(text: string): Valid_2; @@ -688,43 +543,18 @@ declare namespace Path { Specificity } } +export { Path } -declare namespace Path_2 { - export { - from, - parts, - decode, - encode, - hasPrefix, - stripPrefix, - join, - empty, - normalizeRelative, - resolve, - tryResolve, - relative, - Valid, - Relative, - MAX_PARTS, - compareSpecificity, - InvalidPattern, - Pattern, - Patterns, - Segment, - Specificity - } -} - -interface Position_2 { +interface Position { frame: number; group: number; } class Prepared { [Symbol.dispose](): void; - readonly broadcast: Broadcast_2.Producer; + readonly broadcast: Broadcast.Producer; close(): void; - publish(): Broadcast_2.Producer; + publish(): Broadcast.Producer; } interface Probe { @@ -741,10 +571,10 @@ class Producer { get closed(): GetPromise; demand(): Demand; dropGroups(start: number, end: number, error: Error): void; - finishAt(end: Position_2): void; + finishAt(end: Position): void; info(): Promise; insertDatagram(sequence: number, timestamp: Timestamp | undefined, payload: Uint8Array): void; - largest(): Position_2 | undefined; + largest(): Position | undefined; readonly name: string; get priority(): number; subscribe(options?: Subscription): Subscriber; @@ -775,31 +605,24 @@ class Producer_3 { close(): void; get closed(): GetPromise; consume(): Consumer_4; - createTrack(name: string, info?: Partial): track.Producer; + createTrack(name: string, info?: Partial): Track.Producer; removeTrack(name: string): void; get route(): Route | undefined; - track(name: string): track.Consumer; + track(name: string): Track.Consumer; unannounce(): void; } -class Producer_4 { - append(event: Event_2): void; - close(abort?: Error): void; - get closed(): GetPromise; - consume(): Consumer; -} - -class Producer_5 implements Table { +class Producer_4 implements Table { constructor(); - announced(scope?: Path_2.Pattern, options?: Announce_3.Options): Announce_3.Consumer; + announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; close(abort?: Error): void; get closed(): GetPromise; consume(): Consumer_5; - createBroadcast(path: Path_2.Valid): Broadcast_2.Producer; + createBroadcast(path: Path.Valid): Broadcast.Producer; get discovery(): Getter; - dynamic(prefix: Path_2.Valid): Dynamic; - request(path: Path_2.Valid, options?: RequestOptions): Requesting; - scope(root: Path_2.Valid, patterns: Path_2.Patterns): Producer_5; + dynamic(prefix: Path.Valid): Dynamic; + request(path: Path.Valid, options?: RequestOptions): Requesting; + scope(root: Path.Valid, patterns: Path.Patterns): Producer_4; } class ProtocolViolation extends Error { @@ -810,29 +633,6 @@ class ProtocolViolation extends Error { readonly code: SessionCode; } -class Reader { - constructor(stream: ReadableStream, buffer: Uint8Array | undefined, version: StreamVersion); - constructor(stream: undefined, buffer: Uint8Array, version: StreamVersion); - bool(): Promise; - get closed(): Promise; - decode(decode: (c: Cursor) => T): Promise; - decodeMaybe(decode: (c: Cursor) => T): Promise; - discard(): Promise; - done(): Promise; - peekU62(): Promise; - read(size: number): Promise; - readAll(): Promise; - stop(reason: unknown): void; - string(): Promise; - tryDecode>(decode: (c: Cursor) => T): T | undefined; - u16(): Promise; - u53(): Promise; - u62(): Promise; - u8(): Promise; - varint(): Promise; - version: StreamVersion; -} - interface ReadOptions { from?: number; } @@ -870,23 +670,21 @@ class Request_2 { } class Request_3 { - readonly path: Path_2.Valid; - prepare(epoch: Epoch_2.Valid): Prepared; + readonly path: Path.Valid; + prepare(epoch: Epoch.Valid): Prepared; reject(err: Error): void; } -const REQUEST_WINDOW = 240000n; - class Requesting { - readonly active: Getter; + readonly active: Getter; close(): void; readonly closed: GetPromise; - readonly path: Path_2.Valid; + readonly path: Path.Valid; } interface RequestOptions { announced?: boolean; - epoch?: Epoch_2.Valid; + epoch?: Epoch.Valid; } class Reservation implements Disposable { @@ -902,32 +700,20 @@ function resolve(base: Valid, rel: Relative): Valid; interface Route { auth?: Auth_2; cost: Cost; - epoch?: Epoch_2.Valid; + epoch?: Epoch.Valid; hops: Hop[]; } const Route: { default: Route; normalize(route?: Route | { - epoch?: Epoch_2.Valid; + epoch?: Epoch.Valid; hops?: readonly Hop[]; cost?: Cost; auth?: Auth_2; }): Route; }; -class ServerSetup { - constructor(input: { - version: number; - parameters?: SetupOptions; - }); - static decode(r: Reader, version: IetfVersion): Promise; - encode(w: Writer, version: IetfVersion): Promise; - static id: number; - parameters: SetupOptions; - version: number; -} - class Session extends Error { constructor(code: SessionCode, options?: { cause?: unknown; @@ -963,48 +749,6 @@ export const SessionCode: ((code: number) => SessionCode) & { readonly TooManyRequestUpdates: SessionCode; }; -class Setup { - constructor(input?: { - parameters?: SetupOptions; - }); - static decode(r: Reader, version: IetfVersion): Promise; - encode(w: Writer, version: IetfVersion): Promise; - static id: number; - parameters: SetupOptions; -} - -const SetupOption: { - readonly Path: 1n; - readonly MaxRequestId: 2n; - readonly AuthorizationToken: 3n; - readonly MaxAuthTokenCacheSize: 4n; - readonly Authority: 5n; - readonly Implementation: 7n; - readonly HopId: 0x40b54n; - readonly RelayCost: 0x40b56n; - readonly Solicit: 0x40b5an; - readonly Hidden: 0x40b5cn; - readonly MaxAge: 0x915c4n; - readonly Auth: 0x40b70n; - readonly ActiveCount: 0x40b64n; - readonly Epoch: 0x40b68n; -}; - -class SetupOptions { - constructor(); - bytes: Map; - static decode(r: Reader, version: IetfVersion): Promise; - encode(w: Writer, version: IetfVersion): Promise; - getBytes(id: bigint): Uint8Array | undefined; - getVarint(id: bigint): bigint | undefined; - removeBytes(id: bigint): boolean; - removeVarint(id: bigint): boolean; - setBytes(id: bigint, value: Uint8Array): void; - setVarint(id: bigint, value: bigint): void; - get size(): number; - vars: Map; -} - export { Signals } function size(v: number): number; @@ -1064,17 +808,15 @@ interface StreamOptions { reason?: string; } -type StreamVersion = IetfVersion | Version_2; - function stripPrefix(prefix: Valid, path: Valid): Valid | null; class Subscriber { close(abort?: Error): void; get closed(): GetPromise; - end(): Position_2 | undefined; - finished(): Promise; + end(): Position | undefined; + finished(): Promise; info(): Promise; - largest(): Promise; + largest(): Promise; readonly name: string; ordered(): Ordered; recvDatagram(): Promise; @@ -1093,12 +835,12 @@ interface Subscription { } interface Table { - announced(scope?: Path_2.Pattern, options?: Announce_3.Options): Announce_3.Consumer; + announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; readonly closed: GetPromise; - createBroadcast(path: Path_2.Valid): Broadcast_2.Producer; + createBroadcast(path: Path.Valid): Broadcast.Producer; readonly discovery: Getter; - dynamic(prefix: Path_2.Valid): Dynamic; - request(path: Path_2.Valid, options?: RequestOptions): Requesting; + dynamic(prefix: Path.Valid): Dynamic; + request(path: Path.Valid, options?: RequestOptions): Requesting; } declare namespace Time { @@ -1107,6 +849,7 @@ declare namespace Time { Timestamp } } +export { Time } function time(epoch: Valid_2): Date; @@ -1155,28 +898,7 @@ declare namespace Track { export { infoDefaults, Datagram, - Position_2 as Position, - Info, - Bound, - Groups, - Subscription, - Order, - Request_2 as Request, - Staged, - FetchGroupOptions, - Consumer_3 as Consumer, - Demand, - Producer, - Subscriber, - Ordered - } -} - -declare namespace track { - export { - infoDefaults, - Datagram, - Position_2 as Position, + Position, Info, Bound, Groups, @@ -1192,6 +914,7 @@ declare namespace track { Ordered } } +export { Track } class Tracks { [Symbol.asyncIterator](): AsyncGenerator; @@ -1202,7 +925,7 @@ class Tracks { type TracksEvent = { kind: "added"; name: string; - info: track.Info; + info: Track.Info; } | { kind: "synced"; } | { @@ -1215,28 +938,8 @@ type TracksEvent = { type Transport = "webtransport" | "websocket" | "webrtc"; -interface TryOpenOptions extends OpenOptions { - cancel: Promise; -} - function tryResolve(base: Valid, rel: Relative): Valid | undefined; -class U64 { - constructor(hi: number, lo: number); - add(delta: number): U64; - compare(other: U64): number; - equals(other: U64): boolean; - static fromBigInt(v: bigint): U64; - static fromNumber(v: number): U64; - readonly hi: number; - readonly lo: number; - static readonly MAX: U64; - toBigInt(): bigint; - toNumber(): number; - toString(): string; - static readonly ZERO: U64; -} - class Unsupported extends Error { constructor(message?: string); readonly code: SessionCode; @@ -1267,32 +970,7 @@ declare namespace Varint { MAX_U53 } } - -const Version: { - readonly DRAFT_07: 4278190087; - readonly DRAFT_14: 4278190094; - readonly DRAFT_15: 4278190095; - readonly DRAFT_16: 4278190096; - readonly DRAFT_17: 4278190097; - readonly DRAFT_18: 4278190098; - readonly DRAFT_22: 4278190102; -}; - -type Version = (typeof Version)[keyof typeof Version]; - -const Version_2: { - readonly DRAFT_01: 4279086337; - readonly DRAFT_02: 4279086338; - readonly DRAFT_03: 4279086339; - readonly DRAFT_04: 4279086340; - readonly DRAFT_05: 4279086341; - readonly DRAFT_06: 4279086342; - readonly DRAFT_07: 4279086343; -}; - -type Version_2 = (typeof Version_2)[keyof typeof Version_2]; - -function versionName(v: Version): string; +export { Varint } interface WebSocketProps { delay?: Milli; @@ -1305,26 +983,4 @@ interface WebTransportProps extends Omit, version: StreamVersion); - bool(v: boolean): Promise; - close(): void; - get closed(): Promise; - static collect(version: StreamVersion, f: (w: Writer) => Promise): Promise; - i32(v: number): Promise; - static open(quic: WebTransport, options: OpenOptions): Promise; - reset(reason: unknown): void; - setPriority(sendOrder: number): void; - string(str: string): Promise; - static tryOpen(quic: WebTransport, options: TryOpenOptions): Promise; - u16(v: number): Promise; - u53(v: number): Promise; - u62(v: bigint): Promise; - u8(v: number): Promise; - varint(v: U64): Promise; - version: StreamVersion; - write(v: Uint8Array): Promise; -} - - ``` diff --git a/js/net/api/zod.api.md b/js/net/api/zod.api.md index 953b970143b..a7ddeb3fb3a 100644 --- a/js/net/api/zod.api.md +++ b/js/net/api/zod.api.md @@ -116,10 +116,10 @@ type Order = "ascending" | "descending"; class Ordered { close(abort?: Error): void; get closed(): GetPromise; - end(): Position_2 | undefined; - finished(): Promise; + end(): Position | undefined; + finished(): Promise; info(): Promise; - largest(): Promise; + largest(): Promise; readonly name: string; nextGroup(): Promise; readBool(): Promise; @@ -136,7 +136,7 @@ class Ordered { withRange(groups: Groups): this; } -interface Position_2 { +interface Position { frame: number; group: number; } @@ -150,10 +150,10 @@ class Producer { get closed(): GetPromise; demand(): Demand; dropGroups(start: number, end: number, error: Error): void; - finishAt(end: Position_2): void; + finishAt(end: Position): void; info(): Promise; insertDatagram(sequence: number, timestamp: Timestamp | undefined, payload: Uint8Array): void; - largest(): Position_2 | undefined; + largest(): Position | undefined; readonly name: string; get priority(): number; subscribe(options?: Subscription): Subscriber; @@ -198,10 +198,10 @@ class Staged { class Subscriber { close(abort?: Error): void; get closed(): GetPromise; - end(): Position_2 | undefined; - finished(): Promise; + end(): Position | undefined; + finished(): Promise; info(): Promise; - largest(): Promise; + largest(): Promise; readonly name: string; ordered(): Ordered; recvDatagram(): Promise; @@ -247,7 +247,7 @@ declare namespace track { export { infoDefaults, Datagram, - Position_2 as Position, + Position, Info, Bound, Groups, @@ -264,5 +264,4 @@ declare namespace track { } } - ``` diff --git a/js/net/src/announce.ts b/js/net/src/announce.ts index ebc2adaf251..9cfe489c6d8 100644 --- a/js/net/src/announce.ts +++ b/js/net/src/announce.ts @@ -3,4 +3,4 @@ * * @module */ -export { type Announce, Consumer, type Event } from "./announced.ts"; +export { type Announce, Consumer, type Event, type Options } from "./announced.ts"; diff --git a/js/net/src/broadcast.ts b/js/net/src/broadcast.ts index 07a452d170e..c23cf9b7733 100644 --- a/js/net/src/broadcast.ts +++ b/js/net/src/broadcast.ts @@ -637,8 +637,10 @@ export class Consumer { return new Consumer(this.shareState()); } - // Hand this consumer's backing state and path to a clone. Opaque (`never`) so the state type - // stays unexported; a subclass passes it straight back into its own `super(...)`. + /** + * This consumer's backing state and path, for a clone. Opaque (`never`) so the state type + * stays unexported; a subclass passes it straight back into its own `super(...)`. + */ protected shareState(): never { return { state: this.#state, diff --git a/js/net/src/connection/accept.ts b/js/net/src/connection/accept.ts index 67e1c554ea7..35a85a7db74 100644 --- a/js/net/src/connection/accept.ts +++ b/js/net/src/connection/accept.ts @@ -5,6 +5,7 @@ import * as Lite from "../lite/index.ts"; import type { Consumer as OriginConsumer, Producer as OriginProducer } from "../origin.ts"; import { Stream } from "../stream.ts"; import type { Established } from "./established.ts"; +import type { Extensions as ExtensionsType } from "./extensions.ts"; import * as Extensions from "./extensions.ts"; import { DISCOVERY_REMOVED, forwardAnnounced } from "./forward.ts"; import { exchangeSetup, legacyPeerImplementation } from "./handshake.ts"; @@ -32,7 +33,7 @@ export interface AcceptProps { consume?: OriginProducer; /** The moq-transport extensions to offer, each on unless set to `false`. */ - extensions?: Extensions.Extensions; + extensions?: ExtensionsType; /** The implementation this side advertises in SETUP; see the `implementation` connect option. */ implementation?: string; diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 9d16f8b33cb..96e4f23de4d 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -15,6 +15,7 @@ import { redact } from "../util/log.ts"; import { after } from "../util/timer.ts"; import { isWebTransportSupported } from "./browser.ts"; import type { Established } from "./established.ts"; +import type { Extensions as ExtensionsType } from "./extensions.ts"; import * as Extensions from "./extensions.ts"; import { DISCOVERY_REMOVED, forwardAnnounced } from "./forward.ts"; import { exchangeSetup, legacyPeerImplementation } from "./handshake.ts"; @@ -216,7 +217,7 @@ export interface ConnectProps { consume?: OriginProducer; /** The moq-transport extensions to offer, each on unless set to `false`. */ - extensions?: Extensions.Extensions; + extensions?: ExtensionsType; /** * Build the session on `auth`, so it presents every token the handle holds and a route diff --git a/js/net/src/connection/established.ts b/js/net/src/connection/established.ts index 89c09ba01b8..1e25985de45 100644 --- a/js/net/src/connection/established.ts +++ b/js/net/src/connection/established.ts @@ -1,5 +1,5 @@ import type { Getter } from "@moq/signals"; -import type * as announce from "../announced.ts"; +import type * as announce from "../announce.ts"; import type * as Auth from "../auth.ts"; import type * as Path from "../path.ts"; import type { Probe, Stats } from "./stats.ts"; diff --git a/js/net/src/connection/pool.ts b/js/net/src/connection/pool.ts index e6f09fe9b01..05021aa2892 100644 --- a/js/net/src/connection/pool.ts +++ b/js/net/src/connection/pool.ts @@ -6,7 +6,8 @@ import { Milli, Nano } from "@moq/clock"; import { Effect, type GetPromise, type Getter, Once, Signal } from "@moq/signals"; -import * as Announce from "../announced.ts"; +import type * as Announce from "../announce.ts"; +import { Producer as AnnounceProducer } from "../announced.ts"; import type * as Auth from "../auth.ts"; import type { Handle } from "../bandwidth.ts"; import * as Origin from "../origin.ts"; @@ -335,7 +336,7 @@ export class Connection { * the old relay's origin, then the new one's arrivals stream in. */ announced(scope: Path.Pattern = Path.Pattern.all(), options?: Announce.Options): Announce.Consumer { - const producer = new Announce.Producer(); + const producer = new AnnounceProducer(); const consumer = producer.consume(); // A child of this handle's scope rather than a standalone Effect it merely cleans up diff --git a/js/net/src/hop.ts b/js/net/src/hop.ts index 4cd49d41d13..75f4047572e 100644 --- a/js/net/src/hop.ts +++ b/js/net/src/hop.ts @@ -15,7 +15,7 @@ import { isLeadingOnes, type StreamVersion } from "./stream.ts"; /** * One relay's identity in a broadcast's hop chain: any 64-bit id. * - * Names a *hop*, not an {@link !Origin | Origin} routing table: this is the id a relay + * Names a *hop*, not an `Origin` routing table: this is the id a relay * stamps into a chain as an announcement passes through, so a receiver can spot its own * id and reject a loop. The SETUP parameter that carries it session-wide is `Hop` too. * diff --git a/js/net/src/origin.ts b/js/net/src/origin.ts index 1d331596015..3b081f460b5 100644 --- a/js/net/src/origin.ts +++ b/js/net/src/origin.ts @@ -11,6 +11,7 @@ * @module */ import { Derived, type Dispose, type GetPromise, type Getter, Once, race, Signal } from "@moq/signals"; +import type * as Announce from "./announce.ts"; import * as announce from "./announced.ts"; import * as broadcast from "./broadcast.ts"; import type * as Epoch from "./epoch.ts"; @@ -39,7 +40,7 @@ import { } from "./wire.ts"; export type { Cost, Hop, Route } from "./hop.ts"; -export { isAnonymous } from "./hop.ts"; +export { HopSchema, isAnonymous } from "./hop.ts"; /** The rooted permissions shared by a handle and every route it inserts. */ class Scope { @@ -1063,7 +1064,7 @@ export interface Table { request(path: Path.Valid, options?: RequestOptions): Requesting; /** The available broadcasts under `scope`, as a live stream; see {@link Consumer.announced}. */ - announced(scope?: Path.Pattern, options?: announce.Options): announce.Consumer; + announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; /** Advertise a prefix and serve requests under it; see {@link Producer.dynamic}. */ dynamic(prefix: Path.Valid): Dynamic; @@ -1464,7 +1465,7 @@ export class Producer implements Table { } /** The available broadcasts under `scope`, as a live stream; see {@link Consumer.announced}. */ - announced(scope?: Path.Pattern, options?: announce.Options): announce.Consumer { + announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer { return this.#reader.announced(scope, options); } @@ -1956,11 +1957,11 @@ export class Consumer { * Any pattern is accepted. A local broadcast appears once it announces, exactly as a * peer sees it. A dynamic or received route announces the prefix it covers when its * subtree overlaps the scope. The stream ends when the origin closes or the consumer is - * closed. Hidden routes are left out unless `options.hidden` opts in (see {@link announce.Options}). + * closed. Hidden routes are left out unless `options.hidden` opts in (see {@link Announce.Options}). * While open, it watches the scope's literal head: a `consume` session asks its peer for * announcements there. */ - announced(scope: Path.Pattern = Path.Pattern.all(), options?: announce.Options): announce.Consumer { + announced(scope: Path.Pattern = Path.Pattern.all(), options?: Announce.Options): Announce.Consumer { const producer = new announce.Producer(); const patterns = this.#scope.patterns(scope); void producer.closed.then(this.#state.watch([...patterns].map(scopeHead))); diff --git a/js/pattern/api/index.api.md b/js/pattern/api/index.api.md index 0b82ad97195..f20d705e4a0 100644 --- a/js/pattern/api/index.api.md +++ b/js/pattern/api/index.api.md @@ -95,5 +95,4 @@ export interface Specificity { readonly wildcards: number; } - ``` diff --git a/js/pattern/src/index.ts b/js/pattern/src/index.ts index ddb76c549a5..3d736b618f9 100644 --- a/js/pattern/src/index.ts +++ b/js/pattern/src/index.ts @@ -81,6 +81,7 @@ export class InvalidPattern extends Error { } } +/** Types for {@link InvalidPattern}. */ export namespace InvalidPattern { /** Why a string or a segment list is not a valid {@link Pattern}. */ export type Code = diff --git a/js/publish/api/element.api.md b/js/publish/api/element.api.md index eaf1a59e8cc..920b6556ff3 100644 --- a/js/publish/api/element.api.md +++ b/js/publish/api/element.api.md @@ -33,6 +33,7 @@ declare namespace Audio_2 { Codec, Encoder_2 as Encoder, EncoderInput_2 as EncoderInput, + EncoderOutput_2 as EncoderOutput, EncoderProps_2 as EncoderProps, Opus, OpusConfig, @@ -42,6 +43,7 @@ declare namespace Audio_2 { Format, CaptureInput_2 as CaptureInput, CaptureProps, + CaptureOutput_2 as CaptureOutput, Capture_2 as Capture, isSampleSource, sourceKind, @@ -358,7 +360,7 @@ class MoqPublish extends HTMLElement { constructor(); get announce(): AnnounceMode; set announce(value: AnnounceMode); - attributeChangedCallback(name: Observed, oldValue: string | null, newValue: string | null): void; + attributeChangedCallback(name: (typeof OBSERVED)[number], oldValue: string | null, newValue: string | null): void; audio: Audio_2.Encoder; get backend(): Preview.Backend; set backend(value: Preview.Backend); @@ -380,7 +382,7 @@ class MoqPublish extends HTMLElement { set muted(value: boolean); get name(): Moq.Path.Valid; set name(value: string | Moq.Path.Valid); - static observedAttributes: readonly ["url", "versions", "name", "muted", "invisible", "source", "preview", "backend", "announce"]; + static observedAttributes: typeof OBSERVED; get preview(): Preview.Mode; set preview(value: Preview.Mode); readonly signals: Effect; @@ -405,8 +407,6 @@ function normalizeSource_2(source: StreamTrack_2 | SourceConfig_2): SourceConfig const OBSERVED: readonly ["url", "versions", "name", "muted", "invisible", "source", "preview", "backend", "announce"]; -type Observed = (typeof OBSERVED)[number]; - type Opus = "opus" | OpusConfig; type OpusConfig = { @@ -427,6 +427,7 @@ declare namespace Preview { Renderer, TranscodeInput, TranscodeProps, + TranscodeOutput, Transcode } } @@ -506,17 +507,22 @@ declare namespace Source_3 { export { CameraInput, CameraProps, + CameraOutput, Camera, DeviceProps, + DeviceOutput, Device, FileInput, FileProps, + FileOutput, File_2 as File, MicrophoneInput, MicrophoneProps, + MicrophoneOutput, Microphone, ScreenInput, ScreenProps, + ScreenOutput, Screen_2 as Screen, Media } @@ -604,11 +610,13 @@ declare namespace Video { export { Rendition, CaptureInput, + CaptureOutput, Capture, Stats, Config, EncoderInput, EncoderProps, + EncoderOutput, Encoder, normalizeSource, isStreamTrack, @@ -621,5 +629,4 @@ declare namespace Video { } } - ``` diff --git a/js/publish/api/index.api.md b/js/publish/api/index.api.md index 43d1cad25f5..4233c29a977 100644 --- a/js/publish/api/index.api.md +++ b/js/publish/api/index.api.md @@ -36,6 +36,7 @@ declare namespace Audio_2 { Codec, Encoder, EncoderInput, + EncoderOutput, EncoderProps, Opus, OpusConfig, @@ -45,6 +46,7 @@ declare namespace Audio_2 { Format, CaptureInput, CaptureProps, + CaptureOutput, Capture, isSampleSource, sourceKind, @@ -59,37 +61,7 @@ declare namespace Audio_2 { TrackSettings } } - -declare namespace Audio_3 { - export { - Aac, - AacConfig, - Codec, - Encoder, - EncoderInput, - EncoderProps, - Opus, - OpusConfig, - Stats, - Rendition_2 as Rendition, - AudioFrame, - Format, - CaptureInput, - CaptureProps, - Capture, - isSampleSource, - sourceKind, - normalizeSource, - Kind_2 as Kind, - CodecMime, - Source_2 as Source, - SourceConfig, - SampleSource, - Constraints, - StreamTrack, - TrackSettings - } -} +export { Audio_2 as Audio } interface AudioFrame { channels: Float32Array[]; @@ -126,8 +98,8 @@ export type BroadcastInput = { class Camera { constructor(props?: CameraProps); close(): void; - constraints: Signal; - static readonly DEFAULT_CONSTRAINTS: Encoder_2.Constraints; + constraints: Signal; + static readonly DEFAULT_CONSTRAINTS: Video.Constraints; readonly device: Device<"video">; readonly in: Readonlys; readonly out: Readonlys; @@ -144,7 +116,7 @@ type CameraOutput = { }; interface CameraProps extends Inputs { - constraints?: Encoder_2.Constraints | Signal; + constraints?: Video.Constraints | Signal; device?: DeviceProps; } @@ -258,28 +230,7 @@ class Encoder { volume: Signal; } -declare namespace Encoder_2 { - export { - Rendition_3 as Rendition, - CaptureInput_2 as CaptureInput, - Capture_2 as Capture, - Stats_2 as Stats, - Config, - EncoderInput_2 as EncoderInput, - EncoderProps_2 as EncoderProps, - Encoder_3 as Encoder, - normalizeSource_2 as normalizeSource, - isStreamTrack, - Source_3 as Source, - SourceConfig_2 as SourceConfig, - FrameSource, - StreamTrack_2 as StreamTrack, - TrackSettings_2 as TrackSettings, - Constraints_2 as Constraints - } -} - -class Encoder_3 { +class Encoder_2 { constructor(name: string, props?: EncoderProps_2); get capture(): Capture_2 | undefined; close(): void; @@ -330,13 +281,13 @@ type EncoderProps_2 = Inputs & { config?: Config | Signal; }; -class Fanout { +export class Fanout { constructor(source: ReadableStream, props?: FanoutProps); close(): void; subscribe(effect: Effect, queue?: number): ReadableStream; } -interface FanoutProps { +export interface FanoutProps { clone?: (value: T) => T; queue?: number; release?: (value: T) => void; @@ -384,14 +335,14 @@ export type Kind = "video" | "audio" | "text"; type Kind_2 = "voice" | "music" | "auto"; type Media = { - video?: Encoder_2.Source; - audio?: Audio_3.Source; + video?: Video.Source; + audio?: Audio_2.Source; }; class Microphone { constructor(props?: MicrophoneProps); close(): void; - constraints: Signal; + constraints: Signal; readonly device: Device<"audio">; readonly in: Readonlys; readonly out: Readonlys; @@ -407,7 +358,7 @@ type MicrophoneOutput = { }; interface MicrophoneProps extends Inputs { - constraints?: Audio_3.Constraints | Signal; + constraints?: Audio_2.Constraints | Signal; device?: DeviceProps; } @@ -439,9 +390,11 @@ declare namespace Preview { Renderer, TranscodeInput, TranscodeProps, + TranscodeOutput, Transcode } } +export { Preview } class Renderer { constructor(props?: RendererProps); @@ -461,7 +414,7 @@ type RendererInput = { } | undefined>; flip: Getter; rotation: Getter; - encoder: Getter; + encoder: Getter; mode: Getter; enabled: Getter; backend: Getter; @@ -490,11 +443,11 @@ interface SampleSource { class Screen_2 { constructor(props?: ScreenProps); - audio: Signal; + audio: Signal; close(): void; readonly in: Readonlys; readonly out: Readonlys; - video: Signal; + video: Signal; } type ScreenInput = { @@ -506,8 +459,8 @@ type ScreenOutput = { }; interface ScreenProps extends Inputs { - audio?: Audio_3.Constraints | boolean | Signal; - video?: Encoder_2.Constraints | boolean | Signal; + audio?: Audio_2.Constraints | boolean | Signal; + video?: Video.Constraints | boolean | Signal; } export { Signals } @@ -516,21 +469,27 @@ declare namespace Source { export { CameraInput, CameraProps, + CameraOutput, Camera, DeviceProps, + DeviceOutput, Device, FileInput, FileProps, + FileOutput, File_2 as File, MicrophoneInput, MicrophoneProps, + MicrophoneOutput, Microphone, ScreenInput, ScreenProps, + ScreenOutput, Screen_2 as Screen, Media } } +export { Source } type Source_2 = StreamTrack | SourceConfig | SampleSource; @@ -603,7 +562,7 @@ class Transcode { type TranscodeInput = { source: Getter | undefined>; config: Getter; - settings: Getter; + settings: Getter; }; type TranscodeOutput = { @@ -616,12 +575,14 @@ declare namespace Video { export { Rendition_3 as Rendition, CaptureInput_2 as CaptureInput, + CaptureOutput_2 as CaptureOutput, Capture_2 as Capture, Stats_2 as Stats, Config, EncoderInput_2 as EncoderInput, EncoderProps_2 as EncoderProps, - Encoder_3 as Encoder, + EncoderOutput_2 as EncoderOutput, + Encoder_2 as Encoder, normalizeSource_2 as normalizeSource, isStreamTrack, Source_3 as Source, @@ -632,6 +593,6 @@ declare namespace Video { Constraints_2 as Constraints } } - +export { Video } ``` diff --git a/js/publish/api/support-element.api.md b/js/publish/api/support-element.api.md index d391cbdab1a..fcc7e89a891 100644 --- a/js/publish/api/support-element.api.md +++ b/js/publish/api/support-element.api.md @@ -15,5 +15,4 @@ export default MoqPublishSupport; export { Show } - ``` diff --git a/js/publish/api/support.api.md b/js/publish/api/support.api.md index fed8c64abbe..3f67624436b 100644 --- a/js/publish/api/support.api.md +++ b/js/publish/api/support.api.md @@ -39,5 +39,4 @@ export type Video = { av1: Codec; }; - ``` diff --git a/js/publish/api/ui.api.md b/js/publish/api/ui.api.md index 788ca2b3e62..28418227e5a 100644 --- a/js/publish/api/ui.api.md +++ b/js/publish/api/ui.api.md @@ -11,5 +11,4 @@ class MoqPublishUi extends HTMLElement { } export default MoqPublishUi; - ``` diff --git a/js/publish/src/audio/capture.ts b/js/publish/src/audio/capture.ts index 3f377628ccb..ce319c884c4 100644 --- a/js/publish/src/audio/capture.ts +++ b/js/publish/src/audio/capture.ts @@ -62,7 +62,8 @@ export type CaptureProps = Inputs & { channelCount?: number | Signal; }; -type CaptureOutput = { +/** Signals the capture derives. */ +export type CaptureOutput = { // The PCM to encode, replaced whenever the source changes. Subscribe for a stream of your own: // several renditions share one capture, and each needs every frame rather than the newest. frames: Signal | undefined>; diff --git a/js/publish/src/audio/encoder.ts b/js/publish/src/audio/encoder.ts index 0342be1de9a..cd7f3408980 100644 --- a/js/publish/src/audio/encoder.ts +++ b/js/publish/src/audio/encoder.ts @@ -115,7 +115,8 @@ export type EncoderProps = Inputs & { groupDuration?: Milli | Signal; }; -type EncoderOutput = { +/** Signals the encoder derives. */ +export type EncoderOutput = { /** The encoder failure, cleared only by a new capture source or format, or new encoder settings. */ error: Signal; // The catalog config published for this rendition, `enabled: false` while disabled, or undefined diff --git a/js/publish/src/audio/index.ts b/js/publish/src/audio/index.ts index b0e9654455a..837ad3d250f 100644 --- a/js/publish/src/audio/index.ts +++ b/js/publish/src/audio/index.ts @@ -8,6 +8,7 @@ export { type Codec, Encoder, type EncoderInput, + type EncoderOutput, type EncoderProps, type Opus, type OpusConfig, diff --git a/js/publish/src/audio/types.ts b/js/publish/src/audio/types.ts index a05e3a46d13..0c2252acdd6 100644 --- a/js/publish/src/audio/types.ts +++ b/js/publish/src/audio/types.ts @@ -16,13 +16,15 @@ export type CodecMime = "opus" | "aac"; /** * Where audio comes from: a live capture track, or a stream of samples we decoded ourselves. * A bare track is accepted for backwards compatibility and treated as kind="auto". - * Prefer the { track, kind } object form so the encoder can pick the right Opus settings. + * Prefer the `{ track, kind }` object form so the encoder can pick the right Opus settings. */ export type Source = StreamTrack | SourceConfig | SampleSource; /** A capture track plus the kind of audio it carries. */ export interface SourceConfig { + /** The track to capture. */ track: StreamTrack; + /** What kind of audio the track carries, driving the Opus defaults. */ kind: Kind; } @@ -72,8 +74,11 @@ export type Constraints = Omit< /** Stronger typing for the MediaStreamTrack interface. */ export interface StreamTrack extends MediaStreamTrack { + /** Always audio. */ kind: "audio"; + /** A new track on the same source, with its own settings and lifetime. */ clone(): StreamTrack; + /** The settings the track currently runs with. */ getSettings(): TrackSettings; } @@ -82,16 +87,24 @@ export interface StreamTrack extends MediaStreamTrack { * This is a fork of the MediaTrackSettings interface with properties required for audio or video. */ export interface TrackSettings { + /** The capture device. */ deviceId: string; + /** The physical device the capture device belongs to. */ groupId: string; // Seems to be available on all browsers. + /** The sample rate in Hz. */ sampleRate: number; // The rest is optional unfortunately. + /** Whether automatic gain control is on. */ autoGainControl?: boolean; - channelCount?: number; // ugh Safari why + /** The channel count; Safari omits it. */ + channelCount?: number; + /** Whether echo cancellation is on. */ echoCancellation?: boolean; + /** Whether noise suppression is on. */ noiseSuppression?: boolean; + /** The bits per sample. */ sampleSize?: number; } diff --git a/js/publish/src/element.ts b/js/publish/src/element.ts index 356e6f5930c..d41d9a25f6f 100644 --- a/js/publish/src/element.ts +++ b/js/publish/src/element.ts @@ -35,8 +35,8 @@ function parseVersions(value: string | null): string[] | undefined { return versions?.length ? versions : undefined; } +/** The attributes the element observes. */ const OBSERVED = ["url", "versions", "name", "muted", "invisible", "source", "preview", "backend", "announce"] as const; -type Observed = (typeof OBSERVED)[number]; /** The built-in capture sources selectable via the `source` attribute. */ export type SourceType = "camera" | "screen" | "file"; @@ -100,7 +100,8 @@ const cleanup = new FinalizationRegistry((signals) => signals.close()); /** The `` element: captures a source and publishes it as a broadcast. */ export default class MoqPublish extends HTMLElement { - static observedAttributes = OBSERVED; + /** The attributes the browser reports changes to. */ + static observedAttributes: typeof OBSERVED = OBSERVED; /** * The mutable user controls. As the top of the tree, this element owns the writable Signals @@ -326,15 +327,18 @@ export default class MoqPublish extends HTMLElement { this.signals.run(this.#runSource.bind(this)); } + /** Called by the browser when the element joins a document. */ connectedCallback() { this.#enabled.set(true); } + /** Called by the browser when the element leaves its document. */ disconnectedCallback() { this.#enabled.set(false); } - attributeChangedCallback(name: Observed, oldValue: string | null, newValue: string | null) { + /** Called by the browser when an observed attribute changes. */ + attributeChangedCallback(name: (typeof OBSERVED)[number], oldValue: string | null, newValue: string | null) { if (oldValue === newValue) return; if (name === "url") { diff --git a/js/publish/src/index.ts b/js/publish/src/index.ts index 0733aba7cfb..3e31c8878af 100644 --- a/js/publish/src/index.ts +++ b/js/publish/src/index.ts @@ -20,6 +20,7 @@ export { assets } from "./assets"; export * as Audio from "./audio"; export * from "./broadcast"; export * from "./catalog"; +export { Fanout, type FanoutProps } from "./fanout"; /** The local canvas preview. */ export * as Preview from "./preview"; export * from "./rendition"; diff --git a/js/publish/src/preview.ts b/js/publish/src/preview.ts index 0e9ec17686b..3b456f33cea 100644 --- a/js/publish/src/preview.ts +++ b/js/publish/src/preview.ts @@ -198,7 +198,8 @@ export type TranscodeInput = { /** Constructor options for {@link Transcode}. */ export type TranscodeProps = Inputs; -type TranscodeOutput = { +/** Signals the transcoder derives. */ +export type TranscodeOutput = { // The decoded output frame. Owned here, closed on each update and on close(). frame: Signal; }; diff --git a/js/publish/src/source/camera.ts b/js/publish/src/source/camera.ts index 3dd416807ab..d79dd29fe29 100644 --- a/js/publish/src/source/camera.ts +++ b/js/publish/src/source/camera.ts @@ -18,7 +18,8 @@ export interface CameraProps extends Inputs { constraints?: Video.Constraints | Signal; } -type CameraOutput = { +/** Signals the camera derives. */ +export type CameraOutput = { // The live camera track, or undefined while disabled or denied. source: Signal; // Clockwise turn a landscape picture needs to appear upright on this screen: 90 or 270 while the diff --git a/js/publish/src/source/device.ts b/js/publish/src/source/device.ts index 6d70d6068dd..430d6c75f99 100644 --- a/js/publish/src/source/device.ts +++ b/js/publish/src/source/device.ts @@ -6,7 +6,8 @@ export interface DeviceProps { preferred?: string | Signal; } -type DeviceOutput = { +/** Signals the device list derives. */ +export type DeviceOutput = { // The devices that are available, or undefined without permission to enumerate them. available: Signal; // The device the platform names as its default, or undefined when it names none. diff --git a/js/publish/src/source/file.ts b/js/publish/src/source/file.ts index ef584984930..361e8b4218d 100644 --- a/js/publish/src/source/file.ts +++ b/js/publish/src/source/file.ts @@ -17,7 +17,8 @@ export interface FileProps extends Inputs { file?: globalThis.File | Signal; } -type FileOutput = { +/** Signals the file source derives. */ +export type FileOutput = { // The sources decoded from the file, undefined while disabled or undecodable. source: Signal; }; diff --git a/js/publish/src/source/microphone.ts b/js/publish/src/source/microphone.ts index 0f045d5b52f..3a3844ac227 100644 --- a/js/publish/src/source/microphone.ts +++ b/js/publish/src/source/microphone.ts @@ -18,7 +18,8 @@ export interface MicrophoneProps extends Inputs { constraints?: Audio.Constraints | Signal; } -type MicrophoneOutput = { +/** Signals the microphone derives. */ +export type MicrophoneOutput = { // The live microphone track, or undefined while disabled or denied. source: Signal; /** A terminal capture failure, cleared when a new capture attempt begins. */ diff --git a/js/publish/src/source/screen.ts b/js/publish/src/source/screen.ts index 7153f925c3d..4d497b9df99 100644 --- a/js/publish/src/source/screen.ts +++ b/js/publish/src/source/screen.ts @@ -18,7 +18,8 @@ export interface ScreenProps extends Inputs { audio?: Audio.Constraints | boolean | Signal; } -type ScreenOutput = { +/** Signals the screen capture derives. */ +export type ScreenOutput = { // The captured surface, or undefined while disabled or dismissed. source: Signal; }; diff --git a/js/publish/src/support/element.ts b/js/publish/src/support/element.ts index bec8c1874e9..5c75ac8b796 100644 --- a/js/publish/src/support/element.ts +++ b/js/publish/src/support/element.ts @@ -29,6 +29,7 @@ function summarize(support: Full): Level { /** The `` element: a banner reporting what this browser can publish. */ export default class MoqPublishSupport extends Support { + /** Detect what this browser can publish. */ protected async detect(): Promise { const support = await isSupported(); return { diff --git a/js/publish/src/ui/element.ts b/js/publish/src/ui/element.ts index 0aace94f4f5..14a550ef879 100644 --- a/js/publish/src/ui/element.ts +++ b/js/publish/src/ui/element.ts @@ -38,6 +38,7 @@ export default class MoqPublishUi extends HTMLElement { this.#observer = new MutationObserver(() => this.#updatePublish()); } + /** Called by the browser when the element joins a document. */ connectedCallback() { this.#updatePublish(); this.#observer.observe(this, { childList: true }); @@ -47,6 +48,7 @@ export default class MoqPublishUi extends HTMLElement { signals.run(this.#render.bind(this)); } + /** Called by the browser when the element leaves its document. */ disconnectedCallback() { this.#observer.disconnect(); this.#signals?.close(); diff --git a/js/publish/src/video/capture.ts b/js/publish/src/video/capture.ts index 85187137f31..eb74343b227 100644 --- a/js/publish/src/video/capture.ts +++ b/js/publish/src/video/capture.ts @@ -13,7 +13,8 @@ export type CaptureInput = { orientation: Getter; }; -type CaptureOutput = { +/** Signals the capture derives. */ +export type CaptureOutput = { // The captured frames, replaced whenever the source changes. Subscribe for a stream of your own, // starting with a copy of the current picture; each reader owns the frames it receives and must // close them. diff --git a/js/publish/src/video/encoder.ts b/js/publish/src/video/encoder.ts index 6828af26c58..9b4dfcf64bc 100644 --- a/js/publish/src/video/encoder.ts +++ b/js/publish/src/video/encoder.ts @@ -35,32 +35,42 @@ export interface Stats { // TODO support signals? /** Encoder tuning knobs. All optional; the encoder auto-sizes anything left unset. */ export interface Config { - // If not provided, the encoder will select the best codec. + /** If not provided, the encoder will select the best codec. */ codec?: string; - // Constrain the encoded width/height in pixels. If unset, source width.max and height.max - // constraints provide the cap when both are present; otherwise screens default to logical pixels. + /** + * Constrain the encoded width/height in pixels. If unset, source width.max and height.max + * constraints provide the cap when both are present; otherwise screens default to logical pixels. + */ maxPixels?: number; - // Cap the encoded resolution to this fraction of the source pixel count. - // For example 0.25 yields a quarter of the pixels (half the width and height), - // scaling with the source instead of assuming a fixed resolution. - // When combined with maxPixels, the smaller resulting cap wins. + /** + * Cap the encoded resolution to this fraction of the source pixel count. + * For example 0.25 yields a quarter of the pixels (half the width and height), + * scaling with the source instead of assuming a fixed resolution. + * When combined with maxPixels, the smaller resulting cap wins. + */ maxScale?: number; - // The longest interval between keyframes. A joining subscriber forces one sooner once the - // group's deltas outweigh the track's refresh ratio. (default: 2000 milliseconds) + /** + * The longest interval between keyframes. A joining subscriber forces one sooner once the + * group's deltas outweigh the track's refresh ratio. (default: 2000 milliseconds) + */ keyframeInterval?: Milli; - // If not provided, the encoder will use the best bitrate for the given width, height, and framerate. + /** If not provided, the encoder will use the best bitrate for the given width, height, and framerate. */ maxBitrate?: number; - // Multiply the number of pixels by this value to get the bitrate. (default: 0.07) - // NOTE: This is multiplied by the codecScale (1.0 for h264) to get the final scale. + /** + * Multiply the number of pixels by this value to get the bitrate. (default: 0.07) + * NOTE: This is multiplied by the codecScale (1.0 for h264) to get the final scale. + */ bitrateScale?: number; - // Cap the encoded frame rate. If set below the captured rate, frames are dropped to hit this target. - // Also feeds the bitrate calculation and the encoder config. If unset, the captured track's rate is used. + /** + * Cap the encoded frame rate. If set below the captured rate, frames are dropped to hit this target. + * Also feeds the bitrate calculation and the encoder config. If unset, the captured track's rate is used. + */ frameRate?: number; } @@ -89,7 +99,8 @@ export type EncoderProps = Inputs & { config?: Config | Signal; }; -type EncoderOutput = { +/** Signals the encoder derives. */ +export type EncoderOutput = { /** The encoder failure, cleared only by a new capture source or format, or new encoder settings. */ error: Signal; // The catalog config published for this rendition, `enabled: false` while disabled, or undefined diff --git a/js/publish/src/video/types.ts b/js/publish/src/video/types.ts index 4e593fe5c8d..a1d560d77cc 100644 --- a/js/publish/src/video/types.ts +++ b/js/publish/src/video/types.ts @@ -40,22 +40,33 @@ export function isStreamTrack(source: Source): source is StreamTrack { /** Stronger typing for the MediaStreamTrack interface. */ export interface StreamTrack extends MediaStreamTrack { + /** Always video. */ kind: "video"; + /** A new track on the same source, with its own settings and lifetime. */ clone(): StreamTrack; + /** The settings the track currently runs with. */ getSettings(): TrackSettings; } /** The settings a video track reports, with the fields video always has made required. */ export interface TrackSettings { + /** The capture device. */ deviceId: string; + /** The physical device the capture device belongs to. */ groupId: string; // I'm not sure what fields are always present. + /** Width divided by height. */ aspectRatio: number; + /** Which way a camera faces. */ facingMode: "user" | "environment" | "left" | "right"; + /** The frames per second, when known. */ frameRate?: number; + /** The height in pixels. */ height: number; + /** Whether the browser crops or scales to meet the constraints. */ resizeMode: "none" | "crop-and-scale"; + /** The width in pixels. */ width: number; } diff --git a/js/qmux/api/index.api.md b/js/qmux/api/index.api.md index 8bb5d55ccc9..5183e47e3f4 100644 --- a/js/qmux/api/index.api.md +++ b/js/qmux/api/index.api.md @@ -18,7 +18,7 @@ export interface Config { streamReceiveWindow?: bigint; } -class Datagrams implements WebTransportDatagramDuplexStream { +export class Datagrams implements WebTransportDatagramDuplexStream { constructor(send: (data: Uint8Array) => void); close(err?: Error): void; incomingHighWaterMark: number; @@ -41,7 +41,7 @@ export interface InstallOptions { export function selectSubprotocol(offered: string | readonly string[] | null | undefined, options?: Pick): string | undefined; -type SendStreamOptions = WebTransportSendStreamOptions & { +export type SendStreamOptions = WebTransportSendStreamOptions & { waitUntilAvailable?: boolean; }; @@ -113,17 +113,17 @@ export interface WebSocketLike { readonly url?: string; } -interface WebSocketStreamCloseEvent { +export interface WebSocketStreamCloseEvent { closeCode: number; reason: string; } -interface WebSocketStreamCloseInfo { +export interface WebSocketStreamCloseInfo { closeCode?: number; reason?: string; } -type WebSocketStreamData = Uint8Array | string; +export type WebSocketStreamData = Uint8Array | string; export interface WebSocketStreamLike { close(closeInfo?: WebSocketStreamCloseInfo): void; @@ -133,7 +133,7 @@ export interface WebSocketStreamLike { readonly url: string; } -interface WebSocketStreamOpenEvent { +export interface WebSocketStreamOpenEvent { extensions: string; protocol: string; readable: ReadableStream; diff --git a/js/qmux/src/index.ts b/js/qmux/src/index.ts index 749b0ee9b80..6790ee32bf8 100644 --- a/js/qmux/src/index.ts +++ b/js/qmux/src/index.ts @@ -3,15 +3,22 @@ import type { Version } from "./session.ts"; import Session from "./session.ts"; export { SessionError, StreamError } from "./error.ts"; -export type { AcceptOptions, Config, SessionOptions, Version } from "./session.ts"; -export { selectSubprotocol } from "./session.ts"; -export type { WebSocketLike, WebSocketStreamLike } from "./web-socket-stream.ts"; +export type { AcceptOptions, Config, SendStreamOptions, SessionOptions, Version } from "./session.ts"; +export { Datagrams, selectSubprotocol } from "./session.ts"; +export type { + WebSocketLike, + WebSocketStreamCloseEvent, + WebSocketStreamCloseInfo, + WebSocketStreamData, + WebSocketStreamLike, + WebSocketStreamOpenEvent, +} from "./web-socket-stream.ts"; -/** Options forwarded to every `Session` constructed by [[install]]. */ +/** Options forwarded to every `Session` constructed by {@link install}. */ export interface InstallOptions { - /** ALPN -> wire-format version(s). See [[SessionOptions.versions]]. */ + /** Wire-format version(s) by ALPN. See {@link SessionOptions.versions}. */ versions?: Record; - /** Require the peer to negotiate an app protocol. See [[SessionOptions.requireProtocol]]. */ + /** Require the peer to negotiate an app protocol. See {@link SessionOptions.requireProtocol}. */ requireProtocol?: boolean; } diff --git a/js/qmux/src/session.ts b/js/qmux/src/session.ts index ea90b14666d..7ae4748a458 100644 --- a/js/qmux/src/session.ts +++ b/js/qmux/src/session.ts @@ -20,7 +20,7 @@ import { export type Version = WireFormat; /** Options for a new outgoing stream. `@types/web` doesn't declare `waitUntilAvailable` yet. */ -type SendStreamOptions = WebTransportSendStreamOptions & { +export type SendStreamOptions = WebTransportSendStreamOptions & { /** Wait for the peer to grant stream credit (the default) instead of rejecting at once. */ waitUntilAvailable?: boolean; }; @@ -119,12 +119,18 @@ function configToTransportParams(config: Required): TransportParams { * silently discarded, matching the W3C WebTransport semantics. */ export class Datagrams implements WebTransportDatagramDuplexStream { + /** Inbound datagrams the readable queues before dropping more; fixed at construction. */ incomingHighWaterMark = 1024; + /** Part of the WebTransport interface; unused, since a datagram never expires here. */ incomingMaxAge: number | null = null; + /** Part of the WebTransport interface; unused, since a datagram is sent once written. */ outgoingHighWaterMark = 1024; + /** Part of the WebTransport interface; unused, since a datagram never expires here. */ outgoingMaxAge: number | null = null; + /** The datagrams the peer sends. */ readonly readable: ReadableStream; + /** The datagrams to send to the peer. */ readonly writable: WritableStream; #incoming!: ReadableStreamDefaultController; @@ -133,7 +139,7 @@ export class Datagrams implements WebTransportDatagramDuplexStream { #maxDatagramSize = 0; #send: (data: Uint8Array) => void; - /** @param send Enqueue a datagram payload onto the wire (best-effort). */ + /** @param send - Enqueue a datagram payload onto the wire (best-effort). */ constructor(send: (data: Uint8Array) => void) { this.#send = send; // A bounded queue: `pull` is a no-op, so `desiredSize` reflects the @@ -158,6 +164,7 @@ export class Datagrams implements WebTransportDatagramDuplexStream { }); } + /** The largest payload a datagram can carry, or 0 before the peer allows any. */ get maxDatagramSize(): number { return this.#maxDatagramSize; } @@ -285,7 +292,7 @@ export interface SessionOptions extends WebTransportOptions { * * Each entry is either: * - A bare ALPN (e.g. `"moq-lite-04"`). The polyfill resolves it via - * [[SessionOptions.versions]] and emits the prefixed wire form + * {@link SessionOptions.versions} and emits the prefixed wire form * `{version}.{alpn}` (e.g. `"qmux-01.moq-lite-04"`). * - An explicit pair already prefixed with a QMux version * (e.g. `"qmux-00.moq-transport-17"`). Advertised as-is. @@ -334,7 +341,7 @@ export interface SessionOptions extends WebTransportOptions { /** Options for accepting a QMux Session on an already-negotiated socket. * * The handshake is done by the time [[Session.accept]] is called, so the - * subprotocol options ([[SessionOptions.protocols]], `versions`, + * subprotocol options ({@link SessionOptions.protocols}, `versions`, * `requireProtocol`) don't apply — see [[selectSubprotocol]], which consumes * them during the upgrade instead. */ @@ -537,7 +544,7 @@ export default class Session implements WebTransport { // [[AcceptOptions.protocol]]: stands in for `socket.protocol` when the host // doesn't expose the negotiated subprotocol. #protocolOverride?: string; - // [[SessionOptions.requireProtocol]] on a dial: the server must pick one of + // `SessionOptions.requireProtocol` on a dial: the server must pick one of // our application protocols, not answer with none. #requireProtocol = false; #closed?: Error; diff --git a/js/qmux/src/web-socket-stream.ts b/js/qmux/src/web-socket-stream.ts index 89f7ea8869b..ffcc90f3e74 100644 --- a/js/qmux/src/web-socket-stream.ts +++ b/js/qmux/src/web-socket-stream.ts @@ -20,29 +20,41 @@ export type WebSocketStreamData = Uint8Array | string; /** Resolved value of {@link WebSocketStreamLike.opened}. */ export interface WebSocketStreamOpenEvent { + /** The messages the peer sends. */ readable: ReadableStream; + /** The messages to send to the peer. */ writable: WritableStream; + /** The extensions the server selected. */ extensions: string; + /** The subprotocol the server selected, or empty. */ protocol: string; } /** Resolved value of {@link WebSocketStreamLike.closed}. */ export interface WebSocketStreamCloseEvent { + /** The close code the connection ended with. */ closeCode: number; + /** The close reason the connection ended with. */ reason: string; } /** Argument to {@link WebSocketStreamLike.close}. */ export interface WebSocketStreamCloseInfo { + /** The close code to send. */ closeCode?: number; + /** The close reason to send. */ reason?: string; } /** The common shape implemented by both the native API and this ponyfill. */ export interface WebSocketStreamLike { + /** The URL the socket connected to. */ readonly url: string; + /** Resolves with the streams once the handshake completes. */ readonly opened: Promise; + /** Resolves once the connection closes. */ readonly closed: Promise; + /** Close the connection, with an optional code and reason. */ close(closeInfo?: WebSocketStreamCloseInfo): void; /** Ponyfill-only: resize the write-backpressure high-water mark at runtime * (see {@link WebSocketStream.setHighWaterMark}). Absent on the native API, @@ -77,19 +89,30 @@ type NativeWebSocketStreamConstructor = new ( /** The slice of the `WebSocket` API this ponyfill relies on. Both the browser * `WebSocket` and Node's `ws` satisfy it. */ export interface WebSocketLike { + /** How binary messages arrive; set to `arraybuffer`. */ binaryType: string; /** Absent on some server-side implementations; only used to report * {@link WebSocketStreamLike.url} for an adopted socket. */ readonly url?: string; + /** Bytes queued to send but not yet sent. */ readonly bufferedAmount: number; + /** The connection state, as the `WebSocket` constants number it. */ readonly readyState: number; + /** The subprotocol the server selected, or empty. */ readonly protocol: string; + /** The extensions the server selected. */ readonly extensions: string; + /** Queue a message to send. */ send(data: string | ArrayBufferLike | ArrayBufferView): void; + /** Close the connection, with an optional code and reason. */ close(code?: number, reason?: string): void; + /** Called once the handshake completes. */ onopen: ((ev: unknown) => void) | null; + /** Called with each message received. */ onmessage: ((ev: { data: unknown }) => void) | null; + /** Called when the connection fails. */ onerror: ((ev: unknown) => void) | null; + /** Called once the connection closes. */ onclose: ((ev: { code?: number; reason?: string }) => void) | null; } diff --git a/js/room/api/index.api.md b/js/room/api/index.api.md index 5838295c502..268c21c5ece 100644 --- a/js/room/api/index.api.md +++ b/js/room/api/index.api.md @@ -34,6 +34,7 @@ declare namespace Chat { Subscriber } } +export { Chat } export type Claims = { root: string; @@ -47,7 +48,7 @@ export { Clock } export function consume(broadcast: Watch.Broadcast): Consumed; -type Consumed = { +export type Consumed = { user: Readonlys; preview: Getter; close: () => void; @@ -212,7 +213,7 @@ export const TRACK: { const TRACK_2 = "chat"; -type TrackRef = { +export type TrackRef = { track: string; }; @@ -232,7 +233,7 @@ export type UserFields = { export function userFields(props?: UserProps): UserFields; -type UserInput = { +export type UserInput = { id: Getter; name: Getter; avatar: Getter; @@ -246,5 +247,4 @@ export type UserProps = { color?: string | Signal; }; - ``` diff --git a/js/room/src/index.ts b/js/room/src/index.ts index 4722bb9100e..22f854fb1b9 100644 --- a/js/room/src/index.ts +++ b/js/room/src/index.ts @@ -18,6 +18,7 @@ export * as Clock from "@moq/clock"; export * as Chat from "./chat.ts"; export { Local, type LocalProps } from "./local.ts"; export { + type Consumed, consume, type ExtendedCatalog, type HangCatalog, @@ -25,8 +26,10 @@ export { type Preview, serve, TRACK, + type TrackRef, type User, type UserFields, + type UserInput, type UserProps, userFields, } from "./metadata.ts"; diff --git a/js/room/src/metadata.ts b/js/room/src/metadata.ts index 1c7067a0854..63a27ef5c15 100644 --- a/js/room/src/metadata.ts +++ b/js/room/src/metadata.ts @@ -54,7 +54,9 @@ export type Preview = { typing?: boolean; }; -type TrackRef = { +/** Points a `hang` catalog section at a track. */ +export type TrackRef = { + /** The track name. */ track: string; }; @@ -170,7 +172,8 @@ function serveSnapshot( }); } -type Consumed = { +/** The signals {@link consume} reads, and how to stop reading them. */ +export type Consumed = { user: Readonlys; preview: Getter; close: () => void; diff --git a/js/signals/api/dom.api.md b/js/signals/api/dom.api.md index d600ee7c9be..299e25d5c9c 100644 --- a/js/signals/api/dom.api.md +++ b/js/signals/api/dom.api.md @@ -6,7 +6,7 @@ import { Nano } from '@moq/clock'; -interface ArrayElement extends Array { +export interface ArrayElement extends Array { } class Computed implements Getter { @@ -52,7 +52,7 @@ class Effect { event(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; get(signal: Getter): T; getAll[]>(signals: [...S]): { - [K in keyof S]: Truthy>; + [K in keyof S]: Exclude, false | 0 | "" | null | undefined>; } | undefined; interval(fn: () => void, period: Nano): void; proxy(dst: Setter, src: Getter): void; @@ -68,8 +68,6 @@ class Effect { type Element_2 = Node | ArrayElement | (string & {}) | number | boolean | null | undefined; export { Element_2 as Element } -type Falsy = false | 0 | "" | null | undefined; - interface Getter { changed(): Promise; changed(fn: Subscriber): Dispose; @@ -94,7 +92,4 @@ type SetterType = S extends Setter ? T : never; type Subscriber = (value: T) => void; -type Truthy = Exclude; - - ``` diff --git a/js/signals/api/index.api.md b/js/signals/api/index.api.md index d850becfc4d..bc2c2c5f684 100644 --- a/js/signals/api/index.api.md +++ b/js/signals/api/index.api.md @@ -47,7 +47,7 @@ export class Effect { event(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; get(signal: Getter): T; getAll[]>(signals: [...S]): { - [K in keyof S]: Truthy>; + [K in keyof S]: Exclude, false | 0 | "" | null | undefined>; } | undefined; interval(fn: () => void, period: Nano): void; proxy(dst: Setter, src: Getter): void; @@ -60,8 +60,6 @@ export class Effect { timer(fn: () => void, duration: Nano): void; } -type Falsy = false | 0 | "" | null | undefined; - export interface GetPromise extends Getter, PromiseLike { } @@ -111,7 +109,7 @@ export interface Setter { update(fn: (prev: T) => T): void; } -type SetterType = S extends Setter ? T : never; +export type SetterType = S extends Setter ? T : never; export class Signal implements Getter, Setter { readonly [GETTER_BRAND] = true; @@ -135,9 +133,6 @@ const SIGNAL_BRAND: unique symbol; export type SignalMap = Record>; -type Subscriber = (value: T) => void; - -type Truthy = Exclude; - +export type Subscriber = (value: T) => void; ``` diff --git a/js/signals/api/react.api.md b/js/signals/api/react.api.md index 701b56f31dd..3c658112fde 100644 --- a/js/signals/api/react.api.md +++ b/js/signals/api/react.api.md @@ -49,5 +49,4 @@ export function useSignal(signal: Signal): [T, (value: T | ((prev: T) => T export function useValue(signal: Getter): T; - ``` diff --git a/js/signals/api/solid.api.md b/js/signals/api/solid.api.md index 9b9033213df..4e04679a912 100644 --- a/js/signals/api/solid.api.md +++ b/js/signals/api/solid.api.md @@ -55,5 +55,4 @@ const SIGNAL_BRAND: unique symbol; type Subscriber = (value: T) => void; - ``` diff --git a/js/signals/src/dom.ts b/js/signals/src/dom.ts index d1ef03f8162..8e9f70f1ade 100644 --- a/js/signals/src/dom.ts +++ b/js/signals/src/dom.ts @@ -70,7 +70,8 @@ export function create( /** Renderable content: a node, array of nodes, primitive, or nullish. Matches solid.js's JSX.Element. */ export type Element = Node | ArrayElement | (string & {}) | number | boolean | null | undefined; -interface ArrayElement extends Array {} +/** A nested list of {@link Element}s. */ +export interface ArrayElement extends Array {} /** Renders `element` into `parent`, removing it again when the effect reruns or closes. */ export function render(effect: Effect, parent: Node, element: Element | ((effect: Effect) => Element)) { diff --git a/js/signals/src/index.ts b/js/signals/src/index.ts index f93e5ef1393..ea784aa5ea1 100644 --- a/js/signals/src/index.ts +++ b/js/signals/src/index.ts @@ -11,11 +11,13 @@ export type Dispose = () => void; const noop: Dispose = () => {}; -type Subscriber = (value: T) => void; +/** Receives a value each time it changes. */ +export type Subscriber = (value: T) => void; // Symbols to identify our instances across different package versions. -// SIGNAL_BRAND is Signal only (it implies a write side); GETTER_BRAND is every readable we ship. +/** Marks a {@link Signal}, even one from another copy of this package; it implies a write side. */ const SIGNAL_BRAND = Symbol.for("@moq/signals"); +/** Marks every readable this package ships, even one from another copy of it. */ const GETTER_BRAND = Symbol.for("@moq/signals.getter"); const CHANGE_LISTEN = Symbol.for("@moq/signals.change.listen"); @@ -65,8 +67,9 @@ export class Signal implements Getter, Setter { #hasCapturedOldValue = false; #forceNotify = false; - // Brands to identify this as a Signal (and a readable) across package instances. + /** Marks this as a Signal across package instances. */ readonly [SIGNAL_BRAND] = true; + /** Marks this as a readable across package instances. */ readonly [GETTER_BRAND] = true; constructor(value: T) { @@ -182,8 +185,9 @@ export class Signal implements Getter, Setter { return () => this.#subscribers.delete(fn); } - /** Resolves with the value the next time it changes, or calls `fn` once on the next change. */ + /** Resolves with the value the next time it changes. */ changed(): Promise; + /** Calls `fn` once the next time the value changes. Returns a function to cancel. */ changed(fn: Subscriber): Dispose; changed(fn?: Subscriber): Promise | Dispose { if (fn) { @@ -329,7 +333,7 @@ class Changed implements GetPromise> { export class Once implements GetPromise { #signal = new Signal(undefined); - // Brand to identify this as a readable across package instances. + /** Marks this as a readable across package instances. */ readonly [GETTER_BRAND] = true; /** Settle the value. Throws if it has already settled. */ @@ -345,8 +349,9 @@ export class Once implements GetPromise { return this.#signal.peek(); } - /** Resolves when it settles, or calls `fn` once when it settles. */ + /** Resolves when it settles. */ changed(): Promise; + /** Calls `fn` once when it settles. Returns a function to cancel. */ changed(fn: (value: T | undefined) => void): Dispose; changed(fn?: (value: T | undefined) => void): Promise | Dispose { return fn ? this.#signal.changed(fn) : this.#signal.changed(); @@ -490,7 +495,8 @@ export function race(values: T): Promise = S extends Setter ? T : never; +/** The value type a {@link Setter} accepts, e.g. `number` for `Signal`. */ +export type SetterType = S extends Setter ? T : never; /** The value type a {@link Getter} yields, e.g. `number` for `Getter`. */ export type GetterType = G extends Getter ? T : never; @@ -593,10 +599,6 @@ function getterShaped(value: unknown): boolean { */ export type Inputs = { [K in keyof I]?: GetterInit> }; -// Excludes common falsy values from a type -type Falsy = false | 0 | "" | null | undefined; -type Truthy = Exclude; - /** * Runs a function that reads signals via `effect.get(...)` and reruns whenever * any of them change. Registers cleanup, timers, and event listeners that are @@ -931,14 +933,14 @@ export class Effect { /** Reads and tracks several signals, returning their values or `undefined` if any is falsy. */ getAll[]>( signals: [...S], - ): { [K in keyof S]: Truthy> } | undefined { + ): { [K in keyof S]: Exclude, false | 0 | "" | null | undefined> } | undefined { const values: unknown[] = []; for (const signal of signals) { const value = this.get(signal); if (!value) return undefined; values.push(value); } - return values as { [K in keyof S]: Truthy> }; + return values as { [K in keyof S]: Exclude, false | 0 | "" | null | undefined> }; } /** Runs `fn` with the signal's value now and again whenever it changes, scoped to this effect. */ @@ -955,61 +957,70 @@ export class Effect { }); } - /** Adds an event listener that is removed automatically when the effect reruns or closes. */ + /** Adds an {@link HTMLElement} listener, removed automatically when the effect reruns or closes. */ event( target: HTMLElement, type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed SVGElement listener, removed when the effect reruns or closes. */ event( target: SVGElement, type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed Document listener, removed when the effect reruns or closes. */ event( target: Document, type: K, listener: (this: Document, ev: DocumentEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed Window listener, removed when the effect reruns or closes. */ event( target: Window, type: K, listener: (this: Window, ev: WindowEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed WebSocket listener, removed when the effect reruns or closes. */ event( target: WebSocket, type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed XMLHttpRequest listener, removed when the effect reruns or closes. */ event( target: XMLHttpRequest, type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed MediaQueryList listener, removed when the effect reruns or closes. */ event( target: MediaQueryList, type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed Animation listener, removed when the effect reruns or closes. */ event( target: Animation, type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a typed EventSource listener, removed when the effect reruns or closes. */ event( target: EventSource, type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => void, options?: boolean | AddEventListenerOptions, ): void; + /** Adds a listener for any event on any target, removed when the effect reruns or closes. */ event( target: EventTarget, type: string, @@ -1159,7 +1170,7 @@ export class Computed implements Getter { #signal = new Signal(undefined); #effect: Effect; - // Brand to identify this as a readable across package instances. + /** Marks this as a readable across package instances. */ readonly [GETTER_BRAND] = true; /** Creates a computed that derives its value from `fn`, rerunning when dependencies change. */ @@ -1174,8 +1185,9 @@ export class Computed implements Getter { return this.#signal.peek(); } - /** Resolves the next time the derived value changes, or calls `fn` once on the next change. */ + /** Resolves the next time the derived value changes. */ changed(): Promise; + /** Calls `fn` once the next time the derived value changes. Returns a function to cancel. */ changed(fn: Subscriber): Dispose; changed(fn?: Subscriber): Promise | Dispose { return fn ? this.#signal.changed(fn) : this.#signal.changed(); @@ -1225,7 +1237,7 @@ export class Derived[], T> implements G #sources: S; #fn: (...values: GetterValues) => T; - // Brand to identify this as a readable across package instances. + /** Marks this as a readable across package instances. */ readonly [GETTER_BRAND] = true; /** Creates a view deriving its value from `sources` via `fn`, recomputed on every read. */ @@ -1244,8 +1256,9 @@ export class Derived[], T> implements G return this.#watch(fn); } - /** Resolves the next time the derived value changes, or calls `fn` once on the next change. */ + /** Resolves the next time the derived value changes. */ changed(): Promise; + /** Calls `fn` once the next time the derived value changes. Returns a function to cancel. */ changed(fn: Subscriber): Dispose; changed(fn?: Subscriber): Promise | Dispose { if (fn) return this.#once(fn); diff --git a/js/ui/api/index.api.md b/js/ui/api/index.api.md index 228206c9e39..5267e4af004 100644 --- a/js/ui/api/index.api.md +++ b/js/ui/api/index.api.md @@ -29,8 +29,6 @@ export type Level = "full" | "partial" | "none"; const OBSERVED: readonly ["show", "details"]; -type Observed = (typeof OBSERVED)[number]; - interface Report_2 { rows: [group: string, feature: string, status: Status][]; summary: Level; @@ -48,16 +46,15 @@ export type Status = boolean | Level | { export abstract class Support extends HTMLElement { constructor(); - attributeChangedCallback(name: Observed, _oldValue: string | null, newValue: string | null): void; + attributeChangedCallback(name: (typeof OBSERVED)[number], _oldValue: string | null, newValue: string | null): void; connectedCallback(): void; get details(): boolean; set details(details: boolean); protected abstract detect(): Promise; disconnectedCallback(): void; - static observedAttributes: readonly ["show", "details"]; + static observedAttributes: typeof OBSERVED; get show(): Show; set show(show: Show); } - ``` diff --git a/js/ui/src/support.ts b/js/ui/src/support.ts index 9c0d0671ae8..e08666bb84e 100644 --- a/js/ui/src/support.ts +++ b/js/ui/src/support.ts @@ -30,8 +30,8 @@ export interface Report { */ export type Show = "always" | "warning" | "error" | "never"; +/** The attributes the element observes. */ const OBSERVED = ["show", "details"] as const; -type Observed = (typeof OBSERVED)[number]; /** * A banner reporting what this browser supports, with an optional details table. @@ -46,7 +46,8 @@ export abstract class Support extends HTMLElement { #signals?: Effect; - static observedAttributes = OBSERVED; + /** The attributes the browser reports changes to. */ + static observedAttributes: typeof OBSERVED = OBSERVED; constructor() { super(); @@ -59,17 +60,20 @@ export abstract class Support extends HTMLElement { /** Detect what this browser supports, called once on construction. */ protected abstract detect(): Promise; + /** Called by the browser when the element joins a document. */ connectedCallback() { this.#signals = new Effect(); this.#signals.run(this.#render.bind(this)); } + /** Called by the browser when the element leaves its document. */ disconnectedCallback() { this.#signals?.close(); this.#signals = undefined; } - attributeChangedCallback(name: Observed, _oldValue: string | null, newValue: string | null) { + /** Called by the browser when an observed attribute changes. */ + attributeChangedCallback(name: (typeof OBSERVED)[number], _oldValue: string | null, newValue: string | null) { if (name === "show") { const show = newValue ?? "warning"; if (show === "always" || show === "warning" || show === "error" || show === "never") { diff --git a/js/video/api/index.api.md b/js/video/api/index.api.md index d452f5eb3c6..fb8dcc0b988 100644 --- a/js/video/api/index.api.md +++ b/js/video/api/index.api.md @@ -48,5 +48,4 @@ export type RendererProps = Inputs; export function rotateVideoDimensions(dimensions: Dimensions, rotation?: number): Dimensions; - ``` diff --git a/js/watch/api/element.api.md b/js/watch/api/element.api.md index a10db978ccb..0da4ad5232e 100644 --- a/js/watch/api/element.api.md +++ b/js/watch/api/element.api.md @@ -42,14 +42,17 @@ declare namespace Audio_2 { export { DecoderInput_2 as DecoderInput, DecoderProps_2 as DecoderProps, + DecoderOutput_2 as DecoderOutput, Stats_2 as Stats, Decoder_2 as Decoder, EmitterInput, EmitterProps, + EmitterOutput, Emitter, Target_2 as Target, Supported_2 as Supported, SourceInput_2 as SourceInput, + SourceOutput_2 as SourceOutput, Source_2 as Source } } @@ -71,7 +74,7 @@ type BroadcastInput = { }; type BroadcastOutput = { - status: Signal; + status: Signal<"offline" | "loading" | "live" | "error" | "unsupported">; active: Signal; error: Signal; catalog: Signal; @@ -171,13 +174,11 @@ type EmitterProps = Inputs & { source: Decoder_2; }; -type Kind = "video" | "audio" | "text"; - class MoqWatch extends HTMLElement { constructor(); get announced(): boolean; set announced(value: boolean); - attributeChangedCallback(name: Observed, oldValue: string | null, newValue: string | null): void; + attributeChangedCallback(name: (typeof OBSERVED)[number], oldValue: string | null, newValue: string | null): void; audio: Audio_2.Decoder; get backend(): Video.Backend; set backend(value: Video.Backend); @@ -218,7 +219,7 @@ class MoqWatch extends HTMLElement { set muted(value: boolean); get name(): Moq.Path.Valid; set name(value: string | Moq.Path.Valid); - static observedAttributes: readonly ["url", "versions", "name", "paused", "volume", "muted", "visible", "backend", "announced", "delay", "buffer", "catalog-format", "captions"]; + static observedAttributes: typeof OBSERVED; get paused(): boolean; set paused(value: boolean); readonly player: Player; @@ -242,8 +243,6 @@ export default MoqWatch; const OBSERVED: readonly ["url", "versions", "name", "paused", "volume", "muted", "visible", "backend", "announced", "delay", "buffer", "catalog-format", "captions"]; -type Observed = (typeof OBSERVED)[number]; - export function parseCatalogFormat(value: string | null): CatalogFormat | undefined; class Player { @@ -252,8 +251,8 @@ class Player { readonly broadcast: Broadcast; close(): void; readonly emitter: Audio_2.Emitter; - readonly in: Readonlys> & { - readonly [K in Kind]: Readonlys; + readonly in: Readonlys> & { + readonly [K in "video" | "audio" | "text"]: Readonlys; }; readonly renderer: Video.Renderer; reset(): void; @@ -291,8 +290,8 @@ type PlayerInput = { }; }; -type PlayerProps = Inputs> & { - [K in Kind]?: Inputs; +type PlayerProps = Inputs> & { + [K in "video" | "audio" | "text"]?: Inputs; }; function renderable(config: Catalog.TextConfig): boolean; @@ -410,8 +409,6 @@ interface Stats_2 { underruns: number; } -type Status = "offline" | "loading" | "live" | "error" | "unsupported"; - type Supported = (config: Catalog.VideoConfig) => Promise; function supported(config: Catalog.VideoConfig): Promise; @@ -462,6 +459,7 @@ declare namespace Text_2 { Renderer_2 as Renderer, renderable, SourceInput_3 as SourceInput, + SourceOutput_3 as SourceOutput, Source_3 as Source } } @@ -472,6 +470,7 @@ declare namespace Video { DecoderInput, DecoderProps, Stats, + DecoderOutput, Decoder, Visible, RendererInput, @@ -480,11 +479,11 @@ declare namespace Video { Supported, Target, SourceInput, + SourceOutput, Source } } type Visible = "never" | "always" | (string & {}); - ``` diff --git a/js/watch/api/index.api.md b/js/watch/api/index.api.md index e56b2861b01..95825a68c16 100644 --- a/js/watch/api/index.api.md +++ b/js/watch/api/index.api.md @@ -48,33 +48,21 @@ declare namespace Audio_2 { export { DecoderInput, DecoderProps, + DecoderOutput, Stats, Decoder, EmitterInput, EmitterProps, + EmitterOutput, Emitter, Target, Supported, SourceInput, + SourceOutput, Source } } - -declare namespace Audio_3 { - export { - DecoderInput, - DecoderProps, - Stats, - Decoder, - EmitterInput, - EmitterProps, - Emitter, - Target, - Supported, - SourceInput, - Source - } -} +export { Audio_2 as Audio } export class Broadcast { constructor(props?: Inputs); @@ -92,8 +80,8 @@ export type BroadcastInput = { catalog: Getter; }; -type BroadcastOutput = { - status: Signal; +export type BroadcastOutput = { + status: Signal<"offline" | "loading" | "live" | "error" | "unsupported">; active: Signal; error: Signal; catalog: Signal; @@ -201,25 +189,23 @@ type EmitterProps = Inputs & { export { Hang } -type Kind = "video" | "audio" | "text"; - export { Net } export class Player { constructor(props?: PlayerProps); - readonly audio: Audio_3.Decoder; + readonly audio: Audio_2.Decoder; readonly broadcast: Broadcast; close(): void; - readonly emitter: Audio_3.Emitter; - readonly in: Readonlys> & { - readonly [K in Kind]: Readonlys; + readonly emitter: Audio_2.Emitter; + readonly in: Readonlys> & { + readonly [K in "video" | "audio" | "text"]: Readonlys; }; - readonly renderer: Video_3.Renderer; + readonly renderer: Video.Renderer; reset(): void; readonly sync: Sync; - readonly text: Text_3.Source; - readonly textRenderer: Text_3.Renderer; - readonly video: Video_3.Decoder; + readonly text: Text_2.Source; + readonly textRenderer: Text_2.Renderer; + readonly video: Video.Decoder; } export type PlayerInput = { @@ -234,13 +220,13 @@ export type PlayerInput = { delay: Getter; buffer: Getter; video: { - target: Getter; + target: Getter; canvas: Getter; - visible: Getter; - backend: Getter; + visible: Getter; + backend: Getter; }; audio: { - target: Getter; + target: Getter; volume: Getter; muted: Getter; }; @@ -250,8 +236,8 @@ export type PlayerInput = { }; }; -export type PlayerProps = Inputs> & { - [K in Kind]?: Inputs; +export type PlayerProps = Inputs> & { + [K in "video" | "audio" | "text"]?: Inputs; }; function renderable(config: Catalog.TextConfig): boolean; @@ -371,8 +357,6 @@ interface Stats_2 { frameCount: number; } -type Status = "offline" | "loading" | "live" | "error" | "unsupported"; - type Supported = (config: Catalog.AudioConfig) => Promise; function supported(config: Catalog.AudioConfig): Promise; @@ -395,7 +379,7 @@ export type SyncInput = { buffer: Getter; }; -type SyncOutput = { +export type SyncOutput = { instant: Signal; reference: Signal; delay: Signal; @@ -423,20 +407,11 @@ declare namespace Text_2 { Renderer, renderable, SourceInput_2 as SourceInput, + SourceOutput_2 as SourceOutput, Source_2 as Source } } - -declare namespace Text_3 { - export { - RendererInput, - RendererProps, - Renderer, - renderable, - SourceInput_2 as SourceInput, - Source_2 as Source - } -} +export { Text_2 as Text } declare namespace Video { export { @@ -444,6 +419,7 @@ declare namespace Video { DecoderInput_2 as DecoderInput, DecoderProps_2 as DecoderProps, Stats_2 as Stats, + DecoderOutput_2 as DecoderOutput, Decoder_2 as Decoder, Visible, RendererInput_2 as RendererInput, @@ -452,29 +428,12 @@ declare namespace Video { Supported_2 as Supported, Target_2 as Target, SourceInput_3 as SourceInput, + SourceOutput_3 as SourceOutput, Source_3 as Source } } - -declare namespace Video_3 { - export { - Backend, - DecoderInput_2 as DecoderInput, - DecoderProps_2 as DecoderProps, - Stats_2 as Stats, - Decoder_2 as Decoder, - Visible, - RendererInput_2 as RendererInput, - RendererProps_2 as RendererProps, - Renderer_2 as Renderer, - Supported_2 as Supported, - Target_2 as Target, - SourceInput_3 as SourceInput, - Source_3 as Source - } -} +export { Video } type Visible = "never" | "always" | (string & {}); - ``` diff --git a/js/watch/api/support-element.api.md b/js/watch/api/support-element.api.md index a9d8b3df7b7..f83089bbfac 100644 --- a/js/watch/api/support-element.api.md +++ b/js/watch/api/support-element.api.md @@ -15,5 +15,4 @@ export default MoqWatchSupport; export { Show } - ``` diff --git a/js/watch/api/support.api.md b/js/watch/api/support.api.md index 44752b7d909..d46f2a05d0b 100644 --- a/js/watch/api/support.api.md +++ b/js/watch/api/support.api.md @@ -39,5 +39,4 @@ export type Video = { av1: Codec; }; - ``` diff --git a/js/watch/api/ui.api.md b/js/watch/api/ui.api.md index b98b4dab9e2..7a9742573cc 100644 --- a/js/watch/api/ui.api.md +++ b/js/watch/api/ui.api.md @@ -11,5 +11,4 @@ class MoqWatchUi extends HTMLElement { } export default MoqWatchUi; - ``` diff --git a/js/watch/src/audio/decoder.ts b/js/watch/src/audio/decoder.ts index 98c5dceb039..1a6c8792cee 100644 --- a/js/watch/src/audio/decoder.ts +++ b/js/watch/src/audio/decoder.ts @@ -49,7 +49,8 @@ export type DecoderProps = Inputs & { sync: Sync; }; -type DecoderOutput = { +/** Signals the decoder derives. */ +export type DecoderOutput = { /** Fatal decode failure, cleared when another source is selected. */ error: Signal; context: Signal; @@ -914,6 +915,7 @@ export class Decoder { static supported = supported; } +/** Whether the WebCodecs audio decoder can play this config. */ async function supported(config: Catalog.AudioConfig): Promise { if (!Catalog.containerSupported(config.container)) { // `kind` is the literal "unknown" tag; the container the publisher actually named is in `raw`. diff --git a/js/watch/src/audio/emitter.ts b/js/watch/src/audio/emitter.ts index cb5b848aca5..d191852ad5c 100644 --- a/js/watch/src/audio/emitter.ts +++ b/js/watch/src/audio/emitter.ts @@ -23,7 +23,8 @@ export type EmitterProps = Inputs & { source: Decoder; }; -type EmitterOutput = { +/** Signals the emitter derives. */ +export type EmitterOutput = { // Whether audio should be downloaded. Wired into the decoder's `enabled` input by the owner. enabled: Signal; }; diff --git a/js/watch/src/audio/source.ts b/js/watch/src/audio/source.ts index fb2d0027b9f..ab693fc7827 100644 --- a/js/watch/src/audio/source.ts +++ b/js/watch/src/audio/source.ts @@ -28,7 +28,8 @@ export type SourceInput = { supported: Getter; }; -type SourceOutput = { +/** Signals the source derives. */ +export type SourceOutput = { catalog: Signal; available: Signal>; track: Signal; diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index 24dd9ea8a60..15eba3b0813 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -3,7 +3,16 @@ import * as Json from "@moq/json"; import * as Msf from "@moq/msf"; import type * as Moq from "@moq/net"; import { Error as NetError, Path, StreamCode } from "@moq/net"; -import { Effect, type Getter, getter, type Inputs, type Readonlys, readonlys, Signal } from "@moq/signals"; +import { + Effect, + type Getter, + type GetterType, + getter, + type Inputs, + type Readonlys, + readonlys, + Signal, +} from "@moq/signals"; import { toHang } from "./msf"; @@ -79,7 +88,7 @@ function filterCatalog(catalog: Catalog.Root, usable: Usable): Catalog.Root { } /** - * Watch supports the on-the-wire catalog formats from @moq/hang, plus "hangz" (the + * Watch supports the on-the-wire catalog formats from `@moq/hang`, plus "hangz" (the * DEFLATE-compressed `catalog.json.z` track) and a "manual" mode where the user supplies the * catalog directly without fetching. "hangz" is opt-in only: it shares the `.hang` broadcast suffix * and is never auto-detected, so set it explicitly via `catalogFormat`. @@ -88,10 +97,6 @@ export const CATALOG_FORMATS = [...Catalog.FORMATS, "hangz", "manual"] as const; /** A catalog format the watcher can read; see {@link CATALOG_FORMATS}. */ export type CatalogFormat = (typeof CATALOG_FORMATS)[number]; -// "error" means the origin refused the broadcast; `out.error` says why. -// "unsupported" means its catalog requires a newer player. -type Status = "offline" | "loading" | "live" | "error" | "unsupported"; - /** * Signals the component reads. Whoever owns the backing Signal (the caller, or * another component whose output is wired in) does the writing. @@ -123,8 +128,11 @@ export type BroadcastInput = { catalog: Getter; }; -type BroadcastOutput = { - status: Signal; +/** Signals the component derives. */ +export type BroadcastOutput = { + // "error" means the origin refused the broadcast; `error` says why. + // "unsupported" means its catalog requires a newer player. + status: Signal<"offline" | "loading" | "live" | "error" | "unsupported">; active: Signal; // Why the origin refused the broadcast, while `status` is "error". A refusal is final: @@ -137,6 +145,8 @@ type BroadcastOutput = { catalog: Signal; }; +type Status = GetterType; + /** A catalog source that can wait for announcement before subscribing. */ export class Broadcast { /** The wired inputs, read-only. */ diff --git a/js/watch/src/element.ts b/js/watch/src/element.ts index 88c95b42f2b..19e5f9c51e9 100644 --- a/js/watch/src/element.ts +++ b/js/watch/src/element.ts @@ -46,6 +46,7 @@ function parseVolume(value: string | null): number { return 0.5; } +/** The attributes the element observes. */ const OBSERVED = [ "url", "versions", @@ -61,7 +62,6 @@ const OBSERVED = [ "catalog-format", "captions", ] as const; -type Observed = (typeof OBSERVED)[number]; // Parse the `visible` attribute into a Visible value, falling back to "20%". function parseVisible(value: string | null): Video.Visible { @@ -130,7 +130,8 @@ const cleanup = new FinalizationRegistry((signals) => signals.close()); /** The `` element: plays a broadcast into a nested . */ export default class MoqWatch extends HTMLElement { - static observedAttributes = OBSERVED; + /** The attributes the browser reports changes to. */ + static observedAttributes: typeof OBSERVED = OBSERVED; /** * The relay connection, shared with every other element on the page pointing at the @@ -397,6 +398,7 @@ export default class MoqWatch extends HTMLElement { // Annoyingly, we have to use these callbacks to figure out when the element is connected to the DOM. // This wouldn't be so bad if there was a destructor for web components to clean up our effects. + /** Called by the browser when the element joins a document. */ connectedCallback() { this.#enabled.set(true); this.style.display = "block"; @@ -416,12 +418,14 @@ export default class MoqWatch extends HTMLElement { } } + /** Called by the browser when the element leaves its document. */ disconnectedCallback() { // Stop everything but don't actually cleanup just in case we get added back to the DOM. this.#enabled.set(false); } - attributeChangedCallback(name: Observed, oldValue: string | null, newValue: string | null) { + /** Called by the browser when an observed attribute changes. */ + attributeChangedCallback(name: (typeof OBSERVED)[number], oldValue: string | null, newValue: string | null) { if (oldValue === newValue) { return; } diff --git a/js/watch/src/player.ts b/js/watch/src/player.ts index bf2d19d7b38..c921cdaea98 100644 --- a/js/watch/src/player.ts +++ b/js/watch/src/player.ts @@ -60,16 +60,20 @@ export type PlayerInput = { }; }; -// The inputs nested under a media kind; the rest are flat. -type Kind = "video" | "audio" | "text"; - -/** Constructor options for {@link Player}; omitted controls use the element defaults. */ -export type PlayerProps = Inputs> & { [K in Kind]?: Inputs }; +/** + * Constructor options for {@link Player}; omitted controls use the element defaults. The inputs of + * each media kind nest under its own key. + */ +export type PlayerProps = Inputs> & { + [K in "video" | "audio" | "text"]?: Inputs; +}; /** Owns the broadcast, synchronized media pipelines, and their download policy. */ export class Player { /** Inputs wired into the pipeline. Pass signals to change them after construction. */ - readonly in: Readonlys> & { readonly [K in Kind]: Readonlys }; + readonly in: Readonlys> & { + readonly [K in "video" | "audio" | "text"]: Readonlys; + }; /** Broadcast subscription and effective catalog. */ readonly broadcast: Broadcast; /** Shared audio, video, and caption clock. */ diff --git a/js/watch/src/support/element.ts b/js/watch/src/support/element.ts index 85470ca8cf0..399a63dedfb 100644 --- a/js/watch/src/support/element.ts +++ b/js/watch/src/support/element.ts @@ -28,6 +28,7 @@ function summarize(support: Full): Level { /** The `` element: a banner reporting what this browser can play. */ export default class MoqWatchSupport extends Support { + /** Detect what this browser can play. */ protected async detect(): Promise { const support = await isSupported(); return { diff --git a/js/watch/src/sync.ts b/js/watch/src/sync.ts index f0aafdbf54d..b1d99b47ed8 100644 --- a/js/watch/src/sync.ts +++ b/js/watch/src/sync.ts @@ -42,7 +42,8 @@ export type SyncInput = { buffer: Getter; }; -type SyncOutput = { +/** Signals the sync derives. */ +export type SyncOutput = { // Derived: whether the delay is "instant". Numeric and "auto" delays share `false`, so readers // that only care about the mode don't rerun when the number changes. instant: Signal; diff --git a/js/watch/src/text/source.ts b/js/watch/src/text/source.ts index d20438ac3ff..67e2a19c467 100644 --- a/js/watch/src/text/source.ts +++ b/js/watch/src/text/source.ts @@ -19,7 +19,8 @@ export type SourceInput = { target: Getter; }; -type SourceOutput = { +/** Signals the source derives. */ +export type SourceOutput = { // The catalog text section, or undefined when the broadcast publishes no captions. catalog: Signal; diff --git a/js/watch/src/ui/element.ts b/js/watch/src/ui/element.ts index aace80961e9..ed39bc7516f 100644 --- a/js/watch/src/ui/element.ts +++ b/js/watch/src/ui/element.ts @@ -56,6 +56,7 @@ export default class MoqWatchUi extends HTMLElement { this.#observer = new MutationObserver(() => this.#updateWatch()); } + /** Called by the browser when the element joins a document. */ connectedCallback() { this.#updateWatch(); this.#observer.observe(this, { childList: true }); @@ -65,6 +66,7 @@ export default class MoqWatchUi extends HTMLElement { signals.run(this.#render.bind(this)); } + /** Called by the browser when the element leaves its document. */ disconnectedCallback() { this.#observer.disconnect(); this.#signals?.close(); diff --git a/js/watch/src/video/decoder.ts b/js/watch/src/video/decoder.ts index 76b186bd2e3..5e5b73138d7 100644 --- a/js/watch/src/video/decoder.ts +++ b/js/watch/src/video/decoder.ts @@ -55,7 +55,8 @@ export interface Stats { bytesReceived: number; } -type DecoderOutput = { +/** Signals the decoder derives. */ +export type DecoderOutput = { /** Fatal decode failure, cleared when another source is selected. */ error: Signal; // The current frame to render. @@ -843,6 +844,7 @@ function hardwareAcceleration(config: { interlaced?: boolean }): HardwareAcceler return config.interlaced ? "prefer-software" : undefined; } +/** Whether the WebCodecs video decoder can play this config. */ async function supported(config: Catalog.VideoConfig): Promise { if (!Catalog.containerSupported(config.container)) { // `kind` is the literal "unknown" tag; the container the publisher actually named is in `raw`. diff --git a/js/watch/src/video/source.ts b/js/watch/src/video/source.ts index 3c4fa40cd75..c9e035e052d 100644 --- a/js/watch/src/video/source.ts +++ b/js/watch/src/video/source.ts @@ -48,7 +48,8 @@ export type SourceInput = { probe: Getter; }; -type SourceOutput = { +/** Signals the source derives. */ +export type SourceOutput = { catalog: Signal; available: Signal>; diff --git a/quest/m1/api-extractor-checks.md b/quest/m1/api-extractor-checks.md index 05a61d0633f..b3d51642042 100644 --- a/quest/m1/api-extractor-checks.md +++ b/quest/m1/api-extractor-checks.md @@ -33,25 +33,26 @@ Decided 2026-10-23 (maintainer interview): and dropping an export's doc comment must each fail `just check`. - Rust is a non-goal: docs.rs and cargo-semver-checks cover it. -Implementation checkpoint: strict compiler, extractor, and TSDoc messages are -wired into the shared report configuration. The JSR `@module` tag is defined -and translated to `@packageDocumentation` in the isolated declaration copy; -focused fixtures cover missing exports, stripped names, and undocumented -exports. The old checkers remain until the replacement can pass the workspace. - -Open decision: the isolated copy intentionally cannot resolve external -packages, so strict compiler diagnostics reject every bare dependency import -with TS2307. Choose whether to preserve isolation with narrowly scoped external -module diagnostics, or resolve declared dependency types without relying on -sibling packages having been built. The former keeps today's independent -reports and is the smaller change, but makes the unresolved-declaration check -explicitly local to the package. No diagnostic exception is implemented yet. - -Remaining after that decision: migrate existing release tags and TSDoc syntax, -replace private-helper `typeof` references in public static method bags with -explicit signatures, fix any other exposed public declarations without -expanding exports unnecessarily, remove `docs.ts` and `declarations.ts` with -their superseded tests, and pass `just check` and `just ci`. +Decided 2026-10-25 (maintainer): resolve declared dependency types without +requiring sibling packages to be built, accepting a broader redesign of the +analysis and its inputs, rather than scoping external-module diagnostics. +Reason: an unresolved declaration should fail wherever it is, not only inside +the package, and no blanket suppression of external-module diagnostics. + +- The `dist/` copy gets a `node_modules` holding only the declared + dependencies, peer and optional dependencies, linked to their workspace + install. A workspace sibling resolves to its source through its `exports`, + so it never needs to be built; an undeclared import fails with TS2307. +- A dependency's own declarations are checked by its own build: messages + located in files outside the copy are ignored, by location, not by code. +- One compiler state covers every entrypoint. A forgotten export is accepted + when every same-named declaration in this package the reporting signature + references is nameable from some entrypoint: exported, a namespace member, + or renamed by a nameable declaration (`type A = B`, `x: typeof f`). +- `export * as X` is rewritten to import-then-export, since API Extractor + treats each namespace re-export as a new namespace. +- `ae-missing-release-tag` is off (`@internal` is the only tier) and + `ae-unresolved-link` is off (JSR resolves links in lexical scope). ## Related diff --git a/quest/m2/audit-docs.md b/quest/m2/audit-docs.md index 6dca30e50b1..ef9e7ce7550 100644 --- a/quest/m2/audit-docs.md +++ b/quest/m2/audit-docs.md @@ -41,11 +41,10 @@ freshest. Baselines: unlinted for their macOS, Windows, and Android items. `moq-gst` has 3 items from `gst::plugin_define!`. `moq-v4l` reports 3108, nearly all its generated `sys` bindings; whether the fork earns docs is still undecided. -- JS: since [docs-js](https://github.com/moq-dev/moq/pull/6163), every - published package's build runs `js/common/docs.ts`, which fails on an - undocumented export or public class member, so check only that its - exemptions (private, protected, symbol brands, and custom element reactions) - still hold up and that docs say something. +- JS: every published package's build runs API Extractor through + `js/common/api.ts`, which fails on an undocumented API item, so check only + that its exemptions (`ae-missing-release-tag`, `ae-unresolved-link`) still + hold up and that docs say something. - Links: GET (not HEAD) every external URL in `doc/` with a browser user agent. 316 URLs: all answered except placeholder and local hosts, relay URLs that only speak MoQ, npmjs.com and w3.org pages that refuse diff --git a/sh/js/workspace.py b/sh/js/workspace.py index cb0e29ff011..1a472c79775 100644 --- a/sh/js/workspace.py +++ b/sh/js/workspace.py @@ -144,8 +144,8 @@ def scripts(verb): command("bun", "install", "--frozen-lockfile") if action == "test": command("python3", "sh/js/playwright.test.py") - command("bun", "test", "js/common/api.test.ts", "js/common/declarations.test.ts", "js/common/deps.test.ts", - "js/common/docs.test.ts", "js/common/worklet.test.ts", "js/common/release.test.ts") + command("bun", "test", "js/common/api.test.ts", "js/common/deps.test.ts", "js/common/worklet.test.ts", + "js/common/release.test.ts") scripts("test") return if action == "build": From 0c5ed5813a4f39b74cfce79cae8a1fcbbe5e0e43 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 25 Oct 2026 16:22:20 -0700 Subject: [PATCH 4/5] chore(quest): complete the API Extractor checks quest Co-Authored-By: Claude Opus 5.5 --- quest/m1/README.md | 1 - quest/m1/api-extractor-checks.md | 59 -------------------------------- quest/m1/js-api-reference.md | 9 ++--- 3 files changed, 3 insertions(+), 66 deletions(-) delete mode 100644 quest/m1/api-extractor-checks.md diff --git a/quest/m1/README.md b/quest/m1/README.md index fed911f4ff8..fdc1528bf11 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -138,7 +138,6 @@ Catalog HLS field. - [CI housekeeping](/quest/m1/ci-housekeeping.md) - validate queue nextest at 24 threads and remove the actionlint queue ignore after its release - [Main is no slower than release](/quest/m1/release-perf/README.md) - every benchmark where main is slower than release is fixed or accepted with a reason, checked by a final paired run before the cut - [Drop announce="never"](/quest/m1/publish-announce-never.md) - `@moq/publish` offers only announce modes a watcher can reach -- [API Extractor checks](/quest/m1/api-extractor-checks.md) - API Extractor fails a PR on a forgotten export, an unresolved declaration, or an undocumented export, replacing the hand-rolled `.d.ts` checkers - [Generated JS API reference](/quest/m1/js-api-reference.md) - the doc site renders an API reference for every `@moq/*` package from API Extractor's doc model - [Interop coverage](/quest/m1/interop-coverage/README.md) - the riskiest moq-transport features moq-net exposes get cross-implementation tests over drafts 18 and 22 - [AMF0 exact reads](/quest/m1/rtmp-amf0-exact-reads.md) - a truncated RTMP string fails with `UnexpectedEof` instead of parsing NUL padding diff --git a/quest/m1/api-extractor-checks.md b/quest/m1/api-extractor-checks.md deleted file mode 100644 index b3d51642042..00000000000 --- a/quest/m1/api-extractor-checks.md +++ /dev/null @@ -1,59 +0,0 @@ -# [M] API Extractor checks for @moq/* declarations - -## Goal - -Every published `@moq/*` entrypoint is checked by API Extractor on every PR, -with its messages as errors: a type the public API uses but does not export -(`ae-forgotten-export`), a declaration that does not resolve, and an exported -item without a doc comment (`ae-undocumented`) fail the build. -`js/common/docs.ts` and `js/common/declarations.ts` are deleted. - -## Plan - -Decided 2026-10-23 (maintainer interview): - -- Builds on the shared API Extractor config in `js/common/api.ts` and the - committed `.api.md` reports that - [moq-dev/moq#6477](https://github.com/moq-dev/moq/pull/6477) added. One - config serves the reports, these checks, and the - [reference](/quest/m1/js-api-reference.md); do not add a second. It - analyzes a copy of `dist/` with no `node_modules`, so a package's report - never depends on its dependencies being built, and silences every message - for now. -- Keep only the rules API Extractor enforces. A `docs.ts` rule with no - API Extractor equivalent is dropped, not kept in a reduced checker. -- JSR reads `@module` blocks, so define `@module` in `tsdoc.json` instead of - switching entrypoints to `@packageDocumentation`. API Extractor reads an - entrypoint's summary only from a block tagged `@packageDocumentation`, so - add that tag beside `@module` (or an equivalent transform) to keep module - summaries in the doc model for the reference. -- `stripInternal` stays: rolling declarations up with release tags - (`dtsRollup`) is a non-goal. -- Prove the replacement: reintroducing the `@moq/auth` `AccessInput` bug - and dropping an export's doc comment must each fail `just check`. -- Rust is a non-goal: docs.rs and cargo-semver-checks cover it. - -Decided 2026-10-25 (maintainer): resolve declared dependency types without -requiring sibling packages to be built, accepting a broader redesign of the -analysis and its inputs, rather than scoping external-module diagnostics. -Reason: an unresolved declaration should fail wherever it is, not only inside -the package, and no blanket suppression of external-module diagnostics. - -- The `dist/` copy gets a `node_modules` holding only the declared - dependencies, peer and optional dependencies, linked to their workspace - install. A workspace sibling resolves to its source through its `exports`, - so it never needs to be built; an undeclared import fails with TS2307. -- A dependency's own declarations are checked by its own build: messages - located in files outside the copy are ignored, by location, not by code. -- One compiler state covers every entrypoint. A forgotten export is accepted - when every same-named declaration in this package the reporting signature - references is nameable from some entrypoint: exported, a namespace member, - or renamed by a nameable declaration (`type A = B`, `x: typeof f`). -- `export * as X` is rewritten to import-then-export, since API Extractor - treats each namespace re-export as a new namespace. -- `ae-missing-release-tag` is off (`@internal` is the only tier) and - `ae-unresolved-link` is off (JSR resolves links in lexical scope). - -## Related - -- [Generated JS API reference](/quest/m1/js-api-reference.md) - renders the doc model from the same config diff --git a/quest/m1/js-api-reference.md b/quest/m1/js-api-reference.md index 3f1643554e8..2d9d2f098e1 100644 --- a/quest/m1/js-api-reference.md +++ b/quest/m1/js-api-reference.md @@ -12,8 +12,9 @@ page under `doc/lib/js/` links its reference. Decided 2026-10-23 (maintainer interview): - API Extractor's doc model (`.api.json`), from the shared per-package config - that [the checks](/quest/m1/api-extractor-checks.md) finish, is the only - source. The reference is TSDoc next to the code, rendered; update the + in `js/common/api.ts`, is the only source. That config turns + `ae-unresolved-link` off, so links the reference renders may need fixing. + The reference is TSDoc next to the code, rendered; update the "not the reference" line in `doc/AGENTS.md` to say so. - Our own renderer, not api-documenter: a small script turns the doc model into VitePress pages styled like the rest of the site. @@ -23,7 +24,3 @@ Decided 2026-10-23 (maintainer interview): matches the guides beside it. Nothing generated is committed. - JSR keeps publishing its own reference; this does not replace it. - Rust is a non-goal: docs.rs covers it. - -## Required - -- [API Extractor checks](/quest/m1/api-extractor-checks.md) - finishes the shared config and makes every exported item documented From 851378ca843f1fd9099d3701e8125248468dda72 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 25 Oct 2026 16:48:27 -0700 Subject: [PATCH 5/5] chore(js): type the compiler API API Extractor leaves unknown API Extractor types its program `unknown`, so the checks libav's build script runs failed to typecheck. Declare the parts of the TypeScript compiler API the analysis uses. Co-Authored-By: Claude Opus 5.5 --- js/common/api.ts | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/js/common/api.ts b/js/common/api.ts index 90b9edab4ce..7322f8de0b3 100644 --- a/js/common/api.ts +++ b/js/common/api.ts @@ -84,7 +84,7 @@ function reports(dir: string): Map { additionalEntryPoints: entries.map(({ entrypoint }) => entrypoint), }); const named = nameable( - compilerState.program, + compilerState.program as Program, entries.map(({ entrypoint }) => entrypoint), ); @@ -124,10 +124,35 @@ function installation(dir: string, name: string): string | undefined { } } -type Program = CompilerState["program"]; -type Checker = ReturnType; -type Node = Parameters[0]; -type Symbol = NonNullable>; +// The parts of the TypeScript compiler API used here. API Extractor types its program `unknown` +// rather than expose the TypeScript it bundles. +interface Program { + getTypeChecker(): Checker; + getSourceFile(path: string): SourceFile | undefined; +} +interface Checker { + getSymbolAtLocation(node: Node): Symbol | undefined; + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(symbol: Symbol): Symbol[]; +} +interface Node { + kind: number; + end: number; + parent: Node; + getChildren(): Node[]; + getStart(): number; + getText(): string; + getSourceFile(): SourceFile; +} +interface SourceFile extends Node { + fileName: string; + getPositionOfLineAndCharacter(line: number, character: number): number; +} +interface Symbol { + flags: number; + name: string; + declarations?: Node[]; +} // The TypeScript that API Extractor bundles and built the program with. const ts: { @@ -358,7 +383,7 @@ function extract( name && line && column && - nameableReference(compilerState.program, root, named, path, line, column, name) + nameableReference(compilerState.program as Program, root, named, path, line, column, name) ) { message.logLevel = ExtractorLogLevel.None; }