@12-apps/marketplace 1.1.0 → 1.3.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 (92) hide show
  1. package/ADOPTING.md +37 -7
  2. package/README.md +238 -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 +162 -0
  7. package/dist/99food/index.js +444 -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-BggtVFf9.d.ts → adapter-0l_EmuJA.d.ts} +206 -2
  13. package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
  14. package/dist/chunk-AYYBRQJV.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-M2V4RFMA.js +23 -0
  18. package/dist/chunk-M2V4RFMA.js.map +1 -0
  19. package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
  20. package/dist/chunk-RVBTARIY.js.map +1 -0
  21. package/dist/chunk-XUAFXNOH.js +1604 -0
  22. package/dist/chunk-XUAFXNOH.js.map +1 -0
  23. package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
  24. package/dist/hono/index.d.ts +2 -2
  25. package/dist/hono/index.js +2 -2
  26. package/dist/ifood/index.d.ts +16 -12
  27. package/dist/ifood/index.js +248 -121
  28. package/dist/ifood/index.js.map +1 -1
  29. package/dist/index.d.ts +30 -4
  30. package/dist/index.js +189 -346
  31. package/dist/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +4 -2
  33. package/dist/manifest/server.js +2 -2
  34. package/dist/rappi/en-US.d.ts +14 -0
  35. package/dist/rappi/en-US.js +18 -0
  36. package/dist/rappi/en-US.js.map +1 -0
  37. package/dist/rappi/index.d.ts +190 -0
  38. package/dist/rappi/index.js +359 -0
  39. package/dist/rappi/index.js.map +1 -0
  40. package/dist/rappi/pt-BR.d.ts +18 -0
  41. package/dist/rappi/pt-BR.js +18 -0
  42. package/dist/rappi/pt-BR.js.map +1 -0
  43. package/dist/server/index.d.ts +19 -8
  44. package/dist/server/index.js +4 -2
  45. package/package.json +26 -2
  46. package/prisma/marketplace.prisma +97 -2
  47. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  48. package/src/99food/catalogue.ts +117 -0
  49. package/src/99food/copy.ts +36 -0
  50. package/src/99food/en-US.ts +19 -0
  51. package/src/99food/index.ts +125 -0
  52. package/src/99food/normalize.ts +263 -0
  53. package/src/99food/outbound.ts +220 -0
  54. package/src/99food/pt-BR.ts +23 -0
  55. package/src/core/adapter.ts +27 -2
  56. package/src/core/catalogue-category.ts +119 -0
  57. package/src/core/catalogue-ids.ts +23 -0
  58. package/src/core/catalogue-job.ts +332 -0
  59. package/src/core/catalogue-port.ts +173 -0
  60. package/src/core/catalogue-store.ts +172 -0
  61. package/src/core/catalogue-sweep.ts +43 -0
  62. package/src/core/catalogue.ts +226 -0
  63. package/src/core/decisions.ts +16 -4
  64. package/src/core/engine.ts +54 -0
  65. package/src/core/fetch-order.ts +253 -0
  66. package/src/core/inbox.ts +8 -2
  67. package/src/core/ingest.ts +10 -2
  68. package/src/core/integration.ts +30 -1
  69. package/src/core/order-fetch-marks.ts +63 -0
  70. package/src/core/outbound-sweep.ts +7 -2
  71. package/src/core/outbound.ts +22 -2
  72. package/src/core/payload-read.ts +101 -0
  73. package/src/core/pipeline.ts +64 -15
  74. package/src/core/ports.ts +36 -0
  75. package/src/core/types.ts +14 -0
  76. package/src/ifood/catalogue.ts +273 -0
  77. package/src/ifood/index.ts +4 -0
  78. package/src/ifood/normalize.ts +15 -88
  79. package/src/ifood/outbound.ts +9 -6
  80. package/src/index.ts +49 -1
  81. package/src/rappi/copy.ts +39 -0
  82. package/src/rappi/en-US.ts +14 -0
  83. package/src/rappi/index.ts +161 -0
  84. package/src/rappi/normalize.ts +314 -0
  85. package/src/rappi/outbound.ts +182 -0
  86. package/src/rappi/pt-BR.ts +18 -0
  87. package/src/server/index.ts +1 -0
  88. package/src/server/jobs.ts +71 -8
  89. package/dist/chunk-7BYVGNU5.js.map +0 -1
  90. package/dist/chunk-DVIRN42O.js +0 -707
  91. package/dist/chunk-DVIRN42O.js.map +0 -1
  92. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -0,0 +1,1604 @@
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/catalogue-category.ts
101
+ var CLAIM_STALE_MS = 3 * 6e4;
102
+ async function claim(table, key, row, now) {
103
+ if (!row) {
104
+ try {
105
+ await table.create({ data: { ...key, claimedAt: now } });
106
+ return true;
107
+ } catch (error) {
108
+ if (error.code === "P2002") return false;
109
+ throw error;
110
+ }
111
+ }
112
+ const stale = new Date(now.getTime() - CLAIM_STALE_MS);
113
+ const moved = await table.updateMany({
114
+ where: { ...key, externalId: null, OR: [{ claimedAt: null }, { claimedAt: { lt: stale } }] },
115
+ data: { claimedAt: now }
116
+ });
117
+ return moved.count > 0;
118
+ }
119
+ __name(claim, "claim");
120
+ async function release(table, key, claimedAt, id) {
121
+ if (id !== null) {
122
+ await table.updateMany({ where: { ...key, externalId: null }, data: { externalId: id, claimedAt: null } });
123
+ return;
124
+ }
125
+ await table.updateMany({ where: { ...key, externalId: null, claimedAt }, data: { claimedAt: null } });
126
+ }
127
+ __name(release, "release");
128
+ async function resolveCategory(ctx, connection, name, resolve, state = { waited: false }) {
129
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
130
+ if (!table) return resolve();
131
+ const key = { clientId: connection.clientId, provider: connection.provider, name: name.trim() };
132
+ const row = await table.findFirst({ where: key, select: { externalId: true } });
133
+ if (row?.externalId) return { id: row.externalId };
134
+ const now = ctx.ports.clock.now();
135
+ if (!await claim(table, key, row, now)) {
136
+ state.waited = true;
137
+ return { kind: "retry", reason: `another publish is creating the category "${key.name}"` };
138
+ }
139
+ let result = { kind: "retry", reason: "the category was not resolved" };
140
+ try {
141
+ result = await resolve();
142
+ } catch (error) {
143
+ result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
144
+ } finally {
145
+ await release(table, key, now, "id" in result ? result.id : null);
146
+ }
147
+ return result;
148
+ }
149
+ __name(resolveCategory, "resolveCategory");
150
+ async function forgetCategory(ctx, connection, name) {
151
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
152
+ if (!table) return;
153
+ await table.updateMany({
154
+ where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },
155
+ data: { externalId: null, claimedAt: null }
156
+ });
157
+ }
158
+ __name(forgetCategory, "forgetCategory");
159
+
160
+ // src/core/integration.ts
161
+ var VIEW_SELECT = {
162
+ provider: true,
163
+ enabled: true,
164
+ environment: true,
165
+ status: true,
166
+ externalMerchantId: true,
167
+ autoAccept: true,
168
+ ackSlaSeconds: true,
169
+ credentials: true,
170
+ lastEventAt: true,
171
+ lastVerifiedAt: true,
172
+ archivedAt: true
173
+ };
174
+ function toView(row) {
175
+ return {
176
+ provider: row.provider,
177
+ enabled: row.enabled,
178
+ environment: row.environment,
179
+ status: row.status,
180
+ externalMerchantId: row.externalMerchantId,
181
+ autoAccept: row.autoAccept,
182
+ ackSlaSeconds: row.ackSlaSeconds,
183
+ connected: row.credentials !== "",
184
+ lastEventAt: row.lastEventAt,
185
+ lastVerifiedAt: row.lastVerifiedAt,
186
+ archivedAt: row.archivedAt ?? null
187
+ };
188
+ }
189
+ __name(toView, "toView");
190
+ async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
191
+ const db = await ctx.ports.db();
192
+ const rows = await db.marketplaceIntegration.findMany({
193
+ where: {
194
+ clientId,
195
+ ...options.providers ? { provider: { in: [...options.providers] } } : {},
196
+ ...options.includeArchived ? {} : { archivedAt: null }
197
+ },
198
+ select: VIEW_SELECT,
199
+ orderBy: { provider: "asc" }
200
+ });
201
+ return rows.map(toView);
202
+ }
203
+ __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
204
+ async function saveMarketplaceIntegration(ctx, input, db) {
205
+ const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
206
+ const mutable = {
207
+ ...input.enabled === void 0 ? {} : { enabled: input.enabled },
208
+ ...input.environment === void 0 ? {} : { environment: input.environment },
209
+ ...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
210
+ ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
211
+ ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
212
+ ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED" }
213
+ };
214
+ const row = await db.marketplaceIntegration.upsert({
215
+ where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
216
+ create: {
217
+ clientId: input.clientId,
218
+ provider: input.provider,
219
+ credentials: sealed ?? "",
220
+ ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
221
+ ...mutable
222
+ },
223
+ update: mutable,
224
+ select: VIEW_SELECT
225
+ });
226
+ return toView(row);
227
+ }
228
+ __name(saveMarketplaceIntegration, "saveMarketplaceIntegration");
229
+ async function connectionMerchantId(ctx, clientId, provider) {
230
+ const db = await ctx.ports.db();
231
+ const row = await db.marketplaceIntegration.findUnique({
232
+ where: { clientId_provider: { clientId, provider } },
233
+ select: { externalMerchantId: true, archivedAt: true }
234
+ });
235
+ return row && !row.archivedAt ? row.externalMerchantId ?? null : null;
236
+ }
237
+ __name(connectionMerchantId, "connectionMerchantId");
238
+ async function resolveIngestionTarget(ctx, clientId, provider) {
239
+ const db = await ctx.ports.db();
240
+ const row = await db.marketplaceIntegration.findUnique({
241
+ where: { clientId_provider: { clientId, provider } },
242
+ select: {
243
+ enabled: true,
244
+ autoAccept: true,
245
+ ackSlaSeconds: true,
246
+ credentials: true,
247
+ archivedAt: true,
248
+ externalMerchantId: true
249
+ }
250
+ });
251
+ if (!row || row.archivedAt) return null;
252
+ return {
253
+ enabled: row.enabled,
254
+ autoAccept: row.autoAccept,
255
+ ackSlaSeconds: row.ackSlaSeconds,
256
+ externalMerchantId: row.externalMerchantId ?? null,
257
+ // An unopenable blob must not read as "no secret configured" — that would
258
+ // turn a key-rotation problem into an endpoint that accepts unsigned
259
+ // deliveries. The secrets port throws instead, and the caller answers 401.
260
+ webhookSecret: row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret
261
+ };
262
+ }
263
+ __name(resolveIngestionTarget, "resolveIngestionTarget");
264
+ function openCredentials(ctx, sealed) {
265
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
266
+ if (typeof parsed !== "object" || parsed === null) {
267
+ throw new Error("Stored marketplace credentials are not an object.");
268
+ }
269
+ const record = parsed;
270
+ return {
271
+ clientId: String(record.clientId ?? ""),
272
+ clientSecret: String(record.clientSecret ?? ""),
273
+ webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
274
+ };
275
+ }
276
+ __name(openCredentials, "openCredentials");
277
+ async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
278
+ const db = await ctx.ports.db();
279
+ const rows = await db.marketplaceIntegration.findMany({
280
+ where: { provider, externalMerchantId, archivedAt: null },
281
+ select: { clientId: true },
282
+ take: 1
283
+ });
284
+ return rows[0]?.clientId ?? null;
285
+ }
286
+ __name(resolveTenantByMerchant, "resolveTenantByMerchant");
287
+ async function markMarketplaceEventSeen(db, clientId, provider, at) {
288
+ await db.marketplaceIntegration.updateMany({
289
+ where: { clientId, provider },
290
+ data: { lastEventAt: at }
291
+ });
292
+ }
293
+ __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
294
+ async function readOutboundConnection(ctx, clientId, provider) {
295
+ const db = await ctx.ports.db();
296
+ const row = await db.marketplaceIntegration.findUnique({
297
+ where: { clientId_provider: { clientId, provider } },
298
+ select: { environment: true, credentials: true }
299
+ });
300
+ if (!row || row.credentials === "") return null;
301
+ return {
302
+ environment: row.environment === "PRODUCTION" ? "PRODUCTION" : "SANDBOX",
303
+ credentials: openCredentials(ctx, row.credentials)
304
+ };
305
+ }
306
+ __name(readOutboundConnection, "readOutboundConnection");
307
+
308
+ // src/core/catalogue-store.ts
309
+ var CATALOGUE_ROW_SELECT = {
310
+ id: true,
311
+ clientId: true,
312
+ provider: true,
313
+ productId: true,
314
+ status: true,
315
+ priceCents: true,
316
+ sentPriceCents: true,
317
+ externalId: true,
318
+ imageRef: true,
319
+ imageSourceUrl: true,
320
+ warningCode: true,
321
+ failedAction: true,
322
+ failureCode: true,
323
+ failureReason: true,
324
+ requestedAt: true,
325
+ publishedAt: true,
326
+ withdrawnAt: true,
327
+ failedAt: true
328
+ };
329
+ async function catalogueTable(ctx) {
330
+ return (await ctx.ports.db()).marketplaceCataloguePublication ?? null;
331
+ }
332
+ __name(catalogueTable, "catalogueTable");
333
+ function viewOf(row) {
334
+ return {
335
+ provider: row.provider,
336
+ productId: row.productId,
337
+ status: row.status,
338
+ priceCents: row.priceCents,
339
+ sentPriceCents: row.sentPriceCents,
340
+ externalId: row.externalId,
341
+ warningCode: row.warningCode,
342
+ failedAction: row.failedAction,
343
+ failureCode: row.failureCode,
344
+ failureReason: row.failureReason,
345
+ requestedAt: row.requestedAt,
346
+ publishedAt: row.publishedAt,
347
+ withdrawnAt: row.withdrawnAt,
348
+ failedAt: row.failedAt
349
+ };
350
+ }
351
+ __name(viewOf, "viewOf");
352
+ var NO_FAILURE = { failedAction: null, failureCode: null, failureReason: null, failedAt: null };
353
+ var REASON_LIMIT = 300;
354
+ function truncateReason(reason) {
355
+ return reason.length > REASON_LIMIT ? reason.slice(0, REASON_LIMIT) : reason;
356
+ }
357
+ __name(truncateReason, "truncateReason");
358
+ async function catalogueConnection(ctx, clientId, provider, categoryState) {
359
+ const merchantId = await connectionMerchantId(ctx, clientId, provider);
360
+ if (merchantId === null) return { problem: "NOT_CONNECTED" };
361
+ try {
362
+ const connection = await readOutboundConnection(ctx, clientId, provider);
363
+ if (!connection) return { problem: "CREDENTIALS" };
364
+ const catalogue = ctx.ports.catalogue;
365
+ return {
366
+ ...connection,
367
+ http: ctx.ports.http,
368
+ tokens: ctx.tokens,
369
+ externalMerchantId: merchantId,
370
+ loadImage: /* @__PURE__ */ __name((url) => catalogue ? catalogue.image(url) : Promise.resolve(null), "loadImage"),
371
+ category: /* @__PURE__ */ __name((name, resolve) => resolveCategory(ctx, { clientId, provider }, name, resolve, categoryState), "category"),
372
+ forgetCategory: /* @__PURE__ */ __name((name) => forgetCategory(ctx, { clientId, provider }, name), "forgetCategory")
373
+ };
374
+ } catch (error) {
375
+ ctx.ports.logger.error(
376
+ `marketplace.catalogue: ${provider} credentials of ${clientId} do not open: ${error instanceof Error ? error.message : String(error)}`
377
+ );
378
+ return { problem: "CREDENTIALS" };
379
+ }
380
+ }
381
+ __name(catalogueConnection, "catalogueConnection");
382
+
383
+ // src/core/catalogue-job.ts
384
+ var MARKETPLACE_CATALOGUE_JOB = "marketplace.catalogue";
385
+ var CatalogueRetryError = class extends Error {
386
+ static {
387
+ __name(this, "CatalogueRetryError");
388
+ }
389
+ constructor(message) {
390
+ super(message);
391
+ this.name = "CatalogueRetryError";
392
+ }
393
+ };
394
+ var WANTED = { publish: "PUBLISHING", withdraw: "WITHDRAWING" };
395
+ function catalogueDedupeKey(payload, requestedAt) {
396
+ return `${MARKETPLACE_CATALOGUE_JOB}:${payload.action}:${payload.publicationId}:${requestedAt.getTime()}`;
397
+ }
398
+ __name(catalogueDedupeKey, "catalogueDedupeKey");
399
+ async function enqueueCatalogue(ctx, payload, dedupeKey) {
400
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CATALOGUE_JOB, payload, { dedupeKey });
401
+ if (outcome.enqueued) return;
402
+ ctx.ports.logger.warn(
403
+ `${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
404
+ );
405
+ }
406
+ __name(enqueueCatalogue, "enqueueCatalogue");
407
+ async function callFor(ctx, row, action, catalogue, call) {
408
+ if (action === "withdraw") {
409
+ if (catalogue.mode === "pull") return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: null };
410
+ const ref = { ref: row.id, productId: row.productId, externalId: row.externalId };
411
+ return { result: await catalogue.withdrawItem(call, ref), sentPriceCents: null };
412
+ }
413
+ const item = (await ctx.ports.catalogue?.items(row.clientId, [row.productId]))?.get(row.productId);
414
+ if (!item) return { code: "PRODUCT_GONE" };
415
+ const priceCents = row.priceCents ?? item.priceCents;
416
+ if (catalogue.mode === "pull") {
417
+ return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: priceCents, name: item.name };
418
+ }
419
+ const storedImage = row.imageRef && row.imageSourceUrl ? { ref: row.imageRef, sourceUrl: row.imageSourceUrl } : null;
420
+ const out = { ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage };
421
+ return { result: await catalogue.publishItem(call, out), sentPriceCents: priceCents, name: item.name };
422
+ }
423
+ __name(callFor, "callFor");
424
+ var stillAsked = /* @__PURE__ */ __name((row, action) => ({
425
+ id: row.id,
426
+ status: WANTED[action],
427
+ requestedAt: row.requestedAt
428
+ }), "stillAsked");
429
+ async function withdrawLateLanding(ctx, table, row, externalId) {
430
+ const now = ctx.ports.clock.now();
431
+ const moved = await table.updateMany({
432
+ where: { id: row.id, status: { in: ["WITHDRAWING", "WITHDRAWN"] } },
433
+ data: { status: "WITHDRAWING", requestedAt: now, ...externalId === null ? {} : { externalId } }
434
+ });
435
+ if (moved.count === 0) return;
436
+ const payload = { clientId: row.clientId, publicationId: row.id, action: "withdraw" };
437
+ await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));
438
+ }
439
+ __name(withdrawLateLanding, "withdrawLateLanding");
440
+ async function publishLateLanding(ctx, table, row) {
441
+ const now = ctx.ports.clock.now();
442
+ const moved = await table.updateMany({
443
+ where: { id: row.id, status: { in: ["PUBLISHING", "PUBLISHED"] } },
444
+ data: { status: "PUBLISHING", requestedAt: now }
445
+ });
446
+ if (moved.count === 0) return;
447
+ const payload = { clientId: row.clientId, publicationId: row.id, action: "publish" };
448
+ await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));
449
+ }
450
+ __name(publishLateLanding, "publishLateLanding");
451
+ async function mapPublishedSku(ctx, row, result, name) {
452
+ const sku = (result.kind === "published" ? result.sku : void 0) ?? row.productId;
453
+ const db = await ctx.ports.db();
454
+ const key = { clientId: row.clientId, provider: row.provider, externalSku: sku };
455
+ const existing = await db.marketplaceMenuLink.findMany({ where: key, select: { menuItemId: true }, take: 1 });
456
+ if (existing[0]?.menuItemId) return;
457
+ await db.marketplaceMenuLink.upsert({
458
+ where: { clientId_provider_externalSku: key },
459
+ create: { ...key, externalName: name ?? null, menuItemId: row.productId, lastSeenAt: ctx.ports.clock.now() },
460
+ update: { menuItemId: row.productId }
461
+ });
462
+ }
463
+ __name(mapPublishedSku, "mapPublishedSku");
464
+ function publishedExtras(result) {
465
+ if (result.kind !== "published") return { warningCode: null };
466
+ const image = result.image === void 0 ? {} : { imageRef: result.image?.ref ?? null, imageSourceUrl: result.image?.sourceUrl ?? null };
467
+ return { externalId: result.externalId, warningCode: result.warning ?? null, ...image };
468
+ }
469
+ __name(publishedExtras, "publishedExtras");
470
+ async function stampSuccess(ctx, table, row, action, result, sentPriceCents) {
471
+ const now = ctx.ports.clock.now();
472
+ const externalId = result.kind === "published" ? result.externalId : null;
473
+ const data = action === "publish" ? { status: "PUBLISHED", publishedAt: now, sentPriceCents, ...publishedExtras(result), ...NO_FAILURE } : { status: "WITHDRAWN", withdrawnAt: now, ...NO_FAILURE };
474
+ const moved = await table.updateMany({ where: stillAsked(row, action), data });
475
+ if (moved.count > 0) return;
476
+ if (action === "publish") await withdrawLateLanding(ctx, table, row, externalId);
477
+ else await publishLateLanding(ctx, table, row);
478
+ }
479
+ __name(stampSuccess, "stampSuccess");
480
+ async function stampFailure(table, row, action, failure, now) {
481
+ await table.updateMany({
482
+ where: stillAsked(row, action),
483
+ data: {
484
+ status: "FAILED",
485
+ failedAction: action === "publish" ? "PUBLISH" : "WITHDRAW",
486
+ failureCode: failure.code,
487
+ failureReason: failure.reason === null ? null : truncateReason(failure.reason),
488
+ failedAt: now
489
+ }
490
+ });
491
+ }
492
+ __name(stampFailure, "stampFailure");
493
+ function failureOf(result) {
494
+ if (result.kind === "retry") return { code: "UNAVAILABLE", reason: null };
495
+ return { code: "REFUSED", reason: result.message === "" ? null : result.message };
496
+ }
497
+ __name(failureOf, "failureOf");
498
+ async function runFor(ctx, row, action) {
499
+ const catalogue = ctx.registry.get(row.provider)?.catalogue;
500
+ if (!catalogue) return { code: "UNSUPPORTED" };
501
+ const categoryState = { waited: false };
502
+ const connection = await catalogueConnection(ctx, row.clientId, row.provider, categoryState);
503
+ if ("problem" in connection && connection.problem === "NOT_CONNECTED" && action === "withdraw") {
504
+ return { result: { kind: "accepted" }, sentPriceCents: null };
505
+ }
506
+ if ("problem" in connection) return { code: connection.problem };
507
+ const run = await callFor(ctx, row, action, catalogue, { ...connection, now: ctx.ports.clock.now() });
508
+ return "result" in run ? { ...run, waited: categoryState.waited } : run;
509
+ }
510
+ __name(runFor, "runFor");
511
+ function waitedOut(ctx, row, action, detail) {
512
+ ctx.ports.logger.warn(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} left for the sweep: ${detail}`);
513
+ return { kind: "skipped", reason: detail };
514
+ }
515
+ __name(waitedOut, "waitedOut");
516
+ async function fail(ctx, table, row, action, failure, detail) {
517
+ await stampFailure(table, row, action, failure, ctx.ports.clock.now());
518
+ ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} failed (${failure.code}): ${detail}`);
519
+ ctx.ports.publishChanged(row.clientId);
520
+ return { kind: "failed", action, reason: failure.code };
521
+ }
522
+ __name(fail, "fail");
523
+ async function runOnce(ctx, table, payload, attempt) {
524
+ const row = await readRow(table, payload);
525
+ if (!row) return { kind: "skipped", reason: "no such publication for this tenant" };
526
+ const { action } = payload;
527
+ if (row.status !== WANTED[action]) return { kind: "skipped", reason: `the publication is ${row.status}, not ${WANTED[action]}` };
528
+ const run = await runFor(ctx, row, action);
529
+ if ("code" in run) return fail(ctx, table, row, action, { code: run.code, reason: null }, run.code);
530
+ return settle(ctx, table, row, action, run, attempt);
531
+ }
532
+ __name(runOnce, "runOnce");
533
+ async function settle(ctx, table, row, action, run, attempt) {
534
+ const { result } = run;
535
+ if (result.kind === "accepted" || result.kind === "published") {
536
+ await stampSuccess(ctx, table, row, action, result, run.sentPriceCents);
537
+ if (action === "publish") await mapPublishedSku(ctx, row, result, run.name);
538
+ ctx.ports.publishChanged(row.clientId);
539
+ return { kind: "done", action };
540
+ }
541
+ const detail = result.kind === "retry" ? result.reason : `refused ${result.status}: ${result.message}`;
542
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
543
+ throw new CatalogueRetryError(`${action} of ${row.productId} on ${row.provider}: ${detail}`);
544
+ }
545
+ if (result.kind === "retry" && run.waited) return waitedOut(ctx, row, action, detail);
546
+ return fail(ctx, table, row, action, failureOf(result), detail);
547
+ }
548
+ __name(settle, "settle");
549
+ function readRow(table, payload) {
550
+ return table.findFirst({
551
+ where: { id: payload.publicationId, clientId: payload.clientId },
552
+ select: CATALOGUE_ROW_SELECT
553
+ });
554
+ }
555
+ __name(readRow, "readRow");
556
+ async function runCatalogue(ctx, payload, attempt) {
557
+ const table = await catalogueTable(ctx);
558
+ if (!table) return { kind: "skipped", reason: "the host has no catalogue table" };
559
+ try {
560
+ return await runOnce(ctx, table, payload, attempt);
561
+ } catch (error) {
562
+ if (error instanceof CatalogueRetryError || attempt.attempt < attempt.maxAttempts) throw error;
563
+ const detail = error instanceof Error ? error.message : String(error);
564
+ const row = await readRow(table, payload);
565
+ if (row && row.status === WANTED[payload.action]) return fail(ctx, table, row, payload.action, { code: "INTERNAL", reason: null }, detail);
566
+ ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} failed: ${detail}`);
567
+ return { kind: "failed", action: payload.action, reason: "INTERNAL" };
568
+ }
569
+ }
570
+ __name(runCatalogue, "runCatalogue");
571
+
572
+ // src/core/inbox.ts
573
+ async function recordInboxEvent(ctx, input) {
574
+ const db = await ctx.ports.db();
575
+ const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
576
+ const existing = await db.marketplaceInboxEvent.findUnique({
577
+ where: key,
578
+ select: { id: true }
579
+ });
580
+ if (existing) return { id: existing.id, fresh: false };
581
+ try {
582
+ const row = await db.marketplaceInboxEvent.create({
583
+ data: {
584
+ clientId: input.clientId,
585
+ provider: input.event.provider,
586
+ eventId: input.event.eventId,
587
+ eventType: input.event.eventType,
588
+ externalOrderId: input.event.externalOrderId,
589
+ payload: input.payload,
590
+ // The engine's clock, not the database's: an announced order's
591
+ // acceptance window counts from here (`./fetch-order.ts`).
592
+ receivedAt: ctx.ports.clock.now()
593
+ },
594
+ select: { id: true }
595
+ });
596
+ return { id: row.id, fresh: true };
597
+ } catch (error) {
598
+ if (error.code !== "P2002") throw error;
599
+ const raced = await db.marketplaceInboxEvent.findUnique({
600
+ where: key,
601
+ select: { id: true }
602
+ });
603
+ return { id: raced?.id ?? "", fresh: false };
604
+ }
605
+ }
606
+ __name(recordInboxEvent, "recordInboxEvent");
607
+ async function settleInboxEvent(ctx, id, outcome, error) {
608
+ if (!id) return;
609
+ const db = await ctx.ports.db();
610
+ await db.marketplaceInboxEvent.update({
611
+ where: { id },
612
+ data: {
613
+ status: outcome,
614
+ // Truncated: a provider's error body can be a page of HTML, and the
615
+ // column exists to be read by a human in a list.
616
+ error: error ? error.slice(0, 500) : null,
617
+ processedAt: ctx.ports.clock.now(),
618
+ attempts: { increment: 1 }
619
+ }
620
+ });
621
+ }
622
+ __name(settleInboxEvent, "settleInboxEvent");
623
+ async function deferInboxEvent(ctx, id, reason) {
624
+ if (!id) return;
625
+ const db = await ctx.ports.db();
626
+ await db.marketplaceInboxEvent.update({
627
+ where: { id },
628
+ data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
629
+ });
630
+ }
631
+ __name(deferInboxEvent, "deferInboxEvent");
632
+ async function listRetryableInboxEvents(ctx) {
633
+ const db = await ctx.ports.db();
634
+ const rows = await db.marketplaceInboxEvent.findMany({
635
+ where: {
636
+ status: { in: ["PENDING", "FAILED"] },
637
+ clientId: { not: null },
638
+ attempts: { lt: ctx.ports.maxInboxAttempts }
639
+ },
640
+ orderBy: { receivedAt: "asc" },
641
+ take: ctx.ports.reconcileBatchSize,
642
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
643
+ });
644
+ return rows.map((row) => ({
645
+ id: row.id,
646
+ clientId: row.clientId,
647
+ provider: row.provider,
648
+ payload: row.payload,
649
+ receivedAt: row.receivedAt
650
+ }));
651
+ }
652
+ __name(listRetryableInboxEvents, "listRetryableInboxEvents");
653
+
654
+ // src/core/menu-links.ts
655
+ var LINK_SELECT = {
656
+ id: true,
657
+ provider: true,
658
+ externalSku: true,
659
+ externalName: true,
660
+ menuItemId: true,
661
+ lastSeenAt: true
662
+ };
663
+ function toView2(row) {
664
+ return {
665
+ id: row.id,
666
+ provider: row.provider,
667
+ externalSku: row.externalSku,
668
+ externalName: row.externalName ?? row.externalSku,
669
+ menuItemId: row.menuItemId,
670
+ lastSeenAt: row.lastSeenAt
671
+ };
672
+ }
673
+ __name(toView2, "toView");
674
+ async function listMarketplaceMenuLinks(ctx, input) {
675
+ const db = await ctx.ports.db();
676
+ const rows = await db.marketplaceMenuLink.findMany({
677
+ where: {
678
+ clientId: input.clientId,
679
+ ...input.ids ? { id: { in: [...input.ids] } } : {},
680
+ ...input.provider ? { provider: input.provider } : {},
681
+ ...input.unmappedOnly ? { menuItemId: null } : {}
682
+ },
683
+ select: LINK_SELECT,
684
+ orderBy: { lastSeenAt: "desc" }
685
+ });
686
+ return rows.map(toView2);
687
+ }
688
+ __name(listMarketplaceMenuLinks, "listMarketplaceMenuLinks");
689
+ async function upsertLink(db, input) {
690
+ const row = await db.marketplaceMenuLink.upsert({
691
+ where: {
692
+ clientId_provider_externalSku: {
693
+ clientId: input.clientId,
694
+ provider: input.provider,
695
+ externalSku: input.externalSku
696
+ }
697
+ },
698
+ create: {
699
+ clientId: input.clientId,
700
+ provider: input.provider,
701
+ externalSku: input.externalSku,
702
+ externalName: input.externalName ?? input.externalSku,
703
+ menuItemId: input.menuItemId
704
+ },
705
+ // `externalName` is NOT rewritten here. It is the marketplace's snapshot of
706
+ // what it called the item, and an operator's typing is not a better record
707
+ // of that than the marketplace's own text.
708
+ update: { menuItemId: input.menuItemId },
709
+ select: LINK_SELECT
710
+ });
711
+ return toView2(row);
712
+ }
713
+ __name(upsertLink, "upsertLink");
714
+ async function resolveSkus(db, input) {
715
+ const resolved = /* @__PURE__ */ new Map();
716
+ for (const sku of input.skus) {
717
+ const row = await db.marketplaceMenuLink.upsert({
718
+ where: {
719
+ clientId_provider_externalSku: {
720
+ clientId: input.clientId,
721
+ provider: input.provider,
722
+ externalSku: sku.externalSku
723
+ }
724
+ },
725
+ create: {
726
+ clientId: input.clientId,
727
+ provider: input.provider,
728
+ externalSku: sku.externalSku,
729
+ externalName: sku.name,
730
+ lastSeenAt: input.seenAt
731
+ },
732
+ update: { lastSeenAt: input.seenAt },
733
+ select: { menuItemId: true }
734
+ });
735
+ resolved.set(sku.externalSku, row.menuItemId);
736
+ }
737
+ return resolved;
738
+ }
739
+ __name(resolveSkus, "resolveSkus");
740
+
741
+ // src/core/ingest.ts
742
+ async function composeLines(db, clientId, order, seenAt) {
743
+ const mapping = await resolveSkus(db, {
744
+ clientId,
745
+ provider: order.provider,
746
+ skus: order.lines.map((line) => ({ externalSku: line.externalSku, name: line.name })),
747
+ seenAt
748
+ });
749
+ return order.lines.map((line) => ({
750
+ externalSku: line.externalSku,
751
+ // The MARKETPLACE's text, never the catalog's, even for a mapped line.
752
+ // Every other order snapshots what the buyer was shown, and what this buyer
753
+ // was shown is the marketplace's menu — a mapped line renamed to the host's
754
+ // own product name would quietly disagree with the receipt in the bag.
755
+ name: line.name,
756
+ quantity: line.quantity,
757
+ unitPriceCents: line.unitPriceCents,
758
+ note: line.note,
759
+ subjectRef: mapping.get(line.externalSku) ?? null
760
+ }));
761
+ }
762
+ __name(composeLines, "composeLines");
763
+ function acceptanceData(clientId, orderId, order, settings, now, clockStartsAt) {
764
+ const accepted = settings.autoAccept;
765
+ return {
766
+ clientId,
767
+ orderId,
768
+ provider: order.provider,
769
+ externalOrderId: order.externalOrderId,
770
+ externalDisplayId: order.externalDisplayId,
771
+ // Who carries a delivery: the merchant's courier or the marketplace's fleet.
772
+ deliveredBy: order.deliveredBy ?? null,
773
+ status: accepted ? "ACCEPTED" : "AWAITING",
774
+ acknowledgeBy: new Date(clockStartsAt.getTime() + settings.ackSlaSeconds * 1e3),
775
+ acknowledgedAt: accepted ? now : null,
776
+ externalDueAt: order.deliveryDueAt,
777
+ commissionCents: order.commissionCents,
778
+ // The order's SKUs: what a cancellation's offending SKUs are checked against.
779
+ lineSkus: [...new Set(order.lines.map((line) => line.externalSku))]
780
+ };
781
+ }
782
+ __name(acceptanceData, "acceptanceData");
783
+ async function ingestMarketplaceOrder(ctx, input) {
784
+ const { clientId, order, settings } = input;
785
+ const now = input.now ?? ctx.ports.clock.now();
786
+ const clockStartsAt = input.clockStartsAt ?? now;
787
+ const db = await ctx.ports.db();
788
+ const existing = await db.marketplaceAcceptance.findFirst({
789
+ where: { provider: order.provider, externalOrderId: order.externalOrderId },
790
+ select: { orderId: true }
791
+ });
792
+ if (existing) {
793
+ return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };
794
+ }
795
+ const accepted = settings.autoAccept;
796
+ const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
797
+ const lines = await composeLines(tx, clientId, order, now);
798
+ const created = await ctx.ports.order.create(clientId, order, lines, tx);
799
+ await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });
800
+ await markMarketplaceEventSeen(tx, clientId, order.provider, now);
801
+ return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
802
+ });
803
+ if (accepted) {
804
+ await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, order.provider);
805
+ await ctx.ports.order.onAccepted(clientId, orderId);
806
+ }
807
+ ctx.ports.publishChanged(clientId);
808
+ return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
809
+ }
810
+ __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
811
+
812
+ // src/core/cancellation-outcome.ts
813
+ async function tell(ctx, what, orderId, call) {
814
+ try {
815
+ await call();
816
+ } catch (error) {
817
+ ctx.ports.logger.error(
818
+ `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
819
+ );
820
+ }
821
+ }
822
+ __name(tell, "tell");
823
+ function requestsFirst(ctx) {
824
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
825
+ }
826
+ __name(requestsFirst, "requestsFirst");
827
+ async function rejectConfirmed(db, orderId, now) {
828
+ await db.marketplaceAcceptance.updateMany({
829
+ where: { orderId, status: "AWAITING" },
830
+ data: { status: "REJECTED", acknowledgedAt: now }
831
+ });
832
+ await db.marketplaceAcceptance.updateMany({
833
+ where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
834
+ data: { status: "REJECTED" }
835
+ });
836
+ }
837
+ __name(rejectConfirmed, "rejectConfirmed");
838
+ async function confirmedToHost(ctx, clientId, orderId) {
839
+ if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
840
+ await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
841
+ }
842
+ __name(confirmedToHost, "confirmedToHost");
843
+ async function tellCancellationConfirmed(ctx, clientId, orderId) {
844
+ const hook = ctx.ports.order.onCancellationConfirmed;
845
+ if (!hook) return false;
846
+ await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
847
+ return true;
848
+ }
849
+ __name(tellCancellationConfirmed, "tellCancellationConfirmed");
850
+ async function tellCancellationFailed(ctx, clientId, orderId, reason) {
851
+ const hook = ctx.ports.order.onCancellationFailed;
852
+ if (!hook) return;
853
+ await tell(
854
+ ctx,
855
+ `had its cancellation request fail (${reason})`,
856
+ orderId,
857
+ () => hook.call(ctx.ports.order, clientId, orderId, reason)
858
+ );
859
+ }
860
+ __name(tellCancellationFailed, "tellCancellationFailed");
861
+ function cancellationWindowMs(ctx, adapter) {
862
+ return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
863
+ }
864
+ __name(cancellationWindowMs, "cancellationWindowMs");
865
+ function failedRequestData(reason) {
866
+ return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
867
+ }
868
+ __name(failedRequestData, "failedRequestData");
869
+
870
+ // src/core/cancellation.ts
871
+ function noStandingRequest(cancellationStatus) {
872
+ return cancellationStatus === null || cancellationStatus === "FAILED";
873
+ }
874
+ __name(noStandingRequest, "noStandingRequest");
875
+ var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
876
+ var CLAIM_SELECT = {
877
+ orderId: true,
878
+ provider: true,
879
+ status: true,
880
+ cancellationStatus: true,
881
+ lineSkus: true
882
+ };
883
+ function notPendingProblem(row, path, allowed = ["AWAITING"]) {
884
+ if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
885
+ if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
886
+ const status = row.status;
887
+ return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
888
+ }
889
+ __name(notPendingProblem, "notPendingProblem");
890
+ function lineSkusOf(row) {
891
+ return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
892
+ }
893
+ __name(lineSkusOf, "lineSkusOf");
894
+ function skuProblems(reason, skus, row, path) {
895
+ if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
896
+ const known = lineSkusOf(row);
897
+ if (!known) return [];
898
+ return skus.flatMap(
899
+ (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
900
+ );
901
+ }
902
+ __name(skuProblems, "skuProblems");
903
+ function invalidReasonProblem(adapter, reason, code, path) {
904
+ if (code === null || code === void 0 || reason) return null;
905
+ const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
906
+ return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
907
+ }
908
+ __name(invalidReasonProblem, "invalidReasonProblem");
909
+ function planCancellation(adapter, input, row, path) {
910
+ if (!adapter) return { status: null, reason: null, skus: [] };
911
+ const reason = resolveReason(adapter, input.reasonCode);
912
+ const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
913
+ if (invalid) return [invalid];
914
+ const skus = [...new Set(input.offendingSkus ?? [])];
915
+ const problems = skuProblems(reason, skus, row, path);
916
+ if (problems.length > 0) return problems;
917
+ const { apiCancel, cancelAfterAccept } = adapter.capabilities;
918
+ const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
919
+ return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
920
+ }
921
+ __name(planCancellation, "planCancellation");
922
+ function refusalData(plan, fromStatus, now) {
923
+ return {
924
+ status: "REJECTED",
925
+ // An accepted row keeps the instant it was accepted; a row leaving the
926
+ // clock is acknowledged now (the table's CHECK pairs the two).
927
+ ...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
928
+ cancellationStatus: plan.status,
929
+ cancellationReasonCode: plan.reason?.code ?? null,
930
+ cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
931
+ cancellationRequestedAt: plan.status === "PENDING" ? now : null,
932
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
933
+ };
934
+ }
935
+ __name(refusalData, "refusalData");
936
+ function requestData(plan, now) {
937
+ return {
938
+ cancellationStatus: plan.status,
939
+ cancellationReasonCode: plan.reason?.code ?? null,
940
+ cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
941
+ cancellationRequestedAt: plan.status === "PENDING" ? now : null,
942
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
943
+ };
944
+ }
945
+ __name(requestData, "requestData");
946
+ async function failCancellationRequest(ctx, input) {
947
+ const db = await ctx.ports.db();
948
+ const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
949
+ const row = await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } });
950
+ if (!row) return false;
951
+ const moved = await db.marketplaceAcceptance.updateMany({
952
+ where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
953
+ data: failedRequestData("REFUSED")
954
+ });
955
+ if (moved.count === 0) return false;
956
+ ctx.ports.publishChanged(input.clientId);
957
+ await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
958
+ return true;
959
+ }
960
+ __name(failCancellationRequest, "failCancellationRequest");
961
+
962
+ // src/core/acceptance.ts
963
+ async function listPendingAcceptances(ctx, clientId, orderIds) {
964
+ const db = await ctx.ports.db();
965
+ const rows = await db.marketplaceAcceptance.findMany({
966
+ where: { clientId, status: "AWAITING", ...orderIds ? { orderId: { in: [...orderIds] } } : {} },
967
+ orderBy: { acknowledgeBy: "asc" },
968
+ select: {
969
+ id: true,
970
+ orderId: true,
971
+ provider: true,
972
+ externalOrderId: true,
973
+ externalDisplayId: true,
974
+ acknowledgeBy: true,
975
+ externalDueAt: true,
976
+ commissionCents: true
977
+ }
978
+ });
979
+ if (rows.length === 0) return [];
980
+ const summaries = await ctx.ports.order.summarize(
981
+ clientId,
982
+ rows.map((row) => row.orderId)
983
+ );
984
+ return rows.map((row) => {
985
+ const summary = summaries.get(row.orderId);
986
+ return {
987
+ ...row,
988
+ buyerName: summary?.buyerName ?? null,
989
+ totalCents: summary?.totalCents ?? 0,
990
+ unmappedLines: summary?.unmappedLines ?? 0,
991
+ createdAt: summary?.createdAt ?? null
992
+ };
993
+ });
994
+ }
995
+ __name(listPendingAcceptances, "listPendingAcceptances");
996
+ async function expireLapsedAcceptances(ctx, now) {
997
+ const db = await ctx.ports.db();
998
+ const lapsed = await db.marketplaceAcceptance.findMany({
999
+ // An order whose cancellation request waits is left to that request: its
1000
+ // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
1001
+ // never hears EXPIRED and then the confirmation for one order.
1002
+ where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
1003
+ select: { id: true, clientId: true, orderId: true }
1004
+ });
1005
+ if (lapsed.length === 0) return { expired: 0, tenants: 0 };
1006
+ const result = await db.marketplaceAcceptance.updateMany({
1007
+ where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
1008
+ data: { status: "EXPIRED", acknowledgedAt: now }
1009
+ });
1010
+ for (const row of lapsed) {
1011
+ try {
1012
+ await ctx.ports.order.onRefused(row.clientId, row.orderId, "EXPIRED");
1013
+ } catch (error) {
1014
+ ctx.ports.logger.error(
1015
+ `marketplace.expire-acceptances: order ${row.orderId} expired but the host's refusal failed: ` + (error instanceof Error ? error.message : String(error))
1016
+ );
1017
+ }
1018
+ }
1019
+ const tenants = new Set(lapsed.map((row) => row.clientId));
1020
+ for (const clientId of tenants) ctx.ports.publishChanged(clientId);
1021
+ return { expired: result.count, tenants: tenants.size };
1022
+ }
1023
+ __name(expireLapsedAcceptances, "expireLapsedAcceptances");
1024
+ function hasConfirmHook(ctx) {
1025
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
1026
+ }
1027
+ __name(hasConfirmHook, "hasConfirmHook");
1028
+ async function cancelAcceptance(ctx, input) {
1029
+ const db = await ctx.ports.db();
1030
+ const row = await db.marketplaceAcceptance.findFirst({
1031
+ where: {
1032
+ clientId: input.clientId,
1033
+ provider: input.provider,
1034
+ externalOrderId: input.externalOrderId
1035
+ },
1036
+ select: { orderId: true, cancellationStatus: true }
1037
+ });
1038
+ if (!row) return false;
1039
+ const answered = await ctx.ports.transaction(async (tx) => {
1040
+ await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());
1041
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
1042
+ where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "REQUESTED", "FAILED"] } },
1043
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
1044
+ });
1045
+ return confirmed.count > 0;
1046
+ });
1047
+ const storeAsked = answered || row.cancellationStatus === "CONFIRMED";
1048
+ const told = storeAsked && (answered ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));
1049
+ if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
1050
+ ctx.ports.publishChanged(input.clientId);
1051
+ return true;
1052
+ }
1053
+ __name(cancelAcceptance, "cancelAcceptance");
1054
+
1055
+ // src/core/order-fetch-marks.ts
1056
+ var MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
1057
+ var markerId = /* @__PURE__ */ __name((externalOrderId) => `engine:cancelled:${externalOrderId}`, "markerId");
1058
+ async function markCancelledBeforeIngest(ctx, input) {
1059
+ if (!ctx.registry.get(input.provider)?.fetchOrder) return;
1060
+ const db = await ctx.ports.db();
1061
+ try {
1062
+ await db.marketplaceInboxEvent.create({
1063
+ data: {
1064
+ clientId: input.clientId,
1065
+ provider: input.provider,
1066
+ eventId: markerId(input.externalOrderId),
1067
+ eventType: MARKER_TYPE,
1068
+ externalOrderId: input.externalOrderId,
1069
+ payload: {},
1070
+ status: "IGNORED",
1071
+ error: "cancelled before the order was ingested",
1072
+ receivedAt: ctx.ports.clock.now(),
1073
+ processedAt: ctx.ports.clock.now()
1074
+ },
1075
+ select: { id: true }
1076
+ });
1077
+ } catch (error) {
1078
+ if (error.code !== "P2002") throw error;
1079
+ }
1080
+ }
1081
+ __name(markCancelledBeforeIngest, "markCancelledBeforeIngest");
1082
+ async function cancelledBeforeIngest(ctx, input) {
1083
+ const db = await ctx.ports.db();
1084
+ const row = await db.marketplaceInboxEvent.findUnique({
1085
+ where: { provider_eventId: { provider: input.provider, eventId: markerId(input.externalOrderId) } },
1086
+ select: { clientId: true }
1087
+ });
1088
+ return row !== null && row.clientId === input.clientId;
1089
+ }
1090
+ __name(cancelledBeforeIngest, "cancelledBeforeIngest");
1091
+
1092
+ // src/core/fetch-order.ts
1093
+ var MARKETPLACE_FETCH_ORDER_JOB = "marketplace.fetch-order";
1094
+ var FetchOrderRetryError = class extends Error {
1095
+ static {
1096
+ __name(this, "FetchOrderRetryError");
1097
+ }
1098
+ constructor(message) {
1099
+ super(message);
1100
+ this.name = "FetchOrderRetryError";
1101
+ }
1102
+ };
1103
+ var AWAITING_ORDER_REASON = "order details to fetch";
1104
+ var FETCH_REQUEUE_AGE_MS = 2 * 6e4;
1105
+ async function awaitOrderBody(ctx, clientId, inboxId, dedupeKey = `${MARKETPLACE_FETCH_ORDER_JOB}:${inboxId}`) {
1106
+ await deferInboxEvent(ctx, inboxId, AWAITING_ORDER_REASON);
1107
+ const payload = { clientId, inboxId };
1108
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_FETCH_ORDER_JOB, payload, { dedupeKey });
1109
+ if (!outcome.enqueued) {
1110
+ ctx.ports.logger.warn(
1111
+ `${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${inboxId} was not queued; the reconciliation sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
1112
+ );
1113
+ }
1114
+ }
1115
+ __name(awaitOrderBody, "awaitOrderBody");
1116
+ async function requeueOwedFetch(ctx, input) {
1117
+ const now = ctx.ports.clock.now();
1118
+ const age = input.receivedAt ? now.getTime() - input.receivedAt.getTime() : Number.POSITIVE_INFINITY;
1119
+ if (age < FETCH_REQUEUE_AGE_MS) return { kind: "awaitingOrder" };
1120
+ ctx.ports.logger.warn(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${input.id} still waits for its order body; re-queued`);
1121
+ await awaitOrderBody(ctx, input.clientId, input.id, `${MARKETPLACE_FETCH_ORDER_JOB}:${input.id}:${now.getTime()}`);
1122
+ return { kind: "awaitingOrder" };
1123
+ }
1124
+ __name(requeueOwedFetch, "requeueOwedFetch");
1125
+ async function owedFetch(ctx, payload) {
1126
+ const db = await ctx.ports.db();
1127
+ const row = await db.marketplaceInboxEvent.findUnique({
1128
+ where: { id: payload.inboxId },
1129
+ select: { id: true, clientId: true, provider: true, payload: true, status: true, receivedAt: true }
1130
+ });
1131
+ if (!row || row.clientId !== payload.clientId) return "no such inbox row for this tenant";
1132
+ if (row.status !== "PENDING" && row.status !== "FAILED") return `the row is already ${row.status}`;
1133
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
1134
+ if (!event?.orderToFetch || event.order) return "the event announces no order to fetch";
1135
+ return { row, event };
1136
+ }
1137
+ __name(owedFetch, "owedFetch");
1138
+ async function fetchThroughAdapter(ctx, clientId, provider, externalOrderId) {
1139
+ const adapter = ctx.registry.get(provider);
1140
+ if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
1141
+ let connection;
1142
+ try {
1143
+ connection = await readOutboundConnection(ctx, clientId, provider);
1144
+ } catch (error) {
1145
+ const reason = error instanceof Error ? error.message : String(error);
1146
+ return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
1147
+ }
1148
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
1149
+ try {
1150
+ return await adapter.fetchOrder(
1151
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
1152
+ { externalOrderId }
1153
+ );
1154
+ } catch (error) {
1155
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1156
+ }
1157
+ }
1158
+ __name(fetchThroughAdapter, "fetchThroughAdapter");
1159
+ async function refusalOf(ctx, clientId, order, connectionMerchantId2) {
1160
+ if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
1161
+ return { settle: "IGNORED", reason: "cancelled before its order body arrived", failed: false };
1162
+ }
1163
+ const mismatch = merchantMismatch(order, connectionMerchantId2);
1164
+ return mismatch ? { settle: "FAILED", reason: mismatch, failed: true } : null;
1165
+ }
1166
+ __name(refusalOf, "refusalOf");
1167
+ function merchantMismatch(order, connectionMerchantId2) {
1168
+ const named = order.externalMerchantId ?? null;
1169
+ if (named === null || connectionMerchantId2 === null || named === connectionMerchantId2) return null;
1170
+ return `the order names merchant ${named}, not this connection's`;
1171
+ }
1172
+ __name(merchantMismatch, "merchantMismatch");
1173
+ async function ingestFetched(ctx, row, clientId, order, target) {
1174
+ const refusal = await refusalOf(ctx, clientId, order, target.externalMerchantId);
1175
+ if (refusal) {
1176
+ await settleInboxEvent(ctx, row.id, refusal.settle, refusal.reason);
1177
+ if (!refusal.failed) return { kind: "skipped", reason: refusal.reason };
1178
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} refused: ${refusal.reason}`);
1179
+ return { kind: "failed", reason: refusal.reason };
1180
+ }
1181
+ const ingested = await ingestMarketplaceOrder(ctx, {
1182
+ clientId,
1183
+ order,
1184
+ settings: { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
1185
+ // The store's acceptance window starts when the event arrived, not when a
1186
+ // delayed fetch finished: the marketplace's own clock started then.
1187
+ clockStartsAt: row.receivedAt ?? void 0
1188
+ });
1189
+ const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };
1190
+ if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);
1191
+ await settleInboxEvent(ctx, row.id, "PROCESSED");
1192
+ return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
1193
+ }
1194
+ __name(ingestFetched, "ingestFetched");
1195
+ async function runFetchOrder(ctx, payload, attempt) {
1196
+ const owed = await owedFetch(ctx, payload);
1197
+ if (typeof owed === "string") return { kind: "skipped", reason: owed };
1198
+ const { row, event } = owed;
1199
+ const target = await resolveIngestionTarget(ctx, payload.clientId, event.provider);
1200
+ if (!target?.enabled) {
1201
+ await deferInboxEvent(ctx, row.id, "integration is not enabled");
1202
+ return { kind: "skipped", reason: "integration is not enabled" };
1203
+ }
1204
+ const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
1205
+ if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
1206
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1207
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1208
+ throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
1209
+ }
1210
+ await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
1211
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
1212
+ return { kind: "failed", reason };
1213
+ }
1214
+ __name(runFetchOrder, "runFetchOrder");
1215
+
1216
+ // src/core/catalogue-sweep.ts
1217
+ var CATALOGUE_STALE_MS = 10 * 6e4;
1218
+ var CATALOGUE_GIVE_UP_MS = 24 * 60 * 6e4;
1219
+ async function sweepCatalogue(ctx, now) {
1220
+ const table = await catalogueTable(ctx);
1221
+ if (!table) return 0;
1222
+ const stale = new Date(now.getTime() - CATALOGUE_STALE_MS);
1223
+ const giveUp = new Date(now.getTime() - CATALOGUE_GIVE_UP_MS);
1224
+ for (const [status, failedAction] of [["PUBLISHING", "PUBLISH"], ["WITHDRAWING", "WITHDRAW"]]) {
1225
+ await table.updateMany({
1226
+ where: { status, requestedAt: { lt: giveUp } },
1227
+ data: { status: "FAILED", failedAction, failureCode: "TIMEOUT", failureReason: null, failedAt: now }
1228
+ });
1229
+ }
1230
+ const rows = await table.findMany({
1231
+ where: { status: { in: ["PUBLISHING", "WITHDRAWING"] }, requestedAt: { lt: stale, gte: giveUp } },
1232
+ select: CATALOGUE_ROW_SELECT
1233
+ });
1234
+ for (const row of rows) {
1235
+ const action = row.status === "PUBLISHING" ? "publish" : "withdraw";
1236
+ const payload = { clientId: row.clientId, publicationId: row.id, action };
1237
+ await enqueueCatalogue(ctx, payload, `${catalogueDedupeKey(payload, row.requestedAt)}:sweep:${now.getTime()}`);
1238
+ }
1239
+ return rows.length;
1240
+ }
1241
+ __name(sweepCatalogue, "sweepCatalogue");
1242
+
1243
+ // src/core/outbound-sweep.ts
1244
+ var OUTBOUND_STALE_MS = 10 * 6e4;
1245
+ var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
1246
+ var WAITING = ["PENDING", "REQUESTED"];
1247
+ var OWED_SELECT = { clientId: true, orderId: true, provider: true };
1248
+ function sweepDedupeKey(action, orderId, now) {
1249
+ return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
1250
+ }
1251
+ __name(sweepDedupeKey, "sweepDedupeKey");
1252
+ async function requeue(ctx, rows, action, now) {
1253
+ let queued = 0;
1254
+ for (const row of rows) {
1255
+ const payload = { clientId: row.clientId, orderId: row.orderId, action };
1256
+ if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
1257
+ }
1258
+ return queued;
1259
+ }
1260
+ __name(requeue, "requeue");
1261
+ async function failAsTimeout(ctx, rows) {
1262
+ const db = await ctx.ports.db();
1263
+ let failed = 0;
1264
+ for (const row of rows) {
1265
+ const moved = await db.marketplaceAcceptance.updateMany({
1266
+ where: { orderId: row.orderId, clientId: row.clientId, cancellationStatus: { in: WAITING } },
1267
+ data: failedRequestData("TIMEOUT")
1268
+ });
1269
+ if (moved.count === 0) continue;
1270
+ failed += 1;
1271
+ ctx.ports.publishChanged(row.clientId);
1272
+ await tellCancellationFailed(ctx, row.clientId, row.orderId, "TIMEOUT");
1273
+ }
1274
+ return failed;
1275
+ }
1276
+ __name(failAsTimeout, "failAsTimeout");
1277
+ async function waitingSince(ctx, cutoff, statuses, provider) {
1278
+ const db = await ctx.ports.db();
1279
+ return await db.marketplaceAcceptance.findMany({
1280
+ where: { ...provider ? { provider } : {}, cancellationStatus: { in: statuses }, cancellationRequestedAt: { lt: cutoff } },
1281
+ select: OWED_SELECT
1282
+ });
1283
+ }
1284
+ __name(waitingSince, "waitingSince");
1285
+ async function expireUnanswered(ctx, now) {
1286
+ if (!requestsFirst(ctx)) return 0;
1287
+ let expired = 0;
1288
+ for (const provider of ctx.registry.providers()) {
1289
+ const adapter = ctx.registry.get(provider);
1290
+ const window = adapter ? cancellationWindowMs(ctx, adapter) : null;
1291
+ if (window === null) continue;
1292
+ const cutoff = new Date(now.getTime() - window);
1293
+ expired += await failAsTimeout(ctx, await waitingSince(ctx, cutoff, WAITING, provider));
1294
+ }
1295
+ return expired;
1296
+ }
1297
+ __name(expireUnanswered, "expireUnanswered");
1298
+ async function sweepOutbound(ctx, now) {
1299
+ const db = await ctx.ports.db();
1300
+ const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
1301
+ const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
1302
+ const timedOut = await expireUnanswered(ctx, now);
1303
+ const givenUp = await failAsTimeout(ctx, await waitingSince(ctx, giveUp, requestsFirst(ctx) ? WAITING : ["PENDING"]));
1304
+ const cancellations = await db.marketplaceAcceptance.findMany({
1305
+ where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: stale, gte: giveUp } },
1306
+ select: OWED_SELECT
1307
+ });
1308
+ const confirms = await db.marketplaceAcceptance.findMany({
1309
+ where: {
1310
+ status: "ACCEPTED",
1311
+ confirmedAt: null,
1312
+ confirmFailedAt: null,
1313
+ acknowledgedAt: { lt: stale, gte: giveUp },
1314
+ // An accept the store asked to cancel is not confirmed while the request waits.
1315
+ ...NO_STANDING_REQUEST
1316
+ },
1317
+ select: OWED_SELECT
1318
+ });
1319
+ const requeued = await requeue(ctx, cancellations, "requestCancellation", now) + await requeue(ctx, confirms, "confirm", now);
1320
+ if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
1321
+ const catalogueRequeued = await sweepCatalogue(ctx, now);
1322
+ return { requeued, givenUp, timedOut, catalogueRequeued };
1323
+ }
1324
+ __name(sweepOutbound, "sweepOutbound");
1325
+
1326
+ // src/core/outbound.ts
1327
+ var OutboundRetryError = class extends Error {
1328
+ static {
1329
+ __name(this, "OutboundRetryError");
1330
+ }
1331
+ constructor(message) {
1332
+ super(message);
1333
+ this.name = "OutboundRetryError";
1334
+ }
1335
+ };
1336
+ var ROW_SELECT = {
1337
+ orderId: true,
1338
+ provider: true,
1339
+ externalOrderId: true,
1340
+ externalDisplayId: true,
1341
+ status: true,
1342
+ confirmedAt: true,
1343
+ confirmFailedAt: true,
1344
+ cancellationStatus: true,
1345
+ cancellationReasonCode: true,
1346
+ cancellationOffendingSkus: true,
1347
+ cancellationRequestedAt: true,
1348
+ preparationMinutes: true,
1349
+ createdAt: true
1350
+ };
1351
+ function refOf(row) {
1352
+ return {
1353
+ externalOrderId: row.externalOrderId,
1354
+ externalDisplayId: row.externalDisplayId,
1355
+ hostOrderCode: row.orderId,
1356
+ placedAt: row.createdAt
1357
+ };
1358
+ }
1359
+ __name(refOf, "refOf");
1360
+ function confirmSkip(row, adapter) {
1361
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
1362
+ if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
1363
+ return `a cancellation request is ${row.cancellationStatus}`;
1364
+ }
1365
+ if (row.confirmedAt || row.confirmFailedAt) return "the confirm is already stamped";
1366
+ if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
1367
+ return null;
1368
+ }
1369
+ __name(confirmSkip, "confirmSkip");
1370
+ async function stampConfirm(ctx, row, succeeded, now) {
1371
+ const db = await ctx.ports.db();
1372
+ await db.marketplaceAcceptance.updateMany({
1373
+ where: { orderId: row.orderId, confirmedAt: null, confirmFailedAt: null },
1374
+ data: succeeded ? { confirmedAt: now } : { confirmFailedAt: now }
1375
+ });
1376
+ }
1377
+ __name(stampConfirm, "stampConfirm");
1378
+ async function stampCancellation(ctx, row, status, clientId) {
1379
+ if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
1380
+ const db = await ctx.ports.db();
1381
+ const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
1382
+ const moved = await db.marketplaceAcceptance.updateMany({
1383
+ where: { orderId: row.orderId, cancellationStatus: "PENDING" },
1384
+ data
1385
+ });
1386
+ if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
1387
+ }
1388
+ __name(stampCancellation, "stampCancellation");
1389
+ function answerableRequest(row) {
1390
+ const waiting = { cancellationStatus: { in: ["PENDING", "FAILED"] } };
1391
+ if (row.cancellationRequestedAt === null) return [waiting];
1392
+ const tombstone = { status: "ACCEPTED", cancellationStatus: null, cancellationRequestedAt: row.cancellationRequestedAt };
1393
+ return [waiting, tombstone];
1394
+ }
1395
+ __name(answerableRequest, "answerableRequest");
1396
+ async function stampConfirmedCancellation(ctx, row, clientId) {
1397
+ const now = ctx.ports.clock.now();
1398
+ const moved = await ctx.ports.transaction(async (tx) => {
1399
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
1400
+ where: { orderId: row.orderId, OR: answerableRequest(row) },
1401
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
1402
+ });
1403
+ if (confirmed.count === 0) return false;
1404
+ await rejectConfirmed(tx, row.orderId, now);
1405
+ return true;
1406
+ });
1407
+ if (!moved) return;
1408
+ try {
1409
+ await confirmedToHost(ctx, clientId, row.orderId);
1410
+ } catch (error) {
1411
+ ctx.ports.logger.error(
1412
+ `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))
1413
+ );
1414
+ }
1415
+ }
1416
+ __name(stampConfirmedCancellation, "stampConfirmedCancellation");
1417
+ async function connectionFor(ctx, clientId, provider) {
1418
+ try {
1419
+ return await readOutboundConnection(ctx, clientId, provider) ?? "no credentials on file";
1420
+ } catch (error) {
1421
+ return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
1422
+ }
1423
+ }
1424
+ __name(connectionFor, "connectionFor");
1425
+ async function settle2(ctx, payload, row, result, attempt, succeed, fail2) {
1426
+ if (result.kind === "accepted") {
1427
+ await succeed();
1428
+ ctx.ports.publishChanged(payload.clientId);
1429
+ return { kind: "done", action: payload.action };
1430
+ }
1431
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1432
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1433
+ throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);
1434
+ }
1435
+ await fail2();
1436
+ ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);
1437
+ ctx.ports.publishChanged(payload.clientId);
1438
+ return { kind: "failed", action: payload.action, reason };
1439
+ }
1440
+ __name(settle2, "settle");
1441
+ async function runConfirm(ctx, payload, row, adapter, attempt) {
1442
+ const skip = confirmSkip(row, adapter);
1443
+ if (skip) return { kind: "skipped", reason: skip };
1444
+ const now = ctx.ports.clock.now();
1445
+ const connection = await connectionFor(ctx, payload.clientId, row.provider);
1446
+ const result = typeof connection === "string" ? { kind: "refused", status: 0, message: connection } : await adapter.confirm(
1447
+ { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
1448
+ refOf(row),
1449
+ // The stated preparation time, for a marketplace whose confirm takes one.
1450
+ { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
1451
+ );
1452
+ return settle2(
1453
+ ctx,
1454
+ payload,
1455
+ row,
1456
+ result,
1457
+ attempt,
1458
+ () => stampConfirm(ctx, row, true, now),
1459
+ () => stampConfirm(ctx, row, false, now)
1460
+ );
1461
+ }
1462
+ __name(runConfirm, "runConfirm");
1463
+ function pastWindow(ctx, row, adapter) {
1464
+ if (!requestsFirst(ctx)) return false;
1465
+ const window = cancellationWindowMs(ctx, adapter);
1466
+ if (window === null || row.cancellationRequestedAt === null) return false;
1467
+ return ctx.ports.clock.now().getTime() - row.cancellationRequestedAt.getTime() > window;
1468
+ }
1469
+ __name(pastWindow, "pastWindow");
1470
+ function skusOf(row) {
1471
+ return Array.isArray(row.cancellationOffendingSkus) ? row.cancellationOffendingSkus.map(String) : [];
1472
+ }
1473
+ __name(skusOf, "skusOf");
1474
+ async function runCancellation(ctx, payload, row, adapter, attempt) {
1475
+ if (row.cancellationStatus !== "PENDING") {
1476
+ return { kind: "skipped", reason: `the request is ${row.cancellationStatus ?? "absent"}, not PENDING` };
1477
+ }
1478
+ if (pastWindow(ctx, row, adapter)) {
1479
+ await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
1480
+ return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
1481
+ }
1482
+ const reason = resolveReason(adapter, row.cancellationReasonCode);
1483
+ const connection = await connectionFor(ctx, payload.clientId, row.provider);
1484
+ let result;
1485
+ if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's" };
1486
+ else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection };
1487
+ else {
1488
+ result = await adapter.requestCancellation(
1489
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
1490
+ refOf(row),
1491
+ { reason, text: "", mode: "MANUAL", offendingSkus: skusOf(row) }
1492
+ );
1493
+ }
1494
+ const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
1495
+ return settle2(
1496
+ ctx,
1497
+ payload,
1498
+ row,
1499
+ result,
1500
+ attempt,
1501
+ () => stampCancellation(ctx, row, taken, payload.clientId),
1502
+ () => stampCancellation(ctx, row, "FAILED", payload.clientId)
1503
+ );
1504
+ }
1505
+ __name(runCancellation, "runCancellation");
1506
+ async function stampLastAttemptFailure(ctx, payload, error) {
1507
+ const reason = error instanceof Error ? error.message : String(error);
1508
+ const db = await ctx.ports.db();
1509
+ const moved = await (payload.action === "confirm" ? db.marketplaceAcceptance.updateMany({
1510
+ where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },
1511
+ data: { confirmFailedAt: ctx.ports.clock.now() }
1512
+ }) : db.marketplaceAcceptance.updateMany({
1513
+ where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
1514
+ data: failedRequestData("REFUSED")
1515
+ }));
1516
+ ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
1517
+ ctx.ports.publishChanged(payload.clientId);
1518
+ if (payload.action === "requestCancellation" && moved.count > 0) {
1519
+ await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
1520
+ }
1521
+ return { kind: "failed", action: payload.action, reason };
1522
+ }
1523
+ __name(stampLastAttemptFailure, "stampLastAttemptFailure");
1524
+ async function runOnce2(ctx, payload, attempt) {
1525
+ const db = await ctx.ports.db();
1526
+ const row = await db.marketplaceAcceptance.findFirst({
1527
+ where: { orderId: payload.orderId, clientId: payload.clientId },
1528
+ select: ROW_SELECT
1529
+ });
1530
+ if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
1531
+ const adapter = ctx.registry.get(row.provider);
1532
+ if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
1533
+ return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
1534
+ }
1535
+ __name(runOnce2, "runOnce");
1536
+ async function runOutbound(ctx, payload, attempt) {
1537
+ try {
1538
+ return await runOnce2(ctx, payload, attempt);
1539
+ } catch (error) {
1540
+ if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;
1541
+ return stampLastAttemptFailure(ctx, payload, error);
1542
+ }
1543
+ }
1544
+ __name(runOutbound, "runOutbound");
1545
+
1546
+ export {
1547
+ requestsFirst,
1548
+ tellCancellationFailed,
1549
+ PROVIDER_ID_PATTERN,
1550
+ MarketplaceAdapterRegistrationError,
1551
+ createAdapterRegistry,
1552
+ resolveReason,
1553
+ suggestReason,
1554
+ NO_STANDING_REQUEST,
1555
+ CLAIM_SELECT,
1556
+ notPendingProblem,
1557
+ planCancellation,
1558
+ refusalData,
1559
+ requestData,
1560
+ failCancellationRequest,
1561
+ listPendingAcceptances,
1562
+ expireLapsedAcceptances,
1563
+ cancelAcceptance,
1564
+ listMarketplaceIntegrations,
1565
+ saveMarketplaceIntegration,
1566
+ connectionMerchantId,
1567
+ resolveIngestionTarget,
1568
+ resolveTenantByMerchant,
1569
+ listMarketplaceMenuLinks,
1570
+ upsertLink,
1571
+ MARKETPLACE_OUTBOUND_JOB,
1572
+ outboundDedupeKey,
1573
+ enqueueOutbound,
1574
+ CATALOGUE_ROW_SELECT,
1575
+ catalogueTable,
1576
+ viewOf,
1577
+ NO_FAILURE,
1578
+ catalogueConnection,
1579
+ MARKETPLACE_CATALOGUE_JOB,
1580
+ CatalogueRetryError,
1581
+ catalogueDedupeKey,
1582
+ enqueueCatalogue,
1583
+ runCatalogue,
1584
+ recordInboxEvent,
1585
+ settleInboxEvent,
1586
+ deferInboxEvent,
1587
+ listRetryableInboxEvents,
1588
+ ingestMarketplaceOrder,
1589
+ markCancelledBeforeIngest,
1590
+ MARKETPLACE_FETCH_ORDER_JOB,
1591
+ FetchOrderRetryError,
1592
+ awaitOrderBody,
1593
+ requeueOwedFetch,
1594
+ merchantMismatch,
1595
+ runFetchOrder,
1596
+ CATALOGUE_STALE_MS,
1597
+ CATALOGUE_GIVE_UP_MS,
1598
+ OUTBOUND_STALE_MS,
1599
+ OUTBOUND_GIVE_UP_MS,
1600
+ sweepOutbound,
1601
+ OutboundRetryError,
1602
+ runOutbound
1603
+ };
1604
+ //# sourceMappingURL=chunk-XUAFXNOH.js.map