@workerstack/clients 1.0.0-rc.30 → 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 (115) hide show
  1. package/README.md +175 -21
  2. package/bin/clients.js +5 -6
  3. package/bin/installgen.js +5 -9
  4. package/dist/cli.js +3 -1
  5. package/dist/emit/csharp/sdk-method.d.ts +18 -1
  6. package/dist/emit/csharp/sdk-method.js +14 -3
  7. package/dist/emit/csharp/sdk.js +4 -1
  8. package/dist/emit/go/sdk-method.d.ts +9 -0
  9. package/dist/emit/go/sdk-method.js +10 -1
  10. package/dist/emit/go/sdk.js +4 -3
  11. package/dist/emit/java/sdk-client.js +1 -0
  12. package/dist/emit/java/sdk-op.d.ts +6 -1
  13. package/dist/emit/java/sdk-op.js +15 -3
  14. package/dist/emit/java/sdk.js +7 -1
  15. package/dist/emit/python/sdk-method.d.ts +11 -0
  16. package/dist/emit/python/sdk-method.js +15 -0
  17. package/dist/emit/python/sdk.js +5 -1
  18. package/dist/emit/rust/sdk-method.d.ts +12 -1
  19. package/dist/emit/rust/sdk-method.js +10 -2
  20. package/dist/emit/rust/sdk.js +4 -1
  21. package/dist/emit/ts/http.d.ts +8 -0
  22. package/dist/emit/ts/http.js +48 -3
  23. package/dist/emit/ts/package.js +1 -0
  24. package/dist/emit/ts/sdk-types-preamble.js +10 -2
  25. package/dist/emit/ts/sdk-types.d.ts +0 -5
  26. package/dist/emit/ts/sdk-types.js +52 -8
  27. package/dist/emit/ts/sdk.d.ts +3 -1
  28. package/dist/emit/ts/sdk.js +40 -8
  29. package/dist/emit/ts/service-map.d.ts +5 -0
  30. package/dist/emit/ts/service-map.js +10 -1
  31. package/dist/emit/ts/single-flight-text.d.ts +3 -0
  32. package/dist/emit/ts/single-flight-text.js +38 -0
  33. package/dist/emit/ts/tanstack-query.d.ts +3 -2
  34. package/dist/emit/ts/tanstack-query.js +54 -29
  35. package/dist/gen/process.js +2 -1
  36. package/dist/gen/switch-on.constants.d.ts +2 -0
  37. package/dist/gen/switch-on.constants.js +2 -0
  38. package/dist/gen/targets.d.ts +4 -3
  39. package/dist/gen/targets.js +4 -3
  40. package/dist/ir/invalidate-reads.d.ts +17 -0
  41. package/dist/ir/invalidate-reads.js +104 -0
  42. package/dist/ir/load.d.ts +10 -0
  43. package/dist/ir/load.js +62 -14
  44. package/dist/ir/read-method.constants.d.ts +2 -0
  45. package/dist/ir/read-method.constants.js +2 -0
  46. package/dist/release/load.js +1 -1
  47. package/dist/runtime/csharp/Config.cs +9 -1
  48. package/dist/runtime/csharp/Exchange.cs +56 -4
  49. package/dist/runtime/csharp/Hooks.cs +9 -0
  50. package/dist/runtime/csharp/Operation.cs +6 -1
  51. package/dist/runtime/csharp/WsDial.cs +3 -1
  52. package/dist/runtime/go/config.go +5 -0
  53. package/dist/runtime/go/hooks.go +70 -0
  54. package/dist/runtime/go/request.go +6 -2
  55. package/dist/runtime/go/stream.go +4 -1
  56. package/dist/runtime/go/ws.go +3 -1
  57. package/dist/runtime/java/ClientConfig.java +11 -0
  58. package/dist/runtime/java/Flight.java +2 -12
  59. package/dist/runtime/java/Hooks.java +45 -0
  60. package/dist/runtime/java/InvalidateEvent.java +10 -0
  61. package/dist/runtime/java/InvalidateHook.java +12 -0
  62. package/dist/runtime/java/InvalidateTarget.java +7 -0
  63. package/dist/runtime/java/Operation.java +23 -3
  64. package/dist/runtime/java/Realtime.java +3 -1
  65. package/dist/runtime/java/WsDial.java +3 -0
  66. package/dist/runtime/python/config.py +8 -2
  67. package/dist/runtime/python/exchange.py +3 -1
  68. package/dist/runtime/python/hooks.py +110 -5
  69. package/dist/runtime/python/operation.py +2 -0
  70. package/dist/runtime/python/send_async.py +14 -2
  71. package/dist/runtime/python/send_sync.py +4 -2
  72. package/dist/runtime/python/ws.py +5 -1
  73. package/dist/runtime/rust/config.rs +6 -1
  74. package/dist/runtime/rust/exchange.rs +15 -3
  75. package/dist/runtime/rust/hooks.rs +127 -2
  76. package/dist/runtime/rust/log.rs +11 -3
  77. package/dist/runtime/rust/request.rs +17 -0
  78. package/dist/runtime/rust/ws.rs +9 -1
  79. package/dist/runtime/ts/config.ts +69 -0
  80. package/dist/runtime/ts/http.ts +12 -10
  81. package/dist/runtime/ts/request.ts +2 -0
  82. package/dist/runtime/ts/response.ts +7 -0
  83. package/dist/runtime/ts/sdk-invalidate.ts +82 -0
  84. package/dist/runtime/ts/sdk-single-flight.constants.ts +25 -0
  85. package/dist/runtime/ts/sdk-single-flight.ts +203 -0
  86. package/dist/runtime/ts/sdk-sse.ts +5 -1
  87. package/dist/runtime/ts/sdk-ws.ts +9 -3
  88. package/dist/runtime/ts/sdk.ts +55 -31
  89. package/dist/runtime/ts/single-flight-batch.ts +184 -0
  90. package/dist/runtime/ts/single-flight-body.ts +59 -0
  91. package/dist/runtime/ts/single-flight-run.ts +160 -0
  92. package/dist/runtime/ts/single-flight.constants.ts +31 -0
  93. package/dist/runtime/ts/single-flight.ts +158 -0
  94. package/dist/runtime/ts-tanstack-query/invalidate.ts +96 -92
  95. package/dist/runtime/ts-tanstack-query/query.ts +140 -168
  96. package/package.json +10 -18
  97. package/references/INDEX.md +31 -0
  98. package/references/cli.md +33 -0
  99. package/references/configuring.md +29 -0
  100. package/references/documentation.md +15 -0
  101. package/references/errors.md +23 -0
  102. package/references/flags.md +104 -0
  103. package/references/gates.md +46 -0
  104. package/references/generate.md +29 -0
  105. package/references/install-scripts.md +28 -0
  106. package/references/install.md +38 -0
  107. package/references/license.md +8 -0
  108. package/references/mcp.md +76 -0
  109. package/references/output.md +45 -0
  110. package/references/overview.md +14 -0
  111. package/references/release-tooling.md +34 -0
  112. package/references/release.md +305 -0
  113. package/references/sdks.md +393 -0
  114. package/references/start.md +22 -0
  115. package/references/tdd.md +16 -0
package/README.md CHANGED
@@ -128,6 +128,7 @@ One table, since a flag that is not written down is a flag nobody finds:
128
128
  | `--ts-stem` | ts | the file stem the generated modules share |
129
129
  | `--ts-package-name` | ts | the npm name, and the JSR name when scoped; the stem by default |
130
130
  | `--ts-version` | ts | the version both registries carry; the document's by default |
131
+ | `--ts-single-flight` | ts | also write the single-flight handler; takes no value |
131
132
  | `--ts-tanstack-query` | ts | also write the TanStack Query adapter; takes no value |
132
133
  | `--go-module-path` | go | the Go module path the SDK is imported by |
133
134
  | `--go-version` | go | its semver; from v2 on, the major suffix (`/v2`) it puts on the module path |
@@ -225,7 +226,7 @@ language's client in a slice of a compiled example; the
225
226
  clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen
226
227
  ```
227
228
 
228
- ```ts sdk
229
+ ```sdk ts
229
230
  import { DecodeError, Kitchen, NotFoundError } from "./kitchen"
230
231
 
231
232
  export function newClient(): Kitchen {
@@ -277,37 +278,190 @@ clients generate --spec openapi.json --target ts --out generated --ts-name Kitch
277
278
  clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen --ts-tanstack-query
278
279
  ```
279
280
 
280
- Its `createQueryHelpers(sdk, { getQueryClient })` gives five surfaces — `query`, `mutation`, `infiniteQuery`,
281
- `queryKey` and `mutationKey` — each nested exactly as the client is, so `query.org.member.list(…)` sits where
282
- `client.org.member.list(…)` does. `sdk` may be a client or a thunk for one, which an isomorphic app needs.
281
+ Build the QueryClient first, then the SDK with the file's `invalidateQueries` hook, then the helpers. The
282
+ `QueryClient` is the one your framework's adapter exports (`@tanstack/solid-query`, `@tanstack/react-query`), or
283
+ query-core's own, as here:
284
+
285
+ ```sdk ts tanstack
286
+ import { QueryClient } from "@tanstack/query-core"
287
+ import { Kitchen } from "./kitchen"
288
+ import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"
289
+
290
+ export const queryClient = new QueryClient()
291
+ const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
292
+ export const { query, mutation, infiniteQuery, queryKey, mutationKey } = createQueryHelpers(() => sdk)
293
+ ```
294
+
295
+ The five surfaces are nested exactly as the client is, so `query.organizations.retrieve(…)` sits where
296
+ `client.organizations.retrieve(…)` does. `createQueryHelpers` takes a function that returns the client, and it calls it
297
+ on every request, so an isomorphic app can return a different client for each request.
283
298
 
284
299
  The document decides what goes where. A `GET` is on `query`, every other method is on `mutation`, and an event
285
300
  stream, a WebSocket or an `x-realtime` operation is on neither, because a stream is not a cache entry. Nothing
286
301
  is keyed off a method's name.
287
302
 
288
- **Keys.** A read's key is `[<SDK name>, ...the member path, the request]` — the request object whole, so
289
- `params`, `search` and anything else the SDK sends are all in it. That is what TanStack requires: every input
303
+ **Call shapes.** Each factory returns only its key and its function. Spread the result into TanStack's own
304
+ options and put everything else after it, so every other option is typed by TanStack. These use query-core's
305
+ observers; `useQuery(() => ({ ... }))` in solid-query, or `useQuery({ ... })` in react-query, takes the same
306
+ object:
307
+
308
+ ```sdk ts tanstack
309
+ import { InfiniteQueryObserver, MutationObserver, QueryClient, QueryObserver } from "@tanstack/query-core"
310
+ import { Kitchen } from "./kitchen"
311
+ import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"
312
+
313
+ const queryClient = new QueryClient()
314
+ const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
315
+ const { query, mutation, infiniteQuery, queryKey } = createQueryHelpers(() => sdk)
316
+
317
+ export function organization(orgId: string) {
318
+ return new QueryObserver(queryClient, { ...query.organizations.retrieve({ params: { orgId } }), staleTime: 0 })
319
+ }
320
+
321
+ // the second argument is the SDK's own call options; they reach the call, not the key
322
+ export const timed = query.organizations.retrieve({ params: { orgId: "org_1" } }, { timeout: 5_000 })
323
+
324
+ export const greet = new MutationObserver(queryClient, {
325
+ ...mutation.hello.create(),
326
+ onMutate: (input) => console.log(`greeting ${input.json.name}`),
327
+ })
328
+
329
+ export const greetings = new InfiniteQueryObserver(queryClient, {
330
+ ...infiniteQuery.hello.list((q: string | undefined) => ({ search: { q: q ?? "" } })),
331
+ initialPageParam: undefined,
332
+ getNextPageParam: () => undefined, // read the next page param off the last page, when your API pages
333
+ })
334
+
335
+ export const cached = queryClient.getQueryData(queryKey.hello.list({ search: { q: "Ada" } }))
336
+ ```
337
+
338
+ A read takes the SDK method's request, then optionally its call options (`timeout`, `headers`, `signal`, and
339
+ the other per-call options). `mutate` takes exactly what the SDK method takes. A paged read takes a function
340
+ from the page param to the request. The adapter calls that function once with `undefined` to build the key, so
341
+ it must accept `undefined`. Annotate its parameter and TanStack infers the page param type from it. Every call
342
+ gets TanStack's abort signal merged with yours, so a cancel, or the last observer unmounting, aborts the
343
+ request.
344
+
345
+ **Keys.** A read's key is `[<SDK name>, ...the member path, the request]`. The request object goes in whole,
346
+ so `params`, `search` and anything else the SDK sends are all in it. That is what TanStack requires: every input
290
347
  the `queryFn` depends on belongs in the key, so two reads of one route that differ only by `search` are two
291
- cache entries. `init` is not in the key, since a signal and a timeout say nothing about the answer. A read with
292
- no request keys as `[<SDK name>, ...the member path]`. `queryKey.<…>(req)` returns exactly the key
293
- `query.<…>({ reqOptions: { req } })` writes. A paged read carries a trailing `"infinite"` marker, because its
294
- cached shape is `InfiniteData` and it must not share the plain read's entry.
295
-
296
- **Invalidation** works by prefix, which is why the two are not the same shape. A successful write makes stale
297
- the reads its `x-invalidate` selectors name, with the mutation's own path params filled in:
298
- `[<SDK name>, ...the member path, { params }]`. TanStack matches objects partially and compares only the
299
- filter's own positions, so that reaches every search of that read, the paged entry included. When a selector's
300
- params are not all known the filter stays the bare prefix, which reaches everything under it — made stale
301
- rather than missed.
302
-
303
- Two notes. `@tanstack/query-core` is your dependency, not backend's — install it yourself; the file imports it for
304
- types only. And a read's options carry `initialData: undefined`, which is what solid-query needs to keep the
305
- unseeded overload; it is harmless under react-query.
348
+ cache entries. The call options are not in the key, since a signal and a timeout say nothing about the answer.
349
+ A read with no request keys as `[<SDK name>, ...the member path]`. `queryKey.<…>(req)` returns exactly the key
350
+ `query.<…>(req)` uses, typed so `getQueryData` infers the answer. A paged read's key is the key of its request
351
+ for `undefined` plus a trailing `"infinite"` marker, because its cached shape is `InfiniteData` and it must not
352
+ share the plain read's entry.
353
+
354
+ **Invalidation** happens in the SDK, not the helpers. A successful write fires the SDK's `onInvalidate` with the
355
+ reads its `x-invalidate` selectors name, and `invalidateQueries(queryClient)` makes each of them stale as
356
+ `[<SDK name>, ...the member path, { params }]`, or as the bare prefix when the target has no params. TanStack
357
+ matches objects partially and compares only the filter's own positions, so that reaches every search of that
358
+ read, the paged entry included. Because the SDK fires the hook, a plain `sdk.hello.create(…)` refreshes the
359
+ cache just as `mutation.hello.create()` does. The SDK awaits the hook, so a write resolves only after the
360
+ active reads it made stale have refetched. A failing refetch holds the write through its retries but never
361
+ rejects it, and an infinite query refetches every page it holds.
362
+
363
+ **Server rendering.** On the server, build the QueryClient and the SDK per request, in that order. Both are
364
+ dropped when the request ends, and the hook holds no state of its own. If a route preload prefetches, skip the
365
+ browser's hydration run, or it refetches what the server already sent:
366
+
367
+ ```sdk ts tanstack
368
+ import { QueryClient } from "@tanstack/query-core"
369
+ import { Kitchen } from "./kitchen"
370
+ import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"
371
+
372
+ const queryClient = new QueryClient()
373
+ const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
374
+ const { query } = createQueryHelpers(() => sdk)
375
+
376
+ // a route preload: `isServer` from your framework (`@solidjs/web` in Solid), `intent` from the router
377
+ export function preloadOrganization(isServer: boolean, intent: string, orgId: string): void {
378
+ if (!isServer && intent === "initial") return
379
+ void queryClient.prefetchQuery(query.organizations.retrieve({ params: { orgId } }))
380
+ }
381
+ ```
382
+
383
+ `@tanstack/query-core` is your dependency, not backend's. Install it yourself; the file imports it for types
384
+ only.
306
385
 
307
386
  Drop the flag and the next run deletes the file, the way `.clients-generated.json` deletes anything the previous
308
387
  run wrote and this one did not. The index file never re-exports the adapter, so an SDK generated without the
309
388
  flag names no TanStack type anywhere.
310
389
 
390
+ #### Single-flight, a write and its reads in one request
391
+
392
+ `--ts-single-flight` writes `<stem>.single-flight.gen.ts`, a server's file: `singleFlightHandler(getSdk, options)`
393
+ is a fetch handler, and `runSingleFlight(sdk, body)` runs the same batch with no Request or Response. It takes no
394
+ value, and the run refuses it for a document with no write whose `x-invalidate` names a read.
395
+
396
+ ```sh
397
+ clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen --ts-single-flight
398
+ ```
399
+
400
+ A batch is `{ v: 1, op, input, reads: [{ id, operationId, input }] }` and its answer is
401
+ `{ v: 1, write: { status, headers, body }, reads: [{ id, data } | { id, error: { status, body? } }] }`. Everything
402
+ is checked against the service map before anything runs: one REST write, at most `maxReads` (10) REST JSON reads,
403
+ and input of only `params`, `search`, `json` (the write's) and `idempotencyKey` (an idempotent write's). The
404
+ handler takes only a JSON POST of at most `maxBodyBytes` (64 KiB), refuses a browser on another site or an origin
405
+ outside `allowedOrigins` (its own by default), and answers a refusal as a 400 `application/problem+json`.
406
+
407
+ The write runs once on `getSdk(request)`, which you make per request, forwarding only the auth you choose; the
408
+ handler adds no retry, though the SDK's own hooks may. Only after a 2xx do the reads run, in parallel and past any
409
+ cache, within `readBudgetMs` (2000) and `maxReadBytes` (1 MiB) in all; a read past either ends as its own error
410
+ entry (504 or 502) and never fails the batch. The write's `Set-Cookie` headers are copied onto the 200, and a
411
+ cookie only sticks when the API shares the handler's site.
412
+
413
+ The index never re-exports the file, so no browser bundle carries the handler; the package exports it at
414
+ `./single-flight`.
415
+
416
+ The client sends its writes there once you give it `singleFlight`. A write goes in a batch only when it can: a
417
+ REST write with a JSON answer whose `x-invalidate` names reads, called with nothing a batch cannot carry
418
+ (`headers`, `cookies`, `body`, `form`, `baseURL`, `raw`), its operationId not in `exclude`, and `select` picking at
419
+ least one read. `select` gets the write's targets and returns the reads to bring back, at most `maxReads` (10).
420
+ Every other call goes direct, as does one called with `singleFlight: false`. The batch is a POST to `path`
421
+ (`_mutate`) under the base URL, so the client's hooks, timeout and signal apply to it. An idempotent write's key
422
+ is made before the batch, so a resend carries the same one. With TanStack Query, `activeReads(queryClient)` picks
423
+ the active reads, and `invalidateQueries` puts each one in the cache before it marks the rest stale:
424
+
425
+ ```sdk ts tanstack
426
+ import { QueryClient } from "@tanstack/query-core"
427
+ import { Kitchen } from "./kitchen"
428
+ import { activeReads, invalidateQueries } from "./kitchen.tanstack-query.gen"
429
+
430
+ const queryClient = new QueryClient()
431
+ const sdk = new Kitchen({
432
+ baseURL: "https://app.example.com/api",
433
+ onInvalidate: [invalidateQueries(queryClient)],
434
+ singleFlight: { select: activeReads(queryClient) },
435
+ })
436
+ ```
437
+
438
+ The write resolves with the answer a direct call would have, and throws the same error. Its reads reach the
439
+ `onInvalidate` hooks first, as `event.fresh`: each answered read's data by the id `select` gave it, and in
440
+ `failed` the ids that did not come back. A query opts out with `meta: { singleFlight: false }`, and a mutation with
441
+ the same meta sends its write direct. A 401 on the write refreshes the token once through `onAuthExpired` and sends
442
+ the batch again. When the handler refuses the batch, the client sends the write direct; any other failure throws
443
+ and the write is never sent twice. A batch answer that is no envelope throws `DecodeError`, the hooks still
444
+ called, since the write may have run.
445
+
446
+ `send` replaces the POST, for an app that calls its server another way, such as a server function that returns
447
+ `runSingleFlight(sdk, batch)`. It gets the batch and resolves the envelope. The client cannot tell a refusal
448
+ through `send` from a failure, so it throws one and never resends the write:
449
+
450
+ ```sdk ts
451
+ import { Kitchen, type SingleFlightBatch } from "./kitchen"
452
+
453
+ declare function mutate(batch: SingleFlightBatch): Promise<object>
454
+
455
+ export const sdk = new Kitchen({
456
+ baseURL: "https://app.example.com/api",
457
+ singleFlight: {
458
+ select: (targets) =>
459
+ targets.map((target, at) => ({ id: `r${at}`, input: { params: target.params }, operationId: target.operationId })),
460
+ send: mutate,
461
+ },
462
+ })
463
+ ```
464
+
311
465
  ### The Go SDK
312
466
 
313
467
  Idiomatic Go: a `Config`, `context.Context` on every call, errors read with `errors.As`, and an event stream as a
package/bin/clients.js CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // The clients bin (bit 17 phase h). A repository checkout (marked by tsconfig.json, which is not published)
3
- // runs the TypeScript source, natively on Bun (under the backend-source condition) and through jiti on Node, so a stale
4
- // dist/ never runs; an installed package runs the compiled JavaScript on any runtime (the tarball ships dist/, not src/).
3
+ // runs the TypeScript source natively (on Bun under the backend-source condition, on Node by its type stripping), so a
4
+ // stale dist/ never runs; an installed package runs the compiled JavaScript on any runtime (the tarball ships dist/,
5
+ // not src/).
5
6
  import { spawn } from "node:child_process";
6
7
  import { existsSync } from "node:fs";
7
8
  import { basename } from "node:path";
@@ -77,10 +78,8 @@ const sourceEnv = checkout
77
78
  */
78
79
  async function entry() {
79
80
  if (checkout) {
80
- if (isBun) return import("../src/cli.ts");
81
- const { createJiti } = await import("jiti");
82
-
83
- return createJiti(import.meta.url).import("../src/cli.ts");
81
+ // Node strips the source's types by default from 22.18
82
+ return import("../src/cli.ts");
84
83
  }
85
84
 
86
85
  try {
package/bin/installgen.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // The installgen bin. A repository checkout (marked by tsconfig.json, which is not published) runs the TypeScript
3
- // source, natively on Bun and through jiti on Node, so a stale build never runs; an installed package runs the
4
- // compiled JavaScript (the tarball ships it, not src/).
3
+ // source natively (Node by its type stripping), so a stale build never runs; an installed package runs the compiled
4
+ // JavaScript (the tarball ships it, not src/).
5
5
  import { existsSync } from "node:fs";
6
6
 
7
7
  const checkout = existsSync(new URL("../tsconfig.json", import.meta.url));
@@ -11,13 +11,9 @@ const checkout = existsSync(new URL("../tsconfig.json", import.meta.url));
11
11
  *
12
12
  * @returns {Promise<typeof import("../src/installers/cli.ts")>}
13
13
  */
14
- async function entry() {
15
- if (checkout) {
16
- if (typeof globalThis.Bun !== "undefined") return import("../src/installers/cli.ts");
17
- const { createJiti } = await import("jiti");
18
-
19
- return createJiti(import.meta.url).import("../src/installers/cli.ts");
20
- }
14
+ function entry() {
15
+ // Node strips the source's types by default from 22.18
16
+ if (checkout) return import("../src/installers/cli.ts");
21
17
 
22
18
  // typed as the source it compiles from, so lint reads the same types with or without a build
23
19
  return /** @type {Promise<typeof import("../src/installers/cli.ts")>} */ (import("../dist/installers/cli.js"));
package/dist/cli.js CHANGED
@@ -25,6 +25,7 @@ import { parseGenerate, usage, UsageError } from "./gen/args.js";
25
25
  import { FORMATTERS, formatterFor, missingFormatter } from "./gen/formatters.js";
26
26
  import { runCli } from "./gen/process.js";
27
27
  import { shippedFiles } from "./gen/shipped.js";
28
+ import { SWITCH_ON } from "./gen/switch-on.constants.js";
28
29
  import { optionsFor } from "./gen/targets.js";
29
30
  import { writeTarget } from "./gen/write.js";
30
31
  import { appRef, loadAppDocument } from "./ir/load.js";
@@ -33,11 +34,12 @@ import { release } from "./release/cli.js";
33
34
  function sdkOf(target, document, options, metadata) {
34
35
  switch (target) {
35
36
  case "ts": {
36
- // mapped key by key, never spread: `options` holds strings, and `tanstackQuery` is a boolean —
37
+ // mapped key by key, never spread: `options` holds strings, and `singleFlight` and `tanstackQuery` are booleans —
37
38
  // a spread under a cast would make "false" as truthy as "true"
38
39
  return generateSdkPackage(document, {
39
40
  name: options.name ?? "SDK",
40
41
  ...(options.packageName === undefined ? {} : { packageName: options.packageName }),
42
+ singleFlight: options.singleFlight === SWITCH_ON,
41
43
  ...(options.stem === undefined ? {} : { stem: options.stem }),
42
44
  tanstackQuery: options.tanstackQuery === "true",
43
45
  ...(options.version === undefined ? {} : { version: options.version }),
@@ -1,9 +1,26 @@
1
+ /**
2
+ * One operation (§4.4, §4.8; contract 47 §2): its private `Operation` field (`Accept` for a text or binary answer,
3
+ * `Invalidates` for its `x-invalidate` targets), its method, the types the JSON context must list for it, and its
4
+ * call plan. A method takes its path params as `string` in path order, then a required body, the required query
5
+ * and header params, an optional body, the optional ones, `idempotencyKey` on an idempotent op, `headersInto` where
6
+ * the op declares response headers (Fc7), a stream's own fields, `options` and `cancellationToken` (C#4). Its body
7
+ * by kind is sdk-body.ts's, its answer sdk-answer.ts's, a stream's its `CsStream`'s (contract 50 §2): a stream takes
8
+ * no idempotency key, an SSE one asks for `text/event-stream`, and a declared param a stream field carries gets no
9
+ * parameter. Its body is one call into the transport, a stream's arguments then its answer's (and their type infos) after the `Call`, the
10
+ * signature on one line and the call on the next (Fb8). Its `client.Safe` twin (C#2, bit 21 i5) restates the
11
+ * signature and answers `Task<Result<T>>` (`Task<Result>` for no body) through `Transport.Safe` and the very method,
12
+ * its options given a response box; a connection's twin is the very method. A param named like one of the method's
13
+ * own locals or its stream's fields is `…2`, a keyword `@`-escaped (H52); the twin's lambda takes `_o`, which no
14
+ * param is (a `_` leads a name only before a digit).
15
+ */
16
+ import type { InvalidatedRead } from "../../ir/invalidate-reads.ts";
1
17
  import type { SdkOp } from "../../ir/sdk-model.ts";
2
18
  import type { CSharpCallPlan } from "./sdk-plan.ts";
3
19
  import { type CsTypeContext } from "./types.ts";
4
- /** What every method of one SDK shares: the type context. */
20
+ /** The type context, and each write's reads by operationId (`invalidateReads`): what its `OnInvalidate` event names. */
5
21
  export type MethodEnv = {
6
22
  readonly at: CsTypeContext;
23
+ readonly reads: ReadonlyMap<string, readonly InvalidatedRead[]>;
7
24
  };
8
25
  /** How a rendered method spells a type the context lists: its runtime type, and its `<Context>.Default.<Name>`. */
9
26
  export type Spelling = {
@@ -161,13 +161,24 @@ function acceptOf(op) {
161
161
  return "text/event-stream";
162
162
  return op.success.kind === "binary" || op.success.kind === "text" ? op.success.contentType : undefined;
163
163
  }
164
- /** The `Operation` field: method, path, path params, `Idempotent`, then `Accept` and `Invalidates` when they apply. */
165
- function operationField({ field, keyed, op, path }) {
164
+ /** The `Operation` members a write's `OnInvalidate` event needs: its operationId and the reads it makes stale. */
165
+ function readsOf(op, reads) {
166
+ if (reads === undefined || reads.length === 0)
167
+ return [];
168
+ const each = reads.map((read) => `new(${csString(read.operationId)}, [${read.params.map(csString).join(", ")}])`);
169
+ return [`By: ${csString(op.id)}`, `Reads: [${each.join(", ")}]`];
170
+ }
171
+ /**
172
+ * The `Operation` field: method, path, path params, `Idempotent`, then `Accept`, `Invalidates` and the
173
+ * `OnInvalidate` reads when they apply.
174
+ */
175
+ function operationField({ field, keyed, op, path }, reads) {
166
176
  const accept = acceptOf(op);
167
177
  const named = [
168
178
  `Idempotent: ${keyed}`,
169
179
  ...(accept === undefined ? [] : [`Accept: ${csString(accept)}`]),
170
180
  ...(op.invalidates.length === 0 ? [] : [`Invalidates: [${op.invalidates.map(csString).join(", ")}]`]),
181
+ ...readsOf(op, reads),
171
182
  ];
172
183
  const params = path.map(({ param }) => csString(param.name)).join(", ");
173
184
  return ` private static readonly Operation ${field} = new(${csString(op.method)}, ${csString(op.path)}, [${params}], ${named.join(", ")});`;
@@ -184,7 +195,7 @@ export function csMethod(op, name, field, env) {
184
195
  const keyed = op.idempotent && stream === null;
185
196
  const parts = { answer, body, field, headers, keyed, name, op, params, path, stream };
186
197
  return {
187
- field: operationField(parts),
198
+ field: operationField(parts, env.reads.get(op.id)),
188
199
  lines: (spell) => methodLines(parts, spell),
189
200
  plan: planOf(parts),
190
201
  twin: (spell) => twinLines(parts, spell),
@@ -10,6 +10,7 @@
10
10
  * reports every name it emits other than the spec's (`notices`, shared/mirror.ts), never silently.
11
11
  */
12
12
  import { toIR } from "../../ir/build.js";
13
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
13
14
  import { sdkModel } from "../../ir/sdk-model.js";
14
15
  import { compareCodeUnits, csTypeName } from "../shared/lang.js";
15
16
  import { packageOn } from "../shared/metadata.js";
@@ -67,7 +68,9 @@ function emitCSharp(document, options, shipped) {
67
68
  renamed,
68
69
  what: "component",
69
70
  }));
70
- const env = { at, client: id.client, context: id.context, notices, ops: model.opsById };
71
+ const { reads, warnings } = invalidateReads(ir);
72
+ notices.push(...warnings.map((warning) => `csharp: ${warning}`));
73
+ const env = { at, client: id.client, context: id.context, notices, ops: model.opsById, reads };
71
74
  const client = clientDecls(ir, env);
72
75
  const decls = [...components, ...[...at.decls].sort(([a], [b]) => compareCodeUnits(a, b))];
73
76
  const types = [...decls.map(([, text]) => text), ...(errorKey === null ? [] : [errorKey])].join("\n\n");
@@ -1,3 +1,10 @@
1
+ /**
2
+ * One operation as a Go method (G1): `(ctx, <path params in path order>, <body>?, opts *<Op>Opts,
3
+ * reqOpts ...RequestOption)`, filling the runtime's `call` and handing it to `doRequest`, or to its
4
+ * stream's runtime call (`sse.ts`, `ws.ts`). The query and header params ride on `<Op>Opts`, sent
5
+ * only when set. Spec text reaches the source only through the shared escape layer.
6
+ */
7
+ import type { InvalidatedRead } from "../../ir/invalidate-reads.ts";
1
8
  import { type SdkBody, type SdkOp, type SdkResponseKind, type SdkStream } from "../../ir/sdk-model.ts";
2
9
  import { type GoSends } from "./sdk-answer.ts";
3
10
  import { type GoPart } from "./sdk-body.ts";
@@ -47,8 +54,10 @@ export type GoMethod = {
47
54
  readonly twin: Twin;
48
55
  };
49
56
  /** What every method of one SDK shares: the type context it hoists into. */
57
+ /** The type context, and each write's reads by operationId (`invalidateReads`): what its `OnInvalidate` event names. */
50
58
  export type MethodEnv = {
51
59
  readonly at: GoTypeContext;
60
+ readonly reads: ReadonlyMap<string, readonly InvalidatedRead[]>;
52
61
  };
53
62
  /** Where a method lives: its receiver's type, and the expression reaching the `*Client` from it. */
54
63
  export type Receiver = {
@@ -40,6 +40,7 @@ const METHOD_LOCALS = [
40
40
  "setIdempotencyKey",
41
41
  "sseData",
42
42
  "sseFail",
43
+ "staleRead",
43
44
  "streamEvents",
44
45
  "streamText",
45
46
  "textField",
@@ -120,6 +121,13 @@ function callMembers(op, path, body, client) {
120
121
  ...(path.lines.length > 0 ? ["params: params"] : []),
121
122
  ];
122
123
  }
124
+ /** The `call` literal's `OnInvalidate` members: its operationId and the reads a success makes stale, for a write. */
125
+ function invalidatingMembers(op, reads) {
126
+ if (reads === undefined || reads.length === 0)
127
+ return [];
128
+ const each = reads.map((read) => `{${goString(read.operationId)}, []string{${read.params.map(goString).join(", ")}}}`);
129
+ return [`by: ${goString(op.id)}`, `reads: []staleRead{${each.join(", ")}}`];
130
+ }
123
131
  /** The twin of a method of `op` returning `returns`, taking `params` before its RequestOptions. */
124
132
  function twinOf(op, returns, params) {
125
133
  const answered = returns.slice("(".length, -", error)".length);
@@ -150,12 +158,13 @@ export function goMethod(op, name, receiver, env) {
150
158
  `opts *${opts}`,
151
159
  "reqOpts ...RequestOption",
152
160
  ];
161
+ const members = [...callMembers(op, path, body, receiver.client), ...invalidatingMembers(op, env.reads.get(op.id))];
153
162
  const lines = [
154
163
  ...methodDoc(op, name, stream),
155
164
  `func (r *${receiver.type}) ${name}(${params.join(", ")}) ${shape.returns} {`,
156
165
  ...path.lines,
157
166
  ...(body ? body.lines(shape.fail) : []),
158
- `\tc := &call{${callMembers(op, path, body, receiver.client).join(", ")}}`,
167
+ `\tc := &call{${members.join(", ")}}`,
159
168
  ...optsLines(op, fields, streamOpts),
160
169
  ...shape.tail(receiver.client),
161
170
  "}",
@@ -7,6 +7,7 @@
7
7
  * generated-code marker.
8
8
  */
9
9
  import { toIR } from "../../ir/build.js";
10
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
10
11
  import { sdkModel } from "../../ir/sdk-model.js";
11
12
  import { lineComment } from "../shared/escape.js";
12
13
  import { compareCodeUnits } from "../shared/lang.js";
@@ -72,9 +73,9 @@ function emitGo(document, options) {
72
73
  const at = goTypeContext(ir);
73
74
  // components first: the client's hoisted types then land beside them
74
75
  const components = componentDecls(ir, at);
75
- const ops = model.opsById;
76
+ const { reads, warnings } = invalidateReads(ir);
76
77
  const notices = [];
77
- const client = clientDecls(ir, { at, notices, ops });
78
+ const client = clientDecls(ir, { at, notices, ops: model.opsById, reads });
78
79
  const errorKeys = goErrorKeys(model, at);
79
80
  const hoisted = [...at.decls].sort(([a], [b]) => compareCodeUnits(a, b)).map(([, decl]) => decl);
80
81
  const features = {
@@ -92,7 +93,7 @@ function emitGo(document, options) {
92
93
  ["json", "encoding/json"],
93
94
  ]),
94
95
  },
95
- notices,
96
+ notices: [...notices, ...warnings.map((warning) => `go: ${warning}`)],
96
97
  packages: [packageOn("go", modulePath, options.version)],
97
98
  plans: client.plans,
98
99
  };
@@ -110,6 +110,7 @@ const SETTERS = [
110
110
  ["onRequest", "RequestHook"],
111
111
  ["onResponse", "ResponseHook"],
112
112
  ["onAuthExpired", "Supplier<String>"],
113
+ ["onInvalidate", "InvalidateHook"],
113
114
  ["onLog", "Consumer<LogEntry>"],
114
115
  ["redirect", "RedirectPolicy"],
115
116
  ["maxResponseBytes", "long"],
@@ -6,16 +6,21 @@
6
6
  * JSON as the mapper writes it, a form urlencoded, text as its raw bytes, binary as sized bytes or a one-shot stream,
7
7
  * multipart as hand-built parts under a `clients-<uuid>` boundary.
8
8
  */
9
+ import type { InvalidatedRead } from "../../ir/invalidate-reads.ts";
9
10
  import type { IRSchema } from "../../ir/model.ts";
10
11
  import type { SdkOp } from "../../ir/sdk-model.ts";
11
12
  import { type Expr } from "./layout.ts";
12
13
  import { type JavaTypeContext } from "./models.ts";
13
14
  import { type JavaHeaders } from "./sdk-headers.ts";
14
15
  import type { JavaCallPlan } from "./sdk-plan.ts";
15
- /** What an operation's text needs: the type context its types hoist into, and the array test. */
16
+ /**
17
+ * What an operation's text needs: the type context its types hoist into, the array test, and each write's reads by
18
+ * operationId (`invalidateReads`): what its `onInvalidate` event names.
19
+ */
16
20
  export type OpEnv = {
17
21
  readonly ctx: JavaTypeContext;
18
22
  readonly isArray: (schema: IRSchema) => boolean;
23
+ readonly reads: ReadonlyMap<string, readonly InvalidatedRead[]>;
19
24
  };
20
25
  /** One operation's text and plan, before its accessors are known. */
21
26
  export type JavaOp = {
@@ -141,8 +141,19 @@ function methodLines(op, site, env) {
141
141
  ]),
142
142
  ];
143
143
  }
144
- /** The `Operation` constant: the method, the path template, the path params in path order, accept and idempotence. */
145
- function constantLines(op, constant) {
144
+ /** A write's `onInvalidate` members: its operationId and the reads it makes stale; `null` and none without reads. */
145
+ function readItems(op, reads) {
146
+ const each = (reads ?? []).map((read) => newOf("Operation.Read", [
147
+ javaString(read.operationId),
148
+ array("String[]", read.params.map((name) => javaString(name))),
149
+ ]));
150
+ return [lit(each.length === 0 ? "null" : javaString(op.id)), array("Operation.Read[]", each)];
151
+ }
152
+ /**
153
+ * The `Operation` constant: the method, the path template, the path params in path order, accept and idempotence,
154
+ * then a write's targets, operationId and reads.
155
+ */
156
+ function constantLines(op, constant, reads) {
146
157
  const names = op.pathSegments.flatMap((segment) => (segment.kind === "param" ? [segment.name] : []));
147
158
  const accept = acceptOf(op);
148
159
  const items = [
@@ -155,6 +166,7 @@ function constantLines(op, constant) {
155
166
  ? []
156
167
  : [
157
168
  array("String[]", op.invalidates.map((target) => javaString(target))),
169
+ ...readItems(op, reads),
158
170
  ]),
159
171
  ];
160
172
  return field(2, {
@@ -206,7 +218,7 @@ export function javaOp(op, name, env) {
206
218
  ? null
207
219
  : { lines: multipartRecordLines(multipart.name, op.id, multipart.components), name: multipart.name },
208
220
  constant,
209
- constantLines: constantLines(op, constant),
221
+ constantLines: constantLines(op, constant, env.reads.get(op.id)),
210
222
  headers,
211
223
  helper: multipartHelper(op, env),
212
224
  lines: methodLines(op, { fields, headers, name }, env),
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { readFileSync } from "node:fs";
8
8
  import { toIR } from "../../ir/build.js";
9
+ import { invalidateReads } from "../../ir/invalidate-reads.js";
9
10
  import { sdkModel } from "../../ir/sdk-model.js";
10
11
  import { compareCodeUnits } from "../shared/lang.js";
11
12
  import { packageOn } from "../shared/metadata.js";
@@ -97,6 +98,9 @@ const OPERATION_FILES = [
97
98
  "HttpException",
98
99
  "Hops",
99
100
  "Hooks",
101
+ "InvalidateEvent",
102
+ "InvalidateHook",
103
+ "InvalidateTarget",
100
104
  "LogEntry",
101
105
  "Operation",
102
106
  "RawResponse",
@@ -172,6 +176,7 @@ function emitJava(document, options) {
172
176
  const ctx = javaTypeContext(ir, [pkg.clientName]);
173
177
  const isArray = (schema) => model.resolve(schema).kind === "array";
174
178
  const operations = model.ops.length > 0;
179
+ const { reads, warnings } = invalidateReads(ir);
175
180
  const env = {
176
181
  client: pkg.clientName,
177
182
  ctx,
@@ -180,6 +185,7 @@ function emitJava(document, options) {
180
185
  notices: [],
181
186
  ops: model.opsById,
182
187
  packageName: pkg.packageName,
188
+ reads,
183
189
  };
184
190
  const surface = operations ? surfaceOf(ir, env) : { files: {}, plans: [] };
185
191
  const errors = operations
@@ -211,7 +217,7 @@ function emitJava(document, options) {
211
217
  const renamed = ctx.names.renamed.map((rename) => renameNotice("java", rename));
212
218
  return {
213
219
  files: Object.fromEntries(Object.entries(files).sort(([a], [b]) => compareCodeUnits(a, b))),
214
- notices: [...new Set([...env.notices, ...renamed])],
220
+ notices: [...new Set([...env.notices, ...renamed, ...warnings.map((warning) => `java: ${warning}`)])],
215
221
  plans: surface.plans,
216
222
  };
217
223
  }
@@ -1,3 +1,12 @@
1
+ /**
2
+ * One operation (G1, G3, G5): its `_<NAME>: Operation[T]` constant, its method on the resource classes (async
3
+ * only for a stream), its `<Op>Headers` TypedDict, and its call plan. A method takes `self`, its path params as
4
+ * `str` in path order, then its body, then keyword-only query and header params (a required one without a
5
+ * default), `idempotency_key`, `headers_into`, its stream's own fields, and `options` last. The body is one
6
+ * call into the transport, evaluating only `self` and module globals named `_<UPPER>`: no parameter can
7
+ * shadow one (S3). Spec text reaches the source only through the shared escape layer.
8
+ */
9
+ import type { InvalidatedRead } from "../../ir/invalidate-reads.ts";
1
10
  import { type SdkOp } from "../../ir/sdk-model.ts";
2
11
  import { NameScope } from "../shared/lang.ts";
3
12
  import type { PythonCallPlan } from "./sdk-plan.ts";
@@ -12,6 +21,8 @@ export type MethodEnv = {
12
21
  readonly imports: Set<string>;
13
22
  /** the runtime names types.py imports (a multipart body's `FilePart`, a named event's `SseEventOf`) */
14
23
  readonly typesImports: Set<string>;
24
+ /** each write's reads by operationId (`invalidateReads`): what its `on_invalidate` event names */
25
+ readonly reads: ReadonlyMap<string, readonly InvalidatedRead[]>;
15
26
  };
16
27
  /**
17
28
  * One operation's constant, its methods (no sync one for a stream) written given the builtins its class's