@nordhavnhq/beacon 0.6.0 → 0.8.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/README.md +4 -3
- package/dist/{cache-q8uLEGYg.d.cts → cache-DIs1jN1m.d.cts} +8 -3
- package/dist/{cache-q8uLEGYg.d.ts → cache-DIs1jN1m.d.ts} +8 -3
- package/dist/chunk-FLRBCD6H.js +361 -0
- package/dist/chunk-FLRBCD6H.js.map +1 -0
- package/dist/file-store.cjs +293 -34
- package/dist/file-store.cjs.map +1 -1
- package/dist/file-store.d.cts +10 -24
- package/dist/file-store.d.ts +10 -24
- package/dist/file-store.js +34 -128
- package/dist/file-store.js.map +1 -1
- package/dist/index.cjs +1443 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +225 -81
- package/dist/index.d.ts +225 -81
- package/dist/index.js +1085 -103
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,178 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// src/runtime.ts
|
|
4
|
+
var BODY_LIMIT = 16 * 1024;
|
|
5
|
+
function environment() {
|
|
6
|
+
try {
|
|
7
|
+
return globalThis.process?.env ?? {};
|
|
8
|
+
} catch {
|
|
9
|
+
return {};
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function readEnv(name) {
|
|
13
|
+
try {
|
|
14
|
+
const value = environment()[name];
|
|
15
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
16
|
+
} catch {
|
|
17
|
+
return void 0;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function nodeRuntime() {
|
|
21
|
+
const g = globalThis;
|
|
22
|
+
if (typeof g.window !== "undefined" || typeof g.document !== "undefined") return false;
|
|
23
|
+
if (g.navigator?.userAgent === "Cloudflare-Workers") return false;
|
|
24
|
+
return typeof g.process?.versions?.node === "string";
|
|
25
|
+
}
|
|
26
|
+
function nodeBuiltin(id) {
|
|
27
|
+
try {
|
|
28
|
+
const proc = globalThis.process;
|
|
29
|
+
return typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : void 0;
|
|
30
|
+
} catch {
|
|
31
|
+
return void 0;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function loadHttp(protocol) {
|
|
35
|
+
const name = protocol === "https:" ? "node:https" : "node:http";
|
|
36
|
+
const builtin = nodeBuiltin(name);
|
|
37
|
+
if (builtin) return builtin;
|
|
38
|
+
return await import(
|
|
39
|
+
/* webpackIgnore: true */
|
|
40
|
+
/* @vite-ignore */
|
|
41
|
+
name
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
function unrefTimer(run, ms) {
|
|
45
|
+
const timer = setTimeout(run, ms);
|
|
46
|
+
timer.unref?.();
|
|
47
|
+
return timer;
|
|
48
|
+
}
|
|
49
|
+
function sentHeaders(apiKey, extra) {
|
|
50
|
+
const headers = { authorization: `Bearer ${apiKey}` };
|
|
51
|
+
for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
|
|
52
|
+
return headers;
|
|
53
|
+
}
|
|
54
|
+
function identityOf(baseUrl, headers) {
|
|
55
|
+
return `${baseUrl}
|
|
56
|
+
${headers.authorization ?? ""}`;
|
|
57
|
+
}
|
|
58
|
+
function getJson(http, url, headers, timeoutMs) {
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
let req;
|
|
61
|
+
let settled = false;
|
|
62
|
+
const finish = (body) => {
|
|
63
|
+
if (settled) return;
|
|
64
|
+
settled = true;
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
try {
|
|
67
|
+
req?.destroy();
|
|
68
|
+
} catch {
|
|
69
|
+
}
|
|
70
|
+
resolve(body);
|
|
71
|
+
};
|
|
72
|
+
const timer = unrefTimer(() => finish(), timeoutMs);
|
|
73
|
+
try {
|
|
74
|
+
req = http.request(url, { method: "GET", headers, agent: false }, (res) => {
|
|
75
|
+
res.on("error", () => finish());
|
|
76
|
+
if (res.statusCode !== 200) {
|
|
77
|
+
res.resume();
|
|
78
|
+
finish();
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
let body = "";
|
|
82
|
+
res.setEncoding("utf8");
|
|
83
|
+
res.on("data", (chunk) => {
|
|
84
|
+
body += chunk;
|
|
85
|
+
if (body.length > BODY_LIMIT) finish();
|
|
86
|
+
});
|
|
87
|
+
res.on("end", () => finish(parseJson(body)));
|
|
88
|
+
res.on("close", () => finish());
|
|
89
|
+
});
|
|
90
|
+
req.on("socket", (socket) => {
|
|
91
|
+
try {
|
|
92
|
+
socket.unref();
|
|
93
|
+
} catch {
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
req.on("error", () => finish());
|
|
97
|
+
req.end();
|
|
98
|
+
} catch {
|
|
99
|
+
finish();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
function parseJson(text) {
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(text);
|
|
106
|
+
} catch {
|
|
107
|
+
return void 0;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
var WRITTEN = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/written/1");
|
|
111
|
+
function firstTime(key) {
|
|
112
|
+
const scope = globalThis;
|
|
113
|
+
let seen = scope[WRITTEN];
|
|
114
|
+
if (!seen) {
|
|
115
|
+
seen = /* @__PURE__ */ new Set();
|
|
116
|
+
scope[WRITTEN] = seen;
|
|
117
|
+
}
|
|
118
|
+
if (seen.has(key)) return false;
|
|
119
|
+
seen.add(key);
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
function loggerOf(option) {
|
|
123
|
+
if (option === false) return void 0;
|
|
124
|
+
return option ?? console;
|
|
125
|
+
}
|
|
126
|
+
function logLine(log, level, message, ...rest) {
|
|
127
|
+
try {
|
|
128
|
+
const write = log?.[level];
|
|
129
|
+
if (typeof write === "function") write.call(log, `[@nordhavnhq/beacon] ${message}`, ...rest);
|
|
130
|
+
} catch {
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/announce.ts
|
|
135
|
+
var PROJECT_TIMEOUT_MS = 3e3;
|
|
136
|
+
var NAME_LIMIT = 200;
|
|
137
|
+
function isDevelopment(env) {
|
|
138
|
+
if (env.NODE_ENV?.trim().toLowerCase() !== "development") return false;
|
|
139
|
+
const ci = env.CI?.trim().toLowerCase();
|
|
140
|
+
return ci === void 0 || ci === "" || ci === "0" || ci === "false";
|
|
141
|
+
}
|
|
142
|
+
function wantAnnounce(settings) {
|
|
143
|
+
try {
|
|
144
|
+
return typeof settings.log?.info === "function" && !settings.customFetch && nodeRuntime() && isDevelopment(environment());
|
|
145
|
+
} catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function announceProject(baseUrl, headers, log) {
|
|
150
|
+
try {
|
|
151
|
+
if (!firstTime(`project
|
|
152
|
+
${identityOf(baseUrl, headers)}`)) return;
|
|
153
|
+
const url = new URL(`${baseUrl}/api/content/project`);
|
|
154
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return;
|
|
155
|
+
loadHttp(url.protocol).then((http) => getJson(http, url, { ...headers, accept: "application/json" }, PROJECT_TIMEOUT_MS)).then((body) => {
|
|
156
|
+
const line = projectLine(body);
|
|
157
|
+
if (line) logLine(log, "info", line);
|
|
158
|
+
}, () => {
|
|
159
|
+
});
|
|
160
|
+
} catch {
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function projectLine(body) {
|
|
164
|
+
const answer = body;
|
|
165
|
+
const project = printable(answer?.project?.name);
|
|
166
|
+
if (!project) return void 0;
|
|
167
|
+
const key = printable(answer?.key?.name);
|
|
168
|
+
return key ? `connected to "${project}" (key "${key}")` : `connected to "${project}"`;
|
|
169
|
+
}
|
|
170
|
+
function printable(value) {
|
|
171
|
+
if (typeof value !== "string") return void 0;
|
|
172
|
+
const text = value.replace(/[\u0000-\u001F\u007F]+/g, " ").trim().slice(0, NAME_LIMIT);
|
|
173
|
+
return text === "" ? void 0 : text;
|
|
174
|
+
}
|
|
175
|
+
|
|
3
176
|
// src/cache.ts
|
|
4
177
|
var EXPIRED = 1;
|
|
5
178
|
var MemoryCacheStore = class {
|
|
@@ -130,13 +303,14 @@ var ContentCache = class {
|
|
|
130
303
|
};
|
|
131
304
|
|
|
132
305
|
// src/errors.ts
|
|
133
|
-
var
|
|
306
|
+
var NordhavnError = class _NordhavnError extends Error {
|
|
134
307
|
constructor(message, status, body) {
|
|
135
308
|
super(message);
|
|
136
|
-
this.name = "
|
|
309
|
+
this.name = "NordhavnError";
|
|
137
310
|
this.status = status;
|
|
138
311
|
this.body = body;
|
|
139
|
-
|
|
312
|
+
this.code = errorCode(body);
|
|
313
|
+
Object.setPrototypeOf(this, _NordhavnError.prototype);
|
|
140
314
|
}
|
|
141
315
|
get isUnauthorized() {
|
|
142
316
|
return this.status === 401;
|
|
@@ -148,6 +322,209 @@ var HavenError = class _HavenError extends Error {
|
|
|
148
322
|
return this.status === 404;
|
|
149
323
|
}
|
|
150
324
|
};
|
|
325
|
+
function errorCode(body) {
|
|
326
|
+
if (typeof body !== "object" || body === null) return void 0;
|
|
327
|
+
const data = body.data;
|
|
328
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
329
|
+
const code = data.code;
|
|
330
|
+
return typeof code === "string" && code !== "" ? code : void 0;
|
|
331
|
+
}
|
|
332
|
+
function isStudioBody(status, body) {
|
|
333
|
+
if (typeof body !== "object" || body === null) return false;
|
|
334
|
+
const b = body;
|
|
335
|
+
return b.statusCode === status || b.status === status;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// src/live-policy.ts
|
|
339
|
+
var LIVE = {
|
|
340
|
+
/**
|
|
341
|
+
* No message (a version or a ping) for this long and the connection counts
|
|
342
|
+
* as dead. The studio pings every 25 s, so this is two missed pings and then
|
|
343
|
+
* some: a frozen process, a proxy that holds the stream without passing it on.
|
|
344
|
+
*/
|
|
345
|
+
staleMs: 6e4,
|
|
346
|
+
/**
|
|
347
|
+
* A connection that stayed up this long, and heard from the studio, resets
|
|
348
|
+
* the backoff. One that is accepted and then closed sooner counts as a
|
|
349
|
+
* failure, so accept-then-close cannot loop.
|
|
350
|
+
*/
|
|
351
|
+
stableMs: 6e4,
|
|
352
|
+
/**
|
|
353
|
+
* Even while the connection is healthy, it is checked against the stamp
|
|
354
|
+
* itself this often (once per connection, in the background, never awaited
|
|
355
|
+
* by a read): a safety net for a change the stream missed. It should never
|
|
356
|
+
* miss one, but one missed would otherwise stay unseen until the stream ends.
|
|
357
|
+
*/
|
|
358
|
+
safetyPollMs: 5 * 6e4,
|
|
359
|
+
/**
|
|
360
|
+
* How long the stream may stay behind a check that found the studio ahead
|
|
361
|
+
* before it counts as having missed a change and is replaced. The studio
|
|
362
|
+
* sends a change up to 5.25 s late on purpose (at most once per 5 s per
|
|
363
|
+
* project), so a stream that is merely behind catches up well within this.
|
|
364
|
+
*/
|
|
365
|
+
lagToleranceMs: 1e4,
|
|
366
|
+
/** The longest that check may take; it runs on an unref'd socket, so it never holds a process. */
|
|
367
|
+
safetyProbeTimeoutMs: 3e3,
|
|
368
|
+
/** The longest the studio may take to answer the connection with its headers. */
|
|
369
|
+
connectTimeoutMs: 1e4,
|
|
370
|
+
/** After the studio ended a connection that lived its full term: wait 1 to 5 s. */
|
|
371
|
+
cleanMinMs: 1e3,
|
|
372
|
+
cleanMaxMs: 5e3,
|
|
373
|
+
/** After a failure: at least 1 s, then a window that doubles per failure, up to 30 s. */
|
|
374
|
+
backoffBaseMs: 1e3,
|
|
375
|
+
backoffMaxMs: 3e4,
|
|
376
|
+
/** `Retry-After` is honoured within these bounds. */
|
|
377
|
+
retryAfterMinMs: 3e4,
|
|
378
|
+
retryAfterMaxMs: 60 * 6e4,
|
|
379
|
+
/** A `429` without `Retry-After` waits as long as the studio itself asks for. */
|
|
380
|
+
rateLimitedMs: 5 * 6e4,
|
|
381
|
+
/** The most added at random to a long wait, so the sites refused together do not return together. */
|
|
382
|
+
longJitterMs: 6e4
|
|
383
|
+
};
|
|
384
|
+
function planReconnect(outcome, ctx) {
|
|
385
|
+
const attempts = ctx.stable ? 0 : ctx.attempts;
|
|
386
|
+
if (outcome.kind === "closed" && ctx.stable) {
|
|
387
|
+
return { delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 };
|
|
388
|
+
}
|
|
389
|
+
if (outcome.kind === "refused") return planRefused(outcome, { ...ctx, attempts });
|
|
390
|
+
return backoff(attempts, ctx.random);
|
|
391
|
+
}
|
|
392
|
+
function planRefused(outcome, ctx) {
|
|
393
|
+
const { status, studio } = outcome;
|
|
394
|
+
const asked = parseRetryAfter(outcome.retryAfter, ctx.now);
|
|
395
|
+
if (status === 429 || status === 503 && asked !== void 0) {
|
|
396
|
+
const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs);
|
|
397
|
+
return { delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts };
|
|
398
|
+
}
|
|
399
|
+
const studioRefusal = studio && status >= 400 && status < 500 && status !== 408;
|
|
400
|
+
if (studioRefusal || status >= 300 && status < 400) {
|
|
401
|
+
return { delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts };
|
|
402
|
+
}
|
|
403
|
+
return backoff(ctx.attempts, ctx.random);
|
|
404
|
+
}
|
|
405
|
+
function backoff(attempts, random) {
|
|
406
|
+
const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16);
|
|
407
|
+
const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window);
|
|
408
|
+
return { delay, attempts: attempts + 1 };
|
|
409
|
+
}
|
|
410
|
+
function longJitter(wait, random) {
|
|
411
|
+
return random() * Math.min(LIVE.longJitterMs, wait / 5);
|
|
412
|
+
}
|
|
413
|
+
function between(min, max, random) {
|
|
414
|
+
return min + random() * (max - min);
|
|
415
|
+
}
|
|
416
|
+
function clamp(value, min, max) {
|
|
417
|
+
return Math.min(max, Math.max(min, value));
|
|
418
|
+
}
|
|
419
|
+
var IMF_FIXDATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/;
|
|
420
|
+
function parseRetryAfter(value, now) {
|
|
421
|
+
const text = value?.trim();
|
|
422
|
+
if (!text) return void 0;
|
|
423
|
+
if (/^\d+$/.test(text)) return Number(text) * 1e3;
|
|
424
|
+
if (!IMF_FIXDATE.test(text)) return void 0;
|
|
425
|
+
const at = Date.parse(text);
|
|
426
|
+
return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
|
|
427
|
+
}
|
|
428
|
+
var SHORT_LIVED_ENV = [
|
|
429
|
+
"VERCEL",
|
|
430
|
+
"NETLIFY",
|
|
431
|
+
"AWS_LAMBDA_FUNCTION_NAME",
|
|
432
|
+
"LAMBDA_TASK_ROOT",
|
|
433
|
+
"FUNCTIONS_WORKER_RUNTIME",
|
|
434
|
+
"FUNCTION_TARGET",
|
|
435
|
+
"DENO_DEPLOYMENT_ID",
|
|
436
|
+
"K_SERVICE",
|
|
437
|
+
"CI"
|
|
438
|
+
];
|
|
439
|
+
function isShortLived(env) {
|
|
440
|
+
return SHORT_LIVED_ENV.some((name) => {
|
|
441
|
+
const value = env[name]?.trim().toLowerCase();
|
|
442
|
+
return value !== void 0 && value !== "" && value !== "0" && value !== "false";
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
function chooseLive(choice) {
|
|
446
|
+
if (!choice.runtime || !choice.revalidating || choice.option === false) return false;
|
|
447
|
+
if (choice.option === true) return true;
|
|
448
|
+
return !choice.customFetch && !choice.waitsForStudio && !isShortLived(choice.env);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/live-sse.ts
|
|
452
|
+
var DEFAULT_LIMIT = 64 * 1024;
|
|
453
|
+
var SseParser = class {
|
|
454
|
+
constructor(limit = DEFAULT_LIMIT) {
|
|
455
|
+
this.buffer = "";
|
|
456
|
+
this.data = [];
|
|
457
|
+
this.dataSize = 0;
|
|
458
|
+
this.event = "";
|
|
459
|
+
this.started = false;
|
|
460
|
+
/** The last chunk ended in `\r`: a `\n` that starts the next one belongs to it. */
|
|
461
|
+
this.afterCr = false;
|
|
462
|
+
this.limit = limit;
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* The events completed by `chunk`, in order. `null` once more than the limit
|
|
466
|
+
* is waiting for a line or an event to end: a stream like that is not the
|
|
467
|
+
* studio's, and the caller drops the connection rather than the memory.
|
|
468
|
+
*/
|
|
469
|
+
feed(chunk) {
|
|
470
|
+
const text = this.prepare(this.buffer + chunk);
|
|
471
|
+
const out = [];
|
|
472
|
+
let pos = 0;
|
|
473
|
+
const breaks = { cr: text.indexOf("\r"), lf: text.indexOf("\n") };
|
|
474
|
+
while (pos < text.length) {
|
|
475
|
+
const end = nextBreak(text, pos, breaks);
|
|
476
|
+
if (end === -1) break;
|
|
477
|
+
let next = end + 1;
|
|
478
|
+
if (text.charCodeAt(end) === 13) {
|
|
479
|
+
if (end + 1 === text.length) this.afterCr = true;
|
|
480
|
+
else if (text.charCodeAt(end + 1) === 10) next = end + 2;
|
|
481
|
+
}
|
|
482
|
+
this.line(text.slice(pos, end), out);
|
|
483
|
+
pos = next;
|
|
484
|
+
}
|
|
485
|
+
this.buffer = text.slice(pos);
|
|
486
|
+
if (this.buffer.length > this.limit || this.dataSize > this.limit) return null;
|
|
487
|
+
return out;
|
|
488
|
+
}
|
|
489
|
+
/** Drops the `\n` of a `\r\n` split over two chunks, and a byte order mark at the start. */
|
|
490
|
+
prepare(text) {
|
|
491
|
+
let out = text;
|
|
492
|
+
if (this.afterCr && out.length > 0) {
|
|
493
|
+
this.afterCr = false;
|
|
494
|
+
if (out.charCodeAt(0) === 10) out = out.slice(1);
|
|
495
|
+
}
|
|
496
|
+
if (!this.started && out.length > 0) {
|
|
497
|
+
this.started = true;
|
|
498
|
+
if (out.charCodeAt(0) === 65279) out = out.slice(1);
|
|
499
|
+
}
|
|
500
|
+
return out;
|
|
501
|
+
}
|
|
502
|
+
line(line, out) {
|
|
503
|
+
if (line === "") {
|
|
504
|
+
if (this.data.length > 0) out.push({ event: this.event || "message", data: this.data.join("\n") });
|
|
505
|
+
this.data = [];
|
|
506
|
+
this.dataSize = 0;
|
|
507
|
+
this.event = "";
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (line.charCodeAt(0) === 58) return;
|
|
511
|
+
const colon = line.indexOf(":");
|
|
512
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
513
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
514
|
+
if (value.charCodeAt(0) === 32) value = value.slice(1);
|
|
515
|
+
if (field === "event") this.event = value;
|
|
516
|
+
else if (field === "data") {
|
|
517
|
+
this.data.push(value);
|
|
518
|
+
this.dataSize += value.length + 1;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
function nextBreak(text, pos, breaks) {
|
|
523
|
+
if (breaks.cr !== -1 && breaks.cr < pos) breaks.cr = text.indexOf("\r", pos);
|
|
524
|
+
if (breaks.lf !== -1 && breaks.lf < pos) breaks.lf = text.indexOf("\n", pos);
|
|
525
|
+
const { cr, lf } = breaks;
|
|
526
|
+
return cr === -1 ? lf : lf === -1 ? cr : Math.min(cr, lf);
|
|
527
|
+
}
|
|
151
528
|
|
|
152
529
|
// src/version.ts
|
|
153
530
|
var UNSUPPORTED_PAUSE_MS = 15 * 6e4;
|
|
@@ -171,6 +548,23 @@ var VersionTracker = class {
|
|
|
171
548
|
current() {
|
|
172
549
|
return this.version;
|
|
173
550
|
}
|
|
551
|
+
/**
|
|
552
|
+
* A stamp heard from the live connection, current as of `at`. It counts as a
|
|
553
|
+
* check made at that moment: the next probe is due one interval after it.
|
|
554
|
+
* Never a request of its own, and never a reason for one.
|
|
555
|
+
*/
|
|
556
|
+
observe(version, at) {
|
|
557
|
+
this.version = version;
|
|
558
|
+
this.lastChecked = Math.max(this.lastChecked, at);
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Makes the next `refresh` ask at once, whatever the interval says (still
|
|
562
|
+
* not during the pause for a server without the route). For when the stamp
|
|
563
|
+
* may have moved unseen: the live connection went silent.
|
|
564
|
+
*/
|
|
565
|
+
due() {
|
|
566
|
+
this.lastChecked = 0;
|
|
567
|
+
}
|
|
174
568
|
/**
|
|
175
569
|
* Refresh the stamp if we are due. Resolves once the answer is in, so the
|
|
176
570
|
* read that triggered it sees an up-to-date stamp. A failed probe leaves the
|
|
@@ -204,10 +598,844 @@ var VersionTracker = class {
|
|
|
204
598
|
}
|
|
205
599
|
};
|
|
206
600
|
|
|
207
|
-
// src/
|
|
208
|
-
var
|
|
601
|
+
// src/live.ts
|
|
602
|
+
var REGISTRY = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/live-hubs/2");
|
|
603
|
+
var LINGER_MS = 5 * 6e4;
|
|
604
|
+
var REFUSAL_BODY_LIMIT = 16 * 1024;
|
|
605
|
+
function hubs() {
|
|
606
|
+
const scope = globalThis;
|
|
607
|
+
let map = scope[REGISTRY];
|
|
608
|
+
if (!map) {
|
|
609
|
+
map = /* @__PURE__ */ new Map();
|
|
610
|
+
scope[REGISTRY] = map;
|
|
611
|
+
}
|
|
612
|
+
return map;
|
|
613
|
+
}
|
|
614
|
+
var collected = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ hub, token }) => {
|
|
615
|
+
try {
|
|
616
|
+
hub.detach(token, true);
|
|
617
|
+
} catch {
|
|
618
|
+
}
|
|
619
|
+
}) : void 0;
|
|
620
|
+
function wantLive(settings) {
|
|
621
|
+
try {
|
|
622
|
+
return chooseLive({ ...settings, runtime: nodeRuntime(), env: environment() });
|
|
623
|
+
} catch {
|
|
624
|
+
return false;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
var LiveLink = class {
|
|
628
|
+
constructor(baseUrl, apiKey, headers, owner) {
|
|
629
|
+
this.baseUrl = baseUrl;
|
|
630
|
+
this.apiKey = apiKey;
|
|
631
|
+
this.headers = headers;
|
|
632
|
+
this.token = {};
|
|
633
|
+
this.silences = 0;
|
|
634
|
+
this.closed = false;
|
|
635
|
+
this.owner = owner;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* The stamp gate in front of a read, in place of `tracker.refresh`. While
|
|
639
|
+
* the connection is healthy the stamp it heard counts as a fresh check and
|
|
640
|
+
* nothing is fetched; otherwise the poll runs, at once when the connection
|
|
641
|
+
* went silent since the last read. Connects on the first call.
|
|
642
|
+
*/
|
|
643
|
+
gate(tracker, now) {
|
|
644
|
+
try {
|
|
645
|
+
const view = this.join()?.view(now);
|
|
646
|
+
if (view?.healthy && view.version !== void 0) {
|
|
647
|
+
tracker.observe(view.version, view.at);
|
|
648
|
+
this.hub?.safetyCheck(now);
|
|
649
|
+
return Promise.resolve();
|
|
650
|
+
}
|
|
651
|
+
if (view && view.silences !== this.silences) {
|
|
652
|
+
this.silences = view.silences;
|
|
653
|
+
tracker.due();
|
|
654
|
+
}
|
|
655
|
+
} catch {
|
|
656
|
+
}
|
|
657
|
+
return tracker.refresh(now);
|
|
658
|
+
}
|
|
659
|
+
/** Leaves the connection for good; the last client out closes it. */
|
|
660
|
+
close() {
|
|
661
|
+
if (this.closed) return;
|
|
662
|
+
this.closed = true;
|
|
663
|
+
const hub = this.hub;
|
|
664
|
+
this.hub = void 0;
|
|
665
|
+
this.owner = void 0;
|
|
666
|
+
if (!hub) return;
|
|
667
|
+
collected?.unregister(this.token);
|
|
668
|
+
try {
|
|
669
|
+
hub.detach(this.token, false);
|
|
670
|
+
} catch {
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
join() {
|
|
674
|
+
if (this.hub || this.closed) return this.hub;
|
|
675
|
+
const url = eventsUrl(this.baseUrl);
|
|
676
|
+
if (!url) {
|
|
677
|
+
this.closed = true;
|
|
678
|
+
return void 0;
|
|
679
|
+
}
|
|
680
|
+
const registry2 = hubs();
|
|
681
|
+
const headers = liveHeaders(this.apiKey, this.headers);
|
|
682
|
+
const id = identityOf(this.baseUrl, headers);
|
|
683
|
+
let hub = registry2.get(id);
|
|
684
|
+
if (!hub) {
|
|
685
|
+
hub = new LiveHub(id, url, headers);
|
|
686
|
+
registry2.set(id, hub);
|
|
687
|
+
}
|
|
688
|
+
this.silences = hub.attach(this.token);
|
|
689
|
+
if (this.owner) collected?.register(this.owner, { hub, token: this.token }, this.token);
|
|
690
|
+
this.owner = void 0;
|
|
691
|
+
this.hub = hub;
|
|
692
|
+
return hub;
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
function eventsUrl(baseUrl) {
|
|
696
|
+
try {
|
|
697
|
+
const url = new URL(`${baseUrl}/api/content/events`);
|
|
698
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url : void 0;
|
|
699
|
+
} catch {
|
|
700
|
+
return void 0;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function liveHeaders(apiKey, extra) {
|
|
704
|
+
const headers = sentHeaders(apiKey, extra);
|
|
705
|
+
headers.accept = "text/event-stream";
|
|
706
|
+
headers["cache-control"] = "no-cache";
|
|
707
|
+
headers["accept-encoding"] = "identity";
|
|
708
|
+
return headers;
|
|
709
|
+
}
|
|
710
|
+
var LiveHub = class {
|
|
711
|
+
constructor(id, url, headers) {
|
|
712
|
+
this.id = id;
|
|
713
|
+
this.url = url;
|
|
714
|
+
this.headers = headers;
|
|
715
|
+
this.state = "idle";
|
|
716
|
+
this.openedAt = 0;
|
|
717
|
+
this.lastHeardAt = 0;
|
|
718
|
+
/** Failures in a row, for the backoff. */
|
|
719
|
+
this.attempts = 0;
|
|
720
|
+
this.retryAt = 0;
|
|
721
|
+
this.silences = 0;
|
|
722
|
+
this.owners = /* @__PURE__ */ new Set();
|
|
723
|
+
/** Version events on the open connection: tells a stream that moved from one that did not. */
|
|
724
|
+
this.tells = 0;
|
|
725
|
+
/** When the open connection was last checked against the stamp itself. */
|
|
726
|
+
this.checkedAt = 0;
|
|
727
|
+
this.checking = false;
|
|
728
|
+
}
|
|
729
|
+
attach(token) {
|
|
730
|
+
clearTimeout(this.lingerTimer);
|
|
731
|
+
this.lingerTimer = void 0;
|
|
732
|
+
this.owners.add(token);
|
|
733
|
+
return this.silences;
|
|
734
|
+
}
|
|
735
|
+
detach(token, linger) {
|
|
736
|
+
if (!this.owners.delete(token) || this.owners.size > 0) return;
|
|
737
|
+
clearTimeout(this.lingerTimer);
|
|
738
|
+
if (linger) this.lingerTimer = unrefTimer(() => this.owners.size === 0 && this.dispose(), LINGER_MS);
|
|
739
|
+
else this.dispose();
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* The state of the connection for a read at `now`, after the checks a read
|
|
743
|
+
* makes: connect the first time; a connection silent for `LIVE.staleMs` is
|
|
744
|
+
* dead (a frozen process misses events and runs no timers, so the watchdog
|
|
745
|
+
* alone cannot be trusted); a reconnect whose time has come goes now.
|
|
746
|
+
*/
|
|
747
|
+
view(now) {
|
|
748
|
+
if (this.state === "idle") this.connect();
|
|
749
|
+
else if (this.state === "open" && now - this.lastHeardAt > LIVE.staleMs) this.current?.end({ kind: "silent" });
|
|
750
|
+
else if (this.state === "waiting" && now >= this.retryAt) this.connect();
|
|
751
|
+
if (this.state === "open" && this.behind) this.judgeBehind(now);
|
|
752
|
+
return {
|
|
753
|
+
healthy: this.state === "open" && this.version !== void 0,
|
|
754
|
+
version: this.version,
|
|
755
|
+
at: this.lastHeardAt,
|
|
756
|
+
silences: this.silences
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* The safety net, at most once per `LIVE.safetyPollMs` per connection, set
|
|
761
|
+
* off by a read: ask the stamp and compare it with the stream's. Never
|
|
762
|
+
* awaited by a read, never reported, and over an unref'd socket, so it holds
|
|
763
|
+
* up no read and no process. Only a clear answer counts: a failed check, a
|
|
764
|
+
* check that outlived its connection, or one during which the stream told a
|
|
765
|
+
* new stamp proves nothing. A studio ahead of the stream is noted, not acted
|
|
766
|
+
* on: see `judgeBehind`.
|
|
767
|
+
*/
|
|
768
|
+
safetyCheck(now) {
|
|
769
|
+
if (this.state !== "open" || this.version === void 0 || this.checking || this.behind) return;
|
|
770
|
+
if (now - this.checkedAt < LIVE.safetyPollMs) return;
|
|
771
|
+
this.checking = true;
|
|
772
|
+
this.checkedAt = now;
|
|
773
|
+
const attempt = this.current;
|
|
774
|
+
const tells = this.tells;
|
|
775
|
+
const heard = this.version;
|
|
776
|
+
const url = versionUrl(this.url);
|
|
777
|
+
const headers = { ...this.headers, accept: "application/json" };
|
|
778
|
+
loadHttp(url.protocol).then((http) => probeStamp(http, url, headers), () => void 0).then(
|
|
779
|
+
(stamp) => {
|
|
780
|
+
this.checking = false;
|
|
781
|
+
if (stamp === void 0 || attempt !== this.current || tells !== this.tells) return;
|
|
782
|
+
if (stamp !== heard) this.behind = { tells, since: Date.now() };
|
|
783
|
+
},
|
|
784
|
+
() => {
|
|
785
|
+
this.checking = false;
|
|
786
|
+
}
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* A check found the studio ahead of the stream. The studio sends late on
|
|
791
|
+
* purpose (its 5 s throttle), so that alone is no fault: only a stream that
|
|
792
|
+
* told nothing new for `LIVE.lagToleranceMs` since then missed a change. The
|
|
793
|
+
* first read after that drops it, which makes that same read check the stamp
|
|
794
|
+
* itself (and the hub reconnect).
|
|
795
|
+
*/
|
|
796
|
+
judgeBehind(now) {
|
|
797
|
+
const behind = this.behind;
|
|
798
|
+
if (this.tells !== behind.tells) this.behind = void 0;
|
|
799
|
+
else if (now - behind.since >= LIVE.lagToleranceMs) {
|
|
800
|
+
this.behind = void 0;
|
|
801
|
+
this.current?.end({ kind: "silent" });
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
connect() {
|
|
805
|
+
clearTimeout(this.retryTimer);
|
|
806
|
+
this.state = "connecting";
|
|
807
|
+
const attempt = new LiveAttempt(this);
|
|
808
|
+
this.current = attempt;
|
|
809
|
+
loadHttp(this.url.protocol).then(
|
|
810
|
+
(http) => {
|
|
811
|
+
if (this.current === attempt) attempt.start(http, this.url, this.headers);
|
|
812
|
+
},
|
|
813
|
+
() => {
|
|
814
|
+
if (this.current === attempt) this.halt();
|
|
815
|
+
}
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
/** The attempt got its stream: the studio's answer is in. */
|
|
819
|
+
opened(attempt) {
|
|
820
|
+
if (attempt !== this.current) return;
|
|
821
|
+
this.state = "open";
|
|
822
|
+
this.version = void 0;
|
|
823
|
+
this.openedAt = Date.now();
|
|
824
|
+
this.lastHeardAt = this.openedAt;
|
|
825
|
+
this.checkedAt = this.openedAt;
|
|
826
|
+
this.behind = void 0;
|
|
827
|
+
}
|
|
828
|
+
/** Something came in on the stream: a sign of life. */
|
|
829
|
+
heard(attempt) {
|
|
830
|
+
if (attempt === this.current) this.lastHeardAt = Date.now();
|
|
831
|
+
}
|
|
832
|
+
/** A `version` event, its data as sent. */
|
|
833
|
+
told(attempt, data) {
|
|
834
|
+
if (attempt !== this.current) return;
|
|
835
|
+
try {
|
|
836
|
+
const version = JSON.parse(data)?.version;
|
|
837
|
+
if (typeof version === "string" && version !== "") {
|
|
838
|
+
this.version = version;
|
|
839
|
+
this.tells++;
|
|
840
|
+
}
|
|
841
|
+
} catch {
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
/** The attempt is over: plan the next one. `outcome` is absent when the hub ended it itself. */
|
|
845
|
+
ended(attempt, outcome) {
|
|
846
|
+
if (attempt !== this.current) return;
|
|
847
|
+
this.current = void 0;
|
|
848
|
+
const now = Date.now();
|
|
849
|
+
const stable = this.state === "open" && this.version !== void 0 && now - this.openedAt >= LIVE.stableMs;
|
|
850
|
+
this.version = void 0;
|
|
851
|
+
if (!outcome || this.state === "stopped") return;
|
|
852
|
+
if (outcome.kind === "silent") this.silences++;
|
|
853
|
+
const plan = planReconnect(outcome, { attempts: this.attempts, stable, pauseMs: UNSUPPORTED_PAUSE_MS, now, random: Math.random });
|
|
854
|
+
this.attempts = plan.attempts;
|
|
855
|
+
this.state = "waiting";
|
|
856
|
+
this.retryAt = now + plan.delay;
|
|
857
|
+
this.retryTimer = unrefTimer(() => {
|
|
858
|
+
if (this.state === "waiting") this.connect();
|
|
859
|
+
}, plan.delay);
|
|
860
|
+
}
|
|
861
|
+
/** Stops for good (no `http` here, or the last client left): reads keep to the poll. */
|
|
862
|
+
halt() {
|
|
863
|
+
this.state = "stopped";
|
|
864
|
+
clearTimeout(this.retryTimer);
|
|
865
|
+
const attempt = this.current;
|
|
866
|
+
this.current = void 0;
|
|
867
|
+
this.version = void 0;
|
|
868
|
+
attempt?.end();
|
|
869
|
+
}
|
|
870
|
+
dispose() {
|
|
871
|
+
this.halt();
|
|
872
|
+
const registry2 = hubs();
|
|
873
|
+
if (registry2.get(this.id) === this) registry2.delete(this.id);
|
|
874
|
+
}
|
|
875
|
+
};
|
|
876
|
+
var LiveAttempt = class {
|
|
877
|
+
constructor(hub) {
|
|
878
|
+
this.hub = hub;
|
|
879
|
+
this.done = false;
|
|
880
|
+
this.timers = [];
|
|
881
|
+
}
|
|
882
|
+
start(http, url, headers) {
|
|
883
|
+
if (this.done) return;
|
|
884
|
+
this.timers.push(unrefTimer(() => this.end({ kind: "failed" }), LIVE.connectTimeoutMs));
|
|
885
|
+
try {
|
|
886
|
+
const req = http.request(url, { method: "GET", headers, agent: false }, (res) => this.answered(res));
|
|
887
|
+
this.req = req;
|
|
888
|
+
req.on("socket", (socket) => {
|
|
889
|
+
try {
|
|
890
|
+
socket.unref();
|
|
891
|
+
} catch {
|
|
892
|
+
this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
try {
|
|
896
|
+
socket.setKeepAlive(true, 3e4);
|
|
897
|
+
} catch {
|
|
898
|
+
}
|
|
899
|
+
});
|
|
900
|
+
req.on("error", () => this.end({ kind: "failed" }));
|
|
901
|
+
req.end();
|
|
902
|
+
} catch {
|
|
903
|
+
this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
/** Ends the attempt; the hub plans what comes next from `outcome`, unless it ended it itself. */
|
|
907
|
+
end(outcome) {
|
|
908
|
+
if (this.done) return;
|
|
909
|
+
this.done = true;
|
|
910
|
+
for (const timer of this.timers) clearTimeout(timer);
|
|
911
|
+
try {
|
|
912
|
+
this.req?.destroy();
|
|
913
|
+
} catch {
|
|
914
|
+
}
|
|
915
|
+
this.hub.ended(this, outcome);
|
|
916
|
+
}
|
|
917
|
+
answered(res) {
|
|
918
|
+
res.on("error", () => this.end({ kind: "failed" }));
|
|
919
|
+
if (this.done) {
|
|
920
|
+
res.resume();
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
const type = String(res.headers["content-type"] ?? "");
|
|
924
|
+
if (res.statusCode === 200 && type.includes("text/event-stream")) this.stream(res);
|
|
925
|
+
else this.refused(res);
|
|
926
|
+
}
|
|
927
|
+
stream(res) {
|
|
928
|
+
for (const timer of this.timers) clearTimeout(timer);
|
|
929
|
+
this.timers = [];
|
|
930
|
+
const watchdog = unrefTimer(() => this.end({ kind: "silent" }), LIVE.staleMs);
|
|
931
|
+
this.timers.push(watchdog);
|
|
932
|
+
this.hub.opened(this);
|
|
933
|
+
const parser = new SseParser();
|
|
934
|
+
res.setEncoding("utf8");
|
|
935
|
+
res.on("data", (chunk) => {
|
|
936
|
+
if (this.done) return;
|
|
937
|
+
watchdog.refresh?.();
|
|
938
|
+
this.hub.heard(this);
|
|
939
|
+
const events = parser.feed(chunk);
|
|
940
|
+
if (events === null) {
|
|
941
|
+
this.end({ kind: "failed" });
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
for (const event of events) {
|
|
945
|
+
if (event.event === "version") this.hub.told(this, event.data);
|
|
946
|
+
}
|
|
947
|
+
});
|
|
948
|
+
res.on("end", () => this.end({ kind: "closed" }));
|
|
949
|
+
res.on("close", () => this.end({ kind: "failed" }));
|
|
950
|
+
}
|
|
951
|
+
/** Not the stream: read a little of the body, to tell the studio's own refusal from a proxy's. */
|
|
952
|
+
refused(res) {
|
|
953
|
+
const status = res.statusCode ?? 0;
|
|
954
|
+
const header = res.headers["retry-after"];
|
|
955
|
+
const retryAfter = (Array.isArray(header) ? header[0] : header) ?? null;
|
|
956
|
+
let body = "";
|
|
957
|
+
res.setEncoding("utf8");
|
|
958
|
+
res.on("data", (chunk) => {
|
|
959
|
+
body += chunk;
|
|
960
|
+
if (body.length > REFUSAL_BODY_LIMIT) res.destroy();
|
|
961
|
+
});
|
|
962
|
+
const settle = () => this.end({ kind: "refused", status, retryAfter, studio: isStudioBody(status, parseJson(body)) });
|
|
963
|
+
res.on("end", settle);
|
|
964
|
+
res.on("close", settle);
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
function versionUrl(events) {
|
|
968
|
+
const url = new URL(events.href);
|
|
969
|
+
url.pathname = url.pathname.replace(/events$/, "version");
|
|
970
|
+
return url;
|
|
971
|
+
}
|
|
972
|
+
async function probeStamp(http, url, headers) {
|
|
973
|
+
const stamp = (await getJson(http, url, headers, LIVE.safetyProbeTimeoutMs))?.version;
|
|
974
|
+
return typeof stamp === "string" && stamp !== "" ? stamp : void 0;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// src/file-cache.ts
|
|
978
|
+
var ATTACH = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/file-cache-attach/3");
|
|
979
|
+
var SUFFIX = ".json";
|
|
980
|
+
var CACHE_FILE = /^[0-9a-f]{64}\.json$/;
|
|
981
|
+
var TEMP_FILE = /^[0-9a-f]{64}\.json\.\d+(\.[0-9a-f]+)?\.tmp$/;
|
|
982
|
+
var FOLDER = /^[0-9a-f]{16}$/;
|
|
983
|
+
var MARKER = ".beacon-cache";
|
|
984
|
+
var MARKER_TEXT = "A cache of @nordhavnhq/beacon. Removed by beacon once unused for 30 days; safe to delete.\n";
|
|
985
|
+
var TEMP_ORPHAN_MS = 6e4;
|
|
986
|
+
var STALE_MS = 30 * 24 * 36e5;
|
|
987
|
+
var TOUCH_MS = 24 * 36e5;
|
|
988
|
+
var FileCache = class {
|
|
989
|
+
constructor(options, deps) {
|
|
990
|
+
/** Same order contract as `MemoryCacheStore`: oldest written first. */
|
|
991
|
+
this.map = /* @__PURE__ */ new Map();
|
|
992
|
+
/** Read from disk on first use, not at construction: a client attaching first decides where from. */
|
|
993
|
+
this.loaded = false;
|
|
994
|
+
this.touchedAt = 0;
|
|
995
|
+
/** Where the one warning goes without an `onError`: the console, or the attaching client's `logger`. */
|
|
996
|
+
this.warnTo = (...args) => console.warn(...args);
|
|
997
|
+
if (!options?.dir) throw new Error("FileCacheStore: `dir` is required");
|
|
998
|
+
this.dir = options.dir;
|
|
999
|
+
this.folder = options.dir;
|
|
1000
|
+
this.maxEntries = options.maxEntries ?? 500;
|
|
1001
|
+
this.deps = deps;
|
|
1002
|
+
let warned = false;
|
|
1003
|
+
this.onError = options.onError ?? ((err) => {
|
|
1004
|
+
if (warned) return;
|
|
1005
|
+
warned = true;
|
|
1006
|
+
this.warnTo?.(`[@nordhavnhq/beacon] file cache at ${this.folder} unusable, continuing in memory:`, err instanceof Error ? err.message : err);
|
|
1007
|
+
});
|
|
1008
|
+
this.ownWarning = options.onError === void 0;
|
|
1009
|
+
}
|
|
1010
|
+
get(key) {
|
|
1011
|
+
this.ensureLoaded();
|
|
1012
|
+
this.touch();
|
|
1013
|
+
return this.map.get(key);
|
|
1014
|
+
}
|
|
1015
|
+
set(key, entry) {
|
|
1016
|
+
this.ensureLoaded();
|
|
1017
|
+
this.map.delete(key);
|
|
1018
|
+
this.map.set(key, entry);
|
|
1019
|
+
this.write(key, entry);
|
|
1020
|
+
this.evict();
|
|
1021
|
+
}
|
|
1022
|
+
delete(key) {
|
|
1023
|
+
this.ensureLoaded();
|
|
1024
|
+
this.map.delete(key);
|
|
1025
|
+
this.remove(this.fileOf(key));
|
|
1026
|
+
}
|
|
1027
|
+
keys() {
|
|
1028
|
+
this.ensureLoaded();
|
|
1029
|
+
return this.map.keys();
|
|
1030
|
+
}
|
|
1031
|
+
clear() {
|
|
1032
|
+
this.ensureLoaded();
|
|
1033
|
+
this.map.clear();
|
|
1034
|
+
for (const name of this.list(this.folder)) {
|
|
1035
|
+
if (CACHE_FILE.test(name)) this.remove(this.deps.join(this.folder, name));
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Moves the store into its folder (`<dir>/<hash>`) and reads that; copies
|
|
1040
|
+
* the cache files of 0.7 in when asked and the folder is empty; then clears
|
|
1041
|
+
* out folders of this store that went unused (`sweep`). Entries already
|
|
1042
|
+
* read from `dir` itself are dropped from memory. A second client with the
|
|
1043
|
+
* same identity finds it done; one with another identity is refused, as the
|
|
1044
|
+
* store holds one site's entries.
|
|
1045
|
+
*/
|
|
1046
|
+
[ATTACH](scope) {
|
|
1047
|
+
const hash = this.deps.sha256(scope.identity).slice(0, 16);
|
|
1048
|
+
if (this.hash !== void 0) {
|
|
1049
|
+
return this.hash === hash && this.attached ? { ...this.attached, first: false } : void 0;
|
|
1050
|
+
}
|
|
1051
|
+
if (this.ownWarning) this.warnTo = scope.warn;
|
|
1052
|
+
this.hash = hash;
|
|
1053
|
+
this.folder = this.deps.join(this.dir, hash);
|
|
1054
|
+
this.map.clear();
|
|
1055
|
+
this.loaded = false;
|
|
1056
|
+
this.ensureLoaded();
|
|
1057
|
+
this.mark();
|
|
1058
|
+
const legacy = this.legacyFiles();
|
|
1059
|
+
const copied = scope.adoptLegacy && this.map.size === 0 ? this.adopt(legacy) : 0;
|
|
1060
|
+
this.sweep();
|
|
1061
|
+
this.attached = { store: this, dir: this.dir, folder: this.folder, loaded: this.map.size, legacy: legacy.length, copied, first: true };
|
|
1062
|
+
return this.attached;
|
|
1063
|
+
}
|
|
1064
|
+
// ── Disk ────────────────────────────────────────────────────────────────────
|
|
1065
|
+
/** File name per key: a hash, as keys hold `/` and `:` and may be long. */
|
|
1066
|
+
fileOf(key, folder = this.folder) {
|
|
1067
|
+
return this.deps.join(folder, this.deps.sha256(key) + SUFFIX);
|
|
1068
|
+
}
|
|
1069
|
+
ensureLoaded() {
|
|
1070
|
+
if (this.loaded) return;
|
|
1071
|
+
this.loaded = true;
|
|
1072
|
+
this.load();
|
|
1073
|
+
}
|
|
1074
|
+
/** Fills memory from disk, oldest file first so eviction order survives a restart. */
|
|
1075
|
+
load() {
|
|
1076
|
+
try {
|
|
1077
|
+
this.deps.fs.mkdirSync(this.folder, { recursive: true });
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
this.fail(err);
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
for (const name of this.list(this.folder)) {
|
|
1083
|
+
if (TEMP_FILE.test(name)) {
|
|
1084
|
+
const file = this.deps.join(this.folder, name);
|
|
1085
|
+
if (this.olderThan(file, TEMP_ORPHAN_MS)) this.remove(file);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
const found = this.readEntries(this.folder, (file) => this.remove(file));
|
|
1089
|
+
for (const { key, entry } of found) this.map.set(key, entry);
|
|
1090
|
+
this.evict();
|
|
1091
|
+
}
|
|
1092
|
+
/**
|
|
1093
|
+
* The readable cache files in `folder`, oldest first. Files that are this
|
|
1094
|
+
* store's by name but not a cache entry (half written, filed under another
|
|
1095
|
+
* key) go to `bad`; anything else in `folder` is not looked at.
|
|
1096
|
+
*/
|
|
1097
|
+
readEntries(folder, bad) {
|
|
1098
|
+
const { fs } = this.deps;
|
|
1099
|
+
const found = [];
|
|
1100
|
+
for (const name of this.list(folder)) {
|
|
1101
|
+
if (!CACHE_FILE.test(name)) continue;
|
|
1102
|
+
const file = this.deps.join(folder, name);
|
|
1103
|
+
try {
|
|
1104
|
+
const stored = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1105
|
+
if (stored?.v !== 1 || typeof stored.key !== "string" || !stored.entry || file !== this.fileOf(stored.key, folder)) {
|
|
1106
|
+
throw new Error("not a cache file");
|
|
1107
|
+
}
|
|
1108
|
+
found.push({ key: stored.key, entry: stored.entry, mtime: fs.statSync(file).mtimeMs });
|
|
1109
|
+
} catch {
|
|
1110
|
+
bad(file);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
return found.sort((a, b) => a.mtime - b.mtime);
|
|
1114
|
+
}
|
|
1115
|
+
/** The cache files of 0.7 in `dir` itself: read only, never changed or removed. */
|
|
1116
|
+
legacyFiles() {
|
|
1117
|
+
return this.readEntries(this.dir, () => {
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* Copies the cache files of 0.7 into the (empty) folder, the newest
|
|
1122
|
+
* `maxEntries` of them, so a site that restarts during an outage right after
|
|
1123
|
+
* upgrading still has its content. Copied, not moved: a 0.7 process on the
|
|
1124
|
+
* same directory (the old container during a redeploy) keeps its own.
|
|
1125
|
+
*/
|
|
1126
|
+
adopt(legacy) {
|
|
1127
|
+
const take = legacy.slice(-this.maxEntries);
|
|
1128
|
+
for (const { key, entry } of take) {
|
|
1129
|
+
this.map.set(key, entry);
|
|
1130
|
+
this.write(key, entry);
|
|
1131
|
+
}
|
|
1132
|
+
return take.length;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* At attach, in `dir`: removes the folders of this store that went unused
|
|
1136
|
+
* for `STALE_MS`. A folder counts only when its name is a hash, it carries
|
|
1137
|
+
* `MARKER`, and it holds nothing but cache files, temp files and the
|
|
1138
|
+
* marker: then those go, and the folder. Anything else (a folder of the
|
|
1139
|
+
* site's, another site's 0.7 cache files, a folder with one foreign file in
|
|
1140
|
+
* it) is never touched, and neither is anything in `dir` itself.
|
|
1141
|
+
*
|
|
1142
|
+
* Silent on failure: this is tidying, not caching, and a folder another
|
|
1143
|
+
* user owns is no reason to say the cache is unusable.
|
|
1144
|
+
*/
|
|
1145
|
+
sweep() {
|
|
1146
|
+
const { fs, join } = this.deps;
|
|
1147
|
+
let entries;
|
|
1148
|
+
try {
|
|
1149
|
+
entries = fs.readdirSync(this.dir, { withFileTypes: true });
|
|
1150
|
+
} catch {
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
for (const entry of entries) {
|
|
1154
|
+
if (!entry.isDirectory() || !FOLDER.test(entry.name) || entry.name === this.hash) continue;
|
|
1155
|
+
const folder = join(this.dir, entry.name);
|
|
1156
|
+
const marker = join(folder, MARKER);
|
|
1157
|
+
if (!this.olderThan(marker, STALE_MS) || !this.olderThan(folder, STALE_MS)) continue;
|
|
1158
|
+
this.quietly(() => {
|
|
1159
|
+
const names = fs.readdirSync(folder);
|
|
1160
|
+
if (!names.every((name) => name === MARKER || CACHE_FILE.test(name) || TEMP_FILE.test(name))) return;
|
|
1161
|
+
for (const name of names) fs.rmSync(join(folder, name), { force: true });
|
|
1162
|
+
fs.rmdirSync(folder);
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
/** Puts `MARKER` in the folder, or marks it as used if it is there: see `touch`. */
|
|
1167
|
+
mark() {
|
|
1168
|
+
const marker = this.deps.join(this.folder, MARKER);
|
|
1169
|
+
const now = /* @__PURE__ */ new Date();
|
|
1170
|
+
this.touchedAt = now.getTime();
|
|
1171
|
+
this.quietly(() => {
|
|
1172
|
+
try {
|
|
1173
|
+
this.deps.fs.utimesSync(marker, now, now);
|
|
1174
|
+
} catch {
|
|
1175
|
+
this.deps.fs.writeFileSync(marker, MARKER_TEXT);
|
|
1176
|
+
}
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Marks the folder as used, at most once per `TOUCH_MS`: a site whose
|
|
1181
|
+
* content does not change writes nothing, and its folder must not look
|
|
1182
|
+
* abandoned to the sweep of another site sharing `dir`.
|
|
1183
|
+
*/
|
|
1184
|
+
touch() {
|
|
1185
|
+
if (this.hash === void 0 || Date.now() - this.touchedAt < TOUCH_MS) return;
|
|
1186
|
+
this.mark();
|
|
1187
|
+
}
|
|
1188
|
+
evict() {
|
|
1189
|
+
while (this.map.size > this.maxEntries) {
|
|
1190
|
+
const oldest = this.map.keys().next().value;
|
|
1191
|
+
if (oldest === void 0) break;
|
|
1192
|
+
this.delete(oldest);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
/** Temp file plus rename, so a reader (or a crash) never sees half a file. */
|
|
1196
|
+
write(key, entry) {
|
|
1197
|
+
const file = this.fileOf(key);
|
|
1198
|
+
const tmp = `${file}.${processId()}.${this.deps.randomHex(6)}.tmp`;
|
|
1199
|
+
const stored = JSON.stringify({ v: 1, key, entry });
|
|
1200
|
+
try {
|
|
1201
|
+
this.writeAt(tmp, file, stored);
|
|
1202
|
+
} catch (err) {
|
|
1203
|
+
this.remove(tmp);
|
|
1204
|
+
this.fail(err);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* One write. A folder that is gone, before the temp file is written or
|
|
1209
|
+
* before it is renamed, is made again and the write done once more: the
|
|
1210
|
+
* sweep of another site sharing `dir` removes a folder only after 30 days
|
|
1211
|
+
* unused, but a process may well sit that long without a read, and a
|
|
1212
|
+
* person may clear the directory by hand. Only a failure that outlasts
|
|
1213
|
+
* that second try is reported.
|
|
1214
|
+
*/
|
|
1215
|
+
writeAt(tmp, file, stored) {
|
|
1216
|
+
const { fs } = this.deps;
|
|
1217
|
+
try {
|
|
1218
|
+
fs.writeFileSync(tmp, stored);
|
|
1219
|
+
fs.renameSync(tmp, file);
|
|
1220
|
+
} catch (err) {
|
|
1221
|
+
if (!isMissing(err)) throw err;
|
|
1222
|
+
fs.mkdirSync(this.folder, { recursive: true });
|
|
1223
|
+
if (this.hash !== void 0) this.mark();
|
|
1224
|
+
fs.writeFileSync(tmp, stored);
|
|
1225
|
+
fs.renameSync(tmp, file);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* Hands a disk problem to `onError`. Never throws and never leaves a rejection
|
|
1230
|
+
* behind: this runs inside a cache write, which runs inside a read, and a
|
|
1231
|
+
* hook that fails (or an `async` one whose own work fails) must not fail the
|
|
1232
|
+
* read or stop the process over a cache that merely fell back to memory.
|
|
1233
|
+
*/
|
|
1234
|
+
fail(err) {
|
|
1235
|
+
try {
|
|
1236
|
+
const outcome = this.onError(err);
|
|
1237
|
+
if (typeof outcome?.then === "function") {
|
|
1238
|
+
outcome.then(void 0, () => {
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
} catch {
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
/** Whether a file or folder was last changed more than `ms` ago. Unknown (missing) counts as "no". */
|
|
1245
|
+
olderThan(path, ms) {
|
|
1246
|
+
try {
|
|
1247
|
+
return Date.now() - this.deps.fs.statSync(path).mtimeMs > ms;
|
|
1248
|
+
} catch {
|
|
1249
|
+
return false;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
quietly(run) {
|
|
1253
|
+
try {
|
|
1254
|
+
run();
|
|
1255
|
+
} catch {
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
remove(file) {
|
|
1259
|
+
try {
|
|
1260
|
+
this.deps.fs.rmSync(file, { force: true });
|
|
1261
|
+
} catch (err) {
|
|
1262
|
+
this.fail(err);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
/** The names in `folder`; none for a folder that is not there (yet, or any more), which is no disk problem. */
|
|
1266
|
+
list(folder) {
|
|
1267
|
+
try {
|
|
1268
|
+
return this.deps.fs.readdirSync(folder);
|
|
1269
|
+
} catch (err) {
|
|
1270
|
+
if (!isMissing(err)) this.fail(err);
|
|
1271
|
+
return [];
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
var FILE_CACHES = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/file-caches/2");
|
|
1276
|
+
var FIRST_STARTS = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/first-starts/1");
|
|
1277
|
+
function hasFolders(deps, dir) {
|
|
1278
|
+
const { fs, join } = deps;
|
|
1279
|
+
try {
|
|
1280
|
+
return fs.readdirSync(dir, { withFileTypes: true }).some((entry) => entry.isDirectory() && FOLDER.test(entry.name) && fs.readdirSync(join(dir, entry.name)).includes(MARKER));
|
|
1281
|
+
} catch {
|
|
1282
|
+
return false;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
function registry(symbol) {
|
|
1286
|
+
const scope = globalThis;
|
|
1287
|
+
const map = scope[symbol] ?? /* @__PURE__ */ new Map();
|
|
1288
|
+
scope[symbol] = map;
|
|
1289
|
+
return map;
|
|
1290
|
+
}
|
|
1291
|
+
function attachShared(options, deps, scope) {
|
|
1292
|
+
const dir = deps.resolve(options.dir);
|
|
1293
|
+
const firstStarts = registry(FIRST_STARTS);
|
|
1294
|
+
if (!firstStarts.has(dir)) firstStarts.set(dir, !hasFolders(deps, dir));
|
|
1295
|
+
const caches = registry(FILE_CACHES);
|
|
1296
|
+
const id = `${dir}
|
|
1297
|
+
${scope.identity}`;
|
|
1298
|
+
const maxEntries = options.maxEntries ?? 500;
|
|
1299
|
+
let shared = caches.get(id);
|
|
1300
|
+
if (!shared) {
|
|
1301
|
+
shared = { cache: new FileCache(options, deps), maxEntries, onError: options.onError, told: false };
|
|
1302
|
+
caches.set(id, shared);
|
|
1303
|
+
}
|
|
1304
|
+
const attached = shared.cache[ATTACH]({ ...scope, adoptLegacy: scope.adoptLegacy && firstStarts.get(dir) === true });
|
|
1305
|
+
const differs = maxEntries !== shared.maxEntries || options.onError !== void 0 && options.onError !== shared.onError;
|
|
1306
|
+
if (attached && differs && !shared.told) {
|
|
1307
|
+
shared.told = true;
|
|
1308
|
+
scope.warn?.(`[@nordhavnhq/beacon] file cache ${attached.folder} is already open in this process: its first settings apply (maxEntries ${shared.maxEntries}, ${shared.onError ? "the first store's onError" : "no onError"}), not this one's`);
|
|
1309
|
+
}
|
|
1310
|
+
return attached;
|
|
1311
|
+
}
|
|
1312
|
+
function isMissing(err) {
|
|
1313
|
+
return err?.code === "ENOENT";
|
|
1314
|
+
}
|
|
1315
|
+
function processId() {
|
|
1316
|
+
return globalThis.process?.pid ?? 0;
|
|
1317
|
+
}
|
|
1318
|
+
function builtinFileDeps(builtin) {
|
|
1319
|
+
const fs = builtin("node:fs");
|
|
1320
|
+
const crypto = builtin("node:crypto");
|
|
1321
|
+
const path = builtin("node:path");
|
|
1322
|
+
if (!fs || !crypto || !path) return void 0;
|
|
1323
|
+
return fileDeps(fs, crypto, path);
|
|
1324
|
+
}
|
|
1325
|
+
function fileDeps(fs, crypto, path) {
|
|
1326
|
+
return {
|
|
1327
|
+
fs,
|
|
1328
|
+
join: path.join,
|
|
1329
|
+
resolve: path.resolve,
|
|
1330
|
+
sha256: (text) => crypto.createHash("sha256").update(text).digest("hex"),
|
|
1331
|
+
randomHex: (bytes) => crypto.randomBytes(bytes).toString("hex")
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
// src/options.ts
|
|
209
1336
|
var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
|
|
1337
|
+
var API_KEY_ENV = "NORDHAVN_API_KEY";
|
|
1338
|
+
var BASE_URL_ENV = "NORDHAVN_BASE_URL";
|
|
1339
|
+
function connectionOf(options) {
|
|
1340
|
+
const apiKey = "apiKey" in options ? options.apiKey?.trim() : readEnv(API_KEY_ENV);
|
|
1341
|
+
if (!apiKey) throw new Error(missingKey(options));
|
|
1342
|
+
const baseUrl = "baseUrl" in options ? options.baseUrl === void 0 ? DEFAULT_BASE_URL : options.baseUrl.trim() : readEnv(BASE_URL_ENV) ?? DEFAULT_BASE_URL;
|
|
1343
|
+
if (!baseUrl) {
|
|
1344
|
+
throw new Error("NordhavnClient: `baseUrl` is empty (leave it out for NORDHAVN_BASE_URL or the hosted platform)");
|
|
1345
|
+
}
|
|
1346
|
+
return { apiKey, baseUrl: baseUrl.replace(/\/+$/, "") };
|
|
1347
|
+
}
|
|
1348
|
+
function missingKey(options) {
|
|
1349
|
+
if (!("apiKey" in options)) return `NordhavnClient: \`apiKey\` is required: pass it, or set ${API_KEY_ENV}`;
|
|
1350
|
+
if (options.apiKey === void 0) {
|
|
1351
|
+
return `NordhavnClient: \`apiKey\` is required (it was passed as \`undefined\`; leave it out altogether to read ${API_KEY_ENV})`;
|
|
1352
|
+
}
|
|
1353
|
+
return "NordhavnClient: `apiKey` is empty (an empty string does not fall back to the environment)";
|
|
1354
|
+
}
|
|
1355
|
+
function cacheStore(options, identity, log) {
|
|
1356
|
+
if (options.enabled === false) return options.store;
|
|
1357
|
+
const dir = options.dir || void 0;
|
|
1358
|
+
if (dir !== void 0 && options.store !== void 0) {
|
|
1359
|
+
throw new Error("NordhavnClient: pass `cache.dir` or `cache.store`, not both");
|
|
1360
|
+
}
|
|
1361
|
+
const warn = log && typeof log.warn === "function" ? (...args) => log.warn(...args) : void 0;
|
|
1362
|
+
const scope = { identity, adoptLegacy: dir === void 0, warn };
|
|
1363
|
+
let attached;
|
|
1364
|
+
if (dir !== void 0) {
|
|
1365
|
+
const deps = builtinFileDeps(nodeBuiltin);
|
|
1366
|
+
if (!deps) {
|
|
1367
|
+
if (firstTime("no-file-cache")) {
|
|
1368
|
+
logLine(log, "warn", "`cache.dir` needs Node 22.3 or later (`process.getBuiltinModule`): caching in memory. `FileCacheStore` from `@nordhavnhq/beacon/file-store` works on any Node.");
|
|
1369
|
+
}
|
|
1370
|
+
return void 0;
|
|
1371
|
+
}
|
|
1372
|
+
attached = attachShared({ dir, maxEntries: options.maxEntries }, deps, scope);
|
|
1373
|
+
} else {
|
|
1374
|
+
const attach = options.store?.[ATTACH];
|
|
1375
|
+
if (typeof attach !== "function") return options.store;
|
|
1376
|
+
attached = attach.call(options.store, scope);
|
|
1377
|
+
}
|
|
1378
|
+
if (!attached) {
|
|
1379
|
+
logLine(log, "warn", "this FileCacheStore (a subclass, used as given) already holds the cache of another key, so this client caches in memory. Give each key its own store.");
|
|
1380
|
+
return new MemoryCacheStore(options.maxEntries ?? 500);
|
|
1381
|
+
}
|
|
1382
|
+
if (attached.first) tellDisk(attached, dir === void 0, log);
|
|
1383
|
+
return attached.store;
|
|
1384
|
+
}
|
|
1385
|
+
function tellDisk(attached, fromStore, log) {
|
|
1386
|
+
const { folder, loaded, legacy, copied } = attached;
|
|
1387
|
+
if (copied > 0 && firstTime(`copied
|
|
1388
|
+
${folder}`)) {
|
|
1389
|
+
logLine(log, "info", `file cache ${folder}: ${count(copied, "entry", "entries")} copied from the cache beacon 0.7 kept in ${attached.dir}, which is left as it is`);
|
|
1390
|
+
} else if (copied === 0 && legacy > 0 && loaded === 0 && firstTime(`legacy
|
|
1391
|
+
${folder}`)) {
|
|
1392
|
+
const why = fromStore ? "only the first start after 0.7 copies them" : "`cache.dir` keeps its entries per key";
|
|
1393
|
+
logLine(log, "info", `file cache ${attached.dir}: ${count(legacy, "entry", "entries")} left by beacon 0.7 ${legacy === 1 ? "is" : "are"} not used for this key (${why}); this cache starts empty in ${folder}`);
|
|
1394
|
+
}
|
|
1395
|
+
if (!firstTime(`disk
|
|
1396
|
+
${folder}`)) return;
|
|
1397
|
+
if (loaded > 0) logLine(log, "info", `file cache ${folder}: ${count(loaded, "entry", "entries")} on disk`);
|
|
1398
|
+
else logLine(log, "warn", `file cache ${folder}: nothing on disk yet, so until the studio has answered once, a read fails while it is unreachable. Expected on a first start; on every start, the directory does not survive a restart (put it on a persistent volume).`);
|
|
1399
|
+
}
|
|
1400
|
+
function count(n, one, many) {
|
|
1401
|
+
return `${n} ${n === 1 ? one : many}`;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// src/rate-gate.ts
|
|
1405
|
+
var GATES = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/rate-gates/2");
|
|
1406
|
+
var GATE_MAX_MS = 6e4;
|
|
1407
|
+
function monotonicNow() {
|
|
1408
|
+
const perf = globalThis.performance;
|
|
1409
|
+
return typeof perf?.now === "function" ? perf.now() : Date.now();
|
|
1410
|
+
}
|
|
1411
|
+
function gates() {
|
|
1412
|
+
const scope = globalThis;
|
|
1413
|
+
let map = scope[GATES];
|
|
1414
|
+
if (!map) {
|
|
1415
|
+
map = /* @__PURE__ */ new Map();
|
|
1416
|
+
scope[GATES] = map;
|
|
1417
|
+
}
|
|
1418
|
+
return map;
|
|
1419
|
+
}
|
|
1420
|
+
function gateRemaining(identity, now = monotonicNow()) {
|
|
1421
|
+
const map = gates();
|
|
1422
|
+
const opensAt = map.get(identity) ?? 0;
|
|
1423
|
+
if (opensAt > now) return opensAt - now;
|
|
1424
|
+
map.delete(identity);
|
|
1425
|
+
return 0;
|
|
1426
|
+
}
|
|
1427
|
+
function shutGate(identity, ms, now = monotonicNow()) {
|
|
1428
|
+
const map = gates();
|
|
1429
|
+
const opensAt = now + Math.min(Math.max(0, ms), GATE_MAX_MS);
|
|
1430
|
+
if (opensAt > (map.get(identity) ?? 0)) map.set(identity, opensAt);
|
|
1431
|
+
}
|
|
1432
|
+
function spreadOf(ms, random = Math.random) {
|
|
1433
|
+
return random() * Math.max(1e3, ms / 5);
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
// src/client.ts
|
|
210
1437
|
var DEFAULT_TIMEOUT = 1e4;
|
|
1438
|
+
var MIN_WRITE_TIMEOUT = 3e4;
|
|
211
1439
|
var MIN_UPLOAD_TIMEOUT = 6e4;
|
|
212
1440
|
var VERSION_TIMEOUT = 3e3;
|
|
213
1441
|
var DEFAULT_WAIT_FOR_FRESH = 1e3;
|
|
@@ -216,8 +1444,10 @@ var STORED_LIMIT = 5e3;
|
|
|
216
1444
|
var LOCALES_RETRY_MS = 6e4;
|
|
217
1445
|
var DEFAULT_GATEWAY_RETRY = 200;
|
|
218
1446
|
var MAX_GATEWAY_RETRY = 6e4;
|
|
219
|
-
var
|
|
220
|
-
|
|
1447
|
+
var DEFAULT_RATE_LIMIT_WAIT = 1e4;
|
|
1448
|
+
var MAX_RATE_LIMIT_RETRIES = 2;
|
|
1449
|
+
var NordhavnClient = class {
|
|
1450
|
+
constructor(options = {}) {
|
|
221
1451
|
/**
|
|
222
1452
|
* The refresh under way per cache key, so concurrent reads of one key share
|
|
223
1453
|
* one request, with the ticket it left on (see `state.ticket`).
|
|
@@ -230,8 +1460,7 @@ var HavenClient = class {
|
|
|
230
1460
|
this.storedBy = /* @__PURE__ */ new Map();
|
|
231
1461
|
/**
|
|
232
1462
|
* Everything that changes while the client runs and is not a collection of
|
|
233
|
-
* its own.
|
|
234
|
-
* fields through its prototype - changes the same values and never a copy.
|
|
1463
|
+
* its own.
|
|
235
1464
|
*/
|
|
236
1465
|
this.state = {
|
|
237
1466
|
/**
|
|
@@ -252,26 +1481,32 @@ var HavenClient = class {
|
|
|
252
1481
|
*/
|
|
253
1482
|
locales: void 0,
|
|
254
1483
|
/** Epoch ms before which the locales are not asked for again, after that failed. */
|
|
255
|
-
localesRetryAt: 0
|
|
1484
|
+
localesRetryAt: 0,
|
|
1485
|
+
/** Whether the first read still has to say which project this is (`announceProject`). */
|
|
1486
|
+
announce: false
|
|
256
1487
|
};
|
|
257
|
-
|
|
258
|
-
this.apiKey =
|
|
259
|
-
this.baseUrl =
|
|
1488
|
+
const { apiKey, baseUrl } = connectionOf(options);
|
|
1489
|
+
this.apiKey = apiKey;
|
|
1490
|
+
this.baseUrl = baseUrl;
|
|
260
1491
|
const resolvedFetch = options.fetch ?? globalThis.fetch;
|
|
261
1492
|
if (!resolvedFetch) {
|
|
262
|
-
throw new Error("
|
|
1493
|
+
throw new Error("NordhavnClient: no `fetch` available; pass one via options.fetch");
|
|
263
1494
|
}
|
|
264
1495
|
this.fetchImpl = resolvedFetch.bind(globalThis);
|
|
265
1496
|
this.headers = options.headers ?? {};
|
|
266
1497
|
this.locale = options.locale || void 0;
|
|
267
|
-
this.readDefault = options.preview !== true;
|
|
268
1498
|
this.timeout = normalizeTimeout(options.timeout);
|
|
1499
|
+
this.writeTimeout = normalizeWriteTimeout(this.timeout, options.writeTimeout);
|
|
269
1500
|
this.onError = options.onError;
|
|
1501
|
+
this.log = loggerOf(options.logger);
|
|
1502
|
+
this.identity = identityOf(this.baseUrl, sentHeaders(this.apiKey, this.headers));
|
|
270
1503
|
const cacheOpt = options.cache;
|
|
271
1504
|
const cacheOptions = cacheOpt === false ? { enabled: false } : cacheOpt === true || cacheOpt === void 0 ? {} : cacheOpt;
|
|
272
|
-
this.cache = new ContentCache(cacheOptions);
|
|
1505
|
+
this.cache = new ContentCache({ ...cacheOptions, store: cacheStore(cacheOptions, this.identity, this.log) });
|
|
273
1506
|
this.waitForFresh = normalizeWait(cacheOptions.waitForFresh);
|
|
274
1507
|
this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry);
|
|
1508
|
+
this.rateLimitWait = normalizeRateLimitWait(options.rateLimitWait);
|
|
1509
|
+
this.state.announce = wantAnnounce({ log: this.log, customFetch: options.fetch !== void 0 });
|
|
275
1510
|
const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false ? 0 : cacheOptions.revalidate ?? 6e4;
|
|
276
1511
|
const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT);
|
|
277
1512
|
this.versionTracker = new VersionTracker(
|
|
@@ -290,39 +1525,23 @@ var HavenClient = class {
|
|
|
290
1525
|
revalidate,
|
|
291
1526
|
isMissingRoute
|
|
292
1527
|
);
|
|
1528
|
+
const live = wantLive({
|
|
1529
|
+
option: options.live,
|
|
1530
|
+
revalidating: revalidate > 0,
|
|
1531
|
+
customFetch: options.fetch !== void 0,
|
|
1532
|
+
waitsForStudio: this.waitForFresh === Infinity
|
|
1533
|
+
});
|
|
1534
|
+
this.live = live ? new LiveLink(this.baseUrl, this.apiKey, this.headers, this) : void 0;
|
|
293
1535
|
}
|
|
294
|
-
// ── Preview scoping ─────────────────────────────────────────────────────────
|
|
295
1536
|
/**
|
|
296
|
-
*
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
* Accepts whatever your framework hands you: a `Request`, a URL string or
|
|
302
|
-
* `URL`, `URLSearchParams`, or a plain searchParams object.
|
|
303
|
-
*
|
|
304
|
-
* ```ts
|
|
305
|
-
* // Next.js app router
|
|
306
|
-
* export default async function Page({ searchParams }) {
|
|
307
|
-
* const posts = await studio.forRequest(await searchParams).dataset('blog', 'posts').list()
|
|
308
|
-
* }
|
|
309
|
-
* ```
|
|
310
|
-
*
|
|
311
|
-
* Note this only bypasses the SDK's own cache. If the page itself sits behind
|
|
312
|
-
* a CDN or framework data cache, that layer needs the same treatment (e.g.
|
|
313
|
-
* `cache: 'no-store'` when the preview marker is present) or the editor keeps
|
|
314
|
-
* seeing a stale page no matter what this client returns.
|
|
1537
|
+
* Lets go of the live connection: the last client of a server and key to
|
|
1538
|
+
* close it closes the connection. The client keeps working, on the stamp
|
|
1539
|
+
* check alone. Not needed to let a process end (the connection never keeps
|
|
1540
|
+
* one alive); for a test, or code that builds clients and drops them.
|
|
315
1541
|
*/
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
const view = Object.create(this);
|
|
320
|
-
view.readDefault = false;
|
|
321
|
-
return view;
|
|
322
|
-
}
|
|
323
|
-
/** Whether this client bypasses the cache (i.e. came from a preview request). */
|
|
324
|
-
get isPreview() {
|
|
325
|
-
return !this.readDefault;
|
|
1542
|
+
close() {
|
|
1543
|
+
this.live?.close();
|
|
1544
|
+
this.live = void 0;
|
|
326
1545
|
}
|
|
327
1546
|
// ── Introspection ─────────────────────────────────────────────────────────
|
|
328
1547
|
/** The full content shape this key can reach: nodes, datasets, field schemas. */
|
|
@@ -369,7 +1588,7 @@ var HavenClient = class {
|
|
|
369
1588
|
async readLocale(opts) {
|
|
370
1589
|
const requested = this.resolveLocale(opts)?.trim() || void 0;
|
|
371
1590
|
if (requested === void 0 || !this.cache.enabled) return requested;
|
|
372
|
-
const bypass =
|
|
1591
|
+
const bypass = opts?.cache === false;
|
|
373
1592
|
const configured = await this.configuredLocales(!bypass);
|
|
374
1593
|
return configured ? matchLocale(requested, configured) : requested;
|
|
375
1594
|
}
|
|
@@ -476,7 +1695,7 @@ var HavenClient = class {
|
|
|
476
1695
|
* The field decides what it takes: its `mimes` and `max_size` rules, within
|
|
477
1696
|
* what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
|
|
478
1697
|
* studio reads the type from the content, so a renamed file is refused. Only
|
|
479
|
-
* top-level fields. A file of the wrong type or size throws `
|
|
1698
|
+
* top-level fields. A file of the wrong type or size throws `NordhavnError` 400
|
|
480
1699
|
* with a message fit to show; other refusals (400, 403, 404) are setup
|
|
481
1700
|
* errors. More than 10 uploads a minute per key throws 429. From a Node
|
|
482
1701
|
* `Buffer`, send `new Blob([buffer])` with a `filename`.
|
|
@@ -489,7 +1708,7 @@ var HavenClient = class {
|
|
|
489
1708
|
async uploadFile(nodeSlug, datasetSlug, fieldSlug, file, opts) {
|
|
490
1709
|
const filename = opts?.filename ?? file.name;
|
|
491
1710
|
if (!filename) {
|
|
492
|
-
throw new Error("
|
|
1711
|
+
throw new Error("NordhavnClient.uploadFile: the file has no name; pass `filename` (with its extension)");
|
|
493
1712
|
}
|
|
494
1713
|
const form = new FormData();
|
|
495
1714
|
form.set("file", file, filename);
|
|
@@ -497,7 +1716,7 @@ var HavenClient = class {
|
|
|
497
1716
|
form.set("datasetSlug", datasetSlug);
|
|
498
1717
|
form.set("fieldSlug", fieldSlug);
|
|
499
1718
|
const url = `${this.baseUrl}/api/content/files`;
|
|
500
|
-
const timeout = uploadTimeout(this.
|
|
1719
|
+
const timeout = uploadTimeout(this.writeTimeout, opts?.timeout);
|
|
501
1720
|
return withTimeout(url, timeout, async (signal) => {
|
|
502
1721
|
const res = await this.fetchImpl(url, {
|
|
503
1722
|
method: "POST",
|
|
@@ -524,7 +1743,7 @@ var HavenClient = class {
|
|
|
524
1743
|
async write(method, path, body, nodeSlug, datasetSlug) {
|
|
525
1744
|
let res;
|
|
526
1745
|
try {
|
|
527
|
-
res = await this.request(method, path, body);
|
|
1746
|
+
res = await this.request(method, path, body, this.writeTimeout);
|
|
528
1747
|
} catch (err) {
|
|
529
1748
|
if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, "recheck");
|
|
530
1749
|
throw err;
|
|
@@ -691,13 +1910,22 @@ var HavenClient = class {
|
|
|
691
1910
|
* 5. One request per key at a time (`refresh`).
|
|
692
1911
|
*/
|
|
693
1912
|
async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
|
|
694
|
-
const useCache = opts?.cache
|
|
1913
|
+
const useCache = opts?.cache !== false;
|
|
1914
|
+
this.announceOnce();
|
|
695
1915
|
if (!useCache) {
|
|
696
|
-
|
|
697
|
-
|
|
1916
|
+
let version2 = this.versionTracker.current() ?? void 0;
|
|
1917
|
+
let ticket = ++this.state.ticket;
|
|
698
1918
|
let res;
|
|
699
1919
|
try {
|
|
700
|
-
|
|
1920
|
+
const got = await this.askRetrying(path, void 0, isExpected, false, {
|
|
1921
|
+
allowed: () => true,
|
|
1922
|
+
resume: () => {
|
|
1923
|
+
ticket = ++this.state.ticket;
|
|
1924
|
+
version2 = this.versionTracker.current() ?? void 0;
|
|
1925
|
+
return void 0;
|
|
1926
|
+
}
|
|
1927
|
+
});
|
|
1928
|
+
res = got.answer;
|
|
701
1929
|
} catch (err) {
|
|
702
1930
|
if (isDefinitive(err)) this.gone(cacheKey, ticket);
|
|
703
1931
|
throw err;
|
|
@@ -710,7 +1938,7 @@ var HavenClient = class {
|
|
|
710
1938
|
}
|
|
711
1939
|
const started = Date.now();
|
|
712
1940
|
const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity;
|
|
713
|
-
await within(this.
|
|
1941
|
+
await within(this.checkVersion(started), budget);
|
|
714
1942
|
const version = this.versionTracker.current() ?? void 0;
|
|
715
1943
|
const entry = this.cache.peek(cacheKey, Date.now());
|
|
716
1944
|
if (entry) {
|
|
@@ -727,6 +1955,16 @@ var HavenClient = class {
|
|
|
727
1955
|
const outcome = await within(refresh, budget - (Date.now() - started));
|
|
728
1956
|
return outcome.settled ? outcome.value : last.value;
|
|
729
1957
|
}
|
|
1958
|
+
/** On the first read, in development: which project this key reads (`announceProject`). */
|
|
1959
|
+
announceOnce() {
|
|
1960
|
+
if (!this.state.announce) return;
|
|
1961
|
+
this.state.announce = false;
|
|
1962
|
+
announceProject(this.baseUrl, sentHeaders(this.apiKey, this.headers), this.log);
|
|
1963
|
+
}
|
|
1964
|
+
/** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */
|
|
1965
|
+
checkVersion(now) {
|
|
1966
|
+
return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now);
|
|
1967
|
+
}
|
|
730
1968
|
/**
|
|
731
1969
|
* Fetches `cacheKey` from the studio and settles the cache with the answer.
|
|
732
1970
|
* One per key at a time: reads that arrive while it runs get the same promise,
|
|
@@ -746,23 +1984,22 @@ var HavenClient = class {
|
|
|
746
1984
|
};
|
|
747
1985
|
const job = (async () => {
|
|
748
1986
|
try {
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
}
|
|
1987
|
+
const got = await this.askRetrying(path, last?.etag, isExpected, retry, {
|
|
1988
|
+
allowed: () => !last && !this.cache.stale(cacheKey),
|
|
1989
|
+
resume: () => {
|
|
1990
|
+
const meanwhile = this.cache.stale(cacheKey);
|
|
1991
|
+
if (meanwhile) return { value: meanwhile.value };
|
|
1992
|
+
const slot = this.inflight.get(cacheKey);
|
|
1993
|
+
if (slot && !registered()) return { value: slot.job };
|
|
1994
|
+
ticket = ++this.state.ticket;
|
|
1995
|
+
if (slot) slot.ticket = ticket;
|
|
1996
|
+
else register();
|
|
1997
|
+
version = this.versionTracker.current() ?? void 0;
|
|
1998
|
+
return void 0;
|
|
1999
|
+
}
|
|
2000
|
+
});
|
|
2001
|
+
if ("value" in got) return got.value;
|
|
2002
|
+
const res = got.answer;
|
|
766
2003
|
if (res.notModified && last) {
|
|
767
2004
|
if (this.storable(cacheKey, ticket)) {
|
|
768
2005
|
this.cache.confirm(cacheKey, version, Date.now());
|
|
@@ -791,6 +2028,102 @@ var HavenClient = class {
|
|
|
791
2028
|
this.inflight.set(cacheKey, { job, ticket });
|
|
792
2029
|
return job;
|
|
793
2030
|
}
|
|
2031
|
+
/**
|
|
2032
|
+
* Sends a read's request, and sends it again where the failure says that
|
|
2033
|
+
* may help (`retryPause`) and `hooks.allowed()` says the read has nothing to
|
|
2034
|
+
* serve instead; such a read is also held back while its key is rate
|
|
2035
|
+
* limited (`holdBack`). Every other failure is thrown as it is.
|
|
2036
|
+
*
|
|
2037
|
+
* The one retry loop of the read path, for the cached read (`refresh`) and
|
|
2038
|
+
* the bypass alike, so the waits are the same for both. What differs sits in
|
|
2039
|
+
* the hooks: `resume` runs after each wait, just before the next try, and
|
|
2040
|
+
* either ends the read without one (`{ value }`: what another request stored
|
|
2041
|
+
* meanwhile, a newer refresh to join) or takes the ticket and stamp the
|
|
2042
|
+
* next try leaves with and returns `undefined`.
|
|
2043
|
+
*
|
|
2044
|
+
* A next try only ever happens with nothing cached, so it never has an etag
|
|
2045
|
+
* to send: `etag` is the first try's.
|
|
2046
|
+
*/
|
|
2047
|
+
async askRetrying(path, etag, isExpected, gateway, hooks) {
|
|
2048
|
+
const read = { started: Date.now(), gateway, rateLimited: 0, heldUntil: 0, spread: false };
|
|
2049
|
+
let ifNoneMatch = etag;
|
|
2050
|
+
for (; ; ) {
|
|
2051
|
+
if (await this.holdBack(read, hooks.allowed())) {
|
|
2052
|
+
const early = hooks.resume();
|
|
2053
|
+
if (early) return early;
|
|
2054
|
+
ifNoneMatch = void 0;
|
|
2055
|
+
continue;
|
|
2056
|
+
}
|
|
2057
|
+
try {
|
|
2058
|
+
return { answer: await this.conditionalGet(path, ifNoneMatch, isExpected) };
|
|
2059
|
+
} catch (err) {
|
|
2060
|
+
const asked = rateLimitPause(err);
|
|
2061
|
+
if (asked !== void 0 && err instanceof NordhavnError && isStudioAnswer(err)) shutGate(this.identity, asked);
|
|
2062
|
+
const pause = hooks.allowed() ? this.retryPause(err, read) : void 0;
|
|
2063
|
+
if (pause === void 0) throw err;
|
|
2064
|
+
ifNoneMatch = void 0;
|
|
2065
|
+
if (pause === "hold") continue;
|
|
2066
|
+
await sleep(pause);
|
|
2067
|
+
const early = hooks.resume();
|
|
2068
|
+
if (early) return early;
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* Whether, and how, a failed read with nothing cached is sent again;
|
|
2074
|
+
* counts what it allows in `read`.
|
|
2075
|
+
*
|
|
2076
|
+
* - A `502` or `503` is often one bad moment (a proxy switching to a new
|
|
2077
|
+
* studio container): once, `gatewayRetry` later plus up to as much at
|
|
2078
|
+
* random. Not when it carried `Retry-After`: that one asked to wait.
|
|
2079
|
+
* - A `429` with `Retry-After`: `'hold'`, so `holdBack` waits as asked, at
|
|
2080
|
+
* most `MAX_RATE_LIMIT_RETRIES` times, and only when that wait ends
|
|
2081
|
+
* within `rateLimitWait` of the read's start. Without `Retry-After`
|
|
2082
|
+
* nothing says when it would help: thrown.
|
|
2083
|
+
*/
|
|
2084
|
+
retryPause(err, read) {
|
|
2085
|
+
if (read.gateway && this.gatewayRetry !== void 0 && isGatewayHiccup(err)) {
|
|
2086
|
+
read.gateway = false;
|
|
2087
|
+
return this.gatewayRetry + Math.random() * this.gatewayRetry;
|
|
2088
|
+
}
|
|
2089
|
+
const asked = rateLimitPause(err);
|
|
2090
|
+
if (asked === void 0 || this.rateLimitWait === void 0 || read.rateLimited >= MAX_RATE_LIMIT_RETRIES) return void 0;
|
|
2091
|
+
const now = Date.now();
|
|
2092
|
+
if (now + asked - read.started > this.rateLimitWait) return void 0;
|
|
2093
|
+
read.rateLimited++;
|
|
2094
|
+
read.heldUntil = now + asked;
|
|
2095
|
+
read.spread = true;
|
|
2096
|
+
return "hold";
|
|
2097
|
+
}
|
|
2098
|
+
/**
|
|
2099
|
+
* Keeps a read from going out while its key is rate limited: until its own
|
|
2100
|
+
* `429` said, or the studio's own `429` to any read of this server and key
|
|
2101
|
+
* in the process (`gateRemaining`, at most a minute). Resolves `true` after
|
|
2102
|
+
* waiting, `false` to go now.
|
|
2103
|
+
*
|
|
2104
|
+
* A read with nothing cached (`uncached`) waits for the gate, plus a random
|
|
2105
|
+
* spread (`spreadOf`, also after a `Retry-After: 0`), when that wait ends
|
|
2106
|
+
* within `rateLimitWait` of the read's start. Otherwise (a read with a value
|
|
2107
|
+
* cached, a wait that does not fit, `rateLimitWait: false`) the request is
|
|
2108
|
+
* not sent: the studio already said this key must wait, so it would be
|
|
2109
|
+
* refused, and count against the key's limit as well. It fails as that
|
|
2110
|
+
* refusal would (`heldBackError`), so a cached value is served in its place
|
|
2111
|
+
* and a read with nothing cached throws, without a request.
|
|
2112
|
+
*/
|
|
2113
|
+
async holdBack(read, uncached) {
|
|
2114
|
+
const now = Date.now();
|
|
2115
|
+
const gateLeft = gateRemaining(this.identity);
|
|
2116
|
+
const gate = gateLeft > 0 ? now + gateLeft : 0;
|
|
2117
|
+
const until = uncached ? Math.max(gate, read.heldUntil) : gate;
|
|
2118
|
+
if (until <= now && !read.spread) return false;
|
|
2119
|
+
if (!uncached || this.rateLimitWait === void 0 || until - read.started > this.rateLimitWait) {
|
|
2120
|
+
throw heldBackError(until - now);
|
|
2121
|
+
}
|
|
2122
|
+
read.spread = false;
|
|
2123
|
+
const wait = Math.max(0, until - now);
|
|
2124
|
+
await sleep(wait + spreadOf(wait));
|
|
2125
|
+
return true;
|
|
2126
|
+
}
|
|
794
2127
|
/**
|
|
795
2128
|
* Hands an absorbed failure to `onError`, or without one warns once per
|
|
796
2129
|
* outage. Never throws and never leaves a rejection behind: a broken hook
|
|
@@ -809,7 +2142,7 @@ var HavenClient = class {
|
|
|
809
2142
|
} else if (first) {
|
|
810
2143
|
const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
|
|
811
2144
|
const what = failure.during === "read" ? `could not refresh "${failure.key}"` : "stamp check failed";
|
|
812
|
-
|
|
2145
|
+
logLine(this.log, "warn", `${what} (${reason}); cached content keeps being served.`);
|
|
813
2146
|
}
|
|
814
2147
|
} catch {
|
|
815
2148
|
}
|
|
@@ -871,7 +2204,7 @@ var HavenClient = class {
|
|
|
871
2204
|
return await res.json();
|
|
872
2205
|
});
|
|
873
2206
|
}
|
|
874
|
-
/** Parse a non-2xx response into a `
|
|
2207
|
+
/** Parse a non-2xx response into a `NordhavnError`, preferring its message. */
|
|
875
2208
|
async toError(res) {
|
|
876
2209
|
let message = res.statusText || `Request failed with status ${res.status}`;
|
|
877
2210
|
let parsed;
|
|
@@ -882,8 +2215,8 @@ var HavenClient = class {
|
|
|
882
2215
|
else if (typeof m?.statusMessage === "string") message = m.statusMessage;
|
|
883
2216
|
} catch {
|
|
884
2217
|
}
|
|
885
|
-
const err = new
|
|
886
|
-
if (res.headers.has("retry-after")) askedToWait.
|
|
2218
|
+
const err = new NordhavnError(message, res.status, parsed);
|
|
2219
|
+
if (res.headers.has("retry-after")) askedToWait.set(err, parseRetryAfter(res.headers.get("retry-after"), Date.now()));
|
|
887
2220
|
return err;
|
|
888
2221
|
}
|
|
889
2222
|
};
|
|
@@ -905,7 +2238,7 @@ var DatasetHandle = class {
|
|
|
905
2238
|
update(recordUid, data) {
|
|
906
2239
|
return this.client.updateRecord(this.nodeSlug, this.datasetSlug, recordUid, data);
|
|
907
2240
|
}
|
|
908
|
-
/** Upload a file for one of this dataset's file fields; see `
|
|
2241
|
+
/** Upload a file for one of this dataset's file fields; see `NordhavnClient.uploadFile`. */
|
|
909
2242
|
uploadFile(fieldSlug, file, opts) {
|
|
910
2243
|
return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts);
|
|
911
2244
|
}
|
|
@@ -914,19 +2247,6 @@ var DatasetHandle = class {
|
|
|
914
2247
|
this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug });
|
|
915
2248
|
}
|
|
916
2249
|
};
|
|
917
|
-
function isPreviewRequest(input) {
|
|
918
|
-
if (!input) return false;
|
|
919
|
-
if (typeof input === "string") {
|
|
920
|
-
const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
|
|
921
|
-
return new URLSearchParams(query).has(PREVIEW_PARAM);
|
|
922
|
-
}
|
|
923
|
-
if (input instanceof URLSearchParams) return input.has(PREVIEW_PARAM);
|
|
924
|
-
if (input instanceof URL) return input.searchParams.has(PREVIEW_PARAM);
|
|
925
|
-
if (typeof input.url === "string") {
|
|
926
|
-
return isPreviewRequest(input.url);
|
|
927
|
-
}
|
|
928
|
-
return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM);
|
|
929
|
-
}
|
|
930
2250
|
async function withTimeout(url, ms, run) {
|
|
931
2251
|
if (ms <= 0) return run(void 0);
|
|
932
2252
|
const controller = new AbortController();
|
|
@@ -949,9 +2269,13 @@ function normalizeTimeout(value) {
|
|
|
949
2269
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
|
|
950
2270
|
return value > MAX_TIMER ? 0 : value;
|
|
951
2271
|
}
|
|
952
|
-
function
|
|
2272
|
+
function normalizeWriteTimeout(timeout, value) {
|
|
2273
|
+
if (typeof value === "number" && !Number.isNaN(value) && value >= 0) return normalizeTimeout(value);
|
|
2274
|
+
return timeout === 0 ? 0 : Math.max(timeout, MIN_WRITE_TIMEOUT);
|
|
2275
|
+
}
|
|
2276
|
+
function uploadTimeout(writeTimeout, perCall) {
|
|
953
2277
|
if (typeof perCall === "number" && perCall >= 0) return normalizeTimeout(perCall);
|
|
954
|
-
return
|
|
2278
|
+
return writeTimeout === 0 ? 0 : Math.max(writeTimeout, MIN_UPLOAD_TIMEOUT);
|
|
955
2279
|
}
|
|
956
2280
|
function withoutContentType(headers) {
|
|
957
2281
|
return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-type"));
|
|
@@ -961,6 +2285,11 @@ function normalizeGatewayRetry(value) {
|
|
|
961
2285
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
|
|
962
2286
|
return Math.min(value, MAX_GATEWAY_RETRY);
|
|
963
2287
|
}
|
|
2288
|
+
function normalizeRateLimitWait(value) {
|
|
2289
|
+
if (value === false) return void 0;
|
|
2290
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_RATE_LIMIT_WAIT;
|
|
2291
|
+
return Math.min(value, MAX_TIMER);
|
|
2292
|
+
}
|
|
964
2293
|
function normalizeWait(value) {
|
|
965
2294
|
if (value === false) return Infinity;
|
|
966
2295
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH;
|
|
@@ -1000,26 +2329,34 @@ function unexpectedBody(url) {
|
|
|
1000
2329
|
function isTransientStatus(status) {
|
|
1001
2330
|
return status >= 500 || status === 408 || status === 429;
|
|
1002
2331
|
}
|
|
1003
|
-
var askedToWait = /* @__PURE__ */ new
|
|
2332
|
+
var askedToWait = /* @__PURE__ */ new WeakMap();
|
|
2333
|
+
function heldBackError(waitMs) {
|
|
2334
|
+
const seconds = Math.max(1, Math.ceil(waitMs / 1e3));
|
|
2335
|
+
const message = `Too many requests: this key is rate limited for ${seconds} s more, so the request was not sent`;
|
|
2336
|
+
const err = new NordhavnError(message, 429, { statusCode: 429, statusMessage: "Too Many Requests", message });
|
|
2337
|
+
askedToWait.set(err, Math.max(0, waitMs));
|
|
2338
|
+
return err;
|
|
2339
|
+
}
|
|
2340
|
+
function rateLimitPause(err) {
|
|
2341
|
+
return err instanceof NordhavnError && err.status === 429 ? askedToWait.get(err) : void 0;
|
|
2342
|
+
}
|
|
1004
2343
|
function isGatewayHiccup(err) {
|
|
1005
|
-
return err instanceof
|
|
2344
|
+
return err instanceof NordhavnError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
|
|
1006
2345
|
}
|
|
1007
2346
|
function sleep(ms) {
|
|
1008
2347
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1009
2348
|
}
|
|
1010
2349
|
function isDefinitive(err) {
|
|
1011
|
-
return err instanceof
|
|
2350
|
+
return err instanceof NordhavnError && !isTransientStatus(err.status) && isStudioAnswer(err);
|
|
1012
2351
|
}
|
|
1013
2352
|
function isStudioAnswer(err) {
|
|
1014
|
-
|
|
1015
|
-
if (typeof body !== "object" || body === null) return false;
|
|
1016
|
-
return body.statusCode === err.status || body.status === err.status;
|
|
2353
|
+
return isStudioBody(err.status, err.body);
|
|
1017
2354
|
}
|
|
1018
2355
|
function isMissingRoute(err) {
|
|
1019
|
-
return err instanceof
|
|
2356
|
+
return err instanceof NordhavnError && err.status === 404 && isStudioAnswer(err);
|
|
1020
2357
|
}
|
|
1021
2358
|
function writeMayHaveLanded(err) {
|
|
1022
|
-
return !(err instanceof
|
|
2359
|
+
return !(err instanceof NordhavnError && err.status >= 400 && err.status < 500);
|
|
1023
2360
|
}
|
|
1024
2361
|
function datasetPath(nodeSlug, datasetSlug) {
|
|
1025
2362
|
return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`;
|
|
@@ -1276,8 +2613,10 @@ function parseChartFence(source) {
|
|
|
1276
2613
|
|
|
1277
2614
|
// src/index.ts
|
|
1278
2615
|
function createClient(options) {
|
|
1279
|
-
return new
|
|
2616
|
+
return new NordhavnClient(options);
|
|
1280
2617
|
}
|
|
2618
|
+
var HavenClient = NordhavnClient;
|
|
2619
|
+
var HavenError = NordhavnError;
|
|
1281
2620
|
|
|
1282
2621
|
exports.AGGREGATIONS = AGGREGATIONS;
|
|
1283
2622
|
exports.BUCKET_MODES = BUCKET_MODES;
|
|
@@ -1293,18 +2632,16 @@ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
|
|
|
1293
2632
|
exports.DatasetHandle = DatasetHandle;
|
|
1294
2633
|
exports.HavenClient = HavenClient;
|
|
1295
2634
|
exports.HavenError = HavenError;
|
|
1296
|
-
exports.JustmadeClient = HavenClient;
|
|
1297
|
-
exports.JustmadeError = HavenError;
|
|
1298
2635
|
exports.MemoryCacheStore = MemoryCacheStore;
|
|
2636
|
+
exports.NordhavnClient = NordhavnClient;
|
|
2637
|
+
exports.NordhavnError = NordhavnError;
|
|
1299
2638
|
exports.PALETTE_KEYS = PALETTE_KEYS;
|
|
1300
|
-
exports.PREVIEW_PARAM = PREVIEW_PARAM;
|
|
1301
2639
|
exports.chartFenceHeight = chartFenceHeight;
|
|
1302
2640
|
exports.chartTypeInfo = chartTypeInfo;
|
|
1303
2641
|
exports.createClient = createClient;
|
|
1304
2642
|
exports.isBarChart = isBarChart;
|
|
1305
2643
|
exports.isChartFence = isChartFence;
|
|
1306
2644
|
exports.isPartChart = isPartChart;
|
|
1307
|
-
exports.isPreviewRequest = isPreviewRequest;
|
|
1308
2645
|
exports.parseChartFence = parseChartFence;
|
|
1309
2646
|
//# sourceMappingURL=index.cjs.map
|
|
1310
2647
|
//# sourceMappingURL=index.cjs.map
|