@revenexx/app-sdk 1.5.0 → 2.0.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.cjs CHANGED
@@ -113,11 +113,11 @@ function toParams(query = {}) {
113
113
  const { where = {}, select, order, limit, offset } = query;
114
114
  for (const [col, cond] of Object.entries(where)) {
115
115
  if (Array.isArray(cond)) {
116
- params.append(col, `in.(${cond.join(",")})`);
116
+ params.append(col, `in.${inList(cond)}`);
117
117
  } else if (cond && typeof cond === "object" && typeof cond.op === "string") {
118
118
  const c = cond;
119
119
  if (!OPS.has(c.op)) throw new Error(`query: unsupported operator '${c.op}'`);
120
- const v = Array.isArray(c.value) ? `(${c.value.join(",")})` : c.value;
120
+ const v = Array.isArray(c.value) ? inList(c.value) : c.value;
121
121
  params.append(col, `${c.op}.${v}`);
122
122
  } else if (cond === null) {
123
123
  params.append(col, "is.null");
@@ -131,6 +131,13 @@ function toParams(query = {}) {
131
131
  if (Number.isInteger(offset)) params.set("offset", String(offset));
132
132
  return params;
133
133
  }
134
+ function inList(values) {
135
+ return `(${values.map(quoteListValue).join(",")})`;
136
+ }
137
+ function quoteListValue(v) {
138
+ if (v === null || v === void 0) return "null";
139
+ return `"${String(v).replace(/[\\"]/g, "\\$&")}"`;
140
+ }
134
141
  function matches(row, where = {}) {
135
142
  for (const [col, cond] of Object.entries(where)) {
136
143
  const val = row[col] ?? null;
@@ -176,6 +183,91 @@ function compare(a, op, b) {
176
183
  }
177
184
  }
178
185
 
186
+ // src/patch.ts
187
+ var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
188
+ function updateFields(patch) {
189
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return [];
190
+ return Object.keys(patch).filter(
191
+ (key) => patch[key] !== void 0
192
+ );
193
+ }
194
+ var EMPTY_CREATE_MESSAGE = "request body must contain at least one field to create";
195
+ function assertCreatable(data) {
196
+ if (updateFields(data).length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, void 0, { code: "empty_create" });
197
+ }
198
+ function assertUpdatable(patch) {
199
+ if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE, void 0, { code: "empty_update" });
200
+ }
201
+ var EMPTY_CONDITION_MESSAGE = "a conditional update needs at least one condition in where";
202
+ function assertCondition(where) {
203
+ if (!where || typeof where !== "object" || Array.isArray(where) || Object.keys(where).length === 0) {
204
+ throw badRequest(EMPTY_CONDITION_MESSAGE, void 0, { code: "empty_condition" });
205
+ }
206
+ assertDefined(where);
207
+ }
208
+ function assertDefined(where) {
209
+ if (!where || typeof where !== "object") return;
210
+ for (const [col, cond] of Object.entries(where)) {
211
+ if (cond === void 0) {
212
+ throw badRequest(`where.${col} is undefined \u2014 a condition needs a value`, void 0, { code: "undefined_condition" });
213
+ }
214
+ }
215
+ }
216
+ var IMPLICIT_COLUMNS = ["tenant_id"];
217
+ var TRASH_FLAG_COLUMNS = [
218
+ "deleted_at",
219
+ "deleted_by",
220
+ "deleted_by_id",
221
+ "trash_batch",
222
+ "purge_blocked_reason"
223
+ ];
224
+ var EXTERNAL_ID_FLAG_COLUMNS = ["external_id"];
225
+ function flagColumns(entity) {
226
+ return [
227
+ ...entity.trash === true ? TRASH_FLAG_COLUMNS : [],
228
+ ...entity.external_id === true ? EXTERNAL_ID_FLAG_COLUMNS : []
229
+ ];
230
+ }
231
+ function writableColumns(entity) {
232
+ return [.../* @__PURE__ */ new Set([...Object.keys(entity.columns ?? {}), ...flagColumns(entity)])].sort();
233
+ }
234
+ function unknownFields(entity, data) {
235
+ if (!checksFields(entity)) return [];
236
+ if (!data || typeof data !== "object" || Array.isArray(data)) return [];
237
+ const row = data;
238
+ const writable = /* @__PURE__ */ new Set([...writableColumns(entity), ...IMPLICIT_COLUMNS]);
239
+ return Object.keys(row).filter((key) => row[key] !== void 0 && !writable.has(key)).sort();
240
+ }
241
+ function checksFields(entity) {
242
+ return !!entity.columns && Object.keys(entity.columns).length > 0;
243
+ }
244
+ var ONE_RECORD_MESSAGE = "a write takes one record, as a JSON object \u2014 not a list";
245
+ function assertOneRecord(entity, data) {
246
+ if (checksFields(entity) && isList(data)) throw oneRecordRefusal();
247
+ }
248
+ var INDEX = /^(?:0|[1-9]\d*)$/;
249
+ function isList(data) {
250
+ if (!data || typeof data !== "object") return false;
251
+ if (Array.isArray(data)) return data.length > 0;
252
+ const keys = Object.keys(data);
253
+ return keys.length > 0 && keys.every((k) => INDEX.test(k) && Number(k) < keys.length);
254
+ }
255
+ var ENTITY_DESCRIPTOR = /* @__PURE__ */ Symbol.for("revenexx.app-sdk.entity");
256
+ function oneRecordRefusal() {
257
+ return badRequest(ONE_RECORD_MESSAGE, void 0, { code: "bad_request" });
258
+ }
259
+ function assertKnownFields(entity, data) {
260
+ assertOneRecord(entity, data);
261
+ const unknown = unknownFields(entity, data);
262
+ if (unknown.length === 0) return;
263
+ const quoted = unknown.map((k) => `'${k}'`).join(", ");
264
+ throw badRequest(
265
+ `unknown field${unknown.length > 1 ? "s" : ""} ${quoted} \u2014 not a column of '${entity.name}'. A field that cannot be written is refused rather than dropped; see details.allowed.`,
266
+ { unknown, allowed: writableColumns(entity) },
267
+ { code: "unknown_field" }
268
+ );
269
+ }
270
+
179
271
  // src/adapters/mock.ts
180
272
  function shape(rows, query) {
181
273
  let out = rows;
@@ -193,12 +285,13 @@ function shape(rows, query) {
193
285
  }
194
286
  return out.map((r) => ({ ...r }));
195
287
  }
196
- var IMPLICIT_COLUMNS = /* @__PURE__ */ new Set(["tenant_id"]);
288
+ var IMPLICIT_COLUMNS2 = new Set(IMPLICIT_COLUMNS);
197
289
  function assertWhereColumns(entity, where) {
198
290
  const columns = entity.columns;
199
291
  if (!columns || Object.keys(columns).length === 0 || !where) return;
292
+ const flagged = new Set(flagColumns(entity));
200
293
  const unknown = Object.keys(where).filter(
201
- (k) => !Object.prototype.hasOwnProperty.call(columns, k) && !IMPLICIT_COLUMNS.has(k)
294
+ (k) => !Object.prototype.hasOwnProperty.call(columns, k) && !IMPLICIT_COLUMNS2.has(k) && !flagged.has(k)
202
295
  );
203
296
  if (unknown.length === 0) return;
204
297
  throw new HttpError(400, "the request could not be processed", void 0, {
@@ -255,13 +348,19 @@ function createMockAdapter(seed = {}) {
255
348
  const r = tbl(entity).get(id);
256
349
  return r ? { ...r } : null;
257
350
  },
351
+ // A key that is not a declared column is the same 400 `unknown_field` the
352
+ // remote adapter raises, so a test cannot pass on a write production
353
+ // refuses.
258
354
  async create(entity, data) {
355
+ assertKnownFields(entity, data);
356
+ assertCreatable(data);
259
357
  const row = applyDefaults(entity, data);
260
358
  if (row[entity.pk] === void 0) row[entity.pk] = (0, import_node_crypto.randomUUID)();
261
359
  tbl(entity).set(row[entity.pk], row);
262
360
  return { ...row };
263
361
  },
264
362
  async update(entity, id, patch) {
363
+ assertKnownFields(entity, patch);
265
364
  const cur = tbl(entity).get(id);
266
365
  if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
267
366
  return write(entity, id, cur, patch);
@@ -273,6 +372,7 @@ function createMockAdapter(seed = {}) {
273
372
  // a lost race: answering `null` would read as "somebody else moved it".
274
373
  async updateIf(entity, id, where, patch) {
275
374
  assertWhereColumns(entity, where);
375
+ assertKnownFields(entity, patch);
276
376
  const cur = tbl(entity).get(id);
277
377
  if (!cur || !matches(cur, where)) return null;
278
378
  return write(entity, id, cur, patch);
@@ -454,7 +554,12 @@ function createRemoteAdapter(config) {
454
554
  });
455
555
  return rows?.[0] ?? null;
456
556
  },
557
+ // Every write is checked against the entity's declared columns here as
558
+ // well as in the client, so the adapter used on its own refuses the same
559
+ // keys (see ../patch.ts `unknownFields`).
457
560
  async create(entity, data) {
561
+ assertKnownFields(entity, data);
562
+ assertCreatable(data);
458
563
  const rows = await req("POST", `/${entity.table}`, {
459
564
  body: data,
460
565
  prefer: "return=representation",
@@ -469,6 +574,7 @@ function createRemoteAdapter(config) {
469
574
  );
470
575
  },
471
576
  async update(entity, id, patch) {
577
+ assertKnownFields(entity, patch);
472
578
  const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
473
579
  body: patch,
474
580
  prefer: "return=representation",
@@ -477,6 +583,7 @@ function createRemoteAdapter(config) {
477
583
  return oneRow(rows, () => notFound());
478
584
  },
479
585
  async updateIf(entity, id, where, patch) {
586
+ assertKnownFields(entity, patch);
480
587
  const cond = toParams({ where }).toString();
481
588
  const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&${cond}`, {
482
589
  body: patch,
@@ -606,33 +713,6 @@ registerAdapter("mock", (c) => createMockAdapter(c.seed));
606
713
  registerAdapter("remote", (c) => createRemoteAdapter(c));
607
714
  registerAdapter("runtime", (c) => createRuntimeAdapter(c));
608
715
 
609
- // src/patch.ts
610
- var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
611
- function updateFields(patch) {
612
- if (!patch || typeof patch !== "object" || Array.isArray(patch)) return [];
613
- return Object.keys(patch).filter(
614
- (key) => patch[key] !== void 0
615
- );
616
- }
617
- function assertUpdatable(patch) {
618
- if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE, void 0, { code: "empty_update" });
619
- }
620
- var EMPTY_CONDITION_MESSAGE = "a conditional update needs at least one condition in where";
621
- function assertCondition(where) {
622
- if (!where || typeof where !== "object" || Array.isArray(where) || Object.keys(where).length === 0) {
623
- throw badRequest(EMPTY_CONDITION_MESSAGE, void 0, { code: "empty_condition" });
624
- }
625
- assertDefined(where);
626
- }
627
- function assertDefined(where) {
628
- if (!where || typeof where !== "object") return;
629
- for (const [col, cond] of Object.entries(where)) {
630
- if (cond === void 0) {
631
- throw badRequest(`where.${col} is undefined \u2014 a condition needs a value`, void 0, { code: "undefined_condition" });
632
- }
633
- }
634
- }
635
-
636
716
  // src/client.ts
637
717
  var ACCESS_TO_OPS = {
638
718
  read: ["list", "get"],
@@ -655,7 +735,7 @@ function entityClient(adapter, entity) {
655
735
  { code: "not_permitted" }
656
736
  );
657
737
  });
658
- return {
738
+ const client = {
659
739
  list: guard("list", async (query) => {
660
740
  assertDefined(query?.where);
661
741
  return adapter.list(entity, query ?? {});
@@ -668,7 +748,16 @@ function entityClient(adapter, entity) {
668
748
  return adapter.page(entity, query ?? {});
669
749
  }),
670
750
  get: guard("get", (id) => adapter.get(entity, id)),
671
- create: guard("create", (data) => adapter.create(entity, data)),
751
+ // A key that is not a column this version declares is refused before the
752
+ // request (see ./patch.ts `unknownFields`): the database cannot tell an
753
+ // old version's stray key from a new version's column. `async` so the
754
+ // refusal is a rejection like every other write failure; the permission
755
+ // refusal above stays synchronous.
756
+ create: guard("create", async (data) => {
757
+ assertKnownFields(entity, data);
758
+ assertCreatable(data);
759
+ return adapter.create(entity, data);
760
+ }),
672
761
  // A patch with no fields is a malformed request, not a write: PostgREST
673
762
  // performs no update and returns no row, which used to leave the App
674
763
  // serialising `undefined` and answering 500 (see ./patch.ts). Rejected here
@@ -679,14 +768,18 @@ function entityClient(adapter, entity) {
679
768
  // patch is handled like any other data-plane failure (`await` / `.catch()`)
680
769
  // and the declared `Promise<T>` stays honest.
681
770
  update: guard("update", async (id, patch) => {
771
+ assertOneRecord(entity, patch);
682
772
  assertUpdatable(patch);
773
+ assertKnownFields(entity, patch);
683
774
  return adapter.update(entity, id, patch);
684
775
  }),
685
776
  // Validated in the same order and at the same layer as `update`, so every
686
777
  // adapter refuses a missing condition identically, before any request.
687
778
  updateIf: guard("update", async (id, where, patch) => {
688
779
  assertCondition(where);
780
+ assertOneRecord(entity, patch);
689
781
  assertUpdatable(patch);
782
+ assertKnownFields(entity, patch);
690
783
  if (!adapter.updateIf) {
691
784
  throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);
692
785
  }
@@ -694,6 +787,8 @@ function entityClient(adapter, entity) {
694
787
  }, "updateIf"),
695
788
  delete: guard("delete", (id) => adapter.remove(entity, id))
696
789
  };
790
+ Object.defineProperty(client, ENTITY_DESCRIPTOR, { value: entity, enumerable: true });
791
+ return client;
697
792
  }
698
793
  function eventsClient(adapter, config) {
699
794
  const names = () => Object.keys(config.declared).sort().join(", ") || "(none)";
@@ -1001,7 +1096,7 @@ function backdatingDb(db, entities) {
1001
1096
  const member = Reflect.get(r, key, rr);
1002
1097
  if (key !== "create" || typeof member !== "function") return member;
1003
1098
  return (data, ...rest) => {
1004
- if (!backdated() || !data || typeof data !== "object" || Array.isArray(data)) {
1099
+ if (!backdated() || !data || typeof data !== "object" || Array.isArray(data) || isList(data)) {
1005
1100
  return member.call(r, data, ...rest);
1006
1101
  }
1007
1102
  const at = now();