@olyzon/sdk 0.0.0-stage → 0.1.0-stg.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/client.d.ts +62 -0
  4. package/dist/client.js +104 -0
  5. package/dist/core/config.d.ts +153 -0
  6. package/dist/core/config.js +368 -0
  7. package/dist/core/contracts.d.ts +52 -0
  8. package/dist/core/contracts.js +12 -0
  9. package/dist/core/dpop.d.ts +39 -0
  10. package/dist/core/dpop.js +63 -0
  11. package/dist/core/errors.d.ts +34 -0
  12. package/dist/core/errors.js +43 -0
  13. package/dist/core/session.d.ts +82 -0
  14. package/dist/core/session.js +170 -0
  15. package/dist/core/transport.d.ts +38 -0
  16. package/dist/core/transport.js +84 -0
  17. package/dist/generated/index.d.ts +24 -0
  18. package/dist/generated/index.js +20 -0
  19. package/dist/generated/manifest.json +13 -0
  20. package/dist/generated/projects/client/client.gen.d.ts +2 -0
  21. package/dist/generated/projects/client/client.gen.js +216 -0
  22. package/dist/generated/projects/client/index.d.ts +10 -0
  23. package/dist/generated/projects/client/index.js +6 -0
  24. package/dist/generated/projects/client/types.gen.d.ts +120 -0
  25. package/dist/generated/projects/client/types.gen.js +2 -0
  26. package/dist/generated/projects/client/utils.gen.d.ts +37 -0
  27. package/dist/generated/projects/client/utils.gen.js +228 -0
  28. package/dist/generated/projects/client.gen.d.ts +12 -0
  29. package/dist/generated/projects/client.gen.js +3 -0
  30. package/dist/generated/projects/core/auth.gen.d.ts +25 -0
  31. package/dist/generated/projects/core/auth.gen.js +14 -0
  32. package/dist/generated/projects/core/bodySerializer.gen.d.ts +25 -0
  33. package/dist/generated/projects/core/bodySerializer.gen.js +57 -0
  34. package/dist/generated/projects/core/params.gen.d.ts +43 -0
  35. package/dist/generated/projects/core/params.gen.js +109 -0
  36. package/dist/generated/projects/core/pathSerializer.gen.d.ts +33 -0
  37. package/dist/generated/projects/core/pathSerializer.gen.js +106 -0
  38. package/dist/generated/projects/core/queryKeySerializer.gen.d.ts +18 -0
  39. package/dist/generated/projects/core/queryKeySerializer.gen.js +92 -0
  40. package/dist/generated/projects/core/serverSentEvents.gen.d.ts +71 -0
  41. package/dist/generated/projects/core/serverSentEvents.gen.js +132 -0
  42. package/dist/generated/projects/core/types.gen.d.ts +83 -0
  43. package/dist/generated/projects/core/types.gen.js +2 -0
  44. package/dist/generated/projects/core/utils.gen.d.ts +19 -0
  45. package/dist/generated/projects/core/utils.gen.js +87 -0
  46. package/dist/generated/projects/index.d.ts +2 -0
  47. package/dist/generated/projects/index.js +2 -0
  48. package/dist/generated/projects/sdk.gen.d.ts +47 -0
  49. package/dist/generated/projects/sdk.gen.js +55 -0
  50. package/dist/generated/projects/types.gen.d.ts +388 -0
  51. package/dist/generated/projects/types.gen.js +2 -0
  52. package/dist/generated/projects.d.ts +54 -0
  53. package/dist/generated/projects.js +58 -0
  54. package/dist/generated/specs/projects.json +872 -0
  55. package/dist/generated/specs/sts.json +942 -0
  56. package/dist/generated/sts/client/client.gen.d.ts +2 -0
  57. package/dist/generated/sts/client/client.gen.js +216 -0
  58. package/dist/generated/sts/client/index.d.ts +10 -0
  59. package/dist/generated/sts/client/index.js +6 -0
  60. package/dist/generated/sts/client/types.gen.d.ts +120 -0
  61. package/dist/generated/sts/client/types.gen.js +2 -0
  62. package/dist/generated/sts/client/utils.gen.d.ts +37 -0
  63. package/dist/generated/sts/client/utils.gen.js +228 -0
  64. package/dist/generated/sts/client.gen.d.ts +12 -0
  65. package/dist/generated/sts/client.gen.js +3 -0
  66. package/dist/generated/sts/core/auth.gen.d.ts +25 -0
  67. package/dist/generated/sts/core/auth.gen.js +14 -0
  68. package/dist/generated/sts/core/bodySerializer.gen.d.ts +25 -0
  69. package/dist/generated/sts/core/bodySerializer.gen.js +57 -0
  70. package/dist/generated/sts/core/params.gen.d.ts +43 -0
  71. package/dist/generated/sts/core/params.gen.js +109 -0
  72. package/dist/generated/sts/core/pathSerializer.gen.d.ts +33 -0
  73. package/dist/generated/sts/core/pathSerializer.gen.js +106 -0
  74. package/dist/generated/sts/core/queryKeySerializer.gen.d.ts +18 -0
  75. package/dist/generated/sts/core/queryKeySerializer.gen.js +92 -0
  76. package/dist/generated/sts/core/serverSentEvents.gen.d.ts +71 -0
  77. package/dist/generated/sts/core/serverSentEvents.gen.js +132 -0
  78. package/dist/generated/sts/core/types.gen.d.ts +83 -0
  79. package/dist/generated/sts/core/types.gen.js +2 -0
  80. package/dist/generated/sts/core/utils.gen.d.ts +19 -0
  81. package/dist/generated/sts/core/utils.gen.js +87 -0
  82. package/dist/generated/sts/index.d.ts +2 -0
  83. package/dist/generated/sts/index.js +2 -0
  84. package/dist/generated/sts/sdk.gen.d.ts +41 -0
  85. package/dist/generated/sts/sdk.gen.js +44 -0
  86. package/dist/generated/sts/types.gen.d.ts +445 -0
  87. package/dist/generated/sts/types.gen.js +2 -0
  88. package/dist/generated/sts.d.ts +44 -0
  89. package/dist/generated/sts.js +49 -0
  90. package/dist/index.d.ts +14 -0
  91. package/dist/index.js +13 -0
  92. package/package.json +43 -3
@@ -0,0 +1,82 @@
1
+ import { type SessionClaims } from "./contracts.ts";
2
+ import { type DpopKeyPair } from "./dpop.ts";
3
+ export interface Session {
4
+ /** The session JWT, sent as `Authorization: DPoP <token>`. */
5
+ token: string;
6
+ claims: SessionClaims;
7
+ /** When it expires, on this machine's clock (milliseconds). */
8
+ expiresAt: number;
9
+ }
10
+ /** A grant, as its actor keeps it (spec §6.4): its ID and its org. */
11
+ export interface GrantReference {
12
+ id: string;
13
+ org: string;
14
+ }
15
+ /**
16
+ * The credentials a service received from its caller, forwarded when it
17
+ * calls another service for that caller (spec §6.1): the session and the
18
+ * proof, as they came.
19
+ */
20
+ export interface ForwardedCredentials {
21
+ token: string;
22
+ proof: string;
23
+ }
24
+ /** Which session a request is signed with. */
25
+ export interface SessionRequest {
26
+ /** The org to act in (people, user API keys, machines). */
27
+ orgId?: string | undefined;
28
+ /** The role named at exchange (org API keys, machines). */
29
+ role?: string | undefined;
30
+ /**
31
+ * A grant this client is the actor of: the session is then its subject's,
32
+ * for one service (`audience`, a service name), exchanged with this
33
+ * client's own session in the grant's org (`orgId` is ignored).
34
+ */
35
+ grant?: (GrantReference & {
36
+ audience: string;
37
+ }) | undefined;
38
+ }
39
+ /** A request to sign: the body must be bytes or text, so that its proof covers it. */
40
+ export interface SignedRequestInit {
41
+ method?: string;
42
+ headers?: Record<string, string>;
43
+ body?: Uint8Array | string | undefined;
44
+ signal?: AbortSignal | null | undefined;
45
+ /**
46
+ * The caller's credentials, sent with this client's session and covered
47
+ * by its proof (`obo`), when calling another service for the caller of a
48
+ * request being handled (spec §6.1).
49
+ */
50
+ forward?: ForwardedCredentials | undefined;
51
+ }
52
+ export interface UserClientOptions {
53
+ /** The STS's origin: `https://sts.us.stg.api.olyzon.ai`. */
54
+ stsOrigin: string;
55
+ /** A Clerk credential, read again at every exchange; `null` when signed out. */
56
+ getClerkToken: () => Promise<string | null>;
57
+ /** Default: the global `fetch`. */
58
+ fetch?: typeof fetch;
59
+ /** Sessions closer than this to expiry are renewed. Default: 60 s. */
60
+ refreshMarginMs?: number;
61
+ }
62
+ /** The DPoP key, the sessions it holds and the requests it signs. */
63
+ export interface UserClient {
64
+ /** The client's DPoP key: one per client, its private key non-extractable. */
65
+ key(): Promise<DpopKeyPair>;
66
+ /** The session for `request`: cached, exchanged at the STS when missing or about to expire. */
67
+ getSession(request?: SessionRequest): Promise<Session>;
68
+ /**
69
+ * Sends a request with the session for `request` (`Authorization: DPoP`)
70
+ * and a proof of this exact method, URL, query and body.
71
+ */
72
+ signedFetch(url: string, init?: SignedRequestInit, request?: SessionRequest): Promise<Response>;
73
+ /**
74
+ * Sends a request without a session, with a proof made with the server's
75
+ * nonce (learnt from its `DPoP-Nonce`, retried once when it asks for a
76
+ * new one): the token endpoint's calls.
77
+ */
78
+ proofFetch(url: string, init?: SignedRequestInit): Promise<Response>;
79
+ /** Forgets every session (sign-out). */
80
+ clear(): void;
81
+ }
82
+ export declare function createUserClient(options: UserClientOptions): UserClient;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Sessions: a Clerk credential exchanged at the STS for an Olyzon session
3
+ * bound to this client's DPoP key (spec §4.2), kept until shortly before it
4
+ * expires, and every request signed with it (spec §5). The STS also issues a
5
+ * grant's session to the grant's actor (spec §6.3).
6
+ */
7
+ import { decodeJwt } from "jose";
8
+ import { ACCESS_TOKEN_TYPE, CLERK_TOKEN_TYPE, GRANT_TOKEN_TYPE, TOKEN_EXCHANGE_GRANT, } from "./contracts.js";
9
+ import { FORWARDED_PROOF_HEADER, FORWARDED_SESSION_HEADER, createProof, forwardedHash, generateDpopKeyPair, } from "./dpop.js";
10
+ import { StsError } from "./errors.js";
11
+ const toBytes = (body) => typeof body === "string" ? new TextEncoder().encode(body) : body;
12
+ export function createUserClient(options) {
13
+ const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
14
+ const tokenUrl = `${options.stsOrigin.replace(/\/+$/, "")}/oauth/token`;
15
+ const margin = options.refreshMarginMs ?? 60_000;
16
+ const sessions = new Map();
17
+ let keyPromise;
18
+ // The last nonce an origin sent, per origin: the next proof carries it.
19
+ const nonces = new Map();
20
+ const key = () => (keyPromise ??= generateDpopKeyPair());
21
+ async function proofFetch(url, init = {}) {
22
+ const method = (init.method ?? "GET").toUpperCase();
23
+ const body = toBytes(init.body);
24
+ const { origin } = new URL(url);
25
+ // Two attempts at most: the first may only teach us the server's nonce.
26
+ for (let attempt = 0;; attempt++) {
27
+ const nonce = nonces.get(origin);
28
+ const proof = await createProof({
29
+ key: await key(),
30
+ method,
31
+ url,
32
+ ...(body ? { body } : {}),
33
+ ...(nonce === undefined ? {} : { nonce }),
34
+ });
35
+ const response = await fetchFn(url, {
36
+ method,
37
+ headers: { ...init.headers, DPoP: proof },
38
+ ...(body ? { body: body } : {}),
39
+ ...(init.signal ? { signal: init.signal } : {}),
40
+ });
41
+ const serverNonce = response.headers.get("DPoP-Nonce");
42
+ if (serverNonce)
43
+ nonces.set(origin, serverNonce);
44
+ if (attempt === 0 && response.status === 400 && serverNonce) {
45
+ const error = (await response
46
+ .clone()
47
+ .json()
48
+ .catch(() => ({})));
49
+ if (error.error === "use_dpop_nonce")
50
+ continue;
51
+ }
52
+ return response;
53
+ }
54
+ }
55
+ /** `POST /oauth/token`: a session bound to this client's key. */
56
+ async function token(params) {
57
+ const response = await proofFetch(tokenUrl, {
58
+ method: "POST",
59
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
60
+ body: params.toString(),
61
+ });
62
+ if (!response.ok) {
63
+ const error = (await response.json().catch(() => ({})));
64
+ throw new StsError(error.error ?? "server_error", error.error_description ?? `the STS answered ${response.status}`, response.status);
65
+ }
66
+ const result = (await response.json());
67
+ const claims = decodeJwt(result.access_token);
68
+ if (claims.cnf?.jkt !== (await key()).jkt)
69
+ throw new StsError("invalid_grant", "the session is not bound to this client's key");
70
+ return {
71
+ token: result.access_token,
72
+ claims,
73
+ expiresAt: Date.now() + result.expires_in * 1000,
74
+ };
75
+ }
76
+ async function exchange(request) {
77
+ if (request.grant) {
78
+ // The grant's actor is this client, with its own session in the grant's org.
79
+ const actor = await client.getSession({
80
+ orgId: request.grant.org,
81
+ role: request.role,
82
+ });
83
+ return token(new URLSearchParams({
84
+ grant_type: TOKEN_EXCHANGE_GRANT,
85
+ subject_token: request.grant.id,
86
+ subject_token_type: GRANT_TOKEN_TYPE,
87
+ actor_token: actor.token,
88
+ actor_token_type: ACCESS_TOKEN_TYPE,
89
+ requested_token_type: ACCESS_TOKEN_TYPE,
90
+ audience: request.grant.audience,
91
+ }));
92
+ }
93
+ const subjectToken = await options.getClerkToken();
94
+ if (!subjectToken)
95
+ throw new StsError("invalid_grant", "not signed in");
96
+ const params = new URLSearchParams({
97
+ grant_type: TOKEN_EXCHANGE_GRANT,
98
+ subject_token: subjectToken,
99
+ subject_token_type: CLERK_TOKEN_TYPE,
100
+ requested_token_type: ACCESS_TOKEN_TYPE,
101
+ });
102
+ if (request.orgId)
103
+ params.set("org_id", request.orgId);
104
+ if (request.role)
105
+ params.set("role", request.role);
106
+ return token(params);
107
+ }
108
+ const client = {
109
+ key,
110
+ async getSession(request = {}) {
111
+ const cacheKey = JSON.stringify(request.grant
112
+ ? ["grant", request.grant.id, request.grant.audience]
113
+ : [request.orgId ?? null, request.role ?? null]);
114
+ const cached = sessions.get(cacheKey);
115
+ if (cached) {
116
+ const session = await cached.catch(() => undefined);
117
+ if (session && session.expiresAt - Date.now() > margin)
118
+ return session;
119
+ // Another call may have started a new exchange meanwhile.
120
+ if (sessions.get(cacheKey) !== cached)
121
+ return client.getSession(request);
122
+ }
123
+ const pending = exchange(request);
124
+ sessions.set(cacheKey, pending);
125
+ // A failed exchange is not cached: the next call tries again.
126
+ pending.catch(() => {
127
+ if (sessions.get(cacheKey) === pending)
128
+ sessions.delete(cacheKey);
129
+ });
130
+ return pending;
131
+ },
132
+ async signedFetch(url, init = {}, request = {}) {
133
+ const session = await client.getSession(request);
134
+ const method = (init.method ?? "GET").toUpperCase();
135
+ const body = toBytes(init.body);
136
+ const { forward } = init;
137
+ const proof = await createProof({
138
+ key: await key(),
139
+ method,
140
+ url,
141
+ ...(body ? { body } : {}),
142
+ accessToken: session.token,
143
+ ...(forward
144
+ ? { obo: await forwardedHash(forward.token, forward.proof) }
145
+ : {}),
146
+ });
147
+ return fetchFn(url, {
148
+ method,
149
+ headers: {
150
+ ...init.headers,
151
+ Authorization: `DPoP ${session.token}`,
152
+ DPoP: proof,
153
+ ...(forward
154
+ ? {
155
+ [FORWARDED_SESSION_HEADER]: forward.token,
156
+ [FORWARDED_PROOF_HEADER]: forward.proof,
157
+ }
158
+ : {}),
159
+ },
160
+ ...(body ? { body: body } : {}),
161
+ ...(init.signal ? { signal: init.signal } : {}),
162
+ });
163
+ },
164
+ proofFetch,
165
+ clear() {
166
+ sessions.clear();
167
+ },
168
+ };
169
+ return client;
170
+ }
@@ -0,0 +1,38 @@
1
+ import type { ForwardedCredentials, GrantReference, UserClient } from "./session.ts";
2
+ /** How a generated API sends its requests. */
3
+ export interface Transport {
4
+ /** The service's origin: `https://sts.us.stg.api.olyzon.ai`. */
5
+ origin: string;
6
+ /** Sends a request with the scope's session and a proof. */
7
+ signed: typeof fetch;
8
+ /** Sends a request with a proof and no session: operations open to anyone (the token endpoint). */
9
+ anonymous: typeof fetch;
10
+ }
11
+ /**
12
+ * Whom an API's calls are for: the session to sign with (`orgId`, `role`),
13
+ * a grant this client is the actor of (calls run as its subject, spec
14
+ * §6.3), and the credentials of the caller a service is calling for, when it
15
+ * is (spec §6.1).
16
+ */
17
+ export interface CallScope {
18
+ orgId?: string | undefined;
19
+ role?: string | undefined;
20
+ grant?: GrantReference | undefined;
21
+ forward?: ForwardedCredentials | undefined;
22
+ }
23
+ /** An operation's input: hey-api's `{ path, query, body }`, plus the request's headers and abort signal. */
24
+ export type Input<Data> = Omit<Data, "url"> & {
25
+ headers?: Record<string, string>;
26
+ signal?: AbortSignal;
27
+ };
28
+ /**
29
+ * The transport of one service for `scope`, or for what `scope()` returns at
30
+ * each call (an org that changes: the web app's active org).
31
+ */
32
+ export declare function createTransport(user: UserClient, scope: CallScope | (() => CallScope), service: string, origin: string): Transport;
33
+ /**
34
+ * Calls a generated operation with `client` and returns its data. An error
35
+ * answer is a `ServiceError`; anything thrown before an answer (the network,
36
+ * the STS refusing a session, the configuration) is thrown as it was.
37
+ */
38
+ export declare function call<Result>(client: unknown, service: string, operation: (options: any) => Promise<unknown>, input: object | undefined): Promise<Result>;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Between hey-api's generated clients and the session layer: each generated
3
+ * client sends its `Request` through a `fetch` of ours, which signs the final
4
+ * method, URL, query and body bytes (DPoP), with the session of the call's
5
+ * scope. Nothing here knows any service.
6
+ */
7
+ import { ServiceError } from "./errors.js";
8
+ /** What a generated client fetches: always a `Request`, but `fetch`'s signature allows more. */
9
+ function requestOf(input, init) {
10
+ return input instanceof Request && init === undefined
11
+ ? input
12
+ : new Request(input, init);
13
+ }
14
+ async function bodyOf(request) {
15
+ if (request.body === null)
16
+ return undefined;
17
+ return new Uint8Array(await request.arrayBuffer());
18
+ }
19
+ /**
20
+ * The transport of one service for `scope`, or for what `scope()` returns at
21
+ * each call (an org that changes: the web app's active org).
22
+ */
23
+ export function createTransport(user, scope, service, origin) {
24
+ return {
25
+ origin,
26
+ async signed(input, init) {
27
+ const request = requestOf(input, init);
28
+ const { forward, grant, orgId, role } = typeof scope === "function" ? scope() : scope;
29
+ const session = grant
30
+ ? { role, grant: { ...grant, audience: service } }
31
+ : { orgId, role };
32
+ return user.signedFetch(request.url, {
33
+ method: request.method,
34
+ headers: Object.fromEntries(request.headers),
35
+ body: await bodyOf(request),
36
+ signal: request.signal,
37
+ forward,
38
+ }, session);
39
+ },
40
+ async anonymous(input, init) {
41
+ const request = requestOf(input, init);
42
+ return user.proofFetch(request.url, {
43
+ method: request.method,
44
+ headers: Object.fromEntries(request.headers),
45
+ body: await bodyOf(request),
46
+ signal: request.signal,
47
+ });
48
+ },
49
+ };
50
+ }
51
+ /**
52
+ * Calls a generated operation with `client` and returns its data. An error
53
+ * answer is a `ServiceError`; anything thrown before an answer (the network,
54
+ * the STS refusing a session, the configuration) is thrown as it was.
55
+ */
56
+ export async function call(client, service,
57
+ // hey-api's functions are generic over their options: any of them fits.
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ operation, input) {
60
+ const result = (await operation({
61
+ ...input,
62
+ client,
63
+ throwOnError: false,
64
+ }));
65
+ const { response, error } = result;
66
+ if (!response) {
67
+ if (error instanceof Error)
68
+ throw error;
69
+ throw new TypeError(`${service}: the request failed before any answer`);
70
+ }
71
+ if (response.ok)
72
+ return result.data;
73
+ const body = error;
74
+ throw new ServiceError({
75
+ service,
76
+ status: response.status,
77
+ code: typeof body?.error === "string" ? body.error : "server_error",
78
+ message: typeof body?.error_description === "string"
79
+ ? body.error_description
80
+ : `${service} answered ${response.status}`,
81
+ body: error,
82
+ challenge: response.headers.get("WWW-Authenticate") ?? undefined,
83
+ });
84
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The services of this build: those "stg" served when it was
3
+ * generated (specs/stg/), each with its API.
4
+ */
5
+ import type { Transport } from "../core/transport.ts";
6
+ import { type ProjectsApi } from "./projects.ts";
7
+ import { type StsApi } from "./sts.ts";
8
+ export * as projects from "./projects.ts";
9
+ export * as sts from "./sts.ts";
10
+ /** The environment whose OpenAPI documents this build was generated from. */
11
+ export declare const BUILD_ENVIRONMENT = "stg";
12
+ /** The services of this build: one API each. */
13
+ export declare const SERVICES: readonly string[];
14
+ /** Every service's port on this machine (environment `local`), the STS's included. */
15
+ export declare const LOCAL_PORTS: Readonly<Record<string, number>>;
16
+ /** Every API of this build. */
17
+ export interface Apis {
18
+ /** The Olyzon Projects API (`projects`). */
19
+ projects: ProjectsApi;
20
+ /** The Olyzon STS API (`sts`). */
21
+ sts: StsApi;
22
+ }
23
+ /** Every API, each sending its calls through the transport made for it. */
24
+ export declare function createApis(transport: (service: string) => Transport): Apis;
@@ -0,0 +1,20 @@
1
+ import { createProjectsApi } from "./projects.js";
2
+ import { createStsApi } from "./sts.js";
3
+ export * as projects from "./projects.js";
4
+ export * as sts from "./sts.js";
5
+ /** The environment whose OpenAPI documents this build was generated from. */
6
+ export const BUILD_ENVIRONMENT = "stg";
7
+ /** The services of this build: one API each. */
8
+ export const SERVICES = ["projects", "sts"];
9
+ /** Every service's port on this machine (environment `local`), the STS's included. */
10
+ export const LOCAL_PORTS = {
11
+ "projects": 4010,
12
+ "sts": 4000,
13
+ };
14
+ /** Every API, each sending its calls through the transport made for it. */
15
+ export function createApis(transport) {
16
+ return {
17
+ projects: createProjectsApi(transport("projects")),
18
+ sts: createStsApi(transport("sts")),
19
+ };
20
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "environment": "stg",
3
+ "services": {
4
+ "projects": {
5
+ "version": "0.0.0",
6
+ "sha256": "884e89df5f8dc710e83a24566d3b404bd9764e738e7a4bb313c82f83bd69326b"
7
+ },
8
+ "sts": {
9
+ "version": "d7e44df9023f",
10
+ "sha256": "638dc323f5cb2bc50a3697688d1987dd65d2ea38641fb1b2fa7e591d3cc4b4af"
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,2 @@
1
+ import type { Client, Config } from './types.gen.ts';
2
+ export declare const createClient: (config?: Config) => Client;
@@ -0,0 +1,216 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ import { createSseClient } from '../core/serverSentEvents.gen.js';
3
+ import { getValidRequestBody } from '../core/utils.gen.js';
4
+ import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js';
5
+ export const createClient = (config = {}) => {
6
+ let _config = mergeConfigs(createConfig(), config);
7
+ const getConfig = () => ({ ..._config });
8
+ const setConfig = (config) => {
9
+ _config = mergeConfigs(_config, config);
10
+ return getConfig();
11
+ };
12
+ const interceptors = createInterceptors();
13
+ const beforeRequest = async (options) => {
14
+ const opts = {
15
+ ..._config,
16
+ ...options,
17
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
18
+ headers: mergeHeaders(_config.headers, options.headers),
19
+ serializedBody: undefined,
20
+ };
21
+ if (opts.security) {
22
+ await setAuthParams(opts);
23
+ }
24
+ if (opts.requestValidator) {
25
+ await opts.requestValidator(opts);
26
+ }
27
+ if (opts.body !== undefined && opts.bodySerializer) {
28
+ opts.serializedBody = opts.bodySerializer(opts.body);
29
+ }
30
+ // remove Content-Type header if body is empty to avoid sending invalid requests
31
+ if (opts.body === undefined || opts.serializedBody === '') {
32
+ opts.headers.delete('Content-Type');
33
+ }
34
+ const resolvedOpts = opts;
35
+ const url = buildUrl(resolvedOpts);
36
+ return { opts: resolvedOpts, url };
37
+ };
38
+ const request = async (options) => {
39
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
40
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
41
+ let request;
42
+ let response;
43
+ try {
44
+ const { opts, url } = await beforeRequest(options);
45
+ const requestInit = {
46
+ redirect: 'follow',
47
+ ...opts,
48
+ body: getValidRequestBody(opts),
49
+ };
50
+ request = new Request(url, requestInit);
51
+ for (const fn of interceptors.request.fns) {
52
+ if (fn) {
53
+ request = await fn(request, opts);
54
+ }
55
+ }
56
+ // fetch must be assigned here, otherwise it would throw the error:
57
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
58
+ const _fetch = opts.fetch;
59
+ response = await _fetch(request);
60
+ for (const fn of interceptors.response.fns) {
61
+ if (fn) {
62
+ response = await fn(response, request, opts);
63
+ }
64
+ }
65
+ const result = {
66
+ request,
67
+ response,
68
+ };
69
+ if (response.ok) {
70
+ const parseAs = (opts.parseAs === 'auto'
71
+ ? getParseAs(response.headers.get('Content-Type'))
72
+ : opts.parseAs) ?? 'json';
73
+ if (response.status === 204 || response.headers.get('Content-Length') === '0') {
74
+ let emptyData;
75
+ switch (parseAs) {
76
+ case 'arrayBuffer':
77
+ case 'blob':
78
+ case 'text':
79
+ emptyData = await response[parseAs]();
80
+ break;
81
+ case 'formData':
82
+ emptyData = new FormData();
83
+ break;
84
+ case 'stream':
85
+ emptyData = response.body;
86
+ break;
87
+ case 'json':
88
+ default:
89
+ emptyData = {};
90
+ break;
91
+ }
92
+ return opts.responseStyle === 'data'
93
+ ? emptyData
94
+ : {
95
+ data: emptyData,
96
+ ...result,
97
+ };
98
+ }
99
+ let data;
100
+ switch (parseAs) {
101
+ case 'arrayBuffer':
102
+ case 'blob':
103
+ case 'formData':
104
+ case 'text':
105
+ data = await response[parseAs]();
106
+ break;
107
+ case 'json': {
108
+ // Some servers return 200 with no Content-Length and empty body.
109
+ // response.json() would throw; read as text and parse if non-empty.
110
+ const text = await response.text();
111
+ data = text ? JSON.parse(text) : {};
112
+ break;
113
+ }
114
+ case 'stream':
115
+ return opts.responseStyle === 'data'
116
+ ? response.body
117
+ : {
118
+ data: response.body,
119
+ ...result,
120
+ };
121
+ }
122
+ if (parseAs === 'json') {
123
+ if (opts.responseValidator) {
124
+ await opts.responseValidator(data);
125
+ }
126
+ if (opts.responseTransformer) {
127
+ data = await opts.responseTransformer(data);
128
+ }
129
+ }
130
+ return opts.responseStyle === 'data'
131
+ ? data
132
+ : {
133
+ data,
134
+ ...result,
135
+ };
136
+ }
137
+ const textError = await response.text();
138
+ let jsonError;
139
+ try {
140
+ jsonError = JSON.parse(textError);
141
+ }
142
+ catch {
143
+ // noop
144
+ }
145
+ throw jsonError ?? textError;
146
+ }
147
+ catch (error) {
148
+ let finalError = error;
149
+ for (const fn of interceptors.error.fns) {
150
+ if (fn) {
151
+ finalError = await fn(finalError, response, request, options);
152
+ }
153
+ }
154
+ finalError = finalError || {};
155
+ if (throwOnError) {
156
+ throw finalError;
157
+ }
158
+ // TODO: we probably want to return error and improve types
159
+ return responseStyle === 'data'
160
+ ? undefined
161
+ : {
162
+ error: finalError,
163
+ request,
164
+ response,
165
+ };
166
+ }
167
+ };
168
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
169
+ const makeSseFn = (method) => async (options) => {
170
+ const { opts, url } = await beforeRequest(options);
171
+ return createSseClient({
172
+ ...opts,
173
+ body: opts.body,
174
+ method,
175
+ onRequest: async (url, init) => {
176
+ let request = new Request(url, init);
177
+ for (const fn of interceptors.request.fns) {
178
+ if (fn) {
179
+ request = await fn(request, opts);
180
+ }
181
+ }
182
+ return request;
183
+ },
184
+ serializedBody: getValidRequestBody(opts),
185
+ url,
186
+ });
187
+ };
188
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
189
+ return {
190
+ buildUrl: _buildUrl,
191
+ connect: makeMethodFn('CONNECT'),
192
+ delete: makeMethodFn('DELETE'),
193
+ get: makeMethodFn('GET'),
194
+ getConfig,
195
+ head: makeMethodFn('HEAD'),
196
+ interceptors,
197
+ options: makeMethodFn('OPTIONS'),
198
+ patch: makeMethodFn('PATCH'),
199
+ post: makeMethodFn('POST'),
200
+ put: makeMethodFn('PUT'),
201
+ request,
202
+ setConfig,
203
+ sse: {
204
+ connect: makeSseFn('CONNECT'),
205
+ delete: makeSseFn('DELETE'),
206
+ get: makeSseFn('GET'),
207
+ head: makeSseFn('HEAD'),
208
+ options: makeSseFn('OPTIONS'),
209
+ patch: makeSseFn('PATCH'),
210
+ post: makeSseFn('POST'),
211
+ put: makeSseFn('PUT'),
212
+ trace: makeSseFn('TRACE'),
213
+ },
214
+ trace: makeMethodFn('TRACE'),
215
+ };
216
+ };
@@ -0,0 +1,10 @@
1
+ export type { Auth } from '../core/auth.gen.ts';
2
+ export type { QuerySerializerOptions } from '../core/bodySerializer.gen.ts';
3
+ export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.ts';
4
+ export { buildClientParams } from '../core/params.gen.ts';
5
+ export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.ts';
6
+ export type { ServerSentEventsResult } from '../core/serverSentEvents.gen.ts';
7
+ export type { ClientMeta } from '../core/types.gen.ts';
8
+ export { createClient } from './client.gen.ts';
9
+ export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.ts';
10
+ export { createConfig, mergeHeaders } from './utils.gen.ts';
@@ -0,0 +1,6 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js';
3
+ export { buildClientParams } from '../core/params.gen.js';
4
+ export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js';
5
+ export { createClient } from './client.gen.js';
6
+ export { createConfig, mergeHeaders } from './utils.gen.js';