@eigenpal/sdk 0.25.13 → 1.0.0-rc.1
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 +27 -105
- package/dist/client.d.ts +164 -0
- package/dist/client.js +234 -0
- package/dist/core.d.ts +82 -0
- package/dist/core.js +311 -0
- package/dist/errors.d.ts +64 -0
- package/dist/errors.js +132 -0
- package/dist/generated/operations.gen.d.ts +336 -0
- package/dist/generated/operations.gen.js +135 -0
- package/dist/generated/public.gen.d.ts +2 -0
- package/dist/generated/public.gen.js +2 -0
- package/dist/generated/resources.gen.d.ts +490 -0
- package/dist/generated/resources.gen.js +659 -0
- package/dist/generated/types.gen.d.ts +2457 -0
- package/dist/generated/types.gen.js +2 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +15 -0
- package/dist/lib/fetch-body.d.ts +23 -0
- package/dist/lib/fetch-body.js +66 -0
- package/dist/lib/files.d.ts +134 -0
- package/dist/lib/files.js +296 -0
- package/dist/lib/upload-app-chunked.d.ts +36 -0
- package/dist/lib/upload-app-chunked.js +94 -0
- package/dist/lib/upload-limits.d.ts +32 -0
- package/dist/lib/upload-limits.js +60 -0
- package/dist/lib/upload-presigned-multipart.d.ts +74 -0
- package/dist/lib/upload-presigned-multipart.js +212 -0
- package/dist/page.d.ts +30 -0
- package/dist/page.js +38 -0
- package/dist/resources.d.ts +85 -0
- package/dist/resources.js +247 -0
- package/dist/telemetry.d.ts +20 -0
- package/{src/telemetry.ts → dist/telemetry.js} +26 -31
- package/dist/upload-file.d.ts +31 -0
- package/dist/upload-file.js +286 -0
- package/{src/upload.ts → dist/upload.d.ts} +4 -4
- package/dist/upload.js +12 -0
- package/package.json +19 -15
- package/src/client.ts +0 -656
- package/src/errors.ts +0 -130
- package/src/generated/client/client.gen.ts +0 -277
- package/src/generated/client/index.ts +0 -27
- package/src/generated/client/types.gen.ts +0 -218
- package/src/generated/client/utils.gen.ts +0 -316
- package/src/generated/client.gen.ts +0 -18
- package/src/generated/core/auth.gen.ts +0 -48
- package/src/generated/core/bodySerializer.gen.ts +0 -82
- package/src/generated/core/params.gen.ts +0 -178
- package/src/generated/core/pathSerializer.gen.ts +0 -171
- package/src/generated/core/queryKeySerializer.gen.ts +0 -117
- package/src/generated/core/serverSentEvents.gen.ts +0 -242
- package/src/generated/core/types.gen.ts +0 -110
- package/src/generated/core/utils.gen.ts +0 -140
- package/src/generated/index.ts +0 -4
- package/src/generated/sdk.gen.ts +0 -1361
- package/src/generated/types.gen.ts +0 -9282
- package/src/index.ts +0 -120
- package/src/lib/fetch-body.ts +0 -92
- package/src/lib/files.ts +0 -390
- package/src/lib/upload-app-chunked.ts +0 -121
- package/src/lib/upload-limits.ts +0 -72
- package/src/lib/upload-presigned-multipart.ts +0 -285
- package/src/resources/auth.ts +0 -18
- package/src/resources/automations.ts +0 -830
- package/src/resources/dataset-review-requests.ts +0 -38
- package/src/resources/email-servers.ts +0 -95
- package/src/resources/files.ts +0 -592
- package/src/resources/folders.ts +0 -77
- package/src/resources/human-reviews.ts +0 -106
- package/src/resources/models.ts +0 -37
- package/src/resources/runs.ts +0 -350
- package/src/resources/templates.ts +0 -153
- package/src/runtime-config.ts +0 -14
package/dist/core.js
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transport: API key and base URL, telemetry headers, timeouts, retries
|
|
3
|
+
* (429 and 5xx; a non-idempotent call only when the server refused it), error
|
|
4
|
+
* mapping, JSON and binary bodies, waiting, and `call(opId, ...)`.
|
|
5
|
+
*
|
|
6
|
+
* Hand-written. Every request goes through an operation id of
|
|
7
|
+
* `generated/operations.gen.ts`; `api()` is the one escape hatch.
|
|
8
|
+
*/
|
|
9
|
+
import { EigenPalError, EigenPalTimeoutError, errorFromResponse } from './errors.js';
|
|
10
|
+
import { OPERATIONS } from './generated/operations.gen.js';
|
|
11
|
+
import { PagePromise } from './page.js';
|
|
12
|
+
import { buildTelemetryHeaders } from './telemetry.js';
|
|
13
|
+
export const DEFAULT_BASE_URL = 'https://api.eigenpal.com';
|
|
14
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
15
|
+
const DEFAULT_MAX_RETRIES = 3;
|
|
16
|
+
export const DEFAULT_WAIT_TIMEOUT_MS = 30 * 60_000;
|
|
17
|
+
const POLL_START_MS = 2_000;
|
|
18
|
+
const POLL_MAX_MS = 5_000;
|
|
19
|
+
/** Read one env var as a fallback (a published SDK cannot use `@eigenpal/env`). */
|
|
20
|
+
export function readEnv(name) {
|
|
21
|
+
// eslint-disable-next-line no-process-env
|
|
22
|
+
if (typeof process === 'undefined' || !process.env)
|
|
23
|
+
return undefined;
|
|
24
|
+
// eslint-disable-next-line no-process-env
|
|
25
|
+
const value = process.env[name];
|
|
26
|
+
return value && value.length > 0 ? value : undefined;
|
|
27
|
+
}
|
|
28
|
+
/** A signal that aborts when any of `signals` does (AbortSignal.any where the runtime has it). */
|
|
29
|
+
function anySignal(signals) {
|
|
30
|
+
const any = AbortSignal.any;
|
|
31
|
+
if (any)
|
|
32
|
+
return any(signals);
|
|
33
|
+
const controller = new AbortController();
|
|
34
|
+
for (const s of signals) {
|
|
35
|
+
if (s.aborted) {
|
|
36
|
+
controller.abort(s.reason);
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
s.addEventListener('abort', () => controller.abort(s.reason), { once: true });
|
|
40
|
+
}
|
|
41
|
+
return controller.signal;
|
|
42
|
+
}
|
|
43
|
+
export const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
44
|
+
const timer = setTimeout(resolve, ms);
|
|
45
|
+
signal?.addEventListener('abort', () => {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
reject(signal.reason);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
export class Core {
|
|
51
|
+
baseUrl;
|
|
52
|
+
project;
|
|
53
|
+
apiKey;
|
|
54
|
+
timeoutMs;
|
|
55
|
+
maxRetries;
|
|
56
|
+
fetchImpl;
|
|
57
|
+
headers;
|
|
58
|
+
/** Clock and sleep, replaceable in tests. */
|
|
59
|
+
sleep = sleep;
|
|
60
|
+
now = () => Date.now();
|
|
61
|
+
constructor(options = {}) {
|
|
62
|
+
const apiKey = options.apiKey ?? readEnv('EIGENPAL_API_KEY');
|
|
63
|
+
if (!apiKey) {
|
|
64
|
+
throw new EigenPalError('Missing API key. Pass `new EigenPalClient({ apiKey })` or set the EIGENPAL_API_KEY environment variable.', { status: 0 });
|
|
65
|
+
}
|
|
66
|
+
this.apiKey = apiKey;
|
|
67
|
+
this.baseUrl = (options.baseUrl ?? readEnv('EIGENPAL_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
68
|
+
this.project = options.project ?? readEnv('EIGENPAL_PROJECT');
|
|
69
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
70
|
+
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
71
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
72
|
+
this.headers = {
|
|
73
|
+
Authorization: `Bearer ${apiKey}`,
|
|
74
|
+
...buildTelemetryHeaders(),
|
|
75
|
+
...(options.defaultHeaders ?? {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Call one operation of the table. */
|
|
79
|
+
async request(op, req, meta = {}) {
|
|
80
|
+
const prepared = this.withProject(op, req, meta);
|
|
81
|
+
const first = await this.send(op, prepared, meta);
|
|
82
|
+
const wait = meta.wait;
|
|
83
|
+
if (!wait?.enabled)
|
|
84
|
+
return first.body;
|
|
85
|
+
return (await this.waitFor(prepared, meta, first));
|
|
86
|
+
}
|
|
87
|
+
/** Call a list operation and answer its page, iterable over every item. */
|
|
88
|
+
page(op, req, meta) {
|
|
89
|
+
return new PagePromise(meta.list, req.query?.cursor, (cursor) => this.request(op, { ...req, query: { ...req.query, cursor } }, meta));
|
|
90
|
+
}
|
|
91
|
+
/** The escape hatch: any route, by method and path (`/v1/...`). */
|
|
92
|
+
async api(method, path, options = {}) {
|
|
93
|
+
const response = await this.fetchWithRetries(method.toUpperCase(), this.url(path, options.query), options.body, { signal: options.signal, idempotent: method.toUpperCase() !== 'POST' });
|
|
94
|
+
return this.readJson(response);
|
|
95
|
+
}
|
|
96
|
+
/** Raw response of an operation (streams, files); the status is checked. */
|
|
97
|
+
async raw(op, req, meta = {}) {
|
|
98
|
+
const prepared = this.withProject(op, req, meta);
|
|
99
|
+
const spec = OPERATIONS[op];
|
|
100
|
+
return this.fetchWithRetries(spec.method, this.url(fillPath(spec.path, prepared.path), prepared.query), prepared.body, {
|
|
101
|
+
signal: prepared.signal,
|
|
102
|
+
idempotent: spec.idempotent !== false,
|
|
103
|
+
headers: prepared.headers,
|
|
104
|
+
binary: true,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
withProject(op, req, meta) {
|
|
108
|
+
if (!meta.project)
|
|
109
|
+
return req;
|
|
110
|
+
const project = req.project ?? this.project;
|
|
111
|
+
if (meta.project === 'path') {
|
|
112
|
+
if (!project) {
|
|
113
|
+
throw new EigenPalError(`${op} needs a project: pass \`project\`, \`new EigenPalClient({ project })\` or set EIGENPAL_PROJECT.`, { status: 0 });
|
|
114
|
+
}
|
|
115
|
+
return { ...req, path: { ...req.path, id: project } };
|
|
116
|
+
}
|
|
117
|
+
if (!project)
|
|
118
|
+
return req;
|
|
119
|
+
if (meta.project === 'query')
|
|
120
|
+
return { ...req, query: { project, ...req.query } };
|
|
121
|
+
return { ...req, body: { project, ...req.body } };
|
|
122
|
+
}
|
|
123
|
+
async send(op, req, meta) {
|
|
124
|
+
const spec = OPERATIONS[op];
|
|
125
|
+
const response = await this.fetchWithRetries(spec.method, this.url(fillPath(spec.path, req.path), req.query), req.body, {
|
|
126
|
+
signal: req.signal,
|
|
127
|
+
idempotent: spec.idempotent !== false,
|
|
128
|
+
headers: req.headers,
|
|
129
|
+
binary: meta.binary,
|
|
130
|
+
});
|
|
131
|
+
const retryAfter = parseRetryAfter(response.headers.get('retry-after'));
|
|
132
|
+
if (meta.binary)
|
|
133
|
+
return { status: response.status, body: await response.blob(), retryAfter };
|
|
134
|
+
return { status: response.status, body: await this.readJson(response), retryAfter };
|
|
135
|
+
}
|
|
136
|
+
async waitFor(req, meta, first) {
|
|
137
|
+
const wait = meta.wait;
|
|
138
|
+
const deadline = this.now() + (wait.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS);
|
|
139
|
+
let current = first;
|
|
140
|
+
let delay = POLL_START_MS;
|
|
141
|
+
for (;;) {
|
|
142
|
+
if (isFinal(current.body, wait))
|
|
143
|
+
return current.body;
|
|
144
|
+
if (this.now() >= deadline) {
|
|
145
|
+
throw new EigenPalTimeoutError('The wait ran out; the record is in `.record`.', current.body);
|
|
146
|
+
}
|
|
147
|
+
await this.sleep(delay, req.signal);
|
|
148
|
+
delay = Math.min(POLL_MAX_MS, Math.round(delay * 1.5));
|
|
149
|
+
const key = wait.idParam ?? 'id';
|
|
150
|
+
const id = current.body.id ?? req.path?.[key];
|
|
151
|
+
const path = { ...req.path, [key]: id };
|
|
152
|
+
current = await this.send(wait.poll, { path, signal: req.signal }, {});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** `baseUrl` + `/v1/...`, without a doubled `/api/v1` or `/v1`. */
|
|
156
|
+
url(path, query) {
|
|
157
|
+
if (/^https?:\/\//i.test(path))
|
|
158
|
+
return withQuery(path, query);
|
|
159
|
+
const base = this.baseUrl;
|
|
160
|
+
let joined;
|
|
161
|
+
if (/\/api\/v1$/.test(base) && path.startsWith('/v1/'))
|
|
162
|
+
joined = base + path.slice(3);
|
|
163
|
+
else if (/\/v1$/.test(base) && path.startsWith('/v1/'))
|
|
164
|
+
joined = base + path.slice(3);
|
|
165
|
+
else if (path.startsWith('/api/v1/') && /\/api$/.test(base))
|
|
166
|
+
joined = base + path.slice(4);
|
|
167
|
+
else if (path.startsWith('/api/v1/'))
|
|
168
|
+
joined = base + path.slice(4);
|
|
169
|
+
else
|
|
170
|
+
joined = base + path;
|
|
171
|
+
return withQuery(joined, query);
|
|
172
|
+
}
|
|
173
|
+
async fetchWithRetries(method, url, body, options) {
|
|
174
|
+
for (let attempt = 0;; attempt++) {
|
|
175
|
+
const canRetry = attempt < this.maxRetries;
|
|
176
|
+
let response;
|
|
177
|
+
// The request timeout holds also when the caller passes a signal: either one ends the request.
|
|
178
|
+
const timeout = AbortSignal.timeout(this.timeoutMs);
|
|
179
|
+
const signal = options.signal ? anySignal([options.signal, timeout]) : timeout;
|
|
180
|
+
try {
|
|
181
|
+
response = await this.fetchImpl(new Request(url, {
|
|
182
|
+
method,
|
|
183
|
+
headers: { ...this.headers, ...contentType(body), ...options.headers },
|
|
184
|
+
body: encodeBody(body),
|
|
185
|
+
signal,
|
|
186
|
+
...(isStream(body) ? { duplex: 'half' } : {}),
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
if (isAbort(err) && timeout.aborted && !options.signal?.aborted) {
|
|
191
|
+
if (options.idempotent && canRetry) {
|
|
192
|
+
await this.sleep(backoff(attempt));
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
throw new EigenPalTimeoutError();
|
|
196
|
+
}
|
|
197
|
+
if (isAbort(err))
|
|
198
|
+
throw err;
|
|
199
|
+
if (options.idempotent && canRetry) {
|
|
200
|
+
await this.sleep(backoff(attempt));
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
throw err;
|
|
204
|
+
}
|
|
205
|
+
const retriable = options.idempotent
|
|
206
|
+
? response.status >= 500 || response.status === 429
|
|
207
|
+
: response.status === 429 ||
|
|
208
|
+
(response.status === 503 && response.headers.has('retry-after'));
|
|
209
|
+
if (retriable && canRetry) {
|
|
210
|
+
await this.sleep(retryDelay(response, attempt));
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (!response.ok) {
|
|
214
|
+
assertApiHost(response);
|
|
215
|
+
const envelope = (await response.json().catch(() => undefined));
|
|
216
|
+
throw errorFromResponse(response.status, envelope, parseRetryAfter(response.headers.get('retry-after')));
|
|
217
|
+
}
|
|
218
|
+
assertApiHost(response, options.binary);
|
|
219
|
+
return response;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
async readJson(response) {
|
|
223
|
+
if (response.status === 204)
|
|
224
|
+
return null;
|
|
225
|
+
const text = await response.text();
|
|
226
|
+
return text ? JSON.parse(text) : null;
|
|
227
|
+
}
|
|
228
|
+
/** The API key (for upload helpers that talk to the same host). */
|
|
229
|
+
get authorization() {
|
|
230
|
+
return `Bearer ${this.apiKey}`;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function isFinal(record, wait) {
|
|
234
|
+
const r = record;
|
|
235
|
+
if (!r)
|
|
236
|
+
return false;
|
|
237
|
+
return wait.final.includes(String(r[wait.field]));
|
|
238
|
+
}
|
|
239
|
+
export function fillPath(template, params = {}) {
|
|
240
|
+
return template.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
241
|
+
const value = params[name];
|
|
242
|
+
if (value === undefined)
|
|
243
|
+
throw new EigenPalError(`Missing path parameter ${name} for ${template}.`, { status: 0 });
|
|
244
|
+
// Catch-all params (`{path}`, `{filename}`) keep their slashes.
|
|
245
|
+
return name === 'path' || name === 'filename'
|
|
246
|
+
? value.split('/').map(encodeURIComponent).join('/')
|
|
247
|
+
: encodeURIComponent(value);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
function withQuery(url, query) {
|
|
251
|
+
if (!query)
|
|
252
|
+
return url;
|
|
253
|
+
const params = new URLSearchParams();
|
|
254
|
+
for (const [key, value] of Object.entries(query)) {
|
|
255
|
+
if (value === undefined || value === null)
|
|
256
|
+
continue;
|
|
257
|
+
// A list filter repeats its key (`?state=failed&state=cancelled`).
|
|
258
|
+
if (Array.isArray(value))
|
|
259
|
+
for (const item of value)
|
|
260
|
+
params.append(key, String(item));
|
|
261
|
+
else
|
|
262
|
+
params.append(key, String(value));
|
|
263
|
+
}
|
|
264
|
+
const s = params.toString();
|
|
265
|
+
return s ? `${url}${url.includes('?') ? '&' : '?'}${s}` : url;
|
|
266
|
+
}
|
|
267
|
+
const isStream = (body) => !!body && typeof body === 'object' && typeof body.pipe === 'function';
|
|
268
|
+
function isRawBody(body) {
|
|
269
|
+
return (body instanceof FormData ||
|
|
270
|
+
body instanceof Blob ||
|
|
271
|
+
body instanceof ArrayBuffer ||
|
|
272
|
+
body instanceof Uint8Array ||
|
|
273
|
+
body instanceof URLSearchParams ||
|
|
274
|
+
typeof body === 'string' ||
|
|
275
|
+
isStream(body) ||
|
|
276
|
+
(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream));
|
|
277
|
+
}
|
|
278
|
+
function contentType(body) {
|
|
279
|
+
if (body === undefined || isRawBody(body))
|
|
280
|
+
return {};
|
|
281
|
+
return { 'Content-Type': 'application/json' };
|
|
282
|
+
}
|
|
283
|
+
function encodeBody(body) {
|
|
284
|
+
if (body === undefined)
|
|
285
|
+
return undefined;
|
|
286
|
+
if (isRawBody(body))
|
|
287
|
+
return body;
|
|
288
|
+
return JSON.stringify(body);
|
|
289
|
+
}
|
|
290
|
+
function assertApiHost(response, binary = false) {
|
|
291
|
+
const type = response.headers.get('content-type')?.toLowerCase() ?? '';
|
|
292
|
+
if (!type.includes('html'))
|
|
293
|
+
return;
|
|
294
|
+
throw new EigenPalError(`Expected a ${binary ? 'binary' : 'JSON'} response from the API but got Content-Type "${type}". ` +
|
|
295
|
+
'This usually means `baseUrl` points at a non-API host (the marketing site or a proxy). ' +
|
|
296
|
+
'Set `baseUrl` to your EigenPal instance, e.g. "https://api.eigenpal.com".', { status: response.status });
|
|
297
|
+
}
|
|
298
|
+
const backoff = (attempt) => 250 * 2 ** attempt;
|
|
299
|
+
function retryDelay(response, attempt) {
|
|
300
|
+
const seconds = parseRetryAfter(response.headers.get('retry-after'));
|
|
301
|
+
return seconds !== undefined ? seconds * 1000 : backoff(attempt);
|
|
302
|
+
}
|
|
303
|
+
export function parseRetryAfter(value) {
|
|
304
|
+
if (!value)
|
|
305
|
+
return undefined;
|
|
306
|
+
const seconds = Number(value);
|
|
307
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;
|
|
308
|
+
}
|
|
309
|
+
const isAbort = (err) => typeof err === 'object' &&
|
|
310
|
+
err !== null &&
|
|
311
|
+
['AbortError', 'TimeoutError'].includes(err.name ?? '');
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ApiErrorEnvelope } from './generated/types.gen.js';
|
|
2
|
+
/**
|
|
3
|
+
* Base class for every error the SDK throws.
|
|
4
|
+
*
|
|
5
|
+
* Sub-classes are dispatched on HTTP status: `EigenPalAuthError` for 401,
|
|
6
|
+
* `EigenPalForbiddenError` for 403, `EigenPalNotFoundError` for 404,
|
|
7
|
+
* `EigenPalConflictError` for 409, `EigenPalPayloadTooLargeError` for 413,
|
|
8
|
+
* `EigenPalRateLimitError` for 429, `EigenPalServerError` for 5xx.
|
|
9
|
+
* Validation failures (400) come back as `EigenPalValidationError` with
|
|
10
|
+
* the parsed `issues[]` from the canonical `ApiErrorEnvelope`.
|
|
11
|
+
*/
|
|
12
|
+
export declare class EigenPalError extends Error {
|
|
13
|
+
readonly status: number;
|
|
14
|
+
/** The server's stable error word (`not_live`, `approval_required`, `not_found`, ...): branch on it. */
|
|
15
|
+
readonly code?: string;
|
|
16
|
+
/** What to do next, from the server. */
|
|
17
|
+
readonly hint?: string;
|
|
18
|
+
readonly requestId?: string;
|
|
19
|
+
readonly envelope?: ApiErrorEnvelope;
|
|
20
|
+
constructor(message: string, opts: {
|
|
21
|
+
status: number;
|
|
22
|
+
envelope?: ApiErrorEnvelope;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export declare class EigenPalAuthError extends EigenPalError {
|
|
26
|
+
constructor(envelope?: ApiErrorEnvelope);
|
|
27
|
+
}
|
|
28
|
+
export declare class EigenPalForbiddenError extends EigenPalError {
|
|
29
|
+
constructor(envelope?: ApiErrorEnvelope);
|
|
30
|
+
}
|
|
31
|
+
export declare class EigenPalNotFoundError extends EigenPalError {
|
|
32
|
+
constructor(envelope?: ApiErrorEnvelope);
|
|
33
|
+
}
|
|
34
|
+
export declare class EigenPalValidationError extends EigenPalError {
|
|
35
|
+
readonly issues: ApiErrorEnvelope['issues'];
|
|
36
|
+
constructor(envelope: ApiErrorEnvelope);
|
|
37
|
+
}
|
|
38
|
+
/** 409: the resource changed or already exists (e.g. a stale `expectedUpdatedAt`). */
|
|
39
|
+
export declare class EigenPalConflictError extends EigenPalError {
|
|
40
|
+
constructor(envelope?: ApiErrorEnvelope);
|
|
41
|
+
}
|
|
42
|
+
/** 413: the request body or uploaded file is larger than the server accepts. */
|
|
43
|
+
export declare class EigenPalPayloadTooLargeError extends EigenPalError {
|
|
44
|
+
constructor(envelope?: ApiErrorEnvelope);
|
|
45
|
+
}
|
|
46
|
+
export declare class EigenPalRateLimitError extends EigenPalError {
|
|
47
|
+
/** Seconds until the next request may succeed. From `Retry-After`. */
|
|
48
|
+
readonly retryAfter?: number;
|
|
49
|
+
constructor(envelope?: ApiErrorEnvelope, retryAfter?: number);
|
|
50
|
+
}
|
|
51
|
+
export declare class EigenPalServerError extends EigenPalError {
|
|
52
|
+
constructor(status: number, envelope?: ApiErrorEnvelope);
|
|
53
|
+
}
|
|
54
|
+
/** A request or a wait ran out. A wait carries the last record it saw in `record`. */
|
|
55
|
+
export declare class EigenPalTimeoutError extends EigenPalError {
|
|
56
|
+
readonly record?: unknown;
|
|
57
|
+
constructor(message?: string, record?: unknown);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Map an HTTP response into the appropriate typed error. Used by the
|
|
61
|
+
* `EigenPalClient` facade to wrap raw fetch errors before they bubble to user
|
|
62
|
+
* code.
|
|
63
|
+
*/
|
|
64
|
+
export declare function errorFromResponse(status: number, envelope: ApiErrorEnvelope | undefined, retryAfter?: number): EigenPalError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base class for every error the SDK throws.
|
|
3
|
+
*
|
|
4
|
+
* Sub-classes are dispatched on HTTP status: `EigenPalAuthError` for 401,
|
|
5
|
+
* `EigenPalForbiddenError` for 403, `EigenPalNotFoundError` for 404,
|
|
6
|
+
* `EigenPalConflictError` for 409, `EigenPalPayloadTooLargeError` for 413,
|
|
7
|
+
* `EigenPalRateLimitError` for 429, `EigenPalServerError` for 5xx.
|
|
8
|
+
* Validation failures (400) come back as `EigenPalValidationError` with
|
|
9
|
+
* the parsed `issues[]` from the canonical `ApiErrorEnvelope`.
|
|
10
|
+
*/
|
|
11
|
+
export class EigenPalError extends Error {
|
|
12
|
+
status;
|
|
13
|
+
/** The server's stable error word (`not_live`, `approval_required`, `not_found`, ...): branch on it. */
|
|
14
|
+
code;
|
|
15
|
+
/** What to do next, from the server. */
|
|
16
|
+
hint;
|
|
17
|
+
requestId;
|
|
18
|
+
envelope;
|
|
19
|
+
constructor(message, opts) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = 'EigenPalError';
|
|
22
|
+
this.status = opts.status;
|
|
23
|
+
this.code = opts.envelope?.code;
|
|
24
|
+
this.hint = opts.envelope?.hint;
|
|
25
|
+
this.requestId = opts.envelope?.requestId;
|
|
26
|
+
this.envelope = opts.envelope;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** The server's sentence for an error envelope. */
|
|
30
|
+
const said = (envelope, fallback) => envelope?.message ?? envelope?.issues?.[0]?.message ?? fallback;
|
|
31
|
+
export class EigenPalAuthError extends EigenPalError {
|
|
32
|
+
constructor(envelope) {
|
|
33
|
+
super(said(envelope, 'Invalid or missing API key. Generate one at studio.eigenpal.com → Settings → API Keys; ' +
|
|
34
|
+
'pass it as `new EigenPalClient({ apiKey })` or set EIGENPAL_API_KEY.'), { status: 401, envelope });
|
|
35
|
+
this.name = 'EigenPalAuthError';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export class EigenPalForbiddenError extends EigenPalError {
|
|
39
|
+
constructor(envelope) {
|
|
40
|
+
super(said(envelope, 'forbidden'), { status: 403, envelope });
|
|
41
|
+
this.name = 'EigenPalForbiddenError';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export class EigenPalNotFoundError extends EigenPalError {
|
|
45
|
+
constructor(envelope) {
|
|
46
|
+
super(said(envelope, 'not found'), { status: 404, envelope });
|
|
47
|
+
this.name = 'EigenPalNotFoundError';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export class EigenPalValidationError extends EigenPalError {
|
|
51
|
+
issues;
|
|
52
|
+
constructor(envelope) {
|
|
53
|
+
const first = envelope.issues?.[0];
|
|
54
|
+
super(envelope.message ?? (first ? `${first.field}: ${first.message}` : 'validation error'), {
|
|
55
|
+
status: 400,
|
|
56
|
+
envelope,
|
|
57
|
+
});
|
|
58
|
+
this.name = 'EigenPalValidationError';
|
|
59
|
+
this.issues = envelope.issues;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** 409: the resource changed or already exists (e.g. a stale `expectedUpdatedAt`). */
|
|
63
|
+
export class EigenPalConflictError extends EigenPalError {
|
|
64
|
+
constructor(envelope) {
|
|
65
|
+
super(said(envelope, 'conflict'), { status: 409, envelope });
|
|
66
|
+
this.name = 'EigenPalConflictError';
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** 413: the request body or uploaded file is larger than the server accepts. */
|
|
70
|
+
export class EigenPalPayloadTooLargeError extends EigenPalError {
|
|
71
|
+
constructor(envelope) {
|
|
72
|
+
super(said(envelope, 'payload too large'), { status: 413, envelope });
|
|
73
|
+
this.name = 'EigenPalPayloadTooLargeError';
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export class EigenPalRateLimitError extends EigenPalError {
|
|
77
|
+
/** Seconds until the next request may succeed. From `Retry-After`. */
|
|
78
|
+
retryAfter;
|
|
79
|
+
constructor(envelope, retryAfter) {
|
|
80
|
+
super(said(envelope, 'rate limit exceeded'), { status: 429, envelope });
|
|
81
|
+
this.name = 'EigenPalRateLimitError';
|
|
82
|
+
this.retryAfter = retryAfter;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export class EigenPalServerError extends EigenPalError {
|
|
86
|
+
constructor(status, envelope) {
|
|
87
|
+
super(said(envelope, 'internal server error'), { status, envelope });
|
|
88
|
+
this.name = 'EigenPalServerError';
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** A request or a wait ran out. A wait carries the last record it saw in `record`. */
|
|
92
|
+
export class EigenPalTimeoutError extends EigenPalError {
|
|
93
|
+
record;
|
|
94
|
+
constructor(message = 'operation timed out', record) {
|
|
95
|
+
super(message, { status: 0 });
|
|
96
|
+
this.name = 'EigenPalTimeoutError';
|
|
97
|
+
this.record = record;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Map an HTTP response into the appropriate typed error. Used by the
|
|
102
|
+
* `EigenPalClient` facade to wrap raw fetch errors before they bubble to user
|
|
103
|
+
* code.
|
|
104
|
+
*/
|
|
105
|
+
export function errorFromResponse(status, envelope, retryAfter) {
|
|
106
|
+
if (status === 400)
|
|
107
|
+
return new EigenPalValidationError(envelope ?? {
|
|
108
|
+
code: 'validation_failed',
|
|
109
|
+
message: 'The request was refused.',
|
|
110
|
+
hint: 'Check the request against the API reference.',
|
|
111
|
+
issues: [],
|
|
112
|
+
requestId: '',
|
|
113
|
+
});
|
|
114
|
+
if (status === 401)
|
|
115
|
+
return new EigenPalAuthError(envelope);
|
|
116
|
+
if (status === 403)
|
|
117
|
+
return new EigenPalForbiddenError(envelope);
|
|
118
|
+
if (status === 404)
|
|
119
|
+
return new EigenPalNotFoundError(envelope);
|
|
120
|
+
if (status === 409)
|
|
121
|
+
return new EigenPalConflictError(envelope);
|
|
122
|
+
if (status === 413)
|
|
123
|
+
return new EigenPalPayloadTooLargeError(envelope);
|
|
124
|
+
if (status === 429)
|
|
125
|
+
return new EigenPalRateLimitError(envelope, retryAfter);
|
|
126
|
+
if (status >= 500)
|
|
127
|
+
return new EigenPalServerError(status, envelope);
|
|
128
|
+
return new EigenPalError(said(envelope, `unexpected status ${status}`), {
|
|
129
|
+
status,
|
|
130
|
+
envelope,
|
|
131
|
+
});
|
|
132
|
+
}
|