@12-apps/marketplace 1.10.0 → 1.12.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 (84) hide show
  1. package/ADOPTING.md +126 -1
  2. package/README.md +100 -1
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CYJzu1c9.d.ts → adapter-nUyZpLzz.d.ts} +448 -173
  6. package/dist/{chunk-2BA2EHNF.js → chunk-45ZVN5XI.js} +316 -42
  7. package/dist/chunk-45ZVN5XI.js.map +1 -0
  8. package/dist/{chunk-PYHNM47K.js → chunk-L6FG6T4S.js} +2 -2
  9. package/dist/{chunk-HEXLCTOG.js → chunk-LACBT6NC.js} +1 -1
  10. package/dist/chunk-LACBT6NC.js.map +1 -0
  11. package/dist/{chunk-WVZ2IXFH.js → chunk-MIPNQ7X5.js} +190 -12
  12. package/dist/chunk-MIPNQ7X5.js.map +1 -0
  13. package/dist/chunk-SGOTN5PX.js +345 -0
  14. package/dist/chunk-SGOTN5PX.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-Ctas7WCS.d.ts} +1 -1
  16. package/dist/{engine-DK3iV_Kk.d.ts → engine-CIy9P7Cq.d.ts} +149 -8
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +10 -2
  20. package/dist/ifood/index.js +297 -25
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +424 -84
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -18
  26. package/dist/keeta/index.js +12 -3
  27. package/dist/keeta/index.js.map +1 -1
  28. package/dist/manifest/index.d.ts +219 -1
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +2 -2
  31. package/dist/manifest/server.js +3 -3
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/en-US.d.ts +13 -0
  35. package/dist/server/en-US.js +13 -0
  36. package/dist/server/en-US.js.map +1 -1
  37. package/dist/server/index.d.ts +241 -7
  38. package/dist/server/index.js +3 -3
  39. package/dist/server/pt-BR.d.ts +13 -0
  40. package/dist/server/pt-BR.js +13 -0
  41. package/dist/server/pt-BR.js.map +1 -1
  42. package/package.json +1 -1
  43. package/prisma/marketplace.prisma +41 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +27 -0
  46. package/src/core/bulk.ts +43 -8
  47. package/src/core/courier-port.ts +100 -0
  48. package/src/core/courier.ts +153 -0
  49. package/src/core/engine.ts +63 -4
  50. package/src/core/integration.ts +60 -32
  51. package/src/core/lifecycle.ts +27 -4
  52. package/src/core/link-store.ts +170 -0
  53. package/src/core/linking-port.ts +100 -0
  54. package/src/core/linking.ts +363 -0
  55. package/src/core/merchant-claim.ts +106 -0
  56. package/src/core/outbound-queue.ts +24 -11
  57. package/src/core/outbound.ts +8 -6
  58. package/src/core/pickup-code.ts +136 -0
  59. package/src/core/pipeline.ts +15 -6
  60. package/src/core/ports.ts +26 -1
  61. package/src/core/status-store.ts +2 -3
  62. package/src/core/types.ts +56 -4
  63. package/src/ifood/courier.ts +210 -0
  64. package/src/ifood/index.ts +8 -0
  65. package/src/ifood/linking.ts +170 -0
  66. package/src/ifood/normalize.ts +7 -0
  67. package/src/ifood/outbound.ts +10 -3
  68. package/src/index.ts +30 -0
  69. package/src/keeta/normalize.ts +21 -6
  70. package/src/server/copy.ts +20 -2
  71. package/src/server/en-US.ts +13 -0
  72. package/src/server/index.ts +1 -1
  73. package/src/server/link-routes.ts +140 -0
  74. package/src/server/mcp-link.ts +103 -0
  75. package/src/server/mcp.ts +6 -2
  76. package/src/server/pt-BR.ts +13 -0
  77. package/src/server/routes.ts +5 -2
  78. package/src/server/webhook.ts +86 -0
  79. package/dist/chunk-2BA2EHNF.js.map +0 -1
  80. package/dist/chunk-HEXLCTOG.js.map +0 -1
  81. package/dist/chunk-WVZ2IXFH.js.map +0 -1
  82. package/dist/chunk-ZO4S3LF4.js +0 -254
  83. package/dist/chunk-ZO4S3LF4.js.map +0 -1
  84. /package/dist/{chunk-PYHNM47K.js.map → chunk-L6FG6T4S.js.map} +0 -0
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  MARKETPLACE_FETCH_ORDER_JOB,
13
13
  MARKETPLACE_OUTBOUND_JOB,
14
14
  MarketplaceAdapterRegistrationError,
15
+ MarketplaceMerchantTakenError,
15
16
  NO_FAILURE,
16
17
  NO_STANDING_REQUEST,
17
18
  OUTBOUND_GIVE_UP_MS,
@@ -19,8 +20,10 @@ import {
19
20
  OutboundRetryError,
20
21
  PROVIDER_ID_PATTERN,
21
22
  STORE_PAUSE_LEASE_MS,
23
+ appCredentialsOf,
22
24
  availabilityDedupeKey,
23
25
  awaitOrderBody,
26
+ cacheLinkToken,
24
27
  cancelAcceptance,
25
28
  cancelledBeforeIngest,
26
29
  catalogueConnection,
@@ -34,14 +37,18 @@ import {
34
37
  enqueueOutbound,
35
38
  expireLapsedAcceptances,
36
39
  failCancellationRequest,
40
+ guardMerchantClaim,
37
41
  hasPauseTable,
38
42
  holdsSomething,
39
43
  ingestMarketplaceOrder,
44
+ isUniqueViolation,
45
+ linkTokenKey,
40
46
  listMarketplaceIntegrations,
41
47
  listMarketplaceMenuLinks,
42
48
  listPendingAcceptances,
43
49
  listRetryableInboxEvents,
44
50
  markCancelledBeforeIngest,
51
+ merchantHeldElsewhere,
45
52
  merchantMismatch,
46
53
  notPendingProblem,
47
54
  noteMarketplaceStep,
@@ -64,6 +71,7 @@ import {
64
71
  runFetchOrder,
65
72
  runOutbound,
66
73
  saveMarketplaceIntegration,
74
+ sealLink,
67
75
  settleInboxEvent,
68
76
  statusDedupeKey,
69
77
  statusTable,
@@ -71,8 +79,9 @@ import {
71
79
  sweepOutbound,
72
80
  tellCancellationFailed,
73
81
  upsertLink,
82
+ validatePickupCode,
74
83
  viewOf
75
- } from "./chunk-2BA2EHNF.js";
84
+ } from "./chunk-45ZVN5XI.js";
76
85
  import {
77
86
  centsFromMajor
78
87
  } from "./chunk-WN2EK4KX.js";
@@ -83,16 +92,16 @@ import {
83
92
  answered,
84
93
  outboundResultOf,
85
94
  tokenGrantResultOf
86
- } from "./chunk-HEXLCTOG.js";
95
+ } from "./chunk-LACBT6NC.js";
87
96
  import {
88
97
  __name
89
98
  } from "./chunk-7QVYU63E.js";
90
99
 
91
100
  // src/core/bulk.ts
92
- function duplicates(rows, keyOf, list, field) {
101
+ function duplicates(rows, keyOf2, list, field) {
93
102
  const seen = /* @__PURE__ */ new Set();
94
103
  return rows.flatMap((row, index) => {
95
- const key = keyOf(row);
104
+ const key = keyOf2(row);
96
105
  if (!seen.has(key)) {
97
106
  seen.add(key);
98
107
  return [];
@@ -117,6 +126,19 @@ function integrationRowProblems(row, index, existing) {
117
126
  return changes ? [] : [{ path: ["integrations", index], code: "NOTHING_TO_UPDATE" }];
118
127
  }
119
128
  __name(integrationRowProblems, "integrationRowProblems");
129
+ async function merchantProblems(ctx, clientId, rows, merchantOf) {
130
+ const db = await ctx.ports.db();
131
+ const problems = [];
132
+ for (const [index, row] of rows.entries()) {
133
+ const unarchive = row.operation === "unarchive";
134
+ const merchantId = unarchive ? merchantOf.get(row.provider) : "externalMerchantId" in row ? row.externalMerchantId : null;
135
+ if (row.operation === "archive" || !merchantId) continue;
136
+ if (!await merchantHeldElsewhere(db, clientId, row.provider, merchantId)) continue;
137
+ problems.push({ path: ["integrations", index, unarchive ? "provider" : "externalMerchantId"], code: "MERCHANT_TAKEN" });
138
+ }
139
+ return problems;
140
+ }
141
+ __name(merchantProblems, "merchantProblems");
120
142
  var ValidateOnly = class extends Error {
121
143
  static {
122
144
  __name(this, "ValidateOnly");
@@ -152,21 +174,29 @@ async function writeIntegration(ctx, db, clientId, row, now) {
152
174
  }
153
175
  __name(writeIntegration, "writeIntegration");
154
176
  async function upsertIntegrations(ctx, input) {
155
- const existing = new Set(
156
- (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider)
157
- );
177
+ const stored = await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true });
178
+ const existing = new Set(stored.map((row) => row.provider));
179
+ const merchantOf = new Map(stored.map((row) => [row.provider, row.externalMerchantId]));
158
180
  const problems = [
159
181
  ...duplicates(input.rows, (row) => row.provider, "integrations", "provider"),
160
182
  ...unknownProviders(ctx, input.rows, "integrations"),
161
183
  ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing))
162
184
  ];
185
+ if (problems.length === 0) problems.push(...await merchantProblems(ctx, input.clientId, input.rows, merchantOf));
163
186
  if (problems.length > 0) return { kind: "refused", problems };
164
187
  const validateOnly = input.validateOnly === true;
165
188
  const now = ctx.ports.clock.now();
166
- await inTransaction(ctx, validateOnly, async (db) => {
167
- for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);
168
- await auditArchives(ctx, db, input, now);
169
- });
189
+ try {
190
+ await inTransaction(ctx, validateOnly, async (db) => {
191
+ for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);
192
+ await auditArchives(ctx, db, input, now);
193
+ });
194
+ } catch (error) {
195
+ const raced = error instanceof MarketplaceMerchantTakenError || isUniqueViolation(error);
196
+ const lost = raced ? await merchantProblems(ctx, input.clientId, input.rows, merchantOf) : [];
197
+ if (lost.length === 0) throw error;
198
+ return { kind: "refused", problems: lost };
199
+ }
170
200
  const providers = input.rows.map((row) => row.provider);
171
201
  const rows = validateOnly ? [] : await listMarketplaceIntegrations(ctx, input.clientId, { providers, includeArchived: true });
172
202
  return { kind: "saved", validateOnly, rows };
@@ -285,7 +315,7 @@ function requestOnly(ctx, plan) {
285
315
  __name(requestOnly, "requestOnly");
286
316
  async function admitAndClaim(ctx, clientId, planned, validateOnly) {
287
317
  await ctx.ports.transaction(async (tx) => {
288
- const refused2 = [];
318
+ const refused3 = [];
289
319
  for (const one of planned) {
290
320
  const admission = one.input.decision === "ACCEPT" ? one.input.admission ?? {} : {};
291
321
  const answer = await ctx.ports.order.admit({
@@ -297,18 +327,18 @@ async function admitAndClaim(ctx, clientId, planned, validateOnly) {
297
327
  });
298
328
  if (!answer.admitted) {
299
329
  const host = { code: answer.code, message: answer.message, details: answer.details };
300
- refused2.push({ path: ["decisions", one.index], code: "HOST_REFUSED", host });
330
+ refused3.push({ path: ["decisions", one.index], code: "HOST_REFUSED", host });
301
331
  }
302
332
  }
303
- if (refused2.length > 0) throw new Rollback(refused2);
333
+ if (refused3.length > 0) throw new Rollback(refused3);
304
334
  for (const one of planned) {
305
335
  const claimed = await tx.marketplaceAcceptance.updateMany({
306
336
  where: { orderId: one.input.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
307
337
  data: one.data
308
338
  });
309
- if (claimed.count === 0) refused2.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
339
+ if (claimed.count === 0) refused3.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
310
340
  }
311
- if (refused2.length > 0) throw new Rollback(refused2);
341
+ if (refused3.length > 0) throw new Rollback(refused3);
312
342
  if (validateOnly) throw new Rollback(null);
313
343
  });
314
344
  }
@@ -566,6 +596,367 @@ var engineRefusal = /* @__PURE__ */ __name((code) => ({
566
596
  message: null
567
597
  }), "engineRefusal");
568
598
 
599
+ // src/core/lifecycle.ts
600
+ var ECHO_OF = {
601
+ DISPATCHED: "DISPATCHED",
602
+ // The courier holding the bag answers the store's hand-over (FUT-5665).
603
+ COLLECTED: "HANDED_OVER",
604
+ CONCLUDED: "HANDED_OVER"
605
+ };
606
+ var NOTED_AS = {
607
+ DISPATCHED: "DISPATCHED",
608
+ COLLECTED: "HANDED_OVER",
609
+ CONCLUDED: "CONCLUDED"
610
+ };
611
+ async function ignored(ctx, inboxId, reason) {
612
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
613
+ return { kind: "ignored", reason };
614
+ }
615
+ __name(ignored, "ignored");
616
+ function refusal(held) {
617
+ if (held.status !== "ACCEPTED") return `the order is ${held.status}, not ACCEPTED`;
618
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") {
619
+ return `a cancellation request is ${held.cancellationStatus}`;
620
+ }
621
+ return null;
622
+ }
623
+ __name(refusal, "refusal");
624
+ function notTheFleets(lifecycle, held) {
625
+ return lifecycle === "COLLECTED" && held.deliveredBy !== "MARKETPLACE" ? "COLLECTED of a bag the marketplace does not carry" : null;
626
+ }
627
+ __name(notTheFleets, "notTheFleets");
628
+ function deliveredByOf(held) {
629
+ return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
630
+ }
631
+ __name(deliveredByOf, "deliveredByOf");
632
+ function following(ctx, event, settings) {
633
+ const hook = ctx.ports.order.onLifecycle;
634
+ if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;
635
+ return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };
636
+ }
637
+ __name(following, "following");
638
+ async function followLifecycle(ctx, inboxId, clientId, event, settings) {
639
+ const follow = following(ctx, event, settings);
640
+ if (!follow) return null;
641
+ const { lifecycle, hook } = follow;
642
+ const db = await ctx.ports.db();
643
+ const table = statusTable(db);
644
+ if (!table) return null;
645
+ const held = await db.marketplaceAcceptance.findFirst({
646
+ where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },
647
+ select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true }
648
+ });
649
+ if (!held) {
650
+ const reason2 = "lifecycle before its order";
651
+ await deferInboxEvent(ctx, inboxId, reason2);
652
+ return { kind: "ignored", reason: reason2 };
653
+ }
654
+ const stopped = refusal(held) ?? notTheFleets(lifecycle, held);
655
+ if (stopped) return ignored(ctx, inboxId, stopped);
656
+ const echo = ECHO_OF[lifecycle];
657
+ const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === "STORE");
658
+ if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);
659
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
660
+ await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: NOTED_AS[lifecycle] });
661
+ if (answer === "moved") {
662
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
663
+ ctx.ports.publishChanged(clientId);
664
+ return { kind: "moved", orderId: held.orderId, lifecycle };
665
+ }
666
+ const reason = answer === "unchanged" ? `already at or past ${lifecycle}` : answer.reason;
667
+ if (answer !== "unchanged") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);
668
+ return ignored(ctx, inboxId, reason);
669
+ }
670
+ __name(followLifecycle, "followLifecycle");
671
+
672
+ // src/core/courier.ts
673
+ function deliveredByOf2(value) {
674
+ return value === "MERCHANT" || value === "MARKETPLACE" ? value : null;
675
+ }
676
+ __name(deliveredByOf2, "deliveredByOf");
677
+ function reasonOf(answer, step) {
678
+ if (answer === "unchanged") return `nothing to record for ${step}`;
679
+ return answer === "recorded" ? "" : answer.reason;
680
+ }
681
+ __name(reasonOf, "reasonOf");
682
+ async function followCourier(ctx, clientId, event) {
683
+ const hook = ctx.ports.order.onCourier;
684
+ const courier = event.courier;
685
+ if (!hook || !courier || !event.externalOrderId) return null;
686
+ const db = await ctx.ports.db();
687
+ const held = await db.marketplaceAcceptance.findFirst({
688
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
689
+ select: { orderId: true, status: true, deliveredBy: true }
690
+ });
691
+ if (!held) return { kind: "deferred" };
692
+ if (held.status !== "ACCEPTED") return { kind: "stopped", reason: `the order is ${held.status}, not ACCEPTED` };
693
+ const facts = { deliveredBy: deliveredByOf2(held.deliveredBy), at: courier.at ?? ctx.ports.clock.now() };
694
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, courier, facts);
695
+ if (answer === "recorded") return { kind: "recorded", orderId: held.orderId, step: courier.step };
696
+ return { kind: "stopped", reason: reasonOf(answer, courier.step) };
697
+ }
698
+ __name(followCourier, "followCourier");
699
+ async function settleCourier(ctx, inboxId, clientId, outcome) {
700
+ if (outcome.kind === "recorded") {
701
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
702
+ ctx.ports.publishChanged(clientId);
703
+ return { kind: "courier", orderId: outcome.orderId, step: outcome.step };
704
+ }
705
+ if (outcome.kind === "deferred") {
706
+ const reason = "courier event before its order";
707
+ await deferInboxEvent(ctx, inboxId, reason);
708
+ return { kind: "ignored", reason };
709
+ }
710
+ await settleInboxEvent(ctx, inboxId, "IGNORED", outcome.reason);
711
+ return { kind: "ignored", reason: outcome.reason };
712
+ }
713
+ __name(settleCourier, "settleCourier");
714
+ async function followCourierAndLifecycle(ctx, inboxId, clientId, event, settings) {
715
+ const courier = await followCourier(ctx, clientId, event);
716
+ const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
717
+ const recorded = courier?.kind === "recorded";
718
+ if (followed && !(recorded && followed.kind === "ignored")) return followed;
719
+ return courier ? settleCourier(ctx, inboxId, clientId, courier) : null;
720
+ }
721
+ __name(followCourierAndLifecycle, "followCourierAndLifecycle");
722
+ async function readCourierTracking(ctx, input) {
723
+ const db = await ctx.ports.db();
724
+ const row = await db.marketplaceAcceptance.findFirst({
725
+ where: { clientId: input.clientId, orderId: input.orderId },
726
+ select: { orderId: true, provider: true, externalOrderId: true, externalDisplayId: true, deliveredBy: true, createdAt: true }
727
+ });
728
+ if (!row) return { kind: "unsupported", reason: "no marketplace order with this id" };
729
+ const api = ctx.registry.get(row.provider)?.courier;
730
+ if (!api) return { kind: "unsupported", reason: `${row.provider} has no courier tracking` };
731
+ if (row.deliveredBy !== "MARKETPLACE") return { kind: "unsupported", reason: "the order is not carried by the marketplace's courier" };
732
+ let connection;
733
+ try {
734
+ connection = await readOutboundConnection(ctx, input.clientId, row.provider);
735
+ } catch (error) {
736
+ return { kind: "refused", status: 0, message: `credentials do not open: ${error instanceof Error ? error.message : String(error)}`, own: true };
737
+ }
738
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
739
+ const ref = {
740
+ externalOrderId: row.externalOrderId,
741
+ externalDisplayId: row.externalDisplayId,
742
+ hostOrderCode: row.orderId,
743
+ placedAt: row.createdAt
744
+ };
745
+ return api.tracking({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, ref);
746
+ }
747
+ __name(readCourierTracking, "readCourierTracking");
748
+ function courierEngine(ctx) {
749
+ return {
750
+ validatePickupCode: /* @__PURE__ */ __name((input) => validatePickupCode(ctx, input), "validatePickupCode"),
751
+ courierTracking: /* @__PURE__ */ __name((input) => readCourierTracking(ctx, input), "courierTracking")
752
+ };
753
+ }
754
+ __name(courierEngine, "courierEngine");
755
+
756
+ // src/core/linking.ts
757
+ var refused2 = /* @__PURE__ */ __name((code, status = null, message = null) => ({
758
+ kind: "refused",
759
+ code,
760
+ status,
761
+ message
762
+ }), "refused");
763
+ var pendingOf = /* @__PURE__ */ __name((row) => ({
764
+ userCode: row.userCode,
765
+ verificationUrl: row.verificationUrl,
766
+ verificationUrlComplete: row.verificationUrlComplete,
767
+ expiresAt: row.expiresAt
768
+ }), "pendingOf");
769
+ async function linkingOf(ctx, provider, environment) {
770
+ const linking = ctx.registry.get(provider)?.linking;
771
+ if (!linking) return null;
772
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
773
+ if (!attempts) return null;
774
+ const app = await appCredentialsOf(ctx, provider, environment);
775
+ if (!app) return null;
776
+ return { linking, attempts, call: { http: ctx.ports.http, credentials: app, environment, now: ctx.ports.clock.now() } };
777
+ }
778
+ __name(linkingOf, "linkingOf");
779
+ var keyOf = /* @__PURE__ */ __name((clientId, provider) => ({ clientId_provider: { clientId, provider } }), "keyOf");
780
+ async function linkState(ctx, input) {
781
+ const ready = await linkingOf(ctx, input.provider, input.environment ?? "PRODUCTION");
782
+ if (!ready) return { available: false, pending: null };
783
+ const row = await ready.attempts.findUnique({ where: keyOf(input.clientId, input.provider) });
784
+ const live = row && row.expiresAt.getTime() > ctx.ports.clock.now().getTime();
785
+ return { available: true, pending: live ? pendingOf(row) : null };
786
+ }
787
+ __name(linkState, "linkState");
788
+ async function startLink(ctx, input) {
789
+ const environment = input.environment ?? "PRODUCTION";
790
+ const ready = await linkingOf(ctx, input.provider, environment);
791
+ if (!ready) return refused2("UNAVAILABLE");
792
+ const answer = await ready.linking.requestCode(ready.call);
793
+ if (answer.kind === "retry") return answer;
794
+ if (answer.kind === "refused") return refused2("MARKETPLACE_REFUSED", answer.status, answer.message);
795
+ const code = answer.value;
796
+ const row = {
797
+ environment,
798
+ verifier: ctx.ports.secrets.seal(code.verifier),
799
+ userCode: code.userCode,
800
+ verificationUrl: code.verificationUrl,
801
+ verificationUrlComplete: code.verificationUrlComplete,
802
+ expiresAt: new Date(ready.call.now.getTime() + code.expiresInSeconds * 1e3)
803
+ };
804
+ await ready.attempts.upsert({
805
+ where: keyOf(input.clientId, input.provider),
806
+ create: { clientId: input.clientId, provider: input.provider, ...row },
807
+ update: row
808
+ });
809
+ return { kind: "started", pending: pendingOf(row) };
810
+ }
811
+ __name(startLink, "startLink");
812
+ async function chooseMerchant(db, input, merchants, current) {
813
+ if (!merchants) return current;
814
+ const candidate = merchants.length === 1 ? merchants[0].id : merchants.some((merchant) => merchant.id === current) ? current : null;
815
+ if (candidate === null) return null;
816
+ return await merchantHeldElsewhere(db, input.clientId, input.provider, candidate) ? null : candidate;
817
+ }
818
+ __name(chooseMerchant, "chooseMerchant");
819
+ async function saveLink(ctx, input, link) {
820
+ const now = ctx.ports.clock.now();
821
+ const credentials = sealLink(ctx, link.refreshToken);
822
+ await ctx.ports.transaction(async (db) => {
823
+ const existing = await db.marketplaceIntegration.findUnique({
824
+ where: keyOf(input.clientId, input.provider),
825
+ select: { archivedAt: true, externalMerchantId: true }
826
+ });
827
+ const data = {
828
+ credentials,
829
+ authMode: "LINKED",
830
+ environment: link.environment,
831
+ status: "VERIFIED",
832
+ lastVerifiedAt: now,
833
+ archivedAt: null,
834
+ externalMerchantId: await chooseMerchant(db, input, link.merchants, existing?.externalMerchantId ?? null),
835
+ ...input.enabled === void 0 ? {} : { enabled: input.enabled }
836
+ };
837
+ await db.marketplaceIntegration.upsert({
838
+ where: keyOf(input.clientId, input.provider),
839
+ create: { clientId: input.clientId, provider: input.provider, ackSlaSeconds: ctx.ports.defaultAckSlaSeconds, ...data },
840
+ update: data
841
+ });
842
+ if (existing?.archivedAt) {
843
+ await ctx.ports.audit.record(
844
+ {
845
+ clientId: input.clientId,
846
+ actorId: input.actorId,
847
+ action: "marketplace.integration.unarchive",
848
+ provider: input.provider,
849
+ reason: "linked again",
850
+ at: now
851
+ },
852
+ db
853
+ );
854
+ }
855
+ await db.marketplaceLinkAttempt.deleteMany({ where: { clientId: input.clientId, provider: input.provider, verifier: link.verifier } });
856
+ });
857
+ return credentials;
858
+ }
859
+ __name(saveLink, "saveLink");
860
+ async function saveLinkKeepingTokens(ctx, input, link) {
861
+ try {
862
+ return await saveLink(ctx, input, link);
863
+ } catch (error) {
864
+ if (!isUniqueViolation(error)) throw error;
865
+ ctx.ports.logger.warn(`marketplace.link: ${input.provider} merchant of ${input.clientId} taken meanwhile; none chosen`);
866
+ return saveLink(ctx, input, { ...link, merchants: [] });
867
+ }
868
+ }
869
+ __name(saveLinkKeepingTokens, "saveLinkKeepingTokens");
870
+ async function viewOf2(ctx, clientId, provider) {
871
+ const [view] = await listMarketplaceIntegrations(ctx, clientId, { providers: [provider] });
872
+ if (!view) throw new Error(`The ${provider} connection of ${clientId} was not saved.`);
873
+ return view;
874
+ }
875
+ __name(viewOf2, "viewOf");
876
+ async function finishLink(ctx, input) {
877
+ const opened = await openAttempt(ctx, input);
878
+ if ("kind" in opened) return opened;
879
+ const { ready, environment, verifier, sealedVerifier } = opened;
880
+ const exchanged = await ready.linking.exchange(ready.call, { authorizationCode: input.authorizationCode.trim(), verifier });
881
+ if (exchanged.kind === "retry") return exchanged;
882
+ if (exchanged.kind === "refused") return refused2("CODE_REFUSED", exchanged.status, exchanged.message);
883
+ const grant = exchanged.value;
884
+ if (grant.refreshToken === null) return refused2("CODE_REFUSED", null, "the marketplace answered no refresh token");
885
+ const listed = await ready.linking.merchants(ready.call, { accessToken: grant.accessToken });
886
+ const merchants = listed.kind === "ok" ? listed.value : null;
887
+ if (listed.kind !== "ok") {
888
+ ctx.ports.logger.warn(`marketplace.link: ${input.provider} merchants of ${input.clientId} not listed (${listed.kind})`);
889
+ }
890
+ const sealed = await saveLinkKeepingTokens(ctx, input, { environment, refreshToken: grant.refreshToken, merchants, verifier: sealedVerifier });
891
+ await cacheLinkToken(ctx, { ...input, sealed }, linkTokenKey(input.provider, environment, input.clientId), grant);
892
+ ctx.ports.publishChanged(input.clientId);
893
+ return { kind: "linked", integration: await viewOf2(ctx, input.clientId, input.provider), merchants };
894
+ }
895
+ __name(finishLink, "finishLink");
896
+ async function openAttempt(ctx, input) {
897
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
898
+ if (!attempts) return refused2("UNAVAILABLE");
899
+ const attempt = await attempts.findUnique({ where: keyOf(input.clientId, input.provider) });
900
+ if (!attempt) return refused2("NO_LINK_IN_PROGRESS");
901
+ const environment = attempt.environment === "SANDBOX" ? "SANDBOX" : "PRODUCTION";
902
+ const ready = await linkingOf(ctx, input.provider, environment);
903
+ if (!ready) return refused2("UNAVAILABLE");
904
+ if (attempt.expiresAt.getTime() <= ready.call.now.getTime()) return refused2("LINK_EXPIRED");
905
+ return { ready, environment, verifier: ctx.ports.secrets.open(attempt.verifier), sealedVerifier: attempt.verifier };
906
+ }
907
+ __name(openAttempt, "openAttempt");
908
+ async function grantCall(ctx, clientId, provider) {
909
+ const views = await listMarketplaceIntegrations(ctx, clientId, { providers: [provider] });
910
+ if (views[0]?.authMode !== "LINKED") return refused2("NOT_LINKED");
911
+ const connection = await readOutboundConnection(ctx, clientId, provider).catch(() => null);
912
+ if (!connection?.grant) return refused2("UNAVAILABLE");
913
+ const token = await connection.grant.accessToken();
914
+ if ("token" in token) {
915
+ const call = { http: ctx.ports.http, credentials: connection.credentials, environment: connection.environment, now: ctx.ports.clock.now() };
916
+ return { call, accessToken: token.token };
917
+ }
918
+ if (token.kind === "retry") return token;
919
+ return token.kind === "refused" ? refused2("NOT_LINKED", token.status, token.message) : refused2("NOT_LINKED");
920
+ }
921
+ __name(grantCall, "grantCall");
922
+ async function grantMerchants(ctx, clientId, provider) {
923
+ const linking = ctx.registry.get(provider)?.linking;
924
+ if (!linking) return refused2("UNAVAILABLE");
925
+ const granted = await grantCall(ctx, clientId, provider);
926
+ if ("kind" in granted) return granted;
927
+ const listed = await linking.merchants(granted.call, { accessToken: granted.accessToken });
928
+ if (listed.kind === "ok") return listed.value;
929
+ return listed.kind === "retry" ? listed : refused2("MARKETPLACE_REFUSED", listed.status, listed.message);
930
+ }
931
+ __name(grantMerchants, "grantMerchants");
932
+ async function linkedMerchants(ctx, input) {
933
+ const merchants = await grantMerchants(ctx, input.clientId, input.provider);
934
+ return Array.isArray(merchants) ? { kind: "listed", merchants } : merchants;
935
+ }
936
+ __name(linkedMerchants, "linkedMerchants");
937
+ async function selectLinkedMerchant(ctx, input) {
938
+ const merchants = await grantMerchants(ctx, input.clientId, input.provider);
939
+ if (!Array.isArray(merchants)) return merchants;
940
+ if (!merchants.some((merchant) => merchant.id === input.merchantId)) return refused2("UNKNOWN_MERCHANT");
941
+ const db = await ctx.ports.db();
942
+ if (await merchantHeldElsewhere(db, input.clientId, input.provider, input.merchantId)) return refused2("MERCHANT_TAKEN");
943
+ const write = /* @__PURE__ */ __name(() => db.marketplaceIntegration.updateMany({
944
+ where: { clientId: input.clientId, provider: input.provider, authMode: "LINKED", archivedAt: null },
945
+ data: { externalMerchantId: input.merchantId }
946
+ }), "write");
947
+ const taken = await guardMerchantClaim(ctx, { ...input, merchantId: input.merchantId }, write).then(
948
+ () => false,
949
+ (error) => {
950
+ if (error instanceof MarketplaceMerchantTakenError) return true;
951
+ throw error;
952
+ }
953
+ );
954
+ if (taken) return refused2("MERCHANT_TAKEN");
955
+ ctx.ports.publishChanged(input.clientId);
956
+ return { kind: "selected", integration: await viewOf2(ctx, input.clientId, input.provider) };
957
+ }
958
+ __name(selectLinkedMerchant, "selectLinkedMerchant");
959
+
569
960
  // src/core/status-inform.ts
570
961
  async function informStatus(ctx, input) {
571
962
  const payload = { clientId: input.clientId, orderId: input.orderId, action: "status", step: input.step, claimKey: String(input.at.getTime()) };
@@ -736,7 +1127,7 @@ var NEVER_ASKED = {
736
1127
  resumedAt: null,
737
1128
  updatedAt: null
738
1129
  };
739
- function viewOf2(ctx, provider, connection, row) {
1130
+ function viewOf3(ctx, provider, connection, row) {
740
1131
  const availability = ctx.registry.get(provider)?.availability;
741
1132
  const recorded = row ? {
742
1133
  state: row.state,
@@ -757,18 +1148,18 @@ function viewOf2(ctx, provider, connection, row) {
757
1148
  ...recorded
758
1149
  };
759
1150
  }
760
- __name(viewOf2, "viewOf");
1151
+ __name(viewOf3, "viewOf");
761
1152
  async function availabilityState(ctx, clientId) {
762
1153
  const db = await ctx.ports.db();
763
1154
  const connections = await liveConnections(ctx, clientId);
764
1155
  const rows = db.marketplaceStorePause ? await db.marketplaceStorePause.findMany({ where: { clientId } }) : [];
765
1156
  const byProvider = new Map(rows.map((row) => [row.provider, row]));
766
1157
  const views = connections.map(
767
- (connection) => viewOf2(ctx, connection.provider, connection, byProvider.get(connection.provider))
1158
+ (connection) => viewOf3(ctx, connection.provider, connection, byProvider.get(connection.provider))
768
1159
  );
769
1160
  const live = new Set(connections.map((connection) => connection.provider));
770
1161
  for (const row of rows) {
771
- if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf2(ctx, row.provider, void 0, row));
1162
+ if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf3(ctx, row.provider, void 0, row));
772
1163
  }
773
1164
  return views;
774
1165
  }
@@ -868,68 +1259,6 @@ async function sweepAvailability(ctx, now) {
868
1259
  }
869
1260
  __name(sweepAvailability, "sweepAvailability");
870
1261
 
871
- // src/core/lifecycle.ts
872
- var ECHO_OF = {
873
- DISPATCHED: "DISPATCHED",
874
- CONCLUDED: "HANDED_OVER"
875
- };
876
- async function ignored(ctx, inboxId, reason) {
877
- await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
878
- return { kind: "ignored", reason };
879
- }
880
- __name(ignored, "ignored");
881
- function refusal(held) {
882
- if (held.status !== "ACCEPTED") return `the order is ${held.status}, not ACCEPTED`;
883
- if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") {
884
- return `a cancellation request is ${held.cancellationStatus}`;
885
- }
886
- return null;
887
- }
888
- __name(refusal, "refusal");
889
- function deliveredByOf(held) {
890
- return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
891
- }
892
- __name(deliveredByOf, "deliveredByOf");
893
- function following(ctx, event, settings) {
894
- const hook = ctx.ports.order.onLifecycle;
895
- if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;
896
- return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };
897
- }
898
- __name(following, "following");
899
- async function followLifecycle(ctx, inboxId, clientId, event, settings) {
900
- const follow = following(ctx, event, settings);
901
- if (!follow) return null;
902
- const { lifecycle, hook } = follow;
903
- const db = await ctx.ports.db();
904
- const table = statusTable(db);
905
- if (!table) return null;
906
- const held = await db.marketplaceAcceptance.findFirst({
907
- where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },
908
- select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true }
909
- });
910
- if (!held) {
911
- const reason2 = "lifecycle before its order";
912
- await deferInboxEvent(ctx, inboxId, reason2);
913
- return { kind: "ignored", reason: reason2 };
914
- }
915
- const stopped = refusal(held);
916
- if (stopped) return ignored(ctx, inboxId, stopped);
917
- const echo = ECHO_OF[lifecycle];
918
- const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === "STORE");
919
- if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);
920
- const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
921
- await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
922
- if (answer === "moved") {
923
- await settleInboxEvent(ctx, inboxId, "PROCESSED");
924
- ctx.ports.publishChanged(clientId);
925
- return { kind: "moved", orderId: held.orderId, lifecycle };
926
- }
927
- const reason = answer === "unchanged" ? `already at or past ${lifecycle}` : answer.reason;
928
- if (answer !== "unchanged") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);
929
- return ignored(ctx, inboxId, reason);
930
- }
931
- __name(followLifecycle, "followLifecycle");
932
-
933
1262
  // src/core/pipeline.ts
934
1263
  function normalizeEvent(ctx, provider, payload) {
935
1264
  return ctx.registry.get(provider)?.normalize(payload) ?? null;
@@ -984,7 +1313,7 @@ async function applyEvent(ctx, inboxId, clientId, event, settings, now) {
984
1313
  await awaitOrderBody(ctx, clientId, inboxId);
985
1314
  return { kind: "awaitingOrder" };
986
1315
  }
987
- const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
1316
+ const followed = await followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
988
1317
  if (followed) return followed;
989
1318
  return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
990
1319
  }
@@ -1114,8 +1443,17 @@ function createMarketplaceEngine(config) {
1114
1443
  ingest: /* @__PURE__ */ __name((input) => ingestMarketplaceOrder(ctx, input), "ingest"),
1115
1444
  deliver: /* @__PURE__ */ __name((input) => processDelivery(ctx, input), "deliver"),
1116
1445
  integrations: /* @__PURE__ */ __name((clientId, options) => listMarketplaceIntegrations(ctx, clientId, options), "integrations"),
1117
- saveIntegration: /* @__PURE__ */ __name(async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()), "saveIntegration"),
1446
+ saveIntegration: /* @__PURE__ */ __name((input) => guardMerchantClaim(
1447
+ ctx,
1448
+ { ...input, merchantId: input.externalMerchantId },
1449
+ async () => saveMarketplaceIntegration(ctx, input, await ports.db())
1450
+ ), "saveIntegration"),
1118
1451
  upsertIntegrations: /* @__PURE__ */ __name((input) => upsertIntegrations(ctx, input), "upsertIntegrations"),
1452
+ linkState: /* @__PURE__ */ __name((input) => linkState(ctx, input), "linkState"),
1453
+ startLink: /* @__PURE__ */ __name((input) => startLink(ctx, input), "startLink"),
1454
+ finishLink: /* @__PURE__ */ __name((input) => finishLink(ctx, input), "finishLink"),
1455
+ linkedMerchants: /* @__PURE__ */ __name((input) => linkedMerchants(ctx, input), "linkedMerchants"),
1456
+ selectLinkedMerchant: /* @__PURE__ */ __name((input) => selectLinkedMerchant(ctx, input), "selectLinkedMerchant"),
1119
1457
  menuLinks: /* @__PURE__ */ __name((input) => listMarketplaceMenuLinks(ctx, input), "menuLinks"),
1120
1458
  upsertMenuLinks: /* @__PURE__ */ __name((input) => upsertMenuLinks(ctx, input), "upsertMenuLinks"),
1121
1459
  setMenuLink: /* @__PURE__ */ __name(async ({ clientId, ...row }) => {
@@ -1135,6 +1473,7 @@ function createMarketplaceEngine(config) {
1135
1473
  runOutbound: /* @__PURE__ */ __name((payload, attempt) => runOutbound(ctx, payload, attempt), "runOutbound"),
1136
1474
  runFetchOrder: /* @__PURE__ */ __name((payload, attempt) => runFetchOrder(ctx, payload, attempt), "runFetchOrder"),
1137
1475
  informStatus: /* @__PURE__ */ __name((input) => informStatus(ctx, input), "informStatus"),
1476
+ ...courierEngine(ctx),
1138
1477
  // Null too when the host bound no catalogue port: nothing could be published.
1139
1478
  catalogueMode: /* @__PURE__ */ __name((provider) => ports.catalogue ? registry.get(provider)?.catalogue?.mode ?? null : null, "catalogueMode"),
1140
1479
  publish: /* @__PURE__ */ __name((input) => publishToCatalogue(ctx, input), "publish"),
@@ -1162,6 +1501,7 @@ export {
1162
1501
  MARKETPLACE_FETCH_ORDER_JOB,
1163
1502
  MARKETPLACE_OUTBOUND_JOB,
1164
1503
  MarketplaceAdapterRegistrationError,
1504
+ MarketplaceMerchantTakenError,
1165
1505
  OUTBOUND_GIVE_UP_MS,
1166
1506
  OUTBOUND_STALE_MS,
1167
1507
  OutboundRetryError,