nenavi 0.0.0 → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,80 @@
1
+ import { NenaviError } from './errors.js';
2
+ /** The `fetch` the SDK calls: the runtime's own, or one the caller passes. */
3
+ export type Fetch = (input: string, init: RequestInit) => Promise<Response>;
4
+ export interface ClientOptions {
5
+ /** The project key. Defaults to `NENAVI_API_KEY`. */
6
+ apiKey?: string | null;
7
+ /** Defaults to `NENAVI_BASE_URL`, else `https://api.prismemory.com`. */
8
+ baseURL?: string | null;
9
+ /** Milliseconds per attempt, 30 000 by default. */
10
+ timeout?: number;
11
+ /** Automatic retries of a retry-safe call, 2 by default; 0 turns them off. */
12
+ maxRetries?: number;
13
+ /** A `fetch` to send the requests with, for tests and unusual runtimes. */
14
+ fetch?: Fetch;
15
+ }
16
+ export interface RequestOptions {
17
+ /** Aborting it stops the request and any pending retry. */
18
+ signal?: AbortSignal | null;
19
+ /** Milliseconds per attempt, for this call. */
20
+ timeout?: number;
21
+ /** Automatic retries, for this call. */
22
+ maxRetries?: number;
23
+ }
24
+ export interface IdempotentRequestOptions extends RequestOptions {
25
+ /** The `Idempotency-Key` to send. Pass an error's `idempotencyKey` to retry by hand. */
26
+ idempotencyKey?: string | null;
27
+ }
28
+ /** A successful call's status, headers and request id, with the parsed body as `data`. */
29
+ export interface RawResponse<T> {
30
+ status: number;
31
+ headers: Headers;
32
+ requestId: string | null;
33
+ data: T;
34
+ }
35
+ /** One operation call, before it is sent. */
36
+ export interface Call {
37
+ method: 'GET' | 'POST' | 'PUT';
38
+ /** The path, with its parameters already encoded by `pathParam`. */
39
+ path: string;
40
+ retrySafe: boolean;
41
+ /** False only for `health`, which sends no key. */
42
+ auth?: boolean;
43
+ query?: object | undefined;
44
+ /** The JSON body; undefined sends none. */
45
+ body?: unknown;
46
+ idempotencyKey?: string | null;
47
+ options?: RequestOptions | undefined;
48
+ /** The JSON type of the answer: an object (the default), an array, or an object or null. */
49
+ answer?: 'object' | 'array' | 'nullable';
50
+ /**
51
+ * A helper's deadline on `Core.now`: it caps each attempt's timeout and stops a retry
52
+ * whose wait would end past it. Unset for an ordinary call.
53
+ */
54
+ deadline?: number;
55
+ }
56
+ /** Encode one path parameter, so a value cannot add or change path segments. */
57
+ export declare function pathParam(value: string): string;
58
+ /** A copy of the object's own enumerable properties, with no prototype. */
59
+ export declare function ownProperties<T extends object>(value: T | null | undefined): Partial<T>;
60
+ /** Check a helper's `timeout` and `interval` (milliseconds); return when it must stop. */
61
+ export declare function helperDeadline(now: number, timeout: number, interval: number): number;
62
+ /** The milliseconds to wait before a helper's next poll, or null when the time is up. */
63
+ export declare function helperWait(now: number, deadline: number, interval: number): number | null;
64
+ /** Wait `ms` milliseconds, or reject with the signal's reason when it is aborted first. */
65
+ export declare function sleep(ms: number, signal?: AbortSignal | null): Promise<void>;
66
+ /** Set `cause` as the `Error` constructor does: an own property that is not enumerable. */
67
+ export declare function withCause<E extends Error>(error: E, cause: NenaviError): E;
68
+ /** Holds the configuration and sends the calls. The key is a private field. */
69
+ export declare class Core {
70
+ #private;
71
+ readonly baseURL: string;
72
+ readonly timeout: number;
73
+ readonly maxRetries: number;
74
+ /** How the client waits before a retry: replaced in tests. */
75
+ sleep: (ms: number, signal?: AbortSignal | null) => Promise<void>;
76
+ /** The helpers' clock, in milliseconds: replaced in tests. */
77
+ now: () => number;
78
+ constructor(given: ClientOptions);
79
+ request<T>(call: Call, raw: boolean): Promise<T | RawResponse<T>>;
80
+ }
@@ -0,0 +1,426 @@
1
+ "use strict";
2
+ // Configuration, request building, sending and retries (sdks/CONTRACT.md).
3
+ //
4
+ // Everything that decides what to send, whether to retry, how long to wait and which
5
+ // error to throw lives here. The method classes in client.ts only describe each call.
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.Core = void 0;
8
+ exports.pathParam = pathParam;
9
+ exports.ownProperties = ownProperties;
10
+ exports.helperDeadline = helperDeadline;
11
+ exports.helperWait = helperWait;
12
+ exports.sleep = sleep;
13
+ exports.withCause = withCause;
14
+ const errors_js_1 = require("./errors.js");
15
+ const version_js_1 = require("./version.js");
16
+ const DEFAULT_BASE_URL = 'https://api.prismemory.com';
17
+ /** Milliseconds per attempt. */
18
+ const DEFAULT_TIMEOUT = 30_000;
19
+ const DEFAULT_MAX_RETRIES = 2;
20
+ /** Seconds: a longer `Retry-After` is not waited for. */
21
+ const MAX_RETRY_AFTER = 60;
22
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
23
+ const RETRYABLE_503 = new Set(['database_unavailable', 'lease_unavailable']);
24
+ /**
25
+ * Milliseconds: the shortest attempt timeout a helper's poll gets near its deadline, so the
26
+ * poll at the deadline (and the one poll of `timeout: 0`) can still be answered.
27
+ */
28
+ const MIN_POLL_TIMEOUT = 1_000;
29
+ /** The longest delay setTimeout keeps: a longer one fires at once. */
30
+ const MAX_TIMEOUT = 2_147_483_647;
31
+ // Visible ASCII only: what an HTTP header can carry without encoding. This is not a check
32
+ // of the key's format (the service is the authority on that); it stops a pasted space,
33
+ // line break or curly quote from reaching fetch, whose error would show the value.
34
+ const HEADER_VALUE = /^[\x21-\x7e]+$/;
35
+ const runtime = globalThis;
36
+ function env(name) {
37
+ try {
38
+ // Deno without --allow-env throws here; that counts as unset. Own properties only:
39
+ // Node's process.env falls back to Object.prototype for a name it does not have.
40
+ const variables = runtime.process?.env;
41
+ const value = variables && Object.hasOwn(variables, name) ? variables[name] : undefined;
42
+ return typeof value === 'string' && value !== '' ? value : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ function runtimeName() {
49
+ // Bun and Deno also set process.versions.node, so they are checked first.
50
+ if (runtime.Bun?.version)
51
+ return `bun/${runtime.Bun.version}`;
52
+ if (runtime.Deno?.version?.deno)
53
+ return `deno/${runtime.Deno.version.deno}`;
54
+ const node = runtime.process?.versions?.node;
55
+ if (node)
56
+ return `node/${node}`;
57
+ return 'unknown/unknown';
58
+ }
59
+ const USER_AGENT = `nenavi-typescript/${version_js_1.VERSION} ${runtimeName()}`;
60
+ /** Return the base URL to use, or throw ConfigurationError for an unsafe one. */
61
+ function resolveBaseURL(baseURL) {
62
+ const value = baseURL || env('NENAVI_BASE_URL') || DEFAULT_BASE_URL;
63
+ let url;
64
+ try {
65
+ url = new URL(value);
66
+ }
67
+ catch {
68
+ throw new errors_js_1.ConfigurationError('The base URL is not a valid URL.');
69
+ }
70
+ if (url.username || url.password) {
71
+ throw new errors_js_1.ConfigurationError('The base URL must not contain a user name or password.');
72
+ }
73
+ if (url.search || url.hash || value.includes('?') || value.includes('#')) {
74
+ throw new errors_js_1.ConfigurationError('The base URL must not contain a query or a fragment.');
75
+ }
76
+ const loopback = url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname);
77
+ if (!loopback && (url.protocol !== 'https:' || !url.hostname)) {
78
+ throw new errors_js_1.ConfigurationError(`The base URL ${url.origin} must use https (http is allowed only for localhost, ` +
79
+ '127.0.0.1 or ::1), so the API key never travels unencrypted.');
80
+ }
81
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, '');
82
+ }
83
+ /** Encode one path parameter, so a value cannot add or change path segments. */
84
+ function pathParam(value) {
85
+ const text = String(value);
86
+ // fetch's URL parser removes dot segments, even percent-encoded ones, and an empty
87
+ // value would reach another route, so these cannot be sent as one path segment.
88
+ if (text === '' || text === '.' || text === '..') {
89
+ throw new errors_js_1.ConfigurationError(`A path parameter cannot be ${JSON.stringify(text)}.`);
90
+ }
91
+ return encodeURIComponent(text);
92
+ }
93
+ /** The query string for the parameters the caller passed; a query cannot carry null. */
94
+ function queryString(query) {
95
+ if (query === undefined || query === null)
96
+ return '';
97
+ const params = new URLSearchParams();
98
+ for (const [name, value] of Object.entries(query)) {
99
+ if (value === undefined || value === null)
100
+ continue;
101
+ for (const item of Array.isArray(value) ? value : [value]) {
102
+ if (item !== undefined && item !== null)
103
+ params.append(name, String(item));
104
+ }
105
+ }
106
+ const text = params.toString();
107
+ return text ? `?${text}` : '';
108
+ }
109
+ /** A copy of the object's own enumerable properties, with no prototype. */
110
+ function ownProperties(value) {
111
+ return Object.assign(Object.create(null), value ?? {});
112
+ }
113
+ function checkTimeout(timeout) {
114
+ if (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout <= 0) {
115
+ throw new errors_js_1.ConfigurationError('timeout must be a positive number of milliseconds.');
116
+ }
117
+ if (timeout > MAX_TIMEOUT) {
118
+ throw new errors_js_1.ConfigurationError(`timeout must be at most ${MAX_TIMEOUT} milliseconds.`);
119
+ }
120
+ return timeout;
121
+ }
122
+ /** Check a helper's `timeout` and `interval` (milliseconds); return when it must stop. */
123
+ function helperDeadline(now, timeout, interval) {
124
+ if (typeof timeout !== 'number' || !(timeout >= 0)) {
125
+ throw new errors_js_1.ConfigurationError('timeout must be 0 or more milliseconds.');
126
+ }
127
+ if (typeof interval !== 'number' || !Number.isFinite(interval) || interval <= 0) {
128
+ throw new errors_js_1.ConfigurationError('interval must be a positive number of milliseconds.');
129
+ }
130
+ if (interval > MAX_TIMEOUT) {
131
+ throw new errors_js_1.ConfigurationError(`interval must be at most ${MAX_TIMEOUT} milliseconds.`);
132
+ }
133
+ return now + timeout;
134
+ }
135
+ /** The milliseconds to wait before a helper's next poll, or null when the time is up. */
136
+ function helperWait(now, deadline, interval) {
137
+ const left = deadline - now;
138
+ if (!(left > 0))
139
+ return null;
140
+ return Math.min(interval, left);
141
+ }
142
+ function monotonicNow() {
143
+ return typeof performance !== 'undefined' ? performance.now() : Date.now();
144
+ }
145
+ function checkMaxRetries(maxRetries) {
146
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) {
147
+ throw new errors_js_1.ConfigurationError('maxRetries must be a whole number, 0 or more.');
148
+ }
149
+ return maxRetries;
150
+ }
151
+ function abortReason(signal) {
152
+ return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
153
+ }
154
+ /** Wait `ms` milliseconds, or reject with the signal's reason when it is aborted first. */
155
+ function sleep(ms, signal) {
156
+ return new Promise((resolve, reject) => {
157
+ if (signal?.aborted) {
158
+ reject(abortReason(signal));
159
+ return;
160
+ }
161
+ const onAbort = () => {
162
+ clearTimeout(timer);
163
+ reject(abortReason(signal));
164
+ };
165
+ const timer = setTimeout(() => {
166
+ signal?.removeEventListener('abort', onAbort);
167
+ resolve();
168
+ }, ms);
169
+ signal?.addEventListener('abort', onAbort, { once: true });
170
+ });
171
+ }
172
+ /** Settle as `promise` does, or reject once `signal` aborts, whichever comes first. */
173
+ function untilAborted(promise, signal) {
174
+ if (signal.aborted)
175
+ return Promise.reject(abortReason(signal));
176
+ return new Promise((resolve, reject) => {
177
+ const onAbort = () => reject(abortReason(signal));
178
+ signal.addEventListener('abort', onAbort, { once: true });
179
+ promise.then((value) => {
180
+ signal.removeEventListener('abort', onAbort);
181
+ resolve(value);
182
+ }, (error) => {
183
+ signal.removeEventListener('abort', onAbort);
184
+ reject(error);
185
+ });
186
+ });
187
+ }
188
+ /** `min(8, 0.5 × 2^(n−1))` seconds, times a random factor from 0.75 to 1.0, in milliseconds. */
189
+ function backoff(retryNumber) {
190
+ const base = Math.min(8, 0.5 * 2 ** (retryNumber - 1));
191
+ return base * (0.75 + Math.random() * 0.25) * 1000;
192
+ }
193
+ /** The milliseconds to wait before retry `retryNumber`, or null for no retry. */
194
+ function retryWait(error, retryNumber) {
195
+ if (error instanceof errors_js_1.APITimeoutError)
196
+ return null;
197
+ if (error instanceof errors_js_1.APIConnectionError)
198
+ return backoff(retryNumber);
199
+ if (error instanceof errors_js_1.RateLimitError ||
200
+ (error instanceof errors_js_1.ServiceUnavailableError && RETRYABLE_503.has(error.reasonCode ?? ''))) {
201
+ const retryAfter = (0, errors_js_1.parseRetryAfter)(error.headers['retry-after']);
202
+ if (retryAfter === null)
203
+ return backoff(retryNumber);
204
+ if (retryAfter > MAX_RETRY_AFTER)
205
+ return null;
206
+ return retryAfter * 1000;
207
+ }
208
+ return null;
209
+ }
210
+ /**
211
+ * The error for a helper's poll that its deadline stopped; the helper adds its status. The
212
+ * poll's own error becomes its `cause`.
213
+ */
214
+ function deadlineError(error, retrySkipped) {
215
+ const reason = retrySkipped
216
+ ? `the last poll threw ${error.name}, and its retry would have waited past the deadline`
217
+ : `the last poll got no answer before the deadline (${error.name})`;
218
+ return withCause(new errors_js_1.WaitTimeoutError(reason, { idempotencyKey: error.idempotencyKey }), error);
219
+ }
220
+ /** Set `cause` as the `Error` constructor does: an own property that is not enumerable. */
221
+ function withCause(error, cause) {
222
+ Object.defineProperty(error, 'cause', { value: cause, writable: true, configurable: true });
223
+ return error;
224
+ }
225
+ /** The name, and the system error code when there is one, of what fetch threw. */
226
+ function failureName(error) {
227
+ const raw = error instanceof Error ? error.name : typeof error;
228
+ // Only a plain identifier, so the message stays fixed text.
229
+ const name = /^[A-Za-z]{1,40}$/.test(raw) ? raw : 'Error';
230
+ const cause = error instanceof Error ? error.cause : null;
231
+ const code = typeof cause?.code === 'string' && /^[A-Z_]+$/.test(cause.code) ? cause.code : '';
232
+ return code ? `${name}, ${code}` : name;
233
+ }
234
+ function headerRecord(headers) {
235
+ const record = {};
236
+ headers.forEach((value, name) => {
237
+ record[name.toLowerCase()] = value;
238
+ });
239
+ return record;
240
+ }
241
+ /** Holds the configuration and sends the calls. The key is a private field. */
242
+ class Core {
243
+ #apiKey;
244
+ #fetch;
245
+ baseURL;
246
+ timeout;
247
+ maxRetries;
248
+ /** How the client waits before a retry: replaced in tests. */
249
+ sleep = sleep;
250
+ /** The helpers' clock, in milliseconds: replaced in tests. */
251
+ now = monotonicNow;
252
+ constructor(given) {
253
+ // Own properties only: an option inherited from a polluted Object.prototype must not
254
+ // choose where the key is sent.
255
+ const options = ownProperties(given);
256
+ const apiKey = options.apiKey || env('NENAVI_API_KEY');
257
+ if (apiKey !== null && !HEADER_VALUE.test(apiKey)) {
258
+ throw new errors_js_1.ConfigurationError('The API key contains a space, a line break or a character outside ASCII, ' +
259
+ 'which an HTTP header cannot carry. Check that it was copied exactly.');
260
+ }
261
+ this.#apiKey = apiKey;
262
+ this.baseURL = resolveBaseURL(options.baseURL);
263
+ this.timeout = checkTimeout(options.timeout ?? DEFAULT_TIMEOUT);
264
+ this.maxRetries = checkMaxRetries(options.maxRetries ?? DEFAULT_MAX_RETRIES);
265
+ const custom = options.fetch;
266
+ if (custom !== undefined && typeof custom !== 'function') {
267
+ throw new errors_js_1.ConfigurationError('fetch must be a function.');
268
+ }
269
+ // Called unbound: some runtimes refuse a fetch called as a method of another object.
270
+ this.#fetch = (input, init) => {
271
+ const send = custom ?? globalThis.fetch;
272
+ if (send === undefined) {
273
+ throw new errors_js_1.ConfigurationError('This runtime has no fetch: pass one as the fetch option.');
274
+ }
275
+ // Promise.resolve: a caller's fetch may return a Response rather than a promise.
276
+ return Promise.resolve(send(input, init));
277
+ };
278
+ }
279
+ async request(call, raw) {
280
+ const options = ownProperties(call.options);
281
+ const signal = options.signal ?? null;
282
+ if (signal?.aborted)
283
+ throw abortReason(signal);
284
+ const auth = call.auth ?? true;
285
+ if (auth && this.#apiKey === null) {
286
+ throw new errors_js_1.ConfigurationError('No API key: pass apiKey or set NENAVI_API_KEY. Only health() works without a key.');
287
+ }
288
+ const callTimeout = checkTimeout(options.timeout ?? this.timeout);
289
+ const deadline = call.deadline ?? null;
290
+ const maxRetries = checkMaxRetries(options.maxRetries ?? this.maxRetries);
291
+ const idempotencyKey = call.idempotencyKey ?? null;
292
+ const headers = {
293
+ Accept: 'application/json',
294
+ 'User-Agent': USER_AGENT,
295
+ };
296
+ if (auth && this.#apiKey !== null)
297
+ headers.Authorization = `Bearer ${this.#apiKey}`;
298
+ if (idempotencyKey !== null) {
299
+ if (!HEADER_VALUE.test(idempotencyKey)) {
300
+ throw new errors_js_1.ConfigurationError('The idempotency key contains a space, a line break or a character outside ASCII, ' +
301
+ 'which an HTTP header cannot carry.');
302
+ }
303
+ headers['Idempotency-Key'] = idempotencyKey;
304
+ }
305
+ let body;
306
+ if (call.body !== undefined) {
307
+ headers['Content-Type'] = 'application/json';
308
+ body = JSON.stringify(call.body);
309
+ }
310
+ const url = `${this.baseURL}${call.path}${queryString(call.query)}`;
311
+ let retries = 0;
312
+ for (;;) {
313
+ // A helper's poll gets only the time left.
314
+ const left = deadline === null ? Infinity : Math.max(deadline - this.now(), MIN_POLL_TIMEOUT);
315
+ const shortened = left < callTimeout;
316
+ const timeout = shortened ? left : callTimeout;
317
+ const attempt = await this.#send(url, call.method, headers, body, timeout, signal, idempotencyKey);
318
+ if (attempt.response !== undefined) {
319
+ return this.#result(attempt.response, attempt.text, raw, idempotencyKey, call.answer ?? 'object');
320
+ }
321
+ if (call.retrySafe && retries < maxRetries) {
322
+ const wait = retryWait(attempt.error, retries + 1);
323
+ if (wait !== null) {
324
+ if (deadline === null || this.now() + wait < deadline) {
325
+ retries += 1;
326
+ await this.sleep(wait, signal);
327
+ continue;
328
+ }
329
+ throw deadlineError(attempt.error, true);
330
+ }
331
+ }
332
+ if (shortened && attempt.error instanceof errors_js_1.APITimeoutError) {
333
+ throw deadlineError(attempt.error, false);
334
+ }
335
+ throw attempt.error;
336
+ }
337
+ }
338
+ async #send(url, method, headers, body, timeout, signal, idempotencyKey) {
339
+ const controller = new AbortController();
340
+ let timedOut = false;
341
+ const timer = setTimeout(() => {
342
+ timedOut = true;
343
+ controller.abort();
344
+ }, timeout);
345
+ const onAbort = () => controller.abort();
346
+ signal?.addEventListener('abort', onAbort, { once: true });
347
+ try {
348
+ // redirect: "manual": a 3xx is the answer, so the key is never sent elsewhere.
349
+ // The timeout and the caller's signal cover the whole attempt, reading the body
350
+ // included, also with a caller's fetch that does not follow the signal.
351
+ const response = await untilAborted(this.#fetch(url,
352
+ // No prototype, so an option inherited from a polluted Object.prototype (such
353
+ // as a dispatcher) cannot reach fetch.
354
+ Object.assign(Object.create(null), {
355
+ method,
356
+ headers: { ...headers },
357
+ body,
358
+ redirect: 'manual',
359
+ signal: controller.signal,
360
+ })), controller.signal);
361
+ const text = await untilAborted(response.text(), controller.signal);
362
+ if (response.ok)
363
+ return { response, text };
364
+ const error = (0, errors_js_1.errorFromResponse)(response.status, headerRecord(response.headers), text, idempotencyKey);
365
+ return { error };
366
+ }
367
+ catch (error) {
368
+ if (signal?.aborted)
369
+ throw abortReason(signal);
370
+ if (error instanceof errors_js_1.ConfigurationError)
371
+ throw error;
372
+ // A new error with no cause: what fetch threw can hold the request and its key.
373
+ if (timedOut) {
374
+ return {
375
+ error: new errors_js_1.APITimeoutError(`No response within the timeout (${timeout} ms).`, {
376
+ idempotencyKey,
377
+ }),
378
+ };
379
+ }
380
+ return {
381
+ error: new errors_js_1.APIConnectionError(`No usable response from the service (${failureName(error)}).`, { idempotencyKey }),
382
+ };
383
+ }
384
+ finally {
385
+ clearTimeout(timer);
386
+ signal?.removeEventListener('abort', onAbort);
387
+ }
388
+ }
389
+ #result(response, text, raw, idempotencyKey, answer) {
390
+ const requestId = response.headers.get('x-request-id');
391
+ let data;
392
+ let problem = null;
393
+ try {
394
+ data = JSON.parse(text);
395
+ const matches = answer === 'array'
396
+ ? Array.isArray(data)
397
+ : (typeof data === 'object' && data !== null && !Array.isArray(data)) ||
398
+ (answer === 'nullable' && data === null);
399
+ if (!matches) {
400
+ problem = 'the body is not the JSON type the operation answers with';
401
+ }
402
+ }
403
+ catch {
404
+ problem = 'the body is not JSON';
405
+ // Not JSON: keep the start of the text, as an APIError does.
406
+ data = text ? text.slice(0, errors_js_1.DETAIL_TEXT_LIMIT) : null;
407
+ }
408
+ if (problem !== null) {
409
+ // The body can hold stored memory text, which does not belong in a log line.
410
+ const suffix = requestId ? ` (request id ${requestId})` : '';
411
+ throw new errors_js_1.ResponseValidationError(`The ${response.status} response did not match the expected shape${suffix}: ` +
412
+ `${problem}. The call may have taken effect.`, {
413
+ status: response.status,
414
+ requestId,
415
+ headers: headerRecord(response.headers),
416
+ body: data,
417
+ idempotencyKey,
418
+ });
419
+ }
420
+ if (raw) {
421
+ return { status: response.status, headers: response.headers, requestId, data: data };
422
+ }
423
+ return data;
424
+ }
425
+ }
426
+ exports.Core = Core;
@@ -0,0 +1,129 @@
1
+ /** Base class of every error the SDK throws. */
2
+ export declare class NenaviError extends Error {
3
+ /**
4
+ * `value instanceof` this class, also for an error from another copy of the package.
5
+ * Installed below with `Object.defineProperty`.
6
+ */
7
+ static [Symbol.hasInstance]: <T>(this: abstract new (...args: never[]) => T, value: unknown) => value is T;
8
+ /** The `Idempotency-Key` the call sent, or null when it sent none. */
9
+ idempotencyKey: string | null;
10
+ /**
11
+ * The last status a helper read before it threw: on `WaitTimeoutError`, and on the
12
+ * error of a poll that failed inside `reingest.run()`, where it holds the run's
13
+ * `run_id`. Null on other errors.
14
+ */
15
+ lastStatus: unknown;
16
+ constructor(message: string, options?: {
17
+ idempotencyKey?: string | null;
18
+ lastStatus?: unknown;
19
+ });
20
+ }
21
+ /** No key for an operation that needs one, or an invalid option. */
22
+ export declare class ConfigurationError extends NenaviError {
23
+ }
24
+ /** A helper ran out of time before the work it waited for finished. */
25
+ export declare class WaitTimeoutError extends NenaviError {
26
+ }
27
+ export interface ResponseValidationErrorOptions {
28
+ status: number;
29
+ requestId: string | null;
30
+ headers: Record<string, string>;
31
+ body: unknown;
32
+ idempotencyKey: string | null;
33
+ }
34
+ /**
35
+ * A 2xx response whose body does not match the shape the operation answers with.
36
+ *
37
+ * The call may have taken effect: a `store` or `ingest` that throws this has usually
38
+ * stored the memory, so read `body` (for example its `event_id`) before calling again.
39
+ * It is not an `APIError`, because the service did not refuse the call.
40
+ */
41
+ export declare class ResponseValidationError extends NenaviError {
42
+ /** The HTTP status. */
43
+ status: number;
44
+ /** The response's `X-Request-ID` header, or null. */
45
+ requestId: string | null;
46
+ /** The response headers, with names in lower case. */
47
+ headers: Record<string, string>;
48
+ /** The parsed body, the first 500 characters of its text when it is not JSON, or null when empty. */
49
+ body: unknown;
50
+ constructor(message: string, options: ResponseValidationErrorOptions);
51
+ }
52
+ /** No response: DNS failure, connection refused or reset, or a TLS error. */
53
+ export declare class APIConnectionError extends NenaviError {
54
+ }
55
+ /** No response within the timeout. */
56
+ export declare class APITimeoutError extends APIConnectionError {
57
+ }
58
+ export interface APIErrorOptions {
59
+ status: number;
60
+ reasonCode: string | null;
61
+ detail: unknown;
62
+ requestId: string | null;
63
+ headers: Record<string, string>;
64
+ body: unknown;
65
+ idempotencyKey: string | null;
66
+ }
67
+ /** The service answered with a status other than 2xx. */
68
+ export declare class APIError extends NenaviError {
69
+ /** The HTTP status. */
70
+ status: number;
71
+ /** The body's `reason_code` when it is a string, else null (engine errors have none). */
72
+ reasonCode: string | null;
73
+ /** The body's `detail` as it was sent, or the first 500 characters of a text body. */
74
+ detail: unknown;
75
+ /** The response's `X-Request-ID` header, or null. */
76
+ requestId: string | null;
77
+ /** The response headers, with names in lower case. */
78
+ headers: Record<string, string>;
79
+ /** The parsed body, or its text when it is not JSON. */
80
+ body: unknown;
81
+ constructor(message: string, options: APIErrorOptions);
82
+ }
83
+ /** 400. */
84
+ export declare class BadRequestError extends APIError {
85
+ }
86
+ /** 401: the key is missing, invalid or revoked, or its project was deleted. */
87
+ export declare class AuthenticationError extends APIError {
88
+ }
89
+ /** 403. */
90
+ export declare class PermissionDeniedError extends APIError {
91
+ }
92
+ /** 404. */
93
+ export declare class NotFoundError extends APIError {
94
+ }
95
+ /** 409, for example `reingest_running`. */
96
+ export declare class ConflictError extends APIError {
97
+ }
98
+ /** 413. */
99
+ export declare class PayloadTooLargeError extends APIError {
100
+ }
101
+ /** 422: a refused value, or a request validation error. */
102
+ export declare class UnprocessableEntityError extends APIError {
103
+ }
104
+ /** 429 `rate_limited`. `retryAfter` is the `Retry-After` header in seconds, or null. */
105
+ export declare class RateLimitError extends APIError {
106
+ retryAfter: number | null;
107
+ constructor(message: string, options: APIErrorOptions & {
108
+ retryAfter: number | null;
109
+ });
110
+ }
111
+ /** 429 for a monthly limit, the node cap or any other `reason_code`: never retried. */
112
+ export declare class QuotaExceededError extends APIError {
113
+ }
114
+ /** 500 to 599, except 503. */
115
+ export declare class InternalServerError extends APIError {
116
+ }
117
+ /** 503. */
118
+ export declare class ServiceUnavailableError extends APIError {
119
+ }
120
+ export declare const DETAIL_TEXT_LIMIT = 500;
121
+ /**
122
+ * Return a `Retry-After` header as whole seconds, or null when it is unusable.
123
+ *
124
+ * Only a whole, non-negative number of seconds counts. An HTTP date, a fraction or a
125
+ * negative value is unusable, and the caller falls back to the backoff.
126
+ */
127
+ export declare function parseRetryAfter(value: string | null | undefined): number | null;
128
+ /** Build the error for a non-2xx answer, mapped by status first and reason_code second. */
129
+ export declare function errorFromResponse(status: number, headers: Record<string, string>, text: string, idempotencyKey: string | null): APIError;