@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.
- package/README.md +175 -21
- package/bin/clients.js +5 -6
- package/bin/installgen.js +5 -9
- package/dist/cli.js +3 -1
- package/dist/emit/csharp/sdk-method.d.ts +18 -1
- package/dist/emit/csharp/sdk-method.js +14 -3
- package/dist/emit/csharp/sdk.js +4 -1
- package/dist/emit/go/sdk-method.d.ts +9 -0
- package/dist/emit/go/sdk-method.js +10 -1
- package/dist/emit/go/sdk.js +4 -3
- package/dist/emit/java/sdk-client.js +1 -0
- package/dist/emit/java/sdk-op.d.ts +6 -1
- package/dist/emit/java/sdk-op.js +15 -3
- package/dist/emit/java/sdk.js +7 -1
- package/dist/emit/python/sdk-method.d.ts +11 -0
- package/dist/emit/python/sdk-method.js +15 -0
- package/dist/emit/python/sdk.js +5 -1
- package/dist/emit/rust/sdk-method.d.ts +12 -1
- package/dist/emit/rust/sdk-method.js +10 -2
- package/dist/emit/rust/sdk.js +4 -1
- package/dist/emit/ts/http.d.ts +8 -0
- package/dist/emit/ts/http.js +48 -3
- package/dist/emit/ts/package.js +1 -0
- package/dist/emit/ts/sdk-types-preamble.js +10 -2
- package/dist/emit/ts/sdk-types.d.ts +0 -5
- package/dist/emit/ts/sdk-types.js +52 -8
- package/dist/emit/ts/sdk.d.ts +3 -1
- package/dist/emit/ts/sdk.js +40 -8
- package/dist/emit/ts/service-map.d.ts +5 -0
- package/dist/emit/ts/service-map.js +10 -1
- package/dist/emit/ts/single-flight-text.d.ts +3 -0
- package/dist/emit/ts/single-flight-text.js +38 -0
- package/dist/emit/ts/tanstack-query.d.ts +3 -2
- package/dist/emit/ts/tanstack-query.js +54 -29
- package/dist/gen/process.js +2 -1
- package/dist/gen/switch-on.constants.d.ts +2 -0
- package/dist/gen/switch-on.constants.js +2 -0
- package/dist/gen/targets.d.ts +4 -3
- package/dist/gen/targets.js +4 -3
- package/dist/ir/invalidate-reads.d.ts +17 -0
- package/dist/ir/invalidate-reads.js +104 -0
- package/dist/ir/load.d.ts +10 -0
- package/dist/ir/load.js +62 -14
- package/dist/ir/read-method.constants.d.ts +2 -0
- package/dist/ir/read-method.constants.js +2 -0
- package/dist/release/load.js +1 -1
- package/dist/runtime/csharp/Config.cs +9 -1
- package/dist/runtime/csharp/Exchange.cs +56 -4
- package/dist/runtime/csharp/Hooks.cs +9 -0
- package/dist/runtime/csharp/Operation.cs +6 -1
- package/dist/runtime/csharp/WsDial.cs +3 -1
- package/dist/runtime/go/config.go +5 -0
- package/dist/runtime/go/hooks.go +70 -0
- package/dist/runtime/go/request.go +6 -2
- package/dist/runtime/go/stream.go +4 -1
- package/dist/runtime/go/ws.go +3 -1
- package/dist/runtime/java/ClientConfig.java +11 -0
- package/dist/runtime/java/Flight.java +2 -12
- package/dist/runtime/java/Hooks.java +45 -0
- package/dist/runtime/java/InvalidateEvent.java +10 -0
- package/dist/runtime/java/InvalidateHook.java +12 -0
- package/dist/runtime/java/InvalidateTarget.java +7 -0
- package/dist/runtime/java/Operation.java +23 -3
- package/dist/runtime/java/Realtime.java +3 -1
- package/dist/runtime/java/WsDial.java +3 -0
- package/dist/runtime/python/config.py +8 -2
- package/dist/runtime/python/exchange.py +3 -1
- package/dist/runtime/python/hooks.py +110 -5
- package/dist/runtime/python/operation.py +2 -0
- package/dist/runtime/python/send_async.py +14 -2
- package/dist/runtime/python/send_sync.py +4 -2
- package/dist/runtime/python/ws.py +5 -1
- package/dist/runtime/rust/config.rs +6 -1
- package/dist/runtime/rust/exchange.rs +15 -3
- package/dist/runtime/rust/hooks.rs +127 -2
- package/dist/runtime/rust/log.rs +11 -3
- package/dist/runtime/rust/request.rs +17 -0
- package/dist/runtime/rust/ws.rs +9 -1
- package/dist/runtime/ts/config.ts +69 -0
- package/dist/runtime/ts/http.ts +12 -10
- package/dist/runtime/ts/request.ts +2 -0
- package/dist/runtime/ts/response.ts +7 -0
- package/dist/runtime/ts/sdk-invalidate.ts +82 -0
- package/dist/runtime/ts/sdk-single-flight.constants.ts +25 -0
- package/dist/runtime/ts/sdk-single-flight.ts +203 -0
- package/dist/runtime/ts/sdk-sse.ts +5 -1
- package/dist/runtime/ts/sdk-ws.ts +9 -3
- package/dist/runtime/ts/sdk.ts +55 -31
- package/dist/runtime/ts/single-flight-batch.ts +184 -0
- package/dist/runtime/ts/single-flight-body.ts +59 -0
- package/dist/runtime/ts/single-flight-run.ts +160 -0
- package/dist/runtime/ts/single-flight.constants.ts +31 -0
- package/dist/runtime/ts/single-flight.ts +158 -0
- package/dist/runtime/ts-tanstack-query/invalidate.ts +96 -92
- package/dist/runtime/ts-tanstack-query/query.ts +140 -168
- package/package.json +10 -18
- package/references/INDEX.md +31 -0
- package/references/cli.md +33 -0
- package/references/configuring.md +29 -0
- package/references/documentation.md +15 -0
- package/references/errors.md +23 -0
- package/references/flags.md +104 -0
- package/references/gates.md +46 -0
- package/references/generate.md +29 -0
- package/references/install-scripts.md +28 -0
- package/references/install.md +38 -0
- package/references/license.md +8 -0
- package/references/mcp.md +76 -0
- package/references/output.md +45 -0
- package/references/overview.md +14 -0
- package/references/release-tooling.md +34 -0
- package/references/release.md +305 -0
- package/references/sdks.md +393 -0
- package/references/start.md +22 -0
- package/references/tdd.md +16 -0
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: The six SDKs
|
|
3
|
+
order: 60
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# The six SDKs
|
|
7
|
+
|
|
8
|
+
Every SDK takes the same configuration — a base URL, the auth the spec's security scheme names, a timeout, retries,
|
|
9
|
+
hooks around each HTTP call, and per-call overrides — and every one answers the same way: the normal call returns
|
|
10
|
+
your value and throws a typed error by status, while `client.safe` answers a result instead. What follows is each
|
|
11
|
+
language's client in a slice of a compiled example; the
|
|
12
|
+
[SDK recipes](https://github.com/workerstack/clients/blob/main/docs/sdk-recipes.md) page has the whole programs.
|
|
13
|
+
|
|
14
|
+
## The TypeScript SDK
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```sdk ts
|
|
21
|
+
import { DecodeError, Kitchen, NotFoundError } from "./kitchen"
|
|
22
|
+
|
|
23
|
+
export function newClient(): Kitchen {
|
|
24
|
+
return new Kitchen({
|
|
25
|
+
baseURL: "https://api.example.com",
|
|
26
|
+
headers: { authorization: `Bearer ${process.env.KITCHEN_TOKEN ?? ""}` },
|
|
27
|
+
timeout: 10_000,
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function organization(client: Kitchen, orgId: string): Promise<string | null> {
|
|
32
|
+
try {
|
|
33
|
+
await client.organizations.retrieve({ params: { orgId } })
|
|
34
|
+
return orgId
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (error instanceof NotFoundError) return null
|
|
37
|
+
throw error
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function health(client: Kitchen): Promise<string> {
|
|
42
|
+
const result = await client.safe.health.check()
|
|
43
|
+
if (result.ok) return "up"
|
|
44
|
+
if (result.error instanceof DecodeError) return `unreadable answer: ${result.error.message}`
|
|
45
|
+
return `answered ${result.error.status}`
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Publishing it to npm and JSR
|
|
50
|
+
|
|
51
|
+
The target writes a package around the SDK, so the output directory publishes as it is. The sources stay where a
|
|
52
|
+
workspace imports them; they import each other as `.js`, which every TypeScript resolution and bundler maps to the
|
|
53
|
+
`.ts` file. Node will not strip types under `node_modules`, so `dist/` holds each source compiled to ES module
|
|
54
|
+
JavaScript beside its declarations, and `package.json` exports those: the root, `./webhook` when the document has
|
|
55
|
+
webhook events, and `./tanstack-query` with `@tanstack/query-core` as an optional peer. A scoped `--ts-package-name`
|
|
56
|
+
also gets a `jsr.json` that publishes the sources themselves, its `.js` imports mapped to their `.ts` files.
|
|
57
|
+
`--metadata-*` fills description, keywords, homepage, bugs, license, author and repository.
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen \
|
|
61
|
+
--ts-package-name @acme/kitchen --ts-version 1.4.0 --metadata-license MIT
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### TanStack Query, from the same document
|
|
65
|
+
|
|
66
|
+
`--ts-tanstack-query` writes one more file beside the SDK, `<stem>.tanstack-query.gen.ts`. It takes no value:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen --ts-tanstack-query
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Build the QueryClient first, then the SDK with the file's `invalidateQueries` hook, then the helpers. The
|
|
73
|
+
`QueryClient` is the one your framework's adapter exports (`@tanstack/solid-query`, `@tanstack/react-query`), or
|
|
74
|
+
query-core's own, as here:
|
|
75
|
+
|
|
76
|
+
```sdk ts tanstack
|
|
77
|
+
import { QueryClient } from "@tanstack/query-core"
|
|
78
|
+
import { Kitchen } from "./kitchen"
|
|
79
|
+
import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"
|
|
80
|
+
|
|
81
|
+
export const queryClient = new QueryClient()
|
|
82
|
+
const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
|
|
83
|
+
export const { query, mutation, infiniteQuery, queryKey, mutationKey } = createQueryHelpers(() => sdk)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The five surfaces are nested exactly as the client is, so `query.organizations.retrieve(…)` sits where
|
|
87
|
+
`client.organizations.retrieve(…)` does. `createQueryHelpers` takes a function that returns the client, and it calls it
|
|
88
|
+
on every request, so an isomorphic app can return a different client for each request.
|
|
89
|
+
|
|
90
|
+
The document decides what goes where. A `GET` is on `query`, every other method is on `mutation`, and an event
|
|
91
|
+
stream, a WebSocket or an `x-realtime` operation is on neither, because a stream is not a cache entry. Nothing
|
|
92
|
+
is keyed off a method's name.
|
|
93
|
+
|
|
94
|
+
**Call shapes.** Each factory returns only its key and its function. Spread the result into TanStack's own
|
|
95
|
+
options and put everything else after it, so every other option is typed by TanStack. These use query-core's
|
|
96
|
+
observers; `useQuery(() => ({ ... }))` in solid-query, or `useQuery({ ... })` in react-query, takes the same
|
|
97
|
+
object:
|
|
98
|
+
|
|
99
|
+
```sdk ts tanstack
|
|
100
|
+
import { InfiniteQueryObserver, MutationObserver, QueryClient, QueryObserver } from "@tanstack/query-core"
|
|
101
|
+
import { Kitchen } from "./kitchen"
|
|
102
|
+
import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"
|
|
103
|
+
|
|
104
|
+
const queryClient = new QueryClient()
|
|
105
|
+
const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
|
|
106
|
+
const { query, mutation, infiniteQuery, queryKey } = createQueryHelpers(() => sdk)
|
|
107
|
+
|
|
108
|
+
export function organization(orgId: string) {
|
|
109
|
+
return new QueryObserver(queryClient, { ...query.organizations.retrieve({ params: { orgId } }), staleTime: 0 })
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// the second argument is the SDK's own call options; they reach the call, not the key
|
|
113
|
+
export const timed = query.organizations.retrieve({ params: { orgId: "org_1" } }, { timeout: 5_000 })
|
|
114
|
+
|
|
115
|
+
export const greet = new MutationObserver(queryClient, {
|
|
116
|
+
...mutation.hello.create(),
|
|
117
|
+
onMutate: (input) => console.log(`greeting ${input.json.name}`),
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
export const greetings = new InfiniteQueryObserver(queryClient, {
|
|
121
|
+
...infiniteQuery.hello.list((q: string | undefined) => ({ search: { q: q ?? "" } })),
|
|
122
|
+
initialPageParam: undefined,
|
|
123
|
+
getNextPageParam: () => undefined, // read the next page param off the last page, when your API pages
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
export const cached = queryClient.getQueryData(queryKey.hello.list({ search: { q: "Ada" } }))
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
A read takes the SDK method's request, then optionally its call options (`timeout`, `headers`, `signal`, and
|
|
130
|
+
the other per-call options). `mutate` takes exactly what the SDK method takes. A paged read takes a function
|
|
131
|
+
from the page param to the request. The adapter calls that function once with `undefined` to build the key, so
|
|
132
|
+
it must accept `undefined`. Annotate its parameter and TanStack infers the page param type from it. Every call
|
|
133
|
+
gets TanStack's abort signal merged with yours, so a cancel, or the last observer unmounting, aborts the
|
|
134
|
+
request.
|
|
135
|
+
|
|
136
|
+
**Keys.** A read's key is `[<SDK name>, ...the member path, the request]`. The request object goes in whole,
|
|
137
|
+
so `params`, `search` and anything else the SDK sends are all in it. That is what TanStack requires: every input
|
|
138
|
+
the `queryFn` depends on belongs in the key, so two reads of one route that differ only by `search` are two
|
|
139
|
+
cache entries. The call options are not in the key, since a signal and a timeout say nothing about the answer.
|
|
140
|
+
A read with no request keys as `[<SDK name>, ...the member path]`. `queryKey.<…>(req)` returns exactly the key
|
|
141
|
+
`query.<…>(req)` uses, typed so `getQueryData` infers the answer. A paged read's key is the key of its request
|
|
142
|
+
for `undefined` plus a trailing `"infinite"` marker, because its cached shape is `InfiniteData` and it must not
|
|
143
|
+
share the plain read's entry.
|
|
144
|
+
|
|
145
|
+
**Invalidation** happens in the SDK, not the helpers. A successful write fires the SDK's `onInvalidate` with the
|
|
146
|
+
reads its `x-invalidate` selectors name, and `invalidateQueries(queryClient)` makes each of them stale as
|
|
147
|
+
`[<SDK name>, ...the member path, { params }]`, or as the bare prefix when the target has no params. TanStack
|
|
148
|
+
matches objects partially and compares only the filter's own positions, so that reaches every search of that
|
|
149
|
+
read, the paged entry included. Because the SDK fires the hook, a plain `sdk.hello.create(…)` refreshes the
|
|
150
|
+
cache just as `mutation.hello.create()` does. The SDK awaits the hook, so a write resolves only after the
|
|
151
|
+
active reads it made stale have refetched. A failing refetch holds the write through its retries but never
|
|
152
|
+
rejects it, and an infinite query refetches every page it holds.
|
|
153
|
+
|
|
154
|
+
**Server rendering.** On the server, build the QueryClient and the SDK per request, in that order. Both are
|
|
155
|
+
dropped when the request ends, and the hook holds no state of its own. If a route preload prefetches, skip the
|
|
156
|
+
browser's hydration run, or it refetches what the server already sent:
|
|
157
|
+
|
|
158
|
+
```sdk ts tanstack
|
|
159
|
+
import { QueryClient } from "@tanstack/query-core"
|
|
160
|
+
import { Kitchen } from "./kitchen"
|
|
161
|
+
import { createQueryHelpers, invalidateQueries } from "./kitchen.tanstack-query.gen"
|
|
162
|
+
|
|
163
|
+
const queryClient = new QueryClient()
|
|
164
|
+
const sdk = new Kitchen({ baseURL: "https://api.example.com", onInvalidate: [invalidateQueries(queryClient)] })
|
|
165
|
+
const { query } = createQueryHelpers(() => sdk)
|
|
166
|
+
|
|
167
|
+
// a route preload: `isServer` from your framework (`@solidjs/web` in Solid), `intent` from the router
|
|
168
|
+
export function preloadOrganization(isServer: boolean, intent: string, orgId: string): void {
|
|
169
|
+
if (!isServer && intent === "initial") return
|
|
170
|
+
void queryClient.prefetchQuery(query.organizations.retrieve({ params: { orgId } }))
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`@tanstack/query-core` is your dependency, not backend's. Install it yourself; the file imports it for types
|
|
175
|
+
only.
|
|
176
|
+
|
|
177
|
+
Drop the flag and the next run deletes the file, the way `.clients-generated.json` deletes anything the previous
|
|
178
|
+
run wrote and this one did not. The index file never re-exports the adapter, so an SDK generated without the
|
|
179
|
+
flag names no TanStack type anywhere.
|
|
180
|
+
|
|
181
|
+
### Single-flight, a write and its reads in one request
|
|
182
|
+
|
|
183
|
+
`--ts-single-flight` writes `<stem>.single-flight.gen.ts`, a server's file: `singleFlightHandler(getSdk, options)`
|
|
184
|
+
is a fetch handler, and `runSingleFlight(sdk, body)` runs the same batch with no Request or Response. It takes no
|
|
185
|
+
value, and the run refuses it for a document with no write whose `x-invalidate` names a read.
|
|
186
|
+
|
|
187
|
+
```sh
|
|
188
|
+
clients generate --spec openapi.json --target ts --out generated --ts-name Kitchen --ts-single-flight
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
A batch is `{ v: 1, op, input, reads: [{ id, operationId, input }] }` and its answer is
|
|
192
|
+
`{ v: 1, write: { status, headers, body }, reads: [{ id, data } | { id, error: { status, body? } }] }`. Everything
|
|
193
|
+
is checked against the service map before anything runs: one REST write, at most `maxReads` (10) REST JSON reads,
|
|
194
|
+
and input of only `params`, `search`, `json` (the write's) and `idempotencyKey` (an idempotent write's). The
|
|
195
|
+
handler takes only a JSON POST of at most `maxBodyBytes` (64 KiB), refuses a browser on another site or an origin
|
|
196
|
+
outside `allowedOrigins` (its own by default), and answers a refusal as a 400 `application/problem+json`.
|
|
197
|
+
|
|
198
|
+
The write runs once on `getSdk(request)`, which you make per request, forwarding only the auth you choose; the
|
|
199
|
+
handler adds no retry, though the SDK's own hooks may. Only after a 2xx do the reads run, in parallel and past any
|
|
200
|
+
cache, within `readBudgetMs` (2000) and `maxReadBytes` (1 MiB) in all; a read past either ends as its own error
|
|
201
|
+
entry (504 or 502) and never fails the batch. The write's `Set-Cookie` headers are copied onto the 200, and a
|
|
202
|
+
cookie only sticks when the API shares the handler's site.
|
|
203
|
+
|
|
204
|
+
The index never re-exports the file, so no browser bundle carries the handler; the package exports it at
|
|
205
|
+
`./single-flight`.
|
|
206
|
+
|
|
207
|
+
The client sends its writes there once you give it `singleFlight`. A write goes in a batch only when it can: a
|
|
208
|
+
REST write with a JSON answer whose `x-invalidate` names reads, called with nothing a batch cannot carry
|
|
209
|
+
(`headers`, `cookies`, `body`, `form`, `baseURL`, `raw`), its operationId not in `exclude`, and `select` picking at
|
|
210
|
+
least one read. `select` gets the write's targets and returns the reads to bring back, at most `maxReads` (10).
|
|
211
|
+
Every other call goes direct, as does one called with `singleFlight: false`. The batch is a POST to `path`
|
|
212
|
+
(`_mutate`) under the base URL, so the client's hooks, timeout and signal apply to it. An idempotent write's key
|
|
213
|
+
is made before the batch, so a resend carries the same one. With TanStack Query, `activeReads(queryClient)` picks
|
|
214
|
+
the active reads, and `invalidateQueries` puts each one in the cache before it marks the rest stale:
|
|
215
|
+
|
|
216
|
+
```sdk ts tanstack
|
|
217
|
+
import { QueryClient } from "@tanstack/query-core"
|
|
218
|
+
import { Kitchen } from "./kitchen"
|
|
219
|
+
import { activeReads, invalidateQueries } from "./kitchen.tanstack-query.gen"
|
|
220
|
+
|
|
221
|
+
const queryClient = new QueryClient()
|
|
222
|
+
const sdk = new Kitchen({
|
|
223
|
+
baseURL: "https://app.example.com/api",
|
|
224
|
+
onInvalidate: [invalidateQueries(queryClient)],
|
|
225
|
+
singleFlight: { select: activeReads(queryClient) },
|
|
226
|
+
})
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
The write resolves with the answer a direct call would have, and throws the same error. Its reads reach the
|
|
230
|
+
`onInvalidate` hooks first, as `event.fresh`: each answered read's data by the id `select` gave it, and in
|
|
231
|
+
`failed` the ids that did not come back. A query opts out with `meta: { singleFlight: false }`, and a mutation with
|
|
232
|
+
the same meta sends its write direct. A 401 on the write refreshes the token once through `onAuthExpired` and sends
|
|
233
|
+
the batch again. When the handler refuses the batch, the client sends the write direct; any other failure throws
|
|
234
|
+
and the write is never sent twice. A batch answer that is no envelope throws `DecodeError`, the hooks still
|
|
235
|
+
called, since the write may have run.
|
|
236
|
+
|
|
237
|
+
`send` replaces the POST, for an app that calls its server another way, such as a server function that returns
|
|
238
|
+
`runSingleFlight(sdk, batch)`. It gets the batch and resolves the envelope. The client cannot tell a refusal
|
|
239
|
+
through `send` from a failure, so it throws one and never resends the write:
|
|
240
|
+
|
|
241
|
+
```sdk ts
|
|
242
|
+
import { Kitchen, type SingleFlightBatch } from "./kitchen"
|
|
243
|
+
|
|
244
|
+
declare function mutate(batch: SingleFlightBatch): Promise<object>
|
|
245
|
+
|
|
246
|
+
export const sdk = new Kitchen({
|
|
247
|
+
baseURL: "https://app.example.com/api",
|
|
248
|
+
singleFlight: {
|
|
249
|
+
select: (targets) =>
|
|
250
|
+
targets.map((target, at) => ({ id: `r${at}`, input: { params: target.params }, operationId: target.operationId })),
|
|
251
|
+
send: mutate,
|
|
252
|
+
},
|
|
253
|
+
})
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## The Go SDK
|
|
257
|
+
|
|
258
|
+
Idiomatic Go: a `Config`, `context.Context` on every call, errors read with `errors.As`, and an event stream as a
|
|
259
|
+
`range` over a function.
|
|
260
|
+
|
|
261
|
+
```sh
|
|
262
|
+
clients generate --spec openapi.json --target go --out generated --go-module-path github.com/acme/shop/sdk
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Go wants a v2-or-later module's major version at the end of its path, so pass the base path and the version:
|
|
266
|
+
`--go-version 2.1.0` makes go.mod declare `github.com/acme/shop/sdk/v2`, and the CLI target's `--cli-version` does the
|
|
267
|
+
same for its module and the version it links in. A path Go would not publish (no domain first, or a suffix such as
|
|
268
|
+
`/v1`) is refused, as is a suffix next to a version, since the version gives it.
|
|
269
|
+
|
|
270
|
+
```go
|
|
271
|
+
func listing(ctx context.Context, client *sdk.Client) string {
|
|
272
|
+
r, err := client.Safe().Root.List(ctx, nil)
|
|
273
|
+
if err != nil {
|
|
274
|
+
return fmt.Sprintf("no answer: %v", err) // never sent, refused, dropped, timed out or canceled
|
|
275
|
+
}
|
|
276
|
+
var unreadable *sdk.DecodeError
|
|
277
|
+
var failed *sdk.ClientError
|
|
278
|
+
switch {
|
|
279
|
+
case r.Ok():
|
|
280
|
+
return fmt.Sprintf("answered %d: %v", r.Response.StatusCode, r.Data)
|
|
281
|
+
case errors.As(r.Err, &unreadable):
|
|
282
|
+
return fmt.Sprintf("answered %d, unreadable: %v", r.Response.StatusCode, unreadable.Err)
|
|
283
|
+
case errors.As(r.Err, &failed):
|
|
284
|
+
return fmt.Sprintf("answered %d: %s", failed.StatusCode, failed.Key)
|
|
285
|
+
}
|
|
286
|
+
return r.Err.Error()
|
|
287
|
+
}
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
## The Rust SDK
|
|
291
|
+
|
|
292
|
+
Async over `reqwest`, each call taking its options struct, with the safe mirror as a second client style.
|
|
293
|
+
|
|
294
|
+
```sh
|
|
295
|
+
clients generate --spec openapi.json --target rust --out generated --rust-crate-name shop-sdk
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
```rust
|
|
299
|
+
async fn listing(client: &Client) -> String {
|
|
300
|
+
match client.safe().root().list(&RootListOpts::default()).await {
|
|
301
|
+
Ok(Answer::Ok { data, response }) => format!("answered {}: {data:?}", response.status),
|
|
302
|
+
Ok(Answer::Err {
|
|
303
|
+
error: SafeError::Api(failed),
|
|
304
|
+
response,
|
|
305
|
+
}) => format!("answered {}: {}", response.status, failed.message()),
|
|
306
|
+
Ok(Answer::Err {
|
|
307
|
+
error: SafeError::Decode(unreadable),
|
|
308
|
+
response,
|
|
309
|
+
}) => format!("answered {}, unreadable: {unreadable}", response.status),
|
|
310
|
+
Err(no_answer) => format!("no answer: {no_answer}"), // never sent, refused, timed out or canceled
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
## The Python SDK
|
|
316
|
+
|
|
317
|
+
A sync `SDK` and an async `AsyncSDK`, both context managers, typed for `mypy --strict`, with results as frozen
|
|
318
|
+
dataclasses to narrow with `match`.
|
|
319
|
+
|
|
320
|
+
```sh
|
|
321
|
+
clients generate --spec openapi.json --target python --out generated --python-package-name shop_sdk
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
`pyproject.toml` builds with hatchling and carries what PyPI shows: `--metadata-*` gives the description, the SPDX
|
|
325
|
+
`license` (PEP 639, so no `License ::` classifier), authors, keywords, and `[project.urls]` (Homepage, Source,
|
|
326
|
+
Issues, Documentation, Changelog). The classifiers name the Python versions clients tests and `Typing :: Typed`, and
|
|
327
|
+
clients' own manifest stays out of the sdist.
|
|
328
|
+
|
|
329
|
+
```python
|
|
330
|
+
async def health(client: AsyncSDK) -> str:
|
|
331
|
+
match await client.safe.health.check():
|
|
332
|
+
case Ok(data, response):
|
|
333
|
+
return f"answered {response.status}: {data}"
|
|
334
|
+
case Err(DecodeError() as unreadable, response):
|
|
335
|
+
return f"answered {response.status}, unreadable: {unreadable}"
|
|
336
|
+
case Err(error, response):
|
|
337
|
+
return f"answered {response.status}: {error}"
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
## The C# SDK
|
|
341
|
+
|
|
342
|
+
A .NET project with its own `HttpClient` pipeline, `IAsyncDisposable` streams, and `client.Safe` answering
|
|
343
|
+
`Result<T>`.
|
|
344
|
+
|
|
345
|
+
```sh
|
|
346
|
+
clients generate --spec openapi.json --target csharp --out generated --csharp-package-id Acme.Shop
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
nuget.org shows a package's description, authors, license and links: give them with `--csharp-description`,
|
|
350
|
+
`--csharp-authors`, `--csharp-license`, `--csharp-homepage` and `--csharp-repository`, and the `.csproj` carries them
|
|
351
|
+
into `dotnet pack`.
|
|
352
|
+
|
|
353
|
+
```csharp
|
|
354
|
+
public static async Task<string> Listing(HttpSdkClient client, string id)
|
|
355
|
+
{
|
|
356
|
+
var result = await client.Safe.Root.ListAsync(id); // no answer (never sent, refused, timed out, canceled) still throws
|
|
357
|
+
return result.Match(
|
|
358
|
+
found => $"answered {result.Response.Status}: {found}",
|
|
359
|
+
error => error switch
|
|
360
|
+
{
|
|
361
|
+
DecodeException unreadable => $"answered {result.Response.Status}, unreadable: {unreadable.Message}",
|
|
362
|
+
ApiStatusException failed => $"answered {failed.Status}: {failed.Key}",
|
|
363
|
+
_ => error.Message,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
## The Java SDK
|
|
369
|
+
|
|
370
|
+
A Java 17 library on Jackson 3, with builders, `try`-with-resources streams, `client.safe()` answering a sealed
|
|
371
|
+
`Result<T>`, and a Gradle publication.
|
|
372
|
+
|
|
373
|
+
```sh
|
|
374
|
+
clients generate --spec openapi.json --target java --out generated --java-group-id com.acme
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
Maven Central refuses a POM without a URL, a license, a developer and scm: give them with `--java-homepage`,
|
|
378
|
+
`--java-license`, `--java-developers "Name <email>, Other Name"` and `--java-repository`, or once for every target in
|
|
379
|
+
the metadata block, whose authors are the POM's developers. Signing the publication stays yours.
|
|
380
|
+
|
|
381
|
+
```java
|
|
382
|
+
static String listing(KitchenClient client) {
|
|
383
|
+
// no answer (never sent, refused, timed out, canceled) still throws
|
|
384
|
+
Result<ListApiResponse200> result = client.safe().root().list(RootListParams.builder().build());
|
|
385
|
+
int status = result.response().status();
|
|
386
|
+
return result.fold(
|
|
387
|
+
found -> "answered " + status + ": " + found,
|
|
388
|
+
error ->
|
|
389
|
+
error instanceof ApiException failed
|
|
390
|
+
? "answered " + status + ": " + failed.key()
|
|
391
|
+
: "answered " + status + ", unreadable: " + error.getMessage());
|
|
392
|
+
}
|
|
393
|
+
```
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: First generation
|
|
3
|
+
order: 30
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Start
|
|
7
|
+
|
|
8
|
+
From a document:
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npx clients generate --spec openapi.json --target ts --target python --out generated
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
From a backend app module, with no document written first:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npx clients generate --app src/app.ts --target ts --target go --go-module-path github.com/acme/shop/sdk \
|
|
18
|
+
--out generated
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The targets are `ts`, `go`, `rust`, `python`, `csharp`, `java`, `cli` and `mcp`. Each target's files go under
|
|
22
|
+
`<out>/<target>`.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Red, fix, green
|
|
3
|
+
order: 810
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Red, fix, green
|
|
7
|
+
|
|
8
|
+
1. Red: write the test that shows the bug or the missing behavior. Run it. It must fail, for the reason the test names. Record the failing output (BUGS.md for a bug, where the repo has one).
|
|
9
|
+
2. Fix: the smallest change that makes it pass.
|
|
10
|
+
3. Green: run it again and record the passing output. Then run the tests the change reaches, and leave the full gates to CI on the push.
|
|
11
|
+
|
|
12
|
+
A test that cannot fail proves nothing. Check it: revert or break the fix, and the test must go red.
|
|
13
|
+
|
|
14
|
+
Commits: the test and the fix may share a commit or come as `test(...)` then `fix(...)`. A `fix` or `feat` commit always contains a test change.
|
|
15
|
+
|
|
16
|
+
Lint rules follow the same loop. A mistake that a rule could catch mechanically ships with a rule: a RuleTester case that fails first, then the rule, in the repo's `lint/` plugin.
|