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