@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
@@ -0,0 +1,172 @@
1
+ import { dispatchOf } from "../../ir/sdk-model.js";
2
+ import { csString } from "../shared/escape.js";
3
+ import { csTypeName, NameScope } from "../shared/lang.js";
4
+ import { docLines } from "./sdk-doc.js";
5
+ import { csTypeOf } from "./types.js";
6
+ /* the names a nested record never takes: its members, every record's, and the types its converter spells */
7
+ const TAKEN = [
8
+ "Value",
9
+ "Raw",
10
+ "Unknown",
11
+ "Clone",
12
+ "Deconstruct",
13
+ "EqualityContract",
14
+ "Equals",
15
+ "Finalize",
16
+ "GetHashCode",
17
+ "GetType",
18
+ "MemberwiseClone",
19
+ "PrintMembers",
20
+ "ToString",
21
+ "JsonElement",
22
+ ];
23
+ /** `JsonTypeInfo<T>` of `type` from the converter's options. */
24
+ const info = (type) => `(JsonTypeInfo<${type}>)options.GetTypeInfo(typeof(${type}))`;
25
+ /** Each member of `dispatch` once per value, its variant typed at `<parent><Value>`, its nested name claimed. */
26
+ function nestedOf(name, dispatch, parent, at) {
27
+ const seen = new Set();
28
+ const members = dispatch.members.flatMap(({ value, variant }) => {
29
+ if (seen.has(value))
30
+ return [];
31
+ seen.add(value);
32
+ const type = csTypeOf(variant, { ...at, fieldName: value, parentName: parent }).replace(/\?$/, "");
33
+ at.serialized.add(type);
34
+ return [{ type, value }];
35
+ });
36
+ /* a type a member spells would be shadowed by a nested record of its name */
37
+ const spelled = members.flatMap(({ type }) => type.split(/\W+/).filter((word) => word !== ""));
38
+ const reserved = new Set([...TAKEN, ...spelled, name]);
39
+ const scope = new NameScope(reserved);
40
+ return members.map((member) => {
41
+ const base = csTypeName(member.value);
42
+ return { ...member, record: scope.claim(reserved.has(base) ? `${base}Message` : base) };
43
+ });
44
+ }
45
+ /** The converter's `Read`: the key's string value selects a member; any other value is `Unknown`, or refused. */
46
+ function readLines(name, key, nested, read) {
47
+ const other = read ? `new ${name}.Unknown(raw)` : `throw new JsonException($"no ${name} member is keyed {kind}")`;
48
+ return [
49
+ ` public override ${name} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)`,
50
+ " {",
51
+ " var raw = JsonElement.ParseValue(ref reader);",
52
+ ` var kind = raw.ValueKind == JsonValueKind.Object && raw.TryGetProperty(${csString(key)}, out var at) && at.ValueKind == JsonValueKind.String ? at.GetString() : null;`,
53
+ " return kind switch",
54
+ " {",
55
+ ...nested.map(({ record, type, value }) => ` ${csString(value)} => new ${name}.${record}(raw.Deserialize(${info(type)}) ?? throw new JsonException("a ${record} message is null")),`),
56
+ ` _ => ${other},`,
57
+ " };",
58
+ " }",
59
+ ];
60
+ }
61
+ /** The converter's `Write`: the member's variant through its own type, `Unknown` as received. */
62
+ function writeLines(name, nested, read) {
63
+ const arms = [
64
+ ...nested.map(({ record, type }, i) => [
65
+ `value is ${name}.${record} member${i}`,
66
+ `JsonSerializer.Serialize(writer, member${i}.Value, ${info(type)});`,
67
+ ]),
68
+ ...(read ? [[`value is ${name}.Unknown unknown`, "unknown.Raw.WriteTo(writer);"]] : []),
69
+ ];
70
+ return [
71
+ ` public override void Write(Utf8JsonWriter writer, ${name} value, JsonSerializerOptions options)`,
72
+ " {",
73
+ ...arms.flatMap(([test, write], i) => [
74
+ ` ${i > 0 ? "else " : ""}if (${test})`,
75
+ " {",
76
+ ` ${write}`,
77
+ " }",
78
+ ]),
79
+ " else",
80
+ " {",
81
+ " writer.WriteNullValue();",
82
+ " }",
83
+ " }",
84
+ ];
85
+ }
86
+ /** `<Op>Inbound` or `<Op>Outbound` for the keyed `dispatch`, hoisted with its converter into `at.decls`. */
87
+ function keyedType(op, dispatch, side, at) {
88
+ const read = side === "Send";
89
+ const name = at.names.claim(`${csTypeName(op.id)}${read ? "Inbound" : "Outbound"}`);
90
+ /* claimed before its body: what the members hoist comes after it */
91
+ at.decls.set(name, "");
92
+ const nested = nestedOf(name, dispatch, `${op.id}.${side}`, at);
93
+ const converter = at.names.claim(`${name}Converter`);
94
+ const list = nested.map(({ record }) => record).join(", ");
95
+ const summary = read
96
+ ? `One message ${op.id} reads: ${list}, or Unknown for a value the operation does not declare, as received. An is match reads its Value.`
97
+ : `One message ${op.id} sends: ${list}. Each member's record converts to it implicitly.`;
98
+ const converts = [...new Map(nested.map((n) => [n.type, n])).values()].map(({ record, type }) => ` public static implicit operator ${name}(${type} value) => new ${record}(value);`);
99
+ at.decls.set(name, [
100
+ ...docLines("summary", summary),
101
+ `[JsonConverter(typeof(${converter}))]`,
102
+ `public abstract record ${name}`,
103
+ "{",
104
+ ` private ${name}()`,
105
+ " {",
106
+ " }",
107
+ "",
108
+ ...nested.map(({ record, type }) => ` public sealed record ${record}(${type} Value) : ${name};`),
109
+ ...(read ? [` public sealed record Unknown(JsonElement Raw) : ${name};`] : ["", ...converts]),
110
+ "}",
111
+ "",
112
+ `public sealed class ${converter} : JsonConverter<${name}>`,
113
+ "{",
114
+ ...readLines(name, dispatch.key, nested, read),
115
+ "",
116
+ ...writeLines(name, nested, read),
117
+ "}",
118
+ ].join("\n"));
119
+ return { keyed: { key: dispatch.key, nested }, type: name };
120
+ }
121
+ /** One direction of `op`'s messages as its C# type: a keyed union's hierarchy, else the declared type itself. */
122
+ export function messageType(op, schema, side, at) {
123
+ const dispatch = dispatchOf(schema, at.names.resolve);
124
+ const message = dispatch === undefined
125
+ ? { type: csTypeOf(schema, { ...at, fieldName: side, parentName: op.id }).replace(/\?$/, "") }
126
+ : keyedType(op, dispatch, side, at);
127
+ at.serialized.add(message.type);
128
+ return message;
129
+ }
130
+ /**
131
+ * The `On<Value>` extensions of `<base><read, TOut>` (a socket or a connection, `reader`), `read` a keyed read side,
132
+ * declared beside it in `at`: each takes the variant of the member its value selects, matched inside the reader's
133
+ * `Message`; a value whose method one of the reader's `handlers` names gets none.
134
+ */
135
+ export function valueHandlers({ base, handlers, receiver }, read, at) {
136
+ const declared = at.decls.get(read.type);
137
+ if (read.keyed === undefined || declared === undefined)
138
+ return;
139
+ const { key, nested } = read.keyed;
140
+ const scope = new NameScope(handlers);
141
+ const methods = nested.flatMap(({ record, type, value }) => {
142
+ const method = `On${csTypeName(value)}`;
143
+ if (scope.has(method))
144
+ return [];
145
+ return [
146
+ "",
147
+ ...docLines("summary", `Calls handler with each message whose ${csString(key)} is ${csString(value)}, inside Message.`, " "),
148
+ ` public static void ${scope.claim(method)}<TOut>(this ${base}<${read.type}, TOut> ${receiver}, Action<${type}> handler)`,
149
+ " {",
150
+ ` ${receiver}.Message += message =>`,
151
+ " {",
152
+ ` if (message is ${read.type}.${record} matched)`,
153
+ " {",
154
+ " handler(matched.Value);",
155
+ " }",
156
+ " };",
157
+ " }",
158
+ ];
159
+ });
160
+ if (methods.length === 0)
161
+ return;
162
+ const holder = at.names.claim(`${read.type}Extensions`);
163
+ at.decls.set(read.type, [
164
+ declared,
165
+ "",
166
+ ...docLines("summary", `A handler per member of ${read.type}, each matching inside the Message of a ${base} that reads it.`),
167
+ `public static class ${holder}`,
168
+ "{",
169
+ ...methods.slice(1),
170
+ "}",
171
+ ].join("\n"));
172
+ }
@@ -3,7 +3,7 @@ import { compareCodeUnits, csTypeName, NameScope } from "../shared/lang.js";
3
3
  import { runtimeFiles, runtimeTypeNames } from "./transport.js";
4
4
  /* the BCL names emitted text spells unqualified, by the namespace a `using` brings them from (§4.7) */
5
5
  export const BCL = {
6
- System: ["Exception", "Func", "IDisposable", "Object", "String", "TimeSpan", "Type"],
6
+ System: ["Action", "Exception", "Func", "IDisposable", "Object", "String", "TimeSpan", "Type"],
7
7
  "System.Collections.Generic": ["IDictionary", "IReadOnlyDictionary", "IReadOnlyList"],
8
8
  "System.Text.Json": [
9
9
  "JsonElement",
@@ -35,8 +35,8 @@ export const BCL = {
35
35
  * the emitted types share the runtime's namespace (Fb2), so each is reserved, never a `using`
36
36
  */
37
37
  export const RUNTIME_BCL = [
38
- "Action",
39
38
  "Array",
39
+ "BrotliStream",
40
40
  "ByteArrayContent",
41
41
  "CancellationTokenRegistration",
42
42
  "CancellationTokenSource",
@@ -48,6 +48,7 @@ export const RUNTIME_BCL = [
48
48
  "Encoding",
49
49
  "Enum",
50
50
  "EqualityComparer",
51
+ "GZipStream",
51
52
  "Guid",
52
53
  "HashCode",
53
54
  "HashSet",
@@ -1,19 +1,4 @@
1
- /**
2
- * A WebSocket operation's answer (contract 50 §2, Fd5): `Task<TypedWebSocket>` through `SocketAsync`, opened by
3
- * awaiting the method and dialed offering `protocols`, its `reconnectToken` sent as one query param only when set and
4
- * non-empty; a declared `reconnect_token` query param is folded into that field.
5
- */
6
1
  import type { CsStream } from "./sdk-answer.ts";
7
- /** The subprotocols a WebSocket or realtime dial offers. */
8
- export declare const PROTOCOLS: {
9
- ident: string;
10
- type: string;
11
- };
12
- /** The resume cursor's token, which the WebSocket and realtime methods take. */
13
- export declare const RECONNECT_TOKEN: {
14
- ident: string;
15
- type: string;
16
- };
17
2
  /** Whether a declared param is the `reconnect_token` query param, the resume channel a socket dial sends. */
18
3
  export declare const isReconnectToken: (name: string, where: string) => boolean;
19
4
  /** The WebSocket operation's answer, its two fields and its `<returns>` text. */
@@ -1,12 +1,33 @@
1
- /** The subprotocols a WebSocket or realtime dial offers. */
2
- export const PROTOCOLS = { ident: "protocols", type: "IReadOnlyList<string>?" };
3
- /** The resume cursor's token, which the WebSocket and realtime methods take. */
4
- export const RECONNECT_TOKEN = { ident: "reconnectToken", type: "string?" };
1
+ import { JSON_ELEMENT } from "./types.js";
2
+ import { messageType, valueHandlers } from "./types-messages.js";
3
+ /** The subprotocols a WebSocket dial offers. */
4
+ const PROTOCOLS = { ident: "protocols", type: "IReadOnlyList<string>?" };
5
+ /** The resume cursor's token, which the WebSocket method takes. */
6
+ const RECONNECT_TOKEN = { ident: "reconnectToken", type: "string?" };
7
+ /* the typed socket, and its own events: a member whose On<Value> one of them names gets none */
8
+ const READER = { base: "TypedWebSocket", handlers: ["OnMessage", "OnClose", "OnError"], receiver: "socket" };
5
9
  /** Whether a declared param is the `reconnect_token` query param, the resume channel a socket dial sends. */
6
10
  export const isReconnectToken = (name, where) => where === "query" && name === "reconnect_token";
11
+ /** The WebSocket operation `op`'s answer, its message types hoisted into `env.at`. */
12
+ function wsAnswer(op, { at }) {
13
+ if (op.ir.messages === undefined)
14
+ return { render: () => ["Task<TypedWebSocket>", "SocketAsync"], type: null };
15
+ const { receive, send } = op.ir.messages;
16
+ const read = send === undefined ? { type: JSON_ELEMENT } : messageType(op, send, "Send", at);
17
+ const write = receive === undefined ? { type: JSON_ELEMENT } : messageType(op, receive, "Receive", at);
18
+ valueHandlers(READER, read, at);
19
+ return {
20
+ infos: [read.type, write.type],
21
+ render: (spell) => [
22
+ `Task<TypedWebSocket<${spell.runtime(read.type)}, ${spell.runtime(write.type)}>>`,
23
+ "TypedSocketAsync",
24
+ ],
25
+ type: null,
26
+ };
27
+ }
7
28
  /** The WebSocket operation's answer, its two fields and its `<returns>` text. */
8
29
  export const wsStream = {
9
- answer: () => ({ render: () => ["Task<TypedWebSocket>", "SocketAsync"], type: null }),
30
+ answer: wsAnswer,
10
31
  args: ["protocols", "reconnectToken"],
11
32
  carries: isReconnectToken,
12
33
  fields: [PROTOCOLS, RECONNECT_TOKEN],
@@ -11,11 +11,34 @@ export type Shape = {
11
11
  readonly fail: string;
12
12
  readonly tail: (client: string) => string[];
13
13
  };
14
- /** What a streaming operation's method is: how it answers, what its Opts add, and the note its godoc ends on. */
14
+ /**
15
+ * What a streaming operation's method is: how it answers, what its Opts add, the note its godoc ends on, and the
16
+ * package-level functions declared for it that its body calls, which a path param never shadows.
17
+ */
15
18
  export type GoStream = {
16
19
  readonly shape: Shape;
17
20
  readonly opts: StreamOpts;
18
21
  readonly doc: string;
22
+ readonly calls: readonly string[];
23
+ /** what a socket's server receives, typed; absent for an SSE op and a socket that declares no `receive` */
24
+ readonly sends?: GoSends;
25
+ };
26
+ /** A message type the server receives: its Go type, and the fields it requires at its top level. */
27
+ export type GoMessageType = {
28
+ readonly type: string;
29
+ readonly required: readonly string[];
30
+ };
31
+ /**
32
+ * What a socket's server receives, as the CLI checks an input line against it: one message type,
33
+ * or a union keyed on `key` (D9), each member by its value.
34
+ */
35
+ export type GoSends = (GoMessageType & {
36
+ readonly key: null;
37
+ }) | {
38
+ readonly key: string;
39
+ readonly members: readonly (GoMessageType & {
40
+ readonly value: string;
41
+ })[];
19
42
  };
20
43
  /** The runtime call's arguments: the ctx, the client's config, the call, each of `extra`, then the per-call options. */
21
44
  export declare const sendArgs: (client: string, ...extra: string[]) => string;
@@ -1,4 +1,5 @@
1
1
  import { type SdkBody, type SdkOp, type SdkResponseKind, type SdkStream } from "../../ir/sdk-model.ts";
2
+ import { type GoSends } from "./sdk-answer.ts";
2
3
  import { type GoPart } from "./sdk-body.ts";
3
4
  import { type GoResponseHeaders } from "./sdk-opts.ts";
4
5
  import { type GoTypeContext } from "./types.ts";
@@ -32,6 +33,8 @@ export type GoMethodCall = {
32
33
  readonly opts: string;
33
34
  /** a multipart body's parts by their `<Op>Body` fields; null for any other body */
34
35
  readonly parts: readonly GoPart[] | null;
36
+ /** what a socket's server receives, typed: the CLI checks each input line against it; null when untyped or no socket */
37
+ readonly sends: GoSends | null;
35
38
  };
36
39
  /**
37
40
  * One operation's method, its client.go declarations by name (`<Op>Opts`, `<Op>Headers`), how a caller reaches it,
@@ -11,6 +11,7 @@ import { socketStream } from "./ws.js";
11
11
  const METHOD_LOCALS = [
12
12
  "c",
13
13
  "call",
14
+ "conn",
14
15
  "ctx",
15
16
  "data",
16
17
  "decodeJSON",
@@ -37,8 +38,9 @@ const METHOD_LOCALS = [
37
38
  "result",
38
39
  "setHeaderValue",
39
40
  "setIdempotencyKey",
41
+ "sseData",
40
42
  "sseFail",
41
- "streamJSON",
43
+ "streamEvents",
42
44
  "streamText",
43
45
  "textField",
44
46
  "topts",
@@ -69,15 +71,18 @@ function methodDoc(op, name, stream) {
69
71
  const text = [route, op.summary, op.description].filter((part) => part !== "");
70
72
  return lineComment(text.join("\n\n"), "//");
71
73
  }
72
- /** How the method of `op` answers, and its stream: null for an operation that answers once. */
74
+ /**
75
+ * How the method of `op` answers, its stream (null for an operation that answers once), and the method's locals: the
76
+ * runtime's names, and the stream's own.
77
+ */
73
78
  function answering(op, env) {
74
79
  if (op.stream !== null) {
75
- const stream = op.stream === "sse" ? sseStream(op, env.at) : socketStream(op.stream);
76
- return { shape: stream.shape, stream };
80
+ const stream = op.stream === "sse" ? sseStream(op, env.at) : socketStream(op, op.stream, env.at);
81
+ return { locals: new NameScope([...METHOD_LOCALS, ...stream.calls]), shape: stream.shape, stream };
77
82
  }
78
83
  const schema = op.success.schema;
79
84
  const result = schema && goTypeOf(schema, { ...env.at, fieldName: "Response", parentName: op.id }).replace(/^\*/, "");
80
- return { shape: shapeOf({ kind: op.success.kind, result }), stream: null };
85
+ return { locals: new NameScope(METHOD_LOCALS), shape: shapeOf({ kind: op.success.kind, result }), stream: null };
81
86
  }
82
87
  /** The statements before `c`: the path expanded from its params, or the template as it is. */
83
88
  function pathLines(op, locals, fail) {
@@ -129,19 +134,19 @@ function twinOf(op, returns, params) {
129
134
  /** The method of `op` named `name` on `receiver`, and its `<Op>Opts` and `<Op>Headers`. */
130
135
  export function goMethod(op, name, receiver, env) {
131
136
  const opts = env.at.names.claimConst(`${goExported(op.id)}Opts`);
132
- const locals = new NameScope(METHOD_LOCALS);
137
+ const { locals, shape, stream } = answering(op, env);
133
138
  const bodyLocal = op.body && locals.claim("body");
134
139
  const body = op.body && goBody(op, op.body, { at: env.at, local: bodyLocal });
135
140
  const pathLocals = pathParamsOf(op).map((param) => [param, locals.claim(goLocal(param.name))]);
136
- const { shape, stream } = answering(op, env);
137
141
  const streamOpts = stream?.opts ?? null;
138
142
  const fields = optsFields(op, opts, env.at, streamOpts);
139
143
  const path = pathLines(op, pathLocals, shape.fail);
140
144
  const headers = responseHeaders(op, env.at);
145
+ const bodyTypes = body ? [body.type] : [];
141
146
  const params = [
142
147
  "ctx context.Context",
143
148
  ...pathLocals.map(([, local]) => `${local} string`),
144
- ...(body ? [`${bodyLocal} ${body.type}`] : []),
149
+ ...bodyTypes.map((type) => `${bodyLocal} ${type}`),
145
150
  `opts *${opts}`,
146
151
  "reqOpts ...RequestOption",
147
152
  ];
@@ -160,13 +165,14 @@ export function goMethod(op, name, receiver, env) {
160
165
  decls.push([headers.plan.type, headers.decl]);
161
166
  const call = {
162
167
  ...callOf(op, name, pathLocals, fields),
163
- bodyType: body ? body.type : null,
168
+ bodyType: bodyTypes[0] ?? null,
164
169
  opts,
165
170
  parts: body?.parts ?? null,
166
171
  responseHeaders: headers?.plan ?? null,
167
172
  returns: shape.returns,
173
+ sends: stream?.sends ?? null,
168
174
  };
169
- const types = ["context.Context", ...pathLocals.map(() => "string"), ...(body ? [body.type] : []), `*${opts}`];
175
+ const types = ["context.Context", ...pathLocals.map(() => "string"), ...bodyTypes, `*${opts}`];
170
176
  const twin = twinOf(op, shape.returns, types);
171
177
  return { call, decls, lines, twin };
172
178
  }
@@ -1,16 +1,8 @@
1
- /**
2
- * A server-sent-events operation as a Go method (G12): it returns `iter.Seq2[SSEEvent[T], error]`,
3
- * `T` the type of the declared event schema (`string` when the events are untyped), and opens the
4
- * stream when ranged. `<Op>Opts.LastEventID` resumes it as the Last-Event-ID header, which also
5
- * carries a declared Last-Event-ID header param (Fd3). An error status at the opening is the
6
- * stream's error value; its `Client.Safe()` twin opens the stream on the call and answers that
7
- * status as its Result's Err (bit 21 i3).
8
- */
9
- import type { SdkOp } from "../../ir/sdk-model.ts";
1
+ import { type SdkOp } from "../../ir/sdk-model.ts";
10
2
  import { type GoStream } from "./sdk-answer.ts";
11
3
  import type { OptsField } from "./sdk-opts.ts";
12
4
  import { type GoTypeContext } from "./types.ts";
13
5
  /** Whether a declared param is the Last-Event-ID header (any casing), the resume channel an SSE dial sends. */
14
6
  export declare const isLastEventIdHeader: (param: string, where: OptsField["in"]) => boolean;
15
- /** The method of the SSE operation `op`, its event type hoisted into `at` as `<Op>Event` when inline. */
7
+ /** The method of the SSE operation `op`, its event types hoisted into `at`. */
16
8
  export declare function sseStream(op: SdkOp, at: GoTypeContext): GoStream;
@@ -1,3 +1,6 @@
1
+ import { isJsonEventData, sseEvents } from "../../ir/sdk-model.js";
2
+ import { goString, lineComment } from "../shared/escape.js";
3
+ import { goExported } from "../shared/lang.js";
1
4
  import { sendArgs } from "./sdk-answer.js";
2
5
  import { goTypeOf } from "./types.js";
3
6
  /** Whether a declared param is the Last-Event-ID header (any casing), the resume channel an SSE dial sends. */
@@ -9,18 +12,90 @@ const SSE_OPTS = {
9
12
  fields: [{ name: "LastEventID", type: "string" }],
10
13
  sets: ['if opts.LastEventID != "" {', '\tc.headers["Last-Event-ID"] = opts.LastEventID', "}"],
11
14
  };
12
- /** The method of the SSE operation `op`, its event type hoisted into `at` as `<Op>Event` when inline. */
15
+ const DOC = "Breaking out of the loop closes the stream; ctx ends it quietly.";
16
+ /** A stream method yielding `elem`, each event read off the wire by `decode`, as sent without one (G12). */
17
+ const streamOf = (elem, decode, calls) => ({
18
+ calls,
19
+ doc: DOC,
20
+ opts: SSE_OPTS,
21
+ shape: {
22
+ fail: `sseFail[${elem}](err)`,
23
+ returns: `iter.Seq2[${elem}, error]`,
24
+ tail: (client) => [
25
+ decode === undefined
26
+ ? `\treturn streamText(${sendArgs(client)})`
27
+ : `\treturn streamEvents(${sendArgs(client, decode)})`,
28
+ ],
29
+ },
30
+ });
31
+ /** A type of the sealed `iface`, embedding `SSEEvent[data]`, with its marker method. */
32
+ const variantDecl = (iface, type, data, doc) => [
33
+ ...lineComment(doc, "//"),
34
+ `type ${type} struct {`,
35
+ `\tSSEEvent[${data}]`,
36
+ "}",
37
+ "",
38
+ `func (${type}) is${iface}() {}`,
39
+ ];
40
+ /** The `case` of the decoder for `variant`: its data decoded from JSON, or its event as sent. */
41
+ const caseOf = ({ event, json, type, data }) => [
42
+ `\tcase ${goString(event)}:`,
43
+ ...(json
44
+ ? [`\t\tev, err := sseData[${data}](raw)`, `\t\treturn ${type}{ev}, err`]
45
+ : [`\t\treturn ${type}{raw}, nil`]),
46
+ ];
47
+ /**
48
+ * `<Op>Event` and its types, declared in one block in `at` (the interface, a type per event name in the order
49
+ * declared, `<Op>OtherEvent`, the decoder); the interface's name and the decoder's.
50
+ */
51
+ function namedEvents(op, events, at) {
52
+ const base = goExported(op.id);
53
+ const iface = at.names.claimConst(`${base}Event`);
54
+ const variants = events.map(({ data, name }) => ({
55
+ data: goTypeOf(data, { ...at, fieldName: name, parentName: op.id }).replace(/^\*/, ""),
56
+ event: name,
57
+ json: isJsonEventData(data, at.names.resolve),
58
+ type: at.names.claimConst(`${base}${goExported(name)}Event`),
59
+ }));
60
+ const other = at.names.claimConst(`${base}OtherEvent`);
61
+ const decode = at.names.claimConst(`decode${iface}`);
62
+ const types = [...variants.map((variant) => variant.type), other];
63
+ at.decls.set(iface, [
64
+ ...lineComment(`${iface} is one event of ${op.id}: ${types.slice(0, -1).join(", ")}, or ${other} for a name the operation does not declare. A type switch on it reads the event's Data.`, "//"),
65
+ `type ${iface} interface {`,
66
+ "\t// Untyped is the event with its Data as text.",
67
+ "\tUntyped() SSEEvent[string]",
68
+ `\tis${iface}()`,
69
+ "}",
70
+ "",
71
+ ...variants.flatMap((variant) => [
72
+ ...variantDecl(iface, variant.type, variant.data, `${variant.type} is the ${goString(variant.event)} event.`),
73
+ "",
74
+ ]),
75
+ ...variantDecl(iface, other, "string", `${other} is an event of a name the operation does not declare, its Data as sent.`),
76
+ "",
77
+ `// ${decode} is raw as its event's type, its Data decoded by its name; an unnamed event is "message".`,
78
+ `func ${decode}(raw SSEEvent[string]) (${iface}, error) {`,
79
+ '\tif raw.Event == "" {',
80
+ '\t\traw.Event = "message"',
81
+ "\t}",
82
+ "\tswitch raw.Event {",
83
+ ...variants.flatMap(caseOf),
84
+ "\t}",
85
+ `\treturn ${other}{raw}, nil`,
86
+ "}",
87
+ ].join("\n"));
88
+ return { decode, iface };
89
+ }
90
+ /** The method of the SSE operation `op`, its event types hoisted into `at`. */
13
91
  export function sseStream(op, at) {
92
+ const events = sseEvents(op.ir);
93
+ if (events !== undefined) {
94
+ const { decode, iface } = namedEvents(op, events, at);
95
+ return streamOf(iface, decode, [decode]);
96
+ }
14
97
  const typed = op.events && goTypeOf(op.events, { ...at, fieldName: "Event", parentName: op.id }).replace(/^\*/, "");
15
- const event = typed ?? "string";
16
- const open = typed === undefined ? "streamText" : `streamJSON[${typed}]`;
17
- return {
18
- doc: "Breaking out of the loop closes the stream; ctx ends it quietly.",
19
- opts: SSE_OPTS,
20
- shape: {
21
- fail: `sseFail[${event}](err)`,
22
- returns: `iter.Seq2[SSEEvent[${event}], error]`,
23
- tail: (client) => [`\treturn ${open}(${sendArgs(client)})`],
24
- },
25
- };
98
+ if (typed === undefined)
99
+ return streamOf("SSEEvent[string]", undefined, []);
100
+ return streamOf(`SSEEvent[${typed}]`, `sseData[${typed}]`, []);
26
101
  }
@@ -5,13 +5,14 @@
5
5
  */
6
6
  import type { IRDiscriminator, IRSchema } from "../../ir/model.ts";
7
7
  import type { GoTypeNames } from "./types.ts";
8
- type Union = Extract<IRSchema, {
8
+ export type Union = Extract<IRSchema, {
9
9
  kind: "union";
10
10
  }> & {
11
11
  discriminator: IRDiscriminator;
12
12
  };
13
13
  /** Declares an inline variant once under `names.hoist(key, base)`; its name. */
14
14
  export type DeclareVariant = (schema: IRSchema, key: string, base: string) => string;
15
+ /** The Go type of each ref or inline-object variant of `union`, in order; inline ones declared through `declare`. */
16
+ export declare const variantTypes: (name: string, union: Union, names: GoTypeNames, declare: DeclareVariant) => string[];
15
17
  /** The union's struct and its (un)marshal methods; inline object variants are declared through `declare`. */
16
18
  export declare function unionDecl(name: string, union: Union, names: GoTypeNames, declare: DeclareVariant): string;
17
- export {};
@@ -65,6 +65,8 @@ function marshal(name, variants) {
65
65
  "}",
66
66
  ];
67
67
  }
68
+ /** The Go type of each ref or inline-object variant of `union`, in order; inline ones declared through `declare`. */
69
+ export const variantTypes = (name, union, names, declare) => variantsOf(name, union, names, declare).map(({ type }) => type);
68
70
  /** The union's struct and its (un)marshal methods; inline object variants are declared through `declare`. */
69
71
  export function unionDecl(name, union, names, declare) {
70
72
  const property = union.discriminator.propertyName;
@@ -5,6 +5,7 @@
5
5
  * the shared escape layer.
6
6
  */
7
7
  import type { IR, IRSchema } from "../../ir/model.ts";
8
+ import type { Dispatch } from "../../ir/sdk-model.ts";
8
9
  /** Package-level naming shared by every type one SDK declares. */
9
10
  export type GoTypeNames = {
10
11
  /** the Go type name of the component `schema` */
@@ -30,3 +31,8 @@ export declare function goTypeContext(ir?: IR): GoTypeContext;
30
31
  export declare function goTypeOf(ir: IRSchema, at: GoTypeContext): string;
31
32
  /** The top-level declaration of the type `name` (a Go identifier already) for `ir` (v0 irRenderTopLevel). */
32
33
  export declare function goTopLevel(name: string, ir: IRSchema, at: GoTypeContext): string;
34
+ /**
35
+ * Each member of the keyed union `schema` (D9) as its value beside its Go type: a component's struct names its
36
+ * members; an inline union, raw JSON in a struct, hoists each inline member into `at` as `<Parent><Field><Value>`.
37
+ */
38
+ export declare function goKeyedMembers(schema: IRSchema, dispatch: Dispatch, at: GoTypeContext): (readonly [string, string])[];
@@ -3,7 +3,7 @@ import { compareCodeUnits, goExported, NameScope } from "../shared/lang.js";
3
3
  import { irNames, plainNames } from "./types-names.js";
4
4
  import { isNilable } from "./types-codec.js";
5
5
  import { isTagName, structDecl } from "./types-struct.js";
6
- import { unionDecl } from "./types-union.js";
6
+ import { unionDecl, variantTypes } from "./types-union.js";
7
7
  const RAW = "json.RawMessage";
8
8
  /* deeper than this, a schema is raw JSON */
9
9
  const MAX_DEPTH = 12;
@@ -175,3 +175,14 @@ export function goTopLevel(name, ir, at) {
175
175
  /* a map or an empty struct is a named type; anything else an alias */
176
176
  return `type ${name} ${ir.kind === "object" ? "" : "= "}${use(ir, member(name, at, "Value"))}`;
177
177
  }
178
+ /**
179
+ * Each member of the keyed union `schema` (D9) as its value beside its Go type: a component's struct names its
180
+ * members; an inline union, raw JSON in a struct, hoists each inline member into `at` as `<Parent><Field><Value>`.
181
+ */
182
+ export function goKeyedMembers(schema, dispatch, at) {
183
+ const name = schema.kind === "ref" ? at.names.ref(schema.name) : `${goExported(at.parentName)}${goExported(at.fieldName)}`;
184
+ /* a mapping names refs only, whose type is their component's: the key alone names each inline member */
185
+ const union = { ...dispatch.union, discriminator: { propertyName: dispatch.key } };
186
+ const types = variantTypes(name, union, at.names, (variant, key, base) => declare(variant, at, key, base));
187
+ return dispatch.members.map(({ value }, i) => [value, types[i]]);
188
+ }
@@ -1,12 +1,5 @@
1
- /**
2
- * A WebSocket or realtime operation as a Go method. A WebSocket operation dials its socket and
3
- * returns `(*TypedWebSocket, error)`: `<Op>Opts.ReconnectToken` rides as the `reconnect_token`
4
- * query param after the declared ones, and `Protocols` are the subprotocols it offers. A realtime
5
- * operation returns `(*ResumableConnection, error)`, already open over the WebSocket, SSE and
6
- * long-poll chain, its ctx bounding the open (Fd1); its Opts carry the resume cursor, the protocols
7
- * and the reconnect policy. A declared param on a resume channel the runtime sends itself is carried
8
- * by those fields, so the wire holds one pair (Fd3). Neither declares a response a caller receives.
9
- */
1
+ import { type SdkOp } from "../../ir/sdk-model.ts";
10
2
  import { type GoStream } from "./sdk-answer.ts";
11
- /** The method of a WebSocket or realtime operation. */
12
- export declare const socketStream: (stream: "realtime" | "ws") => GoStream;
3
+ import { type GoTypeContext } from "./types.ts";
4
+ /** The method of a WebSocket or realtime operation, its message types hoisted into `at`. */
5
+ export declare const socketStream: (op: SdkOp, stream: "realtime" | "ws", at: GoTypeContext) => GoStream;