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,305 @@
1
+ "use strict";
2
+ // The errors the SDK throws (sdks/CONTRACT.md, Errors).
3
+ //
4
+ // An error holds plain values only: the status, a copy of the response headers and the
5
+ // parsed body. It never holds a Request, a Response or the error fetch threw, so the
6
+ // `Authorization` header cannot reach a message, `util.inspect` or `JSON.stringify`.
7
+ //
8
+ // The package ships an ES module build and a CommonJS build, and a process that loads
9
+ // both holds two copies of every class here. So that `instanceof` still works across the
10
+ // copies, each class's prototype carries its name under a key in the global symbol
11
+ // registry, and `instanceof` falls back to matching that name along the prototype chain.
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.DETAIL_TEXT_LIMIT = exports.ServiceUnavailableError = exports.InternalServerError = exports.QuotaExceededError = exports.RateLimitError = exports.UnprocessableEntityError = exports.PayloadTooLargeError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIError = exports.APITimeoutError = exports.APIConnectionError = exports.ResponseValidationError = exports.WaitTimeoutError = exports.ConfigurationError = exports.NenaviError = void 0;
14
+ exports.parseRetryAfter = parseRetryAfter;
15
+ exports.errorFromResponse = errorFromResponse;
16
+ /**
17
+ * The key, shared by every copy of the package, under which a prototype names its class.
18
+ *
19
+ * Copies of different versions match each other by this key and the class name alone, so
20
+ * the key is a contract between versions. A release that changes an error class's fields
21
+ * incompatibly must change the key (for example to `nenavi.error.class.v2`), so that its
22
+ * errors stop matching older copies' classes instead of narrowing to the old shape.
23
+ */
24
+ const CLASS_NAME = Symbol.for('nenavi.error.class');
25
+ /** Base class of every error the SDK throws. */
26
+ class NenaviError extends Error {
27
+ /** The `Idempotency-Key` the call sent, or null when it sent none. */
28
+ idempotencyKey;
29
+ /**
30
+ * The last status a helper read before it threw: on `WaitTimeoutError`, and on the
31
+ * error of a poll that failed inside `reingest.run()`, where it holds the run's
32
+ * `run_id`. Null on other errors.
33
+ */
34
+ lastStatus;
35
+ constructor(message, options = {}) {
36
+ super(message);
37
+ this.idempotencyKey = options.idempotencyKey ?? null;
38
+ this.lastStatus = options.lastStatus ?? null;
39
+ }
40
+ }
41
+ exports.NenaviError = NenaviError;
42
+ // The ordinary check comes first. Failing that, a class of this package matches a value
43
+ // whose prototype chain holds a prototype marked with the same class name, as the other
44
+ // copy's classes are. A subclass written outside the package keeps the ordinary check.
45
+ //
46
+ // This is defined as a property rather than written as a static method, because a loose
47
+ // class transform in a consumer's build turns a static method into an assignment, and
48
+ // assigning over the read-only `Function.prototype[Symbol.hasInstance]` throws.
49
+ Object.defineProperty(NenaviError, Symbol.hasInstance, {
50
+ value: function hasInstance(value) {
51
+ if (Function.prototype[Symbol.hasInstance].call(this, value))
52
+ return true;
53
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null) {
54
+ return false;
55
+ }
56
+ const prototype = this.prototype;
57
+ if (typeof prototype !== 'object' || prototype === null)
58
+ return false;
59
+ if (!Object.hasOwn(prototype, CLASS_NAME))
60
+ return false;
61
+ const name = prototype[CLASS_NAME];
62
+ for (let link = Object.getPrototypeOf(value); link !== null; link = Object.getPrototypeOf(link)) {
63
+ if (Object.hasOwn(link, CLASS_NAME) &&
64
+ link[CLASS_NAME] === name) {
65
+ return true;
66
+ }
67
+ }
68
+ return false;
69
+ },
70
+ writable: true,
71
+ enumerable: false,
72
+ configurable: true,
73
+ });
74
+ /** No key for an operation that needs one, or an invalid option. */
75
+ class ConfigurationError extends NenaviError {
76
+ }
77
+ exports.ConfigurationError = ConfigurationError;
78
+ /** A helper ran out of time before the work it waited for finished. */
79
+ class WaitTimeoutError extends NenaviError {
80
+ }
81
+ exports.WaitTimeoutError = WaitTimeoutError;
82
+ /**
83
+ * A 2xx response whose body does not match the shape the operation answers with.
84
+ *
85
+ * The call may have taken effect: a `store` or `ingest` that throws this has usually
86
+ * stored the memory, so read `body` (for example its `event_id`) before calling again.
87
+ * It is not an `APIError`, because the service did not refuse the call.
88
+ */
89
+ class ResponseValidationError extends NenaviError {
90
+ /** The HTTP status. */
91
+ status;
92
+ /** The response's `X-Request-ID` header, or null. */
93
+ requestId;
94
+ /** The response headers, with names in lower case. */
95
+ headers;
96
+ /** The parsed body, the first 500 characters of its text when it is not JSON, or null when empty. */
97
+ body;
98
+ constructor(message, options) {
99
+ super(message, options);
100
+ this.status = options.status;
101
+ this.requestId = options.requestId;
102
+ this.headers = { ...options.headers };
103
+ this.body = options.body;
104
+ }
105
+ }
106
+ exports.ResponseValidationError = ResponseValidationError;
107
+ /** No response: DNS failure, connection refused or reset, or a TLS error. */
108
+ class APIConnectionError extends NenaviError {
109
+ }
110
+ exports.APIConnectionError = APIConnectionError;
111
+ /** No response within the timeout. */
112
+ class APITimeoutError extends APIConnectionError {
113
+ }
114
+ exports.APITimeoutError = APITimeoutError;
115
+ /** The service answered with a status other than 2xx. */
116
+ class APIError extends NenaviError {
117
+ /** The HTTP status. */
118
+ status;
119
+ /** The body's `reason_code` when it is a string, else null (engine errors have none). */
120
+ reasonCode;
121
+ /** The body's `detail` as it was sent, or the first 500 characters of a text body. */
122
+ detail;
123
+ /** The response's `X-Request-ID` header, or null. */
124
+ requestId;
125
+ /** The response headers, with names in lower case. */
126
+ headers;
127
+ /** The parsed body, or its text when it is not JSON. */
128
+ body;
129
+ constructor(message, options) {
130
+ super(message, options);
131
+ this.status = options.status;
132
+ this.reasonCode = options.reasonCode;
133
+ this.detail = options.detail;
134
+ this.requestId = options.requestId;
135
+ this.headers = { ...options.headers };
136
+ this.body = options.body;
137
+ }
138
+ }
139
+ exports.APIError = APIError;
140
+ /** 400. */
141
+ class BadRequestError extends APIError {
142
+ }
143
+ exports.BadRequestError = BadRequestError;
144
+ /** 401: the key is missing, invalid or revoked, or its project was deleted. */
145
+ class AuthenticationError extends APIError {
146
+ }
147
+ exports.AuthenticationError = AuthenticationError;
148
+ /** 403. */
149
+ class PermissionDeniedError extends APIError {
150
+ }
151
+ exports.PermissionDeniedError = PermissionDeniedError;
152
+ /** 404. */
153
+ class NotFoundError extends APIError {
154
+ }
155
+ exports.NotFoundError = NotFoundError;
156
+ /** 409, for example `reingest_running`. */
157
+ class ConflictError extends APIError {
158
+ }
159
+ exports.ConflictError = ConflictError;
160
+ /** 413. */
161
+ class PayloadTooLargeError extends APIError {
162
+ }
163
+ exports.PayloadTooLargeError = PayloadTooLargeError;
164
+ /** 422: a refused value, or a request validation error. */
165
+ class UnprocessableEntityError extends APIError {
166
+ }
167
+ exports.UnprocessableEntityError = UnprocessableEntityError;
168
+ /** 429 `rate_limited`. `retryAfter` is the `Retry-After` header in seconds, or null. */
169
+ class RateLimitError extends APIError {
170
+ retryAfter;
171
+ constructor(message, options) {
172
+ super(message, options);
173
+ this.retryAfter = options.retryAfter;
174
+ }
175
+ }
176
+ exports.RateLimitError = RateLimitError;
177
+ /** 429 for a monthly limit, the node cap or any other `reason_code`: never retried. */
178
+ class QuotaExceededError extends APIError {
179
+ }
180
+ exports.QuotaExceededError = QuotaExceededError;
181
+ /** 500 to 599, except 503. */
182
+ class InternalServerError extends APIError {
183
+ }
184
+ exports.InternalServerError = InternalServerError;
185
+ /** 503. */
186
+ class ServiceUnavailableError extends APIError {
187
+ }
188
+ exports.ServiceUnavailableError = ServiceUnavailableError;
189
+ // Each class's name, written out so that `error.name` survives a minifier that renames
190
+ // classes. It sits on the prototype, so it is not an own property of an error. The same
191
+ // name marks the prototype under CLASS_NAME for the cross-copy `instanceof` above.
192
+ const NAMES = [
193
+ [NenaviError, 'NenaviError'],
194
+ [ConfigurationError, 'ConfigurationError'],
195
+ [WaitTimeoutError, 'WaitTimeoutError'],
196
+ [ResponseValidationError, 'ResponseValidationError'],
197
+ [APIConnectionError, 'APIConnectionError'],
198
+ [APITimeoutError, 'APITimeoutError'],
199
+ [APIError, 'APIError'],
200
+ [BadRequestError, 'BadRequestError'],
201
+ [AuthenticationError, 'AuthenticationError'],
202
+ [PermissionDeniedError, 'PermissionDeniedError'],
203
+ [NotFoundError, 'NotFoundError'],
204
+ [ConflictError, 'ConflictError'],
205
+ [PayloadTooLargeError, 'PayloadTooLargeError'],
206
+ [UnprocessableEntityError, 'UnprocessableEntityError'],
207
+ [RateLimitError, 'RateLimitError'],
208
+ [QuotaExceededError, 'QuotaExceededError'],
209
+ [InternalServerError, 'InternalServerError'],
210
+ [ServiceUnavailableError, 'ServiceUnavailableError'],
211
+ ];
212
+ for (const [ErrorClass, name] of NAMES) {
213
+ Object.defineProperty(ErrorClass.prototype, 'name', {
214
+ value: name,
215
+ writable: true,
216
+ enumerable: false,
217
+ configurable: true,
218
+ });
219
+ Object.defineProperty(ErrorClass.prototype, CLASS_NAME, {
220
+ value: name,
221
+ writable: false,
222
+ enumerable: false,
223
+ configurable: false,
224
+ });
225
+ }
226
+ const BY_STATUS = {
227
+ 400: BadRequestError,
228
+ 401: AuthenticationError,
229
+ 403: PermissionDeniedError,
230
+ 404: NotFoundError,
231
+ 409: ConflictError,
232
+ 413: PayloadTooLargeError,
233
+ 422: UnprocessableEntityError,
234
+ 503: ServiceUnavailableError,
235
+ };
236
+ exports.DETAIL_TEXT_LIMIT = 500;
237
+ /**
238
+ * Return a `Retry-After` header as whole seconds, or null when it is unusable.
239
+ *
240
+ * Only a whole, non-negative number of seconds counts. An HTTP date, a fraction or a
241
+ * negative value is unusable, and the caller falls back to the backoff.
242
+ */
243
+ function parseRetryAfter(value) {
244
+ if (value == null)
245
+ return null;
246
+ const text = value.trim();
247
+ if (!/^[0-9]{1,15}$/.test(text))
248
+ return null;
249
+ return Number(text);
250
+ }
251
+ /** Build the error for a non-2xx answer, mapped by status first and reason_code second. */
252
+ function errorFromResponse(status, headers, text, idempotencyKey) {
253
+ let body = null;
254
+ let parsed = true;
255
+ if (text) {
256
+ try {
257
+ body = JSON.parse(text);
258
+ }
259
+ catch {
260
+ body = text.slice(0, exports.DETAIL_TEXT_LIMIT);
261
+ parsed = false;
262
+ }
263
+ }
264
+ let reasonCode = null;
265
+ let detail = null;
266
+ if (parsed && typeof body === 'object' && body !== null && !Array.isArray(body)) {
267
+ const fields = body;
268
+ reasonCode = typeof fields.reason_code === 'string' ? fields.reason_code : null;
269
+ detail = fields.detail ?? null;
270
+ }
271
+ else if (!parsed) {
272
+ detail = body;
273
+ }
274
+ const message = reasonCode
275
+ ? `${status} ${reasonCode}: ${detailText(detail)}`
276
+ : `${status}: ${detailText(detail)}`;
277
+ const options = {
278
+ status,
279
+ reasonCode,
280
+ detail,
281
+ requestId: headers['x-request-id'] ?? null,
282
+ headers,
283
+ body,
284
+ idempotencyKey,
285
+ };
286
+ if (status === 429) {
287
+ if (reasonCode === 'rate_limited') {
288
+ return new RateLimitError(message, {
289
+ ...options,
290
+ retryAfter: parseRetryAfter(headers['retry-after']),
291
+ });
292
+ }
293
+ return new QuotaExceededError(message, options);
294
+ }
295
+ let ErrorClass = BY_STATUS[status];
296
+ if (ErrorClass === undefined && status >= 500 && status <= 599) {
297
+ ErrorClass = InternalServerError;
298
+ }
299
+ return new (ErrorClass ?? APIError)(message, options);
300
+ }
301
+ function detailText(detail) {
302
+ if (typeof detail === 'string')
303
+ return detail;
304
+ return JSON.stringify(detail) ?? 'null';
305
+ }