@12-apps/marketplace 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/ADOPTING.md +44 -9
  2. package/README.md +149 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
  13. package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
  18. package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
  19. package/dist/chunk-D2X7TOR6.js +1240 -0
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +10 -12
  25. package/dist/ifood/index.js +19 -61
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +113 -497
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +12 -1
  45. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  46. package/src/99food/copy.ts +36 -0
  47. package/src/99food/en-US.ts +19 -0
  48. package/src/99food/index.ts +121 -0
  49. package/src/99food/normalize.ts +263 -0
  50. package/src/99food/outbound.ts +220 -0
  51. package/src/99food/pt-BR.ts +23 -0
  52. package/src/core/acceptance.ts +30 -14
  53. package/src/core/adapter.ts +23 -1
  54. package/src/core/cancellation-outcome.ts +92 -0
  55. package/src/core/cancellation.ts +46 -15
  56. package/src/core/decisions.ts +94 -19
  57. package/src/core/engine.ts +8 -0
  58. package/src/core/fetch-order.ts +253 -0
  59. package/src/core/inbox.ts +8 -2
  60. package/src/core/ingest.ts +10 -2
  61. package/src/core/integration.ts +30 -1
  62. package/src/core/order-fetch-marks.ts +63 -0
  63. package/src/core/outbound-sweep.ts +87 -8
  64. package/src/core/outbound.ts +103 -7
  65. package/src/core/payload-read.ts +101 -0
  66. package/src/core/pipeline.ts +64 -15
  67. package/src/core/ports.ts +32 -0
  68. package/src/core/state.ts +6 -1
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +9 -0
  71. package/src/ifood/normalize.ts +15 -88
  72. package/src/index.ts +10 -1
  73. package/src/rappi/copy.ts +39 -0
  74. package/src/rappi/en-US.ts +14 -0
  75. package/src/rappi/index.ts +155 -0
  76. package/src/rappi/normalize.ts +314 -0
  77. package/src/rappi/outbound.ts +182 -0
  78. package/src/rappi/pt-BR.ts +18 -0
  79. package/src/server/index.ts +1 -0
  80. package/src/server/jobs.ts +38 -4
  81. package/dist/chunk-6OODIO3E.js +0 -395
  82. package/dist/chunk-6OODIO3E.js.map +0 -1
  83. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -0,0 +1,1240 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/core/types.ts
6
+ var PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;
7
+
8
+ // src/core/registry.ts
9
+ var MarketplaceAdapterRegistrationError = class extends Error {
10
+ static {
11
+ __name(this, "MarketplaceAdapterRegistrationError");
12
+ }
13
+ constructor(message) {
14
+ super(`@12-apps/marketplace: ${message}`);
15
+ this.name = "MarketplaceAdapterRegistrationError";
16
+ }
17
+ };
18
+ function assertReasons(adapter) {
19
+ const codes = /* @__PURE__ */ new Set();
20
+ for (const reason of adapter.cancellationReasons()) {
21
+ if (reason.code.trim() === "") {
22
+ throw new MarketplaceAdapterRegistrationError(`${adapter.provider} declares a reason with a blank code.`);
23
+ }
24
+ if (codes.has(reason.code)) {
25
+ throw new MarketplaceAdapterRegistrationError(
26
+ `${adapter.provider} declares the reason code "${reason.code}" twice.`
27
+ );
28
+ }
29
+ codes.add(reason.code);
30
+ }
31
+ if (adapter.capabilities.apiCancel && codes.size === 0) {
32
+ throw new MarketplaceAdapterRegistrationError(
33
+ `${adapter.provider} can cancel through its API but declares no reason to cancel with.`
34
+ );
35
+ }
36
+ }
37
+ __name(assertReasons, "assertReasons");
38
+ function createAdapterRegistry(adapters) {
39
+ if (adapters.length === 0) {
40
+ throw new MarketplaceAdapterRegistrationError("an engine needs at least one adapter.");
41
+ }
42
+ const byProvider = /* @__PURE__ */ new Map();
43
+ for (const adapter of adapters) {
44
+ if (!PROVIDER_ID_PATTERN.test(adapter.provider)) {
45
+ throw new MarketplaceAdapterRegistrationError(
46
+ `provider id "${adapter.provider}" must be uppercase letters, digits and underscores.`
47
+ );
48
+ }
49
+ if (byProvider.has(adapter.provider)) {
50
+ throw new MarketplaceAdapterRegistrationError(`two adapters claim "${adapter.provider}".`);
51
+ }
52
+ assertReasons(adapter);
53
+ byProvider.set(adapter.provider, adapter);
54
+ }
55
+ const providers = [...byProvider.keys()];
56
+ return {
57
+ get: /* @__PURE__ */ __name((provider) => byProvider.get(provider) ?? null, "get"),
58
+ has: /* @__PURE__ */ __name((provider) => byProvider.has(provider), "has"),
59
+ providers: /* @__PURE__ */ __name(() => providers, "providers")
60
+ };
61
+ }
62
+ __name(createAdapterRegistry, "createAdapterRegistry");
63
+ function resolveReason(adapter, code) {
64
+ const reasons = adapter.cancellationReasons();
65
+ if (code === null || code === void 0) return reasons[0] ?? null;
66
+ return reasons.find((reason) => reason.code === code) ?? null;
67
+ }
68
+ __name(resolveReason, "resolveReason");
69
+ function suggestReason(adapter, input) {
70
+ const reasons = adapter.cancellationReasons();
71
+ if (input.itemUnavailable) {
72
+ const unavailable = reasons.find((reason) => reason.itemUnavailable);
73
+ if (unavailable) return unavailable;
74
+ }
75
+ return reasons[0] ?? null;
76
+ }
77
+ __name(suggestReason, "suggestReason");
78
+
79
+ // src/core/outbound-queue.ts
80
+ var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
81
+ function outboundDedupeKey(payload) {
82
+ return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;
83
+ }
84
+ __name(outboundDedupeKey, "outboundDedupeKey");
85
+ async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
86
+ const adapter = ctx.registry.get(provider);
87
+ if (!adapter) return false;
88
+ const able = payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
89
+ if (!able) return false;
90
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
91
+ if (!outcome.enqueued) {
92
+ ctx.ports.logger.warn(
93
+ `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
94
+ );
95
+ }
96
+ return outcome.enqueued;
97
+ }
98
+ __name(enqueueOutbound, "enqueueOutbound");
99
+
100
+ // src/core/inbox.ts
101
+ async function recordInboxEvent(ctx, input) {
102
+ const db = await ctx.ports.db();
103
+ const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
104
+ const existing = await db.marketplaceInboxEvent.findUnique({
105
+ where: key,
106
+ select: { id: true }
107
+ });
108
+ if (existing) return { id: existing.id, fresh: false };
109
+ try {
110
+ const row = await db.marketplaceInboxEvent.create({
111
+ data: {
112
+ clientId: input.clientId,
113
+ provider: input.event.provider,
114
+ eventId: input.event.eventId,
115
+ eventType: input.event.eventType,
116
+ externalOrderId: input.event.externalOrderId,
117
+ payload: input.payload,
118
+ // The engine's clock, not the database's: an announced order's
119
+ // acceptance window counts from here (`./fetch-order.ts`).
120
+ receivedAt: ctx.ports.clock.now()
121
+ },
122
+ select: { id: true }
123
+ });
124
+ return { id: row.id, fresh: true };
125
+ } catch (error) {
126
+ if (error.code !== "P2002") throw error;
127
+ const raced = await db.marketplaceInboxEvent.findUnique({
128
+ where: key,
129
+ select: { id: true }
130
+ });
131
+ return { id: raced?.id ?? "", fresh: false };
132
+ }
133
+ }
134
+ __name(recordInboxEvent, "recordInboxEvent");
135
+ async function settleInboxEvent(ctx, id, outcome, error) {
136
+ if (!id) return;
137
+ const db = await ctx.ports.db();
138
+ await db.marketplaceInboxEvent.update({
139
+ where: { id },
140
+ data: {
141
+ status: outcome,
142
+ // Truncated: a provider's error body can be a page of HTML, and the
143
+ // column exists to be read by a human in a list.
144
+ error: error ? error.slice(0, 500) : null,
145
+ processedAt: ctx.ports.clock.now(),
146
+ attempts: { increment: 1 }
147
+ }
148
+ });
149
+ }
150
+ __name(settleInboxEvent, "settleInboxEvent");
151
+ async function deferInboxEvent(ctx, id, reason) {
152
+ if (!id) return;
153
+ const db = await ctx.ports.db();
154
+ await db.marketplaceInboxEvent.update({
155
+ where: { id },
156
+ data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
157
+ });
158
+ }
159
+ __name(deferInboxEvent, "deferInboxEvent");
160
+ async function listRetryableInboxEvents(ctx) {
161
+ const db = await ctx.ports.db();
162
+ const rows = await db.marketplaceInboxEvent.findMany({
163
+ where: {
164
+ status: { in: ["PENDING", "FAILED"] },
165
+ clientId: { not: null },
166
+ attempts: { lt: ctx.ports.maxInboxAttempts }
167
+ },
168
+ orderBy: { receivedAt: "asc" },
169
+ take: ctx.ports.reconcileBatchSize,
170
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
171
+ });
172
+ return rows.map((row) => ({
173
+ id: row.id,
174
+ clientId: row.clientId,
175
+ provider: row.provider,
176
+ payload: row.payload,
177
+ receivedAt: row.receivedAt
178
+ }));
179
+ }
180
+ __name(listRetryableInboxEvents, "listRetryableInboxEvents");
181
+
182
+ // src/core/integration.ts
183
+ var VIEW_SELECT = {
184
+ provider: true,
185
+ enabled: true,
186
+ environment: true,
187
+ status: true,
188
+ externalMerchantId: true,
189
+ autoAccept: true,
190
+ ackSlaSeconds: true,
191
+ credentials: true,
192
+ lastEventAt: true,
193
+ lastVerifiedAt: true,
194
+ archivedAt: true
195
+ };
196
+ function toView(row) {
197
+ return {
198
+ provider: row.provider,
199
+ enabled: row.enabled,
200
+ environment: row.environment,
201
+ status: row.status,
202
+ externalMerchantId: row.externalMerchantId,
203
+ autoAccept: row.autoAccept,
204
+ ackSlaSeconds: row.ackSlaSeconds,
205
+ connected: row.credentials !== "",
206
+ lastEventAt: row.lastEventAt,
207
+ lastVerifiedAt: row.lastVerifiedAt,
208
+ archivedAt: row.archivedAt ?? null
209
+ };
210
+ }
211
+ __name(toView, "toView");
212
+ async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
213
+ const db = await ctx.ports.db();
214
+ const rows = await db.marketplaceIntegration.findMany({
215
+ where: {
216
+ clientId,
217
+ ...options.providers ? { provider: { in: [...options.providers] } } : {},
218
+ ...options.includeArchived ? {} : { archivedAt: null }
219
+ },
220
+ select: VIEW_SELECT,
221
+ orderBy: { provider: "asc" }
222
+ });
223
+ return rows.map(toView);
224
+ }
225
+ __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
226
+ async function saveMarketplaceIntegration(ctx, input, db) {
227
+ const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
228
+ const mutable = {
229
+ ...input.enabled === void 0 ? {} : { enabled: input.enabled },
230
+ ...input.environment === void 0 ? {} : { environment: input.environment },
231
+ ...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
232
+ ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
233
+ ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
234
+ ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED" }
235
+ };
236
+ const row = await db.marketplaceIntegration.upsert({
237
+ where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
238
+ create: {
239
+ clientId: input.clientId,
240
+ provider: input.provider,
241
+ credentials: sealed ?? "",
242
+ ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
243
+ ...mutable
244
+ },
245
+ update: mutable,
246
+ select: VIEW_SELECT
247
+ });
248
+ return toView(row);
249
+ }
250
+ __name(saveMarketplaceIntegration, "saveMarketplaceIntegration");
251
+ async function connectionMerchantId(ctx, clientId, provider) {
252
+ const db = await ctx.ports.db();
253
+ const row = await db.marketplaceIntegration.findUnique({
254
+ where: { clientId_provider: { clientId, provider } },
255
+ select: { externalMerchantId: true, archivedAt: true }
256
+ });
257
+ return row && !row.archivedAt ? row.externalMerchantId ?? null : null;
258
+ }
259
+ __name(connectionMerchantId, "connectionMerchantId");
260
+ async function resolveIngestionTarget(ctx, clientId, provider) {
261
+ const db = await ctx.ports.db();
262
+ const row = await db.marketplaceIntegration.findUnique({
263
+ where: { clientId_provider: { clientId, provider } },
264
+ select: {
265
+ enabled: true,
266
+ autoAccept: true,
267
+ ackSlaSeconds: true,
268
+ credentials: true,
269
+ archivedAt: true,
270
+ externalMerchantId: true
271
+ }
272
+ });
273
+ if (!row || row.archivedAt) return null;
274
+ return {
275
+ enabled: row.enabled,
276
+ autoAccept: row.autoAccept,
277
+ ackSlaSeconds: row.ackSlaSeconds,
278
+ externalMerchantId: row.externalMerchantId ?? null,
279
+ // An unopenable blob must not read as "no secret configured" — that would
280
+ // turn a key-rotation problem into an endpoint that accepts unsigned
281
+ // deliveries. The secrets port throws instead, and the caller answers 401.
282
+ webhookSecret: row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret
283
+ };
284
+ }
285
+ __name(resolveIngestionTarget, "resolveIngestionTarget");
286
+ function openCredentials(ctx, sealed) {
287
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
288
+ if (typeof parsed !== "object" || parsed === null) {
289
+ throw new Error("Stored marketplace credentials are not an object.");
290
+ }
291
+ const record = parsed;
292
+ return {
293
+ clientId: String(record.clientId ?? ""),
294
+ clientSecret: String(record.clientSecret ?? ""),
295
+ webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
296
+ };
297
+ }
298
+ __name(openCredentials, "openCredentials");
299
+ async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
300
+ const db = await ctx.ports.db();
301
+ const rows = await db.marketplaceIntegration.findMany({
302
+ where: { provider, externalMerchantId, archivedAt: null },
303
+ select: { clientId: true },
304
+ take: 1
305
+ });
306
+ return rows[0]?.clientId ?? null;
307
+ }
308
+ __name(resolveTenantByMerchant, "resolveTenantByMerchant");
309
+ async function markMarketplaceEventSeen(db, clientId, provider, at) {
310
+ await db.marketplaceIntegration.updateMany({
311
+ where: { clientId, provider },
312
+ data: { lastEventAt: at }
313
+ });
314
+ }
315
+ __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
316
+ async function readOutboundConnection(ctx, clientId, provider) {
317
+ const db = await ctx.ports.db();
318
+ const row = await db.marketplaceIntegration.findUnique({
319
+ where: { clientId_provider: { clientId, provider } },
320
+ select: { environment: true, credentials: true }
321
+ });
322
+ if (!row || row.credentials === "") return null;
323
+ return {
324
+ environment: row.environment === "PRODUCTION" ? "PRODUCTION" : "SANDBOX",
325
+ credentials: openCredentials(ctx, row.credentials)
326
+ };
327
+ }
328
+ __name(readOutboundConnection, "readOutboundConnection");
329
+
330
+ // src/core/menu-links.ts
331
+ var LINK_SELECT = {
332
+ id: true,
333
+ provider: true,
334
+ externalSku: true,
335
+ externalName: true,
336
+ menuItemId: true,
337
+ lastSeenAt: true
338
+ };
339
+ function toView2(row) {
340
+ return {
341
+ id: row.id,
342
+ provider: row.provider,
343
+ externalSku: row.externalSku,
344
+ externalName: row.externalName ?? row.externalSku,
345
+ menuItemId: row.menuItemId,
346
+ lastSeenAt: row.lastSeenAt
347
+ };
348
+ }
349
+ __name(toView2, "toView");
350
+ async function listMarketplaceMenuLinks(ctx, input) {
351
+ const db = await ctx.ports.db();
352
+ const rows = await db.marketplaceMenuLink.findMany({
353
+ where: {
354
+ clientId: input.clientId,
355
+ ...input.ids ? { id: { in: [...input.ids] } } : {},
356
+ ...input.provider ? { provider: input.provider } : {},
357
+ ...input.unmappedOnly ? { menuItemId: null } : {}
358
+ },
359
+ select: LINK_SELECT,
360
+ orderBy: { lastSeenAt: "desc" }
361
+ });
362
+ return rows.map(toView2);
363
+ }
364
+ __name(listMarketplaceMenuLinks, "listMarketplaceMenuLinks");
365
+ async function upsertLink(db, input) {
366
+ const row = await db.marketplaceMenuLink.upsert({
367
+ where: {
368
+ clientId_provider_externalSku: {
369
+ clientId: input.clientId,
370
+ provider: input.provider,
371
+ externalSku: input.externalSku
372
+ }
373
+ },
374
+ create: {
375
+ clientId: input.clientId,
376
+ provider: input.provider,
377
+ externalSku: input.externalSku,
378
+ externalName: input.externalName ?? input.externalSku,
379
+ menuItemId: input.menuItemId
380
+ },
381
+ // `externalName` is NOT rewritten here. It is the marketplace's snapshot of
382
+ // what it called the item, and an operator's typing is not a better record
383
+ // of that than the marketplace's own text.
384
+ update: { menuItemId: input.menuItemId },
385
+ select: LINK_SELECT
386
+ });
387
+ return toView2(row);
388
+ }
389
+ __name(upsertLink, "upsertLink");
390
+ async function resolveSkus(db, input) {
391
+ const resolved = /* @__PURE__ */ new Map();
392
+ for (const sku of input.skus) {
393
+ const row = await db.marketplaceMenuLink.upsert({
394
+ where: {
395
+ clientId_provider_externalSku: {
396
+ clientId: input.clientId,
397
+ provider: input.provider,
398
+ externalSku: sku.externalSku
399
+ }
400
+ },
401
+ create: {
402
+ clientId: input.clientId,
403
+ provider: input.provider,
404
+ externalSku: sku.externalSku,
405
+ externalName: sku.name,
406
+ lastSeenAt: input.seenAt
407
+ },
408
+ update: { lastSeenAt: input.seenAt },
409
+ select: { menuItemId: true }
410
+ });
411
+ resolved.set(sku.externalSku, row.menuItemId);
412
+ }
413
+ return resolved;
414
+ }
415
+ __name(resolveSkus, "resolveSkus");
416
+
417
+ // src/core/ingest.ts
418
+ async function composeLines(db, clientId, order, seenAt) {
419
+ const mapping = await resolveSkus(db, {
420
+ clientId,
421
+ provider: order.provider,
422
+ skus: order.lines.map((line) => ({ externalSku: line.externalSku, name: line.name })),
423
+ seenAt
424
+ });
425
+ return order.lines.map((line) => ({
426
+ externalSku: line.externalSku,
427
+ // The MARKETPLACE's text, never the catalog's, even for a mapped line.
428
+ // Every other order snapshots what the buyer was shown, and what this buyer
429
+ // was shown is the marketplace's menu — a mapped line renamed to the host's
430
+ // own product name would quietly disagree with the receipt in the bag.
431
+ name: line.name,
432
+ quantity: line.quantity,
433
+ unitPriceCents: line.unitPriceCents,
434
+ note: line.note,
435
+ subjectRef: mapping.get(line.externalSku) ?? null
436
+ }));
437
+ }
438
+ __name(composeLines, "composeLines");
439
+ function acceptanceData(clientId, orderId, order, settings, now, clockStartsAt) {
440
+ const accepted = settings.autoAccept;
441
+ return {
442
+ clientId,
443
+ orderId,
444
+ provider: order.provider,
445
+ externalOrderId: order.externalOrderId,
446
+ externalDisplayId: order.externalDisplayId,
447
+ // Who carries a delivery: the merchant's courier or the marketplace's fleet.
448
+ deliveredBy: order.deliveredBy ?? null,
449
+ status: accepted ? "ACCEPTED" : "AWAITING",
450
+ acknowledgeBy: new Date(clockStartsAt.getTime() + settings.ackSlaSeconds * 1e3),
451
+ acknowledgedAt: accepted ? now : null,
452
+ externalDueAt: order.deliveryDueAt,
453
+ commissionCents: order.commissionCents,
454
+ // The order's SKUs: what a cancellation's offending SKUs are checked against.
455
+ lineSkus: [...new Set(order.lines.map((line) => line.externalSku))]
456
+ };
457
+ }
458
+ __name(acceptanceData, "acceptanceData");
459
+ async function ingestMarketplaceOrder(ctx, input) {
460
+ const { clientId, order, settings } = input;
461
+ const now = input.now ?? ctx.ports.clock.now();
462
+ const clockStartsAt = input.clockStartsAt ?? now;
463
+ const db = await ctx.ports.db();
464
+ const existing = await db.marketplaceAcceptance.findFirst({
465
+ where: { provider: order.provider, externalOrderId: order.externalOrderId },
466
+ select: { orderId: true }
467
+ });
468
+ if (existing) {
469
+ return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };
470
+ }
471
+ const accepted = settings.autoAccept;
472
+ const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
473
+ const lines = await composeLines(tx, clientId, order, now);
474
+ const created = await ctx.ports.order.create(clientId, order, lines, tx);
475
+ await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });
476
+ await markMarketplaceEventSeen(tx, clientId, order.provider, now);
477
+ return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
478
+ });
479
+ if (accepted) {
480
+ await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, order.provider);
481
+ await ctx.ports.order.onAccepted(clientId, orderId);
482
+ }
483
+ ctx.ports.publishChanged(clientId);
484
+ return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
485
+ }
486
+ __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
487
+
488
+ // src/core/cancellation-outcome.ts
489
+ async function tell(ctx, what, orderId, call) {
490
+ try {
491
+ await call();
492
+ } catch (error) {
493
+ ctx.ports.logger.error(
494
+ `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
495
+ );
496
+ }
497
+ }
498
+ __name(tell, "tell");
499
+ function requestsFirst(ctx) {
500
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
501
+ }
502
+ __name(requestsFirst, "requestsFirst");
503
+ async function rejectConfirmed(db, orderId, now) {
504
+ await db.marketplaceAcceptance.updateMany({
505
+ where: { orderId, status: "AWAITING" },
506
+ data: { status: "REJECTED", acknowledgedAt: now }
507
+ });
508
+ await db.marketplaceAcceptance.updateMany({
509
+ where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
510
+ data: { status: "REJECTED" }
511
+ });
512
+ }
513
+ __name(rejectConfirmed, "rejectConfirmed");
514
+ async function confirmedToHost(ctx, clientId, orderId) {
515
+ if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
516
+ await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
517
+ }
518
+ __name(confirmedToHost, "confirmedToHost");
519
+ async function tellCancellationConfirmed(ctx, clientId, orderId) {
520
+ const hook = ctx.ports.order.onCancellationConfirmed;
521
+ if (!hook) return false;
522
+ await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
523
+ return true;
524
+ }
525
+ __name(tellCancellationConfirmed, "tellCancellationConfirmed");
526
+ async function tellCancellationFailed(ctx, clientId, orderId, reason) {
527
+ const hook = ctx.ports.order.onCancellationFailed;
528
+ if (!hook) return;
529
+ await tell(
530
+ ctx,
531
+ `had its cancellation request fail (${reason})`,
532
+ orderId,
533
+ () => hook.call(ctx.ports.order, clientId, orderId, reason)
534
+ );
535
+ }
536
+ __name(tellCancellationFailed, "tellCancellationFailed");
537
+ function cancellationWindowMs(ctx, adapter) {
538
+ return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
539
+ }
540
+ __name(cancellationWindowMs, "cancellationWindowMs");
541
+ function failedRequestData(reason) {
542
+ return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
543
+ }
544
+ __name(failedRequestData, "failedRequestData");
545
+
546
+ // src/core/cancellation.ts
547
+ function noStandingRequest(cancellationStatus) {
548
+ return cancellationStatus === null || cancellationStatus === "FAILED";
549
+ }
550
+ __name(noStandingRequest, "noStandingRequest");
551
+ var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
552
+ var CLAIM_SELECT = {
553
+ orderId: true,
554
+ provider: true,
555
+ status: true,
556
+ cancellationStatus: true,
557
+ lineSkus: true
558
+ };
559
+ function notPendingProblem(row, path, allowed = ["AWAITING"]) {
560
+ if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
561
+ if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
562
+ const status = row.status;
563
+ return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
564
+ }
565
+ __name(notPendingProblem, "notPendingProblem");
566
+ function lineSkusOf(row) {
567
+ return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
568
+ }
569
+ __name(lineSkusOf, "lineSkusOf");
570
+ function skuProblems(reason, skus, row, path) {
571
+ if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
572
+ const known = lineSkusOf(row);
573
+ if (!known) return [];
574
+ return skus.flatMap(
575
+ (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
576
+ );
577
+ }
578
+ __name(skuProblems, "skuProblems");
579
+ function invalidReasonProblem(adapter, reason, code, path) {
580
+ if (code === null || code === void 0 || reason) return null;
581
+ const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
582
+ return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
583
+ }
584
+ __name(invalidReasonProblem, "invalidReasonProblem");
585
+ function planCancellation(adapter, input, row, path) {
586
+ if (!adapter) return { status: null, reason: null, skus: [] };
587
+ const reason = resolveReason(adapter, input.reasonCode);
588
+ const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
589
+ if (invalid) return [invalid];
590
+ const skus = [...new Set(input.offendingSkus ?? [])];
591
+ const problems = skuProblems(reason, skus, row, path);
592
+ if (problems.length > 0) return problems;
593
+ const { apiCancel, cancelAfterAccept } = adapter.capabilities;
594
+ const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
595
+ return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
596
+ }
597
+ __name(planCancellation, "planCancellation");
598
+ function refusalData(plan, fromStatus, now) {
599
+ return {
600
+ status: "REJECTED",
601
+ // An accepted row keeps the instant it was accepted; a row leaving the
602
+ // clock is acknowledged now (the table's CHECK pairs the two).
603
+ ...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
604
+ cancellationStatus: plan.status,
605
+ cancellationReasonCode: plan.reason?.code ?? null,
606
+ cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
607
+ cancellationRequestedAt: plan.status === "PENDING" ? now : null,
608
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
609
+ };
610
+ }
611
+ __name(refusalData, "refusalData");
612
+ function requestData(plan, now) {
613
+ return {
614
+ cancellationStatus: plan.status,
615
+ cancellationReasonCode: plan.reason?.code ?? null,
616
+ cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
617
+ cancellationRequestedAt: plan.status === "PENDING" ? now : null,
618
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
619
+ };
620
+ }
621
+ __name(requestData, "requestData");
622
+ async function failCancellationRequest(ctx, input) {
623
+ const db = await ctx.ports.db();
624
+ const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
625
+ const row = await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } });
626
+ if (!row) return false;
627
+ const moved = await db.marketplaceAcceptance.updateMany({
628
+ where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
629
+ data: failedRequestData("REFUSED")
630
+ });
631
+ if (moved.count === 0) return false;
632
+ ctx.ports.publishChanged(input.clientId);
633
+ await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
634
+ return true;
635
+ }
636
+ __name(failCancellationRequest, "failCancellationRequest");
637
+
638
+ // src/core/acceptance.ts
639
+ async function listPendingAcceptances(ctx, clientId, orderIds) {
640
+ const db = await ctx.ports.db();
641
+ const rows = await db.marketplaceAcceptance.findMany({
642
+ where: { clientId, status: "AWAITING", ...orderIds ? { orderId: { in: [...orderIds] } } : {} },
643
+ orderBy: { acknowledgeBy: "asc" },
644
+ select: {
645
+ id: true,
646
+ orderId: true,
647
+ provider: true,
648
+ externalOrderId: true,
649
+ externalDisplayId: true,
650
+ acknowledgeBy: true,
651
+ externalDueAt: true,
652
+ commissionCents: true
653
+ }
654
+ });
655
+ if (rows.length === 0) return [];
656
+ const summaries = await ctx.ports.order.summarize(
657
+ clientId,
658
+ rows.map((row) => row.orderId)
659
+ );
660
+ return rows.map((row) => {
661
+ const summary = summaries.get(row.orderId);
662
+ return {
663
+ ...row,
664
+ buyerName: summary?.buyerName ?? null,
665
+ totalCents: summary?.totalCents ?? 0,
666
+ unmappedLines: summary?.unmappedLines ?? 0,
667
+ createdAt: summary?.createdAt ?? null
668
+ };
669
+ });
670
+ }
671
+ __name(listPendingAcceptances, "listPendingAcceptances");
672
+ async function expireLapsedAcceptances(ctx, now) {
673
+ const db = await ctx.ports.db();
674
+ const lapsed = await db.marketplaceAcceptance.findMany({
675
+ // An order whose cancellation request waits is left to that request: its
676
+ // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
677
+ // never hears EXPIRED and then the confirmation for one order.
678
+ where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
679
+ select: { id: true, clientId: true, orderId: true }
680
+ });
681
+ if (lapsed.length === 0) return { expired: 0, tenants: 0 };
682
+ const result = await db.marketplaceAcceptance.updateMany({
683
+ where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
684
+ data: { status: "EXPIRED", acknowledgedAt: now }
685
+ });
686
+ for (const row of lapsed) {
687
+ try {
688
+ await ctx.ports.order.onRefused(row.clientId, row.orderId, "EXPIRED");
689
+ } catch (error) {
690
+ ctx.ports.logger.error(
691
+ `marketplace.expire-acceptances: order ${row.orderId} expired but the host's refusal failed: ` + (error instanceof Error ? error.message : String(error))
692
+ );
693
+ }
694
+ }
695
+ const tenants = new Set(lapsed.map((row) => row.clientId));
696
+ for (const clientId of tenants) ctx.ports.publishChanged(clientId);
697
+ return { expired: result.count, tenants: tenants.size };
698
+ }
699
+ __name(expireLapsedAcceptances, "expireLapsedAcceptances");
700
+ function hasConfirmHook(ctx) {
701
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
702
+ }
703
+ __name(hasConfirmHook, "hasConfirmHook");
704
+ async function cancelAcceptance(ctx, input) {
705
+ const db = await ctx.ports.db();
706
+ const row = await db.marketplaceAcceptance.findFirst({
707
+ where: {
708
+ clientId: input.clientId,
709
+ provider: input.provider,
710
+ externalOrderId: input.externalOrderId
711
+ },
712
+ select: { orderId: true, cancellationStatus: true }
713
+ });
714
+ if (!row) return false;
715
+ const answered = await ctx.ports.transaction(async (tx) => {
716
+ await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());
717
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
718
+ where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "REQUESTED", "FAILED"] } },
719
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
720
+ });
721
+ return confirmed.count > 0;
722
+ });
723
+ const storeAsked = answered || row.cancellationStatus === "CONFIRMED";
724
+ const told = storeAsked && (answered ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));
725
+ if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
726
+ ctx.ports.publishChanged(input.clientId);
727
+ return true;
728
+ }
729
+ __name(cancelAcceptance, "cancelAcceptance");
730
+
731
+ // src/core/order-fetch-marks.ts
732
+ var MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
733
+ var markerId = /* @__PURE__ */ __name((externalOrderId) => `engine:cancelled:${externalOrderId}`, "markerId");
734
+ async function markCancelledBeforeIngest(ctx, input) {
735
+ if (!ctx.registry.get(input.provider)?.fetchOrder) return;
736
+ const db = await ctx.ports.db();
737
+ try {
738
+ await db.marketplaceInboxEvent.create({
739
+ data: {
740
+ clientId: input.clientId,
741
+ provider: input.provider,
742
+ eventId: markerId(input.externalOrderId),
743
+ eventType: MARKER_TYPE,
744
+ externalOrderId: input.externalOrderId,
745
+ payload: {},
746
+ status: "IGNORED",
747
+ error: "cancelled before the order was ingested",
748
+ receivedAt: ctx.ports.clock.now(),
749
+ processedAt: ctx.ports.clock.now()
750
+ },
751
+ select: { id: true }
752
+ });
753
+ } catch (error) {
754
+ if (error.code !== "P2002") throw error;
755
+ }
756
+ }
757
+ __name(markCancelledBeforeIngest, "markCancelledBeforeIngest");
758
+ async function cancelledBeforeIngest(ctx, input) {
759
+ const db = await ctx.ports.db();
760
+ const row = await db.marketplaceInboxEvent.findUnique({
761
+ where: { provider_eventId: { provider: input.provider, eventId: markerId(input.externalOrderId) } },
762
+ select: { clientId: true }
763
+ });
764
+ return row !== null && row.clientId === input.clientId;
765
+ }
766
+ __name(cancelledBeforeIngest, "cancelledBeforeIngest");
767
+
768
+ // src/core/fetch-order.ts
769
+ var MARKETPLACE_FETCH_ORDER_JOB = "marketplace.fetch-order";
770
+ var FetchOrderRetryError = class extends Error {
771
+ static {
772
+ __name(this, "FetchOrderRetryError");
773
+ }
774
+ constructor(message) {
775
+ super(message);
776
+ this.name = "FetchOrderRetryError";
777
+ }
778
+ };
779
+ var AWAITING_ORDER_REASON = "order details to fetch";
780
+ var FETCH_REQUEUE_AGE_MS = 2 * 6e4;
781
+ async function awaitOrderBody(ctx, clientId, inboxId, dedupeKey = `${MARKETPLACE_FETCH_ORDER_JOB}:${inboxId}`) {
782
+ await deferInboxEvent(ctx, inboxId, AWAITING_ORDER_REASON);
783
+ const payload = { clientId, inboxId };
784
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_FETCH_ORDER_JOB, payload, { dedupeKey });
785
+ if (!outcome.enqueued) {
786
+ ctx.ports.logger.warn(
787
+ `${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${inboxId} was not queued; the reconciliation sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
788
+ );
789
+ }
790
+ }
791
+ __name(awaitOrderBody, "awaitOrderBody");
792
+ async function requeueOwedFetch(ctx, input) {
793
+ const now = ctx.ports.clock.now();
794
+ const age = input.receivedAt ? now.getTime() - input.receivedAt.getTime() : Number.POSITIVE_INFINITY;
795
+ if (age < FETCH_REQUEUE_AGE_MS) return { kind: "awaitingOrder" };
796
+ ctx.ports.logger.warn(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${input.id} still waits for its order body; re-queued`);
797
+ await awaitOrderBody(ctx, input.clientId, input.id, `${MARKETPLACE_FETCH_ORDER_JOB}:${input.id}:${now.getTime()}`);
798
+ return { kind: "awaitingOrder" };
799
+ }
800
+ __name(requeueOwedFetch, "requeueOwedFetch");
801
+ async function owedFetch(ctx, payload) {
802
+ const db = await ctx.ports.db();
803
+ const row = await db.marketplaceInboxEvent.findUnique({
804
+ where: { id: payload.inboxId },
805
+ select: { id: true, clientId: true, provider: true, payload: true, status: true, receivedAt: true }
806
+ });
807
+ if (!row || row.clientId !== payload.clientId) return "no such inbox row for this tenant";
808
+ if (row.status !== "PENDING" && row.status !== "FAILED") return `the row is already ${row.status}`;
809
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
810
+ if (!event?.orderToFetch || event.order) return "the event announces no order to fetch";
811
+ return { row, event };
812
+ }
813
+ __name(owedFetch, "owedFetch");
814
+ async function fetchThroughAdapter(ctx, clientId, provider, externalOrderId) {
815
+ const adapter = ctx.registry.get(provider);
816
+ if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
817
+ let connection;
818
+ try {
819
+ connection = await readOutboundConnection(ctx, clientId, provider);
820
+ } catch (error) {
821
+ const reason = error instanceof Error ? error.message : String(error);
822
+ return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
823
+ }
824
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
825
+ try {
826
+ return await adapter.fetchOrder(
827
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
828
+ { externalOrderId }
829
+ );
830
+ } catch (error) {
831
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
832
+ }
833
+ }
834
+ __name(fetchThroughAdapter, "fetchThroughAdapter");
835
+ async function refusalOf(ctx, clientId, order, connectionMerchantId2) {
836
+ if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
837
+ return { settle: "IGNORED", reason: "cancelled before its order body arrived", failed: false };
838
+ }
839
+ const mismatch = merchantMismatch(order, connectionMerchantId2);
840
+ return mismatch ? { settle: "FAILED", reason: mismatch, failed: true } : null;
841
+ }
842
+ __name(refusalOf, "refusalOf");
843
+ function merchantMismatch(order, connectionMerchantId2) {
844
+ const named = order.externalMerchantId ?? null;
845
+ if (named === null || connectionMerchantId2 === null || named === connectionMerchantId2) return null;
846
+ return `the order names merchant ${named}, not this connection's`;
847
+ }
848
+ __name(merchantMismatch, "merchantMismatch");
849
+ async function ingestFetched(ctx, row, clientId, order, target) {
850
+ const refusal = await refusalOf(ctx, clientId, order, target.externalMerchantId);
851
+ if (refusal) {
852
+ await settleInboxEvent(ctx, row.id, refusal.settle, refusal.reason);
853
+ if (!refusal.failed) return { kind: "skipped", reason: refusal.reason };
854
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} refused: ${refusal.reason}`);
855
+ return { kind: "failed", reason: refusal.reason };
856
+ }
857
+ const ingested = await ingestMarketplaceOrder(ctx, {
858
+ clientId,
859
+ order,
860
+ settings: { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
861
+ // The store's acceptance window starts when the event arrived, not when a
862
+ // delayed fetch finished: the marketplace's own clock started then.
863
+ clockStartsAt: row.receivedAt ?? void 0
864
+ });
865
+ const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };
866
+ if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);
867
+ await settleInboxEvent(ctx, row.id, "PROCESSED");
868
+ return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
869
+ }
870
+ __name(ingestFetched, "ingestFetched");
871
+ async function runFetchOrder(ctx, payload, attempt) {
872
+ const owed = await owedFetch(ctx, payload);
873
+ if (typeof owed === "string") return { kind: "skipped", reason: owed };
874
+ const { row, event } = owed;
875
+ const target = await resolveIngestionTarget(ctx, payload.clientId, event.provider);
876
+ if (!target?.enabled) {
877
+ await deferInboxEvent(ctx, row.id, "integration is not enabled");
878
+ return { kind: "skipped", reason: "integration is not enabled" };
879
+ }
880
+ const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
881
+ if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
882
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
883
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
884
+ throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
885
+ }
886
+ await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
887
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
888
+ return { kind: "failed", reason };
889
+ }
890
+ __name(runFetchOrder, "runFetchOrder");
891
+
892
+ // src/core/outbound-sweep.ts
893
+ var OUTBOUND_STALE_MS = 10 * 6e4;
894
+ var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
895
+ var WAITING = ["PENDING", "REQUESTED"];
896
+ var OWED_SELECT = { clientId: true, orderId: true, provider: true };
897
+ function sweepDedupeKey(action, orderId, now) {
898
+ return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
899
+ }
900
+ __name(sweepDedupeKey, "sweepDedupeKey");
901
+ async function requeue(ctx, rows, action, now) {
902
+ let queued = 0;
903
+ for (const row of rows) {
904
+ const payload = { clientId: row.clientId, orderId: row.orderId, action };
905
+ if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
906
+ }
907
+ return queued;
908
+ }
909
+ __name(requeue, "requeue");
910
+ async function failAsTimeout(ctx, rows) {
911
+ const db = await ctx.ports.db();
912
+ let failed = 0;
913
+ for (const row of rows) {
914
+ const moved = await db.marketplaceAcceptance.updateMany({
915
+ where: { orderId: row.orderId, clientId: row.clientId, cancellationStatus: { in: WAITING } },
916
+ data: failedRequestData("TIMEOUT")
917
+ });
918
+ if (moved.count === 0) continue;
919
+ failed += 1;
920
+ ctx.ports.publishChanged(row.clientId);
921
+ await tellCancellationFailed(ctx, row.clientId, row.orderId, "TIMEOUT");
922
+ }
923
+ return failed;
924
+ }
925
+ __name(failAsTimeout, "failAsTimeout");
926
+ async function waitingSince(ctx, cutoff, statuses, provider) {
927
+ const db = await ctx.ports.db();
928
+ return await db.marketplaceAcceptance.findMany({
929
+ where: { ...provider ? { provider } : {}, cancellationStatus: { in: statuses }, cancellationRequestedAt: { lt: cutoff } },
930
+ select: OWED_SELECT
931
+ });
932
+ }
933
+ __name(waitingSince, "waitingSince");
934
+ async function expireUnanswered(ctx, now) {
935
+ if (!requestsFirst(ctx)) return 0;
936
+ let expired = 0;
937
+ for (const provider of ctx.registry.providers()) {
938
+ const adapter = ctx.registry.get(provider);
939
+ const window = adapter ? cancellationWindowMs(ctx, adapter) : null;
940
+ if (window === null) continue;
941
+ const cutoff = new Date(now.getTime() - window);
942
+ expired += await failAsTimeout(ctx, await waitingSince(ctx, cutoff, WAITING, provider));
943
+ }
944
+ return expired;
945
+ }
946
+ __name(expireUnanswered, "expireUnanswered");
947
+ async function sweepOutbound(ctx, now) {
948
+ const db = await ctx.ports.db();
949
+ const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
950
+ const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
951
+ const timedOut = await expireUnanswered(ctx, now);
952
+ const givenUp = await failAsTimeout(ctx, await waitingSince(ctx, giveUp, requestsFirst(ctx) ? WAITING : ["PENDING"]));
953
+ const cancellations = await db.marketplaceAcceptance.findMany({
954
+ where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: stale, gte: giveUp } },
955
+ select: OWED_SELECT
956
+ });
957
+ const confirms = await db.marketplaceAcceptance.findMany({
958
+ where: {
959
+ status: "ACCEPTED",
960
+ confirmedAt: null,
961
+ confirmFailedAt: null,
962
+ acknowledgedAt: { lt: stale, gte: giveUp },
963
+ // An accept the store asked to cancel is not confirmed while the request waits.
964
+ ...NO_STANDING_REQUEST
965
+ },
966
+ select: OWED_SELECT
967
+ });
968
+ const requeued = await requeue(ctx, cancellations, "requestCancellation", now) + await requeue(ctx, confirms, "confirm", now);
969
+ if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
970
+ return { requeued, givenUp, timedOut };
971
+ }
972
+ __name(sweepOutbound, "sweepOutbound");
973
+
974
+ // src/core/outbound.ts
975
+ var OutboundRetryError = class extends Error {
976
+ static {
977
+ __name(this, "OutboundRetryError");
978
+ }
979
+ constructor(message) {
980
+ super(message);
981
+ this.name = "OutboundRetryError";
982
+ }
983
+ };
984
+ var ROW_SELECT = {
985
+ orderId: true,
986
+ provider: true,
987
+ externalOrderId: true,
988
+ externalDisplayId: true,
989
+ status: true,
990
+ confirmedAt: true,
991
+ confirmFailedAt: true,
992
+ cancellationStatus: true,
993
+ cancellationReasonCode: true,
994
+ cancellationOffendingSkus: true,
995
+ cancellationRequestedAt: true,
996
+ preparationMinutes: true,
997
+ createdAt: true
998
+ };
999
+ function refOf(row) {
1000
+ return {
1001
+ externalOrderId: row.externalOrderId,
1002
+ externalDisplayId: row.externalDisplayId,
1003
+ hostOrderCode: row.orderId,
1004
+ placedAt: row.createdAt
1005
+ };
1006
+ }
1007
+ __name(refOf, "refOf");
1008
+ function confirmSkip(row, adapter) {
1009
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
1010
+ if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
1011
+ return `a cancellation request is ${row.cancellationStatus}`;
1012
+ }
1013
+ if (row.confirmedAt || row.confirmFailedAt) return "the confirm is already stamped";
1014
+ if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
1015
+ return null;
1016
+ }
1017
+ __name(confirmSkip, "confirmSkip");
1018
+ async function stampConfirm(ctx, row, succeeded, now) {
1019
+ const db = await ctx.ports.db();
1020
+ await db.marketplaceAcceptance.updateMany({
1021
+ where: { orderId: row.orderId, confirmedAt: null, confirmFailedAt: null },
1022
+ data: succeeded ? { confirmedAt: now } : { confirmFailedAt: now }
1023
+ });
1024
+ }
1025
+ __name(stampConfirm, "stampConfirm");
1026
+ async function stampCancellation(ctx, row, status, clientId) {
1027
+ if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
1028
+ const db = await ctx.ports.db();
1029
+ const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
1030
+ const moved = await db.marketplaceAcceptance.updateMany({
1031
+ where: { orderId: row.orderId, cancellationStatus: "PENDING" },
1032
+ data
1033
+ });
1034
+ if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
1035
+ }
1036
+ __name(stampCancellation, "stampCancellation");
1037
+ function answerableRequest(row) {
1038
+ const waiting = { cancellationStatus: { in: ["PENDING", "FAILED"] } };
1039
+ if (row.cancellationRequestedAt === null) return [waiting];
1040
+ const tombstone = { status: "ACCEPTED", cancellationStatus: null, cancellationRequestedAt: row.cancellationRequestedAt };
1041
+ return [waiting, tombstone];
1042
+ }
1043
+ __name(answerableRequest, "answerableRequest");
1044
+ async function stampConfirmedCancellation(ctx, row, clientId) {
1045
+ const now = ctx.ports.clock.now();
1046
+ const moved = await ctx.ports.transaction(async (tx) => {
1047
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
1048
+ where: { orderId: row.orderId, OR: answerableRequest(row) },
1049
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
1050
+ });
1051
+ if (confirmed.count === 0) return false;
1052
+ await rejectConfirmed(tx, row.orderId, now);
1053
+ return true;
1054
+ });
1055
+ if (!moved) return;
1056
+ try {
1057
+ await confirmedToHost(ctx, clientId, row.orderId);
1058
+ } catch (error) {
1059
+ ctx.ports.logger.error(
1060
+ `marketplace.outbound: order ${row.orderId} was cancelled on the store's request but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
1061
+ );
1062
+ }
1063
+ }
1064
+ __name(stampConfirmedCancellation, "stampConfirmedCancellation");
1065
+ async function connectionFor(ctx, clientId, provider) {
1066
+ try {
1067
+ return await readOutboundConnection(ctx, clientId, provider) ?? "no credentials on file";
1068
+ } catch (error) {
1069
+ return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
1070
+ }
1071
+ }
1072
+ __name(connectionFor, "connectionFor");
1073
+ async function settle(ctx, payload, row, result, attempt, succeed, fail) {
1074
+ if (result.kind === "accepted") {
1075
+ await succeed();
1076
+ ctx.ports.publishChanged(payload.clientId);
1077
+ return { kind: "done", action: payload.action };
1078
+ }
1079
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1080
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1081
+ throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);
1082
+ }
1083
+ await fail();
1084
+ ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);
1085
+ ctx.ports.publishChanged(payload.clientId);
1086
+ return { kind: "failed", action: payload.action, reason };
1087
+ }
1088
+ __name(settle, "settle");
1089
+ async function runConfirm(ctx, payload, row, adapter, attempt) {
1090
+ const skip = confirmSkip(row, adapter);
1091
+ if (skip) return { kind: "skipped", reason: skip };
1092
+ const now = ctx.ports.clock.now();
1093
+ const connection = await connectionFor(ctx, payload.clientId, row.provider);
1094
+ const result = typeof connection === "string" ? { kind: "refused", status: 0, message: connection } : await adapter.confirm(
1095
+ { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
1096
+ refOf(row),
1097
+ // The stated preparation time, for a marketplace whose confirm takes one.
1098
+ { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
1099
+ );
1100
+ return settle(
1101
+ ctx,
1102
+ payload,
1103
+ row,
1104
+ result,
1105
+ attempt,
1106
+ () => stampConfirm(ctx, row, true, now),
1107
+ () => stampConfirm(ctx, row, false, now)
1108
+ );
1109
+ }
1110
+ __name(runConfirm, "runConfirm");
1111
+ function pastWindow(ctx, row, adapter) {
1112
+ if (!requestsFirst(ctx)) return false;
1113
+ const window = cancellationWindowMs(ctx, adapter);
1114
+ if (window === null || row.cancellationRequestedAt === null) return false;
1115
+ return ctx.ports.clock.now().getTime() - row.cancellationRequestedAt.getTime() > window;
1116
+ }
1117
+ __name(pastWindow, "pastWindow");
1118
+ function skusOf(row) {
1119
+ return Array.isArray(row.cancellationOffendingSkus) ? row.cancellationOffendingSkus.map(String) : [];
1120
+ }
1121
+ __name(skusOf, "skusOf");
1122
+ async function runCancellation(ctx, payload, row, adapter, attempt) {
1123
+ if (row.cancellationStatus !== "PENDING") {
1124
+ return { kind: "skipped", reason: `the request is ${row.cancellationStatus ?? "absent"}, not PENDING` };
1125
+ }
1126
+ if (pastWindow(ctx, row, adapter)) {
1127
+ await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
1128
+ return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
1129
+ }
1130
+ const reason = resolveReason(adapter, row.cancellationReasonCode);
1131
+ const connection = await connectionFor(ctx, payload.clientId, row.provider);
1132
+ let result;
1133
+ if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's" };
1134
+ else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection };
1135
+ else {
1136
+ result = await adapter.requestCancellation(
1137
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
1138
+ refOf(row),
1139
+ { reason, text: "", mode: "MANUAL", offendingSkus: skusOf(row) }
1140
+ );
1141
+ }
1142
+ const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
1143
+ return settle(
1144
+ ctx,
1145
+ payload,
1146
+ row,
1147
+ result,
1148
+ attempt,
1149
+ () => stampCancellation(ctx, row, taken, payload.clientId),
1150
+ () => stampCancellation(ctx, row, "FAILED", payload.clientId)
1151
+ );
1152
+ }
1153
+ __name(runCancellation, "runCancellation");
1154
+ async function stampLastAttemptFailure(ctx, payload, error) {
1155
+ const reason = error instanceof Error ? error.message : String(error);
1156
+ const db = await ctx.ports.db();
1157
+ const moved = await (payload.action === "confirm" ? db.marketplaceAcceptance.updateMany({
1158
+ where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },
1159
+ data: { confirmFailedAt: ctx.ports.clock.now() }
1160
+ }) : db.marketplaceAcceptance.updateMany({
1161
+ where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
1162
+ data: failedRequestData("REFUSED")
1163
+ }));
1164
+ ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
1165
+ ctx.ports.publishChanged(payload.clientId);
1166
+ if (payload.action === "requestCancellation" && moved.count > 0) {
1167
+ await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
1168
+ }
1169
+ return { kind: "failed", action: payload.action, reason };
1170
+ }
1171
+ __name(stampLastAttemptFailure, "stampLastAttemptFailure");
1172
+ async function runOnce(ctx, payload, attempt) {
1173
+ const db = await ctx.ports.db();
1174
+ const row = await db.marketplaceAcceptance.findFirst({
1175
+ where: { orderId: payload.orderId, clientId: payload.clientId },
1176
+ select: ROW_SELECT
1177
+ });
1178
+ if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
1179
+ const adapter = ctx.registry.get(row.provider);
1180
+ if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
1181
+ return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
1182
+ }
1183
+ __name(runOnce, "runOnce");
1184
+ async function runOutbound(ctx, payload, attempt) {
1185
+ try {
1186
+ return await runOnce(ctx, payload, attempt);
1187
+ } catch (error) {
1188
+ if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;
1189
+ return stampLastAttemptFailure(ctx, payload, error);
1190
+ }
1191
+ }
1192
+ __name(runOutbound, "runOutbound");
1193
+
1194
+ export {
1195
+ requestsFirst,
1196
+ tellCancellationFailed,
1197
+ PROVIDER_ID_PATTERN,
1198
+ MarketplaceAdapterRegistrationError,
1199
+ createAdapterRegistry,
1200
+ resolveReason,
1201
+ suggestReason,
1202
+ NO_STANDING_REQUEST,
1203
+ CLAIM_SELECT,
1204
+ notPendingProblem,
1205
+ planCancellation,
1206
+ refusalData,
1207
+ requestData,
1208
+ failCancellationRequest,
1209
+ listPendingAcceptances,
1210
+ expireLapsedAcceptances,
1211
+ cancelAcceptance,
1212
+ listMarketplaceIntegrations,
1213
+ saveMarketplaceIntegration,
1214
+ connectionMerchantId,
1215
+ resolveIngestionTarget,
1216
+ resolveTenantByMerchant,
1217
+ listMarketplaceMenuLinks,
1218
+ upsertLink,
1219
+ MARKETPLACE_OUTBOUND_JOB,
1220
+ outboundDedupeKey,
1221
+ enqueueOutbound,
1222
+ recordInboxEvent,
1223
+ settleInboxEvent,
1224
+ deferInboxEvent,
1225
+ listRetryableInboxEvents,
1226
+ ingestMarketplaceOrder,
1227
+ markCancelledBeforeIngest,
1228
+ MARKETPLACE_FETCH_ORDER_JOB,
1229
+ FetchOrderRetryError,
1230
+ awaitOrderBody,
1231
+ requeueOwedFetch,
1232
+ merchantMismatch,
1233
+ runFetchOrder,
1234
+ OUTBOUND_STALE_MS,
1235
+ OUTBOUND_GIVE_UP_MS,
1236
+ sweepOutbound,
1237
+ OutboundRetryError,
1238
+ runOutbound
1239
+ };
1240
+ //# sourceMappingURL=chunk-D2X7TOR6.js.map