@revenexx/app-sdk 1.3.0 → 1.5.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.
@@ -32,6 +32,9 @@ var router_exports = {};
32
32
  __export(router_exports, {
33
33
  ACTOR_HEADERS: () => ACTOR_HEADERS,
34
34
  AUDIT_SETTINGS_PATH: () => AUDIT_SETTINGS_PATH,
35
+ BACKDATING_FIELD: () => BACKDATING_FIELD,
36
+ BACKDATING_INVALID: () => BACKDATING_INVALID,
37
+ BACKDATING_SETTING: () => BACKDATING_SETTING,
35
38
  DEFAULT_GATEWAY_ENDPOINT: () => DEFAULT_GATEWAY_ENDPOINT,
36
39
  DEFAULT_SETTINGS_ERROR_TTL_MS: () => DEFAULT_SETTINGS_ERROR_TTL_MS,
37
40
  DEFAULT_SETTINGS_TIMEOUT_MS: () => DEFAULT_SETTINGS_TIMEOUT_MS,
@@ -39,12 +42,17 @@ __export(router_exports, {
39
42
  DEFAULT_TRASH_RETENTION_DAYS: () => DEFAULT_TRASH_RETENTION_DAYS,
40
43
  HttpError: () => HttpError,
41
44
  MARKET_HEADERS: () => MARKET_HEADERS,
45
+ MAX_MONTHS_BACK: () => MAX_MONTHS_BACK,
42
46
  PURGE_REASON_COLUMN: () => PURGE_REASON_COLUMN,
43
47
  RESERVED_LIST_QUERY_KEYS: () => RESERVED_LIST_QUERY_KEYS,
44
48
  TRASH_COLUMN: () => TRASH_COLUMN,
45
49
  actorFrom: () => actorFrom,
46
50
  auditSettingsUrl: () => auditSettingsUrl,
51
+ backdated: () => backdated,
52
+ backdatingAllowed: () => backdatingAllowed,
53
+ backdatingDb: () => backdatingDb,
47
54
  badRequest: () => badRequest,
55
+ clock: () => clock,
48
56
  conflict: () => conflict,
49
57
  createApp: () => createApp,
50
58
  createGatewayCounter: () => createGatewayCounter,
@@ -55,8 +63,11 @@ __export(router_exports, {
55
63
  mountCrud: () => mountCrud,
56
64
  mountTrash: () => mountTrash,
57
65
  notFound: () => notFound,
66
+ now: () => now,
67
+ parseBackdate: () => parseBackdate,
58
68
  readTrashRetention: () => readTrashRetention,
59
- refusalOf: () => refusalOf
69
+ refusalOf: () => refusalOf,
70
+ runAt: () => runAt
60
71
  });
61
72
  module.exports = __toCommonJS(router_exports);
62
73
 
@@ -153,6 +164,9 @@ var DEFAULT_GATEWAY_ENDPOINT = "https://api.revenexx.com";
153
164
  var DEFAULT_SETTINGS_TTL_MS = 6e4;
154
165
  var DEFAULT_SETTINGS_ERROR_TTL_MS = 5e3;
155
166
  var DEFAULT_SETTINGS_TIMEOUT_MS = 2e3;
167
+ function stringList(value) {
168
+ return Array.isArray(value) ? value.filter((k) => typeof k === "string") : [];
169
+ }
156
170
  function headerOf(source, name) {
157
171
  if (!source) return "";
158
172
  if (typeof source.header === "function") {
@@ -206,6 +220,7 @@ function createSettings(options = {}) {
206
220
  market,
207
221
  settings: mergeSettings(defaults, void 0),
208
222
  masked: [],
223
+ stored: [],
209
224
  resolved: false,
210
225
  error
211
226
  });
@@ -239,10 +254,81 @@ function createSettings(options = {}) {
239
254
  tenant,
240
255
  market,
241
256
  settings: mergeSettings(defaults, body.settings),
242
- masked: Array.isArray(body.masked) ? body.masked.filter((k) => typeof k === "string") : [],
257
+ masked: stringList(body.masked),
258
+ stored: stringList(body.stored),
243
259
  resolved: true
244
260
  };
245
261
  }
262
+ const forgetTenant = (tenant, app) => {
263
+ const prefix = `${tenant}\0${app}\0`;
264
+ for (const key of [...cache.keys()]) if (key.startsWith(prefix)) cache.delete(key);
265
+ for (const key of [...lastGood.keys()]) if (key.startsWith(prefix)) lastGood.delete(key);
266
+ };
267
+ async function set(source, values, writeOptions = {}) {
268
+ const app = appName();
269
+ const tenant = (source?.tenant ?? "") || headerOf(source, "x-revenexx-tenant");
270
+ const refused = (status, error) => ({
271
+ ok: false,
272
+ status,
273
+ written: [],
274
+ kept: [],
275
+ ignored: [],
276
+ error
277
+ });
278
+ if (!app) return refused(0, "no app name (pass `app` or set REVENEXX_APP_NAME)");
279
+ if (!tenant) return refused(0, "no tenant on the request");
280
+ const appContext = headerOf(source, "x-revenexx-app-context");
281
+ if (!appContext) {
282
+ return refused(0, "no app context on the request \u2014 settings are written from an HTTP route, not an event or schedule run");
283
+ }
284
+ if (!values || typeof values !== "object" || Array.isArray(values)) return refused(0, "values must be an object");
285
+ const f = options.fetchImpl ?? globalThis.fetch;
286
+ if (typeof f !== "function") return refused(0, "settings: no fetch available (Node >=18 or pass fetchImpl)");
287
+ const token = (source?.contextToken ?? "") || headerOf(source, "x-revenexx-context");
288
+ const headers = {
289
+ Accept: "application/json",
290
+ "Content-Type": "application/json",
291
+ "X-Revenexx-Tenant": tenant,
292
+ "X-Revenexx-App-Context": appContext
293
+ };
294
+ if (token) headers.Authorization = `Bearer ${token}`;
295
+ try {
296
+ const signal = timeoutSignal(timeoutMs);
297
+ const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}`, {
298
+ method: "PATCH",
299
+ headers,
300
+ body: JSON.stringify({ data: values, if_absent: writeOptions.ifAbsent === true }),
301
+ ...signal ? { signal } : {}
302
+ });
303
+ const text = await res.text();
304
+ let body = {};
305
+ try {
306
+ body = text ? JSON.parse(text) : {};
307
+ } catch {
308
+ body = {};
309
+ }
310
+ if (!res.ok) {
311
+ const reason = typeof body.error === "string" ? body.error : typeof body.message === "string" ? body.message : "";
312
+ const err = new Error(`settings: write ${res.status} for ${app}${reason ? ` \u2014 ${reason}` : ""}`);
313
+ err.status = res.status;
314
+ report(err, { app, tenant, market: null });
315
+ return refused(res.status, err.message);
316
+ }
317
+ const result = {
318
+ ok: true,
319
+ status: res.status,
320
+ written: stringList(body.written),
321
+ kept: stringList(body.kept),
322
+ ignored: stringList(body.ignored)
323
+ };
324
+ if (result.written.length > 0) forgetTenant(tenant, app);
325
+ return result;
326
+ } catch (err) {
327
+ const error = err instanceof Error ? err : new Error(String(err));
328
+ report(error, { app, tenant, market: null });
329
+ return refused(0, error.message);
330
+ }
331
+ }
246
332
  async function load(source, readOptions = {}) {
247
333
  const app = appName();
248
334
  const tenant = (source?.tenant ?? "") || headerOf(source, "x-revenexx-tenant");
@@ -250,11 +336,11 @@ function createSettings(options = {}) {
250
336
  if (!app) return fallback("", tenant, market, "no app name (pass `app` or set REVENEXX_APP_NAME)");
251
337
  if (!tenant) return fallback(app, "", market, "no tenant on the request");
252
338
  const key = `${tenant}\0${app}\0${market ?? ""}`;
253
- const now = Date.now();
339
+ const now2 = Date.now();
254
340
  const hit = cache.get(key);
255
- if (hit && now - hit.at < hit.ttl) return hit.promise;
341
+ if (hit && now2 - hit.at < hit.ttl) return hit.promise;
256
342
  const token = (source?.contextToken ?? "") || headerOf(source, "x-revenexx-context");
257
- const entry = { at: now, ttl: ttlMs, promise: void 0 };
343
+ const entry = { at: now2, ttl: ttlMs, promise: void 0 };
258
344
  entry.promise = request(app, tenant, token, market).then((snapshot) => {
259
345
  lastGood.set(key, snapshot);
260
346
  return snapshot;
@@ -272,6 +358,7 @@ function createSettings(options = {}) {
272
358
  }
273
359
  return {
274
360
  load,
361
+ set,
275
362
  async get(source, readOptions) {
276
363
  return (await load(source, readOptions)).settings;
277
364
  },
@@ -282,6 +369,9 @@ function createSettings(options = {}) {
282
369
  };
283
370
  }
284
371
 
372
+ // src/backdating.ts
373
+ var import_node_async_hooks = require("async_hooks");
374
+
285
375
  // src/errors.ts
286
376
  var HttpError = class extends Error {
287
377
  status;
@@ -345,6 +435,125 @@ function refusalOf(err) {
345
435
  };
346
436
  }
347
437
 
438
+ // src/backdating.ts
439
+ var MAX_MONTHS_BACK = 24;
440
+ var BACKDATING_SETTING = "allow_backdating";
441
+ var BACKDATING_FIELD = "at";
442
+ var BACKDATING_INVALID = "backdating_invalid";
443
+ var BACKDATING_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
444
+ var STORE_KEY = /* @__PURE__ */ Symbol.for("@revenexx/app-sdk/backdating-clock");
445
+ function clockStorage() {
446
+ const g = globalThis;
447
+ let storage = g[STORE_KEY];
448
+ if (!storage) {
449
+ storage = new import_node_async_hooks.AsyncLocalStorage();
450
+ g[STORE_KEY] = storage;
451
+ }
452
+ return storage;
453
+ }
454
+ var CLOCK = clockStorage();
455
+ var now = () => CLOCK.getStore()?.at ?? (/* @__PURE__ */ new Date()).toISOString();
456
+ var clock = () => new Date(now());
457
+ var backdated = () => Boolean(CLOCK.getStore()?.at);
458
+ function runAt(at, fn) {
459
+ return at ? CLOCK.run({ at }, fn) : fn();
460
+ }
461
+ var ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})$/;
462
+ var invalid = (field, message) => new HttpError(400, `'${field}' ${message}`, { field }, { code: BACKDATING_INVALID });
463
+ function parseBackdate(field, value, reference = /* @__PURE__ */ new Date()) {
464
+ const text = typeof value === "string" ? value.trim() : "";
465
+ if (!ISO_DATE_TIME.test(text)) throw invalid(field, "must be an ISO 8601 date-time with a time zone");
466
+ const at = new Date(text);
467
+ if (Number.isNaN(at.getTime())) throw invalid(field, "must be an ISO 8601 date-time with a time zone");
468
+ if (at.getTime() > reference.getTime()) throw invalid(field, "must not be in the future");
469
+ const earliest = new Date(reference.getTime());
470
+ earliest.setUTCMonth(earliest.getUTCMonth() - MAX_MONTHS_BACK);
471
+ if (at.getTime() < earliest.getTime()) {
472
+ throw invalid(field, `must not be more than ${MAX_MONTHS_BACK} months back`);
473
+ }
474
+ return at.toISOString();
475
+ }
476
+ function tokenTenant(token) {
477
+ const parts = typeof token === "string" ? token.split(".") : [];
478
+ if (parts.length < 2) return "";
479
+ try {
480
+ const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
481
+ const claims = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
482
+ return typeof claims?.tenant_id === "string" ? claims.tenant_id.trim() : "";
483
+ } catch {
484
+ return "";
485
+ }
486
+ }
487
+ function settingAllowsBackdating(value) {
488
+ return value === true || typeof value === "string" && value.trim().toLowerCase() === "true";
489
+ }
490
+ async function backdatingAllowed(c) {
491
+ const read = (name) => typeof c?.header === "function" ? String(c.header(name) ?? "").trim() : "";
492
+ const header = read("x-revenexx-tenant");
493
+ const claimed = tokenTenant(c?.contextToken || read("x-revenexx-context"));
494
+ if (!header || header !== claimed) return false;
495
+ if (typeof c?.settings !== "function") return false;
496
+ try {
497
+ const settings = await c.settings();
498
+ return settingAllowsBackdating(settings?.[BACKDATING_SETTING]);
499
+ } catch {
500
+ return false;
501
+ }
502
+ }
503
+ var present = (value) => value !== void 0 && value !== null && value !== "";
504
+ async function requestedMoment(c, fields) {
505
+ const body = c?.body;
506
+ if (!body || typeof body !== "object") return null;
507
+ const field = fields.find((f) => present(body[f]));
508
+ if (field === void 0) return null;
509
+ if (!await backdatingAllowed(c)) return null;
510
+ return parseBackdate(field, body[field]);
511
+ }
512
+ function backdatingFields(option, method, template) {
513
+ if (!option) return null;
514
+ const opts = option === true ? {} : option;
515
+ const key = `${method.toUpperCase()} ${template}`;
516
+ if (opts.exclude?.includes(key)) return null;
517
+ const named = opts.routes?.[key];
518
+ if (named) return named.includes(BACKDATING_FIELD) ? [...named] : [...named, BACKDATING_FIELD];
519
+ return BACKDATING_METHODS.includes(method.toUpperCase()) ? [BACKDATING_FIELD] : null;
520
+ }
521
+ function backdatingDb(db, entities) {
522
+ const wrapped = /* @__PURE__ */ new Map();
523
+ return new Proxy(db, {
524
+ get(target, prop, receiver) {
525
+ const value = Reflect.get(target, prop, receiver);
526
+ if (typeof prop !== "string") return value;
527
+ const columns = entities?.[prop]?.columns;
528
+ if (!columns || !("created_at" in columns) || !value || typeof value !== "object") return value;
529
+ const repo = value;
530
+ if (typeof repo.create !== "function") return value;
531
+ if (!wrapped.has(prop)) {
532
+ wrapped.set(
533
+ prop,
534
+ new Proxy(repo, {
535
+ get(r, key, rr) {
536
+ const member = Reflect.get(r, key, rr);
537
+ if (key !== "create" || typeof member !== "function") return member;
538
+ return (data, ...rest) => {
539
+ if (!backdated() || !data || typeof data !== "object" || Array.isArray(data)) {
540
+ return member.call(r, data, ...rest);
541
+ }
542
+ const at = now();
543
+ const row = { ...data };
544
+ if (row.created_at === void 0) row.created_at = at;
545
+ if ("updated_at" in columns && row.updated_at === void 0) row.updated_at = at;
546
+ return member.call(r, row, ...rest);
547
+ };
548
+ }
549
+ })
550
+ );
551
+ }
552
+ return wrapped.get(prop);
553
+ }
554
+ });
555
+ }
556
+
348
557
  // src/router/router.ts
349
558
  var splitPath = (path) => path.split("/").filter(Boolean);
350
559
  function compileTemplate(template) {
@@ -429,6 +638,7 @@ var headerGetter = {
429
638
  function createApp(options = {}) {
430
639
  const routes = [];
431
640
  const health = options.health !== false;
641
+ const strip = typeof options.backdating === "object" && options.backdating.strip === true;
432
642
  const settings = options.settings && isSettingsReader(options.settings) ? options.settings : createSettings({ app: options.name, ...options.settings ?? {} });
433
643
  const app = {
434
644
  settings,
@@ -444,7 +654,8 @@ function createApp(options = {}) {
444
654
  template,
445
655
  segments,
446
656
  literals: segments.filter((s) => s.lit !== void 0).length,
447
- handler
657
+ handler,
658
+ backdating: backdatingFields(options.backdating, method, template)
448
659
  });
449
660
  routes.sort((a, b) => b.literals - a.literals);
450
661
  return app;
@@ -488,12 +699,12 @@ function createApp(options = {}) {
488
699
  const reqSegs = splitPath(path);
489
700
  let matched = null;
490
701
  let pathExists = false;
491
- for (const route of routes) {
492
- const params = matchSegments(route.segments, reqSegs);
702
+ for (const route2 of routes) {
703
+ const params = matchSegments(route2.segments, reqSegs);
493
704
  if (!params) continue;
494
705
  pathExists = true;
495
- if (route.method === method) {
496
- matched = { route, params };
706
+ if (route2.method === method) {
707
+ matched = { route: route2, params };
497
708
  break;
498
709
  }
499
710
  }
@@ -532,9 +743,24 @@ function createApp(options = {}) {
532
743
  // The market rides on the request, so a market-scoped setting
533
744
  // resolves for the market this call is for — no argument needed.
534
745
  settings: (readOptions) => settings.get(c, readOptions),
535
- settingsSnapshot: (readOptions) => settings.load(c, readOptions)
746
+ settingsSnapshot: (readOptions) => settings.load(c, readOptions),
747
+ setSettings: (values, writeOptions) => settings.set(c, values, writeOptions),
748
+ now,
749
+ clock
536
750
  };
537
- return await matched.route.handler(c);
751
+ const fields = matched.route.backdating;
752
+ if (!fields) return await matched.route.handler(c);
753
+ const at = await requestedMoment(c, fields);
754
+ if (at) {
755
+ span.setAttribute("revenexx.backdated_at", at);
756
+ if (strip) {
757
+ const body = { ...c.body };
758
+ for (const field of fields) delete body[field];
759
+ c.body = body;
760
+ }
761
+ }
762
+ const route = matched.route;
763
+ return await runAt(at, () => route.handler(c));
538
764
  } catch (err) {
539
765
  if (isHttpError(err)) {
540
766
  span.setAttribute("http.response.status_code", err.status);
@@ -780,7 +1006,7 @@ function mountTrash(app, repo, opts) {
780
1006
  const base = opts.path.replace(/\/+$/, "");
781
1007
  const idParam = opts.idParam ?? "id";
782
1008
  const children = opts.children ?? [];
783
- const now = opts.now ?? (() => /* @__PURE__ */ new Date());
1009
+ const now2 = opts.now ?? (() => /* @__PURE__ */ new Date());
784
1010
  const reasonColumn = opts.purgeReasonColumn === false ? null : opts.purgeReasonColumn ?? PURGE_REASON_COLUMN;
785
1011
  const load = async (id) => {
786
1012
  if (!id) throw refuse(400, `missing path parameter '${idParam}'`, "missing_parameter");
@@ -801,7 +1027,7 @@ function mountTrash(app, repo, opts) {
801
1027
  }
802
1028
  const batch = (0, import_node_crypto.randomUUID)();
803
1029
  const fields = {
804
- [TRASH_COLUMN]: now().toISOString(),
1030
+ [TRASH_COLUMN]: now2().toISOString(),
805
1031
  deleted_by: caller.actor?.email ?? caller.actor?.user ?? null,
806
1032
  deleted_by_id: caller.actor?.user ?? caller.actor?.contact ?? null,
807
1033
  trash_batch: batch
@@ -874,7 +1100,7 @@ function mountTrash(app, repo, opts) {
874
1100
  } catch (err) {
875
1101
  return { skipped: true, reason: err instanceof Error ? err.message : String(err), purged: [], blocked: [] };
876
1102
  }
877
- const cutoff = new Date(now().getTime() - retentionDays * 864e5).toISOString();
1103
+ const cutoff = new Date(now2().getTime() - retentionDays * 864e5).toISOString();
878
1104
  const max = options.max ?? 500;
879
1105
  const due = (await listAll(repo, { [TRASH_COLUMN]: { op: "lt", value: cutoff } })).slice(0, max);
880
1106
  const result = { skipped: false, retentionDays, cutoff, purged: [], blocked: [] };
@@ -959,6 +1185,9 @@ function createGatewayCounter(options = {}) {
959
1185
  0 && (module.exports = {
960
1186
  ACTOR_HEADERS,
961
1187
  AUDIT_SETTINGS_PATH,
1188
+ BACKDATING_FIELD,
1189
+ BACKDATING_INVALID,
1190
+ BACKDATING_SETTING,
962
1191
  DEFAULT_GATEWAY_ENDPOINT,
963
1192
  DEFAULT_SETTINGS_ERROR_TTL_MS,
964
1193
  DEFAULT_SETTINGS_TIMEOUT_MS,
@@ -966,12 +1195,17 @@ function createGatewayCounter(options = {}) {
966
1195
  DEFAULT_TRASH_RETENTION_DAYS,
967
1196
  HttpError,
968
1197
  MARKET_HEADERS,
1198
+ MAX_MONTHS_BACK,
969
1199
  PURGE_REASON_COLUMN,
970
1200
  RESERVED_LIST_QUERY_KEYS,
971
1201
  TRASH_COLUMN,
972
1202
  actorFrom,
973
1203
  auditSettingsUrl,
1204
+ backdated,
1205
+ backdatingAllowed,
1206
+ backdatingDb,
974
1207
  badRequest,
1208
+ clock,
975
1209
  conflict,
976
1210
  createApp,
977
1211
  createGatewayCounter,
@@ -982,7 +1216,10 @@ function createGatewayCounter(options = {}) {
982
1216
  mountCrud,
983
1217
  mountTrash,
984
1218
  notFound,
1219
+ now,
1220
+ parseBackdate,
985
1221
  readTrashRetention,
986
- refusalOf
1222
+ refusalOf,
1223
+ runAt
987
1224
  });
988
1225
  //# sourceMappingURL=index.cjs.map