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

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 (368) hide show
  1. package/README.md +403 -21
  2. package/assets/installers/examples/github.config.ts +17 -19
  3. package/assets/installers/examples/goreleaser.config.ts +16 -18
  4. package/assets/installers/examples/raw.config.ts +13 -15
  5. package/bin/clients.js +87 -66
  6. package/bin/installgen.js +19 -10
  7. package/dist/cli.d.ts +4 -4
  8. package/dist/cli.js +18 -12
  9. package/dist/emit/cli/channels.d.ts +2 -2
  10. package/dist/emit/cli/channels.js +18 -13
  11. package/dist/emit/cli/commands.d.ts +1 -1
  12. package/dist/emit/cli/commands.js +39 -13
  13. package/dist/emit/cli/discovery.d.ts +0 -6
  14. package/dist/emit/cli/discovery.js +9 -7
  15. package/dist/emit/cli/flags.d.ts +1 -3
  16. package/dist/emit/cli/flags.js +18 -8
  17. package/dist/emit/cli/install.d.ts +0 -8
  18. package/dist/emit/cli/install.js +3 -3
  19. package/dist/emit/cli/layout.d.ts +1 -1
  20. package/dist/emit/cli/layout.js +13 -10
  21. package/dist/emit/cli/module.d.ts +6 -6
  22. package/dist/emit/cli/module.js +10 -10
  23. package/dist/emit/cli/release.d.ts +0 -11
  24. package/dist/emit/cli/release.js +4 -4
  25. package/dist/emit/cli/skills.js +8 -4
  26. package/dist/emit/csharp/errors.js +4 -4
  27. package/dist/emit/csharp/json.js +8 -8
  28. package/dist/emit/csharp/realtime.d.ts +1 -8
  29. package/dist/emit/csharp/realtime.js +26 -26
  30. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  31. package/dist/emit/csharp/sdk-answer.js +4 -4
  32. package/dist/emit/csharp/sdk-body.js +8 -6
  33. package/dist/emit/csharp/sdk-client.d.ts +3 -3
  34. package/dist/emit/csharp/sdk-client.js +2 -2
  35. package/dist/emit/csharp/sdk-csproj.d.ts +7 -9
  36. package/dist/emit/csharp/sdk-csproj.js +10 -10
  37. package/dist/emit/csharp/sdk-doc.js +1 -1
  38. package/dist/emit/csharp/sdk-method.d.ts +0 -1
  39. package/dist/emit/csharp/sdk-method.js +19 -8
  40. package/dist/emit/csharp/sdk-plan.js +0 -1
  41. package/dist/emit/csharp/sdk.js +3 -3
  42. package/dist/emit/csharp/sse.d.ts +0 -13
  43. package/dist/emit/csharp/sse.js +92 -11
  44. package/dist/emit/csharp/transport.js +9 -9
  45. package/dist/emit/csharp/types-enum.js +3 -1
  46. package/dist/emit/csharp/types-messages.d.ts +47 -0
  47. package/dist/emit/csharp/types-messages.js +172 -0
  48. package/dist/emit/csharp/types-names.js +13 -14
  49. package/dist/emit/csharp/types-record.js +3 -3
  50. package/dist/emit/csharp/types-union.d.ts +1 -1
  51. package/dist/emit/csharp/types.d.ts +0 -1
  52. package/dist/emit/csharp/types.js +3 -3
  53. package/dist/emit/csharp/ws.d.ts +0 -15
  54. package/dist/emit/csharp/ws.js +26 -5
  55. package/dist/emit/go/errors.js +1 -1
  56. package/dist/emit/go/http.js +2 -2
  57. package/dist/emit/go/module-path.js +2 -2
  58. package/dist/emit/go/sdk-answer.d.ts +24 -1
  59. package/dist/emit/go/sdk-answer.js +1 -1
  60. package/dist/emit/go/sdk-body.js +11 -7
  61. package/dist/emit/go/sdk-client.js +1 -1
  62. package/dist/emit/go/sdk-method.d.ts +3 -0
  63. package/dist/emit/go/sdk-method.js +18 -12
  64. package/dist/emit/go/sdk-mirror.js +2 -2
  65. package/dist/emit/go/sdk-opts.d.ts +0 -2
  66. package/dist/emit/go/sdk-opts.js +3 -3
  67. package/dist/emit/go/sdk.d.ts +1 -1
  68. package/dist/emit/go/sdk.js +9 -9
  69. package/dist/emit/go/sse.d.ts +2 -10
  70. package/dist/emit/go/sse.js +88 -13
  71. package/dist/emit/go/types-names.js +5 -0
  72. package/dist/emit/go/types-struct.d.ts +2 -1
  73. package/dist/emit/go/types-struct.js +1 -1
  74. package/dist/emit/go/types-union.d.ts +3 -2
  75. package/dist/emit/go/types-union.js +2 -0
  76. package/dist/emit/go/types.d.ts +6 -0
  77. package/dist/emit/go/types.js +20 -9
  78. package/dist/emit/go/ws.d.ts +4 -11
  79. package/dist/emit/go/ws.js +215 -59
  80. package/dist/emit/java/gradle.d.ts +7 -9
  81. package/dist/emit/java/gradle.js +8 -8
  82. package/dist/emit/java/json.d.ts +3 -0
  83. package/dist/emit/java/json.js +1 -1
  84. package/dist/emit/java/layout-ast.d.ts +4 -1
  85. package/dist/emit/java/layout-ast.js +1 -1
  86. package/dist/emit/java/layout-decl.js +5 -4
  87. package/dist/emit/java/layout-doc.js +13 -7
  88. package/dist/emit/java/layout-dot.js +1 -1
  89. package/dist/emit/java/layout-strings.js +4 -5
  90. package/dist/emit/java/layout-types.js +7 -5
  91. package/dist/emit/java/layout-visitor.js +4 -3
  92. package/dist/emit/java/layout.js +5 -4
  93. package/dist/emit/java/models-names.d.ts +2 -0
  94. package/dist/emit/java/models-names.js +6 -4
  95. package/dist/emit/java/models-record.d.ts +0 -1
  96. package/dist/emit/java/models-record.js +3 -3
  97. package/dist/emit/java/models-union.d.ts +13 -2
  98. package/dist/emit/java/models-union.js +12 -6
  99. package/dist/emit/java/models.d.ts +5 -1
  100. package/dist/emit/java/models.js +44 -20
  101. package/dist/emit/java/realtime.d.ts +34 -26
  102. package/dist/emit/java/realtime.js +45 -10
  103. package/dist/emit/java/sdk-client.d.ts +6 -6
  104. package/dist/emit/java/sdk-client.js +1 -1
  105. package/dist/emit/java/sdk-decl.js +2 -2
  106. package/dist/emit/java/sdk-errors.js +1 -1
  107. package/dist/emit/java/sdk-headers.js +2 -2
  108. package/dist/emit/java/sdk-mirror.js +7 -6
  109. package/dist/emit/java/sdk-models.d.ts +1 -1
  110. package/dist/emit/java/sdk-models.js +7 -7
  111. package/dist/emit/java/sdk-op.d.ts +1 -10
  112. package/dist/emit/java/sdk-op.js +9 -9
  113. package/dist/emit/java/sdk-params.d.ts +5 -5
  114. package/dist/emit/java/sdk-params.js +3 -2
  115. package/dist/emit/java/sdk-plan.js +0 -1
  116. package/dist/emit/java/sdk.d.ts +1 -1
  117. package/dist/emit/java/sdk.js +14 -13
  118. package/dist/emit/java/sse.d.ts +12 -13
  119. package/dist/emit/java/sse.js +105 -6
  120. package/dist/emit/java/ws.d.ts +48 -9
  121. package/dist/emit/java/ws.js +88 -4
  122. package/dist/emit/mcp/annotations.js +8 -4
  123. package/dist/emit/mcp/files.js +9 -9
  124. package/dist/emit/mcp/mounted.js +2 -2
  125. package/dist/emit/mcp/output-schema.d.ts +4 -2
  126. package/dist/emit/mcp/output-schema.js +58 -14
  127. package/dist/emit/mcp/registry.d.ts +0 -2
  128. package/dist/emit/mcp/registry.js +5 -4
  129. package/dist/emit/mcp/runtime.js +2 -2
  130. package/dist/emit/mcp/schema.js +22 -11
  131. package/dist/emit/mcp/server.d.ts +7 -7
  132. package/dist/emit/mcp/server.js +7 -6
  133. package/dist/emit/mcp/tools.js +7 -6
  134. package/dist/emit/python/errors.js +3 -3
  135. package/dist/emit/python/realtime.d.ts +9 -6
  136. package/dist/emit/python/realtime.js +22 -20
  137. package/dist/emit/python/sdk-answer.d.ts +8 -8
  138. package/dist/emit/python/sdk-answer.js +2 -2
  139. package/dist/emit/python/sdk-body.js +4 -5
  140. package/dist/emit/python/sdk-client.js +5 -5
  141. package/dist/emit/python/sdk-doc.js +2 -2
  142. package/dist/emit/python/sdk-method.d.ts +1 -1
  143. package/dist/emit/python/sdk-method.js +38 -11
  144. package/dist/emit/python/sdk-plan.js +0 -1
  145. package/dist/emit/python/sdk-pyproject.d.ts +0 -2
  146. package/dist/emit/python/sdk-pyproject.js +8 -8
  147. package/dist/emit/python/sdk.d.ts +1 -1
  148. package/dist/emit/python/sdk.js +28 -8
  149. package/dist/emit/python/sse.d.ts +0 -7
  150. package/dist/emit/python/sse.js +36 -6
  151. package/dist/emit/python/transport.js +4 -4
  152. package/dist/emit/python/types-dict.d.ts +2 -2
  153. package/dist/emit/python/types-dict.js +1 -1
  154. package/dist/emit/python/types-names.js +2 -2
  155. package/dist/emit/python/types-union.js +1 -1
  156. package/dist/emit/python/types.d.ts +7 -0
  157. package/dist/emit/python/types.js +23 -6
  158. package/dist/emit/python/ws.d.ts +21 -10
  159. package/dist/emit/python/ws.js +69 -3
  160. package/dist/emit/rust/errors.js +3 -3
  161. package/dist/emit/rust/http.js +4 -4
  162. package/dist/emit/rust/realtime.d.ts +7 -5
  163. package/dist/emit/rust/realtime.js +15 -18
  164. package/dist/emit/rust/sdk-body.js +8 -5
  165. package/dist/emit/rust/sdk-cargo.d.ts +16 -18
  166. package/dist/emit/rust/sdk-cargo.js +12 -12
  167. package/dist/emit/rust/sdk-client.d.ts +1 -1
  168. package/dist/emit/rust/sdk-client.js +3 -3
  169. package/dist/emit/rust/sdk-method.js +3 -3
  170. package/dist/emit/rust/sdk-opts.d.ts +2 -1
  171. package/dist/emit/rust/sdk-opts.js +2 -2
  172. package/dist/emit/rust/sdk-plan.js +0 -1
  173. package/dist/emit/rust/sdk.d.ts +1 -1
  174. package/dist/emit/rust/sdk.js +5 -5
  175. package/dist/emit/rust/sse.d.ts +11 -12
  176. package/dist/emit/rust/sse.js +54 -8
  177. package/dist/emit/rust/types-names.js +3 -3
  178. package/dist/emit/rust/types-struct.js +1 -1
  179. package/dist/emit/rust/types-union.d.ts +10 -2
  180. package/dist/emit/rust/types-union.js +4 -0
  181. package/dist/emit/rust/types.d.ts +9 -0
  182. package/dist/emit/rust/types.js +20 -12
  183. package/dist/emit/rust/ws.d.ts +22 -15
  184. package/dist/emit/rust/ws.js +60 -10
  185. package/dist/emit/shared/escape.js +17 -17
  186. package/dist/emit/shared/format.js +1 -1
  187. package/dist/emit/shared/gofmt.js +1 -1
  188. package/dist/emit/shared/lang.js +10 -10
  189. package/dist/emit/shared/literals.d.ts +5 -0
  190. package/dist/emit/shared/literals.js +8 -0
  191. package/dist/emit/shared/metadata.d.ts +0 -6
  192. package/dist/emit/shared/metadata.js +8 -7
  193. package/dist/emit/shared/ruff.js +1 -1
  194. package/dist/emit/shared/rustfmt.js +1 -1
  195. package/dist/emit/shared/type-emitter.js +37 -20
  196. package/dist/emit/shared/unknown-type.constants.d.ts +2 -0
  197. package/dist/emit/shared/unknown-type.constants.js +2 -0
  198. package/dist/emit/ts/http.d.ts +0 -2
  199. package/dist/emit/ts/http.js +4 -4
  200. package/dist/emit/ts/package.d.ts +14 -12
  201. package/dist/emit/ts/package.js +9 -8
  202. package/dist/emit/ts/route-tree.js +2 -2
  203. package/dist/emit/ts/sdk-types-preamble.d.ts +1 -1
  204. package/dist/emit/ts/sdk-types-preamble.js +6 -2
  205. package/dist/emit/ts/sdk-types.js +59 -20
  206. package/dist/emit/ts/sdk.js +6 -6
  207. package/dist/emit/ts/service-map.d.ts +10 -3
  208. package/dist/emit/ts/service-map.js +30 -2
  209. package/dist/emit/ts/tanstack-query.js +6 -6
  210. package/dist/emit/ts/type-gen.js +36 -21
  211. package/dist/emit/ts/webhooks.d.ts +0 -2
  212. package/dist/emit/ts/webhooks.js +3 -3
  213. package/dist/extract/chain.js +5 -4
  214. package/dist/extract/extract.js +5 -5
  215. package/dist/extract/serialize.d.ts +0 -2
  216. package/dist/extract/serialize.js +14 -15
  217. package/dist/extract/walk.js +15 -12
  218. package/dist/gen/args.js +9 -5
  219. package/dist/gen/formatters.js +5 -3
  220. package/dist/gen/shipped.js +2 -2
  221. package/dist/gen/targets.d.ts +2 -4
  222. package/dist/gen/targets.js +8 -4
  223. package/dist/gen/write.js +4 -2
  224. package/dist/index.js +2 -2
  225. package/dist/installers/cli.d.ts +4 -4
  226. package/dist/installers/cli.js +24 -24
  227. package/dist/installers/commands/build.d.ts +4 -4
  228. package/dist/installers/commands/build.js +2 -3
  229. package/dist/installers/commands/check.d.ts +2 -2
  230. package/dist/installers/commands/check.js +11 -10
  231. package/dist/installers/commands/init.d.ts +2 -2
  232. package/dist/installers/commands/init.js +1 -2
  233. package/dist/installers/config/define-config.d.ts +16 -16
  234. package/dist/installers/config/define-config.js +1 -1
  235. package/dist/installers/config/hooks/bun.d.ts +6 -6
  236. package/dist/installers/config/hooks/node.js +1 -1
  237. package/dist/installers/config/load.d.ts +6 -8
  238. package/dist/installers/config/load.js +7 -8
  239. package/dist/installers/config/resolve.d.ts +1 -2
  240. package/dist/installers/config/resolve.js +28 -33
  241. package/dist/installers/config/types.d.ts +6 -6
  242. package/dist/installers/config/types.js +0 -1
  243. package/dist/installers/render/quote.js +3 -5
  244. package/dist/installers/render/render.d.ts +6 -6
  245. package/dist/installers/render/render.js +26 -26
  246. package/dist/installers/ui.d.ts +4 -4
  247. package/dist/installers/ui.js +3 -3
  248. package/dist/ir/build.d.ts +3 -3
  249. package/dist/ir/build.js +12 -5
  250. package/dist/ir/load.js +9 -10
  251. package/dist/ir/model.d.ts +16 -1
  252. package/dist/ir/model.js +0 -1
  253. package/dist/ir/resolve-refs.js +2 -2
  254. package/dist/ir/resource-tree.js +2 -1
  255. package/dist/ir/route-tree-intern.js +1 -1
  256. package/dist/ir/schema.js +3 -3
  257. package/dist/ir/sdk-model.d.ts +25 -1
  258. package/dist/ir/sdk-model.js +38 -8
  259. package/dist/ir/slots.d.ts +1 -1
  260. package/dist/ir/slots.js +22 -11
  261. package/dist/ir/streams.d.ts +16 -0
  262. package/dist/ir/streams.js +40 -0
  263. package/dist/release/bootstrap.d.ts +3 -3
  264. package/dist/release/bootstrap.js +7 -7
  265. package/dist/release/bump-args.js +4 -4
  266. package/dist/release/bump-command.d.ts +1 -1
  267. package/dist/release/bump-command.js +9 -10
  268. package/dist/release/bump.d.ts +5 -4
  269. package/dist/release/bump.js +2 -2
  270. package/dist/release/cli.d.ts +4 -4
  271. package/dist/release/cli.js +4 -4
  272. package/dist/release/codegen.js +1 -1
  273. package/dist/release/digest.js +5 -7
  274. package/dist/release/git.js +5 -8
  275. package/dist/release/load.js +3 -3
  276. package/dist/release/manifest.js +9 -10
  277. package/dist/release/oasdiff.d.ts +10 -15
  278. package/dist/release/oasdiff.js +5 -6
  279. package/dist/release/registries.d.ts +0 -11
  280. package/dist/release/registries.js +17 -17
  281. package/dist/release/release-state.d.ts +16 -13
  282. package/dist/release/release-workflow.js +5 -7
  283. package/dist/release/repo-settings.d.ts +2 -1
  284. package/dist/release/spec-gate.d.ts +0 -2
  285. package/dist/release/spec-gate.js +6 -10
  286. package/dist/release/sync-command.d.ts +2 -2
  287. package/dist/release/sync-command.js +1 -1
  288. package/dist/release/sync-tree.js +9 -13
  289. package/dist/release/sync.d.ts +6 -6
  290. package/dist/release/sync.js +12 -13
  291. package/dist/release/types.d.ts +22 -22
  292. package/dist/release/types.js +0 -1
  293. package/dist/release/version-files.d.ts +3 -4
  294. package/dist/release/version-files.js +4 -5
  295. package/dist/runtime/.oxfmtrc.jsonc +8 -0
  296. package/dist/runtime/cli/socket.go +107 -13
  297. package/dist/runtime/cli/stream.go +18 -11
  298. package/dist/runtime/csharp/Adapters.cs +12 -11
  299. package/dist/runtime/csharp/Events.cs +22 -17
  300. package/dist/runtime/csharp/Realtime.cs +50 -23
  301. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  302. package/dist/runtime/csharp/TransportSse.cs +3 -3
  303. package/dist/runtime/csharp/Ws.cs +1 -1
  304. package/dist/runtime/csharp/WsDial.cs +19 -1
  305. package/dist/runtime/csharp/WsTyped.cs +109 -0
  306. package/dist/runtime/go/realtime.go +125 -41
  307. package/dist/runtime/go/realtime_loop.go +21 -18
  308. package/dist/runtime/go/result.go +2 -1
  309. package/dist/runtime/go/sse.go +11 -0
  310. package/dist/runtime/go/stream.go +29 -13
  311. package/dist/runtime/go/transport.go +15 -21
  312. package/dist/runtime/go/transport_longpoll.go +3 -4
  313. package/dist/runtime/go/transport_sse.go +6 -6
  314. package/dist/runtime/go/ws.go +157 -61
  315. package/dist/runtime/java/EventStream.java +47 -29
  316. package/dist/runtime/java/Exchange.java +5 -5
  317. package/dist/runtime/java/Flight.java +3 -3
  318. package/dist/runtime/java/Realtime.java +45 -11
  319. package/dist/runtime/java/ResumableConnection.java +77 -32
  320. package/dist/runtime/java/Socket.java +8 -4
  321. package/dist/runtime/java/SseAdapter.java +1 -1
  322. package/dist/runtime/java/TypedWebSocket.java +81 -24
  323. package/dist/runtime/java/WsAdapter.java +4 -2
  324. package/dist/runtime/java/WsDial.java +12 -5
  325. package/dist/runtime/mcp/files.ts +1 -1
  326. package/dist/runtime/mcp/http.ts +6 -2
  327. package/dist/runtime/mcp/listen.ts +1 -1
  328. package/dist/runtime/mcp/mount.ts +2 -2
  329. package/dist/runtime/mcp/protocol.ts +1 -1
  330. package/dist/runtime/python/events.py +25 -11
  331. package/dist/runtime/python/operation.py +6 -1
  332. package/dist/runtime/python/realtime.py +47 -33
  333. package/dist/runtime/python/send_async.py +1 -0
  334. package/dist/runtime/python/transport_sse.py +2 -2
  335. package/dist/runtime/python/transport_ws.py +1 -1
  336. package/dist/runtime/python/ws.py +100 -39
  337. package/dist/runtime/rust/events.rs +64 -41
  338. package/dist/runtime/rust/realtime.rs +80 -34
  339. package/dist/runtime/rust/realtime_loop.rs +37 -12
  340. package/dist/runtime/rust/sse.rs +3 -2
  341. package/dist/runtime/rust/transport_sse.rs +1 -1
  342. package/dist/runtime/rust/transport_ws.rs +3 -2
  343. package/dist/runtime/rust/ws.rs +122 -50
  344. package/dist/runtime/ts/realtime-connection.ts +22 -0
  345. package/dist/runtime/ts/realtime-transports.ts +13 -4
  346. package/dist/runtime/ts/realtime.ts +27 -3
  347. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  348. package/dist/runtime/ts/sdk-sse.ts +31 -14
  349. package/dist/runtime/ts/sdk-ws.ts +2 -1
  350. package/dist/runtime/ts/sdk.ts +9 -2
  351. package/dist/runtime/ts/sse.ts +8 -0
  352. package/dist/runtime/ts/ws.ts +88 -50
  353. package/dist/runtime/ts-tanstack-query/query.ts +0 -2
  354. package/package.json +12 -40
  355. package/dist/emit/cli/index.d.ts +0 -1
  356. package/dist/emit/cli/index.js +0 -1
  357. package/dist/emit/csharp/index.d.ts +0 -1
  358. package/dist/emit/csharp/index.js +0 -1
  359. package/dist/emit/go/index.d.ts +0 -1
  360. package/dist/emit/go/index.js +0 -1
  361. package/dist/emit/java/index.d.ts +0 -2
  362. package/dist/emit/java/index.js +0 -2
  363. package/dist/emit/mcp/index.d.ts +0 -3
  364. package/dist/emit/mcp/index.js +0 -3
  365. package/dist/emit/python/index.d.ts +0 -1
  366. package/dist/emit/python/index.js +0 -1
  367. package/dist/emit/rust/index.d.ts +0 -1
  368. package/dist/emit/rust/index.js +0 -1
@@ -11,16 +11,16 @@ import { toIR } from "../../ir/build.js";
11
11
  import { sdkModel } from "../../ir/sdk-model.js";
12
12
  import { pyDocLines } from "../shared/escape.js";
13
13
  import { compareCodeUnits, NameScope } from "../shared/lang.js";
14
+ import { packageOn } from "../shared/metadata.js";
14
15
  import { pythonErrorKeys } from "./errors.js";
15
16
  import { clientDecls, clientTitle } from "./sdk-client.js";
16
17
  import { allOrder, importBlock, importLine } from "./sdk-imports.js";
17
- import { packageOn } from "../shared/metadata.js";
18
18
  import { pyproject, validatePackageName, validateVersion } from "./sdk-pyproject.js";
19
19
  import { needsWebSocket, runtimeExports, runtimeFiles } from "./transport.js";
20
20
  import { pyTopLevel, pyTypeContext } from "./types.js";
21
- /* the marker ruff, mypy and linguist read */
21
+ // the marker ruff, mypy and linguist read
22
22
  const MARKER = "# @generated by clients. DO NOT EDIT.";
23
- /* where client.py imports each runtime name from, under `._http.` */
23
+ // where client.py imports each runtime name from, under `._http.`
24
24
  const RUNTIME = {
25
25
  AsyncRealtimeTransport: "realtime",
26
26
  AsyncTransport: "send_async",
@@ -32,9 +32,25 @@ const RUNTIME = {
32
32
  RequestOptions: "config",
33
33
  ResumableConnection: "realtime",
34
34
  Safe: "result",
35
+ SseEvent: "events",
35
36
  SyncTransport: "send_sync",
37
+ TransportOpts: "transport",
38
+ TypedWebSocket: "ws",
39
+ };
40
+ // where types.py imports each runtime name from, under `._http.`; any other it spells is `collections.abc`'s
41
+ const TYPES_RUNTIME = {
42
+ FilePart: "body",
43
+ HttpError: "errors",
44
+ ResumableConnection: "realtime",
45
+ SseEventOf: "events",
36
46
  TypedWebSocket: "ws",
47
+ WsClose: "ws",
37
48
  };
49
+ /** types.py's imports of the runtime names it spells, a line per module in code-unit order. */
50
+ function typesRuntime(names) {
51
+ const modules = [...new Set([...names].flatMap((name) => TYPES_RUNTIME[name] ?? []))].sort(compareCodeUnits);
52
+ return modules.flatMap((module) => importLine(`._http.${module}`, [...names].filter((name) => TYPES_RUNTIME[name] === module)));
53
+ }
38
54
  /** A docstring of `lines` at column 0: one line, or the first on the quotes and the closing quotes alone. */
39
55
  const docstring = (lines) => lines.length === 1 ? [`"""${lines[0]}"""`] : [`"""${lines[0]}`, ...lines.slice(1), '"""'];
40
56
  /** The blank lines before a module's `i`th declaration: one after the imports unless it is a class, else two. */
@@ -55,7 +71,7 @@ function componentDecls(ir, at) {
55
71
  });
56
72
  }
57
73
  /** The identifiers `text` spells outside its strings. */
58
- const spelled = (text) => new Set(Array.from(text.replace(/"""[\s\S]*?"""|"(?:[^"\\\n]|\\.)*"/g, '""').matchAll(/[A-Za-z_]\w*/g), (match) => match[0]));
74
+ const spelled = (text) => new Set(Array.from(text.replaceAll(/"""[\s\S]*?"""|"(?:[^"\\\n]|\\.)*"/g, '""').matchAll(/[A-Za-z_]\w*/g), (match) => match[0]));
59
75
  /** client.py: the marker, the API's doc, its imports, then its declarations. */
60
76
  function clientFile(ir, env, body) {
61
77
  const doc = pyDocLines([clientTitle(ir), ir.info.description].filter((part) => part !== undefined).join("\n\n"));
@@ -99,9 +115,9 @@ function emitPython(document, options, metadata = {}) {
99
115
  const ir = toIR(document, { deriveOperationIds: true });
100
116
  const model = sdkModel(ir);
101
117
  const at = pyTypeContext(ir);
102
- /* components first: the client's hoisted types then land beside them */
118
+ // components first: the client's hoisted types then land beside them
103
119
  const components = componentDecls(ir, at);
104
- /* before the client: its `_DEFAULTS` names ErrorKey, and each `<Key>Data` lands among the hoisted declarations */
120
+ // before the client: its `_DEFAULTS` names ErrorKey, and each `<Key>Data` lands among the hoisted declarations
105
121
  const errorKey = pythonErrorKeys(model, at);
106
122
  const features = {
107
123
  realtime: model.ops.some((op) => op.stream === "realtime"),
@@ -132,8 +148,12 @@ function emitPython(document, options, metadata = {}) {
132
148
  [`${root}/py.typed`]: "",
133
149
  [`${root}/types.py`]: pyFile([typesDoc[0]], [
134
150
  ["from __future__ import annotations"],
135
- [...(errorKey === null ? [] : ["from enum import StrEnum"]), ...importLine("typing", at.typing)],
136
- importLine("._http.body", env.typesImports),
151
+ [
152
+ ...importLine("collections.abc", [...env.typesImports].filter((name) => !(name in TYPES_RUNTIME))),
153
+ ...(errorKey === null ? [] : ["from enum import StrEnum"]),
154
+ ...importLine("typing", at.typing),
155
+ ],
156
+ typesRuntime(env.typesImports),
137
157
  ], decls.map(([, text]) => text)),
138
158
  ...Object.fromEntries(Object.entries(runtime).map(([name, source]) => [`${root}/_http/${name}`, source])),
139
159
  };
@@ -1,11 +1,4 @@
1
- /**
2
- * An SSE operation's answer (contract 34 §2.0–2.1): `EventStream[E]`, `E` the declared event schema's type (`str`
3
- * for untyped events), opened by awaiting the method (G15), and its `last_event_id` field, sent as Last-Event-ID
4
- * only when set and non-empty; a declared Last-Event-ID header param is folded into that field (Fd3).
5
- */
6
1
  import { type PyStream } from "./sdk-answer.ts";
7
- /** The header the SSE and realtime dials resume an event stream with. */
8
- export declare const LAST_EVENT_ID = "Last-Event-ID";
9
2
  /** Whether a declared param is the Last-Event-ID header (any casing), the resume channel an SSE dial sends. */
10
3
  export declare const isLastEventIdHeader: (name: string, where: string) => boolean;
11
4
  /** The SSE operation's answer, its one field and its docstring's lines. */
@@ -1,18 +1,48 @@
1
1
  /**
2
- * An SSE operation's answer (contract 34 §2.0–2.1): `EventStream[E]`, `E` the declared event schema's type (`str`
3
- * for untyped events), opened by awaiting the method (G15), and its `last_event_id` field, sent as Last-Event-ID
4
- * only when set and non-empty; a declared Last-Event-ID header param is folded into that field (Fd3).
2
+ * An SSE operation's answer (contract 34 §2.0–2.1): `EventStream[E]`, opened by awaiting the method (G15), and its
3
+ * `last_event_id` field, sent as Last-Event-ID only when set and non-empty; a declared Last-Event-ID header param is
4
+ * folded into that field (Fd3). An operation that names its events (D7) yields `<Op>Event`, a union of
5
+ * `SseEventOf[Literal[name], Data]` hoisted beside the types; any other yields `SseEvent[T]`, `T` its declared
6
+ * event schema's type (`str` for untyped events).
5
7
  */
8
+ import { sseEvents } from "../../ir/sdk-model.js";
9
+ import { pyClassName } from "../shared/lang.js";
6
10
  import { eventType } from "./sdk-answer.js";
11
+ import { aliasDecl } from "./types-union.js";
12
+ import { pyTypeOf } from "./types.js";
7
13
  /** The header the SSE and realtime dials resume an event stream with. */
8
- export const LAST_EVENT_ID = "Last-Event-ID";
14
+ const LAST_EVENT_ID = "Last-Event-ID";
9
15
  /** Whether a declared param is the Last-Event-ID header (any casing), the resume channel an SSE dial sends. */
10
16
  export const isLastEventIdHeader = (name, where) => where === "header" && name.toLowerCase() === LAST_EVENT_ID.toLowerCase();
17
+ /**
18
+ * The event type of an op that names its events: `<Op>Event`, each event's `data` typed at `<Op><Name>`, declared
19
+ * in types.py; null for an op that names none.
20
+ */
21
+ function namedEvents(op, env) {
22
+ const events = sseEvents(op.ir);
23
+ if (events === undefined)
24
+ return null;
25
+ const typing = env.at.declTyping;
26
+ const at = { ...env.at, parentName: op.id, typing };
27
+ const members = events.map(({ data, name }) => {
28
+ const literal = pyTypeOf({ kind: "const", value: name }, { ...at, fieldName: "" });
29
+ return `SseEventOf[${literal}, ${pyTypeOf(data, { ...at, fieldName: name })}]`;
30
+ });
31
+ const alias = env.at.names.claim(`${pyClassName(op.id)}Event`);
32
+ typing.add("TypeAlias");
33
+ env.typesImports.add("SseEventOf");
34
+ env.at.decls.set(alias, aliasDecl(alias, members.join(" | ")));
35
+ return alias;
36
+ }
11
37
  /** The SSE operation's answer, its one field and its docstring's lines. */
12
38
  export const sseStream = {
13
39
  answer: (op, env) => {
14
- const events = eventType(op, env, () => "str");
15
- return { returns: `EventStream[${events}]`, run: "sse", type: events };
40
+ const named = namedEvents(op, env);
41
+ if (named !== null)
42
+ return { returns: `EventStream[${named}]`, run: "sse", type: named };
43
+ env.imports.add("SseEvent");
44
+ const event = `SseEvent[${eventType(op, env, () => "str")}]`;
45
+ return { returns: `EventStream[${event}]`, run: "sse", type: event };
16
46
  },
17
47
  carries: isLastEventIdHeader,
18
48
  doc: [
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { readFileSync } from "node:fs";
8
8
  import { compareCodeUnits } from "../shared/lang.js";
9
- /* every SDK: the sans-IO core and its two shells, config, errors, hooks, log, redirects, SSE, invalidation */
9
+ // every SDK: the sans-IO core and its two shells, config, errors, hooks, log, redirects, SSE, invalidation
10
10
  const CORE = [
11
11
  "__init__",
12
12
  "auth",
@@ -28,12 +28,12 @@ const CORE = [
28
28
  "sse",
29
29
  "stale",
30
30
  ];
31
- /* a WebSocket operation; realtime adds the transports on top of it */
31
+ // a WebSocket operation; realtime adds the transports on top of it
32
32
  const WS = ["ws"];
33
33
  const REALTIME = ["realtime", "transport", "transport_longpoll", "transport_sse", "transport_ws"];
34
- /* a module's `__all__ = [...]`, one name per line or on one line */
34
+ // a module's `__all__ = [...]`, one name per line or on one line
35
35
  const ALL = /^__all__ = \[([^\]]*)\]/m;
36
- /* a top-level public name: `class X`, `def x`, `async def x`, `X =` or `X: T =` at column 0 */
36
+ // a top-level public name: `class X`, `def x`, `async def x`, `X =` or `X: T =` at column 0
37
37
  const PUBLIC_NAME = /^(?:class (?<cls>[A-Za-z]\w*)|(?:async )?def (?<fn>[A-Za-z]\w*)\(|(?<bound>[A-Za-z]\w*)(?:: [^=\n]+)? = )/gm;
38
38
  /** Whether these features make the package depend on `httpx2[ws]` (Fb3). */
39
39
  export const needsWebSocket = (features) => features.ws || features.realtime;
@@ -17,8 +17,8 @@ export type DictKey = {
17
17
  };
18
18
  /** How a dict is declared beyond its keys: its bases and its docstring. */
19
19
  export type DictShape = {
20
- readonly bases?: readonly string[];
21
- readonly doc?: string;
20
+ readonly bases?: readonly string[] | undefined;
21
+ readonly doc?: string | undefined;
22
22
  };
23
23
  /** The TypedDict `name` over `keys`: the class form when every key is spellable, else the functional form. */
24
24
  export declare function dictDecl(name: string, keys: readonly DictKey[], shape?: DictShape): string;
@@ -1,6 +1,6 @@
1
1
  import { lineComment, pyDocLines, pyString } from "../shared/escape.js";
2
2
  import { compareCodeUnits } from "../shared/lang.js";
3
- /* the hard keywords: no class body can spell one as a key */
3
+ // the hard keywords: no class body can spell one as a key
4
4
  const HARD_KEYWORDS = " False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield ";
5
5
  /** Whether a class body can spell `key` as it is. */
6
6
  const spellable = (key) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && !HARD_KEYWORDS.includes(` ${key} `) && !key.startsWith("__");
@@ -1,7 +1,7 @@
1
1
  import { irResolver } from "../../ir/schema.js";
2
2
  import { compareCodeUnits, NameScope, pyClassName } from "../shared/lang.js";
3
3
  import { publicNames, runtimeFiles } from "./transport.js";
4
- /* the names the emitted modules import or declare beside the runtime's */
4
+ // the names the emitted modules import or declare beside the runtime's
5
5
  const EMITTED = [
6
6
  "SDK",
7
7
  "AsyncSDK",
@@ -45,7 +45,7 @@ export function irNames(ir) {
45
45
  hoisted.set(key, name);
46
46
  return name;
47
47
  },
48
- /* only a declared component is referred to by name (types.ts reads a dangling ref as Any) */
48
+ // only a declared component is referred to by name (types.ts reads a dangling ref as Any)
49
49
  ref: (name) => components.get(name),
50
50
  resolve: irResolver(ir.schemas),
51
51
  };
@@ -12,7 +12,7 @@ export function valuePart(value) {
12
12
  const integral = typeof value === "number" && Number.isInteger(value);
13
13
  return integral ? { literal: BigInt(value).toString() } : { type: "float" };
14
14
  }
15
- /* where the Literal goes among a union's types: a string no type is spelled as */
15
+ // where the Literal goes among a union's types: a string no type is spelled as
16
16
  const LITERAL = "\u0000";
17
17
  /** `parts` as one annotation, and whether it spells `Literal`. */
18
18
  export function joined(parts) {
@@ -5,6 +5,7 @@
5
5
  * quoted string. Spec text reaches the source only through 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
  /** How component and hoisted names are claimed. */
9
10
  export type PyTypeNames = {
10
11
  /** the class name of the component `name` */
@@ -32,5 +33,11 @@ export type PyTypeContext = {
32
33
  export declare function pyTypeContext(ir?: IR): PyTypeContext;
33
34
  /** The Python type of `ir` in use position; what it hoists lands in `at.decls`. */
34
35
  export declare function pyTypeOf(ir: IRSchema, at: PyTypeContext): string;
36
+ /**
37
+ * Each member of the keyed union `ir` (a ref to it, or it written at `at`) as its value and the type its declaration
38
+ * names it by, in order: the names the union's own declaration spells, a ref's class or a hoisted
39
+ * `<Parent><Field><Const>`. Spelled in types.py, so what they hoist imports into `at.typing`.
40
+ */
41
+ export declare function pyKeyedMembers(ir: IRSchema, dispatch: Dispatch, at: PyTypeContext): (readonly [string, string])[];
35
42
  /** The declaration of `name` (a class name already) for `ir`, `doc` its description. */
36
43
  export declare function pyTopLevel(name: string, ir: IRSchema, at: PyTypeContext, doc?: string): string;
@@ -2,7 +2,7 @@ import { pascalWords, pyClassName } from "../shared/lang.js";
2
2
  import { dictDecl, dictParts, keysOf, mergedFields } from "./types-dict.js";
3
3
  import { irNames, plainNames } from "./types-names.js";
4
4
  import { aliasDecl, joined, valuePart, variantSuffix } from "./types-union.js";
5
- /* deeper than this, a schema is Any (Go and Rust parity; v0 Python stopped at 8) */
5
+ // deeper than this, a schema is Any (Go and Rust parity; v0 Python stopped at 8)
6
6
  const MAX_DEPTH = 12;
7
7
  const SCALARS = {
8
8
  boolean: "bool",
@@ -20,7 +20,7 @@ export function pyTypeContext(ir) {
20
20
  function declare(ir, at, key, base) {
21
21
  const name = at.names.hoist(key, base);
22
22
  if (!at.decls.has(name)) {
23
- /* claimed before its body: what the body hoists in turn comes after it */
23
+ // claimed before its body: what the body hoists in turn comes after it
24
24
  at.decls.set(name, "");
25
25
  at.decls.set(name, pyTopLevel(name, ir, { ...at, typing: at.declTyping }));
26
26
  }
@@ -72,9 +72,13 @@ function partsOf(ir, at) {
72
72
  return [...partsOf(ir.inner, deeper(at)), { type: "None" }];
73
73
  if (ir.kind !== "union")
74
74
  return [{ type: single(ir, at) }];
75
- return ir.variants.flatMap((variant, i) => variant.kind === "object" && variant.fields.length > 0
76
- ? [{ type: hoist(variant, deeper(at), variantSuffix(variant, i, ir.discriminator)) }]
77
- : partsOf(variant, deeper(at)));
75
+ return ir.variants.flatMap((variant, i) => variantParts(variant, i, ir, at));
76
+ }
77
+ /** The members variant `i` of `union` contributes: an inline object hoisted as `<Parent><Field><Const>`. */
78
+ function variantParts(variant, i, union, at) {
79
+ return variant.kind === "object" && variant.fields.length > 0
80
+ ? [{ type: hoist(variant, deeper(at), variantSuffix(variant, i, union.discriminator)) }]
81
+ : partsOf(variant, deeper(at));
78
82
  }
79
83
  /** A type that is never a union by itself. */
80
84
  function single(ir, at) {
@@ -86,7 +90,7 @@ function single(ir, at) {
86
90
  return objectUse(ir, at);
87
91
  if (ir.kind === "allOf")
88
92
  return allOfUse(ir, deeper(at));
89
- /* a ref to no component reads as any JSON value: the IR resolves it to unknown */
93
+ // a ref to no component reads as any JSON value: the IR resolves it to unknown
90
94
  if (ir.kind === "ref")
91
95
  return at.names.resolve(ir).kind === "unknown" ? "Any" : at.names.ref(ir.name);
92
96
  if (ir.kind === "scalar")
@@ -105,6 +109,19 @@ function use(ir, at) {
105
109
  export function pyTypeOf(ir, at) {
106
110
  return use(ir, { ...at, declTyping: at.declTyping ?? at.typing, depth: 0 });
107
111
  }
112
+ /**
113
+ * Each member of the keyed union `ir` (a ref to it, or it written at `at`) as its value and the type its declaration
114
+ * names it by, in order: the names the union's own declaration spells, a ref's class or a hoisted
115
+ * `<Parent><Field><Const>`. Spelled in types.py, so what they hoist imports into `at.typing`.
116
+ */
117
+ export function pyKeyedMembers(ir, dispatch, at) {
118
+ const base = { ...at, declTyping: at.typing, depth: 0 };
119
+ const where = ir.kind === "ref" ? { ...base, fieldName: "", parentName: at.names.ref(ir.name) } : base;
120
+ return dispatch.members.map(({ value, variant }, i) => [
121
+ value,
122
+ joined(variantParts(variant, i, dispatch.union, where)).text,
123
+ ]);
124
+ }
108
125
  /** The keys of the TypedDict `name` declares for `fields`, `NotRequired` noted when one is optional. */
109
126
  function dictKeys(name, fields, at) {
110
127
  const member = (schema, fieldName) => use(schema, { ...at, declTyping: at.declTyping ?? at.typing, depth: 0, fieldName, parentName: name });
@@ -1,14 +1,25 @@
1
- /**
2
- * A WebSocket operation's answer (contract 34 §2.0, §2.2): `TypedWebSocket`, opened by awaiting the method and
3
- * dialed offering `protocols`, its `reconnect_token` sent as one query param only when set and non-empty; a
4
- * declared `reconnect_token` query param is folded into that field (Fd3).
5
- */
6
- import type { PyStream } from "./sdk-answer.ts";
7
- /** The resume cursor's token, which the WebSocket and realtime methods take. */
8
- export declare const RECONNECT_TOKEN = "reconnect_token: str | None = None";
9
- /** The subprotocols a WebSocket or realtime dial offers. */
10
- export declare const PROTOCOLS = "protocols: Sequence[str] | None = None";
1
+ import { type SdkOp } from "../../ir/sdk-model.ts";
2
+ import { type Answer, type PyStream } from "./sdk-answer.ts";
3
+ import type { MethodEnv } from "./sdk-method.ts";
11
4
  /** Whether a declared param is the `reconnect_token` query param, the resume channel a socket dial sends. */
12
5
  export declare const isReconnectToken: (name: string, where: string) => boolean;
6
+ /** A socket class's `on` events beyond its members', given its `Out`: each with the type its handler takes. */
7
+ type Lifecycle = (out: string) => readonly (readonly [event: string, handler: string])[];
8
+ /**
9
+ * How a socket stream answers: its generic class `base[Out, In]` and the transport call it makes; what it reads and
10
+ * sends when its op declares no `send` or `receive`; the subclass suffix a keyed `send` union names; the events
11
+ * every `on` takes.
12
+ */
13
+ export type SocketShape = {
14
+ readonly base: string;
15
+ readonly run: string;
16
+ readonly out: () => string;
17
+ readonly in: string;
18
+ readonly suffix: string;
19
+ readonly lifecycle: Lifecycle;
20
+ };
21
+ /** A socket op's answer: its `<Op><suffix>` when its `send` union is keyed (D9), else `base[Out, In]`. */
22
+ export declare function socketAnswer(op: SdkOp, env: MethodEnv, shape: SocketShape): Answer;
13
23
  /** The WebSocket operation's answer, its two fields and its docstring's lines. */
14
24
  export declare const wsStream: PyStream;
25
+ export {};
@@ -1,12 +1,78 @@
1
+ import { dispatchOf } from "../../ir/sdk-model.js";
2
+ import { pyString } from "../shared/escape.js";
3
+ import { pyClassName } from "../shared/lang.js";
4
+ import { typeAt } from "./sdk-answer.js";
5
+ import { pyKeyedMembers, pyTypeOf } from "./types.js";
1
6
  /** The resume cursor's token, which the WebSocket and realtime methods take. */
2
- export const RECONNECT_TOKEN = "reconnect_token: str | None = None";
7
+ const RECONNECT_TOKEN = "reconnect_token: str | None = None";
3
8
  /** The subprotocols a WebSocket or realtime dial offers. */
4
- export const PROTOCOLS = "protocols: Sequence[str] | None = None";
9
+ const PROTOCOLS = "protocols: Sequence[str] | None = None";
5
10
  /** Whether a declared param is the `reconnect_token` query param, the resume channel a socket dial sends. */
6
11
  export const isReconnectToken = (name, where) => where === "query" && name === "reconnect_token";
12
+ /** One `on` overload: `event` hands its handler a `type`. */
13
+ const overload = ([event, type]) => [
14
+ " @overload",
15
+ ` def on(self, event: Literal[${pyString(event)}], handler: Callable[[${type}], None]) -> None: ...`,
16
+ "",
17
+ ];
18
+ /**
19
+ * `<Op><suffix>`, the subclass of `base[Out, In]` whose `on` takes each member of the keyed `send` union by its value
20
+ * (one a lifecycle event names excepted), then the lifecycle events, hoisted beside the types; null when no member is
21
+ * left to take.
22
+ */
23
+ function keyedClass(op, env, shape, dispatch) {
24
+ const { receive, send } = op.ir.messages;
25
+ const typing = env.at.declTyping;
26
+ const at = { ...env.at, fieldName: "Send", parentName: op.id, typing };
27
+ // spelled in types.py, whose typing names they then take: the same hoist keys, so the names client.py spells
28
+ const out = pyTypeOf(send, at);
29
+ const inType = receive === undefined ? shape.in : pyTypeOf(receive, { ...at, fieldName: "Receive" });
30
+ const lifecycle = shape.lifecycle(out);
31
+ const taken = new Set(lifecycle.map(([event]) => event));
32
+ const members = pyKeyedMembers(send, dispatch, at).filter(([value]) => !taken.has(value));
33
+ if (members.length === 0)
34
+ return null;
35
+ const name = env.at.names.claim(`${pyClassName(op.id)}${shape.suffix}`);
36
+ for (const used of ["Any", "Literal", "overload"])
37
+ typing.add(used);
38
+ env.typesImports.add("Callable").add(shape.base);
39
+ for (const [, type] of lifecycle)
40
+ if (type !== out)
41
+ env.typesImports.add(type);
42
+ env.at.decls.set(name, [
43
+ `class ${name}(${shape.base}[${pyString(out)}, ${pyString(inType)}]):`,
44
+ ...[...members, ...lifecycle].flatMap(overload),
45
+ " def on(self, event: str, handler: Callable[[Any], None]) -> None:",
46
+ " self.listen(event, handler)",
47
+ ].join("\n"));
48
+ return name;
49
+ }
50
+ /** A socket op's answer: its `<Op><suffix>` when its `send` union is keyed (D9), else `base[Out, In]`. */
51
+ export function socketAnswer(op, env, shape) {
52
+ const { receive, send } = op.ir.messages ?? {};
53
+ const dispatch = send === undefined ? undefined : dispatchOf(send, env.at.names.resolve);
54
+ const kind = dispatch === undefined ? null : keyedClass(op, env, shape, dispatch);
55
+ if (kind !== null)
56
+ return { kind, returns: kind, run: shape.run, type: kind };
57
+ const out = send === undefined ? shape.out() : typeAt(op, "Send", send, env);
58
+ const type = `${shape.base}[${out}, ${receive === undefined ? shape.in : typeAt(op, "Receive", receive, env)}]`;
59
+ return { returns: type, run: shape.run, type };
60
+ }
7
61
  /** The WebSocket operation's answer, its two fields and its docstring's lines. */
8
62
  export const wsStream = {
9
- answer: () => ({ returns: "TypedWebSocket", run: "websocket", type: "None" }),
63
+ answer: (op, env) => socketAnswer(op, env, {
64
+ base: "TypedWebSocket",
65
+ in: "object",
66
+ // the events every socket's `on` takes, with what each hands its handler
67
+ lifecycle: (out) => [
68
+ ["message", out],
69
+ ["close", "WsClose"],
70
+ ["error", "HttpError"],
71
+ ],
72
+ out: () => "str | bytes",
73
+ run: "websocket",
74
+ suffix: "Socket",
75
+ }),
10
76
  carries: isReconnectToken,
11
77
  doc: [
12
78
  'Opens the socket: a refused handshake raises its status\'s error; options["cancel"], close() or',
@@ -5,7 +5,7 @@ import { rustTopLevel } from "./types.js";
5
5
  /** The keys an error response's envelope names, over every operation's JSON error statuses (the runtime reads JSON only). */
6
6
  function envelopeKeys(model) {
7
7
  return model.ops.flatMap((op) => op.errorStatuses.flatMap((status) => {
8
- /* an error status is a declared response, and a schema comes with the content type it is under */
8
+ // an error status is a declared response, and a schema comes with the content type it is under
9
9
  const { contentType, schema } = op.ir.responses[String(status)];
10
10
  if (schema === undefined || !isJsonMedia(contentType))
11
11
  return [];
@@ -19,7 +19,7 @@ function envelopeKeys(model) {
19
19
  function declaredKeys(model) {
20
20
  const byId = [...model.ops].sort((a, b) => compareCodeUnits(a.id, b.id));
21
21
  const declared = byId.flatMap((op) => Object.entries(op.ir.extensions.errors ?? {}));
22
- /* reversed, so a key ends on its first declaration */
22
+ // reversed, so a key ends on its first declaration
23
23
  const keys = new Map(declared.toReversed().map(([key, { schema }]) => [key, schema]));
24
24
  for (const key of envelopeKeys(model))
25
25
  if (!keys.has(key))
@@ -77,7 +77,7 @@ function fromLines(keys) {
77
77
  ];
78
78
  return ["impl From<&str> for ErrorKey {", " fn from(key: &str) -> Self {", ...parse, " }", "}"];
79
79
  }
80
- /* Display as the wire spells it, and ApiError::key() over the runtime's raw key */
80
+ // Display as the wire spells it, and ApiError::key() over the runtime's raw key
81
81
  const TAIL = [
82
82
  "impl std::fmt::Display for ErrorKey {",
83
83
  " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {",
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { readFileSync } from "node:fs";
8
8
  import { compareCodeUnits } from "../shared/lang.js";
9
- /* every SDK: config, the call, its request and exchange, redirects, auth, hooks, log, errors and their envelope, answers, SSE, invalidation */
9
+ // every SDK: config, the call, its request and exchange, redirects, auth, hooks, log, errors and their envelope, answers, SSE, invalidation
10
10
  const CORE = [
11
11
  "answer",
12
12
  "auth",
@@ -29,7 +29,7 @@ const CORE = [
29
29
  "sse",
30
30
  "stale",
31
31
  ];
32
- /* a WebSocket operation; realtime adds the transports on top of it */
32
+ // a WebSocket operation; realtime adds the transports on top of it
33
33
  const WS = ["ws"];
34
34
  const REALTIME = [
35
35
  "realtime",
@@ -39,9 +39,9 @@ const REALTIME = [
39
39
  "transport_sse",
40
40
  "transport_ws",
41
41
  ];
42
- /* the lock template every crate's Cargo.lock is cut from */
42
+ // the lock template every crate's Cargo.lock is cut from
43
43
  const LOCK = "Cargo.lock";
44
- /* a top-level public item: `pub struct Name`, `pub fn name`, … at column 0 */
44
+ // a top-level public item: `pub struct Name`, `pub fn name`, … at column 0
45
45
  const PUBLIC_ITEM = /^pub (?:struct|enum|trait|type|fn|const|static) ([A-Za-z_][A-Za-z0-9_]*)/gm;
46
46
  /** The runtime `.rs` file names an SDK with `features` ships, in code-unit order. */
47
47
  export function runtimeFileNames(features) {
@@ -1,11 +1,13 @@
1
1
  /**
2
- * A realtime operation's answer (contract 20 §2.0, §2.3): `ResumableConnection<E>`, `E` the declared event
3
- * schema's type (`serde_json::Value` for a string or absent one), opened before the call resolves over
4
- * WebSocket, else SSE, else long-poll. Its Opts carry the resume cursor, the offered subprotocols and the
5
- * reconnect policy as the `TransportOpts` of their names; a declared param on a resume channel is folded in.
2
+ * A realtime operation's answer (contract 20 §2.0, §2.3): `ResumableConnection<In, Out>`, opened before the call
3
+ * resolves over WebSocket, else SSE, else long-poll. `In` is what the server sends (`send`), else the declared event
4
+ * schema's type, `Out` what it receives (`receive`), an inline union hoisted as `<Op>Send` or `<Op>Receive`; an op
5
+ * without them keeps the defaults, `serde_json::Value` read from JSON else text. A read side keyed on one field (D9)
6
+ * gets an `on_<value>` per member but `message`. Its Opts carry the resume cursor, the offered subprotocols and the
7
+ * reconnect policy as one `transport: TransportOpts`; a declared param on a resume channel is folded into it.
6
8
  */
7
9
  import type { SdkOp } from "../../ir/sdk-model.ts";
8
10
  import type { StreamAnswer } from "./sdk-opts.ts";
9
11
  import type { RustTypeContext } from "./types.ts";
10
- /** The realtime operation `op`'s answer. */
12
+ /** The realtime operation `op`'s answer, its message types hoisted into `at`. */
11
13
  export declare function realtimeAnswer(op: SdkOp, at: RustTypeContext): StreamAnswer;
@@ -1,29 +1,26 @@
1
- import { eventType, isLastEventIdHeader, LAST_EVENT_ID } from "./sse.js";
2
- import { isReconnectToken, PROTOCOLS, RECONNECT_TOKEN } from "./ws.js";
3
- /* the WebSocket and long-poll dials send the cursor as query params, the SSE dial its id as Last-Event-ID */
1
+ import { eventType, isLastEventIdHeader } from "./sse.js";
2
+ import { isReconnectToken, messageType, typeParams, valueHandlers } from "./ws.js";
3
+ // the WebSocket and long-poll dials send the cursor as query params, the SSE dial its id as Last-Event-ID
4
4
  const REALTIME = {
5
5
  carries: (param, where) => isReconnectToken(param, where) ||
6
6
  (where === "query" && param === "last_event_id") ||
7
7
  isLastEventIdHeader(param, where),
8
8
  fields: [
9
- LAST_EVENT_ID,
10
- RECONNECT_TOKEN,
11
- PROTOCOLS,
12
- { doc: "Reconnects after a drop; 5 when None.", ident: "max_reconnect_attempts", type: "Option<u32>" },
13
- {
14
- doc: "The first backoff delay in milliseconds; 1000 when None.",
15
- ident: "reconnect_delay_ms",
16
- type: "Option<u64>",
17
- },
9
+ { doc: "The resume cursor, offered subprotocols and reconnect policy.", ident: "transport", type: "TransportOpts" },
18
10
  ],
19
11
  sends: [],
20
12
  };
21
- /* the realtime Opts' own fields, each the TransportOpts field of its name */
22
- const TRANSPORT_OPTS = "TransportOpts { last_event_id: opts.last_event_id.clone(), reconnect_token: opts.reconnect_token.clone(), protocols: opts.protocols.clone(), max_reconnect_attempts: opts.max_reconnect_attempts, reconnect_delay_ms: opts.reconnect_delay_ms }";
23
13
  const DOC = "Resolves once the connection is open over WebSocket, else SSE, else long-poll; `recv` reconnects after a drop and resumes after the last message it delivered. `cancel_on` ends it quietly; dropping it closes it.";
24
- /** The realtime operation `op`'s answer. */
14
+ /** The realtime operation `op`'s answer, its message types hoisted into `at`. */
25
15
  export function realtimeAnswer(op, at) {
26
- const events = eventType(op, at, "serde_json::Value");
27
- const run = `crate::realtime_loop::connect::<${events}>(${TRANSPORT_OPTS})`;
28
- return { doc: DOC, run, stream: REALTIME, type: `ResumableConnection<${events}>` };
16
+ const { receive, send } = op.ir.messages ?? {};
17
+ const read = send && messageType(op, send, "Send", at);
18
+ const write = receive && messageType(op, receive, "Receive", at);
19
+ if (send !== undefined && read !== undefined)
20
+ valueHandlers("ResumableConnection", ["on_message"], { schema: send, type: read }, at);
21
+ // declared messages are JSON: one that is not is an error; an event type or none reads text too
22
+ const loop = read === undefined && write === undefined ? "connect" : "typed";
23
+ const params = typeParams(read ?? (op.events === undefined ? undefined : eventType(op, op.events, at)), write, "serde_json::Value");
24
+ const run = `crate::realtime_loop::${loop}(opts.transport.clone())`;
25
+ return { doc: DOC, run, stream: REALTIME, type: `ResumableConnection${params}` };
29
26
  }
@@ -6,14 +6,13 @@ import { rustTypeOf } from "./types.js";
6
6
  export const typeAt = (schema, parent, field, at) => unboxed(schema, rustTypeOf(schema, { ...at, fieldName: field, parentName: parent }));
7
7
  /** The field of `part` named `ident` on the struct `parent`: its type by the part's kind, and its statement. */
8
8
  function partField(part, ident, parent, at) {
9
- /* the IR gives every part its schema (ir/slots.ts partsOf) */
9
+ // the IR gives every part its schema (ir/slots.ts partsOf)
10
10
  const declared = part.schema;
11
11
  const schema = at.names.resolve(declared);
12
12
  const call = part.type === "file" ? "files" : "text";
13
13
  const line = `form.${call}(${rustString(part.name)}, &body.${ident});`;
14
- if (part.type === "file") {
14
+ if (part.type === "file")
15
15
  return { decl: schema.kind === "array" ? "Vec<crate::FilePart>" : "Option<crate::FilePart>", line };
16
- }
17
16
  if (schema.kind === "array")
18
17
  return { decl: `Vec<${typeAt(schema.items, parent, part.name, at)}>`, line };
19
18
  return { decl: `Option<${typeAt(declared, parent, part.name, at)}>`, line };
@@ -28,7 +27,7 @@ function multipartBody(op, parts, at) {
28
27
  return { ident, ...partField(part, ident, type, at) };
29
28
  });
30
29
  const doc = `The multipart/form-data parts of ${op.id}'s body: None and an empty list send no part.`;
31
- /* never empty: a body is multipart only with a file part (ir/slots.ts bodyOf) */
30
+ // never empty: a body is multipart only with a file part (ir/slots.ts bodyOf)
32
31
  const decl = [
33
32
  ...lineComment(doc, "///"),
34
33
  "#[derive(Debug, Clone, Default)]",
@@ -37,7 +36,11 @@ function multipartBody(op, parts, at) {
37
36
  "}",
38
37
  ];
39
38
  at.decls.set(type, decl.join("\n"));
40
- const lines = ["let mut form = crate::body::Multipart::new();", ...fields.map((f) => f.line), "spec.multipart(form);"];
39
+ const lines = [
40
+ "let mut form = crate::body::Multipart::new();",
41
+ ...fields.map((f) => f.line),
42
+ "spec.multipart(form);",
43
+ ];
41
44
  return { lines, type: `&${type}` };
42
45
  }
43
46
  /** The body of `op` as its method takes it, and the statements encoding it into the spec at once. */