From b808dbb8acc44dfedce9754e4ac1215613fb1e8f Mon Sep 17 00:00:00 2001 From: Kinflou Date: Sun, 15 Nov 2026 07:00:29 +0800 Subject: [PATCH 1/2] runtime tests: record what the generated fixtures put on the wire The schema digests, the package's connection digest, the Hello, the protocols' numbers and the calls' numbers and names, read from the blessed fixtures and compared with a record taken from the generator as it stands. A change to how generated code is laid out has to leave all of it as it is. --- runtime/test/wire-invariance.json | 647 +++++++++++++++++++++++++++ runtime/test/wire-invariance.test.ts | 144 ++++++ 2 files changed, 791 insertions(+) create mode 100644 runtime/test/wire-invariance.json create mode 100644 runtime/test/wire-invariance.test.ts diff --git a/runtime/test/wire-invariance.json b/runtime/test/wire-invariance.json new file mode 100644 index 0000000..8d8943e --- /dev/null +++ b/runtime/test/wire-invariance.json @@ -0,0 +1,647 @@ +{ + "acme-encodings.ts": { + "files": {}, + "connectionIrHash": [], + "hello": [], + "format": [] + }, + "acme.ts": { + "files": { + "acme.ts": { + "irHash": "0x5d4d4284d465589e", + "callTables": { + "CHAT_CALLS": [ + "send", + "history", + "wipe", + "note" + ] + }, + "callsWritten": [ + "0 send", + "1 history", + "2 wipe", + "3 note" + ], + "callsTaken": [ + 0, + 1, + 2, + 3 + ] + } + }, + "connectionIrHash": [], + "hello": [], + "format": [ + "CborCodec" + ] + }, + "bounds.ts": { + "files": { + "bounds.ts": { + "irHash": "0x17305ca8c4eea701", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "DIRECTORY_CALLS": [ + "find", + "tree" + ] + }, + "callsWritten": [ + "0 find", + "1 tree" + ], + "callsTaken": [ + 0, + 1 + ] + } + }, + "connectionIrHash": [ + "0x17305ca8c4eea701" + ], + "hello": [], + "format": [ + "PackedCodec" + ] + }, + "chat.ts": { + "files": { + "chat.ts": { + "irHash": "0xed1189b980d9a3f8", + "callTables": { + "CHAT_CALLS": [ + "send", + "history", + "wipe", + "note" + ] + }, + "callsWritten": [ + "0 send", + "1 history", + "2 wipe", + "3 note" + ], + "callsTaken": [ + 0, + 1, + 2, + 3 + ] + } + }, + "connectionIrHash": [], + "hello": [], + "format": [ + "PackedCodec" + ] + }, + "clash/": { + "files": { + "clash/api.ts": { + "irHash": "0xa14195a41e817a01", + "protocolNumbers": [ + 0, + 0, + 1, + 1 + ], + "callTables": { + "CHAT_CALLS": [ + "greet" + ], + "EVENTS_CALLS": [ + "notify" + ] + }, + "callsWritten": [ + "0 greet", + "0 notify" + ], + "callsTaken": [ + 0, + 0 + ] + }, + "clash/localdeps/greeting.ts": { + "irHash": "0x3c4249f5704f3397", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "FOO_CALLS": [ + "greet" + ] + }, + "callsWritten": [ + "0 greet" + ], + "callsTaken": [ + 0 + ] + } + }, + "connectionIrHash": [ + "0xe9ca523b62a2c19f" + ], + "hello": [ + "434f0201000123456789abcdef0123456789abcdef00010000030052185fd60992ad43029cc29962b3afb401ffa14eb2bc0ae6184d69b5acc570917e0258809aaf4b47d56c69b2c1fc9d4330c102000001005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a0100010001005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a0100" + ], + "format": [ + "PackedCodec" + ] + }, + "collisions/": { + "files": { + "collisions/shapes.ts": { + "irHash": "0xe84d76dcf6442bd3", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "WIRE_CALLS": [ + "then", + "constructor", + "peer", + "client" + ], + "LOCK_CALLS": [ + "then", + "client", + "peer" + ] + }, + "callsWritten": [ + "0 then", + "1 constructor", + "2 peer", + "3 client", + "0 then", + "1 client", + "2 peer" + ], + "callsTaken": [ + 0, + 1, + 2, + 3, + 0, + 1, + 2 + ] + }, + "collisions/user.ts": { + "irHash": "0x2581145250fde0c6", + "protocolNumbers": [ + 2, + 2 + ], + "callTables": { + "AGAIN_CALLS": [ + "get" + ] + }, + "callsWritten": [ + "0 get" + ], + "callsTaken": [ + 0 + ] + } + }, + "connectionIrHash": [ + "0x9dffbf799cccf0f4" + ], + "hello": [], + "format": [ + "PackedCodec" + ] + }, + "comline2/alien/": { + "files": { + "comline2/alien/chat.ts": { + "irHash": "0x70132e163503db63", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "CHAT_CALLS": [ + "hello", + "shout" + ] + }, + "callsWritten": [ + "0 hello", + "1 shout" + ], + "callsTaken": [ + 0, + 1 + ] + } + }, + "connectionIrHash": [ + "0x70132e163503db63" + ], + "hello": [ + "434f020100fedcba9876543210fedcba987654321000010000030052185fd60992ad43029cc29962b3afb4014e6ede7cc8f5aa52ce169f9e656740e20258809aaf4b47d56c69b2c1fc9d4330c10100000100aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa020001" + ], + "format": [ + "PackedCodec" + ] + }, + "comline2/new/": { + "files": { + "comline2/new/chat.ts": { + "irHash": "0xe21c2f843f183318", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "CHAT_CALLS": [ + "shout", + "whisper", + "hello" + ] + }, + "callsWritten": [ + "1 shout", + "2 whisper", + "0 hello" + ], + "callsTaken": [ + 1, + 2, + 0 + ] + } + }, + "connectionIrHash": [ + "0xe21c2f843f183318" + ], + "hello": [ + "434f0201000123456789abcdef0123456789abcdef00020000030052185fd60992ad43029cc29962b3afb4014e6ede7cc8f5aa52ce169f9e656740e20258809aaf4b47d56c69b2c1fc9d4330c10100000100bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb03000102" + ], + "format": [ + "PackedCodec" + ] + }, + "comline2/old/": { + "files": { + "comline2/old/chat.ts": { + "irHash": "0x70132e163503db63", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "CHAT_CALLS": [ + "hello", + "shout" + ] + }, + "callsWritten": [ + "0 hello", + "1 shout" + ], + "callsTaken": [ + 0, + 1 + ] + } + }, + "connectionIrHash": [ + "0x70132e163503db63" + ], + "hello": [ + "434f0201000123456789abcdef0123456789abcdef00010000030052185fd60992ad43029cc29962b3afb4014e6ede7cc8f5aa52ce169f9e656740e20258809aaf4b47d56c69b2c1fc9d4330c10100000100aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa020001" + ], + "format": [ + "PackedCodec" + ] + }, + "dependency": { + "files": { + "dependency/only/localdeps/greeting.ts": { + "irHash": "0x653ed335b8ab7ba0", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "FOO_CALLS": [ + "greet" + ] + }, + "callsWritten": [ + "0 greet" + ], + "callsTaken": [ + 0 + ] + } + }, + "connectionIrHash": [ + "0xc1fed94bf808faea" + ], + "hello": [], + "format": [ + "PackedCodec" + ] + }, + "dependency/own/": { + "files": { + "dependency/own/api.ts": { + "irHash": "0x25f4c4d936e7aa90", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "CHAT_CALLS": [ + "greet" + ] + }, + "callsWritten": [ + "0 greet" + ], + "callsTaken": [ + 0 + ] + }, + "dependency/own/localdeps/greeting.ts": { + "irHash": "0x653ed335b8ab7ba0", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "FOO_CALLS": [ + "greet" + ] + }, + "callsWritten": [ + "0 greet" + ], + "callsTaken": [ + 0 + ] + } + }, + "connectionIrHash": [ + "0x55e3b94344a9c775" + ], + "hello": [ + "434f0201000123456789abcdef0123456789abcdef00010000030052185fd60992ad43029cc29962b3afb4014e6ede7cc8f5aa52ce169f9e656740e20258809aaf4b47d56c69b2c1fc9d4330c101000001005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a0100" + ], + "format": [ + "PackedCodec" + ] + }, + "hello/": { + "files": { + "hello/hello.ts": { + "irHash": "0xe3d09136af39a1c1", + "protocolNumbers": [ + 1, + 1 + ], + "callTables": { + "CLOCK_CALLS": [ + "now" + ], + "LINK_CALLS": [ + "now" + ] + }, + "callsWritten": [ + "0 now", + "0 now" + ], + "callsTaken": [ + 0, + 0 + ] + } + }, + "connectionIrHash": [ + "0xe3d09136af39a1c1" + ], + "hello": [], + "format": [ + "PackedCodec" + ] + }, + "link.ts": { + "files": { + "link.ts": { + "irHash": "0x9704f8e8a43acdbd", + "protocolNumbers": [ + 0, + 0, + 1, + 1 + ], + "callTables": { + "CHAT_CALLS": [ + "send", + "count" + ], + "EVENTS_CALLS": [ + "message", + "ping" + ] + }, + "callsWritten": [ + "0 send", + "1 count", + "0 message", + "1 ping" + ], + "callsTaken": [ + 0, + 1, + 0, + 1 + ] + } + }, + "connectionIrHash": [ + "0x9704f8e8a43acdbd" + ], + "hello": [], + "format": [ + "PackedCodec" + ] + }, + "link_jsonrpc.ts": { + "files": { + "link_jsonrpc.ts": { + "irHash": "0xb4520b20f67b5ccb", + "protocolNumbers": [ + 0, + 0, + 1, + 1 + ], + "callTables": { + "CHAT_CALLS": [ + "send", + "count" + ], + "EVENTS_CALLS": [ + "link.Events/message", + "link.Events/ping" + ] + }, + "callsWritten": [ + "0 send", + "1 count", + "0 link.Events/message", + "1 link.Events/ping" + ], + "callsTaken": [ + 0, + 1, + 0, + 1 + ] + } + }, + "connectionIrHash": [ + "0xb4520b20f67b5ccb" + ], + "hello": [], + "format": [] + }, + "nested/": { + "files": { + "nested/chat/admin.ts": { + "irHash": "0xa6f61afefe65d74a", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "ADMIN_CALLS": [ + "greet" + ] + }, + "callsWritten": [ + "0 greet" + ], + "callsTaken": [ + 0 + ] + } + }, + "connectionIrHash": [ + "0xa6f61afefe65d74a" + ], + "hello": [ + "434f0201000123456789abcdef0123456789abcdef00010000030052185fd60992ad43029cc29962b3afb4014e6ede7cc8f5aa52ce169f9e656740e20258809aaf4b47d56c69b2c1fc9d4330c101000001005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a0100" + ], + "format": [ + "PackedCodec" + ] + }, + "reserved/": { + "files": { + "reserved/names.ts": { + "irHash": "0xc4c5bf4244cbec4a", + "protocolNumbers": [ + 0, + 0 + ], + "callTables": { + "STATIC_CALLS": [ + "typeof" + ] + }, + "callsWritten": [ + "0 typeof" + ], + "callsTaken": [ + 0 + ] + } + }, + "connectionIrHash": [ + "0xc579d2e8df3a409b" + ], + "hello": [], + "format": [ + "PackedCodec" + ] + }, + "services/": { + "files": { + "services/game.ts": { + "irHash": "0x0e7319ed91fcea68", + "protocolNumbers": [ + 0, + 0, + 1, + 1 + ], + "callTables": { + "ACCOUNT_CALLS": [ + "login" + ], + "PLAYER_CALLS": [ + "level" + ] + }, + "callsWritten": [ + "0 login", + "0 level" + ], + "callsTaken": [ + 0, + 0 + ] + }, + "services/items.ts": { + "irHash": "0x5c9c55a1bd9938af", + "protocolNumbers": [ + 2, + 2, + 3, + 3 + ], + "callTables": { + "INVENTORY_CALLS": [ + "items" + ], + "EVENTS_CALLS": [ + "changed" + ] + }, + "callsWritten": [ + "0 items", + "0 changed" + ], + "callsTaken": [ + 0, + 0 + ] + } + }, + "connectionIrHash": [ + "0x795ece8a736e83e2" + ], + "hello": [], + "format": [ + "PackedCodec" + ] + } +} diff --git a/runtime/test/wire-invariance.test.ts b/runtime/test/wire-invariance.test.ts new file mode 100644 index 0000000..c14fd2b --- /dev/null +++ b/runtime/test/wire-invariance.test.ts @@ -0,0 +1,144 @@ +// What the generated code puts on the wire - the schema digests, the package's +// connection digest, this end's `comline@2` Hello, the protocols' wire numbers +// and the calls' numbers and names - recorded in `wire-invariance.json` from +// the generator's output, and compared against the blessed fixtures in +// `generated/`. Changing how generated code is *laid out* (where a constant is +// defined, what is marked `@internal`, which comments it carries) must not +// move any of it: a changed value means a changed wire. +// +// Read from the fixtures' source text rather than by importing them, which a +// fixture naming a third-party package (`acme-encodings`) can't be. +// +// A change that moves the wire on purpose re-records it: +// `WIRE_INVARIANCE_BLESS=1 npm test`. + +import assert from "node:assert/strict"; +import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { test } from "node:test"; + +const RUNTIME = new URL("../../", import.meta.url); +const GENERATED = new URL("test/generated/", RUNTIME); +const RECORD = new URL("test/wire-invariance.json", RUNTIME); + +/** What one generated file says about the wire; absent where it says nothing. */ +interface FileFacts { + /** `IR_HASH`: the digest of the schema the file was generated from. */ + irHash?: string; + /** Each `PROTOCOL = N` in the file, in order: a protocol's number on a connection. */ + protocolNumbers?: number[]; + /** Each `_CALLS` table: the names a call is matched by. */ + callTables?: Record; + /** Each `{ id: N, name: "x" }` a sender writes. */ + callsWritten?: string[]; + /** Each `case N:` a dispatcher takes. */ + callsTaken?: number[]; +} + +/** What a fixture - a directory, or a file at the top - says about the wire as a whole. */ +interface ShapeFacts { + files: Record; + /** Every distinct `CONNECTION_IR_HASH` the shape defines: one, the package's. */ + connectionIrHash: string[]; + /** Every distinct `HELLO`, as hex. */ + hello: string[]; + /** Every distinct codec `Format` is built from. */ + format: string[]; +} + +function sources(dir: URL, prefix = ""): string[] { + const out: string[] = []; + for (const entry of readdirSync(dir).sort()) { + const path = new URL(entry, dir); + if (statSync(path).isDirectory()) { + out.push(...sources(new URL(`${entry}/`, dir), `${prefix}${entry}/`)); + } else if (entry.endsWith(".ts")) { + out.push(`${prefix}${entry}`); + } + } + return out; +} + +const distinct = (values: string[]): string[] => [...new Set(values)].sort(); +const all = (text: string, pattern: RegExp): RegExpMatchArray[] => [...text.matchAll(pattern)]; + +function factsOf(text: string): { file: FileFacts; connectionIrHash: string[]; hello: string[]; format: string[] } { + const file: FileFacts = {}; + const ir = all(text, /^export const IR_HASH = (0x[0-9a-f]+)n;$/gm); + if (ir[0]) file.irHash = ir[0][1]; + const numbers = all(text, /static readonly PROTOCOL = (\d+);/g).map((m) => Number(m[1])); + if (numbers.length) file.protocolNumbers = numbers; + const tables = all(text, /^export const ([A-Z0-9_]+_CALLS) = \[(.*)\] as const;$/gm); + if (tables.length) { + file.callTables = Object.fromEntries( + tables.map((m) => [m[1]!, [...m[2]!.matchAll(/"([^"]*)"/g)].map((n) => n[1]!)]), + ); + } + const written = all(text, /\{ id: (\d+), name: "([^"]*)" \}/g).map((m) => `${m[1]} ${m[2]}`); + if (written.length) file.callsWritten = written; + const taken = all(text, /^\s+case (\d+): \{$/gm).map((m) => Number(m[1])); + if (taken.length) file.callsTaken = taken; + + const hello = all(text, /export const HELLO = new Uint8Array\(\[([^\]]*)\]\);/g).map((m) => + [...m[1]!.matchAll(/0x([0-9a-f]{2})/g)].map((b) => b[1]).join(""), + ); + return { + file, + connectionIrHash: all(text, /^export const CONNECTION_IR_HASH = (0x[0-9a-f]+)n;$/gm).map((m) => m[1]!), + hello, + format: all(text, /^export const Format: Codec = new (\w+)\(\);$/gm).map((m) => m[1]!), + }; +} + +function record(): Record { + const paths = sources(GENERATED); + // A package is the directory its `connection.ts` is in; without one, a + // fixture is the top-level directory, or the file at the top. + const packages = paths.filter((p) => p.endsWith("/connection.ts")).map((p) => p.slice(0, -"connection.ts".length)); + const shapes = new Map(); + for (const path of paths) { + const root = packages.filter((dir) => path.startsWith(dir)).sort((a, b) => b.length - a.length)[0]; + const slash = path.indexOf("/"); + const shape = root ?? (slash < 0 ? path : path.slice(0, slash)); + shapes.set(shape, [...(shapes.get(shape) ?? []), path]); + } + const out: Record = {}; + for (const [shape, paths] of shapes) { + const facts: ShapeFacts = { files: {}, connectionIrHash: [], hello: [], format: [] }; + const hashes: string[] = []; + const hellos: string[] = []; + const formats: string[] = []; + for (const path of paths) { + const found = factsOf(readFileSync(new URL(path, GENERATED), "utf8")); + if (Object.keys(found.file).length) facts.files[path] = found.file; + hashes.push(...found.connectionIrHash); + hellos.push(...found.hello); + formats.push(...found.format); + } + facts.connectionIrHash = distinct(hashes); + facts.hello = distinct(hellos); + facts.format = distinct(formats); + out[shape] = facts; + } + return out; +} + +test("the generated fixtures' wire constants are the recorded ones", () => { + const current = record(); + if (process.env.WIRE_INVARIANCE_BLESS) { + writeFileSync(RECORD, `${JSON.stringify(current, null, 2)}\n`); + return; + } + const recorded = JSON.parse(readFileSync(RECORD, "utf8")) as Record; + assert.deepEqual(Object.keys(current), Object.keys(recorded), "a fixture was added or removed: re-record"); + for (const shape of Object.keys(recorded)) { + assert.deepEqual(current[shape], recorded[shape], `${shape}: the wire facts moved`); + } +}); + +test("each fixture has one connection digest, one Hello and one format", () => { + for (const [shape, facts] of Object.entries(record())) { + assert.ok(facts.connectionIrHash.length <= 1, `${shape}: ${facts.connectionIrHash.join(", ")}`); + assert.ok(facts.hello.length <= 1, `${shape}: more than one HELLO`); + assert.ok(facts.format.length <= 1, `${shape}: ${facts.format.join(", ")}`); + } +}); From 557d25148385b641a93a0b59662f9991ed453273 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Sun, 15 Nov 2026 07:15:03 +0800 Subject: [PATCH 2/2] Generated TypeScript: name the entry points, mark the plumbing internal, define shared constants once (#170) - A header on connection.ts and, in lib mode, on the root index: what to implement, serve, dial and call for the package's shape, lockstep protocols included. - /** @internal */ on the wire plumbing: params layouts, call tables, HELLO, handshake(), provideServices / provideClientServices, and dispatchers the package's Services builds. Params interfaces and type layouts are not marked: the user-implemented interface and other packages name them, and a consumer's stripInternal would leave their declarations dangling. typecheck:stripped type-checks the stripped declarations. - Format and CONNECTION_IR_HASH are defined once, in wire.ts, when more than one file would define them; connection.ts re-exports them. Not in connection.ts itself: it imports every protocol file, so they would import it back. A lone file keeps its own. - connect()'s doc no longer says it provides services when it takes none. No wire change: wire-invariance.json is unchanged but for the keys of the three fixtures that moved into directories, and for link_jsonrpc/'s newly blessed wire.ts naming the package's declared codec. --- .github/workflows/ci.yml | 4 + codegen/src/generator.rs | 430 ++++++++++++++++-- codegen/tests/generate.rs | 251 ++++++++-- codegen/tests/nested_namespaces.rs | 8 +- runtime/package.json | 3 +- runtime/test/generated-bounds.test.ts | 6 +- runtime/test/generated-connection.test.ts | 6 +- .../test/generated-jsonrpc-connection.test.ts | 6 +- runtime/test/generated/acme.ts | 4 + .../{bounds.ts => bounds/account.ts} | 15 +- runtime/test/generated/bounds/connection.ts | 62 +++ runtime/test/generated/bounds/wire.ts | 14 + runtime/test/generated/chat.ts | 4 + runtime/test/generated/clash/api.ts | 10 +- runtime/test/generated/clash/connection.ts | 40 +- .../generated/clash/localdeps/greeting.ts | 8 +- runtime/test/generated/clash/wire.ts | 14 + .../test/generated/collisions/connection.ts | 33 +- runtime/test/generated/collisions/shapes.ts | 23 +- runtime/test/generated/collisions/user.ts | 14 +- runtime/test/generated/collisions/wire.ts | 14 + runtime/test/generated/comline2/alien/chat.ts | 13 +- .../generated/comline2/alien/connection.ts | 40 +- runtime/test/generated/comline2/alien/wire.ts | 14 + runtime/test/generated/comline2/new/chat.ts | 14 +- .../test/generated/comline2/new/connection.ts | 40 +- runtime/test/generated/comline2/new/wire.ts | 14 + runtime/test/generated/comline2/old/chat.ts | 13 +- .../test/generated/comline2/old/connection.ts | 40 +- runtime/test/generated/comline2/old/wire.ts | 14 + .../dependency/only/localdeps/greeting.ts | 2 + runtime/test/generated/dependency/own/api.ts | 12 +- .../generated/dependency/own/connection.ts | 40 +- .../dependency/own/localdeps/greeting.ts | 13 +- runtime/test/generated/dependency/own/wire.ts | 14 + runtime/test/generated/hello/connection.ts | 33 +- runtime/test/generated/hello/hello.ts | 16 +- runtime/test/generated/hello/wire.ts | 14 + runtime/test/generated/link/connection.ts | 77 ++++ runtime/test/generated/{ => link}/link.ts | 19 +- runtime/test/generated/link/wire.ts | 14 + .../test/generated/link_jsonrpc/connection.ts | 79 ++++ .../{link_jsonrpc.ts => link_jsonrpc/link.ts} | 14 +- runtime/test/generated/link_jsonrpc/wire.ts | 14 + runtime/test/generated/nested/chat/admin.ts | 12 +- runtime/test/generated/nested/connection.ts | 40 +- runtime/test/generated/nested/wire.ts | 14 + runtime/test/generated/reserved/connection.ts | 33 +- runtime/test/generated/reserved/names.ts | 14 +- runtime/test/generated/reserved/wire.ts | 14 + runtime/test/generated/services/connection.ts | 33 +- runtime/test/generated/services/game.ts | 19 +- runtime/test/generated/services/items.ts | 19 +- runtime/test/generated/services/wire.ts | 14 + runtime/test/wire-invariance.json | 16 +- runtime/tsconfig.stripped.json | 13 + 56 files changed, 1395 insertions(+), 378 deletions(-) rename runtime/test/generated/{bounds.ts => bounds/account.ts} (92%) create mode 100644 runtime/test/generated/bounds/connection.ts create mode 100644 runtime/test/generated/bounds/wire.ts create mode 100644 runtime/test/generated/clash/wire.ts create mode 100644 runtime/test/generated/collisions/wire.ts create mode 100644 runtime/test/generated/comline2/alien/wire.ts create mode 100644 runtime/test/generated/comline2/new/wire.ts create mode 100644 runtime/test/generated/comline2/old/wire.ts create mode 100644 runtime/test/generated/dependency/own/wire.ts create mode 100644 runtime/test/generated/hello/wire.ts create mode 100644 runtime/test/generated/link/connection.ts rename runtime/test/generated/{ => link}/link.ts (92%) create mode 100644 runtime/test/generated/link/wire.ts create mode 100644 runtime/test/generated/link_jsonrpc/connection.ts rename runtime/test/generated/{link_jsonrpc.ts => link_jsonrpc/link.ts} (94%) create mode 100644 runtime/test/generated/link_jsonrpc/wire.ts create mode 100644 runtime/test/generated/nested/wire.ts create mode 100644 runtime/test/generated/reserved/wire.ts create mode 100644 runtime/test/generated/services/wire.ts create mode 100644 runtime/tsconfig.stripped.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9e4c4f1..8a3f0d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -107,6 +107,10 @@ jobs: # The generated fixtures, against the built runtime as a consumer sees # it, under the strictest flags and erasable syntax only. - run: npm run typecheck:generated + # What `/** @internal */` marks in that output is plumbing a consumer's + # `stripInternal` may drop from its declarations: their declarations, + # stripped, must still type-check on their own. + - run: npm run typecheck:stripped # The wire conformance vectors are vendored from # ComlineProject/specification at the commit in SPEC_REV; this fails if # the copy was edited. diff --git a/codegen/src/generator.rs b/codegen/src/generator.rs index 206f99c..0049fab 100644 --- a/codegen/src/generator.rs +++ b/codegen/src/generator.rs @@ -128,21 +128,39 @@ pub fn generate_typescript(req: &GenerateRequest) -> Result> for (namespace, units) in emitted { collisions::check(namespace, units, derived_names(units, &req.schemas, &req.dependencies, &req.encodings))?; } + let connection = package_connection(req, emitted); + // The constants every file of the package would otherwise define for + // itself, in a module of their own when more than one would. + let wire = shared_constants(req, emitted, connection.is_some()); + let facts = PackageFacts { + wire, + covered: connection + .iter() + .flat_map(|c| c.server.iter().chain(&c.client)) + .map(|p| (p.namespace.clone(), p.name.clone())) + .collect(), + }; + let package = connection.as_ref().and_then(|c| package_module(&header, req, c, codec, &facts)); // Loose files or a `src/` tree, the package module has a file of its own, // which a schema of that name would be. - let package = package_module(&header, req, emitted, codec); if package.is_some() && emitted.iter().any(|(namespace, _)| namespace == PACKAGE_MODULE) { return Err(eyre::eyre!( "a schema named `{PACKAGE_MODULE}` would be overwritten by the package's \ `{PACKAGE_MODULE}.ts` (its `Services` and `serve`) - rename the schema" )); } + if facts.wire.is_some() && emitted.iter().any(|(namespace, _)| namespace == WIRE_MODULE) { + return Err(eyre::eyre!( + "a schema named `{WIRE_MODULE}` would be overwritten by the package's \ + `{WIRE_MODULE}.ts` (its `Format` and `CONNECTION_IR_HASH`) - rename the schema" + )); + } match req.mode { Mode::Code => Ok(emitted .iter() .map(|(namespace, units)| { - let source = schema_source(&header, namespace, units, req, external_std); + let source = schema_source(&header, namespace, units, req, external_std, &facts); // `code` mode has no manifest to add the dependency to, so // the file says what it needs - the same courtesy the Rust // generator extends for `Cargo.toml`. @@ -163,6 +181,10 @@ pub fn generate_typescript(req: &GenerateRequest) -> Result> path: PathBuf::from(format!("{PACKAGE_MODULE}.ts")), contents, })) + .chain(facts.wire.map(|constants| GeneratedFile { + path: PathBuf::from(format!("{WIRE_MODULE}.ts")), + contents: wire_module(&header, req, constants, codec), + })) .collect()), Mode::Lib => { @@ -173,7 +195,7 @@ pub fn generate_typescript(req: &GenerateRequest) -> Result> // them, including an external `std` this package emits no file // for. let mut sources = tree.emit("src", &TsLayout, &|namespace, units| { - schema_source(&header, namespace, units, req, external_std) + schema_source(&header, namespace, units, req, external_std, &facts) }); // The package module beside the schemas, its names at the root. if let Some(contents) = package { @@ -184,6 +206,31 @@ pub fn generate_typescript(req: &GenerateRequest) -> Result> root.contents.push_str(&format!("export * from \"./{PACKAGE_MODULE}.js\";\n")); sources.push(GeneratedFile { path: PathBuf::from(format!("src/{PACKAGE_MODULE}.ts")), contents }); } + // The shared constants beside it, at the root too: through the + // package module where there is one, which re-exports them. + if let Some(constants) = facts.wire { + if connection.is_none() { + let root = sources + .iter_mut() + .find(|f| f.path == std::path::Path::new("src/index.ts")) + .ok_or_else(|| eyre::eyre!("no root barrel to export the package's `Format` from"))?; + root.contents.push_str(&format!("export * from \"./{WIRE_MODULE}.js\";\n")); + } + sources.push(GeneratedFile { + path: PathBuf::from(format!("src/{WIRE_MODULE}.ts")), + contents: wire_module(&header, req, constants, codec), + }); + } + // What the package's entry says to start from. + if let Some(entry) = entry_points(req, emitted, connection.as_ref()) { + let root = sources + .iter_mut() + .find(|f| f.path == std::path::Path::new("src/index.ts")) + .ok_or_else(|| eyre::eyre!("no root barrel to name the package's entry points in"))?; + // After the generated header's own lines, before the exports. + let at = root.contents.find("\n\n").map_or(0, |i| i + 2); + root.contents.insert_str(at, &format!("{entry}\n")); + } // A protocol needs the runtime. A type's `Layout` only names it // in an erased `import type`, so types alone make it an optional // peer: whoever encodes them has the runtime already. @@ -498,6 +545,7 @@ fn schema_source( units: &[FrozenUnit], req: &GenerateRequest, external_std: bool, + package: &PackageFacts, ) -> String { let schemas = &req.schemas; let encodings = &req.encodings; @@ -581,6 +629,9 @@ fn schema_source( addressing, &errors, &types, + // Built by the package's `provideServices`, not by a user. + package.covered.contains(&(namespace.to_string(), name.clone())), + package.wire.map(|_| relative_specifier(namespace, WIRE_MODULE)), )); } _ => {} @@ -641,7 +692,8 @@ fn schema_source( for pick in picks.iter().filter(|p| !p.jsonrpc).chain(picks.iter().filter(|p| p.jsonrpc)) { import_class(encodings, &pick.name, &mut values, &mut external); } - if formatted { + // The package's codec, where this file defines `Format` itself. + if formatted && package.wire.is_none() { import_class(encodings, &req.wire_format, &mut values, &mut external); } if picks.iter().any(|p| p.json) { @@ -685,6 +737,13 @@ fn schema_source( } runtime_import.push_str("} from \"@comline/runtime\";\n\n"); runtime_import.push_str(&external_imports(&external, |name| types.binding(name))); + // Its helpers' default codec, from where the package defines it. + if package.wire.is_some() && picks.iter().any(|p| !p.json) { + runtime_import.push_str(&format!( + "import {{ Format }} from \"{}\";\n\n", + relative_specifier(namespace, WIRE_MODULE) + )); + } ir_hash.push_str(&format!( "/** Canonical digest of the frozen IR this file was generated from — the\n\ @@ -692,7 +751,8 @@ fn schema_source( export const IR_HASH = {:#018x}n;\n\n", schema_ir_hash(units) )); - if has_connection { + // Defined here unless the package keeps them in a module of their own. + if has_connection && package.wire.is_none() { ir_hash.push_str(&format!( "/** Digest of every schema in the package — what a connection's handshake\n\ * checks, so both ends agree on each protocol's number. */\n\ @@ -700,7 +760,7 @@ fn schema_source( connections::connection_ir_hash(schemas) )); } - if formatted { + if formatted && package.wire.is_none() { ir_hash.push_str(&format!( "/** The package's wire format (`wire.format`): what this file's helpers\n\ * encode with, and what the peer has to speak too. */\n\ @@ -1095,14 +1155,22 @@ fn annotation<'a>(parameters: &'a [FrozenUnit], key: &str) -> Option)], codec: &str) -> Option { +struct EmittedConnection { + package: connections::PackageConnection, + server: Vec, + client: Vec, +} + +fn package_connection(req: &GenerateRequest, emitted: &[(String, Vec)]) -> Option { let package = connections::package_connection_among(&req.schemas, &req.dependencies).ok()??; - // Only what this package emits: an external `std` provides nothing here. let emitted_only = |side: &[connections::Provided]| -> Vec { side.iter().filter(|p| emitted.iter().any(|(ns, _)| *ns == p.namespace)).cloned().collect() }; @@ -1110,6 +1178,110 @@ fn package_module(header: &str, req: &GenerateRequest, emitted: &[(String, Vec Constants { + let mut constants = Constants::default(); + for unit in units { + if let FrozenUnit::Protocol { parameters, .. } = unit { + constants.format |= !writes_json(parameters, &req.encodings); + constants.connection_hash |= + connections::on_connection_among(&req.schemas, &req.dependencies, parameters); + } + } + constants +} + +/// What the files of the package would each define for themselves - every +/// protocol file that needs them, and the package module, which defines both - +/// when it is more than one file: those go in a module of their own, which +/// they import from. A lone file keeps its own, so a package of one protocol +/// file reads as it always did. +/// +/// A module of their own rather than `connection.ts`: the package module +/// imports every protocol's file (it builds their dispatchers), so a protocol +/// file importing it back would be an import cycle. +fn shared_constants(req: &GenerateRequest, emitted: &[(String, Vec)], has_package_module: bool) -> Option { + let mut formats = usize::from(has_package_module); + let mut hashes = usize::from(has_package_module); + for (_, units) in emitted { + let constants = constants_of(units, req); + formats += usize::from(constants.format); + hashes += usize::from(constants.connection_hash); + } + // One digest is defined once whoever needs it, and so is the format. + (formats > 1 || hashes > 1).then_some(Constants { format: formats > 0, connection_hash: hashes > 0 }) +} + +/// What a schema file needs to know about the package it is part of. +struct PackageFacts { + /// The constants defined in the module of their own, when there is one. + wire: Option, + /// The protocols (namespace, name) the package's `Services` and + /// `ClientServices` provide: their dispatchers are built by + /// `provideServices`, not by a user. + covered: BTreeSet<(String, String)>, +} + +/// The module of shared constants: the package's wire format and the digest +/// of every schema in it. +fn wire_module(header: &str, req: &GenerateRequest, constants: Constants, codec: &str) -> String { + let encodings = &req.encodings; + let mut values: Vec<&str> = Vec::new(); + let mut external: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); + if constants.format { + import_class(encodings, &req.wire_format, &mut values, &mut external); + } + let mut s = format!("{header}\n"); + if constants.format { + s.push_str("import {\n"); + for v in &values { + s.push_str(&format!(" {v},\n")); + } + s.push_str(" type Codec,\n} from \"@comline/runtime\";\n"); + s.push_str(&external_imports(&external, str::to_string)); + if external.is_empty() { + s.push('\n'); + } + s.push_str(&format!( + "/** The package's wire format (`wire.format`). */\n\ + export const Format: Codec = new {codec}();\n\n" + )); + } + if constants.connection_hash { + s.push_str(&format!( + "/** Digest of every schema in the package — what a connection's handshake\n\ + * checks, so both ends agree on each protocol's number. */\n\ + export const CONNECTION_IR_HASH = {:#018x}n;\n", + connections::connection_ir_hash(&req.schemas) + )); + } + s +} + +/// The package module's source: `connection.ts`. +fn package_module( + header: &str, + req: &GenerateRequest, + connection: &EmittedConnection, + codec: &str, + facts: &PackageFacts, +) -> Option { + let package = &connection.package; + let (server, client) = (&connection.server, &connection.client); let jsonrpc = package.framing == FRAMING_JSONRPC; let datagram3 = package.framing == comline_codegen::facts::FRAMING_DATAGRAM3; let unverified = package.handshake == HANDSHAKE_NONE; @@ -1133,7 +1305,10 @@ fn package_module(header: &str, req: &GenerateRequest, emitted: &[(String, Vec = server.iter().chain(&client).map(|p| p.namespace.as_str()).collect(); + let namespaces: BTreeSet<&str> = server.iter().chain(client.iter()).map(|p| p.namespace.as_str()).collect(); for namespace in &namespaces { s.push_str(&format!( "import * as {} from \"{}\";\n", @@ -1168,17 +1345,29 @@ fn package_module(header: &str, req: &GenerateRequest, emitted: &[(String, Vec {{\n\ \x20 await (await accept({pass})).closed;\n\ }}\n\n\ - /**\n\ - * Dial over `transport`: run the handshake, then provide every protocol in\n\ - * `services`, which the server calls. Call the server's protocols through\n\ - * their senders.\n\ - */\n\ + {dial_doc}\ export async function connect({client_params}): Promise {{\n\ {opening}\ \x20 const conn = {};\n\ @@ -1284,6 +1485,139 @@ fn package_module(header: &str, req: &GenerateRequest, emitted: &[(String, Vec String { + match spelling { + Spelling::Beside => name.to_string(), + Spelling::Barrel => format!("{}.{name}", namespace.split('/').collect::>().join(".")), + } +} + +/// The first call a protocol declares, to show a call in the header. +fn first_call(req: &GenerateRequest, namespace: &str, name: &str) -> Option { + let (_, units) = req.schemas.iter().find(|(ns, _)| ns == namespace)?; + units.iter().find_map(|unit| match unit { + FrozenUnit::Protocol { name: n, functions, .. } if n == name => functions.iter().find_map(|f| match f { + FrozenUnit::Function { name, .. } => Some(method_ident(name)), + _ => None, + }), + _ => None, + }) +} + +/// What a reader of the package's connection starts from, one line each: what +/// to implement, how to serve and dial, and how to call. +fn connection_entry(req: &GenerateRequest, connection: &EmittedConnection, spelling: Spelling) -> Vec { + let (server, client) = (&connection.server, &connection.client); + // Each protocol once, in the order the package lists them, under the + // schema it is declared in. + let mut by_namespace: Vec<(&str, Vec<&str>)> = Vec::new(); + for p in server.iter().chain(client) { + match by_namespace.iter_mut().find(|(ns, _)| *ns == p.namespace) { + Some((_, names)) if names.contains(&p.name.as_str()) => {} + Some((_, names)) => names.push(&p.name), + None => by_namespace.push((&p.namespace, vec![&p.name])), + } + } + let implement = by_namespace + .iter() + .map(|(namespace, names)| { + let names = names + .iter() + .map(|n| format!("`{}`", spelled(namespace, &ident(n), spelling))) + .collect::>() + .join(", "); + match spelling { + Spelling::Beside => format!("{names} (in `{}`)", relative_specifier(PACKAGE_MODULE, namespace)), + Spelling::Barrel => names, + } + }) + .collect::>() + .join("; "); + let fields = |provided: &[connections::Provided]| { + let fields = provided.iter().map(|p| camel(&p.field)).collect::>().join(", "); + if provided.is_empty() { "transport".to_string() } else { format!("transport, {{ {fields} }}") } + }; + let mut lines = vec![format!("Implement what you provide: {implement}.")]; + lines.push(format!( + "Serve with `serve({0})`; `accept({0})` takes the same and hands back the connection.", + fields(server) + )); + lines.push(format!("Dial with `connect({})`.", fields(client))); + // What the other end provides is what a caller reaches: the server's + // protocols from the dialling side, the client's from the serving one. + if let Some(p) = server.first().or_else(|| client.first()) { + let sender = spelled(&p.namespace, &format!("{}Sender", p.name), spelling); + let call = first_call(req, &p.namespace, &p.name).map(|f| format!(".{f}(…)")).unwrap_or_default(); + lines.push(format!( + "Call the other end with `new {}(conn){call}`, on the connection `connect` returns or the peer a handler is given.", + sender + )); + } + lines +} + +/// A comment block of bullet lines, ending with what the plumbing is. +fn entry_doc(lines: &[String], package_documentation: bool) -> String { + let mut doc = String::from("/**\n * Where to start:\n *\n"); + for line in lines { + doc.push_str(&format!(" * - {line}\n")); + } + doc.push_str( + " *\n * What is marked internal is wire plumbing: exported for hand-written use, and not what\n * a user calls.\n", + ); + if package_documentation { + doc.push_str(" *\n * @packageDocumentation\n"); + } + doc.push_str(" */\n"); + doc +} + +/// The package entry's header (`src/index.ts`, in `lib` mode): the +/// connection's entry points where the package has one, and each lockstep +/// protocol's. `None` when no protocol is emitted at all. +fn entry_points( + req: &GenerateRequest, + emitted: &[(String, Vec)], + connection: Option<&EmittedConnection>, +) -> Option { + let mut lines = connection.map(|c| connection_entry(req, c, Spelling::Barrel)).unwrap_or_default(); + for (namespace, units) in emitted { + for unit in units { + let FrozenUnit::Protocol { name, parameters, functions, .. } = unit else { continue }; + let lockstep = !connections::on_connection_among(&req.schemas, &req.dependencies, parameters); + if !lockstep || !functions.iter().any(|f| matches!(f, FrozenUnit::Function { .. })) { + continue; + } + let (interface, client, serve, dispatcher) = ( + spelled(namespace, &ident(name), Spelling::Barrel), + spelled(namespace, &format!("{name}Client"), Spelling::Barrel), + spelled(namespace, &format!("serve{name}"), Spelling::Barrel), + spelled(namespace, &format!("{name}Dispatcher"), Spelling::Barrel), + ); + let call = first_call(req, namespace, name).map(|f| format!(" and call `client.{f}(…)`")).unwrap_or_default(); + lines.push(format!( + "`{interface}` has its own framing: implement it and run `{serve}(impl, transport)` (which serves `{dispatcher}`), \ + or dial with `await {client}.connect(transport)`{call}.", + )); + } + } + if lines.is_empty() { + return None; + } + Some(entry_doc(&lines, true)) +} + /// A protocol's path as the generated text shows it: `chat::admin::Admin`, /// every segment joined by `::` however the namespace is spelled (a request's /// is `/`-joined, the facts' `::`-joined). Display only; no number, order or @@ -1325,7 +1659,7 @@ fn comline2_items( functions.join(", ") )); } - s.push_str(" */\nexport const HELLO = new Uint8Array([\n"); + s.push_str(" *\n * @internal\n */\nexport const HELLO = new Uint8Array([\n"); for chunk in hello.chunks(12) { let bytes: Vec = chunk.iter().map(|b| format!("{b:#04x}")).collect(); s.push_str(&format!(" {},\n", bytes.join(", "))); @@ -1333,7 +1667,10 @@ fn comline2_items( s.push_str("]);\n\n"); let camel_value = |v: &str| v.to_string(); s.push_str(&format!( - "/** The `comline@2` handshake, with {{@link HELLO}} and the parameters the package states. */\n\ + "/**\n\ + \x20* The `comline@2` handshake, with {{@link HELLO}} and the parameters the package states.\n\ + \x20* @internal\n\ + \x20*/\n\ export function handshake(): {class} {{\n\ \x20 return new {class}(HELLO, {{\n\ \x20 scope: \"{}\",\n\ @@ -1433,6 +1770,17 @@ fn unverified_doc(parameters: &[FrozenUnit]) -> String { doc } +/// The doc comment of a dispatcher: the `@unverified` one, if it has one, +/// and `@internal` where the package's `Services` builds it, so that a user +/// never needs to. +fn dispatcher_doc(unverified: &str, internal: bool) -> String { + match (unverified.strip_suffix(" */\n"), internal) { + (_, false) => unverified.to_string(), + (Some(open), true) => format!("{open} *\n * @internal\n */\n"), + (None, true) => "/** @internal */\n".to_string(), + } +} + /// `number` is the protocol's number on a connection, for a protocol that /// runs on one: its handlers take the peer, its dispatcher is provided on a /// `Connection`, and a `Sender` calls it through any `Peer`. @@ -1447,6 +1795,8 @@ fn protocol( addressing: Option, errors: &HashMap, types: &TypeMapper, + internal: bool, + wire: Option, ) -> String { let number = addressing.as_ref().map(|a| a.protocol); let by_id = addressing.as_ref().is_some_and(|a| a.by_id); @@ -1481,7 +1831,7 @@ fn protocol( let params_layout = params_ty.as_ref().map(|ty| { let fields: Vec<(&str, &TypeRef, bool)> = arguments.iter().map(|a| (a.name.as_str(), &a.ty, false)).collect(); - args_layout(ty, &fields, types) + format!("/** @internal */\n{}", args_layout(ty, &fields, types)) }); let (ret, ret_layout) = match _return { None | Some(TypeRef::Unit) => ("void".to_string(), "\"unit\"".to_string()), @@ -1567,7 +1917,7 @@ fn protocol( .collect::>() .join(", "); s.push_str(&format!( - "export const {calls_const} = [{call_names}] as const;\n\n" + "/** @internal */\nexport const {calls_const} = [{call_names}] as const;\n\n" )); let doc = unverified_doc(parameters); @@ -1580,7 +1930,7 @@ fn protocol( }; // 4. the dispatcher - s.push_str(&doc); + s.push_str(&dispatcher_doc(&doc, internal)); s.push_str(&format!( "export class {proto}Dispatcher implements {dispatch_t} {{\n" )); @@ -1727,7 +2077,11 @@ fn protocol( let open = if addressing.as_ref().is_some_and(|a| a.checks.is_some()) { "the package's `accept` / `connect`, which run `comline@2` with this package's facts".to_string() } else { - open + match &wire { + // `Format` and `CONNECTION_IR_HASH` aren't defined in this file. + Some(specifier) => format!("{open} (`Format` and `CONNECTION_IR_HASH` are in `{specifier}`)"), + None => open, + } }; s.push_str(&format!( "\n /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with {open}, or let the package's `serve` / `connect` do it. */\n\ diff --git a/codegen/tests/generate.rs b/codegen/tests/generate.rs index e608bd2..1beecb2 100644 --- a/codegen/tests/generate.rs +++ b/codegen/tests/generate.rs @@ -51,15 +51,35 @@ fn external_std_req(schemas: &[(String, Vec)]) -> GenerateRequest { } /// The schema's own file; a protocol on a connection brings the package's -/// `connection.ts` too. +/// `connection.ts` too, and the `wire.ts` they share their constants in. fn one(units: Vec) -> String { let schemas = vec![("account".to_string(), units)]; let mut files = generate_typescript(&code_req(&schemas)).unwrap(); assert_eq!(files[0].path.to_str().unwrap(), "account.ts"); - assert!(files.iter().skip(1).all(|f| f.path.to_str() == Some("connection.ts"))); + assert!(files.iter().skip(1).all(|f| matches!(f.path.to_str(), Some("connection.ts" | "wire.ts")))); files.remove(0).contents } +/// Every file generated for a fixture, kept in `runtime/test/generated//` +/// so the Node job type-checks and runs them together. Regenerate with +/// `TS_BLESS=1 cargo test -p comline-codegen-typescript`. +fn bless_fixture(dir: &str, files: &[comline_codegen::GeneratedFile]) { + for file in files { + let path = format!("{}/../runtime/test/generated/{dir}/{}", env!("CARGO_MANIFEST_DIR"), file.path.display()); + if std::env::var_os("TS_BLESS").is_some() { + std::fs::create_dir_all(std::path::Path::new(&path).parent().unwrap()).unwrap(); + std::fs::write(&path, &file.contents).unwrap(); + continue; + } + let committed = std::fs::read_to_string(&path).unwrap_or_default(); + assert_eq!( + file.contents, committed, + "generated {dir}/{} drifted from {path} - re-bless with TS_BLESS=1 cargo test -p comline-codegen-typescript", + file.path.display() + ); + } +} + /// The type a schema spells `written` - a primitive name, a named type, or /// either followed by `[]` / `[N]`. fn type_of(written: &str) -> TypeRef { @@ -572,7 +592,7 @@ fn a_third_party_handshake_is_imported_and_run() { ); let files = generate_typescript(&req).unwrap(); let file = |name: &str| files.iter().find(|f| f.path.to_str() == Some(name)).unwrap().contents.clone(); - let (hello, connection) = (file("hello.ts"), file("connection.ts")); + let (hello, connection, wire) = (file("hello.ts"), file("connection.ts"), file("wire.ts")); assert!(hello.contains("import { HelloHandshake } from \"acme-encodings\";\n"), "{hello}"); assert!(hello.contains("await Client.connect(transport, codec, IR_HASH, framing, new HelloHandshake())"), "{hello}"); assert!(hello.contains(".serve(transport, IR_HASH, new HelloHandshake());"), "{hello}"); @@ -581,7 +601,7 @@ fn a_third_party_handshake_is_imported_and_run() { connection.contains("await Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new HelloHandshake())"), "{connection}" ); - for (name, generated) in [("hello.ts", &hello), ("connection.ts", &connection)] { + for (name, generated) in [("hello.ts", &hello), ("connection.ts", &connection), ("wire.ts", &wire)] { let path = format!("{}/../runtime/test/generated/hello/{name}", env!("CARGO_MANIFEST_DIR")); if std::env::var_os("TS_BLESS").is_some() { std::fs::create_dir_all(std::path::Path::new(&path).parent().unwrap()).unwrap(); @@ -1641,7 +1661,8 @@ fn a_connection_protocol_gets_a_sender_and_peer_taking_handlers() { assert!(out.contains("export class EventsSender {")); assert!(out.contains("message(peer: Peer, params: EventsMessageParams): Promise;")); assert!(out.contains("static readonly PROTOCOL = 1;")); - assert!(out.contains("export const CONNECTION_IR_HASH = ")); + // The package's digest is defined once, in the module its files share. + assert!(!out.contains("export const CONNECTION_IR_HASH = ")); assert!(!out.contains("ChatClient"), "no lockstep client for a connection protocol"); assert!(!out.contains("serveChat")); } @@ -1716,41 +1737,19 @@ fn bare_jsonrpc_names_that_would_clash_on_a_connection_are_refused() { } /// The generated connection protocols, kept in -/// `runtime/test/generated/link.ts` so the Node job type-checks and runs +/// `runtime/test/generated/link/` so the Node job type-checks and runs /// them. Regenerate with `TS_BLESS=1 cargo test -p comline-codegen-typescript`. #[test] fn generated_link_matches_the_runtime_test_fixture() { let schemas = vec![("link".to_string(), link_units())]; - let generated = generate_typescript(&code_req(&schemas)).unwrap().remove(0).contents; - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../runtime/test/generated/link.ts"); - if std::env::var_os("TS_BLESS").is_some() { - std::fs::write(path, &generated).unwrap(); - return; - } - let committed = std::fs::read_to_string(path).unwrap_or_default(); - assert_eq!( - generated, committed, - "generated link drifted from runtime/test/generated/link.ts — \ - re-bless with TS_BLESS=1 cargo test -p comline-codegen-typescript" - ); + bless_fixture("link", &generate_typescript(&code_req(&schemas)).unwrap()); } -/// The same over JSON-RPC, in `runtime/test/generated/link_jsonrpc.ts`. +/// The same over JSON-RPC, in `runtime/test/generated/link_jsonrpc/`. #[test] fn generated_jsonrpc_link_matches_the_runtime_test_fixture() { let schemas = vec![("link".to_string(), link_jsonrpc_units())]; - let generated = generate_typescript(&code_req(&schemas)).unwrap().remove(0).contents; - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../runtime/test/generated/link_jsonrpc.ts"); - if std::env::var_os("TS_BLESS").is_some() { - std::fs::write(path, &generated).unwrap(); - return; - } - let committed = std::fs::read_to_string(path).unwrap_or_default(); - assert_eq!( - generated, committed, - "generated link drifted from runtime/test/generated/link_jsonrpc.ts — \ - re-bless with TS_BLESS=1 cargo test -p comline-codegen-typescript" - ); + bless_fixture("link_jsonrpc", &generate_typescript(&code_req(&schemas)).unwrap()); } /// A package of protocols across schemas, none naming a framing: on one @@ -1777,7 +1776,8 @@ fn the_package_connection_gets_services_and_serve() { let module = &files.iter().find(|f| f.path.to_str() == Some("connection.ts")).unwrap().contents; for expected in [ "import * as ns_game from \"./game.js\";", - "export const Format: Codec = new PackedCodec();", + // The package's constants are defined once, in the module its files share. + "export { CONNECTION_IR_HASH, Format } from \"./wire.js\";", "export interface Services {\n account: ns_game.Account;\n player: ns_game.Player;\n inventory: ns_items.Inventory;\n}", "export interface ClientServices {\n events: ns_items.Events;\n}", " new ns_items.InventoryDispatcher(services.inventory).provideOn(conn);", @@ -1787,6 +1787,16 @@ fn the_package_connection_gets_services_and_serve() { assert!(module.contains(expected), "missing `{expected}` in:\n{module}"); } + assert!(!module.contains("export const Format"), "{module}"); + let wire = &files.iter().find(|f| f.path.to_str() == Some("wire.ts")).unwrap().contents; + for expected in ["export const Format: Codec = new PackedCodec();", "export const CONNECTION_IR_HASH = 0x"] { + assert!(wire.contains(expected), "missing `{expected}` in:\n{wire}"); + } + for file in files.iter().filter(|f| matches!(f.path.to_str(), Some("game.ts" | "items.ts"))) { + assert!(!file.contents.contains("export const CONNECTION_IR_HASH"), "{}", file.contents); + assert!(!file.contents.contains("export const Format"), "{}", file.contents); + } + // In `lib` mode it's beside the schemas, its names at the root. let files = generate_typescript(&lib_req(&schemas)).unwrap(); let index = &files.iter().find(|f| f.path.to_str() == Some("src/index.ts")).unwrap().contents; @@ -1937,7 +1947,8 @@ fn schema_names_the_generated_code_also_needs_are_kept() { " private readonly client: $Client;", " async client_(params: LockClientParams): globalThis.Promise {", "export function serveLock(impl: Lock, transport: $Transport, codec: $Codec = Format, framing: $Framing = new $DatagramFraming()): globalThis.Promise {", - "export const Format: $Codec = new $PackedCodec();", + // `Lock` is lockstep, so its helper's default codec is the package's. + "import { Format } from \"./wire.js\";", // The wire names are the schema's. "{ id: 0, name: \"then\" }", ] { @@ -2019,24 +2030,14 @@ fn a_schema_without_bounds_imports_no_check() { assert!(!out.contains("max:"), "{out}"); } -/// The generated `Directory`, kept in `runtime/test/generated/bounds.ts` so +/// The generated `Directory`, kept in `runtime/test/generated/bounds/` so /// the Node job type-checks it (also at the TypeScript 5.0 floor) and runs it /// against the codecs' bound checks. Regenerate with /// `TS_BLESS=1 cargo test -p comline-codegen-typescript`. #[test] fn generated_bounds_match_the_runtime_test_fixture() { - let generated = one(bounds_units()); - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../runtime/test/generated/bounds.ts"); - if std::env::var_os("TS_BLESS").is_some() { - std::fs::write(path, &generated).unwrap(); - return; - } - let committed = std::fs::read_to_string(path).unwrap_or_default(); - assert_eq!( - generated, committed, - "generated Directory drifted from runtime/test/generated/bounds.ts - \ - re-bless with TS_BLESS=1 cargo test -p comline-codegen-typescript" - ); + let schemas = vec![("account".to_string(), bounds_units())]; + bless_fixture("bounds", &generate_typescript(&code_req(&schemas)).unwrap()); } // ── datagram@3 + comline@2 ───────────────────────────────────────────────── @@ -2184,3 +2185,161 @@ fn datagram3_without_its_facts_is_refused() { let err = generate_typescript(&req).unwrap_err().to_string(); assert!(err.contains("the request carries no facts"), "{err}"); } + +// ── where to start, what is plumbing, what is shared ─────────────────────── + +/// The package's header names what to implement, serve, dial and call: beside +/// the connection, in the connection's own words; at the entry, by the +/// namespaces the barrel exports. +#[test] +fn the_package_entry_points_are_named() { + let schemas = game_schemas(); + let files = generate_typescript(&code_req(&schemas)).unwrap(); + let module = &files.iter().find(|f| f.path.to_str() == Some("connection.ts")).unwrap().contents; + for expected in [ + " * - Implement what you provide: `Account`, `Player` (in `./game.js`); `Inventory`, `Events` (in `./items.js`).\n", + " * - Serve with `serve(transport, { account, player, inventory })`; `accept(transport, { account, player, inventory })` takes the same and hands back the connection.\n", + " * - Dial with `connect(transport, { events })`.\n", + " * - Call the other end with `new AccountSender(conn).login(…)`,", + ] { + assert!(module.contains(expected), "missing `{expected}` in:\n{module}"); + } + // The wording never says the marker itself, which a declaration file's + // `stripInternal` would act on. + assert!(!module[..module.find("import {").unwrap()].contains("@internal"), "{module}"); + + let files = generate_typescript(&lib_req(&schemas)).unwrap(); + let index = &files.iter().find(|f| f.path.to_str() == Some("src/index.ts")).unwrap().contents; + assert!(index.contains(" * - Implement what you provide: `game.Account`, `game.Player`; `items.Inventory`, `items.Events`.\n"), "{index}"); + assert!(index.contains(" * @packageDocumentation\n"), "{index}"); + assert!(index.starts_with("// Generated by Comline\n"), "{index}"); + assert!(index.ends_with("export * from \"./connection.js\";\n"), "{index}"); +} + +/// A lockstep protocol has no package module: the entry names its server +/// helper and dispatcher, and its client. +#[test] +fn a_lockstep_protocols_entry_points_are_named_at_the_package_entry() { + let schemas = vec![("chat".to_string(), chat_units())]; + let files = generate_typescript(&lib_req(&schemas)).unwrap(); + let index = &files.iter().find(|f| f.path.to_str() == Some("src/index.ts")).unwrap().contents; + for expected in [ + "`chat.Chat` has its own framing: implement it and run `chat.serveChat(impl, transport)` (which serves `chat.ChatDispatcher`), ", + "or dial with `await chat.ChatClient.connect(transport)` and call `client.send(…)`.", + " * @packageDocumentation\n", + ] { + assert!(index.contains(expected), "missing `{expected}` in:\n{index}"); + } + // Nothing to start from, nothing said: types alone have no entry. + let files = generate_typescript(&lib_req(&[("shapes".to_string(), vec![])])).unwrap(); + let index = &files.iter().find(|f| f.path.to_str() == Some("src/index.ts")).unwrap().contents; + assert!(!index.contains("Where to start"), "{index}"); +} + +/// The wire plumbing is marked `@internal`, and what a declaration file's +/// `stripInternal` would take from the public signatures is not: a params +/// interface is named by the interface the user implements, and a type's +/// `Layout` by every package that uses the type. +#[test] +fn the_wire_plumbing_is_marked_internal_and_the_api_is_not() { + let schemas = game_schemas(); + let files = generate_typescript(&code_req(&schemas)).unwrap(); + let game = &files.iter().find(|f| f.path.to_str() == Some("game.ts")).unwrap().contents; + let items = &files.iter().find(|f| f.path.to_str() == Some("items.ts")).unwrap().contents; + let connection = &files.iter().find(|f| f.path.to_str() == Some("connection.ts")).unwrap().contents; + for (file, marked) in [ + (game, "/** @internal */\nexport const AccountLoginParamsLayout"), + (game, "/** @internal */\nexport const ACCOUNT_CALLS"), + // `Services` builds its dispatcher. + (game, "/** @internal */\nexport class AccountDispatcher"), + (items, "/** @internal */\nexport class EventsDispatcher"), + (connection, " * @internal\n */\nexport function provideServices"), + (connection, " * @internal\n */\nexport function provideClientServices"), + ] { + assert!(file.contains(marked), "missing `{marked}` in:\n{file}"); + } + for (file, plain) in [ + (game, "\nexport interface AccountLoginParams {"), + (game, "\nexport interface Account {"), + (game, "\nexport class AccountSender {"), + (items, "\nexport interface Item {"), + (items, "\nexport const ItemLayout: Layout"), + (connection, "\nexport interface Services {"), + (connection, "\nexport async function serve("), + ] { + assert!(file.contains(plain), "missing `{plain}` in:\n{file}"); + let before = &file[..file.find(plain).unwrap()]; + assert!(!before.ends_with("/** @internal */"), "`{plain}` must not be internal:\n{file}"); + } +} + +/// A lockstep protocol's dispatcher is what its server helper builds, and a +/// user may build it too: nothing covers it. +#[test] +fn a_dispatcher_nothing_provides_stays_public() { + let out = one(chat_units()); + assert!(out.contains("\nexport class ChatDispatcher implements Dispatch {"), "{out}"); + assert!(!out.contains("/** @internal */\nexport class ChatDispatcher"), "{out}"); +} + +/// `Format` and `CONNECTION_IR_HASH` are defined once for the package: in +/// the module its files share when more than one would, which the package +/// module re-exports. The protocol files define neither, and import `Format` +/// only where a lockstep helper uses it. +#[test] +fn the_shared_constants_are_defined_once() { + let schemas = game_schemas(); + let files = generate_typescript(&code_req(&schemas)).unwrap(); + let paths: Vec<_> = files.iter().map(|f| f.path.to_str().unwrap()).collect(); + assert_eq!(paths, ["game.ts", "items.ts", "connection.ts", "wire.ts"]); + let defined = |text: &str| text.matches("export const Format").count() + text.matches("export const CONNECTION_IR_HASH").count(); + assert_eq!(files.iter().map(|f| defined(&f.contents)).sum::(), 2, "one each"); + assert_eq!(defined(&files[3].contents), 2); + assert!(files[..2].iter().all(|f| !f.contents.contains("import { Format }")), "a connection protocol uses neither"); + + // In `lib` mode the module is beside the others; the package module's + // re-export carries its names to the root. + let files = generate_typescript(&lib_req(&schemas)).unwrap(); + assert!(files.iter().any(|f| f.path.to_str() == Some("src/wire.ts"))); + let index = &files.iter().find(|f| f.path.to_str() == Some("src/index.ts")).unwrap().contents; + assert!(!index.contains("wire.js"), "{index}"); + + // A lone file keeps its own: nothing is repeated, so nothing is moved. + let schemas = vec![("chat".to_string(), chat_units())]; + let files = generate_typescript(&code_req(&schemas)).unwrap(); + assert_eq!(files.len(), 1); + assert!(files[0].contents.contains("export const Format: Codec = new PackedCodec();")); +} + +/// Lockstep protocols in more than one file share the codec too, and have no +/// package module to re-export it, so the entry does. +#[test] +fn lockstep_files_share_one_format() { + use comline_core::schema::ir::compiler::interpreter::incremental::IncrementalInterpreter; + use comline_core::schema::ir::compiler::Compile; + let source = |name: &str| format!("@framing = \"datagram\"\nprotocol {name} {{\n function ping() -> u8;\n}}\n"); + let schemas = vec![ + ("one".to_string(), IncrementalInterpreter::from_source(&source("One"))), + ("two".to_string(), IncrementalInterpreter::from_source(&source("Two"))), + ]; + let files = generate_typescript(&lib_req(&schemas)).unwrap(); + let file = |path: &str| files.iter().find(|f| f.path.to_str() == Some(path)).unwrap().contents.clone(); + for name in ["src/one.ts", "src/two.ts"] { + let text = file(name); + assert!(text.contains("import { Format } from \"./wire.js\";\n"), "{text}"); + assert!(!text.contains("export const Format"), "{text}"); + assert!(!text.contains("PackedCodec"), "{text}"); + } + let wire = file("src/wire.ts"); + assert!(wire.contains("export const Format: Codec = new PackedCodec();"), "{wire}"); + assert!(!wire.contains("CONNECTION_IR_HASH"), "no connection, no digest: {wire}"); + assert!(file("src/index.ts").ends_with("export * from \"./wire.js\";\n")); +} + +#[test] +fn a_schema_named_like_the_shared_module_is_refused() { + let mut schemas = game_schemas(); + schemas.push(("wire".to_string(), vec![])); + let error = generate_typescript(&code_req(&schemas)).unwrap_err().to_string(); + assert!(error.contains("a schema named `wire` would be overwritten"), "{error}"); +} diff --git a/codegen/tests/nested_namespaces.rs b/codegen/tests/nested_namespaces.rs index a1d84cc..c0990cc 100644 --- a/codegen/tests/nested_namespaces.rs +++ b/codegen/tests/nested_namespaces.rs @@ -102,9 +102,13 @@ fn a_nested_protocols_path_is_spelled_with_colons() { fn the_display_path_changes_no_number_or_hash() { let req = request(&nested_protocol()); let files = generated(&req, "nested"); - let connection = file(&files, "connection.ts"); + // The package's digest is defined once, in the module its files share, + // and the package module re-exports it. + let wire = file(&files, "wire.ts"); let hash = format!("CONNECTION_IR_HASH = {:#018x}n;", connections::connection_ir_hash(&req.schemas)); - assert!(connection.contains(&hash), "{connection}"); + assert!(wire.contains(&hash), "{wire}"); + let connection = file(&files, "connection.ts"); + assert!(connection.contains("export { CONNECTION_IR_HASH, Format } from \"./wire.js\";"), "{connection}"); let admin = file(&files, "chat/admin.ts"); assert!(admin.contains("checkCall(this.peer, AdminSender.PROTOCOL, 0, "), "{admin}"); } diff --git a/runtime/package.json b/runtime/package.json index bdac7cd..15c7068 100644 --- a/runtime/package.json +++ b/runtime/package.json @@ -22,7 +22,8 @@ "build": "tsc -p tsconfig.json", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "tsc -p tsconfig.json && node --test dist/test/*.test.js dist/test/prop/*.test.js", - "typecheck:generated": "tsc -p tsconfig.generated.json --erasableSyntaxOnly" + "typecheck:generated": "tsc -p tsconfig.generated.json --erasableSyntaxOnly", + "typecheck:stripped": "node -e \"require('node:fs').rmSync('dist/stripped', { recursive: true, force: true })\" && tsc -p tsconfig.generated.json --declaration --emitDeclarationOnly --noEmit false --stripInternal --outDir dist/stripped && tsc -p tsconfig.stripped.json" }, "devDependencies": { "@types/node": "^20.14.0", diff --git a/runtime/test/generated-bounds.test.ts b/runtime/test/generated-bounds.test.ts index 0e47431..0541b78 100644 --- a/runtime/test/generated-bounds.test.ts +++ b/runtime/test/generated-bounds.test.ts @@ -1,4 +1,4 @@ -// Exercises generated bounds (core#98) against the runtime. `generated/bounds.ts` +// Exercises generated bounds (core#98) against the runtime. `generated/bounds/` // is written by `comline-codegen-typescript`'s `generated_bounds_match_the_ // runtime_test_fixture` test; this proves it type-checks and that every // bound it declares is checked, both ways, in both formats. @@ -11,14 +11,14 @@ import { type Customer, type Directory, type Folder, - CONNECTION_IR_HASH, CountryCode, CustomerLayout, DirectoryDispatcher, DirectorySender, FolderLayout, Name, -} from "./generated/bounds.js"; +} from "./generated/bounds/account.js"; +import { CONNECTION_IR_HASH } from "./generated/bounds/wire.js"; const bound = (measure: Measure) => (e: unknown) => e instanceof RuntimeError && e.is("boundExceeded") && e.measure === measure; diff --git a/runtime/test/generated-connection.test.ts b/runtime/test/generated-connection.test.ts index acacf2d..4352d4d 100644 --- a/runtime/test/generated-connection.test.ts +++ b/runtime/test/generated-connection.test.ts @@ -1,4 +1,4 @@ -// Exercises real generator output on a `Connection`. `generated/link.ts` is +// Exercises real generator output on a `Connection`. `generated/link/` is // written by `comline-codegen-typescript`'s `generated_link_matches_the_ // runtime_test_fixture` test; this proves it type-checks and runs. @@ -13,10 +13,10 @@ import { type EventsMessageParams, ChatDispatcher, ChatSender, - CONNECTION_IR_HASH, EventsDispatcher, EventsSender, -} from "./generated/link.js"; +} from "./generated/link/link.js"; +import { CONNECTION_IR_HASH } from "./generated/link/wire.js"; class Sent { constructor(public count: bigint) {} diff --git a/runtime/test/generated-jsonrpc-connection.test.ts b/runtime/test/generated-jsonrpc-connection.test.ts index 902cc62..35a8133 100644 --- a/runtime/test/generated-jsonrpc-connection.test.ts +++ b/runtime/test/generated-jsonrpc-connection.test.ts @@ -1,4 +1,4 @@ -// Exercises real generator output on a JSON-RPC `Connection`. `generated/link_jsonrpc.ts` is +// Exercises real generator output on a JSON-RPC `Connection`. `generated/link_jsonrpc/` is // written by `comline-codegen-typescript`'s `generated_jsonrpc_link_matches_the_ // runtime_test_fixture` test; this proves it type-checks and runs. @@ -13,10 +13,10 @@ import { type EventsMessageParams, ChatDispatcher, ChatSender, - CONNECTION_IR_HASH, EventsDispatcher, EventsSender, -} from "./generated/link_jsonrpc.js"; +} from "./generated/link_jsonrpc/link.js"; +import { CONNECTION_IR_HASH } from "./generated/link_jsonrpc/wire.js"; class Sent { constructor(public count: bigint) {} diff --git a/runtime/test/generated/acme.ts b/runtime/test/generated/acme.ts index e701ac3..d5ab9a7 100644 --- a/runtime/test/generated/acme.ts +++ b/runtime/test/generated/acme.ts @@ -52,18 +52,21 @@ export interface ChatSendParams { text: string; } +/** @internal */ export const ChatSendParamsLayout: Layout = { struct: [["text", "string"]] }; export interface ChatHistoryParams { limit: number; } +/** @internal */ export const ChatHistoryParamsLayout: Layout = { struct: [["limit", "u32"]] }; export interface ChatNoteParams { text: string; } +/** @internal */ export const ChatNoteParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Chat { @@ -74,6 +77,7 @@ export interface Chat { note(params: ChatNoteParams): Promise; } +/** @internal */ export const CHAT_CALLS = ["send", "history", "wipe", "note"] as const; export class ChatDispatcher implements Dispatch { diff --git a/runtime/test/generated/bounds.ts b/runtime/test/generated/bounds/account.ts similarity index 92% rename from runtime/test/generated/bounds.ts rename to runtime/test/generated/bounds/account.ts index 963ac5d..35a31b2 100644 --- a/runtime/test/generated/bounds.ts +++ b/runtime/test/generated/bounds/account.ts @@ -6,7 +6,6 @@ import { resolveKind, checkChars, checkCharsExact, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -20,14 +19,6 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x17305ca8c4eea701n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x17305ca8c4eea701n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - /** A string of exactly 2 characters: make one with `CountryCode.from`. */ export type CountryCode = string & { readonly __brand: "CountryCode" }; @@ -76,12 +67,14 @@ export interface DirectoryFindParams { query: string; } +/** @internal */ export const DirectoryFindParamsLayout: Layout = { struct: [["query", { chars: { max: 8 } }]] }; export interface DirectoryTreeParams { root: Folder; } +/** @internal */ export const DirectoryTreeParamsLayout: Layout = { struct: [["root", () => FolderLayout]] }; export interface Directory { @@ -89,8 +82,10 @@ export interface Directory { tree(peer: Peer, params: DirectoryTreeParams): Promise; } +/** @internal */ export const DIRECTORY_CALLS = ["find", "tree"] as const; +/** @internal */ export class DirectoryDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; @@ -136,7 +131,7 @@ export class DirectoryDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(DirectoryDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/bounds/connection.ts b/runtime/test/generated/bounds/connection.ts new file mode 100644 index 0000000..0751cec --- /dev/null +++ b/runtime/test/generated/bounds/connection.ts @@ -0,0 +1,62 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +/** + * Where to start: + * + * - Implement what you provide: `Directory` (in `./account.js`). + * - Serve with `serve(transport, { directory })`; `accept(transport, { directory })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new DirectorySender(conn).find(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + +import { + Connection, + type Transport, +} from "@comline/runtime"; +import * as ns_account from "./account.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface Services { + directory: ns_account.Directory; +} + +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideServices(conn: Connection, services: Services): void { + new ns_account.DirectoryDispatcher(services.directory).provideOn(conn); +} + +/** +* Accept a connection over `transport`: run the handshake, then provide +* every protocol in `services` on it. The connection comes back serving, +* so the server can call the client through it. +*/ +export async function accept(transport: Transport, services: Services): Promise { + const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); + provideServices(conn, services); + return conn; +} + +/** {@link accept}, then serve every call until the peer leaves. */ +export async function serve(transport: Transport, services: Services): Promise { + await (await accept(transport, services)).closed; +} + +/** +* Dial over `transport`: run the handshake. Call the server's protocols +* through their senders. +*/ +export async function connect(transport: Transport): Promise { + const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); + return conn; +} diff --git a/runtime/test/generated/bounds/wire.ts b/runtime/test/generated/bounds/wire.ts new file mode 100644 index 0000000..639da3b --- /dev/null +++ b/runtime/test/generated/bounds/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x17305ca8c4eea701n; diff --git a/runtime/test/generated/chat.ts b/runtime/test/generated/chat.ts index 3c5eade..07cd444 100644 --- a/runtime/test/generated/chat.ts +++ b/runtime/test/generated/chat.ts @@ -52,18 +52,21 @@ export interface ChatSendParams { text: string; } +/** @internal */ export const ChatSendParamsLayout: Layout = { struct: [["text", "string"]] }; export interface ChatHistoryParams { limit: number; } +/** @internal */ export const ChatHistoryParamsLayout: Layout = { struct: [["limit", "u32"]] }; export interface ChatNoteParams { text: string; } +/** @internal */ export const ChatNoteParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Chat { @@ -74,6 +77,7 @@ export interface Chat { note(params: ChatNoteParams): Promise; } +/** @internal */ export const CHAT_CALLS = ["send", "history", "wipe", "note"] as const; export class ChatDispatcher implements Dispatch { diff --git a/runtime/test/generated/clash/api.ts b/runtime/test/generated/clash/api.ts index ff0df7a..0d2b31a 100644 --- a/runtime/test/generated/clash/api.ts +++ b/runtime/test/generated/clash/api.ts @@ -21,10 +21,6 @@ import type { Greeting } from "./localdeps/greeting.js"; * two ends of a connection must agree on it. */ export const IR_HASH = 0xa14195a41e817a01n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xe9ca523b62a2c19fn; - export interface Message { greeting: Greeting; } @@ -35,14 +31,17 @@ export interface ChatGreetParams { n: number; } +/** @internal */ export const ChatGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; export interface Chat { greet(peer: Peer, params: ChatGreetParams): Promise; } +/** @internal */ export const CHAT_CALLS = ["greet"] as const; +/** @internal */ export class ChatDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; @@ -109,14 +108,17 @@ export interface EventsNotifyParams { n: number; } +/** @internal */ export const EventsNotifyParamsLayout: Layout = { struct: [["n", "u32"]] }; export interface Events { notify(peer: Peer, params: EventsNotifyParams): Promise; } +/** @internal */ export const EVENTS_CALLS = ["notify"] as const; +/** @internal */ export class EventsDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 1; diff --git a/runtime/test/generated/clash/connection.ts b/runtime/test/generated/clash/connection.ts index 3f78b96..a19b5c9 100644 --- a/runtime/test/generated/clash/connection.ts +++ b/runtime/test/generated/clash/connection.ts @@ -1,25 +1,32 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Chat`, `Events` (in `./api.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport, { events })`. + * - Call the other end with `new ChatSender(conn).greet(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, JsonCodec, JsonRpcConnectionFraming, - PackedCodec, Comline2Handshake, Negotiated, - type Codec, type Peer, type Transport, } from "@comline/runtime"; import * as ns_api from "./api.js"; +import { CONNECTION_IR_HASH } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xe9ca523b62a2c19fn; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history @@ -27,6 +34,8 @@ export const CONNECTION_IR_HASH = 0xe9ca523b62a2c19fn; * * - 0 `api::Chat`, line 0.1.0: `greet` 0 * - 1 `api::Events`, line 0.1.0: `notify` 0 + * + * @internal */ export const HELLO = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, @@ -42,7 +51,10 @@ export const HELLO = new Uint8Array([ 0x01, 0x00, ]); -/** The `comline@2` handshake, with {@link HELLO} and the parameters the package states. */ +/** + * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * @internal + */ export function handshake(): Comline2Handshake { return new Comline2Handshake(HELLO, { scope: "protocol", @@ -73,7 +85,10 @@ export interface Services { chat: ns_api.Chat; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_api.ChatDispatcher(services.chat).provideOn(conn); } @@ -83,7 +98,10 @@ export interface ClientServices { events: ns_api.Events; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideClientServices(conn: Connection, services: ClientServices): void { new ns_api.EventsDispatcher(services.events).provideOn(conn); } diff --git a/runtime/test/generated/clash/localdeps/greeting.ts b/runtime/test/generated/clash/localdeps/greeting.ts index 2b81491..06e02e8 100644 --- a/runtime/test/generated/clash/localdeps/greeting.ts +++ b/runtime/test/generated/clash/localdeps/greeting.ts @@ -17,10 +17,6 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x3c4249f5704f3397n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xe9ca523b62a2c19fn; - export interface Greeting { text: string; } @@ -31,12 +27,14 @@ export interface FooGreetParams { n: number; } +/** @internal */ export const FooGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; export interface Foo { greet(peer: Peer, params: FooGreetParams): Promise; } +/** @internal */ export const FOO_CALLS = ["greet"] as const; export class FooDispatcher implements Dispatch { @@ -75,7 +73,7 @@ export class FooDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming(), new Comline2Handshake())`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming(), new Comline2Handshake())` (`Format` and `CONNECTION_IR_HASH` are in `../wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(FooDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/clash/wire.ts b/runtime/test/generated/clash/wire.ts new file mode 100644 index 0000000..4c7a4a1 --- /dev/null +++ b/runtime/test/generated/clash/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0xe9ca523b62a2c19fn; diff --git a/runtime/test/generated/collisions/connection.ts b/runtime/test/generated/collisions/connection.ts index d210955..5a4e02c 100644 --- a/runtime/test/generated/collisions/connection.ts +++ b/runtime/test/generated/collisions/connection.ts @@ -1,21 +1,28 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Wire` (in `./shapes.js`); `Again` (in `./user.js`). + * - Serve with `serve(transport, { wire, again })`; `accept(transport, { wire, again })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new WireSender(conn).then_(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, - PackedCodec, - type Codec, type Transport, } from "@comline/runtime"; import * as ns_shapes from "./shapes.js"; import * as ns_user from "./user.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x9dffbf799cccf0f4n; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ export interface Services { @@ -23,7 +30,10 @@ export interface Services { again: ns_user.Again; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_shapes.WireDispatcher(services.wire).provideOn(conn); new ns_user.AgainDispatcher(services.again).provideOn(conn); @@ -46,9 +56,8 @@ export async function serve(transport: Transport, services: Services): Promise { const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); diff --git a/runtime/test/generated/collisions/shapes.ts b/runtime/test/generated/collisions/shapes.ts index af033b5..d667554 100644 --- a/runtime/test/generated/collisions/shapes.ts +++ b/runtime/test/generated/collisions/shapes.ts @@ -7,7 +7,6 @@ import { RuntimeError as $RuntimeError, resolveKind, DatagramFraming as $DatagramFraming, - PackedCodec as $PackedCodec, type Codec as $Codec, type Connection as $Connection, type Dispatch as $Dispatch, @@ -19,18 +18,12 @@ import { type Transport as $Transport, } from "@comline/runtime"; +import { Format } from "./wire.js"; + /** Canonical digest of the frozen IR this file was generated from — the * two ends of a connection must agree on it. */ export const IR_HASH = 0xe84d76dcf6442bd3n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x9dffbf799cccf0f4n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: $Codec = new $PackedCodec(); - export interface Layout { a: number; } @@ -131,24 +124,28 @@ export interface WireThenParams { l: Layout; } +/** @internal */ export const WireThenParamsLayout: $Layout = { struct: [["l", () => LayoutLayout]] }; export interface WireConstructorParams { p: Peer; } +/** @internal */ export const WireConstructorParamsLayout: $Layout = { struct: [["p", () => PeerLayout]] }; export interface WirePeerParams { c: Codec; } +/** @internal */ export const WirePeerParamsLayout: $Layout = { struct: [["c", () => CodecLayout]] }; export interface WireClientParams { k: Kind; } +/** @internal */ export const WireClientParamsLayout: $Layout = { struct: [["k", () => KindLayout]] }; export interface Wire { @@ -158,8 +155,10 @@ export interface Wire { client_(peer: $Peer, params: WireClientParams): globalThis.Promise; } +/** @internal */ export const WIRE_CALLS = ["then", "constructor", "peer", "client"] as const; +/** @internal */ export class WireDispatcher implements $Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; @@ -223,7 +222,7 @@ export class WireDispatcher implements $Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: $Connection): void { conn.provide(WireDispatcher.PROTOCOL, this); } @@ -273,12 +272,14 @@ export interface LockThenParams { c: Client; } +/** @internal */ export const LockThenParamsLayout: $Layout = { struct: [["c", () => ClientLayout]] }; export interface LockClientParams { t: Transport; } +/** @internal */ export const LockClientParamsLayout: $Layout = { struct: [["t", () => TransportLayout]] }; export interface LockPeerParams { @@ -286,6 +287,7 @@ export interface LockPeerParams { p: PackedCodec; } +/** @internal */ export const LockPeerParamsLayout: $Layout = { struct: [["f", () => DatagramFramingLayout], ["p", () => PackedCodecLayout]] }; export interface Lock { @@ -294,6 +296,7 @@ export interface Lock { peer_(params: LockPeerParams): globalThis.Promise; } +/** @internal */ export const LOCK_CALLS = ["then", "client", "peer"] as const; export class LockDispatcher implements $Dispatch { diff --git a/runtime/test/generated/collisions/user.ts b/runtime/test/generated/collisions/user.ts index 8d85632..00e12b1 100644 --- a/runtime/test/generated/collisions/user.ts +++ b/runtime/test/generated/collisions/user.ts @@ -4,7 +4,6 @@ import { RuntimeError, resolveKind, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -21,14 +20,6 @@ import type { Layout, Promise } from "./shapes.js"; * two ends of a connection must agree on it. */ export const IR_HASH = 0x2581145250fde0c6n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x9dffbf799cccf0f4n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface Uses { l: Layout; p: Promise; @@ -40,14 +31,17 @@ export interface AgainGetParams { u: Uses; } +/** @internal */ export const AgainGetParamsLayout: $Layout = { struct: [["u", () => UsesLayout]] }; export interface Again { get(peer: Peer, params: AgainGetParams): globalThis.Promise; } +/** @internal */ export const AGAIN_CALLS = ["get"] as const; +/** @internal */ export class AgainDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 2; @@ -84,7 +78,7 @@ export class AgainDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(AgainDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/collisions/wire.ts b/runtime/test/generated/collisions/wire.ts new file mode 100644 index 0000000..01befad --- /dev/null +++ b/runtime/test/generated/collisions/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x9dffbf799cccf0f4n; diff --git a/runtime/test/generated/comline2/alien/chat.ts b/runtime/test/generated/comline2/alien/chat.ts index 4cb1828..18d925e 100644 --- a/runtime/test/generated/comline2/alien/chat.ts +++ b/runtime/test/generated/comline2/alien/chat.ts @@ -5,7 +5,6 @@ import { RuntimeError, resolveKind, checkCall, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -19,24 +18,18 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x70132e163503db63n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x70132e163503db63n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface ChatHelloParams { name: string; } +/** @internal */ export const ChatHelloParamsLayout: Layout = { struct: [["name", "string"]] }; export interface ChatShoutParams { text: string; } +/** @internal */ export const ChatShoutParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Chat { @@ -44,8 +37,10 @@ export interface Chat { shout(peer: Peer, params: ChatShoutParams): Promise; } +/** @internal */ export const CHAT_CALLS = ["hello", "shout"] as const; +/** @internal */ export class ChatDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; diff --git a/runtime/test/generated/comline2/alien/connection.ts b/runtime/test/generated/comline2/alien/connection.ts index cd4326a..4be8eea 100644 --- a/runtime/test/generated/comline2/alien/connection.ts +++ b/runtime/test/generated/comline2/alien/connection.ts @@ -1,30 +1,39 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Chat` (in `./chat.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new ChatSender(conn).hello(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, Datagram3Framing, - PackedCodec, Comline2Handshake, Negotiated, - type Codec, type Peer, type Transport, } from "@comline/runtime"; import * as ns_chat from "./chat.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x70132e163503db63n; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** * This end's `comline@2` Hello: version 0.1.0 of package `fedcba9876543210fedcba9876543210`, as its history * records it. Its protocols, by wire number: * * - 0 `chat::Chat`, line 0.1.0: `hello` 0, `shout` 1 + * + * @internal */ export const HELLO = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, @@ -38,7 +47,10 @@ export const HELLO = new Uint8Array([ 0xaa, 0xaa, 0x02, 0x00, 0x01, ]); -/** The `comline@2` handshake, with {@link HELLO} and the parameters the package states. */ +/** + * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * @internal + */ export function handshake(): Comline2Handshake { return new Comline2Handshake(HELLO, { scope: "protocol", @@ -69,7 +81,10 @@ export interface Services { chat: ns_chat.Chat; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_chat.ChatDispatcher(services.chat).provideOn(conn); } @@ -93,9 +108,8 @@ export async function serve(transport: Transport, services: Services): Promise { const agreed = handshake(); diff --git a/runtime/test/generated/comline2/alien/wire.ts b/runtime/test/generated/comline2/alien/wire.ts new file mode 100644 index 0000000..8898f80 --- /dev/null +++ b/runtime/test/generated/comline2/alien/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x70132e163503db63n; diff --git a/runtime/test/generated/comline2/new/chat.ts b/runtime/test/generated/comline2/new/chat.ts index e83314b..975511c 100644 --- a/runtime/test/generated/comline2/new/chat.ts +++ b/runtime/test/generated/comline2/new/chat.ts @@ -5,7 +5,6 @@ import { RuntimeError, resolveKind, checkCall, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -19,30 +18,25 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0xe21c2f843f183318n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xe21c2f843f183318n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface ChatShoutParams { text: string; } +/** @internal */ export const ChatShoutParamsLayout: Layout = { struct: [["text", "string"]] }; export interface ChatWhisperParams { text: string; } +/** @internal */ export const ChatWhisperParamsLayout: Layout = { struct: [["text", "string"]] }; export interface ChatHelloParams { name: string; } +/** @internal */ export const ChatHelloParamsLayout: Layout = { struct: [["name", "string"]] }; export interface Chat { @@ -51,8 +45,10 @@ export interface Chat { hello(peer: Peer, params: ChatHelloParams): Promise; } +/** @internal */ export const CHAT_CALLS = ["shout", "whisper", "hello"] as const; +/** @internal */ export class ChatDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; diff --git a/runtime/test/generated/comline2/new/connection.ts b/runtime/test/generated/comline2/new/connection.ts index 348a3a6..90aff57 100644 --- a/runtime/test/generated/comline2/new/connection.ts +++ b/runtime/test/generated/comline2/new/connection.ts @@ -1,30 +1,39 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Chat` (in `./chat.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new ChatSender(conn).shout(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, Datagram3Framing, - PackedCodec, Comline2Handshake, Negotiated, - type Codec, type Peer, type Transport, } from "@comline/runtime"; import * as ns_chat from "./chat.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xe21c2f843f183318n; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** * This end's `comline@2` Hello: version 0.2.0 of package `0123456789abcdef0123456789abcdef`, as its history * records it. Its protocols, by wire number: * * - 0 `chat::Chat`, line 0.1.0: `shout` 1, `whisper` 2, `hello` 0 + * + * @internal */ export const HELLO = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, @@ -38,7 +47,10 @@ export const HELLO = new Uint8Array([ 0xbb, 0xbb, 0x03, 0x00, 0x01, 0x02, ]); -/** The `comline@2` handshake, with {@link HELLO} and the parameters the package states. */ +/** + * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * @internal + */ export function handshake(): Comline2Handshake { return new Comline2Handshake(HELLO, { scope: "protocol", @@ -69,7 +81,10 @@ export interface Services { chat: ns_chat.Chat; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_chat.ChatDispatcher(services.chat).provideOn(conn); } @@ -93,9 +108,8 @@ export async function serve(transport: Transport, services: Services): Promise { const agreed = handshake(); diff --git a/runtime/test/generated/comline2/new/wire.ts b/runtime/test/generated/comline2/new/wire.ts new file mode 100644 index 0000000..704ed47 --- /dev/null +++ b/runtime/test/generated/comline2/new/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0xe21c2f843f183318n; diff --git a/runtime/test/generated/comline2/old/chat.ts b/runtime/test/generated/comline2/old/chat.ts index 4cb1828..18d925e 100644 --- a/runtime/test/generated/comline2/old/chat.ts +++ b/runtime/test/generated/comline2/old/chat.ts @@ -5,7 +5,6 @@ import { RuntimeError, resolveKind, checkCall, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -19,24 +18,18 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x70132e163503db63n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x70132e163503db63n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface ChatHelloParams { name: string; } +/** @internal */ export const ChatHelloParamsLayout: Layout = { struct: [["name", "string"]] }; export interface ChatShoutParams { text: string; } +/** @internal */ export const ChatShoutParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Chat { @@ -44,8 +37,10 @@ export interface Chat { shout(peer: Peer, params: ChatShoutParams): Promise; } +/** @internal */ export const CHAT_CALLS = ["hello", "shout"] as const; +/** @internal */ export class ChatDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; diff --git a/runtime/test/generated/comline2/old/connection.ts b/runtime/test/generated/comline2/old/connection.ts index d569015..1268d00 100644 --- a/runtime/test/generated/comline2/old/connection.ts +++ b/runtime/test/generated/comline2/old/connection.ts @@ -1,30 +1,39 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Chat` (in `./chat.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new ChatSender(conn).hello(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, Datagram3Framing, - PackedCodec, Comline2Handshake, Negotiated, - type Codec, type Peer, type Transport, } from "@comline/runtime"; import * as ns_chat from "./chat.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x70132e163503db63n; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history * records it. Its protocols, by wire number: * * - 0 `chat::Chat`, line 0.1.0: `hello` 0, `shout` 1 + * + * @internal */ export const HELLO = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, @@ -38,7 +47,10 @@ export const HELLO = new Uint8Array([ 0xaa, 0xaa, 0x02, 0x00, 0x01, ]); -/** The `comline@2` handshake, with {@link HELLO} and the parameters the package states. */ +/** + * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * @internal + */ export function handshake(): Comline2Handshake { return new Comline2Handshake(HELLO, { scope: "protocol", @@ -69,7 +81,10 @@ export interface Services { chat: ns_chat.Chat; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_chat.ChatDispatcher(services.chat).provideOn(conn); } @@ -93,9 +108,8 @@ export async function serve(transport: Transport, services: Services): Promise { const agreed = handshake(); diff --git a/runtime/test/generated/comline2/old/wire.ts b/runtime/test/generated/comline2/old/wire.ts new file mode 100644 index 0000000..8898f80 --- /dev/null +++ b/runtime/test/generated/comline2/old/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x70132e163503db63n; diff --git a/runtime/test/generated/dependency/only/localdeps/greeting.ts b/runtime/test/generated/dependency/only/localdeps/greeting.ts index c8fdef8..643f01d 100644 --- a/runtime/test/generated/dependency/only/localdeps/greeting.ts +++ b/runtime/test/generated/dependency/only/localdeps/greeting.ts @@ -36,12 +36,14 @@ export interface FooGreetParams { n: number; } +/** @internal */ export const FooGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; export interface Foo { greet(peer: Peer, params: FooGreetParams): Promise; } +/** @internal */ export const FOO_CALLS = ["greet"] as const; export class FooDispatcher implements Dispatch { diff --git a/runtime/test/generated/dependency/own/api.ts b/runtime/test/generated/dependency/own/api.ts index 6b3e01f..2b606ed 100644 --- a/runtime/test/generated/dependency/own/api.ts +++ b/runtime/test/generated/dependency/own/api.ts @@ -5,7 +5,6 @@ import { RuntimeError, resolveKind, checkCall, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -22,14 +21,6 @@ import type { Greeting } from "./localdeps/greeting.js"; * two ends of a connection must agree on it. */ export const IR_HASH = 0x25f4c4d936e7aa90n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x55e3b94344a9c775n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface Message { greeting: Greeting; } @@ -40,14 +31,17 @@ export interface ChatGreetParams { n: number; } +/** @internal */ export const ChatGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; export interface Chat { greet(peer: Peer, params: ChatGreetParams): Promise; } +/** @internal */ export const CHAT_CALLS = ["greet"] as const; +/** @internal */ export class ChatDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; diff --git a/runtime/test/generated/dependency/own/connection.ts b/runtime/test/generated/dependency/own/connection.ts index 282f9f3..7f6dd4c 100644 --- a/runtime/test/generated/dependency/own/connection.ts +++ b/runtime/test/generated/dependency/own/connection.ts @@ -1,30 +1,39 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Chat` (in `./api.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new ChatSender(conn).greet(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, Datagram3Framing, - PackedCodec, Comline2Handshake, Negotiated, - type Codec, type Peer, type Transport, } from "@comline/runtime"; import * as ns_api from "./api.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x55e3b94344a9c775n; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history * records it. Its protocols, by wire number: * * - 0 `api::Chat`, line 0.1.0: `greet` 0 + * + * @internal */ export const HELLO = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, @@ -38,7 +47,10 @@ export const HELLO = new Uint8Array([ 0x5a, 0x5a, 0x01, 0x00, ]); -/** The `comline@2` handshake, with {@link HELLO} and the parameters the package states. */ +/** + * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * @internal + */ export function handshake(): Comline2Handshake { return new Comline2Handshake(HELLO, { scope: "protocol", @@ -69,7 +81,10 @@ export interface Services { chat: ns_api.Chat; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_api.ChatDispatcher(services.chat).provideOn(conn); } @@ -93,9 +108,8 @@ export async function serve(transport: Transport, services: Services): Promise { const agreed = handshake(); diff --git a/runtime/test/generated/dependency/own/localdeps/greeting.ts b/runtime/test/generated/dependency/own/localdeps/greeting.ts index 5c0c403..66fc420 100644 --- a/runtime/test/generated/dependency/own/localdeps/greeting.ts +++ b/runtime/test/generated/dependency/own/localdeps/greeting.ts @@ -4,7 +4,6 @@ import { RuntimeError, resolveKind, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -18,14 +17,6 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x653ed335b8ab7ba0n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x55e3b94344a9c775n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface Greeting { text: string; } @@ -36,12 +27,14 @@ export interface FooGreetParams { n: number; } +/** @internal */ export const FooGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; export interface Foo { greet(peer: Peer, params: FooGreetParams): Promise; } +/** @internal */ export const FOO_CALLS = ["greet"] as const; export class FooDispatcher implements Dispatch { @@ -80,7 +73,7 @@ export class FooDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new Comline2Handshake())`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new Comline2Handshake())` (`Format` and `CONNECTION_IR_HASH` are in `../wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(FooDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/dependency/own/wire.ts b/runtime/test/generated/dependency/own/wire.ts new file mode 100644 index 0000000..bf972a3 --- /dev/null +++ b/runtime/test/generated/dependency/own/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x55e3b94344a9c775n; diff --git a/runtime/test/generated/hello/connection.ts b/runtime/test/generated/hello/connection.ts index 23aaa48..0f8f42d 100644 --- a/runtime/test/generated/hello/connection.ts +++ b/runtime/test/generated/hello/connection.ts @@ -1,28 +1,38 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Link` (in `./hello.js`). + * - Serve with `serve(transport, { link })`; `accept(transport, { link })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new LinkSender(conn).now(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, - PackedCodec, - type Codec, type Transport, } from "@comline/runtime"; import { HelloHandshake } from "acme-encodings"; import * as ns_hello from "./hello.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xe3d09136af39a1c1n; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ export interface Services { link: ns_hello.Link; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_hello.LinkDispatcher(services.link).provideOn(conn); } @@ -44,9 +54,8 @@ export async function serve(transport: Transport, services: Services): Promise { const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, undefined, new HelloHandshake()); diff --git a/runtime/test/generated/hello/hello.ts b/runtime/test/generated/hello/hello.ts index 706e14a..8f625aa 100644 --- a/runtime/test/generated/hello/hello.ts +++ b/runtime/test/generated/hello/hello.ts @@ -7,7 +7,6 @@ import { RuntimeError, resolveKind, DatagramFraming, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -20,22 +19,17 @@ import { import { HelloHandshake } from "acme-encodings"; +import { Format } from "./wire.js"; + /** Canonical digest of the frozen IR this file was generated from — the * two ends of a connection must agree on it. */ export const IR_HASH = 0xe3d09136af39a1c1n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xe3d09136af39a1c1n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface Clock { now(): Promise; } +/** @internal */ export const CLOCK_CALLS = ["now"] as const; export class ClockDispatcher implements Dispatch { @@ -92,8 +86,10 @@ export interface Link { now(peer: Peer): Promise; } +/** @internal */ export const LINK_CALLS = ["now"] as const; +/** @internal */ export class LinkDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 1; @@ -129,7 +125,7 @@ export class LinkDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new HelloHandshake())`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH, undefined, new HelloHandshake())` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(LinkDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/hello/wire.ts b/runtime/test/generated/hello/wire.ts new file mode 100644 index 0000000..a5a0b7d --- /dev/null +++ b/runtime/test/generated/hello/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0xe3d09136af39a1c1n; diff --git a/runtime/test/generated/link/connection.ts b/runtime/test/generated/link/connection.ts new file mode 100644 index 0000000..e290d9d --- /dev/null +++ b/runtime/test/generated/link/connection.ts @@ -0,0 +1,77 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +/** + * Where to start: + * + * - Implement what you provide: `Chat`, `Events` (in `./link.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport, { events })`. + * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + +import { + Connection, + type Transport, +} from "@comline/runtime"; +import * as ns_link from "./link.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface Services { + chat: ns_link.Chat; +} + +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideServices(conn: Connection, services: Services): void { + new ns_link.ChatDispatcher(services.chat).provideOn(conn); +} + +/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface ClientServices { + events: ns_link.Events; +} + +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideClientServices(conn: Connection, services: ClientServices): void { + new ns_link.EventsDispatcher(services.events).provideOn(conn); +} + +/** +* Accept a connection over `transport`: run the handshake, then provide +* every protocol in `services` on it. The connection comes back serving, +* so the server can call the client through it. +*/ +export async function accept(transport: Transport, services: Services): Promise { + const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH); + provideServices(conn, services); + return conn; +} + +/** {@link accept}, then serve every call until the peer leaves. */ +export async function serve(transport: Transport, services: Services): Promise { + await (await accept(transport, services)).closed; +} + +/** +* Dial over `transport`: run the handshake, then provide every protocol in +* `services`, which the server calls. Call the server's protocols through +* their senders. +*/ +export async function connect(transport: Transport, services: ClientServices): Promise { + const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); + provideClientServices(conn, services); + return conn; +} diff --git a/runtime/test/generated/link.ts b/runtime/test/generated/link/link.ts similarity index 92% rename from runtime/test/generated/link.ts rename to runtime/test/generated/link/link.ts index 331f142..2f9b1d3 100644 --- a/runtime/test/generated/link.ts +++ b/runtime/test/generated/link/link.ts @@ -4,7 +4,6 @@ import { RuntimeError, resolveKind, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -18,18 +17,11 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x9704f8e8a43acdbdn; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x9704f8e8a43acdbdn; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface ChatSendParams { text: string; } +/** @internal */ export const ChatSendParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Chat { @@ -37,8 +29,10 @@ export interface Chat { count(peer: Peer): Promise; } +/** @internal */ export const CHAT_CALLS = ["send", "count"] as const; +/** @internal */ export class ChatDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; @@ -83,7 +77,7 @@ export class ChatDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(ChatDispatcher.PROTOCOL, this); } @@ -119,6 +113,7 @@ export interface EventsMessageParams { text: string; } +/** @internal */ export const EventsMessageParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Events { @@ -126,8 +121,10 @@ export interface Events { ping(peer: Peer): Promise; } +/** @internal */ export const EVENTS_CALLS = ["message", "ping"] as const; +/** @internal */ export class EventsDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 1; @@ -172,7 +169,7 @@ export class EventsDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(EventsDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/link/wire.ts b/runtime/test/generated/link/wire.ts new file mode 100644 index 0000000..16a2979 --- /dev/null +++ b/runtime/test/generated/link/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x9704f8e8a43acdbdn; diff --git a/runtime/test/generated/link_jsonrpc/connection.ts b/runtime/test/generated/link_jsonrpc/connection.ts new file mode 100644 index 0000000..cb521da --- /dev/null +++ b/runtime/test/generated/link_jsonrpc/connection.ts @@ -0,0 +1,79 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +/** + * Where to start: + * + * - Implement what you provide: `Chat`, `Events` (in `./link.js`). + * - Serve with `serve(transport, { chat })`; `accept(transport, { chat })` takes the same and hands back the connection. + * - Dial with `connect(transport, { events })`. + * - Call the other end with `new ChatSender(conn).send(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + +import { + Connection, + JsonCodec, + JsonRpcConnectionFraming, + type Transport, +} from "@comline/runtime"; +import * as ns_link from "./link.js"; +import { CONNECTION_IR_HASH } from "./wire.js"; + +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; + +/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface Services { + chat: ns_link.Chat; +} + +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideServices(conn: Connection, services: Services): void { + new ns_link.ChatDispatcher(services.chat).provideOn(conn); +} + +/** What the dialling side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface ClientServices { + events: ns_link.Events; +} + +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ +export function provideClientServices(conn: Connection, services: ClientServices): void { + new ns_link.EventsDispatcher(services.events).provideOn(conn); +} + +/** +* Accept a connection over `transport`: run the handshake, then provide +* every protocol in `services` on it. The connection comes back serving, +* so the server can call the client through it. +*/ +export async function accept(transport: Transport, services: Services): Promise { + const conn = await Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming()); + provideServices(conn, services); + return conn; +} + +/** {@link accept}, then serve every call until the peer leaves. */ +export async function serve(transport: Transport, services: Services): Promise { + await (await accept(transport, services)).closed; +} + +/** +* Dial over `transport`: run the handshake, then provide every protocol in +* `services`, which the server calls. Call the server's protocols through +* their senders. +*/ +export async function connect(transport: Transport, services: ClientServices): Promise { + const conn = await Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming()); + provideClientServices(conn, services); + return conn; +} diff --git a/runtime/test/generated/link_jsonrpc.ts b/runtime/test/generated/link_jsonrpc/link.ts similarity index 94% rename from runtime/test/generated/link_jsonrpc.ts rename to runtime/test/generated/link_jsonrpc/link.ts index 52efa8d..912d960 100644 --- a/runtime/test/generated/link_jsonrpc.ts +++ b/runtime/test/generated/link_jsonrpc/link.ts @@ -17,14 +17,11 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0xb4520b20f67b5ccbn; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xb4520b20f67b5ccbn; - export interface ChatSendParams { text: string; } +/** @internal */ export const ChatSendParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Chat { @@ -32,8 +29,10 @@ export interface Chat { count(peer: Peer): Promise; } +/** @internal */ export const CHAT_CALLS = ["send", "count"] as const; +/** @internal */ export class ChatDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; @@ -78,7 +77,7 @@ export class ChatDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming())`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming())` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(ChatDispatcher.PROTOCOL, this); } @@ -114,6 +113,7 @@ export interface EventsMessageParams { text: string; } +/** @internal */ export const EventsMessageParamsLayout: Layout = { struct: [["text", "string"]] }; export interface Events { @@ -121,8 +121,10 @@ export interface Events { ping(peer: Peer): Promise; } +/** @internal */ export const EVENTS_CALLS = ["link.Events/message", "link.Events/ping"] as const; +/** @internal */ export class EventsDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 1; @@ -167,7 +169,7 @@ export class EventsDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming())`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, new JsonCodec(), CONNECTION_IR_HASH, new JsonRpcConnectionFraming())` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(EventsDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/link_jsonrpc/wire.ts b/runtime/test/generated/link_jsonrpc/wire.ts new file mode 100644 index 0000000..0724716 --- /dev/null +++ b/runtime/test/generated/link_jsonrpc/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0xb4520b20f67b5ccbn; diff --git a/runtime/test/generated/nested/chat/admin.ts b/runtime/test/generated/nested/chat/admin.ts index eb84a27..02baaeb 100644 --- a/runtime/test/generated/nested/chat/admin.ts +++ b/runtime/test/generated/nested/chat/admin.ts @@ -5,7 +5,6 @@ import { RuntimeError, resolveKind, checkCall, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -19,14 +18,6 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0xa6f61afefe65d74an; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xa6f61afefe65d74an; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface Notice { text: string; } @@ -37,14 +28,17 @@ export interface AdminGreetParams { n: number; } +/** @internal */ export const AdminGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; export interface Admin { greet(peer: Peer, params: AdminGreetParams): Promise; } +/** @internal */ export const ADMIN_CALLS = ["greet"] as const; +/** @internal */ export class AdminDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; diff --git a/runtime/test/generated/nested/connection.ts b/runtime/test/generated/nested/connection.ts index dc47823..82a2972 100644 --- a/runtime/test/generated/nested/connection.ts +++ b/runtime/test/generated/nested/connection.ts @@ -1,30 +1,39 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Admin` (in `./chat/admin.js`). + * - Serve with `serve(transport, { admin })`; `accept(transport, { admin })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new AdminSender(conn).greet(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, Datagram3Framing, - PackedCodec, Comline2Handshake, Negotiated, - type Codec, type Peer, type Transport, } from "@comline/runtime"; import * as ns_chat_admin from "./chat/admin.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xa6f61afefe65d74an; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** * This end's `comline@2` Hello: version 0.1.0 of package `0123456789abcdef0123456789abcdef`, as its history * records it. Its protocols, by wire number: * * - 0 `chat::admin::Admin`, line 0.1.0: `greet` 0 + * + * @internal */ export const HELLO = new Uint8Array([ 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, @@ -38,7 +47,10 @@ export const HELLO = new Uint8Array([ 0x5a, 0x5a, 0x01, 0x00, ]); -/** The `comline@2` handshake, with {@link HELLO} and the parameters the package states. */ +/** + * The `comline@2` handshake, with {@link HELLO} and the parameters the package states. + * @internal + */ export function handshake(): Comline2Handshake { return new Comline2Handshake(HELLO, { scope: "protocol", @@ -69,7 +81,10 @@ export interface Services { admin: ns_chat_admin.Admin; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_chat_admin.AdminDispatcher(services.admin).provideOn(conn); } @@ -93,9 +108,8 @@ export async function serve(transport: Transport, services: Services): Promise { const agreed = handshake(); diff --git a/runtime/test/generated/nested/wire.ts b/runtime/test/generated/nested/wire.ts new file mode 100644 index 0000000..cf9accb --- /dev/null +++ b/runtime/test/generated/nested/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0xa6f61afefe65d74an; diff --git a/runtime/test/generated/reserved/connection.ts b/runtime/test/generated/reserved/connection.ts index f57a911..01b5cac 100644 --- a/runtime/test/generated/reserved/connection.ts +++ b/runtime/test/generated/reserved/connection.ts @@ -1,27 +1,37 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `static_` (in `./names.js`). + * - Serve with `serve(transport, { static })`; `accept(transport, { static })` takes the same and hands back the connection. + * - Dial with `connect(transport)`. + * - Call the other end with `new staticSender(conn).typeof(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, - PackedCodec, - type Codec, type Transport, } from "@comline/runtime"; import * as ns_names from "./names.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xc579d2e8df3a409bn; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ export interface Services { static: ns_names.static_; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_names.staticDispatcher(services.static).provideOn(conn); } @@ -43,9 +53,8 @@ export async function serve(transport: Transport, services: Services): Promise { const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH); diff --git a/runtime/test/generated/reserved/names.ts b/runtime/test/generated/reserved/names.ts index 11f655d..2ae7a0b 100644 --- a/runtime/test/generated/reserved/names.ts +++ b/runtime/test/generated/reserved/names.ts @@ -4,7 +4,6 @@ import { RuntimeError, resolveKind, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -18,14 +17,6 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0xc4c5bf4244cbec4an; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0xc579d2e8df3a409bn; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export const class_ = { delete: "delete", new: "new", @@ -69,6 +60,7 @@ export interface staticTypeofParams { new: function_; } +/** @internal */ export const staticTypeofParamsLayout: Layout = { struct: [["default", "u8"], ["new", () => functionLayout]] }; export interface static_ { @@ -76,8 +68,10 @@ export interface static_ { typeof(peer: Peer, params: staticTypeofParams): Promise; } +/** @internal */ export const STATIC_CALLS = ["typeof"] as const; +/** @internal */ export class staticDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; @@ -115,7 +109,7 @@ export class staticDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(staticDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/reserved/wire.ts b/runtime/test/generated/reserved/wire.ts new file mode 100644 index 0000000..822f93e --- /dev/null +++ b/runtime/test/generated/reserved/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0xc579d2e8df3a409bn; diff --git a/runtime/test/generated/services/connection.ts b/runtime/test/generated/services/connection.ts index 9134156..b120e5b 100644 --- a/runtime/test/generated/services/connection.ts +++ b/runtime/test/generated/services/connection.ts @@ -1,21 +1,28 @@ // Generated by Comline // For TypeScript 5.0 or later; verified up to 5.9. +/** + * Where to start: + * + * - Implement what you provide: `Account`, `Player` (in `./game.js`); `Inventory`, `Events` (in `./items.js`). + * - Serve with `serve(transport, { account, player, inventory })`; `accept(transport, { account, player, inventory })` takes the same and hands back the connection. + * - Dial with `connect(transport, { events })`. + * - Call the other end with `new AccountSender(conn).login(…)`, on the connection `connect` returns or the peer a handler is given. + * + * What is marked internal is wire plumbing: exported for hand-written use, and not what + * a user calls. + */ + import { Connection, - PackedCodec, - type Codec, type Transport, } from "@comline/runtime"; import * as ns_game from "./game.js"; import * as ns_items from "./items.js"; +import { CONNECTION_IR_HASH, Format } from "./wire.js"; -/** The package's wire format (`wire.format`). */ -export const Format: Codec = new PackedCodec(); - -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x795ece8a736e83e2n; +/** The package's wire format and the digest of every schema in it, which every file of the package shares. */ +export { CONNECTION_IR_HASH, Format } from "./wire.js"; /** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ export interface Services { @@ -24,7 +31,10 @@ export interface Services { inventory: ns_items.Inventory; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideServices(conn: Connection, services: Services): void { new ns_game.AccountDispatcher(services.account).provideOn(conn); new ns_game.PlayerDispatcher(services.player).provideOn(conn); @@ -36,7 +46,10 @@ export interface ClientServices { events: ns_items.Events; } -/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +/** + * Provide every protocol in `services` on `conn`: the peer's calls to them come here. + * @internal + */ export function provideClientServices(conn: Connection, services: ClientServices): void { new ns_items.EventsDispatcher(services.events).provideOn(conn); } diff --git a/runtime/test/generated/services/game.ts b/runtime/test/generated/services/game.ts index d488062..f823ae2 100644 --- a/runtime/test/generated/services/game.ts +++ b/runtime/test/generated/services/game.ts @@ -4,7 +4,6 @@ import { RuntimeError, resolveKind, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -18,26 +17,21 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x0e7319ed91fcea68n; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x795ece8a736e83e2n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface AccountLoginParams { name: string; } +/** @internal */ export const AccountLoginParamsLayout: Layout = { struct: [["name", "string"]] }; export interface Account { login(peer: Peer, params: AccountLoginParams): Promise; } +/** @internal */ export const ACCOUNT_CALLS = ["login"] as const; +/** @internal */ export class AccountDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 0; @@ -74,7 +68,7 @@ export class AccountDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(AccountDispatcher.PROTOCOL, this); } @@ -103,14 +97,17 @@ export interface PlayerLevelParams { id: number; } +/** @internal */ export const PlayerLevelParamsLayout: Layout = { struct: [["id", "u32"]] }; export interface Player { level(peer: Peer, params: PlayerLevelParams): Promise; } +/** @internal */ export const PLAYER_CALLS = ["level"] as const; +/** @internal */ export class PlayerDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 1; @@ -147,7 +144,7 @@ export class PlayerDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(PlayerDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/services/items.ts b/runtime/test/generated/services/items.ts index 2ea774a..fb57036 100644 --- a/runtime/test/generated/services/items.ts +++ b/runtime/test/generated/services/items.ts @@ -4,7 +4,6 @@ import { RuntimeError, resolveKind, - PackedCodec, type Codec, type Connection, type Dispatch, @@ -18,14 +17,6 @@ import { * two ends of a connection must agree on it. */ export const IR_HASH = 0x5c9c55a1bd9938afn; -/** Digest of every schema in the package — what a connection's handshake -* checks, so both ends agree on each protocol's number. */ -export const CONNECTION_IR_HASH = 0x795ece8a736e83e2n; - -/** The package's wire format (`wire.format`): what this file's helpers -* encode with, and what the peer has to speak too. */ -export const Format: Codec = new PackedCodec(); - export interface Item { name: string; count: number; @@ -37,14 +28,17 @@ export interface InventoryItemsParams { id: number; } +/** @internal */ export const InventoryItemsParamsLayout: Layout = { struct: [["id", "u32"]] }; export interface Inventory { items(peer: Peer, params: InventoryItemsParams): Promise; } +/** @internal */ export const INVENTORY_CALLS = ["items"] as const; +/** @internal */ export class InventoryDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 2; @@ -81,7 +75,7 @@ export class InventoryDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.accept(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(InventoryDispatcher.PROTOCOL, this); } @@ -110,14 +104,17 @@ export interface EventsChangedParams { count: number; } +/** @internal */ export const EventsChangedParamsLayout: Layout = { struct: [["count", "u8"]] }; export interface Events { changed(peer: Peer, params: EventsChangedParams): Promise; } +/** @internal */ export const EVENTS_CALLS = ["changed"] as const; +/** @internal */ export class EventsDispatcher implements Dispatch { /** This protocol's number on a connection. */ static readonly PROTOCOL = 3; @@ -154,7 +151,7 @@ export class EventsDispatcher implements Dispatch { } } - /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, Format, CONNECTION_IR_HASH)`, or let the package's `serve` / `connect` do it. */ + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with `Connection.connect(transport, Format, CONNECTION_IR_HASH)` (`Format` and `CONNECTION_IR_HASH` are in `./wire.js`), or let the package's `serve` / `connect` do it. */ provideOn(conn: Connection): void { conn.provide(EventsDispatcher.PROTOCOL, this); } diff --git a/runtime/test/generated/services/wire.ts b/runtime/test/generated/services/wire.ts new file mode 100644 index 0000000..16fbd8f --- /dev/null +++ b/runtime/test/generated/services/wire.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + PackedCodec, + type Codec, +} from "@comline/runtime"; + +/** The package's wire format (`wire.format`). */ +export const Format: Codec = new PackedCodec(); + +/** Digest of every schema in the package — what a connection's handshake +* checks, so both ends agree on each protocol's number. */ +export const CONNECTION_IR_HASH = 0x795ece8a736e83e2n; diff --git a/runtime/test/wire-invariance.json b/runtime/test/wire-invariance.json index 8d8943e..edd14bd 100644 --- a/runtime/test/wire-invariance.json +++ b/runtime/test/wire-invariance.json @@ -37,9 +37,9 @@ "CborCodec" ] }, - "bounds.ts": { + "bounds/": { "files": { - "bounds.ts": { + "bounds/account.ts": { "irHash": "0x17305ca8c4eea701", "protocolNumbers": [ 0, @@ -441,9 +441,9 @@ "PackedCodec" ] }, - "link.ts": { + "link/": { "files": { - "link.ts": { + "link/link.ts": { "irHash": "0x9704f8e8a43acdbd", "protocolNumbers": [ 0, @@ -483,9 +483,9 @@ "PackedCodec" ] }, - "link_jsonrpc.ts": { + "link_jsonrpc/": { "files": { - "link_jsonrpc.ts": { + "link_jsonrpc/link.ts": { "irHash": "0xb4520b20f67b5ccb", "protocolNumbers": [ 0, @@ -521,7 +521,9 @@ "0xb4520b20f67b5ccb" ], "hello": [], - "format": [] + "format": [ + "PackedCodec" + ] }, "nested/": { "files": { diff --git a/runtime/tsconfig.stripped.json b/runtime/tsconfig.stripped.json new file mode 100644 index 0000000..b9328bb --- /dev/null +++ b/runtime/tsconfig.stripped.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.generated.json", + "compilerOptions": { + "skipLibCheck": false, + "types": [], + "paths": { + "@comline/runtime": ["./dist/src/index.d.ts"], + "acme-encodings": ["./dist/stripped/test/generated/acme-encodings.d.ts"] + } + }, + "exclude": [], + "include": ["dist/stripped/test/generated/**/*.d.ts"] +}