@zitadel/api 0.3.0 → 0.4.0
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 +17 -3
- package/dist/api-factory-C5b1Gqwv.mjs +357 -0
- package/dist/api-factory-C5b1Gqwv.mjs.map +1 -0
- package/dist/api-factory-Dt5lUjyu.d.mts +212 -0
- package/dist/api-factory-Dt5lUjyu.d.mts.map +1 -0
- package/dist/{fetch-CtYe0OvX.d.mts → fetch-B-lgjlrf.d.mts} +22 -12
- package/dist/fetch-B-lgjlrf.d.mts.map +1 -0
- package/dist/generated/endpoints/zitadelNextGen.d.mts +1 -1
- package/dist/generated/endpoints/zitadelNextGen.mjs +129 -122
- package/dist/generated/endpoints/zitadelNextGen.mjs.map +1 -1
- package/dist/generated/endpoints/zitadelNextGen.msw.d.mts +1 -1
- package/dist/generated/endpoints/zitadelNextGen.zod.d.mts +33 -26
- package/dist/generated/endpoints/zitadelNextGen.zod.d.mts.map +1 -1
- package/dist/generated/endpoints/zitadelNextGen.zod.mjs +33 -26
- package/dist/generated/endpoints/zitadelNextGen.zod.mjs.map +1 -1
- package/dist/generated/model/index.d.mts +2 -2
- package/dist/generated/operations.mjs +1 -1
- package/dist/generated/operations.mjs.map +1 -1
- package/dist/{index-DAm3tCA7.d.mts → index-DGQY1rfH.d.mts} +66 -4
- package/dist/index-DGQY1rfH.d.mts.map +1 -0
- package/dist/runtime/api-factory.d.mts +2 -51
- package/dist/runtime/api-factory.mjs +3 -62
- package/dist/runtime/auth.mjs +1 -1
- package/dist/runtime/auth.mjs.map +1 -1
- package/dist/runtime/base-url.d.mts +14 -0
- package/dist/runtime/base-url.d.mts.map +1 -1
- package/dist/runtime/base-url.mjs +22 -1
- package/dist/runtime/base-url.mjs.map +1 -1
- package/dist/runtime/config.d.mts +1 -1
- package/dist/runtime/config.mjs +1 -1
- package/dist/runtime/fetch.d.mts +2 -2
- package/dist/runtime/fetch.mjs +41 -17
- package/dist/runtime/fetch.mjs.map +1 -1
- package/dist/runtime/paging.d.mts +35 -0
- package/dist/runtime/paging.d.mts.map +1 -0
- package/dist/runtime/paging.mjs +38 -0
- package/dist/runtime/paging.mjs.map +1 -0
- package/dist/{zitadelNextGen-B_VRpP2W.d.mts → zitadelNextGen-BVO4sdKD.d.mts} +37 -30
- package/dist/zitadelNextGen-BVO4sdKD.d.mts.map +1 -0
- package/package.json +6 -1
- package/src/generated/endpoints/zitadelNextGen.ts +131 -124
- package/src/generated/endpoints/zitadelNextGen.zod.ts +33 -26
- package/src/generated/model/deleteUserByID409.ts +20 -0
- package/src/generated/model/deleteUserByID409Details.ts +12 -0
- package/src/generated/model/deleteUserByIDDefault.ts +9 -0
- package/src/generated/model/getFlowStepDefault.ts +9 -0
- package/src/generated/model/index.ts +2 -0
- package/src/generated/model/queryTeamsParams.ts +3 -2
- package/src/generated/model/submitFlowStepDefault.ts +9 -0
- package/src/generated/operations.ts +1 -1
- package/src/generated/paging.ts +128 -0
- package/src/runtime/api-factory.spec.ts +278 -0
- package/src/runtime/api-factory.ts +93 -12
- package/src/runtime/auth.ts +1 -1
- package/src/runtime/base-url.spec.ts +40 -4
- package/src/runtime/base-url.ts +28 -0
- package/src/runtime/fetch.spec.ts +51 -0
- package/src/runtime/fetch.ts +69 -30
- package/src/runtime/paged.spec.ts +104 -0
- package/src/runtime/paged.ts +61 -0
- package/src/runtime/paging.spec.ts +94 -0
- package/src/runtime/paging.ts +58 -0
- package/dist/fetch-CtYe0OvX.d.mts.map +0 -1
- package/dist/index-DAm3tCA7.d.mts.map +0 -1
- package/dist/runtime/api-factory.d.mts.map +0 -1
- package/dist/runtime/api-factory.mjs.map +0 -1
- package/dist/zitadelNextGen-B_VRpP2W.d.mts.map +0 -1
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { createServer, type Server } from "node:http";
|
|
2
|
+
import type { AddressInfo } from "node:net";
|
|
3
|
+
|
|
4
|
+
import { afterEach, describe, expect, expectTypeOf, it } from "vitest";
|
|
5
|
+
|
|
6
|
+
import type { ListDeployments200DeploymentsItem } from "../generated/model";
|
|
7
|
+
import type { paging } from "../generated/paging";
|
|
8
|
+
import { createZitadelClient, type ItemOf } from "./api-factory";
|
|
9
|
+
|
|
10
|
+
type Paging = typeof paging;
|
|
11
|
+
|
|
12
|
+
const servers: Server[] = [];
|
|
13
|
+
|
|
14
|
+
afterEach(async () => {
|
|
15
|
+
await Promise.all(servers.splice(0).map((s) => new Promise((done) => s.close(done))));
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/** Answers `GET /deployments` two pages deep, recording each request's URL and bearer. */
|
|
19
|
+
async function deployments(): Promise<{ base: string; requests: string[][] }> {
|
|
20
|
+
const requests: string[][] = [];
|
|
21
|
+
const server = createServer((req, res) => {
|
|
22
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
23
|
+
requests.push([url.pathname + url.search, req.headers.authorization ?? ""]);
|
|
24
|
+
const second = url.searchParams.get("page_token") === "t1";
|
|
25
|
+
res.setHeader("content-type", "application/json");
|
|
26
|
+
res.end(
|
|
27
|
+
JSON.stringify({
|
|
28
|
+
deployments: [{ id: second ? "dep_2" : "dep_1" }],
|
|
29
|
+
...(second ? {} : { next_page_token: "t1" }),
|
|
30
|
+
}),
|
|
31
|
+
);
|
|
32
|
+
});
|
|
33
|
+
servers.push(server);
|
|
34
|
+
await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
|
|
35
|
+
return { base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, requests };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Answers any paged request two pages deep, its list under `field`, reading the
|
|
40
|
+
* cursor from the query or the JSON body; records each request's path and body.
|
|
41
|
+
*/
|
|
42
|
+
async function twoPages(field: string): Promise<{ base: string; requests: unknown[][] }> {
|
|
43
|
+
const requests: unknown[][] = [];
|
|
44
|
+
const server = createServer((req, res) => {
|
|
45
|
+
let text = "";
|
|
46
|
+
req.on("data", (chunk) => {
|
|
47
|
+
text += chunk;
|
|
48
|
+
});
|
|
49
|
+
req.on("end", () => {
|
|
50
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
51
|
+
const body: unknown = text === "" ? undefined : JSON.parse(text);
|
|
52
|
+
requests.push([url.pathname + url.search, body]);
|
|
53
|
+
const second = url.search.includes("page_token=t1") || text.includes('"page_token":"t1"');
|
|
54
|
+
res.setHeader("content-type", "application/json");
|
|
55
|
+
res.end(JSON.stringify({ [field]: [], ...(second ? {} : { next_page_token: "t1" }) }));
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
servers.push(server);
|
|
59
|
+
await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
|
|
60
|
+
return { base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, requests };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
describe("createZitadelClient", () => {
|
|
64
|
+
it("walks a paged function's pages with its own base URL and token", async () => {
|
|
65
|
+
const { base, requests } = await deployments();
|
|
66
|
+
const elsewhere = await deployments();
|
|
67
|
+
const client = createZitadelClient({ baseUrl: base, token: "secret" });
|
|
68
|
+
const other = createZitadelClient({ baseUrl: elsewhere.base, token: "other" });
|
|
69
|
+
|
|
70
|
+
const ids = [];
|
|
71
|
+
for await (const deployment of client.listDeployments.items({
|
|
72
|
+
project_id: "proj_1",
|
|
73
|
+
})) {
|
|
74
|
+
ids.push(deployment.id);
|
|
75
|
+
// Another client's call between two pages must not redirect the next one.
|
|
76
|
+
if (ids.length === 1) {
|
|
77
|
+
await other.listDeployments({
|
|
78
|
+
project_id: "proj_2",
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
expect(ids).toEqual(["dep_1", "dep_2"]);
|
|
84
|
+
expect(requests).toEqual([
|
|
85
|
+
["/api/v1/deployments?project_id=proj_1", "Bearer secret"],
|
|
86
|
+
["/api/v1/deployments?project_id=proj_1&page_token=t1", "Bearer secret"],
|
|
87
|
+
]);
|
|
88
|
+
expect(elsewhere.requests).toEqual([["/api/v1/deployments?project_id=proj_2", "Bearer other"]]);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("keeps two clients' walks apart while both are in flight", async () => {
|
|
92
|
+
const one = await deployments();
|
|
93
|
+
const two = await deployments();
|
|
94
|
+
const first = createZitadelClient({ baseUrl: one.base, token: "one" });
|
|
95
|
+
const second = createZitadelClient({ baseUrl: two.base, token: "two" });
|
|
96
|
+
|
|
97
|
+
await Promise.all([
|
|
98
|
+
first.listDeployments.all({
|
|
99
|
+
project_id: "proj_1",
|
|
100
|
+
}),
|
|
101
|
+
second.listDeployments.all({
|
|
102
|
+
project_id: "proj_2",
|
|
103
|
+
}),
|
|
104
|
+
]);
|
|
105
|
+
|
|
106
|
+
expect([one.requests, two.requests]).toEqual([
|
|
107
|
+
[
|
|
108
|
+
["/api/v1/deployments?project_id=proj_1", "Bearer one"],
|
|
109
|
+
["/api/v1/deployments?project_id=proj_1&page_token=t1", "Bearer one"],
|
|
110
|
+
],
|
|
111
|
+
[
|
|
112
|
+
["/api/v1/deployments?project_id=proj_2", "Bearer two"],
|
|
113
|
+
["/api/v1/deployments?project_id=proj_2&page_token=t1", "Bearer two"],
|
|
114
|
+
],
|
|
115
|
+
]);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("types a paged function's items as the response's list entries", () => {
|
|
119
|
+
const client = createZitadelClient({ baseUrl: "http://127.0.0.1:1" });
|
|
120
|
+
|
|
121
|
+
expectTypeOf(client.listDeployments.all).returns.resolves.toEqualTypeOf<
|
|
122
|
+
ListDeployments200DeploymentsItem[]
|
|
123
|
+
>();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("applies its response hook to every page", async () => {
|
|
127
|
+
const { base } = await deployments();
|
|
128
|
+
const client = createZitadelClient({
|
|
129
|
+
baseUrl: base,
|
|
130
|
+
onResponse: (body) => ({
|
|
131
|
+
...(body as object),
|
|
132
|
+
deployments: (body as { deployments: { id: string }[] }).deployments.map((d) => ({
|
|
133
|
+
id: d.id.toUpperCase(),
|
|
134
|
+
})),
|
|
135
|
+
}),
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
const listed = await client.listDeployments.all({
|
|
139
|
+
project_id: "proj_1",
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
expect(listed.map((deployment) => deployment.id)).toEqual(["DEP_1", "DEP_2"]);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("applies its hooks when the global Promise has been replaced", async () => {
|
|
146
|
+
const { base } = await deployments();
|
|
147
|
+
const seen: unknown[] = [];
|
|
148
|
+
const client = createZitadelClient({
|
|
149
|
+
baseUrl: base,
|
|
150
|
+
onResponse: (body) => {
|
|
151
|
+
seen.push(body);
|
|
152
|
+
return body;
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
const Native = globalThis.Promise;
|
|
156
|
+
// As zone.js does: a subclass the engine's own promises are not instances of.
|
|
157
|
+
globalThis.Promise = class extends Native<unknown> {} as PromiseConstructor;
|
|
158
|
+
try {
|
|
159
|
+
await client.listDeployments({
|
|
160
|
+
project_id: "proj_1",
|
|
161
|
+
});
|
|
162
|
+
} finally {
|
|
163
|
+
globalThis.Promise = Native;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
expect(seen).toHaveLength(1);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("walks every page when its response hook reshapes them", async () => {
|
|
170
|
+
const { base } = await deployments();
|
|
171
|
+
const client = createZitadelClient({
|
|
172
|
+
baseUrl: base,
|
|
173
|
+
onResponse: (body) => {
|
|
174
|
+
const { next_page_token: nextPageToken, ...rest } = body as Record<string, unknown>;
|
|
175
|
+
return { ...rest, nextPageToken };
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
const listed = await client.listDeployments.all({
|
|
180
|
+
project_id: "proj_1",
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
expect(listed).toHaveLength(2);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("hands its response hook's failures to its error hook", async () => {
|
|
187
|
+
const { base } = await deployments();
|
|
188
|
+
const client = createZitadelClient({
|
|
189
|
+
baseUrl: base,
|
|
190
|
+
onResponse: () => {
|
|
191
|
+
throw new Error("hook");
|
|
192
|
+
},
|
|
193
|
+
onError: () => {
|
|
194
|
+
throw new Error("handled");
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
const listed = client.listDeployments({
|
|
199
|
+
project_id: "proj_1",
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
await expect(listed).rejects.toThrow("handled");
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("hands every failure to its error hook", async () => {
|
|
206
|
+
const client = createZitadelClient({
|
|
207
|
+
baseUrl: "http://127.0.0.1:1",
|
|
208
|
+
onError: () => {
|
|
209
|
+
throw new Error("handled");
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
const listed = client.listDeployments.all({
|
|
214
|
+
project_id: "proj_1",
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
await expect(listed).rejects.toThrow("handled");
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("puts a later page's page_token in the query parameters after a path parameter", async () => {
|
|
221
|
+
const { base, requests } = await twoPages("previews");
|
|
222
|
+
|
|
223
|
+
await createZitadelClient({ baseUrl: base }).listPreviews.all("proj_1", { limit: 1 });
|
|
224
|
+
|
|
225
|
+
expect(requests.map(([path]) => path)).toEqual([
|
|
226
|
+
"/api/v1/projects/proj_1/previews?limit=1",
|
|
227
|
+
"/api/v1/projects/proj_1/previews?limit=1&page_token=t1",
|
|
228
|
+
]);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it("puts a later page's page_token in query parameters the caller left off", async () => {
|
|
232
|
+
const { base, requests } = await twoPages("previews");
|
|
233
|
+
|
|
234
|
+
await createZitadelClient({ baseUrl: base }).listPreviews.all("proj_1");
|
|
235
|
+
|
|
236
|
+
expect(requests.map(([path]) => path)).toEqual([
|
|
237
|
+
"/api/v1/projects/proj_1/previews",
|
|
238
|
+
"/api/v1/projects/proj_1/previews?page_token=t1",
|
|
239
|
+
]);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
it("puts a later page's page_token in the body of a query", async () => {
|
|
243
|
+
const { base, requests } = await twoPages("users");
|
|
244
|
+
|
|
245
|
+
await createZitadelClient({ baseUrl: base }).queryUsers.all({ limit: 1 });
|
|
246
|
+
|
|
247
|
+
expect(requests.map(([, body]) => body)).toEqual([
|
|
248
|
+
{ limit: 1 },
|
|
249
|
+
{ limit: 1, page_token: "t1" },
|
|
250
|
+
]);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it("types every paged function's items", () => {
|
|
254
|
+
// A list field the generated types lost or renamed fails here, naming the function.
|
|
255
|
+
type Untyped = {
|
|
256
|
+
// A missing field leaves the items `unknown`, a field that is not an array `never`.
|
|
257
|
+
[K in keyof Paging]: [ItemOf<K>] extends [never] ? K : unknown extends ItemOf<K> ? K : never;
|
|
258
|
+
}[keyof Paging];
|
|
259
|
+
|
|
260
|
+
expectTypeOf<Untyped>().toBeNever();
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("builds a URL against its own base URL", () => {
|
|
264
|
+
const client = createZitadelClient({ baseUrl: "http://127.0.0.1:1/" });
|
|
265
|
+
|
|
266
|
+
const url = client.getListDeploymentsUrl({
|
|
267
|
+
project_id: "proj_1",
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
expect(url).toBe("http://127.0.0.1:1/api/v1/deployments?project_id=proj_1");
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
it("leaves paging off a function that does not page", () => {
|
|
274
|
+
const client = createZitadelClient({ baseUrl: "http://127.0.0.1:1" });
|
|
275
|
+
|
|
276
|
+
expect("items" in client.getDeploymentById).toBe(false);
|
|
277
|
+
});
|
|
278
|
+
});
|
|
@@ -9,24 +9,62 @@
|
|
|
9
9
|
* public API.
|
|
10
10
|
*
|
|
11
11
|
* Per-instance isolation: multiple clients can coexist in one process
|
|
12
|
-
* (different servers, different tokens).
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
12
|
+
* (different servers, different tokens). Every call through a client,
|
|
13
|
+
* each page of a paged one included, sets that client's globals
|
|
14
|
+
* synchronously before invoking the underlying generated function,
|
|
15
|
+
* which reads them at the top of `customFetch` before any `await`. So
|
|
16
|
+
* clients can run in parallel across awaits without clobbering each
|
|
17
|
+
* other.
|
|
18
18
|
*/
|
|
19
19
|
import * as endpoints from "../generated/endpoints/zitadelNextGen";
|
|
20
|
+
import { paging } from "../generated/paging";
|
|
20
21
|
|
|
21
22
|
import { setApiAuthToken } from "./auth";
|
|
22
23
|
import { setProxyPath } from "./base-url";
|
|
23
24
|
import { setRequestPolicy } from "./fetch";
|
|
25
|
+
import { paged } from "./paged";
|
|
24
26
|
|
|
25
27
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
+
* How each paged function pages, by name: typed readers of a page's items and
|
|
29
|
+
* of its cursor, and the arguments that fetch the page a cursor names. Named
|
|
30
|
+
* apart from `@zitadel/api/runtime/paging`, the walk itself.
|
|
28
31
|
*/
|
|
29
|
-
export
|
|
32
|
+
export { paging as pagedFunctions };
|
|
33
|
+
|
|
34
|
+
type Endpoints = typeof endpoints;
|
|
35
|
+
type Paging = typeof paging;
|
|
36
|
+
|
|
37
|
+
/** The name of a client function that pages. */
|
|
38
|
+
export type PagedOperation = keyof Paging;
|
|
39
|
+
|
|
40
|
+
/** One page of a paged function's response. */
|
|
41
|
+
export type PageOf<K extends PagedOperation> = Awaited<ReturnType<Endpoints[K]>>;
|
|
42
|
+
|
|
43
|
+
/** One item of a paged function's response. */
|
|
44
|
+
export type ItemOf<K extends PagedOperation> =
|
|
45
|
+
ReturnType<Paging[K]["items"]> extends readonly (infer T)[] ? T : never;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* What a paged function carries besides fetching one page. Each takes the
|
|
49
|
+
* function's own arguments; a `page_token` among them is where it starts, and
|
|
50
|
+
* `limit` is the page size.
|
|
51
|
+
*/
|
|
52
|
+
export type Paged<K extends PagedOperation> = {
|
|
53
|
+
/** Every page, fetched as the loop reaches it. */
|
|
54
|
+
pages(...args: Parameters<Endpoints[K]>): AsyncGenerator<PageOf<K>, void, undefined>;
|
|
55
|
+
/** Every item of every page, fetched a page at a time as the loop reaches it. */
|
|
56
|
+
items(...args: Parameters<Endpoints[K]>): AsyncGenerator<ItemOf<K>, void, undefined>;
|
|
57
|
+
/** Every item of every page, in one array. */
|
|
58
|
+
all(...args: Parameters<Endpoints[K]>): Promise<ItemOf<K>[]>;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Typed Zitadel client returned by {@link createZitadelClient}: the
|
|
63
|
+
* orval-generated endpoints, with {@link Paged} on every function that pages.
|
|
64
|
+
*/
|
|
65
|
+
export type ZitadelClient = {
|
|
66
|
+
[K in keyof Endpoints]: K extends PagedOperation ? Endpoints[K] & Paged<K> : Endpoints[K];
|
|
67
|
+
};
|
|
30
68
|
|
|
31
69
|
/** Re-exported under the legacy name some consumers (`runtime/config.ts`) still import. */
|
|
32
70
|
export type ZitadelApi = ZitadelClient;
|
|
@@ -53,34 +91,77 @@ export type ZitadelClientOptions = {
|
|
|
53
91
|
* Unset by default: no deadline beyond the runtime's own.
|
|
54
92
|
*/
|
|
55
93
|
timeoutMs?: number;
|
|
94
|
+
/**
|
|
95
|
+
* Applied to every response this client resolves with, each page of a
|
|
96
|
+
* paged function's included, before the caller sees it. A paged function
|
|
97
|
+
* reads its cursor from the page as the server sent it, and its items from
|
|
98
|
+
* what this returns under the same field.
|
|
99
|
+
*/
|
|
100
|
+
onResponse?: (body: unknown) => unknown;
|
|
101
|
+
/**
|
|
102
|
+
* Applied to every failure of a call: the request's, `onResponse`'s, and a
|
|
103
|
+
* paged function's own. It throws what the caller sees.
|
|
104
|
+
*/
|
|
105
|
+
onError?: (error: unknown) => never;
|
|
56
106
|
};
|
|
57
107
|
|
|
58
108
|
/**
|
|
59
109
|
* Build a typed Zitadel client pre-bound to a base URL and (optionally)
|
|
60
110
|
* a bearer token. Every method on the returned object mirrors a
|
|
61
|
-
* generated orval function:
|
|
111
|
+
* generated orval function, and one that pages also walks its pages:
|
|
62
112
|
*
|
|
63
113
|
* const client = createZitadelClient({ baseUrl, token });
|
|
64
114
|
* await client.createProject({ origins: [] });
|
|
65
115
|
* await client.createSchema(body, { project_id });
|
|
116
|
+
* for await (const deployment of client.listDeployments.items({ project_id })) { … }
|
|
66
117
|
*/
|
|
67
118
|
export function createZitadelClient(opts: ZitadelClientOptions): ZitadelClient {
|
|
68
119
|
let baseUrl = opts.baseUrl;
|
|
69
120
|
while (baseUrl.endsWith("/")) {
|
|
70
121
|
baseUrl = baseUrl.slice(0, -1);
|
|
71
122
|
}
|
|
72
|
-
|
|
123
|
+
const hooks = {
|
|
124
|
+
respond: (body: unknown) => (opts.onResponse ? opts.onResponse(body) : body),
|
|
125
|
+
fail: (error: unknown): never => {
|
|
126
|
+
opts.onError?.(error);
|
|
127
|
+
throw error;
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
const hooked = opts.onResponse !== undefined || opts.onError !== undefined;
|
|
131
|
+
// Built once per function, not on every property read.
|
|
132
|
+
const bound = new Map<PropertyKey, unknown>();
|
|
133
|
+
return new Proxy(endpoints as unknown as ZitadelClient, {
|
|
73
134
|
get(target, prop, receiver) {
|
|
135
|
+
const known = bound.get(prop);
|
|
136
|
+
if (known !== undefined) {
|
|
137
|
+
return known;
|
|
138
|
+
}
|
|
74
139
|
const value = Reflect.get(target, prop, receiver);
|
|
75
140
|
if (typeof value !== "function") {
|
|
76
141
|
return value;
|
|
77
142
|
}
|
|
78
|
-
|
|
143
|
+
// Every request, each page included, sets this client's base URL and
|
|
144
|
+
// token again: another client may have run in between.
|
|
145
|
+
const send = (...args: unknown[]) => {
|
|
79
146
|
setProxyPath(baseUrl);
|
|
80
147
|
setApiAuthToken(opts.token);
|
|
81
148
|
setRequestPolicy({ signal: opts.signal, timeoutMs: opts.timeoutMs });
|
|
82
149
|
return (value as (...a: unknown[]) => unknown)(...args);
|
|
83
150
|
};
|
|
151
|
+
// The URL builders orval exports beside the requests return strings, so
|
|
152
|
+
// only a pending result is hooked. A then-check rather than `instanceof`,
|
|
153
|
+
// which a replaced global `Promise` (zone.js) would fail.
|
|
154
|
+
const call = (...args: unknown[]) => {
|
|
155
|
+
const result = send(...args);
|
|
156
|
+
return hooked && typeof (result as { then?: unknown } | null)?.then === "function"
|
|
157
|
+
? Promise.resolve(result).then(hooks.respond).catch(hooks.fail)
|
|
158
|
+
: result;
|
|
159
|
+
};
|
|
160
|
+
const fn = Object.hasOwn(paging, prop)
|
|
161
|
+
? Object.assign(call, paged(send, paging[prop as PagedOperation], hooks))
|
|
162
|
+
: call;
|
|
163
|
+
bound.set(prop, fn);
|
|
164
|
+
return fn;
|
|
84
165
|
},
|
|
85
166
|
});
|
|
86
167
|
}
|
package/src/runtime/auth.ts
CHANGED
|
@@ -20,7 +20,7 @@ export function setApiAuthToken(token: string | undefined): void {
|
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
22
|
* The CSRF token for the first-party browser surfaces (ADR 053 §5). A
|
|
23
|
-
* state-changing request that the
|
|
23
|
+
* state-changing request that the session cookie authenticates must
|
|
24
24
|
* carry the session's token — `csrf_token` from `GET /sessions/me/csrf` — in the
|
|
25
25
|
* `X-Zitadel-CSRF` header. The app sets it once it has loaded its session;
|
|
26
26
|
* `runtime/fetch.ts` then adds the header to unsafe requests. Unset (every
|
|
@@ -1,10 +1,25 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
|
|
1
3
|
import { afterEach, expect, test } from "vitest";
|
|
2
4
|
|
|
3
5
|
import { getGetSchemaByIdUrl, getGetUserByIDUrl } from "../generated/endpoints/zitadelNextGen";
|
|
4
|
-
import { getProxyPath, setProxyPath } from "./base-url";
|
|
6
|
+
import { API_PREFIX, apiBaseUrl, getApiBaseUrl, getProxyPath, setProxyPath } from "./base-url";
|
|
5
7
|
|
|
6
8
|
afterEach(() => setProxyPath(""));
|
|
7
9
|
|
|
10
|
+
// The spec's servers URL is the contract (ADR 077), and API_PREFIX what every
|
|
11
|
+
// TypeScript client puts in front of an operation's path; the Go client's
|
|
12
|
+
// PathPrefix has the same test. A change to one alone would leave the others
|
|
13
|
+
// behind.
|
|
14
|
+
test("API_PREFIX is the spec's server URL", () => {
|
|
15
|
+
const spec = readFileSync(
|
|
16
|
+
new URL("../../../../api/openapi/openapi-spec.yaml", import.meta.url),
|
|
17
|
+
"utf8",
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
expect(spec.match(/^servers:\n(?:\s*#.*\n)*\s*- url: (\S+)/m)?.[1]).toBe(API_PREFIX);
|
|
21
|
+
});
|
|
22
|
+
|
|
8
23
|
test("getProxyPath returns empty string by default", () => {
|
|
9
24
|
expect(getProxyPath()).toBe("");
|
|
10
25
|
});
|
|
@@ -16,7 +31,7 @@ test("getProxyPath returns empty string by default", () => {
|
|
|
16
31
|
test("a path parameter is encoded and the base URL is not", () => {
|
|
17
32
|
setProxyPath("http://localhost:3000");
|
|
18
33
|
|
|
19
|
-
expect(getGetUserByIDUrl("usr_01")).toBe("http://localhost:3000/users/usr_01");
|
|
34
|
+
expect(getGetUserByIDUrl("usr_01")).toBe("http://localhost:3000/api/v1/users/usr_01");
|
|
20
35
|
});
|
|
21
36
|
|
|
22
37
|
// A schema's id is its `$id`, usually a URL. Sent raw, the `//` collapses on a
|
|
@@ -25,7 +40,7 @@ test("a schema id that is a URL survives as one path segment", () => {
|
|
|
25
40
|
const id = "https://zitadel.com/schemas/v1/default-human-user.json";
|
|
26
41
|
|
|
27
42
|
expect(getGetSchemaByIdUrl(id)).toBe(
|
|
28
|
-
"/schemas/https%3A%2F%2Fzitadel.com%2Fschemas%2Fv1%2Fdefault-human-user.json",
|
|
43
|
+
"/api/v1/schemas/https%3A%2F%2Fzitadel.com%2Fschemas%2Fv1%2Fdefault-human-user.json",
|
|
29
44
|
);
|
|
30
45
|
});
|
|
31
46
|
|
|
@@ -34,5 +49,26 @@ test.each([
|
|
|
34
49
|
["with space", "with%20space"],
|
|
35
50
|
["a/b", "a%2Fb"],
|
|
36
51
|
])("encodes %j", (id, encoded) => {
|
|
37
|
-
expect(getGetSchemaByIdUrl(id)).toBe(`/schemas/${encoded}`);
|
|
52
|
+
expect(getGetSchemaByIdUrl(id)).toBe(`/api/v1/schemas/${encoded}`);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("the operations follow the proxy path and the API prefix", () => {
|
|
56
|
+
setProxyPath("/__nextgen");
|
|
57
|
+
|
|
58
|
+
expect(getApiBaseUrl()).toBe("/__nextgen/api/v1");
|
|
59
|
+
expect(getGetUserByIDUrl("usr_01")).toBe("/__nextgen/api/v1/users/usr_01");
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test.each([
|
|
63
|
+
["", API_PREFIX],
|
|
64
|
+
["/", API_PREFIX],
|
|
65
|
+
["/__nextgen", "/__nextgen/api/v1"],
|
|
66
|
+
["http://localhost:8080", "http://localhost:8080/api/v1"],
|
|
67
|
+
["http://localhost:8080/", "http://localhost:8080/api/v1"],
|
|
68
|
+
["http://localhost:8080/api/v1", "http://localhost:8080/api/v1"],
|
|
69
|
+
["http://localhost:8080/api/v1/", "http://localhost:8080/api/v1"],
|
|
70
|
+
["https://zitadel.example.com/zitadel", "https://zitadel.example.com/zitadel/api/v1"],
|
|
71
|
+
["https://zitadel.example.com/xapi/v1", "https://zitadel.example.com/xapi/v1/api/v1"],
|
|
72
|
+
])("puts the prefix after %j once", (base, expected) => {
|
|
73
|
+
expect(apiBaseUrl(base)).toBe(expected);
|
|
38
74
|
});
|
package/src/runtime/base-url.ts
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The path the server serves the resource API under (ADR 077). An operation's
|
|
3
|
+
* path in the spec, such as `/users/me`, follows it: `/api/v1/users/me`.
|
|
4
|
+
*/
|
|
5
|
+
export const API_PREFIX = "/api/v1";
|
|
6
|
+
|
|
1
7
|
let proxyPath = "";
|
|
2
8
|
|
|
3
9
|
export function getProxyPath(): string {
|
|
@@ -7,3 +13,25 @@ export function getProxyPath(): string {
|
|
|
7
13
|
export function setProxyPath(path: string): void {
|
|
8
14
|
proxyPath = path;
|
|
9
15
|
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `base`, a server's origin or a same-origin proxy path, with
|
|
19
|
+
* {@link API_PREFIX} after it: the base URL every operation's path follows.
|
|
20
|
+
* Trailing slashes go, and a base that already ends in the prefix, as an
|
|
21
|
+
* origin copied together with it might, keeps one.
|
|
22
|
+
*/
|
|
23
|
+
export function apiBaseUrl(base: string): string {
|
|
24
|
+
let trimmed = base;
|
|
25
|
+
while (trimmed.endsWith("/")) {
|
|
26
|
+
trimmed = trimmed.slice(0, -1);
|
|
27
|
+
}
|
|
28
|
+
if (trimmed.endsWith(API_PREFIX)) {
|
|
29
|
+
trimmed = trimmed.slice(0, -API_PREFIX.length);
|
|
30
|
+
}
|
|
31
|
+
return `${trimmed}${API_PREFIX}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The base URL of the generated operations: the configured proxy path or server URL, then {@link API_PREFIX}. */
|
|
35
|
+
export function getApiBaseUrl(): string {
|
|
36
|
+
return apiBaseUrl(proxyPath);
|
|
37
|
+
}
|
|
@@ -100,6 +100,57 @@ describe("customFetch", () => {
|
|
|
100
100
|
expect(error).toMatchObject({ status: 503, requestId: undefined });
|
|
101
101
|
});
|
|
102
102
|
|
|
103
|
+
it("says a server without the operation may predate the API prefix", async () => {
|
|
104
|
+
const http = createHttpServer((_req, res) => {
|
|
105
|
+
res.writeHead(404, { "content-type": "application/json" });
|
|
106
|
+
res.end(JSON.stringify({ code: "req.not_found", message: "not found" }));
|
|
107
|
+
});
|
|
108
|
+
const base = await listening(http as unknown as Server);
|
|
109
|
+
|
|
110
|
+
const error = await customFetch(`${base}/api/v1/users/me`, { method: "GET" }).catch(
|
|
111
|
+
(e: unknown) => e,
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
expect(error).toBeInstanceOf(ApiError);
|
|
115
|
+
expect((error as Error).message).toBe(
|
|
116
|
+
`GET ${base}/api/v1/users/me returned 404 (req.not_found): the server has no such operation; a server older than this client does not serve the API under /api/v1`,
|
|
117
|
+
);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("keeps the plain message for a resource that is not there", async () => {
|
|
121
|
+
const http = createHttpServer((_req, res) => {
|
|
122
|
+
res.writeHead(404, { "content-type": "application/json" });
|
|
123
|
+
res.end(JSON.stringify({ code: "usr.not_found", message: "not found" }));
|
|
124
|
+
});
|
|
125
|
+
const base = await listening(http as unknown as Server);
|
|
126
|
+
|
|
127
|
+
const error = await customFetch(`${base}/api/v1/users/usr_1`, { method: "GET" }).catch(
|
|
128
|
+
(e: unknown) => e,
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
expect((error as Error).message).toBe(`GET ${base}/api/v1/users/usr_1 returned 404`);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("rejects an answer whose body cannot be read as unreadable, not as no response", async () => {
|
|
135
|
+
// A proxy that forwards `content-encoding` over a body fetch already
|
|
136
|
+
// decoded: the status arrives, the body fails to decode (#2466).
|
|
137
|
+
const http = createHttpServer((_req, res) => {
|
|
138
|
+
res.writeHead(200, { "content-type": "application/json", "content-encoding": "gzip" });
|
|
139
|
+
res.end(JSON.stringify({ session: { user_id: "usr_1" } }));
|
|
140
|
+
});
|
|
141
|
+
const base = await listening(http as unknown as Server);
|
|
142
|
+
|
|
143
|
+
const error = await customFetch(`${base}/sessions/exchange`, { method: "POST" }).catch(
|
|
144
|
+
(e: unknown) => e,
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
expect(error).toBeInstanceOf(NetworkError);
|
|
148
|
+
expect(error).toMatchObject({ reason: "unreadable", url: `${base}/sessions/exchange` });
|
|
149
|
+
expect((error as Error).message).toMatch(
|
|
150
|
+
new RegExp(`^POST ${base}/sessions/exchange answered 200, but its body could not be read`),
|
|
151
|
+
);
|
|
152
|
+
});
|
|
153
|
+
|
|
103
154
|
it("keeps the server's request ID on the ApiError", async () => {
|
|
104
155
|
const http = createHttpServer((_req, res) => {
|
|
105
156
|
res.writeHead(400, { "content-type": "application/json", "x-request-id": "req_01TEST" });
|