@12-apps/marketplace 1.4.0 → 1.6.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 (41) hide show
  1. package/ADOPTING.md +1 -0
  2. package/README.md +52 -2
  3. package/dist/99food/index.d.ts +1 -1
  4. package/dist/99food/index.js +1 -1
  5. package/dist/{adapter-B8QtQ2RA.d.ts → adapter-CCWMqt2g.d.ts} +150 -1
  6. package/dist/{chunk-DPCZVN2C.js → chunk-4CJ7B5OR.js} +2 -2
  7. package/dist/{chunk-EBAIZQPB.js → chunk-NFZT5TWR.js} +19 -5
  8. package/dist/chunk-NFZT5TWR.js.map +1 -0
  9. package/dist/{chunk-SZRZTLVU.js → chunk-RGMSD7S7.js} +1 -1
  10. package/dist/chunk-RGMSD7S7.js.map +1 -0
  11. package/dist/chunk-WN2EK4KX.js +15 -0
  12. package/dist/chunk-WN2EK4KX.js.map +1 -0
  13. package/dist/{engine-o5cm54vC.d.ts → engine-w2TgRrlc.d.ts} +26 -2
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +32 -2
  17. package/dist/ifood/index.js +286 -9
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +44 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/manifest/server.d.ts +2 -2
  23. package/dist/manifest/server.js +2 -2
  24. package/dist/rappi/index.d.ts +1 -1
  25. package/dist/rappi/index.js +1 -1
  26. package/dist/server/index.d.ts +2 -2
  27. package/dist/server/index.js +2 -2
  28. package/package.json +1 -1
  29. package/src/core/adapter.ts +7 -0
  30. package/src/core/catalogue-read-port.ts +151 -0
  31. package/src/core/catalogue-read.ts +51 -0
  32. package/src/core/engine.ts +9 -0
  33. package/src/core/ingest.ts +32 -4
  34. package/src/core/ports.ts +11 -0
  35. package/src/ifood/catalogue-read.ts +187 -0
  36. package/src/ifood/catalogue-snapshot.ts +246 -0
  37. package/src/ifood/index.ts +5 -0
  38. package/src/index.ts +15 -0
  39. package/dist/chunk-EBAIZQPB.js.map +0 -1
  40. package/dist/chunk-SZRZTLVU.js.map +0 -1
  41. /package/dist/{chunk-DPCZVN2C.js.map → chunk-4CJ7B5OR.js.map} +0 -0
@@ -0,0 +1,15 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/core/catalogue-read-port.ts
6
+ function centsFromMajor(value) {
7
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
8
+ return Math.round(Number((value * 100).toPrecision(12)));
9
+ }
10
+ __name(centsFromMajor, "centsFromMajor");
11
+
12
+ export {
13
+ centsFromMajor
14
+ };
15
+ //# sourceMappingURL=chunk-WN2EK4KX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/catalogue-read-port.ts"],"sourcesContent":["import type { AdapterCallContext } from \"./adapter\";\n\n/**\n * The catalogue READ half of the adapter port (FUT-951): the menu a store\n * already keeps on a marketplace, read through the store's own connection, so\n * the host can import it (onboarding: \"bring my menu over\").\n *\n * The opposite direction of `catalogue-port.ts` and independent of it: an\n * adapter may read a menu it cannot publish to, or publish to one it cannot\n * read. Nothing here names a marketplace; each adapter maps its own catalogue\n * into the {@link CatalogueSnapshot} below.\n *\n * Money is integer cents of the menu's currency ({@link centsFromMajor}).\n * Nothing the adapter cannot map is dropped silently: a field it could not read\n * is a {@link CatalogueReadWarning} on the item, and an item or category it\n * could not read at all is a {@link CatalogueReadNotice} on the snapshot.\n */\n\n/** Why part of an item could not be mapped. Vocabulary, not copy: the host words it. */\nexport type CatalogueReadWarningCode =\n /** The item carries no readable price: `priceCents` is null. */\n | \"PRICE_MISSING\"\n /** An option carries no readable price: its `priceDeltaCents` is null. */\n | \"OPTION_PRICE_MISSING\"\n /** A group of choices could not be read (no name, no options, bounds that make no sense): left out. */\n | \"OPTION_GROUP_UNREADABLE\"\n /** One choice of a group could not be read (no name): left out of its group. */\n | \"OPTION_UNREADABLE\"\n /** The photo reference is there but is not a path or URL the adapter can resolve: `photoUrl` is null. */\n | \"PHOTO_UNREADABLE\"\n /** The item is of a kind this reader maps only partly (a combo, a pizza by halves): read as a plain item. */\n | \"ITEM_TYPE_UNSUPPORTED\";\n\n/** One thing about an item the read could not map. */\nexport interface CatalogueReadWarning {\n code: CatalogueReadWarningCode;\n /** The marketplace's id of the group or option concerned, or null when it is the item itself. */\n subject: string | null;\n /** What the marketplace sent, for a developer (never shown as copy). */\n detail: string | null;\n}\n\n/** One choice of a group: a size, a flavour, an add-on. */\nexport interface CatalogueSnapshotOption {\n externalId: string;\n /** The store's own code for it on the marketplace, when it set one. */\n externalCode: string | null;\n name: string;\n description: string | null;\n /** What choosing it adds to the item's price, in cents (0 = free); null when the marketplace sent none. */\n priceDeltaCents: number | null;\n photoUrl: string | null;\n available: boolean;\n}\n\n/** A group of choices on an item: \"Size\" (min 1, max 1), \"Extras\" (min 0, max 3). */\nexport interface CatalogueSnapshotOptionGroup {\n externalId: string;\n externalCode: string | null;\n name: string;\n /** At least this many choices (0 = optional). */\n min: number;\n /** At most this many choices (always >= `min` and >= 1). */\n max: number;\n available: boolean;\n options: CatalogueSnapshotOption[];\n}\n\n/** One item as the marketplace sells it. */\nexport interface CatalogueSnapshotItem {\n externalId: string;\n externalCode: string | null;\n name: string;\n description: string | null;\n /** The item's own price in cents; null when the marketplace sent none (with a PRICE_MISSING warning). */\n priceCents: number | null;\n /** An absolute https URL of the photo, or null when the item has none. */\n photoUrl: string | null;\n /** Whether the marketplace sells it now (a paused item is still read). */\n available: boolean;\n optionGroups: CatalogueSnapshotOptionGroup[];\n warnings: CatalogueReadWarning[];\n}\n\n/** One category, its items in the marketplace's order. */\nexport interface CatalogueSnapshotCategory {\n externalId: string;\n externalCode: string | null;\n name: string;\n available: boolean;\n items: CatalogueSnapshotItem[];\n}\n\n/** An item or a category the read could not map at all, said rather than dropped. */\nexport interface CatalogueReadNotice {\n code: \"ITEM_UNREADABLE\" | \"CATEGORY_UNREADABLE\";\n /** The category it was found in (the category itself for CATEGORY_UNREADABLE), or null when it had no id. */\n categoryExternalId: string | null;\n /** The item's id, when it had one; null for a category. */\n externalId: string | null;\n detail: string;\n}\n\n/** The store's menu on a marketplace, as read. */\nexport interface CatalogueSnapshot {\n categories: CatalogueSnapshotCategory[];\n notices: CatalogueReadNotice[];\n}\n\n/**\n * Why a read failed for good. Vocabulary, not copy.\n * - `UNSUPPORTED`: the marketplace's adapter states no catalogue read.\n * - `NOT_CONNECTED`: no live connection with a merchant id for that marketplace.\n * - `CREDENTIALS`: no credentials on file, they do not open, or the marketplace refused them.\n * - `NOT_AUTHORIZED`: the marketplace refused this merchant to this app (not\n * authorized, the catalogue module not enabled, an unknown merchant id).\n * - `REFUSED`: any other final refusal.\n */\nexport type CatalogueReadRefusalCode = \"UNSUPPORTED\" | \"NOT_CONNECTED\" | \"CREDENTIALS\" | \"NOT_AUTHORIZED\" | \"REFUSED\";\n\n/** What a read answers: the snapshot, a final refusal, or a failure worth asking again later (429, 5xx, a timeout). */\nexport type CatalogueReadResult =\n | { kind: \"snapshot\"; snapshot: CatalogueSnapshot }\n /** `status` and `message` are the marketplace's answer; null when the engine refused before calling. */\n | { kind: \"refused\"; code: CatalogueReadRefusalCode; status: number | null; message: string | null }\n | { kind: \"retry\"; reason: string };\n\n/** What one catalogue read is handed: the outbound context plus the connection's merchant id. */\nexport interface CatalogueReadContext extends AdapterCallContext {\n externalMerchantId: string;\n}\n\n/** A marketplace whose menu can be read. */\nexport interface CatalogueReader {\n /** Read the whole menu. Never throws: a call with no answer is a `retry`. */\n read(ctx: CatalogueReadContext): Promise<CatalogueReadResult>;\n}\n\n/**\n * A price in the currency's MAJOR unit (`25.9`) as integer cents (`2590`), or\n * null when it is not a finite, non-negative number.\n *\n * Rounding is explicit: the product is first cut to 12 significant digits,\n * which removes binary floating-point error (`1.005 * 100` is\n * `100.49999999999999`), and then rounded half up to the cent (`1.005` →\n * `101`, `0.125` → `13`).\n */\nexport function centsFromMajor(value: unknown): number | null {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) return null;\n return Math.round(Number((value * 100).toPrecision(12)));\n}\n"],"mappings":";;;;;AAmJO,SAAS,eAAe,OAA+B;AAC5D,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,EAAG,QAAO;AAC9E,SAAO,KAAK,MAAM,QAAQ,QAAQ,KAAK,YAAY,EAAE,CAAC,CAAC;AACzD;AAHgB;","names":[]}
@@ -1,4 +1,4 @@
1
- import { p as CatalogueItem, o as CatalogueImage, a as NormalizedMarketplaceOrder, y as MarketplaceHttp, c as MarketplaceAdapter, h as MarketplaceProvider, w as MarketplaceCredentials, t as CatalogueWarningCode, i as CancellationReason, I as OutboundOrderRef, N as NormalizedEvent, b as CatalogueMenuOptions } from './adapter-B8QtQ2RA.js';
1
+ import { q as CatalogueItem, p as CatalogueImage, a as NormalizedMarketplaceOrder, R as MarketplaceHttp, c as MarketplaceAdapter, i as MarketplaceProvider, L as MarketplaceCredentials, H as CatalogueWarningCode, j as CancellationReason, Z as OutboundOrderRef, N as NormalizedEvent, b as CatalogueMenuOptions, w as CatalogueReadResult } from './adapter-CCWMqt2g.js';
2
2
 
3
3
  /**
4
4
  * What the engine needs FROM its host, and nothing more.
@@ -180,6 +180,17 @@ interface MarketplaceOrderPort {
180
180
  catalogHas(clientId: string, subjectRef: string): Promise<boolean>;
181
181
  /** The store said yes, or the connection auto-accepts. */
182
182
  onAccepted(clientId: string, orderId: string): Promise<void>;
183
+ /**
184
+ * OPTIONAL. May an arriving order of this tenant be accepted automatically?
185
+ * Asked once per NEW order of a connection with auto-accept on, before the
186
+ * ingest's transaction (never for a redelivery, never with auto-accept off).
187
+ * `false` declines the automatic acceptance: the order lands exactly as it
188
+ * would with auto-accept off — AWAITING on the clock, no confirm queued, no
189
+ * `onAccepted` — and a person decides it. The order itself is never refused.
190
+ * A throw is logged and declines too. Absent: every auto-accept proceeds.
191
+ * Answer it cheaply: it sits on the ingest path of every order.
192
+ */
193
+ mayAutoAccept?(clientId: string): Promise<boolean>;
183
194
  /** The store said no, the marketplace cancelled, or the clock lapsed. */
184
195
  onRefused(clientId: string, orderId: string, reason: MarketplaceRefusal): Promise<void>;
185
196
  /**
@@ -869,7 +880,10 @@ interface IngestResult {
869
880
  created: boolean;
870
881
  /** SKUs that arrived with nothing behind them, in this order. */
871
882
  unmappedSkus: string[];
872
- /** Whether the connection's policy made this order born accepted. */
883
+ /**
884
+ * Whether this order was born accepted: the connection auto-accepts AND the
885
+ * host's `mayAutoAccept`, when bound, allowed it.
886
+ */
873
887
  autoAccepted: boolean;
874
888
  }
875
889
  /** The store's operating decisions, read from the connection at ingest time. */
@@ -1327,6 +1341,16 @@ interface MarketplaceEngine {
1327
1341
  provider: MarketplaceProvider;
1328
1342
  options: CatalogueMenuOptions;
1329
1343
  }): Promise<CatalogueDocumentResult>;
1344
+ /**
1345
+ * Read the menu the store keeps on a marketplace, through its own
1346
+ * connection (FUT-951): the snapshot, a final refusal, or a `retry` (429,
1347
+ * 5xx, a timeout). Calls the marketplace at once; nothing is queued.
1348
+ */
1349
+ readCatalogue(input: {
1350
+ clientId: string;
1351
+ provider: MarketplaceProvider;
1352
+ now?: Date;
1353
+ }): Promise<CatalogueReadResult>;
1330
1354
  /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
1331
1355
  runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
1332
1356
  /**
@@ -1,7 +1,7 @@
1
1
  import { Hono, Context } from 'hono';
2
2
  import { ApiMarketplace, MarketplaceApiConfig, MarketplaceActor } from '../server/index.js';
3
- import '../engine-o5cm54vC.js';
4
- import '../adapter-B8QtQ2RA.js';
3
+ import '../engine-w2TgRrlc.js';
4
+ import '../adapter-CCWMqt2g.js';
5
5
  import '@12-apps/wiring';
6
6
  import 'zod';
7
7
 
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  createApiMarketplace
3
- } from "../chunk-DPCZVN2C.js";
3
+ } from "../chunk-4CJ7B5OR.js";
4
4
  import "../chunk-UYFYGGCS.js";
5
- import "../chunk-EBAIZQPB.js";
5
+ import "../chunk-NFZT5TWR.js";
6
6
  import {
7
7
  __name
8
8
  } from "../chunk-7QVYU63E.js";
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, f as StorePauseResult, g as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-B8QtQ2RA.js';
1
+ import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, f as CatalogueReader, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, g as StorePauseResult, h as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CCWMqt2g.js';
2
2
 
3
3
  /**
4
4
  * The words the iFood adapter needs from its host, and nothing else.
@@ -50,6 +50,36 @@ declare function ifoodItemBody(item: CatalogueItemOut, category: string, image:
50
50
  /** iFood's catalogue capability. */
51
51
  declare const IFOOD_CATALOGUE: PushCatalogue;
52
52
 
53
+ /** iFood's catalogue read. */
54
+ declare const IFOOD_CATALOGUE_READER: CatalogueReader;
55
+
56
+ /**
57
+ * iFood's catalogue answer mapped into the engine's {@link CatalogueSnapshotItem}
58
+ * (FUT-951). Pure and offline: `./catalogue-read.ts` makes the calls.
59
+ *
60
+ * The shapes are the Catalog API v2.0's `PUT /items` payload, which the
61
+ * portal's Introduction shows whole (read 2026-11-16): an `item` (id, type,
62
+ * categoryId, status, `price { value }`, externalCode), `products` (id, name,
63
+ * description, externalCode, and `optionGroups: [{ id, min, max }]` linking a
64
+ * product to its groups), `optionGroups` (id, name, status, `optionIds`) and
65
+ * `options` (id, `productId` naming the product that holds its name, status,
66
+ * `price { value }`). The package README's "Catalogue reading" table marks
67
+ * each fact CONFIRMED with its URL or ESTIMATED. ESTIMATED here, and said
68
+ * beside each use:
69
+ * - that `GET /categories/{categoryId}/items` answers the same four lists
70
+ * (`items` plural) the PUT takes;
71
+ * - that `item.productId` names the item's product (the field the push sends);
72
+ * - that `products[].imagePath` holds the photo, a path under
73
+ * {@link IFOOD_IMAGE_BASE_URL}.
74
+ */
75
+ /**
76
+ * Where iFood serves a catalogue photo's `imagePath`. ESTIMATED: the Catalog
77
+ * pages read name `imagePath` but not its host; this is the host iFood's own
78
+ * app loads dish photos from. A path that is already an absolute https URL is
79
+ * used as it is.
80
+ */
81
+ declare const IFOOD_IMAGE_BASE_URL = "https://static-images.ifood.com.br/image/upload/t_high/pratos/";
82
+
53
83
  /**
54
84
  * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.
55
85
  * Read the same whether iFood honours the offset or reads the store's clock.
@@ -88,4 +118,4 @@ interface IfoodAdapterConfig {
88
118
  /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
89
119
  declare function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter;
90
120
 
91
- export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, verifyIfoodSignature };
121
+ export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_IMAGE_BASE_URL, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, verifyIfoodSignature };
@@ -1,3 +1,6 @@
1
+ import {
2
+ centsFromMajor
3
+ } from "../chunk-WN2EK4KX.js";
1
4
  import {
2
5
  stableUuid
3
6
  } from "../chunk-M2V4RFMA.js";
@@ -12,7 +15,7 @@ import {
12
15
  import {
13
16
  answered,
14
17
  outboundResultOf
15
- } from "../chunk-SZRZTLVU.js";
18
+ } from "../chunk-RGMSD7S7.js";
16
19
  import {
17
20
  __name
18
21
  } from "../chunk-7QVYU63E.js";
@@ -269,6 +272,276 @@ var IFOOD_CATALOGUE = {
269
272
  withdrawItem: /* @__PURE__ */ __name((ctx, item) => answered(() => withdraw(ctx, item)), "withdrawItem")
270
273
  };
271
274
 
275
+ // src/ifood/catalogue-snapshot.ts
276
+ var IFOOD_IMAGE_BASE_URL = "https://static-images.ifood.com.br/image/upload/t_high/pratos/";
277
+ var record = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null, "record");
278
+ var text = /* @__PURE__ */ __name((value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null, "text");
279
+ function entriesOf(value) {
280
+ const entries = [];
281
+ const others = [];
282
+ for (const entry of Array.isArray(value) ? value : []) {
283
+ const object = record(entry);
284
+ if (object) entries.push(object);
285
+ else others.push(entry);
286
+ }
287
+ return { entries, others };
288
+ }
289
+ __name(entriesOf, "entriesOf");
290
+ var list = /* @__PURE__ */ __name((value) => entriesOf(value).entries, "list");
291
+ var availableOf = /* @__PURE__ */ __name((status) => status !== "UNAVAILABLE", "availableOf");
292
+ var byId = /* @__PURE__ */ __name((entries) => new Map(entries.flatMap((entry) => text(entry.id) ? [[text(entry.id), entry]] : [])), "byId");
293
+ function indexOf(answer) {
294
+ return { products: byId(list(answer.products)), optionGroups: byId(list(answer.optionGroups)), options: byId(list(answer.options)) };
295
+ }
296
+ __name(indexOf, "indexOf");
297
+ var priceCentsOf = /* @__PURE__ */ __name((price) => centsFromMajor(record(price)?.value), "priceCentsOf");
298
+ var warning = /* @__PURE__ */ __name((code, subject, detail = null) => ({
299
+ code,
300
+ subject,
301
+ detail: detail === null || detail === void 0 ? null : JSON.stringify(detail)
302
+ }), "warning");
303
+ function photoOf(imagePath, subject) {
304
+ if (imagePath === void 0 || imagePath === null || imagePath === "") return { url: null };
305
+ const path = text(imagePath);
306
+ if (path === null) return { url: null, warning: warning("PHOTO_UNREADABLE", subject, imagePath) };
307
+ if (/^https:\/\//i.test(path)) return { url: path };
308
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path)) return { url: null, warning: warning("PHOTO_UNREADABLE", subject, path) };
309
+ return { url: `${IFOOD_IMAGE_BASE_URL}${urlSafePath(path.replace(/^\/+/, ""))}` };
310
+ }
311
+ __name(photoOf, "photoOf");
312
+ function urlSafePath(path) {
313
+ return path.replace(/%(?![0-9A-Fa-f]{2})/g, "%25").replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@/%]/g, (character) => encodeURIComponent(character));
314
+ }
315
+ __name(urlSafePath, "urlSafePath");
316
+ function describedBy(index, own) {
317
+ const product = index.products.get(text(own.productId) ?? "") ?? {};
318
+ return {
319
+ name: text(product.name) ?? text(own.name),
320
+ description: text(product.description) ?? text(own.description),
321
+ externalCode: text(own.externalCode) ?? text(product.externalCode),
322
+ imagePath: product.imagePath ?? own.imagePath
323
+ };
324
+ }
325
+ __name(describedBy, "describedBy");
326
+ function photoInto(imagePath, subject, warnings) {
327
+ const photo = photoOf(imagePath, subject);
328
+ if (photo.warning) warnings.push(photo.warning);
329
+ return photo.url;
330
+ }
331
+ __name(photoInto, "photoInto");
332
+ function optionOf(id, index, warnings) {
333
+ const option = index.options.get(id);
334
+ const described = option ? describedBy(index, option) : null;
335
+ if (!option || !described || described.name === null) {
336
+ warnings.push(warning("OPTION_UNREADABLE", id, option));
337
+ return null;
338
+ }
339
+ const priceDeltaCents = priceCentsOf(option.price);
340
+ if (priceDeltaCents === null) warnings.push(warning("OPTION_PRICE_MISSING", id, option.price));
341
+ return {
342
+ externalId: id,
343
+ externalCode: described.externalCode,
344
+ name: described.name,
345
+ description: described.description,
346
+ priceDeltaCents,
347
+ photoUrl: photoInto(described.imagePath, id, warnings),
348
+ available: availableOf(option.status)
349
+ };
350
+ }
351
+ __name(optionOf, "optionOf");
352
+ function boundsOf(link, group) {
353
+ const min = link.min ?? group.min ?? 0;
354
+ const max = link.max ?? group.max;
355
+ if (!Number.isInteger(min) || !Number.isInteger(max)) return null;
356
+ const [low, high] = [min, max];
357
+ return low >= 0 && high >= 1 && high >= low ? { min: low, max: high } : null;
358
+ }
359
+ __name(boundsOf, "boundsOf");
360
+ function idsOf(groupId, value, warnings) {
361
+ const ids = [];
362
+ for (const entry of Array.isArray(value) ? value : []) {
363
+ const id = text(entry);
364
+ if (id === null) warnings.push(warning("OPTION_UNREADABLE", groupId, entry));
365
+ else ids.push(id);
366
+ }
367
+ return ids;
368
+ }
369
+ __name(idsOf, "idsOf");
370
+ function groupOf(link, index, warnings) {
371
+ const id = text(link.id);
372
+ const group = id === null ? void 0 : index.optionGroups.get(id);
373
+ const bounds = group ? boundsOf(link, group) : null;
374
+ const name = text(group?.name);
375
+ if (id === null || !group || name === null || bounds === null) {
376
+ warnings.push(warning("OPTION_GROUP_UNREADABLE", id, { link, group }));
377
+ return null;
378
+ }
379
+ const options = idsOf(id, group.optionIds, warnings).flatMap((optionId) => optionOf(optionId, index, warnings) ?? []);
380
+ if (options.length === 0) {
381
+ warnings.push(warning("OPTION_GROUP_UNREADABLE", id, "no readable option"));
382
+ return null;
383
+ }
384
+ return { externalId: id, externalCode: text(group.externalCode), name, ...bounds, available: availableOf(group.status), options };
385
+ }
386
+ __name(groupOf, "groupOf");
387
+ function itemWarnings(raw, priceCents) {
388
+ const warnings = [];
389
+ const type = text(raw.type);
390
+ if (type !== null && type !== "DEFAULT") warnings.push(warning("ITEM_TYPE_UNSUPPORTED", null, type));
391
+ if (priceCents === null) warnings.push(warning("PRICE_MISSING", null, raw.price));
392
+ return warnings;
393
+ }
394
+ __name(itemWarnings, "itemWarnings");
395
+ function linksOf(index, raw, warnings) {
396
+ const product = index.products.get(text(raw.productId) ?? "");
397
+ const value = product?.optionGroups ?? raw.optionGroups;
398
+ if (value !== void 0 && value !== null && !Array.isArray(value)) warnings.push(warning("OPTION_GROUP_UNREADABLE", null, value));
399
+ const { entries, others } = entriesOf(value);
400
+ for (const other of others) warnings.push(warning("OPTION_GROUP_UNREADABLE", null, other));
401
+ return entries;
402
+ }
403
+ __name(linksOf, "linksOf");
404
+ function itemOf(raw, index, categoryId2) {
405
+ const id = text(raw.id);
406
+ const described = describedBy(index, raw);
407
+ if (id === null || described.name === null) {
408
+ return { code: "ITEM_UNREADABLE", categoryExternalId: categoryId2, externalId: id, detail: JSON.stringify(raw).slice(0, 300) };
409
+ }
410
+ const priceCents = priceCentsOf(raw.price);
411
+ const warnings = itemWarnings(raw, priceCents);
412
+ const photoUrl = photoInto(described.imagePath, null, warnings);
413
+ const optionGroups = linksOf(index, raw, warnings).flatMap((link) => groupOf(link, index, warnings) ?? []);
414
+ return {
415
+ externalId: id,
416
+ externalCode: described.externalCode,
417
+ name: described.name,
418
+ description: described.description,
419
+ priceCents,
420
+ photoUrl,
421
+ available: availableOf(raw.status),
422
+ optionGroups,
423
+ warnings
424
+ };
425
+ }
426
+ __name(itemOf, "itemOf");
427
+
428
+ // src/ifood/catalogue-read.ts
429
+ var catalogUrl2 = /* @__PURE__ */ __name((merchantId, path) => `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`, "catalogUrl");
430
+ function tokenFailure(result) {
431
+ if (result.kind === "refused") return { kind: "refused", code: "CREDENTIALS", status: result.status, message: result.message };
432
+ return { kind: "retry", reason: result.kind === "retry" ? result.reason : "unexpected token answer" };
433
+ }
434
+ __name(tokenFailure, "tokenFailure");
435
+ function failureOf2(response) {
436
+ const result = outboundResultOf(response);
437
+ if (result.kind !== "refused") return { kind: "retry", reason: result.kind === "retry" ? result.reason : "unexpected answer" };
438
+ const code = response.status === 403 || response.status === 404 ? "NOT_AUTHORIZED" : "REFUSED";
439
+ return { kind: "refused", code, status: result.status, message: result.message };
440
+ }
441
+ __name(failureOf2, "failureOf");
442
+ async function get(ctx, path) {
443
+ for (let attempt = 0; attempt < 2; attempt += 1) {
444
+ const auth = await bearer(ctx);
445
+ if (!("token" in auth)) return tokenFailure(auth);
446
+ const response = await ctx.http({
447
+ method: "GET",
448
+ url: catalogUrl2(ctx.externalMerchantId, path),
449
+ headers: { Authorization: `Bearer ${auth.token}`, Accept: "application/json" }
450
+ });
451
+ if (response.status !== 401) return response;
452
+ ctx.tokens.delete(ifoodTokenKey(ctx));
453
+ }
454
+ return { kind: "retry", reason: "iFood refused a fresh token" };
455
+ }
456
+ __name(get, "get");
457
+ var ok2 = /* @__PURE__ */ __name((response) => response.status >= 200 && response.status < 300, "ok");
458
+ function parse2(body) {
459
+ try {
460
+ return JSON.parse(body);
461
+ } catch {
462
+ return null;
463
+ }
464
+ }
465
+ __name(parse2, "parse");
466
+ var unexpected = /* @__PURE__ */ __name((what, body) => ({
467
+ kind: "refused",
468
+ code: "REFUSED",
469
+ status: 200,
470
+ message: `unexpected ${what} answer: ${body.slice(0, 200)}`
471
+ }), "unexpected");
472
+ async function categoryOf(ctx, raw, notices) {
473
+ const id = text(raw.id);
474
+ const name = text(raw.name);
475
+ if (id === null || name === null) {
476
+ notices.push(unreadableCategory(id, raw));
477
+ return null;
478
+ }
479
+ const answered2 = await get(ctx, `categories/${encodeURIComponent(id)}/items`);
480
+ if ("kind" in answered2) return answered2;
481
+ if (answered2.status === 404) {
482
+ notices.push(unreadableCategory(id, "its items answered 404"));
483
+ return null;
484
+ }
485
+ if (!ok2(answered2)) return failureOf2(answered2);
486
+ const items = itemsOf(answered2.body, id, notices);
487
+ return items && { externalId: id, externalCode: text(raw.externalCode), name, available: availableOf(raw.status), items };
488
+ }
489
+ __name(categoryOf, "categoryOf");
490
+ var unreadableCategory = /* @__PURE__ */ __name((categoryExternalId, detail) => ({
491
+ code: "CATEGORY_UNREADABLE",
492
+ categoryExternalId,
493
+ externalId: null,
494
+ detail: (typeof detail === "string" ? detail : JSON.stringify(detail) ?? String(detail)).slice(0, 300)
495
+ }), "unreadableCategory");
496
+ function itemsOf(rawBody, categoryId2, notices) {
497
+ const body = record(parse2(rawBody));
498
+ if (!body || !Array.isArray(body.items)) {
499
+ notices.push(unreadableCategory(categoryId2, `unexpected items answer: ${rawBody}`));
500
+ return null;
501
+ }
502
+ const index = indexOf(body);
503
+ const { entries, others } = entriesOf(body.items);
504
+ for (const other of others) {
505
+ notices.push({ code: "ITEM_UNREADABLE", categoryExternalId: categoryId2, externalId: null, detail: String(JSON.stringify(other)).slice(0, 300) });
506
+ }
507
+ const items = [];
508
+ for (const entry of entries) {
509
+ const mapped = itemOf(entry, index, categoryId2);
510
+ if ("code" in mapped) notices.push(mapped);
511
+ else items.push(mapped);
512
+ }
513
+ return items;
514
+ }
515
+ __name(itemsOf, "itemsOf");
516
+ async function read(ctx) {
517
+ const listed = await get(ctx, "categories");
518
+ if ("kind" in listed) return listed;
519
+ if (!ok2(listed)) return failureOf2(listed);
520
+ const parsed = parse2(listed.body);
521
+ if (!Array.isArray(parsed)) return unexpected("category list", listed.body);
522
+ const categories = [];
523
+ const notices = [];
524
+ const { entries, others } = entriesOf(parsed);
525
+ for (const other of others) notices.push(unreadableCategory(null, other));
526
+ for (const raw of entries) {
527
+ const category = await categoryOf(ctx, raw, notices);
528
+ if (category === null) continue;
529
+ if ("kind" in category) return category;
530
+ categories.push(category);
531
+ }
532
+ return { kind: "snapshot", snapshot: { categories, notices } };
533
+ }
534
+ __name(read, "read");
535
+ var IFOOD_CATALOGUE_READER = {
536
+ read: /* @__PURE__ */ __name(async (ctx) => {
537
+ try {
538
+ return await read(ctx);
539
+ } catch (error) {
540
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
541
+ }
542
+ }, "read")
543
+ };
544
+
272
545
  // src/ifood/normalize.ts
273
546
  var ORDER_PLACED = /* @__PURE__ */ new Set(["PLC", "PLACED", "ORDER_PLACED"]);
274
547
  var ORDER_CANCELLED = /* @__PURE__ */ new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
@@ -442,8 +715,8 @@ function sameEnd(end, until, timeZone) {
442
715
  return end.slice(0, 19) === sent.slice(0, 19);
443
716
  }
444
717
  __name(sameEnd, "sameEnd");
445
- function ours(list, key, sent, keep = []) {
446
- const candidates = list.filter((entry) => !keep.includes(entry.id));
718
+ function ours(list2, key, sent, keep = []) {
719
+ const candidates = list2.filter((entry) => !keep.includes(entry.id));
447
720
  const byKey = candidates.find((entry) => entry.id === key);
448
721
  if (byKey || !sent) return byKey;
449
722
  return candidates.find(
@@ -489,9 +762,9 @@ function createdId(body, sent) {
489
762
  __name(createdId, "createdId");
490
763
  function ifoodPause(ctx, request) {
491
764
  return answeredPause(async () => {
492
- const list = await listInterruptions(ctx, request.merchantId);
493
- if (!Array.isArray(list)) return list;
494
- const landed = ours(list, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
765
+ const list2 = await listInterruptions(ctx, request.merchantId);
766
+ if (!Array.isArray(list2)) return list2;
767
+ const landed = ours(list2, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
495
768
  if (landed) return { kind: "paused", externalId: landed.id, until: request.until };
496
769
  const response = await call2(ctx, {
497
770
  method: "POST",
@@ -514,9 +787,9 @@ function ifoodResume(ctx, ref) {
514
787
  return answered(async () => {
515
788
  let id = ref.externalId;
516
789
  if (id === null && ref.key !== null) {
517
- const list = await listInterruptions(ctx, ref.merchantId);
518
- if (!Array.isArray(list)) return list;
519
- id = ours(list, ref.key, ref.sent, ref.keep)?.id ?? null;
790
+ const list2 = await listInterruptions(ctx, ref.merchantId);
791
+ if (!Array.isArray(list2)) return list2;
792
+ id = ours(list2, ref.key, ref.sent, ref.keep)?.id ?? null;
520
793
  }
521
794
  if (id === null) return { kind: "accepted" };
522
795
  const response = await call2(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
@@ -574,6 +847,8 @@ function createIfoodAdapter(config) {
574
847
  cancellationReasons: /* @__PURE__ */ __name(() => reasons, "cancellationReasons"),
575
848
  // The Catalog API v2.0: each item is written and paused through the API (FUT-4768).
576
849
  catalogue: IFOOD_CATALOGUE,
850
+ // The same API read back: the menu the store keeps on iFood, for the host to import (FUT-951).
851
+ catalogueReader: IFOOD_CATALOGUE_READER,
577
852
  confirm: /* @__PURE__ */ __name((ctx, order) => ifoodConfirm(ctx, order), "confirm"),
578
853
  requestCancellation: ifoodRequestCancellation,
579
854
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
@@ -588,6 +863,8 @@ export {
588
863
  IFOOD_AVAILABILITY,
589
864
  IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
590
865
  IFOOD_CATALOGUE,
866
+ IFOOD_CATALOGUE_READER,
867
+ IFOOD_IMAGE_BASE_URL,
591
868
  IFOOD_PROVIDER,
592
869
  IFOOD_REASON_CODES,
593
870
  createIfoodAdapter,