@nordhavnhq/beacon 0.4.1 → 0.5.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/dist/index.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/cache.ts
4
+ var EXPIRED = 1;
4
5
  var MemoryCacheStore = class {
5
6
  constructor(maxEntries = 500) {
6
7
  this.maxEntries = maxEntries;
@@ -32,23 +33,31 @@ var ContentCache = class {
32
33
  constructor(opts = {}) {
33
34
  this.enabled = opts.enabled ?? true;
34
35
  this.ttl = opts.ttl ?? 6048e5;
36
+ this.retryDelay = typeof opts.revalidate === "number" && opts.revalidate > 0 ? opts.revalidate : 6e4;
35
37
  this.store = opts.store ?? new MemoryCacheStore(opts.maxEntries ?? 500);
36
38
  }
37
39
  /**
38
40
  * The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
39
41
  * whole entry (value + etag + validated stamp) so the client can decide
40
42
  * whether to serve it, revalidate it, or fall back to it on error.
43
+ *
44
+ * An expired entry is left in the store (the refetch overwrites it, or
45
+ * `maxEntries` evicts it) so `stale` can still fall back to it.
41
46
  */
42
47
  peek(key, now) {
43
- if (!this.enabled) return void 0;
44
- const entry = this.store.get(key);
48
+ const entry = this.stale(key);
45
49
  if (!entry) return void 0;
46
- if (entry.expiresAt !== 0 && entry.expiresAt <= now) {
47
- this.store.delete(key);
48
- return void 0;
49
- }
50
+ if (entry.expiresAt !== 0 && entry.expiresAt <= now) return void 0;
50
51
  return entry;
51
52
  }
53
+ /**
54
+ * The entry for `key` whether or not its TTL has run out: the last good value
55
+ * to serve when a refetch fails transiently.
56
+ */
57
+ stale(key) {
58
+ if (!this.enabled) return void 0;
59
+ return this.store.get(key);
60
+ }
52
61
  /** Store a freshly fetched value with its validator and the stamp it is current against. */
53
62
  set(key, value, opts, now) {
54
63
  if (!this.enabled) return;
@@ -68,8 +77,43 @@ var ContentCache = class {
68
77
  if (!entry) return;
69
78
  entry.validatedVersion = version;
70
79
  entry.expiresAt = this.ttl === 0 ? 0 : now + this.ttl;
80
+ delete entry.retryAt;
81
+ this.store.set(key, entry);
82
+ }
83
+ /**
84
+ * Record that refetching `key` from `from` just failed transiently, so reads
85
+ * serve it as-is for a while instead of each waiting on an unreachable studio.
86
+ * Returns the entry to serve: `from`, or the newer one a concurrent read stored
87
+ * in the meantime (left unpaused, since its own fetch succeeded).
88
+ */
89
+ backoff(key, from, now) {
90
+ const entry = this.store.get(key);
91
+ if (!entry) return from;
92
+ if (entry.etag !== from.etag || entry.expiresAt !== from.expiresAt) return entry;
93
+ entry.retryAt = now + this.retryDelay;
94
+ this.store.set(key, entry);
95
+ return entry;
96
+ }
97
+ /**
98
+ * Mark `key` as due for a refetch while keeping its value to fall back on:
99
+ * the next read asks the studio again whatever the stamp says, and still
100
+ * serves this value if the studio does not answer. For when the stored value
101
+ * may be outdated but there is no telling - dropping it would throw away the
102
+ * only thing left to show during an outage. No-op for a key that is not held.
103
+ */
104
+ expire(key) {
105
+ const entry = this.store.get(key);
106
+ if (!entry) return;
107
+ entry.expiresAt = EXPIRED;
108
+ delete entry.retryAt;
71
109
  this.store.set(key, entry);
72
110
  }
111
+ /** `expire` for every key that starts with `prefix`. */
112
+ expirePrefix(prefix) {
113
+ for (const key of [...this.store.keys()]) {
114
+ if (key.startsWith(prefix)) this.expire(key);
115
+ }
116
+ }
73
117
  /** Drop one exact key. */
74
118
  delete(key) {
75
119
  this.store.delete(key);
@@ -106,15 +150,22 @@ var HavenError = class _HavenError extends Error {
106
150
  };
107
151
 
108
152
  // src/version.ts
153
+ var UNSUPPORTED_PAUSE_MS = 15 * 6e4;
109
154
  var VersionTracker = class {
110
- constructor(probe, interval) {
155
+ constructor(probe, interval, isUnsupported = (err) => err?.status === 404) {
111
156
  this.probe = probe;
112
157
  this.interval = interval;
158
+ this.isUnsupported = isUnsupported;
113
159
  this.lastChecked = 0;
114
160
  this.version = null;
115
161
  this.inFlight = null;
116
- /** Set when the server has no version route, so we stop asking. */
117
- this.unsupported = false;
162
+ /**
163
+ * Epoch ms before which we do not ask again, after the server turned out
164
+ * to have no version route. A pause and not a final verdict: an old server
165
+ * costs one request per pause, and one that gains the route is picked up
166
+ * without a restart.
167
+ */
168
+ this.pausedUntil = 0;
118
169
  }
119
170
  /** The most recent stamp seen, or `null` before the first successful probe. */
120
171
  current() {
@@ -124,24 +175,31 @@ var VersionTracker = class {
124
175
  * Refresh the stamp if we are due. Resolves once the answer is in, so the
125
176
  * read that triggered it sees an up-to-date stamp. A failed probe leaves the
126
177
  * last known stamp in place (serve-from-cache rather than thrash).
178
+ *
179
+ * A failed probe counts towards the interval like any other, also when no
180
+ * stamp has ever come in. Otherwise a process that starts while the studio
181
+ * is down (with a persisted cache to serve from) would probe on every read,
182
+ * and against a hanging studio make each of them wait out the probe.
127
183
  */
128
184
  async refresh(now) {
129
- if (this.interval <= 0 || this.unsupported) return;
185
+ if (this.interval <= 0 || now < this.pausedUntil) return;
130
186
  if (this.inFlight) return this.inFlight;
131
- if (this.version !== null && now - this.lastChecked < this.interval) return;
187
+ if (now - this.lastChecked < this.interval) return;
132
188
  this.lastChecked = now;
133
- this.inFlight = this.run();
189
+ this.inFlight = this.run(now);
134
190
  try {
135
191
  await this.inFlight;
136
192
  } finally {
137
193
  this.inFlight = null;
138
194
  }
139
195
  }
140
- async run() {
196
+ async run(now) {
141
197
  try {
142
198
  this.version = await this.probe();
143
199
  } catch (err) {
144
- if (err?.status === 404) this.unsupported = true;
200
+ if (this.isUnsupported(err)) {
201
+ this.pausedUntil = now + Math.max(this.interval, UNSUPPORTED_PAUSE_MS);
202
+ }
145
203
  }
146
204
  }
147
205
  };
@@ -149,26 +207,87 @@ var VersionTracker = class {
149
207
  // src/client.ts
150
208
  var PREVIEW_PARAM = "sl-preview";
151
209
  var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
152
- var HavenClient = class _HavenClient {
210
+ var DEFAULT_TIMEOUT = 1e4;
211
+ var VERSION_TIMEOUT = 3e3;
212
+ var DEFAULT_WAIT_FOR_FRESH = 1e3;
213
+ var MAX_TIMER = 2147483647;
214
+ var STORED_LIMIT = 5e3;
215
+ var LOCALES_RETRY_MS = 6e4;
216
+ var DEFAULT_GATEWAY_RETRY = 200;
217
+ var MAX_GATEWAY_RETRY = 6e4;
218
+ var HavenClient = class {
153
219
  constructor(options) {
220
+ /**
221
+ * The refresh under way per cache key, so concurrent reads of one key share
222
+ * one request, with the ticket it left on (see `state.ticket`).
223
+ */
224
+ this.inflight = /* @__PURE__ */ new Map();
225
+ /**
226
+ * Per cache key, the ticket of the request whose answer the cache holds.
227
+ * Emptied on every invalidation, capped by `STORED_LIMIT`. See `storable`.
228
+ */
229
+ this.storedBy = /* @__PURE__ */ new Map();
230
+ /**
231
+ * Everything that changes while the client runs and is not a collection of
232
+ * its own. One object, so that a preview view - which shares this client's
233
+ * fields through its prototype - changes the same values and never a copy.
234
+ */
235
+ this.state = {
236
+ /**
237
+ * Numbers the requests in the order they leave. Answers come back in any
238
+ * order, and the cache must never go back in time: a request takes a
239
+ * ticket when it leaves, and `storable` compares it on the way back.
240
+ */
241
+ ticket: 0,
242
+ /** The last ticket handed out when the cache was last invalidated. */
243
+ invalidatedAt: 0,
244
+ /** Set by an absorbed failure, cleared by the next answer: one warning per outage. */
245
+ unreachable: false,
246
+ /**
247
+ * The project's locales as last read. Kept here and not only in the cache,
248
+ * where the entry can be evicted: without the list a requested locale
249
+ * cannot be mapped onto the key its content is cached under, and that
250
+ * content would be out of reach for as long as the studio is away.
251
+ */
252
+ locales: void 0,
253
+ /** Epoch ms before which the locales are not asked for again, after that failed. */
254
+ localesRetryAt: 0
255
+ };
154
256
  if (!options.apiKey) throw new Error("HavenClient: `apiKey` is required");
155
257
  this.apiKey = options.apiKey;
156
258
  this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
157
259
  const resolvedFetch = options.fetch ?? globalThis.fetch;
158
260
  if (!resolvedFetch) {
159
- throw new Error("HavenClient: no `fetch` available; pass one via options.fetch (Node < 18)");
261
+ throw new Error("HavenClient: no `fetch` available; pass one via options.fetch");
160
262
  }
161
263
  this.fetchImpl = resolvedFetch.bind(globalThis);
162
264
  this.headers = options.headers ?? {};
163
265
  this.locale = options.locale || void 0;
164
266
  this.readDefault = options.preview !== true;
267
+ this.timeout = normalizeTimeout(options.timeout);
268
+ this.onError = options.onError;
165
269
  const cacheOpt = options.cache;
166
270
  const cacheOptions = cacheOpt === false ? { enabled: false } : cacheOpt === true || cacheOpt === void 0 ? {} : cacheOpt;
167
271
  this.cache = new ContentCache(cacheOptions);
272
+ this.waitForFresh = normalizeWait(cacheOptions.waitForFresh);
273
+ this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry);
168
274
  const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false ? 0 : cacheOptions.revalidate ?? 6e4;
275
+ const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT);
169
276
  this.versionTracker = new VersionTracker(
170
- async () => (await this.request("GET", "/version")).version,
171
- revalidate
277
+ async () => {
278
+ try {
279
+ const res = await this.request("GET", "/version", void 0, probeTimeout);
280
+ if (typeof res?.version !== "string") throw unexpectedBody(`${this.baseUrl}/api/content/version`);
281
+ this.state.unreachable = false;
282
+ return res.version;
283
+ } catch (err) {
284
+ if (isMissingRoute(err)) this.state.unreachable = false;
285
+ else this.report({ during: "stamp-check", error: err });
286
+ throw err;
287
+ }
288
+ },
289
+ revalidate,
290
+ isMissingRoute
172
291
  );
173
292
  }
174
293
  // ── Preview scoping ─────────────────────────────────────────────────────────
@@ -196,17 +315,9 @@ var HavenClient = class _HavenClient {
196
315
  forRequest(input) {
197
316
  if (!this.readDefault) return this;
198
317
  if (!isPreviewRequest(input)) return this;
199
- const clone = new _HavenClient({
200
- apiKey: this.apiKey,
201
- baseUrl: this.baseUrl,
202
- fetch: this.fetchImpl,
203
- headers: this.headers,
204
- locale: this.locale,
205
- preview: true
206
- });
207
- clone.cache = this.cache;
208
- clone.versionTracker = this.versionTracker;
209
- return clone;
318
+ const view = Object.create(this);
319
+ view.readDefault = false;
320
+ return view;
210
321
  }
211
322
  /** Whether this client bypasses the cache (i.e. came from a preview request). */
212
323
  get isPreview() {
@@ -215,7 +326,7 @@ var HavenClient = class _HavenClient {
215
326
  // ── Introspection ─────────────────────────────────────────────────────────
216
327
  /** The full content shape this key can reach: nodes, datasets, field schemas. */
217
328
  async schema(opts) {
218
- return this.cachedGet("schema", "/schema", opts);
329
+ return this.cachedGet("schema", "/schema", opts, has("nodes", Array.isArray));
219
330
  }
220
331
  /** Shorthand for `schema()` then `.nodes`. */
221
332
  async nodes(opts) {
@@ -226,43 +337,111 @@ var HavenClient = class _HavenClient {
226
337
  * a locale `code` as the client `locale` option or a per-call `opts.locale`.
227
338
  */
228
339
  async locales(opts) {
229
- const res = await this.cachedGet("locales", "/locales", opts);
340
+ const res = await this.cachedGet("locales", "/locales", opts, has("locales", Array.isArray));
230
341
  return res.locales;
231
342
  }
232
- /** Resolve the locale for a read: per-call override, else the client default. */
343
+ /**
344
+ * Resolve the locale for a read: per-call override, else the client default.
345
+ * Only a value overrides: `{ locale: undefined }` (or `null`) is what a site
346
+ * passes when the visitor sent no language, and must leave the client locale standing.
347
+ * `''` is the one way to ask for the project default.
348
+ */
233
349
  resolveLocale(opts) {
234
- const l = opts && "locale" in opts ? opts.locale : this.locale;
350
+ const l = opts?.locale != null ? opts.locale : this.locale;
235
351
  return l || void 0;
236
352
  }
353
+ /**
354
+ * The locale a read is requested and cached under: the requested one mapped
355
+ * onto a locale the project is configured with (see `matchLocale`).
356
+ *
357
+ * Sites pass on whatever language the visitor's browser asks for, and the
358
+ * studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed
359
+ * by the raw value, each spelling would be its own cache entry and its own
360
+ * request - and a stream of made-up ones would push every real entry out of
361
+ * the cache, the last good values for an outage among them. Mapped first,
362
+ * the cache holds one entry per configured locale, whatever is asked for.
363
+ *
364
+ * Without the list of locales (caching off, an older studio without the
365
+ * route, studio unreachable and never read) the requested value goes to the
366
+ * studio as it is, and the studio resolves it.
367
+ */
368
+ async readLocale(opts) {
369
+ const requested = this.resolveLocale(opts)?.trim() || void 0;
370
+ if (requested === void 0 || !this.cache.enabled) return requested;
371
+ const bypass = !(opts?.cache ?? this.readDefault);
372
+ const configured = await this.configuredLocales(!bypass);
373
+ return configured ? matchLocale(requested, configured) : requested;
374
+ }
375
+ /**
376
+ * The project's locales, or `undefined` when they have never been read and
377
+ * cannot be now. An empty list is an answer like any other: the project has
378
+ * no locales, the studio serves the same content whatever language is asked
379
+ * for, and `matchLocale` then maps every request onto the default.
380
+ *
381
+ * Once the list is known this does not wait for anything: the read maps from
382
+ * the list as it stands, and the list is brought up to date on the side. A
383
+ * read therefore spends its `waitForFresh` on its content alone, and keeps
384
+ * finding that content under the same key while the studio is away. Only
385
+ * the very first localized read waits here, as it has nothing to map from.
386
+ *
387
+ * The exception is `waitForFresh: false`. That setting promises that a read
388
+ * waits for the studio and leaves nothing running when it returns - what a
389
+ * host needs that freezes the process once the response is out. So there
390
+ * the list is brought up to date first, like the content after it.
391
+ */
392
+ async configuredLocales(retry) {
393
+ const state = this.state;
394
+ if (Date.now() >= state.localesRetryAt) {
395
+ const lookup = this.cachedGet(
396
+ "locales",
397
+ "/locales",
398
+ { cache: true },
399
+ has("locales", Array.isArray),
400
+ retry
401
+ ).then(
402
+ (res) => {
403
+ state.locales = res.locales;
404
+ },
405
+ () => {
406
+ state.localesRetryAt = Date.now() + LOCALES_RETRY_MS;
407
+ }
408
+ );
409
+ if (state.locales === void 0 || this.waitForFresh === Infinity) await lookup;
410
+ }
411
+ return state.locales;
412
+ }
237
413
  // ── Records ───────────────────────────────────────────────────────────────
238
414
  /** List every record in a dataset (references inflated). Requires read scope. */
239
415
  async listRecords(nodeSlug, datasetSlug, opts) {
240
- const locale = this.resolveLocale(opts);
416
+ const locale = await this.readLocale(opts);
241
417
  const res = await this.cachedGet(
242
418
  recordsKey(nodeSlug, datasetSlug, locale),
243
419
  datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),
244
- opts
420
+ opts,
421
+ has("records", Array.isArray)
245
422
  );
246
423
  return res.records;
247
424
  }
248
425
  /** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */
249
426
  async getRecord(nodeSlug, datasetSlug, recordUid, opts) {
250
- const locale = this.resolveLocale(opts);
427
+ const locale = await this.readLocale(opts);
251
428
  const res = await this.cachedGet(
252
429
  recordKey(nodeSlug, datasetSlug, recordUid, locale),
253
430
  `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}${localeQuery(locale)}`,
254
- opts
431
+ opts,
432
+ has("record", isObject)
255
433
  );
256
434
  return res.record;
257
435
  }
258
436
  /** Create a record. Requires write scope. Invalidates cached reads of the dataset. */
259
437
  async createRecord(nodeSlug, datasetSlug, data) {
260
- const res = await this.request(
438
+ const res = await this.write(
261
439
  "POST",
262
440
  datasetPath(nodeSlug, datasetSlug),
263
- { data }
441
+ { data },
442
+ nodeSlug,
443
+ datasetSlug
264
444
  );
265
- this.invalidateDataset(nodeSlug, datasetSlug);
266
445
  return res.record;
267
446
  }
268
447
  /**
@@ -271,22 +450,45 @@ var HavenClient = class _HavenClient {
271
450
  * reads of the dataset and of this record.
272
451
  */
273
452
  async updateRecord(nodeSlug, datasetSlug, recordUid, data) {
274
- const res = await this.request(
453
+ const res = await this.write(
275
454
  "PATCH",
276
455
  `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,
277
- { data }
456
+ { data },
457
+ nodeSlug,
458
+ datasetSlug
278
459
  );
279
- this.invalidateDataset(nodeSlug, datasetSlug);
280
- this.cache.delete(recordKey(nodeSlug, datasetSlug, recordUid));
281
460
  return res.record;
282
461
  }
462
+ /**
463
+ * Sends a write and settles the cached reads of its dataset with the outcome.
464
+ *
465
+ * Stored: they are dropped. Refused (an answered 4xx): they are still right
466
+ * and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves
467
+ * open whether the studio carried the write out, so they are marked for a
468
+ * recheck: the next read asks the studio again, and keeps the cached value to
469
+ * fall back on if the studio is in fact down.
470
+ */
471
+ async write(method, path, body, nodeSlug, datasetSlug) {
472
+ let res;
473
+ try {
474
+ res = await this.request(method, path, body);
475
+ } catch (err) {
476
+ if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, "recheck");
477
+ throw err;
478
+ }
479
+ this.invalidateDataset(nodeSlug, datasetSlug);
480
+ return res;
481
+ }
283
482
  // -- Queries --
284
483
  /** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */
285
484
  async query(querySlug, opts) {
286
485
  return this.cachedGet(
287
486
  `query:${querySlug}`,
288
487
  `/queries/${encodeURIComponent(querySlug)}`,
289
- opts
488
+ opts,
489
+ // Recognised by `shape`, never by `value`: that may be anything, and a
490
+ // query without a result can come back with no `value` at all.
491
+ has("shape", (shape) => typeof shape === "string")
290
492
  );
291
493
  }
292
494
  // ── Fluent dataset handle ───────────────────────────────────────────────────
@@ -301,31 +503,114 @@ var HavenClient = class _HavenClient {
301
503
  /**
302
504
  * Clear cached reads. With no argument, clears everything. Pass a scope to
303
505
  * clear just part of it: a node slug, or `{ node, dataset }` for one dataset.
506
+ * A scoped clear also drops every saved query result, as any of them may
507
+ * aggregate the content that was cleared.
304
508
  */
305
509
  clearCache(scope) {
306
510
  if (scope === void 0) {
307
511
  this.cache.clear();
512
+ this.invalidated();
308
513
  return;
309
514
  }
310
- if (typeof scope === "string") {
311
- this.cache.deletePrefix(`records:${scope}/`);
312
- this.cache.deletePrefix(`record:${scope}/`);
515
+ const node = typeof scope === "string" ? scope : scope.node;
516
+ const dataset = typeof scope === "string" ? void 0 : scope.dataset;
517
+ if (dataset) {
518
+ this.invalidateDataset(node, dataset);
313
519
  return;
314
520
  }
315
- if (scope.dataset) {
316
- this.invalidateDataset(scope.node, scope.dataset);
317
- } else {
318
- this.cache.deletePrefix(`records:${scope.node}/`);
319
- this.cache.deletePrefix(`record:${scope.node}/`);
320
- }
521
+ this.dropPrefix(`records:${node}/`);
522
+ this.dropPrefix(`record:${node}/`);
523
+ this.dropPrefix("query:");
321
524
  }
322
- /** Drop cached record reads for a dataset (every locale), plus all query
323
- * results (which may aggregate it). */
324
- invalidateDataset(nodeSlug, datasetSlug) {
325
- this.cache.delete(recordsKey(nodeSlug, datasetSlug));
326
- this.cache.deletePrefix(`${recordsKey(nodeSlug, datasetSlug)}::`);
327
- this.cache.deletePrefix(`${recordKey(nodeSlug, datasetSlug, "")}`);
328
- this.cache.deletePrefix("query:");
525
+ /**
526
+ * Invalidate cached record reads for a dataset (every locale), plus all query
527
+ * results (which may aggregate it). `drop` removes them; `recheck` keeps each
528
+ * value as a fallback but makes the next read ask the studio again.
529
+ */
530
+ invalidateDataset(nodeSlug, datasetSlug, how = "drop") {
531
+ const one = how === "drop" ? (key) => this.drop(key) : (key) => this.recheck(key);
532
+ const all = how === "drop" ? (prefix) => this.dropPrefix(prefix) : (prefix) => this.recheckPrefix(prefix);
533
+ one(recordsKey(nodeSlug, datasetSlug));
534
+ all(`${recordsKey(nodeSlug, datasetSlug)}::`);
535
+ all(`${recordKey(nodeSlug, datasetSlug, "")}`);
536
+ all("query:");
537
+ }
538
+ /** Drop one key from the cache. */
539
+ drop(key) {
540
+ this.cache.delete(key);
541
+ this.invalidated();
542
+ }
543
+ /** `drop` for every key that starts with `prefix`. */
544
+ dropPrefix(prefix) {
545
+ this.cache.deletePrefix(prefix);
546
+ this.invalidated();
547
+ }
548
+ /** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */
549
+ recheck(key) {
550
+ this.cache.expire(key);
551
+ this.invalidated();
552
+ }
553
+ /** `recheck` for every key that starts with `prefix`. */
554
+ recheckPrefix(prefix) {
555
+ this.cache.expirePrefix(prefix);
556
+ this.invalidated();
557
+ }
558
+ /**
559
+ * Called by everything that invalidates cached reads. Every request that is
560
+ * under way at this moment left before it, so its answer may show the
561
+ * content as it was: none of them may store what they come back with
562
+ * (`storable`), and no later read may join one of them (hence the cleared
563
+ * `inflight`). They still answer the reads that were already waiting on them.
564
+ *
565
+ * Deliberately not narrowed to the keys that were invalidated. The price is
566
+ * that an unrelated answer now and then is served without being stored, and
567
+ * asked for once more; what it buys is one rule without exceptions.
568
+ */
569
+ invalidated() {
570
+ this.state.invalidatedAt = this.state.ticket;
571
+ this.storedBy.clear();
572
+ this.inflight.clear();
573
+ }
574
+ /**
575
+ * Whether the answer to the request that left on `ticket` may change what
576
+ * the cache holds for `key`. The single gate in front of every cache write
577
+ * that follows a request - cached read or bypass, a new value, a `304`, a
578
+ * deletion or a retry pause alike. It keeps the cache from going back in time:
579
+ *
580
+ * - not when the cache was invalidated after the request left: the answer
581
+ * may show the content from before (a write, `clearCache`);
582
+ * - not when the cache already holds the answer to a request that left
583
+ * later: that one is newer, whichever of the two came back first.
584
+ */
585
+ storable(key, ticket) {
586
+ return ticket > this.state.invalidatedAt && ticket >= (this.storedBy.get(key) ?? 0);
587
+ }
588
+ /**
589
+ * Settles the cache with the studio's own definitive "no" for `key` (deleted,
590
+ * forbidden), in answer to the request that left on `ticket`: the entry goes.
591
+ * The one place this happens, for a cached read and a bypass alike.
592
+ *
593
+ * The deletion is noted like any other answer. Without that, a request that
594
+ * left earlier and comes back later would pass the gate and put the deleted
595
+ * content straight back.
596
+ */
597
+ gone(key, ticket) {
598
+ if (!this.storable(key, ticket)) return;
599
+ this.cache.delete(key);
600
+ this.stored(key, ticket);
601
+ }
602
+ /**
603
+ * Notes that the cache now reflects, for `key`, the answer to the request
604
+ * that left on `ticket` - a value, a `304`, or the studio's own "this does
605
+ * not exist", after which the cache holds nothing for it. A refresh of that
606
+ * key that left earlier and is still under way is retired: a read arriving
607
+ * now must not join it for an older answer than the cache already reflects.
608
+ */
609
+ stored(key, ticket) {
610
+ if (this.storedBy.size >= STORED_LIMIT) this.invalidated();
611
+ this.storedBy.set(key, ticket);
612
+ const running = this.inflight.get(key);
613
+ if (running && running.ticket < ticket) this.inflight.delete(key);
329
614
  }
330
615
  // ── Transport ───────────────────────────────────────────────────────────────
331
616
  /**
@@ -334,76 +619,204 @@ var HavenClient = class _HavenClient {
334
619
  * Steady state (project stamp unchanged since we last confirmed this entry):
335
620
  * served straight from cache, zero network. After a content change the stamp
336
621
  * moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps
337
- * the cached value, a `200` replaces it - and then it is fast again. If the
338
- * studio is unreachable, the last good value is served rather than failing
339
- * (unless it is a definitive 4xx like a deleted record).
622
+ * the cached value, a `200` replaces it - and then it is fast again.
623
+ *
624
+ * Five rules hold for every read, whatever the studio does. Each is enforced
625
+ * in exactly one place, named here, so that it cannot hold for one kind of
626
+ * read and not for another:
627
+ *
628
+ * 1. A failure that is not the studio's own definitive answer never costs a
629
+ * cached value: it is served instead, and stays cached (`refresh`).
630
+ * 2. Only what is recognisably this endpoint's answer is ever stored
631
+ * (`conditionalGet`).
632
+ * 3. The cache never goes back in time: an answer is not stored when the
633
+ * cache was invalidated, or filled with a newer answer, after its request
634
+ * left (`storable`, in front of every write to the cache).
635
+ * 4. A read that already holds a value waits on the studio for `waitForFresh`
636
+ * at most, stamp check and refresh together (here); the refresh then
637
+ * finishes on the side.
638
+ * 5. One request per key at a time (`refresh`).
340
639
  */
341
- async cachedGet(cacheKey, path, opts) {
640
+ async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
342
641
  const useCache = opts?.cache ?? this.readDefault;
343
642
  if (!useCache) {
344
- const res2 = await this.conditionalGet(path);
345
- this.cache.set(cacheKey, res2.value, { etag: res2.etag, version: this.versionTracker.current() ?? void 0 }, Date.now());
346
- return res2.value;
643
+ const version2 = this.versionTracker.current() ?? void 0;
644
+ const ticket = ++this.state.ticket;
645
+ let res;
646
+ try {
647
+ res = await this.conditionalGet(path, void 0, isExpected);
648
+ } catch (err) {
649
+ if (isDefinitive(err)) this.gone(cacheKey, ticket);
650
+ throw err;
651
+ }
652
+ if (this.storable(cacheKey, ticket)) {
653
+ this.cache.set(cacheKey, res.value, { etag: res.etag, version: version2 }, Date.now());
654
+ this.stored(cacheKey, ticket);
655
+ }
656
+ return res.value;
347
657
  }
348
- await this.versionTracker.refresh(Date.now());
658
+ const started = Date.now();
659
+ const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity;
660
+ await within(this.versionTracker.refresh(started), budget);
349
661
  const version = this.versionTracker.current() ?? void 0;
350
662
  const entry = this.cache.peek(cacheKey, Date.now());
351
663
  if (entry) {
352
664
  if (version === void 0 || entry.validatedVersion === version) {
353
665
  return entry.value;
354
666
  }
667
+ }
668
+ const last = entry ?? this.cache.stale(cacheKey);
669
+ if (last?.retryAt !== void 0 && Date.now() < last.retryAt) {
670
+ return last.value;
671
+ }
672
+ const refresh = this.refresh(cacheKey, path, last, version, isExpected, retry);
673
+ if (!last) return refresh;
674
+ const outcome = await within(refresh, budget - (Date.now() - started));
675
+ return outcome.settled ? outcome.value : last.value;
676
+ }
677
+ /**
678
+ * Fetches `cacheKey` from the studio and settles the cache with the answer.
679
+ * One per key at a time: reads that arrive while it runs get the same promise,
680
+ * so a slow studio sees one request for a key and not one per visitor.
681
+ *
682
+ * Resolves with the value to serve: the fresh one, or a cached one when the
683
+ * studio failed transiently. Rejects on a definitive answer, or when there is
684
+ * nothing cached to serve in its place.
685
+ */
686
+ refresh(cacheKey, path, last, version, isExpected, retry) {
687
+ const running = this.inflight.get(cacheKey);
688
+ if (running) return running.job;
689
+ let ticket = ++this.state.ticket;
690
+ const registered = () => this.inflight.get(cacheKey)?.job === job;
691
+ const register = () => {
692
+ this.inflight.set(cacheKey, { job, ticket });
693
+ };
694
+ const job = (async () => {
355
695
  try {
356
- const res2 = await this.conditionalGet(path, entry.etag);
357
- if (res2.notModified) {
358
- this.cache.confirm(cacheKey, version, Date.now());
359
- return entry.value;
696
+ let res;
697
+ try {
698
+ res = await this.conditionalGet(path, last?.etag, isExpected);
699
+ } catch (err) {
700
+ const pause = this.gatewayRetry;
701
+ if (!retry || pause === void 0 || last || this.cache.stale(cacheKey) || !isGatewayHiccup(err)) throw err;
702
+ await sleep(pause + Math.random() * pause);
703
+ const meanwhile = this.cache.stale(cacheKey);
704
+ if (meanwhile) return meanwhile.value;
705
+ const slot = this.inflight.get(cacheKey);
706
+ if (slot && !registered()) return slot.job;
707
+ ticket = ++this.state.ticket;
708
+ if (slot) slot.ticket = ticket;
709
+ else register();
710
+ version = this.versionTracker.current() ?? void 0;
711
+ res = await this.conditionalGet(path, void 0, isExpected);
360
712
  }
361
- this.cache.set(cacheKey, res2.value, { etag: res2.etag, version }, Date.now());
362
- return res2.value;
713
+ if (res.notModified && last) {
714
+ if (this.storable(cacheKey, ticket)) {
715
+ this.cache.confirm(cacheKey, version, Date.now());
716
+ this.stored(cacheKey, ticket);
717
+ }
718
+ return last.value;
719
+ }
720
+ if (this.storable(cacheKey, ticket)) {
721
+ this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now());
722
+ this.stored(cacheKey, ticket);
723
+ }
724
+ return res.value;
363
725
  } catch (err) {
364
- if (err instanceof HavenError && err.status < 500) {
365
- this.cache.delete(cacheKey);
726
+ if (isDefinitive(err)) {
727
+ this.gone(cacheKey, ticket);
366
728
  throw err;
367
729
  }
368
- return entry.value;
730
+ const held = this.cache.stale(cacheKey) ?? last;
731
+ if (!held) throw err;
732
+ this.report({ during: "read", key: cacheKey, error: err });
733
+ return (this.storable(cacheKey, ticket) ? this.cache.backoff(cacheKey, held, Date.now()) : held).value;
734
+ } finally {
735
+ if (registered()) this.inflight.delete(cacheKey);
736
+ }
737
+ })();
738
+ this.inflight.set(cacheKey, { job, ticket });
739
+ return job;
740
+ }
741
+ /**
742
+ * Hands an absorbed failure to `onError`, or without one warns once per
743
+ * outage. Never throws and never leaves a rejection behind: a broken hook
744
+ * must not turn a served read into an error, and an `async` hook whose own
745
+ * work fails (an alert that cannot be delivered, during the very outage it
746
+ * reports) must not become the unhandled rejection that stops the process.
747
+ */
748
+ report(failure) {
749
+ const first = !this.state.unreachable;
750
+ this.state.unreachable = true;
751
+ try {
752
+ if (this.onError) {
753
+ const outcome = this.onError(failure);
754
+ if (isThenable(outcome)) outcome.then(void 0, () => {
755
+ });
756
+ } else if (first) {
757
+ const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
758
+ const what = failure.during === "read" ? `could not refresh "${failure.key}"` : "stamp check failed";
759
+ console.warn(`[@nordhavnhq/beacon] ${what} (${reason}); cached content keeps being served.`);
369
760
  }
761
+ } catch {
370
762
  }
371
- const res = await this.conditionalGet(path);
372
- this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now());
373
- return res.value;
374
763
  }
375
764
  /**
376
765
  * A GET that understands conditional requests: sends `If-None-Match` when an
377
766
  * etag is supplied, and reports a `304` as `notModified` rather than a value.
767
+ *
768
+ * The one place that decides what counts as an answer, for every read:
769
+ *
770
+ * - A `2xx` whose body fails `isExpected` is rejected, not returned. A
771
+ * maintenance page or a captive portal can answer `200` with JSON of its
772
+ * own; storing that would replace the last good value with nothing, at the
773
+ * very moment the studio is away.
774
+ * - A `304` is only an answer to a request that sent an etag. Unasked for,
775
+ * it says "keep what you have" to a caller that has nothing, and there is
776
+ * no value to return or store.
378
777
  */
379
- async conditionalGet(path, ifNoneMatch) {
380
- const res = await this.fetchImpl(`${this.baseUrl}/api/content${path}`, {
381
- method: "GET",
382
- headers: {
383
- Authorization: `Bearer ${this.apiKey}`,
384
- ...ifNoneMatch ? { "If-None-Match": ifNoneMatch } : {},
385
- ...this.headers
778
+ async conditionalGet(path, ifNoneMatch, isExpected) {
779
+ const url = `${this.baseUrl}/api/content${path}`;
780
+ return withTimeout(url, this.timeout, async (signal) => {
781
+ const res = await this.fetchImpl(url, {
782
+ method: "GET",
783
+ headers: {
784
+ Authorization: `Bearer ${this.apiKey}`,
785
+ ...ifNoneMatch ? { "If-None-Match": ifNoneMatch } : {},
786
+ ...this.headers
787
+ },
788
+ signal
789
+ });
790
+ if (res.status === 304) {
791
+ if (!ifNoneMatch) throw unexpectedBody(url);
792
+ this.state.unreachable = false;
793
+ return { notModified: true, etag: res.headers.get("etag") ?? ifNoneMatch };
386
794
  }
795
+ if (!res.ok) throw await this.toError(res);
796
+ const etag = res.headers.get("etag") ?? void 0;
797
+ const value = res.status === 204 ? void 0 : await res.json();
798
+ if (!isExpected(value)) throw unexpectedBody(url);
799
+ this.state.unreachable = false;
800
+ return { notModified: false, value, etag };
387
801
  });
388
- if (res.status === 304) return { notModified: true, etag: res.headers.get("etag") ?? ifNoneMatch ?? void 0 };
389
- if (!res.ok) throw await this.toError(res);
390
- const etag = res.headers.get("etag") ?? void 0;
391
- if (res.status === 204) return { notModified: false, value: void 0, etag };
392
- return { notModified: false, value: await res.json(), etag };
393
- }
394
- async request(method, path, body) {
395
- const res = await this.fetchImpl(`${this.baseUrl}/api/content${path}`, {
396
- method,
397
- headers: {
398
- Authorization: `Bearer ${this.apiKey}`,
399
- ...body !== void 0 ? { "Content-Type": "application/json" } : {},
400
- ...this.headers
401
- },
402
- body: body !== void 0 ? JSON.stringify(body) : void 0
802
+ }
803
+ async request(method, path, body, timeout = this.timeout) {
804
+ const url = `${this.baseUrl}/api/content${path}`;
805
+ return withTimeout(url, timeout, async (signal) => {
806
+ const res = await this.fetchImpl(url, {
807
+ method,
808
+ headers: {
809
+ Authorization: `Bearer ${this.apiKey}`,
810
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
811
+ ...this.headers
812
+ },
813
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
814
+ signal
815
+ });
816
+ if (!res.ok) throw await this.toError(res);
817
+ if (res.status === 204) return void 0;
818
+ return await res.json();
403
819
  });
404
- if (!res.ok) throw await this.toError(res);
405
- if (res.status === 204) return void 0;
406
- return res.json();
407
820
  }
408
821
  /** Parse a non-2xx response into a `HavenError`, preferring its message. */
409
822
  async toError(res) {
@@ -416,7 +829,9 @@ var HavenClient = class _HavenClient {
416
829
  else if (typeof m?.statusMessage === "string") message = m.statusMessage;
417
830
  } catch {
418
831
  }
419
- return new HavenError(message, res.status, parsed);
832
+ const err = new HavenError(message, res.status, parsed);
833
+ if (res.headers.has("retry-after")) askedToWait.add(err);
834
+ return err;
420
835
  }
421
836
  };
422
837
  var DatasetHandle = class {
@@ -455,9 +870,108 @@ function isPreviewRequest(input) {
455
870
  }
456
871
  return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM);
457
872
  }
873
+ async function withTimeout(url, ms, run) {
874
+ if (ms <= 0) return run(void 0);
875
+ const controller = new AbortController();
876
+ let timer;
877
+ const expired = new Promise((_, reject) => {
878
+ timer = setTimeout(() => {
879
+ const err = new Error(`The studio did not answer within ${ms}ms: ${url}`);
880
+ err.name = "TimeoutError";
881
+ controller.abort(err);
882
+ reject(err);
883
+ }, ms);
884
+ });
885
+ try {
886
+ return await Promise.race([run(controller.signal), expired]);
887
+ } finally {
888
+ clearTimeout(timer);
889
+ }
890
+ }
891
+ function normalizeTimeout(value) {
892
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
893
+ return value > MAX_TIMER ? 0 : value;
894
+ }
895
+ function normalizeGatewayRetry(value) {
896
+ if (value === false) return void 0;
897
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
898
+ return Math.min(value, MAX_GATEWAY_RETRY);
899
+ }
900
+ function normalizeWait(value) {
901
+ if (value === false) return Infinity;
902
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH;
903
+ return value > MAX_TIMER ? Infinity : value;
904
+ }
905
+ async function within(promise, ms) {
906
+ if (ms > MAX_TIMER) return { settled: true, value: await promise };
907
+ if (ms <= 0) {
908
+ promise.catch(() => {
909
+ });
910
+ return { settled: false };
911
+ }
912
+ let timer;
913
+ const late = new Promise((resolve) => {
914
+ timer = setTimeout(() => resolve({ settled: false }), ms);
915
+ });
916
+ try {
917
+ return await Promise.race([promise.then((value) => ({ settled: true, value })), late]);
918
+ } finally {
919
+ clearTimeout(timer);
920
+ }
921
+ }
922
+ function isThenable(value) {
923
+ return typeof value?.then === "function";
924
+ }
925
+ function isObject(value) {
926
+ return typeof value === "object" && value !== null && !Array.isArray(value);
927
+ }
928
+ function has(field, check) {
929
+ return (body) => isObject(body) && field in body && check(body[field]);
930
+ }
931
+ function unexpectedBody(url) {
932
+ const err = new Error(`The studio answered with an unexpected response: ${url}`);
933
+ err.name = "UnexpectedResponseError";
934
+ return err;
935
+ }
936
+ function isTransientStatus(status) {
937
+ return status >= 500 || status === 408 || status === 429;
938
+ }
939
+ var askedToWait = /* @__PURE__ */ new WeakSet();
940
+ function isGatewayHiccup(err) {
941
+ return err instanceof HavenError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
942
+ }
943
+ function sleep(ms) {
944
+ return new Promise((resolve) => setTimeout(resolve, ms));
945
+ }
946
+ function isDefinitive(err) {
947
+ return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err);
948
+ }
949
+ function isStudioAnswer(err) {
950
+ const body = err.body;
951
+ if (typeof body !== "object" || body === null) return false;
952
+ return body.statusCode === err.status || body.status === err.status;
953
+ }
954
+ function isMissingRoute(err) {
955
+ return err instanceof HavenError && err.status === 404 && isStudioAnswer(err);
956
+ }
957
+ function writeMayHaveLanded(err) {
958
+ return !(err instanceof HavenError && err.status >= 400 && err.status < 500);
959
+ }
458
960
  function datasetPath(nodeSlug, datasetSlug) {
459
961
  return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`;
460
962
  }
963
+ function matchLocale(requested, locales) {
964
+ const canonical = (code) => code.trim().toLowerCase().replace(/_/g, "-");
965
+ const known = locales.filter((locale) => typeof locale?.code === "string" && locale.code !== "");
966
+ const wanted = canonical(requested);
967
+ const exact = known.find((locale) => canonical(locale.code) === wanted);
968
+ if (exact) return exact.code;
969
+ const language = wanted.split("-")[0];
970
+ const related = known.filter((locale) => canonical(locale.code).split("-")[0] === language);
971
+ const close = related.find((locale) => locale.isDefault) ?? related[0];
972
+ if (close) return close.code;
973
+ return known.find((locale) => locale.isFallback)?.code;
974
+ }
461
975
  function localeQuery(locale) {
462
976
  return locale ? `?locale=${encodeURIComponent(locale)}` : "";
463
977
  }