@12-apps/marketplace 1.10.0 → 1.11.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.
- package/ADOPTING.md +36 -0
- package/README.md +63 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CYJzu1c9.d.ts → adapter-CD0SfdVS.d.ts} +124 -1
- package/dist/{chunk-PYHNM47K.js → chunk-DCWOQ5PN.js} +2 -2
- package/dist/{chunk-WVZ2IXFH.js → chunk-OS4TSIFU.js} +190 -12
- package/dist/chunk-OS4TSIFU.js.map +1 -0
- package/dist/chunk-SGOTN5PX.js +345 -0
- package/dist/chunk-SGOTN5PX.js.map +1 -0
- package/dist/{chunk-HEXLCTOG.js → chunk-TVZU4HNT.js} +1 -1
- package/dist/chunk-TVZU4HNT.js.map +1 -0
- package/dist/{chunk-2BA2EHNF.js → chunk-YWMEIMO3.js} +206 -22
- package/dist/chunk-YWMEIMO3.js.map +1 -0
- package/dist/{client-B4EQCRD_.d.ts → client-11sncog4.d.ts} +1 -1
- package/dist/{engine-DK3iV_Kk.d.ts → engine-C_3RK8wC.d.ts} +116 -4
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +5 -2
- package/dist/ifood/index.js +125 -7
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +23 -4
- package/dist/index.js +264 -21
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- package/dist/manifest/index.d.ts +219 -1
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/en-US.d.ts +13 -0
- package/dist/server/en-US.js +13 -0
- package/dist/server/en-US.js.map +1 -1
- package/dist/server/index.d.ts +241 -7
- package/dist/server/index.js +3 -3
- package/dist/server/pt-BR.d.ts +13 -0
- package/dist/server/pt-BR.js +13 -0
- package/dist/server/pt-BR.js.map +1 -1
- package/package.json +1 -1
- package/prisma/marketplace.prisma +41 -0
- package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
- package/src/core/adapter.ts +21 -0
- package/src/core/bulk.ts +43 -8
- package/src/core/engine.ts +59 -3
- package/src/core/integration.ts +60 -32
- package/src/core/link-store.ts +170 -0
- package/src/core/linking-port.ts +100 -0
- package/src/core/linking.ts +363 -0
- package/src/core/merchant-claim.ts +106 -0
- package/src/core/ports.ts +3 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/linking.ts +170 -0
- package/src/ifood/outbound.ts +10 -3
- package/src/index.ts +14 -0
- package/src/server/copy.ts +20 -2
- package/src/server/en-US.ts +13 -0
- package/src/server/index.ts +1 -1
- package/src/server/link-routes.ts +140 -0
- package/src/server/mcp-link.ts +103 -0
- package/src/server/mcp.ts +6 -2
- package/src/server/pt-BR.ts +13 -0
- package/src/server/routes.ts +5 -2
- package/src/server/webhook.ts +86 -0
- package/dist/chunk-2BA2EHNF.js.map +0 -1
- package/dist/chunk-HEXLCTOG.js.map +0 -1
- package/dist/chunk-WVZ2IXFH.js.map +0 -1
- package/dist/chunk-ZO4S3LF4.js +0 -254
- package/dist/chunk-ZO4S3LF4.js.map +0 -1
- /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/http.ts","../src/server/link-routes.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 { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { LinkFailure, LinkPendingView, LinkRefusalCode } from \"../core/linking\";\nimport { MARKETPLACE_MANAGE } from \"./contribution\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport { finishLinkBody, linkMerchantsQuery, linkStateQuery, selectLinkMerchantBody, startLinkBody } from \"./mcp-link\";\n\n/**\n * Linking a store through the software's own marketplace app (FUT-5613), as\n * HTTP, beside the connection routes and behind the same permission:\n *\n * - `GET …/marketplace/link?provider=` — whether linking is available, and the code in progress;\n * - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);\n * - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;\n * - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;\n * - `PUT …/marketplace/link/merchant` — which of them this store is.\n *\n * No answer ever carries a token, a verifier or the app's credentials.\n */\n\nconst BASE = \"/admin/:tenantSlug/marketplace/link\";\n\n/** The HTTP status each refusal answers. */\nconst STATUS: Readonly<Record<LinkRefusalCode, number>> = {\n UNAVAILABLE: 409,\n NO_LINK_IN_PROGRESS: 409,\n LINK_EXPIRED: 409,\n CODE_REFUSED: 422,\n MARKETPLACE_REFUSED: 502,\n NOT_LINKED: 409,\n UNKNOWN_MERCHANT: 422,\n MERCHANT_TAKEN: 409,\n};\n\n/** A failure as the routes answer it: the host's sentence, the code, and the marketplace's own words. */\nfunction failed(config: MarketplaceApiConfig, failure: LinkFailure): WireResponse {\n const words = config.copy.link;\n if (failure.kind === \"retry\") {\n return refuse(503, words?.tryAgain ?? \"MARKETPLACE_UNREACHABLE\", { code: \"MARKETPLACE_UNREACHABLE\" });\n }\n return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {\n code: failure.code,\n ...(failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }),\n });\n}\n\nconst pendingOut = (pending: LinkPendingView | null) => (pending ? { ...pending, expiresAt: pending.expiresAt.toISOString() } : null);\n\nfunction connectionOut(row: MarketplaceIntegrationView) {\n return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };\n}\n\n/** An unknown provider, before anything is asked of the engine. */\nfunction unknown(config: MarketplaceApiConfig, id: string): WireResponse | null {\n return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: \"UNKNOWN_PROVIDER\" });\n}\n\nfunction readRoutes(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(linkStateQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });\n return ok({ available: state.available, pending: pendingOut(state.pending) });\n },\n },\n {\n method: \"GET\",\n path: `${BASE}/merchants`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(linkMerchantsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });\n return result.kind === \"listed\" ? ok(result.merchants) : failed(config, result);\n },\n },\n ];\n}\n\nfunction writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"POST\",\n path: `${BASE}/start`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(startLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });\n return result.kind === \"started\" ? ok(pendingOut(result.pending)) : failed(config, result);\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/finish`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(finishLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });\n if (result.kind !== \"linked\") return failed(config, result);\n return ok({ integration: connectionOut(result.integration), merchants: result.merchants });\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/merchant`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(selectLinkMerchantBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, ...parsed.value });\n return result.kind === \"selected\" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);\n },\n },\n ];\n}\n\n/** The linking routes, in mount order. */\nexport function linkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n return [...readRoutes(config), ...writeRoutes(config)];\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\ninterface Admitted {\n clientId: string;\n provider: string;\n payload: unknown;\n target: IngestionTarget;\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 return deliverAdmitted(config, admitted);\n}\n\n/** Record and act on a delivery whose store and signature are proven. */\nasync function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {\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\n ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus }\n : 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/**\n * The store a delivery to the APP's single address belongs to, and its\n * connection: resolved from the merchant the payload names, then proved by\n * the signature (FUT-5613). The payload is read before it is verified only to\n * find whose key verifies it; nothing of it is acted on until it is.\n */\nasync function admitApp(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<Admitted | WireResponse> {\n const { provider = \"\" } = request.params;\n if (!config.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 const rawBody = await raw.text();\n const payload = parsedJson(rawBody);\n if (payload === undefined) return { status: 400, body: { error: \"invalid_json\" } };\n const found = await appConnection(config, provider, payload);\n if (\"status\" in found) return found;\n // The app's address never takes an unsigned delivery, whatever the store's own setting.\n const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));\n const secret = found.target.webhookSecret;\n if (!secret || !config.engine.verifySignature(provider, rawBody, signature, secret)) {\n config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);\n return UNAUTHORIZED;\n }\n return { ...found, provider, payload };\n}\n\n/** A JSON body, or undefined when it is not JSON. */\nfunction parsedJson(rawBody: string): unknown {\n try {\n return JSON.parse(rawBody) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** The store whose live connection holds the merchant a delivery names, or the 401. */\nasync function appConnection(\n config: MarketplaceApiConfig,\n provider: string,\n payload: unknown,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;\n const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);\n if (!clientId) return UNAUTHORIZED;\n try {\n const target = await config.engine.target(clientId, provider);\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(`marketplace.webhook: app ${provider} key of ${clientId} unavailable: ${String(error)}`);\n return UNAUTHORIZED;\n }\n}\n\n/**\n * `POST /webhooks/marketplace/:provider` — the ONE address the software's own\n * app registers with a marketplace, for every store linked through it\n * (FUT-5613). The store is found by the merchant id the delivery names, and\n * the delivery must carry a valid signature: unsigned is refused here.\n */\nexport function appWebhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:provider\",\n kind: \"webhook\",\n handle: async (request) => {\n const admitted = await admitApp(config, request);\n return \"status\" in admitted ? admitted : deliverAdmitted(config, admitted);\n },\n };\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 { linkRoutes } from \"./link-routes\";\nimport { appWebhookRoute, 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 ?? (problem.code === \"MERCHANT_TAKEN\" ? (copy.link?.problems.MERCHANT_TAKEN ?? problem.code) : 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 appWebhookRoute(config),\n ...integrationRoutes(config),\n ...linkRoutes(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 { MarketplaceLinkCopy, 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,GAAiB;AACvG,SAAO,EAAE,QAAQ,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE;AAC7C;AAFgB;AAKT,SAAS,MACd,QACA,OACA,MACgE;AAChE,QAAM,SAAS,OAAO,UAAU,SAAS,CAAC,CAAC;AAC3C,MAAI,OAAO,QAAS,QAAO,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;AAC1D,QAAM,WAAW,OAAO,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,IACnD,MAAM,MAAM,KAAK,IAAI,CAAC,YAAa,OAAO,YAAY,WAAW,UAAU,OAAO,OAAO,CAAE;AAAA,IAC3F,MAAM;AAAA,IACN,SAAS,MAAM;AAAA,EACjB,EAAE;AACF,SAAO,EAAE,IAAI,OAAO,UAAU,OAAO,KAAK,KAAK,cAAc,EAAE,SAAS,CAAC,EAAE;AAC7E;AAbgB;AAgBT,SAAS,IAAI,OAA+C;AACjE,SAAO,QAAQ,MAAM,YAAY,IAAI;AACvC;AAFgB;;;AC1ChB,IAAM,OAAO;AAGb,IAAM,SAAoD;AAAA,EACxD,aAAa;AAAA,EACb,qBAAqB;AAAA,EACrB,cAAc;AAAA,EACd,cAAc;AAAA,EACd,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,gBAAgB;AAClB;AAGA,SAAS,OAAO,QAA8B,SAAoC;AAChF,QAAM,QAAQ,OAAO,KAAK;AAC1B,M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;AAAA,EACF,GAPQ;AAQV;AAGO,IAAM,mBAAmB;AAAA,EAC9B,WAAW;AAAA,EACX,YAAY;AAAA,IACV,sBAAsB;AAAA,IACtB,mBAAmB;AAAA,IACnB;AAAA,IACA,eAAe;AAAA,IACf;AAAA,IACA,kBAAkB;AAAA,IAClB;AAAA,IACA,sBAAsB;AAAA,EACxB;AACF;;;ACxOO,SAAS,qBAAqB,QAA8C;AACjF,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,kFAAkF;AAAA,EACpG;AACA,SAAO,EAAE,QAAQ,kBAAkB,MAAM,GAAG,QAAQ,OAAO,OAAO;AACpE;AALgB;","names":["BASE"]}
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/server/contribution.ts
|
|
6
|
+
var MARKETPLACE_PERMISSIONS = {
|
|
7
|
+
source: "@12-apps/marketplace",
|
|
8
|
+
ids: ["marketplace:manage", "marketplace:decide"],
|
|
9
|
+
permissions: {
|
|
10
|
+
"marketplace:manage": { kind: "class" },
|
|
11
|
+
"marketplace:decide": { kind: "class" }
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
var MARKETPLACE_MANAGE = "marketplace:manage";
|
|
15
|
+
var MARKETPLACE_DECIDE = "marketplace:decide";
|
|
16
|
+
|
|
17
|
+
// src/server/mcp.ts
|
|
18
|
+
import { z as z2 } from "zod";
|
|
19
|
+
|
|
20
|
+
// src/server/mcp-link.ts
|
|
21
|
+
import { z } from "zod";
|
|
22
|
+
var provider = z.string().regex(/^[A-Z][A-Z0-9_]*$/u);
|
|
23
|
+
var environment = z.enum(["SANDBOX", "PRODUCTION"]);
|
|
24
|
+
var linkStateQuery = z.strictObject({ provider, environment: environment.optional() });
|
|
25
|
+
var startLinkBody = z.strictObject({ provider, environment: environment.optional() });
|
|
26
|
+
var finishLinkBody = z.strictObject({
|
|
27
|
+
provider,
|
|
28
|
+
authorizationCode: z.string().trim().min(1).max(512),
|
|
29
|
+
enabled: z.boolean().optional()
|
|
30
|
+
});
|
|
31
|
+
var linkMerchantsQuery = z.strictObject({ provider });
|
|
32
|
+
var selectLinkMerchantBody = z.strictObject({ provider, merchantId: z.string().trim().min(1).max(200) });
|
|
33
|
+
var pendingSchema = z.object({
|
|
34
|
+
userCode: z.string(),
|
|
35
|
+
verificationUrl: z.string(),
|
|
36
|
+
verificationUrlComplete: z.string(),
|
|
37
|
+
expiresAt: z.string()
|
|
38
|
+
});
|
|
39
|
+
var merchantSchema = z.object({ id: z.string(), name: z.string().nullable(), corporateName: z.string().nullable() });
|
|
40
|
+
var BASE = "/admin/{tenantSlug}/marketplace/link";
|
|
41
|
+
function marketplaceLinkTools(params, integration) {
|
|
42
|
+
return [
|
|
43
|
+
{
|
|
44
|
+
operationId: "getMarketplaceLink",
|
|
45
|
+
method: "GET",
|
|
46
|
+
path: BASE,
|
|
47
|
+
summary: "Read in one call whether a store can connect a marketplace through the software's own app (no credentials typed), and the portal code still in progress, if any: `userCode`, the portal link that already carries it, and when it expires.",
|
|
48
|
+
tags: ["marketplace"],
|
|
49
|
+
params,
|
|
50
|
+
query: linkStateQuery,
|
|
51
|
+
response: z.object({ data: z.object({ available: z.boolean(), pending: pendingSchema.nullable() }) }),
|
|
52
|
+
annotations: { readOnly: true }
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
operationId: "listMarketplaceLinkMerchants",
|
|
56
|
+
method: "GET",
|
|
57
|
+
path: `${BASE}/merchants`,
|
|
58
|
+
summary: "List the marketplace stores a linked connection's authorization covers, to choose which one this store is.",
|
|
59
|
+
tags: ["marketplace"],
|
|
60
|
+
params,
|
|
61
|
+
query: linkMerchantsQuery,
|
|
62
|
+
response: z.object({ data: z.array(merchantSchema) }),
|
|
63
|
+
annotations: { readOnly: true, openWorld: true }
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
operationId: "startMarketplaceLink",
|
|
67
|
+
method: "POST",
|
|
68
|
+
path: `${BASE}/start`,
|
|
69
|
+
summary: "Start connecting a marketplace through the software's own app in one call: answers the code the person types on the marketplace's portal and the portal link that already carries it (valid ten minutes on iFood). Replaces a code in progress. 409 UNAVAILABLE when the software has no app on that marketplace.",
|
|
70
|
+
tags: ["marketplace"],
|
|
71
|
+
params,
|
|
72
|
+
body: startLinkBody,
|
|
73
|
+
response: z.object({ data: pendingSchema }),
|
|
74
|
+
annotations: { readOnly: false, destructive: false, openWorld: true }
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
operationId: "finishMarketplaceLink",
|
|
78
|
+
method: "POST",
|
|
79
|
+
path: `${BASE}/finish`,
|
|
80
|
+
summary: "Finish connecting, in one call, with the authorization code the marketplace's portal showed the person. Stores the connection as LINKED and selects the marketplace store when the authorization covers only one; `merchants` lists them (null when they could not be listed). 422 CODE_REFUSED for a wrong code (the code in progress stays, paste again); 409 LINK_EXPIRED past its ten minutes.",
|
|
81
|
+
tags: ["marketplace"],
|
|
82
|
+
params,
|
|
83
|
+
body: finishLinkBody,
|
|
84
|
+
response: z.object({ data: z.object({ integration, merchants: z.array(merchantSchema).nullable() }) }),
|
|
85
|
+
annotations: { readOnly: false, destructive: false, openWorld: true }
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
operationId: "selectMarketplaceLinkMerchant",
|
|
89
|
+
method: "PUT",
|
|
90
|
+
path: `${BASE}/merchant`,
|
|
91
|
+
summary: "Choose in one call which marketplace store a linked connection is, among those its authorization covers. 422 UNKNOWN_MERCHANT for one it does not cover; 409 MERCHANT_TAKEN when another store's connection holds it.",
|
|
92
|
+
tags: ["marketplace"],
|
|
93
|
+
params,
|
|
94
|
+
body: selectLinkMerchantBody,
|
|
95
|
+
response: z.object({ data: z.object({ integration }) }),
|
|
96
|
+
annotations: { readOnly: false, destructive: false, openWorld: true }
|
|
97
|
+
}
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
__name(marketplaceLinkTools, "marketplaceLinkTools");
|
|
101
|
+
|
|
102
|
+
// src/server/mcp.ts
|
|
103
|
+
var providerSchema = z2.string().regex(/^[A-Z][A-Z0-9_]*$/u);
|
|
104
|
+
var environmentSchema = z2.enum(["SANDBOX", "PRODUCTION"]);
|
|
105
|
+
var booleanText = z2.enum(["true", "false"]);
|
|
106
|
+
var idsText = z2.string().transform((text) => text.split(",").map((id) => id.trim()).filter((id) => id !== "")).pipe(z2.array(z2.string().min(1)).min(1).max(100));
|
|
107
|
+
function noDuplicates(list, field, keyOf) {
|
|
108
|
+
return (rows, ctx) => {
|
|
109
|
+
const seen = /* @__PURE__ */ new Set();
|
|
110
|
+
rows.forEach((row, index) => {
|
|
111
|
+
const key = keyOf(row);
|
|
112
|
+
if (seen.has(key)) {
|
|
113
|
+
ctx.addIssue({ code: "custom", path: [index, field], message: `${field} repeats an earlier row of ${list}` });
|
|
114
|
+
}
|
|
115
|
+
seen.add(key);
|
|
116
|
+
});
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
__name(noDuplicates, "noDuplicates");
|
|
120
|
+
var marketplaceParams = z2.strictObject({
|
|
121
|
+
tenantSlug: z2.string().min(1)
|
|
122
|
+
});
|
|
123
|
+
var listMarketplaceIntegrationsQuery = z2.strictObject({
|
|
124
|
+
ids: idsText.optional(),
|
|
125
|
+
includeArchived: booleanText.optional()
|
|
126
|
+
});
|
|
127
|
+
var credentialsInput = z2.strictObject({
|
|
128
|
+
clientId: z2.string().trim().min(1),
|
|
129
|
+
clientSecret: z2.string().trim().min(1),
|
|
130
|
+
webhookSecret: z2.string().trim().min(1).nullable().optional()
|
|
131
|
+
});
|
|
132
|
+
var integrationUpsertInput = z2.strictObject({
|
|
133
|
+
operation: z2.literal("upsert").optional(),
|
|
134
|
+
provider: providerSchema,
|
|
135
|
+
enabled: z2.boolean().optional(),
|
|
136
|
+
environment: environmentSchema.optional(),
|
|
137
|
+
externalMerchantId: z2.string().trim().min(1).nullable().optional(),
|
|
138
|
+
autoAccept: z2.boolean().optional(),
|
|
139
|
+
followStatus: z2.boolean().optional(),
|
|
140
|
+
// Below a minute nothing human can answer in time; above an hour the
|
|
141
|
+
// deadline has stopped describing anything a marketplace would wait for.
|
|
142
|
+
ackSlaSeconds: z2.number().int().min(60).max(3600).optional(),
|
|
143
|
+
credentials: credentialsInput.optional()
|
|
144
|
+
});
|
|
145
|
+
var integrationArchiveInput = z2.strictObject({
|
|
146
|
+
operation: z2.enum(["archive", "unarchive"]),
|
|
147
|
+
provider: providerSchema,
|
|
148
|
+
reason: z2.string().trim().min(1).max(500).nullable().optional()
|
|
149
|
+
});
|
|
150
|
+
var upsertMarketplaceIntegrationsBody = z2.strictObject({
|
|
151
|
+
validateOnly: z2.boolean().optional(),
|
|
152
|
+
integrations: z2.array(z2.union([integrationArchiveInput, integrationUpsertInput])).min(1).max(20).superRefine(noDuplicates("integrations", "provider", (row) => row.provider))
|
|
153
|
+
});
|
|
154
|
+
var listMarketplaceMenuLinksQuery = z2.strictObject({
|
|
155
|
+
provider: providerSchema.optional(),
|
|
156
|
+
// A query string is text: "false" must mean false.
|
|
157
|
+
unmapped: booleanText.optional(),
|
|
158
|
+
ids: idsText.optional()
|
|
159
|
+
});
|
|
160
|
+
var menuLinkInput = z2.strictObject({
|
|
161
|
+
provider: providerSchema,
|
|
162
|
+
externalSku: z2.string().trim().min(1),
|
|
163
|
+
externalName: z2.string().trim().min(1).optional(),
|
|
164
|
+
menuItemId: z2.string().min(1).nullable(),
|
|
165
|
+
variationId: z2.string().min(1).nullable().optional()
|
|
166
|
+
});
|
|
167
|
+
var upsertMarketplaceMenuLinksBody = z2.strictObject({
|
|
168
|
+
validateOnly: z2.boolean().optional(),
|
|
169
|
+
links: z2.array(menuLinkInput).min(1).max(200).superRefine(noDuplicates("links", "externalSku", (row) => `${row.provider}\0${row.externalSku}`))
|
|
170
|
+
});
|
|
171
|
+
var listMarketplaceAcceptancesQuery = z2.strictObject({
|
|
172
|
+
ids: idsText.optional()
|
|
173
|
+
});
|
|
174
|
+
var admissionInput = z2.strictObject({
|
|
175
|
+
admitStockPastZero: z2.boolean().optional()
|
|
176
|
+
});
|
|
177
|
+
var decisionInput = z2.discriminatedUnion("decision", [
|
|
178
|
+
z2.strictObject({
|
|
179
|
+
orderId: z2.string().min(1),
|
|
180
|
+
decision: z2.literal("ACCEPT"),
|
|
181
|
+
admission: admissionInput.optional(),
|
|
182
|
+
preparationMinutes: z2.number().int().min(1).max(240).optional()
|
|
183
|
+
}),
|
|
184
|
+
z2.strictObject({
|
|
185
|
+
orderId: z2.string().min(1),
|
|
186
|
+
decision: z2.literal("REJECT"),
|
|
187
|
+
reasonCode: z2.string().trim().min(1).optional(),
|
|
188
|
+
offendingSkus: z2.array(z2.string().trim().min(1)).min(1).max(50).optional()
|
|
189
|
+
})
|
|
190
|
+
]);
|
|
191
|
+
var decideMarketplaceOrdersBody = z2.strictObject({
|
|
192
|
+
validateOnly: z2.boolean().optional(),
|
|
193
|
+
decisions: z2.array(decisionInput).min(1).max(50).superRefine(noDuplicates("decisions", "orderId", (row) => row.orderId))
|
|
194
|
+
});
|
|
195
|
+
var reasonSchema = z2.object({
|
|
196
|
+
code: z2.string(),
|
|
197
|
+
label: z2.string(),
|
|
198
|
+
itemUnavailable: z2.boolean(),
|
|
199
|
+
needsItems: z2.boolean()
|
|
200
|
+
});
|
|
201
|
+
var capabilitiesSchema = z2.object({
|
|
202
|
+
apiConfirm: z2.boolean(),
|
|
203
|
+
apiCancel: z2.boolean(),
|
|
204
|
+
cancelAfterAccept: z2.boolean(),
|
|
205
|
+
asyncCancellationOutcome: z2.boolean(),
|
|
206
|
+
perOrderAppLink: z2.boolean(),
|
|
207
|
+
confirmTakesPreparationTime: z2.boolean()
|
|
208
|
+
});
|
|
209
|
+
var integrationSchema = z2.object({
|
|
210
|
+
provider: z2.string(),
|
|
211
|
+
enabled: z2.boolean(),
|
|
212
|
+
environment: environmentSchema,
|
|
213
|
+
status: z2.enum(["UNVERIFIED", "VERIFIED", "FAILED"]),
|
|
214
|
+
externalMerchantId: z2.string().nullable(),
|
|
215
|
+
autoAccept: z2.boolean(),
|
|
216
|
+
followStatus: z2.boolean(),
|
|
217
|
+
ackSlaSeconds: z2.number().int(),
|
|
218
|
+
connected: z2.boolean(),
|
|
219
|
+
lastEventAt: z2.string().nullable(),
|
|
220
|
+
lastVerifiedAt: z2.string().nullable(),
|
|
221
|
+
archivedAt: z2.string().nullable(),
|
|
222
|
+
authMode: z2.enum(["CREDENTIALS", "LINKED"]),
|
|
223
|
+
capabilities: capabilitiesSchema.nullable(),
|
|
224
|
+
reasons: z2.array(reasonSchema)
|
|
225
|
+
});
|
|
226
|
+
var menuLinkSchema = z2.object({
|
|
227
|
+
id: z2.string(),
|
|
228
|
+
provider: z2.string(),
|
|
229
|
+
externalSku: z2.string(),
|
|
230
|
+
externalName: z2.string(),
|
|
231
|
+
menuItemId: z2.string().nullable(),
|
|
232
|
+
variationId: z2.string().nullable(),
|
|
233
|
+
lastSeenAt: z2.string()
|
|
234
|
+
});
|
|
235
|
+
var pendingAcceptanceSchema = z2.object({
|
|
236
|
+
id: z2.string(),
|
|
237
|
+
orderId: z2.string(),
|
|
238
|
+
provider: z2.string(),
|
|
239
|
+
externalOrderId: z2.string(),
|
|
240
|
+
externalDisplayId: z2.string().nullable(),
|
|
241
|
+
totalCents: z2.number().int(),
|
|
242
|
+
buyerName: z2.string().nullable(),
|
|
243
|
+
acknowledgeBy: z2.string().nullable(),
|
|
244
|
+
externalDueAt: z2.string().nullable(),
|
|
245
|
+
commissionCents: z2.number().int().nullable(),
|
|
246
|
+
unmappedLines: z2.number().int(),
|
|
247
|
+
createdAt: z2.string().nullable()
|
|
248
|
+
});
|
|
249
|
+
var decidedSchema = z2.object({
|
|
250
|
+
orderId: z2.string(),
|
|
251
|
+
status: z2.enum(["ACCEPTED", "REJECTED"]),
|
|
252
|
+
cancellation: z2.enum(["PENDING", "REQUESTED", "CONFIRMED", "FAILED"]).nullable(),
|
|
253
|
+
reasonCode: z2.string().nullable(),
|
|
254
|
+
offendingSkus: z2.array(z2.string())
|
|
255
|
+
});
|
|
256
|
+
var BASE2 = "/admin/{tenantSlug}/marketplace";
|
|
257
|
+
var MARKETPLACE_MCP_TOOLS = [
|
|
258
|
+
{
|
|
259
|
+
operationId: "listMarketplaceIntegrations",
|
|
260
|
+
method: "GET",
|
|
261
|
+
path: BASE2,
|
|
262
|
+
summary: "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.",
|
|
263
|
+
tags: ["marketplace"],
|
|
264
|
+
params: marketplaceParams,
|
|
265
|
+
query: listMarketplaceIntegrationsQuery,
|
|
266
|
+
response: z2.object({ data: z2.array(integrationSchema) }),
|
|
267
|
+
annotations: { readOnly: true }
|
|
268
|
+
},
|
|
269
|
+
{
|
|
270
|
+
operationId: "upsertMarketplaceIntegrations",
|
|
271
|
+
method: "PUT",
|
|
272
|
+
path: BASE2,
|
|
273
|
+
summary: "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`). An `externalMerchantId` another store's live connection holds is refused `MERCHANT_TAKEN` at that field (an unarchive reviving one, at `provider`). Any problem writes nothing and every problem comes back with its path. `validateOnly: true` checks without writing.",
|
|
274
|
+
tags: ["marketplace"],
|
|
275
|
+
params: marketplaceParams,
|
|
276
|
+
body: upsertMarketplaceIntegrationsBody,
|
|
277
|
+
response: z2.object({ data: z2.object({ validateOnly: z2.boolean(), integrations: z2.array(integrationSchema) }) }),
|
|
278
|
+
annotations: { readOnly: false, destructive: false }
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
operationId: "listMarketplaceMenuLinks",
|
|
282
|
+
method: "GET",
|
|
283
|
+
path: `${BASE2}/menu-links`,
|
|
284
|
+
summary: "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.",
|
|
285
|
+
tags: ["marketplace"],
|
|
286
|
+
params: marketplaceParams,
|
|
287
|
+
query: listMarketplaceMenuLinksQuery,
|
|
288
|
+
response: z2.object({ data: z2.array(menuLinkSchema) }),
|
|
289
|
+
annotations: { readOnly: true }
|
|
290
|
+
},
|
|
291
|
+
{
|
|
292
|
+
operationId: "upsertMarketplaceMenuLinks",
|
|
293
|
+
method: "PUT",
|
|
294
|
+
path: `${BASE2}/menu-links`,
|
|
295
|
+
summary: "Map one or many external marketplace SKUs to the store's catalog ids, or unmap them with `menuItemId: null`; `variationId` maps a SKU to one variation of its catalog id instead of the item alone, 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 variation that is not one of its catalog id's, a repeated SKU) writes nothing; `validateOnly: true` checks without writing.",
|
|
296
|
+
tags: ["marketplace"],
|
|
297
|
+
params: marketplaceParams,
|
|
298
|
+
body: upsertMarketplaceMenuLinksBody,
|
|
299
|
+
response: z2.object({ data: z2.object({ validateOnly: z2.boolean(), links: z2.array(menuLinkSchema) }) }),
|
|
300
|
+
annotations: { readOnly: false, destructive: false }
|
|
301
|
+
},
|
|
302
|
+
{
|
|
303
|
+
operationId: "listMarketplaceAcceptances",
|
|
304
|
+
method: "GET",
|
|
305
|
+
path: `${BASE2}/acceptances`,
|
|
306
|
+
summary: "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.",
|
|
307
|
+
tags: ["marketplace"],
|
|
308
|
+
params: marketplaceParams,
|
|
309
|
+
query: listMarketplaceAcceptancesQuery,
|
|
310
|
+
response: z2.object({ data: z2.array(pendingAcceptanceSchema) }),
|
|
311
|
+
annotations: { readOnly: true }
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
operationId: "decideMarketplaceOrders",
|
|
315
|
+
method: "POST",
|
|
316
|
+
path: `${BASE2}/acceptances`,
|
|
317
|
+
summary: "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.",
|
|
318
|
+
tags: ["marketplace"],
|
|
319
|
+
params: marketplaceParams,
|
|
320
|
+
body: decideMarketplaceOrdersBody,
|
|
321
|
+
response: z2.object({ data: z2.object({ validateOnly: z2.boolean(), decisions: z2.array(decidedSchema) }) }),
|
|
322
|
+
annotations: { readOnly: false, destructive: true, openWorld: true }
|
|
323
|
+
},
|
|
324
|
+
...marketplaceLinkTools(marketplaceParams, integrationSchema)
|
|
325
|
+
];
|
|
326
|
+
|
|
327
|
+
export {
|
|
328
|
+
MARKETPLACE_PERMISSIONS,
|
|
329
|
+
MARKETPLACE_MANAGE,
|
|
330
|
+
MARKETPLACE_DECIDE,
|
|
331
|
+
linkStateQuery,
|
|
332
|
+
startLinkBody,
|
|
333
|
+
finishLinkBody,
|
|
334
|
+
linkMerchantsQuery,
|
|
335
|
+
selectLinkMerchantBody,
|
|
336
|
+
marketplaceParams,
|
|
337
|
+
listMarketplaceIntegrationsQuery,
|
|
338
|
+
upsertMarketplaceIntegrationsBody,
|
|
339
|
+
listMarketplaceMenuLinksQuery,
|
|
340
|
+
upsertMarketplaceMenuLinksBody,
|
|
341
|
+
listMarketplaceAcceptancesQuery,
|
|
342
|
+
decideMarketplaceOrdersBody,
|
|
343
|
+
MARKETPLACE_MCP_TOOLS
|
|
344
|
+
};
|
|
345
|
+
//# sourceMappingURL=chunk-SGOTN5PX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/contribution.ts","../src/server/mcp.ts","../src/server/mcp-link.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\nimport { marketplaceLinkTools } from \"./mcp-link\";\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 followStatus: 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/**\n * Map one external SKU to a catalog id, or unmap it with `menuItemId: null`.\n * `variationId` narrows it to one variation of that id; absent or null maps the item alone.\n */\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 variationId: z.string().min(1).nullable().optional(),\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 followStatus: 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 authMode: z.enum([\"CREDENTIALS\", \"LINKED\"]),\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 variationId: 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 marketplace tools: a read and a bulk write per entity, and the five linking tools (FUT-5613). */\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`). An `externalMerchantId` another store's live connection holds is refused `MERCHANT_TAKEN` at that field (an unarchive reviving one, at `provider`). 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`; `variationId` maps a SKU to one variation of its catalog id instead of the item alone, 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 variation that is not one of its catalog id'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 ...marketplaceLinkTools(marketplaceParams, integrationSchema),\n] as const satisfies readonly WireMcpTool<z.ZodType>[];\n","import { z } from \"zod\";\n\nimport type { WireMcpTool } from \"@12-apps/wiring\";\n\n/**\n * The linking tools (FUT-5613), one per linking route, authored once and\n * reused as the routes' validators. Every input is STRICT. No answer carries a\n * token, a verifier or the app's credentials.\n */\n\nconst provider = z.string().regex(/^[A-Z][A-Z0-9_]*$/u);\nconst environment = z.enum([\"SANDBOX\", \"PRODUCTION\"]);\n\n/** Whether linking is available, and the code in progress. */\nexport const linkStateQuery = z.strictObject({ provider, environment: environment.optional() });\n/** Start a linking: a new portal code. */\nexport const startLinkBody = z.strictObject({ provider, environment: environment.optional() });\n/** Finish it with the authorization code the person pasted. */\nexport const finishLinkBody = z.strictObject({\n provider,\n authorizationCode: z.string().trim().min(1).max(512),\n enabled: z.boolean().optional(),\n});\n/** The marketplace stores a linked connection's grant covers. */\nexport const linkMerchantsQuery = z.strictObject({ provider });\n/** Which of them this store is. */\nexport const selectLinkMerchantBody = z.strictObject({ provider, merchantId: z.string().trim().min(1).max(200) });\n\nconst pendingSchema = z.object({\n userCode: z.string(),\n verificationUrl: z.string(),\n verificationUrlComplete: z.string(),\n expiresAt: z.string(),\n});\n\nconst merchantSchema = z.object({ id: z.string(), name: z.string().nullable(), corporateName: z.string().nullable() });\n\nconst BASE = \"/admin/{tenantSlug}/marketplace/link\";\n\n/** The five linking tools, over the connection schema the connection tools answer. */\nexport function marketplaceLinkTools<P extends z.ZodType, I extends z.ZodType>(params: P, integration: I) {\n return [\n {\n operationId: \"getMarketplaceLink\",\n method: \"GET\",\n path: BASE,\n summary:\n \"Read in one call whether a store can connect a marketplace through the software's own app (no credentials typed), and the portal code still in progress, if any: `userCode`, the portal link that already carries it, and when it expires.\",\n tags: [\"marketplace\"],\n params,\n query: linkStateQuery,\n response: z.object({ data: z.object({ available: z.boolean(), pending: pendingSchema.nullable() }) }),\n annotations: { readOnly: true },\n },\n {\n operationId: \"listMarketplaceLinkMerchants\",\n method: \"GET\",\n path: `${BASE}/merchants`,\n summary: \"List the marketplace stores a linked connection's authorization covers, to choose which one this store is.\",\n tags: [\"marketplace\"],\n params,\n query: linkMerchantsQuery,\n response: z.object({ data: z.array(merchantSchema) }),\n annotations: { readOnly: true, openWorld: true },\n },\n {\n operationId: \"startMarketplaceLink\",\n method: \"POST\",\n path: `${BASE}/start`,\n summary:\n \"Start connecting a marketplace through the software's own app in one call: answers the code the person types on the marketplace's portal and the portal link that already carries it (valid ten minutes on iFood). Replaces a code in progress. 409 UNAVAILABLE when the software has no app on that marketplace.\",\n tags: [\"marketplace\"],\n params,\n body: startLinkBody,\n response: z.object({ data: pendingSchema }),\n annotations: { readOnly: false, destructive: false, openWorld: true },\n },\n {\n operationId: \"finishMarketplaceLink\",\n method: \"POST\",\n path: `${BASE}/finish`,\n summary:\n \"Finish connecting, in one call, with the authorization code the marketplace's portal showed the person. Stores the connection as LINKED and selects the marketplace store when the authorization covers only one; `merchants` lists them (null when they could not be listed). 422 CODE_REFUSED for a wrong code (the code in progress stays, paste again); 409 LINK_EXPIRED past its ten minutes.\",\n tags: [\"marketplace\"],\n params,\n body: finishLinkBody,\n response: z.object({ data: z.object({ integration, merchants: z.array(merchantSchema).nullable() }) }),\n annotations: { readOnly: false, destructive: false, openWorld: true },\n },\n {\n operationId: \"selectMarketplaceLinkMerchant\",\n method: \"PUT\",\n path: `${BASE}/merchant`,\n summary:\n \"Choose in one call which marketplace store a linked connection is, among those its authorization covers. 422 UNKNOWN_MERCHANT for one it does not cover; 409 MERCHANT_TAKEN when another store's connection holds it.\",\n tags: [\"marketplace\"],\n params,\n body: selectLinkMerchantBody,\n response: z.object({ data: z.object({ integration }) }),\n annotations: { readOnly: false, destructive: false, openWorld: true },\n },\n ] as const satisfies readonly WireMcpTool<z.ZodType>[];\n}\n"],"mappings":";;;;;AAqBO,IAAM,0BAA0B;AAAA,EACrC,QAAQ;AAAA,EACR,KAAK,CAAC,sBAAsB,oBAAoB;AAAA,EAChD,aAAa;AAAA,IACX,sBAAsB,EAAE,MAAM,QAAQ;AAAA,IACtC,sBAAsB,EAAE,MAAM,QAAQ;AAAA,EACxC;AACF;AAGO,IAAM,qBAAqB;AAE3B,IAAM,qBAAqB;;;ACjClC,SAAS,KAAAA,UAAS;;;ACAlB,SAAS,SAAS;AAUlB,IAAM,WAAW,EAAE,OAAO,EAAE,MAAM,oBAAoB;AACtD,IAAM,cAAc,EAAE,KAAK,CAAC,WAAW,YAAY,CAAC;AAG7C,IAAM,iBAAiB,EAAE,aAAa,EAAE,UAAU,aAAa,YAA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IACpG,aAAa,EAAE,UAAU,OAAO,aAAa,MAAM;AAAA,EACrD;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,MAAM,GAAGC,KAAI;AAAA,IACb,SACE;AAAA,IACF,MAAM,CAAC,aAAa;AAAA,IACpB,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,UAAUD,GAAE,OAAO,EAAE,MAAMA,GAAE,MAAM,uBAAuB,EAAE,CAAC;AAAA,IAC7D,aAAa,EAAE,UAAU,KAAK;AAAA,EAChC;AAAA,EACA;AAAA,IACE,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,MAAM,GAAGC,KAAI;AAAA,IACb,SACE;AAAA,IACF,MAAM,CAAC,aAAa;AAAA,IACpB,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,UAAUD,GAAE,OAAO,EAAE,MAAMA,GAAE,OAAO,EAAE,cAAcA,GAAE,QAAQ,GAAG,WAAWA,GAAE,MAAM,aAAa,EAAE,CAAC,EAAE,CAAC;AAAA,IACvG,aAAa,EAAE,UAAU,OAAO,aAAa,MAAM,WAAW,KAAK;AAAA,EACrE;AAAA,EACA,GAAG,qBAAqB,mBAAmB,iBAAiB;AAC9D;","names":["z","z","BASE"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n}\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order (iFood) leaves it out.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAkRA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
|