@revenexx/app-sdk 2.1.0 → 2.2.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/errors.ts","../src/query.ts","../src/settings.ts","../src/backdating.ts","../src/patch.ts"],"sourcesContent":["/**\n * The one error representation every layer of the SDK agrees on.\n *\n * `HttpError` used to live in `./router/router.ts`. It moved here so the data\n * adapters can raise it too: an adapter that knows a PostgREST failure is a\n * duplicate key can say \"409\" without the router having to guess from a\n * message string.\n *\n * Two fields exist purely to keep internal database detail out of responses:\n * - `message` / `details` are the *client-facing* payload — always safe,\n * never derived from a database error body.\n * - `serverDetail` is the raw diagnosis. The router logs it and drops it; it\n * is never serialised into a response.\n */\n\nexport interface HttpErrorOptions {\n /** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */\n code?: string;\n /**\n * Raw diagnosis for server-side logs and traces only — may contain table and\n * constraint names. Never included in the HTTP response.\n */\n serverDetail?: unknown;\n}\n\n/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n readonly code?: string;\n readonly serverDetail?: unknown;\n /**\n * Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate\n * bundles, so an error thrown by the data client and caught by the router is\n * an instance of a *different* copy of this class — `instanceof` would be\n * false. Everything checks this flag via `isHttpError` instead.\n */\n readonly __isHttpError = true as const;\n\n constructor(status: number, message: string, details?: unknown, options: HttpErrorOptions = {}) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n if (details !== undefined) this.details = details;\n if (options.code !== undefined) this.code = options.code;\n if (options.serverDetail !== undefined) this.serverDetail = options.serverDetail;\n }\n}\n\n/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */\nexport function isHttpError(err: unknown): err is HttpError {\n if (!err || typeof err !== 'object') return false;\n const e = err as { __isHttpError?: unknown; name?: unknown; status?: unknown };\n return e.__isHttpError === true || (e.name === 'HttpError' && typeof e.status === 'number');\n}\n\n/*\n * The helpers carry a stable `code` (from 1.0), so every refusal the SDK or an App\n * raises through them is machine-readable. Pass `options.code` for a sharper one.\n */\nexport const notFound = (message = 'not found', options: HttpErrorOptions = {}): HttpError =>\n new HttpError(404, message, undefined, { code: 'not_found', ...options });\nexport const badRequest = (message = 'bad request', details?: unknown, options: HttpErrorOptions = {}): HttpError =>\n new HttpError(400, message, details, { code: 'bad_request', ...options });\nexport const forbidden = (message = 'forbidden', options: HttpErrorOptions = {}): HttpError =>\n new HttpError(403, message, undefined, { code: 'forbidden', ...options });\nexport const conflict = (message = 'conflict', options: HttpErrorOptions = {}): HttpError =>\n new HttpError(409, message, undefined, { code: 'conflict', ...options });\n\n/**\n * The body every refusal is answered with. `error` is the message (the router's\n * shape since 0.3); `message` and `type` repeat the message and the code under the\n * names the platform client (`@revenexx/sdk`) reads, so a caller that catches its\n * `RevenexxException` sees the App's reason as `err.message` and its code as\n * `err.type` instead of `undefined` (RAD-98).\n */\nexport function refusalBody(message: string, code?: string, details?: unknown): Record<string, unknown> {\n return {\n error: message,\n message,\n ...(code ? { code, type: code } : {}),\n ...(details != null ? { details } : {}),\n };\n}\n\n/** A refusal, whichever side raised it. */\nexport interface Refusal {\n /** HTTP status the refusal was answered with. */\n status: number;\n /** The refusing App's stable code, or null when it gave none. */\n code: string | null;\n /** Why, in words safe to show. */\n message: string;\n details: unknown;\n /** The App that answered, as the gateway tagged it; null for this App's own refusal. */\n app: string | null;\n}\n\n/**\n * Read a refusal out of whatever was thrown: this App's own `HttpError`, or the\n * exception the platform client (`@revenexx/sdk`) throws when another App refused a\n * call — whose `code` is the HTTP status and whose `response` is that App's body\n * verbatim. `null` for anything that is not a refusal (a crash, a network fault),\n * which is the distinction a caller needs: a question that could not be answered is\n * not the far side being down.\n */\nexport function refusalOf(err: unknown): Refusal | null {\n if (isHttpError(err)) {\n return { status: err.status, code: err.code ?? null, message: err.message, details: err.details ?? null, app: null };\n }\n if (!err || typeof err !== 'object') return null;\n const e = err as { code?: unknown; response?: unknown; message?: unknown; type?: unknown; app?: unknown };\n const status = typeof e.code === 'number' ? e.code : Number.NaN;\n if (!(status >= 400 && status <= 599) || typeof e.response !== 'string') return null;\n let body: Record<string, unknown> = {};\n try {\n const parsed: unknown = JSON.parse(e.response || '{}');\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) body = parsed as Record<string, unknown>;\n } catch {\n /* not JSON: fall back to what the exception itself carries */\n }\n const str = (v: unknown): string | null => (typeof v === 'string' && v !== '' ? v : null);\n return {\n status,\n code: str(body.code) ?? str(body.type) ?? str(e.type),\n message: str(body.error) ?? str(body.message) ?? str(e.message) ?? 'the call was refused',\n details: body.details ?? null,\n app: str(e.app),\n };\n}\n","import type { Query, FilterOp, Row } from './types.js';\n\n/**\n * PostgREST query helpers. `toParams` serialises a query for the HTTP adapters;\n * `matches` applies the same `where` semantics in memory for the mock adapter —\n * keeping one shape means App code is identical across adapters.\n */\n\nexport const OPS: ReadonlySet<FilterOp> = new Set<FilterOp>(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'like', 'ilike', 'in', 'is']);\n\n/** Serialise a query object to PostgREST URLSearchParams. */\nexport function toParams(query: Query = {}): URLSearchParams {\n const params = new URLSearchParams();\n const { where = {}, select, order, limit, offset } = query;\n\n for (const [col, cond] of Object.entries(where)) {\n if (Array.isArray(cond)) {\n params.append(col, `in.${inList(cond)}`);\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!OPS.has(c.op)) throw new Error(`query: unsupported operator '${c.op}'`);\n const v = Array.isArray(c.value) ? inList(c.value) : c.value;\n params.append(col, `${c.op}.${v}`);\n } else if (cond === null) {\n // `eq.null` compares against the string 'null'; the mock already reads a\n // null condition as \"is null\", and now the data plane does too.\n params.append(col, 'is.null');\n } else {\n params.append(col, `eq.${cond}`);\n }\n }\n\n if (Array.isArray(select) && select.length) params.set('select', (select as string[]).join(','));\n if (order) params.set('order', /\\.(asc|desc)$/.test(order) ? order : `${order}.asc`);\n if (Number.isInteger(limit)) params.set('limit', String(limit));\n if (Number.isInteger(offset)) params.set('offset', String(offset));\n\n return params;\n}\n\n/**\n * A value list as PostgREST reads it: `(\"a\",\"b\")`. Every value is double-quoted\n * with `\\` and `\"` escaped, so a comma, a parenthesis, a quote or a backslash\n * inside a value stays part of that value instead of splitting the list or\n * breaking the filter. `null` stays the bare word `null`.\n */\nfunction inList(values: readonly unknown[]): string {\n return `(${values.map(quoteListValue).join(',')})`;\n}\n\nfunction quoteListValue(v: unknown): string {\n if (v === null || v === undefined) return 'null';\n return `\"${String(v).replace(/[\\\\\"]/g, '\\\\$&')}\"`;\n}\n\n/** In-memory predicate mirroring `toParams`' `where` semantics (mock adapter). */\nexport function matches(row: Row, where: Query['where'] = {}): boolean {\n for (const [col, cond] of Object.entries(where)) {\n // A column a row does not carry reads as null — in Postgres every row has\n // every column. Same as the PHP runtime.\n const val = row[col] ?? null;\n if (Array.isArray(cond)) {\n if (!cond.includes(val as never)) return false;\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!compare(val, c.op, c.value)) return false;\n } else if (val !== cond) {\n return false;\n }\n }\n return true;\n}\n\nfunction compare(a: unknown, op: FilterOp, b: unknown): boolean {\n switch (op) {\n case 'eq': return a === b;\n case 'neq': return a !== b;\n case 'gt': return (a as number) > (b as number);\n case 'gte': return (a as number) >= (b as number);\n case 'lt': return (a as number) < (b as number);\n case 'lte': return (a as number) <= (b as number);\n case 'is': return a === b;\n case 'in': return Array.isArray(b) && b.includes(a);\n case 'like':\n case 'ilike': {\n const re = new RegExp(\n '^' + String(b).replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/%/g, '.*').replace(/_/g, '.') + '$',\n op === 'ilike' ? 'i' : '',\n );\n return re.test(String(a));\n }\n default: return false;\n }\n}\n","/**\n * App settings — the tenant's configuration for THIS app, read at runtime.\n *\n * An App declares its settings in `settings.json` (`{ settings: { <key>:\n * { type, scope, default, sensitive, ... } } }`). The cockpit renders that\n * schema, Console stores the tenant's chosen values, and the gateway resolves\n * the two into an effective map:\n *\n * GET {gateway}/v1/settings/apps/{app}[?market={code}]\n * -> { app, market, settings: { … }, masked: [ … ], stored: [ … ] }\n *\n * Resolution happens ON THE GATEWAY, and this reader does not second-guess it.\n * Per key, the gateway applies (api/internal/gateway/settings.go,\n * `resolveSettings`):\n *\n * 1. per-market override — only for settings declared `\"scope\": \"market\"`,\n * and only when `?market=` is sent\n * 2. stored tenant value — the flat value in `settings_values`\n * 3. schema default — the `default` from settings.json\n *\n * Settings flagged `sensitive` are never in `settings`; their keys are listed\n * in `masked` so a caller can tell \"not configured\" from \"not for you\".\n *\n * The `defaults` you pass here are a *fourth*, last-resort layer: they are what\n * the app runs on when the settings service cannot be reached, and they are\n * what types the resolved object. They never override a value the gateway\n * actually resolved — only a `null`/absent one.\n *\n * const settings = createSettings({\n * app: 'orders',\n * defaults: { auto_reserve: true, reservation_minutes: 30 },\n * });\n *\n * app.post('/orders', async (c) => {\n * const s = await settings.get(c); // market taken from the request\n * if (s.auto_reserve) { … }\n * });\n *\n * Or let the router own it — `createApp({ name, settings: { defaults } })`\n * gives every handler `await c.settings()`.\n *\n * ## Writing the app's OWN settings\n *\n * Some values have to be STORED, not merely declared — a platform service may\n * refuse to act on a default it cannot tell from \"nobody decided\". The app can\n * store them itself:\n *\n * const result = await settings.set(c, { locale_granularity: 'language' }, { ifAbsent: true });\n * // PATCH {gateway}/v1/settings/apps/{app}\n * // -> { ok, written: [...], kept: [...], ignored: [...] }\n *\n * The gateway lets an app write only its own settings, for the tenant its\n * request belongs to: it reads the app from the platform-signed\n * `x-revenexx-app-context` header the router hands every HTTP invocation, which\n * this reader forwards. A run started by an event or a schedule carries none,\n * so a write from there comes back `ok: false` — write from an HTTP route.\n * `ifAbsent` keeps every key the tenant already stored: use it for defaults,\n * so an install hook never undoes a merchant's choice. `stored` on a snapshot\n * says which keys are stored rather than defaulted.\n *\n * Two properties make this safe to call on every request:\n *\n * - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that\n * declares no settings at all: you get the last good values if there are\n * any, otherwise your declared defaults. It never throws and never takes\n * the app down. Availability is the default; switching something off is\n * the deliberate act, and a deliberate act must not be the accident.\n * - it CACHES. Per (tenant, app, market), for a short TTL, with concurrent\n * reads sharing one in-flight request. A warm read is a Map lookup.\n */\n\n/** The platform gateway. Override with REVENEXX_GATEWAY_ENDPOINT. */\nexport const DEFAULT_GATEWAY_ENDPOINT = 'https://api.revenexx.com';\n\n/**\n * How long a resolved settings map stays warm in the process (ms).\n *\n * Settings are configuration, not data: a merchant flips one every few weeks.\n * The gateway keeps its own 30s cache in front of Console and drops it on a\n * NATS invalidation when values change, so this second layer is the only real\n * staleness — a cockpit change takes effect within a minute. That is the right\n * trade against the alternative, which is a gateway round trip on the hot path\n * of every single request.\n *\n * Override per reader (`ttlMs`) or per deployment (REVENEXX_SETTINGS_TTL_MS).\n */\nexport const DEFAULT_SETTINGS_TTL_MS = 60_000;\n\n/**\n * How long a FAILED read stays cached (ms). Short, because the failure is\n * usually transient and we want to recover quickly — but not zero, or an\n * unreachable gateway would put a doomed round trip on every request, which is\n * exactly the outage the fail-open is supposed to absorb.\n *\n * A 404 (\"app not installed or declares no settings\") is not a failure but a\n * stable answer, and is cached for the full TTL.\n */\nexport const DEFAULT_SETTINGS_ERROR_TTL_MS = 5_000;\n\n/** Request timeout (ms). A hung settings service must not hang the app. */\nexport const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;\n\nexport type SettingsDefaults = Record<string, unknown>;\n\n/**\n * The resolved map. Keys you declared in `defaults` keep their type; anything\n * else the manifest declares is still there, as `unknown`.\n */\nexport type ResolvedSettings<D extends SettingsDefaults = SettingsDefaults> = D & Record<string, unknown>;\n\n/**\n * Anything a request's tenant/token/market can be read from: the router's\n * `RouteContext`, the raw function context (`{ req: { headers } }`), or a bare\n * headers object.\n */\nexport interface SettingsSource {\n header?(name: string): string;\n tenant?: string | null;\n contextToken?: string;\n req?: { headers?: Record<string, string> | undefined } | undefined;\n headers?: Record<string, string> | undefined;\n}\n\nexport interface SettingsOptions<D extends SettingsDefaults = SettingsDefaults> {\n /**\n * The app whose settings to read. Defaults to REVENEXX_APP_NAME, which the\n * runtime sets — a deployed app usually needs no value here. `createApp`\n * passes its own `name`.\n */\n app?: string;\n /**\n * Last-resort values, and the type source. Use the same defaults your\n * settings.json declares: they are what the app runs on if the settings\n * service is unreachable.\n */\n defaults?: D;\n /** Gateway base URL. Default: REVENEXX_GATEWAY_ENDPOINT or the platform gateway. */\n endpoint?: string;\n /** Cache TTL in ms. Default: REVENEXX_SETTINGS_TTL_MS or 60_000. */\n ttlMs?: number;\n /** How long a failed read is cached, in ms. Default 5_000. */\n errorTtlMs?: number;\n /** Per-request timeout in ms. Default 2_000. */\n timeoutMs?: number;\n /** Environment to read from (tests). Default `process.env`. */\n env?: Record<string, string | undefined>;\n /** Fetch implementation (tests). Default `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /**\n * Called when a read fails and the app falls back. Wire it to the function's\n * `error()` so a silent fallback is still visible. Must not throw.\n */\n onError?: (error: Error, info: { app: string; tenant: string; market: string | null }) => void;\n}\n\n/** A resolved read, with the provenance a caller occasionally needs. */\nexport interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {\n app: string;\n tenant: string;\n /** The market the values were resolved for, or null for the tenant baseline. */\n market: string | null;\n settings: ResolvedSettings<D>;\n /** Keys that exist but are `sensitive`, so their values were withheld. */\n masked: string[];\n /**\n * Keys whose value the tenant STORED (a tenant value, or the market's\n * override), as opposed to the declared default. A stored default and an\n * unset key resolve to the same value; this tells them apart. Empty on a\n * fallback, and from a gateway too old to say.\n */\n stored: string[];\n /** true when these values came from the gateway (fresh or cached). */\n resolved: boolean;\n /** Why the fallback happened, when `resolved` is false. */\n error?: string;\n}\n\nexport interface ReadOptions {\n /** Resolve for this market instead of the one on the request. `''` = tenant baseline. */\n market?: string;\n}\n\nexport interface WriteOptions {\n /** Keep every key the tenant already stored; write only the missing ones. */\n ifAbsent?: boolean;\n}\n\n/** The outcome of `set()`. Key names only — the gateway never echoes values. */\nexport interface SettingsWriteResult {\n /** true when the gateway accepted the write (even if it wrote nothing). */\n ok: boolean;\n /** HTTP status of the gateway's answer; 0 when it was never asked or unreachable. */\n status: number;\n /** Keys stored by this write. */\n written: string[];\n /** Keys left alone because they were already stored (`ifAbsent`). */\n kept: string[];\n /** Keys dropped because the app's settings.json does not declare them. */\n ignored: string[];\n /** Why the write did not happen, when `ok` is false. */\n error?: string;\n}\n\nexport interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {\n /** The effective settings for this request. Never throws. */\n get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/stored/provenance. */\n load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n /**\n * Store this app's OWN tenant-level settings for the request's tenant.\n * Never throws: a refusal or an unreachable gateway is `ok: false`, also\n * reported to `onError`. A successful write drops the tenant's cached reads.\n */\n set(source: SettingsSource | undefined, values: Record<string, unknown>, options?: WriteOptions): Promise<SettingsWriteResult>;\n /** Drop the cache (tests, or right after writing settings). */\n clear(): void;\n}\n\ninterface Entry<D extends SettingsDefaults> {\n at: number;\n ttl: number;\n promise: Promise<SettingsSnapshot<D>>;\n}\n\ninterface GatewayResponse {\n settings?: Record<string, unknown>;\n masked?: unknown;\n stored?: unknown;\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((k): k is string => typeof k === 'string') : [];\n}\n\n/** Case-insensitive header read across the three shapes we accept. */\nfunction headerOf(source: SettingsSource | undefined, name: string): string {\n if (!source) return '';\n if (typeof source.header === 'function') {\n const v = source.header(name);\n if (typeof v === 'string' && v !== '') return v;\n }\n const bags = [source.req?.headers, source.headers];\n const want = name.toLowerCase();\n for (const bag of bags) {\n if (!bag) continue;\n const direct = bag[name] ?? bag[want];\n if (typeof direct === 'string' && direct !== '') return direct;\n for (const [k, v] of Object.entries(bag)) {\n if (k.toLowerCase() === want && typeof v === 'string' && v !== '') return v;\n }\n }\n return '';\n}\n\n/**\n * Merge the gateway's resolved map over the declared defaults.\n *\n * A `null` from the gateway does NOT clobber a default: a setting the merchant\n * never touched and whose schema carries no default resolves to `null`, and a\n * caller should not have to null-check a key it declared a default for. A real\n * stored value — including `false`, `0` and `''` — always wins.\n */\nfunction mergeSettings<D extends SettingsDefaults>(\n defaults: D | undefined,\n resolved: Record<string, unknown> | undefined,\n): ResolvedSettings<D> {\n const out: Record<string, unknown> = { ...(defaults ?? {}) };\n for (const [key, value] of Object.entries(resolved ?? {})) {\n if (value !== null && value !== undefined) out[key] = value;\n else if (!(key in out)) out[key] = value ?? null;\n }\n return out as ResolvedSettings<D>;\n}\n\nfunction timeoutSignal(ms: number): AbortSignal | undefined {\n const factory = (AbortSignal as { timeout?: (ms: number) => AbortSignal }).timeout;\n if (typeof factory === 'function') return factory(ms);\n if (typeof AbortController !== 'function') return undefined;\n const controller = new AbortController();\n setTimeout(() => controller.abort(), ms).unref?.();\n return controller.signal;\n}\n\n/**\n * Build a settings reader for one app. Create it once at module scope — the\n * cache lives on the reader, and a per-request reader would cache nothing.\n */\nexport function createSettings<D extends SettingsDefaults = SettingsDefaults>(\n options: SettingsOptions<D> = {},\n): SettingsReader<D> {\n const env = options.env ?? process.env;\n const defaults = options.defaults;\n const ttlMs = options.ttlMs ?? Number(env.REVENEXX_SETTINGS_TTL_MS ?? DEFAULT_SETTINGS_TTL_MS);\n const errorTtlMs = options.errorTtlMs ?? DEFAULT_SETTINGS_ERROR_TTL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_SETTINGS_TIMEOUT_MS;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(\n /\\/+$/,\n '',\n );\n\n const cache = new Map<string, Entry<D>>();\n /** Last successful snapshot per key — served instead of defaults on a blip. */\n const lastGood = new Map<string, SettingsSnapshot<D>>();\n\n const appName = (): string => String(options.app || env.REVENEXX_APP_NAME || '').trim();\n\n const fallback = (app: string, tenant: string, market: string | null, error: string): SettingsSnapshot<D> => ({\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, undefined),\n masked: [],\n stored: [],\n resolved: false,\n error,\n });\n\n const report = (err: Error, info: { app: string; tenant: string; market: string | null }): void => {\n try {\n options.onError?.(err, info);\n } catch {\n /* an error reporter must never be the reason a request fails */\n }\n };\n\n async function request(app: string, tenant: string, token: string, market: string | null): Promise<SettingsSnapshot<D>> {\n const f = options.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') throw new Error('settings: no fetch available (Node >=18 or pass fetchImpl)');\n\n const qs = market ? `?market=${encodeURIComponent(market)}` : '';\n const headers: Record<string, string> = { Accept: 'application/json', 'X-Revenexx-Tenant': tenant };\n if (token) headers.Authorization = `Bearer ${token}`;\n\n const signal = timeoutSignal(timeoutMs);\n const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}${qs}`, {\n method: 'GET',\n headers,\n ...(signal ? { signal } : {}),\n });\n const text = await res.text();\n if (!res.ok) {\n const err = new Error(`settings: ${res.status} for ${app}`) as Error & { status?: number };\n err.status = res.status;\n throw err;\n }\n const body = (text ? JSON.parse(text) : {}) as GatewayResponse;\n return {\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, body.settings),\n masked: stringList(body.masked),\n stored: stringList(body.stored),\n resolved: true,\n };\n }\n\n /** Drop every cached read for one tenant of this app (after a write). */\n const forgetTenant = (tenant: string, app: string): void => {\n const prefix = `${tenant}\\u0000${app}\\u0000`;\n for (const key of [...cache.keys()]) if (key.startsWith(prefix)) cache.delete(key);\n for (const key of [...lastGood.keys()]) if (key.startsWith(prefix)) lastGood.delete(key);\n };\n\n async function set(\n source: SettingsSource | undefined,\n values: Record<string, unknown>,\n writeOptions: WriteOptions = {},\n ): Promise<SettingsWriteResult> {\n const app = appName();\n const tenant = (source?.tenant ?? '') || headerOf(source, 'x-revenexx-tenant');\n const refused = (status: number, error: string): SettingsWriteResult => ({\n ok: false,\n status,\n written: [],\n kept: [],\n ignored: [],\n error,\n });\n\n // Nothing the gateway could accept — answer without a round trip.\n if (!app) return refused(0, 'no app name (pass `app` or set REVENEXX_APP_NAME)');\n if (!tenant) return refused(0, 'no tenant on the request');\n const appContext = headerOf(source, 'x-revenexx-app-context');\n if (!appContext) {\n return refused(0, 'no app context on the request — settings are written from an HTTP route, not an event or schedule run');\n }\n if (!values || typeof values !== 'object' || Array.isArray(values)) return refused(0, 'values must be an object');\n\n const f = options.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') return refused(0, 'settings: no fetch available (Node >=18 or pass fetchImpl)');\n\n const token = (source?.contextToken ?? '') || headerOf(source, 'x-revenexx-context');\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Revenexx-Tenant': tenant,\n 'X-Revenexx-App-Context': appContext,\n };\n if (token) headers.Authorization = `Bearer ${token}`;\n\n try {\n const signal = timeoutSignal(timeoutMs);\n const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}`, {\n method: 'PATCH',\n headers,\n body: JSON.stringify({ data: values, if_absent: writeOptions.ifAbsent === true }),\n ...(signal ? { signal } : {}),\n });\n const text = await res.text();\n let body: Record<string, unknown> = {};\n try {\n body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n } catch {\n body = {};\n }\n if (!res.ok) {\n const reason = typeof body.error === 'string' ? body.error : typeof body.message === 'string' ? body.message : '';\n const err = new Error(`settings: write ${res.status} for ${app}${reason ? ` — ${reason}` : ''}`) as Error & {\n status?: number;\n };\n err.status = res.status;\n report(err, { app, tenant, market: null });\n return refused(res.status, err.message);\n }\n const result: SettingsWriteResult = {\n ok: true,\n status: res.status,\n written: stringList(body.written),\n kept: stringList(body.kept),\n ignored: stringList(body.ignored),\n };\n if (result.written.length > 0) forgetTenant(tenant, app);\n return result;\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error(String(err));\n report(error, { app, tenant, market: null });\n return refused(0, error.message);\n }\n }\n\n async function load(source?: SettingsSource, readOptions: ReadOptions = {}): Promise<SettingsSnapshot<D>> {\n const app = appName();\n const tenant = (source?.tenant ?? '') || headerOf(source, 'x-revenexx-tenant');\n const market = (readOptions.market ?? headerOf(source, 'x-revenexx-market')).trim() || null;\n\n // Nothing to ask with — answer from the defaults without a round trip.\n if (!app) return fallback('', tenant, market, 'no app name (pass `app` or set REVENEXX_APP_NAME)');\n if (!tenant) return fallback(app, '', market, 'no tenant on the request');\n\n const key = `${tenant}\u0000${app}\u0000${market ?? ''}`;\n const now = Date.now();\n const hit = cache.get(key);\n if (hit && now - hit.at < hit.ttl) return hit.promise;\n\n const token = (source?.contextToken ?? '') || headerOf(source, 'x-revenexx-context');\n const entry: Entry<D> = { at: now, ttl: ttlMs, promise: undefined as unknown as Promise<SettingsSnapshot<D>> };\n entry.promise = request(app, tenant, token, market)\n .then((snapshot) => {\n lastGood.set(key, snapshot);\n return snapshot;\n })\n .catch((err: unknown) => {\n const error = err instanceof Error ? err : new Error(String(err));\n // A 404 is the gateway saying \"this app is not installed, or declares\n // no settings\" — a stable answer, not a blip. Cache it for the full TTL\n // so an app without settings does not re-ask every five seconds.\n const status = (error as { status?: number }).status;\n entry.ttl = status === 404 ? ttlMs : errorTtlMs;\n report(error, { app, tenant, market });\n // Prefer the last values we genuinely resolved over the defaults: they\n // are the tenant's actual configuration, and a gateway blip is no\n // reason to silently revert a merchant's choices.\n const stale = lastGood.get(key);\n if (stale) return { ...stale, resolved: false, error: error.message };\n return fallback(app, tenant, market, error.message);\n });\n\n // Cached before it settles, so concurrent requests share one fetch.\n cache.set(key, entry);\n return entry.promise;\n }\n\n return {\n load,\n set,\n async get(source?: SettingsSource, readOptions?: ReadOptions): Promise<ResolvedSettings<D>> {\n return (await load(source, readOptions)).settings;\n },\n clear(): void {\n cache.clear();\n lastGood.clear();\n },\n };\n}\n","/**\n * Backdating — replaying history into a test tenant (RAD-311).\n *\n * A simulator fills a test tenant with months of orders, payments and stock\n * movements. Everything an App stamps is \"now\", so without help the whole\n * history would land on the afternoon the simulator ran. An App that opts in\n * (`createApp({ backdating: true })`) lets a mutating request carry a past\n * moment in its body (`at`, or a route's own field) and runs the WHOLE request\n * on that clock: every `now()` the handler reads, every timestamp it writes,\n * and — through `backdatingDb` — the `created_at` of every row it creates.\n *\n * Only for a tenant whose admin switched it on: the App setting\n * `allow_backdating` (scope tenant, default off), read through `c.settings()`.\n * A settings service that cannot be reached hands back the declared defaults,\n * so an unreadable setting means off. The tenant has to be named twice and\n * agree: the `x-revenexx-tenant` header AND the `tenant_id` claim of the\n * forwarded identity token (`x-revenexx-context`). The header alone is not\n * enough — a caller reaching the function URL directly can set it. The claim is\n * not verified here; the data plane verifies the token on every read and write,\n * so a token claiming another tenant writes nothing at all.\n *\n * Without the gate the field is ignored, unread and unvalidated. With it the\n * moment must be an ISO 8601 date-time with a zone, not in the future and not\n * more than `MAX_MONTHS_BACK` months back; anything else is a 400 with code\n * `backdating_invalid`.\n *\n * The clock lives in an AsyncLocalStorage kept on `globalThis`, so the two\n * entry points (`@revenexx/app-sdk` and `@revenexx/app-sdk/router`, separate\n * bundles, each in ESM and CJS) read one and the same clock.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { HttpError } from './errors.js';\nimport { isList } from './patch.js';\n\n/** How far back a backdated request may reach, in months. */\nexport const MAX_MONTHS_BACK = 24;\n\n/** The App setting that opens backdating for a tenant. */\nexport const BACKDATING_SETTING = 'allow_backdating';\n\n/** The body field every backdated route accepts. Reserved in Apps that opt in. */\nexport const BACKDATING_FIELD = 'at';\n\n/** The refusal code of a moment that cannot be honoured. */\nexport const BACKDATING_INVALID = 'backdating_invalid';\n\n/** The route methods `backdating: true` covers. */\nexport const BACKDATING_METHODS: readonly string[] = ['POST', 'PUT', 'PATCH', 'DELETE'];\n\n/**\n * `createApp({ backdating })`. `true` lets every mutating route (POST, PUT,\n * PATCH, DELETE) accept `at`; the object form does the same and refines it.\n */\nexport interface BackdatingOptions {\n /**\n * Per-route body fields that carry the moment, in precedence order, keyed\n * `METHOD /template` exactly as the route was registered:\n * `{ 'POST /orders/place': ['placed_at', 'at'] }`. `at` is always accepted —\n * appended last when the list does not name it. A route named here is\n * backdatable whatever its method.\n */\n routes?: Record<string, readonly string[]>;\n /** Routes (`METHOD /template`) that are never backdated. Wins over `routes`. */\n exclude?: readonly string[];\n /**\n * Remove the moment's fields from `c.body` before the handler runs, on every\n * request to a backdatable route — whether the gate opened or not. Default\n * false: the body is left as it came. Set it when a handler spreads its body\n * into a row: the data client refuses a key that is not a column.\n */\n strip?: boolean;\n}\n\ninterface ClockStore {\n at: string;\n}\n\nconst STORE_KEY = Symbol.for('@revenexx/app-sdk/backdating-clock');\n\nfunction clockStorage(): AsyncLocalStorage<ClockStore> {\n const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<ClockStore> | undefined>;\n let storage = g[STORE_KEY];\n if (!storage) {\n storage = new AsyncLocalStorage<ClockStore>();\n g[STORE_KEY] = storage;\n }\n return storage;\n}\n\nconst CLOCK = clockStorage();\n\n/** The request's clock as an ISO string: the backdated moment while one runs, the wall clock otherwise. */\nexport const now = (): string => CLOCK.getStore()?.at ?? new Date().toISOString();\n\n/** The request's clock as a Date, for code that does arithmetic on it. */\nexport const clock = (): Date => new Date(now());\n\n/** True while a backdated request (or `runAt`) is running. */\nexport const backdated = (): boolean => Boolean(CLOCK.getStore()?.at);\n\n/**\n * Run `fn` on the clock `at` (a normalized ISO string). `null` runs it on the\n * wall clock. Everything `fn` awaits sees the same clock. For a job outside a\n * route — a replay worker — and for tests.\n */\nexport function runAt<T>(at: string | null | undefined, fn: () => T): T {\n return at ? CLOCK.run({ at }, fn) : fn();\n}\n\n/** Date-time with a zone, seconds and fraction optional. A bare date is not a moment. */\nconst ISO_DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:?\\d{2})$/;\n\nconst invalid = (field: string, message: string): HttpError =>\n new HttpError(400, `'${field}' ${message}`, { field }, { code: BACKDATING_INVALID });\n\n/**\n * Check one requested moment and answer it normalized (UTC, `toISOString`).\n * Throws a 400 `backdating_invalid` naming `field` when it is not an ISO 8601\n * date-time with a zone, lies in the future, or lies more than\n * `MAX_MONTHS_BACK` months back. `reference` is the wall clock to measure\n * against (tests).\n */\nexport function parseBackdate(field: string, value: unknown, reference: Date = new Date()): string {\n const text = typeof value === 'string' ? value.trim() : '';\n if (!ISO_DATE_TIME.test(text)) throw invalid(field, 'must be an ISO 8601 date-time with a time zone');\n const at = new Date(text);\n if (Number.isNaN(at.getTime())) throw invalid(field, 'must be an ISO 8601 date-time with a time zone');\n if (at.getTime() > reference.getTime()) throw invalid(field, 'must not be in the future');\n const earliest = new Date(reference.getTime());\n earliest.setUTCMonth(earliest.getUTCMonth() - MAX_MONTHS_BACK);\n if (at.getTime() < earliest.getTime()) {\n throw invalid(field, `must not be more than ${MAX_MONTHS_BACK} months back`);\n }\n return at.toISOString();\n}\n\n/** What the gate reads off a request: the router's route context fits. */\nexport interface BackdatingSource {\n header?(name: string): string;\n contextToken?: string;\n settings?(): Promise<Record<string, unknown>>;\n}\n\n/** The `tenant_id` claim of a JWT, or '' (decoded, not verified). */\nfunction tokenTenant(token: unknown): string {\n const parts = typeof token === 'string' ? token.split('.') : [];\n if (parts.length < 2) return '';\n try {\n const payload = parts[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const claims = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')) as { tenant_id?: unknown } | null;\n return typeof claims?.tenant_id === 'string' ? claims.tenant_id.trim() : '';\n } catch {\n return '';\n }\n}\n\n/** `true`, or the text `'true'` a settings store may hand back, opens it. Nothing else does. */\nexport function settingAllowsBackdating(value: unknown): boolean {\n return value === true || (typeof value === 'string' && value.trim().toLowerCase() === 'true');\n}\n\n/**\n * Whether this request's tenant may backdate: the tenant header and the\n * identity token's `tenant_id` claim name the same tenant, and that tenant's\n * `allow_backdating` setting is on. Never throws; anything unreadable is false.\n */\nexport async function backdatingAllowed(c: BackdatingSource): Promise<boolean> {\n const read = (name: string): string => (typeof c?.header === 'function' ? String(c.header(name) ?? '').trim() : '');\n const header = read('x-revenexx-tenant');\n const claimed = tokenTenant(c?.contextToken || read('x-revenexx-context'));\n if (!header || header !== claimed) return false;\n if (typeof c?.settings !== 'function') return false;\n try {\n const settings = await c.settings();\n return settingAllowsBackdating(settings?.[BACKDATING_SETTING]);\n } catch {\n return false;\n }\n}\n\nconst present = (value: unknown): boolean => value !== undefined && value !== null && value !== '';\n\n/**\n * The moment a request asks for, or null. Reads nothing when no field is\n * present, resolves the gate next and returns null when it is closed, then\n * validates the first field present in `fields` order.\n */\nexport async function requestedMoment(\n c: BackdatingSource & { body?: Record<string, unknown> },\n fields: readonly string[],\n): Promise<string | null> {\n const body = c?.body;\n if (!body || typeof body !== 'object') return null;\n const field = fields.find((f) => present(body[f]));\n if (field === undefined) return null;\n if (!(await backdatingAllowed(c))) return null;\n return parseBackdate(field, body[field]);\n}\n\n/**\n * The fields a route reads its moment from under these options, or null when\n * the route is not backdatable. `key` is `METHOD /template`.\n */\nexport function backdatingFields(\n option: boolean | BackdatingOptions | undefined,\n method: string,\n template: string,\n): string[] | null {\n if (!option) return null;\n const opts: BackdatingOptions = option === true ? {} : option;\n const key = `${method.toUpperCase()} ${template}`;\n if (opts.exclude?.includes(key)) return null;\n const named = opts.routes?.[key];\n if (named) return named.includes(BACKDATING_FIELD) ? [...named] : [...named, BACKDATING_FIELD];\n return BACKDATING_METHODS.includes(method.toUpperCase()) ? [BACKDATING_FIELD] : null;\n}\n\n/** The part of an entity descriptor `backdatingDb` reads: does it have the column? */\nexport interface BackdatingEntity {\n columns?: Record<string, unknown>;\n}\n\n/**\n * The data client, with `created_at` (and `updated_at`, when the entity has\n * it) stamped on every row a backdated request creates. Outside a backdated\n * request it changes nothing: the database default stamps the row as always.\n * A value the caller set is kept. Only entities whose descriptor in `entities`\n * declares a `created_at` column are touched; pass the generated `ENTITIES`.\n *\n * const { createDb, ENTITIES } = require('./db.generated');\n * const db = backdatingDb(createDb(), ENTITIES);\n */\nexport function backdatingDb<T extends object>(db: T, entities: Record<string, BackdatingEntity | undefined>): T {\n const wrapped = new Map<string, unknown>();\n return new Proxy(db, {\n get(target, prop, receiver) {\n const value: unknown = Reflect.get(target, prop, receiver);\n if (typeof prop !== 'string') return value;\n const columns = entities?.[prop]?.columns;\n if (!columns || !('created_at' in columns) || !value || typeof value !== 'object') return value;\n const repo = value as { create?: unknown };\n if (typeof repo.create !== 'function') return value;\n if (!wrapped.has(prop)) {\n wrapped.set(\n prop,\n new Proxy(repo, {\n get(r, key, rr) {\n const member: unknown = Reflect.get(r, key, rr);\n if ((key !== 'create' && key !== 'createMany') || typeof member !== 'function') return member;\n const call = (data: unknown, rest: unknown[]) => (member as (...a: unknown[]) => unknown).call(r, data, ...rest);\n /** One record, stamped; anything that is not a record goes on to be refused. */\n const stamp = (data: unknown, at: string): unknown => {\n if (!data || typeof data !== 'object' || Array.isArray(data) || isList(data)) return data;\n const row: Record<string, unknown> = { ...(data as Record<string, unknown>) };\n if (row.created_at === undefined) row.created_at = at;\n if ('updated_at' in columns && row.updated_at === undefined) row.updated_at = at;\n return row;\n };\n if (key === 'createMany') {\n // Every record of a bulk create is stamped as a single create is,\n // so the records keep naming the same fields.\n return (data: unknown, ...rest: unknown[]) => {\n if (!backdated() || !Array.isArray(data)) return call(data, rest);\n const at = now();\n return call(data.map((record) => stamp(record, at)), rest);\n };\n }\n return (data: unknown, ...rest: unknown[]) => (backdated() ? call(stamp(data, now()), rest) : call(data, rest));\n },\n }),\n );\n }\n return wrapped.get(prop);\n },\n });\n}\n","/**\n * What counts as an update.\n *\n * PostgREST answers a `PATCH` whose body carries no columns with `200 []` — no\n * error, no representation. The adapter then hands `rows[0]` (i.e. `undefined`)\n * back as the updated row, and the App serialises it: open-runtimes does\n * `Buffer.from(JSON.stringify(obj), 'utf8')`, and `JSON.stringify(undefined)`\n * is `undefined`, so Node throws\n *\n * TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string\n * or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\n * Received undefined\n *\n * which the App reports as a 500. A caller who sent nothing to update is told\n * the service is broken instead of what to send.\n *\n * The rule lives here, one level below the router, because not every App routes\n * its writes through `mountCrud`: `PUT /v1/greetings/{id}` and\n * `PUT /v1/payments/providers/{id}` are hand-written handlers that call\n * `db.<entity>.update()` directly, and they were the two endpoints that 500ed.\n * A guard in `mountCrud` alone only protects the Apps that happen to use it.\n */\n\nimport { badRequest } from './errors.js';\nimport type { Row } from './types.js';\n\n/** The one wording every layer uses for \"you sent nothing to update\". */\nexport const EMPTY_UPDATE_MESSAGE = 'request body must contain at least one field to update';\n\n/**\n * The fields a patch would actually send. `undefined` values are excluded\n * because `JSON.stringify` drops them: `{ name: undefined }` reaches PostgREST\n * as `{}` and is exactly as empty as `{}` itself.\n */\nexport function updateFields(patch: unknown): string[] {\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return [];\n return Object.keys(patch as Record<string, unknown>).filter(\n (key) => (patch as Record<string, unknown>)[key] !== undefined,\n );\n}\n\n/** The one wording every layer uses for \"you sent nothing to create\". */\nexport const EMPTY_CREATE_MESSAGE = 'request body must contain at least one field to create';\n\n/**\n * Throw a 400 `empty_create` when a create carries no field — `{}`, `[]`, or\n * only `undefined` values.\n *\n * The two adapters disagreed about it: the mock stored a row of defaults, the\n * remote adapter sent the body to PostgREST, which reads `[]` as a bulk insert\n * of no rows and answers `[]` — the App then reported `500\n * empty_representation`. PHP cannot tell `[]` from `{}`, so both are refused,\n * in both runtimes and on both adapters, before any request.\n */\nexport function assertCreatable(data: unknown): void {\n if (updateFields(data).length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, undefined, { code: 'empty_create' });\n}\n\n/** Throw a 400 when a patch carries nothing to write. */\nexport function assertUpdatable(patch: unknown): void {\n if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE, undefined, { code: 'empty_update' });\n}\n\n/**\n * The one wording every layer uses for \"a conditional update with no condition\".\n *\n * `updateIf(id, {}, patch)` is an unconditional update spelled as a\n * conditional one — almost always a condition built from a variable that was\n * never set. Running it would let through the very race the caller reached\n * for `updateIf` to close, so it is refused; `update()` is the unconditional\n * write.\n */\nexport const EMPTY_CONDITION_MESSAGE = 'a conditional update needs at least one condition in where';\n\n/**\n * Throw a 400 when a `where` carries no condition, or one left `undefined`.\n *\n * An `undefined` entry is refused rather than dropped: dropping it would\n * quietly weaken the condition, and the two adapters would disagree about it\n * (`toParams` sends `eq.undefined`, `matches` compares against a missing key).\n */\nexport function assertCondition(where: unknown): void {\n if (!where || typeof where !== 'object' || Array.isArray(where) || Object.keys(where).length === 0) {\n throw badRequest(EMPTY_CONDITION_MESSAGE, undefined, { code: 'empty_condition' });\n }\n assertDefined(where);\n}\n\n/**\n * Throw a 400 when any `where` entry is `undefined` — on every read, not only a\n * conditional update. The two adapters disagree about one: `toParams` sends\n * `eq.undefined`, `matches` compares against a missing key. It is almost always\n * a variable that was never set, so it is refused rather than guessed at.\n */\nexport function assertDefined(where: unknown): void {\n if (!where || typeof where !== 'object') return;\n for (const [col, cond] of Object.entries(where as Record<string, unknown>)) {\n if (cond === undefined) {\n throw badRequest(`where.${col} is undefined — a condition needs a value`, undefined, { code: 'undefined_condition' });\n }\n }\n}\n\n/**\n * Columns every table has without declaring them in schema.json — Baseline\n * adds them, so the generated column list does not name them. Writing one is\n * left exactly as it was before the field check existed.\n */\nexport const IMPLICIT_COLUMNS: readonly string[] = ['tenant_id'];\n\n/**\n * The columns `trash: true` adds to an entity that does not declare them\n * itself: when the row went into the trash, who put it there (by name and by\n * subject id), the group it went with, and why it may not be purged yet.\n */\nexport const TRASH_FLAG_COLUMNS: readonly string[] = [\n 'deleted_at',\n 'deleted_by',\n 'deleted_by_id',\n 'trash_batch',\n 'purge_blocked_reason',\n];\n\n/** The column `external_id: true` adds to an entity that does not declare it. */\nexport const EXTERNAL_ID_FLAG_COLUMNS: readonly string[] = ['external_id'];\n\n/** The parts of an entity descriptor the field check reads. */\nexport interface WriteShape {\n name: string;\n columns?: Record<string, unknown>;\n trash?: boolean;\n external_id?: boolean;\n}\n\n/**\n * The columns Baseline adds for the entity's schema flags, whether or not the\n * App declares them as well. A column that exists in the table is a column\n * this version may write, even when the generated list only carries the flag.\n */\nexport function flagColumns(entity: Omit<WriteShape, 'name'>): string[] {\n return [\n ...(entity.trash === true ? TRASH_FLAG_COLUMNS : []),\n ...(entity.external_id === true ? EXTERNAL_ID_FLAG_COLUMNS : []),\n ];\n}\n\n/**\n * Every column a write may name, sorted: the declared columns plus the ones the\n * entity's flags add. `tenant_id` is accepted on top of these without being\n * listed, as before.\n */\nexport function writableColumns(entity: Omit<WriteShape, 'name'>): string[] {\n return [...new Set([...Object.keys(entity.columns ?? {}), ...flagColumns(entity)])].sort();\n}\n\n/**\n * The keys of a write that are not columns this version declares.\n *\n * A version writes only the columns it declares. The data plane cannot hold\n * that line on its own: during a rollout the new schema is applied before the\n * new code is served (and, with a release candidate, days before the stable\n * tenants move), and from that moment the old code can store a key it never\n * knew into the new column — without the validation the new version brings.\n * The generated `columns` are the list this version was built against, so a\n * key outside them is refused here, before the request.\n *\n * The columns an entity's `trash` and `external_id` flags add count as\n * declared: Baseline creates them from the flag, and an App that sets only the\n * flag still writes them (`mountTrash`, an import keeping the foreign key).\n *\n * Only the top level is checked: a `jsonb` column takes any document. A key\n * whose value is `undefined` is not sent (`JSON.stringify` drops it) and is\n * not checked. An entity without column metadata is not checked — there is\n * nothing to check against. A list is not a record and has no fields of its\n * own; `assertKnownFields` refuses it before this is asked.\n */\nexport function unknownFields(entity: Omit<WriteShape, 'name'>, data: unknown): string[] {\n if (!checksFields(entity)) return [];\n if (!data || typeof data !== 'object' || Array.isArray(data)) return [];\n const row = data as Record<string, unknown>;\n const writable = new Set([...writableColumns(entity), ...IMPLICIT_COLUMNS]);\n return Object.keys(row)\n .filter((key) => row[key] !== undefined && !writable.has(key))\n .sort();\n}\n\n/** Whether the entity carries the column metadata the field check reads. */\nfunction checksFields(entity: Omit<WriteShape, 'name'>): boolean {\n return !!entity.columns && Object.keys(entity.columns).length > 0;\n}\n\n/** The one wording every layer uses for \"a write takes one record\". */\nexport const ONE_RECORD_MESSAGE = 'a write takes one record, as a JSON object — not a list';\n\n/**\n * Throw a 400 `bad_request` when a write is a list rather than one record.\n *\n * `create` sends its data as the body of `POST /<table>`, and PostgREST reads a\n * JSON array there as a bulk insert: every element a row, every element's keys\n * columns. The field check reads the keys of one object, so a list slipped past\n * it with any key in any element — the rollout gap the check closes, reopened\n * one level down. The router hands an App a JSON array body unchanged, so a\n * handler that writes `db.x.create(c.body)` reached it from outside.\n *\n * Checked wherever the field check runs (an entity with column metadata), and\n * by `mountCrud` for every body it routes. What counts as a list is `isList`.\n */\nexport function assertOneRecord(entity: Omit<WriteShape, 'name'>, data: unknown): void {\n if (checksFields(entity) && isList(data)) throw oneRecordRefusal();\n}\n\nconst INDEX = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Whether a body is a list: a non-empty array, or a non-empty object whose keys\n * are exactly the indexes `0` … `n-1`, in any order.\n *\n * The definition is the one the PHP runtime can apply, and both use it: PHP\n * decodes `[…]` and `{\"0\":…}` to the same array, and `[]` to the same array as\n * `{}`. So an empty list is an empty record, and an object keyed by indexes is\n * a list.\n */\nexport function isList(data: unknown): boolean {\n if (!data || typeof data !== 'object') return false;\n if (Array.isArray(data)) return data.length > 0;\n const keys = Object.keys(data);\n return keys.length > 0 && keys.every((k) => INDEX.test(k) && Number(k) < keys.length);\n}\n\n/**\n * The columns `trash: true` adds are kept by the trash machinery — `mountTrash`\n * puts a record into the trash with its children, restores the group and\n * records why a purge waits. A body sent to a mounted collection that set them\n * would skip all of that: a record trashed with a forged `deleted_by`, or\n * restored and unblocked by `{\"deleted_at\": null, \"purge_blocked_reason\": null}`.\n * So `POST` / `PUT` of `mountCrud` refuse them on a trash entity, declared or\n * not; the data client still writes them for the trash routes.\n */\nexport function trashFieldsIn(entity: Omit<WriteShape, 'name'>, body: unknown): string[] {\n if (entity.trash !== true || !body || typeof body !== 'object') return [];\n const row = body as Record<string, unknown>;\n return TRASH_FLAG_COLUMNS.filter((k) => Object.prototype.hasOwnProperty.call(row, k) && row[k] !== undefined).sort();\n}\n\n/** Throw a 400 `read_only_field` when a mounted write sets a trash column. */\nexport function assertNoTrashFields(entity: Omit<WriteShape, 'name'>, body: unknown): void {\n const fields = trashFieldsIn(entity, body);\n if (fields.length === 0) return;\n const quoted = fields.map((k) => `'${k}'`).join(', ');\n throw badRequest(\n `field${fields.length > 1 ? 's' : ''} ${quoted} ${fields.length > 1 ? 'are' : 'is'} kept by the trash — ` +\n 'put a record into the trash, restore or purge it through the trash routes.',\n { fields },\n { code: 'read_only_field' },\n );\n}\n\n/**\n * The descriptor an entity client was built from, on a non-enumerable symbol\n * key, so `mountCrud` reads the entity's flags from the repo it is given, as\n * PHP's `Crud::mount` reads them from the `Entity`. `Symbol.for` keeps it the\n * same key across the ESM and CJS builds.\n */\nexport const ENTITY_DESCRIPTOR: unique symbol = Symbol.for('revenexx.app-sdk.entity') as never;\n\n/**\n * Whether a mounted collection keeps the trash columns out of bodies. Flags are\n * only ever added, never taken away: the repo's descriptor or `opts.trash`\n * turns it on, and `trash: false` cannot turn off what the descriptor says.\n * When neither states the flag — a repo of the App's own, wrapped or rebuilt —\n * a `trash_batch` among the columns, which only the trash machinery has, keeps\n * the guard on: unreadable fails closed.\n */\nexport function guardsTrash(stated: boolean | undefined, described: boolean | undefined, columns?: Record<string, unknown>): boolean {\n if (stated === true || described === true) return true;\n if (stated === undefined && described === undefined) return !!columns && Object.prototype.hasOwnProperty.call(columns, 'trash_batch');\n return false;\n}\n\n/** The descriptor behind a repo, when it is an entity client of this SDK. */\nexport function describedEntity(repo: unknown): Omit<WriteShape, 'name'> | undefined {\n if (!repo || typeof repo !== 'object') return undefined;\n return (repo as { [ENTITY_DESCRIPTOR]?: Omit<WriteShape, 'name'> })[ENTITY_DESCRIPTOR];\n}\n\n/** The one wording every layer uses for \"createMany takes a list\". */\nexport const MANY_RECORDS_MESSAGE = 'createMany takes a list of records';\n\n/**\n * The records of a `createMany`, in index order, checked before any request.\n *\n * PostgREST inserts a JSON array in one statement, so a bulk create is one\n * request, and every record must pass what a single create passes:\n *\n * - the data is a list (`isList`): anything else is `400 bad_request`, and an\n * empty list is `400 empty_create`;\n * - an element that is not a record is `400 bad_request`;\n * - an element with no field is `400 empty_create`;\n * - an element naming a key that is not a column is `400 unknown_field`;\n * - an element naming other fields than the first is `400 bad_request`:\n * PostgREST refuses a JSON array whose objects do not share their keys\n * (PGRST102). A key whose value is `undefined` does not count — it is not\n * sent.\n *\n * Every refusal of an element names it in `details.index` (0-based). The same\n * rule as the PHP runtime (`Entity::bulkRecords`).\n */\nexport function bulkRecords(entity: WriteShape, data: unknown): Row[] {\n if (Array.isArray(data) && data.length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, undefined, { code: 'empty_create' });\n if (!isList(data)) throw badRequest(MANY_RECORDS_MESSAGE, undefined, { code: 'bad_request' });\n const records = Array.isArray(data)\n ? (data as unknown[])\n : Object.keys(data as object)\n .sort((a, b) => Number(a) - Number(b))\n .map((k) => (data as Record<string, unknown>)[k]);\n let shape: string | undefined;\n records.forEach((record, index) => {\n // A list inside a list is not a record either; `[]` and `{}` are the same\n // empty record to PHP, so an empty array is an empty record here too.\n if (!record || typeof record !== 'object' || isList(record)) {\n throw badRequest(`record ${index} of a bulk create is not an object — each element is one record`, { index }, { code: 'bad_request' });\n }\n const fields = updateFields(record);\n if (fields.length === 0) {\n throw badRequest(`record ${index} of a bulk create has no field — ${EMPTY_CREATE_MESSAGE}`, { index }, { code: 'empty_create' });\n }\n const unknown = unknownFields(entity, record);\n if (unknown.length > 0) {\n const quoted = unknown.map((k) => `'${k}'`).join(', ');\n throw badRequest(\n `unknown field${unknown.length > 1 ? 's' : ''} ${quoted} in record ${index} — not a column of '${entity.name}'. ` +\n 'A field that cannot be written is refused rather than dropped; see details.allowed.',\n { index, unknown, allowed: writableColumns(entity) },\n { code: 'unknown_field' },\n );\n }\n const key = [...fields].sort().join('\\u0000');\n if (shape === undefined) shape = key;\n else if (key !== shape) {\n throw badRequest(\n `record ${index} of a bulk create names other fields than record 0 — every record of a bulk create names the same fields`,\n { index },\n { code: 'bad_request' },\n );\n }\n });\n return records as Row[];\n}\n\n/** The refusal for a list where one record belongs. */\nexport function oneRecordRefusal() {\n return badRequest(ONE_RECORD_MESSAGE, undefined, { code: 'bad_request' });\n}\n\n/**\n * Throw a 400 `unknown_field` when a write carries a key that is not a column.\n * Refused, never dropped: dropping would turn a caller's mistake into lost\n * data with no signal. A list is refused first (`assertOneRecord`).\n */\nexport function assertKnownFields(entity: WriteShape, data: unknown): void {\n assertOneRecord(entity, data);\n const unknown = unknownFields(entity, data);\n if (unknown.length === 0) return;\n const quoted = unknown.map((k) => `'${k}'`).join(', ');\n throw badRequest(\n `unknown field${unknown.length > 1 ? 's' : ''} ${quoted} — not a column of '${entity.name}'. ` +\n 'A field that cannot be written is refused rather than dropped; see details.allowed.',\n { unknown, allowed: writableColumns(entity) },\n { code: 'unknown_field' },\n );\n}\n"],"mappings":";AA0BO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,gBAAgB;AAAA,EAEzB,YAAY,QAAgB,SAAiB,SAAmB,UAA4B,CAAC,GAAG;AAC9F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,QAAI,YAAY,OAAW,MAAK,UAAU;AAC1C,QAAI,QAAQ,SAAS,OAAW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,QAAQ,IAAI,KAAK,OAAO,IAAI,EAAG,QAAO;AACrF,sBAAM,MAA+B,EAAE,GAAI,KAAiC;AAC5E,oBAAI,IAAI,eAAe,OAAW,KAAI,aAAa;AACnD,oBAAI,gBAAgB,WAAW,IAAI,eAAe,OAAW,KAAI,aAAa;AAC9E,uBAAO;AAAA,cACT;AACA,kBAAI,QAAQ,cAAc;AAGxB,uBAAO,CAAC,SAAkB,SAAoB;AAC5C,sBAAI,CAAC,UAAU,KAAK,CAAC,MAAM,QAAQ,IAAI,EAAG,QAAO,KAAK,MAAM,IAAI;AAChE,wBAAM,KAAK,IAAI;AACf,yBAAO,KAAK,KAAK,IAAI,CAAC,WAAW,MAAM,QAAQ,EAAE,CAAC,GAAG,IAAI;AAAA,gBAC3D;AAAA,cACF;AACA,qBAAO,CAAC,SAAkB,SAAqB,UAAU,IAAI,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,IAAI,IAAI,KAAK,MAAM,IAAI;AAAA,YAC/G;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AACA,aAAO,QAAQ,IAAI,IAAI;AAAA,IACzB;AAAA,EACF,CAAC;AACH;","names":["now"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/query.ts","../src/settings.ts","../src/backdating.ts","../src/patch.ts"],"sourcesContent":["/**\n * The one error representation every layer of the SDK agrees on.\n *\n * `HttpError` used to live in `./router/router.ts`. It moved here so the data\n * adapters can raise it too: an adapter that knows a PostgREST failure is a\n * duplicate key can say \"409\" without the router having to guess from a\n * message string.\n *\n * Two fields exist purely to keep internal database detail out of responses:\n * - `message` / `details` are the *client-facing* payload — always safe,\n * never derived from a database error body.\n * - `serverDetail` is the raw diagnosis. The router logs it and drops it; it\n * is never serialised into a response.\n */\n\nexport interface HttpErrorOptions {\n /** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */\n code?: string;\n /**\n * Raw diagnosis for server-side logs and traces only — may contain table and\n * constraint names. Never included in the HTTP response.\n */\n serverDetail?: unknown;\n}\n\n/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n readonly code?: string;\n readonly serverDetail?: unknown;\n /**\n * Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate\n * bundles, so an error thrown by the data client and caught by the router is\n * an instance of a *different* copy of this class — `instanceof` would be\n * false. Everything checks this flag via `isHttpError` instead.\n */\n readonly __isHttpError = true as const;\n\n constructor(status: number, message: string, details?: unknown, options: HttpErrorOptions = {}) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n if (details !== undefined) this.details = details;\n if (options.code !== undefined) this.code = options.code;\n if (options.serverDetail !== undefined) this.serverDetail = options.serverDetail;\n }\n}\n\n/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */\nexport function isHttpError(err: unknown): err is HttpError {\n if (!err || typeof err !== 'object') return false;\n const e = err as { __isHttpError?: unknown; name?: unknown; status?: unknown };\n return e.__isHttpError === true || (e.name === 'HttpError' && typeof e.status === 'number');\n}\n\n/*\n * The helpers carry a stable `code` (from 1.0), so every refusal the SDK or an App\n * raises through them is machine-readable. Pass `options.code` for a sharper one.\n */\nexport const notFound = (message = 'not found', options: HttpErrorOptions = {}): HttpError =>\n new HttpError(404, message, undefined, { code: 'not_found', ...options });\nexport const badRequest = (message = 'bad request', details?: unknown, options: HttpErrorOptions = {}): HttpError =>\n new HttpError(400, message, details, { code: 'bad_request', ...options });\nexport const forbidden = (message = 'forbidden', options: HttpErrorOptions = {}): HttpError =>\n new HttpError(403, message, undefined, { code: 'forbidden', ...options });\nexport const conflict = (message = 'conflict', options: HttpErrorOptions = {}): HttpError =>\n new HttpError(409, message, undefined, { code: 'conflict', ...options });\n\n/**\n * The body every refusal is answered with. `error` is the message (the router's\n * shape since 0.3); `message` and `type` repeat the message and the code under the\n * names the platform client (`@revenexx/sdk`) reads, so a caller that catches its\n * `RevenexxException` sees the App's reason as `err.message` and its code as\n * `err.type` instead of `undefined` (RAD-98).\n */\nexport function refusalBody(message: string, code?: string, details?: unknown): Record<string, unknown> {\n return {\n error: message,\n message,\n ...(code ? { code, type: code } : {}),\n ...(details != null ? { details } : {}),\n };\n}\n\n/** A refusal, whichever side raised it. */\nexport interface Refusal {\n /** HTTP status the refusal was answered with. */\n status: number;\n /** The refusing App's stable code, or null when it gave none. */\n code: string | null;\n /** Why, in words safe to show. */\n message: string;\n details: unknown;\n /** The App that answered, as the gateway tagged it; null for this App's own refusal. */\n app: string | null;\n}\n\n/**\n * Read a refusal out of whatever was thrown: this App's own `HttpError`, or the\n * exception the platform client (`@revenexx/sdk`) throws when another App refused a\n * call — whose `code` is the HTTP status and whose `response` is that App's body\n * verbatim. `null` for anything that is not a refusal (a crash, a network fault),\n * which is the distinction a caller needs: a question that could not be answered is\n * not the far side being down.\n */\nexport function refusalOf(err: unknown): Refusal | null {\n if (isHttpError(err)) {\n return { status: err.status, code: err.code ?? null, message: err.message, details: err.details ?? null, app: null };\n }\n if (!err || typeof err !== 'object') return null;\n const e = err as { code?: unknown; response?: unknown; message?: unknown; type?: unknown; app?: unknown };\n const status = typeof e.code === 'number' ? e.code : Number.NaN;\n if (!(status >= 400 && status <= 599) || typeof e.response !== 'string') return null;\n let body: Record<string, unknown> = {};\n try {\n const parsed: unknown = JSON.parse(e.response || '{}');\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) body = parsed as Record<string, unknown>;\n } catch {\n /* not JSON: fall back to what the exception itself carries */\n }\n const str = (v: unknown): string | null => (typeof v === 'string' && v !== '' ? v : null);\n return {\n status,\n code: str(body.code) ?? str(body.type) ?? str(e.type),\n message: str(body.error) ?? str(body.message) ?? str(e.message) ?? 'the call was refused',\n details: body.details ?? null,\n app: str(e.app),\n };\n}\n","import type { Query, FilterOp, Row } from './types.js';\n\n/**\n * PostgREST query helpers. `toParams` serialises a query for the HTTP adapters;\n * `matches` applies the same `where` semantics in memory for the mock adapter —\n * keeping one shape means App code is identical across adapters.\n */\n\nexport const OPS: ReadonlySet<FilterOp> = new Set<FilterOp>(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'like', 'ilike', 'in', 'is']);\n\n/** Serialise a query object to PostgREST URLSearchParams. */\nexport function toParams(query: Query = {}): URLSearchParams {\n const params = new URLSearchParams();\n const { where = {}, select, order, limit, offset } = query;\n\n for (const [col, cond] of Object.entries(where)) {\n if (Array.isArray(cond)) {\n params.append(col, `in.${inList(cond)}`);\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!OPS.has(c.op)) throw new Error(`query: unsupported operator '${c.op}'`);\n const v = Array.isArray(c.value) ? inList(c.value) : c.value;\n params.append(col, `${c.op}.${v}`);\n } else if (cond === null) {\n // `eq.null` compares against the string 'null'; the mock already reads a\n // null condition as \"is null\", and now the data plane does too.\n params.append(col, 'is.null');\n } else {\n params.append(col, `eq.${cond}`);\n }\n }\n\n if (Array.isArray(select) && select.length) params.set('select', (select as string[]).join(','));\n if (order) params.set('order', /\\.(asc|desc)$/.test(order) ? order : `${order}.asc`);\n if (Number.isInteger(limit)) params.set('limit', String(limit));\n if (Number.isInteger(offset)) params.set('offset', String(offset));\n\n return params;\n}\n\n/**\n * A value list as PostgREST reads it: `(\"a\",\"b\")`. Every value is double-quoted\n * with `\\` and `\"` escaped, so a comma, a parenthesis, a quote or a backslash\n * inside a value stays part of that value instead of splitting the list or\n * breaking the filter. `null` stays the bare word `null`.\n */\nfunction inList(values: readonly unknown[]): string {\n return `(${values.map(quoteListValue).join(',')})`;\n}\n\nfunction quoteListValue(v: unknown): string {\n if (v === null || v === undefined) return 'null';\n return `\"${String(v).replace(/[\\\\\"]/g, '\\\\$&')}\"`;\n}\n\n/** In-memory predicate mirroring `toParams`' `where` semantics (mock adapter). */\nexport function matches(row: Row, where: Query['where'] = {}): boolean {\n for (const [col, cond] of Object.entries(where)) {\n // A column a row does not carry reads as null — in Postgres every row has\n // every column. Same as the PHP runtime.\n const val = row[col] ?? null;\n if (Array.isArray(cond)) {\n if (!cond.includes(val as never)) return false;\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!compare(val, c.op, c.value)) return false;\n } else if (val !== cond) {\n return false;\n }\n }\n return true;\n}\n\nfunction compare(a: unknown, op: FilterOp, b: unknown): boolean {\n switch (op) {\n case 'eq': return a === b;\n case 'neq': return a !== b;\n case 'gt': return (a as number) > (b as number);\n case 'gte': return (a as number) >= (b as number);\n case 'lt': return (a as number) < (b as number);\n case 'lte': return (a as number) <= (b as number);\n case 'is': return a === b;\n case 'in': return Array.isArray(b) && b.includes(a);\n case 'like':\n case 'ilike': {\n const re = new RegExp(\n '^' + String(b).replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/%/g, '.*').replace(/_/g, '.') + '$',\n op === 'ilike' ? 'i' : '',\n );\n return re.test(String(a));\n }\n default: return false;\n }\n}\n","/**\n * App settings — the tenant's configuration for THIS app, read at runtime.\n *\n * An App declares its settings in `settings.json` (`{ settings: { <key>:\n * { type, scope, default, sensitive, ... } } }`). The cockpit renders that\n * schema, Console stores the tenant's chosen values, and the gateway resolves\n * the two into an effective map:\n *\n * GET {gateway}/v1/settings/apps/{app}[?market={code}]\n * -> { app, market, settings: { … }, masked: [ … ], stored: [ … ] }\n *\n * Resolution happens ON THE GATEWAY, and this reader does not second-guess it.\n * Per key, the gateway applies (api/internal/gateway/settings.go,\n * `resolveSettings`):\n *\n * 1. per-market override — only for settings declared `\"scope\": \"market\"`,\n * and only when `?market=` is sent\n * 2. stored tenant value — the flat value in `settings_values`\n * 3. schema default — the `default` from settings.json\n *\n * Settings flagged `sensitive` are never in `settings`; their keys are listed\n * in `masked` so a caller can tell \"not configured\" from \"not for you\".\n *\n * The `defaults` you pass here are a *fourth*, last-resort layer: they are what\n * the app runs on when the settings service cannot be reached, and they are\n * what types the resolved object. They never override a value the gateway\n * actually resolved — only a `null`/absent one.\n *\n * const settings = createSettings({\n * app: 'orders',\n * defaults: { auto_reserve: true, reservation_minutes: 30 },\n * });\n *\n * app.post('/orders', async (c) => {\n * const s = await settings.get(c); // market taken from the request\n * if (s.auto_reserve) { … }\n * });\n *\n * Or let the router own it — `createApp({ name, settings: { defaults } })`\n * gives every handler `await c.settings()`.\n *\n * ## Writing the app's OWN settings\n *\n * Some values have to be STORED, not merely declared — a platform service may\n * refuse to act on a default it cannot tell from \"nobody decided\". The app can\n * store them itself:\n *\n * const result = await settings.set(c, { locale_granularity: 'language' }, { ifAbsent: true });\n * // PATCH {gateway}/v1/settings/apps/{app}\n * // -> { ok, written: [...], kept: [...], ignored: [...] }\n *\n * The gateway lets an app write only its own settings, for the tenant its\n * request belongs to: it reads the app from the platform-signed\n * `x-revenexx-app-context` header the router hands every HTTP invocation, which\n * this reader forwards. A run started by an event or a schedule carries none,\n * so a write from there comes back `ok: false` — write from an HTTP route.\n * `ifAbsent` keeps every key the tenant already stored: use it for defaults,\n * so an install hook never undoes a merchant's choice. `stored` on a snapshot\n * says which keys are stored rather than defaulted.\n *\n * Two properties make this safe to call on every request:\n *\n * - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that\n * declares no settings at all: you get the last good values if there are\n * any, otherwise your declared defaults. It never throws and never takes\n * the app down. Availability is the default; switching something off is\n * the deliberate act, and a deliberate act must not be the accident.\n * - it CACHES. Per (tenant, app, market), for a short TTL, with concurrent\n * reads sharing one in-flight request. A warm read is a Map lookup.\n */\n\n/** The platform gateway. Override with REVENEXX_GATEWAY_ENDPOINT. */\nexport const DEFAULT_GATEWAY_ENDPOINT = 'https://api.revenexx.com';\n\n/**\n * How long a resolved settings map stays warm in the process (ms).\n *\n * Settings are configuration, not data: a merchant flips one every few weeks.\n * The gateway keeps its own 30s cache in front of Console and drops it on a\n * NATS invalidation when values change, so this second layer is the only real\n * staleness — a cockpit change takes effect within a minute. That is the right\n * trade against the alternative, which is a gateway round trip on the hot path\n * of every single request.\n *\n * Override per reader (`ttlMs`) or per deployment (REVENEXX_SETTINGS_TTL_MS).\n */\nexport const DEFAULT_SETTINGS_TTL_MS = 60_000;\n\n/**\n * How long a FAILED read stays cached (ms). Short, because the failure is\n * usually transient and we want to recover quickly — but not zero, or an\n * unreachable gateway would put a doomed round trip on every request, which is\n * exactly the outage the fail-open is supposed to absorb.\n *\n * A 404 (\"app not installed or declares no settings\") is not a failure but a\n * stable answer, and is cached for the full TTL.\n */\nexport const DEFAULT_SETTINGS_ERROR_TTL_MS = 5_000;\n\n/** Request timeout (ms). A hung settings service must not hang the app. */\nexport const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;\n\nexport type SettingsDefaults = Record<string, unknown>;\n\n/**\n * The resolved map. Keys you declared in `defaults` keep their type; anything\n * else the manifest declares is still there, as `unknown`.\n */\nexport type ResolvedSettings<D extends SettingsDefaults = SettingsDefaults> = D & Record<string, unknown>;\n\n/**\n * Anything a request's tenant/token/market can be read from: the router's\n * `RouteContext`, the raw function context (`{ req: { headers } }`), or a bare\n * headers object.\n */\nexport interface SettingsSource {\n header?(name: string): string;\n tenant?: string | null;\n contextToken?: string;\n req?: { headers?: Record<string, string> | undefined } | undefined;\n headers?: Record<string, string> | undefined;\n}\n\nexport interface SettingsOptions<D extends SettingsDefaults = SettingsDefaults> {\n /**\n * The app whose settings to read. Defaults to REVENEXX_APP_NAME, which the\n * runtime sets — a deployed app usually needs no value here. `createApp`\n * passes its own `name`.\n */\n app?: string;\n /**\n * Last-resort values, and the type source. Use the same defaults your\n * settings.json declares: they are what the app runs on if the settings\n * service is unreachable.\n */\n defaults?: D;\n /** Gateway base URL. Default: REVENEXX_GATEWAY_ENDPOINT or the platform gateway. */\n endpoint?: string;\n /** Cache TTL in ms. Default: REVENEXX_SETTINGS_TTL_MS or 60_000. */\n ttlMs?: number;\n /** How long a failed read is cached, in ms. Default 5_000. */\n errorTtlMs?: number;\n /** Per-request timeout in ms. Default 2_000. */\n timeoutMs?: number;\n /** Environment to read from (tests). Default `process.env`. */\n env?: Record<string, string | undefined>;\n /** Fetch implementation (tests). Default `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /**\n * Called when a read fails and the app falls back. Wire it to the function's\n * `error()` so a silent fallback is still visible. Must not throw.\n */\n onError?: (error: Error, info: { app: string; tenant: string; market: string | null }) => void;\n}\n\n/** A resolved read, with the provenance a caller occasionally needs. */\nexport interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {\n app: string;\n tenant: string;\n /** The market the values were resolved for, or null for the tenant baseline. */\n market: string | null;\n settings: ResolvedSettings<D>;\n /** Keys that exist but are `sensitive`, so their values were withheld. */\n masked: string[];\n /**\n * Keys whose value the tenant STORED (a tenant value, or the market's\n * override), as opposed to the declared default. A stored default and an\n * unset key resolve to the same value; this tells them apart. Empty on a\n * fallback, and from a gateway too old to say.\n */\n stored: string[];\n /** true when these values came from the gateway (fresh or cached). */\n resolved: boolean;\n /** Why the fallback happened, when `resolved` is false. */\n error?: string;\n}\n\nexport interface ReadOptions {\n /** Resolve for this market instead of the one on the request. `''` = tenant baseline. */\n market?: string;\n}\n\nexport interface WriteOptions {\n /** Keep every key the tenant already stored; write only the missing ones. */\n ifAbsent?: boolean;\n}\n\n/** The outcome of `set()`. Key names only — the gateway never echoes values. */\nexport interface SettingsWriteResult {\n /** true when the gateway accepted the write (even if it wrote nothing). */\n ok: boolean;\n /** HTTP status of the gateway's answer; 0 when it was never asked or unreachable. */\n status: number;\n /** Keys stored by this write. */\n written: string[];\n /** Keys left alone because they were already stored (`ifAbsent`). */\n kept: string[];\n /** Keys dropped because the app's settings.json does not declare them. */\n ignored: string[];\n /** Why the write did not happen, when `ok` is false. */\n error?: string;\n}\n\nexport interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {\n /** The effective settings for this request. Never throws. */\n get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/stored/provenance. */\n load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n /**\n * Store this app's OWN tenant-level settings for the request's tenant.\n * Never throws: a refusal or an unreachable gateway is `ok: false`, also\n * reported to `onError`. A successful write drops the tenant's cached reads.\n */\n set(source: SettingsSource | undefined, values: Record<string, unknown>, options?: WriteOptions): Promise<SettingsWriteResult>;\n /** Drop the cache (tests, or right after writing settings). */\n clear(): void;\n}\n\ninterface Entry<D extends SettingsDefaults> {\n at: number;\n ttl: number;\n promise: Promise<SettingsSnapshot<D>>;\n}\n\ninterface GatewayResponse {\n settings?: Record<string, unknown>;\n masked?: unknown;\n stored?: unknown;\n}\n\nfunction stringList(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((k): k is string => typeof k === 'string') : [];\n}\n\n/** Case-insensitive header read across the three shapes we accept. */\nfunction headerOf(source: SettingsSource | undefined, name: string): string {\n if (!source) return '';\n if (typeof source.header === 'function') {\n const v = source.header(name);\n if (typeof v === 'string' && v !== '') return v;\n }\n const bags = [source.req?.headers, source.headers];\n const want = name.toLowerCase();\n for (const bag of bags) {\n if (!bag) continue;\n const direct = bag[name] ?? bag[want];\n if (typeof direct === 'string' && direct !== '') return direct;\n for (const [k, v] of Object.entries(bag)) {\n if (k.toLowerCase() === want && typeof v === 'string' && v !== '') return v;\n }\n }\n return '';\n}\n\n/**\n * Merge the gateway's resolved map over the declared defaults.\n *\n * A `null` from the gateway does NOT clobber a default: a setting the merchant\n * never touched and whose schema carries no default resolves to `null`, and a\n * caller should not have to null-check a key it declared a default for. A real\n * stored value — including `false`, `0` and `''` — always wins.\n */\nfunction mergeSettings<D extends SettingsDefaults>(\n defaults: D | undefined,\n resolved: Record<string, unknown> | undefined,\n): ResolvedSettings<D> {\n const out: Record<string, unknown> = { ...(defaults ?? {}) };\n for (const [key, value] of Object.entries(resolved ?? {})) {\n if (value !== null && value !== undefined) out[key] = value;\n else if (!(key in out)) out[key] = value ?? null;\n }\n return out as ResolvedSettings<D>;\n}\n\nfunction timeoutSignal(ms: number): AbortSignal | undefined {\n const factory = (AbortSignal as { timeout?: (ms: number) => AbortSignal }).timeout;\n if (typeof factory === 'function') return factory(ms);\n if (typeof AbortController !== 'function') return undefined;\n const controller = new AbortController();\n setTimeout(() => controller.abort(), ms).unref?.();\n return controller.signal;\n}\n\n/**\n * Build a settings reader for one app. Create it once at module scope — the\n * cache lives on the reader, and a per-request reader would cache nothing.\n */\nexport function createSettings<D extends SettingsDefaults = SettingsDefaults>(\n options: SettingsOptions<D> = {},\n): SettingsReader<D> {\n const env = options.env ?? process.env;\n const defaults = options.defaults;\n const ttlMs = options.ttlMs ?? Number(env.REVENEXX_SETTINGS_TTL_MS ?? DEFAULT_SETTINGS_TTL_MS);\n const errorTtlMs = options.errorTtlMs ?? DEFAULT_SETTINGS_ERROR_TTL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_SETTINGS_TIMEOUT_MS;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(\n /\\/+$/,\n '',\n );\n\n const cache = new Map<string, Entry<D>>();\n /** Last successful snapshot per key — served instead of defaults on a blip. */\n const lastGood = new Map<string, SettingsSnapshot<D>>();\n\n const appName = (): string => String(options.app || env.REVENEXX_APP_NAME || '').trim();\n\n const fallback = (app: string, tenant: string, market: string | null, error: string): SettingsSnapshot<D> => ({\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, undefined),\n masked: [],\n stored: [],\n resolved: false,\n error,\n });\n\n const report = (err: Error, info: { app: string; tenant: string; market: string | null }): void => {\n try {\n options.onError?.(err, info);\n } catch {\n /* an error reporter must never be the reason a request fails */\n }\n };\n\n async function request(app: string, tenant: string, token: string, market: string | null): Promise<SettingsSnapshot<D>> {\n const f = options.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') throw new Error('settings: no fetch available (Node >=18 or pass fetchImpl)');\n\n const qs = market ? `?market=${encodeURIComponent(market)}` : '';\n const headers: Record<string, string> = { Accept: 'application/json', 'X-Revenexx-Tenant': tenant };\n if (token) headers.Authorization = `Bearer ${token}`;\n\n const signal = timeoutSignal(timeoutMs);\n const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}${qs}`, {\n method: 'GET',\n headers,\n ...(signal ? { signal } : {}),\n });\n const text = await res.text();\n if (!res.ok) {\n const err = new Error(`settings: ${res.status} for ${app}`) as Error & { status?: number };\n err.status = res.status;\n throw err;\n }\n const body = (text ? JSON.parse(text) : {}) as GatewayResponse;\n return {\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, body.settings),\n masked: stringList(body.masked),\n stored: stringList(body.stored),\n resolved: true,\n };\n }\n\n /** Drop every cached read for one tenant of this app (after a write). */\n const forgetTenant = (tenant: string, app: string): void => {\n const prefix = `${tenant}\\u0000${app}\\u0000`;\n for (const key of [...cache.keys()]) if (key.startsWith(prefix)) cache.delete(key);\n for (const key of [...lastGood.keys()]) if (key.startsWith(prefix)) lastGood.delete(key);\n };\n\n async function set(\n source: SettingsSource | undefined,\n values: Record<string, unknown>,\n writeOptions: WriteOptions = {},\n ): Promise<SettingsWriteResult> {\n const app = appName();\n const tenant = (source?.tenant ?? '') || headerOf(source, 'x-revenexx-tenant');\n const refused = (status: number, error: string): SettingsWriteResult => ({\n ok: false,\n status,\n written: [],\n kept: [],\n ignored: [],\n error,\n });\n\n // Nothing the gateway could accept — answer without a round trip.\n if (!app) return refused(0, 'no app name (pass `app` or set REVENEXX_APP_NAME)');\n if (!tenant) return refused(0, 'no tenant on the request');\n const appContext = headerOf(source, 'x-revenexx-app-context');\n if (!appContext) {\n return refused(0, 'no app context on the request — settings are written from an HTTP route, not an event or schedule run');\n }\n if (!values || typeof values !== 'object' || Array.isArray(values)) return refused(0, 'values must be an object');\n\n const f = options.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') return refused(0, 'settings: no fetch available (Node >=18 or pass fetchImpl)');\n\n const token = (source?.contextToken ?? '') || headerOf(source, 'x-revenexx-context');\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Revenexx-Tenant': tenant,\n 'X-Revenexx-App-Context': appContext,\n };\n if (token) headers.Authorization = `Bearer ${token}`;\n\n try {\n const signal = timeoutSignal(timeoutMs);\n const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}`, {\n method: 'PATCH',\n headers,\n body: JSON.stringify({ data: values, if_absent: writeOptions.ifAbsent === true }),\n ...(signal ? { signal } : {}),\n });\n const text = await res.text();\n let body: Record<string, unknown> = {};\n try {\n body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n } catch {\n body = {};\n }\n if (!res.ok) {\n const reason = typeof body.error === 'string' ? body.error : typeof body.message === 'string' ? body.message : '';\n const err = new Error(`settings: write ${res.status} for ${app}${reason ? ` — ${reason}` : ''}`) as Error & {\n status?: number;\n };\n err.status = res.status;\n report(err, { app, tenant, market: null });\n return refused(res.status, err.message);\n }\n const result: SettingsWriteResult = {\n ok: true,\n status: res.status,\n written: stringList(body.written),\n kept: stringList(body.kept),\n ignored: stringList(body.ignored),\n };\n if (result.written.length > 0) forgetTenant(tenant, app);\n return result;\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error(String(err));\n report(error, { app, tenant, market: null });\n return refused(0, error.message);\n }\n }\n\n async function load(source?: SettingsSource, readOptions: ReadOptions = {}): Promise<SettingsSnapshot<D>> {\n const app = appName();\n const tenant = (source?.tenant ?? '') || headerOf(source, 'x-revenexx-tenant');\n const market = (readOptions.market ?? headerOf(source, 'x-revenexx-market')).trim() || null;\n\n // Nothing to ask with — answer from the defaults without a round trip.\n if (!app) return fallback('', tenant, market, 'no app name (pass `app` or set REVENEXX_APP_NAME)');\n if (!tenant) return fallback(app, '', market, 'no tenant on the request');\n\n const key = `${tenant}\u0000${app}\u0000${market ?? ''}`;\n const now = Date.now();\n const hit = cache.get(key);\n if (hit && now - hit.at < hit.ttl) return hit.promise;\n\n const token = (source?.contextToken ?? '') || headerOf(source, 'x-revenexx-context');\n const entry: Entry<D> = { at: now, ttl: ttlMs, promise: undefined as unknown as Promise<SettingsSnapshot<D>> };\n entry.promise = request(app, tenant, token, market)\n .then((snapshot) => {\n lastGood.set(key, snapshot);\n return snapshot;\n })\n .catch((err: unknown) => {\n const error = err instanceof Error ? err : new Error(String(err));\n // A 404 is the gateway saying \"this app is not installed, or declares\n // no settings\" — a stable answer, not a blip. Cache it for the full TTL\n // so an app without settings does not re-ask every five seconds.\n const status = (error as { status?: number }).status;\n entry.ttl = status === 404 ? ttlMs : errorTtlMs;\n report(error, { app, tenant, market });\n // Prefer the last values we genuinely resolved over the defaults: they\n // are the tenant's actual configuration, and a gateway blip is no\n // reason to silently revert a merchant's choices.\n const stale = lastGood.get(key);\n if (stale) return { ...stale, resolved: false, error: error.message };\n return fallback(app, tenant, market, error.message);\n });\n\n // Cached before it settles, so concurrent requests share one fetch.\n cache.set(key, entry);\n return entry.promise;\n }\n\n return {\n load,\n set,\n async get(source?: SettingsSource, readOptions?: ReadOptions): Promise<ResolvedSettings<D>> {\n return (await load(source, readOptions)).settings;\n },\n clear(): void {\n cache.clear();\n lastGood.clear();\n },\n };\n}\n","/**\n * Backdating — replaying history into a test tenant (RAD-311).\n *\n * A simulator fills a test tenant with months of orders, payments and stock\n * movements. Everything an App stamps is \"now\", so without help the whole\n * history would land on the afternoon the simulator ran. An App that opts in\n * (`createApp({ backdating: true })`) lets a mutating request carry a past\n * moment in its body (`at`, or a route's own field) and runs the WHOLE request\n * on that clock: every `now()` the handler reads, every timestamp it writes,\n * and — through `backdatingDb` — the `created_at` of every row it creates.\n *\n * Only for a tenant whose admin switched it on: the App setting\n * `allow_backdating` (scope tenant, default off), read through `c.settings()`.\n * A settings service that cannot be reached hands back the declared defaults,\n * so an unreadable setting means off. The tenant has to be named twice and\n * agree: the `x-revenexx-tenant` header AND the `tenant_id` claim of the\n * forwarded identity token (`x-revenexx-context`). The header alone is not\n * enough — a caller reaching the function URL directly can set it. The claim is\n * not verified here; the data plane verifies the token on every read and write,\n * so a token claiming another tenant writes nothing at all.\n *\n * Without the gate the field is ignored, unread and unvalidated. With it the\n * moment must be an ISO 8601 date-time with a zone, not in the future and not\n * more than `MAX_MONTHS_BACK` months back; anything else is a 400 with code\n * `backdating_invalid`.\n *\n * The clock lives in an AsyncLocalStorage kept on `globalThis`, so the two\n * entry points (`@revenexx/app-sdk` and `@revenexx/app-sdk/router`, separate\n * bundles, each in ESM and CJS) read one and the same clock.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { HttpError } from './errors.js';\nimport { isList } from './patch.js';\n\n/** How far back a backdated request may reach, in months. */\nexport const MAX_MONTHS_BACK = 24;\n\n/** The App setting that opens backdating for a tenant. */\nexport const BACKDATING_SETTING = 'allow_backdating';\n\n/** The body field every backdated route accepts. Reserved in Apps that opt in. */\nexport const BACKDATING_FIELD = 'at';\n\n/** The refusal code of a moment that cannot be honoured. */\nexport const BACKDATING_INVALID = 'backdating_invalid';\n\n/** The route methods `backdating: true` covers. */\nexport const BACKDATING_METHODS: readonly string[] = ['POST', 'PUT', 'PATCH', 'DELETE'];\n\n/**\n * `createApp({ backdating })`. `true` lets every mutating route (POST, PUT,\n * PATCH, DELETE) accept `at`; the object form does the same and refines it.\n */\nexport interface BackdatingOptions {\n /**\n * Per-route body fields that carry the moment, in precedence order, keyed\n * `METHOD /template` exactly as the route was registered:\n * `{ 'POST /orders/place': ['placed_at', 'at'] }`. `at` is always accepted —\n * appended last when the list does not name it. A route named here is\n * backdatable whatever its method.\n */\n routes?: Record<string, readonly string[]>;\n /** Routes (`METHOD /template`) that are never backdated. Wins over `routes`. */\n exclude?: readonly string[];\n /**\n * Remove the moment's fields from `c.body` before the handler runs, on every\n * request to a backdatable route — whether the gate opened or not. Default\n * false: the body is left as it came. Set it when a handler spreads its body\n * into a row: the data client refuses a key that is not a column.\n */\n strip?: boolean;\n}\n\ninterface ClockStore {\n at: string;\n}\n\nconst STORE_KEY = Symbol.for('@revenexx/app-sdk/backdating-clock');\n\nfunction clockStorage(): AsyncLocalStorage<ClockStore> {\n const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<ClockStore> | undefined>;\n let storage = g[STORE_KEY];\n if (!storage) {\n storage = new AsyncLocalStorage<ClockStore>();\n g[STORE_KEY] = storage;\n }\n return storage;\n}\n\nconst CLOCK = clockStorage();\n\n/** The request's clock as an ISO string: the backdated moment while one runs, the wall clock otherwise. */\nexport const now = (): string => CLOCK.getStore()?.at ?? new Date().toISOString();\n\n/** The request's clock as a Date, for code that does arithmetic on it. */\nexport const clock = (): Date => new Date(now());\n\n/** True while a backdated request (or `runAt`) is running. */\nexport const backdated = (): boolean => Boolean(CLOCK.getStore()?.at);\n\n/**\n * Run `fn` on the clock `at` (a normalized ISO string). `null` runs it on the\n * wall clock. Everything `fn` awaits sees the same clock. For a job outside a\n * route — a replay worker — and for tests.\n */\nexport function runAt<T>(at: string | null | undefined, fn: () => T): T {\n return at ? CLOCK.run({ at }, fn) : fn();\n}\n\n/** Date-time with a zone, seconds and fraction optional. A bare date is not a moment. */\nconst ISO_DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:?\\d{2})$/;\n\nconst invalid = (field: string, message: string): HttpError =>\n new HttpError(400, `'${field}' ${message}`, { field }, { code: BACKDATING_INVALID });\n\n/**\n * Check one requested moment and answer it normalized (UTC, `toISOString`).\n * Throws a 400 `backdating_invalid` naming `field` when it is not an ISO 8601\n * date-time with a zone, lies in the future, or lies more than\n * `MAX_MONTHS_BACK` months back. `reference` is the wall clock to measure\n * against (tests).\n */\nexport function parseBackdate(field: string, value: unknown, reference: Date = new Date()): string {\n const text = typeof value === 'string' ? value.trim() : '';\n if (!ISO_DATE_TIME.test(text)) throw invalid(field, 'must be an ISO 8601 date-time with a time zone');\n const at = new Date(text);\n if (Number.isNaN(at.getTime())) throw invalid(field, 'must be an ISO 8601 date-time with a time zone');\n if (at.getTime() > reference.getTime()) throw invalid(field, 'must not be in the future');\n const earliest = new Date(reference.getTime());\n earliest.setUTCMonth(earliest.getUTCMonth() - MAX_MONTHS_BACK);\n if (at.getTime() < earliest.getTime()) {\n throw invalid(field, `must not be more than ${MAX_MONTHS_BACK} months back`);\n }\n return at.toISOString();\n}\n\n/** What the gate reads off a request: the router's route context fits. */\nexport interface BackdatingSource {\n header?(name: string): string;\n contextToken?: string;\n settings?(): Promise<Record<string, unknown>>;\n}\n\n/** The `tenant_id` claim of a JWT, or '' (decoded, not verified). */\nfunction tokenTenant(token: unknown): string {\n const parts = typeof token === 'string' ? token.split('.') : [];\n if (parts.length < 2) return '';\n try {\n const payload = parts[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const claims = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')) as { tenant_id?: unknown } | null;\n return typeof claims?.tenant_id === 'string' ? claims.tenant_id.trim() : '';\n } catch {\n return '';\n }\n}\n\n/** `true`, or the text `'true'` a settings store may hand back, opens it. Nothing else does. */\nexport function settingAllowsBackdating(value: unknown): boolean {\n return value === true || (typeof value === 'string' && value.trim().toLowerCase() === 'true');\n}\n\n/**\n * Whether this request's tenant may backdate: the tenant header and the\n * identity token's `tenant_id` claim name the same tenant, and that tenant's\n * `allow_backdating` setting is on. Never throws; anything unreadable is false.\n */\nexport async function backdatingAllowed(c: BackdatingSource): Promise<boolean> {\n const read = (name: string): string => (typeof c?.header === 'function' ? String(c.header(name) ?? '').trim() : '');\n const header = read('x-revenexx-tenant');\n const claimed = tokenTenant(c?.contextToken || read('x-revenexx-context'));\n if (!header || header !== claimed) return false;\n if (typeof c?.settings !== 'function') return false;\n try {\n const settings = await c.settings();\n return settingAllowsBackdating(settings?.[BACKDATING_SETTING]);\n } catch {\n return false;\n }\n}\n\nconst present = (value: unknown): boolean => value !== undefined && value !== null && value !== '';\n\n/**\n * The moment a request asks for, or null. Reads nothing when no field is\n * present, resolves the gate next and returns null when it is closed, then\n * validates the first field present in `fields` order.\n */\nexport async function requestedMoment(\n c: BackdatingSource & { body?: Record<string, unknown> },\n fields: readonly string[],\n): Promise<string | null> {\n const body = c?.body;\n if (!body || typeof body !== 'object') return null;\n const field = fields.find((f) => present(body[f]));\n if (field === undefined) return null;\n if (!(await backdatingAllowed(c))) return null;\n return parseBackdate(field, body[field]);\n}\n\n/**\n * The fields a route reads its moment from under these options, or null when\n * the route is not backdatable. `key` is `METHOD /template`.\n */\nexport function backdatingFields(\n option: boolean | BackdatingOptions | undefined,\n method: string,\n template: string,\n): string[] | null {\n if (!option) return null;\n const opts: BackdatingOptions = option === true ? {} : option;\n const key = `${method.toUpperCase()} ${template}`;\n if (opts.exclude?.includes(key)) return null;\n const named = opts.routes?.[key];\n if (named) return named.includes(BACKDATING_FIELD) ? [...named] : [...named, BACKDATING_FIELD];\n return BACKDATING_METHODS.includes(method.toUpperCase()) ? [BACKDATING_FIELD] : null;\n}\n\n/** The part of an entity descriptor `backdatingDb` reads: does it have the column? */\nexport interface BackdatingEntity {\n columns?: Record<string, unknown>;\n}\n\n/**\n * The data client, with `created_at` (and `updated_at`, when the entity has\n * it) stamped on every row a backdated request creates. Outside a backdated\n * request it changes nothing: the database default stamps the row as always.\n * A value the caller set is kept. Only entities whose descriptor in `entities`\n * declares a `created_at` column are touched; pass the generated `ENTITIES`.\n *\n * const { createDb, ENTITIES } = require('./db.generated');\n * const db = backdatingDb(createDb(), ENTITIES);\n */\nexport function backdatingDb<T extends object>(db: T, entities: Record<string, BackdatingEntity | undefined>): T {\n const wrapped = new Map<string, unknown>();\n return new Proxy(db, {\n get(target, prop, receiver) {\n const value: unknown = Reflect.get(target, prop, receiver);\n if (typeof prop !== 'string') return value;\n const columns = entities?.[prop]?.columns;\n if (!columns || !('created_at' in columns) || !value || typeof value !== 'object') return value;\n const repo = value as { create?: unknown };\n if (typeof repo.create !== 'function') return value;\n if (!wrapped.has(prop)) {\n wrapped.set(\n prop,\n new Proxy(repo, {\n get(r, key, rr) {\n const member: unknown = Reflect.get(r, key, rr);\n if ((key !== 'create' && key !== 'createMany') || typeof member !== 'function') return member;\n const call = (data: unknown, rest: unknown[]) => (member as (...a: unknown[]) => unknown).call(r, data, ...rest);\n /** One record, stamped; anything that is not a record goes on to be refused. */\n const stamp = (data: unknown, at: string): unknown => {\n if (!data || typeof data !== 'object' || Array.isArray(data) || isList(data)) return data;\n const row: Record<string, unknown> = { ...(data as Record<string, unknown>) };\n if (row.created_at === undefined) row.created_at = at;\n if ('updated_at' in columns && row.updated_at === undefined) row.updated_at = at;\n return row;\n };\n if (key === 'createMany') {\n // Every record of a bulk create is stamped as a single create is,\n // so the records keep naming the same fields.\n return (data: unknown, ...rest: unknown[]) => {\n if (!backdated() || !Array.isArray(data)) return call(data, rest);\n const at = now();\n return call(data.map((record) => stamp(record, at)), rest);\n };\n }\n return (data: unknown, ...rest: unknown[]) => (backdated() ? call(stamp(data, now()), rest) : call(data, rest));\n },\n }),\n );\n }\n return wrapped.get(prop);\n },\n });\n}\n","/**\n * What counts as an update.\n *\n * PostgREST answers a `PATCH` whose body carries no columns with `200 []` — no\n * error, no representation. The adapter then hands `rows[0]` (i.e. `undefined`)\n * back as the updated row, and the App serialises it: open-runtimes does\n * `Buffer.from(JSON.stringify(obj), 'utf8')`, and `JSON.stringify(undefined)`\n * is `undefined`, so Node throws\n *\n * TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string\n * or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\n * Received undefined\n *\n * which the App reports as a 500. A caller who sent nothing to update is told\n * the service is broken instead of what to send.\n *\n * The rule lives here, one level below the router, because not every App routes\n * its writes through `mountCrud`: `PUT /v1/greetings/{id}` and\n * `PUT /v1/payments/providers/{id}` are hand-written handlers that call\n * `db.<entity>.update()` directly, and they were the two endpoints that 500ed.\n * A guard in `mountCrud` alone only protects the Apps that happen to use it.\n */\n\nimport { badRequest } from './errors.js';\nimport type { Row } from './types.js';\n\n/** The one wording every layer uses for \"you sent nothing to update\". */\nexport const EMPTY_UPDATE_MESSAGE = 'request body must contain at least one field to update';\n\n/**\n * The fields a patch would actually send. `undefined` values are excluded\n * because `JSON.stringify` drops them: `{ name: undefined }` reaches PostgREST\n * as `{}` and is exactly as empty as `{}` itself.\n */\nexport function updateFields(patch: unknown): string[] {\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return [];\n return Object.keys(patch as Record<string, unknown>).filter(\n (key) => (patch as Record<string, unknown>)[key] !== undefined,\n );\n}\n\n/** The one wording every layer uses for \"you sent nothing to create\". */\nexport const EMPTY_CREATE_MESSAGE = 'request body must contain at least one field to create';\n\n/**\n * Throw a 400 `empty_create` when a create carries no field — `{}`, `[]`, or\n * only `undefined` values.\n *\n * The two adapters disagreed about it: the mock stored a row of defaults, the\n * remote adapter sent the body to PostgREST, which reads `[]` as a bulk insert\n * of no rows and answers `[]` — the App then reported `500\n * empty_representation`. PHP cannot tell `[]` from `{}`, so both are refused,\n * in both runtimes and on both adapters, before any request.\n */\nexport function assertCreatable(data: unknown): void {\n if (updateFields(data).length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, undefined, { code: 'empty_create' });\n}\n\n/** Throw a 400 when a patch carries nothing to write. */\nexport function assertUpdatable(patch: unknown): void {\n if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE, undefined, { code: 'empty_update' });\n}\n\n/**\n * The one wording every layer uses for \"a conditional update with no condition\".\n *\n * `updateIf(id, {}, patch)` is an unconditional update spelled as a\n * conditional one — almost always a condition built from a variable that was\n * never set. Running it would let through the very race the caller reached\n * for `updateIf` to close, so it is refused; `update()` is the unconditional\n * write.\n */\nexport const EMPTY_CONDITION_MESSAGE = 'a conditional update needs at least one condition in where';\n\n/**\n * Throw a 400 when a `where` carries no condition, or one left `undefined`.\n *\n * An `undefined` entry is refused rather than dropped: dropping it would\n * quietly weaken the condition, and the two adapters would disagree about it\n * (`toParams` sends `eq.undefined`, `matches` compares against a missing key).\n */\nexport function assertCondition(where: unknown): void {\n if (!where || typeof where !== 'object' || Array.isArray(where) || Object.keys(where).length === 0) {\n throw badRequest(EMPTY_CONDITION_MESSAGE, undefined, { code: 'empty_condition' });\n }\n assertDefined(where);\n}\n\n/**\n * Throw a 400 when any `where` entry is `undefined` — on every read, not only a\n * conditional update. The two adapters disagree about one: `toParams` sends\n * `eq.undefined`, `matches` compares against a missing key. It is almost always\n * a variable that was never set, so it is refused rather than guessed at.\n */\nexport function assertDefined(where: unknown): void {\n if (!where || typeof where !== 'object') return;\n for (const [col, cond] of Object.entries(where as Record<string, unknown>)) {\n if (cond === undefined) {\n throw badRequest(`where.${col} is undefined — a condition needs a value`, undefined, { code: 'undefined_condition' });\n }\n }\n}\n\n/**\n * Columns every table has without declaring them in schema.json — Baseline\n * adds them, so the generated column list does not name them. Writing one is\n * left exactly as it was before the field check existed.\n */\nexport const IMPLICIT_COLUMNS: readonly string[] = ['tenant_id'];\n\n/**\n * The columns `trash: true` adds to an entity that does not declare them\n * itself: when the row went into the trash, who put it there (by name and by\n * subject id), the group it went with, and why it may not be purged yet.\n */\nexport const TRASH_FLAG_COLUMNS: readonly string[] = [\n 'deleted_at',\n 'deleted_by',\n 'deleted_by_id',\n 'trash_batch',\n 'purge_blocked_reason',\n];\n\n/** The column `external_id: true` adds to an entity that does not declare it. */\nexport const EXTERNAL_ID_FLAG_COLUMNS: readonly string[] = ['external_id'];\n\n/** The parts of an entity descriptor the field check reads. */\nexport interface WriteShape {\n name: string;\n columns?: Record<string, unknown>;\n trash?: boolean;\n external_id?: boolean;\n}\n\n/**\n * The columns Baseline adds for the entity's schema flags, whether or not the\n * App declares them as well. A column that exists in the table is a column\n * this version may write, even when the generated list only carries the flag.\n */\nexport function flagColumns(entity: Omit<WriteShape, 'name'>): string[] {\n return [\n ...(entity.trash === true ? TRASH_FLAG_COLUMNS : []),\n ...(entity.external_id === true ? EXTERNAL_ID_FLAG_COLUMNS : []),\n ];\n}\n\n/**\n * Every column a write may name, sorted: the declared columns plus the ones the\n * entity's flags add. `tenant_id` is accepted on top of these without being\n * listed, as before.\n */\nexport function writableColumns(entity: Omit<WriteShape, 'name'>): string[] {\n return [...new Set([...Object.keys(entity.columns ?? {}), ...flagColumns(entity)])].sort();\n}\n\n/**\n * The keys of a write that are not columns this version declares.\n *\n * A version writes only the columns it declares. The data plane cannot hold\n * that line on its own: during a rollout the new schema is applied before the\n * new code is served (and, with a release candidate, days before the stable\n * tenants move), and from that moment the old code can store a key it never\n * knew into the new column — without the validation the new version brings.\n * The generated `columns` are the list this version was built against, so a\n * key outside them is refused here, before the request.\n *\n * The columns an entity's `trash` and `external_id` flags add count as\n * declared: Baseline creates them from the flag, and an App that sets only the\n * flag still writes them (`mountTrash`, an import keeping the foreign key).\n *\n * Only the top level is checked: a `jsonb` column takes any document. A key\n * whose value is `undefined` is not sent (`JSON.stringify` drops it) and is\n * not checked. An entity without column metadata is not checked — there is\n * nothing to check against. A list is not a record and has no fields of its\n * own; `assertKnownFields` refuses it before this is asked.\n */\nexport function unknownFields(entity: Omit<WriteShape, 'name'>, data: unknown): string[] {\n if (!checksFields(entity)) return [];\n if (!data || typeof data !== 'object' || Array.isArray(data)) return [];\n const row = data as Record<string, unknown>;\n const writable = new Set([...writableColumns(entity), ...IMPLICIT_COLUMNS]);\n return Object.keys(row)\n .filter((key) => row[key] !== undefined && !writable.has(key))\n .sort();\n}\n\n/** Whether the entity carries the column metadata the field check reads. */\nfunction checksFields(entity: Omit<WriteShape, 'name'>): boolean {\n return !!entity.columns && Object.keys(entity.columns).length > 0;\n}\n\n/** The one wording every layer uses for \"a write takes one record\". */\nexport const ONE_RECORD_MESSAGE = 'a write takes one record, as a JSON object — not a list';\n\n/**\n * Throw a 400 `bad_request` when a write is a list rather than one record.\n *\n * `create` sends its data as the body of `POST /<table>`, and PostgREST reads a\n * JSON array there as a bulk insert: every element a row, every element's keys\n * columns. The field check reads the keys of one object, so a list slipped past\n * it with any key in any element — the rollout gap the check closes, reopened\n * one level down. The router hands an App a JSON array body unchanged, so a\n * handler that writes `db.x.create(c.body)` reached it from outside.\n *\n * Checked wherever the field check runs (an entity with column metadata), and\n * by `mountCrud` for every body it routes. What counts as a list is `isList`.\n */\nexport function assertOneRecord(entity: Omit<WriteShape, 'name'>, data: unknown): void {\n if (checksFields(entity) && isList(data)) throw oneRecordRefusal();\n}\n\nconst INDEX = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Whether a body is a list: a non-empty array, or a non-empty object whose keys\n * are exactly the indexes `0` … `n-1`, in any order.\n *\n * The definition is the one the PHP runtime can apply, and both use it: PHP\n * decodes `[…]` and `{\"0\":…}` to the same array, and `[]` to the same array as\n * `{}`. So an empty list is an empty record, and an object keyed by indexes is\n * a list.\n */\nexport function isList(data: unknown): boolean {\n if (!data || typeof data !== 'object') return false;\n if (Array.isArray(data)) return data.length > 0;\n const keys = Object.keys(data);\n return keys.length > 0 && keys.every((k) => INDEX.test(k) && Number(k) < keys.length);\n}\n\n/**\n * The columns `trash: true` adds are kept by the trash machinery — `mountTrash`\n * puts a record into the trash with its children, restores the group and\n * records why a purge waits. A body sent to a mounted collection that set them\n * would skip all of that: a record trashed with a forged `deleted_by`, or\n * restored and unblocked by `{\"deleted_at\": null, \"purge_blocked_reason\": null}`.\n * So `POST` / `PUT` of `mountCrud` refuse them on a trash entity, declared or\n * not; the data client still writes them for the trash routes.\n */\nexport function trashFieldsIn(entity: Omit<WriteShape, 'name'>, body: unknown): string[] {\n if (entity.trash !== true || !body || typeof body !== 'object') return [];\n const row = body as Record<string, unknown>;\n return TRASH_FLAG_COLUMNS.filter((k) => Object.prototype.hasOwnProperty.call(row, k) && row[k] !== undefined).sort();\n}\n\n/** Throw a 400 `read_only_field` when a mounted write sets a trash column. */\nexport function assertNoTrashFields(entity: Omit<WriteShape, 'name'>, body: unknown): void {\n const fields = trashFieldsIn(entity, body);\n if (fields.length === 0) return;\n const quoted = fields.map((k) => `'${k}'`).join(', ');\n throw badRequest(\n `field${fields.length > 1 ? 's' : ''} ${quoted} ${fields.length > 1 ? 'are' : 'is'} kept by the trash — ` +\n 'put a record into the trash, restore or purge it through the trash routes.',\n { fields },\n { code: 'read_only_field' },\n );\n}\n\n/**\n * The descriptor an entity client was built from, on a non-enumerable symbol\n * key, so `mountCrud` reads the entity's flags from the repo it is given, as\n * PHP's `Crud::mount` reads them from the `Entity`. `Symbol.for` keeps it the\n * same key across the ESM and CJS builds.\n */\nexport const ENTITY_DESCRIPTOR: unique symbol = Symbol.for('revenexx.app-sdk.entity') as never;\n\n/**\n * Whether a mounted collection keeps the trash columns out of bodies. Flags are\n * only ever added, never taken away: the repo's descriptor or `opts.trash`\n * turns it on, and `trash: false` cannot turn off what the descriptor says.\n * When neither states the flag — a repo of the App's own, wrapped or rebuilt —\n * a `trash_batch` among the columns, which only the trash machinery has, keeps\n * the guard on: unreadable fails closed.\n */\nexport function guardsTrash(stated: boolean | undefined, described: boolean | undefined, columns?: Record<string, unknown>): boolean {\n if (stated === true || described === true) return true;\n if (stated === undefined && described === undefined) return !!columns && Object.prototype.hasOwnProperty.call(columns, 'trash_batch');\n return false;\n}\n\n/** The descriptor behind a repo, when it is an entity client of this SDK. */\nexport function describedEntity(repo: unknown): Omit<WriteShape, 'name'> | undefined {\n if (!repo || typeof repo !== 'object') return undefined;\n return (repo as { [ENTITY_DESCRIPTOR]?: Omit<WriteShape, 'name'> })[ENTITY_DESCRIPTOR];\n}\n\n/** The one wording every layer uses for \"createMany takes a list\". */\nexport const MANY_RECORDS_MESSAGE = 'createMany takes a list of records';\n\n/**\n * The records of a `createMany`, in index order, checked before any request.\n *\n * PostgREST inserts a JSON array in one statement, so a bulk create is one\n * request, and every record must pass what a single create passes:\n *\n * - the data is a list (`isList`): anything else is `400 bad_request`, and an\n * empty list is `400 empty_create`;\n * - an element that is not a record is `400 bad_request`;\n * - an element with no field is `400 empty_create`;\n * - an element naming a key that is not a column is `400 unknown_field`;\n * - an element naming other fields than the first is `400 bad_request`:\n * PostgREST refuses a JSON array whose objects do not share their keys\n * (PGRST102). A key whose value is `undefined` does not count — it is not\n * sent.\n *\n * Every refusal of an element names it in `details.index` (0-based). The same\n * rule as the PHP runtime (`Entity::bulkRecords`).\n */\nexport function bulkRecords(entity: WriteShape, data: unknown): Row[] {\n if (Array.isArray(data) && data.length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, undefined, { code: 'empty_create' });\n if (!isList(data)) throw badRequest(MANY_RECORDS_MESSAGE, undefined, { code: 'bad_request' });\n const records = Array.isArray(data)\n ? (data as unknown[])\n : Object.keys(data as object)\n .sort((a, b) => Number(a) - Number(b))\n .map((k) => (data as Record<string, unknown>)[k]);\n let shape: string | undefined;\n records.forEach((record, index) => {\n // A list inside a list is not a record either; `[]` and `{}` are the same\n // empty record to PHP, so an empty array is an empty record here too.\n if (!record || typeof record !== 'object' || isList(record)) {\n throw badRequest(`record ${index} of a bulk create is not an object — each element is one record`, { index }, { code: 'bad_request' });\n }\n const fields = updateFields(record);\n if (fields.length === 0) {\n throw badRequest(`record ${index} of a bulk create has no field — ${EMPTY_CREATE_MESSAGE}`, { index }, { code: 'empty_create' });\n }\n const unknown = unknownFields(entity, record);\n if (unknown.length > 0) {\n const quoted = unknown.map((k) => `'${k}'`).join(', ');\n throw badRequest(\n `unknown field${unknown.length > 1 ? 's' : ''} ${quoted} in record ${index} — not a column of '${entity.name}'. ` +\n 'A field that cannot be written is refused rather than dropped; see details.allowed.',\n { index, unknown, allowed: writableColumns(entity) },\n { code: 'unknown_field' },\n );\n }\n const key = [...fields].sort().join('\\u0000');\n if (shape === undefined) shape = key;\n else if (key !== shape) {\n throw badRequest(\n `record ${index} of a bulk create names other fields than record 0 — every record of a bulk create names the same fields`,\n { index },\n { code: 'bad_request' },\n );\n }\n });\n return records as Row[];\n}\n\n/** The refusal for a list where one record belongs. */\nexport function oneRecordRefusal() {\n return badRequest(ONE_RECORD_MESSAGE, undefined, { code: 'bad_request' });\n}\n\n/**\n * Throw a 400 `unknown_field` when a write carries a key that is not a column.\n * Refused, never dropped: dropping would turn a caller's mistake into lost\n * data with no signal. A list is refused first (`assertOneRecord`).\n */\nexport function assertKnownFields(entity: WriteShape, data: unknown): void {\n assertOneRecord(entity, data);\n const unknown = unknownFields(entity, data);\n if (unknown.length === 0) return;\n const quoted = unknown.map((k) => `'${k}'`).join(', ');\n throw badRequest(\n `unknown field${unknown.length > 1 ? 's' : ''} ${quoted} — not a column of '${entity.name}'. ` +\n 'A field that cannot be written is refused rather than dropped; see details.allowed.',\n { unknown, allowed: writableColumns(entity) },\n { code: 'unknown_field' },\n );\n}\n\n/*\n * ---------------------------------------------------------------------------\n * A record read and sent back: the round trip every edit form makes.\n * ---------------------------------------------------------------------------\n *\n * A read answers fields no caller sets: the primary key and `tenant_id` (the\n * store's), `created_at` and `updated_at` (the clock's), the trash columns (the\n * trash routes'), and the stored generated columns (the database's). An edit\n * form changes one field and sends the whole row back, so a write naming them\n * is the ordinary case, not a mistake. The data plane refused it: `id` and\n * `tenant_id` have no UPDATE grant (42501, which reaches a caller as a 401 that\n * names nothing), and Postgres refuses any value for a generated column.\n *\n * So the key and the tenant are dropped when they say what the record already\n * says, and refused with `400 store_owned_field` when they say something else\n * — a body naming another record is a mistake worth reporting, not one to apply\n * to the record in the path. A generated column is dropped whatever it says:\n * the database computes it, and a read a concurrent write overtook carries an\n * older value. `updated_at` is dropped too — Baseline's trigger stamps it on\n * every write — unless it is the only field sent: that is a touch, and the\n * write is what makes the trigger stamp it. `created_at` is dropped when it\n * names the stored instant and written otherwise (a correction; it is granted).\n * Columns the App names in `mountCrud`'s `readOnly` are dropped when they repeat\n * the stored value and refused with `400 read_only_field` otherwise.\n *\n * When nothing is left, nothing is written: the caller is answered the record\n * as it stands, and no update event fires. A body that was empty to begin with\n * (`{}`) is still `400 empty_update` — that is a request with nothing in it,\n * not a record sent back.\n */\n\n/** The code of a refusal of a field the store assigns: the key, the tenant. */\nexport const STORE_OWNED_FIELD = 'store_owned_field';\n/** The code of a refusal of a field no write may change. */\nexport const READ_ONLY_FIELD = 'read_only_field';\n\n/** Stamped by Baseline on every write: dropped from an update, unless it is all the update sends (a touch). */\nexport const STORE_STAMPED_COLUMNS: readonly string[] = ['updated_at'];\n/** Stamped when the record is created: dropped when an update repeats it, written when it corrects it. */\nexport const CREATION_STAMP_COLUMNS: readonly string[] = ['created_at'];\n\n/**\n * The trash columns a live record reads as `null`. `purge_at` is not a column\n * the trash flag adds — Apps that show a purge date declare it — but a read of\n * a live record carries it as `null` like the others.\n */\nexport const TRASH_ROUND_TRIP_COLUMNS: readonly string[] = [...TRASH_FLAG_COLUMNS, 'purge_at'];\n\n/** The parts of an entity descriptor the round-trip rules read. */\nexport interface RoundTripShape {\n pk?: string;\n columns?: Record<string, unknown>;\n}\n\n/** What the round trip compares a write against. */\nexport interface RoundTripOptions {\n /** The record as it is now; read once, only when a rule needs it. */\n stored: () => Promise<Row | null> | Row | null;\n /** Columns the App declares as its own (never written by a caller), compared like a generated column. */\n readOnly?: readonly string[];\n}\n\n/** Thrown inside `roundTripped` when the stored record is not there; turned into its answer by the caller. */\nexport class RecordGone extends Error {\n constructor() {\n super('the record is not there');\n this.name = 'RecordGone';\n }\n}\n\n/** null, undefined and '' are no value for a key or a tenant. */\nconst noValue = (v: unknown): boolean => v === null || v === undefined || v === '';\nconst has = (row: Row, key: string): boolean => Object.prototype.hasOwnProperty.call(row, key) && row[key] !== undefined;\nconst nullish = (v: unknown): boolean => v === null || v === undefined;\nconst DECIMAL = /^([+-]?)(\\d*)(?:\\.(\\d*))?$/;\nconst NUMERIC_TYPE = /^(?:(?:small|big)?int(?:eger)?|int[248]|(?:big|small)?serial|serial[248]|numeric|decimal|real|double|float[48]?)\\b/i;\nconst INSTANT = /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}/;\n\n/** Two timestamps are the same instant, whatever offset or precision either is written in. */\nexport function sameInstant(a: unknown, b: unknown): boolean {\n if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);\n if (String(a) === String(b)) return true;\n if (typeof a !== 'string' || typeof b !== 'string' || !INSTANT.test(a) || !INSTANT.test(b)) return false;\n const x = Date.parse(a);\n const y = Date.parse(b);\n return Number.isFinite(x) && Number.isFinite(y) && x === y;\n}\n\n/**\n * A number written as a plain decimal, normalised exactly — sign, no leading\n * zeros, no trailing fraction zeros — so `5`, `\"5.000\"` and `\"+05\"` agree and a\n * big integer is never rounded through a float. `null` when it is not one.\n */\nfunction decimal(v: unknown): string | null {\n const text = typeof v === 'number' ? (Number.isFinite(v) ? String(v) : '') : typeof v === 'string' ? v.trim() : '';\n const m = DECIMAL.exec(text);\n if (!m || (m[2] === '' && (m[3] ?? '') === '')) return null;\n const whole = m[2]!.replace(/^0+(?=\\d)/, '') || '0';\n const fraction = (m[3] ?? '').replace(/0+$/, '');\n const digits = fraction ? `${whole}.${fraction}` : whole;\n return digits === '0' ? '0' : `${m[1] === '-' ? '-' : ''}${digits}`;\n}\n\n/** Whether a column type compares by number (`int`, `bigint`, `numeric(14,3)`, `real`, …). */\nexport function isNumericType(type: unknown): boolean {\n return NUMERIC_TYPE.test(String(type ?? '').trim());\n}\n\n/**\n * Two values are the same, compared as a read answers them: documents by their\n * JSON, timestamps by instant, a column of a numeric type by number — exactly,\n * so `\"007\"` and `7` agree only there and a big integer is never rounded —\n * and the rest as text.\n */\nexport function sameValue(a: unknown, b: unknown, type?: unknown): boolean {\n if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);\n if (typeof a === 'object' || typeof b === 'object') return canonical(a) === canonical(b);\n if (String(a) === String(b)) return true;\n if (isNumericType(type)) {\n const x = decimal(a);\n const y = decimal(b);\n if (x !== null && y !== null) return x === y;\n // An exponent (1e21) is no plain decimal; compare it as a float.\n const fx = Number(a);\n const fy = Number(b);\n return Number.isFinite(fx) && Number.isFinite(fy) && fx === fy;\n }\n return sameInstant(a, b);\n}\n\n/**\n * JSON with object keys sorted, so key order does not make two documents\n * differ. An empty object is written as an empty list: PHP decodes `{}` and\n * `[]` to the same array, so both runtimes count them as one document.\n */\nfunction canonical(v: unknown): string {\n return JSON.stringify(v, (_k, value: unknown) => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return value;\n const keys = Object.keys(value as object);\n return keys.length === 0 ? [] : Object.fromEntries(keys.sort().map((k) => [k, (value as Row)[k]]));\n });\n}\n\n/** The primary key column of an entity (`id` when the descriptor does not say). */\nexport function pkOf(entity: RoundTripShape | undefined): string {\n return entity?.pk || 'id';\n}\n\n/** Whether a column is declared, or the entity carries no column metadata to say. */\nfunction declares(entity: RoundTripShape, column: string): boolean {\n const columns = entity.columns;\n return !columns || Object.keys(columns).length === 0 || Object.prototype.hasOwnProperty.call(columns, column);\n}\n\n/** The stored generated columns of an entity (`generated` in schema.json). */\nexport function generatedColumns(entity: RoundTripShape | undefined): string[] {\n return Object.entries(entity?.columns ?? {})\n .filter(([, def]) => !!def && typeof def === 'object' && !!(def as { generated?: unknown }).generated)\n .map(([name]) => name)\n .sort();\n}\n\n/**\n * Whether the store assigns an entity's key on create: a `serial` / `bigserial`\n * key, or one whose default is `gen_random_uuid()`. Baseline grants no INSERT\n * on such a key. A key without a default (a natural text key) is the caller's.\n */\nexport function storeAssignsKey(entity: RoundTripShape | undefined): boolean {\n const def = entity?.columns?.[pkOf(entity)] as { type?: unknown; default?: unknown } | undefined;\n if (!def || typeof def !== 'object') return false;\n if (/^(big)?serial\\b/i.test(String(def.type ?? ''))) return true;\n return /gen_random_uuid/i.test(String(def.default ?? ''));\n}\n\nconst storeOwned = (field: string, message: string) =>\n badRequest(message, { field, fields: [field] }, { code: STORE_OWNED_FIELD });\n\nconst readOnly = (field: string, what: string) =>\n badRequest(\n `'${field}' is ${what} and cannot be changed by a write — send it as read, or leave it out`,\n { field, fields: [field] },\n { code: READ_ONLY_FIELD },\n );\n\nconst TENANT_CHANGED = \"'tenant_id' cannot be changed: a record stays in the tenant it was written under\";\n\n/**\n * The write an update makes of a record sent back: `patch` without the fields\n * that say what the record already says, refusing the ones that say something\n * else.\n *\n * - the primary key: equal to `id` (the record in the path) → dropped; another\n * value → `400 store_owned_field`; `null` / `''` → dropped.\n * - `tenant_id`: equal to the record's → dropped; another value →\n * `400 store_owned_field`; `null` / `''` → dropped. A record that does not\n * carry its tenant cannot be compared, and the value is dropped — the data\n * plane writes the tenant itself, so dropping never moves a record.\n * - `updated_at`: dropped — unless it is the only field left once the key and\n * the tenant are, which is a touch: the write goes out and Baseline's\n * trigger stamps the time.\n * - `created_at`: the same instant, in any offset → dropped; another instant\n * is written, as before (a correction).\n * - a stored generated column: always dropped — Postgres computes it.\n * - every column in `readOnly`: equal to the stored value → dropped; anything\n * else → `400 read_only_field`. Compared by the column's declared type.\n *\n * The timestamps are only treated so when the entity declares them (or carries\n * no column metadata): an undeclared key stays the field check's to refuse.\n * The stored record is read at most once, and only when a rule needs it; a\n * record that is not there throws `RecordGone`, which `update` answers `404`\n * and `updateIf` `null` — the answers each gives for it anyway.\n * The trash columns are not touched here: the trash routes write them through\n * the data client. `mountCrud` drops the null ones the stored record holds as\n * null too (`trashRoundTripped`).\n */\nexport async function roundTripped(entity: RoundTripShape, id: string | number, patch: Row, options: RoundTripOptions): Promise<Row> {\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return patch;\n const out: Row = { ...patch };\n let loaded = false;\n let current: Row | null = null;\n const stored = async (): Promise<Row> => {\n if (!loaded) {\n current = await options.stored();\n loaded = true;\n }\n if (!current) throw new RecordGone();\n return current;\n };\n\n const pk = pkOf(entity);\n if (has(out, pk)) {\n if (!noValue(out[pk]) && String(out[pk]) !== String(id)) {\n throw storeOwned(pk, `'${pk}' cannot be changed: the record is '${String(id)}'`);\n }\n delete out[pk];\n }\n if (has(out, 'tenant_id')) {\n if (!noValue(out.tenant_id)) {\n const tenant = (await stored()).tenant_id;\n if (!noValue(tenant) && String(out.tenant_id) !== String(tenant)) throw storeOwned('tenant_id', TENANT_CHANGED);\n }\n delete out.tenant_id;\n }\n // A patch of nothing but updated_at — once the key and the tenant that\n // repeat the record are gone — is a touch: the write is the point.\n const left = updateFields(out);\n const touch = left.length === 1 && STORE_STAMPED_COLUMNS.includes(left[0]!);\n for (const field of STORE_STAMPED_COLUMNS) {\n if (!touch && has(out, field) && declares(entity, field)) delete out[field];\n }\n for (const field of CREATION_STAMP_COLUMNS) {\n if (!has(out, field) || !declares(entity, field)) continue;\n if (sameInstant(out[field], (await stored())[field])) delete out[field];\n }\n const generated = generatedColumns(entity);\n for (const field of generated) delete out[field];\n for (const field of [...new Set(options.readOnly ?? [])].sort()) {\n if (!has(out, field) || generated.includes(field)) continue;\n const type = (entity.columns?.[field] as { type?: unknown } | undefined)?.type;\n if (!sameValue(out[field], (await stored())[field], type)) throw readOnly(field, 'kept by the app');\n delete out[field];\n }\n return out;\n}\n\n/**\n * The write a create makes of a body: the key and the tenant are the store's.\n *\n * - the primary key, when the store assigns it (`storeAssignsKey`): a value →\n * `400 store_owned_field`; `null` / `''` → dropped. A key the caller assigns\n * (no default) is written as before.\n * - `tenant_id`: another tenant than the request's → `400 store_owned_field`;\n * the request's tenant, `null` or `''` → dropped. Without a request tenant\n * to compare with the value is dropped — the data plane writes the tenant.\n */\nexport function createdFields(entity: RoundTripShape, body: Row, tenant: string | null | undefined): Row {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return body;\n const out: Row = { ...body };\n const pk = pkOf(entity);\n if (has(out, pk) && storeAssignsKey(entity)) {\n if (!noValue(out[pk])) throw storeOwned(pk, `'${pk}' is assigned by the store and cannot be sent on a create`);\n delete out[pk];\n }\n if (has(out, 'tenant_id')) {\n if (!noValue(out.tenant_id) && !noValue(tenant) && String(out.tenant_id) !== String(tenant)) {\n throw storeOwned('tenant_id', \"'tenant_id' is the tenant of the request and cannot name another\");\n }\n delete out.tenant_id;\n }\n return out;\n}\n\n/**\n * A body without its trash columns sent as `null` — for a create, where the new\n * record holds exactly that. A trash column with a value is left in place, for\n * `assertNoTrashFields` to refuse: only the trash routes move a record in or\n * out of the trash. An update compares against the stored record instead\n * (`trashRoundTripped`).\n */\nexport function withoutNullTrash(body: unknown): unknown {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return body;\n const row = body as Row;\n if (!TRASH_ROUND_TRIP_COLUMNS.some((k) => Object.prototype.hasOwnProperty.call(row, k) && row[k] === null)) return body;\n const out: Row = { ...row };\n for (const k of TRASH_ROUND_TRIP_COLUMNS) if (out[k] === null) delete out[k];\n return out;\n}\n\n/**\n * An update's body without the trash columns sent as `null` that the stored\n * record holds as `null` as well — what a live record reads. A `null` the\n * stored record does not hold (a record in the trash) is left in place, for\n * `assertNoTrashFields` to refuse: sent to a mounted route it would restore the\n * record past the trash routes. `purge_at`, which the trash flag does not add,\n * is left to be written as before.\n */\nexport function trashRoundTripped(body: unknown, stored: Row): unknown {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return body;\n const out: Row = { ...(body as Row) };\n for (const k of TRASH_ROUND_TRIP_COLUMNS) {\n if (Object.prototype.hasOwnProperty.call(out, k) && out[k] === null && nullish(stored[k])) delete out[k];\n }\n return out;\n}\n"],"mappings":";AA0BO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,gBAAgB;AAAA,EAEzB,YAAY,QAAgB,SAAiB,SAAmB,UAA4B,CAAC,GAAG;AAC9F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,QAAI,YAAY,OAAW,MAAK,UAAU;AAC1C,QAAI,QAAQ,SAAS,OAAW,MAAK,OAAO,QAAQ;AACpD,QAAI,QAAQ,iBAAiB,OAAW,MAAK,eAAe,QAAQ;AAAA,EACtE;AACF;AAGO,SAAS,YAAY,KAAgC;AAC1D,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,IAAI;AACV,SAAO,EAAE,kBAAkB,QAAS,EAAE,SAAS,eAAe,OAAO,EAAE,WAAW;AACpF;AAMO,IAAM,WAAW,CAAC,UAAU,aAAa,UAA4B,CAAC,MAC3E,IAAI,UAAU,KAAK,SAAS,QAAW,EAAE,MAAM,aA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K,GAAG,MAAM,GAAG,IAAI;AAE/G,oBAAM,QAAQ,CAAC,MAAe,OAAwB;AACpD,oBAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,KAAK,OAAO,IAAI,EAAG,QAAO;AACrF,sBAAM,MAA+B,EAAE,GAAI,KAAiC;AAC5E,oBAAI,IAAI,eAAe,OAAW,KAAI,aAAa;AACnD,oBAAI,gBAAgB,WAAW,IAAI,eAAe,OAAW,KAAI,aAAa;AAC9E,uBAAO;AAAA,cACT;AACA,kBAAI,QAAQ,cAAc;AAGxB,uBAAO,CAAC,SAAkB,SAAoB;AAC5C,sBAAI,CAAC,UAAU,KAAK,CAAC,MAAM,QAAQ,IAAI,EAAG,QAAO,KAAK,MAAM,IAAI;AAChE,wBAAM,KAAK,IAAI;AACf,yBAAO,KAAK,KAAK,IAAI,CAAC,WAAW,MAAM,QAAQ,EAAE,CAAC,GAAG,IAAI;AAAA,gBAC3D;AAAA,cACF;AACA,qBAAO,CAAC,SAAkB,SAAqB,UAAU,IAAI,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,IAAI,IAAI,KAAK,MAAM,IAAI;AAAA,YAC/G;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AACA,aAAO,QAAQ,IAAI,IAAI;AAAA,IACzB;AAAA,EACF,CAAC;AACH;","names":["now"]}
@@ -31,6 +31,16 @@ interface ColumnDef {
31
31
  notNull?: boolean;
32
32
  default?: string | null;
33
33
  check?: string;
34
+ /**
35
+ * schema.json `generated`: a stored computed column. Postgres computes it on
36
+ * every write and refuses a value for it; a write that repeats the stored
37
+ * value is dropped, any other refused (`read_only_field`).
38
+ */
39
+ generated?: {
40
+ expression: string;
41
+ stored?: boolean;
42
+ } | null;
43
+ [key: string]: unknown;
34
44
  }
35
45
  /** A generated entity descriptor: maps an App entity to its real table + ops. */
36
46
  interface Entity {
@@ -31,6 +31,16 @@ interface ColumnDef {
31
31
  notNull?: boolean;
32
32
  default?: string | null;
33
33
  check?: string;
34
+ /**
35
+ * schema.json `generated`: a stored computed column. Postgres computes it on
36
+ * every write and refuses a value for it; a write that repeats the stored
37
+ * value is dropped, any other refused (`read_only_field`).
38
+ */
39
+ generated?: {
40
+ expression: string;
41
+ stored?: boolean;
42
+ } | null;
43
+ [key: string]: unknown;
34
44
  }
35
45
  /** A generated entity descriptor: maps an App entity to its real table + ops. */
36
46
  interface Entity {