@12-apps/marketplace 1.17.0 → 1.18.1

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 (57) hide show
  1. package/ADOPTING.md +70 -0
  2. package/README.md +7 -7
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CxzF-qGx.d.ts → adapter-ZpAWKoCk.d.ts} +116 -2
  6. package/dist/{chunk-7IYUO2KC.js → chunk-3B5EULS6.js} +2 -2
  7. package/dist/{chunk-EABVLQKK.js → chunk-BLHZ3MRB.js} +2 -2
  8. package/dist/{chunk-UZO2NILN.js → chunk-MDEIRGNL.js} +1067 -877
  9. package/dist/chunk-MDEIRGNL.js.map +1 -0
  10. package/dist/{chunk-KKFMDV5K.js → chunk-Q5RMVNU5.js} +1 -1
  11. package/dist/{chunk-KKFMDV5K.js.map → chunk-Q5RMVNU5.js.map} +1 -1
  12. package/dist/{chunk-CF5BSXE5.js → chunk-ZT6TZTLD.js} +1 -1
  13. package/dist/chunk-ZT6TZTLD.js.map +1 -0
  14. package/dist/{client-C-4QvVq3.d.ts → client-DpEq0yXb.d.ts} +1 -1
  15. package/dist/{engine-Y6Rpf5p7.d.ts → engine-DRRhAjZK.d.ts} +171 -143
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +3 -3
  18. package/dist/ifood/index.d.ts +7 -2
  19. package/dist/ifood/index.js +189 -107
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +76 -5
  23. package/dist/index.js.map +1 -1
  24. package/dist/keeta/index.d.ts +2 -2
  25. package/dist/keeta/index.js +2 -2
  26. package/dist/manifest/server.d.ts +2 -2
  27. package/dist/manifest/server.js +3 -3
  28. package/dist/rappi/index.d.ts +1 -1
  29. package/dist/rappi/index.js +1 -1
  30. package/dist/server/index.d.ts +2 -2
  31. package/dist/server/index.js +3 -3
  32. package/package.json +1 -1
  33. package/prisma/marketplace.prisma +1 -1
  34. package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
  35. package/src/core/adapter.ts +2 -1
  36. package/src/core/delivery-code.ts +119 -0
  37. package/src/core/engine.ts +10 -2
  38. package/src/core/logistics.ts +388 -0
  39. package/src/core/outbound-queue.ts +6 -1
  40. package/src/core/outbound-sweep.ts +10 -5
  41. package/src/core/outbound.ts +4 -5
  42. package/src/core/pipeline.ts +6 -1
  43. package/src/core/ports.ts +5 -2
  44. package/src/core/status-job.ts +3 -0
  45. package/src/core/status-store.ts +2 -1
  46. package/src/core/types.ts +2 -0
  47. package/src/ifood/catalogs.ts +34 -0
  48. package/src/ifood/catalogue-read.ts +30 -10
  49. package/src/ifood/catalogue.ts +34 -9
  50. package/src/ifood/index.ts +3 -0
  51. package/src/ifood/logistics.ts +38 -0
  52. package/src/ifood/normalize.ts +11 -1
  53. package/src/index.ts +10 -0
  54. package/dist/chunk-CF5BSXE5.js.map +0 -1
  55. package/dist/chunk-UZO2NILN.js.map +0 -1
  56. /package/dist/{chunk-7IYUO2KC.js.map → chunk-3B5EULS6.js.map} +0 -0
  57. /package/dist/{chunk-EABVLQKK.js.map → chunk-BLHZ3MRB.js.map} +0 -0
@@ -7,6 +7,7 @@ import type {
7
7
  CatalogueSnapshotCategory,
8
8
  CatalogueSnapshotItem,
9
9
  } from "../core/catalogue-read-port";
10
+ import { categoriesPath, defaultCatalogIdIn } from "./catalogs";
10
11
  import { availableOf, entriesOf, indexOf, itemOf, record, text } from "./catalogue-snapshot";
11
12
  import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
12
13
 
@@ -16,12 +17,16 @@ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
16
17
  * client-credentials token of its app, `bearer`), for the host to import.
17
18
  *
18
19
  * One read is, in order:
19
- * 1. `GET /categories` — the merchant's categories (CONFIRMED, the Endpoints
20
- * page as read 2026-11-13; ESTIMATED that it answers an array of
21
- * `{ id, name, status, externalCode }`, the same estimate the push makes);
22
- * 2. `GET /categories/{categoryId}/items` for each, in the list's order
23
- * (CONFIRMED, the Introduction's step 5, read 2026-11-16), mapped by
24
- * `./catalogue-snapshot.ts`.
20
+ * 1. `GET /catalogs` — the merchant's catalogs, of which the DEFAULT one is
21
+ * read (`./catalogs.ts`; CONFIRMED live against iFood's sandbox,
22
+ * 2026-12-03, FUT-6146);
23
+ * 2. `GET /catalogs/{catalogId}/categories` — its categories (CONFIRMED live,
24
+ * same run: the merchant-level `GET /categories` does not exist and
25
+ * answers 404; ESTIMATED that each entry is `{ id, name, status,
26
+ * externalCode }`, the same estimate the push makes);
27
+ * 3. `GET /categories/{categoryId}/items` for each, in the list's order
28
+ * (CONFIRMED, the Introduction's step 5, read 2026-11-16; merchant-level,
29
+ * not under the catalog), mapped by `./catalogue-snapshot.ts`.
25
30
  *
26
31
  * Pagination: none. The pages read show no page, size or cursor parameter on
27
32
  * either call (ESTIMATED that there is none), so the menu is read one category
@@ -32,8 +37,11 @@ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
32
37
  * push's `call` does); a second 401 is a `retry`;
33
38
  * - the token grant refused (400, 401, 403) is `CREDENTIALS`;
34
39
  * - 403 (the Errors page: the app is not allowed this merchant, or the
35
- * catalogue module is not enabled for it) and 404 on the category list (no
36
- * such merchant for this app, ESTIMATED) are `NOT_AUTHORIZED`;
40
+ * catalogue module is not enabled for it) is `NOT_AUTHORIZED`;
41
+ * - 404 on the catalog or category list is `REFUSED` with iFood's status and
42
+ * words: a path iFood does not have, or a resource it does not hold, is not
43
+ * a permission problem (FUT-6146: a wrong route read as "not authorized");
44
+ * - a catalog list naming no DEFAULT catalog is `REFUSED`;
37
45
  * - 429, 408, 425, 5xx and a call with no answer are `retry`;
38
46
  * - any other 4xx is `REFUSED`, with iFood's words.
39
47
  * A category whose own items answer 404 (deleted between the two calls), or
@@ -58,7 +66,8 @@ function tokenFailure(result: OutboundResult): Failure {
58
66
  function failureOf(response: MarketplaceHttpResponse): Failure {
59
67
  const result = outboundResultOf(response);
60
68
  if (result.kind !== "refused") return { kind: "retry", reason: result.kind === "retry" ? result.reason : "unexpected answer" };
61
- const code = response.status === 403 || response.status === 404 ? "NOT_AUTHORIZED" : "REFUSED";
69
+ // Only a 403 is the merchant refusing this app; a 404 is a path or resource iFood does not have (FUT-6146).
70
+ const code = response.status === 403 ? "NOT_AUTHORIZED" : "REFUSED";
62
71
  return { kind: "refused", code, status: result.status, message: result.message };
63
72
  }
64
73
 
@@ -155,8 +164,19 @@ function itemsOf(rawBody: string, categoryId: string, notices: CatalogueReadNoti
155
164
  return items;
156
165
  }
157
166
 
167
+ /** The merchant's DEFAULT catalog id, or the failure that ends the read. */
168
+ async function catalogOf(ctx: CatalogueReadContext): Promise<{ catalogId: string } | Failure> {
169
+ const listed = await get(ctx, "catalogs");
170
+ if ("kind" in listed) return listed;
171
+ if (!ok(listed)) return failureOf(listed);
172
+ const catalogId = defaultCatalogIdIn(listed.body);
173
+ return catalogId === null ? unexpected("catalog list (no DEFAULT catalog)", listed.body) : { catalogId };
174
+ }
175
+
158
176
  async function read(ctx: CatalogueReadContext): Promise<CatalogueReadResult> {
159
- const listed = await get(ctx, "categories");
177
+ const catalog = await catalogOf(ctx);
178
+ if ("kind" in catalog) return catalog;
179
+ const listed = await get(ctx, categoriesPath(catalog.catalogId));
160
180
  if ("kind" in listed) return listed;
161
181
  if (!ok(listed)) return failureOf(listed);
162
182
  const parsed = parse(listed.body);
@@ -15,6 +15,7 @@ import type {
15
15
  CatalogueWarningCode,
16
16
  PushCatalogue,
17
17
  } from "../core/catalogue-port";
18
+ import { categoriesPath, defaultCatalogIdIn } from "./catalogs";
18
19
  import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
19
20
 
20
21
  /**
@@ -27,12 +28,17 @@ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
27
28
  * it, and lives in this file only, so the homologation run corrects one file.
28
29
  *
29
30
  * One publish is, in order:
30
- * 1. the category, by name: `GET /categories`, else `POST /categories`
31
- * (`template: "DEFAULT"`);
31
+ * 1. the category, by name, in the merchant's DEFAULT catalog: `GET
32
+ * /catalogs` for its id (`./catalogs.ts`), then `GET
33
+ * /catalogs/{catalogId}/categories`, else `POST
34
+ * /catalogs/{catalogId}/categories` (`template: "DEFAULT"`). Categories
35
+ * live under a catalog: the merchant-level `/categories` route does not
36
+ * exist and answers 404 (CONFIRMED live against iFood's sandbox,
37
+ * 2026-12-03, FUT-6146);
32
38
  * 2. the photo, when the item has one: the `imagePath` iFood already holds
33
39
  * for the same photo URL, else `POST /image/upload` with a base64 data URL
34
40
  * of the bytes the host's loader reads, which answers `imagePath`;
35
- * 3. the item: `PUT /items` with `item`, `products`, `optionGroups`,
41
+ * 3. the item: `PUT /items` (merchant-level, like the photo and the status) with `item`, `products`, `optionGroups`,
36
42
  * `options` — idempotent, it replaces the whole item, and the item appears
37
43
  * at once (synchronous).
38
44
  *
@@ -110,14 +116,31 @@ function categoryIdIn(body: string, name: string): string | null {
110
116
  return typeof found?.id === "string" ? found.id : null;
111
117
  }
112
118
 
113
- /** The category named `name` on iFood, or null; the failure that ended the read otherwise. */
114
- async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {
115
- const listed = await call(ctx, "GET", "categories");
119
+ /** The merchant's DEFAULT catalog id, or the failure that ends the publish. */
120
+ async function catalogOf(ctx: CatalogueCallContext): Promise<{ catalogId: string } | Failure> {
121
+ const listed = await call(ctx, "GET", "catalogs");
122
+ if ("kind" in listed) return listed;
123
+ if (!ok(listed)) return failureOf(listed);
124
+ const catalogId = defaultCatalogIdIn(listed.body);
125
+ return catalogId === null
126
+ ? { kind: "refused", status: listed.status, message: `no DEFAULT catalog: ${listed.body.slice(0, 200)}` }
127
+ : { catalogId };
128
+ }
129
+
130
+ /** The category named `name` in the catalog, or null; the failure that ended the read otherwise. */
131
+ async function findCategoryIn(ctx: CatalogueCallContext, catalogId: string, name: string): Promise<{ id: string | null } | Failure> {
132
+ const listed = await call(ctx, "GET", categoriesPath(catalogId));
116
133
  if ("kind" in listed) return listed;
117
134
  if (!ok(listed)) return failureOf(listed);
118
135
  return { id: categoryIdIn(listed.body, name) };
119
136
  }
120
137
 
138
+ /** The category named `name` in the merchant's DEFAULT catalog, or null; the failure otherwise. */
139
+ async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {
140
+ const catalog = await catalogOf(ctx);
141
+ return "kind" in catalog ? catalog : findCategoryIn(ctx, catalog.catalogId, name);
142
+ }
143
+
121
144
  /**
122
145
  * Find the category by name, else create it, then read the list again and
123
146
  * adopt the first of that name: a POST whose answer was lost and was retried
@@ -125,16 +148,18 @@ async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{
125
148
  * (connection, name) at a time and stores the id (`ctx.category`).
126
149
  */
127
150
  async function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {
128
- const found = await findCategory(ctx, name);
151
+ const catalog = await catalogOf(ctx);
152
+ if ("kind" in catalog) return catalog;
153
+ const found = await findCategoryIn(ctx, catalog.catalogId, name);
129
154
  if ("kind" in found) return found;
130
155
  if (found.id) return { id: found.id };
131
- const created = await call(ctx, "POST", "categories", { name, status: "AVAILABLE", template: "DEFAULT" });
156
+ const created = await call(ctx, "POST", categoriesPath(catalog.catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
132
157
  if ("kind" in created) return created;
133
158
  if (!ok(created)) return failureOf(created);
134
159
  const id = (parse(created.body) as { id?: unknown } | null)?.id;
135
160
  if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
136
161
  // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.
137
- const again = await findCategory(ctx, name);
162
+ const again = await findCategoryIn(ctx, catalog.catalogId, name);
138
163
  return "id" in again && again.id ? { id: again.id } : { id };
139
164
  }
140
165
 
@@ -4,6 +4,7 @@ import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
5
  import { IFOOD_COURIER } from "./courier";
6
6
  import { IFOOD_DISPUTES } from "./disputes";
7
+ import { IFOOD_LOGISTICS } from "./logistics";
7
8
  import { ifoodFetchOrder } from "./fetch-order";
8
9
  import { IFOOD_APP_LINKING } from "./app-linking";
9
10
  import { IFOOD_LINKING } from "./linking";
@@ -121,6 +122,7 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
121
122
  courier: IFOOD_COURIER,
122
123
  // The buyer's disputes: accept, reject with iFood's reason, or one of its alternatives (FUT-6099).
123
124
  disputes: IFOOD_DISPUTES,
125
+ logistics: IFOOD_LOGISTICS,
124
126
  // No per-order deep link is known, so the portal, where a live order is
125
127
  // on the first screen.
126
128
  appLink: () => IFOOD_PORTAL_URL,
@@ -138,6 +140,7 @@ export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
138
140
  export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
139
141
  export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
140
142
  export {
143
+ IFOOD_LOGISTICS,
141
144
  IFOOD_LOGISTICS_STEPS,
142
145
  IFOOD_LOGISTICS_VEHICLES,
143
146
  ifoodLogisticsAssignDriver,
@@ -1,3 +1,4 @@
1
+ import type { DeliveryCodeAnswer, LogisticsVehicle, MarketplaceLogistics } from "../core/logistics";
1
2
  import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
2
3
  import { IFOOD_API, withIfoodToken } from "./outbound";
3
4
 
@@ -193,3 +194,40 @@ export async function ifoodLogisticsVerifyDeliveryCode(
193
194
  if (result.kind === "refused" && result.status === 412) return { kind: "not-requested" };
194
195
  return result;
195
196
  }
197
+
198
+ /** The engine's vehicles, as iFood names them. */
199
+ const VEHICLE: Readonly<Record<LogisticsVehicle, IfoodLogisticsVehicle>> = {
200
+ MOTORCYCLE: "MOTORCYCLE",
201
+ CAR: "CAR",
202
+ BICYCLE: "BICYCLE",
203
+ ON_FOOT: "ONFOOT",
204
+ SCOOTER: "PATINETE",
205
+ };
206
+
207
+ /**
208
+ * The adapter's Logistics half (FUT-6166): the engine's steps on iFood's
209
+ * wire. An invalid driver is answered as the engine's `invalid`.
210
+ */
211
+ export const IFOOD_LOGISTICS: MarketplaceLogistics = {
212
+ assignDriver: (ctx, order, driver) =>
213
+ ifoodLogisticsAssignDriver(ctx, order.externalOrderId, { name: driver.name, phone: driver.phone, vehicle: VEHICLE[driver.vehicle] }),
214
+ step: (ctx, order, step) => ifoodLogisticsStep(ctx, order.externalOrderId, step),
215
+ verifyDeliveryCode: async (ctx, order, code) => deliveryCodeAnswerOf(await ifoodLogisticsVerifyDeliveryCode(ctx, order.externalOrderId, code)),
216
+ };
217
+
218
+ /** iFood's answer to a code, as the engine's closed set (FUT-6167). */
219
+ function deliveryCodeAnswerOf(result: IfoodDeliveryCodeResult): DeliveryCodeAnswer {
220
+ switch (result.kind) {
221
+ case "verified":
222
+ return { kind: "VERIFIED" };
223
+ case "wrong-code":
224
+ case "invalid":
225
+ return { kind: "WRONG_CODE" };
226
+ case "not-requested":
227
+ return { kind: "NOT_REQUESTED" };
228
+ case "refused":
229
+ return { kind: "UNAVAILABLE", reason: `refused ${result.status}` };
230
+ default:
231
+ return { kind: "UNAVAILABLE", reason: result.reason };
232
+ }
233
+ }
@@ -43,6 +43,16 @@ const ORDER_PLACED = new Set(["PLC", "PLACED", "ORDER_PLACED"]);
43
43
  const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
44
44
  /** The store accepted the order on iFood's own app (FUT-5653). Also the echo of our own confirm. */
45
45
  const ORDER_CONFIRMED = new Set(["CFM", "CONFIRMED"]);
46
+ /** iFood asked the customer's delivery code (FUT-6167), by its code or its full code. */
47
+ const DELIVERY_CODE_REQUESTED = new Set(["DDCR", "DELIVERY_DROP_CODE_REQUESTED"]);
48
+ /** The event's yes-or-no facts, present only when true. */
49
+ function flagsOf(code: string): Pick<NormalizedEvent, "marketplaceConfirmed" | "deliveryCodeRequested"> {
50
+ return {
51
+ ...(ORDER_CONFIRMED.has(code) ? { marketplaceConfirmed: true } : {}),
52
+ ...(DELIVERY_CODE_REQUESTED.has(code) ? { deliveryCodeRequested: true } : {}),
53
+ };
54
+ }
55
+
46
56
  /** iFood's presence heartbeat (FUT-5984, `presence.md`): every 30 s, naming no order. */
47
57
  const KEEPALIVE = "KEEPALIVE";
48
58
  /** iFood refused the store's own cancellation request. */
@@ -323,7 +333,7 @@ export function normalizeIfoodEvent(
323
333
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
324
334
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
325
335
  ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
326
- ...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),
336
+ ...flagsOf(eventType.toUpperCase()),
327
337
  // The Negotiation Platform's HSD / HSS (FUT-6099): a dispute opened or closed, never an order body.
328
338
  ...optional("dispute", readIfoodDispute(payload, eventType) ?? undefined),
329
339
  };
package/src/index.ts CHANGED
@@ -306,3 +306,13 @@ export type {
306
306
  export { MARKETPLACE_LINK_CHECK_JOB, ATTEMPT_MINUTES as LINK_ATTEMPT_MINUTES, CHECK_EVERY_SECONDS as LINK_CHECK_EVERY_SECONDS, type AppLinkPendingView } from "./core/app-linking";
307
307
  export type { LinkFailure, LinkFinished, LinkPendingView, LinkRefusalCode } from "./core/linking";
308
308
  export type { MarketplaceAuthMode } from "./core/link-store";
309
+ export type { MarketplaceDeliveryCodeEngine, VerifyDeliveryCodeInput } from "./core/delivery-code";
310
+ export {
311
+ LOGISTICS_STEPS,
312
+ type DeliveryCodeAnswer,
313
+ type InformLogisticsInput,
314
+ type LogisticsDriver,
315
+ type LogisticsStep,
316
+ type LogisticsVehicle,
317
+ type MarketplaceLogistics,
318
+ } from "./core/logistics";
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { MarketplaceDisputeApi } from \"./dispute-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceAppLinking, 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 /** OPTIONAL (FUT-6099). The buyer's disputes arrive as events and are answered through `disputes`. */\n disputes?: 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. Linking a store through the software's CENTRALIZED app (FUT-5798):\n * the store authorizes the app on the portal and picks its store from the\n * app's list; no code, no token of its own. Wins over `linking` when both are set.\n */\n readonly appLinking?: MarketplaceAppLinking;\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 /** OPTIONAL (FUT-6099). Answering the buyer's disputes; present with `capabilities.disputes`. */\n readonly disputes?: MarketplaceDisputeApi;\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":";;;;;AA6WA,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":[]}