@12-apps/marketplace 1.0.0 → 1.1.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 (39) hide show
  1. package/ADOPTING.md +35 -5
  2. package/README.md +2 -2
  3. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-BggtVFf9.d.ts} +6 -0
  4. package/dist/{chunk-OEKTWUQH.js → chunk-7BYVGNU5.js} +1 -1
  5. package/dist/chunk-7BYVGNU5.js.map +1 -0
  6. package/dist/{chunk-6OODIO3E.js → chunk-DVIRN42O.js} +325 -13
  7. package/dist/chunk-DVIRN42O.js.map +1 -0
  8. package/dist/{chunk-BEMTRJYM.js → chunk-NGNEL4HS.js} +4 -4
  9. package/dist/{chunk-BEMTRJYM.js.map → chunk-NGNEL4HS.js.map} +1 -1
  10. package/dist/{engine-DDE0mnTu.d.ts → engine-KrgZ4pA4.d.ts} +61 -17
  11. package/dist/hono/index.d.ts +2 -2
  12. package/dist/hono/index.js +2 -2
  13. package/dist/ifood/index.d.ts +4 -2
  14. package/dist/ifood/index.js +10 -2
  15. package/dist/ifood/index.js.map +1 -1
  16. package/dist/index.d.ts +3 -3
  17. package/dist/index.js +81 -169
  18. package/dist/index.js.map +1 -1
  19. package/dist/manifest/server.d.ts +2 -2
  20. package/dist/manifest/server.js +2 -2
  21. package/dist/server/index.d.ts +2 -2
  22. package/dist/server/index.js +2 -2
  23. package/package.json +1 -1
  24. package/prisma/marketplace.prisma +7 -0
  25. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  26. package/src/core/acceptance.ts +30 -14
  27. package/src/core/adapter.ts +6 -0
  28. package/src/core/cancellation-outcome.ts +92 -0
  29. package/src/core/cancellation.ts +46 -15
  30. package/src/core/decisions.ts +82 -19
  31. package/src/core/outbound-sweep.ts +87 -8
  32. package/src/core/outbound.ts +83 -7
  33. package/src/core/ports.ts +32 -0
  34. package/src/core/state.ts +6 -1
  35. package/src/ifood/index.ts +9 -0
  36. package/src/index.ts +1 -0
  37. package/src/server/jobs.ts +3 -2
  38. package/dist/chunk-6OODIO3E.js.map +0 -1
  39. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -1,6 +1,15 @@
1
1
  import type { MarketplaceAdapter, OutboundOrderRef, OutboundResult } from "./adapter";
2
+ import {
3
+ cancellationWindowMs,
4
+ confirmedToHost,
5
+ failedRequestData,
6
+ rejectConfirmed,
7
+ requestsFirst,
8
+ tellCancellationFailed,
9
+ } from "./cancellation-outcome";
2
10
  import { readOutboundConnection, type OutboundConnection } from "./integration";
3
11
  import type { OutboundJobPayload } from "./outbound-queue";
12
+ import { failAsTimeout } from "./outbound-sweep";
4
13
  import type { EngineContext } from "./ports";
5
14
  import { resolveReason } from "./registry";
6
15
 
@@ -56,6 +65,7 @@ interface OutboundRow {
56
65
  cancellationStatus: string | null;
57
66
  cancellationReasonCode: string | null;
58
67
  cancellationOffendingSkus: unknown;
68
+ cancellationRequestedAt: Date | null;
59
69
  preparationMinutes: number | null;
60
70
  createdAt: Date;
61
71
  }
@@ -71,6 +81,7 @@ const ROW_SELECT = {
71
81
  cancellationStatus: true,
72
82
  cancellationReasonCode: true,
73
83
  cancellationOffendingSkus: true,
84
+ cancellationRequestedAt: true,
74
85
  preparationMinutes: true,
75
86
  createdAt: true,
76
87
  } as const;
@@ -87,6 +98,11 @@ function refOf(row: OutboundRow): OutboundOrderRef {
87
98
  /** Why a confirm is not owed, or null when it is. */
88
99
  function confirmSkip(row: OutboundRow, adapter: MarketplaceAdapter): string | null {
89
100
  if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
101
+ // A request to cancel stands (FUT-4758: the status stays ACCEPTED while it
102
+ // waits): confirming now would tell the marketplace the opposite.
103
+ if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
104
+ return `a cancellation request is ${row.cancellationStatus}`;
105
+ }
90
106
  if (row.confirmedAt || row.confirmFailedAt) return "the confirm is already stamped";
91
107
  if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
92
108
  return null;
@@ -106,17 +122,59 @@ async function stampConfirm(
106
122
  });
107
123
  }
108
124
 
109
- /** The cancellation stamp, predicated on the request still being PENDING. */
125
+ /**
126
+ * The cancellation stamp, predicated on the request still being PENDING, and
127
+ * the host told how it ended when this run is what ended it (FUT-4758): a
128
+ * marketplace that answers in the response CONFIRMS here, and a refusal FAILS
129
+ * here. REQUESTED tells nobody: the answer is still to come, by event.
130
+ */
110
131
  async function stampCancellation(
111
132
  ctx: EngineContext,
112
133
  row: OutboundRow,
113
134
  status: "REQUESTED" | "CONFIRMED" | "FAILED",
135
+ clientId: string,
114
136
  ): Promise<void> {
137
+ if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
115
138
  const db = await ctx.ports.db();
116
- await db.marketplaceAcceptance.updateMany({
139
+ const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
140
+ const moved = await db.marketplaceAcceptance.updateMany({
117
141
  where: { orderId: row.orderId, cancellationStatus: "PENDING" },
118
- data: { cancellationStatus: status },
142
+ data,
119
143
  });
144
+ if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
145
+ }
146
+
147
+ /**
148
+ * A marketplace that confirms in its answer: the same stamps as its
149
+ * CANCELLED event (`cancelAcceptance`) — CONFIRMED and REJECTED in one
150
+ * transaction — then the host's `onCancellationConfirmed`, or
151
+ * `onRefused(…, "CANCELLED")` when it binds none. A host failure is logged:
152
+ * the stamps have committed.
153
+ */
154
+ async function stampConfirmedCancellation(ctx: EngineContext, row: OutboundRow, clientId: string): Promise<void> {
155
+ const now = ctx.ports.clock.now();
156
+ const moved = await ctx.ports.transaction(async (tx) => {
157
+ // From FAILED too: the sweep may have timed the request out while this
158
+ // call was in flight, and a marketplace that answers in the response sends
159
+ // no event — its "cancelled" is the only word that it did (the event path's
160
+ // own rule: a confirmation after a TIMEOUT still confirms).
161
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
162
+ where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "FAILED"] } },
163
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null },
164
+ });
165
+ if (confirmed.count === 0) return false;
166
+ await rejectConfirmed(tx, row.orderId, now);
167
+ return true;
168
+ });
169
+ if (!moved) return;
170
+ try {
171
+ await confirmedToHost(ctx, clientId, row.orderId);
172
+ } catch (error) {
173
+ ctx.ports.logger.error(
174
+ `marketplace.outbound: order ${row.orderId} was cancelled on the store's request but the host's half failed: ` +
175
+ (error instanceof Error ? error.message : String(error)),
176
+ );
177
+ }
120
178
  }
121
179
 
122
180
  /** The connection, or the reason it cannot be used (a refusal: no retry fixes it). */
@@ -188,6 +246,15 @@ async function runConfirm(
188
246
  );
189
247
  }
190
248
 
249
+ /** Whether a request is older than its marketplace's answer window, so it must not be sent any more. */
250
+ function pastWindow(ctx: EngineContext, row: OutboundRow, adapter: MarketplaceAdapter): boolean {
251
+ // A 1.0.0 host (no `onCancellationConfirmed`) has no window: it retries, as before.
252
+ if (!requestsFirst(ctx)) return false;
253
+ const window = cancellationWindowMs(ctx, adapter);
254
+ if (window === null || row.cancellationRequestedAt === null) return false;
255
+ return ctx.ports.clock.now().getTime() - row.cancellationRequestedAt.getTime() > window;
256
+ }
257
+
191
258
  /** The offending SKUs stored with the request. */
192
259
  function skusOf(row: OutboundRow): string[] {
193
260
  return Array.isArray(row.cancellationOffendingSkus) ? row.cancellationOffendingSkus.map(String) : [];
@@ -203,6 +270,12 @@ async function runCancellation(
203
270
  if (row.cancellationStatus !== "PENDING") {
204
271
  return { kind: "skipped", reason: `the request is ${row.cancellationStatus ?? "absent"}, not PENDING` };
205
272
  }
273
+ if (pastWindow(ctx, row, adapter)) {
274
+ // A retry that comes after the window never delivers (FUT-4758): the host
275
+ // was, or is now, told TIMEOUT, and the store cancels in the marketplace's app.
276
+ await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
277
+ return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
278
+ }
206
279
  const reason = resolveReason(adapter, row.cancellationReasonCode);
207
280
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
208
281
  let result: OutboundResult;
@@ -222,8 +295,8 @@ async function runCancellation(
222
295
  row,
223
296
  result,
224
297
  attempt,
225
- () => stampCancellation(ctx, row, taken),
226
- () => stampCancellation(ctx, row, "FAILED"),
298
+ () => stampCancellation(ctx, row, taken, payload.clientId),
299
+ () => stampCancellation(ctx, row, "FAILED", payload.clientId),
227
300
  );
228
301
  }
229
302
 
@@ -235,17 +308,20 @@ async function runCancellation(
235
308
  async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
236
309
  const reason = error instanceof Error ? error.message : String(error);
237
310
  const db = await ctx.ports.db();
238
- await (payload.action === "confirm"
311
+ const moved = await (payload.action === "confirm"
239
312
  ? db.marketplaceAcceptance.updateMany({
240
313
  where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },
241
314
  data: { confirmFailedAt: ctx.ports.clock.now() },
242
315
  })
243
316
  : db.marketplaceAcceptance.updateMany({
244
317
  where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
245
- data: { cancellationStatus: "FAILED" },
318
+ data: failedRequestData("REFUSED"),
246
319
  }));
247
320
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
248
321
  ctx.ports.publishChanged(payload.clientId);
322
+ if (payload.action === "requestCancellation" && moved.count > 0) {
323
+ await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
324
+ }
249
325
  return { kind: "failed", action: payload.action, reason };
250
326
  }
251
327
 
package/src/core/ports.ts CHANGED
@@ -116,6 +116,13 @@ export type MarketplaceAdmissionResult =
116
116
  /** Why the engine tells the host to refuse an order. Vocabulary, not copy. */
117
117
  export type MarketplaceRefusal = "REJECTED" | "EXPIRED" | "CANCELLED";
118
118
 
119
+ /**
120
+ * Why the store's own cancellation request FAILED: REFUSED (the marketplace
121
+ * said no, or every attempt failed) or TIMEOUT (no answer inside the
122
+ * marketplace's cancellation window). Vocabulary, not copy.
123
+ */
124
+ export type CancellationFailureReason = "REFUSED" | "TIMEOUT";
125
+
119
126
  /**
120
127
  * The host's domain, as five questions the engine asks and never answers.
121
128
  *
@@ -151,6 +158,23 @@ export interface MarketplaceOrderPort {
151
158
  onAccepted(clientId: string, orderId: string): Promise<void>;
152
159
  /** The store said no, the marketplace cancelled, or the clock lapsed. */
153
160
  onRefused(clientId: string, orderId: string, reason: MarketplaceRefusal): Promise<void>;
161
+ /**
162
+ * OPTIONAL. The marketplace CONFIRMED the store's own cancellation request
163
+ * (the job's answer, or the marketplace's event). A host that requests first
164
+ * and cancels on confirm runs its cancel here. When present it is called
165
+ * INSTEAD of `onRefused(…, "CANCELLED")` for a cancellation the store asked
166
+ * for; a cancellation the marketplace made on its own still reaches
167
+ * `onRefused`. Absent (a 1.0.0 host): `onRefused(…, "CANCELLED")` as before.
168
+ */
169
+ onCancellationConfirmed?(clientId: string, orderId: string): Promise<void>;
170
+ /**
171
+ * OPTIONAL. The store's own cancellation request FAILED: refused (the job's
172
+ * answer, the marketplace's event, or the last attempt) or timed out (the
173
+ * outbound sweep, past the marketplace's window). Called once per request,
174
+ * by the call that moved the row to FAILED. The pedido is still the
175
+ * marketplace's: a person finishes it there, through the adapter's app link.
176
+ */
177
+ onCancellationFailed?(clientId: string, orderId: string, reason: CancellationFailureReason): Promise<void>;
154
178
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
155
179
  summarize(
156
180
  clientId: string,
@@ -238,6 +262,14 @@ export interface MarketplacePorts {
238
262
  * awaits it, and a dead bus costs latency, never a transition.
239
263
  */
240
264
  publishChanged: (clientId: string) => void;
265
+ /**
266
+ * OPTIONAL. How long a store's cancellation request may wait for the
267
+ * marketplace's answer before the outbound sweep fails it as TIMEOUT, in
268
+ * milliseconds, for every adapter. Absent: each adapter's own
269
+ * `capabilities.cancellationAnswerWindowMs`; an adapter that states none is
270
+ * only given up on after `OUTBOUND_GIVE_UP_MS`.
271
+ */
272
+ cancellationWindowMs?: number;
241
273
  /** The acceptance window a connection gets when it does not state its own. */
242
274
  defaultAckSlaSeconds: number;
243
275
  /** How many stored deliveries one reconciliation pass re-runs. */
package/src/core/state.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
2
- import type { EngineContext } from "./ports";
2
+ import type { CancellationFailureReason, EngineContext } from "./ports";
3
3
  import type { MarketplaceProvider } from "./types";
4
4
 
5
5
  /**
@@ -17,6 +17,8 @@ export interface MarketplaceOrderState {
17
17
  confirmFailedAt: Date | null;
18
18
  cancellation: CancellationStatus | null;
19
19
  cancellationReasonCode: string | null;
20
+ /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */
21
+ cancellationFailure: CancellationFailureReason | null;
20
22
  /** The adapter's app link, or null when no adapter is registered for it. */
21
23
  appUrl: string | null;
22
24
  }
@@ -31,6 +33,7 @@ interface StateRow {
31
33
  confirmFailedAt: Date | null;
32
34
  cancellationStatus: string | null;
33
35
  cancellationReasonCode: string | null;
36
+ cancellationFailureReason: string | null;
34
37
  }
35
38
 
36
39
  /** The state of each of these orders that is a marketplace order, keyed by id. */
@@ -53,6 +56,7 @@ export async function readOrderStates(
53
56
  confirmFailedAt: true,
54
57
  cancellationStatus: true,
55
58
  cancellationReasonCode: true,
59
+ cancellationFailureReason: true,
56
60
  },
57
61
  })) as StateRow[];
58
62
  return new Map(
@@ -68,6 +72,7 @@ export async function readOrderStates(
68
72
  confirmFailedAt: row.confirmFailedAt,
69
73
  cancellation: row.cancellationStatus as CancellationStatus | null,
70
74
  cancellationReasonCode: row.cancellationReasonCode,
75
+ cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,
71
76
  appUrl: adapter ? adapter.appLink(row) : null,
72
77
  };
73
78
  return [row.orderId, state];
@@ -25,6 +25,9 @@ export const IFOOD_PROVIDER = "IFOOD";
25
25
  /** The one reason that means "an item is unavailable". */
26
26
  const ITEM_UNAVAILABLE: IfoodReasonCode = "503";
27
27
 
28
+ /** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */
29
+ export const IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
30
+
28
31
  export interface IfoodAdapterConfig {
29
32
  /** The words the adapter needs: reason labels and the missing-number text. Required. */
30
33
  copy: IfoodAdapterCopy;
@@ -48,6 +51,12 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
48
51
  asyncCancellationOutcome: true,
49
52
  perOrderAppLink: false,
50
53
  confirmTakesPreparationTime: false,
54
+ // How long iFood takes, at most, to answer a cancellation request: its
55
+ // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off
56
+ // iFood's documentation, which names no answer deadline: iFood answers a
57
+ // request in seconds when it answers at all, so 5 minutes is generous.
58
+ // A host overrides it with the engine's `cancellationWindowMs`.
59
+ cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
51
60
  },
52
61
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
53
62
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
package/src/index.ts CHANGED
@@ -47,6 +47,7 @@ export type {
47
47
  MarketplaceAdmission,
48
48
  MarketplaceAdmissionRequest,
49
49
  MarketplaceAdmissionResult,
50
+ CancellationFailureReason,
50
51
  MarketplaceAuditEntry,
51
52
  MarketplaceAuditPort,
52
53
  MarketplaceClockPort,
@@ -112,9 +112,10 @@ const outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
112
112
  lease: { ttlMs: SWEEP_LEASE_MS },
113
113
  handle: async (_payload, deps, context) => {
114
114
  const result = await deps.engine.sweepOutbound();
115
- if (result.requeued === 0 && result.givenUp === 0) return;
115
+ if (result.requeued === 0 && result.givenUp === 0 && result.timedOut === 0) return;
116
116
  context.logger.info(
117
- `marketplace.outbound-sweep: re-queued ${result.requeued} call(s), gave up on ${result.givenUp} request(s).`,
117
+ `marketplace.outbound-sweep: re-queued ${result.requeued} call(s), timed out ${result.timedOut} ` +
118
+ `cancellation request(s), gave up on ${result.givenUp}.`,
118
119
  );
119
120
  },
120
121
  };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/types.ts","../src/core/registry.ts","../src/core/integration.ts","../src/core/outbound.ts"],"sourcesContent":["/**\n * The canonical shape every marketplace adapter normalizes INTO.\n *\n * This type is the seam. The engine below it knows no marketplace by name: a\n * marketplace is an adapter registered with the engine (`./adapter`), and the\n * provider id is whatever that adapter says it is. A second marketplace is a\n * second adapter, never a second pipeline, a second acceptance clock or a\n * second idea of what an order is.\n *\n * Deliberately POORER than any marketplace's own payload. Everything a store\n * operates on is here; everything else stays in the inbox row's raw `payload`,\n * which is where a normalization bug is reconstructed from.\n */\n\n/**\n * A marketplace's id, as its adapter declares it (`\"IFOOD\"`). Uppercase\n * letters, digits and underscores; the migration's CHECK holds the same shape.\n * A string rather than a closed union, because the set of marketplaces is the\n * set of registered adapters, and a union would make a new one a code change\n * in the engine.\n */\nexport type MarketplaceProvider = string;\n\n/** The shape a provider id must have. Shared by the registry and the CHECK. */\nexport const PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;\n\n/** One line of an incoming order, before it is resolved against the catalog. */\nexport interface NormalizedOrderLine {\n /** The marketplace's own SKU — the key the SKU map is matched on. */\n externalSku: string;\n /** What the marketplace called it. Snapshotted, and the fallback line text. */\n name: string;\n quantity: number;\n /**\n * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A\n * marketplace's menu carries its own prices, and the buyer's receipt is the\n * marketplace's one: re-pricing from the host's catalog would produce a\n * total nobody was charged.\n */\n unitPriceCents: number;\n /** The buyer's note on this line, when they left one. */\n note: string | null;\n}\n\n/** The buyer, as much of them as the marketplace discloses. */\nexport interface NormalizedBuyer {\n /** The marketplace's own stable id for this customer, when it gives one. */\n externalId: string | null;\n name: string | null;\n phone: string | null;\n}\n\n/** Where a delivery goes, as much of it as the marketplace states. */\nexport interface NormalizedAddress {\n street: string;\n number: string;\n neighborhood: string;\n complement: string | null;\n /** The sentence that finds the door. */\n reference: string | null;\n postalCode: string | null;\n city: string | null;\n state: string | null;\n}\n\n/** How the order reaches the buyer: brought to the door, or collected. */\nexport type MarketplaceOrderType = \"DELIVERY\" | \"TAKEOUT\";\n\n/** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */\nexport type MarketplaceDeliveredBy = \"MERCHANT\" | \"MARKETPLACE\";\n\n/** An incoming marketplace order, normalized. */\nexport interface NormalizedMarketplaceOrder {\n provider: MarketplaceProvider;\n /** The marketplace's order id — THE idempotency key for the whole pipeline. */\n externalOrderId: string;\n /** The short code the courier and the buyer say out loud. */\n externalDisplayId: string | null;\n buyer: NormalizedBuyer;\n lines: NormalizedOrderLine[];\n /**\n * What the buyer paid, gross. NOT derived from the lines when the\n * marketplace states it: its total carries fees, promotions and rounding the\n * line sum does not, and the number that must match the receipt is this one.\n */\n totalCents: number;\n /** The marketplace's cut, when it states one. NULL is \"did not say\", not 0. */\n commissionCents: number | null;\n /** The marketplace's own promise to the buyer. */\n deliveryDueAt: Date | null;\n /** When the marketplace says the order was placed. */\n placedAt: Date;\n /** Null when the payload does not say. */\n orderType?: MarketplaceOrderType | null;\n /** Null on a take-out and when unstated. */\n deliveredBy?: MarketplaceDeliveredBy | null;\n /** Null on a take-out and when unstated. */\n deliveryAddress?: NormalizedAddress | null;\n}\n\n/**\n * What an event says about the STORE's own cancellation request: `CONFIRMED`\n * when the marketplace cancelled the order (a pending request is answered),\n * `FAILED` when it refused the request.\n */\nexport type CancellationOutcome = \"CONFIRMED\" | \"FAILED\";\n\n/** What an adapter makes of one inbound delivery. */\nexport interface NormalizedEvent {\n provider: MarketplaceProvider;\n /** The delivery's own id — the inbox dedup key, paired with the provider. */\n eventId: string;\n /** The provider's event type verbatim, kept for the inbox row and the log. */\n eventType: string;\n /** The merchant this event names, used to attribute it to a tenant. */\n externalMerchantId: string | null;\n externalOrderId: string | null;\n /**\n * The order this event carries, or null when the event is one the engine\n * understands and does not ingest. A null here is an IGNORED inbox row (or a\n * cancellation, below), never a failure.\n */\n order: NormalizedMarketplaceOrder | null;\n /** The marketplace has CANCELLED the order. */\n cancelled: boolean;\n /**\n * The answer to the store's own cancellation request, when this event is\n * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.\n */\n cancellationOutcome?: CancellationOutcome | null;\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"./adapter\";\nimport { PROVIDER_ID_PATTERN, type MarketplaceProvider } from \"./types\";\n\n/**\n * The adapter registry: the ONE place a provider id becomes a marketplace.\n *\n * Every dispatch in the engine — normalize, signature, outbound, reasons, the\n * app link — asks this registry, so no module below it holds a branch on a\n * provider id. Registering an adapter is the whole cost of a marketplace.\n */\nexport interface AdapterRegistry {\n /** The adapter for this provider, or null when none is registered. */\n get(provider: string): MarketplaceAdapter | null;\n /** Whether a provider id names a registered adapter (URL segments arrive as text). */\n has(provider: string): provider is MarketplaceProvider;\n /** Every registered provider, in registration order. */\n providers(): readonly MarketplaceProvider[];\n}\n\n/** Thrown at mount when the adapter list cannot be a registry. */\nexport class MarketplaceAdapterRegistrationError extends Error {\n constructor(message: string) {\n super(`@12-apps/marketplace: ${message}`);\n this.name = \"MarketplaceAdapterRegistrationError\";\n }\n}\n\nfunction assertReasons(adapter: MarketplaceAdapter): void {\n const codes = new Set<string>();\n for (const reason of adapter.cancellationReasons()) {\n if (reason.code.trim() === \"\") {\n throw new MarketplaceAdapterRegistrationError(`${adapter.provider} declares a reason with a blank code.`);\n }\n if (codes.has(reason.code)) {\n throw new MarketplaceAdapterRegistrationError(\n `${adapter.provider} declares the reason code \"${reason.code}\" twice.`,\n );\n }\n codes.add(reason.code);\n }\n if (adapter.capabilities.apiCancel && codes.size === 0) {\n throw new MarketplaceAdapterRegistrationError(\n `${adapter.provider} can cancel through its API but declares no reason to cancel with.`,\n );\n }\n}\n\n/**\n * Build the registry, refusing what would only fail later: an empty list, a\n * malformed id, a duplicate provider, a reason list that cannot be validated\n * against.\n */\nexport function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]): AdapterRegistry {\n if (adapters.length === 0) {\n throw new MarketplaceAdapterRegistrationError(\"an engine needs at least one adapter.\");\n }\n const byProvider = new Map<string, MarketplaceAdapter>();\n for (const adapter of adapters) {\n if (!PROVIDER_ID_PATTERN.test(adapter.provider)) {\n throw new MarketplaceAdapterRegistrationError(\n `provider id \"${adapter.provider}\" must be uppercase letters, digits and underscores.`,\n );\n }\n if (byProvider.has(adapter.provider)) {\n throw new MarketplaceAdapterRegistrationError(`two adapters claim \"${adapter.provider}\".`);\n }\n assertReasons(adapter);\n byProvider.set(adapter.provider, adapter);\n }\n const providers = [...byProvider.keys()];\n return {\n get: (provider) => byProvider.get(provider) ?? null,\n has: (provider): provider is MarketplaceProvider => byProvider.has(provider),\n providers: () => providers,\n };\n}\n\n/**\n * The reason a refusal carries: the one named by `code`, or — when the store\n * named none — the adapter's first. `null` when the code is not one of the\n * adapter's, which a caller answers as a refusal of the whole request.\n */\nexport function resolveReason(\n adapter: MarketplaceAdapter,\n code: string | null | undefined,\n): CancellationReason | null {\n const reasons = adapter.cancellationReasons();\n if (code === null || code === undefined) return reasons[0] ?? null;\n return reasons.find((reason) => reason.code === code) ?? null;\n}\n\n/**\n * The reason a host should preselect: the adapter's \"item unavailable\" reason\n * when the order cannot be covered, else its first. The SHORTAGE is the\n * host's to judge (stock is the host's), so it arrives as a boolean.\n */\nexport function suggestReason(\n adapter: MarketplaceAdapter,\n input: { itemUnavailable: boolean },\n): CancellationReason | null {\n const reasons = adapter.cancellationReasons();\n if (input.itemUnavailable) {\n const unavailable = reasons.find((reason) => reason.itemUnavailable);\n if (unavailable) return unavailable;\n }\n return reasons[0] ?? null;\n}\n","import type { MarketplaceCredentials } from \"./adapter\";\nimport type { EngineContext, MarketplaceDb } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The (tenant, marketplace) connection repository .\n *\n * Nothing here ever returns the credential blob. The read every surface uses\n * answers whether a connection EXISTS and how it is configured, never what it\n * is configured with. The one opening read is {@link resolveIngestionTarget},\n * which the webhook path needs and nobody else calls.\n */\n\n/** A connection as every read surface sees it: no secrets, ever. */\nexport interface MarketplaceIntegrationView {\n provider: MarketplaceProvider;\n enabled: boolean;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n status: \"UNVERIFIED\" | \"VERIFIED\" | \"FAILED\";\n externalMerchantId: string | null;\n autoAccept: boolean;\n ackSlaSeconds: number;\n /**\n * Whether the store has a usable connection — i.e. whether secrets are on\n * file at all. Named for the STATE rather than for the blob behind it: the\n * only fact anyone needs about a stored secret is that one exists, and it is\n * the only one that can be answered without disclosing it.\n */\n connected: boolean;\n lastEventAt: Date | null;\n lastVerifiedAt: Date | null;\n /** Archived connections ingest nothing; null while live. */\n archivedAt: Date | null;\n}\n\ninterface IntegrationRow {\n provider: string;\n enabled: boolean;\n environment: string;\n status: string;\n externalMerchantId: string | null;\n autoAccept: boolean;\n ackSlaSeconds: number;\n credentials: string;\n lastEventAt: Date | null;\n lastVerifiedAt: Date | null;\n archivedAt: Date | null;\n}\n\nconst VIEW_SELECT = {\n provider: true,\n enabled: true,\n environment: true,\n status: true,\n externalMerchantId: true,\n autoAccept: true,\n ackSlaSeconds: true,\n credentials: true,\n lastEventAt: true,\n lastVerifiedAt: true,\n archivedAt: true,\n} as const;\n\nfunction toView(row: IntegrationRow): MarketplaceIntegrationView {\n return {\n provider: row.provider as MarketplaceProvider,\n enabled: row.enabled,\n environment: row.environment as MarketplaceIntegrationView[\"environment\"],\n status: row.status as MarketplaceIntegrationView[\"status\"],\n externalMerchantId: row.externalMerchantId,\n autoAccept: row.autoAccept,\n ackSlaSeconds: row.ackSlaSeconds,\n connected: row.credentials !== \"\",\n lastEventAt: row.lastEventAt,\n lastVerifiedAt: row.lastVerifiedAt,\n archivedAt: row.archivedAt ?? null,\n };\n}\n\n/**\n * This store's marketplace connections, secrets withheld: the live ones, or\n * with `includeArchived` the archived too; `providers` narrows to those ids.\n */\nexport async function listMarketplaceIntegrations(\n ctx: EngineContext,\n clientId: string,\n options: { providers?: readonly string[]; includeArchived?: boolean } = {},\n): Promise<MarketplaceIntegrationView[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceIntegration.findMany({\n where: {\n clientId,\n ...(options.providers ? { provider: { in: [...options.providers] } } : {}),\n ...(options.includeArchived ? {} : { archivedAt: null }),\n },\n select: VIEW_SELECT,\n orderBy: { provider: \"asc\" },\n })) as IntegrationRow[];\n return rows.map(toView);\n}\n\n/** What a save may change. Absent keys leave their column alone. */\nexport interface SaveMarketplaceIntegrationInput {\n clientId: string;\n provider: MarketplaceProvider;\n enabled?: boolean;\n environment?: \"SANDBOX\" | \"PRODUCTION\";\n externalMerchantId?: string | null;\n autoAccept?: boolean;\n ackSlaSeconds?: number;\n /**\n * The secrets, when the operator re-entered them. Absent means \"leave the\n * stored blob alone\", which is what makes it possible to flip `autoAccept`\n * without retyping a client secret nobody can read back off the screen.\n */\n credentials?: MarketplaceCredentials;\n}\n\n/**\n * Create or update a store's connection to one marketplace.\n *\n * An upsert on `(clientId, provider)` — the row IS the connection, so there is\n * no separate \"connect\" and \"edit\". A CREATE with no credentials stores the\n * empty blob rather than refusing: a merchant mid-homologation has a merchant\n * id and no secrets for weeks, and that half-connected state is exactly what\n * the screen exists to show them.\n *\n * Re-entering credentials resets `status` to UNVERIFIED. The stored status is a\n * claim about a specific secret; carrying VERIFIED across a credential change\n * would assert that a probe which never ran had passed.\n */\nexport async function saveMarketplaceIntegration(\n ctx: EngineContext,\n input: SaveMarketplaceIntegrationInput,\n db: MarketplaceDb,\n): Promise<MarketplaceIntegrationView> {\n const sealed = input.credentials\n ? ctx.ports.secrets.seal(JSON.stringify(input.credentials))\n : undefined;\n const mutable = {\n ...(input.enabled === undefined ? {} : { enabled: input.enabled }),\n ...(input.environment === undefined ? {} : { environment: input.environment }),\n ...(input.externalMerchantId === undefined\n ? {}\n : { externalMerchantId: input.externalMerchantId }),\n ...(input.autoAccept === undefined ? {} : { autoAccept: input.autoAccept }),\n ...(input.ackSlaSeconds === undefined ? {} : { ackSlaSeconds: input.ackSlaSeconds }),\n ...(sealed === undefined ? {} : { credentials: sealed, status: \"UNVERIFIED\" }),\n };\n const row = (await db.marketplaceIntegration.upsert({\n where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n credentials: sealed ?? \"\",\n ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,\n ...mutable,\n },\n update: mutable,\n select: VIEW_SELECT,\n })) as IntegrationRow;\n return toView(row);\n}\n\n/** What the ingestion path needs to know about a store's connection. */\nexport interface IngestionTarget {\n enabled: boolean;\n autoAccept: boolean;\n ackSlaSeconds: number;\n webhookSecret: string | null;\n}\n\n/**\n * The connection a delivery belongs to, plus the two things the webhook path\n * needs from it: the shared secret to verify against, and whether the store has\n * the connection ON.\n *\n * A DISABLED connection still resolves. The caller decides what to do with that\n * (it stores the event and does not ingest it), and it must be able to tell\n * \"this store turned the channel off\" apart from \"this store has no channel\",\n * because only one of them is a misconfiguration worth shouting about.\n */\nexport async function resolveIngestionTarget(\n ctx: EngineContext,\n clientId: string,\n provider: MarketplaceProvider,\n): Promise<IngestionTarget | null> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceIntegration.findUnique({\n where: { clientId_provider: { clientId, provider } },\n select: { enabled: true, autoAccept: true, ackSlaSeconds: true, credentials: true, archivedAt: true },\n })) as {\n enabled: boolean;\n autoAccept: boolean;\n ackSlaSeconds: number;\n credentials: string;\n archivedAt: Date | null;\n } | null;\n // An archived connection is no connection: its deliveries are refused.\n if (!row || row.archivedAt) return null;\n return {\n enabled: row.enabled,\n autoAccept: row.autoAccept,\n ackSlaSeconds: row.ackSlaSeconds,\n // An unopenable blob must not read as \"no secret configured\" — that would\n // turn a key-rotation problem into an endpoint that accepts unsigned\n // deliveries. The secrets port throws instead, and the caller answers 401.\n webhookSecret:\n row.credentials === \"\" ? null : openCredentials(ctx, row.credentials).webhookSecret,\n };\n}\n\n/**\n * Open a stored credential set.\n *\n * Throws on a ciphertext that will not open, by way of the host's secrets port\n * — which is the right outcome and not a hypothetical: a row written under a\n * key that has since rotated cannot be used to talk to anyone, and treating it\n * as \"no credentials\" would silently turn a KEY problem into a connection that\n * looks merely unconfigured.\n */\nfunction openCredentials(\n ctx: EngineContext,\n sealed: string,\n): MarketplaceCredentials {\n const parsed: unknown = JSON.parse(ctx.ports.secrets.open(sealed));\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(\"Stored marketplace credentials are not an object.\");\n }\n const record = parsed as Partial<MarketplaceCredentials>;\n return {\n clientId: String(record.clientId ?? \"\"),\n clientSecret: String(record.clientSecret ?? \"\"),\n webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null,\n };\n}\n\n/**\n * Which tenant a delivery belongs to, resolved from the merchant id the\n * marketplace names.\n *\n * Matched against the column OUTSIDE the ciphertext, which is the whole reason\n * `externalMerchantId` lives there: attributing a delivery must not require\n * decrypting every store's secrets to find the match.\n */\nexport async function resolveTenantByMerchant(\n ctx: EngineContext,\n provider: MarketplaceProvider,\n externalMerchantId: string,\n): Promise<string | null> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceIntegration.findMany({\n where: { provider, externalMerchantId, archivedAt: null },\n select: { clientId: true },\n take: 1,\n })) as { clientId: string }[];\n return rows[0]?.clientId ?? null;\n}\n\n/** Stamp the connection's liveness marker. Best-effort; never blocks ingestion. */\nexport async function markMarketplaceEventSeen(\n db: MarketplaceDb,\n clientId: string,\n provider: MarketplaceProvider,\n at: Date,\n): Promise<void> {\n await db.marketplaceIntegration.updateMany({\n where: { clientId, provider },\n data: { lastEventAt: at },\n });\n}\n\n/** What the outbound engine needs to talk to a marketplace for one store. */\nexport interface OutboundConnection {\n environment: \"SANDBOX\" | \"PRODUCTION\";\n credentials: MarketplaceCredentials;\n}\n\n/**\n * The opened connection for one (tenant, marketplace), or null when there is\n * no connection or no credentials on file. Throws when the stored blob will\n * not open — the outbound engine records that as a failure rather than\n * mistaking a key problem for an unconfigured store.\n */\nexport async function readOutboundConnection(\n ctx: EngineContext,\n clientId: string,\n provider: MarketplaceProvider,\n): Promise<OutboundConnection | null> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceIntegration.findUnique({\n where: { clientId_provider: { clientId, provider } },\n select: { environment: true, credentials: true },\n })) as { environment: string; credentials: string } | null;\n if (!row || row.credentials === \"\") return null;\n return {\n environment: row.environment === \"PRODUCTION\" ? \"PRODUCTION\" : \"SANDBOX\",\n credentials: openCredentials(ctx, row.credentials),\n };\n}\n","import type { MarketplaceAdapter, OutboundOrderRef, OutboundResult } from \"./adapter\";\nimport { readOutboundConnection, type OutboundConnection } from \"./integration\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport type { EngineContext } from \"./ports\";\nimport { resolveReason } from \"./registry\";\n\n/**\n * The outbound engine: one queued call to a marketplace, start to finish.\n *\n * The job (`marketplace.outbound`) is the only caller. It re-reads the row,\n * decides whether a call is still owed, makes it through the adapter with the\n * host's HTTP client, and stamps the outcome. The rule for an answer is the\n * same for every marketplace:\n *\n * - **2xx** — done: `confirmed_at`, or REQUESTED (CONFIRMED for a marketplace\n * that answers a cancellation in the response rather than by event);\n * - **4xx** — refused, final, never retried: `confirm_failed_at`, or FAILED;\n * - **anything else** (5xx, timeout, network) — retried by the queue: this\n * THROWS {@link OutboundRetryError}, until the last attempt, which stamps the\n * failure and returns.\n *\n * Idempotent by the ROW, never by the queue's dedupe alone: a stamped confirm\n * (`confirmed_at` or `confirm_failed_at`) is never sent again, and a request\n * is only sent from PENDING. A confirm is never sent for an order that is no\n * longer ACCEPTED here.\n */\n\n/** What one run did. */\nexport type OutboundOutcome =\n | { kind: \"skipped\"; reason: string }\n | { kind: \"done\"; action: OutboundJobPayload[\"action\"] }\n | { kind: \"failed\"; action: OutboundJobPayload[\"action\"]; reason: string };\n\n/** Thrown so the queue retries. Its message is what the job log reads. */\nexport class OutboundRetryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OutboundRetryError\";\n }\n}\n\n/** Which attempt this is, as the job runner says. */\nexport interface OutboundAttempt {\n attempt: number;\n maxAttempts: number;\n}\n\ninterface OutboundRow {\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: string;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellationStatus: string | null;\n cancellationReasonCode: string | null;\n cancellationOffendingSkus: unknown;\n preparationMinutes: number | null;\n createdAt: Date;\n}\n\nconst ROW_SELECT = {\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n status: true,\n confirmedAt: true,\n confirmFailedAt: true,\n cancellationStatus: true,\n cancellationReasonCode: true,\n cancellationOffendingSkus: true,\n preparationMinutes: true,\n createdAt: true,\n} as const;\n\nfunction refOf(row: OutboundRow): OutboundOrderRef {\n return {\n externalOrderId: row.externalOrderId,\n externalDisplayId: row.externalDisplayId,\n hostOrderCode: row.orderId,\n placedAt: row.createdAt,\n };\n}\n\n/** Why a confirm is not owed, or null when it is. */\nfunction confirmSkip(row: OutboundRow, adapter: MarketplaceAdapter): string | null {\n if (row.status !== \"ACCEPTED\") return `the order is ${row.status}, not ACCEPTED`;\n if (row.confirmedAt || row.confirmFailedAt) return \"the confirm is already stamped\";\n if (!adapter.capabilities.apiConfirm) return \"the marketplace has no confirm API\";\n return null;\n}\n\n/** The stamps one confirm outcome writes, predicated on the confirm still being owed. */\nasync function stampConfirm(\n ctx: EngineContext,\n row: OutboundRow,\n succeeded: boolean,\n now: Date,\n): Promise<void> {\n const db = await ctx.ports.db();\n await db.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, confirmedAt: null, confirmFailedAt: null },\n data: succeeded ? { confirmedAt: now } : { confirmFailedAt: now },\n });\n}\n\n/** The cancellation stamp, predicated on the request still being PENDING. */\nasync function stampCancellation(\n ctx: EngineContext,\n row: OutboundRow,\n status: \"REQUESTED\" | \"CONFIRMED\" | \"FAILED\",\n): Promise<void> {\n const db = await ctx.ports.db();\n await db.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, cancellationStatus: \"PENDING\" },\n data: { cancellationStatus: status },\n });\n}\n\n/** The connection, or the reason it cannot be used (a refusal: no retry fixes it). */\nasync function connectionFor(\n ctx: EngineContext,\n clientId: string,\n provider: string,\n): Promise<OutboundConnection | string> {\n try {\n return (await readOutboundConnection(ctx, clientId, provider)) ?? \"no credentials on file\";\n } catch (error) {\n return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\n/** Turn a call's answer into the stamp and the outcome, or a retry. */\nasync function settle(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n row: OutboundRow,\n result: OutboundResult,\n attempt: OutboundAttempt,\n succeed: () => Promise<void>,\n fail: () => Promise<void>,\n): Promise<OutboundOutcome> {\n if (result.kind === \"accepted\") {\n await succeed();\n ctx.ports.publishChanged(payload.clientId);\n return { kind: \"done\", action: payload.action };\n }\n const reason = result.kind === \"refused\" ? `refused ${result.status}: ${result.message}` : result.reason;\n if (result.kind === \"retry\" && attempt.attempt < attempt.maxAttempts) {\n throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);\n }\n await fail();\n ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);\n ctx.ports.publishChanged(payload.clientId);\n return { kind: \"failed\", action: payload.action, reason };\n}\n\nasync function runConfirm(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n row: OutboundRow,\n adapter: MarketplaceAdapter,\n attempt: OutboundAttempt,\n): Promise<OutboundOutcome> {\n const skip = confirmSkip(row, adapter);\n if (skip) return { kind: \"skipped\", reason: skip };\n const now = ctx.ports.clock.now();\n const connection = await connectionFor(ctx, payload.clientId, row.provider);\n const result: OutboundResult =\n typeof connection === \"string\"\n ? { kind: \"refused\", status: 0, message: connection }\n : await adapter.confirm(\n { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },\n refOf(row),\n // The stated preparation time, for a marketplace whose confirm takes one.\n { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null },\n );\n return settle(\n ctx,\n payload,\n row,\n result,\n attempt,\n () => stampConfirm(ctx, row, true, now),\n () => stampConfirm(ctx, row, false, now),\n );\n}\n\n/** The offending SKUs stored with the request. */\nfunction skusOf(row: OutboundRow): string[] {\n return Array.isArray(row.cancellationOffendingSkus) ? row.cancellationOffendingSkus.map(String) : [];\n}\n\nasync function runCancellation(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n row: OutboundRow,\n adapter: MarketplaceAdapter,\n attempt: OutboundAttempt,\n): Promise<OutboundOutcome> {\n if (row.cancellationStatus !== \"PENDING\") {\n return { kind: \"skipped\", reason: `the request is ${row.cancellationStatus ?? \"absent\"}, not PENDING` };\n }\n const reason = resolveReason(adapter, row.cancellationReasonCode);\n const connection = await connectionFor(ctx, payload.clientId, row.provider);\n let result: OutboundResult;\n if (!reason) result = { kind: \"refused\", status: 0, message: \"the stored reason is not the marketplace's\" };\n else if (typeof connection === \"string\") result = { kind: \"refused\", status: 0, message: connection };\n else {\n result = await adapter.requestCancellation(\n { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },\n refOf(row),\n { reason, text: \"\", mode: \"MANUAL\", offendingSkus: skusOf(row) },\n );\n }\n const taken = adapter.capabilities.asyncCancellationOutcome ? \"REQUESTED\" : \"CONFIRMED\";\n return settle(\n ctx,\n payload,\n row,\n result,\n attempt,\n () => stampCancellation(ctx, row, taken),\n () => stampCancellation(ctx, row, \"FAILED\"),\n );\n}\n\n/**\n * The failure stamp a run that died on its LAST attempt leaves: FAILED, never\n * PENDING, so a person is shown the app link. Best-effort: if the database is\n * what failed, the row stays owed and the outbound sweep picks it up.\n */\nasync function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {\n const reason = error instanceof Error ? error.message : String(error);\n const db = await ctx.ports.db();\n await (payload.action === \"confirm\"\n ? db.marketplaceAcceptance.updateMany({\n where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },\n data: { confirmFailedAt: ctx.ports.clock.now() },\n })\n : db.marketplaceAcceptance.updateMany({\n where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: \"PENDING\" },\n data: { cancellationStatus: \"FAILED\" },\n }));\n ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);\n ctx.ports.publishChanged(payload.clientId);\n return { kind: \"failed\", action: payload.action, reason };\n}\n\nasync function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceAcceptance.findFirst({\n where: { orderId: payload.orderId, clientId: payload.clientId },\n select: ROW_SELECT,\n })) as OutboundRow | null;\n if (!row) return { kind: \"skipped\", reason: \"no acceptance for this order\" };\n const adapter = ctx.registry.get(row.provider);\n if (!adapter) return { kind: \"skipped\", reason: `no adapter for ${row.provider}` };\n return payload.action === \"confirm\"\n ? runConfirm(ctx, payload, row, adapter, attempt)\n : runCancellation(ctx, payload, row, adapter, attempt);\n}\n\n/**\n * Run one queued outbound call. Returns what it did; throws\n * {@link OutboundRetryError} for an answer worth retrying before the last\n * attempt. Any OTHER throw (an adapter bug, a database error while stamping)\n * is rethrown for the queue to retry, and on the last attempt ends FAILED.\n */\nexport async function runOutbound(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n attempt: OutboundAttempt,\n): Promise<OutboundOutcome> {\n try {\n return await runOnce(ctx, payload, attempt);\n } catch (error) {\n if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;\n return stampLastAttemptF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wB,KAAK,SAAS,KAAK;AAAA,EACpD;AACF;AAXsB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceProvider, NormalizedEvent } from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n method: \"GET\" | \"POST\" | \"PUT\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /** A final 4xx (not 408/425/429): never retried. */\n | { kind: \"refused\"; status: number; message: string }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAgKA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAShB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}