@workerstack/clients 1.0.0-rc.28 → 1.0.0-rc.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +30 -7
  2. package/dist/emit/cli/commands.js +25 -5
  3. package/dist/emit/cli/flags.js +7 -3
  4. package/dist/emit/cli/skills.js +5 -1
  5. package/dist/emit/csharp/realtime.d.ts +1 -8
  6. package/dist/emit/csharp/realtime.js +25 -25
  7. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  8. package/dist/emit/csharp/sdk-method.js +9 -2
  9. package/dist/emit/csharp/sse.d.ts +0 -11
  10. package/dist/emit/csharp/sse.js +91 -10
  11. package/dist/emit/csharp/transport.js +3 -3
  12. package/dist/emit/csharp/types-messages.d.ts +47 -0
  13. package/dist/emit/csharp/types-messages.js +172 -0
  14. package/dist/emit/csharp/types-names.js +3 -2
  15. package/dist/emit/csharp/ws.d.ts +0 -15
  16. package/dist/emit/csharp/ws.js +26 -5
  17. package/dist/emit/go/sdk-answer.d.ts +24 -1
  18. package/dist/emit/go/sdk-method.d.ts +3 -0
  19. package/dist/emit/go/sdk-method.js +16 -10
  20. package/dist/emit/go/sse.d.ts +2 -10
  21. package/dist/emit/go/sse.js +87 -12
  22. package/dist/emit/go/types-union.d.ts +3 -2
  23. package/dist/emit/go/types-union.js +2 -0
  24. package/dist/emit/go/types.d.ts +6 -0
  25. package/dist/emit/go/types.js +12 -1
  26. package/dist/emit/go/ws.d.ts +4 -11
  27. package/dist/emit/go/ws.js +214 -58
  28. package/dist/emit/java/json.d.ts +3 -0
  29. package/dist/emit/java/layout-ast.d.ts +4 -1
  30. package/dist/emit/java/layout-types.js +1 -1
  31. package/dist/emit/java/models-names.d.ts +2 -0
  32. package/dist/emit/java/models-names.js +1 -0
  33. package/dist/emit/java/models-union.d.ts +12 -1
  34. package/dist/emit/java/models-union.js +11 -5
  35. package/dist/emit/java/models.d.ts +5 -0
  36. package/dist/emit/java/models.js +22 -7
  37. package/dist/emit/java/realtime.d.ts +29 -9
  38. package/dist/emit/java/realtime.js +45 -10
  39. package/dist/emit/java/sdk-mirror.js +6 -5
  40. package/dist/emit/java/sdk-op.js +1 -1
  41. package/dist/emit/java/sse.d.ts +11 -10
  42. package/dist/emit/java/sse.js +104 -5
  43. package/dist/emit/java/ws.d.ts +46 -7
  44. package/dist/emit/java/ws.js +89 -4
  45. package/dist/emit/mcp/output-schema.d.ts +4 -2
  46. package/dist/emit/mcp/output-schema.js +56 -12
  47. package/dist/emit/python/realtime.d.ts +9 -6
  48. package/dist/emit/python/realtime.js +21 -19
  49. package/dist/emit/python/sdk-answer.d.ts +5 -1
  50. package/dist/emit/python/sdk-method.d.ts +1 -1
  51. package/dist/emit/python/sdk-method.js +33 -6
  52. package/dist/emit/python/sdk.js +22 -2
  53. package/dist/emit/python/sse.d.ts +0 -5
  54. package/dist/emit/python/sse.js +35 -5
  55. package/dist/emit/python/types.d.ts +7 -0
  56. package/dist/emit/python/types.js +20 -3
  57. package/dist/emit/python/ws.d.ts +20 -6
  58. package/dist/emit/python/ws.js +67 -1
  59. package/dist/emit/rust/realtime.d.ts +7 -5
  60. package/dist/emit/rust/realtime.js +14 -17
  61. package/dist/emit/rust/sdk-method.js +1 -1
  62. package/dist/emit/rust/sse.d.ts +11 -7
  63. package/dist/emit/rust/sse.js +52 -6
  64. package/dist/emit/rust/types-union.d.ts +9 -1
  65. package/dist/emit/rust/types-union.js +4 -0
  66. package/dist/emit/rust/types.d.ts +9 -0
  67. package/dist/emit/rust/types.js +13 -7
  68. package/dist/emit/rust/ws.d.ts +22 -4
  69. package/dist/emit/rust/ws.js +57 -7
  70. package/dist/emit/ts/sdk-types-preamble.js +4 -0
  71. package/dist/emit/ts/sdk-types.js +49 -10
  72. package/dist/emit/ts/sdk.js +2 -2
  73. package/dist/emit/ts/service-map.d.ts +8 -2
  74. package/dist/emit/ts/service-map.js +30 -2
  75. package/dist/emit/ts/type-gen.js +6 -4
  76. package/dist/ir/build.js +4 -0
  77. package/dist/ir/model.d.ts +14 -0
  78. package/dist/ir/sdk-model.d.ts +25 -1
  79. package/dist/ir/sdk-model.js +35 -5
  80. package/dist/ir/slots.d.ts +1 -1
  81. package/dist/ir/slots.js +9 -3
  82. package/dist/ir/streams.d.ts +16 -0
  83. package/dist/ir/streams.js +40 -0
  84. package/dist/runtime/cli/socket.go +107 -13
  85. package/dist/runtime/cli/stream.go +18 -11
  86. package/dist/runtime/csharp/Adapters.cs +12 -11
  87. package/dist/runtime/csharp/Events.cs +22 -17
  88. package/dist/runtime/csharp/Realtime.cs +50 -23
  89. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  90. package/dist/runtime/csharp/TransportSse.cs +3 -3
  91. package/dist/runtime/csharp/Ws.cs +1 -1
  92. package/dist/runtime/csharp/WsDial.cs +19 -1
  93. package/dist/runtime/csharp/WsTyped.cs +109 -0
  94. package/dist/runtime/go/realtime.go +125 -41
  95. package/dist/runtime/go/realtime_loop.go +21 -18
  96. package/dist/runtime/go/result.go +2 -1
  97. package/dist/runtime/go/sse.go +11 -0
  98. package/dist/runtime/go/stream.go +29 -13
  99. package/dist/runtime/go/transport.go +15 -21
  100. package/dist/runtime/go/transport_longpoll.go +3 -4
  101. package/dist/runtime/go/transport_sse.go +6 -6
  102. package/dist/runtime/go/ws.go +157 -61
  103. package/dist/runtime/java/EventStream.java +47 -29
  104. package/dist/runtime/java/Exchange.java +5 -5
  105. package/dist/runtime/java/Flight.java +3 -3
  106. package/dist/runtime/java/Realtime.java +45 -11
  107. package/dist/runtime/java/ResumableConnection.java +77 -32
  108. package/dist/runtime/java/Socket.java +8 -4
  109. package/dist/runtime/java/SseAdapter.java +1 -1
  110. package/dist/runtime/java/TypedWebSocket.java +81 -24
  111. package/dist/runtime/java/WsAdapter.java +4 -2
  112. package/dist/runtime/java/WsDial.java +12 -5
  113. package/dist/runtime/python/events.py +25 -11
  114. package/dist/runtime/python/operation.py +6 -1
  115. package/dist/runtime/python/realtime.py +47 -33
  116. package/dist/runtime/python/send_async.py +1 -0
  117. package/dist/runtime/python/transport_sse.py +2 -2
  118. package/dist/runtime/python/transport_ws.py +1 -1
  119. package/dist/runtime/python/ws.py +100 -39
  120. package/dist/runtime/rust/events.rs +64 -41
  121. package/dist/runtime/rust/realtime.rs +80 -34
  122. package/dist/runtime/rust/realtime_loop.rs +37 -12
  123. package/dist/runtime/rust/sse.rs +3 -2
  124. package/dist/runtime/rust/transport_sse.rs +1 -1
  125. package/dist/runtime/rust/transport_ws.rs +3 -2
  126. package/dist/runtime/rust/ws.rs +122 -50
  127. package/dist/runtime/ts/realtime-connection.ts +22 -0
  128. package/dist/runtime/ts/realtime-transports.ts +13 -4
  129. package/dist/runtime/ts/realtime.ts +27 -3
  130. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  131. package/dist/runtime/ts/sdk-sse.ts +31 -14
  132. package/dist/runtime/ts/sdk-ws.ts +2 -1
  133. package/dist/runtime/ts/sdk.ts +9 -2
  134. package/dist/runtime/ts/sse.ts +8 -0
  135. package/dist/runtime/ts/ws.ts +88 -50
  136. package/package.json +3 -34
@@ -80,7 +80,7 @@ function streamMethodLines(op, site, env) {
80
80
  if (op.stream === "sse")
81
81
  return sseMethodLines(op, { call: lines, constant, headers, name, params }, env.ctx);
82
82
  if (op.stream === "ws")
83
- return wsMethodLines(op, { call: lines, constant, name, params });
83
+ return wsMethodLines(op, { call: lines, constant, name, params }, env.ctx);
84
84
  return realtimeMethodLines(op, { call: lines, constant, name, params }, env.ctx);
85
85
  }
86
86
  /**
@@ -1,12 +1,6 @@
1
- /**
2
- * An SSE operation's method (bit 16 phase d1, J1/J3/J7; C#'s `sse.ts`): `EventStream<T>`, `T` the declared event
3
- * schema's type, or `EventStream<String>` for untyped events, opened by the call through the exchange's `events`, so an
4
- * error status throws before any event. Its cursor field, `lastEventId`, is sent as Last-Event-ID only when set and
5
- * non-empty; a declared Last-Event-ID header param folds into it. A stream method is the same text in either mode: it
6
- * answers no Result. Its javadoc says how a stream lets its connection go (F1: a for-each `break` has no close hook).
7
- */
8
- import type { SdkOp } from "../../ir/sdk-model.ts";
1
+ import { type SdkOp } from "../../ir/sdk-model.ts";
9
2
  import { type JavaTypeContext } from "./models.ts";
3
+ import { type Expr } from "./layout.ts";
10
4
  import type { JavaHeaders } from "./sdk-headers.ts";
11
5
  /** The header an SSE open resumes an event stream with. */
12
6
  export declare const LAST_EVENT_ID = "Last-Event-ID";
@@ -18,8 +12,15 @@ export declare const isLastEventIdHeader: (name: string) => boolean;
18
12
  export declare const RELEASE = "Open it in try-with-resources: a for-each break without one keeps the connection.";
19
13
  /** The SSE runtime's files: the stream, its event, the parser and the body's pump; core, with every exchange. */
20
14
  export declare const SSE_FILES: string[];
21
- /** The type an SSE op's events decode to: the declared event schema's, else `String`. */
22
- export declare const eventTypeOf: (op: SdkOp, ctx: JavaTypeContext) => string;
15
+ /**
16
+ * What an SSE op's stream yields and the decode the method hands the runtime: a named-event op's `<Op>Event` through
17
+ * its `of`; else `SseEvent<T>` through `EventStream.typed`, `T` the declared event schema's type, or `SseEvent<String>`
18
+ * as parsed for untyped or string events.
19
+ */
20
+ export declare function sseEventOf(op: SdkOp, ctx: JavaTypeContext): {
21
+ readonly type: string;
22
+ readonly decode: Expr;
23
+ };
23
24
  /** What an SSE method's lines need: its name and constant, its Params, its headers holder, and its Call's lines. */
24
25
  export type SseSite = {
25
26
  readonly name: string;
@@ -1,5 +1,8 @@
1
+ import { isJsonEventData, sseEvents } from "../../ir/sdk-model.js";
2
+ import { javaString } from "../shared/escape.js";
3
+ import { javaTypeName, NameScope } from "../shared/lang.js";
1
4
  import { javaTypeOf } from "./models.js";
2
- import { bin, call as callOf, cond, methodHeader, param, newOf, ref, returnStmt, statement, } from "./layout.js";
5
+ import { bin, call as callOf, cond, id, lambda, lit, local, methodHeader, param, newOf, ref, returnStmt, rule, statement, typeHeader, } from "./layout.js";
3
6
  import { docOf } from "./sdk-decl.js";
4
7
  /** The header an SSE open resumes an event stream with. */
5
8
  export const LAST_EVENT_ID = "Last-Event-ID";
@@ -11,21 +14,117 @@ export const isLastEventIdHeader = (name) => name.toLowerCase() === LAST_EVENT_I
11
14
  export const RELEASE = "Open it in try-with-resources: a for-each break without one keeps the connection.";
12
15
  /** The SSE runtime's files: the stream, its event, the parser and the body's pump; core, with every exchange. */
13
16
  export const SSE_FILES = ["EventStream", "Pump", "Sse", "SseEvent"];
14
- /** The type an SSE op's events decode to: the declared event schema's, else `String`. */
15
- export const eventTypeOf = (op, ctx) => op.events === undefined ? "String" : javaTypeOf(op.events, { ...ctx, fieldName: "Event", parentName: op.id });
17
+ /* the names a nested record never takes besides the models scope's: the types its declaration spells */
18
+ const SPELLED = ["Duration", "EventStream", "Object", "SseEvent", "String", "TypeReference"];
19
+ /** A nested record's header: its data, then the event's name, id and retry. */
20
+ const recordLines = (record, data, name) => typeHeader(2, {
21
+ components: [
22
+ { name: "data", type: data },
23
+ { name: "event", type: "String" },
24
+ { name: "id", type: "String" },
25
+ { name: "retry", type: "Duration" },
26
+ ],
27
+ end: "{}",
28
+ implements: name,
29
+ kind: "record",
30
+ modifiers: ["public"],
31
+ name: record,
32
+ });
33
+ /** The record `record` built from `e` under `name`, its data `data`. */
34
+ const built = (record, data) => newOf(record, [data, "name", callOf("e", "id"), callOf("e", "retry")]);
35
+ /** The `of` arm of `nested`: its data from JSON by its type, or as sent. */
36
+ const armOf = ({ data, event, json, record }) => {
37
+ const text = callOf("e", "data");
38
+ const value = json ? callOf("EventStream", "data", [text, newOf(`TypeReference<${data}>`, [], true)]) : text;
39
+ return statement(6, rule(lit(javaString(event)), built(record, value)));
40
+ };
41
+ /**
42
+ * The nested records of `name`, one per event name (a name declared twice is its first declaration's): each data's
43
+ * type, and a record name that never shadows a type the declaration spells, one the models scope holds, `Unknown` or
44
+ * `name` itself.
45
+ */
46
+ function nestedOf(op, events, name, ctx) {
47
+ const typed = events
48
+ .filter((e, i) => events.findIndex((other) => other.name === e.name) === i)
49
+ .map(({ data, name: event }) => {
50
+ const json = isJsonEventData(data, ctx.names.resolve);
51
+ const type = json ? javaTypeOf(data, { ...ctx, fieldName: event, parentName: op.id, path: "" }) : "String";
52
+ return { data: type, event, json };
53
+ });
54
+ /* a type a record's data spells would be shadowed by a nested record of its name */
55
+ const spelled = typed.flatMap(({ data }) => data.split(/\W+/).filter((word) => word !== ""));
56
+ const reserved = new Set([...SPELLED, ...spelled, name, "Unknown"]);
57
+ const scope = new NameScope(reserved);
58
+ return typed.map((t) => {
59
+ const base = javaTypeName(t.event);
60
+ return { ...t, record: scope.claim(reserved.has(base) || ctx.names.has(base) ? `${base}Event` : base) };
61
+ });
62
+ }
63
+ /** `name`'s `of`: the event's name, then the record its switch builds. */
64
+ const ofLines = (name, nested) => [
65
+ docOf("The event {@code e} decoded by its name, an unnamed one {@code message}; a JSON event that does not decode throws {@link DecodeException}."),
66
+ ...methodHeader(2, { modifiers: ["static"], name: "of", params: [param("SseEvent<String>", "e")], returns: name }),
67
+ ...statement(4, local({ init: callOf("EventStream", "nameOf", ["e"]), name: "name", type: "String" })),
68
+ " return switch (name) {",
69
+ ...nested.flatMap(armOf),
70
+ ...statement(6, rule(null, built("Unknown", callOf("e", "data")))),
71
+ " };",
72
+ " }",
73
+ ];
74
+ /** `<Op>Event`, hoisted into `ctx.decls` once with its nested records and its `of`; its name. */
75
+ function namedEvents(op, events, ctx) {
76
+ const name = ctx.names.hoist(`${op.id}.events`, `${javaTypeName(op.id)}Event`);
77
+ if (ctx.decls.has(name))
78
+ return name;
79
+ /* claimed before its body: what the data types hoist comes after it */
80
+ ctx.decls.set(name, "");
81
+ const nested = nestedOf(op, events, name, ctx);
82
+ const records = nested.map(({ record }) => record).join(", ");
83
+ /* the nested records are its permits */
84
+ const header = typeHeader(0, { end: "{", kind: "interface", modifiers: ["public", "sealed"], name, permits: [] });
85
+ ctx.decls.set(name, [
86
+ docOf(`One event of ${op.id}: ${records}, or Unknown for a name the operation does not declare, its data as sent. An instanceof match reads the event's data.`, ""),
87
+ ...header,
88
+ ...nested.flatMap(({ data, record }) => [...recordLines(record, data, name), ""]),
89
+ ...recordLines("Unknown", "String", name),
90
+ "",
91
+ ...ofLines(name, nested),
92
+ "}",
93
+ ].join("\n"));
94
+ return name;
95
+ }
96
+ /**
97
+ * What an SSE op's stream yields and the decode the method hands the runtime: a named-event op's `<Op>Event` through
98
+ * its `of`; else `SseEvent<T>` through `EventStream.typed`, `T` the declared event schema's type, or `SseEvent<String>`
99
+ * as parsed for untyped or string events.
100
+ */
101
+ export function sseEventOf(op, ctx) {
102
+ const events = sseEvents(op.ir);
103
+ if (events !== undefined) {
104
+ const name = namedEvents(op, events, ctx);
105
+ return { decode: ref(name, "of"), type: name };
106
+ }
107
+ const type = op.events === undefined ? "String" : javaTypeOf(op.events, { ...ctx, fieldName: "Event", parentName: op.id });
108
+ if (type === "String")
109
+ return { decode: lambda("e", id("e")), type: "SseEvent<String>" };
110
+ return {
111
+ decode: callOf("EventStream", "typed", [newOf(`TypeReference<${type}>`, [], true)]),
112
+ type: `SseEvent<${type}>`,
113
+ };
114
+ }
16
115
  /**
17
116
  * An SSE method's lines: `op(params)` and `op(params, options)`, and `op(params, headersInto, options)` for an operation
18
117
  * with response headers, filled at the open; the shorter overloads delegate to the longest.
19
118
  */
20
119
  export function sseMethodLines(op, site, ctx) {
21
120
  const { call, constant, headers, name, params } = site;
22
- const type = eventTypeOf(op, ctx);
121
+ const { decode, type } = sseEventOf(op, ctx);
23
122
  const doc = docOf(`${op.id}: the open stream. An error status throws before any event, and no timeout bounds it after that. ${RELEASE}`);
24
123
  const signature = (args) => methodHeader(2, { modifiers: ["public"], name, params: args, returns: `EventStream<${type}>` });
25
124
  const holder = headers === null ? "null" : cond(bin("==", "headersInto", "null"), "null", ref("headersInto", "read"));
26
125
  const open = [
27
126
  ...call,
28
- ...statement(4, returnStmt(callOf("exchange", "events", [constant, "call", "options", holder, newOf(`TypeReference<${type}>`, [], true)]))),
127
+ ...statement(4, returnStmt(callOf("exchange", "events", [constant, "call", "options", holder, decode]))),
29
128
  ];
30
129
  const delegate = (args) => statement(4, returnStmt(callOf(null, name, args)));
31
130
  const longest = headers === null ? open : delegate(["params", "null", "options"]);
@@ -1,12 +1,22 @@
1
1
  /**
2
- * A WebSocket operation's method (bit 16 phase d2a, K1/K2/K3; C#'s `ws.ts`): `TypedWebSocket`, dialed by the call
3
- * through `WsDial.open` (no hook and no log), so a refused handshake throws before the method returns. The entry
4
- * sits in the gated WebSocket files, as C#'s `SocketAsync` in WsDial.cs: an SDK without a socket references none. Its
5
- * fields, `protocols` (offered in order) and `reconnectToken` (sent as `reconnect_token` after the declared query, only
6
- * when set and non-empty); a declared `reconnect_token` query folds into the token, and a param spelled like either
7
- * field claims `…2`. A socket method is the same text in either mode: it answers no Result.
2
+ * A WebSocket operation's method (bit 16 phase d2a, K1/K2/K3; C#'s `ws.ts`): `TypedWebSocket<TIn, TOut>`, dialed by
3
+ * the call through `WsDial.open` (no hook and no log), so a refused handshake throws before the method returns. An
4
+ * operation that declares its messages (D9) reads `TIn`, what the server sends, each frame as JSON, and sends `TOut`,
5
+ * what it receives, each a direction's declared type (an inline one hoisted as `<Op>Send` or `<Op>Receive`); a side it
6
+ * does not declare reads `WsMessage`, each frame as it came, or sends `JsonNode`. A keyed read side (the sealed
7
+ * interface models-union.ts declares) answers `<Read>Socket<TOut>`, one per read type, whose `on<Value>` per member
8
+ * matches inside `onMessage` and returns the socket, none for a value whose handler the socket has (message, closed,
9
+ * error); its name is claimed through the models scope after the union's wrappers, and a second value of one handler
10
+ * name is numbered. The entry sits in the gated WebSocket files, as C#'s `SocketAsync` in WsDial.cs: an SDK without a
11
+ * socket references none. Its fields, `protocols` (offered in order) and `reconnectToken` (sent as `reconnect_token`
12
+ * after the declared query, only when set and non-empty); a declared `reconnect_token` query folds into the token,
13
+ * and a param spelled like either field claims `…2`. A socket method is the same text in either mode: it answers no
14
+ * Result.
8
15
  */
9
16
  import type { SdkOp } from "../../ir/sdk-model.ts";
17
+ import type { Dispatch } from "./json.ts";
18
+ import { type Expr } from "./layout.ts";
19
+ import { type JavaTypeContext } from "./models.ts";
10
20
  /** The query param the token travels in. */
11
21
  export declare const RECONNECT_TOKEN = "reconnect_token";
12
22
  /** The socket's Params fields: the subprotocols offered, then the resume token. */
@@ -16,6 +26,35 @@ export declare const TOKEN = "reconnectToken";
16
26
  export declare const isReconnectTokenQuery: (name: string) => name is "reconnect_token";
17
27
  /** The WebSocket runtime's files: the socket and its parts; only an SDK with a WebSocket operation ships them. */
18
28
  export declare const WS_FILES: string[];
29
+ /**
30
+ * What a generated reader extends: its base class, the handlers the base has (a member whose `on<Value>` one of them
31
+ * names gets none), what its docs call it, and the suffix its name takes after the read type's.
32
+ */
33
+ export type Reader = {
34
+ readonly base: string;
35
+ readonly handlers: readonly string[];
36
+ readonly noun: string;
37
+ readonly suffix: string;
38
+ };
39
+ /** What a socket method answers, the frame reader it hands the dial, and the wrap of the dialed socket. */
40
+ export type WsSocket = {
41
+ readonly type: string;
42
+ readonly read: Expr;
43
+ readonly wrap: (dialed: Expr) => Expr;
44
+ };
45
+ /** The arms of `arms` that get an `on<Value>`: each but one whose handler `reader` has already. */
46
+ export declare const handledArms: (reader: Reader, arms: readonly Dispatch[]) => Dispatch[];
47
+ /**
48
+ * `<read><Suffix>`, hoisted into `ctx.decls` once per read type and reader with an `on<Value>` per arm of `arms` but
49
+ * one whose handler `reader` has; its name. The wrappers were claimed first, so a member spelled like the subclass
50
+ * keeps its wrapper and this one is numbered, and a second value of one handler name is numbered.
51
+ */
52
+ export declare function keyedReader(reader: Reader, read: string, arms: readonly Dispatch[], ctx: JavaTypeContext): string;
53
+ /**
54
+ * What `op`'s socket method answers and hands the dial: an op without messages `TypedWebSocket<WsMessage, JsonNode>`,
55
+ * its frames as they came; else each declared side's type, a keyed read side's socket wrapping the dialed one.
56
+ */
57
+ export declare function wsSocketOf(op: SdkOp, ctx: JavaTypeContext): WsSocket;
19
58
  /** What a socket method's lines need: its name and constant, its Params, and its Call's lines. */
20
59
  export type WsSite = {
21
60
  readonly name: string;
@@ -24,4 +63,4 @@ export type WsSite = {
24
63
  readonly call: readonly string[];
25
64
  };
26
65
  /** A socket method's lines: `op(params)`, delegating to `op(params, options)`, which dials. */
27
- export declare function wsMethodLines(op: SdkOp, site: WsSite): string[];
66
+ export declare function wsMethodLines(op: SdkOp, site: WsSite, ctx: JavaTypeContext): string[];
@@ -1,4 +1,7 @@
1
- import { call as callOf, methodHeader, param, returnStmt, statement } from "./layout.js";
1
+ import { NameScope } from "../shared/lang.js";
2
+ import { bin, call as callOf, exprStmt, id, ifOpen, lambda, lit, methodHeader, newOf, param, returnStmt, statement, typeHeader, } from "./layout.js";
3
+ import { declaredTypeOf, keyedArms } from "./models.js";
4
+ import { JSON_NODE } from "./models-names.js";
2
5
  import { docOf } from "./sdk-decl.js";
3
6
  /** The query param the token travels in. */
4
7
  export const RECONNECT_TOKEN = "reconnect_token";
@@ -9,12 +12,94 @@ export const TOKEN = "reconnectToken";
9
12
  export const isReconnectTokenQuery = (name) => name === RECONNECT_TOKEN;
10
13
  /** The WebSocket runtime's files: the socket and its parts; only an SDK with a WebSocket operation ships them. */
11
14
  export const WS_FILES = ["Keepalive", "Socket", "TypedWebSocket", "WsClose", "WsDial", "WsMessage"];
15
+ /** The socket's reader: its own handlers are onMessage, onClosed and onError. */
16
+ const SOCKET = {
17
+ base: "TypedWebSocket",
18
+ handlers: ["onMessage", "onClosed", "onError"],
19
+ noun: "socket",
20
+ suffix: "Socket",
21
+ };
22
+ /** The frame reader of an undeclared read side: each frame as it came. */
23
+ const asSent = () => lambda("m", id("m"));
24
+ /** One `on<Value>` of `sub`, named `name`: it matches `arm`'s wrapper inside onMessage and hands on its variant. */
25
+ const handlerLines = (reader, sub, name, { payload, wrapper }) => [
26
+ "",
27
+ docOf(`Runs {@code handler} with the variant of each ${wrapper} message, inside onMessage; this ${reader.noun}.`),
28
+ ...methodHeader(2, {
29
+ modifiers: ["public"],
30
+ name,
31
+ params: [param(`Consumer<${payload}>`, "handler")],
32
+ returns: `${sub}<TOut>`,
33
+ }),
34
+ " onMessage(",
35
+ " message -> {",
36
+ ...statement(10, ifOpen(bin("instanceof", "message", lit(`${wrapper} matched`)))),
37
+ ...statement(12, exprStmt(callOf("handler", "accept", [callOf("matched", "value")]))),
38
+ " }",
39
+ " });",
40
+ ...statement(4, returnStmt("this")),
41
+ " }",
42
+ ];
43
+ /** The arms of `arms` that get an `on<Value>`: each but one whose handler `reader` has already. */
44
+ export const handledArms = (reader, arms) => arms.filter((arm) => !reader.handlers.includes(handlerName(arm)));
45
+ /* the handler an arm's first value spells */
46
+ const handlerName = (arm) => `on${arm.spelled}`;
47
+ /**
48
+ * `<read><Suffix>`, hoisted into `ctx.decls` once per read type and reader with an `on<Value>` per arm of `arms` but
49
+ * one whose handler `reader` has; its name. The wrappers were claimed first, so a member spelled like the subclass
50
+ * keeps its wrapper and this one is numbered, and a second value of one handler name is numbered.
51
+ */
52
+ export function keyedReader(reader, read, arms, ctx) {
53
+ const sub = ctx.names.hoist(`${read}.${reader.noun}`, `${read}${reader.suffix}`);
54
+ if (ctx.decls.has(sub))
55
+ return sub;
56
+ const scope = new NameScope(reader.handlers);
57
+ const handlers = handledArms(reader, arms).flatMap((arm) => handlerLines(reader, sub, scope.claim(handlerName(arm)), arm));
58
+ ctx.decls.set(sub, [
59
+ docOf(`A ${reader.noun} reading ${read}: a handler per member, each matched inside onMessage.`, ""),
60
+ ...typeHeader(0, {
61
+ end: "{",
62
+ extends: `${reader.base}<${read}, TOut>`,
63
+ kind: "class",
64
+ modifiers: ["public", "final"],
65
+ name: `${sub}<TOut>`,
66
+ }),
67
+ ...methodHeader(2, { name: sub, params: [param(`${reader.base}<${read}, TOut>`, "opened")] }),
68
+ ...statement(4, exprStmt(callOf(null, "super", ["opened"]))),
69
+ " }",
70
+ ...handlers,
71
+ "}",
72
+ ].join("\n"));
73
+ return sub;
74
+ }
75
+ /** The dialed socket as it is: a socket whose read side has no members to handle. */
76
+ const AS_DIALED = (dialed) => dialed;
77
+ /**
78
+ * What `op`'s socket method answers and hands the dial: an op without messages `TypedWebSocket<WsMessage, JsonNode>`,
79
+ * its frames as they came; else each declared side's type, a keyed read side's socket wrapping the dialed one.
80
+ */
81
+ export function wsSocketOf(op, ctx) {
82
+ const messages = op.ir.messages;
83
+ const at = (fieldName) => ({ ...ctx, fieldName, parentName: op.id, path: "" });
84
+ const write = messages?.receive === undefined ? JSON_NODE : declaredTypeOf(messages.receive, at("Receive"));
85
+ if (messages?.send === undefined) {
86
+ return { read: asSent(), type: `TypedWebSocket<WsMessage, ${write}>`, wrap: AS_DIALED };
87
+ }
88
+ const read = declaredTypeOf(messages.send, at("Send"));
89
+ const decode = callOf("TypedWebSocket", "json", [newOf(`TypeReference<${read}>`, [], true)]);
90
+ const arms = keyedArms(read, messages.send, ctx);
91
+ if (arms.length === 0)
92
+ return { read: decode, type: `TypedWebSocket<${read}, ${write}>`, wrap: AS_DIALED };
93
+ const sub = keyedReader(SOCKET, read, arms, ctx);
94
+ return { read: decode, type: `${sub}<${write}>`, wrap: (dialed) => newOf(`${sub}<${write}>`, [dialed]) };
95
+ }
12
96
  /** A socket method's lines: `op(params)`, delegating to `op(params, options)`, which dials. */
13
- export function wsMethodLines(op, site) {
97
+ export function wsMethodLines(op, site, ctx) {
14
98
  const { call, constant, name, params } = site;
99
+ const socket = wsSocketOf(op, ctx);
15
100
  const doc = docOf(`${op.id}: the open socket. A refused handshake throws; once open, no timeout bounds it. Close it, or open it in try-with-resources.`);
16
- const signature = (args) => methodHeader(2, { modifiers: ["public"], name, params: args, returns: "TypedWebSocket" });
17
- const dial = callOf("WsDial", "open", ["exchange", constant, "call", "options", callOf("params", "protocols")]);
101
+ const signature = (args) => methodHeader(2, { modifiers: ["public"], name, params: args, returns: socket.type });
102
+ const dial = socket.wrap(callOf("WsDial", "open", ["exchange", constant, "call", "options", callOf("params", "protocols"), socket.read]));
18
103
  return [
19
104
  doc,
20
105
  ...signature([param(params, "params")]),
@@ -4,10 +4,12 @@
4
4
  * an object (2025-11-25), and so is an answer whose operation declares response headers (Q11), as `{result, headers}`:
5
5
  * a body key named `headers` then never meets them. Each header is a string, as it arrives. No JSON success schema
6
6
  * means no outputSchema: the result is text only. An event stream's collect (phase e) is `{events, last_event_id,
7
- * ended}`, each event's data its declared schema, else a string.
7
+ * ended}`, each event's data its declared schema, else a string. A stream that names its events (D7) types each event
8
+ * by its name, as the TS SDK yields it: the names sharing one data schema are one `anyOf` member, `event` their const
9
+ * (one name) or enum (several), and a last member takes a name the operation does not declare, its data the raw text.
8
10
  */
9
11
  import type { IR } from "../../ir/model.ts";
10
- import type { SdkOp } from "../../ir/sdk-model.ts";
12
+ import { type SdkOp } from "../../ir/sdk-model.ts";
11
13
  import { type JsonSchema } from "./schema.ts";
12
14
  /** A tool's outputSchema, and whether its structuredContent wraps the answer. */
13
15
  export type Output = {
@@ -1,16 +1,56 @@
1
+ import { sseEvents } from "../../ir/sdk-model.js";
2
+ import { irResolver } from "../../ir/schema.js";
1
3
  import { jsonSchemaOf } from "./schema.js";
2
- /** What a collect gathered, its events' data as `data` says. */
3
- const collectedOf = (data) => ({
4
+ const STRING = { type: "string" };
5
+ /** An event of a stream that does not name its events: its data as `data` says, its name and id when it has them. */
6
+ const unnamedOf = (data) => ({
4
7
  type: "object",
5
- properties: {
6
- events: {
7
- type: "array",
8
- items: {
9
- type: "object",
10
- properties: { data, event: { type: "string" }, id: { type: "string" } },
11
- required: ["data"],
12
- },
8
+ properties: { data, event: STRING, id: STRING },
9
+ required: ["data"],
10
+ });
11
+ /**
12
+ * An event of a stream that names `events` (D7). An event whose data is JSON is one `anyOf` member per distinct data
13
+ * schema, `event` its const (one name) or enum (several). Any other event's data arrives as its text, so one string
14
+ * member holds the rest, declared or not; `event` names every declared name as an example.
15
+ */
16
+ function namedOf(events, ir) {
17
+ const resolve = irResolver(ir.schemas);
18
+ const groups = new Map();
19
+ const names = [];
20
+ for (const { data, name } of events) {
21
+ if (!names.includes(name))
22
+ names.push(name);
23
+ const schema = resolve(data).kind === "unknown" ? STRING : jsonSchemaOf(data, ir.schemas);
24
+ const key = JSON.stringify(schema);
25
+ if (key === JSON.stringify(STRING))
26
+ continue;
27
+ const group = groups.get(key) ?? { data: schema, names: [] };
28
+ if (!group.names.includes(name))
29
+ group.names.push(name);
30
+ groups.set(key, group);
31
+ }
32
+ const event = { type: "string", examples: names };
33
+ const required = ["data", "event"];
34
+ if (groups.size === 0)
35
+ return { type: "object", properties: { data: STRING, event, id: STRING }, required };
36
+ const members = [...groups.values()].map((group) => ({
37
+ properties: {
38
+ event: group.names.length === 1 ? { const: group.names[0] } : { enum: group.names },
39
+ data: group.data,
13
40
  },
41
+ }));
42
+ return {
43
+ type: "object",
44
+ properties: { event, id: STRING },
45
+ required,
46
+ anyOf: [...members, { properties: { data: STRING } }],
47
+ };
48
+ }
49
+ /** What a collect gathered, each event as `item` says. */
50
+ const collectedOf = (item) => ({
51
+ type: "object",
52
+ properties: {
53
+ events: { type: "array", items: item },
14
54
  last_event_id: { anyOf: [{ type: "string" }, { type: "null" }] },
15
55
  ended: { type: "string", enum: ["end", "max_events", "cap", "timeout"] },
16
56
  },
@@ -18,10 +58,14 @@ const collectedOf = (data) => ({
18
58
  });
19
59
  /** The outputSchema `op`'s success answer gives, or none. */
20
60
  export function outputOf(op, ir) {
21
- if (op.stream === "sse")
61
+ if (op.stream === "sse") {
62
+ const named = sseEvents(op.ir);
63
+ if (named !== undefined)
64
+ return { outputSchema: collectedOf(namedOf(named, ir)) };
22
65
  return {
23
- outputSchema: collectedOf(op.events === undefined ? { type: "string" } : jsonSchemaOf(op.events, ir.schemas)),
66
+ outputSchema: collectedOf(unnamedOf(op.events === undefined ? STRING : jsonSchemaOf(op.events, ir.schemas))),
24
67
  };
68
+ }
25
69
  /* the SDK model gives a success its schema only when it is JSON */
26
70
  if (op.success.schema === undefined)
27
71
  return undefined;
@@ -1,10 +1,13 @@
1
1
  /**
2
- * A realtime operation's answer (contract 34 §2.0, §2.3; Fd3): `ResumableConnection[E]`, `E` the declared event
3
- * schema's type (`Any` for a string or absent one), opened by awaiting the method over WebSocket, else SSE, else
4
- * long-poll. Its five fields are the `TransportOpts` of their names: the resume cursor, the offered subprotocols
5
- * and the reconnect policy; a declared param on a resume channel is folded in, and one named like a policy field
6
- * is claimed as `…2` (`sdk-method.ts`).
2
+ * A realtime operation's answer (contract 34 §2.0, §2.3; Fd3): `ResumableConnection[Out, In]`, opened by awaiting the
3
+ * method over WebSocket, else SSE, else long-poll. `Out` is what the server sends (its declared `send`, else the
4
+ * declared event schema's type, `Any` for a string or absent one) and `In` what it receives (its `receive`, else
5
+ * `object`). A `send` union keyed on one field (D9) makes the answer `<Op>Connection`, a subclass hoisted beside the
6
+ * types whose `on` overloads give each member's value its member's type; a `message` member gets none. Its one field
7
+ * is `transport: TransportOpts | None`: the resume cursor, the offered subprotocols and the reconnect policy, which
8
+ * the connection advances in its own copy, so `rc.opts` resumes past the last message. A declared param on a resume
9
+ * channel is carried by it, and one named `transport` is claimed as `transport2` (`sdk-method.ts`).
7
10
  */
8
11
  import { type PyStream } from "./sdk-answer.ts";
9
- /** The realtime operation's answer, its five fields and its docstring's lines. */
12
+ /** The realtime operation's answer, its one field and its docstring's lines. */
10
13
  export declare const realtimeStream: PyStream;
@@ -1,20 +1,28 @@
1
1
  /**
2
- * A realtime operation's answer (contract 34 §2.0, §2.3; Fd3): `ResumableConnection[E]`, `E` the declared event
3
- * schema's type (`Any` for a string or absent one), opened by awaiting the method over WebSocket, else SSE, else
4
- * long-poll. Its five fields are the `TransportOpts` of their names: the resume cursor, the offered subprotocols
5
- * and the reconnect policy; a declared param on a resume channel is folded in, and one named like a policy field
6
- * is claimed as `…2` (`sdk-method.ts`).
2
+ * A realtime operation's answer (contract 34 §2.0, §2.3; Fd3): `ResumableConnection[Out, In]`, opened by awaiting the
3
+ * method over WebSocket, else SSE, else long-poll. `Out` is what the server sends (its declared `send`, else the
4
+ * declared event schema's type, `Any` for a string or absent one) and `In` what it receives (its `receive`, else
5
+ * `object`). A `send` union keyed on one field (D9) makes the answer `<Op>Connection`, a subclass hoisted beside the
6
+ * types whose `on` overloads give each member's value its member's type; a `message` member gets none. Its one field
7
+ * is `transport: TransportOpts | None`: the resume cursor, the offered subprotocols and the reconnect policy, which
8
+ * the connection advances in its own copy, so `rc.opts` resumes past the last message. A declared param on a resume
9
+ * channel is carried by it, and one named `transport` is claimed as `transport2` (`sdk-method.ts`).
7
10
  */
8
11
  import { eventType } from "./sdk-answer.js";
9
- import { isLastEventIdHeader, sseStream } from "./sse.js";
12
+ import { isLastEventIdHeader } from "./sse.js";
10
13
  import { pyTypeOf } from "./types.js";
11
- import { isReconnectToken, PROTOCOLS, RECONNECT_TOKEN } from "./ws.js";
12
- /** The realtime operation's answer, its five fields and its docstring's lines. */
14
+ import { isReconnectToken, socketAnswer } from "./ws.js";
15
+ /** The realtime operation's answer, its one field and its docstring's lines. */
13
16
  export const realtimeStream = {
14
- answer: (op, env) => {
15
- const events = eventType(op, env, () => pyTypeOf({ kind: "unknown" }, env.at));
16
- return { returns: `ResumableConnection[${events}]`, run: "realtime", type: events };
17
- },
17
+ answer: (op, env) => socketAnswer(op, env, {
18
+ base: "ResumableConnection",
19
+ in: "object",
20
+ /* the one event a connection's `on` takes for itself */
21
+ lifecycle: (out) => [["message", out]],
22
+ out: () => eventType(op, env, () => pyTypeOf({ kind: "unknown" }, env.at)),
23
+ run: "realtime",
24
+ suffix: "Connection",
25
+ }),
18
26
  /* the WebSocket and long-poll dials send the cursor as query params, the SSE dial its id as Last-Event-ID */
19
27
  carries: (name, where) => isReconnectToken(name, where) ||
20
28
  (where === "query" && name === "last_event_id") ||
@@ -23,11 +31,5 @@ export const realtimeStream = {
23
31
  "Opens the connection over WebSocket, else SSE, else long-poll; recv() reconnects after a drop and",
24
32
  "resumes after the last message it delivered.",
25
33
  ],
26
- fields: [
27
- ...sseStream.fields,
28
- RECONNECT_TOKEN,
29
- PROTOCOLS,
30
- "max_reconnect_attempts: int | None = None",
31
- "reconnect_delay_ms: int | None = None",
32
- ],
34
+ fields: ["transport: TransportOpts | None = None"],
33
35
  };
@@ -12,11 +12,15 @@ import type { MethodEnv } from "./sdk-method.ts";
12
12
  export declare const typeAt: (op: SdkOp, field: string, schema: IRParam["schema"], env: MethodEnv) => string;
13
13
  /** The body parameter's type: its schema's for JSON and a form, `<Op>Body` for multipart, `str` for text, bytes or chunks for binary. */
14
14
  export declare function bodyType(op: SdkOp, async: boolean, env: MethodEnv): string | null;
15
- /** What a method answers (its `Operation`'s type and its return type), and the transport call it makes. */
15
+ /**
16
+ * What a method answers (its `Operation`'s type and its return type), the transport call it makes, and the
17
+ * socket class the runtime builds for it, when it has its own.
18
+ */
16
19
  export type Answer = {
17
20
  readonly type: string;
18
21
  readonly returns: string;
19
22
  readonly run: string;
23
+ readonly kind?: string;
20
24
  };
21
25
  /**
22
26
  * What a streaming operation's method is: whether a declared param is one its own fields carry (Fd3), those
@@ -10,7 +10,7 @@ export type MethodEnv = {
10
10
  readonly constants: NameScope;
11
11
  /** the `collections.abc` and runtime names client.py imports */
12
12
  readonly imports: Set<string>;
13
- /** the runtime names types.py imports (a multipart body's `FilePart`) */
13
+ /** the runtime names types.py imports (a multipart body's `FilePart`, a named event's `SseEventOf`) */
14
14
  readonly typesImports: Set<string>;
15
15
  };
16
16
  /**