@nordhavnhq/beacon 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cache.ts","../src/errors.ts","../src/version.ts","../src/client.ts","../src/chart.ts","../src/chart-fence.ts","../src/index.ts"],"names":["version"],"mappings":";;;AAiGA,IAAM,OAAA,GAAU,CAAA;AAGT,IAAM,mBAAN,MAA6C;AAAA,EAGlD,WAAA,CAAoB,aAAa,GAAA,EAAK;AAAlB,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAFpB,IAAA,IAAA,CAAQ,GAAA,uBAAU,GAAA,EAAwB;AAAA,EAEH;AAAA,EAEvC,IAAI,GAAA,EAAqC;AACvC,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA;AAAA,EACzB;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAAyB;AAExC,IAAA,IAAA,CAAK,GAAA,CAAI,OAAO,GAAG,CAAA;AACnB,IAAA,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACvB,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,GAAO,IAAA,CAAK,UAAA,EAAY;AACtC,MAAA,MAAM,SAAS,IAAA,CAAK,GAAA,CAAI,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACtC,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,IAAA,CAAK,GAAA,CAAI,OAAO,MAAM,CAAA;AAAA,IACxB;AAAA,EACF;AAAA,EAEA,OAAO,GAAA,EAAmB;AACxB,IAAA,IAAA,CAAK,GAAA,CAAI,OAAO,GAAG,CAAA;AAAA,EACrB;AAAA,EAEA,IAAA,GAAyB;AACvB,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,EAAK;AAAA,EACvB;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAA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AM,IAAI,CAAA;AAAA,EACvB,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,gBAAA,EAAmB,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA,EAAG;AAAA,EACnG;AACA,EAAA,IAAI;AACF,IAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,KAAA,EAAO,UAAA,CAAW,GAAG,CAAA,EAAE;AAAA,EAC5C,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,EAC9E;AACF;;;AC/DO,SAAS,aAAa,OAAA,EAA0C;AACrE,EAAA,OAAO,IAAI,YAAY,OAAO,CAAA;AAChC","file":"index.cjs","sourcesContent":["/**\n * Read caching for the content client. GET responses (schema, record lists,\n * single records, queries) are cached by request key and kept fresh by\n * conditional revalidation: each entry stores the studio's `ETag`, which the\n * client sends back as `If-None-Match`. A cheap project-wide stamp gates whether\n * a revalidation is even attempted, so a stable site serves straight from cache.\n *\n * Swap in a custom `CacheStore` to share a cache across client instances or to\n * back it with something persistent.\n */\n\nexport interface CacheEntry {\n value: unknown\n /**\n * The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`\n * to revalidate: a `304` means the stored value is still current.\n */\n etag?: string\n /**\n * The project stamp this entry was last confirmed current against. When it\n * equals the client's latest known stamp, the entry is served without any\n * network call at all.\n */\n validatedVersion?: string\n /** Epoch ms when the entry expires. `0` means it never expires. */\n expiresAt: number\n /**\n * Epoch ms before which a failed refetch is not retried: until then the entry\n * is served as-is. Set after a transient error, cleared by a fresh value or a\n * `304`.\n */\n retryAt?: number\n}\n\n/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */\nexport interface CacheStore {\n get(key: string): CacheEntry | undefined\n set(key: string, entry: CacheEntry): void\n delete(key: string): void\n /** Iterate current keys (used for prefix invalidation). */\n keys(): Iterable<string>\n clear(): void\n}\n\nexport interface CacheOptions {\n /** Master switch. Default `true`. */\n enabled?: boolean\n /**\n * How long a cached entry survives, in ms. Default `604800000` (7 days).\n *\n * This is NOT how long until content refreshes - revalidation keeps entries\n * current within `revalidate` (seconds) whenever the studio is reachable. The\n * TTL only decides when an entry stops being served blindly and the next read\n * must refetch it. If that refetch fails transiently (studio down, 5xx,\n * network), the expired value is served anyway, so a studio outage degrades\n * to \"slightly stale\" rather than \"site errors\" however long it lasts.\n *\n * The one case where it bounds staleness directly is when revalidation is off\n * (`revalidate: false`) or the server has no `/version` endpoint: then content\n * can be up to `ttl` old while the studio is reachable. `0` = never expire.\n */\n ttl?: number\n /**\n * Minimum ms between two project-stamp checks. Default `60000` (1 minute) -\n * this is the freshness window for PUBLIC visitors (an edit is picked up on\n * the next check after it lands); an editor viewing a surface preview bypasses\n * the cache entirely and always sees changes instantly.\n *\n * The check fires only on a read and is throttled, so a quiet site barely\n * checks at all; the interval only caps the busy case. Each check costs the\n * studio a small API-key lookup, so raise it (a few minutes) if you run many\n * frontends; lower it for a tighter public window. `false` disables checking\n * and leaves you with pure TTL expiry.\n */\n revalidate?: number | false\n /**\n * How long a read that already holds a cached value waits on the studio for a\n * fresher one, in ms. Default `1000`. Past it the read gets the cached value\n * and the refresh finishes in the background, so the next read has it.\n *\n * It keeps a slow or hanging studio from slowing your pages down: without it\n * every read after an edit waits for as long as the studio takes, up to\n * `timeout`. The price is that on a slow studio an edit shows one read later.\n *\n * `0` never waits (always serve the cached value, refresh in the background).\n * `false` waits for the studio; choose it where work cannot outlive the\n * request, as on serverless platforms that freeze the process once the\n * response is out. A read with nothing cached always waits.\n */\n waitForFresh?: number | false\n /** Soft cap on entries; oldest are evicted first. Default `500`. */\n maxEntries?: number\n /** Custom backing store. Defaults to an in-memory store. */\n store?: CacheStore\n}\n\n/** An `expiresAt` that is always in the past (`0` would mean \"never expires\"). */\nconst EXPIRED = 1\n\n/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */\nexport class MemoryCacheStore implements CacheStore {\n private map = new Map<string, CacheEntry>()\n\n constructor(private maxEntries = 500) {}\n\n get(key: string): CacheEntry | undefined {\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n // Re-insert so recently written keys are considered newest.\n this.map.delete(key)\n this.map.set(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.map.delete(oldest)\n }\n }\n\n delete(key: string): void {\n this.map.delete(key)\n }\n\n keys(): Iterable<string> {\n return this.map.keys()\n }\n\n clear(): void {\n this.map.clear()\n }\n}\n\n/**\n * Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation\n * bookkeeping (etag + validated stamp), and prefix invalidation, so the client\n * only deals in cache keys.\n */\nexport class ContentCache {\n readonly enabled: boolean\n private ttl: number\n /** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */\n private retryDelay: number\n private store: CacheStore\n\n constructor(opts: CacheOptions = {}) {\n this.enabled = opts.enabled ?? true\n this.ttl = opts.ttl ?? 604_800_000\n this.retryDelay = typeof opts.revalidate === 'number' && opts.revalidate > 0 ? opts.revalidate : 60_000\n this.store = opts.store ?? new MemoryCacheStore(opts.maxEntries ?? 500)\n }\n\n /**\n * The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the\n * whole entry (value + etag + validated stamp) so the client can decide\n * whether to serve it, revalidate it, or fall back to it on error.\n *\n * An expired entry is left in the store (the refetch overwrites it, or\n * `maxEntries` evicts it) so `stale` can still fall back to it.\n */\n peek(key: string, now: number): CacheEntry | undefined {\n const entry = this.stale(key)\n if (!entry) return undefined\n if (entry.expiresAt !== 0 && entry.expiresAt <= now) return undefined\n return entry\n }\n\n /**\n * The entry for `key` whether or not its TTL has run out: the last good value\n * to serve when a refetch fails transiently.\n */\n stale(key: string): CacheEntry | undefined {\n if (!this.enabled) return undefined\n return this.store.get(key)\n }\n\n /** Store a freshly fetched value with its validator and the stamp it is current against. */\n set(key: string, value: unknown, opts: { etag?: string, version?: string }, now: number): void {\n if (!this.enabled) return\n this.store.set(key, {\n value,\n etag: opts.etag,\n validatedVersion: opts.version,\n expiresAt: this.ttl === 0 ? 0 : now + this.ttl,\n })\n }\n\n /**\n * Record that an existing entry is still current as of `version` (after a\n * `304`), refreshing its TTL without touching the value. No-op if it is gone.\n */\n confirm(key: string, version: string | undefined, now: number): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.validatedVersion = version\n entry.expiresAt = this.ttl === 0 ? 0 : now + this.ttl\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /**\n * Record that refetching `key` from `from` just failed transiently, so reads\n * serve it as-is for a while instead of each waiting on an unreachable studio.\n * Returns the entry to serve: `from`, or the newer one a concurrent read stored\n * in the meantime (left unpaused, since its own fetch succeeded).\n */\n backoff(key: string, from: CacheEntry, now: number): CacheEntry {\n const entry = this.store.get(key)\n if (!entry) return from\n // Compare fields, not identity: a custom store may hand back copies.\n if (entry.etag !== from.etag || entry.expiresAt !== from.expiresAt) return entry\n entry.retryAt = now + this.retryDelay\n this.store.set(key, entry)\n return entry\n }\n\n /**\n * Mark `key` as due for a refetch while keeping its value to fall back on:\n * the next read asks the studio again whatever the stamp says, and still\n * serves this value if the studio does not answer. For when the stored value\n * may be outdated but there is no telling - dropping it would throw away the\n * only thing left to show during an outage. No-op for a key that is not held.\n */\n expire(key: string): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.expiresAt = EXPIRED\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /** `expire` for every key that starts with `prefix`. */\n expirePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.expire(key)\n }\n }\n\n /** Drop one exact key. */\n delete(key: string): void {\n this.store.delete(key)\n }\n\n /** Drop every key that starts with `prefix`. */\n deletePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.store.delete(key)\n }\n }\n\n clear(): void {\n this.store.clear()\n }\n}\n","/**\n * Error thrown for any non-2xx response from the content API. `status` carries\n * the HTTP status code so callers can branch (401 bad key, 403 out of scope,\n * 404 missing node/dataset/record, 422 query failed).\n */\nexport class HavenError extends Error {\n readonly status: number\n /** The raw parsed response body, when the server returned one. */\n readonly body: unknown\n\n constructor(message: string, status: number, body?: unknown) {\n super(message)\n this.name = 'HavenError'\n this.status = status\n this.body = body\n // Restore prototype chain for `instanceof` when transpiled to ES5.\n Object.setPrototypeOf(this, HavenError.prototype)\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401\n }\n\n get isForbidden(): boolean {\n return this.status === 403\n }\n\n get isNotFound(): boolean {\n return this.status === 404\n }\n}\n","/**\n * Project-stamp tracker: the cheap gate in front of conditional revalidation.\n *\n * The cache lives in YOUR process, so the studio cannot push an invalidation\n * into it. Instead it publishes a stamp per project at `GET /api/content/version`\n * that changes on every content edit. This tracker fetches that stamp at most\n * once per interval (one tiny request regardless of read volume) and exposes the\n * latest value it has seen.\n *\n * The client uses it as a gate: while the stamp is unchanged, cached entries are\n * served with no network at all; when it moves, entries revalidate individually\n * with `If-None-Match` (a `304` keeps the cached value, a `200` replaces it). If\n * the stamp check itself fails - studio down, network blip - the last known\n * stamp stands, so the cache keeps serving instead of hammering a dead endpoint.\n */\n\nexport type VersionProbe = () => Promise<string>\n\n/** How long a server without the version route silences the check. */\nexport const UNSUPPORTED_PAUSE_MS = 15 * 60_000\n\nexport class VersionTracker {\n private lastChecked = 0\n private version: string | null = null\n private inFlight: Promise<void> | null = null\n /**\n * Epoch ms before which we do not ask again, after the server turned out\n * to have no version route. A pause and not a final verdict: an old server\n * costs one request per pause, and one that gains the route is picked up\n * without a restart.\n */\n private pausedUntil = 0\n\n constructor(\n private readonly probe: VersionProbe,\n /** Minimum ms between two probes. `0` disables checking entirely. */\n private readonly interval: number,\n /**\n * Whether a probe failure means \"this server has no version route\", as\n * opposed to \"could not be reached\". The caller decides, as only it can\n * tell the server's own `404` from the one a proxy answers with while\n * the server is away - and that one must not pause anything: the server\n * is back in seconds, and freshness would stay off for the whole pause.\n */\n private readonly isUnsupported: (err: unknown) => boolean = (err) => (err as { status?: number } | null)?.status === 404,\n ) {}\n\n /** The most recent stamp seen, or `null` before the first successful probe. */\n current(): string | null {\n return this.version\n }\n\n /**\n * Refresh the stamp if we are due. Resolves once the answer is in, so the\n * read that triggered it sees an up-to-date stamp. A failed probe leaves the\n * last known stamp in place (serve-from-cache rather than thrash).\n *\n * A failed probe counts towards the interval like any other, also when no\n * stamp has ever come in. Otherwise a process that starts while the studio\n * is down (with a persisted cache to serve from) would probe on every read,\n * and against a hanging studio make each of them wait out the probe.\n */\n async refresh(now: number): Promise<void> {\n if (this.interval <= 0 || now < this.pausedUntil) return\n if (this.inFlight) return this.inFlight\n if (now - this.lastChecked < this.interval) return\n\n this.lastChecked = now\n this.inFlight = this.run(now)\n try {\n await this.inFlight\n }\n finally {\n this.inFlight = null\n }\n }\n\n private async run(now: number): Promise<void> {\n try {\n this.version = await this.probe()\n }\n catch (err) {\n // A server that predates the version route: ask again only after a\n // long pause. Any other failure is transient - keep the last stamp\n // so the cache keeps serving, and try again next interval.\n if (this.isUnsupported(err)) {\n this.pausedUntil = now + Math.max(this.interval, UNSUPPORTED_PAUSE_MS)\n }\n }\n }\n}\n","import { ContentCache, type CacheEntry, type CacheOptions } from './cache'\nimport { HavenError } from './errors'\nimport type { ContentLocale, ContentRecord, ContentSchema, QueryResult, SchemaNode, UploadedFile } from './types'\nimport { VersionTracker } from './version'\n\n/**\n * Query parameter Nordhavn OS appends when it loads your site in a\n * surface preview. Its presence means \"an editor is looking at this right now\",\n * which is exactly when caching must get out of the way - see `forRequest`.\n */\nexport const PREVIEW_PARAM = 'sl-preview'\n\n/** Hosted Nordhavn OS platform. Used when no `baseUrl` is provided. */\nexport const DEFAULT_BASE_URL = 'https://beacon.nordhavn.ai'\n\n/** Default request timeout in ms (`timeout` option). */\nconst DEFAULT_TIMEOUT = 10_000\n/** The least time an upload gets by default: the studio takes up to 10 MB. */\nconst MIN_UPLOAD_TIMEOUT = 60_000\n/** Ceiling for the stamp check, which every concurrent read waits on. */\nconst VERSION_TIMEOUT = 3_000\n/** Default for `cache.waitForFresh`, in ms. */\nconst DEFAULT_WAIT_FOR_FRESH = 1_000\n/** The longest delay a timer holds; beyond it `setTimeout` fires after 1 ms. */\nconst MAX_TIMER = 2_147_483_647\n/** How many keys `storedBy` remembers before it starts over. */\nconst STORED_LIMIT = 5_000\n/** How long a failed read of the project's locales is not repeated. */\nconst LOCALES_RETRY_MS = 60_000\n/** Default for `gatewayRetry`, in ms. */\nconst DEFAULT_GATEWAY_RETRY = 200\n/** The longest `gatewayRetry` honoured; a larger value is cut back to this. */\nconst MAX_GATEWAY_RETRY = 60_000\n\n/** A studio failure the client absorbed, handed to `onError`. */\nexport interface StudioFailure {\n /**\n * What failed: the periodic `stamp-check`, or the `read` that refreshes one\n * cache entry (its cached value was served instead).\n */\n during: 'stamp-check' | 'read'\n /** Cache key of the entry that could not be refreshed. Only for `read`. */\n key?: string\n /** What went wrong: a `HavenError`, a `TimeoutError`, a network error. */\n error: unknown\n}\n\nexport interface HavenClientOptions {\n /**\n * Project API key, `slk_...`. Mint one in the project's settings under\n * \"API keys\". Its reach is the union of its per-node read/write scopes.\n */\n apiKey: string\n /**\n * Base URL of your Nordhavn OS server, without a trailing `/api/content`\n * (that path is appended automatically). Defaults to the hosted platform at\n * `https://beacon.nordhavn.ai`; override it for a self-hosted instance.\n */\n baseUrl?: string\n /**\n * Default locale for reads, e.g. `nl` or `fr-BE`. When set, records are\n * returned in that language, with untranslated fields falling back to the\n * project default. Override per call with `opts.locale`. Omit for the default\n * locale. Discover available locales with `client.locales()`.\n */\n locale?: string\n /** Read caching. Pass `false` to disable, or an options object to tune it. */\n cache?: boolean | CacheOptions\n /** Custom `fetch` implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch\n /**\n * Give up on a request after this many ms, body included. Default `10000`.\n * `0` disables it, as does `Infinity`.\n *\n * Without one, a studio that accepts the connection but never answers holds\n * every read until the runtime gives up (minutes, in Node). A timed-out read\n * counts as transient, like a `5xx`: the last good value is served. The\n * once-a-minute stamp check uses at most 3 seconds of it, as every read in\n * that moment waits on the check.\n *\n * It covers writes too. A write that times out may still have reached the\n * studio, so do not blindly send it again: you could store it twice.\n */\n timeout?: number\n /**\n * A read with nothing cached that gets a `502` or `503` tries once more after\n * this many ms, plus up to as many again at random (so the reads of one page\n * do not all come back at once). Default `200`. `false` turns it off.\n *\n * Often one bad moment, such as a proxy switching to a new studio container;\n * and with nothing cached the error is all the caller would get. Never for a\n * read with a value cached (that value is served), a preview or\n * `cache: false` read, a write, or an answer carrying `Retry-After`.\n */\n gatewayRetry?: number | false\n /**\n * Called for every studio failure the client absorbs: a failed stamp check,\n * or a read answered from the cache because its refresh failed. These never\n * reach your code as an error, so this is the only place to notice that the\n * site is running on cached content. Errors that are thrown to the caller\n * (a read with nothing cached, a write) are not repeated here.\n *\n * At most one call per stamp check and one per cache entry per retry pause,\n * so it is safe to log or alert from. Without it the client logs one\n * `console.warn` per outage.\n */\n onError?: (failure: StudioFailure) => void\n /** Extra headers merged into every request. */\n headers?: Record<string, string>\n /**\n * Force preview behaviour: every read bypasses the cache and refreshes it.\n * Usually you do not set this by hand - use `client.forRequest(req)`, which\n * turns it on only for requests that carry the studio's preview marker.\n */\n preview?: boolean\n}\n\n/** Per-call read options. */\nexport interface ReadOptions {\n /** Set `false` to bypass the cache for this call and always hit the network. */\n cache?: boolean\n /**\n * Locale for this read, overriding the client-level `locale`. Pass an empty\n * string to force the project default even when a client locale is set;\n * `undefined` or `null` (a missing header, from `headers.get()`) leaves the\n * client locale in place. Untranslated fields fall back to the default\n * locale. Only record reads use it (`listRecords`, `getRecord`, a dataset's\n * `list` and `get`); `query()`, `schema()`, `nodes()` and `locales()` ignore it.\n */\n locale?: string | null | undefined\n}\n\n/** Per-call options for `uploadFile`. */\nexport interface UploadOptions {\n /**\n * The file name to send, extension included: the studio checks the\n * extension against the field's allowed types. Defaults to the name of a\n * `File`; required for a plain `Blob`.\n */\n filename?: string\n /**\n * Give up after this many ms, body included. Defaults to the client's\n * `timeout`, but at least 60 s (an upload may be 10 MB); `0` for none. A\n * client created with `timeout: 0` uploads without one too. A negative\n * number or `NaN` counts as not given.\n */\n timeout?: number\n}\n\ntype Method = 'GET' | 'POST' | 'PATCH'\n\n/**\n * Typed client for the Nordhavn OS content API: read and write a project's node\n * datasets from any website or app. Reads are cached (see the `cache` option);\n * writes invalidate the affected cache entries automatically.\n *\n * ```ts\n * const studio = new HavenClient({ apiKey: 'slk_...', baseUrl: 'https://studio.example.com' })\n * const posts = await studio.dataset<Post>('blog', 'posts').list()\n * ```\n */\nexport class HavenClient {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly fetchImpl: typeof fetch\n private readonly headers: Record<string, string>\n private readonly cache: ContentCache\n private readonly versionTracker: VersionTracker\n /**\n * `false` on a preview view (see `forRequest`), so reads bypass the cache by\n * default. The one field such a view has of its own; all the rest is shared.\n */\n private readDefault: boolean\n /** Client-level default locale for reads (undefined = project default). */\n private readonly locale?: string\n /** Request timeout in ms, `0` for none. */\n private readonly timeout: number\n /** `cache.waitForFresh` in ms, `Infinity` to wait for the studio. */\n private readonly waitForFresh: number\n /** `gatewayRetry` in ms, `undefined` when it is off. */\n private readonly gatewayRetry: number | undefined\n /**\n * The refresh under way per cache key, so concurrent reads of one key share\n * one request, with the ticket it left on (see `state.ticket`).\n */\n private readonly inflight = new Map<string, { job: Promise<unknown>, ticket: number }>()\n /**\n * Per cache key, the ticket of the request whose answer the cache holds.\n * Emptied on every invalidation, capped by `STORED_LIMIT`. See `storable`.\n */\n private readonly storedBy = new Map<string, number>()\n private readonly onError?: (failure: StudioFailure) => void\n /**\n * Everything that changes while the client runs and is not a collection of\n * its own. One object, so that a preview view - which shares this client's\n * fields through its prototype - changes the same values and never a copy.\n */\n private readonly state = {\n /**\n * Numbers the requests in the order they leave. Answers come back in any\n * order, and the cache must never go back in time: a request takes a\n * ticket when it leaves, and `storable` compares it on the way back.\n */\n ticket: 0,\n /** The last ticket handed out when the cache was last invalidated. */\n invalidatedAt: 0,\n /** Set by an absorbed failure, cleared by the next answer: one warning per outage. */\n unreachable: false,\n /**\n * The project's locales as last read. Kept here and not only in the cache,\n * where the entry can be evicted: without the list a requested locale\n * cannot be mapped onto the key its content is cached under, and that\n * content would be out of reach for as long as the studio is away.\n */\n locales: undefined as ContentLocale[] | undefined,\n /** Epoch ms before which the locales are not asked for again, after that failed. */\n localesRetryAt: 0,\n }\n\n constructor(options: HavenClientOptions) {\n if (!options.apiKey) throw new Error('HavenClient: `apiKey` is required')\n\n this.apiKey = options.apiKey\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n const resolvedFetch = options.fetch ?? globalThis.fetch\n if (!resolvedFetch) {\n throw new Error('HavenClient: no `fetch` available; pass one via options.fetch')\n }\n this.fetchImpl = resolvedFetch.bind(globalThis)\n this.headers = options.headers ?? {}\n this.locale = options.locale || undefined\n this.readDefault = options.preview !== true\n this.timeout = normalizeTimeout(options.timeout)\n this.onError = options.onError\n\n const cacheOpt = options.cache\n const cacheOptions: CacheOptions\n = cacheOpt === false ? { enabled: false }\n : cacheOpt === true || cacheOpt === undefined ? {}\n : cacheOpt\n this.cache = new ContentCache(cacheOptions)\n this.waitForFresh = normalizeWait(cacheOptions.waitForFresh)\n this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry)\n\n const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false\n ? 0\n : cacheOptions.revalidate ?? 60_000\n // The stamp check is tiny, and every read arriving while it runs waits on it,\n // so it gets a tighter budget than a full read.\n const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT)\n this.versionTracker = new VersionTracker(\n async () => {\n try {\n const res = await this.request<{ version?: unknown }>('GET', '/version', undefined, probeTimeout)\n // Anything but a stamp (a maintenance page answering 200) is no\n // answer: the last known stamp stands.\n if (typeof res?.version !== 'string') throw unexpectedBody(`${this.baseUrl}/api/content/version`)\n this.state.unreachable = false\n return res.version\n }\n catch (err) {\n // A studio without the route is up and answering: nothing to report.\n if (isMissingRoute(err)) this.state.unreachable = false\n else this.report({ during: 'stamp-check', error: err })\n throw err\n }\n },\n revalidate,\n isMissingRoute,\n )\n }\n\n // ── Preview scoping ─────────────────────────────────────────────────────────\n\n /**\n * A per-request view of this client that skips the cache when the request\n * comes from a Nordhavn OS surface preview, and behaves exactly like this\n * client otherwise. Reads still refresh the shared cache, so an editor\n * refreshing the preview also warms what real visitors get.\n *\n * Accepts whatever your framework hands you: a `Request`, a URL string or\n * `URL`, `URLSearchParams`, or a plain searchParams object.\n *\n * ```ts\n * // Next.js app router\n * export default async function Page({ searchParams }) {\n * const posts = await studio.forRequest(await searchParams).dataset('blog', 'posts').list()\n * }\n * ```\n *\n * Note this only bypasses the SDK's own cache. If the page itself sits behind\n * a CDN or framework data cache, that layer needs the same treatment (e.g.\n * `cache: 'no-store'` when the preview marker is present) or the editor keeps\n * seeing a stale page no matter what this client returns.\n */\n forRequest(input: PreviewInput): HavenClient {\n if (!this.readDefault) return this // already a preview client\n if (!isPreviewRequest(input)) return this\n\n // A view on this client, not a second one: it inherits every field through\n // its prototype - the cache, the stamp, the requests under way, the options -\n // and differs in the one it sets here. The preview must refresh what the\n // public site reads, not keep a second universe of its own; and built this\n // way there is no list of fields to hand over that a new one could be\n // missing from.\n const view = Object.create(this) as HavenClient\n view.readDefault = false\n return view\n }\n\n /** Whether this client bypasses the cache (i.e. came from a preview request). */\n get isPreview(): boolean {\n return !this.readDefault\n }\n\n // ── Introspection ─────────────────────────────────────────────────────────\n\n /** The full content shape this key can reach: nodes, datasets, field schemas. */\n async schema(opts?: ReadOptions): Promise<ContentSchema> {\n return this.cachedGet<ContentSchema>('schema', '/schema', opts, has('nodes', Array.isArray))\n }\n\n /** Shorthand for `schema()` then `.nodes`. */\n async nodes(opts?: ReadOptions): Promise<SchemaNode[]> {\n return (await this.schema(opts)).nodes\n }\n\n /**\n * The locales this project's content can be requested in (default first). Use\n * a locale `code` as the client `locale` option or a per-call `opts.locale`.\n */\n async locales(opts?: ReadOptions): Promise<ContentLocale[]> {\n const res = await this.cachedGet<{ locales: ContentLocale[] }>('locales', '/locales', opts, has('locales', Array.isArray))\n return res.locales\n }\n\n /**\n * Resolve the locale for a read: per-call override, else the client default.\n * Only a value overrides: `{ locale: undefined }` (or `null`) is what a site\n * passes when the visitor sent no language, and must leave the client locale standing.\n * `''` is the one way to ask for the project default.\n */\n private resolveLocale(opts?: ReadOptions): string | undefined {\n // `!= null`: from plain JavaScript a missing header arrives as `null`\n // (`headers.get()`), and means the same as `undefined`.\n const l = opts?.locale != null ? opts.locale : this.locale\n return l || undefined\n }\n\n /**\n * The locale a read is requested and cached under: the requested one mapped\n * onto a locale the project is configured with (see `matchLocale`).\n *\n * Sites pass on whatever language the visitor's browser asks for, and the\n * studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed\n * by the raw value, each spelling would be its own cache entry and its own\n * request - and a stream of made-up ones would push every real entry out of\n * the cache, the last good values for an outage among them. Mapped first,\n * the cache holds one entry per configured locale, whatever is asked for.\n *\n * Without the list of locales (caching off, an older studio without the\n * route, studio unreachable and never read) the requested value goes to the\n * studio as it is, and the studio resolves it.\n */\n private async readLocale(opts?: ReadOptions): Promise<string | undefined> {\n const requested = this.resolveLocale(opts)?.trim() || undefined\n if (requested === undefined || !this.cache.enabled) return requested\n\n // A preview or `cache: false` read is never tried twice (`gatewayRetry`),\n // and neither is the lookup it may have to wait for.\n const bypass = !(opts?.cache ?? this.readDefault)\n const configured = await this.configuredLocales(!bypass)\n return configured ? matchLocale(requested, configured) : requested\n }\n\n /**\n * The project's locales, or `undefined` when they have never been read and\n * cannot be now. An empty list is an answer like any other: the project has\n * no locales, the studio serves the same content whatever language is asked\n * for, and `matchLocale` then maps every request onto the default.\n *\n * Once the list is known this does not wait for anything: the read maps from\n * the list as it stands, and the list is brought up to date on the side. A\n * read therefore spends its `waitForFresh` on its content alone, and keeps\n * finding that content under the same key while the studio is away. Only\n * the very first localized read waits here, as it has nothing to map from.\n *\n * The exception is `waitForFresh: false`. That setting promises that a read\n * waits for the studio and leaves nothing running when it returns - what a\n * host needs that freezes the process once the response is out. So there\n * the list is brought up to date first, like the content after it.\n */\n private async configuredLocales(retry: boolean): Promise<ContentLocale[] | undefined> {\n const state = this.state\n if (Date.now() >= state.localesRetryAt) {\n // Always through the cache, also on a preview view: this runs on every\n // localized read, and a new locale shows up when the stamp moves.\n const lookup = this.cachedGet<{ locales: ContentLocale[] }>(\n 'locales',\n '/locales',\n { cache: true },\n has('locales', Array.isArray),\n retry,\n ).then(\n (res) => {\n state.locales = res.locales\n },\n () => {\n // Leave the list as it is, and the studio alone for a while.\n state.localesRetryAt = Date.now() + LOCALES_RETRY_MS\n },\n )\n if (state.locales === undefined || this.waitForFresh === Infinity) await lookup\n }\n return state.locales\n }\n\n // ── Records ───────────────────────────────────────────────────────────────\n\n /** List every record in a dataset (references inflated). Requires read scope. */\n async listRecords<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>[]> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ records: ContentRecord<T>[] }>(\n recordsKey(nodeSlug, datasetSlug, locale),\n datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),\n opts,\n has('records', Array.isArray),\n )\n return res.records\n }\n\n /** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */\n async getRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ record: ContentRecord<T> }>(\n recordKey(nodeSlug, datasetSlug, recordUid, locale),\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}${localeQuery(locale)}`,\n opts,\n has('record', isObject),\n )\n return res.record\n }\n\n /** Create a record. Requires write scope. Invalidates cached reads of the dataset. */\n async createRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'POST',\n datasetPath(nodeSlug, datasetSlug),\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Partially update a record. The patch is merged onto the stored data (omitted\n * top-level fields are preserved). Requires write scope. Invalidates cached\n * reads of the dataset and of this record.\n */\n async updateRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'PATCH',\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Upload one file for a `file` field, for a form that sends an attachment.\n * Requires write scope on the dataset. Returns the file; hang it on a record\n * in a second call by writing `{ uid }` into that field:\n *\n * ```ts\n * const attachment = form.get('attachment')\n * if (attachment instanceof File && attachment.size > 0) {\n * const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)\n * await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })\n * }\n * ```\n *\n * The field decides what it takes: its `mimes` and `max_size` rules, within\n * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The\n * studio reads the type from the content, so a renamed file is refused. Only\n * top-level fields. A file of the wrong type or size throws `HavenError` 400\n * with a message fit to show; other refusals (400, 403, 404) are setup\n * errors. More than 10 uploads a minute per key throws 429. From a Node\n * `Buffer`, send `new Blob([buffer])` with a `filename`.\n *\n * Server-side only: the key that uploads can write, and must never reach a\n * browser. Not retried, not cached, and it leaves cached reads alone: until a\n * record takes it up, the file belongs to no content. An upload that failed\n * may still have been stored; an unused one is removed after 24 hours.\n */\n async uploadFile(\n nodeSlug: string,\n datasetSlug: string,\n fieldSlug: string,\n file: Blob,\n opts?: UploadOptions,\n ): Promise<UploadedFile> {\n const filename = opts?.filename ?? (file as Partial<File>).name\n if (!filename) {\n throw new Error('HavenClient.uploadFile: the file has no name; pass `filename` (with its extension)')\n }\n const form = new FormData()\n form.set('file', file, filename)\n form.set('nodeSlug', nodeSlug)\n form.set('datasetSlug', datasetSlug)\n form.set('fieldSlug', fieldSlug)\n\n const url = `${this.baseUrl}/api/content/files`\n const timeout = uploadTimeout(this.timeout, opts?.timeout)\n return withTimeout(url, timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method: 'POST',\n // No Content-Type: fetch sets the multipart one, with its boundary.\n headers: { Authorization: `Bearer ${this.apiKey}`, ...withoutContentType(this.headers) },\n body: form,\n signal,\n })\n if (!res.ok) throw await this.toError(res)\n // A maintenance page, or an empty body, is no upload either.\n const value: unknown = await res.json().catch(() => undefined)\n if (!has('uid', (uid) => typeof uid === 'string' && uid !== '')(value)) throw unexpectedBody(url)\n return value as UploadedFile\n })\n }\n\n /**\n * Sends a write and settles the cached reads of its dataset with the outcome.\n *\n * Stored: they are dropped. Refused (an answered 4xx): they are still right\n * and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves\n * open whether the studio carried the write out, so they are marked for a\n * recheck: the next read asks the studio again, and keeps the cached value to\n * fall back on if the studio is in fact down.\n */\n private async write<T>(method: Method, path: string, body: unknown, nodeSlug: string, datasetSlug: string): Promise<T> {\n let res: T\n try {\n res = await this.request<T>(method, path, body)\n }\n catch (err) {\n if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, 'recheck')\n throw err\n }\n this.invalidateDataset(nodeSlug, datasetSlug)\n return res\n }\n\n // -- Queries --\n\n /** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */\n async query<V = unknown>(querySlug: string, opts?: ReadOptions): Promise<QueryResult<V>> {\n return this.cachedGet<QueryResult<V>>(\n `query:${querySlug}`,\n `/queries/${encodeURIComponent(querySlug)}`,\n opts,\n // Recognised by `shape`, never by `value`: that may be anything, and a\n // query without a result can come back with no `value` at all.\n has('shape', (shape) => typeof shape === 'string'),\n )\n }\n\n // ── Fluent dataset handle ───────────────────────────────────────────────────\n\n /**\n * A fluent, type-parameterised handle to one dataset:\n * `client.dataset<Post>('blog', 'posts').list()`.\n */\n dataset<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string): DatasetHandle<T> {\n return new DatasetHandle<T>(this, nodeSlug, datasetSlug)\n }\n\n // ── Cache control ───────────────────────────────────────────────────────────\n\n /**\n * Clear cached reads. With no argument, clears everything. Pass a scope to\n * clear just part of it: a node slug, or `{ node, dataset }` for one dataset.\n * A scoped clear also drops every saved query result, as any of them may\n * aggregate the content that was cleared.\n */\n clearCache(scope?: string | { node: string, dataset?: string }): void {\n if (scope === undefined) {\n this.cache.clear()\n this.invalidated()\n return\n }\n const node = typeof scope === 'string' ? scope : scope.node\n const dataset = typeof scope === 'string' ? undefined : scope.dataset\n if (dataset) {\n this.invalidateDataset(node, dataset)\n return\n }\n this.dropPrefix(`records:${node}/`)\n this.dropPrefix(`record:${node}/`)\n this.dropPrefix('query:')\n }\n\n /**\n * Invalidate cached record reads for a dataset (every locale), plus all query\n * results (which may aggregate it). `drop` removes them; `recheck` keeps each\n * value as a fallback but makes the next read ask the studio again.\n */\n private invalidateDataset(nodeSlug: string, datasetSlug: string, how: 'drop' | 'recheck' = 'drop'): void {\n const one = how === 'drop' ? (key: string) => this.drop(key) : (key: string) => this.recheck(key)\n const all = how === 'drop' ? (prefix: string) => this.dropPrefix(prefix) : (prefix: string) => this.recheckPrefix(prefix)\n // Default-locale list key + every `::<locale>` variant of it.\n one(recordsKey(nodeSlug, datasetSlug))\n all(`${recordsKey(nodeSlug, datasetSlug)}::`)\n // All single-record keys under the dataset (every uid, every locale).\n all(`${recordKey(nodeSlug, datasetSlug, '')}`)\n all('query:')\n }\n\n /** Drop one key from the cache. */\n private drop(key: string): void {\n this.cache.delete(key)\n this.invalidated()\n }\n\n /** `drop` for every key that starts with `prefix`. */\n private dropPrefix(prefix: string): void {\n this.cache.deletePrefix(prefix)\n this.invalidated()\n }\n\n /** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */\n private recheck(key: string): void {\n this.cache.expire(key)\n this.invalidated()\n }\n\n /** `recheck` for every key that starts with `prefix`. */\n private recheckPrefix(prefix: string): void {\n this.cache.expirePrefix(prefix)\n this.invalidated()\n }\n\n /**\n * Called by everything that invalidates cached reads. Every request that is\n * under way at this moment left before it, so its answer may show the\n * content as it was: none of them may store what they come back with\n * (`storable`), and no later read may join one of them (hence the cleared\n * `inflight`). They still answer the reads that were already waiting on them.\n *\n * Deliberately not narrowed to the keys that were invalidated. The price is\n * that an unrelated answer now and then is served without being stored, and\n * asked for once more; what it buys is one rule without exceptions.\n */\n private invalidated(): void {\n this.state.invalidatedAt = this.state.ticket\n this.storedBy.clear()\n this.inflight.clear()\n }\n\n /**\n * Whether the answer to the request that left on `ticket` may change what\n * the cache holds for `key`. The single gate in front of every cache write\n * that follows a request - cached read or bypass, a new value, a `304`, a\n * deletion or a retry pause alike. It keeps the cache from going back in time:\n *\n * - not when the cache was invalidated after the request left: the answer\n * may show the content from before (a write, `clearCache`);\n * - not when the cache already holds the answer to a request that left\n * later: that one is newer, whichever of the two came back first.\n */\n private storable(key: string, ticket: number): boolean {\n return ticket > this.state.invalidatedAt && ticket >= (this.storedBy.get(key) ?? 0)\n }\n\n /**\n * Settles the cache with the studio's own definitive \"no\" for `key` (deleted,\n * forbidden), in answer to the request that left on `ticket`: the entry goes.\n * The one place this happens, for a cached read and a bypass alike.\n *\n * The deletion is noted like any other answer. Without that, a request that\n * left earlier and comes back later would pass the gate and put the deleted\n * content straight back.\n */\n private gone(key: string, ticket: number): void {\n if (!this.storable(key, ticket)) return\n this.cache.delete(key)\n this.stored(key, ticket)\n }\n\n /**\n * Notes that the cache now reflects, for `key`, the answer to the request\n * that left on `ticket` - a value, a `304`, or the studio's own \"this does\n * not exist\", after which the cache holds nothing for it. A refresh of that\n * key that left earlier and is still under way is retired: a read arriving\n * now must not join it for an older answer than the cache already reflects.\n */\n private stored(key: string, ticket: number): void {\n // Unbounded growth is cut off the blunt, safe way: forget everything and\n // bar every request under way from storing, as an invalidation does.\n if (this.storedBy.size >= STORED_LIMIT) this.invalidated()\n this.storedBy.set(key, ticket)\n const running = this.inflight.get(key)\n if (running && running.ticket < ticket) this.inflight.delete(key)\n }\n\n // ── Transport ───────────────────────────────────────────────────────────────\n\n /**\n * The read path, with conditional revalidation.\n *\n * Steady state (project stamp unchanged since we last confirmed this entry):\n * served straight from cache, zero network. After a content change the stamp\n * moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps\n * the cached value, a `200` replaces it - and then it is fast again.\n *\n * Five rules hold for every read, whatever the studio does. Each is enforced\n * in exactly one place, named here, so that it cannot hold for one kind of\n * read and not for another:\n *\n * 1. A failure that is not the studio's own definitive answer never costs a\n * cached value: it is served instead, and stays cached (`refresh`).\n * 2. Only what is recognisably this endpoint's answer is ever stored\n * (`conditionalGet`).\n * 3. The cache never goes back in time: an answer is not stored when the\n * cache was invalidated, or filled with a newer answer, after its request\n * left (`storable`, in front of every write to the cache).\n * 4. A read that already holds a value waits on the studio for `waitForFresh`\n * at most, stamp check and refresh together (here); the refresh then\n * finishes on the side.\n * 5. One request per key at a time (`refresh`).\n */\n private async cachedGet<T>(\n cacheKey: string,\n path: string,\n opts: ReadOptions | undefined,\n isExpected: BodyCheck,\n /** Whether a `502`/`503` with nothing cached may be tried again (`gatewayRetry`). */\n retry = true,\n ): Promise<T> {\n const useCache = opts?.cache ?? this.readDefault\n\n // Preview / explicit bypass: always fetch fresh and never fall back, but\n // still refresh the shared cache so real visitors benefit from the warm entry.\n if (!useCache) {\n // The stamp as it stands before asking, like the cached path below. Read\n // after the answer it can be newer than the content that came back (an\n // edit landed in between, and another read's stamp check saw it), and\n // that older content would then count as current until the next edit.\n const version = this.versionTracker.current() ?? undefined\n const ticket = ++this.state.ticket\n let res: Awaited<ReturnType<HavenClient['conditionalGet']>>\n try {\n res = await this.conditionalGet(path, undefined, isExpected)\n }\n catch (err) {\n // Never falls back - but the studio's own \"this does not exist\" is an\n // answer for the cache as well, here as on the cached path.\n if (isDefinitive(err)) this.gone(cacheKey, ticket)\n throw err\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n\n // With something to serve, expired or not, the studio gets a budget.\n const started = Date.now()\n const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity\n\n // Cheap, throttled: at most one tiny stamp request per `revalidate` window.\n // A check that outlasts the budget carries on; this read uses the stamp we had.\n await within(this.versionTracker.refresh(started), budget)\n const version = this.versionTracker.current() ?? undefined\n const entry = this.cache.peek(cacheKey, Date.now())\n\n if (entry) {\n // Serve from cache when we cannot see a newer stamp (tracking off, first\n // probe not in yet, or studio unreachable) or the stamp is unchanged since\n // this entry was last confirmed.\n if (version === undefined || entry.validatedVersion === version) {\n return entry.value as T\n }\n }\n\n // Revalidate (the stamp moved) or refetch (miss / TTL expired). An expired\n // entry still has its etag, so an unchanged value comes back as a `304`.\n const last = entry ?? this.cache.stale(cacheKey)\n // A refetch failed moments ago: serve the last good value until the pause\n // is over, rather than making every read wait on an unreachable studio.\n if (last?.retryAt !== undefined && Date.now() < last.retryAt) {\n return last.value as T\n }\n\n const refresh = this.refresh<T>(cacheKey, path, last, version, isExpected, retry)\n if (!last) return refresh\n const outcome = await within(refresh, budget - (Date.now() - started))\n return outcome.settled ? outcome.value : last.value as T\n }\n\n /**\n * Fetches `cacheKey` from the studio and settles the cache with the answer.\n * One per key at a time: reads that arrive while it runs get the same promise,\n * so a slow studio sees one request for a key and not one per visitor.\n *\n * Resolves with the value to serve: the fresh one, or a cached one when the\n * studio failed transiently. Rejects on a definitive answer, or when there is\n * nothing cached to serve in its place.\n */\n private refresh<T>(\n cacheKey: string,\n path: string,\n last: CacheEntry | undefined,\n version: string | undefined,\n isExpected: BodyCheck,\n retry: boolean,\n ): Promise<T> {\n const running = this.inflight.get(cacheKey)\n if (running) return running.job as Promise<T>\n\n let ticket = ++this.state.ticket\n // Whether the slot for this key is still this refresh's own: once retired\n // it is empty, or belongs to the refresh that came after.\n const registered = (): boolean => this.inflight.get(cacheKey)?.job === job\n const register = (): void => {\n this.inflight.set(cacheKey, { job, ticket })\n }\n const job: Promise<T> = (async () => {\n try {\n let res: Awaited<ReturnType<HavenClient['conditionalGet']>>\n try {\n res = await this.conditionalGet(path, last?.etag, isExpected)\n }\n catch (err) {\n // A `502` or `503` is often one bad moment (a proxy switching to a\n // new studio container), and with nothing cached it is all the caller\n // would get. So once more, a moment later. A read is safe to repeat;\n // with a value to fall back on it is served instead, as below.\n const pause = this.gatewayRetry\n if (!retry || pause === undefined || last || this.cache.stale(cacheKey) || !isGatewayHiccup(err)) throw err\n await sleep(pause + Math.random() * pause)\n\n // Another request may have stored a value meanwhile: serve that.\n const meanwhile = this.cache.stale(cacheKey)\n if (meanwhile) return meanwhile.value as T\n // Or the slot went to a refresh that started during the pause, after\n // a newer answer retired this one's: that refresh left later, so its\n // answer is the one to have, and asking alongside it would break the\n // one request per key.\n const slot = this.inflight.get(cacheKey)\n // Returned as it is, not awaited: its outcome is that refresh's own,\n // already settled with the cache there, not a failure of this one.\n if (slot && !registered()) return slot.job as Promise<T>\n\n // The second try leaves now, after anything that left during the\n // pause, so it takes a ticket of its own: under the first one its\n // answer, newer than theirs, would count as older (`storable`). The\n // slot carries it, so an older answer does not retire it (`stored`);\n // emptied meanwhile (an invalidation), it is taken again, so that\n // reads arriving now join this request instead of sending their own.\n // And it reads the stamp as it stands now, before leaving: the\n // answer is at least as new as that.\n ticket = ++this.state.ticket\n if (slot) slot.ticket = ticket\n else register()\n version = this.versionTracker.current() ?? undefined\n res = await this.conditionalGet(path, undefined, isExpected)\n }\n // A `304` is only ever accepted in answer to an etag, so `last` is there.\n if (res.notModified && last) {\n if (this.storable(cacheKey, ticket)) {\n this.cache.confirm(cacheKey, version, Date.now())\n this.stored(cacheKey, ticket)\n }\n return last.value as T\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n catch (err) {\n // Definitive answer from the studio itself (deleted/forbidden): drop the\n // entry and surface it.\n if (isDefinitive(err)) {\n this.gone(cacheKey, ticket)\n throw err\n }\n // Anything else is transient: studio down, 5xx, timeout, rate limit,\n // network, a body that is not what this endpoint returns, or a 4xx from\n // whatever stands in front of the studio while it is gone. Serve a\n // cached value, even an expired one, and keep it.\n //\n // What the cache holds *now*, not only what it held when this request\n // left: every read that joined gets this same outcome, and one of them\n // may hold a value that was stored in the meantime (by a preview read,\n // say) while the read that started the request had none. Failing that\n // one with an error it had the content for is exactly what rule 1 forbids.\n const held = this.cache.stale(cacheKey) ?? last\n if (!held) throw err\n this.report({ during: 'read', key: cacheKey, error: err })\n return (this.storable(cacheKey, ticket) ? this.cache.backoff(cacheKey, held, Date.now()) : held).value as T\n }\n finally {\n if (registered()) this.inflight.delete(cacheKey)\n }\n })()\n this.inflight.set(cacheKey, { job, ticket })\n return job\n }\n\n /**\n * Hands an absorbed failure to `onError`, or without one warns once per\n * outage. Never throws and never leaves a rejection behind: a broken hook\n * must not turn a served read into an error, and an `async` hook whose own\n * work fails (an alert that cannot be delivered, during the very outage it\n * reports) must not become the unhandled rejection that stops the process.\n */\n private report(failure: StudioFailure): void {\n const first = !this.state.unreachable\n this.state.unreachable = true\n try {\n if (this.onError) {\n const outcome: unknown = this.onError(failure)\n if (isThenable(outcome)) outcome.then(undefined, () => {})\n }\n else if (first) {\n const reason = failure.error instanceof Error ? failure.error.message : String(failure.error)\n const what = failure.during === 'read' ? `could not refresh \"${failure.key}\"` : 'stamp check failed'\n console.warn(`[@nordhavnhq/beacon] ${what} (${reason}); cached content keeps being served.`)\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /**\n * A GET that understands conditional requests: sends `If-None-Match` when an\n * etag is supplied, and reports a `304` as `notModified` rather than a value.\n *\n * The one place that decides what counts as an answer, for every read:\n *\n * - A `2xx` whose body fails `isExpected` is rejected, not returned. A\n * maintenance page or a captive portal can answer `200` with JSON of its\n * own; storing that would replace the last good value with nothing, at the\n * very moment the studio is away.\n * - A `304` is only an answer to a request that sent an etag. Unasked for,\n * it says \"keep what you have\" to a caller that has nothing, and there is\n * no value to return or store.\n */\n private async conditionalGet(\n path: string,\n ifNoneMatch: string | undefined,\n isExpected: BodyCheck,\n ): Promise<{ notModified: boolean, value?: unknown, etag?: string }> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, this.timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(ifNoneMatch ? { 'If-None-Match': ifNoneMatch } : {}),\n ...this.headers,\n },\n signal,\n })\n\n if (res.status === 304) {\n if (!ifNoneMatch) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: true, etag: res.headers.get('etag') ?? ifNoneMatch }\n }\n if (!res.ok) throw await this.toError(res)\n const etag = res.headers.get('etag') ?? undefined\n const value: unknown = res.status === 204 ? undefined : await res.json()\n if (!isExpected(value)) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: false, value, etag }\n })\n }\n\n private async request<T>(method: Method, path: string, body?: unknown, timeout = this.timeout): Promise<T> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...this.headers,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal,\n })\n\n if (!res.ok) throw await this.toError(res)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n })\n }\n\n /** Parse a non-2xx response into a `HavenError`, preferring its message. */\n private async toError(res: Response): Promise<HavenError> {\n let message = res.statusText || `Request failed with status ${res.status}`\n let parsed: unknown\n try {\n parsed = await res.json()\n const m = parsed as { message?: unknown, statusMessage?: unknown }\n if (typeof m?.message === 'string') message = m.message\n else if (typeof m?.statusMessage === 'string') message = m.statusMessage\n } catch {\n /* non-JSON error body; keep the status text */\n }\n const err = new HavenError(message, res.status, parsed)\n if (res.headers.has('retry-after')) askedToWait.add(err)\n return err\n }\n}\n\n/** Fluent, dataset-scoped view returned by `client.dataset()`. */\nexport class DatasetHandle<T = Record<string, unknown>> {\n constructor(\n private readonly client: HavenClient,\n private readonly nodeSlug: string,\n private readonly datasetSlug: string,\n ) {}\n\n list(opts?: ReadOptions): Promise<ContentRecord<T>[]> {\n return this.client.listRecords<T>(this.nodeSlug, this.datasetSlug, opts)\n }\n\n get(recordUid: string, opts?: ReadOptions): Promise<ContentRecord<T>> {\n return this.client.getRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, opts)\n }\n\n create(data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.createRecord<T>(this.nodeSlug, this.datasetSlug, data)\n }\n\n update(recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.updateRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, data)\n }\n\n /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */\n uploadFile(fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile> {\n return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts)\n }\n\n /** Clear cached reads for this dataset. */\n clearCache(): void {\n this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug })\n }\n}\n\n// ── Preview detection ─────────────────────────────────────────────────────────\n\n/** Anything a framework might hand you that could carry the preview marker. */\nexport type PreviewInput\n = | string\n | URL\n | URLSearchParams\n | { url: string }\n | Record<string, string | string[] | undefined>\n | null\n | undefined\n\n/**\n * True when the request was opened from a Nordhavn OS surface preview, i.e. it\n * carries the `sl-preview` query parameter the studio appends to the iframe URL.\n */\nexport function isPreviewRequest(input: PreviewInput): boolean {\n if (!input) return false\n\n if (typeof input === 'string') {\n // Either a full URL or a bare query string (\"?a=1\" / \"a=1\").\n const query = input.includes('?') ? input.slice(input.indexOf('?') + 1) : input\n return new URLSearchParams(query).has(PREVIEW_PARAM)\n }\n if (input instanceof URLSearchParams) return input.has(PREVIEW_PARAM)\n if (input instanceof URL) return input.searchParams.has(PREVIEW_PARAM)\n if (typeof (input as { url?: unknown }).url === 'string') {\n return isPreviewRequest((input as { url: string }).url)\n }\n return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM)\n}\n\n// ── Timeout ───────────────────────────────────────────────────────────────────\n\n/**\n * Runs `run` with an abort signal that fires after `ms`, and rejects with a\n * `TimeoutError` at that moment whether or not `run` listens to the signal: a\n * custom `fetch` may ignore it. The timer spans the whole of `run`, so a studio\n * that sends headers and then stalls the body is caught too.\n *\n * The error is a plain `Error`, not a `HavenError`: the read path treats\n * anything without an HTTP status as transient and serves the cache.\n */\nasync function withTimeout<T>(url: string, ms: number, run: (signal?: AbortSignal) => Promise<T>): Promise<T> {\n if (ms <= 0) return run(undefined)\n\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const err = new Error(`The studio did not answer within ${ms}ms: ${url}`)\n err.name = 'TimeoutError'\n controller.abort(err)\n reject(err)\n }, ms)\n })\n\n try {\n return await Promise.race([run(controller.signal), expired])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * The `timeout` option as a usable number of ms, `0` for none. `Infinity`, or\n * more than a timer can hold, means \"no timeout\" - handed to `setTimeout` as\n * it is, it would fire after 1 ms and fail every request.\n */\nfunction normalizeTimeout(value: number | undefined): number {\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT\n return value > MAX_TIMER ? 0 : value\n}\n\n/**\n * An upload's timeout in ms, `0` for none. A valid per-call `timeout` wins;\n * otherwise (none, or a negative number or `NaN`, as from an unset\n * environment variable) the client's, but at least `MIN_UPLOAD_TIMEOUT`. A\n * client without a timeout (`0`) uploads without one too.\n */\nfunction uploadTimeout(clientTimeout: number, perCall: number | undefined): number {\n if (typeof perCall === 'number' && perCall >= 0) return normalizeTimeout(perCall)\n return clientTimeout === 0 ? 0 : Math.max(clientTimeout, MIN_UPLOAD_TIMEOUT)\n}\n\n/**\n * The client's extra headers without a `Content-Type`: one set for every\n * request would replace the multipart type and its boundary, and the studio\n * could not read the upload.\n */\nfunction withoutContentType(headers: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'content-type'))\n}\n\n/** `gatewayRetry` in ms, `undefined` when the second try is off. */\nfunction normalizeGatewayRetry(value: number | false | undefined): number | undefined {\n if (value === false) return undefined\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY\n return Math.min(value, MAX_GATEWAY_RETRY)\n}\n\n/** `cache.waitForFresh` in ms, `Infinity` when a read should wait for the studio. */\nfunction normalizeWait(value: number | false | undefined): number {\n if (value === false) return Infinity\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH\n // More than a timer can hold is no budget at all: `within` already waits\n // such a value out, so it is made to mean `false` everywhere, in one place.\n return value > MAX_TIMER ? Infinity : value\n}\n\ntype Settled<T> = { settled: true, value: T } | { settled: false }\n\n/**\n * Waits on `promise` for at most `ms`. Past that it reports \"not settled\" and\n * lets the promise run on; a later rejection is swallowed here, as whoever\n * started the work deals with its outcome. A rejection within `ms` is thrown.\n */\nasync function within<T>(promise: Promise<T>, ms: number): Promise<Settled<T>> {\n if (ms > MAX_TIMER) return { settled: true, value: await promise }\n if (ms <= 0) {\n promise.catch(() => {})\n return { settled: false }\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined\n const late = new Promise<Settled<T>>((resolve) => {\n timer = setTimeout(() => resolve({ settled: false }), ms)\n })\n try {\n return await Promise.race([promise.then((value): Settled<T> => ({ settled: true, value })), late])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n// ── Response shape ────────────────────────────────────────────────────────────\n\n/** Whether a value is a promise, or anything else that settles later. */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === 'function'\n}\n\n/** Whether a response body is what its endpoint returns. */\ntype BodyCheck = (body: unknown) => boolean\n\nfunction isObject(value: unknown): boolean {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A body that is an object carrying `field`, with a value that passes `check`. */\nfunction has(field: string, check: (value: unknown) => boolean): BodyCheck {\n return (body) => isObject(body) && field in (body as object) && check((body as Record<string, unknown>)[field])\n}\n\n/**\n * The error for a response its endpoint never gives: a `2xx` with a body of\n * another shape, or a `304` nobody asked for. A plain `Error` without a status,\n * so the read path treats it as transient and serves the cache.\n */\nfunction unexpectedBody(url: string): Error {\n const err = new Error(`The studio answered with an unexpected response: ${url}`)\n err.name = 'UnexpectedResponseError'\n return err\n}\n\n// ── Cache-key + path helpers ──────────────────────────────────────────────────\n\n/**\n * Whether an error status says \"try again later\" rather than \"this is the\n * answer\": server errors, request timeout (408) and rate limiting (429).\n */\nfunction isTransientStatus(status: number): boolean {\n return status >= 500 || status === 408 || status === 429\n}\n\n/**\n * Errors whose response carried `Retry-After`: the studio, or the proxy in\n * front of it, asked to wait, so they are not tried again a moment later.\n * Kept here instead of on the error, which is public API.\n */\nconst askedToWait = new WeakSet<object>()\n\n/**\n * A `502` or `503`: worth one more try a moment later. A `504` already waited,\n * and an answer with `Retry-After` asked not to.\n */\nfunction isGatewayHiccup(err: unknown): boolean {\n return err instanceof HavenError && (err.status === 502 || err.status === 503) && !askedToWait.has(err)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Whether a failed read is the studio's own definitive answer - this does not\n * exist, this key may not see it - rather than a sign that the studio could\n * not be reached. The only kind of failure that may cost a cached value.\n */\nfunction isDefinitive(err: unknown): err is HavenError {\n return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err)\n}\n\n/**\n * Whether an error response was written by the studio, and not by something\n * answering in its place. While the studio container is gone (a redeploy, a\n * crash) the proxy in front of it answers for it, and often with a `404`:\n * Traefik's `404 page not found`, an HTML error page, a gateway's own JSON.\n * Taking that for \"this record was deleted\" would drop the very entry that\n * should carry the site through the outage.\n *\n * The studio's errors are JSON objects that restate their status\n * (`{ \"statusCode\": 404, \"message\": \"...\" }`); nothing else is trusted to be\n * the studio speaking. `status` is accepted next to `statusCode`, the name\n * newer server frameworks give the same field.\n */\nfunction isStudioAnswer(err: HavenError): boolean {\n const body = err.body as { statusCode?: unknown, status?: unknown } | null | undefined\n if (typeof body !== 'object' || body === null) return false\n return body.statusCode === err.status || body.status === err.status\n}\n\n/**\n * Whether a failed stamp check says \"this studio has no stamp route\": its own\n * `404`, as an older server answers. Not the `404` of a proxy standing in for a\n * studio that is away - that one is an outage like any other.\n */\nfunction isMissingRoute(err: unknown): boolean {\n return err instanceof HavenError && err.status === 404 && isStudioAnswer(err)\n}\n\n/**\n * Whether a failed write may have been stored all the same. Only an answered\n * 4xx rules it out: the request was refused. A timeout, a dropped connection or\n * a 5xx can each follow a write the studio did carry out.\n */\nfunction writeMayHaveLanded(err: unknown): boolean {\n return !(err instanceof HavenError && err.status >= 400 && err.status < 500)\n}\n\nfunction datasetPath(nodeSlug: string, datasetSlug: string): string {\n return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`\n}\n\n/**\n * Maps a requested locale onto one the project is configured with, by the rule\n * the studio applies itself: the exact locale, else one in the same language\n * (`nl` or `nl-NL` for a configured `nl-BE`), else the project's fallback\n * locale. `undefined` means the project default, which is requested by sending\n * no locale at all.\n *\n * With several locales in one language and no exact match, the default locale\n * wins if it is among them, otherwise the first one listed.\n */\nfunction matchLocale(requested: string, locales: ContentLocale[]): string | undefined {\n const canonical = (code: string): string => code.trim().toLowerCase().replace(/_/g, '-')\n const known = locales.filter((locale) => typeof locale?.code === 'string' && locale.code !== '')\n const wanted = canonical(requested)\n\n const exact = known.find((locale) => canonical(locale.code) === wanted)\n if (exact) return exact.code\n\n const language = wanted.split('-')[0]\n const related = known.filter((locale) => canonical(locale.code).split('-')[0] === language)\n const close = related.find((locale) => locale.isDefault) ?? related[0]\n if (close) return close.code\n\n return known.find((locale) => locale.isFallback)?.code\n}\n\n/** `?locale=xx` query suffix, or empty for the default locale. */\nfunction localeQuery(locale?: string): string {\n return locale ? `?locale=${encodeURIComponent(locale)}` : ''\n}\n\n/** Locale cache-key suffix. `::<locale>` keeps each locale a distinct entry;\n * the default locale has no suffix. `::` never collides with a slug. */\nfunction localeKeySuffix(locale?: string): string {\n return locale ? `::${locale}` : ''\n}\n\nfunction recordsKey(nodeSlug: string, datasetSlug: string, locale?: string): string {\n return `records:${nodeSlug}/${datasetSlug}${localeKeySuffix(locale)}`\n}\n\nfunction recordKey(nodeSlug: string, datasetSlug: string, recordUid: string, locale?: string): string {\n return `record:${nodeSlug}/${datasetSlug}/${recordUid}${localeKeySuffix(locale)}`\n}\n","/**\n * The chart contract: what a chart block is (`ChartSpec`, as authored and\n * stored) and what a renderer draws (`ChartData`, the resolved categories and\n * series). Shared by the Nordhavn OS server, the client and every renderer, so a\n * chart means the same thing wherever it is read. Pure data: no dependencies.\n * The zod schemas for these shapes live in `@nordhavnhq/beacon/schema`.\n */\n\n/**\n * The palette a series colour may pick from. A renderer maps a key to a colour\n * of the theme it runs in; a spec never carries a raw hex.\n */\nexport const PALETTE_KEYS = ['ember', 'aurora', 'crimson', 'dusk', 'jade', 'cobalt', 'iris', 'nebula'] as const\nexport type PaletteKey = typeof PALETTE_KEYS[number]\n\nexport const CHART_TYPES = ['bar', 'bar-horizontal', 'line', 'area', 'pie', 'donut', 'share', 'heatmap'] as const\nexport type ChartType = typeof CHART_TYPES[number]\n\n/**\n * How a chart reads its data: `cartesian` plots each series over the\n * categories, `part` cuts one series into its categories (one whole), `matrix`\n * is a grid of the categories (columns) by the series (rows).\n */\nexport type ChartFamily = 'cartesian' | 'part' | 'matrix'\n\n/** What a chart type is and takes: every editor, parser and renderer reads it from here. */\nexport interface ChartTypeInfo {\n value: ChartType\n label: string\n /** One line on what the type is for (editor hint, agent docs). */\n purpose: string\n /** A lucide icon name (kebab-case); the host maps it to its icon set. */\n icon: string\n family: ChartFamily\n /** Exactly one series (the parts are the categories). */\n singleSeries: boolean\n /** Series may sit on a left or right value axis. */\n axes: boolean\n /** Series may stack. */\n stacked: boolean\n /** Each series wears its own colour (else one hue in tints). */\n seriesColors: boolean\n /** Value labels on the marks are possible. */\n valueLabels: boolean\n /** Drawn as HTML that sizes to its content, not into a fixed canvas box. */\n html: boolean\n /** Default box height in px. */\n height: number\n}\n\nexport const CHART_TYPE_INFO: Record<ChartType, ChartTypeInfo> = {\n 'bar': {\n value: 'bar', label: 'Bar', icon: 'chart-column', family: 'cartesian',\n purpose: 'Compare values across categories or periods.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'bar-horizontal': {\n value: 'bar-horizontal', label: 'Bar (horizontal)', icon: 'chart-bar', family: 'cartesian',\n purpose: 'Rank categories with long labels, largest on top when sorted by value.',\n singleSeries: false, axes: false, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'line': {\n value: 'line', label: 'Line', icon: 'chart-line', family: 'cartesian',\n purpose: 'A trend over time.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'area': {\n value: 'area', label: 'Area', icon: 'chart-area', family: 'cartesian',\n purpose: 'A trend over time with its volume.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'pie': {\n value: 'pie', label: 'Pie', icon: 'chart-pie', family: 'part',\n purpose: 'Parts of one whole, few slices.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'donut': {\n value: 'donut', label: 'Donut', icon: 'circle-dashed', family: 'part',\n purpose: 'Parts of one whole around a centred total (status, category breakdown).',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'share': {\n value: 'share', label: 'Share bars', icon: 'align-left', family: 'part',\n purpose: 'Parts of one whole as ranked thin bars with figure and percentage; reads well with many parts.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: true, height: 260,\n },\n 'heatmap': {\n value: 'heatmap', label: 'Heatmap', icon: 'grid-3x3', family: 'matrix',\n purpose: 'A grid of the categories (columns) by the series (rows), one hue from faint to full.',\n singleSeries: false, axes: false, stacked: false, seriesColors: false, valueLabels: true, html: false, height: 300,\n },\n}\n\nexport function chartTypeInfo(type: ChartType): ChartTypeInfo {\n return CHART_TYPE_INFO[type] ?? CHART_TYPE_INFO.bar\n}\n\n/** Pie, donut and share: one series cut into its categories. */\nexport function isPartChart(type: ChartType): boolean {\n return chartTypeInfo(type).family === 'part'\n}\n\n/** Bar in either direction. */\nexport function isBarChart(type: ChartType): boolean {\n return type === 'bar' || type === 'bar-horizontal'\n}\n\n/** Which Y axis a series scales against. Only for the types with `axes`. */\nexport const CHART_AXES = ['left', 'right'] as const\nexport type ChartAxis = typeof CHART_AXES[number]\n\n/** Periods a date category can be grouped into. */\nexport const DATE_BUCKET_VALUES = ['day', 'week', 'month', 'quarter', 'year'] as const\nexport type DateBucket = typeof DATE_BUCKET_VALUES[number]\n\n/** `auto` picks the period from the date range. */\nexport const BUCKET_MODES = ['auto', ...DATE_BUCKET_VALUES] as const\nexport type BucketMode = typeof BUCKET_MODES[number]\n\n/** How the records that fall in one category combine into one point. */\nexport const AGGREGATIONS = ['sum', 'avg', 'count', 'min', 'max', 'first', 'last'] as const\nexport type Aggregation = typeof AGGREGATIONS[number]\n\n/** Category order. `default` is chronological for dates, source order otherwise. */\nexport const CHART_SORTS = ['default', 'category-asc', 'category-desc', 'value-desc', 'value-asc'] as const\nexport type ChartSort = typeof CHART_SORTS[number]\n\nexport interface ChartSeriesSpec {\n /** Field slug whose numeric value is the Y value. */\n field: string\n label?: string\n /** Omitted: the next colour of the renderer's default rotation. */\n color?: PaletteKey\n axis: ChartAxis\n aggregate: Aggregation\n}\n\n/** A chart as authored and stored: where its data comes from and how it is shaped. */\nexport interface ChartSpec {\n title: string\n chartType: ChartType\n /** A dataset (`node.dataset`) or a saved query (`queries.<slug>`). */\n source: string\n /** Field slug for the X axis or the slice labels. */\n categoryField: string\n /**\n * Field slug to split the first series by: one series per distinct value of\n * this field (top 12 by record count, the rest as \"Other\"). The rows of a\n * heatmap, the stacks of a bar. Empty: the series are the value fields.\n */\n splitField: string\n series: ChartSeriesSpec[]\n /** Date categories only. */\n bucket: BucketMode\n sort: ChartSort\n /** Keep the top N categories, the rest becomes \"Other\". 0 is no limit. Non-date only. */\n limit: number\n /** Date buckets only: emit empty periods so a line stays continuous. */\n fillGaps: boolean\n stacked: boolean\n legend: boolean\n}\n\nexport interface ChartSeriesData {\n name: string\n /** One value per category; null is a gap (nothing measured there). */\n data: Array<number | null>\n /** A palette key or any CSS colour the host resolved. */\n color?: string\n axis?: ChartAxis\n}\n\n/** A chart as a renderer draws it: the data already resolved and consolidated. */\nexport interface ChartData {\n type: ChartType\n categories: string[]\n series: ChartSeriesData[]\n stacked?: boolean\n legend?: boolean\n}\n","/**\n * The ```chart fence: a chart written inline in markdown, as JSON in the\n * shape a renderer draws (`ChartData`) plus a title. One parser for every\n * reader: the Nordhavn OS server validates a save with it, the markdown renderer\n * draws what it returns, the PDF export rasterises it, a site can use it too.\n * Pure and dependency-free.\n *\n * A `{{ expr }}` signal may stand where a number goes (`\"data\": [{{ a.b }}, 4]`).\n * The host fills it in before parsing; whatever is still left reads as a gap\n * (null), so a document never fails to save or print on a signal.\n */\nimport { CHART_AXES, CHART_TYPES, PALETTE_KEYS, chartTypeInfo, type ChartData, type ChartSeriesData } from './chart'\n\n/** The fence language. */\nexport const CHART_FENCE_LANG = 'chart'\n\nexport const CHART_FENCE_LIMITS = {\n categories: 100,\n series: 12,\n label: 120,\n title: 200,\n minHeight: 120,\n maxHeight: 600,\n} as const\n\n/** A chart as a ```chart fence carries it. */\nexport interface ChartFence extends ChartData {\n title?: string\n /** Box height in px; the renderer's default when omitted. */\n height?: number\n /** Value labels on the marks (bar types and heatmap). */\n valueLabels?: boolean\n}\n\nexport type ChartFenceResult = { ok: true, chart: ChartFence } | { ok: false, error: string }\n\nconst SIGNAL_RE = /\\{\\{[\\s\\S]*?\\}\\}/g\n\n/** Box height of a fenced chart in px: its own `height`, else a default per type. */\nexport function chartFenceHeight(chart: Pick<ChartFence, 'type' | 'height'>): number {\n if (chart.height) return chart.height\n return chartTypeInfo(chart.type).height\n}\n\n/** True for the language of a ```chart fence (case-insensitive, options after it ignored). */\nexport function isChartFence(lang: string | null | undefined): boolean {\n return (lang ?? '').trim().split(/\\s+/)[0]?.toLowerCase() === CHART_FENCE_LANG\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\nfunction oneOf<T extends string>(list: readonly T[], v: unknown): v is T {\n return typeof v === 'string' && (list as readonly string[]).includes(v)\n}\n\nfunction label(v: unknown, what: string, max: number = CHART_FENCE_LIMITS.label): string {\n if (typeof v === 'number' && Number.isFinite(v)) return String(v)\n if (typeof v !== 'string') throw new Error(`${what} must be a string`)\n if (v.length > max) throw new Error(`${what} is longer than ${max} characters`)\n return v\n}\n\nfunction parseSeries(raw: unknown, i: number, size: number): ChartSeriesData {\n const at = `series[${i}]`\n if (!isRecord(raw)) throw new Error(`${at} must be an object with \"name\" and \"data\"`)\n if (!Array.isArray(raw.data)) throw new Error(`${at}.data must be an array of numbers`)\n if (raw.data.length !== size) throw new Error(`${at}.data has ${raw.data.length} values, \"categories\" has ${size}: one value per category`)\n const data = raw.data.map((v, j) => {\n if (v === null) return null\n if (typeof v === 'number' && Number.isFinite(v)) return v\n throw new Error(`${at}.data[${j}] must be a number or null, got ${JSON.stringify(v)}`)\n })\n const out: ChartSeriesData = { name: raw.name === undefined ? `Series ${i + 1}` : label(raw.name, `${at}.name`), data }\n if (raw.color !== undefined) {\n if (!oneOf(PALETTE_KEYS, raw.color)) throw new Error(`${at}.color must be one of ${PALETTE_KEYS.join(', ')}`)\n out.color = raw.color\n }\n if (raw.axis !== undefined) {\n if (!oneOf(CHART_AXES, raw.axis)) throw new Error(`${at}.axis must be ${CHART_AXES.join(' or ')}`)\n out.axis = raw.axis\n }\n return out\n}\n\nfunction parseShape(raw: unknown): ChartFence {\n if (!isRecord(raw)) throw new Error('The fence must hold one JSON object')\n if (!oneOf(CHART_TYPES, raw.type)) throw new Error(`\"type\" must be one of ${CHART_TYPES.join(', ')}`)\n if (!Array.isArray(raw.categories) || raw.categories.length === 0) throw new Error('\"categories\" must be a non-empty array of labels')\n if (raw.categories.length > CHART_FENCE_LIMITS.categories) throw new Error(`\"categories\" has ${raw.categories.length} entries, at most ${CHART_FENCE_LIMITS.categories}`)\n const categories = raw.categories.map((c, i) => label(c, `categories[${i}]`))\n if (!Array.isArray(raw.series) || raw.series.length === 0) throw new Error('\"series\" must be a non-empty array')\n if (raw.series.length > CHART_FENCE_LIMITS.series) throw new Error(`\"series\" has ${raw.series.length} entries, at most ${CHART_FENCE_LIMITS.series}`)\n if (chartTypeInfo(raw.type).singleSeries && raw.series.length !== 1) throw new Error(`A ${raw.type} takes exactly one series (the parts are the categories)`)\n const series = raw.series.map((s, i) => parseSeries(s, i, categories.length))\n\n const chart: ChartFence = { type: raw.type, categories, series }\n if (raw.title !== undefined) chart.title = label(raw.title, '\"title\"', CHART_FENCE_LIMITS.title)\n for (const key of ['stacked', 'legend', 'valueLabels'] as const) {\n if (raw[key] === undefined) continue\n if (typeof raw[key] !== 'boolean') throw new Error(`\"${key}\" must be true or false`)\n chart[key] = raw[key]\n }\n if (raw.height !== undefined) {\n const h = raw.height\n if (typeof h !== 'number' || h < CHART_FENCE_LIMITS.minHeight || h > CHART_FENCE_LIMITS.maxHeight) {\n throw new Error(`\"height\" must be a number from ${CHART_FENCE_LIMITS.minHeight} to ${CHART_FENCE_LIMITS.maxHeight}`)\n }\n chart.height = Math.round(h)\n }\n return chart\n}\n\n/** The chart in a ```chart fence body, or what is wrong with it (one line an author can act on). */\nexport function parseChartFence(source: string): ChartFenceResult {\n const text = source.replace(SIGNAL_RE, 'null').trim()\n if (!text) return { ok: false, error: 'Empty chart fence' }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n }\n catch (err) {\n return { ok: false, error: `Not valid JSON: ${err instanceof Error ? err.message : String(err)}` }\n }\n try {\n return { ok: true, chart: parseShape(raw) }\n }\n catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n }\n}\n","export { HavenClient, DatasetHandle, DEFAULT_BASE_URL, PREVIEW_PARAM, isPreviewRequest } from './client'\nexport type { HavenClientOptions, ReadOptions, UploadOptions, PreviewInput, StudioFailure } from './client'\nexport { HavenError } from './errors'\nexport { ContentCache, MemoryCacheStore } from './cache'\nexport type { CacheOptions, CacheStore, CacheEntry } from './cache'\nexport type {\n ContentSchema,\n SchemaNode,\n SchemaDataset,\n SchemaField,\n FieldKind,\n FieldType,\n ContentRecord,\n ContentLocale,\n QueryResult,\n QueryShape,\n UploadedFile,\n} from './types'\nexport {\n PALETTE_KEYS,\n CHART_TYPES,\n CHART_TYPE_INFO,\n chartTypeInfo,\n isPartChart,\n isBarChart,\n CHART_AXES,\n DATE_BUCKET_VALUES,\n BUCKET_MODES,\n AGGREGATIONS,\n CHART_SORTS,\n} from './chart'\nexport type {\n PaletteKey,\n ChartType,\n ChartFamily,\n ChartTypeInfo,\n ChartAxis,\n DateBucket,\n BucketMode,\n Aggregation,\n ChartSort,\n ChartSeriesSpec,\n ChartSpec,\n ChartSeriesData,\n ChartData,\n} from './chart'\nexport { CHART_FENCE_LANG, CHART_FENCE_LIMITS, chartFenceHeight, isChartFence, parseChartFence } from './chart-fence'\nexport type { ChartFence, ChartFenceResult } from './chart-fence'\nexport type {\n RoadmapPhaseState,\n RoadmapWorkState,\n RoadmapTone,\n RoadmapTip,\n RoadmapPhase,\n RoadmapLane,\n RoadmapMilestone,\n RoadmapWaiting,\n RoadmapTask,\n RoadmapRepeat,\n RoadmapHappening,\n RoadmapEvent,\n RoadmapData,\n ForecastSeries,\n} from './roadmap'\n\nimport { HavenClient, type HavenClientOptions } from './client'\n\n/** Convenience factory: `createClient({ apiKey, baseUrl })`. */\nexport function createClient(options: HavenClientOptions): HavenClient {\n return new HavenClient(options)\n}\n\n// Names of the package's former life as `@justmade/client`, so a site that\n// switches only changes its import. Removed in the next breaking release.\n/** @deprecated Use `HavenClient`. */\nexport { HavenClient as JustmadeClient } from './client'\n/** @deprecated Use `HavenClientOptions`. */\nexport type { HavenClientOptions as JustmadeClientOptions } from './client'\n/** @deprecated Use `HavenError`. */\nexport { HavenError as JustmadeError } from './errors'\n"]}
1
+ {"version":3,"sources":["../src/runtime.ts","../src/announce.ts","../src/cache.ts","../src/errors.ts","../src/live-policy.ts","../src/live-sse.ts","../src/version.ts","../src/live.ts","../src/file-cache.ts","../src/options.ts","../src/rate-gate.ts","../src/client.ts","../src/chart.ts","../src/chart-fence.ts","../src/index.ts"],"names":["registry","version"],"mappings":";;;AAuDA,IAAM,aAAa,EAAA,GAAK,IAAA;AAMjB,SAAS,WAAA,GAAkD;AAChE,EAAA,IAAI;AACF,IAAA,OAAQ,UAAA,CAAuB,OAAA,EAAS,GAAA,IAAO,EAAC;AAAA,EAClD,CAAA,CAAA,MACM;AACJ,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAGO,SAAS,QAAQ,IAAA,EAAkC;AACxD,EAAA,IAAI;AAC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kC,kBAAA,CAAmB,SAAS,CAAA,IAAA,EAAO,kBAAA,CAAmB,SAAS,CAAA,CAAE,CAAA;AAAA,IACrH;AACA,IAAA,KAAA,CAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AAAA,EAC7B;AACA,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,gBAAgB,MAAA,EAAkC;AAChE,EAAA,MAAM,OAAO,MAAA,CAAO,OAAA,CAAQ,SAAA,EAAW,MAAM,EAAE,IAAA,EAAK;AACpD,EAAA,IAAI,CAAC,IAAA,EAAM,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,mBAAA,EAAoB;AAC1D,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACvB,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,gBAAA,EAAmB,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA,EAAG;AAAA,EACnG;AACA,EAAA,IAAI;AACF,IAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,KAAA,EAAO,UAAA,CAAW,GAAG,CAAA,EAAE;AAAA,EAC5C,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,EAC9E;AACF;;;ACvDO,SAAS,aAAa,OAAA,EAAiD;AAC5E,EAAA,OAAO,IAAI,eAAe,OAAO,CAAA;AACnC;AASO,IAAM,WAAA,GAAc;AAMpB,IAAM,UAAA,GAAa","file":"index.cjs","sourcesContent":["/**\n * What beacon takes from the runtime it runs in, each guarded for a runtime\n * that lacks it (a browser, an edge worker, Deno without permissions):\n * environment variables, Node's `http`, timers that hold no process, a small\n * GET in the background, and log lines written once per process.\n *\n * Nothing here is imported from `node:*`: beacon's main entry must load where\n * Node is not, and its source typecheck without Node's types. Node's modules\n * are loaded when they are used, out of sight of bundlers.\n */\n\n/*\n * The few parts of Node's `http` used here, declared locally and not imported\n * from `node:http`: beacon's source also typechecks without Node's types, in a\n * consumer with only the DOM library.\n */\nexport interface NodeSocket {\n unref(): void\n setKeepAlive(enable: boolean, initialDelay: number): void\n}\nexport interface NodeResponse {\n statusCode?: number\n headers: Record<string, string | string[] | undefined>\n setEncoding(encoding: 'utf8'): void\n on(event: 'data', listener: (chunk: string) => void): void\n on(event: 'end' | 'close', listener: () => void): void\n on(event: 'error', listener: (err: unknown) => void): void\n resume(): void\n destroy(): void\n}\nexport interface NodeRequest {\n on(event: 'socket', listener: (socket: NodeSocket) => void): void\n on(event: 'error', listener: (err: unknown) => void): void\n end(): void\n destroy(): void\n}\nexport type HttpModule = {\n request: (url: URL, options: { method: 'GET', headers: Record<string, string>, agent: false }, callback: (res: NodeResponse) => void) => NodeRequest\n}\ntype Globals = {\n process?: {\n versions?: { node?: unknown }\n env?: Record<string, string | undefined>\n getBuiltinModule?: (id: string) => unknown\n }\n window?: unknown\n document?: unknown\n navigator?: { userAgent?: unknown }\n}\n\ntype Timer = ReturnType<typeof setTimeout>\n/** What a Node timer adds to the handle; absent from the DOM's `number`. */\nexport type NodeTimer = { unref?: () => void, refresh?: () => void }\n\n/** The most of a response body `getJson` reads. */\nconst BODY_LIMIT = 16 * 1024\n\n/**\n * The environment variables, or `{}` where there are none (a browser) or\n * reading them throws (Deno without `--allow-env`).\n */\nexport function environment(): Record<string, string | undefined> {\n try {\n return (globalThis as Globals).process?.env ?? {}\n }\n catch {\n return {}\n }\n}\n\n/** One environment variable, trimmed; `undefined` when unset or blank. */\nexport function readEnv(name: string): string | undefined {\n try {\n const value = environment()[name]\n return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined\n }\n catch {\n return undefined\n }\n}\n\n/** Whether this runtime speaks Node's `http`: Node (or one that passes for it), not a browser or a worker. */\nexport function nodeRuntime(): boolean {\n const g = globalThis as Globals\n if (typeof g.window !== 'undefined' || typeof g.document !== 'undefined') return false\n if (g.navigator?.userAgent === 'Cloudflare-Workers') return false\n return typeof g.process?.versions?.node === 'string'\n}\n\n/**\n * A Node builtin (`node:fs`), synchronously, or `undefined` where there is\n * none: not Node, or a Node before 22.3 (`process.getBuiltinModule`).\n */\nexport function nodeBuiltin(id: string): unknown {\n try {\n const proc = (globalThis as Globals).process\n return typeof proc?.getBuiltinModule === 'function' ? proc.getBuiltinModule(id) : undefined\n }\n catch {\n return undefined\n }\n}\n\n/**\n * Loads Node's `http` or `https` only when a request is made, and out of\n * sight of bundlers: the package must load where neither exists (an edge\n * runtime, a browser), and never gets here there.\n */\nexport async function loadHttp(protocol: string): Promise<HttpModule> {\n const name = protocol === 'https:' ? 'node:https' : 'node:http'\n const builtin = nodeBuiltin(name)\n if (builtin) return builtin as HttpModule\n return (await import(/* webpackIgnore: true */ /* @vite-ignore */ name)) as HttpModule\n}\n\n/** A timer that holds no process: a script ends whether or not it is due. */\nexport function unrefTimer(run: () => void, ms: number): Timer {\n const timer = setTimeout(run, ms)\n ;(timer as unknown as NodeTimer).unref?.()\n return timer\n}\n\n/**\n * The headers a client sends with every request, names in lower case: the\n * key, then the client's extra headers, which may override it.\n */\nexport function sentHeaders(apiKey: string, extra: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = { authorization: `Bearer ${apiKey}` }\n for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value\n return headers\n}\n\n/**\n * Who a client is to the studio: the server and the credentials it actually\n * sends (`headers` may override the key's Authorization). What the live\n * connection, the file cache's folder and the dev log line are each kept\n * per. Holds the key: hash it before it goes anywhere outside the process.\n */\nexport function identityOf(baseUrl: string, headers: Record<string, string>): string {\n return `${baseUrl}\\n${headers.authorization ?? ''}`\n}\n\n/**\n * A GET of a JSON body over Node's `http`, in the background: the parsed body\n * of a `200`, `undefined` for anything else (an error, another status, a body\n * that is no JSON or larger than `BODY_LIMIT`, no answer within `timeoutMs`).\n * Settles exactly once, and its socket and timer are unref'd: a script whose\n * last read set it off ends without waiting for it.\n */\nexport function getJson(http: HttpModule, url: URL, headers: Record<string, string>, timeoutMs: number): Promise<unknown> {\n return new Promise((resolve) => {\n let req: NodeRequest | undefined\n let settled = false\n const finish = (body?: unknown): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n try {\n req?.destroy()\n }\n catch {\n /* already gone */\n }\n resolve(body)\n }\n const timer = unrefTimer(() => finish(), timeoutMs)\n try {\n req = http.request(url, { method: 'GET', headers, agent: false }, (res) => {\n res.on('error', () => finish())\n if (res.statusCode !== 200) {\n res.resume()\n finish()\n return\n }\n let body = ''\n res.setEncoding('utf8')\n res.on('data', (chunk: string) => {\n body += chunk\n if (body.length > BODY_LIMIT) finish()\n })\n res.on('end', () => finish(parseJson(body)))\n res.on('close', () => finish())\n })\n req.on('socket', (socket) => {\n try {\n socket.unref()\n }\n catch {\n /* a short request; the timer still ends it */\n }\n })\n req.on('error', () => finish())\n req.end()\n }\n catch {\n finish()\n }\n })\n}\n\nexport function parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n }\n catch {\n return undefined\n }\n}\n\n/**\n * The lines already written, per process: on `globalThis`, so a dev server\n * that reloads this module (and builds a new client each time) does not\n * write them again. When what a key names changes, so does the number.\n */\nconst WRITTEN = Symbol.for('@nordhavnhq/beacon/written/1')\n\n/**\n * Whether `key` is new to this process, noting it if so: for what is said\n * once per process (a log line), however many clients come and go.\n */\nexport function firstTime(key: string): boolean {\n const scope = globalThis as unknown as Record<symbol, Set<string> | undefined>\n let seen = scope[WRITTEN]\n if (!seen) {\n seen = new Set()\n scope[WRITTEN] = seen\n }\n if (seen.has(key)) return false\n seen.add(key)\n return true\n}\n\n/**\n * Where beacon's lines go: the client's `logger` option. Both methods are\n * optional; a missing one drops that level.\n */\nexport interface Logger {\n info?(...args: unknown[]): void\n warn?(...args: unknown[]): void\n}\n\n/** The `logger` option as used: the console by default, `undefined` for `false` (nothing is written). */\nexport function loggerOf(option: Logger | false | undefined): Logger | undefined {\n if (option === false) return undefined\n return option ?? console\n}\n\n/**\n * Writes one line through `log`, prefixed with the package name; nothing\n * without a logger or without that level. Never throws: a logger that fails\n * must not fail the read that wrote to it.\n */\nexport function logLine(log: Logger | undefined, level: 'info' | 'warn', message: string, ...rest: unknown[]): void {\n try {\n const write = log?.[level]\n if (typeof write === 'function') write.call(log, `[@nordhavnhq/beacon] ${message}`, ...rest)\n }\n catch {\n /* the logger's own problem */\n }\n}\n","/**\n * In development, one line on the console naming the project the key belongs\n * to: `connected to \"<project>\" (key \"<key>\")`. A site started with the `.env`\n * of another site shows that other project's content without any error; this\n * line is where the developer sees it.\n *\n * Asked of `GET /api/content/project` on a client's first read, in the\n * background and over an unref'd socket, like the live connection's safety\n * check: no read waits on it, no process is held by it, and whatever goes\n * wrong (an older server's `404`, a refused key, no answer) is silent. Once\n * per server and credentials in a process (`firstTime`), so a dev server\n * that builds a new client on every reload says it once.\n *\n * Never in production: a project's name has no business in the logs of\n * another environment.\n */\nimport { environment, firstTime, getJson, identityOf, loadHttp, logLine, nodeRuntime, type Logger } from './runtime'\n\n/** The longest the question may take; it holds nothing up either way. */\nconst PROJECT_TIMEOUT_MS = 3_000\n/** The most of a name written to the log. */\nconst NAME_LIMIT = 200\n\n/**\n * Whether this process is a developer's: `NODE_ENV` set to `development`\n * (as Vite, Astro, Next.js and Nuxt set it for their dev servers), and not a\n * CI job. Asked positively, not as \"not production\": a production container\n * often runs without `NODE_ENV` at all.\n */\nexport function isDevelopment(env: Record<string, string | undefined>): boolean {\n if (env.NODE_ENV?.trim().toLowerCase() !== 'development') return false\n const ci = env.CI?.trim().toLowerCase()\n return ci === undefined || ci === '' || ci === '0' || ci === 'false'\n}\n\n/** Whether a client says which project it reads: with somewhere to say it (`logger`), in development. */\nexport function wantAnnounce(settings: { log: Logger | undefined, customFetch: boolean }): boolean {\n try {\n // A custom `fetch` is skipped by Node's `http`, as by the live connection.\n return typeof settings.log?.info === 'function' && !settings.customFetch && nodeRuntime() && isDevelopment(environment())\n }\n catch {\n return false\n }\n}\n\n/** Asks which project `headers` reads, and writes the line to `log`. Never throws, never waits. */\nexport function announceProject(baseUrl: string, headers: Record<string, string>, log: Logger | undefined): void {\n try {\n if (!firstTime(`project\\n${identityOf(baseUrl, headers)}`)) return\n const url = new URL(`${baseUrl}/api/content/project`)\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return\n loadHttp(url.protocol)\n .then(http => getJson(http, url, { ...headers, accept: 'application/json' }, PROJECT_TIMEOUT_MS))\n .then((body) => {\n const line = projectLine(body)\n if (line) logLine(log, 'info', line)\n }, () => {})\n }\n catch {\n /* nothing to say */\n }\n}\n\n/** The line for a `/project` answer, or `undefined` for anything else. */\nfunction projectLine(body: unknown): string | undefined {\n const answer = body as { project?: { name?: unknown }, key?: { name?: unknown } } | undefined\n const project = printable(answer?.project?.name)\n if (!project) return undefined\n const key = printable(answer?.key?.name)\n return key ? `connected to \"${project}\" (key \"${key}\")` : `connected to \"${project}\"`\n}\n\n/** A name fit for one log line: no control characters, not endless. */\nfunction printable(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n // eslint-disable-next-line no-control-regex\n const text = value.replace(/[\\u0000-\\u001F\\u007F]+/g, ' ').trim().slice(0, NAME_LIMIT)\n return text === '' ? undefined : text\n}\n","/**\n * Read caching for the content client. GET responses (schema, record lists,\n * single records, queries) are cached by request key and kept fresh by\n * conditional revalidation: each entry stores the studio's `ETag`, which the\n * client sends back as `If-None-Match`. A cheap project-wide stamp gates whether\n * a revalidation is even attempted, so a stable site serves straight from cache.\n *\n * Swap in a custom `CacheStore` to share a cache across client instances or to\n * back it with something persistent.\n */\n\nexport interface CacheEntry {\n value: unknown\n /**\n * The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`\n * to revalidate: a `304` means the stored value is still current.\n */\n etag?: string\n /**\n * The project stamp this entry was last confirmed current against. When it\n * equals the client's latest known stamp, the entry is served without any\n * network call at all.\n */\n validatedVersion?: string\n /** Epoch ms when the entry expires. `0` means it never expires. */\n expiresAt: number\n /**\n * Epoch ms before which a failed refetch is not retried: until then the entry\n * is served as-is. Set after a transient error, cleared by a fresh value or a\n * `304`.\n */\n retryAt?: number\n}\n\n/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */\nexport interface CacheStore {\n get(key: string): CacheEntry | undefined\n set(key: string, entry: CacheEntry): void\n delete(key: string): void\n /** Iterate current keys (used for prefix invalidation). */\n keys(): Iterable<string>\n clear(): void\n}\n\nexport interface CacheOptions {\n /** Master switch. Default `true`. */\n enabled?: boolean\n /**\n * How long a cached entry survives, in ms. Default `604800000` (7 days).\n *\n * This is NOT how long until content refreshes - revalidation keeps entries\n * current within `revalidate` (seconds) whenever the studio is reachable. The\n * TTL only decides when an entry stops being served blindly and the next read\n * must refetch it. If that refetch fails transiently (studio down, 5xx,\n * network), the expired value is served anyway, so a studio outage degrades\n * to \"slightly stale\" rather than \"site errors\" however long it lasts.\n *\n * The one case where it bounds staleness directly is when revalidation is off\n * (`revalidate: false`) or the server has no `/version` endpoint: then content\n * can be up to `ttl` old while the studio is reachable. `0` = never expire.\n */\n ttl?: number\n /**\n * Minimum ms between two project-stamp checks. Default `60000` (1 minute) -\n * this is the freshness window for PUBLIC visitors (an edit is picked up on\n * the next check after it lands). A read with `{ cache: false }` skips the\n * wait.\n *\n * The check fires only on a read and is throttled, so a quiet site barely\n * checks at all; the interval only caps the busy case. Each check costs the\n * studio a small API-key lookup, so raise it (a few minutes) if you run many\n * frontends; lower it for a tighter public window. `false` disables checking\n * and leaves you with pure TTL expiry.\n */\n revalidate?: number | false\n /**\n * How long a read that already holds a cached value waits on the studio for a\n * fresher one, in ms. Default `1000`. Past it the read gets the cached value\n * and the refresh finishes in the background, so the next read has it.\n *\n * It keeps a slow or hanging studio from slowing your pages down: without it\n * every read after an edit waits for as long as the studio takes, up to\n * `timeout`. The price is that on a slow studio an edit shows one read later.\n *\n * `0` never waits (always serve the cached value, refresh in the background).\n * `false` waits for the studio; choose it where work cannot outlive the\n * request, as on serverless platforms that freeze the process once the\n * response is out. A read with nothing cached always waits.\n */\n waitForFresh?: number | false\n /** Soft cap on entries; oldest are evicted first. Default `500`. */\n maxEntries?: number\n /**\n * Custom backing store. Defaults to an in-memory store. A `FileCacheStore`\n * passed to a client is kept per key, as the client's `cache.dir` is; a\n * store of your own gets the cache keys as they are, so one shared by\n * several sites must keep them apart itself.\n */\n store?: CacheStore\n}\n\n/** An `expiresAt` that is always in the past (`0` would mean \"never expires\"). */\nconst EXPIRED = 1\n\n/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */\nexport class MemoryCacheStore implements CacheStore {\n private map = new Map<string, CacheEntry>()\n\n constructor(private maxEntries = 500) {}\n\n get(key: string): CacheEntry | undefined {\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n // Re-insert so recently written keys are considered newest.\n this.map.delete(key)\n this.map.set(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.map.delete(oldest)\n }\n }\n\n delete(key: string): void {\n this.map.delete(key)\n }\n\n keys(): Iterable<string> {\n return this.map.keys()\n }\n\n clear(): void {\n this.map.clear()\n }\n}\n\n/**\n * Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation\n * bookkeeping (etag + validated stamp), and prefix invalidation, so the client\n * only deals in cache keys.\n */\nexport class ContentCache {\n readonly enabled: boolean\n private ttl: number\n /** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */\n private retryDelay: number\n private store: CacheStore\n\n constructor(opts: CacheOptions = {}) {\n this.enabled = opts.enabled ?? true\n this.ttl = opts.ttl ?? 604_800_000\n this.retryDelay = typeof opts.revalidate === 'number' && opts.revalidate > 0 ? opts.revalidate : 60_000\n this.store = opts.store ?? new MemoryCacheStore(opts.maxEntries ?? 500)\n }\n\n /**\n * The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the\n * whole entry (value + etag + validated stamp) so the client can decide\n * whether to serve it, revalidate it, or fall back to it on error.\n *\n * An expired entry is left in the store (the refetch overwrites it, or\n * `maxEntries` evicts it) so `stale` can still fall back to it.\n */\n peek(key: string, now: number): CacheEntry | undefined {\n const entry = this.stale(key)\n if (!entry) return undefined\n if (entry.expiresAt !== 0 && entry.expiresAt <= now) return undefined\n return entry\n }\n\n /**\n * The entry for `key` whether or not its TTL has run out: the last good value\n * to serve when a refetch fails transiently.\n */\n stale(key: string): CacheEntry | undefined {\n if (!this.enabled) return undefined\n return this.store.get(key)\n }\n\n /** Store a freshly fetched value with its validator and the stamp it is current against. */\n set(key: string, value: unknown, opts: { etag?: string, version?: string }, now: number): void {\n if (!this.enabled) return\n this.store.set(key, {\n value,\n etag: opts.etag,\n validatedVersion: opts.version,\n expiresAt: this.ttl === 0 ? 0 : now + this.ttl,\n })\n }\n\n /**\n * Record that an existing entry is still current as of `version` (after a\n * `304`), refreshing its TTL without touching the value. No-op if it is gone.\n */\n confirm(key: string, version: string | undefined, now: number): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.validatedVersion = version\n entry.expiresAt = this.ttl === 0 ? 0 : now + this.ttl\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /**\n * Record that refetching `key` from `from` just failed transiently, so reads\n * serve it as-is for a while instead of each waiting on an unreachable studio.\n * Returns the entry to serve: `from`, or the newer one a concurrent read stored\n * in the meantime (left unpaused, since its own fetch succeeded).\n */\n backoff(key: string, from: CacheEntry, now: number): CacheEntry {\n const entry = this.store.get(key)\n if (!entry) return from\n // Compare fields, not identity: a custom store may hand back copies.\n if (entry.etag !== from.etag || entry.expiresAt !== from.expiresAt) return entry\n entry.retryAt = now + this.retryDelay\n this.store.set(key, entry)\n return entry\n }\n\n /**\n * Mark `key` as due for a refetch while keeping its value to fall back on:\n * the next read asks the studio again whatever the stamp says, and still\n * serves this value if the studio does not answer. For when the stored value\n * may be outdated but there is no telling - dropping it would throw away the\n * only thing left to show during an outage. No-op for a key that is not held.\n */\n expire(key: string): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.expiresAt = EXPIRED\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /** `expire` for every key that starts with `prefix`. */\n expirePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.expire(key)\n }\n }\n\n /** Drop one exact key. */\n delete(key: string): void {\n this.store.delete(key)\n }\n\n /** Drop every key that starts with `prefix`. */\n deletePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.store.delete(key)\n }\n }\n\n clear(): void {\n this.store.clear()\n }\n}\n","/**\n * Error thrown for any non-2xx response from the content API. `status` carries\n * the HTTP status code so callers can branch (401 bad key, 403 out of scope,\n * 404 missing node/dataset/record, 422 query failed). `code` says more where\n * the studio sends one: why an upload was refused, for example\n * (`upload_too_large`).\n */\nexport class NordhavnError extends Error {\n readonly status: number\n /** The raw parsed response body, when the server returned one. */\n readonly body: unknown\n /**\n * The studio's code for this error (`data.code` in the body), when it sent\n * one, else `undefined`. Unlike the message it never changes wording, so it\n * is what a site branches on: the upload codes are `upload_type_not_allowed`,\n * `upload_content_invalid`, `upload_too_large` and the ones about the field.\n */\n readonly code: string | undefined\n\n constructor(message: string, status: number, body?: unknown) {\n super(message)\n this.name = 'NordhavnError'\n this.status = status\n this.body = body\n this.code = errorCode(body)\n // Restore prototype chain for `instanceof` when transpiled to ES5.\n Object.setPrototypeOf(this, NordhavnError.prototype)\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401\n }\n\n get isForbidden(): boolean {\n return this.status === 403\n }\n\n get isNotFound(): boolean {\n return this.status === 404\n }\n}\n\n/** `data.code` of an error body, when it is a non-empty string. */\nfunction errorCode(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined\n const data = (body as { data?: unknown }).data\n if (typeof data !== 'object' || data === null) return undefined\n const code = (data as { code?: unknown }).code\n return typeof code === 'string' && code !== '' ? code : undefined\n}\n\n/**\n * Whether an error body was written by the studio, and not by something\n * answering in its place (a proxy's `404 page not found`, a WAF's HTML page, a\n * gateway's own JSON). The studio's errors are JSON objects that restate their\n * status (`{ \"statusCode\": 404, \"message\": \"...\" }`); `status` is accepted next\n * to `statusCode`, the name newer server frameworks give the same field.\n */\nexport function isStudioBody(status: number, body: unknown): boolean {\n if (typeof body !== 'object' || body === null) return false\n const b = body as { statusCode?: unknown, status?: unknown }\n return b.statusCode === status || b.status === status\n}\n","/**\n * The decisions of the live connection, as plain functions: whether a client\n * goes live by default, and how long to wait after a connection attempt ended\n * before the next one. `live.ts` does the I/O.\n *\n * No imports and only erasable TypeScript, so its test can load the source as\n * it is and walk every branch without a server or a clock.\n */\n\n/** Every number the live connection runs on. */\nexport const LIVE = {\n /**\n * No message (a version or a ping) for this long and the connection counts\n * as dead. The studio pings every 25 s, so this is two missed pings and then\n * some: a frozen process, a proxy that holds the stream without passing it on.\n */\n staleMs: 60_000,\n /**\n * A connection that stayed up this long, and heard from the studio, resets\n * the backoff. One that is accepted and then closed sooner counts as a\n * failure, so accept-then-close cannot loop.\n */\n stableMs: 60_000,\n /**\n * Even while the connection is healthy, it is checked against the stamp\n * itself this often (once per connection, in the background, never awaited\n * by a read): a safety net for a change the stream missed. It should never\n * miss one, but one missed would otherwise stay unseen until the stream ends.\n */\n safetyPollMs: 5 * 60_000,\n /**\n * How long the stream may stay behind a check that found the studio ahead\n * before it counts as having missed a change and is replaced. The studio\n * sends a change up to 5.25 s late on purpose (at most once per 5 s per\n * project), so a stream that is merely behind catches up well within this.\n */\n lagToleranceMs: 10_000,\n /** The longest that check may take; it runs on an unref'd socket, so it never holds a process. */\n safetyProbeTimeoutMs: 3_000,\n /** The longest the studio may take to answer the connection with its headers. */\n connectTimeoutMs: 10_000,\n /** After the studio ended a connection that lived its full term: wait 1 to 5 s. */\n cleanMinMs: 1_000,\n cleanMaxMs: 5_000,\n /** After a failure: at least 1 s, then a window that doubles per failure, up to 30 s. */\n backoffBaseMs: 1_000,\n backoffMaxMs: 30_000,\n /** `Retry-After` is honoured within these bounds. */\n retryAfterMinMs: 30_000,\n retryAfterMaxMs: 60 * 60_000,\n /** A `429` without `Retry-After` waits as long as the studio itself asks for. */\n rateLimitedMs: 5 * 60_000,\n /** The most added at random to a long wait, so the sites refused together do not return together. */\n longJitterMs: 60_000,\n} as const\n\n/** How a connection attempt ended. */\nexport type LiveOutcome =\n /** The studio ended the stream properly (its lifetime is up, or the key changed). */\n | { kind: 'closed' }\n /** A network error, a timeout, a dropped connection, a stream that is not the studio's. */\n | { kind: 'failed' }\n /** Nothing heard for `LIVE.staleMs`. */\n | { kind: 'silent' }\n /** Answered with something other than the stream. */\n | {\n kind: 'refused'\n status: number\n /** Whether the body is the studio's own JSON error (see `isStudioBody`). */\n studio: boolean\n /** The `Retry-After` header as sent, `null` without one. */\n retryAfter: string | null\n }\n\n/** When to try the next connection, and the failures in a row that counts as. */\nexport interface LivePlan {\n delay: number\n attempts: number\n}\n\nexport interface LivePlanContext {\n /** Failures in a row so far. */\n attempts: number\n /** Whether the connection that just ended was stable (see `LIVE.stableMs`). */\n stable: boolean\n /** How long a server without the stream is left alone (`UNSUPPORTED_PAUSE_MS`). */\n pauseMs: number\n now: number\n random: () => number\n}\n\n/**\n * When to try again after a connection attempt. Never a final verdict: what\n * the studio answered may change while the process runs (a key enabled again,\n * a server that gains the stream), and a site should not need a restart to\n * notice.\n *\n * - closed by the studio after a stable connection: a few seconds;\n * - a network error, a `5xx`, anything that is not the studio speaking (a\n * proxy's `404` page, a WAF's `403`, a `200` that is no stream), an early\n * close, silence: exponential backoff with jitter, 1 s to 30 s;\n * - `429`, or a `503` with `Retry-After`: as asked, within 30 s and 1 hour,\n * plus jitter;\n * - the studio's own `401` or `403` (the key disabled, deleted, or left with\n * no read scope), its own `404` (a server without the stream), another of\n * its `4xx`, or a redirect: the long pause, as for a server without\n * `/version`. Reads report a refused key themselves, and keep to the poll.\n */\nexport function planReconnect(outcome: LiveOutcome, ctx: LivePlanContext): LivePlan {\n const attempts = ctx.stable ? 0 : ctx.attempts\n if (outcome.kind === 'closed' && ctx.stable) {\n return { delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 }\n }\n if (outcome.kind === 'refused') return planRefused(outcome, { ...ctx, attempts })\n return backoff(attempts, ctx.random)\n}\n\n/** `planReconnect` for an answer other than the stream. */\nfunction planRefused(outcome: Extract<LiveOutcome, { kind: 'refused' }>, ctx: LivePlanContext): LivePlan {\n const { status, studio } = outcome\n const asked = parseRetryAfter(outcome.retryAfter, ctx.now)\n if (status === 429 || (status === 503 && asked !== undefined)) {\n const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs)\n return { delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts }\n }\n const studioRefusal = studio && status >= 400 && status < 500 && status !== 408\n if (studioRefusal || (status >= 300 && status < 400)) {\n return { delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts }\n }\n return backoff(ctx.attempts, ctx.random)\n}\n\n/** At least `backoffBaseMs`, plus full jitter over a window that doubles per failure, capped. */\nfunction backoff(attempts: number, random: () => number): LivePlan {\n const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16)\n const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window)\n return { delay, attempts: attempts + 1 }\n}\n\nfunction longJitter(wait: number, random: () => number): number {\n return random() * Math.min(LIVE.longJitterMs, wait / 5)\n}\n\nfunction between(min: number, max: number, random: () => number): number {\n return min + random() * (max - min)\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value))\n}\n\n/** An HTTP date as RFC 9110 has it sent (IMF-fixdate): `Sun, 06 Nov 1994 08:49:37 GMT`. */\nconst 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$/\n\n/**\n * `Retry-After` in ms from `now`: a whole number of seconds, or an HTTP date\n * in the one form servers must send (IMF-fixdate). `undefined` without one,\n * and for anything else (`1.5`, `-5`, `soon`, a date in another form): a\n * value nobody can be sure how to read is treated as absent, not guessed at.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number): number | undefined {\n const text = value?.trim()\n if (!text) return undefined\n if (/^\\d+$/.test(text)) return Number(text) * 1000\n if (!IMF_FIXDATE.test(text)) return undefined\n const at = Date.parse(text)\n return Number.isNaN(at) ? undefined : Math.max(0, at - now)\n}\n\n/**\n * Environment variables that say this process is short-lived or frozen between\n * requests, so a connection held open would mostly cost the studio a slot:\n *\n * - `VERCEL`, `NETLIFY`, `AWS_LAMBDA_FUNCTION_NAME` and `LAMBDA_TASK_ROOT`\n * (Lambda, also under Netlify's functions), `FUNCTIONS_WORKER_RUNTIME`\n * (Azure Functions), `FUNCTION_TARGET` (Google Cloud Functions),\n * `DENO_DEPLOYMENT_ID` (Deno Deploy);\n * - `K_SERVICE`: Google Cloud Run (and Cloud Functions on it). Its processes\n * run between requests only with \"CPU always allocated\", which is not the\n * default, and it scales out to many instances that would each hold one of\n * the key's 50 connections. A service set up to stay warm turns `live` on;\n * - `CI`: a build or a test job. It ends in minutes, and a framework building\n * in many workers would hold a connection per worker, from the same 50 the\n * site's own processes need.\n *\n * A variable counts when it is set to anything but empty, `0` or `false`.\n */\nexport const SHORT_LIVED_ENV = [\n 'VERCEL',\n 'NETLIFY',\n 'AWS_LAMBDA_FUNCTION_NAME',\n 'LAMBDA_TASK_ROOT',\n 'FUNCTIONS_WORKER_RUNTIME',\n 'FUNCTION_TARGET',\n 'DENO_DEPLOYMENT_ID',\n 'K_SERVICE',\n 'CI',\n] as const\n\n/** Whether one of `SHORT_LIVED_ENV` is set in `env`. */\nexport function isShortLived(env: Record<string, string | undefined>): boolean {\n return SHORT_LIVED_ENV.some((name) => {\n const value = env[name]?.trim().toLowerCase()\n return value !== undefined && value !== '' && value !== '0' && value !== 'false'\n })\n}\n\nexport interface LiveChoice {\n /** The `live` option as given. */\n option: boolean | undefined\n /** Whether this runtime can hold the connection: Node's `http`, not a browser. */\n runtime: boolean\n /** Whether the client checks the stamp at all (a cache, `revalidate` not off). */\n revalidating: boolean\n /** Whether a custom `fetch` was passed. */\n customFetch: boolean\n /** `cache.waitForFresh: false`: the host asked that nothing outlives a read. */\n waitsForStudio: boolean\n env: Record<string, string | undefined>\n}\n\n/**\n * Whether a client goes live. Never where it cannot (no Node `http`, a browser)\n * or where it would serve no purpose (no cache, `revalidate: false`). Else\n * `live: true` and `live: false` decide. By default it is on, except where the\n * process does not live on between requests (`SHORT_LIVED_ENV`, or\n * `waitForFresh: false`, which says as much), and with a custom `fetch`: the\n * stream goes over Node's `http` and not through that `fetch`, so it would skip\n * whatever the `fetch` adds (a proxy, a header, a test's fake studio).\n */\nexport function chooseLive(choice: LiveChoice): boolean {\n if (!choice.runtime || !choice.revalidating || choice.option === false) return false\n if (choice.option === true) return true\n return !choice.customFetch && !choice.waitsForStudio && !isShortLived(choice.env)\n}\n","/**\n * A small parser for server-sent events, enough for the live connection\n * (`GET /api/content/events`). Fed text as it arrives, in chunks that may end\n * anywhere (mid-line, between a `\\r` and its `\\n`), it hands back the complete\n * events. It follows the WHATWG rules that matter here: lines end in `\\n`,\n * `\\r\\n` or `\\r`; a line starting with `:` is a comment; `data` lines add up,\n * joined with `\\n`; a blank line ends the event; `id`, `retry` and unknown\n * fields are ignored. An event without `data` lines is dropped, as a browser\n * does.\n *\n * No imports and only erasable TypeScript, so its test can load the source as\n * it is.\n */\n\nexport interface SseEvent {\n /** The `event` field, `message` when the event named none. */\n event: string\n data: string\n}\n\n/** The most text the parser holds while waiting for the end of a line or an event. */\nconst DEFAULT_LIMIT = 64 * 1024\n\nexport class SseParser {\n private buffer = ''\n private data: string[] = []\n private dataSize = 0\n private event = ''\n private started = false\n /** The last chunk ended in `\\r`: a `\\n` that starts the next one belongs to it. */\n private afterCr = false\n private readonly limit: number\n\n constructor(limit: number = DEFAULT_LIMIT) {\n this.limit = limit\n }\n\n /**\n * The events completed by `chunk`, in order. `null` once more than the limit\n * is waiting for a line or an event to end: a stream like that is not the\n * studio's, and the caller drops the connection rather than the memory.\n */\n feed(chunk: string): SseEvent[] | null {\n const text = this.prepare(this.buffer + chunk)\n const out: SseEvent[] = []\n let pos = 0\n const breaks = { cr: text.indexOf('\\r'), lf: text.indexOf('\\n') }\n while (pos < text.length) {\n const end = nextBreak(text, pos, breaks)\n if (end === -1) break\n let next = end + 1\n if (text.charCodeAt(end) === 13) {\n // A `\\r` that ends the text may be the first half of a `\\r\\n` split\n // over two chunks: the line ends here, and a `\\n` up next is skipped.\n if (end + 1 === text.length) this.afterCr = true\n else if (text.charCodeAt(end + 1) === 10) next = end + 2\n }\n this.line(text.slice(pos, end), out)\n pos = next\n }\n this.buffer = text.slice(pos)\n if (this.buffer.length > this.limit || this.dataSize > this.limit) return null\n return out\n }\n\n /** Drops the `\\n` of a `\\r\\n` split over two chunks, and a byte order mark at the start. */\n private prepare(text: string): string {\n let out = text\n if (this.afterCr && out.length > 0) {\n this.afterCr = false\n if (out.charCodeAt(0) === 10) out = out.slice(1)\n }\n if (!this.started && out.length > 0) {\n this.started = true\n if (out.charCodeAt(0) === 0xFEFF) out = out.slice(1)\n }\n return out\n }\n\n private line(line: string, out: SseEvent[]): void {\n if (line === '') {\n if (this.data.length > 0) out.push({ event: this.event || 'message', data: this.data.join('\\n') })\n this.data = []\n this.dataSize = 0\n this.event = ''\n return\n }\n if (line.charCodeAt(0) === 58) return\n const colon = line.indexOf(':')\n const field = colon === -1 ? line : line.slice(0, colon)\n let value = colon === -1 ? '' : line.slice(colon + 1)\n if (value.charCodeAt(0) === 32) value = value.slice(1)\n if (field === 'event') this.event = value\n else if (field === 'data') {\n this.data.push(value)\n this.dataSize += value.length + 1\n }\n }\n}\n\n/**\n * Where the next line ends from `pos` on: the first `\\r` or `\\n`, `-1` when\n * there is none yet. `breaks` remembers the last ones found, so a long text is\n * searched once and not once per line.\n */\nfunction nextBreak(text: string, pos: number, breaks: { cr: number, lf: number }): number {\n if (breaks.cr !== -1 && breaks.cr < pos) breaks.cr = text.indexOf('\\r', pos)\n if (breaks.lf !== -1 && breaks.lf < pos) breaks.lf = text.indexOf('\\n', pos)\n const { cr, lf } = breaks\n return cr === -1 ? lf : lf === -1 ? cr : Math.min(cr, lf)\n}\n","/**\n * Project-stamp tracker: the cheap gate in front of conditional revalidation.\n *\n * The cache lives in YOUR process, so the studio cannot push an invalidation\n * into it. Instead it publishes a stamp per project at `GET /api/content/version`\n * that changes on every content edit. This tracker fetches that stamp at most\n * once per interval (one tiny request regardless of read volume) and exposes the\n * latest value it has seen.\n *\n * The client uses it as a gate: while the stamp is unchanged, cached entries are\n * served with no network at all; when it moves, entries revalidate individually\n * with `If-None-Match` (a `304` keeps the cached value, a `200` replaces it). If\n * the stamp check itself fails - studio down, network blip - the last known\n * stamp stands, so the cache keeps serving instead of hammering a dead endpoint.\n *\n * Where the client holds a live connection (`live.ts`), the stamps it hears are\n * fed in with `observe` and the probe is skipped while that connection is\n * healthy; the probe is the fallback for when it is not.\n */\n\nexport type VersionProbe = () => Promise<string>\n\n/** How long a server without the version route silences the check. */\nexport const UNSUPPORTED_PAUSE_MS = 15 * 60_000\n\nexport class VersionTracker {\n private lastChecked = 0\n private version: string | null = null\n private inFlight: Promise<void> | null = null\n /**\n * Epoch ms before which we do not ask again, after the server turned out\n * to have no version route. A pause and not a final verdict: an old server\n * costs one request per pause, and one that gains the route is picked up\n * without a restart.\n */\n private pausedUntil = 0\n\n constructor(\n private readonly probe: VersionProbe,\n /** Minimum ms between two probes. `0` disables checking entirely. */\n private readonly interval: number,\n /**\n * Whether a probe failure means \"this server has no version route\", as\n * opposed to \"could not be reached\". The caller decides, as only it can\n * tell the server's own `404` from the one a proxy answers with while\n * the server is away - and that one must not pause anything: the server\n * is back in seconds, and freshness would stay off for the whole pause.\n */\n private readonly isUnsupported: (err: unknown) => boolean = (err) => (err as { status?: number } | null)?.status === 404,\n ) {}\n\n /** The most recent stamp seen, or `null` before the first successful probe. */\n current(): string | null {\n return this.version\n }\n\n /**\n * A stamp heard from the live connection, current as of `at`. It counts as a\n * check made at that moment: the next probe is due one interval after it.\n * Never a request of its own, and never a reason for one.\n */\n observe(version: string, at: number): void {\n this.version = version\n this.lastChecked = Math.max(this.lastChecked, at)\n }\n\n /**\n * Makes the next `refresh` ask at once, whatever the interval says (still\n * not during the pause for a server without the route). For when the stamp\n * may have moved unseen: the live connection went silent.\n */\n due(): void {\n this.lastChecked = 0\n }\n\n /**\n * Refresh the stamp if we are due. Resolves once the answer is in, so the\n * read that triggered it sees an up-to-date stamp. A failed probe leaves the\n * last known stamp in place (serve-from-cache rather than thrash).\n *\n * A failed probe counts towards the interval like any other, also when no\n * stamp has ever come in. Otherwise a process that starts while the studio\n * is down (with a persisted cache to serve from) would probe on every read,\n * and against a hanging studio make each of them wait out the probe.\n */\n async refresh(now: number): Promise<void> {\n if (this.interval <= 0 || now < this.pausedUntil) return\n if (this.inFlight) return this.inFlight\n if (now - this.lastChecked < this.interval) return\n\n this.lastChecked = now\n this.inFlight = this.run(now)\n try {\n await this.inFlight\n }\n finally {\n this.inFlight = null\n }\n }\n\n private async run(now: number): Promise<void> {\n try {\n this.version = await this.probe()\n }\n catch (err) {\n // A server that predates the version route: ask again only after a\n // long pause. Any other failure is transient - keep the last stamp\n // so the cache keeps serving, and try again next interval.\n if (this.isUnsupported(err)) {\n this.pausedUntil = now + Math.max(this.interval, UNSUPPORTED_PAUSE_MS)\n }\n }\n }\n}\n","/**\n * The live connection: `GET /api/content/events`, a stream on which the studio\n * pushes the project's stamp the moment it changes, so a site sees an edit at\n * its next visitor instead of up to a minute later.\n *\n * An optimisation on top of the `/version` poll, never a replacement, and\n * built so that it cannot take a site down:\n *\n * - A stamp it hears only feeds the `VersionTracker` (`observe`), at the next\n * read. It never fetches anything itself: revalidation stays lazy, on the\n * read path and by its rules, so fifty sites do not all fetch the moment an\n * editor saves.\n * - While it is healthy, reads skip the poll. When it is not (still\n * connecting, dropped, refused, silent for a minute) they poll as before.\n * - It never keeps a process alive: Node's `http` with the socket unref'd,\n * every timer unref'd. A build or a script ends as it would without it.\n * - It never throws into a read, and leaves no unhandled rejection or `error`\n * event behind.\n * - One connection per server and key in a process, whatever the number of\n * clients (a dev server builds a new one on every reload): the hubs live in\n * a registry on `globalThis`, which outlasts a reloaded copy of this module.\n *\n * The decisions (when it is on, how long to wait after what) are in\n * `live-policy.ts`, the stream parser in `live-sse.ts`.\n */\nimport { isStudioBody } from './errors'\nimport { LIVE, chooseLive, planReconnect, type LiveOutcome } from './live-policy'\nimport { SseParser } from './live-sse'\nimport {\n environment,\n getJson,\n identityOf,\n loadHttp,\n nodeRuntime,\n parseJson,\n sentHeaders,\n unrefTimer,\n type HttpModule,\n type NodeRequest,\n type NodeResponse,\n type NodeTimer,\n} from './runtime'\nimport { UNSUPPORTED_PAUSE_MS, type VersionTracker } from './version'\n\n/** What the connection looks like to a read. */\ninterface LiveView {\n /** Open, and the studio told the stamp on it within `LIVE.staleMs`. */\n healthy: boolean\n /** The stamp heard on the open connection. */\n version: string | undefined\n /** Epoch ms of the last message: the moment `version` is known to be current. */\n at: number\n /** How many times the connection went silent: the stamp may have moved unseen. */\n silences: number\n}\n\n/**\n * A hub as a link sees it. Shared through `globalThis`, so also with a copy of\n * this module from another build (a reload, a second install): when its shape\n * changes, so does the number in `REGISTRY`.\n */\ninterface SharedHub {\n /** Joins a client; returns the hub's `silences`. */\n attach(token: object): number\n /** Leaves; the last one out stops the connection, at once or after `LINGER_MS`. */\n detach(token: object, linger: boolean): void\n view(now: number): LiveView\n /** Checks the open connection against the stamp itself, when that is due (`LIVE.safetyPollMs`). In the background. */\n safetyCheck(now: number): void\n}\n\nconst REGISTRY = Symbol.for('@nordhavnhq/beacon/live-hubs/2')\n\n/** How long a hub that lost its last client to the garbage collector waits for a new one. */\nconst LINGER_MS = 5 * 60_000\n/** The most of an error body read to tell the studio's own from a proxy's. */\nconst REFUSAL_BODY_LIMIT = 16 * 1024\n\ntype Timer = ReturnType<typeof setTimeout>\n\nfunction hubs(): Map<string, SharedHub> {\n const scope = globalThis as unknown as Record<symbol, Map<string, SharedHub> | undefined>\n let map = scope[REGISTRY]\n if (!map) {\n map = new Map()\n scope[REGISTRY] = map\n }\n return map\n}\n\n/** A client that is collected without `close()` leaves its hub, after a grace period. */\nconst collected = typeof FinalizationRegistry === 'function'\n ? new FinalizationRegistry<{ hub: SharedHub, token: object }>(({ hub, token }) => {\n try {\n hub.detach(token, true)\n }\n catch {\n /* nothing to do */\n }\n })\n : undefined\n\n/** Whether a client with these settings goes live (see `chooseLive`). */\nexport function wantLive(settings: { option: boolean | undefined, revalidating: boolean, customFetch: boolean, waitsForStudio: boolean }): boolean {\n try {\n return chooseLive({ ...settings, runtime: nodeRuntime(), env: environment() })\n }\n catch {\n return false\n }\n}\n\n/** A client's handle on the shared connection. Each `NordhavnClient` with `live` has one. */\nexport class LiveLink {\n private hub: SharedHub | undefined\n private readonly token = {}\n private silences = 0\n private closed = false\n private owner: object | undefined\n\n constructor(\n private readonly baseUrl: string,\n private readonly apiKey: string,\n private readonly headers: Record<string, string>,\n owner: object,\n ) {\n this.owner = owner\n }\n\n /**\n * The stamp gate in front of a read, in place of `tracker.refresh`. While\n * the connection is healthy the stamp it heard counts as a fresh check and\n * nothing is fetched; otherwise the poll runs, at once when the connection\n * went silent since the last read. Connects on the first call.\n */\n gate(tracker: VersionTracker, now: number): Promise<void> {\n try {\n const view = this.join()?.view(now)\n if (view?.healthy && view.version !== undefined) {\n tracker.observe(view.version, view.at)\n this.hub?.safetyCheck(now)\n return Promise.resolve()\n }\n if (view && view.silences !== this.silences) {\n this.silences = view.silences\n tracker.due()\n }\n }\n catch {\n /* the poll below is the answer */\n }\n return tracker.refresh(now)\n }\n\n /** Leaves the connection for good; the last client out closes it. */\n close(): void {\n if (this.closed) return\n this.closed = true\n const hub = this.hub\n this.hub = undefined\n this.owner = undefined\n if (!hub) return\n collected?.unregister(this.token)\n try {\n hub.detach(this.token, false)\n }\n catch {\n /* nothing to do */\n }\n }\n\n private join(): SharedHub | undefined {\n if (this.hub || this.closed) return this.hub\n const url = eventsUrl(this.baseUrl)\n if (!url) {\n this.closed = true\n return undefined\n }\n const registry = hubs()\n // Keyed on the credentials actually sent: `headers` may override the\n // key's Authorization, and a client of another project must never share\n // (and so trust) this project's stream.\n const headers = liveHeaders(this.apiKey, this.headers)\n const id = identityOf(this.baseUrl, headers)\n let hub = registry.get(id)\n if (!hub) {\n hub = new LiveHub(id, url, headers)\n registry.set(id, hub)\n }\n this.silences = hub.attach(this.token)\n if (this.owner) collected?.register(this.owner, { hub, token: this.token }, this.token)\n this.owner = undefined\n this.hub = hub\n return hub\n }\n}\n\nfunction eventsUrl(baseUrl: string): URL | undefined {\n try {\n const url = new URL(`${baseUrl}/api/content/events`)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined\n }\n catch {\n return undefined\n }\n}\n\n/**\n * The headers of the stream: the key, the client's extra headers (which may\n * override it, as on every request), and what makes it a stream. No\n * compression: a proxy that gzips the stream would hand the parser bytes.\n */\nfunction liveHeaders(apiKey: string, extra: Record<string, string>): Record<string, string> {\n const headers = sentHeaders(apiKey, extra)\n headers.accept = 'text/event-stream'\n headers['cache-control'] = 'no-cache'\n headers['accept-encoding'] = 'identity'\n return headers\n}\n\ntype HubState = 'idle' | 'connecting' | 'open' | 'waiting' | 'stopped'\n\n/** One connection per server and key in this process, shared by the clients that use them. */\nclass LiveHub implements SharedHub {\n private state: HubState = 'idle'\n private current: LiveAttempt | undefined\n /** The stamp heard on the open connection, `undefined` until it is told. */\n private version: string | undefined\n private openedAt = 0\n private lastHeardAt = 0\n /** Failures in a row, for the backoff. */\n private attempts = 0\n private retryAt = 0\n private silences = 0\n private retryTimer: Timer | undefined\n private lingerTimer: Timer | undefined\n private readonly owners = new Set<object>()\n /** Version events on the open connection: tells a stream that moved from one that did not. */\n private tells = 0\n /** When the open connection was last checked against the stamp itself. */\n private checkedAt = 0\n private checking = false\n /** A check found the studio ahead of the stream, with `tells` as it was then. */\n private behind: { tells: number, since: number } | undefined\n\n constructor(\n private readonly id: string,\n private readonly url: URL,\n private readonly headers: Record<string, string>,\n ) {}\n\n attach(token: object): number {\n clearTimeout(this.lingerTimer)\n this.lingerTimer = undefined\n this.owners.add(token)\n return this.silences\n }\n\n detach(token: object, linger: boolean): void {\n if (!this.owners.delete(token) || this.owners.size > 0) return\n clearTimeout(this.lingerTimer)\n if (linger) this.lingerTimer = unrefTimer(() => this.owners.size === 0 && this.dispose(), LINGER_MS)\n else this.dispose()\n }\n\n /**\n * The state of the connection for a read at `now`, after the checks a read\n * makes: connect the first time; a connection silent for `LIVE.staleMs` is\n * dead (a frozen process misses events and runs no timers, so the watchdog\n * alone cannot be trusted); a reconnect whose time has come goes now.\n */\n view(now: number): LiveView {\n if (this.state === 'idle') this.connect()\n else if (this.state === 'open' && now - this.lastHeardAt > LIVE.staleMs) this.current?.end({ kind: 'silent' })\n else if (this.state === 'waiting' && now >= this.retryAt) this.connect()\n if (this.state === 'open' && this.behind) this.judgeBehind(now)\n return {\n healthy: this.state === 'open' && this.version !== undefined,\n version: this.version,\n at: this.lastHeardAt,\n silences: this.silences,\n }\n }\n\n /**\n * The safety net, at most once per `LIVE.safetyPollMs` per connection, set\n * off by a read: ask the stamp and compare it with the stream's. Never\n * awaited by a read, never reported, and over an unref'd socket, so it holds\n * up no read and no process. Only a clear answer counts: a failed check, a\n * check that outlived its connection, or one during which the stream told a\n * new stamp proves nothing. A studio ahead of the stream is noted, not acted\n * on: see `judgeBehind`.\n */\n safetyCheck(now: number): void {\n if (this.state !== 'open' || this.version === undefined || this.checking || this.behind) return\n if (now - this.checkedAt < LIVE.safetyPollMs) return\n this.checking = true\n this.checkedAt = now\n const attempt = this.current\n const tells = this.tells\n const heard = this.version\n const url = versionUrl(this.url)\n const headers = { ...this.headers, accept: 'application/json' }\n loadHttp(url.protocol).then(http => probeStamp(http, url, headers), () => undefined).then(\n (stamp) => {\n this.checking = false\n if (stamp === undefined || attempt !== this.current || tells !== this.tells) return\n if (stamp !== heard) this.behind = { tells, since: Date.now() }\n },\n () => {\n this.checking = false\n },\n )\n }\n\n /**\n * A check found the studio ahead of the stream. The studio sends late on\n * purpose (its 5 s throttle), so that alone is no fault: only a stream that\n * told nothing new for `LIVE.lagToleranceMs` since then missed a change. The\n * first read after that drops it, which makes that same read check the stamp\n * itself (and the hub reconnect).\n */\n private judgeBehind(now: number): void {\n const behind = this.behind!\n if (this.tells !== behind.tells) this.behind = undefined\n else if (now - behind.since >= LIVE.lagToleranceMs) {\n this.behind = undefined\n this.current?.end({ kind: 'silent' })\n }\n }\n\n private connect(): void {\n clearTimeout(this.retryTimer)\n this.state = 'connecting'\n const attempt = new LiveAttempt(this)\n this.current = attempt\n loadHttp(this.url.protocol).then(\n (http) => {\n if (this.current === attempt) attempt.start(http, this.url, this.headers)\n },\n () => {\n // No `http` here after all: nothing to connect with, ever.\n if (this.current === attempt) this.halt()\n },\n )\n }\n\n /** The attempt got its stream: the studio's answer is in. */\n opened(attempt: LiveAttempt): void {\n if (attempt !== this.current) return\n this.state = 'open'\n this.version = undefined\n this.openedAt = Date.now()\n this.lastHeardAt = this.openedAt\n this.checkedAt = this.openedAt\n this.behind = undefined\n }\n\n /** Something came in on the stream: a sign of life. */\n heard(attempt: LiveAttempt): void {\n if (attempt === this.current) this.lastHeardAt = Date.now()\n }\n\n /** A `version` event, its data as sent. */\n told(attempt: LiveAttempt, data: string): void {\n if (attempt !== this.current) return\n try {\n const version = (JSON.parse(data) as { version?: unknown } | null)?.version\n if (typeof version === 'string' && version !== '') {\n this.version = version\n this.tells++\n }\n }\n catch {\n /* not a stamp: ignored */\n }\n }\n\n /** The attempt is over: plan the next one. `outcome` is absent when the hub ended it itself. */\n ended(attempt: LiveAttempt, outcome: LiveOutcome | undefined): void {\n if (attempt !== this.current) return\n this.current = undefined\n const now = Date.now()\n const stable = this.state === 'open' && this.version !== undefined && now - this.openedAt >= LIVE.stableMs\n this.version = undefined\n if (!outcome || this.state === 'stopped') return\n if (outcome.kind === 'silent') this.silences++\n const plan = planReconnect(outcome, { attempts: this.attempts, stable, pauseMs: UNSUPPORTED_PAUSE_MS, now, random: Math.random })\n this.attempts = plan.attempts\n this.state = 'waiting'\n this.retryAt = now + plan.delay\n this.retryTimer = unrefTimer(() => {\n if (this.state === 'waiting') this.connect()\n }, plan.delay)\n }\n\n /** Stops for good (no `http` here, or the last client left): reads keep to the poll. */\n private halt(): void {\n this.state = 'stopped'\n clearTimeout(this.retryTimer)\n const attempt = this.current\n this.current = undefined\n this.version = undefined\n attempt?.end()\n }\n\n private dispose(): void {\n this.halt()\n const registry = hubs()\n if (registry.get(this.id) === this) registry.delete(this.id)\n }\n}\n\n/**\n * One connection attempt, from the request to its end. Settles exactly once,\n * however it ends (an error, a close, a timeout, the hub ending it), and\n * reports to the hub only before that. Every event a socket or a stream can\n * emit has a listener here, so none of them can surface as an uncaught error.\n */\nclass LiveAttempt {\n private done = false\n private req: NodeRequest | undefined\n private timers: Timer[] = []\n\n constructor(private readonly hub: LiveHub) {}\n\n start(http: HttpModule, url: URL, headers: Record<string, string>): void {\n if (this.done) return\n this.timers.push(unrefTimer(() => this.end({ kind: 'failed' }), LIVE.connectTimeoutMs))\n try {\n const req = http.request(url, { method: 'GET', headers, agent: false }, (res) => this.answered(res))\n this.req = req\n // A listener that throws would be an uncaught exception, which ends the\n // process: a runtime that speaks Node's `http` may lack either method.\n req.on('socket', (socket) => {\n try {\n socket.unref()\n }\n catch {\n // A socket that cannot be unref'd would keep a build alive: no stream.\n this.end({ kind: 'refused', status: 400, studio: true, retryAfter: null })\n return\n }\n try {\n socket.setKeepAlive(true, 30_000)\n }\n catch {\n /* the pings and the watchdog find a dead connection anyway */\n }\n })\n req.on('error', () => this.end({ kind: 'failed' }))\n req.end()\n }\n catch {\n // A header Node will not send, say: the long pause, not a loop.\n this.end({ kind: 'refused', status: 400, studio: true, retryAfter: null })\n }\n }\n\n /** Ends the attempt; the hub plans what comes next from `outcome`, unless it ended it itself. */\n end(outcome?: LiveOutcome): void {\n if (this.done) return\n this.done = true\n for (const timer of this.timers) clearTimeout(timer)\n try {\n this.req?.destroy()\n }\n catch {\n /* already gone */\n }\n this.hub.ended(this, outcome)\n }\n\n private answered(res: NodeResponse): void {\n res.on('error', () => this.end({ kind: 'failed' }))\n if (this.done) {\n res.resume()\n return\n }\n const type = String(res.headers['content-type'] ?? '')\n if (res.statusCode === 200 && type.includes('text/event-stream')) this.stream(res)\n else this.refused(res)\n }\n\n private stream(res: NodeResponse): void {\n for (const timer of this.timers) clearTimeout(timer)\n this.timers = []\n const watchdog = unrefTimer(() => this.end({ kind: 'silent' }), LIVE.staleMs)\n this.timers.push(watchdog)\n this.hub.opened(this)\n const parser = new SseParser()\n res.setEncoding('utf8')\n res.on('data', (chunk: string) => {\n if (this.done) return\n ;(watchdog as unknown as NodeTimer).refresh?.()\n this.hub.heard(this)\n const events = parser.feed(chunk)\n if (events === null) {\n this.end({ kind: 'failed' })\n return\n }\n for (const event of events) {\n if (event.event === 'version') this.hub.told(this, event.data)\n }\n })\n res.on('end', () => this.end({ kind: 'closed' }))\n res.on('close', () => this.end({ kind: 'failed' }))\n }\n\n /** Not the stream: read a little of the body, to tell the studio's own refusal from a proxy's. */\n private refused(res: NodeResponse): void {\n const status = res.statusCode ?? 0\n const header = res.headers['retry-after']\n const retryAfter = (Array.isArray(header) ? header[0] : header) ?? null\n let body = ''\n res.setEncoding('utf8')\n res.on('data', (chunk: string) => {\n body += chunk\n if (body.length > REFUSAL_BODY_LIMIT) res.destroy()\n })\n const settle = (): void => this.end({ kind: 'refused', status, retryAfter, studio: isStudioBody(status, parseJson(body)) })\n res.on('end', settle)\n res.on('close', settle)\n }\n}\n\n/** `/api/content/version` beside the stream's `/api/content/events`. */\nfunction versionUrl(events: URL): URL {\n const url = new URL(events.href)\n url.pathname = url.pathname.replace(/events$/, 'version')\n return url\n}\n\n/**\n * The safety check's request: the stamp from `GET /version`, `undefined` for\n * anything else (an error, a status other than 200, a body without a stamp,\n * no answer within `LIVE.safetyProbeTimeoutMs`). Holds no process (`getJson`).\n */\nasync function probeStamp(http: HttpModule, url: URL, headers: Record<string, string>): Promise<string | undefined> {\n const stamp = (await getJson(http, url, headers, LIVE.safetyProbeTimeoutMs) as { version?: unknown } | undefined)?.version\n return typeof stamp === 'string' && stamp !== '' ? stamp : undefined\n}\n","/**\n * The file cache behind `FileCacheStore` (`@nordhavnhq/beacon/file-store`) and\n * the `cache.dir` option: entries on disk as well as in memory, so a restarted\n * process still has the last good content, also when the studio is down at\n * that very moment.\n *\n * Node's `fs`, `crypto` and `path` come in as `FileDeps` and are not imported\n * here: the file-store entry hands over its static imports, the main entry\n * (for `cache.dir`) takes them from `process.getBuiltinModule`, so the main\n * entry stays loadable in a browser.\n *\n * Kept per site. A client hands its identity over (`ATTACH`, `attachShared`);\n * the entries then live in `<dir>/<hash>/`, the hash a short sha256 of the\n * server and the credentials the client sends, and two sites (or two keys of\n * a developer) sharing `dir` never see each other's content. One cache per\n * folder in a process (`attachShared`), whoever asks for it. A store no client\n * attached to keeps its entries in `dir` itself, as it did up to 0.7.\n *\n * What it removes on its own is narrow on purpose, as `dir` may be mistyped\n * (a project root, `/tmp`, a parent of other sites' folders): only its own\n * cache files, and only folders it made itself, which carry `MARKER`.\n */\nimport type { CacheEntry, CacheStore } from './cache'\n\nexport interface FileCacheOptions {\n /** Directory for the cache files. Created when missing. */\n dir: string\n /** Soft cap on entries; oldest are evicted first, from memory and disk. Default `500`. */\n maxEntries?: number\n /**\n * Called when the disk cannot be read or written. Without one, the store\n * warns once, through the client's `logger` once a client attached it.\n */\n onError?: (err: unknown) => void\n}\n\n/*\n * The parts of Node's `fs`, `crypto` and `path` the store uses, declared\n * locally: beacon's main entry builds one too (for `cache.dir`) and must\n * typecheck without Node's types.\n */\ninterface DirEntry {\n name: string\n isDirectory(): boolean\n}\nexport interface FileSystem {\n mkdirSync(path: string, options: { recursive: true }): unknown\n readdirSync(path: string): string[]\n readdirSync(path: string, options: { withFileTypes: true }): DirEntry[]\n readFileSync(path: string, encoding: 'utf8'): string\n writeFileSync(path: string, data: string): void\n renameSync(from: string, to: string): void\n rmSync(path: string, options: { force: true }): void\n rmdirSync(path: string): void\n statSync(path: string): { mtimeMs: number }\n utimesSync(path: string, atime: Date, mtime: Date): void\n}\nexport interface FileDeps {\n fs: FileSystem\n join(...parts: string[]): string\n resolve(path: string): string\n sha256(text: string): string\n randomHex(bytes: number): string\n}\n\n/** What a client tells the store it attaches to. */\nexport interface StoreScope {\n /** Server and credentials (`identityOf`), hashed into the folder's name. */\n identity: string\n /**\n * Whether the cache files of 0.7 in `dir` itself are copied into a folder\n * that has no entries yet: for a `FileCacheStore` a site passes in, which\n * up to 0.7 had one `dir` per site, on the first start after 0.7 (decided\n * in `attachShared`). Not for `cache.dir`, new in 0.8.\n */\n adoptLegacy: boolean\n /** Where disk problems go when the store has no `onError` of its own; `undefined` keeps them quiet. */\n warn: ((...args: unknown[]) => void) | undefined\n}\n\n/** What the store reports back to the client that attached it. */\nexport interface AttachedStore {\n /** What the client caches in: the cache of its folder. */\n store: CacheStore\n /** The store's `dir`. */\n dir: string\n /** Where its entries live: `<dir>/<hash>`. */\n folder: string\n /** Entries in the folder on attaching, copied ones included. */\n loaded: number\n /** Cache files of 0.7 in `dir` itself, left where they are. */\n legacy: number\n /** How many of those were copied into the folder (`adoptLegacy`). */\n copied: number\n /** `false` for a second client with the same identity: it was already loaded. */\n first: boolean\n}\n\n/**\n * The method a client calls to hand the store its identity. A symbol from\n * the global registry: the main entry and the file-store entry are separate\n * bundles (and a site may load two copies), and must still find each other.\n * Returns `undefined` when the store already serves another identity.\n *\n * Keep this symbol (and the `globalThis` ones below) stable across releases.\n * A site can load two copies of beacon (a dependency pinning another\n * version), and a client from one hands its identity to a store from the\n * other through this name. If it is ever bumped, clients must keep trying\n * the older symbols too: else a store from an older copy is no longer found,\n * and a client of the newer one uses it as a plain store, in its unsplit\n * `dir`, as 0.7 did.\n */\nexport const ATTACH = Symbol.for('@nordhavnhq/beacon/file-cache-attach/3')\nexport type Attach = (scope: StoreScope) => AttachedStore | undefined\n\n/** On-disk shape. `v` leaves room to change it without misreading old files. */\ninterface StoredFile {\n v: 1\n key: string\n entry: CacheEntry\n}\n\nconst SUFFIX = '.json'\n\n/**\n * The only names this store reads, replaces or removes: the sha256 of a cache\n * key (see `fileOf`), and the temp file of a write to one. `dir` may hold other\n * files - a mistyped path can point at a project root - and those are never\n * touched, whatever their extension.\n */\nconst CACHE_FILE = /^[0-9a-f]{64}\\.json$/\nconst TEMP_FILE = /^[0-9a-f]{64}\\.json\\.\\d+(\\.[0-9a-f]+)?\\.tmp$/\n\n/** The name of a folder this store makes: 16 hex characters of a sha256. */\nconst FOLDER = /^[0-9a-f]{16}$/\n\n/**\n * Put in every folder this store makes, and kept fresh while it is used: the\n * sweep of another client looks only at folders that carry it, so a folder of\n * anything else that happens to have a fitting name is never touched.\n */\nexport const MARKER = '.beacon-cache'\nconst MARKER_TEXT = 'A cache of @nordhavnhq/beacon. Removed by beacon once unused for 30 days; safe to delete.\\n'\n\n/**\n * How old a temp file must be before a starting store takes it for an orphan.\n * A write takes milliseconds, so anything younger may be a write under way in\n * another process on the same directory: the old and the new container during\n * a redeploy, or the workers of a cluster.\n */\nconst TEMP_ORPHAN_MS = 60_000\n\n/**\n * How long a folder of this store may go unused before a starting store\n * removes it: the cache of a key that was replaced. Its own folder is marked\n * as used at start and then at least daily (`TOUCH_MS`), whether or not\n * anything changes.\n */\nexport const STALE_MS = 30 * 24 * 3_600_000\nconst TOUCH_MS = 24 * 3_600_000\n\nexport class FileCache implements CacheStore {\n private readonly dir: string\n private readonly maxEntries: number\n private readonly onError: (err: unknown) => void\n private readonly deps: FileDeps\n /** Same order contract as `MemoryCacheStore`: oldest written first. */\n private readonly map = new Map<string, CacheEntry>()\n /** Where the entries live: `dir` until a client attaches, then `<dir>/<hash>`. */\n private folder: string\n /** The folder's name once a client attached. */\n private hash: string | undefined\n /** What the first attach reported, for the clients after it. */\n private attached: AttachedStore | undefined\n /** Read from disk on first use, not at construction: a client attaching first decides where from. */\n private loaded = false\n private touchedAt = 0\n /** Whether disk problems go to the default warning (and so follow an attaching client's `logger`). */\n private readonly ownWarning: boolean\n /** Where the one warning goes without an `onError`: the console, or the attaching client's `logger`. */\n private warnTo: ((...args: unknown[]) => void) | undefined = (...args) => console.warn(...args)\n\n constructor(options: FileCacheOptions, deps: FileDeps) {\n if (!options?.dir) throw new Error('FileCacheStore: `dir` is required')\n this.dir = options.dir\n this.folder = options.dir\n this.maxEntries = options.maxEntries ?? 500\n this.deps = deps\n\n let warned = false\n this.onError = options.onError ?? ((err) => {\n if (warned) return\n warned = true\n this.warnTo?.(`[@nordhavnhq/beacon] file cache at ${this.folder} unusable, continuing in memory:`, err instanceof Error ? err.message : err)\n })\n this.ownWarning = options.onError === undefined\n }\n\n get(key: string): CacheEntry | undefined {\n this.ensureLoaded()\n this.touch()\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n this.ensureLoaded()\n this.map.delete(key)\n this.map.set(key, entry)\n this.write(key, entry)\n this.evict()\n }\n\n delete(key: string): void {\n this.ensureLoaded()\n this.map.delete(key)\n this.remove(this.fileOf(key))\n }\n\n keys(): Iterable<string> {\n this.ensureLoaded()\n return this.map.keys()\n }\n\n clear(): void {\n this.ensureLoaded()\n this.map.clear()\n for (const name of this.list(this.folder)) {\n if (CACHE_FILE.test(name)) this.remove(this.deps.join(this.folder, name))\n }\n }\n\n /**\n * Moves the store into its folder (`<dir>/<hash>`) and reads that; copies\n * the cache files of 0.7 in when asked and the folder is empty; then clears\n * out folders of this store that went unused (`sweep`). Entries already\n * read from `dir` itself are dropped from memory. A second client with the\n * same identity finds it done; one with another identity is refused, as the\n * store holds one site's entries.\n */\n [ATTACH](scope: StoreScope): AttachedStore | undefined {\n const hash = this.deps.sha256(scope.identity).slice(0, 16)\n if (this.hash !== undefined) {\n return this.hash === hash && this.attached ? { ...this.attached, first: false } : undefined\n }\n if (this.ownWarning) this.warnTo = scope.warn\n this.hash = hash\n this.folder = this.deps.join(this.dir, hash)\n this.map.clear()\n this.loaded = false\n this.ensureLoaded()\n this.mark()\n const legacy = this.legacyFiles()\n const copied = scope.adoptLegacy && this.map.size === 0 ? this.adopt(legacy) : 0\n this.sweep()\n this.attached = { store: this, dir: this.dir, folder: this.folder, loaded: this.map.size, legacy: legacy.length, copied, first: true }\n return this.attached\n }\n\n // ── Disk ────────────────────────────────────────────────────────────────────\n\n /** File name per key: a hash, as keys hold `/` and `:` and may be long. */\n private fileOf(key: string, folder = this.folder): string {\n return this.deps.join(folder, this.deps.sha256(key) + SUFFIX)\n }\n\n private ensureLoaded(): void {\n if (this.loaded) return\n this.loaded = true\n this.load()\n }\n\n /** Fills memory from disk, oldest file first so eviction order survives a restart. */\n private load(): void {\n try {\n this.deps.fs.mkdirSync(this.folder, { recursive: true })\n }\n catch (err) {\n this.fail(err)\n return\n }\n for (const name of this.list(this.folder)) {\n // Left behind by a process killed between write and rename - unless it\n // is fresh, and then it belongs to a write that is still happening.\n if (TEMP_FILE.test(name)) {\n const file = this.deps.join(this.folder, name)\n if (this.olderThan(file, TEMP_ORPHAN_MS)) this.remove(file)\n }\n }\n // Ours by name but unreadable, or filed under another key: it can only\n // ever be a miss, so it goes.\n const found = this.readEntries(this.folder, file => this.remove(file))\n for (const { key, entry } of found) this.map.set(key, entry)\n this.evict()\n }\n\n /**\n * The readable cache files in `folder`, oldest first. Files that are this\n * store's by name but not a cache entry (half written, filed under another\n * key) go to `bad`; anything else in `folder` is not looked at.\n */\n private readEntries(folder: string, bad: (file: string) => void): { key: string, entry: CacheEntry, mtime: number }[] {\n const { fs } = this.deps\n const found: { key: string, entry: CacheEntry, mtime: number }[] = []\n for (const name of this.list(folder)) {\n if (!CACHE_FILE.test(name)) continue\n const file = this.deps.join(folder, name)\n try {\n const stored = JSON.parse(fs.readFileSync(file, 'utf8')) as StoredFile\n if (stored?.v !== 1 || typeof stored.key !== 'string' || !stored.entry || file !== this.fileOf(stored.key, folder)) {\n throw new Error('not a cache file')\n }\n found.push({ key: stored.key, entry: stored.entry, mtime: fs.statSync(file).mtimeMs })\n }\n catch {\n bad(file)\n }\n }\n return found.sort((a, b) => a.mtime - b.mtime)\n }\n\n /** The cache files of 0.7 in `dir` itself: read only, never changed or removed. */\n private legacyFiles(): { key: string, entry: CacheEntry, mtime: number }[] {\n return this.readEntries(this.dir, () => {})\n }\n\n /**\n * Copies the cache files of 0.7 into the (empty) folder, the newest\n * `maxEntries` of them, so a site that restarts during an outage right after\n * upgrading still has its content. Copied, not moved: a 0.7 process on the\n * same directory (the old container during a redeploy) keeps its own.\n */\n private adopt(legacy: { key: string, entry: CacheEntry }[]): number {\n const take = legacy.slice(-this.maxEntries)\n for (const { key, entry } of take) {\n this.map.set(key, entry)\n this.write(key, entry)\n }\n return take.length\n }\n\n /**\n * At attach, in `dir`: removes the folders of this store that went unused\n * for `STALE_MS`. A folder counts only when its name is a hash, it carries\n * `MARKER`, and it holds nothing but cache files, temp files and the\n * marker: then those go, and the folder. Anything else (a folder of the\n * site's, another site's 0.7 cache files, a folder with one foreign file in\n * it) is never touched, and neither is anything in `dir` itself.\n *\n * Silent on failure: this is tidying, not caching, and a folder another\n * user owns is no reason to say the cache is unusable.\n */\n private sweep(): void {\n const { fs, join } = this.deps\n let entries: DirEntry[]\n try {\n entries = fs.readdirSync(this.dir, { withFileTypes: true })\n }\n catch {\n return\n }\n for (const entry of entries) {\n // `isDirectory()` of a symbolic link is false: one is never followed.\n if (!entry.isDirectory() || !FOLDER.test(entry.name) || entry.name === this.hash) continue\n const folder = join(this.dir, entry.name)\n const marker = join(folder, MARKER)\n if (!this.olderThan(marker, STALE_MS) || !this.olderThan(folder, STALE_MS)) continue\n this.quietly(() => {\n const names = fs.readdirSync(folder)\n if (!names.every(name => name === MARKER || CACHE_FILE.test(name) || TEMP_FILE.test(name))) return\n for (const name of names) fs.rmSync(join(folder, name), { force: true })\n fs.rmdirSync(folder)\n })\n }\n }\n\n /** Puts `MARKER` in the folder, or marks it as used if it is there: see `touch`. */\n private mark(): void {\n const marker = this.deps.join(this.folder, MARKER)\n const now = new Date()\n this.touchedAt = now.getTime()\n this.quietly(() => {\n try {\n this.deps.fs.utimesSync(marker, now, now)\n }\n catch {\n this.deps.fs.writeFileSync(marker, MARKER_TEXT)\n }\n })\n }\n\n /**\n * Marks the folder as used, at most once per `TOUCH_MS`: a site whose\n * content does not change writes nothing, and its folder must not look\n * abandoned to the sweep of another site sharing `dir`.\n */\n private touch(): void {\n if (this.hash === undefined || Date.now() - this.touchedAt < TOUCH_MS) return\n this.mark()\n }\n\n private evict(): void {\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.delete(oldest)\n }\n }\n\n /** Temp file plus rename, so a reader (or a crash) never sees half a file. */\n private write(key: string, entry: CacheEntry): void {\n const file = this.fileOf(key)\n // The random part keeps two processes apart that write the same key at the\n // same moment. The pid alone does not: in a container it is 1 for both.\n const tmp = `${file}.${processId()}.${this.deps.randomHex(6)}.tmp`\n const stored = JSON.stringify({ v: 1, key, entry } satisfies StoredFile)\n try {\n this.writeAt(tmp, file, stored)\n }\n catch (err) {\n this.remove(tmp)\n this.fail(err)\n }\n }\n\n /**\n * One write. A folder that is gone, before the temp file is written or\n * before it is renamed, is made again and the write done once more: the\n * sweep of another site sharing `dir` removes a folder only after 30 days\n * unused, but a process may well sit that long without a read, and a\n * person may clear the directory by hand. Only a failure that outlasts\n * that second try is reported.\n */\n private writeAt(tmp: string, file: string, stored: string): void {\n const { fs } = this.deps\n try {\n fs.writeFileSync(tmp, stored)\n fs.renameSync(tmp, file)\n }\n catch (err) {\n if (!isMissing(err)) throw err\n fs.mkdirSync(this.folder, { recursive: true })\n if (this.hash !== undefined) this.mark()\n fs.writeFileSync(tmp, stored)\n fs.renameSync(tmp, file)\n }\n }\n\n /**\n * Hands a disk problem to `onError`. Never throws and never leaves a rejection\n * behind: this runs inside a cache write, which runs inside a read, and a\n * hook that fails (or an `async` one whose own work fails) must not fail the\n * read or stop the process over a cache that merely fell back to memory.\n */\n private fail(err: unknown): void {\n try {\n const outcome: unknown = this.onError(err)\n if (typeof (outcome as { then?: unknown } | null | undefined)?.then === 'function') {\n (outcome as PromiseLike<unknown>).then(undefined, () => {})\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /** Whether a file or folder was last changed more than `ms` ago. Unknown (missing) counts as \"no\". */\n private olderThan(path: string, ms: number): boolean {\n try {\n return Date.now() - this.deps.fs.statSync(path).mtimeMs > ms\n }\n catch {\n return false\n }\n }\n\n private quietly(run: () => void): void {\n try {\n run()\n }\n catch {\n /* see `sweep` */\n }\n }\n\n private remove(file: string): void {\n try {\n this.deps.fs.rmSync(file, { force: true })\n }\n catch (err) {\n this.fail(err)\n }\n }\n\n /** The names in `folder`; none for a folder that is not there (yet, or any more), which is no disk problem. */\n private list(folder: string): string[] {\n try {\n return this.deps.fs.readdirSync(folder)\n }\n catch (err) {\n if (!isMissing(err)) this.fail(err)\n return []\n }\n }\n}\n\n/**\n * The file caches attached by clients, one per folder (resolved `dir` and\n * identity) in a process, on `globalThis`: whoever asks for a folder gets\n * the same cache, `cache.dir` and a `FileCacheStore` alike, also from\n * another build of beacon (its ESM and CommonJS entries, a dev server's\n * reload). A site that makes a client (or a store) per request does not read\n * the directory again each time, and no two caches on one folder evict each\n * other's files. The first to ask decides `maxEntries` and `onError`; a later\n * one asking with others is told so, once.\n *\n * Keep the symbol stable (see `ATTACH`).\n */\nconst FILE_CACHES = Symbol.for('@nordhavnhq/beacon/file-caches/2')\n\ninterface SharedCache {\n cache: FileCache\n maxEntries: number\n onError: ((err: unknown) => void) | undefined\n /** Whether a later asker was already told that the first one's settings apply. */\n told: boolean\n}\n\n/**\n * Per resolved `dir` in a process, whether this is the first start after\n * 0.7: no folder of beacon's in it yet (a hash name with `MARKER`) when the\n * first client of the process attached. Decided once, before that client\n * makes its own folder, so a reader and a writer of one site, whichever\n * comes first, both copy the 0.7 entries into their folders; a new key in a\n * later process finds the folders and copies nothing (the 0.7 entries are\n * months old by then). Keep the symbol stable (see `ATTACH`).\n */\nconst FIRST_STARTS = Symbol.for('@nordhavnhq/beacon/first-starts/1')\n\n/** Whether `dir` holds a folder of beacon's: a hash name with `MARKER` in it. */\nfunction hasFolders(deps: FileDeps, dir: string): boolean {\n const { fs, join } = deps\n try {\n return fs.readdirSync(dir, { withFileTypes: true }).some(entry =>\n entry.isDirectory() && FOLDER.test(entry.name) && fs.readdirSync(join(dir, entry.name)).includes(MARKER))\n }\n catch {\n return false\n }\n}\n\nfunction registry<T>(symbol: symbol): Map<string, T> {\n const scope = globalThis as unknown as Record<symbol, Map<string, T> | undefined>\n const map = scope[symbol] ?? new Map<string, T>()\n scope[symbol] = map\n return map\n}\n\n/** Attaches `scope` to the cache of its folder in `options.dir`, made with `options` and `deps` if it is the first. */\nexport function attachShared(options: FileCacheOptions, deps: FileDeps, scope: StoreScope): AttachedStore | undefined {\n const dir = deps.resolve(options.dir)\n const firstStarts = registry<boolean>(FIRST_STARTS)\n if (!firstStarts.has(dir)) firstStarts.set(dir, !hasFolders(deps, dir))\n const caches = registry<SharedCache>(FILE_CACHES)\n const id = `${dir}\\n${scope.identity}`\n const maxEntries = options.maxEntries ?? 500\n let shared = caches.get(id)\n if (!shared) {\n shared = { cache: new FileCache(options, deps), maxEntries, onError: options.onError, told: false }\n caches.set(id, shared)\n }\n const attached = shared.cache[ATTACH]({ ...scope, adoptLegacy: scope.adoptLegacy && firstStarts.get(dir) === true })\n const differs = maxEntries !== shared.maxEntries || (options.onError !== undefined && options.onError !== shared.onError)\n if (attached && differs && !shared.told) {\n shared.told = true\n 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`)\n }\n return attached\n}\n\nfunction isMissing(err: unknown): boolean {\n return (err as { code?: unknown } | null)?.code === 'ENOENT'\n}\n\n/** The pid, for temp file names; `0` where there is no `process`. */\nfunction processId(): number {\n return (globalThis as { process?: { pid?: number } }).process?.pid ?? 0\n}\n\n/**\n * `FileDeps` from the modules Node hands out synchronously\n * (`process.getBuiltinModule`, Node 22.3 and later), or `undefined` where\n * there are none: a browser, an edge runtime, an older Node.\n */\nexport function builtinFileDeps(builtin: (id: string) => unknown): FileDeps | undefined {\n const fs = builtin('node:fs') as FileSystem | undefined\n const crypto = builtin('node:crypto') as NodeCrypto | undefined\n const path = builtin('node:path') as NodePath | undefined\n if (!fs || !crypto || !path) return undefined\n return fileDeps(fs, crypto, path)\n}\n\ninterface NodeCrypto {\n createHash(algorithm: 'sha256'): { update(text: string): { digest(encoding: 'hex'): string } }\n randomBytes(size: number): { toString(encoding: 'hex'): string }\n}\ninterface NodePath {\n join(...parts: string[]): string\n resolve(path: string): string\n}\n\n/** `FileDeps` from Node's `fs`, `crypto` and `path`. */\nexport function fileDeps(fs: FileSystem, crypto: NodeCrypto, path: NodePath): FileDeps {\n return {\n fs,\n join: path.join,\n resolve: path.resolve,\n sha256: text => crypto.createHash('sha256').update(text).digest('hex'),\n randomHex: bytes => crypto.randomBytes(bytes).toString('hex'),\n }\n}\n","// How a client's options are resolved where that takes more than a default:\n// the key and the server (passed, else from the environment), and the store\n// the cache lives in (passed, or built from `cache.dir`), with what a file\n// cache found on disk written to the client's logger.\nimport { MemoryCacheStore, type CacheOptions, type CacheStore } from './cache'\nimport type { NordhavnClientOptions } from './client'\nimport { ATTACH, attachShared, builtinFileDeps, type Attach, type AttachedStore, type StoreScope } from './file-cache'\nimport { firstTime, logLine, nodeBuiltin, readEnv, type Logger } from './runtime'\n\n/** The hosted platform. Used when no `baseUrl` is passed or set in the environment. */\nexport const DEFAULT_BASE_URL = 'https://beacon.nordhavn.ai'\n\n/** Where `apiKey` and `baseUrl` are read from when they are not passed. */\nconst API_KEY_ENV = 'NORDHAVN_API_KEY'\nconst BASE_URL_ENV = 'NORDHAVN_BASE_URL'\n\n/**\n * The key and the server: as passed, else from the environment\n * (`NORDHAVN_API_KEY`, `NORDHAVN_BASE_URL`), but only for an option that is\n * not in `options` at all. One that is there with no usable value is taken\n * as passed, as up to 0.7: an `undefined` key (`apiKey: process.env.SITE_KEY`\n * with that unset) throws, an `undefined` server is the hosted platform, and\n * an empty string throws. Falling back from any of those could quietly pick\n * up another site's key, or send a self-hosted studio's key to the hosted\n * platform.\n */\nexport function connectionOf(options: NordhavnClientOptions): { apiKey: string, baseUrl: string } {\n const apiKey = 'apiKey' in options ? options.apiKey?.trim() : readEnv(API_KEY_ENV)\n if (!apiKey) throw new Error(missingKey(options))\n const baseUrl = 'baseUrl' in options\n ? options.baseUrl === undefined ? DEFAULT_BASE_URL : options.baseUrl.trim()\n : readEnv(BASE_URL_ENV) ?? DEFAULT_BASE_URL\n if (!baseUrl) {\n throw new Error('NordhavnClient: `baseUrl` is empty (leave it out for NORDHAVN_BASE_URL or the hosted platform)')\n }\n return { apiKey, baseUrl: baseUrl.replace(/\\/+$/, '') }\n}\n\n/** Why there is no key: never passed and not in the environment, or passed without a value. */\nfunction missingKey(options: NordhavnClientOptions): string {\n if (!('apiKey' in options)) return `NordhavnClient: \\`apiKey\\` is required: pass it, or set ${API_KEY_ENV}`\n if (options.apiKey === undefined) {\n return `NordhavnClient: \\`apiKey\\` is required (it was passed as \\`undefined\\`; leave it out altogether to read ${API_KEY_ENV})`\n }\n return 'NordhavnClient: `apiKey` is empty (an empty string does not fall back to the environment)'\n}\n\n/** The `cache` option of a client: `CacheOptions` and the disk cache, which only a client builds. */\nexport interface ClientCacheOptions extends CacheOptions {\n /**\n * Keep the cache on disk too, in this directory, so a process that restarts\n * while the studio is down still has the last good content (Node 22.3 or\n * later). Put it on a volume that survives a redeploy. An empty string\n * counts as not given, so `dir: process.env.CACHE_DIR` works unset.\n *\n * The entries go in a folder of `dir` named after a short hash of the\n * server and the key (never the key itself), so sites, or a developer's\n * keys, sharing a directory never see each other's content. Folders of\n * beacon's that went unused for 30 days are removed when a client starts;\n * nothing else in `dir` is touched. Not with `store`.\n */\n dir?: string\n}\n\n/**\n * The store a client caches in: the one passed (`cache.store`), the file\n * cache of `cache.dir`, or `undefined` for the default memory store.\n *\n * A file cache (of `cache.dir`, or a `FileCacheStore` passed in) is handed the\n * client's identity here (`ATTACH`, `attachShared`), and the client caches in\n * what comes back: the cache of the folder named after that identity, one per\n * folder in the process. So one `FileCacheStore` given to clients of two keys\n * keeps a folder for each. A custom store has no such method and is used as\n * it is. A client whose cache is off attaches nothing: it never reads the\n * store.\n */\nexport function cacheStore(options: ClientCacheOptions, identity: string, log: Logger | undefined): CacheStore | undefined {\n if (options.enabled === false) return options.store\n const dir = options.dir || undefined\n if (dir !== undefined && options.store !== undefined) {\n throw new Error('NordhavnClient: pass `cache.dir` or `cache.store`, not both')\n }\n const warn = log && typeof log.warn === 'function' ? (...args: unknown[]) => log.warn!(...args) : undefined\n const scope: StoreScope = { identity, adoptLegacy: dir === undefined, warn }\n let attached: AttachedStore | undefined\n if (dir !== undefined) {\n const deps = builtinFileDeps(nodeBuiltin)\n if (!deps) {\n if (firstTime('no-file-cache')) {\n 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.')\n }\n return undefined\n }\n attached = attachShared({ dir, maxEntries: options.maxEntries }, deps, scope)\n }\n else {\n const attach = (options.store as { [ATTACH]?: Attach } | undefined)?.[ATTACH]\n if (typeof attach !== 'function') return options.store\n attached = attach.call(options.store, scope)\n }\n if (!attached) {\n // A subclass of `FileCacheStore` already given to another key: better memory than another key's entries.\n 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.')\n return new MemoryCacheStore(options.maxEntries ?? 500)\n }\n if (attached.first) tellDisk(attached, dir === undefined, log)\n return attached.store\n}\n\n/**\n * What a file cache found on disk, once per folder per process. Nothing on\n * disk is worth a warning: fine on a first start, but on every start it\n * means the directory does not survive a restart, and nothing else would\n * show that until an outage meets a restart.\n */\nfunction tellDisk(attached: AttachedStore, fromStore: boolean, log: Logger | undefined): void {\n const { folder, loaded, legacy, copied } = attached\n if (copied > 0 && firstTime(`copied\\n${folder}`)) {\n 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`)\n }\n else if (copied === 0 && legacy > 0 && loaded === 0 && firstTime(`legacy\\n${folder}`)) {\n const why = fromStore ? 'only the first start after 0.7 copies them' : '`cache.dir` keeps its entries per key'\n 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}`)\n }\n if (!firstTime(`disk\\n${folder}`)) return\n if (loaded > 0) logLine(log, 'info', `file cache ${folder}: ${count(loaded, 'entry', 'entries')} on disk`)\n 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).`)\n}\n\nfunction count(n: number, one: string, many: string): string {\n return `${n} ${n === 1 ? one : many}`\n}\n","/**\n * One gate per server and key in a process, shut by the studio's own `429`\n * with `Retry-After`: until the studio said, reads with nothing cached hold\n * back instead of going out to be refused as well. Without it, forty reads of\n * a cold start that meet the studio's limit each wait out their own\n * `Retry-After` and come back together, to be refused together again.\n *\n * Bounded on purpose, as it holds back every read of a key: at most\n * `GATE_MAX_MS` whatever `Retry-After` says (the studio asks for seconds),\n * and kept on a monotonic clock, so a wall clock set back cannot stretch it.\n * Only the client decides whose `429` may shut it (the studio's own, not a\n * proxy's page).\n *\n * On `globalThis`, like the live connection's hubs: shared by every client of\n * that server and key, also by a copy of this module from another build (a\n * dev server's reload, a second install). When its shape changes, so does\n * the number in `GATES`.\n *\n * No imports and only erasable TypeScript, so its test can load the source as\n * it is.\n */\n\nconst GATES = Symbol.for('@nordhavnhq/beacon/rate-gates/2')\n\n/** The longest the gate stays shut, whatever `Retry-After` asks. */\nexport const GATE_MAX_MS = 60_000\n\n/** A clock that only goes forward: `performance.now()`, or `Date.now()` where there is none. */\nexport function monotonicNow(): number {\n const perf = (globalThis as { performance?: { now?: () => number } }).performance\n return typeof perf?.now === 'function' ? perf.now() : Date.now()\n}\n\n/** Per identity, the `monotonicNow()` at which the gate opens. */\nfunction gates(): Map<string, number> {\n const scope = globalThis as unknown as Record<symbol, Map<string, number> | undefined>\n let map = scope[GATES]\n if (!map) {\n map = new Map()\n scope[GATES] = map\n }\n return map\n}\n\n/** Ms until the gate of `identity` opens; `0` when it is open. */\nexport function gateRemaining(identity: string, now: number = monotonicNow()): number {\n const map = gates()\n const opensAt = map.get(identity) ?? 0\n if (opensAt > now) return opensAt - now\n map.delete(identity)\n return 0\n}\n\n/** Shuts the gate of `identity` for `ms` (at most `GATE_MAX_MS`), or longer if it already is. */\nexport function shutGate(identity: string, ms: number, now: number = monotonicNow()): void {\n const map = gates()\n const opensAt = now + Math.min(Math.max(0, ms), GATE_MAX_MS)\n if (opensAt > (map.get(identity) ?? 0)) map.set(identity, opensAt)\n}\n\n/**\n * The random time added to a wait of `ms` before a read goes out again, so\n * the reads held back together do not return together: up to a fifth of the\n * wait, and at least up to a second. Never cut short, also for a wait of 0.\n */\nexport function spreadOf(ms: number, random: () => number = Math.random): number {\n return random() * Math.max(1_000, ms / 5)\n}\n","import { announceProject, wantAnnounce } from './announce'\nimport { ContentCache, type CacheEntry } from './cache'\nimport { NordhavnError, isStudioBody } from './errors'\nimport type { ContentLocale, ContentRecord, ContentSchema, QueryResult, SchemaNode, UploadedFile } from './types'\nimport { LiveLink, wantLive } from './live'\nimport { parseRetryAfter } from './live-policy'\nimport { cacheStore, connectionOf, type ClientCacheOptions } from './options'\nimport { gateRemaining, shutGate, spreadOf } from './rate-gate'\nimport { identityOf, logLine, loggerOf, sentHeaders, type Logger } from './runtime'\nimport { VersionTracker } from './version'\n\nexport { DEFAULT_BASE_URL } from './options'\n\n/** Default request timeout in ms (`timeout` option). */\nconst DEFAULT_TIMEOUT = 10_000\n/** The least a write gets by default (`writeTimeout`): one that times out may still have been stored. */\nconst MIN_WRITE_TIMEOUT = 30_000\n/** The least time an upload gets by default: the studio takes up to 10 MB. */\nconst MIN_UPLOAD_TIMEOUT = 60_000\n/** Ceiling for the stamp check, which every concurrent read waits on. */\nconst VERSION_TIMEOUT = 3_000\n/** Default for `cache.waitForFresh`, in ms. */\nconst DEFAULT_WAIT_FOR_FRESH = 1_000\n/** The longest delay a timer holds; beyond it `setTimeout` fires after 1 ms. */\nconst MAX_TIMER = 2_147_483_647\n/** How many keys `storedBy` remembers before it starts over. */\nconst STORED_LIMIT = 5_000\n/** How long a failed read of the project's locales is not repeated. */\nconst LOCALES_RETRY_MS = 60_000\n/** Default for `gatewayRetry`, in ms. */\nconst DEFAULT_GATEWAY_RETRY = 200\n/** The longest `gatewayRetry` honoured; a larger value is cut back to this. */\nconst MAX_GATEWAY_RETRY = 60_000\n/** Default for `rateLimitWait`, in ms. */\nconst DEFAULT_RATE_LIMIT_WAIT = 10_000\n/** How many times one read is sent again after a `429`, however much of `rateLimitWait` is left. */\nconst MAX_RATE_LIMIT_RETRIES = 2\n\n/** A studio failure the client absorbed, handed to `onError`. */\nexport interface StudioFailure {\n /**\n * What failed: the periodic `stamp-check`, or the `read` that refreshes one\n * cache entry (its cached value was served instead).\n */\n during: 'stamp-check' | 'read'\n /** Cache key of the entry that could not be refreshed. Only for `read`. */\n key?: string\n /** What went wrong: a `NordhavnError`, a `TimeoutError`, a network error. */\n error: unknown\n}\n\nexport interface NordhavnClientOptions {\n /**\n * Project API key, `slk_...`. Mint one in the project's settings under\n * \"API keys\". Its reach is the union of its per-node read/write scopes.\n *\n * Left out of the options altogether, it is read from the environment\n * variable `NORDHAVN_API_KEY` (`process.env`, where the runtime has one). A\n * key passed here always wins. Passed without a value (`undefined`, as from\n * an unset variable of the site's own, or an empty string) it throws, as up\n * to 0.7: it never falls back to the environment.\n */\n apiKey?: string\n /**\n * Base URL of your server, without a trailing `/api/content` (that path is\n * appended automatically). Left out of the options altogether, it is read\n * from the environment variable `NORDHAVN_BASE_URL`, else it is the hosted\n * platform (`DEFAULT_BASE_URL`). A URL passed here always wins; passed as\n * `undefined` it is the hosted platform, as up to 0.7; an empty string\n * throws.\n */\n baseUrl?: string\n /**\n * Default locale for reads, e.g. `nl` or `fr-BE`. When set, records are\n * returned in that language, with untranslated fields falling back to the\n * project default. Override per call with `opts.locale`. Omit for the default\n * locale. Discover available locales with `client.locales()`.\n */\n locale?: string\n /** Read caching. Pass `false` to disable, or an options object to tune it (and `dir` to keep it on disk). */\n cache?: boolean | ClientCacheOptions\n /** Custom `fetch` implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch\n /**\n * Give up on a request after this many ms, body included. Default `10000`.\n * `0` disables it, as does `Infinity`.\n *\n * Without one, a studio that accepts the connection but never answers holds\n * every read until the runtime gives up (minutes, in Node). A timed-out read\n * counts as transient, like a `5xx`: the last good value is served. The\n * once-a-minute stamp check uses at most 3 seconds of it, as every read in\n * that moment waits on the check.\n *\n * Writes and uploads have their own, longer deadline: `writeTimeout`.\n */\n timeout?: number\n /**\n * Give up on a write (`createRecord`, `updateRecord`) after this many ms,\n * body included. Default: `timeout`, but at least `30000`; `0` disables it,\n * as does a client `timeout` of `0` when this is not set. An upload gets\n * this too, but at least 60 s.\n *\n * Longer than a read's on purpose. A read that times out serves its cached\n * value; a write that times out may still have reached the studio, and the\n * visitor sees an error for a form that arrived. Do not blindly send it\n * again: you could store it twice.\n */\n writeTimeout?: number\n /**\n * A read with nothing cached that gets a `502` or `503` tries once more after\n * this many ms, plus up to as many again at random (so the reads of one page\n * do not all come back at once). Default `200`. `false` turns it off.\n *\n * Often one bad moment, such as a proxy switching to a new studio container;\n * and with nothing cached the error is all the caller would get. Never for a\n * read with a value cached (that value is served), a `cache: false` read,\n * a write, or an answer carrying `Retry-After`.\n */\n gatewayRetry?: number | false\n /**\n * How long, in ms from when it began, a read with nothing cached (or a\n * `cache: false` read) may wait for the studio's rate limit. Default\n * `10000`. `false` turns waiting off: a `429` is thrown at once.\n *\n * The studio's own `429` with `Retry-After` shuts a gate for this server\n * and key in the process, until the time it names but at most a minute:\n * reads with nothing cached hold back until then, instead of going out to\n * be refused as well, and the one that was refused is sent again, at most\n * twice. A `429` from something in front of the studio (a proxy's page)\n * shuts no gate; only the read it refused waits. Each adds a random spread to its\n * wait (up to a fifth of it, at least up to 1 s), so they do not come back\n * together. A wait that would end more than `rateLimitWait` after the read\n * began is not started; the random spread may take a read a little past it.\n * While the gate is shut nothing is sent that would only be refused: a\n * read that cannot wait for it (or has a value cached, or with `false`)\n * fails as a `429` would, without a request: a cached value is served,\n * else that `429` is thrown.\n *\n * The studio limits the requests per key and asks to wait a few seconds at\n * most; with nothing to show instead, waiting is better than an error. A\n * build that reads everything at once may want more. Never for a read with\n * a value cached (that value is served), a write, an upload, or a `429`\n * without `Retry-After`.\n */\n rateLimitWait?: number | false\n /**\n * Called for every studio failure the client absorbs: a failed stamp check,\n * or a read answered from the cache because its refresh failed. These never\n * reach your code as an error, so this is the only place to notice that the\n * site is running on cached content. Errors that are thrown to the caller\n * (a read with nothing cached, a write) are not repeated here.\n *\n * At most one call per stamp check and one per cache entry per retry pause,\n * so it is safe to log or alert from. Without it the client writes one\n * warning per outage to `logger`.\n */\n onError?: (failure: StudioFailure) => void\n /** Extra headers merged into every request. */\n headers?: Record<string, string>\n /**\n * Hold a live connection to the studio, which tells the moment content\n * changes, so an edit shows at the next read instead of up to `revalidate`\n * later. While it is up, reads skip the once-a-minute stamp check; when it\n * is down, they make it as before. It only ever replaces that check: it\n * fetches no content itself, keeps no process alive, and cannot fail a read.\n *\n * On by default in a long-lived Node process, for a client with a cache.\n * Off by default on serverless and in CI (`VERCEL`, `NETLIFY`, AWS Lambda,\n * Azure Functions, Google Cloud Functions and Cloud Run, Deno Deploy, `CI`),\n * with `cache.waitForFresh: false`, and with a custom `fetch` (the\n * connection goes over Node's `http`, not through it); `true` turns it on\n * there. Never in a browser or an edge runtime, nor without a cache or with\n * `revalidate: false`. One connection per server and key in a process, shared\n * by every client with those.\n */\n live?: boolean\n /**\n * Where beacon writes its lines. Default: the console. `false` writes\n * nothing at all. Every line goes here: once per process what a file cache\n * found on disk; in development (`NODE_ENV` is `development`, not in CI)\n * which project and key the client reads with, `connected to \"<project>\"\n * (key \"<key>\")`; and the warnings: an outage (unless `onError` is set), a\n * disk the cache cannot use (unless the `FileCacheStore` has its own\n * `onError`), a store shared by two keys, a Node too old for `cache.dir`.\n * Each line is one string, prefixed `[@nordhavnhq/beacon]`, sometimes with\n * the error's message as a second argument.\n */\n logger?: Logger | false\n}\n\n/** Per-call read options. */\nexport interface ReadOptions {\n /** Set `false` to bypass the cache for this call and always hit the network. */\n cache?: boolean\n /**\n * Locale for this read, overriding the client-level `locale`. Pass an empty\n * string to force the project default even when a client locale is set;\n * `undefined` or `null` (a missing header, from `headers.get()`) leaves the\n * client locale in place. Untranslated fields fall back to the default\n * locale. Only record reads use it (`listRecords`, `getRecord`, a dataset's\n * `list` and `get`); `query()`, `schema()`, `nodes()` and `locales()` ignore it.\n */\n locale?: string | null | undefined\n}\n\n/** Per-call options for `uploadFile`. */\nexport interface UploadOptions {\n /**\n * The file name to send, extension included: the studio checks the\n * extension against the field's allowed types. Defaults to the name of a\n * `File`; required for a plain `Blob`.\n */\n filename?: string\n /**\n * Give up after this many ms, body included. Defaults to the client's\n * `writeTimeout`, but at least 60 s (an upload may be 10 MB); `0` for none.\n * A client whose writes have no timeout (`writeTimeout: 0`, or `timeout: 0`\n * without one) uploads without one too. A negative number or `NaN` counts\n * as not given.\n */\n timeout?: number\n}\n\ntype Method = 'GET' | 'POST' | 'PATCH'\n\n/**\n * Typed client for the Nordhavn OS content API: read and write a project's node\n * datasets from any website or app. Reads are cached (see the `cache` option);\n * writes invalidate the affected cache entries automatically.\n *\n * ```ts\n * const studio = new NordhavnClient({ apiKey: 'slk_...', baseUrl: 'https://studio.example.com' })\n * const posts = await studio.dataset<Post>('blog', 'posts').list()\n * ```\n *\n * With `NORDHAVN_API_KEY` (and for a self-hosted studio `NORDHAVN_BASE_URL`)\n * in the environment, `new NordhavnClient()` is enough.\n */\nexport class NordhavnClient {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly fetchImpl: typeof fetch\n private readonly headers: Record<string, string>\n private readonly cache: ContentCache\n private readonly versionTracker: VersionTracker\n /** The client's share of the live connection, when it has one (`live` option). */\n private live: LiveLink | undefined\n /** Client-level default locale for reads (undefined = project default). */\n private readonly locale?: string\n /** Request timeout in ms, `0` for none. */\n private readonly timeout: number\n /** `writeTimeout` in ms, `0` for none. */\n private readonly writeTimeout: number\n /** `cache.waitForFresh` in ms, `Infinity` to wait for the studio. */\n private readonly waitForFresh: number\n /** `gatewayRetry` in ms, `undefined` when it is off. */\n private readonly gatewayRetry: number | undefined\n /** `rateLimitWait` in ms, `undefined` when it is off. */\n private readonly rateLimitWait: number | undefined\n /** Who this client is to the studio (`identityOf`): what the rate gate is kept per. Holds the key. */\n private readonly identity: string\n /** The `logger` option, `undefined` for `false`. */\n private readonly log: Logger | undefined\n /**\n * The refresh under way per cache key, so concurrent reads of one key share\n * one request, with the ticket it left on (see `state.ticket`).\n */\n private readonly inflight = new Map<string, { job: Promise<unknown>, ticket: number }>()\n /**\n * Per cache key, the ticket of the request whose answer the cache holds.\n * Emptied on every invalidation, capped by `STORED_LIMIT`. See `storable`.\n */\n private readonly storedBy = new Map<string, number>()\n private readonly onError?: (failure: StudioFailure) => void\n /**\n * Everything that changes while the client runs and is not a collection of\n * its own.\n */\n private readonly state = {\n /**\n * Numbers the requests in the order they leave. Answers come back in any\n * order, and the cache must never go back in time: a request takes a\n * ticket when it leaves, and `storable` compares it on the way back.\n */\n ticket: 0,\n /** The last ticket handed out when the cache was last invalidated. */\n invalidatedAt: 0,\n /** Set by an absorbed failure, cleared by the next answer: one warning per outage. */\n unreachable: false,\n /**\n * The project's locales as last read. Kept here and not only in the cache,\n * where the entry can be evicted: without the list a requested locale\n * cannot be mapped onto the key its content is cached under, and that\n * content would be out of reach for as long as the studio is away.\n */\n locales: undefined as ContentLocale[] | undefined,\n /** Epoch ms before which the locales are not asked for again, after that failed. */\n localesRetryAt: 0,\n /** Whether the first read still has to say which project this is (`announceProject`). */\n announce: false,\n }\n\n constructor(options: NordhavnClientOptions = {}) {\n const { apiKey, baseUrl } = connectionOf(options)\n this.apiKey = apiKey\n this.baseUrl = baseUrl\n const resolvedFetch = options.fetch ?? globalThis.fetch\n if (!resolvedFetch) {\n throw new Error('NordhavnClient: no `fetch` available; pass one via options.fetch')\n }\n this.fetchImpl = resolvedFetch.bind(globalThis)\n this.headers = options.headers ?? {}\n this.locale = options.locale || undefined\n this.timeout = normalizeTimeout(options.timeout)\n this.writeTimeout = normalizeWriteTimeout(this.timeout, options.writeTimeout)\n this.onError = options.onError\n this.log = loggerOf(options.logger)\n this.identity = identityOf(this.baseUrl, sentHeaders(this.apiKey, this.headers))\n\n const cacheOpt = options.cache\n const cacheOptions: ClientCacheOptions\n = cacheOpt === false ? { enabled: false }\n : cacheOpt === true || cacheOpt === undefined ? {}\n : cacheOpt\n this.cache = new ContentCache({ ...cacheOptions, store: cacheStore(cacheOptions, this.identity, this.log) })\n this.waitForFresh = normalizeWait(cacheOptions.waitForFresh)\n this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry)\n this.rateLimitWait = normalizeRateLimitWait(options.rateLimitWait)\n this.state.announce = wantAnnounce({ log: this.log, customFetch: options.fetch !== undefined })\n\n const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false\n ? 0\n : cacheOptions.revalidate ?? 60_000\n // The stamp check is tiny, and every read arriving while it runs waits on it,\n // so it gets a tighter budget than a full read.\n const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT)\n this.versionTracker = new VersionTracker(\n async () => {\n try {\n const res = await this.request<{ version?: unknown }>('GET', '/version', undefined, probeTimeout)\n // Anything but a stamp (a maintenance page answering 200) is no\n // answer: the last known stamp stands.\n if (typeof res?.version !== 'string') throw unexpectedBody(`${this.baseUrl}/api/content/version`)\n this.state.unreachable = false\n return res.version\n }\n catch (err) {\n // A studio without the route is up and answering: nothing to report.\n if (isMissingRoute(err)) this.state.unreachable = false\n else this.report({ during: 'stamp-check', error: err })\n throw err\n }\n },\n revalidate,\n isMissingRoute,\n )\n const live = wantLive({\n option: options.live,\n revalidating: revalidate > 0,\n customFetch: options.fetch !== undefined,\n waitsForStudio: this.waitForFresh === Infinity,\n })\n this.live = live ? new LiveLink(this.baseUrl, this.apiKey, this.headers, this) : undefined\n }\n\n /**\n * Lets go of the live connection: the last client of a server and key to\n * close it closes the connection. The client keeps working, on the stamp\n * check alone. Not needed to let a process end (the connection never keeps\n * one alive); for a test, or code that builds clients and drops them.\n */\n close(): void {\n this.live?.close()\n this.live = undefined\n }\n\n // ── Introspection ─────────────────────────────────────────────────────────\n\n /** The full content shape this key can reach: nodes, datasets, field schemas. */\n async schema(opts?: ReadOptions): Promise<ContentSchema> {\n return this.cachedGet<ContentSchema>('schema', '/schema', opts, has('nodes', Array.isArray))\n }\n\n /** Shorthand for `schema()` then `.nodes`. */\n async nodes(opts?: ReadOptions): Promise<SchemaNode[]> {\n return (await this.schema(opts)).nodes\n }\n\n /**\n * The locales this project's content can be requested in (default first). Use\n * a locale `code` as the client `locale` option or a per-call `opts.locale`.\n */\n async locales(opts?: ReadOptions): Promise<ContentLocale[]> {\n const res = await this.cachedGet<{ locales: ContentLocale[] }>('locales', '/locales', opts, has('locales', Array.isArray))\n return res.locales\n }\n\n /**\n * Resolve the locale for a read: per-call override, else the client default.\n * Only a value overrides: `{ locale: undefined }` (or `null`) is what a site\n * passes when the visitor sent no language, and must leave the client locale standing.\n * `''` is the one way to ask for the project default.\n */\n private resolveLocale(opts?: ReadOptions): string | undefined {\n // `!= null`: from plain JavaScript a missing header arrives as `null`\n // (`headers.get()`), and means the same as `undefined`.\n const l = opts?.locale != null ? opts.locale : this.locale\n return l || undefined\n }\n\n /**\n * The locale a read is requested and cached under: the requested one mapped\n * onto a locale the project is configured with (see `matchLocale`).\n *\n * Sites pass on whatever language the visitor's browser asks for, and the\n * studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed\n * by the raw value, each spelling would be its own cache entry and its own\n * request - and a stream of made-up ones would push every real entry out of\n * the cache, the last good values for an outage among them. Mapped first,\n * the cache holds one entry per configured locale, whatever is asked for.\n *\n * Without the list of locales (caching off, an older studio without the\n * route, studio unreachable and never read) the requested value goes to the\n * studio as it is, and the studio resolves it.\n */\n private async readLocale(opts?: ReadOptions): Promise<string | undefined> {\n const requested = this.resolveLocale(opts)?.trim() || undefined\n if (requested === undefined || !this.cache.enabled) return requested\n\n // A `cache: false` read is never tried twice (`gatewayRetry`), and\n // neither is the lookup it may have to wait for.\n const bypass = opts?.cache === false\n const configured = await this.configuredLocales(!bypass)\n return configured ? matchLocale(requested, configured) : requested\n }\n\n /**\n * The project's locales, or `undefined` when they have never been read and\n * cannot be now. An empty list is an answer like any other: the project has\n * no locales, the studio serves the same content whatever language is asked\n * for, and `matchLocale` then maps every request onto the default.\n *\n * Once the list is known this does not wait for anything: the read maps from\n * the list as it stands, and the list is brought up to date on the side. A\n * read therefore spends its `waitForFresh` on its content alone, and keeps\n * finding that content under the same key while the studio is away. Only\n * the very first localized read waits here, as it has nothing to map from.\n *\n * The exception is `waitForFresh: false`. That setting promises that a read\n * waits for the studio and leaves nothing running when it returns - what a\n * host needs that freezes the process once the response is out. So there\n * the list is brought up to date first, like the content after it.\n */\n private async configuredLocales(retry: boolean): Promise<ContentLocale[] | undefined> {\n const state = this.state\n if (Date.now() >= state.localesRetryAt) {\n // Always through the cache, also for a `cache: false` read: this runs on every\n // localized read, and a new locale shows up when the stamp moves.\n const lookup = this.cachedGet<{ locales: ContentLocale[] }>(\n 'locales',\n '/locales',\n { cache: true },\n has('locales', Array.isArray),\n retry,\n ).then(\n (res) => {\n state.locales = res.locales\n },\n () => {\n // Leave the list as it is, and the studio alone for a while.\n state.localesRetryAt = Date.now() + LOCALES_RETRY_MS\n },\n )\n if (state.locales === undefined || this.waitForFresh === Infinity) await lookup\n }\n return state.locales\n }\n\n // ── Records ───────────────────────────────────────────────────────────────\n\n /** List every record in a dataset (references inflated). Requires read scope. */\n async listRecords<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>[]> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ records: ContentRecord<T>[] }>(\n recordsKey(nodeSlug, datasetSlug, locale),\n datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),\n opts,\n has('records', Array.isArray),\n )\n return res.records\n }\n\n /** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */\n async getRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ record: ContentRecord<T> }>(\n recordKey(nodeSlug, datasetSlug, recordUid, locale),\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}${localeQuery(locale)}`,\n opts,\n has('record', isObject),\n )\n return res.record\n }\n\n /** Create a record. Requires write scope. Invalidates cached reads of the dataset. */\n async createRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'POST',\n datasetPath(nodeSlug, datasetSlug),\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Partially update a record. The patch is merged onto the stored data (omitted\n * top-level fields are preserved). Requires write scope. Invalidates cached\n * reads of the dataset and of this record.\n */\n async updateRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'PATCH',\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Upload one file for a `file` field, for a form that sends an attachment.\n * Requires write scope on the dataset. Returns the file; hang it on a record\n * in a second call by writing `{ uid }` into that field:\n *\n * ```ts\n * const attachment = form.get('attachment')\n * if (attachment instanceof File && attachment.size > 0) {\n * const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)\n * await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })\n * }\n * ```\n *\n * The field decides what it takes: its `mimes` and `max_size` rules, within\n * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The\n * studio reads the type from the content, so a renamed file is refused. Only\n * top-level fields. A file of the wrong type or size throws `NordhavnError` 400\n * with a message fit to show; other refusals (400, 403, 404) are setup\n * errors. More than 10 uploads a minute per key throws 429. From a Node\n * `Buffer`, send `new Blob([buffer])` with a `filename`.\n *\n * Server-side only: the key that uploads can write, and must never reach a\n * browser. Not retried, not cached, and it leaves cached reads alone: until a\n * record takes it up, the file belongs to no content. An upload that failed\n * may still have been stored; an unused one is removed after 24 hours.\n */\n async uploadFile(\n nodeSlug: string,\n datasetSlug: string,\n fieldSlug: string,\n file: Blob,\n opts?: UploadOptions,\n ): Promise<UploadedFile> {\n const filename = opts?.filename ?? (file as Partial<File>).name\n if (!filename) {\n throw new Error('NordhavnClient.uploadFile: the file has no name; pass `filename` (with its extension)')\n }\n const form = new FormData()\n form.set('file', file, filename)\n form.set('nodeSlug', nodeSlug)\n form.set('datasetSlug', datasetSlug)\n form.set('fieldSlug', fieldSlug)\n\n const url = `${this.baseUrl}/api/content/files`\n const timeout = uploadTimeout(this.writeTimeout, opts?.timeout)\n return withTimeout(url, timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method: 'POST',\n // No Content-Type: fetch sets the multipart one, with its boundary.\n headers: { Authorization: `Bearer ${this.apiKey}`, ...withoutContentType(this.headers) },\n body: form,\n signal,\n })\n if (!res.ok) throw await this.toError(res)\n // A maintenance page, or an empty body, is no upload either.\n const value: unknown = await res.json().catch(() => undefined)\n if (!has('uid', (uid) => typeof uid === 'string' && uid !== '')(value)) throw unexpectedBody(url)\n return value as UploadedFile\n })\n }\n\n /**\n * Sends a write and settles the cached reads of its dataset with the outcome.\n *\n * Stored: they are dropped. Refused (an answered 4xx): they are still right\n * and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves\n * open whether the studio carried the write out, so they are marked for a\n * recheck: the next read asks the studio again, and keeps the cached value to\n * fall back on if the studio is in fact down.\n */\n private async write<T>(method: Method, path: string, body: unknown, nodeSlug: string, datasetSlug: string): Promise<T> {\n let res: T\n try {\n res = await this.request<T>(method, path, body, this.writeTimeout)\n }\n catch (err) {\n if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, 'recheck')\n throw err\n }\n this.invalidateDataset(nodeSlug, datasetSlug)\n return res\n }\n\n // -- Queries --\n\n /** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */\n async query<V = unknown>(querySlug: string, opts?: ReadOptions): Promise<QueryResult<V>> {\n return this.cachedGet<QueryResult<V>>(\n `query:${querySlug}`,\n `/queries/${encodeURIComponent(querySlug)}`,\n opts,\n // Recognised by `shape`, never by `value`: that may be anything, and a\n // query without a result can come back with no `value` at all.\n has('shape', (shape) => typeof shape === 'string'),\n )\n }\n\n // ── Fluent dataset handle ───────────────────────────────────────────────────\n\n /**\n * A fluent, type-parameterised handle to one dataset:\n * `client.dataset<Post>('blog', 'posts').list()`.\n */\n dataset<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string): DatasetHandle<T> {\n return new DatasetHandle<T>(this, nodeSlug, datasetSlug)\n }\n\n // ── Cache control ───────────────────────────────────────────────────────────\n\n /**\n * Clear cached reads. With no argument, clears everything. Pass a scope to\n * clear just part of it: a node slug, or `{ node, dataset }` for one dataset.\n * A scoped clear also drops every saved query result, as any of them may\n * aggregate the content that was cleared.\n */\n clearCache(scope?: string | { node: string, dataset?: string }): void {\n if (scope === undefined) {\n this.cache.clear()\n this.invalidated()\n return\n }\n const node = typeof scope === 'string' ? scope : scope.node\n const dataset = typeof scope === 'string' ? undefined : scope.dataset\n if (dataset) {\n this.invalidateDataset(node, dataset)\n return\n }\n this.dropPrefix(`records:${node}/`)\n this.dropPrefix(`record:${node}/`)\n this.dropPrefix('query:')\n }\n\n /**\n * Invalidate cached record reads for a dataset (every locale), plus all query\n * results (which may aggregate it). `drop` removes them; `recheck` keeps each\n * value as a fallback but makes the next read ask the studio again.\n */\n private invalidateDataset(nodeSlug: string, datasetSlug: string, how: 'drop' | 'recheck' = 'drop'): void {\n const one = how === 'drop' ? (key: string) => this.drop(key) : (key: string) => this.recheck(key)\n const all = how === 'drop' ? (prefix: string) => this.dropPrefix(prefix) : (prefix: string) => this.recheckPrefix(prefix)\n // Default-locale list key + every `::<locale>` variant of it.\n one(recordsKey(nodeSlug, datasetSlug))\n all(`${recordsKey(nodeSlug, datasetSlug)}::`)\n // All single-record keys under the dataset (every uid, every locale).\n all(`${recordKey(nodeSlug, datasetSlug, '')}`)\n all('query:')\n }\n\n /** Drop one key from the cache. */\n private drop(key: string): void {\n this.cache.delete(key)\n this.invalidated()\n }\n\n /** `drop` for every key that starts with `prefix`. */\n private dropPrefix(prefix: string): void {\n this.cache.deletePrefix(prefix)\n this.invalidated()\n }\n\n /** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */\n private recheck(key: string): void {\n this.cache.expire(key)\n this.invalidated()\n }\n\n /** `recheck` for every key that starts with `prefix`. */\n private recheckPrefix(prefix: string): void {\n this.cache.expirePrefix(prefix)\n this.invalidated()\n }\n\n /**\n * Called by everything that invalidates cached reads. Every request that is\n * under way at this moment left before it, so its answer may show the\n * content as it was: none of them may store what they come back with\n * (`storable`), and no later read may join one of them (hence the cleared\n * `inflight`). They still answer the reads that were already waiting on them.\n *\n * Deliberately not narrowed to the keys that were invalidated. The price is\n * that an unrelated answer now and then is served without being stored, and\n * asked for once more; what it buys is one rule without exceptions.\n */\n private invalidated(): void {\n this.state.invalidatedAt = this.state.ticket\n this.storedBy.clear()\n this.inflight.clear()\n }\n\n /**\n * Whether the answer to the request that left on `ticket` may change what\n * the cache holds for `key`. The single gate in front of every cache write\n * that follows a request - cached read or bypass, a new value, a `304`, a\n * deletion or a retry pause alike. It keeps the cache from going back in time:\n *\n * - not when the cache was invalidated after the request left: the answer\n * may show the content from before (a write, `clearCache`);\n * - not when the cache already holds the answer to a request that left\n * later: that one is newer, whichever of the two came back first.\n */\n private storable(key: string, ticket: number): boolean {\n return ticket > this.state.invalidatedAt && ticket >= (this.storedBy.get(key) ?? 0)\n }\n\n /**\n * Settles the cache with the studio's own definitive \"no\" for `key` (deleted,\n * forbidden), in answer to the request that left on `ticket`: the entry goes.\n * The one place this happens, for a cached read and a bypass alike.\n *\n * The deletion is noted like any other answer. Without that, a request that\n * left earlier and comes back later would pass the gate and put the deleted\n * content straight back.\n */\n private gone(key: string, ticket: number): void {\n if (!this.storable(key, ticket)) return\n this.cache.delete(key)\n this.stored(key, ticket)\n }\n\n /**\n * Notes that the cache now reflects, for `key`, the answer to the request\n * that left on `ticket` - a value, a `304`, or the studio's own \"this does\n * not exist\", after which the cache holds nothing for it. A refresh of that\n * key that left earlier and is still under way is retired: a read arriving\n * now must not join it for an older answer than the cache already reflects.\n */\n private stored(key: string, ticket: number): void {\n // Unbounded growth is cut off the blunt, safe way: forget everything and\n // bar every request under way from storing, as an invalidation does.\n if (this.storedBy.size >= STORED_LIMIT) this.invalidated()\n this.storedBy.set(key, ticket)\n const running = this.inflight.get(key)\n if (running && running.ticket < ticket) this.inflight.delete(key)\n }\n\n // ── Transport ───────────────────────────────────────────────────────────────\n\n /**\n * The read path, with conditional revalidation.\n *\n * Steady state (project stamp unchanged since we last confirmed this entry):\n * served straight from cache, zero network. After a content change the stamp\n * moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps\n * the cached value, a `200` replaces it - and then it is fast again.\n *\n * Five rules hold for every read, whatever the studio does. Each is enforced\n * in exactly one place, named here, so that it cannot hold for one kind of\n * read and not for another:\n *\n * 1. A failure that is not the studio's own definitive answer never costs a\n * cached value: it is served instead, and stays cached (`refresh`).\n * 2. Only what is recognisably this endpoint's answer is ever stored\n * (`conditionalGet`).\n * 3. The cache never goes back in time: an answer is not stored when the\n * cache was invalidated, or filled with a newer answer, after its request\n * left (`storable`, in front of every write to the cache).\n * 4. A read that already holds a value waits on the studio for `waitForFresh`\n * at most, stamp check and refresh together (here); the refresh then\n * finishes on the side.\n * 5. One request per key at a time (`refresh`).\n */\n private async cachedGet<T>(\n cacheKey: string,\n path: string,\n opts: ReadOptions | undefined,\n isExpected: BodyCheck,\n /** Whether a `502`/`503` with nothing cached may be tried again (`gatewayRetry`). */\n retry = true,\n ): Promise<T> {\n const useCache = opts?.cache !== false\n this.announceOnce()\n\n // An explicit bypass: always fetch fresh and never fall back, but still\n // refresh the cache so the reads after it benefit from the warm entry.\n if (!useCache) {\n // The stamp as it stands before asking, like the cached path below. Read\n // after the answer it can be newer than the content that came back (an\n // edit landed in between, and another read's stamp check saw it), and\n // that older content would then count as current until the next edit.\n let version = this.versionTracker.current() ?? undefined\n let ticket = ++this.state.ticket\n let res: Answer\n try {\n // With nothing to fall back on it waits out a `429` (`rateLimitWait`),\n // but is not tried again after a `502`/`503` (`gatewayRetry`). A try\n // after a wait leaves later, so it takes a new ticket and stamp, as in\n // `refresh`.\n const got = await this.askRetrying<never>(path, undefined, isExpected, false, {\n allowed: () => true,\n resume: () => {\n ticket = ++this.state.ticket\n version = this.versionTracker.current() ?? undefined\n return undefined\n },\n })\n res = (got as { answer: Answer }).answer\n }\n catch (err) {\n // Never falls back - but the studio's own \"this does not exist\" is an\n // answer for the cache as well, here as on the cached path.\n if (isDefinitive(err)) this.gone(cacheKey, ticket)\n throw err\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n\n // With something to serve, expired or not, the studio gets a budget.\n const started = Date.now()\n const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity\n\n // Cheap, throttled: at most one tiny stamp request per `revalidate` window,\n // and none while the live connection is healthy (its stamp counts as a check).\n // A check that outlasts the budget carries on; this read uses the stamp we had.\n await within(this.checkVersion(started), budget)\n const version = this.versionTracker.current() ?? undefined\n const entry = this.cache.peek(cacheKey, Date.now())\n\n if (entry) {\n // Serve from cache when we cannot see a newer stamp (tracking off, first\n // probe not in yet, or studio unreachable) or the stamp is unchanged since\n // this entry was last confirmed.\n if (version === undefined || entry.validatedVersion === version) {\n return entry.value as T\n }\n }\n\n // Revalidate (the stamp moved) or refetch (miss / TTL expired). An expired\n // entry still has its etag, so an unchanged value comes back as a `304`.\n const last = entry ?? this.cache.stale(cacheKey)\n // A refetch failed moments ago: serve the last good value until the pause\n // is over, rather than making every read wait on an unreachable studio.\n if (last?.retryAt !== undefined && Date.now() < last.retryAt) {\n return last.value as T\n }\n\n const refresh = this.refresh<T>(cacheKey, path, last, version, isExpected, retry)\n if (!last) return refresh\n const outcome = await within(refresh, budget - (Date.now() - started))\n return outcome.settled ? outcome.value : last.value as T\n }\n\n /** On the first read, in development: which project this key reads (`announceProject`). */\n private announceOnce(): void {\n if (!this.state.announce) return\n this.state.announce = false\n announceProject(this.baseUrl, sentHeaders(this.apiKey, this.headers), this.log)\n }\n\n /** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */\n private checkVersion(now: number): Promise<void> {\n return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now)\n }\n\n /**\n * Fetches `cacheKey` from the studio and settles the cache with the answer.\n * One per key at a time: reads that arrive while it runs get the same promise,\n * so a slow studio sees one request for a key and not one per visitor.\n *\n * Resolves with the value to serve: the fresh one, or a cached one when the\n * studio failed transiently. Rejects on a definitive answer, or when there is\n * nothing cached to serve in its place.\n */\n private refresh<T>(\n cacheKey: string,\n path: string,\n last: CacheEntry | undefined,\n version: string | undefined,\n isExpected: BodyCheck,\n retry: boolean,\n ): Promise<T> {\n const running = this.inflight.get(cacheKey)\n if (running) return running.job as Promise<T>\n\n let ticket = ++this.state.ticket\n // Whether the slot for this key is still this refresh's own: once retired\n // it is empty, or belongs to the refresh that came after.\n const registered = (): boolean => this.inflight.get(cacheKey)?.job === job\n const register = (): void => {\n this.inflight.set(cacheKey, { job, ticket })\n }\n const job: Promise<T> = (async () => {\n try {\n // A read is safe to repeat, and with nothing cached the error is all\n // the caller would get, so a `502`/`503` or a `429` is tried again\n // (`askRetrying`). With a value to fall back on it is served instead,\n // as below.\n const got = await this.askRetrying<T>(path, last?.etag, isExpected, retry, {\n allowed: () => !last && !this.cache.stale(cacheKey),\n resume: () => {\n // Another request may have stored a value meanwhile: serve that.\n const meanwhile = this.cache.stale(cacheKey)\n if (meanwhile) return { value: meanwhile.value as T }\n // Or the slot went to a refresh that started during the pause, after\n // a newer answer retired this one's: that refresh left later, so its\n // answer is the one to have, and asking alongside it would break the\n // one request per key.\n const slot = this.inflight.get(cacheKey)\n // Handed back as it is, not awaited: its outcome is that refresh's\n // own, already settled with the cache there, not a failure of this one.\n if (slot && !registered()) return { value: slot.job as Promise<T> }\n\n // The next try leaves now, after anything that left during the\n // pause, so it takes a ticket of its own: under the first one its\n // answer, newer than theirs, would count as older (`storable`). The\n // slot carries it, so an older answer does not retire it (`stored`);\n // emptied meanwhile (an invalidation), it is taken again, so that\n // reads arriving now join this request instead of sending their own.\n // And it reads the stamp as it stands now, before leaving: the\n // answer is at least as new as that.\n ticket = ++this.state.ticket\n if (slot) slot.ticket = ticket\n else register()\n version = this.versionTracker.current() ?? undefined\n return undefined\n },\n })\n if ('value' in got) return got.value\n const res = got.answer\n // A `304` is only ever accepted in answer to an etag, so `last` is there.\n if (res.notModified && last) {\n if (this.storable(cacheKey, ticket)) {\n this.cache.confirm(cacheKey, version, Date.now())\n this.stored(cacheKey, ticket)\n }\n return last.value as T\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n catch (err) {\n // Definitive answer from the studio itself (deleted/forbidden): drop the\n // entry and surface it.\n if (isDefinitive(err)) {\n this.gone(cacheKey, ticket)\n throw err\n }\n // Anything else is transient: studio down, 5xx, timeout, rate limit,\n // network, a body that is not what this endpoint returns, or a 4xx from\n // whatever stands in front of the studio while it is gone. Serve a\n // cached value, even an expired one, and keep it.\n //\n // What the cache holds *now*, not only what it held when this request\n // left: every read that joined gets this same outcome, and one of them\n // may hold a value that was stored in the meantime (by a `cache: false`\n // read, say) while the read that started the request had none. Failing that\n // one with an error it had the content for is exactly what rule 1 forbids.\n const held = this.cache.stale(cacheKey) ?? last\n if (!held) throw err\n this.report({ during: 'read', key: cacheKey, error: err })\n return (this.storable(cacheKey, ticket) ? this.cache.backoff(cacheKey, held, Date.now()) : held).value as T\n }\n finally {\n if (registered()) this.inflight.delete(cacheKey)\n }\n })()\n this.inflight.set(cacheKey, { job, ticket })\n return job\n }\n\n /**\n * Sends a read's request, and sends it again where the failure says that\n * may help (`retryPause`) and `hooks.allowed()` says the read has nothing to\n * serve instead; such a read is also held back while its key is rate\n * limited (`holdBack`). Every other failure is thrown as it is.\n *\n * The one retry loop of the read path, for the cached read (`refresh`) and\n * the bypass alike, so the waits are the same for both. What differs sits in\n * the hooks: `resume` runs after each wait, just before the next try, and\n * either ends the read without one (`{ value }`: what another request stored\n * meanwhile, a newer refresh to join) or takes the ticket and stamp the\n * next try leaves with and returns `undefined`.\n *\n * A next try only ever happens with nothing cached, so it never has an etag\n * to send: `etag` is the first try's.\n */\n private async askRetrying<T>(\n path: string,\n etag: string | undefined,\n isExpected: BodyCheck,\n /** Whether a `502`/`503` may be tried again (`gatewayRetry`). */\n gateway: boolean,\n hooks: {\n allowed: () => boolean\n resume: () => { value: T | Promise<T> } | undefined\n },\n ): Promise<{ answer: Answer } | { value: T | Promise<T> }> {\n const read: ReadTries = { started: Date.now(), gateway, rateLimited: 0, heldUntil: 0, spread: false }\n let ifNoneMatch = etag\n for (;;) {\n if (await this.holdBack(read, hooks.allowed())) {\n const early = hooks.resume()\n if (early) return early\n ifNoneMatch = undefined\n continue\n }\n try {\n return { answer: await this.conditionalGet(path, ifNoneMatch, isExpected) }\n }\n catch (err) {\n // Only the studio's own `429` shuts the gate for every read of the key:\n // one from a proxy or a WAF page holds back no read but this one.\n const asked = rateLimitPause(err)\n if (asked !== undefined && err instanceof NordhavnError && isStudioAnswer(err)) shutGate(this.identity, asked)\n const pause = hooks.allowed() ? this.retryPause(err, read) : undefined\n if (pause === undefined) throw err\n ifNoneMatch = undefined\n // After a `429` the wait is `holdBack`'s, at the top of the loop.\n if (pause === 'hold') continue\n await sleep(pause)\n const early = hooks.resume()\n if (early) return early\n }\n }\n }\n\n /**\n * Whether, and how, a failed read with nothing cached is sent again;\n * counts what it allows in `read`.\n *\n * - A `502` or `503` is often one bad moment (a proxy switching to a new\n * studio container): once, `gatewayRetry` later plus up to as much at\n * random. Not when it carried `Retry-After`: that one asked to wait.\n * - A `429` with `Retry-After`: `'hold'`, so `holdBack` waits as asked, at\n * most `MAX_RATE_LIMIT_RETRIES` times, and only when that wait ends\n * within `rateLimitWait` of the read's start. Without `Retry-After`\n * nothing says when it would help: thrown.\n */\n private retryPause(err: unknown, read: ReadTries): number | 'hold' | undefined {\n if (read.gateway && this.gatewayRetry !== undefined && isGatewayHiccup(err)) {\n read.gateway = false\n return this.gatewayRetry + Math.random() * this.gatewayRetry\n }\n const asked = rateLimitPause(err)\n if (asked === undefined || this.rateLimitWait === undefined || read.rateLimited >= MAX_RATE_LIMIT_RETRIES) return undefined\n const now = Date.now()\n if (now + asked - read.started > this.rateLimitWait) return undefined\n read.rateLimited++\n read.heldUntil = now + asked\n read.spread = true\n return 'hold'\n }\n\n /**\n * Keeps a read from going out while its key is rate limited: until its own\n * `429` said, or the studio's own `429` to any read of this server and key\n * in the process (`gateRemaining`, at most a minute). Resolves `true` after\n * waiting, `false` to go now.\n *\n * A read with nothing cached (`uncached`) waits for the gate, plus a random\n * spread (`spreadOf`, also after a `Retry-After: 0`), when that wait ends\n * within `rateLimitWait` of the read's start. Otherwise (a read with a value\n * cached, a wait that does not fit, `rateLimitWait: false`) the request is\n * not sent: the studio already said this key must wait, so it would be\n * refused, and count against the key's limit as well. It fails as that\n * refusal would (`heldBackError`), so a cached value is served in its place\n * and a read with nothing cached throws, without a request.\n */\n private async holdBack(read: ReadTries, uncached: boolean): Promise<boolean> {\n const now = Date.now()\n // The gate keeps its own (monotonic) clock; here it is a moment on the read's.\n const gateLeft = gateRemaining(this.identity)\n const gate = gateLeft > 0 ? now + gateLeft : 0\n const until = uncached ? Math.max(gate, read.heldUntil) : gate\n if (until <= now && !read.spread) return false\n if (!uncached || this.rateLimitWait === undefined || until - read.started > this.rateLimitWait) {\n throw heldBackError(until - now)\n }\n read.spread = false\n const wait = Math.max(0, until - now)\n await sleep(wait + spreadOf(wait))\n return true\n }\n\n /**\n * Hands an absorbed failure to `onError`, or without one warns once per\n * outage. Never throws and never leaves a rejection behind: a broken hook\n * must not turn a served read into an error, and an `async` hook whose own\n * work fails (an alert that cannot be delivered, during the very outage it\n * reports) must not become the unhandled rejection that stops the process.\n */\n private report(failure: StudioFailure): void {\n const first = !this.state.unreachable\n this.state.unreachable = true\n try {\n if (this.onError) {\n const outcome: unknown = this.onError(failure)\n if (isThenable(outcome)) outcome.then(undefined, () => {})\n }\n else if (first) {\n const reason = failure.error instanceof Error ? failure.error.message : String(failure.error)\n const what = failure.during === 'read' ? `could not refresh \"${failure.key}\"` : 'stamp check failed'\n logLine(this.log, 'warn', `${what} (${reason}); cached content keeps being served.`)\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /**\n * A GET that understands conditional requests: sends `If-None-Match` when an\n * etag is supplied, and reports a `304` as `notModified` rather than a value.\n *\n * The one place that decides what counts as an answer, for every read:\n *\n * - A `2xx` whose body fails `isExpected` is rejected, not returned. A\n * maintenance page or a captive portal can answer `200` with JSON of its\n * own; storing that would replace the last good value with nothing, at the\n * very moment the studio is away.\n * - A `304` is only an answer to a request that sent an etag. Unasked for,\n * it says \"keep what you have\" to a caller that has nothing, and there is\n * no value to return or store.\n */\n private async conditionalGet(\n path: string,\n ifNoneMatch: string | undefined,\n isExpected: BodyCheck,\n ): Promise<Answer> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, this.timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(ifNoneMatch ? { 'If-None-Match': ifNoneMatch } : {}),\n ...this.headers,\n },\n signal,\n })\n\n if (res.status === 304) {\n if (!ifNoneMatch) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: true, etag: res.headers.get('etag') ?? ifNoneMatch }\n }\n if (!res.ok) throw await this.toError(res)\n const etag = res.headers.get('etag') ?? undefined\n const value: unknown = res.status === 204 ? undefined : await res.json()\n if (!isExpected(value)) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: false, value, etag }\n })\n }\n\n private async request<T>(method: Method, path: string, body?: unknown, timeout = this.timeout): Promise<T> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...this.headers,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal,\n })\n\n if (!res.ok) throw await this.toError(res)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n })\n }\n\n /** Parse a non-2xx response into a `NordhavnError`, preferring its message. */\n private async toError(res: Response): Promise<NordhavnError> {\n let message = res.statusText || `Request failed with status ${res.status}`\n let parsed: unknown\n try {\n parsed = await res.json()\n const m = parsed as { message?: unknown, statusMessage?: unknown }\n if (typeof m?.message === 'string') message = m.message\n else if (typeof m?.statusMessage === 'string') message = m.statusMessage\n } catch {\n /* non-JSON error body; keep the status text */\n }\n const err = new NordhavnError(message, res.status, parsed)\n if (res.headers.has('retry-after')) askedToWait.set(err, parseRetryAfter(res.headers.get('retry-after'), Date.now()))\n return err\n }\n}\n\n/** Fluent, dataset-scoped view returned by `client.dataset()`. */\nexport class DatasetHandle<T = Record<string, unknown>> {\n constructor(\n private readonly client: NordhavnClient,\n private readonly nodeSlug: string,\n private readonly datasetSlug: string,\n ) {}\n\n list(opts?: ReadOptions): Promise<ContentRecord<T>[]> {\n return this.client.listRecords<T>(this.nodeSlug, this.datasetSlug, opts)\n }\n\n get(recordUid: string, opts?: ReadOptions): Promise<ContentRecord<T>> {\n return this.client.getRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, opts)\n }\n\n create(data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.createRecord<T>(this.nodeSlug, this.datasetSlug, data)\n }\n\n update(recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.updateRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, data)\n }\n\n /** Upload a file for one of this dataset's file fields; see `NordhavnClient.uploadFile`. */\n uploadFile(fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile> {\n return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts)\n }\n\n /** Clear cached reads for this dataset. */\n clearCache(): void {\n this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug })\n }\n}\n\n// ── Timeout ───────────────────────────────────────────────────────────────────\n\n/**\n * Runs `run` with an abort signal that fires after `ms`, and rejects with a\n * `TimeoutError` at that moment whether or not `run` listens to the signal: a\n * custom `fetch` may ignore it. The timer spans the whole of `run`, so a studio\n * that sends headers and then stalls the body is caught too.\n *\n * The error is a plain `Error`, not a `NordhavnError`: the read path treats\n * anything without an HTTP status as transient and serves the cache.\n */\nasync function withTimeout<T>(url: string, ms: number, run: (signal?: AbortSignal) => Promise<T>): Promise<T> {\n if (ms <= 0) return run(undefined)\n\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const err = new Error(`The studio did not answer within ${ms}ms: ${url}`)\n err.name = 'TimeoutError'\n controller.abort(err)\n reject(err)\n }, ms)\n })\n\n try {\n return await Promise.race([run(controller.signal), expired])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * The `timeout` option as a usable number of ms, `0` for none. `Infinity`, or\n * more than a timer can hold, means \"no timeout\" - handed to `setTimeout` as\n * it is, it would fire after 1 ms and fail every request.\n */\nfunction normalizeTimeout(value: number | undefined): number {\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT\n return value > MAX_TIMER ? 0 : value\n}\n\n/**\n * `writeTimeout` in ms, `0` for none. A valid one wins; otherwise (none, or a\n * negative number or `NaN`) the read `timeout`, but at least\n * `MIN_WRITE_TIMEOUT`, and none for a client without a timeout.\n */\nfunction normalizeWriteTimeout(timeout: number, value: number | undefined): number {\n if (typeof value === 'number' && !Number.isNaN(value) && value >= 0) return normalizeTimeout(value)\n return timeout === 0 ? 0 : Math.max(timeout, MIN_WRITE_TIMEOUT)\n}\n\n/**\n * An upload's timeout in ms, `0` for none. A valid per-call `timeout` wins;\n * otherwise (none, or a negative number or `NaN`, as from an unset\n * environment variable) the client's `writeTimeout`, but at least\n * `MIN_UPLOAD_TIMEOUT`. A client whose writes have no timeout (`0`) uploads\n * without one too.\n */\nfunction uploadTimeout(writeTimeout: number, perCall: number | undefined): number {\n if (typeof perCall === 'number' && perCall >= 0) return normalizeTimeout(perCall)\n return writeTimeout === 0 ? 0 : Math.max(writeTimeout, MIN_UPLOAD_TIMEOUT)\n}\n\n/**\n * The client's extra headers without a `Content-Type`: one set for every\n * request would replace the multipart type and its boundary, and the studio\n * could not read the upload.\n */\nfunction withoutContentType(headers: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'content-type'))\n}\n\n/** `gatewayRetry` in ms, `undefined` when the second try is off. */\nfunction normalizeGatewayRetry(value: number | false | undefined): number | undefined {\n if (value === false) return undefined\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY\n return Math.min(value, MAX_GATEWAY_RETRY)\n}\n\n/** `rateLimitWait` in ms, `undefined` when waiting out a `429` is off. */\nfunction normalizeRateLimitWait(value: number | false | undefined): number | undefined {\n if (value === false) return undefined\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_RATE_LIMIT_WAIT\n return Math.min(value, MAX_TIMER)\n}\n\n/** `cache.waitForFresh` in ms, `Infinity` when a read should wait for the studio. */\nfunction normalizeWait(value: number | false | undefined): number {\n if (value === false) return Infinity\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH\n // More than a timer can hold is no budget at all: `within` already waits\n // such a value out, so it is made to mean `false` everywhere, in one place.\n return value > MAX_TIMER ? Infinity : value\n}\n\ntype Settled<T> = { settled: true, value: T } | { settled: false }\n\n/**\n * Waits on `promise` for at most `ms`. Past that it reports \"not settled\" and\n * lets the promise run on; a later rejection is swallowed here, as whoever\n * started the work deals with its outcome. A rejection within `ms` is thrown.\n */\nasync function within<T>(promise: Promise<T>, ms: number): Promise<Settled<T>> {\n if (ms > MAX_TIMER) return { settled: true, value: await promise }\n if (ms <= 0) {\n promise.catch(() => {})\n return { settled: false }\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined\n const late = new Promise<Settled<T>>((resolve) => {\n timer = setTimeout(() => resolve({ settled: false }), ms)\n })\n try {\n return await Promise.race([promise.then((value): Settled<T> => ({ settled: true, value })), late])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n// ── Response shape ────────────────────────────────────────────────────────────\n\n/** Whether a value is a promise, or anything else that settles later. */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === 'function'\n}\n\n/** Whether a response body is what its endpoint returns. */\ntype BodyCheck = (body: unknown) => boolean\n\n/** What `conditionalGet` comes back with. */\ntype Answer = { notModified: boolean, value?: unknown, etag?: string }\n\n/** Where one read stands in its retries (`askRetrying`). */\ninterface ReadTries {\n /** Epoch ms the read's first try was due: what `rateLimitWait` counts from. */\n started: number\n /** Whether the one more try after a `502`/`503` is still to come. */\n gateway: boolean\n /** Tries sent again after a `429` so far. */\n rateLimited: number\n /** Epoch ms until which its own `429` asked it to wait. */\n heldUntil: number\n /** Whether the next try still owes a random spread (after a `429`, even with `Retry-After: 0`). */\n spread: boolean\n}\n\nfunction isObject(value: unknown): boolean {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A body that is an object carrying `field`, with a value that passes `check`. */\nfunction has(field: string, check: (value: unknown) => boolean): BodyCheck {\n return (body) => isObject(body) && field in (body as object) && check((body as Record<string, unknown>)[field])\n}\n\n/**\n * The error for a response its endpoint never gives: a `2xx` with a body of\n * another shape, or a `304` nobody asked for. A plain `Error` without a status,\n * so the read path treats it as transient and serves the cache.\n */\nfunction unexpectedBody(url: string): Error {\n const err = new Error(`The studio answered with an unexpected response: ${url}`)\n err.name = 'UnexpectedResponseError'\n return err\n}\n\n// ── Cache-key + path helpers ──────────────────────────────────────────────────\n\n/**\n * Whether an error status says \"try again later\" rather than \"this is the\n * answer\": server errors, request timeout (408) and rate limiting (429).\n */\nfunction isTransientStatus(status: number): boolean {\n return status >= 500 || status === 408 || status === 429\n}\n\n/**\n * Errors whose response carried `Retry-After`, with the wait it asked for in\n * ms (`undefined` when it could not be read): the studio, or the proxy in\n * front of it, asked to wait, so they are not tried again a moment later, and\n * a `429` is tried again only after that wait. Kept here instead of on the\n * error, which is public API.\n */\nconst askedToWait = new WeakMap<object, number | undefined>()\n\n/**\n * The `429` a request held back by the rate gate fails with (`holdBack`):\n * the studio's own answer as it would have come, status, body and all, with\n * the wait that is left as its `Retry-After`, so everything after it (a\n * cached value served, an error thrown) goes as for a `429` that was sent.\n * Its message says that it was not sent.\n */\nfunction heldBackError(waitMs: number): NordhavnError {\n const seconds = Math.max(1, Math.ceil(waitMs / 1000))\n const message = `Too many requests: this key is rate limited for ${seconds} s more, so the request was not sent`\n const err = new NordhavnError(message, 429, { statusCode: 429, statusMessage: 'Too Many Requests', message })\n askedToWait.set(err, Math.max(0, waitMs))\n return err\n}\n\n/** The wait a `429` asked for, in ms, or `undefined` when it named none. */\nfunction rateLimitPause(err: unknown): number | undefined {\n return err instanceof NordhavnError && err.status === 429 ? askedToWait.get(err) : undefined\n}\n\n/**\n * A `502` or `503`: worth one more try a moment later. A `504` already waited,\n * and an answer with `Retry-After` asked not to.\n */\nfunction isGatewayHiccup(err: unknown): boolean {\n return err instanceof NordhavnError && (err.status === 502 || err.status === 503) && !askedToWait.has(err)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Whether a failed read is the studio's own definitive answer - this does not\n * exist, this key may not see it - rather than a sign that the studio could\n * not be reached. The only kind of failure that may cost a cached value.\n */\nfunction isDefinitive(err: unknown): err is NordhavnError {\n return err instanceof NordhavnError && !isTransientStatus(err.status) && isStudioAnswer(err)\n}\n\n/**\n * Whether an error response was written by the studio, and not by something\n * answering in its place. While the studio container is gone (a redeploy, a\n * crash) the proxy in front of it answers for it, and often with a `404`:\n * Traefik's `404 page not found`, an HTML error page, a gateway's own JSON.\n * Taking that for \"this record was deleted\" would drop the very entry that\n * should carry the site through the outage.\n *\n * The studio's errors are JSON objects that restate their status\n * (`{ \"statusCode\": 404, \"message\": \"...\" }`); nothing else is trusted to be\n * the studio speaking. `status` is accepted next to `statusCode`, the name\n * newer server frameworks give the same field.\n */\nfunction isStudioAnswer(err: NordhavnError): boolean {\n return isStudioBody(err.status, err.body)\n}\n\n/**\n * Whether a failed stamp check says \"this studio has no stamp route\": its own\n * `404`, as an older server answers. Not the `404` of a proxy standing in for a\n * studio that is away - that one is an outage like any other.\n */\nfunction isMissingRoute(err: unknown): boolean {\n return err instanceof NordhavnError && err.status === 404 && isStudioAnswer(err)\n}\n\n/**\n * Whether a failed write may have been stored all the same. Only an answered\n * 4xx rules it out: the request was refused. A timeout, a dropped connection or\n * a 5xx can each follow a write the studio did carry out.\n */\nfunction writeMayHaveLanded(err: unknown): boolean {\n return !(err instanceof NordhavnError && err.status >= 400 && err.status < 500)\n}\n\nfunction datasetPath(nodeSlug: string, datasetSlug: string): string {\n return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`\n}\n\n/**\n * Maps a requested locale onto one the project is configured with, by the rule\n * the studio applies itself: the exact locale, else one in the same language\n * (`nl` or `nl-NL` for a configured `nl-BE`), else the project's fallback\n * locale. `undefined` means the project default, which is requested by sending\n * no locale at all.\n *\n * With several locales in one language and no exact match, the default locale\n * wins if it is among them, otherwise the first one listed.\n */\nfunction matchLocale(requested: string, locales: ContentLocale[]): string | undefined {\n const canonical = (code: string): string => code.trim().toLowerCase().replace(/_/g, '-')\n const known = locales.filter((locale) => typeof locale?.code === 'string' && locale.code !== '')\n const wanted = canonical(requested)\n\n const exact = known.find((locale) => canonical(locale.code) === wanted)\n if (exact) return exact.code\n\n const language = wanted.split('-')[0]\n const related = known.filter((locale) => canonical(locale.code).split('-')[0] === language)\n const close = related.find((locale) => locale.isDefault) ?? related[0]\n if (close) return close.code\n\n return known.find((locale) => locale.isFallback)?.code\n}\n\n/** `?locale=xx` query suffix, or empty for the default locale. */\nfunction localeQuery(locale?: string): string {\n return locale ? `?locale=${encodeURIComponent(locale)}` : ''\n}\n\n/** Locale cache-key suffix. `::<locale>` keeps each locale a distinct entry;\n * the default locale has no suffix. `::` never collides with a slug. */\nfunction localeKeySuffix(locale?: string): string {\n return locale ? `::${locale}` : ''\n}\n\nfunction recordsKey(nodeSlug: string, datasetSlug: string, locale?: string): string {\n return `records:${nodeSlug}/${datasetSlug}${localeKeySuffix(locale)}`\n}\n\nfunction recordKey(nodeSlug: string, datasetSlug: string, recordUid: string, locale?: string): string {\n return `record:${nodeSlug}/${datasetSlug}/${recordUid}${localeKeySuffix(locale)}`\n}\n","/**\n * The chart contract: what a chart block is (`ChartSpec`, as authored and\n * stored) and what a renderer draws (`ChartData`, the resolved categories and\n * series). Shared by the Nordhavn OS server, the client and every renderer, so a\n * chart means the same thing wherever it is read. Pure data: no dependencies.\n * The zod schemas for these shapes live in `@nordhavnhq/beacon/schema`.\n */\n\n/**\n * The palette a series colour may pick from. A renderer maps a key to a colour\n * of the theme it runs in; a spec never carries a raw hex.\n */\nexport const PALETTE_KEYS = ['ember', 'aurora', 'crimson', 'dusk', 'jade', 'cobalt', 'iris', 'nebula'] as const\nexport type PaletteKey = typeof PALETTE_KEYS[number]\n\nexport const CHART_TYPES = ['bar', 'bar-horizontal', 'line', 'area', 'pie', 'donut', 'share', 'heatmap'] as const\nexport type ChartType = typeof CHART_TYPES[number]\n\n/**\n * How a chart reads its data: `cartesian` plots each series over the\n * categories, `part` cuts one series into its categories (one whole), `matrix`\n * is a grid of the categories (columns) by the series (rows).\n */\nexport type ChartFamily = 'cartesian' | 'part' | 'matrix'\n\n/** What a chart type is and takes: every editor, parser and renderer reads it from here. */\nexport interface ChartTypeInfo {\n value: ChartType\n label: string\n /** One line on what the type is for (editor hint, agent docs). */\n purpose: string\n /** A lucide icon name (kebab-case); the host maps it to its icon set. */\n icon: string\n family: ChartFamily\n /** Exactly one series (the parts are the categories). */\n singleSeries: boolean\n /** Series may sit on a left or right value axis. */\n axes: boolean\n /** Series may stack. */\n stacked: boolean\n /** Each series wears its own colour (else one hue in tints). */\n seriesColors: boolean\n /** Value labels on the marks are possible. */\n valueLabels: boolean\n /** Drawn as HTML that sizes to its content, not into a fixed canvas box. */\n html: boolean\n /** Default box height in px. */\n height: number\n}\n\nexport const CHART_TYPE_INFO: Record<ChartType, ChartTypeInfo> = {\n 'bar': {\n value: 'bar', label: 'Bar', icon: 'chart-column', family: 'cartesian',\n purpose: 'Compare values across categories or periods.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'bar-horizontal': {\n value: 'bar-horizontal', label: 'Bar (horizontal)', icon: 'chart-bar', family: 'cartesian',\n purpose: 'Rank categories with long labels, largest on top when sorted by value.',\n singleSeries: false, axes: false, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'line': {\n value: 'line', label: 'Line', icon: 'chart-line', family: 'cartesian',\n purpose: 'A trend over time.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'area': {\n value: 'area', label: 'Area', icon: 'chart-area', family: 'cartesian',\n purpose: 'A trend over time with its volume.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'pie': {\n value: 'pie', label: 'Pie', icon: 'chart-pie', family: 'part',\n purpose: 'Parts of one whole, few slices.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'donut': {\n value: 'donut', label: 'Donut', icon: 'circle-dashed', family: 'part',\n purpose: 'Parts of one whole around a centred total (status, category breakdown).',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'share': {\n value: 'share', label: 'Share bars', icon: 'align-left', family: 'part',\n purpose: 'Parts of one whole as ranked thin bars with figure and percentage; reads well with many parts.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: true, height: 260,\n },\n 'heatmap': {\n value: 'heatmap', label: 'Heatmap', icon: 'grid-3x3', family: 'matrix',\n purpose: 'A grid of the categories (columns) by the series (rows), one hue from faint to full.',\n singleSeries: false, axes: false, stacked: false, seriesColors: false, valueLabels: true, html: false, height: 300,\n },\n}\n\nexport function chartTypeInfo(type: ChartType): ChartTypeInfo {\n return CHART_TYPE_INFO[type] ?? CHART_TYPE_INFO.bar\n}\n\n/** Pie, donut and share: one series cut into its categories. */\nexport function isPartChart(type: ChartType): boolean {\n return chartTypeInfo(type).family === 'part'\n}\n\n/** Bar in either direction. */\nexport function isBarChart(type: ChartType): boolean {\n return type === 'bar' || type === 'bar-horizontal'\n}\n\n/** Which Y axis a series scales against. Only for the types with `axes`. */\nexport const CHART_AXES = ['left', 'right'] as const\nexport type ChartAxis = typeof CHART_AXES[number]\n\n/** Periods a date category can be grouped into. */\nexport const DATE_BUCKET_VALUES = ['day', 'week', 'month', 'quarter', 'year'] as const\nexport type DateBucket = typeof DATE_BUCKET_VALUES[number]\n\n/** `auto` picks the period from the date range. */\nexport const BUCKET_MODES = ['auto', ...DATE_BUCKET_VALUES] as const\nexport type BucketMode = typeof BUCKET_MODES[number]\n\n/** How the records that fall in one category combine into one point. */\nexport const AGGREGATIONS = ['sum', 'avg', 'count', 'min', 'max', 'first', 'last'] as const\nexport type Aggregation = typeof AGGREGATIONS[number]\n\n/** Category order. `default` is chronological for dates, source order otherwise. */\nexport const CHART_SORTS = ['default', 'category-asc', 'category-desc', 'value-desc', 'value-asc'] as const\nexport type ChartSort = typeof CHART_SORTS[number]\n\nexport interface ChartSeriesSpec {\n /** Field slug whose numeric value is the Y value. */\n field: string\n label?: string\n /** Omitted: the next colour of the renderer's default rotation. */\n color?: PaletteKey\n axis: ChartAxis\n aggregate: Aggregation\n}\n\n/** A chart as authored and stored: where its data comes from and how it is shaped. */\nexport interface ChartSpec {\n title: string\n chartType: ChartType\n /** A dataset (`node.dataset`) or a saved query (`queries.<slug>`). */\n source: string\n /** Field slug for the X axis or the slice labels. */\n categoryField: string\n /**\n * Field slug to split the first series by: one series per distinct value of\n * this field (top 12 by record count, the rest as \"Other\"). The rows of a\n * heatmap, the stacks of a bar. Empty: the series are the value fields.\n */\n splitField: string\n series: ChartSeriesSpec[]\n /** Date categories only. */\n bucket: BucketMode\n sort: ChartSort\n /** Keep the top N categories, the rest becomes \"Other\". 0 is no limit. Non-date only. */\n limit: number\n /** Date buckets only: emit empty periods so a line stays continuous. */\n fillGaps: boolean\n stacked: boolean\n legend: boolean\n}\n\nexport interface ChartSeriesData {\n name: string\n /** One value per category; null is a gap (nothing measured there). */\n data: Array<number | null>\n /** A palette key or any CSS colour the host resolved. */\n color?: string\n axis?: ChartAxis\n}\n\n/** A chart as a renderer draws it: the data already resolved and consolidated. */\nexport interface ChartData {\n type: ChartType\n categories: string[]\n series: ChartSeriesData[]\n stacked?: boolean\n legend?: boolean\n}\n","/**\n * The ```chart fence: a chart written inline in markdown, as JSON in the\n * shape a renderer draws (`ChartData`) plus a title. One parser for every\n * reader: the Nordhavn OS server validates a save with it, the markdown renderer\n * draws what it returns, the PDF export rasterises it, a site can use it too.\n * Pure and dependency-free.\n *\n * A `{{ expr }}` signal may stand where a number goes (`\"data\": [{{ a.b }}, 4]`).\n * The host fills it in before parsing; whatever is still left reads as a gap\n * (null), so a document never fails to save or print on a signal.\n */\nimport { CHART_AXES, CHART_TYPES, PALETTE_KEYS, chartTypeInfo, type ChartData, type ChartSeriesData } from './chart'\n\n/** The fence language. */\nexport const CHART_FENCE_LANG = 'chart'\n\nexport const CHART_FENCE_LIMITS = {\n categories: 100,\n series: 12,\n label: 120,\n title: 200,\n minHeight: 120,\n maxHeight: 600,\n} as const\n\n/** A chart as a ```chart fence carries it. */\nexport interface ChartFence extends ChartData {\n title?: string\n /** Box height in px; the renderer's default when omitted. */\n height?: number\n /** Value labels on the marks (bar types and heatmap). */\n valueLabels?: boolean\n}\n\nexport type ChartFenceResult = { ok: true, chart: ChartFence } | { ok: false, error: string }\n\nconst SIGNAL_RE = /\\{\\{[\\s\\S]*?\\}\\}/g\n\n/** Box height of a fenced chart in px: its own `height`, else a default per type. */\nexport function chartFenceHeight(chart: Pick<ChartFence, 'type' | 'height'>): number {\n if (chart.height) return chart.height\n return chartTypeInfo(chart.type).height\n}\n\n/** True for the language of a ```chart fence (case-insensitive, options after it ignored). */\nexport function isChartFence(lang: string | null | undefined): boolean {\n return (lang ?? '').trim().split(/\\s+/)[0]?.toLowerCase() === CHART_FENCE_LANG\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\nfunction oneOf<T extends string>(list: readonly T[], v: unknown): v is T {\n return typeof v === 'string' && (list as readonly string[]).includes(v)\n}\n\nfunction label(v: unknown, what: string, max: number = CHART_FENCE_LIMITS.label): string {\n if (typeof v === 'number' && Number.isFinite(v)) return String(v)\n if (typeof v !== 'string') throw new Error(`${what} must be a string`)\n if (v.length > max) throw new Error(`${what} is longer than ${max} characters`)\n return v\n}\n\nfunction parseSeries(raw: unknown, i: number, size: number): ChartSeriesData {\n const at = `series[${i}]`\n if (!isRecord(raw)) throw new Error(`${at} must be an object with \"name\" and \"data\"`)\n if (!Array.isArray(raw.data)) throw new Error(`${at}.data must be an array of numbers`)\n if (raw.data.length !== size) throw new Error(`${at}.data has ${raw.data.length} values, \"categories\" has ${size}: one value per category`)\n const data = raw.data.map((v, j) => {\n if (v === null) return null\n if (typeof v === 'number' && Number.isFinite(v)) return v\n throw new Error(`${at}.data[${j}] must be a number or null, got ${JSON.stringify(v)}`)\n })\n const out: ChartSeriesData = { name: raw.name === undefined ? `Series ${i + 1}` : label(raw.name, `${at}.name`), data }\n if (raw.color !== undefined) {\n if (!oneOf(PALETTE_KEYS, raw.color)) throw new Error(`${at}.color must be one of ${PALETTE_KEYS.join(', ')}`)\n out.color = raw.color\n }\n if (raw.axis !== undefined) {\n if (!oneOf(CHART_AXES, raw.axis)) throw new Error(`${at}.axis must be ${CHART_AXES.join(' or ')}`)\n out.axis = raw.axis\n }\n return out\n}\n\nfunction parseShape(raw: unknown): ChartFence {\n if (!isRecord(raw)) throw new Error('The fence must hold one JSON object')\n if (!oneOf(CHART_TYPES, raw.type)) throw new Error(`\"type\" must be one of ${CHART_TYPES.join(', ')}`)\n if (!Array.isArray(raw.categories) || raw.categories.length === 0) throw new Error('\"categories\" must be a non-empty array of labels')\n if (raw.categories.length > CHART_FENCE_LIMITS.categories) throw new Error(`\"categories\" has ${raw.categories.length} entries, at most ${CHART_FENCE_LIMITS.categories}`)\n const categories = raw.categories.map((c, i) => label(c, `categories[${i}]`))\n if (!Array.isArray(raw.series) || raw.series.length === 0) throw new Error('\"series\" must be a non-empty array')\n if (raw.series.length > CHART_FENCE_LIMITS.series) throw new Error(`\"series\" has ${raw.series.length} entries, at most ${CHART_FENCE_LIMITS.series}`)\n if (chartTypeInfo(raw.type).singleSeries && raw.series.length !== 1) throw new Error(`A ${raw.type} takes exactly one series (the parts are the categories)`)\n const series = raw.series.map((s, i) => parseSeries(s, i, categories.length))\n\n const chart: ChartFence = { type: raw.type, categories, series }\n if (raw.title !== undefined) chart.title = label(raw.title, '\"title\"', CHART_FENCE_LIMITS.title)\n for (const key of ['stacked', 'legend', 'valueLabels'] as const) {\n if (raw[key] === undefined) continue\n if (typeof raw[key] !== 'boolean') throw new Error(`\"${key}\" must be true or false`)\n chart[key] = raw[key]\n }\n if (raw.height !== undefined) {\n const h = raw.height\n if (typeof h !== 'number' || h < CHART_FENCE_LIMITS.minHeight || h > CHART_FENCE_LIMITS.maxHeight) {\n throw new Error(`\"height\" must be a number from ${CHART_FENCE_LIMITS.minHeight} to ${CHART_FENCE_LIMITS.maxHeight}`)\n }\n chart.height = Math.round(h)\n }\n return chart\n}\n\n/** The chart in a ```chart fence body, or what is wrong with it (one line an author can act on). */\nexport function parseChartFence(source: string): ChartFenceResult {\n const text = source.replace(SIGNAL_RE, 'null').trim()\n if (!text) return { ok: false, error: 'Empty chart fence' }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n }\n catch (err) {\n return { ok: false, error: `Not valid JSON: ${err instanceof Error ? err.message : String(err)}` }\n }\n try {\n return { ok: true, chart: parseShape(raw) }\n }\n catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n }\n}\n","import { NordhavnClient, type NordhavnClientOptions } from './client'\nimport { NordhavnError } from './errors'\n\nexport { NordhavnClient, DatasetHandle, DEFAULT_BASE_URL } from './client'\nexport type { NordhavnClientOptions, ReadOptions, UploadOptions, StudioFailure } from './client'\nexport type { ClientCacheOptions } from './options'\nexport type { Logger } from './runtime'\nexport { NordhavnError } from './errors'\nexport { ContentCache, MemoryCacheStore } from './cache'\nexport type { CacheOptions, CacheStore, CacheEntry } from './cache'\nexport type {\n ContentSchema,\n SchemaNode,\n SchemaDataset,\n SchemaField,\n FieldKind,\n FieldType,\n ContentRecord,\n ContentLocale,\n QueryResult,\n QueryShape,\n UploadedFile,\n} from './types'\nexport {\n PALETTE_KEYS,\n CHART_TYPES,\n CHART_TYPE_INFO,\n chartTypeInfo,\n isPartChart,\n isBarChart,\n CHART_AXES,\n DATE_BUCKET_VALUES,\n BUCKET_MODES,\n AGGREGATIONS,\n CHART_SORTS,\n} from './chart'\nexport type {\n PaletteKey,\n ChartType,\n ChartFamily,\n ChartTypeInfo,\n ChartAxis,\n DateBucket,\n BucketMode,\n Aggregation,\n ChartSort,\n ChartSeriesSpec,\n ChartSpec,\n ChartSeriesData,\n ChartData,\n} from './chart'\nexport { CHART_FENCE_LANG, CHART_FENCE_LIMITS, chartFenceHeight, isChartFence, parseChartFence } from './chart-fence'\nexport type { ChartFence, ChartFenceResult } from './chart-fence'\nexport type {\n RoadmapPhaseState,\n RoadmapWorkState,\n RoadmapTone,\n RoadmapTip,\n RoadmapPhase,\n RoadmapLane,\n RoadmapMilestone,\n RoadmapWaiting,\n RoadmapTask,\n RoadmapRepeat,\n RoadmapHappening,\n RoadmapEvent,\n RoadmapData,\n ForecastSeries,\n} from './roadmap'\n\n\n/**\n * Convenience factory: `createClient({ apiKey, baseUrl })`. Both fall back to\n * the environment (`NORDHAVN_API_KEY`, `NORDHAVN_BASE_URL`), so on a server\n * with those set `createClient()` is enough.\n */\nexport function createClient(options?: NordhavnClientOptions): NordhavnClient {\n return new NordhavnClient(options)\n}\n\n/*\n * The names up to 0.7, kept so code written for them works unchanged. Each\n * is the same class as its new name, not a copy: `instanceof HavenError`\n * holds for a `NordhavnError` and the other way round.\n */\n\n/** @deprecated Renamed in 0.8.0: use `NordhavnClient`. */\nexport const HavenClient = NordhavnClient\n/** @deprecated Renamed in 0.8.0: use `NordhavnClient`. */\nexport type HavenClient = NordhavnClient\n/** @deprecated Renamed in 0.8.0: use `NordhavnClientOptions`. */\nexport type HavenClientOptions = NordhavnClientOptions\n/** @deprecated Renamed in 0.8.0: use `NordhavnError`. */\nexport const HavenError = NordhavnError\n/** @deprecated Renamed in 0.8.0: use `NordhavnError`. */\nexport type HavenError = NordhavnError\n"]}