@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.js
CHANGED
|
@@ -1,6 +1,180 @@
|
|
|
1
|
+
import { builtinFileDeps, attachShared, ATTACH } from './chunk-FLRBCD6H.js';
|
|
1
2
|
import { chartTypeInfo, CHART_TYPES, PALETTE_KEYS, CHART_AXES } from './chunk-UNIWH5QN.js';
|
|
2
3
|
export { AGGREGATIONS, BUCKET_MODES, CHART_AXES, CHART_SORTS, CHART_TYPES, CHART_TYPE_INFO, DATE_BUCKET_VALUES, PALETTE_KEYS, chartTypeInfo, isBarChart, isPartChart } from './chunk-UNIWH5QN.js';
|
|
3
4
|
|
|
5
|
+
// src/runtime.ts
|
|
6
|
+
var BODY_LIMIT = 16 * 1024;
|
|
7
|
+
function environment() {
|
|
8
|
+
try {
|
|
9
|
+
return globalThis.process?.env ?? {};
|
|
10
|
+
} catch {
|
|
11
|
+
return {};
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function readEnv(name) {
|
|
15
|
+
try {
|
|
16
|
+
const value = environment()[name];
|
|
17
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
18
|
+
} catch {
|
|
19
|
+
return void 0;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function nodeRuntime() {
|
|
23
|
+
const g = globalThis;
|
|
24
|
+
if (typeof g.window !== "undefined" || typeof g.document !== "undefined") return false;
|
|
25
|
+
if (g.navigator?.userAgent === "Cloudflare-Workers") return false;
|
|
26
|
+
return typeof g.process?.versions?.node === "string";
|
|
27
|
+
}
|
|
28
|
+
function nodeBuiltin(id) {
|
|
29
|
+
try {
|
|
30
|
+
const proc = globalThis.process;
|
|
31
|
+
return typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : void 0;
|
|
32
|
+
} catch {
|
|
33
|
+
return void 0;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function loadHttp(protocol) {
|
|
37
|
+
const name = protocol === "https:" ? "node:https" : "node:http";
|
|
38
|
+
const builtin = nodeBuiltin(name);
|
|
39
|
+
if (builtin) return builtin;
|
|
40
|
+
return await import(
|
|
41
|
+
/* webpackIgnore: true */
|
|
42
|
+
/* @vite-ignore */
|
|
43
|
+
name
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
function unrefTimer(run, ms) {
|
|
47
|
+
const timer = setTimeout(run, ms);
|
|
48
|
+
timer.unref?.();
|
|
49
|
+
return timer;
|
|
50
|
+
}
|
|
51
|
+
function sentHeaders(apiKey, extra) {
|
|
52
|
+
const headers = { authorization: `Bearer ${apiKey}` };
|
|
53
|
+
for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
|
|
54
|
+
return headers;
|
|
55
|
+
}
|
|
56
|
+
function identityOf(baseUrl, headers) {
|
|
57
|
+
return `${baseUrl}
|
|
58
|
+
${headers.authorization ?? ""}`;
|
|
59
|
+
}
|
|
60
|
+
function getJson(http, url, headers, timeoutMs) {
|
|
61
|
+
return new Promise((resolve) => {
|
|
62
|
+
let req;
|
|
63
|
+
let settled = false;
|
|
64
|
+
const finish = (body) => {
|
|
65
|
+
if (settled) return;
|
|
66
|
+
settled = true;
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
try {
|
|
69
|
+
req?.destroy();
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
72
|
+
resolve(body);
|
|
73
|
+
};
|
|
74
|
+
const timer = unrefTimer(() => finish(), timeoutMs);
|
|
75
|
+
try {
|
|
76
|
+
req = http.request(url, { method: "GET", headers, agent: false }, (res) => {
|
|
77
|
+
res.on("error", () => finish());
|
|
78
|
+
if (res.statusCode !== 200) {
|
|
79
|
+
res.resume();
|
|
80
|
+
finish();
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
let body = "";
|
|
84
|
+
res.setEncoding("utf8");
|
|
85
|
+
res.on("data", (chunk) => {
|
|
86
|
+
body += chunk;
|
|
87
|
+
if (body.length > BODY_LIMIT) finish();
|
|
88
|
+
});
|
|
89
|
+
res.on("end", () => finish(parseJson(body)));
|
|
90
|
+
res.on("close", () => finish());
|
|
91
|
+
});
|
|
92
|
+
req.on("socket", (socket) => {
|
|
93
|
+
try {
|
|
94
|
+
socket.unref();
|
|
95
|
+
} catch {
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
req.on("error", () => finish());
|
|
99
|
+
req.end();
|
|
100
|
+
} catch {
|
|
101
|
+
finish();
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
function parseJson(text) {
|
|
106
|
+
try {
|
|
107
|
+
return JSON.parse(text);
|
|
108
|
+
} catch {
|
|
109
|
+
return void 0;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
var WRITTEN = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/written/1");
|
|
113
|
+
function firstTime(key) {
|
|
114
|
+
const scope = globalThis;
|
|
115
|
+
let seen = scope[WRITTEN];
|
|
116
|
+
if (!seen) {
|
|
117
|
+
seen = /* @__PURE__ */ new Set();
|
|
118
|
+
scope[WRITTEN] = seen;
|
|
119
|
+
}
|
|
120
|
+
if (seen.has(key)) return false;
|
|
121
|
+
seen.add(key);
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
function loggerOf(option) {
|
|
125
|
+
if (option === false) return void 0;
|
|
126
|
+
return option ?? console;
|
|
127
|
+
}
|
|
128
|
+
function logLine(log, level, message, ...rest) {
|
|
129
|
+
try {
|
|
130
|
+
const write = log?.[level];
|
|
131
|
+
if (typeof write === "function") write.call(log, `[@nordhavnhq/beacon] ${message}`, ...rest);
|
|
132
|
+
} catch {
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/announce.ts
|
|
137
|
+
var PROJECT_TIMEOUT_MS = 3e3;
|
|
138
|
+
var NAME_LIMIT = 200;
|
|
139
|
+
function isDevelopment(env) {
|
|
140
|
+
if (env.NODE_ENV?.trim().toLowerCase() !== "development") return false;
|
|
141
|
+
const ci = env.CI?.trim().toLowerCase();
|
|
142
|
+
return ci === void 0 || ci === "" || ci === "0" || ci === "false";
|
|
143
|
+
}
|
|
144
|
+
function wantAnnounce(settings) {
|
|
145
|
+
try {
|
|
146
|
+
return typeof settings.log?.info === "function" && !settings.customFetch && nodeRuntime() && isDevelopment(environment());
|
|
147
|
+
} catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function announceProject(baseUrl, headers, log) {
|
|
152
|
+
try {
|
|
153
|
+
if (!firstTime(`project
|
|
154
|
+
${identityOf(baseUrl, headers)}`)) return;
|
|
155
|
+
const url = new URL(`${baseUrl}/api/content/project`);
|
|
156
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return;
|
|
157
|
+
loadHttp(url.protocol).then((http) => getJson(http, url, { ...headers, accept: "application/json" }, PROJECT_TIMEOUT_MS)).then((body) => {
|
|
158
|
+
const line = projectLine(body);
|
|
159
|
+
if (line) logLine(log, "info", line);
|
|
160
|
+
}, () => {
|
|
161
|
+
});
|
|
162
|
+
} catch {
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function projectLine(body) {
|
|
166
|
+
const answer = body;
|
|
167
|
+
const project = printable(answer?.project?.name);
|
|
168
|
+
if (!project) return void 0;
|
|
169
|
+
const key = printable(answer?.key?.name);
|
|
170
|
+
return key ? `connected to "${project}" (key "${key}")` : `connected to "${project}"`;
|
|
171
|
+
}
|
|
172
|
+
function printable(value) {
|
|
173
|
+
if (typeof value !== "string") return void 0;
|
|
174
|
+
const text = value.replace(/[\u0000-\u001F\u007F]+/g, " ").trim().slice(0, NAME_LIMIT);
|
|
175
|
+
return text === "" ? void 0 : text;
|
|
176
|
+
}
|
|
177
|
+
|
|
4
178
|
// src/cache.ts
|
|
5
179
|
var EXPIRED = 1;
|
|
6
180
|
var MemoryCacheStore = class {
|
|
@@ -131,14 +305,14 @@ var ContentCache = class {
|
|
|
131
305
|
};
|
|
132
306
|
|
|
133
307
|
// src/errors.ts
|
|
134
|
-
var
|
|
308
|
+
var NordhavnError = class _NordhavnError extends Error {
|
|
135
309
|
constructor(message, status, body) {
|
|
136
310
|
super(message);
|
|
137
|
-
this.name = "
|
|
311
|
+
this.name = "NordhavnError";
|
|
138
312
|
this.status = status;
|
|
139
313
|
this.body = body;
|
|
140
314
|
this.code = errorCode(body);
|
|
141
|
-
Object.setPrototypeOf(this,
|
|
315
|
+
Object.setPrototypeOf(this, _NordhavnError.prototype);
|
|
142
316
|
}
|
|
143
317
|
get isUnauthorized() {
|
|
144
318
|
return this.status === 401;
|
|
@@ -212,29 +386,28 @@ var LIVE = {
|
|
|
212
386
|
function planReconnect(outcome, ctx) {
|
|
213
387
|
const attempts = ctx.stable ? 0 : ctx.attempts;
|
|
214
388
|
if (outcome.kind === "closed" && ctx.stable) {
|
|
215
|
-
return {
|
|
389
|
+
return { delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 };
|
|
216
390
|
}
|
|
217
391
|
if (outcome.kind === "refused") return planRefused(outcome, { ...ctx, attempts });
|
|
218
392
|
return backoff(attempts, ctx.random);
|
|
219
393
|
}
|
|
220
394
|
function planRefused(outcome, ctx) {
|
|
221
395
|
const { status, studio } = outcome;
|
|
222
|
-
if (studio && (status === 401 || status === 403)) return { stop: true };
|
|
223
396
|
const asked = parseRetryAfter(outcome.retryAfter, ctx.now);
|
|
224
397
|
if (status === 429 || status === 503 && asked !== void 0) {
|
|
225
398
|
const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs);
|
|
226
|
-
return {
|
|
399
|
+
return { delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts };
|
|
227
400
|
}
|
|
228
401
|
const studioRefusal = studio && status >= 400 && status < 500 && status !== 408;
|
|
229
402
|
if (studioRefusal || status >= 300 && status < 400) {
|
|
230
|
-
return {
|
|
403
|
+
return { delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts };
|
|
231
404
|
}
|
|
232
405
|
return backoff(ctx.attempts, ctx.random);
|
|
233
406
|
}
|
|
234
407
|
function backoff(attempts, random) {
|
|
235
408
|
const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16);
|
|
236
409
|
const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window);
|
|
237
|
-
return {
|
|
410
|
+
return { delay, attempts: attempts + 1 };
|
|
238
411
|
}
|
|
239
412
|
function longJitter(wait, random) {
|
|
240
413
|
return random() * Math.min(LIVE.longJitterMs, wait / 5);
|
|
@@ -245,10 +418,12 @@ function between(min, max, random) {
|
|
|
245
418
|
function clamp(value, min, max) {
|
|
246
419
|
return Math.min(max, Math.max(min, value));
|
|
247
420
|
}
|
|
421
|
+
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$/;
|
|
248
422
|
function parseRetryAfter(value, now) {
|
|
249
423
|
const text = value?.trim();
|
|
250
424
|
if (!text) return void 0;
|
|
251
|
-
if (
|
|
425
|
+
if (/^\d+$/.test(text)) return Number(text) * 1e3;
|
|
426
|
+
if (!IMF_FIXDATE.test(text)) return void 0;
|
|
252
427
|
const at = Date.parse(text);
|
|
253
428
|
return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
|
|
254
429
|
}
|
|
@@ -444,35 +619,13 @@ var collected = typeof FinalizationRegistry === "function" ? new FinalizationReg
|
|
|
444
619
|
} catch {
|
|
445
620
|
}
|
|
446
621
|
}) : void 0;
|
|
447
|
-
function liveRuntime() {
|
|
448
|
-
const g = globalThis;
|
|
449
|
-
if (typeof g.window !== "undefined" || typeof g.document !== "undefined") return false;
|
|
450
|
-
if (g.navigator?.userAgent === "Cloudflare-Workers") return false;
|
|
451
|
-
return typeof g.process?.versions?.node === "string";
|
|
452
|
-
}
|
|
453
622
|
function wantLive(settings) {
|
|
454
623
|
try {
|
|
455
|
-
return chooseLive({ ...settings, runtime:
|
|
624
|
+
return chooseLive({ ...settings, runtime: nodeRuntime(), env: environment() });
|
|
456
625
|
} catch {
|
|
457
626
|
return false;
|
|
458
627
|
}
|
|
459
628
|
}
|
|
460
|
-
async function loadHttp(protocol) {
|
|
461
|
-
const name = protocol === "https:" ? "node:https" : "node:http";
|
|
462
|
-
const proc = globalThis.process;
|
|
463
|
-
const builtin = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule(name) : void 0;
|
|
464
|
-
if (builtin) return builtin;
|
|
465
|
-
return await import(
|
|
466
|
-
/* webpackIgnore: true */
|
|
467
|
-
/* @vite-ignore */
|
|
468
|
-
name
|
|
469
|
-
);
|
|
470
|
-
}
|
|
471
|
-
function unrefTimer(run, ms) {
|
|
472
|
-
const timer = setTimeout(run, ms);
|
|
473
|
-
timer.unref?.();
|
|
474
|
-
return timer;
|
|
475
|
-
}
|
|
476
629
|
var LiveLink = class {
|
|
477
630
|
constructor(baseUrl, apiKey, headers, owner) {
|
|
478
631
|
this.baseUrl = baseUrl;
|
|
@@ -528,8 +681,7 @@ var LiveLink = class {
|
|
|
528
681
|
}
|
|
529
682
|
const registry = hubs();
|
|
530
683
|
const headers = liveHeaders(this.apiKey, this.headers);
|
|
531
|
-
const id =
|
|
532
|
-
${headers.authorization ?? ""}`;
|
|
684
|
+
const id = identityOf(this.baseUrl, headers);
|
|
533
685
|
let hub = registry.get(id);
|
|
534
686
|
if (!hub) {
|
|
535
687
|
hub = new LiveHub(id, url, headers);
|
|
@@ -551,8 +703,7 @@ function eventsUrl(baseUrl) {
|
|
|
551
703
|
}
|
|
552
704
|
}
|
|
553
705
|
function liveHeaders(apiKey, extra) {
|
|
554
|
-
const headers =
|
|
555
|
-
for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
|
|
706
|
+
const headers = sentHeaders(apiKey, extra);
|
|
556
707
|
headers.accept = "text/event-stream";
|
|
557
708
|
headers["cache-control"] = "no-cache";
|
|
558
709
|
headers["accept-encoding"] = "identity";
|
|
@@ -702,10 +853,6 @@ var LiveHub = class {
|
|
|
702
853
|
if (!outcome || this.state === "stopped") return;
|
|
703
854
|
if (outcome.kind === "silent") this.silences++;
|
|
704
855
|
const plan = planReconnect(outcome, { attempts: this.attempts, stable, pauseMs: UNSUPPORTED_PAUSE_MS, now, random: Math.random });
|
|
705
|
-
if (plan.stop) {
|
|
706
|
-
this.halt();
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
856
|
this.attempts = plan.attempts;
|
|
710
857
|
this.state = "waiting";
|
|
711
858
|
this.retryAt = now + plan.delay;
|
|
@@ -713,7 +860,7 @@ var LiveHub = class {
|
|
|
713
860
|
if (this.state === "waiting") this.connect();
|
|
714
861
|
}, plan.delay);
|
|
715
862
|
}
|
|
716
|
-
/** Stops for good: reads keep to the poll. */
|
|
863
|
+
/** Stops for good (no `http` here, or the last client left): reads keep to the poll. */
|
|
717
864
|
halt() {
|
|
718
865
|
this.state = "stopped";
|
|
719
866
|
clearTimeout(this.retryTimer);
|
|
@@ -824,65 +971,115 @@ function versionUrl(events) {
|
|
|
824
971
|
url.pathname = url.pathname.replace(/events$/, "version");
|
|
825
972
|
return url;
|
|
826
973
|
}
|
|
827
|
-
function probeStamp(http, url, headers) {
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
974
|
+
async function probeStamp(http, url, headers) {
|
|
975
|
+
const stamp = (await getJson(http, url, headers, LIVE.safetyProbeTimeoutMs))?.version;
|
|
976
|
+
return typeof stamp === "string" && stamp !== "" ? stamp : void 0;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// src/options.ts
|
|
980
|
+
var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
|
|
981
|
+
var API_KEY_ENV = "NORDHAVN_API_KEY";
|
|
982
|
+
var BASE_URL_ENV = "NORDHAVN_BASE_URL";
|
|
983
|
+
function connectionOf(options) {
|
|
984
|
+
const apiKey = "apiKey" in options ? options.apiKey?.trim() : readEnv(API_KEY_ENV);
|
|
985
|
+
if (!apiKey) throw new Error(missingKey(options));
|
|
986
|
+
const baseUrl = "baseUrl" in options ? options.baseUrl === void 0 ? DEFAULT_BASE_URL : options.baseUrl.trim() : readEnv(BASE_URL_ENV) ?? DEFAULT_BASE_URL;
|
|
987
|
+
if (!baseUrl) {
|
|
988
|
+
throw new Error("NordhavnClient: `baseUrl` is empty (leave it out for NORDHAVN_BASE_URL or the hosted platform)");
|
|
989
|
+
}
|
|
990
|
+
return { apiKey, baseUrl: baseUrl.replace(/\/+$/, "") };
|
|
991
|
+
}
|
|
992
|
+
function missingKey(options) {
|
|
993
|
+
if (!("apiKey" in options)) return `NordhavnClient: \`apiKey\` is required: pass it, or set ${API_KEY_ENV}`;
|
|
994
|
+
if (options.apiKey === void 0) {
|
|
995
|
+
return `NordhavnClient: \`apiKey\` is required (it was passed as \`undefined\`; leave it out altogether to read ${API_KEY_ENV})`;
|
|
996
|
+
}
|
|
997
|
+
return "NordhavnClient: `apiKey` is empty (an empty string does not fall back to the environment)";
|
|
998
|
+
}
|
|
999
|
+
function cacheStore(options, identity, log) {
|
|
1000
|
+
if (options.enabled === false) return options.store;
|
|
1001
|
+
const dir = options.dir || void 0;
|
|
1002
|
+
if (dir !== void 0 && options.store !== void 0) {
|
|
1003
|
+
throw new Error("NordhavnClient: pass `cache.dir` or `cache.store`, not both");
|
|
1004
|
+
}
|
|
1005
|
+
const warn = log && typeof log.warn === "function" ? (...args) => log.warn(...args) : void 0;
|
|
1006
|
+
const scope = { identity, adoptLegacy: dir === void 0, warn };
|
|
1007
|
+
let attached;
|
|
1008
|
+
if (dir !== void 0) {
|
|
1009
|
+
const deps = builtinFileDeps(nodeBuiltin);
|
|
1010
|
+
if (!deps) {
|
|
1011
|
+
if (firstTime("no-file-cache")) {
|
|
1012
|
+
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.");
|
|
838
1013
|
}
|
|
839
|
-
|
|
840
|
-
};
|
|
841
|
-
const timer = unrefTimer(() => finish(), LIVE.safetyProbeTimeoutMs);
|
|
842
|
-
try {
|
|
843
|
-
req = http.request(url, { method: "GET", headers, agent: false }, (res) => {
|
|
844
|
-
res.on("error", () => finish());
|
|
845
|
-
if (res.statusCode !== 200) {
|
|
846
|
-
res.resume();
|
|
847
|
-
finish();
|
|
848
|
-
return;
|
|
849
|
-
}
|
|
850
|
-
let body = "";
|
|
851
|
-
res.setEncoding("utf8");
|
|
852
|
-
res.on("data", (chunk) => {
|
|
853
|
-
body += chunk;
|
|
854
|
-
if (body.length > REFUSAL_BODY_LIMIT) finish();
|
|
855
|
-
});
|
|
856
|
-
res.on("end", () => {
|
|
857
|
-
const stamp = parseJson(body)?.version;
|
|
858
|
-
finish(typeof stamp === "string" && stamp !== "" ? stamp : void 0);
|
|
859
|
-
});
|
|
860
|
-
res.on("close", () => finish());
|
|
861
|
-
});
|
|
862
|
-
req.on("socket", (socket) => {
|
|
863
|
-
try {
|
|
864
|
-
socket.unref();
|
|
865
|
-
} catch {
|
|
866
|
-
}
|
|
867
|
-
});
|
|
868
|
-
req.on("error", () => finish());
|
|
869
|
-
req.end();
|
|
870
|
-
} catch {
|
|
871
|
-
finish();
|
|
1014
|
+
return void 0;
|
|
872
1015
|
}
|
|
873
|
-
|
|
1016
|
+
attached = attachShared({ dir, maxEntries: options.maxEntries }, deps, scope);
|
|
1017
|
+
} else {
|
|
1018
|
+
const attach = options.store?.[ATTACH];
|
|
1019
|
+
if (typeof attach !== "function") return options.store;
|
|
1020
|
+
attached = attach.call(options.store, scope);
|
|
1021
|
+
}
|
|
1022
|
+
if (!attached) {
|
|
1023
|
+
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.");
|
|
1024
|
+
return new MemoryCacheStore(options.maxEntries ?? 500);
|
|
1025
|
+
}
|
|
1026
|
+
if (attached.first) tellDisk(attached, dir === void 0, log);
|
|
1027
|
+
return attached.store;
|
|
874
1028
|
}
|
|
875
|
-
function
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
1029
|
+
function tellDisk(attached, fromStore, log) {
|
|
1030
|
+
const { folder, loaded, legacy, copied } = attached;
|
|
1031
|
+
if (copied > 0 && firstTime(`copied
|
|
1032
|
+
${folder}`)) {
|
|
1033
|
+
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`);
|
|
1034
|
+
} else if (copied === 0 && legacy > 0 && loaded === 0 && firstTime(`legacy
|
|
1035
|
+
${folder}`)) {
|
|
1036
|
+
const why = fromStore ? "only the first start after 0.7 copies them" : "`cache.dir` keeps its entries per key";
|
|
1037
|
+
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}`);
|
|
1038
|
+
}
|
|
1039
|
+
if (!firstTime(`disk
|
|
1040
|
+
${folder}`)) return;
|
|
1041
|
+
if (loaded > 0) logLine(log, "info", `file cache ${folder}: ${count(loaded, "entry", "entries")} on disk`);
|
|
1042
|
+
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).`);
|
|
1043
|
+
}
|
|
1044
|
+
function count(n, one, many) {
|
|
1045
|
+
return `${n} ${n === 1 ? one : many}`;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// src/rate-gate.ts
|
|
1049
|
+
var GATES = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/rate-gates/2");
|
|
1050
|
+
var GATE_MAX_MS = 6e4;
|
|
1051
|
+
function monotonicNow() {
|
|
1052
|
+
const perf = globalThis.performance;
|
|
1053
|
+
return typeof perf?.now === "function" ? perf.now() : Date.now();
|
|
1054
|
+
}
|
|
1055
|
+
function gates() {
|
|
1056
|
+
const scope = globalThis;
|
|
1057
|
+
let map = scope[GATES];
|
|
1058
|
+
if (!map) {
|
|
1059
|
+
map = /* @__PURE__ */ new Map();
|
|
1060
|
+
scope[GATES] = map;
|
|
880
1061
|
}
|
|
1062
|
+
return map;
|
|
1063
|
+
}
|
|
1064
|
+
function gateRemaining(identity, now = monotonicNow()) {
|
|
1065
|
+
const map = gates();
|
|
1066
|
+
const opensAt = map.get(identity) ?? 0;
|
|
1067
|
+
if (opensAt > now) return opensAt - now;
|
|
1068
|
+
map.delete(identity);
|
|
1069
|
+
return 0;
|
|
1070
|
+
}
|
|
1071
|
+
function shutGate(identity, ms, now = monotonicNow()) {
|
|
1072
|
+
const map = gates();
|
|
1073
|
+
const opensAt = now + Math.min(Math.max(0, ms), GATE_MAX_MS);
|
|
1074
|
+
if (opensAt > (map.get(identity) ?? 0)) map.set(identity, opensAt);
|
|
1075
|
+
}
|
|
1076
|
+
function spreadOf(ms, random = Math.random) {
|
|
1077
|
+
return random() * Math.max(1e3, ms / 5);
|
|
881
1078
|
}
|
|
882
1079
|
|
|
883
1080
|
// src/client.ts
|
|
884
|
-
var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
|
|
885
1081
|
var DEFAULT_TIMEOUT = 1e4;
|
|
1082
|
+
var MIN_WRITE_TIMEOUT = 3e4;
|
|
886
1083
|
var MIN_UPLOAD_TIMEOUT = 6e4;
|
|
887
1084
|
var VERSION_TIMEOUT = 3e3;
|
|
888
1085
|
var DEFAULT_WAIT_FOR_FRESH = 1e3;
|
|
@@ -891,8 +1088,10 @@ var STORED_LIMIT = 5e3;
|
|
|
891
1088
|
var LOCALES_RETRY_MS = 6e4;
|
|
892
1089
|
var DEFAULT_GATEWAY_RETRY = 200;
|
|
893
1090
|
var MAX_GATEWAY_RETRY = 6e4;
|
|
894
|
-
var
|
|
895
|
-
|
|
1091
|
+
var DEFAULT_RATE_LIMIT_WAIT = 1e4;
|
|
1092
|
+
var MAX_RATE_LIMIT_RETRIES = 2;
|
|
1093
|
+
var NordhavnClient = class {
|
|
1094
|
+
constructor(options = {}) {
|
|
896
1095
|
/**
|
|
897
1096
|
* The refresh under way per cache key, so concurrent reads of one key share
|
|
898
1097
|
* one request, with the ticket it left on (see `state.ticket`).
|
|
@@ -926,25 +1125,32 @@ var HavenClient = class {
|
|
|
926
1125
|
*/
|
|
927
1126
|
locales: void 0,
|
|
928
1127
|
/** Epoch ms before which the locales are not asked for again, after that failed. */
|
|
929
|
-
localesRetryAt: 0
|
|
1128
|
+
localesRetryAt: 0,
|
|
1129
|
+
/** Whether the first read still has to say which project this is (`announceProject`). */
|
|
1130
|
+
announce: false
|
|
930
1131
|
};
|
|
931
|
-
|
|
932
|
-
this.apiKey =
|
|
933
|
-
this.baseUrl =
|
|
1132
|
+
const { apiKey, baseUrl } = connectionOf(options);
|
|
1133
|
+
this.apiKey = apiKey;
|
|
1134
|
+
this.baseUrl = baseUrl;
|
|
934
1135
|
const resolvedFetch = options.fetch ?? globalThis.fetch;
|
|
935
1136
|
if (!resolvedFetch) {
|
|
936
|
-
throw new Error("
|
|
1137
|
+
throw new Error("NordhavnClient: no `fetch` available; pass one via options.fetch");
|
|
937
1138
|
}
|
|
938
1139
|
this.fetchImpl = resolvedFetch.bind(globalThis);
|
|
939
1140
|
this.headers = options.headers ?? {};
|
|
940
1141
|
this.locale = options.locale || void 0;
|
|
941
1142
|
this.timeout = normalizeTimeout(options.timeout);
|
|
1143
|
+
this.writeTimeout = normalizeWriteTimeout(this.timeout, options.writeTimeout);
|
|
942
1144
|
this.onError = options.onError;
|
|
1145
|
+
this.log = loggerOf(options.logger);
|
|
1146
|
+
this.identity = identityOf(this.baseUrl, sentHeaders(this.apiKey, this.headers));
|
|
943
1147
|
const cacheOpt = options.cache;
|
|
944
1148
|
const cacheOptions = cacheOpt === false ? { enabled: false } : cacheOpt === true || cacheOpt === void 0 ? {} : cacheOpt;
|
|
945
|
-
this.cache = new ContentCache(cacheOptions);
|
|
1149
|
+
this.cache = new ContentCache({ ...cacheOptions, store: cacheStore(cacheOptions, this.identity, this.log) });
|
|
946
1150
|
this.waitForFresh = normalizeWait(cacheOptions.waitForFresh);
|
|
947
1151
|
this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry);
|
|
1152
|
+
this.rateLimitWait = normalizeRateLimitWait(options.rateLimitWait);
|
|
1153
|
+
this.state.announce = wantAnnounce({ log: this.log, customFetch: options.fetch !== void 0 });
|
|
948
1154
|
const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false ? 0 : cacheOptions.revalidate ?? 6e4;
|
|
949
1155
|
const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT);
|
|
950
1156
|
this.versionTracker = new VersionTracker(
|
|
@@ -1133,7 +1339,7 @@ var HavenClient = class {
|
|
|
1133
1339
|
* The field decides what it takes: its `mimes` and `max_size` rules, within
|
|
1134
1340
|
* what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
|
|
1135
1341
|
* studio reads the type from the content, so a renamed file is refused. Only
|
|
1136
|
-
* top-level fields. A file of the wrong type or size throws `
|
|
1342
|
+
* top-level fields. A file of the wrong type or size throws `NordhavnError` 400
|
|
1137
1343
|
* with a message fit to show; other refusals (400, 403, 404) are setup
|
|
1138
1344
|
* errors. More than 10 uploads a minute per key throws 429. From a Node
|
|
1139
1345
|
* `Buffer`, send `new Blob([buffer])` with a `filename`.
|
|
@@ -1146,7 +1352,7 @@ var HavenClient = class {
|
|
|
1146
1352
|
async uploadFile(nodeSlug, datasetSlug, fieldSlug, file, opts) {
|
|
1147
1353
|
const filename = opts?.filename ?? file.name;
|
|
1148
1354
|
if (!filename) {
|
|
1149
|
-
throw new Error("
|
|
1355
|
+
throw new Error("NordhavnClient.uploadFile: the file has no name; pass `filename` (with its extension)");
|
|
1150
1356
|
}
|
|
1151
1357
|
const form = new FormData();
|
|
1152
1358
|
form.set("file", file, filename);
|
|
@@ -1154,7 +1360,7 @@ var HavenClient = class {
|
|
|
1154
1360
|
form.set("datasetSlug", datasetSlug);
|
|
1155
1361
|
form.set("fieldSlug", fieldSlug);
|
|
1156
1362
|
const url = `${this.baseUrl}/api/content/files`;
|
|
1157
|
-
const timeout = uploadTimeout(this.
|
|
1363
|
+
const timeout = uploadTimeout(this.writeTimeout, opts?.timeout);
|
|
1158
1364
|
return withTimeout(url, timeout, async (signal) => {
|
|
1159
1365
|
const res = await this.fetchImpl(url, {
|
|
1160
1366
|
method: "POST",
|
|
@@ -1181,7 +1387,7 @@ var HavenClient = class {
|
|
|
1181
1387
|
async write(method, path, body, nodeSlug, datasetSlug) {
|
|
1182
1388
|
let res;
|
|
1183
1389
|
try {
|
|
1184
|
-
res = await this.request(method, path, body);
|
|
1390
|
+
res = await this.request(method, path, body, this.writeTimeout);
|
|
1185
1391
|
} catch (err) {
|
|
1186
1392
|
if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, "recheck");
|
|
1187
1393
|
throw err;
|
|
@@ -1349,12 +1555,21 @@ var HavenClient = class {
|
|
|
1349
1555
|
*/
|
|
1350
1556
|
async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
|
|
1351
1557
|
const useCache = opts?.cache !== false;
|
|
1558
|
+
this.announceOnce();
|
|
1352
1559
|
if (!useCache) {
|
|
1353
|
-
|
|
1354
|
-
|
|
1560
|
+
let version2 = this.versionTracker.current() ?? void 0;
|
|
1561
|
+
let ticket = ++this.state.ticket;
|
|
1355
1562
|
let res;
|
|
1356
1563
|
try {
|
|
1357
|
-
|
|
1564
|
+
const got = await this.askRetrying(path, void 0, isExpected, false, {
|
|
1565
|
+
allowed: () => true,
|
|
1566
|
+
resume: () => {
|
|
1567
|
+
ticket = ++this.state.ticket;
|
|
1568
|
+
version2 = this.versionTracker.current() ?? void 0;
|
|
1569
|
+
return void 0;
|
|
1570
|
+
}
|
|
1571
|
+
});
|
|
1572
|
+
res = got.answer;
|
|
1358
1573
|
} catch (err) {
|
|
1359
1574
|
if (isDefinitive(err)) this.gone(cacheKey, ticket);
|
|
1360
1575
|
throw err;
|
|
@@ -1384,6 +1599,12 @@ var HavenClient = class {
|
|
|
1384
1599
|
const outcome = await within(refresh, budget - (Date.now() - started));
|
|
1385
1600
|
return outcome.settled ? outcome.value : last.value;
|
|
1386
1601
|
}
|
|
1602
|
+
/** On the first read, in development: which project this key reads (`announceProject`). */
|
|
1603
|
+
announceOnce() {
|
|
1604
|
+
if (!this.state.announce) return;
|
|
1605
|
+
this.state.announce = false;
|
|
1606
|
+
announceProject(this.baseUrl, sentHeaders(this.apiKey, this.headers), this.log);
|
|
1607
|
+
}
|
|
1387
1608
|
/** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */
|
|
1388
1609
|
checkVersion(now) {
|
|
1389
1610
|
return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now);
|
|
@@ -1407,23 +1628,22 @@ var HavenClient = class {
|
|
|
1407
1628
|
};
|
|
1408
1629
|
const job = (async () => {
|
|
1409
1630
|
try {
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
}
|
|
1631
|
+
const got = await this.askRetrying(path, last?.etag, isExpected, retry, {
|
|
1632
|
+
allowed: () => !last && !this.cache.stale(cacheKey),
|
|
1633
|
+
resume: () => {
|
|
1634
|
+
const meanwhile = this.cache.stale(cacheKey);
|
|
1635
|
+
if (meanwhile) return { value: meanwhile.value };
|
|
1636
|
+
const slot = this.inflight.get(cacheKey);
|
|
1637
|
+
if (slot && !registered()) return { value: slot.job };
|
|
1638
|
+
ticket = ++this.state.ticket;
|
|
1639
|
+
if (slot) slot.ticket = ticket;
|
|
1640
|
+
else register();
|
|
1641
|
+
version = this.versionTracker.current() ?? void 0;
|
|
1642
|
+
return void 0;
|
|
1643
|
+
}
|
|
1644
|
+
});
|
|
1645
|
+
if ("value" in got) return got.value;
|
|
1646
|
+
const res = got.answer;
|
|
1427
1647
|
if (res.notModified && last) {
|
|
1428
1648
|
if (this.storable(cacheKey, ticket)) {
|
|
1429
1649
|
this.cache.confirm(cacheKey, version, Date.now());
|
|
@@ -1452,6 +1672,102 @@ var HavenClient = class {
|
|
|
1452
1672
|
this.inflight.set(cacheKey, { job, ticket });
|
|
1453
1673
|
return job;
|
|
1454
1674
|
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Sends a read's request, and sends it again where the failure says that
|
|
1677
|
+
* may help (`retryPause`) and `hooks.allowed()` says the read has nothing to
|
|
1678
|
+
* serve instead; such a read is also held back while its key is rate
|
|
1679
|
+
* limited (`holdBack`). Every other failure is thrown as it is.
|
|
1680
|
+
*
|
|
1681
|
+
* The one retry loop of the read path, for the cached read (`refresh`) and
|
|
1682
|
+
* the bypass alike, so the waits are the same for both. What differs sits in
|
|
1683
|
+
* the hooks: `resume` runs after each wait, just before the next try, and
|
|
1684
|
+
* either ends the read without one (`{ value }`: what another request stored
|
|
1685
|
+
* meanwhile, a newer refresh to join) or takes the ticket and stamp the
|
|
1686
|
+
* next try leaves with and returns `undefined`.
|
|
1687
|
+
*
|
|
1688
|
+
* A next try only ever happens with nothing cached, so it never has an etag
|
|
1689
|
+
* to send: `etag` is the first try's.
|
|
1690
|
+
*/
|
|
1691
|
+
async askRetrying(path, etag, isExpected, gateway, hooks) {
|
|
1692
|
+
const read = { started: Date.now(), gateway, rateLimited: 0, heldUntil: 0, spread: false };
|
|
1693
|
+
let ifNoneMatch = etag;
|
|
1694
|
+
for (; ; ) {
|
|
1695
|
+
if (await this.holdBack(read, hooks.allowed())) {
|
|
1696
|
+
const early = hooks.resume();
|
|
1697
|
+
if (early) return early;
|
|
1698
|
+
ifNoneMatch = void 0;
|
|
1699
|
+
continue;
|
|
1700
|
+
}
|
|
1701
|
+
try {
|
|
1702
|
+
return { answer: await this.conditionalGet(path, ifNoneMatch, isExpected) };
|
|
1703
|
+
} catch (err) {
|
|
1704
|
+
const asked = rateLimitPause(err);
|
|
1705
|
+
if (asked !== void 0 && err instanceof NordhavnError && isStudioAnswer(err)) shutGate(this.identity, asked);
|
|
1706
|
+
const pause = hooks.allowed() ? this.retryPause(err, read) : void 0;
|
|
1707
|
+
if (pause === void 0) throw err;
|
|
1708
|
+
ifNoneMatch = void 0;
|
|
1709
|
+
if (pause === "hold") continue;
|
|
1710
|
+
await sleep(pause);
|
|
1711
|
+
const early = hooks.resume();
|
|
1712
|
+
if (early) return early;
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1717
|
+
* Whether, and how, a failed read with nothing cached is sent again;
|
|
1718
|
+
* counts what it allows in `read`.
|
|
1719
|
+
*
|
|
1720
|
+
* - A `502` or `503` is often one bad moment (a proxy switching to a new
|
|
1721
|
+
* studio container): once, `gatewayRetry` later plus up to as much at
|
|
1722
|
+
* random. Not when it carried `Retry-After`: that one asked to wait.
|
|
1723
|
+
* - A `429` with `Retry-After`: `'hold'`, so `holdBack` waits as asked, at
|
|
1724
|
+
* most `MAX_RATE_LIMIT_RETRIES` times, and only when that wait ends
|
|
1725
|
+
* within `rateLimitWait` of the read's start. Without `Retry-After`
|
|
1726
|
+
* nothing says when it would help: thrown.
|
|
1727
|
+
*/
|
|
1728
|
+
retryPause(err, read) {
|
|
1729
|
+
if (read.gateway && this.gatewayRetry !== void 0 && isGatewayHiccup(err)) {
|
|
1730
|
+
read.gateway = false;
|
|
1731
|
+
return this.gatewayRetry + Math.random() * this.gatewayRetry;
|
|
1732
|
+
}
|
|
1733
|
+
const asked = rateLimitPause(err);
|
|
1734
|
+
if (asked === void 0 || this.rateLimitWait === void 0 || read.rateLimited >= MAX_RATE_LIMIT_RETRIES) return void 0;
|
|
1735
|
+
const now = Date.now();
|
|
1736
|
+
if (now + asked - read.started > this.rateLimitWait) return void 0;
|
|
1737
|
+
read.rateLimited++;
|
|
1738
|
+
read.heldUntil = now + asked;
|
|
1739
|
+
read.spread = true;
|
|
1740
|
+
return "hold";
|
|
1741
|
+
}
|
|
1742
|
+
/**
|
|
1743
|
+
* Keeps a read from going out while its key is rate limited: until its own
|
|
1744
|
+
* `429` said, or the studio's own `429` to any read of this server and key
|
|
1745
|
+
* in the process (`gateRemaining`, at most a minute). Resolves `true` after
|
|
1746
|
+
* waiting, `false` to go now.
|
|
1747
|
+
*
|
|
1748
|
+
* A read with nothing cached (`uncached`) waits for the gate, plus a random
|
|
1749
|
+
* spread (`spreadOf`, also after a `Retry-After: 0`), when that wait ends
|
|
1750
|
+
* within `rateLimitWait` of the read's start. Otherwise (a read with a value
|
|
1751
|
+
* cached, a wait that does not fit, `rateLimitWait: false`) the request is
|
|
1752
|
+
* not sent: the studio already said this key must wait, so it would be
|
|
1753
|
+
* refused, and count against the key's limit as well. It fails as that
|
|
1754
|
+
* refusal would (`heldBackError`), so a cached value is served in its place
|
|
1755
|
+
* and a read with nothing cached throws, without a request.
|
|
1756
|
+
*/
|
|
1757
|
+
async holdBack(read, uncached) {
|
|
1758
|
+
const now = Date.now();
|
|
1759
|
+
const gateLeft = gateRemaining(this.identity);
|
|
1760
|
+
const gate = gateLeft > 0 ? now + gateLeft : 0;
|
|
1761
|
+
const until = uncached ? Math.max(gate, read.heldUntil) : gate;
|
|
1762
|
+
if (until <= now && !read.spread) return false;
|
|
1763
|
+
if (!uncached || this.rateLimitWait === void 0 || until - read.started > this.rateLimitWait) {
|
|
1764
|
+
throw heldBackError(until - now);
|
|
1765
|
+
}
|
|
1766
|
+
read.spread = false;
|
|
1767
|
+
const wait = Math.max(0, until - now);
|
|
1768
|
+
await sleep(wait + spreadOf(wait));
|
|
1769
|
+
return true;
|
|
1770
|
+
}
|
|
1455
1771
|
/**
|
|
1456
1772
|
* Hands an absorbed failure to `onError`, or without one warns once per
|
|
1457
1773
|
* outage. Never throws and never leaves a rejection behind: a broken hook
|
|
@@ -1470,7 +1786,7 @@ var HavenClient = class {
|
|
|
1470
1786
|
} else if (first) {
|
|
1471
1787
|
const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
|
|
1472
1788
|
const what = failure.during === "read" ? `could not refresh "${failure.key}"` : "stamp check failed";
|
|
1473
|
-
|
|
1789
|
+
logLine(this.log, "warn", `${what} (${reason}); cached content keeps being served.`);
|
|
1474
1790
|
}
|
|
1475
1791
|
} catch {
|
|
1476
1792
|
}
|
|
@@ -1532,7 +1848,7 @@ var HavenClient = class {
|
|
|
1532
1848
|
return await res.json();
|
|
1533
1849
|
});
|
|
1534
1850
|
}
|
|
1535
|
-
/** Parse a non-2xx response into a `
|
|
1851
|
+
/** Parse a non-2xx response into a `NordhavnError`, preferring its message. */
|
|
1536
1852
|
async toError(res) {
|
|
1537
1853
|
let message = res.statusText || `Request failed with status ${res.status}`;
|
|
1538
1854
|
let parsed;
|
|
@@ -1543,8 +1859,8 @@ var HavenClient = class {
|
|
|
1543
1859
|
else if (typeof m?.statusMessage === "string") message = m.statusMessage;
|
|
1544
1860
|
} catch {
|
|
1545
1861
|
}
|
|
1546
|
-
const err = new
|
|
1547
|
-
if (res.headers.has("retry-after")) askedToWait.
|
|
1862
|
+
const err = new NordhavnError(message, res.status, parsed);
|
|
1863
|
+
if (res.headers.has("retry-after")) askedToWait.set(err, parseRetryAfter(res.headers.get("retry-after"), Date.now()));
|
|
1548
1864
|
return err;
|
|
1549
1865
|
}
|
|
1550
1866
|
};
|
|
@@ -1566,7 +1882,7 @@ var DatasetHandle = class {
|
|
|
1566
1882
|
update(recordUid, data) {
|
|
1567
1883
|
return this.client.updateRecord(this.nodeSlug, this.datasetSlug, recordUid, data);
|
|
1568
1884
|
}
|
|
1569
|
-
/** Upload a file for one of this dataset's file fields; see `
|
|
1885
|
+
/** Upload a file for one of this dataset's file fields; see `NordhavnClient.uploadFile`. */
|
|
1570
1886
|
uploadFile(fieldSlug, file, opts) {
|
|
1571
1887
|
return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts);
|
|
1572
1888
|
}
|
|
@@ -1597,9 +1913,13 @@ function normalizeTimeout(value) {
|
|
|
1597
1913
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
|
|
1598
1914
|
return value > MAX_TIMER ? 0 : value;
|
|
1599
1915
|
}
|
|
1600
|
-
function
|
|
1916
|
+
function normalizeWriteTimeout(timeout, value) {
|
|
1917
|
+
if (typeof value === "number" && !Number.isNaN(value) && value >= 0) return normalizeTimeout(value);
|
|
1918
|
+
return timeout === 0 ? 0 : Math.max(timeout, MIN_WRITE_TIMEOUT);
|
|
1919
|
+
}
|
|
1920
|
+
function uploadTimeout(writeTimeout, perCall) {
|
|
1601
1921
|
if (typeof perCall === "number" && perCall >= 0) return normalizeTimeout(perCall);
|
|
1602
|
-
return
|
|
1922
|
+
return writeTimeout === 0 ? 0 : Math.max(writeTimeout, MIN_UPLOAD_TIMEOUT);
|
|
1603
1923
|
}
|
|
1604
1924
|
function withoutContentType(headers) {
|
|
1605
1925
|
return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-type"));
|
|
@@ -1609,6 +1929,11 @@ function normalizeGatewayRetry(value) {
|
|
|
1609
1929
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
|
|
1610
1930
|
return Math.min(value, MAX_GATEWAY_RETRY);
|
|
1611
1931
|
}
|
|
1932
|
+
function normalizeRateLimitWait(value) {
|
|
1933
|
+
if (value === false) return void 0;
|
|
1934
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_RATE_LIMIT_WAIT;
|
|
1935
|
+
return Math.min(value, MAX_TIMER);
|
|
1936
|
+
}
|
|
1612
1937
|
function normalizeWait(value) {
|
|
1613
1938
|
if (value === false) return Infinity;
|
|
1614
1939
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH;
|
|
@@ -1648,24 +1973,34 @@ function unexpectedBody(url) {
|
|
|
1648
1973
|
function isTransientStatus(status) {
|
|
1649
1974
|
return status >= 500 || status === 408 || status === 429;
|
|
1650
1975
|
}
|
|
1651
|
-
var askedToWait = /* @__PURE__ */ new
|
|
1976
|
+
var askedToWait = /* @__PURE__ */ new WeakMap();
|
|
1977
|
+
function heldBackError(waitMs) {
|
|
1978
|
+
const seconds = Math.max(1, Math.ceil(waitMs / 1e3));
|
|
1979
|
+
const message = `Too many requests: this key is rate limited for ${seconds} s more, so the request was not sent`;
|
|
1980
|
+
const err = new NordhavnError(message, 429, { statusCode: 429, statusMessage: "Too Many Requests", message });
|
|
1981
|
+
askedToWait.set(err, Math.max(0, waitMs));
|
|
1982
|
+
return err;
|
|
1983
|
+
}
|
|
1984
|
+
function rateLimitPause(err) {
|
|
1985
|
+
return err instanceof NordhavnError && err.status === 429 ? askedToWait.get(err) : void 0;
|
|
1986
|
+
}
|
|
1652
1987
|
function isGatewayHiccup(err) {
|
|
1653
|
-
return err instanceof
|
|
1988
|
+
return err instanceof NordhavnError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
|
|
1654
1989
|
}
|
|
1655
1990
|
function sleep(ms) {
|
|
1656
1991
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1657
1992
|
}
|
|
1658
1993
|
function isDefinitive(err) {
|
|
1659
|
-
return err instanceof
|
|
1994
|
+
return err instanceof NordhavnError && !isTransientStatus(err.status) && isStudioAnswer(err);
|
|
1660
1995
|
}
|
|
1661
1996
|
function isStudioAnswer(err) {
|
|
1662
1997
|
return isStudioBody(err.status, err.body);
|
|
1663
1998
|
}
|
|
1664
1999
|
function isMissingRoute(err) {
|
|
1665
|
-
return err instanceof
|
|
2000
|
+
return err instanceof NordhavnError && err.status === 404 && isStudioAnswer(err);
|
|
1666
2001
|
}
|
|
1667
2002
|
function writeMayHaveLanded(err) {
|
|
1668
|
-
return !(err instanceof
|
|
2003
|
+
return !(err instanceof NordhavnError && err.status >= 400 && err.status < 500);
|
|
1669
2004
|
}
|
|
1670
2005
|
function datasetPath(nodeSlug, datasetSlug) {
|
|
1671
2006
|
return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`;
|
|
@@ -1790,9 +2125,11 @@ function parseChartFence(source) {
|
|
|
1790
2125
|
|
|
1791
2126
|
// src/index.ts
|
|
1792
2127
|
function createClient(options) {
|
|
1793
|
-
return new
|
|
2128
|
+
return new NordhavnClient(options);
|
|
1794
2129
|
}
|
|
2130
|
+
var HavenClient = NordhavnClient;
|
|
2131
|
+
var HavenError = NordhavnError;
|
|
1795
2132
|
|
|
1796
|
-
export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, MemoryCacheStore, chartFenceHeight, createClient, isChartFence, parseChartFence };
|
|
2133
|
+
export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, MemoryCacheStore, NordhavnClient, NordhavnError, chartFenceHeight, createClient, isChartFence, parseChartFence };
|
|
1797
2134
|
//# sourceMappingURL=index.js.map
|
|
1798
2135
|
//# sourceMappingURL=index.js.map
|