@zitadel/api 0.2.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 +2 -2
- package/dist/generated/endpoints/zitadelNextGen.mjs +192 -124
- package/dist/generated/endpoints/zitadelNextGen.mjs.map +1 -1
- package/dist/generated/endpoints/zitadelNextGen.msw.d.mts +3 -1
- package/dist/generated/endpoints/zitadelNextGen.msw.d.mts.map +1 -1
- package/dist/generated/endpoints/zitadelNextGen.msw.mjs +40 -7
- package/dist/generated/endpoints/zitadelNextGen.msw.mjs.map +1 -1
- package/dist/generated/endpoints/zitadelNextGen.zod.d.mts +104 -28
- package/dist/generated/endpoints/zitadelNextGen.zod.d.mts.map +1 -1
- package/dist/generated/endpoints/zitadelNextGen.zod.mjs +117 -37
- package/dist/generated/endpoints/zitadelNextGen.zod.mjs.map +1 -1
- package/dist/generated/model/index.d.mts +2 -2
- package/dist/generated/model/index.mjs +5 -1
- package/dist/generated/model/index.mjs.map +1 -1
- package/dist/generated/operations.mjs +22 -1
- package/dist/generated/operations.mjs.map +1 -1
- package/dist/{index-D7-l5LV6.d.mts → index-DGQY1rfH.d.mts} +398 -10
- 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-Cw3DrCn1.d.mts → zitadelNextGen-BVO4sdKD.d.mts} +69 -34
- package/dist/zitadelNextGen-BVO4sdKD.d.mts.map +1 -0
- package/package.json +7 -1
- package/src/generated/endpoints/zitadelNextGen.faker.ts +9 -6
- package/src/generated/endpoints/zitadelNextGen.msw.ts +16 -1
- package/src/generated/endpoints/zitadelNextGen.ts +212 -125
- package/src/generated/endpoints/zitadelNextGen.zod.ts +120 -36
- package/src/generated/model/createFlowDefinition201UserSchemaMetadata.ts +5 -0
- 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/evaluatePolicy200.ts +30 -0
- package/src/generated/model/evaluatePolicy200Violations.ts +14 -0
- package/src/generated/model/evaluatePolicyBody.ts +82 -0
- package/src/generated/model/evaluatePolicyDefault.ts +90 -0
- package/src/generated/model/evaluatePolicyParams.ts +15 -0
- package/src/generated/model/getFlowDefinition200UserSchemaMetadata.ts +5 -0
- package/src/generated/model/getFlowStepDefault.ts +9 -0
- package/src/generated/model/getMyUserSchema200Metadata.ts +5 -0
- package/src/generated/model/getSchemaById200Metadata.ts +5 -0
- package/src/generated/model/index.ts +8 -0
- package/src/generated/model/listFlowDefinitions200FlowDefinitionsItemUserSchemaMetadata.ts +5 -0
- package/src/generated/model/listSchemas200SchemasItemMetadata.ts +5 -0
- package/src/generated/model/listSchemasExpandItem.ts +28 -0
- package/src/generated/model/listSchemasParams.ts +5 -0
- package/src/generated/model/queryTeamsParams.ts +3 -2
- package/src/generated/model/queryUsersBodyFilterItem.ts +11 -3
- package/src/generated/model/queryUsersBodyFilterItemField.ts +12 -3
- package/src/generated/model/submitFlowStepDefault.ts +9 -0
- package/src/generated/operations.ts +24 -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-D7-l5LV6.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-Cw3DrCn1.d.mts.map +0 -1
|
@@ -1,62 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { t as zitadelNextGen_exports } from "../generated/endpoints/zitadelNextGen.mjs";
|
|
5
|
-
//#region src/runtime/api-factory.ts
|
|
6
|
-
/**
|
|
7
|
-
* Factory for the typed Zitadel client every consumer reaches for.
|
|
8
|
-
*
|
|
9
|
-
* Wraps the orval-generated endpoints in a {@link Proxy} so each
|
|
10
|
-
* generated function sees the right base URL and (optionally) the
|
|
11
|
-
* right bearer token at call time — without the caller having to
|
|
12
|
-
* thread either through every operation, and without exposing the
|
|
13
|
-
* module-globals (`setProxyPath` / `setApiAuthToken`) as part of the
|
|
14
|
-
* public API.
|
|
15
|
-
*
|
|
16
|
-
* Per-instance isolation: multiple clients can coexist in one process
|
|
17
|
-
* (different servers, different tokens). Their Proxy `get` traps set
|
|
18
|
-
* the globals synchronously before invoking the underlying generated
|
|
19
|
-
* function, which reads them at the top of `customFetch` before any
|
|
20
|
-
* `await`. Two clients running interleaved within a single JS turn
|
|
21
|
-
* are safe; two clients running in parallel across awaits could
|
|
22
|
-
* clobber each other — not a pattern any current consumer uses.
|
|
23
|
-
*/
|
|
24
|
-
/**
|
|
25
|
-
* Build a typed Zitadel client pre-bound to a base URL and (optionally)
|
|
26
|
-
* a bearer token. Every method on the returned object mirrors a
|
|
27
|
-
* generated orval function:
|
|
28
|
-
*
|
|
29
|
-
* const client = createZitadelClient({ baseUrl, token });
|
|
30
|
-
* await client.createProject({ origins: [] });
|
|
31
|
-
* await client.createSchema(body, { project_id });
|
|
32
|
-
*/
|
|
33
|
-
function createZitadelClient(opts) {
|
|
34
|
-
let baseUrl = opts.baseUrl;
|
|
35
|
-
while (baseUrl.endsWith("/")) baseUrl = baseUrl.slice(0, -1);
|
|
36
|
-
return new Proxy(zitadelNextGen_exports, { get(target, prop, receiver) {
|
|
37
|
-
const value = Reflect.get(target, prop, receiver);
|
|
38
|
-
if (typeof value !== "function") return value;
|
|
39
|
-
return (...args) => {
|
|
40
|
-
setProxyPath(baseUrl);
|
|
41
|
-
setApiAuthToken(opts.token);
|
|
42
|
-
setRequestPolicy({
|
|
43
|
-
signal: opts.signal,
|
|
44
|
-
timeoutMs: opts.timeoutMs
|
|
45
|
-
});
|
|
46
|
-
return value(...args);
|
|
47
|
-
};
|
|
48
|
-
} });
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Legacy entry point: builds a client with only the base URL set, no
|
|
52
|
-
* token. Components and SDKs that don't carry an auth token (browser
|
|
53
|
-
* flows authenticated by platform cookies) still consume this name.
|
|
54
|
-
* Equivalent to `createZitadelClient({ baseUrl: apiBase })`.
|
|
55
|
-
*/
|
|
56
|
-
function createApi(apiBase) {
|
|
57
|
-
return createZitadelClient({ baseUrl: apiBase });
|
|
58
|
-
}
|
|
59
|
-
//#endregion
|
|
60
|
-
export { createApi, createZitadelClient };
|
|
61
|
-
|
|
62
|
-
//# sourceMappingURL=api-factory.mjs.map
|
|
1
|
+
import "./base-url.mjs";
|
|
2
|
+
import { n as createZitadelClient, r as paging, t as createApi } from "../api-factory-C5b1Gqwv.mjs";
|
|
3
|
+
export { createApi, createZitadelClient, paging as pagedFunctions };
|
package/dist/runtime/auth.mjs
CHANGED
|
@@ -18,7 +18,7 @@ function setApiAuthToken(token) {
|
|
|
18
18
|
}
|
|
19
19
|
/**
|
|
20
20
|
* The CSRF token for the first-party browser surfaces (ADR 053 §5). A
|
|
21
|
-
* state-changing request that the
|
|
21
|
+
* state-changing request that the session cookie authenticates must
|
|
22
22
|
* carry the session's token — `csrf_token` from `GET /sessions/me/csrf` — in the
|
|
23
23
|
* `X-Zitadel-CSRF` header. The app sets it once it has loaded its session;
|
|
24
24
|
* `runtime/fetch.ts` then adds the header to unsafe requests. Unset (every
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":[],"sources":["../../src/runtime/auth.ts"],"sourcesContent":["/**\n * Module-global bearer token used by the orval-generated client's\n * custom fetch. Set once at command boot (the same lifecycle pattern\n * as `base-url.ts`); every generated request reads from here.\n *\n * Keeping the token here means the CLI doesn't have to thread an\n * `Authorization` header through every generated call site; orval's\n * `mutator` wires `runtime/fetch.ts` in, and that file pulls the token\n * from this module.\n */\nlet apiAuthToken: string | undefined;\n\nexport function getApiAuthToken(): string | undefined {\n return apiAuthToken;\n}\n\nexport function setApiAuthToken(token: string | undefined): void {\n apiAuthToken = token;\n}\n\n/**\n * The CSRF token for the first-party browser surfaces (ADR 053 §5). A\n * state-changing request that the
|
|
1
|
+
{"version":3,"file":"auth.mjs","names":[],"sources":["../../src/runtime/auth.ts"],"sourcesContent":["/**\n * Module-global bearer token used by the orval-generated client's\n * custom fetch. Set once at command boot (the same lifecycle pattern\n * as `base-url.ts`); every generated request reads from here.\n *\n * Keeping the token here means the CLI doesn't have to thread an\n * `Authorization` header through every generated call site; orval's\n * `mutator` wires `runtime/fetch.ts` in, and that file pulls the token\n * from this module.\n */\nlet apiAuthToken: string | undefined;\n\nexport function getApiAuthToken(): string | undefined {\n return apiAuthToken;\n}\n\nexport function setApiAuthToken(token: string | undefined): void {\n apiAuthToken = token;\n}\n\n/**\n * The CSRF token for the first-party browser surfaces (ADR 053 §5). A\n * state-changing request that the session cookie authenticates must\n * carry the session's token — `csrf_token` from `GET /sessions/me/csrf` — in the\n * `X-Zitadel-CSRF` header. The app sets it once it has loaded its session;\n * `runtime/fetch.ts` then adds the header to unsafe requests. Unset (every\n * other caller), nothing is added.\n *\n * The token belongs to the server that issued it, so it is stored with that\n * server's origin and only sent there: another client on the same page, with\n * another base URL, never carries it to a different host. The origin defaults\n * to the page's own, which is where a same-origin app's API lives; with no\n * origin to go by (no page, or an unparsable request URL), nothing is sent.\n *\n * Unlike the bearer slot, the app sets this one rather than the client, so it\n * lives on `globalThis` under a {@link Symbol.for} key, like the project slot in\n * `config.ts`: a second copy of this module (an SDK pinning another version)\n * must read the token the app's copy wrote.\n */\nconst CSRF_SLOT = Symbol.for(\"@zitadel/api/auth:csrf\");\n\ninterface CsrfSlot {\n token?: string;\n tokenOrigin?: string;\n onRejected?: () => Promise<string | undefined>;\n handlerOrigin?: string;\n}\n\nfunction csrfSlot(): CsrfSlot {\n const global = globalThis as Record<symbol, CsrfSlot | undefined>;\n const existing = global[CSRF_SLOT];\n if (existing) return existing;\n const slot: CsrfSlot = {};\n global[CSRF_SLOT] = slot;\n return slot;\n}\n\nfunction pageOrigin(): string | undefined {\n return (globalThis as { location?: { origin?: string } }).location?.origin;\n}\n\nexport function getApiCsrfToken(): string | undefined {\n return csrfSlot().token;\n}\n\n/**\n * Stores the session's CSRF token for the server at `origin` (default: the\n * page's own). `undefined` clears it.\n */\nexport function setApiCsrfToken(token: string | undefined, origin = pageOrigin()): void {\n const slot = csrfSlot();\n slot.token = token;\n slot.tokenOrigin = token === undefined ? undefined : origin;\n}\n\n/** The token to send to `origin`, if it was issued there. */\nexport function apiCsrfTokenFor(origin: string | undefined): string | undefined {\n const slot = csrfSlot();\n return origin !== undefined && slot.tokenOrigin === origin ? slot.token : undefined;\n}\n\n/**\n * Registers what to do when a state-changing request to `origin` (default: the\n * page's own) is refused with `403 auth.csrf_invalid`: the token is tied to the\n * session cookie, which another tab can replace by signing in again, or it was\n * never loaded. A refusal from any other host is not this session's business\n * and is left alone.\n *\n * The handler re-checks the session. It returns a fresh token only when the\n * session still belongs to the person the request was made for; `customFetch`\n * then retries the request once with it. Returning `undefined` (someone else,\n * or nobody, is signed in now) leaves the request refused, so a write is never\n * replayed under a session it was not prepared for.\n */\nexport function setApiCsrfRejectionHandler(\n onRejected: (() => Promise<string | undefined>) | undefined,\n origin = pageOrigin(),\n): void {\n const slot = csrfSlot();\n slot.onRejected = onRejected;\n slot.handlerOrigin = onRejected === undefined ? undefined : origin;\n}\n\nexport function getApiCsrfRejectionHandler(): (() => Promise<string | undefined>) | undefined {\n return csrfSlot().onRejected;\n}\n\n/** The rejection handler for a refusal from `origin`, if it was registered for it. */\nexport function apiCsrfRejectionHandlerFor(\n origin: string | undefined,\n): (() => Promise<string | undefined>) | undefined {\n const slot = csrfSlot();\n return origin !== undefined && slot.handlerOrigin === origin ? slot.onRejected : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAI;AAEJ,SAAgB,kBAAsC;CACpD,OAAO;AACT;AAEA,SAAgB,gBAAgB,OAAiC;CAC/D,eAAe;AACjB;;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,YAAY,OAAO,IAAI,wBAAwB;AASrD,SAAS,WAAqB;CAC5B,MAAM,SAAS;CACf,MAAM,WAAW,OAAO;CACxB,IAAI,UAAU,OAAO;CACrB,MAAM,OAAiB,CAAC;CACxB,OAAO,aAAa;CACpB,OAAO;AACT;AAEA,SAAS,aAAiC;CACxC,OAAQ,WAAkD,UAAU;AACtE;AAEA,SAAgB,kBAAsC;CACpD,OAAO,SAAS,CAAC,CAAC;AACpB;;;;;AAMA,SAAgB,gBAAgB,OAA2B,SAAS,WAAW,GAAS;CACtF,MAAM,OAAO,SAAS;CACtB,KAAK,QAAQ;CACb,KAAK,cAAc,UAAU,KAAA,IAAY,KAAA,IAAY;AACvD;;AAGA,SAAgB,gBAAgB,QAAgD;CAC9E,MAAM,OAAO,SAAS;CACtB,OAAO,WAAW,KAAA,KAAa,KAAK,gBAAgB,SAAS,KAAK,QAAQ,KAAA;AAC5E;;;;;;;;;;;;;;AAeA,SAAgB,2BACd,YACA,SAAS,WAAW,GACd;CACN,MAAM,OAAO,SAAS;CACtB,KAAK,aAAa;CAClB,KAAK,gBAAgB,eAAe,KAAA,IAAY,KAAA,IAAY;AAC9D;AAEA,SAAgB,6BAA8E;CAC5F,OAAO,SAAS,CAAC,CAAC;AACpB;;AAGA,SAAgB,2BACd,QACiD;CACjD,MAAM,OAAO,SAAS;CACtB,OAAO,WAAW,KAAA,KAAa,KAAK,kBAAkB,SAAS,KAAK,aAAa,KAAA;AACnF"}
|
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
//#region src/runtime/base-url.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The path the server serves the resource API under (ADR 077). An operation's
|
|
4
|
+
* path in the spec, such as `/users/me`, follows it: `/api/v1/users/me`.
|
|
5
|
+
*/
|
|
6
|
+
export declare const API_PREFIX = "/api/v1";
|
|
2
7
|
export declare function getProxyPath(): string;
|
|
3
8
|
export declare function setProxyPath(path: string): void;
|
|
9
|
+
/**
|
|
10
|
+
* `base`, a server's origin or a same-origin proxy path, with
|
|
11
|
+
* {@link API_PREFIX} after it: the base URL every operation's path follows.
|
|
12
|
+
* Trailing slashes go, and a base that already ends in the prefix, as an
|
|
13
|
+
* origin copied together with it might, keeps one.
|
|
14
|
+
*/
|
|
15
|
+
export declare function apiBaseUrl(base: string): string;
|
|
16
|
+
/** The base URL of the generated operations: the configured proxy path or server URL, then {@link API_PREFIX}. */
|
|
17
|
+
export declare function getApiBaseUrl(): string;
|
|
4
18
|
//#endregion
|
|
5
19
|
//# sourceMappingURL=base-url.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-url.d.mts","names":[],"sources":["../../src/runtime/base-url.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"base-url.d.mts","names":[],"sources":["../../src/runtime/base-url.ts"],"mappings":";;;;;qBAIa;wBAIG;wBAIA,aAAa;;;;;;;wBAUb,WAAW;;wBAYX"}
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
//#region src/runtime/base-url.ts
|
|
2
|
+
/**
|
|
3
|
+
* The path the server serves the resource API under (ADR 077). An operation's
|
|
4
|
+
* path in the spec, such as `/users/me`, follows it: `/api/v1/users/me`.
|
|
5
|
+
*/
|
|
6
|
+
const API_PREFIX = "/api/v1";
|
|
2
7
|
let proxyPath = "";
|
|
3
8
|
function getProxyPath() {
|
|
4
9
|
return proxyPath;
|
|
@@ -6,7 +11,23 @@ function getProxyPath() {
|
|
|
6
11
|
function setProxyPath(path) {
|
|
7
12
|
proxyPath = path;
|
|
8
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* `base`, a server's origin or a same-origin proxy path, with
|
|
16
|
+
* {@link API_PREFIX} after it: the base URL every operation's path follows.
|
|
17
|
+
* Trailing slashes go, and a base that already ends in the prefix, as an
|
|
18
|
+
* origin copied together with it might, keeps one.
|
|
19
|
+
*/
|
|
20
|
+
function apiBaseUrl(base) {
|
|
21
|
+
let trimmed = base;
|
|
22
|
+
while (trimmed.endsWith("/")) trimmed = trimmed.slice(0, -1);
|
|
23
|
+
if (trimmed.endsWith("/api/v1")) trimmed = trimmed.slice(0, -7);
|
|
24
|
+
return `${trimmed}${API_PREFIX}`;
|
|
25
|
+
}
|
|
26
|
+
/** The base URL of the generated operations: the configured proxy path or server URL, then {@link API_PREFIX}. */
|
|
27
|
+
function getApiBaseUrl() {
|
|
28
|
+
return apiBaseUrl(proxyPath);
|
|
29
|
+
}
|
|
9
30
|
//#endregion
|
|
10
|
-
export { getProxyPath, setProxyPath };
|
|
31
|
+
export { API_PREFIX, apiBaseUrl, getApiBaseUrl, getProxyPath, setProxyPath };
|
|
11
32
|
|
|
12
33
|
//# sourceMappingURL=base-url.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-url.mjs","names":[],"sources":["../../src/runtime/base-url.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"base-url.mjs","names":[],"sources":["../../src/runtime/base-url.ts"],"sourcesContent":["/**\n * The path the server serves the resource API under (ADR 077). An operation's\n * path in the spec, such as `/users/me`, follows it: `/api/v1/users/me`.\n */\nexport const API_PREFIX = \"/api/v1\";\n\nlet proxyPath = \"\";\n\nexport function getProxyPath(): string {\n return proxyPath;\n}\n\nexport function setProxyPath(path: string): void {\n proxyPath = path;\n}\n\n/**\n * `base`, a server's origin or a same-origin proxy path, with\n * {@link API_PREFIX} after it: the base URL every operation's path follows.\n * Trailing slashes go, and a base that already ends in the prefix, as an\n * origin copied together with it might, keeps one.\n */\nexport function apiBaseUrl(base: string): string {\n let trimmed = base;\n while (trimmed.endsWith(\"/\")) {\n trimmed = trimmed.slice(0, -1);\n }\n if (trimmed.endsWith(API_PREFIX)) {\n trimmed = trimmed.slice(0, -API_PREFIX.length);\n }\n return `${trimmed}${API_PREFIX}`;\n}\n\n/** The base URL of the generated operations: the configured proxy path or server URL, then {@link API_PREFIX}. */\nexport function getApiBaseUrl(): string {\n return apiBaseUrl(proxyPath);\n}\n"],"mappings":";;;;;AAIA,MAAa,aAAa;AAE1B,IAAI,YAAY;AAEhB,SAAgB,eAAuB;CACrC,OAAO;AACT;AAEA,SAAgB,aAAa,MAAoB;CAC/C,YAAY;AACd;;;;;;;AAQA,SAAgB,WAAW,MAAsB;CAC/C,IAAI,UAAU;CACd,OAAO,QAAQ,SAAS,GAAG,GACzB,UAAU,QAAQ,MAAM,GAAG,EAAE;CAE/B,IAAI,QAAQ,SAAA,SAAmB,GAC7B,UAAU,QAAQ,MAAM,GAAG,EAAkB;CAE/C,OAAO,GAAG,UAAU;AACtB;;AAGA,SAAgB,gBAAwB;CACtC,OAAO,WAAW,SAAS;AAC7B"}
|
package/dist/runtime/config.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { setProxyPath } from "./base-url.mjs";
|
|
2
|
-
import { createZitadelClient } from "
|
|
2
|
+
import { n as createZitadelClient } from "../api-factory-C5b1Gqwv.mjs";
|
|
3
3
|
//#region src/runtime/config.ts
|
|
4
4
|
/**
|
|
5
5
|
* Slot for the configured project, stored on `globalThis` under a
|
package/dist/runtime/fetch.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
export { ApiError, CSRF_HEADER, NetworkError, RequestPolicy, apiErrorCode, apiErrorMessage, customFetch, request, setRequestPolicy };
|
|
1
|
+
import { a as RequestPolicy, c as customFetch, i as NetworkErrorReason, l as request, n as CSRF_HEADER, o as apiErrorCode, r as NetworkError, s as apiErrorMessage, t as ApiError, u as setRequestPolicy } from "../fetch-B-lgjlrf.mjs";
|
|
2
|
+
export { ApiError, CSRF_HEADER, NetworkError, NetworkErrorReason, RequestPolicy, apiErrorCode, apiErrorMessage, customFetch, request, setRequestPolicy };
|
package/dist/runtime/fetch.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { API_PREFIX } from "./base-url.mjs";
|
|
1
2
|
import { apiCsrfRejectionHandlerFor, apiCsrfTokenFor, getApiAuthToken } from "./auth.mjs";
|
|
2
3
|
//#region src/runtime/fetch.ts
|
|
3
4
|
/** The header the session-bound CSRF token travels in (ADR 053 §5). */
|
|
@@ -9,6 +10,8 @@ const SAFE_METHODS = /* @__PURE__ */ new Set([
|
|
|
9
10
|
]);
|
|
10
11
|
/** The code the server answers a refused CSRF check with. */
|
|
11
12
|
const CSRF_INVALID = "auth.csrf_invalid";
|
|
13
|
+
/** The code the server answers a path no operation of its version has with (ADR 076). */
|
|
14
|
+
const ROUTE_NOT_FOUND = "req.not_found";
|
|
12
15
|
/**
|
|
13
16
|
* Framework-neutral failure type the orval-generated client throws on
|
|
14
17
|
* any non-2xx response. Carries the HTTP status, the parsed error body
|
|
@@ -40,18 +43,24 @@ var ApiError = class extends Error {
|
|
|
40
43
|
}
|
|
41
44
|
};
|
|
42
45
|
/**
|
|
43
|
-
* Thrown when a request got no response
|
|
44
|
-
* reset, the host did not resolve,
|
|
45
|
-
*
|
|
46
|
-
* response that came back with a
|
|
46
|
+
* Thrown when a request got no usable response: the connection was refused or
|
|
47
|
+
* reset, the host did not resolve, the server accepted the connection but did
|
|
48
|
+
* not answer in time, or it answered with a body that could not be read. The
|
|
49
|
+
* counterpart to {@link ApiError}, which is a response that came back with a
|
|
50
|
+
* failing status.
|
|
47
51
|
*
|
|
48
|
-
* `fetch` only rejects when no response arrived,
|
|
49
|
-
*
|
|
50
|
-
*
|
|
52
|
+
* `fetch` only rejects when no response arrived, and reading the body only
|
|
53
|
+
* when the body broke off or could not be decoded, so this is decided by which
|
|
54
|
+
* of the two rejected, never by how a runtime words the failure. The runtime's
|
|
55
|
+
* own error stays on `cause` for debugging.
|
|
51
56
|
*/
|
|
52
57
|
var NetworkError = class extends Error {
|
|
53
58
|
url;
|
|
54
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* `timeout` when a deadline cut the request off, `unreadable` when a response
|
|
61
|
+
* arrived but its body could not be read (a proxy that labels a decoded body
|
|
62
|
+
* as compressed, say), `unreachable` otherwise.
|
|
63
|
+
*/
|
|
55
64
|
reason;
|
|
56
65
|
constructor(url, reason, message, options) {
|
|
57
66
|
super(message, options);
|
|
@@ -112,7 +121,7 @@ async function customFetch(url, options) {
|
|
|
112
121
|
}
|
|
113
122
|
}
|
|
114
123
|
if (!res.ok) {
|
|
115
|
-
const message = `${options.method ?? "GET"} ${url} returned ${res.status}`;
|
|
124
|
+
const message = res.status === 404 && apiErrorCode(parsed) === ROUTE_NOT_FOUND ? `${options.method ?? "GET"} ${url} returned 404 (${ROUTE_NOT_FOUND}): the server has no such operation; a server older than this client does not serve the API under ${API_PREFIX}` : `${options.method ?? "GET"} ${url} returned ${res.status}`;
|
|
116
125
|
throw new ApiError(res.status, url, parsed, message, res.headers.get("x-request-id") || void 0);
|
|
117
126
|
}
|
|
118
127
|
return parsed;
|
|
@@ -148,6 +157,8 @@ function isStream(body) {
|
|
|
148
157
|
* - a deadline fired → {@link NetworkError} with reason `timeout`;
|
|
149
158
|
* - any other abort → the signal's own reason, rethrown untouched, because a
|
|
150
159
|
* cancellation is the caller's decision and the caller knows what it means;
|
|
160
|
+
* - a response arrived but `read` failed → {@link NetworkError} with reason
|
|
161
|
+
* `unreadable`, naming the status that did come back;
|
|
151
162
|
* - anything else → {@link NetworkError} with reason `unreachable`.
|
|
152
163
|
*
|
|
153
164
|
* Exported for the few callers that need the raw {@link Response} (a
|
|
@@ -158,24 +169,37 @@ async function request(url, init, policy = {}, read) {
|
|
|
158
169
|
if (policy.timeoutMs !== void 0) signals.push(AbortSignal.timeout(policy.timeoutMs));
|
|
159
170
|
const signal = signals.length > 0 ? AbortSignal.any(signals) : void 0;
|
|
160
171
|
const method = init.method ?? "GET";
|
|
172
|
+
let res;
|
|
161
173
|
try {
|
|
162
|
-
|
|
174
|
+
res = await fetch(url, {
|
|
163
175
|
...init,
|
|
164
176
|
signal
|
|
165
177
|
});
|
|
178
|
+
} catch (error) {
|
|
179
|
+
throw failure(error, signal, method, url, "unreachable", "got no response");
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
166
182
|
return {
|
|
167
183
|
res,
|
|
168
184
|
rawBody: read ? await read(res) : void 0
|
|
169
185
|
};
|
|
170
186
|
} catch (error) {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
187
|
+
throw failure(error, signal, method, url, "unreadable", `answered ${res.status}, but its body could not be read`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* What {@link request} rejects with when `fetch` or `read` failed: the abort
|
|
192
|
+
* as {@link request} describes it, or else a {@link NetworkError} of `reason`
|
|
193
|
+
* saying `what` happened to the request.
|
|
194
|
+
*/
|
|
195
|
+
function failure(error, signal, method, url, reason, what) {
|
|
196
|
+
if (signal?.aborted) {
|
|
197
|
+
const abort = signal.reason;
|
|
198
|
+
if (abort instanceof DOMException && abort.name === "TimeoutError") return new NetworkError(url, "timeout", `${method} ${url} timed out`, { cause: abort });
|
|
199
|
+
return abort;
|
|
178
200
|
}
|
|
201
|
+
const code = errnoOf(error);
|
|
202
|
+
return new NetworkError(url, reason, `${method} ${url} ${what}${code ? ` (${code})` : ""}`, { cause: error });
|
|
179
203
|
}
|
|
180
204
|
/**
|
|
181
205
|
* The errno a runtime attached to a failed request, if any, for the message.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.mjs","names":[],"sources":["../../src/runtime/fetch.ts"],"sourcesContent":["import { apiCsrfRejectionHandlerFor, apiCsrfTokenFor, getApiAuthToken } from \"./auth\";\n\n/** The header the session-bound CSRF token travels in (ADR 053 §5). */\nexport const CSRF_HEADER = \"X-Zitadel-CSRF\";\n\n// Mirrors the server's list (`httputil.IsSafeMethod` in `internal/httputil`).\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The code the server answers a refused CSRF check with. */\nconst CSRF_INVALID = \"auth.csrf_invalid\";\n\n/**\n * Framework-neutral failure type the orval-generated client throws on\n * any non-2xx response. Carries the HTTP status, the parsed error body\n * (the spec's `{code, message, details?}` envelope when the server\n * returned one), and the request URL — enough for callers to map to\n * their own error taxonomy without re-implementing the fetch layer.\n *\n * Callers that don't care about the distinction can catch `ApiError`\n * generically; callers that do (the CLI's `toZitadelError`) read\n * `status` and decide.\n */\nexport class ApiError extends Error {\n readonly status: number;\n readonly url: string;\n readonly body: unknown;\n /**\n * The server's ID for the request, from its `X-Request-Id` header: the\n * reference that finds the request in the server's logs, to show beside the\n * error. `undefined` when the response carried none, as from a proxy.\n */\n readonly requestId: string | undefined;\n\n constructor(status: number, url: string, body: unknown, message: string, requestId?: string) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.url = url;\n this.body = body;\n this.requestId = requestId;\n }\n}\n\n/**\n * Thrown when a request got no response at all: the connection was refused or\n * reset, the host did not resolve, or the server accepted the connection but\n * did not answer in time. The counterpart to {@link ApiError}, which is a\n * response that came back with a failing status.\n *\n * `fetch` only rejects when no response arrived, so this is decided by the\n * fact that it rejected, never by how a runtime words the failure. The\n * runtime's own error stays on `cause` for debugging.\n */\nexport class NetworkError extends Error {\n readonly url: string;\n /** `timeout` when a deadline cut the request off, `unreachable` otherwise. */\n readonly reason: \"unreachable\" | \"timeout\";\n\n constructor(\n url: string,\n reason: \"unreachable\" | \"timeout\",\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"NetworkError\";\n this.url = url;\n this.reason = reason;\n }\n}\n\n/**\n * What every request a client makes is bound by. Set per call by\n * `createZitadelClient`, the same way as the base URL and token, and read at\n * the top of {@link customFetch} before its first `await`.\n */\nexport type RequestPolicy = {\n /** Aborts every request made while it is set; its reason is rethrown as is. */\n signal?: AbortSignal;\n /** Per-request deadline, covering the response body as well as the headers. */\n timeoutMs?: number;\n};\n\nlet requestPolicy: RequestPolicy = {};\n\nexport function setRequestPolicy(policy: RequestPolicy): void {\n requestPolicy = policy;\n}\n\n/**\n * The orval `mutator` for the fetch client. Every generated operation\n * routes its request through this function instead of the global\n * `fetch`. We pin three concerns here so generated call sites stay\n * focused on the shape of one HTTP call:\n *\n * - bearer auth — read from `runtime/auth.ts` and attached automatically;\n * - the CSRF header — the session-bound token from `runtime/auth.ts`, on\n * unsafe methods to the origin it was issued for, when a first-party surface\n * has set one; an unsafe request to that origin refused with\n * `403 auth.csrf_invalid` asks the registered rejection handler for a fresh\n * token and is retried once with it, only if the handler returns one (the\n * session still belongs to the same person);\n * - non-2xx → throw — orval's stock client parses the body regardless\n * of status, so callers would have to inspect every response. Throw\n * `ApiError` on `!res.ok` so failures interrupt control flow;\n * - body parsing — return the parsed JSON typed as `T` (the operation's\n * return type, threaded through by orval), or `undefined` for the\n * spec's `204`/`205`/`304` no-body responses;\n * - no response → throw {@link NetworkError}, or the abort reason when the\n * caller cancelled (see {@link request}).\n */\nexport async function customFetch<T>(url: string, options: RequestInit): Promise<T> {\n // The client sets the policy per call, so it is read before the first await;\n // the retry below runs under the same policy as the first attempt.\n const policy = requestPolicy;\n const token = getApiAuthToken();\n const headers = new Headers(options.headers);\n if (token && !headers.has(\"authorization\")) {\n headers.set(\"authorization\", `Bearer ${token}`);\n }\n const method = (options.method ?? \"GET\").toUpperCase();\n const unsafe = !SAFE_METHODS.has(method) && !headers.has(CSRF_HEADER);\n // The token and the rejection handler belong to one server: a request to\n // any other origin gets neither.\n const target = originOf(url);\n const csrfToken = apiCsrfTokenFor(target);\n if (unsafe && csrfToken) {\n headers.set(CSRF_HEADER, csrfToken);\n }\n\n let { res, rawBody: parsed } = await request(url, { ...options, headers }, policy, readBody);\n\n // The token was stale (the session cookie changed under this page) or never\n // loaded. The app re-checks the session and hands back a fresh token only if\n // it still belongs to the same person; then the request is retried once. A\n // body that can be read only once cannot be sent again, so it is not retried.\n const onRejected = apiCsrfRejectionHandlerFor(target);\n if (\n unsafe &&\n onRejected &&\n res.status === 403 &&\n apiErrorCode(parsed) === CSRF_INVALID &&\n !isStream(options.body)\n ) {\n const fresh = await onRejected().catch(() => undefined);\n if (fresh && fresh !== csrfToken) {\n headers.set(CSRF_HEADER, fresh);\n ({ res, rawBody: parsed } = await request(url, { ...options, headers }, policy, readBody));\n }\n }\n\n if (!res.ok) {\n const message = `${options.method ?? \"GET\"} ${url} returned ${res.status}`;\n throw new ApiError(\n res.status,\n url,\n parsed,\n message,\n res.headers.get(\"x-request-id\") || undefined,\n );\n }\n\n return parsed as T;\n}\n\n/** The parsed body, or `undefined` for the spec's no-body responses. */\nasync function readBody(res: Response): Promise<unknown> {\n if ([204, 205, 304].includes(res.status)) return undefined;\n const rawBody = await res.text();\n return rawBody ? (safeJsonParse(rawBody) as unknown) : undefined;\n}\n\n/** The request's origin, resolved against the page for a relative URL. */\nfunction originOf(url: string): string | undefined {\n try {\n return new URL(url, (globalThis as { location?: { href?: string } }).location?.href).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction isStream(body: RequestInit[\"body\"]): boolean {\n return typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream;\n}\n\n/**\n * `fetch` bound by a {@link RequestPolicy}, with its failures typed.\n *\n * The policy's signal, its deadline and any signal on `init` are combined, and\n * `read` runs under them too, so a server that sends headers and then stalls\n * mid-body is cut off as well. When the request does not complete:\n *\n * - a deadline fired → {@link NetworkError} with reason `timeout`;\n * - any other abort → the signal's own reason, rethrown untouched, because a\n * cancellation is the caller's decision and the caller knows what it means;\n * - anything else → {@link NetworkError} with reason `unreachable`.\n *\n * Exported for the few callers that need the raw {@link Response} (a\n * `Set-Cookie` header the generated client does not expose).\n */\nexport async function request<R = undefined>(\n url: string,\n init: RequestInit,\n policy: RequestPolicy = {},\n read?: (res: Response) => Promise<R>,\n): Promise<{ res: Response; rawBody: R }> {\n const signals = [init.signal, policy.signal].filter((signal) => signal != null);\n if (policy.timeoutMs !== undefined) {\n signals.push(AbortSignal.timeout(policy.timeoutMs));\n }\n const signal = signals.length > 0 ? AbortSignal.any(signals) : undefined;\n const method = init.method ?? \"GET\";\n try {\n const res = await fetch(url, { ...init, signal });\n return { res, rawBody: (read ? await read(res) : undefined) as R };\n } catch (error) {\n if (signal?.aborted) {\n const reason: unknown = signal.reason;\n if (reason instanceof DOMException && reason.name === \"TimeoutError\") {\n throw new NetworkError(url, \"timeout\", `${method} ${url} timed out`, { cause: reason });\n }\n throw reason;\n }\n const code = errnoOf(error);\n throw new NetworkError(\n url,\n \"unreachable\",\n `${method} ${url} got no response${code ? ` (${code})` : \"\"}`,\n { cause: error },\n );\n }\n}\n\n/**\n * The errno a runtime attached to a failed request, if any, for the message.\n * Undici nests it on `cause`, inside an `AggregateError` when it tried more\n * than one address. Only ever used to describe the failure, never to decide\n * that it was one.\n */\nfunction errnoOf(error: unknown): string | undefined {\n let node: unknown = error;\n for (let depth = 0; depth < 4 && typeof node === \"object\" && node !== null; depth += 1) {\n const { code, errors } = node as { code?: unknown; errors?: unknown };\n if (typeof code === \"string\") {\n return code;\n }\n node = Array.isArray(errors) ? errors[0] : (node as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\n/**\n * `JSON.parse` wrapped so a non-JSON body (e.g. an HTML 502 from a\n * proxy) becomes `{ raw: \"<text>\" }` instead of throwing inside\n * `customFetch`. The thrown `ApiError` then carries something useful\n * for the user to see.\n */\nfunction safeJsonParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return { raw: text };\n }\n}\n\n/**\n * The `code` of the server's `{code, message, details}` error envelope: from an\n * {@link ApiError}, or from a parsed response body. `undefined` when there is\n * none, e.g. an HTML error page from a proxy.\n */\nexport function apiErrorCode(errorOrBody: unknown): string | undefined {\n const body = errorOrBody instanceof ApiError ? errorOrBody.body : errorOrBody;\n return isRecord(body) && typeof body.code === \"string\" ? body.code : undefined;\n}\n\n/**\n * Extracts the server's `{code, message, details}` envelope from an\n * {@link ApiError} into a display string. Falls back to the fetch layer's\n * `\"METHOD url returned N\"` when the body isn't shaped like an envelope, so\n * transport-level failures (HTML from a proxy, empty 5xx) still say\n * something.\n */\nexport function apiErrorMessage(error: ApiError): string {\n const body = error.body;\n if (!isRecord(body)) {\n return error.message;\n }\n const serverMessage = typeof body.message === \"string\" ? body.message : undefined;\n const detail = pickDetailString(body.details);\n if (!serverMessage) {\n return error.message;\n }\n return detail ? `${serverMessage}: ${detail}` : serverMessage;\n}\n\n/**\n * Reads the innermost human-readable string out of the spec's error\n * `details` field. Handles both `details: \"...\"` and the nested\n * `details: { details: \"...\" }` shape the platform emits for validation\n * failures.\n */\nfunction pickDetailString(details: unknown): string | undefined {\n if (typeof details === \"string\") {\n return details;\n }\n if (isRecord(details)) {\n if (typeof details.details === \"string\") {\n return details.details;\n }\n if (typeof details.message === \"string\") {\n return details.message;\n }\n }\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";;;AAGA,MAAa,cAAc;AAG3B,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;AAGvD,MAAM,eAAe;;;;;;;;;;;;AAarB,IAAa,WAAb,cAA8B,MAAM;CAClC;CACA;CACA;;;;;;CAMA;CAEA,YAAY,QAAgB,KAAa,MAAe,SAAiB,WAAoB;EAC3F,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,MAAM;EACX,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;;;;;;;;;;;AAYA,IAAa,eAAb,cAAkC,MAAM;CACtC;;CAEA;CAEA,YACE,KACA,QACA,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,MAAM;EACX,KAAK,SAAS;CAChB;AACF;AAcA,IAAI,gBAA+B,CAAC;AAEpC,SAAgB,iBAAiB,QAA6B;CAC5D,gBAAgB;AAClB;;;;;;;;;;;;;;;;;;;;;;;AAwBA,eAAsB,YAAe,KAAa,SAAkC;CAGlF,MAAM,SAAS;CACf,MAAM,QAAQ,gBAAgB;CAC9B,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;CAC3C,IAAI,SAAS,CAAC,QAAQ,IAAI,eAAe,GACvC,QAAQ,IAAI,iBAAiB,UAAU,OAAO;CAEhD,MAAM,UAAU,QAAQ,UAAU,MAAA,CAAO,YAAY;CACrD,MAAM,SAAS,CAAC,aAAa,IAAI,MAAM,KAAK,CAAC,QAAQ,IAAA,gBAAe;CAGpE,MAAM,SAAS,SAAS,GAAG;CAC3B,MAAM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O,uBAAuB,WAAW,YAAY,OAAO;CAClE,OAAO,SAAS,IAAI,KAAK,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,KAAA;AACvE;;;;;;;;AASA,SAAgB,gBAAgB,OAAyB;CACvD,MAAM,OAAO,MAAM;CACnB,IAAI,CAAC,SAAS,IAAI,GAChB,OAAO,MAAM;CAEf,MAAM,gBAAgB,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU,KAAA;CACxE,MAAM,SAAS,iBAAiB,KAAK,OAAO;CAC5C,IAAI,CAAC,eACH,OAAO,MAAM;CAEf,OAAO,SAAS,GAAG,cAAc,IAAI,WAAW;AAClD;;;;;;;AAQA,SAAS,iBAAiB,SAAsC;CAC9D,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,SAAS,OAAO,GAAG;EACrB,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,QAAQ;EAEjB,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,QAAQ;CAEnB;AAEF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
|
|
1
|
+
{"version":3,"file":"fetch.mjs","names":[],"sources":["../../src/runtime/fetch.ts"],"sourcesContent":["import { apiCsrfRejectionHandlerFor, apiCsrfTokenFor, getApiAuthToken } from \"./auth\";\nimport { API_PREFIX } from \"./base-url\";\n\n/** The header the session-bound CSRF token travels in (ADR 053 §5). */\nexport const CSRF_HEADER = \"X-Zitadel-CSRF\";\n\n// Mirrors the server's list (`httputil.IsSafeMethod` in `internal/httputil`).\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The code the server answers a refused CSRF check with. */\nconst CSRF_INVALID = \"auth.csrf_invalid\";\n\n/** The code the server answers a path no operation of its version has with (ADR 076). */\nconst ROUTE_NOT_FOUND = \"req.not_found\";\n\n/**\n * Framework-neutral failure type the orval-generated client throws on\n * any non-2xx response. Carries the HTTP status, the parsed error body\n * (the spec's `{code, message, details?}` envelope when the server\n * returned one), and the request URL — enough for callers to map to\n * their own error taxonomy without re-implementing the fetch layer.\n *\n * Callers that don't care about the distinction can catch `ApiError`\n * generically; callers that do (the CLI's `toZitadelError`) read\n * `status` and decide.\n */\nexport class ApiError extends Error {\n readonly status: number;\n readonly url: string;\n readonly body: unknown;\n /**\n * The server's ID for the request, from its `X-Request-Id` header: the\n * reference that finds the request in the server's logs, to show beside the\n * error. `undefined` when the response carried none, as from a proxy.\n */\n readonly requestId: string | undefined;\n\n constructor(status: number, url: string, body: unknown, message: string, requestId?: string) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.url = url;\n this.body = body;\n this.requestId = requestId;\n }\n}\n\n/**\n * Thrown when a request got no usable response: the connection was refused or\n * reset, the host did not resolve, the server accepted the connection but did\n * not answer in time, or it answered with a body that could not be read. The\n * counterpart to {@link ApiError}, which is a response that came back with a\n * failing status.\n *\n * `fetch` only rejects when no response arrived, and reading the body only\n * when the body broke off or could not be decoded, so this is decided by which\n * of the two rejected, never by how a runtime words the failure. The runtime's\n * own error stays on `cause` for debugging.\n */\nexport class NetworkError extends Error {\n readonly url: string;\n /**\n * `timeout` when a deadline cut the request off, `unreadable` when a response\n * arrived but its body could not be read (a proxy that labels a decoded body\n * as compressed, say), `unreachable` otherwise.\n */\n readonly reason: NetworkErrorReason;\n\n constructor(url: string, reason: NetworkErrorReason, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"NetworkError\";\n this.url = url;\n this.reason = reason;\n }\n}\n\n/** Why a {@link NetworkError} got no usable response. */\nexport type NetworkErrorReason = \"unreachable\" | \"unreadable\" | \"timeout\";\n\n/**\n * What every request a client makes is bound by. Set per call by\n * `createZitadelClient`, the same way as the base URL and token, and read at\n * the top of {@link customFetch} before its first `await`.\n */\nexport type RequestPolicy = {\n /** Aborts every request made while it is set; its reason is rethrown as is. */\n signal?: AbortSignal;\n /** Per-request deadline, covering the response body as well as the headers. */\n timeoutMs?: number;\n};\n\nlet requestPolicy: RequestPolicy = {};\n\nexport function setRequestPolicy(policy: RequestPolicy): void {\n requestPolicy = policy;\n}\n\n/**\n * The orval `mutator` for the fetch client. Every generated operation\n * routes its request through this function instead of the global\n * `fetch`. We pin three concerns here so generated call sites stay\n * focused on the shape of one HTTP call:\n *\n * - bearer auth — read from `runtime/auth.ts` and attached automatically;\n * - the CSRF header — the session-bound token from `runtime/auth.ts`, on\n * unsafe methods to the origin it was issued for, when a first-party surface\n * has set one; an unsafe request to that origin refused with\n * `403 auth.csrf_invalid` asks the registered rejection handler for a fresh\n * token and is retried once with it, only if the handler returns one (the\n * session still belongs to the same person);\n * - non-2xx → throw — orval's stock client parses the body regardless\n * of status, so callers would have to inspect every response. Throw\n * `ApiError` on `!res.ok` so failures interrupt control flow;\n * - body parsing — return the parsed JSON typed as `T` (the operation's\n * return type, threaded through by orval), or `undefined` for the\n * spec's `204`/`205`/`304` no-body responses;\n * - no response → throw {@link NetworkError}, or the abort reason when the\n * caller cancelled (see {@link request}).\n */\nexport async function customFetch<T>(url: string, options: RequestInit): Promise<T> {\n // The client sets the policy per call, so it is read before the first await;\n // the retry below runs under the same policy as the first attempt.\n const policy = requestPolicy;\n const token = getApiAuthToken();\n const headers = new Headers(options.headers);\n if (token && !headers.has(\"authorization\")) {\n headers.set(\"authorization\", `Bearer ${token}`);\n }\n const method = (options.method ?? \"GET\").toUpperCase();\n const unsafe = !SAFE_METHODS.has(method) && !headers.has(CSRF_HEADER);\n // The token and the rejection handler belong to one server: a request to\n // any other origin gets neither.\n const target = originOf(url);\n const csrfToken = apiCsrfTokenFor(target);\n if (unsafe && csrfToken) {\n headers.set(CSRF_HEADER, csrfToken);\n }\n\n let { res, rawBody: parsed } = await request(url, { ...options, headers }, policy, readBody);\n\n // The token was stale (the session cookie changed under this page) or never\n // loaded. The app re-checks the session and hands back a fresh token only if\n // it still belongs to the same person; then the request is retried once. A\n // body that can be read only once cannot be sent again, so it is not retried.\n const onRejected = apiCsrfRejectionHandlerFor(target);\n if (\n unsafe &&\n onRejected &&\n res.status === 403 &&\n apiErrorCode(parsed) === CSRF_INVALID &&\n !isStream(options.body)\n ) {\n const fresh = await onRejected().catch(() => undefined);\n if (fresh && fresh !== csrfToken) {\n headers.set(CSRF_HEADER, fresh);\n ({ res, rawBody: parsed } = await request(url, { ...options, headers }, policy, readBody));\n }\n }\n\n if (!res.ok) {\n // Every operation this client calls is one the spec has, so a server that\n // knows no such path is another version, most likely one from before the\n // API moved under its prefix.\n const message =\n res.status === 404 && apiErrorCode(parsed) === ROUTE_NOT_FOUND\n ? `${options.method ?? \"GET\"} ${url} returned 404 (${ROUTE_NOT_FOUND}): the server has no such operation; a server older than this client does not serve the API under ${API_PREFIX}`\n : `${options.method ?? \"GET\"} ${url} returned ${res.status}`;\n throw new ApiError(\n res.status,\n url,\n parsed,\n message,\n res.headers.get(\"x-request-id\") || undefined,\n );\n }\n\n // The body is trusted to have the shape the generated types promise; no\n // response is checked here or by the paged functions. Should that change,\n // check it here, against the generated Zod response schemas, so every call\n // is covered.\n return parsed as T;\n}\n\n/** The parsed body, or `undefined` for the spec's no-body responses. */\nasync function readBody(res: Response): Promise<unknown> {\n if ([204, 205, 304].includes(res.status)) return undefined;\n const rawBody = await res.text();\n return rawBody ? (safeJsonParse(rawBody) as unknown) : undefined;\n}\n\n/** The request's origin, resolved against the page for a relative URL. */\nfunction originOf(url: string): string | undefined {\n try {\n return new URL(url, (globalThis as { location?: { href?: string } }).location?.href).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction isStream(body: RequestInit[\"body\"]): boolean {\n return typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream;\n}\n\n/**\n * `fetch` bound by a {@link RequestPolicy}, with its failures typed.\n *\n * The policy's signal, its deadline and any signal on `init` are combined, and\n * `read` runs under them too, so a server that sends headers and then stalls\n * mid-body is cut off as well. When the request does not complete:\n *\n * - a deadline fired → {@link NetworkError} with reason `timeout`;\n * - any other abort → the signal's own reason, rethrown untouched, because a\n * cancellation is the caller's decision and the caller knows what it means;\n * - a response arrived but `read` failed → {@link NetworkError} with reason\n * `unreadable`, naming the status that did come back;\n * - anything else → {@link NetworkError} with reason `unreachable`.\n *\n * Exported for the few callers that need the raw {@link Response} (a\n * `Set-Cookie` header the generated client does not expose).\n */\nexport async function request<R = undefined>(\n url: string,\n init: RequestInit,\n policy: RequestPolicy = {},\n read?: (res: Response) => Promise<R>,\n): Promise<{ res: Response; rawBody: R }> {\n const signals = [init.signal, policy.signal].filter((signal) => signal != null);\n if (policy.timeoutMs !== undefined) {\n signals.push(AbortSignal.timeout(policy.timeoutMs));\n }\n const signal = signals.length > 0 ? AbortSignal.any(signals) : undefined;\n const method = init.method ?? \"GET\";\n let res: Response;\n try {\n res = await fetch(url, { ...init, signal });\n } catch (error) {\n throw failure(error, signal, method, url, \"unreachable\", \"got no response\");\n }\n try {\n return { res, rawBody: (read ? await read(res) : undefined) as R };\n } catch (error) {\n const what = `answered ${res.status}, but its body could not be read`;\n throw failure(error, signal, method, url, \"unreadable\", what);\n }\n}\n\n/**\n * What {@link request} rejects with when `fetch` or `read` failed: the abort\n * as {@link request} describes it, or else a {@link NetworkError} of `reason`\n * saying `what` happened to the request.\n */\nfunction failure(\n error: unknown,\n signal: AbortSignal | undefined,\n method: string,\n url: string,\n reason: \"unreachable\" | \"unreadable\",\n what: string,\n): unknown {\n if (signal?.aborted) {\n const abort: unknown = signal.reason;\n if (abort instanceof DOMException && abort.name === \"TimeoutError\") {\n return new NetworkError(url, \"timeout\", `${method} ${url} timed out`, { cause: abort });\n }\n return abort;\n }\n const code = errnoOf(error);\n return new NetworkError(url, reason, `${method} ${url} ${what}${code ? ` (${code})` : \"\"}`, {\n cause: error,\n });\n}\n\n/**\n * The errno a runtime attached to a failed request, if any, for the message.\n * Undici nests it on `cause`, inside an `AggregateError` when it tried more\n * than one address. Only ever used to describe the failure, never to decide\n * that it was one.\n */\nfunction errnoOf(error: unknown): string | undefined {\n let node: unknown = error;\n for (let depth = 0; depth < 4 && typeof node === \"object\" && node !== null; depth += 1) {\n const { code, errors } = node as { code?: unknown; errors?: unknown };\n if (typeof code === \"string\") {\n return code;\n }\n node = Array.isArray(errors) ? errors[0] : (node as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\n/**\n * `JSON.parse` wrapped so a non-JSON body (e.g. an HTML 502 from a\n * proxy) becomes `{ raw: \"<text>\" }` instead of throwing inside\n * `customFetch`. The thrown `ApiError` then carries something useful\n * for the user to see.\n */\nfunction safeJsonParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return { raw: text };\n }\n}\n\n/**\n * The `code` of the server's `{code, message, details}` error envelope: from an\n * {@link ApiError}, or from a parsed response body. `undefined` when there is\n * none, e.g. an HTML error page from a proxy.\n */\nexport function apiErrorCode(errorOrBody: unknown): string | undefined {\n const body = errorOrBody instanceof ApiError ? errorOrBody.body : errorOrBody;\n return isRecord(body) && typeof body.code === \"string\" ? body.code : undefined;\n}\n\n/**\n * Extracts the server's `{code, message, details}` envelope from an\n * {@link ApiError} into a display string. Falls back to the fetch layer's\n * `\"METHOD url returned N\"` when the body isn't shaped like an envelope, so\n * transport-level failures (HTML from a proxy, empty 5xx) still say\n * something.\n */\nexport function apiErrorMessage(error: ApiError): string {\n const body = error.body;\n if (!isRecord(body)) {\n return error.message;\n }\n const serverMessage = typeof body.message === \"string\" ? body.message : undefined;\n const detail = pickDetailString(body.details);\n if (!serverMessage) {\n return error.message;\n }\n return detail ? `${serverMessage}: ${detail}` : serverMessage;\n}\n\n/**\n * Reads the innermost human-readable string out of the spec's error\n * `details` field. Handles both `details: \"...\"` and the nested\n * `details: { details: \"...\" }` shape the platform emits for validation\n * failures.\n */\nfunction pickDetailString(details: unknown): string | undefined {\n if (typeof details === \"string\") {\n return details;\n }\n if (isRecord(details)) {\n if (typeof details.details === \"string\") {\n return details.details;\n }\n if (typeof details.message === \"string\") {\n return details.message;\n }\n }\n return undefined;\n}\n\nfunction isRecord(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EAET,OAAO,MAAM,QAAQ,MAAM,IAAI,OAAO,KAAM,KAA6B;CAC3E;AAEF;;;;;;;AAQA,SAAS,cAAc,MAAuB;CAC5C,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO,EAAE,KAAK,KAAK;CACrB;AACF;;;;;;AAOA,SAAgB,aAAa,aAA0C;CACrE,MAAM,OAAO,uBAAuB,WAAW,YAAY,OAAO;CAClE,OAAO,SAAS,IAAI,KAAK,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,KAAA;AACvE;;;;;;;;AASA,SAAgB,gBAAgB,OAAyB;CACvD,MAAM,OAAO,MAAM;CACnB,IAAI,CAAC,SAAS,IAAI,GAChB,OAAO,MAAM;CAEf,MAAM,gBAAgB,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU,KAAA;CACxE,MAAM,SAAS,iBAAiB,KAAK,OAAO;CAC5C,IAAI,CAAC,eACH,OAAO,MAAM;CAEf,OAAO,SAAS,GAAG,cAAc,IAAI,WAAW;AAClD;;;;;;;AAQA,SAAS,iBAAiB,SAAsC;CAC9D,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,SAAS,OAAO,GAAG;EACrB,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,QAAQ;EAEjB,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,QAAQ;CAEnB;AAEF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region src/runtime/paging.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Cursor paging (ADR 027): a page carries `next_page_token` while more remain,
|
|
4
|
+
* and the next request sends it back as `page_token`.
|
|
5
|
+
*
|
|
6
|
+
* The walk trusts that contract. A server that repeats a cursor, skips one or
|
|
7
|
+
* answers a page in a different shape is an upstream bug to fix in the server,
|
|
8
|
+
* not something the client detects or works around; do not add guards for it.
|
|
9
|
+
* Typed callers read a page's list straight off it; only {@link itemsOf}, for
|
|
10
|
+
* a caller that knows the list by name alone, checks it is there.
|
|
11
|
+
*/
|
|
12
|
+
/** Fetches the page a cursor names; `undefined` asks for the first page. */
|
|
13
|
+
export type FetchPage<P> = (token: string | undefined) => Promise<P>;
|
|
14
|
+
/**
|
|
15
|
+
* The cursor to the page after `page`, or `undefined` on the last one. `field`
|
|
16
|
+
* names it, for an API that calls it other than `next_page_token`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function nextToken(page: unknown, field?: string): string | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* The array `field` names on a page, for a caller that learns the field only
|
|
21
|
+
* at runtime (an operation picked from a table); a page without one is not a
|
|
22
|
+
* page of that list.
|
|
23
|
+
*/
|
|
24
|
+
export declare function itemsOf(page: unknown, field: string): readonly unknown[];
|
|
25
|
+
/**
|
|
26
|
+
* Every page, fetched only when the loop asks for the next one, so a caller
|
|
27
|
+
* that stops early never reads the rest. The first page is the one
|
|
28
|
+
* `fetchPage(undefined)` answers; `next` reads a page's cursor, and an empty
|
|
29
|
+
* one ends the walk like none.
|
|
30
|
+
*/
|
|
31
|
+
export declare function pages<P>(fetchPage: FetchPage<P>, { next }?: {
|
|
32
|
+
next?: (page: P) => string | undefined;
|
|
33
|
+
}): AsyncGenerator<P, void, undefined>;
|
|
34
|
+
//#endregion
|
|
35
|
+
//# sourceMappingURL=paging.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paging.d.mts","names":[],"sources":["../../src/runtime/paging.ts"],"mappings":";;;;;;;;;;;;YAYY,UAAU,MAAM,8BAA8B,QAAQ;;;;;wBAMlD,UAAU,eAAe;;;;;;wBAUzB,QAAQ,eAAe;;;;;;;wBAchB,MAAM,GAC3B,WAAW,UAAU,MACnB;EAAsB,QAAQ,MAAM;IACrC,eAAe"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/runtime/paging.ts
|
|
2
|
+
/**
|
|
3
|
+
* The cursor to the page after `page`, or `undefined` on the last one. `field`
|
|
4
|
+
* names it, for an API that calls it other than `next_page_token`.
|
|
5
|
+
*/
|
|
6
|
+
function nextToken(page, field = "next_page_token") {
|
|
7
|
+
const token = page?.[field];
|
|
8
|
+
return typeof token === "string" && token !== "" ? token : void 0;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The array `field` names on a page, for a caller that learns the field only
|
|
12
|
+
* at runtime (an operation picked from a table); a page without one is not a
|
|
13
|
+
* page of that list.
|
|
14
|
+
*/
|
|
15
|
+
function itemsOf(page, field) {
|
|
16
|
+
const list = page?.[field];
|
|
17
|
+
if (!Array.isArray(list)) throw new TypeError(`Unexpected list response: missing "${field}" array`);
|
|
18
|
+
return list;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Every page, fetched only when the loop asks for the next one, so a caller
|
|
22
|
+
* that stops early never reads the rest. The first page is the one
|
|
23
|
+
* `fetchPage(undefined)` answers; `next` reads a page's cursor, and an empty
|
|
24
|
+
* one ends the walk like none.
|
|
25
|
+
*/
|
|
26
|
+
async function* pages(fetchPage, { next = nextToken } = {}) {
|
|
27
|
+
let token;
|
|
28
|
+
for (;;) {
|
|
29
|
+
const page = await fetchPage(token);
|
|
30
|
+
token = next(page) || void 0;
|
|
31
|
+
yield page;
|
|
32
|
+
if (token === void 0) return;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
export { itemsOf, nextToken, pages };
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=paging.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paging.mjs","names":[],"sources":["../../src/runtime/paging.ts"],"sourcesContent":["/**\n * Cursor paging (ADR 027): a page carries `next_page_token` while more remain,\n * and the next request sends it back as `page_token`.\n *\n * The walk trusts that contract. A server that repeats a cursor, skips one or\n * answers a page in a different shape is an upstream bug to fix in the server,\n * not something the client detects or works around; do not add guards for it.\n * Typed callers read a page's list straight off it; only {@link itemsOf}, for\n * a caller that knows the list by name alone, checks it is there.\n */\n\n/** Fetches the page a cursor names; `undefined` asks for the first page. */\nexport type FetchPage<P> = (token: string | undefined) => Promise<P>;\n\n/**\n * The cursor to the page after `page`, or `undefined` on the last one. `field`\n * names it, for an API that calls it other than `next_page_token`.\n */\nexport function nextToken(page: unknown, field = \"next_page_token\"): string | undefined {\n const token = (page as Record<string, unknown> | null)?.[field];\n return typeof token === \"string\" && token !== \"\" ? token : undefined;\n}\n\n/**\n * The array `field` names on a page, for a caller that learns the field only\n * at runtime (an operation picked from a table); a page without one is not a\n * page of that list.\n */\nexport function itemsOf(page: unknown, field: string): readonly unknown[] {\n const list = (page as Record<string, unknown> | null)?.[field];\n if (!Array.isArray(list)) {\n throw new TypeError(`Unexpected list response: missing \"${field}\" array`);\n }\n return list;\n}\n\n/**\n * Every page, fetched only when the loop asks for the next one, so a caller\n * that stops early never reads the rest. The first page is the one\n * `fetchPage(undefined)` answers; `next` reads a page's cursor, and an empty\n * one ends the walk like none.\n */\nexport async function* pages<P>(\n fetchPage: FetchPage<P>,\n { next = nextToken }: { next?: (page: P) => string | undefined } = {},\n): AsyncGenerator<P, void, undefined> {\n let token: string | undefined;\n for (;;) {\n const page = await fetchPage(token);\n // Read before the page is handed out, so a loop that changes the page\n // cannot change where the walk goes.\n token = next(page) || undefined;\n yield page;\n if (token === undefined) {\n return;\n }\n }\n}\n"],"mappings":";;;;;AAkBA,SAAgB,UAAU,MAAe,QAAQ,mBAAuC;CACtF,MAAM,QAAS,OAA0C;CACzD,OAAO,OAAO,UAAU,YAAY,UAAU,KAAK,QAAQ,KAAA;AAC7D;;;;;;AAOA,SAAgB,QAAQ,MAAe,OAAmC;CACxE,MAAM,OAAQ,OAA0C;CACxD,IAAI,CAAC,MAAM,QAAQ,IAAI,GACrB,MAAM,IAAI,UAAU,sCAAsC,MAAM,QAAQ;CAE1E,OAAO;AACT;;;;;;;AAQA,gBAAuB,MACrB,WACA,EAAE,OAAO,cAA0D,CAAC,GAChC;CACpC,IAAI;CACJ,SAAS;EACP,MAAM,OAAO,MAAM,UAAU,KAAK;EAGlC,QAAQ,KAAK,IAAI,KAAK,KAAA;EACtB,MAAM;EACN,IAAI,UAAU,KAAA,GACZ;CAEJ;AACF"}
|