@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,870 @@
1
+ import type { Session } from "../../rest/schema.gen.js";
2
+ import {
3
+ describeType,
4
+ MountayaConfigurationError,
5
+ MountayaConnectionError,
6
+ refuseOption,
7
+ } from "../rules/errors.js";
8
+ import { printsAs, redactedSessionToken } from "../rules/redaction.js";
9
+ import { readSessionAnswer, type SessionAnswer } from "../rules/sessionAnswer.js";
10
+ import { MAX_TIMER_MS, REFRESH_MARGIN_MS, refreshSchedule } from "../rules/sessionSchedule.js";
11
+
12
+ /**
13
+ * The session-token lifecycle: mint, schedule, refresh before expiry, back off when a token
14
+ * arrives already spent.
15
+ *
16
+ * A session token scopes a publishable key up to an organization. Minting it means exchanging a
17
+ * **secret** key, which can only happen on a server, so nothing here holds one. It takes a `mint`
18
+ * callback that calls the application's own endpoint and owns the part that is genuinely fiddly
19
+ * and identical for every consumer: refreshing BEFORE expiry rather than after a 401.
20
+ *
21
+ * Refreshing on 401 is the arrangement people reach for first, and it fails in the way that is
22
+ * hardest to reproduce: the token expires mid-flight on one request out of a burst, so one call
23
+ * in a page load fails while its neighbours succeed.
24
+ *
25
+ * It is a state machine and no framework's work: a generation counter, a chained timer and a
26
+ * doubling backoff. None of the subtleties it records is a framework decision: a long wait is
27
+ * walked down in hops so a suspended tab wakes to a re-read clock, the refresh margin is capped
28
+ * at half a token's life so a thirty-second token does not schedule at zero, and each
29
+ * consecutive failed mint or spent token doubles the wait so an endpoint that is down, or a
30
+ * skewed clock, costs that endpoint one slow loop instead of a call every five seconds. So the
31
+ * machine is here, in the package that has no framework, and a React, Vue, Svelte or Solid hook
32
+ * is a binding over it.
33
+ * `getSnapshot` and `subscribe` are `useSyncExternalStore`'s two arguments exactly. Nothing in
34
+ * this file imports React or touches a DOM node, so a Node process, a worker, or a CLI that
35
+ * holds a long-lived client can keep a token fresh the same way a component does.
36
+ */
37
+
38
+ /**
39
+ * SessionTokenSnapshot is what a surface reads, and what `useSyncExternalStore` compares by
40
+ * reference.
41
+ *
42
+ * One object rather than four subscriptions, and it is replaced rather than mutated on every
43
+ * change, so a binding that holds the previous one can tell that something moved.
44
+ *
45
+ * A snapshot prints its token by its prefix alone, `sess_…`, wherever it is printed:
46
+ * `JSON.stringify`, `String`, and `console.log` or Node's `util.inspect`. `token` reads the token
47
+ * itself, as a request carries it.
48
+ */
49
+ export interface SessionTokenSnapshot {
50
+ /**
51
+ * The last mint failure: what the mint rejected with, or a `MountayaConnectionError` where it
52
+ * answered no session or did not answer within the margin. Minting is retried on schedule, except
53
+ * after a mint the application cancelled, which ends that run of minting.
54
+ */
55
+ readonly error: unknown;
56
+ /**
57
+ * When the current token expires, which can be an instant already PAST when the server hands
58
+ * one back that way: the engine answers that by backing off between mints rather than
59
+ * re-minting on a fixed floor.
60
+ */
61
+ readonly expiresAt: Date | undefined;
62
+ /**
63
+ * Whether a token is on its way: a mint is out, or the engine is enabled, holds no token and
64
+ * mints as soon as something subscribes to it. A request made through a client whose
65
+ * credential holds this engine waits for that token while none is held, and the client's
66
+ * `credentialScope` reads the same flag, so the scope a read is keyed under says a session
67
+ * wherever the read carries one.
68
+ */
69
+ readonly isLoading: boolean;
70
+ /** The current token, or undefined before the first mint completes. */
71
+ readonly token: string | undefined;
72
+ /**
73
+ * The user the current token was minted for, its mint's `user_id`: `null` where the token is
74
+ * minted without `user_id`, and undefined where no token is held or the mint did not say. A
75
+ * client whose credential holds this engine refuses locally a call that acts as a member while it
76
+ * reads `null`, since the API would answer that call with a 401.
77
+ */
78
+ readonly userId: string | null | undefined;
79
+ }
80
+
81
+ /** SessionTokenEngineOptions are what a {@link SessionTokenEngine} is built with. */
82
+ export interface SessionTokenEngineOptions {
83
+ /**
84
+ * Set false to stop minting, while signed out for example.
85
+ *
86
+ * Disabling clears the token, its expiry and the last error, so a signed-out consumer cannot
87
+ * keep reading the signed-in user's credential off the snapshot. {@link
88
+ * SessionTokenEngine.refresh} is a no-op while disabled.
89
+ *
90
+ * @default true
91
+ */
92
+ readonly enabled?: boolean | undefined;
93
+ /**
94
+ * Mints a token by calling your server, which holds the secret key.
95
+ *
96
+ * Your endpoint should call `POST /v1/sessions` with `{ publishable_key }` and return the
97
+ * `{ token, expires_at, user_id }` it receives. A call that acts as a member, as every
98
+ * `studio-embedded` operation and every `management` write does, needs a token minted for that
99
+ * member: your endpoint adds `user_id`, the user it signed in, and every request made with the
100
+ * token acts as that user. It reads that user from its own session and never from the request,
101
+ * so a page cannot ask for a token naming somebody else. Reject where the endpoint fails: an
102
+ * answer that holds no token string, or no `expires_at` to read, is taken for a failed mint, so
103
+ * `error` is set, the token in hand is kept, and the mint is tried again five seconds later,
104
+ * each failure in a row waiting twice as long as the last, up to a minute, until a mint answers
105
+ * a token with life left. A timeout set on the call, such as `AbortSignal.timeout`'s, which
106
+ * rejects with a `TimeoutError`, is a failed mint like any other.
107
+ *
108
+ * Each mint is handed `call`, the controller it runs under: hand its `signal` to the request,
109
+ * and abort it to cancel the mint. The engine never aborts it itself. A mint you cancel ends that
110
+ * run of minting instead of failing: one whose `call` you abort, with a reason of your own or
111
+ * none, and one that rejects with an `AbortError`, as `fetch` does once a signal of your own
112
+ * aborts with no reason. A reason named `TimeoutError` is a timeout you set, and that mint failed.
113
+ * `error` is the cancellation, the token in hand is kept, nothing is minting, so a request
114
+ * waiting for a first token goes on at once, and nothing is minted until
115
+ * {@link SessionTokenEngine.refresh}, a new subscriber, or enabling an engine that was disabled.
116
+ * A signal of your own aborted with a reason of its own rejects with that reason alone, which
117
+ * nothing tells from a failure: abort `call` to cancel with a reason.
118
+ *
119
+ * `expires_at` is read as a `Date`, as the string JSON makes of one, or as a number of
120
+ * milliseconds since the epoch, and `user_id` as the snapshot's `userId`. A token for an
121
+ * Embedded Studio, the editor and its read-only viewer alike, is minted with
122
+ * `surface: "studio-embedded"` beside them.
123
+ */
124
+ readonly mint: (call: AbortController) => Promise<Session>;
125
+ }
126
+
127
+ /** The name a refusal says an option was passed to. */
128
+ const CONTEXT = "SessionTokenEngine";
129
+
130
+ /**
131
+ * assertMint refuses a `mint` that is not a function, which would otherwise be called at the first
132
+ * mint and reported through a snapshot's error, far from the line that wrote it.
133
+ *
134
+ * @throws `MountayaConfigurationError` naming `mint` and the value.
135
+ */
136
+ const assertMint = (mint: unknown): void => {
137
+ if (typeof mint !== "function") {
138
+ throw refuseOption(
139
+ "mint",
140
+ mint,
141
+ "pass a function that calls your session endpoint and answers its { token, expires_at, user_id }.",
142
+ CONTEXT,
143
+ );
144
+ }
145
+ };
146
+
147
+ /**
148
+ * assertEnabled refuses an `enabled` that is neither a boolean nor `undefined`.
149
+ *
150
+ * @throws `MountayaConfigurationError` naming `enabled` and the value.
151
+ */
152
+ const assertEnabled = (enabled: unknown): void => {
153
+ if (enabled !== undefined && typeof enabled !== "boolean") {
154
+ throw refuseOption(
155
+ "enabled",
156
+ enabled,
157
+ "pass true to mint, false to stop, or leave it out to mint.",
158
+ CONTEXT,
159
+ );
160
+ }
161
+ };
162
+
163
+ /**
164
+ * snapshotOf makes `fields` a snapshot: a copy of them that prints its token by its prefix alone
165
+ * (see {@link printsAs}). Every snapshot the engine commits is made here, since a spread of the one
166
+ * before copies its members and not the way it prints.
167
+ */
168
+ const snapshotOf = (fields: SessionTokenSnapshot): SessionTokenSnapshot =>
169
+ printsAs({ ...fields }, (snapshot) => ({
170
+ ...snapshot,
171
+ token: snapshot.token === undefined ? undefined : redactedSessionToken(snapshot.token),
172
+ }));
173
+
174
+ /** The snapshot of an engine that is disabled or disposed: no token, and none on its way. */
175
+ const emptySnapshot: SessionTokenSnapshot = snapshotOf({
176
+ error: undefined,
177
+ expiresAt: undefined,
178
+ isLoading: false,
179
+ token: undefined,
180
+ userId: undefined,
181
+ });
182
+
183
+ /**
184
+ * isCancellation reports whether a mint ended because the application cancelled it: it rejected
185
+ * with an `AbortError`, what `fetch` rejects with once the signal it was given aborts with no
186
+ * reason of its own, and what a runtime's own abort is named everywhere, a `DOMException` or, where
187
+ * the runtime has none, an `Error`. A `TimeoutError` is no cancellation: a signal such as
188
+ * `AbortSignal.timeout` aborts with one at a deadline the application set, and that mint failed.
189
+ * Read by `name`, so an abort another realm raised is read the same way.
190
+ */
191
+ const isCancellation = (failure: unknown): boolean =>
192
+ typeof failure === "object" &&
193
+ failure !== null &&
194
+ "name" in failure &&
195
+ failure.name === "AbortError";
196
+
197
+ /**
198
+ * The instant a timer is armed for, and what it does when that instant is reached: a scheduled
199
+ * mint, or the abandonment of a mint that has not settled.
200
+ */
201
+ interface Deadline {
202
+ readonly at: number;
203
+ readonly fire: () => void;
204
+ /**
205
+ * Whether the deadline is the retry of a mint that failed or was abandoned. Such a wait is the
206
+ * engine's own guess at when the endpoint answers again, so
207
+ * {@link SessionTokenEngine.checkNow} does not sit it out.
208
+ */
209
+ readonly retriesFailure: boolean;
210
+ }
211
+
212
+ /** A mint call that is out, with the controller it runs under and the instant it started at. */
213
+ interface MintCall {
214
+ readonly answer: Promise<unknown>;
215
+ readonly controller: AbortController;
216
+ readonly startedAt: number;
217
+ }
218
+
219
+ /**
220
+ * abortedByApplication reports whether the application aborted the controller a mint call runs
221
+ * under, which is a cancellation whatever reason it gives, but for a reason named `TimeoutError`:
222
+ * a deadline the application set, and that mint failed. The engine never aborts the controller
223
+ * itself, so an abort of it is the application's.
224
+ */
225
+ const abortedByApplication = ({ controller: { signal } }: MintCall): boolean =>
226
+ signal.aborted &&
227
+ !(
228
+ typeof signal.reason === "object" &&
229
+ signal.reason !== null &&
230
+ "name" in signal.reason &&
231
+ signal.reason.name === "TimeoutError"
232
+ );
233
+
234
+ /**
235
+ * surfaceFault hands a listener's own fault to the runtime as an uncaught error, on a microtask.
236
+ *
237
+ * A listener that throws is a defect of the program that subscribed it. Thrown through the
238
+ * engine it would read as the mint failing, and dropped it would hide the defect, so it leaves
239
+ * the engine's flow and reaches the program's own uncaught-error handling.
240
+ */
241
+ const surfaceFault = (fault: unknown): void => {
242
+ queueMicrotask(() => {
243
+ throw fault;
244
+ });
245
+ };
246
+
247
+ /**
248
+ * SessionTokenEngine keeps a session token fresh: it mints through the application's own
249
+ * endpoint, refreshes a margin before expiry, backs off from mints that fail and tokens that
250
+ * arrive already spent, and abandons a mint that does not settle.
251
+ *
252
+ * A credential takes it as its `sessionToken`, where a request made while its first mint is out
253
+ * waits for the token: {@link SessionTokenSource} states that contract and shows the wiring.
254
+ *
255
+ * `getSnapshot` and `subscribe` are `useSyncExternalStore`'s two arguments; the first subscriber
256
+ * starts it and the last unsubscribe parks it, and {@link SessionTokenEngine.dispose} latches it
257
+ * for an owner that is not a component. One mint is awaited at a time: a
258
+ * {@link SessionTokenEngine.refresh} or a {@link SessionTokenEngine.checkNow} while one is out
259
+ * joins it, and so does a subscriber that resumes the engine while the mint a park left behind is
260
+ * still out. A mint retired by a disable or an abandonment writes nothing when it answers, and
261
+ * one a park retired writes only for the subscriber that resumed it.
262
+ *
263
+ * A mint's answer is read through {@link readSessionAnswer}: one that holds no token, or no
264
+ * expiry to read, is a failed mint. A mint that fails is minted again on the engine's own
265
+ * schedule, a timeout the application set on its own call among them, and one the application
266
+ * cancels is not: it ends that run of minting, and the next mint is a refresh's, a new
267
+ * subscriber's or an enable's (see {@link SessionTokenEngineOptions.mint}). A listener that throws
268
+ * changes nothing here: every listener is still told, and the fault reaches the runtime as the
269
+ * program's own uncaught error.
270
+ *
271
+ * A subscriber reads the snapshot it subscribed at, then each change, and one that reads nothing
272
+ * for a while reads the newest when it next reads, never a snapshot it missed: `getSnapshot`
273
+ * answers the snapshot held now, and a listener is told after the snapshot it is told of is in
274
+ * place.
275
+ */
276
+ export class SessionTokenEngine {
277
+ private mintFn: (call: AbortController) => Promise<Session>;
278
+ private enabled: boolean;
279
+
280
+ private snapshot: SessionTokenSnapshot;
281
+ private readonly listeners = new Set<() => void>();
282
+
283
+ /**
284
+ * Whether anything is watching. An engine with no listener mints nothing: {@link
285
+ * SessionTokenEngine.subscribe} says why that is the lifecycle rather than a method pair.
286
+ */
287
+ private parked = true;
288
+
289
+ /** The latch an owner that is not a component closes. See {@link dispose}. */
290
+ private disposed = false;
291
+
292
+ /**
293
+ * Whether the application cancelled the last mint, which ended that run of minting: nothing is
294
+ * armed and nothing mints until a refresh, a new subscriber or an enable starts a run again.
295
+ */
296
+ private cancelled = false;
297
+
298
+ private timer: ReturnType<typeof setTimeout> | null = null;
299
+
300
+ /**
301
+ * What the armed timer is for, held as the instant rather than the timer, so
302
+ * {@link SessionTokenEngine.checkNow} can re-read the clock against it. Undefined where nothing
303
+ * is armed.
304
+ */
305
+ private deadline: Deadline | undefined = undefined;
306
+
307
+ /**
308
+ * Whether a mint of the current generation is out. It is what a refresh joins: a mint already
309
+ * on its way answers the question a second one would ask.
310
+ */
311
+ private minting = false;
312
+
313
+ /**
314
+ * The mint call that has not answered yet, kept across a park so that a resume joins it rather
315
+ * than calling the application's endpoint a second time. A disable and an abandonment drop it:
316
+ * the next mint is then a call of its own.
317
+ */
318
+ private call: MintCall | undefined = undefined;
319
+
320
+ /**
321
+ * A generation counter, so a mint still in flight when the engine parks, is disabled or
322
+ * abandons it cannot write its result over a newer one. Comparing generations is what makes an
323
+ * out-of-order response harmless rather than a token that goes backwards.
324
+ */
325
+ private generation = 0;
326
+
327
+ /**
328
+ * How many mints in a row have failed, been abandoned or answered a token with no usable
329
+ * lifetime left, which is what the wait between them doubles on. Only a mint of the current
330
+ * generation touches it, below the generation check: a retired mint must not be able to stretch
331
+ * the schedule of the run that replaced it, for the same reason it must not be able to write
332
+ * its token.
333
+ */
334
+ private backoff = 0;
335
+
336
+ /**
337
+ * Builds an engine over the application's `mint`. It mints nothing until something subscribes.
338
+ *
339
+ * @param options - The `mint` callback, and whether minting starts `enabled`.
340
+ * @throws `MountayaConfigurationError` for options that are not an object, a `mint` that is not
341
+ * a function, or an `enabled` that is neither a boolean nor `undefined`, naming the option and
342
+ * the value.
343
+ */
344
+ constructor(options: SessionTokenEngineOptions) {
345
+ // Typed as the options, and still whatever a JavaScript caller passed.
346
+ const given: unknown = options;
347
+ if (typeof given !== "object" || given === null) {
348
+ throw new MountayaConfigurationError(
349
+ `${CONTEXT}: options is ${describeType(given)}; pass { mint }, a function that calls your session endpoint.`,
350
+ );
351
+ }
352
+
353
+ assertMint(options.mint);
354
+ assertEnabled(options.enabled);
355
+ this.mintFn = options.mint;
356
+ this.enabled = options.enabled ?? true;
357
+ // Enabled, the engine mints on its first subscriber, so a token is on its way from here.
358
+ this.snapshot = this.enabled
359
+ ? snapshotOf({ ...emptySnapshot, isLoading: true })
360
+ : emptySnapshot;
361
+ }
362
+
363
+ /** getSnapshot returns the current snapshot, by reference and stable between changes. */
364
+ getSnapshot(): SessionTokenSnapshot {
365
+ return this.snapshot;
366
+ }
367
+
368
+ /**
369
+ * subscribe registers a listener for every change, and returns its own unsubscribe.
370
+ *
371
+ * **The listeners are the lifecycle.** A mint fires when minting is enabled and somebody is
372
+ * watching; dropping the last listener retires the in-flight mint and clears the timer, and
373
+ * subscribing again starts a fresh cycle. That is what a credential with nobody holding it
374
+ * should do anyway, and it is the only teardown a React binding can express correctly: React
375
+ * tears an effect down and sets it up again with the same object under StrictMode, so a latch
376
+ * here would leave a live surface bound to a dead engine. {@link dispose} is the latch,
377
+ * for an owner that is not a component.
378
+ *
379
+ * A fresh cycle joins the mint the park left out, where that mint has been out for less than
380
+ * the refresh margin: the doubled effect of a development mount then costs the application's
381
+ * endpoint one call, and the mint is still abandoned a margin after it started. A subscriber
382
+ * that arrives once the application cancelled a mint starts a run of minting again, as the first
383
+ * one does.
384
+ *
385
+ * **A binding must hand its framework a stable `subscribe`.** A fresh closure per render
386
+ * unsubscribes and re-subscribes on every one, and with the lifecycle on this method that is
387
+ * a mint retired and re-fired per render.
388
+ *
389
+ * @param listener - Called after every change of the snapshot, with no argument.
390
+ * @returns The function that removes this listener, and parks the engine when it is the last.
391
+ */
392
+ subscribe(listener: () => void): () => void {
393
+ this.listeners.add(listener);
394
+
395
+ if ((this.parked || this.cancelled) && !this.disposed) {
396
+ this.parked = false;
397
+ void this.run();
398
+ }
399
+
400
+ return () => {
401
+ this.listeners.delete(listener);
402
+
403
+ if (this.listeners.size > 0 || this.parked) {
404
+ return;
405
+ }
406
+
407
+ this.parked = true;
408
+ this.park();
409
+ };
410
+ }
411
+
412
+ /**
413
+ * refresh mints now, replacing any pending refresh, or joins the mint already out.
414
+ *
415
+ * Joining is what keeps a burst of refreshes, a retry button pressed twice or several surfaces
416
+ * asking at once, to one call to the application's endpoint: the mint on its way answers every
417
+ * one of them. The current token stays readable until the new one arrives, so a consumer
418
+ * holding a client built from it keeps working across the call rather than losing its
419
+ * credential for the duration of a round trip. A no-op while disabled or parked; once the
420
+ * application cancelled a mint, it is what mints again.
421
+ *
422
+ * Deliberately not a backoff reset. A retry button is exactly what a user presses while the
423
+ * endpoint is handing out expired tokens, so resetting here would hand them a way to hold the
424
+ * interval at five seconds by pressing it: the protection is for the application's endpoint,
425
+ * and a caller cannot be the one to lift it.
426
+ */
427
+ refresh(): void {
428
+ if (this.minting) {
429
+ return;
430
+ }
431
+
432
+ void this.run();
433
+ }
434
+
435
+ /**
436
+ * checkNow re-reads the wall clock against the armed deadline: one already passed fires now,
437
+ * and one still ahead is re-armed from the clock as it reads now.
438
+ *
439
+ * It is what a binding calls when the page comes back (visible again, online again, restored
440
+ * from the back-forward cache), because a suspended machine runs no timer. It wakes with the
441
+ * clock past the deadline and the next hop still minutes away, holding a token that may have
442
+ * expired during the sleep, and this replaces it before a request carries it. A mint already
443
+ * out is joined: its own deadline is re-read, and it is abandoned only once it has been out
444
+ * longer than the margin. A no-op while disabled, parked or disposed, and once the application
445
+ * cancelled a mint, which leaves nothing armed.
446
+ *
447
+ * The one deadline it does not wait for is the retry of a mint that failed or was abandoned:
448
+ * that mint is made now. A machine that wakes offline mints and fails, and the page coming back
449
+ * online is the moment the mint can succeed, before the retry would have tried it.
450
+ */
451
+ checkNow(): void {
452
+ const deadline = this.deadline;
453
+ if (!this.enabled || this.parked || this.disposed || deadline === undefined) {
454
+ return;
455
+ }
456
+
457
+ if (Date.now() < deadline.at && !deadline.retriesFailure) {
458
+ this.armAt(deadline);
459
+
460
+ return;
461
+ }
462
+
463
+ this.disarm();
464
+ deadline.fire();
465
+ }
466
+
467
+ /**
468
+ * setMint replaces the callback without disturbing the schedule.
469
+ *
470
+ * A binding calls this on every commit, from an effect, because the callback is usually an
471
+ * inline arrow and therefore a new function each render. Replacing it must not re-mint: an
472
+ * engine that restarted its cycle whenever the closure changed would loop, and the loop
473
+ * reads like a server problem rather than like a dependency-list one.
474
+ *
475
+ * @throws `MountayaConfigurationError` for a `mint` that is not a function.
476
+ */
477
+ setMint(mint: (call: AbortController) => Promise<Session>): void {
478
+ assertMint(mint);
479
+ this.mintFn = mint;
480
+ }
481
+
482
+ /**
483
+ * setEnabled turns minting on or off.
484
+ *
485
+ * Disabling retires the in-flight mint, clears the timer and returns the snapshot to the
486
+ * shape it had before the first mint, so a signed-out consumer cannot keep reading the
487
+ * signed-in user's credential. The error goes with the token: `error` promises a retry is
488
+ * scheduled, and while disabled none is. The backoff goes too: it counts one run of
489
+ * unusable tokens, and a consumer signing back in later is starting a new run rather than
490
+ * continuing that one.
491
+ *
492
+ * Setting the value it already holds does nothing, which is what lets a binding call it from
493
+ * an effect without guarding.
494
+ *
495
+ * @throws `MountayaConfigurationError` for a value that is neither a boolean nor `undefined`,
496
+ * which reads as `true`, the option's default.
497
+ */
498
+ setEnabled(enabled: boolean): void {
499
+ // Typed as a boolean, and still whatever a JavaScript caller passed: `undefined` reads as the
500
+ // option's own default, which is to mint.
501
+ const given: unknown = enabled;
502
+ assertEnabled(given);
503
+ const next = given !== false;
504
+ if (this.enabled === next) {
505
+ return;
506
+ }
507
+
508
+ this.enabled = next;
509
+
510
+ if (!next) {
511
+ this.retire();
512
+ // The mint in flight belongs to the session that ends here, and the next one enabled may
513
+ // be another person's, so it is never joined.
514
+ this.call = undefined;
515
+ this.backoff = 0;
516
+ // One commit rather than two: `emptySnapshot` already reports idle, so the fix-up
517
+ // `park` does for a teardown is not needed on this path.
518
+ this.commit(emptySnapshot);
519
+
520
+ return;
521
+ }
522
+
523
+ if (this.disposed) {
524
+ return;
525
+ }
526
+
527
+ if (!this.parked) {
528
+ void this.run();
529
+
530
+ return;
531
+ }
532
+
533
+ // Nobody holds the engine, so nothing mints yet; its next subscriber mints at once.
534
+ this.reportResting();
535
+ }
536
+
537
+ /**
538
+ * dispose retires the in-flight mint, drops the timer, clears the token and latches the
539
+ * engine shut.
540
+ *
541
+ * For an owner that is not a component. A React binding must NOT call this: unsubscribing is
542
+ * its teardown, because StrictMode tears an effect down and sets it up again with the same
543
+ * object. The snapshot returns to the shape a disabled engine has, so a client whose credential
544
+ * still holds the engine sends no token from here, and every listener is told of it before the
545
+ * listeners are dropped.
546
+ */
547
+ dispose(): void {
548
+ if (this.disposed) {
549
+ return;
550
+ }
551
+
552
+ this.disposed = true;
553
+ this.parked = true;
554
+ this.retire();
555
+ this.call = undefined;
556
+ this.backoff = 0;
557
+ this.commit(emptySnapshot);
558
+ this.listeners.clear();
559
+ }
560
+
561
+ // -----------------------------------------------------------------------------------------
562
+
563
+ /**
564
+ * commit replaces the snapshot and notifies, skipping a notification when nothing moved.
565
+ *
566
+ * It never throws: every listener is told, and the first fault one of them throws is handed to
567
+ * {@link surfaceFault} once they all have been, so no caller here has to decide what a
568
+ * listener's exception does to a mint.
569
+ */
570
+ private commit(next: SessionTokenSnapshot): void {
571
+ if (next === this.snapshot) {
572
+ return;
573
+ }
574
+
575
+ this.snapshot = next;
576
+
577
+ let fault: { readonly thrown: unknown } | undefined;
578
+ for (const listener of this.listeners) {
579
+ try {
580
+ listener();
581
+ } catch (thrown) {
582
+ fault ??= { thrown };
583
+ }
584
+ }
585
+
586
+ if (fault !== undefined) {
587
+ surfaceFault(fault.thrown);
588
+ }
589
+ }
590
+
591
+ /** disarm drops the armed timer and the deadline it was for. */
592
+ private disarm(): void {
593
+ if (this.timer !== null) {
594
+ clearTimeout(this.timer);
595
+ this.timer = null;
596
+ }
597
+
598
+ this.deadline = undefined;
599
+ }
600
+
601
+ /** retire drops the timer and bumps the generation, so nothing in flight can still write. */
602
+ private retire(): void {
603
+ this.generation += 1;
604
+ this.minting = false;
605
+ this.disarm();
606
+ }
607
+
608
+ /** park retires whatever is in flight and reports what a request made now would wait for. */
609
+ private park(): void {
610
+ this.retire();
611
+ this.reportResting();
612
+ }
613
+
614
+ /**
615
+ * reportResting sets `isLoading` for an engine nobody holds: a token is on its way where the
616
+ * engine is enabled, not disposed and holds none, since its next subscriber mints at once, and
617
+ * none is otherwise.
618
+ *
619
+ * A teardown has to set the flag itself. `run`'s own settle lowers it only for the current
620
+ * generation, which is correct while a NEWER run is taking over, since that one raised the flag
621
+ * for itself; but parking bumps the generation and starts nothing. Without this, a park while a
622
+ * mint is out leaves the flag up with a token held, and a request made then would read a token
623
+ * as both held and on its way.
624
+ */
625
+ private reportResting(): void {
626
+ const onItsWay = this.enabled && !this.disposed && this.snapshot.token === undefined;
627
+ if (this.snapshot.isLoading !== onItsWay) {
628
+ this.commit(snapshotOf({ ...this.snapshot, isLoading: onItsWay }));
629
+ }
630
+ }
631
+
632
+ /**
633
+ * armAt arms a deadline, replacing whatever was armed.
634
+ *
635
+ * The deadline is held as an absolute instant and walked down in MAX_TIMER_MS hops, so what
636
+ * survives a throttled or suspended tab is the DEADLINE rather than a timer. Each hop
637
+ * re-reads the clock; the deadline fires on the first hop that finds it passed.
638
+ */
639
+ private armAt(deadline: Deadline): void {
640
+ this.disarm();
641
+ this.deadline = deadline;
642
+
643
+ const hop = (): void => {
644
+ const remaining = deadline.at - Date.now();
645
+ if (remaining <= 0) {
646
+ this.timer = null;
647
+ this.deadline = undefined;
648
+ deadline.fire();
649
+
650
+ return;
651
+ }
652
+
653
+ this.timer = setTimeout(hop, Math.min(MAX_TIMER_MS, remaining));
654
+ };
655
+
656
+ this.timer = setTimeout(hop, Math.min(MAX_TIMER_MS, Math.max(0, deadline.at - Date.now())));
657
+ }
658
+
659
+ /**
660
+ * armRefresh arms the next mint `delay` milliseconds from now, replacing whatever was armed.
661
+ * `retriesFailure` marks the wait after a mint that failed or was abandoned.
662
+ */
663
+ private armRefresh(delay: number, retriesFailure = false): void {
664
+ this.armAt({
665
+ at: Date.now() + delay,
666
+ fire: () => {
667
+ void this.run();
668
+ },
669
+ retriesFailure,
670
+ });
671
+ }
672
+
673
+ /**
674
+ * callOut answers the mint call a park left out, where a run can still join it: one that
675
+ * started less than a margin ago. A call out for a margin or longer is the one {@link abandon}
676
+ * gives up on, so it is not joined.
677
+ */
678
+ private callOut(): MintCall | undefined {
679
+ const out = this.call;
680
+
681
+ return out !== undefined && Date.now() - out.startedAt < REFRESH_MARGIN_MS ? out : undefined;
682
+ }
683
+
684
+ /**
685
+ * startCall calls the application's mint with the controller the call runs under, and holds the
686
+ * call until it answers. A mint that throws rather than rejecting is read as one that rejected.
687
+ */
688
+ private startCall(): MintCall {
689
+ const controller = new AbortController();
690
+ let answer: Promise<unknown>;
691
+ try {
692
+ answer = Promise.resolve(this.mintFn(controller));
693
+ } catch (cause) {
694
+ answer = Promise.reject(cause);
695
+ }
696
+
697
+ const call: MintCall = { answer, controller, startedAt: Date.now() };
698
+ this.call = call;
699
+
700
+ const settle = (): void => {
701
+ if (this.call === call) {
702
+ this.call = undefined;
703
+ }
704
+ };
705
+ answer.then(settle, settle);
706
+
707
+ return call;
708
+ }
709
+
710
+ /**
711
+ * abandon gives up on the mint of `generation`, still out a margin after it started: it is
712
+ * retired so a late answer writes nothing, the failure is recorded, and a mint is tried again
713
+ * as after one that failed outright, the abandoned mint counting in the same run.
714
+ *
715
+ * The margin is the bound because it is the headroom a token is refreshed with: a mint out for
716
+ * longer has cost the token that headroom, and one that never settles would otherwise hold the
717
+ * engine loading, with nothing scheduled, until the token lapsed.
718
+ */
719
+ private abandon(generation: number): void {
720
+ if (generation !== this.generation) {
721
+ return;
722
+ }
723
+
724
+ this.retire();
725
+ this.call = undefined;
726
+ this.backoff += 1;
727
+ const delayMs = refreshSchedule({ consecutiveSpent: this.backoff }).delayMs;
728
+ // Armed before the commit, so a listener that refreshes from inside it starts a run that
729
+ // replaces this schedule rather than one this schedule replaces.
730
+ this.armRefresh(delayMs, true);
731
+ this.commit(
732
+ snapshotOf({
733
+ ...this.snapshot,
734
+ error: new MountayaConnectionError(
735
+ `mint: no answer within ${REFRESH_MARGIN_MS} ms, so the mint is abandoned and tried again in ${delayMs} ms. Check that the endpoint it calls answers.`,
736
+ ),
737
+ isLoading: false,
738
+ }),
739
+ );
740
+ }
741
+
742
+ /** run mints once and schedules the next attempt from what came back. */
743
+ private async run(): Promise<void> {
744
+ // A run that cannot start retires nothing either, hence the guard ahead of the generation
745
+ // bump. It covers a `refresh` called while disabled, an engine with nobody watching, and
746
+ // a timer that outlived either flag flipping.
747
+ if (!this.enabled || this.parked || this.disposed) {
748
+ return;
749
+ }
750
+
751
+ this.cancelled = false;
752
+ this.generation += 1;
753
+ const generation = this.generation;
754
+ const isCurrent = (): boolean => this.generation === generation;
755
+
756
+ // Armed before the commit, so a listener that reads the snapshot finds the mint already
757
+ // bounded; and before the mint is called, so one that never settles is still abandoned. A
758
+ // mint a park left out is bounded from the instant it started, not from this resume.
759
+ this.minting = true;
760
+ const joined = this.callOut();
761
+ this.armAt({
762
+ at: (joined?.startedAt ?? Date.now()) + REFRESH_MARGIN_MS,
763
+ fire: () => {
764
+ this.abandon(generation);
765
+ },
766
+ retriesFailure: false,
767
+ });
768
+ this.commit(snapshotOf({ ...this.snapshot, isLoading: true }));
769
+
770
+ // A listener that disabled or parked the engine from inside the commit retired this run.
771
+ if (!isCurrent()) {
772
+ return;
773
+ }
774
+
775
+ const call = joined ?? this.startCall();
776
+
777
+ let session: SessionAnswer;
778
+ try {
779
+ // An answer that is no session is a failed mint, as a rejection is: see
780
+ // `readSessionAnswer` for what one must hold.
781
+ session = readSessionAnswer(await call.answer);
782
+ } catch (cause) {
783
+ if (!isCurrent()) {
784
+ return;
785
+ }
786
+
787
+ this.minting = false;
788
+
789
+ // The application ended this mint itself, so the run of minting it belonged to ends with
790
+ // it: nothing is armed, the bound on the mint included, so nothing mints until a refresh, a
791
+ // new subscriber or an enable asks. Minted again on the margin, a cancellation would be
792
+ // undone a minute later by the engine it was meant to stop. Lowering `isLoading` is what
793
+ // lets a request waiting for a first token go on at once.
794
+ if (isCancellation(cause) || abortedByApplication(call)) {
795
+ this.disarm();
796
+ this.cancelled = true;
797
+ this.commit(snapshotOf({ ...this.snapshot, error: cause, isLoading: false }));
798
+
799
+ return;
800
+ }
801
+
802
+ // Retry rather than give up: a failed mint usually means the application's endpoint was
803
+ // briefly unavailable, not that it never will be. It is one more mint of the run a spent
804
+ // token counts in, so the first waits the floor and each next one twice as long, up to the
805
+ // margin: an endpoint that blinked is asked again in seconds, and one that stays down
806
+ // costs a call a minute. Armed before the commit, so a listener that refreshes from inside
807
+ // it replaces this schedule rather than being replaced by it.
808
+ this.backoff += 1;
809
+ this.armRefresh(refreshSchedule({ consecutiveSpent: this.backoff }).delayMs, true);
810
+ this.commit(snapshotOf({ ...this.snapshot, error: cause, isLoading: false }));
811
+
812
+ return;
813
+ }
814
+
815
+ if (!isCurrent()) {
816
+ return;
817
+ }
818
+
819
+ this.minting = false;
820
+
821
+ // An expiry that names no instant is the case worth handling explicitly rather than letting
822
+ // the arithmetic below run on it. `getTime()` on an Invalid Date is NaN, NaN survives
823
+ // Math.min unchanged and loses every comparison it is put through, so a mis-formatted date
824
+ // would read as a token with no lifetime left: one page load, and the engine spends the
825
+ // life of the process re-minting a perfectly good token against the application's OWN
826
+ // endpoint. The token itself is still usable; only its lifetime is unknown, so it is kept
827
+ // and re-minted on the margin.
828
+ const expiry = session.expiresAt;
829
+
830
+ this.commit(
831
+ snapshotOf({
832
+ error: undefined,
833
+ expiresAt: expiry,
834
+ isLoading: false,
835
+ token: session.token,
836
+ userId: session.userId,
837
+ }),
838
+ );
839
+
840
+ // A listener that refreshed from inside the commit started a run of its own, which owns
841
+ // the schedule and the backoff from here.
842
+ if (!isCurrent()) {
843
+ return;
844
+ }
845
+
846
+ // What the schedule is, as against when to fire it: `refreshSchedule` owns the margin, the
847
+ // floor and the doubling, and this method owns the timer they feed. The arithmetic exists
848
+ // once, in the rule `transport.session.refresh` runs against.
849
+ const lifetime = expiry === undefined ? undefined : expiry.getTime() - Date.now();
850
+ const schedule = refreshSchedule({ lifetimeMs: lifetime });
851
+
852
+ if (schedule.armed) {
853
+ // The token brought headroom of its own, so the schedule is the token's rather than the
854
+ // engine's. Clearing the count here is what makes the backoff describe the CURRENT
855
+ // run of bad tokens: a skew that clears costs one short wait, not a schedule the process
856
+ // stays stretched on for the rest of its life.
857
+ this.backoff = 0;
858
+ this.armRefresh(schedule.delayMs);
859
+
860
+ return;
861
+ }
862
+
863
+ // Nothing left to take a proportional margin out of: the token is already spent, or the
864
+ // clock is far enough out of step to look that way. Waiting the floor every time would
865
+ // still cost the application's own endpoint a call every five seconds for as long as that
866
+ // lasts, so each one in a row waits twice as long as the last.
867
+ this.backoff += 1;
868
+ this.armRefresh(refreshSchedule({ consecutiveSpent: this.backoff }).delayMs);
869
+ }
870
+ }