@revenexx/app-sdk 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/mock.ts","../src/query.ts","../src/adapters/postgrest-error.ts","../src/adapters/remote.ts","../src/adapters/runtime.ts","../src/adapters/index.ts","../src/client.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Adapter, Entity, Query, Row, Page } from '../types.js';\nimport { notFound } from '../errors.js';\nimport { matches } from '../query.js';\n\n/** Apply order → offset → limit → select to an already-filtered row set. */\nfunction shape(rows: Row[], query: Query): Row[] {\n let out = rows;\n if (query.order) {\n const [c, dir = 'asc'] = query.order.split('.');\n const key = c as string;\n out = out.slice().sort((a, b) => (a[key]! < b[key]! ? -1 : a[key]! > b[key]! ? 1 : 0));\n if (dir === 'desc') out.reverse();\n }\n if (query.offset) out = out.slice(query.offset);\n if (Number.isInteger(query.limit)) out = out.slice(0, query.limit);\n if (Array.isArray(query.select) && query.select.length) {\n const cols = query.select as string[];\n out = out.map((r) => Object.fromEntries(cols.map((c) => [c, r[c]])));\n }\n return out.map((r) => ({ ...r }));\n}\n\n/** Best-effort apply of schema.json column defaults for the mock adapter. */\nexport function applyDefaults(entity: Entity, data: Row): Row {\n const row: Row = { ...data };\n for (const [col, def] of Object.entries(entity.columns ?? {})) {\n if (row[col] !== undefined || def == null) continue;\n const d = def.default;\n if (d == null) continue;\n if (/gen_random_uuid/i.test(d)) row[col] = randomUUID();\n else if (/now\\(\\)|current_timestamp/i.test(d)) row[col] = new Date().toISOString();\n else {\n const m = /^'(.*)'$/.exec(String(d).trim());\n if (m) row[col] = m[1];\n }\n }\n return row;\n}\n\n/**\n * In-memory adapter. Zero infrastructure: develop + unit-test App logic against\n * fixtures. Does NOT enforce RLS, constraints, triggers or PostgREST semantics —\n * run the `remote` adapter against a dev tenant for that fidelity before deploy.\n */\nexport function createMockAdapter(seed: Record<string, Row[]> = {}): Adapter {\n const store = new Map<string, Map<unknown, Row>>();\n const tbl = (entity: Entity): Map<unknown, Row> => {\n let m = store.get(entity.name);\n if (!m) {\n m = new Map();\n for (const r of seed[entity.name] ?? []) m.set(r[entity.pk], { ...r });\n store.set(entity.name, m);\n }\n return m;\n };\n\n return {\n kind: 'mock',\n async list(entity: Entity, query: Query = {}): Promise<Row[]> {\n const filtered = [...tbl(entity).values()].filter((r) => matches(r, query.where));\n return shape(filtered, query);\n },\n async page(entity: Entity, query: Query = {}): Promise<Page> {\n const filtered = [...tbl(entity).values()].filter((r) => matches(r, query.where));\n return { items: shape(filtered, query), total: filtered.length, limit: query.limit, offset: query.offset };\n },\n async get(entity: Entity, id: string | number): Promise<Row | null> {\n const r = tbl(entity).get(id);\n return r ? { ...r } : null;\n },\n async create(entity: Entity, data: Row): Promise<Row> {\n const row = applyDefaults(entity, data);\n if (row[entity.pk] === undefined) row[entity.pk] = randomUUID();\n tbl(entity).set(row[entity.pk], row);\n return { ...row };\n },\n async update(entity: Entity, id: string | number, patch: Row): Promise<Row> {\n const cur = tbl(entity).get(id);\n // Same answer the remote adapter gives for a patch that matched no row —\n // a 404, not a 500. The message is unchanged so existing App tests that\n // assert on it keep passing.\n if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);\n const row: Row = { ...cur, ...patch };\n if (entity.columns?.updated_at) row.updated_at = new Date().toISOString();\n tbl(entity).set(id, row);\n return { ...row };\n },\n async remove(entity: Entity, id: string | number): Promise<void> {\n tbl(entity).delete(id);\n },\n };\n}\n","import type { Query, FilterOp, Row } from './types.js';\n\n/**\n * PostgREST query helpers. `toParams` serialises a query for the HTTP adapters;\n * `matches` applies the same `where` semantics in memory for the mock adapter —\n * keeping one shape means App code is identical across adapters.\n */\n\nconst OPS = new Set<FilterOp>(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'like', 'ilike', 'in', 'is']);\n\n/** Serialise a query object to PostgREST URLSearchParams. */\nexport function toParams(query: Query = {}): URLSearchParams {\n const params = new URLSearchParams();\n const { where = {}, select, order, limit, offset } = query;\n\n for (const [col, cond] of Object.entries(where)) {\n if (Array.isArray(cond)) {\n params.append(col, `in.(${cond.join(',')})`);\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!OPS.has(c.op)) throw new Error(`query: unsupported operator '${c.op}'`);\n const v = Array.isArray(c.value) ? `(${c.value.join(',')})` : c.value;\n params.append(col, `${c.op}.${v}`);\n } else {\n params.append(col, `eq.${cond}`);\n }\n }\n\n if (Array.isArray(select) && select.length) params.set('select', (select as string[]).join(','));\n if (order) params.set('order', /\\.(asc|desc)$/.test(order) ? order : `${order}.asc`);\n if (Number.isInteger(limit)) params.set('limit', String(limit));\n if (Number.isInteger(offset)) params.set('offset', String(offset));\n\n return params;\n}\n\n/** In-memory predicate mirroring `toParams`' `where` semantics (mock adapter). */\nexport function matches(row: Row, where: Query['where'] = {}): boolean {\n for (const [col, cond] of Object.entries(where)) {\n const val = row[col];\n if (Array.isArray(cond)) {\n if (!cond.includes(val as never)) return false;\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!compare(val, c.op, c.value)) return false;\n } else if (val !== cond) {\n return false;\n }\n }\n return true;\n}\n\nfunction compare(a: unknown, op: FilterOp, b: unknown): boolean {\n switch (op) {\n case 'eq': return a === b;\n case 'neq': return a !== b;\n case 'gt': return (a as number) > (b as number);\n case 'gte': return (a as number) >= (b as number);\n case 'lt': return (a as number) < (b as number);\n case 'lte': return (a as number) <= (b as number);\n case 'is': return a === b;\n case 'in': return Array.isArray(b) && b.includes(a);\n case 'like':\n case 'ilike': {\n const re = new RegExp(\n '^' + String(b).replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/%/g, '.*').replace(/_/g, '.') + '$',\n op === 'ilike' ? 'i' : '',\n );\n return re.test(String(a));\n }\n default: return false;\n }\n}\n","/**\n * PostgREST failure → HTTP answer.\n *\n * PostgREST reports database constraint violations with a JSON body that names\n * the offending table and constraint:\n *\n * {\"code\":\"23505\",\"details\":\"Key (tenant_id, code)=(…) already exists.\",\n * \"message\":\"duplicate key value violates unique constraint\n * \\\"idx__revenexx__channels__channels__tenant_id_code__uniq\\\"\"}\n *\n * Forwarding that verbatim is wrong twice over: an expected condition (a\n * duplicate code) reads as a server outage, and the response leaks the internal\n * schema to every API caller. This module maps the failure to a status the\n * platform's own error contract already understands, with a stable, generic\n * message. The raw body travels on `HttpError.serverDetail`, which the router\n * logs and never serialises.\n *\n * Mapping:\n * 23505 unique_violation → 409 a record with this value already exists\n * 23P01 exclusion_violation → 409 conflicts with an existing record\n * 23503 foreign_key_violation → 400 when the referenced parent is missing\n * → 409 when a dependent row blocks a delete\n * 23502 not_null_violation → 400 a required value is missing\n * 23514 check_violation → 400 value not allowed\n * 22xxx data exception → 400 wrong format (22P02 bad uuid/number …)\n * anything else → PostgREST's own status when it is a client\n * error we recognise, otherwise 500\n *\n * `PGRST103` (offset past the end of the result set) is deliberately *not* an\n * error — see `rangeNotSatisfiable` and the adapter's `list`/`page`.\n */\n\nimport { HttpError } from '../errors.js';\n\n/** The shape PostgREST uses for error bodies. */\ninterface PgErrorBody {\n code?: string;\n message?: string;\n details?: string;\n hint?: string;\n}\n\nfunction parseBody(body: string): PgErrorBody {\n if (!body) return {};\n try {\n const parsed: unknown = JSON.parse(body);\n return parsed && typeof parsed === 'object' ? (parsed as PgErrorBody) : {};\n } catch {\n return {};\n }\n}\n\ninterface Mapped {\n status: number;\n code: string;\n message: string;\n}\n\n/** SQLSTATE → what the caller is allowed to know. */\nconst BY_SQLSTATE: Record<string, Mapped> = {\n '23505': { status: 409, code: 'unique_violation', message: 'a record with this value already exists' },\n '23P01': { status: 409, code: 'exclusion_violation', message: 'a record conflicts with an existing one' },\n '23502': { status: 400, code: 'not_null_violation', message: 'a required value is missing' },\n '23514': { status: 400, code: 'check_violation', message: 'a value is not allowed here' },\n '22P02': { status: 400, code: 'invalid_value', message: 'a value in the request has the wrong format' },\n};\n\n/** Statuses PostgREST returns that already describe the client's mistake. */\nconst CLIENT_STATUS: Record<number, string> = {\n 400: 'the request could not be processed',\n 401: 'unauthenticated',\n 403: 'forbidden',\n 404: 'not found',\n 405: 'method not allowed',\n 406: 'the requested representation is not available',\n 409: 'the request conflicts with the current state of the data',\n 413: 'the request is too large',\n 415: 'unsupported media type',\n 422: 'the request could not be processed',\n 429: 'too many requests',\n};\n\n/**\n * A foreign-key violation is two different bugs depending on direction, and\n * Postgres' own wording distinguishes them reliably (PostgREST forwards it\n * untouched in `details`):\n *\n * write: Key (market_id)=(…) is not present in table \"markets\". → 400\n * delete: Key (id)=(…) is still referenced from table \"locales\". → 409\n *\n * If neither phrase is present (a localised server, or future wording), fall\n * back to the request method: a DELETE can only fail on a dependent row, any\n * other verb can only fail on a missing parent.\n */\nfunction foreignKey(pg: PgErrorBody, method: string): Mapped {\n const blocked: Mapped = {\n status: 409,\n code: 'foreign_key_violation',\n message: 'this record is still referenced by other records',\n };\n const missing: Mapped = {\n status: 400,\n code: 'foreign_key_violation',\n message: 'a referenced record does not exist',\n };\n const text = `${pg.details ?? ''} ${pg.message ?? ''}`;\n if (/is still referenced from/i.test(text)) return blocked;\n if (/is not present in table/i.test(text)) return missing;\n return method.toUpperCase() === 'DELETE' ? blocked : missing;\n}\n\nfunction classify(status: number, pg: PgErrorBody, method: string): Mapped {\n const sqlstate = typeof pg.code === 'string' ? pg.code : '';\n if (sqlstate === '23503') return foreignKey(pg, method);\n const known = BY_SQLSTATE[sqlstate];\n if (known) return known;\n // Class 22 is Postgres' \"data exception\" family — always bad input, never a\n // server fault (22003 numeric out of range, 22007 bad timestamp, 22001 value\n // too long, …).\n if (/^22/.test(sqlstate)) {\n return { status: 400, code: 'invalid_value', message: 'a value in the request has the wrong format' };\n }\n const generic = CLIENT_STATUS[status];\n if (generic) return { status, code: 'bad_request', message: generic };\n return { status: 500, code: 'data_error', message: 'the data service could not complete the request' };\n}\n\n/**\n * Map a non-2xx PostgREST response to an `HttpError` whose message is safe to\n * return. The raw body is preserved on `serverDetail` for logs only.\n */\nexport function postgrestError(status: number, body: string, context: { method: string; table?: string }): HttpError {\n const pg = parseBody(body);\n const mapped = classify(status, pg, context.method);\n return new HttpError(mapped.status, mapped.message, undefined, {\n code: mapped.code,\n serverDetail: {\n source: 'postgrest',\n status,\n method: context.method,\n ...(context.table ? { table: context.table } : {}),\n sqlstate: pg.code ?? null,\n message: pg.message ?? (body || null),\n details: pg.details ?? null,\n hint: pg.hint ?? null,\n },\n });\n}\n\n/**\n * `PGRST103` / HTTP 416: the requested offset is past the end of the result\n * set. That is a legitimate request — the last page of a table someone just\n * emptied — not a failure, so callers answer with an empty page instead of an\n * error. Returns the true row count PostgREST reported, or `null` when the\n * response is a real error.\n */\nexport function rangeNotSatisfiable(status: number, body: string): { total: number } | null {\n if (status !== 416) return null;\n const pg = parseBody(body);\n // PostgREST: \"An offset of 25 was requested, but there are only 3 rows.\"\n const m = /there are only (\\d+) rows/i.exec(`${pg.details ?? ''} ${pg.message ?? ''}`);\n return { total: m ? Number.parseInt(m[1]!, 10) : 0 };\n}\n","import type { Adapter, Entity, Query, Row, Page } from '../types.js';\nimport { toParams } from '../query.js';\nimport { HttpError, notFound } from '../errors.js';\nimport { postgrestError, rangeNotSatisfiable } from './postgrest-error.js';\n\nexport interface RemoteConfig {\n endpoint: string;\n token?: string;\n tenant?: string;\n /**\n * Active market, forwarded as `X-Revenexx-Market`. Never a security boundary\n * — the tenant is the hard contract (token/RLS).\n *\n * What it does depends entirely on which endpoint the entity points at, and\n * the two effects are not symmetric:\n *\n * - **On INSERT it ASSIGNS.** An `AFTER INSERT` trigger on every scopeable\n * table reads the header and writes a `baseline.entity_scopes` row for the\n * new id. Sending a market here narrows what that row is visible as, for\n * good. Sending none leaves it unassigned, i.e. visible everywhere.\n * - **On SELECT it filters only through a `*_scoped` view.**\n * `baseline.is_visible()` is called from the view body and nowhere else, so\n * a read of the BASE table ignores the header completely.\n *\n * Generated entities target the base table (`vendor__app__entity`), so unless\n * an App overrides `entity.table` with the `_scoped` name, a list returns the\n * same rows with or without a market. Absent is therefore a no-op on reads,\n * not a \"globals only\" default.\n */\n market?: string;\n fetchImpl?: typeof fetch;\n}\n\n/** PostgREST-over-HTTP adapter (production data plane / dev tenant). */\nexport function createRemoteAdapter(config: RemoteConfig): Adapter {\n const f = config.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') {\n throw new Error('remote adapter: no fetch available (Node >=18 or pass fetchImpl)');\n }\n const base = String(config.endpoint ?? '').replace(/\\/$/, '');\n if (!base) throw new Error('remote adapter: endpoint is required');\n\n const headers = (extra?: Record<string, string>): Record<string, string> => {\n const h: Record<string, string> = { 'Content-Type': 'application/json', Accept: 'application/json', ...extra };\n if (config.token) h.Authorization = `Bearer ${config.token}`;\n if (config.tenant) h['X-Revenexx-Tenant'] = config.tenant;\n if (config.market) h['X-Revenexx-Market'] = config.market;\n return h;\n };\n\n interface Sent {\n status: number;\n ok: boolean;\n text: string;\n // Total parsed from the Content-Range header (\"0-9/247\"), when present.\n total: number | null;\n }\n\n interface SendOptions {\n body?: unknown;\n prefer?: string;\n /** Table name — server-side log context only, never returned to a caller. */\n table?: string;\n }\n\n async function send(method: string, path: string, opts: SendOptions = {}): Promise<Sent> {\n const res = await f(`${base}${path}`, {\n method,\n headers: headers(opts.prefer ? { Prefer: opts.prefer } : {}),\n body: opts.body != null ? JSON.stringify(opts.body) : undefined,\n });\n const text = await res.text();\n const range = res.headers?.get?.('content-range') ?? '';\n const total = Number.parseInt(range.split('/')[1] ?? '', 10);\n return { status: res.status, ok: res.ok, text, total: Number.isFinite(total) ? total : null };\n }\n\n async function req(method: string, path: string, opts: SendOptions = {}): Promise<unknown> {\n const { ok, status, text } = await send(method, path, opts);\n // Constraint violations become the status they deserve, with a message that\n // names no table or constraint (see ./postgrest-error).\n if (!ok) throw postgrestError(status, text, { method, table: opts.table });\n return text ? JSON.parse(text) : null;\n }\n\n /**\n * The single row out of a `return=representation` response.\n *\n * PostgREST answers `200 []` — a success — whenever the write touched no row:\n * a `PATCH` whose filter matched nothing, or one whose body carried no\n * columns. `rows[0]` is then `undefined`, and returning it breaks the\n * `Promise<Row>` contract in the worst possible place: the App hands it to\n * `res.json()`, `JSON.stringify(undefined)` is `undefined`, and the runtime's\n * `Buffer.from(undefined)` raises a Node type error that surfaces to the\n * caller as a 500. Nothing downstream can recover from that, so the absence\n * is reported here, as an answer the caller can act on.\n */\n const oneRow = (rows: unknown, onMissing: () => HttpError): Row => {\n const row = Array.isArray(rows) ? (rows[0] as Row | undefined) : (rows as Row | null);\n if (row == null) throw onMissing();\n return row;\n };\n\n return {\n kind: 'remote',\n async list(entity: Entity, query: Query = {}): Promise<Row[]> {\n const qs = toParams(query).toString();\n const { ok, status, text } = await send('GET', `/${entity.table}${qs ? `?${qs}` : ''}`, {\n table: entity.table,\n });\n if (!ok) {\n // An offset past the end of the result set is a legitimate request, not\n // a failure — answer with no rows (see ./postgrest-error).\n if (rangeNotSatisfiable(status, text)) return [];\n throw postgrestError(status, text, { method: 'GET', table: entity.table });\n }\n return (text ? (JSON.parse(text) as Row[]) : []) ?? [];\n },\n async get(entity: Entity, id: string | number): Promise<Row | null> {\n const rows = (await req('GET', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&limit=1`, {\n table: entity.table,\n })) as Row[];\n return rows?.[0] ?? null;\n },\n async create(entity: Entity, data: Row): Promise<Row> {\n const rows = await req('POST', `/${entity.table}`, {\n body: data,\n prefer: 'return=representation',\n table: entity.table,\n });\n // An insert that reports success but returns no row means the row is not\n // readable back (an RLS policy that permits INSERT but not SELECT). That\n // is a server-side condition, so it keeps a 5xx — but a described one.\n return oneRow(\n rows,\n () =>\n new HttpError(500, 'the record was created but could not be read back', undefined, {\n code: 'empty_representation',\n serverDetail: { source: 'postgrest', method: 'POST', table: entity.table },\n }),\n );\n },\n async update(entity: Entity, id: string | number, patch: Row): Promise<Row> {\n const rows = await req('PATCH', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {\n body: patch,\n prefer: 'return=representation',\n table: entity.table,\n });\n // No row came back for a patch that carried fields: the row is gone or\n // invisible to this tenant (deleted between the read and the write, or\n // filtered by RLS). Both are a 404 to the caller. An empty patch never\n // reaches here — the client rejects it with a 400 first (see ../patch.ts).\n return oneRow(rows, () => notFound());\n },\n async remove(entity: Entity, id: string | number): Promise<void> {\n await req('DELETE', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {\n table: entity.table,\n });\n },\n async page(entity: Entity, query: Query = {}): Promise<Page> {\n // One request: PostgREST returns the page in the body and the total in\n // Content-Range (\"0-9/247\" or \"*/247\") when asked for an exact count.\n const qs = toParams(query).toString();\n const { ok, status, text, total } = await send('GET', `/${entity.table}${qs ? `?${qs}` : ''}`, {\n prefer: 'count=exact',\n table: entity.table,\n });\n if (!ok) {\n // Paging past the end of the result set is a legitimate request — the\n // last page of a list someone just emptied. Answer with an empty page\n // carrying the requested bounds and the true total, not an error.\n const overflow = rangeNotSatisfiable(status, text);\n if (overflow) {\n return { items: [], total: total ?? overflow.total, limit: query.limit, offset: query.offset };\n }\n throw postgrestError(status, text, { method: 'GET', table: entity.table });\n }\n const items = (text ? JSON.parse(text) : []) as Row[];\n return {\n items,\n total: total ?? items.length,\n limit: query.limit,\n offset: query.offset,\n };\n },\n };\n}\n","import type { Adapter } from '../types.js';\nimport { createRemoteAdapter } from './remote.js';\n\ninterface FunctionContext {\n req?: { headers?: Record<string, string> };\n}\n\nexport interface RuntimeConfig {\n context?: FunctionContext;\n env?: Record<string, string | undefined>;\n}\n\n/** The platform data plane. Override with REVENEXX_DATA_ENDPOINT when needed. */\nexport const DEFAULT_DATA_ENDPOINT = 'https://apps.api.revenexx.com';\n\n/**\n * Production adapter: a `remote` adapter auto-configured from the function's\n * per-invocation context. Token = the brokered identity forwarded as\n * `x-revenexx-context`; tenant = `x-revenexx-tenant`; endpoint = env, falling\n * back to the platform data plane — deployed apps work with zero configuration.\n * App code stays identical — only the adapter selection differs between local\n * and prod.\n */\nexport function createRuntimeAdapter(config: RuntimeConfig = {}): Adapter {\n const env = config.env ?? process.env;\n const h = config.context?.req?.headers ?? {};\n const get = (name: string): string => h[name] ?? h[name.toLowerCase()] ?? '';\n\n const remote = createRemoteAdapter({\n endpoint: env.REVENEXX_DATA_ENDPOINT || DEFAULT_DATA_ENDPOINT,\n token: get('x-revenexx-context') || env.REVENEXX_CONTEXT || '',\n tenant: get('x-revenexx-tenant') || env.REVENEXX_TENANT || '',\n // Active market forwarded to the data layer. It ASSIGNS the market on\n // insert and filters reads only through a `*_scoped` view — generated\n // entities read the base table, so on the app path a list is unaffected by\n // it. See RemoteConfig.market; absent is a no-op on reads, not a narrower\n // default.\n market: get('x-revenexx-market') || env.REVENEXX_MARKET || '',\n });\n\n return { ...remote, kind: 'runtime' };\n}\n","import type { Adapter } from '../types.js';\nimport { createMockAdapter, applyDefaults } from './mock.js';\nimport { createRemoteAdapter } from './remote.js';\nimport { createRuntimeAdapter } from './runtime.js';\n\n/**\n * Adapter registry. Built-ins (mock | remote | runtime) are registered below;\n * add a new backend by calling `registerAdapter('my-kind', (config) => …)`\n * before constructing the client — no changes to the client or generated code.\n */\nexport type AdapterFactory = (config: Record<string, any>) => Adapter;\n\nconst registry = new Map<string, AdapterFactory>();\n\nexport function registerAdapter(kind: string, factory: AdapterFactory): void {\n registry.set(kind, factory);\n}\n\nexport function adapterKinds(): string[] {\n return [...registry.keys()];\n}\n\nexport function createAdapter(config: { adapter?: string } & Record<string, any>): Adapter {\n const kind = config.adapter ?? '';\n const factory = registry.get(kind);\n if (!factory) {\n const known = adapterKinds().join(' | ') || 'none registered';\n throw new Error(`app-sdk: unknown adapter '${kind}' (${known})`);\n }\n return factory(config);\n}\n\nregisterAdapter('mock', (c) => createMockAdapter(c.seed));\nregisterAdapter('remote', (c) => createRemoteAdapter(c as { endpoint: string }));\nregisterAdapter('runtime', (c) => createRuntimeAdapter(c));\n\nexport { createMockAdapter, createRemoteAdapter, createRuntimeAdapter, applyDefaults };\n","import type { Adapter, Entity, Op, Query, Row, Page } from './types.js';\nimport { createAdapter } from './adapters/index.js';\nimport { assertUpdatable } from './patch.js';\n\n/** manifest `permissions` access → entity client methods. */\nconst ACCESS_TO_OPS: Record<string, Op[]> = {\n read: ['list', 'get'],\n create: ['create'],\n update: ['update'],\n delete: ['delete'],\n};\n\n/** Map a manifest access list (e.g. ['read','create']) to a Set of ops. */\nexport function opsFromAccess(access: string[] = []): Set<Op> {\n const ops = new Set<Op>();\n for (const a of access) (ACCESS_TO_OPS[a] ?? []).forEach((o) => ops.add(o));\n return ops;\n}\n\n/** The methods exposed for a single entity; absent ops throw at call time. */\nexport interface EntityClient<T extends Row = Row, Create extends Row = T> {\n list(query?: Query<T>): Promise<T[]>;\n /** Like `list`, but also returns the total count of matching rows (for pagination). */\n page(query?: Query<T>): Promise<Page<T>>;\n get(id: string | number): Promise<T | null>;\n create(data: Create): Promise<T>;\n update(id: string | number, patch: Partial<Create>): Promise<T>;\n delete(id: string | number): Promise<void>;\n}\n\nfunction entityClient(adapter: Adapter, entity: Entity): EntityClient {\n const ops = entity.ops instanceof Set ? entity.ops : new Set<Op>(entity.ops ?? ['list', 'get', 'create', 'update', 'delete']);\n const guard = <F extends (...args: never[]) => unknown>(op: Op, fn: F): F =>\n (ops.has(op)\n ? fn\n : (() => {\n throw new Error(\n `${entity.name}.${op}() is not permitted — add the matching access to manifest.permissions for '${entity.name}'`,\n );\n }) as unknown as F);\n\n return {\n list: guard('list', (query?: Query) => adapter.list(entity, query ?? {})),\n page: guard('list', (query?: Query) => {\n if (!adapter.page) {\n throw new Error(`${entity.name}.page() is not supported by the '${adapter.kind}' adapter`);\n }\n return adapter.page(entity, query ?? {});\n }),\n get: guard('get', (id: string | number) => adapter.get(entity, id)),\n create: guard('create', (data: Row) => adapter.create(entity, data)),\n // A patch with no fields is a malformed request, not a write: PostgREST\n // performs no update and returns no row, which used to leave the App\n // serialising `undefined` and answering 500 (see ./patch.ts). Rejected here\n // rather than in `mountCrud` so every App gets it — hand-written PUT\n // handlers that call `update()` directly were the ones that broke.\n //\n // `async` on purpose: a rejected promise, not a synchronous throw, so a bad\n // patch is handled like any other data-plane failure (`await` / `.catch()`)\n // and the declared `Promise<T>` stays honest.\n update: guard('update', async (id: string | number, patch: Row) => {\n assertUpdatable(patch);\n return adapter.update(entity, id, patch);\n }),\n delete: guard('delete', (id: string | number) => adapter.remove(entity, id)),\n } as EntityClient;\n}\n\nexport interface ClientConfig {\n adapter: string;\n entities: Record<string, Omit<Entity, 'name'>>;\n [key: string]: unknown;\n}\n\nexport type Client = Record<string, EntityClient> & { readonly __adapter: string };\n\n/**\n * Build a typed entity client.\n * local dev : createClient({ adapter: 'mock', entities, seed })\n * dev tenant: createClient({ adapter: 'remote', entities, endpoint, token, tenant })\n * production: createClient({ adapter: 'runtime', entities, context }) // in the function\n */\nexport function createClient(config: ClientConfig): Client {\n if (!config?.entities) throw new Error('app-sdk: createClient needs { adapter, entities }');\n const adapter = createAdapter(config);\n const db = Object.create({ __adapter: adapter.kind }) as Client;\n for (const [name, def] of Object.entries(config.entities)) {\n db[name] = entityClient(adapter, { name, ...def });\n }\n return db;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,kBAAkB;;;ACQ3B,IAAM,MAAM,oBAAI,IAAc,CAAC,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,QAAQ,SAAS,MAAM,IAAI,CAAC;AAG3F,SAAS,SAAS,QAAe,CAAC,GAAoB;AAC3D,QAAM,SAAS,IAAI,gBAAgB;AACnC,QAAM,EAAE,QAAQ,CAAC,GAAG,QAAQ,OAAO,OAAO,OAAO,IAAI;AAErD,aAAW,CAAC,KAAK,IAAI,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC/C,QAAI,MAAM,QAAQ,IAAI,GA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I,WAAW;AAAA,MAC3F;AACA,aAAO,QAAQ,KAAK,QAAQ,SAAS,CAAC,CAAC;AAAA,IACzC,CAAC;AAAA,IACD,KAAK,MAAM,OAAO,CAAC,OAAwB,QAAQ,IAAI,QAAQ,EAAE,CAAC;AAAA,IAClE,QAAQ,MAAM,UAAU,CAAC,SAAc,QAAQ,OAAO,QAAQ,IAAI,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAUnE,QAAQ,MAAM,UAAU,OAAO,IAAqB,UAAe;AACjE,sBAAgB,KAAK;AACrB,aAAO,QAAQ,OAAO,QAAQ,IAAI,KAAK;AAAA,IACzC,CAAC;AAAA,IACD,QAAQ,MAAM,UAAU,CAAC,OAAwB,QAAQ,OAAO,QAAQ,EAAE,CAAC;AAAA,EAC7E;AACF;AAgBO,SAAS,aAAa,QAA8B;AACzD,MAAI,CAAC,QAAQ,SAAU,OAAM,IAAI,MAAM,mDAAmD;AAC1F,QAAM,UAAU,cAAc,MAAM;AACpC,QAAM,KAAK,uBAAO,OAAO,EAAE,WAAW,QAAQ,KAAK,CAAC;AACpD,aAAW,CAAC,MAAM,GAAG,KAAK,OAAO,QAAQ,OAAO,QAAQ,GAAG;AACzD,OAAG,IAAI,IAAI,aAAa,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;AAAA,EACnD;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/adapters/mock.ts","../src/query.ts","../src/adapters/postgrest-error.ts","../src/adapters/remote.ts","../src/adapters/runtime.ts","../src/adapters/index.ts","../src/client.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type {\n Adapter,\n EmitOptions,\n EmitResult,\n EmitTarget,\n EmittedEvent,\n Entity,\n Page,\n Query,\n Row,\n} from '../types.js';\nimport { notFound } from '../errors.js';\nimport { matches } from '../query.js';\n\n/** Apply order → offset → limit → select to an already-filtered row set. */\nfunction shape(rows: Row[], query: Query): Row[] {\n let out = rows;\n if (query.order) {\n const [c, dir = 'asc'] = query.order.split('.');\n const key = c as string;\n out = out.slice().sort((a, b) => (a[key]! < b[key]! ? -1 : a[key]! > b[key]! ? 1 : 0));\n if (dir === 'desc') out.reverse();\n }\n if (query.offset) out = out.slice(query.offset);\n if (Number.isInteger(query.limit)) out = out.slice(0, query.limit);\n if (Array.isArray(query.select) && query.select.length) {\n const cols = query.select as string[];\n out = out.map((r) => Object.fromEntries(cols.map((c) => [c, r[c]])));\n }\n return out.map((r) => ({ ...r }));\n}\n\n/** Best-effort apply of schema.json column defaults for the mock adapter. */\nexport function applyDefaults(entity: Entity, data: Row): Row {\n const row: Row = { ...data };\n for (const [col, def] of Object.entries(entity.columns ?? {})) {\n if (row[col] !== undefined || def == null) continue;\n const d = def.default;\n if (d == null) continue;\n if (/gen_random_uuid/i.test(d)) row[col] = randomUUID();\n else if (/now\\(\\)|current_timestamp/i.test(d)) row[col] = new Date().toISOString();\n else {\n const m = /^'(.*)'$/.exec(String(d).trim());\n if (m) row[col] = m[1];\n }\n }\n return row;\n}\n\n/**\n * In-memory adapter. Zero infrastructure: develop + unit-test App logic against\n * fixtures. Does NOT enforce RLS, constraints, triggers or PostgREST semantics —\n * run the `remote` adapter against a dev tenant for that fidelity before deploy.\n */\nexport function createMockAdapter(seed: Record<string, Row[]> = {}): Adapter {\n const store = new Map<string, Map<unknown, Row>>();\n const events: EmittedEvent[] = [];\n const tbl = (entity: Entity): Map<unknown, Row> => {\n let m = store.get(entity.name);\n if (!m) {\n m = new Map();\n for (const r of seed[entity.name] ?? []) m.set(r[entity.pk], { ...r });\n store.set(entity.name, m);\n }\n return m;\n };\n\n return {\n kind: 'mock',\n async list(entity: Entity, query: Query = {}): Promise<Row[]> {\n const filtered = [...tbl(entity).values()].filter((r) => matches(r, query.where));\n return shape(filtered, query);\n },\n async page(entity: Entity, query: Query = {}): Promise<Page> {\n const filtered = [...tbl(entity).values()].filter((r) => matches(r, query.where));\n return { items: shape(filtered, query), total: filtered.length, limit: query.limit, offset: query.offset };\n },\n async get(entity: Entity, id: string | number): Promise<Row | null> {\n const r = tbl(entity).get(id);\n return r ? { ...r } : null;\n },\n async create(entity: Entity, data: Row): Promise<Row> {\n const row = applyDefaults(entity, data);\n if (row[entity.pk] === undefined) row[entity.pk] = randomUUID();\n tbl(entity).set(row[entity.pk], row);\n return { ...row };\n },\n async update(entity: Entity, id: string | number, patch: Row): Promise<Row> {\n const cur = tbl(entity).get(id);\n // Same answer the remote adapter gives for a patch that matched no row —\n // a 404, not a 500. The message is unchanged so existing App tests that\n // assert on it keep passing.\n if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);\n const row: Row = { ...cur, ...patch };\n if (entity.columns?.updated_at) row.updated_at = new Date().toISOString();\n tbl(entity).set(id, row);\n return { ...row };\n },\n async remove(entity: Entity, id: string | number): Promise<void> {\n tbl(entity).delete(id);\n },\n /**\n * Record instead of publish, so an App can assert what it fired without any\n * infrastructure. The signature and the answer are the remote adapter's,\n * deliberately: the expensive failure in this codebase is a test double\n * that drifted from the real surface, so a test that passes here has to\n * mean the same call works against Postgres.\n *\n * The declared name is NOT checked here — the client does that before it\n * reaches any adapter, so mock and remote refuse a typo identically.\n */\n async emit(target: EmitTarget, data: Row = {}, options: EmitOptions = {}): Promise<EmitResult> {\n const result: EmitResult = {\n id: options.id ?? `evt_${randomUUID().replace(/-/g, '')}`,\n topic: target.descriptor.topic,\n };\n // Idempotency the way the outbox gives it: a second emit under an id\n // already used is a no-op, and the FIRST payload stands. A mock that\n // recorded both would let a test pass that production silently drops.\n if (!events.some((e) => e.result.id === result.id)) {\n events.push({ event: target.name, topic: result.topic, data: { ...data }, options, result });\n }\n return result;\n },\n // Copied a level deep, not spread: an EmittedEvent nests `data`, `options`\n // and `result`, so a shallow copy would hand callers the live payload and\n // let one assertion rewrite what the next one reads.\n emitted: (): EmittedEvent[] =>\n events.map((e) => ({\n event: e.event,\n topic: e.topic,\n data: { ...e.data },\n options: { ...e.options },\n result: { ...e.result },\n })),\n };\n}\n","import type { Query, FilterOp, Row } from './types.js';\n\n/**\n * PostgREST query helpers. `toParams` serialises a query for the HTTP adapters;\n * `matches` applies the same `where` semantics in memory for the mock adapter —\n * keeping one shape means App code is identical across adapters.\n */\n\nconst OPS = new Set<FilterOp>(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'like', 'ilike', 'in', 'is']);\n\n/** Serialise a query object to PostgREST URLSearchParams. */\nexport function toParams(query: Query = {}): URLSearchParams {\n const params = new URLSearchParams();\n const { where = {}, select, order, limit, offset } = query;\n\n for (const [col, cond] of Object.entries(where)) {\n if (Array.isArray(cond)) {\n params.append(col, `in.(${cond.join(',')})`);\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!OPS.has(c.op)) throw new Error(`query: unsupported operator '${c.op}'`);\n const v = Array.isArray(c.value) ? `(${c.value.join(',')})` : c.value;\n params.append(col, `${c.op}.${v}`);\n } else {\n params.append(col, `eq.${cond}`);\n }\n }\n\n if (Array.isArray(select) && select.length) params.set('select', (select as string[]).join(','));\n if (order) params.set('order', /\\.(asc|desc)$/.test(order) ? order : `${order}.asc`);\n if (Number.isInteger(limit)) params.set('limit', String(limit));\n if (Number.isInteger(offset)) params.set('offset', String(offset));\n\n return params;\n}\n\n/** In-memory predicate mirroring `toParams`' `where` semantics (mock adapter). */\nexport function matches(row: Row, where: Query['where'] = {}): boolean {\n for (const [col, cond] of Object.entries(where)) {\n const val = row[col];\n if (Array.isArray(cond)) {\n if (!cond.includes(val as never)) return false;\n } else if (cond && typeof cond === 'object' && typeof (cond as { op?: unknown }).op === 'string') {\n const c = cond as { op: FilterOp; value: unknown };\n if (!compare(val, c.op, c.value)) return false;\n } else if (val !== cond) {\n return false;\n }\n }\n return true;\n}\n\nfunction compare(a: unknown, op: FilterOp, b: unknown): boolean {\n switch (op) {\n case 'eq': return a === b;\n case 'neq': return a !== b;\n case 'gt': return (a as number) > (b as number);\n case 'gte': return (a as number) >= (b as number);\n case 'lt': return (a as number) < (b as number);\n case 'lte': return (a as number) <= (b as number);\n case 'is': return a === b;\n case 'in': return Array.isArray(b) && b.includes(a);\n case 'like':\n case 'ilike': {\n const re = new RegExp(\n '^' + String(b).replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/%/g, '.*').replace(/_/g, '.') + '$',\n op === 'ilike' ? 'i' : '',\n );\n return re.test(String(a));\n }\n default: return false;\n }\n}\n","/**\n * PostgREST failure → HTTP answer.\n *\n * PostgREST reports database constraint violations with a JSON body that names\n * the offending table and constraint:\n *\n * {\"code\":\"23505\",\"details\":\"Key (tenant_id, code)=(…) already exists.\",\n * \"message\":\"duplicate key value violates unique constraint\n * \\\"idx__revenexx__channels__channels__tenant_id_code__uniq\\\"\"}\n *\n * Forwarding that verbatim is wrong twice over: an expected condition (a\n * duplicate code) reads as a server outage, and the response leaks the internal\n * schema to every API caller. This module maps the failure to a status the\n * platform's own error contract already understands, with a stable, generic\n * message. The raw body travels on `HttpError.serverDetail`, which the router\n * logs and never serialises.\n *\n * Mapping:\n * 23505 unique_violation → 409 a record with this value already exists\n * 23P01 exclusion_violation → 409 conflicts with an existing record\n * 23503 foreign_key_violation → 400 when the referenced parent is missing\n * → 409 when a dependent row blocks a delete\n * 23502 not_null_violation → 400 a required value is missing\n * 23514 check_violation → 400 value not allowed\n * 22xxx data exception → 400 wrong format (22P02 bad uuid/number …)\n * anything else → PostgREST's own status when it is a client\n * error we recognise, otherwise 500\n *\n * `PGRST103` (offset past the end of the result set) is deliberately *not* an\n * error — see `rangeNotSatisfiable` and the adapter's `list`/`page`.\n */\n\nimport { HttpError } from '../errors.js';\n\n/** The shape PostgREST uses for error bodies. */\ninterface PgErrorBody {\n code?: string;\n message?: string;\n details?: string;\n hint?: string;\n}\n\nfunction parseBody(body: string): PgErrorBody {\n if (!body) return {};\n try {\n const parsed: unknown = JSON.parse(body);\n return parsed && typeof parsed === 'object' ? (parsed as PgErrorBody) : {};\n } catch {\n return {};\n }\n}\n\ninterface Mapped {\n status: number;\n code: string;\n message: string;\n}\n\n/** SQLSTATE → what the caller is allowed to know. */\nconst BY_SQLSTATE: Record<string, Mapped> = {\n '23505': { status: 409, code: 'unique_violation', message: 'a record with this value already exists' },\n '23P01': { status: 409, code: 'exclusion_violation', message: 'a record conflicts with an existing one' },\n '23502': { status: 400, code: 'not_null_violation', message: 'a required value is missing' },\n '23514': { status: 400, code: 'check_violation', message: 'a value is not allowed here' },\n '22P02': { status: 400, code: 'invalid_value', message: 'a value in the request has the wrong format' },\n};\n\n/** Statuses PostgREST returns that already describe the client's mistake. */\nconst CLIENT_STATUS: Record<number, string> = {\n 400: 'the request could not be processed',\n 401: 'unauthenticated',\n 403: 'forbidden',\n 404: 'not found',\n 405: 'method not allowed',\n 406: 'the requested representation is not available',\n 409: 'the request conflicts with the current state of the data',\n 413: 'the request is too large',\n 415: 'unsupported media type',\n 422: 'the request could not be processed',\n 429: 'too many requests',\n};\n\n/**\n * A foreign-key violation is two different bugs depending on direction, and\n * Postgres' own wording distinguishes them reliably (PostgREST forwards it\n * untouched in `details`):\n *\n * write: Key (market_id)=(…) is not present in table \"markets\". → 400\n * delete: Key (id)=(…) is still referenced from table \"locales\". → 409\n *\n * If neither phrase is present (a localised server, or future wording), fall\n * back to the request method: a DELETE can only fail on a dependent row, any\n * other verb can only fail on a missing parent.\n */\nfunction foreignKey(pg: PgErrorBody, method: string): Mapped {\n const blocked: Mapped = {\n status: 409,\n code: 'foreign_key_violation',\n message: 'this record is still referenced by other records',\n };\n const missing: Mapped = {\n status: 400,\n code: 'foreign_key_violation',\n message: 'a referenced record does not exist',\n };\n const text = `${pg.details ?? ''} ${pg.message ?? ''}`;\n if (/is still referenced from/i.test(text)) return blocked;\n if (/is not present in table/i.test(text)) return missing;\n return method.toUpperCase() === 'DELETE' ? blocked : missing;\n}\n\nfunction classify(status: number, pg: PgErrorBody, method: string): Mapped {\n const sqlstate = typeof pg.code === 'string' ? pg.code : '';\n if (sqlstate === '23503') return foreignKey(pg, method);\n const known = BY_SQLSTATE[sqlstate];\n if (known) return known;\n // Class 22 is Postgres' \"data exception\" family — always bad input, never a\n // server fault (22003 numeric out of range, 22007 bad timestamp, 22001 value\n // too long, …).\n if (/^22/.test(sqlstate)) {\n return { status: 400, code: 'invalid_value', message: 'a value in the request has the wrong format' };\n }\n const generic = CLIENT_STATUS[status];\n if (generic) return { status, code: 'bad_request', message: generic };\n return { status: 500, code: 'data_error', message: 'the data service could not complete the request' };\n}\n\n/**\n * Map a non-2xx PostgREST response to an `HttpError` whose message is safe to\n * return. The raw body is preserved on `serverDetail` for logs only.\n */\nexport function postgrestError(status: number, body: string, context: { method: string; table?: string }): HttpError {\n const pg = parseBody(body);\n const mapped = classify(status, pg, context.method);\n return new HttpError(mapped.status, mapped.message, undefined, {\n code: mapped.code,\n serverDetail: {\n source: 'postgrest',\n status,\n method: context.method,\n ...(context.table ? { table: context.table } : {}),\n sqlstate: pg.code ?? null,\n message: pg.message ?? (body || null),\n details: pg.details ?? null,\n hint: pg.hint ?? null,\n },\n });\n}\n\n/**\n * `PGRST103` / HTTP 416: the requested offset is past the end of the result\n * set. That is a legitimate request — the last page of a table someone just\n * emptied — not a failure, so callers answer with an empty page instead of an\n * error. Returns the true row count PostgREST reported, or `null` when the\n * response is a real error.\n */\nexport function rangeNotSatisfiable(status: number, body: string): { total: number } | null {\n if (status !== 416) return null;\n const pg = parseBody(body);\n // PostgREST: \"An offset of 25 was requested, but there are only 3 rows.\"\n const m = /there are only (\\d+) rows/i.exec(`${pg.details ?? ''} ${pg.message ?? ''}`);\n return { total: m ? Number.parseInt(m[1]!, 10) : 0 };\n}\n","import type { Adapter, EmitOptions, EmitResult, EmitTarget, Entity, Page, Query, Row } from '../types.js';\nimport { toParams } from '../query.js';\nimport { HttpError, notFound } from '../errors.js';\nimport { postgrestError, rangeNotSatisfiable } from './postgrest-error.js';\n\nexport interface RemoteConfig {\n endpoint: string;\n token?: string;\n tenant?: string;\n /**\n * Active market, forwarded as `X-Revenexx-Market`. Never a security boundary\n * — the tenant is the hard contract (token/RLS).\n *\n * What it does depends entirely on which endpoint the entity points at, and\n * the two effects are not symmetric:\n *\n * - **On INSERT it ASSIGNS.** An `AFTER INSERT` trigger on every scopeable\n * table reads the header and writes a `baseline.entity_scopes` row for the\n * new id. Sending a market here narrows what that row is visible as, for\n * good. Sending none leaves it unassigned, i.e. visible everywhere.\n * - **On SELECT it filters only through a `*_scoped` view.**\n * `baseline.is_visible()` is called from the view body and nowhere else, so\n * a read of the BASE table ignores the header completely.\n *\n * Generated entities target the base table (`vendor__app__entity`), so unless\n * an App overrides `entity.table` with the `_scoped` name, a list returns the\n * same rows with or without a market. Absent is therefore a no-op on reads,\n * not a \"globals only\" default.\n */\n market?: string;\n fetchImpl?: typeof fetch;\n}\n\n/** PostgREST-over-HTTP adapter (production data plane / dev tenant). */\nexport function createRemoteAdapter(config: RemoteConfig): Adapter {\n const f = config.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') {\n throw new Error('remote adapter: no fetch available (Node >=18 or pass fetchImpl)');\n }\n const base = String(config.endpoint ?? '').replace(/\\/$/, '');\n if (!base) throw new Error('remote adapter: endpoint is required');\n\n const headers = (extra?: Record<string, string>): Record<string, string> => {\n const h: Record<string, string> = { 'Content-Type': 'application/json', Accept: 'application/json', ...extra };\n if (config.token) h.Authorization = `Bearer ${config.token}`;\n if (config.tenant) h['X-Revenexx-Tenant'] = config.tenant;\n if (config.market) h['X-Revenexx-Market'] = config.market;\n return h;\n };\n\n interface Sent {\n status: number;\n ok: boolean;\n text: string;\n // Total parsed from the Content-Range header (\"0-9/247\"), when present.\n total: number | null;\n }\n\n interface SendOptions {\n body?: unknown;\n prefer?: string;\n /** Table name — server-side log context only, never returned to a caller. */\n table?: string;\n }\n\n async function send(method: string, path: string, opts: SendOptions = {}): Promise<Sent> {\n const res = await f(`${base}${path}`, {\n method,\n headers: headers(opts.prefer ? { Prefer: opts.prefer } : {}),\n body: opts.body != null ? JSON.stringify(opts.body) : undefined,\n });\n const text = await res.text();\n const range = res.headers?.get?.('content-range') ?? '';\n const total = Number.parseInt(range.split('/')[1] ?? '', 10);\n return { status: res.status, ok: res.ok, text, total: Number.isFinite(total) ? total : null };\n }\n\n async function req(method: string, path: string, opts: SendOptions = {}): Promise<unknown> {\n const { ok, status, text } = await send(method, path, opts);\n // Constraint violations become the status they deserve, with a message that\n // names no table or constraint (see ./postgrest-error).\n if (!ok) throw postgrestError(status, text, { method, table: opts.table });\n return text ? JSON.parse(text) : null;\n }\n\n /**\n * The single row out of a `return=representation` response.\n *\n * PostgREST answers `200 []` — a success — whenever the write touched no row:\n * a `PATCH` whose filter matched nothing, or one whose body carried no\n * columns. `rows[0]` is then `undefined`, and returning it breaks the\n * `Promise<Row>` contract in the worst possible place: the App hands it to\n * `res.json()`, `JSON.stringify(undefined)` is `undefined`, and the runtime's\n * `Buffer.from(undefined)` raises a Node type error that surfaces to the\n * caller as a 500. Nothing downstream can recover from that, so the absence\n * is reported here, as an answer the caller can act on.\n */\n const oneRow = (rows: unknown, onMissing: () => HttpError): Row => {\n const row = Array.isArray(rows) ? (rows[0] as Row | undefined) : (rows as Row | null);\n if (row == null) throw onMissing();\n return row;\n };\n\n return {\n kind: 'remote',\n async list(entity: Entity, query: Query = {}): Promise<Row[]> {\n const qs = toParams(query).toString();\n const { ok, status, text } = await send('GET', `/${entity.table}${qs ? `?${qs}` : ''}`, {\n table: entity.table,\n });\n if (!ok) {\n // An offset past the end of the result set is a legitimate request, not\n // a failure — answer with no rows (see ./postgrest-error).\n if (rangeNotSatisfiable(status, text)) return [];\n throw postgrestError(status, text, { method: 'GET', table: entity.table });\n }\n return (text ? (JSON.parse(text) as Row[]) : []) ?? [];\n },\n async get(entity: Entity, id: string | number): Promise<Row | null> {\n const rows = (await req('GET', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&limit=1`, {\n table: entity.table,\n })) as Row[];\n return rows?.[0] ?? null;\n },\n async create(entity: Entity, data: Row): Promise<Row> {\n const rows = await req('POST', `/${entity.table}`, {\n body: data,\n prefer: 'return=representation',\n table: entity.table,\n });\n // An insert that reports success but returns no row means the row is not\n // readable back (an RLS policy that permits INSERT but not SELECT). That\n // is a server-side condition, so it keeps a 5xx — but a described one.\n return oneRow(\n rows,\n () =>\n new HttpError(500, 'the record was created but could not be read back', undefined, {\n code: 'empty_representation',\n serverDetail: { source: 'postgrest', method: 'POST', table: entity.table },\n }),\n );\n },\n async update(entity: Entity, id: string | number, patch: Row): Promise<Row> {\n const rows = await req('PATCH', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {\n body: patch,\n prefer: 'return=representation',\n table: entity.table,\n });\n // No row came back for a patch that carried fields: the row is gone or\n // invisible to this tenant (deleted between the read and the write, or\n // filtered by RLS). Both are a 404 to the caller. An empty patch never\n // reaches here — the client rejects it with a 400 first (see ../patch.ts).\n return oneRow(rows, () => notFound());\n },\n async remove(entity: Entity, id: string | number): Promise<void> {\n await req('DELETE', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {\n table: entity.table,\n });\n },\n async page(entity: Entity, query: Query = {}): Promise<Page> {\n // One request: PostgREST returns the page in the body and the total in\n // Content-Range (\"0-9/247\" or \"*/247\") when asked for an exact count.\n const qs = toParams(query).toString();\n const { ok, status, text, total } = await send('GET', `/${entity.table}${qs ? `?${qs}` : ''}`, {\n prefer: 'count=exact',\n table: entity.table,\n });\n if (!ok) {\n // Paging past the end of the result set is a legitimate request — the\n // last page of a list someone just emptied. Answer with an empty page\n // carrying the requested bounds and the true total, not an error.\n const overflow = rangeNotSatisfiable(status, text);\n if (overflow) {\n return { items: [], total: total ?? overflow.total, limit: query.limit, offset: query.offset };\n }\n throw postgrestError(status, text, { method: 'GET', table: entity.table });\n }\n const items = (text ? JSON.parse(text) : []) as Row[];\n return {\n items,\n total: total ?? items.length,\n limit: query.limit,\n offset: query.offset,\n };\n },\n /**\n * Fire one of the App's own declared events, through the routine Baseline\n * generated for it: `POST /rpc/{vendor}__{app}__emit`.\n *\n * Nothing about WHICH app is emitting travels in this request. The routine\n * is per app, its topic prefix and its allowlist are literals, and only the\n * app's Postgres role may execute it — so the same token that reaches the\n * app's tables is the whole credential, and there is no argument through\n * which another app's topic could be named.\n *\n * The argument names are the routine's, not ours: PostgREST maps the body's\n * keys onto named parameters, so `topicId` becomes `topic_id` and `id`\n * becomes `event_id` (a parameter called `id` would shadow the outbox\n * column in the routine's own ON CONFLICT clause).\n */\n async emit(target: EmitTarget, data: Row = {}, options: EmitOptions = {}): Promise<EmitResult> {\n const { ok, status, text } = await send('POST', `/rpc/${target.fn}`, {\n table: target.fn,\n body: {\n event: target.name,\n data,\n topic_id: options.topicId ?? null,\n metadata: options.metadata ?? {},\n event_id: options.id ?? null,\n },\n });\n if (!ok) throw postgrestError(status, text, { method: 'POST', table: target.fn });\n\n const answer = (text ? JSON.parse(text) : null) as Partial<EmitResult> | null;\n // The routine always returns both, so an answer without them means the\n // request reached something other than the routine we asked for. Failing\n // here beats handing the caller an event id of `undefined`.\n if (!answer?.id || !answer.topic) {\n throw new HttpError(502, 'the event service returned no event id', undefined, {\n code: 'emit_no_id',\n serverDetail: { source: 'postgrest', fn: target.fn, event: target.name, body: text },\n });\n }\n return { id: answer.id, topic: answer.topic };\n },\n };\n}\n","import type { Adapter } from '../types.js';\nimport { createRemoteAdapter } from './remote.js';\n\ninterface FunctionContext {\n req?: { headers?: Record<string, string> };\n}\n\nexport interface RuntimeConfig {\n context?: FunctionContext;\n env?: Record<string, string | undefined>;\n}\n\n/** The platform data plane. Override with REVENEXX_DATA_ENDPOINT when needed. */\nexport const DEFAULT_DATA_ENDPOINT = 'https://apps.api.revenexx.com';\n\n/**\n * Production adapter: a `remote` adapter auto-configured from the function's\n * per-invocation context. Token = the brokered identity forwarded as\n * `x-revenexx-context`; tenant = `x-revenexx-tenant`; endpoint = env, falling\n * back to the platform data plane — deployed apps work with zero configuration.\n * App code stays identical — only the adapter selection differs between local\n * and prod.\n */\nexport function createRuntimeAdapter(config: RuntimeConfig = {}): Adapter {\n const env = config.env ?? process.env;\n const h = config.context?.req?.headers ?? {};\n const get = (name: string): string => h[name] ?? h[name.toLowerCase()] ?? '';\n\n const remote = createRemoteAdapter({\n endpoint: env.REVENEXX_DATA_ENDPOINT || DEFAULT_DATA_ENDPOINT,\n token: get('x-revenexx-context') || env.REVENEXX_CONTEXT || '',\n tenant: get('x-revenexx-tenant') || env.REVENEXX_TENANT || '',\n // Active market forwarded to the data layer. It ASSIGNS the market on\n // insert and filters reads only through a `*_scoped` view — generated\n // entities read the base table, so on the app path a list is unaffected by\n // it. See RemoteConfig.market; absent is a no-op on reads, not a narrower\n // default.\n market: get('x-revenexx-market') || env.REVENEXX_MARKET || '',\n });\n\n return { ...remote, kind: 'runtime' };\n}\n","import type { Adapter } from '../types.js';\nimport { createMockAdapter, applyDefaults } from './mock.js';\nimport { createRemoteAdapter } from './remote.js';\nimport { createRuntimeAdapter } from './runtime.js';\n\n/**\n * Adapter registry. Built-ins (mock | remote | runtime) are registered below;\n * add a new backend by calling `registerAdapter('my-kind', (config) => …)`\n * before constructing the client — no changes to the client or generated code.\n */\nexport type AdapterFactory = (config: Record<string, any>) => Adapter;\n\nconst registry = new Map<string, AdapterFactory>();\n\nexport function registerAdapter(kind: string, factory: AdapterFactory): void {\n registry.set(kind, factory);\n}\n\nexport function adapterKinds(): string[] {\n return [...registry.keys()];\n}\n\nexport function createAdapter(config: { adapter?: string } & Record<string, any>): Adapter {\n const kind = config.adapter ?? '';\n const factory = registry.get(kind);\n if (!factory) {\n const known = adapterKinds().join(' | ') || 'none registered';\n throw new Error(`app-sdk: unknown adapter '${kind}' (${known})`);\n }\n return factory(config);\n}\n\nregisterAdapter('mock', (c) => createMockAdapter(c.seed));\nregisterAdapter('remote', (c) => createRemoteAdapter(c as { endpoint: string }));\nregisterAdapter('runtime', (c) => createRuntimeAdapter(c));\n\nexport { createMockAdapter, createRemoteAdapter, createRuntimeAdapter, applyDefaults };\n","import type {\n Adapter,\n EmitOptions,\n EmitResult,\n EmittedEvent,\n Entity,\n EventDescriptor,\n Op,\n Page,\n Query,\n Row,\n} from './types.js';\nimport { createAdapter } from './adapters/index.js';\nimport { assertUpdatable } from './patch.js';\n\n/** manifest `permissions` access → entity client methods. */\nconst ACCESS_TO_OPS: Record<string, Op[]> = {\n read: ['list', 'get'],\n create: ['create'],\n update: ['update'],\n delete: ['delete'],\n};\n\n/** Map a manifest access list (e.g. ['read','create']) to a Set of ops. */\nexport function opsFromAccess(access: string[] = []): Set<Op> {\n const ops = new Set<Op>();\n for (const a of access) (ACCESS_TO_OPS[a] ?? []).forEach((o) => ops.add(o));\n return ops;\n}\n\n/** The methods exposed for a single entity; absent ops throw at call time. */\nexport interface EntityClient<T extends Row = Row, Create extends Row = T> {\n list(query?: Query<T>): Promise<T[]>;\n /** Like `list`, but also returns the total count of matching rows (for pagination). */\n page(query?: Query<T>): Promise<Page<T>>;\n get(id: string | number): Promise<T | null>;\n create(data: Create): Promise<T>;\n update(id: string | number, patch: Partial<Create>): Promise<T>;\n delete(id: string | number): Promise<void>;\n}\n\nfunction entityClient(adapter: Adapter, entity: Entity): EntityClient {\n const ops = entity.ops instanceof Set ? entity.ops : new Set<Op>(entity.ops ?? ['list', 'get', 'create', 'update', 'delete']);\n const guard = <F extends (...args: never[]) => unknown>(op: Op, fn: F): F =>\n (ops.has(op)\n ? fn\n : (() => {\n throw new Error(\n `${entity.name}.${op}() is not permitted — add the matching access to manifest.permissions for '${entity.name}'`,\n );\n }) as unknown as F);\n\n return {\n list: guard('list', (query?: Query) => adapter.list(entity, query ?? {})),\n page: guard('list', (query?: Query) => {\n if (!adapter.page) {\n throw new Error(`${entity.name}.page() is not supported by the '${adapter.kind}' adapter`);\n }\n return adapter.page(entity, query ?? {});\n }),\n get: guard('get', (id: string | number) => adapter.get(entity, id)),\n create: guard('create', (data: Row) => adapter.create(entity, data)),\n // A patch with no fields is a malformed request, not a write: PostgREST\n // performs no update and returns no row, which used to leave the App\n // serialising `undefined` and answering 500 (see ./patch.ts). Rejected here\n // rather than in `mountCrud` so every App gets it — hand-written PUT\n // handlers that call `update()` directly were the ones that broke.\n //\n // `async` on purpose: a rejected promise, not a synchronous throw, so a bad\n // patch is handled like any other data-plane failure (`await` / `.catch()`)\n // and the declared `Promise<T>` stays honest.\n update: guard('update', async (id: string | number, patch: Row) => {\n assertUpdatable(patch);\n return adapter.update(entity, id, patch);\n }),\n delete: guard('delete', (id: string | number) => adapter.remove(entity, id)),\n } as EntityClient;\n}\n\n/**\n * The App's own events: the routine Baseline generated for it, and the events\n * its manifest declares `trigger: \"app\"`. Absent when the App declares none —\n * then `db.events` does not exist at all, so a stray emit is a TypeError at the\n * call site rather than a request that fails three hops away.\n */\nexport interface EventsConfig {\n /** The generated routine, e.g. `revenexx__inventories__emit`. */\n fn: string;\n declared: Record<string, EventDescriptor>;\n}\n\nexport interface ClientConfig {\n adapter: string;\n entities: Record<string, Omit<Entity, 'name'>>;\n events?: EventsConfig;\n [key: string]: unknown;\n}\n\n/** Fire one of the App's own declared events. */\nexport interface EventsClient {\n emit(name: string, data?: Row, options?: EmitOptions): Promise<EmitResult>;\n /** What was emitted, for tests. Only the `mock` adapter records. */\n emitted(): EmittedEvent[];\n /** The declared events, as generated from the manifest. */\n readonly declared: Record<string, EventDescriptor>;\n}\n\nexport type Client = Record<string, EntityClient> & {\n readonly __adapter: string;\n readonly events?: EventsClient;\n};\n\n/**\n * The events client.\n *\n * The name check happens here, before the round trip, because this is where the\n * declared set actually lives. The generated routine refuses an undeclared name\n * too — that is the backstop — but it can only answer with a Postgres error the\n * error mapper has to reduce to \"a value in the request has the wrong format\",\n * and a typo in an event name deserves to say so.\n */\nfunction eventsClient(adapter: Adapter, config: EventsConfig): EventsClient {\n const names = (): string => Object.keys(config.declared).sort().join(', ') || '(none)';\n\n return {\n declared: config.declared,\n async emit(name: string, data: Row = {}, options: EmitOptions = {}): Promise<EmitResult> {\n const descriptor = config.declared[name];\n if (!descriptor) {\n throw new Error(\n `events.emit('${name}'): not declared by this app — add it to manifest.json events.emits[] with \"trigger\": \"app\". Declared: ${names()}`,\n );\n }\n if (!adapter.emit) {\n throw new Error(`events.emit('${name}') is not supported by the '${adapter.kind}' adapter`);\n }\n return adapter.emit({ fn: config.fn, name, descriptor }, data, options);\n },\n emitted(): EmittedEvent[] {\n if (!adapter.emitted) {\n throw new Error(\n `events.emitted() is only available on the 'mock' adapter — the '${adapter.kind}' adapter publishes for real`,\n );\n }\n return adapter.emitted();\n },\n };\n}\n\n/**\n * Build a typed entity client.\n * local dev : createClient({ adapter: 'mock', entities, seed })\n * dev tenant: createClient({ adapter: 'remote', entities, endpoint, token, tenant })\n * production: createClient({ adapter: 'runtime', entities, context }) // in the function\n */\nexport function createClient(config: ClientConfig): Client {\n if (!config?.entities) throw new Error('app-sdk: createClient needs { adapter, entities }');\n const adapter = createAdapter(config);\n const db = Object.create({ __adapter: adapter.kind }) as Client;\n for (const [name, def] of Object.entries(config.entities)) {\n db[name] = entityClient(adapter, { name, ...def });\n }\n if (config.events?.fn) {\n Object.defineProperty(db, 'events', {\n value: eventsClient(adapter, config.events),\n enumerable: true,\n });\n }\n return db;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,kBAAkB;;;ACQ3B,IAAM,MAAM,oBAAI,IAAc,CAAC,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,QAAQ,SAAS,MAAM,IAAI,CAAC;AAG3F,SAAS,SAAS,QAAe,CAAC,GAAoB;AAC3D,QAAM,SAAS,IAAI,gBAAgB;AACnC,QAAM,EAAE,QAAQ,CAAC,GAAG,QAAQ,OAAO,OAAO,OAAO,IAAI;AAErD,aAAW,CAAC,KAAK,IAAI,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC/C,QAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,aAAO,OAAO,KAAK,OAAO,KAAK,KAAK,GAAG,CAAC,GAAG;AAAA,IAC7C,W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QACvI;AAAA,MACF;AACA,UAAI,CAAC,QAAQ,MAAM;AACjB,cAAM,IAAI,MAAM,gBAAgB,IAAI,+BAA+B,QAAQ,IAAI,WAAW;AAAA,MAC5F;AACA,aAAO,QAAQ,KAAK,EAAE,IAAI,OAAO,IAAI,MAAM,WAAW,GAAG,MAAM,OAAO;AAAA,IACxE;AAAA,IACA,UAA0B;AACxB,UAAI,CAAC,QAAQ,SAAS;AACpB,cAAM,IAAI;AAAA,UACR,wEAAmE,QAAQ,IAAI;AAAA,QACjF;AAAA,MACF;AACA,aAAO,QAAQ,QAAQ;AAAA,IACzB;AAAA,EACF;AACF;AAQO,SAAS,aAAa,QAA8B;AACzD,MAAI,CAAC,QAAQ,SAAU,OAAM,IAAI,MAAM,mDAAmD;AAC1F,QAAM,UAAU,cAAc,MAAM;AACpC,QAAM,KAAK,uBAAO,OAAO,EAAE,WAAW,QAAQ,KAAK,CAAC;AACpD,aAAW,CAAC,MAAM,GAAG,KAAK,OAAO,QAAQ,OAAO,QAAQ,GAAG;AACzD,OAAG,IAAI,IAAI,aAAa,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;AAAA,EACnD;AACA,MAAI,OAAO,QAAQ,IAAI;AACrB,WAAO,eAAe,IAAI,UAAU;AAAA,MAClC,OAAO,aAAa,SAAS,OAAO,MAAM;AAAA,MAC1C,YAAY;AAAA,IACd,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":[]}
@@ -500,7 +500,7 @@ function assertJsonFilter(column, value) {
500
500
  } catch {
501
501
  throw new HttpError(
502
502
  400,
503
- `filter '${column}' must be a whole JSON document, compared for equality \u2014 e.g. ${column}={"de":"Hauptlager"}. It is not a path or containment query.`,
503
+ `filter '${column}' must be a whole JSON document, serialized exactly as stored and compared for equality \u2014 not a path or containment query. This parameter's example in the API contract shows the shape this column holds.`,
504
504
  void 0,
505
505
  { code: "invalid_value" }
506
506
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/router/index.ts","../../src/instrument.ts","../../src/router/router.ts","../../src/settings.ts","../../src/errors.ts","../../src/patch.ts","../../src/router/crud.ts"],"sourcesContent":["/**\n * @revenexx/app-sdk/router — declarative HTTP routing for revenexx App\n * functions. Pair with the generated data client for clean, testable handlers.\n */\n\n// Side effect: auto-start OpenTelemetry when OTEL_* env is configured. Runs in the\n// app's code context (where OTel deps resolve), so no NODE_OPTIONS preload is needed.\nimport '../instrument.js';\n\nexport {\n createApp,\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n} from './router.js';\nexport type {\n HttpErrorOptions,\n App,\n AppOptions,\n Handler,\n RouteContext,\n FnContext,\n FnRequest,\n FnResponse,\n} from './router.js';\n\nexport { mountCrud } from './crud.js';\nexport type { CrudOptions, RepoLike } from './crud.js';\n\n// App settings. `createApp` builds a reader for you (`c.settings()`); create\n// one directly when code outside a handler needs the same values.\nexport {\n createSettings,\n DEFAULT_GATEWAY_ENDPOINT,\n DEFAULT_SETTINGS_TTL_MS,\n DEFAULT_SETTINGS_ERROR_TTL_MS,\n DEFAULT_SETTINGS_TIMEOUT_MS,\n} from '../settings.js';\nexport type {\n SettingsReader,\n SettingsOptions,\n SettingsSnapshot,\n SettingsSource,\n SettingsDefaults,\n ResolvedSettings,\n ReadOptions,\n} from '../settings.js';\n","/**\n * OpenTelemetry bootstrap for revenexx App functions.\n *\n * Loaded automatically as a side effect of importing `@revenexx/app-sdk/router`\n * (the app requires the router from its own code dir, so OTel deps resolve).\n * Do NOT preload via `NODE_OPTIONS=--require` in open-runtimes: that runs in the\n * runtime server's node process, which cannot resolve the app's node_modules and\n * crashes the runtime.\n *\n * Configuration is 100% standard `OTEL_*` env; with no OTLP endpoint set it is a\n * cheap no-op (the heavy OTel packages aren't even loaded):\n * OTEL_EXPORTER_OTLP_ENDPOINT https://traces.revenexx.com\n * OTEL_EXPORTER_OTLP_HEADERS Authorization=Basic <base64>\n * OTEL_SERVICE_NAME products\n * OTEL_RESOURCE_ATTRIBUTES service.namespace=revenue-cloud,deployment.environment=prod\n *\n * Lean: only outbound undici/fetch (the PostgREST data plane) is auto-instrumented.\n * The per-invocation SERVER span is added by the router (createApp).\n */\n\nlet started = false;\n\n/**\n * Start OpenTelemetry once. Safe to call repeatedly. NEVER throws — a telemetry\n * failure must not take the function down (a missing trace beats a dead runtime).\n */\nexport async function startTelemetry(): Promise<void> {\n if (started) {\n return;\n }\n started = true;\n\n const endpoint =\n process.env['OTEL_EXPORTER_OTLP_TRACES_ENDPOINT'] ?? process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? '';\n if (!endpoint) {\n return; // tracing disabled — don't even load the OTel packages\n }\n\n try {\n const [{ NodeSDK }, { OTLPTraceExporter }, { UndiciInstrumentation }] = await Promise.all([\n import('@opentelemetry/sdk-node'),\n import('@opentelemetry/exporter-trace-otlp-proto'),\n import('@opentelemetry/instrumentation-undici'),\n ]);\n\n // Exporter + resource (service.name, resource attrs) are read from OTEL_* env.\n const sdk = new NodeSDK({\n traceExporter: new OTLPTraceExporter(),\n instrumentations: [new UndiciInstrumentation()],\n });\n\n sdk.start();\n\n const flush = (): void => {\n void sdk.shutdown().catch(() => {\n /* best effort */\n });\n };\n process.once('SIGTERM', flush);\n process.once('SIGINT', flush);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n '[app-sdk] OpenTelemetry init failed, continuing without tracing:',\n err instanceof Error ? err.message : err,\n );\n }\n}\n\n// Auto-start on import (side effect). Fire-and-forget; never blocks or throws.\nvoid startTelemetry();\n","/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\nimport { 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 /** 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 } 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({ error: `method ${method} not allowed for ${path}` }, 405);\n }\n return res.json({ error: `no route for ${method} ${path}`, 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 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(\n {\n error: err.message,\n ...(err.code ? { code: err.code } : {}),\n ...(err.details != null ? { details: err.details } : {}),\n },\n err.status,\n );\n }\n const msg = err instanceof Error ? err.message : String(err);\n if (/not permitted/.test(msg)) {\n span.setAttribute('http.response.status_code', 403);\n return res.json({ error: msg }, 403);\n }\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({ error: msg }, 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * App settings — the tenant's configuration for THIS app, read at runtime.\n *\n * An App declares its settings in `settings.json` (`{ settings: { <key>:\n * { type, scope, default, sensitive, ... } } }`). The cockpit renders that\n * schema, Console stores the tenant's chosen values, and the gateway resolves\n * the two into an effective map:\n *\n * GET {gateway}/v1/settings/apps/{app}[?market={code}]\n * -> { app, market, settings: { … }, masked: [ … ] }\n *\n * Resolution happens ON THE GATEWAY, and this reader does not second-guess it.\n * Per key, the gateway applies (api/internal/gateway/settings.go,\n * `resolveSettings`):\n *\n * 1. per-market override — only for settings declared `\"scope\": \"market\"`,\n * and only when `?market=` is sent\n * 2. stored tenant value — the flat value in `settings_values`\n * 3. schema default — the `default` from settings.json\n *\n * Settings flagged `sensitive` are never in `settings`; their keys are listed\n * in `masked` so a caller can tell \"not configured\" from \"not for you\".\n *\n * The `defaults` you pass here are a *fourth*, last-resort layer: they are what\n * the app runs on when the settings service cannot be reached, and they are\n * what types the resolved object. They never override a value the gateway\n * actually resolved — only a `null`/absent one.\n *\n * const settings = createSettings({\n * app: 'orders',\n * defaults: { auto_reserve: true, reservation_minutes: 30 },\n * });\n *\n * app.post('/orders', async (c) => {\n * const s = await settings.get(c); // market taken from the request\n * if (s.auto_reserve) { … }\n * });\n *\n * Or let the router own it — `createApp({ name, settings: { defaults } })`\n * gives every handler `await c.settings()`.\n *\n * Two properties make this safe to call on every request:\n *\n * - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that\n * declares no settings at all: you get the last good values if there are\n * any, otherwise your declared defaults. It never throws and never takes\n * the app down. Availability is the default; switching something off is\n * the deliberate act, and a deliberate act must not be the accident.\n * - it CACHES. Per (tenant, app, market), for a short TTL, with concurrent\n * reads sharing one in-flight request. A warm read is a Map lookup.\n */\n\n/** The platform gateway. Override with REVENEXX_GATEWAY_ENDPOINT. */\nexport const DEFAULT_GATEWAY_ENDPOINT = 'https://api.revenexx.com';\n\n/**\n * How long a resolved settings map stays warm in the process (ms).\n *\n * Settings are configuration, not data: a merchant flips one every few weeks.\n * The gateway keeps its own 30s cache in front of Console and drops it on a\n * NATS invalidation when values change, so this second layer is the only real\n * staleness — a cockpit change takes effect within a minute. That is the right\n * trade against the alternative, which is a gateway round trip on the hot path\n * of every single request.\n *\n * Override per reader (`ttlMs`) or per deployment (REVENEXX_SETTINGS_TTL_MS).\n */\nexport const DEFAULT_SETTINGS_TTL_MS = 60_000;\n\n/**\n * How long a FAILED read stays cached (ms). Short, because the failure is\n * usually transient and we want to recover quickly — but not zero, or an\n * unreachable gateway would put a doomed round trip on every request, which is\n * exactly the outage the fail-open is supposed to absorb.\n *\n * A 404 (\"app not installed or declares no settings\") is not a failure but a\n * stable answer, and is cached for the full TTL.\n */\nexport const DEFAULT_SETTINGS_ERROR_TTL_MS = 5_000;\n\n/** Request timeout (ms). A hung settings service must not hang the app. */\nexport const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;\n\nexport type SettingsDefaults = Record<string, unknown>;\n\n/**\n * The resolved map. Keys you declared in `defaults` keep their type; anything\n * else the manifest declares is still there, as `unknown`.\n */\nexport type ResolvedSettings<D extends SettingsDefaults = SettingsDefaults> = D & Record<string, unknown>;\n\n/**\n * Anything a request's tenant/token/market can be read from: the router's\n * `RouteContext`, the raw function context (`{ req: { headers } }`), or a bare\n * headers object.\n */\nexport interface SettingsSource {\n header?(name: string): string;\n tenant?: string | null;\n contextToken?: string;\n req?: { headers?: Record<string, string> | undefined } | undefined;\n headers?: Record<string, string> | undefined;\n}\n\nexport interface SettingsOptions<D extends SettingsDefaults = SettingsDefaults> {\n /**\n * The app whose settings to read. Defaults to REVENEXX_APP_NAME, which the\n * runtime sets — a deployed app usually needs no value here. `createApp`\n * passes its own `name`.\n */\n app?: string;\n /**\n * Last-resort values, and the type source. Use the same defaults your\n * settings.json declares: they are what the app runs on if the settings\n * service is unreachable.\n */\n defaults?: D;\n /** Gateway base URL. Default: REVENEXX_GATEWAY_ENDPOINT or the platform gateway. */\n endpoint?: string;\n /** Cache TTL in ms. Default: REVENEXX_SETTINGS_TTL_MS or 60_000. */\n ttlMs?: number;\n /** How long a failed read is cached, in ms. Default 5_000. */\n errorTtlMs?: number;\n /** Per-request timeout in ms. Default 2_000. */\n timeoutMs?: number;\n /** Environment to read from (tests). Default `process.env`. */\n env?: Record<string, string | undefined>;\n /** Fetch implementation (tests). Default `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /**\n * Called when a read fails and the app falls back. Wire it to the function's\n * `error()` so a silent fallback is still visible. Must not throw.\n */\n onError?: (error: Error, info: { app: string; tenant: string; market: string | null }) => void;\n}\n\n/** A resolved read, with the provenance a caller occasionally needs. */\nexport interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {\n app: string;\n tenant: string;\n /** The market the values were resolved for, or null for the tenant baseline. */\n market: string | null;\n settings: ResolvedSettings<D>;\n /** Keys that exist but are `sensitive`, so their values were withheld. */\n masked: string[];\n /** true when these values came from the gateway (fresh or cached). */\n resolved: boolean;\n /** Why the fallback happened, when `resolved` is false. */\n error?: string;\n}\n\nexport interface ReadOptions {\n /** Resolve for this market instead of the one on the request. `''` = tenant baseline. */\n market?: string;\n}\n\nexport interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {\n /** The effective settings for this request. Never throws. */\n get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/provenance. */\n load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n /** Drop the cache (tests, or right after writing settings). */\n clear(): void;\n}\n\ninterface Entry<D extends SettingsDefaults> {\n at: number;\n ttl: number;\n promise: Promise<SettingsSnapshot<D>>;\n}\n\ninterface GatewayResponse {\n settings?: Record<string, unknown>;\n masked?: unknown;\n}\n\n/** Case-insensitive header read across the three shapes we accept. */\nfunction headerOf(source: SettingsSource | undefined, name: string): string {\n if (!source) return '';\n if (typeof source.header === 'function') {\n const v = source.header(name);\n if (typeof v === 'string' && v !== '') return v;\n }\n const bags = [source.req?.headers, source.headers];\n const want = name.toLowerCase();\n for (const bag of bags) {\n if (!bag) continue;\n const direct = bag[name] ?? bag[want];\n if (typeof direct === 'string' && direct !== '') return direct;\n for (const [k, v] of Object.entries(bag)) {\n if (k.toLowerCase() === want && typeof v === 'string' && v !== '') return v;\n }\n }\n return '';\n}\n\n/**\n * Merge the gateway's resolved map over the declared defaults.\n *\n * A `null` from the gateway does NOT clobber a default: a setting the merchant\n * never touched and whose schema carries no default resolves to `null`, and a\n * caller should not have to null-check a key it declared a default for. A real\n * stored value — including `false`, `0` and `''` — always wins.\n */\nfunction mergeSettings<D extends SettingsDefaults>(\n defaults: D | undefined,\n resolved: Record<string, unknown> | undefined,\n): ResolvedSettings<D> {\n const out: Record<string, unknown> = { ...(defaults ?? {}) };\n for (const [key, value] of Object.entries(resolved ?? {})) {\n if (value !== null && value !== undefined) out[key] = value;\n else if (!(key in out)) out[key] = value ?? null;\n }\n return out as ResolvedSettings<D>;\n}\n\nfunction timeoutSignal(ms: number): AbortSignal | undefined {\n const factory = (AbortSignal as { timeout?: (ms: number) => AbortSignal }).timeout;\n if (typeof factory === 'function') return factory(ms);\n if (typeof AbortController !== 'function') return undefined;\n const controller = new AbortController();\n setTimeout(() => controller.abort(), ms).unref?.();\n return controller.signal;\n}\n\n/**\n * Build a settings reader for one app. Create it once at module scope — the\n * cache lives on the reader, and a per-request reader would cache nothing.\n */\nexport function createSettings<D extends SettingsDefaults = SettingsDefaults>(\n options: SettingsOptions<D> = {},\n): SettingsReader<D> {\n const env = options.env ?? process.env;\n const defaults = options.defaults;\n const ttlMs = options.ttlMs ?? Number(env.REVENEXX_SETTINGS_TTL_MS ?? DEFAULT_SETTINGS_TTL_MS);\n const errorTtlMs = options.errorTtlMs ?? DEFAULT_SETTINGS_ERROR_TTL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_SETTINGS_TIMEOUT_MS;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(\n /\\/+$/,\n '',\n );\n\n const cache = new Map<string, Entry<D>>();\n /** Last successful snapshot per key — served instead of defaults on a blip. */\n const lastGood = new Map<string, SettingsSnapshot<D>>();\n\n const appName = (): string => String(options.app || env.REVENEXX_APP_NAME || '').trim();\n\n const fallback = (app: string, tenant: string, market: string | null, error: string): SettingsSnapshot<D> => ({\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, undefined),\n masked: [],\n resolved: false,\n error,\n });\n\n const report = (err: Error, info: { app: string; tenant: string; market: string | null }): void => {\n try {\n options.onError?.(err, info);\n } catch {\n /* an error reporter must never be the reason a request fails */\n }\n };\n\n async function request(app: string, tenant: string, token: string, market: string | null): Promise<SettingsSnapshot<D>> {\n const f = options.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') throw new Error('settings: no fetch available (Node >=18 or pass fetchImpl)');\n\n const qs = market ? `?market=${encodeURIComponent(market)}` : '';\n const headers: Record<string, string> = { Accept: 'application/json', 'X-Revenexx-Tenant': tenant };\n if (token) headers.Authorization = `Bearer ${token}`;\n\n const signal = timeoutSignal(timeoutMs);\n const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}${qs}`, {\n method: 'GET',\n headers,\n ...(signal ? { signal } : {}),\n });\n const text = await res.text();\n if (!res.ok) {\n const err = new Error(`settings: ${res.status} for ${app}`) as Error & { status?: number };\n err.status = res.status;\n throw err;\n }\n const body = (text ? JSON.parse(text) : {}) as GatewayResponse;\n return {\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, body.settings),\n masked: Array.isArray(body.masked) ? body.masked.filter((k): k is string => typeof k === 'string') : [],\n resolved: true,\n };\n }\n\n async function load(source?: SettingsSource, readOptions: ReadOptions = {}): Promise<SettingsSnapshot<D>> {\n const app = appName();\n const tenant = (source?.tenant ?? '') || headerOf(source, 'x-revenexx-tenant');\n const market = (readOptions.market ?? headerOf(source, 'x-revenexx-market')).trim() || null;\n\n // Nothing to ask with — answer from the defaults without a round trip.\n if (!app) return fallback('', tenant, market, 'no app name (pass `app` or set REVENEXX_APP_NAME)');\n if (!tenant) return fallback(app, '', market, 'no tenant on the request');\n\n const key = `${tenant}\u0000${app}\u0000${market ?? ''}`;\n const now = Date.now();\n const hit = cache.get(key);\n if (hit && now - hit.at < hit.ttl) return hit.promise;\n\n const token = (source?.contextToken ?? '') || headerOf(source, 'x-revenexx-context');\n const entry: Entry<D> = { at: now, ttl: ttlMs, promise: undefined as unknown as Promise<SettingsSnapshot<D>> };\n entry.promise = request(app, tenant, token, market)\n .then((snapshot) => {\n lastGood.set(key, snapshot);\n return snapshot;\n })\n .catch((err: unknown) => {\n const error = err instanceof Error ? err : new Error(String(err));\n // A 404 is the gateway saying \"this app is not installed, or declares\n // no settings\" — a stable answer, not a blip. Cache it for the full TTL\n // so an app without settings does not re-ask every five seconds.\n const status = (error as { status?: number }).status;\n entry.ttl = status === 404 ? ttlMs : errorTtlMs;\n report(error, { app, tenant, market });\n // Prefer the last values we genuinely resolved over the defaults: they\n // are the tenant's actual configuration, and a gateway blip is no\n // reason to silently revert a merchant's choices.\n const stale = lastGood.get(key);\n if (stale) return { ...stale, resolved: false, error: error.message };\n return fallback(app, tenant, market, error.message);\n });\n\n // Cached before it settles, so concurrent requests share one fetch.\n cache.set(key, entry);\n return entry.promise;\n }\n\n return {\n load,\n async get(source?: SettingsSource, readOptions?: ReadOptions): Promise<ResolvedSettings<D>> {\n return (await load(source, readOptions)).settings;\n },\n clear(): void {\n cache.clear();\n lastGood.clear();\n },\n };\n}\n","/**\n * The one error representation every layer of the SDK agrees on.\n *\n * `HttpError` used to live in `./router/router.ts`. It moved here so the data\n * adapters can raise it too: an adapter that knows a PostgREST failure is a\n * duplicate key can say \"409\" without the router having to guess from a\n * message string.\n *\n * Two fields exist purely to keep internal database detail out of responses:\n * - `message` / `details` are the *client-facing* payload — always safe,\n * never derived from a database error body.\n * - `serverDetail` is the raw diagnosis. The router logs it and drops it; it\n * is never serialised into a response.\n */\n\nexport interface HttpErrorOptions {\n /** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */\n code?: string;\n /**\n * Raw diagnosis for server-side logs and traces only — may contain table and\n * constraint names. Never included in the HTTP response.\n */\n serverDetail?: unknown;\n}\n\n/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n readonly code?: string;\n readonly serverDetail?: unknown;\n /**\n * Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate\n * bundles, so an error thrown by the data client and caught by the router is\n * an instance of a *different* copy of this class — `instanceof` would be\n * false. Everything checks this flag via `isHttpError` instead.\n */\n readonly __isHttpError = true as const;\n\n constructor(status: number, message: string, details?: unknown, options: HttpErrorOptions = {}) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n if (details !== undefined) this.details = details;\n if (options.code !== undefined) this.code = options.code;\n if (options.serverDetail !== undefined) this.serverDetail = options.serverDetail;\n }\n}\n\n/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */\nexport function isHttpError(err: unknown): err is HttpError {\n if (!err || typeof err !== 'object') return false;\n const e = err as { __isHttpError?: unknown; name?: unknown; status?: unknown };\n return e.__isHttpError === true || (e.name === 'HttpError' && typeof e.status === 'number');\n}\n\nexport const notFound = (message = 'not found'): HttpError => new HttpError(404, message);\nexport const badRequest = (message = 'bad request', details?: unknown): HttpError =>\n new HttpError(400, message, details);\nexport const forbidden = (message = 'forbidden'): HttpError => new HttpError(403, message);\nexport const conflict = (message = 'conflict'): HttpError => new HttpError(409, message);\n","/**\n * What counts as an update.\n *\n * PostgREST answers a `PATCH` whose body carries no columns with `200 []` — no\n * error, no representation. The adapter then hands `rows[0]` (i.e. `undefined`)\n * back as the updated row, and the App serialises it: open-runtimes does\n * `Buffer.from(JSON.stringify(obj), 'utf8')`, and `JSON.stringify(undefined)`\n * is `undefined`, so Node throws\n *\n * TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string\n * or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\n * Received undefined\n *\n * which the App reports as a 500. A caller who sent nothing to update is told\n * the service is broken instead of what to send.\n *\n * The rule lives here, one level below the router, because not every App routes\n * its writes through `mountCrud`: `PUT /v1/greetings/{id}` and\n * `PUT /v1/payments/providers/{id}` are hand-written handlers that call\n * `db.<entity>.update()` directly, and they were the two endpoints that 500ed.\n * A guard in `mountCrud` alone only protects the Apps that happen to use it.\n */\n\nimport { badRequest } from './errors.js';\n\n/** The one wording every layer uses for \"you sent nothing to update\". */\nexport const EMPTY_UPDATE_MESSAGE = 'request body must contain at least one field to update';\n\n/**\n * The fields a patch would actually send. `undefined` values are excluded\n * because `JSON.stringify` drops them: `{ name: undefined }` reaches PostgREST\n * as `{}` and is exactly as empty as `{}` itself.\n */\nexport function updateFields(patch: unknown): string[] {\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return [];\n return Object.keys(patch as Record<string, unknown>).filter(\n (key) => (patch as Record<string, unknown>)[key] !== undefined,\n );\n}\n\n/** Throw a 400 when a patch carries nothing to write. */\nexport function assertUpdatable(patch: unknown): void {\n if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE);\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 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 /** Column metadata (from the generated ENTITIES) — enables `?col=value` list filters. */\n columns?: Record<string, unknown>;\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\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 */\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, compared for equality — ` +\n `e.g. ${column}={\"de\":\"Hauptlager\"}. It is not a path or containment query.`,\n undefined,\n { code: 'invalid_value' },\n );\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}'`);\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}'`);\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'}'`);\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 await assertParentExists(c, opts.parent);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n // A key naming no column is dropped, not refused: `filter` below echoes\n // exactly the keys that were honoured, so `filter: {}` next to a full\n // page is how a caller tells \"not filtered\" from \"filtered to nothing\".\n // Thirteen live apps document that, and 400ing instead would break every\n // client that carries a stray parameter.\n if (!opts.columns || !(k in opts.columns)) continue;\n if (isJsonColumn(opts.columns[k])) assertJsonFilter(k, v);\n where[k] = v;\n }\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);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoBA,IAAI,UAAU;AAMd,eAAsB,iBAAgC;AACpD,MAAI,SAAS;AACX;AAAA,EACF;AACA,YAAU;AAEV,QAAM,WACJ,QAAQ,IAAI,oCAAoC,KAAK,QAAQ,IAAI,6BAA6B,KAAK;AACrG,MAAI,CAAC,UAAU;AACb;AAAA,EACF;AAEA,MAAI;AACF,UAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,kBAAkB,GAAG,EAAE,sBAAsB,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,MACxF,OAAO,yBAAyB;AAAA,MAChC,OAAO,0CAA0C;AAAA,MACjD,OAAO,uCAAuC;AAAA,IAChD,CAAC;AAGD,UAAM,MAAM,IAAI,QAAQ;AAAA,MACtB,eAAe,IAAI,kBAAkB;AAAA,MACrC,kBAAkB,CAAC,IAAI,sBAAsB,CAAC;AAAA,IAChD,CAAC;AAED,QAAI,MAAM;AAEV,UAAM,QAAQ,MAAY;AACxB,WAAK,IAAI,SAAS,EAAE,MAAM,MAAM;AAAA,MAEhC,CAAC;AAAA,IACH;AACA,YAAQ,KAAK,WAAW,KAAK;AAC7B,YA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,IAAI,YAAY,OAAO,MAAM;AAC/B,YAAM,EAAE,GAAG,IAAI,MAAM,WAAW,MAAM,GAAG,IAAI;AAO7C,UAAI,aAAa,EAAE,IAAI,EAAE,WAAW,EAAG,OAAM,IAAI,UAAU,KAAK,oBAAoB;AAEpF,YAAM,QAAQ,EAAE,GAAG,EAAE,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":["headerOf","otelContext","items"]}
1
+ {"version":3,"sources":["../../src/router/index.ts","../../src/instrument.ts","../../src/router/router.ts","../../src/settings.ts","../../src/errors.ts","../../src/patch.ts","../../src/router/crud.ts"],"sourcesContent":["/**\n * @revenexx/app-sdk/router — declarative HTTP routing for revenexx App\n * functions. Pair with the generated data client for clean, testable handlers.\n */\n\n// Side effect: auto-start OpenTelemetry when OTEL_* env is configured. Runs in the\n// app's code context (where OTel deps resolve), so no NODE_OPTIONS preload is needed.\nimport '../instrument.js';\n\nexport {\n createApp,\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n} from './router.js';\nexport type {\n HttpErrorOptions,\n App,\n AppOptions,\n Handler,\n RouteContext,\n FnContext,\n FnRequest,\n FnResponse,\n} from './router.js';\n\nexport { mountCrud } from './crud.js';\nexport type { CrudOptions, RepoLike } from './crud.js';\n\n// App settings. `createApp` builds a reader for you (`c.settings()`); create\n// one directly when code outside a handler needs the same values.\nexport {\n createSettings,\n DEFAULT_GATEWAY_ENDPOINT,\n DEFAULT_SETTINGS_TTL_MS,\n DEFAULT_SETTINGS_ERROR_TTL_MS,\n DEFAULT_SETTINGS_TIMEOUT_MS,\n} from '../settings.js';\nexport type {\n SettingsReader,\n SettingsOptions,\n SettingsSnapshot,\n SettingsSource,\n SettingsDefaults,\n ResolvedSettings,\n ReadOptions,\n} from '../settings.js';\n","/**\n * OpenTelemetry bootstrap for revenexx App functions.\n *\n * Loaded automatically as a side effect of importing `@revenexx/app-sdk/router`\n * (the app requires the router from its own code dir, so OTel deps resolve).\n * Do NOT preload via `NODE_OPTIONS=--require` in open-runtimes: that runs in the\n * runtime server's node process, which cannot resolve the app's node_modules and\n * crashes the runtime.\n *\n * Configuration is 100% standard `OTEL_*` env; with no OTLP endpoint set it is a\n * cheap no-op (the heavy OTel packages aren't even loaded):\n * OTEL_EXPORTER_OTLP_ENDPOINT https://traces.revenexx.com\n * OTEL_EXPORTER_OTLP_HEADERS Authorization=Basic <base64>\n * OTEL_SERVICE_NAME products\n * OTEL_RESOURCE_ATTRIBUTES service.namespace=revenue-cloud,deployment.environment=prod\n *\n * Lean: only outbound undici/fetch (the PostgREST data plane) is auto-instrumented.\n * The per-invocation SERVER span is added by the router (createApp).\n */\n\nlet started = false;\n\n/**\n * Start OpenTelemetry once. Safe to call repeatedly. NEVER throws — a telemetry\n * failure must not take the function down (a missing trace beats a dead runtime).\n */\nexport async function startTelemetry(): Promise<void> {\n if (started) {\n return;\n }\n started = true;\n\n const endpoint =\n process.env['OTEL_EXPORTER_OTLP_TRACES_ENDPOINT'] ?? process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] ?? '';\n if (!endpoint) {\n return; // tracing disabled — don't even load the OTel packages\n }\n\n try {\n const [{ NodeSDK }, { OTLPTraceExporter }, { UndiciInstrumentation }] = await Promise.all([\n import('@opentelemetry/sdk-node'),\n import('@opentelemetry/exporter-trace-otlp-proto'),\n import('@opentelemetry/instrumentation-undici'),\n ]);\n\n // Exporter + resource (service.name, resource attrs) are read from OTEL_* env.\n const sdk = new NodeSDK({\n traceExporter: new OTLPTraceExporter(),\n instrumentations: [new UndiciInstrumentation()],\n });\n\n sdk.start();\n\n const flush = (): void => {\n void sdk.shutdown().catch(() => {\n /* best effort */\n });\n };\n process.once('SIGTERM', flush);\n process.once('SIGINT', flush);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\n '[app-sdk] OpenTelemetry init failed, continuing without tracing:',\n err instanceof Error ? err.message : err,\n );\n }\n}\n\n// Auto-start on import (side effect). Fire-and-forget; never blocks or throws.\nvoid startTelemetry();\n","/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\nimport { 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 /** 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 } 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({ error: `method ${method} not allowed for ${path}` }, 405);\n }\n return res.json({ error: `no route for ${method} ${path}`, 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 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(\n {\n error: err.message,\n ...(err.code ? { code: err.code } : {}),\n ...(err.details != null ? { details: err.details } : {}),\n },\n err.status,\n );\n }\n const msg = err instanceof Error ? err.message : String(err);\n if (/not permitted/.test(msg)) {\n span.setAttribute('http.response.status_code', 403);\n return res.json({ error: msg }, 403);\n }\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({ error: msg }, 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * App settings — the tenant's configuration for THIS app, read at runtime.\n *\n * An App declares its settings in `settings.json` (`{ settings: { <key>:\n * { type, scope, default, sensitive, ... } } }`). The cockpit renders that\n * schema, Console stores the tenant's chosen values, and the gateway resolves\n * the two into an effective map:\n *\n * GET {gateway}/v1/settings/apps/{app}[?market={code}]\n * -> { app, market, settings: { … }, masked: [ … ] }\n *\n * Resolution happens ON THE GATEWAY, and this reader does not second-guess it.\n * Per key, the gateway applies (api/internal/gateway/settings.go,\n * `resolveSettings`):\n *\n * 1. per-market override — only for settings declared `\"scope\": \"market\"`,\n * and only when `?market=` is sent\n * 2. stored tenant value — the flat value in `settings_values`\n * 3. schema default — the `default` from settings.json\n *\n * Settings flagged `sensitive` are never in `settings`; their keys are listed\n * in `masked` so a caller can tell \"not configured\" from \"not for you\".\n *\n * The `defaults` you pass here are a *fourth*, last-resort layer: they are what\n * the app runs on when the settings service cannot be reached, and they are\n * what types the resolved object. They never override a value the gateway\n * actually resolved — only a `null`/absent one.\n *\n * const settings = createSettings({\n * app: 'orders',\n * defaults: { auto_reserve: true, reservation_minutes: 30 },\n * });\n *\n * app.post('/orders', async (c) => {\n * const s = await settings.get(c); // market taken from the request\n * if (s.auto_reserve) { … }\n * });\n *\n * Or let the router own it — `createApp({ name, settings: { defaults } })`\n * gives every handler `await c.settings()`.\n *\n * Two properties make this safe to call on every request:\n *\n * - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that\n * declares no settings at all: you get the last good values if there are\n * any, otherwise your declared defaults. It never throws and never takes\n * the app down. Availability is the default; switching something off is\n * the deliberate act, and a deliberate act must not be the accident.\n * - it CACHES. Per (tenant, app, market), for a short TTL, with concurrent\n * reads sharing one in-flight request. A warm read is a Map lookup.\n */\n\n/** The platform gateway. Override with REVENEXX_GATEWAY_ENDPOINT. */\nexport const DEFAULT_GATEWAY_ENDPOINT = 'https://api.revenexx.com';\n\n/**\n * How long a resolved settings map stays warm in the process (ms).\n *\n * Settings are configuration, not data: a merchant flips one every few weeks.\n * The gateway keeps its own 30s cache in front of Console and drops it on a\n * NATS invalidation when values change, so this second layer is the only real\n * staleness — a cockpit change takes effect within a minute. That is the right\n * trade against the alternative, which is a gateway round trip on the hot path\n * of every single request.\n *\n * Override per reader (`ttlMs`) or per deployment (REVENEXX_SETTINGS_TTL_MS).\n */\nexport const DEFAULT_SETTINGS_TTL_MS = 60_000;\n\n/**\n * How long a FAILED read stays cached (ms). Short, because the failure is\n * usually transient and we want to recover quickly — but not zero, or an\n * unreachable gateway would put a doomed round trip on every request, which is\n * exactly the outage the fail-open is supposed to absorb.\n *\n * A 404 (\"app not installed or declares no settings\") is not a failure but a\n * stable answer, and is cached for the full TTL.\n */\nexport const DEFAULT_SETTINGS_ERROR_TTL_MS = 5_000;\n\n/** Request timeout (ms). A hung settings service must not hang the app. */\nexport const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;\n\nexport type SettingsDefaults = Record<string, unknown>;\n\n/**\n * The resolved map. Keys you declared in `defaults` keep their type; anything\n * else the manifest declares is still there, as `unknown`.\n */\nexport type ResolvedSettings<D extends SettingsDefaults = SettingsDefaults> = D & Record<string, unknown>;\n\n/**\n * Anything a request's tenant/token/market can be read from: the router's\n * `RouteContext`, the raw function context (`{ req: { headers } }`), or a bare\n * headers object.\n */\nexport interface SettingsSource {\n header?(name: string): string;\n tenant?: string | null;\n contextToken?: string;\n req?: { headers?: Record<string, string> | undefined } | undefined;\n headers?: Record<string, string> | undefined;\n}\n\nexport interface SettingsOptions<D extends SettingsDefaults = SettingsDefaults> {\n /**\n * The app whose settings to read. Defaults to REVENEXX_APP_NAME, which the\n * runtime sets — a deployed app usually needs no value here. `createApp`\n * passes its own `name`.\n */\n app?: string;\n /**\n * Last-resort values, and the type source. Use the same defaults your\n * settings.json declares: they are what the app runs on if the settings\n * service is unreachable.\n */\n defaults?: D;\n /** Gateway base URL. Default: REVENEXX_GATEWAY_ENDPOINT or the platform gateway. */\n endpoint?: string;\n /** Cache TTL in ms. Default: REVENEXX_SETTINGS_TTL_MS or 60_000. */\n ttlMs?: number;\n /** How long a failed read is cached, in ms. Default 5_000. */\n errorTtlMs?: number;\n /** Per-request timeout in ms. Default 2_000. */\n timeoutMs?: number;\n /** Environment to read from (tests). Default `process.env`. */\n env?: Record<string, string | undefined>;\n /** Fetch implementation (tests). Default `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /**\n * Called when a read fails and the app falls back. Wire it to the function's\n * `error()` so a silent fallback is still visible. Must not throw.\n */\n onError?: (error: Error, info: { app: string; tenant: string; market: string | null }) => void;\n}\n\n/** A resolved read, with the provenance a caller occasionally needs. */\nexport interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {\n app: string;\n tenant: string;\n /** The market the values were resolved for, or null for the tenant baseline. */\n market: string | null;\n settings: ResolvedSettings<D>;\n /** Keys that exist but are `sensitive`, so their values were withheld. */\n masked: string[];\n /** true when these values came from the gateway (fresh or cached). */\n resolved: boolean;\n /** Why the fallback happened, when `resolved` is false. */\n error?: string;\n}\n\nexport interface ReadOptions {\n /** Resolve for this market instead of the one on the request. `''` = tenant baseline. */\n market?: string;\n}\n\nexport interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {\n /** The effective settings for this request. Never throws. */\n get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/provenance. */\n load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n /** Drop the cache (tests, or right after writing settings). */\n clear(): void;\n}\n\ninterface Entry<D extends SettingsDefaults> {\n at: number;\n ttl: number;\n promise: Promise<SettingsSnapshot<D>>;\n}\n\ninterface GatewayResponse {\n settings?: Record<string, unknown>;\n masked?: unknown;\n}\n\n/** Case-insensitive header read across the three shapes we accept. */\nfunction headerOf(source: SettingsSource | undefined, name: string): string {\n if (!source) return '';\n if (typeof source.header === 'function') {\n const v = source.header(name);\n if (typeof v === 'string' && v !== '') return v;\n }\n const bags = [source.req?.headers, source.headers];\n const want = name.toLowerCase();\n for (const bag of bags) {\n if (!bag) continue;\n const direct = bag[name] ?? bag[want];\n if (typeof direct === 'string' && direct !== '') return direct;\n for (const [k, v] of Object.entries(bag)) {\n if (k.toLowerCase() === want && typeof v === 'string' && v !== '') return v;\n }\n }\n return '';\n}\n\n/**\n * Merge the gateway's resolved map over the declared defaults.\n *\n * A `null` from the gateway does NOT clobber a default: a setting the merchant\n * never touched and whose schema carries no default resolves to `null`, and a\n * caller should not have to null-check a key it declared a default for. A real\n * stored value — including `false`, `0` and `''` — always wins.\n */\nfunction mergeSettings<D extends SettingsDefaults>(\n defaults: D | undefined,\n resolved: Record<string, unknown> | undefined,\n): ResolvedSettings<D> {\n const out: Record<string, unknown> = { ...(defaults ?? {}) };\n for (const [key, value] of Object.entries(resolved ?? {})) {\n if (value !== null && value !== undefined) out[key] = value;\n else if (!(key in out)) out[key] = value ?? null;\n }\n return out as ResolvedSettings<D>;\n}\n\nfunction timeoutSignal(ms: number): AbortSignal | undefined {\n const factory = (AbortSignal as { timeout?: (ms: number) => AbortSignal }).timeout;\n if (typeof factory === 'function') return factory(ms);\n if (typeof AbortController !== 'function') return undefined;\n const controller = new AbortController();\n setTimeout(() => controller.abort(), ms).unref?.();\n return controller.signal;\n}\n\n/**\n * Build a settings reader for one app. Create it once at module scope — the\n * cache lives on the reader, and a per-request reader would cache nothing.\n */\nexport function createSettings<D extends SettingsDefaults = SettingsDefaults>(\n options: SettingsOptions<D> = {},\n): SettingsReader<D> {\n const env = options.env ?? process.env;\n const defaults = options.defaults;\n const ttlMs = options.ttlMs ?? Number(env.REVENEXX_SETTINGS_TTL_MS ?? DEFAULT_SETTINGS_TTL_MS);\n const errorTtlMs = options.errorTtlMs ?? DEFAULT_SETTINGS_ERROR_TTL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_SETTINGS_TIMEOUT_MS;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(\n /\\/+$/,\n '',\n );\n\n const cache = new Map<string, Entry<D>>();\n /** Last successful snapshot per key — served instead of defaults on a blip. */\n const lastGood = new Map<string, SettingsSnapshot<D>>();\n\n const appName = (): string => String(options.app || env.REVENEXX_APP_NAME || '').trim();\n\n const fallback = (app: string, tenant: string, market: string | null, error: string): SettingsSnapshot<D> => ({\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, undefined),\n masked: [],\n resolved: false,\n error,\n });\n\n const report = (err: Error, info: { app: string; tenant: string; market: string | null }): void => {\n try {\n options.onError?.(err, info);\n } catch {\n /* an error reporter must never be the reason a request fails */\n }\n };\n\n async function request(app: string, tenant: string, token: string, market: string | null): Promise<SettingsSnapshot<D>> {\n const f = options.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') throw new Error('settings: no fetch available (Node >=18 or pass fetchImpl)');\n\n const qs = market ? `?market=${encodeURIComponent(market)}` : '';\n const headers: Record<string, string> = { Accept: 'application/json', 'X-Revenexx-Tenant': tenant };\n if (token) headers.Authorization = `Bearer ${token}`;\n\n const signal = timeoutSignal(timeoutMs);\n const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}${qs}`, {\n method: 'GET',\n headers,\n ...(signal ? { signal } : {}),\n });\n const text = await res.text();\n if (!res.ok) {\n const err = new Error(`settings: ${res.status} for ${app}`) as Error & { status?: number };\n err.status = res.status;\n throw err;\n }\n const body = (text ? JSON.parse(text) : {}) as GatewayResponse;\n return {\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, body.settings),\n masked: Array.isArray(body.masked) ? body.masked.filter((k): k is string => typeof k === 'string') : [],\n resolved: true,\n };\n }\n\n async function load(source?: SettingsSource, readOptions: ReadOptions = {}): Promise<SettingsSnapshot<D>> {\n const app = appName();\n const tenant = (source?.tenant ?? '') || headerOf(source, 'x-revenexx-tenant');\n const market = (readOptions.market ?? headerOf(source, 'x-revenexx-market')).trim() || null;\n\n // Nothing to ask with — answer from the defaults without a round trip.\n if (!app) return fallback('', tenant, market, 'no app name (pass `app` or set REVENEXX_APP_NAME)');\n if (!tenant) return fallback(app, '', market, 'no tenant on the request');\n\n const key = `${tenant}\u0000${app}\u0000${market ?? ''}`;\n const now = Date.now();\n const hit = cache.get(key);\n if (hit && now - hit.at < hit.ttl) return hit.promise;\n\n const token = (source?.contextToken ?? '') || headerOf(source, 'x-revenexx-context');\n const entry: Entry<D> = { at: now, ttl: ttlMs, promise: undefined as unknown as Promise<SettingsSnapshot<D>> };\n entry.promise = request(app, tenant, token, market)\n .then((snapshot) => {\n lastGood.set(key, snapshot);\n return snapshot;\n })\n .catch((err: unknown) => {\n const error = err instanceof Error ? err : new Error(String(err));\n // A 404 is the gateway saying \"this app is not installed, or declares\n // no settings\" — a stable answer, not a blip. Cache it for the full TTL\n // so an app without settings does not re-ask every five seconds.\n const status = (error as { status?: number }).status;\n entry.ttl = status === 404 ? ttlMs : errorTtlMs;\n report(error, { app, tenant, market });\n // Prefer the last values we genuinely resolved over the defaults: they\n // are the tenant's actual configuration, and a gateway blip is no\n // reason to silently revert a merchant's choices.\n const stale = lastGood.get(key);\n if (stale) return { ...stale, resolved: false, error: error.message };\n return fallback(app, tenant, market, error.message);\n });\n\n // Cached before it settles, so concurrent requests share one fetch.\n cache.set(key, entry);\n return entry.promise;\n }\n\n return {\n load,\n async get(source?: SettingsSource, readOptions?: ReadOptions): Promise<ResolvedSettings<D>> {\n return (await load(source, readOptions)).settings;\n },\n clear(): void {\n cache.clear();\n lastGood.clear();\n },\n };\n}\n","/**\n * The one error representation every layer of the SDK agrees on.\n *\n * `HttpError` used to live in `./router/router.ts`. It moved here so the data\n * adapters can raise it too: an adapter that knows a PostgREST failure is a\n * duplicate key can say \"409\" without the router having to guess from a\n * message string.\n *\n * Two fields exist purely to keep internal database detail out of responses:\n * - `message` / `details` are the *client-facing* payload — always safe,\n * never derived from a database error body.\n * - `serverDetail` is the raw diagnosis. The router logs it and drops it; it\n * is never serialised into a response.\n */\n\nexport interface HttpErrorOptions {\n /** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */\n code?: string;\n /**\n * Raw diagnosis for server-side logs and traces only — may contain table and\n * constraint names. Never included in the HTTP response.\n */\n serverDetail?: unknown;\n}\n\n/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n readonly code?: string;\n readonly serverDetail?: unknown;\n /**\n * Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate\n * bundles, so an error thrown by the data client and caught by the router is\n * an instance of a *different* copy of this class — `instanceof` would be\n * false. Everything checks this flag via `isHttpError` instead.\n */\n readonly __isHttpError = true as const;\n\n constructor(status: number, message: string, details?: unknown, options: HttpErrorOptions = {}) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n if (details !== undefined) this.details = details;\n if (options.code !== undefined) this.code = options.code;\n if (options.serverDetail !== undefined) this.serverDetail = options.serverDetail;\n }\n}\n\n/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */\nexport function isHttpError(err: unknown): err is HttpError {\n if (!err || typeof err !== 'object') return false;\n const e = err as { __isHttpError?: unknown; name?: unknown; status?: unknown };\n return e.__isHttpError === true || (e.name === 'HttpError' && typeof e.status === 'number');\n}\n\nexport const notFound = (message = 'not found'): HttpError => new HttpError(404, message);\nexport const badRequest = (message = 'bad request', details?: unknown): HttpError =>\n new HttpError(400, message, details);\nexport const forbidden = (message = 'forbidden'): HttpError => new HttpError(403, message);\nexport const conflict = (message = 'conflict'): HttpError => new HttpError(409, message);\n","/**\n * What counts as an update.\n *\n * PostgREST answers a `PATCH` whose body carries no columns with `200 []` — no\n * error, no representation. The adapter then hands `rows[0]` (i.e. `undefined`)\n * back as the updated row, and the App serialises it: open-runtimes does\n * `Buffer.from(JSON.stringify(obj), 'utf8')`, and `JSON.stringify(undefined)`\n * is `undefined`, so Node throws\n *\n * TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string\n * or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\n * Received undefined\n *\n * which the App reports as a 500. A caller who sent nothing to update is told\n * the service is broken instead of what to send.\n *\n * The rule lives here, one level below the router, because not every App routes\n * its writes through `mountCrud`: `PUT /v1/greetings/{id}` and\n * `PUT /v1/payments/providers/{id}` are hand-written handlers that call\n * `db.<entity>.update()` directly, and they were the two endpoints that 500ed.\n * A guard in `mountCrud` alone only protects the Apps that happen to use it.\n */\n\nimport { badRequest } from './errors.js';\n\n/** The one wording every layer uses for \"you sent nothing to update\". */\nexport const EMPTY_UPDATE_MESSAGE = 'request body must contain at least one field to update';\n\n/**\n * The fields a patch would actually send. `undefined` values are excluded\n * because `JSON.stringify` drops them: `{ name: undefined }` reaches PostgREST\n * as `{}` and is exactly as empty as `{}` itself.\n */\nexport function updateFields(patch: unknown): string[] {\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return [];\n return Object.keys(patch as Record<string, unknown>).filter(\n (key) => (patch as Record<string, unknown>)[key] !== undefined,\n );\n}\n\n/** Throw a 400 when a patch carries nothing to write. */\nexport function assertUpdatable(patch: unknown): void {\n if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE);\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 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 /** Column metadata (from the generated ENTITIES) — enables `?col=value` list filters. */\n columns?: Record<string, unknown>;\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\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\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}'`);\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}'`);\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'}'`);\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 await assertParentExists(c, opts.parent);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n // A key naming no column is dropped, not refused: `filter` below echoes\n // exactly the keys that were honoured, so `filter: {}` next to a full\n // page is how a caller tells \"not filtered\" from \"filtered to nothing\".\n // Thirteen live apps document that, and 400ing instead would break every\n // client that carries a stray parameter.\n if (!opts.columns || !(k in opts.columns)) continue;\n if (isJsonColumn(opts.columns[k])) assertJsonFilter(k, v);\n where[k] = v;\n }\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);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoBA,IAAI,UAAU;AAMd,eAAsB,iBAAgC;AACpD,MAAI,SAAS;AACX;AAAA,EACF;AACA,YAAU;AAEV,QAAM,WACJ,QAAQ,IAAI,oCAAoC,KAAK,QAAQ,IAAI,6BAA6B,KAAK;AACrG,MAAI,CAAC,UAAU;AACb;AAAA,EACF;AAEA,MAAI;AACF,UAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,kBAAkB,GAAG,EAAE,sBAAsB,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,MACxF,OAAO,yBAAyB;AAAA,MAChC,OAAO,0CAA0C;AAAA,MACjD,OAAO,uCAAuC;AAAA,IAChD,CAAC;AAGD,UAAM,MAAM,IAAI,QAAQ;AAAA,MACtB,eAAe,IAAI,kBAAkB;AAAA,MACrC,kBAAkB,CAAC,IAAI,sBAAsB,CAAC;AAAA,IAChD,CAAC;AAED,QAAI,MAAM;AAEV,UAAM,QAAQ,MAAY;AACxB,WAAK,IAAI,SAAS,EAAE,MAAM,MAAM;AAAA,MAEhC,CAAC;AAAA,IACH;AACA,YAAQ,KAAK,WAAW,KAAK;AAC7B,YAAQ,KAAK,UAAU,KAAK;AAAA,EAC9B,SAAS,KAAK;AAEZ,YAAQ;AAAA,MACN;AAAA,MACA,eAAe,QAAQ,IAAI,UAAU;AAAA,IACvC;AAAA,EACF;AACF;AAGA,KAAK,eAAe;;;ACrDpB,iBAQO;;;AC4BA,IAAM,2BAA2B;AAcjC,IAAM,0BAA0B;AAWhC,IAAM,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