@12-apps/marketplace 1.7.0 → 1.8.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 (67) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +56 -0
  3. package/dist/99food/index.d.ts +4 -2
  4. package/dist/99food/index.js +32 -3
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +3 -3
  18. package/dist/ifood/index.d.ts +1 -1
  19. package/dist/ifood/index.js +29 -3
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +104 -7
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/index.d.ts +3 -0
  25. package/dist/manifest/index.js +1 -1
  26. package/dist/manifest/server.d.ts +2 -2
  27. package/dist/manifest/server.js +3 -3
  28. package/dist/rappi/index.d.ts +7 -1
  29. package/dist/rappi/index.js +20 -3
  30. package/dist/rappi/index.js.map +1 -1
  31. package/dist/server/index.d.ts +6 -2
  32. package/dist/server/index.js +3 -3
  33. package/package.json +1 -1
  34. package/prisma/marketplace.prisma +45 -1
  35. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  36. package/src/99food/index.ts +6 -0
  37. package/src/99food/normalize.ts +7 -1
  38. package/src/99food/outbound.ts +55 -0
  39. package/src/core/adapter.ts +41 -1
  40. package/src/core/bulk.ts +1 -1
  41. package/src/core/engine.ts +9 -0
  42. package/src/core/ingest.ts +6 -0
  43. package/src/core/integration.ts +17 -0
  44. package/src/core/lifecycle-port.ts +16 -0
  45. package/src/core/lifecycle.ts +133 -0
  46. package/src/core/outbound-queue.ts +24 -4
  47. package/src/core/outbound-sweep.ts +49 -5
  48. package/src/core/outbound.ts +11 -0
  49. package/src/core/pipeline.ts +22 -2
  50. package/src/core/ports.ts +39 -3
  51. package/src/core/status-inform.ts +51 -0
  52. package/src/core/status-job.ts +207 -0
  53. package/src/core/status-store.ts +85 -0
  54. package/src/core/types.ts +14 -0
  55. package/src/ifood/index.ts +7 -1
  56. package/src/ifood/normalize.ts +17 -0
  57. package/src/ifood/outbound.ts +35 -0
  58. package/src/index.ts +6 -0
  59. package/src/rappi/index.ts +6 -1
  60. package/src/rappi/normalize.ts +6 -0
  61. package/src/rappi/outbound.ts +31 -2
  62. package/src/server/mcp.ts +2 -0
  63. package/src/server/webhook.ts +3 -1
  64. package/dist/chunk-L3DCOZUU.js.map +0 -1
  65. package/dist/chunk-SJUKBCVO.js.map +0 -1
  66. package/dist/chunk-UYFYGGCS.js.map +0 -1
  67. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/contribution.ts","../src/server/mcp.ts"],"sourcesContent":["import type { WirePermissionsContribution } from \"@12-apps/wiring\";\n\n/**\n * THIS PACKAGE'S OWN PERMISSION CONTRIBUTION.\n *\n * Two privileges, kept apart on purpose (the ADR-0117 pattern of naming the\n * act, not the role):\n *\n * - `marketplace:manage` — CONNECT a marketplace (store its credentials, turn\n * it on, set auto-accept and the acceptance window) and MAP its SKUs to the\n * catalog. Committing the store to a commercial relationship and teaching\n * the engine what a SKU means are the same person's job.\n * - `marketplace:decide` — read the acceptance queue and answer it: accept or\n * refuse an order with a reason. That is whoever is on the floor when the\n * clock runs, and a queue only an owner could answer would lapse.\n *\n * Which roles hold either is the HOST's decision; the package only names\n * them. The shape is `@12-apps/rbac`'s `PermissionContribution`, taken from\n * the wiring contract's type-only twin. No labels: a label is a word in a\n * language, and the vocabulary a picker renders is the host's.\n */\nexport const MARKETPLACE_PERMISSIONS = {\n source: \"@12-apps/marketplace\",\n ids: [\"marketplace:manage\", \"marketplace:decide\"],\n permissions: {\n \"marketplace:manage\": { kind: \"class\" },\n \"marketplace:decide\": { kind: \"class\" },\n },\n} as const satisfies WirePermissionsContribution;\n\n/** Connect a marketplace and map its SKUs. */\nexport const MARKETPLACE_MANAGE = \"marketplace:manage\";\n/** Read and answer the acceptance queue. */\nexport const MARKETPLACE_DECIDE = \"marketplace:decide\";\n","import { z } from \"zod\";\n\nimport type { WireMcpTool } from \"@12-apps/wiring\";\n\n/**\n * The marketplace tool surface — authored ONCE, beside the route descriptors\n * it proxies to, and reused as the runtime validators. The advertised schema\n * and what a handler accepts are the same objects, so they cannot drift.\n *\n * The shape is the bulk-upsert protocol: ONE bulk write per entity\n * (connections, SKU links, decisions), each taking a list, all-or-nothing,\n * `validateOnly` supported, idempotent on the natural key, every refusal\n * returned with its path; a connection is ARCHIVED, never deleted. A read is\n * the entity's `list*` tool, taking `ids`.\n *\n * Every input is STRICT (an unknown key is refused, never stripped), and the\n * cross-row checks (a key twice in one call) are part of the schema. The\n * provider is checked for SHAPE here and for EXISTENCE at runtime, because\n * the set of marketplaces is the set of adapters a host registered.\n *\n * Paths are RELATIVE to the http capability's mount (`/api` in the origin\n * host). The webhook is not a tool: a marketplace's server-to-server callback\n * is not a capability anybody invokes.\n */\n\nconst providerSchema = z.string().regex(/^[A-Z][A-Z0-9_]*$/u);\nconst environmentSchema = z.enum([\"SANDBOX\", \"PRODUCTION\"]);\nconst booleanText = z.enum([\"true\", \"false\"]);\n/** A comma-separated id list in a query string: `ids=a,b`. */\nconst idsText = z\n .string()\n .transform((text) => text.split(\",\").map((id) => id.trim()).filter((id) => id !== \"\"))\n .pipe(z.array(z.string().min(1)).min(1).max(100));\n\n/** Flag every row whose key repeats an earlier one, at that row's path. */\nfunction noDuplicates<T>(list: string, field: string, keyOf: (row: T) => string) {\n return (rows: readonly T[], ctx: z.RefinementCtx): void => {\n const seen = new Set<string>();\n rows.forEach((row, index) => {\n const key = keyOf(row);\n if (seen.has(key)) {\n ctx.addIssue({ code: \"custom\", path: [index, field], message: `${field} repeats an earlier row of ${list}` });\n }\n seen.add(key);\n });\n };\n}\n\n/** Path params for the tenant-scoped marketplace resource. */\nexport const marketplaceParams = z.strictObject({\n tenantSlug: z.string().min(1),\n});\n\n/** Which connections to read. */\nexport const listMarketplaceIntegrationsQuery = z.strictObject({\n ids: idsText.optional(),\n includeArchived: booleanText.optional(),\n});\n\n/** The credential half of a save. Absent leaves the stored secrets alone. */\nconst credentialsInput = z.strictObject({\n clientId: z.string().trim().min(1),\n clientSecret: z.string().trim().min(1),\n webhookSecret: z.string().trim().min(1).nullable().optional(),\n});\n\n/** Create or patch one connection; any subset of its settings. */\nconst integrationUpsertInput = z.strictObject({\n operation: z.literal(\"upsert\").optional(),\n provider: providerSchema,\n enabled: z.boolean().optional(),\n environment: environmentSchema.optional(),\n externalMerchantId: z.string().trim().min(1).nullable().optional(),\n autoAccept: z.boolean().optional(),\n // Below a minute nothing human can answer in time; above an hour the\n // deadline has stopped describing anything a marketplace would wait for.\n ackSlaSeconds: z.number().int().min(60).max(3600).optional(),\n credentials: credentialsInput.optional(),\n});\n\n/** Archive (reversible) or unarchive one connection, with an optional reason. */\nconst integrationArchiveInput = z.strictObject({\n operation: z.enum([\"archive\", \"unarchive\"]),\n provider: providerSchema,\n reason: z.string().trim().min(1).max(500).nullable().optional(),\n});\n\n/** Many connection changes, all-or-nothing. */\nexport const upsertMarketplaceIntegrationsBody = z.strictObject({\n validateOnly: z.boolean().optional(),\n integrations: z\n .array(z.union([integrationArchiveInput, integrationUpsertInput]))\n .min(1)\n .max(20)\n .superRefine(noDuplicates(\"integrations\", \"provider\", (row) => row.provider)),\n});\n\n/** Filters for the SKU map. `unmapped=true` IS the attention list. */\nexport const listMarketplaceMenuLinksQuery = z.strictObject({\n provider: providerSchema.optional(),\n // A query string is text: \"false\" must mean false.\n unmapped: booleanText.optional(),\n ids: idsText.optional(),\n});\n\n/** Map one external SKU to a catalog id, or unmap it with `menuItemId: null`. */\nconst menuLinkInput = z.strictObject({\n provider: providerSchema,\n externalSku: z.string().trim().min(1),\n externalName: z.string().trim().min(1).optional(),\n menuItemId: z.string().min(1).nullable(),\n});\n\n/** Many SKU links, all-or-nothing; idempotent on (provider, externalSku). */\nexport const upsertMarketplaceMenuLinksBody = z.strictObject({\n validateOnly: z.boolean().optional(),\n links: z\n .array(menuLinkInput)\n .min(1)\n .max(200)\n .superRefine(noDuplicates(\"links\", \"externalSku\", (row) => `${row.provider}\\u0000${row.externalSku}`)),\n});\n\n/** Which queued orders to read. */\nexport const listMarketplaceAcceptancesQuery = z.strictObject({\n ids: idsText.optional(),\n});\n\n/** What the person confirmed beside an accept, for the host's admission. */\nconst admissionInput = z.strictObject({\n admitStockPastZero: z.boolean().optional(),\n});\n\n/**\n * One decision. An accept may carry the admission and a preparation time; a\n * refusal one of the marketplace's reason codes (its first when omitted) and,\n * for a reason that needs them, the order's offending SKUs. A field of the\n * other kind is refused, not ignored.\n */\nconst decisionInput = z.discriminatedUnion(\"decision\", [\n z.strictObject({\n orderId: z.string().min(1),\n decision: z.literal(\"ACCEPT\"),\n admission: admissionInput.optional(),\n preparationMinutes: z.number().int().min(1).max(240).optional(),\n }),\n z.strictObject({\n orderId: z.string().min(1),\n decision: z.literal(\"REJECT\"),\n reasonCode: z.string().trim().min(1).optional(),\n offendingSkus: z.array(z.string().trim().min(1)).min(1).max(50).optional(),\n }),\n]);\n\n/** Many decisions, all-or-nothing, the host admitting each inside one transaction. */\nexport const decideMarketplaceOrdersBody = z.strictObject({\n validateOnly: z.boolean().optional(),\n decisions: z\n .array(decisionInput)\n .min(1)\n .max(50)\n .superRefine(noDuplicates(\"decisions\", \"orderId\", (row) => row.orderId)),\n});\n\nconst reasonSchema = z.object({\n code: z.string(),\n label: z.string(),\n itemUnavailable: z.boolean(),\n needsItems: z.boolean(),\n});\n\nconst capabilitiesSchema = z.object({\n apiConfirm: z.boolean(),\n apiCancel: z.boolean(),\n cancelAfterAccept: z.boolean(),\n asyncCancellationOutcome: z.boolean(),\n perOrderAppLink: z.boolean(),\n confirmTakesPreparationTime: z.boolean(),\n});\n\n/** A connection as every read returns it: `connected` stands in for the secrets. */\nconst integrationSchema = z.object({\n provider: z.string(),\n enabled: z.boolean(),\n environment: environmentSchema,\n status: z.enum([\"UNVERIFIED\", \"VERIFIED\", \"FAILED\"]),\n externalMerchantId: z.string().nullable(),\n autoAccept: z.boolean(),\n ackSlaSeconds: z.number().int(),\n connected: z.boolean(),\n lastEventAt: z.string().nullable(),\n lastVerifiedAt: z.string().nullable(),\n archivedAt: z.string().nullable(),\n capabilities: capabilitiesSchema.nullable(),\n reasons: z.array(reasonSchema),\n});\n\nconst menuLinkSchema = z.object({\n id: z.string(),\n provider: z.string(),\n externalSku: z.string(),\n externalName: z.string(),\n menuItemId: z.string().nullable(),\n lastSeenAt: z.string(),\n});\n\nconst pendingAcceptanceSchema = z.object({\n id: z.string(),\n orderId: z.string(),\n provider: z.string(),\n externalOrderId: z.string(),\n externalDisplayId: z.string().nullable(),\n totalCents: z.number().int(),\n buyerName: z.string().nullable(),\n acknowledgeBy: z.string().nullable(),\n externalDueAt: z.string().nullable(),\n commissionCents: z.number().int().nullable(),\n unmappedLines: z.number().int(),\n createdAt: z.string().nullable(),\n});\n\nconst decidedSchema = z.object({\n orderId: z.string(),\n status: z.enum([\"ACCEPTED\", \"REJECTED\"]),\n cancellation: z.enum([\"PENDING\", \"REQUESTED\", \"CONFIRMED\", \"FAILED\"]).nullable(),\n reasonCode: z.string().nullable(),\n offendingSkus: z.array(z.string()),\n});\n\nconst BASE = \"/admin/{tenantSlug}/marketplace\";\n\n/** The six marketplace tools: a read and a bulk write per entity. */\nexport const MARKETPLACE_MCP_TOOLS = [\n {\n operationId: \"listMarketplaceIntegrations\",\n method: \"GET\",\n path: BASE,\n summary:\n \"List one or many of a store's marketplace connections (pass `ids` as provider ids, e.g. `ids=IFOOD`): whether each is enabled, its environment, auto-accept, the acknowledgement window, and each marketplace's capabilities and refusal reasons. Archived connections only with `includeArchived=true`. Never returns the stored credentials: `connected` says only whether a set is on file.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n query: listMarketplaceIntegrationsQuery,\n response: z.object({ data: z.array(integrationSchema) }),\n annotations: { readOnly: true },\n },\n {\n operationId: \"upsertMarketplaceIntegrations\",\n method: \"PUT\",\n path: BASE,\n summary:\n \"Create, update, archive or unarchive one or many marketplace connections in one all-or-nothing call. A row is keyed by `provider`; `operation` is `upsert` (default: any subset of the settings; omitting `credentials` keeps the stored secrets, sending them resets the status to UNVERIFIED), `archive` or `unarchive` (reversible, audited, with an optional `reason`). Any problem writes nothing and every problem comes back with its path. `validateOnly: true` checks without writing.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n body: upsertMarketplaceIntegrationsBody,\n response: z.object({ data: z.object({ validateOnly: z.boolean(), integrations: z.array(integrationSchema) }) }),\n annotations: { readOnly: false, destructive: false },\n },\n {\n operationId: \"listMarketplaceMenuLinks\",\n method: \"GET\",\n path: `${BASE}/menu-links`,\n summary:\n \"List a store's marketplace SKU map, or the links named by `ids`: every external SKU an incoming order has carried, and the catalog id it resolves to. `unmapped=true` is the attention list: the SKUs that arrived with nothing behind them, newest-seen first. An unmapped SKU never rejects an order.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n query: listMarketplaceMenuLinksQuery,\n response: z.object({ data: z.array(menuLinkSchema) }),\n annotations: { readOnly: true },\n },\n {\n operationId: \"upsertMarketplaceMenuLinks\",\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n summary:\n \"Map one or many external marketplace SKUs to the store's catalog ids, or unmap them with `menuItemId: null`, in one all-or-nothing call keyed by (`provider`, `externalSku`). A SKU never seen is created, so a store can map ahead of the first order. Applies to orders ingested from now on. Any problem (a catalog id that is not the store's, a repeated SKU) writes nothing; `validateOnly: true` checks without writing.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n body: upsertMarketplaceMenuLinksBody,\n response: z.object({ data: z.object({ validateOnly: z.boolean(), links: z.array(menuLinkSchema) }) }),\n annotations: { readOnly: false, destructive: false },\n },\n {\n operationId: \"listMarketplaceAcceptances\",\n method: \"GET\",\n path: `${BASE}/acceptances`,\n summary:\n \"List the marketplace orders waiting on the store's acceptance, soonest deadline first, or those named by `ids` (order ids). `acknowledgeBy` is the instant the marketplace cancels an unacknowledged order; `unmappedLines` counts the lines that arrived with nothing behind them.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n query: listMarketplaceAcceptancesQuery,\n response: z.object({ data: z.array(pendingAcceptanceSchema) }),\n annotations: { readOnly: true },\n },\n {\n operationId: \"decideMarketplaceOrders\",\n method: \"POST\",\n path: `${BASE}/acceptances`,\n summary:\n \"Accept or refuse one or many marketplace orders on the acceptance clock, all-or-nothing. ACCEPT may carry `admission` (`admitStockPastZero: true` after the store was told an item is short) and `preparationMinutes`. REJECT cancels the order here and asks the marketplace to cancel it, with `reasonCode` from the marketplace's own list (see `listMarketplaceIntegrations`; its first reason when omitted) and, for a reason that needs them, `offendingSkus` from the order. Any problem writes nothing: an unknown code or item is a 422, an order no longer awaiting a decision a 409, and the store's own refusal a 409 with its code (e.g. `MARKETPLACE_STOCK_ASK` with the short items). `validateOnly: true` checks everything without writing.\",\n tags: [\"marketplace\"],\n params: marketplaceParams,\n body: decideMarketplaceOrdersBody,\n response: z.object({ data: z.object({ validateOnly: z.boolean(), decisions: z.array(decidedSchema) }) }),\n annotations: { readOnly: false, destructive: true, openWorld: true },\n },\n] as const satisfies readonly WireMcpTool<z.Zod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AAa,EAAE,UAAU,OAAO,aAAa,MAAM;AAAA,EACrD;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,MAAM,GAAG,IAAI;AAAA,IACb,SACE;AAAA,IACF,MAAM,CAAC,aAAa;AAAA,IACpB,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,EAAE,CAAC;AAAA,IAC7D,aAAa,EAAE,UAAU,KAAK;AAAA,EAChC;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,MAAM,GAAG,IAAI;AAAA,IACb,SACE;AAAA,IACF,MAAM,CAAC,aAAa;AAAA,IACpB,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,GAAG,WAAW,EAAE,MAAM,aAAa,EAAE,CAAC,EAAE,CAAC;AAAA,IACvG,aAAa,EAAE,UAAU,OAAO,aAAa,MAAM,WAAW,KAAK;AAAA,EACrE;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/http.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately. A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 200: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status: 200, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds } : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n return { status: 200, body: { received: true, outcome: outcome.kind } };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? copy.problems[problem.code],\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n ...integrationRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\nimport { AvailabilityRetryError } from \"../core/pause-job\";\nimport type { AvailabilityJobPayload } from \"../core/pause-store\";\n\n/**\n * The engine's eight jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `fetch-order`, on demand: one GET of an order a marketplace's event only\n * announced (`orderToFetch`), then the one ingest path. Three attempts with\n * backoff; the reconciliation sweep re-queues a row still owed.\n * - `catalogue`, on demand: one publish or withdraw of one product on one\n * marketplace's catalogue (FUT-4768). Three attempts with backoff; the\n * last one stamps FAILED with a failure code.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp, a catalogue\n * publish or withdraw on its way) once it is older than the job's own retry\n * span, so a refused enqueue or a dead process loses nothing.\n * - `availability`, on demand: brings one marketplace in line with the host's\n * last pause or resume ask for one store (FUT-4851). Three attempts with\n * backoff; the last one stamps FAILED with a failure code.\n * - `availability-sweep`, every five minutes: resumes a pause past its\n * `until` (the host stopped renewing it), re-queues an ask still owed, and\n * gives up on one older than a day.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,\n * `marketplace.outbound-sweep`, `marketplace.availability` and\n * `marketplace.availability-sweep`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<\n MarketplaceEngine,\n | \"expireLapsed\"\n | \"retryable\"\n | \"reprocess\"\n | \"runOutbound\"\n | \"runFetchOrder\"\n | \"runCatalogue\"\n | \"sweepOutbound\"\n | \"runAvailability\"\n | \"sweepAvailability\"\n >;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n if (pending.length === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The fetch job's attempts: the last one settles the inbox row FAILED. */\nexport const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;\n\nconst fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {\n name: \"fetch-order\",\n attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n // Short: an order waiting for its body is on the store's acceptance clock.\n backoff: { type: \"exponential\", delayMs: 5_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runFetchOrder(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The catalogue job's attempts: the last one stamps FAILED. */\nconst MARKETPLACE_CATALOGUE_ATTEMPTS = 3;\n\nconst catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {\n name: \"catalogue\",\n attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,\n // Short: a person is watching the switch say \"sending\".\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCatalogue(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;\n if (idle) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +\n `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The availability job's attempts: the last one stamps FAILED. */\nexport const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;\n\nconst availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {\n name: \"availability\",\n attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,\n // Short: a store is open on the marketplace while the kitchen is paused.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAvailability(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"availability-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepAvailability();\n if (result.expired + result.requeued + result.givenUp === 0) return;\n context.logger.info(\n `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +\n `gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"fetch-order\": fetchOrder,\n catalogue,\n \"outbound-sweep\": outboundSweep,\n availability,\n \"availability-sweep\": availabilitySweep,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_AVAILABILITY_ATTEMPTS,\n MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS,OAAO,QAAgB,OAAe,QAAiC,CAAC,GAA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