@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.
- package/CHANGELOG.md +104 -0
- package/LICENCE.fr.txt +280 -0
- package/LICENSE.txt +262 -0
- package/README.md +1260 -2
- package/dist/admin/index.cjs +3521 -0
- package/dist/admin/index.cjs.map +1 -0
- package/dist/admin/index.d.cts +1070 -0
- package/dist/admin/index.d.ts +1070 -0
- package/dist/admin/index.js +301 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/browser.cjs +8073 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +106 -0
- package/dist/browser.d.ts +106 -0
- package/dist/browser.js +53 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-BM526BHG.js +342 -0
- package/dist/chunk-BM526BHG.js.map +1 -0
- package/dist/chunk-D2YEVTG7.js +327 -0
- package/dist/chunk-D2YEVTG7.js.map +1 -0
- package/dist/chunk-OHKVUREN.js +3500 -0
- package/dist/chunk-OHKVUREN.js.map +1 -0
- package/dist/chunk-TDTK2L5H.js +3842 -0
- package/dist/chunk-TDTK2L5H.js.map +1 -0
- package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
- package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
- package/dist/errors-B-GqAtQv.d.cts +75960 -0
- package/dist/errors-B-GqAtQv.d.ts +75960 -0
- package/dist/events/index.cjs +1972 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +781 -0
- package/dist/events/index.d.ts +781 -0
- package/dist/events/index.js +826 -0
- package/dist/events/index.js.map +1 -0
- package/dist/index.cjs +8072 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +1 -0
- package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
- package/dist/operations.gen-DUD406TV.d.ts +3993 -0
- package/package.json +127 -4
- package/src/admin/index.ts +47 -0
- package/src/admin/rules/mountayaAdmin.ts +102 -0
- package/src/browser.ts +232 -0
- package/src/core/engines/sessionToken.ts +870 -0
- package/src/core/rules/auth.ts +1017 -0
- package/src/core/rules/clientHeader.ts +28 -0
- package/src/core/rules/dates.ts +200 -0
- package/src/core/rules/decode.ts +154 -0
- package/src/core/rules/envelope.ts +41 -0
- package/src/core/rules/errors.ts +1486 -0
- package/src/core/rules/graphql.ts +576 -0
- package/src/core/rules/headerValue.ts +42 -0
- package/src/core/rules/idempotencyKey.ts +64 -0
- package/src/core/rules/nullMask.ts +127 -0
- package/src/core/rules/nullMasks.gen.ts +416 -0
- package/src/core/rules/paginate.ts +316 -0
- package/src/core/rules/rateLimit.ts +507 -0
- package/src/core/rules/redaction.ts +219 -0
- package/src/core/rules/resourceRef.ts +110 -0
- package/src/core/rules/responseBody.ts +492 -0
- package/src/core/rules/retry.ts +386 -0
- package/src/core/rules/selection.ts +416 -0
- package/src/core/rules/sessionAnswer.ts +90 -0
- package/src/core/rules/sessionSchedule.ts +131 -0
- package/src/core/rules/sessionWait.ts +112 -0
- package/src/core/rules/transport.ts +2386 -0
- package/src/core/rules/version.gen.ts +16 -0
- package/src/core/rules/webAddress.ts +165 -0
- package/src/core/rules/webAddresses.gen.ts +30 -0
- package/src/data/operations.gen.ts +603 -0
- package/src/data/schema.gen.ts +8078 -0
- package/src/data/selection.gen.ts +472 -0
- package/src/events/index.ts +67 -0
- package/src/events/rules/agent.ts +439 -0
- package/src/events/rules/collab.ts +554 -0
- package/src/events/rules/collabNulls.gen.ts +17 -0
- package/src/events/rules/eventStream.ts +94 -0
- package/src/events/rules/openSseStream.ts +594 -0
- package/src/events/rules/sse.ts +349 -0
- package/src/index.ts +231 -0
- package/src/rest/adminOperations.gen.ts +70 -0
- package/src/rest/adminResources.gen.ts +136 -0
- package/src/rest/coreOperations.gen.ts +74 -0
- package/src/rest/coreResources.gen.ts +244 -0
- package/src/rest/dates.gen.ts +217 -0
- package/src/rest/operations.gen.ts +4341 -0
- package/src/rest/resources.gen.ts +369 -0
- package/src/rest/schema.gen.ts +56840 -0
- package/src/tiles/operations.gen.ts +206 -0
- package/src/tiles/schema.gen.ts +8408 -0
- package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
- package/src/webhooks/rules/webhookEvent.ts +38 -0
- package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Data API seam.
|
|
3
|
+
*
|
|
4
|
+
* GraphQL, but it does not look like GraphQL from the outside. Each Data API operation
|
|
5
|
+
* is exposed as a typed method that sends a generated, depth-bounded full-selection
|
|
6
|
+
* document, so a caller writes `mountaya.data.directions(input)` and never builds a query:
|
|
7
|
+
* neither a REST facade over the Data API nor a bare GraphQL client.
|
|
8
|
+
*
|
|
9
|
+
* Three things about the Data API that a generic GraphQL client gets wrong:
|
|
10
|
+
*
|
|
11
|
+
* 1. **A failure can arrive with any HTTP status.** The API answers a failure as a GraphQL
|
|
12
|
+
* `{errors: […]}` body under that failure's own status, so an entitlement failure is a
|
|
13
|
+
* 402 carrying a GraphQL envelope. Reading only the status loses the message; reading
|
|
14
|
+
* only the body misses that it was a 402. A non-2xx is classified by the same ladder as
|
|
15
|
+
* a REST failure, with the envelope's entries, so a 401 is an authentication error and a
|
|
16
|
+
* 402 one of the agreement's classes on every surface alike.
|
|
17
|
+
* 2. **A 200 can still be a failure.** GraphQL puts errors in the body. A client that
|
|
18
|
+
* branches on `response.ok` alone reports success and hands back `undefined`.
|
|
19
|
+
* 3. **The document is the bulk of the request, and it does not have to be sent.** A full
|
|
20
|
+
* selection is kilobytes of upload; the variables are bytes. The API runs Automatic
|
|
21
|
+
* Persisted Queries, so the document travels once per hash and every call after that
|
|
22
|
+
* sends the hash, on the surface with the tightest per-minute limit.
|
|
23
|
+
*
|
|
24
|
+
* All three are handled here so no operation has to. So is the date rule every REST body
|
|
25
|
+
* follows: each `DateTime` the operation's mask names decodes to a `Date`, so
|
|
26
|
+
* `exportItinerary`'s `expiresAt` is the instant its type says rather than the string the wire
|
|
27
|
+
* carries, and no other string does, so a `filename` that is a timestamp stays a filename.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { type DateMask, parseJsonWithDates } from "./dates.js";
|
|
31
|
+
import {
|
|
32
|
+
answerDetailsOf,
|
|
33
|
+
type ErrorEntry,
|
|
34
|
+
entriesOf,
|
|
35
|
+
errorForStatus,
|
|
36
|
+
errorFromBody,
|
|
37
|
+
failureMessage,
|
|
38
|
+
MountayaDataError,
|
|
39
|
+
metadataOf,
|
|
40
|
+
parseRetryAfter,
|
|
41
|
+
statesErrors,
|
|
42
|
+
} from "./errors.js";
|
|
43
|
+
import { decodeSuccessDates, parseSuccessBody, readFailureText, readText } from "./responseBody.js";
|
|
44
|
+
import type { DataOptions } from "./selection.js";
|
|
45
|
+
import type { MountayaTransport, RequestOptions } from "./transport.js";
|
|
46
|
+
|
|
47
|
+
/** What a Data API call reads of its options bag: a REST call's, and its own `timeoutMs`. */
|
|
48
|
+
type CallOptions = RequestOptions & Pick<DataOptions<unknown>, "timeoutMs">;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* DATA_API_BUDGET_MS is the most the Data API spends on any operation before it answers a 504
|
|
52
|
+
* itself, in milliseconds. The SDL's introduction states it once for every operation, and the
|
|
53
|
+
* contract's model carries it on each as `timeoutMs`, which `scripts/contract-checkout.test.mjs`
|
|
54
|
+
* holds this value to. Each attempt waits it plus the transport's margin, so the API's own 504
|
|
55
|
+
* arrives before the client gives up on it.
|
|
56
|
+
*/
|
|
57
|
+
export const DATA_API_BUDGET_MS = 30_000;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The body of a GraphQL response. Its `errors` are the API's error entries, with the input
|
|
61
|
+
* field a validation failure is about under `extensions.path`.
|
|
62
|
+
*/
|
|
63
|
+
interface GraphQLResponse<T> {
|
|
64
|
+
readonly data?: Record<string, T> | null | undefined;
|
|
65
|
+
readonly errors?: readonly ErrorEntry[] | undefined;
|
|
66
|
+
/** Where a failure's metadata rides, as on REST, for {@link metadataOf} to read. */
|
|
67
|
+
readonly extensions?: unknown;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* PersistedQuery is the `extensions.persistedQuery` member of an APQ request.
|
|
72
|
+
*
|
|
73
|
+
* `version` rides on the wire rather than being something the server assumes: a server that
|
|
74
|
+
* met a version it did not implement would say so by name, which is what makes a future
|
|
75
|
+
* revision of the protocol a visible refusal instead of a silent misreading of the hash.
|
|
76
|
+
*/
|
|
77
|
+
interface PersistedQuery {
|
|
78
|
+
readonly sha256Hash: string;
|
|
79
|
+
readonly version: 1;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* GraphQLRequest is the POST body.
|
|
84
|
+
*
|
|
85
|
+
* Both `query` and `extensions` are optional, and which pair is present is the whole APQ
|
|
86
|
+
* handshake: the hash alone on an optimistic call, the document alongside the hash on the
|
|
87
|
+
* one call that registers it, the document alone where APQ is not available.
|
|
88
|
+
*/
|
|
89
|
+
interface GraphQLRequest {
|
|
90
|
+
readonly query?: string | undefined;
|
|
91
|
+
readonly variables: { readonly input: unknown };
|
|
92
|
+
readonly extensions?: { readonly persistedQuery: PersistedQuery } | undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Attempt is one round trip: the response, and the body already read off it.
|
|
97
|
+
*
|
|
98
|
+
* The body travels alongside the response rather than being fetched from it on demand,
|
|
99
|
+
* because by this point it has been consumed (see {@link execute}), so there is nothing
|
|
100
|
+
* left downstream to read a second time.
|
|
101
|
+
*/
|
|
102
|
+
interface Attempt<TResult> {
|
|
103
|
+
readonly response: Response;
|
|
104
|
+
/** The body as the text it arrived as, for the classifier a failure with no entries falls to. */
|
|
105
|
+
readonly raw: string;
|
|
106
|
+
/**
|
|
107
|
+
* The decoded envelope, or nothing for an empty body or a failure's body that is not JSON. A
|
|
108
|
+
* success's body that is not JSON is the base `MountayaApiError`, and never reaches an attempt.
|
|
109
|
+
*/
|
|
110
|
+
readonly envelope: GraphQLResponse<TResult> | undefined;
|
|
111
|
+
/**
|
|
112
|
+
* The envelope's error entries as {@link entriesOf} reads them: each member of its `errors`
|
|
113
|
+
* that is an object carrying a message.
|
|
114
|
+
*/
|
|
115
|
+
readonly entries: readonly ErrorEntry[];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Automatic Persisted Queries, as the Data API's server speaks them.
|
|
120
|
+
*
|
|
121
|
+
* A call sends `extensions.persistedQuery.sha256Hash` and no document. The server looks the
|
|
122
|
+
* hash up in its cache and either runs the document it already holds, or answers
|
|
123
|
+
* `PersistedQueryNotFound`, at which point the document is sent ONCE, alongside the same
|
|
124
|
+
* hash, which both satisfies that call and seeds the cache for every call after it.
|
|
125
|
+
*
|
|
126
|
+
* Two properties make the optimism worth it. A probe that misses costs one round trip on a
|
|
127
|
+
* request that had almost no body, and it happens once per document per cache lifetime
|
|
128
|
+
* rather than once per call. And the hash is over the exact bytes of the document, which the
|
|
129
|
+
* server recomputes and compares before storing, so a hash and a document can never end up
|
|
130
|
+
* describing different queries.
|
|
131
|
+
*
|
|
132
|
+
* The two pieces of state below are kept at two different grains, because they answer two
|
|
133
|
+
* different questions. A digest is a property of the BYTES, so it is memoised per process: a
|
|
134
|
+
* second client pointed anywhere would only recompute what the first already knows. Support
|
|
135
|
+
* is a property of the SERVER, so it is remembered per transport: an application holding a
|
|
136
|
+
* client against production and a second against a local stack would otherwise let one
|
|
137
|
+
* server's refusal speak for both, and the second client would send full documents forever
|
|
138
|
+
* with nothing to say why.
|
|
139
|
+
*/
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The transports whose server has answered that it does not implement APQ at all.
|
|
143
|
+
*
|
|
144
|
+
* A WeakSet rather than a flag on the transport: this is a fact the GraphQL seam learned and
|
|
145
|
+
* caches, not part of a transport's contract, and putting it on the object would make it
|
|
146
|
+
* something every other caller of `MountayaTransport` can see and set. Weak, so a client that goes
|
|
147
|
+
* out of scope takes its entry with it: the set is keyed by a long-lived object a consumer
|
|
148
|
+
* owns, which is exactly the shape that leaks when held strongly.
|
|
149
|
+
*
|
|
150
|
+
* Membership is one-way on purpose. A server that answered `PersistedQueryNotSupported` has
|
|
151
|
+
* told us about its build, not about its mood, so re-probing it would cost a wasted round
|
|
152
|
+
* trip per document forever to learn the same thing.
|
|
153
|
+
*/
|
|
154
|
+
const apqUnsupported = new WeakSet<MountayaTransport>();
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The most distinct documents whose digests are kept.
|
|
158
|
+
*
|
|
159
|
+
* The generated full selections are a closed set and would need no bound at all. `select` is
|
|
160
|
+
* what opens it: a selection may be built at runtime (from a config file, a query string, or
|
|
161
|
+
* a model's answer), so the documents a long-lived process prints are bounded only by what
|
|
162
|
+
* its callers ask for. The cap sits far above any real application's operation count and
|
|
163
|
+
* turns a map that only grows into a warm cache that occasionally misses.
|
|
164
|
+
*/
|
|
165
|
+
const MAX_MEMOISED_DIGESTS = 256;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Document digests, memoised by the exact bytes that were hashed.
|
|
169
|
+
*
|
|
170
|
+
* The PROMISE is memoised rather than the string it resolves to. `crypto.subtle` is async, so
|
|
171
|
+
* caching only the settled value leaves every caller that arrived before the first one
|
|
172
|
+
* finished to start a digest of its own, which is the burst at application start, exactly
|
|
173
|
+
* where the memo is meant to help.
|
|
174
|
+
*/
|
|
175
|
+
const documentHashes = new Map<string, Promise<string>>();
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* subtleCrypto resolves the Web Crypto digest implementation, or nothing where there is none.
|
|
179
|
+
*
|
|
180
|
+
* There are two ways to have none and neither is exotic: `crypto.subtle` is undefined outside
|
|
181
|
+
* a secure context, which is any page served over plain HTTP, and it is absent altogether in
|
|
182
|
+
* React Native, which this package supports. Neither is an error: APQ is an optimization, and
|
|
183
|
+
* the document is still perfectly sendable.
|
|
184
|
+
*
|
|
185
|
+
* The widened binding is what makes the check expressible at all. `lib.dom` declares `crypto`
|
|
186
|
+
* as always present, so comparing `globalThis.crypto?.subtle` against `undefined` is a
|
|
187
|
+
* comparison TypeScript rejects as impossible, while at runtime it is the case this whole
|
|
188
|
+
* path exists for.
|
|
189
|
+
*/
|
|
190
|
+
const subtleCrypto = (): SubtleCrypto | undefined => {
|
|
191
|
+
const runtime: { readonly crypto?: Crypto | undefined } = globalThis;
|
|
192
|
+
|
|
193
|
+
return runtime.crypto?.subtle;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* hashDocument computes the lowercase hex SHA-256 of a document, memoised, or nothing where
|
|
198
|
+
* there is no digest implementation to compute it with.
|
|
199
|
+
*
|
|
200
|
+
* The encoding is not an implementation detail: the server recomputes this digest from the
|
|
201
|
+
* document it stored and refuses a mismatch, so UTF-8 bytes and lowercase hex are a contract.
|
|
202
|
+
* That is also why there is no hand-rolled fallback for a runtime without Web Crypto: a
|
|
203
|
+
* substitute digest would not be slower, it would be wrong.
|
|
204
|
+
*/
|
|
205
|
+
export const hashDocument = (query: string): Promise<string> | undefined => {
|
|
206
|
+
const memoised = documentHashes.get(query);
|
|
207
|
+
if (memoised !== undefined) {
|
|
208
|
+
return memoised;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const subtle = subtleCrypto();
|
|
212
|
+
if (subtle === undefined) {
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const digest = subtle
|
|
217
|
+
.digest("SHA-256", new TextEncoder().encode(query))
|
|
218
|
+
.then((bytes) =>
|
|
219
|
+
Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join(""),
|
|
220
|
+
);
|
|
221
|
+
|
|
222
|
+
// A rejected digest is dropped rather than kept: memoising it would turn one failure into a
|
|
223
|
+
// permanent opt-out of APQ for that document, and recomputing costs a hash rather than a
|
|
224
|
+
// round trip. The handler also settles this branch of the promise, so the rejection the
|
|
225
|
+
// caller catches is not additionally reported as unhandled.
|
|
226
|
+
digest.catch(() => documentHashes.delete(query));
|
|
227
|
+
|
|
228
|
+
if (documentHashes.size >= MAX_MEMOISED_DIGESTS) {
|
|
229
|
+
// A Map iterates in insertion order, so this is the least recently added entry.
|
|
230
|
+
const oldest = documentHashes.keys().next().value;
|
|
231
|
+
if (oldest !== undefined) {
|
|
232
|
+
documentHashes.delete(oldest);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
documentHashes.set(query, digest);
|
|
237
|
+
|
|
238
|
+
return digest;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* persistedQueryFor builds the APQ extension for a document, or nothing when APQ is not
|
|
243
|
+
* available for this call.
|
|
244
|
+
*
|
|
245
|
+
* It never throws. Every way it can decline (a server that has refused the protocol, a
|
|
246
|
+
* runtime with no Web Crypto, a digest that failed) leaves the caller with a document it can
|
|
247
|
+
* send in full, so none of them is a failure a consumer should ever see.
|
|
248
|
+
*
|
|
249
|
+
* The transport is the first argument because the refusal it checks is that server's, not
|
|
250
|
+
* this process's: see {@link apqUnsupported}.
|
|
251
|
+
*/
|
|
252
|
+
const persistedQueryFor = async (
|
|
253
|
+
transport: MountayaTransport,
|
|
254
|
+
query: string,
|
|
255
|
+
): Promise<PersistedQuery | undefined> => {
|
|
256
|
+
if (apqUnsupported.has(transport)) {
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const digest = hashDocument(query);
|
|
261
|
+
if (digest === undefined) {
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
try {
|
|
266
|
+
return { sha256Hash: await digest, version: 1 };
|
|
267
|
+
} catch {
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
/** Reports whether any entry carries this exact message. */
|
|
273
|
+
const named = (entries: readonly ErrorEntry[], message: string): boolean =>
|
|
274
|
+
entries.some((entry) => entry.message === message);
|
|
275
|
+
|
|
276
|
+
/** Reports whether any entry carries this exact `extensions.code`. */
|
|
277
|
+
const coded = (entries: readonly ErrorEntry[], code: string): boolean =>
|
|
278
|
+
entries.some((entry) => entry.extensions?.code === code);
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Reports whether any ONE entry carries both this exact `extensions.code` and this exact message.
|
|
282
|
+
* Both are asked of the same entry: a code alone, or a message alone, is another answer.
|
|
283
|
+
*/
|
|
284
|
+
const codedAndNamed = (entries: readonly ErrorEntry[], code: string, message: string): boolean =>
|
|
285
|
+
entries.some((entry) => entry.extensions?.code === code && entry.message === message);
|
|
286
|
+
|
|
287
|
+
/** What an APQ probe's answer asks for, when it asks for anything beyond a result. */
|
|
288
|
+
export type ApqRefusal = "register" | "unsupported";
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* declinesProtocol reports whether an answer declines the protocol by one of its own spellings,
|
|
292
|
+
* Apollo Server's message or its code: what a registration's answer is read for, since that
|
|
293
|
+
* attempt sent its document and the Data API's `no operation provided` names nothing there.
|
|
294
|
+
*/
|
|
295
|
+
const declinesProtocol = (entries: readonly ErrorEntry[]): boolean =>
|
|
296
|
+
named(entries, "PersistedQueryNotSupported") || coded(entries, "PERSISTED_QUERY_NOT_SUPPORTED");
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* apqRefusal reads a probe's answer for the two things it can mean other than success.
|
|
300
|
+
*
|
|
301
|
+
* `register`: the server does not hold this document yet and is asking for it. This is the
|
|
302
|
+
* ordinary case, once per document per cache lifetime, and it arrives as a 200 carrying
|
|
303
|
+
* `errors`, so it has to be recognized before the rule that a 200 with errors is a failure.
|
|
304
|
+
* A server may send the message and the code, or the message alone as Apollo Server does, and
|
|
305
|
+
* both are accepted so the seam is not pinned to one server implementation.
|
|
306
|
+
*
|
|
307
|
+
* `unsupported`: the server does not implement APQ at all. Apollo Server says so by name. The
|
|
308
|
+
* Data API's server has no such answer: with the extension turned off it finds no operation in
|
|
309
|
+
* a body with no query in it, and answers a 422 whose entry is coded `GRAPHQL_VALIDATION_FAILED`
|
|
310
|
+
* with the message `no operation provided`. Reading that as an ordinary error would break every
|
|
311
|
+
* Data API call the moment APQ is turned off, which is a server-side flag that looks harmless.
|
|
312
|
+
* It is only readable this way because the document is omitted on this attempt and on no other,
|
|
313
|
+
* and only that code and that message on one entry read so: the same answer to a request that
|
|
314
|
+
* carried its document, the same code with any other message, and a parse failure are genuine
|
|
315
|
+
* failures and reach the caller untouched.
|
|
316
|
+
*
|
|
317
|
+
* An answer that carries both reads as `unsupported`.
|
|
318
|
+
*/
|
|
319
|
+
export const apqRefusal = (entries: readonly ErrorEntry[]): ApqRefusal | undefined => {
|
|
320
|
+
// The declined protocol is read first: an answer that carries both refusals is from a server
|
|
321
|
+
// that would refuse a registration too, so registering would spend a round trip for nothing.
|
|
322
|
+
if (
|
|
323
|
+
declinesProtocol(entries) ||
|
|
324
|
+
codedAndNamed(entries, "GRAPHQL_VALIDATION_FAILED", "no operation provided")
|
|
325
|
+
) {
|
|
326
|
+
return "unsupported";
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (named(entries, "PersistedQueryNotFound") || coded(entries, "PERSISTED_QUERY_NOT_FOUND")) {
|
|
330
|
+
return "register";
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return undefined;
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* execute performs one Data API round trip and reads its body.
|
|
338
|
+
*
|
|
339
|
+
* The body is read ONCE, as text, and everything else is parsed from that string.
|
|
340
|
+
*
|
|
341
|
+
* A `response.clone().json()` is the shape to avoid, and the clone is the reason: on the
|
|
342
|
+
* success path (every call that works) the ORIGINAL body is never read, so undici tees the
|
|
343
|
+
* stream and buffers it with no reader draining the other side, and the only branch that would
|
|
344
|
+
* touch the original is the classifier fallback in {@link unwrap}. Reading text once and
|
|
345
|
+
* rebuilding a Response for that one branch keeps the classifier's input intact and leaves
|
|
346
|
+
* nothing undrained.
|
|
347
|
+
*/
|
|
348
|
+
const execute = async <TResult>(
|
|
349
|
+
transport: MountayaTransport,
|
|
350
|
+
operationId: string,
|
|
351
|
+
body: GraphQLRequest,
|
|
352
|
+
options?: CallOptions,
|
|
353
|
+
): Promise<Attempt<TResult>> => {
|
|
354
|
+
const response = await transport.requestRaw({
|
|
355
|
+
body,
|
|
356
|
+
// Every Data API operation is a query. The POST is GraphQL's transport, not a
|
|
357
|
+
// mutation, so these are safe to retry, and they are the operations that most need
|
|
358
|
+
// it, on the surface with the tightest per-minute limit.
|
|
359
|
+
idempotent: true,
|
|
360
|
+
method: "POST",
|
|
361
|
+
operationId,
|
|
362
|
+
path: "/graphql",
|
|
363
|
+
// The same fact, told to the credential rules that read it: a refusal names a read as a read,
|
|
364
|
+
// not as a write. This is the ONE place the method implies the wrong answer, which is why the
|
|
365
|
+
// flag is declared here and nowhere else.
|
|
366
|
+
read: true,
|
|
367
|
+
// The Data API requires a session token beside the publishable key on every request, and
|
|
368
|
+
// answers one without it with a 401. The SDL has no `security` to generate this from, so
|
|
369
|
+
// it is stated here, once, for every operation: the declaration a REST operation's
|
|
370
|
+
// `security` produces, read by the same refusal. No operation here accepts a share token,
|
|
371
|
+
// which the absence of `acceptsShareToken` says.
|
|
372
|
+
requiresSession: true,
|
|
373
|
+
retry: options?.retry,
|
|
374
|
+
// The Data API states one budget for every operation rather than one per operation, so it
|
|
375
|
+
// is stated here, once, as a REST operation's `x-timeout-ms` is stated on its descriptor.
|
|
376
|
+
serverBudgetMs: DATA_API_BUDGET_MS,
|
|
377
|
+
signal: options?.signal,
|
|
378
|
+
surface: "data",
|
|
379
|
+
timeoutMs: options?.timeoutMs,
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
// A success's body is the answer, so one that breaks off is a connection failure, one that is
|
|
383
|
+
// not JSON an error the API answered that names no status of the ladder, and a caller's abort
|
|
384
|
+
// is theirs; reading either as empty would report an answer the API never gave. A failure's
|
|
385
|
+
// body is only a better message for an error its status already classifies, so it is read as
|
|
386
|
+
// the shared classifier reads one: under the bounds a refusal's body is read under, and
|
|
387
|
+
// tolerated when it does not arrive or does not parse. The caller's abort ends either read,
|
|
388
|
+
// since a caller who left waits for neither.
|
|
389
|
+
const raw = response.ok
|
|
390
|
+
? await readText(response, {
|
|
391
|
+
idempotent: true,
|
|
392
|
+
operationId,
|
|
393
|
+
signal: options?.signal,
|
|
394
|
+
})
|
|
395
|
+
: await readFailureText(response, options?.signal);
|
|
396
|
+
const envelope = ((): GraphQLResponse<TResult> | undefined => {
|
|
397
|
+
// Parsed with no mask: the instants are the result's, which unwrap decodes once it has the
|
|
398
|
+
// result in hand, and a failure's envelope holds none, as a REST failure's does not.
|
|
399
|
+
//
|
|
400
|
+
// The two casts are the wire's boundary: the body is typed as the envelope the Data API
|
|
401
|
+
// answers and is not validated against it. Its `errors` are read through `entriesOf`,
|
|
402
|
+
// which checks them, and its `data` is the operation's own type, as the contract states it.
|
|
403
|
+
if (response.ok) {
|
|
404
|
+
return parseSuccessBody(raw, response, { operationId, surface: "data" }) as
|
|
405
|
+
| GraphQLResponse<TResult>
|
|
406
|
+
| undefined;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
try {
|
|
410
|
+
return parseJsonWithDates(raw) as GraphQLResponse<TResult> | undefined;
|
|
411
|
+
} catch {
|
|
412
|
+
return undefined;
|
|
413
|
+
}
|
|
414
|
+
})();
|
|
415
|
+
|
|
416
|
+
return { entries: entriesOf(envelope), envelope, raw, response };
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* unwrap turns one attempt into the operation's result, with each instant `dates` names decoded
|
|
421
|
+
* to a `Date`, or into the typed error the API described.
|
|
422
|
+
*/
|
|
423
|
+
const unwrap = async <TResult>(
|
|
424
|
+
operationId: string,
|
|
425
|
+
attempt: Attempt<TResult>,
|
|
426
|
+
dates: DateMask | undefined,
|
|
427
|
+
): Promise<TResult> => {
|
|
428
|
+
const { entries, envelope, raw, response } = attempt;
|
|
429
|
+
// What the answer names itself by and the limits it was counted against, which every error
|
|
430
|
+
// raised from it carries, a failure under a success status included.
|
|
431
|
+
const details = answerDetailsOf(response.headers);
|
|
432
|
+
|
|
433
|
+
if (!response.ok) {
|
|
434
|
+
// A failure carrying a GraphQL envelope: keep the API's message and its code, and classify
|
|
435
|
+
// by the real status through the same ladder a REST failure climbs. The status is the
|
|
436
|
+
// classification (a 401 is an authentication failure and a 429 a spent limit on this surface
|
|
437
|
+
// as on every other), and the code splits a 402, which the Data API reports as a bare
|
|
438
|
+
// PAYMENT_REQUIRED and so lands on the billing class.
|
|
439
|
+
if (entries.length > 0) {
|
|
440
|
+
const retryAfterSeconds = parseRetryAfter(response.headers.get("Retry-After"));
|
|
441
|
+
|
|
442
|
+
throw errorForStatus(
|
|
443
|
+
failureMessage(operationId, response.status, entries, {
|
|
444
|
+
rateLimit: details.rateLimit,
|
|
445
|
+
requestId: details.requestId,
|
|
446
|
+
retryAfterSeconds,
|
|
447
|
+
}),
|
|
448
|
+
response.status,
|
|
449
|
+
entries,
|
|
450
|
+
{ ...details, metadata: metadataOf(envelope), retryAfter: retryAfterSeconds },
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// No entry to read: a transport fault or a bodiless 5xx. The shared classifier takes the
|
|
455
|
+
// text already read with the status and the headers it classifies on, so the failure still
|
|
456
|
+
// lands on the right typed class, whatever the status is.
|
|
457
|
+
throw errorFromBody(raw, response, operationId);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
if (statesErrors(envelope)) {
|
|
461
|
+
// The case a generic client reports as success. The status is 200 and the operation
|
|
462
|
+
// did not happen, which no rung of the ladder describes, so the message names no status.
|
|
463
|
+
// Read off the `errors` member and never off the entries alone: one that holds something
|
|
464
|
+
// and no entry to read still says the operation failed.
|
|
465
|
+
const message = failureMessage(operationId, undefined, entries);
|
|
466
|
+
const summary =
|
|
467
|
+
message === operationId ? `${operationId}: the Data API returned an error` : message;
|
|
468
|
+
|
|
469
|
+
throw new MountayaDataError(
|
|
470
|
+
details.requestId === undefined ? summary : `${summary} (request ${details.requestId})`,
|
|
471
|
+
200,
|
|
472
|
+
entries,
|
|
473
|
+
{ ...details, metadata: metadataOf(envelope) },
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const data = envelope?.data;
|
|
478
|
+
if (data === undefined || data === null) {
|
|
479
|
+
throw new MountayaDataError(`${operationId}: the Data API returned no data`, 200, [], details);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// `noUncheckedIndexedAccess` makes this `TResult | undefined`, and a cast would erase it. A
|
|
483
|
+
// contract rename would then return `undefined` typed as the result, and the first sign of it
|
|
484
|
+
// would be a property read on undefined somewhere in the caller. Narrowed here, where the
|
|
485
|
+
// operation name is still in hand to say which field was missing.
|
|
486
|
+
const result = data[operationId];
|
|
487
|
+
if (result === undefined) {
|
|
488
|
+
throw new MountayaDataError(
|
|
489
|
+
`${operationId}: the Data API answered without a '${operationId}' field`,
|
|
490
|
+
200,
|
|
491
|
+
[],
|
|
492
|
+
details,
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// The wire's boundary, as above: the field is typed by the operation that asked for it. A
|
|
497
|
+
// declared instant that names none fails the decode as a REST body's does.
|
|
498
|
+
return decodeSuccessDates(result, dates, response, { operationId }) as TResult;
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* runOperation executes one generated Data API document and unwraps its result.
|
|
503
|
+
*
|
|
504
|
+
* The response is keyed by the operation's own field name (`{"directions": {…}}`), so
|
|
505
|
+
* the field is unwrapped here and the caller receives the result type directly.
|
|
506
|
+
*
|
|
507
|
+
* `options` is the caller's options bag, of which this reads the `signal`, the per-call `retry`
|
|
508
|
+
* and the per-call `timeoutMs`. The `select` beside them has already been printed into `query`.
|
|
509
|
+
* Each attempt waits the call's own `timeoutMs`, or else the larger of the client's
|
|
510
|
+
* and {@link DATA_API_BUDGET_MS} plus the transport's margin.
|
|
511
|
+
*
|
|
512
|
+
* `dates` names the instants in the result, as `RequestArgs.dates` does for a REST body: the
|
|
513
|
+
* `DateTime` fields the operation's document can select. Omitted, the result decodes no `Date`.
|
|
514
|
+
*/
|
|
515
|
+
export const runOperation = async <TResult>(
|
|
516
|
+
transport: MountayaTransport,
|
|
517
|
+
operationId: string,
|
|
518
|
+
query: string,
|
|
519
|
+
input: unknown,
|
|
520
|
+
options?: CallOptions,
|
|
521
|
+
dates?: DateMask,
|
|
522
|
+
): Promise<TResult> => {
|
|
523
|
+
const variables = { input };
|
|
524
|
+
const persistedQuery = await persistedQueryFor(transport, query);
|
|
525
|
+
|
|
526
|
+
if (persistedQuery === undefined) {
|
|
527
|
+
const attempt = await execute<TResult>(transport, operationId, { query, variables }, options);
|
|
528
|
+
|
|
529
|
+
return unwrap(operationId, attempt, dates);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const probe = await execute<TResult>(
|
|
533
|
+
transport,
|
|
534
|
+
operationId,
|
|
535
|
+
{ extensions: { persistedQuery }, variables },
|
|
536
|
+
options,
|
|
537
|
+
);
|
|
538
|
+
|
|
539
|
+
const refusal = apqRefusal(probe.entries);
|
|
540
|
+
if (refusal === undefined) {
|
|
541
|
+
return unwrap(operationId, probe, dates);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
if (refusal === "unsupported") {
|
|
545
|
+
apqUnsupported.add(transport);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// One more attempt, and it is not a retry of a failure: the server asked for the document, so
|
|
549
|
+
// this is the request it would have run had the hash hit. Registering keeps the hash alongside
|
|
550
|
+
// the document: that pair is what seeds the cache, and dropping it would make every call for
|
|
551
|
+
// the rest of the process a miss. A second miss is a genuine failure: it goes to the caller
|
|
552
|
+
// rather than round the loop again.
|
|
553
|
+
const registration = await execute<TResult>(
|
|
554
|
+
transport,
|
|
555
|
+
operationId,
|
|
556
|
+
refusal === "register"
|
|
557
|
+
? { extensions: { persistedQuery }, query, variables }
|
|
558
|
+
: { query, variables },
|
|
559
|
+
options,
|
|
560
|
+
);
|
|
561
|
+
|
|
562
|
+
// A server that asked for the document and then declines the protocol has no cache to seed:
|
|
563
|
+
// the transport stops probing, and the document goes out once more, alone, as it does where the
|
|
564
|
+
// probe itself was declined.
|
|
565
|
+
if (refusal === "register" && declinesProtocol(registration.entries)) {
|
|
566
|
+
apqUnsupported.add(transport);
|
|
567
|
+
|
|
568
|
+
return unwrap(
|
|
569
|
+
operationId,
|
|
570
|
+
await execute<TResult>(transport, operationId, { query, variables }, options),
|
|
571
|
+
dates,
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
return unwrap(operationId, registration, dates);
|
|
576
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a request header carries: the rule a credential's members, a client's `language` and the
|
|
3
|
+
* headers a call names are held to before any request, since each of them is sent as a header's
|
|
4
|
+
* value.
|
|
5
|
+
*
|
|
6
|
+
* A header carries printable ASCII alone, U+0020 to U+007E, in every Mountaya SDK. A value outside
|
|
7
|
+
* it never reaches the API: the runtimes a client sends through do not carry one alike, some
|
|
8
|
+
* refusing the request and some writing the value as bytes a server reads as other letters, and a
|
|
9
|
+
* request the runtime's `fetch` refuses surfaces from the first call as a connection failure,
|
|
10
|
+
* retried and reported with a next step about the network.
|
|
11
|
+
*
|
|
12
|
+
* It is a rule of the headers and nobody's format: it says nothing of what a key or a language tag
|
|
13
|
+
* looks like.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Matches the whitespace a runtime's `fetch` takes off either end of a header's value. */
|
|
17
|
+
const edgeWhitespacePattern = /^[\t\n\r ]+|[\t\n\r ]+$/g;
|
|
18
|
+
|
|
19
|
+
/** Matches a value of printable ASCII alone, U+0020 to U+007E, the space included. */
|
|
20
|
+
const printableAsciiPattern = /^[\x20-\x7e]*$/;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* isHeaderValue reports whether a request can carry `value` as a header's value: every character
|
|
24
|
+
* of it is printable ASCII, U+0020 to U+007E.
|
|
25
|
+
*
|
|
26
|
+
* A line break, a tab, NUL, DEL and every other control character are none, wherever they stand,
|
|
27
|
+
* either end included, so a key read from a file with its closing line break is refused rather
|
|
28
|
+
* than carried. Neither is a character past ASCII: a letter of Latin-1 such as `é`, a no-break
|
|
29
|
+
* space, or the ellipsis of a placeholder.
|
|
30
|
+
*/
|
|
31
|
+
export const isHeaderValue = (value: string): boolean => printableAsciiPattern.test(value);
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* isEmptyHeaderValue reports whether a request would carry `value` as a header with nothing in
|
|
35
|
+
* it: an empty string, or whitespace alone, which a runtime takes off before it sends the value.
|
|
36
|
+
*
|
|
37
|
+
* It is the question for a value that has to name something: a client's `language`, a call's
|
|
38
|
+
* `idempotencyKey` and its `ifMatch`. One of a single space is sent as an empty
|
|
39
|
+
* `Accept-Language`, `Idempotency-Key` or `If-Match`, exactly as an empty one is.
|
|
40
|
+
*/
|
|
41
|
+
export const isEmptyHeaderValue = (value: string): boolean =>
|
|
42
|
+
value.replace(edgeWhitespacePattern, "") === "";
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The key a write carries.
|
|
3
|
+
*
|
|
4
|
+
* Every POST, PATCH and DELETE of the Map Studio API declares `Idempotency-Key` but
|
|
5
|
+
* `postSession`, `postOrganizationLookup` and the two collaboration signals, `postItineraryCollab`
|
|
6
|
+
* and `postZoneCollab`, which a repeat restates; the Tile API has no write. The API answers a key
|
|
7
|
+
* it has seen with the answer it stored rather than run the write again. That is what makes
|
|
8
|
+
* asking again safe after an answer that never came, a 502, a 503 or a 504: a call sends one key
|
|
9
|
+
* on every attempt, its caller's or one drawn here before the first attempt and never again for
|
|
10
|
+
* that call, and an operation that declares no key sends none.
|
|
11
|
+
*
|
|
12
|
+
* The key is drawn from a cryptographic random source or not at all. Two calls that drew the same
|
|
13
|
+
* key would each be answered with the other's stored answer, which is a defect no retry policy
|
|
14
|
+
* can recover from, so a runtime with no such source sends no key, and its writes are then
|
|
15
|
+
* repeated only where the operation declares itself idempotent.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** The cryptographic source a key is drawn from, read off the runtime at each draw. */
|
|
19
|
+
interface RandomSource {
|
|
20
|
+
readonly getRandomValues?: (<T extends Uint8Array>(array: T) => T) | undefined;
|
|
21
|
+
readonly randomUUID?: (() => string) | undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The runtime's `crypto`, read at each draw rather than once, so a test can take it away. */
|
|
25
|
+
const randomSource = (): RandomSource | undefined => {
|
|
26
|
+
const source: unknown = Reflect.get(globalThis, "crypto");
|
|
27
|
+
|
|
28
|
+
return typeof source === "object" && source !== null ? source : undefined;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Spells sixteen bytes as a version 4 UUID, in its lowercase canonical form. */
|
|
32
|
+
const uuidOf = (bytes: Uint8Array): string => {
|
|
33
|
+
// The version, 4, in the high nibble of the seventh byte, and the RFC 9562 variant, 10, in the
|
|
34
|
+
// two high bits of the ninth.
|
|
35
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
|
36
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
37
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
38
|
+
|
|
39
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* mintIdempotencyKey draws the key one call of a write sends on every attempt: a version 4 UUID
|
|
44
|
+
* from the runtime's `crypto.randomUUID`, or built from `crypto.getRandomValues` where a runtime
|
|
45
|
+
* has the one and not the other, or none at all where it has neither.
|
|
46
|
+
*
|
|
47
|
+
* Never from `Math.random`: a weaker source makes two calls drawing the same key a matter of
|
|
48
|
+
* time, and the API answers the second with the first one's answer.
|
|
49
|
+
*
|
|
50
|
+
* @returns The key, or undefined where the runtime offers no cryptographic random source.
|
|
51
|
+
*/
|
|
52
|
+
export const mintIdempotencyKey = (): string | undefined => {
|
|
53
|
+
const source = randomSource();
|
|
54
|
+
|
|
55
|
+
if (typeof source?.randomUUID === "function") {
|
|
56
|
+
return source.randomUUID().toLowerCase();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (typeof source?.getRandomValues === "function") {
|
|
60
|
+
return uuidOf(source.getRandomValues(new Uint8Array(16)));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return undefined;
|
|
64
|
+
};
|