@revenexx/app-sdk 1.4.0 → 1.6.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 +47 -6
- package/dist/{chunk-D6QST6NV.js → chunk-FMHCS3ZH.js} +87 -4
- package/dist/chunk-FMHCS3ZH.js.map +1 -0
- package/dist/{errors-DERK5sWS.d.cts → errors-CWT-wc8L.d.cts} +54 -3
- package/dist/{errors-DERK5sWS.d.ts → errors-CWT-wc8L.d.ts} +54 -3
- package/dist/index.cjs +86 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/router/index.cjs +100 -7
- package/dist/router/index.cjs.map +1 -1
- package/dist/router/index.d.cts +40 -10
- package/dist/router/index.d.ts +40 -10
- package/dist/router/index.js +24 -7
- package/dist/router/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-D6QST6NV.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/router/index.ts","../../src/instrument.ts","../../src/router/router.ts","../../src/router/actor.ts","../../src/router/market.ts","../../src/settings.ts","../../src/backdating.ts","../../src/errors.ts","../../src/patch.ts","../../src/query.ts","../../src/router/crud.ts","../../src/router/trash.ts"],"sourcesContent":["/**\n * @revenexx/app-sdk/router — declarative HTTP routing for revenexx App\n * functions. Pair with the generated data client for clean, testable handlers.\n */\n\n// Side effect: auto-start OpenTelemetry when OTEL_* env is configured. Runs in the\n// app's code context (where OTel deps resolve), so no NODE_OPTIONS preload is needed.\nimport '../instrument.js';\n\nexport {\n createApp,\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n} from './router.js';\nexport type {\n HttpErrorOptions,\n App,\n AppOptions,\n Handler,\n RouteContext,\n FnContext,\n FnRequest,\n FnResponse,\n} from './router.js';\n\n// Reading a refusal — this App's own, or another App's caught from the platform\n// client (`@revenexx/sdk`).\nexport { refusalOf } from '../errors.js';\nexport type { Refusal } from '../errors.js';\n\n// Who is acting. `createApp` reads it for you (`c.actor`); `actorFrom` is here\n// for code outside a handler that has the same headers in hand.\nexport { actorFrom, ACTOR_HEADERS } from './actor.js';\nexport type { Actor, ActorTrust, ActorPlane } from './actor.js';\n\n// The market a request is for and the country it ships from. `createApp`\n// reads it for you (`c.market`); `marketFrom` is here for code outside a\n// handler that has the same headers in hand.\nexport { marketFrom, MARKET_HEADERS } from './market.js';\nexport type { Market } from './market.js';\n\n// Backdating (RAD-311): `createApp({ backdating })` turns it on; the clock and\n// the data-client wrapper are here for handlers, helpers and jobs.\nexport {\n now,\n clock,\n backdated,\n runAt,\n parseBackdate,\n backdatingAllowed,\n backdatingDb,\n MAX_MONTHS_BACK,\n BACKDATING_SETTING,\n BACKDATING_FIELD,\n BACKDATING_INVALID,\n} from '../backdating.js';\nexport type { BackdatingOptions, BackdatingSource, BackdatingEntity } from '../backdating.js';\n\nexport { mountCrud, RESERVED_LIST_QUERY_KEYS } from './crud.js';\nexport type { CrudOptions, RepoLike } from './crud.js';\n\n// The trash (PE-1022): DELETE into the trash, DELETE again for good, restore,\n// and the purge job — one code path for the final delete.\nexport {\n mountTrash,\n createGatewayCounter,\n readTrashRetention,\n auditSettingsUrl,\n TRASH_COLUMN,\n PURGE_REASON_COLUMN,\n AUDIT_SETTINGS_PATH,\n DEFAULT_TRASH_RETENTION_DAYS,\n} from './trash.js';\nexport type {\n TrashOptions,\n TrashHandle,\n TrashChild,\n TrashCaller,\n Blocker,\n BlockerCheck,\n PurgeResult,\n RetentionOptions,\n} from './trash.js';\n\n// App settings. `createApp` builds a reader for you (`c.settings()`); create\n// one directly when code outside a handler needs the same values.\nexport {\n createSettings,\n DEFAULT_GATEWAY_ENDPOINT,\n DEFAULT_SETTINGS_TTL_MS,\n DEFAULT_SETTINGS_ERROR_TTL_MS,\n DEFAULT_SETTINGS_TIMEOUT_MS,\n} from '../settings.js';\nexport type {\n SettingsReader,\n SettingsOptions,\n SettingsSnapshot,\n SettingsSource,\n SettingsDefaults,\n ResolvedSettings,\n ReadOptions,\n} from '../settings.js';\n","/**\n * OpenTelemetry bootstrap for revenexx App functions.\n *\n * Loaded automatically as a side effect of importing `@revenexx/app-sdk/router`\n * (the app requires the router from its own code dir, so OTel deps resolve).\n * Do NOT preload via `NODE_OPTIONS=--require` in open-runtimes: that runs in the\n * runtime server's node process, which cannot resolve the app's node_modules and\n * crashes the runtime.\n *\n * Configuration is 100% standard `OTEL_*` env; with no OTLP endpoint set it is a\n * cheap no-op (the heavy OTel packages aren't even loaded):\n * OTEL_EXPORTER_OTLP_ENDPOINT https://traces.revenexx.com\n * OTEL_EXPORTER_OTLP_HEADERS Authorization=Basic <base64>\n * OTEL_SERVICE_NAME products\n * OTEL_RESOURCE_ATTRIBUTES service.namespace=revenue-cloud,deployment.environment=prod\n *\n * Lean: only outbound undici/fetch (the PostgREST data plane) is auto-instrumented.\n * The per-invocation SERVER span is added by the router (createApp).\n */\n\nlet started = false;\n\n/**\n * Start OpenTelemetry once. Safe to call repeatedly. NEVER throws — a telemetry\n * failure must not take the function down (a missing trace beats a dead runtime).\n */\nexport async function startTelemetry(): Promise<void> {\n if (started) {\n return;\n }\n started = true;\n\n const endpoint =\n process.env['OTEL_EXPORTER_OTLP_TRACES_ENDPOINT'] ?? process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? '';\n if (!endpoint) {\n return; // tracing disabled — don't even load the OTel packages\n }\n\n try {\n const [{ NodeSDK }, { OTLPTraceExporter }, { UndiciInstrumentation }] = await Promise.all([\n import('@opentelemetry/sdk-node'),\n import('@opentelemetry/exporter-trace-otlp-proto'),\n import('@opentelemetry/instrumentation-undici'),\n ]);\n\n // Exporter + resource (service.name, resource attrs) are read from OTEL_* env.\n const sdk = new NodeSDK({\n traceExporter: new OTLPTraceExporter(),\n instrumentations: [new UndiciInstrumentation()],\n });\n\n sdk.start();\n\n const flush = (): void => {\n void sdk.shutdown().catch(() => {\n /* best effort */\n });\n };\n process.once('SIGTERM', flush);\n process.once('SIGINT', flush);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n '[app-sdk] OpenTelemetry init failed, continuing without tracing:',\n err instanceof Error ? err.message : err,\n );\n }\n}\n\n// Auto-start on import (side effect). Fire-and-forget; never blocks or throws.\nvoid startTelemetry();\n","/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\nimport { actorFrom } from './actor.js';\nimport type { Actor } from './actor.js';\nimport { marketFrom } from './market.js';\nimport type { Market } from './market.js';\nimport { createSettings } from '../settings.js';\nimport { backdatingFields, clock as clockNow, now as nowIso, requestedMoment, runAt } from '../backdating.js';\nimport type { BackdatingOptions } from '../backdating.js';\nimport type {\n ReadOptions,\n ResolvedSettings,\n SettingsDefaults,\n SettingsOptions,\n SettingsReader,\n SettingsSnapshot,\n} from '../settings.js';\n\nexport interface FnRequest {\n method?: string;\n path?: string;\n url?: string;\n headers?: Record<string, string>;\n query?: Record<string, unknown>;\n body?: unknown;\n bodyText?: string;\n bodyRaw?: string;\n}\n\nexport interface FnResponse {\n json(data: unknown, statusCode?: number, headers?: Record<string, string>): unknown;\n send?(body: string, statusCode?: number, headers?: Record<string, string>): unknown;\n}\n\n/** The invocation context an App function receives from the runtime. */\nexport interface FnContext {\n req: FnRequest;\n res: FnResponse;\n log?: (message: string) => void;\n error?: (message: string) => void;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {\n /** Raw invocation context (escape hatch). */\n ctx: FnContext;\n req: FnRequest;\n method: string;\n /** Normalised path (no trailing slash, no query string). */\n path: string;\n /** Path parameters from the matched route template (e.g. `{id}`). */\n params: Record<string, string>;\n /** Query string parameters (string values). */\n query: Record<string, string>;\n /** Parsed JSON body, or `{}` when absent/unparsable. */\n body: Record<string, unknown>;\n /** Tenant slug from the `x-revenexx-tenant` header (or token claim). */\n tenant: string | null;\n /** The forwarded identity token (`x-revenexx-context`), if present. */\n contextToken: string;\n /**\n * Who is acting — the person behind this request, as the platform\n * established them (see ./actor.ts).\n *\n * `c.tenant` says whose data this is; this says whose hand is on it. Read\n * `c.actor.authenticated()` before enforcing a per-person rule, and\n * `c.actor.plane` to tell one of the tenant's contacts from a back-office\n * operator from a system caller. Never derive either from the context\n * token's claims: those describe the calling SYSTEM.\n */\n actor: Actor;\n /**\n * The market this request is for, and the country it ships from — both\n * set by the gateway (see ./market.ts). `country` is what a document\n * without a sender address of its own prints addresses for.\n */\n market: Market;\n /** Case-insensitive header lookup. */\n header(name: string): string;\n log(message: string): void;\n /** Respond with JSON. Returning `c.json(...)` ends the request. */\n json(data: unknown, statusCode?: number): unknown;\n /**\n * This tenant's effective settings for the app, resolved for the request's\n * market. Cached and fail-open — see `createSettings`. Available on every\n * app; pass `settings` to `createApp` to declare defaults and get them typed.\n */\n settings(options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/provenance. */\n settingsSnapshot(options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n /**\n * The request's clock as an ISO string — the backdated moment while a\n * backdated request runs, the wall clock otherwise (see `createApp`'s\n * `backdating`). Same as the exported `now()`.\n */\n now(): string;\n /** The request's clock as a Date. Same as the exported `clock()`. */\n clock(): Date;\n}\n\nexport type Handler<D extends SettingsDefaults = SettingsDefaults> = (\n c: RouteContext<D>,\n) => unknown | Promise<unknown>;\n\n// `HttpError` lives in ../errors.js so the data adapters can raise it too — a\n// PostgREST unique violation answers 409 without the router guessing from a\n// message string. Re-exported here so `@revenexx/app-sdk/router` is unchanged.\nexport {\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n type HttpErrorOptions,\n} from '../errors.js';\nimport { isHttpError, refusalBody, refusalOf } from '../errors.js';\n\ninterface Segment {\n lit?: string;\n param?: string;\n}\n\ninterface CompiledRoute<D extends SettingsDefaults> {\n method: string;\n template: string;\n segments: Segment[];\n literals: number;\n handler: Handler<D>;\n /** Body fields carrying a backdated moment, in precedence order; null = not backdatable. */\n backdating: string[] | null;\n}\n\nconst splitPath = (path: string): string[] => path.split('/').filter(Boolean);\n\nfunction compileTemplate(template: string): Segment[] {\n return splitPath(template).map((seg) => {\n const braced = /^\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/.exec(seg);\n if (braced) return { param: braced[1] };\n if (seg.startsWith(':') && seg.length > 1) return { param: seg.slice(1) };\n return { lit: seg };\n });\n}\n\nfunction matchSegments(segments: Segment[], reqSegs: string[]): Record<string, string> | null {\n if (segments.length !== reqSegs.length) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]!;\n if (s.param) params[s.param] = decodeURIComponent(reqSegs[i]!);\n else if (s.lit !== reqSegs[i]) return null;\n }\n return params;\n}\n\nfunction headerOf(headers: Record<string, string> | undefined, name: string): string {\n if (!headers) return '';\n const direct = headers[name] ?? headers[name.toLowerCase()];\n if (typeof direct === 'string') return direct;\n const want = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === want && typeof v === 'string') return v;\n }\n return '';\n}\n\nfunction decodeClaims(token: string): Record<string, unknown> {\n if (!token || token.split('.').length < 2) return {};\n try {\n const payload = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction parseBody(req: FnRequest): Record<string, unknown> {\n const candidate = req.body ?? req.bodyText ?? req.bodyRaw;\n if (candidate == null || candidate === '') return {};\n if (typeof candidate === 'object') return candidate as Record<string, unknown>;\n if (typeof candidate === 'string') {\n try {\n const parsed: unknown = JSON.parse(candidate);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/**\n * Request query, percent-DECODED exactly once.\n *\n * `req.path` carries the query string verbatim as the gateway forwarded it, so\n * it is the authoritative source: `URLSearchParams` decodes it once, correctly,\n * and treats `+` as a space the way a form-encoded query requires.\n *\n * The runtime's own `req.query` hands values through *undecoded*. A filter of\n * `?code=m%61in` arrived as the literal `m%61in` and matched nothing, when per\n * RFC 3986 it simply means `main`. That broke every filter value needing an\n * escape — spaces, `&`, `+`, `/`, commas, anything non-ASCII — so \"Müller & Co\"\n * could not be filtered for at all. It also let the gateway's response cache\n * merge two spellings the app answered differently (revenexx/api#32).\n *\n * `req.query` stays the fallback for callers that populate it without a query\n * string on the path (the mock adapter and direct unit tests do this). Decoding\n * that again here would be wrong — a double decode turns `%2520` into a space —\n * so each source is decoded by exactly one owner.\n */\nfunction parseQuery(req: FnRequest): Record<string, string> {\n const out: Record<string, string> = {};\n const rawPath = String(req.path ?? '');\n const qmark = rawPath.indexOf('?');\n if (qmark >= 0) {\n for (const [k, v] of new URLSearchParams(rawPath.slice(qmark + 1))) out[k] = v;\n return out;\n }\n // The runtime hands `req.query` through UNDECODED — measured in production\n // against every one of the 13 apps after 0.6.0 shipped:\n //\n // GET /v1/customers/organizations?name=ACME%20GmbH\n // -> returned 0, filter {\"name\":\"ACME%20GmbH\"} (the row 'ACME GmbH' exists)\n //\n // 0.6.0 only decoded when the query rode on `req.path`, which this runtime\n // does not do, so the fix was inert. Decode here as well; each source is\n // still decoded exactly once, because the branch above returns.\n for (const [k, v] of Object.entries(req.query ?? {})) {\n const raw = typeof v === 'string' ? v : v == null ? null : String(v);\n if (raw !== null) out[decodeComponent(k)] = decodeComponent(raw);\n }\n return out;\n}\n\n/**\n * Percent-decode one query key or value, treating `+` as a space the way a\n * form-encoded query requires.\n *\n * Falls back to the input when it is not valid percent-encoding — a lone `%`\n * is a legitimate character in a search term, and throwing a URIError on it\n * would turn a harmless filter into a 500.\n */\nfunction decodeComponent(value: string): string {\n try {\n return decodeURIComponent(value.replace(/\\+/g, ' '));\n } catch {\n return value;\n }\n}\n\nexport interface AppOptions<D extends SettingsDefaults = SettingsDefaults> {\n /** App name reported on the built-in health route. */\n name?: string;\n /**\n * Built-in `GET /` health route (default true). Responds with the app\n * identity (from the runtime env), status and the registered routes.\n */\n health?: boolean;\n /** Extra payload merged into the health response. */\n healthExtra?: () => Record<string, unknown>;\n /**\n * App settings behind `c.settings()`. Pass the defaults your settings.json\n * declares — they type the resolved object and are what the app runs on if\n * the settings service is unreachable:\n *\n * createApp({ name: 'orders', settings: { defaults: { auto_reserve: true } } })\n *\n * `app` defaults to this app's `name`. Pass a reader built with\n * `createSettings` instead when you want to share it with code outside the\n * router. Omit entirely and `c.settings()` still works — it just has no\n * declared defaults to fall back on.\n */\n settings?: Omit<SettingsOptions<D>, 'app'> & { app?: string } | SettingsReader<D>;\n /**\n * Let a test tenant backdate requests (RAD-311). Off by default. `true`: every\n * POST/PUT/PATCH/DELETE route accepts a past moment as `at` in its body and\n * runs on that clock (`c.now()`, `now()`, `clock()`). The object form adds\n * per-route field aliases (`routes`), routes never backdated (`exclude`) and\n * `strip`. Honoured only when the tenant header matches the identity token's\n * `tenant_id` and the tenant's `allow_backdating` setting is on; otherwise\n * the field is ignored. Stamp created rows with `backdatingDb`.\n */\n backdating?: boolean | BackdatingOptions;\n}\n\nexport interface App<D extends SettingsDefaults = SettingsDefaults> {\n get(template: string, handler: Handler<D>): App<D>;\n post(template: string, handler: Handler<D>): App<D>;\n put(template: string, handler: Handler<D>): App<D>;\n patch(template: string, handler: Handler<D>): App<D>;\n delete(template: string, handler: Handler<D>): App<D>;\n on(method: string, template: string, handler: Handler<D>): App<D>;\n /** Registered routes (e.g. for docs or the health response). */\n routes(): { method: string; path: string }[];\n /** The settings reader backing `c.settings()` (e.g. to clear its cache). */\n settings: SettingsReader<D>;\n /** Build the function entrypoint: `module.exports = app.handler()`. */\n handler(): (context: FnContext) => Promise<unknown>;\n}\n\nconst isSettingsReader = <D extends SettingsDefaults>(\n value: NonNullable<AppOptions<D>['settings']>,\n): value is SettingsReader<D> => typeof (value as SettingsReader<D>).get === 'function';\n\nconst tracer = trace.getTracer('@revenexx/app-sdk');\n\n/** Case-insensitive W3C trace-context extraction from the function's headers. */\nconst headerGetter: TextMapGetter<Record<string, string>> = {\n keys: (carrier) => Object.keys(carrier ?? {}),\n get: (carrier, key) => headerOf(carrier, key) || undefined,\n};\n\nexport function createApp<D extends SettingsDefaults = SettingsDefaults>(options: AppOptions<D> = {}): App<D> {\n const routes: CompiledRoute<D>[] = [];\n const health = options.health !== false;\n const strip = typeof options.backdating === 'object' && options.backdating.strip === true;\n // The app knows its own name, so the settings reader does not have to be told\n // it. One reader per app, created once: the cache lives on it.\n const settings: SettingsReader<D> =\n options.settings && isSettingsReader(options.settings)\n ? options.settings\n : createSettings<D>({ app: options.name, ...(options.settings ?? {}) });\n\n const app: App<D> = {\n settings,\n get: (t, h) => app.on('GET', t, h),\n post: (t, h) => app.on('POST', t, h),\n put: (t, h) => app.on('PUT', t, h),\n patch: (t, h) => app.on('PATCH', t, h),\n delete: (t, h) => app.on('DELETE', t, h),\n on(method, template, handler) {\n const segments = compileTemplate(template);\n routes.push({\n method: method.toUpperCase(),\n template,\n segments,\n literals: segments.filter((s) => s.lit !== undefined).length,\n handler,\n backdating: backdatingFields(options.backdating, method, template),\n });\n // Literal-first: more literal segments = more specific = tried first.\n routes.sort((a, b) => b.literals - a.literals);\n return app;\n },\n routes: () => routes.map((r) => ({ method: r.method, path: r.template })).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)),\n handler() {\n return (context: FnContext) => {\n const { req, res } = context;\n const headers = req.headers ?? {};\n const method = (req.method ?? 'GET').toUpperCase();\n const rawPath = String(req.path ?? '/').split('?')[0]!;\n const path = rawPath.replace(/\\/+$/, '') || '/';\n\n // Continue the caller's trace (gateway/site) when a traceparent is forwarded;\n // otherwise this SERVER span roots a fresh trace. Outbound PostgREST fetches\n // become child CLIENT spans via the undici instrumentation (see ./instrument).\n const parentCtx = propagation.extract(otelContext.active(), headers, headerGetter);\n\n return tracer.startActiveSpan(\n `${method} ${path}`,\n { kind: SpanKind.SERVER, attributes: { 'http.request.method': method, 'url.path': path } },\n parentCtx,\n async (span: Span) => {\n const contextToken = headerOf(headers, 'x-revenexx-context');\n const tenant =\n headerOf(headers, 'x-revenexx-tenant') ||\n (decodeClaims(contextToken).tenant_id as string | undefined) ||\n null;\n if (options.name) span.setAttribute('revenexx.app', options.name);\n if (tenant) span.setAttribute('revenexx.tenant', tenant);\n const log = (m: string) => context.log?.(m);\n\n log(`${options.name ?? 'app'} ${method} ${path} — tenant=${tenant ?? 'none'}`);\n\n try {\n if (health && path === '/' && method === 'GET') {\n span.setAttribute('http.route', '/');\n return res.json({\n app: {\n id: process.env.REVENEXX_APP_ID ?? null,\n name: options.name ?? process.env.REVENEXX_APP_NAME ?? null,\n deployment: process.env.REVENEXX_APP_DEPLOYMENT ?? null,\n runtime: `${process.env.REVENEXX_APP_RUNTIME_NAME ?? ''}-${process.env.REVENEXX_APP_RUNTIME_VERSION ?? ''}`,\n },\n status: 'ok',\n routes: app.routes(),\n timestamp: new Date().toISOString(),\n ...(options.healthExtra?.() ?? {}),\n });\n }\n\n const reqSegs = splitPath(path);\n let matched: { route: CompiledRoute<D>; params: Record<string, string> } | null = null;\n let pathExists = false;\n for (const route of routes) {\n const params = matchSegments(route.segments, reqSegs);\n if (!params) continue;\n pathExists = true;\n if (route.method === method) {\n matched = { route, params };\n break;\n }\n }\n\n if (!matched) {\n const status = pathExists ? 405 : 404;\n span.setAttribute('http.response.status_code', status);\n span.setStatus({ code: SpanStatusCode.ERROR, message: pathExists ? 'method not allowed' : 'no route' });\n if (pathExists) {\n return res.json(refusalBody(`method ${method} not allowed for ${path}`, 'method_not_allowed'), 405);\n }\n return res.json({ ...refusalBody(`no route for ${method} ${path}`, 'no_route'), routes: app.routes() }, 404);\n }\n\n span.updateName(`${method} ${matched.route.template}`);\n span.setAttribute('http.route', matched.route.template);\n\n // Gateway-extracted params (x-capability-params) win over our own match\n // for safety, but they should always agree.\n let gatewayParams: Record<string, string> = {};\n try {\n gatewayParams = JSON.parse(headerOf(headers, 'x-capability-params') || '{}') as Record<string, string>;\n } catch {\n gatewayParams = {};\n }\n\n const c: RouteContext<D> = {\n ctx: context,\n req,\n method,\n path,\n params: { ...matched.params, ...gatewayParams },\n query: parseQuery(req),\n body: parseBody(req),\n tenant,\n contextToken,\n header: (name) => headerOf(headers, name),\n actor: actorFrom((name) => headerOf(headers, name)),\n market: marketFrom((name) => headerOf(headers, name)),\n log,\n json: (data, statusCode = 200) => res.json(data, statusCode),\n // The market rides on the request, so a market-scoped setting\n // resolves for the market this call is for — no argument needed.\n settings: (readOptions) => settings.get(c, readOptions),\n settingsSnapshot: (readOptions) => settings.load(c, readOptions),\n now: nowIso,\n clock: clockNow,\n };\n\n const fields = matched.route.backdating;\n if (!fields) return await matched.route.handler(c);\n // The gate (an async settings read) is resolved before the handler\n // starts, so the whole handler runs on one clock.\n const at = await requestedMoment(c, fields);\n if (at) {\n span.setAttribute('revenexx.backdated_at', at);\n if (strip) {\n const body = { ...c.body };\n for (const field of fields) delete body[field];\n c.body = body;\n }\n }\n const route = matched.route;\n return await runAt(at, () => route.handler(c));\n } catch (err) {\n if (isHttpError(err)) {\n span.setAttribute('http.response.status_code', err.status);\n if (err.code) span.setAttribute('revenexx.error.code', err.code);\n if (err.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n // The diagnosis (table names, constraint names, the raw\n // PostgREST body) stays on this side of the wire: logged and\n // traced, never serialised into the response.\n if (err.serverDetail !== undefined) {\n const detail =\n typeof err.serverDetail === 'string' ? err.serverDetail : JSON.stringify(err.serverDetail);\n span.setAttribute('revenexx.error.detail', detail);\n context.error?.(`${method} ${path} — ${err.status} ${err.message}: ${detail}`);\n }\n return res.json(refusalBody(err.message, err.code, err.details), err.status);\n }\n // Anything that is not an HttpError is a fault, not an answer: its\n // message may carry internals (a stack's TypeError, a table name),\n // so it is logged and traced, and the caller gets a fixed body.\n // Another App's refusal nobody caught: still a fault here, but log what\n // the far side said rather than the platform client's empty message.\n const upstream = refusalOf(err);\n const msg = upstream\n ? `refused by ${upstream.app ?? 'another app'}: ${upstream.status} ${upstream.code ?? ''} ${upstream.message}`.replace(/\\s+/g, ' ')\n : err instanceof Error\n ? err.message\n : String(err);\n span.setAttribute('http.response.status_code', 500);\n span.recordException(err instanceof Error ? err : new Error(msg));\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n context.error?.(`unhandled error on ${method} ${path}: ${msg}`);\n return res.json(refusalBody('internal error', 'internal_error'), 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * Who is acting — the person behind a request, as the platform established\n * them.\n *\n * An app has always been told which TENANT a call is for. Which PERSON was a\n * different question, and for a long time it had no answer: the brokered\n * context identifies the calling system (in a theme site, the theme's service\n * user — a robot with no name), the gateway strips inbound identity headers\n * because they are forgeable, and anything in the request body is the caller's\n * own word about itself. Apps that needed a person resolved one out of the\n * context's email claim and hoped, or read an `_actor` out of the body and\n * called it attribution rather than authentication, because that is all it was.\n *\n * The gateway now states it (RAD-12), on two planes:\n *\n * - ASSERTED. A storefront call is made by a server — the theme BFF, holding\n * the tenant API key — on behalf of a customer. The credential proves the\n * tenant, so the caller names the person and the gateway resolves that name\n * through the tenant's role provider. It defends against a malicious end\n * user, not against a compromised BFF.\n * - AUTHENTICATED. A Cockpit call, or any call carrying a person's own\n * Zitadel token, needs nobody's word: the signature and issuer were\n * verified before a route was matched, and the contact — if there is one —\n * was resolved from that proven subject.\n *\n * Both arrive in the same headers, which is exactly why `trust` exists. The\n * same `contact` is a signature on one plane and a label on the other, and an\n * app deciding an approval has to be able to tell the two apart. An app that\n * only attributes — a \"last edited by\" — can ignore it.\n *\n * Every header read here is set ONLY by the gateway: it builds a fresh header\n * set per dispatch and strips any copy a caller sent. So `actor.trust` cannot\n * be talked up from outside, and an app never has to decide whether to believe\n * a header — only what to do with what it says.\n */\n\n/** How the platform came to know who is acting. */\nexport type ActorTrust = 'authenticated' | 'asserted' | 'none';\n\n/**\n * Which side of the platform the caller is on.\n *\n * - `contact` — one of the tenant's own people: a buyer, an approver.\n * - `operator` — a human the PLATFORM knows and the tenant's records do not.\n * Back office: Cockpit staff, support, a partner operating the tenant. There\n * is no contact to check a per-row rule against, and that absence is the\n * signal, not a failure to resolve one.\n * - `system` — nobody: a schedule, a webhook, a service token, an in-mesh call.\n *\n * This is the distinction apps otherwise make by hand, badly — usually by\n * treating \"no contact resolved\" as \"must be the platform\", which is also what\n * an unknown customer looks like.\n */\nexport type ActorPlane = 'contact' | 'operator' | 'system';\n\n/** The acting person, as far as the platform can state it. */\nexport interface Actor {\n /** The authenticated human's platform subject, or null when none was proven. */\n user: string | null;\n /** Their email claim, or null. Attribution — never a lookup key to trust on its own. */\n email: string | null;\n /** The `customers` contact the platform resolved them to, or null. */\n contact: string | null;\n /** That contact's organization, or null. */\n organization: string | null;\n /** The permissions the tenant's role provider granted them. Empty when there is no contact. */\n permissions: string[];\n /** How well `contact` is known. `none` when nobody was established at all. */\n trust: ActorTrust;\n /** Which side of the platform the caller is on. */\n plane: ActorPlane;\n /** Does this actor hold the permission? False for every permission when nobody is acting. */\n holds(permission: string): boolean;\n /**\n * Is this a person the platform itself authenticated?\n *\n * The one check a per-person rule should make. An app enforcing \"only the\n * approver this approval names may decide it\" needs a signature, and only\n * this plane produces one.\n */\n authenticated(): boolean;\n}\n\n/** Gateway-set headers. Named here so a reader can grep the wire format. */\nexport const ACTOR_HEADERS = {\n user: 'x-revenexx-actor',\n email: 'x-revenexx-actor-email',\n trust: 'x-revenexx-actor-trust',\n contact: 'x-revenexx-contact',\n organization: 'x-revenexx-organization',\n permissions: 'x-revenexx-permissions',\n} as const;\n\nconst nullIfEmpty = (v: string): string | null => (v.trim() === '' ? null : v.trim());\n\n/**\n * Read the acting person out of a request's headers.\n *\n * Unknown values of the trust header degrade to `asserted` rather than to\n * `authenticated`: a gateway that learns a third plane must not silently\n * promote it past a signature check written today.\n */\nexport function actorFrom(header: (name: string) => string | undefined): Actor {\n // A caller outside a handler has its own header bag — a Node request answers\n // `undefined` for a header nobody sent and an array for one sent twice. Read\n // everything through here so neither shape reaches a `.trim()`.\n const read = (name: string): string => {\n const v = header(name);\n return typeof v === 'string' ? v : '';\n };\n\n const user = nullIfEmpty(read(ACTOR_HEADERS.user));\n const contact = nullIfEmpty(read(ACTOR_HEADERS.contact));\n const permissions = read(ACTOR_HEADERS.permissions)\n .split(',')\n .map((p) => p.trim())\n .filter(Boolean);\n\n // Nobody established: `none`, whatever the header says. An app reading\n // `trust === 'asserted'` must not see it for a call that named no one.\n //\n // And `authenticated` needs the person it authenticated: a trust header\n // arriving beside no subject is a plane half-stated, which degrades like any\n // other value the gateway did not mean.\n const raw = read(ACTOR_HEADERS.trust).trim().toLowerCase();\n const trust: ActorTrust =\n user === null && contact === null\n ? 'none'\n : user !== null && raw === 'authenticated'\n ? 'authenticated'\n : 'asserted';\n\n const plane: ActorPlane = contact !== null ? 'contact' : user !== null ? 'operator' : 'system';\n const held = new Set(permissions);\n\n return {\n user,\n email: nullIfEmpty(read(ACTOR_HEADERS.email)),\n contact,\n organization: nullIfEmpty(read(ACTOR_HEADERS.organization)),\n permissions,\n trust,\n plane,\n holds: (permission) => permission !== '' && held.has(permission),\n authenticated: () => trust === 'authenticated',\n };\n}\n","/**\n * The market a request is for, and the country that market ships from.\n *\n * The gateway forwards the caller's market as `X-Revenexx-Market` and, since\n * PE-1010, resolves the market's `ship_from_country` (markets app, RAD-246)\n * and sets it as `X-Revenexx-Market-Country`. The country header is\n * gateway-injected: a caller's copy never reaches the App, so it can be read\n * the way the tenant is read.\n *\n * An App prints a document's addresses for the sender country — the\n * document's own sender address when it has one, else `c.market.country`.\n * When the gateway could not resolve one (no markets app, a market that names\n * no country yet, an older gateway), `country` is null and the App falls back\n * to its own rule.\n */\n\n/** The market a request is for. */\nexport interface Market {\n /** The market code (`X-Revenexx-Market`), or null when the call names none. */\n code: string | null;\n /**\n * The ISO 3166-1 alpha-2 country the market ships from\n * (`X-Revenexx-Market-Country`), or null. Never set without a market.\n */\n country: string | null;\n}\n\n/** The two headers, as the gateway sets them. */\nexport const MARKET_HEADERS = {\n code: 'x-revenexx-market',\n country: 'x-revenexx-market-country',\n} as const;\n\nconst COUNTRY = /^[A-Z]{2}$/;\n\n/**\n * Read the market off a header reader. A blank market is no market; a country\n * that is not two upper-case letters, or one without a market, is null.\n */\nexport function marketFrom(header: (name: string) => string | undefined | null): Market {\n const code = (header(MARKET_HEADERS.code) ?? '').trim() || null;\n const raw = (header(MARKET_HEADERS.country) ?? '').trim();\n const country = code && COUNTRY.test(raw) ? raw : null;\n return { code, country };\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 * 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","/**\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","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 * CRUD route mounting: wire a generated entity client to REST routes in one\n * call, with the platform's standard list/get/create/update/delete semantics.\n *\n * const app = createApp({ name: 'markets' });\n * const db = createDb({ adapter: 'runtime', context });\n *\n * mountCrud(app, db.markets, { path: '/markets', columns: ENTITIES.markets.columns });\n * mountCrud(app, db.locales, {\n * path: '/markets/{marketId}/locales',\n * columns: ENTITIES.locales.columns,\n * parent: { param: 'marketId', column: 'market_id' },\n * });\n *\n * Nested resources (a `parent` option) scope every operation to the parent row:\n * lists filter by the parent column, creates inject it, and reads/writes 404\n * when the row belongs to a different parent.\n */\n\nimport type { Page, Query, Row } from '../types.js';\nimport { HttpError, notFound, type App, type RouteContext } from './router.js';\nimport { EMPTY_UPDATE_MESSAGE, updateFields } from '../patch.js';\nimport { OPS } from '../query.js';\nimport type { SettingsDefaults } from '../settings.js';\n\n/** Structural subset of the SDK's EntityClient — any compatible repo works. */\nexport interface RepoLike {\n list(query?: Query): Promise<Row[]>;\n page?(query?: Query): Promise<Page>;\n get(id: string | number): Promise<Row | null>;\n create(data: Row): Promise<Row>;\n update(id: string | number, patch: Row): Promise<Row>;\n delete(id: string | number): Promise<void>;\n}\n\nexport interface CrudOptions {\n /** Route base path, e.g. `/markets` or `/markets/{marketId}/locales`. */\n path: string;\n /**\n * Column metadata (from the generated ENTITIES) — enables `?col=value` list\n * filters. A list query key that is neither a column, a reserved key\n * (`limit`, `offset`, `order`) nor declared in `queryParams` is refused with\n * `400 unknown_filter`. Without `columns`, only those keys are accepted.\n */\n columns?: Record<string, unknown>;\n /**\n * Extra list query parameters the App handles itself (e.g. read by\n * middleware, a wrapping handler, or simply tolerated). The list route\n * accepts them and does NOT turn them into filters — they never reach the\n * data plane and are not echoed in `filter`.\n *\n * mountCrud(app, db.accounts, {\n * path: '/punchout/accounts',\n * columns: ENTITIES.accounts.columns,\n * queryParams: ['include_secrets'],\n * });\n */\n queryParams?: string[];\n /**\n * Nested-resource scoping: path param name + the FK column it maps to.\n *\n * Pass `repo` (the PARENT's repo) to make the collection routes verify the\n * parent exists. Without it, `GET /lists/{unknown-id}/entries` answers `200`\n * with an empty page, which a client cannot tell apart from a parent that\n * genuinely has no children — and `POST` would attach a row to a parent that\n * is not there. The single-row routes never had this gap: `fetchOwned`\n * already 404s on an ownership mismatch.\n *\n * Optional to stay backwards compatible; it costs one extra read per\n * collection request, so it is the app's call.\n */\n parent?: { param: string; column: string; repo?: Pick<RepoLike, 'get'> };\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Pagination bounds for list (defaults: 50, max 200). */\n defaultLimit?: number;\n maxLimit?: number;\n /** Restrict which routes are mounted (default: all five). */\n only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\n/**\n * Query keys the list route reads itself. Always accepted, never filters (a\n * column of the same name is still filtered on as well, as before).\n */\nexport const RESERVED_LIST_QUERY_KEYS: readonly string[] = Object.freeze(['limit', 'offset', 'order']);\n\nconst INT = (v: unknown, d: number): number => {\n const n = parseInt(String(v), 10);\n return Number.isFinite(n) ? n : d;\n};\n\n/** `json` / `jsonb`, read off the generated ENTITIES column metadata. */\nconst isJsonColumn = (def: unknown): boolean =>\n /^jsonb?\\b/i.test(String((def as { type?: unknown } | null | undefined)?.type ?? ''));\n\n/**\n * A filter on a jsonb column is a whole-document equality, so the value has to\n * be a JSON document. `k in opts.columns` never looked at the column *type*, so\n * anything else went to the data plane as `col=eq.<junk>`; Postgres failed the\n * cast (SQLSTATE 22P02) and the caller got a 400 that named neither the\n * parameter nor what a good value looks like:\n *\n * GET /v1/forms?definition=x -> 400 {\"error\":\"a value in the request has\n * the wrong format\",\"code\":\"invalid_value\"}\n *\n * It is our query parameter, so it is our 400. Same status and same `code` as\n * before — only the message becomes actionable, and the round trip disappears.\n * The rule is exactly the data plane's: it must parse as JSON. Postgres compares\n * jsonb semantically, so key order and whitespace stay irrelevant and nothing\n * that worked before stops working — a whole, exactly-serialised document is\n * still forwarded unchanged.\n *\n * Deliberately NOT a containment (`cs.`) filter: `?labels={\"de\":\"Hauptlager\"}`\n * matches one exact document today, and turning that into \"contains\" would\n * silently widen a filter three apps already declare, with examples, as\n * equality. Widening it is a product decision, not a bug fix.\n *\n * The message states the rule and does NOT show an instance of the document.\n * It cannot: the generated column metadata carries `type`, `notNull` and\n * sometimes `default`, and nothing about the shape — 22 of the 25 jsonb\n * columns in `products` have no default at all. The first version borrowed\n * one column's example for every column, so a filter on an array-shaped\n * document (`family_variants.axes`, `measurement_families.units`) was\n * illustrated with an object. A caller who copies that shape sends valid JSON,\n * so there is no 400 — the answer is 200 with zero rows, which is the worst\n * failure this API has. The honest example is per column, the app knows it,\n * and it is already published on the parameter; so point there instead of\n * inventing one here.\n */\nfunction assertJsonFilter(column: string, value: string): void {\n try {\n JSON.parse(value);\n } catch {\n throw new HttpError(\n 400,\n `filter '${column}' must be a whole JSON document, serialized exactly as stored ` +\n `and compared for equality — not a path or containment query. ` +\n `This parameter's example in the API contract shows the shape this column holds.`,\n undefined,\n { code: 'invalid_value' },\n );\n }\n}\n\n/**\n * A list query key that names no column used to be dropped, so a wrong filter\n * answered `200` with the UNFILTERED list — indistinguishable, to a caller that\n * does not inspect `filter`, from a correct one. Measured damage:\n * `GET /customers/segments?organization_id=…` (segments has no such column)\n * handed promotions every segment of the tenant. A filter we cannot apply is a\n * caller's mistake, so it is our 400, naming the key(s) and what is accepted.\n */\nfunction assertKnownKeys(query: Record<string, string>, opts: CrudOptions): void {\n const columns = opts.columns ?? {};\n const extra = opts.queryParams ?? [];\n const known = (k: string): boolean =>\n Object.prototype.hasOwnProperty.call(columns, k) || RESERVED_LIST_QUERY_KEYS.includes(k) || extra.includes(k);\n const unknown = Object.keys(query).filter((k) => !known(k));\n if (unknown.length === 0) return;\n const allowed = [...new Set([...Object.keys(columns), ...RESERVED_LIST_QUERY_KEYS, ...extra])].sort();\n const quoted = unknown.map((k) => `'${k}'`).join(', ');\n throw new HttpError(\n 400,\n `unknown list filter ${quoted} — not a column of this resource. ` +\n `A filter that cannot be applied is refused rather than ignored; see details.allowed.`,\n { unknown, allowed },\n { code: 'unknown_filter' },\n );\n}\n\n/** `in.`, `eq.`, `not.` … — a PostgREST operator prefix, as a caller would write one. */\nconst OPERATOR_PREFIX = new RegExp(`^(?:not|${[...OPS].join('|')})\\\\.`);\n\n/**\n * A list filter is an exact value: `toParams` sends the string as `eq.<value>`.\n * A caller who writes PostgREST syntax (`?sku=in.(a,b)`) therefore got\n * `sku=eq.in.(a,b)` — `200` with zero rows, which reads as \"none of those\n * exist\". Measured damage: punchout resolved every product of an inbound cart\n * that way and found none (RAD-160). An exact value that genuinely starts with\n * `in.` or `eq.` is implausible, so a value carrying an operator prefix is our\n * 400 rather than a silent miss. Only column filters are checked: `queryParams`\n * and the reserved keys never reach `where`.\n */\nfunction assertNoOperator(column: string, value: string): void {\n if (!OPERATOR_PREFIX.test(value)) return;\n throw new HttpError(\n 400,\n `filter '${column}' carries an operator ('${value.slice(0, value.indexOf('.') + 1)}') — ` +\n `a list filters by exact value only; operators and value lists are not supported.`,\n { parameter: column },\n { code: 'unsupported_filter_operator' },\n );\n}\n\nfunction parentWhere(c: RouteContext, parent?: CrudOptions['parent']): Record<string, string> {\n if (!parent) return {};\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`, undefined, { code: 'missing_parameter' });\n return { [parent.column]: value };\n}\n\n/**\n * 404 when the nested parent does not exist, so an unknown parent is not\n * reported as an empty collection. No-op unless the app supplied `parent.repo`.\n */\nasync function assertParentExists(c: RouteContext, parent?: CrudOptions['parent']): Promise<void> {\n if (!parent?.repo) return;\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`, undefined, { code: 'missing_parameter' });\n if (!(await parent.repo.get(value))) throw notFound();\n}\n\n/** Fetch a row and enforce nested-parent ownership; throws 404 when absent. */\nasync function fetchOwned(\n repo: RepoLike,\n c: RouteContext,\n opts: CrudOptions,\n): Promise<{ id: string; row: Row }> {\n const id = c.params[opts.idParam ?? 'id'] ?? '';\n if (!id) throw new HttpError(400, `missing path parameter '${opts.idParam ?? 'id'}'`, undefined, { code: 'missing_parameter' });\n const row = await repo.get(id);\n if (!row) throw notFound();\n if (opts.parent) {\n const expected = c.params[opts.parent.param];\n if (String(row[opts.parent.column] ?? '') !== String(expected ?? '')) throw notFound();\n }\n return { id, row };\n}\n\nexport function mountCrud<D extends SettingsDefaults = SettingsDefaults>(\n app: App<D>,\n repo: RepoLike,\n opts: CrudOptions,\n): App<D> {\n const base = opts.path.replace(/\\/+$/, '');\n const idTemplate = `${base}/{${opts.idParam ?? 'id'}}`;\n const enabled = new Set(opts.only ?? ['list', 'get', 'create', 'update', 'delete']);\n const defaultLimit = opts.defaultLimit ?? 50;\n const maxLimit = opts.maxLimit ?? 200;\n\n if (enabled.has('list')) {\n app.get(base, async (c) => {\n // Refuse before any round trip — including the parent lookup.\n assertKnownKeys(c.query, opts);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n // Reserved / app-declared keys that are not columns are not filters.\n if (!opts.columns || !Object.prototype.hasOwnProperty.call(opts.columns, k)) continue;\n assertNoOperator(k, v);\n if (isJsonColumn(opts.columns[k])) assertJsonFilter(k, v);\n where[k] = v;\n }\n await assertParentExists(c, opts.parent);\n // The nested-parent filter always wins — a query param must not widen\n // the scope beyond the parent in the path.\n Object.assign(where, parentWhere(c, opts.parent));\n const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);\n const offset = Math.max(INT(c.query.offset, 0), 0);\n const order = typeof c.query.order === 'string' && c.query.order ? c.query.order : undefined;\n const query: Query = { where, limit, offset, ...(order ? { order } : {}) };\n\n if (repo.page) {\n const { items, total } = await repo.page(query);\n return c.json({\n items,\n page: { limit, offset, total, returned: items.length, hasMore: offset + items.length < total },\n filter: where,\n });\n }\n const items = await repo.list(query);\n return c.json({ items, page: { limit, offset, returned: items.length }, filter: where });\n });\n }\n\n if (enabled.has('create')) {\n app.post(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const data = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.create(data), 201);\n });\n }\n\n if (enabled.has('get')) {\n app.get(idTemplate, async (c) => {\n const { row } = await fetchOwned(repo, c, opts);\n return c.json(row);\n });\n }\n\n if (enabled.has('update')) {\n app.put(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n // A body carrying no fields of its own is not an update. The rule itself\n // lives in ../patch.ts and is enforced by the data client, so Apps that\n // hand-write their PUT handler get it too; this check stays because it is\n // the only one that can see the *body* rather than the merged patch —\n // with a nested parent the merge always carries the FK, so the patch is\n // never literally empty — and because it answers without a round trip.\n if (updateFields(c.body).length === 0) throw new HttpError(400, EMPTY_UPDATE_MESSAGE, undefined, { code: 'empty_update' });\n // Never let a body overwrite the nested-parent FK.\n const patch = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.update(id, patch));\n });\n }\n\n if (enabled.has('delete')) {\n app.delete(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n await repo.delete(id);\n return c.json({ deleted: true, id });\n });\n }\n\n return app;\n}\n","/**\n * The trash, as one helper: `mountTrash` gives an entity the three routes and\n * the purge job every trash needs (PE-1022).\n *\n * const trash = mountTrash(app, db.organizations, {\n * path: '/organizations',\n * children: [{ name: 'contacts', repo: db.contacts, column: 'organization_id' }],\n * guard: (org) => (org.is_default ? { reason: 'The default organization stays.' } : null),\n * blockers: async (org, c) => [\n * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),\n * ],\n * });\n *\n * // the scheduled job (ADR-0103), once per tenant:\n * await trash.purge(c);\n *\n * The routes:\n *\n * DELETE <path>/{id} live row → into the trash, with its children\n * trashed row → deleted for good, through `blockers`\n * POST <path>/{id}/restore back out of the trash, with the children it took\n *\n * The entity needs `trash: true` in schema.json, which gives it `deleted_at`,\n * `deleted_by`, `deleted_by_id`, `trash_batch` and `purge_blocked_reason`.\n * Baseline does the rest of the\n * platform side: lookups leave trashed rows out, the event trigger says\n * `*.trashed` / `*.restored` (declare them with `on: [\"trash\"]` /\n * `on: [\"restore\"]`), and a real DELETE is `*.deleted`.\n *\n * Two rules this helper exists to keep:\n *\n * - The final delete has ONE code path. The second DELETE and the purge job\n * both go through `deleteForGood`, so a blocker the app declares cannot be\n * bypassed by waiting 90 days.\n * - A blocker that cannot be checked blocks. A guard that throws, or a count\n * the gateway would not answer, is a reason to keep the row, never a\n * reason to delete it.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { Row } from '../types.js';\nimport type { Actor } from './actor.js';\nimport { HttpError, notFound, type App } from './router.js';\nimport type { RepoLike } from './crud.js';\nimport { DEFAULT_GATEWAY_ENDPOINT, type SettingsDefaults, type SettingsSource } from '../settings.js';\n\n/** The column whose value says \"in the trash\". */\nexport const TRASH_COLUMN = 'deleted_at';\n\n/** Trash retention when Baseline holds no value for the tenant (RAD-247, ADR-0114). */\nexport const DEFAULT_TRASH_RETENTION_DAYS = 90;\n\n/** The column `trash: true` gives an entity for why the purge left a row in the trash. */\nexport const PURGE_REASON_COLUMN = 'purge_blocked_reason';\n\n/** The gateway route the tenant's retention is read from (PE-1022). */\nexport const AUDIT_SETTINGS_PATH = '/v1/audit/settings';\n\n/** Why a row may not go into the trash, or may not be deleted for good. */\nexport interface Blocker {\n /** One sentence for the person who asked. */\n reason: string;\n /** How many records stand in the way, when it is a count. */\n count?: number;\n /** `unverifiable` when the check itself failed; anything else is the app's. */\n code?: string;\n details?: unknown;\n}\n\n/**\n * Who asks, as far as a check needs it. A handler's `c` is one; so is the\n * purge job's source.\n */\nexport interface TrashCaller extends SettingsSource {\n tenant?: string | null;\n actor?: Actor;\n header?(name: string): string;\n}\n\n/** A guard or blocker check. Return nothing, one blocker or several. */\nexport type BlockerCheck = (\n row: Row,\n caller: TrashCaller,\n) => Blocker | null | undefined | (Blocker | null | undefined)[] | Promise<Blocker | null | undefined | (Blocker | null | undefined)[]>;\n\n/** Rows that go into the trash with their parent and come back with it. */\nexport interface TrashChild {\n /** Key in the answer's `took`, e.g. `contacts`. */\n name: string;\n repo: Pick<RepoLike, 'list' | 'update' | 'delete'>;\n /** The child's column holding the parent id. */\n column: string;\n}\n\nexport interface TrashOptions {\n /** Base path of the entity, e.g. `/organizations`. */\n path: string;\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Dependent rows that form one group with the parent (contacts, sub-categories, variants). */\n children?: TrashChild[];\n /**\n * May the row go into the trash? Only the default record and a running\n * process that would break (an open approval, an active punchout account)\n * belong here; everything else is a warning for the dialog, not a blocker.\n */\n guard?: BlockerCheck;\n /**\n * May the row be deleted for good? Checked on the second DELETE and by the\n * purge job alike: references from open processes, configuration that names\n * the row. Cross-app references are counted through the gateway\n * (`createGatewayCounter`).\n */\n blockers?: BlockerCheck;\n /** Who may delete for good. Default: whoever may call the route. */\n canDeleteForGood?: (caller: TrashCaller) => boolean;\n /**\n * A parent that has to be live for this row to come back, e.g. a contact's\n * organization. Restoring a row whose parent is in the trash is refused.\n */\n parent?: { repo: Pick<RepoLike, 'get'>; column: string };\n /**\n * The final delete of the row itself. Default `repo.delete(id)`. Children\n * of the row's group are deleted before it either way.\n */\n deleteRow?: (row: Row, caller: TrashCaller) => Promise<void>;\n /**\n * The text column the purge writes the blocked reason into, and a restore\n * clears. Default `purge_blocked_reason`, which `trash: true` creates; `false`\n * for an entity that has no such column.\n */\n purgeReasonColumn?: string | false;\n /**\n * App-fired events. Prefer Baseline's trigger for `trashed` / `restored`\n * (`on: [\"trash\"]` / `on: [\"restore\"]`) — it is transactional. Name them\n * here only for an entity that has no such trigger; declaring both\n * publishes twice. `purged` is one summary per purge run.\n */\n events?: {\n emit: (name: string, data: Row, options?: { topicId?: string | null; eventId?: string }) => Promise<unknown>;\n trashed?: string;\n restored?: string;\n purged?: string;\n };\n /** Reading the tenant's trash retention through the gateway. */\n retention?: RetentionOptions;\n /** Clock (tests). */\n now?: () => Date;\n}\n\n/**\n * Where and how the retention is read. The URL is, first match wins: `url`,\n * REVENEXX_AUDIT_SETTINGS_URL, or `{endpoint}/v1/audit/settings` with\n * `endpoint` defaulting to REVENEXX_GATEWAY_ENDPOINT or the platform gateway.\n */\nexport interface RetentionOptions {\n /** The full settings URL. */\n url?: string;\n /** Gateway base URL. */\n endpoint?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n env?: Record<string, string | undefined>;\n}\n\n/** What one purge run did. */\nexport interface PurgeResult {\n /** True when the run did nothing because the retention could not be read. */\n skipped: boolean;\n reason?: string;\n retentionDays?: number;\n /** Rows trashed before this instant were due. */\n cutoff?: string;\n purged: string[];\n blocked: { id: string; blockers: Blocker[] }[];\n}\n\nexport interface TrashHandle {\n /** Put a row into the trash, with its children. Throws the same refusals as the route. */\n trash(id: string, caller: TrashCaller): Promise<{ id: string; batch: string; took: Record<string, number> }>;\n /** Take a row and its group back out of the trash. */\n restore(id: string, caller: TrashCaller): Promise<{ id: string; took: Record<string, number> }>;\n /** Delete a trashed row for good, through the blockers. */\n deleteForGood(id: string, caller: TrashCaller): Promise<{ id: string; took: Record<string, number> }>;\n /** The purge job: delete for good what is past the tenant's retention. Never throws for a single row. */\n purge(caller: TrashCaller, options?: { max?: number }): Promise<PurgeResult>;\n}\n\nconst PAGE = 200;\n\nconst isTrashed = (row: Row): boolean => row[TRASH_COLUMN] !== null && row[TRASH_COLUMN] !== undefined;\n\nconst idOf = (row: Row, fallback: string): string => String(row.id ?? fallback);\n\n/** Every row matching `where`, page by page — a group is never cut off at 50. */\nasync function listAll(repo: Pick<RepoLike, 'list'>, where: Row): Promise<Row[]> {\n const rows: Row[] = [];\n for (;;) {\n const batch = await repo.list({ where: where as never, limit: PAGE, offset: rows.length });\n rows.push(...batch);\n if (batch.length < PAGE) return rows;\n }\n}\n\n/** Run a check; a throw is a blocker, never a pass. */\nasync function runCheck(check: BlockerCheck | undefined, row: Row, caller: TrashCaller): Promise<Blocker[]> {\n if (!check) return [];\n try {\n const out = await check(row, caller);\n const list = Array.isArray(out) ? out : [out];\n return list.filter((b): b is Blocker => Boolean(b && typeof b.reason === 'string'));\n } catch (err) {\n return [\n {\n reason: `could not be checked: ${err instanceof Error ? err.message : String(err)}`,\n code: 'unverifiable',\n },\n ];\n }\n}\n\nconst refuse = (status: number, message: string, code: string, details?: unknown): HttpError =>\n new HttpError(status, message, details, { code });\n\nfunction headerFrom(caller: TrashCaller, name: string): string {\n if (typeof caller.header === 'function') {\n const v = caller.header(name);\n if (typeof v === 'string' && v !== '') return v;\n }\n const want = name.toLowerCase();\n for (const bag of [caller.req?.headers, caller.headers]) {\n if (!bag) continue;\n for (const [k, v] of Object.entries(bag)) if (k.toLowerCase() === want && typeof v === 'string' && v !== '') return v;\n }\n return '';\n}\n\n/** The URL the retention is read from; see `RetentionOptions`. */\nexport function auditSettingsUrl(options: RetentionOptions = {}): string {\n const env = options.env ?? process.env;\n const url = options.url || env.REVENEXX_AUDIT_SETTINGS_URL;\n if (url) return url;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\\/+$/, '');\n return `${endpoint}${AUDIT_SETTINGS_PATH}`;\n}\n\n/**\n * The tenant's trash retention in days, read through the gateway\n * (`GET /v1/audit/settings`, which Baseline answers). An App holds no Baseline\n * credential; the gateway takes the request's own.\n *\n * Throws when the settings cannot be read: guessing would be the dangerous\n * direction — a tenant that keeps its trash for a year must not lose it after\n * 90 days because a request timed out. The default applies only when the\n * settings answer and hold no value.\n */\nexport async function readTrashRetention(caller: TrashCaller, options: RetentionOptions = {}): Promise<number> {\n const url = auditSettingsUrl(options);\n const f = options.fetchImpl ?? globalThis.fetch;\n const tenant = (caller.tenant ?? '') || headerFrom(caller, 'x-revenexx-tenant');\n if (!tenant) throw new Error('trash retention: no tenant');\n const token = (caller.contextToken ?? '') || headerFrom(caller, 'x-revenexx-context');\n\n const headers: Record<string, string> = { Accept: 'application/json', 'X-Revenexx-Tenant': tenant };\n if (token) headers.Authorization = `Bearer ${token}`;\n const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5_000);\n const res = await f(url, { method: 'GET', headers, ...(signal ? { signal } : {}) });\n if (!res.ok) throw new Error(`trash retention: ${res.status} from ${AUDIT_SETTINGS_PATH}`);\n const body = (await res.json()) as { trash_retention_days?: unknown };\n const days = body.trash_retention_days;\n return typeof days === 'number' && Number.isInteger(days) && days > 0 ? days : DEFAULT_TRASH_RETENTION_DAYS;\n}\n\n/**\n * Mount the trash routes for one entity and return the handle the purge job\n * (and any hand-written route) uses.\n */\nexport function mountTrash<D extends SettingsDefaults = SettingsDefaults>(\n app: App<D>,\n repo: RepoLike,\n opts: TrashOptions,\n): TrashHandle {\n const base = opts.path.replace(/\\/+$/, '');\n const idParam = opts.idParam ?? 'id';\n const children = opts.children ?? [];\n const now = opts.now ?? (() => new Date());\n const reasonColumn = opts.purgeReasonColumn === false ? null : (opts.purgeReasonColumn ?? PURGE_REASON_COLUMN);\n\n const load = async (id: string): Promise<Row> => {\n if (!id) throw refuse(400, `missing path parameter '${idParam}'`, 'missing_parameter');\n const row = await repo.get(id);\n if (!row) throw notFound();\n return row;\n };\n\n const emit = async (name: string | undefined, data: Row, topicId: string | null): Promise<void> => {\n if (!name || !opts.events) return;\n await opts.events.emit(name, data, { topicId });\n };\n\n async function trash(id: string, caller: TrashCaller) {\n const row = await load(id);\n if (isTrashed(row)) throw refuse(409, 'this record is already in the trash', 'already_in_trash');\n\n const blockers = await runCheck(opts.guard, row, caller);\n if (blockers.length) {\n throw refuse(409, `cannot go into the trash: ${blockers.map((b) => b.reason).join('; ')}`, 'trash_blocked', { blockers });\n }\n\n const batch = randomUUID();\n const fields: Row = {\n [TRASH_COLUMN]: now().toISOString(),\n deleted_by: caller.actor?.email ?? caller.actor?.user ?? null,\n deleted_by_id: caller.actor?.user ?? caller.actor?.contact ?? null,\n trash_batch: batch,\n };\n\n await repo.update(id, fields);\n const took: Record<string, number> = {};\n for (const child of children) {\n // Only the live children join the group. One that was trashed on its own\n // earlier keeps its own batch, and stays in the trash on restore.\n const rows = await listAll(child.repo, { [child.column]: id, [TRASH_COLUMN]: null });\n for (const r of rows) await child.repo.update(String(r.id), fields);\n took[child.name] = rows.length;\n }\n\n await emit(opts.events?.trashed, { id, batch, took }, idOf(row, id));\n return { id, batch, took };\n }\n\n async function restore(id: string, caller: TrashCaller) {\n void caller;\n const row = await load(id);\n if (!isTrashed(row)) throw refuse(409, 'this record is not in the trash', 'not_in_trash');\n\n if (opts.parent) {\n const parentId = row[opts.parent.column];\n const parent = parentId == null ? null : await opts.parent.repo.get(String(parentId));\n if (parent && isTrashed(parent)) {\n throw refuse(409, 'its parent is in the trash — restore the parent first', 'parent_in_trash', {\n parent: String(parentId),\n });\n }\n }\n\n const fields: Row = { [TRASH_COLUMN]: null, deleted_by: null, deleted_by_id: null, trash_batch: null };\n\n await repo.update(id, reasonColumn ? { ...fields, [reasonColumn]: null } : fields);\n const took: Record<string, number> = {};\n const batch = row.trash_batch;\n for (const child of children) {\n // Children never carry a purge reason: the purge only writes it onto\n // the row it was asked about.\n const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });\n for (const r of rows) await child.repo.update(String(r.id), fields);\n took[child.name] = rows.length;\n }\n\n await emit(opts.events?.restored, { id, took }, idOf(row, id));\n return { id, took };\n }\n\n async function finalDelete(row: Row, id: string, caller: TrashCaller) {\n const took: Record<string, number> = {};\n const batch = row.trash_batch;\n for (const child of children) {\n const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });\n for (const r of rows) await child.repo.delete(String(r.id));\n took[child.name] = rows.length;\n }\n if (opts.deleteRow) await opts.deleteRow(row, caller);\n else await repo.delete(id);\n return { id, took };\n }\n\n async function deleteForGood(id: string, caller: TrashCaller) {\n const row = await load(id);\n if (!isTrashed(row)) throw refuse(409, 'only a record in the trash can be deleted for good', 'not_in_trash');\n if (opts.canDeleteForGood && !opts.canDeleteForGood(caller)) {\n throw refuse(403, 'deleting for good needs its own permission', 'not_permitted');\n }\n const blockers = await runCheck(opts.blockers, row, caller);\n if (blockers.length) {\n throw refuse(409, `cannot be deleted for good: ${blockers.map((b) => b.reason).join('; ')}`, 'delete_blocked', {\n blockers,\n });\n }\n return finalDelete(row, id, caller);\n }\n\n async function purge(caller: TrashCaller, options: { max?: number } = {}): Promise<PurgeResult> {\n let retentionDays: number;\n try {\n retentionDays = await readTrashRetention(caller, opts.retention);\n } catch (err) {\n return { skipped: true, reason: err instanceof Error ? err.message : String(err), purged: [], blocked: [] };\n }\n\n const cutoff = new Date(now().getTime() - retentionDays * 86_400_000).toISOString();\n const max = options.max ?? 500;\n const due = (await listAll(repo, { [TRASH_COLUMN]: { op: 'lt', value: cutoff } })).slice(0, max);\n\n const result: PurgeResult = { skipped: false, retentionDays, cutoff, purged: [], blocked: [] };\n for (const row of due) {\n const id = String(row.id);\n // A purge is the second DELETE, run by the system: same blockers, same\n // children, same delete. Nothing here may delete what the route would not.\n const blockers = await runCheck(opts.blockers, row, caller);\n if (blockers.length) {\n result.blocked.push({ id, blockers });\n const reason = blockers.map((b) => b.reason).join('; ');\n // Written only when it changed: every write is an `*.updated` event,\n // and a nightly run must not repeat one for a row nobody touched.\n if (reasonColumn && row[reasonColumn] !== reason) {\n try {\n await repo.update(id, { [reasonColumn]: reason });\n } catch {\n /* the reason is a courtesy; the row staying is what matters */\n }\n }\n continue;\n }\n try {\n await finalDelete(row, id, caller);\n result.purged.push(id);\n } catch (err) {\n result.blocked.push({\n id,\n blockers: [{ reason: `delete failed: ${err instanceof Error ? err.message : String(err)}`, code: 'delete_failed' }],\n });\n }\n }\n\n await emit(\n opts.events?.purged,\n { retention_days: retentionDays, cutoff, purged: result.purged.length, blocked: result.blocked.length },\n null,\n );\n return result;\n }\n\n app.delete(`${base}/{${idParam}}`, async (c) => {\n const id = c.params[idParam] ?? '';\n const row = await load(id);\n if (isTrashed(row)) return c.json({ deleted: true, ...(await deleteForGood(id, c)) });\n return c.json({ trashed: true, ...(await trash(id, c)) });\n });\n\n app.post(`${base}/{${idParam}}/restore`, async (c) => {\n return c.json({ restored: true, ...(await restore(c.params[idParam] ?? '', c)) });\n });\n\n return { trash, restore, deleteForGood, purge };\n}\n\n/**\n * Count another App's records through the gateway, for a blocker that crosses\n * an App boundary (\"open orders of this organization\"). Apps never read each\n * other's tables; the owning App's list route answers, and its `page.total` is\n * the count.\n *\n * const refs = createGatewayCounter();\n * blockers: async (org, c) => [\n * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),\n * ]\n *\n * A count the gateway does not give — an error, a timeout, a route that does\n * not report `total` — is `null`, and `blocker` turns `null` into an\n * `unverifiable` blocker. Not knowing is never a pass.\n */\nexport function createGatewayCounter(\n options: { endpoint?: string; timeoutMs?: number; fetchImpl?: typeof fetch; env?: Record<string, string | undefined> } = {},\n) {\n const env = options.env ?? process.env;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\\/+$/, '');\n\n async function count(caller: TrashCaller, path: string, where: Record<string, string | number | boolean> = {}): Promise<number | null> {\n const f = options.fetchImpl ?? globalThis.fetch;\n const qs = new URLSearchParams();\n for (const [k, v] of Object.entries(where)) qs.set(k, String(v));\n qs.set('limit', '1');\n const headers: Record<string, string> = { Accept: 'application/json' };\n const tenant = (caller.tenant ?? '') || headerFrom(caller, 'x-revenexx-tenant');\n if (tenant) headers['X-Revenexx-Tenant'] = tenant;\n const context = (caller.contextToken ?? '') || headerFrom(caller, 'x-revenexx-context');\n if (context) headers.Authorization = `Bearer ${context}`;\n const appContext = headerFrom(caller, 'x-revenexx-app-context');\n if (appContext) headers['x-revenexx-app-context'] = appContext;\n\n try {\n const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5_000);\n const sep = path.includes('?') ? '&' : '?';\n const res = await f(`${endpoint}${path}${sep}${qs.toString()}`, { headers, ...(signal ? { signal } : {}) });\n if (!res.ok) return null;\n const body = (await res.json()) as { page?: { total?: unknown } };\n const total = body?.page?.total;\n return typeof total === 'number' && Number.isFinite(total) ? total : null;\n } catch {\n return null;\n }\n }\n\n async function blocker(\n caller: TrashCaller,\n check: { path: string; where?: Record<string, string | number | boolean>; reason: string },\n ): Promise<Blocker | null> {\n const n = await count(caller, check.path, check.where);\n if (n === null) return { reason: `${check.reason} — could not be checked`, code: 'unverifiable' };\n if (n === 0) return null;\n return { reason: `${n} ${check.reason}`, count: n, code: 'referenced' };\n }\n\n return { count, blocker };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoBA,IAAI,UAAU;AAMd,eAAsB,iBAAgC;AACpD,MAAI,SAAS;AACX;AAAA,EACF;AACA,YAAU;AAEV,QAAM,WACJ,QAAQ,IAAI,oCAAoC,KAAK,QAAQ,IAAI,6BAA6B,KAAK;AACrG,MAAI,CAAC,UAAU;AACb;AAAA,EACF;AAEA,MAAI;AACF,UAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,kBAAkB,GAAG,EAAE,sBAAsB,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,MACxF,OAAO,yBAAyB;AAAA,MAChC,OAAO,0CAA0C;AAAA,MACjD,OAAO,uCAAuC;AAAA,IAChD,CAAC;AAGD,UAAM,MAAM,IAAI,QAAQ;AAAA,MACtB,eAAe,IAAI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M,IAAI,MAAM,MAAM,QAAQ,MAAM,MAAM,MAAM,KAAK;AACrD,QAAI,MAAM,KAAM,QAAO,EAAE,QAAQ,GAAG,MAAM,MAAM,gCAA2B,MAAM,eAAe;AAChG,QAAI,MAAM,EAAG,QAAO;AACpB,WAAO,EAAE,QAAQ,GAAG,CAAC,IAAI,MAAM,MAAM,IAAI,OAAO,GAAG,MAAM,aAAa;AAAA,EACxE;AAEA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":["now","headerOf","otelContext","route","items","now"]}
|
|
1
|
+
{"version":3,"sources":["../../src/router/index.ts","../../src/instrument.ts","../../src/router/router.ts","../../src/router/actor.ts","../../src/router/market.ts","../../src/settings.ts","../../src/backdating.ts","../../src/errors.ts","../../src/patch.ts","../../src/query.ts","../../src/router/crud.ts","../../src/router/trash.ts"],"sourcesContent":["/**\n * @revenexx/app-sdk/router — declarative HTTP routing for revenexx App\n * functions. Pair with the generated data client for clean, testable handlers.\n */\n\n// Side effect: auto-start OpenTelemetry when OTEL_* env is configured. Runs in the\n// app's code context (where OTel deps resolve), so no NODE_OPTIONS preload is needed.\nimport '../instrument.js';\n\nexport {\n createApp,\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n} from './router.js';\nexport type {\n HttpErrorOptions,\n App,\n AppOptions,\n Handler,\n RouteContext,\n FnContext,\n FnRequest,\n FnResponse,\n} from './router.js';\n\n// Reading a refusal — this App's own, or another App's caught from the platform\n// client (`@revenexx/sdk`).\nexport { refusalOf } from '../errors.js';\nexport type { Refusal } from '../errors.js';\n\n// Who is acting. `createApp` reads it for you (`c.actor`); `actorFrom` is here\n// for code outside a handler that has the same headers in hand.\nexport { actorFrom, ACTOR_HEADERS } from './actor.js';\nexport type { Actor, ActorTrust, ActorPlane } from './actor.js';\n\n// The market a request is for and the country it ships from. `createApp`\n// reads it for you (`c.market`); `marketFrom` is here for code outside a\n// handler that has the same headers in hand.\nexport { marketFrom, MARKET_HEADERS } from './market.js';\nexport type { Market } from './market.js';\n\n// Backdating (RAD-311): `createApp({ backdating })` turns it on; the clock and\n// the data-client wrapper are here for handlers, helpers and jobs.\nexport {\n now,\n clock,\n backdated,\n runAt,\n parseBackdate,\n backdatingAllowed,\n backdatingDb,\n MAX_MONTHS_BACK,\n BACKDATING_SETTING,\n BACKDATING_FIELD,\n BACKDATING_INVALID,\n} from '../backdating.js';\nexport type { BackdatingOptions, BackdatingSource, BackdatingEntity } from '../backdating.js';\n\nexport { mountCrud, RESERVED_LIST_QUERY_KEYS } from './crud.js';\nexport type { CrudOptions, RepoLike } from './crud.js';\n\n// The trash (PE-1022): DELETE into the trash, DELETE again for good, restore,\n// and the purge job — one code path for the final delete.\nexport {\n mountTrash,\n createGatewayCounter,\n readTrashRetention,\n auditSettingsUrl,\n TRASH_COLUMN,\n PURGE_REASON_COLUMN,\n AUDIT_SETTINGS_PATH,\n DEFAULT_TRASH_RETENTION_DAYS,\n} from './trash.js';\nexport type {\n TrashOptions,\n TrashHandle,\n TrashChild,\n TrashCaller,\n Blocker,\n BlockerCheck,\n PurgeResult,\n RetentionOptions,\n} from './trash.js';\n\n// App settings. `createApp` builds a reader for you (`c.settings()`); create\n// one directly when code outside a handler needs the same values.\nexport {\n createSettings,\n DEFAULT_GATEWAY_ENDPOINT,\n DEFAULT_SETTINGS_TTL_MS,\n DEFAULT_SETTINGS_ERROR_TTL_MS,\n DEFAULT_SETTINGS_TIMEOUT_MS,\n} from '../settings.js';\nexport type {\n SettingsReader,\n SettingsOptions,\n SettingsSnapshot,\n SettingsSource,\n SettingsDefaults,\n ResolvedSettings,\n ReadOptions,\n WriteOptions,\n SettingsWriteResult,\n} from '../settings.js';\n","/**\n * OpenTelemetry bootstrap for revenexx App functions.\n *\n * Loaded automatically as a side effect of importing `@revenexx/app-sdk/router`\n * (the app requires the router from its own code dir, so OTel deps resolve).\n * Do NOT preload via `NODE_OPTIONS=--require` in open-runtimes: that runs in the\n * runtime server's node process, which cannot resolve the app's node_modules and\n * crashes the runtime.\n *\n * Configuration is 100% standard `OTEL_*` env; with no OTLP endpoint set it is a\n * cheap no-op (the heavy OTel packages aren't even loaded):\n * OTEL_EXPORTER_OTLP_ENDPOINT https://traces.revenexx.com\n * OTEL_EXPORTER_OTLP_HEADERS Authorization=Basic <base64>\n * OTEL_SERVICE_NAME products\n * OTEL_RESOURCE_ATTRIBUTES service.namespace=revenue-cloud,deployment.environment=prod\n *\n * Lean: only outbound undici/fetch (the PostgREST data plane) is auto-instrumented.\n * The per-invocation SERVER span is added by the router (createApp).\n */\n\nlet started = false;\n\n/**\n * Start OpenTelemetry once. Safe to call repeatedly. NEVER throws — a telemetry\n * failure must not take the function down (a missing trace beats a dead runtime).\n */\nexport async function startTelemetry(): Promise<void> {\n if (started) {\n return;\n }\n started = true;\n\n const endpoint =\n process.env['OTEL_EXPORTER_OTLP_TRACES_ENDPOINT'] ?? process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? '';\n if (!endpoint) {\n return; // tracing disabled — don't even load the OTel packages\n }\n\n try {\n const [{ NodeSDK }, { OTLPTraceExporter }, { UndiciInstrumentation }] = await Promise.all([\n import('@opentelemetry/sdk-node'),\n import('@opentelemetry/exporter-trace-otlp-proto'),\n import('@opentelemetry/instrumentation-undici'),\n ]);\n\n // Exporter + resource (service.name, resource attrs) are read from OTEL_* env.\n const sdk = new NodeSDK({\n traceExporter: new OTLPTraceExporter(),\n instrumentations: [new UndiciInstrumentation()],\n });\n\n sdk.start();\n\n const flush = (): void => {\n void sdk.shutdown().catch(() => {\n /* best effort */\n });\n };\n process.once('SIGTERM', flush);\n process.once('SIGINT', flush);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n '[app-sdk] OpenTelemetry init failed, continuing without tracing:',\n err instanceof Error ? err.message : err,\n );\n }\n}\n\n// Auto-start on import (side effect). Fire-and-forget; never blocks or throws.\nvoid startTelemetry();\n","/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\nimport { actorFrom } from './actor.js';\nimport type { Actor } from './actor.js';\nimport { marketFrom } from './market.js';\nimport type { Market } from './market.js';\nimport { createSettings } from '../settings.js';\nimport { backdatingFields, clock as clockNow, now as nowIso, requestedMoment, runAt } from '../backdating.js';\nimport type { BackdatingOptions } from '../backdating.js';\nimport type {\n ReadOptions,\n ResolvedSettings,\n SettingsDefaults,\n SettingsOptions,\n SettingsReader,\n SettingsSnapshot,\n SettingsWriteResult,\n WriteOptions,\n} from '../settings.js';\n\nexport interface FnRequest {\n method?: string;\n path?: string;\n url?: string;\n headers?: Record<string, string>;\n query?: Record<string, unknown>;\n body?: unknown;\n bodyText?: string;\n bodyRaw?: string;\n}\n\nexport interface FnResponse {\n json(data: unknown, statusCode?: number, headers?: Record<string, string>): unknown;\n send?(body: string, statusCode?: number, headers?: Record<string, string>): unknown;\n}\n\n/** The invocation context an App function receives from the runtime. */\nexport interface FnContext {\n req: FnRequest;\n res: FnResponse;\n log?: (message: string) => void;\n error?: (message: string) => void;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {\n /** Raw invocation context (escape hatch). */\n ctx: FnContext;\n req: FnRequest;\n method: string;\n /** Normalised path (no trailing slash, no query string). */\n path: string;\n /** Path parameters from the matched route template (e.g. `{id}`). */\n params: Record<string, string>;\n /** Query string parameters (string values). */\n query: Record<string, string>;\n /** Parsed JSON body, or `{}` when absent/unparsable. */\n body: Record<string, unknown>;\n /** Tenant slug from the `x-revenexx-tenant` header (or token claim). */\n tenant: string | null;\n /** The forwarded identity token (`x-revenexx-context`), if present. */\n contextToken: string;\n /**\n * Who is acting — the person behind this request, as the platform\n * established them (see ./actor.ts).\n *\n * `c.tenant` says whose data this is; this says whose hand is on it. Read\n * `c.actor.authenticated()` before enforcing a per-person rule, and\n * `c.actor.plane` to tell one of the tenant's contacts from one of the\n * merchant's sales reps, a back-office operator or a system caller. Never derive either from the context\n * token's claims: those describe the calling SYSTEM.\n */\n actor: Actor;\n /**\n * The market this request is for, and the country it ships from — both\n * set by the gateway (see ./market.ts). `country` is what a document\n * without a sender address of its own prints addresses for.\n */\n market: Market;\n /** Case-insensitive header lookup. */\n header(name: string): string;\n log(message: string): void;\n /** Respond with JSON. Returning `c.json(...)` ends the request. */\n json(data: unknown, statusCode?: number): unknown;\n /**\n * This tenant's effective settings for the app, resolved for the request's\n * market. Cached and fail-open — see `createSettings`. Available on every\n * app; pass `settings` to `createApp` to declare defaults and get them typed.\n */\n settings(options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/stored/provenance. */\n settingsSnapshot(options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n /**\n * Store this app's OWN tenant-level settings for the request's tenant —\n * `{ ifAbsent: true }` for defaults, so a merchant's choice is never\n * overwritten. Never throws; see `SettingsReader.set`.\n */\n setSettings(values: Record<string, unknown>, options?: WriteOptions): Promise<SettingsWriteResult>;\n /**\n * The request's clock as an ISO string — the backdated moment while a\n * backdated request runs, the wall clock otherwise (see `createApp`'s\n * `backdating`). Same as the exported `now()`.\n */\n now(): string;\n /** The request's clock as a Date. Same as the exported `clock()`. */\n clock(): Date;\n}\n\nexport type Handler<D extends SettingsDefaults = SettingsDefaults> = (\n c: RouteContext<D>,\n) => unknown | Promise<unknown>;\n\n// `HttpError` lives in ../errors.js so the data adapters can raise it too — a\n// PostgREST unique violation answers 409 without the router guessing from a\n// message string. Re-exported here so `@revenexx/app-sdk/router` is unchanged.\nexport {\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n type HttpErrorOptions,\n} from '../errors.js';\nimport { isHttpError, refusalBody, refusalOf } from '../errors.js';\n\ninterface Segment {\n lit?: string;\n param?: string;\n}\n\ninterface CompiledRoute<D extends SettingsDefaults> {\n method: string;\n template: string;\n segments: Segment[];\n literals: number;\n handler: Handler<D>;\n /** Body fields carrying a backdated moment, in precedence order; null = not backdatable. */\n backdating: string[] | null;\n}\n\nconst splitPath = (path: string): string[] => path.split('/').filter(Boolean);\n\nfunction compileTemplate(template: string): Segment[] {\n return splitPath(template).map((seg) => {\n const braced = /^\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/.exec(seg);\n if (braced) return { param: braced[1] };\n if (seg.startsWith(':') && seg.length > 1) return { param: seg.slice(1) };\n return { lit: seg };\n });\n}\n\nfunction matchSegments(segments: Segment[], reqSegs: string[]): Record<string, string> | null {\n if (segments.length !== reqSegs.length) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]!;\n if (s.param) params[s.param] = decodeURIComponent(reqSegs[i]!);\n else if (s.lit !== reqSegs[i]) return null;\n }\n return params;\n}\n\nfunction headerOf(headers: Record<string, string> | undefined, name: string): string {\n if (!headers) return '';\n const direct = headers[name] ?? headers[name.toLowerCase()];\n if (typeof direct === 'string') return direct;\n const want = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === want && typeof v === 'string') return v;\n }\n return '';\n}\n\nfunction decodeClaims(token: string): Record<string, unknown> {\n if (!token || token.split('.').length < 2) return {};\n try {\n const payload = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction parseBody(req: FnRequest): Record<string, unknown> {\n const candidate = req.body ?? req.bodyText ?? req.bodyRaw;\n if (candidate == null || candidate === '') return {};\n if (typeof candidate === 'object') return candidate as Record<string, unknown>;\n if (typeof candidate === 'string') {\n try {\n const parsed: unknown = JSON.parse(candidate);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/**\n * Request query, percent-DECODED exactly once.\n *\n * `req.path` carries the query string verbatim as the gateway forwarded it, so\n * it is the authoritative source: `URLSearchParams` decodes it once, correctly,\n * and treats `+` as a space the way a form-encoded query requires.\n *\n * The runtime's own `req.query` hands values through *undecoded*. A filter of\n * `?code=m%61in` arrived as the literal `m%61in` and matched nothing, when per\n * RFC 3986 it simply means `main`. That broke every filter value needing an\n * escape — spaces, `&`, `+`, `/`, commas, anything non-ASCII — so \"Müller & Co\"\n * could not be filtered for at all. It also let the gateway's response cache\n * merge two spellings the app answered differently (revenexx/api#32).\n *\n * `req.query` stays the fallback for callers that populate it without a query\n * string on the path (the mock adapter and direct unit tests do this). Decoding\n * that again here would be wrong — a double decode turns `%2520` into a space —\n * so each source is decoded by exactly one owner.\n */\nfunction parseQuery(req: FnRequest): Record<string, string> {\n const out: Record<string, string> = {};\n const rawPath = String(req.path ?? '');\n const qmark = rawPath.indexOf('?');\n if (qmark >= 0) {\n for (const [k, v] of new URLSearchParams(rawPath.slice(qmark + 1))) out[k] = v;\n return out;\n }\n // The runtime hands `req.query` through UNDECODED — measured in production\n // against every one of the 13 apps after 0.6.0 shipped:\n //\n // GET /v1/customers/organizations?name=ACME%20GmbH\n // -> returned 0, filter {\"name\":\"ACME%20GmbH\"} (the row 'ACME GmbH' exists)\n //\n // 0.6.0 only decoded when the query rode on `req.path`, which this runtime\n // does not do, so the fix was inert. Decode here as well; each source is\n // still decoded exactly once, because the branch above returns.\n for (const [k, v] of Object.entries(req.query ?? {})) {\n const raw = typeof v === 'string' ? v : v == null ? null : String(v);\n if (raw !== null) out[decodeComponent(k)] = decodeComponent(raw);\n }\n return out;\n}\n\n/**\n * Percent-decode one query key or value, treating `+` as a space the way a\n * form-encoded query requires.\n *\n * Falls back to the input when it is not valid percent-encoding — a lone `%`\n * is a legitimate character in a search term, and throwing a URIError on it\n * would turn a harmless filter into a 500.\n */\nfunction decodeComponent(value: string): string {\n try {\n return decodeURIComponent(value.replace(/\\+/g, ' '));\n } catch {\n return value;\n }\n}\n\nexport interface AppOptions<D extends SettingsDefaults = SettingsDefaults> {\n /** App name reported on the built-in health route. */\n name?: string;\n /**\n * Built-in `GET /` health route (default true). Responds with the app\n * identity (from the runtime env), status and the registered routes.\n */\n health?: boolean;\n /** Extra payload merged into the health response. */\n healthExtra?: () => Record<string, unknown>;\n /**\n * App settings behind `c.settings()`. Pass the defaults your settings.json\n * declares — they type the resolved object and are what the app runs on if\n * the settings service is unreachable:\n *\n * createApp({ name: 'orders', settings: { defaults: { auto_reserve: true } } })\n *\n * `app` defaults to this app's `name`. Pass a reader built with\n * `createSettings` instead when you want to share it with code outside the\n * router. Omit entirely and `c.settings()` still works — it just has no\n * declared defaults to fall back on.\n */\n settings?: Omit<SettingsOptions<D>, 'app'> & { app?: string } | SettingsReader<D>;\n /**\n * Let a test tenant backdate requests (RAD-311). Off by default. `true`: every\n * POST/PUT/PATCH/DELETE route accepts a past moment as `at` in its body and\n * runs on that clock (`c.now()`, `now()`, `clock()`). The object form adds\n * per-route field aliases (`routes`), routes never backdated (`exclude`) and\n * `strip`. Honoured only when the tenant header matches the identity token's\n * `tenant_id` and the tenant's `allow_backdating` setting is on; otherwise\n * the field is ignored. Stamp created rows with `backdatingDb`.\n */\n backdating?: boolean | BackdatingOptions;\n}\n\nexport interface App<D extends SettingsDefaults = SettingsDefaults> {\n get(template: string, handler: Handler<D>): App<D>;\n post(template: string, handler: Handler<D>): App<D>;\n put(template: string, handler: Handler<D>): App<D>;\n patch(template: string, handler: Handler<D>): App<D>;\n delete(template: string, handler: Handler<D>): App<D>;\n on(method: string, template: string, handler: Handler<D>): App<D>;\n /** Registered routes (e.g. for docs or the health response). */\n routes(): { method: string; path: string }[];\n /** The settings reader backing `c.settings()` (e.g. to clear its cache). */\n settings: SettingsReader<D>;\n /** Build the function entrypoint: `module.exports = app.handler()`. */\n handler(): (context: FnContext) => Promise<unknown>;\n}\n\nconst isSettingsReader = <D extends SettingsDefaults>(\n value: NonNullable<AppOptions<D>['settings']>,\n): value is SettingsReader<D> => typeof (value as SettingsReader<D>).get === 'function';\n\nconst tracer = trace.getTracer('@revenexx/app-sdk');\n\n/** Case-insensitive W3C trace-context extraction from the function's headers. */\nconst headerGetter: TextMapGetter<Record<string, string>> = {\n keys: (carrier) => Object.keys(carrier ?? {}),\n get: (carrier, key) => headerOf(carrier, key) || undefined,\n};\n\nexport function createApp<D extends SettingsDefaults = SettingsDefaults>(options: AppOptions<D> = {}): App<D> {\n const routes: CompiledRoute<D>[] = [];\n const health = options.health !== false;\n const strip = typeof options.backdating === 'object' && options.backdating.strip === true;\n // The app knows its own name, so the settings reader does not have to be told\n // it. One reader per app, created once: the cache lives on it.\n const settings: SettingsReader<D> =\n options.settings && isSettingsReader(options.settings)\n ? options.settings\n : createSettings<D>({ app: options.name, ...(options.settings ?? {}) });\n\n const app: App<D> = {\n settings,\n get: (t, h) => app.on('GET', t, h),\n post: (t, h) => app.on('POST', t, h),\n put: (t, h) => app.on('PUT', t, h),\n patch: (t, h) => app.on('PATCH', t, h),\n delete: (t, h) => app.on('DELETE', t, h),\n on(method, template, handler) {\n const segments = compileTemplate(template);\n routes.push({\n method: method.toUpperCase(),\n template,\n segments,\n literals: segments.filter((s) => s.lit !== undefined).length,\n handler,\n backdating: backdatingFields(options.backdating, method, template),\n });\n // Literal-first: more literal segments = more specific = tried first.\n routes.sort((a, b) => b.literals - a.literals);\n return app;\n },\n routes: () => routes.map((r) => ({ method: r.method, path: r.template })).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)),\n handler() {\n return (context: FnContext) => {\n const { req, res } = context;\n const headers = req.headers ?? {};\n const method = (req.method ?? 'GET').toUpperCase();\n const rawPath = String(req.path ?? '/').split('?')[0]!;\n const path = rawPath.replace(/\\/+$/, '') || '/';\n\n // Continue the caller's trace (gateway/site) when a traceparent is forwarded;\n // otherwise this SERVER span roots a fresh trace. Outbound PostgREST fetches\n // become child CLIENT spans via the undici instrumentation (see ./instrument).\n const parentCtx = propagation.extract(otelContext.active(), headers, headerGetter);\n\n return tracer.startActiveSpan(\n `${method} ${path}`,\n { kind: SpanKind.SERVER, attributes: { 'http.request.method': method, 'url.path': path } },\n parentCtx,\n async (span: Span) => {\n const contextToken = headerOf(headers, 'x-revenexx-context');\n const tenant =\n headerOf(headers, 'x-revenexx-tenant') ||\n (decodeClaims(contextToken).tenant_id as string | undefined) ||\n null;\n if (options.name) span.setAttribute('revenexx.app', options.name);\n if (tenant) span.setAttribute('revenexx.tenant', tenant);\n const log = (m: string) => context.log?.(m);\n\n log(`${options.name ?? 'app'} ${method} ${path} — tenant=${tenant ?? 'none'}`);\n\n try {\n if (health && path === '/' && method === 'GET') {\n span.setAttribute('http.route', '/');\n return res.json({\n app: {\n id: process.env.REVENEXX_APP_ID ?? null,\n name: options.name ?? process.env.REVENEXX_APP_NAME ?? null,\n deployment: process.env.REVENEXX_APP_DEPLOYMENT ?? null,\n runtime: `${process.env.REVENEXX_APP_RUNTIME_NAME ?? ''}-${process.env.REVENEXX_APP_RUNTIME_VERSION ?? ''}`,\n },\n status: 'ok',\n routes: app.routes(),\n timestamp: new Date().toISOString(),\n ...(options.healthExtra?.() ?? {}),\n });\n }\n\n const reqSegs = splitPath(path);\n let matched: { route: CompiledRoute<D>; params: Record<string, string> } | null = null;\n let pathExists = false;\n for (const route of routes) {\n const params = matchSegments(route.segments, reqSegs);\n if (!params) continue;\n pathExists = true;\n if (route.method === method) {\n matched = { route, params };\n break;\n }\n }\n\n if (!matched) {\n const status = pathExists ? 405 : 404;\n span.setAttribute('http.response.status_code', status);\n span.setStatus({ code: SpanStatusCode.ERROR, message: pathExists ? 'method not allowed' : 'no route' });\n if (pathExists) {\n return res.json(refusalBody(`method ${method} not allowed for ${path}`, 'method_not_allowed'), 405);\n }\n return res.json({ ...refusalBody(`no route for ${method} ${path}`, 'no_route'), routes: app.routes() }, 404);\n }\n\n span.updateName(`${method} ${matched.route.template}`);\n span.setAttribute('http.route', matched.route.template);\n\n // Gateway-extracted params (x-capability-params) win over our own match\n // for safety, but they should always agree.\n let gatewayParams: Record<string, string> = {};\n try {\n gatewayParams = JSON.parse(headerOf(headers, 'x-capability-params') || '{}') as Record<string, string>;\n } catch {\n gatewayParams = {};\n }\n\n const c: RouteContext<D> = {\n ctx: context,\n req,\n method,\n path,\n params: { ...matched.params, ...gatewayParams },\n query: parseQuery(req),\n body: parseBody(req),\n tenant,\n contextToken,\n header: (name) => headerOf(headers, name),\n actor: actorFrom((name) => headerOf(headers, name)),\n market: marketFrom((name) => headerOf(headers, name)),\n log,\n json: (data, statusCode = 200) => res.json(data, statusCode),\n // The market rides on the request, so a market-scoped setting\n // resolves for the market this call is for — no argument needed.\n settings: (readOptions) => settings.get(c, readOptions),\n settingsSnapshot: (readOptions) => settings.load(c, readOptions),\n setSettings: (values, writeOptions) => settings.set(c, values, writeOptions),\n now: nowIso,\n clock: clockNow,\n };\n\n const fields = matched.route.backdating;\n if (!fields) return await matched.route.handler(c);\n // The gate (an async settings read) is resolved before the handler\n // starts, so the whole handler runs on one clock.\n const at = await requestedMoment(c, fields);\n if (at) {\n span.setAttribute('revenexx.backdated_at', at);\n if (strip) {\n const body = { ...c.body };\n for (const field of fields) delete body[field];\n c.body = body;\n }\n }\n const route = matched.route;\n return await runAt(at, () => route.handler(c));\n } catch (err) {\n if (isHttpError(err)) {\n span.setAttribute('http.response.status_code', err.status);\n if (err.code) span.setAttribute('revenexx.error.code', err.code);\n if (err.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n // The diagnosis (table names, constraint names, the raw\n // PostgREST body) stays on this side of the wire: logged and\n // traced, never serialised into the response.\n if (err.serverDetail !== undefined) {\n const detail =\n typeof err.serverDetail === 'string' ? err.serverDetail : JSON.stringify(err.serverDetail);\n span.setAttribute('revenexx.error.detail', detail);\n context.error?.(`${method} ${path} — ${err.status} ${err.message}: ${detail}`);\n }\n return res.json(refusalBody(err.message, err.code, err.details), err.status);\n }\n // Anything that is not an HttpError is a fault, not an answer: its\n // message may carry internals (a stack's TypeError, a table name),\n // so it is logged and traced, and the caller gets a fixed body.\n // Another App's refusal nobody caught: still a fault here, but log what\n // the far side said rather than the platform client's empty message.\n const upstream = refusalOf(err);\n const msg = upstream\n ? `refused by ${upstream.app ?? 'another app'}: ${upstream.status} ${upstream.code ?? ''} ${upstream.message}`.replace(/\\s+/g, ' ')\n : err instanceof Error\n ? err.message\n : String(err);\n span.setAttribute('http.response.status_code', 500);\n span.recordException(err instanceof Error ? err : new Error(msg));\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n context.error?.(`unhandled error on ${method} ${path}: ${msg}`);\n return res.json(refusalBody('internal error', 'internal_error'), 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * Who is acting — the person behind a request, as the platform established\n * them.\n *\n * An app has always been told which TENANT a call is for. Which PERSON was a\n * different question, and for a long time it had no answer: the brokered\n * context identifies the calling system (in a theme site, the theme's service\n * user — a robot with no name), the gateway strips inbound identity headers\n * because they are forgeable, and anything in the request body is the caller's\n * own word about itself. Apps that needed a person resolved one out of the\n * context's email claim and hoped, or read an `_actor` out of the body and\n * called it attribution rather than authentication, because that is all it was.\n *\n * The gateway now states it (RAD-12), on two planes:\n *\n * - ASSERTED. A storefront call is made by a server — the theme BFF, holding\n * the tenant API key — on behalf of a customer. The credential proves the\n * tenant, so the caller names the person and the gateway resolves that name\n * through the tenant's role provider. It defends against a malicious end\n * user, not against a compromised BFF.\n * - AUTHENTICATED. A Cockpit call, or any call carrying a person's own\n * Zitadel token, needs nobody's word: the signature and issuer were\n * verified before a route was matched, and the contact — if there is one —\n * was resolved from that proven subject.\n *\n * Both arrive in the same headers, which is exactly why `trust` exists. The\n * same `contact` is a signature on one plane and a label on the other, and an\n * app deciding an approval has to be able to tell the two apart. An app that\n * only attributes — a \"last edited by\" — can ignore it.\n *\n * A third person arrives the same way (ADR-0132 §9): a SALES REP.\n * The rep portal's server asserts `rep:<rep_code>`, the gateway resolves it\n * through the `sales-reps` app's role provider, and injects\n * `X-Revenexx-Caller: rep`, `X-Revenexx-Rep` (the rep code) and the\n * permissions — never the contact headers. A rep is always ASSERTED, and\n * reads as the `rep` plane.\n *\n * The record-history envelope (`X-Revenexx-Audit`) is not read here. It is\n * Baseline's evidence, not the app's: the adapters forward it to the data\n * plane unchanged (adapters/runtime.ts, adapters/remote.ts), and the gateway\n * signs a rep into it the same way it signs a contact.\n *\n * Every header read here is set ONLY by the gateway: it builds a fresh header\n * set per dispatch and strips any copy a caller sent. So `actor.trust` cannot\n * be talked up from outside, and an app never has to decide whether to believe\n * a header — only what to do with what it says.\n */\n\n/** How the platform came to know who is acting. */\nexport type ActorTrust = 'authenticated' | 'asserted' | 'none';\n\n/**\n * Which side of the platform the caller is on.\n *\n * - `contact` — one of the tenant's own people: a buyer, an approver.\n * - `rep` — one of the merchant's sales reps, asserted by the rep portal and\n * named by their rep code (ADR-0132). Not a buyer: a rep acting FOR a buyer\n * does so through a buyer session, which is the `contact` plane.\n * - `operator` — a human the PLATFORM knows and the tenant's records do not.\n * Back office: Cockpit staff, support, a partner operating the tenant. There\n * is no contact to check a per-row rule against, and that absence is the\n * signal, not a failure to resolve one.\n * - `system` — nobody: a schedule, a webhook, a service token, an in-mesh call.\n *\n * This is the distinction apps otherwise make by hand, badly — usually by\n * treating \"no contact resolved\" as \"must be the platform\", which is also what\n * an unknown customer looks like.\n */\nexport type ActorPlane = 'rep' | 'contact' | 'operator' | 'system';\n\n/** The acting person, as far as the platform can state it. */\nexport interface Actor {\n /** The authenticated human's platform subject, or null when none was proven. */\n user: string | null;\n /** Their email claim, or null. Attribution — never a lookup key to trust on its own. */\n email: string | null;\n /** The `customers` contact the platform resolved them to, or null. Always null for a rep. */\n contact: string | null;\n /** That contact's organization, or null. Always null for a rep. */\n organization: string | null;\n /**\n * The sales rep's code when the gateway resolved a rep (`X-Revenexx-Caller:\n * rep` with `X-Revenexx-Rep`), or null. Set only when both arrive.\n */\n rep: string | null;\n /** The permissions the tenant's role provider granted them. Empty when there is no contact or rep. */\n permissions: string[];\n /** How well `contact` is known. `none` when nobody was established at all. */\n trust: ActorTrust;\n /** Which side of the platform the caller is on. */\n plane: ActorPlane;\n /** Does this actor hold the permission? False for every permission when nobody is acting. */\n holds(permission: string): boolean;\n /**\n * Is this a person the platform itself authenticated?\n *\n * The one check a per-person rule should make. An app enforcing \"only the\n * approver this approval names may decide it\" needs a signature, and only\n * this plane produces one.\n */\n authenticated(): boolean;\n}\n\n/** Gateway-set headers. Named here so a reader can grep the wire format. */\nexport const ACTOR_HEADERS = {\n user: 'x-revenexx-actor',\n email: 'x-revenexx-actor-email',\n trust: 'x-revenexx-actor-trust',\n contact: 'x-revenexx-contact',\n organization: 'x-revenexx-organization',\n permissions: 'x-revenexx-permissions',\n /** `contact` or `rep` — the kind of person the gateway resolved. */\n caller: 'x-revenexx-caller',\n /** The rep's code, beside `caller: rep`, percent-encoded as UTF-8 (RFC 3986). */\n rep: 'x-revenexx-rep',\n} as const;\n\nconst nullIfEmpty = (v: string): string | null => (v.trim() === '' ? null : v.trim());\n\n/**\n * The rep header carries the code percent-encoded as UTF-8, because a rep code\n * may be non-ASCII (`MÜLLER-01`) and a header value is not guaranteed to carry\n * UTF-8 bytes intact. A value that does not decode is no rep.\n */\nconst decodeRep = (v: string | null): string | null => {\n if (v === null) return null;\n try {\n return nullIfEmpty(decodeURIComponent(v));\n } catch {\n return null;\n }\n};\n\n/**\n * Read the acting person out of a request's headers.\n *\n * Unknown values of the trust header degrade to `asserted` rather than to\n * `authenticated`: a gateway that learns a third plane must not silently\n * promote it past a signature check written today.\n */\nexport function actorFrom(header: (name: string) => string | undefined): Actor {\n // A caller outside a handler has its own header bag — a Node request answers\n // `undefined` for a header nobody sent and an array for one sent twice. Read\n // everything through here so neither shape reaches a `.trim()`.\n const read = (name: string): string => {\n const v = header(name);\n return typeof v === 'string' ? v : '';\n };\n\n const user = nullIfEmpty(read(ACTOR_HEADERS.user));\n\n // A rep needs both halves: the caller kind and the code. `rep` beside no\n // code is a principal half-stated, and reads as no rep — degrade, never\n // promote. The contact headers are gated on the caller KIND, not on the\n // code: a call that says `rep` is never read as a contact, with or without\n // a code. The gateway never sends both, and if both arrive the conservative\n // reading is the narrower one, because a rep that is read as a contact\n // would pass a buyer's per-row rules on a buyer's id.\n const isRepCall = read(ACTOR_HEADERS.caller).trim().toLowerCase() === 'rep';\n const rep = isRepCall ? decodeRep(nullIfEmpty(read(ACTOR_HEADERS.rep))) : null;\n const contact = isRepCall ? null : nullIfEmpty(read(ACTOR_HEADERS.contact));\n const organization = isRepCall ? null : nullIfEmpty(read(ACTOR_HEADERS.organization));\n // The permissions belong to the principal the gateway resolved. A rep call\n // without a code resolved nobody, so it holds nothing.\n const permissions =\n isRepCall && rep === null\n ? []\n : read(ACTOR_HEADERS.permissions)\n .split(',')\n .map((p) => p.trim())\n .filter(Boolean);\n\n // Nobody established: `none`, whatever the header says. An app reading\n // `trust === 'asserted'` must not see it for a call that named no one.\n //\n // And `authenticated` needs the person it authenticated: a trust header\n // arriving beside no subject is a plane half-stated, which degrades like any\n // other value the gateway did not mean.\n const raw = read(ACTOR_HEADERS.trust).trim().toLowerCase();\n //\n // A rep is asserted by the rep portal's server, so a rep call is never\n // `authenticated`, whatever a trust header says — with or without a code.\n const trust: ActorTrust =\n user === null && contact === null && rep === null\n ? 'none'\n : !isRepCall && user !== null && raw === 'authenticated'\n ? 'authenticated'\n : 'asserted';\n\n const plane: ActorPlane =\n rep !== null ? 'rep' : contact !== null ? 'contact' : user !== null ? 'operator' : 'system';\n const held = new Set(permissions);\n\n return {\n user,\n email: nullIfEmpty(read(ACTOR_HEADERS.email)),\n contact,\n organization,\n rep,\n permissions,\n trust,\n plane,\n holds: (permission) => permission !== '' && held.has(permission),\n authenticated: () => trust === 'authenticated',\n };\n}\n","/**\n * The market a request is for, and the country that market ships from.\n *\n * The gateway forwards the caller's market as `X-Revenexx-Market` and, since\n * PE-1010, resolves the market's `ship_from_country` (markets app, RAD-246)\n * and sets it as `X-Revenexx-Market-Country`. The country header is\n * gateway-injected: a caller's copy never reaches the App, so it can be read\n * the way the tenant is read.\n *\n * An App prints a document's addresses for the sender country — the\n * document's own sender address when it has one, else `c.market.country`.\n * When the gateway could not resolve one (no markets app, a market that names\n * no country yet, an older gateway), `country` is null and the App falls back\n * to its own rule.\n */\n\n/** The market a request is for. */\nexport interface Market {\n /** The market code (`X-Revenexx-Market`), or null when the call names none. */\n code: string | null;\n /**\n * The ISO 3166-1 alpha-2 country the market ships from\n * (`X-Revenexx-Market-Country`), or null. Never set without a market.\n */\n country: string | null;\n}\n\n/** The two headers, as the gateway sets them. */\nexport const MARKET_HEADERS = {\n code: 'x-revenexx-market',\n country: 'x-revenexx-market-country',\n} as const;\n\nconst COUNTRY = /^[A-Z]{2}$/;\n\n/**\n * Read the market off a header reader. A blank market is no market; a country\n * that is not two upper-case letters, or one without a market, is null.\n */\nexport function marketFrom(header: (name: string) => string | undefined | null): Market {\n const code = (header(MARKET_HEADERS.code) ?? '').trim() || null;\n const raw = (header(MARKET_HEADERS.country) ?? '').trim();\n const country = code && COUNTRY.test(raw) ? raw : null;\n return { code, country };\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';\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 * 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","/**\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","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 * CRUD route mounting: wire a generated entity client to REST routes in one\n * call, with the platform's standard list/get/create/update/delete semantics.\n *\n * const app = createApp({ name: 'markets' });\n * const db = createDb({ adapter: 'runtime', context });\n *\n * mountCrud(app, db.markets, { path: '/markets', columns: ENTITIES.markets.columns });\n * mountCrud(app, db.locales, {\n * path: '/markets/{marketId}/locales',\n * columns: ENTITIES.locales.columns,\n * parent: { param: 'marketId', column: 'market_id' },\n * });\n *\n * Nested resources (a `parent` option) scope every operation to the parent row:\n * lists filter by the parent column, creates inject it, and reads/writes 404\n * when the row belongs to a different parent.\n */\n\nimport type { Page, Query, Row } from '../types.js';\nimport { HttpError, notFound, type App, type RouteContext } from './router.js';\nimport { EMPTY_UPDATE_MESSAGE, updateFields } from '../patch.js';\nimport { OPS } from '../query.js';\nimport type { SettingsDefaults } from '../settings.js';\n\n/** Structural subset of the SDK's EntityClient — any compatible repo works. */\nexport interface RepoLike {\n list(query?: Query): Promise<Row[]>;\n page?(query?: Query): Promise<Page>;\n get(id: string | number): Promise<Row | null>;\n create(data: Row): Promise<Row>;\n update(id: string | number, patch: Row): Promise<Row>;\n delete(id: string | number): Promise<void>;\n}\n\nexport interface CrudOptions {\n /** Route base path, e.g. `/markets` or `/markets/{marketId}/locales`. */\n path: string;\n /**\n * Column metadata (from the generated ENTITIES) — enables `?col=value` list\n * filters. A list query key that is neither a column, a reserved key\n * (`limit`, `offset`, `order`) nor declared in `queryParams` is refused with\n * `400 unknown_filter`. Without `columns`, only those keys are accepted.\n */\n columns?: Record<string, unknown>;\n /**\n * Extra list query parameters the App handles itself (e.g. read by\n * middleware, a wrapping handler, or simply tolerated). The list route\n * accepts them and does NOT turn them into filters — they never reach the\n * data plane and are not echoed in `filter`.\n *\n * mountCrud(app, db.accounts, {\n * path: '/punchout/accounts',\n * columns: ENTITIES.accounts.columns,\n * queryParams: ['include_secrets'],\n * });\n */\n queryParams?: string[];\n /**\n * Nested-resource scoping: path param name + the FK column it maps to.\n *\n * Pass `repo` (the PARENT's repo) to make the collection routes verify the\n * parent exists. Without it, `GET /lists/{unknown-id}/entries` answers `200`\n * with an empty page, which a client cannot tell apart from a parent that\n * genuinely has no children — and `POST` would attach a row to a parent that\n * is not there. The single-row routes never had this gap: `fetchOwned`\n * already 404s on an ownership mismatch.\n *\n * Optional to stay backwards compatible; it costs one extra read per\n * collection request, so it is the app's call.\n */\n parent?: { param: string; column: string; repo?: Pick<RepoLike, 'get'> };\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Pagination bounds for list (defaults: 50, max 200). */\n defaultLimit?: number;\n maxLimit?: number;\n /** Restrict which routes are mounted (default: all five). */\n only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\n/**\n * Query keys the list route reads itself. Always accepted, never filters (a\n * column of the same name is still filtered on as well, as before).\n */\nexport const RESERVED_LIST_QUERY_KEYS: readonly string[] = Object.freeze(['limit', 'offset', 'order']);\n\nconst INT = (v: unknown, d: number): number => {\n const n = parseInt(String(v), 10);\n return Number.isFinite(n) ? n : d;\n};\n\n/** `json` / `jsonb`, read off the generated ENTITIES column metadata. */\nconst isJsonColumn = (def: unknown): boolean =>\n /^jsonb?\\b/i.test(String((def as { type?: unknown } | null | undefined)?.type ?? ''));\n\n/**\n * A filter on a jsonb column is a whole-document equality, so the value has to\n * be a JSON document. `k in opts.columns` never looked at the column *type*, so\n * anything else went to the data plane as `col=eq.<junk>`; Postgres failed the\n * cast (SQLSTATE 22P02) and the caller got a 400 that named neither the\n * parameter nor what a good value looks like:\n *\n * GET /v1/forms?definition=x -> 400 {\"error\":\"a value in the request has\n * the wrong format\",\"code\":\"invalid_value\"}\n *\n * It is our query parameter, so it is our 400. Same status and same `code` as\n * before — only the message becomes actionable, and the round trip disappears.\n * The rule is exactly the data plane's: it must parse as JSON. Postgres compares\n * jsonb semantically, so key order and whitespace stay irrelevant and nothing\n * that worked before stops working — a whole, exactly-serialised document is\n * still forwarded unchanged.\n *\n * Deliberately NOT a containment (`cs.`) filter: `?labels={\"de\":\"Hauptlager\"}`\n * matches one exact document today, and turning that into \"contains\" would\n * silently widen a filter three apps already declare, with examples, as\n * equality. Widening it is a product decision, not a bug fix.\n *\n * The message states the rule and does NOT show an instance of the document.\n * It cannot: the generated column metadata carries `type`, `notNull` and\n * sometimes `default`, and nothing about the shape — 22 of the 25 jsonb\n * columns in `products` have no default at all. The first version borrowed\n * one column's example for every column, so a filter on an array-shaped\n * document (`family_variants.axes`, `measurement_families.units`) was\n * illustrated with an object. A caller who copies that shape sends valid JSON,\n * so there is no 400 — the answer is 200 with zero rows, which is the worst\n * failure this API has. The honest example is per column, the app knows it,\n * and it is already published on the parameter; so point there instead of\n * inventing one here.\n */\nfunction assertJsonFilter(column: string, value: string): void {\n try {\n JSON.parse(value);\n } catch {\n throw new HttpError(\n 400,\n `filter '${column}' must be a whole JSON document, serialized exactly as stored ` +\n `and compared for equality — not a path or containment query. ` +\n `This parameter's example in the API contract shows the shape this column holds.`,\n undefined,\n { code: 'invalid_value' },\n );\n }\n}\n\n/**\n * A list query key that names no column used to be dropped, so a wrong filter\n * answered `200` with the UNFILTERED list — indistinguishable, to a caller that\n * does not inspect `filter`, from a correct one. Measured damage:\n * `GET /customers/segments?organization_id=…` (segments has no such column)\n * handed promotions every segment of the tenant. A filter we cannot apply is a\n * caller's mistake, so it is our 400, naming the key(s) and what is accepted.\n */\nfunction assertKnownKeys(query: Record<string, string>, opts: CrudOptions): void {\n const columns = opts.columns ?? {};\n const extra = opts.queryParams ?? [];\n const known = (k: string): boolean =>\n Object.prototype.hasOwnProperty.call(columns, k) || RESERVED_LIST_QUERY_KEYS.includes(k) || extra.includes(k);\n const unknown = Object.keys(query).filter((k) => !known(k));\n if (unknown.length === 0) return;\n const allowed = [...new Set([...Object.keys(columns), ...RESERVED_LIST_QUERY_KEYS, ...extra])].sort();\n const quoted = unknown.map((k) => `'${k}'`).join(', ');\n throw new HttpError(\n 400,\n `unknown list filter ${quoted} — not a column of this resource. ` +\n `A filter that cannot be applied is refused rather than ignored; see details.allowed.`,\n { unknown, allowed },\n { code: 'unknown_filter' },\n );\n}\n\n/** `in.`, `eq.`, `not.` … — a PostgREST operator prefix, as a caller would write one. */\nconst OPERATOR_PREFIX = new RegExp(`^(?:not|${[...OPS].join('|')})\\\\.`);\n\n/**\n * A list filter is an exact value: `toParams` sends the string as `eq.<value>`.\n * A caller who writes PostgREST syntax (`?sku=in.(a,b)`) therefore got\n * `sku=eq.in.(a,b)` — `200` with zero rows, which reads as \"none of those\n * exist\". Measured damage: punchout resolved every product of an inbound cart\n * that way and found none (RAD-160). An exact value that genuinely starts with\n * `in.` or `eq.` is implausible, so a value carrying an operator prefix is our\n * 400 rather than a silent miss. Only column filters are checked: `queryParams`\n * and the reserved keys never reach `where`.\n */\nfunction assertNoOperator(column: string, value: string): void {\n if (!OPERATOR_PREFIX.test(value)) return;\n throw new HttpError(\n 400,\n `filter '${column}' carries an operator ('${value.slice(0, value.indexOf('.') + 1)}') — ` +\n `a list filters by exact value only; operators and value lists are not supported.`,\n { parameter: column },\n { code: 'unsupported_filter_operator' },\n );\n}\n\nfunction parentWhere(c: RouteContext, parent?: CrudOptions['parent']): Record<string, string> {\n if (!parent) return {};\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`, undefined, { code: 'missing_parameter' });\n return { [parent.column]: value };\n}\n\n/**\n * 404 when the nested parent does not exist, so an unknown parent is not\n * reported as an empty collection. No-op unless the app supplied `parent.repo`.\n */\nasync function assertParentExists(c: RouteContext, parent?: CrudOptions['parent']): Promise<void> {\n if (!parent?.repo) return;\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`, undefined, { code: 'missing_parameter' });\n if (!(await parent.repo.get(value))) throw notFound();\n}\n\n/** Fetch a row and enforce nested-parent ownership; throws 404 when absent. */\nasync function fetchOwned(\n repo: RepoLike,\n c: RouteContext,\n opts: CrudOptions,\n): Promise<{ id: string; row: Row }> {\n const id = c.params[opts.idParam ?? 'id'] ?? '';\n if (!id) throw new HttpError(400, `missing path parameter '${opts.idParam ?? 'id'}'`, undefined, { code: 'missing_parameter' });\n const row = await repo.get(id);\n if (!row) throw notFound();\n if (opts.parent) {\n const expected = c.params[opts.parent.param];\n if (String(row[opts.parent.column] ?? '') !== String(expected ?? '')) throw notFound();\n }\n return { id, row };\n}\n\nexport function mountCrud<D extends SettingsDefaults = SettingsDefaults>(\n app: App<D>,\n repo: RepoLike,\n opts: CrudOptions,\n): App<D> {\n const base = opts.path.replace(/\\/+$/, '');\n const idTemplate = `${base}/{${opts.idParam ?? 'id'}}`;\n const enabled = new Set(opts.only ?? ['list', 'get', 'create', 'update', 'delete']);\n const defaultLimit = opts.defaultLimit ?? 50;\n const maxLimit = opts.maxLimit ?? 200;\n\n if (enabled.has('list')) {\n app.get(base, async (c) => {\n // Refuse before any round trip — including the parent lookup.\n assertKnownKeys(c.query, opts);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n // Reserved / app-declared keys that are not columns are not filters.\n if (!opts.columns || !Object.prototype.hasOwnProperty.call(opts.columns, k)) continue;\n assertNoOperator(k, v);\n if (isJsonColumn(opts.columns[k])) assertJsonFilter(k, v);\n where[k] = v;\n }\n await assertParentExists(c, opts.parent);\n // The nested-parent filter always wins — a query param must not widen\n // the scope beyond the parent in the path.\n Object.assign(where, parentWhere(c, opts.parent));\n const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);\n const offset = Math.max(INT(c.query.offset, 0), 0);\n const order = typeof c.query.order === 'string' && c.query.order ? c.query.order : undefined;\n const query: Query = { where, limit, offset, ...(order ? { order } : {}) };\n\n if (repo.page) {\n const { items, total } = await repo.page(query);\n return c.json({\n items,\n page: { limit, offset, total, returned: items.length, hasMore: offset + items.length < total },\n filter: where,\n });\n }\n const items = await repo.list(query);\n return c.json({ items, page: { limit, offset, returned: items.length }, filter: where });\n });\n }\n\n if (enabled.has('create')) {\n app.post(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const data = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.create(data), 201);\n });\n }\n\n if (enabled.has('get')) {\n app.get(idTemplate, async (c) => {\n const { row } = await fetchOwned(repo, c, opts);\n return c.json(row);\n });\n }\n\n if (enabled.has('update')) {\n app.put(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n // A body carrying no fields of its own is not an update. The rule itself\n // lives in ../patch.ts and is enforced by the data client, so Apps that\n // hand-write their PUT handler get it too; this check stays because it is\n // the only one that can see the *body* rather than the merged patch —\n // with a nested parent the merge always carries the FK, so the patch is\n // never literally empty — and because it answers without a round trip.\n if (updateFields(c.body).length === 0) throw new HttpError(400, EMPTY_UPDATE_MESSAGE, undefined, { code: 'empty_update' });\n // Never let a body overwrite the nested-parent FK.\n const patch = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.update(id, patch));\n });\n }\n\n if (enabled.has('delete')) {\n app.delete(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n await repo.delete(id);\n return c.json({ deleted: true, id });\n });\n }\n\n return app;\n}\n","/**\n * The trash, as one helper: `mountTrash` gives an entity the three routes and\n * the purge job every trash needs (PE-1022).\n *\n * const trash = mountTrash(app, db.organizations, {\n * path: '/organizations',\n * children: [{ name: 'contacts', repo: db.contacts, column: 'organization_id' }],\n * guard: (org) => (org.is_default ? { reason: 'The default organization stays.' } : null),\n * blockers: async (org, c) => [\n * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),\n * ],\n * });\n *\n * // the scheduled job (ADR-0103), once per tenant:\n * await trash.purge(c);\n *\n * The routes:\n *\n * DELETE <path>/{id} live row → into the trash, with its children\n * trashed row → deleted for good, through `blockers`\n * POST <path>/{id}/restore back out of the trash, with the children it took\n *\n * The entity needs `trash: true` in schema.json, which gives it `deleted_at`,\n * `deleted_by`, `deleted_by_id`, `trash_batch` and `purge_blocked_reason`.\n * Baseline does the rest of the\n * platform side: lookups leave trashed rows out, the event trigger says\n * `*.trashed` / `*.restored` (declare them with `on: [\"trash\"]` /\n * `on: [\"restore\"]`), and a real DELETE is `*.deleted`.\n *\n * Two rules this helper exists to keep:\n *\n * - The final delete has ONE code path. The second DELETE and the purge job\n * both go through `deleteForGood`, so a blocker the app declares cannot be\n * bypassed by waiting 90 days.\n * - A blocker that cannot be checked blocks. A guard that throws, or a count\n * the gateway would not answer, is a reason to keep the row, never a\n * reason to delete it.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { Row } from '../types.js';\nimport type { Actor } from './actor.js';\nimport { HttpError, notFound, type App } from './router.js';\nimport type { RepoLike } from './crud.js';\nimport { DEFAULT_GATEWAY_ENDPOINT, type SettingsDefaults, type SettingsSource } from '../settings.js';\n\n/** The column whose value says \"in the trash\". */\nexport const TRASH_COLUMN = 'deleted_at';\n\n/** Trash retention when Baseline holds no value for the tenant (RAD-247, ADR-0114). */\nexport const DEFAULT_TRASH_RETENTION_DAYS = 90;\n\n/** The column `trash: true` gives an entity for why the purge left a row in the trash. */\nexport const PURGE_REASON_COLUMN = 'purge_blocked_reason';\n\n/** The gateway route the tenant's retention is read from (PE-1022). */\nexport const AUDIT_SETTINGS_PATH = '/v1/audit/settings';\n\n/** Why a row may not go into the trash, or may not be deleted for good. */\nexport interface Blocker {\n /** One sentence for the person who asked. */\n reason: string;\n /** How many records stand in the way, when it is a count. */\n count?: number;\n /** `unverifiable` when the check itself failed; anything else is the app's. */\n code?: string;\n details?: unknown;\n}\n\n/**\n * Who asks, as far as a check needs it. A handler's `c` is one; so is the\n * purge job's source.\n */\nexport interface TrashCaller extends SettingsSource {\n tenant?: string | null;\n actor?: Actor;\n header?(name: string): string;\n}\n\n/** A guard or blocker check. Return nothing, one blocker or several. */\nexport type BlockerCheck = (\n row: Row,\n caller: TrashCaller,\n) => Blocker | null | undefined | (Blocker | null | undefined)[] | Promise<Blocker | null | undefined | (Blocker | null | undefined)[]>;\n\n/** Rows that go into the trash with their parent and come back with it. */\nexport interface TrashChild {\n /** Key in the answer's `took`, e.g. `contacts`. */\n name: string;\n repo: Pick<RepoLike, 'list' | 'update' | 'delete'>;\n /** The child's column holding the parent id. */\n column: string;\n}\n\nexport interface TrashOptions {\n /** Base path of the entity, e.g. `/organizations`. */\n path: string;\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Dependent rows that form one group with the parent (contacts, sub-categories, variants). */\n children?: TrashChild[];\n /**\n * May the row go into the trash? Only the default record and a running\n * process that would break (an open approval, an active punchout account)\n * belong here; everything else is a warning for the dialog, not a blocker.\n */\n guard?: BlockerCheck;\n /**\n * May the row be deleted for good? Checked on the second DELETE and by the\n * purge job alike: references from open processes, configuration that names\n * the row. Cross-app references are counted through the gateway\n * (`createGatewayCounter`).\n */\n blockers?: BlockerCheck;\n /** Who may delete for good. Default: whoever may call the route. */\n canDeleteForGood?: (caller: TrashCaller) => boolean;\n /**\n * A parent that has to be live for this row to come back, e.g. a contact's\n * organization. Restoring a row whose parent is in the trash is refused.\n */\n parent?: { repo: Pick<RepoLike, 'get'>; column: string };\n /**\n * The final delete of the row itself. Default `repo.delete(id)`. Children\n * of the row's group are deleted before it either way.\n */\n deleteRow?: (row: Row, caller: TrashCaller) => Promise<void>;\n /**\n * The text column the purge writes the blocked reason into, and a restore\n * clears. Default `purge_blocked_reason`, which `trash: true` creates; `false`\n * for an entity that has no such column.\n */\n purgeReasonColumn?: string | false;\n /**\n * App-fired events. Prefer Baseline's trigger for `trashed` / `restored`\n * (`on: [\"trash\"]` / `on: [\"restore\"]`) — it is transactional. Name them\n * here only for an entity that has no such trigger; declaring both\n * publishes twice. `purged` is one summary per purge run.\n */\n events?: {\n emit: (name: string, data: Row, options?: { topicId?: string | null; eventId?: string }) => Promise<unknown>;\n trashed?: string;\n restored?: string;\n purged?: string;\n };\n /** Reading the tenant's trash retention through the gateway. */\n retention?: RetentionOptions;\n /** Clock (tests). */\n now?: () => Date;\n}\n\n/**\n * Where and how the retention is read. The URL is, first match wins: `url`,\n * REVENEXX_AUDIT_SETTINGS_URL, or `{endpoint}/v1/audit/settings` with\n * `endpoint` defaulting to REVENEXX_GATEWAY_ENDPOINT or the platform gateway.\n */\nexport interface RetentionOptions {\n /** The full settings URL. */\n url?: string;\n /** Gateway base URL. */\n endpoint?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n env?: Record<string, string | undefined>;\n}\n\n/** What one purge run did. */\nexport interface PurgeResult {\n /** True when the run did nothing because the retention could not be read. */\n skipped: boolean;\n reason?: string;\n retentionDays?: number;\n /** Rows trashed before this instant were due. */\n cutoff?: string;\n purged: string[];\n blocked: { id: string; blockers: Blocker[] }[];\n}\n\nexport interface TrashHandle {\n /** Put a row into the trash, with its children. Throws the same refusals as the route. */\n trash(id: string, caller: TrashCaller): Promise<{ id: string; batch: string; took: Record<string, number> }>;\n /** Take a row and its group back out of the trash. */\n restore(id: string, caller: TrashCaller): Promise<{ id: string; took: Record<string, number> }>;\n /** Delete a trashed row for good, through the blockers. */\n deleteForGood(id: string, caller: TrashCaller): Promise<{ id: string; took: Record<string, number> }>;\n /** The purge job: delete for good what is past the tenant's retention. Never throws for a single row. */\n purge(caller: TrashCaller, options?: { max?: number }): Promise<PurgeResult>;\n}\n\nconst PAGE = 200;\n\nconst isTrashed = (row: Row): boolean => row[TRASH_COLUMN] !== null && row[TRASH_COLUMN] !== undefined;\n\nconst idOf = (row: Row, fallback: string): string => String(row.id ?? fallback);\n\n/** Every row matching `where`, page by page — a group is never cut off at 50. */\nasync function listAll(repo: Pick<RepoLike, 'list'>, where: Row): Promise<Row[]> {\n const rows: Row[] = [];\n for (;;) {\n const batch = await repo.list({ where: where as never, limit: PAGE, offset: rows.length });\n rows.push(...batch);\n if (batch.length < PAGE) return rows;\n }\n}\n\n/** Run a check; a throw is a blocker, never a pass. */\nasync function runCheck(check: BlockerCheck | undefined, row: Row, caller: TrashCaller): Promise<Blocker[]> {\n if (!check) return [];\n try {\n const out = await check(row, caller);\n const list = Array.isArray(out) ? out : [out];\n return list.filter((b): b is Blocker => Boolean(b && typeof b.reason === 'string'));\n } catch (err) {\n return [\n {\n reason: `could not be checked: ${err instanceof Error ? err.message : String(err)}`,\n code: 'unverifiable',\n },\n ];\n }\n}\n\nconst refuse = (status: number, message: string, code: string, details?: unknown): HttpError =>\n new HttpError(status, message, details, { code });\n\nfunction headerFrom(caller: TrashCaller, name: string): string {\n if (typeof caller.header === 'function') {\n const v = caller.header(name);\n if (typeof v === 'string' && v !== '') return v;\n }\n const want = name.toLowerCase();\n for (const bag of [caller.req?.headers, caller.headers]) {\n if (!bag) continue;\n for (const [k, v] of Object.entries(bag)) if (k.toLowerCase() === want && typeof v === 'string' && v !== '') return v;\n }\n return '';\n}\n\n/** The URL the retention is read from; see `RetentionOptions`. */\nexport function auditSettingsUrl(options: RetentionOptions = {}): string {\n const env = options.env ?? process.env;\n const url = options.url || env.REVENEXX_AUDIT_SETTINGS_URL;\n if (url) return url;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\\/+$/, '');\n return `${endpoint}${AUDIT_SETTINGS_PATH}`;\n}\n\n/**\n * The tenant's trash retention in days, read through the gateway\n * (`GET /v1/audit/settings`, which Baseline answers). An App holds no Baseline\n * credential; the gateway takes the request's own.\n *\n * Throws when the settings cannot be read: guessing would be the dangerous\n * direction — a tenant that keeps its trash for a year must not lose it after\n * 90 days because a request timed out. The default applies only when the\n * settings answer and hold no value.\n */\nexport async function readTrashRetention(caller: TrashCaller, options: RetentionOptions = {}): Promise<number> {\n const url = auditSettingsUrl(options);\n const f = options.fetchImpl ?? globalThis.fetch;\n const tenant = (caller.tenant ?? '') || headerFrom(caller, 'x-revenexx-tenant');\n if (!tenant) throw new Error('trash retention: no tenant');\n const token = (caller.contextToken ?? '') || headerFrom(caller, 'x-revenexx-context');\n\n const headers: Record<string, string> = { Accept: 'application/json', 'X-Revenexx-Tenant': tenant };\n if (token) headers.Authorization = `Bearer ${token}`;\n const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5_000);\n const res = await f(url, { method: 'GET', headers, ...(signal ? { signal } : {}) });\n if (!res.ok) throw new Error(`trash retention: ${res.status} from ${AUDIT_SETTINGS_PATH}`);\n const body = (await res.json()) as { trash_retention_days?: unknown };\n const days = body.trash_retention_days;\n return typeof days === 'number' && Number.isInteger(days) && days > 0 ? days : DEFAULT_TRASH_RETENTION_DAYS;\n}\n\n/**\n * Mount the trash routes for one entity and return the handle the purge job\n * (and any hand-written route) uses.\n */\nexport function mountTrash<D extends SettingsDefaults = SettingsDefaults>(\n app: App<D>,\n repo: RepoLike,\n opts: TrashOptions,\n): TrashHandle {\n const base = opts.path.replace(/\\/+$/, '');\n const idParam = opts.idParam ?? 'id';\n const children = opts.children ?? [];\n const now = opts.now ?? (() => new Date());\n const reasonColumn = opts.purgeReasonColumn === false ? null : (opts.purgeReasonColumn ?? PURGE_REASON_COLUMN);\n\n const load = async (id: string): Promise<Row> => {\n if (!id) throw refuse(400, `missing path parameter '${idParam}'`, 'missing_parameter');\n const row = await repo.get(id);\n if (!row) throw notFound();\n return row;\n };\n\n const emit = async (name: string | undefined, data: Row, topicId: string | null): Promise<void> => {\n if (!name || !opts.events) return;\n await opts.events.emit(name, data, { topicId });\n };\n\n async function trash(id: string, caller: TrashCaller) {\n const row = await load(id);\n if (isTrashed(row)) throw refuse(409, 'this record is already in the trash', 'already_in_trash');\n\n const blockers = await runCheck(opts.guard, row, caller);\n if (blockers.length) {\n throw refuse(409, `cannot go into the trash: ${blockers.map((b) => b.reason).join('; ')}`, 'trash_blocked', { blockers });\n }\n\n const batch = randomUUID();\n const fields: Row = {\n [TRASH_COLUMN]: now().toISOString(),\n deleted_by: caller.actor?.email ?? caller.actor?.user ?? null,\n deleted_by_id: caller.actor?.user ?? caller.actor?.contact ?? null,\n trash_batch: batch,\n };\n\n await repo.update(id, fields);\n const took: Record<string, number> = {};\n for (const child of children) {\n // Only the live children join the group. One that was trashed on its own\n // earlier keeps its own batch, and stays in the trash on restore.\n const rows = await listAll(child.repo, { [child.column]: id, [TRASH_COLUMN]: null });\n for (const r of rows) await child.repo.update(String(r.id), fields);\n took[child.name] = rows.length;\n }\n\n await emit(opts.events?.trashed, { id, batch, took }, idOf(row, id));\n return { id, batch, took };\n }\n\n async function restore(id: string, caller: TrashCaller) {\n void caller;\n const row = await load(id);\n if (!isTrashed(row)) throw refuse(409, 'this record is not in the trash', 'not_in_trash');\n\n if (opts.parent) {\n const parentId = row[opts.parent.column];\n const parent = parentId == null ? null : await opts.parent.repo.get(String(parentId));\n if (parent && isTrashed(parent)) {\n throw refuse(409, 'its parent is in the trash — restore the parent first', 'parent_in_trash', {\n parent: String(parentId),\n });\n }\n }\n\n const fields: Row = { [TRASH_COLUMN]: null, deleted_by: null, deleted_by_id: null, trash_batch: null };\n\n await repo.update(id, reasonColumn ? { ...fields, [reasonColumn]: null } : fields);\n const took: Record<string, number> = {};\n const batch = row.trash_batch;\n for (const child of children) {\n // Children never carry a purge reason: the purge only writes it onto\n // the row it was asked about.\n const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });\n for (const r of rows) await child.repo.update(String(r.id), fields);\n took[child.name] = rows.length;\n }\n\n await emit(opts.events?.restored, { id, took }, idOf(row, id));\n return { id, took };\n }\n\n async function finalDelete(row: Row, id: string, caller: TrashCaller) {\n const took: Record<string, number> = {};\n const batch = row.trash_batch;\n for (const child of children) {\n const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });\n for (const r of rows) await child.repo.delete(String(r.id));\n took[child.name] = rows.length;\n }\n if (opts.deleteRow) await opts.deleteRow(row, caller);\n else await repo.delete(id);\n return { id, took };\n }\n\n async function deleteForGood(id: string, caller: TrashCaller) {\n const row = await load(id);\n if (!isTrashed(row)) throw refuse(409, 'only a record in the trash can be deleted for good', 'not_in_trash');\n if (opts.canDeleteForGood && !opts.canDeleteForGood(caller)) {\n throw refuse(403, 'deleting for good needs its own permission', 'not_permitted');\n }\n const blockers = await runCheck(opts.blockers, row, caller);\n if (blockers.length) {\n throw refuse(409, `cannot be deleted for good: ${blockers.map((b) => b.reason).join('; ')}`, 'delete_blocked', {\n blockers,\n });\n }\n return finalDelete(row, id, caller);\n }\n\n async function purge(caller: TrashCaller, options: { max?: number } = {}): Promise<PurgeResult> {\n let retentionDays: number;\n try {\n retentionDays = await readTrashRetention(caller, opts.retention);\n } catch (err) {\n return { skipped: true, reason: err instanceof Error ? err.message : String(err), purged: [], blocked: [] };\n }\n\n const cutoff = new Date(now().getTime() - retentionDays * 86_400_000).toISOString();\n const max = options.max ?? 500;\n const due = (await listAll(repo, { [TRASH_COLUMN]: { op: 'lt', value: cutoff } })).slice(0, max);\n\n const result: PurgeResult = { skipped: false, retentionDays, cutoff, purged: [], blocked: [] };\n for (const row of due) {\n const id = String(row.id);\n // A purge is the second DELETE, run by the system: same blockers, same\n // children, same delete. Nothing here may delete what the route would not.\n const blockers = await runCheck(opts.blockers, row, caller);\n if (blockers.length) {\n result.blocked.push({ id, blockers });\n const reason = blockers.map((b) => b.reason).join('; ');\n // Written only when it changed: every write is an `*.updated` event,\n // and a nightly run must not repeat one for a row nobody touched.\n if (reasonColumn && row[reasonColumn] !== reason) {\n try {\n await repo.update(id, { [reasonColumn]: reason });\n } catch {\n /* the reason is a courtesy; the row staying is what matters */\n }\n }\n continue;\n }\n try {\n await finalDelete(row, id, caller);\n result.purged.push(id);\n } catch (err) {\n result.blocked.push({\n id,\n blockers: [{ reason: `delete failed: ${err instanceof Error ? err.message : String(err)}`, code: 'delete_failed' }],\n });\n }\n }\n\n await emit(\n opts.events?.purged,\n { retention_days: retentionDays, cutoff, purged: result.purged.length, blocked: result.blocked.length },\n null,\n );\n return result;\n }\n\n app.delete(`${base}/{${idParam}}`, async (c) => {\n const id = c.params[idParam] ?? '';\n const row = await load(id);\n if (isTrashed(row)) return c.json({ deleted: true, ...(await deleteForGood(id, c)) });\n return c.json({ trashed: true, ...(await trash(id, c)) });\n });\n\n app.post(`${base}/{${idParam}}/restore`, async (c) => {\n return c.json({ restored: true, ...(await restore(c.params[idParam] ?? '', c)) });\n });\n\n return { trash, restore, deleteForGood, purge };\n}\n\n/**\n * Count another App's records through the gateway, for a blocker that crosses\n * an App boundary (\"open orders of this organization\"). Apps never read each\n * other's tables; the owning App's list route answers, and its `page.total` is\n * the count.\n *\n * const refs = createGatewayCounter();\n * blockers: async (org, c) => [\n * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),\n * ]\n *\n * A count the gateway does not give — an error, a timeout, a route that does\n * not report `total` — is `null`, and `blocker` turns `null` into an\n * `unverifiable` blocker. Not knowing is never a pass.\n */\nexport function createGatewayCounter(\n options: { endpoint?: string; timeoutMs?: number; fetchImpl?: typeof fetch; env?: Record<string, string | undefined> } = {},\n) {\n const env = options.env ?? process.env;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\\/+$/, '');\n\n async function count(caller: TrashCaller, path: string, where: Record<string, string | number | boolean> = {}): Promise<number | null> {\n const f = options.fetchImpl ?? globalThis.fetch;\n const qs = new URLSearchParams();\n for (const [k, v] of Object.entries(where)) qs.set(k, String(v));\n qs.set('limit', '1');\n const headers: Record<string, string> = { Accept: 'application/json' };\n const tenant = (caller.tenant ?? '') || headerFrom(caller, 'x-revenexx-tenant');\n if (tenant) headers['X-Revenexx-Tenant'] = tenant;\n const context = (caller.contextToken ?? '') || headerFrom(caller, 'x-revenexx-context');\n if (context) headers.Authorization = `Bearer ${context}`;\n const appContext = headerFrom(caller, 'x-revenexx-app-context');\n if (appContext) headers['x-revenexx-app-context'] = appContext;\n\n try {\n const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5_000);\n const sep = path.includes('?') ? '&' : '?';\n const res = await f(`${endpoint}${path}${sep}${qs.toString()}`, { headers, ...(signal ? { signal } : {}) });\n if (!res.ok) return null;\n const body = (await res.json()) as { page?: { total?: unknown } };\n const total = body?.page?.total;\n return typeof total === 'number' && Number.isFinite(total) ? total : null;\n } catch {\n return null;\n }\n }\n\n async function blocker(\n caller: TrashCaller,\n check: { path: string; where?: Record<string, string | number | boolean>; reason: string },\n ): Promise<Blocker | null> {\n const n = await count(caller, check.path, check.where);\n if (n === null) return { reason: `${check.reason} — could not be checked`, code: 'unverifiable' };\n if (n === 0) return null;\n return { reason: `${n} ${check.reason}`, count: n, code: 'referenced' };\n }\n\n return { count, blocker };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoBA,IAAI,UAAU;AAMd,eAAsB,iBAAgC;AACpD,MAAI,SAAS;AACX;AAAA,EACF;AACA,YAAU;AAEV,QAAM,WACJ,QAAQ,IAAI,oCAAoC,KAAK,QAAQ,IAAI,6BAA6B,KAAK;AACrG,MAAI,CAAC,UAAU;AACb;AAAA,EACF;AAEA,MAAI;AACF,UAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,kBAAkB,GAAG,EAAE,sBAAsB,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,MACxF,OAAO,yBAAyB;AAAA,MAChC,OAAO,0CAA0C;AAAA,MACjD,OAAO,uCAAuC;AAAA,IAChD,CAAC;AAGD,UAAM,MAAM,IAAI,QAAQ;AAAA,MACtB,eAAe,IAAI,kBAAkB;AAAA,MACrC,kBAAkB,CAAC,IAAI,sBAAsB,CAAC;AAAA,IAChD,CAAC;AAED,QAAI,MAAM;AAEV,UAAM,QAAQ,MAAY;AACxB,WAAK,IAAI,SAAS,EAAE,MAAM,MAAM;AAAA,MAEhC,CAAC;AAAA,IACH;AACA,YAAQ,KAAK,WAAW,KAAK;AAC7B,YAAQ,KAAK,UAAU,KAAK;AAAA,EAC9B,SAAS,KAAK;AAEZ,YAAQ;AAAA,MACN;AAAA,MACA,eAAe,QAAQ,IAAI,UAAU;AAAA,IACvC;AAAA,EACF;A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