@revenexx/app-sdk 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/instrument.ts","../../src/router/router.ts","../../src/router/actor.ts","../../src/router/crud.ts"],"sourcesContent":["/**\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 { createSettings } from '../settings.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 /** 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\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}\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\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 // 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 });\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 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 };\n\n return await matched.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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,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,EA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E,MAAM,GAAG,YAAY,GAAG,KAAK,MAAM,EAAE;AAC1D,aAAO,EAAE,KAAK,MAAM,KAAK,OAAO,IAAI,KAAK,CAAC;AAAA,IAC5C,CAAC;AAAA,EACH;AAEA,MAAI,QAAQ,IAAI,QAAQ,GAAG;AACzB,QAAI,OAAO,YAAY,OAAO,MAAM;AAClC,YAAM,EAAE,GAAG,IAAI,MAAM,WAAW,MAAM,GAAG,IAAI;AAC7C,YAAM,KAAK,OAAO,EAAE;AACpB,aAAO,EAAE,KAAK,EAAE,SAAS,MAAM,GAAG,CAAC;AAAA,IACrC,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["items"]}
1
+ {"version":3,"sources":["../../src/instrument.ts","../../src/router/router.ts","../../src/router/actor.ts","../../src/router/market.ts","../../src/router/crud.ts","../../src/router/trash.ts"],"sourcesContent":["/**\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 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\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}\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\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 // 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 });\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 };\n\n return await matched.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 * 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":";;;;;;;;;;;;;;;;;;;;AAoBA,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,QAA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AAC,IAAI,EAAE,SAAS,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC,EAAG,CAAC;AAC1G,UAAI,CAAC,IAAI,GAAI,QAAO;AACpB,YAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,YAAM,QAAQ,MAAM,MAAM;AAC1B,aAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AAAA,IACvE,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,iBAAe,QACb,QACA,OACyB;AACzB,UAAM,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":["items"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/app-sdk",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Typed data client + HTTP router for revenexx Apps. Swappable adapters (mock | remote | runtime) so the same App code runs against in-memory fixtures locally and the real data plane in production.",
5
5
  "license": "MIT",
6
6
  "type": "module",