@revenexx/app-sdk 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -466,6 +466,84 @@ country: its own sender address when it has one, else `c.market.country`.
466
466
  An App calling another App through the gateway sends `X-Revenexx-Market` on;
467
467
  the gateway sets the country on that hop again.
468
468
 
469
+ ## Backdating
470
+
471
+ A test tenant can replay history into an App: a request carries a past moment
472
+ and the whole request runs on that clock, so a simulated year of orders lands
473
+ on its real dates instead of on the afternoon the simulator ran. Off unless the
474
+ App opts in, and then only for a tenant that switched it on.
475
+
476
+ ```js
477
+ const { createApp, backdatingDb, now } = require('@revenexx/app-sdk/router');
478
+ const { createDb, ENTITIES } = require('./db.generated');
479
+
480
+ const db = backdatingDb(createDb(), ENTITIES); // stamps created_at on backdated creates
481
+ const app = createApp({
482
+ name: 'orders',
483
+ settings: { defaults: { allow_backdating: false } },
484
+ backdating: {
485
+ routes: { 'POST /orders/place': ['placed_at'] }, // read first, then `at`
486
+ exclude: ['POST /orders/sync'], // never backdated
487
+ },
488
+ });
489
+
490
+ app.post('/orders/place', async (c) => {
491
+ const order = await db.orders.create({ ...fields, placed_at: c.now() });
492
+ // created_at = the moment, too
493
+ });
494
+ ```
495
+
496
+ - **Which routes.** `backdating: true` lets every POST, PUT, PATCH and DELETE
497
+ route accept `at` in its body. `routes` names extra fields per route
498
+ (`'METHOD /template'` exactly as registered), read in order, with `at`
499
+ appended last when the list leaves it out; a GET named there is backdatable
500
+ too. `exclude` wins over both.
501
+ - **The gate.** The moment is honoured only when the `x-revenexx-tenant`
502
+ header equals the `tenant_id` claim of the forwarded identity token
503
+ (`x-revenexx-context`) **and** that tenant's `allow_backdating` setting,
504
+ read through `c.settings()`, is `true` — or the text `"true"`, which some
505
+ settings stores hand back. Nothing else opens it. Settings that cannot be
506
+ read are the declared defaults, so unreadable means off. The claim is
507
+ decoded, not verified; the data plane verifies the token on every write.
508
+ Without the gate the field is ignored: unread, unvalidated, no refusal.
509
+ - **Validation.** With the gate, the moment must be an ISO 8601 date-time with
510
+ a zone, not in the future and at most `MAX_MONTHS_BACK` (24) months back.
511
+ Anything else is `400 backdating_invalid` with `details.field`.
512
+ - **The clock.** `c.now()` (ISO string) and `c.clock()` (Date) on the route
513
+ context, and `now()` / `clock()` / `backdated()` anywhere below a handler,
514
+ answer the moment for the whole request, across every `await`. Outside a
515
+ backdated request they are the wall clock, so App code can use them
516
+ unconditionally. `runAt(at, fn)` sets the same clock outside a route (a
517
+ replay job, a test). One clock serves both entry points.
518
+ - **Created rows.** The SDK does not own the generated client, so wrap it:
519
+ `backdatingDb(db, ENTITIES)` stamps `created_at` (and `updated_at`, when the
520
+ entity has it) on every `create` inside a backdated request and keeps a value
521
+ the caller set. Outside one it adds nothing; the database default stamps the
522
+ row.
523
+ - **The body.** Left as it came. `at` is a reserved body field in an App that
524
+ opts in; when a handler spreads its body into a row, pass `strip: true` and
525
+ the moment's fields are removed from `c.body` on a backdated request.
526
+
527
+ Every App that opts in declares the setting in its `settings.json`:
528
+
529
+ ```json
530
+ "allow_backdating": {
531
+ "title": { "en": "Allow backdating", "de": "Rückdatierung erlauben" },
532
+ "description": {
533
+ "en": "Lets a request carry a past timestamp, so test data or a replay lands on its real date. Meant for test tenants; leave it off for a live shop.",
534
+ "de": "Erlaubt einem Aufruf, einen vergangenen Zeitpunkt mitzugeben, damit Testdaten oder ein Replay auf ihrem echten Datum landen. Für Testmandanten gedacht; in einem Live-Shop ausgeschaltet lassen."
535
+ },
536
+ "type": "boolean",
537
+ "scope": "tenant",
538
+ "default": false,
539
+ "group": "testing"
540
+ }
541
+ ```
542
+
543
+ and `allow_backdating: false` in the defaults it hands `createApp`. Leave out
544
+ `group` in a `settings.json` that uses no groups. The promise is
545
+ [`specs/backdating.md`](../../specs/backdating.md).
546
+
469
547
  ## Record history
470
548
 
471
549
  The gateway may send a signed, short-lived envelope as `X-Revenexx-Audit` naming
@@ -475,6 +553,16 @@ record history. There is nothing to do in an App: the SDK never reads it, `c.act
475
553
  does not change, and a call without one is attributed to the token's subject as
476
554
  before. Configuring the `remote` adapter by hand, pass it as `audit`.
477
555
 
556
+ A client may also say what a change is and why in `X-Revenexx-Audit-Note`
557
+ (URI-encoded JSON `{"title":"…","reason":"…"}`; the Cockpit sends it when an
558
+ operator rolls a record back). The gateway passes it to the App and the `runtime`
559
+ adapter passes it on with every request, so Baseline stores it with the history
560
+ entry of each write. It is descriptive only and never decides who is acting. A
561
+ note longer than 8192 bytes, or not one line of printable ASCII, is dropped and
562
+ the call proceeds. To describe a change the App makes on its own, pass
563
+ `auditNote` to the client (`createClient({ adapter: 'runtime', context, auditNote })`);
564
+ an empty string sends none. The `remote` adapter takes it as `auditNote` too.
565
+
478
566
  ## App settings
479
567
 
480
568
  An App declares the knobs a merchant may turn in `settings.json`; the Cockpit
@@ -233,11 +233,11 @@ function createSettings(options = {}) {
233
233
  if (!app) return fallback("", tenant, market, "no app name (pass `app` or set REVENEXX_APP_NAME)");
234
234
  if (!tenant) return fallback(app, "", market, "no tenant on the request");
235
235
  const key = `${tenant}\0${app}\0${market ?? ""}`;
236
- const now = Date.now();
236
+ const now2 = Date.now();
237
237
  const hit = cache.get(key);
238
- if (hit && now - hit.at < hit.ttl) return hit.promise;
238
+ if (hit && now2 - hit.at < hit.ttl) return hit.promise;
239
239
  const token = (source?.contextToken ?? "") || headerOf(source, "x-revenexx-context");
240
- const entry = { at: now, ttl: ttlMs, promise: void 0 };
240
+ const entry = { at: now2, ttl: ttlMs, promise: void 0 };
241
241
  entry.promise = request(app, tenant, token, market).then((snapshot) => {
242
242
  lastGood.set(key, snapshot);
243
243
  return snapshot;
@@ -265,6 +265,126 @@ function createSettings(options = {}) {
265
265
  };
266
266
  }
267
267
 
268
+ // src/backdating.ts
269
+ import { AsyncLocalStorage } from "async_hooks";
270
+ var MAX_MONTHS_BACK = 24;
271
+ var BACKDATING_SETTING = "allow_backdating";
272
+ var BACKDATING_FIELD = "at";
273
+ var BACKDATING_INVALID = "backdating_invalid";
274
+ var BACKDATING_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
275
+ var STORE_KEY = /* @__PURE__ */ Symbol.for("@revenexx/app-sdk/backdating-clock");
276
+ function clockStorage() {
277
+ const g = globalThis;
278
+ let storage = g[STORE_KEY];
279
+ if (!storage) {
280
+ storage = new AsyncLocalStorage();
281
+ g[STORE_KEY] = storage;
282
+ }
283
+ return storage;
284
+ }
285
+ var CLOCK = clockStorage();
286
+ var now = () => CLOCK.getStore()?.at ?? (/* @__PURE__ */ new Date()).toISOString();
287
+ var clock = () => new Date(now());
288
+ var backdated = () => Boolean(CLOCK.getStore()?.at);
289
+ function runAt(at, fn) {
290
+ return at ? CLOCK.run({ at }, fn) : fn();
291
+ }
292
+ var ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})$/;
293
+ var invalid = (field, message) => new HttpError(400, `'${field}' ${message}`, { field }, { code: BACKDATING_INVALID });
294
+ function parseBackdate(field, value, reference = /* @__PURE__ */ new Date()) {
295
+ const text = typeof value === "string" ? value.trim() : "";
296
+ if (!ISO_DATE_TIME.test(text)) throw invalid(field, "must be an ISO 8601 date-time with a time zone");
297
+ const at = new Date(text);
298
+ if (Number.isNaN(at.getTime())) throw invalid(field, "must be an ISO 8601 date-time with a time zone");
299
+ if (at.getTime() > reference.getTime()) throw invalid(field, "must not be in the future");
300
+ const earliest = new Date(reference.getTime());
301
+ earliest.setUTCMonth(earliest.getUTCMonth() - MAX_MONTHS_BACK);
302
+ if (at.getTime() < earliest.getTime()) {
303
+ throw invalid(field, `must not be more than ${MAX_MONTHS_BACK} months back`);
304
+ }
305
+ return at.toISOString();
306
+ }
307
+ function tokenTenant(token) {
308
+ const parts = typeof token === "string" ? token.split(".") : [];
309
+ if (parts.length < 2) return "";
310
+ try {
311
+ const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
312
+ const claims = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
313
+ return typeof claims?.tenant_id === "string" ? claims.tenant_id.trim() : "";
314
+ } catch {
315
+ return "";
316
+ }
317
+ }
318
+ function settingAllowsBackdating(value) {
319
+ return value === true || typeof value === "string" && value.trim().toLowerCase() === "true";
320
+ }
321
+ async function backdatingAllowed(c) {
322
+ const read = (name) => typeof c?.header === "function" ? String(c.header(name) ?? "").trim() : "";
323
+ const header = read("x-revenexx-tenant");
324
+ const claimed = tokenTenant(c?.contextToken || read("x-revenexx-context"));
325
+ if (!header || header !== claimed) return false;
326
+ if (typeof c?.settings !== "function") return false;
327
+ try {
328
+ const settings = await c.settings();
329
+ return settingAllowsBackdating(settings?.[BACKDATING_SETTING]);
330
+ } catch {
331
+ return false;
332
+ }
333
+ }
334
+ var present = (value) => value !== void 0 && value !== null && value !== "";
335
+ async function requestedMoment(c, fields) {
336
+ const body = c?.body;
337
+ if (!body || typeof body !== "object") return null;
338
+ const field = fields.find((f) => present(body[f]));
339
+ if (field === void 0) return null;
340
+ if (!await backdatingAllowed(c)) return null;
341
+ return parseBackdate(field, body[field]);
342
+ }
343
+ function backdatingFields(option, method, template) {
344
+ if (!option) return null;
345
+ const opts = option === true ? {} : option;
346
+ const key = `${method.toUpperCase()} ${template}`;
347
+ if (opts.exclude?.includes(key)) return null;
348
+ const named = opts.routes?.[key];
349
+ if (named) return named.includes(BACKDATING_FIELD) ? [...named] : [...named, BACKDATING_FIELD];
350
+ return BACKDATING_METHODS.includes(method.toUpperCase()) ? [BACKDATING_FIELD] : null;
351
+ }
352
+ function backdatingDb(db, entities) {
353
+ const wrapped = /* @__PURE__ */ new Map();
354
+ return new Proxy(db, {
355
+ get(target, prop, receiver) {
356
+ const value = Reflect.get(target, prop, receiver);
357
+ if (typeof prop !== "string") return value;
358
+ const columns = entities?.[prop]?.columns;
359
+ if (!columns || !("created_at" in columns) || !value || typeof value !== "object") return value;
360
+ const repo = value;
361
+ if (typeof repo.create !== "function") return value;
362
+ if (!wrapped.has(prop)) {
363
+ wrapped.set(
364
+ prop,
365
+ new Proxy(repo, {
366
+ get(r, key, rr) {
367
+ const member = Reflect.get(r, key, rr);
368
+ if (key !== "create" || typeof member !== "function") return member;
369
+ return (data, ...rest) => {
370
+ if (!backdated() || !data || typeof data !== "object" || Array.isArray(data)) {
371
+ return member.call(r, data, ...rest);
372
+ }
373
+ const at = now();
374
+ const row = { ...data };
375
+ if (row.created_at === void 0) row.created_at = at;
376
+ if ("updated_at" in columns && row.updated_at === void 0) row.updated_at = at;
377
+ return member.call(r, row, ...rest);
378
+ };
379
+ }
380
+ })
381
+ );
382
+ }
383
+ return wrapped.get(prop);
384
+ }
385
+ });
386
+ }
387
+
268
388
  // src/patch.ts
269
389
  var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
270
390
  function updateFields(patch) {
@@ -313,6 +433,19 @@ export {
313
433
  DEFAULT_SETTINGS_TTL_MS,
314
434
  DEFAULT_SETTINGS_ERROR_TTL_MS,
315
435
  DEFAULT_SETTINGS_TIMEOUT_MS,
316
- createSettings
436
+ createSettings,
437
+ MAX_MONTHS_BACK,
438
+ BACKDATING_SETTING,
439
+ BACKDATING_FIELD,
440
+ BACKDATING_INVALID,
441
+ now,
442
+ clock,
443
+ backdated,
444
+ runAt,
445
+ parseBackdate,
446
+ backdatingAllowed,
447
+ requestedMoment,
448
+ backdatingFields,
449
+ backdatingDb
317
450
  };
318
- //# sourceMappingURL=chunk-P6ZEOMKS.js.map
451
+ //# sourceMappingURL=chunk-D6QST6NV.js.map
@@ -0,0 +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.(${cond.join(',')})`);\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) ? `(${c.value.join(',')})` : 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/** 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: [ … ] }\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 * 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 /** 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 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/provenance. */\n load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;\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}\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 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: Array.isArray(body.masked) ? body.masked.filter((k): k is string => typeof k === 'string') : [],\n resolved: true,\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 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';\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 a\n * backdated request only. Default false: the body is left as it came. Set it\n * when a handler spreads its body into a row and no table has an `at` 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' || typeof member !== 'function') return member;\n return (data: unknown, ...rest: unknown[]) => {\n if (!backdated() || !data || typeof data !== 'object' || Array.isArray(data)) {\n return (member as (...a: unknown[]) => unknown).call(r, data, ...rest);\n }\n const at = now();\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 (member as (...a: unknown[]) => unknown).call(r, row, ...rest);\n };\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';\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/** 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"],"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,aAAa,GAAG,QAAQ,CAAC;AACnE,IAAM,aAAa,CAAC,UAAU,eAAe,SAAmB,UAA4B,CAAC,MA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F;AACF;","names":["now"]}
@@ -301,6 +301,114 @@ interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {
301
301
  */
302
302
  declare function createSettings<D extends SettingsDefaults = SettingsDefaults>(options?: SettingsOptions<D>): SettingsReader<D>;
303
303
 
304
+ /**
305
+ * Backdating — replaying history into a test tenant (RAD-311).
306
+ *
307
+ * A simulator fills a test tenant with months of orders, payments and stock
308
+ * movements. Everything an App stamps is "now", so without help the whole
309
+ * history would land on the afternoon the simulator ran. An App that opts in
310
+ * (`createApp({ backdating: true })`) lets a mutating request carry a past
311
+ * moment in its body (`at`, or a route's own field) and runs the WHOLE request
312
+ * on that clock: every `now()` the handler reads, every timestamp it writes,
313
+ * and — through `backdatingDb` — the `created_at` of every row it creates.
314
+ *
315
+ * Only for a tenant whose admin switched it on: the App setting
316
+ * `allow_backdating` (scope tenant, default off), read through `c.settings()`.
317
+ * A settings service that cannot be reached hands back the declared defaults,
318
+ * so an unreadable setting means off. The tenant has to be named twice and
319
+ * agree: the `x-revenexx-tenant` header AND the `tenant_id` claim of the
320
+ * forwarded identity token (`x-revenexx-context`). The header alone is not
321
+ * enough — a caller reaching the function URL directly can set it. The claim is
322
+ * not verified here; the data plane verifies the token on every read and write,
323
+ * so a token claiming another tenant writes nothing at all.
324
+ *
325
+ * Without the gate the field is ignored, unread and unvalidated. With it the
326
+ * moment must be an ISO 8601 date-time with a zone, not in the future and not
327
+ * more than `MAX_MONTHS_BACK` months back; anything else is a 400 with code
328
+ * `backdating_invalid`.
329
+ *
330
+ * The clock lives in an AsyncLocalStorage kept on `globalThis`, so the two
331
+ * entry points (`@revenexx/app-sdk` and `@revenexx/app-sdk/router`, separate
332
+ * bundles, each in ESM and CJS) read one and the same clock.
333
+ */
334
+ /** How far back a backdated request may reach, in months. */
335
+ declare const MAX_MONTHS_BACK = 24;
336
+ /** The App setting that opens backdating for a tenant. */
337
+ declare const BACKDATING_SETTING = "allow_backdating";
338
+ /** The body field every backdated route accepts. Reserved in Apps that opt in. */
339
+ declare const BACKDATING_FIELD = "at";
340
+ /** The refusal code of a moment that cannot be honoured. */
341
+ declare const BACKDATING_INVALID = "backdating_invalid";
342
+ /**
343
+ * `createApp({ backdating })`. `true` lets every mutating route (POST, PUT,
344
+ * PATCH, DELETE) accept `at`; the object form does the same and refines it.
345
+ */
346
+ interface BackdatingOptions {
347
+ /**
348
+ * Per-route body fields that carry the moment, in precedence order, keyed
349
+ * `METHOD /template` exactly as the route was registered:
350
+ * `{ 'POST /orders/place': ['placed_at', 'at'] }`. `at` is always accepted —
351
+ * appended last when the list does not name it. A route named here is
352
+ * backdatable whatever its method.
353
+ */
354
+ routes?: Record<string, readonly string[]>;
355
+ /** Routes (`METHOD /template`) that are never backdated. Wins over `routes`. */
356
+ exclude?: readonly string[];
357
+ /**
358
+ * Remove the moment's fields from `c.body` before the handler runs, on a
359
+ * backdated request only. Default false: the body is left as it came. Set it
360
+ * when a handler spreads its body into a row and no table has an `at` column.
361
+ */
362
+ strip?: boolean;
363
+ }
364
+ /** The request's clock as an ISO string: the backdated moment while one runs, the wall clock otherwise. */
365
+ declare const now: () => string;
366
+ /** The request's clock as a Date, for code that does arithmetic on it. */
367
+ declare const clock: () => Date;
368
+ /** True while a backdated request (or `runAt`) is running. */
369
+ declare const backdated: () => boolean;
370
+ /**
371
+ * Run `fn` on the clock `at` (a normalized ISO string). `null` runs it on the
372
+ * wall clock. Everything `fn` awaits sees the same clock. For a job outside a
373
+ * route — a replay worker — and for tests.
374
+ */
375
+ declare function runAt<T>(at: string | null | undefined, fn: () => T): T;
376
+ /**
377
+ * Check one requested moment and answer it normalized (UTC, `toISOString`).
378
+ * Throws a 400 `backdating_invalid` naming `field` when it is not an ISO 8601
379
+ * date-time with a zone, lies in the future, or lies more than
380
+ * `MAX_MONTHS_BACK` months back. `reference` is the wall clock to measure
381
+ * against (tests).
382
+ */
383
+ declare function parseBackdate(field: string, value: unknown, reference?: Date): string;
384
+ /** What the gate reads off a request: the router's route context fits. */
385
+ interface BackdatingSource {
386
+ header?(name: string): string;
387
+ contextToken?: string;
388
+ settings?(): Promise<Record<string, unknown>>;
389
+ }
390
+ /**
391
+ * Whether this request's tenant may backdate: the tenant header and the
392
+ * identity token's `tenant_id` claim name the same tenant, and that tenant's
393
+ * `allow_backdating` setting is on. Never throws; anything unreadable is false.
394
+ */
395
+ declare function backdatingAllowed(c: BackdatingSource): Promise<boolean>;
396
+ /** The part of an entity descriptor `backdatingDb` reads: does it have the column? */
397
+ interface BackdatingEntity {
398
+ columns?: Record<string, unknown>;
399
+ }
400
+ /**
401
+ * The data client, with `created_at` (and `updated_at`, when the entity has
402
+ * it) stamped on every row a backdated request creates. Outside a backdated
403
+ * request it changes nothing: the database default stamps the row as always.
404
+ * A value the caller set is kept. Only entities whose descriptor in `entities`
405
+ * declares a `created_at` column are touched; pass the generated `ENTITIES`.
406
+ *
407
+ * const { createDb, ENTITIES } = require('./db.generated');
408
+ * const db = backdatingDb(createDb(), ENTITIES);
409
+ */
410
+ declare function backdatingDb<T extends object>(db: T, entities: Record<string, BackdatingEntity | undefined>): T;
411
+
304
412
  /**
305
413
  * The one error representation every layer of the SDK agrees on.
306
414
  *
@@ -367,4 +475,4 @@ interface Refusal {
367
475
  */
368
476
  declare function refusalOf(err: unknown): Refusal | null;
369
477
 
370
- export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type Where as W, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type Refusal as l, type ResolvedSettings as m, type SettingsDefaults as n, type SettingsOptions as o, type SettingsReader as p, type SettingsSnapshot as q, type SettingsSource as r, createSettings as s, isHttpError as t, refusalOf as u, badRequest as v, conflict as w, forbidden as x, notFound as y };
478
+ export { type Adapter as A, type BackdatingEntity as B, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, refusalOf as G, HttpError as H, runAt as I, BACKDATING_FIELD as J, BACKDATING_INVALID as K, BACKDATING_SETTING as L, MAX_MONTHS_BACK as M, type BackdatingSource as N, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, backdatingAllowed as T, badRequest as U, conflict as V, type Where as W, forbidden as X, notFound as Y, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, type BackdatingOptions as e, DEFAULT_SETTINGS_ERROR_TTL_MS as f, DEFAULT_SETTINGS_TIMEOUT_MS as g, DEFAULT_SETTINGS_TTL_MS as h, type EmitTarget as i, type FilterOp as j, type HttpErrorOptions as k, type ReadOptions as l, type Refusal as m, type ResolvedSettings as n, type SettingsDefaults as o, type SettingsOptions as p, type SettingsReader as q, type SettingsSnapshot as r, type SettingsSource as s, backdated as t, backdatingDb as u, clock as v, createSettings as w, isHttpError as x, now as y, parseBackdate as z };
@@ -301,6 +301,114 @@ interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {
301
301
  */
302
302
  declare function createSettings<D extends SettingsDefaults = SettingsDefaults>(options?: SettingsOptions<D>): SettingsReader<D>;
303
303
 
304
+ /**
305
+ * Backdating — replaying history into a test tenant (RAD-311).
306
+ *
307
+ * A simulator fills a test tenant with months of orders, payments and stock
308
+ * movements. Everything an App stamps is "now", so without help the whole
309
+ * history would land on the afternoon the simulator ran. An App that opts in
310
+ * (`createApp({ backdating: true })`) lets a mutating request carry a past
311
+ * moment in its body (`at`, or a route's own field) and runs the WHOLE request
312
+ * on that clock: every `now()` the handler reads, every timestamp it writes,
313
+ * and — through `backdatingDb` — the `created_at` of every row it creates.
314
+ *
315
+ * Only for a tenant whose admin switched it on: the App setting
316
+ * `allow_backdating` (scope tenant, default off), read through `c.settings()`.
317
+ * A settings service that cannot be reached hands back the declared defaults,
318
+ * so an unreadable setting means off. The tenant has to be named twice and
319
+ * agree: the `x-revenexx-tenant` header AND the `tenant_id` claim of the
320
+ * forwarded identity token (`x-revenexx-context`). The header alone is not
321
+ * enough — a caller reaching the function URL directly can set it. The claim is
322
+ * not verified here; the data plane verifies the token on every read and write,
323
+ * so a token claiming another tenant writes nothing at all.
324
+ *
325
+ * Without the gate the field is ignored, unread and unvalidated. With it the
326
+ * moment must be an ISO 8601 date-time with a zone, not in the future and not
327
+ * more than `MAX_MONTHS_BACK` months back; anything else is a 400 with code
328
+ * `backdating_invalid`.
329
+ *
330
+ * The clock lives in an AsyncLocalStorage kept on `globalThis`, so the two
331
+ * entry points (`@revenexx/app-sdk` and `@revenexx/app-sdk/router`, separate
332
+ * bundles, each in ESM and CJS) read one and the same clock.
333
+ */
334
+ /** How far back a backdated request may reach, in months. */
335
+ declare const MAX_MONTHS_BACK = 24;
336
+ /** The App setting that opens backdating for a tenant. */
337
+ declare const BACKDATING_SETTING = "allow_backdating";
338
+ /** The body field every backdated route accepts. Reserved in Apps that opt in. */
339
+ declare const BACKDATING_FIELD = "at";
340
+ /** The refusal code of a moment that cannot be honoured. */
341
+ declare const BACKDATING_INVALID = "backdating_invalid";
342
+ /**
343
+ * `createApp({ backdating })`. `true` lets every mutating route (POST, PUT,
344
+ * PATCH, DELETE) accept `at`; the object form does the same and refines it.
345
+ */
346
+ interface BackdatingOptions {
347
+ /**
348
+ * Per-route body fields that carry the moment, in precedence order, keyed
349
+ * `METHOD /template` exactly as the route was registered:
350
+ * `{ 'POST /orders/place': ['placed_at', 'at'] }`. `at` is always accepted —
351
+ * appended last when the list does not name it. A route named here is
352
+ * backdatable whatever its method.
353
+ */
354
+ routes?: Record<string, readonly string[]>;
355
+ /** Routes (`METHOD /template`) that are never backdated. Wins over `routes`. */
356
+ exclude?: readonly string[];
357
+ /**
358
+ * Remove the moment's fields from `c.body` before the handler runs, on a
359
+ * backdated request only. Default false: the body is left as it came. Set it
360
+ * when a handler spreads its body into a row and no table has an `at` column.
361
+ */
362
+ strip?: boolean;
363
+ }
364
+ /** The request's clock as an ISO string: the backdated moment while one runs, the wall clock otherwise. */
365
+ declare const now: () => string;
366
+ /** The request's clock as a Date, for code that does arithmetic on it. */
367
+ declare const clock: () => Date;
368
+ /** True while a backdated request (or `runAt`) is running. */
369
+ declare const backdated: () => boolean;
370
+ /**
371
+ * Run `fn` on the clock `at` (a normalized ISO string). `null` runs it on the
372
+ * wall clock. Everything `fn` awaits sees the same clock. For a job outside a
373
+ * route — a replay worker — and for tests.
374
+ */
375
+ declare function runAt<T>(at: string | null | undefined, fn: () => T): T;
376
+ /**
377
+ * Check one requested moment and answer it normalized (UTC, `toISOString`).
378
+ * Throws a 400 `backdating_invalid` naming `field` when it is not an ISO 8601
379
+ * date-time with a zone, lies in the future, or lies more than
380
+ * `MAX_MONTHS_BACK` months back. `reference` is the wall clock to measure
381
+ * against (tests).
382
+ */
383
+ declare function parseBackdate(field: string, value: unknown, reference?: Date): string;
384
+ /** What the gate reads off a request: the router's route context fits. */
385
+ interface BackdatingSource {
386
+ header?(name: string): string;
387
+ contextToken?: string;
388
+ settings?(): Promise<Record<string, unknown>>;
389
+ }
390
+ /**
391
+ * Whether this request's tenant may backdate: the tenant header and the
392
+ * identity token's `tenant_id` claim name the same tenant, and that tenant's
393
+ * `allow_backdating` setting is on. Never throws; anything unreadable is false.
394
+ */
395
+ declare function backdatingAllowed(c: BackdatingSource): Promise<boolean>;
396
+ /** The part of an entity descriptor `backdatingDb` reads: does it have the column? */
397
+ interface BackdatingEntity {
398
+ columns?: Record<string, unknown>;
399
+ }
400
+ /**
401
+ * The data client, with `created_at` (and `updated_at`, when the entity has
402
+ * it) stamped on every row a backdated request creates. Outside a backdated
403
+ * request it changes nothing: the database default stamps the row as always.
404
+ * A value the caller set is kept. Only entities whose descriptor in `entities`
405
+ * declares a `created_at` column are touched; pass the generated `ENTITIES`.
406
+ *
407
+ * const { createDb, ENTITIES } = require('./db.generated');
408
+ * const db = backdatingDb(createDb(), ENTITIES);
409
+ */
410
+ declare function backdatingDb<T extends object>(db: T, entities: Record<string, BackdatingEntity | undefined>): T;
411
+
304
412
  /**
305
413
  * The one error representation every layer of the SDK agrees on.
306
414
  *
@@ -367,4 +475,4 @@ interface Refusal {
367
475
  */
368
476
  declare function refusalOf(err: unknown): Refusal | null;
369
477
 
370
- export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type Where as W, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type Refusal as l, type ResolvedSettings as m, type SettingsDefaults as n, type SettingsOptions as o, type SettingsReader as p, type SettingsSnapshot as q, type SettingsSource as r, createSettings as s, isHttpError as t, refusalOf as u, badRequest as v, conflict as w, forbidden as x, notFound as y };
478
+ export { type Adapter as A, type BackdatingEntity as B, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, refusalOf as G, HttpError as H, runAt as I, BACKDATING_FIELD as J, BACKDATING_INVALID as K, BACKDATING_SETTING as L, MAX_MONTHS_BACK as M, type BackdatingSource as N, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, backdatingAllowed as T, badRequest as U, conflict as V, type Where as W, forbidden as X, notFound as Y, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, type BackdatingOptions as e, DEFAULT_SETTINGS_ERROR_TTL_MS as f, DEFAULT_SETTINGS_TIMEOUT_MS as g, DEFAULT_SETTINGS_TTL_MS as h, type EmitTarget as i, type FilterOp as j, type HttpErrorOptions as k, type ReadOptions as l, type Refusal as m, type ResolvedSettings as n, type SettingsDefaults as o, type SettingsOptions as p, type SettingsReader as q, type SettingsSnapshot as r, type SettingsSource as s, backdated as t, backdatingDb as u, clock as v, createSettings as w, isHttpError as x, now as y, parseBackdate as z };