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

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 (375) hide show
  1. package/README.md +548 -35
  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 +88 -68
  6. package/bin/installgen.js +18 -13
  7. package/dist/cli.d.ts +4 -4
  8. package/dist/cli.js +20 -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 +14 -8
  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 +11 -5
  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 +3 -3
  26. package/dist/emit/csharp/errors.js +4 -4
  27. package/dist/emit/csharp/json.js +8 -8
  28. package/dist/emit/csharp/realtime.js +3 -3
  29. package/dist/emit/csharp/sdk-answer.js +4 -4
  30. package/dist/emit/csharp/sdk-body.js +8 -6
  31. package/dist/emit/csharp/sdk-client.d.ts +3 -3
  32. package/dist/emit/csharp/sdk-client.js +2 -2
  33. package/dist/emit/csharp/sdk-csproj.d.ts +7 -9
  34. package/dist/emit/csharp/sdk-csproj.js +10 -10
  35. package/dist/emit/csharp/sdk-doc.js +1 -1
  36. package/dist/emit/csharp/sdk-method.d.ts +18 -2
  37. package/dist/emit/csharp/sdk-method.js +24 -9
  38. package/dist/emit/csharp/sdk-plan.js +0 -1
  39. package/dist/emit/csharp/sdk.js +7 -4
  40. package/dist/emit/csharp/sse.d.ts +0 -2
  41. package/dist/emit/csharp/sse.js +7 -7
  42. package/dist/emit/csharp/transport.js +7 -7
  43. package/dist/emit/csharp/types-enum.js +3 -1
  44. package/dist/emit/csharp/types-messages.js +3 -3
  45. package/dist/emit/csharp/types-names.js +10 -12
  46. package/dist/emit/csharp/types-record.js +3 -3
  47. package/dist/emit/csharp/types-union.d.ts +1 -1
  48. package/dist/emit/csharp/types.d.ts +0 -1
  49. package/dist/emit/csharp/types.js +3 -3
  50. package/dist/emit/csharp/ws.js +2 -2
  51. package/dist/emit/go/errors.js +1 -1
  52. package/dist/emit/go/http.js +2 -2
  53. package/dist/emit/go/module-path.js +2 -2
  54. package/dist/emit/go/sdk-answer.js +1 -1
  55. package/dist/emit/go/sdk-body.js +11 -7
  56. package/dist/emit/go/sdk-client.js +1 -1
  57. package/dist/emit/go/sdk-method.d.ts +9 -0
  58. package/dist/emit/go/sdk-method.js +12 -3
  59. package/dist/emit/go/sdk-mirror.js +2 -2
  60. package/dist/emit/go/sdk-opts.d.ts +0 -2
  61. package/dist/emit/go/sdk-opts.js +3 -3
  62. package/dist/emit/go/sdk.d.ts +1 -1
  63. package/dist/emit/go/sdk.js +12 -11
  64. package/dist/emit/go/sse.js +1 -1
  65. package/dist/emit/go/types-names.js +5 -0
  66. package/dist/emit/go/types-struct.d.ts +2 -1
  67. package/dist/emit/go/types-struct.js +1 -1
  68. package/dist/emit/go/types.js +9 -9
  69. package/dist/emit/go/ws.js +6 -6
  70. package/dist/emit/java/gradle.d.ts +7 -9
  71. package/dist/emit/java/gradle.js +8 -8
  72. package/dist/emit/java/json.js +1 -1
  73. package/dist/emit/java/layout-ast.js +1 -1
  74. package/dist/emit/java/layout-decl.js +5 -4
  75. package/dist/emit/java/layout-doc.js +13 -7
  76. package/dist/emit/java/layout-dot.js +1 -1
  77. package/dist/emit/java/layout-strings.js +4 -5
  78. package/dist/emit/java/layout-types.js +7 -5
  79. package/dist/emit/java/layout-visitor.js +4 -3
  80. package/dist/emit/java/layout.js +5 -4
  81. package/dist/emit/java/models-names.js +5 -4
  82. package/dist/emit/java/models-record.d.ts +0 -1
  83. package/dist/emit/java/models-record.js +3 -3
  84. package/dist/emit/java/models-union.d.ts +1 -1
  85. package/dist/emit/java/models-union.js +1 -1
  86. package/dist/emit/java/models.d.ts +1 -2
  87. package/dist/emit/java/models.js +25 -16
  88. package/dist/emit/java/realtime.d.ts +5 -17
  89. package/dist/emit/java/realtime.js +1 -1
  90. package/dist/emit/java/sdk-client.d.ts +6 -6
  91. package/dist/emit/java/sdk-client.js +2 -1
  92. package/dist/emit/java/sdk-decl.js +2 -2
  93. package/dist/emit/java/sdk-errors.js +1 -1
  94. package/dist/emit/java/sdk-headers.js +2 -2
  95. package/dist/emit/java/sdk-mirror.js +2 -2
  96. package/dist/emit/java/sdk-models.d.ts +1 -1
  97. package/dist/emit/java/sdk-models.js +7 -7
  98. package/dist/emit/java/sdk-op.d.ts +7 -11
  99. package/dist/emit/java/sdk-op.js +22 -10
  100. package/dist/emit/java/sdk-params.d.ts +5 -5
  101. package/dist/emit/java/sdk-params.js +3 -2
  102. package/dist/emit/java/sdk-plan.js +0 -1
  103. package/dist/emit/java/sdk.d.ts +1 -1
  104. package/dist/emit/java/sdk.js +21 -14
  105. package/dist/emit/java/sse.d.ts +2 -4
  106. package/dist/emit/java/sse.js +6 -6
  107. package/dist/emit/java/ws.d.ts +2 -2
  108. package/dist/emit/java/ws.js +3 -4
  109. package/dist/emit/mcp/annotations.js +8 -4
  110. package/dist/emit/mcp/files.js +9 -9
  111. package/dist/emit/mcp/mounted.js +2 -2
  112. package/dist/emit/mcp/output-schema.js +3 -3
  113. package/dist/emit/mcp/registry.d.ts +0 -2
  114. package/dist/emit/mcp/registry.js +5 -4
  115. package/dist/emit/mcp/runtime.js +2 -2
  116. package/dist/emit/mcp/schema.js +22 -11
  117. package/dist/emit/mcp/server.d.ts +7 -7
  118. package/dist/emit/mcp/server.js +7 -6
  119. package/dist/emit/mcp/tools.js +7 -6
  120. package/dist/emit/python/errors.js +3 -3
  121. package/dist/emit/python/realtime.js +2 -2
  122. package/dist/emit/python/sdk-answer.d.ts +3 -7
  123. package/dist/emit/python/sdk-answer.js +2 -2
  124. package/dist/emit/python/sdk-body.js +4 -5
  125. package/dist/emit/python/sdk-client.js +5 -5
  126. package/dist/emit/python/sdk-doc.js +2 -2
  127. package/dist/emit/python/sdk-method.d.ts +11 -0
  128. package/dist/emit/python/sdk-method.js +20 -5
  129. package/dist/emit/python/sdk-plan.js +0 -1
  130. package/dist/emit/python/sdk-pyproject.d.ts +0 -2
  131. package/dist/emit/python/sdk-pyproject.js +8 -8
  132. package/dist/emit/python/sdk.d.ts +1 -1
  133. package/dist/emit/python/sdk.js +12 -8
  134. package/dist/emit/python/sse.d.ts +0 -2
  135. package/dist/emit/python/sse.js +2 -2
  136. package/dist/emit/python/transport.js +4 -4
  137. package/dist/emit/python/types-dict.d.ts +2 -2
  138. package/dist/emit/python/types-dict.js +1 -1
  139. package/dist/emit/python/types-names.js +2 -2
  140. package/dist/emit/python/types-union.js +1 -1
  141. package/dist/emit/python/types.js +3 -3
  142. package/dist/emit/python/ws.d.ts +2 -5
  143. package/dist/emit/python/ws.js +4 -4
  144. package/dist/emit/rust/errors.js +3 -3
  145. package/dist/emit/rust/http.js +4 -4
  146. package/dist/emit/rust/realtime.js +2 -2
  147. package/dist/emit/rust/sdk-body.js +8 -5
  148. package/dist/emit/rust/sdk-cargo.d.ts +16 -18
  149. package/dist/emit/rust/sdk-cargo.js +12 -12
  150. package/dist/emit/rust/sdk-client.d.ts +1 -1
  151. package/dist/emit/rust/sdk-client.js +3 -3
  152. package/dist/emit/rust/sdk-method.d.ts +12 -1
  153. package/dist/emit/rust/sdk-method.js +12 -4
  154. package/dist/emit/rust/sdk-opts.d.ts +2 -1
  155. package/dist/emit/rust/sdk-opts.js +2 -2
  156. package/dist/emit/rust/sdk-plan.js +0 -1
  157. package/dist/emit/rust/sdk.d.ts +1 -1
  158. package/dist/emit/rust/sdk.js +9 -6
  159. package/dist/emit/rust/sse.d.ts +0 -5
  160. package/dist/emit/rust/sse.js +2 -2
  161. package/dist/emit/rust/types-names.js +3 -3
  162. package/dist/emit/rust/types-struct.js +1 -1
  163. package/dist/emit/rust/types-union.d.ts +1 -1
  164. package/dist/emit/rust/types.js +7 -5
  165. package/dist/emit/rust/ws.d.ts +0 -11
  166. package/dist/emit/rust/ws.js +5 -5
  167. package/dist/emit/shared/escape.js +17 -17
  168. package/dist/emit/shared/format.js +1 -1
  169. package/dist/emit/shared/gofmt.js +1 -1
  170. package/dist/emit/shared/lang.js +10 -10
  171. package/dist/emit/shared/literals.d.ts +5 -0
  172. package/dist/emit/shared/literals.js +8 -0
  173. package/dist/emit/shared/metadata.d.ts +0 -6
  174. package/dist/emit/shared/metadata.js +8 -7
  175. package/dist/emit/shared/ruff.js +1 -1
  176. package/dist/emit/shared/rustfmt.js +1 -1
  177. package/dist/emit/shared/type-emitter.js +37 -20
  178. package/dist/emit/shared/unknown-type.constants.d.ts +2 -0
  179. package/dist/emit/shared/unknown-type.constants.js +2 -0
  180. package/dist/emit/ts/http.d.ts +8 -2
  181. package/dist/emit/ts/http.js +51 -6
  182. package/dist/emit/ts/package.d.ts +14 -12
  183. package/dist/emit/ts/package.js +10 -8
  184. package/dist/emit/ts/route-tree.js +2 -2
  185. package/dist/emit/ts/sdk-types-preamble.d.ts +1 -1
  186. package/dist/emit/ts/sdk-types-preamble.js +12 -4
  187. package/dist/emit/ts/sdk-types.d.ts +0 -5
  188. package/dist/emit/ts/sdk-types.js +63 -19
  189. package/dist/emit/ts/sdk.d.ts +3 -1
  190. package/dist/emit/ts/sdk.js +44 -12
  191. package/dist/emit/ts/service-map.d.ts +7 -1
  192. package/dist/emit/ts/service-map.js +10 -1
  193. package/dist/emit/ts/single-flight-text.d.ts +3 -0
  194. package/dist/emit/ts/single-flight-text.js +38 -0
  195. package/dist/emit/ts/tanstack-query.d.ts +3 -2
  196. package/dist/emit/ts/tanstack-query.js +60 -35
  197. package/dist/emit/ts/type-gen.js +31 -18
  198. package/dist/emit/ts/webhooks.d.ts +0 -2
  199. package/dist/emit/ts/webhooks.js +3 -3
  200. package/dist/extract/chain.js +5 -4
  201. package/dist/extract/extract.js +5 -5
  202. package/dist/extract/serialize.d.ts +0 -2
  203. package/dist/extract/serialize.js +14 -15
  204. package/dist/extract/walk.js +15 -12
  205. package/dist/gen/args.js +9 -5
  206. package/dist/gen/formatters.js +5 -3
  207. package/dist/gen/process.js +2 -1
  208. package/dist/gen/shipped.js +2 -2
  209. package/dist/gen/switch-on.constants.d.ts +2 -0
  210. package/dist/gen/switch-on.constants.js +2 -0
  211. package/dist/gen/targets.d.ts +6 -7
  212. package/dist/gen/targets.js +11 -6
  213. package/dist/gen/write.js +4 -2
  214. package/dist/index.js +2 -2
  215. package/dist/installers/cli.d.ts +4 -4
  216. package/dist/installers/cli.js +24 -24
  217. package/dist/installers/commands/build.d.ts +4 -4
  218. package/dist/installers/commands/build.js +2 -3
  219. package/dist/installers/commands/check.d.ts +2 -2
  220. package/dist/installers/commands/check.js +11 -10
  221. package/dist/installers/commands/init.d.ts +2 -2
  222. package/dist/installers/commands/init.js +1 -2
  223. package/dist/installers/config/define-config.d.ts +16 -16
  224. package/dist/installers/config/define-config.js +1 -1
  225. package/dist/installers/config/hooks/bun.d.ts +6 -6
  226. package/dist/installers/config/hooks/node.js +1 -1
  227. package/dist/installers/config/load.d.ts +6 -8
  228. package/dist/installers/config/load.js +7 -8
  229. package/dist/installers/config/resolve.d.ts +1 -2
  230. package/dist/installers/config/resolve.js +28 -33
  231. package/dist/installers/config/types.d.ts +6 -6
  232. package/dist/installers/config/types.js +0 -1
  233. package/dist/installers/render/quote.js +3 -5
  234. package/dist/installers/render/render.d.ts +6 -6
  235. package/dist/installers/render/render.js +26 -26
  236. package/dist/installers/ui.d.ts +4 -4
  237. package/dist/installers/ui.js +3 -3
  238. package/dist/ir/build.d.ts +3 -3
  239. package/dist/ir/build.js +8 -5
  240. package/dist/ir/invalidate-reads.d.ts +17 -0
  241. package/dist/ir/invalidate-reads.js +104 -0
  242. package/dist/ir/load.d.ts +10 -0
  243. package/dist/ir/load.js +65 -18
  244. package/dist/ir/model.d.ts +2 -1
  245. package/dist/ir/model.js +0 -1
  246. package/dist/ir/read-method.constants.d.ts +2 -0
  247. package/dist/ir/read-method.constants.js +2 -0
  248. package/dist/ir/resolve-refs.js +2 -2
  249. package/dist/ir/resource-tree.js +2 -1
  250. package/dist/ir/route-tree-intern.js +1 -1
  251. package/dist/ir/schema.js +3 -3
  252. package/dist/ir/sdk-model.js +3 -3
  253. package/dist/ir/slots.js +13 -8
  254. package/dist/ir/streams.js +1 -1
  255. package/dist/release/bootstrap.d.ts +3 -3
  256. package/dist/release/bootstrap.js +7 -7
  257. package/dist/release/bump-args.js +4 -4
  258. package/dist/release/bump-command.d.ts +1 -1
  259. package/dist/release/bump-command.js +9 -10
  260. package/dist/release/bump.d.ts +5 -4
  261. package/dist/release/bump.js +2 -2
  262. package/dist/release/cli.d.ts +4 -4
  263. package/dist/release/cli.js +4 -4
  264. package/dist/release/codegen.js +1 -1
  265. package/dist/release/digest.js +5 -7
  266. package/dist/release/git.js +5 -8
  267. package/dist/release/load.js +4 -4
  268. package/dist/release/manifest.js +9 -10
  269. package/dist/release/oasdiff.d.ts +10 -15
  270. package/dist/release/oasdiff.js +5 -6
  271. package/dist/release/registries.d.ts +0 -11
  272. package/dist/release/registries.js +17 -17
  273. package/dist/release/release-state.d.ts +16 -13
  274. package/dist/release/release-workflow.js +5 -7
  275. package/dist/release/repo-settings.d.ts +2 -1
  276. package/dist/release/spec-gate.d.ts +0 -2
  277. package/dist/release/spec-gate.js +6 -10
  278. package/dist/release/sync-command.d.ts +2 -2
  279. package/dist/release/sync-command.js +1 -1
  280. package/dist/release/sync-tree.js +9 -13
  281. package/dist/release/sync.d.ts +6 -6
  282. package/dist/release/sync.js +12 -13
  283. package/dist/release/types.d.ts +22 -22
  284. package/dist/release/types.js +0 -1
  285. package/dist/release/version-files.d.ts +3 -4
  286. package/dist/release/version-files.js +4 -5
  287. package/dist/runtime/.oxfmtrc.jsonc +8 -0
  288. package/dist/runtime/csharp/Config.cs +9 -1
  289. package/dist/runtime/csharp/Exchange.cs +56 -4
  290. package/dist/runtime/csharp/Hooks.cs +9 -0
  291. package/dist/runtime/csharp/Operation.cs +6 -1
  292. package/dist/runtime/csharp/WsDial.cs +3 -1
  293. package/dist/runtime/go/config.go +5 -0
  294. package/dist/runtime/go/hooks.go +70 -0
  295. package/dist/runtime/go/request.go +6 -2
  296. package/dist/runtime/go/stream.go +4 -1
  297. package/dist/runtime/go/ws.go +3 -1
  298. package/dist/runtime/java/ClientConfig.java +11 -0
  299. package/dist/runtime/java/Flight.java +2 -12
  300. package/dist/runtime/java/Hooks.java +45 -0
  301. package/dist/runtime/java/InvalidateEvent.java +10 -0
  302. package/dist/runtime/java/InvalidateHook.java +12 -0
  303. package/dist/runtime/java/InvalidateTarget.java +7 -0
  304. package/dist/runtime/java/Operation.java +23 -3
  305. package/dist/runtime/java/Realtime.java +3 -1
  306. package/dist/runtime/java/WsDial.java +3 -0
  307. package/dist/runtime/mcp/files.ts +1 -1
  308. package/dist/runtime/mcp/http.ts +6 -2
  309. package/dist/runtime/mcp/listen.ts +1 -1
  310. package/dist/runtime/mcp/mount.ts +2 -2
  311. package/dist/runtime/mcp/protocol.ts +1 -1
  312. package/dist/runtime/python/config.py +8 -2
  313. package/dist/runtime/python/exchange.py +3 -1
  314. package/dist/runtime/python/hooks.py +110 -5
  315. package/dist/runtime/python/operation.py +2 -0
  316. package/dist/runtime/python/send_async.py +14 -2
  317. package/dist/runtime/python/send_sync.py +4 -2
  318. package/dist/runtime/python/ws.py +5 -1
  319. package/dist/runtime/rust/config.rs +6 -1
  320. package/dist/runtime/rust/exchange.rs +15 -3
  321. package/dist/runtime/rust/hooks.rs +127 -2
  322. package/dist/runtime/rust/log.rs +11 -3
  323. package/dist/runtime/rust/request.rs +17 -0
  324. package/dist/runtime/rust/ws.rs +9 -1
  325. package/dist/runtime/ts/config.ts +69 -0
  326. package/dist/runtime/ts/http.ts +12 -10
  327. package/dist/runtime/ts/request.ts +2 -0
  328. package/dist/runtime/ts/response.ts +7 -0
  329. package/dist/runtime/ts/sdk-invalidate.ts +82 -0
  330. package/dist/runtime/ts/sdk-single-flight.constants.ts +25 -0
  331. package/dist/runtime/ts/sdk-single-flight.ts +203 -0
  332. package/dist/runtime/ts/sdk-sse.ts +5 -1
  333. package/dist/runtime/ts/sdk-ws.ts +9 -3
  334. package/dist/runtime/ts/sdk.ts +55 -31
  335. package/dist/runtime/ts/single-flight-batch.ts +184 -0
  336. package/dist/runtime/ts/single-flight-body.ts +59 -0
  337. package/dist/runtime/ts/single-flight-run.ts +160 -0
  338. package/dist/runtime/ts/single-flight.constants.ts +31 -0
  339. package/dist/runtime/ts/single-flight.ts +158 -0
  340. package/dist/runtime/ts-tanstack-query/invalidate.ts +96 -92
  341. package/dist/runtime/ts-tanstack-query/query.ts +140 -170
  342. package/package.json +12 -17
  343. package/references/INDEX.md +31 -0
  344. package/references/cli.md +33 -0
  345. package/references/configuring.md +29 -0
  346. package/references/documentation.md +15 -0
  347. package/references/errors.md +23 -0
  348. package/references/flags.md +104 -0
  349. package/references/gates.md +46 -0
  350. package/references/generate.md +29 -0
  351. package/references/install-scripts.md +28 -0
  352. package/references/install.md +38 -0
  353. package/references/license.md +8 -0
  354. package/references/mcp.md +76 -0
  355. package/references/output.md +45 -0
  356. package/references/overview.md +14 -0
  357. package/references/release-tooling.md +34 -0
  358. package/references/release.md +305 -0
  359. package/references/sdks.md +393 -0
  360. package/references/start.md +22 -0
  361. package/references/tdd.md +16 -0
  362. package/dist/emit/cli/index.d.ts +0 -1
  363. package/dist/emit/cli/index.js +0 -1
  364. package/dist/emit/csharp/index.d.ts +0 -1
  365. package/dist/emit/csharp/index.js +0 -1
  366. package/dist/emit/go/index.d.ts +0 -1
  367. package/dist/emit/go/index.js +0 -1
  368. package/dist/emit/java/index.d.ts +0 -2
  369. package/dist/emit/java/index.js +0 -2
  370. package/dist/emit/mcp/index.d.ts +0 -3
  371. package/dist/emit/mcp/index.js +0 -3
  372. package/dist/emit/python/index.d.ts +0 -1
  373. package/dist/emit/python/index.js +0 -1
  374. package/dist/emit/rust/index.d.ts +0 -1
  375. package/dist/emit/rust/index.js +0 -1
@@ -11,6 +11,8 @@ export const RESERVED = [
11
11
  "HttpSafe",
12
12
  "HttpStream",
13
13
  "HttpOptions",
14
+ "InvalidateEvent",
15
+ "InvalidateTarget",
14
16
  "Omit",
15
17
  "Promise",
16
18
  "ReadableStream",
@@ -23,6 +25,7 @@ export const RESERVED = [
23
25
  "SDKConfig",
24
26
  "SSEEvent",
25
27
  "SSEEventOf",
28
+ "SingleFlightConfig",
26
29
  "SseOptions",
27
30
  "TypedWebSocket",
28
31
  "Uint8Array",
@@ -31,12 +34,15 @@ export const RESERVED = [
31
34
  ];
32
35
  /** What the types file may import from the runtime module, in the order the import lists them. */
33
36
  const RUNTIME_TYPES = [
37
+ "InvalidateEvent",
38
+ "InvalidateTarget",
34
39
  "RealtimeOptions",
35
40
  "Result",
36
41
  "ResumableConnection",
37
42
  "SDKConfig",
38
43
  "SSEEvent",
39
44
  "SSEEventOf",
45
+ "SingleFlightConfig",
40
46
  "TypedWebSocket",
41
47
  "WsFrame",
42
48
  ];
@@ -47,12 +53,13 @@ const OPTIONS = `export type HttpOptions = {
47
53
  headers?: Record<string, string>
48
54
  idempotencyKey?: string
49
55
  signal?: AbortSignal
56
+ singleFlight?: boolean
50
57
  timeout?: number
51
58
  }
52
- export type SseOptions = Omit<HttpOptions, "idempotencyKey"> & { lastEventId?: string }
59
+ export type SseOptions = Omit<HttpOptions, "idempotencyKey" | "singleFlight"> & { lastEventId?: string }
53
60
  export type WsOptions = { protocols?: string | string[]; reconnectToken?: string }
54
61
  `;
55
- /* the error envelope, the call and stream shapes, and the safe mirror's opening */
62
+ // the error envelope, the call and stream shapes, and the safe mirror's opening
56
63
  const CALLS = `
57
64
  type ErrorField = { error_key: string; message: string; path: string }
58
65
 
@@ -88,7 +95,7 @@ type HttpStream<I, V, E = never> = {
88
95
  /** \`client.safe\`: every REST and stream call answering a Result, never throwing an API answer; a connection as is. */
89
96
  export type HttpSafe<T> = {
90
97
  [K in keyof T]: `;
91
- /* the safe mirror's REST and stream arms */
98
+ // the safe mirror's REST and stream arms
92
99
  const SAFE_ARMS = ` ? {
93
100
  (input: I & HttpOptions & { raw: true }): Promise<Result<Response, E>>
94
101
  (...input: HttpArgs<I, HttpOptions & { raw?: false }>): Promise<Result<D, E, H>>
@@ -105,7 +112,8 @@ export function shared(features) {
105
112
  ...(features.ws || features.realtime ? ["TypedWebSocket"] : []),
106
113
  ];
107
114
  const realtime = features.realtime
108
- ? `export type RealtimeCallOptions = Omit<HttpOptions, "idempotencyKey" | "timeout"> & RealtimeOptions\n`
115
+ ? 'export type RealtimeCallOptions = Omit<HttpOptions, "idempotencyKey" | "singleFlight" | "timeout"> & ' +
116
+ "RealtimeOptions\n"
109
117
  : "";
110
118
  const rest = "T[K] extends HttpCall<infer I, infer D, infer E, infer H>";
111
119
  const safe = connections.length === 0
@@ -1,8 +1,3 @@
1
- /**
2
- * The `${stem}.types.gen.ts` text: the component schemas, each operation's input, data, error and
3
- * header types, the SDK's config, and the interface its class merges with. Types and runtime meet
4
- * in the member tree, so a renamed member (`state` → `state_`) is renamed in both.
5
- */
6
1
  import type { IR } from "../../ir/model.ts";
7
2
  /**
8
3
  * The component schemas' declared names, clear of `reserved` (the names the emitted file declares
@@ -1,8 +1,14 @@
1
+ /**
2
+ * The `${stem}.types.gen.ts` text: the component schemas, each operation's input, data, error and
3
+ * header types, the SDK's config, and the interface its class merges with. Types and runtime meet
4
+ * in the member tree, so a renamed member (`state` → `state_`) is renamed in both.
5
+ */
6
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
1
7
  import { dispatchKey, irErrorEnvelope, isJsonMedia, mediaEssence, sdkModel, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
2
8
  import { bodiesOf } from "../../ir/slots.js";
3
9
  import { blockCommentText, tsString } from "../shared/escape.js";
4
10
  import { compareCodeUnits, NameTable, pascalWords } from "../shared/lang.js";
5
- import { quoteKey } from "../shared/literals.js";
11
+ import { optionalType, quoteKey } from "../shared/literals.js";
6
12
  import { irToTs } from "../shared/type-emitter.js";
7
13
  import { runtimeFeatures } from "./http.js";
8
14
  import { importText, RESERVED, shared } from "./sdk-types-preamble.js";
@@ -15,7 +21,7 @@ function paramsPart(field, params, value) {
15
21
  return null;
16
22
  const entries = [...params]
17
23
  .sort((a, b) => compareCodeUnits(a.name, b.name))
18
- .map((p) => `${quoteKey(p.name)}${p.required === true ? "" : "?"}: ${value(p)}`);
24
+ .map((p) => p.required === true ? `${quoteKey(p.name)}: ${value(p)}` : `${quoteKey(p.name)}?: ${optionalType(value(p))}`);
19
25
  return { field, required: params.some((p) => p.required === true), type: objectText(entries) };
20
26
  }
21
27
  /** The input field a request body fills, by its media type. */
@@ -41,9 +47,9 @@ function bodyParts(op, ctx) {
41
47
  const body = byField.get(field);
42
48
  if (body === undefined)
43
49
  return [];
44
- /* a multipart file part is a Blob, so a File passes; in JSON a binary field stays a string. the form's own
45
- shape is emitted, never its component's name: one named type cannot be `string` for JSON and `Blob` here,
46
- and a name is what hid the Blob until bit 22 b */
50
+ // a multipart file part is a Blob, so a File passes; in JSON a binary field stays a string. the form's own
51
+ // shape is emitted, never its component's name: one named type cannot be `string` for JSON and `Blob` here,
52
+ // and a name is what hid the Blob until bit 22 b
47
53
  const type = body.kind === "stream"
48
54
  ? "ArrayBuffer | Blob | ReadableStream<Uint8Array> | Uint8Array"
49
55
  : field === "form"
@@ -55,10 +61,10 @@ function bodyParts(op, ctx) {
55
61
  /** A call's input object, and whether it must be passed. */
56
62
  function inputOf(op, ctx) {
57
63
  const { types } = ctx;
58
- /* a header or cookie is text on the wire: an enum keeps its values, anything else is a string */
64
+ // a header or cookie is text on the wire: an enum keeps its values, anything else is a string
59
65
  const text = (p) => (p.schema.kind === "scalar" && p.schema.enum ? irToTs(p.schema, types) : "string");
60
66
  const pathParams = op.pathParams.map((p) => ({ ...p, required: true }));
61
- /* a browser WebSocket sends no headers and sets no cookies, so a socket call takes neither */
67
+ // a browser WebSocket sends no headers and sets no cookies, so a socket call takes neither
62
68
  const socket = op.stream === "ws";
63
69
  const parts = [
64
70
  paramsPart("params", pathParams, (p) => irToTs(p.schema, types)),
@@ -68,7 +74,7 @@ function inputOf(op, ctx) {
68
74
  ...bodyParts(op, ctx),
69
75
  ].filter((part) => part !== null);
70
76
  const ordered = [...parts.filter((p) => p.required), ...parts.filter((p) => !p.required)];
71
- const fields = ordered.map((p) => `${p.field}${p.required ? "" : "?"}: ${p.type}`);
77
+ const fields = ordered.map((p) => (p.required ? `${p.field}: ${p.type}` : `${p.field}?: ${optionalType(p.type)}`));
72
78
  return { required: parts.some((p) => p.required), type: objectText(fields) };
73
79
  }
74
80
  /** The data a successful call resolves to: JSON from its schema, text as a string, bytes (A1), else null. */
@@ -152,7 +158,7 @@ function signature(name, op, ctx) {
152
158
  return `${input.required ? "input" : "input?"}: ${type}`;
153
159
  };
154
160
  const key = quoteKey(name);
155
- /* a realtime op is one resumable connection of its event data; any other is typed by its transport */
161
+ // a realtime op is one resumable connection of its event data; any other is typed by its transport
156
162
  const { realtime, sse, websocket } = op.ir.extensions;
157
163
  if (realtime)
158
164
  return `${key}(${arg("RealtimeCallOptions")}): ${connectionType(op, ctx)}`;
@@ -167,7 +173,7 @@ function signature(name, op, ctx) {
167
173
  const tail = headers === null ? (errors === null ? [] : [errors]) : [errors ?? "never", headers];
168
174
  return `${key}: HttpCall<${[input.type, dataOf(op, ctx.types), ...tail].join(", ")}>`;
169
175
  }
170
- /* every line break a comment splits at, as the shared comment writers split (escape.ts) */
176
+ // every line break a comment splits at, as the shared comment writers split (escape.ts)
171
177
  const LINE_BREAKS = /\r\n|\r|\n|\u2028|\u2029/;
172
178
  /**
173
179
  * `op`'s summary and description as a JSDoc block above its overloads at `indent`, a paragraph each, as Go, Rust,
@@ -209,20 +215,58 @@ export function componentNames(ir, reserved) {
209
215
  }
210
216
  return (schema) => table.get(schema, "Schema");
211
217
  }
212
- /** The config type: `baseURL` optional when the document declares a server, the first one being its default. */
213
- function configText(name, server, runtimeConfig) {
218
+ /** `ids` as a union of string literals in code-unit order, each once. */
219
+ function literalUnion(ids) {
220
+ return [...new Set(ids)].toSorted(compareCodeUnits).map(tsString).join(" | ");
221
+ }
222
+ /**
223
+ * `onInvalidate` with its event narrowed to the API's operationIds: `by` to the writes that invalidate a read, each
224
+ * target to the reads some write invalidates. None for an API whose writes invalidate nothing: no hook is ever called
225
+ * there, so there is nothing to narrow.
226
+ */
227
+ function onInvalidateField(ir) {
228
+ const { reads } = invalidateReads(ir);
229
+ if (reads.size === 0)
230
+ return [];
231
+ const targets = [...reads.values()].flat().map((read) => read.operationId);
232
+ const ids = `${literalUnion(reads.keys())}, ${literalUnion(targets)}`;
233
+ return [
234
+ {
235
+ key: "onInvalidate",
236
+ text: [
237
+ "\t/** The `onInvalidate` hooks, their event narrowed to this API's writes and the reads they make stale. */",
238
+ `\tonInvalidate?: Array<(event: InvalidateEvent<${ids}>) => Promise<void> | void>`,
239
+ ].join("\n"),
240
+ },
241
+ {
242
+ key: "singleFlight",
243
+ text: [
244
+ "\t/** Single flight, its `exclude` and `select` narrowed to this API's writes and the reads they make " +
245
+ "stale. */",
246
+ `\tsingleFlight?: SingleFlightConfig<${ids}>`,
247
+ ].join("\n"),
248
+ },
249
+ ];
250
+ }
251
+ /**
252
+ * The config type: `baseURL` optional when the document declares a server, the first one being its default, and
253
+ * `onInvalidate`'s event narrowed to the API's operationIds when any write invalidates a read.
254
+ */
255
+ function configText(ir, name, runtimeConfig) {
256
+ const server = ir.servers[0];
257
+ const doc = server === undefined ? "" : `\t/** Default: the document's first server, ${blockCommentText(server)} */`;
258
+ const baseURL = server === undefined ? [] : [{ key: "baseURL", text: `${doc}\n\tbaseURL?: string` }];
259
+ const fields = [...baseURL, ...onInvalidateField(ir)];
214
260
  const head = `export type ${name}Config =`;
215
- if (server === undefined)
261
+ if (fields.length === 0)
216
262
  return `${head} ${runtimeConfig}`;
217
- return `${head} Omit<${runtimeConfig}, "baseURL"> & {
218
- /** Default: the document's first server, ${blockCommentText(server)} */
219
- baseURL?: string
220
- }`;
263
+ const omitted = fields.map(({ key }) => tsString(key)).join(" | ");
264
+ return `${head} Omit<${runtimeConfig}, ${omitted}> & {\n${fields.map(({ text }) => text).join("\n")}\n}`;
221
265
  }
222
266
  /** The `${stem}.types.gen.ts` text of `ir` for the SDK `name`, importing the runtime module `runtime`. */
223
267
  export function sdkTypesText(ir, name, runtime) {
224
268
  const model = sdkModel(ir);
225
- /* the SDK named `SDK` declares `SDKConfig`, so the runtime's own is imported under another name */
269
+ // the SDK named `SDK` declares `SDKConfig`, so the runtime's own is imported under another name
226
270
  const aliases = name === "SDK" ? { SDKConfig: "HttpSDKConfig" } : {};
227
271
  const runtimeConfig = aliases["SDKConfig"] ?? "SDKConfig";
228
272
  const own = [
@@ -237,7 +281,7 @@ export function sdkTypesText(ir, name, runtime) {
237
281
  const ctx = { ops: model.opsById, resolve: model.resolve, types };
238
282
  const schemas = model.schemaNames.map((schema) => `export type ${types.refName?.(schema)} = ${irToTs(ir.schemas[schema], types)}`);
239
283
  const body = `${schemas.length === 0 ? "" : `${schemas.join("\n")}\n\n`}${webhookTypesText(ir, types)}${shared(runtimeFeatures(ir))}
240
- ${configText(name, ir.servers[0], runtimeConfig)}
284
+ ${configText(ir, name, runtimeConfig)}
241
285
 
242
286
  /** Every operation of the SDK, by its member path. */
243
287
  export interface ${name}Operations {
@@ -2,6 +2,8 @@ export { sdkMemberPaths, serviceMapOf } from "./service-map.ts";
2
2
  export type SdkOptions = {
3
3
  /** the SDK class name, a TypeScript identifier */
4
4
  readonly name: string;
5
+ /** also write `<stem>.single-flight.gen.ts`, a server's handler for a write and its reads in one request */
6
+ readonly singleFlight?: boolean;
5
7
  /** the file-name stem; the name kebab-cased when left out (`TestSDK` → `test-sdk`) */
6
8
  readonly stem?: string;
7
9
  /** also write `<stem>.tanstack-query.gen.ts`; `@tanstack/query-core` is then the consumer's own peer */
@@ -9,7 +11,7 @@ export type SdkOptions = {
9
11
  };
10
12
  /**
11
13
  * The SDK's files, its stem, the document's own version, and what the generation tells its caller: a root group
12
- * renamed off the safe mirror.
14
+ * renamed off the safe mirror, an `x-invalidate` selector that names no read.
13
15
  */
14
16
  export type GeneratedSdk = {
15
17
  readonly files: Readonly<Record<string, string>>;
@@ -5,18 +5,20 @@
5
5
  * `verifyWebhook` on its own so a receiver imports nothing else. Read from the IR alone (H2).
6
6
  */
7
7
  import { toIR } from "../../ir/build.js";
8
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
8
9
  import { tsString } from "../shared/escape.js";
9
10
  import { compareCodeUnits, words } from "../shared/lang.js";
10
11
  import { MIRROR, mirrorNotice } from "../shared/mirror.js";
11
12
  import { runtimeFeatures, runtimeSource } from "./http.js";
12
13
  import { RESERVED } from "./sdk-types-preamble.js";
13
14
  import { sdkTypesText } from "./sdk-types.js";
14
- import { tanstackQueryText } from "./tanstack-query.js";
15
15
  import { memberTree, serviceMapText } from "./service-map.js";
16
+ import { singleFlightText } from "./single-flight-text.js";
17
+ import { tanstackQueryText } from "./tanstack-query.js";
16
18
  import { webhooksText, webhookTypeNames } from "./webhooks.js";
17
19
  export { sdkMemberPaths, serviceMapOf } from "./service-map.js";
18
20
  const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
19
- /* the error classes and helpers a consumer imports from the SDK beside the class, by the transport that ships them */
21
+ // the error classes and helpers a consumer imports from the SDK beside the class, by the transport that ships them
20
22
  const RUNTIME_EXPORTS = {
21
23
  core: [
22
24
  "APIConnectionError",
@@ -51,7 +53,19 @@ const RUNTIME_EXPORTS = {
51
53
  ws: [],
52
54
  };
53
55
  const RUNTIME_TYPES = {
54
- core: ["ClientConfig", "InvalidationConfig", "LogEntry", "RequestOptions", "Result"],
56
+ core: [
57
+ "ClientConfig",
58
+ "FreshReads",
59
+ "InvalidateEvent",
60
+ "InvalidateTarget",
61
+ "InvalidationConfig",
62
+ "LogEntry",
63
+ "RequestOptions",
64
+ "Result",
65
+ "SingleFlightBatch",
66
+ "SingleFlightConfig",
67
+ "SingleFlightReadRequest",
68
+ ],
55
69
  realtime: [
56
70
  "ConnectionState",
57
71
  "RealtimeOptions",
@@ -113,21 +127,33 @@ function validated(options) {
113
127
  }
114
128
  return { name, stem };
115
129
  }
130
+ /**
131
+ * Why the class casts a config whose `onInvalidate` event is narrowed (sdk-types.ts) to the runtime's, as the
132
+ * constructor's comment lines.
133
+ */
134
+ const NARROWED_CAST = [
135
+ "onInvalidate's hooks and singleFlight's select take only this API's operationIds, all the runtime sends them,",
136
+ "but a callback's parameter is contravariant, so the narrowed config is the runtime's only through a cast",
137
+ ];
116
138
  /**
117
139
  * The class: the runtime's `SDKClient` over the service map, merged with the operations' interface.
118
- * A config without `baseURL` sends to `server`, the document's first one, when it declares any; its auth header
119
- * pair defaults to the API's scheme (`auth`), as every sibling SDK's does.
140
+ * A config without `baseURL` sends to the document's first server, when it declares any; its auth header
141
+ * pair defaults to the API's scheme, as every sibling SDK's does.
120
142
  */
121
- function clientText(name, stem, server, auth) {
143
+ function clientText(name, stem, ir) {
144
+ const server = ir.servers[0];
122
145
  const based = server === undefined ? "config" : `{ ...config, baseURL: config.baseURL ?? ${tsString(server)} }`;
123
- const config = `schemeAuth(${based}, ${tsString(auth.headerName)}, ${tsString(auth.prefix)})`;
146
+ const isNarrowed = invalidateReads(ir).reads.size > 0;
147
+ const cast = isNarrowed ? `${based} as ConstructorParameters<typeof SDKClient>[1]` : based;
148
+ const config = `schemeAuth(${cast}, ${tsString(ir.auth.headerName)}, ${tsString(ir.auth.prefix)})`;
149
+ const reason = isNarrowed ? NARROWED_CAST.map((line) => `\t\t// ${line}\n`).join("") : "";
124
150
  return `import { SDKClient, schemeAuth } from "./${stem}.runtime.gen.js"
125
151
  import { serviceMap } from "./${stem}.map.gen.js"
126
152
  import type { ${name}Config, ${name}Operations, ${name}Safe } from "./${stem}.types.gen.js"
127
153
 
128
154
  export class ${name} extends SDKClient {
129
155
  constructor(config: ${name}Config) {
130
- super(serviceMap, ${config})
156
+ ${reason} super(serviceMap, ${config})
131
157
  }
132
158
  }
133
159
 
@@ -153,12 +179,15 @@ export function generateSdk(document, options) {
153
179
  refuseClash(name, (own) => (events.has(own) ? "the document's webhook events" : undefined));
154
180
  const runtime = `${stem}.runtime.gen`;
155
181
  const features = runtimeFeatures(ir);
156
- /* memberTree emits the root groups in code-unit order, each renamed in place */
182
+ // memberTree emits the root groups in code-unit order, each renamed in place
157
183
  const emitted = [...memberTree(ir.tree).entries.keys()];
158
184
  const groups = [...ir.tree.entries.keys()].sort(compareCodeUnits);
159
- const notices = groups.flatMap((group, i) => mirrorNotice("ts", MIRROR, group, emitted[i]) ?? []);
185
+ const notices = [
186
+ ...groups.flatMap((group, i) => mirrorNotice("ts", MIRROR, group, emitted[i]) ?? []),
187
+ ...invalidateReads(ir).warnings.map((warning) => `ts: ${warning}`),
188
+ ];
160
189
  const files = {
161
- [`${stem}.client.gen.ts`]: clientText(name, stem, ir.servers[0], ir.auth),
190
+ [`${stem}.client.gen.ts`]: clientText(name, stem, ir),
162
191
  [`${stem}.index.gen.ts`]: indexText(name, stem, features),
163
192
  [`${stem}.map.gen.ts`]: serviceMapText(ir, runtime),
164
193
  [`${stem}.runtime.gen.ts`]: runtimeSource(features),
@@ -166,8 +195,11 @@ export function generateSdk(document, options) {
166
195
  };
167
196
  if (ir.webhooks.some((webhook) => webhook.event))
168
197
  files[`${stem}.webhook.gen.ts`] = webhooksText(ir, stem);
169
- /* the index never names it: its text must not vary by option, and it must never name query-core */
198
+ // the index never names it: its text must not vary by option, and it must never name query-core
170
199
  if (options.tanstackQuery === true)
171
200
  files[`${stem}.tanstack-query.gen.ts`] = tanstackQueryText(ir, name, stem);
201
+ // a server's file: the index never names it, so no browser bundle carries the handler
202
+ if (options.singleFlight === true)
203
+ files[`${stem}.single-flight.gen.ts`] = singleFlightText(ir, name, stem);
172
204
  return { files, notices, stem, version: ir.info.version };
173
205
  }
@@ -2,18 +2,23 @@
2
2
  * Where each operation sits on a generated TS client, and the service map the runtime dispatches
3
3
  * by: the resource tree with every member name a client can expose, and one entry per operation.
4
4
  */
5
+ import { type InvalidatedRead } from "../../ir/invalidate-reads.ts";
5
6
  import type { IR, IRNamespace } from "../../ir/model.ts";
6
7
  /** One operation as the runtime's service map holds it (`runtime/ts/sdk.ts` `ServiceEntry`). */
7
- export type ServiceEntry = {
8
+ type ServiceEntry = {
8
9
  accept?: string;
9
10
  /** the operation declares no success body: a 2xx reads as null, its body only through `raw` */
10
11
  empty?: true;
11
12
  headers?: string[];
13
+ /** the operationId, which `onInvalidate` names a write and its reads by; the member path may be renamed */
14
+ id: string;
12
15
  idempotent?: true;
13
16
  invalidate?: string[];
14
17
  method: string;
15
18
  params?: string[];
16
19
  path: string;
20
+ /** the reads a successful call makes stale, resolved from `invalidate` at generation */
21
+ reads?: InvalidatedRead[];
17
22
  realtime?: true;
18
23
  /** an event stream; `"json"` when its declared event schema is not a string, its JSON events' names when it names them */
19
24
  sse?: "json" | string[] | true;
@@ -44,3 +49,4 @@ export declare function sdkMemberPaths(ir: IR): Map<string, string[]>;
44
49
  export declare function serviceMapOf(ir: IR): Record<string, ServiceMapNode>;
45
50
  /** The `${stem}.map.gen.ts` text: the service map as a `const`, importing the adapters its entries name. */
46
51
  export declare function serviceMapText(ir: IR, runtime: string): string;
52
+ export {};
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Where each operation sits on a generated TS client, and the service map the runtime dispatches
3
+ * by: the resource tree with every member name a client can expose, and one entry per operation.
4
+ */
5
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
1
6
  import { isJsonMedia, mediaEssence, sdkModel, dispatchKey, isJsonEventData, sseEventSchema, sseEvents, } from "../../ir/sdk-model.js";
2
7
  import { openApiPathParams } from "../../ir/slots.js";
3
8
  import { tsString } from "../shared/escape.js";
@@ -98,7 +103,7 @@ function socketEntry(op, resolve) {
98
103
  }
99
104
  /** The service entry of `op`; `success` is its success answer as the SDK model reads it. */
100
105
  function entryOf(op, success, resolve) {
101
- const entry = { method: op.method, path: op.path };
106
+ const entry = { id: op.id, method: op.method, path: op.path };
102
107
  const params = openApiPathParams(op.path);
103
108
  if (params.length > 0)
104
109
  entry.params = params;
@@ -144,6 +149,7 @@ class Identifier {
144
149
  function mapOf(ir, calls) {
145
150
  const model = sdkModel(ir);
146
151
  const ops = model.opsById;
152
+ const { reads } = invalidateReads(ir);
147
153
  const walk = (ns) => {
148
154
  const node = Object.create(null);
149
155
  for (const [key, entry] of ns.entries) {
@@ -153,6 +159,9 @@ function mapOf(ir, calls) {
153
159
  }
154
160
  const op = ops.get(entry.op.id);
155
161
  const value = entryOf(entry.op, op.success, model.resolve);
162
+ const invalidated = reads.get(entry.op.id);
163
+ if (invalidated !== undefined)
164
+ value.reads = invalidated;
156
165
  if (calls && op.stream !== null)
157
166
  value.call = new Identifier(OPERATION_CALLS[op.stream]);
158
167
  node[key] = value;
@@ -0,0 +1,3 @@
1
+ import type { IR } from "../../ir/model.ts";
2
+ /** The single-flight file of the SDK `name` over `ir`; an API with no write that invalidates a read is refused. */
3
+ export declare function singleFlightText(ir: IR, name: string, stem: string): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `<stem>.single-flight.gen.ts`, written under `--ts-single-flight`: `singleFlightHandler` and `runSingleFlight`
3
+ * over the SDK's service map, a server's file of its own (as the webhook verifier is), never named by the index.
4
+ */
5
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
6
+ import { singleFlightSource } from "./http.js";
7
+ // the runtime's declarations a consumer never imports: every one but the public SingleFlight* and Json types
8
+ const INTERNAL = /^export ((?:async )?function |type |const )(?!SingleFlight|Json\b|JsonObject\b)/gm;
9
+ /** The two calls a server imports, typed by the SDK class `name`. */
10
+ function wrappers(name) {
11
+ return `/**
12
+ * A fetch handler that runs one write, then the reads it made stale, in one request: \`{ v: 1, op, input, reads }\`
13
+ * in, \`{ v: 1, write, reads }\` out. Mount it before any proxy of the API, and make \`getSdk\`'s client per request,
14
+ * forwarding only the auth it chooses. The write runs once: this handler adds no retry, the SDK's own hooks may.
15
+ * Set-Cookie headers of the write are copied onto the answer; they only stick when the API shares this site.
16
+ */
17
+ export function singleFlightHandler(
18
+ getSdk: SingleFlightSdk<${name}>,
19
+ options: SingleFlightOptions = {},
20
+ ): (request: Request) => Promise<Response> {
21
+ return handlerOf(serviceMap, getSdk, options)
22
+ }
23
+
24
+ /** The same batch run with no Request or Response: a refusal throws a TypeError, the write's cookies are dropped. */
25
+ export function runSingleFlight(sdk: ${name}, body: Json): Promise<SingleFlightEnvelope> {
26
+ return runFlight(serviceMap, sdk, body)
27
+ }
28
+ `;
29
+ }
30
+ /** The single-flight file of the SDK `name` over `ir`; an API with no write that invalidates a read is refused. */
31
+ export function singleFlightText(ir, name, stem) {
32
+ if (invalidateReads(ir).reads.size === 0)
33
+ throw new Error("generateSdk: singleFlight needs a write whose x-invalidate names a read; this API declares none");
34
+ return `import type { ${name} } from "./${stem}.client.gen.js"
35
+ import { serviceMap } from "./${stem}.map.gen.js"
36
+ ${singleFlightSource(stem).replaceAll(INTERNAL, "$1")}
37
+ ${wrappers(name)}`;
38
+ }
@@ -6,7 +6,8 @@ import type { IR } from "../../ir/model.ts";
6
6
  */
7
7
  export declare function tanstackQuerySource(runtime: string): string;
8
8
  /**
9
- * `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document, and the
10
- * mapped types that turn them into exact surfaces over the client's own operations.
9
+ * `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document, the
10
+ * mapped types that turn them into exact surfaces over the client's own operations, and the
11
+ * `onInvalidate` hook bound to this API's reads.
11
12
  */
12
13
  export declare function tanstackQueryText(ir: IR, name: string, stem: string): string;
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The TanStack Query adapter the `ts` target writes under `--ts-tanstack-query` (bit 22):
3
3
  * `<stem>.tanstack-query.gen.ts`, the vendored modules under `runtime/ts-tanstack-query` joined into one
4
- * file beside the SDK, plus the types that make its surfaces exact for this document.
4
+ * file beside the SDK, plus the types that make its surfaces exact for this document and the
5
+ * `onInvalidate` hook bound to its reads.
5
6
  *
6
7
  * The vendoring mirrors `http.ts`'s `runtimeSource`, with one difference it cannot share: those modules
7
8
  * import only each other, so dropping every sibling import is enough. These import clients' runtime too
@@ -14,11 +15,11 @@ import { quoteKey } from "../shared/literals.js";
14
15
  import { memberTree } from "./service-map.js";
15
16
  /** The adapter's modules, each after the ones it imports, as `RUNTIME_MODULES` is ordered. */
16
17
  const QUERY_MODULES = ["invalidate", "query"];
17
- /* an import of a module beside this one: now the same file, so the names are already in scope */
18
+ // an import of a module beside this one: now the same file, so the names are already in scope
18
19
  const SIBLING_IMPORT = /^import\s+(?:type\s+)?\{[^}]*\}\s+from\s+"\.\/[\w-]+\.ts"\n/gm;
19
- /* an import of clients' own runtime, which the emitted file reads from `<stem>.runtime.gen` */
20
+ // an import of clients' own runtime, which the emitted file reads from `<stem>.runtime.gen`
20
21
  const RUNTIME_IMPORT = /^import\s+(type\s+)?\{([^}]*)\}\s+from\s+"\.\.\/ts\/[\w-]+\.ts"\n/gm;
21
- /* query-core, which stays exactly as written: type-only, so nothing has to resolve at run time */
22
+ // query-core, which stays exactly as written: type-only, so nothing has to resolve at run time
22
23
  const QUERY_CORE_IMPORT = /^import\s+type\s+\{([^}]*)\}\s+from\s+"@tanstack\/query-core"\n/gm;
23
24
  /** The names a `{ a, type b }` clause lists, in code-unit order and once each. */
24
25
  function namesOf(clauses) {
@@ -40,15 +41,15 @@ export function tanstackQuerySource(runtime) {
40
41
  const bodies = QUERY_MODULES.map((name) => {
41
42
  const text = readFileSync(new URL(`../../runtime/ts-tanstack-query/${name}.ts`, import.meta.url), "utf8");
42
43
  return text
43
- .replace(QUERY_CORE_IMPORT, (_, named) => {
44
+ .replaceAll(QUERY_CORE_IMPORT, (_, named) => {
44
45
  core.push(named);
45
46
  return "";
46
47
  })
47
- .replace(RUNTIME_IMPORT, (_, __, named) => {
48
+ .replaceAll(RUNTIME_IMPORT, (_, __, named) => {
48
49
  runtimeNames.push(named);
49
50
  return "";
50
51
  })
51
- .replace(SIBLING_IMPORT, "")
52
+ .replaceAll(SIBLING_IMPORT, "")
52
53
  .trim();
53
54
  });
54
55
  const imports = [
@@ -94,15 +95,25 @@ function readable(ir) {
94
95
  }
95
96
  return out;
96
97
  }
98
+ /** Each cacheable read's operationId and its member path, as the client nests it. */
99
+ function readMembers(ns, ops, at = []) {
100
+ return [...ns.entries].flatMap(([name, entry]) => {
101
+ if (entry.kind === "namespace")
102
+ return readMembers(entry.ns, ops, [...at, name]);
103
+ return ops.get(entry.op.id) === true ? [[entry.op.id, [...at, name]]] : [];
104
+ });
105
+ }
97
106
  /**
98
- * `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document, and the
99
- * mapped types that turn them into exact surfaces over the client's own operations.
107
+ * `<stem>.tanstack-query.gen.ts`: the vendored adapter, the two key trees read off this document, the
108
+ * mapped types that turn them into exact surfaces over the client's own operations, and the
109
+ * `onInvalidate` hook bound to this API's reads.
100
110
  */
101
111
  export function tanstackQueryText(ir, name, stem) {
102
112
  const ops = readable(ir);
103
113
  const tree = memberTree(ir.tree);
104
114
  const queries = treeOf(tree, (op) => ops.get(op.id) === true, ops);
105
115
  const mutations = treeOf(tree, (op) => ops.get(op.id) === false, ops);
116
+ const table = readMembers(tree, ops).map(([id, member]) => `\t[${JSON.stringify(id)}, ${JSON.stringify(member)}],`);
106
117
  return `${tanstackQuerySource(`${stem}.runtime.gen`)}
107
118
  import { serviceMap } from "./${stem}.map.gen.js"
108
119
  import type { ${name} } from "./${stem}.client.gen.js"
@@ -115,42 +126,56 @@ type TanstackMutationTree = ${treeText(mutations)}
115
126
 
116
127
  type TreeShape = { readonly [key: string]: TreeShape | 1 }
117
128
 
118
- type Surfaced<TOps, TTree extends TreeShape, TLeaf> = {
129
+ /** A leaf's factory, by surface: query, mutation, infiniteQuery, queryKey, mutationKey. */
130
+ type Leaf<M> = [QueryFactory<M>, MutationFactory<M>, InfiniteFactory<M>, QueryKeyFactory<M>, MutationKeyFactory]
131
+
132
+ type Surfaced<TOps, TTree extends TreeShape, TLeaf extends number> = {
119
133
  [K in Extract<keyof TTree, keyof TOps>]: TTree[K] extends 1
120
- ? TLeaf extends 0
121
- ? QueryFactory<TOps[K]>
122
- : TLeaf extends 1
123
- ? MutationFactory<TOps[K]>
124
- : TLeaf extends 2
125
- ? InfiniteFactory<TOps[K]>
126
- : KeyFactory<TOps[K]>
134
+ ? Leaf<TOps[K]>[TLeaf]
127
135
  : TTree[K] extends TreeShape
128
136
  ? Surfaced<TOps[K], TTree[K], TLeaf>
129
137
  : never
130
138
  }
131
139
 
132
- /**
133
- * The TanStack Query factories for this SDK. \`sdk\` may be a client or a thunk for one, which an
134
- * isomorphic app needs; \`getQueryClient\` is what a successful write invalidates against.
135
- */
136
- export function createQueryHelpers(
137
- sdk: SdkSource<${name}>,
138
- options: QueryHelperOptions = {},
139
- ): {
140
+ type Surfaces = {
140
141
  infiniteQuery: Surfaced<${name}, TanstackQueryTree, 2>
141
142
  mutation: Surfaced<${name}, TanstackMutationTree, 1>
142
- mutationKey: Surfaced<${name}, TanstackMutationTree, 3>
143
+ mutationKey: Surfaced<${name}, TanstackMutationTree, 4>
143
144
  query: Surfaced<${name}, TanstackQueryTree, 0>
144
145
  queryKey: Surfaced<${name}, TanstackQueryTree, 3>
145
- } {
146
- const helpers = queryHelpers(sdk, serviceMap as ServiceMap, ${JSON.stringify(name)}, options)
147
- return helpers as unknown as {
148
- infiniteQuery: Surfaced<${name}, TanstackQueryTree, 2>
149
- mutation: Surfaced<${name}, TanstackMutationTree, 1>
150
- mutationKey: Surfaced<${name}, TanstackMutationTree, 3>
151
- query: Surfaced<${name}, TanstackQueryTree, 0>
152
- queryKey: Surfaced<${name}, TanstackQueryTree, 3>
153
- }
146
+ }
147
+
148
+ /**
149
+ * The TanStack Query factories for this SDK, over the client \`getSdk\` returns, read on every call so an
150
+ * isomorphic app can hand each request its own. Spread a factory's result into TanStack's options.
151
+ */
152
+ export function createQueryHelpers(getSdk: () => ${name}): Surfaces {
153
+ const helpers = queryHelpers(getSdk, serviceMap as ServiceMap, ${JSON.stringify(name)})
154
+ /* the runtime's surfaces are untyped proxies over this map; these types are the map's own */
155
+ return helpers as unknown as Surfaces
156
+ }
157
+
158
+ /** Each read's operationId and the member path its keys start with. */
159
+ const READ_MEMBERS: ReadonlyMap<string, readonly string[]> = new Map<string, readonly string[]>([
160
+ ${table.join("\n")}
161
+ ])
162
+
163
+ /**
164
+ * The hook for \`new ${name}({ onInvalidate: [invalidateQueries(queryClient)] })\`: a write, raw or through
165
+ * \`mutation\`, resolves once the reads it made stale have refetched, and a failing refetch never rejects it.
166
+ */
167
+ export function invalidateQueries(queryClient: QueryClient): (event: InvalidateEvent) => Promise<void> {
168
+ return invalidationHook(queryClient, ${JSON.stringify(name)}, READ_MEMBERS)
169
+ }
170
+
171
+ /**
172
+ * The \`select\` for \`new ${name}({ singleFlight: { select: activeReads(queryClient) } })\`: a write brings back
173
+ * the active reads it made stale in its single-flight batch, and \`invalidateQueries\` puts them in the cache.
174
+ */
175
+ export function activeReads<Read extends string>(
176
+ queryClient: QueryClient,
177
+ ): (targets: InvalidateTarget<Read>[]) => SingleFlightReadRequest<Read>[] {
178
+ return activeReadsOf(queryClient, ${JSON.stringify(name)}, READ_MEMBERS)
154
179
  }
155
180
  `;
156
181
  }