@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.
@@ -12,8 +12,10 @@ import {
12
12
  forbidden,
13
13
  isHttpError,
14
14
  notFound,
15
+ refusalBody,
16
+ refusalOf,
15
17
  updateFields
16
- } from "../chunk-73D37ZGB.js";
18
+ } from "../chunk-P6ZEOMKS.js";
17
19
 
18
20
  // src/instrument.ts
19
21
  var started = false;
@@ -96,6 +98,19 @@ function actorFrom(header) {
96
98
  };
97
99
  }
98
100
 
101
+ // src/router/market.ts
102
+ var MARKET_HEADERS = {
103
+ code: "x-revenexx-market",
104
+ country: "x-revenexx-market-country"
105
+ };
106
+ var COUNTRY = /^[A-Z]{2}$/;
107
+ function marketFrom(header) {
108
+ const code = (header(MARKET_HEADERS.code) ?? "").trim() || null;
109
+ const raw = (header(MARKET_HEADERS.country) ?? "").trim();
110
+ const country = code && COUNTRY.test(raw) ? raw : null;
111
+ return { code, country };
112
+ }
113
+
99
114
  // src/router/router.ts
100
115
  var splitPath = (path) => path.split("/").filter(Boolean);
101
116
  function compileTemplate(template) {
@@ -253,9 +268,9 @@ function createApp(options = {}) {
253
268
  span.setAttribute("http.response.status_code", status);
254
269
  span.setStatus({ code: SpanStatusCode.ERROR, message: pathExists ? "method not allowed" : "no route" });
255
270
  if (pathExists) {
256
- return res.json({ error: `method ${method} not allowed for ${path}`, code: "method_not_allowed" }, 405);
271
+ return res.json(refusalBody(`method ${method} not allowed for ${path}`, "method_not_allowed"), 405);
257
272
  }
258
- return res.json({ error: `no route for ${method} ${path}`, code: "no_route", routes: app.routes() }, 404);
273
+ return res.json({ ...refusalBody(`no route for ${method} ${path}`, "no_route"), routes: app.routes() }, 404);
259
274
  }
260
275
  span.updateName(`${method} ${matched.route.template}`);
261
276
  span.setAttribute("http.route", matched.route.template);
@@ -277,6 +292,7 @@ function createApp(options = {}) {
277
292
  contextToken,
278
293
  header: (name) => headerOf(headers, name),
279
294
  actor: actorFrom((name) => headerOf(headers, name)),
295
+ market: marketFrom((name) => headerOf(headers, name)),
280
296
  log,
281
297
  json: (data, statusCode = 200) => res.json(data, statusCode),
282
298
  // The market rides on the request, so a market-scoped setting
@@ -295,21 +311,15 @@ function createApp(options = {}) {
295
311
  span.setAttribute("revenexx.error.detail", detail);
296
312
  context.error?.(`${method} ${path} \u2014 ${err.status} ${err.message}: ${detail}`);
297
313
  }
298
- return res.json(
299
- {
300
- error: err.message,
301
- ...err.code ? { code: err.code } : {},
302
- ...err.details != null ? { details: err.details } : {}
303
- },
304
- err.status
305
- );
314
+ return res.json(refusalBody(err.message, err.code, err.details), err.status);
306
315
  }
307
- const msg = err instanceof Error ? err.message : String(err);
316
+ const upstream = refusalOf(err);
317
+ 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);
308
318
  span.setAttribute("http.response.status_code", 500);
309
319
  span.recordException(err instanceof Error ? err : new Error(msg));
310
320
  span.setStatus({ code: SpanStatusCode.ERROR, message: msg });
311
321
  context.error?.(`unhandled error on ${method} ${path}: ${msg}`);
312
- return res.json({ error: "internal error", code: "internal_error" }, 500);
322
+ return res.json(refusalBody("internal error", "internal_error"), 500);
313
323
  } finally {
314
324
  span.end();
315
325
  }
@@ -452,22 +462,280 @@ function mountCrud(app, repo, opts) {
452
462
  }
453
463
  return app;
454
464
  }
465
+
466
+ // src/router/trash.ts
467
+ import { randomUUID } from "crypto";
468
+ var TRASH_COLUMN = "deleted_at";
469
+ var DEFAULT_TRASH_RETENTION_DAYS = 90;
470
+ var PURGE_REASON_COLUMN = "purge_blocked_reason";
471
+ var AUDIT_SETTINGS_PATH = "/v1/audit/settings";
472
+ var PAGE = 200;
473
+ var isTrashed = (row) => row[TRASH_COLUMN] !== null && row[TRASH_COLUMN] !== void 0;
474
+ var idOf = (row, fallback) => String(row.id ?? fallback);
475
+ async function listAll(repo, where) {
476
+ const rows = [];
477
+ for (; ; ) {
478
+ const batch = await repo.list({ where, limit: PAGE, offset: rows.length });
479
+ rows.push(...batch);
480
+ if (batch.length < PAGE) return rows;
481
+ }
482
+ }
483
+ async function runCheck(check, row, caller) {
484
+ if (!check) return [];
485
+ try {
486
+ const out = await check(row, caller);
487
+ const list = Array.isArray(out) ? out : [out];
488
+ return list.filter((b) => Boolean(b && typeof b.reason === "string"));
489
+ } catch (err) {
490
+ return [
491
+ {
492
+ reason: `could not be checked: ${err instanceof Error ? err.message : String(err)}`,
493
+ code: "unverifiable"
494
+ }
495
+ ];
496
+ }
497
+ }
498
+ var refuse = (status, message, code, details) => new HttpError(status, message, details, { code });
499
+ function headerFrom(caller, name) {
500
+ if (typeof caller.header === "function") {
501
+ const v = caller.header(name);
502
+ if (typeof v === "string" && v !== "") return v;
503
+ }
504
+ const want = name.toLowerCase();
505
+ for (const bag of [caller.req?.headers, caller.headers]) {
506
+ if (!bag) continue;
507
+ for (const [k, v] of Object.entries(bag)) if (k.toLowerCase() === want && typeof v === "string" && v !== "") return v;
508
+ }
509
+ return "";
510
+ }
511
+ function auditSettingsUrl(options = {}) {
512
+ const env = options.env ?? process.env;
513
+ const url = options.url || env.REVENEXX_AUDIT_SETTINGS_URL;
514
+ if (url) return url;
515
+ const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\/+$/, "");
516
+ return `${endpoint}${AUDIT_SETTINGS_PATH}`;
517
+ }
518
+ async function readTrashRetention(caller, options = {}) {
519
+ const url = auditSettingsUrl(options);
520
+ const f = options.fetchImpl ?? globalThis.fetch;
521
+ const tenant = (caller.tenant ?? "") || headerFrom(caller, "x-revenexx-tenant");
522
+ if (!tenant) throw new Error("trash retention: no tenant");
523
+ const token = (caller.contextToken ?? "") || headerFrom(caller, "x-revenexx-context");
524
+ const headers = { Accept: "application/json", "X-Revenexx-Tenant": tenant };
525
+ if (token) headers.Authorization = `Bearer ${token}`;
526
+ const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5e3);
527
+ const res = await f(url, { method: "GET", headers, ...signal ? { signal } : {} });
528
+ if (!res.ok) throw new Error(`trash retention: ${res.status} from ${AUDIT_SETTINGS_PATH}`);
529
+ const body = await res.json();
530
+ const days = body.trash_retention_days;
531
+ return typeof days === "number" && Number.isInteger(days) && days > 0 ? days : DEFAULT_TRASH_RETENTION_DAYS;
532
+ }
533
+ function mountTrash(app, repo, opts) {
534
+ const base = opts.path.replace(/\/+$/, "");
535
+ const idParam = opts.idParam ?? "id";
536
+ const children = opts.children ?? [];
537
+ const now = opts.now ?? (() => /* @__PURE__ */ new Date());
538
+ const reasonColumn = opts.purgeReasonColumn === false ? null : opts.purgeReasonColumn ?? PURGE_REASON_COLUMN;
539
+ const load = async (id) => {
540
+ if (!id) throw refuse(400, `missing path parameter '${idParam}'`, "missing_parameter");
541
+ const row = await repo.get(id);
542
+ if (!row) throw notFound();
543
+ return row;
544
+ };
545
+ const emit = async (name, data, topicId) => {
546
+ if (!name || !opts.events) return;
547
+ await opts.events.emit(name, data, { topicId });
548
+ };
549
+ async function trash(id, caller) {
550
+ const row = await load(id);
551
+ if (isTrashed(row)) throw refuse(409, "this record is already in the trash", "already_in_trash");
552
+ const blockers = await runCheck(opts.guard, row, caller);
553
+ if (blockers.length) {
554
+ throw refuse(409, `cannot go into the trash: ${blockers.map((b) => b.reason).join("; ")}`, "trash_blocked", { blockers });
555
+ }
556
+ const batch = randomUUID();
557
+ const fields = {
558
+ [TRASH_COLUMN]: now().toISOString(),
559
+ deleted_by: caller.actor?.email ?? caller.actor?.user ?? null,
560
+ deleted_by_id: caller.actor?.user ?? caller.actor?.contact ?? null,
561
+ trash_batch: batch
562
+ };
563
+ await repo.update(id, fields);
564
+ const took = {};
565
+ for (const child of children) {
566
+ const rows = await listAll(child.repo, { [child.column]: id, [TRASH_COLUMN]: null });
567
+ for (const r of rows) await child.repo.update(String(r.id), fields);
568
+ took[child.name] = rows.length;
569
+ }
570
+ await emit(opts.events?.trashed, { id, batch, took }, idOf(row, id));
571
+ return { id, batch, took };
572
+ }
573
+ async function restore(id, caller) {
574
+ void caller;
575
+ const row = await load(id);
576
+ if (!isTrashed(row)) throw refuse(409, "this record is not in the trash", "not_in_trash");
577
+ if (opts.parent) {
578
+ const parentId = row[opts.parent.column];
579
+ const parent = parentId == null ? null : await opts.parent.repo.get(String(parentId));
580
+ if (parent && isTrashed(parent)) {
581
+ throw refuse(409, "its parent is in the trash \u2014 restore the parent first", "parent_in_trash", {
582
+ parent: String(parentId)
583
+ });
584
+ }
585
+ }
586
+ const fields = { [TRASH_COLUMN]: null, deleted_by: null, deleted_by_id: null, trash_batch: null };
587
+ await repo.update(id, reasonColumn ? { ...fields, [reasonColumn]: null } : fields);
588
+ const took = {};
589
+ const batch = row.trash_batch;
590
+ for (const child of children) {
591
+ const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });
592
+ for (const r of rows) await child.repo.update(String(r.id), fields);
593
+ took[child.name] = rows.length;
594
+ }
595
+ await emit(opts.events?.restored, { id, took }, idOf(row, id));
596
+ return { id, took };
597
+ }
598
+ async function finalDelete(row, id, caller) {
599
+ const took = {};
600
+ const batch = row.trash_batch;
601
+ for (const child of children) {
602
+ const rows = batch == null ? [] : await listAll(child.repo, { [child.column]: id, trash_batch: batch });
603
+ for (const r of rows) await child.repo.delete(String(r.id));
604
+ took[child.name] = rows.length;
605
+ }
606
+ if (opts.deleteRow) await opts.deleteRow(row, caller);
607
+ else await repo.delete(id);
608
+ return { id, took };
609
+ }
610
+ async function deleteForGood(id, caller) {
611
+ const row = await load(id);
612
+ if (!isTrashed(row)) throw refuse(409, "only a record in the trash can be deleted for good", "not_in_trash");
613
+ if (opts.canDeleteForGood && !opts.canDeleteForGood(caller)) {
614
+ throw refuse(403, "deleting for good needs its own permission", "not_permitted");
615
+ }
616
+ const blockers = await runCheck(opts.blockers, row, caller);
617
+ if (blockers.length) {
618
+ throw refuse(409, `cannot be deleted for good: ${blockers.map((b) => b.reason).join("; ")}`, "delete_blocked", {
619
+ blockers
620
+ });
621
+ }
622
+ return finalDelete(row, id, caller);
623
+ }
624
+ async function purge(caller, options = {}) {
625
+ let retentionDays;
626
+ try {
627
+ retentionDays = await readTrashRetention(caller, opts.retention);
628
+ } catch (err) {
629
+ return { skipped: true, reason: err instanceof Error ? err.message : String(err), purged: [], blocked: [] };
630
+ }
631
+ const cutoff = new Date(now().getTime() - retentionDays * 864e5).toISOString();
632
+ const max = options.max ?? 500;
633
+ const due = (await listAll(repo, { [TRASH_COLUMN]: { op: "lt", value: cutoff } })).slice(0, max);
634
+ const result = { skipped: false, retentionDays, cutoff, purged: [], blocked: [] };
635
+ for (const row of due) {
636
+ const id = String(row.id);
637
+ const blockers = await runCheck(opts.blockers, row, caller);
638
+ if (blockers.length) {
639
+ result.blocked.push({ id, blockers });
640
+ const reason = blockers.map((b) => b.reason).join("; ");
641
+ if (reasonColumn && row[reasonColumn] !== reason) {
642
+ try {
643
+ await repo.update(id, { [reasonColumn]: reason });
644
+ } catch {
645
+ }
646
+ }
647
+ continue;
648
+ }
649
+ try {
650
+ await finalDelete(row, id, caller);
651
+ result.purged.push(id);
652
+ } catch (err) {
653
+ result.blocked.push({
654
+ id,
655
+ blockers: [{ reason: `delete failed: ${err instanceof Error ? err.message : String(err)}`, code: "delete_failed" }]
656
+ });
657
+ }
658
+ }
659
+ await emit(
660
+ opts.events?.purged,
661
+ { retention_days: retentionDays, cutoff, purged: result.purged.length, blocked: result.blocked.length },
662
+ null
663
+ );
664
+ return result;
665
+ }
666
+ app.delete(`${base}/{${idParam}}`, async (c) => {
667
+ const id = c.params[idParam] ?? "";
668
+ const row = await load(id);
669
+ if (isTrashed(row)) return c.json({ deleted: true, ...await deleteForGood(id, c) });
670
+ return c.json({ trashed: true, ...await trash(id, c) });
671
+ });
672
+ app.post(`${base}/{${idParam}}/restore`, async (c) => {
673
+ return c.json({ restored: true, ...await restore(c.params[idParam] ?? "", c) });
674
+ });
675
+ return { trash, restore, deleteForGood, purge };
676
+ }
677
+ function createGatewayCounter(options = {}) {
678
+ const env = options.env ?? process.env;
679
+ const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(/\/+$/, "");
680
+ async function count(caller, path, where = {}) {
681
+ const f = options.fetchImpl ?? globalThis.fetch;
682
+ const qs = new URLSearchParams();
683
+ for (const [k, v] of Object.entries(where)) qs.set(k, String(v));
684
+ qs.set("limit", "1");
685
+ const headers = { Accept: "application/json" };
686
+ const tenant = (caller.tenant ?? "") || headerFrom(caller, "x-revenexx-tenant");
687
+ if (tenant) headers["X-Revenexx-Tenant"] = tenant;
688
+ const context = (caller.contextToken ?? "") || headerFrom(caller, "x-revenexx-context");
689
+ if (context) headers.Authorization = `Bearer ${context}`;
690
+ const appContext = headerFrom(caller, "x-revenexx-app-context");
691
+ if (appContext) headers["x-revenexx-app-context"] = appContext;
692
+ try {
693
+ const signal = AbortSignal.timeout?.(options.timeoutMs ?? 5e3);
694
+ const sep = path.includes("?") ? "&" : "?";
695
+ const res = await f(`${endpoint}${path}${sep}${qs.toString()}`, { headers, ...signal ? { signal } : {} });
696
+ if (!res.ok) return null;
697
+ const body = await res.json();
698
+ const total = body?.page?.total;
699
+ return typeof total === "number" && Number.isFinite(total) ? total : null;
700
+ } catch {
701
+ return null;
702
+ }
703
+ }
704
+ async function blocker(caller, check) {
705
+ const n = await count(caller, check.path, check.where);
706
+ if (n === null) return { reason: `${check.reason} \u2014 could not be checked`, code: "unverifiable" };
707
+ if (n === 0) return null;
708
+ return { reason: `${n} ${check.reason}`, count: n, code: "referenced" };
709
+ }
710
+ return { count, blocker };
711
+ }
455
712
  export {
456
713
  ACTOR_HEADERS,
714
+ AUDIT_SETTINGS_PATH,
457
715
  DEFAULT_GATEWAY_ENDPOINT,
458
716
  DEFAULT_SETTINGS_ERROR_TTL_MS,
459
717
  DEFAULT_SETTINGS_TIMEOUT_MS,
460
718
  DEFAULT_SETTINGS_TTL_MS,
719
+ DEFAULT_TRASH_RETENTION_DAYS,
461
720
  HttpError,
721
+ MARKET_HEADERS,
722
+ PURGE_REASON_COLUMN,
462
723
  RESERVED_LIST_QUERY_KEYS,
724
+ TRASH_COLUMN,
463
725
  actorFrom,
726
+ auditSettingsUrl,
464
727
  badRequest,
465
728
  conflict,
466
729
  createApp,
730
+ createGatewayCounter,
467
731
  createSettings,
468
732
  forbidden,
469
733
  isHttpError,
734
+ marketFrom,
470
735
  mountCrud,
471
- notFound
736
+ mountTrash,
737
+ notFound,
738
+ readTrashRetention,
739
+ refusalOf
472
740
  };
473
741
  //# sourceMappingURL=index.js.map