@revenexx/app-sdk 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as Row, Q as Query, P as Page, W as Where, E as EmitOptions, a as EmitResult, b as EmittedEvent, c as EventDescriptor, d as Entity, O as Op, A as Adapter } from './errors-BsKwZ07u.cjs';
2
- export { B as BackdatingEntity, e as BackdatingOptions, C as ColumnDef, D as DEFAULT_GATEWAY_ENDPOINT, f as DEFAULT_SETTINGS_ERROR_TTL_MS, g as DEFAULT_SETTINGS_TIMEOUT_MS, h as DEFAULT_SETTINGS_TTL_MS, i as EmitTarget, F as Filter, j as FilterOp, H as HttpError, k as HttpErrorOptions, M as MAX_MONTHS_BACK, l as ReadOptions, m as Refusal, n as ResolvedSettings, S as Scalar, o as SettingsDefaults, p as SettingsOptions, q as SettingsReader, r as SettingsSnapshot, s as SettingsSource, t as SettingsWriteResult, u as WriteOptions, v as backdated, w as backdatingDb, x as clock, y as createSettings, z as isHttpError, G as now, I as parseBackdate, J as refusalOf, K as runAt } from './errors-BsKwZ07u.cjs';
1
+ import { R as Row, Q as Query, P as Page, W as Where, E as EmitOptions, a as EmitResult, b as EmittedEvent, c as EventDescriptor, d as Entity, O as Op, A as Adapter } from './errors-CjuqA3DC.cjs';
2
+ export { B as BackdatingEntity, e as BackdatingOptions, C as ColumnDef, D as DEFAULT_GATEWAY_ENDPOINT, f as DEFAULT_SETTINGS_ERROR_TTL_MS, g as DEFAULT_SETTINGS_TIMEOUT_MS, h as DEFAULT_SETTINGS_TTL_MS, i as EmitTarget, F as Filter, j as FilterOp, H as HttpError, k as HttpErrorOptions, M as MAX_MONTHS_BACK, l as ReadOptions, m as Refusal, n as ResolvedSettings, S as Scalar, o as SettingsDefaults, p as SettingsOptions, q as SettingsReader, r as SettingsSnapshot, s as SettingsSource, t as SettingsWriteResult, u as WriteOptions, v as backdated, w as backdatingDb, x as clock, y as createSettings, z as isHttpError, G as now, I as parseBackdate, J as refusalOf, K as runAt } from './errors-CjuqA3DC.cjs';
3
3
 
4
4
  /** Map a manifest access list (e.g. ['read','create']) to a Set of ops. */
5
5
  declare function opsFromAccess(access?: string[]): Set<Op>;
@@ -10,6 +10,15 @@ interface EntityClient<T extends Row = Row, Create extends Row = T> {
10
10
  page(query?: Query<T>): Promise<Page<T>>;
11
11
  get(id: string | number): Promise<T | null>;
12
12
  create(data: Create): Promise<T>;
13
+ /**
14
+ * Bulk create: a non-empty list of records, inserted in one request. Every
15
+ * record is checked like a single create, and all of them name the same
16
+ * fields; a refusal names the record in `details.index`. Answers the created
17
+ * rows, in order. Needs the `create` permission. `create` itself takes one
18
+ * record, so a handler that writes its request body never becomes a bulk
19
+ * endpoint by accident.
20
+ */
21
+ createMany(rows: Create[]): Promise<T[]>;
13
22
  update(id: string | number, patch: Partial<Create>): Promise<T>;
14
23
  /**
15
24
  * Compare-and-set: update the row only if it still matches `where`, in one
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as Row, Q as Query, P as Page, W as Where, E as EmitOptions, a as EmitResult, b as EmittedEvent, c as EventDescriptor, d as Entity, O as Op, A as Adapter } from './errors-BsKwZ07u.js';
2
- export { B as BackdatingEntity, e as BackdatingOptions, C as ColumnDef, D as DEFAULT_GATEWAY_ENDPOINT, f as DEFAULT_SETTINGS_ERROR_TTL_MS, g as DEFAULT_SETTINGS_TIMEOUT_MS, h as DEFAULT_SETTINGS_TTL_MS, i as EmitTarget, F as Filter, j as FilterOp, H as HttpError, k as HttpErrorOptions, M as MAX_MONTHS_BACK, l as ReadOptions, m as Refusal, n as ResolvedSettings, S as Scalar, o as SettingsDefaults, p as SettingsOptions, q as SettingsReader, r as SettingsSnapshot, s as SettingsSource, t as SettingsWriteResult, u as WriteOptions, v as backdated, w as backdatingDb, x as clock, y as createSettings, z as isHttpError, G as now, I as parseBackdate, J as refusalOf, K as runAt } from './errors-BsKwZ07u.js';
1
+ import { R as Row, Q as Query, P as Page, W as Where, E as EmitOptions, a as EmitResult, b as EmittedEvent, c as EventDescriptor, d as Entity, O as Op, A as Adapter } from './errors-CjuqA3DC.js';
2
+ export { B as BackdatingEntity, e as BackdatingOptions, C as ColumnDef, D as DEFAULT_GATEWAY_ENDPOINT, f as DEFAULT_SETTINGS_ERROR_TTL_MS, g as DEFAULT_SETTINGS_TIMEOUT_MS, h as DEFAULT_SETTINGS_TTL_MS, i as EmitTarget, F as Filter, j as FilterOp, H as HttpError, k as HttpErrorOptions, M as MAX_MONTHS_BACK, l as ReadOptions, m as Refusal, n as ResolvedSettings, S as Scalar, o as SettingsDefaults, p as SettingsOptions, q as SettingsReader, r as SettingsSnapshot, s as SettingsSource, t as SettingsWriteResult, u as WriteOptions, v as backdated, w as backdatingDb, x as clock, y as createSettings, z as isHttpError, G as now, I as parseBackdate, J as refusalOf, K as runAt } from './errors-CjuqA3DC.js';
3
3
 
4
4
  /** Map a manifest access list (e.g. ['read','create']) to a Set of ops. */
5
5
  declare function opsFromAccess(access?: string[]): Set<Op>;
@@ -10,6 +10,15 @@ interface EntityClient<T extends Row = Row, Create extends Row = T> {
10
10
  page(query?: Query<T>): Promise<Page<T>>;
11
11
  get(id: string | number): Promise<T | null>;
12
12
  create(data: Create): Promise<T>;
13
+ /**
14
+ * Bulk create: a non-empty list of records, inserted in one request. Every
15
+ * record is checked like a single create, and all of them name the same
16
+ * fields; a refusal names the record in `details.index`. Answers the created
17
+ * rows, in order. Needs the `create` permission. `create` itself takes one
18
+ * record, so a handler that writes its request body never becomes a bulk
19
+ * endpoint by accident.
20
+ */
21
+ createMany(rows: Create[]): Promise<T[]>;
13
22
  update(id: string | number, patch: Partial<Create>): Promise<T>;
14
23
  /**
15
24
  * Compare-and-set: update the row only if it still matches `where`, in one
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  HttpError,
8
8
  IMPLICIT_COLUMNS,
9
9
  MAX_MONTHS_BACK,
10
+ RecordGone,
10
11
  assertCondition,
11
12
  assertCreatable,
12
13
  assertDefined,
@@ -15,6 +16,7 @@ import {
15
16
  assertUpdatable,
16
17
  backdated,
17
18
  backdatingDb,
19
+ bulkRecords,
18
20
  clock,
19
21
  createSettings,
20
22
  flagColumns,
@@ -23,10 +25,13 @@ import {
23
25
  notFound,
24
26
  now,
25
27
  parseBackdate,
28
+ pkOf,
26
29
  refusalOf,
30
+ roundTripped,
27
31
  runAt,
28
- toParams
29
- } from "./chunk-AVWPY5D2.js";
32
+ toParams,
33
+ updateFields
34
+ } from "./chunk-ZTTYOJYU.js";
30
35
 
31
36
  // src/adapters/mock.ts
32
37
  import { randomUUID } from "crypto";
@@ -60,6 +65,17 @@ function assertWhereColumns(entity, where) {
60
65
  serverDetail: { source: "mock", entity: entity.name, unknownColumns: unknown }
61
66
  });
62
67
  }
68
+ function assertUpdatableColumns(entity, patch) {
69
+ if (!patch || typeof patch !== "object") return;
70
+ const refused = [.../* @__PURE__ */ new Set([entity.pk || "id", "tenant_id"])].filter(
71
+ (k) => Object.prototype.hasOwnProperty.call(patch, k) && patch[k] !== void 0
72
+ );
73
+ if (refused.length === 0) return;
74
+ throw new HttpError(401, "unauthenticated", void 0, {
75
+ code: "bad_request",
76
+ serverDetail: { source: "mock", entity: entity.name, sqlstate: "42501", columns: refused.sort() }
77
+ });
78
+ }
63
79
  function applyDefaults(entity, data) {
64
80
  const row = { ...data };
65
81
  for (const [col, def] of Object.entries(entity.columns ?? {})) {
@@ -89,7 +105,8 @@ function createMockAdapter(seed = {}) {
89
105
  };
90
106
  const write = (entity, id, cur, patch) => {
91
107
  const row = { ...cur, ...patch };
92
- if (entity.columns?.updated_at) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
108
+ const changed = Object.keys(patch).some((k) => patch[k] !== void 0 && JSON.stringify(patch[k]) !== JSON.stringify(cur[k]));
109
+ if (entity.columns?.updated_at && changed) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
93
110
  tbl(entity).set(id, row);
94
111
  return { ...row };
95
112
  };
@@ -120,8 +137,33 @@ function createMockAdapter(seed = {}) {
120
137
  tbl(entity).set(row[entity.pk], row);
121
138
  return { ...row };
122
139
  },
140
+ // One statement in Postgres: a primary key twice in the batch, or one the
141
+ // table already holds, is the 409 the remote adapter maps from 23505, and
142
+ // nothing is stored.
143
+ async createMany(entity, data) {
144
+ const rows = bulkRecords(entity, data).map((record) => {
145
+ const row = applyDefaults(entity, record);
146
+ if (row[entity.pk] === void 0) row[entity.pk] = randomUUID();
147
+ return row;
148
+ });
149
+ const table = tbl(entity);
150
+ const seen = /* @__PURE__ */ new Set();
151
+ for (const row of rows) {
152
+ const id = row[entity.pk];
153
+ if (seen.has(id) || table.has(id)) {
154
+ throw new HttpError(409, "a record with this value already exists", void 0, {
155
+ code: "unique_violation",
156
+ serverDetail: { source: "mock", entity: entity.name, duplicate: id }
157
+ });
158
+ }
159
+ seen.add(id);
160
+ }
161
+ for (const row of rows) table.set(row[entity.pk], row);
162
+ return rows.map((row) => ({ ...row }));
163
+ },
123
164
  async update(entity, id, patch) {
124
165
  assertKnownFields(entity, patch);
166
+ assertUpdatableColumns(entity, patch);
125
167
  const cur = tbl(entity).get(id);
126
168
  if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
127
169
  return write(entity, id, cur, patch);
@@ -134,6 +176,7 @@ function createMockAdapter(seed = {}) {
134
176
  async updateIf(entity, id, where, patch) {
135
177
  assertWhereColumns(entity, where);
136
178
  assertKnownFields(entity, patch);
179
+ assertUpdatableColumns(entity, patch);
137
180
  const cur = tbl(entity).get(id);
138
181
  if (!cur || !matches(cur, where)) return null;
139
182
  return write(entity, id, cur, patch);
@@ -334,6 +377,23 @@ function createRemoteAdapter(config) {
334
377
  })
335
378
  );
336
379
  },
380
+ // One POST of the whole list: PostgREST inserts it in one statement and
381
+ // answers every row, in order. Checked here as well as in the client.
382
+ async createMany(entity, data) {
383
+ const records = bulkRecords(entity, data);
384
+ const rows = await req("POST", `/${entity.table}`, {
385
+ body: records,
386
+ prefer: "return=representation",
387
+ table: entity.table
388
+ });
389
+ if (!Array.isArray(rows) || rows.length < records.length) {
390
+ throw new HttpError(500, "the records were created but could not be read back", void 0, {
391
+ code: "empty_representation",
392
+ serverDetail: { source: "postgrest", method: "POST", table: entity.table, sent: records.length }
393
+ });
394
+ }
395
+ return rows;
396
+ },
337
397
  async update(entity, id, patch) {
338
398
  assertKnownFields(entity, patch);
339
399
  const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
@@ -486,6 +546,18 @@ function opsFromAccess(access = []) {
486
546
  for (const a of access) (ACCESS_TO_OPS[a] ?? []).forEach((o) => ops.add(o));
487
547
  return ops;
488
548
  }
549
+ function storedOnce(adapter, entity, id) {
550
+ let read;
551
+ return () => read ??= adapter.get(entity, id);
552
+ }
553
+ async function roundTrip(stored, entity, id, patch) {
554
+ try {
555
+ return await roundTripped(entity, id, patch, { stored });
556
+ } catch (err) {
557
+ if (err instanceof RecordGone) return null;
558
+ throw err;
559
+ }
560
+ }
489
561
  function entityClient(adapter, entity) {
490
562
  const ops = entity.ops instanceof Set ? entity.ops : new Set(entity.ops ?? ["list", "get", "create", "update", "delete"]);
491
563
  const guard = (op, fn, method = op) => ops.has(op) ? fn : (() => {
@@ -519,6 +591,15 @@ function entityClient(adapter, entity) {
519
591
  assertCreatable(data);
520
592
  return adapter.create(entity, data);
521
593
  }),
594
+ // A bulk create is its own call: checked whole before the one request
595
+ // (./patch.ts `bulkRecords`), never emulated as one create per record.
596
+ createMany: guard("create", async (rows) => {
597
+ const records = bulkRecords(entity, rows);
598
+ if (!adapter.createMany) {
599
+ throw new Error(`${entity.name}.createMany() is not supported by the '${adapter.kind}' adapter`);
600
+ }
601
+ return adapter.createMany(entity, records);
602
+ }, "createMany"),
522
603
  // A patch with no fields is a malformed request, not a write: PostgREST
523
604
  // performs no update and returns no row, which used to leave the App
524
605
  // serialising `undefined` and answering 500 (see ./patch.ts). Rejected here
@@ -532,7 +613,15 @@ function entityClient(adapter, entity) {
532
613
  assertOneRecord(entity, patch);
533
614
  assertUpdatable(patch);
534
615
  assertKnownFields(entity, patch);
535
- return adapter.update(entity, id, patch);
616
+ const stored = storedOnce(adapter, entity, id);
617
+ const write = await roundTrip(stored, entity, id, patch);
618
+ if (write === null) throw notFound();
619
+ if (updateFields(write).length === 0) {
620
+ const row = await stored();
621
+ if (!row) throw notFound();
622
+ return row;
623
+ }
624
+ return adapter.update(entity, id, write);
536
625
  }),
537
626
  // Validated in the same order and at the same layer as `update`, so every
538
627
  // adapter refuses a missing condition identically, before any request.
@@ -544,7 +633,13 @@ function entityClient(adapter, entity) {
544
633
  if (!adapter.updateIf) {
545
634
  throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);
546
635
  }
547
- return adapter.updateIf(entity, id, where, patch);
636
+ const write = await roundTrip(storedOnce(adapter, entity, id), entity, id, patch);
637
+ if (write === null) return null;
638
+ if (updateFields(write).length === 0) {
639
+ const [row] = await adapter.list(entity, { where: { ...where, [pkOf(entity)]: id }, limit: 1 });
640
+ return row ?? null;
641
+ }
642
+ return adapter.updateIf(entity, id, where, write);
548
643
  }, "updateIf"),
549
644
  delete: guard("delete", (id) => adapter.remove(entity, id))
550
645
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/mock.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 Where,\n} from '../types.js';\nimport { HttpError, notFound } from '../errors.js';\nimport { matches } from '../query.js';\nimport { IMPLICIT_COLUMNS as WRITABLE_IMPLICIT, assertCreatable, assertKnownFields, flagColumns } from '../patch.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/**\n * Columns every table has without declaring them in schema.json (Baseline adds\n * them), so the generated column metadata does not list them.\n */\nconst IMPLICIT_COLUMNS = new Set(WRITABLE_IMPLICIT);\n\n/**\n * A `where` on a column the entity does not have. PostgREST answers that with\n * `400` (SQLSTATE 42703), which the remote adapter maps to `bad_request`; the\n * mock used to filter every row out and answer `[]`, so a test passed against a\n * call that fails in production. Same status, code and message as the remote\n * adapter; the offending key travels on `serverDetail` (logged, not returned).\n * Skipped when the entity declares no columns — nothing to check against. The\n * columns the entity's `trash` / `external_id` flags add are columns here too.\n */\nfunction assertWhereColumns(entity: Entity, where: Query['where']): void {\n const columns = entity.columns;\n if (!columns || Object.keys(columns).length === 0 || !where) return;\n const flagged = new Set(flagColumns(entity));\n const unknown = Object.keys(where).filter(\n (k) => !Object.prototype.hasOwnProperty.call(columns, k) && !IMPLICIT_COLUMNS.has(k) && !flagged.has(k),\n );\n if (unknown.length === 0) return;\n throw new HttpError(400, 'the request could not be processed', undefined, {\n code: 'bad_request',\n serverDetail: { source: 'mock', entity: entity.name, unknownColumns: unknown },\n });\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 const write = (entity: Entity, id: string | number, cur: Row, patch: Row): Row => {\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\n return {\n kind: 'mock',\n async list(entity: Entity, query: Query = {}): Promise<Row[]> {\n assertWhereColumns(entity, query.where);\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 assertWhereColumns(entity, query.where);\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 // A key that is not a declared column is the same 400 `unknown_field` the\n // remote adapter raises, so a test cannot pass on a write production\n // refuses.\n async create(entity: Entity, data: Row): Promise<Row> {\n assertKnownFields(entity, data);\n // A row of defaults from nothing is what production refuses too.\n assertCreatable(data);\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 assertKnownFields(entity, patch);\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 return write(entity, id, cur, patch);\n },\n // The check and the write happen in one synchronous step, so no other call\n // can interleave between them — the in-memory analogue of Postgres\n // re-checking the WHERE on the locked row.\n // A condition on a column the entity does not have is PostgREST's 400, not\n // a lost race: answering `null` would read as \"somebody else moved it\".\n async updateIf(entity: Entity, id: string | number, where: Where, patch: Row): Promise<Row | null> {\n assertWhereColumns(entity, where);\n assertKnownFields(entity, patch);\n const cur = tbl(entity).get(id);\n if (!cur || !matches(cur, where)) return null;\n return write(entity, id, cur, patch);\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","/**\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, Where } from '../types.js';\nimport { toParams } from '../query.js';\nimport { HttpError, notFound } from '../errors.js';\nimport { postgrestError, rangeNotSatisfiable } from './postgrest-error.js';\nimport { assertCreatable, assertKnownFields } from '../patch.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 /**\n * The request's record-history envelope, forwarded as `X-Revenexx-Audit`.\n * Opaque to the App and the SDK: the gateway signs it, Baseline verifies it\n * and names the acting person in the record history. Sent unchanged when it\n * is one line of visible ASCII, dropped otherwise; a missing or bad envelope\n * never fails a call, the history then names the token's subject.\n */\n audit?: string;\n /**\n * What a change is and why, forwarded as `X-Revenexx-Audit-Note`: URI-encoded\n * JSON `{\"title\":\"…\",\"reason\":\"…\"}`. Baseline stores it with the record-history\n * entry of each write. Descriptive only — it never decides who is acting.\n * Sent unchanged when it is one line of printable ASCII of at most 8192 bytes\n * (Baseline's own cap), dropped otherwise; a missing or bad note never fails\n * a call.\n */\n auditNote?: 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 const audit = auditEnvelope(config.audit);\n const note = auditNote(config.auditNote);\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 if (audit) h['X-Revenexx-Audit'] = audit;\n if (note) h['X-Revenexx-Audit-Note'] = note;\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 // Every write is checked against the entity's declared columns here as\n // well as in the client, so the adapter used on its own refuses the same\n // keys (see ../patch.ts `unknownFields`).\n async create(entity: Entity, data: Row): Promise<Row> {\n assertKnownFields(entity, data);\n // `[]` would be a bulk insert of no rows (`500 empty_representation`).\n assertCreatable(data);\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 assertKnownFields(entity, patch);\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 updateIf(entity: Entity, id: string | number, where: Where, patch: Row): Promise<Row | null> {\n // One PATCH, the condition ANDed onto the pk filter: Postgres re-checks\n // the WHERE on the locked row, so of two racing writers exactly one\n // matches. No prior read — that would reopen the race.\n assertKnownFields(entity, patch);\n const cond = toParams({ where }).toString();\n const rows = await req('PATCH', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&${cond}`, {\n body: patch,\n prefer: 'return=representation',\n table: entity.table,\n });\n // `200 []` here is the answer, not a fault: no row matched.\n const row = Array.isArray(rows) ? (rows[0] as Row | undefined) : (rows as Row | null);\n return row ?? null;\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\n/**\n * The audit envelope as it may be forwarded: one line of visible ASCII\n * (`v1.<kid>.<payload>.<sig>` is base64url and dots), else nothing. Its content\n * is not read here; Baseline verifies it and ignores what does not verify.\n */\nexport function auditEnvelope(value: string | undefined | null): string {\n return typeof value === 'string' && /^[\\x21-\\x7e]{1,4096}$/.test(value) ? value : '';\n}\n\n/**\n * The record-history note as it may be forwarded: one line of printable ASCII\n * (a URI-encoded JSON object is exactly that) of at most 8192 bytes —\n * Baseline's cap on the header as received — else nothing. Its content is not read here; Baseline parses it and ignores what it\n * cannot read.\n */\nexport function auditNote(value: string | undefined | null): string {\n return typeof value === 'string' && /^[\\x20-\\x7e]{1,8192}$/.test(value) ? value : '';\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 * Overrides the request's `x-revenexx-audit-note` for the writes made through\n * this adapter — for a change the App itself describes. Omit it to pass the\n * request's note on; an empty string sends none.\n */\n auditNote?: string;\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`; market =\n * `x-revenexx-market`; the record-history envelope `x-revenexx-audit` and the\n * note `x-revenexx-audit-note` are passed on unchanged; 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 // The record-history envelope of THIS request, passed through unchanged.\n // Bound to the request's token and short-lived, so there is no env\n // fallback: an App without one is attributed to the token's subject.\n audit: get('x-revenexx-audit'),\n // What the change is and why (the Cockpit sends it on a rollback). Like the\n // envelope it belongs to THIS request, so there is no env fallback; unlike\n // it, it names nobody, so an App may describe its own change instead.\n auditNote: config.auditNote ?? get('x-revenexx-audit-note'),\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 Where,\n} from './types.js';\nimport { createAdapter } from './adapters/index.js';\nimport { ENTITY_DESCRIPTOR, assertCondition, assertCreatable, assertDefined, assertKnownFields, assertOneRecord, assertUpdatable } from './patch.js';\nimport { HttpError } from './errors.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 /**\n * Compare-and-set: update the row only if it still matches `where`, in one\n * write. Resolves to the updated row, or `null` when no row matched — the\n * row is gone, invisible, or the condition no longer holds (a lost race is\n * an outcome to branch on, not an error). Needs the `update` permission.\n */\n updateIf(id: string | number, where: Where<T>, patch: Partial<Create>): Promise<T | null>;\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 // `method` names what the App called when it differs from the op it needs\n // (`updateIf` is gated by `update`).\n const guard = <F extends (...args: never[]) => unknown>(op: Op, fn: F, method: string = op): F =>\n (ops.has(op)\n ? fn\n : (() => {\n // A 403 the router answers as one — not an Error whose wording it\n // has to recognise. Thrown synchronously, as before.\n throw new HttpError(\n 403,\n `${entity.name}.${method}() is not permitted — add the matching access to manifest.permissions for '${entity.name}'`,\n undefined,\n { code: 'not_permitted' },\n );\n }) as unknown as F);\n\n const client = {\n list: guard('list', async (query?: Query) => {\n assertDefined(query?.where);\n return adapter.list(entity, query ?? {});\n }),\n page: guard('list', async (query?: Query) => {\n assertDefined(query?.where);\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 // A key that is not a column this version declares is refused before the\n // request (see ./patch.ts `unknownFields`): the database cannot tell an\n // old version's stray key from a new version's column. `async` so the\n // refusal is a rejection like every other write failure; the permission\n // refusal above stays synchronous.\n create: guard('create', async (data: Row) => {\n assertKnownFields(entity, data);\n assertCreatable(data);\n return adapter.create(entity, data);\n }),\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 // A list is refused before it can read as an empty patch.\n assertOneRecord(entity, patch);\n assertUpdatable(patch);\n assertKnownFields(entity, patch);\n return adapter.update(entity, id, patch);\n }),\n // Validated in the same order and at the same layer as `update`, so every\n // adapter refuses a missing condition identically, before any request.\n updateIf: guard('update', async (id: string | number, where: Where, patch: Row) => {\n assertCondition(where);\n assertOneRecord(entity, patch);\n assertUpdatable(patch);\n assertKnownFields(entity, patch);\n if (!adapter.updateIf) {\n throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);\n }\n return adapter.updateIf(entity, id, where, patch);\n }, 'updateIf'),\n delete: guard('delete', (id: string | number) => adapter.remove(entity, id)),\n } as EntityClient;\n // Read by mountCrud (its flags, and so its trash guard). A symbol key: not in\n // Object.keys, for…in or JSON, so the client looks as before — but enumerable,\n // so `{ ...db.notes }` carries it along and a spread does not drop the guard.\n Object.defineProperty(client, ENTITY_DESCRIPTOR, { value: entity, enumerable: true });\n return client;\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;AAkB3B,SAAS,MAAM,MAAa,OAAqB;A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,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":["IMPLICIT_COLUMNS"]}
1
+ {"version":3,"sources":["../src/adapters/mock.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 Where,\n} from '../types.js';\nimport { HttpError, notFound } from '../errors.js';\nimport { matches } from '../query.js';\nimport { IMPLICIT_COLUMNS as WRITABLE_IMPLICIT, assertCreatable, assertKnownFields, bulkRecords, flagColumns } from '../patch.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/**\n * Columns every table has without declaring them in schema.json (Baseline adds\n * them), so the generated column metadata does not list them.\n */\nconst IMPLICIT_COLUMNS = new Set(WRITABLE_IMPLICIT);\n\n/**\n * A `where` on a column the entity does not have. PostgREST answers that with\n * `400` (SQLSTATE 42703), which the remote adapter maps to `bad_request`; the\n * mock used to filter every row out and answer `[]`, so a test passed against a\n * call that fails in production. Same status, code and message as the remote\n * adapter; the offending key travels on `serverDetail` (logged, not returned).\n * Skipped when the entity declares no columns — nothing to check against. The\n * columns the entity's `trash` / `external_id` flags add are columns here too.\n */\nfunction assertWhereColumns(entity: Entity, where: Query['where']): void {\n const columns = entity.columns;\n if (!columns || Object.keys(columns).length === 0 || !where) return;\n const flagged = new Set(flagColumns(entity));\n const unknown = Object.keys(where).filter(\n (k) => !Object.prototype.hasOwnProperty.call(columns, k) && !IMPLICIT_COLUMNS.has(k) && !flagged.has(k),\n );\n if (unknown.length === 0) return;\n throw new HttpError(400, 'the request could not be processed', undefined, {\n code: 'bad_request',\n serverDetail: { source: 'mock', entity: entity.name, unknownColumns: unknown },\n });\n}\n\n/**\n * Baseline grants no UPDATE on the primary key or on `tenant_id`, so PostgREST\n * answers a PATCH naming either — even with the value the row already holds —\n * with SQLSTATE 42501, which the remote adapter maps to `401` (`bad_request`,\n * `unauthenticated`). The mock wrote both. The data client drops a key or\n * tenant that repeats the record before any adapter sees it, so this is\n * reached only by a write that went past it — the backstop that keeps an App's\n * tests from passing on a write production refuses. Same status, code and\n * message as the remote adapter; the columns travel on `serverDetail`.\n */\nfunction assertUpdatableColumns(entity: Entity, patch: Row): void {\n if (!patch || typeof patch !== 'object') return;\n const refused = [...new Set([entity.pk || 'id', 'tenant_id'])].filter(\n (k) => Object.prototype.hasOwnProperty.call(patch, k) && patch[k] !== undefined,\n );\n if (refused.length === 0) return;\n throw new HttpError(401, 'unauthenticated', undefined, {\n code: 'bad_request',\n serverDetail: { source: 'mock', entity: entity.name, sqlstate: '42501', columns: refused.sort() },\n });\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 // Baseline's trigger stamps updated_at when the row changes; a write of the\n // values the row already holds stamps nothing — so a test sees a write that\n // changed nothing as one.\n const write = (entity: Entity, id: string | number, cur: Row, patch: Row): Row => {\n const row: Row = { ...cur, ...patch };\n const changed = Object.keys(patch).some((k) => patch[k] !== undefined && JSON.stringify(patch[k]) !== JSON.stringify(cur[k]));\n if (entity.columns?.updated_at && changed) row.updated_at = new Date().toISOString();\n tbl(entity).set(id, row);\n return { ...row };\n };\n\n return {\n kind: 'mock',\n async list(entity: Entity, query: Query = {}): Promise<Row[]> {\n assertWhereColumns(entity, query.where);\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 assertWhereColumns(entity, query.where);\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 // A key that is not a declared column is the same 400 `unknown_field` the\n // remote adapter raises, so a test cannot pass on a write production\n // refuses.\n async create(entity: Entity, data: Row): Promise<Row> {\n assertKnownFields(entity, data);\n // A row of defaults from nothing is what production refuses too.\n assertCreatable(data);\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 // One statement in Postgres: a primary key twice in the batch, or one the\n // table already holds, is the 409 the remote adapter maps from 23505, and\n // nothing is stored.\n async createMany(entity: Entity, data: Row[]): Promise<Row[]> {\n const rows = bulkRecords(entity, data).map((record) => {\n const row = applyDefaults(entity, record);\n if (row[entity.pk] === undefined) row[entity.pk] = randomUUID();\n return row;\n });\n const table = tbl(entity);\n const seen = new Set<unknown>();\n for (const row of rows) {\n const id = row[entity.pk];\n if (seen.has(id) || table.has(id as string | number)) {\n throw new HttpError(409, 'a record with this value already exists', undefined, {\n code: 'unique_violation',\n serverDetail: { source: 'mock', entity: entity.name, duplicate: id },\n });\n }\n seen.add(id);\n }\n for (const row of rows) table.set(row[entity.pk] as string | number, row);\n return rows.map((row) => ({ ...row }));\n },\n async update(entity: Entity, id: string | number, patch: Row): Promise<Row> {\n assertKnownFields(entity, patch);\n assertUpdatableColumns(entity, patch);\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 return write(entity, id, cur, patch);\n },\n // The check and the write happen in one synchronous step, so no other call\n // can interleave between them — the in-memory analogue of Postgres\n // re-checking the WHERE on the locked row.\n // A condition on a column the entity does not have is PostgREST's 400, not\n // a lost race: answering `null` would read as \"somebody else moved it\".\n async updateIf(entity: Entity, id: string | number, where: Where, patch: Row): Promise<Row | null> {\n assertWhereColumns(entity, where);\n assertKnownFields(entity, patch);\n assertUpdatableColumns(entity, patch);\n const cur = tbl(entity).get(id);\n if (!cur || !matches(cur, where)) return null;\n return write(entity, id, cur, patch);\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","/**\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, Where } from '../types.js';\nimport { toParams } from '../query.js';\nimport { HttpError, notFound } from '../errors.js';\nimport { postgrestError, rangeNotSatisfiable } from './postgrest-error.js';\nimport { assertCreatable, assertKnownFields, bulkRecords } from '../patch.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 /**\n * The request's record-history envelope, forwarded as `X-Revenexx-Audit`.\n * Opaque to the App and the SDK: the gateway signs it, Baseline verifies it\n * and names the acting person in the record history. Sent unchanged when it\n * is one line of visible ASCII, dropped otherwise; a missing or bad envelope\n * never fails a call, the history then names the token's subject.\n */\n audit?: string;\n /**\n * What a change is and why, forwarded as `X-Revenexx-Audit-Note`: URI-encoded\n * JSON `{\"title\":\"…\",\"reason\":\"…\"}`. Baseline stores it with the record-history\n * entry of each write. Descriptive only — it never decides who is acting.\n * Sent unchanged when it is one line of printable ASCII of at most 8192 bytes\n * (Baseline's own cap), dropped otherwise; a missing or bad note never fails\n * a call.\n */\n auditNote?: 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 const audit = auditEnvelope(config.audit);\n const note = auditNote(config.auditNote);\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 if (audit) h['X-Revenexx-Audit'] = audit;\n if (note) h['X-Revenexx-Audit-Note'] = note;\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 // Every write is checked against the entity's declared columns here as\n // well as in the client, so the adapter used on its own refuses the same\n // keys (see ../patch.ts `unknownFields`).\n async create(entity: Entity, data: Row): Promise<Row> {\n assertKnownFields(entity, data);\n // `[]` would be a bulk insert of no rows (`500 empty_representation`).\n assertCreatable(data);\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 // One POST of the whole list: PostgREST inserts it in one statement and\n // answers every row, in order. Checked here as well as in the client.\n async createMany(entity: Entity, data: Row[]): Promise<Row[]> {\n const records = bulkRecords(entity, data);\n const rows = await req('POST', `/${entity.table}`, {\n body: records,\n prefer: 'return=representation',\n table: entity.table,\n });\n // Fewer rows than records: some are not readable back (RLS) — a 5xx.\n if (!Array.isArray(rows) || rows.length < records.length) {\n throw new HttpError(500, 'the records were created but could not be read back', undefined, {\n code: 'empty_representation',\n serverDetail: { source: 'postgrest', method: 'POST', table: entity.table, sent: records.length },\n });\n }\n return rows as Row[];\n },\n async update(entity: Entity, id: string | number, patch: Row): Promise<Row> {\n assertKnownFields(entity, patch);\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 updateIf(entity: Entity, id: string | number, where: Where, patch: Row): Promise<Row | null> {\n // One PATCH, the condition ANDed onto the pk filter: Postgres re-checks\n // the WHERE on the locked row, so of two racing writers exactly one\n // matches. No prior read — that would reopen the race.\n assertKnownFields(entity, patch);\n const cond = toParams({ where }).toString();\n const rows = await req('PATCH', `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&${cond}`, {\n body: patch,\n prefer: 'return=representation',\n table: entity.table,\n });\n // `200 []` here is the answer, not a fault: no row matched.\n const row = Array.isArray(rows) ? (rows[0] as Row | undefined) : (rows as Row | null);\n return row ?? null;\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\n/**\n * The audit envelope as it may be forwarded: one line of visible ASCII\n * (`v1.<kid>.<payload>.<sig>` is base64url and dots), else nothing. Its content\n * is not read here; Baseline verifies it and ignores what does not verify.\n */\nexport function auditEnvelope(value: string | undefined | null): string {\n return typeof value === 'string' && /^[\\x21-\\x7e]{1,4096}$/.test(value) ? value : '';\n}\n\n/**\n * The record-history note as it may be forwarded: one line of printable ASCII\n * (a URI-encoded JSON object is exactly that) of at most 8192 bytes —\n * Baseline's cap on the header as received — else nothing. Its content is not read here; Baseline parses it and ignores what it\n * cannot read.\n */\nexport function auditNote(value: string | undefined | null): string {\n return typeof value === 'string' && /^[\\x20-\\x7e]{1,8192}$/.test(value) ? value : '';\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 * Overrides the request's `x-revenexx-audit-note` for the writes made through\n * this adapter — for a change the App itself describes. Omit it to pass the\n * request's note on; an empty string sends none.\n */\n auditNote?: string;\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`; market =\n * `x-revenexx-market`; the record-history envelope `x-revenexx-audit` and the\n * note `x-revenexx-audit-note` are passed on unchanged; 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 // The record-history envelope of THIS request, passed through unchanged.\n // Bound to the request's token and short-lived, so there is no env\n // fallback: an App without one is attributed to the token's subject.\n audit: get('x-revenexx-audit'),\n // What the change is and why (the Cockpit sends it on a rollback). Like the\n // envelope it belongs to THIS request, so there is no env fallback; unlike\n // it, it names nobody, so an App may describe its own change instead.\n auditNote: config.auditNote ?? get('x-revenexx-audit-note'),\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 Where,\n} from './types.js';\nimport { createAdapter } from './adapters/index.js';\nimport {\n ENTITY_DESCRIPTOR,\n bulkRecords,\n assertCondition,\n assertCreatable,\n assertDefined,\n assertKnownFields,\n assertOneRecord,\n assertUpdatable,\n RecordGone,\n pkOf,\n roundTripped,\n updateFields,\n} from './patch.js';\nimport { HttpError, notFound } from './errors.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 /**\n * Bulk create: a non-empty list of records, inserted in one request. Every\n * record is checked like a single create, and all of them name the same\n * fields; a refusal names the record in `details.index`. Answers the created\n * rows, in order. Needs the `create` permission. `create` itself takes one\n * record, so a handler that writes its request body never becomes a bulk\n * endpoint by accident.\n */\n createMany(rows: Create[]): Promise<T[]>;\n update(id: string | number, patch: Partial<Create>): Promise<T>;\n /**\n * Compare-and-set: update the row only if it still matches `where`, in one\n * write. Resolves to the updated row, or `null` when no row matched — the\n * row is gone, invisible, or the condition no longer holds (a lost race is\n * an outcome to branch on, not an error). Needs the `update` permission.\n */\n updateIf(id: string | number, where: Where<T>, patch: Partial<Create>): Promise<T | null>;\n delete(id: string | number): Promise<void>;\n}\n\n/** One read of a record, shared by every rule that needs it. */\nfunction storedOnce(adapter: Adapter, entity: Entity, id: string | number): () => Promise<Row | null> {\n let read: Promise<Row | null> | undefined;\n return () => (read ??= adapter.get(entity, id));\n}\n\n/**\n * The round-trip write of `patch` (./patch.ts `roundTripped`), or `null` when\n * the record it compares against is not there — `update` answers that 404,\n * `updateIf` null.\n */\nasync function roundTrip(\n stored: () => Promise<Row | null>,\n entity: Entity,\n id: string | number,\n patch: Row,\n): Promise<Row | null> {\n try {\n return await roundTripped(entity, id, patch, { stored });\n } catch (err) {\n if (err instanceof RecordGone) return null;\n throw err;\n }\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 // `method` names what the App called when it differs from the op it needs\n // (`updateIf` is gated by `update`).\n const guard = <F extends (...args: never[]) => unknown>(op: Op, fn: F, method: string = op): F =>\n (ops.has(op)\n ? fn\n : (() => {\n // A 403 the router answers as one — not an Error whose wording it\n // has to recognise. Thrown synchronously, as before.\n throw new HttpError(\n 403,\n `${entity.name}.${method}() is not permitted — add the matching access to manifest.permissions for '${entity.name}'`,\n undefined,\n { code: 'not_permitted' },\n );\n }) as unknown as F);\n\n const client = {\n list: guard('list', async (query?: Query) => {\n assertDefined(query?.where);\n return adapter.list(entity, query ?? {});\n }),\n page: guard('list', async (query?: Query) => {\n assertDefined(query?.where);\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 // A key that is not a column this version declares is refused before the\n // request (see ./patch.ts `unknownFields`): the database cannot tell an\n // old version's stray key from a new version's column. `async` so the\n // refusal is a rejection like every other write failure; the permission\n // refusal above stays synchronous.\n create: guard('create', async (data: Row) => {\n assertKnownFields(entity, data);\n assertCreatable(data);\n return adapter.create(entity, data);\n }),\n // A bulk create is its own call: checked whole before the one request\n // (./patch.ts `bulkRecords`), never emulated as one create per record.\n createMany: guard('create', async (rows: Row[]) => {\n const records = bulkRecords(entity, rows);\n if (!adapter.createMany) {\n throw new Error(`${entity.name}.createMany() is not supported by the '${adapter.kind}' adapter`);\n }\n return adapter.createMany(entity, records);\n }, 'createMany'),\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 // A list is refused before it can read as an empty patch.\n assertOneRecord(entity, patch);\n assertUpdatable(patch);\n assertKnownFields(entity, patch);\n // A record read and sent back names fields no write may set (./patch.ts\n // `roundTripped`): the ones that repeat the record are dropped, the ones\n // that contradict it refused. Nothing left is no write at all — the\n // record as it stands, no update event.\n const stored = storedOnce(adapter, entity, id);\n const write = await roundTrip(stored, entity, id, patch);\n if (write === null) throw notFound();\n if (updateFields(write).length === 0) {\n const row = await stored();\n if (!row) throw notFound();\n return row;\n }\n return adapter.update(entity, id, write);\n }),\n // Validated in the same order and at the same layer as `update`, so every\n // adapter refuses a missing condition identically, before any request.\n updateIf: guard('update', async (id: string | number, where: Where, patch: Row) => {\n assertCondition(where);\n assertOneRecord(entity, patch);\n assertUpdatable(patch);\n assertKnownFields(entity, patch);\n if (!adapter.updateIf) {\n throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);\n }\n const write = await roundTrip(storedOnce(adapter, entity, id), entity, id, patch);\n if (write === null) return null;\n // Nothing left to write: the row while the condition holds, else null —\n // one read, the condition ANDed onto the key as the write would have.\n if (updateFields(write).length === 0) {\n const [row] = await adapter.list(entity, { where: { ...where, [pkOf(entity)]: id } as Where, limit: 1 });\n return row ?? null;\n }\n return adapter.updateIf(entity, id, where, write);\n }, 'updateIf'),\n delete: guard('delete', (id: string | number) => adapter.remove(entity, id)),\n } as EntityClient;\n // Read by mountCrud (its flags, and so its trash guard). A symbol key: not in\n // Object.keys, for…in or JSON, so the client looks as before — but enumerable,\n // so `{ ...db.notes }` carries it along and a spread does not drop the guard.\n Object.defineProperty(client, ENTITY_DESCRIPTOR, { value: entity, enumerable: true });\n return client;\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;AAkB3B,SAAS,MAAM,MAAa,OAAqB;AAC/C,MAAI,MAAM;AACV,MAAI,MAAM,OAAO;AACf,UAAM,CAAC,GAAG,MAAM,KAAK,IAAI,MAAM,MAAM,MAAM,GAAG;AAC9C,UAAM,MAAM;AACZ,UAAM,IAAI,MAAM,EAAE,KAAK,CAAC,GAAG,MAAO,EAAE,GAAG,IAAK,EAAE,GAAG,IAAK,KAAK,EAAE,GAAG,IAAK,EAAE,GAAG,IAAK,IAAI,CAAE;AACrF,QAAI,QAAQ,OAAQ,KAAI,QAAQ;AAAA,EAClC;AACA,MAAI,MAAM,OAAQ,OAAM,IAAI,MAAM,MAAM,MAAM;AAC9C,MAAI,OAAO,UAAU,MAAM,KAAK,EAAG,OAAM,IAAI,MAAM,GAAG,MAAM,KAAK;AACjE,MAAI,MAAM,QAAQ,MAAM,MAAM,KAAK,MAAM,OAAO,QAAQ;AACtD,UAAM,OAAO,MAAM;AACnB,UAAM,IAAI,IAAI,CAAC,MAAM,OAAO,YAAY,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAAA,EACrE;AACA,SAAO,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE;AAClC;AAMA,IAAMA,oBAAmB,IAAI,IAAI,gBAAiB;AAWlD,SAAS,mBAAmB,QAAgB,OAA6B;AACvE,QAAM,UAAU,OAAO;AACvB,MAAI,CAAC,WAAW,OAAO,KAAK,OAAO,EAAE,WAAW,KAAK,CAAC,MAAO;AAC7D,QAAM,UAAU,IAAI,IAAI,YAAY,MAAM,CAAC;AAC3C,QAAM,UAA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