@12-apps/marketplace 1.8.0 → 1.9.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.
- package/README.md +102 -8
- package/dist/99food/index.d.ts +30 -54
- package/dist/99food/index.js +60 -418
- package/dist/99food/index.js.map +1 -1
- package/dist/chunk-PYHNM47K.js +478 -0
- package/dist/chunk-PYHNM47K.js.map +1 -0
- package/dist/client-B4EQCRD_.d.ts +20 -0
- package/dist/keeta/en-US.d.ts +19 -0
- package/dist/keeta/en-US.js +23 -0
- package/dist/keeta/en-US.js.map +1 -0
- package/dist/keeta/index.d.ts +253 -0
- package/dist/keeta/index.js +388 -0
- package/dist/keeta/index.js.map +1 -0
- package/dist/keeta/pt-BR.d.ts +23 -0
- package/dist/keeta/pt-BR.js +23 -0
- package/dist/keeta/pt-BR.js.map +1 -0
- package/package.json +14 -2
- package/src/99food/catalogue.ts +19 -89
- package/src/99food/copy.ts +4 -19
- package/src/99food/index.ts +28 -33
- package/src/99food/normalize.ts +11 -253
- package/src/99food/outbound.ts +29 -270
- package/src/99food/pause.ts +7 -22
- package/src/index.ts +2 -1
- package/src/keeta/authorization.ts +226 -0
- package/src/keeta/copy.ts +27 -0
- package/src/keeta/en-US.ts +19 -0
- package/src/keeta/index.ts +162 -0
- package/src/keeta/merchant.ts +70 -0
- package/src/keeta/normalize.ts +131 -0
- package/src/keeta/outbound.ts +55 -0
- package/src/keeta/pt-BR.ts +23 -0
- package/src/keeta/signature.ts +85 -0
- package/src/open-delivery/client.ts +185 -0
- package/src/open-delivery/merchant.ts +126 -0
- package/src/open-delivery/normalize.ts +269 -0
- package/src/open-delivery/orders.ts +241 -0
- package/src/open-delivery/reasons.ts +26 -0
package/dist/99food/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/99food/copy.ts","../../src/99food/normalize.ts","../../src/99food/outbound.ts","../../src/99food/catalogue.ts","../../src/99food/pause.ts","../../src/99food/index.ts"],"sourcesContent":["/**\n * The words the 99Food adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * The cancellation codes a merchant may send, verbatim from Open Delivery\n * v1.7.1 (`RequestCancelled.code`). Pinned by the spec, not estimated. The two\n * codes only the marketplace sends (`CONSUMER_CANCELLATION_REQUESTED`,\n * `OTHER_CANCELLATION_REASON`) are not a store's to choose and are left out.\n */\nexport const NINETY_NINE_FOOD_REASON_CODES = [\n \"SYSTEMIC_ISSUES\",\n \"DUPLICATE_APPLICATION\",\n \"UNAVAILABLE_ITEM\",\n \"RESTAURANT_WITHOUT_DELIVERY_PERSON\",\n \"OUTDATED_MENU\",\n \"ORDER_OUTSIDE_THE_DELIVERY_AREA\",\n \"BLOCKED_CUSTOMER\",\n \"OUTSIDE_DELIVERY_HOURS\",\n \"INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT\",\n \"RISK_AREA\",\n \"DELIVERY_PROBLEM\",\n] as const;\n\nexport type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];\n\nexport interface NinetyNineFoodAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n toCents,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\nimport type {\n MarketplaceLifecycle,\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The 99Food adapter's INBOUND half, on Open Delivery v1.7.1 (Abrasel).\n *\n * Open Delivery splits what iFood sends at once: the webhook's `Event` names\n * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and\n * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So\n * there are two readers here: {@link normalizeOpenDeliveryEvent} for the\n * webhook (a `CREATED` becomes `orderToFetch`), and\n * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.\n *\n * Every shape below is the spec's (`components/schemas/Event`, `Order`,\n * `Price`, `Address`), and every fixture in the tests is the spec's own\n * example. Read defensively all the same: a missing field produces null, and\n * only a missing order id refuses an event (it is the idempotency key).\n */\n\n/** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const NINETY_NINE_FOOD_PROVIDER = \"NINETY_NINE_FOOD\";\n\n/** The order exists and its body must be fetched. */\nconst CREATED = \"CREATED\";\n/** The order is cancelled: the store's request was granted, or a mandatory cancellation. */\nconst CANCELLED = \"CANCELLED\";\n/** The order left (DISPATCHED) and the order is finished (CONCLUDED): the lifecycle events (FUT-4653). */\nconst LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = { DISPATCHED: \"DISPATCHED\", CONCLUDED: \"CONCLUDED\" };\n/** The marketplace refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_DENIED = \"CANCELLATION_REQUEST_DENIED\";\n\n/**\n * Verify a delivery: Open Delivery's `X-App-Signature` is \"a lowercased\n * hexadecimal HMAC signature of the webhook HTTP request body, using the\n * client secret as a key and SHA256 as the hash function\". The key is the\n * merchant app's CLIENT SECRET, so a store's connection keeps that same value\n * as its webhook secret.\n *\n * Unlike iFood (whose secret is issued after certification), the key exists\n * from the moment the store connects, so an unset secret REFUSES: an unsigned\n * CANCELLED for a known order id would otherwise cancel it.\n */\nexport function verifyOpenDeliverySignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return false;\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/**\n * Normalize one webhook `Event`. Null only when it names no order.\n *\n * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.\n * - `CANCELLED` is a cancellation, whether the store asked for it or not.\n * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.\n * - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine\n * asks the host to move the order forward, when the store follows them.\n * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, the\n * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and\n * recorded, and acts on nothing: an IGNORED inbox row.\n *\n * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the\n * engine attributes a delivery by its URL's store slug, so it reads none.\n */\nexport function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"]]);\n if (!externalOrderId) return null;\n const eventType = (firstString(payload, [[\"eventType\"]]) ?? \"UNKNOWN\").toUpperCase();\n const cancelled = eventType === CANCELLED;\n const denied = eventType === CANCELLATION_REQUEST_DENIED;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n // The spec's own event id. The fallback is deterministic so a redelivery\n // still collides on the inbox's unique index.\n eventId: firstString(payload, [[\"eventId\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: null,\n externalOrderId,\n order: null,\n orderToFetch: eventType === CREATED,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : denied ? \"FAILED\" : null,\n ...(LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}),\n };\n}\n\n/** A `Price` object (`{ value, currency }`) in cents. */\nfunction priceCents(source: unknown, ...path: string[]): number | null {\n return toCents(pick(source, ...path, \"value\"));\n}\n\n/**\n * The note a kitchen reads: the chosen options (a pizza's halves are options)\n * and the buyer's own instructions. The normalized line has no options of its\n * own, and a flavour dropped from the ticket is food made wrong.\n */\nfunction lineNote(item: unknown, fraction: string | null): string | null {\n const rawOptions = pick(item, \"options\");\n const options = (Array.isArray(rawOptions) ? rawOptions : [])\n .map((option) => {\n const name = asString(pick(option, \"name\"));\n const quantity = Number(pick(option, \"quantity\") ?? 1);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n const parts = [fraction, options.join(\", \") || null, firstString(item, [[\"specialInstructions\"]])];\n const note = parts.filter((part): part is string => part !== null).join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * What the buyer paid for the whole line, in cents. The spec's `totalPrice`\n * (\"quantity * (unitPrice + optionsPrice)\") is the figure the order's\n * `itemsPrice` is built from, and it wins whenever it is stated — its own\n * example does not add up otherwise (unit 43, options 50, total 50).\n *\n * Without it: `unitPrice × quantity + optionsPrice`. ESTIMATED: the spec calls\n * `optionsPrice` \"the sum of the total prices of all options of the item\", a\n * LINE figure, so it is added once, never multiplied by the quantity or by a\n * weight.\n */\nfunction lineTotalCents(item: unknown, quantity: number): number {\n const total = priceCents(item, \"totalPrice\");\n if (total !== null) return total;\n const unit = priceCents(item, \"unitPrice\") ?? 0;\n return Math.round(unit * quantity) + (priceCents(item, \"optionsPrice\") ?? 0);\n}\n\n/** The stated quantity (decimal for weighed units), 1 when absent or nonsense. */\nfunction quantityOf(item: unknown): number {\n const stated = Number(pick(item, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\n/**\n * Split a line total over a whole quantity so the lines add up to it EXACTLY:\n * one row at `total / quantity` when it divides; otherwise `quantity - 1`\n * units at the floor and one unit carrying the remainder, under the same SKU\n * (R$ 10.00 over 3 is 3.33 × 2 + 3.34).\n */\nfunction splitWhole(total: number, quantity: number): { quantity: number; unitPriceCents: number }[] {\n const floor = Math.floor(total / quantity);\n const remainder = total - floor * quantity;\n if (remainder === 0) return [{ quantity, unitPriceCents: floor }];\n const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];\n return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];\n}\n\n/**\n * One `Order.items[]` entry → its lines, which always add up to the line's\n * total ({@link lineTotalCents}). A whole quantity is split by\n * {@link splitWhole}; a fractional one (500 g as `0.5 KG`) is one line at its\n * total, the weight in the note.\n *\n * A line with no `externalCode` keys on the item id, then the name: an\n * unmapped line is recoverable, a dropped one is not. ESTIMATED: whether the\n * item id is stable across orders is not pinned by the spec; if it is per\n * order, each such order adds an unmapped SKU row.\n */\nfunction readLines(item: unknown): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = quantityOf(item);\n const whole = Number.isInteger(quantity);\n const fraction = whole ? null : `${quantity} ${firstString(item, [[\"unit\"]]) ?? \"\"}`.trim();\n const total = lineTotalCents(item, quantity);\n const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];\n const note = lineNote(item, fraction);\n return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));\n}\n\n/** `DELIVERY` or `TAKEOUT`; `INDOOR` (eaten at the store) is neither, so unstated. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"type\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n return stated === \"MERCHANT\" || stated === \"MARKETPLACE\" ? stated : null;\n}\n\n/**\n * `delivery.deliveryAddress`. The spec's schema says `street`, `number`,\n * `district`; its own (commented) order example says `streetName`,\n * `streetNumber`, `neighborhood`. Both are read. The state is ISO 3166-2 by\n * recommendation (`BR-SP`), so the country prefix is dropped.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"street\"], [\"streetName\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"number\"], [\"streetNumber\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"district\"], [\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]])?.replace(/^[A-Z]{2}-/u, \"\") ?? null,\n };\n}\n\n/**\n * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when\n * it carries no id or no line.\n *\n * The total is `total.orderAmount`, \"the final value of the order (itemsPrice\n * + otherFees - discounts)\": the buyer's receipt, gross. Open Delivery's\n * `Order` states NO commission field, so `commissionCents` is null (\"did not\n * say\"), never 0; the marketplace's cut arrives with its statement.\n */\nexport function normalizeOpenDeliveryOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n const externalOrderId = firstString(order, [[\"id\"]]);\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .flatMap(readLines);\n if (!externalOrderId || lines.length === 0) return null;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]),\n externalMerchantId: firstString(order, [[\"merchant\", \"id\"]]),\n buyer: {\n externalId: firstString(order, [[\"customer\", \"id\"]]),\n name: firstString(order, [[\"customer\", \"name\"]]),\n phone: firstString(order, [[\"customer\", \"phone\", \"number\"]]),\n },\n lines,\n // The line sum is the FALLBACK: the stated total carries the fees and\n // discounts the lines do not, and it is the number on the receipt.\n totalCents:\n firstCents(order, [[\"total\", \"orderAmount\", \"value\"]]) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n deliveryDueAt: firstDate(order, [\n [\"delivery\", \"estimatedDeliveryDateTime\"],\n [\"takeout\", \"takeoutDateTime\"],\n [\"schedule\", \"scheduledDateTimeEnd\"],\n ]),\n placedAt: firstDate(order, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n tokenGrantResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n type StatusFacts,\n} from \"../core/adapter\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from \"./normalize\";\n\n/**\n * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth\n * grant, the order fetch, confirm and requestCancellation. Paths, verbs,\n * bodies and answers are the spec's; the job that calls these, its retries\n * and what a failure shows are the engine's.\n *\n * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the\n * paths under each Ordering Application's own base URL, and 99Food gives its\n * base URLs to a partner at onboarding. So the base URL per environment is\n * the adapter's REQUIRED config, never a guessed default. Tests never reach\n * 99Food: the HTTP client is the host's port, answered by a fake.\n */\n\n/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */\nexport type NinetyNineFoodApiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/** `expires_in` is optional in the spec's `TokenResponse`; an hour when absent. ESTIMATED. */\nconst DEFAULT_TOKEN_SECONDS = 3600;\n\n/** The base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nexport function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {\n const base = bases[ctx.environment];\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\nexport const tokenKey = (ctx: AdapterCallContext): string =>\n `${NINETY_NINE_FOOD_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The spec's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token from the per-process cache, or a fresh `client_credentials`\n * grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,\n * `grant_type`). Keyed by environment and client id; memory only.\n */\nexport async function bearer(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n): Promise<{ token: string } | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const cached = ctx.tokens.get(tokenKey(ctx));\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/oauth/token`,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"client_credentials\",\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = tokenGrantResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"99Food answered the token grant without a token\" };\n ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated call to an order's resource, the raw answer or the result that ends it. */\nasync function callOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n request: { method: \"GET\" | \"POST\"; externalOrderId: string; action: string | null; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const suffix = request.action === null ? \"\" : `/${request.action}`;\n const response = await ctx.http({\n method: request.method,\n url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status !== 401) return response;\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */\nfunction alreadyCancelled(response: MarketplaceHttpResponse): boolean {\n if (response.status !== 422) return false;\n try {\n return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === \"CANCELLED\";\n } catch {\n return false;\n }\n}\n\n/** {@link answered} for a fetch: a call that never got an answer is a retry. */\nasync function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */\nexport function openDeliveryFetchOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: { externalOrderId: string },\n options: { missingStreetNumber: string },\n): Promise<FetchOrderResult> {\n return fetched(async () => {\n const response = await callOrder(ctx, bases, { method: \"GET\", externalOrderId: order.externalOrderId, action: null });\n if (\"kind\" in response) return response;\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n let body: unknown;\n try {\n body = JSON.parse(response.body);\n } catch {\n return { kind: \"refused\", status: response.status, message: \"the order is not JSON\" };\n }\n const normalized = normalizeOpenDeliveryOrder(body, options);\n return normalized\n ? { kind: \"order\", order: normalized }\n : { kind: \"refused\", status: response.status, message: \"the order carries no id or no line\" };\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:\n * `orderExternalCode` (the host's own order id) and `createdAt`, plus the\n * `preparationTime` in minutes when the store stated one. The spec describes\n * `createdAt` with the ORDER's creation text (a copy of another schema's), so\n * it is sent as the moment of the confirmation: ESTIMATED.\n *\n * Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`\n * (\"unable to process the contained instructions. (Check if the instruction\n * has not been sent before.)\"), and its body cannot tell a duplicate from a\n * cancelled order. So a retried confirm whose first answer was lost reads\n * \"não confirmou\" with the app link — a false alarm a person dismisses on\n * 99Food — and a confirm 99Food truly refused is never stamped confirmed.\n */\nexport function openDeliveryConfirm(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"confirm\",\n body: {\n orderExternalCode: order.hostOrderCode,\n createdAt: ctx.now.toISOString(),\n ...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),\n },\n });\n if (\"kind\" in response) return response;\n return outboundResultOf(response);\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/requestCancellation` with the spec's\n * `RequestCancelled`: `reason` (free text: the store's, else the label),\n * `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means\n * taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`\n * event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is\n * cancelled already, which is what the request wanted.\n *\n * `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,\n * and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU\n * map is keyed on. The field is optional.\n */\nexport function openDeliveryRequestCancellation(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"requestCancellation\",\n body: { reason: input.text === \"\" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },\n });\n if (\"kind\" in response) return response;\n if (alreadyCancelled(response)) return { kind: \"accepted\" };\n const result = outboundResultOf(response);\n // Open Delivery's 400 is a malformed request (a bad id or body: ours);\n // its 422 is the business answer and stays a refusal.\n return result.kind === \"refused\" && result.status === 400 ? { ...result, own: true } : result;\n });\n}\n\n/**\n * What 99Food is told per step (FUT-4653), from Open Delivery v1.7.1's\n * `openapi.yaml` (https://abrasel-nacional.github.io/opendelivery/openapi.yaml,\n * read 2026-11-25, paths at lines 1605-1890):\n *\n * - READY: `POST /v1/orders/{id}/readyForPickup`, \"ready for pickup by the\n * customer or delivery person\"; 202. Every kind of order.\n * - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`\n * (`deliveryTrackingInfo` optional, sent empty), and \"a DISPATCHED event is\n * expected after this action\". Only where the logistics is the merchant's.\n * - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a\n * take-out `POST /v1/orders/{id}/pickedUp`. Both optional in the spec. The\n * marketplace's own fleet: none.\n *\n * The kind of order is `deliveredBy` (null: a take-out). That a take-out's\n * order states no `deliveredBy` is how 99Food's order reads (ESTIMATED: an\n * order that merely omits it reads as a take-out here).\n */\nconst STATUS_PATH: Readonly<Record<string, (facts: StatusFacts) => { action: string; body?: unknown } | null>> = {\n READY: () => ({ action: \"readyForPickup\" }),\n DISPATCHED: (facts) => (facts.deliveredBy === \"MERCHANT\" ? { action: \"dispatch\", body: {} } : null),\n HANDED_OVER: (facts) =>\n facts.deliveredBy === \"MERCHANT\"\n ? { action: \"delivered\", body: {} }\n : facts.deliveredBy === null\n ? { action: \"pickedUp\", body: {} }\n : null,\n};\n\n/** Whether 99Food takes this step for this kind of order: answered offline. */\nexport function openDeliveryStatusSupported(facts: StatusFacts): boolean {\n return STATUS_PATH[facts.step]?.(facts) != null;\n}\n\n/** Tell 99Food a step happened. `unsupported` when the spec has no call for it. */\nexport function openDeliveryInformStatus(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n facts: StatusFacts,\n): Promise<OutboundResult | { kind: \"unsupported\" }> {\n const path = STATUS_PATH[facts.step]?.(facts) ?? null;\n if (path === null) return Promise.resolve({ kind: \"unsupported\" });\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: path.action,\n ...(path.body === undefined ? {} : { body: path.body }),\n });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n","import { answered, outboundResultOf, type OutboundResult } from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type { CatalogueCallContext, CatalogueMenuEntry, CatalogueMenuOptions, PullCatalogue } from \"../core/catalogue-port\";\nimport { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).\n *\n * In Open Delivery the store's software does not write the menu to the\n * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a\n * `Merchant` document carrying `menus`, `categories`, `items` and\n * `itemOffers` (the price lives on the offer), and the ORDERING APPLICATION\n * (99Food) pulls it, again when its `TTL` runs out or when told the merchant\n * changed (`POST /v1/merchantUpdate`, sent with an empty body: \"pull\n * everything again\"). Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml\n *\n * So the adapter does two things: build the menu part of that document from\n * the items the store switched on (`menuDocument`, pure; the host merges it\n * into the rest of the `Merchant`, which is its own: `basicInfo`, `services`,\n * `lastUpdate`, `TTL`, `status`), and tell 99Food the menu changed\n * (`notifyMenuChanged`).\n *\n * ESTIMATED, to be checked once 99Food grants partner access:\n * - the path: the spec's route table and prose name `POST /merchantUpdate`\n * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this\n * sends the prose's;\n * - the `X-App-MerchantId` header on it: the operation lists none, and one\n * client app may serve many merchants, so it is sent to name which;\n * - that 99Food reads the whole `Merchant` on that notification (scenario 1\n * of the operation) rather than needing `entityType`/`updatedObjects`.\n *\n * Every id in the document is a UUID the software generates (the spec's\n * `format: uuid`), derived from the publication's stable reference, so the\n * same product keeps the same ids across pulls.\n */\n\n/** One category per host category name, in first-seen order. */\nfunction categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {\n const byName = new Map<string, { id: string; name: string; offers: string[] }>();\n for (const entry of entries) {\n const name = entry.categoryName.trim();\n const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };\n category.offers.push(stableUuid(`${entry.ref}:offer`));\n byName.set(name, category);\n }\n return [...byName.values()];\n}\n\n/** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */\nexport function openDeliveryMenuDocument(input: {\n externalMerchantId: string;\n entries: readonly CatalogueMenuEntry[];\n options: CatalogueMenuOptions;\n}) {\n const { externalMerchantId: merchantId, entries, options } = input;\n const categories = categoriesOf(merchantId, entries);\n return {\n menus: [\n {\n id: stableUuid(`${merchantId}:menu`),\n name: options.menuName,\n externalCode: \"menu\",\n categoryId: categories.map((category) => category.id),\n },\n ],\n categories: categories.map((category, index) => ({\n id: category.id,\n index,\n name: category.name,\n externalCode: category.name,\n status: \"AVAILABLE\",\n itemOfferId: category.offers,\n })),\n items: entries.map((entry) => ({\n id: stableUuid(`${entry.ref}:item`),\n name: entry.name,\n description: entry.description ?? \"\",\n externalCode: entry.productId,\n status: \"AVAILABLE\",\n unit: \"UN\",\n ...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),\n })),\n itemOffers: entries.map((entry, index) => {\n const value = Math.round(entry.priceCents) / 100;\n return {\n id: stableUuid(`${entry.ref}:offer`),\n itemId: stableUuid(`${entry.ref}:item`),\n index,\n status: \"AVAILABLE\",\n price: { value, originalValue: value, currency: options.currency },\n };\n }),\n };\n}\n\n/** `POST /v1/merchantUpdate` with no body: 99Food pulls the whole `Merchant` again. 200 or 204. */\nasync function notify(ctx: CatalogueCallContext, bases: NinetyNineFoodApiBaseUrls): Promise<OutboundResult> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,\n headers: { Authorization: `Bearer ${auth.token}`, \"X-App-MerchantId\": ctx.externalMerchantId },\n });\n if (response.status !== 401) return outboundResultOf(response);\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** 99Food's catalogue capability, for the base URLs it was given. */\nexport function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n notifyMenuChanged: (ctx) => answered(() => notify(ctx, bases)),\n };\n}\n","import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from \"../core/adapter\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the\n * software PUSHES the merchant's status to the Ordering Application.\n *\n * `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)\n * \"sent with only the `merchantStatus` field ... will force the opening or\n * closing of the merchant within the Ordering Application\"; `merchantStatus`\n * is `AVAILABLE | UNAVAILABLE`, \"only use this type when you must close\n * (disable) the merchant due to an unexpected event and you don't know when\n * the service will be re-established\"; 204 (200 \"for compatibility\"), 400,\n * 401, 403, 404, 503 (openapi.yaml v1.7.1, README \"Pausing a store\").\n *\n * A SWITCH, with no id and no end, so offered only when the host opts in\n * (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path\n * (the spec files this webhook under the key `/v1/menuUpdated` while its own\n * description and route table say `POST /v1/merchantUpdate`; the latter is\n * sent), that 99Food implements it at all, and that the token names the\n * merchant (Open Delivery authenticates per merchant, so the body names none).\n */\n\n/** Set the merchant's status. */\nexport function openDeliverySetMerchantStatus(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n status: \"AVAILABLE\" | \"UNAVAILABLE\",\n): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,\n headers: { Authorization: `Bearer ${auth.token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ merchantStatus: status }),\n });\n if (response.status !== 401) return outboundResultOf(response);\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n });\n}\n\n/** 99Food's availability capability: Open Delivery's merchant status, a switch. */\nexport function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx, request) => {\n const result = await openDeliverySetMerchantStatus(ctx, bases, \"UNAVAILABLE\");\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, \"AVAILABLE\"),\n };\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nimport { openDeliveryCatalogue } from \"./catalogue\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDeliverySignature } from \"./normalize\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryInformStatus,\n openDeliveryRequestCancellation,\n openDeliveryStatusSupported,\n type NinetyNineFoodApiBaseUrls,\n} from \"./outbound\";\nimport { openDeliveryAvailability } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.\n *\n * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks\n * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,\n * confirm, requestCancellation with the spec's codes. Everything 99Food is\n * under this folder; the engine reaches it only through the\n * {@link MarketplaceAdapter} port, and registering it is the whole cost:\n *\n * ```ts\n * import { createNinetyNineFoodAdapter } from \"@12-apps/marketplace/99food\";\n * import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/99food/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),\n * ],\n * });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.\n */\n\nexport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */\nexport const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: NinetyNineFoodReasonCode = \"UNAVAILABLE_ITEM\";\n\nexport interface NinetyNineFoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: NinetyNineFoodAdapterCopy;\n /**\n * Where 99Food serves Open Delivery, per environment: the base the spec's\n * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at\n * onboarding and not public, so required and defaultless. https only.\n */\n apiBaseUrl: NinetyNineFoodApiBaseUrls;\n /**\n * Where \"open it on 99Food\" goes: the merchant portal. Open Delivery names no\n * per-order deep link, so the link is the portal. Required; https only.\n */\n portalUrl: string;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open\n * Delivery's `merchantStatus`, a store-wide switch with no id: a store the\n * owner also closed by hand on 99Food during the kitchen's pause is opened\n * with it. A host turns this on knowing that.\n */\n pauseByStoreSwitch?: boolean;\n}\n\nfunction assertHttps(name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);\n}\n\n/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */\nexport function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {\n assertHttps(\"apiBaseUrl.SANDBOX\", config.apiBaseUrl.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", config.apiBaseUrl.PRODUCTION);\n assertHttps(\"portalUrl\", config.portalUrl);\n const bases = { ...config.apiBaseUrl };\n const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional in the spec (see `./outbound.ts`).\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // The spec lets a merchant request a cancellation before or after the\n // confirm (\"rules may vary depending on the timing\"); the answer says.\n cancelAfterAccept: true,\n // 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,\n // Open Delivery's readyForPickup, dispatch and delivered / pickedUp (see `./outbound.ts`).\n statusSteps: [\"READY\", \"DISPATCHED\", \"HANDED_OVER\"],\n },\n normalize: normalizeOpenDeliveryEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyOpenDeliverySignature,\n cancellationReasons: () => reasons,\n // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).\n catalogue: openDeliveryCatalogue(bases),\n fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),\n confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),\n requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),\n statusSupported: openDeliveryStatusSupported,\n informStatus: (ctx, order, facts) => openDeliveryInformStatus(ctx, bases, order, facts),\n appLink: () => config.portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),\n };\n}\n\nexport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nexport { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nexport type { NinetyNineFoodApiBaseUrls } from \"./outbound\";\nexport { openDeliveryCatalogue, openDeliveryMenuDocument } from \"./catalogue\";\nexport { openDeliveryAvailability, openDeliverySetMerchantStatus } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAcO,IAAM,gCAAgC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACUO,IAAM,4BAA4B;AAGzC,IAAM,UAAU;AAEhB,IAAM,YAAY;AAElB,IAAM,eAA+D,EAAE,YAAY,cAAc,WAAW,YAAY;AAExH,IAAM,8BAA8B;AAa7B,SAAS,4BACd,SACA,WACA,eACS;AACT,MAAI,CAAC,cAAe,QAAO;AAC3B,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A/E;AAAA,IACrB,iBAAiB;AAAA,IACjB,cAAc,wBAAC,KAAK,OAAO,UAAU,yBAAyB,KAAK,OAAO,OAAO,KAAK,GAAxE;AAAA,IACd,SAAS,6BAAM,OAAO,WAAb;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,yBAAyB,KAAK,EAAE,IAAI,CAAC;AAAA,EACvF;AACF;AA5CgB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/99food/copy.ts","../../src/99food/normalize.ts","../../src/99food/outbound.ts","../../src/99food/catalogue.ts","../../src/99food/pause.ts","../../src/99food/index.ts"],"sourcesContent":["import { OPEN_DELIVERY_MERCHANT_REASON_CODES } from \"../open-delivery/reasons\";\n\n/**\n * The words the 99Food adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/** The cancellation codes a merchant may send: Open Delivery v1.7.1's (`../open-delivery/reasons.ts`). */\nexport const NINETY_NINE_FOOD_REASON_CODES = OPEN_DELIVERY_MERCHANT_REASON_CODES;\n\nexport type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];\n\nexport interface NinetyNineFoodAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import type { NormalizedEvent, NormalizedMarketplaceOrder } from \"../core/types\";\nimport { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from \"../open-delivery/normalize\";\n\n/**\n * The 99Food adapter's INBOUND half: Open Delivery v1.7.1's readers\n * (`../open-delivery/normalize.ts`), stamped with 99Food's provider id. 99Food\n * departs from the standard in nothing inbound: the `X-App-Signature` is the\n * standard's lowercase-hex HMAC-SHA256 of the body.\n */\n\n/** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const NINETY_NINE_FOOD_PROVIDER = \"NINETY_NINE_FOOD\";\n\nexport { verifyOpenDeliverySignature } from \"../open-delivery/normalize\";\n\n/** Normalize one webhook `Event` (see `normalizeOpenDeliveryEventAs`). Null only when it names no order. */\nexport function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {\n return normalizeOpenDeliveryEventAs(NINETY_NINE_FOOD_PROVIDER, payload);\n}\n\n/** Normalize one `Order` (see `normalizeOpenDeliveryOrderAs`). Null when it carries no id or no line. */\nexport function normalizeOpenDeliveryOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n return normalizeOpenDeliveryOrderAs(NINETY_NINE_FOOD_PROVIDER, order, options);\n}\n","import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from \"../open-delivery/client\";\nimport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/**\n * 99Food's Open Delivery DIALECT: v1.7.1 as the standard writes it. The calls\n * themselves (the grant, the order fetch, confirm, requestCancellation, the\n * status steps) are `../open-delivery/`'s; this file only says where and how\n * 99Food takes them.\n *\n * - Token: `POST /oauth/token`, form-encoded `client_id`, `client_secret`,\n * `grant_type=client_credentials`.\n * - Bodies: plain JSON; no request signature.\n *\n * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the\n * paths under each Ordering Application's own base URL, and 99Food gives its\n * base URLs to a partner at onboarding. So the base URL per environment is\n * the adapter's REQUIRED config, never a guessed default.\n */\n\n/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */\nexport type NinetyNineFoodApiBaseUrls = OpenDeliveryApiBaseUrls;\n\n/** 99Food's dialect, for the base URLs it was given. */\nexport function ninetyNineFoodDialect(bases: NinetyNineFoodApiBaseUrls): OpenDeliveryDialect {\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n name: \"99Food\",\n bases,\n tokenGrant: (ctx) => ({\n contentType: \"application/x-www-form-urlencoded\",\n body: new URLSearchParams({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"client_credentials\",\n }).toString(),\n }),\n serialize: (body) => JSON.stringify(body),\n };\n}\n","import type { PullCatalogue } from \"../core/catalogue-port\";\nimport { openDeliveryMenuDocument, openDeliveryMerchantUpdate } from \"../open-delivery/merchant\";\nimport { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).\n *\n * In Open Delivery the store's software does not write the menu to the\n * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a\n * `Merchant` document carrying `menus`, `categories`, `items` and\n * `itemOffers`, and the ORDERING APPLICATION (99Food) pulls it, again when its\n * `TTL` runs out or when told the merchant changed (`POST\n * /v1/merchantUpdate`, sent with an empty body: \"pull everything again\").\n * Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml\n *\n * So the adapter does two things: build the menu part of that document from\n * the items the store switched on (`menuDocument`, pure, shared:\n * `../open-delivery/merchant.ts`; the host merges it into the rest of the\n * `Merchant`, which is its own: `basicInfo`, `services`, `lastUpdate`, `TTL`,\n * `status`), and tell 99Food the menu changed (`notifyMenuChanged`).\n *\n * ESTIMATED, to be checked once 99Food grants partner access:\n * - the path: the spec's route table and prose name `POST /merchantUpdate`\n * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this\n * sends the prose's;\n * - the `X-App-MerchantId` header on it: the operation lists none, and one\n * client app may serve many merchants, so it is sent to name which;\n * - that 99Food reads the whole `Merchant` on that notification (scenario 1\n * of the operation) rather than needing `entityType`/`updatedObjects`.\n */\n\nexport { openDeliveryMenuDocument } from \"../open-delivery/merchant\";\n\n/** 99Food's catalogue capability, for the base URLs it was given. */\nexport function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {\n const dialect = ninetyNineFoodDialect(bases);\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n // No body: 99Food pulls the whole `Merchant` again. 200 or 204.\n notifyMenuChanged: (ctx) =>\n openDeliveryMerchantUpdate(ctx, dialect, {\n path: \"/v1/merchantUpdate\",\n headers: { \"X-App-MerchantId\": ctx.externalMerchantId },\n }),\n };\n}\n","import type { AdapterCallContext, OutboundResult } from \"../core/adapter\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport { openDeliveryMerchantUpdate, openDeliverySwitchAvailability } from \"../open-delivery/merchant\";\nimport { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the\n * software PUSHES the merchant's status to the Ordering Application.\n *\n * `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)\n * \"sent with only the `merchantStatus` field ... will force the opening or\n * closing of the merchant within the Ordering Application\"; `merchantStatus`\n * is `AVAILABLE | UNAVAILABLE`, \"only use this type when you must close\n * (disable) the merchant due to an unexpected event and you don't know when\n * the service will be re-established\"; 204 (200 \"for compatibility\"), 400,\n * 401, 403, 404, 503 (openapi.yaml v1.7.1, README \"Pausing a store\").\n *\n * A SWITCH, with no id and no end, so offered only when the host opts in\n * (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path\n * (the spec files this webhook under the key `/v1/menuUpdated` while its own\n * description and route table say `POST /v1/merchantUpdate`; the latter is\n * sent), that 99Food implements it at all, and that the token names the\n * merchant (Open Delivery authenticates per merchant, so the body names none).\n */\n\n/** Set the merchant's status. */\nexport function openDeliverySetMerchantStatus(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n status: \"AVAILABLE\" | \"UNAVAILABLE\",\n): Promise<OutboundResult> {\n return openDeliveryMerchantUpdate(ctx, ninetyNineFoodDialect(bases), {\n path: \"/v1/merchantUpdate\",\n body: { merchantStatus: status },\n });\n}\n\n/** 99Food's availability capability: Open Delivery's merchant status, a switch. */\nexport function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {\n return openDeliverySwitchAvailability((ctx, _merchantId, status) => openDeliverySetMerchantStatus(ctx, bases, status));\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryRequestCancellation,\n openDeliveryStatus,\n} from \"../open-delivery/orders\";\nimport { assertHttpsUrl } from \"../open-delivery/client\";\nimport { OPEN_DELIVERY_ITEM_UNAVAILABLE } from \"../open-delivery/reasons\";\nimport { NINETY_NINE_FOOD_REASON_CODES, type NinetyNineFoodAdapterCopy } from \"./copy\";\nimport { openDeliveryCatalogue } from \"./catalogue\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nimport { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\nimport { openDeliveryAvailability } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.\n *\n * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks\n * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,\n * confirm, requestCancellation with the spec's codes. The standard's calls\n * and readers are `../open-delivery/`, shared with Keeta; what is 99Food's\n * (its dialect, its copy, its ESTIMATED choices) is under this folder; the engine reaches it only through the\n * {@link MarketplaceAdapter} port, and registering it is the whole cost:\n *\n * ```ts\n * import { createNinetyNineFoodAdapter } from \"@12-apps/marketplace/99food\";\n * import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/99food/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),\n * ],\n * });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.\n */\n\nexport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */\nexport const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** 99Food serves `pickedUp` for a take-out (v1.7.1). */\nconst STATUS = openDeliveryStatus({ takeoutPickedUp: true });\n\nexport interface NinetyNineFoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: NinetyNineFoodAdapterCopy;\n /**\n * Where 99Food serves Open Delivery, per environment: the base the spec's\n * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at\n * onboarding and not public, so required and defaultless. https only.\n */\n apiBaseUrl: NinetyNineFoodApiBaseUrls;\n /**\n * Where \"open it on 99Food\" goes: the merchant portal. Open Delivery names no\n * per-order deep link, so the link is the portal. Required; https only.\n */\n portalUrl: string;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open\n * Delivery's `merchantStatus`, a store-wide switch with no id: a store the\n * owner also closed by hand on 99Food during the kitchen's pause is opened\n * with it. A host turns this on knowing that.\n */\n pauseByStoreSwitch?: boolean;\n}\n\nconst assertHttps = (name: string, url: string): void => assertHttpsUrl(\"@12-apps/marketplace/99food\", name, url);\n\n/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */\nexport function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {\n assertHttps(\"apiBaseUrl.SANDBOX\", config.apiBaseUrl.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", config.apiBaseUrl.PRODUCTION);\n assertHttps(\"portalUrl\", config.portalUrl);\n const dialect = ninetyNineFoodDialect({ ...config.apiBaseUrl });\n const bases = dialect.bases;\n const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional in the spec, and not sent (see `cancellation` below).\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n const fetchOptions = { normalize: (order: unknown) => normalizeOpenDeliveryOrder(order, normalizeOptions) };\n // `outOfStockItems` wants 99Food's item uuids; the engine keeps SKUs (`externalCode`). Not sent.\n const cancellation = { outOfStockAsSkus: false };\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // The spec lets a merchant request a cancellation before or after the\n // confirm (\"rules may vary depending on the timing\"); the answer says.\n cancelAfterAccept: true,\n // 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,\n // Open Delivery's readyForPickup, dispatch and delivered / pickedUp (`../open-delivery/orders.ts`).\n statusSteps: [\"READY\", \"DISPATCHED\", \"HANDED_OVER\"],\n },\n normalize: normalizeOpenDeliveryEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyOpenDeliverySignature,\n cancellationReasons: () => reasons,\n // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).\n catalogue: openDeliveryCatalogue(bases),\n fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, dialect, order, fetchOptions),\n confirm: (ctx, order, input) => openDeliveryConfirm(ctx, dialect, order, input),\n requestCancellation: (ctx, order, input) =>\n openDeliveryRequestCancellation(ctx, dialect, order, input, cancellation),\n statusSupported: STATUS.supported,\n informStatus: (ctx, order, facts) => STATUS.inform(ctx, dialect, order, facts),\n appLink: () => config.portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),\n };\n}\n\nexport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nexport { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nexport type { NinetyNineFoodApiBaseUrls } from \"./outbound\";\nexport { openDeliveryCatalogue, openDeliveryMenuDocument } from \"./catalogue\";\nexport { openDeliveryAvailability, openDeliverySetMerchantStatus } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,gCAAgC;;;ACAtC,IAAM,4BAA4B;AAKlC,SAAS,2BAA2B,SAA0C;AACnF,SAAO,6BAA6B,2BAA2B,OAAO;AACxE;AAFgB;AAKT,SAAS,2BACd,OACA,SACmC;AACnC,SAAO,6BAA6B,2BAA2B,OAAO,OAAO;AAC/E;AALgB;;;ACET,SAAS,sBAAsB,OAAuD;AAC3F,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM;AAAA,IACN;AAAA,IACA,YAAY,wBAAC,SAAS;AAAA,MACpB,aAAa;AAAA,MACb,MAAM,IAAI,gBAAgB;AAAA,QACxB,WAAW,IAAI,YAAY;AAAA,QAC3B,eAAe,IAAI,YAAY;AAAA,QAC/B,YAAY;AAAA,MACd,CAAC,EAAE,SAAS;AAAA,IACd,IAPY;AAAA,IAQZ,WAAW,wBAAC,SAAS,KAAK,UAAU,IAAI,GAA7B;AAAA,EACb;AACF;AAfgB;;;ACWT,SAAS,sBAAsB,OAAiD;AACrF,QAAM,UAAU,sBAAsB,KAAK;AAC3C,SAAO;AAAA,IACL,MAAM;AAAA,IACN,cAAc;AAAA;AAAA,IAEd,mBAAmB,wBAAC,QAClB,2BAA2B,KAAK,SAAS;AAAA,MACvC,MAAM;AAAA,MACN,SAAS,EAAE,oBAAoB,IAAI,mBAAmB;AAAA,IACxD,CAAC,GAJgB;AAAA,EAKrB;AACF;AAZgB;;;ACRT,SAAS,8BACd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,SAAS,cAAc,aAAa;AAAA,IACpD;AAAA,IACA,WAAW;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,iBAAiB,GAApC;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA;AAAA,IAErB,WAAW,sBAAsB,KAAK;AAAA,IACtC,YAAY,wBAAC,KAAK,UAAU,uBAAuB,KAAK,SAAS,OAAO,YAAY,GAAxE;AAAA,IACZ,SAAS,wBAAC,KAAK,OAAO,UAAU,oBAAoB,KAAK,SAAS,OAAO,KAAK,GAArE;AAAA,IACT,qBAAqB,wBAAC,KAAK,OAAO,UAChC,gCAAgC,KAAK,SAAS,OAAO,OAAO,YAAY,GADrD;AAAA,IAErB,iBAAiB,OAAO;AAAA,IACxB,cAAc,wBAAC,KAAK,OAAO,UAAU,OAAO,OAAO,KAAK,SAAS,OAAO,KAAK,GAA/D;AAAA,IACd,SAAS,6BAAM,OAAO,WAAb;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,yBAAyB,KAAK,EAAE,IAAI,CAAC;AAAA,EACvF;AACF;AAjDgB;","names":[]}
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
import {
|
|
2
|
+
stableUuid
|
|
3
|
+
} from "./chunk-M2V4RFMA.js";
|
|
4
|
+
import {
|
|
5
|
+
asString,
|
|
6
|
+
firstCents,
|
|
7
|
+
firstDate,
|
|
8
|
+
firstString,
|
|
9
|
+
pick,
|
|
10
|
+
toCents,
|
|
11
|
+
verifyHmacSha256Hex
|
|
12
|
+
} from "./chunk-BD7DS3XM.js";
|
|
13
|
+
import {
|
|
14
|
+
answered,
|
|
15
|
+
outboundResultOf,
|
|
16
|
+
tokenGrantResultOf
|
|
17
|
+
} from "./chunk-HEXLCTOG.js";
|
|
18
|
+
import {
|
|
19
|
+
__name
|
|
20
|
+
} from "./chunk-7QVYU63E.js";
|
|
21
|
+
|
|
22
|
+
// src/open-delivery/client.ts
|
|
23
|
+
function assertHttpsUrl(packagePath, name, url) {
|
|
24
|
+
let parsed;
|
|
25
|
+
try {
|
|
26
|
+
parsed = new URL(url);
|
|
27
|
+
} catch {
|
|
28
|
+
throw new Error(`${packagePath}: ${name} is not a URL.`);
|
|
29
|
+
}
|
|
30
|
+
if (parsed.protocol !== "https:") throw new Error(`${packagePath}: ${name} must be https.`);
|
|
31
|
+
}
|
|
32
|
+
__name(assertHttpsUrl, "assertHttpsUrl");
|
|
33
|
+
var TOKEN_MARGIN_MS = 6e4;
|
|
34
|
+
var DEFAULT_TOKEN_SECONDS = 3600;
|
|
35
|
+
function baseOf(ctx, bases) {
|
|
36
|
+
const base = bases[ctx.environment];
|
|
37
|
+
let end = base.length;
|
|
38
|
+
while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
|
|
39
|
+
return base.slice(0, end);
|
|
40
|
+
}
|
|
41
|
+
__name(baseOf, "baseOf");
|
|
42
|
+
var tokenKey = /* @__PURE__ */ __name((ctx, dialect) => `${dialect.provider}:${ctx.environment}:${ctx.credentials.clientId}`, "tokenKey");
|
|
43
|
+
function tokenOf(body) {
|
|
44
|
+
try {
|
|
45
|
+
const parsed = JSON.parse(body);
|
|
46
|
+
if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
|
|
47
|
+
const expires = typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
|
|
48
|
+
return { token: parsed.access_token, expiresInSeconds: expires };
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
__name(tokenOf, "tokenOf");
|
|
54
|
+
function signed(ctx, dialect, request) {
|
|
55
|
+
if (!dialect.sign) return request;
|
|
56
|
+
return { ...request, headers: { ...request.headers, ...dialect.sign(ctx, request.url, request.body) } };
|
|
57
|
+
}
|
|
58
|
+
__name(signed, "signed");
|
|
59
|
+
async function bearer(ctx, dialect) {
|
|
60
|
+
const cached = ctx.tokens.get(tokenKey(ctx, dialect));
|
|
61
|
+
if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
|
|
62
|
+
const grant = dialect.tokenGrant(ctx);
|
|
63
|
+
const response = await ctx.http(
|
|
64
|
+
signed(ctx, dialect, {
|
|
65
|
+
method: "POST",
|
|
66
|
+
url: `${baseOf(ctx, dialect.bases)}/oauth/token`,
|
|
67
|
+
headers: { "Content-Type": grant.contentType },
|
|
68
|
+
body: grant.body
|
|
69
|
+
})
|
|
70
|
+
);
|
|
71
|
+
if (response.status < 200 || response.status >= 300) {
|
|
72
|
+
const result = tokenGrantResultOf(response);
|
|
73
|
+
return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
|
|
74
|
+
}
|
|
75
|
+
const token = tokenOf(response.body);
|
|
76
|
+
if (!token) return { kind: "retry", reason: `${dialect.name} answered the token grant without a token` };
|
|
77
|
+
ctx.tokens.set(tokenKey(ctx, dialect), {
|
|
78
|
+
token: token.token,
|
|
79
|
+
expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1e3
|
|
80
|
+
});
|
|
81
|
+
return { token: token.token };
|
|
82
|
+
}
|
|
83
|
+
__name(bearer, "bearer");
|
|
84
|
+
function urlOf(ctx, dialect, call) {
|
|
85
|
+
const query = call.query && Object.keys(call.query).length > 0 ? `?${new URLSearchParams(call.query).toString()}` : "";
|
|
86
|
+
return `${baseOf(ctx, dialect.bases)}${call.path}${query}`;
|
|
87
|
+
}
|
|
88
|
+
__name(urlOf, "urlOf");
|
|
89
|
+
function requestOf(ctx, dialect, call, token) {
|
|
90
|
+
const body = call.body === void 0 ? void 0 : dialect.serialize(call.body);
|
|
91
|
+
return {
|
|
92
|
+
method: call.method,
|
|
93
|
+
url: urlOf(ctx, dialect, call),
|
|
94
|
+
headers: {
|
|
95
|
+
...token === null ? {} : { Authorization: `Bearer ${token}` },
|
|
96
|
+
...body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
97
|
+
...call.headers
|
|
98
|
+
},
|
|
99
|
+
...body === void 0 ? {} : { body }
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
__name(requestOf, "requestOf");
|
|
103
|
+
async function openDeliveryCall(ctx, dialect, call) {
|
|
104
|
+
const authenticated = call.authenticated ?? true;
|
|
105
|
+
const auth = authenticated ? await bearer(ctx, dialect) : null;
|
|
106
|
+
if (auth && !("token" in auth)) return auth;
|
|
107
|
+
const response = await ctx.http(signed(ctx, dialect, requestOf(ctx, dialect, call, auth?.token ?? null)));
|
|
108
|
+
if (!authenticated || response.status !== 401) return response;
|
|
109
|
+
ctx.tokens.delete(tokenKey(ctx, dialect));
|
|
110
|
+
return { kind: "retry", reason: `${dialect.name} refused the token` };
|
|
111
|
+
}
|
|
112
|
+
__name(openDeliveryCall, "openDeliveryCall");
|
|
113
|
+
var isStop = /* @__PURE__ */ __name((value) => "kind" in value, "isStop");
|
|
114
|
+
|
|
115
|
+
// src/open-delivery/orders.ts
|
|
116
|
+
function callOrder(ctx, dialect, request) {
|
|
117
|
+
const suffix = request.action === null ? "" : `/${request.action}`;
|
|
118
|
+
return openDeliveryCall(ctx, dialect, {
|
|
119
|
+
method: request.method,
|
|
120
|
+
path: `/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,
|
|
121
|
+
...request.body === void 0 ? {} : { body: request.body }
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
__name(callOrder, "callOrder");
|
|
125
|
+
function alreadyCancelled(response) {
|
|
126
|
+
if (response.status !== 422) return false;
|
|
127
|
+
try {
|
|
128
|
+
return JSON.parse(response.body).cancellationStatus === "CANCELLED";
|
|
129
|
+
} catch {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
__name(alreadyCancelled, "alreadyCancelled");
|
|
134
|
+
async function fetched(call) {
|
|
135
|
+
try {
|
|
136
|
+
return await call();
|
|
137
|
+
} catch (error) {
|
|
138
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
__name(fetched, "fetched");
|
|
142
|
+
function openDeliveryFetchOrder(ctx, dialect, order, options) {
|
|
143
|
+
return fetched(async () => {
|
|
144
|
+
const response = await callOrder(ctx, dialect, { method: "GET", externalOrderId: order.externalOrderId, action: null });
|
|
145
|
+
if (isStop(response)) return response;
|
|
146
|
+
const result = outboundResultOf(response);
|
|
147
|
+
if (result.kind !== "accepted") return result;
|
|
148
|
+
let body;
|
|
149
|
+
try {
|
|
150
|
+
body = JSON.parse(response.body);
|
|
151
|
+
} catch {
|
|
152
|
+
return { kind: "refused", status: response.status, message: "the order is not JSON" };
|
|
153
|
+
}
|
|
154
|
+
const prepared = options.prepare ? await options.prepare(ctx, body) : body;
|
|
155
|
+
const normalized = options.normalize(prepared);
|
|
156
|
+
return normalized ? { kind: "order", order: normalized } : { kind: "refused", status: response.status, message: "the order carries no id or no line" };
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
__name(openDeliveryFetchOrder, "openDeliveryFetchOrder");
|
|
160
|
+
function openDeliveryConfirm(ctx, dialect, order, input) {
|
|
161
|
+
return answered(async () => {
|
|
162
|
+
const response = await callOrder(ctx, dialect, {
|
|
163
|
+
method: "POST",
|
|
164
|
+
externalOrderId: order.externalOrderId,
|
|
165
|
+
action: "confirm",
|
|
166
|
+
body: {
|
|
167
|
+
orderExternalCode: order.hostOrderCode,
|
|
168
|
+
createdAt: ctx.now.toISOString(),
|
|
169
|
+
...input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
return isStop(response) ? response : outboundResultOf(response);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
__name(openDeliveryConfirm, "openDeliveryConfirm");
|
|
176
|
+
var MAX_OUT_OF_STOCK_ITEMS = 100;
|
|
177
|
+
function openDeliveryRequestCancellation(ctx, dialect, order, input, options) {
|
|
178
|
+
const skus = options.outOfStockAsSkus && input.reason.itemUnavailable && input.offendingSkus.length > 0 ? { outOfStockItems: input.offendingSkus.slice(0, MAX_OUT_OF_STOCK_ITEMS) } : {};
|
|
179
|
+
return answered(async () => {
|
|
180
|
+
const response = await callOrder(ctx, dialect, {
|
|
181
|
+
method: "POST",
|
|
182
|
+
externalOrderId: order.externalOrderId,
|
|
183
|
+
action: "requestCancellation",
|
|
184
|
+
body: {
|
|
185
|
+
reason: input.text === "" ? input.reason.label : input.text,
|
|
186
|
+
code: input.reason.code,
|
|
187
|
+
mode: input.mode,
|
|
188
|
+
...skus
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
if (isStop(response)) return response;
|
|
192
|
+
if (alreadyCancelled(response)) return { kind: "accepted" };
|
|
193
|
+
const result = outboundResultOf(response);
|
|
194
|
+
return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
__name(openDeliveryRequestCancellation, "openDeliveryRequestCancellation");
|
|
198
|
+
function statusPaths(options) {
|
|
199
|
+
return {
|
|
200
|
+
READY: /* @__PURE__ */ __name(() => ({ action: "readyForPickup" }), "READY"),
|
|
201
|
+
DISPATCHED: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? { action: "dispatch", body: {} } : null, "DISPATCHED"),
|
|
202
|
+
HANDED_OVER: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? { action: "delivered", body: {} } : facts.deliveredBy === null && options.takeoutPickedUp ? { action: "pickedUp", body: {} } : null, "HANDED_OVER")
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
__name(statusPaths, "statusPaths");
|
|
206
|
+
function openDeliveryStatus(options) {
|
|
207
|
+
const paths = statusPaths(options);
|
|
208
|
+
return {
|
|
209
|
+
supported: /* @__PURE__ */ __name((facts) => paths[facts.step]?.(facts) != null, "supported"),
|
|
210
|
+
inform(ctx, dialect, order, facts) {
|
|
211
|
+
const path = paths[facts.step]?.(facts) ?? null;
|
|
212
|
+
if (path === null) return Promise.resolve({ kind: "unsupported" });
|
|
213
|
+
return answered(async () => {
|
|
214
|
+
const response = await callOrder(ctx, dialect, {
|
|
215
|
+
method: "POST",
|
|
216
|
+
externalOrderId: order.externalOrderId,
|
|
217
|
+
action: path.action,
|
|
218
|
+
...path.body === void 0 ? {} : { body: path.body }
|
|
219
|
+
});
|
|
220
|
+
return isStop(response) ? response : outboundResultOf(response);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
__name(openDeliveryStatus, "openDeliveryStatus");
|
|
226
|
+
|
|
227
|
+
// src/open-delivery/reasons.ts
|
|
228
|
+
var OPEN_DELIVERY_MERCHANT_REASON_CODES = [
|
|
229
|
+
"SYSTEMIC_ISSUES",
|
|
230
|
+
"DUPLICATE_APPLICATION",
|
|
231
|
+
"UNAVAILABLE_ITEM",
|
|
232
|
+
"RESTAURANT_WITHOUT_DELIVERY_PERSON",
|
|
233
|
+
"OUTDATED_MENU",
|
|
234
|
+
"ORDER_OUTSIDE_THE_DELIVERY_AREA",
|
|
235
|
+
"BLOCKED_CUSTOMER",
|
|
236
|
+
"OUTSIDE_DELIVERY_HOURS",
|
|
237
|
+
"INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT",
|
|
238
|
+
"RISK_AREA",
|
|
239
|
+
"DELIVERY_PROBLEM"
|
|
240
|
+
];
|
|
241
|
+
var OPEN_DELIVERY_ITEM_UNAVAILABLE = "UNAVAILABLE_ITEM";
|
|
242
|
+
|
|
243
|
+
// src/open-delivery/merchant.ts
|
|
244
|
+
function categoriesOf(merchantId, entries) {
|
|
245
|
+
const byName = /* @__PURE__ */ new Map();
|
|
246
|
+
for (const entry of entries) {
|
|
247
|
+
const name = entry.categoryName.trim();
|
|
248
|
+
const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };
|
|
249
|
+
category.offers.push(stableUuid(`${entry.ref}:offer`));
|
|
250
|
+
byName.set(name, category);
|
|
251
|
+
}
|
|
252
|
+
return [...byName.values()];
|
|
253
|
+
}
|
|
254
|
+
__name(categoriesOf, "categoriesOf");
|
|
255
|
+
function openDeliveryMenuDocument(input) {
|
|
256
|
+
const { externalMerchantId: merchantId, entries, options } = input;
|
|
257
|
+
const categories = categoriesOf(merchantId, entries);
|
|
258
|
+
return {
|
|
259
|
+
menus: [
|
|
260
|
+
{
|
|
261
|
+
id: stableUuid(`${merchantId}:menu`),
|
|
262
|
+
name: options.menuName,
|
|
263
|
+
externalCode: "menu",
|
|
264
|
+
categoryId: categories.map((category) => category.id)
|
|
265
|
+
}
|
|
266
|
+
],
|
|
267
|
+
categories: categories.map((category, index) => ({
|
|
268
|
+
id: category.id,
|
|
269
|
+
index,
|
|
270
|
+
name: category.name,
|
|
271
|
+
externalCode: category.name,
|
|
272
|
+
status: "AVAILABLE",
|
|
273
|
+
itemOfferId: category.offers
|
|
274
|
+
})),
|
|
275
|
+
items: entries.map((entry) => ({
|
|
276
|
+
id: stableUuid(`${entry.ref}:item`),
|
|
277
|
+
name: entry.name,
|
|
278
|
+
description: entry.description ?? "",
|
|
279
|
+
externalCode: entry.productId,
|
|
280
|
+
status: "AVAILABLE",
|
|
281
|
+
unit: "UN",
|
|
282
|
+
...entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }
|
|
283
|
+
})),
|
|
284
|
+
itemOffers: entries.map((entry, index) => {
|
|
285
|
+
const value = Math.round(entry.priceCents) / 100;
|
|
286
|
+
return {
|
|
287
|
+
id: stableUuid(`${entry.ref}:offer`),
|
|
288
|
+
itemId: stableUuid(`${entry.ref}:item`),
|
|
289
|
+
index,
|
|
290
|
+
status: "AVAILABLE",
|
|
291
|
+
price: { value, originalValue: value, currency: options.currency }
|
|
292
|
+
};
|
|
293
|
+
})
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
__name(openDeliveryMenuDocument, "openDeliveryMenuDocument");
|
|
297
|
+
function openDeliveryMerchantUpdate(ctx, dialect, update) {
|
|
298
|
+
return answered(async () => {
|
|
299
|
+
const response = await openDeliveryCall(ctx, dialect, {
|
|
300
|
+
method: "POST",
|
|
301
|
+
path: update.path,
|
|
302
|
+
...update.body === void 0 ? {} : { body: update.body },
|
|
303
|
+
...update.headers === void 0 ? {} : { headers: update.headers }
|
|
304
|
+
});
|
|
305
|
+
return isStop(response) ? response : outboundResultOf(response);
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
__name(openDeliveryMerchantUpdate, "openDeliveryMerchantUpdate");
|
|
309
|
+
function openDeliverySwitchAvailability(setStatus) {
|
|
310
|
+
return {
|
|
311
|
+
kind: "switch",
|
|
312
|
+
pause: /* @__PURE__ */ __name(async (ctx, request) => {
|
|
313
|
+
const result = await setStatus(ctx, request.merchantId, "UNAVAILABLE");
|
|
314
|
+
return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
|
|
315
|
+
}, "pause"),
|
|
316
|
+
resume: /* @__PURE__ */ __name((ctx, ref) => setStatus(ctx, ref.merchantId, "AVAILABLE"), "resume")
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
__name(openDeliverySwitchAvailability, "openDeliverySwitchAvailability");
|
|
320
|
+
|
|
321
|
+
// src/open-delivery/normalize.ts
|
|
322
|
+
var CREATED = "CREATED";
|
|
323
|
+
var CANCELLED = "CANCELLED";
|
|
324
|
+
var LIFECYCLE_OF = { DISPATCHED: "DISPATCHED", CONCLUDED: "CONCLUDED" };
|
|
325
|
+
var CANCELLATION_REQUEST_DENIED = "CANCELLATION_REQUEST_DENIED";
|
|
326
|
+
function verifyOpenDeliverySignature(rawBody, signature, webhookSecret) {
|
|
327
|
+
if (!webhookSecret) return false;
|
|
328
|
+
return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
|
|
329
|
+
}
|
|
330
|
+
__name(verifyOpenDeliverySignature, "verifyOpenDeliverySignature");
|
|
331
|
+
function normalizeOpenDeliveryEventAs(provider, payload) {
|
|
332
|
+
const externalOrderId = firstString(payload, [["orderId"]]);
|
|
333
|
+
if (!externalOrderId) return null;
|
|
334
|
+
const eventType = (firstString(payload, [["eventType"]]) ?? "UNKNOWN").toUpperCase();
|
|
335
|
+
const cancelled = eventType === CANCELLED;
|
|
336
|
+
const denied = eventType === CANCELLATION_REQUEST_DENIED;
|
|
337
|
+
return {
|
|
338
|
+
provider,
|
|
339
|
+
// The spec's own event id. The fallback is deterministic so a redelivery
|
|
340
|
+
// still collides on the inbox's unique index.
|
|
341
|
+
eventId: firstString(payload, [["eventId"]]) ?? `${externalOrderId}:${eventType}`,
|
|
342
|
+
eventType,
|
|
343
|
+
externalMerchantId: null,
|
|
344
|
+
externalOrderId,
|
|
345
|
+
order: null,
|
|
346
|
+
orderToFetch: eventType === CREATED,
|
|
347
|
+
cancelled,
|
|
348
|
+
cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null,
|
|
349
|
+
...LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
__name(normalizeOpenDeliveryEventAs, "normalizeOpenDeliveryEventAs");
|
|
353
|
+
function priceCents(source, ...path) {
|
|
354
|
+
return toCents(pick(source, ...path, "value"));
|
|
355
|
+
}
|
|
356
|
+
__name(priceCents, "priceCents");
|
|
357
|
+
function lineNote(item, fraction) {
|
|
358
|
+
const rawOptions = pick(item, "options");
|
|
359
|
+
const options = (Array.isArray(rawOptions) ? rawOptions : []).map((option) => {
|
|
360
|
+
const name = asString(pick(option, "name"));
|
|
361
|
+
const quantity = Number(pick(option, "quantity") ?? 1);
|
|
362
|
+
return name && quantity > 1 ? `${quantity}x ${name}` : name;
|
|
363
|
+
}).filter((name) => name !== null);
|
|
364
|
+
const parts = [fraction, options.join(", ") || null, firstString(item, [["specialInstructions"]])];
|
|
365
|
+
const note = parts.filter((part) => part !== null).join(" \xB7 ");
|
|
366
|
+
return note === "" ? null : note;
|
|
367
|
+
}
|
|
368
|
+
__name(lineNote, "lineNote");
|
|
369
|
+
function lineTotalCents(item, quantity) {
|
|
370
|
+
const total = priceCents(item, "totalPrice");
|
|
371
|
+
if (total !== null) return total;
|
|
372
|
+
const unit = priceCents(item, "unitPrice") ?? 0;
|
|
373
|
+
return Math.round(unit * quantity) + (priceCents(item, "optionsPrice") ?? 0);
|
|
374
|
+
}
|
|
375
|
+
__name(lineTotalCents, "lineTotalCents");
|
|
376
|
+
function quantityOf(item) {
|
|
377
|
+
const stated = Number(pick(item, "quantity") ?? 1);
|
|
378
|
+
return Number.isFinite(stated) && stated > 0 ? stated : 1;
|
|
379
|
+
}
|
|
380
|
+
__name(quantityOf, "quantityOf");
|
|
381
|
+
function splitWhole(total, quantity) {
|
|
382
|
+
const floor = Math.floor(total / quantity);
|
|
383
|
+
const remainder = total - floor * quantity;
|
|
384
|
+
if (remainder === 0) return [{ quantity, unitPriceCents: floor }];
|
|
385
|
+
const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];
|
|
386
|
+
return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];
|
|
387
|
+
}
|
|
388
|
+
__name(splitWhole, "splitWhole");
|
|
389
|
+
function readLines(item) {
|
|
390
|
+
const name = firstString(item, [["name"]]);
|
|
391
|
+
const sku = firstString(item, [["externalCode"], ["id"]]) ?? name;
|
|
392
|
+
if (!sku) return [];
|
|
393
|
+
const quantity = quantityOf(item);
|
|
394
|
+
const whole = Number.isInteger(quantity);
|
|
395
|
+
const fraction = whole ? null : `${quantity} ${firstString(item, [["unit"]]) ?? ""}`.trim();
|
|
396
|
+
const total = lineTotalCents(item, quantity);
|
|
397
|
+
const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];
|
|
398
|
+
const note = lineNote(item, fraction);
|
|
399
|
+
return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));
|
|
400
|
+
}
|
|
401
|
+
__name(readLines, "readLines");
|
|
402
|
+
function readOrderType(order) {
|
|
403
|
+
const stated = firstString(order, [["type"]])?.toUpperCase();
|
|
404
|
+
return stated === "DELIVERY" || stated === "TAKEOUT" ? stated : null;
|
|
405
|
+
}
|
|
406
|
+
__name(readOrderType, "readOrderType");
|
|
407
|
+
function readDeliveredBy(order) {
|
|
408
|
+
const stated = firstString(order, [["delivery", "deliveredBy"]])?.toUpperCase();
|
|
409
|
+
return stated === "MERCHANT" || stated === "MARKETPLACE" ? stated : null;
|
|
410
|
+
}
|
|
411
|
+
__name(readDeliveredBy, "readDeliveredBy");
|
|
412
|
+
function readAddress(order, missingStreetNumber) {
|
|
413
|
+
const raw = pick(order, "delivery", "deliveryAddress");
|
|
414
|
+
const street = firstString(raw, [["street"], ["streetName"]]);
|
|
415
|
+
if (street === null) return null;
|
|
416
|
+
return {
|
|
417
|
+
street,
|
|
418
|
+
number: firstString(raw, [["number"], ["streetNumber"]]) ?? missingStreetNumber,
|
|
419
|
+
neighborhood: firstString(raw, [["district"], ["neighborhood"]]) ?? "",
|
|
420
|
+
complement: firstString(raw, [["complement"]]),
|
|
421
|
+
reference: firstString(raw, [["reference"]]),
|
|
422
|
+
postalCode: firstString(raw, [["postalCode"]])?.replace(/\D/g, "") || null,
|
|
423
|
+
city: firstString(raw, [["city"]]),
|
|
424
|
+
state: firstString(raw, [["state"]])?.replace(/^[A-Z]{2}-/u, "") ?? null
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
__name(readAddress, "readAddress");
|
|
428
|
+
function normalizeOpenDeliveryOrderAs(provider, order, options) {
|
|
429
|
+
const externalOrderId = firstString(order, [["id"]]);
|
|
430
|
+
const rawItems = pick(order, "items");
|
|
431
|
+
const lines = (Array.isArray(rawItems) ? rawItems : []).flatMap(readLines);
|
|
432
|
+
if (!externalOrderId || lines.length === 0) return null;
|
|
433
|
+
return {
|
|
434
|
+
provider,
|
|
435
|
+
externalOrderId,
|
|
436
|
+
externalDisplayId: firstString(order, [["displayId"]]),
|
|
437
|
+
externalMerchantId: firstString(order, [["merchant", "id"]]),
|
|
438
|
+
buyer: {
|
|
439
|
+
externalId: firstString(order, [["customer", "id"]]),
|
|
440
|
+
name: firstString(order, [["customer", "name"]]),
|
|
441
|
+
phone: firstString(order, [["customer", "phone", "number"]])
|
|
442
|
+
},
|
|
443
|
+
lines,
|
|
444
|
+
// The line sum is the FALLBACK: the stated total carries the fees and
|
|
445
|
+
// discounts the lines do not, and it is the number on the receipt.
|
|
446
|
+
totalCents: firstCents(order, [["total", "orderAmount", "value"]]) ?? lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),
|
|
447
|
+
commissionCents: null,
|
|
448
|
+
deliveryDueAt: firstDate(order, [
|
|
449
|
+
["delivery", "estimatedDeliveryDateTime"],
|
|
450
|
+
["takeout", "takeoutDateTime"],
|
|
451
|
+
["schedule", "scheduledDateTimeEnd"]
|
|
452
|
+
]),
|
|
453
|
+
placedAt: firstDate(order, [["createdAt"]]) ?? /* @__PURE__ */ new Date(),
|
|
454
|
+
orderType: readOrderType(order),
|
|
455
|
+
deliveredBy: readDeliveredBy(order),
|
|
456
|
+
deliveryAddress: readAddress(order, options.missingStreetNumber)
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
__name(normalizeOpenDeliveryOrderAs, "normalizeOpenDeliveryOrderAs");
|
|
460
|
+
|
|
461
|
+
export {
|
|
462
|
+
assertHttpsUrl,
|
|
463
|
+
openDeliveryCall,
|
|
464
|
+
isStop,
|
|
465
|
+
openDeliveryFetchOrder,
|
|
466
|
+
openDeliveryConfirm,
|
|
467
|
+
openDeliveryRequestCancellation,
|
|
468
|
+
openDeliveryStatus,
|
|
469
|
+
OPEN_DELIVERY_MERCHANT_REASON_CODES,
|
|
470
|
+
OPEN_DELIVERY_ITEM_UNAVAILABLE,
|
|
471
|
+
openDeliveryMenuDocument,
|
|
472
|
+
openDeliveryMerchantUpdate,
|
|
473
|
+
openDeliverySwitchAvailability,
|
|
474
|
+
verifyOpenDeliverySignature,
|
|
475
|
+
normalizeOpenDeliveryEventAs,
|
|
476
|
+
normalizeOpenDeliveryOrderAs
|
|
477
|
+
};
|
|
478
|
+
//# sourceMappingURL=chunk-PYHNM47K.js.map
|