@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
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/acceptance.ts","../src/core/menu-links.ts","../src/core/bulk.ts","../src/core/decisions.ts","../src/core/inbox.ts","../src/core/ingest.ts","../src/core/pipeline.ts","../src/core/state.ts","../src/core/engine.ts"],"sourcesContent":["import { NO_STANDING_REQUEST } from \"./cancellation\";\nimport { rejectConfirmed, tellCancellationConfirmed } from \"./cancellation-outcome\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The acceptance clock — the store saying yes (or no) to an order.\n *\n * A first-class state rather than a notification, because a marketplace\n * CANCELS an order nobody acknowledged. This module is the only thing that\n * moves an order between the states it can be in:\n *\n * AWAITING ──accept──▶ ACCEPTED ──store cancel──▶ REJECTED\n * │ └──reject───▶ REJECTED\n * └──sweep───────▶ EXPIRED\n *\n * Every transition is guarded on the CURRENT state in the WHERE clause rather\n * than read-then-written, so the sweep and a person deciding in the same\n * second cannot both win. The decisions themselves are `./decisions.ts`;\n * this module holds the queue, the sweep and the marketplace's own cancel.\n *\n * Beside the clock sits the store's own CANCELLATION REQUEST, on the same row:\n *\n * null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED\n * │ └──job 4xx / last retry──▶ FAILED ──event──▶ CONFIRMED\n * └──event (the marketplace cancelled)──▶ CONFIRMED\n *\n * CONFIRMED is terminal; every write to the column is predicated on the\n * statuses it may come from, so an out-of-order event cannot undo it.\n */\n\n/** The states an acceptance can be in. The host renders them; they are not copy. */\nexport type AcceptanceStatus = \"AWAITING\" | \"ACCEPTED\" | \"REJECTED\" | \"EXPIRED\";\n\n/** Where the store's own cancellation request stands. */\nexport type CancellationStatus = \"PENDING\" | \"REQUESTED\" | \"CONFIRMED\" | \"FAILED\";\n\n/** An order waiting on the store, as the acceptance queue shows it. */\nexport interface PendingAcceptance {\n id: string;\n /** The HOST's order id — what every host-side surface keys off. */\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The deadline itself, so a client counts down against a real instant. */\n acknowledgeBy: Date | null;\n externalDueAt: Date | null;\n commissionCents: number | null;\n buyerName: string | null;\n totalCents: number;\n unmappedLines: number;\n createdAt: string | null;\n}\n\ninterface PendingRow {\n id: string;\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n acknowledgeBy: Date | null;\n externalDueAt: Date | null;\n commissionCents: number | null;\n}\n\n/**\n * Orders still on the clock, soonest DEADLINE first — the one about to lapse\n * is the one that has to be at the top of the screen. The host's half of each\n * row arrives in ONE `summarize` call.\n */\nexport async function listPendingAcceptances(\n ctx: EngineContext,\n clientId: string,\n orderIds?: readonly string[],\n): Promise<PendingAcceptance[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, status: \"AWAITING\", ...(orderIds ? { orderId: { in: [...orderIds] } } : {}) },\n orderBy: { acknowledgeBy: \"asc\" },\n select: {\n id: true,\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n acknowledgeBy: true,\n externalDueAt: true,\n commissionCents: true,\n },\n })) as PendingRow[];\n if (rows.length === 0) return [];\n\n const summaries = await ctx.ports.order.summarize(\n clientId,\n rows.map((row) => row.orderId),\n );\n return rows.map((row) => {\n const summary = summaries.get(row.orderId);\n return {\n ...row,\n buyerName: summary?.buyerName ?? null,\n totalCents: summary?.totalCents ?? 0,\n unmappedLines: summary?.unmappedLines ?? 0,\n createdAt: summary?.createdAt ?? null,\n };\n });\n}\n\n/** What one sweep pass did. */\nexport interface ExpirySweepResult {\n expired: number;\n tenants: number;\n}\n\n/**\n * Expire every order whose deadline has passed.\n *\n * The marketplace has already cancelled these on its own side — that is what\n * the deadline MEANS — so this records what the engine now knows happened.\n * Idempotent by durable marker: `status` is in the predicate, and an ACCEPTED\n * row is never touched, so an order a person accepted is never expired.\n */\nexport async function expireLapsedAcceptances(\n ctx: EngineContext,\n now: Date,\n): Promise<ExpirySweepResult> {\n const db = await ctx.ports.db();\n const lapsed = (await db.marketplaceAcceptance.findMany({\n // An order whose cancellation request waits is left to that request: its\n // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host\n // never hears EXPIRED and then the confirmation for one order.\n where: { status: \"AWAITING\", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },\n select: { id: true, clientId: true, orderId: true },\n })) as { id: string; clientId: string; orderId: string }[];\n if (lapsed.length === 0) return { expired: 0, tenants: 0 };\n\n const result = await db.marketplaceAcceptance.updateMany({\n where: { id: { in: lapsed.map((row) => row.id) }, status: \"AWAITING\", ...NO_STANDING_REQUEST },\n data: { status: \"EXPIRED\", acknowledgedAt: now },\n });\n\n // The host's half must not be able to fail the sweep: one tenant's broken\n // cancellation cannot leave every other tenant's lapsed orders on the clock.\n for (const row of lapsed) {\n try {\n await ctx.ports.order.onRefused(row.clientId, row.orderId, \"EXPIRED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.expire-acceptances: order ${row.orderId} expired but the host's refusal failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n\n const tenants = new Set(lapsed.map((row) => row.clientId));\n for (const clientId of tenants) ctx.ports.publishChanged(clientId);\n return { expired: result.count, tenants: tenants.size };\n}\n\n/**\n * The marketplace cancelled an order it had already given us.\n *\n * Terminal on the acceptance side whatever state it was in. A cancellation\n * request the store made is answered: CONFIRMED, from PENDING, REQUESTED or\n * FAILED (a refusal followed by a cancellation is still a cancellation), and\n * the host hears it through `onCancellationConfirmed` when it has one;\n * otherwise, and for a cancellation the store never asked for,\n * `onRefused(…, \"CANCELLED\")`. Returns false when no acceptance stands for this external order — a\n * cancellation can outrun the placement it refers to.\n */\n/** Whether the host takes a confirmed request through `onCancellationConfirmed` (FUT-4758). */\nfunction hasConfirmHook(ctx: EngineContext): boolean {\n return ctx.ports.order.onCancellationConfirmed !== undefined;\n}\n\nexport async function cancelAcceptance(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string; now?: Date },\n): Promise<boolean> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceAcceptance.findFirst({\n where: {\n clientId: input.clientId,\n provider: input.provider,\n externalOrderId: input.externalOrderId,\n },\n select: { orderId: true, cancellationStatus: true },\n })) as { orderId: string; cancellationStatus: string | null } | null;\n if (!row) return false;\n\n // The two stamps commit together: a cancelled order never shows a request\n // still PENDING. The host's cancel runs after; if it throws, the inbox row\n // is FAILED and the retry sweep re-runs this, whose stamps are idempotent.\n const answered = await ctx.ports.transaction(async (tx) => {\n await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());\n const confirmed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, cancellationStatus: { in: [\"PENDING\", \"REQUESTED\", \"FAILED\"] } },\n data: { cancellationStatus: \"CONFIRMED\", cancellationFailureReason: null },\n });\n return confirmed.count > 0;\n });\n // The store's own request, answered (FUT-4758): a host that cancels on the\n // confirmation hears it as such; any other cancellation is the marketplace's.\n // A redelivered confirmation of a request already answered tells a host\n // with the callback nothing more (it heard the first one).\n const storeAsked = answered || row.cancellationStatus === \"CONFIRMED\";\n const told = storeAsked && (answered ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));\n if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, \"CANCELLED\");\n ctx.ports.publishChanged(input.clientId);\n return true;\n}\n\n","import type { EngineContext, MarketplaceDb } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * External SKU ↔ catalog mapping .\n *\n * The rule the whole module is built around: an unmapped SKU is a ROW, not an\n * absence. Every SKU an order has ever carried has a link row, mapped or not,\n * so the attention list is a query rather than a reconciliation, and mapping\n * one is an update on something the store can already see. Manual mapping\n * upkeep has to be visibly cheap or it does not happen — and a store that stops\n * doing it is a store quietly selling food it cannot make.\n *\n * The package never dereferences `menuItemId`. It asks the host whether the id\n * is theirs (`order.catalogHas`, in `./bulk.ts`) and stores it; what the id\n * MEANS is the host's.\n */\n\n/** A link as every read surface sees it. */\nexport interface MarketplaceMenuLinkView {\n id: string;\n provider: MarketplaceProvider;\n externalSku: string;\n externalName: string;\n /** The host catalog id, or null while the SKU is unmapped. */\n menuItemId: string | null;\n lastSeenAt: Date;\n}\n\nconst LINK_SELECT = {\n id: true,\n provider: true,\n externalSku: true,\n externalName: true,\n menuItemId: true,\n lastSeenAt: true,\n} as const;\n\ninterface LinkRow {\n id: string;\n provider: string;\n externalSku: string;\n externalName: string | null;\n menuItemId: string | null;\n lastSeenAt: Date;\n}\n\nfunction toView(row: LinkRow): MarketplaceMenuLinkView {\n return {\n id: row.id,\n provider: row.provider as MarketplaceProvider,\n externalSku: row.externalSku,\n externalName: row.externalName ?? row.externalSku,\n menuItemId: row.menuItemId,\n lastSeenAt: row.lastSeenAt,\n };\n}\n\n/**\n * A store's SKU map. `unmappedOnly` is the attention list.\n *\n * Ordered by `lastSeenAt` descending, which is the ordering that matters for\n * the unmapped half: a store fixing five mappings should fix the five that are\n * costing them money right now, not the five that happen to be oldest.\n */\nexport async function listMarketplaceMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; provider?: MarketplaceProvider; unmappedOnly?: boolean; ids?: readonly string[] },\n): Promise<MarketplaceMenuLinkView[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceMenuLink.findMany({\n where: {\n clientId: input.clientId,\n ...(input.ids ? { id: { in: [...input.ids] } } : {}),\n ...(input.provider ? { provider: input.provider } : {}),\n ...(input.unmappedOnly ? { menuItemId: null } : {}),\n },\n select: LINK_SELECT,\n orderBy: { lastSeenAt: \"desc\" },\n })) as LinkRow[];\n return rows.map(toView);\n}\n\n/**\n * Point an external SKU at a catalog id, or unmap it, inside the caller's\n * transaction. The caller has already checked the id is this tenant's\n * (`order.catalogHas`). Creates the link if the SKU has never been seen: an\n * operator mapping ahead of the first order is doing the right thing.\n */\nexport async function upsertLink(\n db: MarketplaceDb,\n input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n },\n): Promise<MarketplaceMenuLinkView> {\n const row = (await db.marketplaceMenuLink.upsert({\n where: {\n clientId_provider_externalSku: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: input.externalSku,\n },\n },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: input.externalSku,\n externalName: input.externalName ?? input.externalSku,\n menuItemId: input.menuItemId,\n },\n // `externalName` is NOT rewritten here. It is the marketplace's snapshot of\n // what it called the item, and an operator's typing is not a better record\n // of that than the marketplace's own text.\n update: { menuItemId: input.menuItemId },\n select: LINK_SELECT,\n })) as LinkRow;\n return toView(row);\n}\n\n/**\n * Resolve an order's SKUs to catalog ids, recording every one of them.\n *\n * Called on the ingestion path, so it does two jobs at once and both are\n * required: it answers what each SKU maps to, and it makes sure a row exists\n * for each — including the ones that map to nothing, which is how an unmapped\n * SKU reaches the attention list at all. Upserting on the ingest path is what\n * makes the list self-maintaining; a store never has to discover the gap by\n * reading a ticket.\n */\nexport async function resolveSkus(\n db: MarketplaceDb,\n input: {\n clientId: string;\n provider: MarketplaceProvider;\n skus: { externalSku: string; name: string }[];\n seenAt: Date;\n },\n): Promise<Map<string, string | null>> {\n const resolved = new Map<string, string | null>();\n for (const sku of input.skus) {\n const row = (await db.marketplaceMenuLink.upsert({\n where: {\n clientId_provider_externalSku: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: sku.externalSku,\n },\n },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: sku.externalSku,\n externalName: sku.name,\n lastSeenAt: input.seenAt,\n },\n update: { lastSeenAt: input.seenAt },\n select: { menuItemId: true },\n })) as { menuItemId: string | null };\n resolved.set(sku.externalSku, row.menuItemId);\n }\n return resolved;\n}\n","import {\n listMarketplaceIntegrations,\n saveMarketplaceIntegration,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { upsertLink, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from \"./ports\";\n\n/**\n * The bulk writes: one call, many rows, all-or-nothing.\n *\n * Every row is validated first (cross-row duplicates, unknown providers, a\n * catalog id that is not the store's, an archive of nothing) and every problem\n * is returned with its path; any problem writes nothing. Then ONE transaction\n * writes every row, or none. `validateOnly` validates and writes nothing.\n * Idempotent on the natural key: a connection is `(store, provider)`, a SKU\n * link `(store, provider, externalSku)`.\n */\n\n/** Why a bulk row was refused. Vocabulary, not copy. */\nexport type BulkProblemCode =\n | \"DUPLICATE\"\n | \"UNKNOWN_PROVIDER\"\n | \"NOTHING_TO_UPDATE\"\n | \"NOT_FOUND\"\n | \"CATALOG_ITEM_NOT_FOUND\";\n\nexport interface BulkProblem {\n path: (string | number)[];\n code: BulkProblemCode;\n}\n\nexport type BulkResult<T> =\n | { kind: \"saved\"; validateOnly: boolean; rows: T[] }\n | { kind: \"refused\"; problems: BulkProblem[] };\n\n/** One connection row: an upsert of its settings, an archive, or an unarchive. */\nexport type IntegrationRowInput =\n | ({ operation?: \"upsert\" } & Omit<SaveMarketplaceIntegrationInput, \"clientId\">)\n | { operation: \"archive\" | \"unarchive\"; provider: string; reason?: string | null };\n\n/** One SKU link: map it to a catalog id, or unmap it with `menuItemId: null`. */\nexport interface MenuLinkRowInput {\n provider: string;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n}\n\n/** The key of each row seen twice, as problems. */\nfunction duplicates<T>(rows: readonly T[], keyOf: (row: T) => string, list: string, field: string): BulkProblem[] {\n const seen = new Set<string>();\n return rows.flatMap((row, index) => {\n const key = keyOf(row);\n if (!seen.has(key)) {\n seen.add(key);\n return [];\n }\n return [{ path: [list, index, field], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction unknownProviders(ctx: EngineContext, rows: readonly { provider: string }[], list: string): BulkProblem[] {\n return rows.flatMap((row, index) =>\n ctx.registry.has(row.provider) ? [] : [{ path: [list, index, \"provider\"], code: \"UNKNOWN_PROVIDER\" as const }],\n );\n}\n\nconst SETTING_KEYS = [\"enabled\", \"environment\", \"externalMerchantId\", \"autoAccept\", \"ackSlaSeconds\", \"credentials\"] as const;\n\nfunction integrationRowProblems(\n row: IntegrationRowInput,\n index: number,\n existing: ReadonlySet<string>,\n): BulkProblem[] {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n return existing.has(row.provider) ? [] : [{ path: [\"integrations\", index, \"provider\"], code: \"NOT_FOUND\" }];\n }\n const settings = row as Partial<Record<(typeof SETTING_KEYS)[number], unknown>>;\n const changes = SETTING_KEYS.some((key) => settings[key] !== undefined);\n return changes ? [] : [{ path: [\"integrations\", index], code: \"NOTHING_TO_UPDATE\" }];\n}\n\n/** Thrown inside the transaction to roll a `validateOnly` call back. */\nclass ValidateOnly extends Error {\n constructor() {\n super(\"validate only\");\n }\n}\n\n/** Run `write` in one transaction; a `validateOnly` call is rolled back. */\nasync function inTransaction<T>(ctx: EngineContext, validateOnly: boolean, write: (db: MarketplaceDb) => Promise<T>): Promise<T | null> {\n let written: T | null = null;\n try {\n await ctx.ports.transaction(async (db) => {\n written = await write(db);\n if (validateOnly) throw new ValidateOnly();\n });\n } catch (error) {\n if (!(error instanceof ValidateOnly)) throw error;\n }\n return written;\n}\n\nasync function writeIntegration(\n ctx: EngineContext,\n db: MarketplaceDb,\n clientId: string,\n row: IntegrationRowInput,\n now: Date,\n): Promise<MarketplaceIntegrationView | null> {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n await db.marketplaceIntegration.updateMany({\n where: { clientId, provider: row.provider },\n data: { archivedAt: row.operation === \"archive\" ? now : null },\n });\n return null;\n }\n const settings: Omit<IntegrationRowInput, \"operation\"> & { operation?: unknown } = { ...row };\n delete settings.operation;\n return saveMarketplaceIntegration(ctx, { clientId, ...(settings as Omit<SaveMarketplaceIntegrationInput, \"clientId\">) }, db);\n}\n\n/**\n * Create, patch, archive or unarchive many connections at once. A connection\n * is never deleted: archiving is reversible, and each archive and unarchive is\n * an audit line through the host's `audit` port, in the same transaction.\n */\nexport async function upsertIntegrations(\n ctx: EngineContext,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceIntegrationView>> {\n const existing = new Set(\n (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider),\n );\n const problems = [\n ...duplicates(input.rows, (row) => row.provider, \"integrations\", \"provider\"),\n ...unknownProviders(ctx, input.rows, \"integrations\"),\n ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),\n ];\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const now = ctx.ports.clock.now();\n // The audit lines are written INSIDE the archive's transaction, through its\n // client: an archive never lands without its line, and an audit that fails\n // rolls the archive back. A `validateOnly` call rolls both back.\n await inTransaction(ctx, validateOnly, async (db) => {\n for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);\n await auditArchives(ctx, db, input, now);\n });\n const providers = input.rows.map((row) => row.provider);\n const rows = validateOnly\n ? []\n : await listMarketplaceIntegrations(ctx, input.clientId, { providers, includeArchived: true });\n return { kind: \"saved\", validateOnly, rows };\n}\n\nasync function auditArchives(\n ctx: EngineContext,\n db: MarketplaceDb,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[] },\n now: Date,\n): Promise<void> {\n for (const row of input.rows) {\n if (row.operation !== \"archive\" && row.operation !== \"unarchive\") continue;\n const entry: MarketplaceAuditEntry = {\n clientId: input.clientId,\n actorId: input.actorId,\n action: row.operation === \"archive\" ? \"marketplace.integration.archive\" : \"marketplace.integration.unarchive\",\n provider: row.provider,\n reason: row.reason ?? null,\n at: now,\n };\n await ctx.ports.audit.record(entry, db);\n }\n}\n\n/** Map or unmap many SKUs at once; every catalog id must be the store's. */\nexport async function upsertMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; rows: readonly MenuLinkRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceMenuLinkView>> {\n const problems = [\n ...duplicates(input.rows, (row) => `${row.provider}\\u0000${row.externalSku}`, \"links\", \"externalSku\"),\n ...unknownProviders(ctx, input.rows, \"links\"),\n ];\n for (const [index, row] of input.rows.entries()) {\n if (row.menuItemId !== null && !(await ctx.ports.order.catalogHas(input.clientId, row.menuItemId))) {\n problems.push({ path: [\"links\", index, \"menuItemId\"], code: \"CATALOG_ITEM_NOT_FOUND\" });\n }\n }\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const written = await inTransaction(ctx, validateOnly, async (db) => {\n const rows: MarketplaceMenuLinkView[] = [];\n for (const row of input.rows) rows.push(await upsertLink(db, { clientId: input.clientId, ...row }));\n return rows;\n });\n return { kind: \"saved\", validateOnly, rows: written ?? [] };\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport {\n CLAIM_SELECT,\n NO_STANDING_REQUEST,\n notPendingProblem,\n planCancellation,\n refusalData,\n requestData,\n type CancellationPlan,\n type ClaimRow,\n type DecisionProblem,\n type DecisionProblemCode,\n} from \"./cancellation\";\nimport { requestsFirst, tellCancellationFailed } from \"./cancellation-outcome\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceAdmission, MarketplaceDb } from \"./ports\";\n\n/**\n * The store's decisions on orders on the clock — ONE path for every surface\n * (the host's board, the admin route, the MCP tool), and all-or-nothing:\n *\n * 1. every decision is validated against its row (still AWAITING, the reason\n * the marketplace's, the offending SKUs the order's) before anything runs;\n * 2. inside ONE transaction the host ADMITS each decision (`order.admit`: the\n * stock ask, the draw) and the engine claims each row on `AWAITING`. A\n * host refusal or a lost claim rolls the whole call back;\n * 3. after the commit, each outbound call is QUEUED FIRST, then the host's\n * half runs (`onAccepted` / `onRefused`). A host half that throws cannot\n * lose the call; it is logged, and the decision stands.\n *\n * A queue that refuses the job loses nothing either: the outbound sweep\n * (`./outbound-sweep.ts`) re-queues every request still owed.\n */\n\n/** The two things a person can do to an order on the clock. */\nexport type AcceptanceDecision = \"ACCEPT\" | \"REJECT\";\n\n/** One decision, as a caller states it. */\nexport type DecisionInput =\n | {\n orderId: string;\n decision: \"ACCEPT\";\n /** What the person confirmed, for the host's admission. */\n admission?: MarketplaceAdmission;\n /** Minutes to prepare, for a marketplace whose confirm states one. */\n preparationMinutes?: number | null;\n }\n | {\n orderId: string;\n decision: \"REJECT\";\n /** One of the marketplace's codes; its first reason when absent. */\n reasonCode?: string | null;\n /** The order's SKUs a reason that `needsItems` names. */\n offendingSkus?: readonly string[];\n };\n\n/**\n * One decided row. `status` is the row's status after the call: ACCEPTED or\n * REJECTED, or — for a refusal of a host that requests first (FUT-4758) —\n * the status it keeps (AWAITING, ACCEPTED) while `cancellation` waits.\n */\nexport interface DecidedRow {\n orderId: string;\n status: AcceptanceStatus;\n cancellation: CancellationStatus | null;\n reasonCode: string | null;\n offendingSkus: string[];\n}\n\n/** What a call did: every row decided, or nothing written and every problem named. */\nexport type DecideManyResult =\n | { kind: \"decided\"; validateOnly: boolean; rows: DecidedRow[] }\n | { kind: \"refused\"; problems: DecisionProblem[] };\n\n/** One decision's result, for a caller deciding one order. */\nexport type DecisionResult =\n | ({ kind: \"decided\" } & DecidedRow)\n | {\n kind: \"stale\";\n /** Why: gone, decided already (I4: answer it as done), expired, or lost to a race. */\n reason: Extract<DecisionProblemCode, \"NOT_FOUND\" | \"ALREADY_DECIDED\" | \"EXPIRED\" | \"CONFLICT\">;\n status: AcceptanceStatus | null;\n }\n | {\n kind: \"invalidReason\";\n problem: Extract<DecisionProblemCode, \"INVALID_REASON\" | \"ITEMS_REQUIRED\" | \"UNKNOWN_ITEM\">;\n validCodes: string[];\n }\n | { kind: \"refusedByHost\"; code: string; message: string; details?: unknown };\n\n/** A planned decision: the row, the claim's data, and what it becomes. */\ninterface PlannedDecision {\n input: DecisionInput;\n index: number;\n row: ClaimRow;\n data: Record<string, unknown>;\n decided: DecidedRow;\n /** A refusal that only REQUESTS the cancellation: the host cancels on the marketplace's confirmation. */\n requestOnly: boolean;\n}\n\n/** Thrown inside the transaction to roll it back, carrying the reason. */\nclass Rollback extends Error {\n constructor(readonly problems: DecisionProblem[] | null) {\n super(\"rollback\");\n }\n}\n\nfunction duplicateProblems(decisions: readonly DecisionInput[]): DecisionProblem[] {\n const seen = new Set<string>();\n return decisions.flatMap((decision, index) => {\n if (!seen.has(decision.orderId)) {\n seen.add(decision.orderId);\n return [];\n }\n return [{ path: [\"decisions\", index, \"orderId\"], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction decidedOf(input: DecisionInput, plan: CancellationPlan | null, keptStatus?: string): DecidedRow {\n const decided: AcceptanceStatus = input.decision === \"ACCEPT\" ? \"ACCEPTED\" : \"REJECTED\";\n return {\n orderId: input.orderId,\n status: (keptStatus as AcceptanceStatus | undefined) ?? decided,\n cancellation: plan?.status ?? null,\n reasonCode: plan?.reason?.code ?? null,\n offendingSkus: plan?.skus ?? [],\n };\n}\n\n/** Plan one decision against its row, or name what is wrong with it. */\n/** The columns of a request that no longer stands, cleared. */\nconst CLEARED_REQUEST = {\n cancellationStatus: null,\n cancellationReasonCode: null,\n cancellationOffendingSkus: null,\n cancellationRequestedAt: null,\n cancellationFailureReason: null,\n} as const;\n\nfunction planOne(\n ctx: EngineContext,\n input: DecisionInput,\n index: number,\n row: ClaimRow | undefined,\n now: Date,\n): PlannedDecision | DecisionProblem[] {\n const path = [\"decisions\", index];\n const stale = notPendingProblem(row, path);\n if (stale || !row) return stale ? [stale] : [];\n if (input.decision === \"ACCEPT\") {\n // An accept after a FAILED request (FUT-4758) leaves no request behind it.\n const data = {\n status: \"ACCEPTED\",\n acknowledgedAt: now,\n preparationMinutes: input.preparationMinutes ?? null,\n ...(row.cancellationStatus === null ? {} : CLEARED_REQUEST),\n };\n return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };\n }\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);\n if (Array.isArray(plan)) return plan;\n if (requestOnly(ctx, plan)) {\n return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };\n }\n return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };\n}\n\n/**\n * Whether a refusal only REQUESTS the cancellation (FUT-4758): the host\n * requests first (it binds `onCancellationConfirmed`), and there is a request\n * to make — PENDING, or FAILED at once for a marketplace that cannot take it\n * through its API (a person cancels in its app, and its event confirms). A\n * provider with no adapter has nothing to ask: refused at once, as ever.\n */\nfunction requestOnly(ctx: EngineContext, plan: CancellationPlan): boolean {\n return requestsFirst(ctx) && plan.status !== null;\n}\n\n/** Admit every decision through the host, then claim every row, in one transaction. */\nasync function admitAndClaim(\n ctx: EngineContext,\n clientId: string,\n planned: readonly PlannedDecision[],\n validateOnly: boolean,\n): Promise<void> {\n await ctx.ports.transaction(async (tx: MarketplaceDb) => {\n const refused: DecisionProblem[] = [];\n for (const one of planned) {\n const admission = one.input.decision === \"ACCEPT\" ? (one.input.admission ?? {}) : {};\n const answer = await ctx.ports.order.admit({\n clientId,\n orderId: one.input.orderId,\n decision: one.input.decision,\n admission,\n db: tx,\n });\n if (!answer.admitted) {\n const host = { code: answer.code, message: answer.message, details: answer.details };\n refused.push({ path: [\"decisions\", one.index], code: \"HOST_REFUSED\", host });\n }\n }\n if (refused.length > 0) throw new Rollback(refused);\n for (const one of planned) {\n const claimed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: one.input.orderId, clientId, status: \"AWAITING\", ...NO_STANDING_REQUEST },\n data: one.data,\n });\n if (claimed.count === 0) refused.push({ path: [\"decisions\", one.index, \"orderId\"], code: \"CONFLICT\" });\n }\n if (refused.length > 0) throw new Rollback(refused);\n if (validateOnly) throw new Rollback(null);\n });\n}\n\n/** After the commit: queue each owed call FIRST, then the host's half, which may not lose it. */\nasync function afterCommit(ctx: EngineContext, clientId: string, planned: readonly PlannedDecision[]): Promise<void> {\n for (const one of planned) {\n const { orderId } = one.input;\n if (one.input.decision === \"ACCEPT\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, one.row.provider);\n } else if (one.decided.cancellation === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"requestCancellation\" }, one.row.provider);\n }\n try {\n if (one.decided.status === \"ACCEPTED\" && one.input.decision === \"ACCEPT\") await ctx.ports.order.onAccepted(clientId, orderId);\n else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, \"REJECTED\");\n // A request the marketplace cannot take through its API failed at once:\n // the order stays, and a person cancels it in the marketplace's app.\n else if (one.decided.cancellation === \"FAILED\") await tellCancellationFailed(ctx, clientId, orderId, \"REFUSED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n ctx.ports.publishChanged(clientId);\n}\n\n/** Read every row a call names, in one statement. */\nasync function readRows(ctx: EngineContext, clientId: string, orderIds: string[]): Promise<Map<string, ClaimRow>> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: orderIds } },\n select: CLAIM_SELECT,\n })) as ClaimRow[];\n return new Map(rows.map((row) => [row.orderId, row]));\n}\n\n/**\n * Decide many orders at once, all-or-nothing. `validateOnly` runs everything —\n * the host's admission included — and rolls it back.\n */\nexport async function decideMany(\n ctx: EngineContext,\n input: { clientId: string; decisions: readonly DecisionInput[]; validateOnly?: boolean; now?: Date },\n): Promise<DecideManyResult> {\n const duplicates = duplicateProblems(input.decisions);\n if (duplicates.length > 0) return { kind: \"refused\", problems: duplicates };\n const now = input.now ?? ctx.ports.clock.now();\n const rows = await readRows(ctx, input.clientId, input.decisions.map((decision) => decision.orderId));\n\n const planned: PlannedDecision[] = [];\n const problems: DecisionProblem[] = [];\n input.decisions.forEach((decision, index) => {\n const plan = planOne(ctx, decision, index, rows.get(decision.orderId), now);\n if (Array.isArray(plan)) problems.push(...plan);\n else planned.push(plan);\n });\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n try {\n await admitAndClaim(ctx, input.clientId, planned, validateOnly);\n } catch (error) {\n if (!(error instanceof Rollback)) throw error;\n if (error.problems) return { kind: \"refused\", problems: error.problems };\n }\n if (!validateOnly) await afterCommit(ctx, input.clientId, planned);\n return { kind: \"decided\", validateOnly, rows: planned.map((one) => one.decided) };\n}\n\nconst STALE_CODES = new Set<DecisionProblemCode>([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** One decision's problem, as the single-order result names it. */\nfunction resultOfProblem(problem: DecisionProblem): DecisionResult {\n if (problem.code === \"HOST_REFUSED\") {\n const host = problem.host ?? { code: \"\", message: \"\" };\n return { kind: \"refusedByHost\", code: host.code, message: host.message, details: host.details };\n }\n if (STALE_CODES.has(problem.code)) {\n const reason = problem.code as Extract<DecisionResult, { kind: \"stale\" }>[\"reason\"];\n return { kind: \"stale\", reason, status: problem.status ?? null };\n }\n const invalid = problem.code as Extract<DecisionResult, { kind: \"invalidReason\" }>[\"problem\"];\n return { kind: \"invalidReason\", problem: invalid, validCodes: problem.validCodes ?? [] };\n}\n\n/** Decide ONE order: `decideMany` with one decision. */\nexport async function decideOne(\n ctx: EngineContext,\n input: { clientId: string; now?: Date } & DecisionInput,\n): Promise<DecisionResult> {\n const { clientId, now, ...decision } = input;\n const result = await decideMany(ctx, { clientId, decisions: [decision as DecisionInput], now });\n if (result.kind === \"decided\") {\n const [row] = result.rows;\n if (row) return { kind: \"decided\", ...row };\n }\n const [problem] = result.kind === \"refused\" ? result.problems : [];\n return problem ? resultOfProblem(problem) : { kind: \"stale\", reason: \"CONFLICT\", status: null };\n}\n\n/**\n * The STORE asks to cancel an order — before or after accepting it. Stamps\n * the request the marketplace must hear and queues it; the engine neither\n * admits nor calls `onRefused`: it records and queues, and nothing else.\n *\n * REQUEST FIRST (FUT-4758), for a host that binds `onCancellationConfirmed`:\n * only the request moves. The decision status stays AWAITING or ACCEPTED while\n * the marketplace answers, so the host keeps the order as it was until then,\n * and a refused or timed-out request (`onCancellationFailed`) leaves it\n * acceptable. The marketplace's confirmation moves it to REJECTED. A FAILED\n * request may be asked again. A host that binds no `onCancellationConfirmed`\n * cancelled first and gets 1.0.0's stamps exactly: REJECTED at once.\n *\n * The returned row's `status` is the row's after the call.\n *\n * `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the\n * clock lapsed (EXPIRED), or a request is already waiting.\n */\nexport async function recordStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; reasonCode?: string | null; offendingSkus?: readonly string[]; now?: Date },\n): Promise<DecisionResult> {\n const row = (await readRows(ctx, input.clientId, [input.orderId])).get(input.orderId);\n const stale = notPendingProblem(row, [], [\"AWAITING\", \"ACCEPTED\"]);\n if (stale || !row) return stale ? resultOfProblem(stale) : { kind: \"stale\", reason: \"NOT_FOUND\", status: null };\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);\n if (Array.isArray(plan)) return resultOfProblem(plan[0]!);\n\n return claimStoreCancellation(ctx, input, row, plan);\n}\n\n/** Stamp the store's cancellation (the request alone, or 1.0.0's REJECTED), queue it, and tell the host. */\nasync function claimStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; now?: Date },\n row: ClaimRow,\n plan: CancellationPlan,\n): Promise<DecisionResult> {\n const now = input.now ?? ctx.ports.clock.now();\n const db = await ctx.ports.db();\n const only = requestOnly(ctx, plan);\n const claimed = await db.marketplaceAcceptance.updateMany({\n where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },\n data: only ? requestData(plan, now) : refusalData(plan, row.status, now),\n });\n if (claimed.count === 0) return { kind: \"stale\", reason: \"CONFLICT\", status: null };\n if (plan.status === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: \"requestCancellation\" }, row.provider);\n }\n ctx.ports.publishChanged(input.clientId);\n if (only && plan.status === \"FAILED\") await tellCancellationFailed(ctx, input.clientId, input.orderId, \"REFUSED\");\n return { kind: \"decided\", ...decidedOf({ orderId: input.orderId, decision: \"REJECT\" }, plan, only ? row.status : undefined) };\n}\n","import type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent } from \"./types\";\n\n/**\n * The durable inbox , needed here for two reasons rather than one.\n *\n * A marketplace's delivery is not reliably exactly-once, so the SAME event\n * arrives more than once and the pipeline must be able to say \"already seen\".\n * It is not reliably at-least-once either, so reconciliation polling has to be\n * able to inject an event the webhook never brought. Both paths write here, and\n * `(provider, eventId)` is what collapses them onto one row — a duplicate is a\n * DB-level no-op rather than a second order.\n *\n * The RAW payload is stored because normalization is the part most likely to be\n * wrong. When a mapping bug drops a line, the only way to reconstruct what the\n * marketplace actually said is to have kept it.\n */\n\n/** What {@link recordInboxEvent} tells the caller about a delivery. */\ninterface InboxRecord {\n id: string;\n /** False when this exact delivery had already been recorded. */\n fresh: boolean;\n}\n\n/**\n * Record one delivery, deduped on `(provider, eventId)`.\n *\n * Returns `fresh: false` for a redelivery, which is the pipeline's whole\n * idempotency story at the door: the caller stops there and answers the\n * marketplace 200. Answering 200 to a duplicate matters as much as processing\n * the original — a marketplace that gets an error redelivers, and a pipeline\n * that errors on its own duplicates never stops receiving them.\n */\nexport async function recordInboxEvent(\n ctx: EngineContext,\n input: { clientId: string | null; event: NormalizedEvent; payload: unknown },\n): Promise<InboxRecord> {\n const db = await ctx.ports.db();\n const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };\n const existing = (await db.marketplaceInboxEvent.findUnique({\n where: key,\n select: { id: true },\n })) as { id: string } | null;\n if (existing) return { id: existing.id, fresh: false };\n\n try {\n const row = (await db.marketplaceInboxEvent.create({\n data: {\n clientId: input.clientId,\n provider: input.event.provider,\n eventId: input.event.eventId,\n eventType: input.event.eventType,\n externalOrderId: input.event.externalOrderId,\n payload: input.payload,\n },\n select: { id: true },\n })) as { id: string };\n return { id: row.id, fresh: true };\n } catch (error) {\n // The check-then-insert above is not atomic, and two simultaneous\n // redeliveries are exactly the shape that loses that race. The unique index\n // is the real guard; this turns losing the race into the same answer the\n // check would have given, rather than a 500 that provokes another retry.\n if ((error as { code?: string }).code !== \"P2002\") throw error;\n const raced = (await db.marketplaceInboxEvent.findUnique({\n where: key,\n select: { id: true },\n })) as { id: string } | null;\n return { id: raced?.id ?? \"\", fresh: false };\n }\n}\n\n/** How an inbox row ended up. */\ntype InboxOutcome = \"PROCESSED\" | \"FAILED\" | \"IGNORED\";\n\n/**\n * Close out an inbox row.\n *\n * `attempts` increments on every close, including the successful one, so the\n * count reads as \"how many times did we touch this\" rather than \"how many times\n * did we fail\" — a row PROCESSED on its third attempt is a different story from\n * one processed on its first, and only the incrementing version can tell them\n * apart.\n */\nexport async function settleInboxEvent(\n ctx: EngineContext,\n id: string,\n outcome: InboxOutcome,\n error?: string,\n): Promise<void> {\n if (!id) return;\n const db = await ctx.ports.db();\n await db.marketplaceInboxEvent.update({\n where: { id },\n data: {\n status: outcome,\n // Truncated: a provider's error body can be a page of HTML, and the\n // column exists to be read by a human in a list.\n error: error ? error.slice(0, 500) : null,\n processedAt: ctx.ports.clock.now(),\n attempts: { increment: 1 },\n },\n });\n}\n\n/**\n * Leave a row PENDING with its reason recorded, and count the attempt.\n *\n * The state between \"done\" and \"broken\": the delivery is fine and the STORE is\n * not ready for it — the channel is switched off, or was mid-onboarding when\n * the order came in. Settling it either way would be a lie (IGNORED discards an\n * order that could still be ingested; FAILED blames the payload), so it stays\n * PENDING and the sweep picks it up again.\n *\n * The attempt still counts, which is what stops the churn: the sweep's own\n * attempt bound retires a row after a few passes over a store that never turned\n * the channel on, instead of re-reading it forever.\n */\nexport async function deferInboxEvent(\n ctx: EngineContext,\n id: string,\n reason: string,\n): Promise<void> {\n if (!id) return;\n const db = await ctx.ports.db();\n await db.marketplaceInboxEvent.update({\n where: { id },\n data: { error: reason.slice(0, 500), attempts: { increment: 1 } },\n });\n}\n\n/** One stored delivery, as the retry sweep re-reads it. */\nexport interface PendingInboxEvent {\n id: string;\n clientId: string;\n provider: MarketplaceProvider;\n payload: unknown;\n}\n\n/**\n * Deliveries recorded but never processed, oldest first.\n *\n * PENDING and FAILED both qualify: a row left PENDING is one whose process died\n * between recording and processing — the exact crash the durable inbox exists\n * to survive — and dropping it would make the inbox a log rather than a queue.\n *\n * Unattributed events (`clientId` null) are deliberately NOT returned. There is\n * no tenant to ingest them into, so retrying achieves nothing; they stay in the\n * table as the evidence of a half-finished onboarding.\n */\nexport async function listRetryableInboxEvents(\n ctx: EngineContext,\n): Promise<PendingInboxEvent[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceInboxEvent.findMany({\n where: {\n status: { in: [\"PENDING\", \"FAILED\"] },\n clientId: { not: null },\n attempts: { lt: ctx.ports.maxInboxAttempts },\n },\n orderBy: { receivedAt: \"asc\" },\n take: ctx.ports.reconcileBatchSize,\n select: { id: true, clientId: true, provider: true, payload: true },\n })) as { id: string; clientId: string; provider: string; payload: unknown }[];\n return rows.map((row) => ({\n id: row.id,\n clientId: row.clientId,\n provider: row.provider as MarketplaceProvider,\n payload: row.payload,\n }));\n}\n","import { markMarketplaceEventSeen } from \"./integration\";\nimport { resolveSkus } from \"./menu-links\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceDb, ResolvedOrderLine } from \"./ports\";\nimport type { NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * Normalized marketplace order → the host's own order.\n *\n * The rule this module is written around, stated once so every decision below\n * reads against it: **losing a paid marketplace order is the one unforgivable\n * failure.** An unmapped SKU, a buyer with no name, a total that does not equal\n * the line sum — none of them reject the order. They land, flagged, on a screen\n * a human can act on. The only thing that stops an ingestion is a condition\n * under which persisting would be WRONG rather than incomplete.\n *\n * Idempotent on `(provider, externalOrderId)`, which the acceptance table's\n * unique enforces. That is what makes a redelivered webhook, a reconciliation\n * poll racing it, and a retry after a crash all safe: each either creates the\n * one order or finds it already there. The pre-read below is a fast path, not\n * the guarantee — two concurrent deliveries both miss it and only one of them\n * reaches a row.\n */\n\n/** What one ingestion did. */\nexport interface IngestResult {\n /** The HOST's order id. */\n orderId: string;\n /** False when the order already existed — a redelivery, not a second sale. */\n created: boolean;\n /** SKUs that arrived with nothing behind them, in this order. */\n unmappedSkus: string[];\n /** Whether the connection's policy made this order born accepted. */\n autoAccepted: boolean;\n}\n\n/** The store's operating decisions, read from the connection at ingest time. */\nexport interface IngestSettings {\n autoAccept: boolean;\n ackSlaSeconds: number;\n}\n\n/**\n * Resolve the order's SKUs and compose its lines.\n *\n * `resolveSkus` does double duty on this path: it answers what each SKU maps to\n * AND records every one of them, which is how an unmapped SKU reaches the\n * store's attention list without anyone having to notice it first.\n */\nasync function composeLines(\n db: MarketplaceDb,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n seenAt: Date,\n): Promise<ResolvedOrderLine[]> {\n const mapping = await resolveSkus(db, {\n clientId,\n provider: order.provider,\n skus: order.lines.map((line) => ({ externalSku: line.externalSku, name: line.name })),\n seenAt,\n });\n return order.lines.map((line) => ({\n externalSku: line.externalSku,\n // The MARKETPLACE's text, never the catalog's, even for a mapped line.\n // Every other order snapshots what the buyer was shown, and what this buyer\n // was shown is the marketplace's menu — a mapped line renamed to the host's\n // own product name would quietly disagree with the receipt in the bag.\n name: line.name,\n quantity: line.quantity,\n unitPriceCents: line.unitPriceCents,\n note: line.note,\n subjectRef: mapping.get(line.externalSku) ?? null,\n }));\n}\n\n/** The acceptance row an ingest writes: born ACCEPTED or on the clock. */\nfunction acceptanceData(\n clientId: string,\n orderId: string,\n order: NormalizedMarketplaceOrder,\n settings: IngestSettings,\n now: Date,\n): Record<string, unknown> {\n const accepted = settings.autoAccept;\n return {\n clientId,\n orderId,\n provider: order.provider,\n externalOrderId: order.externalOrderId,\n externalDisplayId: order.externalDisplayId,\n // Who carries a delivery: the merchant's courier or the marketplace's fleet.\n deliveredBy: order.deliveredBy ?? null,\n status: accepted ? \"ACCEPTED\" : \"AWAITING\",\n acknowledgeBy: new Date(now.getTime() + settings.ackSlaSeconds * 1000),\n acknowledgedAt: accepted ? now : null,\n externalDueAt: order.deliveryDueAt,\n commissionCents: order.commissionCents,\n // The order's SKUs: what a cancellation's offending SKUs are checked against.\n lineSkus: [...new Set(order.lines.map((line) => line.externalSku))],\n };\n}\n\n/**\n * Ingest one order.\n *\n * The deadline is stamped HERE, from the connection's SLA, and never recomputed\n * afterwards: a store that later lengthens its SLA must not move the deadline of\n * an order already on the clock, and one that shortens it must not retroactively\n * expire orders that were fine when they arrived.\n *\n * The acceptance row and the host's order are written in that dependency order\n * — the host creates its own row first and hands back an id, because only the\n * host knows what creating one costs. Auto-accept is decided at arrival so the\n * order is BORN accepted rather than created and immediately updated: the\n * two-step version has a window in which a crash leaves an order the store\n * believes was auto-accepted sitting on a clock nobody is watching.\n */\nexport async function ingestMarketplaceOrder(\n ctx: EngineContext,\n input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n },\n): Promise<IngestResult> {\n const { clientId, order, settings } = input;\n const now = input.now ?? ctx.ports.clock.now();\n\n const db = await ctx.ports.db();\n // Answered from this package's OWN table rather than through a port: the\n // idempotency key is `(provider, externalOrderId)` on `marketplace_acceptances`,\n // so the package holds it and no host has to be trusted to re-implement it.\n const existing = (await db.marketplaceAcceptance.findFirst({\n where: { provider: order.provider, externalOrderId: order.externalOrderId },\n select: { orderId: true },\n })) as { orderId: string } | null;\n if (existing) {\n return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };\n }\n\n const accepted = settings.autoAccept;\n // ONE transaction for the host's order, the SKU rows, the acceptance row and\n // the liveness stamp: the host's `create` is handed the transaction's client,\n // so an acceptance that cannot be written (a concurrent ingest won the\n // unique) rolls the host's order back with it, and a redelivery never meets\n // an orphan host order to duplicate.\n const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {\n const lines = await composeLines(tx, clientId, order, now);\n const created = await ctx.ports.order.create(clientId, order, lines, tx);\n await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now) });\n await markMarketplaceEventSeen(tx, clientId, order.provider, now);\n return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };\n });\n\n if (accepted) {\n // Born accepted is still an acceptance the marketplace must hear about.\n // Queued FIRST, never called (no ingest waits on a marketplace's API), so\n // a host half that throws cannot lose it; the sweep re-queues it if the\n // queue refused it.\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, order.provider);\n await ctx.ports.order.onAccepted(clientId, orderId);\n }\n\n ctx.ports.publishChanged(clientId);\n\n return { orderId, created: true, unmappedSkus, autoAccepted: accepted };\n}\n","import { cancelAcceptance } from \"./acceptance\";\nimport { failCancellationRequest } from \"./cancellation\";\nimport { deferInboxEvent, recordInboxEvent, settleInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestSettings } from \"./ingest\";\nimport { resolveIngestionTarget } from \"./integration\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent } from \"./types\";\n\n/**\n * One delivery, start to finish: normalize → inbox → ingest.\n *\n * The ONE path both producers use. The webhook calls it, and so does the\n * reconciliation retry sweep — which is the whole reason it is a module rather\n * than the body of a route handler. Two producers with two copies of this\n * sequence is how a webhook and a poll come to disagree about what an order is,\n * and the disagreement only shows up on the orders that took the unlucky path.\n */\n\n/**\n * Normalize a raw payload through the provider's adapter, or null when no\n * adapter is registered for it or the adapter refuses the payload. The\n * registry is the only dispatch: there is no provider branch here.\n */\nexport function normalizeEvent(\n ctx: EngineContext,\n provider: MarketplaceProvider,\n payload: unknown,\n): NormalizedEvent | null {\n return ctx.registry.get(provider)?.normalize(payload) ?? null;\n}\n\n/** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */\nexport type DeliveryOutcome =\n | { kind: \"ingested\"; orderId: string; unmappedSkus: string[] }\n | { kind: \"cancelled\" }\n | { kind: \"cancellationFailed\" }\n | { kind: \"duplicate\" }\n | { kind: \"ignored\"; reason: string }\n | { kind: \"failed\"; reason: string };\n\n/**\n * Process one delivery for one tenant.\n *\n * NEVER throws. Every failure is caught, recorded on the inbox row, and\n * returned — because the caller is a webhook handler whose answer decides\n * whether the marketplace redelivers, and a 500 out of here would make an\n * ingestion bug indistinguishable from a network one while multiplying the\n * traffic that hits it.\n *\n * The delivery is recorded BEFORE it is processed. That ordering is the durable\n * part of the durable inbox: a process that dies mid-ingest leaves a PENDING\n * row the sweep will retry, whereas processing first and recording after loses\n * the event entirely on exactly the crashes worth surviving.\n */\nexport async function processDelivery(\n ctx: EngineContext,\n input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n },\n): Promise<DeliveryOutcome> {\n const { clientId, event, settings } = input;\n const record = await recordInboxEvent(ctx, { clientId, event, payload: input.payload });\n if (!record.fresh) return { kind: \"duplicate\" };\n\n if (!clientId || !settings) {\n // Stored, not dropped, and the two reasons are kept apart because only one\n // of them is a problem. An order naming a merchant no tenant claims is the\n // loudest possible symptom of a half-finished onboarding, and it is only\n // findable later because the row survived. An order for a store that has\n // simply switched the channel off is not a fault at all — it stays PENDING\n // for the retry sweep to pick up if the store switches it back on.\n const reason = clientId ? \"integration is not enabled\" : \"no tenant claims this merchant\";\n if (clientId) await deferInboxEvent(ctx, record.id, reason);\n else await settleInboxEvent(ctx, record.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n try {\n return await applyEvent(ctx, record.id, clientId, event, settings, input.now);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, record.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n\n/**\n * Act on one recorded delivery: cancel, ingest, or deliberately nothing.\n *\n * Extracted so both producers share the ACTION as well as the recording — the\n * webhook and the retry sweep differ only in how they arrived here and in what\n * they do with a throw, never in what an event MEANS.\n */\nasync function applyEvent(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n event: NormalizedEvent,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const outcome = event.cancellationOutcome ?? (event.cancelled ? \"CONFIRMED\" : null);\n if (outcome === \"FAILED\" && event.externalOrderId) {\n // The marketplace refused the store's own cancellation request. Understood\n // and recorded, never IGNORED: it is what tells a person to finish the\n // cancellation on the marketplace's side.\n await failCancellationRequest(ctx, {\n clientId,\n provider: event.provider,\n externalOrderId: event.externalOrderId,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancellationFailed\" };\n }\n\n if (event.cancelled && event.externalOrderId) {\n await cancelAcceptance(ctx, {\n clientId,\n provider: event.provider,\n externalOrderId: event.externalOrderId,\n now,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancelled\" };\n }\n\n if (!event.order) {\n // An event type this ingestion does not act on. Marketplaces emit a wide\n // stream (dispatched, concluded, driver assigned…) and most of it is not an\n // order; IGNORED says \"understood, nothing to do\" and keeps it out of the\n // retry sweep, which FAILED would not.\n const reason = `no order body on ${event.eventType}`;\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n const result = await ingestMarketplaceOrder(ctx, {\n clientId,\n order: event.order,\n settings,\n now,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"ingested\", orderId: result.orderId, unmappedSkus: result.unmappedSkus };\n}\n\n/**\n * Re-run a delivery already sitting in the inbox.\n *\n * Used by the retry sweep. It re-reads the store's CURRENT settings rather than\n * whatever they were when the event first arrived — a store that connected the\n * channel properly an hour after the first order came in should have that order\n * ingested on the retry, which is the case this exists for.\n */\nexport async function reprocessStoredDelivery(\n ctx: EngineContext,\n input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown },\n): Promise<DeliveryOutcome> {\n const event = normalizeEvent(ctx, input.provider, input.payload);\n if (!event) {\n const reason = \"payload no longer normalizes\";\n await settleInboxEvent(ctx, input.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n const target = await resolveIngestionTarget(ctx, input.clientId, input.provider);\n if (!target?.enabled) {\n // Still not ready. Deferred rather than settled, for the same reason as on\n // arrival — and the attempt counter is what eventually retires it, so a\n // store that never switches the channel on does not have its inbox re-read\n // forever.\n const reason = \"integration is not enabled\";\n await deferInboxEvent(ctx, input.id, reason);\n return { kind: \"ignored\", reason };\n }\n try {\n return await applyEvent(\n ctx,\n input.id,\n input.clientId,\n event,\n { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },\n undefined,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, input.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport type { CancellationFailureReason, EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * What the host's order reads need to draw a marketplace order: where its\n * aceite and its cancellation request stand, and where a person goes when the\n * API could not do it. One read for a batch, so a list stays one statement.\n */\nexport interface MarketplaceOrderState {\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: AcceptanceStatus;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellation: CancellationStatus | null;\n cancellationReasonCode: string | null;\n /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */\n cancellationFailure: CancellationFailureReason | null;\n /** The adapter's app link, or null when no adapter is registered for it. */\n appUrl: string | null;\n}\n\ninterface StateRow {\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 cancellationFailureReason: string | null;\n}\n\n/** The state of each of these orders that is a marketplace order, keyed by id. */\nexport async function readOrderStates(\n ctx: EngineContext,\n clientId: string,\n orderIds: readonly string[],\n): Promise<Map<string, MarketplaceOrderState>> {\n if (orderIds.length === 0) return new Map();\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: [...orderIds] } },\n 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 cancellationFailureReason: true,\n },\n })) as StateRow[];\n return new Map(\n rows.map((row) => {\n const adapter = ctx.registry.get(row.provider);\n const state: MarketplaceOrderState = {\n orderId: row.orderId,\n provider: row.provider,\n externalOrderId: row.externalOrderId,\n externalDisplayId: row.externalDisplayId,\n status: row.status as AcceptanceStatus,\n confirmedAt: row.confirmedAt,\n confirmFailedAt: row.confirmFailedAt,\n cancellation: row.cancellationStatus as CancellationStatus | null,\n cancellationReasonCode: row.cancellationReasonCode,\n cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,\n appUrl: adapter ? adapter.appLink(row) : null,\n };\n return [row.orderId, state];\n }),\n );\n}\n","import {\n cancelAcceptance,\n expireLapsedAcceptances,\n listPendingAcceptances,\n type ExpirySweepResult,\n type PendingAcceptance,\n} from \"./acceptance\";\nimport {\n upsertIntegrations,\n upsertMenuLinks,\n type BulkResult,\n type IntegrationRowInput,\n type MenuLinkRowInput,\n} from \"./bulk\";\nimport {\n decideMany,\n decideOne,\n recordStoreCancellation,\n type DecideManyResult,\n type DecisionInput,\n type DecisionResult,\n} from \"./decisions\";\nimport { sweepOutbound, type OutboundSweepResult } from \"./outbound-sweep\";\nimport type {\n AdapterTokenCache,\n CancellationReason,\n MarketplaceAdapter,\n OutboundOrderRef,\n} from \"./adapter\";\nimport { listRetryableInboxEvents, type PendingInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from \"./ingest\";\nimport {\n listMarketplaceIntegrations,\n resolveIngestionTarget,\n resolveTenantByMerchant,\n saveMarketplaceIntegration,\n type IngestionTarget,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport { runOutbound, type OutboundAttempt, type OutboundOutcome } from \"./outbound\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport {\n normalizeEvent,\n processDelivery,\n reprocessStoredDelivery,\n type DeliveryOutcome,\n} from \"./pipeline\";\nimport type { EngineContext, MarketplaceEngineConfig } from \"./ports\";\nimport { createAdapterRegistry, suggestReason } from \"./registry\";\nimport { readOrderStates, type MarketplaceOrderState } from \"./state\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/** Everything the mounted engine can do, with the ports and adapters bound in. */\nexport interface MarketplaceEngine {\n /** Every registered marketplace, in registration order. */\n providers(): readonly MarketplaceProvider[];\n /** Whether a provider id (a URL segment, a body field) names a registered adapter. */\n knows(provider: string): provider is MarketplaceProvider;\n /** The adapter itself: its capabilities, reasons and app link. Null when unknown. */\n adapter(provider: string): MarketplaceAdapter | null;\n /** The marketplace's reasons, static and offline. Empty when unknown. */\n reasons(provider: string): readonly CancellationReason[];\n /** The reason a host preselects, given whether the order is short of an item. */\n suggestReason(provider: string, input: { itemUnavailable: boolean }): CancellationReason | null;\n /** Where a person goes to act on the marketplace's side. Null when unknown. */\n appLink(provider: string, order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string | null;\n\n /** Turn a raw payload into the canonical shape, or null if nothing does. */\n normalize(provider: string, payload: unknown): NormalizedEvent | null;\n /** Read the provider's signature header off a request. */\n readSignature(provider: string, header: (name: string) => string | null): string | null;\n /** Verify a delivery. An unknown provider is never verified, so never accepted. */\n verifySignature(provider: string, rawBody: string, signature: string | null, secret: string | null): boolean;\n /** Which tenant a delivery belongs to, from the merchant id it names. */\n tenantFor(provider: MarketplaceProvider, externalMerchantId: string): Promise<string | null>;\n /** The connection behind one (tenant, marketplace), for the ingestion path. */\n target(clientId: string, provider: MarketplaceProvider): Promise<IngestionTarget | null>;\n /** Ingest ONE already-normalized order, bypassing the inbox. Idempotent. */\n ingest(input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n }): Promise<IngestResult>;\n /** Record and act on one delivery. Never throws. */\n deliver(input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n }): Promise<DeliveryOutcome>;\n\n /** This store's connections, secrets withheld; archived ones only when asked. */\n integrations(\n clientId: string,\n options?: { providers?: readonly string[]; includeArchived?: boolean },\n ): Promise<MarketplaceIntegrationView[]>;\n /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */\n saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;\n /** Create, patch, archive or unarchive many connections, all-or-nothing. */\n upsertIntegrations(input: {\n clientId: string;\n actorId: string | null;\n rows: readonly IntegrationRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceIntegrationView>>;\n\n /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */\n menuLinks(input: {\n clientId: string;\n provider?: MarketplaceProvider;\n unmappedOnly?: boolean;\n ids?: readonly string[];\n }): Promise<MarketplaceMenuLinkView[]>;\n /** Map or unmap many SKUs, all-or-nothing. */\n upsertMenuLinks(input: {\n clientId: string;\n rows: readonly MenuLinkRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceMenuLinkView>>;\n /** Map or unmap ONE SKU. `null` = the catalog id is not this tenant's. */\n setMenuLink(input: { clientId: string } & MenuLinkRowInput): Promise<MarketplaceMenuLinkView | null>;\n\n /** Orders still on the clock, soonest deadline first; `orderIds` narrows. */\n pending(clientId: string, orderIds?: readonly string[]): Promise<PendingAcceptance[]>;\n /** Decide many orders, all-or-nothing, the host admitting each inside the claim's transaction. */\n decideMany(input: {\n clientId: string;\n decisions: readonly DecisionInput[];\n validateOnly?: boolean;\n now?: Date;\n }): Promise<DecideManyResult>;\n /** Decide ONE order (`decideMany` with one decision). */\n decide(input: { clientId: string; now?: Date } & DecisionInput): Promise<DecisionResult>;\n /** The store cancelled through the host's own cancel: stamp and queue the request. */\n recordStoreCancellation(input: {\n clientId: string;\n orderId: string;\n reasonCode?: string | null;\n offendingSkus?: readonly string[];\n now?: Date;\n }): Promise<DecisionResult>;\n /** The marketplace cancelled an order we already have. */\n cancel(input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n now?: Date;\n }): Promise<boolean>;\n /** Where each of these orders' acceptance and cancellation stand. */\n orderStates(clientId: string, orderIds: readonly string[]): Promise<Map<string, MarketplaceOrderState>>;\n\n /** Expire every order whose deadline has passed, across all tenants. */\n expireLapsed(now?: Date): Promise<ExpirySweepResult>;\n /** Deliveries recorded but never processed, oldest first. */\n retryable(): Promise<PendingInboxEvent[]>;\n /** Re-run one stored delivery against the store's CURRENT settings. */\n reprocess(event: PendingInboxEvent): Promise<DeliveryOutcome>;\n /** Re-queue every outbound call still owed (the `marketplace.outbound-sweep` job's body). */\n sweepOutbound(now?: Date): Promise<OutboundSweepResult>;\n /** Run one queued outbound call (the `marketplace.outbound` job's body). */\n runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;\n}\n\n/**\n * Mount the engine onto a host.\n *\n * Every port is REQUIRED and there are no defaults: a default would let a\n * second host silently inherit the first one's answers. The adapter list is\n * validated here (`createAdapterRegistry`), so a malformed adapter fails at\n * boot rather than on the first order it would have mangled.\n */\nexport function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine {\n const { adapters, ...ports } = config;\n const registry = createAdapterRegistry(adapters);\n const tokens: AdapterTokenCache = new Map();\n const ctx: EngineContext = { ports, registry, tokens };\n\n return {\n providers: () => registry.providers(),\n knows: (provider): provider is MarketplaceProvider => registry.has(provider),\n adapter: (provider) => registry.get(provider),\n reasons: (provider) => registry.get(provider)?.cancellationReasons() ?? [],\n suggestReason: (provider, input) => {\n const adapter = registry.get(provider);\n return adapter ? suggestReason(adapter, input) : null;\n },\n appLink: (provider, order) => registry.get(provider)?.appLink(order) ?? null,\n\n normalize: (provider, payload) => normalizeEvent(ctx, provider, payload),\n readSignature: (provider, header) => registry.get(provider)?.readSignature(header) ?? null,\n // An unknown provider cannot be verified, so it is not accepted: trusting\n // what cannot be checked is how an unsigned endpoint ships by omission.\n verifySignature: (provider, rawBody, signature, secret) =>\n registry.get(provider)?.verifySignature(rawBody, signature, secret) ?? false,\n tenantFor: (provider, externalMerchantId) =>\n resolveTenantByMerchant(ctx, provider, externalMerchantId),\n target: (clientId, provider) => resolveIngestionTarget(ctx, clientId, provider),\n ingest: (input) => ingestMarketplaceOrder(ctx, input),\n deliver: (input) => processDelivery(ctx, input),\n\n integrations: (clientId, options) => listMarketplaceIntegrations(ctx, clientId, options),\n saveIntegration: async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()),\n upsertIntegrations: (input) => upsertIntegrations(ctx, input),\n\n menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),\n upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),\n setMenuLink: async ({ clientId, ...row }) => {\n const result = await upsertMenuLinks(ctx, { clientId, rows: [row] });\n return result.kind === \"saved\" ? (result.rows[0] ?? null) : null;\n },\n\n pending: (clientId, orderIds) => listPendingAcceptances(ctx, clientId, orderIds),\n decideMany: (input) => decideMany(ctx, input),\n decide: (input) => decideOne(ctx, input),\n recordStoreCancellation: (input) => recordStoreCancellation(ctx, input),\n cancel: (input) => cancelAcceptance(ctx, input),\n orderStates: (clientId, orderIds) => readOrderStates(ctx, clientId, orderIds),\n\n expireLapsed: (now) => expireLapsedAcceptances(ctx, now ?? ports.clock.now()),\n retryable: () => listRetryableInboxEvents(ctx),\n reprocess: (event) => reprocessStoredDelivery(ctx, event),\n sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),\n runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,eAAsB,uBACpB,KACA,UACA,UAC8B;AAC9B,QAAM,KAAK,MAAM,IAAI,MAAM,GAAG;AAC9B,QAAM,OAAQ,MAAM,GAAG,sBAAsB,SAAS;AAAA,IACpD,OAAO,EAAE,UAAU,QAAQ,YAAY,GAAI,WAAW,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,QAAQ,EAAE,EAAE,IAAI,CAAC,EAAG;AAAA,IAC/F,SAAS,EAAE,eAAe,MAAM;AAAA,IAChC,QAAQ;AAAA,MACN,IAAI;AAAA,MACJ,SAAS;AAAA,MACT,UAAU;AAAA,MACV,iBAAiB;AAAA,MACjB,mBAAmB;AAAA,MACnB,eAAe;AAAA,MACf,eAAe;AAAA,MACf,iBAAiB;AAAA,IACnB;AAAA,EACF,CAAC;AACD,MAAI,KAAK,WAAW,EAAG,QAAO,CAAC;AAE/B,QAAM,YAAY,MAAM,IAAI,MAAM,MAAM;AAAA,IACtC;AAAA,IACA,KAAK,IAAI,CAAC,QAAQ,IAAI,OAAO;AAAA,EAC/B;AACA,SAAO,KAAK,IAAI,CAAC,QAAQ;AACvB,UAAM,UAAU,UAAU,IAAI,IAAI,OAAO;AACzC,WAAO;AAAA,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AKb,SAAS,wBAAC,UAAU,aAAa,uBAAuB,KAAK,UAAU,QAAQ,GAAtE;AAAA,IACT,YAAY,wBAAC,UAAU,WAAW,KAAK,KAAK,GAAhC;AAAA,IACZ,QAAQ,wBAAC,UAAU,UAAU,KAAK,KAAK,GAA/B;AAAA,IACR,yBAAyB,wBAAC,UAAU,wBAAwB,KAAK,KAAK,GAA7C;AAAA,IACzB,QAAQ,wBAAC,UAAU,iBAAiB,KAAK,KAAK,GAAtC;AAAA,IACR,aAAa,wBAAC,UAAU,aAAa,gBAAgB,KAAK,UAAU,QAAQ,GAA/D;AAAA,IAEb,cAAc,wBAAC,QAAQ,wBAAwB,KAAK,OAAO,MAAM,MAAM,IAAI,CAAC,GAA9D;AAAA,IACd,WAAW,6BAAM,yBAAyB,GAAG,GAAlC;AAAA,IACX,WAAW,wBAAC,UAAU,wBAAwB,KAAK,KAAK,GAA7C;AAAA,IACX,eAAe,wBAAC,QAAQ,cAAc,KAAK,OAAO,MAAM,MAAM,IAAI,CAAC,GAApD;AAAA,IACf,aAAa,wBAAC,SAAS,YAAY,YAAY,KAAK,SAAS,OAAO,GAAvD;AAAA,EACf;AACF;AArDgB;","names":["answered","duplicates"]}
1
+ {"version":3,"sources":["../src/core/bulk.ts","../src/core/decisions.ts","../src/core/catalogue.ts","../src/core/pipeline.ts","../src/core/state.ts","../src/core/engine.ts"],"sourcesContent":["import {\n listMarketplaceIntegrations,\n saveMarketplaceIntegration,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { upsertLink, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from \"./ports\";\n\n/**\n * The bulk writes: one call, many rows, all-or-nothing.\n *\n * Every row is validated first (cross-row duplicates, unknown providers, a\n * catalog id that is not the store's, an archive of nothing) and every problem\n * is returned with its path; any problem writes nothing. Then ONE transaction\n * writes every row, or none. `validateOnly` validates and writes nothing.\n * Idempotent on the natural key: a connection is `(store, provider)`, a SKU\n * link `(store, provider, externalSku)`.\n */\n\n/** Why a bulk row was refused. Vocabulary, not copy. */\nexport type BulkProblemCode =\n | \"DUPLICATE\"\n | \"UNKNOWN_PROVIDER\"\n | \"NOTHING_TO_UPDATE\"\n | \"NOT_FOUND\"\n | \"CATALOG_ITEM_NOT_FOUND\";\n\nexport interface BulkProblem {\n path: (string | number)[];\n code: BulkProblemCode;\n}\n\nexport type BulkResult<T> =\n | { kind: \"saved\"; validateOnly: boolean; rows: T[] }\n | { kind: \"refused\"; problems: BulkProblem[] };\n\n/** One connection row: an upsert of its settings, an archive, or an unarchive. */\nexport type IntegrationRowInput =\n | ({ operation?: \"upsert\" } & Omit<SaveMarketplaceIntegrationInput, \"clientId\">)\n | { operation: \"archive\" | \"unarchive\"; provider: string; reason?: string | null };\n\n/** One SKU link: map it to a catalog id, or unmap it with `menuItemId: null`. */\nexport interface MenuLinkRowInput {\n provider: string;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n}\n\n/** The key of each row seen twice, as problems. */\nfunction duplicates<T>(rows: readonly T[], keyOf: (row: T) => string, list: string, field: string): BulkProblem[] {\n const seen = new Set<string>();\n return rows.flatMap((row, index) => {\n const key = keyOf(row);\n if (!seen.has(key)) {\n seen.add(key);\n return [];\n }\n return [{ path: [list, index, field], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction unknownProviders(ctx: EngineContext, rows: readonly { provider: string }[], list: string): BulkProblem[] {\n return rows.flatMap((row, index) =>\n ctx.registry.has(row.provider) ? [] : [{ path: [list, index, \"provider\"], code: \"UNKNOWN_PROVIDER\" as const }],\n );\n}\n\nconst SETTING_KEYS = [\"enabled\", \"environment\", \"externalMerchantId\", \"autoAccept\", \"ackSlaSeconds\", \"credentials\"] as const;\n\nfunction integrationRowProblems(\n row: IntegrationRowInput,\n index: number,\n existing: ReadonlySet<string>,\n): BulkProblem[] {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n return existing.has(row.provider) ? [] : [{ path: [\"integrations\", index, \"provider\"], code: \"NOT_FOUND\" }];\n }\n const settings = row as Partial<Record<(typeof SETTING_KEYS)[number], unknown>>;\n const changes = SETTING_KEYS.some((key) => settings[key] !== undefined);\n return changes ? [] : [{ path: [\"integrations\", index], code: \"NOTHING_TO_UPDATE\" }];\n}\n\n/** Thrown inside the transaction to roll a `validateOnly` call back. */\nclass ValidateOnly extends Error {\n constructor() {\n super(\"validate only\");\n }\n}\n\n/** Run `write` in one transaction; a `validateOnly` call is rolled back. */\nasync function inTransaction<T>(ctx: EngineContext, validateOnly: boolean, write: (db: MarketplaceDb) => Promise<T>): Promise<T | null> {\n let written: T | null = null;\n try {\n await ctx.ports.transaction(async (db) => {\n written = await write(db);\n if (validateOnly) throw new ValidateOnly();\n });\n } catch (error) {\n if (!(error instanceof ValidateOnly)) throw error;\n }\n return written;\n}\n\nasync function writeIntegration(\n ctx: EngineContext,\n db: MarketplaceDb,\n clientId: string,\n row: IntegrationRowInput,\n now: Date,\n): Promise<MarketplaceIntegrationView | null> {\n if (row.operation === \"archive\" || row.operation === \"unarchive\") {\n await db.marketplaceIntegration.updateMany({\n where: { clientId, provider: row.provider },\n data: { archivedAt: row.operation === \"archive\" ? now : null },\n });\n return null;\n }\n const settings: Omit<IntegrationRowInput, \"operation\"> & { operation?: unknown } = { ...row };\n delete settings.operation;\n return saveMarketplaceIntegration(ctx, { clientId, ...(settings as Omit<SaveMarketplaceIntegrationInput, \"clientId\">) }, db);\n}\n\n/**\n * Create, patch, archive or unarchive many connections at once. A connection\n * is never deleted: archiving is reversible, and each archive and unarchive is\n * an audit line through the host's `audit` port, in the same transaction.\n */\nexport async function upsertIntegrations(\n ctx: EngineContext,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceIntegrationView>> {\n const existing = new Set(\n (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider),\n );\n const problems = [\n ...duplicates(input.rows, (row) => row.provider, \"integrations\", \"provider\"),\n ...unknownProviders(ctx, input.rows, \"integrations\"),\n ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),\n ];\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const now = ctx.ports.clock.now();\n // The audit lines are written INSIDE the archive's transaction, through its\n // client: an archive never lands without its line, and an audit that fails\n // rolls the archive back. A `validateOnly` call rolls both back.\n await inTransaction(ctx, validateOnly, async (db) => {\n for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);\n await auditArchives(ctx, db, input, now);\n });\n const providers = input.rows.map((row) => row.provider);\n const rows = validateOnly\n ? []\n : await listMarketplaceIntegrations(ctx, input.clientId, { providers, includeArchived: true });\n return { kind: \"saved\", validateOnly, rows };\n}\n\nasync function auditArchives(\n ctx: EngineContext,\n db: MarketplaceDb,\n input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[] },\n now: Date,\n): Promise<void> {\n for (const row of input.rows) {\n if (row.operation !== \"archive\" && row.operation !== \"unarchive\") continue;\n const entry: MarketplaceAuditEntry = {\n clientId: input.clientId,\n actorId: input.actorId,\n action: row.operation === \"archive\" ? \"marketplace.integration.archive\" : \"marketplace.integration.unarchive\",\n provider: row.provider,\n reason: row.reason ?? null,\n at: now,\n };\n await ctx.ports.audit.record(entry, db);\n }\n}\n\n/** Map or unmap many SKUs at once; every catalog id must be the store's. */\nexport async function upsertMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; rows: readonly MenuLinkRowInput[]; validateOnly?: boolean },\n): Promise<BulkResult<MarketplaceMenuLinkView>> {\n const problems = [\n ...duplicates(input.rows, (row) => `${row.provider}\\u0000${row.externalSku}`, \"links\", \"externalSku\"),\n ...unknownProviders(ctx, input.rows, \"links\"),\n ];\n for (const [index, row] of input.rows.entries()) {\n if (row.menuItemId !== null && !(await ctx.ports.order.catalogHas(input.clientId, row.menuItemId))) {\n problems.push({ path: [\"links\", index, \"menuItemId\"], code: \"CATALOG_ITEM_NOT_FOUND\" });\n }\n }\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n const written = await inTransaction(ctx, validateOnly, async (db) => {\n const rows: MarketplaceMenuLinkView[] = [];\n for (const row of input.rows) rows.push(await upsertLink(db, { clientId: input.clientId, ...row }));\n return rows;\n });\n return { kind: \"saved\", validateOnly, rows: written ?? [] };\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport {\n CLAIM_SELECT,\n NO_STANDING_REQUEST,\n notPendingProblem,\n planCancellation,\n refusalData,\n requestData,\n type CancellationPlan,\n type ClaimRow,\n type DecisionProblem,\n type DecisionProblemCode,\n} from \"./cancellation\";\nimport { requestsFirst, tellCancellationFailed } from \"./cancellation-outcome\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceAdmission, MarketplaceDb } from \"./ports\";\n\n/**\n * The store's decisions on orders on the clock — ONE path for every surface\n * (the host's board, the admin route, the MCP tool), and all-or-nothing:\n *\n * 1. every decision is validated against its row (still AWAITING, the reason\n * the marketplace's, the offending SKUs the order's) before anything runs;\n * 2. inside ONE transaction the host ADMITS each decision (`order.admit`: the\n * stock ask, the draw) and the engine claims each row on `AWAITING`. A\n * host refusal or a lost claim rolls the whole call back;\n * 3. after the commit, each outbound call is QUEUED FIRST, then the host's\n * half runs (`onAccepted` / `onRefused`). A host half that throws cannot\n * lose the call; it is logged, and the decision stands.\n *\n * A queue that refuses the job loses nothing either: the outbound sweep\n * (`./outbound-sweep.ts`) re-queues every request still owed.\n */\n\n/** The two things a person can do to an order on the clock. */\nexport type AcceptanceDecision = \"ACCEPT\" | \"REJECT\";\n\n/** One decision, as a caller states it. */\nexport type DecisionInput =\n | {\n orderId: string;\n decision: \"ACCEPT\";\n /** What the person confirmed, for the host's admission. */\n admission?: MarketplaceAdmission;\n /** Minutes to prepare, for a marketplace whose confirm states one. */\n preparationMinutes?: number | null;\n }\n | {\n orderId: string;\n decision: \"REJECT\";\n /** One of the marketplace's codes; its first reason when absent. */\n reasonCode?: string | null;\n /** The order's SKUs a reason that `needsItems` names. */\n offendingSkus?: readonly string[];\n };\n\n/**\n * One decided row. `status` is the row's status after the call: ACCEPTED or\n * REJECTED, or — for a refusal of a host that requests first (FUT-4758) —\n * the status it keeps (AWAITING, ACCEPTED) while `cancellation` waits.\n */\nexport interface DecidedRow {\n orderId: string;\n status: AcceptanceStatus;\n cancellation: CancellationStatus | null;\n reasonCode: string | null;\n offendingSkus: string[];\n}\n\n/** What a call did: every row decided, or nothing written and every problem named. */\nexport type DecideManyResult =\n | { kind: \"decided\"; validateOnly: boolean; rows: DecidedRow[] }\n | { kind: \"refused\"; problems: DecisionProblem[] };\n\n/** One decision's result, for a caller deciding one order. */\nexport type DecisionResult =\n | ({ kind: \"decided\" } & DecidedRow)\n | {\n kind: \"stale\";\n /** Why: gone, decided already (I4: answer it as done), expired, or lost to a race. */\n reason: Extract<DecisionProblemCode, \"NOT_FOUND\" | \"ALREADY_DECIDED\" | \"EXPIRED\" | \"CONFLICT\">;\n status: AcceptanceStatus | null;\n }\n | {\n kind: \"invalidReason\";\n problem: Extract<DecisionProblemCode, \"INVALID_REASON\" | \"ITEMS_REQUIRED\" | \"UNKNOWN_ITEM\">;\n validCodes: string[];\n }\n | { kind: \"refusedByHost\"; code: string; message: string; details?: unknown };\n\n/** A planned decision: the row, the claim's data, and what it becomes. */\ninterface PlannedDecision {\n input: DecisionInput;\n index: number;\n row: ClaimRow;\n data: Record<string, unknown>;\n decided: DecidedRow;\n /** A refusal that only REQUESTS the cancellation: the host cancels on the marketplace's confirmation. */\n requestOnly: boolean;\n}\n\n/** Thrown inside the transaction to roll it back, carrying the reason. */\nclass Rollback extends Error {\n constructor(readonly problems: DecisionProblem[] | null) {\n super(\"rollback\");\n }\n}\n\nfunction duplicateProblems(decisions: readonly DecisionInput[]): DecisionProblem[] {\n const seen = new Set<string>();\n return decisions.flatMap((decision, index) => {\n if (!seen.has(decision.orderId)) {\n seen.add(decision.orderId);\n return [];\n }\n return [{ path: [\"decisions\", index, \"orderId\"], code: \"DUPLICATE\" as const }];\n });\n}\n\nfunction decidedOf(input: DecisionInput, plan: CancellationPlan | null, keptStatus?: string): DecidedRow {\n const decided: AcceptanceStatus = input.decision === \"ACCEPT\" ? \"ACCEPTED\" : \"REJECTED\";\n return {\n orderId: input.orderId,\n status: (keptStatus as AcceptanceStatus | undefined) ?? decided,\n cancellation: plan?.status ?? null,\n reasonCode: plan?.reason?.code ?? null,\n offendingSkus: plan?.skus ?? [],\n };\n}\n\n/**\n * The columns of a request that no longer stands, cleared, but for its\n * TOMBSTONE: `cancellation_requested_at` stays, naming the request that was\n * made (FUT-4765, R3-N2).\n *\n * A synchronous marketplace answers a cancellation in the call's response,\n * never by event. When the sweep times a request out while that call is still\n * in flight and the store then accepts the order, the late answer must still\n * find the request it answers: \"cancelled\" means the marketplace cancelled the\n * order, and dropping it would leave the order ACCEPTED here and cancelled\n * there. The outbound job matches a status-less row by this instant\n * (`stampConfirmedCancellation`); nothing else reads it without a status.\n */\nconst CLEARED_REQUEST = {\n cancellationStatus: null,\n cancellationReasonCode: null,\n cancellationOffendingSkus: null,\n cancellationFailureReason: null,\n} as const;\n\n/** Plan one decision against its row, or name what is wrong with it. */\nfunction planOne(\n ctx: EngineContext,\n input: DecisionInput,\n index: number,\n row: ClaimRow | undefined,\n now: Date,\n): PlannedDecision | DecisionProblem[] {\n const path = [\"decisions\", index];\n const stale = notPendingProblem(row, path);\n if (stale || !row) return stale ? [stale] : [];\n if (input.decision === \"ACCEPT\") {\n // An accept after a FAILED request (FUT-4758) leaves no request behind it,\n // only its tombstone (see CLEARED_REQUEST).\n const data = {\n status: \"ACCEPTED\",\n acknowledgedAt: now,\n preparationMinutes: input.preparationMinutes ?? null,\n ...(row.cancellationStatus === null ? {} : CLEARED_REQUEST),\n };\n return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };\n }\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);\n if (Array.isArray(plan)) return plan;\n if (requestOnly(ctx, plan)) {\n return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };\n }\n return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };\n}\n\n/**\n * Whether a refusal only REQUESTS the cancellation (FUT-4758): the host\n * requests first (it binds `onCancellationConfirmed`), and there is a request\n * to make — PENDING, or FAILED at once for a marketplace that cannot take it\n * through its API (a person cancels in its app, and its event confirms). A\n * provider with no adapter has nothing to ask: refused at once, as ever.\n */\nfunction requestOnly(ctx: EngineContext, plan: CancellationPlan): boolean {\n return requestsFirst(ctx) && plan.status !== null;\n}\n\n/** Admit every decision through the host, then claim every row, in one transaction. */\nasync function admitAndClaim(\n ctx: EngineContext,\n clientId: string,\n planned: readonly PlannedDecision[],\n validateOnly: boolean,\n): Promise<void> {\n await ctx.ports.transaction(async (tx: MarketplaceDb) => {\n const refused: DecisionProblem[] = [];\n for (const one of planned) {\n const admission = one.input.decision === \"ACCEPT\" ? (one.input.admission ?? {}) : {};\n const answer = await ctx.ports.order.admit({\n clientId,\n orderId: one.input.orderId,\n decision: one.input.decision,\n admission,\n db: tx,\n });\n if (!answer.admitted) {\n const host = { code: answer.code, message: answer.message, details: answer.details };\n refused.push({ path: [\"decisions\", one.index], code: \"HOST_REFUSED\", host });\n }\n }\n if (refused.length > 0) throw new Rollback(refused);\n for (const one of planned) {\n const claimed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: one.input.orderId, clientId, status: \"AWAITING\", ...NO_STANDING_REQUEST },\n data: one.data,\n });\n if (claimed.count === 0) refused.push({ path: [\"decisions\", one.index, \"orderId\"], code: \"CONFLICT\" });\n }\n if (refused.length > 0) throw new Rollback(refused);\n if (validateOnly) throw new Rollback(null);\n });\n}\n\n/** After the commit: queue each owed call FIRST, then the host's half, which may not lose it. */\nasync function afterCommit(ctx: EngineContext, clientId: string, planned: readonly PlannedDecision[]): Promise<void> {\n for (const one of planned) {\n const { orderId } = one.input;\n if (one.input.decision === \"ACCEPT\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, one.row.provider);\n } else if (one.decided.cancellation === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId, orderId, action: \"requestCancellation\" }, one.row.provider);\n }\n try {\n if (one.decided.status === \"ACCEPTED\" && one.input.decision === \"ACCEPT\") await ctx.ports.order.onAccepted(clientId, orderId);\n else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, \"REJECTED\");\n // A request the marketplace cannot take through its API failed at once:\n // the order stays, and a person cancels it in the marketplace's app.\n else if (one.decided.cancellation === \"FAILED\") await tellCancellationFailed(ctx, clientId, orderId, \"REFUSED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n ctx.ports.publishChanged(clientId);\n}\n\n/** Read every row a call names, in one statement. */\nasync function readRows(ctx: EngineContext, clientId: string, orderIds: string[]): Promise<Map<string, ClaimRow>> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: orderIds } },\n select: CLAIM_SELECT,\n })) as ClaimRow[];\n return new Map(rows.map((row) => [row.orderId, row]));\n}\n\n/**\n * Decide many orders at once, all-or-nothing. `validateOnly` runs everything —\n * the host's admission included — and rolls it back.\n */\nexport async function decideMany(\n ctx: EngineContext,\n input: { clientId: string; decisions: readonly DecisionInput[]; validateOnly?: boolean; now?: Date },\n): Promise<DecideManyResult> {\n const duplicates = duplicateProblems(input.decisions);\n if (duplicates.length > 0) return { kind: \"refused\", problems: duplicates };\n const now = input.now ?? ctx.ports.clock.now();\n const rows = await readRows(ctx, input.clientId, input.decisions.map((decision) => decision.orderId));\n\n const planned: PlannedDecision[] = [];\n const problems: DecisionProblem[] = [];\n input.decisions.forEach((decision, index) => {\n const plan = planOne(ctx, decision, index, rows.get(decision.orderId), now);\n if (Array.isArray(plan)) problems.push(...plan);\n else planned.push(plan);\n });\n if (problems.length > 0) return { kind: \"refused\", problems };\n\n const validateOnly = input.validateOnly === true;\n try {\n await admitAndClaim(ctx, input.clientId, planned, validateOnly);\n } catch (error) {\n if (!(error instanceof Rollback)) throw error;\n if (error.problems) return { kind: \"refused\", problems: error.problems };\n }\n if (!validateOnly) await afterCommit(ctx, input.clientId, planned);\n return { kind: \"decided\", validateOnly, rows: planned.map((one) => one.decided) };\n}\n\nconst STALE_CODES = new Set<DecisionProblemCode>([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** One decision's problem, as the single-order result names it. */\nfunction resultOfProblem(problem: DecisionProblem): DecisionResult {\n if (problem.code === \"HOST_REFUSED\") {\n const host = problem.host ?? { code: \"\", message: \"\" };\n return { kind: \"refusedByHost\", code: host.code, message: host.message, details: host.details };\n }\n if (STALE_CODES.has(problem.code)) {\n const reason = problem.code as Extract<DecisionResult, { kind: \"stale\" }>[\"reason\"];\n return { kind: \"stale\", reason, status: problem.status ?? null };\n }\n const invalid = problem.code as Extract<DecisionResult, { kind: \"invalidReason\" }>[\"problem\"];\n return { kind: \"invalidReason\", problem: invalid, validCodes: problem.validCodes ?? [] };\n}\n\n/** Decide ONE order: `decideMany` with one decision. */\nexport async function decideOne(\n ctx: EngineContext,\n input: { clientId: string; now?: Date } & DecisionInput,\n): Promise<DecisionResult> {\n const { clientId, now, ...decision } = input;\n const result = await decideMany(ctx, { clientId, decisions: [decision as DecisionInput], now });\n if (result.kind === \"decided\") {\n const [row] = result.rows;\n if (row) return { kind: \"decided\", ...row };\n }\n const [problem] = result.kind === \"refused\" ? result.problems : [];\n return problem ? resultOfProblem(problem) : { kind: \"stale\", reason: \"CONFLICT\", status: null };\n}\n\n/**\n * The STORE asks to cancel an order — before or after accepting it. Stamps\n * the request the marketplace must hear and queues it; the engine neither\n * admits nor calls `onRefused`: it records and queues, and nothing else.\n *\n * REQUEST FIRST (FUT-4758), for a host that binds `onCancellationConfirmed`:\n * only the request moves. The decision status stays AWAITING or ACCEPTED while\n * the marketplace answers, so the host keeps the order as it was until then,\n * and a refused or timed-out request (`onCancellationFailed`) leaves it\n * acceptable. The marketplace's confirmation moves it to REJECTED. A FAILED\n * request may be asked again. A host that binds no `onCancellationConfirmed`\n * cancelled first and gets 1.0.0's stamps exactly: REJECTED at once.\n *\n * The returned row's `status` is the row's after the call.\n *\n * `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the\n * clock lapsed (EXPIRED), or a request is already waiting.\n */\nexport async function recordStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; reasonCode?: string | null; offendingSkus?: readonly string[]; now?: Date },\n): Promise<DecisionResult> {\n const row = (await readRows(ctx, input.clientId, [input.orderId])).get(input.orderId);\n const stale = notPendingProblem(row, [], [\"AWAITING\", \"ACCEPTED\"]);\n if (stale || !row) return stale ? resultOfProblem(stale) : { kind: \"stale\", reason: \"NOT_FOUND\", status: null };\n const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);\n if (Array.isArray(plan)) return resultOfProblem(plan[0]!);\n\n return claimStoreCancellation(ctx, input, row, plan);\n}\n\n/** Stamp the store's cancellation (the request alone, or 1.0.0's REJECTED), queue it, and tell the host. */\nasync function claimStoreCancellation(\n ctx: EngineContext,\n input: { clientId: string; orderId: string; now?: Date },\n row: ClaimRow,\n plan: CancellationPlan,\n): Promise<DecisionResult> {\n const now = input.now ?? ctx.ports.clock.now();\n const db = await ctx.ports.db();\n const only = requestOnly(ctx, plan);\n const claimed = await db.marketplaceAcceptance.updateMany({\n where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },\n data: only ? requestData(plan, now) : refusalData(plan, row.status, now),\n });\n if (claimed.count === 0) return { kind: \"stale\", reason: \"CONFLICT\", status: null };\n if (plan.status === \"PENDING\") {\n await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: \"requestCancellation\" }, row.provider);\n }\n ctx.ports.publishChanged(input.clientId);\n if (only && plan.status === \"FAILED\") await tellCancellationFailed(ctx, input.clientId, input.orderId, \"REFUSED\");\n return { kind: \"decided\", ...decidedOf({ orderId: input.orderId, decision: \"REJECT\" }, plan, only ? row.status : undefined) };\n}\n","import { catalogueDedupeKey, enqueueCatalogue, type CatalogueJobPayload } from \"./catalogue-job\";\nimport type { CatalogueMenuEntry, CatalogueMenuOptions } from \"./catalogue-port\";\nimport {\n CATALOGUE_ROW_SELECT,\n NO_FAILURE,\n catalogueConnection,\n catalogueTable,\n viewOf,\n type CataloguePublicationView,\n type CatalogueRow,\n type CatalogueTable,\n} from \"./catalogue-store\";\nimport { connectionMerchantId } from \"./integration\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * Catalogue publishing, as a host calls it (FUT-4768): from a product's page,\n * the store turns the product ON (`publish`) or OFF (`withdraw`) per connected\n * marketplace, with an optional price for that marketplace, and reads where\n * each stands (`catalogueState`, one read for a whole page).\n *\n * Nothing here calls a marketplace: a publish or withdraw stamps the row and\n * queues `marketplace.catalogue`, whose job makes the call. The host's product\n * is read through its `catalogue` port, never from a host table, and only the\n * job reads it for sending, so what goes out is the product as it is then.\n */\n\n/** Why a catalogue call was refused before anything was stamped. Vocabulary, not copy. */\nexport type CatalogueRefusalCode =\n /** The marketplace has no catalogue capability, or the host bound no catalogue port or table. */\n | \"UNSUPPORTED\"\n /** No live connection with credentials and a merchant id. */\n | \"NOT_CONNECTED\"\n /** The host's catalogue does not have this product. */\n | \"UNKNOWN_PRODUCT\"\n /** The price for the marketplace is not a positive integer of the smallest unit. */\n | \"INVALID_PRICE\";\n\n/** What `publish` and `withdraw` answer. */\nexport type CatalogueActionResult =\n /** Stamped and queued (or already on its way: a double tap is this, with nothing new queued). */\n | { kind: \"queued\"; publication: CataloguePublicationView }\n /** Nothing to do: the product is not in that marketplace's catalogue, or was never there. */\n | { kind: \"unchanged\"; publication: CataloguePublicationView | null }\n | { kind: \"refused\"; code: CatalogueRefusalCode };\n\n/** What a pull marketplace's menu document read answers. */\nexport type CatalogueDocumentResult =\n | { kind: \"document\"; document: unknown }\n | { kind: \"refused\"; code: Exclude<CatalogueRefusalCode, \"UNKNOWN_PRODUCT\" | \"INVALID_PRICE\"> };\n\n/** One product on one marketplace. */\nexport interface CatalogueTarget {\n clientId: string;\n provider: MarketplaceProvider;\n productId: string;\n}\n\n/** A publish: the target, and the price for this marketplace — absent keeps the stored one, null is the store's. */\nexport interface CataloguePublishInput extends CatalogueTarget {\n priceCents?: number | null;\n}\n\nconst refused = (code: CatalogueRefusalCode): CatalogueActionResult => ({ kind: \"refused\", code });\n\n/** The table, or why the catalogue cannot be used at all for this marketplace. */\nasync function usableTable(ctx: EngineContext, provider: string): Promise<CatalogueTable | null> {\n if (!ctx.ports.catalogue || !ctx.registry.get(provider)?.catalogue) return null;\n return catalogueTable(ctx);\n}\n\nasync function findRow(table: CatalogueTable, target: CatalogueTarget): Promise<CatalogueRow | null> {\n return (await table.findFirst({\n where: { clientId: target.clientId, provider: target.provider, productId: target.productId },\n select: CATALOGUE_ROW_SELECT,\n })) as CatalogueRow | null;\n}\n\nasync function queue(ctx: EngineContext, row: CatalogueRow, action: CatalogueJobPayload[\"action\"]): Promise<CatalogueActionResult> {\n const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action };\n await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, row.requestedAt));\n ctx.ports.publishChanged(row.clientId);\n return { kind: \"queued\", publication: viewOf(row) };\n}\n\nconst validPrice = (price: number | null | undefined): boolean =>\n price === undefined || price === null || (Number.isInteger(price) && price > 0);\n\n/** Why a publish cannot be asked, or null. */\nasync function publishRefusal(ctx: EngineContext, input: CataloguePublishInput): Promise<CatalogueRefusalCode | null> {\n if (!validPrice(input.priceCents)) return \"INVALID_PRICE\";\n if (\"problem\" in (await catalogueConnection(ctx, input.clientId, input.provider))) return \"NOT_CONNECTED\";\n const items = await ctx.ports.catalogue?.items(input.clientId, [input.productId]);\n return items?.has(input.productId) ? null : \"UNKNOWN_PRODUCT\";\n}\n\n/**\n * Put the product in the marketplace's catalogue, or send it again (a new\n * price, a retry after FAILED). A double tap while it is on its way keeps the\n * same ask and queues nothing new.\n */\nexport async function publishToCatalogue(ctx: EngineContext, input: CataloguePublishInput): Promise<CatalogueActionResult> {\n const table = await usableTable(ctx, input.provider);\n if (!table) return refused(\"UNSUPPORTED\");\n const refusal = await publishRefusal(ctx, input);\n if (refusal) return refused(refusal);\n const existing = await findRow(table, input);\n const now = ctx.ports.clock.now();\n const price = input.priceCents === undefined ? {} : { priceCents: input.priceCents };\n // A double tap keeps the ask on its way; a NEW price is a new ask, so the\n // run already queued (which reads the row's price at its own instant) misses\n // its stamp and the new run sends the new price.\n const samePrice = input.priceCents === undefined || input.priceCents === existing?.priceCents;\n const asked = existing?.status === \"PUBLISHING\" && samePrice ? {} : { requestedAt: now };\n const row = (await table.upsert({\n where: { clientId_provider_productId: { clientId: input.clientId, provider: input.provider, productId: input.productId } },\n create: { clientId: input.clientId, provider: input.provider, productId: input.productId, status: \"PUBLISHING\", requestedAt: now, ...price },\n update: { status: \"PUBLISHING\", ...NO_FAILURE, ...asked, ...price },\n select: CATALOGUE_ROW_SELECT,\n })) as CatalogueRow;\n return queue(ctx, row, \"publish\");\n}\n\n/**\n * Take the product out of the marketplace's catalogue. A product never\n * switched on (no row, or WITHDRAWN) is `unchanged`; a double tap while it is\n * on its way out queues nothing new; a withdraw while a publish is on its way\n * wins (the job re-withdraws a publish that lands after it).\n *\n * A withdraw is SENT even after a publish that FAILED: a call whose answer was\n * lost may have put the item there, and a marketplace answers a withdraw of\n * an item it does not have as done. Only a store with no live connection any\n * more (archived, removed) ends WITHDRAWN at once: there is nobody to tell.\n */\nexport async function withdrawFromCatalogue(ctx: EngineContext, target: CatalogueTarget): Promise<CatalogueActionResult> {\n const table = await usableTable(ctx, target.provider);\n if (!table) return refused(\"UNSUPPORTED\");\n const existing = await findRow(table, target);\n if (!existing || existing.status === \"WITHDRAWN\") return { kind: \"unchanged\", publication: existing && viewOf(existing) };\n if (existing.status === \"WITHDRAWING\") return queue(ctx, existing, \"withdraw\");\n const now = ctx.ports.clock.now();\n // No live connection (archived, removed): nothing to tell, so it is out here and now.\n const local = (await connectionMerchantId(ctx, target.clientId, target.provider)) === null;\n const data = local\n ? { status: \"WITHDRAWN\", withdrawnAt: now, requestedAt: now, ...NO_FAILURE }\n : { status: \"WITHDRAWING\", requestedAt: now, ...NO_FAILURE };\n const moved = await table.updateMany({ where: { id: existing.id, status: existing.status }, data });\n // Lost a race with another write: answer what the row now says.\n const row = (await findRow(table, target)) ?? existing;\n if (moved.count === 0 || local) {\n ctx.ports.publishChanged(target.clientId);\n return { kind: \"unchanged\", publication: viewOf(row) };\n }\n return queue(ctx, row, \"withdraw\");\n}\n\n/**\n * Where these products stand on these marketplaces, in ONE read: a product's\n * page asks for one product on every connected marketplace; a list asks for\n * many. Rows only for what was ever switched on.\n */\nexport async function readCatalogueState(\n ctx: EngineContext,\n input: { clientId: string; productIds: readonly string[]; providers?: readonly string[] },\n): Promise<CataloguePublicationView[]> {\n const table = await catalogueTable(ctx);\n if (!table || input.productIds.length === 0) return [];\n const rows = (await table.findMany({\n where: {\n clientId: input.clientId,\n productId: { in: [...input.productIds] },\n ...(input.providers ? { provider: { in: [...input.providers] } } : {}),\n },\n select: CATALOGUE_ROW_SELECT,\n })) as CatalogueRow[];\n return rows.map(viewOf);\n}\n\n/**\n * Every product a pull marketplace's menu lists: switched on, on its way, or\n * already published once and since FAILED to be published again (it stays,\n * at the price last sent, until it is withdrawn).\n */\nconst IN_MENU = [\"PUBLISHING\", \"PUBLISHED\", \"FAILED\"];\n\n/** Whether a row belongs in the served menu, and at which price. */\nfunction menuPrice(row: CatalogueRow, storePrice: number): number | null {\n if (row.status !== \"FAILED\") return row.priceCents ?? storePrice;\n // Published, and not withdrawn since: a withdraw → re-publish that FAILED is\n // not on the marketplace's menu, so it is not listed at an old price.\n const live = row.publishedAt !== null && (row.withdrawnAt === null || row.withdrawnAt < row.publishedAt);\n const republishFailed = row.failedAction === \"PUBLISH\" && live;\n return republishFailed ? (row.sentPriceCents ?? row.priceCents ?? storePrice) : null;\n}\n\n/**\n * The menu part of the document a pull marketplace reads, for the host to\n * serve (merged into the rest of that document, which is the host's). Built\n * from every product switched on for the connection, read through the host's\n * catalogue port; a product that no longer exists is left out.\n */\nexport async function readCatalogueDocument(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; options: CatalogueMenuOptions },\n): Promise<CatalogueDocumentResult> {\n const catalogue = ctx.registry.get(input.provider)?.catalogue;\n const table = await usableTable(ctx, input.provider);\n if (!table || catalogue?.mode !== \"pull\") return { kind: \"refused\", code: \"UNSUPPORTED\" };\n const connection = await catalogueConnection(ctx, input.clientId, input.provider);\n if (\"problem\" in connection) return { kind: \"refused\", code: \"NOT_CONNECTED\" };\n const rows = (await table.findMany({\n where: { clientId: input.clientId, provider: input.provider, status: { in: IN_MENU } },\n select: CATALOGUE_ROW_SELECT,\n orderBy: { createdAt: \"asc\" },\n })) as CatalogueRow[];\n const items = (await ctx.ports.catalogue?.items(input.clientId, rows.map((row) => row.productId))) ?? new Map();\n const entries: CatalogueMenuEntry[] = rows.flatMap((row) => {\n const item = items.get(row.productId);\n const priceCents = item ? menuPrice(row, item.priceCents) : null;\n if (!item || priceCents === null) return [];\n return [{ ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage: null }];\n });\n const document = catalogue.menuDocument({ externalMerchantId: connection.externalMerchantId, entries, options: input.options });\n return { kind: \"document\", document };\n}\n","import { cancelAcceptance } from \"./acceptance\";\nimport { failCancellationRequest } from \"./cancellation\";\nimport { awaitOrderBody, merchantMismatch, requeueOwedFetch } from \"./fetch-order\";\nimport { deferInboxEvent, recordInboxEvent, settleInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestSettings } from \"./ingest\";\nimport { connectionMerchantId, resolveIngestionTarget } from \"./integration\";\nimport { markCancelledBeforeIngest } from \"./order-fetch-marks\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * One delivery, start to finish: normalize → inbox → ingest.\n *\n * The ONE path both producers use. The webhook calls it, and so does the\n * reconciliation retry sweep — which is the whole reason it is a module rather\n * than the body of a route handler. Two producers with two copies of this\n * sequence is how a webhook and a poll come to disagree about what an order is,\n * and the disagreement only shows up on the orders that took the unlucky path.\n */\n\n/**\n * Normalize a raw payload through the provider's adapter, or null when no\n * adapter is registered for it or the adapter refuses the payload. The\n * registry is the only dispatch: there is no provider branch here.\n */\nexport function normalizeEvent(\n ctx: EngineContext,\n provider: MarketplaceProvider,\n payload: unknown,\n): NormalizedEvent | null {\n return ctx.registry.get(provider)?.normalize(payload) ?? null;\n}\n\n/** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */\nexport type DeliveryOutcome =\n | { kind: \"ingested\"; orderId: string; unmappedSkus: string[] }\n | { kind: \"cancelled\" }\n | { kind: \"cancellationFailed\" }\n /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */\n | { kind: \"awaitingOrder\" }\n | { kind: \"duplicate\" }\n | { kind: \"ignored\"; reason: string }\n | { kind: \"failed\"; reason: string };\n\n/**\n * Process one delivery for one tenant.\n *\n * NEVER throws. Every failure is caught, recorded on the inbox row, and\n * returned — because the caller is a webhook handler whose answer decides\n * whether the marketplace redelivers, and a 500 out of here would make an\n * ingestion bug indistinguishable from a network one while multiplying the\n * traffic that hits it.\n *\n * The delivery is recorded BEFORE it is processed. That ordering is the durable\n * part of the durable inbox: a process that dies mid-ingest leaves a PENDING\n * row the sweep will retry, whereas processing first and recording after loses\n * the event entirely on exactly the crashes worth surviving.\n */\nexport async function processDelivery(\n ctx: EngineContext,\n input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n },\n): Promise<DeliveryOutcome> {\n const { clientId, event, settings } = input;\n const record = await recordInboxEvent(ctx, { clientId, event, payload: input.payload });\n if (!record.fresh) return { kind: \"duplicate\" };\n\n if (!clientId || !settings) {\n // Stored, not dropped, and the two reasons are kept apart because only one\n // of them is a problem. An order naming a merchant no tenant claims is the\n // loudest possible symptom of a half-finished onboarding, and it is only\n // findable later because the row survived. An order for a store that has\n // simply switched the channel off is not a fault at all — it stays PENDING\n // for the retry sweep to pick up if the store switches it back on.\n const reason = clientId ? \"integration is not enabled\" : \"no tenant claims this merchant\";\n if (clientId) await deferInboxEvent(ctx, record.id, reason);\n else await settleInboxEvent(ctx, record.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n try {\n return await applyEvent(ctx, record.id, clientId, event, settings, input.now);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, record.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n\n/** The event names an order whose body the marketplace serves apart (`orderToFetch`). */\nfunction announcesOrderToFetch(event: NormalizedEvent): boolean {\n return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;\n}\n\n/**\n * Why an order the event CARRIES must not be ingested for this store: it names\n * another merchant than the connection's (a wrong webhook URL, a replay), the\n * rule a fetched order is held to. Read only for an order that names its\n * merchant (an adapter that sets `externalMerchantId` on the order); an order\n * that names none costs no read.\n */\nasync function carriedOrderMismatch(\n ctx: EngineContext,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n): Promise<string | null> {\n if (!order.externalMerchantId) return null;\n // The one column, never the whole target: no credentials opened per order.\n return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));\n}\n\n/**\n * Act on one recorded delivery: cancel, ingest, or deliberately nothing.\n *\n * Extracted so both producers share the ACTION as well as the recording — the\n * webhook and the retry sweep differ only in how they arrived here and in what\n * they do with a throw, never in what an event MEANS.\n */\nasync function applyEvent(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n event: NormalizedEvent,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const outcome = event.cancellationOutcome ?? (event.cancelled ? \"CONFIRMED\" : null);\n if (outcome === \"FAILED\" && event.externalOrderId) {\n // The marketplace refused the store's own cancellation request. Understood\n // and recorded, never IGNORED: it is what tells a person to finish the\n // cancellation on the marketplace's side.\n await failCancellationRequest(ctx, {\n clientId,\n provider: event.provider,\n externalOrderId: event.externalOrderId,\n });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancellationFailed\" };\n }\n\n if (event.cancelled && event.externalOrderId) {\n const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };\n // A cancellation that outran a fetched order's body leaves its marker, so\n // the fetch that follows ingests nothing.\n if (!(await cancelAcceptance(ctx, { ...order, now }))) await markCancelledBeforeIngest(ctx, order);\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"cancelled\" };\n }\n\n if (announcesOrderToFetch(event)) {\n // The event announces an order whose body the marketplace serves apart.\n // Fetching is a call to the marketplace, so it is a job's, never this\n // request's: the row waits PENDING and the fetch is queued.\n await awaitOrderBody(ctx, clientId, inboxId);\n return { kind: \"awaitingOrder\" };\n }\n\n if (!event.order) {\n // An event type this ingestion does not act on. Marketplaces emit a wide\n // stream (dispatched, concluded, driver assigned…) and most of it is not an\n // order; IGNORED says \"understood, nothing to do\" and keeps it out of the\n // retry sweep, which FAILED would not.\n const reason = `no order body on ${event.eventType}`;\n await settleInboxEvent(ctx, inboxId, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n\n return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);\n}\n\n/** Ingest the order an event carries, unless it names another merchant than the connection's. */\nasync function ingestCarried(\n ctx: EngineContext,\n inboxId: string,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n settings: IngestSettings,\n now: Date | undefined,\n): Promise<DeliveryOutcome> {\n const mismatch = await carriedOrderMismatch(ctx, clientId, order);\n if (mismatch) {\n // FAILED, so the reconciliation sweep retries it once the connection's\n // merchant id is corrected, within the inbox's attempt bound.\n await settleInboxEvent(ctx, inboxId, \"FAILED\", mismatch);\n ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);\n return { kind: \"failed\", reason: mismatch };\n }\n const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });\n await settleInboxEvent(ctx, inboxId, \"PROCESSED\");\n return { kind: \"ingested\", orderId: result.orderId, unmappedSkus: result.unmappedSkus };\n}\n\n/**\n * Re-run a delivery already sitting in the inbox.\n *\n * Used by the retry sweep. It re-reads the store's CURRENT settings rather than\n * whatever they were when the event first arrived — a store that connected the\n * channel properly an hour after the first order came in should have that order\n * ingested on the retry, which is the case this exists for.\n */\nexport async function reprocessStoredDelivery(\n ctx: EngineContext,\n input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown; receivedAt?: Date | null },\n): Promise<DeliveryOutcome> {\n const event = normalizeEvent(ctx, input.provider, input.payload);\n if (!event) {\n const reason = \"payload no longer normalizes\";\n await settleInboxEvent(ctx, input.id, \"IGNORED\", reason);\n return { kind: \"ignored\", reason };\n }\n const target = await resolveIngestionTarget(ctx, input.clientId, input.provider);\n if (!target?.enabled) {\n // Still not ready. Deferred rather than settled, for the same reason as on\n // arrival — and the attempt counter is what eventually retires it, so a\n // store that never switches the channel on does not have its inbox re-read\n // forever.\n const reason = \"integration is not enabled\";\n await deferInboxEvent(ctx, input.id, reason);\n return { kind: \"ignored\", reason };\n }\n // A row waiting for its order body is the fetch job's: re-queued, never fetched here.\n if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);\n try {\n return await applyEvent(\n ctx,\n input.id,\n input.clientId,\n event,\n { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },\n undefined,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n await settleInboxEvent(ctx, input.id, \"FAILED\", reason);\n return { kind: \"failed\", reason };\n }\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport type { CancellationFailureReason, EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * What the host's order reads need to draw a marketplace order: where its\n * aceite and its cancellation request stand, and where a person goes when the\n * API could not do it. One read for a batch, so a list stays one statement.\n */\nexport interface MarketplaceOrderState {\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: AcceptanceStatus;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellation: CancellationStatus | null;\n cancellationReasonCode: string | null;\n /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */\n cancellationFailure: CancellationFailureReason | null;\n /** The adapter's app link, or null when no adapter is registered for it. */\n appUrl: string | null;\n}\n\ninterface StateRow {\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 cancellationFailureReason: string | null;\n}\n\n/** The state of each of these orders that is a marketplace order, keyed by id. */\nexport async function readOrderStates(\n ctx: EngineContext,\n clientId: string,\n orderIds: readonly string[],\n): Promise<Map<string, MarketplaceOrderState>> {\n if (orderIds.length === 0) return new Map();\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, orderId: { in: [...orderIds] } },\n 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 cancellationFailureReason: true,\n },\n })) as StateRow[];\n return new Map(\n rows.map((row) => {\n const adapter = ctx.registry.get(row.provider);\n const state: MarketplaceOrderState = {\n orderId: row.orderId,\n provider: row.provider,\n externalOrderId: row.externalOrderId,\n externalDisplayId: row.externalDisplayId,\n status: row.status as AcceptanceStatus,\n confirmedAt: row.confirmedAt,\n confirmFailedAt: row.confirmFailedAt,\n cancellation: row.cancellationStatus as CancellationStatus | null,\n cancellationReasonCode: row.cancellationReasonCode,\n cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,\n appUrl: adapter ? adapter.appLink(row) : null,\n };\n return [row.orderId, state];\n }),\n );\n}\n","import {\n cancelAcceptance,\n expireLapsedAcceptances,\n listPendingAcceptances,\n type ExpirySweepResult,\n type PendingAcceptance,\n} from \"./acceptance\";\nimport {\n upsertIntegrations,\n upsertMenuLinks,\n type BulkResult,\n type IntegrationRowInput,\n type MenuLinkRowInput,\n} from \"./bulk\";\nimport {\n decideMany,\n decideOne,\n recordStoreCancellation,\n type DecideManyResult,\n type DecisionInput,\n type DecisionResult,\n} from \"./decisions\";\nimport {\n publishToCatalogue,\n readCatalogueDocument,\n readCatalogueState,\n withdrawFromCatalogue,\n type CatalogueActionResult,\n type CatalogueDocumentResult,\n type CataloguePublishInput,\n type CatalogueTarget,\n} from \"./catalogue\";\nimport { runCatalogue, type CatalogueJobPayload, type CatalogueOutcome } from \"./catalogue-job\";\nimport type { CatalogueMenuOptions } from \"./catalogue-port\";\nimport type { CataloguePublicationView } from \"./catalogue-store\";\nimport {\n runFetchOrder,\n type FetchOrderJobPayload,\n type FetchOrderOutcome,\n} from \"./fetch-order\";\nimport { sweepOutbound, type OutboundSweepResult } from \"./outbound-sweep\";\nimport type {\n AdapterTokenCache,\n CancellationReason,\n MarketplaceAdapter,\n OutboundOrderRef,\n} from \"./adapter\";\nimport { listRetryableInboxEvents, type PendingInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from \"./ingest\";\nimport {\n listMarketplaceIntegrations,\n resolveIngestionTarget,\n resolveTenantByMerchant,\n saveMarketplaceIntegration,\n type IngestionTarget,\n type MarketplaceIntegrationView,\n type SaveMarketplaceIntegrationInput,\n} from \"./integration\";\nimport { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from \"./menu-links\";\nimport { runOutbound, type OutboundAttempt, type OutboundOutcome } from \"./outbound\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport {\n normalizeEvent,\n processDelivery,\n reprocessStoredDelivery,\n type DeliveryOutcome,\n} from \"./pipeline\";\nimport type { EngineContext, MarketplaceEngineConfig } from \"./ports\";\nimport { createAdapterRegistry, suggestReason } from \"./registry\";\nimport { readOrderStates, type MarketplaceOrderState } from \"./state\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/** Everything the mounted engine can do, with the ports and adapters bound in. */\nexport interface MarketplaceEngine {\n /** Every registered marketplace, in registration order. */\n providers(): readonly MarketplaceProvider[];\n /** Whether a provider id (a URL segment, a body field) names a registered adapter. */\n knows(provider: string): provider is MarketplaceProvider;\n /** The adapter itself: its capabilities, reasons and app link. Null when unknown. */\n adapter(provider: string): MarketplaceAdapter | null;\n /** The marketplace's reasons, static and offline. Empty when unknown. */\n reasons(provider: string): readonly CancellationReason[];\n /** The reason a host preselects, given whether the order is short of an item. */\n suggestReason(provider: string, input: { itemUnavailable: boolean }): CancellationReason | null;\n /** Where a person goes to act on the marketplace's side. Null when unknown. */\n appLink(provider: string, order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string | null;\n\n /** Turn a raw payload into the canonical shape, or null if nothing does. */\n normalize(provider: string, payload: unknown): NormalizedEvent | null;\n /** Read the provider's signature header off a request. */\n readSignature(provider: string, header: (name: string) => string | null): string | null;\n /** Verify a delivery. An unknown provider is never verified, so never accepted. */\n verifySignature(provider: string, rawBody: string, signature: string | null, secret: string | null): boolean;\n /** Which tenant a delivery belongs to, from the merchant id it names. */\n tenantFor(provider: MarketplaceProvider, externalMerchantId: string): Promise<string | null>;\n /** The connection behind one (tenant, marketplace), for the ingestion path. */\n target(clientId: string, provider: MarketplaceProvider): Promise<IngestionTarget | null>;\n /** Ingest ONE already-normalized order, bypassing the inbox. Idempotent. */\n ingest(input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n }): Promise<IngestResult>;\n /** Record and act on one delivery. Never throws. */\n deliver(input: {\n clientId: string | null;\n event: NormalizedEvent;\n payload: unknown;\n settings: IngestSettings | null;\n now?: Date;\n }): Promise<DeliveryOutcome>;\n\n /** This store's connections, secrets withheld; archived ones only when asked. */\n integrations(\n clientId: string,\n options?: { providers?: readonly string[]; includeArchived?: boolean },\n ): Promise<MarketplaceIntegrationView[]>;\n /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */\n saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;\n /** Create, patch, archive or unarchive many connections, all-or-nothing. */\n upsertIntegrations(input: {\n clientId: string;\n actorId: string | null;\n rows: readonly IntegrationRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceIntegrationView>>;\n\n /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */\n menuLinks(input: {\n clientId: string;\n provider?: MarketplaceProvider;\n unmappedOnly?: boolean;\n ids?: readonly string[];\n }): Promise<MarketplaceMenuLinkView[]>;\n /** Map or unmap many SKUs, all-or-nothing. */\n upsertMenuLinks(input: {\n clientId: string;\n rows: readonly MenuLinkRowInput[];\n validateOnly?: boolean;\n }): Promise<BulkResult<MarketplaceMenuLinkView>>;\n /** Map or unmap ONE SKU. `null` = the catalog id is not this tenant's. */\n setMenuLink(input: { clientId: string } & MenuLinkRowInput): Promise<MarketplaceMenuLinkView | null>;\n\n /** Orders still on the clock, soonest deadline first; `orderIds` narrows. */\n pending(clientId: string, orderIds?: readonly string[]): Promise<PendingAcceptance[]>;\n /** Decide many orders, all-or-nothing, the host admitting each inside the claim's transaction. */\n decideMany(input: {\n clientId: string;\n decisions: readonly DecisionInput[];\n validateOnly?: boolean;\n now?: Date;\n }): Promise<DecideManyResult>;\n /** Decide ONE order (`decideMany` with one decision). */\n decide(input: { clientId: string; now?: Date } & DecisionInput): Promise<DecisionResult>;\n /** The store cancelled through the host's own cancel: stamp and queue the request. */\n recordStoreCancellation(input: {\n clientId: string;\n orderId: string;\n reasonCode?: string | null;\n offendingSkus?: readonly string[];\n now?: Date;\n }): Promise<DecisionResult>;\n /** The marketplace cancelled an order we already have. */\n cancel(input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n now?: Date;\n }): Promise<boolean>;\n /** Where each of these orders' acceptance and cancellation stand. */\n orderStates(clientId: string, orderIds: readonly string[]): Promise<Map<string, MarketplaceOrderState>>;\n\n /** Expire every order whose deadline has passed, across all tenants. */\n expireLapsed(now?: Date): Promise<ExpirySweepResult>;\n /** Deliveries recorded but never processed, oldest first. */\n retryable(): Promise<PendingInboxEvent[]>;\n /** Re-run one stored delivery against the store's CURRENT settings. */\n reprocess(event: PendingInboxEvent): Promise<DeliveryOutcome>;\n /** Re-queue every outbound call still owed (the `marketplace.outbound-sweep` job's body). */\n sweepOutbound(now?: Date): Promise<OutboundSweepResult>;\n /** Run one queued outbound call (the `marketplace.outbound` job's body). */\n runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;\n /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */\n runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;\n\n /**\n * How this marketplace's catalogue is published (`push`, `pull`), or null\n * when it cannot be: the adapter states no catalogue, or the host bound no\n * catalogue port (FUT-4768).\n */\n catalogueMode(provider: string): \"push\" | \"pull\" | null;\n /** Put a product in a marketplace's catalogue (or send it again), with an optional price for it. Queued. */\n publish(input: CataloguePublishInput): Promise<CatalogueActionResult>;\n /** Take a product out of a marketplace's catalogue. Queued. */\n withdraw(input: CatalogueTarget): Promise<CatalogueActionResult>;\n /** Where these products stand on these marketplaces, in one read. */\n catalogueState(input: {\n clientId: string;\n productIds: readonly string[];\n providers?: readonly string[];\n }): Promise<CataloguePublicationView[]>;\n /** The menu part of the document a PULL marketplace reads, for the host to serve. */\n catalogueDocument(input: {\n clientId: string;\n provider: MarketplaceProvider;\n options: CatalogueMenuOptions;\n }): Promise<CatalogueDocumentResult>;\n /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */\n runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;\n}\n\n/**\n * Mount the engine onto a host.\n *\n * Every port is REQUIRED and there are no defaults: a default would let a\n * second host silently inherit the first one's answers. The adapter list is\n * validated here (`createAdapterRegistry`), so a malformed adapter fails at\n * boot rather than on the first order it would have mangled.\n */\nexport function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine {\n const { adapters, ...ports } = config;\n const registry = createAdapterRegistry(adapters);\n const tokens: AdapterTokenCache = new Map();\n const ctx: EngineContext = { ports, registry, tokens };\n\n return {\n providers: () => registry.providers(),\n knows: (provider): provider is MarketplaceProvider => registry.has(provider),\n adapter: (provider) => registry.get(provider),\n reasons: (provider) => registry.get(provider)?.cancellationReasons() ?? [],\n suggestReason: (provider, input) => {\n const adapter = registry.get(provider);\n return adapter ? suggestReason(adapter, input) : null;\n },\n appLink: (provider, order) => registry.get(provider)?.appLink(order) ?? null,\n\n normalize: (provider, payload) => normalizeEvent(ctx, provider, payload),\n readSignature: (provider, header) => registry.get(provider)?.readSignature(header) ?? null,\n // An unknown provider cannot be verified, so it is not accepted: trusting\n // what cannot be checked is how an unsigned endpoint ships by omission.\n verifySignature: (provider, rawBody, signature, secret) =>\n registry.get(provider)?.verifySignature(rawBody, signature, secret) ?? false,\n tenantFor: (provider, externalMerchantId) =>\n resolveTenantByMerchant(ctx, provider, externalMerchantId),\n target: (clientId, provider) => resolveIngestionTarget(ctx, clientId, provider),\n ingest: (input) => ingestMarketplaceOrder(ctx, input),\n deliver: (input) => processDelivery(ctx, input),\n\n integrations: (clientId, options) => listMarketplaceIntegrations(ctx, clientId, options),\n saveIntegration: async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()),\n upsertIntegrations: (input) => upsertIntegrations(ctx, input),\n\n menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),\n upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),\n setMenuLink: async ({ clientId, ...row }) => {\n const result = await upsertMenuLinks(ctx, { clientId, rows: [row] });\n return result.kind === \"saved\" ? (result.rows[0] ?? null) : null;\n },\n\n pending: (clientId, orderIds) => listPendingAcceptances(ctx, clientId, orderIds),\n decideMany: (input) => decideMany(ctx, input),\n decide: (input) => decideOne(ctx, input),\n recordStoreCancellation: (input) => recordStoreCancellation(ctx, input),\n cancel: (input) => cancelAcceptance(ctx, input),\n orderStates: (clientId, orderIds) => readOrderStates(ctx, clientId, orderIds),\n\n expireLapsed: (now) => expireLapsedAcceptances(ctx, now ?? ports.clock.now()),\n retryable: () => listRetryableInboxEvents(ctx),\n reprocess: (event) => reprocessStoredDelivery(ctx, event),\n sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),\n runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),\n runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),\n\n // Null too when the host bound no catalogue port: nothing could be published.\n catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),\n publish: (input) => publishToCatalogue(ctx, input),\n withdraw: (input) => withdrawFromCatalogue(ctx, input),\n catalogueState: (input) => readCatalogueState(ctx, input),\n catalogueDocument: (input) => readCatalogueDocument(ctx, input),\n runCatalogue: (payload, attempt) => runCatalogue(ctx, payload, attempt),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,WAAc,MAAoB,OAA2B,MAAc,OAA8B;AAChH,QAAM,OAAO,oBAAI,IAAY;AAC7B,SAAO,KAAK,QAAQ,CAAC,KAAK,UAAU;AAClC,UAAM,MAAM,MAAM,GAAG;AACrB,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAClB,WAAK,I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,IACf,SAAS,wBAAC,UAAU,mBAAmB,KAAK,KAAK,GAAxC;AAAA,IACT,UAAU,wBAAC,UAAU,sBAAsB,KAAK,KAAK,GAA3C;AAAA,IACV,gBAAgB,wBAAC,UAAU,mBAAmB,KAAK,KAAK,GAAxC;AAAA,IAChB,mBAAmB,wBAAC,UAAU,sBAAsB,KAAK,KAAK,GAA3C;AAAA,IACnB,cAAc,wBAAC,SAAS,YAAY,aAAa,KAAK,SAAS,OAAO,GAAxD;AAAA,EAChB;AACF;AA9DgB;","names":["refused","duplicates"]}
@@ -1,7 +1,7 @@
1
- import { S as OutboundJobPayload } from '../engine-KrgZ4pA4.js';
1
+ import { a9 as OutboundJobPayload, F as FetchOrderJobPayload, j as CatalogueJobPayload } from '../engine-CZsP8KWd.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
- import '../adapter-BggtVFf9.js';
4
+ import '../adapter-0l_EmuJA.js';
5
5
  import 'zod';
6
6
 
7
7
  declare const marketplaceServerManifest: {
@@ -15,6 +15,8 @@ declare const marketplaceServerManifest: {
15
15
  readonly "expire-acceptances": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
16
16
  readonly "reconcile-inbox": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
17
17
  readonly outbound: _12_apps_wiring.WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
18
+ readonly "fetch-order": _12_apps_wiring.WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
19
+ readonly catalogue: _12_apps_wiring.WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps>;
18
20
  readonly "outbound-sweep": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
19
21
  };
20
22
  };
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-NGNEL4HS.js";
4
+ } from "../chunk-AYYBRQJV.js";
5
5
  import "../chunk-UYFYGGCS.js";
6
- import "../chunk-DVIRN42O.js";
6
+ import "../chunk-XUAFXNOH.js";
7
7
  import "../chunk-7QVYU63E.js";
8
8
 
9
9
  // src/manifest/server.ts
@@ -0,0 +1,14 @@
1
+ /** The Rappi adapter's en-US pack: the same reasons, in English. */
2
+ declare const RAPPI_ADAPTER_COPY_EN_US: {
3
+ readonly reasonLabels: {
4
+ readonly ITEM_OUT_OF_STOCK: "Item unavailable";
5
+ readonly ITEM_NOT_FOUND: "Item not found";
6
+ readonly ITEM_WRONG_PRICE: "Wrong item price";
7
+ readonly ORDER_MISSING_INFORMATION: "Order information missing";
8
+ readonly ORDER_MISSING_ADDRESS_INFORMATION: "Address information missing";
9
+ readonly ORDER_TOTAL_INCORRECT: "Order total incorrect";
10
+ };
11
+ readonly missingStreetNumber: "no number";
12
+ };
13
+
14
+ export { RAPPI_ADAPTER_COPY_EN_US };
@@ -0,0 +1,18 @@
1
+ import "../chunk-7QVYU63E.js";
2
+
3
+ // src/rappi/en-US.ts
4
+ var RAPPI_ADAPTER_COPY_EN_US = {
5
+ reasonLabels: {
6
+ ITEM_OUT_OF_STOCK: "Item unavailable",
7
+ ITEM_NOT_FOUND: "Item not found",
8
+ ITEM_WRONG_PRICE: "Wrong item price",
9
+ ORDER_MISSING_INFORMATION: "Order information missing",
10
+ ORDER_MISSING_ADDRESS_INFORMATION: "Address information missing",
11
+ ORDER_TOTAL_INCORRECT: "Order total incorrect"
12
+ },
13
+ missingStreetNumber: "no number"
14
+ };
15
+ export {
16
+ RAPPI_ADAPTER_COPY_EN_US
17
+ };
18
+ //# sourceMappingURL=en-US.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/rappi/en-US.ts"],"sourcesContent":["import type { RappiAdapterCopy } from \"./copy\";\n\n/** The Rappi adapter's en-US pack: the same reasons, in English. */\nexport const RAPPI_ADAPTER_COPY_EN_US = {\n reasonLabels: {\n ITEM_OUT_OF_STOCK: \"Item unavailable\",\n ITEM_NOT_FOUND: \"Item not found\",\n ITEM_WRONG_PRICE: \"Wrong item price\",\n ORDER_MISSING_INFORMATION: \"Order information missing\",\n ORDER_MISSING_ADDRESS_INFORMATION: \"Address information missing\",\n ORDER_TOTAL_INCORRECT: \"Order total incorrect\",\n },\n missingStreetNumber: \"no number\",\n} as const satisfies RappiAdapterCopy;\n"],"mappings":";;;AAGO,IAAM,2BAA2B;AAAA,EACtC,cAAc;AAAA,IACZ,mBAAmB;AAAA,IACnB,gBAAgB;AAAA,IAChB,kBAAkB;AAAA,IAClB,2BAA2B;AAAA,IAC3B,mCAAmC;AAAA,IACnC,uBAAuB;AAAA,EACzB;AAAA,EACA,qBAAqB;AACvB;","names":[]}