@12-apps/marketplace 1.11.0 → 1.12.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 (51) hide show
  1. package/ADOPTING.md +90 -1
  2. package/README.md +37 -1
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CD0SfdVS.d.ts → adapter-nUyZpLzz.d.ts} +325 -173
  6. package/dist/{chunk-YWMEIMO3.js → chunk-45ZVN5XI.js} +114 -24
  7. package/dist/chunk-45ZVN5XI.js.map +1 -0
  8. package/dist/{chunk-DCWOQ5PN.js → chunk-L6FG6T4S.js} +2 -2
  9. package/dist/{chunk-TVZU4HNT.js → chunk-LACBT6NC.js} +1 -1
  10. package/dist/{chunk-TVZU4HNT.js.map → chunk-LACBT6NC.js.map} +1 -1
  11. package/dist/{chunk-OS4TSIFU.js → chunk-MIPNQ7X5.js} +2 -2
  12. package/dist/{client-11sncog4.d.ts → client-Ctas7WCS.d.ts} +1 -1
  13. package/dist/{engine-C_3RK8wC.d.ts → engine-CIy9P7Cq.d.ts} +34 -5
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +7 -2
  17. package/dist/ifood/index.js +184 -30
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +162 -65
  21. package/dist/index.js.map +1 -1
  22. package/dist/keeta/index.d.ts +2 -18
  23. package/dist/keeta/index.js +12 -3
  24. package/dist/keeta/index.js.map +1 -1
  25. package/dist/manifest/server.d.ts +2 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +2 -2
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/src/core/adapter.ts +6 -0
  33. package/src/core/courier-port.ts +100 -0
  34. package/src/core/courier.ts +153 -0
  35. package/src/core/engine.ts +4 -1
  36. package/src/core/lifecycle.ts +27 -4
  37. package/src/core/outbound-queue.ts +24 -11
  38. package/src/core/outbound.ts +8 -6
  39. package/src/core/pickup-code.ts +136 -0
  40. package/src/core/pipeline.ts +15 -6
  41. package/src/core/ports.ts +23 -1
  42. package/src/core/status-store.ts +2 -3
  43. package/src/core/types.ts +56 -4
  44. package/src/ifood/courier.ts +210 -0
  45. package/src/ifood/index.ts +4 -0
  46. package/src/ifood/normalize.ts +7 -0
  47. package/src/index.ts +16 -0
  48. package/src/keeta/normalize.ts +21 -6
  49. package/dist/chunk-YWMEIMO3.js.map +0 -1
  50. /package/dist/{chunk-DCWOQ5PN.js.map → chunk-L6FG6T4S.js.map} +0 -0
  51. /package/dist/{chunk-OS4TSIFU.js.map → chunk-MIPNQ7X5.js.map} +0 -0
@@ -14,7 +14,7 @@ import {
14
14
  answered,
15
15
  outboundResultOf,
16
16
  tokenGrantResultOf
17
- } from "./chunk-TVZU4HNT.js";
17
+ } from "./chunk-LACBT6NC.js";
18
18
  import {
19
19
  __name
20
20
  } from "./chunk-7QVYU63E.js";
@@ -475,4 +475,4 @@ export {
475
475
  normalizeOpenDeliveryEventAs,
476
476
  normalizeOpenDeliveryOrderAs
477
477
  };
478
- //# sourceMappingURL=chunk-DCWOQ5PN.js.map
478
+ //# sourceMappingURL=chunk-L6FG6T4S.js.map
@@ -31,4 +31,4 @@ export {
31
31
  tokenGrantResultOf,
32
32
  answered
33
33
  };
34
- //# sourceMappingURL=chunk-TVZU4HNT.js.map
34
+ //# sourceMappingURL=chunk-LACBT6NC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n}\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order (iFood) leaves it out.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAkRA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
1
+ {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n}\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order (iFood) leaves it out.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /**\n * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check\n * and the tracking read. Absent: neither is offered, and the host says so.\n */\n readonly courier?: MarketplaceCourierApi;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAwRA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
@@ -18,7 +18,7 @@ import {
18
18
  CatalogueRetryError,
19
19
  FetchOrderRetryError,
20
20
  OutboundRetryError
21
- } from "./chunk-YWMEIMO3.js";
21
+ } from "./chunk-45ZVN5XI.js";
22
22
  import {
23
23
  __name
24
24
  } from "./chunk-7QVYU63E.js";
@@ -651,4 +651,4 @@ export {
651
651
  MARKETPLACE_JOBS,
652
652
  createApiMarketplace
653
653
  };
654
- //# sourceMappingURL=chunk-OS4TSIFU.js.map
654
+ //# sourceMappingURL=chunk-MIPNQ7X5.js.map
@@ -1,4 +1,4 @@
1
- import { O as OutboundResult } from './adapter-CD0SfdVS.js';
1
+ import { O as OutboundResult } from './adapter-nUyZpLzz.js';
2
2
 
3
3
  /**
4
4
  * The HTTP half every Open Delivery adapter shares: the token grant and its
@@ -1,4 +1,4 @@
1
- import { Z as MarketplaceDeliveredBy, a3 as MarketplaceLinkAttemptDelegate, s as CatalogueItem, r as CatalogueImage, a as NormalizedMarketplaceOrder, N as NormalizedEvent, ac as StatusStep, $ as MarketplaceHttp, V as MarketplaceAppCredentialsPort, c as MarketplaceAdapter, j as MarketplaceProvider, Y as MarketplaceCredentials, J as CatalogueWarningCode, U as LinkedMerchant, a2 as MarketplaceLifecycle, k as CancellationReason, a9 as OutboundOrderRef, b as CatalogueMenuOptions, y as CatalogueReadResult } from './adapter-CD0SfdVS.js';
1
+ import { a8 as MarketplaceDeliveredBy, ae as MarketplaceLinkAttemptDelegate, u as CatalogueItem, t as CatalogueImage, a as NormalizedMarketplaceOrder, N as NormalizedEvent, ap as StatusStep, i as NormalizedCourierEvent, a3 as MarketplaceCourierFacts, a1 as MarketplaceCourierAnswer, an as PickupCodeValidation, aa as MarketplaceHttp, Z as MarketplaceAppCredentialsPort, c as MarketplaceAdapter, l as MarketplaceProvider, a7 as MarketplaceCredentials, L as CatalogueWarningCode, Y as LinkedMerchant, ad as MarketplaceLifecycle, a4 as MarketplaceCourierStep, a2 as MarketplaceCourierEngine, m as CancellationReason, ak as OutboundOrderRef, b as CatalogueMenuOptions, B as CatalogueReadResult } from './adapter-nUyZpLzz.js';
2
2
 
3
3
  /** What the engine tells the host about the order a lifecycle event names. */
4
4
  interface MarketplaceLifecycleFacts {
@@ -286,6 +286,22 @@ interface MarketplaceOrderPort {
286
286
  * Absent: the engine cannot tell, and sends nothing.
287
287
  */
288
288
  statusHolds?(clientId: string, orderId: string, step: StatusStep): Promise<boolean>;
289
+ /**
290
+ * OPTIONAL (FUT-5665). The marketplace's courier moved: named, on the way,
291
+ * at the counter, holding the bag, or bringing it back. Store the facts on
292
+ * the order; never move it (a `COLLECTED` moves through `onLifecycle`).
293
+ * Idempotent: a redelivery is deduped, but the reconcile pass re-runs a
294
+ * FAILED row. Asked for an ACCEPTED order only, whatever the connection's
295
+ * `followStatus`. Absent: courier events are understood and ignored.
296
+ */
297
+ onCourier?(clientId: string, orderId: string, event: NormalizedCourierEvent, facts: MarketplaceCourierFacts): Promise<MarketplaceCourierAnswer>;
298
+ /**
299
+ * OPTIONAL (FUT-5665). The marketplace's verdict on the pickup code the host
300
+ * sent with `engine.validatePickupCode`. Called once per job, after the
301
+ * hand-over has committed: `INVALID` warns, it moves nothing. A throw is
302
+ * logged. Absent: the verdict is only logged.
303
+ */
304
+ onPickupCodeValidated?(clientId: string, orderId: string, validation: PickupCodeValidation): Promise<void>;
289
305
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
290
306
  summarize(clientId: string, orderIds: readonly string[]): Promise<Map<string, MarketplaceOrderSummary>>;
291
307
  }
@@ -1074,10 +1090,11 @@ interface LinkFinished {
1074
1090
  /** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */
1075
1091
  declare const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
1076
1092
  /**
1077
- * What goes out: the store's aceite, the store's cancellation request, or a
1078
- * step of the order the store reached (`status`, FUT-4653).
1093
+ * What goes out: the store's aceite, the store's cancellation request, a
1094
+ * step of the order the store reached (`status`, FUT-4653), or the pickup code
1095
+ * the store checked at the hand-over (`validatePickupCode`, FUT-5665).
1079
1096
  */
1080
- type OutboundAction = "confirm" | "requestCancellation" | "status";
1097
+ type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode";
1081
1098
  /** The outbound job's payload. Identifiers only. */
1082
1099
  interface OutboundJobPayload {
1083
1100
  clientId: string;
@@ -1090,6 +1107,12 @@ interface OutboundJobPayload {
1090
1107
  * belongs to: the owner of its SENDING claim. Absent on every other action.
1091
1108
  */
1092
1109
  claimKey?: string;
1110
+ /**
1111
+ * OPTIONAL. The pickup code a `validatePickupCode` call sends; absent on every
1112
+ * other action. The one non-identifier in the payload: a short-lived code the
1113
+ * job needs to send, which no log line prints.
1114
+ */
1115
+ code?: string;
1093
1116
  }
1094
1117
  /** The dedupe key: at most one queued call per (order, action). */
1095
1118
  declare function outboundDedupeKey(payload: OutboundJobPayload): string;
@@ -1367,6 +1390,12 @@ type DeliveryOutcome = {
1367
1390
  kind: "moved";
1368
1391
  orderId: string;
1369
1392
  lifecycle: MarketplaceLifecycle;
1393
+ }
1394
+ /** A courier event's facts were stored by the host's `onCourier` (FUT-5665). */
1395
+ | {
1396
+ kind: "courier";
1397
+ orderId: string;
1398
+ step: MarketplaceCourierStep;
1370
1399
  } | {
1371
1400
  kind: "cancelled";
1372
1401
  } | {
@@ -1407,7 +1436,7 @@ interface MarketplaceOrderState {
1407
1436
  }
1408
1437
 
1409
1438
  /** Everything the mounted engine can do, with the ports and adapters bound in. */
1410
- interface MarketplaceEngine {
1439
+ interface MarketplaceEngine extends MarketplaceCourierEngine {
1411
1440
  /** Every registered marketplace, in registration order. */
1412
1441
  providers(): readonly MarketplaceProvider[];
1413
1442
  /** Whether a provider id (a URL segment, a body field) names a registered adapter. */
@@ -1,7 +1,7 @@
1
1
  import { Hono, Context } from 'hono';
2
2
  import { ApiMarketplace, MarketplaceApiConfig, MarketplaceActor } from '../server/index.js';
3
- import '../engine-C_3RK8wC.js';
4
- import '../adapter-CD0SfdVS.js';
3
+ import '../engine-CIy9P7Cq.js';
4
+ import '../adapter-nUyZpLzz.js';
5
5
  import '@12-apps/wiring';
6
6
  import 'zod';
7
7
 
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  createApiMarketplace
3
- } from "../chunk-OS4TSIFU.js";
3
+ } from "../chunk-MIPNQ7X5.js";
4
4
  import "../chunk-SGOTN5PX.js";
5
- import "../chunk-YWMEIMO3.js";
5
+ import "../chunk-45ZVN5XI.js";
6
6
  import {
7
7
  __name
8
8
  } from "../chunk-7QVYU63E.js";
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, f as CatalogueReader, g as MarketplaceLinking, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, h as StorePauseResult, i as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CD0SfdVS.js';
1
+ import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, f as CatalogueReader, g as MarketplaceLinking, h as MarketplaceCourierApi, i as NormalizedCourierEvent, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, j as StorePauseResult, k as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-nUyZpLzz.js';
2
2
 
3
3
  /**
4
4
  * The words the iFood adapter needs from its host, and nothing else.
@@ -56,6 +56,11 @@ declare const IFOOD_CATALOGUE_READER: CatalogueReader;
56
56
  /** The iFood adapter's linking half. */
57
57
  declare const IFOOD_LINKING: MarketplaceLinking;
58
58
 
59
+ /** The courier step an iFood event names, or null. */
60
+ declare function readIfoodCourierEvent(payload: unknown, eventType: string): NormalizedCourierEvent | null;
61
+ /** iFood's courier calls, for the adapter's `courier`. */
62
+ declare const IFOOD_COURIER: MarketplaceCourierApi;
63
+
59
64
  /**
60
65
  * iFood's catalogue answer mapped into the engine's {@link CatalogueSnapshotItem}
61
66
  * (FUT-951). Pure and offline: `./catalogue-read.ts` makes the calls.
@@ -121,4 +126,4 @@ interface IfoodAdapterConfig {
121
126
  /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
122
127
  declare function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter;
123
128
 
124
- export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_IMAGE_BASE_URL, IFOOD_LINKING, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, verifyIfoodSignature };
129
+ export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_COURIER, IFOOD_IMAGE_BASE_URL, IFOOD_LINKING, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, readIfoodCourierEvent, verifyIfoodSignature };
@@ -17,7 +17,7 @@ import {
17
17
  answered,
18
18
  outboundResultOf,
19
19
  tokenGrantResultOf
20
- } from "../chunk-TVZU4HNT.js";
20
+ } from "../chunk-LACBT6NC.js";
21
21
  import {
22
22
  __name
23
23
  } from "../chunk-7QVYU63E.js";
@@ -47,10 +47,10 @@ var TOKEN_MARGIN_MS = 6e4;
47
47
  var ifoodTokenKey = /* @__PURE__ */ __name((ctx) => ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`, "ifoodTokenKey");
48
48
  function tokenOf(body) {
49
49
  try {
50
- const parsed = JSON.parse(body);
51
- if (typeof parsed.accessToken !== "string" || parsed.accessToken === "") return null;
52
- const expires = typeof parsed.expiresIn === "number" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;
53
- return { token: parsed.accessToken, expiresInSeconds: expires };
50
+ const parsed2 = JSON.parse(body);
51
+ if (typeof parsed2.accessToken !== "string" || parsed2.accessToken === "") return null;
52
+ const expires = typeof parsed2.expiresIn === "number" && parsed2.expiresIn > 0 ? parsed2.expiresIn : 3600;
53
+ return { token: parsed2.accessToken, expiresInSeconds: expires };
54
54
  } catch {
55
55
  return null;
56
56
  }
@@ -158,10 +158,10 @@ function parse(body) {
158
158
  }
159
159
  __name(parse, "parse");
160
160
  function categoryIdIn(body, name) {
161
- const parsed = parse(body);
162
- if (!Array.isArray(parsed)) return null;
161
+ const parsed2 = parse(body);
162
+ if (!Array.isArray(parsed2)) return null;
163
163
  const wanted = name.trim().toLowerCase();
164
- const found = parsed.find(
164
+ const found = parsed2.find(
165
165
  (entry) => typeof entry === "object" && entry !== null && String(entry.name ?? "").trim().toLowerCase() === wanted
166
166
  );
167
167
  return typeof found?.id === "string" ? found.id : null;
@@ -533,11 +533,11 @@ async function read(ctx) {
533
533
  const listed = await get(ctx, "categories");
534
534
  if ("kind" in listed) return listed;
535
535
  if (!ok2(listed)) return failureOf2(listed);
536
- const parsed = parse2(listed.body);
537
- if (!Array.isArray(parsed)) return unexpected("category list", listed.body);
536
+ const parsed2 = parse2(listed.body);
537
+ if (!Array.isArray(parsed2)) return unexpected("category list", listed.body);
538
538
  const categories = [];
539
539
  const notices = [];
540
- const { entries, others } = entriesOf(parsed);
540
+ const { entries, others } = entriesOf(parsed2);
541
541
  for (const other of others) notices.push(unreadableCategory(null, other));
542
542
  for (const raw of entries) {
543
543
  const category = await categoryOf(ctx, raw, notices);
@@ -558,6 +558,150 @@ var IFOOD_CATALOGUE_READER = {
558
558
  }, "read")
559
559
  };
560
560
 
561
+ // src/ifood/courier.ts
562
+ var COURIER_STEP_OF = {
563
+ ADR: "ASSIGNED",
564
+ ASSIGN_DRIVER: "ASSIGNED",
565
+ GTO: "GOING_TO_ORIGIN",
566
+ GOING_TO_ORIGIN: "GOING_TO_ORIGIN",
567
+ AAO: "ARRIVED_AT_ORIGIN",
568
+ ARRIVED_AT_ORIGIN: "ARRIVED_AT_ORIGIN",
569
+ CLT: "COLLECTED",
570
+ COLLECTED: "COLLECTED",
571
+ DELIVERY_RETURNING_TO_ORIGIN: "RETURNING_TO_ORIGIN",
572
+ DELIVERY_RETURNED_TO_ORIGIN: "RETURNED_TO_ORIGIN"
573
+ };
574
+ var VEHICLE_OF = {
575
+ MOTORCYCLE: "MOTORCYCLE",
576
+ MOTORBIKE: "MOTORCYCLE",
577
+ MOTO: "MOTORCYCLE",
578
+ BICYCLE: "BICYCLE",
579
+ BIKE: "BICYCLE",
580
+ CAR: "CAR",
581
+ CARRO: "CAR"
582
+ };
583
+ var IFOOD_COURIER_NAME_MAX = 120;
584
+ var IFOOD_COURIER_PHOTO_URL_MAX = 2048;
585
+ function httpsUrl(value) {
586
+ if (!value || value.length > IFOOD_COURIER_PHOTO_URL_MAX) return null;
587
+ try {
588
+ return new URL(value).protocol === "https:" ? value : null;
589
+ } catch {
590
+ return null;
591
+ }
592
+ }
593
+ __name(httpsUrl, "httpsUrl");
594
+ function metadataOf(payload) {
595
+ const raw = pick(payload, "metadata");
596
+ if (typeof raw !== "string") return raw;
597
+ try {
598
+ return JSON.parse(raw);
599
+ } catch {
600
+ return null;
601
+ }
602
+ }
603
+ __name(metadataOf, "metadataOf");
604
+ function readCourier(payload) {
605
+ const metadata = metadataOf(payload);
606
+ const name = firstString(metadata, [["workerName"]])?.slice(0, IFOOD_COURIER_NAME_MAX) ?? null;
607
+ const photoUrl = httpsUrl(firstString(metadata, [["workerPhotoUrl"]]));
608
+ const stated = firstString(metadata, [["workerVehicleType"]])?.toUpperCase() ?? null;
609
+ const vehicle = stated === null ? null : VEHICLE_OF[stated] ?? "OTHER";
610
+ return name === null && photoUrl === null && vehicle === null ? null : { name, photoUrl, vehicle };
611
+ }
612
+ __name(readCourier, "readCourier");
613
+ function readIfoodCourierEvent(payload, eventType) {
614
+ const step = COURIER_STEP_OF[eventType.toUpperCase()];
615
+ if (!step) return null;
616
+ return {
617
+ step,
618
+ at: firstDate(payload, [["createdAt"]]),
619
+ courier: step === "ASSIGNED" ? readCourier(payload) : null,
620
+ returning: step === "RETURNING_TO_ORIGIN" ? "RETURNING" : step === "RETURNED_TO_ORIGIN" ? "RETURNED" : null
621
+ };
622
+ }
623
+ __name(readIfoodCourierEvent, "readIfoodCourierEvent");
624
+ var orderUrl2 = /* @__PURE__ */ __name((ref, action) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(ref.externalOrderId)}/${action}`, "orderUrl");
625
+ async function call2(ctx, request) {
626
+ const auth = await bearer(ctx);
627
+ if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "no token" } : auth;
628
+ const response = await ctx.http({
629
+ method: request.method,
630
+ url: request.url,
631
+ headers: {
632
+ Authorization: `Bearer ${auth.token}`,
633
+ ...request.body === void 0 ? {} : { "Content-Type": "application/json" }
634
+ },
635
+ ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) }
636
+ });
637
+ if (response.status !== 401) return response;
638
+ ctx.tokens.delete(ifoodTokenKey(ctx));
639
+ return { kind: "retry", reason: "iFood refused the token" };
640
+ }
641
+ __name(call2, "call");
642
+ function parsed(body) {
643
+ try {
644
+ return JSON.parse(body);
645
+ } catch {
646
+ return null;
647
+ }
648
+ }
649
+ __name(parsed, "parsed");
650
+ async function validatePickupCode(ctx, order, input) {
651
+ try {
652
+ const response = await call2(ctx, { method: "POST", url: orderUrl2(order, "validatePickupCode"), body: { code: input.code } });
653
+ if ("kind" in response) return response;
654
+ const read2 = outboundResultOf(response);
655
+ if (read2.kind !== "accepted") return read2;
656
+ const valid = pick(parsed(response.body), "valid");
657
+ return typeof valid === "boolean" ? { kind: "answered", valid } : { kind: "refused", status: response.status, message: "iFood answered without a verdict", own: true };
658
+ } catch (error) {
659
+ return retryOf(error);
660
+ }
661
+ }
662
+ __name(validatePickupCode, "validatePickupCode");
663
+ function retryOf(error) {
664
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
665
+ }
666
+ __name(retryOf, "retryOf");
667
+ function numberAt(source, key) {
668
+ const value = pick(source, key);
669
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
670
+ }
671
+ __name(numberAt, "numberAt");
672
+ function plusSeconds(base, seconds) {
673
+ return seconds === null ? null : new Date(base.getTime() + seconds * 1e3);
674
+ }
675
+ __name(plusSeconds, "plusSeconds");
676
+ function readTracking(body, now) {
677
+ const trackedAt = firstDate(body, [["trackDate"]]);
678
+ const base = trackedAt ?? now;
679
+ const pickupSeconds = numberAt(body, "pickupEtaStart") ?? numberAt(body, "pickupEta");
680
+ const deliverySeconds = numberAt(body, "deliveryEtaEnd") ?? numberAt(body, "deliveryEta");
681
+ return {
682
+ pickupEtaAt: plusSeconds(base, pickupSeconds),
683
+ deliveryEtaAt: firstDate(body, [["expectedDelivery"]]) ?? plusSeconds(base, deliverySeconds),
684
+ latitude: numberAt(body, "latitude"),
685
+ longitude: numberAt(body, "longitude"),
686
+ trackedAt
687
+ };
688
+ }
689
+ __name(readTracking, "readTracking");
690
+ async function tracking(ctx, order) {
691
+ try {
692
+ const response = await call2(ctx, { method: "GET", url: orderUrl2(order, "tracking") });
693
+ if ("kind" in response) return response;
694
+ if (response.status === 404) return { kind: "notYet" };
695
+ const read2 = outboundResultOf(response);
696
+ if (read2.kind !== "accepted") return read2;
697
+ return { kind: "tracking", tracking: readTracking(parsed(response.body), ctx.now) };
698
+ } catch (error) {
699
+ return retryOf(error);
700
+ }
701
+ }
702
+ __name(tracking, "tracking");
703
+ var IFOOD_COURIER = { validatePickupCode, tracking };
704
+
561
705
  // src/ifood/linking.ts
562
706
  var USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
563
707
  var TOKEN_URL2 = `${IFOOD_API}/authentication/v1.0/oauth/token`;
@@ -575,7 +719,7 @@ function json(body) {
575
719
  }
576
720
  }
577
721
  __name(json, "json");
578
- async function call2(ctx, request, read2) {
722
+ async function call3(ctx, request, read2) {
579
723
  try {
580
724
  const response = await ctx.http(request);
581
725
  const result = outboundResultOf(response);
@@ -586,7 +730,7 @@ async function call2(ctx, request, read2) {
586
730
  return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
587
731
  }
588
732
  }
589
- __name(call2, "call");
733
+ __name(call3, "call");
590
734
  var positive = /* @__PURE__ */ __name((value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback, "positive");
591
735
  function codeOf(body) {
592
736
  const userCode = asString(pick(body, "userCode"));
@@ -626,7 +770,7 @@ var tokenRequest = /* @__PURE__ */ __name((fields) => ({
626
770
  async function listMerchants(ctx, accessToken) {
627
771
  const all = [];
628
772
  for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
629
- const answer = await call2(
773
+ const answer = await call3(
630
774
  ctx,
631
775
  {
632
776
  method: "GET",
@@ -643,12 +787,12 @@ async function listMerchants(ctx, accessToken) {
643
787
  }
644
788
  __name(listMerchants, "listMerchants");
645
789
  var IFOOD_LINKING = {
646
- requestCode: /* @__PURE__ */ __name((ctx) => call2(
790
+ requestCode: /* @__PURE__ */ __name((ctx) => call3(
647
791
  ctx,
648
792
  { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
649
793
  codeOf
650
794
  ), "requestCode"),
651
- exchange: /* @__PURE__ */ __name((ctx, input) => call2(
795
+ exchange: /* @__PURE__ */ __name((ctx, input) => call3(
652
796
  ctx,
653
797
  tokenRequest({
654
798
  grantType: "authorization_code",
@@ -659,7 +803,7 @@ var IFOOD_LINKING = {
659
803
  }),
660
804
  (body) => grantOf(body, true)
661
805
  ), "exchange"),
662
- refresh: /* @__PURE__ */ __name((ctx, input) => call2(
806
+ refresh: /* @__PURE__ */ __name((ctx, input) => call3(
663
807
  ctx,
664
808
  tokenRequest({
665
809
  grantType: "refresh_token",
@@ -680,7 +824,10 @@ var LIFECYCLE_OF = {
680
824
  DSP: "DISPATCHED",
681
825
  DISPATCHED: "DISPATCHED",
682
826
  CON: "CONCLUDED",
683
- CONCLUDED: "CONCLUDED"
827
+ CONCLUDED: "CONCLUDED",
828
+ // iFood's courier has the bag (FUT-5665): for a fleet bag, the same hand-over as DSP.
829
+ CLT: "COLLECTED",
830
+ COLLECTED: "COLLECTED"
684
831
  };
685
832
  function verifyIfoodSignature(rawBody, signature, webhookSecret) {
686
833
  return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
@@ -796,7 +943,9 @@ function readOrder(payload, externalOrderId, missingStreetNumber) {
796
943
  // never 0; `discounts` is absent when `benefits` is.
797
944
  deliveryFeeCents: firstCents(order, [["total", "deliveryFee"]]),
798
945
  subtotalCents: firstCents(order, [["total", "subTotal"]]),
799
- ...optional("discounts", readDiscounts(order))
946
+ ...optional("discounts", readDiscounts(order)),
947
+ // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.
948
+ pickupCode: firstString(order, [["delivery", "pickupCode"]])
800
949
  };
801
950
  }
802
951
  __name(readOrder, "readOrder");
@@ -820,14 +969,15 @@ function normalizeIfoodEvent(payload, options) {
820
969
  order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
821
970
  cancelled,
822
971
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
823
- ...LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}
972
+ ...LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {},
973
+ ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? void 0)
824
974
  };
825
975
  }
826
976
  __name(normalizeIfoodEvent, "normalizeIfoodEvent");
827
977
 
828
978
  // src/ifood/pause.ts
829
979
  var interruptionsUrl = /* @__PURE__ */ __name((merchantId) => `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`, "interruptionsUrl");
830
- async function call3(ctx, request) {
980
+ async function call4(ctx, request) {
831
981
  const auth = await bearer(ctx);
832
982
  if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
833
983
  const response = await ctx.http({
@@ -843,7 +993,7 @@ async function call3(ctx, request) {
843
993
  ctx.tokens.delete(ifoodTokenKey(ctx));
844
994
  return { kind: "retry", reason: "iFood refused the token" };
845
995
  }
846
- __name(call3, "call");
996
+ __name(call4, "call");
847
997
  var settled = /* @__PURE__ */ __name((value) => "kind" in value, "settled");
848
998
  function notOk(response) {
849
999
  const result = outboundResultOf(response);
@@ -851,14 +1001,14 @@ function notOk(response) {
851
1001
  }
852
1002
  __name(notOk, "notOk");
853
1003
  async function listInterruptions(ctx, merchantId) {
854
- const response = await call3(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
1004
+ const response = await call4(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
855
1005
  if (settled(response)) return response;
856
1006
  const failure = notOk(response);
857
1007
  if (failure) return failure;
858
1008
  try {
859
- const parsed = JSON.parse(response.body === "" ? "[]" : response.body);
860
- if (!Array.isArray(parsed)) return [];
861
- return parsed.flatMap((entry) => {
1009
+ const parsed2 = JSON.parse(response.body === "" ? "[]" : response.body);
1010
+ if (!Array.isArray(parsed2)) return [];
1011
+ return parsed2.flatMap((entry) => {
862
1012
  const value = entry ?? {};
863
1013
  if (typeof value.id !== "string") return [];
864
1014
  return [
@@ -878,8 +1028,8 @@ function sameEnd(end, until, timeZone) {
878
1028
  const sent = ifoodLocalTime(until, timeZone);
879
1029
  if (end === sent) return true;
880
1030
  if (/(?:[zZ]|[+-]\d{2}:?\d{2})$/u.test(end)) {
881
- const parsed = Date.parse(end);
882
- return !Number.isNaN(parsed) && Math.floor(parsed / 1e3) === Math.floor(until.getTime() / 1e3);
1031
+ const parsed2 = Date.parse(end);
1032
+ return !Number.isNaN(parsed2) && Math.floor(parsed2 / 1e3) === Math.floor(until.getTime() / 1e3);
883
1033
  }
884
1034
  return end.slice(0, 19) === sent.slice(0, 19);
885
1035
  }
@@ -935,7 +1085,7 @@ function ifoodPause(ctx, request) {
935
1085
  if (!Array.isArray(list2)) return list2;
936
1086
  const landed = ours(list2, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
937
1087
  if (landed) return { kind: "paused", externalId: landed.id, until: request.until };
938
- const response = await call3(ctx, {
1088
+ const response = await call4(ctx, {
939
1089
  method: "POST",
940
1090
  url: interruptionsUrl(request.merchantId),
941
1091
  json: {
@@ -961,7 +1111,7 @@ function ifoodResume(ctx, ref) {
961
1111
  id = ours(list2, ref.key, ref.sent, ref.keep)?.id ?? null;
962
1112
  }
963
1113
  if (id === null) return { kind: "accepted" };
964
- const response = await call3(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
1114
+ const response = await call4(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
965
1115
  if (settled(response)) return response;
966
1116
  if (response.status === 404) return { kind: "accepted" };
967
1117
  return outboundResultOf(response);
@@ -1030,6 +1180,8 @@ function createIfoodAdapter(config) {
1030
1180
  availability: IFOOD_AVAILABILITY,
1031
1181
  // The distributed-app authorization: a store links the software's own app (FUT-5613).
1032
1182
  linking: IFOOD_LINKING,
1183
+ // iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).
1184
+ courier: IFOOD_COURIER,
1033
1185
  // No per-order deep link is known, so the portal, where a live order is
1034
1186
  // on the first screen.
1035
1187
  appLink: /* @__PURE__ */ __name(() => IFOOD_PORTAL_URL, "appLink")
@@ -1041,6 +1193,7 @@ export {
1041
1193
  IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
1042
1194
  IFOOD_CATALOGUE,
1043
1195
  IFOOD_CATALOGUE_READER,
1196
+ IFOOD_COURIER,
1044
1197
  IFOOD_IMAGE_BASE_URL,
1045
1198
  IFOOD_LINKING,
1046
1199
  IFOOD_PROVIDER,
@@ -1053,6 +1206,7 @@ export {
1053
1206
  ifoodProductId,
1054
1207
  ifoodResume,
1055
1208
  normalizeIfoodEvent,
1209
+ readIfoodCourierEvent,
1056
1210
  verifyIfoodSignature
1057
1211
  };
1058
1212
  //# sourceMappingURL=index.js.map