@12-apps/marketplace 1.12.0 → 1.14.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 (64) hide show
  1. package/ADOPTING.md +184 -0
  2. package/README.md +39 -4
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-nUyZpLzz.d.ts → adapter-szxo9ohc.d.ts} +84 -3
  6. package/dist/{chunk-L6FG6T4S.js → chunk-BNWRIR5J.js} +2 -2
  7. package/dist/{chunk-LACBT6NC.js → chunk-BTKVZAJI.js} +1 -1
  8. package/dist/chunk-BTKVZAJI.js.map +1 -0
  9. package/dist/{chunk-45ZVN5XI.js → chunk-MDXSVE7Q.js} +707 -255
  10. package/dist/chunk-MDXSVE7Q.js.map +1 -0
  11. package/dist/{chunk-MIPNQ7X5.js → chunk-R3BUW5PX.js} +53 -6
  12. package/dist/chunk-R3BUW5PX.js.map +1 -0
  13. package/dist/{client-Ctas7WCS.d.ts → client-CaZiG7Lw.d.ts} +1 -1
  14. package/dist/{engine-CIy9P7Cq.d.ts → engine-CgKBbk9J.d.ts} +127 -3
  15. package/dist/hono/index.d.ts +2 -2
  16. package/dist/hono/index.js +2 -2
  17. package/dist/ifood/index.d.ts +26 -3
  18. package/dist/ifood/index.js +301 -140
  19. package/dist/ifood/index.js.map +1 -1
  20. package/dist/index.d.ts +29 -5
  21. package/dist/index.js +54 -6
  22. package/dist/index.js.map +1 -1
  23. package/dist/keeta/index.d.ts +2 -2
  24. package/dist/keeta/index.js +2 -2
  25. package/dist/manifest/server.d.ts +4 -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 +14 -5
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +17 -3
  33. package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
  34. package/src/core/acceptance.ts +12 -6
  35. package/src/core/acknowledge.ts +189 -0
  36. package/src/core/adapter.ts +76 -2
  37. package/src/core/cancellation.ts +10 -6
  38. package/src/core/conformity.ts +63 -0
  39. package/src/core/connection-stamp.ts +61 -0
  40. package/src/core/engine.ts +3 -2
  41. package/src/core/fetch-order.ts +54 -12
  42. package/src/core/ingest.ts +6 -0
  43. package/src/core/integration.ts +19 -4
  44. package/src/core/link-store.ts +2 -4
  45. package/src/core/marketplace-confirmed.ts +229 -0
  46. package/src/core/order-reasons.ts +119 -0
  47. package/src/core/outbound.ts +5 -1
  48. package/src/core/pipeline.ts +27 -1
  49. package/src/core/ports.ts +2 -0
  50. package/src/core/registry.ts +28 -2
  51. package/src/core/state.ts +10 -0
  52. package/src/core/status-job.ts +86 -3
  53. package/src/core/types.ts +6 -0
  54. package/src/ifood/fetch-order.ts +103 -0
  55. package/src/ifood/index.ts +31 -4
  56. package/src/ifood/normalize.ts +39 -3
  57. package/src/ifood/outbound.ts +131 -27
  58. package/src/index.ts +18 -0
  59. package/src/server/jobs.ts +57 -4
  60. package/src/server/webhook.ts +27 -4
  61. package/dist/chunk-45ZVN5XI.js.map +0 -1
  62. package/dist/chunk-LACBT6NC.js.map +0 -1
  63. package/dist/chunk-MIPNQ7X5.js.map +0 -1
  64. /package/dist/{chunk-L6FG6T4S.js.map → chunk-BNWRIR5J.js.map} +0 -0
package/ADOPTING.md CHANGED
@@ -443,3 +443,187 @@ ETA are the host's own columns.
443
443
 
444
444
  **Copy.** The engine adds no copy key; every sentence ("Código não confere",
445
445
  "Voltando para a loja") is the host's.
446
+
447
+ ## 11. iFood: the order fetched after PLACED (FUT-5800)
448
+
449
+ iFood's events name an order without carrying it: a PLACED is
450
+ `{ id, code: "PLC", fullCode: "PLACED", orderId, merchantId, createdAt }`, and
451
+ the order itself is `GET /order/v1.0/orders/{orderId}`. The iFood adapter now
452
+ marks a PLACED that carries no items `orderToFetch` and implements
453
+ `fetchOrder`, so a PLACED by id goes through the engine's existing order-fetch
454
+ path, the one 99Food and Keeta already use. A PLACED that does carry the order
455
+ (a replay, an older payload) is ingested from its body as before.
456
+
457
+ **The path is the webhook only.** The software connects to iFood as one
458
+ centralized app that iFood calls back (owner, FUT-5798: "no 30-second
459
+ polling"), so the engine has no events poller and never calls
460
+ `events:polling`. Since section 12, each recorded event is acknowledged
461
+ (`events/acknowledgment`, from a job), which iFood's Order homologation asks.
462
+
463
+ **The contract.**
464
+
465
+ | | |
466
+ |---|---|
467
+ | **What the host binds** | Nothing new. The `marketplace.fetch-order` job already arrives with `MARKETPLACE_JOBS` (bind `{ engine }`); the `enqueue` port carries it and the `http` port makes its `GET`. A host that holds the job (its `enqueue` answers "not enqueued") holds every iFood order: each waits PENDING and the reconciliation sweep re-queues it. |
468
+ | **Delivery** | At least once. iFood redelivers a webhook it got no 2xx for; a second copy of an event is expected, never an error. |
469
+ | **Recorded before answered** | The webhook answers 2xx only after the delivery's inbox row is written (PENDING, "order details to fetch"). That 2xx is the acknowledgement: a delivery whose row could not be written answers no 2xx (the write's throw reaches the host's error handler), and iFood delivers it again. |
470
+ | **Dedupe** | By event id, at the inbox's unique `(provider, eventId)`: a redelivered PLACED is `duplicate`, queues nothing and calls nobody. By order id, at ingest's `(provider, externalOrderId)`: a second PLACED for the same order under another event id, or the same order also delivered with its body, fetches at most again and still lands ONE order. |
471
+ | **When iFood is called** | Never in the webhook request. The request queues `marketplace.fetch-order` (`{ clientId, inboxId }`, dedupe key `marketplace.fetch-order:<inboxId>`) after the row is written; the job reads the row, calls `GET /order/v1.0/orders/{id}` with the connection's bearer token (the adapter's token cache, the linked grant for a linked store) and ingests the answer through the one ingest path. The acceptance window counts from when the event arrived, not from when the fetch returned. |
472
+ | **Retry and backoff** | 3 attempts, exponential from 5 s. Retried: 404 (an order iFood has not replicated yet, ESTIMATED), 408, 425, 429, 5xx, a timeout or a network error, and a 2xx whose body is not JSON. Refused at once (row FAILED, no retry): a 2xx naming another order or carrying no items, and any other final 4xx. The last attempt settles the row FAILED (`order fetch failed: …`). The `marketplace.reconcile-inbox` sweep (every 5 min) re-queues a FAILED or still-PENDING row older than 2 minutes, until the row has been tried `maxInboxAttempts` times. |
473
+ | **Terminal state** | The inbox row: PROCESSED (ingested), IGNORED (cancelled before its body arrived), or FAILED with its reason once its attempts are spent. A FAILED row is never re-run past `maxInboxAttempts`; it stays as the evidence. |
474
+ | **401: credentials refused** | A 401 on the order read forgets the cached token and asks for a new one, once, inside the same attempt. A second 401, a 403 (the merchant has not authorized the app), or a token grant iFood refuses with a final 4xx, is our credentials refused, not the order's fault: the job does not retry it, settles the row FAILED (`order fetch failed: refused 401: …`), stamps the connection `status: "FAILED"` (what the connections screen shows) and calls `publishChanged`. The stamp is the engine's, for every adapter whose `fetchOrder` answers an `own` 4xx refusal (99Food and Keeta on a refused token grant too). No tight loop: the next try is the sweep's, at its 5-minute cadence and within the row's attempt bound. Only the credentials the call was made with are judged: a store that entered new ones meanwhile is not stamped. Re-entering the credentials resets the status to UNVERIFIED, and the next fetch that succeeds on credentials stamped FAILED sets them VERIFIED again (`lastVerifiedAt` too); the sweep then ingests what is still within its bound. |
475
+
476
+ **What the host does on the bump.** Nothing to code: confirm the
477
+ `marketplace.fetch-order` job runs on the worker (it was registered with the
478
+ other jobs since 1.x), and that the iFood webhook is registered. An iFood
479
+ order then reaches `order.create` as it did with a body. The outcome the
480
+ webhook answers for a PLACED by id is `{ received: true, outcome: "awaitingOrder" }`.
481
+
482
+ **What the fetched order carries.** The same `NormalizedMarketplaceOrder` a
483
+ PLACED with its body produces (lines with their SKU, name, quantity, unit price
484
+ and note; the buyer; the total, delivery fee, subtotal and discounts; the
485
+ order type, who delivers, the address and the pickup code), plus
486
+ `externalMerchantId` from the order's `merchant.id`: an order naming another
487
+ merchant than the connection's is refused FAILED, as for 99Food. The canonical
488
+ shape has no field for an item's options or for the payment methods; the raw
489
+ order is not stored by the engine.
490
+
491
+ ## 12. iFood homologation conformity (FUT-5984, FUT-5653, FUT-5673)
492
+
493
+ The contract of this release, written before its code: every case below is a
494
+ test that failed on `main` (`be17871d`, 2026-12-02: `npx vitest run` of the six
495
+ files named in the table, 22 failed and 12 passed; the passing 12 are the
496
+ "unchanged" rows, pinned so they stay unchanged). The iFood pages it follows
497
+ were read on 2026-12-02 as Markdown (`developer.ifood.com.br/pt-BR/docs/…/<page>.md`):
498
+ Events `webhook-overview`, `webhook-best-practices`, `presence`,
499
+ `polling-overview` (its API reference), `homologation`; Order `endpoints`,
500
+ `cancellation`, `homologation`; Authentication `intro`.
501
+
502
+ ### 12.1 The cases
503
+
504
+ | id | event / state / provider | `main` today (measured) | this release | test |
505
+ |---|---|---|---|---|
506
+ | W1 | an iFood delivery, per-store or app address, recorded | `200` | `202 Accepted`, after the inbox row is written ("Retorne `202 Accepted` em até 5 segundos", `webhook-overview`); a redelivery too | `server/__tests__/ifood-webhook-answer.test.ts` |
507
+ | W2 | any other marketplace | `200` | `200`, unchanged: the answer status is the adapter's `capabilities.webhookAnswerStatus`, absent = 200 | same |
508
+ | W3 | a refusal (bad signature, no store) or a processing failure | `401` / `500` | unchanged | same |
509
+ | K1 | iFood `KEEPALIVE` (`{code, fullCode, id}`, every 30 s, no merchant) on the app's address, signed by the app's key | `401` (no merchant → no store) | `202`, no statement (no merchant lookup, no connection read), no inbox row: the signature is checked against the app's own key, `appCredentials` for both environments (`presence`: "KEEPALIVE … `X-IFood-Signature`"; "`202 Accepted` → merchant(s) ficam online") | same |
510
+ | K2 | `KEEPALIVE` unsigned, signed by another key, or no app configured | `401` | `401`, unchanged | same |
511
+ | K3 | `KEEPALIVE` in iFood's per-merchant mode (`merchantIds` in the body) | `401` | `202` `{ merchantIds }` naming every merchant it asked about: while the software answers, every store it serves is online, the per-app mode's meaning. The per-app mode is iFood's default ("Por aplicativo (padrão)", configured on the Developer Portal) and is the one to register; the per-merchant answer only keeps a portal switched to it from taking every store offline | same |
512
+ | K4 | `KEEPALIVE` on a store's own address, signed by its key | `200 {ignored: "unrecognized_payload"}` | `202`, no inbox row; a bad signature stays `401` | same |
513
+ | A1 | an iFood event recorded in the inbox (fresh) | nothing | `marketplace.acknowledge` `{ clientId, provider }` queued after the row is written, key `marketplace.acknowledge:<inboxId>`; a redelivery queues nothing; the request calls nobody | `__tests__/acknowledgment.test.ts` |
514
+ | A2 | the job | none exists | `POST /events/v1.0/events/acknowledgment` with `[{ id }]` of every event of that store recorded in the last 8 h and not yet acknowledged, up to 2000 a call (`polling-overview`: "Limite: até 2000 IDs por requisição"); 2xx stamps `acknowledged_at` on exactly those rows; a second run sends nothing ("apenas uma vez por evento") | same |
515
+ | A7 | the marketplace refuses the batch for good (a final 4xx, not our credentials) | — | given up on: stamped and logged at error, never resent (one bad id cannot make every reconcile pass resend the store's events for 8 h); our own credentials refused leave them owed | same |
516
+ | A3 | the call fails (5xx, 429, timeout) | — | retried (3 attempts, exponential from 10 s); the rows stay owed; the last attempt leaves them for the sweep. A final 4xx is logged and leaves them owed until the 8 h window closes. Never blocks or fails the ingest | same |
517
+ | A4 | an enqueue lost, or a job that gave up | — | the `marketplace.reconcile-inbox` pass also re-queues one job per (store, marketplace) with events still owed inside the window | same |
518
+ | A5 | an event older than 8 h | — | never acknowledged (iFood keeps events 8 h) | same |
519
+ | A6 | a marketplace whose adapter states no `acknowledgement` (99Food, Keeta, Rappi) | nothing | nothing | same |
520
+ | R1 | an iFood order ingested | static reasons only, no call | `marketplace.cancellation-reasons` `{ clientId, orderId }` queued after the ingest's commit, key `…:<orderId>` | `__tests__/cancellation-reasons.test.ts` |
521
+ | R2 | the job | none exists | `GET /order/v1.0/orders/{id}/cancellationReasons` with the connection's bearer; `{ reasons: [{ code, description }] }` (or a bare array) is kept on the order (`marketplace_acceptances.cancellation_reasons`) for its life; a second run calls nobody. `engine.orderReasons(clientId, orderId)` and `orderStates(…).cancellationReasons` answer it, each code labelled by the pack when the pack names it, else by iFood's own `description` | same |
522
+ | R3 | the read fails | — | retried (3 attempts); the last leaves the column null and the order's reasons are the adapter's static list (the fallback) | same |
523
+ | R4 | the store refuses with a code of the order's list | the code must be in the static list; the body was `{ reason: <label>, cancellationCode: <code> }` | accepted; the body is exactly `{ "reason": "<code>" }` (`cancellation`: `-d '{"reason": "503"}'`) | same |
524
+ | R5 | a code not in the order's list | judged against the static list | `INVALID_REASON` naming the order's codes | same |
525
+ | R6 | the static fallback | body as R4 on `main` | `{ "reason": "<code>" }` | same |
526
+ | R7 | a refusal validated against the static list, the order's list stored before the send | — | the validated code is sent (resolved against the order's list, else the static one it was validated against); iFood's answer decides, never a FAILED of ours with no call | same |
527
+ | R8 | iFood answers `{ reasons: [] }` | — | not kept: the static list stays the order's (an empty list would refuse every refusal) | same |
528
+ | D1 | READY of an iFood order `deliveredBy: MERCHANT` | skipped ("does not take READY") | `POST /orders/{id}/readyToPickup`, SENT (`endpoints`: "Para entrega própria, notifique o pedido pronto via `POST /orders/{id}/readyToPickup` antes de despachar via `/dispatch`"; the verb is the Endpoints page's POST; the homologation page's PUT is the doc conflict, see 12.3) | `__tests__/status-conformity.test.ts` |
529
+ | D2 | DISPATCHED of a merchant bag with no READY told | `dispatch` alone | `readyToPickup` first (its own READY row), then `dispatch`, in that order, in the same run | same |
530
+ | D3 | DISPATCHED while READY is SENDING under another run | `dispatch` sent | retried (the dispatch waits); nothing sent | same |
531
+ | D4 | DISPATCHED with READY SENT (or FAILED) | `dispatch` | `dispatch`, unchanged | same |
532
+ | D5 | a fleet bag's DISPATCHED | skipped | skipped, unchanged | same |
533
+ | S1 | any status step of an ACCEPTED order whose confirm is still owed (`confirmed_at` and `confirm_failed_at` null), on a marketplace that states `statusAfterConfirm` (iFood only) | sent | retried, no row, no call (FUT-5673 item 1) | same |
534
+ | S2 | the confirm failed (`confirm_failed_at`) | sent | skipped ("the marketplace never took the store's confirm"), no row | same |
535
+ | S3 | still owed on the last attempt | sent | skipped, never sent before the confirm | same |
536
+ | S4 | the confirm taken | sent | sent, unchanged | same |
537
+ | S5 | 99Food, Keeta, Rappi (no `statusAfterConfirm`), confirm owed or failed | sent | sent, unchanged: FUT-5673 is iFood's | `__tests__/status-adapters.test.ts` |
538
+ | T1 | the store's iFood token 30 s from its `expiresIn` | renewed (60 s margin) | used: "Renove tokens … apenas quando expirados, não antecipadamente" (Order `homologation`) | `ifood/__tests__/token.test.ts` |
539
+ | T2 | the token expired | renewed | renewed, unchanged | same |
540
+ | T3 | a 401 on an order call | token forgotten, the attempt answers `retry` (the queue retries 30 s later) | token forgotten, a new one bought and the call made again, once, inside the same call ("Prepare seu aplicativo para solicitar um novo token quando receber status 401", Authentication `intro`) | same |
541
+ | T4 | a second 401 | — | `retry`, no third grant | same |
542
+ | T5 | a linked store's access token 30 s from expiry | refreshed (60 s margin) | used | same |
543
+ | C0 | iFood `CFM` / `CONFIRMED` | normalizes with no meaning (IGNORED, "no order body") | `NormalizedEvent.marketplaceConfirmed: true` | `__tests__/marketplace-confirmed.test.ts` |
544
+ | C1 | CFM of an order AWAITING here | IGNORED; the clock expires it later and the host cancels it | stamped `confirmed_at`, then the SAME admit + claim as a decision (`order.admit` with `decision: "ACCEPT"`, `admission: {}`: the stock ask), AWAITING → ACCEPTED, NO confirm queued (iFood has it), `onAccepted` after the commit; outcome `confirmedByMarketplace`, `accepted: true` (owner's decision on FUT-5653, 2026-12-02) | same |
545
+ | C2 | CFM whose admit the host refuses (stock ask, unmapped line, plan paused) | as C1 | stays AWAITING for a person, `confirmed_at` stamped: the clock never expires it; the person's aceite (Sim on the stock ask) goes through `decide` as ever, and its queued confirm is skipped ("already stamped"); outcome `accepted: false` with the host's `refusal` | same |
546
+ | C3 | an order accepted or stamped by CFM, past its deadline | expired | never expired: the expiry predicate adds `confirmed_at IS NULL` | same |
547
+ | C4 | CFM of an ACCEPTED order whose confirm is stamped (our confirm's echo), or of a REJECTED or EXPIRED one | IGNORED | IGNORED, unchanged | same |
548
+ | C9 | CFM of an ACCEPTED order whose confirm is not stamped (`confirmed_at` null, `confirm_failed_at` either way): a person's aceite raced the tablet's, or our confirm timed out but landed | IGNORED; the queued confirm is sent again (and a 4xx stamps `confirm_failed_at`, which S2 would then make stop every step) | `confirmed_at` stamped, no host call: the queued confirm skips ("already stamped"). With `confirm_failed_at` already set (the tablet confirmed, a person's aceite claimed it here, our duplicate confirm got a 4xx before the CFM landed) it is cleared too: iFood says the order IS confirmed, and leaving the failure would make S2 skip every later step of a confirmed order and the host show "não confirmou" (worse than `main`, where steps ignored the confirm) | same |
549
+ | C5 | CFM before its order (the PLACED's fetch still running) | IGNORED, lost | DEFERRED (PENDING, `confirmed before its order`); when an adapter that `marketplaceConfirms` ingests that order, the deferred confirmation is applied right after the ingest's commit | same |
550
+ | C6 | CFM while the store's cancellation request stands | IGNORED | `confirmed_at` stamped (the request's answer or window ends the order, not the clock); no admit, no claim | same |
551
+ | C7 | a deferred CFM still PENDING when the clock runs out | expired | the expiry sweep applies it first (one inbox read, only when rows lapsed), so the order is accepted, not expired | same |
552
+ | C8 | an AWAITING order with no CFM past its deadline | expired | expired, unchanged | same |
553
+ | N1 | `marketplace.prisma` comment on `follow_status` | "Governs the INBOUND move only: telling the marketplace … is always on" | "Off: neither side moves the other" (FUT-5673 item 2, the owner's decision); comment only, the applied migration's SQL comment is left as it is | — |
554
+
555
+ ### 12.2 Invariants
556
+
557
+ - **No order is created or cancelled differently than on `main`** except where
558
+ the table says: C1/C2/C5/C7 accept (never cancel) an AWAITING order iFood
559
+ confirmed, through the host's own admit; nothing else moves an acceptance.
560
+ - **No iFood call inside a webhook request.** The request writes the inbox row,
561
+ queues (fetch, acknowledge) and answers; KEEPALIVE reads nothing. Every iFood
562
+ call is a job's: `marketplace.fetch-order`, `marketplace.acknowledge`,
563
+ `marketplace.cancellation-reasons`, `marketplace.outbound`.
564
+ - **Every new job is durable and idempotent.** `acknowledge`: the stamp
565
+ `acknowledged_at` is the marker, the reconcile pass re-queues what is owed;
566
+ two runs racing may send an id twice (harmless: iFood answers 202 and keys on
567
+ the id). `cancellation-reasons`: the column is the marker; a lost job leaves
568
+ the static fallback. The admit + claim of a CFM is the decision path's own
569
+ transaction (all or nothing), predicated on AWAITING with no request standing.
570
+ - **Money:** a CFM goes through the host's `order.admit` (the stock ask and its
571
+ draw), never a bypass; a refused admit leaves the order for a person.
572
+ - **The normal webhook path costs no new statement.** The answer status is an
573
+ adapter constant; the acknowledge enqueue is a queue call.
574
+
575
+ ### 12.3 What is still ESTIMATED
576
+
577
+ - `readyToPickup` / `dispatch` verb: the Endpoints page says POST, the Order
578
+ homologation page says PUT. POST is kept (the more detailed page).
579
+ - Acknowledgment for a WEBHOOK app: the Events concepts page says a webhook
580
+ delivery has none; the Order homologation page asks `POST /acknowledgment`
581
+ for every event. Both are honoured (202 fast AND acknowledge).
582
+ - `cancellationReasons` answering a bare array instead of `{ reasons }`: read
583
+ either way.
584
+ - The order's list is read once, after ingest, and kept: iFood's page says it
585
+ lists the codes accepted "now", so a list can be stale by a later cancel.
586
+ iFood's own refusal of the request (CANCELLATION_REQUEST_FAILED) is then
587
+ what tells the store; re-reading before each refusal would put a call in
588
+ the dialog's path.
589
+ - In the sandbox (2026-12-02), `cancellationReasons` of an unknown order
590
+ answered 403, not 404: read as a final refusal, the static list applies.
591
+
592
+ ### 12.4 What the host binds
593
+
594
+ 1. **Migration `20261202120000_marketplace_ifood_conformity`** (additive):
595
+ `marketplace_inbox_events.acknowledged_at` and two partial indexes of the
596
+ rows still owed (per store for the job, per marketplace for the sweep), `marketplace_acceptances.cancellation_reasons` (JSONB). Sync the
597
+ partial, `prisma generate`, apply it with the bump: the engine selects both.
598
+ 2. **The two new jobs** arrive with `MARKETPLACE_JOBS`
599
+ (`marketplace.acknowledge`, `marketplace.cancellation-reasons`); let the
600
+ `enqueue` port take both names (a host that holds jobs by name must not hold
601
+ these: holding the acknowledgment makes iFood redeliver).
602
+ 3. **The app's webhook** stays one address; nothing changes for KEEPALIVE but
603
+ `appCredentials` must be bound (it already is for linking). Register the
604
+ per-app presence mode on iFood's portal.
605
+ 4. **The CFM admit** is the host's existing `order.admit`: it is called with
606
+ `decision: "ACCEPT"` and `admission: {}` outside any surface's context, like
607
+ the admin route's aceite. `onAccepted` follows. An AWAITING row whose
608
+ `orderStates(…).confirmedAt` is set is "accepted on the marketplace, waiting
609
+ for your answer" (C2): draw it so, never with a countdown.
610
+ 5. **The refusal dialog** reads the order's own reasons
611
+ (`orderStates(…).cancellationReasons`, null = `reasons(provider)`), never
612
+ the static list alone.
613
+ 6. **TypeScript-visible additions** (the release is a minor; a host with
614
+ exhaustive switches or hand-built fakes adapts):
615
+ - `DeliveryOutcome` gains `confirmedByMarketplace` (an exhaustive switch
616
+ adds the case);
617
+ - `MarketplaceOrderState.cancellationReasons` is a new required field (a
618
+ hand-built fake adds it, `null` keeps the static list);
619
+ - `MarketplaceDb.marketplaceInboxEvent.updateMany` is a new required member
620
+ (Prisma's delegate has it; a hand-built fake adds it);
621
+ - `MarketplaceCapabilities` gains the optional `webhookAnswerStatus`,
622
+ `marketplaceConfirms` and `statusAfterConfirm`, and the adapter the
623
+ optional `statusPrerequisite`, `presence`, `acknowledgement`,
624
+ `orderCancellationReasons`.
625
+ 7. **Ship the bump as one unit**: the engine selects `cancellation_reasons`
626
+ on every decision, so the partial sync, `prisma generate` and the migration
627
+ go with it; and until the refusal dialog reads the order's own reasons
628
+ (step 5), a static code iFood did not list for that order is refused
629
+ `INVALID_REASON` instead of being sent.
package/README.md CHANGED
@@ -45,7 +45,7 @@ engine code (`src/__tests__/second-adapter.test.ts`).
45
45
  | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. A link may name ONE variation of that id (`variationId`): the host's optional `order.catalogHasVariation` checks it belongs, and ingest hands it on the line as `variationRef` beside `subjectRef`. Without a variation the SKU maps to the item alone, as before. |
46
46
  | **Integration settings** | Enabled, environment, merchant id, auto-accept, acknowledgement window; credentials sealed as one blob by the host's secrets port, never returned. A connection is archived (reversible, audited), never deleted. |
47
47
  | **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. The same sweep fails a request still waiting (never delivered, or delivered and unanswered) as TIMEOUT once past its answer window, and its retries stop (the adapter's `cancellationAnswerWindowMs`, or the engine's `cancellationWindowMs`), so no request waits forever. |
48
- | **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. |
48
+ | **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`, iFood's `PLACED`, FUT-5800), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. A fetch our credentials are refused on (an `own` 4xx) is not retried by the queue and stamps the connection FAILED. Contract: [ADOPTING.md §11](./ADOPTING.md#11-ifood-the-order-fetched-after-placed-fut-5800). |
49
49
  | **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
50
50
  | **Catalogue publishing** | A store turns a product ON or OFF per connected marketplace, with an optional price for that marketplace. One row per (store, marketplace, product): PUBLISHING → PUBLISHED, WITHDRAWING → WITHDRAWN, FAILED with a failure code (and the marketplace's own words for a refusal). The `marketplace.catalogue` job makes the call; the sweep re-queues what is owed. Push or pull is the adapter's. See [Catalogue publishing](#catalogue-publishing). |
51
51
  | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, `capabilities`, and the optional `fetchOrder`, `catalogue` and `catalogueReader`. |
@@ -223,9 +223,44 @@ body fields and reason codes come from the portal's search snippets
223
223
  (2026-11-11). (Its Catalog module's pages were read whole on 2026-11-13: see
224
224
  [Catalogue publishing](#catalogue-publishing).)
225
225
  They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
226
- headers say so, so the homologation run corrects two files. Tests never reach
226
+ headers say so, so the homologation run corrects two files.
227
+
228
+ The order read (FUT-5800) is partly verified. Only the EVENT shape was seen in
229
+ the sandbox (2026-11-27): iFood's events carry only the order id (`{ id, code,
230
+ fullCode, orderId, merchantId, createdAt }`), so a PLACED with no items is
231
+ fetched with `GET /order/v1.0/orders/{id}` by the `marketplace.fetch-order` job
232
+ and ingested like a PLACED carrying its body (`src/ifood/fetch-order.ts`). The
233
+ order body's field names are still the documented ones, not yet checked against
234
+ a real sandbox order. A 404 right after the PLACED is retried (ESTIMATED: not
235
+ yet served). Webhook only: the software is one centralized iFood app, so the
236
+ adapter does not poll iFood's events (FUT-5798). Tests never reach
227
237
  iFood: the HTTP client is the host's port.
228
238
 
239
+ ## iFood homologation conformity (FUT-5984, FUT-5653, FUT-5673)
240
+
241
+ What iFood's Order and Events homologation checks, and what the engine does
242
+ for it (contract, cases and host steps: [ADOPTING.md §12](./ADOPTING.md#12-ifood-homologation-conformity-fut-5984-fut-5653-fut-5673)):
243
+
244
+ - a recorded delivery is answered `202 Accepted`; the presence heartbeat
245
+ (`KEEPALIVE`) is answered 202 with no statement, proved by the app's key;
246
+ - every recorded event is acknowledged (`events/acknowledgment`) by the
247
+ `marketplace.acknowledge` job, batched per store;
248
+ - each order's own cancellation reasons are read once
249
+ (`GET /orders/{id}/cancellationReasons`) by the
250
+ `marketplace.cancellation-reasons` job; the static list is the fallback; a
251
+ request sends `{ "reason": "<code>" }`;
252
+ - a merchant bag is made ready (`readyToPickup`) before it is dispatched, and
253
+ no step is told before the marketplace took the store's confirm;
254
+ - a token is renewed only once expired (or on a 401, once, in the same call);
255
+ - an order accepted on iFood's own app (CFM) is accepted here through the
256
+ host's admit, with no confirm sent back, and is never expired.
257
+
258
+ Type-level additions a TypeScript host meets on this bump (a minor):
259
+ `DeliveryOutcome` gains `confirmedByMarketplace`;
260
+ `MarketplaceOrderState.cancellationReasons` is a new required field;
261
+ `MarketplaceDb.marketplaceInboxEvent.updateMany` is a new required member.
262
+ Ship the migration `20261202120000_marketplace_ifood_conformity` with it.
263
+
229
264
  ## Linking a store through the software's own app (FUT-5613)
230
265
 
231
266
  A store connects iFood WITHOUT typing a client id, a secret, a webhook key or a
@@ -554,8 +589,8 @@ after 10 minutes and failed after 24 hours.
554
589
 
555
590
  | step | iFood (ESTIMATED) | 99Food (Open Delivery v1.7.1) | Keeta | Rappi |
556
591
  |---|---|---|---|---|
557
- | READY | `POST /orders/{id}/readyToPickup`, not for a merchant bag | `POST /v1/orders/{id}/readyForPickup` | `POST /v1/orders/{id}/readyForPickup` | `POST /orders/{id}/ready-for-pickup` (ESTIMATED verb; MANUAL-notification stores only) |
558
- | DISPATCHED | `POST /orders/{id}/dispatch`, merchant bag only | `POST /v1/orders/{id}/dispatch`, merchant bag only | `POST /v1/orders/{id}/dispatch`, merchant bag only | none |
592
+ | READY | `POST /orders/{id}/readyToPickup`, every bag (CONFIRMED, FUT-5984) | `POST /v1/orders/{id}/readyForPickup` | `POST /v1/orders/{id}/readyForPickup` | `POST /orders/{id}/ready-for-pickup` (ESTIMATED verb; MANUAL-notification stores only) |
593
+ | DISPATCHED | `POST /orders/{id}/dispatch`, merchant bag only, strictly after its READY | `POST /v1/orders/{id}/dispatch`, merchant bag only | `POST /v1/orders/{id}/dispatch`, merchant bag only | none |
559
594
  | HANDED_OVER | none | merchant bag `delivered`, take-out `pickedUp`, fleet none | merchant bag `delivered`; no take-out (`PICKED_UP` is never sent), fleet none | none |
560
595
 
561
596
  Sources: Open Delivery `openapi.yaml` (read 2026-11-25), Rappi's portal
@@ -1,5 +1,5 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-nUyZpLzz.js';
2
- import { O as OpenDeliveryApiBaseUrls } from '../client-Ctas7WCS.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-szxo9ohc.js';
2
+ import { O as OpenDeliveryApiBaseUrls } from '../client-CaZiG7Lw.js';
3
3
 
4
4
  /**
5
5
  * The words the 99Food adapter needs from its host, and nothing else.
@@ -12,10 +12,10 @@ import {
12
12
  openDeliveryStatus,
13
13
  openDeliverySwitchAvailability,
14
14
  verifyOpenDeliverySignature
15
- } from "../chunk-L6FG6T4S.js";
15
+ } from "../chunk-BNWRIR5J.js";
16
16
  import "../chunk-M2V4RFMA.js";
17
17
  import "../chunk-BD7DS3XM.js";
18
- import "../chunk-LACBT6NC.js";
18
+ import "../chunk-BTKVZAJI.js";
19
19
  import {
20
20
  __name
21
21
  } from "../chunk-7QVYU63E.js";
@@ -372,6 +372,12 @@ interface NormalizedEvent {
372
372
  * names no courier step.
373
373
  */
374
374
  courier?: NormalizedCourierEvent | null;
375
+ /**
376
+ * OPTIONAL (FUT-5653). The store accepted the order in the marketplace's own
377
+ * app (iFood's `CFM`): an order still AWAITING here is accepted through the
378
+ * host's admit, with no confirm sent back. Carries no order body.
379
+ */
380
+ marketplaceConfirmed?: boolean;
375
381
  }
376
382
 
377
383
  /**
@@ -918,7 +924,53 @@ interface MarketplaceCapabilities {
918
924
  * Absent or empty: the engine tells it nothing.
919
925
  */
920
926
  statusSteps?: readonly StatusStep[];
927
+ /**
928
+ * OPTIONAL. The HTTP status a recorded delivery is answered with (FUT-5984:
929
+ * iFood wants `202 Accepted`). Absent: 200. Refusals and failures keep theirs.
930
+ */
931
+ webhookAnswerStatus?: 200 | 202;
932
+ /**
933
+ * OPTIONAL. The marketplace announces that the store accepted an order in the
934
+ * marketplace's own app (`NormalizedEvent.marketplaceConfirmed`, FUT-5653).
935
+ * Its ingest then applies a confirmation that arrived before the order.
936
+ */
937
+ marketplaceConfirms?: boolean;
938
+ /**
939
+ * OPTIONAL. A status step is told only after the marketplace took the
940
+ * store's confirm (`confirmedAt`, FUT-5673: iFood refuses a step of an order
941
+ * it has not confirmed). Absent: steps never wait on the confirm.
942
+ */
943
+ statusAfterConfirm?: boolean;
944
+ }
945
+ /**
946
+ * A marketplace's presence heartbeat (FUT-5984: iFood's `KEEPALIVE`), read off
947
+ * a delivery: `merchantIds` when it asks about named merchants (its
948
+ * per-merchant mode), null when it asks about the whole app.
949
+ */
950
+ interface PresenceProbe {
951
+ merchantIds: readonly string[] | null;
952
+ }
953
+ /** Acknowledging recorded events to the marketplace (FUT-5984: iFood's `events/acknowledgment`). */
954
+ interface MarketplaceAcknowledgement {
955
+ /** At most this many event ids per call. */
956
+ batchSize: number;
957
+ /** How long the marketplace keeps an event: an older one is never acknowledged. */
958
+ retentionMs: number;
959
+ /** Acknowledge these event ids, in one call. */
960
+ send(ctx: AdapterCallContext, eventIds: readonly string[]): Promise<OutboundResult>;
961
+ }
962
+ /** One cancellation reason the marketplace lists for one order: its code and its own words. */
963
+ interface OrderCancellationReason {
964
+ code: string;
965
+ description: string;
921
966
  }
967
+ /** One order's reasons read from the marketplace, or the refusal / retry of the read. */
968
+ type OrderCancellationReasonsResult = {
969
+ kind: "reasons";
970
+ reasons: OrderCancellationReason[];
971
+ } | Exclude<OutboundResult, {
972
+ kind: "accepted";
973
+ }>;
922
974
  /**
923
975
  * A step of the order the store tells the marketplace about (FUT-4653): the
924
976
  * order is ready for pickup, the courier left, the order was handed over.
@@ -1031,7 +1083,11 @@ interface MarketplaceAdapter {
1031
1083
  readSignature(header: (name: string) => string | null): string | null;
1032
1084
  /** Is this delivery's signature the one this store's secret would produce? */
1033
1085
  verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;
1034
- /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */
1086
+ /**
1087
+ * The marketplace's documented reasons, static and offline: a dialog never
1088
+ * waits on the network. With `orderCancellationReasons`, the fallback of an
1089
+ * order whose own list could not be read.
1090
+ */
1035
1091
  cancellationReasons(): readonly CancellationReason[];
1036
1092
  /** Tell the marketplace the store accepted the order. */
1037
1093
  confirm(ctx: AdapterCallContext, order: OutboundOrderRef, input: {
@@ -1055,11 +1111,36 @@ interface MarketplaceAdapter {
1055
1111
  informStatus?(ctx: AdapterCallContext, order: OutboundOrderRef, facts: StatusFacts): Promise<OutboundResult | {
1056
1112
  kind: "unsupported";
1057
1113
  }>;
1114
+ /**
1115
+ * OPTIONAL. The step that must be told before this one for this kind of
1116
+ * order (FUT-5984: iFood's dispatch of a merchant bag follows its
1117
+ * `readyToPickup`), or null. The status job sends it first when it is not
1118
+ * told yet.
1119
+ */
1120
+ statusPrerequisite?(facts: StatusFacts): StatusStep | null;
1121
+ /**
1122
+ * OPTIONAL. A delivery that is the marketplace's presence heartbeat, not an
1123
+ * event (FUT-5984: iFood's `KEEPALIVE`), or null. Answered 202 once its
1124
+ * signature is proved, with nothing recorded.
1125
+ */
1126
+ presence?(payload: unknown): PresenceProbe | null;
1127
+ /** OPTIONAL. Acknowledging recorded events (FUT-5984). Absent: nothing is acknowledged. */
1128
+ readonly acknowledgement?: MarketplaceAcknowledgement;
1129
+ /**
1130
+ * OPTIONAL. Read the reasons the marketplace accepts for cancelling THIS
1131
+ * order (FUT-5984: iFood's `GET /orders/{id}/cancellationReasons`). Called
1132
+ * only from the `marketplace.cancellation-reasons` job. Absent: the static
1133
+ * `cancellationReasons()` are every order's.
1134
+ */
1135
+ orderCancellationReasons?(ctx: AdapterCallContext, order: {
1136
+ externalOrderId: string;
1137
+ }): Promise<OrderCancellationReasonsResult>;
1058
1138
  /**
1059
1139
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
1060
1140
  * marketplace whose events carry no order body). Called only from the
1061
1141
  * `marketplace.fetch-order` job. An adapter whose events always carry the
1062
- * order (iFood) leaves it out.
1142
+ * order leaves it out. A final `refused` marked `own` with a 4xx status is
1143
+ * our credentials refused: the engine stamps the connection FAILED.
1063
1144
  */
1064
1145
  fetchOrder?(ctx: AdapterCallContext, order: {
1065
1146
  externalOrderId: string;
@@ -1112,4 +1193,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
1112
1193
  /** A call that never got an answer is a retry, with the reason a log can read. */
1113
1194
  declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
1114
1195
 
1115
- export { type MarketplaceCatalogue as $, type AdapterCallContext as A, type CatalogueReadResult as B, type CatalogueMenuEntry as C, type CatalogueReadWarning as D, type CatalogueReadWarningCode as E, type CatalogueSnapshot as F, type CatalogueSnapshotCategory as G, type CatalogueSnapshotItem as H, type CatalogueSnapshotOption as I, type CatalogueSnapshotOptionGroup as J, type CatalogueStoredImage as K, type CatalogueWarningCode as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type CourierTrackingCallResult as Q, type CourierTrackingResult as R, type StorePauseRequest as S, type FetchOrderResult as T, type LinkCallContext as U, type LinkCode as V, type LinkGrant as W, type LinkResult as X, type LinkedMerchant as Y, type MarketplaceAppCredentialsPort as Z, type MarketplaceCapabilities as _, type NormalizedMarketplaceOrder as a, type MarketplaceCourier as a0, type MarketplaceCourierAnswer as a1, type MarketplaceCourierEngine as a2, type MarketplaceCourierFacts as a3, type MarketplaceCourierStep as a4, type MarketplaceCourierTracking as a5, type MarketplaceCourierVehicle as a6, type MarketplaceCredentials as a7, type MarketplaceDeliveredBy as a8, type MarketplaceDiscountSponsor as a9, type MarketplaceHttp as aa, type MarketplaceHttpRequest as ab, type MarketplaceHttpResponse as ac, type MarketplaceLifecycle as ad, type MarketplaceLinkAttemptDelegate as ae, type MarketplaceOrderType as af, type NormalizedAddress as ag, type NormalizedBuyer as ah, type NormalizedOrderDiscount as ai, type NormalizedOrderLine as aj, type OutboundOrderRef as ak, PROVIDER_ID_PATTERN as al, type PickupCodeCallResult as am, type PickupCodeValidation as an, type StatusFacts as ao, type StatusStep as ap, type ValidatePickupCodeInput as aq, answered as ar, centsFromMajor as as, outboundResultOf as at, tokenGrantResultOf as au, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type MarketplaceLinking as g, type MarketplaceCourierApi as h, type NormalizedCourierEvent as i, type StorePauseResult as j, type StorePauseRef as k, type MarketplaceProvider as l, type CancellationReason as m, type AdapterGrant as n, type AdapterTokenCache as o, type CancellationOutcome as p, type CancellationRequestInput as q, type CatalogueCallContext as r, type CatalogueFailure as s, type CatalogueImage as t, type CatalogueItem as u, type CatalogueItemRef as v, type CataloguePublishResult as w, type CatalogueReadContext as x, type CatalogueReadNotice as y, type CatalogueReadRefusalCode as z };
1196
+ export { type MarketplaceCapabilities as $, type AdapterCallContext as A, type CatalogueReadResult as B, type CatalogueMenuEntry as C, type CatalogueReadWarning as D, type CatalogueReadWarningCode as E, type FetchOrderResult as F, type CatalogueSnapshot as G, type CatalogueSnapshotCategory as H, type CatalogueSnapshotItem as I, type CatalogueSnapshotOption as J, type CatalogueSnapshotOptionGroup as K, type CatalogueStoredImage as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type CatalogueWarningCode as Q, type CourierTrackingCallResult as R, type StorePauseRequest as S, type CourierTrackingResult as T, type LinkCallContext as U, type LinkCode as V, type LinkGrant as W, type LinkResult as X, type LinkedMerchant as Y, type MarketplaceAcknowledgement as Z, type MarketplaceAppCredentialsPort as _, type NormalizedMarketplaceOrder as a, type MarketplaceCatalogue as a0, type MarketplaceCourier as a1, type MarketplaceCourierAnswer as a2, type MarketplaceCourierEngine as a3, type MarketplaceCourierFacts as a4, type MarketplaceCourierStep as a5, type MarketplaceCourierTracking as a6, type MarketplaceCourierVehicle as a7, type MarketplaceCredentials as a8, type MarketplaceDeliveredBy as a9, type MarketplaceDiscountSponsor as aa, type MarketplaceHttp as ab, type MarketplaceHttpRequest as ac, type MarketplaceHttpResponse as ad, type MarketplaceLifecycle as ae, type MarketplaceLinkAttemptDelegate as af, type MarketplaceOrderType as ag, type NormalizedAddress as ah, type NormalizedBuyer as ai, type NormalizedOrderDiscount as aj, type NormalizedOrderLine as ak, type OrderCancellationReason as al, type OrderCancellationReasonsResult as am, type OutboundOrderRef as an, PROVIDER_ID_PATTERN as ao, type PickupCodeCallResult as ap, type PickupCodeValidation as aq, type PresenceProbe as ar, type StatusFacts as as, type StatusStep as at, type ValidatePickupCodeInput as au, answered as av, centsFromMajor as aw, outboundResultOf as ax, tokenGrantResultOf as ay, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type MarketplaceLinking as g, type MarketplaceCourierApi as h, type NormalizedCourierEvent as i, type StorePauseResult as j, type StorePauseRef as k, type MarketplaceProvider as l, type CancellationReason as m, type AdapterGrant as n, type AdapterTokenCache as o, type CancellationOutcome as p, type CancellationRequestInput as q, type CatalogueCallContext as r, type CatalogueFailure as s, type CatalogueImage as t, type CatalogueItem as u, type CatalogueItemRef as v, type CataloguePublishResult as w, type CatalogueReadContext as x, type CatalogueReadNotice as y, type CatalogueReadRefusalCode as z };
@@ -14,7 +14,7 @@ import {
14
14
  answered,
15
15
  outboundResultOf,
16
16
  tokenGrantResultOf
17
- } from "./chunk-LACBT6NC.js";
17
+ } from "./chunk-BTKVZAJI.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-L6FG6T4S.js.map
478
+ //# sourceMappingURL=chunk-BNWRIR5J.js.map
@@ -31,4 +31,4 @@ export {
31
31
  tokenGrantResultOf,
32
32
  answered
33
33
  };
34
- //# sourceMappingURL=chunk-LACBT6NC.js.map
34
+ //# sourceMappingURL=chunk-BTKVZAJI.js.map
@@ -0,0 +1 @@
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 * OPTIONAL. The HTTP status a recorded delivery is answered with (FUT-5984:\n * iFood wants `202 Accepted`). Absent: 200. Refusals and failures keep theirs.\n */\n webhookAnswerStatus?: 200 | 202;\n /**\n * OPTIONAL. The marketplace announces that the store accepted an order in the\n * marketplace's own app (`NormalizedEvent.marketplaceConfirmed`, FUT-5653).\n * Its ingest then applies a confirmation that arrived before the order.\n */\n marketplaceConfirms?: boolean;\n /**\n * OPTIONAL. A status step is told only after the marketplace took the\n * store's confirm (`confirmedAt`, FUT-5673: iFood refuses a step of an order\n * it has not confirmed). Absent: steps never wait on the confirm.\n */\n statusAfterConfirm?: boolean;\n}\n\n/**\n * A marketplace's presence heartbeat (FUT-5984: iFood's `KEEPALIVE`), read off\n * a delivery: `merchantIds` when it asks about named merchants (its\n * per-merchant mode), null when it asks about the whole app.\n */\nexport interface PresenceProbe {\n merchantIds: readonly string[] | null;\n}\n\n/** Acknowledging recorded events to the marketplace (FUT-5984: iFood's `events/acknowledgment`). */\nexport interface MarketplaceAcknowledgement {\n /** At most this many event ids per call. */\n batchSize: number;\n /** How long the marketplace keeps an event: an older one is never acknowledged. */\n retentionMs: number;\n /** Acknowledge these event ids, in one call. */\n send(ctx: AdapterCallContext, eventIds: readonly string[]): Promise<OutboundResult>;\n}\n\n/** One cancellation reason the marketplace lists for one order: its code and its own words. */\nexport interface OrderCancellationReason {\n code: string;\n description: string;\n}\n\n/** One order's reasons read from the marketplace, or the refusal / retry of the read. */\nexport type OrderCancellationReasonsResult =\n | { kind: \"reasons\"; reasons: OrderCancellationReason[] }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\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 /**\n * The marketplace's documented reasons, static and offline: a dialog never\n * waits on the network. With `orderCancellationReasons`, the fallback of an\n * order whose own list could not be read.\n */\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. The step that must be told before this one for this kind of\n * order (FUT-5984: iFood's dispatch of a merchant bag follows its\n * `readyToPickup`), or null. The status job sends it first when it is not\n * told yet.\n */\n statusPrerequisite?(facts: StatusFacts): StatusStep | null;\n /**\n * OPTIONAL. A delivery that is the marketplace's presence heartbeat, not an\n * event (FUT-5984: iFood's `KEEPALIVE`), or null. Answered 202 once its\n * signature is proved, with nothing recorded.\n */\n presence?(payload: unknown): PresenceProbe | null;\n /** OPTIONAL. Acknowledging recorded events (FUT-5984). Absent: nothing is acknowledged. */\n readonly acknowledgement?: MarketplaceAcknowledgement;\n /**\n * OPTIONAL. Read the reasons the marketplace accepts for cancelling THIS\n * order (FUT-5984: iFood's `GET /orders/{id}/cancellationReasons`). Called\n * only from the `marketplace.cancellation-reasons` job. Absent: the static\n * `cancellationReasons()` are every order's.\n */\n orderCancellationReasons?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<OrderCancellationReasonsResult>;\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 leaves it out. A final `refused` marked `own` with a 4xx status is\n * our credentials refused: the engine stamps the connection FAILED.\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":";;;;;AAkWA,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":[]}