@revenexx/app-sdk 0.9.0 → 1.1.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.
@@ -15,8 +15,10 @@ type Filter = Scalar | Scalar[] | {
15
15
  * serialise it to a PostgREST querystring, mock applies it in memory — so App
16
16
  * code is identical regardless of where the data lives.
17
17
  */
18
+ /** A `where` clause: every entry must hold (AND). */
19
+ type Where<T = Record<string, unknown>> = Partial<Record<keyof T & string, Filter>> & Record<string, Filter>;
18
20
  interface Query<T = Record<string, unknown>> {
19
- where?: Partial<Record<keyof T & string, Filter>> & Record<string, Filter>;
21
+ where?: Where<T>;
20
22
  select?: (keyof T & string)[] | string[];
21
23
  order?: string;
22
24
  limit?: number;
@@ -107,6 +109,11 @@ interface EmittedEvent {
107
109
  * `page` is optional: adapters that can report a total (PostgREST `count=exact`,
108
110
  * an in-memory store) implement it; others fall back to `list` only.
109
111
  *
112
+ * `updateIf` is optional too, and for a stricter reason: a compare-and-set
113
+ * has to be one atomic write, so the client cannot emulate it as a read
114
+ * followed by an update — that is exactly the race it exists to close. An
115
+ * adapter without it makes `updateIf()` fail rather than degrade.
116
+ *
110
117
  * `emit` and `emitted` are optional for the same reason — an adapter that
111
118
  * cannot reach the event bus simply does not implement them, and the entity
112
119
  * client says so rather than pretending the event went out.
@@ -118,6 +125,11 @@ interface Adapter {
118
125
  create(entity: Entity, data: Row): Promise<Row>;
119
126
  update(entity: Entity, id: string | number, patch: Row): Promise<Row>;
120
127
  remove(entity: Entity, id: string | number): Promise<void>;
128
+ /**
129
+ * Update the row only if it still matches `where`; `null` when no row
130
+ * matched — gone, invisible, or the condition no longer holds.
131
+ */
132
+ updateIf?(entity: Entity, id: string | number, where: Where, patch: Row): Promise<Row | null>;
121
133
  page?(entity: Entity, query?: Query): Promise<Page>;
122
134
  emit?(target: EmitTarget, data: Row, options: EmitOptions): Promise<EmitResult>;
123
135
  /** What this adapter recorded instead of publishing (mock only). */
@@ -329,9 +341,30 @@ declare class HttpError extends Error {
329
341
  }
330
342
  /** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */
331
343
  declare function isHttpError(err: unknown): err is HttpError;
332
- declare const notFound: (message?: string) => HttpError;
333
- declare const badRequest: (message?: string, details?: unknown) => HttpError;
334
- declare const forbidden: (message?: string) => HttpError;
335
- declare const conflict: (message?: string) => HttpError;
344
+ declare const notFound: (message?: string, options?: HttpErrorOptions) => HttpError;
345
+ declare const badRequest: (message?: string, details?: unknown, options?: HttpErrorOptions) => HttpError;
346
+ declare const forbidden: (message?: string, options?: HttpErrorOptions) => HttpError;
347
+ declare const conflict: (message?: string, options?: HttpErrorOptions) => HttpError;
348
+ /** A refusal, whichever side raised it. */
349
+ interface Refusal {
350
+ /** HTTP status the refusal was answered with. */
351
+ status: number;
352
+ /** The refusing App's stable code, or null when it gave none. */
353
+ code: string | null;
354
+ /** Why, in words safe to show. */
355
+ message: string;
356
+ details: unknown;
357
+ /** The App that answered, as the gateway tagged it; null for this App's own refusal. */
358
+ app: string | null;
359
+ }
360
+ /**
361
+ * Read a refusal out of whatever was thrown: this App's own `HttpError`, or the
362
+ * exception the platform client (`@revenexx/sdk`) throws when another App refused a
363
+ * call — whose `code` is the HTTP status and whose `response` is that App's body
364
+ * verbatim. `null` for anything that is not a refusal (a crash, a network fault),
365
+ * which is the distinction a caller needs: a question that could not be answered is
366
+ * not the far side being down.
367
+ */
368
+ declare function refusalOf(err: unknown): Refusal | null;
336
369
 
337
- export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type ResolvedSettings as l, type SettingsDefaults as m, type SettingsOptions as n, type SettingsReader as o, type SettingsSnapshot as p, type SettingsSource as q, createSettings as r, isHttpError as s, badRequest as t, conflict as u, forbidden as v, notFound as w };
370
+ export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type Where as W, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type Refusal as l, type ResolvedSettings as m, type SettingsDefaults as n, type SettingsOptions as o, type SettingsReader as p, type SettingsSnapshot as q, type SettingsSource as r, createSettings as s, isHttpError as t, refusalOf as u, badRequest as v, conflict as w, forbidden as x, notFound as y };
package/dist/index.cjs CHANGED
@@ -37,6 +37,7 @@ __export(src_exports, {
37
37
  isHttpError: () => isHttpError,
38
38
  matches: () => matches,
39
39
  opsFromAccess: () => opsFromAccess,
40
+ refusalOf: () => refusalOf,
40
41
  registerAdapter: () => registerAdapter,
41
42
  toParams: () => toParams
42
43
  });
@@ -72,8 +73,31 @@ function isHttpError(err) {
72
73
  const e = err;
73
74
  return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
74
75
  }
75
- var notFound = (message = "not found") => new HttpError(404, message);
76
- var badRequest = (message = "bad request", details) => new HttpError(400, message, details);
76
+ var notFound = (message = "not found", options = {}) => new HttpError(404, message, void 0, { code: "not_found", ...options });
77
+ var badRequest = (message = "bad request", details, options = {}) => new HttpError(400, message, details, { code: "bad_request", ...options });
78
+ function refusalOf(err) {
79
+ if (isHttpError(err)) {
80
+ return { status: err.status, code: err.code ?? null, message: err.message, details: err.details ?? null, app: null };
81
+ }
82
+ if (!err || typeof err !== "object") return null;
83
+ const e = err;
84
+ const status = typeof e.code === "number" ? e.code : Number.NaN;
85
+ if (!(status >= 400 && status <= 599) || typeof e.response !== "string") return null;
86
+ let body = {};
87
+ try {
88
+ const parsed = JSON.parse(e.response || "{}");
89
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) body = parsed;
90
+ } catch {
91
+ }
92
+ const str = (v) => typeof v === "string" && v !== "" ? v : null;
93
+ return {
94
+ status,
95
+ code: str(body.code) ?? str(body.type) ?? str(e.type),
96
+ message: str(body.error) ?? str(body.message) ?? str(e.message) ?? "the call was refused",
97
+ details: body.details ?? null,
98
+ app: str(e.app)
99
+ };
100
+ }
77
101
 
78
102
  // src/query.ts
79
103
  var OPS = /* @__PURE__ */ new Set(["eq", "neq", "gt", "gte", "lt", "lte", "like", "ilike", "in", "is"]);
@@ -88,6 +112,8 @@ function toParams(query = {}) {
88
112
  if (!OPS.has(c.op)) throw new Error(`query: unsupported operator '${c.op}'`);
89
113
  const v = Array.isArray(c.value) ? `(${c.value.join(",")})` : c.value;
90
114
  params.append(col, `${c.op}.${v}`);
115
+ } else if (cond === null) {
116
+ params.append(col, "is.null");
91
117
  } else {
92
118
  params.append(col, `eq.${cond}`);
93
119
  }
@@ -100,7 +126,7 @@ function toParams(query = {}) {
100
126
  }
101
127
  function matches(row, where = {}) {
102
128
  for (const [col, cond] of Object.entries(where)) {
103
- const val = row[col];
129
+ const val = row[col] ?? null;
104
130
  if (Array.isArray(cond)) {
105
131
  if (!cond.includes(val)) return false;
106
132
  } else if (cond && typeof cond === "object" && typeof cond.op === "string") {
@@ -160,6 +186,19 @@ function shape(rows, query) {
160
186
  }
161
187
  return out.map((r) => ({ ...r }));
162
188
  }
189
+ var IMPLICIT_COLUMNS = /* @__PURE__ */ new Set(["tenant_id"]);
190
+ function assertWhereColumns(entity, where) {
191
+ const columns = entity.columns;
192
+ if (!columns || Object.keys(columns).length === 0 || !where) return;
193
+ const unknown = Object.keys(where).filter(
194
+ (k) => !Object.prototype.hasOwnProperty.call(columns, k) && !IMPLICIT_COLUMNS.has(k)
195
+ );
196
+ if (unknown.length === 0) return;
197
+ throw new HttpError(400, "the request could not be processed", void 0, {
198
+ code: "bad_request",
199
+ serverDetail: { source: "mock", entity: entity.name, unknownColumns: unknown }
200
+ });
201
+ }
163
202
  function applyDefaults(entity, data) {
164
203
  const row = { ...data };
165
204
  for (const [col, def] of Object.entries(entity.columns ?? {})) {
@@ -187,13 +226,21 @@ function createMockAdapter(seed = {}) {
187
226
  }
188
227
  return m;
189
228
  };
229
+ const write = (entity, id, cur, patch) => {
230
+ const row = { ...cur, ...patch };
231
+ if (entity.columns?.updated_at) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
232
+ tbl(entity).set(id, row);
233
+ return { ...row };
234
+ };
190
235
  return {
191
236
  kind: "mock",
192
237
  async list(entity, query = {}) {
238
+ assertWhereColumns(entity, query.where);
193
239
  const filtered = [...tbl(entity).values()].filter((r) => matches(r, query.where));
194
240
  return shape(filtered, query);
195
241
  },
196
242
  async page(entity, query = {}) {
243
+ assertWhereColumns(entity, query.where);
197
244
  const filtered = [...tbl(entity).values()].filter((r) => matches(r, query.where));
198
245
  return { items: shape(filtered, query), total: filtered.length, limit: query.limit, offset: query.offset };
199
246
  },
@@ -210,10 +257,18 @@ function createMockAdapter(seed = {}) {
210
257
  async update(entity, id, patch) {
211
258
  const cur = tbl(entity).get(id);
212
259
  if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
213
- const row = { ...cur, ...patch };
214
- if (entity.columns?.updated_at) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
215
- tbl(entity).set(id, row);
216
- return { ...row };
260
+ return write(entity, id, cur, patch);
261
+ },
262
+ // The check and the write happen in one synchronous step, so no other call
263
+ // can interleave between them — the in-memory analogue of Postgres
264
+ // re-checking the WHERE on the locked row.
265
+ // A condition on a column the entity does not have is PostgREST's 400, not
266
+ // a lost race: answering `null` would read as "somebody else moved it".
267
+ async updateIf(entity, id, where, patch) {
268
+ assertWhereColumns(entity, where);
269
+ const cur = tbl(entity).get(id);
270
+ if (!cur || !matches(cur, where)) return null;
271
+ return write(entity, id, cur, patch);
217
272
  },
218
273
  async remove(entity, id) {
219
274
  tbl(entity).delete(id);
@@ -410,6 +465,16 @@ function createRemoteAdapter(config) {
410
465
  });
411
466
  return oneRow(rows, () => notFound());
412
467
  },
468
+ async updateIf(entity, id, where, patch) {
469
+ const cond = toParams({ where }).toString();
470
+ const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&${cond}`, {
471
+ body: patch,
472
+ prefer: "return=representation",
473
+ table: entity.table
474
+ });
475
+ const row = Array.isArray(rows) ? rows[0] : rows;
476
+ return row ?? null;
477
+ },
413
478
  async remove(entity, id) {
414
479
  await req("DELETE", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
415
480
  table: entity.table
@@ -525,7 +590,22 @@ function updateFields(patch) {
525
590
  );
526
591
  }
527
592
  function assertUpdatable(patch) {
528
- if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE);
593
+ if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE, void 0, { code: "empty_update" });
594
+ }
595
+ var EMPTY_CONDITION_MESSAGE = "a conditional update needs at least one condition in where";
596
+ function assertCondition(where) {
597
+ if (!where || typeof where !== "object" || Array.isArray(where) || Object.keys(where).length === 0) {
598
+ throw badRequest(EMPTY_CONDITION_MESSAGE, void 0, { code: "empty_condition" });
599
+ }
600
+ assertDefined(where);
601
+ }
602
+ function assertDefined(where) {
603
+ if (!where || typeof where !== "object") return;
604
+ for (const [col, cond] of Object.entries(where)) {
605
+ if (cond === void 0) {
606
+ throw badRequest(`where.${col} is undefined \u2014 a condition needs a value`, void 0, { code: "undefined_condition" });
607
+ }
608
+ }
529
609
  }
530
610
 
531
611
  // src/client.ts
@@ -542,14 +622,21 @@ function opsFromAccess(access = []) {
542
622
  }
543
623
  function entityClient(adapter, entity) {
544
624
  const ops = entity.ops instanceof Set ? entity.ops : new Set(entity.ops ?? ["list", "get", "create", "update", "delete"]);
545
- const guard = (op, fn) => ops.has(op) ? fn : (() => {
546
- throw new Error(
547
- `${entity.name}.${op}() is not permitted \u2014 add the matching access to manifest.permissions for '${entity.name}'`
625
+ const guard = (op, fn, method = op) => ops.has(op) ? fn : (() => {
626
+ throw new HttpError(
627
+ 403,
628
+ `${entity.name}.${method}() is not permitted \u2014 add the matching access to manifest.permissions for '${entity.name}'`,
629
+ void 0,
630
+ { code: "not_permitted" }
548
631
  );
549
632
  });
550
633
  return {
551
- list: guard("list", (query) => adapter.list(entity, query ?? {})),
552
- page: guard("list", (query) => {
634
+ list: guard("list", async (query) => {
635
+ assertDefined(query?.where);
636
+ return adapter.list(entity, query ?? {});
637
+ }),
638
+ page: guard("list", async (query) => {
639
+ assertDefined(query?.where);
553
640
  if (!adapter.page) {
554
641
  throw new Error(`${entity.name}.page() is not supported by the '${adapter.kind}' adapter`);
555
642
  }
@@ -570,6 +657,16 @@ function entityClient(adapter, entity) {
570
657
  assertUpdatable(patch);
571
658
  return adapter.update(entity, id, patch);
572
659
  }),
660
+ // Validated in the same order and at the same layer as `update`, so every
661
+ // adapter refuses a missing condition identically, before any request.
662
+ updateIf: guard("update", async (id, where, patch) => {
663
+ assertCondition(where);
664
+ assertUpdatable(patch);
665
+ if (!adapter.updateIf) {
666
+ throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);
667
+ }
668
+ return adapter.updateIf(entity, id, where, patch);
669
+ }, "updateIf"),
573
670
  delete: guard("delete", (id) => adapter.remove(entity, id))
574
671
  };
575
672
  }
@@ -767,6 +864,7 @@ function createSettings(options = {}) {
767
864
  isHttpError,
768
865
  matches,
769
866
  opsFromAccess,
867
+ refusalOf,
770
868
  registerAdapter,
771
869
  toParams
772
870
  });