@revenexx/app-sdk 2.1.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.cjs CHANGED
@@ -302,6 +302,127 @@ function assertKnownFields(entity, data) {
302
302
  { code: "unknown_field" }
303
303
  );
304
304
  }
305
+ var STORE_OWNED_FIELD = "store_owned_field";
306
+ var READ_ONLY_FIELD = "read_only_field";
307
+ var STORE_STAMPED_COLUMNS = ["updated_at"];
308
+ var CREATION_STAMP_COLUMNS = ["created_at"];
309
+ var TRASH_ROUND_TRIP_COLUMNS = [...TRASH_FLAG_COLUMNS, "purge_at"];
310
+ var RecordGone = class extends Error {
311
+ constructor() {
312
+ super("the record is not there");
313
+ this.name = "RecordGone";
314
+ }
315
+ };
316
+ var noValue = (v) => v === null || v === void 0 || v === "";
317
+ var has = (row, key) => Object.prototype.hasOwnProperty.call(row, key) && row[key] !== void 0;
318
+ var nullish = (v) => v === null || v === void 0;
319
+ var DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?$/;
320
+ var NUMERIC_TYPE = /^(?:(?:small|big)?int(?:eger)?|int[248]|(?:big|small)?serial|serial[248]|numeric|decimal|real|double|float[48]?)\b/i;
321
+ var INSTANT = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
322
+ function sameInstant(a, b) {
323
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
324
+ if (String(a) === String(b)) return true;
325
+ if (typeof a !== "string" || typeof b !== "string" || !INSTANT.test(a) || !INSTANT.test(b)) return false;
326
+ const x = Date.parse(a);
327
+ const y = Date.parse(b);
328
+ return Number.isFinite(x) && Number.isFinite(y) && x === y;
329
+ }
330
+ function decimal(v) {
331
+ const text = typeof v === "number" ? Number.isFinite(v) ? String(v) : "" : typeof v === "string" ? v.trim() : "";
332
+ const m = DECIMAL.exec(text);
333
+ if (!m || m[2] === "" && (m[3] ?? "") === "") return null;
334
+ const whole = m[2].replace(/^0+(?=\d)/, "") || "0";
335
+ const fraction = (m[3] ?? "").replace(/0+$/, "");
336
+ const digits = fraction ? `${whole}.${fraction}` : whole;
337
+ return digits === "0" ? "0" : `${m[1] === "-" ? "-" : ""}${digits}`;
338
+ }
339
+ function isNumericType(type) {
340
+ return NUMERIC_TYPE.test(String(type ?? "").trim());
341
+ }
342
+ function sameValue(a, b, type) {
343
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
344
+ if (typeof a === "object" || typeof b === "object") return canonical(a) === canonical(b);
345
+ if (String(a) === String(b)) return true;
346
+ if (isNumericType(type)) {
347
+ const x = decimal(a);
348
+ const y = decimal(b);
349
+ if (x !== null && y !== null) return x === y;
350
+ const fx = Number(a);
351
+ const fy = Number(b);
352
+ return Number.isFinite(fx) && Number.isFinite(fy) && fx === fy;
353
+ }
354
+ return sameInstant(a, b);
355
+ }
356
+ function canonical(v) {
357
+ return JSON.stringify(v, (_k, value) => {
358
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
359
+ const keys = Object.keys(value);
360
+ return keys.length === 0 ? [] : Object.fromEntries(keys.sort().map((k) => [k, value[k]]));
361
+ });
362
+ }
363
+ function pkOf(entity) {
364
+ return entity?.pk || "id";
365
+ }
366
+ function declares(entity, column) {
367
+ const columns = entity.columns;
368
+ return !columns || Object.keys(columns).length === 0 || Object.prototype.hasOwnProperty.call(columns, column);
369
+ }
370
+ function generatedColumns(entity) {
371
+ return Object.entries(entity?.columns ?? {}).filter(([, def]) => !!def && typeof def === "object" && !!def.generated).map(([name]) => name).sort();
372
+ }
373
+ var storeOwned = (field, message) => badRequest(message, { field, fields: [field] }, { code: STORE_OWNED_FIELD });
374
+ var readOnly = (field, what) => badRequest(
375
+ `'${field}' is ${what} and cannot be changed by a write \u2014 send it as read, or leave it out`,
376
+ { field, fields: [field] },
377
+ { code: READ_ONLY_FIELD }
378
+ );
379
+ var TENANT_CHANGED = "'tenant_id' cannot be changed: a record stays in the tenant it was written under";
380
+ async function roundTripped(entity, id, patch, options) {
381
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return patch;
382
+ const out = { ...patch };
383
+ let loaded = false;
384
+ let current = null;
385
+ const stored = async () => {
386
+ if (!loaded) {
387
+ current = await options.stored();
388
+ loaded = true;
389
+ }
390
+ if (!current) throw new RecordGone();
391
+ return current;
392
+ };
393
+ const pk = pkOf(entity);
394
+ if (has(out, pk)) {
395
+ if (!noValue(out[pk]) && String(out[pk]) !== String(id)) {
396
+ throw storeOwned(pk, `'${pk}' cannot be changed: the record is '${String(id)}'`);
397
+ }
398
+ delete out[pk];
399
+ }
400
+ if (has(out, "tenant_id")) {
401
+ if (!noValue(out.tenant_id)) {
402
+ const tenant = (await stored()).tenant_id;
403
+ if (!noValue(tenant) && String(out.tenant_id) !== String(tenant)) throw storeOwned("tenant_id", TENANT_CHANGED);
404
+ }
405
+ delete out.tenant_id;
406
+ }
407
+ const left = updateFields(out);
408
+ const touch = left.length === 1 && STORE_STAMPED_COLUMNS.includes(left[0]);
409
+ for (const field of STORE_STAMPED_COLUMNS) {
410
+ if (!touch && has(out, field) && declares(entity, field)) delete out[field];
411
+ }
412
+ for (const field of CREATION_STAMP_COLUMNS) {
413
+ if (!has(out, field) || !declares(entity, field)) continue;
414
+ if (sameInstant(out[field], (await stored())[field])) delete out[field];
415
+ }
416
+ const generated = generatedColumns(entity);
417
+ for (const field of generated) delete out[field];
418
+ for (const field of [...new Set(options.readOnly ?? [])].sort()) {
419
+ if (!has(out, field) || generated.includes(field)) continue;
420
+ const type = entity.columns?.[field]?.type;
421
+ if (!sameValue(out[field], (await stored())[field], type)) throw readOnly(field, "kept by the app");
422
+ delete out[field];
423
+ }
424
+ return out;
425
+ }
305
426
 
306
427
  // src/adapters/mock.ts
307
428
  function shape(rows, query) {
@@ -334,6 +455,17 @@ function assertWhereColumns(entity, where) {
334
455
  serverDetail: { source: "mock", entity: entity.name, unknownColumns: unknown }
335
456
  });
336
457
  }
458
+ function assertUpdatableColumns(entity, patch) {
459
+ if (!patch || typeof patch !== "object") return;
460
+ const refused = [.../* @__PURE__ */ new Set([entity.pk || "id", "tenant_id"])].filter(
461
+ (k) => Object.prototype.hasOwnProperty.call(patch, k) && patch[k] !== void 0
462
+ );
463
+ if (refused.length === 0) return;
464
+ throw new HttpError(401, "unauthenticated", void 0, {
465
+ code: "bad_request",
466
+ serverDetail: { source: "mock", entity: entity.name, sqlstate: "42501", columns: refused.sort() }
467
+ });
468
+ }
337
469
  function applyDefaults(entity, data) {
338
470
  const row = { ...data };
339
471
  for (const [col, def] of Object.entries(entity.columns ?? {})) {
@@ -363,7 +495,8 @@ function createMockAdapter(seed = {}) {
363
495
  };
364
496
  const write = (entity, id, cur, patch) => {
365
497
  const row = { ...cur, ...patch };
366
- if (entity.columns?.updated_at) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
498
+ const changed = Object.keys(patch).some((k) => patch[k] !== void 0 && JSON.stringify(patch[k]) !== JSON.stringify(cur[k]));
499
+ if (entity.columns?.updated_at && changed) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
367
500
  tbl(entity).set(id, row);
368
501
  return { ...row };
369
502
  };
@@ -420,6 +553,7 @@ function createMockAdapter(seed = {}) {
420
553
  },
421
554
  async update(entity, id, patch) {
422
555
  assertKnownFields(entity, patch);
556
+ assertUpdatableColumns(entity, patch);
423
557
  const cur = tbl(entity).get(id);
424
558
  if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
425
559
  return write(entity, id, cur, patch);
@@ -432,6 +566,7 @@ function createMockAdapter(seed = {}) {
432
566
  async updateIf(entity, id, where, patch) {
433
567
  assertWhereColumns(entity, where);
434
568
  assertKnownFields(entity, patch);
569
+ assertUpdatableColumns(entity, patch);
435
570
  const cur = tbl(entity).get(id);
436
571
  if (!cur || !matches(cur, where)) return null;
437
572
  return write(entity, id, cur, patch);
@@ -801,6 +936,18 @@ function opsFromAccess(access = []) {
801
936
  for (const a of access) (ACCESS_TO_OPS[a] ?? []).forEach((o) => ops.add(o));
802
937
  return ops;
803
938
  }
939
+ function storedOnce(adapter, entity, id) {
940
+ let read;
941
+ return () => read ??= adapter.get(entity, id);
942
+ }
943
+ async function roundTrip(stored, entity, id, patch) {
944
+ try {
945
+ return await roundTripped(entity, id, patch, { stored });
946
+ } catch (err) {
947
+ if (err instanceof RecordGone) return null;
948
+ throw err;
949
+ }
950
+ }
804
951
  function entityClient(adapter, entity) {
805
952
  const ops = entity.ops instanceof Set ? entity.ops : new Set(entity.ops ?? ["list", "get", "create", "update", "delete"]);
806
953
  const guard = (op, fn, method = op) => ops.has(op) ? fn : (() => {
@@ -856,7 +1003,15 @@ function entityClient(adapter, entity) {
856
1003
  assertOneRecord(entity, patch);
857
1004
  assertUpdatable(patch);
858
1005
  assertKnownFields(entity, patch);
859
- return adapter.update(entity, id, patch);
1006
+ const stored = storedOnce(adapter, entity, id);
1007
+ const write = await roundTrip(stored, entity, id, patch);
1008
+ if (write === null) throw notFound();
1009
+ if (updateFields(write).length === 0) {
1010
+ const row = await stored();
1011
+ if (!row) throw notFound();
1012
+ return row;
1013
+ }
1014
+ return adapter.update(entity, id, write);
860
1015
  }),
861
1016
  // Validated in the same order and at the same layer as `update`, so every
862
1017
  // adapter refuses a missing condition identically, before any request.
@@ -868,7 +1023,13 @@ function entityClient(adapter, entity) {
868
1023
  if (!adapter.updateIf) {
869
1024
  throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);
870
1025
  }
871
- return adapter.updateIf(entity, id, where, patch);
1026
+ const write = await roundTrip(storedOnce(adapter, entity, id), entity, id, patch);
1027
+ if (write === null) return null;
1028
+ if (updateFields(write).length === 0) {
1029
+ const [row] = await adapter.list(entity, { where: { ...where, [pkOf(entity)]: id }, limit: 1 });
1030
+ return row ?? null;
1031
+ }
1032
+ return adapter.updateIf(entity, id, where, write);
872
1033
  }, "updateIf"),
873
1034
  delete: guard("delete", (id) => adapter.remove(entity, id))
874
1035
  };