@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/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as CacheOptions } from './cache-1gURpP7O.js';
2
- export { a as CacheEntry, C as CacheStore, c as ContentCache, M as MemoryCacheStore } from './cache-1gURpP7O.js';
1
+ import { b as CacheOptions } from './cache-DIs1jN1m.js';
2
+ export { a as CacheEntry, C as CacheStore, c as ContentCache, M as MemoryCacheStore } from './cache-DIs1jN1m.js';
3
3
  import { C as ChartData } from './chart-CxtDbYAs.js';
4
4
  export { A as AGGREGATIONS, a as Aggregation, B as BUCKET_MODES, b as BucketMode, c as CHART_AXES, d as CHART_SORTS, e as CHART_TYPES, f as CHART_TYPE_INFO, g as ChartAxis, h as ChartFamily, i as ChartSeriesData, j as ChartSeriesSpec, k as ChartSort, l as ChartSpec, m as ChartType, n as ChartTypeInfo, D as DATE_BUCKET_VALUES, o as DateBucket, P as PALETTE_KEYS, p as PaletteKey, q as chartTypeInfo, r as isBarChart, s as isPartChart } from './chart-CxtDbYAs.js';
5
5
 
@@ -101,8 +101,34 @@ interface UploadedFile {
101
101
  size: number;
102
102
  }
103
103
 
104
- /** Hosted Nordhavn OS platform. Used when no `baseUrl` is provided. */
104
+ /**
105
+ * Where beacon's lines go: the client's `logger` option. Both methods are
106
+ * optional; a missing one drops that level.
107
+ */
108
+ interface Logger {
109
+ info?(...args: unknown[]): void;
110
+ warn?(...args: unknown[]): void;
111
+ }
112
+
113
+ /** The hosted platform. Used when no `baseUrl` is passed or set in the environment. */
105
114
  declare const DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
115
+ /** The `cache` option of a client: `CacheOptions` and the disk cache, which only a client builds. */
116
+ interface ClientCacheOptions extends CacheOptions {
117
+ /**
118
+ * Keep the cache on disk too, in this directory, so a process that restarts
119
+ * while the studio is down still has the last good content (Node 22.3 or
120
+ * later). Put it on a volume that survives a redeploy. An empty string
121
+ * counts as not given, so `dir: process.env.CACHE_DIR` works unset.
122
+ *
123
+ * The entries go in a folder of `dir` named after a short hash of the
124
+ * server and the key (never the key itself), so sites, or a developer's
125
+ * keys, sharing a directory never see each other's content. Folders of
126
+ * beacon's that went unused for 30 days are removed when a client starts;
127
+ * nothing else in `dir` is touched. Not with `store`.
128
+ */
129
+ dir?: string;
130
+ }
131
+
106
132
  /** A studio failure the client absorbed, handed to `onError`. */
107
133
  interface StudioFailure {
108
134
  /**
@@ -112,19 +138,28 @@ interface StudioFailure {
112
138
  during: 'stamp-check' | 'read';
113
139
  /** Cache key of the entry that could not be refreshed. Only for `read`. */
114
140
  key?: string;
115
- /** What went wrong: a `HavenError`, a `TimeoutError`, a network error. */
141
+ /** What went wrong: a `NordhavnError`, a `TimeoutError`, a network error. */
116
142
  error: unknown;
117
143
  }
118
- interface HavenClientOptions {
144
+ interface NordhavnClientOptions {
119
145
  /**
120
146
  * Project API key, `slk_...`. Mint one in the project's settings under
121
147
  * "API keys". Its reach is the union of its per-node read/write scopes.
148
+ *
149
+ * Left out of the options altogether, it is read from the environment
150
+ * variable `NORDHAVN_API_KEY` (`process.env`, where the runtime has one). A
151
+ * key passed here always wins. Passed without a value (`undefined`, as from
152
+ * an unset variable of the site's own, or an empty string) it throws, as up
153
+ * to 0.7: it never falls back to the environment.
122
154
  */
123
- apiKey: string;
155
+ apiKey?: string;
124
156
  /**
125
- * Base URL of your Nordhavn OS server, without a trailing `/api/content`
126
- * (that path is appended automatically). Defaults to the hosted platform at
127
- * `https://beacon.nordhavn.ai`; override it for a self-hosted instance.
157
+ * Base URL of your server, without a trailing `/api/content` (that path is
158
+ * appended automatically). Left out of the options altogether, it is read
159
+ * from the environment variable `NORDHAVN_BASE_URL`, else it is the hosted
160
+ * platform (`DEFAULT_BASE_URL`). A URL passed here always wins; passed as
161
+ * `undefined` it is the hosted platform, as up to 0.7; an empty string
162
+ * throws.
128
163
  */
129
164
  baseUrl?: string;
130
165
  /**
@@ -134,8 +169,8 @@ interface HavenClientOptions {
134
169
  * locale. Discover available locales with `client.locales()`.
135
170
  */
136
171
  locale?: string;
137
- /** Read caching. Pass `false` to disable, or an options object to tune it. */
138
- cache?: boolean | CacheOptions;
172
+ /** Read caching. Pass `false` to disable, or an options object to tune it (and `dir` to keep it on disk). */
173
+ cache?: boolean | ClientCacheOptions;
139
174
  /** Custom `fetch` implementation. Defaults to the global `fetch`. */
140
175
  fetch?: typeof fetch;
141
176
  /**
@@ -148,10 +183,21 @@ interface HavenClientOptions {
148
183
  * once-a-minute stamp check uses at most 3 seconds of it, as every read in
149
184
  * that moment waits on the check.
150
185
  *
151
- * It covers writes too. A write that times out may still have reached the
152
- * studio, so do not blindly send it again: you could store it twice.
186
+ * Writes and uploads have their own, longer deadline: `writeTimeout`.
153
187
  */
154
188
  timeout?: number;
189
+ /**
190
+ * Give up on a write (`createRecord`, `updateRecord`) after this many ms,
191
+ * body included. Default: `timeout`, but at least `30000`; `0` disables it,
192
+ * as does a client `timeout` of `0` when this is not set. An upload gets
193
+ * this too, but at least 60 s.
194
+ *
195
+ * Longer than a read's on purpose. A read that times out serves its cached
196
+ * value; a write that times out may still have reached the studio, and the
197
+ * visitor sees an error for a form that arrived. Do not blindly send it
198
+ * again: you could store it twice.
199
+ */
200
+ writeTimeout?: number;
155
201
  /**
156
202
  * A read with nothing cached that gets a `502` or `503` tries once more after
157
203
  * this many ms, plus up to as many again at random (so the reads of one page
@@ -163,6 +209,32 @@ interface HavenClientOptions {
163
209
  * a write, or an answer carrying `Retry-After`.
164
210
  */
165
211
  gatewayRetry?: number | false;
212
+ /**
213
+ * How long, in ms from when it began, a read with nothing cached (or a
214
+ * `cache: false` read) may wait for the studio's rate limit. Default
215
+ * `10000`. `false` turns waiting off: a `429` is thrown at once.
216
+ *
217
+ * The studio's own `429` with `Retry-After` shuts a gate for this server
218
+ * and key in the process, until the time it names but at most a minute:
219
+ * reads with nothing cached hold back until then, instead of going out to
220
+ * be refused as well, and the one that was refused is sent again, at most
221
+ * twice. A `429` from something in front of the studio (a proxy's page)
222
+ * shuts no gate; only the read it refused waits. Each adds a random spread to its
223
+ * wait (up to a fifth of it, at least up to 1 s), so they do not come back
224
+ * together. A wait that would end more than `rateLimitWait` after the read
225
+ * began is not started; the random spread may take a read a little past it.
226
+ * While the gate is shut nothing is sent that would only be refused: a
227
+ * read that cannot wait for it (or has a value cached, or with `false`)
228
+ * fails as a `429` would, without a request: a cached value is served,
229
+ * else that `429` is thrown.
230
+ *
231
+ * The studio limits the requests per key and asks to wait a few seconds at
232
+ * most; with nothing to show instead, waiting is better than an error. A
233
+ * build that reads everything at once may want more. Never for a read with
234
+ * a value cached (that value is served), a write, an upload, or a `429`
235
+ * without `Retry-After`.
236
+ */
237
+ rateLimitWait?: number | false;
166
238
  /**
167
239
  * Called for every studio failure the client absorbs: a failed stamp check,
168
240
  * or a read answered from the cache because its refresh failed. These never
@@ -171,8 +243,8 @@ interface HavenClientOptions {
171
243
  * (a read with nothing cached, a write) are not repeated here.
172
244
  *
173
245
  * At most one call per stamp check and one per cache entry per retry pause,
174
- * so it is safe to log or alert from. Without it the client logs one
175
- * `console.warn` per outage.
246
+ * so it is safe to log or alert from. Without it the client writes one
247
+ * warning per outage to `logger`.
176
248
  */
177
249
  onError?: (failure: StudioFailure) => void;
178
250
  /** Extra headers merged into every request. */
@@ -194,6 +266,18 @@ interface HavenClientOptions {
194
266
  * by every client with those.
195
267
  */
196
268
  live?: boolean;
269
+ /**
270
+ * Where beacon writes its lines. Default: the console. `false` writes
271
+ * nothing at all. Every line goes here: once per process what a file cache
272
+ * found on disk; in development (`NODE_ENV` is `development`, not in CI)
273
+ * which project and key the client reads with, `connected to "<project>"
274
+ * (key "<key>")`; and the warnings: an outage (unless `onError` is set), a
275
+ * disk the cache cannot use (unless the `FileCacheStore` has its own
276
+ * `onError`), a store shared by two keys, a Node too old for `cache.dir`.
277
+ * Each line is one string, prefixed `[@nordhavnhq/beacon]`, sometimes with
278
+ * the error's message as a second argument.
279
+ */
280
+ logger?: Logger | false;
197
281
  }
198
282
  /** Per-call read options. */
199
283
  interface ReadOptions {
@@ -219,9 +303,10 @@ interface UploadOptions {
219
303
  filename?: string;
220
304
  /**
221
305
  * Give up after this many ms, body included. Defaults to the client's
222
- * `timeout`, but at least 60 s (an upload may be 10 MB); `0` for none. A
223
- * client created with `timeout: 0` uploads without one too. A negative
224
- * number or `NaN` counts as not given.
306
+ * `writeTimeout`, but at least 60 s (an upload may be 10 MB); `0` for none.
307
+ * A client whose writes have no timeout (`writeTimeout: 0`, or `timeout: 0`
308
+ * without one) uploads without one too. A negative number or `NaN` counts
309
+ * as not given.
225
310
  */
226
311
  timeout?: number;
227
312
  }
@@ -231,11 +316,14 @@ interface UploadOptions {
231
316
  * writes invalidate the affected cache entries automatically.
232
317
  *
233
318
  * ```ts
234
- * const studio = new HavenClient({ apiKey: 'slk_...', baseUrl: 'https://studio.example.com' })
319
+ * const studio = new NordhavnClient({ apiKey: 'slk_...', baseUrl: 'https://studio.example.com' })
235
320
  * const posts = await studio.dataset<Post>('blog', 'posts').list()
236
321
  * ```
322
+ *
323
+ * With `NORDHAVN_API_KEY` (and for a self-hosted studio `NORDHAVN_BASE_URL`)
324
+ * in the environment, `new NordhavnClient()` is enough.
237
325
  */
238
- declare class HavenClient {
326
+ declare class NordhavnClient {
239
327
  private readonly apiKey;
240
328
  private readonly baseUrl;
241
329
  private readonly fetchImpl;
@@ -248,10 +336,18 @@ declare class HavenClient {
248
336
  private readonly locale?;
249
337
  /** Request timeout in ms, `0` for none. */
250
338
  private readonly timeout;
339
+ /** `writeTimeout` in ms, `0` for none. */
340
+ private readonly writeTimeout;
251
341
  /** `cache.waitForFresh` in ms, `Infinity` to wait for the studio. */
252
342
  private readonly waitForFresh;
253
343
  /** `gatewayRetry` in ms, `undefined` when it is off. */
254
344
  private readonly gatewayRetry;
345
+ /** `rateLimitWait` in ms, `undefined` when it is off. */
346
+ private readonly rateLimitWait;
347
+ /** Who this client is to the studio (`identityOf`): what the rate gate is kept per. Holds the key. */
348
+ private readonly identity;
349
+ /** The `logger` option, `undefined` for `false`. */
350
+ private readonly log;
255
351
  /**
256
352
  * The refresh under way per cache key, so concurrent reads of one key share
257
353
  * one request, with the ticket it left on (see `state.ticket`).
@@ -268,7 +364,7 @@ declare class HavenClient {
268
364
  * its own.
269
365
  */
270
366
  private readonly state;
271
- constructor(options: HavenClientOptions);
367
+ constructor(options?: NordhavnClientOptions);
272
368
  /**
273
369
  * Lets go of the live connection: the last client of a server and key to
274
370
  * close it closes the connection. The client keeps working, on the stamp
@@ -354,7 +450,7 @@ declare class HavenClient {
354
450
  * The field decides what it takes: its `mimes` and `max_size` rules, within
355
451
  * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
356
452
  * studio reads the type from the content, so a renamed file is refused. Only
357
- * top-level fields. A file of the wrong type or size throws `HavenError` 400
453
+ * top-level fields. A file of the wrong type or size throws `NordhavnError` 400
358
454
  * with a message fit to show; other refusals (400, 403, 404) are setup
359
455
  * errors. More than 10 uploads a minute per key throws 429. From a Node
360
456
  * `Buffer`, send `new Blob([buffer])` with a `filename`.
@@ -473,6 +569,8 @@ declare class HavenClient {
473
569
  * 5. One request per key at a time (`refresh`).
474
570
  */
475
571
  private cachedGet;
572
+ /** On the first read, in development: which project this key reads (`announceProject`). */
573
+ private announceOnce;
476
574
  /** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */
477
575
  private checkVersion;
478
576
  /**
@@ -485,6 +583,52 @@ declare class HavenClient {
485
583
  * nothing cached to serve in its place.
486
584
  */
487
585
  private refresh;
586
+ /**
587
+ * Sends a read's request, and sends it again where the failure says that
588
+ * may help (`retryPause`) and `hooks.allowed()` says the read has nothing to
589
+ * serve instead; such a read is also held back while its key is rate
590
+ * limited (`holdBack`). Every other failure is thrown as it is.
591
+ *
592
+ * The one retry loop of the read path, for the cached read (`refresh`) and
593
+ * the bypass alike, so the waits are the same for both. What differs sits in
594
+ * the hooks: `resume` runs after each wait, just before the next try, and
595
+ * either ends the read without one (`{ value }`: what another request stored
596
+ * meanwhile, a newer refresh to join) or takes the ticket and stamp the
597
+ * next try leaves with and returns `undefined`.
598
+ *
599
+ * A next try only ever happens with nothing cached, so it never has an etag
600
+ * to send: `etag` is the first try's.
601
+ */
602
+ private askRetrying;
603
+ /**
604
+ * Whether, and how, a failed read with nothing cached is sent again;
605
+ * counts what it allows in `read`.
606
+ *
607
+ * - A `502` or `503` is often one bad moment (a proxy switching to a new
608
+ * studio container): once, `gatewayRetry` later plus up to as much at
609
+ * random. Not when it carried `Retry-After`: that one asked to wait.
610
+ * - A `429` with `Retry-After`: `'hold'`, so `holdBack` waits as asked, at
611
+ * most `MAX_RATE_LIMIT_RETRIES` times, and only when that wait ends
612
+ * within `rateLimitWait` of the read's start. Without `Retry-After`
613
+ * nothing says when it would help: thrown.
614
+ */
615
+ private retryPause;
616
+ /**
617
+ * Keeps a read from going out while its key is rate limited: until its own
618
+ * `429` said, or the studio's own `429` to any read of this server and key
619
+ * in the process (`gateRemaining`, at most a minute). Resolves `true` after
620
+ * waiting, `false` to go now.
621
+ *
622
+ * A read with nothing cached (`uncached`) waits for the gate, plus a random
623
+ * spread (`spreadOf`, also after a `Retry-After: 0`), when that wait ends
624
+ * within `rateLimitWait` of the read's start. Otherwise (a read with a value
625
+ * cached, a wait that does not fit, `rateLimitWait: false`) the request is
626
+ * not sent: the studio already said this key must wait, so it would be
627
+ * refused, and count against the key's limit as well. It fails as that
628
+ * refusal would (`heldBackError`), so a cached value is served in its place
629
+ * and a read with nothing cached throws, without a request.
630
+ */
631
+ private holdBack;
488
632
  /**
489
633
  * Hands an absorbed failure to `onError`, or without one warns once per
490
634
  * outage. Never throws and never leaves a rejection behind: a broken hook
@@ -509,7 +653,7 @@ declare class HavenClient {
509
653
  */
510
654
  private conditionalGet;
511
655
  private request;
512
- /** Parse a non-2xx response into a `HavenError`, preferring its message. */
656
+ /** Parse a non-2xx response into a `NordhavnError`, preferring its message. */
513
657
  private toError;
514
658
  }
515
659
  /** Fluent, dataset-scoped view returned by `client.dataset()`. */
@@ -517,12 +661,12 @@ declare class DatasetHandle<T = Record<string, unknown>> {
517
661
  private readonly client;
518
662
  private readonly nodeSlug;
519
663
  private readonly datasetSlug;
520
- constructor(client: HavenClient, nodeSlug: string, datasetSlug: string);
664
+ constructor(client: NordhavnClient, nodeSlug: string, datasetSlug: string);
521
665
  list(opts?: ReadOptions): Promise<ContentRecord<T>[]>;
522
666
  get(recordUid: string, opts?: ReadOptions): Promise<ContentRecord<T>>;
523
667
  create(data: Record<string, unknown>): Promise<ContentRecord<T>>;
524
668
  update(recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>>;
525
- /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */
669
+ /** Upload a file for one of this dataset's file fields; see `NordhavnClient.uploadFile`. */
526
670
  uploadFile(fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile>;
527
671
  /** Clear cached reads for this dataset. */
528
672
  clearCache(): void;
@@ -535,7 +679,7 @@ declare class DatasetHandle<T = Record<string, unknown>> {
535
679
  * the studio sends one: why an upload was refused, for example
536
680
  * (`upload_too_large`).
537
681
  */
538
- declare class HavenError extends Error {
682
+ declare class NordhavnError extends Error {
539
683
  readonly status: number;
540
684
  /** The raw parsed response body, when the server returned one. */
541
685
  readonly body: unknown;
@@ -751,8 +895,22 @@ interface ForecastSeries {
751
895
  unit?: string;
752
896
  }
753
897
 
754
- /** Convenience factory: `createClient({ apiKey, baseUrl })`. */
755
- declare function createClient(options: HavenClientOptions): HavenClient;
898
+ /**
899
+ * Convenience factory: `createClient({ apiKey, baseUrl })`. Both fall back to
900
+ * the environment (`NORDHAVN_API_KEY`, `NORDHAVN_BASE_URL`), so on a server
901
+ * with those set `createClient()` is enough.
902
+ */
903
+ declare function createClient(options?: NordhavnClientOptions): NordhavnClient;
904
+ /** @deprecated Renamed in 0.8.0: use `NordhavnClient`. */
905
+ declare const HavenClient: typeof NordhavnClient;
906
+ /** @deprecated Renamed in 0.8.0: use `NordhavnClient`. */
907
+ type HavenClient = NordhavnClient;
908
+ /** @deprecated Renamed in 0.8.0: use `NordhavnClientOptions`. */
909
+ type HavenClientOptions = NordhavnClientOptions;
910
+ /** @deprecated Renamed in 0.8.0: use `NordhavnError`. */
911
+ declare const HavenError: typeof NordhavnError;
912
+ /** @deprecated Renamed in 0.8.0: use `NordhavnError`. */
913
+ type HavenError = NordhavnError;
756
914
 
757
- export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, CacheOptions, ChartData, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, chartFenceHeight, createClient, isChartFence, parseChartFence };
758
- export type { ChartFence, ChartFenceResult, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode, StudioFailure, UploadOptions, UploadedFile };
915
+ export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, CacheOptions, ChartData, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, NordhavnClient, NordhavnError, chartFenceHeight, createClient, isChartFence, parseChartFence };
916
+ export type { ChartFence, ChartFenceResult, ClientCacheOptions, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, Logger, NordhavnClientOptions, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode, StudioFailure, UploadOptions, UploadedFile };