@12-apps/marketplace 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/ADOPTING.md +37 -7
  2. package/README.md +238 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +162 -0
  7. package/dist/99food/index.js +444 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-BggtVFf9.d.ts → adapter-0l_EmuJA.d.ts} +206 -2
  13. package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
  14. package/dist/chunk-AYYBRQJV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/chunk-M2V4RFMA.js +23 -0
  18. package/dist/chunk-M2V4RFMA.js.map +1 -0
  19. package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
  20. package/dist/chunk-RVBTARIY.js.map +1 -0
  21. package/dist/chunk-XUAFXNOH.js +1604 -0
  22. package/dist/chunk-XUAFXNOH.js.map +1 -0
  23. package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
  24. package/dist/hono/index.d.ts +2 -2
  25. package/dist/hono/index.js +2 -2
  26. package/dist/ifood/index.d.ts +16 -12
  27. package/dist/ifood/index.js +248 -121
  28. package/dist/ifood/index.js.map +1 -1
  29. package/dist/index.d.ts +30 -4
  30. package/dist/index.js +189 -346
  31. package/dist/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +4 -2
  33. package/dist/manifest/server.js +2 -2
  34. package/dist/rappi/en-US.d.ts +14 -0
  35. package/dist/rappi/en-US.js +18 -0
  36. package/dist/rappi/en-US.js.map +1 -0
  37. package/dist/rappi/index.d.ts +190 -0
  38. package/dist/rappi/index.js +359 -0
  39. package/dist/rappi/index.js.map +1 -0
  40. package/dist/rappi/pt-BR.d.ts +18 -0
  41. package/dist/rappi/pt-BR.js +18 -0
  42. package/dist/rappi/pt-BR.js.map +1 -0
  43. package/dist/server/index.d.ts +19 -8
  44. package/dist/server/index.js +4 -2
  45. package/package.json +26 -2
  46. package/prisma/marketplace.prisma +97 -2
  47. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  48. package/src/99food/catalogue.ts +117 -0
  49. package/src/99food/copy.ts +36 -0
  50. package/src/99food/en-US.ts +19 -0
  51. package/src/99food/index.ts +125 -0
  52. package/src/99food/normalize.ts +263 -0
  53. package/src/99food/outbound.ts +220 -0
  54. package/src/99food/pt-BR.ts +23 -0
  55. package/src/core/adapter.ts +27 -2
  56. package/src/core/catalogue-category.ts +119 -0
  57. package/src/core/catalogue-ids.ts +23 -0
  58. package/src/core/catalogue-job.ts +332 -0
  59. package/src/core/catalogue-port.ts +173 -0
  60. package/src/core/catalogue-store.ts +172 -0
  61. package/src/core/catalogue-sweep.ts +43 -0
  62. package/src/core/catalogue.ts +226 -0
  63. package/src/core/decisions.ts +16 -4
  64. package/src/core/engine.ts +54 -0
  65. package/src/core/fetch-order.ts +253 -0
  66. package/src/core/inbox.ts +8 -2
  67. package/src/core/ingest.ts +10 -2
  68. package/src/core/integration.ts +30 -1
  69. package/src/core/order-fetch-marks.ts +63 -0
  70. package/src/core/outbound-sweep.ts +7 -2
  71. package/src/core/outbound.ts +22 -2
  72. package/src/core/payload-read.ts +101 -0
  73. package/src/core/pipeline.ts +64 -15
  74. package/src/core/ports.ts +36 -0
  75. package/src/core/types.ts +14 -0
  76. package/src/ifood/catalogue.ts +273 -0
  77. package/src/ifood/index.ts +4 -0
  78. package/src/ifood/normalize.ts +15 -88
  79. package/src/ifood/outbound.ts +9 -6
  80. package/src/index.ts +49 -1
  81. package/src/rappi/copy.ts +39 -0
  82. package/src/rappi/en-US.ts +14 -0
  83. package/src/rappi/index.ts +161 -0
  84. package/src/rappi/normalize.ts +314 -0
  85. package/src/rappi/outbound.ts +182 -0
  86. package/src/rappi/pt-BR.ts +18 -0
  87. package/src/server/index.ts +1 -0
  88. package/src/server/jobs.ts +71 -8
  89. package/dist/chunk-7BYVGNU5.js.map +0 -1
  90. package/dist/chunk-DVIRN42O.js +0 -707
  91. package/dist/chunk-DVIRN42O.js.map +0 -1
  92. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/types.ts","../src/core/registry.ts","../src/core/outbound-queue.ts","../src/core/cancellation-outcome.ts","../src/core/cancellation.ts","../src/core/outbound-sweep.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 { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The outbound job's name and payload — what a decision QUEUES.\n *\n * No path that answers a request ever calls a marketplace: an aceite, a\n * refusal, a webhook and an ingest only enqueue this, and the job does the\n * call. The payload carries identifiers only; the reason code and every\n * outcome live on the acceptance row, so a replayed or duplicated job reads\n * the truth rather than a stale copy of it.\n */\n\n/** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */\nexport const MARKETPLACE_OUTBOUND_JOB = \"marketplace.outbound\";\n\n/** What goes out: the store's aceite, or the store's cancellation request. */\nexport type OutboundAction = \"confirm\" | \"requestCancellation\";\n\n/** The outbound job's payload. Identifiers only. */\nexport interface OutboundJobPayload {\n clientId: string;\n orderId: string;\n action: OutboundAction;\n}\n\n/** The dedupe key: at most one queued call per (order, action). */\nexport function outboundDedupeKey(payload: OutboundJobPayload): string {\n return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;\n}\n\n/**\n * Queue one outbound call, when the marketplace's API can take it at all.\n *\n * A marketplace whose adapter states no API for the action gets nothing\n * queued: there is nobody to call, and the host shows the app link instead.\n * The queue port never throws. A refusal to enqueue is logged AND recovered:\n * the row still owes the call (PENDING, or ACCEPTED with no confirm stamp),\n * and the outbound sweep re-queues every such row (`./outbound-sweep.ts`).\n *\n * `dedupeKey` defaults to the job's own key; the sweep passes its own, since a\n * queue keeps a finished job's id and would swallow a re-queue under it.\n */\nexport async function enqueueOutbound(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n provider: MarketplaceProvider,\n dedupeKey: string = outboundDedupeKey(payload),\n): Promise<boolean> {\n const adapter = ctx.registry.get(provider);\n if (!adapter) return false;\n const able =\n payload.action === \"confirm\" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;\n if (!able) return false;\n const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });\n if (!outcome.enqueued) {\n ctx.ports.logger.warn(\n `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` +\n (outcome.reason ? ` (${outcome.reason})` : \"\"),\n );\n }\n return outcome.enqueued;\n}\n","import type { MarketplaceAdapter } from \"./adapter\";\nimport type { CancellationFailureReason, EngineContext, MarketplaceDb } from \"./ports\";\n\n/**\n * How the store's own cancellation request ENDS, told to the host (FUT-4758).\n *\n * A host that requests first and cancels only on the marketplace's answer\n * needs both ends: the confirmation, to run its cancel, and the failure, to\n * put the pedido back in a person's hands. Both are optional order-port\n * callbacks, so a 1.0.0 host compiles and behaves unchanged. Each is called by\n * whichever path moved the row (the outbound job, the marketplace's event, the\n * sweep's expiry), once, and a host failure is logged, never rethrown: the\n * row's stamp has committed, and a host that fails its half must not undo it.\n */\n\nasync function tell(ctx: EngineContext, what: string, orderId: string, call: () => Promise<void>): Promise<void> {\n try {\n await call();\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\n/**\n * Whether the host REQUESTS FIRST and cancels on the marketplace's\n * confirmation: it binds `onCancellationConfirmed` (FUT-4758). A host that\n * does not keeps 1.0.0's behaviour exactly — the store's cancel is stamped\n * REJECTED at request time and `onRefused` runs then.\n */\nexport function requestsFirst(ctx: EngineContext): boolean {\n return ctx.ports.order.onCancellationConfirmed !== undefined;\n}\n\n/**\n * Move a row whose cancellation was just confirmed off the clock: REJECTED,\n * acknowledged now when it was still AWAITING (the table's CHECK pairs the\n * two); an accepted row keeps its acceptance instant.\n */\nexport async function rejectConfirmed(db: MarketplaceDb, orderId: string, now: Date): Promise<void> {\n await db.marketplaceAcceptance.updateMany({\n where: { orderId, status: \"AWAITING\" },\n data: { status: \"REJECTED\", acknowledgedAt: now },\n });\n await db.marketplaceAcceptance.updateMany({\n where: { orderId, status: { in: [\"ACCEPTED\", \"EXPIRED\"] } },\n data: { status: \"REJECTED\" },\n });\n}\n\n/**\n * The store's confirmed request, told to the host: `onCancellationConfirmed`\n * when bound, else `onRefused(…, \"CANCELLED\")` as in 1.0.0.\n */\nexport async function confirmedToHost(ctx: EngineContext, clientId: string, orderId: string): Promise<void> {\n if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;\n await ctx.ports.order.onRefused(clientId, orderId, \"CANCELLED\");\n}\n\n/** The marketplace confirmed the store's request. Returns whether the host took it (it has the callback). */\nexport async function tellCancellationConfirmed(ctx: EngineContext, clientId: string, orderId: string): Promise<boolean> {\n const hook = ctx.ports.order.onCancellationConfirmed;\n if (!hook) return false;\n await tell(ctx, \"was cancelled on the store's request\", orderId, () => hook.call(ctx.ports.order, clientId, orderId));\n return true;\n}\n\n/** The store's request failed, refused or timed out. */\nexport async function tellCancellationFailed(\n ctx: EngineContext,\n clientId: string,\n orderId: string,\n reason: CancellationFailureReason,\n): Promise<void> {\n const hook = ctx.ports.order.onCancellationFailed;\n if (!hook) return;\n await tell(ctx, `had its cancellation request fail (${reason})`, orderId, () =>\n hook.call(ctx.ports.order, clientId, orderId, reason),\n );\n}\n\n/** How long a request to this adapter may wait for its answer: the engine's override, else the adapter's own. */\nexport function cancellationWindowMs(ctx: EngineContext, adapter: MarketplaceAdapter): number | null {\n return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;\n}\n\n/** The columns a request that FAILED for `reason` writes. */\nexport function failedRequestData(reason: CancellationFailureReason): Record<string, unknown> {\n return { cancellationStatus: \"FAILED\", cancellationFailureReason: reason };\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport type { CancellationReason, MarketplaceAdapter } from \"./adapter\";\nimport { failedRequestData, tellCancellationFailed } from \"./cancellation-outcome\";\nimport type { EngineContext } from \"./ports\";\nimport { resolveReason } from \"./registry\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The store's own CANCELLATION REQUEST — the half of a refusal that must reach\n * the marketplace. Lives on the acceptance row:\n *\n * null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED\n * │ ├──job 4xx / last attempt / event──▶ FAILED (REFUSED) ──event──▶ CONFIRMED\n * │ └──past the window (sweep)──▶ FAILED (TIMEOUT)\n * └──event (the marketplace cancelled)──▶ CONFIRMED\n *\n * CONFIRMED is terminal; every write is predicated on the statuses it may come\n * from, so an out-of-order event cannot undo it. A FAILED request stands for\n * nothing: the order may be decided again, or the cancellation asked again\n * (FUT-4758: a refused or timed-out request leaves the order as it was).\n */\n\n/** No request of the store's is waiting on the marketplace: never asked, or asked and FAILED. */\nfunction noStandingRequest(cancellationStatus: string | null): boolean {\n return cancellationStatus === null || cancellationStatus === \"FAILED\";\n}\n\n/** The same, as the `where` a claim is predicated on. */\nexport const NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: \"FAILED\" }] } as const;\n\n/** Why a decision (or a store cancellation) was refused. Vocabulary, not copy. */\nexport type DecisionProblemCode =\n | \"DUPLICATE\"\n | \"NOT_FOUND\"\n | \"ALREADY_DECIDED\"\n | \"EXPIRED\"\n | \"CONFLICT\"\n | \"INVALID_REASON\"\n | \"ITEMS_REQUIRED\"\n | \"UNKNOWN_ITEM\"\n | \"HOST_REFUSED\";\n\n/** One refusal, with the path of the input it is about. Nothing was written. */\nexport interface DecisionProblem {\n path: (string | number)[];\n code: DecisionProblemCode;\n /** The row's current status, for NOT-pending refusals (ALREADY_DECIDED, EXPIRED). */\n status?: AcceptanceStatus;\n /** The marketplace's codes, for INVALID_REASON. */\n validCodes?: string[];\n /** The host's own refusal, for HOST_REFUSED. */\n host?: { code: string; message: string; details?: unknown };\n}\n\n/** The acceptance row a claim reads first. */\nexport interface ClaimRow {\n orderId: string;\n provider: string;\n status: string;\n cancellationStatus: string | null;\n lineSkus: unknown;\n}\n\nexport const CLAIM_SELECT = {\n orderId: true,\n provider: true,\n status: true,\n cancellationStatus: true,\n lineSkus: true,\n} as const;\n\n/** The refusal a row that is no longer on the clock earns, or null. */\nexport function notPendingProblem(\n row: ClaimRow | undefined | null,\n path: (string | number)[],\n allowed: readonly string[] = [\"AWAITING\"],\n): DecisionProblem | null {\n if (!row) return { path: [...path, \"orderId\"], code: \"NOT_FOUND\" };\n if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;\n const status = row.status as AcceptanceStatus;\n return { path: [...path, \"orderId\"], code: status === \"EXPIRED\" ? \"EXPIRED\" : \"ALREADY_DECIDED\", status };\n}\n\n/** What a refusal stamps, and with which reason and SKUs. */\nexport interface CancellationPlan {\n status: CancellationStatus | null;\n reason: CancellationReason | null;\n skus: string[];\n}\n\nfunction lineSkusOf(row: ClaimRow): Set<string> | null {\n return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;\n}\n\n/** Every refusal the named SKUs earn: none when the reason needs some, an unknown one. */\nfunction skuProblems(\n reason: CancellationReason | null,\n skus: string[],\n row: ClaimRow,\n path: (string | number)[],\n): DecisionProblem[] {\n if (reason?.needsItems && skus.length === 0) return [{ path: [...path, \"offendingSkus\"], code: \"ITEMS_REQUIRED\" }];\n const known = lineSkusOf(row);\n // A row from before `line_skus` existed cannot be checked; its SKUs pass.\n if (!known) return [];\n return skus.flatMap((sku, index) =>\n known.has(sku) ? [] : [{ path: [...path, \"offendingSkus\", index], code: \"UNKNOWN_ITEM\" as const }],\n );\n}\n\n/** The refusal of a named code that is not the marketplace's, or null. */\nfunction invalidReasonProblem(\n adapter: MarketplaceAdapter,\n reason: CancellationReason | null,\n code: string | null | undefined,\n path: (string | number)[],\n): DecisionProblem | null {\n if (code === null || code === undefined || reason) return null;\n const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);\n return { path: [...path, \"reasonCode\"], code: \"INVALID_REASON\", validCodes };\n}\n\n/**\n * Plan the cancellation half of a refusal, or say what is wrong with it.\n *\n * - No adapter (a provider nobody registers any more): nothing goes out.\n * - The code must be the marketplace's; with none, its first reason is taken.\n * - A reason that `needsItems` needs offending SKUs, each one of the order's.\n * - An API that cannot cancel — at all, or after an accept — stamps FAILED at\n * once: the request cannot be made from here, and FAILED is what puts the\n * adapter's app link in front of a person.\n * - Otherwise PENDING, for the outbound job.\n */\nexport function planCancellation(\n adapter: MarketplaceAdapter | null,\n input: { reasonCode?: string | null; offendingSkus?: readonly string[] },\n row: ClaimRow,\n path: (string | number)[],\n): CancellationPlan | DecisionProblem[] {\n if (!adapter) return { status: null, reason: null, skus: [] };\n const reason = resolveReason(adapter, input.reasonCode);\n const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);\n if (invalid) return [invalid];\n const skus = [...new Set(input.offendingSkus ?? [])];\n const problems = skuProblems(reason, skus, row, path);\n if (problems.length > 0) return problems;\n const { apiCancel, cancelAfterAccept } = adapter.capabilities;\n const canAsk = apiCancel && reason !== null && (row.status === \"AWAITING\" || cancelAfterAccept);\n return { status: canAsk ? \"PENDING\" : \"FAILED\", reason, skus };\n}\n\n/** The columns one refusal writes, from the status it leaves. */\nexport function refusalData(plan: CancellationPlan, fromStatus: string, now: Date): Record<string, unknown> {\n return {\n status: \"REJECTED\",\n // An accepted row keeps the instant it was accepted; a row leaving the\n // clock is acknowledged now (the table's CHECK pairs the two).\n ...(fromStatus === \"AWAITING\" ? { acknowledgedAt: now } : {}),\n cancellationStatus: plan.status,\n cancellationReasonCode: plan.reason?.code ?? null,\n cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,\n cancellationRequestedAt: plan.status === \"PENDING\" ? now : null,\n cancellationFailureReason: plan.status === \"FAILED\" ? \"REFUSED\" : null,\n };\n}\n\n/**\n * The columns the store's own cancellation REQUEST writes (FUT-4758): the\n * request alone. The decision status stays as it is (AWAITING or ACCEPTED)\n * while the marketplace answers, so a refused or timed-out request leaves the\n * order acceptable and still on the acceptance clock; only the marketplace's\n * confirmation moves it to REJECTED.\n */\nexport function requestData(plan: CancellationPlan, now: Date): Record<string, unknown> {\n return {\n cancellationStatus: plan.status,\n cancellationReasonCode: plan.reason?.code ?? null,\n cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,\n cancellationRequestedAt: plan.status === \"PENDING\" ? now : null,\n cancellationFailureReason: plan.status === \"FAILED\" ? \"REFUSED\" : null,\n };\n}\n\n/**\n * The marketplace refused the store's cancellation request. FAILED (REFUSED),\n * from PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving\n * after the cancellation changes nothing. The host hears it once, from the\n * call that moved the row. Returns whether a row moved.\n */\nexport async function failCancellationRequest(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },\n): Promise<boolean> {\n const db = await ctx.ports.db();\n const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };\n const row = (await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } })) as { orderId: string } | null;\n if (!row) return false;\n const moved = await db.marketplaceAcceptance.updateMany({\n where: { ...where, cancellationStatus: { in: [\"PENDING\", \"REQUESTED\"] } },\n data: failedRequestData(\"REFUSED\"),\n });\n if (moved.count === 0) return false;\n ctx.ports.publishChanged(input.clientId);\n await tellCancellationFailed(ctx, input.clientId, row.orderId, \"REFUSED\");\n return true;\n}\n","import { NO_STANDING_REQUEST } from \"./cancellation\";\nimport { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from \"./cancellation-outcome\";\nimport { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from \"./outbound-queue\";\nimport type { EngineContext } from \"./ports\";\n\n/**\n * The outbound sweep: nothing owed to a marketplace is lost.\n *\n * A decision queues its call right after the commit, but a queue can refuse\n * the job, a process can die between the commit and the enqueue, and a job can\n * die without stamping. The ROW still says what is owed — a PENDING request,\n * or an ACCEPTED order with neither confirm stamp — so this pass re-queues\n * every such row once it is older than the outbound job's own retry span.\n *\n * Bounded both ways:\n * - younger than {@link OUTBOUND_STALE_MS}: the original job may still be\n * retrying, so it is left alone;\n * - older than {@link OUTBOUND_GIVE_UP_MS}: a marketplace has long since\n * settled the order on its own clock. A request still waiting that old is\n * stamped FAILED, TIMEOUT (a person finishes it on the marketplace, through\n * the app link),\n * and an accept that old is never confirmed — which is also what keeps a\n * host's ACCEPTED history from before this engine from being confirmed on\n * the first pass.\n *\n * For a host that REQUESTS FIRST (it binds `onCancellationConfirmed`; a 1.0.0\n * host keeps the re-queue and the give-up below, unchanged), and before\n * anything else, a store's cancellation request still waiting (PENDING:\n * never delivered, or REQUESTED: delivered and unanswered) past its\n * marketplace's answer window — the engine's `cancellationWindowMs`, else the\n * adapter's `cancellationAnswerWindowMs`, counted from the request — is FAILED\n * as TIMEOUT, and the host hears it through `onCancellationFailed` (FUT-4758,\n * the owner: \"it cannot stay in that state with nothing happening\"). The\n * store then cancels in the marketplace's own app. A PENDING request's\n * retries stop with it: the job re-reads the row and sends only from PENDING,\n * a run that starts past the window ends TIMEOUT itself without calling, and\n * this sweep re-queues no FAILED row. The window is read at the sweep's own\n * cadence, so a request ends between the window and the window plus one pass.\n *\n * Re-queued under a key of its own per pass: a queue keeps a finished job's id\n * and would swallow a re-queue under the job's plain key. The job itself is\n * idempotent by the row, so a duplicate run calls nobody twice.\n */\n\n/** Longer than the outbound job's three attempts with their backoff. */\nexport const OUTBOUND_STALE_MS = 10 * 60_000;\n\n/** Past this, a marketplace has settled the order without us. */\nexport const OUTBOUND_GIVE_UP_MS = 24 * 60 * 60_000;\n\n/** What one sweep pass did. */\nexport interface OutboundSweepResult {\n requeued: number;\n /** Requests still waiting past {@link OUTBOUND_GIVE_UP_MS}, failed as TIMEOUT. */\n givenUp: number;\n /** Requests failed as TIMEOUT past their marketplace's answer window. */\n timedOut: number;\n}\n\n/** A store's cancellation request still waiting on the marketplace. */\nconst WAITING = [\"PENDING\", \"REQUESTED\"];\n\ninterface OwedRow {\n clientId: string;\n orderId: string;\n provider: string;\n}\n\nconst OWED_SELECT = { clientId: true, orderId: true, provider: true } as const;\n\n/** The sweep's own dedupe key: distinct from the job's, and per pass. */\nfunction sweepDedupeKey(action: OutboundAction, orderId: string, now: Date): string {\n return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;\n}\n\nasync function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: OutboundAction, now: Date): Promise<number> {\n let queued = 0;\n for (const row of rows) {\n const payload = { clientId: row.clientId, orderId: row.orderId, action };\n if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;\n }\n return queued;\n}\n\n/** Re-queue every owed call older than the job's retry span; give up on the ancient ones. */\n/**\n * Fail as TIMEOUT every request in `rows` still waiting, one predicated write\n * each, so a confirmation that lands meanwhile wins and its host hears nothing\n * twice. Returns how many moved.\n */\nexport async function failAsTimeout(ctx: EngineContext, rows: readonly OwedRow[]): Promise<number> {\n const db = await ctx.ports.db();\n let failed = 0;\n for (const row of rows) {\n const moved = await db.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, clientId: row.clientId, cancellationStatus: { in: WAITING } },\n data: failedRequestData(\"TIMEOUT\"),\n });\n if (moved.count === 0) continue;\n failed += 1;\n ctx.ports.publishChanged(row.clientId);\n await tellCancellationFailed(ctx, row.clientId, row.orderId, \"TIMEOUT\");\n }\n return failed;\n}\n\n/** Every request in `statuses` since before `cutoff`, for one provider or all. */\nasync function waitingSince(\n ctx: EngineContext,\n cutoff: Date,\n statuses: readonly string[],\n provider?: string,\n): Promise<OwedRow[]> {\n const db = await ctx.ports.db();\n return (await db.marketplaceAcceptance.findMany({\n where: { ...(provider ? { provider } : {}), cancellationStatus: { in: statuses }, cancellationRequestedAt: { lt: cutoff } },\n select: OWED_SELECT,\n })) as OwedRow[];\n}\n\n/** Fail every request still waiting past its marketplace's window; no window, only the give-up. */\nasync function expireUnanswered(ctx: EngineContext, now: Date): Promise<number> {\n // Only for a host that requests first: a 1.0.0 host (it cancelled already)\n // keeps the re-queue and the 24-hour give-up exactly as before.\n if (!requestsFirst(ctx)) return 0;\n let expired = 0;\n for (const provider of ctx.registry.providers()) {\n const adapter = ctx.registry.get(provider);\n const window = adapter ? cancellationWindowMs(ctx, adapter) : null;\n if (window === null) continue;\n const cutoff = new Date(now.getTime() - window);\n expired += await failAsTimeout(ctx, await waitingSince(ctx, cutoff, WAITING, provider));\n }\n return expired;\n}\n\n/**\n * One sweep pass: expire the requests nobody answered, give up on the very old,\n * and re-queue what is still owed.\n */\nexport async function sweepOutbound(ctx: EngineContext, now: Date): Promise<OutboundSweepResult> {\n const db = await ctx.ports.db();\n const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);\n const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);\n\n const timedOut = await expireUnanswered(ctx, now);\n // 1.0.0 gave up on PENDING requests only; a host that requests first, on any still waiting.\n const givenUp = await failAsTimeout(ctx, await waitingSince(ctx, giveUp, requestsFirst(ctx) ? WAITING : [\"PENDING\"]));\n const cancellations = (await db.marketplaceAcceptance.findMany({\n where: { cancellationStatus: \"PENDING\", cancellationRequestedAt: { lt: stale, gte: giveUp } },\n select: OWED_SELECT,\n })) as OwedRow[];\n const confirms = (await db.marketplaceAcceptance.findMany({\n where: {\n status: \"ACCEPTED\",\n confirmedAt: null,\n confirmFailedAt: null,\n acknowledgedAt: { lt: stale, gte: giveUp },\n // An accept the store asked to cancel is not confirmed while the request waits.\n ...NO_STANDING_REQUEST,\n },\n select: OWED_SELECT,\n })) as OwedRow[];\n\n const requeued =\n (await requeue(ctx, cancellations, \"requestCancellation\", now)) + (await requeue(ctx, confirms, \"confirm\", now));\n if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);\n return { requeued, givenUp, timedOut };\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 {\n cancellationWindowMs,\n confirmedToHost,\n failedRequestData,\n rejectConfirmed,\n requestsFirst,\n tellCancellationFailed,\n} from \"./cancellation-outcome\";\nimport { readOutboundConnection, type OutboundConnection } from \"./integration\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport { failAsTimeout } from \"./outbound-sweep\";\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 cancellationRequestedAt: Date | null;\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 cancellationRequestedAt: 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 // A request to cancel stands (FUT-4758: the status stays ACCEPTED while it\n // waits): confirming now would tell the marketplace the opposite.\n if (row.cancellationStatus !== null && row.cancellationStatus !== \"FAILED\") {\n return `a cancellation request is ${row.cancellationStatus}`;\n }\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/**\n * The cancellation stamp, predicated on the request still being PENDING, and\n * the host told how it ended when this run is what ended it (FUT-4758): a\n * marketplace that answers in the response CONFIRMS here, and a refusal FAILS\n * here. REQUESTED tells nobody: the answer is still to come, by event.\n */\nasync function stampCancellation(\n ctx: EngineContext,\n row: OutboundRow,\n status: \"REQUESTED\" | \"CONFIRMED\" | \"FAILED\",\n clientId: string,\n): Promise<void> {\n if (status === \"CONFIRMED\") return stampConfirmedCancellation(ctx, row, clientId);\n const db = await ctx.ports.db();\n const data = status === \"FAILED\" ? failedRequestData(\"REFUSED\") : { cancellationStatus: status };\n const moved = await db.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, cancellationStatus: \"PENDING\" },\n data,\n });\n if (moved.count > 0 && status === \"FAILED\") await tellCancellationFailed(ctx, clientId, row.orderId, \"REFUSED\");\n}\n\n/**\n * A marketplace that confirms in its answer: the same stamps as its\n * CANCELLED event (`cancelAcceptance`) — CONFIRMED and REJECTED in one\n * transaction — then the host's `onCancellationConfirmed`, or\n * `onRefused(…, \"CANCELLED\")` when it binds none. A host failure is logged:\n * the stamps have committed.\n */\nasync function stampConfirmedCancellation(ctx: EngineContext, row: OutboundRow, clientId: string): Promise<void> {\n const now = ctx.ports.clock.now();\n const moved = await ctx.ports.transaction(async (tx) => {\n // From FAILED too: the sweep may have timed the request out while this\n // call was in flight, and a marketplace that answers in the response sends\n // no event — its \"cancelled\" is the only word that it did (the event path's\n // own rule: a confirmation after a TIMEOUT still confirms).\n const confirmed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, cancellationStatus: { in: [\"PENDING\", \"FAILED\"] } },\n data: { cancellationStatus: \"CONFIRMED\", cancellationFailureReason: null },\n });\n if (confirmed.count === 0) return false;\n await rejectConfirmed(tx, row.orderId, now);\n return true;\n });\n if (!moved) return;\n try {\n await confirmedToHost(ctx, clientId, row.orderId);\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.outbound: order ${row.orderId} was cancelled on the store's request but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\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/** Whether a request is older than its marketplace's answer window, so it must not be sent any more. */\nfunction pastWindow(ctx: EngineContext, row: OutboundRow, adapter: MarketplaceAdapter): boolean {\n // A 1.0.0 host (no `onCancellationConfirmed`) has no window: it retries, as before.\n if (!requestsFirst(ctx)) return false;\n const window = cancellationWindowMs(ctx, adapter);\n if (window === null || row.cancellationRequestedAt === null) return false;\n return ctx.ports.clock.now().getTime() - row.cancellationRequestedAt.getTime() > window;\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 if (pastWindow(ctx, row, adapter)) {\n // A retry that comes after the window never delivers (FUT-4758): the host\n // was, or is now, told TIMEOUT, and the store cancels in the marketplace's app.\n await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);\n return { kind: \"failed\", action: payload.action, reason: \"past the marketplace's answer window\" };\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, payload.clientId),\n () => stampCancellation(ctx, row, \"FAILED\", payload.clientId),\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 const moved = 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: failedRequestData(\"REFUSED\"),\n }));\n ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);\n ctx.ports.publishChanged(payload.clientId);\n if (payload.action === \"requestCancellation\" && moved.count > 0) {\n await tellCancellationFailed(ctx, payload.clientId, payload.orderId, \"REFUSED\");\n }\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 stampLastAttemptFailure(ctx, payload, error);\n }\n}\n"],"mappings":";;;;;AAwBO,IAAM,sBAAsB;;;ACJ5B,IAAM,sCAAN,cAAkD,MAAM;AAAA,EApB/D,OAoB+D;AAAA;AAAA;AAAA,EAC7D,YAAY,SAAiB;AAC3B,UAAM,yBAAyB,OAAO,EAAE;AACxC,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,cAAc,SAAmC;AACxD,QAAM,QAAQ,oBAAI,IAAY;AAC9B,aAAW,UAAU,QAAQ,oBAAoB,GAAG;AAClD,QAAI,OAAO,KAAK,KAAK,MAAM,IAAI;AAC7B,YAAM,IAAI,oCAAoC,GAAG,QAAQ,QAAQ,uCAAuC;AAAA,IAC1G;AACA,QAAI,MAAM,IAAI,OAAO,IAAI,GAAG;AAC1B,YAAM,IAAI;AAAA,QACR,GAAG,QAAQ,QAAQ,8BAA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AACA,SAAO,EAAE,MAAM,UAAU,QAAQ,QAAQ,QAAQ,OAAO;AAC1D;AAlBe;AAoBf,eAAe,QAAQ,KAAoB,SAA6B,SAAoD;AAC1H,QAAM,KAAK,MAAM,IAAI,MAAM,GAAG;AAC9B,QAAM,MAAO,MAAM,GAAG,sBAAsB,UAAU;AAAA,IACpD,OAAO,EAAE,SAAS,QAAQ,SAAS,UAAU,QAAQ,SAAS;AAAA,IAC9D,QAAQ;AAAA,EACV,CAAC;AACD,MAAI,CAAC,IAAK,QAAO,EAAE,MAAM,WAAW,QAAQ,+BAA+B;AAC3E,QAAM,UAAU,IAAI,SAAS,IAAI,IAAI,QAAQ;AAC7C,MAAI,CAAC,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,kBAAkB,IAAI,QAAQ,GAAG;AACjF,SAAO,QAAQ,WAAW,YACtB,WAAW,KAAK,SAAS,KAAK,SAAS,OAAO,IAC9C,gBAAgB,KAAK,SAAS,KAAK,SAAS,OAAO;AACzD;AAZe;AAoBf,eAAsB,YACpB,KACA,SACA,SAC0B;AAC1B,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK,SAAS,OAAO;AAAA,EAC5C,SAAS,OAAO;AACd,QAAI,iBAAiB,sBAAsB,QAAQ,UAAU,QAAQ,YAAa,OAAM;AACxF,WAAO,wBAAwB,KAAK,SAAS,KAAK;AAAA,EACpD;AACF;AAXsB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/http.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately. A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 200: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status: 200, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds } : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n return { status: 200, body: { received: true, outcome: outcome.kind } };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? copy.problems[problem.code],\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n ...integrationRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\n\n/**\n * The engine's three jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp) once it is older\n * than the job's own retry span, so a refused enqueue or a dead process\n * loses nothing.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound` and `marketplace.outbound-sweep`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<MarketplaceEngine, \"expireLapsed\" | \"retryable\" | \"reprocess\" | \"runOutbound\" | \"sweepOutbound\">;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n if (pending.length === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n if (result.requeued === 0 && result.givenUp === 0 && result.timedOut === 0) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s), timed out ${result.timedOut} ` +\n `cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"outbound-sweep\": outboundSweep,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS,OAAO,QAAgB,OAAe,QAAiC,CAAC,GAAiB;AACvG,SAAO,EAAE,QAAQ,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE;AAC7C;AAFgB;AAKT,SAAS,MACd,QACA,OACA,MACgE;AAChE,QAAM,SAAS,OAAO,UAAU,SAAS,CAAC,CAAC;AAC3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