@jutsustack/api-codegen 0.1.0 → 0.2.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 +574 -141
- package/dist/cache/manifest.d.ts +0 -1
- package/dist/cache/manifest.d.ts.map +1 -1
- package/dist/cache/manifest.js +1 -1
- package/dist/cache/manifest.js.map +1 -1
- package/dist/cjs/cache/manifest.d.ts +34 -0
- package/dist/cjs/cache/manifest.js +45 -0
- package/dist/cjs/cli.d.ts +8 -0
- package/dist/cjs/cli.js +245 -0
- package/dist/cjs/codegen/emit-api.d.ts +6 -0
- package/dist/cjs/codegen/emit-api.js +108 -0
- package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
- package/dist/cjs/codegen/emit-bindings.js +115 -0
- package/dist/cjs/codegen/emit-types.d.ts +10 -0
- package/dist/cjs/codegen/emit-types.js +232 -0
- package/dist/cjs/codegen/emit.d.ts +28 -0
- package/dist/cjs/codegen/emit.js +180 -0
- package/dist/cjs/codegen/files.d.ts +14 -0
- package/dist/cjs/codegen/files.js +66 -0
- package/dist/cjs/codegen/plan.d.ts +32 -0
- package/dist/cjs/codegen/plan.js +84 -0
- package/dist/cjs/codegen/print.d.ts +10 -0
- package/dist/cjs/codegen/print.js +65 -0
- package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
- package/dist/cjs/codegen/templates/bindings.js +707 -0
- package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
- package/dist/cjs/codegen/templates/runtime.js +1401 -0
- package/dist/cjs/codegen/templates/transports.d.ts +1 -0
- package/dist/cjs/codegen/templates/transports.js +272 -0
- package/dist/cjs/codegen/tsType.d.ts +15 -0
- package/dist/cjs/codegen/tsType.js +114 -0
- package/dist/cjs/collect/collect.d.ts +16 -0
- package/dist/cjs/collect/collect.js +472 -0
- package/dist/cjs/collect/naming.d.ts +25 -0
- package/dist/cjs/collect/naming.js +149 -0
- package/dist/cjs/collect/path.d.ts +10 -0
- package/dist/cjs/collect/path.js +67 -0
- package/dist/cjs/config/init.d.ts +37 -0
- package/dist/cjs/config/init.js +143 -0
- package/dist/cjs/config/load.d.ts +11 -0
- package/dist/cjs/config/load.js +121 -0
- package/dist/cjs/config/types.d.ts +88 -0
- package/dist/cjs/config/types.js +2 -0
- package/dist/cjs/config/validate.d.ts +8 -0
- package/dist/cjs/config/validate.js +200 -0
- package/dist/cjs/generate.d.ts +55 -0
- package/dist/cjs/generate.js +263 -0
- package/dist/cjs/index.d.ts +23 -0
- package/dist/cjs/index.js +48 -0
- package/dist/cjs/model/collection.d.ts +83 -0
- package/dist/cjs/model/collection.js +16 -0
- package/dist/cjs/model/infer.d.ts +7 -0
- package/dist/cjs/model/infer.js +95 -0
- package/dist/cjs/model/merge.d.ts +3 -0
- package/dist/cjs/model/merge.js +131 -0
- package/dist/cjs/model/reserved.d.ts +2 -0
- package/dist/cjs/model/reserved.js +128 -0
- package/dist/cjs/model/schema.d.ts +54 -0
- package/dist/cjs/model/schema.js +2 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
- package/dist/cjs/parsers/openapi-schema.js +241 -0
- package/dist/cjs/parsers/openapi.d.ts +8 -0
- package/dist/cjs/parsers/openapi.js +435 -0
- package/dist/cjs/parsers/postman.d.ts +20 -0
- package/dist/cjs/parsers/postman.js +493 -0
- package/dist/cjs/parsers/types.d.ts +52 -0
- package/dist/cjs/parsers/types.js +2 -0
- package/dist/cjs/sources/load.d.ts +25 -0
- package/dist/cjs/sources/load.js +296 -0
- package/dist/cjs/sources/parse.d.ts +4 -0
- package/dist/cjs/sources/parse.js +50 -0
- package/dist/cjs/util/errors.d.ts +9 -0
- package/dist/cjs/util/errors.js +23 -0
- package/dist/cjs/util/fs.d.ts +7 -0
- package/dist/cjs/util/fs.js +44 -0
- package/dist/cjs/util/hash.d.ts +3 -0
- package/dist/cjs/util/hash.js +26 -0
- package/dist/cjs/util/json.d.ts +10 -0
- package/dist/cjs/util/json.js +31 -0
- package/dist/cjs/util/log.d.ts +22 -0
- package/dist/cjs/util/log.js +45 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cli.d.ts +3 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +42 -12
- package/dist/cli.js.map +1 -1
- package/dist/codegen/emit-api.d.ts +3 -1
- package/dist/codegen/emit-api.d.ts.map +1 -1
- package/dist/codegen/emit-api.js +32 -7
- package/dist/codegen/emit-api.js.map +1 -1
- package/dist/codegen/emit-bindings.d.ts +9 -0
- package/dist/codegen/emit-bindings.d.ts.map +1 -0
- package/dist/codegen/emit-bindings.js +112 -0
- package/dist/codegen/emit-bindings.js.map +1 -0
- package/dist/codegen/emit-types.d.ts +8 -1
- package/dist/codegen/emit-types.d.ts.map +1 -1
- package/dist/codegen/emit-types.js +10 -8
- package/dist/codegen/emit-types.js.map +1 -1
- package/dist/codegen/emit.d.ts +10 -1
- package/dist/codegen/emit.d.ts.map +1 -1
- package/dist/codegen/emit.js +142 -37
- package/dist/codegen/emit.js.map +1 -1
- package/dist/codegen/files.d.ts +3 -12
- package/dist/codegen/files.d.ts.map +1 -1
- package/dist/codegen/files.js +3 -12
- package/dist/codegen/files.js.map +1 -1
- package/dist/codegen/print.d.ts +1 -4
- package/dist/codegen/print.d.ts.map +1 -1
- package/dist/codegen/print.js +1 -4
- package/dist/codegen/print.js.map +1 -1
- package/dist/codegen/templates/bindings.d.ts +14 -0
- package/dist/codegen/templates/bindings.d.ts.map +1 -0
- package/dist/codegen/templates/bindings.js +705 -0
- package/dist/codegen/templates/bindings.js.map +1 -0
- package/dist/codegen/templates/runtime.d.ts +2 -1
- package/dist/codegen/templates/runtime.d.ts.map +1 -1
- package/dist/codegen/templates/runtime.js +1192 -279
- package/dist/codegen/templates/runtime.js.map +1 -1
- package/dist/codegen/templates/transports.d.ts +2 -0
- package/dist/codegen/templates/transports.d.ts.map +1 -0
- package/dist/codegen/templates/transports.js +270 -0
- package/dist/codegen/templates/transports.js.map +1 -0
- package/dist/collect/collect.d.ts +1 -11
- package/dist/collect/collect.d.ts.map +1 -1
- package/dist/collect/collect.js +21 -28
- package/dist/collect/collect.js.map +1 -1
- package/dist/collect/naming.d.ts +1 -4
- package/dist/collect/naming.d.ts.map +1 -1
- package/dist/collect/naming.js +1 -4
- package/dist/collect/naming.js.map +1 -1
- package/dist/collect/path.d.ts +2 -9
- package/dist/collect/path.d.ts.map +1 -1
- package/dist/collect/path.js +2 -9
- package/dist/collect/path.js.map +1 -1
- package/dist/config/init.d.ts +11 -2
- package/dist/config/init.d.ts.map +1 -1
- package/dist/config/init.js +55 -7
- package/dist/config/init.js.map +1 -1
- package/dist/config/load.d.ts.map +1 -1
- package/dist/config/load.js +26 -1
- package/dist/config/load.js.map +1 -1
- package/dist/config/types.d.ts +13 -5
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/validate.d.ts +2 -6
- package/dist/config/validate.d.ts.map +1 -1
- package/dist/config/validate.js +18 -7
- package/dist/config/validate.js.map +1 -1
- package/dist/generate.d.ts +2 -8
- package/dist/generate.d.ts.map +1 -1
- package/dist/generate.js +13 -12
- package/dist/generate.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/model/infer.d.ts +2 -9
- package/dist/model/infer.d.ts.map +1 -1
- package/dist/model/infer.js +2 -9
- package/dist/model/infer.js.map +1 -1
- package/dist/model/merge.d.ts +1 -5
- package/dist/model/merge.d.ts.map +1 -1
- package/dist/model/merge.js +1 -5
- package/dist/model/merge.js.map +1 -1
- package/dist/model/reserved.d.ts +1 -4
- package/dist/model/reserved.d.ts.map +1 -1
- package/dist/model/reserved.js +63 -4
- package/dist/model/reserved.js.map +1 -1
- package/dist/model/schema.d.ts +1 -4
- package/dist/model/schema.d.ts.map +1 -1
- package/dist/parsers/openapi-schema.d.ts +1 -5
- package/dist/parsers/openapi-schema.d.ts.map +1 -1
- package/dist/parsers/openapi-schema.js +2 -5
- package/dist/parsers/openapi-schema.js.map +1 -1
- package/dist/parsers/postman.d.ts +0 -3
- package/dist/parsers/postman.d.ts.map +1 -1
- package/dist/parsers/postman.js +2 -5
- package/dist/parsers/postman.js.map +1 -1
- package/dist/sources/load.d.ts +0 -6
- package/dist/sources/load.d.ts.map +1 -1
- package/dist/sources/load.js +4 -7
- package/dist/sources/load.js.map +1 -1
- package/dist/sources/parse.d.ts +0 -2
- package/dist/sources/parse.d.ts.map +1 -1
- package/dist/sources/parse.js +1 -1
- package/dist/sources/parse.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +40 -12
- package/schema/config.schema.json +58 -12
- package/dist/codegen/emit-hooks.d.ts +0 -5
- package/dist/codegen/emit-hooks.d.ts.map +0 -1
- package/dist/codegen/emit-hooks.js +0 -67
- package/dist/codegen/emit-hooks.js.map +0 -1
- package/dist/codegen/templates/hooks.d.ts +0 -11
- package/dist/codegen/templates/hooks.d.ts.map +0 -1
- package/dist/codegen/templates/hooks.js +0 -272
- package/dist/codegen/templates/hooks.js.map +0 -1
|
@@ -0,0 +1,1401 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Source of the generated runtime.ts. Inside String.raw: no backticks, no dollar braces.
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.RUNTIME = void 0;
|
|
5
|
+
exports.runtimeSource = runtimeSource;
|
|
6
|
+
const transports_js_1 = require("./transports.js");
|
|
7
|
+
exports.RUNTIME = String.raw `// ─── Basics ─────────────────────────────────────────────────────────────────
|
|
8
|
+
|
|
9
|
+
export type HttpMethod = 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
10
|
+
export type QueryValue = string | number | boolean | Date | null | undefined;
|
|
11
|
+
export type Query = Record<string, QueryValue | readonly QueryValue[]>;
|
|
12
|
+
export type BodyEncoding = 'json' | 'urlencoded' | 'multipart' | 'text' | 'binary';
|
|
13
|
+
export type ResponseKind = 'json' | 'text' | 'blob' | 'arraybuffer';
|
|
14
|
+
export type HeaderValues = Record<string, string | undefined>;
|
|
15
|
+
|
|
16
|
+
/** A file part on React Native: a file:// or content:// uri. */
|
|
17
|
+
export interface NativeFile {
|
|
18
|
+
uri: string;
|
|
19
|
+
name: string;
|
|
20
|
+
type: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A file part: a Blob / File on the web, a NativeFile on React Native. */
|
|
24
|
+
export type FileInput = Blob | NativeFile;
|
|
25
|
+
|
|
26
|
+
/** Multipart body: a FormData, or a plain fields object (encoded by the transport). */
|
|
27
|
+
export type MultipartBody = FormData;
|
|
28
|
+
|
|
29
|
+
export type BinaryBody = Blob | ArrayBuffer | ArrayBufferView | NativeFile;
|
|
30
|
+
|
|
31
|
+
/** Extra fetch() options: cache, credentials, mode… and Next.js next: { revalidate, tags }. */
|
|
32
|
+
export interface FetchInit extends Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'> {
|
|
33
|
+
next?: { revalidate?: number | false; tags?: string[] };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ─── Errors ─────────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
export type ApiErrorKind = 'HTTP' | 'NETWORK' | 'TIMEOUT' | 'ABORTED' | 'PARSE';
|
|
39
|
+
|
|
40
|
+
const API_ERROR = Symbol.for('@jutsustack/api-codegen/ApiError');
|
|
41
|
+
|
|
42
|
+
export class ApiError<TData = unknown> extends Error {
|
|
43
|
+
readonly kind: ApiErrorKind;
|
|
44
|
+
/** HTTP status; 0 when no response was received */
|
|
45
|
+
readonly status: number;
|
|
46
|
+
/** decoded response body (HTTP errors) */
|
|
47
|
+
readonly data: TData | undefined;
|
|
48
|
+
readonly headers: Record<string, string>;
|
|
49
|
+
readonly method: HttpMethod;
|
|
50
|
+
/** full request URL, query included */
|
|
51
|
+
readonly url: string;
|
|
52
|
+
/** endpoint id ('users.getUser') when the call came from the generated api */
|
|
53
|
+
readonly endpoint: string | undefined;
|
|
54
|
+
/** underlying error (network failure, JSON syntax error, …) */
|
|
55
|
+
readonly originalError: unknown;
|
|
56
|
+
/** message for people, from the configured error messages; never server internals by default */
|
|
57
|
+
userMessage: string;
|
|
58
|
+
|
|
59
|
+
constructor(
|
|
60
|
+
kind: ApiErrorKind,
|
|
61
|
+
init: {
|
|
62
|
+
method: HttpMethod;
|
|
63
|
+
url: string;
|
|
64
|
+
status?: number;
|
|
65
|
+
data?: TData;
|
|
66
|
+
headers?: Record<string, string>;
|
|
67
|
+
endpoint?: string | undefined;
|
|
68
|
+
message?: string;
|
|
69
|
+
originalError?: unknown;
|
|
70
|
+
}
|
|
71
|
+
) {
|
|
72
|
+
const status = init.status ?? 0;
|
|
73
|
+
const where = init.method + ' ' + stripQuery(init.url);
|
|
74
|
+
super(init.message ?? (status ? kind + ' ' + status + ' ' + where : kind + ' ' + where));
|
|
75
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
76
|
+
this.name = 'ApiError';
|
|
77
|
+
this.kind = kind;
|
|
78
|
+
this.status = status;
|
|
79
|
+
this.data = init.data;
|
|
80
|
+
this.headers = init.headers ?? {};
|
|
81
|
+
this.method = init.method;
|
|
82
|
+
this.url = init.url;
|
|
83
|
+
this.endpoint = init.endpoint;
|
|
84
|
+
this.originalError = init.originalError;
|
|
85
|
+
this.userMessage = '';
|
|
86
|
+
Object.defineProperty(this, API_ERROR, { value: true });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Safe for logs: no body, headers or query string. */
|
|
90
|
+
toJSON(): Record<string, unknown> {
|
|
91
|
+
return {
|
|
92
|
+
name: this.name,
|
|
93
|
+
kind: this.kind,
|
|
94
|
+
status: this.status,
|
|
95
|
+
method: this.method,
|
|
96
|
+
url: stripQuery(this.url),
|
|
97
|
+
endpoint: this.endpoint,
|
|
98
|
+
message: this.message,
|
|
99
|
+
userMessage: this.userMessage,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Works across bundles (e.g. Next.js server and client copies of this module). */
|
|
105
|
+
export function isApiError(error: unknown): error is ApiError {
|
|
106
|
+
return (
|
|
107
|
+
error instanceof ApiError ||
|
|
108
|
+
(typeof error === 'object' && error !== null && (error as Record<symbol, unknown>)[API_ERROR] === true)
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 'https://api.example.com' (lower case) for an absolute URL, undefined for a relative one. */
|
|
113
|
+
function originOf(url: string): string | undefined {
|
|
114
|
+
const match = /^([a-z][a-z\d+\-.]*:\/\/[^/?#]*)/i.exec(url);
|
|
115
|
+
return match ? (match[1] as string).toLowerCase() : undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function stripQuery(url: string): string {
|
|
119
|
+
const i = url.indexOf('?');
|
|
120
|
+
return i === -1 ? url : url.slice(0, i);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ─── Error messages ─────────────────────────────────────────────────────────
|
|
124
|
+
|
|
125
|
+
export type ErrorMessage = string | ((error: ApiError) => string | undefined);
|
|
126
|
+
|
|
127
|
+
/** Messages by status, status class, failure kind or 'default'; the most specific key wins. */
|
|
128
|
+
export interface ErrorMessages {
|
|
129
|
+
[status: number]: ErrorMessage | undefined;
|
|
130
|
+
'4XX'?: ErrorMessage;
|
|
131
|
+
'5XX'?: ErrorMessage;
|
|
132
|
+
'NETWORK'?: ErrorMessage;
|
|
133
|
+
'TIMEOUT'?: ErrorMessage;
|
|
134
|
+
'ABORTED'?: ErrorMessage;
|
|
135
|
+
'PARSE'?: ErrorMessage;
|
|
136
|
+
'default'?: ErrorMessage;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Built-in English messages; override any of them with the messages option. */
|
|
140
|
+
export const defaultErrorMessages: ErrorMessages = {
|
|
141
|
+
400: 'The request was not valid.',
|
|
142
|
+
401: 'Please sign in to continue.',
|
|
143
|
+
403: 'You do not have permission to do that.',
|
|
144
|
+
404: 'We could not find what you were looking for.',
|
|
145
|
+
408: 'The server took too long to respond. Please try again.',
|
|
146
|
+
409: 'This conflicts with the current state. Refresh and try again.',
|
|
147
|
+
413: 'That is too large to send.',
|
|
148
|
+
422: 'Some of the information is not valid.',
|
|
149
|
+
429: 'Too many requests. Please wait a moment and try again.',
|
|
150
|
+
'4XX': 'The request could not be completed.',
|
|
151
|
+
'5XX': 'Something went wrong on our side. Please try again later.',
|
|
152
|
+
'NETWORK': 'Cannot reach the server. Check your connection and try again.',
|
|
153
|
+
'TIMEOUT': 'The server took too long to respond. Please try again.',
|
|
154
|
+
'ABORTED': 'The request was cancelled.',
|
|
155
|
+
'PARSE': 'The server sent a response that could not be read.',
|
|
156
|
+
'default': 'Something went wrong. Please try again.',
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
function messageKeys(error: ApiError): Array<keyof ErrorMessages> {
|
|
160
|
+
if (error.kind !== 'HTTP') return [error.kind, 'default'];
|
|
161
|
+
const keys: Array<keyof ErrorMessages> = [error.status];
|
|
162
|
+
if (error.status >= 400 && error.status < 500) keys.push('4XX');
|
|
163
|
+
if (error.status >= 500 && error.status < 600) keys.push('5XX');
|
|
164
|
+
keys.push('default');
|
|
165
|
+
return keys;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function resolveMessage(error: ApiError, layers: ReadonlyArray<ErrorMessages | undefined>): string {
|
|
169
|
+
const keys = messageKeys(error);
|
|
170
|
+
for (const layer of layers) {
|
|
171
|
+
if (!layer) continue;
|
|
172
|
+
for (const key of keys) {
|
|
173
|
+
const entry = layer[key as number];
|
|
174
|
+
if (entry === undefined) continue;
|
|
175
|
+
let text: string | undefined;
|
|
176
|
+
try {
|
|
177
|
+
text = typeof entry === 'function' ? entry(error) : entry;
|
|
178
|
+
} catch {
|
|
179
|
+
text = undefined;
|
|
180
|
+
}
|
|
181
|
+
if (text) return text;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return defaultErrorMessages.default as string;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A message for people for anything a call can throw; other errors get the generic message. */
|
|
188
|
+
export function getErrorMessage(error: unknown, messages?: ErrorMessages): string {
|
|
189
|
+
if (isApiError(error)) {
|
|
190
|
+
if (!messages && error.userMessage) return error.userMessage;
|
|
191
|
+
return resolveMessage(error, [messages, defaultErrorMessages]);
|
|
192
|
+
}
|
|
193
|
+
return (messages && typeof messages.default === 'string' && messages.default) || (defaultErrorMessages.default as string);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ─── Retry ──────────────────────────────────────────────────────────────────
|
|
197
|
+
|
|
198
|
+
export interface RetryPolicy {
|
|
199
|
+
/** retries after the first attempt (default 2, max 10) */
|
|
200
|
+
attempts?: number;
|
|
201
|
+
/** delay before retry n (1-based); default 300 ms · 2^(n-1) with jitter */
|
|
202
|
+
delayMs?: number | ((attempt: number, error: ApiError) => number);
|
|
203
|
+
/** cap for every delay, Retry-After included (default 30000) */
|
|
204
|
+
maxDelayMs?: number;
|
|
205
|
+
/** default: network errors, timeouts, 408/429/500/502/503/504; only idempotent calls retry */
|
|
206
|
+
retryOn?: (error: ApiError, attempt: number) => boolean;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** false / 0: off (default) · true: the default policy · n: n retries · or a policy. */
|
|
210
|
+
export type RetryOption = boolean | number | RetryPolicy;
|
|
211
|
+
|
|
212
|
+
interface Retry {
|
|
213
|
+
attempts: number;
|
|
214
|
+
policy: RetryPolicy;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const IDEMPOTENT: readonly HttpMethod[] = ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'];
|
|
218
|
+
const RETRY_STATUS: readonly number[] = [408, 429, 500, 502, 503, 504];
|
|
219
|
+
|
|
220
|
+
function normalizeRetry(option: RetryOption | undefined): Retry {
|
|
221
|
+
if (option === undefined || option === false) return { attempts: 0, policy: {} };
|
|
222
|
+
if (option === true) return { attempts: 2, policy: {} };
|
|
223
|
+
const policy = typeof option === 'number' ? {} : option;
|
|
224
|
+
const wanted = typeof option === 'number' ? option : (option.attempts ?? 2);
|
|
225
|
+
const attempts = Number.isFinite(wanted) ? Math.min(10, Math.max(0, Math.floor(wanted))) : 0;
|
|
226
|
+
return { attempts, policy };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function shouldRetry(error: ApiError, attempt: number, retry: Retry, idempotent: boolean): boolean {
|
|
230
|
+
if (!idempotent || error.kind === 'ABORTED' || attempt > retry.attempts) return false;
|
|
231
|
+
if (retry.policy.retryOn) {
|
|
232
|
+
try {
|
|
233
|
+
return retry.policy.retryOn(error, attempt);
|
|
234
|
+
} catch {
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return error.kind === 'NETWORK' || error.kind === 'TIMEOUT' || (error.kind === 'HTTP' && RETRY_STATUS.indexOf(error.status) !== -1);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Largest delay setTimeout honours. */
|
|
242
|
+
const MAX_DELAY = 2147483647;
|
|
243
|
+
|
|
244
|
+
function delayOr(value: unknown, fallback: number): number {
|
|
245
|
+
if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return fallback;
|
|
246
|
+
return Math.min(value, MAX_DELAY);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function retryDelay(error: ApiError, attempt: number, policy: RetryPolicy): number {
|
|
250
|
+
const max = delayOr(policy.maxDelayMs, 30000);
|
|
251
|
+
let delay: number;
|
|
252
|
+
if (typeof policy.delayMs === 'function') delay = policy.delayMs(attempt, error);
|
|
253
|
+
else if (typeof policy.delayMs === 'number') delay = policy.delayMs;
|
|
254
|
+
else delay = 300 * Math.pow(2, attempt - 1) * (0.75 + Math.random() * 0.5);
|
|
255
|
+
const after = retryAfterMs(error.headers['retry-after']);
|
|
256
|
+
if (after !== undefined && after > delay) delay = after;
|
|
257
|
+
return Math.min(max, Math.max(0, Number.isFinite(delay) ? delay : 0));
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function retryAfterMs(value: string | undefined): number | undefined {
|
|
261
|
+
if (!value) return undefined;
|
|
262
|
+
const seconds = Number(value);
|
|
263
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
|
|
264
|
+
const date = Date.parse(value);
|
|
265
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ─── Transport ──────────────────────────────────────────────────────────────
|
|
269
|
+
|
|
270
|
+
/** What a transport is asked to send. Headers are lower-case. */
|
|
271
|
+
export interface TransportRequest {
|
|
272
|
+
method: HttpMethod;
|
|
273
|
+
/** path params filled in and query appended; absolute when baseURL is set */
|
|
274
|
+
url: string;
|
|
275
|
+
/** endpoint path template, e.g. /users/:id */
|
|
276
|
+
path: string;
|
|
277
|
+
/** endpoint id, e.g. users.getUser */
|
|
278
|
+
endpoint: string | undefined;
|
|
279
|
+
headers: Record<string, string>;
|
|
280
|
+
/** the body as the caller passed it; encode it with encodeBody() if needed */
|
|
281
|
+
body: unknown;
|
|
282
|
+
contentType: BodyEncoding | undefined;
|
|
283
|
+
responseType: ResponseKind | undefined;
|
|
284
|
+
/** aborted on timeout or when the caller cancels */
|
|
285
|
+
signal: AbortSignal;
|
|
286
|
+
timeoutMs: number;
|
|
287
|
+
skipAuth: boolean;
|
|
288
|
+
idempotencyKey: string | undefined;
|
|
289
|
+
/** 1 for the first try */
|
|
290
|
+
attempt: number;
|
|
291
|
+
init: FetchInit | undefined;
|
|
292
|
+
/** passed through to the HTTP library untouched */
|
|
293
|
+
adapterOptions: Record<string, unknown> | undefined;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** A response as middleware sees it: lower-case headers, data decoded. */
|
|
297
|
+
export interface TransportResponse {
|
|
298
|
+
status: number;
|
|
299
|
+
headers: Record<string, string>;
|
|
300
|
+
data: unknown;
|
|
301
|
+
url?: string;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Response headers as a plain object (any case) or a Headers-like object. */
|
|
305
|
+
export type ResponseHeaders =
|
|
306
|
+
| Record<string, string | number | readonly string[] | null | undefined>
|
|
307
|
+
| { forEach(callback: (value: string, key: string) => void): void };
|
|
308
|
+
|
|
309
|
+
/** What a transport or middleware resolves with; headers and JSON text are normalised. */
|
|
310
|
+
export interface RawResponse {
|
|
311
|
+
status: number;
|
|
312
|
+
headers?: ResponseHeaders | null | undefined;
|
|
313
|
+
data?: unknown;
|
|
314
|
+
url?: string | null | undefined;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Sends one request. Resolve for every HTTP status; reject only when no response arrived. */
|
|
318
|
+
export type Transport = (request: TransportRequest) => Promise<RawResponse>;
|
|
319
|
+
|
|
320
|
+
export type MiddlewareNext = (request: TransportRequest) => Promise<TransportResponse>;
|
|
321
|
+
|
|
322
|
+
function headerRecord(source: unknown): Record<string, string> {
|
|
323
|
+
const out: Record<string, string> = {};
|
|
324
|
+
if (!source || typeof source !== 'object') return out;
|
|
325
|
+
const add = (key: string, value: unknown) => {
|
|
326
|
+
if (value === undefined || value === null) return;
|
|
327
|
+
out[String(key).toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);
|
|
328
|
+
};
|
|
329
|
+
// AxiosHeaders has toJSON; Headers and Map have forEach
|
|
330
|
+
const json = (source as { toJSON?: unknown }).toJSON;
|
|
331
|
+
const value = typeof json === 'function' ? (json.call(source) as unknown) : source;
|
|
332
|
+
if (!value || typeof value !== 'object') return out;
|
|
333
|
+
const each = (value as { forEach?: unknown }).forEach;
|
|
334
|
+
if (typeof each === 'function' && !Array.isArray(value)) {
|
|
335
|
+
each.call(value, (v: unknown, k: unknown) => add(String(k), v));
|
|
336
|
+
} else {
|
|
337
|
+
for (const key of Object.keys(value)) add(key, (value as Record<string, unknown>)[key]);
|
|
338
|
+
}
|
|
339
|
+
return out;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function toResponse(raw: unknown, request: TransportRequest): TransportResponse {
|
|
343
|
+
const r = raw as RawResponse | null | undefined;
|
|
344
|
+
if (!r || typeof r.status !== 'number') {
|
|
345
|
+
throw new ApiError('PARSE', {
|
|
346
|
+
method: request.method,
|
|
347
|
+
url: request.url,
|
|
348
|
+
endpoint: request.endpoint,
|
|
349
|
+
message: 'PARSE ' + request.method + ' ' + stripQuery(request.url) + ': the transport returned no response',
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
const headers = headerRecord(r.headers);
|
|
353
|
+
let data = r.data;
|
|
354
|
+
const type = headers['content-type'] || '';
|
|
355
|
+
const wantsJson = request.responseType === undefined || request.responseType === 'json';
|
|
356
|
+
if (typeof data === 'string' && wantsJson && type.indexOf('json') !== -1) {
|
|
357
|
+
if (data.trim() === '') data = undefined;
|
|
358
|
+
else {
|
|
359
|
+
try {
|
|
360
|
+
data = JSON.parse(data);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
// an unreadable error body stays text
|
|
363
|
+
if (r.status >= 200 && r.status < 300) {
|
|
364
|
+
throw new ApiError('PARSE', {
|
|
365
|
+
method: request.method,
|
|
366
|
+
url: request.url,
|
|
367
|
+
status: r.status,
|
|
368
|
+
headers,
|
|
369
|
+
endpoint: request.endpoint,
|
|
370
|
+
originalError: error,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
const response: TransportResponse = { status: r.status, headers, data };
|
|
377
|
+
if (typeof r.url === 'string') response.url = r.url;
|
|
378
|
+
return response;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Wraps every attempt: call next(request) to continue, or return a response yourself. */
|
|
382
|
+
export type Middleware = (request: TransportRequest, next: MiddlewareNext) => Promise<RawResponse>;
|
|
383
|
+
|
|
384
|
+
function checkMiddleware(middleware: readonly Middleware[] | undefined, where: string): readonly Middleware[] {
|
|
385
|
+
if (middleware === undefined) return [];
|
|
386
|
+
if (!Array.isArray(middleware)) throw new TypeError(where + ': "middleware" must be an array of functions');
|
|
387
|
+
middleware.forEach((m, i) => {
|
|
388
|
+
if (typeof m !== 'function') throw new TypeError(where + ': middleware[' + i + '] is not a function');
|
|
389
|
+
});
|
|
390
|
+
return middleware;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function chain(middleware: readonly Middleware[], last: MiddlewareNext): MiddlewareNext {
|
|
394
|
+
return middleware.reduceRight<MiddlewareNext>(
|
|
395
|
+
(next, m) => (request) => Promise.resolve(m(request, next)).then((raw) => toResponse(raw, request)),
|
|
396
|
+
last
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function normalised(transport: Transport): MiddlewareNext {
|
|
401
|
+
return (request) => Promise.resolve(transport(request)).then((raw) => toResponse(raw, request));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Wraps a transport in middleware (first = outermost). */
|
|
405
|
+
export function applyMiddleware(transport: Transport, middleware: readonly Middleware[]): Transport {
|
|
406
|
+
if (typeof transport !== 'function') throw new TypeError('applyMiddleware: "transport" must be a function');
|
|
407
|
+
return chain(checkMiddleware(middleware, 'applyMiddleware'), normalised(transport));
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// ─── Client ─────────────────────────────────────────────────────────────────
|
|
411
|
+
|
|
412
|
+
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
|
|
413
|
+
|
|
414
|
+
export interface ApiLogger {
|
|
415
|
+
debug?(message: string, details?: Record<string, unknown>): void;
|
|
416
|
+
info?(message: string, details?: Record<string, unknown>): void;
|
|
417
|
+
warn?(message: string, details?: Record<string, unknown>): void;
|
|
418
|
+
error?(message: string, details?: Record<string, unknown>): void;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** One finished call, for performance monitoring. */
|
|
422
|
+
export interface RequestMetric {
|
|
423
|
+
endpoint: string | undefined;
|
|
424
|
+
method: HttpMethod;
|
|
425
|
+
/** path template: no ids, no query (safe to send to analytics) */
|
|
426
|
+
path: string;
|
|
427
|
+
/** 0 when no response was received */
|
|
428
|
+
status: number;
|
|
429
|
+
ok: boolean;
|
|
430
|
+
errorKind: ApiErrorKind | undefined;
|
|
431
|
+
durationMs: number;
|
|
432
|
+
attempts: number;
|
|
433
|
+
fromFallback: boolean;
|
|
434
|
+
/** slower than slowRequestMs */
|
|
435
|
+
slow: boolean;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export interface ApiResponse<T> {
|
|
439
|
+
data: T;
|
|
440
|
+
status: number;
|
|
441
|
+
headers: Record<string, string>;
|
|
442
|
+
url: string;
|
|
443
|
+
durationMs: number;
|
|
444
|
+
attempts: number;
|
|
445
|
+
/** data came from a fallback, not from the server */
|
|
446
|
+
fromFallback: boolean;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Options every generated endpoint accepts (in its args object). */
|
|
450
|
+
export interface CallOptions<R = unknown> {
|
|
451
|
+
headers?: HeaderValues;
|
|
452
|
+
/** cancels the call; the hooks pass their own */
|
|
453
|
+
signal?: AbortSignal;
|
|
454
|
+
/** per attempt; overrides the client timeout; 0 disables it */
|
|
455
|
+
timeoutMs?: number;
|
|
456
|
+
/** body encoding; inferred when omitted (FormData → multipart, string → text, object → json) */
|
|
457
|
+
contentType?: BodyEncoding;
|
|
458
|
+
/** response decoding; inferred from Content-Type when omitted */
|
|
459
|
+
responseType?: ResponseKind;
|
|
460
|
+
/** do not attach the bearer token from getToken */
|
|
461
|
+
skipAuth?: boolean;
|
|
462
|
+
/** sent as Idempotency-Key; also makes non-idempotent methods eligible for retry */
|
|
463
|
+
idempotencyKey?: string;
|
|
464
|
+
retry?: RetryOption;
|
|
465
|
+
/** value to resolve with instead of throwing (not for cancelled calls) */
|
|
466
|
+
fallback?: (error: ApiError) => R | Promise<R>;
|
|
467
|
+
/** messages for this call; override endpoint and client messages */
|
|
468
|
+
messages?: ErrorMessages;
|
|
469
|
+
/** true when the call starts, false when it settles */
|
|
470
|
+
onLoading?: (loading: boolean) => void;
|
|
471
|
+
/** false keeps this call out of the logs (e.g. a login body) */
|
|
472
|
+
log?: boolean;
|
|
473
|
+
/** extra fetch() options (fetchTransport) */
|
|
474
|
+
init?: FetchInit;
|
|
475
|
+
/** options for the HTTP library (axios config, Angular HttpClient options, …) */
|
|
476
|
+
adapterOptions?: Record<string, unknown>;
|
|
477
|
+
/** runs inside the client and endpoint middleware, for this call only */
|
|
478
|
+
middleware?: readonly Middleware[];
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Per-endpoint defaults, set with createApi(client, { endpoints }). */
|
|
482
|
+
export type EndpointOptions<R = unknown> = Pick<
|
|
483
|
+
CallOptions<R>,
|
|
484
|
+
'headers' | 'timeoutMs' | 'skipAuth' | 'retry' | 'fallback' | 'messages' | 'log' | 'responseType' | 'init' | 'adapterOptions' | 'middleware'
|
|
485
|
+
>;
|
|
486
|
+
|
|
487
|
+
export interface RequestOptions<R = unknown> extends CallOptions<R> {
|
|
488
|
+
params?: Record<string, string | number>;
|
|
489
|
+
query?: Query;
|
|
490
|
+
body?: unknown;
|
|
491
|
+
/** endpoint id, for logs, metrics and errors */
|
|
492
|
+
endpoint?: string;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export interface ClientConfig {
|
|
496
|
+
/** fetch (default), axios, Angular HttpClient or a react-native-fetch client */
|
|
497
|
+
http?: HttpLibrary;
|
|
498
|
+
/** instead of http: your own function that sends a request (see Transport) */
|
|
499
|
+
transport?: Transport;
|
|
500
|
+
/** prepended to relative endpoint paths, e.g. 'https://api.example.com/v1' */
|
|
501
|
+
baseURL?: string;
|
|
502
|
+
/** headers for every call to a trusted origin; an object or a function */
|
|
503
|
+
headers?: HeaderValues | (() => HeaderValues | Promise<HeaderValues>);
|
|
504
|
+
/** bearer token for every call to a trusted origin */
|
|
505
|
+
getToken?: () => string | null | undefined | Promise<string | null | undefined>;
|
|
506
|
+
/** origins besides baseURL's that receive the token and client headers */
|
|
507
|
+
trustedOrigins?: readonly string[];
|
|
508
|
+
/** per attempt; default 30000 ms; 0 disables */
|
|
509
|
+
timeoutMs?: number;
|
|
510
|
+
/** query arrays: 'repeat' (a=1&a=2, default), 'comma' (a=1,2), 'brackets' (a[]=1&a[]=2) */
|
|
511
|
+
arrayFormat?: 'repeat' | 'comma' | 'brackets';
|
|
512
|
+
/** default retry policy (off unless set) */
|
|
513
|
+
retry?: RetryOption;
|
|
514
|
+
/** messages for people for every call */
|
|
515
|
+
messages?: ErrorMessages;
|
|
516
|
+
/** read a message from an error body; off by default to hide server internals */
|
|
517
|
+
messageFromResponse?: (error: ApiError) => string | undefined;
|
|
518
|
+
/** true logs to the console; or your logger */
|
|
519
|
+
logger?: boolean | ApiLogger;
|
|
520
|
+
/** default 'info' */
|
|
521
|
+
logLevel?: LogLevel;
|
|
522
|
+
/** include request and response bodies in debug / info logs (default false) */
|
|
523
|
+
logBodies?: boolean;
|
|
524
|
+
/** headers logged as [redacted] */
|
|
525
|
+
redactHeaders?: readonly string[];
|
|
526
|
+
/** log a warning and flag the metric when a call takes longer (ms) */
|
|
527
|
+
slowRequestMs?: number;
|
|
528
|
+
/** around every attempt, first = outermost; endpoint and call middleware run inside */
|
|
529
|
+
middleware?: readonly Middleware[];
|
|
530
|
+
/** before each attempt; may change request.headers (e.g. add a trace id) */
|
|
531
|
+
onRequest?: (request: TransportRequest) => void | Promise<void>;
|
|
532
|
+
/** after each successful call */
|
|
533
|
+
onResponse?: (response: ApiResponse<unknown>, request: TransportRequest) => void;
|
|
534
|
+
/** after each failed call (before any fallback); the error is still thrown */
|
|
535
|
+
onError?: (error: ApiError) => void;
|
|
536
|
+
/** after every call, for performance monitoring */
|
|
537
|
+
onMetrics?: (metric: RequestMetric) => void;
|
|
538
|
+
/** whenever the number of calls in flight changes (global spinner) */
|
|
539
|
+
onLoadingChange?: (pending: number) => void;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export interface ApiClient {
|
|
543
|
+
request<T = unknown>(method: HttpMethod, path: string, options?: RequestOptions<T>): Promise<ApiResponse<T>>;
|
|
544
|
+
/** calls in flight */
|
|
545
|
+
readonly pending: number;
|
|
546
|
+
/** listener runs whenever pending changes; returns unsubscribe */
|
|
547
|
+
subscribe(listener: (pending: number) => void): () => void;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** Anything with request(): a client from createClient(), or a test double. */
|
|
551
|
+
export type ApiRequester = Pick<ApiClient, 'request'>;
|
|
552
|
+
|
|
553
|
+
const DEFAULT_REDACT = [
|
|
554
|
+
'authorization',
|
|
555
|
+
'cookie',
|
|
556
|
+
'set-cookie',
|
|
557
|
+
'proxy-authorization',
|
|
558
|
+
'x-api-key',
|
|
559
|
+
'x-auth-token',
|
|
560
|
+
'x-csrf-token',
|
|
561
|
+
];
|
|
562
|
+
|
|
563
|
+
const LEVELS: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 };
|
|
564
|
+
|
|
565
|
+
function now(): number {
|
|
566
|
+
const perf = (globalThis as { performance?: { now(): number } }).performance;
|
|
567
|
+
return perf && typeof perf.now === 'function' ? perf.now() : Date.now();
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** Runs an observer; a throwing observer must not break the call. */
|
|
571
|
+
function safely(fn: () => void): void {
|
|
572
|
+
try {
|
|
573
|
+
fn();
|
|
574
|
+
} catch {
|
|
575
|
+
// observers only observe
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
export function createClient(config: ClientConfig = {}): ApiClient {
|
|
580
|
+
if (config.transport !== undefined && config.http !== undefined) {
|
|
581
|
+
throw new TypeError('createClient: pass "http" (a library) or "transport" (your own function), not both');
|
|
582
|
+
}
|
|
583
|
+
if (config.transport !== undefined && typeof config.transport !== 'function') {
|
|
584
|
+
throw new TypeError('createClient: "transport" must be a function');
|
|
585
|
+
}
|
|
586
|
+
const transport: Transport = config.transport ?? toTransport(config.http);
|
|
587
|
+
const sendNormalised = normalised(transport);
|
|
588
|
+
const clientMiddleware = checkMiddleware(config.middleware, 'createClient');
|
|
589
|
+
const redact = (config.redactHeaders ?? DEFAULT_REDACT).map((h) => h.toLowerCase());
|
|
590
|
+
const trusted = (config.trustedOrigins ?? []).map((o) => originOf(o) ?? o.toLowerCase());
|
|
591
|
+
const baseOrigin = originOf(config.baseURL ?? '');
|
|
592
|
+
if (baseOrigin) trusted.push(baseOrigin);
|
|
593
|
+
const mayReceiveCredentials = (url: string): boolean => {
|
|
594
|
+
const origin = originOf(url);
|
|
595
|
+
return origin === undefined || trusted.indexOf(origin) !== -1;
|
|
596
|
+
};
|
|
597
|
+
const logger: ApiLogger | undefined = config.logger === true ? console : config.logger || undefined;
|
|
598
|
+
const minLevel = LEVELS[config.logLevel ?? 'info'];
|
|
599
|
+
const listeners = new Set<(pending: number) => void>();
|
|
600
|
+
let pending = 0;
|
|
601
|
+
|
|
602
|
+
const log = (level: Exclude<LogLevel, 'silent'>, enabled: boolean, message: string, details: Record<string, unknown>) => {
|
|
603
|
+
if (!logger || !enabled || LEVELS[level] < minLevel) return;
|
|
604
|
+
const write = logger[level];
|
|
605
|
+
if (typeof write === 'function') safely(() => write.call(logger, message, details));
|
|
606
|
+
};
|
|
607
|
+
const setPending = (delta: number) => {
|
|
608
|
+
pending += delta;
|
|
609
|
+
const count = pending;
|
|
610
|
+
if (config.onLoadingChange) safely(() => config.onLoadingChange!(count));
|
|
611
|
+
listeners.forEach((listener) => safely(() => listener(count)));
|
|
612
|
+
};
|
|
613
|
+
const redacted = (headers: Record<string, string>) => {
|
|
614
|
+
const out: Record<string, string> = {};
|
|
615
|
+
for (const key of Object.keys(headers)) out[key] = redact.indexOf(key) !== -1 ? '[redacted]' : (headers[key] as string);
|
|
616
|
+
return out;
|
|
617
|
+
};
|
|
618
|
+
|
|
619
|
+
async function request<T = unknown>(
|
|
620
|
+
method: HttpMethod,
|
|
621
|
+
path: string,
|
|
622
|
+
options: RequestOptions<T> = {}
|
|
623
|
+
): Promise<ApiResponse<T>> {
|
|
624
|
+
const started = now();
|
|
625
|
+
const endpointId = options.endpoint;
|
|
626
|
+
const logged = options.log !== false;
|
|
627
|
+
const label = method + ' ' + path;
|
|
628
|
+
const url = buildUrl(config.baseURL ?? '', path, options.params, options.query, config.arrayFormat ?? 'repeat');
|
|
629
|
+
const retry = normalizeRetry(options.retry !== undefined ? options.retry : config.retry);
|
|
630
|
+
const idempotent = IDEMPOTENT.indexOf(method) !== -1 || !!options.idempotencyKey;
|
|
631
|
+
const timeoutMs = delayOr(options.timeoutMs ?? config.timeoutMs, 30000);
|
|
632
|
+
const middleware = clientMiddleware.concat(checkMiddleware(options.middleware, 'request'));
|
|
633
|
+
/** token and config.headers: only trusted origins get them */
|
|
634
|
+
const credentialHeaders: Record<string, string> = {};
|
|
635
|
+
let credentials = false;
|
|
636
|
+
let attempt = 0;
|
|
637
|
+
let lastRequest: TransportRequest | undefined;
|
|
638
|
+
|
|
639
|
+
const failure = (kind: ApiErrorKind, originalError?: unknown) =>
|
|
640
|
+
new ApiError(kind, { method, url, endpoint: endpointId, originalError });
|
|
641
|
+
|
|
642
|
+
const finish = (status: number, ok: boolean, kind: ApiErrorKind | undefined, fromFallback: boolean): number => {
|
|
643
|
+
const durationMs = Math.round(now() - started);
|
|
644
|
+
const slow = config.slowRequestMs !== undefined && durationMs > config.slowRequestMs;
|
|
645
|
+
if (slow) log('warn', logged, 'slow request: ' + label + ' took ' + durationMs + ' ms', { endpoint: endpointId, durationMs });
|
|
646
|
+
if (config.onMetrics) {
|
|
647
|
+
const metric: RequestMetric = {
|
|
648
|
+
endpoint: endpointId,
|
|
649
|
+
method,
|
|
650
|
+
path,
|
|
651
|
+
status,
|
|
652
|
+
ok,
|
|
653
|
+
errorKind: kind,
|
|
654
|
+
durationMs,
|
|
655
|
+
attempts: attempt,
|
|
656
|
+
fromFallback,
|
|
657
|
+
slow,
|
|
658
|
+
};
|
|
659
|
+
safely(() => config.onMetrics!(metric));
|
|
660
|
+
}
|
|
661
|
+
return durationMs;
|
|
662
|
+
};
|
|
663
|
+
|
|
664
|
+
const attemptOnce = async (headers: Record<string, string>): Promise<TransportResponse> => {
|
|
665
|
+
const controller = new AbortController();
|
|
666
|
+
const external = options.signal;
|
|
667
|
+
let timedOut = false;
|
|
668
|
+
const onAbort = () => controller.abort();
|
|
669
|
+
if (external) {
|
|
670
|
+
if (external.aborted) controller.abort();
|
|
671
|
+
else external.addEventListener('abort', onAbort);
|
|
672
|
+
}
|
|
673
|
+
const timer =
|
|
674
|
+
timeoutMs > 0
|
|
675
|
+
? setTimeout(() => {
|
|
676
|
+
timedOut = true;
|
|
677
|
+
controller.abort();
|
|
678
|
+
}, timeoutMs)
|
|
679
|
+
: undefined;
|
|
680
|
+
try {
|
|
681
|
+
if (controller.signal.aborted) throw failure('ABORTED');
|
|
682
|
+
const req: TransportRequest = {
|
|
683
|
+
method,
|
|
684
|
+
url,
|
|
685
|
+
path,
|
|
686
|
+
endpoint: endpointId,
|
|
687
|
+
headers: { ...headers },
|
|
688
|
+
body: options.body,
|
|
689
|
+
contentType: options.contentType,
|
|
690
|
+
responseType: options.responseType,
|
|
691
|
+
signal: controller.signal,
|
|
692
|
+
timeoutMs,
|
|
693
|
+
skipAuth: !!options.skipAuth,
|
|
694
|
+
idempotencyKey: options.idempotencyKey,
|
|
695
|
+
attempt,
|
|
696
|
+
init: options.init,
|
|
697
|
+
adapterOptions: options.adapterOptions,
|
|
698
|
+
};
|
|
699
|
+
lastRequest = req;
|
|
700
|
+
if (config.onRequest) await config.onRequest(req);
|
|
701
|
+
log('debug', logged, '→ ' + label, {
|
|
702
|
+
endpoint: endpointId,
|
|
703
|
+
url: stripQuery(url),
|
|
704
|
+
attempt,
|
|
705
|
+
headers: redacted(req.headers),
|
|
706
|
+
...(config.logBodies ? { body: options.body } : {}),
|
|
707
|
+
});
|
|
708
|
+
// settles on abort even when the transport ignores the signal
|
|
709
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
710
|
+
const fail = () => reject(failure(timedOut ? 'TIMEOUT' : 'ABORTED'));
|
|
711
|
+
if (controller.signal.aborted) fail();
|
|
712
|
+
else controller.signal.addEventListener('abort', fail);
|
|
713
|
+
});
|
|
714
|
+
aborted.catch(() => undefined);
|
|
715
|
+
// a request redirected by middleware loses the credentials
|
|
716
|
+
const send: MiddlewareNext = (sent) => {
|
|
717
|
+
if (sent && credentials && sent.url !== url && !mayReceiveCredentials(String(sent.url))) {
|
|
718
|
+
const stripped = { ...sent.headers };
|
|
719
|
+
for (const key of Object.keys(credentialHeaders)) {
|
|
720
|
+
if (stripped[key] === credentialHeaders[key]) delete stripped[key];
|
|
721
|
+
}
|
|
722
|
+
sent = { ...sent, headers: stripped };
|
|
723
|
+
}
|
|
724
|
+
checkHeaderValues(sent.headers);
|
|
725
|
+
return sendNormalised(sent);
|
|
726
|
+
};
|
|
727
|
+
const run = middleware.length ? chain(middleware, send) : send;
|
|
728
|
+
// called in this tick; a synchronous throw becomes a rejection
|
|
729
|
+
let sending: Promise<TransportResponse>;
|
|
730
|
+
try {
|
|
731
|
+
sending = Promise.resolve(run(req));
|
|
732
|
+
} catch (error) {
|
|
733
|
+
sending = Promise.reject(error);
|
|
734
|
+
}
|
|
735
|
+
let response: TransportResponse;
|
|
736
|
+
try {
|
|
737
|
+
response = await Promise.race([sending, aborted]);
|
|
738
|
+
} catch (error) {
|
|
739
|
+
if (controller.signal.aborted) {
|
|
740
|
+
if (isApiError(error) && (error.kind === 'TIMEOUT' || error.kind === 'ABORTED')) throw error;
|
|
741
|
+
throw failure(timedOut ? 'TIMEOUT' : 'ABORTED', error);
|
|
742
|
+
}
|
|
743
|
+
if (isApiError(error) || error instanceof InvalidHeaderError) throw error;
|
|
744
|
+
throw failure('NETWORK', error);
|
|
745
|
+
}
|
|
746
|
+
if (response.status < 200 || response.status >= 300) {
|
|
747
|
+
throw new ApiError('HTTP', {
|
|
748
|
+
method,
|
|
749
|
+
url,
|
|
750
|
+
status: response.status,
|
|
751
|
+
data: response.data,
|
|
752
|
+
headers: response.headers,
|
|
753
|
+
endpoint: endpointId,
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
return response;
|
|
757
|
+
} finally {
|
|
758
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
759
|
+
external?.removeEventListener('abort', onAbort);
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
setPending(1);
|
|
764
|
+
if (options.onLoading) safely(() => options.onLoading!(true));
|
|
765
|
+
try {
|
|
766
|
+
const headers: Record<string, string> = { accept: 'application/json, text/plain, */*' };
|
|
767
|
+
credentials = mayReceiveCredentials(url);
|
|
768
|
+
if (credentials) {
|
|
769
|
+
assignHeaders(credentialHeaders, typeof config.headers === 'function' ? await config.headers() : config.headers);
|
|
770
|
+
Object.assign(headers, credentialHeaders);
|
|
771
|
+
}
|
|
772
|
+
assignHeaders(headers, options.headers);
|
|
773
|
+
for (const key of Object.keys(credentialHeaders)) {
|
|
774
|
+
if (headers[key] !== credentialHeaders[key]) delete credentialHeaders[key];
|
|
775
|
+
}
|
|
776
|
+
if (credentials && config.getToken && !options.skipAuth && headers.authorization === undefined) {
|
|
777
|
+
const token = await config.getToken();
|
|
778
|
+
if (token) headers.authorization = credentialHeaders.authorization = 'Bearer ' + token;
|
|
779
|
+
}
|
|
780
|
+
if (options.idempotencyKey && headers['idempotency-key'] === undefined) {
|
|
781
|
+
headers['idempotency-key'] = options.idempotencyKey;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
for (;;) {
|
|
785
|
+
attempt++;
|
|
786
|
+
try {
|
|
787
|
+
const response = await attemptOnce(headers);
|
|
788
|
+
const durationMs = finish(response.status, true, undefined, false);
|
|
789
|
+
const result: ApiResponse<T> = {
|
|
790
|
+
data: response.data as T,
|
|
791
|
+
status: response.status,
|
|
792
|
+
headers: response.headers,
|
|
793
|
+
url: response.url ?? url,
|
|
794
|
+
durationMs,
|
|
795
|
+
attempts: attempt,
|
|
796
|
+
fromFallback: false,
|
|
797
|
+
};
|
|
798
|
+
log('info', logged, '← ' + response.status + ' ' + label + ' (' + durationMs + ' ms)', {
|
|
799
|
+
endpoint: endpointId,
|
|
800
|
+
status: response.status,
|
|
801
|
+
durationMs,
|
|
802
|
+
attempts: attempt,
|
|
803
|
+
...(config.logBodies ? { data: response.data } : {}),
|
|
804
|
+
});
|
|
805
|
+
const sent = lastRequest;
|
|
806
|
+
if (config.onResponse && sent) safely(() => config.onResponse!(result, sent));
|
|
807
|
+
return result;
|
|
808
|
+
} catch (error) {
|
|
809
|
+
if (!isApiError(error) || !shouldRetry(error, attempt, retry, idempotent)) throw error;
|
|
810
|
+
const delay = retryDelay(error, attempt, retry.policy);
|
|
811
|
+
log('warn', logged, 'retry ' + attempt + '/' + retry.attempts + ' ' + label + ' in ' + Math.round(delay) + ' ms (' + (error.status || error.kind) + ')', {
|
|
812
|
+
endpoint: endpointId,
|
|
813
|
+
kind: error.kind,
|
|
814
|
+
status: error.status,
|
|
815
|
+
});
|
|
816
|
+
await sleep(delay, options.signal, () => failure('ABORTED'));
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
} catch (thrown) {
|
|
820
|
+
if (!isApiError(thrown)) {
|
|
821
|
+
finish(0, false, undefined, false);
|
|
822
|
+
throw thrown;
|
|
823
|
+
}
|
|
824
|
+
const error = thrown;
|
|
825
|
+
const fromResponse: ErrorMessages | undefined =
|
|
826
|
+
config.messageFromResponse && error.kind === 'HTTP'
|
|
827
|
+
? { default: config.messageFromResponse }
|
|
828
|
+
: undefined;
|
|
829
|
+
error.userMessage = resolveMessage(error, [options.messages, fromResponse, config.messages, defaultErrorMessages]);
|
|
830
|
+
log(error.kind === 'ABORTED' ? 'debug' : 'error', logged, '✖ ' + (error.status || error.kind) + ' ' + label, {
|
|
831
|
+
endpoint: endpointId,
|
|
832
|
+
kind: error.kind,
|
|
833
|
+
status: error.status,
|
|
834
|
+
attempts: attempt,
|
|
835
|
+
userMessage: error.userMessage,
|
|
836
|
+
...(config.logBodies ? { data: error.data } : {}),
|
|
837
|
+
});
|
|
838
|
+
if (config.onError) safely(() => config.onError!(error));
|
|
839
|
+
if (options.fallback && error.kind !== 'ABORTED') {
|
|
840
|
+
const data = await options.fallback(error);
|
|
841
|
+
log('warn', logged, 'fallback used for ' + label + ' after ' + (error.status || error.kind), { endpoint: endpointId });
|
|
842
|
+
const durationMs = finish(error.status, false, error.kind, true);
|
|
843
|
+
return { data, status: error.status, headers: error.headers, url, durationMs, attempts: attempt, fromFallback: true };
|
|
844
|
+
}
|
|
845
|
+
finish(error.status, false, error.kind, false);
|
|
846
|
+
throw error;
|
|
847
|
+
} finally {
|
|
848
|
+
setPending(-1);
|
|
849
|
+
if (options.onLoading) safely(() => options.onLoading!(false));
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
return {
|
|
854
|
+
request,
|
|
855
|
+
get pending() {
|
|
856
|
+
return pending;
|
|
857
|
+
},
|
|
858
|
+
subscribe(listener) {
|
|
859
|
+
listeners.add(listener);
|
|
860
|
+
return () => {
|
|
861
|
+
listeners.delete(listener);
|
|
862
|
+
};
|
|
863
|
+
},
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function sleep(ms: number, signal: AbortSignal | undefined, aborted: () => ApiError): Promise<void> {
|
|
868
|
+
ms = delayOr(ms, 0);
|
|
869
|
+
return new Promise<void>((resolve, reject) => {
|
|
870
|
+
if (signal?.aborted) return reject(aborted());
|
|
871
|
+
const onAbort = () => {
|
|
872
|
+
clearTimeout(timer);
|
|
873
|
+
reject(aborted());
|
|
874
|
+
};
|
|
875
|
+
const timer = setTimeout(() => {
|
|
876
|
+
signal?.removeEventListener('abort', onAbort);
|
|
877
|
+
resolve();
|
|
878
|
+
}, ms);
|
|
879
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** Thrown as is: not retried, not wrapped in an ApiError. */
|
|
884
|
+
class InvalidHeaderError extends TypeError {}
|
|
885
|
+
|
|
886
|
+
function checkHeaderValues(headers: Record<string, string>): void {
|
|
887
|
+
for (const key of Object.keys(headers)) {
|
|
888
|
+
if (/[\r\n]/.test(String(headers[key]))) throw new InvalidHeaderError('Header "' + key + '" contains a line break');
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
function assignHeaders(target: Record<string, string>, source: HeaderValues | undefined): void {
|
|
893
|
+
if (!source) return;
|
|
894
|
+
for (const key of Object.keys(source)) {
|
|
895
|
+
const value = source[key];
|
|
896
|
+
const name = key.toLowerCase();
|
|
897
|
+
if (value === undefined) delete target[name];
|
|
898
|
+
else target[name] = value;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
// ─── URL and body encoding ──────────────────────────────────────────────────
|
|
903
|
+
|
|
904
|
+
const PARAM = /\/:([A-Za-z_]\w*)/g;
|
|
905
|
+
const ABSOLUTE = /^[a-z][a-z\d+\-.]*:\/\//i;
|
|
906
|
+
|
|
907
|
+
function buildUrl(
|
|
908
|
+
baseURL: string,
|
|
909
|
+
path: string,
|
|
910
|
+
params: Record<string, string | number> | undefined,
|
|
911
|
+
query: Query | undefined,
|
|
912
|
+
arrayFormat: 'repeat' | 'comma' | 'brackets'
|
|
913
|
+
): string {
|
|
914
|
+
const filled = path.replace(PARAM, (_match, name: string) => {
|
|
915
|
+
const value = params ? params[name] : undefined;
|
|
916
|
+
if (value === undefined || value === null || value === '') {
|
|
917
|
+
throw new TypeError('Missing path param ":' + name + '" for "' + path + '"');
|
|
918
|
+
}
|
|
919
|
+
const text = String(value);
|
|
920
|
+
// ".." would walk up the server path
|
|
921
|
+
if (text === '.' || text === '..') throw new TypeError('Invalid path param ":' + name + '" for "' + path + '"');
|
|
922
|
+
return '/' + encodeURIComponent(text);
|
|
923
|
+
});
|
|
924
|
+
let url = filled;
|
|
925
|
+
if (baseURL && !ABSOLUTE.test(filled)) {
|
|
926
|
+
url = baseURL.replace(/\/+$/, '') + '/' + filled.replace(/^\/+/, '');
|
|
927
|
+
}
|
|
928
|
+
const qs = encodeQuery(query, arrayFormat);
|
|
929
|
+
return qs ? url + (url.indexOf('?') === -1 ? '?' : '&') + qs : url;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function stringify(value: QueryValue): string {
|
|
933
|
+
return value instanceof Date ? value.toISOString() : String(value);
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
export function encodeQuery(query: Query | undefined, arrayFormat: 'repeat' | 'comma' | 'brackets' = 'repeat'): string {
|
|
937
|
+
if (!query) return '';
|
|
938
|
+
const parts: string[] = [];
|
|
939
|
+
for (const key of Object.keys(query)) {
|
|
940
|
+
const value = query[key];
|
|
941
|
+
if (value === undefined || value === null) continue;
|
|
942
|
+
const k = encodeURIComponent(key);
|
|
943
|
+
if (Array.isArray(value)) {
|
|
944
|
+
const items = (value as readonly QueryValue[]).filter((v) => v !== undefined && v !== null);
|
|
945
|
+
if (!items.length) continue;
|
|
946
|
+
if (arrayFormat === 'comma') {
|
|
947
|
+
parts.push(k + '=' + items.map((v) => encodeURIComponent(stringify(v))).join(','));
|
|
948
|
+
} else {
|
|
949
|
+
const name = arrayFormat === 'brackets' ? k + '[]' : k;
|
|
950
|
+
for (const v of items) parts.push(name + '=' + encodeURIComponent(stringify(v)));
|
|
951
|
+
}
|
|
952
|
+
} else {
|
|
953
|
+
parts.push(k + '=' + encodeURIComponent(stringify(value as QueryValue)));
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
return parts.join('&');
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
function isNativeFile(value: unknown): value is NativeFile {
|
|
960
|
+
return typeof value === 'object' && value !== null && typeof (value as NativeFile).uri === 'string';
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
function isBinary(body: unknown): boolean {
|
|
964
|
+
return (
|
|
965
|
+
(typeof Blob !== 'undefined' && body instanceof Blob) ||
|
|
966
|
+
body instanceof ArrayBuffer ||
|
|
967
|
+
ArrayBuffer.isView(body) ||
|
|
968
|
+
(typeof body === 'object' && body !== null && typeof (body as { getReader?: unknown }).getReader === 'function')
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
/** The encoding a body is sent with when the call does not say. */
|
|
973
|
+
export function bodyEncoding(body: unknown, encoding?: BodyEncoding): BodyEncoding {
|
|
974
|
+
if (encoding) return encoding;
|
|
975
|
+
if (typeof FormData !== 'undefined' && body instanceof FormData) return 'multipart';
|
|
976
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return 'urlencoded';
|
|
977
|
+
if (typeof body === 'string') return 'text';
|
|
978
|
+
return isBinary(body) ? 'binary' : 'json';
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/** Encodes a body for fetch-like libraries and sets its content-type in headers. */
|
|
982
|
+
export function encodeBody(body: unknown, encoding: BodyEncoding | undefined, headers: Record<string, string>): unknown {
|
|
983
|
+
if (body === undefined || body === null) return undefined;
|
|
984
|
+
const kind = bodyEncoding(body, encoding);
|
|
985
|
+
switch (kind) {
|
|
986
|
+
case 'multipart': {
|
|
987
|
+
// the platform sets the boundary; a hand-written multipart header would break it
|
|
988
|
+
if (headers['content-type'] && headers['content-type'].indexOf('boundary=') === -1) delete headers['content-type'];
|
|
989
|
+
if (typeof FormData !== 'undefined' && body instanceof FormData) return body;
|
|
990
|
+
const form = new FormData();
|
|
991
|
+
const fields = body as Record<string, unknown>;
|
|
992
|
+
for (const key of Object.keys(fields)) {
|
|
993
|
+
const value = fields[key];
|
|
994
|
+
const values = Array.isArray(value) ? value : [value];
|
|
995
|
+
for (const v of values) {
|
|
996
|
+
if (v === undefined || v === null) continue;
|
|
997
|
+
if (typeof Blob !== 'undefined' && v instanceof Blob) form.append(key, v);
|
|
998
|
+
// React Native's FormData sends { uri, name, type } as a file part
|
|
999
|
+
else if (isNativeFile(v)) form.append(key, v as unknown as Blob);
|
|
1000
|
+
else form.append(key, typeof v === 'object' && !(v instanceof Date) ? JSON.stringify(v) : stringify(v as QueryValue));
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
return form;
|
|
1004
|
+
}
|
|
1005
|
+
case 'urlencoded':
|
|
1006
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return body;
|
|
1007
|
+
if (!headers['content-type']) headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
|
|
1008
|
+
return typeof body === 'string' ? body : encodeQuery(body as Query, 'repeat');
|
|
1009
|
+
case 'text':
|
|
1010
|
+
if (!headers['content-type']) headers['content-type'] = 'text/plain;charset=UTF-8';
|
|
1011
|
+
return typeof body === 'string' ? body : JSON.stringify(body);
|
|
1012
|
+
case 'binary':
|
|
1013
|
+
if (isNativeFile(body)) {
|
|
1014
|
+
throw new TypeError('A { uri } file body needs a transport that streams files (e.g. reactNativeFetchTransport)');
|
|
1015
|
+
}
|
|
1016
|
+
if (!headers['content-type'] && !(typeof Blob !== 'undefined' && body instanceof Blob && body.type)) {
|
|
1017
|
+
headers['content-type'] = 'application/octet-stream';
|
|
1018
|
+
}
|
|
1019
|
+
return body;
|
|
1020
|
+
default:
|
|
1021
|
+
if (!headers['content-type']) headers['content-type'] = 'application/json';
|
|
1022
|
+
return typeof body === 'string' ? body : JSON.stringify(body);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
// ─── Endpoints ──────────────────────────────────────────────────────────────
|
|
1027
|
+
|
|
1028
|
+
type Call<A, R> = {} extends A ? (args?: A) => Promise<R> : (args: A) => Promise<R>;
|
|
1029
|
+
|
|
1030
|
+
/** { status: 401; data: AuthError } | … for the documented error responses of an endpoint. */
|
|
1031
|
+
export type ErrorOf<E, D = never> =
|
|
1032
|
+
| { [S in keyof E]: { status: S; data: E[S] } }[keyof E]
|
|
1033
|
+
| ([D] extends [never] ? never : { status: number; data: D });
|
|
1034
|
+
|
|
1035
|
+
/** A generated endpoint: call it for the data, .raw() for the whole response. */
|
|
1036
|
+
export type Endpoint<A, R, E = {}, D = never> = Call<A, R> & {
|
|
1037
|
+
/** same call, resolving the full response (status, headers, timing, fromFallback) */
|
|
1038
|
+
raw: Call<A, ApiResponse<R>>;
|
|
1039
|
+
/** typed body of a documented error response; undefined for any other failure */
|
|
1040
|
+
errorOf(error: unknown): ErrorOf<E, D> | undefined;
|
|
1041
|
+
readonly id: string;
|
|
1042
|
+
readonly method: HttpMethod;
|
|
1043
|
+
readonly path: string;
|
|
1044
|
+
};
|
|
1045
|
+
|
|
1046
|
+
export interface EndpointSpec {
|
|
1047
|
+
/** 'group.name' */
|
|
1048
|
+
id: string;
|
|
1049
|
+
method: HttpMethod;
|
|
1050
|
+
path: string;
|
|
1051
|
+
/** applied before endpoint options and the caller's options */
|
|
1052
|
+
defaults?: CallOptions;
|
|
1053
|
+
/** documented error statuses */
|
|
1054
|
+
errors?: readonly number[];
|
|
1055
|
+
/** documented error classes: 4 for 4XX, 5 for 5XX */
|
|
1056
|
+
errorRanges?: readonly number[];
|
|
1057
|
+
/** a catch-all (default) error response is documented */
|
|
1058
|
+
defaultError?: boolean;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
function mergeRecords<V>(...records: Array<Record<string, V> | undefined>): Record<string, V> | undefined {
|
|
1062
|
+
let out: Record<string, V> | undefined;
|
|
1063
|
+
for (const record of records) if (record) out = { ...out, ...record };
|
|
1064
|
+
return out;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/** Bind one endpoint to a client. Used by the generated createApi. */
|
|
1068
|
+
export function endpoint<A, R, E = {}, D = never>(
|
|
1069
|
+
client: ApiRequester,
|
|
1070
|
+
spec: EndpointSpec,
|
|
1071
|
+
overrides?: EndpointOptions<R>
|
|
1072
|
+
): Endpoint<A, R, E, D> {
|
|
1073
|
+
const raw = (args?: A) => {
|
|
1074
|
+
const call = (args ?? {}) as RequestOptions<R>;
|
|
1075
|
+
const options: RequestOptions<R> = { ...(spec.defaults as RequestOptions<R>), ...overrides, ...call, endpoint: spec.id };
|
|
1076
|
+
const headers = mergeRecords(spec.defaults?.headers, overrides?.headers, call.headers);
|
|
1077
|
+
if (headers) options.headers = headers;
|
|
1078
|
+
const messages = mergeRecords<ErrorMessage | undefined>(
|
|
1079
|
+
spec.defaults?.messages as Record<string, ErrorMessage | undefined> | undefined,
|
|
1080
|
+
overrides?.messages as Record<string, ErrorMessage | undefined> | undefined,
|
|
1081
|
+
call.messages as Record<string, ErrorMessage | undefined> | undefined
|
|
1082
|
+
);
|
|
1083
|
+
if (messages) options.messages = messages as ErrorMessages;
|
|
1084
|
+
const middleware = ([] as Middleware[]).concat(
|
|
1085
|
+
spec.defaults?.middleware ?? [],
|
|
1086
|
+
overrides?.middleware ?? [],
|
|
1087
|
+
call.middleware ?? []
|
|
1088
|
+
);
|
|
1089
|
+
if (middleware.length) options.middleware = middleware;
|
|
1090
|
+
else delete options.middleware;
|
|
1091
|
+
return client.request<R>(spec.method, spec.path, options);
|
|
1092
|
+
};
|
|
1093
|
+
const call = (args?: A) => raw(args).then((response) => response.data);
|
|
1094
|
+
const errorOf = (error: unknown) => {
|
|
1095
|
+
if (!isApiError(error) || error.kind !== 'HTTP') return undefined;
|
|
1096
|
+
const status = error.status;
|
|
1097
|
+
const documented =
|
|
1098
|
+
(spec.errors !== undefined && spec.errors.indexOf(status) !== -1) ||
|
|
1099
|
+
(spec.errorRanges !== undefined && spec.errorRanges.indexOf(Math.floor(status / 100)) !== -1) ||
|
|
1100
|
+
(spec.defaultError === true && status >= 400);
|
|
1101
|
+
return documented ? { status, data: error.data } : undefined;
|
|
1102
|
+
};
|
|
1103
|
+
return Object.assign(call, {
|
|
1104
|
+
raw,
|
|
1105
|
+
errorOf,
|
|
1106
|
+
id: spec.id,
|
|
1107
|
+
method: spec.method,
|
|
1108
|
+
path: spec.path,
|
|
1109
|
+
}) as unknown as Endpoint<A, R, E, D>;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// ─── Request state for UI bindings (React, Vue, Angular, Svelte, Solid, …) ──
|
|
1113
|
+
|
|
1114
|
+
export type RequestStatus = 'idle' | 'loading' | 'success' | 'error';
|
|
1115
|
+
|
|
1116
|
+
export interface RequestState<T> {
|
|
1117
|
+
readonly status: RequestStatus;
|
|
1118
|
+
/** last successful data (kept while reloading and after an error) */
|
|
1119
|
+
readonly data: T | undefined;
|
|
1120
|
+
readonly error: ApiError | Error | undefined;
|
|
1121
|
+
readonly isIdle: boolean;
|
|
1122
|
+
readonly isLoading: boolean;
|
|
1123
|
+
readonly isSuccess: boolean;
|
|
1124
|
+
readonly isError: boolean;
|
|
1125
|
+
/** Date.now() of the last success */
|
|
1126
|
+
readonly updatedAt: number | undefined;
|
|
1127
|
+
/** data came from a fallback, not the server: show it as stale / offline */
|
|
1128
|
+
readonly fromFallback: boolean;
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/** Lets a controller's function say where its data came from (e.g. from .raw()). */
|
|
1132
|
+
export type FallbackReporter = (response: { fromFallback: boolean }) => void;
|
|
1133
|
+
|
|
1134
|
+
function snapshot<T>(
|
|
1135
|
+
status: RequestStatus,
|
|
1136
|
+
data: T | undefined,
|
|
1137
|
+
error: ApiError | Error | undefined,
|
|
1138
|
+
updatedAt: number | undefined,
|
|
1139
|
+
fromFallback = false
|
|
1140
|
+
): RequestState<T> {
|
|
1141
|
+
return {
|
|
1142
|
+
status,
|
|
1143
|
+
data,
|
|
1144
|
+
error,
|
|
1145
|
+
isIdle: status === 'idle',
|
|
1146
|
+
isLoading: status === 'loading',
|
|
1147
|
+
isSuccess: status === 'success',
|
|
1148
|
+
isError: status === 'error',
|
|
1149
|
+
updatedAt,
|
|
1150
|
+
fromFallback,
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
export interface QueryOptions<T> {
|
|
1155
|
+
/** default true; false keeps the query idle (and cancels a running one) */
|
|
1156
|
+
enabled?: boolean;
|
|
1157
|
+
/** default true: keep the last data while reloading */
|
|
1158
|
+
keepPreviousData?: boolean;
|
|
1159
|
+
onSuccess?: (data: T) => void;
|
|
1160
|
+
onError?: (error: ApiError | Error) => void;
|
|
1161
|
+
onSettled?: () => void;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
export interface MutationOptions<T, V> {
|
|
1165
|
+
onSuccess?: (data: T, vars: V) => void;
|
|
1166
|
+
onError?: (error: ApiError | Error, vars: V) => void;
|
|
1167
|
+
/** after success or error (e.g. refetch a list) */
|
|
1168
|
+
onSettled?: (vars: V) => void;
|
|
1169
|
+
/** true: while a call is running, run() returns it instead of sending again (double submit) */
|
|
1170
|
+
dedupe?: boolean;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
interface Store<T> {
|
|
1174
|
+
getState(): RequestState<T>;
|
|
1175
|
+
/** listener runs on every state change; returns unsubscribe */
|
|
1176
|
+
subscribe(listener: () => void): () => void;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
export interface QueryController<A, T> extends Store<T> {
|
|
1180
|
+
/** start when args (by value) or enabled changed; a no-op otherwise */
|
|
1181
|
+
update(args: A, enabled?: boolean): void;
|
|
1182
|
+
/** run again with the last args */
|
|
1183
|
+
refetch(): void;
|
|
1184
|
+
/** abort the call in flight; the next update() starts again */
|
|
1185
|
+
cancel(): void;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
export interface MutationController<V, T> extends Store<T> {
|
|
1189
|
+
/** rejects with the error (also passed to onError) */
|
|
1190
|
+
runAsync(vars: V): Promise<T>;
|
|
1191
|
+
/** never rejects: resolves the data, or undefined after an error */
|
|
1192
|
+
run(vars: V): Promise<T | undefined>;
|
|
1193
|
+
reset(): void;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function createStore<T>(initial: RequestState<T>) {
|
|
1197
|
+
let state = initial;
|
|
1198
|
+
const listeners = new Set<() => void>();
|
|
1199
|
+
return {
|
|
1200
|
+
get: () => state,
|
|
1201
|
+
set(next: RequestState<T>) {
|
|
1202
|
+
state = next;
|
|
1203
|
+
listeners.forEach((listener) => listener());
|
|
1204
|
+
},
|
|
1205
|
+
subscribe(listener: () => void) {
|
|
1206
|
+
listeners.add(listener);
|
|
1207
|
+
return () => {
|
|
1208
|
+
listeners.delete(listener);
|
|
1209
|
+
};
|
|
1210
|
+
},
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
function isAbort(error: unknown): boolean {
|
|
1215
|
+
return (
|
|
1216
|
+
(isApiError(error) && error.kind === 'ABORTED') ||
|
|
1217
|
+
(typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError')
|
|
1218
|
+
);
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/** Refetch key: path params, query, body and headers (not signal or callbacks). */
|
|
1222
|
+
export function argsKey(args: unknown): string {
|
|
1223
|
+
if (!args || typeof args !== 'object') return '';
|
|
1224
|
+
const a = args as { params?: unknown; query?: unknown; body?: unknown; headers?: unknown };
|
|
1225
|
+
try {
|
|
1226
|
+
return JSON.stringify([a.params, a.query, a.body, a.headers]) ?? '';
|
|
1227
|
+
} catch {
|
|
1228
|
+
// circular or BigInt
|
|
1229
|
+
return '?';
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/** A signal aborted when either input is. */
|
|
1234
|
+
export function linkSignals(signal: AbortSignal, other: AbortSignal | undefined): AbortSignal {
|
|
1235
|
+
if (!other) return signal;
|
|
1236
|
+
if (other.aborted) return other;
|
|
1237
|
+
const controller = new AbortController();
|
|
1238
|
+
const abort = () => controller.abort();
|
|
1239
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
1240
|
+
other.addEventListener('abort', abort, { once: true });
|
|
1241
|
+
return controller.signal;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/** Framework-neutral query: aborts stale calls and keeps the last data. */
|
|
1245
|
+
export function createQueryController<A, T>(
|
|
1246
|
+
fn: (args: A, signal: AbortSignal, report: FallbackReporter) => Promise<T>,
|
|
1247
|
+
getOptions: () => QueryOptions<T> = () => ({})
|
|
1248
|
+
): QueryController<A, T> {
|
|
1249
|
+
const store = createStore<T>(snapshot<T>(getOptions().enabled === false ? 'idle' : 'loading', undefined, undefined, undefined));
|
|
1250
|
+
let key: string | undefined;
|
|
1251
|
+
let args: A | undefined;
|
|
1252
|
+
let hasArgs = false;
|
|
1253
|
+
let enabled = true;
|
|
1254
|
+
let runId = 0;
|
|
1255
|
+
let controller: AbortController | undefined;
|
|
1256
|
+
|
|
1257
|
+
const stop = () => {
|
|
1258
|
+
runId++;
|
|
1259
|
+
controller?.abort();
|
|
1260
|
+
controller = undefined;
|
|
1261
|
+
};
|
|
1262
|
+
|
|
1263
|
+
const start = () => {
|
|
1264
|
+
stop();
|
|
1265
|
+
const id = runId;
|
|
1266
|
+
const own = new AbortController();
|
|
1267
|
+
controller = own;
|
|
1268
|
+
const options = getOptions();
|
|
1269
|
+
const s = store.get();
|
|
1270
|
+
const keep = options.keepPreviousData !== false;
|
|
1271
|
+
store.set(snapshot<T>('loading', keep ? s.data : undefined, undefined, s.updatedAt, keep && s.fromFallback));
|
|
1272
|
+
let fromFallback = false;
|
|
1273
|
+
const report: FallbackReporter = (response) => {
|
|
1274
|
+
fromFallback = !!response.fromFallback;
|
|
1275
|
+
};
|
|
1276
|
+
let promise: Promise<T>;
|
|
1277
|
+
try {
|
|
1278
|
+
promise = fn(args as A, own.signal, report);
|
|
1279
|
+
} catch (error) {
|
|
1280
|
+
promise = Promise.reject(error);
|
|
1281
|
+
}
|
|
1282
|
+
promise.then(
|
|
1283
|
+
(data) => {
|
|
1284
|
+
if (id !== runId) return;
|
|
1285
|
+
controller = undefined;
|
|
1286
|
+
store.set(snapshot<T>('success', data, undefined, Date.now(), fromFallback));
|
|
1287
|
+
safely(() => options.onSuccess?.(data));
|
|
1288
|
+
safely(() => options.onSettled?.());
|
|
1289
|
+
},
|
|
1290
|
+
(error: unknown) => {
|
|
1291
|
+
if (id !== runId) return;
|
|
1292
|
+
controller = undefined;
|
|
1293
|
+
const s = store.get();
|
|
1294
|
+
if (isAbort(error)) {
|
|
1295
|
+
store.set(snapshot<T>('idle', s.data, undefined, s.updatedAt, s.fromFallback));
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1299
|
+
store.set(snapshot<T>('error', s.data, err, s.updatedAt, s.fromFallback));
|
|
1300
|
+
safely(() => options.onError?.(err));
|
|
1301
|
+
safely(() => options.onSettled?.());
|
|
1302
|
+
}
|
|
1303
|
+
);
|
|
1304
|
+
};
|
|
1305
|
+
|
|
1306
|
+
return {
|
|
1307
|
+
getState: store.get,
|
|
1308
|
+
subscribe: store.subscribe,
|
|
1309
|
+
update(nextArgs, nextEnabled = true) {
|
|
1310
|
+
const nextKey = argsKey(nextArgs);
|
|
1311
|
+
args = nextArgs;
|
|
1312
|
+
hasArgs = true;
|
|
1313
|
+
if (!nextEnabled) {
|
|
1314
|
+
enabled = false;
|
|
1315
|
+
key = undefined;
|
|
1316
|
+
stop();
|
|
1317
|
+
const s = store.get();
|
|
1318
|
+
if (s.status === 'loading') store.set(snapshot<T>('idle', s.data, s.error, s.updatedAt, s.fromFallback));
|
|
1319
|
+
return;
|
|
1320
|
+
}
|
|
1321
|
+
if (enabled && nextKey === key) return;
|
|
1322
|
+
enabled = true;
|
|
1323
|
+
key = nextKey;
|
|
1324
|
+
start();
|
|
1325
|
+
},
|
|
1326
|
+
refetch() {
|
|
1327
|
+
if (hasArgs && enabled) start();
|
|
1328
|
+
},
|
|
1329
|
+
cancel() {
|
|
1330
|
+
stop();
|
|
1331
|
+
key = undefined;
|
|
1332
|
+
},
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/** Framework-neutral mutation: tracks the latest call; callbacks run for every call. */
|
|
1337
|
+
export function createMutationController<V, T>(
|
|
1338
|
+
fn: (vars: V, report: FallbackReporter) => Promise<T>,
|
|
1339
|
+
getOptions: () => MutationOptions<T, V> = () => ({})
|
|
1340
|
+
): MutationController<V, T> {
|
|
1341
|
+
const store = createStore<T>(snapshot<T>('idle', undefined, undefined, undefined));
|
|
1342
|
+
let runId = 0;
|
|
1343
|
+
let inFlight: Promise<T> | undefined;
|
|
1344
|
+
|
|
1345
|
+
const runAsync = (vars: V): Promise<T> => {
|
|
1346
|
+
const options = getOptions();
|
|
1347
|
+
if (options.dedupe && inFlight) return inFlight;
|
|
1348
|
+
const id = ++runId;
|
|
1349
|
+
const s = store.get();
|
|
1350
|
+
store.set(snapshot<T>('loading', s.data, undefined, s.updatedAt, s.fromFallback));
|
|
1351
|
+
let fromFallback = false;
|
|
1352
|
+
let promise: Promise<T>;
|
|
1353
|
+
try {
|
|
1354
|
+
promise = fn(vars, (response) => {
|
|
1355
|
+
fromFallback = !!response.fromFallback;
|
|
1356
|
+
});
|
|
1357
|
+
} catch (error) {
|
|
1358
|
+
promise = Promise.reject(error);
|
|
1359
|
+
}
|
|
1360
|
+
const tracked = promise.then(
|
|
1361
|
+
(data) => {
|
|
1362
|
+
if (id === runId) store.set(snapshot<T>('success', data, undefined, Date.now(), fromFallback));
|
|
1363
|
+
safely(() => options.onSuccess?.(data, vars));
|
|
1364
|
+
safely(() => options.onSettled?.(vars));
|
|
1365
|
+
return data;
|
|
1366
|
+
},
|
|
1367
|
+
(error: unknown) => {
|
|
1368
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1369
|
+
if (id === runId) {
|
|
1370
|
+
const current = store.get();
|
|
1371
|
+
store.set(snapshot<T>('error', current.data, err, current.updatedAt, current.fromFallback));
|
|
1372
|
+
}
|
|
1373
|
+
safely(() => options.onError?.(err, vars));
|
|
1374
|
+
safely(() => options.onSettled?.(vars));
|
|
1375
|
+
throw err;
|
|
1376
|
+
}
|
|
1377
|
+
);
|
|
1378
|
+
inFlight = tracked;
|
|
1379
|
+
const clear = () => {
|
|
1380
|
+
if (inFlight === tracked) inFlight = undefined;
|
|
1381
|
+
};
|
|
1382
|
+
tracked.then(clear, clear);
|
|
1383
|
+
return tracked;
|
|
1384
|
+
};
|
|
1385
|
+
|
|
1386
|
+
return {
|
|
1387
|
+
getState: store.get,
|
|
1388
|
+
subscribe: store.subscribe,
|
|
1389
|
+
runAsync,
|
|
1390
|
+
run: (vars) => runAsync(vars).catch(() => undefined),
|
|
1391
|
+
reset() {
|
|
1392
|
+
runId++;
|
|
1393
|
+
inFlight = undefined;
|
|
1394
|
+
store.set(snapshot<T>('idle', undefined, undefined, undefined));
|
|
1395
|
+
},
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
`;
|
|
1399
|
+
function runtimeSource() {
|
|
1400
|
+
return exports.RUNTIME + '\n' + transports_js_1.TRANSPORTS;
|
|
1401
|
+
}
|