@nordhavnhq/beacon 0.6.0 → 0.7.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.js CHANGED
@@ -137,6 +137,7 @@ var HavenError = class _HavenError extends Error {
137
137
  this.name = "HavenError";
138
138
  this.status = status;
139
139
  this.body = body;
140
+ this.code = errorCode(body);
140
141
  Object.setPrototypeOf(this, _HavenError.prototype);
141
142
  }
142
143
  get isUnauthorized() {
@@ -149,6 +150,208 @@ var HavenError = class _HavenError extends Error {
149
150
  return this.status === 404;
150
151
  }
151
152
  };
153
+ function errorCode(body) {
154
+ if (typeof body !== "object" || body === null) return void 0;
155
+ const data = body.data;
156
+ if (typeof data !== "object" || data === null) return void 0;
157
+ const code = data.code;
158
+ return typeof code === "string" && code !== "" ? code : void 0;
159
+ }
160
+ function isStudioBody(status, body) {
161
+ if (typeof body !== "object" || body === null) return false;
162
+ const b = body;
163
+ return b.statusCode === status || b.status === status;
164
+ }
165
+
166
+ // src/live-policy.ts
167
+ var LIVE = {
168
+ /**
169
+ * No message (a version or a ping) for this long and the connection counts
170
+ * as dead. The studio pings every 25 s, so this is two missed pings and then
171
+ * some: a frozen process, a proxy that holds the stream without passing it on.
172
+ */
173
+ staleMs: 6e4,
174
+ /**
175
+ * A connection that stayed up this long, and heard from the studio, resets
176
+ * the backoff. One that is accepted and then closed sooner counts as a
177
+ * failure, so accept-then-close cannot loop.
178
+ */
179
+ stableMs: 6e4,
180
+ /**
181
+ * Even while the connection is healthy, it is checked against the stamp
182
+ * itself this often (once per connection, in the background, never awaited
183
+ * by a read): a safety net for a change the stream missed. It should never
184
+ * miss one, but one missed would otherwise stay unseen until the stream ends.
185
+ */
186
+ safetyPollMs: 5 * 6e4,
187
+ /**
188
+ * How long the stream may stay behind a check that found the studio ahead
189
+ * before it counts as having missed a change and is replaced. The studio
190
+ * sends a change up to 5.25 s late on purpose (at most once per 5 s per
191
+ * project), so a stream that is merely behind catches up well within this.
192
+ */
193
+ lagToleranceMs: 1e4,
194
+ /** The longest that check may take; it runs on an unref'd socket, so it never holds a process. */
195
+ safetyProbeTimeoutMs: 3e3,
196
+ /** The longest the studio may take to answer the connection with its headers. */
197
+ connectTimeoutMs: 1e4,
198
+ /** After the studio ended a connection that lived its full term: wait 1 to 5 s. */
199
+ cleanMinMs: 1e3,
200
+ cleanMaxMs: 5e3,
201
+ /** After a failure: at least 1 s, then a window that doubles per failure, up to 30 s. */
202
+ backoffBaseMs: 1e3,
203
+ backoffMaxMs: 3e4,
204
+ /** `Retry-After` is honoured within these bounds. */
205
+ retryAfterMinMs: 3e4,
206
+ retryAfterMaxMs: 60 * 6e4,
207
+ /** A `429` without `Retry-After` waits as long as the studio itself asks for. */
208
+ rateLimitedMs: 5 * 6e4,
209
+ /** The most added at random to a long wait, so the sites refused together do not return together. */
210
+ longJitterMs: 6e4
211
+ };
212
+ function planReconnect(outcome, ctx) {
213
+ const attempts = ctx.stable ? 0 : ctx.attempts;
214
+ if (outcome.kind === "closed" && ctx.stable) {
215
+ return { stop: false, delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 };
216
+ }
217
+ if (outcome.kind === "refused") return planRefused(outcome, { ...ctx, attempts });
218
+ return backoff(attempts, ctx.random);
219
+ }
220
+ function planRefused(outcome, ctx) {
221
+ const { status, studio } = outcome;
222
+ if (studio && (status === 401 || status === 403)) return { stop: true };
223
+ const asked = parseRetryAfter(outcome.retryAfter, ctx.now);
224
+ if (status === 429 || status === 503 && asked !== void 0) {
225
+ const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs);
226
+ return { stop: false, delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts };
227
+ }
228
+ const studioRefusal = studio && status >= 400 && status < 500 && status !== 408;
229
+ if (studioRefusal || status >= 300 && status < 400) {
230
+ return { stop: false, delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts };
231
+ }
232
+ return backoff(ctx.attempts, ctx.random);
233
+ }
234
+ function backoff(attempts, random) {
235
+ const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16);
236
+ const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window);
237
+ return { stop: false, delay, attempts: attempts + 1 };
238
+ }
239
+ function longJitter(wait, random) {
240
+ return random() * Math.min(LIVE.longJitterMs, wait / 5);
241
+ }
242
+ function between(min, max, random) {
243
+ return min + random() * (max - min);
244
+ }
245
+ function clamp(value, min, max) {
246
+ return Math.min(max, Math.max(min, value));
247
+ }
248
+ function parseRetryAfter(value, now) {
249
+ const text = value?.trim();
250
+ if (!text) return void 0;
251
+ if (/^-?\d+$/.test(text)) return text.startsWith("-") ? void 0 : Number(text) * 1e3;
252
+ const at = Date.parse(text);
253
+ return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
254
+ }
255
+ var SHORT_LIVED_ENV = [
256
+ "VERCEL",
257
+ "NETLIFY",
258
+ "AWS_LAMBDA_FUNCTION_NAME",
259
+ "LAMBDA_TASK_ROOT",
260
+ "FUNCTIONS_WORKER_RUNTIME",
261
+ "FUNCTION_TARGET",
262
+ "DENO_DEPLOYMENT_ID",
263
+ "K_SERVICE",
264
+ "CI"
265
+ ];
266
+ function isShortLived(env) {
267
+ return SHORT_LIVED_ENV.some((name) => {
268
+ const value = env[name]?.trim().toLowerCase();
269
+ return value !== void 0 && value !== "" && value !== "0" && value !== "false";
270
+ });
271
+ }
272
+ function chooseLive(choice) {
273
+ if (!choice.runtime || !choice.revalidating || choice.option === false) return false;
274
+ if (choice.option === true) return true;
275
+ return !choice.customFetch && !choice.waitsForStudio && !isShortLived(choice.env);
276
+ }
277
+
278
+ // src/live-sse.ts
279
+ var DEFAULT_LIMIT = 64 * 1024;
280
+ var SseParser = class {
281
+ constructor(limit = DEFAULT_LIMIT) {
282
+ this.buffer = "";
283
+ this.data = [];
284
+ this.dataSize = 0;
285
+ this.event = "";
286
+ this.started = false;
287
+ /** The last chunk ended in `\r`: a `\n` that starts the next one belongs to it. */
288
+ this.afterCr = false;
289
+ this.limit = limit;
290
+ }
291
+ /**
292
+ * The events completed by `chunk`, in order. `null` once more than the limit
293
+ * is waiting for a line or an event to end: a stream like that is not the
294
+ * studio's, and the caller drops the connection rather than the memory.
295
+ */
296
+ feed(chunk) {
297
+ const text = this.prepare(this.buffer + chunk);
298
+ const out = [];
299
+ let pos = 0;
300
+ const breaks = { cr: text.indexOf("\r"), lf: text.indexOf("\n") };
301
+ while (pos < text.length) {
302
+ const end = nextBreak(text, pos, breaks);
303
+ if (end === -1) break;
304
+ let next = end + 1;
305
+ if (text.charCodeAt(end) === 13) {
306
+ if (end + 1 === text.length) this.afterCr = true;
307
+ else if (text.charCodeAt(end + 1) === 10) next = end + 2;
308
+ }
309
+ this.line(text.slice(pos, end), out);
310
+ pos = next;
311
+ }
312
+ this.buffer = text.slice(pos);
313
+ if (this.buffer.length > this.limit || this.dataSize > this.limit) return null;
314
+ return out;
315
+ }
316
+ /** Drops the `\n` of a `\r\n` split over two chunks, and a byte order mark at the start. */
317
+ prepare(text) {
318
+ let out = text;
319
+ if (this.afterCr && out.length > 0) {
320
+ this.afterCr = false;
321
+ if (out.charCodeAt(0) === 10) out = out.slice(1);
322
+ }
323
+ if (!this.started && out.length > 0) {
324
+ this.started = true;
325
+ if (out.charCodeAt(0) === 65279) out = out.slice(1);
326
+ }
327
+ return out;
328
+ }
329
+ line(line, out) {
330
+ if (line === "") {
331
+ if (this.data.length > 0) out.push({ event: this.event || "message", data: this.data.join("\n") });
332
+ this.data = [];
333
+ this.dataSize = 0;
334
+ this.event = "";
335
+ return;
336
+ }
337
+ if (line.charCodeAt(0) === 58) return;
338
+ const colon = line.indexOf(":");
339
+ const field = colon === -1 ? line : line.slice(0, colon);
340
+ let value = colon === -1 ? "" : line.slice(colon + 1);
341
+ if (value.charCodeAt(0) === 32) value = value.slice(1);
342
+ if (field === "event") this.event = value;
343
+ else if (field === "data") {
344
+ this.data.push(value);
345
+ this.dataSize += value.length + 1;
346
+ }
347
+ }
348
+ };
349
+ function nextBreak(text, pos, breaks) {
350
+ if (breaks.cr !== -1 && breaks.cr < pos) breaks.cr = text.indexOf("\r", pos);
351
+ if (breaks.lf !== -1 && breaks.lf < pos) breaks.lf = text.indexOf("\n", pos);
352
+ const { cr, lf } = breaks;
353
+ return cr === -1 ? lf : lf === -1 ? cr : Math.min(cr, lf);
354
+ }
152
355
 
153
356
  // src/version.ts
154
357
  var UNSUPPORTED_PAUSE_MS = 15 * 6e4;
@@ -172,6 +375,23 @@ var VersionTracker = class {
172
375
  current() {
173
376
  return this.version;
174
377
  }
378
+ /**
379
+ * A stamp heard from the live connection, current as of `at`. It counts as a
380
+ * check made at that moment: the next probe is due one interval after it.
381
+ * Never a request of its own, and never a reason for one.
382
+ */
383
+ observe(version, at) {
384
+ this.version = version;
385
+ this.lastChecked = Math.max(this.lastChecked, at);
386
+ }
387
+ /**
388
+ * Makes the next `refresh` ask at once, whatever the interval says (still
389
+ * not during the pause for a server without the route). For when the stamp
390
+ * may have moved unseen: the live connection went silent.
391
+ */
392
+ due() {
393
+ this.lastChecked = 0;
394
+ }
175
395
  /**
176
396
  * Refresh the stamp if we are due. Resolves once the answer is in, so the
177
397
  * read that triggered it sees an up-to-date stamp. A failed probe leaves the
@@ -205,8 +425,462 @@ var VersionTracker = class {
205
425
  }
206
426
  };
207
427
 
428
+ // src/live.ts
429
+ var REGISTRY = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/live-hubs/2");
430
+ var LINGER_MS = 5 * 6e4;
431
+ var REFUSAL_BODY_LIMIT = 16 * 1024;
432
+ function hubs() {
433
+ const scope = globalThis;
434
+ let map = scope[REGISTRY];
435
+ if (!map) {
436
+ map = /* @__PURE__ */ new Map();
437
+ scope[REGISTRY] = map;
438
+ }
439
+ return map;
440
+ }
441
+ var collected = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ hub, token }) => {
442
+ try {
443
+ hub.detach(token, true);
444
+ } catch {
445
+ }
446
+ }) : void 0;
447
+ function liveRuntime() {
448
+ const g = globalThis;
449
+ if (typeof g.window !== "undefined" || typeof g.document !== "undefined") return false;
450
+ if (g.navigator?.userAgent === "Cloudflare-Workers") return false;
451
+ return typeof g.process?.versions?.node === "string";
452
+ }
453
+ function wantLive(settings) {
454
+ try {
455
+ return chooseLive({ ...settings, runtime: liveRuntime(), env: globalThis.process?.env ?? {} });
456
+ } catch {
457
+ return false;
458
+ }
459
+ }
460
+ async function loadHttp(protocol) {
461
+ const name = protocol === "https:" ? "node:https" : "node:http";
462
+ const proc = globalThis.process;
463
+ const builtin = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule(name) : void 0;
464
+ if (builtin) return builtin;
465
+ return await import(
466
+ /* webpackIgnore: true */
467
+ /* @vite-ignore */
468
+ name
469
+ );
470
+ }
471
+ function unrefTimer(run, ms) {
472
+ const timer = setTimeout(run, ms);
473
+ timer.unref?.();
474
+ return timer;
475
+ }
476
+ var LiveLink = class {
477
+ constructor(baseUrl, apiKey, headers, owner) {
478
+ this.baseUrl = baseUrl;
479
+ this.apiKey = apiKey;
480
+ this.headers = headers;
481
+ this.token = {};
482
+ this.silences = 0;
483
+ this.closed = false;
484
+ this.owner = owner;
485
+ }
486
+ /**
487
+ * The stamp gate in front of a read, in place of `tracker.refresh`. While
488
+ * the connection is healthy the stamp it heard counts as a fresh check and
489
+ * nothing is fetched; otherwise the poll runs, at once when the connection
490
+ * went silent since the last read. Connects on the first call.
491
+ */
492
+ gate(tracker, now) {
493
+ try {
494
+ const view = this.join()?.view(now);
495
+ if (view?.healthy && view.version !== void 0) {
496
+ tracker.observe(view.version, view.at);
497
+ this.hub?.safetyCheck(now);
498
+ return Promise.resolve();
499
+ }
500
+ if (view && view.silences !== this.silences) {
501
+ this.silences = view.silences;
502
+ tracker.due();
503
+ }
504
+ } catch {
505
+ }
506
+ return tracker.refresh(now);
507
+ }
508
+ /** Leaves the connection for good; the last client out closes it. */
509
+ close() {
510
+ if (this.closed) return;
511
+ this.closed = true;
512
+ const hub = this.hub;
513
+ this.hub = void 0;
514
+ this.owner = void 0;
515
+ if (!hub) return;
516
+ collected?.unregister(this.token);
517
+ try {
518
+ hub.detach(this.token, false);
519
+ } catch {
520
+ }
521
+ }
522
+ join() {
523
+ if (this.hub || this.closed) return this.hub;
524
+ const url = eventsUrl(this.baseUrl);
525
+ if (!url) {
526
+ this.closed = true;
527
+ return void 0;
528
+ }
529
+ const registry = hubs();
530
+ const headers = liveHeaders(this.apiKey, this.headers);
531
+ const id = `${this.baseUrl}
532
+ ${headers.authorization ?? ""}`;
533
+ let hub = registry.get(id);
534
+ if (!hub) {
535
+ hub = new LiveHub(id, url, headers);
536
+ registry.set(id, hub);
537
+ }
538
+ this.silences = hub.attach(this.token);
539
+ if (this.owner) collected?.register(this.owner, { hub, token: this.token }, this.token);
540
+ this.owner = void 0;
541
+ this.hub = hub;
542
+ return hub;
543
+ }
544
+ };
545
+ function eventsUrl(baseUrl) {
546
+ try {
547
+ const url = new URL(`${baseUrl}/api/content/events`);
548
+ return url.protocol === "http:" || url.protocol === "https:" ? url : void 0;
549
+ } catch {
550
+ return void 0;
551
+ }
552
+ }
553
+ function liveHeaders(apiKey, extra) {
554
+ const headers = { authorization: `Bearer ${apiKey}` };
555
+ for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
556
+ headers.accept = "text/event-stream";
557
+ headers["cache-control"] = "no-cache";
558
+ headers["accept-encoding"] = "identity";
559
+ return headers;
560
+ }
561
+ var LiveHub = class {
562
+ constructor(id, url, headers) {
563
+ this.id = id;
564
+ this.url = url;
565
+ this.headers = headers;
566
+ this.state = "idle";
567
+ this.openedAt = 0;
568
+ this.lastHeardAt = 0;
569
+ /** Failures in a row, for the backoff. */
570
+ this.attempts = 0;
571
+ this.retryAt = 0;
572
+ this.silences = 0;
573
+ this.owners = /* @__PURE__ */ new Set();
574
+ /** Version events on the open connection: tells a stream that moved from one that did not. */
575
+ this.tells = 0;
576
+ /** When the open connection was last checked against the stamp itself. */
577
+ this.checkedAt = 0;
578
+ this.checking = false;
579
+ }
580
+ attach(token) {
581
+ clearTimeout(this.lingerTimer);
582
+ this.lingerTimer = void 0;
583
+ this.owners.add(token);
584
+ return this.silences;
585
+ }
586
+ detach(token, linger) {
587
+ if (!this.owners.delete(token) || this.owners.size > 0) return;
588
+ clearTimeout(this.lingerTimer);
589
+ if (linger) this.lingerTimer = unrefTimer(() => this.owners.size === 0 && this.dispose(), LINGER_MS);
590
+ else this.dispose();
591
+ }
592
+ /**
593
+ * The state of the connection for a read at `now`, after the checks a read
594
+ * makes: connect the first time; a connection silent for `LIVE.staleMs` is
595
+ * dead (a frozen process misses events and runs no timers, so the watchdog
596
+ * alone cannot be trusted); a reconnect whose time has come goes now.
597
+ */
598
+ view(now) {
599
+ if (this.state === "idle") this.connect();
600
+ else if (this.state === "open" && now - this.lastHeardAt > LIVE.staleMs) this.current?.end({ kind: "silent" });
601
+ else if (this.state === "waiting" && now >= this.retryAt) this.connect();
602
+ if (this.state === "open" && this.behind) this.judgeBehind(now);
603
+ return {
604
+ healthy: this.state === "open" && this.version !== void 0,
605
+ version: this.version,
606
+ at: this.lastHeardAt,
607
+ silences: this.silences
608
+ };
609
+ }
610
+ /**
611
+ * The safety net, at most once per `LIVE.safetyPollMs` per connection, set
612
+ * off by a read: ask the stamp and compare it with the stream's. Never
613
+ * awaited by a read, never reported, and over an unref'd socket, so it holds
614
+ * up no read and no process. Only a clear answer counts: a failed check, a
615
+ * check that outlived its connection, or one during which the stream told a
616
+ * new stamp proves nothing. A studio ahead of the stream is noted, not acted
617
+ * on: see `judgeBehind`.
618
+ */
619
+ safetyCheck(now) {
620
+ if (this.state !== "open" || this.version === void 0 || this.checking || this.behind) return;
621
+ if (now - this.checkedAt < LIVE.safetyPollMs) return;
622
+ this.checking = true;
623
+ this.checkedAt = now;
624
+ const attempt = this.current;
625
+ const tells = this.tells;
626
+ const heard = this.version;
627
+ const url = versionUrl(this.url);
628
+ const headers = { ...this.headers, accept: "application/json" };
629
+ loadHttp(url.protocol).then((http) => probeStamp(http, url, headers), () => void 0).then(
630
+ (stamp) => {
631
+ this.checking = false;
632
+ if (stamp === void 0 || attempt !== this.current || tells !== this.tells) return;
633
+ if (stamp !== heard) this.behind = { tells, since: Date.now() };
634
+ },
635
+ () => {
636
+ this.checking = false;
637
+ }
638
+ );
639
+ }
640
+ /**
641
+ * A check found the studio ahead of the stream. The studio sends late on
642
+ * purpose (its 5 s throttle), so that alone is no fault: only a stream that
643
+ * told nothing new for `LIVE.lagToleranceMs` since then missed a change. The
644
+ * first read after that drops it, which makes that same read check the stamp
645
+ * itself (and the hub reconnect).
646
+ */
647
+ judgeBehind(now) {
648
+ const behind = this.behind;
649
+ if (this.tells !== behind.tells) this.behind = void 0;
650
+ else if (now - behind.since >= LIVE.lagToleranceMs) {
651
+ this.behind = void 0;
652
+ this.current?.end({ kind: "silent" });
653
+ }
654
+ }
655
+ connect() {
656
+ clearTimeout(this.retryTimer);
657
+ this.state = "connecting";
658
+ const attempt = new LiveAttempt(this);
659
+ this.current = attempt;
660
+ loadHttp(this.url.protocol).then(
661
+ (http) => {
662
+ if (this.current === attempt) attempt.start(http, this.url, this.headers);
663
+ },
664
+ () => {
665
+ if (this.current === attempt) this.halt();
666
+ }
667
+ );
668
+ }
669
+ /** The attempt got its stream: the studio's answer is in. */
670
+ opened(attempt) {
671
+ if (attempt !== this.current) return;
672
+ this.state = "open";
673
+ this.version = void 0;
674
+ this.openedAt = Date.now();
675
+ this.lastHeardAt = this.openedAt;
676
+ this.checkedAt = this.openedAt;
677
+ this.behind = void 0;
678
+ }
679
+ /** Something came in on the stream: a sign of life. */
680
+ heard(attempt) {
681
+ if (attempt === this.current) this.lastHeardAt = Date.now();
682
+ }
683
+ /** A `version` event, its data as sent. */
684
+ told(attempt, data) {
685
+ if (attempt !== this.current) return;
686
+ try {
687
+ const version = JSON.parse(data)?.version;
688
+ if (typeof version === "string" && version !== "") {
689
+ this.version = version;
690
+ this.tells++;
691
+ }
692
+ } catch {
693
+ }
694
+ }
695
+ /** The attempt is over: plan the next one. `outcome` is absent when the hub ended it itself. */
696
+ ended(attempt, outcome) {
697
+ if (attempt !== this.current) return;
698
+ this.current = void 0;
699
+ const now = Date.now();
700
+ const stable = this.state === "open" && this.version !== void 0 && now - this.openedAt >= LIVE.stableMs;
701
+ this.version = void 0;
702
+ if (!outcome || this.state === "stopped") return;
703
+ if (outcome.kind === "silent") this.silences++;
704
+ const plan = planReconnect(outcome, { attempts: this.attempts, stable, pauseMs: UNSUPPORTED_PAUSE_MS, now, random: Math.random });
705
+ if (plan.stop) {
706
+ this.halt();
707
+ return;
708
+ }
709
+ this.attempts = plan.attempts;
710
+ this.state = "waiting";
711
+ this.retryAt = now + plan.delay;
712
+ this.retryTimer = unrefTimer(() => {
713
+ if (this.state === "waiting") this.connect();
714
+ }, plan.delay);
715
+ }
716
+ /** Stops for good: reads keep to the poll. */
717
+ halt() {
718
+ this.state = "stopped";
719
+ clearTimeout(this.retryTimer);
720
+ const attempt = this.current;
721
+ this.current = void 0;
722
+ this.version = void 0;
723
+ attempt?.end();
724
+ }
725
+ dispose() {
726
+ this.halt();
727
+ const registry = hubs();
728
+ if (registry.get(this.id) === this) registry.delete(this.id);
729
+ }
730
+ };
731
+ var LiveAttempt = class {
732
+ constructor(hub) {
733
+ this.hub = hub;
734
+ this.done = false;
735
+ this.timers = [];
736
+ }
737
+ start(http, url, headers) {
738
+ if (this.done) return;
739
+ this.timers.push(unrefTimer(() => this.end({ kind: "failed" }), LIVE.connectTimeoutMs));
740
+ try {
741
+ const req = http.request(url, { method: "GET", headers, agent: false }, (res) => this.answered(res));
742
+ this.req = req;
743
+ req.on("socket", (socket) => {
744
+ try {
745
+ socket.unref();
746
+ } catch {
747
+ this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
748
+ return;
749
+ }
750
+ try {
751
+ socket.setKeepAlive(true, 3e4);
752
+ } catch {
753
+ }
754
+ });
755
+ req.on("error", () => this.end({ kind: "failed" }));
756
+ req.end();
757
+ } catch {
758
+ this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
759
+ }
760
+ }
761
+ /** Ends the attempt; the hub plans what comes next from `outcome`, unless it ended it itself. */
762
+ end(outcome) {
763
+ if (this.done) return;
764
+ this.done = true;
765
+ for (const timer of this.timers) clearTimeout(timer);
766
+ try {
767
+ this.req?.destroy();
768
+ } catch {
769
+ }
770
+ this.hub.ended(this, outcome);
771
+ }
772
+ answered(res) {
773
+ res.on("error", () => this.end({ kind: "failed" }));
774
+ if (this.done) {
775
+ res.resume();
776
+ return;
777
+ }
778
+ const type = String(res.headers["content-type"] ?? "");
779
+ if (res.statusCode === 200 && type.includes("text/event-stream")) this.stream(res);
780
+ else this.refused(res);
781
+ }
782
+ stream(res) {
783
+ for (const timer of this.timers) clearTimeout(timer);
784
+ this.timers = [];
785
+ const watchdog = unrefTimer(() => this.end({ kind: "silent" }), LIVE.staleMs);
786
+ this.timers.push(watchdog);
787
+ this.hub.opened(this);
788
+ const parser = new SseParser();
789
+ res.setEncoding("utf8");
790
+ res.on("data", (chunk) => {
791
+ if (this.done) return;
792
+ watchdog.refresh?.();
793
+ this.hub.heard(this);
794
+ const events = parser.feed(chunk);
795
+ if (events === null) {
796
+ this.end({ kind: "failed" });
797
+ return;
798
+ }
799
+ for (const event of events) {
800
+ if (event.event === "version") this.hub.told(this, event.data);
801
+ }
802
+ });
803
+ res.on("end", () => this.end({ kind: "closed" }));
804
+ res.on("close", () => this.end({ kind: "failed" }));
805
+ }
806
+ /** Not the stream: read a little of the body, to tell the studio's own refusal from a proxy's. */
807
+ refused(res) {
808
+ const status = res.statusCode ?? 0;
809
+ const header = res.headers["retry-after"];
810
+ const retryAfter = (Array.isArray(header) ? header[0] : header) ?? null;
811
+ let body = "";
812
+ res.setEncoding("utf8");
813
+ res.on("data", (chunk) => {
814
+ body += chunk;
815
+ if (body.length > REFUSAL_BODY_LIMIT) res.destroy();
816
+ });
817
+ const settle = () => this.end({ kind: "refused", status, retryAfter, studio: isStudioBody(status, parseJson(body)) });
818
+ res.on("end", settle);
819
+ res.on("close", settle);
820
+ }
821
+ };
822
+ function versionUrl(events) {
823
+ const url = new URL(events.href);
824
+ url.pathname = url.pathname.replace(/events$/, "version");
825
+ return url;
826
+ }
827
+ function probeStamp(http, url, headers) {
828
+ return new Promise((resolve) => {
829
+ let req;
830
+ let settled = false;
831
+ const finish = (stamp) => {
832
+ if (settled) return;
833
+ settled = true;
834
+ clearTimeout(timer);
835
+ try {
836
+ req?.destroy();
837
+ } catch {
838
+ }
839
+ resolve(stamp);
840
+ };
841
+ const timer = unrefTimer(() => finish(), LIVE.safetyProbeTimeoutMs);
842
+ try {
843
+ req = http.request(url, { method: "GET", headers, agent: false }, (res) => {
844
+ res.on("error", () => finish());
845
+ if (res.statusCode !== 200) {
846
+ res.resume();
847
+ finish();
848
+ return;
849
+ }
850
+ let body = "";
851
+ res.setEncoding("utf8");
852
+ res.on("data", (chunk) => {
853
+ body += chunk;
854
+ if (body.length > REFUSAL_BODY_LIMIT) finish();
855
+ });
856
+ res.on("end", () => {
857
+ const stamp = parseJson(body)?.version;
858
+ finish(typeof stamp === "string" && stamp !== "" ? stamp : void 0);
859
+ });
860
+ res.on("close", () => finish());
861
+ });
862
+ req.on("socket", (socket) => {
863
+ try {
864
+ socket.unref();
865
+ } catch {
866
+ }
867
+ });
868
+ req.on("error", () => finish());
869
+ req.end();
870
+ } catch {
871
+ finish();
872
+ }
873
+ });
874
+ }
875
+ function parseJson(text) {
876
+ try {
877
+ return JSON.parse(text);
878
+ } catch {
879
+ return void 0;
880
+ }
881
+ }
882
+
208
883
  // src/client.ts
209
- var PREVIEW_PARAM = "sl-preview";
210
884
  var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
211
885
  var DEFAULT_TIMEOUT = 1e4;
212
886
  var MIN_UPLOAD_TIMEOUT = 6e4;
@@ -231,8 +905,7 @@ var HavenClient = class {
231
905
  this.storedBy = /* @__PURE__ */ new Map();
232
906
  /**
233
907
  * Everything that changes while the client runs and is not a collection of
234
- * its own. One object, so that a preview view - which shares this client's
235
- * fields through its prototype - changes the same values and never a copy.
908
+ * its own.
236
909
  */
237
910
  this.state = {
238
911
  /**
@@ -265,7 +938,6 @@ var HavenClient = class {
265
938
  this.fetchImpl = resolvedFetch.bind(globalThis);
266
939
  this.headers = options.headers ?? {};
267
940
  this.locale = options.locale || void 0;
268
- this.readDefault = options.preview !== true;
269
941
  this.timeout = normalizeTimeout(options.timeout);
270
942
  this.onError = options.onError;
271
943
  const cacheOpt = options.cache;
@@ -291,39 +963,23 @@ var HavenClient = class {
291
963
  revalidate,
292
964
  isMissingRoute
293
965
  );
966
+ const live = wantLive({
967
+ option: options.live,
968
+ revalidating: revalidate > 0,
969
+ customFetch: options.fetch !== void 0,
970
+ waitsForStudio: this.waitForFresh === Infinity
971
+ });
972
+ this.live = live ? new LiveLink(this.baseUrl, this.apiKey, this.headers, this) : void 0;
294
973
  }
295
- // ── Preview scoping ─────────────────────────────────────────────────────────
296
974
  /**
297
- * A per-request view of this client that skips the cache when the request
298
- * comes from a Nordhavn OS surface preview, and behaves exactly like this
299
- * client otherwise. Reads still refresh the shared cache, so an editor
300
- * refreshing the preview also warms what real visitors get.
301
- *
302
- * Accepts whatever your framework hands you: a `Request`, a URL string or
303
- * `URL`, `URLSearchParams`, or a plain searchParams object.
304
- *
305
- * ```ts
306
- * // Next.js app router
307
- * export default async function Page({ searchParams }) {
308
- * const posts = await studio.forRequest(await searchParams).dataset('blog', 'posts').list()
309
- * }
310
- * ```
311
- *
312
- * Note this only bypasses the SDK's own cache. If the page itself sits behind
313
- * a CDN or framework data cache, that layer needs the same treatment (e.g.
314
- * `cache: 'no-store'` when the preview marker is present) or the editor keeps
315
- * seeing a stale page no matter what this client returns.
975
+ * Lets go of the live connection: the last client of a server and key to
976
+ * close it closes the connection. The client keeps working, on the stamp
977
+ * check alone. Not needed to let a process end (the connection never keeps
978
+ * one alive); for a test, or code that builds clients and drops them.
316
979
  */
317
- forRequest(input) {
318
- if (!this.readDefault) return this;
319
- if (!isPreviewRequest(input)) return this;
320
- const view = Object.create(this);
321
- view.readDefault = false;
322
- return view;
323
- }
324
- /** Whether this client bypasses the cache (i.e. came from a preview request). */
325
- get isPreview() {
326
- return !this.readDefault;
980
+ close() {
981
+ this.live?.close();
982
+ this.live = void 0;
327
983
  }
328
984
  // ── Introspection ─────────────────────────────────────────────────────────
329
985
  /** The full content shape this key can reach: nodes, datasets, field schemas. */
@@ -370,7 +1026,7 @@ var HavenClient = class {
370
1026
  async readLocale(opts) {
371
1027
  const requested = this.resolveLocale(opts)?.trim() || void 0;
372
1028
  if (requested === void 0 || !this.cache.enabled) return requested;
373
- const bypass = !(opts?.cache ?? this.readDefault);
1029
+ const bypass = opts?.cache === false;
374
1030
  const configured = await this.configuredLocales(!bypass);
375
1031
  return configured ? matchLocale(requested, configured) : requested;
376
1032
  }
@@ -692,7 +1348,7 @@ var HavenClient = class {
692
1348
  * 5. One request per key at a time (`refresh`).
693
1349
  */
694
1350
  async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
695
- const useCache = opts?.cache ?? this.readDefault;
1351
+ const useCache = opts?.cache !== false;
696
1352
  if (!useCache) {
697
1353
  const version2 = this.versionTracker.current() ?? void 0;
698
1354
  const ticket = ++this.state.ticket;
@@ -711,7 +1367,7 @@ var HavenClient = class {
711
1367
  }
712
1368
  const started = Date.now();
713
1369
  const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity;
714
- await within(this.versionTracker.refresh(started), budget);
1370
+ await within(this.checkVersion(started), budget);
715
1371
  const version = this.versionTracker.current() ?? void 0;
716
1372
  const entry = this.cache.peek(cacheKey, Date.now());
717
1373
  if (entry) {
@@ -728,6 +1384,10 @@ var HavenClient = class {
728
1384
  const outcome = await within(refresh, budget - (Date.now() - started));
729
1385
  return outcome.settled ? outcome.value : last.value;
730
1386
  }
1387
+ /** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */
1388
+ checkVersion(now) {
1389
+ return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now);
1390
+ }
731
1391
  /**
732
1392
  * Fetches `cacheKey` from the studio and settles the cache with the answer.
733
1393
  * One per key at a time: reads that arrive while it runs get the same promise,
@@ -915,19 +1575,6 @@ var DatasetHandle = class {
915
1575
  this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug });
916
1576
  }
917
1577
  };
918
- function isPreviewRequest(input) {
919
- if (!input) return false;
920
- if (typeof input === "string") {
921
- const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
922
- return new URLSearchParams(query).has(PREVIEW_PARAM);
923
- }
924
- if (input instanceof URLSearchParams) return input.has(PREVIEW_PARAM);
925
- if (input instanceof URL) return input.searchParams.has(PREVIEW_PARAM);
926
- if (typeof input.url === "string") {
927
- return isPreviewRequest(input.url);
928
- }
929
- return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM);
930
- }
931
1578
  async function withTimeout(url, ms, run) {
932
1579
  if (ms <= 0) return run(void 0);
933
1580
  const controller = new AbortController();
@@ -1012,9 +1659,7 @@ function isDefinitive(err) {
1012
1659
  return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err);
1013
1660
  }
1014
1661
  function isStudioAnswer(err) {
1015
- const body = err.body;
1016
- if (typeof body !== "object" || body === null) return false;
1017
- return body.statusCode === err.status || body.status === err.status;
1662
+ return isStudioBody(err.status, err.body);
1018
1663
  }
1019
1664
  function isMissingRoute(err) {
1020
1665
  return err instanceof HavenError && err.status === 404 && isStudioAnswer(err);
@@ -1148,6 +1793,6 @@ function createClient(options) {
1148
1793
  return new HavenClient(options);
1149
1794
  }
1150
1795
 
1151
- export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, HavenClient as JustmadeClient, HavenError as JustmadeError, MemoryCacheStore, PREVIEW_PARAM, chartFenceHeight, createClient, isChartFence, isPreviewRequest, parseChartFence };
1796
+ export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, MemoryCacheStore, chartFenceHeight, createClient, isChartFence, parseChartFence };
1152
1797
  //# sourceMappingURL=index.js.map
1153
1798
  //# sourceMappingURL=index.js.map