@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
@@ -0,0 +1,160 @@
1
+ import { ClientError } from "./error.ts"
2
+ import { type Answer, parseBody } from "./response.ts"
3
+ import type { CallInput, SDKClient, ServiceEntry } from "./sdk.ts"
4
+ import type { FlightBatch, FlightOp, FlightRead } from "./single-flight-batch.ts"
5
+ import { bodyOf } from "./single-flight-body.ts"
6
+ import { BATCH_VERSION } from "./sdk-single-flight.constants.ts"
7
+ import { FIRST_SUCCESS, LAST_SUCCESS, NO_ANSWER_STATUS, TIMED_OUT_STATUS } from "./single-flight.constants.ts"
8
+
9
+ /** How far the reads of one batch may go: their count, their time and their bytes in all. */
10
+ export type FlightLimits = { maxReadBytes: number; maxReads: number; readBudgetMs: number }
11
+
12
+ /** The write's answer: its status, `content-type` and declared headers, and its body. */
13
+ export type SingleFlightWrite = { body: unknown; headers: Record<string, string>; status: number }
14
+
15
+ /** A read that failed: the status it ended in, and the API's error body when it fit the byte budget. */
16
+ export type SingleFlightReadError = { body?: unknown; status: number }
17
+
18
+ /** One read's entry: its data, or the error it ended in. */
19
+ export type SingleFlightRead = { data: unknown; id: string } | { error: SingleFlightReadError; id: string }
20
+
21
+ /** The one answer a batch gets: the write's, then each read's in the order asked. */
22
+ export type SingleFlightEnvelope = { reads: SingleFlightRead[]; v: typeof BATCH_VERSION; write: SingleFlightWrite }
23
+
24
+ /** A batch run: its envelope, and the write's `Set-Cookie` values, apart. */
25
+ export type Flown = { cookies: string[]; envelope: SingleFlightEnvelope }
26
+
27
+ /** A REST call of the SDK, as `raw` makes it: its Response, unread. */
28
+ type RawCall = (input: CallInput) => Promise<Response>
29
+
30
+ /** The SDK as a walk over it sees it: a Proxy over the map's namespaces, each key a namespace or a call. */
31
+ type SdkMember = { readonly [key: string]: SdkMember | undefined }
32
+
33
+ /** What every read of a batch shares: the time left, as one signal, and the bytes left. */
34
+ type ReadRun = { budget: { left: number }; signal: AbortSignal }
35
+
36
+ /** Each read refetches past any cache. */
37
+ const NO_CACHE = { "cache-control": "no-cache" }
38
+
39
+ /** Whether `value` may hold members: an SDK namespace, a Proxy over the map's keys. */
40
+ function isMember(value: unknown): value is SdkMember {
41
+ return (typeof value === "object" || typeof value === "function") && value !== null
42
+ }
43
+
44
+ /** Whether `value` is a call: the SDK's members at a map entry are functions. */
45
+ function isCall(value: unknown): value is RawCall {
46
+ return typeof value === "function"
47
+ }
48
+
49
+ /** The SDK member at `path`: the call the service map names there, made with `raw` to answer its Response. */
50
+ function callOf(sdk: SDKClient, path: readonly string[]): RawCall {
51
+ let member: unknown = sdk
52
+ for (const key of path) member = isMember(member) ? member[key] : undefined
53
+ if (!isCall(member)) throw new TypeError(`single-flight: the SDK has no call at ${path.join(".")}`)
54
+ return member
55
+ }
56
+
57
+ /** The write's headers the envelope carries: `content-type` and the ones its entry declares, never any other. */
58
+ function headersOf(response: Response, entry: ServiceEntry) {
59
+ const names = ["content-type", ...(entry.headers ?? [])]
60
+ return Object.fromEntries(
61
+ names.flatMap((name) => {
62
+ const value = response.headers.get(name)
63
+ return value === null ? [] : [[name, value]]
64
+ }),
65
+ )
66
+ }
67
+
68
+ /** The write's Response and its decoded body, of any status; a throw when it got no answer at all. */
69
+ async function answerOf(sdk: SDKClient, op: FlightOp, input: CallInput): Promise<Answer> {
70
+ try {
71
+ const response = await callOf(sdk, op.path)({ ...input, raw: true })
72
+ const data = await parseBody(response, op.entry.method, op.entry.empty === true ? null : op.entry.accept)
73
+ return { data, response }
74
+ } catch (e) {
75
+ if (!(e instanceof ClientError) || e.status === 0)
76
+ throw new Error("single-flight: the write got no answer", { cause: e })
77
+ return { data: e.body, response: e.response }
78
+ }
79
+ }
80
+
81
+ /** The write run once with its input and its own Idempotency-Key. */
82
+ async function write(sdk: SDKClient, op: FlightOp, input: CallInput): Promise<Flown> {
83
+ const { data, response } = await answerOf(sdk, op, input)
84
+ const envelope: SingleFlightEnvelope = {
85
+ reads: [],
86
+ v: BATCH_VERSION,
87
+ write: { body: data, headers: headersOf(response, op.entry), status: response.status },
88
+ }
89
+ return { cookies: response.headers.getSetCookie(), envelope }
90
+ }
91
+
92
+ /** `promise`, or the signal's reason once it aborts first. */
93
+ function within<T>(signal: AbortSignal, promise: Promise<T>): Promise<T> {
94
+ const aborted = new Promise<never>((_resolve, reject) => {
95
+ if (signal.aborted) reject(signal.reason)
96
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true })
97
+ })
98
+ return Promise.race([promise, aborted])
99
+ }
100
+
101
+ /** `response`'s body, each chunk taken from what is left of the run's bytes; cancelled past it or at the deadline. */
102
+ async function counted(response: Response, run: ReadRun): Promise<Uint8Array<ArrayBuffer>> {
103
+ function take(chunk: Uint8Array): boolean {
104
+ run.budget.left -= chunk.byteLength
105
+ return run.budget.left >= 0 && !run.signal.aborted
106
+ }
107
+ const bytes = await bodyOf({ body: response.body, signal: run.signal, take })
108
+ if (bytes === undefined || run.signal.aborted) throw new RangeError("over the read budget")
109
+ return bytes
110
+ }
111
+
112
+ /** The error a read that failed with `e` gets: the API's status and body when it answered, else ours. */
113
+ function errorOf(e: ClientError | undefined, run: ReadRun): SingleFlightReadError {
114
+ if (e === undefined || e.status === 0) return { status: run.signal.aborted ? TIMED_OUT_STATUS : NO_ANSWER_STATUS }
115
+ const size = e.body === null ? 0 : new TextEncoder().encode(JSON.stringify(e.body)).byteLength
116
+ if (size === 0 || size > run.budget.left) return { status: e.status }
117
+ run.budget.left -= size
118
+ return { body: e.body, status: e.status }
119
+ }
120
+
121
+ /** One read: sent with no-cache and the run's signal, its body counted, then decoded; an error entry when it fails. */
122
+ async function read(sdk: SDKClient, entry: FlightRead, run: ReadRun): Promise<SingleFlightRead> {
123
+ try {
124
+ const input = { ...entry.input, headers: NO_CACHE, raw: true, signal: run.signal }
125
+ const response = await within(run.signal, callOf(sdk, entry.op.path)(input))
126
+ const bytes = await counted(response, run)
127
+ const decoded = new Response(bytes, { headers: response.headers, status: response.status })
128
+ return { data: await parseBody(decoded, entry.op.entry.method), id: entry.id }
129
+ } catch (e) {
130
+ return { error: errorOf(e instanceof ClientError ? e : undefined, run), id: entry.id }
131
+ }
132
+ }
133
+
134
+ /** The reads, in parallel, cut at the time budget, sharing the byte budget; in the order asked. */
135
+ async function readAll(
136
+ sdk: SDKClient,
137
+ reads: readonly FlightRead[],
138
+ limits: FlightLimits,
139
+ ): Promise<SingleFlightRead[]> {
140
+ const deadline = new AbortController()
141
+ const timer = setTimeout(
142
+ () => deadline.abort(new Error("single-flight: the read budget ran out")),
143
+ limits.readBudgetMs,
144
+ )
145
+ const run: ReadRun = { budget: { left: limits.maxReadBytes }, signal: deadline.signal }
146
+ try {
147
+ return await Promise.all(reads.map((entry) => read(sdk, entry, run)))
148
+ } finally {
149
+ clearTimeout(timer)
150
+ }
151
+ }
152
+
153
+ /** Run `batch` on `sdk`: the write once, then, only when it answered 2xx, the reads. */
154
+ export async function fly(sdk: SDKClient, batch: FlightBatch, limits: FlightLimits): Promise<Flown> {
155
+ const flown = await write(sdk, batch.write, batch.input)
156
+ const { status } = flown.envelope.write
157
+ if (status < FIRST_SUCCESS || status > LAST_SUCCESS) return flown
158
+ flown.envelope.reads = await readAll(sdk, batch.reads, limits)
159
+ return flown
160
+ }
@@ -0,0 +1,31 @@
1
+ /** The only method and media type a batch is taken with. */
2
+ export const BATCH_METHOD = "POST"
3
+ export const BATCH_MEDIA_TYPE = "application/json"
4
+
5
+ /** The only `Sec-Fetch-Site` a browser may send a batch with. */
6
+ export const SAME_ORIGIN = "same-origin"
7
+
8
+ /** The method every read is sent with. */
9
+ export const READ_METHOD = "GET"
10
+
11
+ /** The problem `type` of a write that got no answer (a refusal's is the client's `REFUSED`). */
12
+ export const UNANSWERED = "urn:workerstack:single-flight:unanswered"
13
+
14
+ /** The statuses the handler answers with: the envelope, and a write that got no answer (a refusal's is the client's
15
+ `REFUSED_STATUS`). */
16
+ export const ANSWERED_STATUS = 200
17
+ export const UNANSWERED_STATUS = 502
18
+
19
+ /** A read's own error statuses: no usable answer (no connection, over the byte budget, not JSON), and out of time. */
20
+ export const NO_ANSWER_STATUS = 502
21
+ export const TIMED_OUT_STATUS = 504
22
+
23
+ /** The success statuses: a write outside them runs no read. */
24
+ export const FIRST_SUCCESS = 200
25
+ export const LAST_SUCCESS = 299
26
+
27
+ /** The defaults: a batch body's bytes, and the reads' bytes in all and their time in milliseconds (the reads per
28
+ batch: the client's `DEFAULT_MAX_READS`). */
29
+ export const DEFAULT_MAX_BODY_BYTES = 64 * 1024
30
+ export const DEFAULT_MAX_READ_BYTES = 1024 * 1024
31
+ export const DEFAULT_READ_BUDGET_MS = 2000
@@ -0,0 +1,158 @@
1
+ import { parseMediaType } from "./media-type.ts"
2
+ import type { SDKClient, ServiceMap } from "./sdk.ts"
3
+ import { DEFAULT_MAX_READS, REFUSED, REFUSED_STATUS } from "./sdk-single-flight.constants.ts"
4
+ import { type FlightOp, type Json, operationsOf, parseBatch } from "./single-flight-batch.ts"
5
+ import { bodyOf } from "./single-flight-body.ts"
6
+ import { type FlightLimits, fly, type Flown, type SingleFlightEnvelope } from "./single-flight-run.ts"
7
+ import {
8
+ ANSWERED_STATUS,
9
+ BATCH_MEDIA_TYPE,
10
+ BATCH_METHOD,
11
+ DEFAULT_MAX_BODY_BYTES,
12
+ DEFAULT_MAX_READ_BYTES,
13
+ DEFAULT_READ_BUDGET_MS,
14
+ SAME_ORIGIN,
15
+ UNANSWERED,
16
+ UNANSWERED_STATUS,
17
+ } from "./single-flight.constants.ts"
18
+
19
+ /** How far a single-flight batch may go, and who may send one. */
20
+ export type SingleFlightOptions = {
21
+ /** the origins a browser may send from; the handler's own origin when left out */
22
+ allowedOrigins?: readonly string[]
23
+ /** the most bytes a batch's body may hold, counted while it is read. Default 64 KiB. */
24
+ maxBodyBytes?: number
25
+ /** the most bytes the reads' bodies may hold in all, counted before they are decoded. Default 1 MiB. */
26
+ maxReadBytes?: number
27
+ /** the most reads one batch may ask for. Default 10. */
28
+ maxReads?: number
29
+ /** how long the reads may take in all, in milliseconds, once the write answered. Default 2000. */
30
+ readBudgetMs?: number
31
+ }
32
+
33
+ /** The SDK a request runs on: the app's, made for that request, forwarding only the auth it chooses. */
34
+ export type SingleFlightSdk<S extends SDKClient> = (request: Request) => S
35
+
36
+ const DEFAULT_LIMITS: FlightLimits = {
37
+ maxReadBytes: DEFAULT_MAX_READ_BYTES,
38
+ maxReads: DEFAULT_MAX_READS,
39
+ readBudgetMs: DEFAULT_READ_BUDGET_MS,
40
+ }
41
+
42
+ /** `options`' limits, each left out one its default. */
43
+ function limitsOf(options: SingleFlightOptions): FlightLimits {
44
+ return {
45
+ maxReadBytes: options.maxReadBytes ?? DEFAULT_LIMITS.maxReadBytes,
46
+ maxReads: options.maxReads ?? DEFAULT_LIMITS.maxReads,
47
+ readBudgetMs: options.readBudgetMs ?? DEFAULT_LIMITS.readBudgetMs,
48
+ }
49
+ }
50
+
51
+ /** `text` parsed as JSON, or undefined when it is none. */
52
+ function parsedJson(text: string): Json | undefined {
53
+ try {
54
+ return JSON.parse(text) /* JSON.parse answers only JSON values */ as Json
55
+ } catch {
56
+ return undefined
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Run a batch on `sdk`: `{ v: 1, op, input, reads: [{ id, operationId, input }] }`, validated against the service
62
+ * map before anything runs (a refusal throws a TypeError), then the write once, then its reads in parallel. Its
63
+ * `Set-Cookie` headers are not in the envelope: `singleFlightHandler` copies them onto its answer.
64
+ */
65
+ export async function runFlight(map: ServiceMap, sdk: SDKClient, body: Json): Promise<SingleFlightEnvelope> {
66
+ const parsed = parseBatch(operationsOf(map), body, DEFAULT_LIMITS.maxReads)
67
+ if ("refused" in parsed) throw new TypeError(`single-flight: refused: ${parsed.refused}`)
68
+ const flown = await fly(sdk, parsed.batch, DEFAULT_LIMITS)
69
+ return flown.envelope
70
+ }
71
+
72
+ /** An `application/problem+json` answer of `type`, saying why in `detail`. */
73
+ function problem(status: number, type: string, detail: string): Response {
74
+ const headers = { "cache-control": "no-store", "content-type": "application/problem+json" }
75
+ return new Response(JSON.stringify({ detail, status, title: "Single-flight batch not run", type }), {
76
+ headers,
77
+ status,
78
+ })
79
+ }
80
+
81
+ /** Why `request` is refused before its body is read: its method, media type, or the browser's site or origin. */
82
+ function headerRefusal(request: Request, allowed: readonly string[] | undefined): string | undefined {
83
+ const site = request.headers.get("sec-fetch-site")
84
+ const origin = request.headers.get("origin")
85
+ if (request.method !== BATCH_METHOD) return "a batch is POSTed"
86
+ if (parseMediaType(request.headers.get("content-type"))?.essence !== BATCH_MEDIA_TYPE) return "the body is not JSON"
87
+ if (site !== null && site !== SAME_ORIGIN) return "the browser sent it from another site"
88
+ if (origin !== null && !(allowed ?? [new URL(request.url).origin]).includes(origin))
89
+ return "the origin is not allowed"
90
+ return undefined
91
+ }
92
+
93
+ /** `request`'s body as text, read no further than `max` bytes; undefined past it. */
94
+ async function bodyText(request: Request, max: number): Promise<string | undefined> {
95
+ if (Number(request.headers.get("content-length") ?? 0) > max) return undefined
96
+ let size = 0
97
+ function take(chunk: Uint8Array): boolean {
98
+ size += chunk.byteLength
99
+ return size <= max
100
+ }
101
+ const bytes = await bodyOf({ body: request.body, take })
102
+ return bytes === undefined ? undefined : new TextDecoder().decode(bytes)
103
+ }
104
+
105
+ /** The envelope as the handler's 200: JSON, never cached, the write's cookies each a header of its own. */
106
+ function answered(flown: Flown): Response {
107
+ const headers = new Headers({ "cache-control": "no-store", "content-type": BATCH_MEDIA_TYPE })
108
+ for (const cookie of flown.cookies) headers.append("set-cookie", cookie)
109
+ return new Response(JSON.stringify(flown.envelope), { headers, status: ANSWERED_STATUS })
110
+ }
111
+
112
+ /** What a handler holds for every request: the map's operations, its SDK maker and its limits. */
113
+ type Served = {
114
+ allowedOrigins: readonly string[] | undefined
115
+ getSdk: SingleFlightSdk<SDKClient>
116
+ limits: FlightLimits
117
+ maxBodyBytes: number
118
+ ops: ReadonlyMap<string, FlightOp>
119
+ }
120
+
121
+ /** One batch request: checked, read, validated, then run on the request's own SDK. */
122
+ async function handle(request: Request, served: Served): Promise<Response> {
123
+ const header = headerRefusal(request, served.allowedOrigins)
124
+ if (header !== undefined) return problem(REFUSED_STATUS, REFUSED, header)
125
+ const text = await bodyText(request, served.maxBodyBytes)
126
+ if (text === undefined) return problem(REFUSED_STATUS, REFUSED, "the body is over maxBodyBytes")
127
+ const parsed = parseBatch(served.ops, parsedJson(text) ?? null, served.limits.maxReads)
128
+ if ("refused" in parsed) return problem(REFUSED_STATUS, REFUSED, parsed.refused)
129
+ try {
130
+ return answered(await fly(served.getSdk(request), parsed.batch, served.limits))
131
+ } catch {
132
+ return problem(UNANSWERED_STATUS, UNANSWERED, "the write got no answer; it may or may not have run")
133
+ }
134
+ }
135
+
136
+ /**
137
+ * A fetch handler for single-flight batches over `map`: it refuses a batch before anything runs unless it is a
138
+ * JSON POST, from no browser or from an allowed origin, within `maxBodyBytes`, of one REST write and at most
139
+ * `maxReads` REST JSON reads with only params, search, json (the write's) and idempotencyKey (an idempotent write's).
140
+ * Then it runs the write once on `getSdk(request)`, with the caller's Idempotency-Key and no retry of its own (the
141
+ * SDK's own hooks may retry), and only after a 2xx the reads, in parallel, within `readBudgetMs` and `maxReadBytes`.
142
+ * It answers 200 with the envelope, never cached, the write's Set-Cookie headers copied on: a cookie only sticks
143
+ * when the API shares the handler's site. Make the SDK per request; it outlives none.
144
+ */
145
+ export function handlerOf<S extends SDKClient>(
146
+ map: ServiceMap,
147
+ getSdk: SingleFlightSdk<S>,
148
+ options: SingleFlightOptions = {},
149
+ ): (request: Request) => Promise<Response> {
150
+ const served: Served = {
151
+ allowedOrigins: options.allowedOrigins,
152
+ getSdk,
153
+ limits: limitsOf(options),
154
+ maxBodyBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,
155
+ ops: operationsOf(map),
156
+ }
157
+ return (request) => handle(request, served)
158
+ }
@@ -1,10 +1,11 @@
1
1
  /**
2
- * Turning a service map into query keys (bit 22): which entries are readable, how a route selector and a
3
- * `{param}` path meet at one spelling, and what key a read is cached under. One body of knowledge — an
4
- * `x-invalidate` target names a route and a key names a member path, and this is the only place that
5
- * crosses between them. `query.ts` holds the surfaces that use it.
2
+ * Turning a service map into query keys (bit 22): which entries are readable, what key a read is cached
3
+ * under, and which keys a write's `onInvalidate` event makes stale. The event names reads by operationId
4
+ * and a key names a member path, and this is the one place that crosses between them; `query.ts` holds
5
+ * the surfaces that use it.
6
6
  */
7
- import type { QueryKey } from "@tanstack/query-core"
7
+ import type { QueryClient, QueryKey } from "@tanstack/query-core"
8
+ import type { FreshReads, InvalidateEvent, InvalidateTarget, SingleFlightReadRequest } from "../ts/config.ts"
8
9
  import type { ServiceEntry, ServiceMap } from "../ts/sdk.ts"
9
10
 
10
11
  /** The one method a cache reads from; every other method is a write. */
@@ -15,7 +16,7 @@ export function isEntry(node: unknown): node is ServiceEntry {
15
16
  typeof node === "object" &&
16
17
  node !== null &&
17
18
  Object.hasOwn(node, "method") &&
18
- typeof (node as ServiceEntry).method === "string" &&
19
+ typeof (node /* narrowed to an own `method` just above */ as ServiceEntry).method === "string" &&
19
20
  Object.hasOwn(node, "path")
20
21
  )
21
22
  }
@@ -27,63 +28,8 @@ export function isStream(entry: ServiceEntry): boolean {
27
28
 
28
29
  /** Only an own key is an operation: never `toString`, `constructor` or `then`. */
29
30
  export function childOf(node: ServiceMap | ServiceEntry, key: string): ServiceMap | ServiceEntry | undefined {
30
- return Object.hasOwn(node, key) ? (node as Record<string, ServiceMap | ServiceEntry>)[key] : undefined
31
- }
32
-
33
- /** `/orgs/{id}` → `/orgs/:id`, so a `{param}` path and a `:param` selector meet at one spelling. */
34
- function normalizePath(path: string): string {
35
- return path
36
- .split("/")
37
- .map((segment) => {
38
- const braced = /^\{([^{}/]+)\}$/.exec(segment)
39
- return braced === null ? segment : `:${braced[1] as string}`
40
- })
41
- .join("/")
42
- }
43
-
44
- /** `GET /orgs/{id}` and `get /orgs/:id` normalize alike; a selector with no space has no method. */
45
- function normalizeSelector(selector: string): string | undefined {
46
- const space = selector.indexOf(" ")
47
- if (space <= 0) return undefined
48
- return `${selector.slice(0, space).toUpperCase()} ${normalizePath(selector.slice(space + 1))}`
49
- }
50
-
51
- export type Read = { member: string[]; params: readonly string[] }
52
-
53
- /**
54
- * Every readable entry by its normalized selector. An `x-invalidate` target names a route, and a query key
55
- * names a member path and its params, so this is the one table that turns one into the other. Built once
56
- * per helper set: a map walk per mutation would be the O(n) cost this avoids.
57
- */
58
- export function indexReads(map: ServiceMap): Map<string, Read> {
59
- const reads = new Map<string, Read>()
60
- const walk = (node: ServiceMap, member: string[]): void => {
61
- for (const key of Object.keys(node)) {
62
- const child = childOf(node, key)
63
- if (child === undefined) continue
64
- if (!isEntry(child)) {
65
- walk(child as ServiceMap, [...member, key])
66
- continue
67
- }
68
- if (child.method !== READ || isStream(child)) continue
69
- reads.set(`${READ} ${normalizePath(child.path)}`, {
70
- member: [...member, key],
71
- params: child.params ?? [],
72
- })
73
- }
74
- }
75
- walk(map, [])
76
- return reads
77
- }
78
-
79
- /** The `params` of an SDK input, string values only: a key holds what addresses a resource. */
80
- export function paramsOf(input: unknown): Record<string, string> {
81
- if (typeof input !== "object" || input === null || !Object.hasOwn(input, "params")) return {}
82
- const raw = (input as { params?: unknown }).params
83
- if (typeof raw !== "object" || raw === null) return {}
84
- const params: Record<string, string> = {}
85
- for (const [key, value] of Object.entries(raw)) if (typeof value === "string" && value !== "") params[key] = value
86
- return params
31
+ if (!Object.hasOwn(node, key)) return undefined
32
+ return (node /* an own key of a map node is a branch or an entry */ as { readonly [key: string]: ServiceMap })[key]
87
33
  }
88
34
 
89
35
  /**
@@ -95,7 +41,7 @@ export function paramsOf(input: unknown): Record<string, string> {
95
41
  * and would not hash. Two reads of one route that differ by search are two entries, which is the whole
96
42
  * point.
97
43
  *
98
- * `keyOf` is a FILTER: the prefix an `x-invalidate` target makes stale. A mutation knows its own path
44
+ * `targetKey` is a FILTER: the prefix an invalidation target makes stale. A write knows its own path
99
45
  * params and nothing about what a reader searched for, so it names `{ params }` at most and TanStack's
100
46
  * partial matching does the rest — `[sdk, …member, { params }]` matches a longer key that also carries
101
47
  * `search`, and `[sdk, …member]` matches every search there is.
@@ -114,39 +60,97 @@ export function readKey(sdkName: string, member: readonly string[], req: unknown
114
60
  */
115
61
  export const INFINITE = "infinite"
116
62
 
63
+ /** The prefix a target makes stale: its member path, plus `{ params }` when the target names any. */
64
+ function targetKey(sdkName: string, member: readonly string[], params: InvalidateTarget["params"]): QueryKey {
65
+ const prefix = [sdkName, ...member]
66
+ return Object.keys(params).length === 0 ? prefix : [...prefix, { params }]
67
+ }
68
+
69
+ /** The request keys a single-flight read takes: a plain read's key holds no other. */
70
+ const FLIGHT_KEYS: readonly string[] = ["params", "search"]
71
+
72
+ /** Whether `value` is a request a single-flight read can carry: an object of params and search only. */
73
+ function isFlightRequest(value: unknown): value is SingleFlightReadRequest["input"] {
74
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false
75
+ return Object.keys(value).every((name) => FLIGHT_KEYS.includes(name))
76
+ }
77
+
78
+ /** The request a plain read's key at `member` holds, or undefined for any other key (a paged one, say). */
79
+ function requestOf(key: QueryKey, at: number): SingleFlightReadRequest["input"] | undefined {
80
+ if (key.length === at) return {}
81
+ const req = key[at]
82
+ return key.length === at + 1 && isFlightRequest(req) ? req : undefined
83
+ }
84
+
117
85
  /**
118
- * The prefix an `x-invalidate` target makes stale: the read's member path, plus `{ params }` once every
119
- * path param has a value. One missing value leaves the bare prefix, which invalidates every query of that
120
- * read — the key-space answer to a partially resolved route, never a dropped target.
86
+ * The single-flight `select` that brings back the active plain reads a write's targets match in `client`, each by
87
+ * its query hash, so `invalidationHook` can seed it. A paged read, a disabled or unobserved one, and one whose
88
+ * `meta.singleFlight` is false are left to refetch as before.
121
89
  */
122
- export function keyOf(sdkName: string, read: Read, params: Record<string, string>): QueryKey {
123
- const prefix = [sdkName, ...read.member]
124
- if (read.params.length === 0) return prefix
125
- const filled: Record<string, string> = {}
126
- for (const name of read.params) {
127
- const value = params[name]
128
- if (value === undefined) return prefix
129
- filled[name] = value
90
+ export function activeReadsOf<Read extends string>(
91
+ client: QueryClient,
92
+ sdkName: string,
93
+ members: ReadonlyMap<string, readonly string[]>,
94
+ ): (targets: InvalidateTarget<Read>[]) => SingleFlightReadRequest<Read>[] {
95
+ return (targets) => {
96
+ const reads = new Map<string, SingleFlightReadRequest<Read>>()
97
+ for (const { operationId, params } of targets) {
98
+ const member = members.get(operationId)
99
+ if (member === undefined) continue
100
+ const filters = { queryKey: targetKey(sdkName, member, params), type: "active" as const }
101
+ for (const query of client.getQueryCache().findAll(filters)) {
102
+ const input = requestOf(query.queryKey, member.length + 1)
103
+ if (input === undefined || query.meta?.["singleFlight"] === false) continue
104
+ if (!reads.has(query.queryHash)) reads.set(query.queryHash, { id: query.queryHash, input, operationId })
105
+ }
106
+ }
107
+ return [...reads.values()]
130
108
  }
131
- return [...prefix, { params: filled }]
132
109
  }
133
110
 
134
- /** The keys a successful `selector` write makes stale. */
135
- export function invalidatedBy(
136
- reads: Map<string, Read>,
111
+ /** Put each fresh read in `client` by its hash, a refetch in flight cancelled first; the hashes it put. */
112
+ async function seed(client: QueryClient, fresh: FreshReads | undefined): Promise<Set<string>> {
113
+ const seeded = new Set<string>()
114
+ const cache = client.getQueryCache()
115
+ const each = [...(fresh?.data ?? [])].map(async ([hash, data]) => {
116
+ const query = cache.get(hash)
117
+ if (query === undefined) return
118
+ await client.cancelQueries({ exact: true, queryKey: query.queryKey })
119
+ client.setQueryData(query.queryKey, data)
120
+ seeded.add(hash)
121
+ })
122
+ await Promise.all(each)
123
+ return seeded
124
+ }
125
+
126
+ /** The filters a target's `queryKey` invalidates by: every match but a query `seeded` just put fresh data in. */
127
+ function filtersOf(queryKey: QueryKey, seeded: ReadonlySet<string>) {
128
+ if (seeded.size === 0) return { queryKey }
129
+ return { predicate: (query: { queryHash: string }) => !seeded.has(query.queryHash), queryKey }
130
+ }
131
+
132
+ /**
133
+ * The SDK `onInvalidate` hook that makes a write's targets stale in `client`: each target's key by its
134
+ * member path (`members`, operationId to path, which the emitted file builds from the document), an
135
+ * operationId it does not hold skipped. `cancelRefetch` restarts a refetch already running, so the read
136
+ * sees the write. The SDK awaits the hook, so a write resolves once its active reads have refetched: a
137
+ * failing refetch holds it through its retries but never rejects it (TanStack's `invalidateQueries`
138
+ * swallows a refetch error), and an infinite query refetches every page it holds. A single-flight write's
139
+ * fresh reads are put in the cache first and not refetched; a failed one, and every other match, are.
140
+ */
141
+ export function invalidationHook(
142
+ client: QueryClient,
137
143
  sdkName: string,
138
- entry: ServiceEntry,
139
- input: unknown,
140
- ): QueryKey[] {
141
- if (entry.invalidate === undefined || entry.invalidate.length === 0) return []
142
- const params = paramsOf(input)
143
- const keys: QueryKey[] = []
144
- for (const target of entry.invalidate) {
145
- const selector = normalizeSelector(target)
146
- if (selector === undefined) continue
147
- const read = reads.get(selector)
148
- if (read === undefined) continue
149
- keys.push(keyOf(sdkName, read, params))
144
+ members: ReadonlyMap<string, readonly string[]>,
145
+ ): (event: InvalidateEvent) => Promise<void> {
146
+ return async (event) => {
147
+ const seeded = await seed(client, event.fresh)
148
+ const keys: QueryKey[] = []
149
+ for (const target of event.targets) {
150
+ const member = members.get(target.operationId)
151
+ if (member !== undefined) keys.push(targetKey(sdkName, member, target.params))
152
+ }
153
+ const each = keys.map((key) => client.invalidateQueries(filtersOf(key, seeded), { cancelRefetch: true }))
154
+ await Promise.all(each)
150
155
  }
151
- return keys
152
156
  }