diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index 0ea84ee..413e86e 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -8,7 +8,7 @@ license = "GPL-3.0-only" # Consumed by git rev (see ComlineProject/docs → Design → Runtime & generation # repository structure — no crates.io publishing at this stage). Local # iteration: add a `[patch]` onto a sibling checkout. -comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "05771e0679ff514da3ba73a3b0b94643e5262fe5" } +comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "da81b688c949a0ebad4f213d6fdb648920cf641d" } comline-core = { git = "https://github.com/ComlineProject/core", rev = "868e8310e33df317e3cba4f76b81fbcd8639c1c2", default-features = false } eyre = "0.6.8" @@ -21,6 +21,6 @@ path = "src/bin/comline-gen-typescript.rs" # The conformance corpus: every fixture is a whole package. Same generation # rev as `comline-codegen` above, so the corpus and the generator share one # `comline-codegen`. -comline-conformance = { git = "https://github.com/ComlineProject/generation", rev = "05771e0679ff514da3ba73a3b0b94643e5262fe5" } +comline-conformance = { git = "https://github.com/ComlineProject/generation", rev = "da81b688c949a0ebad4f213d6fdb648920cf641d" } # The tests compile schemas, so they need core's compiler. comline-core = { git = "https://github.com/ComlineProject/core", rev = "868e8310e33df317e3cba4f76b81fbcd8639c1c2" } diff --git a/codegen/src/generator.rs b/codegen/src/generator.rs index 7a8afe2..ab7ce1c 100644 --- a/codegen/src/generator.rs +++ b/codegen/src/generator.rs @@ -126,7 +126,7 @@ pub fn generate_typescript(req: &GenerateRequest) -> Result> // collision in the last one does not arrive after the earlier files are // already written. for (namespace, units) in emitted { - collisions::check(namespace, units, derived_names(units, &req.schemas, &req.encodings))?; + collisions::check(namespace, units, derived_names(units, &req.schemas, &req.dependencies, &req.encodings))?; } // Loose files or a `src/` tree, the package module has a file of its own, // which a schema of that name would be. @@ -389,7 +389,12 @@ fn package_json( /// The shapes differ from Rust's - there is no per-function error type and no /// protocol-wide union here, but every `error` grows an `Error` suffix, which /// Rust has no equivalent of. Keep it in step with the emitters below. -fn derived_names(units: &[FrozenUnit], schemas: &[(String, Vec)], encodings: &Encodings) -> Vec { +fn derived_names( + units: &[FrozenUnit], + schemas: &[(String, Vec)], + dependencies: &[String], + encodings: &Encodings, +) -> Vec { let mut derived = Vec::new(); let mut any_protocol = false; let mut any_connection = false; @@ -432,7 +437,7 @@ fn derived_names(units: &[FrozenUnit], schemas: &[(String, Vec)], en format!("{proto}Dispatcher"), format!("protocol `{proto}`'s dispatcher"), )); - if connections::on_connection(schemas, parameters) { + if connections::on_connection_among(schemas, dependencies, parameters) { any_connection = true; derived.push(Derived::new( format!("{proto}Sender"), @@ -551,12 +556,10 @@ fn schema_source( .. } => { // `facts::check` has vouched for every protocol that needs facts. - let addressing = connections::on_connection(schemas, parameters) + let addressing = connections::on_connection_among(schemas, &req.dependencies, parameters) .then(|| { - comline_codegen::facts::addressing( - req.facts.as_ref(), - schemas, - encodings, + comline_codegen::facts::addressing_in( + req, namespace, name, parameters, @@ -590,7 +593,7 @@ fn schema_source( // Which framings the protocols in this file reach for: the lockstep ones // only, since a protocol on a connection names none of its own. - let on_connection = |parameters: &[FrozenUnit]| connections::on_connection(schemas, parameters); + let on_connection = |parameters: &[FrozenUnit]| connections::on_connection_among(schemas, &req.dependencies, parameters); let picks: Vec = units .iter() .filter_map(|u| match u { @@ -621,9 +624,12 @@ fn schema_source( values.extend(["Client", "Server"]); } values.extend(["RuntimeError", "resolveKind"]); + // Only a protocol the package reaches is checked against its facts: a + // dependency's is addressed by position, so has nothing to check. if units.iter().any(|u| { - matches!(u, FrozenUnit::Protocol { parameters, .. } + matches!(u, FrozenUnit::Protocol { name, parameters, .. } if on_connection(parameters) + && connections::reached(&req.dependencies, namespace, name) && connections::handshake_name(parameters) == comline_codegen::facts::HANDSHAKE_COMLINE2) }) { values.push("checkCall"); @@ -1095,7 +1101,7 @@ const PACKAGE_MODULE: &str = "connection"; /// emits is on a connection, or when its protocols don't share one /// (`comline generation` says why). fn package_module(header: &str, req: &GenerateRequest, emitted: &[(String, Vec)], codec: &str) -> Option { - let package = connections::package_connection(&req.schemas).ok()??; + 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() diff --git a/codegen/tests/dependency_protocols.rs b/codegen/tests/dependency_protocols.rs new file mode 100644 index 0000000..2773983 --- /dev/null +++ b/codegen/tests/dependency_protocols.rs @@ -0,0 +1,114 @@ +//! A dependency's protocol that the package doesn't reach (generation#143, step +//! 0 of the dependency protocols proposal): it is generated as a type, but it +//! isn't on the package's connection, so it isn't in `Services`, isn't in the +//! Hello, and is addressed by position instead of by the package's wire +//! numbers. +//! +//! Both packages of generation's conformance fixtures are generated, and their +//! output is kept in `runtime/test/generated/dependency/` so the Node job +//! type-checks it (`npm run typecheck:generated`). Regenerate with +//! `TS_BLESS=1 cargo test -p comline-codegen-typescript`. + +use comline_codegen::validation::ValidateOnDecode; +use comline_codegen::{connections, facts, GenerateRequest, PackageMeta, TargetLanguage}; +use comline_codegen_typescript::generate_typescript; +use comline_conformance::{dependency_and_own_protocols, dependency_protocol, Fixture}; + +/// The request `comline generation` would send for `fx`: with the facts of the +/// package's own schemas when they're needed. +fn request(fx: &Fixture) -> GenerateRequest { + let dependencies: Vec = fx.dependencies.iter().map(|d| d.to_string()).collect(); + let own: Vec<_> = fx + .schemas + .iter() + .filter(|(namespace, _)| !connections::is_dependency(&dependencies, namespace)) + .cloned() + .collect(); + let mut req = GenerateRequest { + mode: fx.mode, + schemas: fx.schemas.clone(), + package: PackageMeta { name: "conformance".into(), version: "0.1.0".into() }, + target: TargetLanguage { + language: "typescript".into(), + version: comline_codegen_typescript::LANG_VERSION.into(), + }, + wire_format: "packed@1".into(), + external_std: false, + validate_on_decode: ValidateOnDecode::Off, + async_api: false, + encodings: comline_codegen::encodings::official_for("typescript"), + facts: None, + dependencies, + }; + if facts::needed_in(&req) { + req.facts = Some(comline_conformance::facts_for(&own, "packed@1")); + } + req +} + +/// Every file generated for `fx`, checked against `runtime/test/generated/dependency/`. +fn generated(fx: &Fixture, dir: &str) -> Vec<(String, String)> { + let req = request(fx); + let files = generate_typescript(&req).unwrap_or_else(|e| panic!("{}: {e:#}", fx.name)); + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../runtime/test/generated/dependency").join(dir); + let mut out = Vec::new(); + for file in files { + let path = root.join(&file.path); + if std::env::var_os("TS_BLESS").is_some() { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, &file.contents).unwrap(); + } else { + let committed = std::fs::read_to_string(&path).unwrap_or_default(); + assert_eq!( + file.contents, committed, + "generated output drifted from {} — re-bless with TS_BLESS=1 cargo test -p comline-codegen-typescript", + path.display() + ); + } + out.push((file.path.to_str().unwrap().to_string(), file.contents)); + } + out +} + +fn file<'a>(files: &'a [(String, String)], path: &str) -> &'a str { + &files.iter().find(|(p, _)| p == path).unwrap_or_else(|| panic!("no `{path}` in {:?}", files.iter().map(|(p, _)| p).collect::>())).1 +} + +/// A package that uses only a dependency's types generates, and has no +/// connection: the dependency's protocol is a type to generate, nothing more. +#[test] +fn a_package_using_only_a_dependencys_types_has_no_connection() { + let files = generated(&dependency_protocol(), "only"); + assert!(files.iter().all(|(p, _)| p != "connection.ts"), "{:?}", files.iter().map(|(p, _)| p).collect::>()); + // The dependency's protocol keeps its generated types. + let greeting = file(&files, "localdeps/greeting.ts"); + assert!(greeting.contains("export interface Foo"), "{greeting}"); + assert!(greeting.contains("export class FooDispatcher"), "{greeting}"); + // Nothing in it is addressed by the package's facts. + assert!(!greeting.contains("checkCall"), "{greeting}"); +} + +/// With a protocol of its own, the package's connection serves that one: +/// `Services` and the Hello leave the dependency's out, which is addressed by +/// position where `Chat` is addressed by its wire numbers. +#[test] +fn a_dependencys_protocol_is_not_in_services_or_the_hello() { + let files = generated(&dependency_and_own_protocols(), "own"); + let connection = file(&files, "connection.ts"); + assert!(connection.contains("export interface Services {\n chat: ns_api.Chat;\n}"), "{connection}"); + assert!(!connection.contains("Foo"), "{connection}"); + assert!(!connection.contains("localdeps"), "{connection}"); + assert!(!connection.contains("ns_localdeps"), "{connection}"); + + // The Hello and the protocols by number name only `Chat`. + assert!(connection.contains(" * - 0 `api::Chat`, line 0.1.0: `greet` 0\n"), "{connection}"); + assert!(connection.contains("new Map([[0, \"api::Chat\"]])"), "{connection}"); + + // The dependency's protocol is still generated, with no wire numbers of the + // package's: its calls are by position. + let greeting = file(&files, "localdeps/greeting.ts"); + assert!(greeting.contains("export interface Foo"), "{greeting}"); + assert!(!greeting.contains("checkCall"), "{greeting}"); + let api = file(&files, "api.ts"); + assert!(api.contains("checkCall"), "{api}"); +} diff --git a/codegen/tests/generate.rs b/codegen/tests/generate.rs index 53b7872..e608bd2 100644 --- a/codegen/tests/generate.rs +++ b/codegen/tests/generate.rs @@ -20,6 +20,7 @@ fn code_req(schemas: &[(String, Vec)]) -> GenerateRequest { async_api: false, encodings: comline_codegen::encodings::official_for("typescript"), facts: None, + dependencies: vec![], } } @@ -38,6 +39,7 @@ fn lib_req(schemas: &[(String, Vec)]) -> GenerateRequest { async_api: false, encodings: comline_codegen::encodings::official_for("typescript"), facts: None, + dependencies: vec![], } } diff --git a/codegen/tests/stdio.rs b/codegen/tests/stdio.rs index 7953e69..e02bc06 100644 --- a/codegen/tests/stdio.rs +++ b/codegen/tests/stdio.rs @@ -38,6 +38,7 @@ fn request(fx: &Fixture, version: &str) -> GenerateRequest { async_api: fx.async_api, encodings: comline_codegen::encodings::official_for("typescript"), facts: None, + dependencies: fx.dependencies.iter().map(|d| d.to_string()).collect(), } } diff --git a/runtime/test/generated/dependency/only/api.ts b/runtime/test/generated/dependency/only/api.ts new file mode 100644 index 0000000..35d787a --- /dev/null +++ b/runtime/test/generated/dependency/only/api.ts @@ -0,0 +1,14 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import type { Layout } from "@comline/runtime"; + +import { GreetingLayout } from "./localdeps/greeting.js"; +import type { Greeting } from "./localdeps/greeting.js"; + +export interface Message { + greeting: Greeting; +} + +export const MessageLayout: Layout = { struct: [["greeting", () => GreetingLayout]] }; + diff --git a/runtime/test/generated/dependency/only/localdeps/greeting.ts b/runtime/test/generated/dependency/only/localdeps/greeting.ts new file mode 100644 index 0000000..c8fdef8 --- /dev/null +++ b/runtime/test/generated/dependency/only/localdeps/greeting.ts @@ -0,0 +1,107 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + PackedCodec, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +/** 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 = 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 = 0xc1fed94bf808faean; + +/** 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; +} + +export const GreetingLayout: Layout = { struct: [["text", "string"]] }; + +export interface FooGreetParams { + n: number; +} + +export const FooGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Foo { + greet(peer: Peer, params: FooGreetParams): Promise; +} + +export const FOO_CALLS = ["greet"] as const; + +export class FooDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly impl: Foo; + + constructor(impl: Foo) { + this.impl = impl; + } + + calls(): readonly string[] { + return FOO_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, FooGreetParamsLayout); + reply.ok(codec.encode((await this.impl.greet(peer, p)) ?? null, "u32")); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** 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. */ + provideOn(conn: Connection): void { + conn.provide(FooDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Foo` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class FooSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async greet(params: FooGreetParams): Promise { + const env = await this.peer.call(FooSender.PROTOCOL, { id: 0, name: "greet" }, params, { layout: FooGreetParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + diff --git a/runtime/test/generated/dependency/own/api.ts b/runtime/test/generated/dependency/own/api.ts new file mode 100644 index 0000000..6b3e01f --- /dev/null +++ b/runtime/test/generated/dependency/own/api.ts @@ -0,0 +1,112 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + checkCall, + PackedCodec, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +import { GreetingLayout } from "./localdeps/greeting.js"; +import type { Greeting } from "./localdeps/greeting.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 = 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; +} + +export const MessageLayout: Layout = { struct: [["greeting", () => GreetingLayout]] }; + +export interface ChatGreetParams { + n: number; +} + +export const ChatGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Chat { + greet(peer: Peer, params: ChatGreetParams): Promise; +} + +export const CHAT_CALLS = ["greet"] as const; + +export class ChatDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly impl: Chat; + + constructor(impl: Chat) { + this.impl = impl; + } + + calls(): readonly string[] { + return CHAT_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, ChatGreetParamsLayout); + reply.ok(codec.encode((await this.impl.greet(peer, p)) ?? null, "u32")); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** Provide this protocol on `conn`: the peer's calls to it come here. Open `conn` with the package's `accept` / `connect`, which run `comline@2` with this package's facts, or let the package's `serve` / `connect` do it. */ + provideOn(conn: Connection): void { + conn.provide(ChatDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Chat` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class ChatSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async greet(params: ChatGreetParams): Promise { + checkCall(this.peer, ChatSender.PROTOCOL, 0, "api::Chat", "greet"); + const env = await this.peer.call(ChatSender.PROTOCOL, { id: 0, name: "greet" }, params, { layout: ChatGreetParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + diff --git a/runtime/test/generated/dependency/own/connection.ts b/runtime/test/generated/dependency/own/connection.ts new file mode 100644 index 0000000..282f9f3 --- /dev/null +++ b/runtime/test/generated/dependency/own/connection.ts @@ -0,0 +1,105 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + Connection, + Datagram3Framing, + PackedCodec, + Comline2Handshake, + Negotiated, + type Codec, + type Peer, + type Transport, +} from "@comline/runtime"; +import * as ns_api from "./api.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; + +/** + * 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 + */ +export const HELLO = new Uint8Array([ + 0x43, 0x4f, 0x02, 0x01, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, + 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x00, + 0x00, 0x03, 0x00, 0x52, 0x18, 0x5f, 0xd6, 0x09, 0x92, 0xad, 0x43, 0x02, + 0x9c, 0xc2, 0x99, 0x62, 0xb3, 0xaf, 0xb4, 0x01, 0x4e, 0x6e, 0xde, 0x7c, + 0xc8, 0xf5, 0xaa, 0x52, 0xce, 0x16, 0x9f, 0x9e, 0x65, 0x67, 0x40, 0xe2, + 0x02, 0x58, 0x80, 0x9a, 0xaf, 0x4b, 0x47, 0xd5, 0x6c, 0x69, 0xb2, 0xc1, + 0xfc, 0x9d, 0x43, 0x30, 0xc1, 0x01, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x01, 0x00, +]); + +/** The `comline@2` handshake, with {@link HELLO} and the parameters the package states. */ +export function handshake(): Comline2Handshake { + return new Comline2Handshake(HELLO, { + scope: "protocol", + newerConsumer: "degrade", + sameVersionDiffers: "refuse", + exchange: "offer", + }); +} + +/** The package's protocols on the connection, by wire number. */ +const PROTOCOLS = new Map([[0, "api::Chat"]]); + +/** What the connection's `comline@2` handshake agreed, if `accept` / `connect` opened it. */ +export function negotiated(conn: Peer): Negotiated | undefined { + return conn.extensions.get(Negotiated); +} + +/** + * The protocols that connected although their wire shape differs from the + * peer's at the same version (`same_version_differs = warn`), by path. + */ +export function warnings(conn: Peer): string[] { + return (negotiated(conn)?.warnings ?? []).map((n) => PROTOCOLS.get(n) ?? `#${n}`); +} + +/** What the accepting side provides: one field per protocol, so leaving one out doesn't type-check. */ +export interface Services { + chat: ns_api.Chat; +} + +/** Provide every protocol in `services` on `conn`: the peer's calls to them come here. */ +export function provideServices(conn: Connection, services: Services): void { + new ns_api.ChatDispatcher(services.chat).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 agreed = handshake(); + const conn = await Connection.accept(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + 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): Promise { + const agreed = handshake(); + const conn = await Connection.connect(transport, Format, CONNECTION_IR_HASH, new Datagram3Framing(), agreed); + conn.extensions.set(agreed.negotiated!); + return conn; +} diff --git a/runtime/test/generated/dependency/own/localdeps/greeting.ts b/runtime/test/generated/dependency/own/localdeps/greeting.ts new file mode 100644 index 0000000..5c0c403 --- /dev/null +++ b/runtime/test/generated/dependency/own/localdeps/greeting.ts @@ -0,0 +1,107 @@ +// Generated by Comline +// For TypeScript 5.0 or later; verified up to 5.9. + +import { + RuntimeError, + resolveKind, + PackedCodec, + type Codec, + type Connection, + type Dispatch, + type Kind, + type Layout, + type Peer, + type Reply, +} from "@comline/runtime"; + +/** 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 = 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; +} + +export const GreetingLayout: Layout = { struct: [["text", "string"]] }; + +export interface FooGreetParams { + n: number; +} + +export const FooGreetParamsLayout: Layout = { struct: [["n", "u32"]] }; + +export interface Foo { + greet(peer: Peer, params: FooGreetParams): Promise; +} + +export const FOO_CALLS = ["greet"] as const; + +export class FooDispatcher implements Dispatch { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly impl: Foo; + + constructor(impl: Foo) { + this.impl = impl; + } + + calls(): readonly string[] { + return FOO_CALLS; + } + + /** Only served on a connection, whose handlers are given the peer: anywhere else the caller hears a fault. */ + async dispatch(_call: Kind, _params: Uint8Array, _codec: Codec, reply: Reply): Promise { + reply.fault(); + } + + async dispatchWith(call: Kind, params: Uint8Array, reply: Reply, peer: Peer): Promise { + const codec = peer.codec; + switch ("id" in call ? call.id : -1) { + case 0: { + try { + const p = codec.decode(params, FooGreetParamsLayout); + reply.ok(codec.encode((await this.impl.greet(peer, p)) ?? null, "u32")); + } catch { + reply.fault(); + } + return; + } + default: + throw RuntimeError.unknownCall(); + } + } + + /** 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. */ + provideOn(conn: Connection): void { + conn.provide(FooDispatcher.PROTOCOL, this); + } +} + +/** Calls protocol `Foo` on the other end of a connection: the peer a `Connection` reaches, or the one a handler was given. */ +export class FooSender { + /** This protocol's number on a connection. */ + static readonly PROTOCOL = 0; + + private readonly peer: Peer; + + constructor(peer: Peer) { + this.peer = peer; + } + + async greet(params: FooGreetParams): Promise { + const env = await this.peer.call(FooSender.PROTOCOL, { id: 0, name: "greet" }, params, { layout: FooGreetParamsLayout }); + if ("ok" in env) return this.peer.codec.decode(env.ok, "u32"); + if ("fault" in env) throw RuntimeError.provider(); + throw RuntimeError.remote(env.err.id); + } +} + diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 7b0d825..18f57d1 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -8,7 +8,7 @@ publish = false # Same revs `codegen` pins, so this tool and the generator it drives agree on # one `comline-core` - see codegen/Cargo.toml's own comment. comline-core = { git = "https://github.com/ComlineProject/core", rev = "868e8310e33df317e3cba4f76b81fbcd8639c1c2" } -comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "05771e0679ff514da3ba73a3b0b94643e5262fe5" } +comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "da81b688c949a0ebad4f213d6fdb648920cf641d" } comline-codegen-typescript = { path = "../codegen" } eyre = "0.6.8" diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 942c7cf..63e8ce8 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -77,6 +77,7 @@ fn main() -> eyre::Result<()> { async_api: false, encodings: comline_codegen::encodings::official_for("typescript"), facts: None, + dependencies: vec![], }; let files = generate_typescript(&req)?;