@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,316 @@
1
+ /**
2
+ * Walking a paged listing.
3
+ *
4
+ * Every listing of what an organization or its members create is served a page at a time, by an
5
+ * opaque cursor: the caller names a page size, `limit`, and where to start, `cursor`, under
6
+ * `query`, and each answer names the cursor of the page after it at
7
+ * `extensions.metadata.pagination.next_cursor`, null on the last page. Reading a whole listing is
8
+ * therefore a loop, and the loop is easy to write wrong in ways no request reports: a cursor sent
9
+ * beside other filters than the ones it was issued under is refused, a walk that stops at the
10
+ * first short or empty page drops whatever follows it, and one that follows a cursor it has
11
+ * already sent reads the listing again without end. {@link paginate} is that loop, written once.
12
+ */
13
+
14
+ import type { PaginationMetadata } from "../../rest/schema.gen.js";
15
+ import { MountayaApiError, MountayaConfigurationError, refuseOption } from "./errors.js";
16
+ import { abortReasonOf } from "./retry.js";
17
+ import type { RequestOptions } from "./transport.js";
18
+
19
+ /**
20
+ * MAX_PAGE_SIZE is the most rows one page holds: the ceiling the contract sets on every `limit`.
21
+ */
22
+ const MAX_PAGE_SIZE = 100;
23
+
24
+ /**
25
+ * DEFAULT_PAGE_SIZE is the size a walk asks for where the caller names none: the contract's own
26
+ * default for `limit`.
27
+ */
28
+ const DEFAULT_PAGE_SIZE = 50;
29
+
30
+ /** The name a refusal says an option was passed to. */
31
+ const CONTEXT = "paginate";
32
+
33
+ /**
34
+ * PagedResponse is what a paged operation answers with: the rows of one page at `data`, and at
35
+ * `extensions.metadata.pagination` the page size it was served under and the cursor of the page
36
+ * after it.
37
+ *
38
+ * Every Map Studio operation that takes `cursor` and `limit` under `query` answers with this
39
+ * shape, whatever else its metadata carries, so each is an operation {@link paginate} walks.
40
+ */
41
+ export interface PagedResponse<T> {
42
+ /** The rows of this page, in the listing's order. */
43
+ readonly data: readonly T[];
44
+ /** The envelope's extensions, where the page names the next one. */
45
+ readonly extensions: {
46
+ /** The page's metadata, which carries more than the cursor on some operations. */
47
+ readonly metadata: {
48
+ /** The page size this page was served under, and the cursor of the next, null on the last. */
49
+ readonly pagination: PaginationMetadata;
50
+ };
51
+ };
52
+ }
53
+
54
+ /**
55
+ * PaginateOptions are the options of one walk: a call's own `retry`, `signal` and `timeoutMs`,
56
+ * which every request of the walk is made under, and the two that shape the walk itself.
57
+ *
58
+ * `pageSize` and `maxPages` are checked when {@link paginate} is called, and a value outside its
59
+ * range throws a `MountayaConfigurationError` naming the option and the value, before any
60
+ * request. `undefined` is an omitted member, never a value.
61
+ */
62
+ export interface PaginateOptions extends RequestOptions {
63
+ /**
64
+ * How many rows each request asks for, as a whole number from 1 to 100, the ceiling the API
65
+ * sets on a page. A smaller page is a faster first row and more requests for the whole listing.
66
+ *
67
+ * @default 50
68
+ */
69
+ readonly pageSize?: number | undefined;
70
+ /**
71
+ * The most requests one walk makes, as a whole number of 1 or more, for a caller who wants at
72
+ * most that much of the listing. A walk that reaches it ends there with no error and the rest
73
+ * of the listing unread. Left out, the walk reads to the listing's last page.
74
+ *
75
+ * @default none: the walk ends at the listing's last page.
76
+ */
77
+ readonly maxPages?: number | undefined;
78
+ }
79
+
80
+ /** One page as a walk reads it: its rows, and the cursor of the page after it. */
81
+ interface Page<T> {
82
+ readonly next: string | null;
83
+ readonly rows: readonly T[];
84
+ }
85
+
86
+ /**
87
+ * wholeNumberOption reads one numeric option of a walk, refusing a value that is not a whole
88
+ * number from 1 to `max`. Returns `fallback` for an omitted option.
89
+ *
90
+ * @throws `MountayaConfigurationError` naming the option and the value.
91
+ */
92
+ const wholeNumberOption = (
93
+ name: "maxPages" | "pageSize",
94
+ value: unknown,
95
+ max: number,
96
+ fallback: number,
97
+ ): number => {
98
+ if (value === undefined) {
99
+ return fallback;
100
+ }
101
+
102
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= max) {
103
+ return value;
104
+ }
105
+
106
+ const range = Number.isFinite(max) ? `from 1 to ${max}` : "of 1 or more";
107
+ const omitted = Number.isFinite(fallback)
108
+ ? `for the default of ${fallback}`
109
+ : "to walk to the listing's last page";
110
+
111
+ throw refuseOption(
112
+ name,
113
+ value,
114
+ `pass a whole number ${range}, or leave it out ${omitted}.`,
115
+ CONTEXT,
116
+ );
117
+ };
118
+
119
+ /**
120
+ * pageOf reads the rows and the next cursor out of one answer.
121
+ *
122
+ * Read member by member, because the transport types a body and does not validate it, and a
123
+ * caller outside the type system can pass an operation that takes no cursor. Such an operation
124
+ * answers the same rows whatever it is sent, so walking it would repeat its one page.
125
+ *
126
+ * @throws `MountayaConfigurationError` for an answer with no `data` list, or no string or null at
127
+ * `extensions.metadata.pagination.next_cursor`, which is what ends a walk with no `maxPages`.
128
+ */
129
+ const pageOf = <T>(answer: PagedResponse<T> | undefined): Page<T> => {
130
+ const rows = answer?.data;
131
+ const next: unknown = answer?.extensions?.metadata?.pagination?.next_cursor;
132
+
133
+ if (!Array.isArray(rows) || (typeof next !== "string" && next !== null)) {
134
+ throw new MountayaConfigurationError(
135
+ `${CONTEXT}: the operation answered no page: a paged listing answers a list at data and a cursor or null at extensions.metadata.pagination.next_cursor. Pass an operation that takes cursor and limit under query.`,
136
+ );
137
+ }
138
+
139
+ return { next, rows };
140
+ };
141
+
142
+ /**
143
+ * paginate walks a paged Map Studio listing and answers its rows one at a time, requesting each
144
+ * page as the rows before it are read.
145
+ *
146
+ * Every request carries the caller's `args` with the walk's own page under `query`: `limit` is
147
+ * `pageSize`, and `cursor` is where the walk has reached. On the first request that is the
148
+ * caller's own `query.cursor`, where it wrote one, so a walk resumes where an earlier one stopped;
149
+ * after it, the `next_cursor` the latest page named. A `limit` the caller wrote is replaced, and
150
+ * every other member of `args`, the filters and the `sort` under `query` included, is sent as
151
+ * given on every request: a cursor is bound to the filters and the order it was issued under, and
152
+ * the API refuses one sent with others. A page may hold fewer rows than it was asked for, and is
153
+ * followed by its cursor all the same, and so is a page that holds no row and names a cursor: the
154
+ * API cuts a page before it leaves out what the caller may not see, so an empty page can come
155
+ * before the rows that follow it, and only a null `next_cursor` ends a listing.
156
+ *
157
+ * The walk ends, with no further request, at the first of:
158
+ *
159
+ * - a page whose `next_cursor` is null;
160
+ * - `maxPages` requests made, where the caller states it, which leaves the rest of the listing
161
+ * unread;
162
+ * - a `next_cursor` the walk has already sent, which it refuses to follow: the iteration rejects
163
+ * with a `MountayaApiError`, since following it would read the listing again without end and
164
+ * stopping there would answer part of a listing as if it were the whole.
165
+ *
166
+ * An operation's failure rejects the iteration with the error the operation threw, and the rows
167
+ * already answered stay answered.
168
+ *
169
+ * `options.signal` is read before each request, and each request is made under it. Once it
170
+ * aborts, the walk requests no further page: the rows of a page already answered are still
171
+ * answered, and where the walk would have requested the next page it rejects with the signal's
172
+ * own reason, as an aborted call does, so a listing the abort cut short never reads as one read
173
+ * to its end. A walk with no page left to request ends as it would have, with no error.
174
+ *
175
+ * What it answers is iterable more than once, and each iteration walks the listing again from
176
+ * where the caller's own cursor starts it. No request is made until it is iterated, and a reader
177
+ * that stops early (a `break`) leaves the remaining pages unrequested. The API reads by keyset, so
178
+ * a row whose sort key does not change is neither skipped nor read twice, though a row a write
179
+ * moves across the cursor may be.
180
+ *
181
+ * `args` is typed by `operation`, so a member the operation does not declare (a `limit` beside a
182
+ * path parameter, a filter it does not take) is a type error, as it is in a call to the operation
183
+ * itself. `A` is read off the operation's parameter, and `NonNullable<A>` is an inference site of
184
+ * lower priority, which also drops the `undefined` of a parameter declared optional. It decides
185
+ * `A` only where `operation` declares nothing, which is a wrapper whose `args` parameter carries
186
+ * no type: there the arguments type the wrapper, and a member the operation does not declare can
187
+ * pass unrefused. Typing that parameter
188
+ * (`args: Parameters<typeof rest.getZones>[1]`) restores the check.
189
+ *
190
+ * @param operation - A method of the client that takes `cursor` and `limit` under `query`, such
191
+ * as `mountaya.studio.zones.getZones`, or one the admin unit binds, such as
192
+ * `new MountayaAdmin(mountaya).members.getOrganizationMembers`. An operation that takes no
193
+ * cursor answers
194
+ * no {@link PagedResponse}, so it is a type error here. A free function takes its transport
195
+ * first, so it is passed wrapped: `(args, options) => rest.getZones(transport, args, options)`.
196
+ * @param args - The operation's own arguments: its path parameters, and any filter, `sort` or
197
+ * starting `cursor` under `query`. `{}` for an operation that requires none.
198
+ * @param options - The walk's `pageSize` and `maxPages`, and the `retry`, `signal` and
199
+ * `timeoutMs` each request is made under.
200
+ * @returns The listing's rows, in the listing's order, typed as the operation's own.
201
+ * @throws `MountayaConfigurationError` when called, for an `operation` that is not a function,
202
+ * for `args` or `options` that are not an object, or for a `pageSize` or a `maxPages` outside
203
+ * its range; and while iterating, for an operation that answers no page, and a
204
+ * `MountayaApiError` for a `next_cursor` the walk has already sent.
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * const itineraries = [];
209
+ * for await (const itinerary of paginate(mountaya.studio.itineraries.getItineraries, {
210
+ * query: { organization_id, sort: "-updated_at" },
211
+ * })) {
212
+ * itineraries.push(itinerary);
213
+ * }
214
+ * ```
215
+ */
216
+ export const paginate = <A extends object | undefined, T>(
217
+ operation: (args: A, options?: RequestOptions) => Promise<PagedResponse<T>>,
218
+ args: NonNullable<A>,
219
+ options: PaginateOptions = {},
220
+ ): AsyncIterable<T> => {
221
+ // All three are used below, and a caller outside the type system can pass each as anything: a
222
+ // method name mistyped there reads `undefined`.
223
+ if (typeof operation !== "function") {
224
+ throw refuseOption(
225
+ "operation",
226
+ operation,
227
+ "pass a method of the client that takes cursor and limit under query, such as mountaya.studio.itineraries.getItineraries.",
228
+ CONTEXT,
229
+ );
230
+ }
231
+
232
+ if (typeof args !== "object" || args === null) {
233
+ throw refuseOption(
234
+ "args",
235
+ args,
236
+ "pass the operation's own arguments as an object, {} where it takes none.",
237
+ CONTEXT,
238
+ );
239
+ }
240
+
241
+ if (typeof options !== "object" || options === null) {
242
+ throw refuseOption(
243
+ "options",
244
+ options,
245
+ "pass an object such as { pageSize: 25 }, or leave it out for the defaults.",
246
+ CONTEXT,
247
+ );
248
+ }
249
+
250
+ const pageSize = wholeNumberOption(
251
+ "pageSize",
252
+ options.pageSize,
253
+ MAX_PAGE_SIZE,
254
+ DEFAULT_PAGE_SIZE,
255
+ );
256
+ const maxPages = wholeNumberOption(
257
+ "maxPages",
258
+ options.maxPages,
259
+ Number.POSITIVE_INFINITY,
260
+ Number.POSITIVE_INFINITY,
261
+ );
262
+ const { retry, signal, timeoutMs } = options;
263
+ // What the caller wrote under `query`, read as the object it is where there is one: its page is
264
+ // replaced below and its other members are sent on. A `query` that is no object, which only a
265
+ // caller outside the type system can pass, holds no member to send on.
266
+ const written: Record<string, unknown> | undefined =
267
+ "query" in args && typeof args.query === "object" && args.query !== null
268
+ ? { ...args.query }
269
+ : undefined;
270
+ const { cursor: start, limit: _replaced, ...query } = written ?? {};
271
+
272
+ return {
273
+ async *[Symbol.asyncIterator]() {
274
+ // The caller's own cursor, where it wrote one, starts the walk where an earlier one stopped.
275
+ let cursor: string | undefined = typeof start === "string" ? start : undefined;
276
+ const sent = new Set<string | undefined>();
277
+
278
+ for (let requested = 0; requested < maxPages; requested += 1) {
279
+ // Checked here as well as by the request: an operation already answered has nothing left
280
+ // to abort, and the next page is a request the caller has walked away from.
281
+ if (signal?.aborted === true) {
282
+ throw abortReasonOf(signal);
283
+ }
284
+
285
+ sent.add(cursor);
286
+ const { next, rows } = pageOf(
287
+ await operation(
288
+ {
289
+ ...args,
290
+ query: { ...query, ...(cursor === undefined ? {} : { cursor }), limit: pageSize },
291
+ },
292
+ { retry, signal, timeoutMs },
293
+ ),
294
+ );
295
+
296
+ for (const row of rows) {
297
+ yield row;
298
+ }
299
+
300
+ if (next === null) {
301
+ return;
302
+ }
303
+
304
+ if (sent.has(next)) {
305
+ throw new MountayaApiError(
306
+ `${CONTEXT}: the listing named the cursor ${JSON.stringify(next)} again, which this walk already followed, so following it would read the listing again without end. Read the listing again from its start.`,
307
+ 200,
308
+ [],
309
+ );
310
+ }
311
+
312
+ cursor = next;
313
+ }
314
+ },
315
+ };
316
+ };