@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.
@@ -509,6 +509,165 @@ function describedEntity(repo) {
509
509
  function oneRecordRefusal() {
510
510
  return badRequest(ONE_RECORD_MESSAGE, void 0, { code: "bad_request" });
511
511
  }
512
+ var STORE_OWNED_FIELD = "store_owned_field";
513
+ var READ_ONLY_FIELD = "read_only_field";
514
+ var STORE_STAMPED_COLUMNS = ["updated_at"];
515
+ var CREATION_STAMP_COLUMNS = ["created_at"];
516
+ var TRASH_ROUND_TRIP_COLUMNS = [...TRASH_FLAG_COLUMNS, "purge_at"];
517
+ var RecordGone = class extends Error {
518
+ constructor() {
519
+ super("the record is not there");
520
+ this.name = "RecordGone";
521
+ }
522
+ };
523
+ var noValue = (v) => v === null || v === void 0 || v === "";
524
+ var has = (row, key) => Object.prototype.hasOwnProperty.call(row, key) && row[key] !== void 0;
525
+ var nullish = (v) => v === null || v === void 0;
526
+ var DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?$/;
527
+ var NUMERIC_TYPE = /^(?:(?:small|big)?int(?:eger)?|int[248]|(?:big|small)?serial|serial[248]|numeric|decimal|real|double|float[48]?)\b/i;
528
+ var INSTANT = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
529
+ function sameInstant(a, b) {
530
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
531
+ if (String(a) === String(b)) return true;
532
+ if (typeof a !== "string" || typeof b !== "string" || !INSTANT.test(a) || !INSTANT.test(b)) return false;
533
+ const x = Date.parse(a);
534
+ const y = Date.parse(b);
535
+ return Number.isFinite(x) && Number.isFinite(y) && x === y;
536
+ }
537
+ function decimal(v) {
538
+ const text = typeof v === "number" ? Number.isFinite(v) ? String(v) : "" : typeof v === "string" ? v.trim() : "";
539
+ const m = DECIMAL.exec(text);
540
+ if (!m || m[2] === "" && (m[3] ?? "") === "") return null;
541
+ const whole = m[2].replace(/^0+(?=\d)/, "") || "0";
542
+ const fraction = (m[3] ?? "").replace(/0+$/, "");
543
+ const digits = fraction ? `${whole}.${fraction}` : whole;
544
+ return digits === "0" ? "0" : `${m[1] === "-" ? "-" : ""}${digits}`;
545
+ }
546
+ function isNumericType(type) {
547
+ return NUMERIC_TYPE.test(String(type ?? "").trim());
548
+ }
549
+ function sameValue(a, b, type) {
550
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
551
+ if (typeof a === "object" || typeof b === "object") return canonical(a) === canonical(b);
552
+ if (String(a) === String(b)) return true;
553
+ if (isNumericType(type)) {
554
+ const x = decimal(a);
555
+ const y = decimal(b);
556
+ if (x !== null && y !== null) return x === y;
557
+ const fx = Number(a);
558
+ const fy = Number(b);
559
+ return Number.isFinite(fx) && Number.isFinite(fy) && fx === fy;
560
+ }
561
+ return sameInstant(a, b);
562
+ }
563
+ function canonical(v) {
564
+ return JSON.stringify(v, (_k, value) => {
565
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
566
+ const keys = Object.keys(value);
567
+ return keys.length === 0 ? [] : Object.fromEntries(keys.sort().map((k) => [k, value[k]]));
568
+ });
569
+ }
570
+ function pkOf(entity) {
571
+ return entity?.pk || "id";
572
+ }
573
+ function declares(entity, column) {
574
+ const columns = entity.columns;
575
+ return !columns || Object.keys(columns).length === 0 || Object.prototype.hasOwnProperty.call(columns, column);
576
+ }
577
+ function generatedColumns(entity) {
578
+ return Object.entries(entity?.columns ?? {}).filter(([, def]) => !!def && typeof def === "object" && !!def.generated).map(([name]) => name).sort();
579
+ }
580
+ function storeAssignsKey(entity) {
581
+ const def = entity?.columns?.[pkOf(entity)];
582
+ if (!def || typeof def !== "object") return false;
583
+ if (/^(big)?serial\b/i.test(String(def.type ?? ""))) return true;
584
+ return /gen_random_uuid/i.test(String(def.default ?? ""));
585
+ }
586
+ var storeOwned = (field, message) => badRequest(message, { field, fields: [field] }, { code: STORE_OWNED_FIELD });
587
+ var readOnly = (field, what) => badRequest(
588
+ `'${field}' is ${what} and cannot be changed by a write \u2014 send it as read, or leave it out`,
589
+ { field, fields: [field] },
590
+ { code: READ_ONLY_FIELD }
591
+ );
592
+ var TENANT_CHANGED = "'tenant_id' cannot be changed: a record stays in the tenant it was written under";
593
+ async function roundTripped(entity, id, patch, options) {
594
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return patch;
595
+ const out = { ...patch };
596
+ let loaded = false;
597
+ let current = null;
598
+ const stored = async () => {
599
+ if (!loaded) {
600
+ current = await options.stored();
601
+ loaded = true;
602
+ }
603
+ if (!current) throw new RecordGone();
604
+ return current;
605
+ };
606
+ const pk = pkOf(entity);
607
+ if (has(out, pk)) {
608
+ if (!noValue(out[pk]) && String(out[pk]) !== String(id)) {
609
+ throw storeOwned(pk, `'${pk}' cannot be changed: the record is '${String(id)}'`);
610
+ }
611
+ delete out[pk];
612
+ }
613
+ if (has(out, "tenant_id")) {
614
+ if (!noValue(out.tenant_id)) {
615
+ const tenant = (await stored()).tenant_id;
616
+ if (!noValue(tenant) && String(out.tenant_id) !== String(tenant)) throw storeOwned("tenant_id", TENANT_CHANGED);
617
+ }
618
+ delete out.tenant_id;
619
+ }
620
+ const left = updateFields(out);
621
+ const touch = left.length === 1 && STORE_STAMPED_COLUMNS.includes(left[0]);
622
+ for (const field of STORE_STAMPED_COLUMNS) {
623
+ if (!touch && has(out, field) && declares(entity, field)) delete out[field];
624
+ }
625
+ for (const field of CREATION_STAMP_COLUMNS) {
626
+ if (!has(out, field) || !declares(entity, field)) continue;
627
+ if (sameInstant(out[field], (await stored())[field])) delete out[field];
628
+ }
629
+ const generated = generatedColumns(entity);
630
+ for (const field of generated) delete out[field];
631
+ for (const field of [...new Set(options.readOnly ?? [])].sort()) {
632
+ if (!has(out, field) || generated.includes(field)) continue;
633
+ const type = entity.columns?.[field]?.type;
634
+ if (!sameValue(out[field], (await stored())[field], type)) throw readOnly(field, "kept by the app");
635
+ delete out[field];
636
+ }
637
+ return out;
638
+ }
639
+ function createdFields(entity, body, tenant) {
640
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
641
+ const out = { ...body };
642
+ const pk = pkOf(entity);
643
+ if (has(out, pk) && storeAssignsKey(entity)) {
644
+ if (!noValue(out[pk])) throw storeOwned(pk, `'${pk}' is assigned by the store and cannot be sent on a create`);
645
+ delete out[pk];
646
+ }
647
+ if (has(out, "tenant_id")) {
648
+ if (!noValue(out.tenant_id) && !noValue(tenant) && String(out.tenant_id) !== String(tenant)) {
649
+ throw storeOwned("tenant_id", "'tenant_id' is the tenant of the request and cannot name another");
650
+ }
651
+ delete out.tenant_id;
652
+ }
653
+ return out;
654
+ }
655
+ function withoutNullTrash(body) {
656
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
657
+ const row = body;
658
+ if (!TRASH_ROUND_TRIP_COLUMNS.some((k) => Object.prototype.hasOwnProperty.call(row, k) && row[k] === null)) return body;
659
+ const out = { ...row };
660
+ for (const k of TRASH_ROUND_TRIP_COLUMNS) if (out[k] === null) delete out[k];
661
+ return out;
662
+ }
663
+ function trashRoundTripped(body, stored) {
664
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
665
+ const out = { ...body };
666
+ for (const k of TRASH_ROUND_TRIP_COLUMNS) {
667
+ if (Object.prototype.hasOwnProperty.call(out, k) && out[k] === null && nullish(stored[k])) delete out[k];
668
+ }
669
+ return out;
670
+ }
512
671
 
513
672
  // src/backdating.ts
514
673
  var MAX_MONTHS_BACK = 24;
@@ -954,6 +1113,10 @@ function mountCrud(app, repo, opts) {
954
1113
  trash: guardsTrash(opts.trash, described?.trash, opts.columns),
955
1114
  external_id: opts.external_id === true || described?.external_id === true
956
1115
  };
1116
+ const shape = {
1117
+ pk: described?.pk,
1118
+ columns: opts.columns ?? described?.columns
1119
+ };
957
1120
  if (enabled.has("list")) {
958
1121
  app.get(base, async (c) => {
959
1122
  assertKnownKeys(c.query, opts, flags);
@@ -985,9 +1148,11 @@ function mountCrud(app, repo, opts) {
985
1148
  if (enabled.has("create")) {
986
1149
  app.post(base, async (c) => {
987
1150
  if (isList(c.body)) throw oneRecordRefusal();
988
- assertNoTrashFields(flags, c.body);
1151
+ const body = flags.trash ? withoutNullTrash(c.body) : c.body;
1152
+ assertNoTrashFields(flags, body);
1153
+ const fields = createdFields(shape, body ?? {}, c.tenant);
989
1154
  await assertParentExists(c, opts.parent);
990
- const data = { ...c.body, ...parentWhere(c, opts.parent) };
1155
+ const data = { ...fields, ...parentWhere(c, opts.parent) };
991
1156
  return c.json(await repo.create(data), 201);
992
1157
  });
993
1158
  }
@@ -1000,11 +1165,15 @@ function mountCrud(app, repo, opts) {
1000
1165
  if (enabled.has("update")) {
1001
1166
  app.put(idTemplate, async (c) => {
1002
1167
  if (isList(c.body)) throw oneRecordRefusal();
1003
- assertNoTrashFields(flags, c.body);
1004
- const { id } = await fetchOwned(repo, c, opts);
1168
+ assertNoTrashFields(flags, flags.trash ? withoutNullTrash(c.body) : c.body);
1169
+ const { id, row } = await fetchOwned(repo, c, opts);
1170
+ const body = flags.trash ? trashRoundTripped(c.body, row) : c.body;
1171
+ assertNoTrashFields(flags, body);
1005
1172
  if (updateFields(c.body).length === 0) throw new HttpError(400, EMPTY_UPDATE_MESSAGE, void 0, { code: "empty_update" });
1006
- const patch = { ...c.body, ...parentWhere(c, opts.parent) };
1007
- return c.json(await repo.update(id, patch));
1173
+ const fields = await roundTripped(shape, id, body, { stored: () => row, readOnly: opts.readOnly });
1174
+ if (opts.parent) delete fields[opts.parent.column];
1175
+ if (updateFields(fields).length === 0) return c.json(row);
1176
+ return c.json(await repo.update(id, fields));
1008
1177
  });
1009
1178
  }
1010
1179
  if (enabled.has("delete")) {