@mountaya/client 0.0.0-stage → 0.1.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.
Files changed (96) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +1260 -2
  5. package/dist/admin/index.cjs +3521 -0
  6. package/dist/admin/index.cjs.map +1 -0
  7. package/dist/admin/index.d.cts +1070 -0
  8. package/dist/admin/index.d.ts +1070 -0
  9. package/dist/admin/index.js +301 -0
  10. package/dist/admin/index.js.map +1 -0
  11. package/dist/browser.cjs +8073 -0
  12. package/dist/browser.cjs.map +1 -0
  13. package/dist/browser.d.cts +106 -0
  14. package/dist/browser.d.ts +106 -0
  15. package/dist/browser.js +53 -0
  16. package/dist/browser.js.map +1 -0
  17. package/dist/chunk-BM526BHG.js +342 -0
  18. package/dist/chunk-BM526BHG.js.map +1 -0
  19. package/dist/chunk-D2YEVTG7.js +327 -0
  20. package/dist/chunk-D2YEVTG7.js.map +1 -0
  21. package/dist/chunk-OHKVUREN.js +3500 -0
  22. package/dist/chunk-OHKVUREN.js.map +1 -0
  23. package/dist/chunk-TDTK2L5H.js +3842 -0
  24. package/dist/chunk-TDTK2L5H.js.map +1 -0
  25. package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
  26. package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
  27. package/dist/errors-B-GqAtQv.d.cts +75960 -0
  28. package/dist/errors-B-GqAtQv.d.ts +75960 -0
  29. package/dist/events/index.cjs +1972 -0
  30. package/dist/events/index.cjs.map +1 -0
  31. package/dist/events/index.d.cts +781 -0
  32. package/dist/events/index.d.ts +781 -0
  33. package/dist/events/index.js +826 -0
  34. package/dist/events/index.js.map +1 -0
  35. package/dist/index.cjs +8072 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +76 -0
  38. package/dist/index.d.ts +76 -0
  39. package/dist/index.js +52 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
  42. package/dist/operations.gen-DUD406TV.d.ts +3993 -0
  43. package/package.json +127 -4
  44. package/src/admin/index.ts +47 -0
  45. package/src/admin/rules/mountayaAdmin.ts +102 -0
  46. package/src/browser.ts +232 -0
  47. package/src/core/engines/sessionToken.ts +870 -0
  48. package/src/core/rules/auth.ts +1017 -0
  49. package/src/core/rules/clientHeader.ts +28 -0
  50. package/src/core/rules/dates.ts +200 -0
  51. package/src/core/rules/decode.ts +154 -0
  52. package/src/core/rules/envelope.ts +41 -0
  53. package/src/core/rules/errors.ts +1486 -0
  54. package/src/core/rules/graphql.ts +576 -0
  55. package/src/core/rules/headerValue.ts +42 -0
  56. package/src/core/rules/idempotencyKey.ts +64 -0
  57. package/src/core/rules/nullMask.ts +127 -0
  58. package/src/core/rules/nullMasks.gen.ts +416 -0
  59. package/src/core/rules/paginate.ts +316 -0
  60. package/src/core/rules/rateLimit.ts +507 -0
  61. package/src/core/rules/redaction.ts +219 -0
  62. package/src/core/rules/resourceRef.ts +110 -0
  63. package/src/core/rules/responseBody.ts +492 -0
  64. package/src/core/rules/retry.ts +386 -0
  65. package/src/core/rules/selection.ts +416 -0
  66. package/src/core/rules/sessionAnswer.ts +90 -0
  67. package/src/core/rules/sessionSchedule.ts +131 -0
  68. package/src/core/rules/sessionWait.ts +112 -0
  69. package/src/core/rules/transport.ts +2386 -0
  70. package/src/core/rules/version.gen.ts +16 -0
  71. package/src/core/rules/webAddress.ts +165 -0
  72. package/src/core/rules/webAddresses.gen.ts +30 -0
  73. package/src/data/operations.gen.ts +603 -0
  74. package/src/data/schema.gen.ts +8078 -0
  75. package/src/data/selection.gen.ts +472 -0
  76. package/src/events/index.ts +67 -0
  77. package/src/events/rules/agent.ts +439 -0
  78. package/src/events/rules/collab.ts +554 -0
  79. package/src/events/rules/collabNulls.gen.ts +17 -0
  80. package/src/events/rules/eventStream.ts +94 -0
  81. package/src/events/rules/openSseStream.ts +594 -0
  82. package/src/events/rules/sse.ts +349 -0
  83. package/src/index.ts +231 -0
  84. package/src/rest/adminOperations.gen.ts +70 -0
  85. package/src/rest/adminResources.gen.ts +136 -0
  86. package/src/rest/coreOperations.gen.ts +74 -0
  87. package/src/rest/coreResources.gen.ts +244 -0
  88. package/src/rest/dates.gen.ts +217 -0
  89. package/src/rest/operations.gen.ts +4341 -0
  90. package/src/rest/resources.gen.ts +369 -0
  91. package/src/rest/schema.gen.ts +56840 -0
  92. package/src/tiles/operations.gen.ts +206 -0
  93. package/src/tiles/schema.gen.ts +8408 -0
  94. package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
  95. package/src/webhooks/rules/webhookEvent.ts +38 -0
  96. package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
@@ -0,0 +1,1486 @@
1
+ /**
2
+ * The Mountaya error model.
3
+ *
4
+ * Every non-2xx response carries the same envelope (`{ errors: [{ message, path?,
5
+ * extensions: { code } }] }`) across REST, the Tile API and the Data API, because the API
6
+ * renders one error into all three. This module turns that envelope into typed classes so a
7
+ * caller branches on a class or a code rather than on a status number.
8
+ *
9
+ * A 402 says something about the organization's agreement or its billing: a product the
10
+ * organization does not hold, an organization billed by card with no payment method on file, which
11
+ * the Data API refuses, or invoices still owed, which keep its Data API subscription from opening.
12
+ * Every 402 is one class here, carrying `PAYMENT_REQUIRED`, and each is answered by changing the
13
+ * agreement or the billing details, not in code.
14
+ *
15
+ * A 403 says what the caller may not do whatever the agreement holds: a scope its key lacks,
16
+ * another organization, a calling page the organization does not allow, or a member without the
17
+ * role. A limit or a monthly allowance that is spent is a 429, and so is a ceiling (the seats, the
18
+ * published itineraries or zones, the invitations waiting, the itineraries of a personal space),
19
+ * whose entry carries `LIMIT_REACHED` and which names no wait. Those three are routinely conflated
20
+ * and each wants a different response from a caller, so none of them shares a class with another.
21
+ *
22
+ * Every error the API answered names its request: the answer's `X-Request-Id`, the one thing a
23
+ * caller quotes to support, and the rate-limit state its headers describe.
24
+ */
25
+
26
+ import type { ErrorCode as DataErrorCode } from "../../data/schema.gen.js";
27
+ import type { HTTPError as RestErrorEntry } from "../../rest/schema.gen.js";
28
+ import type { HTTPError as TileErrorEntry } from "../../tiles/schema.gen.js";
29
+ import { parseRateLimit, type RateLimitInfo } from "./rateLimit.js";
30
+
31
+ /**
32
+ * ErrorCode is the canonical machine-readable code the API stamps on a failure: the closed
33
+ * vocabulary each surface declares for `extensions.code`, joined.
34
+ *
35
+ * **Derived, never listed.** Each surface's contract declares the codes it sends (the two REST
36
+ * bundles as the enum on their error entry, the Data API as its `ErrorCode` enum), and this is
37
+ * their union, read off the generated types, so a code the contract adds reaches a caller
38
+ * switching on this type the day the client is regenerated.
39
+ *
40
+ * It stays open, with `string & {}` beside the declared codes, so an unrecognized code from a
41
+ * newer API release widens to `string` instead of failing a parse (a client should never break
42
+ * because it met a code it has not been taught yet), while an editor still offers every
43
+ * declared one.
44
+ */
45
+ export type ErrorCode =
46
+ | RestErrorEntry["extensions"]["code"]
47
+ | TileErrorEntry["extensions"]["code"]
48
+ | DataErrorCode
49
+ | (string & {});
50
+
51
+ /**
52
+ * ErrorPath is the field an error entry is about, as the contract spells it: a path of names
53
+ * with numeric array indices (`["request", "body", "segments", 2, "geojson"]`).
54
+ *
55
+ * The index stays a number on the wire, so it stays a number here: coercing it to a string
56
+ * would discard the most specific thing the API can tell a caller about a rejected request.
57
+ * Read off the REST contract's own error entry, which is where the shape is declared; the Data
58
+ * API's SDL describes the same shape for its `extensions.path` in prose, because GraphQL has no
59
+ * way to type an error.
60
+ */
61
+ type ErrorPath = Readonly<NonNullable<RestErrorEntry["path"]>>;
62
+
63
+ /**
64
+ * ErrorEntry is one entry of the API's error envelope.
65
+ *
66
+ * The field the entry is about is carried in a different place per surface, and both are typed
67
+ * here so a caller reading a failure does not have to know which surface it came from to find
68
+ * them:
69
+ *
70
+ * - **REST and the Tile API** carry it on the entry itself, as `path`, from the root of the
71
+ * request: `["request", "body", "name"]`, `["request", "query", "limit"]`.
72
+ * - **The Data API** carries it under `extensions.path`, from the root of the operation's
73
+ * input: `["input", "waypoints", 0]`. The entry's own `path` there is GraphQL's, and names the
74
+ * response field that failed rather than the input that did.
75
+ */
76
+ export interface ErrorEntry {
77
+ /** The sentence the API wrote, in the client's `language` where the API localizes it. */
78
+ readonly message: string;
79
+ /**
80
+ * On REST and the Tile API, the request field the entry is about; on the Data API, GraphQL's
81
+ * own path to the response field that failed.
82
+ */
83
+ readonly path?: ErrorPath | undefined;
84
+ /** The machine-readable half of the entry: its code, and on the Data API its input field. */
85
+ readonly extensions?:
86
+ | {
87
+ /** The entry's code, which a caller switches on rather than on the message. */
88
+ readonly code?: ErrorCode | undefined;
89
+ /** On the Data API, the input field a validation failure is about. */
90
+ readonly path?: ErrorPath | undefined;
91
+ }
92
+ | undefined;
93
+ }
94
+
95
+ /**
96
+ * MountayaError is the base of every error this package throws. Catching it separates a
97
+ * platform failure from a bug in the calling program.
98
+ *
99
+ * **Every class in the family declares its `name` as a string literal**, and none of them
100
+ * reads it off the constructor. `this.name = new.target.name` is the obvious spelling and it
101
+ * is wrong in a published package: a class name is an identifier, and a consumer's minifier
102
+ * renames identifiers. Vite, Next and esbuild all ship production defaults that do, so
103
+ * `error.name === "MountayaNotFoundError"` holds in the consumer's development build, and in
104
+ * their production build the same error reports `name: "a"`. A literal is data, so it
105
+ * survives; and it is what makes `name` usable at all where `instanceof` is not, which is a
106
+ * real case rather than a hypothetical one: a package resolved once as ESM and once as CJS
107
+ * loads two class objects, and an error thrown from one fails `instanceof` against the other.
108
+ *
109
+ * `errors.test.ts` derives the check from the barrel, so a class added without a literal
110
+ * fails there rather than in a consumer's minified bundle.
111
+ */
112
+ export class MountayaError extends Error {
113
+ override readonly name: string = "MountayaError";
114
+
115
+ /**
116
+ * The `Idempotency-Key` the call that raised this error fixed for its attempts, the caller's own
117
+ * or the one the client drew for it, and undefined where it fixed none: a read, an operation
118
+ * that declares no key, a call whose own arguments were refused, and a runtime with no
119
+ * cryptographic random source. The key is fixed before the first attempt, so a call whose
120
+ * credential its first attempt refused, or whose wait for a first session token ran out,
121
+ * carries it too.
122
+ *
123
+ * A write that carried one may have been made whatever the error says: an answer that never
124
+ * arrived, a 5xx and a body that broke off do not tell. Send the same call again with this key
125
+ * as its `idempotencyKey`, never a new one: the API answers a key it has seen with the answer it
126
+ * kept, or runs the write where it made none, so the write is made once. A new key is a new
127
+ * write, made a second time where the first one landed.
128
+ */
129
+ readonly idempotencyKey?: string | undefined;
130
+
131
+ // The constructor narrows the signature rather than adding behaviour: `Error`'s `message`
132
+ // is optional and this family's is not. Dropping it makes
133
+ // `new MountayaConfigurationError()` compile, which is a thrown value carrying nothing a
134
+ // caller can read.
135
+ /**
136
+ * @param message - what went wrong and what to do about it, naming the call where there is one.
137
+ * @param options - the standard error options, for the `cause` behind it, and the
138
+ * `idempotencyKey` the call sent, where it sent one.
139
+ */
140
+ constructor(
141
+ message: string,
142
+ options?: (ErrorOptions & { readonly idempotencyKey?: string | undefined }) | undefined,
143
+ ) {
144
+ super(message, options);
145
+ this.idempotencyKey = options?.idempotencyKey;
146
+ }
147
+ }
148
+
149
+ /**
150
+ * MountayaConfigurationError is thrown when the client is set up in a way that cannot work, and
151
+ * before any request is made wherever that can be known: no credential (an empty or blank key
152
+ * included), a credential whose prefix does not match its slot, a secret key in a browser, or an
153
+ * option outside its range (a `timeoutMs`, a `retry` member, a `baseUrls` entry). A call refuses
154
+ * the same way, before its first attempt, when its credential cannot make it, it asks for
155
+ * `text/event-stream` (which the openers of `@mountaya/client/events` read), its own `retry` or
156
+ * `timeoutMs` is out of range, a header it names holds a character outside printable ASCII, or
157
+ * its body is one `JSON.stringify` refuses (a cycle, a `BigInt`) or holds a web address with no
158
+ * scheme where the operation's contract types one. An operation that requires a session is
159
+ * refused the same way once its wait for the first session token ends with none, with the mint's
160
+ * error as its `cause`. A stream open raises one once its answer arrives when the runtime's fetch
161
+ * exposes no response body to read the stream from, which only the response can show. A webhook
162
+ * delivery that verifies and holds no event raises one as well, carrying the parser's failure as
163
+ * its `cause` where the body is not JSON.
164
+ *
165
+ * It is deliberately not an `APIError`: the API refused nothing, so there is no status to report
166
+ * and no retry that could help.
167
+ */
168
+ export class MountayaConfigurationError extends MountayaError {
169
+ override readonly name = "MountayaConfigurationError";
170
+ }
171
+
172
+ /**
173
+ * describeType spells the type a refusal names a value by, with its article (`a string`,
174
+ * `an object`, `null`), for a value a refusal must never quote: a credential, or options that may
175
+ * hold one, since a key is a secret whatever type it arrived as.
176
+ */
177
+ export const describeType = (value: unknown): string => {
178
+ if (value === null || value === undefined) {
179
+ return String(value);
180
+ }
181
+
182
+ const type = Array.isArray(value) ? "array" : typeof value;
183
+
184
+ return /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
185
+ };
186
+
187
+ /**
188
+ * describeValue spells an option's value the way a refusal quotes it: a string in quotes, so an
189
+ * empty or padded one is visible, and anything else as `String` prints it. A value `String`
190
+ * cannot print (an object with no prototype, one whose `toString` throws) is named by its type,
191
+ * as {@link describeType} spells it, so the refusal is still the one that names the option.
192
+ */
193
+ const describeValue = (value: unknown): string => {
194
+ if (typeof value === "string") {
195
+ return JSON.stringify(value);
196
+ }
197
+
198
+ try {
199
+ return String(value);
200
+ } catch {
201
+ return describeType(value);
202
+ }
203
+ };
204
+
205
+ /**
206
+ * refuseOption builds the error an option outside its range throws: the option by the path a
207
+ * caller writes it at (`timeoutMs`, `retry.maxRetries`, `baseUrls.rest`), the value, and what to
208
+ * pass instead.
209
+ *
210
+ * `context` names the call a per-call option was passed to, and is omitted for a client's own
211
+ * options, which belong to no call.
212
+ */
213
+ export const refuseOption = (
214
+ path: string,
215
+ value: unknown,
216
+ remedy: string,
217
+ context?: string,
218
+ ): MountayaConfigurationError =>
219
+ new MountayaConfigurationError(
220
+ `${context === undefined ? "" : `${context}: `}${path} is ${describeValue(value)}; ${remedy}`,
221
+ );
222
+
223
+ /**
224
+ * MountayaConnectionError wraps a transport failure: DNS, TLS, a dropped socket, an attempt
225
+ * that had no response within its `timeoutMs` (the call's, or else the client's), a wait for
226
+ * the first session token that the mint did not answer within it, a stream open with no
227
+ * response within its bound, a stream that delivered nothing (not even the heartbeat comment
228
+ * the API writes to every live stream) for its stall window, a response whose body broke off
229
+ * before it was complete, or an ok answer to a stream open that carries no body, which is what
230
+ * something on the network path (a captive portal, a proxy) sends in the API's place. Its message
231
+ * names the call, and says which of those it was where the transport can tell. A success whose
232
+ * body is not JSON is none of them: an answer came, so it is the base {@link MountayaApiError}.
233
+ *
234
+ * A caller's own abort is not one: it rejects with the signal's own reason, never wrapped, or
235
+ * with an `AbortError` where the signal carries none.
236
+ *
237
+ * The original is carried on the standard `Error.cause` rather than on a field of our
238
+ * own, so every tool that already knows how to unwrap a chained error (Node's inspector,
239
+ * test reporters, error trackers) finds it without being taught about this package.
240
+ */
241
+ export class MountayaConnectionError extends MountayaError {
242
+ override readonly name = "MountayaConnectionError";
243
+
244
+ /**
245
+ * @param message - the call, and which transport failure it met where the transport can tell.
246
+ * @param cause - the runtime's own failure, carried on `Error.cause`.
247
+ * @param idempotencyKey - the `Idempotency-Key` the call sent, where it sent one.
248
+ */
249
+ constructor(message: string, cause?: unknown, idempotencyKey?: string | undefined) {
250
+ super(message, { cause, idempotencyKey });
251
+ }
252
+ }
253
+
254
+ /**
255
+ * ErrorMetadata is the envelope's `extensions.metadata`: what a failure says about the state
256
+ * that refused it, in the shape the operation's own contract declares.
257
+ *
258
+ * It is what tells apart two answers that share a status and a code. A `409` refused by a held
259
+ * lock names the member holding it at `holder.id` (`RestSchema.ResponseMetadataLockConflict`),
260
+ * a `409` refused because another write landed first carries none, and a name conflict names the
261
+ * resource holding the name. Typed as a record of unknown values rather than as one of those
262
+ * shapes, because which shape a failure carries is the operation's to declare: a caller narrows
263
+ * it against the operation's schema, reading each member before trusting it.
264
+ */
265
+ export interface ErrorMetadata {
266
+ readonly [member: string]: unknown;
267
+ }
268
+
269
+ /**
270
+ * ApiErrorDetails is what an error the API answered carries beside its status and its entries,
271
+ * each where the answer sent it: what {@link errorForStatus} and the constructors of the family
272
+ * take fourth.
273
+ */
274
+ export interface ApiErrorDetails {
275
+ /**
276
+ * What kept the answer from being read, carried on the standard `Error.cause`: the parser's
277
+ * failure for a success whose body is not JSON.
278
+ */
279
+ readonly cause?: unknown;
280
+ /**
281
+ * The answer's `ETag`, exactly as sent: the tag the resource carries now, which a
282
+ * {@link MountayaPreconditionFailedError} carries and every other class leaves out.
283
+ */
284
+ readonly etag?: string | undefined;
285
+ /** The `Idempotency-Key` the call sent, where it sent one: see {@link MountayaError}. */
286
+ readonly idempotencyKey?: string | undefined;
287
+ /** The envelope's `extensions.metadata`, exactly as sent: see {@link ErrorMetadata}. */
288
+ readonly metadata?: ErrorMetadata | undefined;
289
+ /** The rate-limit state the answer's `RateLimit-Policy` and `RateLimit` describe. */
290
+ readonly rateLimit?: RateLimitInfo | undefined;
291
+ /** The answer's `X-Request-Id`, exactly as sent. */
292
+ readonly requestId?: string | undefined;
293
+ /** The whole seconds the answer's `Retry-After` names, where it sent one it can read. */
294
+ readonly retryAfter?: number | undefined;
295
+ }
296
+
297
+ /**
298
+ * MountayaApiError is any error the API itself reported, carrying the HTTP status, the parsed
299
+ * envelope entries, the envelope's metadata where it sent any, the answer's request id, the
300
+ * rate-limit state it describes and the wait its `Retry-After` names.
301
+ *
302
+ * `code` is the first entry's code, which is the classification for the response as a
303
+ * whole; `errors` holds every entry for a caller that needs the field-level detail of a
304
+ * multi-error validation failure.
305
+ *
306
+ * A success whose body is not JSON raises this class itself, with no entry: an answer came, and
307
+ * no status of the ladder classifies it. It carries the answer's status and request id, with the
308
+ * parser's failure as its `cause`.
309
+ */
310
+ export class MountayaApiError extends MountayaError {
311
+ override readonly name: string = "MountayaApiError";
312
+
313
+ /** The HTTP status the response carried. */
314
+ readonly status: number;
315
+ /** Every entry of the envelope, in the order the API wrote them; empty for a bodiless answer. */
316
+ readonly errors: readonly ErrorEntry[];
317
+
318
+ /**
319
+ * The envelope's `extensions.metadata`, exactly as sent, or undefined where the response
320
+ * carried none: see {@link ErrorMetadata}.
321
+ */
322
+ readonly metadata?: ErrorMetadata | undefined;
323
+
324
+ /**
325
+ * The rate-limit state the answer's `RateLimit-Policy` and `RateLimit` describe, or undefined
326
+ * where they describe none, as on every Map Studio API answer.
327
+ */
328
+ readonly rateLimit?: RateLimitInfo | undefined;
329
+
330
+ /**
331
+ * The answer's `X-Request-Id`, exactly as sent: 32 lowercase hex characters the API recorded
332
+ * the request under, and the one thing to quote to support. Undefined where the answer sent
333
+ * none; the client never makes one up.
334
+ */
335
+ readonly requestId?: string | undefined;
336
+
337
+ /**
338
+ * How many seconds the answer asked the caller to wait before asking again, from its
339
+ * `Retry-After` header, read as whole seconds or an HTTP date; undefined where the header was
340
+ * absent or neither.
341
+ *
342
+ * Every 429 of a limit names one, the wait a spent limit asks for
343
+ * ({@link MountayaRateLimitError}); a ceiling's 429, coded `LIMIT_REACHED`, names none, since no
344
+ * wait lifts it. A 503 names one where the API knows when it can answer, and a 409 whose
345
+ * `Idempotency-Key` is still in use names the second the first request may take. The client waits each out itself where it
346
+ * repeats the call and the wait fits its `retry.maxWaitMs`; an error that arrives carrying one
347
+ * is the wait a caller schedules the next call from, and one carrying none says nothing of when.
348
+ */
349
+ readonly retryAfter?: number | undefined;
350
+
351
+ /**
352
+ * @param message - the message {@link failureMessage} spells for the call.
353
+ * @param status - the HTTP status the response carried.
354
+ * @param errors - the envelope's entries, the first of which classifies the response.
355
+ * @param details - the envelope's metadata, the request id, the rate-limit state and the wait
356
+ * `Retry-After` names, where the answer sent them, the `Idempotency-Key` the call sent,
357
+ * where it sent one, and the `cause` that kept the answer from being read, where one did.
358
+ */
359
+ constructor(
360
+ message: string,
361
+ status: number,
362
+ errors: readonly ErrorEntry[],
363
+ details: ApiErrorDetails = {},
364
+ ) {
365
+ // A `cause` is set where there is one and never as `undefined`, which the standard options
366
+ // would install as a property of its own.
367
+ super(
368
+ message,
369
+ details.cause === undefined
370
+ ? { idempotencyKey: details.idempotencyKey }
371
+ : { cause: details.cause, idempotencyKey: details.idempotencyKey },
372
+ );
373
+ this.status = status;
374
+ this.errors = errors;
375
+ this.metadata = details.metadata;
376
+ this.rateLimit = details.rateLimit;
377
+ this.requestId = details.requestId;
378
+ this.retryAfter = details.retryAfter;
379
+ }
380
+
381
+ /** The classifying code of the response, taken from its first entry. */
382
+ get code(): ErrorCode | undefined {
383
+ return this.errors[0]?.extensions?.code;
384
+ }
385
+
386
+ /** Reports whether any entry carries the given code. */
387
+ hasCode(code: ErrorCode): boolean {
388
+ return this.errors.some((entry) => entry.extensions?.code === code);
389
+ }
390
+ }
391
+
392
+ /** 400: the request was malformed or a field failed validation. */
393
+ export class MountayaBadRequestError extends MountayaApiError {
394
+ override readonly name = "MountayaBadRequestError";
395
+ }
396
+
397
+ /**
398
+ * 401: the credential is missing, malformed, unknown, rotated or disabled. A session token that
399
+ * expired, or was minted for another key, is one, and so is a call to an operation that acts as
400
+ * the user its session token names, under a token minted without `user_id`, which gives the call
401
+ * no user to act as. A call to a `studio-embedded` operation under a token minted for another
402
+ * surface than `studio-embedded` is one too.
403
+ */
404
+ export class MountayaAuthenticationError extends MountayaApiError {
405
+ override readonly name = "MountayaAuthenticationError";
406
+ }
407
+
408
+ /**
409
+ * 402: the organization does not hold the product the call needs, such as Map Studio for a write
410
+ * into one of its itineraries; or, on the Data API, a self-serve organization has no payment
411
+ * method on file, or still owes invoices its payment method could not pay, which keep a
412
+ * subscription from opening. The message names which, in the API's words: a product of the
413
+ * agreement is changed with Mountaya (https://mountaya.com/en/contact/), and a payment method is
414
+ * added, and what is owed paid, in the organization's billing settings.
415
+ *
416
+ * Its entry carries `PAYMENT_REQUIRED`. A call past a ceiling of the agreement, such as its seats
417
+ * or its published itineraries, is a {@link MountayaRateLimitError} coded `LIMIT_REACHED` instead.
418
+ */
419
+ export class MountayaBillingError extends MountayaApiError {
420
+ override readonly name = "MountayaBillingError";
421
+ }
422
+
423
+ /**
424
+ * 403: the caller may not do this, whatever the organization's agreement holds. A scope its key
425
+ * does not carry, a resource outside its organization, or a page the organization does not allow
426
+ * to call. So is a call that acts as a member whose session token names a user without the role
427
+ * the call asks.
428
+ *
429
+ * A product the organization does not hold is a {@link MountayaBillingError} instead: the
430
+ * agreement is what answers it, where a 403 is answered by the key, the page or the member. A
431
+ * ceiling, such as the itineraries a personal space keeps, is a {@link MountayaRateLimitError}
432
+ * coded `LIMIT_REACHED`.
433
+ */
434
+ export class MountayaForbiddenError extends MountayaApiError {
435
+ override readonly name = "MountayaForbiddenError";
436
+ }
437
+
438
+ /** 404: no such resource, or none the caller is allowed to know exists. */
439
+ export class MountayaNotFoundError extends MountayaApiError {
440
+ override readonly name = "MountayaNotFoundError";
441
+ }
442
+
443
+ /**
444
+ * 405: the path exists and does not answer that method.
445
+ *
446
+ * Distinct from 404 because the remedy is: a 404 means the resource is wrong and a 405 means
447
+ * the verb is, and a caller that folded them together would retry a correct path with the same
448
+ * wrong method.
449
+ */
450
+ export class MountayaMethodNotAllowedError extends MountayaApiError {
451
+ override readonly name = "MountayaMethodNotAllowedError";
452
+ }
453
+
454
+ /**
455
+ * 409: the write conflicts with the current state of the resource: a lock another member holds,
456
+ * a write that landed first, a name already taken, or a state that forbids the act, as the shape
457
+ * of an itinerary's chain forbids deleting one of its interior segments.
458
+ *
459
+ * Two 409s answer the `Idempotency-Key` a write carried rather than the write itself, and each
460
+ * raises a subclass of this class: {@link MountayaIdempotencyKeyInUseError}, whose first request
461
+ * is still running, and {@link MountayaIdempotentAnswerUnavailableError}, whose write was made.
462
+ */
463
+ export class MountayaConflictError extends MountayaApiError {
464
+ // Typed as a string rather than as its literal, so each subclass can declare its own.
465
+ override readonly name: string = "MountayaConflictError";
466
+ }
467
+
468
+ /**
469
+ * KEY_IN_USE_CODE is the code of a 409 whose `Idempotency-Key` is still in use: the first request
470
+ * with that key has not finished.
471
+ */
472
+ export const KEY_IN_USE_CODE = "IDEMPOTENCY_KEY_IN_USE";
473
+
474
+ /**
475
+ * CEILING_CODE is the code of a 429 refusing a ceiling rather than a limit counted over a window,
476
+ * `LIMIT_REACHED`: it names no wait, and no wait lifts it, so the client never repeats it.
477
+ */
478
+ export const CEILING_CODE = "LIMIT_REACHED";
479
+
480
+ /**
481
+ * MountayaIdempotencyKeyInUseError is the 409 whose first entry is coded `IDEMPOTENCY_KEY_IN_USE`:
482
+ * **the first request with this key is still running; send the same call again with the same
483
+ * key.**
484
+ *
485
+ * The client asks again itself, with the same key, after the second the answer names, for as long
486
+ * as the call's `retry.maxWaitMs` lasts, and raises this once that budget is spent with the first
487
+ * request still running. Its `idempotencyKey` is the key: send the same call again with it as the
488
+ * call's `idempotencyKey`, and the API answers with whatever the first request is answered with.
489
+ * Never send it with a new key, which is a second write, made beside the first.
490
+ *
491
+ * A {@link MountayaConflictError} by its status, so a caller handling every 409 alike still meets
492
+ * it, and a class of its own so that one handling a conflict can tell a write still running from
493
+ * one that was refused.
494
+ */
495
+ export class MountayaIdempotencyKeyInUseError extends MountayaConflictError {
496
+ override readonly name = "MountayaIdempotencyKeyInUseError";
497
+ }
498
+
499
+ /**
500
+ * IDEMPOTENT_ANSWER_UNAVAILABLE_CODE is the code of the 409 a repeat of an `Idempotency-Key` is
501
+ * answered with when the write it carried was made and the first answer to it cannot be given
502
+ * again, for one of three reasons: too large for the API to keep whole, a 5xx the API answered
503
+ * after the write, or an answer carrying a credential shown only once, which is never kept.
504
+ */
505
+ export const IDEMPOTENT_ANSWER_UNAVAILABLE_CODE = "IDEMPOTENCY_ANSWER_UNAVAILABLE";
506
+
507
+ /**
508
+ * IdempotentAnswer is what the 409 coded `IDEMPOTENCY_ANSWER_UNAVAILABLE` says of the answer the
509
+ * write was first given, read off its `extensions.metadata` member by member: each is undefined
510
+ * where the metadata does not state it in the type the contract declares.
511
+ */
512
+ export interface IdempotentAnswer {
513
+ /**
514
+ * The status the write was first answered with: `201` for a write that created something,
515
+ * `200` for one that changed it, the 2xx of an answer carrying a credential shown only once,
516
+ * or the 5xx a request failed with after its write was made.
517
+ */
518
+ readonly status?: number | undefined;
519
+ /**
520
+ * The path of what the write created, relative to the API's host: the `Location` its `201`
521
+ * carried, or, for a create whose operation says so (`postOrganization`,
522
+ * `postOrganizationInvitation`), the path of what it made when the request failed with a 5xx
523
+ * once that was made. Undefined on every other answer.
524
+ */
525
+ readonly location?: string | undefined;
526
+ /** The `ETag` that answer carried, the version of the resource the write left. */
527
+ readonly etag?: string | undefined;
528
+ }
529
+
530
+ /**
531
+ * MountayaIdempotentAnswerUnavailableError is the 409 whose first entry is coded
532
+ * `IDEMPOTENCY_ANSWER_UNAVAILABLE`: **the write was made; re-read the resource.**
533
+ *
534
+ * The call repeated an `Idempotency-Key` (the client's own retry after a lost answer, or the
535
+ * caller's) whose first request made its write, and the answer to that request cannot be given
536
+ * again, for one of three reasons: it was too large for the API to keep whole, the request failed
537
+ * with a 5xx after the write was made, which `answer.status` then names, or the answer carried a
538
+ * credential shown only once, which the API never keeps. Every repeat of the key is refused the
539
+ * same way, so the client never retries this one, and sending the write again with a new key
540
+ * would make it twice. Read the resource instead: at `answer.location` where the write created
541
+ * one, and with `answer.etag` as the `ifMatch` of the next write once it has been read. A
542
+ * credential that cannot be shown again is revoked rather than created a second time beside it.
543
+ *
544
+ * A {@link MountayaConflictError} by its status, so a caller handling every 409 alike still meets
545
+ * it, and a class of its own so that one handling a conflict can tell a write that was made from
546
+ * one that was refused.
547
+ */
548
+ export class MountayaIdempotentAnswerUnavailableError extends MountayaConflictError {
549
+ override readonly name = "MountayaIdempotentAnswerUnavailableError";
550
+
551
+ /** What the write's first answer was, as the metadata states it: see {@link IdempotentAnswer}. */
552
+ readonly answer: IdempotentAnswer;
553
+
554
+ /**
555
+ * @param message - the message {@link failureMessage} spells for the call.
556
+ * @param status - the HTTP status the response carried, which is 409.
557
+ * @param errors - the envelope's entries, the first of which is coded
558
+ * `IDEMPOTENCY_ANSWER_UNAVAILABLE`.
559
+ * @param details - what the answer sent beside them, the first answer at `metadata` included.
560
+ */
561
+ constructor(
562
+ message: string,
563
+ status: number,
564
+ errors: readonly ErrorEntry[],
565
+ details: ApiErrorDetails = {},
566
+ ) {
567
+ super(message, status, errors, details);
568
+
569
+ // Each member read for itself and kept only in the type the contract declares it in, so a
570
+ // metadata object the API did not write reads as the members it does state.
571
+ const { etag: taggedAs, location: createdAt, status: answeredWith } = details.metadata ?? {};
572
+ this.answer = {
573
+ etag: typeof taggedAs === "string" ? taggedAs : undefined,
574
+ location: typeof createdAt === "string" ? createdAt : undefined,
575
+ status:
576
+ typeof answeredWith === "number" && Number.isInteger(answeredWith)
577
+ ? answeredWith
578
+ : undefined,
579
+ };
580
+ }
581
+ }
582
+
583
+ /**
584
+ * 412: a conditional write whose `ifMatch` names a tag the resource no longer carries. Somebody
585
+ * changed it since it was read, and nothing was written. It is never repeated: read the resource
586
+ * again, and decide what the write should be now.
587
+ */
588
+ export class MountayaPreconditionFailedError extends MountayaApiError {
589
+ override readonly name = "MountayaPreconditionFailedError";
590
+
591
+ /**
592
+ * The tag the resource carries now, from the 412's `ETag`, exactly as sent, or undefined where
593
+ * the answer carried none. It is what the resource was changed to, not what the caller has read:
594
+ * read the resource again before a write names it as its `ifMatch`, so the write is decided
595
+ * against what it holds.
596
+ */
597
+ readonly etag?: string | undefined;
598
+
599
+ /**
600
+ * @param message - the message {@link failureMessage} spells for the call.
601
+ * @param status - the HTTP status the response carried, which is 412.
602
+ * @param errors - the envelope's entries, the first of which classifies the response.
603
+ * @param details - what the answer sent beside them, its `ETag` included.
604
+ */
605
+ constructor(
606
+ message: string,
607
+ status: number,
608
+ errors: readonly ErrorEntry[],
609
+ details: ApiErrorDetails = {},
610
+ ) {
611
+ super(message, status, errors, details);
612
+ this.etag = details.etag;
613
+ }
614
+ }
615
+
616
+ /** 413: the request body exceeds the accepted size. */
617
+ export class MountayaPayloadTooLargeError extends MountayaApiError {
618
+ override readonly name = "MountayaPayloadTooLargeError";
619
+ }
620
+
621
+ /**
622
+ * 429: a limit is spent, or a ceiling is reached. A limit is a per-minute limit of the Tile or
623
+ * Data API, a monthly allowance there, one of the Map Studio API's own limits (a key's reads,
624
+ * imports and previews, routed writes, agent runs, collaboration signals, stream opens,
625
+ * invitations, `postSession`, `postOrganizationLookup`), or the signed download URL an export
626
+ * answers with. A ceiling is the seats, the published itineraries or the published zones an
627
+ * agreement allows, the invitations an organization may have waiting at once, or the itineraries
628
+ * a personal space keeps.
629
+ *
630
+ * `retryAfter` is seconds, from the `Retry-After` a limit's 429 carries, the client's own retries
631
+ * waiting it out where it fits the call's `retry.maxWaitMs`. A per-minute limit names the
632
+ * seconds left in its minute, which the client waits out within its budget before it asks again.
633
+ * A spent monthly allowance names the seconds until the organization's next billing period
634
+ * begins, a wait past any budget, so the error arrives at once and carries it. Each surface's
635
+ * limits are its own, so a caller that hits this on one surface has learned nothing about its
636
+ * headroom on another.
637
+ *
638
+ * A ceiling is told apart by its code: its entry carries `LIMIT_REACHED`, which
639
+ * `hasCode("LIMIT_REACHED")` reads, and `metadata` names the ceiling with what it allows and what
640
+ * is held (`{ limit, allowed, used }`). It names no wait, so `retryAfter` is undefined, and the
641
+ * client never repeats it: it lifts when something is freed or the agreement changes.
642
+ */
643
+ export class MountayaRateLimitError extends MountayaApiError {
644
+ override readonly name = "MountayaRateLimitError";
645
+ }
646
+
647
+ /** 5xx: the API failed. These carry no server detail, by design. */
648
+ export class MountayaServerError extends MountayaApiError {
649
+ override readonly name = "MountayaServerError";
650
+ }
651
+
652
+ /**
653
+ * MountayaDataError is a Data API failure the API reported in a GraphQL envelope carried by a
654
+ * SUCCESS: a 200 whose `errors` say the operation did not happen, or one with no data at all.
655
+ *
656
+ * It is the one member of this family named for a TRANSPORT rather than for a status, which
657
+ * is why it sits after the status ladder instead of inside it. A Data API failure answered with
658
+ * a non-2xx status is NOT this class: it climbs the same ladder a REST failure does, so a 401 is
659
+ * a {@link MountayaAuthenticationError}, a 402 a {@link MountayaBillingError}, a 429 a
660
+ * {@link MountayaRateLimitError} and a 5xx a {@link MountayaServerError}, carrying the
661
+ * envelope's entries. A caller handling the ladder handles both surfaces. This class is what is
662
+ * left: GraphQL puts a field's failure in the body of a 200, which no status can classify. It
663
+ * subclasses {@link MountayaApiError} because the envelope entries are the same
664
+ * `{message, path, extensions.code}` the REST surface uses (the API renders one error into
665
+ * both), so a caller that already handles `MountayaApiError` handles this too.
666
+ */
667
+ export class MountayaDataError extends MountayaApiError {
668
+ override readonly name = "MountayaDataError";
669
+ }
670
+
671
+ /**
672
+ * MOUNTAYA_API_ERROR_NAMES holds the name each failure the API answered declares:
673
+ * {@link MountayaApiError}'s, and that of each class a status or a Data API envelope maps to.
674
+ */
675
+ export const MOUNTAYA_API_ERROR_NAMES: readonly string[] = [
676
+ "MountayaApiError",
677
+ "MountayaAuthenticationError",
678
+ "MountayaBadRequestError",
679
+ "MountayaBillingError",
680
+ "MountayaConflictError",
681
+ "MountayaDataError",
682
+ "MountayaForbiddenError",
683
+ "MountayaIdempotencyKeyInUseError",
684
+ "MountayaIdempotentAnswerUnavailableError",
685
+ "MountayaMethodNotAllowedError",
686
+ "MountayaNotFoundError",
687
+ "MountayaPayloadTooLargeError",
688
+ "MountayaPreconditionFailedError",
689
+ "MountayaRateLimitError",
690
+ "MountayaServerError",
691
+ ];
692
+
693
+ /**
694
+ * MOUNTAYA_ERROR_NAMES holds the name each error of the family declares: the failures the API
695
+ * answered, and those no answer came with, the event-stream parser's and the webhook
696
+ * verification's among them.
697
+ *
698
+ * Spelled as each class declares its name, the `Mountaya` prefix included and
699
+ * `SseBufferOverflowError` without one, because a thrown value carries that spelling and no other.
700
+ * `errors.test.ts` derives the family from the published barrels and holds this list to it in
701
+ * both directions.
702
+ */
703
+ export const MOUNTAYA_ERROR_NAMES: readonly string[] = [
704
+ ...MOUNTAYA_API_ERROR_NAMES,
705
+ "MountayaConfigurationError",
706
+ "MountayaConnectionError",
707
+ "MountayaError",
708
+ "MountayaSelectionError",
709
+ "MountayaWebhookSignatureError",
710
+ "SseBufferOverflowError",
711
+ ];
712
+
713
+ /**
714
+ * declaresName reports whether a value is an object whose `name`, read as data, is one of
715
+ * `names`. A class is refused, though its own `name` spells the class: it is not an error.
716
+ */
717
+ const declaresName = (
718
+ value: unknown,
719
+ names: readonly string[],
720
+ ): value is { readonly name: string } =>
721
+ typeof value === "object" &&
722
+ value !== null &&
723
+ "name" in value &&
724
+ typeof value.name === "string" &&
725
+ names.includes(value.name);
726
+
727
+ /**
728
+ * isMountayaError reports whether a value is an error of this family, read from the name its
729
+ * class declares rather than from its constructor.
730
+ *
731
+ * Structural, so an error thrown by a second copy of this package still classifies: a package
732
+ * resolved once as ESM and once as CJS, or installed twice, loads two class objects, and
733
+ * `instanceof` against one refuses every error the other throws. Each class in the family
734
+ * declares its name as a literal for this reading (see {@link MountayaError}). A value whose name
735
+ * is none of the family's is none of its errors, whatever status it carries.
736
+ *
737
+ * It answers for the whole family, a timeout and a refused configuration included, so what it
738
+ * narrows to is the base: narrow further with {@link isMountayaApiError} before reading `status`,
739
+ * `code` or `errors`.
740
+ *
741
+ * @example
742
+ * ```ts
743
+ * try {
744
+ * await mountaya.studio.itineraries.getItinerary({ itinerary_id });
745
+ * } catch (error) {
746
+ * if (!isMountayaError(error)) {
747
+ * throw error; // A defect in the calling program, not a failure of the call.
748
+ * }
749
+ * console.warn(error.message);
750
+ * }
751
+ * ```
752
+ */
753
+ export const isMountayaError = (error: unknown): error is MountayaError =>
754
+ declaresName(error, MOUNTAYA_ERROR_NAMES);
755
+
756
+ /**
757
+ * isMountayaApiError reports whether a value is a failure the API answered: an error of the
758
+ * family whose class a status maps to, carrying what that class carries, so that everything the
759
+ * narrowed type promises is there to read whichever copy of this package built it.
760
+ *
761
+ * Narrow with it before reading `status`, `code`, `errors` or `metadata`, or calling `hasCode`,
762
+ * none of which a timeout, a dropped connection or a refused configuration carries. Structural,
763
+ * for the reason {@link isMountayaError} gives: it reads the name the class declares, the numeric
764
+ * `status`, the `errors` array with each entry an object, and the `hasCode` method the class
765
+ * adds, and never the constructor.
766
+ *
767
+ * A value revived from JSON is refused. It holds the data and none of what the class adds: on it
768
+ * `code` reads `undefined` and `hasCode` is no function, so narrowing it to the class would be
769
+ * false. Read such a value as the plain data it is, through its `errors` member, and classify it
770
+ * by its `name` with {@link isMountayaError}, which promises the name alone.
771
+ *
772
+ * @example
773
+ * ```ts
774
+ * try {
775
+ * await mountaya.studio.itineraries.getItinerary({ itinerary_id });
776
+ * } catch (error) {
777
+ * if (isMountayaApiError(error) && error.hasCode("NOT_FOUND")) {
778
+ * console.warn(error.status, error.errors[0]?.message);
779
+ * }
780
+ * }
781
+ * ```
782
+ */
783
+ export const isMountayaApiError = (error: unknown): error is MountayaApiError =>
784
+ declaresName(error, MOUNTAYA_API_ERROR_NAMES) &&
785
+ "status" in error &&
786
+ typeof error.status === "number" &&
787
+ "errors" in error &&
788
+ Array.isArray(error.errors) &&
789
+ error.errors.every((entry: unknown) => typeof entry === "object" && entry !== null) &&
790
+ "hasCode" in error &&
791
+ typeof error.hasCode === "function";
792
+
793
+ /**
794
+ * isErrorEntry narrows one member of an envelope's `errors` to an entry of the API's error
795
+ * envelope: an object carrying a string `message`.
796
+ *
797
+ * Hand-written rather than schema-validated because this package ships zero runtime
798
+ * dependencies, and because the parse must be forward-compatible: an entry missing
799
+ * `extensions` or carrying fields this release has never heard of is still a valid entry,
800
+ * so only `message` is required. A stricter parse would downgrade a specific, actionable
801
+ * message of the API to a bare status code the first time the envelope grew a field.
802
+ */
803
+ const isErrorEntry = (entry: unknown): entry is ErrorEntry =>
804
+ typeof entry === "object" &&
805
+ entry !== null &&
806
+ "message" in entry &&
807
+ typeof entry.message === "string";
808
+
809
+ /**
810
+ * errorsOf reads the `errors` member of a parsed body as it parsed, or undefined where the body
811
+ * is no object or carries none.
812
+ */
813
+ const errorsOf = (body: unknown): unknown =>
814
+ typeof body === "object" && body !== null && "errors" in body ? body.errors : undefined;
815
+
816
+ /**
817
+ * entriesOf reads the entries of an error envelope off a parsed body, whatever the body parsed
818
+ * to: each member of its `errors` list that is an object carrying a message, in the order sent,
819
+ * and none where `errors` is no list.
820
+ *
821
+ * One reading for every surface, one entry at a time. A REST or Tile API refusal and a Data API
822
+ * envelope are both read through it before anything reads an entry, so a body something on the
823
+ * network path wrote (`{"errors":"bad gateway"}`, `{"errors":[null]}`) classifies by its status
824
+ * rather than throwing a `TypeError` from the first property read, and a member that is no entry
825
+ * costs none of the entries beside it.
826
+ */
827
+ export const entriesOf = (body: unknown): readonly ErrorEntry[] => {
828
+ const errors = errorsOf(body);
829
+
830
+ return Array.isArray(errors) ? errors.filter(isErrorEntry) : [];
831
+ };
832
+
833
+ /**
834
+ * statesErrors reports whether a parsed body's `errors` member holds anything: it is present and
835
+ * is neither `null` nor an empty list, whether or not what it holds is an entry
836
+ * {@link entriesOf} reads.
837
+ *
838
+ * It is what makes a `200` from the Data API a failure. An answer that states errors did not do
839
+ * what was asked, and one whose `errors` hold no entry to read (a string, a list of `null`) says
840
+ * so just as surely: read by its entries alone, it would be handed to the caller as a success.
841
+ */
842
+ export const statesErrors = (body: unknown): boolean => {
843
+ const errors = errorsOf(body);
844
+
845
+ return errors !== undefined && errors !== null && !(Array.isArray(errors) && errors.length === 0);
846
+ };
847
+
848
+ /**
849
+ * isMetadata reports whether a value can stand as an envelope's metadata: an object that is
850
+ * neither null nor an array, which every metadata shape the contract declares is.
851
+ */
852
+ const isMetadata = (value: unknown): value is ErrorMetadata =>
853
+ typeof value === "object" && value !== null && !Array.isArray(value);
854
+
855
+ /**
856
+ * metadataOf reads an envelope's `extensions.metadata` off a parsed body, or undefined where the
857
+ * body carries none.
858
+ *
859
+ * Read apart from the entries, because a failure can carry one without the other: a `409` for a
860
+ * held lock carries both, and an answer with no entries still classifies by its status. A value
861
+ * that is not an object is no metadata this contract declares, and is left out rather than
862
+ * handed on under a type it does not have.
863
+ */
864
+ export const metadataOf = (body: unknown): ErrorMetadata | undefined => {
865
+ if (typeof body !== "object" || body === null || !("extensions" in body)) {
866
+ return undefined;
867
+ }
868
+
869
+ const { extensions } = body;
870
+ if (typeof extensions !== "object" || extensions === null || !("metadata" in extensions)) {
871
+ return undefined;
872
+ }
873
+
874
+ const { metadata } = extensions;
875
+
876
+ return isMetadata(metadata) ? metadata : undefined;
877
+ };
878
+
879
+ /**
880
+ * PAYMENT_REQUIRED_CODE is the code of a 402, the status {@link MountayaBillingError} stands for:
881
+ * a product the organization does not hold, or, on the Data API, a self-serve organization with no
882
+ * payment method on file or with invoices still owed.
883
+ */
884
+ export const PAYMENT_REQUIRED_CODE = "PAYMENT_REQUIRED";
885
+
886
+ /**
887
+ * What a 402 tells a caller: where each of its remedies is taken, with the API's message naming
888
+ * which one applies.
889
+ *
890
+ * Every remedy is named because the status alone does not say which fact the API refused for,
891
+ * and choosing one here would send a reader with no payment method on file, or with an invoice
892
+ * still owed, to change an agreement that already covers the call, or a reader without the
893
+ * product to a settings page that cannot grant it. The API's own message names the fact.
894
+ */
895
+ const BILLING_STEP =
896
+ "The API's message says which applies: a product of the organization's agreement is changed with Mountaya (https://mountaya.com/en/contact/), and a missing payment method is added, or an invoice still owed paid, in the organization's billing settings.";
897
+
898
+ /**
899
+ * What a 429 coded `LIMIT_REACHED` asks a caller to do: no wait lifts a ceiling, so the step names
900
+ * the two things that do rather than a wait.
901
+ */
902
+ const CEILING_STEP =
903
+ "No wait lifts a ceiling, so this call is not repeated: free a place in what the error's metadata names, or change the organization's agreement with Mountaya (https://mountaya.com/en/contact/) where it sets that ceiling.";
904
+
905
+ /** A whole count of seconds, in the singular for one: `1 second`, `23 seconds`. */
906
+ const secondsSpelled = (count: number): string => `${count} ${count === 1 ? "second" : "seconds"}`;
907
+
908
+ /**
909
+ * The moment a wait of `seconds` from now ends, as an instant in UTC to the second
910
+ * (`2026-11-26T00:00:00Z`), or undefined where it lies past the last moment a `Date` holds.
911
+ */
912
+ const momentAfter = (seconds: number): string | undefined => {
913
+ // A `Retry-After` delay counts from the answer's receipt (RFC 9110, section 10.2.3), so it is
914
+ // placed on this reader's clock rather than on the `Date` the answer states, which a browser
915
+ // hides from a cross-origin caller. Placing protocol time on the clock converts no measurement.
916
+ const end = new Date(Date.now() + seconds * 1000);
917
+
918
+ return Number.isNaN(end.getTime()) ? undefined : end.toISOString().replace(/\.\d{3}Z$/, "Z");
919
+ };
920
+
921
+ /**
922
+ * What a 429 of a spent monthly allowance asks a caller to do: nothing lifts it before the
923
+ * organization's next billing period begins but a larger allowance in its agreement, so the step
924
+ * names when that is, in the seconds its `Retry-After` names and the moment in UTC they end,
925
+ * rather than a wait a caller would sit out.
926
+ */
927
+ const monthlyAllowanceStep = (retryAfterSeconds: number | undefined): string => {
928
+ const moment = retryAfterSeconds === undefined ? undefined : momentAfter(retryAfterSeconds);
929
+ const when =
930
+ retryAfterSeconds === undefined || retryAfterSeconds === 0
931
+ ? ""
932
+ : ` in ${secondsSpelled(retryAfterSeconds)}${moment === undefined ? "" : ` (at ${moment})`}`;
933
+
934
+ return `The organization's monthly allowance on this API is spent: it renews when the next billing period begins${when}, so this call is not repeated before then. A larger allowance is set in the organization's agreement with Mountaya (https://mountaya.com/en/contact/).`;
935
+ };
936
+
937
+ /**
938
+ * spendsMonthlyAllowance reports whether a 429's rate-limit state says it was refused for a spent
939
+ * monthly allowance: its `month` policy has nothing left, and no other policy it lists is spent.
940
+ * A refusal for the allowance is weighed before every per-minute bound, so it lists none of
941
+ * them; a per-minute refusal while the allowance is spent to its last unit lists that bound spent
942
+ * too, and stays a wait.
943
+ */
944
+ const spendsMonthlyAllowance = (rateLimit: RateLimitInfo | undefined): boolean => {
945
+ const policies = rateLimit?.policies ?? [];
946
+
947
+ return (
948
+ policies.some((policy) => policy.name === "month" && policy.remaining === 0) &&
949
+ policies.every((policy) => policy.name === "month" || policy.remaining !== 0)
950
+ );
951
+ };
952
+
953
+ /** What a 401 asks a caller to check, whatever the call. */
954
+ const CREDENTIAL_STEP =
955
+ "Check the credential this client sends: a key that is unknown, rotated or disabled, and a session token that has expired, are refused.";
956
+
957
+ /**
958
+ * What a 401 adds for a call that acts as a member: its session token has to name the user it
959
+ * acts as, which a token minted without `user_id` does not, and the API answers that token as it
960
+ * answers none.
961
+ */
962
+ const MEMBER_SESSION_STEP =
963
+ "This call acts as the user its session token was minted for, so mint the token with postSession's user_id set to that user.";
964
+
965
+ /** What a 401 on `postSession` asks a caller to check: the secret key, which it alone takes. */
966
+ const SECRET_KEY_STEP =
967
+ "Check the secret key this client sends: one that is unknown, revoked or malformed, or one of a canceled organization, is refused.";
968
+
969
+ /** What a 403 asks a caller to check, whatever the call. */
970
+ const FORBIDDEN_STEP =
971
+ "Check that the key carries the scope this call needs, that the resource belongs to the key's organization, and that the page calling is one the organization allows.";
972
+
973
+ /**
974
+ * What a 403 adds for a call that acts as a member: the user its session token names has to be a
975
+ * member of the key's organization holding the role the call asks.
976
+ */
977
+ const ACTING_USER_STEP =
978
+ "This call acts as the user its session token names (postSession's user_id), who must be a member of the key's organization holding the role the call asks.";
979
+
980
+ /**
981
+ * What a 403 on `postSession` asks a caller to check: the publishable key it names, and the user
982
+ * it mints for. A user who is not a member, and one who does not exist, answer alike.
983
+ */
984
+ const MINT_REFUSAL_STEP =
985
+ "Check that the publishable key in the body is one this secret key's organization issued, and that user_id names a member of that organization or a user holding an invitation to it.";
986
+
987
+ /**
988
+ * What a 412 asks a caller to do: the tag the write named is stale, so the write is not repeated
989
+ * as it is.
990
+ */
991
+ const PRECONDITION_STEP =
992
+ "The resource changed since the etag this write names was read: read it again, and decide what the write should be now.";
993
+
994
+ /**
995
+ * What the 409 coded `IDEMPOTENCY_ANSWER_UNAVAILABLE` asks a caller to do: the write was made, so
996
+ * it is read again rather than sent again.
997
+ */
998
+ const IDEMPOTENT_ANSWER_STEP =
999
+ "The write was made, and its answer cannot be given again: read the resource again rather than sending the write once more.";
1000
+
1001
+ /**
1002
+ * What the 409 coded `IDEMPOTENCY_KEY_IN_USE` asks a caller to do once the client stopped asking:
1003
+ * the first request with the key is still running, so the call is sent again with the same key.
1004
+ */
1005
+ const KEY_IN_USE_STEP =
1006
+ "The first request with this Idempotency-Key is still running: send the same call again with the error's idempotencyKey, never a new key, which would make the write twice.";
1007
+
1008
+ /**
1009
+ * What a 429 on `postSession` adds: the limits it keeps, the last of which a `user_id` the API
1010
+ * refuses runs into on its own, so a caller minting for somebody who left meets it while minting
1011
+ * for everybody else still works.
1012
+ */
1013
+ const MINT_LIMIT_STEP =
1014
+ "Minting is limited per secret key, per client IP address and secret key whose requests keep failing, and per user_id it refuses, so check the publishable key and the user_id before asking again.";
1015
+
1016
+ /**
1017
+ * FailureDeclaration is what a failed call's operation declares about the credentials it takes,
1018
+ * as far as the step its refusal names turns on it. Each member is the `RequestArgs` member of the
1019
+ * same name, so a request descriptor is one, and an absent member is a declaration not made.
1020
+ */
1021
+ export interface FailureDeclaration {
1022
+ /** Whether the operation acts as the user its session token names (`x-acting-user: required`). */
1023
+ readonly actsAsMember?: boolean | undefined;
1024
+ /** Whether the operation is authenticated by a secret key, as `postSession` alone is. */
1025
+ readonly requiresSecretKey?: boolean | undefined;
1026
+ }
1027
+
1028
+ /**
1029
+ * nextStepFor names what a caller can do about a failure, for the statuses that name one.
1030
+ *
1031
+ * A 401, 402, 403, 412 and 429 each have a remedy on the caller's side, and so do the 409 coded
1032
+ * `IDEMPOTENCY_ANSWER_UNAVAILABLE`, whose write was made, and the one coded
1033
+ * `IDEMPOTENCY_KEY_IN_USE`, whose first request is still running; a message that stops at the
1034
+ * status leaves the reader of a log to work it out. Every other status says nothing a caller can act on beyond
1035
+ * the API's own message: a 400 or another 409 is about this request, which the entries describe,
1036
+ * and a 5xx is the API's. A 429 coded `LIMIT_REACHED` is a ceiling, which no wait lifts, so its
1037
+ * step names what does rather than a wait.
1038
+ *
1039
+ * A 429 whose rate-limit state says the monthly allowance is spent names when the next billing
1040
+ * period begins rather than a wait, since no retry within it is answered otherwise.
1041
+ *
1042
+ * What the operation declares sharpens the step. A call that acts as a member is told which user
1043
+ * its session token has to name, and `postSession`, authenticated by a secret key, is told about
1044
+ * the secret key, the publishable key and the user it mints for.
1045
+ */
1046
+ const nextStepFor = (
1047
+ status: number,
1048
+ code: unknown,
1049
+ retryAfterSeconds: number | undefined,
1050
+ monthlyAllowanceSpent: boolean,
1051
+ declaration: FailureDeclaration,
1052
+ ): string | undefined => {
1053
+ const mints = declaration.requiresSecretKey === true;
1054
+ const actsAsMember = declaration.actsAsMember === true;
1055
+
1056
+ switch (status) {
1057
+ case 401:
1058
+ if (mints) {
1059
+ return SECRET_KEY_STEP;
1060
+ }
1061
+
1062
+ return actsAsMember ? `${CREDENTIAL_STEP} ${MEMBER_SESSION_STEP}` : CREDENTIAL_STEP;
1063
+ case 402:
1064
+ return BILLING_STEP;
1065
+ case 403:
1066
+ if (mints) {
1067
+ return MINT_REFUSAL_STEP;
1068
+ }
1069
+
1070
+ return actsAsMember ? `${FORBIDDEN_STEP} ${ACTING_USER_STEP}` : FORBIDDEN_STEP;
1071
+ case 409:
1072
+ return code === IDEMPOTENT_ANSWER_UNAVAILABLE_CODE
1073
+ ? IDEMPOTENT_ANSWER_STEP
1074
+ : code === KEY_IN_USE_CODE
1075
+ ? KEY_IN_USE_STEP
1076
+ : undefined;
1077
+ case 412:
1078
+ return PRECONDITION_STEP;
1079
+ case 429: {
1080
+ if (code === CEILING_CODE) {
1081
+ return CEILING_STEP;
1082
+ }
1083
+
1084
+ if (monthlyAllowanceSpent) {
1085
+ return monthlyAllowanceStep(retryAfterSeconds);
1086
+ }
1087
+
1088
+ // A wait of none is still a wait for the limit's window, so it is named without a number.
1089
+ const wait =
1090
+ retryAfterSeconds === undefined || retryAfterSeconds === 0
1091
+ ? "Wait before calling again."
1092
+ : `Wait ${secondsSpelled(retryAfterSeconds)} before calling again.`;
1093
+
1094
+ return mints ? `${wait} ${MINT_LIMIT_STEP}` : wait;
1095
+ }
1096
+ default:
1097
+ return undefined;
1098
+ }
1099
+ };
1100
+
1101
+ /**
1102
+ * FailureFacts are what a failure's message reads beyond its status and its entries, each where
1103
+ * the answer or the call states it.
1104
+ */
1105
+ export interface FailureFacts {
1106
+ /** What the call's operation declares, which sharpens the next step. */
1107
+ readonly declaration?: FailureDeclaration | undefined;
1108
+ /** The answer's `X-Request-Id`, which the message ends on. */
1109
+ readonly requestId?: string | undefined;
1110
+ /** The whole seconds a 429's `Retry-After` names, which its next step spells. */
1111
+ readonly retryAfterSeconds?: number | undefined;
1112
+ /** The answer's rate-limit state, which tells a 429 of a spent monthly allowance apart. */
1113
+ readonly rateLimit?: RateLimitInfo | undefined;
1114
+ }
1115
+
1116
+ /**
1117
+ * failureMessage spells what a failed call reports: `<context>: <status> <CODE> <message>`, then
1118
+ * the next step a caller can take where the status names one, then the request id where the
1119
+ * answer named one: `getItinerary: 404 NOT_FOUND Itinerary not found. (request 4bf9…)`.
1120
+ *
1121
+ * The code and the message are the first entry's, which classifies the response as a whole, and
1122
+ * each part is left out when the response did not carry it: a bodiless 502 reads
1123
+ * `getItinerary: 502`. `status` is omitted for a Data API field failure, whose 200 says nothing
1124
+ * about it. The message ends at the API's words, and the next step, when there is one,
1125
+ * follows as a sentence of its own, sharpened by what the call's operation declares.
1126
+ */
1127
+ export const failureMessage = (
1128
+ context: string,
1129
+ status: number | undefined,
1130
+ entries: readonly ErrorEntry[],
1131
+ facts: FailureFacts = {},
1132
+ ): string => {
1133
+ // Read as unknown: an entry is held to an object carrying a message and to nothing else, so a
1134
+ // code or a message that is not a string is left out rather than printed as `[object Object]`.
1135
+ const first: {
1136
+ readonly extensions?: { readonly code?: unknown } | undefined;
1137
+ readonly message?: unknown;
1138
+ } = entries[0] ?? {};
1139
+ const parts = [status, first.extensions?.code, first.message]
1140
+ .map((part) =>
1141
+ typeof part === "string" ? part.trim() : typeof part === "number" ? String(part) : "",
1142
+ )
1143
+ .filter((part) => part !== "");
1144
+ const summary = parts.length === 0 ? context : `${context}: ${parts.join(" ")}`;
1145
+ const next =
1146
+ status === undefined
1147
+ ? undefined
1148
+ : nextStepFor(
1149
+ status,
1150
+ first.extensions?.code,
1151
+ facts.retryAfterSeconds,
1152
+ spendsMonthlyAllowance(facts.rateLimit),
1153
+ facts.declaration ?? {},
1154
+ );
1155
+ const sentence =
1156
+ next === undefined ? summary : `${/[.!?]$/.test(summary) ? summary : `${summary}.`} ${next}`;
1157
+
1158
+ return facts.requestId === undefined ? sentence : `${sentence} (request ${facts.requestId})`;
1159
+ };
1160
+
1161
+ /** The month names an HTTP date spells, in calendar order. */
1162
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1163
+
1164
+ /** The whole-seconds form: digits alone, with the optional whitespace a field value may carry. */
1165
+ const delaySecondsPattern = /^[ \t]*(\d+)[ \t]*$/;
1166
+
1167
+ /** The greatest count of seconds the header is read as: the largest signed 64-bit integer. */
1168
+ const MAX_DELAY_SECONDS_COUNT = 9_223_372_036_854_775_807n;
1169
+
1170
+ /** IMF-fixdate, the form a sender writes today: `Sun, 06 Nov 1994 08:49:37 GMT`. */
1171
+ const imfFixdatePattern =
1172
+ /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) ([A-Z][a-z]{2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
1173
+
1174
+ /** The obsolete RFC 850 form, with a two-digit year: `Sunday, 06-Nov-94 08:49:37 GMT`. */
1175
+ const rfc850DatePattern =
1176
+ /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-([A-Z][a-z]{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
1177
+
1178
+ /** The obsolete asctime form, in UTC though it says nothing: `Sun Nov 6 08:49:37 1994`. */
1179
+ const asctimeDatePattern =
1180
+ /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) ([A-Z][a-z]{2}) ([ \d]\d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/;
1181
+
1182
+ /**
1183
+ * utcInstant turns the fields of an HTTP date into epoch milliseconds, or undefined where they
1184
+ * name no real instant: a month outside the list, a day the month does not have, an hour past
1185
+ * 23. A second of 60 is the leap second the grammar allows.
1186
+ */
1187
+ const utcInstant = (
1188
+ year: number,
1189
+ month: string,
1190
+ day: number,
1191
+ hour: number,
1192
+ minute: number,
1193
+ second: number,
1194
+ ): number | undefined => {
1195
+ const monthIndex = MONTHS.indexOf(month);
1196
+ if (monthIndex < 0 || hour > 23 || minute > 59 || second > 60) {
1197
+ return undefined;
1198
+ }
1199
+
1200
+ // Checked against the calendar rather than a table, so 29 February is right in a leap year.
1201
+ // `setUTCFullYear` rather than `Date.UTC`, which reads a year below 100 as one in the 1900s.
1202
+ const midnight = new Date(0);
1203
+ midnight.setUTCFullYear(year, monthIndex, day);
1204
+ if (midnight.getUTCMonth() !== monthIndex || midnight.getUTCDate() !== day) {
1205
+ return undefined;
1206
+ }
1207
+
1208
+ return midnight.getTime() + ((hour * 60 + minute) * 60 + second) * 1000;
1209
+ };
1210
+
1211
+ /**
1212
+ * httpDate reads an HTTP date in any of its three forms, strictly, as epoch milliseconds.
1213
+ *
1214
+ * Strictly, because the runtime's own `Date.parse` reads far more than the grammar allows, and
1215
+ * reads it differently per engine: V8 takes an ISO-8601 timestamp, a date with no weekday, and
1216
+ * even `"-5"`, which it reads as a date in 2001. The names are case-sensitive, as the grammar
1217
+ * says; the weekday is read and not checked against the date.
1218
+ *
1219
+ * `now` places the RFC 850 form's two-digit year, which is read in the current century, or in the
1220
+ * one before where the current century's reading is more than 50 years ahead: the rule RFC 9110
1221
+ * (section 5.6.7) gives a recipient.
1222
+ */
1223
+ const httpDate = (value: string, now: number): number | undefined => {
1224
+ const fixdate = imfFixdatePattern.exec(value);
1225
+ if (fixdate !== null) {
1226
+ const [, day, month, year, hour, minute, second] = fixdate;
1227
+
1228
+ return utcInstant(
1229
+ Number(year),
1230
+ month ?? "",
1231
+ Number(day),
1232
+ Number(hour),
1233
+ Number(minute),
1234
+ Number(second),
1235
+ );
1236
+ }
1237
+
1238
+ const rfc850 = rfc850DatePattern.exec(value);
1239
+ if (rfc850 !== null) {
1240
+ const [, day, month, shortYear, hour, minute, second] = rfc850;
1241
+ const currentYear = new Date(now).getUTCFullYear();
1242
+ const sameDigits = currentYear - (currentYear % 100) + Number(shortYear);
1243
+ const year = sameDigits > currentYear + 50 ? sameDigits - 100 : sameDigits;
1244
+
1245
+ return utcInstant(year, month ?? "", Number(day), Number(hour), Number(minute), Number(second));
1246
+ }
1247
+
1248
+ const asctime = asctimeDatePattern.exec(value);
1249
+ if (asctime !== null) {
1250
+ const [, month, day, hour, minute, second, year] = asctime;
1251
+
1252
+ return utcInstant(
1253
+ Number(year),
1254
+ month ?? "",
1255
+ Number(day),
1256
+ Number(hour),
1257
+ Number(minute),
1258
+ Number(second),
1259
+ );
1260
+ }
1261
+
1262
+ return undefined;
1263
+ };
1264
+
1265
+ /**
1266
+ * parseRetryAfter reads the `Retry-After` header as whole seconds, or undefined where it says
1267
+ * nothing this client can use.
1268
+ *
1269
+ * The header is defined as either a delay in seconds or an HTTP date, and both forms appear in
1270
+ * the wild behind proxies, so both are handled, and nothing else is: a blank, a sign, a
1271
+ * fraction, an exponent, a hex prefix or a count past 64 bits is ignored, and the backoff
1272
+ * schedule applies as if no header had come. The grammar is matched rather than the value coerced, because `Number` reads
1273
+ * each of those as a delay (a blank as zero seconds, `"1e3"` as a thousand). A date's distance
1274
+ * from now is carried in whole seconds rounded up, so a caller that waits out what it names never
1275
+ * comes back early, and a date in the past clamps to 0 rather than producing a negative delay a
1276
+ * backoff would treat as an error.
1277
+ *
1278
+ * `now` is a parameter with a default because the date form is a SUBTRACTION from the
1279
+ * current instant, and a rule whose answer moves with the wall clock is one no fixture can
1280
+ * pin and no second language can be held to. Every caller takes the default; the conformance
1281
+ * suite passes a fixed instant, which is the only way the date branch has an expected value
1282
+ * at all.
1283
+ */
1284
+ export const parseRetryAfter = (
1285
+ header: string | null,
1286
+ now: () => number = Date.now,
1287
+ ): number | undefined => {
1288
+ if (header === null) {
1289
+ return undefined;
1290
+ }
1291
+
1292
+ const digits = delaySecondsPattern.exec(header)?.[1];
1293
+ if (digits !== undefined) {
1294
+ // A count past 64 bits is neither form, where every SDK's integer read of it ends. Within
1295
+ // them, a delay past what a double holds exactly is read as the greatest one it does, which
1296
+ // is still a wait no retry sits out.
1297
+ if (BigInt(digits) > MAX_DELAY_SECONDS_COUNT) {
1298
+ return undefined;
1299
+ }
1300
+
1301
+ return Math.min(Number(digits), Number.MAX_SAFE_INTEGER);
1302
+ }
1303
+
1304
+ const current = now();
1305
+ const instant = httpDate(header.replace(/^[ \t]+|[ \t]+$/g, ""), current);
1306
+
1307
+ return instant === undefined ? undefined : Math.max(0, Math.ceil((instant - current) / 1000));
1308
+ };
1309
+
1310
+ /**
1311
+ * answerDetailsOf reads what an answer's headers say about it beside its body: its request id
1312
+ * and the rate-limit state it describes. A request id that is empty or whitespace alone is none.
1313
+ */
1314
+ export const answerDetailsOf = (
1315
+ headers: Pick<Headers, "get">,
1316
+ ): Pick<ApiErrorDetails, "rateLimit" | "requestId"> => {
1317
+ const requestId = headers.get("X-Request-Id")?.trim();
1318
+
1319
+ return {
1320
+ rateLimit: parseRateLimit(headers),
1321
+ requestId: requestId === undefined || requestId === "" ? undefined : requestId,
1322
+ };
1323
+ };
1324
+
1325
+ /**
1326
+ * replayedOf reports whether an answer is one the API kept for an `Idempotency-Key` it had seen
1327
+ * and gave again: it carries `Idempotent-Replayed: true`, read without regard to case. Every other
1328
+ * value, and no header at all, is an answer the API made for this request.
1329
+ */
1330
+ export const replayedOf = (headers: Pick<Headers, "get">): boolean =>
1331
+ headers.get("Idempotent-Replayed")?.trim().toLowerCase() === "true";
1332
+
1333
+ /**
1334
+ * errorOfBody builds the typed error for a non-2xx answer from its parsed body, whatever the
1335
+ * body parsed to: the one place a refusal's entries, metadata, `Retry-After`, `ETag`, request id
1336
+ * and rate-limit state become an error, beside the `Idempotency-Key` the call sent.
1337
+ */
1338
+ const errorOfBody = (
1339
+ body: unknown,
1340
+ answer: Pick<Response, "headers" | "status">,
1341
+ context: string,
1342
+ declaration: FailureDeclaration | undefined,
1343
+ idempotencyKey: string | undefined,
1344
+ ): MountayaApiError => {
1345
+ const entries = entriesOf(body);
1346
+ const retryAfterSeconds = parseRetryAfter(answer.headers.get("Retry-After"));
1347
+ const details = answerDetailsOf(answer.headers);
1348
+
1349
+ return errorForStatus(
1350
+ failureMessage(context, answer.status, entries, {
1351
+ declaration,
1352
+ rateLimit: details.rateLimit,
1353
+ requestId: details.requestId,
1354
+ retryAfterSeconds,
1355
+ }),
1356
+ answer.status,
1357
+ entries,
1358
+ {
1359
+ ...details,
1360
+ etag: answer.headers.get("ETag") ?? undefined,
1361
+ idempotencyKey,
1362
+ metadata: metadataOf(body),
1363
+ retryAfter: retryAfterSeconds,
1364
+ },
1365
+ );
1366
+ };
1367
+
1368
+ /**
1369
+ * errorFromResponse builds the right typed error for a non-2xx response.
1370
+ *
1371
+ * The body is read once and tolerated when absent or unparseable: a bodiless 502 from a proxy is
1372
+ * still a real error and still deserves its class. `context` names the operation, and the
1373
+ * message is {@link failureMessage}'s: `getItinerary: 403 FORBIDDEN Access is forbidden.`
1374
+ * followed by the next step a 401, 402, 403, 412 or 429 asks for, or a 409 that answers the
1375
+ * call's `Idempotency-Key`, sharpened by what the call's operation `declaration` states, and the
1376
+ * request id. The error carries the envelope's entries, its {@link ErrorMetadata}, the request
1377
+ * id and the rate-limit state, each where the answer sent it, and the `idempotencyKey` the call
1378
+ * sent, where it sent one.
1379
+ */
1380
+ export const errorFromResponse = async (
1381
+ response: Response,
1382
+ context: string,
1383
+ declaration?: FailureDeclaration,
1384
+ idempotencyKey?: string,
1385
+ ): Promise<MountayaApiError> =>
1386
+ errorOfBody(
1387
+ await response.json().catch(() => undefined),
1388
+ response,
1389
+ context,
1390
+ declaration,
1391
+ idempotencyKey,
1392
+ );
1393
+
1394
+ /**
1395
+ * errorFromBody builds the typed error {@link errorFromResponse} builds, for an answer whose
1396
+ * body is already read, as the text it arrived as.
1397
+ *
1398
+ * It takes the status and the headers off `answer` and never builds a `Response` to carry them,
1399
+ * so a status the `Response` constructor refuses (a 304, or one outside 200 to 599, which a
1400
+ * runtime hands back as a server sent it) classifies like any other. Text that is not JSON is no
1401
+ * envelope, and the status alone decides the class.
1402
+ */
1403
+ export const errorFromBody = (
1404
+ text: string,
1405
+ answer: Pick<Response, "headers" | "status">,
1406
+ context: string,
1407
+ declaration?: FailureDeclaration,
1408
+ idempotencyKey?: string,
1409
+ ): MountayaApiError => {
1410
+ let body: unknown;
1411
+ try {
1412
+ body = JSON.parse(text);
1413
+ } catch {
1414
+ body = undefined;
1415
+ }
1416
+
1417
+ return errorOfBody(body, answer, context, declaration, idempotencyKey);
1418
+ };
1419
+
1420
+ /**
1421
+ * errorForStatus picks the class a status maps to, for a caller holding a status and no
1422
+ * `Response` to read.
1423
+ *
1424
+ * The Data API is that caller. It has a response, but one whose body is a GraphQL envelope
1425
+ * already decoded, and a non-2xx one is classified here exactly as a REST response is: the same
1426
+ * status decides the same class on every surface. The alternative is a bespoke error class
1427
+ * beside the family, which is exactly the duplication `namespaces.test.ts` asserts against.
1428
+ * Split out of {@link errorFromResponse} rather than copied, so the two cannot disagree about
1429
+ * which class a 402 is.
1430
+ *
1431
+ * @param message - The error's message, as {@link failureMessage} spells one.
1432
+ * @param status - The HTTP status the response carried.
1433
+ * @param entries - The envelope's entries, none where omitted. The status alone decides the
1434
+ * class, a 402's and a 429's included, whatever code an entry carries.
1435
+ * @param details - What the answer sent beside them: the envelope's metadata, the request id, the
1436
+ * rate-limit state, the `Idempotency-Key` the call sent, the wait its `Retry-After` names as
1437
+ * `retryAfter`, and the tag a 412 carries as its `etag`, which every other status leaves out.
1438
+ * @returns The class the status maps to: a {@link MountayaServerError} for any 5xx, and a
1439
+ * plain {@link MountayaApiError} for a status no class is named for.
1440
+ */
1441
+ export const errorForStatus = (
1442
+ message: string,
1443
+ status: number,
1444
+ entries: readonly ErrorEntry[] = [],
1445
+ details: ApiErrorDetails = {},
1446
+ ): MountayaApiError => {
1447
+ // The tag is a 412's alone: a success's is the resource's, and a refusal names no tag but the
1448
+ // one a stale write meets. The wait rides every class whose answer named one.
1449
+ const { etag, ...rest } = details;
1450
+ const args = [message, status, entries, rest] as const;
1451
+
1452
+ switch (status) {
1453
+ case 400:
1454
+ return new MountayaBadRequestError(...args);
1455
+ case 401:
1456
+ return new MountayaAuthenticationError(...args);
1457
+ case 402:
1458
+ return new MountayaBillingError(...args);
1459
+ case 403:
1460
+ return new MountayaForbiddenError(...args);
1461
+ case 404:
1462
+ return new MountayaNotFoundError(...args);
1463
+ case 405:
1464
+ return new MountayaMethodNotAllowedError(...args);
1465
+ case 409:
1466
+ // The status decides the class, and two 409s' entry decides a subclass: each answers the
1467
+ // call's key rather than its write, and one says the write was made, which is the one thing
1468
+ // a caller must never read as a conflict.
1469
+ switch (entries[0]?.extensions?.code) {
1470
+ case IDEMPOTENT_ANSWER_UNAVAILABLE_CODE:
1471
+ return new MountayaIdempotentAnswerUnavailableError(...args);
1472
+ case KEY_IN_USE_CODE:
1473
+ return new MountayaIdempotencyKeyInUseError(...args);
1474
+ default:
1475
+ return new MountayaConflictError(...args);
1476
+ }
1477
+ case 412:
1478
+ return new MountayaPreconditionFailedError(message, status, entries, { ...rest, etag });
1479
+ case 413:
1480
+ return new MountayaPayloadTooLargeError(...args);
1481
+ case 429:
1482
+ return new MountayaRateLimitError(...args);
1483
+ default:
1484
+ return status >= 500 ? new MountayaServerError(...args) : new MountayaApiError(...args);
1485
+ }
1486
+ };