@nordhavnhq/beacon 0.7.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 -2
- package/dist/{cache-1gURpP7O.d.cts → cache-DIs1jN1m.d.cts} +6 -1
- package/dist/{cache-1gURpP7O.d.ts → cache-DIs1jN1m.d.ts} +6 -1
- 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 +832 -136
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +188 -30
- package/dist/index.d.ts +188 -30
- package/dist/index.js +475 -138
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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,14 +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);
|
|
140
|
-
Object.setPrototypeOf(this,
|
|
313
|
+
Object.setPrototypeOf(this, _NordhavnError.prototype);
|
|
141
314
|
}
|
|
142
315
|
get isUnauthorized() {
|
|
143
316
|
return this.status === 401;
|
|
@@ -211,29 +384,28 @@ var LIVE = {
|
|
|
211
384
|
function planReconnect(outcome, ctx) {
|
|
212
385
|
const attempts = ctx.stable ? 0 : ctx.attempts;
|
|
213
386
|
if (outcome.kind === "closed" && ctx.stable) {
|
|
214
|
-
return {
|
|
387
|
+
return { delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 };
|
|
215
388
|
}
|
|
216
389
|
if (outcome.kind === "refused") return planRefused(outcome, { ...ctx, attempts });
|
|
217
390
|
return backoff(attempts, ctx.random);
|
|
218
391
|
}
|
|
219
392
|
function planRefused(outcome, ctx) {
|
|
220
393
|
const { status, studio } = outcome;
|
|
221
|
-
if (studio && (status === 401 || status === 403)) return { stop: true };
|
|
222
394
|
const asked = parseRetryAfter(outcome.retryAfter, ctx.now);
|
|
223
395
|
if (status === 429 || status === 503 && asked !== void 0) {
|
|
224
396
|
const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs);
|
|
225
|
-
return {
|
|
397
|
+
return { delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts };
|
|
226
398
|
}
|
|
227
399
|
const studioRefusal = studio && status >= 400 && status < 500 && status !== 408;
|
|
228
400
|
if (studioRefusal || status >= 300 && status < 400) {
|
|
229
|
-
return {
|
|
401
|
+
return { delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts };
|
|
230
402
|
}
|
|
231
403
|
return backoff(ctx.attempts, ctx.random);
|
|
232
404
|
}
|
|
233
405
|
function backoff(attempts, random) {
|
|
234
406
|
const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16);
|
|
235
407
|
const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window);
|
|
236
|
-
return {
|
|
408
|
+
return { delay, attempts: attempts + 1 };
|
|
237
409
|
}
|
|
238
410
|
function longJitter(wait, random) {
|
|
239
411
|
return random() * Math.min(LIVE.longJitterMs, wait / 5);
|
|
@@ -244,10 +416,12 @@ function between(min, max, random) {
|
|
|
244
416
|
function clamp(value, min, max) {
|
|
245
417
|
return Math.min(max, Math.max(min, value));
|
|
246
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$/;
|
|
247
420
|
function parseRetryAfter(value, now) {
|
|
248
421
|
const text = value?.trim();
|
|
249
422
|
if (!text) return void 0;
|
|
250
|
-
if (
|
|
423
|
+
if (/^\d+$/.test(text)) return Number(text) * 1e3;
|
|
424
|
+
if (!IMF_FIXDATE.test(text)) return void 0;
|
|
251
425
|
const at = Date.parse(text);
|
|
252
426
|
return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
|
|
253
427
|
}
|
|
@@ -443,35 +617,13 @@ var collected = typeof FinalizationRegistry === "function" ? new FinalizationReg
|
|
|
443
617
|
} catch {
|
|
444
618
|
}
|
|
445
619
|
}) : 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
620
|
function wantLive(settings) {
|
|
453
621
|
try {
|
|
454
|
-
return chooseLive({ ...settings, runtime:
|
|
622
|
+
return chooseLive({ ...settings, runtime: nodeRuntime(), env: environment() });
|
|
455
623
|
} catch {
|
|
456
624
|
return false;
|
|
457
625
|
}
|
|
458
626
|
}
|
|
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
627
|
var LiveLink = class {
|
|
476
628
|
constructor(baseUrl, apiKey, headers, owner) {
|
|
477
629
|
this.baseUrl = baseUrl;
|
|
@@ -525,14 +677,13 @@ var LiveLink = class {
|
|
|
525
677
|
this.closed = true;
|
|
526
678
|
return void 0;
|
|
527
679
|
}
|
|
528
|
-
const
|
|
680
|
+
const registry2 = hubs();
|
|
529
681
|
const headers = liveHeaders(this.apiKey, this.headers);
|
|
530
|
-
const id =
|
|
531
|
-
|
|
532
|
-
let hub = registry.get(id);
|
|
682
|
+
const id = identityOf(this.baseUrl, headers);
|
|
683
|
+
let hub = registry2.get(id);
|
|
533
684
|
if (!hub) {
|
|
534
685
|
hub = new LiveHub(id, url, headers);
|
|
535
|
-
|
|
686
|
+
registry2.set(id, hub);
|
|
536
687
|
}
|
|
537
688
|
this.silences = hub.attach(this.token);
|
|
538
689
|
if (this.owner) collected?.register(this.owner, { hub, token: this.token }, this.token);
|
|
@@ -550,8 +701,7 @@ function eventsUrl(baseUrl) {
|
|
|
550
701
|
}
|
|
551
702
|
}
|
|
552
703
|
function liveHeaders(apiKey, extra) {
|
|
553
|
-
const headers =
|
|
554
|
-
for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
|
|
704
|
+
const headers = sentHeaders(apiKey, extra);
|
|
555
705
|
headers.accept = "text/event-stream";
|
|
556
706
|
headers["cache-control"] = "no-cache";
|
|
557
707
|
headers["accept-encoding"] = "identity";
|
|
@@ -701,10 +851,6 @@ var LiveHub = class {
|
|
|
701
851
|
if (!outcome || this.state === "stopped") return;
|
|
702
852
|
if (outcome.kind === "silent") this.silences++;
|
|
703
853
|
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
854
|
this.attempts = plan.attempts;
|
|
709
855
|
this.state = "waiting";
|
|
710
856
|
this.retryAt = now + plan.delay;
|
|
@@ -712,7 +858,7 @@ var LiveHub = class {
|
|
|
712
858
|
if (this.state === "waiting") this.connect();
|
|
713
859
|
}, plan.delay);
|
|
714
860
|
}
|
|
715
|
-
/** Stops for good: reads keep to the poll. */
|
|
861
|
+
/** Stops for good (no `http` here, or the last client left): reads keep to the poll. */
|
|
716
862
|
halt() {
|
|
717
863
|
this.state = "stopped";
|
|
718
864
|
clearTimeout(this.retryTimer);
|
|
@@ -723,8 +869,8 @@ var LiveHub = class {
|
|
|
723
869
|
}
|
|
724
870
|
dispose() {
|
|
725
871
|
this.halt();
|
|
726
|
-
const
|
|
727
|
-
if (
|
|
872
|
+
const registry2 = hubs();
|
|
873
|
+
if (registry2.get(this.id) === this) registry2.delete(this.id);
|
|
728
874
|
}
|
|
729
875
|
};
|
|
730
876
|
var LiveAttempt = class {
|
|
@@ -823,65 +969,473 @@ function versionUrl(events) {
|
|
|
823
969
|
url.pathname = url.pathname.replace(/events$/, "version");
|
|
824
970
|
return url;
|
|
825
971
|
}
|
|
826
|
-
function probeStamp(http, url, headers) {
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
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);
|
|
834
1103
|
try {
|
|
835
|
-
|
|
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 });
|
|
836
1109
|
} catch {
|
|
1110
|
+
bad(file);
|
|
837
1111
|
}
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
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;
|
|
841
1148
|
try {
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
});
|
|
855
|
-
|
|
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
|
-
}
|
|
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);
|
|
866
1163
|
});
|
|
867
|
-
|
|
868
|
-
|
|
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
|
+
}
|
|
869
1241
|
} catch {
|
|
870
|
-
finish();
|
|
871
1242
|
}
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
|
|
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;
|
|
875
1279
|
try {
|
|
876
|
-
return
|
|
1280
|
+
return fs.readdirSync(dir, { withFileTypes: true }).some((entry) => entry.isDirectory() && FOLDER.test(entry.name) && fs.readdirSync(join(dir, entry.name)).includes(MARKER));
|
|
877
1281
|
} catch {
|
|
878
|
-
return
|
|
1282
|
+
return false;
|
|
879
1283
|
}
|
|
880
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
|
+
}
|
|
881
1334
|
|
|
882
|
-
// src/
|
|
1335
|
+
// src/options.ts
|
|
883
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
|
|
884
1437
|
var DEFAULT_TIMEOUT = 1e4;
|
|
1438
|
+
var MIN_WRITE_TIMEOUT = 3e4;
|
|
885
1439
|
var MIN_UPLOAD_TIMEOUT = 6e4;
|
|
886
1440
|
var VERSION_TIMEOUT = 3e3;
|
|
887
1441
|
var DEFAULT_WAIT_FOR_FRESH = 1e3;
|
|
@@ -890,8 +1444,10 @@ var STORED_LIMIT = 5e3;
|
|
|
890
1444
|
var LOCALES_RETRY_MS = 6e4;
|
|
891
1445
|
var DEFAULT_GATEWAY_RETRY = 200;
|
|
892
1446
|
var MAX_GATEWAY_RETRY = 6e4;
|
|
893
|
-
var
|
|
894
|
-
|
|
1447
|
+
var DEFAULT_RATE_LIMIT_WAIT = 1e4;
|
|
1448
|
+
var MAX_RATE_LIMIT_RETRIES = 2;
|
|
1449
|
+
var NordhavnClient = class {
|
|
1450
|
+
constructor(options = {}) {
|
|
895
1451
|
/**
|
|
896
1452
|
* The refresh under way per cache key, so concurrent reads of one key share
|
|
897
1453
|
* one request, with the ticket it left on (see `state.ticket`).
|
|
@@ -925,25 +1481,32 @@ var HavenClient = class {
|
|
|
925
1481
|
*/
|
|
926
1482
|
locales: void 0,
|
|
927
1483
|
/** Epoch ms before which the locales are not asked for again, after that failed. */
|
|
928
|
-
localesRetryAt: 0
|
|
1484
|
+
localesRetryAt: 0,
|
|
1485
|
+
/** Whether the first read still has to say which project this is (`announceProject`). */
|
|
1486
|
+
announce: false
|
|
929
1487
|
};
|
|
930
|
-
|
|
931
|
-
this.apiKey =
|
|
932
|
-
this.baseUrl =
|
|
1488
|
+
const { apiKey, baseUrl } = connectionOf(options);
|
|
1489
|
+
this.apiKey = apiKey;
|
|
1490
|
+
this.baseUrl = baseUrl;
|
|
933
1491
|
const resolvedFetch = options.fetch ?? globalThis.fetch;
|
|
934
1492
|
if (!resolvedFetch) {
|
|
935
|
-
throw new Error("
|
|
1493
|
+
throw new Error("NordhavnClient: no `fetch` available; pass one via options.fetch");
|
|
936
1494
|
}
|
|
937
1495
|
this.fetchImpl = resolvedFetch.bind(globalThis);
|
|
938
1496
|
this.headers = options.headers ?? {};
|
|
939
1497
|
this.locale = options.locale || void 0;
|
|
940
1498
|
this.timeout = normalizeTimeout(options.timeout);
|
|
1499
|
+
this.writeTimeout = normalizeWriteTimeout(this.timeout, options.writeTimeout);
|
|
941
1500
|
this.onError = options.onError;
|
|
1501
|
+
this.log = loggerOf(options.logger);
|
|
1502
|
+
this.identity = identityOf(this.baseUrl, sentHeaders(this.apiKey, this.headers));
|
|
942
1503
|
const cacheOpt = options.cache;
|
|
943
1504
|
const cacheOptions = cacheOpt === false ? { enabled: false } : cacheOpt === true || cacheOpt === void 0 ? {} : cacheOpt;
|
|
944
|
-
this.cache = new ContentCache(cacheOptions);
|
|
1505
|
+
this.cache = new ContentCache({ ...cacheOptions, store: cacheStore(cacheOptions, this.identity, this.log) });
|
|
945
1506
|
this.waitForFresh = normalizeWait(cacheOptions.waitForFresh);
|
|
946
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 });
|
|
947
1510
|
const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false ? 0 : cacheOptions.revalidate ?? 6e4;
|
|
948
1511
|
const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT);
|
|
949
1512
|
this.versionTracker = new VersionTracker(
|
|
@@ -1132,7 +1695,7 @@ var HavenClient = class {
|
|
|
1132
1695
|
* The field decides what it takes: its `mimes` and `max_size` rules, within
|
|
1133
1696
|
* what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
|
|
1134
1697
|
* 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 `
|
|
1698
|
+
* top-level fields. A file of the wrong type or size throws `NordhavnError` 400
|
|
1136
1699
|
* with a message fit to show; other refusals (400, 403, 404) are setup
|
|
1137
1700
|
* errors. More than 10 uploads a minute per key throws 429. From a Node
|
|
1138
1701
|
* `Buffer`, send `new Blob([buffer])` with a `filename`.
|
|
@@ -1145,7 +1708,7 @@ var HavenClient = class {
|
|
|
1145
1708
|
async uploadFile(nodeSlug, datasetSlug, fieldSlug, file, opts) {
|
|
1146
1709
|
const filename = opts?.filename ?? file.name;
|
|
1147
1710
|
if (!filename) {
|
|
1148
|
-
throw new Error("
|
|
1711
|
+
throw new Error("NordhavnClient.uploadFile: the file has no name; pass `filename` (with its extension)");
|
|
1149
1712
|
}
|
|
1150
1713
|
const form = new FormData();
|
|
1151
1714
|
form.set("file", file, filename);
|
|
@@ -1153,7 +1716,7 @@ var HavenClient = class {
|
|
|
1153
1716
|
form.set("datasetSlug", datasetSlug);
|
|
1154
1717
|
form.set("fieldSlug", fieldSlug);
|
|
1155
1718
|
const url = `${this.baseUrl}/api/content/files`;
|
|
1156
|
-
const timeout = uploadTimeout(this.
|
|
1719
|
+
const timeout = uploadTimeout(this.writeTimeout, opts?.timeout);
|
|
1157
1720
|
return withTimeout(url, timeout, async (signal) => {
|
|
1158
1721
|
const res = await this.fetchImpl(url, {
|
|
1159
1722
|
method: "POST",
|
|
@@ -1180,7 +1743,7 @@ var HavenClient = class {
|
|
|
1180
1743
|
async write(method, path, body, nodeSlug, datasetSlug) {
|
|
1181
1744
|
let res;
|
|
1182
1745
|
try {
|
|
1183
|
-
res = await this.request(method, path, body);
|
|
1746
|
+
res = await this.request(method, path, body, this.writeTimeout);
|
|
1184
1747
|
} catch (err) {
|
|
1185
1748
|
if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, "recheck");
|
|
1186
1749
|
throw err;
|
|
@@ -1348,12 +1911,21 @@ var HavenClient = class {
|
|
|
1348
1911
|
*/
|
|
1349
1912
|
async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
|
|
1350
1913
|
const useCache = opts?.cache !== false;
|
|
1914
|
+
this.announceOnce();
|
|
1351
1915
|
if (!useCache) {
|
|
1352
|
-
|
|
1353
|
-
|
|
1916
|
+
let version2 = this.versionTracker.current() ?? void 0;
|
|
1917
|
+
let ticket = ++this.state.ticket;
|
|
1354
1918
|
let res;
|
|
1355
1919
|
try {
|
|
1356
|
-
|
|
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;
|
|
1357
1929
|
} catch (err) {
|
|
1358
1930
|
if (isDefinitive(err)) this.gone(cacheKey, ticket);
|
|
1359
1931
|
throw err;
|
|
@@ -1383,6 +1955,12 @@ var HavenClient = class {
|
|
|
1383
1955
|
const outcome = await within(refresh, budget - (Date.now() - started));
|
|
1384
1956
|
return outcome.settled ? outcome.value : last.value;
|
|
1385
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
|
+
}
|
|
1386
1964
|
/** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */
|
|
1387
1965
|
checkVersion(now) {
|
|
1388
1966
|
return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now);
|
|
@@ -1406,23 +1984,22 @@ var HavenClient = class {
|
|
|
1406
1984
|
};
|
|
1407
1985
|
const job = (async () => {
|
|
1408
1986
|
try {
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
}
|
|
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;
|
|
1426
2003
|
if (res.notModified && last) {
|
|
1427
2004
|
if (this.storable(cacheKey, ticket)) {
|
|
1428
2005
|
this.cache.confirm(cacheKey, version, Date.now());
|
|
@@ -1451,6 +2028,102 @@ var HavenClient = class {
|
|
|
1451
2028
|
this.inflight.set(cacheKey, { job, ticket });
|
|
1452
2029
|
return job;
|
|
1453
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
|
+
}
|
|
1454
2127
|
/**
|
|
1455
2128
|
* Hands an absorbed failure to `onError`, or without one warns once per
|
|
1456
2129
|
* outage. Never throws and never leaves a rejection behind: a broken hook
|
|
@@ -1469,7 +2142,7 @@ var HavenClient = class {
|
|
|
1469
2142
|
} else if (first) {
|
|
1470
2143
|
const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
|
|
1471
2144
|
const what = failure.during === "read" ? `could not refresh "${failure.key}"` : "stamp check failed";
|
|
1472
|
-
|
|
2145
|
+
logLine(this.log, "warn", `${what} (${reason}); cached content keeps being served.`);
|
|
1473
2146
|
}
|
|
1474
2147
|
} catch {
|
|
1475
2148
|
}
|
|
@@ -1531,7 +2204,7 @@ var HavenClient = class {
|
|
|
1531
2204
|
return await res.json();
|
|
1532
2205
|
});
|
|
1533
2206
|
}
|
|
1534
|
-
/** Parse a non-2xx response into a `
|
|
2207
|
+
/** Parse a non-2xx response into a `NordhavnError`, preferring its message. */
|
|
1535
2208
|
async toError(res) {
|
|
1536
2209
|
let message = res.statusText || `Request failed with status ${res.status}`;
|
|
1537
2210
|
let parsed;
|
|
@@ -1542,8 +2215,8 @@ var HavenClient = class {
|
|
|
1542
2215
|
else if (typeof m?.statusMessage === "string") message = m.statusMessage;
|
|
1543
2216
|
} catch {
|
|
1544
2217
|
}
|
|
1545
|
-
const err = new
|
|
1546
|
-
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()));
|
|
1547
2220
|
return err;
|
|
1548
2221
|
}
|
|
1549
2222
|
};
|
|
@@ -1565,7 +2238,7 @@ var DatasetHandle = class {
|
|
|
1565
2238
|
update(recordUid, data) {
|
|
1566
2239
|
return this.client.updateRecord(this.nodeSlug, this.datasetSlug, recordUid, data);
|
|
1567
2240
|
}
|
|
1568
|
-
/** 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`. */
|
|
1569
2242
|
uploadFile(fieldSlug, file, opts) {
|
|
1570
2243
|
return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts);
|
|
1571
2244
|
}
|
|
@@ -1596,9 +2269,13 @@ function normalizeTimeout(value) {
|
|
|
1596
2269
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
|
|
1597
2270
|
return value > MAX_TIMER ? 0 : value;
|
|
1598
2271
|
}
|
|
1599
|
-
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) {
|
|
1600
2277
|
if (typeof perCall === "number" && perCall >= 0) return normalizeTimeout(perCall);
|
|
1601
|
-
return
|
|
2278
|
+
return writeTimeout === 0 ? 0 : Math.max(writeTimeout, MIN_UPLOAD_TIMEOUT);
|
|
1602
2279
|
}
|
|
1603
2280
|
function withoutContentType(headers) {
|
|
1604
2281
|
return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-type"));
|
|
@@ -1608,6 +2285,11 @@ function normalizeGatewayRetry(value) {
|
|
|
1608
2285
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
|
|
1609
2286
|
return Math.min(value, MAX_GATEWAY_RETRY);
|
|
1610
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
|
+
}
|
|
1611
2293
|
function normalizeWait(value) {
|
|
1612
2294
|
if (value === false) return Infinity;
|
|
1613
2295
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH;
|
|
@@ -1647,24 +2329,34 @@ function unexpectedBody(url) {
|
|
|
1647
2329
|
function isTransientStatus(status) {
|
|
1648
2330
|
return status >= 500 || status === 408 || status === 429;
|
|
1649
2331
|
}
|
|
1650
|
-
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
|
+
}
|
|
1651
2343
|
function isGatewayHiccup(err) {
|
|
1652
|
-
return err instanceof
|
|
2344
|
+
return err instanceof NordhavnError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
|
|
1653
2345
|
}
|
|
1654
2346
|
function sleep(ms) {
|
|
1655
2347
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1656
2348
|
}
|
|
1657
2349
|
function isDefinitive(err) {
|
|
1658
|
-
return err instanceof
|
|
2350
|
+
return err instanceof NordhavnError && !isTransientStatus(err.status) && isStudioAnswer(err);
|
|
1659
2351
|
}
|
|
1660
2352
|
function isStudioAnswer(err) {
|
|
1661
2353
|
return isStudioBody(err.status, err.body);
|
|
1662
2354
|
}
|
|
1663
2355
|
function isMissingRoute(err) {
|
|
1664
|
-
return err instanceof
|
|
2356
|
+
return err instanceof NordhavnError && err.status === 404 && isStudioAnswer(err);
|
|
1665
2357
|
}
|
|
1666
2358
|
function writeMayHaveLanded(err) {
|
|
1667
|
-
return !(err instanceof
|
|
2359
|
+
return !(err instanceof NordhavnError && err.status >= 400 && err.status < 500);
|
|
1668
2360
|
}
|
|
1669
2361
|
function datasetPath(nodeSlug, datasetSlug) {
|
|
1670
2362
|
return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`;
|
|
@@ -1921,8 +2613,10 @@ function parseChartFence(source) {
|
|
|
1921
2613
|
|
|
1922
2614
|
// src/index.ts
|
|
1923
2615
|
function createClient(options) {
|
|
1924
|
-
return new
|
|
2616
|
+
return new NordhavnClient(options);
|
|
1925
2617
|
}
|
|
2618
|
+
var HavenClient = NordhavnClient;
|
|
2619
|
+
var HavenError = NordhavnError;
|
|
1926
2620
|
|
|
1927
2621
|
exports.AGGREGATIONS = AGGREGATIONS;
|
|
1928
2622
|
exports.BUCKET_MODES = BUCKET_MODES;
|
|
@@ -1939,6 +2633,8 @@ exports.DatasetHandle = DatasetHandle;
|
|
|
1939
2633
|
exports.HavenClient = HavenClient;
|
|
1940
2634
|
exports.HavenError = HavenError;
|
|
1941
2635
|
exports.MemoryCacheStore = MemoryCacheStore;
|
|
2636
|
+
exports.NordhavnClient = NordhavnClient;
|
|
2637
|
+
exports.NordhavnError = NordhavnError;
|
|
1942
2638
|
exports.PALETTE_KEYS = PALETTE_KEYS;
|
|
1943
2639
|
exports.chartFenceHeight = chartFenceHeight;
|
|
1944
2640
|
exports.chartTypeInfo = chartTypeInfo;
|