@workerstack/clients 1.0.0-rc.27 → 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 (145) 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/route-tree.d.ts +1 -1
  71. package/dist/emit/ts/route-tree.js +0 -11
  72. package/dist/emit/ts/sdk-types-preamble.js +4 -0
  73. package/dist/emit/ts/sdk-types.js +49 -10
  74. package/dist/emit/ts/sdk.js +2 -2
  75. package/dist/emit/ts/service-map.d.ts +8 -2
  76. package/dist/emit/ts/service-map.js +30 -2
  77. package/dist/emit/ts/type-gen.d.ts +4 -3
  78. package/dist/emit/ts/type-gen.js +83 -40
  79. package/dist/extract/chain.d.ts +10 -6
  80. package/dist/extract/chain.js +5 -19
  81. package/dist/extract/extract.d.ts +2 -2
  82. package/dist/extract/extract.js +37 -23
  83. package/dist/extract/walk.d.ts +15 -4
  84. package/dist/extract/walk.js +159 -15
  85. package/dist/ir/build.js +4 -0
  86. package/dist/ir/model.d.ts +16 -0
  87. package/dist/ir/sdk-model.d.ts +25 -1
  88. package/dist/ir/sdk-model.js +35 -5
  89. package/dist/ir/slots.d.ts +1 -1
  90. package/dist/ir/slots.js +11 -3
  91. package/dist/ir/streams.d.ts +16 -0
  92. package/dist/ir/streams.js +40 -0
  93. package/dist/runtime/cli/socket.go +107 -13
  94. package/dist/runtime/cli/stream.go +18 -11
  95. package/dist/runtime/csharp/Adapters.cs +12 -11
  96. package/dist/runtime/csharp/Events.cs +22 -17
  97. package/dist/runtime/csharp/Realtime.cs +50 -23
  98. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  99. package/dist/runtime/csharp/TransportSse.cs +3 -3
  100. package/dist/runtime/csharp/Ws.cs +1 -1
  101. package/dist/runtime/csharp/WsDial.cs +19 -1
  102. package/dist/runtime/csharp/WsTyped.cs +109 -0
  103. package/dist/runtime/go/realtime.go +125 -41
  104. package/dist/runtime/go/realtime_loop.go +21 -18
  105. package/dist/runtime/go/result.go +2 -1
  106. package/dist/runtime/go/sse.go +11 -0
  107. package/dist/runtime/go/stream.go +29 -13
  108. package/dist/runtime/go/transport.go +15 -21
  109. package/dist/runtime/go/transport_longpoll.go +3 -4
  110. package/dist/runtime/go/transport_sse.go +6 -6
  111. package/dist/runtime/go/ws.go +157 -61
  112. package/dist/runtime/java/EventStream.java +47 -29
  113. package/dist/runtime/java/Exchange.java +5 -5
  114. package/dist/runtime/java/Flight.java +3 -3
  115. package/dist/runtime/java/Realtime.java +45 -11
  116. package/dist/runtime/java/ResumableConnection.java +77 -32
  117. package/dist/runtime/java/Socket.java +8 -4
  118. package/dist/runtime/java/SseAdapter.java +1 -1
  119. package/dist/runtime/java/TypedWebSocket.java +81 -24
  120. package/dist/runtime/java/WsAdapter.java +4 -2
  121. package/dist/runtime/java/WsDial.java +12 -5
  122. package/dist/runtime/python/events.py +25 -11
  123. package/dist/runtime/python/operation.py +6 -1
  124. package/dist/runtime/python/realtime.py +47 -33
  125. package/dist/runtime/python/send_async.py +1 -0
  126. package/dist/runtime/python/transport_sse.py +2 -2
  127. package/dist/runtime/python/transport_ws.py +1 -1
  128. package/dist/runtime/python/ws.py +100 -39
  129. package/dist/runtime/rust/events.rs +64 -41
  130. package/dist/runtime/rust/realtime.rs +80 -34
  131. package/dist/runtime/rust/realtime_loop.rs +37 -12
  132. package/dist/runtime/rust/sse.rs +3 -2
  133. package/dist/runtime/rust/transport_sse.rs +1 -1
  134. package/dist/runtime/rust/transport_ws.rs +3 -2
  135. package/dist/runtime/rust/ws.rs +122 -50
  136. package/dist/runtime/ts/realtime-connection.ts +22 -0
  137. package/dist/runtime/ts/realtime-transports.ts +13 -4
  138. package/dist/runtime/ts/realtime.ts +27 -3
  139. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  140. package/dist/runtime/ts/sdk-sse.ts +31 -14
  141. package/dist/runtime/ts/sdk-ws.ts +2 -1
  142. package/dist/runtime/ts/sdk.ts +9 -2
  143. package/dist/runtime/ts/sse.ts +8 -0
  144. package/dist/runtime/ts/ws.ts +88 -50
  145. package/package.json +3 -61
package/README.md CHANGED
@@ -234,7 +234,7 @@ export function newClient(): Kitchen {
234
234
 
235
235
  export async function organization(client: Kitchen, orgId: string): Promise<string | null> {
236
236
  try {
237
- await client.getApiV1OrganizationsByOrgId({ params: { orgId } })
237
+ await client.organizations.retrieve({ params: { orgId } })
238
238
  return orgId
239
239
  } catch (error) {
240
240
  if (error instanceof NotFoundError) return null
@@ -243,7 +243,7 @@ export async function organization(client: Kitchen, orgId: string): Promise<stri
243
243
  }
244
244
 
245
245
  export async function health(client: Kitchen): Promise<string> {
246
- const result = await client.safe.getApiHealth()
246
+ const result = await client.safe.health.check()
247
247
  if (result.ok) return "up"
248
248
  if (result.error instanceof DecodeError) return `unreadable answer: ${result.error.message}`
249
249
  return `answered ${result.error.status}`
@@ -320,7 +320,7 @@ same for its module and the version it links in. A path Go would not publish (no
320
320
 
321
321
  ```go
322
322
  func listing(ctx context.Context, client *sdk.Client) string {
323
- r, err := client.Safe().GetApi(ctx, nil)
323
+ r, err := client.Safe().Root.List(ctx, nil)
324
324
  if err != nil {
325
325
  return fmt.Sprintf("no answer: %v", err) // never sent, refused, dropped, timed out or canceled
326
326
  }
@@ -348,7 +348,7 @@ clients generate --spec openapi.json --target rust --out generated --rust-crate-
348
348
 
349
349
  ```rust
350
350
  async fn listing(client: &Client) -> String {
351
- match client.safe().get_api(&GetApiOpts::default()).await {
351
+ match client.safe().root().list(&RootListOpts::default()).await {
352
352
  Ok(Answer::Ok { data, response }) => format!("answered {}: {data:?}", response.status),
353
353
  Ok(Answer::Err {
354
354
  error: SafeError::Api(failed),
@@ -379,7 +379,7 @@ clients' own manifest stays out of the sdist.
379
379
 
380
380
  ```python
381
381
  async def health(client: AsyncSDK) -> str:
382
- match await client.safe.get_api_health():
382
+ match await client.safe.health.check():
383
383
  case Ok(data, response):
384
384
  return f"answered {response.status}: {data}"
385
385
  case Err(DecodeError() as unreadable, response):
@@ -404,7 +404,7 @@ into `dotnet pack`.
404
404
  ```csharp
405
405
  public static async Task<string> Listing(HttpSdkClient client, string id)
406
406
  {
407
- var result = await client.Safe.GetApiAsync(id); // no answer (never sent, refused, timed out, canceled) still throws
407
+ var result = await client.Safe.Root.ListAsync(id); // no answer (never sent, refused, timed out, canceled) still throws
408
408
  return result.Match(
409
409
  found => $"answered {result.Response.Status}: {found}",
410
410
  error => error switch
@@ -432,7 +432,7 @@ the metadata block, whose authors are the POM's developers. Signing the publicat
432
432
  ```java
433
433
  static String listing(KitchenClient client) {
434
434
  // no answer (never sent, refused, timed out, canceled) still throws
435
- Result<ListApiResponse200> result = client.safe().getApi(GetApiParams.builder().build());
435
+ Result<ListApiResponse200> result = client.safe().root().list(RootListParams.builder().build());
436
436
  int status = result.response().status();
437
437
  return result.fold(
438
438
  found -> "answered " + status + ": " + found,
@@ -573,6 +573,29 @@ or GitLab repository. Where a hosted server runs is yours, so it lists no `remot
573
573
  }
574
574
  ```
575
575
 
576
+ An event stream is one bounded collect: `max_events` (1 to 100, 20 by default) and `last_event_id` in, and
577
+ `{ events, last_event_id, ended }` out. When the stream names its events, each event's `event` is required and the
578
+ declared names are its `examples`. Each JSON event's `data` is typed by its name in an `anyOf` member, and any other
579
+ event, declared or not, has its `data` as a string. A stream of `tick` JSON events and `heartbeat` text events lists
580
+ its events as:
581
+
582
+ ```json
583
+ {
584
+ "type": "object",
585
+ "properties": { "event": { "type": "string", "examples": ["tick", "heartbeat"] }, "id": { "type": "string" } },
586
+ "required": ["data", "event"],
587
+ "anyOf": [
588
+ {
589
+ "properties": {
590
+ "event": { "const": "tick" },
591
+ "data": { "type": "object", "properties": { "n": { "type": "number" } } }
592
+ }
593
+ },
594
+ { "properties": { "data": { "type": "string" } } }
595
+ ]
596
+ }
597
+ ```
598
+
576
599
  The server reads its configuration from the environment, under the `--mcp-env-prefix` (or the document's title,
577
600
  upper-cased):
578
601
 
@@ -81,8 +81,25 @@ function bodyLines(op, plan, flags) {
81
81
  return [[`\tbody, err := p.Reader(${required})`, ...fail], ", body"];
82
82
  }
83
83
  }
84
- /** A stream's call: its stream opened first (its output flags checked), then each event printed as it comes. */
85
- function streamLines(call, stream) {
84
+ /** The check of one message type: an input line decoded as it, holding each field it requires. */
85
+ const lineCheck = ({ required, type }) => `cli.JSONLine[${qualified(type)}](${required.map(goString).join(", ")})`;
86
+ /** The check a WebSocket command runs on each input line: by what the server receives; nil when it is untyped. */
87
+ function linesChecked(sends) {
88
+ if (sends === null)
89
+ return "nil";
90
+ if (sends.key === null)
91
+ return lineCheck(sends);
92
+ const members = [...sends.members]
93
+ .sort((a, b) => compareCodeUnits(a.value, b.value))
94
+ .map((member) => `${goString(member.value)}: ${lineCheck(member)}`);
95
+ return `cli.Keyed(${goString(sends.key)}, map[string]cli.LineCheck{${members.join(", ")}})`;
96
+ }
97
+ /**
98
+ * A stream's call: its stream opened first (its output flags checked), then each event printed as it comes. A
99
+ * WebSocket's input lines are checked against what the server receives, and a message that does not decode, the
100
+ * SDK's `*DecodeError`, ends the conversation.
101
+ */
102
+ function streamLines(call, stream, sends) {
86
103
  const open = ["\tout, err := cli.OpenStream(c)", "\tif err != nil {", "\t\treturn err", "\t}", "\tdefer out.Close()"];
87
104
  if (stream === "sse")
88
105
  return [
@@ -91,7 +108,8 @@ function streamLines(call, stream) {
91
108
  "\t\tif err != nil {",
92
109
  "\t\t\treturn failed(err)",
93
110
  "\t\t}",
94
- "\t\tif !out.Event(event.Event, event.ID, event.Data) {",
111
+ "\t\tev := event.Untyped()",
112
+ "\t\tif !out.Event(ev.Event, ev.ID, ev.Data) {",
95
113
  "\t\t\tbreak",
96
114
  "\t\t}",
97
115
  "\t}",
@@ -103,7 +121,9 @@ function streamLines(call, stream) {
103
121
  "\tif err != nil {",
104
122
  "\t\treturn failed(err)",
105
123
  "\t}",
106
- stream === "realtime" ? "\treturn failed(out.Resume(conn))" : "\treturn out.Converse(conn)",
124
+ stream === "realtime"
125
+ ? "\treturn failed(cli.Resume(out, conn, conn.Events()))"
126
+ : `\treturn cli.Converse(out, conn, conn.Read, ${linesChecked(sends)}, cli.Undecoded[*sdk.DecodeError])`,
107
127
  ];
108
128
  }
109
129
  /** The call and what follows it, by what the method returns: the answer printed with the response it came on. */
@@ -154,7 +174,7 @@ function opFunc(node, path, ir) {
154
174
  "\t}",
155
175
  ...(plan.stream === null
156
176
  ? callLines(`${method}(c.Context()${args}${bodyArg}, opts, sdk.WithResponseInto(&resp))`, plan)
157
- : streamLines(`${method}(c.Context()${args}${bodyArg}, opts)`, plan.stream)),
177
+ : streamLines(`${method}(c.Context()${args}${bodyArg}, opts)`, plan.stream, plan.sends)),
158
178
  ];
159
179
  return [
160
180
  ...lineComment(`${node.fn} is \`${[...path, node.name].join(" ")}\`: ${op.method} ${op.path}.`, "//"),
@@ -130,16 +130,20 @@ export function commandFlags(op, plan, schemas) {
130
130
  const LAST_EVENT_ID = ["last-event-id", "LastEventID", "resume after this event id"];
131
131
  const RECONNECT_TOKEN = ["reconnect-token", "ReconnectToken", "resume with this reconnect token"];
132
132
  const CURSOR = { realtime: [LAST_EVENT_ID, RECONNECT_TOKEN], sse: [LAST_EVENT_ID], ws: [RECONNECT_TOKEN] };
133
- /** A stream command's own flags: --take, a realtime one's --max-reconnects, and its cursor flags, each set into its Opts field. */
133
+ /**
134
+ * A stream command's own flags: --take, a realtime one's --max-reconnects, and its cursor flags, each set into its
135
+ * Opts field (a realtime one's into its one `Transport`).
136
+ */
134
137
  function streamFlags(stream, lines, opts) {
138
+ const into = stream === "realtime" ? "opts.Transport" : "opts";
135
139
  lines.push("\tp.Take()");
136
140
  if (stream === "realtime") {
137
141
  lines.push("\tp.MaxReconnects()");
138
- opts.push("\treconnects, err := p.Reconnects()", "\tif err != nil {", "\t\treturn err", "\t}", "\topts.MaxReconnectAttempts = reconnects");
142
+ opts.push("\treconnects, err := p.Reconnects()", "\tif err != nil {", "\t\treturn err", "\t}", `\t${into}.MaxReconnectAttempts = reconnects`);
139
143
  }
140
144
  for (const [flag, field, usage] of CURSOR[stream]) {
141
145
  lines.push(flagLine(flag, { enum: [], kind: "string", list: false }, false, usage));
142
- opts.push(`\tif err := cli.Set(&opts.${field}, p.Values(${goString(flag)})); err != nil {`, "\t\treturn err", "\t}");
146
+ opts.push(`\tif err := cli.Set(&${into}.${field}, p.Values(${goString(flag)})); err != nil {`, "\t\treturn err", "\t}");
143
147
  }
144
148
  }
145
149
  /** A multipart body's flags, each declared into `lines` by its part's name: a text part typed by its schema, a file part a path. */
@@ -18,7 +18,11 @@ export function skillFile(bin, title, prefix, ops) {
18
18
  "",
19
19
  "## Streams",
20
20
  `A stream command (${streams.join(", ")}) prints one JSON line per event; \`--take N\` ends it after N.`,
21
- ...(streams.includes("ws") ? ["A ws command sends each stdin line as a text frame."] : []),
21
+ ...(streams.includes("ws")
22
+ ? [
23
+ "A ws command sends each stdin line as a text frame; where its messages are typed, a line that is not one is refused on stderr, not sent, and the run exits 4.",
24
+ ]
25
+ : []),
22
26
  ...(streams.includes("realtime")
23
27
  ? [
24
28
  "A realtime feed writes its resume cursor to stderr when it ends; pass it back with `--reconnect-token` and `--last-event-id`.",
@@ -1,10 +1,3 @@
1
- /**
2
- * A realtime operation's answer (contract 50 §2, Fd6, Fd7): `Task<ResumableConnection<T>>` through `RealtimeAsync`,
3
- * `T` the declared event schema's type (`JsonElement` for a string or absent one), opened by awaiting the method over
4
- * WebSocket, else SSE, else long-poll. Its five fields are `TransportOptions.Of`'s: the resume cursor, the offered
5
- * subprotocols and the reconnect policy (`TimeSpan? reconnectDelay`). A declared param on a resume channel is folded
6
- * in, and one named like a field is claimed as `…2` (`sdk-method.ts`).
7
- */
8
1
  import { type CsStream } from "./sdk-answer.ts";
9
- /** The realtime operation's answer, its five fields and its `<returns>` text. */
2
+ /** The realtime operation's answer, its one field and its `<returns>` text. */
10
3
  export declare const realtimeStream: CsStream;
@@ -1,33 +1,33 @@
1
- /**
2
- * A realtime operation's answer (contract 50 §2, Fd6, Fd7): `Task<ResumableConnection<T>>` through `RealtimeAsync`,
3
- * `T` the declared event schema's type (`JsonElement` for a string or absent one), opened by awaiting the method over
4
- * WebSocket, else SSE, else long-poll. Its five fields are `TransportOptions.Of`'s: the resume cursor, the offered
5
- * subprotocols and the reconnect policy (`TimeSpan? reconnectDelay`). A declared param on a resume channel is folded
6
- * in, and one named like a field is claimed as `…2` (`sdk-method.ts`).
7
- */
8
1
  import { eventType } from "./sdk-answer.js";
9
- import { isLastEventIdHeader, LAST_EVENT_ID_FIELD } from "./sse.js";
10
- import { isReconnectToken, PROTOCOLS, RECONNECT_TOKEN } from "./ws.js";
11
- /** The realtime operation's answer, its five fields and its `<returns>` text. */
2
+ import { isLastEventIdHeader } from "./sse.js";
3
+ import { JSON_ELEMENT } from "./types.js";
4
+ import { messageType, valueHandlers } from "./types-messages.js";
5
+ import { isReconnectToken } from "./ws.js";
6
+ /* the connection, and its own event: a member whose On<Value> it names gets none */
7
+ const READER = { base: "ResumableConnection", handlers: ["OnMessage"], receiver: "connection" };
8
+ /** The realtime operation `op`'s answer, its message types hoisted into `env.at`. */
9
+ function realtimeAnswer(op, env) {
10
+ const { receive, send } = op.ir.messages ?? {};
11
+ const read = send === undefined ? undefined : messageType(op, send, "Send", env.at);
12
+ const write = receive === undefined ? JSON_ELEMENT : messageType(op, receive, "Receive", env.at).type;
13
+ if (read !== undefined)
14
+ valueHandlers(READER, read, env.at);
15
+ const type = read?.type ?? (op.events === undefined ? JSON_ELEMENT : eventType(op.events, op, env));
16
+ const run = send === undefined && receive === undefined ? "RealtimeAsync" : "TypedRealtimeAsync";
17
+ return {
18
+ infos: [type, write],
19
+ render: (spell) => [`Task<ResumableConnection<${spell.runtime(type)}, ${spell.runtime(write)}>>`, run],
20
+ type: null,
21
+ };
22
+ }
23
+ /** The realtime operation's answer, its one field and its `<returns>` text. */
12
24
  export const realtimeStream = {
13
- answer: (op, env) => {
14
- const type = op.events === undefined ? "JsonElement" : eventType(op.events, op, env);
15
- return {
16
- render: (spell) => [`Task<ResumableConnection<${spell.runtime(type)}>>`, "RealtimeAsync"],
17
- type,
18
- };
19
- },
20
- args: ["TransportOptions.Of(lastEventId, reconnectToken, protocols, maxReconnectAttempts, reconnectDelay)"],
25
+ answer: realtimeAnswer,
26
+ args: ["(transport ?? new()).Copy()"],
21
27
  /* the WebSocket and long-poll dials send the cursor as query params, the SSE dial its id as Last-Event-ID */
22
28
  carries: (name, where) => isReconnectToken(name, where) ||
23
29
  (where === "query" && name === "last_event_id") ||
24
30
  isLastEventIdHeader(name, where),
25
- fields: [
26
- LAST_EVENT_ID_FIELD,
27
- RECONNECT_TOKEN,
28
- PROTOCOLS,
29
- { ident: "maxReconnectAttempts", type: "int?" },
30
- { ident: "reconnectDelay", type: "TimeSpan?" },
31
- ],
31
+ fields: [{ ident: "transport", type: "TransportOptions?" }],
32
32
  returns: "The connection over WebSocket, else SSE, else long-poll: it reconnects after a drop and resumes after the last message it delivered; the token, CloseAsync or DisposeAsync ends it.",
33
33
  };
@@ -6,14 +6,22 @@
6
6
  * in the JSON context) with one nullable `{ get; private set; }` property per header in code-unit order of its
7
7
  * name, typed by the header's scalar (`long?`, `double?`, `bool?`, else `string?`), and an `internal` `Read` the
8
8
  * transport calls on a 2xx; a WebSocket or realtime operation, whose 2xx no caller receives, gets none. A
9
- * stream operation answers as its `CsStream` says (`sse.ts`, `ws.ts`, `realtime.ts`).
9
+ * stream operation answers as its `CsStream` says (`sse.ts`, `ws.ts`, `realtime.ts`), its call passing the arguments
10
+ * and type infos its answer adds (a named-event stream's decode, a socket's or a connection's two types) before
11
+ * the type info.
10
12
  */
11
13
  import type { IRSchema } from "../../ir/model.ts";
12
14
  import type { SdkOp } from "../../ir/sdk-model.ts";
13
15
  import type { MethodEnv, Spelling } from "./sdk-method.ts";
14
- /** A method's answer: its JSON type (null for any other kind), and its return type and transport method. */
16
+ /**
17
+ * A method's answer: its JSON type (null for any other kind), the arguments its call passes before that type's info
18
+ * (a named-event stream's decode), the types whose infos it passes after them (a typed socket's or a realtime
19
+ * connection's read and send types), and its return type and transport method.
20
+ */
15
21
  export type CsAnswer = {
16
22
  readonly type: string | null;
23
+ readonly args?: readonly string[];
24
+ readonly infos?: readonly string[];
17
25
  readonly render: (spell: Spelling) => readonly [returns: string, run: string];
18
26
  };
19
27
  /**
@@ -86,12 +86,14 @@ function call({ body, headers, keyed, params, path }, spell) {
86
86
  ...(headers === null ? [] : ["headersInto is null ? null : headersInto.Read"]),
87
87
  ].join(", ");
88
88
  }
89
- /** The method's lines: its docs (its error statuses' exceptions), its signature, the one call into the transport (a stream's arguments after the `Call`). */
89
+ /** The method's lines: its docs (its error statuses' exceptions), its signature, the one call into the transport (a stream's arguments, then its answer's, after the `Call`). */
90
90
  function methodLines(parts, spell) {
91
91
  const { answer, stream } = parts;
92
92
  const [returns, run] = answer.render(spell);
93
93
  const args = [
94
94
  ...(stream?.args ?? []),
95
+ ...(answer.args ?? []),
96
+ ...(answer.infos ?? []).map(spell.info),
95
97
  ...(answer.type === null ? [] : [spell.info(answer.type)]),
96
98
  "cancellationToken",
97
99
  ];
@@ -182,6 +184,11 @@ export function csMethod(op, name, field, env) {
182
184
  lines: (spell) => methodLines(parts, spell),
183
185
  plan: planOf(parts),
184
186
  twin: (spell) => twinLines(parts, spell),
185
- types: [...params.map(({ type }) => type), ...body.types, ...(answer.type === null ? [] : [answer.type])],
187
+ types: [
188
+ ...params.map(({ type }) => type),
189
+ ...body.types,
190
+ ...(answer.infos ?? []),
191
+ ...(answer.type === null ? [] : [answer.type]),
192
+ ],
186
193
  };
187
194
  }
@@ -1,17 +1,6 @@
1
- /**
2
- * An SSE operation's answer (contract 50 §2, Fd1, Fd4): `Task<EventStream<T>>` through `EventsAsync`, `T` the
3
- * declared event schema's type, or `Task<EventStream<string>>` through `TextEventsAsync` for untyped events, opened
4
- * by awaiting the method (G15). Its one field, `lastEventId`, is sent as Last-Event-ID only when set and non-empty;
5
- * a declared Last-Event-ID header param is folded into that field.
6
- */
7
1
  import { type CsStream } from "./sdk-answer.ts";
8
2
  /** The header the SSE and realtime dials resume an event stream with. */
9
3
  export declare const LAST_EVENT_ID = "Last-Event-ID";
10
- /** The resume cursor's event id, which the SSE and realtime methods take. */
11
- export declare const LAST_EVENT_ID_FIELD: {
12
- ident: string;
13
- type: string;
14
- };
15
4
  /** Whether a declared param is the Last-Event-ID header (any casing), the resume channel an SSE dial sends. */
16
5
  export declare const isLastEventIdHeader: (name: string, where: string) => boolean;
17
6
  /** The SSE operation's answer, its one field and its `<returns>` text. */
@@ -1,24 +1,105 @@
1
- /**
2
- * An SSE operation's answer (contract 50 §2, Fd1, Fd4): `Task<EventStream<T>>` through `EventsAsync`, `T` the
3
- * declared event schema's type, or `Task<EventStream<string>>` through `TextEventsAsync` for untyped events, opened
4
- * by awaiting the method (G15). Its one field, `lastEventId`, is sent as Last-Event-ID only when set and non-empty;
5
- * a declared Last-Event-ID header param is folded into that field.
6
- */
1
+ import { isJsonEventData, sseEvents } from "../../ir/sdk-model.js";
2
+ import { csString } from "../shared/escape.js";
3
+ import { csTypeName, NameScope } from "../shared/lang.js";
7
4
  import { eventType } from "./sdk-answer.js";
5
+ import { docLines } from "./sdk-doc.js";
6
+ import { csTypeOf } from "./types.js";
8
7
  /** The header the SSE and realtime dials resume an event stream with. */
9
8
  export const LAST_EVENT_ID = "Last-Event-ID";
10
- /** The resume cursor's event id, which the SSE and realtime methods take. */
11
- export const LAST_EVENT_ID_FIELD = { ident: "lastEventId", type: "string?" };
9
+ /** The resume cursor's event id, which the SSE method takes. */
10
+ const LAST_EVENT_ID_FIELD = { ident: "lastEventId", type: "string?" };
12
11
  /** Whether a declared param is the Last-Event-ID header (any casing), the resume channel an SSE dial sends. */
13
12
  export const isLastEventIdHeader = (name, where) => where === "header" && name.toLowerCase() === LAST_EVENT_ID.toLowerCase();
13
+ /* the names a nested record never takes: the members, and the types the decode spells */
14
+ const TAKEN = [
15
+ /* a nested record's members */
16
+ "Data",
17
+ "Event",
18
+ "Id",
19
+ "Retry",
20
+ "Of",
21
+ /* every record's */
22
+ "Deconstruct",
23
+ "EqualityContract",
24
+ "Equals",
25
+ "Finalize",
26
+ "GetHashCode",
27
+ "GetType",
28
+ "MemberwiseClone",
29
+ "PrintMembers",
30
+ "ToString",
31
+ /* the decode's */
32
+ "JsonSerializerOptions",
33
+ "JsonTypeInfo",
34
+ "SseEvent",
35
+ "TimeSpan",
36
+ "Transport",
37
+ ];
38
+ /** The decode arm of `nested`: its data from JSON through the context, or as sent. */
39
+ const armOf = ({ data, event, json, record }) => {
40
+ const value = json
41
+ ? `Transport.EventData(e.Data, (JsonTypeInfo<${data}>)options.GetTypeInfo(typeof(${data})))`
42
+ : "e.Data";
43
+ return ` ${csString(event)} => new ${record}(${value}, ${csString(event)}, e.Id, e.Retry),`;
44
+ };
45
+ /** A nested record's declaration: its data, then the event's name, id and retry. */
46
+ const recordOf = (record, data, name) => ` public sealed record ${record}(${data} Data, string Event, string? Id, TimeSpan? Retry) : ${name};`;
47
+ /** `<Op>Event`, hoisted into `env.at.decls` (never listed) with its nested records and its decode; its name. */
48
+ function namedEvents(op, events, env) {
49
+ const { at } = env;
50
+ const name = at.names.claim(`${csTypeName(op.id)}Event`);
51
+ at.unlisted.add(name);
52
+ const typed = events.map(({ data, name: event }) => {
53
+ const json = isJsonEventData(data, at.names.resolve);
54
+ /* the decode throws on null, so the data is never null */
55
+ const type = json ? csTypeOf(data, { ...at, fieldName: event, parentName: op.id }).replace(/\?$/, "") : "string";
56
+ if (json)
57
+ at.serialized.add(type);
58
+ return { data: type, event, json };
59
+ });
60
+ /* a type a record's data spells would be shadowed by a nested record of its name */
61
+ const spelled = typed.flatMap(({ data }) => data.split(/\W+/).filter((word) => word !== ""));
62
+ const reserved = new Set([...TAKEN, ...spelled, name, "Unknown"]);
63
+ const scope = new NameScope(reserved);
64
+ const nested = typed.map((t) => {
65
+ const base = csTypeName(t.event);
66
+ return { ...t, record: scope.claim(reserved.has(base) ? `${base}Event` : base) };
67
+ });
68
+ const list = nested.map(({ record }) => record).join(", ");
69
+ at.decls.set(name, [
70
+ ...docLines("summary", `One event of ${op.id}: ${list}, or Unknown for a name the operation does not declare, its data as sent. An is match reads the event's data.`),
71
+ `public abstract record ${name}`,
72
+ "{",
73
+ ` private ${name}()`,
74
+ " {",
75
+ " }",
76
+ "",
77
+ ...nested.map(({ data, record }) => recordOf(record, data, name)),
78
+ recordOf("Unknown", "string", name),
79
+ "",
80
+ ` internal static ${name} Of(SseEvent<string> e, JsonSerializerOptions options) =>`,
81
+ ' (e.Event is null or "" ? "message" : e.Event) switch',
82
+ " {",
83
+ ...nested.map(armOf),
84
+ " var named => new Unknown(e.Data, named, e.Id, e.Retry),",
85
+ " };",
86
+ "}",
87
+ ].join("\n"));
88
+ return name;
89
+ }
14
90
  /** The SSE operation's answer, its one field and its `<returns>` text. */
15
91
  export const sseStream = {
16
92
  answer: (op, env) => {
93
+ const named = sseEvents(op.ir);
94
+ if (named !== undefined) {
95
+ const name = namedEvents(op, named, env);
96
+ return { args: [`${name}.Of`], render: () => [`Task<EventStream<${name}>>`, "NamedEventsAsync"], type: null };
97
+ }
17
98
  const type = op.events === undefined ? null : eventType(op.events, op, env);
18
99
  return {
19
100
  render: (spell) => type === null
20
- ? ["Task<EventStream<string>>", "TextEventsAsync"]
21
- : [`Task<EventStream<${spell.runtime(type)}>>`, "EventsAsync"],
101
+ ? ["Task<EventStream<SseEvent<string>>>", "TextEventsAsync"]
102
+ : [`Task<EventStream<SseEvent<${spell.runtime(type)}>>>`, "EventsAsync"],
22
103
  type,
23
104
  };
24
105
  },
@@ -3,7 +3,7 @@
3
3
  * and nowhere else (the F8 mutation target), each emitted as committed but for its one `namespace Http.Runtime;`
4
4
  * line, which becomes the SDK's own namespace (Fb2), so `using <RootNamespace>;` reaches the client, the config,
5
5
  * the exceptions and the models alike. Every API ships the core, SSE among it; a WebSocket or realtime API adds the
6
- * socket and its dial, and a realtime API the adapters and the connection (contract 50 §2).
6
+ * socket, its dial and its typed face, and a realtime API the adapters and the connection (contract 50 §2).
7
7
  */
8
8
  import { readFileSync } from "node:fs";
9
9
  import { compareCodeUnits } from "../shared/lang.js";
@@ -33,8 +33,8 @@ const CORE = [
33
33
  "Transport",
34
34
  "Wire",
35
35
  ];
36
- /* a WebSocket or realtime operation: the socket and its own HTTP/1.1 upgrade */
37
- const WS = ["Ws", "WsDial"];
36
+ /* a WebSocket or realtime operation: the socket, its own HTTP/1.1 upgrade, and the socket of declared messages */
37
+ const WS = ["Ws", "WsDial", "WsTyped"];
38
38
  /* a realtime operation: the adapters, the resumable connection and its loop, and the three transports */
39
39
  const REALTIME = [
40
40
  "Adapters",
@@ -0,0 +1,47 @@
1
+ /**
2
+ * C# message types (D9, D17): one direction of a socket's declared messages as the type its socket reads or sends.
3
+ * A union keyed on one field (`dispatchOf`) is `<Op>Inbound` (what the server sends, the read side) or
4
+ * `<Op>Outbound` (what it receives, the send side), declared beside the body union, which does not change: an
5
+ * abstract record with a private constructor and one nested sealed record per member in the order declared, each
6
+ * wrapping its variant record as `Value`; the read side adds `Unknown(JsonElement Raw)` for a value the op does not
7
+ * declare, the send side an implicit conversion from each variant record. Its converter reads the discriminator and
8
+ * decodes the variant through the context (AOT-safe). A nested name that is one of the record's members, a type it
9
+ * spells or the enclosing type takes the suffix `Message`. Any other direction is its declared type itself, an
10
+ * inline schema hoisted as `<Op><Side>`. Each keyed read side gets an `On<Value>` extension per member, in a static
11
+ * class beside it, for the socket or the connection that reads it, except a member whose value names one of that
12
+ * reader's own events.
13
+ */
14
+ import type { IRSchema } from "../../ir/model.ts";
15
+ import { type SdkOp } from "../../ir/sdk-model.ts";
16
+ import { type CsTypeContext } from "./types.ts";
17
+ /** Which way a direction goes: the server's `send` is the client's read, its `receive` the client's send. */
18
+ export type Side = "Receive" | "Send";
19
+ /** One keyed member as a nested record: the value that selects it, its record, and its variant's type. */
20
+ type Nested = {
21
+ readonly value: string;
22
+ readonly record: string;
23
+ readonly type: string;
24
+ };
25
+ /** One direction's C# type, and a keyed one's key and nested records in the order declared. */
26
+ export type MessageType = {
27
+ readonly type: string;
28
+ readonly keyed?: {
29
+ readonly key: string;
30
+ readonly nested: readonly Nested[];
31
+ };
32
+ };
33
+ /** One direction of `op`'s messages as its C# type: a keyed union's hierarchy, else the declared type itself. */
34
+ export declare function messageType(op: SdkOp, schema: IRSchema, side: Side, at: CsTypeContext): MessageType;
35
+ /** What reads a keyed side: its generic type, the name its extensions give their `this` param, and its own events. */
36
+ export type Reader = {
37
+ readonly base: string;
38
+ readonly receiver: string;
39
+ readonly handlers: readonly string[];
40
+ };
41
+ /**
42
+ * The `On<Value>` extensions of `<base><read, TOut>` (a socket or a connection, `reader`), `read` a keyed read side,
43
+ * declared beside it in `at`: each takes the variant of the member its value selects, matched inside the reader's
44
+ * `Message`; a value whose method one of the reader's `handlers` names gets none.
45
+ */
46
+ export declare function valueHandlers({ base, handlers, receiver }: Reader, read: MessageType, at: CsTypeContext): void;
47
+ export {};