@revenexx/app-sdk 1.0.0 → 1.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.
@@ -31,21 +31,32 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var router_exports = {};
32
32
  __export(router_exports, {
33
33
  ACTOR_HEADERS: () => ACTOR_HEADERS,
34
+ AUDIT_SETTINGS_PATH: () => AUDIT_SETTINGS_PATH,
34
35
  DEFAULT_GATEWAY_ENDPOINT: () => DEFAULT_GATEWAY_ENDPOINT,
35
36
  DEFAULT_SETTINGS_ERROR_TTL_MS: () => DEFAULT_SETTINGS_ERROR_TTL_MS,
36
37
  DEFAULT_SETTINGS_TIMEOUT_MS: () => DEFAULT_SETTINGS_TIMEOUT_MS,
37
38
  DEFAULT_SETTINGS_TTL_MS: () => DEFAULT_SETTINGS_TTL_MS,
39
+ DEFAULT_TRASH_RETENTION_DAYS: () => DEFAULT_TRASH_RETENTION_DAYS,
38
40
  HttpError: () => HttpError,
41
+ MARKET_HEADERS: () => MARKET_HEADERS,
42
+ PURGE_REASON_COLUMN: () => PURGE_REASON_COLUMN,
39
43
  RESERVED_LIST_QUERY_KEYS: () => RESERVED_LIST_QUERY_KEYS,
44
+ TRASH_COLUMN: () => TRASH_COLUMN,
40
45
  actorFrom: () => actorFrom,
46
+ auditSettingsUrl: () => auditSettingsUrl,
41
47
  badRequest: () => badRequest,
42
48
  conflict: () => conflict,
43
49
  createApp: () => createApp,
50
+ createGatewayCounter: () => createGatewayCounter,
44
51
  createSettings: () => createSettings,
45
52
  forbidden: () => forbidden,
46
53
  isHttpError: () => isHttpError,
54
+ marketFrom: () => marketFrom,
47
55
  mountCrud: () => mountCrud,
48
- notFound: () => notFound
56
+ mountTrash: () => mountTrash,
57
+ notFound: () => notFound,
58
+ readTrashRetention: () => readTrashRetention,
59
+ refusalOf: () => refusalOf
49
60
  });
50
61
  module.exports = __toCommonJS(router_exports);
51
62
 
@@ -124,6 +135,19 @@ function actorFrom(header) {
124
135
  };
125
136
  }
126
137
 
138
+ // src/router/market.ts
139
+ var MARKET_HEADERS = {
140
+ code: "x-revenexx-market",
141
+ country: "x-revenexx-market-country"
142
+ };
143
+ var COUNTRY = /^[A-Z]{2}$/;
144
+ function marketFrom(header) {
145
+ const code = (header(MARKET_HEADERS.code) ?? "").trim() || null;
146
+ const raw = (header(MARKET_HEADERS.country) ?? "").trim();
147
+ const country = code && COUNTRY.test(raw) ? raw : null;
148
+ return { code, country };
149
+ }
150
+
127
151
  // src/settings.ts
128
152
  var DEFAULT_GATEWAY_ENDPOINT = "https://api.revenexx.com";
129
153
  var DEFAULT_SETTINGS_TTL_MS = 6e4;
@@ -289,6 +313,37 @@ var notFound = (message = "not found", options = {}) => new HttpError(404, messa
289
313
  var badRequest = (message = "bad request", details, options = {}) => new HttpError(400, message, details, { code: "bad_request", ...options });
290
314
  var forbidden = (message = "forbidden", options = {}) => new HttpError(403, message, void 0, { code: "forbidden", ...options });
291
315
  var conflict = (message = "conflict", options = {}) => new HttpError(409, message, void 0, { code: "conflict", ...options });
316
+ function refusalBody(message, code, details) {
317
+ return {
318
+ error: message,
319
+ message,
320
+ ...code ? { code, type: code } : {},
321
+ ...details != null ? { details } : {}
322
+ };
323
+ }
324
+ function refusalOf(err) {
325
+ if (isHttpError(err)) {
326
+ return { status: err.status, code: err.code ?? null, message: err.message, details: err.details ?? null, app: null };
327
+ }
328
+ if (!err || typeof err !== "object") return null;
329
+ const e = err;
330
+ const status = typeof e.code === "number" ? e.code : Number.NaN;
331
+ if (!(status >= 400 && status <= 599) || typeof e.response !== "string") return null;
332
+ let body = {};
333
+ try {
334
+ const parsed = JSON.parse(e.response || "{}");
335
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) body = parsed;
336
+ } catch {
337
+ }
338
+ const str = (v) => typeof v === "string" && v !== "" ? v : null;
339
+ return {
340
+ status,
341
+ code: str(body.code) ?? str(body.type) ?? str(e.type),
342
+ message: str(body.error) ?? str(body.message) ?? str(e.message) ?? "the call was refused",
343
+ details: body.details ?? null,
344
+ app: str(e.app)
345
+ };
346
+ }
292
347
 
293
348
  // src/router/router.ts
294
349
  var splitPath = (path) => path.split("/").filter(Boolean);
@@ -447,9 +502,9 @@ function createApp(options = {}) {
447
502
  span.setAttribute("http.response.status_code", status);
448
503
  span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: pathExists ? "method not allowed" : "no route" });
449
504
  if (pathExists) {
450
- return res.json({ error: `method ${method} not allowed for ${path}`, code: "method_not_allowed" }, 405);
505
+ return res.json(refusalBody(`method ${method} not allowed for ${path}`, "method_not_allowed"), 405);
451
506
  }
452
- return res.json({ error: `no route for ${method} ${path}`, code: "no_route", routes: app.routes() }, 404);
507
+ return res.json({ ...refusalBody(`no route for ${method} ${path}`, "no_route"), routes: app.routes() }, 404);
453
508
  }
454
509
  span.updateName(`${method} ${matched.route.template}`);
455
510
  span.setAttribute("http.route", matched.route.template);
@@ -471,6 +526,7 @@ function createApp(options = {}) {
471
526
  contextToken,
472
527
  header: (name) => headerOf2(headers, name),
473
528
  actor: actorFrom((name) => headerOf2(headers, name)),
529
+ market: marketFrom((name) => headerOf2(headers, name)),
474
530
  log,
475
531
  json: (data, statusCode = 200) => res.json(data, statusCode),
476
532
  // The market rides on the request, so a market-scoped setting
@@ -489,21 +545,15 @@ function createApp(options = {}) {
489
545
  span.setAttribute("revenexx.error.detail", detail);
490
546
  context.error?.(`${method} ${path} \u2014 ${err.status} ${err.message}: ${detail}`);
491
547
  }
492
- return res.json(
493
- {
494
- error: err.message,
495
- ...err.code ? { code: err.code } : {},
496
- ...err.details != null ? { details: err.details } : {}
497
- },
498
- err.status
499
- );
548
+ return res.json(refusalBody(err.message, err.code, err.details), err.status);
500
549
  }
501
- const msg = err instanceof Error ? err.message : String(err);
550
+ const upstream = refusalOf(err);
551
+ const msg = upstream ? `refused by ${upstream.app ?? "another app"}: ${upstream.status} ${upstream.code ?? ""} ${upstream.message}`.replace(/\s+/g, " ") : err instanceof Error ? err.message : String(err);
502
552
  span.setAttribute("http.response.status_code", 500);
503
553
  span.recordException(err instanceof Error ? err : new Error(msg));
504
554
  span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: msg });
505
555
  context.error?.(`unhandled error on ${method} ${path}: ${msg}`);
506
- return res.json({ error: "internal error", code: "internal_error" }, 500);
556
+ return res.json(refusalBody("internal error", "internal_error"), 500);
507
557
  } finally {
508
558
  span.end();
509
559
  }
@@ -658,23 +708,281 @@ function mountCrud(app, repo, opts) {
658
708
  }
659
709
  return app;
660
710
  }
711
+
712
+ // src/router/trash.ts
713
+ var import_node_crypto = require("crypto");
714
+ var TRASH_COLUMN = "deleted_at";
715
+ var DEFAULT_TRASH_RETENTION_DAYS = 90;
716
+ var PURGE_REASON_COLUMN = "purge_blocked_reason";
717
+ var AUDIT_SETTINGS_PATH = "/v1/audit/settings";
718
+ var PAGE = 200;
719
+ var isTrashed = (row) => row[TRASH_COLUMN] !== null && row[TRASH_COLUMN] !== void 0;
720
+ var idOf = (row, fallback) => String(row.id ?? fallback);
721
+ async function listAll(repo, where) {
722
+ const rows = [];
723
+ for (; ; ) {
724
+ const batch = await repo.list({ where, limit: PAGE, offset: rows.length });
725
+ rows.push(...batch);
726
+ if (batch.length < PAGE) return rows;
727
+ }
728
+ }
729
+ async function runCheck(check, row, caller) {
730
+ if (!check) return [];
731
+ try {
732
+ const out = await check(row, caller);
733
+ const list = Array.isArray(out) ? out : [out];
734
+ return list.filter((b) => Boolean(b && typeof b.reason === "string"));
735
+ } catch (err) {
736
+ return [
737
+ {
738
+ reason: `could not be checked: ${err instanceof Error ? err.message : String(err)}`,
739
+ code: "unverifiable"
740
+ }
741
+ ];
742
+ }
743
+ }
744
+ var refuse = (status, message, code, details) => new HttpError(status, message, details, { code });
745
+ function headerFrom(caller, name) {
746
+ if (typeof caller.header === "function") {
747
+ const v = caller.header(name);
748
+ if (typeof v === "string" && v !== "") return v;
749
+ }
750
+ const want = name.toLowerCase();
751
+ for (const bag of [caller.req?.headers, caller.headers]) {
752
+ if (!bag) continue;
753
+ for (const [k, v] of Object.entries(bag)) if (k.toLowerCase() === want && typeof v === "string" && v !== "") return v;
754
+ }
755
+ return "";
756
+ }
757
+ function auditSettingsUrl(options = {}) {
758
+ const env = options.env ?? process.env;
759
+ const url = options.url || env.REVENEXX_AUDIT_SETTINGS_URL;
760
+ if (url) return url;
761
+ const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\/+$/, "");
762
+ return `${endpoint}${AUDIT_SETTINGS_PATH}`;
763
+ }
764
+ async function readTrashRetention(caller, options = {}) {
765
+ const url = auditSettingsUrl(options);
766
+ const f = options.fetchImpl ?? globalThis.fetch;
767
+ const tenant = (caller.tenant ?? "") || headerFrom(caller, "x-revenexx-tenant");
768
+ if (!tenant) throw new Error("trash retention: no tenant");
769
+ const token = (caller.contextToken ?? "") || headerFrom(caller, "x-revenexx-context");
770
+ const headers = { Accept: "application/json", "X-Revenexx-Tenant": tenant };
771
+ if (token) headers.Authorization = `Bearer ${token}`;
772
+ const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5e3);
773
+ const res = await f(url, { method: "GET", headers, ...signal ? { signal } : {} });
774
+ if (!res.ok) throw new Error(`trash retention: ${res.status} from ${AUDIT_SETTINGS_PATH}`);
775
+ const body = await res.json();
776
+ const days = body.trash_retention_days;
777
+ return typeof days === "number" && Number.isInteger(days) && days > 0 ? days : DEFAULT_TRASH_RETENTION_DAYS;
778
+ }
779
+ function mountTrash(app, repo, opts) {
780
+ const base = opts.path.replace(/\/+$/, "");
781
+ const idParam = opts.idParam ?? "id";
782
+ const children = opts.children ?? [];
783
+ const now = opts.now ?? (() => /* @__PURE__ */ new Date());
784
+ const reasonColumn = opts.purgeReasonColumn === false ? null : opts.purgeReasonColumn ?? PURGE_REASON_COLUMN;
785
+ const load = async (id) => {
786
+ if (!id) throw refuse(400, `missing path parameter '${idParam}'`, "missing_parameter");
787
+ const row = await repo.get(id);
788
+ if (!row) throw notFound();
789
+ return row;
790
+ };
791
+ const emit = async (name, data, topicId) => {
792
+ if (!name || !opts.events) return;
793
+ await opts.events.emit(name, data, { topicId });
794
+ };
795
+ async function trash(id, caller) {
796
+ const row = await load(id);
797
+ if (isTrashed(row)) throw refuse(409, "this record is already in the trash", "already_in_trash");
798
+ const blockers = await runCheck(opts.guard, row, caller);
799
+ if (blockers.length) {
800
+ throw refuse(409, `cannot go into the trash: ${blockers.map((b) => b.reason).join("; ")}`, "trash_blocked", { blockers });
801
+ }
802
+ const batch = (0, import_node_crypto.randomUUID)();
803
+ const fields = {
804
+ [TRASH_COLUMN]: now().toISOString(),
805
+ deleted_by: caller.actor?.email ?? caller.actor?.user ?? null,
806
+ deleted_by_id: caller.actor?.user ?? caller.actor?.contact ?? null,
807
+ trash_batch: batch
808
+ };
809
+ await repo.update(id, fields);
810
+ const took = {};
811
+ for (const child of children) {
812
+ const rows = await listAll(child.repo, { [child.column]: id, [TRASH_COLUMN]: null });
813
+ for (const r of rows) await child.repo.update(String(r.id), fields);
814
+ took[child.name] = rows.length;
815
+ }
816
+ await emit(opts.events?.trashed, { id, batch, took }, idOf(row, id));
817
+ return { id, batch, took };
818
+ }
819
+ async function restore(id, caller) {
820
+ void caller;
821
+ const row = await load(id);
822
+ if (!isTrashed(row)) throw refuse(409, "this record is not in the trash", "not_in_trash");
823
+ if (opts.parent) {
824
+ const parentId = row[opts.parent.column];
825
+ const parent = parentId == null ? null : await opts.parent.repo.get(String(parentId));
826
+ if (parent && isTrashed(parent)) {
827
+ throw refuse(409, "its parent is in the trash \u2014 restore the parent first", "parent_in_trash", {
828
+ parent: String(parentId)
829
+ });
830
+ }
831
+ }
832
+ const fields = { [TRASH_COLUMN]: null, deleted_by: null, deleted_by_id: null, trash_batch: null };
833
+ await repo.update(id, reasonColumn ? { ...fields, [reasonColumn]: null } : fields);
834
+ const took = {};
835
+ const batch = row.trash_batch;
836
+ for (const child of children) {
837
+ const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });
838
+ for (const r of rows) await child.repo.update(String(r.id), fields);
839
+ took[child.name] = rows.length;
840
+ }
841
+ await emit(opts.events?.restored, { id, took }, idOf(row, id));
842
+ return { id, took };
843
+ }
844
+ async function finalDelete(row, id, caller) {
845
+ const took = {};
846
+ const batch = row.trash_batch;
847
+ for (const child of children) {
848
+ const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });
849
+ for (const r of rows) await child.repo.delete(String(r.id));
850
+ took[child.name] = rows.length;
851
+ }
852
+ if (opts.deleteRow) await opts.deleteRow(row, caller);
853
+ else await repo.delete(id);
854
+ return { id, took };
855
+ }
856
+ async function deleteForGood(id, caller) {
857
+ const row = await load(id);
858
+ if (!isTrashed(row)) throw refuse(409, "only a record in the trash can be deleted for good", "not_in_trash");
859
+ if (opts.canDeleteForGood && !opts.canDeleteForGood(caller)) {
860
+ throw refuse(403, "deleting for good needs its own permission", "not_permitted");
861
+ }
862
+ const blockers = await runCheck(opts.blockers, row, caller);
863
+ if (blockers.length) {
864
+ throw refuse(409, `cannot be deleted for good: ${blockers.map((b) => b.reason).join("; ")}`, "delete_blocked", {
865
+ blockers
866
+ });
867
+ }
868
+ return finalDelete(row, id, caller);
869
+ }
870
+ async function purge(caller, options = {}) {
871
+ let retentionDays;
872
+ try {
873
+ retentionDays = await readTrashRetention(caller, opts.retention);
874
+ } catch (err) {
875
+ return { skipped: true, reason: err instanceof Error ? err.message : String(err), purged: [], blocked: [] };
876
+ }
877
+ const cutoff = new Date(now().getTime() - retentionDays * 864e5).toISOString();
878
+ const max = options.max ?? 500;
879
+ const due = (await listAll(repo, { [TRASH_COLUMN]: { op: "lt", value: cutoff } })).slice(0, max);
880
+ const result = { skipped: false, retentionDays, cutoff, purged: [], blocked: [] };
881
+ for (const row of due) {
882
+ const id = String(row.id);
883
+ const blockers = await runCheck(opts.blockers, row, caller);
884
+ if (blockers.length) {
885
+ result.blocked.push({ id, blockers });
886
+ const reason = blockers.map((b) => b.reason).join("; ");
887
+ if (reasonColumn && row[reasonColumn] !== reason) {
888
+ try {
889
+ await repo.update(id, { [reasonColumn]: reason });
890
+ } catch {
891
+ }
892
+ }
893
+ continue;
894
+ }
895
+ try {
896
+ await finalDelete(row, id, caller);
897
+ result.purged.push(id);
898
+ } catch (err) {
899
+ result.blocked.push({
900
+ id,
901
+ blockers: [{ reason: `delete failed: ${err instanceof Error ? err.message : String(err)}`, code: "delete_failed" }]
902
+ });
903
+ }
904
+ }
905
+ await emit(
906
+ opts.events?.purged,
907
+ { retention_days: retentionDays, cutoff, purged: result.purged.length, blocked: result.blocked.length },
908
+ null
909
+ );
910
+ return result;
911
+ }
912
+ app.delete(`${base}/{${idParam}}`, async (c) => {
913
+ const id = c.params[idParam] ?? "";
914
+ const row = await load(id);
915
+ if (isTrashed(row)) return c.json({ deleted: true, ...await deleteForGood(id, c) });
916
+ return c.json({ trashed: true, ...await trash(id, c) });
917
+ });
918
+ app.post(`${base}/{${idParam}}/restore`, async (c) => {
919
+ return c.json({ restored: true, ...await restore(c.params[idParam] ?? "", c) });
920
+ });
921
+ return { trash, restore, deleteForGood, purge };
922
+ }
923
+ function createGatewayCounter(options = {}) {
924
+ const env = options.env ?? process.env;
925
+ const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\/+$/, "");
926
+ async function count(caller, path, where = {}) {
927
+ const f = options.fetchImpl ?? globalThis.fetch;
928
+ const qs = new URLSearchParams();
929
+ for (const [k, v] of Object.entries(where)) qs.set(k, String(v));
930
+ qs.set("limit", "1");
931
+ const headers = { Accept: "application/json" };
932
+ const tenant = (caller.tenant ?? "") || headerFrom(caller, "x-revenexx-tenant");
933
+ if (tenant) headers["X-Revenexx-Tenant"] = tenant;
934
+ const context = (caller.contextToken ?? "") || headerFrom(caller, "x-revenexx-context");
935
+ if (context) headers.Authorization = `Bearer ${context}`;
936
+ const appContext = headerFrom(caller, "x-revenexx-app-context");
937
+ if (appContext) headers["x-revenexx-app-context"] = appContext;
938
+ try {
939
+ const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5e3);
940
+ const sep = path.includes("?") ? "&" : "?";
941
+ const res = await f(`${endpoint}${path}${sep}${qs.toString()}`, { headers, ...signal ? { signal } : {} });
942
+ if (!res.ok) return null;
943
+ const body = await res.json();
944
+ const total = body?.page?.total;
945
+ return typeof total === "number" && Number.isFinite(total) ? total : null;
946
+ } catch {
947
+ return null;
948
+ }
949
+ }
950
+ async function blocker(caller, check) {
951
+ const n = await count(caller, check.path, check.where);
952
+ if (n === null) return { reason: `${check.reason} \u2014 could not be checked`, code: "unverifiable" };
953
+ if (n === 0) return null;
954
+ return { reason: `${n} ${check.reason}`, count: n, code: "referenced" };
955
+ }
956
+ return { count, blocker };
957
+ }
661
958
  // Annotate the CommonJS export names for ESM import in node:
662
959
  0 && (module.exports = {
663
960
  ACTOR_HEADERS,
961
+ AUDIT_SETTINGS_PATH,
664
962
  DEFAULT_GATEWAY_ENDPOINT,
665
963
  DEFAULT_SETTINGS_ERROR_TTL_MS,
666
964
  DEFAULT_SETTINGS_TIMEOUT_MS,
667
965
  DEFAULT_SETTINGS_TTL_MS,
966
+ DEFAULT_TRASH_RETENTION_DAYS,
668
967
  HttpError,
968
+ MARKET_HEADERS,
969
+ PURGE_REASON_COLUMN,
669
970
  RESERVED_LIST_QUERY_KEYS,
971
+ TRASH_COLUMN,
670
972
  actorFrom,
973
+ auditSettingsUrl,
671
974
  badRequest,
672
975
  conflict,
673
976
  createApp,
977
+ createGatewayCounter,
674
978
  createSettings,
675
979
  forbidden,
676
980
  isHttpError,
981
+ marketFrom,
677
982
  mountCrud,
678
- notFound
983
+ mountTrash,
984
+ notFound,
985
+ readTrashRetention,
986
+ refusalOf
679
987
  });
680
988
  //# sourceMappingURL=index.cjs.map