@nymbalhq/platform 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.
Files changed (41) hide show
  1. package/dist/{chunk-QN56IB4G.js → chunk-NNDIAIT6.js} +187 -5
  2. package/dist/chunk-NNDIAIT6.js.map +1 -0
  3. package/dist/{chunk-2PLYK5RU.js → chunk-TRLERRUI.js} +3559 -509
  4. package/dist/chunk-TRLERRUI.js.map +1 -0
  5. package/dist/db/schema/index.d.ts +5276 -3224
  6. package/dist/db/schema/index.js +1 -1
  7. package/dist/index.d.ts +428 -81
  8. package/dist/index.js +1200 -2254
  9. package/dist/index.js.map +1 -1
  10. package/dist/register-SBGUI2L5.js +8 -0
  11. package/migrations/postgres/0013_order_access_keys.sql +11 -0
  12. package/migrations/postgres/0014_alert_subscriptions.sql +22 -0
  13. package/migrations/postgres/0015_events_retry_at.sql +1 -0
  14. package/migrations/postgres/0016_email_suppressions.sql +7 -0
  15. package/migrations/postgres/0017_order_shipments.sql +14 -0
  16. package/migrations/postgres/0018_order_key_expiry.sql +8 -0
  17. package/migrations/postgres/meta/0013_snapshot.json +2000 -0
  18. package/migrations/postgres/meta/0014_snapshot.json +2185 -0
  19. package/migrations/postgres/meta/0015_snapshot.json +2191 -0
  20. package/migrations/postgres/meta/0016_snapshot.json +2233 -0
  21. package/migrations/postgres/meta/0017_snapshot.json +2300 -0
  22. package/migrations/postgres/meta/0018_snapshot.json +2306 -0
  23. package/migrations/postgres/meta/_journal.json +42 -0
  24. package/migrations/sqlite/0013_order_access_keys.sql +11 -0
  25. package/migrations/sqlite/0014_alert_subscriptions.sql +22 -0
  26. package/migrations/sqlite/0015_events_retry_at.sql +1 -0
  27. package/migrations/sqlite/0016_email_suppressions.sql +7 -0
  28. package/migrations/sqlite/0017_order_shipments.sql +9 -0
  29. package/migrations/sqlite/0018_order_key_expiry.sql +25 -0
  30. package/migrations/sqlite/meta/0013_snapshot.json +1788 -0
  31. package/migrations/sqlite/meta/0014_snapshot.json +1931 -0
  32. package/migrations/sqlite/meta/0015_snapshot.json +1938 -0
  33. package/migrations/sqlite/meta/0016_snapshot.json +1981 -0
  34. package/migrations/sqlite/meta/0017_snapshot.json +2041 -0
  35. package/migrations/sqlite/meta/0018_snapshot.json +2048 -0
  36. package/migrations/sqlite/meta/_journal.json +42 -0
  37. package/package.json +17 -47
  38. package/dist/chunk-2PLYK5RU.js.map +0 -1
  39. package/dist/chunk-QN56IB4G.js.map +0 -1
  40. package/dist/register-UUQ64HZP.js +0 -8
  41. /package/dist/{register-UUQ64HZP.js.map → register-SBGUI2L5.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,23 +1,44 @@
1
1
  import {
2
+ CATEGORIES,
2
3
  COMMERCE_SLOTS,
3
4
  CSRF_COOKIE,
4
5
  CSRF_HEADER,
5
- PROVIDER_PACKAGES,
6
+ CUSTOMER_PROFILES,
7
+ KEY_OF,
8
+ ORDERS,
9
+ ORDERS_BY_CUSTOMER,
10
+ PRODUCTS,
11
+ PRODUCTS_BY_CATEGORY,
6
12
  PROVIDER_REFUND_REASON,
7
13
  SECRETS_KEY_ENV,
8
14
  SECRETS_KEY_OLD_ENV,
9
15
  actorOf,
16
+ addSecret,
10
17
  afterCommit,
11
18
  appendAuditEntry,
12
19
  audit,
13
20
  auditEntriesInOrder,
14
21
  auditedCommand,
15
22
  buildAdapters,
23
+ buildCategoryDoc,
24
+ buildCustomerProfile,
25
+ buildOrderDoc,
26
+ buildProductDoc,
27
+ buildSearchDoc,
16
28
  buildSecurityHeaders,
29
+ buildServices,
30
+ checkAdapterModule,
17
31
  checkInjectedAdapters,
18
32
  checkInjectedSlot,
33
+ createAlertService,
19
34
  createAuditEntryRepository,
35
+ createAuthService,
36
+ createCartService,
37
+ createCategoryService,
38
+ createCheckoutService,
20
39
  createCommandStore,
40
+ createCustomerService,
41
+ createInventoryService,
21
42
  createMiddlewareSecurityAdapter,
22
43
  createNativeAnalyticsAdapter,
23
44
  createNativeEmailAdapter,
@@ -26,21 +47,27 @@ import {
26
47
  createNativeShippingAdapter,
27
48
  createNativeStubPaymentsAdapter,
28
49
  createNativeTaxAdapter,
50
+ createOrderService,
51
+ createProductService,
52
+ createRecentlyViewedService,
29
53
  createRefundService,
54
+ createSearchService,
30
55
  createSettingsRepository,
31
56
  currentActor,
32
57
  currentCorrelationId,
33
58
  declaredSettings,
34
59
  decrypt,
60
+ emailDelivers,
35
61
  encodeSearchCursor,
36
62
  encrypt,
37
63
  fillFromSettings,
38
64
  findAppliedByKey,
39
65
  formatMoney,
40
- importProviderPackage,
41
- inOrderScope,
66
+ importAdapterModule,
42
67
  installLine,
68
+ isHooked,
43
69
  isMissingSettingsTable,
70
+ isNotConfigured,
44
71
  isValidCorrelationId,
45
72
  keyId,
46
73
  keyProblem,
@@ -48,20 +75,30 @@ import {
48
75
  listStoredSettings,
49
76
  loadBootSettings,
50
77
  loadProviderAdapter,
78
+ mintOrderKey,
79
+ missingPackage,
51
80
  nativeIndexDocuments,
81
+ newAlertToken,
52
82
  newCorrelationId,
53
- noopInitialize,
54
- okHealth,
83
+ normaliseEmail,
55
84
  orderPayment,
85
+ orderWrites,
56
86
  outsideActor,
57
87
  outsideCommand,
58
88
  outsideCorrelation,
89
+ parseDurationToMs,
59
90
  postgresDb,
91
+ productByCategoryKey,
92
+ productWrites,
60
93
  rawClients,
61
94
  readSecretsKey,
95
+ recentlyViewed,
62
96
  refreshRefunded,
63
97
  registerAdminStaticRoute,
98
+ registerAlertRoutes,
64
99
  registerAllRoutes,
100
+ registerRecentlyViewedProjection,
101
+ resolveChoice,
65
102
  resolvePaymentsAdapter,
66
103
  resolveSecurityAdapter,
67
104
  routeSchemas,
@@ -69,31 +106,40 @@ import {
69
106
  runWithCorrelation,
70
107
  scrub,
71
108
  scrubbingLogger,
109
+ securityChoice,
72
110
  settingAad,
73
111
  settingValues,
74
112
  settlementOf,
75
113
  slotBuilders,
76
114
  sqliteDb,
77
115
  sqliteFile,
78
- toCustomerSnapshot
79
- } from "./chunk-2PLYK5RU.js";
116
+ subscribeDerived
117
+ } from "./chunk-TRLERRUI.js";
80
118
  import {
119
+ alertSubscriptions,
120
+ alertSubscriptions2,
81
121
  carts,
82
122
  carts2,
83
123
  categories,
84
124
  categories2,
85
125
  customers,
86
126
  customers2,
127
+ emailSuppressions,
128
+ emailSuppressions2,
87
129
  events,
88
130
  events2,
89
131
  inventoryReservations,
90
132
  inventoryReservations2,
133
+ orderAccessKeys,
134
+ orderAccessKeys2,
91
135
  orderHistory,
92
136
  orderHistory2,
93
137
  orderRefunds,
94
138
  orderRefunds2,
95
139
  orderSequences,
96
140
  orderSequences2,
141
+ orderShipments,
142
+ orderShipments2,
97
143
  orders,
98
144
  orders2,
99
145
  postgres_exports,
@@ -112,7 +158,7 @@ import {
112
158
  stockAdjustments2,
113
159
  variants,
114
160
  variants2
115
- } from "./chunk-QN56IB4G.js";
161
+ } from "./chunk-NNDIAIT6.js";
116
162
 
117
163
  // src/platform.ts
118
164
  import { join as join2 } from "path";
@@ -243,7 +289,7 @@ var InMemoryDocumentStore = class {
243
289
 
244
290
  // src/event-bus/in-process.ts
245
291
  import { v7 as uuidv7 } from "uuid";
246
- import { ValidationError } from "@nymbalhq/types";
292
+ import { handlerFailedError, ValidationError } from "@nymbalhq/types";
247
293
  var InProcessEventBus = class {
248
294
  #registrations = /* @__PURE__ */ new Map();
249
295
  #logger;
@@ -258,35 +304,44 @@ var InProcessEventBus = class {
258
304
  return { status: "healthy" };
259
305
  }
260
306
  async publish(event) {
261
- await this.#deliver(event, () => true);
307
+ const failed = await this.#deliver(event, () => true);
308
+ if (failed.length > 0) throw handlerFailedError(event, failed);
262
309
  }
263
310
  async publishBatch(events3) {
311
+ let first;
264
312
  for (const event of events3) {
265
- await this.publish(event);
313
+ const failed = await this.#deliver(event, () => true);
314
+ if (failed.length > 0) first ??= handlerFailedError(event, failed);
266
315
  }
316
+ if (first !== void 0) throw first;
267
317
  }
268
318
  async replay(events3) {
269
319
  for (const event of events3) {
270
320
  await this.#deliver(event, (r) => r.config?.derived === true);
271
321
  }
272
322
  }
323
+ /** Runs every matching handler to the end, each error logged; returns the named subscriptions that threw. */
273
324
  async #deliver(event, eligible) {
274
325
  this.#validate(event);
275
326
  const matches = Array.from(this.#registrations.values()).filter(
276
327
  (r) => eligible(r) && r.regexes.some((re) => re.test(event.type))
277
328
  );
278
- await Promise.all(
329
+ const outcomes = await Promise.all(
279
330
  matches.map(async (r) => {
280
331
  try {
281
332
  await r.handler(event);
333
+ return null;
282
334
  } catch (err) {
335
+ const subscription = r.config?.name;
283
336
  this.#logger?.error(
284
- { err, subscriptionId: r.id, eventType: event.type, eventId: event.id },
337
+ { err, subscriptionId: r.id, subscription, eventType: event.type, eventId: event.id },
285
338
  "Event handler failed"
286
339
  );
340
+ return subscription === void 0 ? null : { subscription, message: messageOf(err) };
287
341
  }
288
342
  })
289
343
  );
344
+ return outcomes.filter((o) => o !== null);
290
345
  }
291
346
  async subscribe(eventPattern, handler, config) {
292
347
  const patterns = Array.isArray(eventPattern) ? eventPattern : [eventPattern];
@@ -322,6 +377,9 @@ var InProcessEventBus = class {
322
377
  }
323
378
  }
324
379
  };
380
+ function messageOf(err) {
381
+ return err instanceof Error ? err.message : String(err);
382
+ }
325
383
  function compilePattern(pattern) {
326
384
  const escaped = pattern.replace(/[.+?^${}()|[\]\\*]/g, "\\$&").replace(/\\\*/g, ".*");
327
385
  return new RegExp(`^${escaped}$`);
@@ -451,22 +509,22 @@ function s3Connection(config, env) {
451
509
  ...publicUrl !== void 0 && { publicUrl }
452
510
  };
453
511
  }
454
- async function loadPrimitive(slot, provider, config, logger, env) {
455
- const instance = await loadProviderAdapter(slot, provider, {
512
+ async function loadPrimitive(slot, choice, config, logger, env) {
513
+ const instance = await loadProviderAdapter(slot, choice, {
456
514
  config,
457
515
  logger: logger.child({ primitive: slot }),
458
516
  env
459
517
  });
460
518
  if (instance === void 0) {
461
- throw new ConfigError(`infrastructure.${slot} '${provider}' has no implementation`, {
462
- context: { slot, provider }
519
+ throw new ConfigError(`infrastructure.${slot} '${choice.provider}' has no implementation`, {
520
+ context: { slot, provider: choice.provider }
463
521
  });
464
522
  }
465
523
  return instance;
466
524
  }
467
525
  async function buildDocumentStore(config, options, logger, env) {
468
526
  const choice = config.infrastructure.documentStore;
469
- switch (choice) {
527
+ switch (choice.provider) {
470
528
  case "in-memory":
471
529
  return new InMemoryDocumentStore();
472
530
  case "redis": {
@@ -489,15 +547,13 @@ async function buildDocumentStore(config, options, logger, env) {
489
547
  env
490
548
  );
491
549
  }
492
- default: {
493
- const exhaustive = choice;
494
- throw new ConfigError(`Unknown documentStore: ${String(exhaustive)}`);
495
- }
550
+ default:
551
+ return loadPrimitive("documentStore", choice, choice.config ?? {}, logger, env);
496
552
  }
497
553
  }
498
554
  async function buildEventBus(config, logger, env) {
499
555
  const choice = config.infrastructure.eventBus;
500
- switch (choice) {
556
+ switch (choice.provider) {
501
557
  case "in-process":
502
558
  return new InProcessEventBus({ logger });
503
559
  case "redis-streams":
@@ -508,15 +564,13 @@ async function buildEventBus(config, logger, env) {
508
564
  logger,
509
565
  env
510
566
  );
511
- default: {
512
- const exhaustive = choice;
513
- throw new ConfigError(`Unknown eventBus: ${String(exhaustive)}`);
514
- }
567
+ default:
568
+ return loadPrimitive("eventBus", choice, choice.config ?? {}, logger, env);
515
569
  }
516
570
  }
517
571
  async function buildMedia(config, options, logger, env) {
518
572
  const choice = config.infrastructure.media;
519
- switch (choice) {
573
+ switch (choice.provider) {
520
574
  case "local-fs":
521
575
  return createLocalFsMediaStorage({
522
576
  root: options.mediaRoot ?? join2(process.cwd(), "public", "imported-media"),
@@ -524,22 +578,21 @@ async function buildMedia(config, options, logger, env) {
524
578
  });
525
579
  case "s3":
526
580
  return loadPrimitive("media", choice, s3Connection(config, env), logger, env);
527
- default: {
528
- const exhaustive = choice;
529
- throw new ConfigError(`Unknown media: ${String(exhaustive)}`);
530
- }
581
+ default:
582
+ return loadPrimitive("media", choice, choice.config ?? {}, logger, env);
531
583
  }
532
584
  }
533
585
  async function resolvePrimitives(config, options = {}) {
534
586
  const env = options.env ?? process.env;
535
587
  const logger = options.logger ?? createLogger({ base: { store: config.store.name } });
536
- if (config.infrastructure.media === "s3") s3Connection(config, env);
537
- if (config.infrastructure.documentStore === "redis") redisConnection(config, env, "documentStore");
538
- if (config.infrastructure.eventBus === "redis-streams") redisConnection(config, env, "eventBus");
588
+ const { documentStore: store, eventBus: bus, media: storage } = config.infrastructure;
589
+ if (storage.provider === "s3") s3Connection(config, env);
590
+ if (store.provider === "redis") redisConnection(config, env, "documentStore");
591
+ if (bus.provider === "redis-streams") redisConnection(config, env, "eventBus");
539
592
  const media = await buildMedia(config, options, logger, env);
540
593
  const documentStore = await buildDocumentStore(config, options, logger, env);
541
594
  try {
542
- if (config.infrastructure.documentStore === "postgres-jsonb") await documentStore.initialize?.();
595
+ if (store.provider === "postgres-jsonb") await documentStore.initialize?.();
543
596
  const eventBus = await buildEventBus(config, logger, env);
544
597
  return { documentStore, eventBus, media };
545
598
  } catch (error) {
@@ -1790,33 +1843,79 @@ function createOrderRefundRepository(store) {
1790
1843
  }
1791
1844
 
1792
1845
  // src/repositories/order-sequence.ts
1793
- import { eq as eq11, sql as sql3 } from "drizzle-orm";
1846
+ import { sql as sql3 } from "drizzle-orm";
1794
1847
  function createOrderSequenceRepository(store) {
1795
1848
  return {
1796
1849
  store,
1850
+ // One upsert: on a fresh store a read finds no row to lock, so concurrent first allocations would each insert it.
1851
+ // The value handed out is the one the row held before this call (startFrom on the first).
1797
1852
  async nextSequence(tx, startFrom = 1e3) {
1798
1853
  if (tx.kind === "sqlite") {
1799
- const client2 = sqliteDb(tx);
1800
- const row2 = client2.select().from(orderSequences).where(eq11(orderSequences.id, 1)).get();
1801
- if (!row2) {
1802
- const next = startFrom + 1;
1803
- client2.insert(orderSequences).values({ id: 1, nextValue: next }).run();
1804
- return startFrom;
1805
- }
1806
- const current2 = row2.nextValue;
1807
- client2.update(orderSequences).set({ nextValue: current2 + 1 }).where(eq11(orderSequences.id, 1)).run();
1808
- return current2;
1809
- }
1810
- const client = postgresDb(tx);
1811
- const [row] = await client.select().from(orderSequences2).where(eq11(orderSequences2.id, 1)).for("update");
1812
- if (!row) {
1813
- const next = startFrom + 1;
1814
- await client.insert(orderSequences2).values({ id: 1, nextValue: next });
1815
- return startFrom;
1816
- }
1817
- const current = row.nextValue;
1818
- await client.update(orderSequences2).set({ nextValue: sql3`${orderSequences2.nextValue} + 1` }).where(eq11(orderSequences2.id, 1));
1819
- return current;
1854
+ const row2 = sqliteDb(tx).insert(orderSequences).values({ id: 1, nextValue: startFrom + 1 }).onConflictDoUpdate({
1855
+ target: orderSequences.id,
1856
+ set: { nextValue: sql3`${orderSequences.nextValue} + 1` }
1857
+ }).returning({ nextValue: orderSequences.nextValue }).get();
1858
+ return row2.nextValue - 1;
1859
+ }
1860
+ const [row] = await postgresDb(tx).insert(orderSequences2).values({ id: 1, nextValue: startFrom + 1 }).onConflictDoUpdate({
1861
+ target: orderSequences2.id,
1862
+ set: { nextValue: sql3`${orderSequences2.nextValue} + 1` }
1863
+ }).returning({ nextValue: orderSequences2.nextValue });
1864
+ return row.nextValue - 1;
1865
+ }
1866
+ };
1867
+ }
1868
+
1869
+ // src/repositories/order-access-key.ts
1870
+ import { and as and6, asc as asc8, eq as eq11, inArray as inArray2 } from "drizzle-orm";
1871
+ function createOrderAccessKeyRepository(store) {
1872
+ return {
1873
+ store,
1874
+ async insert(tx, k) {
1875
+ const row = { id: k.id, orderId: k.orderId, keyHash: k.keyHash, purpose: k.purpose };
1876
+ if (tx.kind === "sqlite") {
1877
+ sqliteDb(tx).insert(orderAccessKeys).values({
1878
+ ...row,
1879
+ createdAt: k.createdAt.toISOString(),
1880
+ expiresAt: k.expiresAt.toISOString()
1881
+ }).run();
1882
+ return;
1883
+ }
1884
+ await postgresDb(tx).insert(orderAccessKeys2).values({ ...row, createdAt: k.createdAt, expiresAt: k.expiresAt });
1885
+ },
1886
+ async opens(tx, orderId, keyHash, now) {
1887
+ let expiresAt;
1888
+ if (tx.kind === "sqlite") {
1889
+ const t = orderAccessKeys;
1890
+ const row = sqliteDb(tx).select({ expiresAt: t.expiresAt }).from(t).where(and6(eq11(t.orderId, orderId), eq11(t.keyHash, keyHash))).get();
1891
+ if (row !== void 0) expiresAt = Date.parse(row.expiresAt);
1892
+ } else {
1893
+ const t = orderAccessKeys2;
1894
+ const rows = await postgresDb(tx).select({ expiresAt: t.expiresAt }).from(t).where(and6(eq11(t.orderId, orderId), eq11(t.keyHash, keyHash))).limit(1);
1895
+ if (rows[0] !== void 0) expiresAt = rows[0].expiresAt.getTime();
1896
+ }
1897
+ if (expiresAt === void 0) return "none";
1898
+ return now.getTime() < expiresAt ? "open" : "expired";
1899
+ },
1900
+ async keepNewest(tx, orderId, purpose, keep) {
1901
+ let ids;
1902
+ if (tx.kind === "sqlite") {
1903
+ const t2 = orderAccessKeys;
1904
+ ids = sqliteDb(tx).select({ id: t2.id }).from(t2).where(and6(eq11(t2.orderId, orderId), eq11(t2.purpose, purpose))).orderBy(asc8(t2.createdAt), asc8(t2.id)).all().map((r) => r.id);
1905
+ } else {
1906
+ const t2 = orderAccessKeys2;
1907
+ const rows = await postgresDb(tx).select({ id: t2.id }).from(t2).where(and6(eq11(t2.orderId, orderId), eq11(t2.purpose, purpose))).orderBy(asc8(t2.createdAt), asc8(t2.id));
1908
+ ids = rows.map((r) => r.id);
1909
+ }
1910
+ const stale = ids.slice(0, Math.max(0, ids.length - keep));
1911
+ if (stale.length === 0) return;
1912
+ if (tx.kind === "sqlite") {
1913
+ const t2 = orderAccessKeys;
1914
+ sqliteDb(tx).delete(t2).where(inArray2(t2.id, stale)).run();
1915
+ return;
1916
+ }
1917
+ const t = orderAccessKeys2;
1918
+ await postgresDb(tx).delete(t).where(inArray2(t.id, stale));
1820
1919
  }
1821
1920
  };
1822
1921
  }
@@ -1944,7 +2043,7 @@ function createStockAdjustmentRepository(store) {
1944
2043
  }
1945
2044
 
1946
2045
  // src/repositories/review.ts
1947
- import { and as and6, desc as desc3, eq as eq14, lt as lt3, or } from "drizzle-orm";
2046
+ import { and as and7, desc as desc3, eq as eq14, lt as lt3, or } from "drizzle-orm";
1948
2047
  function rowToReview(row) {
1949
2048
  return {
1950
2049
  id: String(row.id),
@@ -1978,9 +2077,9 @@ function createReviewRepository(store) {
1978
2077
  if (status) conds2.push(eq14(t2.moderationStatus, status));
1979
2078
  if (after) {
1980
2079
  const at = new Date(after.submittedAt).toISOString();
1981
- conds2.push(or(lt3(t2.submittedAt, at), and6(eq14(t2.submittedAt, at), lt3(t2.id, after.id))));
2080
+ conds2.push(or(lt3(t2.submittedAt, at), and7(eq14(t2.submittedAt, at), lt3(t2.id, after.id))));
1982
2081
  }
1983
- const rows2 = sqliteDb(tx).select().from(t2).where(and6(...conds2)).orderBy(desc3(t2.submittedAt), desc3(t2.id)).limit(limit).all();
2082
+ const rows2 = sqliteDb(tx).select().from(t2).where(and7(...conds2)).orderBy(desc3(t2.submittedAt), desc3(t2.id)).limit(limit).all();
1984
2083
  return rows2.map((r) => rowToReview(r));
1985
2084
  }
1986
2085
  const t = reviews2;
@@ -1988,9 +2087,9 @@ function createReviewRepository(store) {
1988
2087
  if (status) conds.push(eq14(t.moderationStatus, status));
1989
2088
  if (after) {
1990
2089
  const at = new Date(after.submittedAt);
1991
- conds.push(or(lt3(t.submittedAt, at), and6(eq14(t.submittedAt, at), lt3(t.id, after.id))));
2090
+ conds.push(or(lt3(t.submittedAt, at), and7(eq14(t.submittedAt, at), lt3(t.id, after.id))));
1992
2091
  }
1993
- const rows = await postgresDb(tx).select().from(t).where(and6(...conds)).orderBy(desc3(t.submittedAt), desc3(t.id)).limit(limit);
2092
+ const rows = await postgresDb(tx).select().from(t).where(and7(...conds)).orderBy(desc3(t.submittedAt), desc3(t.id)).limit(limit);
1994
2093
  return rows.map((r) => rowToReview(r));
1995
2094
  },
1996
2095
  async listByStatus(tx, status, limit = 100) {
@@ -2064,7 +2163,7 @@ function createReviewRepository(store) {
2064
2163
  }
2065
2164
 
2066
2165
  // src/repositories/processed-event.ts
2067
- import { and as and7, eq as eq15, lt as lt4 } from "drizzle-orm";
2166
+ import { and as and8, eq as eq15, lt as lt4 } from "drizzle-orm";
2068
2167
  function createProcessedEventRepository(store) {
2069
2168
  const s = processedEvents;
2070
2169
  const p = processedEvents2;
@@ -2072,10 +2171,10 @@ function createProcessedEventRepository(store) {
2072
2171
  store,
2073
2172
  async seen(tx, handlerName, eventId) {
2074
2173
  if (tx.kind === "sqlite") {
2075
- const row = sqliteDb(tx).select({ eventId: s.eventId }).from(s).where(and7(eq15(s.handlerName, handlerName), eq15(s.eventId, eventId))).get();
2174
+ const row = sqliteDb(tx).select({ eventId: s.eventId }).from(s).where(and8(eq15(s.handlerName, handlerName), eq15(s.eventId, eventId))).get();
2076
2175
  return row !== void 0;
2077
2176
  }
2078
- const rows = await postgresDb(tx).select({ eventId: p.eventId }).from(p).where(and7(eq15(p.handlerName, handlerName), eq15(p.eventId, eventId))).limit(1);
2177
+ const rows = await postgresDb(tx).select({ eventId: p.eventId }).from(p).where(and8(eq15(p.handlerName, handlerName), eq15(p.eventId, eventId))).limit(1);
2079
2178
  return rows.length > 0;
2080
2179
  },
2081
2180
  async markProcessed(tx, handlerName, eventId, at) {
@@ -2085,6 +2184,14 @@ function createProcessedEventRepository(store) {
2085
2184
  }
2086
2185
  await postgresDb(tx).insert(p).values({ handlerName, eventId, processedAt: at }).onConflictDoNothing();
2087
2186
  },
2187
+ async claim(tx, handlerName, eventId, at) {
2188
+ if (tx.kind === "sqlite") {
2189
+ const result2 = sqliteDb(tx).insert(s).values({ handlerName, eventId, processedAt: at.toISOString() }).onConflictDoNothing().run();
2190
+ return result2.changes > 0;
2191
+ }
2192
+ const result = await postgresDb(tx).insert(p).values({ handlerName, eventId, processedAt: at }).onConflictDoNothing();
2193
+ return (result.rowCount ?? 0) > 0;
2194
+ },
2088
2195
  async deleteBefore(tx, at) {
2089
2196
  if (tx.kind === "sqlite") {
2090
2197
  return sqliteDb(tx).delete(s).where(lt4(s.processedAt, at.toISOString())).run().changes;
@@ -2097,12 +2204,12 @@ function createProcessedEventRepository(store) {
2097
2204
 
2098
2205
  // src/repositories/event-log.ts
2099
2206
  import {
2100
- and as and8,
2101
- asc as asc8,
2207
+ and as and9,
2208
+ asc as asc9,
2102
2209
  eq as eq16,
2103
2210
  gt as gt5,
2104
2211
  gte as gte2,
2105
- inArray as inArray2,
2212
+ inArray as inArray3,
2106
2213
  isNotNull,
2107
2214
  isNull as isNull2,
2108
2215
  lt as lt5,
@@ -2112,6 +2219,7 @@ import {
2112
2219
  } from "drizzle-orm";
2113
2220
 
2114
2221
  // src/history/subject.ts
2222
+ import { EVT_PRODUCT_VIEWED } from "@nymbalhq/types";
2115
2223
  function text(value) {
2116
2224
  return typeof value === "string" ? value : void 0;
2117
2225
  }
@@ -2123,6 +2231,7 @@ function subjectOf(envelope) {
2123
2231
  const type = envelope.type;
2124
2232
  let subject;
2125
2233
  let id;
2234
+ if (type === EVT_PRODUCT_VIEWED) return null;
2126
2235
  if (type.startsWith("product.")) {
2127
2236
  subject = "product";
2128
2237
  id = nestedId(payload["product"]) ?? text(payload["productId"]);
@@ -2142,6 +2251,7 @@ function subjectOf(envelope) {
2142
2251
  // src/repositories/event-log.ts
2143
2252
  var APPEND_CHUNK = 100;
2144
2253
  var DELETE_CHUNK = 500;
2254
+ var APPEND_INTO = "INSERT INTO events (id, type, envelope, correlation_id, subject_type, subject_id, created_at) VALUES";
2145
2255
  var CATCH_UP_LIMIT = 1e4;
2146
2256
  function sqliteGlob(glob) {
2147
2257
  return glob.replace(/[[?]/g, (c) => `[${c}]`);
@@ -2207,83 +2317,120 @@ function createEventLogRepository(store) {
2207
2317
  }
2208
2318
  async function select(tx, where, limit) {
2209
2319
  if (tx.kind === "sqlite") {
2210
- return sqliteDb(tx).select().from(s).where(and8(...where.sqlite)).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
2320
+ return sqliteDb(tx).select(sqliteLogged).from(s).where(and9(...where.sqlite)).orderBy(asc9(s.seq)).limit(limit).all().map(rowToLogged);
2211
2321
  }
2212
- const rows = await postgresDb(tx).select().from(p).where(and8(...where.postgres)).orderBy(asc8(p.seq)).limit(limit);
2322
+ const rows = await postgresDb(tx).select(postgresLogged).from(p).where(and9(...where.postgres)).orderBy(asc9(p.seq)).limit(limit);
2213
2323
  return rows.map(rowToLogged);
2214
2324
  }
2215
2325
  return {
2216
2326
  store,
2327
+ // The columns are named, not taken from the schema: a store a migration behind, before a later column of the log
2328
+ // (retry_at), still takes appends.
2217
2329
  async append(tx, events3) {
2218
2330
  const now = /* @__PURE__ */ new Date();
2219
2331
  for (let i = 0; i < events3.length; i += APPEND_CHUNK) {
2220
2332
  const chunk = events3.slice(i, i + APPEND_CHUNK);
2333
+ const rows = (row) => sql4.join(chunk.map(row), sql4`, `);
2221
2334
  if (tx.kind === "sqlite") {
2222
- sqliteDb(tx).insert(s).values(
2223
- chunk.map((e) => ({
2224
- id: e.id,
2225
- type: e.type,
2226
- envelope: JSON.stringify(e),
2227
- correlationId: e.correlationId,
2228
- ...subjectColumns(e),
2229
- createdAt: now.toISOString()
2230
- }))
2231
- ).run();
2335
+ const at = now.toISOString();
2336
+ sqliteDb(tx).run(
2337
+ sql4`${sql4.raw(APPEND_INTO)} ${rows((e) => {
2338
+ const { subjectType, subjectId } = subjectColumns(e);
2339
+ return sql4`(${e.id}, ${e.type}, ${JSON.stringify(e)}, ${e.correlationId}, ${subjectType}, ${subjectId}, ${at})`;
2340
+ })}`
2341
+ );
2232
2342
  } else {
2233
- await postgresDb(tx).insert(p).values(
2234
- chunk.map((e) => ({
2235
- id: e.id,
2236
- type: e.type,
2237
- envelope: e,
2238
- correlationId: e.correlationId,
2239
- ...subjectColumns(e),
2240
- createdAt: now
2241
- }))
2343
+ await postgresDb(tx).execute(
2344
+ sql4`${sql4.raw(APPEND_INTO)} ${rows((e) => {
2345
+ const { subjectType, subjectId } = subjectColumns(e);
2346
+ return sql4`(${e.id}, ${e.type}, ${JSON.stringify(e)}::jsonb, ${e.correlationId}, ${subjectType}, ${subjectId}, ${now.toISOString()}::timestamptz)`;
2347
+ })}`
2242
2348
  );
2243
2349
  }
2244
2350
  }
2245
2351
  },
2246
- async listUndelivered(tx, limit, afterSeq = 0) {
2247
- if (tx.kind === "sqlite") {
2248
- return sqliteDb(tx).select().from(s).where(and8(isNull2(s.deliveredAt), isNull2(s.deadAt), gt5(s.seq, afterSeq))).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
2249
- }
2250
- const rows = await postgresDb(tx).select().from(p).where(and8(isNull2(p.deliveredAt), isNull2(p.deadAt), gt5(p.seq, afterSeq))).orderBy(asc8(p.seq)).limit(limit);
2251
- return rows.map(rowToLogged);
2352
+ listUndelivered(tx, limit, afterSeq = 0, now) {
2353
+ return select(
2354
+ tx,
2355
+ {
2356
+ sqlite: [
2357
+ isNull2(s.deliveredAt),
2358
+ isNull2(s.deadAt),
2359
+ gt5(s.seq, afterSeq),
2360
+ ...now === void 0 ? [] : [or2(isNull2(s.retryAt), lte(s.retryAt, now.toISOString()))]
2361
+ ],
2362
+ postgres: [
2363
+ isNull2(p.deliveredAt),
2364
+ isNull2(p.deadAt),
2365
+ gt5(p.seq, afterSeq),
2366
+ ...now === void 0 ? [] : [or2(isNull2(p.retryAt), lte(p.retryAt, now))]
2367
+ ]
2368
+ },
2369
+ limit
2370
+ );
2252
2371
  },
2253
2372
  async markDelivered(tx, ids, at) {
2254
2373
  if (ids.length === 0) return;
2255
2374
  if (tx.kind === "sqlite") {
2256
- sqliteDb(tx).update(s).set({ deliveredAt: at.toISOString() }).where(inArray2(s.id, ids)).run();
2375
+ sqliteDb(tx).update(s).set({ deliveredAt: at.toISOString() }).where(inArray3(s.id, ids)).run();
2257
2376
  return;
2258
2377
  }
2259
- await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray2(p.id, ids));
2378
+ await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray3(p.id, ids));
2260
2379
  },
2261
- async recordFailure(tx, id, at, maxAttempts) {
2380
+ async recordFailure(tx, id, at, maxAttempts, retryAt) {
2262
2381
  if (tx.kind === "sqlite") {
2263
2382
  sqliteDb(tx).update(s).set({
2264
2383
  attempts: sql4`${s.attempts} + 1`,
2265
- deadAt: sql4`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END`
2384
+ deadAt: sql4`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END`,
2385
+ ...retryAt !== void 0 && { retryAt: retryAt.toISOString() }
2266
2386
  }).where(eq16(s.id, id)).run();
2267
2387
  return;
2268
2388
  }
2269
2389
  await postgresDb(tx).update(p).set({
2270
2390
  attempts: sql4`${p.attempts} + 1`,
2271
- deadAt: sql4`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END`
2391
+ deadAt: sql4`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END`,
2392
+ ...retryAt !== void 0 && { retryAt }
2272
2393
  }).where(eq16(p.id, id));
2273
2394
  },
2395
+ async recordOutage(tx, id, retryAt) {
2396
+ if (tx.kind === "sqlite") {
2397
+ sqliteDb(tx).update(s).set({ retryAt: retryAt.toISOString() }).where(eq16(s.id, id)).run();
2398
+ return;
2399
+ }
2400
+ await postgresDb(tx).update(p).set({ retryAt }).where(eq16(p.id, id));
2401
+ },
2402
+ async countDead(tx) {
2403
+ if (tx.kind === "sqlite") {
2404
+ const row2 = sqliteDb(tx).select({ n: sql4`count(*)` }).from(s).where(isNotNull(s.deadAt)).get();
2405
+ return Number(row2?.n ?? 0);
2406
+ }
2407
+ const [row] = await postgresDb(tx).select({ n: sql4`count(*)` }).from(p).where(isNotNull(p.deadAt));
2408
+ return Number(row?.n ?? 0);
2409
+ },
2410
+ listDead(tx, limit) {
2411
+ return select(tx, { sqlite: [isNotNull(s.deadAt)], postgres: [isNotNull(p.deadAt)] }, limit);
2412
+ },
2413
+ async countRetrying(tx) {
2414
+ if (tx.kind === "sqlite") {
2415
+ const row2 = sqliteDb(tx).select({ n: sql4`count(*)` }).from(s).where(and9(isNull2(s.deliveredAt), isNull2(s.deadAt), gt5(s.attempts, 0))).get();
2416
+ return Number(row2?.n ?? 0);
2417
+ }
2418
+ const [row] = await postgresDb(tx).select({ n: sql4`count(*)` }).from(p).where(and9(isNull2(p.deliveredAt), isNull2(p.deadAt), gt5(p.attempts, 0)));
2419
+ return Number(row?.n ?? 0);
2420
+ },
2274
2421
  async deleteDeliveredBefore(tx, at) {
2275
2422
  if (tx.kind === "sqlite") {
2276
- const result2 = sqliteDb(tx).delete(s).where(and8(isNotNull(s.deliveredAt), lt5(s.deliveredAt, at.toISOString()))).run();
2423
+ const result2 = sqliteDb(tx).delete(s).where(and9(isNotNull(s.deliveredAt), lt5(s.deliveredAt, at.toISOString()))).run();
2277
2424
  return result2.changes;
2278
2425
  }
2279
- const result = await postgresDb(tx).delete(p).where(and8(isNotNull(p.deliveredAt), lt5(p.deliveredAt, at)));
2426
+ const result = await postgresDb(tx).delete(p).where(and9(isNotNull(p.deliveredAt), lt5(p.deliveredAt, at)));
2280
2427
  return result.rowCount ?? 0;
2281
2428
  },
2282
2429
  async listAll(tx) {
2283
2430
  if (tx.kind === "sqlite") {
2284
- return sqliteDb(tx).select().from(s).orderBy(asc8(s.seq)).all().map(rowToLogged);
2431
+ return sqliteDb(tx).select(sqliteLogged).from(s).orderBy(asc9(s.seq)).all().map(rowToLogged);
2285
2432
  }
2286
- const rows = await postgresDb(tx).select().from(p).orderBy(asc8(p.seq));
2433
+ const rows = await postgresDb(tx).select(postgresLogged).from(p).orderBy(asc9(p.seq));
2287
2434
  return rows.map(rowToLogged);
2288
2435
  },
2289
2436
  queryByCorrelation(tx, correlationId, filter) {
@@ -2320,20 +2467,20 @@ function createEventLogRepository(store) {
2320
2467
  const limit = page.limit ?? CATCH_UP_LIMIT;
2321
2468
  if (tx.kind === "sqlite") {
2322
2469
  return sqliteDb(tx).select(sqliteLogged).from(s).where(
2323
- and8(
2470
+ and9(
2324
2471
  isNull2(s.deadAt),
2325
2472
  or2(isNull2(s.deliveredAt), gte2(s.deliveredAt, since.toISOString())),
2326
2473
  gt5(s.seq, afterSeq)
2327
2474
  )
2328
- ).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
2475
+ ).orderBy(asc9(s.seq)).limit(limit).all().map(rowToLogged);
2329
2476
  }
2330
2477
  const rows = await postgresDb(tx).select(postgresLogged).from(p).where(
2331
- and8(
2478
+ and9(
2332
2479
  isNull2(p.deadAt),
2333
2480
  or2(isNull2(p.deliveredAt), gte2(p.deliveredAt, since)),
2334
2481
  gt5(p.seq, afterSeq)
2335
2482
  )
2336
- ).orderBy(asc8(p.seq)).limit(limit);
2483
+ ).orderBy(asc9(p.seq)).limit(limit);
2337
2484
  return rows.map(rowToLogged);
2338
2485
  },
2339
2486
  listDeliveredBefore(tx, at, limit) {
@@ -2351,9 +2498,9 @@ function createEventLogRepository(store) {
2351
2498
  for (let i = 0; i < seqs.length; i += DELETE_CHUNK) {
2352
2499
  const chunk = seqs.slice(i, i + DELETE_CHUNK);
2353
2500
  if (tx.kind === "sqlite") {
2354
- deleted += sqliteDb(tx).delete(s).where(and8(inArray2(s.seq, chunk), isNotNull(s.deliveredAt), isNull2(s.deadAt))).run().changes;
2501
+ deleted += sqliteDb(tx).delete(s).where(and9(inArray3(s.seq, chunk), isNotNull(s.deliveredAt), isNull2(s.deadAt))).run().changes;
2355
2502
  } else {
2356
- const result = await postgresDb(tx).delete(p).where(and8(inArray2(p.seq, chunk), isNotNull(p.deliveredAt), isNull2(p.deadAt)));
2503
+ const result = await postgresDb(tx).delete(p).where(and9(inArray3(p.seq, chunk), isNotNull(p.deliveredAt), isNull2(p.deadAt)));
2357
2504
  deleted += result.rowCount ?? 0;
2358
2505
  }
2359
2506
  }
@@ -2366,12 +2513,12 @@ function createEventLogRepository(store) {
2366
2513
  tx,
2367
2514
  {
2368
2515
  sqlite: [
2369
- or2(...subjects.map((x) => and8(eq16(s.subjectType, x.type), eq16(s.subjectId, x.id)))),
2516
+ or2(...subjects.map((x) => and9(eq16(s.subjectType, x.type), eq16(s.subjectId, x.id)))),
2370
2517
  gt5(s.seq, afterSeq),
2371
2518
  ...page.until === void 0 ? [] : [lte(s.createdAt, page.until.toISOString())]
2372
2519
  ],
2373
2520
  postgres: [
2374
- or2(...subjects.map((x) => and8(eq16(p.subjectType, x.type), eq16(p.subjectId, x.id)))),
2521
+ or2(...subjects.map((x) => and9(eq16(p.subjectType, x.type), eq16(p.subjectId, x.id)))),
2375
2522
  gt5(p.seq, afterSeq),
2376
2523
  ...page.until === void 0 ? [] : [lte(p.createdAt, page.until)]
2377
2524
  ]
@@ -2383,7 +2530,7 @@ function createEventLogRepository(store) {
2383
2530
  }
2384
2531
 
2385
2532
  // src/repositories/cart.ts
2386
- import { and as and9, asc as asc9, eq as eq17, gt as gt6, isNull as isNull3, lt as lt6, lte as lte2, sql as sql5 } from "drizzle-orm";
2533
+ import { and as and10, asc as asc10, eq as eq17, gt as gt6, isNull as isNull3, lt as lt6, lte as lte2, sql as sql5 } from "drizzle-orm";
2387
2534
  function rowToCart(store, row) {
2388
2535
  return {
2389
2536
  token: String(row.token),
@@ -2437,7 +2584,7 @@ var fromExcluded = {
2437
2584
  };
2438
2585
  function sqliteDue(window) {
2439
2586
  const t = carts;
2440
- return and9(
2587
+ return and10(
2441
2588
  isNull3(t.abandonedNotifiedAt),
2442
2589
  gt6(t.lineCount, 0),
2443
2590
  lt6(t.updatedAt, window.cutoff.toISOString()),
@@ -2446,7 +2593,7 @@ function sqliteDue(window) {
2446
2593
  }
2447
2594
  function postgresDue(window) {
2448
2595
  const t = carts2;
2449
- return and9(
2596
+ return and10(
2450
2597
  isNull3(t.abandonedNotifiedAt),
2451
2598
  gt6(t.lineCount, 0),
2452
2599
  lt6(t.updatedAt, window.cutoff),
@@ -2515,7 +2662,7 @@ function createCartRepository(store) {
2515
2662
  subtotalMinor: 0,
2516
2663
  updatedAt: at.toISOString(),
2517
2664
  abandonedNotifiedAt: null
2518
- }).where(and9(eq17(t2.token, token), gt6(t2.expiresAt, at.toISOString()))).run();
2665
+ }).where(and10(eq17(t2.token, token), gt6(t2.expiresAt, at.toISOString()))).run();
2519
2666
  return result.changes > 0;
2520
2667
  }
2521
2668
  const t = carts2;
@@ -2525,7 +2672,7 @@ function createCartRepository(store) {
2525
2672
  subtotalMinor: 0,
2526
2673
  updatedAt: at,
2527
2674
  abandonedNotifiedAt: null
2528
- }).where(and9(eq17(t.token, token), gt6(t.expiresAt, at))).returning({ token: t.token });
2675
+ }).where(and10(eq17(t.token, token), gt6(t.expiresAt, at))).returning({ token: t.token });
2529
2676
  return rows.length > 0;
2530
2677
  },
2531
2678
  async deleteExpired(tx, at) {
@@ -2540,29 +2687,181 @@ function createCartRepository(store) {
2540
2687
  if (tx.kind === "sqlite") {
2541
2688
  const t2 = carts;
2542
2689
  const rows2 = sqliteDb(tx).select({ token: t2.token }).from(t2).where(
2543
- and9(sqliteDue(window), page.after === void 0 ? void 0 : gt6(t2.token, page.after))
2544
- ).orderBy(asc9(t2.token)).limit(page.limit).all();
2690
+ and10(sqliteDue(window), page.after === void 0 ? void 0 : gt6(t2.token, page.after))
2691
+ ).orderBy(asc10(t2.token)).limit(page.limit).all();
2545
2692
  return rows2.map((r) => r.token);
2546
2693
  }
2547
2694
  const t = carts2;
2548
2695
  const rows = await postgresDb(tx).select({ token: t.token }).from(t).where(
2549
- and9(postgresDue(window), page.after === void 0 ? void 0 : gt6(t.token, page.after))
2550
- ).orderBy(asc9(t.token)).limit(page.limit);
2696
+ and10(postgresDue(window), page.after === void 0 ? void 0 : gt6(t.token, page.after))
2697
+ ).orderBy(asc10(t.token)).limit(page.limit);
2551
2698
  return rows.map((r) => r.token);
2552
2699
  },
2553
2700
  async claimAbandoned(tx, token, window) {
2554
2701
  if (tx.kind === "sqlite") {
2555
2702
  const t2 = carts;
2556
- const row2 = sqliteDb(tx).update(t2).set({ abandonedNotifiedAt: window.at.toISOString() }).where(and9(eq17(t2.token, token), sqliteDue(window))).returning({ token: t2.token, updatedAt: t2.updatedAt }).get();
2703
+ const row2 = sqliteDb(tx).update(t2).set({ abandonedNotifiedAt: window.at.toISOString() }).where(and10(eq17(t2.token, token), sqliteDue(window))).returning({ token: t2.token, updatedAt: t2.updatedAt }).get();
2557
2704
  return row2 ? { token: row2.token, lastActivityAt: fromTimestamp(row2.updatedAt) } : null;
2558
2705
  }
2559
2706
  const t = carts2;
2560
- const [row] = await postgresDb(tx).update(t).set({ abandonedNotifiedAt: window.at }).where(and9(eq17(t.token, token), postgresDue(window))).returning({ token: t.token, updatedAt: t.updatedAt });
2707
+ const [row] = await postgresDb(tx).update(t).set({ abandonedNotifiedAt: window.at }).where(and10(eq17(t.token, token), postgresDue(window))).returning({ token: t.token, updatedAt: t.updatedAt });
2561
2708
  return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null;
2562
2709
  }
2563
2710
  };
2564
2711
  }
2565
2712
 
2713
+ // src/repositories/alert-subscription.ts
2714
+ import { and as and11, eq as eq18, inArray as inArray4, sql as sql6 } from "drizzle-orm";
2715
+ function fromSqlite(row) {
2716
+ return {
2717
+ ...row,
2718
+ kind: row.kind,
2719
+ status: row.status,
2720
+ createdAt: new Date(row.createdAt),
2721
+ updatedAt: new Date(row.updatedAt),
2722
+ confirmedAt: row.confirmedAt === null ? null : new Date(row.confirmedAt)
2723
+ };
2724
+ }
2725
+ function fromPostgres(row) {
2726
+ return { ...row, kind: row.kind, status: row.status };
2727
+ }
2728
+ function createAlertSubscriptionRepository(store) {
2729
+ const s = alertSubscriptions;
2730
+ const p = alertSubscriptions2;
2731
+ async function findOne(tx, where) {
2732
+ if (tx.kind === "sqlite") {
2733
+ const row2 = sqliteDb(tx).select().from(s).where(where(s)).get();
2734
+ return row2 === void 0 ? null : fromSqlite(row2);
2735
+ }
2736
+ const [row] = await postgresDb(tx).select().from(p).where(where(p)).limit(1);
2737
+ return row === void 0 ? null : fromPostgres(row);
2738
+ }
2739
+ return {
2740
+ store,
2741
+ async upsertPending(tx, r) {
2742
+ const keep = (t) => sql6`${t.status} = 'active'`;
2743
+ const reissue = (t) => sql6`${t.status} IN ('unsubscribed', 'fired')`;
2744
+ const set = (t) => ({
2745
+ status: sql6`CASE WHEN ${keep(t)} THEN ${t.status} ELSE 'pending' END`,
2746
+ origin: sql6`CASE WHEN ${keep(t)} THEN ${t.origin} ELSE excluded.origin END`,
2747
+ confirmToken: sql6`CASE WHEN ${reissue(t)} THEN excluded.confirm_token ELSE ${t.confirmToken} END`,
2748
+ baselinePriceMinor: sql6`CASE WHEN ${reissue(t)} THEN excluded.baseline_price_minor ELSE ${t.baselinePriceMinor} END`,
2749
+ confirmedAt: sql6`CASE WHEN ${keep(t)} THEN ${t.confirmedAt} ELSE NULL END`,
2750
+ updatedAt: sql6`excluded.updated_at`
2751
+ });
2752
+ const values = {
2753
+ id: r.id,
2754
+ email: r.email,
2755
+ kind: r.kind,
2756
+ variantId: r.variantId,
2757
+ productId: r.productId,
2758
+ status: "pending",
2759
+ confirmToken: r.confirmToken,
2760
+ unsubscribeToken: r.unsubscribeToken,
2761
+ origin: r.origin,
2762
+ baselinePriceMinor: r.baselinePriceMinor,
2763
+ confirmedAt: null
2764
+ };
2765
+ if (tx.kind === "sqlite") {
2766
+ const at = r.at.toISOString();
2767
+ const row2 = sqliteDb(tx).insert(s).values({ ...values, createdAt: at, updatedAt: at }).onConflictDoUpdate({ target: [s.email, s.variantId, s.kind], set: set(s) }).returning().get();
2768
+ return fromSqlite(row2);
2769
+ }
2770
+ const [row] = await postgresDb(tx).insert(p).values({ ...values, createdAt: r.at, updatedAt: r.at }).onConflictDoUpdate({ target: [p.email, p.variantId, p.kind], set: set(p) }).returning();
2771
+ return fromPostgres(row);
2772
+ },
2773
+ findById: (tx, id) => findOne(tx, (t) => eq18(t.id, id)),
2774
+ findByConfirmToken: (tx, token) => findOne(tx, (t) => eq18(t.confirmToken, token)),
2775
+ findByUnsubscribeToken: (tx, token) => findOne(tx, (t) => eq18(t.unsubscribeToken, token)),
2776
+ async listActive(tx, variantId, kind) {
2777
+ if (tx.kind === "sqlite") {
2778
+ return sqliteDb(tx).select().from(s).where(and11(eq18(s.variantId, variantId), eq18(s.kind, kind), eq18(s.status, "active"))).orderBy(s.id).all().map(fromSqlite);
2779
+ }
2780
+ const rows = await postgresDb(tx).select().from(p).where(and11(eq18(p.variantId, variantId), eq18(p.kind, kind), eq18(p.status, "active"))).orderBy(p.id);
2781
+ return rows.map(fromPostgres);
2782
+ },
2783
+ async update(tx, id, patch, from) {
2784
+ if (tx.kind === "sqlite") {
2785
+ const row2 = sqliteDb(tx).update(s).set({
2786
+ status: patch.status,
2787
+ updatedAt: patch.updatedAt.toISOString(),
2788
+ ...patch.confirmedAt !== void 0 && {
2789
+ confirmedAt: patch.confirmedAt.toISOString()
2790
+ },
2791
+ ...patch.baselinePriceMinor !== void 0 && {
2792
+ baselinePriceMinor: patch.baselinePriceMinor
2793
+ }
2794
+ }).where(and11(eq18(s.id, id), inArray4(s.status, [...from]))).returning().get();
2795
+ return row2 === void 0 ? null : fromSqlite(row2);
2796
+ }
2797
+ const [row] = await postgresDb(tx).update(p).set({
2798
+ status: patch.status,
2799
+ updatedAt: patch.updatedAt,
2800
+ ...patch.confirmedAt !== void 0 && { confirmedAt: patch.confirmedAt },
2801
+ ...patch.baselinePriceMinor !== void 0 && {
2802
+ baselinePriceMinor: patch.baselinePriceMinor
2803
+ }
2804
+ }).where(and11(eq18(p.id, id), inArray4(p.status, [...from]))).returning();
2805
+ return row === void 0 ? null : fromPostgres(row);
2806
+ }
2807
+ };
2808
+ }
2809
+
2810
+ // src/repositories/email-suppression.ts
2811
+ import { eq as eq19 } from "drizzle-orm";
2812
+ function createEmailSuppressionRepository(store) {
2813
+ const s = emailSuppressions;
2814
+ const p = emailSuppressions2;
2815
+ return {
2816
+ store,
2817
+ async suppress(tx, { email, reason, eventId, at }) {
2818
+ const values = { email: normaliseEmail(email), reason, eventId };
2819
+ if (tx.kind === "sqlite") {
2820
+ const result2 = sqliteDb(tx).insert(s).values({ ...values, createdAt: at.toISOString() }).onConflictDoNothing().run();
2821
+ return result2.changes > 0;
2822
+ }
2823
+ const result = await postgresDb(tx).insert(p).values({ ...values, createdAt: at }).onConflictDoNothing();
2824
+ return (result.rowCount ?? 0) > 0;
2825
+ },
2826
+ async isSuppressed(tx, email) {
2827
+ const key = normaliseEmail(email);
2828
+ if (tx.kind === "sqlite") {
2829
+ const row = sqliteDb(tx).select({ email: s.email }).from(s).where(eq19(s.email, key)).get();
2830
+ return row !== void 0;
2831
+ }
2832
+ const rows = await postgresDb(tx).select({ email: p.email }).from(p).where(eq19(p.email, key)).limit(1);
2833
+ return rows.length > 0;
2834
+ }
2835
+ };
2836
+ }
2837
+
2838
+ // src/repositories/order-shipment.ts
2839
+ import { eq as eq20 } from "drizzle-orm";
2840
+ import { normaliseTrackingNumber } from "@nymbalhq/types";
2841
+ function createOrderShipmentRepository(store) {
2842
+ const s = orderShipments;
2843
+ const p = orderShipments2;
2844
+ return {
2845
+ store,
2846
+ async record(tx, { orderId, carrier, trackingNumber, at }) {
2847
+ const values = { orderId, carrier, trackingNumber: normaliseTrackingNumber(trackingNumber) };
2848
+ if (tx.kind === "sqlite") {
2849
+ sqliteDb(tx).insert(s).values({ ...values, createdAt: at.toISOString() }).run();
2850
+ return;
2851
+ }
2852
+ await postgresDb(tx).insert(p).values({ ...values, createdAt: at });
2853
+ },
2854
+ async ordersByTrackingNumber(tx, trackingNumber) {
2855
+ const key = normaliseTrackingNumber(trackingNumber);
2856
+ if (tx.kind === "sqlite") {
2857
+ return sqliteDb(tx).select({ orderId: s.orderId }).from(s).where(eq20(s.trackingNumber, key)).all().map((r) => r.orderId);
2858
+ }
2859
+ const rows = await postgresDb(tx).select({ orderId: p.orderId }).from(p).where(eq20(p.trackingNumber, key));
2860
+ return rows.map((r) => r.orderId);
2861
+ }
2862
+ };
2863
+ }
2864
+
2566
2865
  // src/repositories/index.ts
2567
2866
  function buildRepositories(commandStore, _documentStore) {
2568
2867
  return {
@@ -2576,6 +2875,7 @@ function buildRepositories(commandStore, _documentStore) {
2576
2875
  orderHistory: createOrderHistoryRepository(commandStore),
2577
2876
  orderRefund: createOrderRefundRepository(commandStore),
2578
2877
  orderSequence: createOrderSequenceRepository(commandStore),
2878
+ orderAccessKey: createOrderAccessKeyRepository(commandStore),
2579
2879
  inventoryReservation: createInventoryReservationRepository(commandStore),
2580
2880
  stockAdjustment: createStockAdjustmentRepository(commandStore),
2581
2881
  review: createReviewRepository(commandStore),
@@ -2583,7 +2883,10 @@ function buildRepositories(commandStore, _documentStore) {
2583
2883
  eventLog: createEventLogRepository(commandStore),
2584
2884
  cart: createCartRepository(commandStore),
2585
2885
  settings: createSettingsRepository(commandStore),
2586
- auditEntry: createAuditEntryRepository(commandStore)
2886
+ auditEntry: createAuditEntryRepository(commandStore),
2887
+ alertSubscription: createAlertSubscriptionRepository(commandStore),
2888
+ emailSuppression: createEmailSuppressionRepository(commandStore),
2889
+ orderShipment: createOrderShipmentRepository(commandStore)
2587
2890
  };
2588
2891
  }
2589
2892
 
@@ -2635,6 +2938,11 @@ function createEventPublisher(opts) {
2635
2938
  async publishMany(events3) {
2636
2939
  await append(events3.map((e) => build(e.type, e.payload, e.options ?? {})));
2637
2940
  },
2941
+ async publishUntyped(events3, options) {
2942
+ const built = events3.map((e) => build(e.type, e.payload, options ?? {}));
2943
+ await append(built);
2944
+ return built;
2945
+ },
2638
2946
  correlated(correlationId) {
2639
2947
  return createEventPublisher({ ...opts, correlationId });
2640
2948
  }
@@ -2643,7 +2951,11 @@ function createEventPublisher(opts) {
2643
2951
 
2644
2952
  // src/events/relay.ts
2645
2953
  import { AsyncLocalStorage } from "async_hooks";
2954
+ import {
2955
+ HEALTH_CHECK_TIMEOUT_MS
2956
+ } from "@nymbalhq/types";
2646
2957
  var PAGE_SIZE = 100;
2958
+ var NO_OUTAGE = { outage: false, down: [] };
2647
2959
  function deferred() {
2648
2960
  let resolve4;
2649
2961
  const promise = new Promise((r) => {
@@ -2651,10 +2963,17 @@ function deferred() {
2651
2963
  });
2652
2964
  return { promise, resolve: resolve4 };
2653
2965
  }
2966
+ function failedOf(err) {
2967
+ const failed = err?.context?.failed;
2968
+ return Array.isArray(failed) ? { failed } : {};
2969
+ }
2654
2970
  function createRelay(opts) {
2655
2971
  const { store, eventLog } = opts;
2656
2972
  const maxAttempts = opts.maxAttempts ?? 5;
2657
2973
  const intervalMs = opts.intervalMs ?? 1e4;
2974
+ const retryDelayMs = opts.retryDelayMs ?? intervalMs;
2975
+ const now = opts.now ?? (() => /* @__PURE__ */ new Date());
2976
+ const outageTimeoutMs = opts.outageTimeoutMs ?? HEALTH_CHECK_TIMEOUT_MS + 1e3;
2658
2977
  const logger = opts.logger.child({ component: "event-relay" });
2659
2978
  const delivering = new AsyncLocalStorage();
2660
2979
  let active = false;
@@ -2662,17 +2981,73 @@ function createRelay(opts) {
2662
2981
  let followUp;
2663
2982
  let timer;
2664
2983
  let stopped = false;
2665
- async function deliver({ event, attempts }) {
2984
+ async function probe() {
2985
+ const ask = opts.outage;
2986
+ if (ask === void 0) return NO_OUTAGE;
2987
+ let bound;
2988
+ const timedOut = new Promise((resolve4) => {
2989
+ bound = setTimeout(
2990
+ () => resolve4({
2991
+ outage: true,
2992
+ down: [{ name: "probe", detail: `timed out after ${outageTimeoutMs} ms` }]
2993
+ }),
2994
+ outageTimeoutMs
2995
+ );
2996
+ });
2997
+ try {
2998
+ return await Promise.race([Promise.resolve().then(ask), timedOut]);
2999
+ } catch (err) {
3000
+ return {
3001
+ outage: true,
3002
+ down: [{ name: "probe", detail: err instanceof Error ? err.message : String(err) }]
3003
+ };
3004
+ } finally {
3005
+ clearTimeout(bound);
3006
+ }
3007
+ }
3008
+ function outageOfPass() {
3009
+ let asked;
3010
+ return () => asked ??= probe().then((report) => {
3011
+ if (report.outage) {
3012
+ const named = report.down.map(({ name, detail }) => `${name} (${detail})`).join(", ");
3013
+ logger.warn({ down: report.down }, `outage: ${named}`);
3014
+ }
3015
+ return report;
3016
+ });
3017
+ }
3018
+ async function deliver({ event, attempts }, outage) {
2666
3019
  try {
2667
3020
  await delivering.run(true, () => opts.eventBus.publish(event));
2668
3021
  } catch (err) {
2669
- const at = /* @__PURE__ */ new Date();
2670
- await store.transaction((tx) => eventLog.recordFailure(tx, event.id, at, maxAttempts));
2671
- const context = { err, eventId: event.id, eventType: event.type, attempts: attempts + 1 };
2672
- if (attempts + 1 >= maxAttempts) {
3022
+ const at = now();
3023
+ if ((await outage()).outage) {
3024
+ const retryAt2 = new Date(at.getTime() + retryDelayMs * 2 ** attempts);
3025
+ await store.transaction((tx) => eventLog.recordOutage(tx, event.id, retryAt2));
3026
+ logger.debug(
3027
+ { err, eventId: event.id, eventType: event.type, retryAt: retryAt2.toISOString() },
3028
+ "event delivery failed during an outage; not counted, tried again from retryAt"
3029
+ );
3030
+ return;
3031
+ }
3032
+ const failures = attempts + 1;
3033
+ const retryAt = new Date(at.getTime() + retryDelayMs * 2 ** (failures - 1));
3034
+ await store.transaction(
3035
+ (tx) => eventLog.recordFailure(tx, event.id, at, maxAttempts, retryAt)
3036
+ );
3037
+ const context = {
3038
+ err,
3039
+ eventId: event.id,
3040
+ eventType: event.type,
3041
+ attempts: failures,
3042
+ ...failedOf(err)
3043
+ };
3044
+ if (failures >= maxAttempts) {
2673
3045
  logger.error(context, "event delivery failed for the last time; the event is dead");
2674
3046
  } else {
2675
- logger.warn(context, "event delivery failed; the event stays in the log for a later drain");
3047
+ logger.warn(
3048
+ { ...context, retryAt: retryAt.toISOString() },
3049
+ "event delivery failed; the event stays in the log and is tried again from retryAt"
3050
+ );
2676
3051
  }
2677
3052
  return;
2678
3053
  }
@@ -2681,13 +3056,16 @@ function createRelay(opts) {
2681
3056
  async function pass() {
2682
3057
  try {
2683
3058
  let afterSeq = 0;
3059
+ const outage = outageOfPass();
2684
3060
  for (; ; ) {
2685
3061
  if (stopped) return;
2686
- const page = await store.read((tx) => eventLog.listUndelivered(tx, PAGE_SIZE, afterSeq));
3062
+ const page = await store.read(
3063
+ (tx) => eventLog.listUndelivered(tx, PAGE_SIZE, afterSeq, now())
3064
+ );
2687
3065
  for (const logged of page) {
2688
3066
  if (stopped) return;
2689
3067
  afterSeq = logged.seq;
2690
- await deliver(logged);
3068
+ await deliver(logged, outage);
2691
3069
  }
2692
3070
  if (page.length < PAGE_SIZE) return;
2693
3071
  }
@@ -2777,158 +3155,6 @@ import {
2777
3155
  EVT_CATEGORY_DELETED,
2778
3156
  EVT_CATEGORY_UPDATED
2779
3157
  } from "@nymbalhq/types";
2780
-
2781
- // src/read-models/builders.ts
2782
- var CATEGORIES = "categories";
2783
- var PRODUCTS = "products";
2784
- var PRODUCTS_BY_CATEGORY = "products-by-category";
2785
- var ORDERS = "orders";
2786
- var ORDERS_BY_CUSTOMER = "orders-by-customer";
2787
- var CUSTOMER_PROFILES = "customer-profiles";
2788
- function buildCategoryDoc(category, storeId) {
2789
- return {
2790
- id: category.id,
2791
- storeId,
2792
- parentId: category.parentId,
2793
- slug: category.slug,
2794
- name: category.name,
2795
- description: category.description,
2796
- position: category.position,
2797
- createdAt: category.createdAt
2798
- };
2799
- }
2800
- var isVariantOption = (o) => typeof o === "object" && o !== null && typeof o.name === "string" && typeof o.value === "string";
2801
- function variantOptions(raw, sku, logger) {
2802
- let value = raw;
2803
- if (typeof raw === "string") {
2804
- try {
2805
- value = JSON.parse(raw);
2806
- } catch (err) {
2807
- logger?.warn({ sku, err }, "variant options are not JSON; projected as none");
2808
- return [];
2809
- }
2810
- }
2811
- if (!Array.isArray(value)) return [];
2812
- return value.filter(isVariantOption).map((o) => ({ name: o.name, value: o.value }));
2813
- }
2814
- function buildProductDoc(p, categories3, ctx) {
2815
- const prices = p.variants.map((v) => v.priceMinor);
2816
- return {
2817
- id: p.id,
2818
- storeId: ctx.storeId,
2819
- slug: p.slug,
2820
- name: p.name,
2821
- description: p.description,
2822
- shortDescription: p.shortDescription,
2823
- status: p.status,
2824
- type: p.type,
2825
- media: p.media,
2826
- variantCount: p.variants.length,
2827
- inStock: p.variants.some((v) => v.stock > 0),
2828
- priceRange: prices.length ? { minMinor: Math.min(...prices), maxMinor: Math.max(...prices) } : null,
2829
- currency: ctx.currency,
2830
- priceMinor: prices[0] ?? null,
2831
- variants: p.variants.map((v) => ({
2832
- id: v.id,
2833
- sku: v.sku,
2834
- name: v.name,
2835
- priceMinor: v.priceMinor,
2836
- stock: v.stock,
2837
- options: variantOptions(v.options, v.sku, ctx.logger)
2838
- })),
2839
- categoryIds: p.categoryIds,
2840
- categories: p.categoryIds.flatMap((id) => {
2841
- const c = categories3.get(id);
2842
- return c ? [{ id: c.id, name: c.name, slug: c.slug }] : [];
2843
- }),
2844
- createdAt: p.createdAt,
2845
- updatedAt: p.updatedAt
2846
- };
2847
- }
2848
- var productByCategoryKey = (categorySlug, productSlug) => `category:${categorySlug}#product:${productSlug}`;
2849
- function productWrites(doc) {
2850
- return [
2851
- { collection: PRODUCTS, key: doc.slug, doc },
2852
- ...doc.categories.map((c) => ({
2853
- collection: PRODUCTS_BY_CATEGORY,
2854
- key: productByCategoryKey(c.slug, doc.slug),
2855
- doc: { ...doc, partitionKey: `category:${c.slug}`, sortKey: `product:${doc.slug}` }
2856
- }))
2857
- ];
2858
- }
2859
- function customerSortKey(o) {
2860
- return `order:${String(Number.MAX_SAFE_INTEGER - new Date(String(o.createdAt)).getTime()).padStart(16, "0")}:${o.orderNumber}`;
2861
- }
2862
- function buildOrderDoc(order, history) {
2863
- return {
2864
- ...order,
2865
- history: history.map((h) => ({
2866
- fromStatus: h.fromStatus,
2867
- toStatus: h.toStatus,
2868
- actor: h.actor,
2869
- note: h.note,
2870
- timestamp: String(h.timestamp)
2871
- }))
2872
- };
2873
- }
2874
- function orderWrites(doc) {
2875
- const writes = [{ collection: ORDERS, key: doc.orderNumber, doc }];
2876
- if (doc.customerId) {
2877
- const sortKey = customerSortKey(doc);
2878
- writes.push({
2879
- collection: ORDERS_BY_CUSTOMER,
2880
- key: `customer:${doc.customerId}#${sortKey}`,
2881
- doc: { ...doc, partitionKey: `customer:${doc.customerId}`, sortKey }
2882
- });
2883
- }
2884
- return writes;
2885
- }
2886
- function buildCustomerProfile(c) {
2887
- const { orderCount, totalSpentMinor } = c;
2888
- return {
2889
- customerId: c.id,
2890
- orderCount,
2891
- totalSpentMinor,
2892
- segment: totalSpentMinor > 1e5 ? "vip" : orderCount > 3 ? "returning" : orderCount > 0 ? "active" : "new",
2893
- createdAt: String(c.createdAt)
2894
- };
2895
- }
2896
- var partitioned = (doc) => {
2897
- const { partitionKey, sortKey } = doc;
2898
- return `${String(partitionKey)}#${String(sortKey)}`;
2899
- };
2900
- var KEY_OF = {
2901
- [CATEGORIES]: (doc) => String(doc.slug),
2902
- [PRODUCTS]: (doc) => String(doc.slug),
2903
- [PRODUCTS_BY_CATEGORY]: partitioned,
2904
- [ORDERS]: (doc) => String(doc.orderNumber),
2905
- [ORDERS_BY_CUSTOMER]: partitioned,
2906
- [CUSTOMER_PROFILES]: (doc) => String(doc.customerId)
2907
- };
2908
- function buildSearchDoc(p) {
2909
- return {
2910
- id: p.id,
2911
- type: "product",
2912
- fields: {
2913
- slug: p.slug,
2914
- name: p.name,
2915
- description: p.description,
2916
- status: p.status,
2917
- categoryIds: p.categoryIds,
2918
- variants: p.variants.map((v) => ({ sku: v.sku, name: v.name, priceMinor: v.priceMinor }))
2919
- }
2920
- };
2921
- }
2922
-
2923
- // src/handlers/derived.ts
2924
- async function subscribeDerived(eventBus, handlers) {
2925
- for (const h of handlers) {
2926
- const pattern = h.types.length === 1 ? h.types[0] : [...h.types];
2927
- await eventBus.subscribe(pattern, h.handle, { name: h.name, derived: true });
2928
- }
2929
- }
2930
-
2931
- // src/handlers/projections/category-projection.ts
2932
3158
  function categoryProjection(deps) {
2933
3159
  const { documentStore, logger, storeId, repos } = deps;
2934
3160
  const onUpsert = async (event) => {
@@ -2991,8 +3217,8 @@ async function categoriesOf(tx, repos, ids) {
2991
3217
  async function loadProduct(tx, repos, productId) {
2992
3218
  const product = await repos.product.findById(tx, productId);
2993
3219
  if (!product) return null;
2994
- const snapshot2 = await productSnapshot(tx, repos, product);
2995
- return { snapshot: snapshot2, categories: await categoriesOf(tx, repos, snapshot2.categoryIds) };
3220
+ const snapshot = await productSnapshot(tx, repos, product);
3221
+ return { snapshot, categories: await categoriesOf(tx, repos, snapshot.categoryIds) };
2996
3222
  }
2997
3223
  async function loadOrderDoc(tx, repos, orderId) {
2998
3224
  const order = await repos.order.findById(tx, orderId);
@@ -3203,37 +3429,77 @@ async function registerInventoryProjection(deps) {
3203
3429
  }
3204
3430
 
3205
3431
  // src/handlers/side-effects/email-handler.ts
3432
+ import { v7 as uuidv73 } from "uuid";
3206
3433
  import {
3207
3434
  EVT_CART_ABANDONED,
3208
3435
  EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED2,
3436
+ EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,
3209
3437
  EVT_ORDER_PAID as EVT_ORDER_PAID3,
3210
3438
  EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED2
3211
3439
  } from "@nymbalhq/types";
3212
3440
  var ORDER_PAID_EMAIL = "email:order-paid";
3441
+ var DEFAULT_EMAIL_KEY_LIFETIME_MS = 30 * 24 * 36e5;
3213
3442
  async function registerEmailHandler(deps) {
3214
- const { eventBus, email, logger, processedEventRepo, orderRepo, storeName } = deps;
3215
- const onOrderPaid = async (event) => {
3216
- const { orderId } = event.payload;
3217
- const { store } = processedEventRepo;
3218
- if (await store.read((tx) => processedEventRepo.seen(tx, ORDER_PAID_EMAIL, orderId))) return;
3219
- const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId));
3220
- if (order === null) {
3221
- logger.warn({ orderId, eventId: event.id }, "email handler: paid order not found");
3222
- return;
3443
+ const { eventBus, email, logger, processedEventRepo, orderRepo, orderAccessKeyRepo } = deps;
3444
+ const { storeName, storeUrl } = deps;
3445
+ const keyLifetimeMs = deps.keyLifetimeMs ?? DEFAULT_EMAIL_KEY_LIFETIME_MS;
3446
+ async function orderLink(base, order) {
3447
+ const number = encodeURIComponent(order.orderNumber);
3448
+ let orderUrl = `${base}/account/orders/${number}`;
3449
+ if (order.customerId === null) {
3450
+ const { key, hash } = mintOrderKey();
3451
+ const createdAt = /* @__PURE__ */ new Date();
3452
+ await orderAccessKeyRepo.store.transaction(
3453
+ (tx) => orderAccessKeyRepo.insert(tx, {
3454
+ id: uuidv73(),
3455
+ orderId: order.id,
3456
+ keyHash: hash,
3457
+ purpose: "email",
3458
+ createdAt,
3459
+ expiresAt: new Date(createdAt.getTime() + keyLifetimeMs)
3460
+ })
3461
+ );
3462
+ orderUrl = `${base}/order/${number}?key=${key}`;
3223
3463
  }
3464
+ return { orderUrl, orderLink: `
3465
+
3466
+ View your order: ${orderUrl}` };
3467
+ }
3468
+ async function sendOrderPlaced(order) {
3224
3469
  await email.sendTransactional({
3225
3470
  template: "order-placed",
3226
3471
  to: order.email,
3227
3472
  vars: {
3228
3473
  orderNumber: order.orderNumber,
3229
3474
  customerName: order.billingAddress.firstName,
3230
- totalFormatted: formatMoney(order.totalMinor, order.currency)
3475
+ totalFormatted: formatMoney(order.totalMinor, order.currency),
3476
+ ...storeUrl !== void 0 && await orderLink(storeUrl, order)
3231
3477
  }
3232
3478
  });
3479
+ }
3480
+ const onOrderPaid = async (event) => {
3481
+ const { orderId } = event.payload;
3482
+ const { store } = processedEventRepo;
3483
+ if (await store.read((tx) => processedEventRepo.seen(tx, ORDER_PAID_EMAIL, orderId))) return;
3484
+ const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId));
3485
+ if (order === null) {
3486
+ logger.warn({ orderId, eventId: event.id }, "email handler: paid order not found");
3487
+ return;
3488
+ }
3489
+ await sendOrderPlaced(order);
3233
3490
  await store.transaction(
3234
3491
  (tx) => processedEventRepo.markProcessed(tx, ORDER_PAID_EMAIL, orderId, /* @__PURE__ */ new Date())
3235
3492
  );
3236
3493
  };
3494
+ const onConfirmationResendRequested = async (event) => {
3495
+ const { orderId } = event.payload;
3496
+ const order = await orderRepo.store.read((tx) => orderRepo.findById(tx, orderId));
3497
+ if (order === null) {
3498
+ logger.warn({ orderId, eventId: event.id }, "email handler: resent order not found");
3499
+ return;
3500
+ }
3501
+ await sendOrderPlaced(order);
3502
+ };
3237
3503
  const onOrderShipped = async (event) => {
3238
3504
  logger.debug({ orderId: event.payload.orderId }, "email handler: order shipped");
3239
3505
  };
@@ -3250,6 +3516,15 @@ async function registerEmailHandler(deps) {
3250
3516
  await eventBus.subscribe(EVT_ORDER_PAID3, onOrderPaid, {
3251
3517
  name: "email-order-paid"
3252
3518
  });
3519
+ await eventBus.subscribe(
3520
+ EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,
3521
+ withIdempotency(
3522
+ "email:order-confirmation-resend",
3523
+ onConfirmationResendRequested,
3524
+ { repo: processedEventRepo, logger }
3525
+ ),
3526
+ { name: "email-order-confirmation-resend" }
3527
+ );
3253
3528
  await eventBus.subscribe(
3254
3529
  EVT_ORDER_SHIPPED2,
3255
3530
  withIdempotency("email:order-shipped", onOrderShipped, {
@@ -3283,17 +3558,27 @@ import {
3283
3558
  EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED2
3284
3559
  } from "@nymbalhq/types";
3285
3560
  function searchHandler(deps) {
3286
- const { search: search2, repos } = deps;
3561
+ const { search: search2, repos, logger } = deps;
3562
+ const skips = (event) => {
3563
+ if (search2.capabilities().includes("index")) return false;
3564
+ logger.debug(
3565
+ { eventId: event.id, type: event.type, provider: search2.providerName },
3566
+ "search: the slot cannot index, event skipped"
3567
+ );
3568
+ return true;
3569
+ };
3287
3570
  const onUpsert = async (event) => {
3571
+ if (skips(event)) return;
3288
3572
  const { id } = event.payload.product;
3289
- const snapshot2 = await repos.product.store.read(async (tx) => {
3573
+ const snapshot = await repos.product.store.read(async (tx) => {
3290
3574
  const product = await repos.product.findById(tx, id);
3291
3575
  return product ? productSnapshot(tx, repos, product) : null;
3292
3576
  });
3293
- if (snapshot2) await search2.index([buildSearchDoc(snapshot2)]);
3577
+ if (snapshot) await search2.index([buildSearchDoc(snapshot)]);
3294
3578
  else await search2.remove([id]);
3295
3579
  };
3296
3580
  const onDelete = async (event) => {
3581
+ if (skips(event)) return;
3297
3582
  await search2.remove([event.payload.productId]);
3298
3583
  };
3299
3584
  return [
@@ -3332,1907 +3617,375 @@ async function registerReviewsHandler(deps) {
3332
3617
  );
3333
3618
  }
3334
3619
 
3335
- // src/handlers/register.ts
3336
- async function registerHandlers(deps) {
3337
- const { config, eventBus, documentStore, repos, adapters, logger } = deps;
3338
- const handlerLogger = logger.child({ component: "handlers" });
3339
- await registerCategoryProjection({
3340
- eventBus,
3341
- documentStore,
3342
- logger: handlerLogger.child({ projection: "category" }),
3343
- storeId: config.store.name,
3344
- repos
3345
- });
3346
- await registerProductProjection({
3347
- eventBus,
3348
- documentStore,
3349
- logger: handlerLogger.child({ projection: "product" }),
3350
- storeId: config.store.name,
3351
- currency: config.store.currency,
3352
- repos
3353
- });
3354
- await registerOrderProjection({
3355
- eventBus,
3356
- documentStore,
3357
- logger: handlerLogger.child({ projection: "order" }),
3358
- orderRepo: repos.order,
3359
- orderHistoryRepo: repos.orderHistory
3360
- });
3361
- await registerCustomerProjection({
3362
- eventBus,
3363
- documentStore,
3364
- logger: handlerLogger.child({ projection: "customer" }),
3365
- customerRepo: repos.customer,
3366
- orderRepo: repos.order
3367
- });
3368
- await registerInventoryProjection({
3369
- eventBus,
3370
- documentStore,
3371
- logger: handlerLogger.child({ projection: "inventory" }),
3372
- storeId: config.store.name,
3373
- currency: config.store.currency,
3374
- repos
3375
- });
3376
- await registerEmailHandler({
3377
- eventBus,
3378
- email: adapters.email,
3379
- logger: handlerLogger.child({ handler: "email" }),
3380
- processedEventRepo: repos.processedEvent,
3381
- orderRepo: repos.order,
3382
- storeName: config.store.name
3383
- });
3384
- await registerSearchHandler({
3385
- eventBus,
3386
- search: adapters.search,
3387
- repos
3388
- });
3389
- await registerReviewsHandler({
3390
- eventBus,
3391
- reviews: adapters.reviews,
3392
- logger: handlerLogger.child({ handler: "reviews" }),
3393
- processedEventRepo: repos.processedEvent
3394
- });
3395
- logger.debug("event handlers registered");
3396
- }
3397
-
3398
- // src/app.ts
3399
- import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
3400
- import { ConfigError as ConfigError2 } from "@nymbalhq/types";
3401
-
3402
- // src/services/product-service.ts
3403
- import { v7 as uuidv73 } from "uuid";
3404
- import {
3405
- EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED3,
3406
- EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED3,
3407
- EVT_PRODUCT_DELETED as EVT_PRODUCT_DELETED3,
3408
- EVT_PRODUCT_PUBLISHED,
3409
- EVT_PRODUCT_UNPUBLISHED,
3410
- NotFoundError,
3411
- ValidationError as ValidationError2
3412
- } from "@nymbalhq/types";
3413
- async function snapshot(tx, repos, product) {
3414
- const [variants3, categoryIds] = await Promise.all([
3415
- repos.variant.findByProduct(tx, product.id),
3416
- repos.productCategory.listCategoriesForProduct(tx, product.id)
3417
- ]);
3418
- return { ...product, variants: variants3, categoryIds };
3419
- }
3420
- function createProductService(deps) {
3421
- const { store, repos, publisher } = deps;
3422
- async function requireProduct(tx, id) {
3423
- const product = await repos.product.findById(tx, id);
3424
- if (!product) throw new NotFoundError("product", id);
3425
- return product;
3426
- }
3427
- return {
3428
- async create(input) {
3429
- audit.note("product.create");
3430
- if (!input.slug.trim()) throw new ValidationError2("Product slug is required");
3431
- if (!input.name.trim()) throw new ValidationError2("Product name is required");
3432
- const existing = await store.read((tx) => repos.product.findBySlug(tx, input.slug));
3433
- if (existing) {
3434
- throw new ValidationError2(`Product slug already exists: ${input.slug}`, {
3435
- context: { slug: input.slug }
3436
- });
3437
- }
3438
- return store.transaction(async (tx) => {
3439
- const now = /* @__PURE__ */ new Date();
3440
- const productId = uuidv73();
3441
- audit.note("product.create", [{ type: "product", id: productId }]);
3442
- const insert = {
3443
- id: productId,
3444
- slug: input.slug,
3445
- name: input.name,
3446
- ...input.description !== void 0 && { description: input.description },
3447
- ...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
3448
- ...input.status !== void 0 && { status: input.status },
3449
- ...input.type !== void 0 && { type: input.type },
3450
- ...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
3451
- ...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
3452
- ...input.media !== void 0 && { media: input.media },
3453
- ...input.metadata !== void 0 && { metadata: input.metadata },
3454
- createdAt: now,
3455
- updatedAt: now
3456
- };
3457
- await repos.product.insert(tx, insert);
3458
- const variantRows = [];
3459
- for (const v of input.variants ?? []) {
3460
- const id = v.id ?? uuidv73();
3461
- const vi = {
3462
- ...v,
3463
- id,
3464
- productId,
3465
- createdAt: now,
3466
- updatedAt: now
3467
- };
3468
- await repos.variant.insert(tx, vi);
3469
- const stored = await repos.variant.findById(tx, id);
3470
- if (stored) variantRows.push(stored);
3471
- }
3472
- for (const categoryId of input.categoryIds ?? []) {
3473
- await repos.productCategory.attach(tx, productId, categoryId);
3474
- }
3475
- const created = await requireProduct(tx, productId);
3476
- const snap = {
3477
- ...created,
3478
- variants: variantRows,
3479
- categoryIds: input.categoryIds ?? []
3480
- };
3481
- await publisher.publish(EVT_PRODUCT_CREATED3, { product: snap });
3482
- return snap;
3483
- });
3484
- },
3485
- async update(id, input) {
3486
- return store.transaction(async (tx) => {
3487
- audit.note("product.update", [{ type: "product", id }]);
3488
- const product = await requireProduct(tx, id);
3489
- const now = /* @__PURE__ */ new Date();
3490
- const updateInput = {
3491
- ...input.name !== void 0 && { name: input.name },
3492
- ...input.description !== void 0 && { description: input.description },
3493
- ...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
3494
- ...input.status !== void 0 && { status: input.status },
3495
- ...input.type !== void 0 && { type: input.type },
3496
- ...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
3497
- ...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
3498
- ...input.media !== void 0 && { media: input.media },
3499
- ...input.metadata !== void 0 && { metadata: input.metadata },
3500
- updatedAt: now
3501
- };
3502
- await repos.product.update(tx, product.id, updateInput);
3503
- if (input.categoryIds) {
3504
- await repos.productCategory.detachAllForProduct(tx, product.id);
3505
- for (const categoryId of input.categoryIds) {
3506
- await repos.productCategory.attach(tx, product.id, categoryId);
3507
- }
3508
- }
3509
- const snap = await snapshot(tx, repos, await requireProduct(tx, product.id));
3510
- await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
3511
- return snap;
3512
- });
3513
- },
3514
- async delete(id) {
3515
- await store.transaction(async (tx) => {
3516
- audit.note("product.delete", [{ type: "product", id }]);
3517
- const product = await requireProduct(tx, id);
3518
- await repos.productCategory.detachAllForProduct(tx, product.id);
3519
- const variants3 = await repos.variant.findByProduct(tx, product.id);
3520
- for (const v of variants3) await repos.variant.delete(tx, v.id);
3521
- await repos.product.delete(tx, product.id);
3522
- await publisher.publish(EVT_PRODUCT_DELETED3, {
3523
- productId: product.id,
3524
- slug: product.slug
3525
- });
3526
- });
3527
- },
3528
- async publish(id) {
3529
- await store.transaction(async (tx) => {
3530
- audit.note("product.publish", [{ type: "product", id }]);
3531
- const product = await requireProduct(tx, id);
3532
- if (product.status === "active") return;
3533
- await repos.product.setStatus(tx, product.id, "active", /* @__PURE__ */ new Date());
3534
- await publisher.publish(EVT_PRODUCT_PUBLISHED, {
3535
- productId: product.id,
3536
- slug: product.slug
3537
- });
3538
- const fresh = await requireProduct(tx, product.id);
3539
- const snap = await snapshot(tx, repos, fresh);
3540
- await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
3541
- });
3542
- },
3543
- async unpublish(id) {
3544
- await store.transaction(async (tx) => {
3545
- audit.note("product.unpublish", [{ type: "product", id }]);
3546
- const product = await requireProduct(tx, id);
3547
- if (product.status === "draft") return;
3548
- await repos.product.setStatus(tx, product.id, "draft", /* @__PURE__ */ new Date());
3549
- await publisher.publish(EVT_PRODUCT_UNPUBLISHED, {
3550
- productId: product.id,
3551
- slug: product.slug
3552
- });
3553
- const fresh = await requireProduct(tx, product.id);
3554
- const snap = await snapshot(tx, repos, fresh);
3555
- await publisher.publish(EVT_PRODUCT_UPDATED3, { product: snap });
3556
- });
3557
- },
3558
- async getById(id) {
3559
- return store.read(async (tx) => snapshot(tx, repos, await requireProduct(tx, id)));
3560
- },
3561
- async getBySlug(slug) {
3562
- return store.read(async (tx) => {
3563
- const product = await repos.product.findBySlug(tx, slug);
3564
- if (!product) throw new NotFoundError("product", slug);
3565
- return snapshot(tx, repos, product);
3566
- });
3567
- },
3568
- async list(opts = {}) {
3569
- return store.read(async (tx) => {
3570
- const products3 = await repos.product.list(tx, opts);
3571
- const out = [];
3572
- for (const p of products3) {
3573
- out.push(await snapshot(tx, repos, p));
3574
- }
3575
- return out;
3576
- });
3577
- }
3578
- };
3579
- }
3580
-
3581
- // src/services/category-service.ts
3582
- import { v7 as uuidv74 } from "uuid";
3620
+ // src/handlers/side-effects/alert-handler.ts
3583
3621
  import {
3584
- EVT_CATEGORY_CREATED as EVT_CATEGORY_CREATED3,
3585
- EVT_CATEGORY_UPDATED as EVT_CATEGORY_UPDATED3,
3586
- EVT_CATEGORY_DELETED as EVT_CATEGORY_DELETED3,
3587
- NotFoundError as NotFoundError2,
3588
- ValidationError as ValidationError3
3622
+ EVT_ALERT_REQUESTED,
3623
+ EVT_PRODUCT_RESTOCKED,
3624
+ EVT_PRODUCT_VARIANT_PRICE_CHANGED
3589
3625
  } from "@nymbalhq/types";
3590
- function createCategoryService(deps) {
3591
- const { repos, publisher } = deps;
3592
- const { store } = repos.category;
3626
+ var HANDLER = "email:alert";
3627
+ function links(row, product) {
3628
+ const token = (value) => encodeURIComponent(value);
3593
3629
  return {
3594
- async list() {
3595
- return store.read((tx) => repos.category.list(tx));
3596
- },
3597
- async getById(id) {
3598
- const c = await store.read((tx) => repos.category.findById(tx, id));
3599
- if (!c) throw new NotFoundError2("category", id);
3600
- return c;
3601
- },
3602
- async getBySlug(slug) {
3603
- const c = await store.read((tx) => repos.category.findBySlug(tx, slug));
3604
- if (!c) throw new NotFoundError2("category", slug);
3605
- return c;
3606
- },
3607
- async create(input) {
3608
- audit.note("category.create");
3609
- if (!input.slug.trim()) throw new ValidationError3("Category slug is required");
3610
- return store.transaction(async (tx) => {
3611
- if (await repos.category.findBySlug(tx, input.slug)) {
3612
- throw new ValidationError3(`Category slug already exists: ${input.slug}`);
3613
- }
3614
- const now = /* @__PURE__ */ new Date();
3615
- const id = uuidv74();
3616
- audit.note("category.create", [{ type: "category", id }]);
3617
- const category = {
3618
- id,
3619
- parentId: input.parentId ?? null,
3620
- slug: input.slug,
3621
- name: input.name,
3622
- description: input.description ?? "",
3623
- position: input.position ?? 0,
3624
- createdAt: now.toISOString()
3625
- };
3626
- await repos.category.insert(tx, { ...category, createdAt: now });
3627
- await publisher.publish(EVT_CATEGORY_CREATED3, { category });
3628
- return category;
3629
- });
3630
- },
3631
- async update(id, input) {
3632
- return store.transaction(async (tx) => {
3633
- audit.note("category.update", [{ type: "category", id }]);
3634
- const existing = await repos.category.findById(tx, id);
3635
- if (!existing) throw new NotFoundError2("category", id);
3636
- await repos.category.update(tx, id, input);
3637
- const fresh = await repos.category.findById(tx, id);
3638
- await publisher.publish(EVT_CATEGORY_UPDATED3, { category: fresh });
3639
- return fresh;
3640
- });
3641
- },
3642
- async delete(id) {
3643
- await store.transaction(async (tx) => {
3644
- audit.note("category.delete", [{ type: "category", id }]);
3645
- const existing = await repos.category.findById(tx, id);
3646
- if (!existing) throw new NotFoundError2("category", id);
3647
- await repos.category.delete(tx, id);
3648
- await publisher.publish(EVT_CATEGORY_DELETED3, {
3649
- categoryId: existing.id,
3650
- slug: existing.slug
3651
- });
3652
- });
3653
- }
3630
+ confirmUrl: `${row.origin}/alerts/confirm?token=${token(row.confirmToken)}`,
3631
+ unsubscribeUrl: `${row.origin}/alerts/unsubscribe?token=${token(row.unsubscribeToken)}`,
3632
+ productUrl: `${row.origin}/product/${encodeURIComponent(product.slug)}`
3654
3633
  };
3655
3634
  }
3656
-
3657
- // src/services/cart-service.ts
3658
- import { v7 as uuidv75 } from "uuid";
3659
- import {
3660
- EVT_CART_CREATED,
3661
- EVT_CART_ITEM_ADDED,
3662
- EVT_CART_ITEM_REMOVED,
3663
- EVT_CART_UPDATED,
3664
- NotFoundError as NotFoundError3,
3665
- ValidationError as ValidationError4
3666
- } from "@nymbalhq/types";
3667
- var TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 30;
3668
- function calcSubtotal(items) {
3669
- return items.reduce((sum, item) => sum + item.priceMinor * item.qty, 0);
3670
- }
3671
- function createCartService(deps) {
3672
- const { store, carts: carts3, publisher, currency } = deps;
3673
- const ttlMs = (deps.ttlSeconds ?? TTL_SECONDS_DEFAULT) * 1e3;
3674
- const now = deps.now ?? (() => /* @__PURE__ */ new Date());
3675
- function live(cart, at) {
3676
- return cart !== null && Date.parse(cart.expiresAt) > at.getTime();
3677
- }
3678
- function written(cart, items, at) {
3679
- return {
3680
- ...cart,
3681
- items,
3682
- subtotalMinor: calcSubtotal(items),
3683
- updatedAt: at.toISOString(),
3684
- expiresAt: new Date(at.getTime() + ttlMs).toISOString()
3685
- };
3686
- }
3687
- async function requireCart(tx, token, at) {
3688
- const cart = await carts3.lock(tx, token);
3689
- if (!live(cart, at)) throw new NotFoundError3("cart", token);
3690
- return cart;
3691
- }
3692
- async function emitUpdated(cart) {
3693
- await publisher.publish(EVT_CART_UPDATED, {
3694
- cartId: cart.token,
3695
- itemCount: cart.items.reduce((n, i) => n + i.qty, 0),
3696
- totalMinor: cart.subtotalMinor
3697
- });
3698
- }
3699
- function command(token, change) {
3700
- return store.transaction(async (tx) => {
3701
- const at = now();
3702
- const next = await change(await requireCart(tx, token, at), at);
3703
- await carts3.put(tx, next);
3704
- await emitUpdated(next);
3705
- return next;
3635
+ async function registerAlertHandler(deps) {
3636
+ const { eventBus, email, logger, repos, alerts, storeName } = deps;
3637
+ const { store } = repos.processedEvent;
3638
+ const skipped = (subscriptionId, eventId) => logger.info({ subscriptionId, eventId }, "alert mail skipped: the address is suppressed");
3639
+ const onRequested = async (event) => {
3640
+ const key = `${event.id}:${event.payload.subscriptionId}`;
3641
+ const found = await store.read(async (tx) => {
3642
+ if (await repos.processedEvent.seen(tx, HANDLER, key)) return null;
3643
+ const row2 = await repos.alertSubscription.findById(tx, event.payload.subscriptionId);
3644
+ if (row2 === null || row2.status !== "pending") return null;
3645
+ if (await repos.emailSuppression.isSuppressed(tx, row2.email)) return "suppressed";
3646
+ const product2 = await repos.product.findById(tx, row2.productId);
3647
+ return product2 === null ? null : { row: row2, product: product2 };
3706
3648
  });
3707
- }
3708
- return {
3709
- async getOrCreate(token, customerId = null) {
3710
- return store.transaction(async (tx) => {
3711
- const at = now();
3712
- const { cart, created } = await carts3.create(tx, {
3713
- token: token ?? uuidv75(),
3714
- customerId,
3715
- items: [],
3716
- subtotalMinor: 0,
3717
- currency,
3718
- expiresAt: new Date(at.getTime() + ttlMs).toISOString(),
3719
- createdAt: at.toISOString(),
3720
- updatedAt: at.toISOString()
3721
- });
3722
- if (created) {
3723
- await publisher.publish(EVT_CART_CREATED, { cartId: cart.token, token: cart.token });
3724
- }
3725
- return cart;
3726
- });
3727
- },
3728
- async get(token) {
3729
- const at = now();
3730
- const cart = await store.read((tx) => carts3.findByToken(tx, token));
3731
- return live(cart, at) ? cart : null;
3732
- },
3733
- async addItem(token, item) {
3734
- return command(token, async (cart, at) => {
3735
- const qty = item.qty ?? 1;
3736
- if (qty <= 0) throw new ValidationError4(`qty must be positive, got ${qty}`);
3737
- const onCart = cart.items.some((i) => i.variantId === item.variantId);
3738
- const items = onCart ? cart.items.map((i) => i.variantId === item.variantId ? { ...i, qty: i.qty + qty } : i) : [
3739
- ...cart.items,
3740
- {
3741
- variantId: item.variantId,
3742
- productId: item.productId,
3743
- productName: item.productName,
3744
- variantName: item.variantName,
3745
- priceMinor: item.priceMinor,
3746
- imageUrl: item.imageUrl,
3747
- qty
3748
- }
3749
- ];
3750
- await publisher.publish(EVT_CART_ITEM_ADDED, {
3751
- cartId: cart.token,
3752
- variantId: item.variantId,
3753
- qty
3754
- });
3755
- return written(cart, items, at);
3756
- });
3757
- },
3758
- async updateItemQuantity(token, variantId, qty) {
3759
- if (qty < 0) throw new ValidationError4(`qty must be non-negative, got ${qty}`);
3760
- return command(token, async (cart, at) => {
3761
- if (!cart.items.some((i) => i.variantId === variantId)) {
3762
- throw new NotFoundError3("cart_item", variantId);
3763
- }
3764
- if (qty === 0) {
3765
- await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
3766
- return written(
3767
- cart,
3768
- cart.items.filter((i) => i.variantId !== variantId),
3769
- at
3770
- );
3771
- }
3772
- return written(
3773
- cart,
3774
- cart.items.map((i) => i.variantId === variantId ? { ...i, qty } : i),
3775
- at
3776
- );
3777
- });
3778
- },
3779
- async removeItem(token, variantId) {
3780
- return command(token, async (cart, at) => {
3781
- const items = cart.items.filter((i) => i.variantId !== variantId);
3782
- if (items.length < cart.items.length) {
3783
- await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
3784
- }
3785
- return written(cart, items, at);
3786
- });
3787
- },
3788
- async clear(token) {
3789
- return command(token, async (cart, at) => written(cart, [], at));
3790
- },
3791
- async attachCustomer(token, customerId) {
3792
- return command(token, async (cart, at) => ({ ...written(cart, cart.items, at), customerId }));
3793
- },
3794
- async merge(guestToken, customerToken) {
3795
- return store.transaction(async (tx) => {
3796
- const at = now();
3797
- const guest = await carts3.lock(tx, guestToken);
3798
- if (!live(guest, at)) return requireCart(tx, customerToken, at);
3799
- const customerCart = await carts3.lock(tx, customerToken);
3800
- let merged;
3801
- if (live(customerCart, at)) {
3802
- const held = customerCart.items;
3803
- const items = [
3804
- ...held.map((i) => {
3805
- const g = guest.items.find((x) => x.variantId === i.variantId);
3806
- return g ? { ...i, qty: Math.max(i.qty, g.qty) } : i;
3807
- }),
3808
- ...guest.items.filter((g) => !held.some((i) => i.variantId === g.variantId))
3809
- ];
3810
- merged = written(customerCart, items, at);
3811
- } else {
3812
- merged = written({ ...guest, token: customerToken }, guest.items, at);
3813
- }
3814
- await carts3.remove(tx, guestToken);
3815
- await carts3.put(tx, merged);
3816
- await emitUpdated(merged);
3817
- return merged;
3818
- });
3819
- }
3820
- };
3821
- }
3822
-
3823
- // src/services/customer-service.ts
3824
- import { v7 as uuidv76 } from "uuid";
3825
- import {
3826
- EVT_CUSTOMER_UPDATED as EVT_CUSTOMER_UPDATED2,
3827
- NotFoundError as NotFoundError4,
3828
- ValidationError as ValidationError5
3829
- } from "@nymbalhq/types";
3830
- function stripPassword(c) {
3831
- const { passwordHash: _pw, ...rest } = c;
3832
- return rest;
3833
- }
3834
- function createCustomerService(deps) {
3835
- const { repos, publisher } = deps;
3836
- const { store } = repos.customer;
3837
- async function loadOrThrow(tx, id) {
3838
- const c = await repos.customer.findById(tx, id);
3839
- if (!c) throw new NotFoundError4("customer", id);
3840
- return c;
3841
- }
3842
- async function publishUpdated(tx, customerId) {
3843
- const fresh = stripPassword(await loadOrThrow(tx, customerId));
3844
- await publisher.publish(EVT_CUSTOMER_UPDATED2, {
3845
- customerId,
3846
- customer: toCustomerSnapshot(fresh)
3649
+ if (found === null) return;
3650
+ if (found === "suppressed") return skipped(event.payload.subscriptionId, event.id);
3651
+ const { row, product } = found;
3652
+ const { confirmUrl, unsubscribeUrl, productUrl } = links(row, product);
3653
+ await email.sendTransactional({
3654
+ template: row.kind === "price_drop" ? "alert-confirm-price-drop" : "alert-confirm",
3655
+ to: row.email,
3656
+ vars: { storeName, productName: product.name, productUrl, confirmUrl, unsubscribeUrl }
3847
3657
  });
3848
- return fresh;
3849
- }
3850
- return {
3851
- async getProfile(customerId) {
3852
- return stripPassword(await store.read((tx) => loadOrThrow(tx, customerId)));
3853
- },
3854
- async updateProfile(customerId, patch) {
3855
- return store.transaction(async (tx) => {
3856
- audit.note("customer.update", [{ type: "customer", id: customerId }]);
3857
- await loadOrThrow(tx, customerId);
3858
- const now = /* @__PURE__ */ new Date();
3859
- await repos.customer.update(tx, customerId, { ...patch, updatedAt: now });
3860
- return publishUpdated(tx, customerId);
3861
- });
3862
- },
3863
- async listAddresses(customerId) {
3864
- const customer = await store.read((tx) => loadOrThrow(tx, customerId));
3865
- return customer.addresses;
3866
- },
3867
- async addAddress(customerId, addr) {
3868
- return store.transaction(async (tx) => {
3869
- audit.note("customer.addAddress", [{ type: "customer", id: customerId }]);
3870
- const customer = await loadOrThrow(tx, customerId);
3871
- const newAddr = { ...addr, id: uuidv76() };
3872
- const defaultBilling = newAddr.isDefaultBilling;
3873
- const defaultShipping = newAddr.isDefaultShipping;
3874
- const addresses = customer.addresses.map((a) => ({
3875
- ...a,
3876
- isDefaultBilling: defaultBilling ? false : a.isDefaultBilling,
3877
- isDefaultShipping: defaultShipping ? false : a.isDefaultShipping
3878
- }));
3879
- addresses.push(newAddr);
3880
- const now = /* @__PURE__ */ new Date();
3881
- await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
3882
- await publishUpdated(tx, customerId);
3883
- return newAddr;
3884
- });
3885
- },
3886
- async deleteAddress(customerId, addressId) {
3887
- await store.transaction(async (tx) => {
3888
- audit.note("customer.removeAddress", [{ type: "customer", id: customerId }]);
3889
- const customer = await loadOrThrow(tx, customerId);
3890
- const addresses = customer.addresses.filter((a) => a.id !== addressId);
3891
- if (addresses.length === customer.addresses.length) {
3892
- throw new NotFoundError4("address", addressId);
3893
- }
3894
- if (!addresses.length) {
3895
- throw new ValidationError5("Cannot remove last address");
3896
- }
3897
- const now = /* @__PURE__ */ new Date();
3898
- await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
3899
- await publishUpdated(tx, customerId);
3900
- });
3901
- }
3902
- };
3903
- }
3904
-
3905
- // src/services/auth-service.ts
3906
- import { v7 as uuidv77 } from "uuid";
3907
- import bcrypt from "bcryptjs";
3908
- import { SignJWT, jwtVerify } from "jose";
3909
- import { createHash } from "crypto";
3910
- import {
3911
- AuthError,
3912
- EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED3,
3913
- ValidationError as ValidationError6
3914
- } from "@nymbalhq/types";
3915
- var { hash: bcryptHash, compare: bcryptCompare } = bcrypt;
3916
- function parseDurationToMs(s) {
3917
- const match = /^(\d+)(ms|s|m|h|d)$/.exec(s);
3918
- if (!match) throw new ValidationError6(`invalid duration: ${s}`);
3919
- const qty = Number(match[1]);
3920
- switch (match[2]) {
3921
- case "ms":
3922
- return qty;
3923
- case "s":
3924
- return qty * 1e3;
3925
- case "m":
3926
- return qty * 60 * 1e3;
3927
- case "h":
3928
- return qty * 60 * 60 * 1e3;
3929
- case "d":
3930
- return qty * 24 * 60 * 60 * 1e3;
3931
- /* c8 ignore next 2 -- regex above only matches ms|s|m|h|d, making this unreachable */
3932
- default:
3933
- throw new ValidationError6(`invalid duration unit: ${match[2]}`);
3934
- }
3935
- }
3936
- function hashRefresh(token) {
3937
- return createHash("sha256").update(token).digest("hex");
3938
- }
3939
- function stripPassword2(c) {
3940
- const { passwordHash: _pw, ...rest } = c;
3941
- return rest;
3942
- }
3943
- function createAuthService(deps) {
3944
- const { repos, publisher, logger, jwtSecret, accessTtl, refreshTtl } = deps;
3945
- const { store } = repos.customer;
3946
- const issuer = deps.issuer ?? "nymbal";
3947
- const secretKey = new TextEncoder().encode(jwtSecret);
3948
- const accessTtlMs = parseDurationToMs(accessTtl);
3949
- const refreshTtlMs = parseDurationToMs(refreshTtl);
3950
- async function mintAccess(customer) {
3951
- return new SignJWT({
3952
- sub: customer.id,
3953
- email: customer.email,
3954
- roles: customer.roles,
3955
- type: "access"
3956
- }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setIssuer(issuer).setExpirationTime(new Date(Date.now() + accessTtlMs)).sign(secretKey);
3957
- }
3958
- async function mintRefresh(customer, jti) {
3959
- return new SignJWT({
3960
- sub: customer.id,
3961
- email: customer.email,
3962
- roles: ["customer"],
3963
- type: "refresh",
3964
- jti
3965
- }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setJti(jti).setIssuer(issuer).setExpirationTime(new Date(Date.now() + refreshTtlMs)).sign(secretKey);
3966
- }
3967
- async function issueTokens(customer) {
3968
- const jti = uuidv77();
3969
- const refreshToken = await mintRefresh(customer, jti);
3970
3658
  await store.transaction(
3971
- (tx) => repos.refreshToken.insert(tx, {
3972
- id: jti,
3973
- customerId: customer.id,
3974
- tokenHash: hashRefresh(refreshToken),
3975
- expiresAt: new Date(Date.now() + refreshTtlMs),
3976
- createdAt: /* @__PURE__ */ new Date()
3977
- })
3659
+ (tx) => repos.processedEvent.markProcessed(tx, HANDLER, key, /* @__PURE__ */ new Date())
3978
3660
  );
3979
- const accessToken = await mintAccess(customer);
3980
- return {
3981
- accessToken,
3982
- refreshToken,
3983
- expiresIn: Math.floor(accessTtlMs / 1e3)
3984
- };
3985
- }
3986
- return {
3987
- async register(input) {
3988
- audit.note("customer.register");
3989
- if (!input.email.includes("@")) throw new ValidationError6("invalid email");
3990
- if (input.password.length < 8) throw new ValidationError6("password must be \u2265 8 characters");
3991
- const email = input.email.toLowerCase();
3992
- const existing = await store.read((tx) => repos.customer.findByEmail(tx, email));
3993
- if (existing) {
3994
- throw new AuthError("invalid_credentials", "An account with this email already exists");
3995
- }
3996
- const id = uuidv77();
3997
- const passwordHash = await bcryptHash(input.password, 10);
3998
- const now = /* @__PURE__ */ new Date();
3999
- const customer = await store.transaction(async (tx) => {
4000
- audit.note("customer.register", [{ type: "customer", id }]);
4001
- await repos.customer.insert(tx, {
4002
- id,
4003
- email,
4004
- passwordHash,
4005
- ...input.firstName !== void 0 && { firstName: input.firstName },
4006
- ...input.lastName !== void 0 && { lastName: input.lastName },
4007
- ...input.phone !== void 0 && { phone: input.phone },
4008
- createdAt: now,
4009
- updatedAt: now
4010
- });
4011
- const inserted = await repos.customer.findById(tx, id);
4012
- if (!inserted) throw new Error("customer disappeared after insert");
4013
- await publisher.publish(EVT_CUSTOMER_CREATED3, {
4014
- customerId: id,
4015
- email,
4016
- customer: toCustomerSnapshot(inserted)
4017
- });
4018
- return inserted;
4019
- });
4020
- const tokens = await issueTokens(customer);
4021
- logger.info({ customerId: id }, "customer registered");
4022
- return { customer: stripPassword2(customer), tokens };
4023
- },
4024
- async login(email, password) {
4025
- const customer = await store.read((tx) => repos.customer.findByEmail(tx, email.toLowerCase()));
4026
- if (!customer) throw new AuthError("invalid_credentials", "Invalid email or password");
4027
- const ok = await bcryptCompare(password, customer.passwordHash);
4028
- if (!ok) throw new AuthError("invalid_credentials", "Invalid email or password");
4029
- const tokens = await issueTokens(customer);
4030
- logger.info({ customerId: customer.id }, "customer login");
4031
- return { customer: stripPassword2(customer), tokens };
4032
- },
4033
- async refresh(refreshToken) {
4034
- let verified;
4035
- try {
4036
- verified = await jwtVerify(refreshToken, secretKey, { issuer });
4037
- } catch {
4038
- throw new AuthError("token_invalid", "refresh token invalid");
4039
- }
4040
- const payload = verified.payload;
4041
- if (payload.type !== "refresh" || !payload.jti || !payload.sub) {
4042
- throw new AuthError("token_invalid", "not a refresh token");
4043
- }
4044
- const jti = payload.jti;
4045
- const customerId = payload.sub;
4046
- const record = await store.read((tx) => repos.refreshToken.findById(tx, jti));
4047
- if (!record) throw new AuthError("token_invalid", "refresh token unknown");
4048
- if (record.revokedAt) throw new AuthError("token_invalid", "refresh token revoked");
4049
- if (record.tokenHash !== hashRefresh(refreshToken)) {
4050
- await store.transaction((tx) => repos.refreshToken.revokeAllForCustomer(tx, customerId));
4051
- throw new AuthError("token_invalid", "refresh token mismatch; revoking chain");
4052
- }
4053
- const customer = await store.read((tx) => repos.customer.findById(tx, customerId));
4054
- if (!customer) throw new AuthError("token_invalid", "customer missing");
4055
- const nextJti = uuidv77();
4056
- const nextRefresh = await mintRefresh(customer, nextJti);
4057
- await store.transaction(
4058
- (tx) => repos.refreshToken.rotate(tx, jti, {
4059
- id: nextJti,
4060
- customerId: customer.id,
4061
- tokenHash: hashRefresh(nextRefresh),
4062
- expiresAt: new Date(Date.now() + refreshTtlMs),
4063
- createdAt: /* @__PURE__ */ new Date()
4064
- })
4065
- );
4066
- const accessToken = await mintAccess(customer);
4067
- return {
4068
- accessToken,
4069
- refreshToken: nextRefresh,
4070
- expiresIn: Math.floor(accessTtlMs / 1e3)
4071
- };
4072
- },
4073
- async logout(refreshToken) {
4074
- try {
4075
- const verified = await jwtVerify(refreshToken, secretKey, { issuer });
4076
- const payload = verified.payload;
4077
- const { jti } = payload;
4078
- if (jti) await store.transaction((tx) => repos.refreshToken.revoke(tx, jti));
4079
- } catch {
4080
- }
4081
- },
4082
- async verifyAccessToken(token) {
4083
- try {
4084
- const verified = await jwtVerify(token, secretKey, { issuer });
4085
- const payload = verified.payload;
4086
- if (payload.type !== "access") throw new AuthError("token_invalid", "not an access token");
4087
- return payload;
4088
- } catch (err) {
4089
- if (err instanceof AuthError) throw err;
4090
- throw new AuthError("token_invalid", "access token invalid", { cause: err });
4091
- }
4092
- },
4093
- async importCustomer(input) {
4094
- if (!input.email.includes("@")) throw new ValidationError6("invalid email");
4095
- const email = input.email.toLowerCase();
4096
- const customer = await store.transaction(async (tx) => {
4097
- const existing = await repos.customer.findByEmail(tx, email);
4098
- if (existing) return existing;
4099
- const id = uuidv77();
4100
- audit.note("customer.import", [{ type: "customer", id }]);
4101
- const now = /* @__PURE__ */ new Date();
4102
- await repos.customer.insert(tx, {
4103
- id,
4104
- email,
4105
- passwordHash: "IMPORTED_NO_PASSWORD",
4106
- requiresPasswordReset: true,
4107
- ...input.firstName !== void 0 && { firstName: input.firstName },
4108
- ...input.lastName !== void 0 && { lastName: input.lastName },
4109
- ...input.phone !== void 0 && { phone: input.phone },
4110
- ...input.addresses !== void 0 && { addresses: input.addresses },
4111
- ...input.metadata !== void 0 && { metadata: input.metadata },
4112
- roles: ["customer"],
4113
- createdAt: now,
4114
- updatedAt: now
4115
- });
4116
- const inserted = await repos.customer.findById(tx, id);
4117
- if (!inserted) throw new Error("customer disappeared after insert");
4118
- await publisher.publish(EVT_CUSTOMER_CREATED3, {
4119
- customerId: id,
4120
- email,
4121
- customer: toCustomerSnapshot(inserted)
4122
- });
4123
- logger.info({ customerId: id }, "customer imported");
4124
- return inserted;
4125
- });
4126
- return stripPassword2(customer);
4127
- }
4128
3661
  };
4129
- }
4130
-
4131
- // src/services/order-service.ts
4132
- import { v7 as uuidv78 } from "uuid";
4133
- import {
4134
- EVT_ORDER_CANCELLED as EVT_ORDER_CANCELLED2,
4135
- EVT_ORDER_DELIVERED as EVT_ORDER_DELIVERED3,
4136
- EVT_ORDER_PLACED as EVT_ORDER_PLACED2,
4137
- EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED3,
4138
- EVT_ORDER_STATUS_CHANGED as EVT_ORDER_STATUS_CHANGED2,
4139
- NotFoundError as NotFoundError5,
4140
- OrderConflictError,
4141
- StatusTransitionError,
4142
- ValidationError as ValidationError7,
4143
- assertOrderTransition
4144
- } from "@nymbalhq/types";
4145
- function createOrderService(deps) {
4146
- const { store, repos, publisher } = deps;
4147
- async function requireOrder(tx, id) {
4148
- const order = await repos.order.findById(tx, id);
4149
- if (!order) throw new NotFoundError5("order", id);
4150
- return order;
4151
- }
4152
- async function doTransition(tx, order, toStatus, actor, note) {
4153
- assertOrderTransition(order.status, toStatus);
4154
- const now = /* @__PURE__ */ new Date();
4155
- await repos.order.setStatus(tx, order.id, toStatus, now);
4156
- await repos.orderHistory.append(tx, {
4157
- id: uuidv78(),
4158
- orderId: order.id,
4159
- fromStatus: order.status,
4160
- toStatus,
4161
- actor,
4162
- note,
4163
- timestamp: now
4164
- });
4165
- return requireOrder(tx, order.id);
4166
- }
4167
- return {
4168
- async createFromCheckout(input) {
4169
- return store.transaction(async (tx) => {
4170
- audit.note("order.place", [{ type: "order", id: input.orderId }]);
4171
- const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
4172
- const orderNumber = `${deps.orderNumberPrefix}-${sequence + 1}`;
4173
- const now = /* @__PURE__ */ new Date();
4174
- await repos.order.insert(tx, {
4175
- id: input.orderId,
4176
- orderNumber,
4177
- sequence,
4178
- customerId: input.customerId,
4179
- status: "pending",
4180
- email: input.email,
4181
- billingAddress: input.billingAddress,
4182
- shippingAddress: input.shippingAddress,
4183
- lineItems: input.lineItems,
4184
- subtotalMinor: input.subtotalMinor,
4185
- taxTotalMinor: input.taxTotalMinor,
4186
- shippingTotalMinor: input.shippingTotalMinor,
4187
- discountTotalMinor: input.discountTotalMinor,
4188
- totalMinor: input.totalMinor,
4189
- currency: input.currency,
4190
- notes: input.notes ?? "",
4191
- metadata: input.metadata ?? {},
4192
- paymentIntentId: input.paymentIntentId ?? null,
4193
- cartToken: input.cartToken ?? null,
4194
- createdAt: now,
4195
- updatedAt: now
4196
- });
4197
- await repos.orderHistory.append(tx, {
4198
- id: uuidv78(),
4199
- orderId: input.orderId,
4200
- fromStatus: null,
4201
- toStatus: "pending",
4202
- actor: "system:checkout",
4203
- note: "order draft created",
4204
- timestamp: now
4205
- });
4206
- const fresh = await requireOrder(tx, input.orderId);
4207
- await publisher.publish(EVT_ORDER_PLACED2, { order: fresh });
4208
- return fresh;
4209
- });
4210
- },
4211
- async getById(id) {
4212
- return store.read((tx) => requireOrder(tx, id));
4213
- },
4214
- async getByOrderNumber(orderNumber) {
4215
- const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
4216
- if (!order) throw new NotFoundError5("order", orderNumber);
4217
- return order;
4218
- },
4219
- async listByCustomer(customerId) {
4220
- return store.read((tx) => repos.order.listByCustomer(tx, customerId));
4221
- },
4222
- async updateStatus(id, toStatus, actor, note = "") {
4223
- return store.transaction(async (tx) => {
4224
- audit.note("order.updateStatus", [{ type: "order", id }]);
4225
- const order = await requireOrder(tx, id);
4226
- const fresh = await doTransition(tx, order, toStatus, actor, note);
4227
- await publisher.publish(EVT_ORDER_STATUS_CHANGED2, {
4228
- orderId: fresh.id,
4229
- from: order.status,
4230
- to: fresh.status
4231
- });
4232
- return fresh;
4233
- });
4234
- },
4235
- async markShipped(id, trackingNumber, carrier, actor) {
4236
- return store.transaction(async (tx) => {
4237
- audit.note("order.ship", [{ type: "order", id }]);
4238
- const order = await requireOrder(tx, id);
4239
- const fresh = await doTransition(
4240
- tx,
4241
- order,
4242
- "shipped",
4243
- actor,
4244
- `Shipped via ${carrier}: ${trackingNumber}`
4245
- );
4246
- await publisher.publish(EVT_ORDER_SHIPPED3, {
4247
- orderId: fresh.id,
4248
- trackingNumber,
4249
- carrier
4250
- });
4251
- return fresh;
4252
- });
4253
- },
4254
- async markDelivered(id, actor) {
4255
- return store.transaction(async (tx) => {
4256
- audit.note("order.markDelivered", [{ type: "order", id }]);
4257
- const order = await requireOrder(tx, id);
4258
- const fresh = await doTransition(tx, order, "delivered", actor, "Delivered");
4259
- await publisher.publish(EVT_ORDER_DELIVERED3, { orderId: fresh.id });
4260
- return fresh;
4261
- });
4262
- },
4263
- async cancel(id, reason, actor) {
4264
- return store.transaction(async (tx) => {
4265
- audit.note("order.cancel", [{ type: "order", id }]);
4266
- const order = await repos.order.lock(tx, id);
4267
- if (!order) throw new NotFoundError5("order", id);
4268
- if (order.capturedMinor > 0) {
4269
- throw new OrderConflictError(
4270
- "order.paid",
4271
- `Order ${order.orderNumber} is paid: refund it instead of cancelling`
4272
- );
4273
- }
4274
- assertOrderTransition(order.status, "cancelled");
4275
- const now = /* @__PURE__ */ new Date();
4276
- if (!await repos.order.setStatusIf(tx, order.id, order.status, "cancelled", now)) {
4277
- const current = await requireOrder(tx, order.id);
4278
- throw new StatusTransitionError("order", current.status, "cancelled");
4279
- }
4280
- await repos.orderHistory.append(tx, {
4281
- id: uuidv78(),
4282
- orderId: order.id,
4283
- fromStatus: order.status,
4284
- toStatus: "cancelled",
4285
- actor,
4286
- note: reason,
4287
- timestamp: now
4288
- });
4289
- const fresh = await requireOrder(tx, order.id);
4290
- await publisher.publish(EVT_ORDER_CANCELLED2, { orderId: fresh.id, reason });
4291
- return fresh;
4292
- });
4293
- },
4294
- async importOrder(input) {
4295
- const capturedMinor = input.capturedMinor ?? 0;
4296
- const refundedMinor = input.refundedMinor ?? 0;
4297
- if (!(0 <= refundedMinor && refundedMinor <= capturedMinor && capturedMinor <= input.totalMinor) || capturedMinor > 0 !== (input.captureMethod != null)) {
4298
- throw new ValidationError7("imported payment amounts are inconsistent", {
4299
- context: { capturedMinor, refundedMinor, totalMinor: input.totalMinor }
4300
- });
4301
- }
4302
- return store.transaction(async (tx) => {
4303
- audit.note("order.import", [{ type: "order", id: input.orderId }]);
4304
- const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
4305
- await repos.order.insert(tx, {
4306
- id: input.orderId,
4307
- orderNumber: input.orderNumber,
4308
- sequence,
4309
- customerId: input.customerId,
4310
- status: input.status,
4311
- email: input.email,
4312
- billingAddress: input.billingAddress,
4313
- shippingAddress: input.shippingAddress,
4314
- lineItems: input.lineItems,
4315
- subtotalMinor: input.subtotalMinor,
4316
- taxTotalMinor: input.taxTotalMinor,
4317
- shippingTotalMinor: input.shippingTotalMinor,
4318
- discountTotalMinor: input.discountTotalMinor,
4319
- totalMinor: input.totalMinor,
4320
- currency: input.currency,
4321
- notes: input.notes ?? "",
4322
- metadata: input.metadata ?? {},
4323
- paymentIntentId: input.paymentIntentId ?? null,
4324
- ...input.captureMethod != null && {
4325
- capture: {
4326
- amountMinor: capturedMinor,
4327
- method: input.captureMethod,
4328
- at: input.createdAt,
4329
- refundedMinor
4330
- }
4331
- },
4332
- createdAt: input.createdAt,
4333
- updatedAt: input.createdAt
4334
- });
4335
- const fresh = await requireOrder(tx, input.orderId);
4336
- await publisher.publish(EVT_ORDER_PLACED2, { order: fresh });
4337
- return fresh;
4338
- });
4339
- }
4340
- };
4341
- }
4342
-
4343
- // src/services/inventory-service.ts
4344
- import { v7 as uuidv79 } from "uuid";
4345
- import {
4346
- AdapterError as AdapterError2,
4347
- NotFoundError as NotFoundError6,
4348
- ValidationError as ValidationError8,
4349
- EVT_INVENTORY_CHANGED as EVT_INVENTORY_CHANGED2,
4350
- EVT_INVENTORY_RESERVED,
4351
- EVT_INVENTORY_RELEASED,
4352
- EVT_INVENTORY_LOW_STOCK,
4353
- EVT_INVENTORY_OUT_OF_STOCK
4354
- } from "@nymbalhq/types";
4355
- function classifyStock(stock, threshold) {
4356
- if (stock <= 0) return "out_of_stock";
4357
- if (stock <= threshold) return "low_stock";
4358
- return "in_stock";
4359
- }
4360
- function createInventoryService(deps) {
4361
- const { store, repos, publisher, logger } = deps;
4362
- const defaultTtl = deps.defaultReservationTtlSeconds ?? 15 * 60;
4363
- async function emitThresholdEvents(variantId, newQty, threshold) {
4364
- if (newQty <= 0) {
4365
- await publisher.publish(EVT_INVENTORY_OUT_OF_STOCK, { variantId });
4366
- } else if (newQty <= threshold) {
4367
- await publisher.publish(EVT_INVENTORY_LOW_STOCK, {
4368
- variantId,
4369
- currentQty: newQty,
4370
- threshold
4371
- });
4372
- }
4373
- }
4374
- async function take(variantId, qty, orderRef, ttlSeconds) {
4375
- if (qty <= 0) throw new ValidationError8(`Reservation qty must be positive, got ${qty}`);
4376
- return store.transaction(async (tx) => {
4377
- audit.note("inventory.reserve", [{ type: "variant", id: variantId }]);
4378
- const variant = await repos.variant.findById(tx, variantId);
4379
- if (!variant) throw new NotFoundError6("variant", variantId);
4380
- const now = /* @__PURE__ */ new Date();
4381
- const remaining = await repos.variant.decrementStock(tx, variant.id, qty, now);
4382
- if (remaining === null) return { available: variant.stock };
4383
- const expiresAt = new Date(now.getTime() + (ttlSeconds ?? defaultTtl) * 1e3);
4384
- const reservationId = uuidv79();
4385
- await repos.inventoryReservation.insert(tx, {
4386
- reservationId,
4387
- variantId: variant.id,
4388
- qty,
4389
- orderRef,
4390
- expiresAt,
4391
- createdAt: now
4392
- });
4393
- await publisher.publish(EVT_INVENTORY_RESERVED, {
4394
- variantId: variant.id,
4395
- qty,
4396
- reservationId,
4397
- expiresAt: expiresAt.toISOString()
4398
- });
4399
- await publisher.publish(EVT_INVENTORY_CHANGED2, {
4400
- variantId: variant.id,
4401
- previousQty: remaining + qty,
4402
- newQty: remaining,
4403
- reason: "manual"
3662
+ async function fanOut(event, rows, what, message) {
3663
+ const failed = [];
3664
+ for (const row of rows) {
3665
+ const key = `${event.id}:${row.id}`;
3666
+ const skip = await store.read(async (tx) => {
3667
+ if (await repos.processedEvent.seen(tx, HANDLER, key)) return "sent";
3668
+ return await repos.emailSuppression.isSuppressed(tx, row.email) ? "suppressed" : null;
4404
3669
  });
4405
- await emitThresholdEvents(variant.id, remaining, variant.lowStockThreshold);
4406
- return { reservationId, expiresAt: expiresAt.toISOString() };
4407
- });
4408
- }
4409
- return {
4410
- async adjustStock(variantId, delta, reason, actor) {
4411
- return store.transaction(async (tx) => {
4412
- audit.note("inventory.adjust", [{ type: "variant", id: variantId }]);
4413
- const variant = await repos.variant.findById(tx, variantId);
4414
- if (!variant) throw new NotFoundError6("variant", variantId);
4415
- const now = /* @__PURE__ */ new Date();
4416
- const newQty = delta < 0 ? await repos.variant.decrementStock(tx, variant.id, -delta, now) : await repos.variant.incrementStock(tx, variant.id, delta, now);
4417
- if (newQty === null) {
4418
- throw new ValidationError8(`Cannot reduce stock below zero (variant ${variantId})`, {
4419
- context: { variantId, stock: variant.stock, delta }
4420
- });
4421
- }
4422
- const previousQty = newQty - delta;
4423
- await repos.stockAdjustment.append(tx, {
4424
- id: uuidv79(),
4425
- variantId: variant.id,
4426
- adjustment: delta,
4427
- reason,
4428
- actor,
4429
- previousQty,
4430
- newQty,
4431
- timestamp: now
4432
- });
4433
- await publisher.publish(EVT_INVENTORY_CHANGED2, {
4434
- variantId: variant.id,
4435
- previousQty,
4436
- newQty,
4437
- reason
4438
- });
4439
- await emitThresholdEvents(variant.id, newQty, variant.lowStockThreshold);
4440
- logger.debug({ variantId, delta, newQty, reason }, "stock adjusted");
4441
- return { newQty };
4442
- });
4443
- },
4444
- async reserveStock(variantId, qty, orderRef = null, ttlSeconds) {
4445
- const taken = await take(variantId, qty, orderRef, ttlSeconds);
4446
- if ("available" in taken) {
4447
- throw new AdapterError2(
4448
- "inventory.insufficient",
4449
- `Insufficient stock for variant ${variantId}`,
4450
- {
4451
- context: { variantId, requested: qty, available: taken.available }
4452
- }
4453
- );
4454
- }
4455
- return taken;
4456
- },
4457
- async tryReserveStock(variantId, qty, orderRef = null, ttlSeconds) {
4458
- const taken = await take(variantId, qty, orderRef, ttlSeconds);
4459
- return "available" in taken ? null : taken;
4460
- },
4461
- async releaseReservation(reservationId, reason) {
4462
- await store.transaction(async (tx) => {
4463
- const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
4464
- if (!reservation) {
4465
- logger.debug(
4466
- { reservationId },
4467
- "reservation already released, committed or never existed"
4468
- );
4469
- return;
4470
- }
4471
- audit.note("inventory.release", [{ type: "variant", id: reservation.variantId }]);
4472
- const now = /* @__PURE__ */ new Date();
4473
- const newQty = await repos.variant.incrementStock(
4474
- tx,
4475
- reservation.variantId,
4476
- reservation.qty,
4477
- now
4478
- );
4479
- if (newQty !== null) {
4480
- const previousQty = newQty - reservation.qty;
4481
- await repos.stockAdjustment.append(tx, {
4482
- id: uuidv79(),
4483
- variantId: reservation.variantId,
4484
- adjustment: reservation.qty,
4485
- reason: "reservation-release",
4486
- actor: `system:release:${reason}`,
4487
- previousQty,
4488
- newQty,
4489
- timestamp: now
4490
- });
4491
- await publisher.publish(EVT_INVENTORY_CHANGED2, {
4492
- variantId: reservation.variantId,
4493
- previousQty,
4494
- newQty,
4495
- reason: "reservation-release"
4496
- });
4497
- }
4498
- await publisher.publish(EVT_INVENTORY_RELEASED, {
4499
- variantId: reservation.variantId,
4500
- qty: reservation.qty,
4501
- reservationId: reservation.reservationId,
4502
- reason
4503
- });
4504
- });
4505
- },
4506
- async commitReservation(reservationId, actor) {
4507
- await store.transaction(async (tx) => {
4508
- const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
4509
- if (!reservation) throw new NotFoundError6("reservation", reservationId);
4510
- audit.note("inventory.commit", [{ type: "variant", id: reservation.variantId }]);
4511
- const variant = await repos.variant.findById(tx, reservation.variantId);
4512
- if (!variant) throw new NotFoundError6("variant", reservation.variantId);
4513
- await repos.stockAdjustment.append(tx, {
4514
- id: uuidv79(),
4515
- variantId: variant.id,
4516
- adjustment: -reservation.qty,
4517
- reason: "reservation-commit",
4518
- actor,
4519
- previousQty: variant.stock + reservation.qty,
4520
- newQty: variant.stock,
4521
- timestamp: /* @__PURE__ */ new Date()
4522
- });
4523
- await publisher.publish(EVT_INVENTORY_RELEASED, {
4524
- variantId: reservation.variantId,
4525
- qty: reservation.qty,
4526
- reservationId: reservation.reservationId,
4527
- reason: "committed"
3670
+ if (skip === "suppressed") skipped(row.id, event.id);
3671
+ if (skip !== null) continue;
3672
+ try {
3673
+ await email.sendTransactional({ ...message(row), to: row.email });
3674
+ await store.transaction(async (tx) => {
3675
+ await repos.processedEvent.markProcessed(tx, HANDLER, key, /* @__PURE__ */ new Date());
3676
+ await alerts.recordSent(tx, row, event);
4528
3677
  });
4529
- });
4530
- },
4531
- async getStockStatus(variantId) {
4532
- const variant = await store.read((tx) => repos.variant.findById(tx, variantId));
4533
- if (!variant) throw new NotFoundError6("variant", variantId);
4534
- return {
4535
- stock: variant.stock,
4536
- threshold: variant.lowStockThreshold,
4537
- status: classifyStock(variant.stock, variant.lowStockThreshold)
4538
- };
4539
- }
4540
- };
4541
- }
4542
-
4543
- // src/services/checkout-service.ts
4544
- import { v5 as uuidv5, v7 as uuidv710 } from "uuid";
4545
- import {
4546
- CheckoutError,
4547
- EVT_CART_CONVERTED,
4548
- EVT_CART_UPDATED as EVT_CART_UPDATED2,
4549
- EVT_ORDER_PAID as EVT_ORDER_PAID4,
4550
- EVT_PAYMENT_CAPTURED,
4551
- EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED2,
4552
- EVT_PAYMENT_INTENT_CREATED as EVT_PAYMENT_INTENT_CREATED2,
4553
- EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED2,
4554
- NotFoundError as NotFoundError7,
4555
- OrderConflictError as OrderConflictError2,
4556
- PaymentError,
4557
- StatusTransitionError as StatusTransitionError2
4558
- } from "@nymbalhq/types";
4559
- var StockUnavailable = class extends Error {
4560
- constructor(variantId) {
4561
- super(`stock unavailable for variant ${variantId}`);
4562
- this.variantId = variantId;
4563
- }
4564
- variantId;
4565
- };
4566
- var NoLongerPending = class extends Error {
4567
- };
4568
- var PROVIDER_CAPTURE = {
4569
- method: "provider",
4570
- actor: "system:checkout",
4571
- note: "payment captured"
4572
- };
4573
- var FINALIZE_ACTOR = "system:checkout-finalize";
4574
- var CANCEL_ACTOR = "system:checkout-cancel";
4575
- var DUPLICATE_CAPTURE = "duplicate_capture_refunded";
4576
- var DUPLICATE_CAPTURE_HANDLER = "checkout:duplicate-capture";
4577
- var CAPTURE_REFUND_NAMESPACE = "49e623d3-5784-4331-80e9-6f951d97f7c0";
4578
- var SUPERSEDE_ATTEMPTS = 3;
4579
- var ABANDON_AFTER_MS = 12e4;
4580
- function outcomeOf(status) {
4581
- if (status === "succeeded") return "succeeded";
4582
- if (status === "failed" || status === "cancelled") return "failed";
4583
- return "requires_action";
4584
- }
4585
- function sameLines(order, cart) {
4586
- if (order.totalMinor !== cart.subtotalMinor || order.currency !== cart.currency) return false;
4587
- if (order.lineItems.length !== cart.items.length) return false;
4588
- return cart.items.every((item, i) => {
4589
- const line = order.lineItems[i];
4590
- return line?.variantId === item.variantId && line.qty === item.qty && line.unitPriceMinor === item.priceMinor;
4591
- });
4592
- }
4593
- function createCheckoutService(deps) {
4594
- const { store, repos, publisher, logger, cart, orders: orders4, inventory, payments, currency } = deps;
4595
- async function cartEmpty(token) {
4596
- const converted = await store.read((tx) => repos.order.findLastConvertedByCartToken(tx, token));
4597
- return new CheckoutError(
4598
- "cart_empty",
4599
- "Cart has no items",
4600
- converted ? { context: { orderNumber: converted.orderNumber } } : {}
4601
- );
4602
- }
4603
- async function loadValidCart(token) {
4604
- const c = await cart.get(token);
4605
- if (!c) throw new NotFoundError7("cart", token);
4606
- if (!c.items.length) throw await cartEmpty(token);
4607
- if (c.currency !== currency) {
4608
- throw new CheckoutError(
4609
- "cart_empty",
4610
- `Cart currency ${c.currency} does not match store currency ${currency}`
4611
- );
4612
- }
4613
- return c;
4614
- }
4615
- async function settled(tx, paymentIntentId, order, paid) {
4616
- if (order === null) return recordOutcome(tx, paymentIntentId, null, "no_order");
4617
- if (order.captureMethod === "manual" || order.captureMethod === "import") {
4618
- return refundDuplicateCapture(tx, paymentIntentId, paid, order);
4619
- }
4620
- if (order.status === "confirmed") return { orderNumber: order.orderNumber, finalized: true };
4621
- if (order.status === "cancelled") {
4622
- if (order.capturedMinor === 0) await refundCancelledCapture(paymentIntentId, paid, order);
4623
- return recordOutcome(tx, paymentIntentId, order, "order_cancelled_refunded");
4624
- }
4625
- return recordOutcome(tx, paymentIntentId, order, `order_not_pending: ${order.status}`);
4626
- }
4627
- async function recordOutcome(tx, paymentIntentId, order, reason, detail) {
4628
- await publisher.publish(EVT_PAYMENT_FAILED2, {
4629
- paymentId: paymentIntentId,
4630
- orderId: order?.id ?? "",
4631
- reason
4632
- });
4633
- if (order !== null) {
4634
- audit.note("payment.recordOutcome", [{ type: "order", id: order.id }]);
4635
- await repos.orderHistory.append(tx, {
4636
- id: uuidv710(),
4637
- orderId: order.id,
4638
- fromStatus: order.status,
4639
- toStatus: order.status,
4640
- actor: FINALIZE_ACTOR,
4641
- note: `captured payment not applied: ${reason}${detail === void 0 ? "" : ` (${detail})`}`,
4642
- timestamp: /* @__PURE__ */ new Date()
4643
- });
4644
- }
4645
- logger.warn({ paymentIntentId, orderId: order?.id, reason }, "captured payment not applied");
4646
- return { orderNumber: order?.orderNumber ?? null, finalized: false, reason };
4647
- }
4648
- async function reservationFor(tx, order, reservationId, index) {
4649
- const held = await repos.inventoryReservation.findById(tx, reservationId);
4650
- if (held !== null) return reservationId;
4651
- const line = order.lineItems[index];
4652
- if (line === void 0) {
4653
- throw new CheckoutError(
4654
- "finalize_failed",
4655
- `Order ${order.id} has no line for reservation ${reservationId}`
4656
- );
4657
- }
4658
- const retaken = await inventory.tryReserveStock(line.variantId, line.qty, order.id).catch((err) => {
4659
- if (err instanceof NotFoundError7) return null;
4660
- throw err;
4661
- });
4662
- if (retaken === null) throw new StockUnavailable(line.variantId);
4663
- return retaken.reservationId;
4664
- }
4665
- async function refundCapture(paymentIntentId, paid, currency2, key, context) {
4666
- try {
4667
- const answer = await payments.refund(
4668
- paymentIntentId,
4669
- paid.amountMinor,
4670
- PROVIDER_REFUND_REASON,
4671
- {
4672
- idempotencyKey: key,
4673
- currency: currency2
4674
- }
4675
- );
4676
- const settlement = settlementOf(answer, { amountMinor: paid.amountMinor, currency: currency2 });
4677
- if (settlement.mismatch) {
4678
- logger.error(
4679
- { ...context, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
4680
- "provider refund answer differs from the capture; left pending"
3678
+ } catch (err) {
3679
+ failed.push(row.id);
3680
+ logger.warn(
3681
+ { err, subscriptionId: row.id, eventId: event.id },
3682
+ `${what.alert} alert failed; the subscription stays active until a retry or the next ${what.next}`
4681
3683
  );
4682
3684
  }
4683
- return settlement;
4684
- } catch (err) {
4685
- if (err instanceof PaymentError && err.code === "payment.refund_rejected") {
4686
- logger.error({ ...context, err }, "provider refused the refund of a capture");
4687
- return { status: "failed", providerRefundId: null, mismatch: false };
4688
- }
4689
- logger.error(
4690
- { ...context, err },
4691
- "capture refund outcome unknown; left pending until reconciled"
4692
- );
4693
- return { status: "pending", providerRefundId: null, mismatch: false };
4694
3685
  }
4695
- }
4696
- async function refundCancelledCapture(paymentIntentId, paid, order) {
4697
- const refundId = uuidv5(`cancelled-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
4698
- const held = await store.transaction(async (tx) => {
4699
- audit.note("payment.refundCapture", [{ type: "order", id: order.id }]);
4700
- const locked = await repos.order.lock(tx, order.id);
4701
- if (locked === null || locked.capturedMinor > 0) return false;
4702
- const now = /* @__PURE__ */ new Date();
4703
- await repos.order.recordCapture(tx, order.id, {
4704
- amountMinor: paid.amountMinor,
4705
- method: "provider",
4706
- at: now
4707
- });
4708
- await repos.orderRefund.insert(tx, {
4709
- id: refundId,
4710
- orderId: order.id,
4711
- amountMinor: paid.amountMinor,
4712
- currency: order.currency,
4713
- providerRefundId: null,
4714
- status: "pending",
4715
- reason: "captured for a cancelled order",
4716
- actor: "system:checkout",
4717
- createdAt: now
4718
- });
4719
- await publisher.publish(EVT_PAYMENT_CAPTURED, {
4720
- paymentId: paymentIntentId,
4721
- orderId: order.id,
4722
- amountMinor: paid.amountMinor,
4723
- currency: order.currency
4724
- });
4725
- return true;
4726
- });
4727
- if (!held) return;
4728
- const settlement = await refundCapture(paymentIntentId, paid, order.currency, refundId, {
4729
- orderId: order.id,
4730
- refundId
4731
- });
4732
- if (settlement.status === "pending") return;
4733
- await store.transaction(async (tx) => {
4734
- await repos.order.lock(tx, order.id);
4735
- await repos.orderRefund.settle(tx, refundId, {
4736
- status: settlement.status,
4737
- providerRefundId: settlement.providerRefundId
4738
- });
4739
- await refreshRefunded(repos, tx, order.id, /* @__PURE__ */ new Date());
4740
- if (settlement.status === "succeeded") {
4741
- await publisher.publish(EVT_PAYMENT_REFUNDED2, {
4742
- paymentId: paymentIntentId,
4743
- orderId: order.id,
4744
- refundId,
4745
- amountMinor: paid.amountMinor,
4746
- currency: order.currency
4747
- });
4748
- }
4749
- });
4750
- }
4751
- async function refundDuplicateCapture(tx, paymentIntentId, paid, order) {
4752
- if (await repos.processedEvent.seen(tx, DUPLICATE_CAPTURE_HANDLER, paymentIntentId)) {
4753
- return { orderNumber: order.orderNumber, finalized: false, reason: DUPLICATE_CAPTURE };
4754
- }
4755
- const key = uuidv5(`duplicate-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
4756
- const settlement = await refundCapture(
4757
- paymentIntentId,
4758
- paid,
4759
- paid.currency.toUpperCase(),
4760
- key,
4761
- {
4762
- orderId: order.id,
4763
- idempotencyKey: key
4764
- }
4765
- );
4766
- if (settlement.status === "pending" && !settlement.mismatch) {
4767
- throw new CheckoutError(
4768
- "finalize_failed",
4769
- `The refund of a second capture of order ${order.orderNumber} has no known outcome`,
4770
- { context: { orderNumber: order.orderNumber } }
3686
+ if (failed.length > 0) {
3687
+ throw new Error(
3688
+ `${what.alert} alerts for event ${event.id} failed for subscriptions ${failed.join(", ")}`
4771
3689
  );
4772
3690
  }
4773
- await repos.processedEvent.markProcessed(
4774
- tx,
4775
- DUPLICATE_CAPTURE_HANDLER,
4776
- paymentIntentId,
4777
- /* @__PURE__ */ new Date()
4778
- );
4779
- const reason = settlement.status === "succeeded" ? DUPLICATE_CAPTURE : `duplicate_capture_refund_${settlement.status}`;
4780
- return recordOutcome(
4781
- tx,
4782
- paymentIntentId,
4783
- order,
4784
- reason,
4785
- `capture of ${formatMoney(paid.amountMinor, paid.currency)}`
4786
- );
4787
- }
4788
- async function confirm(tx, paymentIntentId, paid, order, capture) {
4789
- const metadata = order.metadata;
4790
- const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
4791
- audit.note("order.confirm", [{ type: "order", id: order.id }]);
4792
- for (const [index, reservationId] of reservationIds.entries()) {
4793
- const reservation = await reservationFor(tx, order, reservationId, index);
4794
- await inventory.commitReservation(reservation, FINALIZE_ACTOR);
4795
- }
4796
- const now = /* @__PURE__ */ new Date();
4797
- if (!await repos.order.setStatusIf(tx, order.id, "pending", "confirmed", now)) {
4798
- throw new NoLongerPending();
4799
- }
4800
- await repos.order.recordCapture(tx, order.id, {
4801
- amountMinor: paid.amountMinor,
4802
- method: capture.method,
4803
- at: now
4804
- });
4805
- await repos.orderHistory.append(tx, {
4806
- id: uuidv710(),
4807
- orderId: order.id,
4808
- fromStatus: "pending",
4809
- toStatus: "confirmed",
4810
- actor: capture.actor,
4811
- note: capture.note,
4812
- timestamp: now
4813
- });
4814
- if (order.customerId) {
4815
- await repos.customer.incrementStats(tx, order.customerId, 1, paid.amountMinor, now);
4816
- }
4817
- await publisher.publish(EVT_PAYMENT_CAPTURED, {
4818
- paymentId: paymentIntentId,
4819
- orderId: order.id,
4820
- amountMinor: paid.amountMinor,
4821
- currency: order.currency
4822
- });
4823
- await publisher.publish(EVT_ORDER_PAID4, {
4824
- orderId: order.id,
4825
- paymentIntentId,
4826
- amountMinor: paid.amountMinor,
4827
- currency: order.currency
4828
- });
4829
- const cartToken = metadata.cartToken;
4830
- if (cartToken) {
4831
- if (await repos.cart.clearIfLive(tx, cartToken, now)) {
4832
- await publisher.publish(EVT_CART_UPDATED2, {
4833
- cartId: cartToken,
4834
- itemCount: 0,
4835
- totalMinor: 0
4836
- });
4837
- }
4838
- await publisher.publish(EVT_CART_CONVERTED, {
4839
- cartId: cartToken,
4840
- orderId: order.id
4841
- });
4842
- }
4843
- logger.info({ orderId: order.id, orderNumber: order.orderNumber }, "checkout finalized");
4844
- return { orderNumber: order.orderNumber, finalized: true };
4845
- }
4846
- async function cancelDraft(orderId, reason) {
4847
- await store.transaction(async (tx) => {
4848
- const order = await repos.order.findById(tx, orderId);
4849
- if (!order) throw new NotFoundError7("order", orderId);
4850
- const metadata = order.metadata;
4851
- const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
4852
- for (const rid of reservationIds) {
4853
- await inventory.releaseReservation(rid, "cancelled");
4854
- }
4855
- await orders4.cancel(orderId, reason, CANCEL_ACTOR);
4856
- });
4857
- }
4858
- async function checkStock(tx, cartDoc) {
4859
- for (const item of cartDoc.items) {
4860
- const v = await repos.variant.findById(tx, item.variantId);
4861
- if (!v) {
4862
- throw new CheckoutError("variant_missing", `Variant missing: ${item.variantId}`);
4863
- }
4864
- if (v.stock < item.qty) {
4865
- throw new CheckoutError(
4866
- "out_of_stock",
4867
- `Insufficient stock for ${item.variantName}: available ${v.stock}, requested ${item.qty}`
4868
- );
4869
- }
4870
- }
4871
3691
  }
4872
- async function place(tx, input, closed) {
4873
- const cartDoc = await repos.cart.lock(tx, input.cartToken);
4874
- if (cartDoc === null) throw new NotFoundError7("cart", input.cartToken);
4875
- if (!cartDoc.items.length) throw await cartEmpty(input.cartToken);
4876
- const pending = await repos.order.findPendingByCartToken(tx, input.cartToken);
4877
- if (pending !== null) {
4878
- const { paymentIntentId } = pending;
4879
- if (paymentIntentId === null) {
4880
- if (Date.now() - Date.parse(pending.createdAt) <= ABANDON_AFTER_MS) {
4881
- throw new CheckoutError("in_progress", "A checkout for this cart is already in progress");
4882
- }
4883
- await cancelDraft(pending.id, "abandoned: no payment intent");
4884
- } else {
4885
- const reason = closed.get(paymentIntentId);
4886
- if (reason === void 0) {
4887
- if (sameLines(pending, cartDoc))
4888
- return { kind: "existing", order: { ...pending, paymentIntentId } };
4889
- return { kind: "cancel-first", order: { ...pending, paymentIntentId } };
4890
- }
4891
- await cancelDraft(pending.id, reason);
4892
- }
4893
- }
4894
- await checkStock(tx, cartDoc);
4895
- const lineItems = cartDoc.items.map((item) => ({
4896
- variantId: item.variantId,
4897
- productId: item.productId,
4898
- productName: item.productName,
4899
- variantName: item.variantName,
4900
- sku: "",
4901
- qty: item.qty,
4902
- unitPriceMinor: item.priceMinor,
4903
- lineSubtotalMinor: item.priceMinor * item.qty,
4904
- lineTaxMinor: 0,
4905
- lineTotalMinor: item.priceMinor * item.qty,
4906
- imageUrl: item.imageUrl
3692
+ const onRestocked = async (event) => {
3693
+ const { variantId, productId } = event.payload;
3694
+ const { rows, product } = await store.read(async (tx) => ({
3695
+ rows: await repos.alertSubscription.listActive(tx, variantId, "back_in_stock"),
3696
+ product: await repos.product.findById(tx, productId)
4907
3697
  }));
4908
- const orderId = uuidv710();
4909
- audit.note("checkout.place", [{ type: "order", id: orderId }]);
4910
- const correlationId = currentCorrelationId();
4911
- const reservationIds = [];
4912
- for (const item of cartDoc.items) {
4913
- try {
4914
- const r = await inventory.reserveStock(item.variantId, item.qty, orderId);
4915
- reservationIds.push(r.reservationId);
4916
- } catch (err) {
4917
- if (err instanceof CheckoutError) throw err;
4918
- throw new CheckoutError("reservation_failed", "Inventory reservation failed", {
4919
- cause: err
4920
- });
4921
- }
4922
- }
4923
- const order = await orders4.createFromCheckout({
4924
- orderId,
4925
- customerId: input.customerId ?? null,
4926
- email: input.email,
4927
- billingAddress: input.billingAddress,
4928
- shippingAddress: input.shippingAddress,
4929
- lineItems,
4930
- subtotalMinor: cartDoc.subtotalMinor,
4931
- taxTotalMinor: 0,
4932
- shippingTotalMinor: 0,
4933
- discountTotalMinor: 0,
4934
- totalMinor: cartDoc.subtotalMinor,
4935
- currency: cartDoc.currency,
4936
- ...input.notes !== void 0 && { notes: input.notes },
4937
- metadata: {
4938
- cartToken: cartDoc.token,
4939
- reservationIds,
4940
- ...correlationId !== void 0 && { correlationId }
4941
- },
4942
- cartToken: cartDoc.token
4943
- });
4944
- return { kind: "placed", order };
4945
- }
4946
- async function answerExisting(order) {
4947
- const paymentIntent = await payments.getPaymentIntent(order.paymentIntentId);
4948
- if (outcomeOf(paymentIntent.status) === "failed") {
4949
- return { closed: `payment_${paymentIntent.status}` };
4950
- }
4951
- return {
4952
- orderId: order.id,
4953
- orderNumber: order.orderNumber,
4954
- paymentIntent,
4955
- currency: order.currency,
4956
- totalMinor: order.totalMinor,
4957
- orderStatus: order.status,
4958
- payment: { status: "requires_action" }
4959
- };
4960
- }
4961
- async function cancelIntent(order) {
4962
- try {
4963
- await payments.cancelPaymentIntent(order.paymentIntentId);
4964
- } catch (err) {
4965
- if (!(err instanceof PaymentError && err.code === "payment.cancel_refused")) throw err;
4966
- throw new CheckoutError(
4967
- "payment_in_progress",
4968
- `The payment for order ${order.orderNumber} is already under way`,
4969
- { cause: err, context: { orderNumber: order.orderNumber } }
4970
- );
4971
- }
4972
- }
4973
- async function pay(input, order) {
4974
- const params = {
4975
- amountMinor: order.totalMinor,
4976
- currency: order.currency,
4977
- orderRef: order.id,
4978
- receiptEmail: input.email,
4979
- metadata: { orderId: order.id, orderNumber: order.orderNumber }
4980
- };
4981
- if (input.customerId != null) params.customerId = input.customerId;
4982
- let intent;
4983
- try {
4984
- intent = await payments.createPaymentIntent(params);
4985
- } catch (err) {
4986
- await cancelDraft(order.id, "payment intent not created");
4987
- throw err;
4988
- }
4989
- let unconfirmed = null;
4990
- const answer = await store.transaction(async (tx) => {
4991
- await repos.cart.lock(tx, input.cartToken);
4992
- await repos.order.setPaymentIntent(tx, order.id, intent.id, /* @__PURE__ */ new Date());
4993
- await publisher.publish(EVT_PAYMENT_INTENT_CREATED2, {
4994
- paymentId: intent.id,
4995
- orderId: order.id
4996
- });
4997
- let payment;
4998
- const outcome = outcomeOf(intent.status);
4999
- if (outcome === "succeeded") {
5000
- const done = await finalize(intent.id, {
5001
- amountMinor: intent.amountMinor,
5002
- currency: intent.currency
5003
- });
5004
- if (!done.finalized) unconfirmed = done.reason ?? "not_confirmed";
5005
- payment = unconfirmed === null ? { status: "succeeded" } : { status: "failed", reason: unconfirmed };
5006
- } else if (outcome === "failed") {
5007
- const reason = `payment_${intent.status}`;
5008
- await cancelDraft(order.id, reason);
5009
- await publisher.publish(EVT_PAYMENT_FAILED2, {
5010
- paymentId: intent.id,
5011
- orderId: order.id,
5012
- reason
5013
- });
5014
- payment = { status: "failed", reason };
5015
- } else {
5016
- payment = { status: "requires_action" };
5017
- }
5018
- const current = await repos.order.findById(tx, order.id);
5019
- logger.info(
5020
- { orderId: order.id, orderNumber: order.orderNumber, payment: payment.status },
5021
- "checkout started"
5022
- );
3698
+ if (product === null) return;
3699
+ await fanOut(event, rows, { alert: "back-in-stock", next: "restock" }, (row) => {
3700
+ const { productUrl, unsubscribeUrl } = links(row, product);
5023
3701
  return {
5024
- orderId: order.id,
5025
- orderNumber: order.orderNumber,
5026
- paymentIntent: intent,
5027
- currency: order.currency,
5028
- totalMinor: order.totalMinor,
5029
- orderStatus: current?.status ?? order.status,
5030
- payment
3702
+ template: "alert-back-in-stock",
3703
+ vars: { storeName, productName: product.name, productUrl, unsubscribeUrl }
5031
3704
  };
5032
3705
  });
5033
- if (unconfirmed !== null && answer.orderStatus === "pending") {
5034
- await cancelDraft(order.id, unconfirmed);
5035
- await refundCancelledCapture(
5036
- intent.id,
5037
- { amountMinor: intent.amountMinor, currency: intent.currency },
5038
- order
5039
- );
5040
- return { ...answer, orderStatus: "cancelled" };
5041
- }
5042
- return answer;
5043
- }
5044
- async function finalize(paymentIntentId, paid) {
5045
- return store.transaction(async (tx) => {
5046
- const order = await repos.order.findByPaymentIntentId(tx, paymentIntentId);
5047
- return inOrderScope(order, () => finalizeLoaded(tx, paymentIntentId, paid, order));
3706
+ };
3707
+ const onPriceChanged = async (event) => {
3708
+ const { variantId, productId, previousPriceMinor, priceMinor, currency } = event.payload;
3709
+ if (priceMinor >= previousPriceMinor) return;
3710
+ const { rows, product } = await store.read(async (tx) => ({
3711
+ rows: await repos.alertSubscription.listActive(tx, variantId, "price_drop"),
3712
+ product: await repos.product.findById(tx, productId)
3713
+ }));
3714
+ if (product === null) return;
3715
+ const due = rows.filter(
3716
+ (row) => row.baselinePriceMinor !== null && priceMinor < row.baselinePriceMinor
3717
+ );
3718
+ const previousPriceFormatted = formatMoney(previousPriceMinor, currency);
3719
+ const priceFormatted = formatMoney(priceMinor, currency);
3720
+ await fanOut(event, due, { alert: "price-drop", next: "drop" }, (row) => {
3721
+ const { productUrl, unsubscribeUrl } = links(row, product);
3722
+ return {
3723
+ template: "alert-price-drop",
3724
+ vars: {
3725
+ storeName,
3726
+ productName: product.name,
3727
+ productUrl,
3728
+ unsubscribeUrl,
3729
+ previousPriceFormatted,
3730
+ priceFormatted
3731
+ }
3732
+ };
5048
3733
  });
3734
+ };
3735
+ await eventBus.subscribe(EVT_ALERT_REQUESTED, onRequested, {
3736
+ name: "email-alert-requested"
3737
+ });
3738
+ await eventBus.subscribe(EVT_PRODUCT_RESTOCKED, onRestocked, {
3739
+ name: "email-alert-back-in-stock"
3740
+ });
3741
+ await eventBus.subscribe(EVT_PRODUCT_VARIANT_PRICE_CHANGED, onPriceChanged, {
3742
+ name: "email-alert-price-drop"
3743
+ });
3744
+ }
3745
+
3746
+ // src/handlers/side-effects/email-feedback-handler.ts
3747
+ import {
3748
+ emailFeedbackType
3749
+ } from "@nymbalhq/types";
3750
+ async function registerEmailFeedbackHandler(deps) {
3751
+ const { eventBus, email, repos, logger } = deps;
3752
+ if (!isHooked(email)) return;
3753
+ const { store } = repos.emailSuppression;
3754
+ async function suppress(event, reason) {
3755
+ const suppressed = await store.transaction(
3756
+ (tx) => repos.emailSuppression.suppress(tx, {
3757
+ email: normaliseEmail(event.payload.recipient),
3758
+ reason,
3759
+ eventId: event.id,
3760
+ at: /* @__PURE__ */ new Date()
3761
+ })
3762
+ );
3763
+ logger.info(
3764
+ { eventId: event.id, reason, suppressed },
3765
+ suppressed ? "an address was suppressed" : "the address was already suppressed"
3766
+ );
5049
3767
  }
5050
- async function finalizeLoaded(tx, paymentIntentId, paid, order) {
5051
- const outcome = (order2, reason) => recordOutcome(tx, paymentIntentId, order2, reason);
5052
- if (order === null || order.status !== "pending") {
5053
- return settled(tx, paymentIntentId, order, paid);
5054
- }
5055
- if (paid.amountMinor !== order.totalMinor || paid.currency.toUpperCase() !== order.currency.toUpperCase()) {
5056
- return outcome(
5057
- order,
5058
- `amount_mismatch: paid ${paid.amountMinor} ${paid.currency.toUpperCase()}, due ${order.totalMinor} ${order.currency.toUpperCase()}`
5059
- );
3768
+ const onBounced = async (event) => {
3769
+ if (event.payload.bounce !== "hard") {
3770
+ logger.info({ eventId: event.id }, "a soft bounce changes nothing");
3771
+ return;
5060
3772
  }
3773
+ await suppress(event, "hard_bounce");
3774
+ };
3775
+ const onComplained = (event) => suppress(event, "complaint");
3776
+ await eventBus.subscribe(
3777
+ emailFeedbackType(email.providerName, "bounced"),
3778
+ onBounced,
3779
+ { name: "email-feedback-bounced" }
3780
+ );
3781
+ await eventBus.subscribe(
3782
+ emailFeedbackType(email.providerName, "complained"),
3783
+ onComplained,
3784
+ { name: "email-feedback-complained" }
3785
+ );
3786
+ }
3787
+
3788
+ // src/handlers/side-effects/shipping-tracking-handler.ts
3789
+ import {
3790
+ StatusTransitionError,
3791
+ shippingTrackingType
3792
+ } from "@nymbalhq/types";
3793
+ var ACTOR = "system:shipping-tracking";
3794
+ async function registerShippingTrackingHandler(deps) {
3795
+ const { eventBus, shipping, repos, orderService, logger } = deps;
3796
+ if (!isHooked(shipping)) return;
3797
+ const { store } = repos.orderShipment;
3798
+ async function deliver(eventId, orderId) {
5061
3799
  try {
5062
- return await store.savepoint(
5063
- () => confirm(tx, paymentIntentId, paid, order, PROVIDER_CAPTURE)
3800
+ await runAsActor(
3801
+ { kind: "system", id: "shipping-tracking" },
3802
+ () => orderService.markDelivered(orderId, ACTOR)
5064
3803
  );
3804
+ logger.info({ eventId, orderId }, "a tracking update delivered the order");
5065
3805
  } catch (err) {
5066
- if (err instanceof StockUnavailable) {
5067
- const current = await repos.order.findById(tx, order.id);
5068
- if (current?.status !== "pending") return settled(tx, paymentIntentId, current, paid);
5069
- return outcome(current, `stock_unavailable: ${err.variantId}`);
5070
- }
5071
- if (!(err instanceof NoLongerPending)) throw err;
3806
+ if (!(err instanceof StatusTransitionError)) throw err;
3807
+ logger.info({ eventId, orderId }, "the order was no longer shipped");
5072
3808
  }
5073
- return settled(tx, paymentIntentId, await repos.order.findById(tx, order.id), paid);
5074
3809
  }
5075
- return {
5076
- async beginCheckout(input) {
5077
- audit.note("checkout.place");
5078
- await loadValidCart(input.cartToken);
5079
- const closed = /* @__PURE__ */ new Map();
5080
- for (let attempt = 0; ; attempt += 1) {
5081
- const placement = await store.transaction((tx) => place(tx, input, closed));
5082
- if (placement.kind === "placed") return pay(input, placement.order);
5083
- if (placement.kind === "existing") {
5084
- const answer = await answerExisting(placement.order);
5085
- if (!("closed" in answer)) return answer;
5086
- closed.set(placement.order.paymentIntentId, answer.closed);
5087
- continue;
5088
- }
5089
- if (attempt === SUPERSEDE_ATTEMPTS) {
5090
- throw new CheckoutError("in_progress", "A checkout for this cart is already in progress");
5091
- }
5092
- await cancelIntent(placement.order);
5093
- closed.set(placement.order.paymentIntentId, "superseded: the cart changed");
5094
- }
5095
- },
5096
- finalize,
5097
- async cancel(orderId, reason) {
5098
- await cancelDraft(orderId, reason);
5099
- },
5100
- async markPaid(orderId, actor, note) {
5101
- audit.note("order.markPaid", [{ type: "order", id: orderId }]);
5102
- const found = await store.read((tx) => repos.order.findById(tx, orderId));
5103
- if (!found) throw new NotFoundError7("order", orderId);
5104
- if (found.status !== "pending") {
5105
- throw new StatusTransitionError2("order", found.status, "confirmed");
3810
+ const onTracking = async (event) => {
3811
+ const { status, trackingNumber } = event.payload;
3812
+ if (status !== "delivered") {
3813
+ logger.info({ eventId: event.id, status }, "a tracking update other than delivered");
3814
+ return;
3815
+ }
3816
+ const orders4 = await store.read(async (tx) => {
3817
+ const found = [];
3818
+ for (const id of await repos.orderShipment.ordersByTrackingNumber(tx, trackingNumber)) {
3819
+ const order = await repos.order.findById(tx, id);
3820
+ if (order !== null) found.push(order);
5106
3821
  }
5107
- if (found.paymentIntentId) {
5108
- try {
5109
- await payments.cancelPaymentIntent(found.paymentIntentId);
5110
- } catch (err) {
5111
- if (!(err instanceof PaymentError && err.code === "payment.cancel_refused")) throw err;
5112
- throw new OrderConflictError2(
5113
- "order.payment_in_progress",
5114
- `The payment for order ${found.orderNumber} is under way with the provider`,
5115
- { cause: err, context: { orderNumber: found.orderNumber } }
5116
- );
5117
- }
3822
+ return found;
3823
+ });
3824
+ if (orders4.length === 0) {
3825
+ logger.info({ eventId: event.id }, "no order was shipped under the tracking number");
3826
+ return;
3827
+ }
3828
+ for (const order of orders4) {
3829
+ if (order.status !== "shipped") {
3830
+ logger.info(
3831
+ { eventId: event.id, orderId: order.id, orderStatus: order.status },
3832
+ "the order is not shipped"
3833
+ );
3834
+ continue;
5118
3835
  }
5119
- return store.transaction(async (tx) => {
5120
- const order = await repos.order.lock(tx, orderId);
5121
- if (!order) throw new NotFoundError7("order", orderId);
5122
- if (order.status !== "pending") {
5123
- throw new StatusTransitionError2("order", order.status, "confirmed");
5124
- }
5125
- const capture = {
5126
- method: "manual",
5127
- actor,
5128
- note: note ? `payment recorded manually: ${note}` : "payment recorded manually"
5129
- };
5130
- const paid = { amountMinor: order.totalMinor, currency: order.currency };
5131
- try {
5132
- await inOrderScope(order, () => confirm(tx, "", paid, order, capture));
5133
- } catch (err) {
5134
- if (!(err instanceof StockUnavailable)) throw err;
5135
- throw new OrderConflictError2(
5136
- "order.stock_unavailable",
5137
- `The stock order ${order.orderNumber} held has gone to another order`,
5138
- { context: { variantId: err.variantId } }
5139
- );
5140
- }
5141
- return await repos.order.findById(tx, order.id);
5142
- });
3836
+ await deliver(event.id, order.id);
5143
3837
  }
5144
3838
  };
5145
- }
5146
-
5147
- // src/services/search-service.ts
5148
- function createSearchService(deps) {
5149
- return {
5150
- async products(query, params) {
5151
- return deps.adapter.search(query, params);
3839
+ await eventBus.subscribe(
3840
+ shippingTrackingType(shipping.providerName),
3841
+ onTracking,
3842
+ {
3843
+ name: "shipping-tracking"
5152
3844
  }
5153
- };
3845
+ );
5154
3846
  }
5155
3847
 
5156
- // src/services/index.ts
5157
- function buildServices(deps) {
5158
- const { config, store, repos, publisher, logger, payments, searchAdapter } = deps;
5159
- const inventory = createInventoryService({
5160
- store,
3848
+ // src/handlers/register.ts
3849
+ async function registerHandlers(deps) {
3850
+ const { config, eventBus, documentStore, repos, adapters, alerts, orders: orders4, logger } = deps;
3851
+ const handlerLogger = logger.child({ component: "handlers" });
3852
+ await registerCategoryProjection({
3853
+ eventBus,
3854
+ documentStore,
3855
+ logger: handlerLogger.child({ projection: "category" }),
3856
+ storeId: config.store.name,
3857
+ repos
3858
+ });
3859
+ await registerProductProjection({
3860
+ eventBus,
3861
+ documentStore,
3862
+ logger: handlerLogger.child({ projection: "product" }),
3863
+ storeId: config.store.name,
3864
+ currency: config.store.currency,
3865
+ repos
3866
+ });
3867
+ await registerOrderProjection({
3868
+ eventBus,
3869
+ documentStore,
3870
+ logger: handlerLogger.child({ projection: "order" }),
3871
+ orderRepo: repos.order,
3872
+ orderHistoryRepo: repos.orderHistory
3873
+ });
3874
+ await registerCustomerProjection({
3875
+ eventBus,
3876
+ documentStore,
3877
+ logger: handlerLogger.child({ projection: "customer" }),
3878
+ customerRepo: repos.customer,
3879
+ orderRepo: repos.order
3880
+ });
3881
+ await registerInventoryProjection({
3882
+ eventBus,
3883
+ documentStore,
3884
+ logger: handlerLogger.child({ projection: "inventory" }),
3885
+ storeId: config.store.name,
3886
+ currency: config.store.currency,
3887
+ repos
3888
+ });
3889
+ await registerRecentlyViewedProjection({
3890
+ eventBus,
3891
+ documentStore,
3892
+ logger: handlerLogger.child({ projection: "recently-viewed" })
3893
+ });
3894
+ await registerEmailHandler({
3895
+ eventBus,
3896
+ email: adapters.email,
3897
+ logger: handlerLogger.child({ handler: "email" }),
3898
+ processedEventRepo: repos.processedEvent,
3899
+ orderRepo: repos.order,
3900
+ orderAccessKeyRepo: repos.orderAccessKey,
3901
+ storeName: config.store.name,
3902
+ ...config.store.url !== void 0 && { storeUrl: config.store.url },
3903
+ keyLifetimeMs: parseDurationToMs(config.commerce.orders.keyLifetime.email)
3904
+ });
3905
+ await registerAlertHandler({
3906
+ eventBus,
3907
+ email: adapters.email,
3908
+ logger: handlerLogger.child({ handler: "alert" }),
5161
3909
  repos,
5162
- publisher,
5163
- logger: logger.child({ service: "inventory" })
3910
+ alerts,
3911
+ storeName: config.store.name
5164
3912
  });
5165
- const orders4 = createOrderService({
5166
- store,
3913
+ await registerEmailFeedbackHandler({
3914
+ eventBus,
3915
+ email: adapters.email,
5167
3916
  repos,
5168
- publisher,
5169
- logger: logger.child({ service: "order" }),
5170
- orderNumberPrefix: config.commerce.orders.numberPrefix,
5171
- orderNumberStart: config.commerce.orders.numberStart
3917
+ logger: handlerLogger.child({ handler: "email-feedback" })
5172
3918
  });
5173
- const cart = createCartService({
5174
- store,
5175
- carts: repos.cart,
5176
- publisher,
5177
- logger: logger.child({ service: "cart" }),
5178
- currency: config.store.currency
3919
+ await registerShippingTrackingHandler({
3920
+ eventBus,
3921
+ shipping: adapters.shipping,
3922
+ repos,
3923
+ orderService: orders4,
3924
+ logger: handlerLogger.child({ handler: "shipping-tracking" })
5179
3925
  });
5180
- const checkout = createCheckoutService({
5181
- store,
3926
+ await registerSearchHandler({
3927
+ eventBus,
3928
+ search: adapters.search,
5182
3929
  repos,
5183
- publisher,
5184
- logger: logger.child({ service: "checkout" }),
5185
- cart,
5186
- orders: orders4,
5187
- inventory,
5188
- payments,
5189
- currency: config.store.currency
3930
+ logger: handlerLogger.child({ handler: "search" })
5190
3931
  });
5191
- return {
5192
- product: createProductService({
5193
- store,
5194
- repos,
5195
- publisher,
5196
- logger: logger.child({ service: "product" })
5197
- }),
5198
- category: createCategoryService({
5199
- repos,
5200
- publisher,
5201
- logger: logger.child({ service: "category" })
5202
- }),
5203
- cart,
5204
- customer: createCustomerService({
5205
- repos,
5206
- publisher,
5207
- logger: logger.child({ service: "customer" })
5208
- }),
5209
- auth: createAuthService({
5210
- repos,
5211
- publisher,
5212
- logger: logger.child({ service: "auth" }),
5213
- jwtSecret: config.security.auth.jwtSecret,
5214
- accessTtl: config.security.auth.accessTtl,
5215
- refreshTtl: config.security.auth.refreshTtl
5216
- }),
5217
- order: orders4,
5218
- inventory,
5219
- checkout,
5220
- refund: createRefundService({
5221
- store,
5222
- repos,
5223
- publisher,
5224
- logger: logger.child({ service: "refund" }),
5225
- payments
5226
- }),
5227
- search: createSearchService({
5228
- adapter: searchAdapter,
5229
- logger: logger.child({ service: "search" })
5230
- })
3932
+ await registerReviewsHandler({
3933
+ eventBus,
3934
+ reviews: adapters.reviews,
3935
+ logger: handlerLogger.child({ handler: "reviews" }),
3936
+ processedEventRepo: repos.processedEvent
3937
+ });
3938
+ logger.debug("event handlers registered");
3939
+ }
3940
+
3941
+ // src/app.ts
3942
+ import { DEFAULT_JWT_SECRET as DEFAULT_JWT_SECRET2 } from "@nymbalhq/config";
3943
+ import {
3944
+ ConfigError as ConfigError3
3945
+ } from "@nymbalhq/types";
3946
+
3947
+ // src/auth-secret.ts
3948
+ import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
3949
+ import { ConfigError as ConfigError2 } from "@nymbalhq/types";
3950
+ var JWT_SECRET_ENV = "NYMBAL_JWT_SECRET";
3951
+ var MIN_LENGTH = 16;
3952
+ function resolveAuthSecret(config, env) {
3953
+ const fromEnv = env[JWT_SECRET_ENV];
3954
+ if (fromEnv !== void 0 && fromEnv.length < MIN_LENGTH) {
3955
+ throw new ConfigError2(
3956
+ `${JWT_SECRET_ENV} is shorter than ${MIN_LENGTH} characters; set it to a random secret, such as \`openssl rand -base64 32\`.`,
3957
+ { code: "config.jwt_secret_too_short", context: { variable: JWT_SECRET_ENV } }
3958
+ );
3959
+ }
3960
+ const own = config.security.auth.jwtSecret;
3961
+ if (own !== DEFAULT_JWT_SECRET) return { secret: own, source: "config" };
3962
+ if (fromEnv !== void 0) return { secret: fromEnv, source: "env" };
3963
+ return { secret: DEFAULT_JWT_SECRET, source: "default" };
3964
+ }
3965
+
3966
+ // src/events/outage.ts
3967
+ import { boundedHealthCheck, HEALTH_CHECK_TIMEOUT_MS as HEALTH_CHECK_TIMEOUT_MS2 } from "@nymbalhq/types";
3968
+ function createOutageProbe(subjects, options = {}) {
3969
+ const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS2;
3970
+ const checked = subjects.filter(
3971
+ (subject) => !isNotConfigured(subject) && typeof subject.healthCheck === "function"
3972
+ );
3973
+ return async () => {
3974
+ const reports = await Promise.all(
3975
+ checked.map(async (subject) => ({
3976
+ name: subject.name,
3977
+ report: await boundedHealthCheck(() => subject.healthCheck(), { timeoutMs })
3978
+ }))
3979
+ );
3980
+ const down = reports.filter(({ report }) => report.status === "down").map(({ name, report }) => ({ name, detail: report.detail ?? "down" }));
3981
+ return { outage: down.length > 0, down };
5231
3982
  };
5232
3983
  }
5233
3984
 
5234
3985
  // src/read-models/index.ts
5235
- import { errorText } from "@nymbalhq/types";
3986
+ import {
3987
+ errorText
3988
+ } from "@nymbalhq/types";
5236
3989
 
5237
3990
  // src/read-models/catalogue.ts
5238
3991
  function snapshotsOf({ repos }) {
@@ -5260,8 +4013,8 @@ var catalogue = {
5260
4013
  }
5261
4014
  const context = { storeId, currency: config.store.currency, logger };
5262
4015
  for await (const page of ctx.pages("products", snapshotsOf(ctx.deps))) {
5263
- for (const snapshot2 of page) {
5264
- yield* productWrites(buildProductDoc(snapshot2, categories3, context));
4016
+ for (const snapshot of page) {
4017
+ yield* productWrites(buildProductDoc(snapshot, categories3, context));
5265
4018
  }
5266
4019
  }
5267
4020
  },
@@ -5346,19 +4099,25 @@ var search = {
5346
4099
  collections: [],
5347
4100
  async *rebuild(ctx) {
5348
4101
  for await (const page of ctx.pages("products", snapshotsOf(ctx.deps))) {
5349
- for (const snapshot2 of page) {
5350
- const doc = buildSearchDoc(snapshot2);
4102
+ for (const snapshot of page) {
4103
+ const doc = buildSearchDoc(snapshot);
5351
4104
  yield { collection: SEARCH_INDEX, key: doc.id, doc };
5352
4105
  }
5353
4106
  }
5354
4107
  },
5355
4108
  handlers(deps) {
5356
- return searchHandler({ search: searchOf(deps), repos: deps.repos });
4109
+ return searchHandler({ search: searchOf(deps), repos: deps.repos, logger: deps.logger });
5357
4110
  }
5358
4111
  };
5359
4112
 
5360
4113
  // src/read-models/index.ts
5361
- var READ_MODELS = [catalogue, orders3, customers3, search];
4114
+ var READ_MODELS = [
4115
+ catalogue,
4116
+ orders3,
4117
+ customers3,
4118
+ search,
4119
+ recentlyViewed
4120
+ ];
5362
4121
  var READ_MODEL_NAMES = READ_MODELS.map((m) => m.name);
5363
4122
  var CATCH_UP_MARGIN_MS = 10 * 6e4;
5364
4123
  var DEFAULT_PAGE_SIZE = 200;
@@ -5389,7 +4148,8 @@ function modelsOf(names) {
5389
4148
  function contextFor(model, deps) {
5390
4149
  const limit = deps.pageSize ?? DEFAULT_PAGE_SIZE;
5391
4150
  let page = 0;
5392
- return {
4151
+ let logReadThrough;
4152
+ const ctx = {
5393
4153
  deps,
5394
4154
  async *pages(table, read) {
5395
4155
  let after;
@@ -5402,15 +4162,35 @@ function contextFor(model, deps) {
5402
4162
  if (rows.length < limit) return;
5403
4163
  after = rows[rows.length - 1].id;
5404
4164
  }
4165
+ },
4166
+ async *events(types) {
4167
+ let after = 0;
4168
+ logReadThrough ??= 0;
4169
+ for (; ; ) {
4170
+ await deps.onPage?.({ model: model.name, table: "events", page });
4171
+ page += 1;
4172
+ const rows = await deps.store.read(
4173
+ (tx) => deps.repos.eventLog.listAfter(tx, after, { types: [...types], limit })
4174
+ );
4175
+ if (rows.length > 0) {
4176
+ after = rows[rows.length - 1].seq;
4177
+ logReadThrough = Math.max(logReadThrough, after);
4178
+ const live = rows.filter((r) => r.deadAt === null);
4179
+ if (live.length > 0) yield live;
4180
+ }
4181
+ if (rows.length < limit) return;
4182
+ }
5405
4183
  }
5406
4184
  };
4185
+ return { ctx, logReadThrough: () => logReadThrough };
5407
4186
  }
5408
4187
  async function collect(model, deps) {
5409
4188
  const startedAt = Date.now();
5410
4189
  const owned = model.target === "search" ? [SEARCH_INDEX] : model.collections;
5411
4190
  const writes = new Map(owned.map((c) => [c, /* @__PURE__ */ new Map()]));
4191
+ const { ctx, logReadThrough } = contextFor(model, deps);
5412
4192
  try {
5413
- for await (const w of model.rebuild(contextFor(model, deps))) {
4193
+ for await (const w of model.rebuild(ctx)) {
5414
4194
  const into = writes.get(w.collection);
5415
4195
  if (into === void 0) throw new Error(`it wrote to ${w.collection}, which it does not own`);
5416
4196
  into.set(w.key, w.doc);
@@ -5418,7 +4198,7 @@ async function collect(model, deps) {
5418
4198
  } catch (error) {
5419
4199
  throw new RebuildError(model.name, error);
5420
4200
  }
5421
- return { model, startedAt, writes };
4201
+ return { model, startedAt, writes, logReadThrough: logReadThrough() };
5422
4202
  }
5423
4203
  async function* entries(docs) {
5424
4204
  yield* docs;
@@ -5439,11 +4219,79 @@ async function swap({ model, writes }, deps) {
5439
4219
  await search2.index(docs);
5440
4220
  return `${search2.providerName} has no replaceAll: every document was indexed, removals not guaranteed`;
5441
4221
  }
5442
- async function catchUp(model, since, deps) {
4222
+ function stagedDeps({ model, writes }, deps) {
4223
+ if (model.target === "search") return { ...deps, search: stagedSearch(searchOf(deps), writes) };
4224
+ const live = deps.documentStore;
4225
+ const documentStore = {
4226
+ capabilities: () => live.capabilities(),
4227
+ async get(collection, key) {
4228
+ const docs = writes.get(collection);
4229
+ if (docs === void 0) return live.get(collection, key);
4230
+ return docs.get(key) ?? null;
4231
+ },
4232
+ async put(collection, key, doc, options) {
4233
+ const docs = writes.get(collection);
4234
+ if (docs === void 0) return live.put(collection, key, doc, options);
4235
+ docs.set(key, doc);
4236
+ },
4237
+ async delete(collection, key) {
4238
+ const docs = writes.get(collection);
4239
+ if (docs === void 0) return live.delete(collection, key);
4240
+ docs.delete(key);
4241
+ },
4242
+ async batchGet(collection, keys) {
4243
+ const docs = writes.get(collection);
4244
+ if (docs === void 0) return live.batchGet(collection, keys);
4245
+ const out = /* @__PURE__ */ new Map();
4246
+ for (const key of keys) if (docs.has(key)) out.set(key, docs.get(key));
4247
+ return out;
4248
+ },
4249
+ async batchPut(collection, items) {
4250
+ const docs = writes.get(collection);
4251
+ if (docs === void 0) return live.batchPut(collection, items);
4252
+ for (const [key, doc] of items) docs.set(key, doc);
4253
+ },
4254
+ query() {
4255
+ throw new Error("a staged read model does not answer queries");
4256
+ },
4257
+ replaceCollection() {
4258
+ throw new Error("a staged read model is not replaced");
4259
+ },
4260
+ close: async () => void 0
4261
+ };
4262
+ return { ...deps, documentStore };
4263
+ }
4264
+ function stagedSearch(live, writes) {
4265
+ const held = writes.get(SEARCH_INDEX);
4266
+ return {
4267
+ kind: "search",
4268
+ get providerName() {
4269
+ return live.providerName;
4270
+ },
4271
+ capabilities: () => live.capabilities(),
4272
+ producesEvents: [],
4273
+ consumesEvents: [],
4274
+ initialize: async () => void 0,
4275
+ healthCheck: () => live.healthCheck(),
4276
+ async index(docs) {
4277
+ for (const doc of docs) held.set(doc.id, doc);
4278
+ return { indexed: docs.length };
4279
+ },
4280
+ async remove(ids) {
4281
+ for (const id of ids) held.delete(id);
4282
+ },
4283
+ search() {
4284
+ throw new Error("a staged search index does not answer searches");
4285
+ },
4286
+ facet() {
4287
+ throw new Error("a staged search index does not answer facets");
4288
+ }
4289
+ };
4290
+ }
4291
+ async function catchUp(model, since, deps, afterSeq = 0) {
5443
4292
  const handlers = model.handlers(deps);
5444
4293
  const failures = [];
5445
4294
  let applied = 0;
5446
- let afterSeq = 0;
5447
4295
  for (; ; ) {
5448
4296
  const page = await deps.store.read(
5449
4297
  (tx) => deps.repos.eventLog.listForCatchUp(tx, since, { afterSeq, limit: CATCH_UP_PAGE })
@@ -5475,15 +4323,16 @@ async function rebuild(names, deps) {
5475
4323
  for (const model of modelsOf(names)) collected.push(await collect(model, deps));
5476
4324
  const report = [];
5477
4325
  for (const c of collected) {
4326
+ const since = new Date(c.startedAt - CATCH_UP_MARGIN_MS);
4327
+ await deps.onPhase?.("collected", c.model.name);
4328
+ const staged = await catchUp(c.model, since, stagedDeps(c, deps), c.logReadThrough);
5478
4329
  const note = await swap(c, deps);
5479
- const { applied, failures } = await catchUp(
5480
- c.model,
5481
- new Date(c.startedAt - CATCH_UP_MARGIN_MS),
5482
- deps
5483
- );
4330
+ await deps.onPhase?.("swapped", c.model.name);
4331
+ const { applied, failures } = await catchUp(c.model, since, deps, c.logReadThrough);
5484
4332
  const entry = {
5485
4333
  model: c.model.name,
5486
4334
  collections: [...c.writes].map(([name, docs]) => ({ name, documents: docs.size })),
4335
+ caughtUpBeforeSwap: staged.applied,
5487
4336
  caughtUpEvents: applied,
5488
4337
  failures,
5489
4338
  ms: Date.now() - c.startedAt,
@@ -5751,18 +4600,18 @@ function startEventRetentionSweeper(deps) {
5751
4600
  }
5752
4601
 
5753
4602
  // src/app.ts
5754
- function refuseUnsafeProduction(config, payments) {
4603
+ function refuseUnsafeProduction(config, payments, jwtSecret) {
5755
4604
  if (process.env.NODE_ENV !== "production") return;
5756
4605
  const provider = config.commerce.payments.provider;
5757
4606
  if (payments.providerName === "native-stub") {
5758
- throw new ConfigError2(
4607
+ throw new ConfigError3(
5759
4608
  `Payments provider "${provider}" resolves to the stub adapter, which verifies no webhook signature; configure a real payments provider for production.`,
5760
4609
  { code: "config.production_stub_payments", context: { provider } }
5761
4610
  );
5762
4611
  }
5763
- if (config.security.auth.jwtSecret === DEFAULT_JWT_SECRET) {
5764
- throw new ConfigError2(
5765
- "security.auth.jwtSecret is the schema default; set a secret of your own for production.",
4612
+ if (jwtSecret === DEFAULT_JWT_SECRET2) {
4613
+ throw new ConfigError3(
4614
+ `security.auth.jwtSecret is the schema default and ${JWT_SECRET_ENV} is not set; set either to a secret of your own for production.`,
5766
4615
  { code: "config.production_default_jwt_secret" }
5767
4616
  );
5768
4617
  }
@@ -5773,10 +4622,10 @@ async function eventArchiveWriter(config) {
5773
4622
  const { adapter, ...options } = archive;
5774
4623
  let mod;
5775
4624
  try {
5776
- mod = await importProviderPackage("media", adapter, process.env);
4625
+ mod = await importAdapterModule("media", { provider: adapter }, process.env);
5777
4626
  } catch (error) {
5778
- if (!(error instanceof ConfigError2 && error.code === "adapter.package_missing")) throw error;
5779
- throw new ConfigError2(
4627
+ if (!(error instanceof ConfigError3 && error.code === "adapter.package_missing")) throw error;
4628
+ throw new ConfigError3(
5780
4629
  `events.archive needs @nymbalhq/media-s3: ${String(error.context["install"])}`,
5781
4630
  {
5782
4631
  code: "adapter.package_missing",
@@ -5786,19 +4635,64 @@ async function eventArchiveWriter(config) {
5786
4635
  );
5787
4636
  }
5788
4637
  if (typeof mod?.createS3ObjectWriter !== "function") {
5789
- throw new ConfigError2("@nymbalhq/media-s3 exports no createS3ObjectWriter; upgrade it", {
4638
+ throw new ConfigError3("@nymbalhq/media-s3 exports no createS3ObjectWriter; upgrade it", {
5790
4639
  code: "adapter.package_invalid",
5791
4640
  context: { package: "@nymbalhq/media-s3" }
5792
4641
  });
5793
4642
  }
5794
4643
  return mod.createS3ObjectWriter(options);
5795
4644
  }
4645
+ function outageSubjects(config, platform, adapters) {
4646
+ const subject = (name, provider, adapter) => {
4647
+ if (isNotConfigured(adapter)) return [];
4648
+ if (typeof adapter.healthCheck !== "function") return [{ name }];
4649
+ const check = adapter.healthCheck.bind(adapter);
4650
+ const named = (detail) => detail ? `${provider}: ${detail}` : provider;
4651
+ return [
4652
+ {
4653
+ name,
4654
+ healthCheck: () => Promise.resolve().then(check).then(
4655
+ (report) => report.status === "down" ? { ...report, detail: named(report.detail) } : report,
4656
+ (err) => {
4657
+ throw new Error(named(err instanceof Error ? err.message : String(err)));
4658
+ }
4659
+ )
4660
+ }
4661
+ ];
4662
+ };
4663
+ const { infrastructure } = config;
4664
+ return [
4665
+ ...subject("eventBus", infrastructure.eventBus.provider, platform.eventBus),
4666
+ ...subject("documentStore", infrastructure.documentStore.provider, platform.documentStore),
4667
+ ...subject("media", infrastructure.media.provider, platform.media),
4668
+ ...COMMERCE_SLOTS.filter((slot) => slot !== "ai").flatMap((slot) => {
4669
+ const adapter = adapters[slot];
4670
+ const provider = typeof adapter.providerName === "string" ? adapter.providerName : config.commerce[slot].provider;
4671
+ return subject(slot, provider, adapter);
4672
+ })
4673
+ ];
4674
+ }
5796
4675
  async function createApp(config, options = {}) {
5797
4676
  const logger = scrubbingLogger(
5798
4677
  options.logger ?? createLogger({ base: { store: config.store.name } })
5799
4678
  );
5800
4679
  const adapterLogger = logger.child({ layer: "adapter" });
5801
4680
  checkInjectedAdapters(config, options.adapters);
4681
+ const jwt = resolveAuthSecret(config, process.env);
4682
+ addSecret(jwt.secret);
4683
+ const shadowed = process.env[JWT_SECRET_ENV];
4684
+ if (jwt.source === "config" && shadowed !== void 0 && shadowed !== jwt.secret) {
4685
+ logger.warn(
4686
+ { variable: JWT_SECRET_ENV },
4687
+ `security.auth.jwtSecret in the config is used; ${JWT_SECRET_ENV} is set and ignored`
4688
+ );
4689
+ }
4690
+ if (process.env.NODE_ENV === "production" && jwt.secret.length < 32) {
4691
+ logger.warn(
4692
+ { source: jwt.source },
4693
+ "the JWT secret is shorter than 32 characters; HS256 wants 256 bits (`openssl rand -base64 32`)"
4694
+ );
4695
+ }
5802
4696
  const settings = await loadBootSettings(config, {
5803
4697
  storage: {
5804
4698
  ...options.sqlitePath !== void 0 && { sqlitePath: options.sqlitePath },
@@ -5813,7 +4707,7 @@ async function createApp(config, options = {}) {
5813
4707
  options.adapters,
5814
4708
  settings.values
5815
4709
  );
5816
- refuseUnsafeProduction(config, payments);
4710
+ refuseUnsafeProduction(config, payments, jwt.secret);
5817
4711
  const security = await resolveSecurityAdapter(config, adapterLogger);
5818
4712
  const archive = await eventArchiveWriter(config);
5819
4713
  const primitives = await resolvePrimitives(config, { ...options, logger });
@@ -5840,7 +4734,9 @@ async function createApp(config, options = {}) {
5840
4734
  store: platform.commandStore,
5841
4735
  eventLog: repos.eventLog,
5842
4736
  eventBus: platform.eventBus,
5843
- logger
4737
+ logger,
4738
+ outage: createOutageProbe(outageSubjects(config, platform, adapters)),
4739
+ ...options.relay
5844
4740
  });
5845
4741
  const subscriberBus = deliveringBus(platform.eventBus, relay);
5846
4742
  const publisher = createEventPublisher({
@@ -5862,7 +4758,9 @@ async function createApp(config, options = {}) {
5862
4758
  publisher,
5863
4759
  logger: logger.child({ layer: "service" }),
5864
4760
  payments: adapters.payments,
5865
- searchAdapter: adapters.search
4761
+ searchAdapter: adapters.search,
4762
+ email: adapters.email,
4763
+ jwtSecret: jwt.secret
5866
4764
  });
5867
4765
  await registerHandlers({
5868
4766
  config,
@@ -5870,16 +4768,22 @@ async function createApp(config, options = {}) {
5870
4768
  documentStore: platform.documentStore,
5871
4769
  repos,
5872
4770
  adapters,
4771
+ alerts: services.alert,
4772
+ orders: services.order,
5873
4773
  logger
5874
4774
  });
5875
- await rebuild(READ_MODEL_NAMES, {
5876
- config,
5877
- store: platform.commandStore,
5878
- repos,
5879
- documentStore: platform.documentStore,
5880
- search: adapters.search,
5881
- logger
5882
- });
4775
+ const externalSearch = resolveChoice("search", config.commerce.search).kind === "package";
4776
+ await rebuild(
4777
+ externalSearch ? READ_MODEL_NAMES.filter((name) => name !== "search") : READ_MODEL_NAMES,
4778
+ {
4779
+ config,
4780
+ store: platform.commandStore,
4781
+ repos,
4782
+ documentStore: platform.documentStore,
4783
+ search: adapters.search,
4784
+ logger
4785
+ }
4786
+ );
5883
4787
  await relay.drain();
5884
4788
  relay.start();
5885
4789
  const sweepers = [
@@ -5912,7 +4816,7 @@ async function createApp(config, options = {}) {
5912
4816
  relay,
5913
4817
  async attachHttp(adapter, options2 = {}) {
5914
4818
  await adapters.security.applyMiddleware(adapter, config.security);
5915
- const { registerAllRoutes: registerAllRoutes2 } = await import("./register-UUQ64HZP.js");
4819
+ const { registerAllRoutes: registerAllRoutes2 } = await import("./register-SBGUI2L5.js");
5916
4820
  registerAllRoutes2({
5917
4821
  config,
5918
4822
  adapter,
@@ -5923,6 +4827,7 @@ async function createApp(config, options = {}) {
5923
4827
  eventBus: subscriberBus,
5924
4828
  publisher,
5925
4829
  settingsSlots: settings.slots,
4830
+ jwtSecret: jwt.secret,
5926
4831
  adminRoot: options2.adminRoot !== void 0 ? options2.adminRoot : process.env["NYMBAL_ADMIN_DIST"]
5927
4832
  });
5928
4833
  },
@@ -5946,15 +4851,15 @@ async function createApp(config, options = {}) {
5946
4851
  capabilities: adapters.security.capabilities()
5947
4852
  },
5948
4853
  documentStore: {
5949
- provider: config.infrastructure.documentStore,
4854
+ provider: config.infrastructure.documentStore.provider,
5950
4855
  capabilities: platform.documentStore.capabilities()
5951
4856
  },
5952
4857
  eventBus: {
5953
- provider: config.infrastructure.eventBus,
4858
+ provider: config.infrastructure.eventBus.provider,
5954
4859
  capabilities: platform.eventBus.capabilities()
5955
4860
  },
5956
4861
  media: {
5957
- provider: config.infrastructure.media,
4862
+ provider: config.infrastructure.media.provider,
5958
4863
  capabilities: platform.media.capabilities()
5959
4864
  }
5960
4865
  };
@@ -6033,37 +4938,17 @@ function compilePathPattern(pattern) {
6033
4938
  return new RegExp(`^${escaped}$`);
6034
4939
  }
6035
4940
 
6036
- // src/adapters/ai/native-adapter.ts
6037
- import { AdapterError as AdapterError3 } from "@nymbalhq/types";
6038
- function createNativeAiAdapter(_logger) {
6039
- return {
6040
- kind: "ai",
6041
- providerName: "native",
6042
- capabilities: () => [],
6043
- producesEvents: [],
6044
- consumesEvents: [],
6045
- initialize: noopInitialize,
6046
- healthCheck: () => okHealth("AI adapter is stubbed \u2014 configure a real provider for v1.0"),
6047
- async embed() {
6048
- throw new AdapterError3("not_configured", "AI embedding is not configured in v0.1");
6049
- },
6050
- async complete() {
6051
- throw new AdapterError3("not_configured", "AI completion is not configured in v0.1");
6052
- }
6053
- };
6054
- }
6055
-
6056
4941
  // src/diagnose.ts
6057
4942
  import { existsSync } from "fs";
6058
4943
  import { resolve as resolve3 } from "path";
6059
4944
  import { fileURLToPath } from "url";
6060
- import { nymbalConfigSchema } from "@nymbalhq/config";
4945
+ import { nymbalConfigSchema, slotFolder } from "@nymbalhq/config";
6061
4946
  import {
6062
- boundedHealthCheck,
4947
+ boundedHealthCheck as boundedHealthCheck2,
6063
4948
  connectionSecrets,
6064
4949
  displayUrl,
6065
4950
  errorText as errorText2,
6066
- HEALTH_CHECK_TIMEOUT_MS
4951
+ HEALTH_CHECK_TIMEOUT_MS as HEALTH_CHECK_TIMEOUT_MS3
6067
4952
  } from "@nymbalhq/types";
6068
4953
  var OWN_MIGRATIONS = fileURLToPath(new URL("../migrations", import.meta.url));
6069
4954
  var PRIMITIVES = ["documentStore", "eventBus", "media"];
@@ -6134,29 +5019,32 @@ async function diagnose(input, options = {}) {
6134
5019
  return { checks: [{ name: "config", status: "down", detail }] };
6135
5020
  }
6136
5021
  const config = parsed.data;
6137
- const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS;
5022
+ const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS3;
6138
5023
  const env = options.env ?? process.env;
6139
5024
  const logger = scrubbingLogger(
6140
5025
  options.logger ?? createLogger({ base: { store: config.store.name } })
6141
5026
  );
6142
5027
  const injected = options.adapters ?? {};
6143
5028
  const infrastructure = config.infrastructure;
6144
- const providers = {
6145
- ...Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s].provider])),
5029
+ const choices = {
5030
+ ...Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s]])),
6146
5031
  documentStore: infrastructure.documentStore,
6147
5032
  eventBus: infrastructure.eventBus,
6148
5033
  media: infrastructure.media,
6149
- security: config.security.adapter
5034
+ security: securityChoice(config)
6150
5035
  };
5036
+ const providers = Object.fromEntries(
5037
+ Object.entries(choices).map(([slot, choice]) => [slot, choice.provider])
5038
+ );
6151
5039
  const packages = [];
6152
5040
  for (const slot of [...COMMERCE_SLOTS, ...PRIMITIVES, "security"]) {
6153
- const entry = PROVIDER_PACKAGES[slot]?.[providers[slot]];
6154
- if (entry === void 0) continue;
6155
- const found = await within(timeoutMs, () => importProviderPackage(slot, providers[slot], env));
5041
+ const resolution = resolveChoice(slot, choices[slot]);
5042
+ if (resolution.kind !== "package") continue;
5043
+ const found = await within(timeoutMs, () => importAdapterModule(slot, choices[slot], env));
6156
5044
  packages.push({
6157
- name: `package ${slot}`,
5045
+ name: `package ${slotFolder(slot)}`,
6158
5046
  status: found.ok ? "ok" : "down",
6159
- detail: found.ok ? entry.package : found.detail
5047
+ detail: found.ok ? resolution.package : found.detail
6160
5048
  });
6161
5049
  }
6162
5050
  const closers = [];
@@ -6234,7 +5122,7 @@ async function diagnose(input, options = {}) {
6234
5122
  const built = {};
6235
5123
  const primitiveFailures = {};
6236
5124
  let documentStore;
6237
- if (infrastructure.documentStore === "postgres-jsonb" && commandStore === void 0) {
5125
+ if (infrastructure.documentStore.provider === "postgres-jsonb" && commandStore === void 0) {
6238
5126
  primitiveFailures.documentStore = notChecked("command store");
6239
5127
  } else {
6240
5128
  const store = await within(
@@ -6269,13 +5157,13 @@ async function diagnose(input, options = {}) {
6269
5157
  return Promise.resolve({ status: "degraded", detail: "no healthCheck" });
6270
5158
  }
6271
5159
  const check = subject2.healthCheck.bind(subject2);
6272
- return boundedHealthCheck(() => check(), { timeoutMs });
5160
+ return boundedHealthCheck2(() => check(), { timeoutMs });
6273
5161
  };
6274
5162
  const stored = commandStore === void 0 ? { ok: true, value: [] } : await within(timeoutMs, () => listStoredSettings(commandStore));
6275
5163
  const settingsOf = async (slot) => {
6276
5164
  const provider = providers[slot];
6277
5165
  if (provider === "custom") return [];
6278
- const declared = declaredSettings(await importProviderPackage(slot, provider, env));
5166
+ const declared = declaredSettings(await importAdapterModule(slot, choices[slot], env));
6279
5167
  if (declared.length === 0) return [];
6280
5168
  if (!stored.ok) throw new Error(`settings not read: ${stored.detail}`);
6281
5169
  return settingValues(config, [{ slot, provider, declared }], stored.value, env, logger);
@@ -6327,14 +5215,17 @@ async function diagnose(input, options = {}) {
6327
5215
  const primitive = built[name];
6328
5216
  if (primitive === void 0) {
6329
5217
  primitives.push({
6330
- name: `primitive ${name}`,
5218
+ name: `primitive ${slotFolder(name)}`,
6331
5219
  status: "down",
6332
5220
  detail: primitiveFailures[name] ?? ""
6333
5221
  });
6334
5222
  } else {
6335
- primitives.push(fromReport(`primitive ${name}`, subject(name), await health(primitive)));
5223
+ primitives.push(
5224
+ fromReport(`primitive ${slotFolder(name)}`, subject(name), await health(primitive))
5225
+ );
6336
5226
  }
6337
5227
  }
5228
+ const eventsCheck = commandStore === void 0 ? { name: "events", status: "down", detail: notChecked("command store") } : migrationsCheck.status !== "ok" ? { name: "events", status: "down", detail: notChecked("migrations") } : await eventLogCheck(commandStore, timeoutMs);
6338
5229
  for (const close of closers) {
6339
5230
  const closed = await within(timeoutMs, close);
6340
5231
  if (!closed.ok) logger.debug({ detail: closed.detail }, "diagnose: a connection did not close");
@@ -6348,22 +5239,47 @@ async function diagnose(input, options = {}) {
6348
5239
  storeCheck,
6349
5240
  migrationsCheck,
6350
5241
  ...slots,
6351
- ...primitives
5242
+ ...primitives,
5243
+ eventsCheck
6352
5244
  ].map((check) => ({
6353
5245
  ...check,
6354
5246
  detail: scrub(secrets.reduce((text2, secret) => text2.split(secret).join("***"), check.detail))
6355
5247
  }));
6356
5248
  return { checks };
6357
5249
  }
5250
+ var DEAD_SHOWN = 5;
5251
+ async function eventLogCheck(store, timeoutMs) {
5252
+ const eventLog = createEventLogRepository(store);
5253
+ const read = await within(
5254
+ timeoutMs,
5255
+ () => store.read(async (tx) => ({
5256
+ dead: await eventLog.countDead(tx),
5257
+ shown: await eventLog.listDead(tx, DEAD_SHOWN),
5258
+ waiting: await eventLog.countRetrying(tx)
5259
+ }))
5260
+ );
5261
+ if (!read.ok) return { name: "events", status: "down", detail: read.detail };
5262
+ const { dead, shown, waiting } = read.value;
5263
+ if (dead === 0) {
5264
+ return { name: "events", status: "ok", detail: `none dead, ${waiting} waiting to retry` };
5265
+ }
5266
+ const named = shown.map((e) => `seq ${e.seq} ${e.event.type} ${e.event.id}`);
5267
+ if (dead > shown.length) named.push(`${dead - shown.length} more`);
5268
+ return {
5269
+ name: "events",
5270
+ status: "degraded",
5271
+ detail: `${dead} dead: ${named.join(", ")}; ${waiting} waiting to retry`
5272
+ };
5273
+ }
6358
5274
  function fromReport(name, what, report) {
6359
5275
  return { name, status: report.status, detail: described(what, report.detail) };
6360
5276
  }
6361
5277
 
6362
5278
  // src/seed/run.ts
6363
- import { inArray as inArray3 } from "drizzle-orm";
6364
- import { v7 as uuidv711 } from "uuid";
6365
- import bcrypt2 from "bcryptjs";
6366
- import { EVT_CATEGORY_CREATED as EVT_CATEGORY_CREATED4, EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED4, EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED4 } from "@nymbalhq/types";
5279
+ import { inArray as inArray5 } from "drizzle-orm";
5280
+ import { v7 as uuidv74 } from "uuid";
5281
+ import bcrypt from "bcryptjs";
5282
+ import { EVT_CATEGORY_CREATED as EVT_CATEGORY_CREATED3, EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED3, EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED3 } from "@nymbalhq/types";
6367
5283
 
6368
5284
  // src/seed/data.ts
6369
5285
  var seedCategories = [
@@ -6423,7 +5339,7 @@ function seedImage(product) {
6423
5339
  }
6424
5340
 
6425
5341
  // src/seed/run.ts
6426
- var { hashSync } = bcrypt2;
5342
+ var { hashSync } = bcrypt;
6427
5343
  async function insertVariants(store, rows) {
6428
5344
  if (rows.length === 0) return;
6429
5345
  const clients = rawClients(store);
@@ -6480,13 +5396,13 @@ async function demoRowsPresent(store, emails) {
6480
5396
  const clients = rawClients(store);
6481
5397
  if (clients.kind === "sqlite") {
6482
5398
  const { categories: categories4, products: products4, customers: customers5 } = sqlite_exports;
6483
- return clients.db.select({ id: categories4.id }).from(categories4).where(inArray3(categories4.slug, categorySlugs)).limit(1).all().length > 0 || clients.db.select({ id: products4.id }).from(products4).where(inArray3(products4.slug, productSlugs)).limit(1).all().length > 0 || clients.db.select({ id: customers5.id }).from(customers5).where(inArray3(customers5.email, emails)).limit(1).all().length > 0;
5399
+ return clients.db.select({ id: categories4.id }).from(categories4).where(inArray5(categories4.slug, categorySlugs)).limit(1).all().length > 0 || clients.db.select({ id: products4.id }).from(products4).where(inArray5(products4.slug, productSlugs)).limit(1).all().length > 0 || clients.db.select({ id: customers5.id }).from(customers5).where(inArray5(customers5.email, emails)).limit(1).all().length > 0;
6484
5400
  }
6485
5401
  const { categories: categories3, products: products3, customers: customers4 } = postgres_exports;
6486
5402
  const [category, product, customer] = await Promise.all([
6487
- clients.db.select({ id: categories3.id }).from(categories3).where(inArray3(categories3.slug, categorySlugs)).limit(1),
6488
- clients.db.select({ id: products3.id }).from(products3).where(inArray3(products3.slug, productSlugs)).limit(1),
6489
- clients.db.select({ id: customers4.id }).from(customers4).where(inArray3(customers4.email, emails)).limit(1)
5403
+ clients.db.select({ id: categories3.id }).from(categories3).where(inArray5(categories3.slug, categorySlugs)).limit(1),
5404
+ clients.db.select({ id: products3.id }).from(products3).where(inArray5(products3.slug, productSlugs)).limit(1),
5405
+ clients.db.select({ id: customers4.id }).from(customers4).where(inArray5(customers4.email, emails)).limit(1)
6490
5406
  ]);
6491
5407
  return category.length > 0 || product.length > 0 || customer.length > 0;
6492
5408
  }
@@ -6529,6 +5445,9 @@ async function insertCustomer(store, row) {
6529
5445
  updatedAt: row.updatedAt
6530
5446
  });
6531
5447
  }
5448
+ function failedOf2(err) {
5449
+ return err.context?.failed ?? [];
5450
+ }
6532
5451
  async function runSeed(deps) {
6533
5452
  const { config, commandStore, documentStore, eventBus, logger, version } = deps;
6534
5453
  const categoryRepo = createCategoryRepository(commandStore);
@@ -6547,7 +5466,7 @@ async function runSeed(deps) {
6547
5466
  }
6548
5467
  const now = /* @__PURE__ */ new Date();
6549
5468
  const categoryInserts = seedCategories.map((c, i) => ({
6550
- id: uuidv711(),
5469
+ id: uuidv74(),
6551
5470
  slug: c.slug,
6552
5471
  name: c.name,
6553
5472
  description: c.description,
@@ -6565,7 +5484,7 @@ async function runSeed(deps) {
6565
5484
  }
6566
5485
  }
6567
5486
  const productInserts = seedProducts.map((p) => ({
6568
- id: uuidv711(),
5487
+ id: uuidv74(),
6569
5488
  slug: p.slug,
6570
5489
  name: p.title,
6571
5490
  description: p.description,
@@ -6583,7 +5502,7 @@ async function runSeed(deps) {
6583
5502
  const variantInserts = productInserts.map((p, i) => {
6584
5503
  const seed = seedProducts[i];
6585
5504
  return {
6586
- id: uuidv711(),
5505
+ id: uuidv74(),
6587
5506
  productId: p.id,
6588
5507
  sku: p.slug.toUpperCase().replaceAll("-", "_"),
6589
5508
  name: "Default",
@@ -6603,7 +5522,7 @@ async function runSeed(deps) {
6603
5522
  });
6604
5523
  await insertProductCategories(commandStore, joinRows);
6605
5524
  const demoCustomer = {
6606
- id: uuidv711(),
5525
+ id: uuidv74(),
6607
5526
  email: demoEmail,
6608
5527
  passwordHash: hashSync("nymbal", 10),
6609
5528
  firstName: "Demo",
@@ -6615,7 +5534,7 @@ async function runSeed(deps) {
6615
5534
  const adminPassword = process.env["NYMBAL_ADMIN_PASSWORD"] ?? "nymbal-admin-dev";
6616
5535
  const adminRoles = ["admin"];
6617
5536
  const adminCustomer = {
6618
- id: uuidv711(),
5537
+ id: uuidv74(),
6619
5538
  email: adminEmail,
6620
5539
  passwordHash: hashSync(adminPassword, 10),
6621
5540
  firstName: "Admin",
@@ -6627,7 +5546,7 @@ async function runSeed(deps) {
6627
5546
  await insertCustomer(commandStore, adminCustomer);
6628
5547
  const events3 = [
6629
5548
  ...categoryInserts.map(
6630
- (c) => makeEvent(EVT_CATEGORY_CREATED4, {
5549
+ (c) => makeEvent(EVT_CATEGORY_CREATED3, {
6631
5550
  category: {
6632
5551
  id: c.id,
6633
5552
  parentId: c.parentId,
@@ -6643,7 +5562,7 @@ async function runSeed(deps) {
6643
5562
  const v = variantInserts[i];
6644
5563
  const seed = seedProducts[i];
6645
5564
  const cat = categoryBySlug.get(seed.categorySlug);
6646
- return makeEvent(EVT_PRODUCT_CREATED4, {
5565
+ return makeEvent(EVT_PRODUCT_CREATED3, {
6647
5566
  product: {
6648
5567
  id: p.id,
6649
5568
  slug: p.slug,
@@ -6680,16 +5599,27 @@ async function runSeed(deps) {
6680
5599
  }
6681
5600
  });
6682
5601
  }),
6683
- makeEvent(EVT_CUSTOMER_CREATED4, {
5602
+ makeEvent(EVT_CUSTOMER_CREATED3, {
6684
5603
  customerId: demoCustomer.id,
6685
5604
  email: demoCustomer.email
6686
5605
  }),
6687
- makeEvent(EVT_CUSTOMER_CREATED4, {
5606
+ makeEvent(EVT_CUSTOMER_CREATED3, {
6688
5607
  customerId: adminCustomer.id,
6689
5608
  email: adminCustomer.email
6690
5609
  })
6691
5610
  ];
6692
- await eventBus.publishBatch(events3);
5611
+ const failures = [];
5612
+ for (const event of events3) {
5613
+ try {
5614
+ await eventBus.publish(event);
5615
+ } catch (err) {
5616
+ if (err?.code !== "adapter.handler_failed") throw err;
5617
+ failures.push({ eventId: event.id, eventType: event.type, failed: failedOf2(err) });
5618
+ }
5619
+ }
5620
+ if (failures.length > 0) {
5621
+ logger.warn({ failures }, "seed events whose handlers failed; they are not retried");
5622
+ }
6693
5623
  logger.info({ adminEmail }, "Admin user seeded");
6694
5624
  if (!process.env["NYMBAL_ADMIN_EMAIL"]) {
6695
5625
  console.log(
@@ -6745,7 +5675,8 @@ async function openReadModels(config, options) {
6745
5675
  try {
6746
5676
  const documentStore = await buildDocumentStore(config, { ...storage, logger, env }, logger, env);
6747
5677
  closers.push(() => documentStore.close());
6748
- if (config.infrastructure.documentStore === "postgres-jsonb") await documentStore.initialize?.();
5678
+ if (config.infrastructure.documentStore.provider === "postgres-jsonb")
5679
+ await documentStore.initialize?.();
6749
5680
  const repos = buildRepositories(store, documentStore);
6750
5681
  const search2 = await slotBuilders({
6751
5682
  config,
@@ -6768,7 +5699,6 @@ export {
6768
5699
  InMemoryDocumentStore,
6769
5700
  InProcessEventBus,
6770
5701
  LOCAL_FS_MEDIA_CAPABILITIES,
6771
- PROVIDER_PACKAGES,
6772
5702
  PROVIDER_REFUND_REASON,
6773
5703
  READ_MODELS,
6774
5704
  READ_MODEL_NAMES,
@@ -6786,6 +5716,9 @@ export {
6786
5716
  buildRepositories,
6787
5717
  buildSecurityHeaders,
6788
5718
  buildServices,
5719
+ checkAdapterModule,
5720
+ createAlertService,
5721
+ createAlertSubscriptionRepository,
6789
5722
  createApp,
6790
5723
  createAuditEntryRepository,
6791
5724
  createAuthService,
@@ -6797,6 +5730,7 @@ export {
6797
5730
  createCommandStore,
6798
5731
  createCustomerRepository,
6799
5732
  createCustomerService,
5733
+ createEmailSuppressionRepository,
6800
5734
  createEventBuilder,
6801
5735
  createEventLogRepository,
6802
5736
  createEventPublisher,
@@ -6807,7 +5741,6 @@ export {
6807
5741
  createLocalFsMediaStorage,
6808
5742
  createLogger,
6809
5743
  createMiddlewareSecurityAdapter,
6810
- createNativeAiAdapter,
6811
5744
  createNativeAnalyticsAdapter,
6812
5745
  createNativeEmailAdapter,
6813
5746
  createNativeReviewsAdapter,
@@ -6815,16 +5748,19 @@ export {
6815
5748
  createNativeShippingAdapter,
6816
5749
  createNativeStubPaymentsAdapter,
6817
5750
  createNativeTaxAdapter,
5751
+ createOrderAccessKeyRepository,
6818
5752
  createOrderHistoryRepository,
6819
5753
  createOrderRefundRepository,
6820
5754
  createOrderRepository,
6821
5755
  createOrderSequenceRepository,
6822
5756
  createOrderService,
5757
+ createOrderShipmentRepository,
6823
5758
  createPlatform,
6824
5759
  createProcessedEventRepository,
6825
5760
  createProductCategoryRepository,
6826
5761
  createProductRepository2 as createProductRepository,
6827
5762
  createProductService,
5763
+ createRecentlyViewedService,
6828
5764
  createRefreshTokenRepository,
6829
5765
  createRefundService,
6830
5766
  createRelay,
@@ -6835,30 +5771,40 @@ export {
6835
5771
  createVariantRepository,
6836
5772
  currentActor,
6837
5773
  currentCorrelationId,
5774
+ declaredSettings,
6838
5775
  decrypt,
6839
5776
  diagnose,
6840
5777
  diffReadModel,
5778
+ emailDelivers,
6841
5779
  encodeSearchCursor,
6842
5780
  encrypt,
6843
5781
  fillFromSettings,
6844
5782
  findAppliedByKey,
6845
- importProviderPackage,
5783
+ importAdapterModule,
6846
5784
  installLine,
6847
5785
  isMissingSettingsTable,
6848
5786
  isValidCorrelationId,
6849
5787
  keyId,
6850
5788
  keyProblem,
6851
5789
  listAuditEntries,
5790
+ migrationState,
5791
+ missingPackage,
5792
+ newAlertToken,
6852
5793
  newCorrelationId,
6853
5794
  openReadModels,
6854
5795
  orderPayment,
5796
+ parseDurationToMs,
6855
5797
  rawClients,
6856
5798
  readSecretsKey,
6857
5799
  rebuild,
6858
5800
  refreshRefunded,
6859
5801
  registerAdminStaticRoute,
5802
+ registerAlertHandler,
5803
+ registerAlertRoutes,
6860
5804
  registerAllRoutes,
6861
5805
  registerHandlers,
5806
+ resolveAuthSecret,
5807
+ resolveChoice,
6862
5808
  resolvePrimitives,
6863
5809
  routeSchemas,
6864
5810
  runAsActor,