typizer 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/CHANGELOG.md +60 -0
- package/README.md +273 -134
- package/dist/client.d.ts +323 -0
- package/dist/client.js +629 -0
- package/dist/core.d.ts +109 -0
- package/dist/core.js +339 -0
- package/dist/errors.d.ts +146 -0
- package/dist/errors.js +281 -0
- package/dist/files.d.ts +42 -0
- package/dist/files.js +159 -0
- package/dist/gen/index.d.ts +2 -2
- package/dist/gen/index.js +1 -1
- package/dist/gen/sdk.gen.d.ts +329 -5
- package/dist/gen/sdk.gen.js +588 -4
- package/dist/gen/types.gen.d.ts +2490 -245
- package/dist/index.d.ts +26 -3
- package/dist/index.js +33 -4
- package/dist/pagination.d.ts +30 -0
- package/dist/pagination.js +49 -0
- package/dist/run.d.ts +48 -0
- package/dist/run.js +45 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/webhooks.d.ts +40 -0
- package/dist/webhooks.js +208 -0
- package/package.json +9 -7
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** Settings of one call; every method takes them as its last argument. */
|
|
2
|
+
export interface RequestOptions {
|
|
3
|
+
/** Timeout of one HTTP attempt, in milliseconds (default: the client's, 75 000). */
|
|
4
|
+
timeout?: number;
|
|
5
|
+
/** Automatic retries of this call (default: the client's, 2). */
|
|
6
|
+
maxRetries?: number;
|
|
7
|
+
/** `Idempotency-Key` of a `POST` (default: a new UUID v4 per call, the same for its retries). */
|
|
8
|
+
idempotencyKey?: string;
|
|
9
|
+
/** More request headers (`Authorization` cannot be overridden). */
|
|
10
|
+
extraHeaders?: Record<string, string>;
|
|
11
|
+
/** Cancels the attempt, the pause before a retry and the wait for a run. */
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}
|
|
14
|
+
/** A logger compatible with `console`. */
|
|
15
|
+
export interface Logger {
|
|
16
|
+
debug(message: string): void;
|
|
17
|
+
info(message: string): void;
|
|
18
|
+
warn(message: string): void;
|
|
19
|
+
}
|
|
20
|
+
export type LogLevel = 'debug' | 'info' | 'warn' | 'off';
|
|
21
|
+
/** Name and version of your application, appended to `User-Agent`. */
|
|
22
|
+
export interface AppInfo {
|
|
23
|
+
name: string;
|
|
24
|
+
version: string;
|
|
25
|
+
url?: string;
|
|
26
|
+
}
|
|
27
|
+
/** The successful result of a call together with its HTTP response (SPEC §7.5). */
|
|
28
|
+
export interface WithResponse<T> {
|
|
29
|
+
data: T;
|
|
30
|
+
/** The HTTP response (status, headers). Its body has already been read. */
|
|
31
|
+
response: Response;
|
|
32
|
+
/** `X-Request-Id`: quote it to support. */
|
|
33
|
+
requestId: string | undefined;
|
|
34
|
+
/** True when the API replayed the stored response of an earlier request with the same `Idempotency-Key`. */
|
|
35
|
+
idempotentReplayed: boolean;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* What every client method returns: a promise of the result, plus `.withResponse()` for the
|
|
39
|
+
* HTTP status and headers (`X-Request-Id`, `RateLimit-*`, `Idempotent-Replayed`, `Location`).
|
|
40
|
+
* The request starts at once, like any promise.
|
|
41
|
+
*/
|
|
42
|
+
export declare class APIPromise<T> implements PromiseLike<T> {
|
|
43
|
+
#private;
|
|
44
|
+
constructor(inner: Promise<WithResponse<T>>);
|
|
45
|
+
/** The result together with the HTTP response. */
|
|
46
|
+
withResponse(): Promise<WithResponse<T>>;
|
|
47
|
+
then<R1 = T, R2 = never>(onfulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: any) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
|
|
48
|
+
catch<R = never>(onrejected?: ((reason: any) => R | PromiseLike<R>) | null): Promise<T | R>;
|
|
49
|
+
finally(onfinally?: (() => void) | null): Promise<T>;
|
|
50
|
+
get [Symbol.toStringTag](): string;
|
|
51
|
+
}
|
|
52
|
+
export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
53
|
+
export type Query = Record<string, string | number | boolean | undefined | null>;
|
|
54
|
+
/** One logical call. */
|
|
55
|
+
export interface Req {
|
|
56
|
+
method: Method;
|
|
57
|
+
/** The path with its parameters already escaped (`/v1/runs/run_1`). */
|
|
58
|
+
path: string;
|
|
59
|
+
query?: Query;
|
|
60
|
+
json?: unknown;
|
|
61
|
+
form?: FormData;
|
|
62
|
+
/** A non-JSON response: the `Response` is returned unread. */
|
|
63
|
+
download?: boolean;
|
|
64
|
+
/** The lowest attempt timeout (run creation with `wait`: wait + 15 s). */
|
|
65
|
+
minTimeout?: number;
|
|
66
|
+
/** Epoch ms: no pause before a retry may end after it (the `extract` deadline). */
|
|
67
|
+
deadline?: number;
|
|
68
|
+
}
|
|
69
|
+
export interface CoreConfig {
|
|
70
|
+
apiKey: string;
|
|
71
|
+
baseUrl: string;
|
|
72
|
+
timeout: number;
|
|
73
|
+
maxRetries: number;
|
|
74
|
+
maxRetryDelay: number;
|
|
75
|
+
fetch: typeof fetch | undefined;
|
|
76
|
+
proxy: string | undefined;
|
|
77
|
+
defaultHeaders: Record<string, string>;
|
|
78
|
+
userAgent: string;
|
|
79
|
+
logger: Logger;
|
|
80
|
+
logLevel: LogLevel;
|
|
81
|
+
}
|
|
82
|
+
/** State shared by a client and its `withOptions()` copies. */
|
|
83
|
+
export interface Shared {
|
|
84
|
+
maintenance: Set<string>;
|
|
85
|
+
dispatcher?: Promise<unknown>;
|
|
86
|
+
}
|
|
87
|
+
export declare function env(name: string): string | undefined;
|
|
88
|
+
/** `tz_live_…a1b2`: the key's prefix and its last 4 characters (SPEC §10). */
|
|
89
|
+
export declare function maskKey(key: string): string;
|
|
90
|
+
/** `typizer-ts/0.2.0 (node/24.3.0; darwin/arm64) acme-erp/2.1.0` (SPEC §2.3). */
|
|
91
|
+
export declare function userAgent(appInfo?: AppInfo): string;
|
|
92
|
+
export declare function newIdempotencyKey(): string;
|
|
93
|
+
/** `min(8 s, 0.5 s × 2^n) × random(0.75, 1.0)`, in ms (SPEC §7.2). */
|
|
94
|
+
export declare function backoff(n: number): number;
|
|
95
|
+
export declare function abortReason(signal: AbortSignal): unknown;
|
|
96
|
+
/** Waits `ms`, or rejects with the signal's reason as soon as it aborts. */
|
|
97
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
98
|
+
export declare function checkIdempotencyKey(key: string): void;
|
|
99
|
+
export declare function buildUrl(baseUrl: string, path: string, query?: Query): string;
|
|
100
|
+
export declare class Transport {
|
|
101
|
+
#private;
|
|
102
|
+
constructor(cfg: CoreConfig, shared: Shared);
|
|
103
|
+
/** State shared with `withOptions()` copies. */
|
|
104
|
+
get shared(): Shared;
|
|
105
|
+
log(level: Exclude<LogLevel, 'off'>, message: string): void;
|
|
106
|
+
request<T>(req: Req, opts?: RequestOptions): Promise<WithResponse<T>>;
|
|
107
|
+
}
|
|
108
|
+
/** Combines signals (AbortSignal.any where available). */
|
|
109
|
+
export declare function anySignal(signals: Array<AbortSignal | undefined | null>): AbortSignal | undefined;
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP core of the `Typizer` client: one logical call → attempts with retries (SPEC §7),
|
|
3
|
+
* timeouts, `Idempotency-Key`, `User-Agent`, logging (§10) and the raw response (§7.5).
|
|
4
|
+
*/
|
|
5
|
+
import { APIConnectionError, APITimeoutError, ConfigurationError, errorFromResponse, TypizerError, } from './errors.js';
|
|
6
|
+
import { VERSION } from './version.js';
|
|
7
|
+
/**
|
|
8
|
+
* What every client method returns: a promise of the result, plus `.withResponse()` for the
|
|
9
|
+
* HTTP status and headers (`X-Request-Id`, `RateLimit-*`, `Idempotent-Replayed`, `Location`).
|
|
10
|
+
* The request starts at once, like any promise.
|
|
11
|
+
*/
|
|
12
|
+
export class APIPromise {
|
|
13
|
+
#inner;
|
|
14
|
+
constructor(inner) {
|
|
15
|
+
this.#inner = inner;
|
|
16
|
+
// A call nobody awaits must not crash the process with an unhandled rejection.
|
|
17
|
+
inner.catch(() => { });
|
|
18
|
+
}
|
|
19
|
+
/** The result together with the HTTP response. */
|
|
20
|
+
withResponse() {
|
|
21
|
+
return this.#inner;
|
|
22
|
+
}
|
|
23
|
+
// biome-ignore lint/suspicious/noThenProperty: this is a thenable on purpose.
|
|
24
|
+
then(onfulfilled,
|
|
25
|
+
// biome-ignore lint/suspicious/noExplicitAny: the same signature as Promise#then.
|
|
26
|
+
onrejected) {
|
|
27
|
+
return this.#inner.then((r) => r.data).then(onfulfilled, onrejected);
|
|
28
|
+
}
|
|
29
|
+
// biome-ignore lint/suspicious/noExplicitAny: the same signature as Promise#catch.
|
|
30
|
+
catch(onrejected) {
|
|
31
|
+
return this.then(undefined, onrejected);
|
|
32
|
+
}
|
|
33
|
+
finally(onfinally) {
|
|
34
|
+
return this.#inner.then((r) => r.data).finally(onfinally);
|
|
35
|
+
}
|
|
36
|
+
get [Symbol.toStringTag]() {
|
|
37
|
+
return 'APIPromise';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const LEVELS = { debug: 10, info: 20, warn: 30, off: 100 };
|
|
41
|
+
export function env(name) {
|
|
42
|
+
const g = globalThis;
|
|
43
|
+
try {
|
|
44
|
+
return g.process?.env?.[name] || undefined;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** `tz_live_…a1b2`: the key's prefix and its last 4 characters (SPEC §10). */
|
|
51
|
+
export function maskKey(key) {
|
|
52
|
+
const prefix = /^tz_[a-z]+_/.exec(key)?.[0] ?? '';
|
|
53
|
+
return key.length > prefix.length + 8 ? `${prefix}…${key.slice(-4)}` : `${prefix}…`;
|
|
54
|
+
}
|
|
55
|
+
function runtime() {
|
|
56
|
+
const g = globalThis;
|
|
57
|
+
try {
|
|
58
|
+
if (g.Deno?.version?.deno) {
|
|
59
|
+
return `deno/${g.Deno.version.deno}; ${g.Deno.build?.os}/${g.Deno.build?.arch}`;
|
|
60
|
+
}
|
|
61
|
+
const p = g.process;
|
|
62
|
+
if (p?.versions?.bun)
|
|
63
|
+
return `bun/${p.versions.bun}; ${p.platform}/${p.arch}`;
|
|
64
|
+
if (p?.versions?.node)
|
|
65
|
+
return `node/${p.versions.node}; ${p.platform}/${p.arch}`;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
/** `typizer-ts/0.2.0 (node/24.3.0; darwin/arm64) acme-erp/2.1.0` (SPEC §2.3). */
|
|
73
|
+
export function userAgent(appInfo) {
|
|
74
|
+
const rt = runtime();
|
|
75
|
+
let ua = `typizer-ts/${VERSION}${rt ? ` (${rt})` : ''}`;
|
|
76
|
+
if (appInfo)
|
|
77
|
+
ua += ` ${appInfo.name}/${appInfo.version}${appInfo.url ? ` (${appInfo.url})` : ''}`;
|
|
78
|
+
return ua;
|
|
79
|
+
}
|
|
80
|
+
export function newIdempotencyKey() {
|
|
81
|
+
return globalThis.crypto.randomUUID().toLowerCase();
|
|
82
|
+
}
|
|
83
|
+
/** `min(8 s, 0.5 s × 2^n) × random(0.75, 1.0)`, in ms (SPEC §7.2). */
|
|
84
|
+
export function backoff(n) {
|
|
85
|
+
return Math.min(8000, 500 * 2 ** Math.min(n, 4)) * (0.75 + 0.25 * Math.random());
|
|
86
|
+
}
|
|
87
|
+
export function abortReason(signal) {
|
|
88
|
+
return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
|
|
89
|
+
}
|
|
90
|
+
/** Waits `ms`, or rejects with the signal's reason as soon as it aborts. */
|
|
91
|
+
export function sleep(ms, signal) {
|
|
92
|
+
if (signal?.aborted)
|
|
93
|
+
return Promise.reject(abortReason(signal));
|
|
94
|
+
if (ms <= 0)
|
|
95
|
+
return Promise.resolve();
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
const onAbort = () => {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
reject(abortReason(signal));
|
|
100
|
+
};
|
|
101
|
+
const timer = setTimeout(() => {
|
|
102
|
+
signal?.removeEventListener('abort', onAbort);
|
|
103
|
+
resolve();
|
|
104
|
+
}, ms);
|
|
105
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
function seconds(ms) {
|
|
109
|
+
return `${(ms / 1000).toFixed(2)}s`;
|
|
110
|
+
}
|
|
111
|
+
/** Connection errors that prove the request never left (safe to retry a PATCH). */
|
|
112
|
+
const NOT_SENT = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT']);
|
|
113
|
+
function causeOf(err) {
|
|
114
|
+
let e = err;
|
|
115
|
+
for (let i = 0; i < 4 && e && typeof e === 'object'; i++) {
|
|
116
|
+
const c = e.cause;
|
|
117
|
+
if (!c)
|
|
118
|
+
break;
|
|
119
|
+
e = c;
|
|
120
|
+
}
|
|
121
|
+
const obj = (e ?? {});
|
|
122
|
+
return { code: obj.code, message: obj.message ?? String(e) };
|
|
123
|
+
}
|
|
124
|
+
export function checkIdempotencyKey(key) {
|
|
125
|
+
if (!/^[\x20-\x7e]{1,255}$/.test(key)) {
|
|
126
|
+
throw new TypeError('typizer: idempotencyKey must be 1–255 printable ASCII characters');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export function buildUrl(baseUrl, path, query) {
|
|
130
|
+
let url = baseUrl + path;
|
|
131
|
+
if (query) {
|
|
132
|
+
const qs = new URLSearchParams();
|
|
133
|
+
for (const [k, v] of Object.entries(query)) {
|
|
134
|
+
if (v !== undefined && v !== null)
|
|
135
|
+
qs.append(k, String(v));
|
|
136
|
+
}
|
|
137
|
+
const s = qs.toString();
|
|
138
|
+
if (s)
|
|
139
|
+
url += `?${s}`;
|
|
140
|
+
}
|
|
141
|
+
return url;
|
|
142
|
+
}
|
|
143
|
+
export class Transport {
|
|
144
|
+
#cfg;
|
|
145
|
+
#shared;
|
|
146
|
+
constructor(cfg, shared) {
|
|
147
|
+
this.#cfg = cfg;
|
|
148
|
+
this.#shared = shared;
|
|
149
|
+
}
|
|
150
|
+
/** State shared with `withOptions()` copies. */
|
|
151
|
+
get shared() {
|
|
152
|
+
return this.#shared;
|
|
153
|
+
}
|
|
154
|
+
log(level, message) {
|
|
155
|
+
if (LEVELS[level] < LEVELS[this.#cfg.logLevel])
|
|
156
|
+
return;
|
|
157
|
+
try {
|
|
158
|
+
this.#cfg.logger[level](message);
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
// a broken logger must not break the call
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
#noteMaintenance(header) {
|
|
165
|
+
if (!header)
|
|
166
|
+
return;
|
|
167
|
+
const id = header.split(';')[0]?.trim() ?? header;
|
|
168
|
+
if (this.#shared.maintenance.has(id))
|
|
169
|
+
return;
|
|
170
|
+
this.#shared.maintenance.add(id);
|
|
171
|
+
this.log('warn', `typizer: maintenance announced: ${header}`);
|
|
172
|
+
}
|
|
173
|
+
async #dispatcher() {
|
|
174
|
+
const proxy = this.#cfg.proxy;
|
|
175
|
+
if (!proxy)
|
|
176
|
+
return undefined;
|
|
177
|
+
this.#shared.dispatcher ??= (async () => {
|
|
178
|
+
const name = 'undici';
|
|
179
|
+
try {
|
|
180
|
+
const undici = (await import(/* @vite-ignore */ name));
|
|
181
|
+
return new undici.ProxyAgent(proxy);
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
throw new ConfigurationError('typizer: the proxy option needs the undici package (npm i undici), or pass your own fetch', { cause: err });
|
|
185
|
+
}
|
|
186
|
+
})();
|
|
187
|
+
return this.#shared.dispatcher;
|
|
188
|
+
}
|
|
189
|
+
async request(req, opts = {}) {
|
|
190
|
+
const cfg = this.#cfg;
|
|
191
|
+
const { method, path } = req;
|
|
192
|
+
const url = buildUrl(cfg.baseUrl, path, req.query);
|
|
193
|
+
let idemKey;
|
|
194
|
+
if (method === 'POST') {
|
|
195
|
+
if (opts.idempotencyKey !== undefined)
|
|
196
|
+
checkIdempotencyKey(opts.idempotencyKey);
|
|
197
|
+
idemKey = opts.idempotencyKey ?? newIdempotencyKey();
|
|
198
|
+
}
|
|
199
|
+
const maxRetries = Math.max(0, opts.maxRetries ?? cfg.maxRetries);
|
|
200
|
+
let timeout = opts.timeout ?? cfg.timeout;
|
|
201
|
+
if (req.minTimeout && req.minTimeout > timeout)
|
|
202
|
+
timeout = req.minTimeout;
|
|
203
|
+
const attempts = maxRetries + 1;
|
|
204
|
+
const body = req.json !== undefined ? JSON.stringify(req.json) : req.form;
|
|
205
|
+
const fetchImpl = cfg.fetch ?? globalThis.fetch;
|
|
206
|
+
const dispatcher = await this.#dispatcher();
|
|
207
|
+
const signal = opts.signal;
|
|
208
|
+
for (let attempt = 1;; attempt++) {
|
|
209
|
+
if (signal?.aborted)
|
|
210
|
+
throw abortReason(signal);
|
|
211
|
+
const headers = new Headers();
|
|
212
|
+
for (const [k, v] of Object.entries(cfg.defaultHeaders))
|
|
213
|
+
headers.set(k, v);
|
|
214
|
+
for (const [k, v] of Object.entries(opts.extraHeaders ?? {}))
|
|
215
|
+
headers.set(k, v);
|
|
216
|
+
headers.set('Authorization', `Bearer ${cfg.apiKey}`);
|
|
217
|
+
if (!headers.has('User-Agent'))
|
|
218
|
+
headers.set('User-Agent', cfg.userAgent);
|
|
219
|
+
headers.set('Accept', req.download ? '*/*' : 'application/json');
|
|
220
|
+
if (req.json !== undefined)
|
|
221
|
+
headers.set('Content-Type', 'application/json');
|
|
222
|
+
if (idemKey)
|
|
223
|
+
headers.set('Idempotency-Key', idemKey);
|
|
224
|
+
const ctrl = new AbortController();
|
|
225
|
+
let timedOut = false;
|
|
226
|
+
const timer = timeout > 0 && Number.isFinite(timeout)
|
|
227
|
+
? setTimeout(() => {
|
|
228
|
+
timedOut = true;
|
|
229
|
+
ctrl.abort(new DOMException('The attempt timed out', 'TimeoutError'));
|
|
230
|
+
}, timeout)
|
|
231
|
+
: undefined;
|
|
232
|
+
const onAbort = () => ctrl.abort(abortReason(signal));
|
|
233
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
234
|
+
const cleanup = () => {
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
signal?.removeEventListener('abort', onAbort);
|
|
237
|
+
};
|
|
238
|
+
const started = Date.now();
|
|
239
|
+
let res;
|
|
240
|
+
let text = '';
|
|
241
|
+
try {
|
|
242
|
+
const init = {
|
|
243
|
+
method,
|
|
244
|
+
headers,
|
|
245
|
+
body: body ?? null,
|
|
246
|
+
signal: ctrl.signal,
|
|
247
|
+
};
|
|
248
|
+
if (dispatcher)
|
|
249
|
+
init.dispatcher = dispatcher;
|
|
250
|
+
res = await fetchImpl(url, init);
|
|
251
|
+
if (!(res.ok && req.download))
|
|
252
|
+
text = await res.text();
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
cleanup();
|
|
256
|
+
if (signal?.aborted)
|
|
257
|
+
throw abortReason(signal);
|
|
258
|
+
if (err instanceof TypizerError)
|
|
259
|
+
throw err;
|
|
260
|
+
const cause = causeOf(err);
|
|
261
|
+
const connErr = timedOut
|
|
262
|
+
? new APITimeoutError(`typizer: ${method} ${path}: no response in ${seconds(timeout)}`, method, path, { cause: err })
|
|
263
|
+
: new APIConnectionError(`typizer: ${method} ${path}: connection error: ${cause.message}`, method, path, { cause: err });
|
|
264
|
+
const reason = timedOut ? 'timeout' : 'connection error';
|
|
265
|
+
this.log('debug', `typizer: ${method} ${path} -> ${reason} in ${seconds(Date.now() - started)} (attempt ${attempt}/${attempts})`);
|
|
266
|
+
const safe = method !== 'PATCH' || (!timedOut && NOT_SENT.has(cause.code ?? ''));
|
|
267
|
+
if (attempt < attempts && safe) {
|
|
268
|
+
if (await this.#pause(req, backoff(attempt - 1), attempt + 1, attempts, reason, '', signal)) {
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
throw connErr;
|
|
273
|
+
}
|
|
274
|
+
const requestId = res.headers.get('x-request-id') ?? undefined;
|
|
275
|
+
this.log('debug', `typizer: ${method} ${path} -> ${res.status} in ${seconds(Date.now() - started)} (request_id=${requestId ?? ''}, attempt ${attempt}/${attempts})`);
|
|
276
|
+
this.#noteMaintenance(res.headers.get('typizer-maintenance'));
|
|
277
|
+
const idempotentReplayed = res.headers.get('idempotent-replayed')?.toLowerCase() === 'true';
|
|
278
|
+
if (res.ok) {
|
|
279
|
+
if (req.download) {
|
|
280
|
+
// The body is streamed by the caller: the attempt timeout ends with the headers, the
|
|
281
|
+
// caller's signal still cancels the download.
|
|
282
|
+
clearTimeout(timer);
|
|
283
|
+
return { data: res, response: res, requestId, idempotentReplayed };
|
|
284
|
+
}
|
|
285
|
+
cleanup();
|
|
286
|
+
let data;
|
|
287
|
+
if (text.trim()) {
|
|
288
|
+
try {
|
|
289
|
+
data = JSON.parse(text);
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
throw new TypizerError(`typizer: ${method} ${path}: the response is not JSON (HTTP ${res.status}, request_id=${requestId ?? ''})`, { cause: err });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return { data: data, response: res, requestId, idempotentReplayed };
|
|
296
|
+
}
|
|
297
|
+
cleanup();
|
|
298
|
+
const apiErr = errorFromResponse(res.status, res.headers, text);
|
|
299
|
+
if (attempt >= attempts || !apiErr.retryable)
|
|
300
|
+
throw apiErr;
|
|
301
|
+
let delay = backoff(attempt - 1);
|
|
302
|
+
if (apiErr.retryAfter !== undefined) {
|
|
303
|
+
if (apiErr.retryAfter * 1000 > cfg.maxRetryDelay)
|
|
304
|
+
throw apiErr;
|
|
305
|
+
delay = apiErr.retryAfter * 1000;
|
|
306
|
+
}
|
|
307
|
+
const reason = `${apiErr.status} ${apiErr.code}`;
|
|
308
|
+
if (!(await this.#pause(req, delay, attempt + 1, attempts, reason, apiErr.requestId, signal))) {
|
|
309
|
+
throw apiErr;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
/** Waits before the next attempt; false when the pause would cross the call's deadline. */
|
|
314
|
+
async #pause(req, delay, next, attempts, reason, requestId, signal) {
|
|
315
|
+
if (req.deadline !== undefined && Date.now() + delay > req.deadline)
|
|
316
|
+
return false;
|
|
317
|
+
this.log('info', `typizer: retrying ${req.method} ${req.path} in ${(delay / 1000).toFixed(1)}s after ${reason} (attempt ${next}/${attempts}${requestId ? `, request_id=${requestId}` : ''})`);
|
|
318
|
+
await sleep(delay, signal);
|
|
319
|
+
return true;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/** Combines signals (AbortSignal.any where available). */
|
|
323
|
+
export function anySignal(signals) {
|
|
324
|
+
const list = signals.filter((s) => Boolean(s));
|
|
325
|
+
if (list.length <= 1)
|
|
326
|
+
return list[0];
|
|
327
|
+
const any = AbortSignal.any;
|
|
328
|
+
if (any)
|
|
329
|
+
return any.call(AbortSignal, list);
|
|
330
|
+
const ctrl = new AbortController();
|
|
331
|
+
for (const s of list) {
|
|
332
|
+
if (s.aborted) {
|
|
333
|
+
ctrl.abort(s.reason);
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
s.addEventListener('abort', () => ctrl.abort(s.reason), { once: true });
|
|
337
|
+
}
|
|
338
|
+
return ctrl.signal;
|
|
339
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The errors the `Typizer` client throws (SPEC §6). Everything is a `TypizerError`; an HTTP error
|
|
3
|
+
* response is an `APIError` subclass chosen by the problem's `code`, else by the HTTP status.
|
|
4
|
+
* Argument mistakes (no schema, two documents at once) are plain `TypeError`s: they are bugs in
|
|
5
|
+
* the calling code, not failures of the service.
|
|
6
|
+
*/
|
|
7
|
+
import type { Run } from './gen/types.gen.js';
|
|
8
|
+
/** Everything the `Typizer` client throws. */
|
|
9
|
+
export declare class TypizerError extends Error {
|
|
10
|
+
constructor(message: string, options?: {
|
|
11
|
+
cause?: unknown;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/** The client is misconfigured (no API key, a proxy without `undici`, …). */
|
|
15
|
+
export declare class ConfigurationError extends TypizerError {
|
|
16
|
+
}
|
|
17
|
+
/** No response: DNS, TCP, TLS or a dropped connection. Retried automatically. */
|
|
18
|
+
export declare class APIConnectionError extends TypizerError {
|
|
19
|
+
readonly retryable = true;
|
|
20
|
+
readonly method: string;
|
|
21
|
+
readonly path: string;
|
|
22
|
+
constructor(message: string, method: string, path: string, options?: {
|
|
23
|
+
cause?: unknown;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** One HTTP attempt took longer than `timeout`. Retried automatically. */
|
|
27
|
+
export declare class APITimeoutError extends APIConnectionError {
|
|
28
|
+
}
|
|
29
|
+
/** `RateLimit-Limit/Remaining/Reset` of a response, when they came. */
|
|
30
|
+
export interface RateLimitInfo {
|
|
31
|
+
limit?: number;
|
|
32
|
+
remaining?: number;
|
|
33
|
+
reset?: number;
|
|
34
|
+
}
|
|
35
|
+
/** An HTTP error response (4xx/5xx), with or without a problem+json body. */
|
|
36
|
+
export declare class APIError extends TypizerError {
|
|
37
|
+
/** HTTP status. */
|
|
38
|
+
readonly status: number;
|
|
39
|
+
/** `Problem.code` (`rate_limited`, `invalid_schema`, …), or derived from the status. */
|
|
40
|
+
readonly code: string;
|
|
41
|
+
readonly title: string | undefined;
|
|
42
|
+
readonly detail: string | undefined;
|
|
43
|
+
readonly type: string | undefined;
|
|
44
|
+
readonly docUrl: string | undefined;
|
|
45
|
+
/** The request field at fault, if any. */
|
|
46
|
+
readonly param: string | undefined;
|
|
47
|
+
/** `Problem.request_id`, else the `X-Request-Id` header: quote it to support. */
|
|
48
|
+
readonly requestId: string | undefined;
|
|
49
|
+
/** Whether repeating the same request can succeed (SPEC §7.1). */
|
|
50
|
+
readonly retryable: boolean;
|
|
51
|
+
/** `Retry-After` in seconds (429/503), if the response had it. */
|
|
52
|
+
readonly retryAfter: number | undefined;
|
|
53
|
+
readonly rateLimit: RateLimitInfo | undefined;
|
|
54
|
+
/** All response headers (lower-case names). */
|
|
55
|
+
readonly headers: Record<string, string>;
|
|
56
|
+
/** The parsed problem object, or the raw text of a non-JSON body. */
|
|
57
|
+
readonly body: unknown;
|
|
58
|
+
/** Other problem fields (`batch_id`, `created`, `expected`, `findings`, …). */
|
|
59
|
+
readonly extra: Record<string, unknown>;
|
|
60
|
+
constructor(init: {
|
|
61
|
+
status: number;
|
|
62
|
+
code: string;
|
|
63
|
+
title?: string;
|
|
64
|
+
detail?: string;
|
|
65
|
+
type?: string;
|
|
66
|
+
docUrl?: string;
|
|
67
|
+
param?: string;
|
|
68
|
+
requestId?: string;
|
|
69
|
+
retryAfter?: number;
|
|
70
|
+
rateLimit?: RateLimitInfo;
|
|
71
|
+
headers?: Record<string, string>;
|
|
72
|
+
body?: unknown;
|
|
73
|
+
extra?: Record<string, unknown>;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/** 400: `invalid_request`, `invalid_id`, `invalid_schema`, `unsupported_schema_feature`, `too_many_pages`. */
|
|
77
|
+
export declare class BadRequestError extends APIError {
|
|
78
|
+
}
|
|
79
|
+
/** 401 `unauthorized`: the API key is missing, wrong or revoked. */
|
|
80
|
+
export declare class AuthenticationError extends APIError {
|
|
81
|
+
}
|
|
82
|
+
/** 402 `insufficient_balance`: not enough pages on the balance. */
|
|
83
|
+
export declare class InsufficientBalanceError extends APIError {
|
|
84
|
+
}
|
|
85
|
+
/** 403 `forbidden`, `insufficient_scope`. */
|
|
86
|
+
export declare class PermissionDeniedError extends APIError {
|
|
87
|
+
}
|
|
88
|
+
/** 404 `not_found`. */
|
|
89
|
+
export declare class NotFoundError extends APIError {
|
|
90
|
+
}
|
|
91
|
+
/** 409 `conflict`. */
|
|
92
|
+
export declare class ConflictError extends APIError {
|
|
93
|
+
}
|
|
94
|
+
/** 409 `idempotency_conflict`: the Idempotency-Key was used with another request (or is still in flight). */
|
|
95
|
+
export declare class IdempotencyConflictError extends ConflictError {
|
|
96
|
+
}
|
|
97
|
+
/** 413 `file_too_large`: more than 50 MiB. */
|
|
98
|
+
export declare class FileTooLargeError extends APIError {
|
|
99
|
+
}
|
|
100
|
+
/** 415 `unsupported_file_type`. */
|
|
101
|
+
export declare class UnsupportedFileTypeError extends APIError {
|
|
102
|
+
}
|
|
103
|
+
/** 422 `document_unreadable`, `extraction_failed`. */
|
|
104
|
+
export declare class UnprocessableDocumentError extends APIError {
|
|
105
|
+
}
|
|
106
|
+
/** 429 `rate_limited`. Retried automatically after `Retry-After`. */
|
|
107
|
+
export declare class RateLimitError extends APIError {
|
|
108
|
+
}
|
|
109
|
+
/** 500 `internal_error` (and other 5xx except 502–504). Retried automatically. */
|
|
110
|
+
export declare class InternalServerError extends APIError {
|
|
111
|
+
}
|
|
112
|
+
/** 503 `upstream_unavailable` (and 502, 504). Retried automatically. */
|
|
113
|
+
export declare class ServiceUnavailableError extends APIError {
|
|
114
|
+
}
|
|
115
|
+
/** `client.extract()`: the run finished `failed`. */
|
|
116
|
+
export declare class RunFailedError extends TypizerError {
|
|
117
|
+
/** `run.error.code`: `document_unreadable`, `too_many_pages`, `timeout`, … */
|
|
118
|
+
readonly code: string;
|
|
119
|
+
/** `run.error.message`. */
|
|
120
|
+
readonly detail: string;
|
|
121
|
+
readonly run: Run;
|
|
122
|
+
/** True for `timeout`, `upstream_unavailable`, `internal_error`: repeat with `client.runs.retry(id)`. */
|
|
123
|
+
readonly retryable: boolean;
|
|
124
|
+
constructor(run: Run);
|
|
125
|
+
}
|
|
126
|
+
/** `client.extract()` / `client.runs.wait()`: the wait ran out; the run goes on and will be billed. */
|
|
127
|
+
export declare class WaitTimeoutError extends TypizerError {
|
|
128
|
+
readonly runId: string;
|
|
129
|
+
/** The last known state of the run. */
|
|
130
|
+
readonly run: Run;
|
|
131
|
+
/** How long it waited, in milliseconds. */
|
|
132
|
+
readonly waited: number;
|
|
133
|
+
constructor(run: Run, waited: number);
|
|
134
|
+
}
|
|
135
|
+
/** Why `verifyWebhook` rejected a delivery. */
|
|
136
|
+
export type WebhookVerificationReason = 'missing_header' | 'invalid_timestamp' | 'timestamp_out_of_tolerance' | 'signature_mismatch' | 'invalid_secret';
|
|
137
|
+
/** `verifyWebhook()`: the signature or the timestamp did not pass. */
|
|
138
|
+
export declare class WebhookVerificationError extends TypizerError {
|
|
139
|
+
readonly reason: WebhookVerificationReason;
|
|
140
|
+
constructor(reason: WebhookVerificationReason, message: string);
|
|
141
|
+
}
|
|
142
|
+
export declare function isRetryableStatus(status: number): boolean;
|
|
143
|
+
/** `Retry-After`: delta seconds or an HTTP date, in seconds from `now`. */
|
|
144
|
+
export declare function parseRetryAfter(value: string | null | undefined, now?: number): number | undefined;
|
|
145
|
+
/** Classifies an error response (SPEC §6.2): never fails on a body that is not JSON. */
|
|
146
|
+
export declare function errorFromResponse(status: number, headers: Headers, text: string): APIError;
|