@12-apps/marketplace 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/ADOPTING.md +258 -3
  2. package/README.md +27 -2
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +3 -3
  5. package/dist/{adapter-CQ4QiZPi.d.ts → adapter-CjVdMhZ2.d.ts} +177 -4
  6. package/dist/{chunk-CEWTV2TC.js → chunk-B4DYPQFE.js} +657 -251
  7. package/dist/chunk-B4DYPQFE.js.map +1 -0
  8. package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
  9. package/dist/chunk-BTKVZAJI.js.map +1 -0
  10. package/dist/{chunk-BD7DS3XM.js → chunk-E4XJXHUK.js} +20 -1
  11. package/dist/chunk-E4XJXHUK.js.map +1 -0
  12. package/dist/{chunk-W57TITU4.js → chunk-FQI56NGC.js} +53 -6
  13. package/dist/chunk-FQI56NGC.js.map +1 -0
  14. package/dist/chunk-H2VQRD3B.js +16 -0
  15. package/dist/chunk-H2VQRD3B.js.map +1 -0
  16. package/dist/{chunk-NFJQQWG4.js → chunk-TRUK5ZBE.js} +12 -4
  17. package/dist/chunk-TRUK5ZBE.js.map +1 -0
  18. package/dist/{client-CCSnylou.d.ts → client-DgzCkl8u.d.ts} +1 -1
  19. package/dist/{engine-1KlJ_8jK.d.ts → engine-BSLdhAGC.d.ts} +134 -3
  20. package/dist/hono/index.d.ts +2 -2
  21. package/dist/hono/index.js +3 -2
  22. package/dist/hono/index.js.map +1 -1
  23. package/dist/ifood/index.d.ts +13 -3
  24. package/dist/ifood/index.js +219 -29
  25. package/dist/ifood/index.js.map +1 -1
  26. package/dist/index.d.ts +29 -5
  27. package/dist/index.js +59 -7
  28. package/dist/index.js.map +1 -1
  29. package/dist/keeta/index.d.ts +2 -2
  30. package/dist/keeta/index.js +3 -3
  31. package/dist/manifest/server.d.ts +4 -2
  32. package/dist/manifest/server.js +3 -2
  33. package/dist/manifest/server.js.map +1 -1
  34. package/dist/rappi/index.d.ts +1 -1
  35. package/dist/rappi/index.js +2 -2
  36. package/dist/server/index.d.ts +14 -5
  37. package/dist/server/index.js +3 -2
  38. package/package.json +1 -1
  39. package/prisma/marketplace.prisma +17 -3
  40. package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
  41. package/src/core/acceptance.ts +12 -6
  42. package/src/core/acknowledge.ts +189 -0
  43. package/src/core/adapter.ts +74 -1
  44. package/src/core/cancellation.ts +10 -6
  45. package/src/core/conformity.ts +63 -0
  46. package/src/core/engine.ts +3 -2
  47. package/src/core/ingest.ts +7 -0
  48. package/src/core/link-store.ts +2 -4
  49. package/src/core/marketplace-confirmed.ts +229 -0
  50. package/src/core/order-reasons.ts +119 -0
  51. package/src/core/order-types.ts +8 -0
  52. package/src/core/outbound.ts +5 -1
  53. package/src/core/payload-read.ts +24 -0
  54. package/src/core/pipeline.ts +27 -1
  55. package/src/core/ports.ts +2 -0
  56. package/src/core/registry.ts +28 -2
  57. package/src/core/state.ts +10 -0
  58. package/src/core/status-job.ts +86 -3
  59. package/src/core/types.ts +117 -2
  60. package/src/ifood/index.ts +27 -4
  61. package/src/ifood/normalize.ts +38 -5
  62. package/src/ifood/order-details.ts +120 -0
  63. package/src/ifood/outbound.ts +131 -27
  64. package/src/index.ts +24 -0
  65. package/src/open-delivery/normalize.ts +9 -0
  66. package/src/server/jobs.ts +57 -4
  67. package/src/server/webhook.ts +27 -4
  68. package/dist/chunk-4J2KJ3ZW.js.map +0 -1
  69. package/dist/chunk-BD7DS3XM.js.map +0 -1
  70. package/dist/chunk-CEWTV2TC.js.map +0 -1
  71. package/dist/chunk-NFJQQWG4.js.map +0 -1
  72. package/dist/chunk-W57TITU4.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ifood/copy.ts","../../src/ifood/outbound.ts","../../src/ifood/catalogue.ts","../../src/ifood/catalogue-snapshot.ts","../../src/ifood/catalogue-read.ts","../../src/ifood/courier.ts","../../src/ifood/normalize.ts","../../src/ifood/fetch-order.ts","../../src/ifood/linking.ts","../../src/ifood/pause.ts","../../src/ifood/index.ts"],"sourcesContent":["/**\n * The words the iFood adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * iFood's documented cancellation reason codes. UNVERIFIED: read from the\n * merchant portal's search snippets (2026-11-11), not from a page we could\n * read whole; the homologation run against iFood's sandbox corrects them here.\n */\nexport const IFOOD_REASON_CODES = [\n \"501\",\n \"502\",\n \"503\",\n \"504\",\n \"505\",\n \"506\",\n \"507\",\n \"508\",\n \"509\",\n \"511\",\n \"512\",\n \"513\",\n] as const;\n\nexport type IfoodReasonCode = (typeof IFOOD_REASON_CODES)[number];\n\nexport interface IfoodAdapterCopy {\n /** One label per reason code. Sent to iFood as the reason text when the store wrote none. */\n reasonLabels: Readonly<Record<IfoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import {\n answered,\n outboundResultOf,\n tokenGrantResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type OutboundOrderRef,\n type OutboundResult,\n type StatusFacts,\n} from \"../core/adapter\";\n\n/**\n * The iFood adapter's OUTBOUND half: auth, URLs and payload shapes. Everything\n * here is iFood's wire format and nothing else — the job that calls it, its\n * retries and what a failure shows are the engine's (`../core/outbound.ts`).\n *\n * UNVERIFIED. iFood's developer portal refused our reader, so every URL, body\n * field below (and the reason codes in `./copy.ts`) comes from the portal's search snippets\n * (2026-11-11), not from a page we could read whole. They are in THIS file and\n * nowhere else so that the homologation run against iFood's sandbox, once\n * homologation credentials exist, corrects one file. Tests never reach\n * iFood: the HTTP client is the host's port, answered by a fake.\n */\n\n/** iFood's merchant API. Sandbox and production share the host; the credentials differ. */\nexport const IFOOD_API = \"https://merchant-api.ifood.com.br\";\nconst TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;\nconst orderUrl = (externalOrderId: string, action: string): string =>\n `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;\n\n/**\n * iFood's order-manager portal. No per-order deep link was found in the\n * snippets, so the app link opens the portal, where the order is on the\n * first screen while it is live.\n */\nexport const IFOOD_PORTAL_URL = \"https://portal.ifood.com.br/\";\n\n/** A token is renewed this long before iFood says it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n\n/**\n * The token cache key: per environment and merchant app, or, for a store\n * linked through the software's app (FUT-5613), the store's own grant key, so\n * deleting it after a 401 forgets that store's token and nobody else's.\n */\nexport const ifoodTokenKey = (ctx: AdapterCallContext): string =>\n ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** iFood's OAuth answer, read defensively: a missing field is \"no token\". */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { accessToken?: unknown; expiresIn?: unknown };\n if (typeof parsed.accessToken !== \"string\" || parsed.accessToken === \"\") return null;\n const expires = typeof parsed.expiresIn === \"number\" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;\n return { token: parsed.accessToken, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token for this merchant app, from the per-process cache or a fresh\n * client-credentials grant (or, linked, the store's grant). Keyed by the app's client id, so two stores with\n * two apps never share one. The token lives in memory only.\n */\nexport async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {\n // A linked store: its refresh token buys the token, never a client-credentials grant.\n if (ctx.grant) return ctx.grant.accessToken();\n const key = ifoodTokenKey(ctx);\n const cached = ctx.tokens.get(key);\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: TOKEN_URL,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grantType: \"client_credentials\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) return tokenGrantResultOf(response);\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"iFood answered the token grant without a token\" };\n ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated POST to an order's resource. */\nfunction postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: orderUrl(externalOrderId, action),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status === 401) ctx.tokens.delete(ifoodTokenKey(ctx));\n return response.status === 401 ? { kind: \"retry\", reason: \"iFood refused the token\" } : outboundResultOf(response);\n });\n}\n\n/** Tell iFood the store accepted the order. No body: the URL names the order. */\nexport function ifoodConfirm(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"confirm\");\n}\n\n/** Ask iFood to cancel the order with one of its reason codes. */\nexport function ifoodRequestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"requestCancellation\", {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancellationCode: input.reason.code,\n });\n}\n\n/**\n * What iFood is told, per step (FUT-4653). ESTIMATED, every row: iFood's\n * developer portal answered 403 behind Cloudflare to our reader\n * (https://developer.ifood.com.br, 2026-11-25), so the endpoint names below are\n * the Merchant API's commonly documented ones (`order/v1.0`), not read off a\n * page.\n *\n * - READY: `POST /orders/{id}/readyToPickup`, for a take-out, and ESTIMATED\n * whether iFood takes it for its own fleet; not for a bag the merchant\n * delivers, which is dispatched, not made ready for pickup.\n * - DISPATCHED: `POST /orders/{id}/dispatch`, only for `deliveredBy: MERCHANT`.\n * - HANDED_OVER: none. iFood has no conclude endpoint for a merchant;\n * CONCLUDED is iFood's own event.\n */\nconst STATUS_ACTION: Readonly<Record<string, (facts: StatusFacts) => string | null>> = {\n READY: (facts) => (facts.deliveredBy === \"MERCHANT\" ? null : \"readyToPickup\"),\n DISPATCHED: (facts) => (facts.deliveredBy === \"MERCHANT\" ? \"dispatch\" : null),\n};\n\n/** Whether iFood takes this step for this kind of order: answered offline. */\nexport function ifoodStatusSupported(facts: StatusFacts): boolean {\n return STATUS_ACTION[facts.step]?.(facts) != null;\n}\n\n/** Tell iFood a step happened. `unsupported` when it has no endpoint for it. */\nexport async function ifoodInformStatus(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n): Promise<OutboundResult | { kind: \"unsupported\" }> {\n const action = STATUS_ACTION[facts.step]?.(facts) ?? null;\n return action === null ? { kind: \"unsupported\" } : postOrder(ctx, order.externalOrderId, action);\n}\n","import {\n answered,\n outboundResultOf,\n type MarketplaceHttpResponse,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type {\n CatalogueCallContext,\n CatalogueImage,\n CatalogueItemOut,\n CatalogueItemRef,\n CataloguePublishResult,\n CatalogueStoredImage,\n CatalogueWarningCode,\n PushCatalogue,\n} from \"../core/catalogue-port\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * The iFood adapter's CATALOGUE half: iFood's Catalog API v2.0, push (FUT-4768).\n *\n * Read 2026-11-13 from iFood's developer portal (the Catalog module's\n * Introduction, Fundamentals, Endpoints and Errors pages, and the rate-limit\n * page); the package README's \"Catalogue publishing\" table marks each fact\n * CONFIRMED with its URL or ESTIMATED. What is ESTIMATED here is said beside\n * it, and lives in this file only, so the homologation run corrects one file.\n *\n * One publish is, in order:\n * 1. the category, by name: `GET /categories`, else `POST /categories`\n * (`template: \"DEFAULT\"`);\n * 2. the photo, when the item has one: the `imagePath` iFood already holds\n * for the same photo URL, else `POST /image/upload` with a base64 data URL\n * of the bytes the host's loader reads, which answers `imagePath`;\n * 3. the item: `PUT /items` with `item`, `products`, `optionGroups`,\n * `options` — idempotent, it replaces the whole item, and the item appears\n * at once (synchronous).\n *\n * iFood wants item and product ids the software generates, UUID v4 (any other\n * shape answers 404), so they are derived from the engine's publication\n * reference: a retried publish names the same item. The item's `externalCode`\n * is the host's product id (unique per merchant).\n *\n * A withdraw pauses the item, `PATCH /items/status` with `UNAVAILABLE`: the\n * Endpoints page lists no item delete, and a paused item is not shown in the\n * app (ESTIMATED that this is what \"off\" should mean; a re-publish puts it\n * back AVAILABLE with the same id).\n */\n\nconst catalogUrl = (merchantId: string, path: string): string =>\n `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;\n\n/** The item's and its product's ids, stable per publication. */\nexport const ifoodItemId = (ref: string): string => stableUuid(`${ref}:item`);\nexport const ifoodProductId = (ref: string): string => stableUuid(`${ref}:product`);\n\ntype Failure = Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** iFood's price object: a decimal of the currency's major unit. */\nconst priceOf = (cents: number): { value: number } => ({ value: Math.round(cents) / 100 });\n\n/** One authenticated call to the catalogue: the raw answer, or the failure that ends it. */\nasync function call(\n ctx: CatalogueCallContext,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\",\n path: string,\n body?: unknown,\n): Promise<MarketplaceHttpResponse | Failure> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : auth;\n const response = await ctx.http({\n method,\n url: catalogUrl(ctx.externalMerchantId, path),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n return { kind: \"retry\", reason: \"iFood refused the token\" };\n}\n\n/** A non-2xx answer as the failure it is (never `accepted`). */\nfunction failureOf(response: MarketplaceHttpResponse): Failure {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected answer\" } : result;\n}\n\nconst ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;\n\nfunction parse(body: string): unknown {\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return null;\n }\n}\n\n/** The id of the category named `name`, from a category list. ESTIMATED: the list answers an array of `{ id, name }`. */\nfunction categoryIdIn(body: string, name: string): string | null {\n const parsed = parse(body);\n if (!Array.isArray(parsed)) return null;\n const wanted = name.trim().toLowerCase();\n const found = parsed.find(\n (entry: unknown) =>\n typeof entry === \"object\" && entry !== null && String((entry as { name?: unknown }).name ?? \"\").trim().toLowerCase() === wanted,\n ) as { id?: unknown } | undefined;\n return typeof found?.id === \"string\" ? found.id : null;\n}\n\n/** The category named `name` on iFood, or null; the failure that ended the read otherwise. */\nasync function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {\n const listed = await call(ctx, \"GET\", \"categories\");\n if (\"kind\" in listed) return listed;\n if (!ok(listed)) return failureOf(listed);\n return { id: categoryIdIn(listed.body, name) };\n}\n\n/**\n * Find the category by name, else create it, then read the list again and\n * adopt the first of that name: a POST whose answer was lost and was retried\n * is found rather than created twice. The engine runs this once per\n * (connection, name) at a time and stores the id (`ctx.category`).\n */\nasync function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {\n const found = await findCategory(ctx, name);\n if (\"kind\" in found) return found;\n if (found.id) return { id: found.id };\n const created = await call(ctx, \"POST\", \"categories\", { name, status: \"AVAILABLE\", template: \"DEFAULT\" });\n if (\"kind\" in created) return created;\n if (!ok(created)) return failureOf(created);\n const id = (parse(created.body) as { id?: unknown } | null)?.id;\n if (typeof id !== \"string\") return { kind: \"retry\", reason: \"iFood created the category without an id\" };\n // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.\n const again = await findCategory(ctx, name);\n return \"id\" in again && again.id ? { id: again.id } : { id };\n}\n\nconst categoryId = (ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> =>\n ctx.category(name, () => findOrCreateCategory(ctx, name));\n\n/** The photo the item goes out with, and what the publish could not do about it. */\ninterface PhotoOutcome {\n image: CatalogueStoredImage | null;\n warning?: CatalogueWarningCode;\n}\n\n/**\n * The photo for this publish, uploading only when it must:\n * - no `imageUrl`: no photo;\n * - the photo iFood already holds was made from this same URL: reuse it;\n * - else upload the bytes the host's loader reads; when it reads nothing,\n * keep the photo iFood holds, if any (PUT replaces the whole item, so\n * sending none would drop it);\n * - an upload iFood refuses (413 over 5 MB, another final 4xx) publishes\n * without a photo and says why as a warning, rather than failing the item.\n */\nasync function photoFor(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<PhotoOutcome | Failure> {\n const stored = item.storedImage;\n if (item.imageUrl === null) return { image: null };\n if (stored && stored.sourceUrl === item.imageUrl) return { image: stored };\n const bytes = await ctx.loadImage(item.imageUrl);\n return bytes ? upload(ctx, bytes, item.imageUrl) : { image: stored };\n}\n\n/** `POST /image/upload`: the new photo, a warning for a refused one, or the failure to retry. */\nasync function upload(ctx: CatalogueCallContext, bytes: CatalogueImage, sourceUrl: string): Promise<PhotoOutcome | Failure> {\n const uploaded = await call(ctx, \"POST\", \"image/upload\", { image: `data:${bytes.contentType};base64,${bytes.base64}` });\n if (\"kind\" in uploaded) return uploaded;\n if (!ok(uploaded)) {\n const failure = failureOf(uploaded);\n if (failure.kind === \"retry\") return failure;\n return { image: null, warning: uploaded.status === 413 ? \"IMAGE_TOO_LARGE\" : \"IMAGE_REFUSED\" };\n }\n const path = (parse(uploaded.body) as { imagePath?: unknown } | null)?.imagePath;\n if (typeof path !== \"string\") return { kind: \"retry\", reason: \"iFood answered the upload without an imagePath\" };\n return { image: { ref: path, sourceUrl } };\n}\n\n/** The `PUT /items` body for one simple item with no add-ons. */\nexport function ifoodItemBody(item: CatalogueItemOut, category: string, image: string | null): unknown {\n const itemId = ifoodItemId(item.ref);\n const productId = ifoodProductId(item.ref);\n return {\n item: {\n id: itemId,\n type: \"DEFAULT\",\n categoryId: category,\n status: \"AVAILABLE\",\n price: priceOf(item.priceCents),\n externalCode: item.productId,\n // ESTIMATED: the guide's examples link item and product implicitly; the\n // field naming the product is not shown on the pages read.\n productId,\n },\n products: [\n {\n id: productId,\n name: item.name,\n description: item.description ?? \"\",\n externalCode: `${item.productId}-product`,\n // ESTIMATED field name: the Errors page names `imagePath` as what the upload returns and the item carries.\n ...(image === null ? {} : { imagePath: image }),\n },\n ],\n optionGroups: [],\n options: [],\n };\n}\n\n/**\n * Whether a refused PUT was refused because the stored category is gone (the\n * store deleted it on iFood's portal): iFood's 400 and 404 do not say which id\n * was unknown, so the list is read again, and a category of that name with\n * another id, or none at all, means the stored one is stale. ESTIMATED that a\n * deleted category answers 400 or 404.\n */\nasync function categoryWentStale(ctx: CatalogueCallContext, put: MarketplaceHttpResponse, name: string, used: string): Promise<boolean> {\n if (put.status !== 400 && put.status !== 404) return false;\n const found = await findCategory(ctx, name);\n return !(\"kind\" in found) && found.id !== used;\n}\n\n/** `PUT /items`, once more with the category found or created again when the stored one went stale. */\nasync function putItem(ctx: CatalogueCallContext, item: CatalogueItemOut, image: string | null): Promise<MarketplaceHttpResponse | Failure> {\n const category = await categoryId(ctx, item.categoryName);\n if (\"kind\" in category) return category;\n const put = await call(ctx, \"PUT\", \"items\", ifoodItemBody(item, category.id, image));\n if (\"kind\" in put || ok(put) || !(await categoryWentStale(ctx, put, item.categoryName, category.id))) return put;\n await ctx.forgetCategory(item.categoryName);\n const again = await categoryId(ctx, item.categoryName);\n if (\"kind\" in again) return again;\n return call(ctx, \"PUT\", \"items\", ifoodItemBody(item, again.id, image));\n}\n\nasync function publish(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult> {\n const photo = await photoFor(ctx, item);\n if (\"kind\" in photo) return photo;\n const put = await putItem(ctx, item, photo.image?.ref ?? null);\n if (\"kind\" in put) return put;\n if (!ok(put)) return failureOf(put);\n // iFood's orders carry the item's `externalCode` as the line's SKU (the order normalizer reads it).\n const published = { kind: \"published\" as const, externalId: ifoodItemId(item.ref), sku: item.productId, image: photo.image };\n return photo.warning ? { ...published, warning: photo.warning } : published;\n}\n\nasync function withdraw(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult> {\n const itemId = item.externalId ?? ifoodItemId(item.ref);\n const patched = await call(ctx, \"PATCH\", \"items/status\", { itemId, status: \"UNAVAILABLE\" });\n if (\"kind\" in patched) return patched;\n // ESTIMATED: a 404 means iFood does not have the item, so it is already out\n // of its catalogue (the Errors page says 404 is \"the resource does not exist\").\n if (patched.status === 404) return { kind: \"accepted\" };\n return outboundResultOf(patched);\n}\n\n/** A call that never got an answer is a retry. */\nasync function publishedOrRetry(run: () => Promise<CataloguePublishResult>): Promise<CataloguePublishResult> {\n try {\n return await run();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** iFood's catalogue capability. */\nexport const IFOOD_CATALOGUE: PushCatalogue = {\n mode: \"push\",\n publishItem: (ctx, item) => publishedOrRetry(() => publish(ctx, item)),\n withdrawItem: (ctx, item) => answered(() => withdraw(ctx, item)),\n};\n","import {\n centsFromMajor,\n type CatalogueReadNotice,\n type CatalogueReadWarning,\n type CatalogueSnapshotItem,\n type CatalogueSnapshotOption,\n type CatalogueSnapshotOptionGroup,\n} from \"../core/catalogue-read-port\";\n\n/**\n * iFood's catalogue answer mapped into the engine's {@link CatalogueSnapshotItem}\n * (FUT-951). Pure and offline: `./catalogue-read.ts` makes the calls.\n *\n * The shapes are the Catalog API v2.0's `PUT /items` payload, which the\n * portal's Introduction shows whole (read 2026-11-16): an `item` (id, type,\n * categoryId, status, `price { value }`, externalCode), `products` (id, name,\n * description, externalCode, and `optionGroups: [{ id, min, max }]` linking a\n * product to its groups), `optionGroups` (id, name, status, `optionIds`) and\n * `options` (id, `productId` naming the product that holds its name, status,\n * `price { value }`). The package README's \"Catalogue reading\" table marks\n * each fact CONFIRMED with its URL or ESTIMATED. ESTIMATED here, and said\n * beside each use:\n * - that `GET /categories/{categoryId}/items` answers the same four lists\n * (`items` plural) the PUT takes;\n * - that `item.productId` names the item's product (the field the push sends);\n * - that `products[].imagePath` holds the photo, a path under\n * {@link IFOOD_IMAGE_BASE_URL}.\n */\n\n/**\n * Where iFood serves a catalogue photo's `imagePath`. ESTIMATED: the Catalog\n * pages read name `imagePath` but not its host; this is the host iFood's own\n * app loads dish photos from. A path that is already an absolute https URL is\n * used as it is.\n */\nexport const IFOOD_IMAGE_BASE_URL = \"https://static-images.ifood.com.br/image/upload/t_high/pratos/\";\n\ntype Json = Record<string, unknown>;\n\nexport const record = (value: unknown): Json | null =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Json) : null;\n\nexport const text = (value: unknown): string | null => (typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : null);\n\n/**\n * The objects of a JSON array, and every other entry it held (a string, a\n * number, a nested array), so the caller can SAY what it could not read rather\n * than lose it. Not an array: no entries, nothing else.\n */\nexport function entriesOf(value: unknown): { entries: Json[]; others: unknown[] } {\n const entries: Json[] = [];\n const others: unknown[] = [];\n for (const entry of Array.isArray(value) ? value : []) {\n const object = record(entry);\n if (object) entries.push(object);\n else others.push(entry);\n }\n return { entries, others };\n}\n\n/**\n * The lookup lists (`products`, `optionGroups`, `options`) keep only objects\n * with an id: an entry is only ever reached through an id that names it, and a\n * reference that finds nothing is warned about where it is made\n * (OPTION_GROUP_UNREADABLE, OPTION_UNREADABLE, or the item's ITEM_UNREADABLE).\n */\nconst list = (value: unknown): Json[] => entriesOf(value).entries;\n\n/** iFood's `status`: anything but UNAVAILABLE is on sale (an absent status included). */\nexport const availableOf = (status: unknown): boolean => status !== \"UNAVAILABLE\";\n\n/** The four lists of one category's answer, each by id. */\ninterface IfoodCatalogueIndex {\n products: Map<string, Json>;\n optionGroups: Map<string, Json>;\n options: Map<string, Json>;\n}\n\nconst byId = (entries: Json[]): Map<string, Json> =>\n new Map(entries.flatMap((entry) => (text(entry.id) ? [[text(entry.id) as string, entry] as const] : [])));\n\nexport function indexOf(answer: Json): IfoodCatalogueIndex {\n return { products: byId(list(answer.products)), optionGroups: byId(list(answer.optionGroups)), options: byId(list(answer.options)) };\n}\n\nconst priceCentsOf = (price: unknown): number | null => centsFromMajor(record(price)?.value);\n\nconst warning = (code: CatalogueReadWarning[\"code\"], subject: string | null, detail: unknown = null): CatalogueReadWarning => ({\n code,\n subject,\n detail: detail === null || detail === undefined ? null : JSON.stringify(detail),\n});\n\n/** The photo's absolute URL; a warning when a reference is there but cannot be resolved. */\nexport function photoOf(imagePath: unknown, subject: string | null): { url: string | null; warning?: CatalogueReadWarning } {\n if (imagePath === undefined || imagePath === null || imagePath === \"\") return { url: null };\n const path = text(imagePath);\n if (path === null) return { url: null, warning: warning(\"PHOTO_UNREADABLE\", subject, imagePath) };\n if (/^https:\\/\\//i.test(path)) return { url: path };\n if (/^[a-z][a-z0-9+.-]*:/i.test(path)) return { url: null, warning: warning(\"PHOTO_UNREADABLE\", subject, path) };\n return { url: `${IFOOD_IMAGE_BASE_URL}${urlSafePath(path.replace(/^\\/+/, \"\"))}` };\n}\n\n/**\n * The path as a URL path: kept as it is when it is already one (an encoded\n * `%20` stays `%20`, never `%2520`); only a character a URL may not carry\n * (a space, a quote, a non-ASCII letter) is encoded, and a `%` that starts no\n * escape becomes `%25`.\n */\nfunction urlSafePath(path: string): string {\n return path\n .replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\")\n .replace(/[^A-Za-z0-9\\-._~!$&'()*+,;=:@/%]/g, (character) => encodeURIComponent(character));\n}\n\n/** The words and photo of an item or option: its product's (`productId`), else its own. */\ninterface Described {\n name: string | null;\n description: string | null;\n externalCode: string | null;\n imagePath: unknown;\n}\n\nfunction describedBy(index: IfoodCatalogueIndex, own: Json): Described {\n const product = index.products.get(text(own.productId) ?? \"\") ?? {};\n return {\n name: text(product.name) ?? text(own.name),\n description: text(product.description) ?? text(own.description),\n externalCode: text(own.externalCode) ?? text(product.externalCode),\n imagePath: product.imagePath ?? own.imagePath,\n };\n}\n\n/** The photo's URL, its warning (if any) pushed onto `warnings`. */\nfunction photoInto(imagePath: unknown, subject: string | null, warnings: CatalogueReadWarning[]): string | null {\n const photo = photoOf(imagePath, subject);\n if (photo.warning) warnings.push(photo.warning);\n return photo.url;\n}\n\n/** One option of a group, or the warning that leaves it out. */\nfunction optionOf(id: string, index: IfoodCatalogueIndex, warnings: CatalogueReadWarning[]): CatalogueSnapshotOption | null {\n const option = index.options.get(id);\n const described = option ? describedBy(index, option) : null;\n if (!option || !described || described.name === null) {\n warnings.push(warning(\"OPTION_UNREADABLE\", id, option));\n return null;\n }\n const priceDeltaCents = priceCentsOf(option.price);\n if (priceDeltaCents === null) warnings.push(warning(\"OPTION_PRICE_MISSING\", id, option.price));\n return {\n externalId: id,\n externalCode: described.externalCode,\n name: described.name,\n description: described.description,\n priceDeltaCents,\n photoUrl: photoInto(described.imagePath, id, warnings),\n available: availableOf(option.status),\n };\n}\n\n/** A group's bounds, when they make sense: whole numbers, 0 <= min <= max, max >= 1. */\nfunction boundsOf(link: Json, group: Json): { min: number; max: number } | null {\n const min = link.min ?? group.min ?? 0;\n const max = link.max ?? group.max;\n if (!Number.isInteger(min) || !Number.isInteger(max)) return null;\n const [low, high] = [min as number, max as number];\n return low >= 0 && high >= 1 && high >= low ? { min: low, max: high } : null;\n}\n\n/** A group's option ids; an entry that is not an id is an OPTION_UNREADABLE warning, never dropped. */\nfunction idsOf(groupId: string, value: unknown, warnings: CatalogueReadWarning[]): string[] {\n const ids: string[] = [];\n for (const entry of Array.isArray(value) ? value : []) {\n const id = text(entry);\n if (id === null) warnings.push(warning(\"OPTION_UNREADABLE\", groupId, entry));\n else ids.push(id);\n }\n return ids;\n}\n\n/** One group a product links to (`products[].optionGroups[]`), or the warning that leaves it out. */\nfunction groupOf(link: Json, index: IfoodCatalogueIndex, warnings: CatalogueReadWarning[]): CatalogueSnapshotOptionGroup | null {\n const id = text(link.id);\n const group = id === null ? undefined : index.optionGroups.get(id);\n const bounds = group ? boundsOf(link, group) : null;\n const name = text(group?.name);\n if (id === null || !group || name === null || bounds === null) {\n warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", id, { link, group }));\n return null;\n }\n const options = idsOf(id, group.optionIds, warnings).flatMap((optionId) => optionOf(optionId, index, warnings) ?? []);\n if (options.length === 0) {\n warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", id, \"no readable option\"));\n return null;\n }\n return { externalId: id, externalCode: text(group.externalCode), name, ...bounds, available: availableOf(group.status), options };\n}\n\n/** The item's own warnings: a kind it maps only partly, and a missing price. */\nfunction itemWarnings(raw: Json, priceCents: number | null): CatalogueReadWarning[] {\n const warnings: CatalogueReadWarning[] = [];\n const type = text(raw.type);\n if (type !== null && type !== \"DEFAULT\") warnings.push(warning(\"ITEM_TYPE_UNSUPPORTED\", null, type));\n if (priceCents === null) warnings.push(warning(\"PRICE_MISSING\", null, raw.price));\n return warnings;\n}\n\n/**\n * The group links of an item: on its product (CONFIRMED, the PUT example),\n * else on the item itself. Links that are not objects, or a value that is not\n * a list at all, are an OPTION_GROUP_UNREADABLE warning each.\n */\nfunction linksOf(index: IfoodCatalogueIndex, raw: Json, warnings: CatalogueReadWarning[]): Json[] {\n const product = index.products.get(text(raw.productId) ?? \"\");\n const value = product?.optionGroups ?? raw.optionGroups;\n if (value !== undefined && value !== null && !Array.isArray(value)) warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", null, value));\n const { entries, others } = entriesOf(value);\n for (const other of others) warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", null, other));\n return entries;\n}\n\n/** One item of a category, or the notice that says why it could not be read. */\nexport function itemOf(raw: Json, index: IfoodCatalogueIndex, categoryId: string): CatalogueSnapshotItem | CatalogueReadNotice {\n const id = text(raw.id);\n // ESTIMATED: `item.productId` names the product that holds the item's name, description and photo.\n const described = describedBy(index, raw);\n if (id === null || described.name === null) {\n return { code: \"ITEM_UNREADABLE\", categoryExternalId: categoryId, externalId: id, detail: JSON.stringify(raw).slice(0, 300) };\n }\n const priceCents = priceCentsOf(raw.price);\n const warnings = itemWarnings(raw, priceCents);\n const photoUrl = photoInto(described.imagePath, null, warnings);\n const optionGroups = linksOf(index, raw, warnings).flatMap((link) => groupOf(link, index, warnings) ?? []);\n return {\n externalId: id,\n externalCode: described.externalCode,\n name: described.name,\n description: described.description,\n priceCents,\n photoUrl,\n available: availableOf(raw.status),\n optionGroups,\n warnings,\n };\n}\n","import { outboundResultOf, type MarketplaceHttpResponse, type OutboundResult } from \"../core/adapter\";\nimport type {\n CatalogueReadContext,\n CatalogueReader,\n CatalogueReadNotice,\n CatalogueReadResult,\n CatalogueSnapshotCategory,\n CatalogueSnapshotItem,\n} from \"../core/catalogue-read-port\";\nimport { availableOf, entriesOf, indexOf, itemOf, record, text } from \"./catalogue-snapshot\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * The iFood adapter's catalogue READ (FUT-951): the menu a store already keeps\n * on iFood, read through the store's OWN connection (its merchant id, and the\n * client-credentials token of its app, `bearer`), for the host to import.\n *\n * One read is, in order:\n * 1. `GET /categories` — the merchant's categories (CONFIRMED, the Endpoints\n * page as read 2026-11-13; ESTIMATED that it answers an array of\n * `{ id, name, status, externalCode }`, the same estimate the push makes);\n * 2. `GET /categories/{categoryId}/items` for each, in the list's order\n * (CONFIRMED, the Introduction's step 5, read 2026-11-16), mapped by\n * `./catalogue-snapshot.ts`.\n *\n * Pagination: none. The pages read show no page, size or cursor parameter on\n * either call (ESTIMATED that there is none), so the menu is read one category\n * per call, which bounds each answer by a category's size.\n *\n * Failures:\n * - a 401 drops the cached token and asks once more with a fresh one (as the\n * push's `call` does); a second 401 is a `retry`;\n * - the token grant refused (400, 401, 403) is `CREDENTIALS`;\n * - 403 (the Errors page: the app is not allowed this merchant, or the\n * catalogue module is not enabled for it) and 404 on the category list (no\n * such merchant for this app, ESTIMATED) are `NOT_AUTHORIZED`;\n * - 429, 408, 425, 5xx and a call with no answer are `retry`;\n * - any other 4xx is `REFUSED`, with iFood's words.\n * A category whose own items answer 404 (deleted between the two calls), or\n * answer in a shape other than `{ items: [...] }`, is left out with a\n * CATEGORY_UNREADABLE notice rather than failing the read; an entry of a list\n * that is not an object is a notice too. Only a category LIST that is not a\n * list refuses the read (REFUSED): without it there is no menu to keep.\n */\n\nconst catalogUrl = (merchantId: string, path: string): string =>\n `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;\n\ntype Failure = Exclude<CatalogueReadResult, { kind: \"snapshot\" }>;\n\n/** The token grant's failure: a refusal is the store's credentials, anything else is asked again. */\nfunction tokenFailure(result: OutboundResult): Failure {\n if (result.kind === \"refused\") return { kind: \"refused\", code: \"CREDENTIALS\", status: result.status, message: result.message };\n return { kind: \"retry\", reason: result.kind === \"retry\" ? result.reason : \"unexpected token answer\" };\n}\n\n/** A non-2xx catalogue answer as the failure it is. */\nfunction failureOf(response: MarketplaceHttpResponse): Failure {\n const result = outboundResultOf(response);\n if (result.kind !== \"refused\") return { kind: \"retry\", reason: result.kind === \"retry\" ? result.reason : \"unexpected answer\" };\n const code = response.status === 403 || response.status === 404 ? \"NOT_AUTHORIZED\" : \"REFUSED\";\n return { kind: \"refused\", code, status: result.status, message: result.message };\n}\n\n/** One authenticated GET: iFood's answer (any status but 401), or the failure that ends the read. */\nasync function get(ctx: CatalogueReadContext, path: string): Promise<MarketplaceHttpResponse | Failure> {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return tokenFailure(auth);\n const response = await ctx.http({\n method: \"GET\",\n url: catalogUrl(ctx.externalMerchantId, path),\n headers: { Authorization: `Bearer ${auth.token}`, Accept: \"application/json\" },\n });\n if (response.status !== 401) return response;\n // A token that went stale under us: forget it, and the next turn grants another.\n ctx.tokens.delete(ifoodTokenKey(ctx));\n }\n return { kind: \"retry\", reason: \"iFood refused a fresh token\" };\n}\n\nconst ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;\n\nfunction parse(body: string): unknown {\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return null;\n }\n}\n\nconst unexpected = (what: string, body: string): Failure => ({\n kind: \"refused\",\n code: \"REFUSED\",\n status: 200,\n message: `unexpected ${what} answer: ${body.slice(0, 200)}`,\n});\n\n/** One category's items, or the notice that leaves the category out, or the failure that ends the read. */\nasync function categoryOf(\n ctx: CatalogueReadContext,\n raw: Record<string, unknown>,\n notices: CatalogueReadNotice[],\n): Promise<CatalogueSnapshotCategory | null | Failure> {\n const id = text(raw.id);\n const name = text(raw.name);\n if (id === null || name === null) {\n notices.push(unreadableCategory(id, raw));\n return null;\n }\n const answered = await get(ctx, `categories/${encodeURIComponent(id)}/items`);\n if (\"kind\" in answered) return answered;\n if (answered.status === 404) {\n notices.push(unreadableCategory(id, \"its items answered 404\"));\n return null;\n }\n if (!ok(answered)) return failureOf(answered);\n const items = itemsOf(answered.body, id, notices);\n return items && { externalId: id, externalCode: text(raw.externalCode), name, available: availableOf(raw.status), items };\n}\n\nconst unreadableCategory = (categoryExternalId: string | null, detail: unknown): CatalogueReadNotice => ({\n code: \"CATEGORY_UNREADABLE\",\n categoryExternalId,\n externalId: null,\n detail: (typeof detail === \"string\" ? detail : JSON.stringify(detail) ?? String(detail)).slice(0, 300),\n});\n\n/**\n * One category's items, each one it cannot read an ITEM_UNREADABLE notice; or\n * null, with a CATEGORY_UNREADABLE notice, when the answer is not the expected\n * `{ items: [...] }` (ESTIMATED: the PUT's four lists, `items` plural). A\n * notice rather than refusing the whole read: one category answered in an odd\n * shape keeps the rest of the menu importable, and the host shows which\n * category did not come over; a shape iFood changed everywhere leaves a notice\n * on every category, never a silent empty menu.\n */\nfunction itemsOf(rawBody: string, categoryId: string, notices: CatalogueReadNotice[]): CatalogueSnapshotItem[] | null {\n const body = record(parse(rawBody));\n if (!body || !Array.isArray(body.items)) {\n notices.push(unreadableCategory(categoryId, `unexpected items answer: ${rawBody}`));\n return null;\n }\n const index = indexOf(body);\n const { entries, others } = entriesOf(body.items);\n for (const other of others) {\n notices.push({ code: \"ITEM_UNREADABLE\", categoryExternalId: categoryId, externalId: null, detail: String(JSON.stringify(other)).slice(0, 300) });\n }\n const items: CatalogueSnapshotItem[] = [];\n for (const entry of entries) {\n const mapped = itemOf(entry, index, categoryId);\n if (\"code\" in mapped) notices.push(mapped);\n else items.push(mapped);\n }\n return items;\n}\n\nasync function read(ctx: CatalogueReadContext): Promise<CatalogueReadResult> {\n const listed = await get(ctx, \"categories\");\n if (\"kind\" in listed) return listed;\n if (!ok(listed)) return failureOf(listed);\n const parsed = parse(listed.body);\n if (!Array.isArray(parsed)) return unexpected(\"category list\", listed.body);\n const categories: CatalogueSnapshotCategory[] = [];\n const notices: CatalogueReadNotice[] = [];\n const { entries, others } = entriesOf(parsed);\n // A category entry that is not an object is said, never skipped.\n for (const other of others) notices.push(unreadableCategory(null, other));\n for (const raw of entries) {\n const category = await categoryOf(ctx, raw, notices);\n if (category === null) continue;\n if (\"kind\" in category) return category;\n categories.push(category);\n }\n return { kind: \"snapshot\", snapshot: { categories, notices } };\n}\n\n/** iFood's catalogue read. */\nexport const IFOOD_CATALOGUE_READER: CatalogueReader = {\n read: async (ctx) => {\n try {\n return await read(ctx);\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n },\n};\n","import { outboundResultOf, type AdapterCallContext, type OutboundOrderRef } from \"../core/adapter\";\nimport type {\n CourierTrackingCallResult,\n MarketplaceCourierApi,\n MarketplaceCourierTracking,\n PickupCodeCallResult,\n} from \"../core/courier-port\";\nimport { firstDate, firstString, pick } from \"../core/payload-read\";\nimport type { MarketplaceCourier, MarketplaceCourierStep, MarketplaceCourierVehicle, NormalizedCourierEvent } from \"../core/types\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * iFood's own fleet (FUT-5665), both halves: the courier events of iFood's\n * stream, and the two calls about the courier (the pickup-code check and the\n * tracking read). Only for an order iFood's fleet carries\n * (`delivery.deliveredBy = IFOOD`); the engine never calls either for another.\n *\n * Source: the iFood research of 2026-11-26 (Levantamento, lines 95-115),\n * marked confirmed there against iFood's Order module docs; what it could not\n * confirm is marked ESTIMATED below, in this file only.\n */\n\n/**\n * iFood's courier event codes, short and long. The four short codes and every\n * long form are confirmed; the two return events have no documented short\n * code, so only their long forms are read (ESTIMATED: none is guessed).\n */\nconst COURIER_STEP_OF: Readonly<Record<string, MarketplaceCourierStep>> = {\n ADR: \"ASSIGNED\",\n ASSIGN_DRIVER: \"ASSIGNED\",\n GTO: \"GOING_TO_ORIGIN\",\n GOING_TO_ORIGIN: \"GOING_TO_ORIGIN\",\n AAO: \"ARRIVED_AT_ORIGIN\",\n ARRIVED_AT_ORIGIN: \"ARRIVED_AT_ORIGIN\",\n CLT: \"COLLECTED\",\n COLLECTED: \"COLLECTED\",\n DELIVERY_RETURNING_TO_ORIGIN: \"RETURNING_TO_ORIGIN\",\n DELIVERY_RETURNED_TO_ORIGIN: \"RETURNED_TO_ORIGIN\",\n};\n\n/**\n * `workerVehicleType` as the host's closed set. ESTIMATED: the field is\n * confirmed, its values are not documented in the research; these are the\n * words a vehicle is plausibly named with, and anything else stated is OTHER.\n */\nconst VEHICLE_OF: Readonly<Record<string, MarketplaceCourierVehicle>> = {\n MOTORCYCLE: \"MOTORCYCLE\",\n MOTORBIKE: \"MOTORCYCLE\",\n MOTO: \"MOTORCYCLE\",\n BICYCLE: \"BICYCLE\",\n BIKE: \"BICYCLE\",\n CAR: \"CAR\",\n CARRO: \"CAR\",\n};\n\n/** The longest courier name kept: a longer one is truncated, never refused. */\nexport const IFOOD_COURIER_NAME_MAX = 120;\n/** The longest photo URL kept: a longer one is dropped (a truncated URL is a broken one). */\nconst IFOOD_COURIER_PHOTO_URL_MAX = 2048;\n\n/** An https URL of bounded length, or null: a photo the host renders is never another scheme. */\nfunction httpsUrl(value: string | null): string | null {\n if (!value || value.length > IFOOD_COURIER_PHOTO_URL_MAX) return null;\n try {\n return new URL(value).protocol === \"https:\" ? value : null;\n } catch {\n return null;\n }\n}\n\n/** The event's `metadata`: an object, or a JSON string of one. */\nfunction metadataOf(payload: unknown): unknown {\n const raw = pick(payload, \"metadata\");\n if (typeof raw !== \"string\") return raw;\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n}\n\n/** The courier an ADR names: `workerName`, `workerPhotoUrl`, `workerVehicleType`. Null when it names nothing. */\nfunction readCourier(payload: unknown): MarketplaceCourier | null {\n const metadata = metadataOf(payload);\n const name = firstString(metadata, [[\"workerName\"]])?.slice(0, IFOOD_COURIER_NAME_MAX) ?? null;\n const photoUrl = httpsUrl(firstString(metadata, [[\"workerPhotoUrl\"]]));\n const stated = firstString(metadata, [[\"workerVehicleType\"]])?.toUpperCase() ?? null;\n const vehicle = stated === null ? null : (VEHICLE_OF[stated] ?? \"OTHER\");\n return name === null && photoUrl === null && vehicle === null ? null : { name, photoUrl, vehicle };\n}\n\n/** The courier step an iFood event names, or null. */\nexport function readIfoodCourierEvent(payload: unknown, eventType: string): NormalizedCourierEvent | null {\n const step = COURIER_STEP_OF[eventType.toUpperCase()];\n if (!step) return null;\n return {\n step,\n at: firstDate(payload, [[\"createdAt\"]]),\n courier: step === \"ASSIGNED\" ? readCourier(payload) : null,\n returning: step === \"RETURNING_TO_ORIGIN\" ? \"RETURNING\" : step === \"RETURNED_TO_ORIGIN\" ? \"RETURNED\" : null,\n };\n}\n\nconst orderUrl = (ref: OutboundOrderRef, action: string): string =>\n `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(ref.externalOrderId)}/${action}`;\n\n/** One authenticated call; a 401 forgets the token so the retry fetches another. */\nasync function call(\n ctx: AdapterCallContext,\n request: { method: \"GET\" | \"POST\"; url: string; body?: unknown },\n): Promise<{ status: number; body: string } | { kind: \"refused\"; status: number; message: string; own?: true } | { kind: \"retry\"; reason: string }> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"no token\" } : auth;\n const response = await ctx.http({\n method: request.method,\n url: request.url,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),\n });\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n return { kind: \"retry\", reason: \"iFood refused the token\" };\n}\n\nfunction parsed(body: string): unknown {\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return null;\n }\n}\n\n/**\n * `POST /order/v1.0/orders/{id}/validatePickupCode {\"code\"}`, answering\n * `{\"valid\": true|false}` (confirmed). A 2xx without a boolean `valid` is no\n * verdict: our own refusal, never read as INVALID.\n */\nasync function validatePickupCode(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { code: string },\n): Promise<PickupCodeCallResult> {\n try {\n const response = await call(ctx, { method: \"POST\", url: orderUrl(order, \"validatePickupCode\"), body: { code: input.code } });\n if (\"kind\" in response) return response;\n const read = outboundResultOf(response);\n if (read.kind !== \"accepted\") return read;\n const valid = pick(parsed(response.body), \"valid\");\n return typeof valid === \"boolean\"\n ? { kind: \"answered\", valid }\n : { kind: \"refused\", status: response.status, message: \"iFood answered without a verdict\", own: true };\n } catch (error) {\n return retryOf(error);\n }\n}\n\n/** A call that never got an answer is a retry. */\nfunction retryOf(error: unknown): { kind: \"retry\"; reason: string } {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n}\n\nfunction numberAt(source: unknown, key: string): number | null {\n const value = pick(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\n/** `base` plus a number of seconds, or null when either is missing. */\nfunction plusSeconds(base: Date, seconds: number | null): Date | null {\n return seconds === null ? null : new Date(base.getTime() + seconds * 1000);\n}\n\n/**\n * The tracking body. Confirmed: latitude, longitude, `expectedDelivery`,\n * `trackDate`, and seconds to the pickup and to the delivery. ESTIMATED: the\n * names of the two second counts (`pickupEtaStart`, `deliveryEtaEnd`, or\n * `pickupEta`, `deliveryEta`), counted from `trackDate`.\n */\nfunction readTracking(body: unknown, now: Date): MarketplaceCourierTracking {\n const trackedAt = firstDate(body, [[\"trackDate\"]]);\n const base = trackedAt ?? now;\n const pickupSeconds = numberAt(body, \"pickupEtaStart\") ?? numberAt(body, \"pickupEta\");\n const deliverySeconds = numberAt(body, \"deliveryEtaEnd\") ?? numberAt(body, \"deliveryEta\");\n return {\n pickupEtaAt: plusSeconds(base, pickupSeconds),\n deliveryEtaAt: firstDate(body, [[\"expectedDelivery\"]]) ?? plusSeconds(base, deliverySeconds),\n latitude: numberAt(body, \"latitude\"),\n longitude: numberAt(body, \"longitude\"),\n trackedAt,\n };\n}\n\n/** `GET /order/v1.0/orders/{id}/tracking` (confirmed): 404 before ASSIGN_DRIVER is \"not yet\". */\nasync function tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<CourierTrackingCallResult> {\n try {\n const response = await call(ctx, { method: \"GET\", url: orderUrl(order, \"tracking\") });\n if (\"kind\" in response) return response;\n if (response.status === 404) return { kind: \"notYet\" };\n const read = outboundResultOf(response);\n if (read.kind !== \"accepted\") return read;\n return { kind: \"tracking\", tracking: readTracking(parsed(response.body), ctx.now) };\n } catch (error) {\n return retryOf(error);\n }\n}\n\n/** iFood's courier calls, for the adapter's `courier`. */\nexport const IFOOD_COURIER: MarketplaceCourierApi = { validatePickupCode, tracking };\n","import type {\n MarketplaceLifecycle,\n MarketplaceDeliveredBy,\n MarketplaceDiscountSponsor,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedBuyer,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderDiscount,\n NormalizedOrderLine,\n} from \"../core/types\";\nimport {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n toCents,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\nimport { readIfoodCourierEvent } from \"./courier\";\n\n/**\n * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.\n *\n * Everything iFood-shaped about a delivery is in this file, and the engine\n * never learns the name: it reaches this through the adapter registry.\n *\n * The payload is treated as UNTRUSTED and read defensively throughout: iFood's\n * documented shape and iFood's actual shape have drifted before, and a\n * `TypeError` reading a missing field would reject a paid order at the door.\n * Every reader below either produces a value or produces null; the one thing\n * that can refuse an order outright is a missing order ID, because without it\n * there is no idempotency key and ingesting would risk a duplicate.\n */\n\n/** iFood event codes this ingestion acts on. */\nconst ORDER_PLACED = new Set([\"PLC\", \"PLACED\", \"ORDER_PLACED\"]);\nconst ORDER_CANCELLED = new Set([\"CAN\", \"CANCELLED\", \"ORDER_CANCELLED\"]);\n/** iFood refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_FAILED = new Set([\"CARF\", \"CANCELLATION_REQUEST_FAILED\"]);\n\n/**\n * The lifecycle events (FUT-4653): the order left (`DSP`) and the order is\n * finished (`CON`). ESTIMATED: iFood's portal refused our reader (Cloudflare\n * 403, https://developer.ifood.com.br, 2026-11-25), so these codes and their\n * long forms are the ones iFood's event stream is commonly documented with,\n * not read off a page. They sit here beside the sets above so homologation\n * corrects one place.\n */\nconst LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = {\n DSP: \"DISPATCHED\",\n DISPATCHED: \"DISPATCHED\",\n CON: \"CONCLUDED\",\n CONCLUDED: \"CONCLUDED\",\n // iFood's courier has the bag (FUT-5665): for a fleet bag, the same hand-over as DSP.\n CLT: \"COLLECTED\",\n COLLECTED: \"COLLECTED\",\n};\n\n/**\n * Verify a delivery against the merchant's webhook secret: iFood signs the raw\n * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one\n * refuses an unsigned delivery; constant-time compare) is the engine's\n * {@link verifyHmacSha256Hex}. iFood's own onboarding issues the secret after\n * the merchant is certified, so refusing before then would make the\n * connection untestable.\n */\nexport function verifyIfoodSignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/** The buyer, as much of them as iFood discloses on the order. */\nfunction readBuyer(order: unknown): NormalizedBuyer {\n return {\n externalId: asString(pick(order, \"customer\", \"id\")),\n name: asString(pick(order, \"customer\", \"name\")),\n phone: firstString(order, [\n [\"customer\", \"phone\", \"number\"],\n [\"customer\", \"phone\"],\n ]),\n };\n}\n\n/**\n * One iFood item → one normalized line.\n *\n * A line with no resolvable SKU still becomes a line: `externalSku` falls back\n * to the item's own id, and failing that to its name. That fallback is doing\n * real work — an unmapped line is recoverable (the store maps it and it is\n * fixed forever), a DROPPED line is not, because nothing downstream can tell\n * that food is missing from the ticket.\n */\nfunction readLine(item: unknown): NormalizedOrderLine | null {\n const name = firstString(item, [[\"name\"], [\"description\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return null;\n const quantity = Number(pick(item, \"quantity\") ?? 1);\n return {\n externalSku: sku,\n name: name ?? sku,\n quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,\n unitPriceCents: firstCents(item, [[\"unitPrice\"], [\"price\"]]) ?? 0,\n note: firstString(item, [[\"observations\"], [\"note\"]]),\n };\n}\n\n/**\n * The commission iFood states on the order, in cents.\n *\n * Absent on plenty of real payloads (it depends on the merchant's contract and\n * on which API version delivered the order), and absent is stored as NULL\n * rather than as 0 — \"iFood took nothing\" and \"iFood did not say\" are different\n * claims, and only one of them is safe to put in a margin report.\n */\nfunction readCommission(order: unknown): number | null {\n return firstCents(order, [[\"total\", \"commission\"], [\"commission\"], [\"payments\", \"commission\"]]);\n}\n\n/** iFood's `orderType` as the two ways an order reaches the buyer, or null when it says neither. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"orderType\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\n/** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : null;\n}\n\n/**\n * iFood's sponsor names as who pays. ESTIMATED: the names are the ones iFood's\n * order-details guide documents for `benefits[].sponsorshipValues[].name`, but\n * no recorded payload in this repo carries them; confirm against a real order\n * (https://developer.ifood.com.br/en-US/docs/guides/order/details).\n */\nfunction sponsorOf(name: string | null): MarketplaceDiscountSponsor {\n const stated = name?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : \"OTHER\";\n}\n\n/**\n * The discounts on an order, one per sponsor's share of each benefit.\n * ESTIMATED shape (see {@link sponsorOf}): `benefits[]` with a `value` and\n * `sponsorshipValues[{ name, value, description? }]`. A benefit that names no\n * sponsor is the whole `value` under OTHER; a share with no usable amount is\n * skipped. Absent `benefits` is undefined (\"did not say\").\n */\nfunction readDiscounts(order: unknown): NormalizedOrderDiscount[] | undefined {\n const benefits = pick(order, \"benefits\");\n if (!Array.isArray(benefits)) return undefined;\n return benefits.flatMap((benefit): NormalizedOrderDiscount[] => {\n const shares = pick(benefit, \"sponsorshipValues\");\n const parts = Array.isArray(shares)\n ? shares.map((share) => ({\n cents: toCents(pick(share, \"value\")),\n sponsor: sponsorOf(firstString(share, [[\"name\"]])),\n name: firstString(share, [[\"description\"]]),\n }))\n : [{ cents: toCents(pick(benefit, \"value\")), sponsor: \"OTHER\" as const, name: null }];\n return parts.flatMap((part) =>\n part.cents === null || part.cents <= 0\n ? []\n : [{ cents: part.cents, sponsor: part.sponsor, ...(part.name === null ? {} : { name: part.name }) }],\n );\n });\n}\n\n/**\n * Where a delivery goes. The street is what a courier cannot find a door\n * without, so an address with none is none; a missing number reads as the\n * host's own words for \"no number\" (`copy.missingStreetNumber`), which keeps\n * the street, the neighbourhood and the reference rather than dropping the\n * whole door.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"streetName\"], [\"street\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"streetNumber\"], [\"number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]]),\n };\n}\n\n/** `{ key: value }` unless the value is undefined, so an unstated field is absent rather than `undefined`. */\nfunction optional<K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } {\n return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });\n}\n\n/**\n * The order body of a placed-order event, or null when it carries none. Also\n * reads the order iFood serves at `GET /order/v1.0/orders/{id}` (`./fetch-order.ts`),\n * whose fields are the same ones the event's `order` would carry.\n */\nexport function readIfoodOrder(\n payload: unknown,\n externalOrderId: string,\n missingStreetNumber: string,\n): NormalizedMarketplaceOrder | null {\n const order = pick(payload, \"order\") ?? payload;\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .map(readLine)\n .filter((line): line is NormalizedOrderLine => line !== null);\n if (lines.length === 0) return null;\n\n const stated = firstCents(order, [[\"total\", \"orderAmount\"], [\"totalPrice\"], [\"total\"]]);\n\n return {\n provider: \"IFOOD\",\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]) ?? firstString(payload, [[\"displayId\"]]),\n buyer: readBuyer(order),\n lines,\n // The line sum is the FALLBACK, never the preference: iFood's stated total\n // carries delivery fees, its promotions and its rounding, and it is the\n // number on the buyer's receipt. Summing lines when iFood did say is how a\n // store's revenue quietly stops matching its iFood statement.\n totalCents: stated ?? lines.reduce((sum, l) => sum + l.unitPriceCents * l.quantity, 0),\n commissionCents: readCommission(order),\n deliveryDueAt: firstDate(order, [[\"delivery\", \"deliveryDateTime\"], [\"preparationStartDateTime\"]]),\n placedAt:\n firstDate(order, [[\"createdAt\"]]) ?? firstDate(payload, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, missingStreetNumber),\n // ESTIMATED names (iFood's order-details guide: `total.deliveryFee`,\n // `total.subTotal`, `benefits[]`). Fee and subtotal are null when unstated,\n // never 0; `discounts` is absent when `benefits` is.\n deliveryFeeCents: firstCents(order, [[\"total\", \"deliveryFee\"]]),\n subtotalCents: firstCents(order, [[\"total\", \"subTotal\"]]),\n ...optional(\"discounts\", readDiscounts(order)),\n // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.\n pickupCode: firstString(order, [[\"delivery\", \"pickupCode\"]]),\n };\n}\n\n/**\n * The order a PLACED carries, or, when it carries none, the mark that has it\n * fetched: iFood's events carry only the order id (sandbox, 2026-11-27), so the\n * `marketplace.fetch-order` job reads it (FUT-5800). Any other event: no order.\n */\nfunction placedOrder(\n payload: unknown,\n placed: boolean,\n externalOrderId: string,\n missingStreetNumber: string,\n): Pick<NormalizedEvent, \"order\" | \"orderToFetch\"> {\n if (!placed) return { order: null };\n const order = readIfoodOrder(payload, externalOrderId, missingStreetNumber);\n return order ? { order } : { order: null, orderToFetch: true };\n}\n\n/**\n * Normalize one iFood delivery.\n *\n * Returns null only when the payload carries no order id at all — the one thing\n * this pipeline cannot proceed without, because it IS the idempotency key and\n * ingesting without it risks the duplicate that \"never lose an order\" is\n * balanced against.\n */\nexport function normalizeIfoodEvent(\n payload: unknown,\n options: { missingStreetNumber: string },\n): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"], [\"order\", \"id\"], [\"id\"]]);\n if (!externalOrderId) return null;\n\n const eventType = firstString(payload, [[\"fullCode\"], [\"code\"]]) ?? \"UNKNOWN\";\n const cancelled = ORDER_CANCELLED.has(eventType.toUpperCase());\n const placed = ORDER_PLACED.has(eventType.toUpperCase());\n const refusedRequest = CANCELLATION_REQUEST_FAILED.has(eventType.toUpperCase());\n\n return {\n provider: \"IFOOD\",\n // iFood's own event id when it sends one. The fallback is deterministic on\n // purpose — (order, type) is stable across a redelivery, so a duplicate\n // still collides on the inbox's unique index instead of creating a second\n // row that would be processed a second time.\n eventId: firstString(payload, [[\"id\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: firstString(payload, [[\"merchantId\"], [\"merchant\", \"id\"]]),\n externalOrderId,\n ...placedOrder(payload, placed, externalOrderId, options.missingStreetNumber),\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : refusedRequest ? \"FAILED\" : null,\n ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),\n ...optional(\"courier\", readIfoodCourierEvent(payload, eventType) ?? undefined),\n };\n}\n","import {\n outboundResultOf,\n type AdapterCallContext,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n} from \"../core/adapter\";\nimport { firstString } from \"../core/payload-read\";\nimport { readIfoodOrder } from \"./normalize\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * The iFood adapter's order read (FUT-5800): `GET /order/v1.0/orders/{id}`.\n *\n * iFood's events carry only the order id, so a PLACED with no items is marked\n * `orderToFetch` (`./normalize.ts`) and the engine's `marketplace.fetch-order`\n * job calls this, after the webhook's row is committed, never inside the\n * request. The order iFood serves has the fields the event's `order` would\n * have carried, so it is normalized by the same reader: a fetched order and a\n * carried one land identically.\n *\n * How an answer is read:\n * - 2xx with an order: the order, with the merchant its `merchant.id` names\n * (the engine refuses one naming another merchant than the connection's).\n * - 2xx that is not JSON: retried. 2xx naming another order, or no items: refused.\n * - 401: the cached token is forgotten and a new one asked for, ONCE, in the\n * same call. A second 401 is our credentials refused (`own`), as is a 403\n * (the merchant has not authorized this app) and a token grant iFood refuses.\n * - 404: retried. ESTIMATED: an order read right after its PLACED may not be\n * served yet; the job's attempt bound ends it.\n * - Everything else: the engine's one rule (`outboundResultOf`).\n */\n\nconst orderResourceUrl = (externalOrderId: string): string =>\n `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`;\n\n/** One authenticated GET, or the token's refusal or retry in its place. */\nasync function getOrder(\n ctx: AdapterCallContext,\n externalOrderId: string,\n): Promise<{ response: MarketplaceHttpResponse } | Exclude<FetchOrderResult, { kind: \"order\" }>> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) {\n return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"iFood answered the token grant without a token\" } : auth;\n }\n const response = await ctx.http({\n method: \"GET\",\n url: orderResourceUrl(externalOrderId),\n headers: { Authorization: `Bearer ${auth.token}`, Accept: \"application/json\" },\n });\n return { response };\n}\n\n/** The order in a 2xx answer, or why it is not one. */\nfunction orderOf(body: string, externalOrderId: string, missingStreetNumber: string): FetchOrderResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body) as unknown;\n } catch {\n return { kind: \"retry\", reason: \"iFood answered the order read with a body that is not JSON\" };\n }\n const named = firstString(parsed, [[\"id\"]]);\n if (named !== null && named !== externalOrderId) {\n return { kind: \"refused\", status: 200, message: `iFood answered order ${named} for ${externalOrderId}` };\n }\n const order = readIfoodOrder(parsed, externalOrderId, missingStreetNumber);\n if (!order) return { kind: \"refused\", status: 200, message: \"iFood answered an order with no items\" };\n return { kind: \"order\", order: { ...order, externalMerchantId: firstString(parsed, [[\"merchant\", \"id\"]]) } };\n}\n\n/** What a non-2xx answer means for the fetch. */\nfunction failureOf(response: MarketplaceHttpResponse): Exclude<FetchOrderResult, { kind: \"order\" }> {\n const message = response.body.slice(0, 300);\n if (response.status === 401 || response.status === 403) {\n return { kind: \"refused\", status: response.status, message, own: true };\n }\n if (response.status === 404) return { kind: \"retry\", reason: `status 404: ${message}` };\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: `status ${response.status}` } : result;\n}\n\n/** Fetch one order iFood's event only named. Never throws: no answer is a retry. */\nexport async function ifoodFetchOrder(\n ctx: AdapterCallContext,\n ref: { externalOrderId: string },\n options: { missingStreetNumber: string },\n): Promise<FetchOrderResult> {\n try {\n let answer = await getOrder(ctx, ref.externalOrderId);\n if (\"response\" in answer && answer.response.status === 401) {\n // A token that went stale under us: forget it and try once with a new one.\n ctx.tokens.delete(ifoodTokenKey(ctx));\n answer = await getOrder(ctx, ref.externalOrderId);\n }\n if (!(\"response\" in answer)) return answer;\n const { response } = answer;\n if (response.status >= 200 && response.status < 300) {\n return orderOf(response.body, ref.externalOrderId, options.missingStreetNumber);\n }\n return failureOf(response);\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n","import { outboundResultOf, type MarketplaceHttpRequest } from \"../core/adapter\";\nimport type { LinkCallContext, LinkCode, LinkGrant, LinkResult, LinkedMerchant, MarketplaceLinking } from \"../core/linking-port\";\nimport { asString, pick } from \"../core/payload-read\";\nimport { IFOOD_API } from \"./outbound\";\n\n/**\n * iFood's DISTRIBUTED-APP authentication, the wire format only (FUT-5613).\n * Read 2026-11-26 off iFood's own pages, served as Markdown at\n * https://developer.ifood.com.br/pt-BR/docs/guides/modules/authentication/distributed.md\n * and .../merchant/endpoints.md:\n *\n * - `POST /authentication/v1.0/oauth/userCode`, form `clientId` → 200\n * `{ userCode, authorizationCodeVerifier, verificationUrl,\n * verificationUrlComplete, expiresIn }` (\"valid for 10 minutes\", 600).\n * - `POST /authentication/v1.0/oauth/token`, form `grantType=authorization_code`,\n * `clientId`, `clientSecret`, `authorizationCode`, `authorizationCodeVerifier`\n * → 200 `{ accessToken, type: \"bearer\", expiresIn }` (6 hours by default)\n * and a refresh token (\"returns an access token and a refresh token\").\n * - The same URL, `grantType=refresh_token`, `clientId`, `clientSecret`,\n * `refreshToken`.\n * - `GET /merchant/v1.0/merchants?page=&size=` (size default 100) → 200\n * `[{ id, name, corporateName }]`: every store the token covers.\n *\n * ESTIMATED, not settled by those pages:\n * - the refresh token's FIELD name in the token answer: the page's table\n * lists only `accessToken`, `type`, `expiresIn`; `refreshToken` (the name\n * the request takes) is read, and the snake-case twin as a fallback;\n * - whether a refresh ROTATES the refresh token: a new one is stored when\n * answered, the old one kept when not;\n * - the refresh token's own lifetime (unstated: \"if the refreshToken\n * expires, the user must authorize again\"): a refused refresh marks the\n * connection FAILED for the store to link again;\n * - the status of a wrong or used authorization code: any final 4xx is\n * `refused`.\n */\n\nconst USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;\nconst TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;\nconst MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;\n\n/** iFood's documented lifetime of a user code, used when the answer states none. */\nconst USER_CODE_SECONDS = 600;\n/** iFood's documented default lifetime of an access token: 6 hours. */\nconst ACCESS_TOKEN_SECONDS = 21_600;\n/** One page of the merchant list; iFood's documented default. */\nconst MERCHANT_PAGE_SIZE = 100;\n/** A ceiling on pages read, so a misbehaving answer cannot loop. */\nconst MAX_MERCHANT_PAGES = 20;\n\nconst FORM = { \"Content-Type\": \"application/x-www-form-urlencoded\" };\n\nfunction json(body: string): unknown {\n try {\n return body === \"\" ? null : (JSON.parse(body) as unknown);\n } catch {\n return null;\n }\n}\n\n/** One call whose 2xx body `read` turns into the value; anything else ends it. */\nasync function call<T>(\n ctx: LinkCallContext,\n request: MarketplaceHttpRequest,\n read: (body: unknown) => T | null,\n): Promise<LinkResult<T>> {\n try {\n const response = await ctx.http(request);\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n const value = read(json(response.body));\n return value === null\n ? { kind: \"refused\", status: response.status, message: \"iFood's answer is not the documented shape\" }\n : { kind: \"ok\", value };\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\nconst positive = (value: unknown, fallback: number): number =>\n typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : fallback;\n\nfunction codeOf(body: unknown): LinkCode | null {\n const userCode = asString(pick(body, \"userCode\"));\n const verifier = asString(pick(body, \"authorizationCodeVerifier\"));\n const verificationUrl = asString(pick(body, \"verificationUrl\"));\n if (!userCode || !verifier || !verificationUrl) return null;\n return {\n userCode,\n verifier,\n verificationUrl,\n verificationUrlComplete: asString(pick(body, \"verificationUrlComplete\")) ?? verificationUrl,\n expiresInSeconds: positive(pick(body, \"expiresIn\"), USER_CODE_SECONDS),\n };\n}\n\nfunction grantOf(body: unknown, requireRefresh: boolean): LinkGrant | null {\n const accessToken = asString(pick(body, \"accessToken\"));\n const refreshToken = asString(pick(body, \"refreshToken\")) ?? asString(pick(body, \"refresh_token\"));\n if (!accessToken || (requireRefresh && !refreshToken)) return null;\n return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, \"expiresIn\"), ACCESS_TOKEN_SECONDS) };\n}\n\nfunction merchantsOf(body: unknown): LinkedMerchant[] | null {\n if (!Array.isArray(body)) return null;\n return body.flatMap((raw: unknown) => {\n const id = asString(pick(raw, \"id\"));\n return id ? [{ id, name: asString(pick(raw, \"name\")), corporateName: asString(pick(raw, \"corporateName\")) }] : [];\n });\n}\n\nconst tokenRequest = (fields: Record<string, string>): MarketplaceHttpRequest => ({\n method: \"POST\",\n url: TOKEN_URL,\n headers: FORM,\n body: new URLSearchParams(fields).toString(),\n});\n\n/** Every merchant the token covers, page by page until a short page. */\nasync function listMerchants(ctx: LinkCallContext, accessToken: string): Promise<LinkResult<LinkedMerchant[]>> {\n const all: LinkedMerchant[] = [];\n for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {\n const answer = await call(\n ctx,\n {\n method: \"GET\",\n url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,\n headers: { Authorization: `Bearer ${accessToken}` },\n },\n merchantsOf,\n );\n if (answer.kind !== \"ok\") return answer;\n all.push(...answer.value);\n if (answer.value.length < MERCHANT_PAGE_SIZE) break;\n }\n return { kind: \"ok\", value: all };\n}\n\n/** The iFood adapter's linking half. */\nexport const IFOOD_LINKING: MarketplaceLinking = {\n requestCode: (ctx) =>\n call(\n ctx,\n { method: \"POST\", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },\n codeOf,\n ),\n exchange: (ctx, input) =>\n call(\n ctx,\n tokenRequest({\n grantType: \"authorization_code\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n authorizationCode: input.authorizationCode,\n authorizationCodeVerifier: input.verifier,\n }),\n (body) => grantOf(body, true),\n ),\n refresh: (ctx, input) =>\n call(\n ctx,\n tokenRequest({\n grantType: \"refresh_token\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n refreshToken: input.refreshToken,\n }),\n (body) => grantOf(body, false),\n ),\n merchants: (ctx, input) => listMerchants(ctx, input.accessToken),\n};\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type MarketplaceHttpRequest,\n type MarketplaceHttpResponse,\n type OutboundResult,\n} from \"../core/adapter\";\nimport type { MarketplaceAvailability, StorePauseRef, StorePauseRequest, StorePauseResult } from \"../core/pause-port\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * iFood's half of the store pause (FUT-4851): the Merchant API's\n * INTERRUPTIONS, a closure with its own id, a start and an end, that does not\n * touch the store's opening hours.\n *\n * - List: `GET /merchant/v1.0/merchants/{merchantId}/interruptions`\n * (active and future interruptions).\n * - Create: `POST …/interruptions` with `{ id, description, start, end }`,\n * 201 with the interruption.\n * - Delete: `DELETE …/interruptions/{interruptionId}`, 204.\n *\n * iFood's developer portal refuses our reader (403), so the paths, verbs and\n * the body's `description`/`start`/`end` come from two public third-party\n * clients of the API (README, \"Pausing a store\"): ESTIMATED until the\n * homologation run. Also ESTIMATED: that iFood takes the client's own `id`.\n * It is sent, but the adapter does not rely on it: every create is preceded\n * by a list, and an interruption is ours when it carries our id OR, where\n * iFood assigned its own, exactly the end and the description the create\n * sent, so a retry after a lost answer never makes a second one and a resume\n * by key deletes the one that landed. An interruption the owner made by hand\n * is neither. ESTIMATED too: that there is no call to move an interruption's\n * end (so no `extend`: the engine creates the new one, then deletes the old);\n * that iFood ACCEPTS the two overlapping for that moment (if it refuses an\n * overlap, the renewal is FAILED with iFood's words and the old interruption\n * still holds to its own end); and how iFood reads a\n * time: one client says the offset is discarded and the time read as the\n * store's own clock, so the time goes out as the store's wall clock WITH its\n * offset, which reads the same either way. A 404 on delete is \"already gone\".\n */\n\nconst interruptionsUrl = (merchantId: string): string =>\n `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`;\n\ntype Settled = Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** One authenticated call: the raw answer, or the result that ends it. */\nasync function call(\n ctx: AdapterCallContext,\n request: Omit<MarketplaceHttpRequest, \"headers\"> & { json?: unknown },\n): Promise<MarketplaceHttpResponse | Settled> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : auth;\n const response = await ctx.http({\n method: request.method,\n url: request.url,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.json === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.json === undefined ? {} : { body: JSON.stringify(request.json) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n return { kind: \"retry\", reason: \"iFood refused the token\" };\n}\n\nconst settled = (value: MarketplaceHttpResponse | Settled): value is Settled => \"kind\" in value;\n\n/** The answer as anything but 2xx, read the engine's way. */\nfunction notOk(response: MarketplaceHttpResponse): Settled | null {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? null : result;\n}\n\n/** One interruption as the list answers it, read defensively. */\ninterface Interruption {\n id: string;\n end: string | null;\n description: string | null;\n}\n\n/** The interruptions on the merchant, or the result that ends the call. */\nasync function listInterruptions(ctx: AdapterCallContext, merchantId: string): Promise<Interruption[] | Settled> {\n const response = await call(ctx, { method: \"GET\", url: interruptionsUrl(merchantId) });\n if (settled(response)) return response;\n const failure = notOk(response);\n if (failure) return failure;\n try {\n const parsed = JSON.parse(response.body === \"\" ? \"[]\" : response.body) as unknown;\n if (!Array.isArray(parsed)) return [];\n return parsed.flatMap((entry: unknown) => {\n const value = (entry ?? {}) as { id?: unknown; end?: unknown; description?: unknown };\n if (typeof value.id !== \"string\") return [];\n return [\n {\n id: value.id,\n end: typeof value.end === \"string\" ? value.end : null,\n description: typeof value.description === \"string\" ? value.description : null,\n },\n ];\n });\n } catch {\n return { kind: \"retry\", reason: \"iFood answered the interruption list with something that is not JSON\" };\n }\n}\n\n/**\n * Whether iFood's `end` is the instant the create sent. An `end` that states\n * its zone (`Z` or an offset) is compared as an instant, and only as one: an\n * owner's interruption at another instant is never claimed because its digits\n * look like ours. Only an `end` with no zone (iFood echoing the store's own\n * clock) is compared as the store's wall clock.\n */\nfunction sameEnd(end: string, until: Date, timeZone: string): boolean {\n const sent = ifoodLocalTime(until, timeZone);\n if (end === sent) return true;\n if (/(?:[zZ]|[+-]\\d{2}:?\\d{2})$/u.test(end)) {\n const parsed = Date.parse(end);\n return !Number.isNaN(parsed) && Math.floor(parsed / 1000) === Math.floor(until.getTime() / 1000);\n }\n return end.slice(0, 19) === sent.slice(0, 19);\n}\n\n/**\n * The interruption the create under `key` made: by our id, or by the end and\n * description it carried, never one the engine already holds (`keep`).\n */\nfunction ours(\n list: readonly Interruption[],\n key: string,\n sent: { until: Date; reason: string; timeZone: string } | null,\n keep: readonly string[] = [],\n): Interruption | undefined {\n const candidates = list.filter((entry) => !keep.includes(entry.id));\n const byKey = candidates.find((entry) => entry.id === key);\n if (byKey || !sent) return byKey;\n return candidates.find(\n (entry) => entry.description === sent.reason && entry.end !== null && sameEnd(entry.end, sent.until, sent.timeZone),\n );\n}\n\ninterface WallClock {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n}\n\n/** The wall clock of `date` in `timeZone`. */\nfunction wallClock(date: Date, timeZone: string): WallClock {\n const format = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n });\n const clock: WallClock = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };\n for (const part of format.formatToParts(date)) {\n if (part.type in clock) clock[part.type as keyof WallClock] = Number(part.value);\n }\n return clock;\n}\n\nconst pad = (value: number, width = 2): string => String(value).padStart(width, \"0\");\n\n/**\n * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.\n * Read the same whether iFood honours the offset or reads the store's clock.\n */\nexport function ifoodLocalTime(date: Date, timeZone: string): string {\n const local = wallClock(date, timeZone);\n const asUtc = Date.UTC(local.year, local.month - 1, local.day, local.hour, local.minute, local.second);\n const offset = Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60_000);\n const abs = Math.abs(offset);\n return (\n `${pad(local.year, 4)}-${pad(local.month)}-${pad(local.day)}` +\n `T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}` +\n `${offset < 0 ? \"-\" : \"+\"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`\n );\n}\n\n/** The created interruption's id: iFood's answer, else the one the engine sent. */\nfunction createdId(body: string, sent: string): string {\n try {\n const id = (JSON.parse(body) as { id?: unknown }).id;\n return typeof id === \"string\" && id !== \"\" ? id : sent;\n } catch {\n return sent;\n }\n}\n\n/** Close the store until `request.until`: find one a lost answer created under the key, else create it. */\nexport function ifoodPause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> {\n return answeredPause(async () => {\n const list = await listInterruptions(ctx, request.merchantId);\n if (!Array.isArray(list)) return list;\n const landed = ours(list, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);\n if (landed) return { kind: \"paused\", externalId: landed.id, until: request.until };\n const response = await call(ctx, {\n method: \"POST\",\n url: interruptionsUrl(request.merchantId),\n json: {\n id: request.key,\n description: request.reason,\n start: ifoodLocalTime(ctx.now, request.timeZone),\n end: ifoodLocalTime(request.until, request.timeZone),\n },\n });\n if (settled(response)) return response;\n const failure = notOk(response);\n if (failure) return failure;\n return { kind: \"paused\", externalId: createdId(response.body, request.key), until: request.until };\n });\n}\n\n/** Delete THIS interruption: by its id, or the one a lost answer created under the key (by id, or by its end and description). */\nexport function ifoodResume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult> {\n return answered(async () => {\n let id = ref.externalId;\n if (id === null && ref.key !== null) {\n const list = await listInterruptions(ctx, ref.merchantId);\n if (!Array.isArray(list)) return list;\n id = ours(list, ref.key, ref.sent, ref.keep)?.id ?? null;\n }\n // Nothing of ours stands: there is nothing to delete.\n if (id === null) return { kind: \"accepted\" };\n const response = await call(ctx, { method: \"DELETE\", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });\n if (settled(response)) return response;\n // Already gone: it ended, or a person removed it.\n if (response.status === 404) return { kind: \"accepted\" };\n return outboundResultOf(response);\n });\n}\n\n/** {@link answered} for a pause: a call that never got an answer is a retry. */\nasync function answeredPause(run: () => Promise<StorePauseResult>): Promise<StorePauseResult> {\n try {\n return await run();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** iFood's availability capability: interruptions, no extend. */\nexport const IFOOD_AVAILABILITY: MarketplaceAvailability = {\n kind: \"interruption\",\n pause: ifoodPause,\n resume: ifoodResume,\n};\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nimport { IFOOD_CATALOGUE } from \"./catalogue\";\nimport { IFOOD_CATALOGUE_READER } from \"./catalogue-read\";\nimport { IFOOD_COURIER } from \"./courier\";\nimport { ifoodFetchOrder } from \"./fetch-order\";\nimport { IFOOD_LINKING } from \"./linking\";\nimport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\nimport { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from \"./outbound\";\nimport { IFOOD_AVAILABILITY } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.\n *\n * The owner's rule: adapters live inside the lib, one per subpath, and no\n * provider-specific branch exists anywhere outside an adapter and its\n * registration. Everything iFood is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port.\n *\n * ```ts\n * import { createIfoodAdapter } from \"@12-apps/marketplace/ifood\";\n * import { IFOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/ifood/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })] });\n * ```\n */\n\n/** The provider id iFood is registered under. */\nexport const IFOOD_PROVIDER = \"IFOOD\";\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: IfoodReasonCode = \"503\";\n\n/** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */\nexport const IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\nexport interface IfoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: IfoodAdapterCopy;\n}\n\n/** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */\nexport function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {\n const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: IFOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n cancelAfterAccept: true,\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n confirmTakesPreparationTime: false,\n // How long iFood takes, at most, to answer a cancellation request: its\n // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off\n // iFood's documentation, which names no answer deadline: iFood answers a\n // request in seconds when it answers at all, so 5 minutes is generous.\n // A host overrides it with the engine's `cancellationWindowMs`.\n cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,\n // Told what iFood has an endpoint for (ESTIMATED, see `./outbound.ts`): ready for\n // pickup, and dispatched for a merchant bag. Never \"handed over\": iFood's own\n // CONCLUDED is that.\n statusSteps: [\"READY\", \"DISPATCHED\"],\n },\n normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),\n readSignature: (header) => header(\"x-ifood-signature\") ?? header(\"x-signature\"),\n verifySignature: verifyIfoodSignature,\n cancellationReasons: () => reasons,\n // The Catalog API v2.0: each item is written and paused through the API (FUT-4768).\n catalogue: IFOOD_CATALOGUE,\n // The same API read back: the menu the store keeps on iFood, for the host to import (FUT-951).\n catalogueReader: IFOOD_CATALOGUE_READER,\n confirm: (ctx, order) => ifoodConfirm(ctx, order),\n requestCancellation: ifoodRequestCancellation,\n // iFood's events carry only the order id: a PLACED with no items is fetched (FUT-5800).\n fetchOrder: (ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions),\n statusSupported: ifoodStatusSupported,\n informStatus: ifoodInformStatus,\n // The Merchant API's interruptions: an id and an end per closure (FUT-4851).\n availability: IFOOD_AVAILABILITY,\n // The distributed-app authorization: a store links the software's own app (FUT-5613).\n linking: IFOOD_LINKING,\n // iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).\n courier: IFOOD_COURIER,\n // No per-order deep link is known, so the portal, where a live order is\n // on the first screen.\n appLink: () => IFOOD_PORTAL_URL,\n };\n}\n\nexport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nexport { normalizeIfoodEvent, readIfoodOrder, verifyIfoodSignature } from \"./normalize\";\nexport { ifoodFetchOrder } from \"./fetch-order\";\nexport { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from \"./catalogue\";\nexport { IFOOD_CATALOGUE_READER } from \"./catalogue-read\";\nexport { IFOOD_LINKING } from \"./linking\";\nexport { IFOOD_COURIER, readIfoodCourierEvent } from \"./courier\";\nexport { IFOOD_IMAGE_BASE_URL } from \"./catalogue-snapshot\";\nexport { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACDO,IAAM,YAAY;AACzB,IAAM,YAAY,GAAG,SAAS;AAC9B,IAAM,WAAW,wBAAC,iBAAyB,WACzC,GAAG,SAAS,sBAAsB,mBAAmB,eAAe,CAAC,IAAI,MAAM,IADhE;AAQV,IAAM,mBAAmB;AAGhC,IAAM,kBAAkB;AAOjB,IAAM,gBAAgB,wBAAC,QAC5B,IAAI,QAAQ,IAAI,MAAM,MAAM,SAAS,I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AAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA;AAAA,IAErB,WAAW;AAAA;AAAA,IAEX,iBAAiB;AAAA,IACjB,SAAS,wBAAC,KAAK,UAAU,aAAa,KAAK,KAAK,GAAvC;AAAA,IACT,qBAAqB;AAAA;AAAA,IAErB,YAAY,wBAAC,KAAK,UAAU,gBAAgB,KAAK,OAAO,gBAAgB,GAA5D;AAAA,IACZ,iBAAiB;AAAA,IACjB,cAAc;AAAA;AAAA,IAEd,cAAc;AAAA;AAAA,IAEd,SAAS;AAAA;AAAA,IAET,SAAS;AAAA;AAAA;AAAA,IAGT,SAAS,6BAAM,kBAAN;AAAA,EACX;AACF;AApDgB;","names":["parsed","parsed","categoryId","catalogUrl","failureOf","ok","parse","answered","categoryId","parsed","orderUrl","call","read","parsed","failureOf","TOKEN_URL","call","read","call","parsed","list"]}
1
+ {"version":3,"sources":["../../src/ifood/copy.ts","../../src/ifood/outbound.ts","../../src/ifood/catalogue.ts","../../src/ifood/catalogue-snapshot.ts","../../src/ifood/catalogue-read.ts","../../src/ifood/courier.ts","../../src/ifood/order-details.ts","../../src/ifood/normalize.ts","../../src/ifood/fetch-order.ts","../../src/ifood/linking.ts","../../src/ifood/pause.ts","../../src/ifood/index.ts"],"sourcesContent":["/**\n * The words the iFood adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * iFood's documented cancellation reason codes. UNVERIFIED: read from the\n * merchant portal's search snippets (2026-11-11), not from a page we could\n * read whole; the homologation run against iFood's sandbox corrects them here.\n */\nexport const IFOOD_REASON_CODES = [\n \"501\",\n \"502\",\n \"503\",\n \"504\",\n \"505\",\n \"506\",\n \"507\",\n \"508\",\n \"509\",\n \"511\",\n \"512\",\n \"513\",\n] as const;\n\nexport type IfoodReasonCode = (typeof IFOOD_REASON_CODES)[number];\n\nexport interface IfoodAdapterCopy {\n /** One label per reason code. Sent to iFood as the reason text when the store wrote none. */\n reasonLabels: Readonly<Record<IfoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import {\n answered,\n outboundResultOf,\n tokenGrantResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type MarketplaceAcknowledgement,\n type MarketplaceHttpResponse,\n type OrderCancellationReason,\n type OrderCancellationReasonsResult,\n type OutboundOrderRef,\n type OutboundResult,\n type StatusFacts,\n type StatusStep,\n} from \"../core/adapter\";\n\n/**\n * The iFood adapter's OUTBOUND half: auth, URLs and payload shapes. Everything\n * here is iFood's wire format and nothing else — the job that calls it, its\n * retries and what a failure shows are the engine's (`../core/outbound.ts`).\n *\n * UNVERIFIED. iFood's developer portal refused our reader, so every URL, body\n * field below (and the reason codes in `./copy.ts`) comes from the portal's search snippets\n * (2026-11-11), not from a page we could read whole. They are in THIS file and\n * nowhere else so that the homologation run against iFood's sandbox, once\n * homologation credentials exist, corrects one file. Tests never reach\n * iFood: the HTTP client is the host's port, answered by a fake.\n */\n\n/** iFood's merchant API. Sandbox and production share the host; the credentials differ. */\nexport const IFOOD_API = \"https://merchant-api.ifood.com.br\";\nconst TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;\nconst orderUrl = (externalOrderId: string, action: string): string =>\n `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;\n\n/**\n * iFood's order-manager portal. No per-order deep link was found in the\n * snippets, so the app link opens the portal, where the order is on the\n * first screen while it is live.\n */\nexport const IFOOD_PORTAL_URL = \"https://portal.ifood.com.br/\";\n\n/**\n * The token cache key: per environment and merchant app, or, for a store\n * linked through the software's app (FUT-5613), the store's own grant key, so\n * deleting it after a 401 forgets that store's token and nobody else's.\n */\nexport const ifoodTokenKey = (ctx: AdapterCallContext): string =>\n ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** iFood's OAuth answer, read defensively: a missing field is \"no token\". */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { accessToken?: unknown; expiresIn?: unknown };\n if (typeof parsed.accessToken !== \"string\" || parsed.accessToken === \"\") return null;\n const expires = typeof parsed.expiresIn === \"number\" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;\n return { token: parsed.accessToken, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token for this merchant app, from the per-process cache or a fresh\n * client-credentials grant (or, linked, the store's grant). Keyed by the app's client id, so two stores with\n * two apps never share one. The token lives in memory only.\n */\nexport async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {\n // A linked store: its refresh token buys the token, never a client-credentials grant.\n if (ctx.grant) return ctx.grant.accessToken();\n const key = ifoodTokenKey(ctx);\n const cached = ctx.tokens.get(key);\n // Renewed only once expired, never early: \"Renove tokens de autenticação apenas quando expirados,\n // não antecipadamente\" (iFood's Order homologation criteria, FUT-5984). A 401 renews it sooner.\n if (cached && cached.expiresAt > ctx.now.getTime()) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: TOKEN_URL,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grantType: \"client_credentials\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) return tokenGrantResultOf(response);\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"iFood answered the token grant without a token\" };\n ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/**\n * One authenticated call, its token renewed once on a 401: the token is\n * forgotten, a new one bought and the call made again, inside the same call\n * (iFood: \"Prepare seu aplicativo para solicitar um novo token quando receber\n * status 401\"). A second 401 forgets that one too and answers `null`.\n */\nasync function withIfoodToken(\n ctx: AdapterCallContext,\n call: (token: string) => Promise<MarketplaceHttpResponse>,\n): Promise<MarketplaceHttpResponse | OutboundResult | null> {\n for (let round = 0; round < 2; round += 1) {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth;\n const response = await call(auth.token);\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n }\n return null;\n}\n\n/** One authenticated request to an order's resource. */\nfunction callOrder(\n ctx: AdapterCallContext,\n externalOrderId: string,\n action: string,\n body?: unknown,\n method: \"POST\" | \"GET\" = \"POST\",\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await withIfoodToken(ctx, (token) =>\n ctx.http({\n method,\n url: orderUrl(externalOrderId, action),\n headers: {\n Authorization: `Bearer ${token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n }),\n );\n if (response === null) return { kind: \"retry\", reason: \"iFood refused the token\" };\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n\n/** One authenticated POST to an order's resource. */\nfunction postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {\n return callOrder(ctx, externalOrderId, action, body);\n}\n\n/** Tell iFood the store accepted the order. No body: the URL names the order. */\nexport function ifoodConfirm(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"confirm\");\n}\n\n/** Ask iFood to cancel the order with one of its reason codes. */\nexport function ifoodRequestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n // The body is the code alone (`cancellation.md`: `-d '{\"reason\": \"503\"}'`), one of the order's own\n // `cancellationReasons` (FUT-5984); iFood takes no free text with it.\n return postOrder(ctx, order.externalOrderId, \"requestCancellation\", { reason: input.reason.code });\n}\n\n/** iFood's reasons for this order, read live (FUT-5984): `{ reasons: [{ code, description }] }`, or a bare array. */\nfunction reasonsOf(body: string): OrderCancellationReason[] | null {\n try {\n const parsed = JSON.parse(body) as unknown;\n const list = Array.isArray(parsed) ? parsed : (parsed as { reasons?: unknown } | null)?.reasons;\n if (!Array.isArray(list)) return null;\n return list.flatMap((entry: unknown) => {\n const { code, description } = (entry ?? {}) as { code?: unknown; description?: unknown };\n if (typeof code !== \"string\" && typeof code !== \"number\") return [];\n return [{ code: String(code), description: typeof description === \"string\" ? description : String(code) }];\n });\n } catch {\n return null;\n }\n}\n\n/** `GET /order/v1.0/orders/{id}/cancellationReasons`: the codes iFood accepts for cancelling this order now. */\nexport async function ifoodOrderCancellationReasons(\n ctx: AdapterCallContext,\n order: { externalOrderId: string },\n): Promise<OrderCancellationReasonsResult> {\n let body = \"\";\n const result = await answered(async () => {\n const response = await withIfoodToken(ctx, (token) =>\n ctx.http({ method: \"GET\", url: orderUrl(order.externalOrderId, \"cancellationReasons\"), headers: { Authorization: `Bearer ${token}` } }),\n );\n if (response === null) return { kind: \"retry\", reason: \"iFood refused the token\" };\n if (\"kind\" in response) return response;\n body = response.body;\n return outboundResultOf(response);\n });\n if (result.kind !== \"accepted\") return result;\n const reasons = reasonsOf(body);\n return reasons ? { kind: \"reasons\", reasons } : { kind: \"retry\", reason: \"iFood answered the reasons with no list\" };\n}\n\n/** iFood keeps an event 8 hours (`polling-overview`: \"até 8 horas\"); an older one is never acknowledged. */\nconst IFOOD_EVENT_RETENTION_MS = 8 * 60 * 60_000;\n\n/**\n * Acknowledge recorded events (FUT-5984): `POST /events/v1.0/events/acknowledgment`\n * with `[{ id }]`, at most 2000 ids a call (\"Limite: até 2000 IDs por requisição\").\n */\nexport const IFOOD_ACKNOWLEDGEMENT: MarketplaceAcknowledgement = {\n batchSize: 2000,\n retentionMs: IFOOD_EVENT_RETENTION_MS,\n send: (ctx, eventIds) =>\n answered(async () => {\n const body = JSON.stringify(eventIds.map((id) => ({ id })));\n const response = await withIfoodToken(ctx, (token) =>\n ctx.http({\n method: \"POST\",\n url: `${IFOOD_API}/events/v1.0/events/acknowledgment`,\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n body,\n }),\n );\n if (response === null) return { kind: \"retry\", reason: \"iFood refused the token\" };\n return \"kind\" in response ? response : outboundResultOf(response);\n }),\n};\n\n/**\n * What iFood is told, per step (FUT-4653). ESTIMATED, every row: iFood's\n * developer portal answered 403 behind Cloudflare to our reader\n * (https://developer.ifood.com.br, 2026-11-25), so the endpoint names below are\n * the Merchant API's commonly documented ones (`order/v1.0`), not read off a\n * page.\n *\n * - READY: `POST /orders/{id}/readyToPickup`, for every order: CONFIRMED for\n * the merchant's own bag by the Order Endpoints page (read 2026-12-02), which\n * wants it before the dispatch. The homologation page spells it PUT; the\n * Endpoints page's POST is kept.\n * - DISPATCHED: `POST /orders/{id}/dispatch`, only for `deliveredBy: MERCHANT`,\n * strictly after READY ({@link ifoodStatusPrerequisite}).\n * - HANDED_OVER: none. iFood has no conclude endpoint for a merchant;\n * CONCLUDED is iFood's own event.\n */\nconst STATUS_ACTION: Readonly<Record<string, (facts: StatusFacts) => string | null>> = {\n // Every order, the merchant's own bag included (FUT-5984, `endpoints.md`: \"Para entrega própria,\n // notifique o pedido pronto via `POST /orders/{id}/readyToPickup` antes de despachar via `/dispatch`\").\n READY: () => \"readyToPickup\",\n DISPATCHED: (facts) => (facts.deliveredBy === \"MERCHANT\" ? \"dispatch\" : null),\n};\n\n/** A merchant bag's dispatch goes strictly after its `readyToPickup` (FUT-5984). */\nexport function ifoodStatusPrerequisite(facts: StatusFacts): StatusStep | null {\n return facts.step === \"DISPATCHED\" && facts.deliveredBy === \"MERCHANT\" ? \"READY\" : null;\n}\n\n/** Whether iFood takes this step for this kind of order: answered offline. */\nexport function ifoodStatusSupported(facts: StatusFacts): boolean {\n return STATUS_ACTION[facts.step]?.(facts) != null;\n}\n\n/** Tell iFood a step happened. `unsupported` when it has no endpoint for it. */\nexport async function ifoodInformStatus(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n): Promise<OutboundResult | { kind: \"unsupported\" }> {\n const action = STATUS_ACTION[facts.step]?.(facts) ?? null;\n return action === null ? { kind: \"unsupported\" } : postOrder(ctx, order.externalOrderId, action);\n}\n","import {\n answered,\n outboundResultOf,\n type MarketplaceHttpResponse,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type {\n CatalogueCallContext,\n CatalogueImage,\n CatalogueItemOut,\n CatalogueItemRef,\n CataloguePublishResult,\n CatalogueStoredImage,\n CatalogueWarningCode,\n PushCatalogue,\n} from \"../core/catalogue-port\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * The iFood adapter's CATALOGUE half: iFood's Catalog API v2.0, push (FUT-4768).\n *\n * Read 2026-11-13 from iFood's developer portal (the Catalog module's\n * Introduction, Fundamentals, Endpoints and Errors pages, and the rate-limit\n * page); the package README's \"Catalogue publishing\" table marks each fact\n * CONFIRMED with its URL or ESTIMATED. What is ESTIMATED here is said beside\n * it, and lives in this file only, so the homologation run corrects one file.\n *\n * One publish is, in order:\n * 1. the category, by name: `GET /categories`, else `POST /categories`\n * (`template: \"DEFAULT\"`);\n * 2. the photo, when the item has one: the `imagePath` iFood already holds\n * for the same photo URL, else `POST /image/upload` with a base64 data URL\n * of the bytes the host's loader reads, which answers `imagePath`;\n * 3. the item: `PUT /items` with `item`, `products`, `optionGroups`,\n * `options` — idempotent, it replaces the whole item, and the item appears\n * at once (synchronous).\n *\n * iFood wants item and product ids the software generates, UUID v4 (any other\n * shape answers 404), so they are derived from the engine's publication\n * reference: a retried publish names the same item. The item's `externalCode`\n * is the host's product id (unique per merchant).\n *\n * A withdraw pauses the item, `PATCH /items/status` with `UNAVAILABLE`: the\n * Endpoints page lists no item delete, and a paused item is not shown in the\n * app (ESTIMATED that this is what \"off\" should mean; a re-publish puts it\n * back AVAILABLE with the same id).\n */\n\nconst catalogUrl = (merchantId: string, path: string): string =>\n `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;\n\n/** The item's and its product's ids, stable per publication. */\nexport const ifoodItemId = (ref: string): string => stableUuid(`${ref}:item`);\nexport const ifoodProductId = (ref: string): string => stableUuid(`${ref}:product`);\n\ntype Failure = Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** iFood's price object: a decimal of the currency's major unit. */\nconst priceOf = (cents: number): { value: number } => ({ value: Math.round(cents) / 100 });\n\n/** One authenticated call to the catalogue: the raw answer, or the failure that ends it. */\nasync function call(\n ctx: CatalogueCallContext,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\",\n path: string,\n body?: unknown,\n): Promise<MarketplaceHttpResponse | Failure> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : auth;\n const response = await ctx.http({\n method,\n url: catalogUrl(ctx.externalMerchantId, path),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n return { kind: \"retry\", reason: \"iFood refused the token\" };\n}\n\n/** A non-2xx answer as the failure it is (never `accepted`). */\nfunction failureOf(response: MarketplaceHttpResponse): Failure {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected answer\" } : result;\n}\n\nconst ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;\n\nfunction parse(body: string): unknown {\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return null;\n }\n}\n\n/** The id of the category named `name`, from a category list. ESTIMATED: the list answers an array of `{ id, name }`. */\nfunction categoryIdIn(body: string, name: string): string | null {\n const parsed = parse(body);\n if (!Array.isArray(parsed)) return null;\n const wanted = name.trim().toLowerCase();\n const found = parsed.find(\n (entry: unknown) =>\n typeof entry === \"object\" && entry !== null && String((entry as { name?: unknown }).name ?? \"\").trim().toLowerCase() === wanted,\n ) as { id?: unknown } | undefined;\n return typeof found?.id === \"string\" ? found.id : null;\n}\n\n/** The category named `name` on iFood, or null; the failure that ended the read otherwise. */\nasync function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {\n const listed = await call(ctx, \"GET\", \"categories\");\n if (\"kind\" in listed) return listed;\n if (!ok(listed)) return failureOf(listed);\n return { id: categoryIdIn(listed.body, name) };\n}\n\n/**\n * Find the category by name, else create it, then read the list again and\n * adopt the first of that name: a POST whose answer was lost and was retried\n * is found rather than created twice. The engine runs this once per\n * (connection, name) at a time and stores the id (`ctx.category`).\n */\nasync function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {\n const found = await findCategory(ctx, name);\n if (\"kind\" in found) return found;\n if (found.id) return { id: found.id };\n const created = await call(ctx, \"POST\", \"categories\", { name, status: \"AVAILABLE\", template: \"DEFAULT\" });\n if (\"kind\" in created) return created;\n if (!ok(created)) return failureOf(created);\n const id = (parse(created.body) as { id?: unknown } | null)?.id;\n if (typeof id !== \"string\") return { kind: \"retry\", reason: \"iFood created the category without an id\" };\n // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.\n const again = await findCategory(ctx, name);\n return \"id\" in again && again.id ? { id: again.id } : { id };\n}\n\nconst categoryId = (ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> =>\n ctx.category(name, () => findOrCreateCategory(ctx, name));\n\n/** The photo the item goes out with, and what the publish could not do about it. */\ninterface PhotoOutcome {\n image: CatalogueStoredImage | null;\n warning?: CatalogueWarningCode;\n}\n\n/**\n * The photo for this publish, uploading only when it must:\n * - no `imageUrl`: no photo;\n * - the photo iFood already holds was made from this same URL: reuse it;\n * - else upload the bytes the host's loader reads; when it reads nothing,\n * keep the photo iFood holds, if any (PUT replaces the whole item, so\n * sending none would drop it);\n * - an upload iFood refuses (413 over 5 MB, another final 4xx) publishes\n * without a photo and says why as a warning, rather than failing the item.\n */\nasync function photoFor(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<PhotoOutcome | Failure> {\n const stored = item.storedImage;\n if (item.imageUrl === null) return { image: null };\n if (stored && stored.sourceUrl === item.imageUrl) return { image: stored };\n const bytes = await ctx.loadImage(item.imageUrl);\n return bytes ? upload(ctx, bytes, item.imageUrl) : { image: stored };\n}\n\n/** `POST /image/upload`: the new photo, a warning for a refused one, or the failure to retry. */\nasync function upload(ctx: CatalogueCallContext, bytes: CatalogueImage, sourceUrl: string): Promise<PhotoOutcome | Failure> {\n const uploaded = await call(ctx, \"POST\", \"image/upload\", { image: `data:${bytes.contentType};base64,${bytes.base64}` });\n if (\"kind\" in uploaded) return uploaded;\n if (!ok(uploaded)) {\n const failure = failureOf(uploaded);\n if (failure.kind === \"retry\") return failure;\n return { image: null, warning: uploaded.status === 413 ? \"IMAGE_TOO_LARGE\" : \"IMAGE_REFUSED\" };\n }\n const path = (parse(uploaded.body) as { imagePath?: unknown } | null)?.imagePath;\n if (typeof path !== \"string\") return { kind: \"retry\", reason: \"iFood answered the upload without an imagePath\" };\n return { image: { ref: path, sourceUrl } };\n}\n\n/** The `PUT /items` body for one simple item with no add-ons. */\nexport function ifoodItemBody(item: CatalogueItemOut, category: string, image: string | null): unknown {\n const itemId = ifoodItemId(item.ref);\n const productId = ifoodProductId(item.ref);\n return {\n item: {\n id: itemId,\n type: \"DEFAULT\",\n categoryId: category,\n status: \"AVAILABLE\",\n price: priceOf(item.priceCents),\n externalCode: item.productId,\n // ESTIMATED: the guide's examples link item and product implicitly; the\n // field naming the product is not shown on the pages read.\n productId,\n },\n products: [\n {\n id: productId,\n name: item.name,\n description: item.description ?? \"\",\n externalCode: `${item.productId}-product`,\n // ESTIMATED field name: the Errors page names `imagePath` as what the upload returns and the item carries.\n ...(image === null ? {} : { imagePath: image }),\n },\n ],\n optionGroups: [],\n options: [],\n };\n}\n\n/**\n * Whether a refused PUT was refused because the stored category is gone (the\n * store deleted it on iFood's portal): iFood's 400 and 404 do not say which id\n * was unknown, so the list is read again, and a category of that name with\n * another id, or none at all, means the stored one is stale. ESTIMATED that a\n * deleted category answers 400 or 404.\n */\nasync function categoryWentStale(ctx: CatalogueCallContext, put: MarketplaceHttpResponse, name: string, used: string): Promise<boolean> {\n if (put.status !== 400 && put.status !== 404) return false;\n const found = await findCategory(ctx, name);\n return !(\"kind\" in found) && found.id !== used;\n}\n\n/** `PUT /items`, once more with the category found or created again when the stored one went stale. */\nasync function putItem(ctx: CatalogueCallContext, item: CatalogueItemOut, image: string | null): Promise<MarketplaceHttpResponse | Failure> {\n const category = await categoryId(ctx, item.categoryName);\n if (\"kind\" in category) return category;\n const put = await call(ctx, \"PUT\", \"items\", ifoodItemBody(item, category.id, image));\n if (\"kind\" in put || ok(put) || !(await categoryWentStale(ctx, put, item.categoryName, category.id))) return put;\n await ctx.forgetCategory(item.categoryName);\n const again = await categoryId(ctx, item.categoryName);\n if (\"kind\" in again) return again;\n return call(ctx, \"PUT\", \"items\", ifoodItemBody(item, again.id, image));\n}\n\nasync function publish(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult> {\n const photo = await photoFor(ctx, item);\n if (\"kind\" in photo) return photo;\n const put = await putItem(ctx, item, photo.image?.ref ?? null);\n if (\"kind\" in put) return put;\n if (!ok(put)) return failureOf(put);\n // iFood's orders carry the item's `externalCode` as the line's SKU (the order normalizer reads it).\n const published = { kind: \"published\" as const, externalId: ifoodItemId(item.ref), sku: item.productId, image: photo.image };\n return photo.warning ? { ...published, warning: photo.warning } : published;\n}\n\nasync function withdraw(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult> {\n const itemId = item.externalId ?? ifoodItemId(item.ref);\n const patched = await call(ctx, \"PATCH\", \"items/status\", { itemId, status: \"UNAVAILABLE\" });\n if (\"kind\" in patched) return patched;\n // ESTIMATED: a 404 means iFood does not have the item, so it is already out\n // of its catalogue (the Errors page says 404 is \"the resource does not exist\").\n if (patched.status === 404) return { kind: \"accepted\" };\n return outboundResultOf(patched);\n}\n\n/** A call that never got an answer is a retry. */\nasync function publishedOrRetry(run: () => Promise<CataloguePublishResult>): Promise<CataloguePublishResult> {\n try {\n return await run();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** iFood's catalogue capability. */\nexport const IFOOD_CATALOGUE: PushCatalogue = {\n mode: \"push\",\n publishItem: (ctx, item) => publishedOrRetry(() => publish(ctx, item)),\n withdrawItem: (ctx, item) => answered(() => withdraw(ctx, item)),\n};\n","import {\n centsFromMajor,\n type CatalogueReadNotice,\n type CatalogueReadWarning,\n type CatalogueSnapshotItem,\n type CatalogueSnapshotOption,\n type CatalogueSnapshotOptionGroup,\n} from \"../core/catalogue-read-port\";\n\n/**\n * iFood's catalogue answer mapped into the engine's {@link CatalogueSnapshotItem}\n * (FUT-951). Pure and offline: `./catalogue-read.ts` makes the calls.\n *\n * The shapes are the Catalog API v2.0's `PUT /items` payload, which the\n * portal's Introduction shows whole (read 2026-11-16): an `item` (id, type,\n * categoryId, status, `price { value }`, externalCode), `products` (id, name,\n * description, externalCode, and `optionGroups: [{ id, min, max }]` linking a\n * product to its groups), `optionGroups` (id, name, status, `optionIds`) and\n * `options` (id, `productId` naming the product that holds its name, status,\n * `price { value }`). The package README's \"Catalogue reading\" table marks\n * each fact CONFIRMED with its URL or ESTIMATED. ESTIMATED here, and said\n * beside each use:\n * - that `GET /categories/{categoryId}/items` answers the same four lists\n * (`items` plural) the PUT takes;\n * - that `item.productId` names the item's product (the field the push sends);\n * - that `products[].imagePath` holds the photo, a path under\n * {@link IFOOD_IMAGE_BASE_URL}.\n */\n\n/**\n * Where iFood serves a catalogue photo's `imagePath`. ESTIMATED: the Catalog\n * pages read name `imagePath` but not its host; this is the host iFood's own\n * app loads dish photos from. A path that is already an absolute https URL is\n * used as it is.\n */\nexport const IFOOD_IMAGE_BASE_URL = \"https://static-images.ifood.com.br/image/upload/t_high/pratos/\";\n\ntype Json = Record<string, unknown>;\n\nexport const record = (value: unknown): Json | null =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Json) : null;\n\nexport const text = (value: unknown): string | null => (typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : null);\n\n/**\n * The objects of a JSON array, and every other entry it held (a string, a\n * number, a nested array), so the caller can SAY what it could not read rather\n * than lose it. Not an array: no entries, nothing else.\n */\nexport function entriesOf(value: unknown): { entries: Json[]; others: unknown[] } {\n const entries: Json[] = [];\n const others: unknown[] = [];\n for (const entry of Array.isArray(value) ? value : []) {\n const object = record(entry);\n if (object) entries.push(object);\n else others.push(entry);\n }\n return { entries, others };\n}\n\n/**\n * The lookup lists (`products`, `optionGroups`, `options`) keep only objects\n * with an id: an entry is only ever reached through an id that names it, and a\n * reference that finds nothing is warned about where it is made\n * (OPTION_GROUP_UNREADABLE, OPTION_UNREADABLE, or the item's ITEM_UNREADABLE).\n */\nconst list = (value: unknown): Json[] => entriesOf(value).entries;\n\n/** iFood's `status`: anything but UNAVAILABLE is on sale (an absent status included). */\nexport const availableOf = (status: unknown): boolean => status !== \"UNAVAILABLE\";\n\n/** The four lists of one category's answer, each by id. */\ninterface IfoodCatalogueIndex {\n products: Map<string, Json>;\n optionGroups: Map<string, Json>;\n options: Map<string, Json>;\n}\n\nconst byId = (entries: Json[]): Map<string, Json> =>\n new Map(entries.flatMap((entry) => (text(entry.id) ? [[text(entry.id) as string, entry] as const] : [])));\n\nexport function indexOf(answer: Json): IfoodCatalogueIndex {\n return { products: byId(list(answer.products)), optionGroups: byId(list(answer.optionGroups)), options: byId(list(answer.options)) };\n}\n\nconst priceCentsOf = (price: unknown): number | null => centsFromMajor(record(price)?.value);\n\nconst warning = (code: CatalogueReadWarning[\"code\"], subject: string | null, detail: unknown = null): CatalogueReadWarning => ({\n code,\n subject,\n detail: detail === null || detail === undefined ? null : JSON.stringify(detail),\n});\n\n/** The photo's absolute URL; a warning when a reference is there but cannot be resolved. */\nexport function photoOf(imagePath: unknown, subject: string | null): { url: string | null; warning?: CatalogueReadWarning } {\n if (imagePath === undefined || imagePath === null || imagePath === \"\") return { url: null };\n const path = text(imagePath);\n if (path === null) return { url: null, warning: warning(\"PHOTO_UNREADABLE\", subject, imagePath) };\n if (/^https:\\/\\//i.test(path)) return { url: path };\n if (/^[a-z][a-z0-9+.-]*:/i.test(path)) return { url: null, warning: warning(\"PHOTO_UNREADABLE\", subject, path) };\n return { url: `${IFOOD_IMAGE_BASE_URL}${urlSafePath(path.replace(/^\\/+/, \"\"))}` };\n}\n\n/**\n * The path as a URL path: kept as it is when it is already one (an encoded\n * `%20` stays `%20`, never `%2520`); only a character a URL may not carry\n * (a space, a quote, a non-ASCII letter) is encoded, and a `%` that starts no\n * escape becomes `%25`.\n */\nfunction urlSafePath(path: string): string {\n return path\n .replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\")\n .replace(/[^A-Za-z0-9\\-._~!$&'()*+,;=:@/%]/g, (character) => encodeURIComponent(character));\n}\n\n/** The words and photo of an item or option: its product's (`productId`), else its own. */\ninterface Described {\n name: string | null;\n description: string | null;\n externalCode: string | null;\n imagePath: unknown;\n}\n\nfunction describedBy(index: IfoodCatalogueIndex, own: Json): Described {\n const product = index.products.get(text(own.productId) ?? \"\") ?? {};\n return {\n name: text(product.name) ?? text(own.name),\n description: text(product.description) ?? text(own.description),\n externalCode: text(own.externalCode) ?? text(product.externalCode),\n imagePath: product.imagePath ?? own.imagePath,\n };\n}\n\n/** The photo's URL, its warning (if any) pushed onto `warnings`. */\nfunction photoInto(imagePath: unknown, subject: string | null, warnings: CatalogueReadWarning[]): string | null {\n const photo = photoOf(imagePath, subject);\n if (photo.warning) warnings.push(photo.warning);\n return photo.url;\n}\n\n/** One option of a group, or the warning that leaves it out. */\nfunction optionOf(id: string, index: IfoodCatalogueIndex, warnings: CatalogueReadWarning[]): CatalogueSnapshotOption | null {\n const option = index.options.get(id);\n const described = option ? describedBy(index, option) : null;\n if (!option || !described || described.name === null) {\n warnings.push(warning(\"OPTION_UNREADABLE\", id, option));\n return null;\n }\n const priceDeltaCents = priceCentsOf(option.price);\n if (priceDeltaCents === null) warnings.push(warning(\"OPTION_PRICE_MISSING\", id, option.price));\n return {\n externalId: id,\n externalCode: described.externalCode,\n name: described.name,\n description: described.description,\n priceDeltaCents,\n photoUrl: photoInto(described.imagePath, id, warnings),\n available: availableOf(option.status),\n };\n}\n\n/** A group's bounds, when they make sense: whole numbers, 0 <= min <= max, max >= 1. */\nfunction boundsOf(link: Json, group: Json): { min: number; max: number } | null {\n const min = link.min ?? group.min ?? 0;\n const max = link.max ?? group.max;\n if (!Number.isInteger(min) || !Number.isInteger(max)) return null;\n const [low, high] = [min as number, max as number];\n return low >= 0 && high >= 1 && high >= low ? { min: low, max: high } : null;\n}\n\n/** A group's option ids; an entry that is not an id is an OPTION_UNREADABLE warning, never dropped. */\nfunction idsOf(groupId: string, value: unknown, warnings: CatalogueReadWarning[]): string[] {\n const ids: string[] = [];\n for (const entry of Array.isArray(value) ? value : []) {\n const id = text(entry);\n if (id === null) warnings.push(warning(\"OPTION_UNREADABLE\", groupId, entry));\n else ids.push(id);\n }\n return ids;\n}\n\n/** One group a product links to (`products[].optionGroups[]`), or the warning that leaves it out. */\nfunction groupOf(link: Json, index: IfoodCatalogueIndex, warnings: CatalogueReadWarning[]): CatalogueSnapshotOptionGroup | null {\n const id = text(link.id);\n const group = id === null ? undefined : index.optionGroups.get(id);\n const bounds = group ? boundsOf(link, group) : null;\n const name = text(group?.name);\n if (id === null || !group || name === null || bounds === null) {\n warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", id, { link, group }));\n return null;\n }\n const options = idsOf(id, group.optionIds, warnings).flatMap((optionId) => optionOf(optionId, index, warnings) ?? []);\n if (options.length === 0) {\n warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", id, \"no readable option\"));\n return null;\n }\n return { externalId: id, externalCode: text(group.externalCode), name, ...bounds, available: availableOf(group.status), options };\n}\n\n/** The item's own warnings: a kind it maps only partly, and a missing price. */\nfunction itemWarnings(raw: Json, priceCents: number | null): CatalogueReadWarning[] {\n const warnings: CatalogueReadWarning[] = [];\n const type = text(raw.type);\n if (type !== null && type !== \"DEFAULT\") warnings.push(warning(\"ITEM_TYPE_UNSUPPORTED\", null, type));\n if (priceCents === null) warnings.push(warning(\"PRICE_MISSING\", null, raw.price));\n return warnings;\n}\n\n/**\n * The group links of an item: on its product (CONFIRMED, the PUT example),\n * else on the item itself. Links that are not objects, or a value that is not\n * a list at all, are an OPTION_GROUP_UNREADABLE warning each.\n */\nfunction linksOf(index: IfoodCatalogueIndex, raw: Json, warnings: CatalogueReadWarning[]): Json[] {\n const product = index.products.get(text(raw.productId) ?? \"\");\n const value = product?.optionGroups ?? raw.optionGroups;\n if (value !== undefined && value !== null && !Array.isArray(value)) warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", null, value));\n const { entries, others } = entriesOf(value);\n for (const other of others) warnings.push(warning(\"OPTION_GROUP_UNREADABLE\", null, other));\n return entries;\n}\n\n/** One item of a category, or the notice that says why it could not be read. */\nexport function itemOf(raw: Json, index: IfoodCatalogueIndex, categoryId: string): CatalogueSnapshotItem | CatalogueReadNotice {\n const id = text(raw.id);\n // ESTIMATED: `item.productId` names the product that holds the item's name, description and photo.\n const described = describedBy(index, raw);\n if (id === null || described.name === null) {\n return { code: \"ITEM_UNREADABLE\", categoryExternalId: categoryId, externalId: id, detail: JSON.stringify(raw).slice(0, 300) };\n }\n const priceCents = priceCentsOf(raw.price);\n const warnings = itemWarnings(raw, priceCents);\n const photoUrl = photoInto(described.imagePath, null, warnings);\n const optionGroups = linksOf(index, raw, warnings).flatMap((link) => groupOf(link, index, warnings) ?? []);\n return {\n externalId: id,\n externalCode: described.externalCode,\n name: described.name,\n description: described.description,\n priceCents,\n photoUrl,\n available: availableOf(raw.status),\n optionGroups,\n warnings,\n };\n}\n","import { outboundResultOf, type MarketplaceHttpResponse, type OutboundResult } from \"../core/adapter\";\nimport type {\n CatalogueReadContext,\n CatalogueReader,\n CatalogueReadNotice,\n CatalogueReadResult,\n CatalogueSnapshotCategory,\n CatalogueSnapshotItem,\n} from \"../core/catalogue-read-port\";\nimport { availableOf, entriesOf, indexOf, itemOf, record, text } from \"./catalogue-snapshot\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * The iFood adapter's catalogue READ (FUT-951): the menu a store already keeps\n * on iFood, read through the store's OWN connection (its merchant id, and the\n * client-credentials token of its app, `bearer`), for the host to import.\n *\n * One read is, in order:\n * 1. `GET /categories` — the merchant's categories (CONFIRMED, the Endpoints\n * page as read 2026-11-13; ESTIMATED that it answers an array of\n * `{ id, name, status, externalCode }`, the same estimate the push makes);\n * 2. `GET /categories/{categoryId}/items` for each, in the list's order\n * (CONFIRMED, the Introduction's step 5, read 2026-11-16), mapped by\n * `./catalogue-snapshot.ts`.\n *\n * Pagination: none. The pages read show no page, size or cursor parameter on\n * either call (ESTIMATED that there is none), so the menu is read one category\n * per call, which bounds each answer by a category's size.\n *\n * Failures:\n * - a 401 drops the cached token and asks once more with a fresh one (as the\n * push's `call` does); a second 401 is a `retry`;\n * - the token grant refused (400, 401, 403) is `CREDENTIALS`;\n * - 403 (the Errors page: the app is not allowed this merchant, or the\n * catalogue module is not enabled for it) and 404 on the category list (no\n * such merchant for this app, ESTIMATED) are `NOT_AUTHORIZED`;\n * - 429, 408, 425, 5xx and a call with no answer are `retry`;\n * - any other 4xx is `REFUSED`, with iFood's words.\n * A category whose own items answer 404 (deleted between the two calls), or\n * answer in a shape other than `{ items: [...] }`, is left out with a\n * CATEGORY_UNREADABLE notice rather than failing the read; an entry of a list\n * that is not an object is a notice too. Only a category LIST that is not a\n * list refuses the read (REFUSED): without it there is no menu to keep.\n */\n\nconst catalogUrl = (merchantId: string, path: string): string =>\n `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;\n\ntype Failure = Exclude<CatalogueReadResult, { kind: \"snapshot\" }>;\n\n/** The token grant's failure: a refusal is the store's credentials, anything else is asked again. */\nfunction tokenFailure(result: OutboundResult): Failure {\n if (result.kind === \"refused\") return { kind: \"refused\", code: \"CREDENTIALS\", status: result.status, message: result.message };\n return { kind: \"retry\", reason: result.kind === \"retry\" ? result.reason : \"unexpected token answer\" };\n}\n\n/** A non-2xx catalogue answer as the failure it is. */\nfunction failureOf(response: MarketplaceHttpResponse): Failure {\n const result = outboundResultOf(response);\n if (result.kind !== \"refused\") return { kind: \"retry\", reason: result.kind === \"retry\" ? result.reason : \"unexpected answer\" };\n const code = response.status === 403 || response.status === 404 ? \"NOT_AUTHORIZED\" : \"REFUSED\";\n return { kind: \"refused\", code, status: result.status, message: result.message };\n}\n\n/** One authenticated GET: iFood's answer (any status but 401), or the failure that ends the read. */\nasync function get(ctx: CatalogueReadContext, path: string): Promise<MarketplaceHttpResponse | Failure> {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return tokenFailure(auth);\n const response = await ctx.http({\n method: \"GET\",\n url: catalogUrl(ctx.externalMerchantId, path),\n headers: { Authorization: `Bearer ${auth.token}`, Accept: \"application/json\" },\n });\n if (response.status !== 401) return response;\n // A token that went stale under us: forget it, and the next turn grants another.\n ctx.tokens.delete(ifoodTokenKey(ctx));\n }\n return { kind: \"retry\", reason: \"iFood refused a fresh token\" };\n}\n\nconst ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;\n\nfunction parse(body: string): unknown {\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return null;\n }\n}\n\nconst unexpected = (what: string, body: string): Failure => ({\n kind: \"refused\",\n code: \"REFUSED\",\n status: 200,\n message: `unexpected ${what} answer: ${body.slice(0, 200)}`,\n});\n\n/** One category's items, or the notice that leaves the category out, or the failure that ends the read. */\nasync function categoryOf(\n ctx: CatalogueReadContext,\n raw: Record<string, unknown>,\n notices: CatalogueReadNotice[],\n): Promise<CatalogueSnapshotCategory | null | Failure> {\n const id = text(raw.id);\n const name = text(raw.name);\n if (id === null || name === null) {\n notices.push(unreadableCategory(id, raw));\n return null;\n }\n const answered = await get(ctx, `categories/${encodeURIComponent(id)}/items`);\n if (\"kind\" in answered) return answered;\n if (answered.status === 404) {\n notices.push(unreadableCategory(id, \"its items answered 404\"));\n return null;\n }\n if (!ok(answered)) return failureOf(answered);\n const items = itemsOf(answered.body, id, notices);\n return items && { externalId: id, externalCode: text(raw.externalCode), name, available: availableOf(raw.status), items };\n}\n\nconst unreadableCategory = (categoryExternalId: string | null, detail: unknown): CatalogueReadNotice => ({\n code: \"CATEGORY_UNREADABLE\",\n categoryExternalId,\n externalId: null,\n detail: (typeof detail === \"string\" ? detail : JSON.stringify(detail) ?? String(detail)).slice(0, 300),\n});\n\n/**\n * One category's items, each one it cannot read an ITEM_UNREADABLE notice; or\n * null, with a CATEGORY_UNREADABLE notice, when the answer is not the expected\n * `{ items: [...] }` (ESTIMATED: the PUT's four lists, `items` plural). A\n * notice rather than refusing the whole read: one category answered in an odd\n * shape keeps the rest of the menu importable, and the host shows which\n * category did not come over; a shape iFood changed everywhere leaves a notice\n * on every category, never a silent empty menu.\n */\nfunction itemsOf(rawBody: string, categoryId: string, notices: CatalogueReadNotice[]): CatalogueSnapshotItem[] | null {\n const body = record(parse(rawBody));\n if (!body || !Array.isArray(body.items)) {\n notices.push(unreadableCategory(categoryId, `unexpected items answer: ${rawBody}`));\n return null;\n }\n const index = indexOf(body);\n const { entries, others } = entriesOf(body.items);\n for (const other of others) {\n notices.push({ code: \"ITEM_UNREADABLE\", categoryExternalId: categoryId, externalId: null, detail: String(JSON.stringify(other)).slice(0, 300) });\n }\n const items: CatalogueSnapshotItem[] = [];\n for (const entry of entries) {\n const mapped = itemOf(entry, index, categoryId);\n if (\"code\" in mapped) notices.push(mapped);\n else items.push(mapped);\n }\n return items;\n}\n\nasync function read(ctx: CatalogueReadContext): Promise<CatalogueReadResult> {\n const listed = await get(ctx, \"categories\");\n if (\"kind\" in listed) return listed;\n if (!ok(listed)) return failureOf(listed);\n const parsed = parse(listed.body);\n if (!Array.isArray(parsed)) return unexpected(\"category list\", listed.body);\n const categories: CatalogueSnapshotCategory[] = [];\n const notices: CatalogueReadNotice[] = [];\n const { entries, others } = entriesOf(parsed);\n // A category entry that is not an object is said, never skipped.\n for (const other of others) notices.push(unreadableCategory(null, other));\n for (const raw of entries) {\n const category = await categoryOf(ctx, raw, notices);\n if (category === null) continue;\n if (\"kind\" in category) return category;\n categories.push(category);\n }\n return { kind: \"snapshot\", snapshot: { categories, notices } };\n}\n\n/** iFood's catalogue read. */\nexport const IFOOD_CATALOGUE_READER: CatalogueReader = {\n read: async (ctx) => {\n try {\n return await read(ctx);\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n },\n};\n","import { outboundResultOf, type AdapterCallContext, type OutboundOrderRef } from \"../core/adapter\";\nimport type {\n CourierTrackingCallResult,\n MarketplaceCourierApi,\n MarketplaceCourierTracking,\n PickupCodeCallResult,\n} from \"../core/courier-port\";\nimport { firstDate, firstString, pick } from \"../core/payload-read\";\nimport type { MarketplaceCourier, MarketplaceCourierStep, MarketplaceCourierVehicle, NormalizedCourierEvent } from \"../core/types\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * iFood's own fleet (FUT-5665), both halves: the courier events of iFood's\n * stream, and the two calls about the courier (the pickup-code check and the\n * tracking read). Only for an order iFood's fleet carries\n * (`delivery.deliveredBy = IFOOD`); the engine never calls either for another.\n *\n * Source: the iFood research of 2026-11-26 (Levantamento, lines 95-115),\n * marked confirmed there against iFood's Order module docs; what it could not\n * confirm is marked ESTIMATED below, in this file only.\n */\n\n/**\n * iFood's courier event codes, short and long. The four short codes and every\n * long form are confirmed; the two return events have no documented short\n * code, so only their long forms are read (ESTIMATED: none is guessed).\n */\nconst COURIER_STEP_OF: Readonly<Record<string, MarketplaceCourierStep>> = {\n ADR: \"ASSIGNED\",\n ASSIGN_DRIVER: \"ASSIGNED\",\n GTO: \"GOING_TO_ORIGIN\",\n GOING_TO_ORIGIN: \"GOING_TO_ORIGIN\",\n AAO: \"ARRIVED_AT_ORIGIN\",\n ARRIVED_AT_ORIGIN: \"ARRIVED_AT_ORIGIN\",\n CLT: \"COLLECTED\",\n COLLECTED: \"COLLECTED\",\n DELIVERY_RETURNING_TO_ORIGIN: \"RETURNING_TO_ORIGIN\",\n DELIVERY_RETURNED_TO_ORIGIN: \"RETURNED_TO_ORIGIN\",\n};\n\n/**\n * `workerVehicleType` as the host's closed set. ESTIMATED: the field is\n * confirmed, its values are not documented in the research; these are the\n * words a vehicle is plausibly named with, and anything else stated is OTHER.\n */\nconst VEHICLE_OF: Readonly<Record<string, MarketplaceCourierVehicle>> = {\n MOTORCYCLE: \"MOTORCYCLE\",\n MOTORBIKE: \"MOTORCYCLE\",\n MOTO: \"MOTORCYCLE\",\n BICYCLE: \"BICYCLE\",\n BIKE: \"BICYCLE\",\n CAR: \"CAR\",\n CARRO: \"CAR\",\n};\n\n/** The longest courier name kept: a longer one is truncated, never refused. */\nexport const IFOOD_COURIER_NAME_MAX = 120;\n/** The longest photo URL kept: a longer one is dropped (a truncated URL is a broken one). */\nconst IFOOD_COURIER_PHOTO_URL_MAX = 2048;\n\n/** An https URL of bounded length, or null: a photo the host renders is never another scheme. */\nfunction httpsUrl(value: string | null): string | null {\n if (!value || value.length > IFOOD_COURIER_PHOTO_URL_MAX) return null;\n try {\n return new URL(value).protocol === \"https:\" ? value : null;\n } catch {\n return null;\n }\n}\n\n/** The event's `metadata`: an object, or a JSON string of one. */\nfunction metadataOf(payload: unknown): unknown {\n const raw = pick(payload, \"metadata\");\n if (typeof raw !== \"string\") return raw;\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n}\n\n/** The courier an ADR names: `workerName`, `workerPhotoUrl`, `workerVehicleType`. Null when it names nothing. */\nfunction readCourier(payload: unknown): MarketplaceCourier | null {\n const metadata = metadataOf(payload);\n const name = firstString(metadata, [[\"workerName\"]])?.slice(0, IFOOD_COURIER_NAME_MAX) ?? null;\n const photoUrl = httpsUrl(firstString(metadata, [[\"workerPhotoUrl\"]]));\n const stated = firstString(metadata, [[\"workerVehicleType\"]])?.toUpperCase() ?? null;\n const vehicle = stated === null ? null : (VEHICLE_OF[stated] ?? \"OTHER\");\n return name === null && photoUrl === null && vehicle === null ? null : { name, photoUrl, vehicle };\n}\n\n/** The courier step an iFood event names, or null. */\nexport function readIfoodCourierEvent(payload: unknown, eventType: string): NormalizedCourierEvent | null {\n const step = COURIER_STEP_OF[eventType.toUpperCase()];\n if (!step) return null;\n return {\n step,\n at: firstDate(payload, [[\"createdAt\"]]),\n courier: step === \"ASSIGNED\" ? readCourier(payload) : null,\n returning: step === \"RETURNING_TO_ORIGIN\" ? \"RETURNING\" : step === \"RETURNED_TO_ORIGIN\" ? \"RETURNED\" : null,\n };\n}\n\nconst orderUrl = (ref: OutboundOrderRef, action: string): string =>\n `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(ref.externalOrderId)}/${action}`;\n\n/** One authenticated call; a 401 forgets the token so the retry fetches another. */\nasync function call(\n ctx: AdapterCallContext,\n request: { method: \"GET\" | \"POST\"; url: string; body?: unknown },\n): Promise<{ status: number; body: string } | { kind: \"refused\"; status: number; message: string; own?: true } | { kind: \"retry\"; reason: string }> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"no token\" } : auth;\n const response = await ctx.http({\n method: request.method,\n url: request.url,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),\n });\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n return { kind: \"retry\", reason: \"iFood refused the token\" };\n}\n\nfunction parsed(body: string): unknown {\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return null;\n }\n}\n\n/**\n * `POST /order/v1.0/orders/{id}/validatePickupCode {\"code\"}`, answering\n * `{\"valid\": true|false}` (confirmed). A 2xx without a boolean `valid` is no\n * verdict: our own refusal, never read as INVALID.\n */\nasync function validatePickupCode(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { code: string },\n): Promise<PickupCodeCallResult> {\n try {\n const response = await call(ctx, { method: \"POST\", url: orderUrl(order, \"validatePickupCode\"), body: { code: input.code } });\n if (\"kind\" in response) return response;\n const read = outboundResultOf(response);\n if (read.kind !== \"accepted\") return read;\n const valid = pick(parsed(response.body), \"valid\");\n return typeof valid === \"boolean\"\n ? { kind: \"answered\", valid }\n : { kind: \"refused\", status: response.status, message: \"iFood answered without a verdict\", own: true };\n } catch (error) {\n return retryOf(error);\n }\n}\n\n/** A call that never got an answer is a retry. */\nfunction retryOf(error: unknown): { kind: \"retry\"; reason: string } {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n}\n\nfunction numberAt(source: unknown, key: string): number | null {\n const value = pick(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\n/** `base` plus a number of seconds, or null when either is missing. */\nfunction plusSeconds(base: Date, seconds: number | null): Date | null {\n return seconds === null ? null : new Date(base.getTime() + seconds * 1000);\n}\n\n/**\n * The tracking body. Confirmed: latitude, longitude, `expectedDelivery`,\n * `trackDate`, and seconds to the pickup and to the delivery. ESTIMATED: the\n * names of the two second counts (`pickupEtaStart`, `deliveryEtaEnd`, or\n * `pickupEta`, `deliveryEta`), counted from `trackDate`.\n */\nfunction readTracking(body: unknown, now: Date): MarketplaceCourierTracking {\n const trackedAt = firstDate(body, [[\"trackDate\"]]);\n const base = trackedAt ?? now;\n const pickupSeconds = numberAt(body, \"pickupEtaStart\") ?? numberAt(body, \"pickupEta\");\n const deliverySeconds = numberAt(body, \"deliveryEtaEnd\") ?? numberAt(body, \"deliveryEta\");\n return {\n pickupEtaAt: plusSeconds(base, pickupSeconds),\n deliveryEtaAt: firstDate(body, [[\"expectedDelivery\"]]) ?? plusSeconds(base, deliverySeconds),\n latitude: numberAt(body, \"latitude\"),\n longitude: numberAt(body, \"longitude\"),\n trackedAt,\n };\n}\n\n/** `GET /order/v1.0/orders/{id}/tracking` (confirmed): 404 before ASSIGN_DRIVER is \"not yet\". */\nasync function tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<CourierTrackingCallResult> {\n try {\n const response = await call(ctx, { method: \"GET\", url: orderUrl(order, \"tracking\") });\n if (\"kind\" in response) return response;\n if (response.status === 404) return { kind: \"notYet\" };\n const read = outboundResultOf(response);\n if (read.kind !== \"accepted\") return read;\n return { kind: \"tracking\", tracking: readTracking(parsed(response.body), ctx.now) };\n } catch (error) {\n return retryOf(error);\n }\n}\n\n/** iFood's courier calls, for the adapter's `courier`. */\nexport const IFOOD_COURIER: MarketplaceCourierApi = { validatePickupCode, tracking };\n","import type {\n MarketplacePaymentMethod,\n NormalizedLineOption,\n NormalizedOrderFee,\n NormalizedPaymentMethod,\n NormalizedPayments,\n} from \"../core/types\";\nimport { firstCents, firstString, firstTaxId, pick, toCents } from \"../core/payload-read\";\n\n/**\n * The parts of an iFood order beyond its items' base price (FUT-5803): each\n * item's options, the payment, the fees besides delivery and the buyer's\n * document. Field names follow iFood's order-details guide\n * (\"Detalhes do pedido\", developer portal); read\n * defensively like the rest of the adapter, so an absent part is absent,\n * never a refused order.\n */\n\n/** A whole, positive count; 1 when absent or nonsense. */\nfunction countOf(source: unknown): number {\n const stated = Number(pick(source, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? Math.round(stated) : 1;\n}\n\n/**\n * The option's rows, each with `unitPriceCents × quantity` exactly its total,\n * because a host writes the two and must read the stated price back. Kept as\n * stated when they agree. Otherwise the stated total is split over the stated\n * quantity, as Open Delivery's lines are: one row when it divides, else\n * `quantity - 1` at the floor and one carrying the remainder (R$ 10.00 over 3\n * is 2 × 3.33 + 1 × 3.34). The count the kitchen reads never changes.\n */\nfunction priced(quantity: number, unit: number | null, total: number): { quantity: number; unitPriceCents: number; totalCents: number }[] {\n if (unit !== null && unit * quantity === total) return [{ quantity, unitPriceCents: unit, totalCents: total }];\n const floor = Math.floor(total / quantity);\n const remainder = total - floor * quantity;\n if (remainder === 0) return [{ quantity, unitPriceCents: floor, totalCents: total }];\n const last = { quantity: 1, unitPriceCents: floor + remainder, totalCents: floor + remainder };\n return quantity === 1 ? [last] : [{ quantity: quantity - 1, unitPriceCents: floor, totalCents: floor * (quantity - 1) }, last];\n}\n\n/** One `items[].options[]` entry as its rows (one, or two when its price splits); none for one with no name and no price. */\nfunction readOption(raw: unknown): NormalizedLineOption[] {\n const quantity = countOf(raw);\n const unit = toCents(pick(raw, \"unitPrice\"));\n const total = toCents(pick(raw, \"price\")) ?? (unit ?? 0) * quantity;\n const name = firstString(raw, [[\"name\"], [\"externalCode\"]]);\n if (name === null && total === 0) return [];\n const option = { externalCode: firstString(raw, [[\"externalCode\"]]), name: name ?? \"\", groupName: firstString(raw, [[\"groupName\"]]) };\n return priced(quantity, unit, total).map((row) => ({ ...option, ...row }));\n}\n\n/** An item's options; undefined when it states none, so a plain line stays as it was. */\nexport function readIfoodOptions(item: unknown): NormalizedLineOption[] | undefined {\n const raw = pick(item, \"options\");\n if (!Array.isArray(raw)) return undefined;\n const options = raw.flatMap(readOption);\n return options.length > 0 ? options : undefined;\n}\n\nconst METHODS: ReadonlySet<string> = new Set<MarketplacePaymentMethod>([\n \"CREDIT\",\n \"DEBIT\",\n \"MEAL_VOUCHER\",\n \"FOOD_VOUCHER\",\n \"PIX\",\n \"CASH\",\n \"DIGITAL_WALLET\",\n]);\n\n/** `type` ONLINE is prepaid and OFFLINE is collected; failing both, the method's own `prepaid` flag. */\nfunction prepaidOf(raw: unknown): boolean | null {\n const type = firstString(raw, [[\"type\"]])?.toUpperCase();\n if (type === \"ONLINE\") return true;\n if (type === \"OFFLINE\") return false;\n const flag = pick(raw, \"prepaid\");\n return typeof flag === \"boolean\" ? flag : null;\n}\n\n/** One `payments.methods[]` entry. A method with no value states 0: the method itself is what the door needs. */\nfunction readMethod(raw: unknown): NormalizedPaymentMethod {\n const stated = firstString(raw, [[\"method\"]])?.toUpperCase() ?? null;\n return {\n method: stated !== null && METHODS.has(stated) ? (stated as MarketplacePaymentMethod) : \"OTHER\",\n statedMethod: stated,\n prepaid: prepaidOf(raw),\n valueCents: toCents(pick(raw, \"value\")) ?? 0,\n cardBrand: firstString(raw, [[\"card\", \"brand\"]]),\n changeForCents: firstCents(raw, [[\"cash\", \"changeFor\"], [\"changeFor\"]]),\n };\n}\n\n/** `payments`: what is prepaid, what is pending, and each method. Undefined when the order states no payment. */\nexport function readIfoodPayments(order: unknown): NormalizedPayments | undefined {\n const payments = pick(order, \"payments\");\n if (typeof payments !== \"object\" || payments === null) return undefined;\n const methods = pick(payments, \"methods\");\n return {\n prepaidCents: firstCents(payments, [[\"prepaid\"]]),\n pendingCents: firstCents(payments, [[\"pending\"]]),\n methods: Array.isArray(methods) ? methods.map(readMethod) : [],\n };\n}\n\n/** `additionalFees[]`: each with a type and a value. Undefined when unstated; a fee with no value is skipped. */\nexport function readIfoodAdditionalFees(order: unknown): NormalizedOrderFee[] | undefined {\n const raw = pick(order, \"additionalFees\");\n if (!Array.isArray(raw)) return undefined;\n return raw.flatMap((fee): NormalizedOrderFee[] => {\n const cents = toCents(pick(fee, \"value\"));\n if (cents === null) return [];\n const name = firstString(fee, [[\"description\"]]);\n return [{ kind: firstString(fee, [[\"type\"]])?.toUpperCase() ?? \"OTHER\", cents, ...(name === null ? {} : { name }) }];\n });\n}\n\n/** The buyer's CPF or CNPJ, digits only (`documentNumber`, or `document`, text or a number); null when unstated. */\nexport function readIfoodBuyerDocument(order: unknown): string | null {\n return firstTaxId(order, [[\"customer\", \"documentNumber\"], [\"customer\", \"document\"]]);\n}\n","import type {\n MarketplaceLifecycle,\n MarketplaceDeliveredBy,\n MarketplaceDiscountSponsor,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedBuyer,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderDiscount,\n NormalizedOrderLine,\n} from \"../core/types\";\nimport { normalizedLineTotalCents } from \"../core/types\";\nimport {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n toCents,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\nimport { readIfoodCourierEvent } from \"./courier\";\nimport { readIfoodAdditionalFees, readIfoodBuyerDocument, readIfoodOptions, readIfoodPayments } from \"./order-details\";\n\n/**\n * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.\n *\n * Everything iFood-shaped about a delivery is in this file, and the engine\n * never learns the name: it reaches this through the adapter registry.\n *\n * The payload is treated as UNTRUSTED and read defensively throughout: iFood's\n * documented shape and iFood's actual shape have drifted before, and a\n * `TypeError` reading a missing field would reject a paid order at the door.\n * Every reader below either produces a value or produces null; the one thing\n * that can refuse an order outright is a missing order ID, because without it\n * there is no idempotency key and ingesting would risk a duplicate.\n */\n\n/** iFood event codes this ingestion acts on. */\nconst ORDER_PLACED = new Set([\"PLC\", \"PLACED\", \"ORDER_PLACED\"]);\nconst ORDER_CANCELLED = new Set([\"CAN\", \"CANCELLED\", \"ORDER_CANCELLED\"]);\n/** The store accepted the order on iFood's own app (FUT-5653). Also the echo of our own confirm. */\nconst ORDER_CONFIRMED = new Set([\"CFM\", \"CONFIRMED\"]);\n/** iFood's presence heartbeat (FUT-5984, `presence.md`): every 30 s, naming no order. */\nconst KEEPALIVE = \"KEEPALIVE\";\n/** iFood refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_FAILED = new Set([\"CARF\", \"CANCELLATION_REQUEST_FAILED\"]);\n\n/**\n * The lifecycle events (FUT-4653): the order left (`DSP`) and the order is\n * finished (`CON`). ESTIMATED: iFood's portal refused our reader (Cloudflare\n * 403, https://developer.ifood.com.br, 2026-11-25), so these codes and their\n * long forms are the ones iFood's event stream is commonly documented with,\n * not read off a page. They sit here beside the sets above so homologation\n * corrects one place.\n */\nconst LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = {\n DSP: \"DISPATCHED\",\n DISPATCHED: \"DISPATCHED\",\n CON: \"CONCLUDED\",\n CONCLUDED: \"CONCLUDED\",\n // iFood's courier has the bag (FUT-5665): for a fleet bag, the same hand-over as DSP.\n CLT: \"COLLECTED\",\n COLLECTED: \"COLLECTED\",\n};\n\n/**\n * Verify a delivery against the merchant's webhook secret: iFood signs the raw\n * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one\n * refuses an unsigned delivery; constant-time compare) is the engine's\n * {@link verifyHmacSha256Hex}. iFood's own onboarding issues the secret after\n * the merchant is certified, so refusing before then would make the\n * connection untestable.\n */\nexport function verifyIfoodSignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/**\n * The buyer, as much of them as iFood discloses on the order. The document\n * (for the invoice) and the masked phone's localizer are absent when unstated.\n */\nfunction readBuyer(order: unknown): NormalizedBuyer {\n return {\n externalId: asString(pick(order, \"customer\", \"id\")),\n name: asString(pick(order, \"customer\", \"name\")),\n phone: firstString(order, [\n [\"customer\", \"phone\", \"number\"],\n [\"customer\", \"phone\"],\n ]),\n ...optional(\"document\", readIfoodBuyerDocument(order) ?? undefined),\n ...optional(\"phoneLocalizer\", firstString(order, [[\"customer\", \"phone\", \"localizer\"]]) ?? undefined),\n };\n}\n\n/**\n * One iFood item → one normalized line.\n *\n * A line with no resolvable SKU still becomes a line: `externalSku` falls back\n * to the item's own id, and failing that to its name. That fallback is doing\n * real work — an unmapped line is recoverable (the store maps it and it is\n * fixed forever), a DROPPED line is not, because nothing downstream can tell\n * that food is missing from the ticket.\n *\n * Its options (FUT-5803) ride on the line, priced on their own: the line costs\n * `unitPrice × quantity` plus each option's `price`, which is iFood's\n * `totalPrice` (`price + optionsPrice`).\n */\nfunction readLine(item: unknown): NormalizedOrderLine | null {\n const name = firstString(item, [[\"name\"], [\"description\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return null;\n const quantity = Number(pick(item, \"quantity\") ?? 1);\n return {\n externalSku: sku,\n name: name ?? sku,\n quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,\n unitPriceCents: firstCents(item, [[\"unitPrice\"], [\"price\"]]) ?? 0,\n note: firstString(item, [[\"observations\"], [\"note\"]]),\n ...optional(\"options\", readIfoodOptions(item)),\n };\n}\n\n/**\n * The commission iFood states on the order, in cents.\n *\n * Absent on plenty of real payloads (it depends on the merchant's contract and\n * on which API version delivered the order), and absent is stored as NULL\n * rather than as 0 — \"iFood took nothing\" and \"iFood did not say\" are different\n * claims, and only one of them is safe to put in a margin report.\n */\nfunction readCommission(order: unknown): number | null {\n return firstCents(order, [[\"total\", \"commission\"], [\"commission\"], [\"payments\", \"commission\"]]);\n}\n\nconst ORDER_TYPES: ReadonlySet<string> = new Set<MarketplaceOrderType>([\"DELIVERY\", \"TAKEOUT\", \"DINE_IN\", \"INDOOR\"]);\n\n/** iFood's `orderType` (DELIVERY, TAKEOUT, DINE_IN, INDOOR), or null when it says none of them. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"orderType\"]])?.toUpperCase();\n return stated !== undefined && ORDER_TYPES.has(stated) ? (stated as MarketplaceOrderType) : null;\n}\n\n/** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : null;\n}\n\n/**\n * iFood's sponsor names as who pays. ESTIMATED: the names are the ones iFood's\n * order-details guide documents for `benefits[].sponsorshipValues[].name`, but\n * no recorded payload in this repo carries them; confirm against a real order\n * (iFood's Order API guide \"Detalhes do pedido\").\n */\nfunction sponsorOf(name: string | null): MarketplaceDiscountSponsor {\n const stated = name?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : \"OTHER\";\n}\n\n/**\n * The discounts on an order, one per sponsor's share of each benefit.\n * ESTIMATED shape (see {@link sponsorOf}): `benefits[]` with a `value` and\n * `sponsorshipValues[{ name, value, description? }]`. A benefit that names no\n * sponsor is the whole `value` under OTHER; a share with no usable amount is\n * skipped. Absent `benefits` is undefined (\"did not say\").\n */\nfunction readDiscounts(order: unknown): NormalizedOrderDiscount[] | undefined {\n const benefits = pick(order, \"benefits\");\n if (!Array.isArray(benefits)) return undefined;\n return benefits.flatMap((benefit): NormalizedOrderDiscount[] => {\n const shares = pick(benefit, \"sponsorshipValues\");\n const parts = Array.isArray(shares)\n ? shares.map((share) => ({\n cents: toCents(pick(share, \"value\")),\n sponsor: sponsorOf(firstString(share, [[\"name\"]])),\n name: firstString(share, [[\"description\"]]),\n }))\n : [{ cents: toCents(pick(benefit, \"value\")), sponsor: \"OTHER\" as const, name: null }];\n return parts.flatMap((part) =>\n part.cents === null || part.cents <= 0\n ? []\n : [{ cents: part.cents, sponsor: part.sponsor, ...(part.name === null ? {} : { name: part.name }) }],\n );\n });\n}\n\n/**\n * Where a delivery goes. The street is what a courier cannot find a door\n * without, so an address with none is none; a missing number reads as the\n * host's own words for \"no number\" (`copy.missingStreetNumber`), which keeps\n * the street, the neighbourhood and the reference rather than dropping the\n * whole door.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"streetName\"], [\"street\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"streetNumber\"], [\"number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]]),\n };\n}\n\n/** `{ key: value }` unless the value is undefined, so an unstated field is absent rather than `undefined`. */\nfunction optional<K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } {\n return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });\n}\n\n/**\n * The order body of a placed-order event, or null when it carries none. Also\n * reads the order iFood serves at `GET /order/v1.0/orders/{id}` (`./fetch-order.ts`),\n * whose fields are the same ones the event's `order` would carry.\n */\nexport function readIfoodOrder(\n payload: unknown,\n externalOrderId: string,\n missingStreetNumber: string,\n): NormalizedMarketplaceOrder | null {\n const order = pick(payload, \"order\") ?? payload;\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .map(readLine)\n .filter((line): line is NormalizedOrderLine => line !== null);\n if (lines.length === 0) return null;\n\n const stated = firstCents(order, [[\"total\", \"orderAmount\"], [\"totalPrice\"], [\"total\"]]);\n\n return {\n provider: \"IFOOD\",\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]) ?? firstString(payload, [[\"displayId\"]]),\n buyer: readBuyer(order),\n lines,\n // The line sum is the FALLBACK, never the preference: iFood's stated total\n // carries delivery fees, its promotions and its rounding, and it is the\n // number on the buyer's receipt. Summing lines when iFood did say is how a\n // store's revenue quietly stops matching its iFood statement.\n totalCents: stated ?? lines.reduce((sum, line) => sum + normalizedLineTotalCents(line), 0),\n commissionCents: readCommission(order),\n deliveryDueAt: firstDate(order, [[\"delivery\", \"deliveryDateTime\"], [\"preparationStartDateTime\"]]),\n placedAt:\n firstDate(order, [[\"createdAt\"]]) ?? firstDate(payload, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, missingStreetNumber),\n // ESTIMATED names (iFood's order-details guide: `total.deliveryFee`,\n // `total.subTotal`, `benefits[]`). Fee and subtotal are null when unstated,\n // never 0; `discounts` is absent when `benefits` is.\n deliveryFeeCents: firstCents(order, [[\"total\", \"deliveryFee\"]]),\n subtotalCents: firstCents(order, [[\"total\", \"subTotal\"]]),\n ...optional(\"discounts\", readDiscounts(order)),\n // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.\n pickupCode: firstString(order, [[\"delivery\", \"pickupCode\"]]),\n // FUT-5803: how the buyer pays and the fees besides delivery; absent when unstated.\n ...optional(\"payments\", readIfoodPayments(order)),\n ...optional(\"additionalFees\", readIfoodAdditionalFees(order)),\n };\n}\n\n/**\n * The order a PLACED carries, or, when it carries none, the mark that has it\n * fetched: iFood's events carry only the order id (sandbox, 2026-11-27), so the\n * `marketplace.fetch-order` job reads it (FUT-5800). Any other event: no order.\n */\nfunction placedOrder(\n payload: unknown,\n placed: boolean,\n externalOrderId: string,\n missingStreetNumber: string,\n): Pick<NormalizedEvent, \"order\" | \"orderToFetch\"> {\n if (!placed) return { order: null };\n const order = readIfoodOrder(payload, externalOrderId, missingStreetNumber);\n return order ? { order } : { order: null, orderToFetch: true };\n}\n\n/**\n * Normalize one iFood delivery.\n *\n * Returns null only when the payload carries no order id at all — the one thing\n * this pipeline cannot proceed without, because it IS the idempotency key and\n * ingesting without it risks the duplicate that \"never lose an order\" is\n * balanced against.\n */\nexport function normalizeIfoodEvent(\n payload: unknown,\n options: { missingStreetNumber: string },\n): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"], [\"order\", \"id\"], [\"id\"]]);\n if (!externalOrderId) return null;\n\n const eventType = firstString(payload, [[\"fullCode\"], [\"code\"]]) ?? \"UNKNOWN\";\n const cancelled = ORDER_CANCELLED.has(eventType.toUpperCase());\n const placed = ORDER_PLACED.has(eventType.toUpperCase());\n const refusedRequest = CANCELLATION_REQUEST_FAILED.has(eventType.toUpperCase());\n\n return {\n provider: \"IFOOD\",\n // iFood's own event id when it sends one. The fallback is deterministic on\n // purpose — (order, type) is stable across a redelivery, so a duplicate\n // still collides on the inbox's unique index instead of creating a second\n // row that would be processed a second time.\n eventId: firstString(payload, [[\"id\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: firstString(payload, [[\"merchantId\"], [\"merchant\", \"id\"]]),\n externalOrderId,\n ...placedOrder(payload, placed, externalOrderId, options.missingStreetNumber),\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : refusedRequest ? \"FAILED\" : null,\n ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),\n ...optional(\"courier\", readIfoodCourierEvent(payload, eventType) ?? undefined),\n ...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),\n };\n}\n\n/**\n * iFood's `KEEPALIVE` (FUT-5984): `{ code, fullCode, id }`, and `merchantIds`\n * in the per-merchant mode. Null for any other delivery.\n */\nexport function readIfoodPresence(payload: unknown): { merchantIds: readonly string[] | null } | null {\n const code = firstString(payload, [[\"fullCode\"], [\"code\"]]);\n if (code?.toUpperCase() !== KEEPALIVE) return null;\n const ids = pick(payload, \"merchantIds\");\n return { merchantIds: Array.isArray(ids) ? ids.filter((id): id is string => typeof id === \"string\") : null };\n}\n","import {\n outboundResultOf,\n type AdapterCallContext,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n} from \"../core/adapter\";\nimport { firstString } from \"../core/payload-read\";\nimport { readIfoodOrder } from \"./normalize\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * The iFood adapter's order read (FUT-5800): `GET /order/v1.0/orders/{id}`.\n *\n * iFood's events carry only the order id, so a PLACED with no items is marked\n * `orderToFetch` (`./normalize.ts`) and the engine's `marketplace.fetch-order`\n * job calls this, after the webhook's row is committed, never inside the\n * request. The order iFood serves has the fields the event's `order` would\n * have carried, so it is normalized by the same reader: a fetched order and a\n * carried one land identically.\n *\n * How an answer is read:\n * - 2xx with an order: the order, with the merchant its `merchant.id` names\n * (the engine refuses one naming another merchant than the connection's).\n * - 2xx that is not JSON: retried. 2xx naming another order, or no items: refused.\n * - 401: the cached token is forgotten and a new one asked for, ONCE, in the\n * same call. A second 401 is our credentials refused (`own`), as is a 403\n * (the merchant has not authorized this app) and a token grant iFood refuses.\n * - 404: retried. ESTIMATED: an order read right after its PLACED may not be\n * served yet; the job's attempt bound ends it.\n * - Everything else: the engine's one rule (`outboundResultOf`).\n */\n\nconst orderResourceUrl = (externalOrderId: string): string =>\n `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`;\n\n/** One authenticated GET, or the token's refusal or retry in its place. */\nasync function getOrder(\n ctx: AdapterCallContext,\n externalOrderId: string,\n): Promise<{ response: MarketplaceHttpResponse } | Exclude<FetchOrderResult, { kind: \"order\" }>> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) {\n return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"iFood answered the token grant without a token\" } : auth;\n }\n const response = await ctx.http({\n method: \"GET\",\n url: orderResourceUrl(externalOrderId),\n headers: { Authorization: `Bearer ${auth.token}`, Accept: \"application/json\" },\n });\n return { response };\n}\n\n/** The order in a 2xx answer, or why it is not one. */\nfunction orderOf(body: string, externalOrderId: string, missingStreetNumber: string): FetchOrderResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body) as unknown;\n } catch {\n return { kind: \"retry\", reason: \"iFood answered the order read with a body that is not JSON\" };\n }\n const named = firstString(parsed, [[\"id\"]]);\n if (named !== null && named !== externalOrderId) {\n return { kind: \"refused\", status: 200, message: `iFood answered order ${named} for ${externalOrderId}` };\n }\n const order = readIfoodOrder(parsed, externalOrderId, missingStreetNumber);\n if (!order) return { kind: \"refused\", status: 200, message: \"iFood answered an order with no items\" };\n return { kind: \"order\", order: { ...order, externalMerchantId: firstString(parsed, [[\"merchant\", \"id\"]]) } };\n}\n\n/** What a non-2xx answer means for the fetch. */\nfunction failureOf(response: MarketplaceHttpResponse): Exclude<FetchOrderResult, { kind: \"order\" }> {\n const message = response.body.slice(0, 300);\n if (response.status === 401 || response.status === 403) {\n return { kind: \"refused\", status: response.status, message, own: true };\n }\n if (response.status === 404) return { kind: \"retry\", reason: `status 404: ${message}` };\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: `status ${response.status}` } : result;\n}\n\n/** Fetch one order iFood's event only named. Never throws: no answer is a retry. */\nexport async function ifoodFetchOrder(\n ctx: AdapterCallContext,\n ref: { externalOrderId: string },\n options: { missingStreetNumber: string },\n): Promise<FetchOrderResult> {\n try {\n let answer = await getOrder(ctx, ref.externalOrderId);\n if (\"response\" in answer && answer.response.status === 401) {\n // A token that went stale under us: forget it and try once with a new one.\n ctx.tokens.delete(ifoodTokenKey(ctx));\n answer = await getOrder(ctx, ref.externalOrderId);\n }\n if (!(\"response\" in answer)) return answer;\n const { response } = answer;\n if (response.status >= 200 && response.status < 300) {\n return orderOf(response.body, ref.externalOrderId, options.missingStreetNumber);\n }\n return failureOf(response);\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n","import { outboundResultOf, type MarketplaceHttpRequest } from \"../core/adapter\";\nimport type { LinkCallContext, LinkCode, LinkGrant, LinkResult, LinkedMerchant, MarketplaceLinking } from \"../core/linking-port\";\nimport { asString, pick } from \"../core/payload-read\";\nimport { IFOOD_API } from \"./outbound\";\n\n/**\n * iFood's DISTRIBUTED-APP authentication, the wire format only (FUT-5613).\n * Read 2026-11-26 off iFood's own pages, served as Markdown at\n * https://developer.ifood.com.br/pt-BR/docs/guides/modules/authentication/distributed.md\n * and .../merchant/endpoints.md:\n *\n * - `POST /authentication/v1.0/oauth/userCode`, form `clientId` → 200\n * `{ userCode, authorizationCodeVerifier, verificationUrl,\n * verificationUrlComplete, expiresIn }` (\"valid for 10 minutes\", 600).\n * - `POST /authentication/v1.0/oauth/token`, form `grantType=authorization_code`,\n * `clientId`, `clientSecret`, `authorizationCode`, `authorizationCodeVerifier`\n * → 200 `{ accessToken, type: \"bearer\", expiresIn }` (6 hours by default)\n * and a refresh token (\"returns an access token and a refresh token\").\n * - The same URL, `grantType=refresh_token`, `clientId`, `clientSecret`,\n * `refreshToken`.\n * - `GET /merchant/v1.0/merchants?page=&size=` (size default 100) → 200\n * `[{ id, name, corporateName }]`: every store the token covers.\n *\n * ESTIMATED, not settled by those pages:\n * - the refresh token's FIELD name in the token answer: the page's table\n * lists only `accessToken`, `type`, `expiresIn`; `refreshToken` (the name\n * the request takes) is read, and the snake-case twin as a fallback;\n * - whether a refresh ROTATES the refresh token: a new one is stored when\n * answered, the old one kept when not;\n * - the refresh token's own lifetime (unstated: \"if the refreshToken\n * expires, the user must authorize again\"): a refused refresh marks the\n * connection FAILED for the store to link again;\n * - the status of a wrong or used authorization code: any final 4xx is\n * `refused`.\n */\n\nconst USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;\nconst TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;\nconst MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;\n\n/** iFood's documented lifetime of a user code, used when the answer states none. */\nconst USER_CODE_SECONDS = 600;\n/** iFood's documented default lifetime of an access token: 6 hours. */\nconst ACCESS_TOKEN_SECONDS = 21_600;\n/** One page of the merchant list; iFood's documented default. */\nconst MERCHANT_PAGE_SIZE = 100;\n/** A ceiling on pages read, so a misbehaving answer cannot loop. */\nconst MAX_MERCHANT_PAGES = 20;\n\nconst FORM = { \"Content-Type\": \"application/x-www-form-urlencoded\" };\n\nfunction json(body: string): unknown {\n try {\n return body === \"\" ? null : (JSON.parse(body) as unknown);\n } catch {\n return null;\n }\n}\n\n/** One call whose 2xx body `read` turns into the value; anything else ends it. */\nasync function call<T>(\n ctx: LinkCallContext,\n request: MarketplaceHttpRequest,\n read: (body: unknown) => T | null,\n): Promise<LinkResult<T>> {\n try {\n const response = await ctx.http(request);\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n const value = read(json(response.body));\n return value === null\n ? { kind: \"refused\", status: response.status, message: \"iFood's answer is not the documented shape\" }\n : { kind: \"ok\", value };\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\nconst positive = (value: unknown, fallback: number): number =>\n typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : fallback;\n\nfunction codeOf(body: unknown): LinkCode | null {\n const userCode = asString(pick(body, \"userCode\"));\n const verifier = asString(pick(body, \"authorizationCodeVerifier\"));\n const verificationUrl = asString(pick(body, \"verificationUrl\"));\n if (!userCode || !verifier || !verificationUrl) return null;\n return {\n userCode,\n verifier,\n verificationUrl,\n verificationUrlComplete: asString(pick(body, \"verificationUrlComplete\")) ?? verificationUrl,\n expiresInSeconds: positive(pick(body, \"expiresIn\"), USER_CODE_SECONDS),\n };\n}\n\nfunction grantOf(body: unknown, requireRefresh: boolean): LinkGrant | null {\n const accessToken = asString(pick(body, \"accessToken\"));\n const refreshToken = asString(pick(body, \"refreshToken\")) ?? asString(pick(body, \"refresh_token\"));\n if (!accessToken || (requireRefresh && !refreshToken)) return null;\n return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, \"expiresIn\"), ACCESS_TOKEN_SECONDS) };\n}\n\nfunction merchantsOf(body: unknown): LinkedMerchant[] | null {\n if (!Array.isArray(body)) return null;\n return body.flatMap((raw: unknown) => {\n const id = asString(pick(raw, \"id\"));\n return id ? [{ id, name: asString(pick(raw, \"name\")), corporateName: asString(pick(raw, \"corporateName\")) }] : [];\n });\n}\n\nconst tokenRequest = (fields: Record<string, string>): MarketplaceHttpRequest => ({\n method: \"POST\",\n url: TOKEN_URL,\n headers: FORM,\n body: new URLSearchParams(fields).toString(),\n});\n\n/** Every merchant the token covers, page by page until a short page. */\nasync function listMerchants(ctx: LinkCallContext, accessToken: string): Promise<LinkResult<LinkedMerchant[]>> {\n const all: LinkedMerchant[] = [];\n for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {\n const answer = await call(\n ctx,\n {\n method: \"GET\",\n url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,\n headers: { Authorization: `Bearer ${accessToken}` },\n },\n merchantsOf,\n );\n if (answer.kind !== \"ok\") return answer;\n all.push(...answer.value);\n if (answer.value.length < MERCHANT_PAGE_SIZE) break;\n }\n return { kind: \"ok\", value: all };\n}\n\n/** The iFood adapter's linking half. */\nexport const IFOOD_LINKING: MarketplaceLinking = {\n requestCode: (ctx) =>\n call(\n ctx,\n { method: \"POST\", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },\n codeOf,\n ),\n exchange: (ctx, input) =>\n call(\n ctx,\n tokenRequest({\n grantType: \"authorization_code\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n authorizationCode: input.authorizationCode,\n authorizationCodeVerifier: input.verifier,\n }),\n (body) => grantOf(body, true),\n ),\n refresh: (ctx, input) =>\n call(\n ctx,\n tokenRequest({\n grantType: \"refresh_token\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n refreshToken: input.refreshToken,\n }),\n (body) => grantOf(body, false),\n ),\n merchants: (ctx, input) => listMerchants(ctx, input.accessToken),\n};\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type MarketplaceHttpRequest,\n type MarketplaceHttpResponse,\n type OutboundResult,\n} from \"../core/adapter\";\nimport type { MarketplaceAvailability, StorePauseRef, StorePauseRequest, StorePauseResult } from \"../core/pause-port\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * iFood's half of the store pause (FUT-4851): the Merchant API's\n * INTERRUPTIONS, a closure with its own id, a start and an end, that does not\n * touch the store's opening hours.\n *\n * - List: `GET /merchant/v1.0/merchants/{merchantId}/interruptions`\n * (active and future interruptions).\n * - Create: `POST …/interruptions` with `{ id, description, start, end }`,\n * 201 with the interruption.\n * - Delete: `DELETE …/interruptions/{interruptionId}`, 204.\n *\n * iFood's developer portal refuses our reader (403), so the paths, verbs and\n * the body's `description`/`start`/`end` come from two public third-party\n * clients of the API (README, \"Pausing a store\"): ESTIMATED until the\n * homologation run. Also ESTIMATED: that iFood takes the client's own `id`.\n * It is sent, but the adapter does not rely on it: every create is preceded\n * by a list, and an interruption is ours when it carries our id OR, where\n * iFood assigned its own, exactly the end and the description the create\n * sent, so a retry after a lost answer never makes a second one and a resume\n * by key deletes the one that landed. An interruption the owner made by hand\n * is neither. ESTIMATED too: that there is no call to move an interruption's\n * end (so no `extend`: the engine creates the new one, then deletes the old);\n * that iFood ACCEPTS the two overlapping for that moment (if it refuses an\n * overlap, the renewal is FAILED with iFood's words and the old interruption\n * still holds to its own end); and how iFood reads a\n * time: one client says the offset is discarded and the time read as the\n * store's own clock, so the time goes out as the store's wall clock WITH its\n * offset, which reads the same either way. A 404 on delete is \"already gone\".\n */\n\nconst interruptionsUrl = (merchantId: string): string =>\n `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`;\n\ntype Settled = Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** One authenticated call: the raw answer, or the result that ends it. */\nasync function call(\n ctx: AdapterCallContext,\n request: Omit<MarketplaceHttpRequest, \"headers\"> & { json?: unknown },\n): Promise<MarketplaceHttpResponse | Settled> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : auth;\n const response = await ctx.http({\n method: request.method,\n url: request.url,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.json === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.json === undefined ? {} : { body: JSON.stringify(request.json) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n return { kind: \"retry\", reason: \"iFood refused the token\" };\n}\n\nconst settled = (value: MarketplaceHttpResponse | Settled): value is Settled => \"kind\" in value;\n\n/** The answer as anything but 2xx, read the engine's way. */\nfunction notOk(response: MarketplaceHttpResponse): Settled | null {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? null : result;\n}\n\n/** One interruption as the list answers it, read defensively. */\ninterface Interruption {\n id: string;\n end: string | null;\n description: string | null;\n}\n\n/** The interruptions on the merchant, or the result that ends the call. */\nasync function listInterruptions(ctx: AdapterCallContext, merchantId: string): Promise<Interruption[] | Settled> {\n const response = await call(ctx, { method: \"GET\", url: interruptionsUrl(merchantId) });\n if (settled(response)) return response;\n const failure = notOk(response);\n if (failure) return failure;\n try {\n const parsed = JSON.parse(response.body === \"\" ? \"[]\" : response.body) as unknown;\n if (!Array.isArray(parsed)) return [];\n return parsed.flatMap((entry: unknown) => {\n const value = (entry ?? {}) as { id?: unknown; end?: unknown; description?: unknown };\n if (typeof value.id !== \"string\") return [];\n return [\n {\n id: value.id,\n end: typeof value.end === \"string\" ? value.end : null,\n description: typeof value.description === \"string\" ? value.description : null,\n },\n ];\n });\n } catch {\n return { kind: \"retry\", reason: \"iFood answered the interruption list with something that is not JSON\" };\n }\n}\n\n/**\n * Whether iFood's `end` is the instant the create sent. An `end` that states\n * its zone (`Z` or an offset) is compared as an instant, and only as one: an\n * owner's interruption at another instant is never claimed because its digits\n * look like ours. Only an `end` with no zone (iFood echoing the store's own\n * clock) is compared as the store's wall clock.\n */\nfunction sameEnd(end: string, until: Date, timeZone: string): boolean {\n const sent = ifoodLocalTime(until, timeZone);\n if (end === sent) return true;\n if (/(?:[zZ]|[+-]\\d{2}:?\\d{2})$/u.test(end)) {\n const parsed = Date.parse(end);\n return !Number.isNaN(parsed) && Math.floor(parsed / 1000) === Math.floor(until.getTime() / 1000);\n }\n return end.slice(0, 19) === sent.slice(0, 19);\n}\n\n/**\n * The interruption the create under `key` made: by our id, or by the end and\n * description it carried, never one the engine already holds (`keep`).\n */\nfunction ours(\n list: readonly Interruption[],\n key: string,\n sent: { until: Date; reason: string; timeZone: string } | null,\n keep: readonly string[] = [],\n): Interruption | undefined {\n const candidates = list.filter((entry) => !keep.includes(entry.id));\n const byKey = candidates.find((entry) => entry.id === key);\n if (byKey || !sent) return byKey;\n return candidates.find(\n (entry) => entry.description === sent.reason && entry.end !== null && sameEnd(entry.end, sent.until, sent.timeZone),\n );\n}\n\ninterface WallClock {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n}\n\n/** The wall clock of `date` in `timeZone`. */\nfunction wallClock(date: Date, timeZone: string): WallClock {\n const format = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n });\n const clock: WallClock = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };\n for (const part of format.formatToParts(date)) {\n if (part.type in clock) clock[part.type as keyof WallClock] = Number(part.value);\n }\n return clock;\n}\n\nconst pad = (value: number, width = 2): string => String(value).padStart(width, \"0\");\n\n/**\n * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.\n * Read the same whether iFood honours the offset or reads the store's clock.\n */\nexport function ifoodLocalTime(date: Date, timeZone: string): string {\n const local = wallClock(date, timeZone);\n const asUtc = Date.UTC(local.year, local.month - 1, local.day, local.hour, local.minute, local.second);\n const offset = Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60_000);\n const abs = Math.abs(offset);\n return (\n `${pad(local.year, 4)}-${pad(local.month)}-${pad(local.day)}` +\n `T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}` +\n `${offset < 0 ? \"-\" : \"+\"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`\n );\n}\n\n/** The created interruption's id: iFood's answer, else the one the engine sent. */\nfunction createdId(body: string, sent: string): string {\n try {\n const id = (JSON.parse(body) as { id?: unknown }).id;\n return typeof id === \"string\" && id !== \"\" ? id : sent;\n } catch {\n return sent;\n }\n}\n\n/** Close the store until `request.until`: find one a lost answer created under the key, else create it. */\nexport function ifoodPause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> {\n return answeredPause(async () => {\n const list = await listInterruptions(ctx, request.merchantId);\n if (!Array.isArray(list)) return list;\n const landed = ours(list, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);\n if (landed) return { kind: \"paused\", externalId: landed.id, until: request.until };\n const response = await call(ctx, {\n method: \"POST\",\n url: interruptionsUrl(request.merchantId),\n json: {\n id: request.key,\n description: request.reason,\n start: ifoodLocalTime(ctx.now, request.timeZone),\n end: ifoodLocalTime(request.until, request.timeZone),\n },\n });\n if (settled(response)) return response;\n const failure = notOk(response);\n if (failure) return failure;\n return { kind: \"paused\", externalId: createdId(response.body, request.key), until: request.until };\n });\n}\n\n/** Delete THIS interruption: by its id, or the one a lost answer created under the key (by id, or by its end and description). */\nexport function ifoodResume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult> {\n return answered(async () => {\n let id = ref.externalId;\n if (id === null && ref.key !== null) {\n const list = await listInterruptions(ctx, ref.merchantId);\n if (!Array.isArray(list)) return list;\n id = ours(list, ref.key, ref.sent, ref.keep)?.id ?? null;\n }\n // Nothing of ours stands: there is nothing to delete.\n if (id === null) return { kind: \"accepted\" };\n const response = await call(ctx, { method: \"DELETE\", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });\n if (settled(response)) return response;\n // Already gone: it ended, or a person removed it.\n if (response.status === 404) return { kind: \"accepted\" };\n return outboundResultOf(response);\n });\n}\n\n/** {@link answered} for a pause: a call that never got an answer is a retry. */\nasync function answeredPause(run: () => Promise<StorePauseResult>): Promise<StorePauseResult> {\n try {\n return await run();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** iFood's availability capability: interruptions, no extend. */\nexport const IFOOD_AVAILABILITY: MarketplaceAvailability = {\n kind: \"interruption\",\n pause: ifoodPause,\n resume: ifoodResume,\n};\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nimport { IFOOD_CATALOGUE } from \"./catalogue\";\nimport { IFOOD_CATALOGUE_READER } from \"./catalogue-read\";\nimport { IFOOD_COURIER } from \"./courier\";\nimport { ifoodFetchOrder } from \"./fetch-order\";\nimport { IFOOD_LINKING } from \"./linking\";\nimport { normalizeIfoodEvent, readIfoodPresence, verifyIfoodSignature } from \"./normalize\";\nimport {\n IFOOD_ACKNOWLEDGEMENT,\n IFOOD_PORTAL_URL,\n ifoodConfirm,\n ifoodInformStatus,\n ifoodOrderCancellationReasons,\n ifoodRequestCancellation,\n ifoodStatusPrerequisite,\n ifoodStatusSupported,\n} from \"./outbound\";\nimport { IFOOD_AVAILABILITY } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.\n *\n * The owner's rule: adapters live inside the lib, one per subpath, and no\n * provider-specific branch exists anywhere outside an adapter and its\n * registration. Everything iFood is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port.\n *\n * ```ts\n * import { createIfoodAdapter } from \"@12-apps/marketplace/ifood\";\n * import { IFOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/ifood/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })] });\n * ```\n */\n\n/** The provider id iFood is registered under. */\nexport const IFOOD_PROVIDER = \"IFOOD\";\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: IfoodReasonCode = \"503\";\n\n/** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */\nexport const IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\nexport interface IfoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: IfoodAdapterCopy;\n}\n\n/**\n * Build the iFood adapter. Its static reasons are the fallback: each order's\n * own are read from iFood in a job after its ingest (FUT-5984).\n */\nexport function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {\n const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: IFOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n cancelAfterAccept: true,\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n confirmTakesPreparationTime: false,\n // How long iFood takes, at most, to answer a cancellation request: its\n // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off\n // iFood's documentation, which names no answer deadline: iFood answers a\n // request in seconds when it answers at all, so 5 minutes is generous.\n // A host overrides it with the engine's `cancellationWindowMs`.\n cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,\n // Told what iFood has an endpoint for (ESTIMATED, see `./outbound.ts`): ready for\n // pickup, and dispatched for a merchant bag. Never \"handed over\": iFood's own\n // CONCLUDED is that.\n statusSteps: [\"READY\", \"DISPATCHED\"],\n // \"Retorne `202 Accepted` em até 5 segundos\" (Events `webhook-overview`, FUT-5984).\n webhookAnswerStatus: 202,\n // CFM: the store accepted on iFood's own app (FUT-5653).\n marketplaceConfirms: true,\n // A step is told only once iFood took the confirm (FUT-5673).\n statusAfterConfirm: true,\n },\n normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),\n readSignature: (header) => header(\"x-ifood-signature\") ?? header(\"x-signature\"),\n verifySignature: verifyIfoodSignature,\n cancellationReasons: () => reasons,\n // The Catalog API v2.0: each item is written and paused through the API (FUT-4768).\n catalogue: IFOOD_CATALOGUE,\n // The same API read back: the menu the store keeps on iFood, for the host to import (FUT-951).\n catalogueReader: IFOOD_CATALOGUE_READER,\n confirm: (ctx, order) => ifoodConfirm(ctx, order),\n requestCancellation: ifoodRequestCancellation,\n // iFood's events carry only the order id: a PLACED with no items is fetched (FUT-5800).\n fetchOrder: (ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions),\n statusSupported: ifoodStatusSupported,\n informStatus: ifoodInformStatus,\n statusPrerequisite: ifoodStatusPrerequisite,\n // The presence heartbeat, the events' acknowledgment and each order's own reasons (FUT-5984).\n presence: readIfoodPresence,\n acknowledgement: IFOOD_ACKNOWLEDGEMENT,\n orderCancellationReasons: ifoodOrderCancellationReasons,\n // The Merchant API's interruptions: an id and an end per closure (FUT-4851).\n availability: IFOOD_AVAILABILITY,\n // The distributed-app authorization: a store links the software's own app (FUT-5613).\n linking: IFOOD_LINKING,\n // iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).\n courier: IFOOD_COURIER,\n // No per-order deep link is known, so the portal, where a live order is\n // on the first screen.\n appLink: () => IFOOD_PORTAL_URL,\n };\n}\n\nexport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nexport { normalizeIfoodEvent, readIfoodOrder, readIfoodPresence, verifyIfoodSignature } from \"./normalize\";\nexport { ifoodFetchOrder } from \"./fetch-order\";\nexport { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from \"./catalogue\";\nexport { IFOOD_CATALOGUE_READER } from \"./catalogue-read\";\nexport { IFOOD_LINKING } from \"./linking\";\nexport { IFOOD_COURIER, readIfoodCourierEvent } from \"./courier\";\nexport { IFOOD_IMAGE_BASE_URL } from \"./catalogue-snapshot\";\nexport { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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AA,MAC1B,iBAAiB;AAAA,MACjB,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAM7B,4BAA4B;AAAA;AAAA;AAAA;AAAA,MAI5B,aAAa,CAAC,SAAS,YAAY;AAAA;AAAA,MAEnC,qBAAqB;AAAA;AAAA,MAErB,qBAAqB;AAAA;AAAA,MAErB,oBAAoB;AAAA,IACtB;AAAA,IACA,WAAW,wBAAC,YAAY,oBAAoB,SAAS,gBAAgB,GAA1D;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,mBAAmB,KAAK,OAAO,aAAa,GAA/D;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA;AAAA,IAErB,WAAW;AAAA;AAAA,IAEX,iBAAiB;AAAA,IACjB,SAAS,wBAAC,KAAK,UAAU,aAAa,KAAK,KAAK,GAAvC;AAAA,IACT,qBAAqB;AAAA;AAAA,IAErB,YAAY,wBAAC,KAAK,UAAU,gBAAgB,KAAK,OAAO,gBAAgB,GAA5D;AAAA,IACZ,iBAAiB;AAAA,IACjB,cAAc;AAAA,IACd,oBAAoB;AAAA;AAAA,IAEpB,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,0BAA0B;AAAA;AAAA,IAE1B,cAAc;AAAA;AAAA,IAEd,SAAS;AAAA;AAAA,IAET,SAAS;AAAA;AAAA;AAAA,IAGT,SAAS,6BAAM,kBAAN;AAAA,EACX;AACF;AA/DgB;","names":["parsed","call","list","parsed","categoryId","catalogUrl","failureOf","ok","parse","answered","categoryId","parsed","orderUrl","call","read","parsed","failureOf","TOKEN_URL","call","read","call","parsed","list"]}