@12-apps/marketplace 1.11.0 → 1.13.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 (55) hide show
  1. package/ADOPTING.md +134 -1
  2. package/README.md +49 -3
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CD0SfdVS.d.ts → adapter-CQ4QiZPi.d.ts} +327 -174
  6. package/dist/{chunk-TVZU4HNT.js → chunk-4J2KJ3ZW.js} +1 -1
  7. package/dist/{chunk-TVZU4HNT.js.map → chunk-4J2KJ3ZW.js.map} +1 -1
  8. package/dist/{chunk-YWMEIMO3.js → chunk-CEWTV2TC.js} +176 -40
  9. package/dist/chunk-CEWTV2TC.js.map +1 -0
  10. package/dist/{chunk-DCWOQ5PN.js → chunk-NFJQQWG4.js} +2 -2
  11. package/dist/{chunk-OS4TSIFU.js → chunk-W57TITU4.js} +2 -2
  12. package/dist/{client-11sncog4.d.ts → client-CCSnylou.d.ts} +1 -1
  13. package/dist/{engine-C_3RK8wC.d.ts → engine-1KlJ_8jK.d.ts} +34 -5
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +20 -2
  17. package/dist/ifood/index.js +349 -125
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +162 -65
  21. package/dist/index.js.map +1 -1
  22. package/dist/keeta/index.d.ts +2 -18
  23. package/dist/keeta/index.js +12 -3
  24. package/dist/keeta/index.js.map +1 -1
  25. package/dist/manifest/server.d.ts +2 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +2 -2
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/src/core/adapter.ts +8 -1
  33. package/src/core/connection-stamp.ts +61 -0
  34. package/src/core/courier-port.ts +100 -0
  35. package/src/core/courier.ts +153 -0
  36. package/src/core/engine.ts +4 -1
  37. package/src/core/fetch-order.ts +54 -12
  38. package/src/core/integration.ts +19 -4
  39. package/src/core/lifecycle.ts +27 -4
  40. package/src/core/outbound-queue.ts +24 -11
  41. package/src/core/outbound.ts +8 -6
  42. package/src/core/pickup-code.ts +136 -0
  43. package/src/core/pipeline.ts +15 -6
  44. package/src/core/ports.ts +23 -1
  45. package/src/core/status-store.ts +2 -3
  46. package/src/core/types.ts +56 -4
  47. package/src/ifood/courier.ts +210 -0
  48. package/src/ifood/fetch-order.ts +103 -0
  49. package/src/ifood/index.ts +9 -1
  50. package/src/ifood/normalize.ts +30 -3
  51. package/src/index.ts +16 -0
  52. package/src/keeta/normalize.ts +21 -6
  53. package/dist/chunk-YWMEIMO3.js.map +0 -1
  54. /package/dist/{chunk-DCWOQ5PN.js.map → chunk-NFJQQWG4.js.map} +0 -0
  55. /package/dist/{chunk-OS4TSIFU.js.map → chunk-W57TITU4.js.map} +0 -0
@@ -1,5 +1,5 @@
1
- import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-CD0SfdVS.js';
2
- import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-11sncog4.js';
1
+ import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-CQ4QiZPi.js';
2
+ import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-CCSnylou.js';
3
3
 
4
4
  /**
5
5
  * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
@@ -147,22 +147,6 @@ type KeetaApiBaseUrls = OpenDeliveryApiBaseUrls;
147
147
  */
148
148
  declare const KEETA_API_BASE_URL = "https://open.mykeeta.com/api/open/opendelivery";
149
149
 
150
- /**
151
- * The Keeta adapter's INBOUND half: Open Delivery's readers
152
- * (`../open-delivery/normalize.ts`) stamped with Keeta's provider id, plus
153
- * the one thing Keeta's `Order` does that the standard's does not: personal
154
- * data arrives ENCRYPTED.
155
- *
156
- * Events (Keeta's order guide, read 2026-11-26): `CREATED` → fetch;
157
- * `CANCELLED` (with a JSON-string `metadata` carrying `reason` and `code`) →
158
- * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle. Keeta has NO
159
- * `CANCELLATION_REQUEST_DENIED`: a store's request that Keeta does not grant
160
- * produces no event, so it ends TIMEOUT at the adapter's answer window. The
161
- * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`,
162
- * `RIDER_ARRIVED_AT_STORE`, `ORDER_COLLECTED`, `DELIVERED`,
163
- * `CANCELLATION_REQUESTED`, `USER_REFUND_REQUEST`, `REFUNDED`,
164
- * `REFUND_FAILED`, `RECOMMENDED_PREPARATION_START`) are recorded and IGNORED.
165
- */
166
150
  /** The provider id Keeta is registered under. Uppercase: the column's CHECK holds that shape. */
167
151
  declare const KEETA_PROVIDER = "KEETA";
168
152
  /** Normalize one webhook `Event`. Null only when it names no order. */
@@ -13,16 +13,17 @@ import {
13
13
  openDeliveryRequestCancellation,
14
14
  openDeliveryStatus,
15
15
  openDeliverySwitchAvailability
16
- } from "../chunk-DCWOQ5PN.js";
16
+ } from "../chunk-NFJQQWG4.js";
17
17
  import "../chunk-M2V4RFMA.js";
18
18
  import {
19
19
  asString,
20
+ firstDate,
20
21
  firstString,
21
22
  pick
22
23
  } from "../chunk-BD7DS3XM.js";
23
24
  import {
24
25
  outboundResultOf
25
- } from "../chunk-TVZU4HNT.js";
26
+ } from "../chunk-4J2KJ3ZW.js";
26
27
  import {
27
28
  __name
28
29
  } from "../chunk-7QVYU63E.js";
@@ -173,11 +174,19 @@ function keetaAvailability(dialect) {
173
174
  __name(keetaAvailability, "keetaAvailability");
174
175
 
175
176
  // src/keeta/normalize.ts
177
+ var KEETA_COURIER_STEP_OF = {
178
+ RIDER_ARRIVED_AT_STORE: "ARRIVED_AT_ORIGIN",
179
+ ORDER_COLLECTED: "COLLECTED"
180
+ };
176
181
  var KEETA_PROVIDER = "KEETA";
177
182
  var ENCRYPTED_PREFIX = "ENC_";
178
183
  var DECRYPT_BATCH = 50;
179
184
  function normalizeKeetaEvent(payload) {
180
- return normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);
185
+ const event = normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);
186
+ const step = event ? KEETA_COURIER_STEP_OF[event.eventType] : void 0;
187
+ if (!event || !step) return event;
188
+ const courier = { step, at: firstDate(payload, [["createdAt"]]), courier: null, returning: null };
189
+ return { ...event, courier, ...step === "COLLECTED" ? { lifecycle: "COLLECTED" } : {} };
181
190
  }
182
191
  __name(normalizeKeetaEvent, "normalizeKeetaEvent");
183
192
  function normalizeKeetaOrder(order, options) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/keeta/authorization.ts","../../src/keeta/copy.ts","../../src/keeta/merchant.ts","../../src/keeta/normalize.ts","../../src/keeta/signature.ts","../../src/keeta/outbound.ts","../../src/keeta/index.ts"],"sourcesContent":["import { outboundResultOf, type AdapterCallContext } from \"../core/adapter\";\nimport { asString, firstString, pick } from \"../core/payload-read\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect, type OpenDeliveryStop } from \"../open-delivery/client\";\n\n/**\n * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's\n * \"Autorização Self-serve do Merchant\", read 2026-11-26 at\n * https://api-docs.mykeeta.com/apis/opendelivery/merchant-self-serve-authorization).\n * Not on the adapter port: connecting a store is the host's flow, and these\n * are the calls it is built from.\n *\n * 1. {@link KeetaAuthorization.authorizationUrl}: `GET\n * /oauth/authorization/url?clientId=&redirectUri=` (no token: a token\n * needs at least one authorized store), the link the merchant opens.\n * 2. The merchant authorizes; Keeta redirects to `redirectUri` with `authId`\n * (and `state`, `appId`, `timestamp`), and POSTs the authorization webhook\n * ({@link normalizeKeetaAuthorizationEvent}: `opType` 1 added, 2 revoked).\n * 3. {@link KeetaAuthorization.authorizedShops}: `GET\n * /oauth/authorized/{authId}/merchantInfo?pageNum=&pageSize=` lists the\n * stores of that authorization (Keeta's ids, names, addresses, time zones).\n * 4. The host maps a Keeta store to its own, then\n * {@link KeetaAuthorization.onboard}: `PUT /v1/merchantOnboarding?merchantId=`\n * binds the SOFTWARE's merchant id (the connection's `externalMerchantId`)\n * to `keetaMerchantId` and registers the `GET /v1/merchant` URL and the\n * orders webhook. \"Without onboarding there are no order events\"; sending\n * it again for the same id REPLACES the mapping. Answer 201.\n *\n * ESTIMATED: the JSON answer the authorization webhook wants (\"200 within\n * ~5 s, with JSON containing `code` and `message`\": the values are not\n * given, {@link KEETA_AUTHORIZATION_WEBHOOK_ANSWER} sends 0 and \"success\").\n */\n\n/** What the authorization webhook is answered with, 200, within ~5 s. ESTIMATED values. */\nexport const KEETA_AUTHORIZATION_WEBHOOK_ANSWER = { code: 0, message: \"success\" } as const;\n\n/** One authorization change Keeta reported (event 1301 added, 1302 revoked). */\nexport interface KeetaAuthorizationEvent {\n authId: string;\n change: \"AUTHORIZED\" | \"REVOKED\";\n /** Keeta's store id (an integer on the wire, text here). */\n shopId: string;\n shopName: string | null;\n /** The application's id. */\n clientId: string | null;\n at: Date | null;\n}\n\n/** Read the authorization webhook's body (`WebhookNotification`). Null when it names no authorization or store. */\nexport function normalizeKeetaAuthorizationEvent(payload: unknown): KeetaAuthorizationEvent | null {\n const authId = firstString(payload, [[\"authId\"]]);\n const shopId = firstString(payload, [[\"shopId\"]]);\n const opType = pick(payload, \"opType\");\n const change = opType === 1 ? \"AUTHORIZED\" : opType === 2 ? \"REVOKED\" : null;\n if (!authId || !shopId || !change) return null;\n const millis = pick(payload, \"createTime\");\n return {\n authId,\n change,\n shopId,\n shopName: firstString(payload, [[\"shopName\"]]),\n clientId: firstString(payload, [[\"clientId\"]]),\n at: typeof millis === \"number\" && Number.isFinite(millis) ? new Date(millis) : null,\n };\n}\n\n/** One store of an authorization, as `merchantInfo` lists it. */\nexport interface KeetaAuthorizedShop {\n /** Keeta's store id: the `keetaMerchantId` the onboarding takes. */\n id: string;\n name: string | null;\n address: string | null;\n latitude: number | null;\n longitude: number | null;\n timeZone: string | null;\n}\n\n/** One page of an authorization's stores. */\nexport interface KeetaAuthorizedShops {\n brandId: string | null;\n brandName: string | null;\n shops: KeetaAuthorizedShop[];\n page: { pageNum: number; totalPage: number; totalCount: number };\n}\n\n/** What the host registers for one store at onboarding. */\nexport interface KeetaOnboarding {\n /** The SOFTWARE's merchant id: the connection's `externalMerchantId`, the `Merchant.id` the host serves. */\n merchantId: string;\n /** Keeta's store id, from `authorizedShops` or Keeta's portal. */\n keetaMerchantId: number;\n /** Where Keeta reads this store's `GET /v1/merchant` (one URL per store), and its key if it wants one. */\n merchantDocument?: { url: string; apiKey?: string };\n /** The engine's webhook for this store: `…/webhooks/marketplace/:tenantSlug/KEETA`. */\n ordersWebhookUrl?: string;\n}\n\nexport type KeetaAuthorizationResult<T> = { kind: \"ok\"; value: T } | OpenDeliveryStop;\n\nconst numberOr = (value: unknown, fallback: number | null): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n\nfunction shopOf(raw: unknown): KeetaAuthorizedShop | null {\n const id = firstString(raw, [[\"id\"]]);\n if (!id) return null;\n return {\n id,\n name: firstString(raw, [[\"name\"]]),\n address: firstString(raw, [[\"address\"]]),\n latitude: numberOr(pick(raw, \"latitude\"), null),\n longitude: numberOr(pick(raw, \"longitude\"), null),\n timeZone: firstString(raw, [[\"timeZone\"]]),\n };\n}\n\nfunction shopsOf(body: unknown): KeetaAuthorizedShops {\n const raw = pick(body, \"authorizedShops\");\n return {\n brandId: asString(pick(body, \"brandId\")),\n brandName: firstString(body, [[\"brandName\"]]),\n shops: (Array.isArray(raw) ? raw : []).map(shopOf).filter((shop): shop is KeetaAuthorizedShop => shop !== null),\n page: {\n pageNum: numberOr(pick(body, \"page\", \"pageNum\"), 1) ?? 1,\n totalPage: numberOr(pick(body, \"page\", \"totalPage\"), 1) ?? 1,\n totalCount: numberOr(pick(body, \"page\", \"totalCount\"), 0) ?? 0,\n },\n };\n}\n\n/** One call whose 2xx answer is read by `read`: the value, or the result that ends it. */\nasync function readCall<T>(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n call: Parameters<typeof openDeliveryCall>[2],\n read: (body: unknown) => T | null,\n): Promise<KeetaAuthorizationResult<T>> {\n try {\n const response = await openDeliveryCall(ctx, dialect, call);\n if (isStop(response)) return response;\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n let body: unknown = null;\n try {\n body = response.body === \"\" ? null : JSON.parse(response.body);\n } catch {\n body = null;\n }\n const value = read(body);\n return value === null\n ? { kind: \"refused\", status: response.status, message: \"Keeta's answer is not the documented shape\" }\n : { kind: \"ok\", value };\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** The self-serve authorization calls, bound to Keeta's dialect. */\nexport interface KeetaAuthorization {\n authorizationUrl(ctx: AdapterCallContext, input: { redirectUri?: string }): Promise<KeetaAuthorizationResult<string>>;\n authorizedShops(\n ctx: AdapterCallContext,\n input: { authId: string; pageNum?: number; pageSize?: number },\n ): Promise<KeetaAuthorizationResult<KeetaAuthorizedShops>>;\n onboard(ctx: AdapterCallContext, input: KeetaOnboarding): Promise<KeetaAuthorizationResult<true>>;\n}\n\n/** An https URL Keeta answered, or null. */\nfunction httpsUrl(body: unknown): string | null {\n const url = firstString(body, [[\"merchantAuthorizationUrl\"]]);\n if (!url) return null;\n try {\n return new URL(url).protocol === \"https:\" ? url : null;\n } catch {\n return null;\n }\n}\n\nexport function keetaAuthorization(dialect: OpenDeliveryDialect): KeetaAuthorization {\n return {\n authorizationUrl: (ctx, input) =>\n readCall(\n ctx,\n dialect,\n {\n method: \"GET\",\n path: \"/oauth/authorization/url\",\n query: { clientId: ctx.credentials.clientId, ...(input.redirectUri ? { redirectUri: input.redirectUri } : {}) },\n authenticated: false,\n },\n httpsUrl,\n ),\n authorizedShops: (ctx, input) =>\n readCall(\n ctx,\n dialect,\n {\n method: \"GET\",\n path: `/oauth/authorized/${encodeURIComponent(input.authId)}/merchantInfo`,\n query: { pageNum: String(input.pageNum ?? 1), pageSize: String(Math.min(input.pageSize ?? 100, 100)) },\n },\n (body) => (body === null ? null : shopsOf(body)),\n ),\n onboard: (ctx, input) =>\n readCall(\n ctx,\n dialect,\n {\n method: \"PUT\",\n path: \"/v1/merchantOnboarding\",\n query: { merchantId: input.merchantId },\n body: {\n keetaMerchantId: input.keetaMerchantId,\n ...(input.merchantDocument\n ? {\n getMerchantURL: {\n baseURL: input.merchantDocument.url,\n ...(input.merchantDocument.apiKey ? { apiKey: input.merchantDocument.apiKey } : {}),\n },\n }\n : {}),\n ...(input.ordersWebhookUrl ? { ordersWebhookURL: input.ordersWebhookUrl } : {}),\n },\n },\n () => true as const,\n ),\n };\n}\n","import { OPEN_DELIVERY_MERCHANT_REASON_CODES } from \"../open-delivery/reasons\";\n\n/**\n * The words the Keeta 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: Keeta's \"códigos de\n * cancelamento (v1.0.7+)\", the same eleven as Open Delivery's\n * (`../open-delivery/reasons.ts`). Keeta still accepts its legacy codes\n * (`INSUFFICIENT_DISHES`, `SUSPENSION_OF_BUSINESS`, `INSUFFICIENT_MANPOWER`,\n * `OTHERS`) and recommends the new ones, so only the new ones are offered.\n */\nexport const KEETA_REASON_CODES = OPEN_DELIVERY_MERCHANT_REASON_CODES;\n\nexport type KeetaReasonCode = (typeof KEETA_REASON_CODES)[number];\n\nexport interface KeetaAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<KeetaReasonCode, string>>;\n /** What an address with no street number (or an encrypted one Keeta would not reveal) says instead. */\n missingStreetNumber: string;\n}\n","import type { AdapterCallContext, OutboundResult } from \"../core/adapter\";\nimport type { PullCatalogue } from \"../core/catalogue-port\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport type { OpenDeliveryDialect } from \"../open-delivery/client\";\nimport {\n openDeliveryMenuDocument,\n openDeliveryMerchantUpdate,\n openDeliverySwitchAvailability,\n} from \"../open-delivery/merchant\";\n\n/**\n * Keeta's MERCHANT half: the menu (FUT-4768) and the store pause (FUT-4851),\n * both on `POST /v1/merchantUpdate/{merchantId}` (Keeta's path names the\n * merchant, by the SOFTWARE's id; the standard's names none). Read\n * 2026-11-26 at https://api-docs.mykeeta.com/apis/opendelivery/merchantendpoints/merchantupdate.\n *\n * MENU. Keeta's menu API takes the store's menu three ways: an empty body\n * (\"Keeta calls your `GET /v1/merchant` and reloads everything\"),\n * `merchantStatus` alone, or `entityType` + `updatedObjects`. Of the last,\n * only `ITEM_OFFER` and `OPTION` are applied as sent, and only their\n * `status`; `MENU`, `CATEGORY`, `ITEM`… still make Keeta pull the whole menu\n * (\"only full-menu update\"). So a product cannot be PUSHED to Keeta: its\n * name, photo and price reach Keeta only through the `Merchant` document the\n * host serves. The adapter is therefore PULL: `menuDocument` builds the menu\n * part of that document (shared with 99Food: every item `UN` with a status,\n * every offer with `originalValue`, which Keeta requires), and\n * `notifyMenuChanged` sends the empty-body update that makes Keeta pull it.\n *\n * What Keeta reads of the rest of the `Merchant`, the host's to serve (Keeta's\n * `getMerchant` page): `id`, `status`, `basicInfo.contactEmails` (up to 3) and\n * `basicInfo.contactPhones.commercialNumber` (required), `services[]` with\n * `serviceType: DELIVERY` (the only one Keeta uses), `menuId` and\n * `serviceHours` in UTC; `lastUpdate`, `TTL` and the offers' `currency` are\n * ignored. The document's URL is registered per merchant at onboarding\n * (`./authorization.ts`).\n *\n * PAUSE. `{ merchantStatus: \"UNAVAILABLE\" | \"AVAILABLE\" }` closes or opens the\n * store, with no end and no id: a switch, offered only when the host opts in.\n * Answer 204; 400, 401, 503.\n *\n * ESTIMATED: that an update sent with no body (no `Content-Type` either) is\n * read as the documented \"empty body\"; that the menu is PUBLISHED once Keeta\n * took the notification, not once it read the menu (as for 99Food).\n */\n\nconst merchantUpdatePath = (merchantId: string): string => `/v1/merchantUpdate/${encodeURIComponent(merchantId)}`;\n\n/** Keeta's catalogue capability. */\nexport function keetaCatalogue(dialect: OpenDeliveryDialect): PullCatalogue {\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n notifyMenuChanged: (ctx) => openDeliveryMerchantUpdate(ctx, dialect, { path: merchantUpdatePath(ctx.externalMerchantId) }),\n };\n}\n\n/** Open or close the store on Keeta. */\nfunction keetaSetMerchantStatus(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n merchantId: string,\n status: \"AVAILABLE\" | \"UNAVAILABLE\",\n): Promise<OutboundResult> {\n return openDeliveryMerchantUpdate(ctx, dialect, { path: merchantUpdatePath(merchantId), body: { merchantStatus: status } });\n}\n\n/** Keeta's availability capability: `merchantStatus`, a switch. */\nexport function keetaAvailability(dialect: OpenDeliveryDialect): MarketplaceAvailability {\n return openDeliverySwitchAvailability((ctx, merchantId, status) => keetaSetMerchantStatus(ctx, dialect, merchantId, status));\n}\n","import { outboundResultOf, type AdapterCallContext } from \"../core/adapter\";\nimport { pick } from \"../core/payload-read\";\nimport type { NormalizedEvent, NormalizedMarketplaceOrder } from \"../core/types\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect } from \"../open-delivery/client\";\nimport { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from \"../open-delivery/normalize\";\n\n/**\n * The Keeta adapter's INBOUND half: Open Delivery's readers\n * (`../open-delivery/normalize.ts`) stamped with Keeta's provider id, plus\n * the one thing Keeta's `Order` does that the standard's does not: personal\n * data arrives ENCRYPTED.\n *\n * Events (Keeta's order guide, read 2026-11-26): `CREATED` → fetch;\n * `CANCELLED` (with a JSON-string `metadata` carrying `reason` and `code`) →\n * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle. Keeta has NO\n * `CANCELLATION_REQUEST_DENIED`: a store's request that Keeta does not grant\n * produces no event, so it ends TIMEOUT at the adapter's answer window. The\n * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`,\n * `RIDER_ARRIVED_AT_STORE`, `ORDER_COLLECTED`, `DELIVERED`,\n * `CANCELLATION_REQUESTED`, `USER_REFUND_REQUEST`, `REFUNDED`,\n * `REFUND_FAILED`, `RECOMMENDED_PREPARATION_START`) are recorded and IGNORED.\n */\n\n/** The provider id Keeta is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const KEETA_PROVIDER = \"KEETA\";\n\n/** Keeta's prefix on an encrypted value (`ENC_#MQesaE=#1#`). */\nconst ENCRYPTED_PREFIX = \"ENC_\";\n/** `POST /v1/batchDecrypt` takes at most 50 values a call. */\nconst DECRYPT_BATCH = 50;\n\n/** Normalize one webhook `Event`. Null only when it names no order. */\nexport function normalizeKeetaEvent(payload: unknown): NormalizedEvent | null {\n return normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);\n}\n\n/** Normalize one `Order`, after {@link revealKeetaOrder}. Null when it carries no id or no line. */\nexport function normalizeKeetaOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n return normalizeOpenDeliveryOrderAs(KEETA_PROVIDER, order, options);\n}\n\nconst isEncrypted = (value: unknown): value is string =>\n typeof value === \"string\" && value.startsWith(ENCRYPTED_PREFIX);\n\n/** Every encrypted value anywhere in the order, once each. */\nfunction ciphersOf(value: unknown, found: Set<string>): Set<string> {\n if (isEncrypted(value)) found.add(value);\n else if (Array.isArray(value)) for (const entry of value) ciphersOf(entry, found);\n else if (typeof value === \"object\" && value !== null) for (const entry of Object.values(value)) ciphersOf(entry, found);\n return found;\n}\n\n/** A copy of the order with each encrypted value replaced by its plain text, or removed when there is none. */\nfunction replaced(value: unknown, plain: ReadonlyMap<string, string>): unknown {\n if (Array.isArray(value)) return value.map((entry) => replaced(entry, plain));\n if (typeof value === \"object\" && value !== null) {\n const copy: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isEncrypted(entry) && !plain.has(entry)) continue;\n copy[key] = isEncrypted(entry) ? plain.get(entry) : replaced(entry, plain);\n }\n return copy;\n }\n return value;\n}\n\n/** The `{ cipherText, plainText }` pairs a `batchDecrypt` answer carries with `errorCode` 0. */\nfunction plainPairs(body: string): [string, string][] {\n const infos = pick(JSON.parse(body), \"plainInfos\");\n return (Array.isArray(infos) ? infos : []).flatMap((info): [string, string][] => {\n const cipher = pick(info, \"cipherText\");\n const text = pick(info, \"plainText\");\n const code = pick(info, \"errorCode\");\n return typeof cipher === \"string\" && typeof text === \"string\" && (code === undefined || code === 0)\n ? [[cipher, text]]\n : [];\n });\n}\n\n/** One `POST /v1/batchDecrypt` call: the plain texts it gave, none on any failure. */\nasync function decrypt(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n ciphers: readonly string[],\n): Promise<[string, string][]> {\n try {\n const response = await openDeliveryCall(ctx, dialect, {\n method: \"POST\",\n path: \"/v1/batchDecrypt\",\n body: { cipherInfos: ciphers.map((cipherText) => ({ cipherText })) },\n });\n if (isStop(response) || outboundResultOf(response).kind !== \"accepted\") return [];\n return plainPairs(response.body);\n } catch {\n return [];\n }\n}\n\n/**\n * Keeta encrypts `customer.phone.number` and the address's `district`,\n * `number`, `complement` and `formattedAddress` (`ENC_…`). Only an order the\n * MERCHANT delivers (its own courier or its 3PL) may be decrypted, through\n * `POST /v1/batchDecrypt` (at most 50 values a call); on Keeta's own fleet\n * the data stays masked. So: a merchant bag is decrypted, and every value\n * still encrypted after that (Keeta's fleet, a value Keeta would not decrypt,\n * a failed call) is REMOVED, never shown — the address then reads the copy's\n * missing-number text, and the phone is null.\n *\n * Never fails the fetch (choice): Keeta cancels an order not accepted within\n * 5 minutes and may close the store for it, so a decrypt that failed must not\n * keep the order out of the queue; the store reads the address on Keeta.\n */\nexport async function revealKeetaOrder(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: unknown,\n): Promise<unknown> {\n const ciphers = [...ciphersOf(order, new Set())];\n if (ciphers.length === 0) return order;\n const plain = new Map<string, string>();\n if (pick(order, \"delivery\", \"deliveredBy\") === \"MERCHANT\") {\n const batches: string[][] = [];\n for (let start = 0; start < ciphers.length; start += DECRYPT_BATCH) batches.push(ciphers.slice(start, start + DECRYPT_BATCH));\n const answers = await Promise.all(batches.map((batch) => decrypt(ctx, dialect, batch)));\n for (const [cipher, text] of answers.flat()) plain.set(cipher, text);\n }\n return replaced(order, plain);\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Keeta's `X-App-Signature`, both directions (read 2026-11-26 at\n * https://api-docs.mykeeta.com/apis/opendelivery/signature-calculation and its\n * three sub-pages, and the `newEvent` and webhook guide pages).\n *\n * OUTBOUND — every request the software sends Keeta, the token grant\n * included, carries it (Keeta's change to Open Delivery: a token alone is not\n * enough, so an intercepted token cannot be replayed):\n *\n * - the string is the URL without its query, then `&key=value` for each\n * query parameter sorted by key (a null value is `key=`), then `&` and the\n * body when there is one: an empty body, a blank one or `{}` is left out,\n * and so is its `&`;\n * - the body is compact JSON canonicalized by RFC 8785 (JCS), and the SAME\n * string is sent;\n * - HMAC-SHA256 of the string (UTF-8), keyed by the application's\n * `client_secret`, encoded Base64.\n *\n * INBOUND — a webhook Keeta sends (`POST /v1/newEvent`, and the\n * authorization webhook) is signed \"HMAC-SHA256 of the body, with the\n * client_secret as key, in Base64\".\n *\n * ESTIMATED:\n * - query values are signed DECODED (the reference implementations take them\n * from a map, before any URL encoding); only the self-serve authorization\n * calls send a query, and only `redirectUri` can hold a character encoding\n * changes;\n * - the inbound signature covers the raw body bytes as received, with no URL\n * prefix (the pages say \"the body\");\n * - the authorization webhook's header uses the same Base64 HMAC (its schema\n * says only \"SHA256 hash of the request body, using the client secret as the\n * key\").\n */\n\n/**\n * RFC 8785 (JCS) for the JSON this adapter sends: object keys sorted by\n * UTF-16 code units, no whitespace, strings and numbers as ECMAScript's\n * `JSON.stringify` writes them (which is what JCS specifies). `undefined`\n * members are dropped, as `JSON.stringify` drops them.\n */\nexport function canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => (entry === undefined ? \"null\" : canonicalJson(entry))).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter((key) => record[key] !== undefined)\n .sort();\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/** The string Keeta signs for one request. */\nexport function keetaSignatureString(url: string, body: string | undefined): string {\n const parsed = new URL(url);\n const parts = [`${parsed.origin}${parsed.pathname}`];\n const keys = [...new Set(parsed.searchParams.keys())].sort();\n for (const key of keys) parts.push(`${key}=${parsed.searchParams.get(key) ?? \"\"}`);\n const trimmed = body?.trim() ?? \"\";\n if (trimmed !== \"\" && trimmed !== \"{}\") parts.push(body ?? \"\");\n return parts.join(\"&\");\n}\n\n/** The `X-App-Signature` of one outbound request. */\nexport function keetaRequestSignature(url: string, body: string | undefined, clientSecret: string): string {\n return createHmac(\"sha256\", clientSecret).update(keetaSignatureString(url, body), \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify a webhook Keeta sent: Base64 HMAC-SHA256 of the raw body, keyed by\n * the application's client secret, which a connection stores as its webhook\n * secret. The key exists from the moment the store connects, so an unset\n * secret REFUSES: an unsigned CANCELLED for a known order id would otherwise\n * cancel it. Compared in constant time.\n */\nexport function verifyKeetaSignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean {\n if (!webhookSecret || !signature) return false;\n const expected = Buffer.from(createHmac(\"sha256\", webhookSecret).update(rawBody, \"utf8\").digest(\"base64\"), \"utf8\");\n const given = Buffer.from(signature.trim(), \"utf8\");\n return given.length === expected.length && timingSafeEqual(given, expected);\n}\n","import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from \"../open-delivery/client\";\nimport { KEETA_PROVIDER } from \"./normalize\";\nimport { canonicalJson, keetaRequestSignature } from \"./signature\";\n\n/**\n * Keeta's Open Delivery DIALECT. Keeta follows Open Delivery v1.5.0 with\n * changes of its own, and \"the definitions of this document prevail\"\n * (https://api-docs.mykeeta.com/apis/opendelivery/general-info, read\n * 2026-11-26). The calls are `../open-delivery/`'s; this file says how Keeta\n * takes them:\n *\n * - Token: `POST /oauth/token` with a JSON body `{ client_id, client_secret,\n * grant_type: \"app_level_token\" }` (v1.0.9's name for the standard's\n * `client_credentials`, which stays accepted for integrations already\n * certified). The token is the APPLICATION's: one for every store that\n * authorized it, so the cache key (provider, environment, client id) is\n * right as it is. Answer `{ access_token, token_type, expires_in }`; no\n * refresh token in this mode.\n * - Every request, the grant included, carries `X-App-Signature`\n * (`./signature.ts`), and every JSON body is RFC 8785 canonical.\n */\n\n/** Where Keeta serves Open Delivery, per environment. */\nexport type KeetaApiBaseUrls = OpenDeliveryApiBaseUrls;\n\n/**\n * The documented server (`servers[0]` of Keeta's `openapi.json`). ESTIMATED\n * for SANDBOX: Keeta documents one host, and a test application (its own\n * client id and secret, its test stores) is what makes a session a test one.\n */\nexport const KEETA_API_BASE_URL = \"https://open.mykeeta.com/api/open/opendelivery\";\n\nexport const KEETA_DEFAULT_API_BASE_URLS: KeetaApiBaseUrls = {\n SANDBOX: KEETA_API_BASE_URL,\n PRODUCTION: KEETA_API_BASE_URL,\n};\n\n/** Keeta's dialect, for the base URLs it was given. */\nexport function keetaDialect(bases: KeetaApiBaseUrls): OpenDeliveryDialect {\n return {\n provider: KEETA_PROVIDER,\n name: \"Keeta\",\n bases,\n tokenGrant: (ctx) => ({\n contentType: \"application/json\",\n body: canonicalJson({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"app_level_token\",\n }),\n }),\n serialize: canonicalJson,\n sign: (ctx, url, body) => ({ \"X-App-Signature\": keetaRequestSignature(url, body, ctx.credentials.clientSecret) }),\n };\n}\n","import type { AdapterCallContext, CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { assertHttpsUrl } from \"../open-delivery/client\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryRequestCancellation,\n openDeliveryStatus,\n} from \"../open-delivery/orders\";\nimport { OPEN_DELIVERY_ITEM_UNAVAILABLE } from \"../open-delivery/reasons\";\nimport { keetaAuthorization, type KeetaAuthorization } from \"./authorization\";\nimport { KEETA_REASON_CODES, type KeetaAdapterCopy } from \"./copy\";\nimport { keetaAvailability, keetaCatalogue } from \"./merchant\";\nimport { KEETA_PROVIDER, normalizeKeetaEvent, normalizeKeetaOrder, revealKeetaOrder } from \"./normalize\";\nimport { KEETA_DEFAULT_API_BASE_URLS, keetaDialect, type KeetaApiBaseUrls } from \"./outbound\";\nimport { verifyKeetaSignature } from \"./signature\";\n\n/**\n * `@12-apps/marketplace/keeta` — Keeta, as one adapter on the engine.\n *\n * Keeta's API is Open Delivery v1.5.0 with Keeta's own changes\n * (https://api-docs.mykeeta.com/apis/opendelivery, `openapi.json` \"v.1.0.7\"\n * with the changelog to 1.0.9, read 2026-11-26), so the adapter is built on\n * the same Open Delivery module as 99Food's (`../open-delivery/`), which\n * speaks v1.7.1. What Keeta does differently, and where it is handled:\n *\n * | Keeta | 99Food (v1.7.1) | handled in |\n * |---|---|---|\n * | `X-App-Signature` on EVERY request: Base64 HMAC-SHA256 of URL + sorted query + RFC 8785 body, keyed by the client secret | no request signature | `./signature.ts`, `./outbound.ts` |\n * | webhook signature Base64 | lowercase hex | `./signature.ts` |\n * | token: JSON `grant_type: app_level_token`, one token per APPLICATION (every authorized store) | form-encoded `client_credentials` | `./outbound.ts` |\n * | merchant authorization by the software: authorization URL, authorized stores, onboarding, authorization webhook | none | `./authorization.ts` |\n * | `merchantUpdate/{merchantId}` (path names the merchant) | `merchantUpdate` | `./merchant.ts` |\n * | menu: full reload only (`ITEM_OFFER`/`OPTION` status excepted) | full reload | `./merchant.ts` |\n * | personal data encrypted (`ENC_…`), `batchDecrypt` for a merchant's own delivery | plain | `./normalize.ts` |\n * | no `CANCELLATION_REQUEST_DENIED`: a refused request is silent, so it ends TIMEOUT | the denial event | `./normalize.ts`, the answer window below |\n * | `outOfStockItems` carries the PDV codes (`externalCode`) | item uuids, not sent | `../open-delivery/orders.ts` option |\n * | no take-out: no `pickedUp`; `delivered` only for the merchant's bag | `pickedUp` for a take-out | `../open-delivery/orders.ts` option |\n * | one public base URL and portal | given at onboarding | defaults below |\n *\n * ```ts\n * import { createKeetaAdapter } from \"@12-apps/marketplace/keeta\";\n * import { KEETA_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/keeta/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createKeetaAdapter({ copy: KEETA_ADAPTER_COPY_PT_BR })] });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/KEETA`, registered per store as\n * `ordersWebhookURL` at onboarding.\n */\n\nexport { KEETA_PROVIDER } from \"./normalize\";\n\n/**\n * How long Keeta may take to answer a cancellation request. ESTIMATED: Keeta\n * names none, and sends no event for a refusal, so past this the request is\n * failed as TIMEOUT. Keeta's own clock is 5 minutes for the acceptance.\n */\nexport const KEETA_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** Where \"open it on Keeta\" goes by default: the Merchant Portal (Keeta names no per-order link). */\nexport const KEETA_PORTAL_URL = \"https://merchant.mykeeta.com/\";\n\n/** Keeta has no take-out (`PICKED_UP` \"is not sent\"), so no `pickedUp`. */\nconst STATUS = openDeliveryStatus({ takeoutPickedUp: false });\n\nexport interface KeetaAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: KeetaAdapterCopy;\n /** OPTIONAL. Where Keeta serves Open Delivery, per environment. Default: the documented server for both. https only. */\n apiBaseUrl?: KeetaApiBaseUrls;\n /** OPTIONAL. Where \"open it on Keeta\" goes. Default: the Merchant Portal. https only. */\n portalUrl?: string;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through\n * `merchantStatus`, a store-wide switch with no id: a store the owner also\n * closed by hand on Keeta during the kitchen's pause is opened with it.\n */\n pauseByStoreSwitch?: boolean;\n}\n\nconst assertHttps = (name: string, url: string): void => assertHttpsUrl(\"@12-apps/marketplace/keeta\", name, url);\n\n/** The Keeta API base URLs a config names, checked. */\nfunction basesOf(config: Pick<KeetaAdapterConfig, \"apiBaseUrl\">): KeetaApiBaseUrls {\n const bases = { ...(config.apiBaseUrl ?? KEETA_DEFAULT_API_BASE_URLS) };\n assertHttps(\"apiBaseUrl.SANDBOX\", bases.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", bases.PRODUCTION);\n return bases;\n}\n\n/** Build the Keeta adapter. Its reasons are static: a dialog never waits on Keeta. */\nexport function createKeetaAdapter(config: KeetaAdapterConfig): MarketplaceAdapter {\n const dialect = keetaDialect(basesOf(config));\n const portalUrl = config.portalUrl ?? KEETA_PORTAL_URL;\n assertHttps(\"portalUrl\", portalUrl);\n const reasons: readonly CancellationReason[] = KEETA_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional: sent when the store named the SKUs, never required.\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n const fetchOptions = {\n normalize: (order: unknown) => normalizeKeetaOrder(order, normalizeOptions),\n prepare: (ctx: AdapterCallContext, order: unknown) => revealKeetaOrder(ctx, dialect, order),\n };\n // Keeta's own example sends PDV codes in `outOfStockItems` (\"PDV-1002\"). ESTIMATED that it reads them so.\n const cancellation = { outOfStockAsSkus: true };\n return {\n provider: KEETA_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // \"The merchant may cancel up to 48 h after the conclusion\"; the answer is Keeta's.\n cancelAfterAccept: true,\n // 202 (\"received for analysis\"), then CANCELLED, or nothing at all.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: KEETA_CANCELLATION_ANSWER_WINDOW_MS,\n // readyForPickup, dispatch (merchant's bag) and delivered (merchant's bag).\n statusSteps: [\"READY\", \"DISPATCHED\", \"HANDED_OVER\"],\n },\n normalize: normalizeKeetaEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyKeetaSignature,\n cancellationReasons: () => reasons,\n // PULL: Keeta reads the menu the host serves (`GET /v1/merchant`) and is told when it changed.\n catalogue: keetaCatalogue(dialect),\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: () => portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: keetaAvailability(dialect) } : {}),\n };\n}\n\n/** The self-serve merchant authorization calls (`./authorization.ts`), for the same base URLs as the adapter. */\nexport function createKeetaAuthorization(config: Pick<KeetaAdapterConfig, \"apiBaseUrl\"> = {}): KeetaAuthorization {\n return keetaAuthorization(keetaDialect(basesOf(config)));\n}\n\nexport { KEETA_REASON_CODES, type KeetaAdapterCopy, type KeetaReasonCode } from \"./copy\";\nexport { normalizeKeetaEvent, normalizeKeetaOrder } from \"./normalize\";\nexport { canonicalJson, keetaRequestSignature, verifyKeetaSignature } from \"./signature\";\nexport { KEETA_API_BASE_URL, type KeetaApiBaseUrls } from \"./outbound\";\nexport {\n KEETA_AUTHORIZATION_WEBHOOK_ANSWER,\n normalizeKeetaAuthorizationEvent,\n type KeetaAuthorization,\n type KeetaAuthorizationEvent,\n type KeetaAuthorizationResult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AAC9C,SAAO;AAAA,IACL,UAAU;AAAA,IACV,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ,WAAW;AAAA;AAAA,MAEX,mBAAmB;AAAA;AAAA,MAEnB,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA;AAAA,MAEjB,6BAA6B;AAAA,MAC7B,4BAA4B;AAAA;AAAA,MAE5B,aAAa,CAAC,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,eAAe,OAAO;AAAA,IACjC,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,WAAN;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,kBAAkB,OAAO,EAAE,IAAI,CAAC;AAAA,EAClF;AACF;AAjDgB;AAoDT,SAAS,yBAAyB,SAAiD,CAAC,GAAuB;AAChH,SAAO,mBAAmB,aAAa,QAAQ,MAAM,CAAC,CAAC;AACzD;AAFgB;","names":[]}
1
+ {"version":3,"sources":["../../src/keeta/authorization.ts","../../src/keeta/copy.ts","../../src/keeta/merchant.ts","../../src/keeta/normalize.ts","../../src/keeta/signature.ts","../../src/keeta/outbound.ts","../../src/keeta/index.ts"],"sourcesContent":["import { outboundResultOf, type AdapterCallContext } from \"../core/adapter\";\nimport { asString, firstString, pick } from \"../core/payload-read\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect, type OpenDeliveryStop } from \"../open-delivery/client\";\n\n/**\n * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's\n * \"Autorização Self-serve do Merchant\", read 2026-11-26 at\n * https://api-docs.mykeeta.com/apis/opendelivery/merchant-self-serve-authorization).\n * Not on the adapter port: connecting a store is the host's flow, and these\n * are the calls it is built from.\n *\n * 1. {@link KeetaAuthorization.authorizationUrl}: `GET\n * /oauth/authorization/url?clientId=&redirectUri=` (no token: a token\n * needs at least one authorized store), the link the merchant opens.\n * 2. The merchant authorizes; Keeta redirects to `redirectUri` with `authId`\n * (and `state`, `appId`, `timestamp`), and POSTs the authorization webhook\n * ({@link normalizeKeetaAuthorizationEvent}: `opType` 1 added, 2 revoked).\n * 3. {@link KeetaAuthorization.authorizedShops}: `GET\n * /oauth/authorized/{authId}/merchantInfo?pageNum=&pageSize=` lists the\n * stores of that authorization (Keeta's ids, names, addresses, time zones).\n * 4. The host maps a Keeta store to its own, then\n * {@link KeetaAuthorization.onboard}: `PUT /v1/merchantOnboarding?merchantId=`\n * binds the SOFTWARE's merchant id (the connection's `externalMerchantId`)\n * to `keetaMerchantId` and registers the `GET /v1/merchant` URL and the\n * orders webhook. \"Without onboarding there are no order events\"; sending\n * it again for the same id REPLACES the mapping. Answer 201.\n *\n * ESTIMATED: the JSON answer the authorization webhook wants (\"200 within\n * ~5 s, with JSON containing `code` and `message`\": the values are not\n * given, {@link KEETA_AUTHORIZATION_WEBHOOK_ANSWER} sends 0 and \"success\").\n */\n\n/** What the authorization webhook is answered with, 200, within ~5 s. ESTIMATED values. */\nexport const KEETA_AUTHORIZATION_WEBHOOK_ANSWER = { code: 0, message: \"success\" } as const;\n\n/** One authorization change Keeta reported (event 1301 added, 1302 revoked). */\nexport interface KeetaAuthorizationEvent {\n authId: string;\n change: \"AUTHORIZED\" | \"REVOKED\";\n /** Keeta's store id (an integer on the wire, text here). */\n shopId: string;\n shopName: string | null;\n /** The application's id. */\n clientId: string | null;\n at: Date | null;\n}\n\n/** Read the authorization webhook's body (`WebhookNotification`). Null when it names no authorization or store. */\nexport function normalizeKeetaAuthorizationEvent(payload: unknown): KeetaAuthorizationEvent | null {\n const authId = firstString(payload, [[\"authId\"]]);\n const shopId = firstString(payload, [[\"shopId\"]]);\n const opType = pick(payload, \"opType\");\n const change = opType === 1 ? \"AUTHORIZED\" : opType === 2 ? \"REVOKED\" : null;\n if (!authId || !shopId || !change) return null;\n const millis = pick(payload, \"createTime\");\n return {\n authId,\n change,\n shopId,\n shopName: firstString(payload, [[\"shopName\"]]),\n clientId: firstString(payload, [[\"clientId\"]]),\n at: typeof millis === \"number\" && Number.isFinite(millis) ? new Date(millis) : null,\n };\n}\n\n/** One store of an authorization, as `merchantInfo` lists it. */\nexport interface KeetaAuthorizedShop {\n /** Keeta's store id: the `keetaMerchantId` the onboarding takes. */\n id: string;\n name: string | null;\n address: string | null;\n latitude: number | null;\n longitude: number | null;\n timeZone: string | null;\n}\n\n/** One page of an authorization's stores. */\nexport interface KeetaAuthorizedShops {\n brandId: string | null;\n brandName: string | null;\n shops: KeetaAuthorizedShop[];\n page: { pageNum: number; totalPage: number; totalCount: number };\n}\n\n/** What the host registers for one store at onboarding. */\nexport interface KeetaOnboarding {\n /** The SOFTWARE's merchant id: the connection's `externalMerchantId`, the `Merchant.id` the host serves. */\n merchantId: string;\n /** Keeta's store id, from `authorizedShops` or Keeta's portal. */\n keetaMerchantId: number;\n /** Where Keeta reads this store's `GET /v1/merchant` (one URL per store), and its key if it wants one. */\n merchantDocument?: { url: string; apiKey?: string };\n /** The engine's webhook for this store: `…/webhooks/marketplace/:tenantSlug/KEETA`. */\n ordersWebhookUrl?: string;\n}\n\nexport type KeetaAuthorizationResult<T> = { kind: \"ok\"; value: T } | OpenDeliveryStop;\n\nconst numberOr = (value: unknown, fallback: number | null): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n\nfunction shopOf(raw: unknown): KeetaAuthorizedShop | null {\n const id = firstString(raw, [[\"id\"]]);\n if (!id) return null;\n return {\n id,\n name: firstString(raw, [[\"name\"]]),\n address: firstString(raw, [[\"address\"]]),\n latitude: numberOr(pick(raw, \"latitude\"), null),\n longitude: numberOr(pick(raw, \"longitude\"), null),\n timeZone: firstString(raw, [[\"timeZone\"]]),\n };\n}\n\nfunction shopsOf(body: unknown): KeetaAuthorizedShops {\n const raw = pick(body, \"authorizedShops\");\n return {\n brandId: asString(pick(body, \"brandId\")),\n brandName: firstString(body, [[\"brandName\"]]),\n shops: (Array.isArray(raw) ? raw : []).map(shopOf).filter((shop): shop is KeetaAuthorizedShop => shop !== null),\n page: {\n pageNum: numberOr(pick(body, \"page\", \"pageNum\"), 1) ?? 1,\n totalPage: numberOr(pick(body, \"page\", \"totalPage\"), 1) ?? 1,\n totalCount: numberOr(pick(body, \"page\", \"totalCount\"), 0) ?? 0,\n },\n };\n}\n\n/** One call whose 2xx answer is read by `read`: the value, or the result that ends it. */\nasync function readCall<T>(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n call: Parameters<typeof openDeliveryCall>[2],\n read: (body: unknown) => T | null,\n): Promise<KeetaAuthorizationResult<T>> {\n try {\n const response = await openDeliveryCall(ctx, dialect, call);\n if (isStop(response)) return response;\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n let body: unknown = null;\n try {\n body = response.body === \"\" ? null : JSON.parse(response.body);\n } catch {\n body = null;\n }\n const value = read(body);\n return value === null\n ? { kind: \"refused\", status: response.status, message: \"Keeta's answer is not the documented shape\" }\n : { kind: \"ok\", value };\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** The self-serve authorization calls, bound to Keeta's dialect. */\nexport interface KeetaAuthorization {\n authorizationUrl(ctx: AdapterCallContext, input: { redirectUri?: string }): Promise<KeetaAuthorizationResult<string>>;\n authorizedShops(\n ctx: AdapterCallContext,\n input: { authId: string; pageNum?: number; pageSize?: number },\n ): Promise<KeetaAuthorizationResult<KeetaAuthorizedShops>>;\n onboard(ctx: AdapterCallContext, input: KeetaOnboarding): Promise<KeetaAuthorizationResult<true>>;\n}\n\n/** An https URL Keeta answered, or null. */\nfunction httpsUrl(body: unknown): string | null {\n const url = firstString(body, [[\"merchantAuthorizationUrl\"]]);\n if (!url) return null;\n try {\n return new URL(url).protocol === \"https:\" ? url : null;\n } catch {\n return null;\n }\n}\n\nexport function keetaAuthorization(dialect: OpenDeliveryDialect): KeetaAuthorization {\n return {\n authorizationUrl: (ctx, input) =>\n readCall(\n ctx,\n dialect,\n {\n method: \"GET\",\n path: \"/oauth/authorization/url\",\n query: { clientId: ctx.credentials.clientId, ...(input.redirectUri ? { redirectUri: input.redirectUri } : {}) },\n authenticated: false,\n },\n httpsUrl,\n ),\n authorizedShops: (ctx, input) =>\n readCall(\n ctx,\n dialect,\n {\n method: \"GET\",\n path: `/oauth/authorized/${encodeURIComponent(input.authId)}/merchantInfo`,\n query: { pageNum: String(input.pageNum ?? 1), pageSize: String(Math.min(input.pageSize ?? 100, 100)) },\n },\n (body) => (body === null ? null : shopsOf(body)),\n ),\n onboard: (ctx, input) =>\n readCall(\n ctx,\n dialect,\n {\n method: \"PUT\",\n path: \"/v1/merchantOnboarding\",\n query: { merchantId: input.merchantId },\n body: {\n keetaMerchantId: input.keetaMerchantId,\n ...(input.merchantDocument\n ? {\n getMerchantURL: {\n baseURL: input.merchantDocument.url,\n ...(input.merchantDocument.apiKey ? { apiKey: input.merchantDocument.apiKey } : {}),\n },\n }\n : {}),\n ...(input.ordersWebhookUrl ? { ordersWebhookURL: input.ordersWebhookUrl } : {}),\n },\n },\n () => true as const,\n ),\n };\n}\n","import { OPEN_DELIVERY_MERCHANT_REASON_CODES } from \"../open-delivery/reasons\";\n\n/**\n * The words the Keeta 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: Keeta's \"códigos de\n * cancelamento (v1.0.7+)\", the same eleven as Open Delivery's\n * (`../open-delivery/reasons.ts`). Keeta still accepts its legacy codes\n * (`INSUFFICIENT_DISHES`, `SUSPENSION_OF_BUSINESS`, `INSUFFICIENT_MANPOWER`,\n * `OTHERS`) and recommends the new ones, so only the new ones are offered.\n */\nexport const KEETA_REASON_CODES = OPEN_DELIVERY_MERCHANT_REASON_CODES;\n\nexport type KeetaReasonCode = (typeof KEETA_REASON_CODES)[number];\n\nexport interface KeetaAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<KeetaReasonCode, string>>;\n /** What an address with no street number (or an encrypted one Keeta would not reveal) says instead. */\n missingStreetNumber: string;\n}\n","import type { AdapterCallContext, OutboundResult } from \"../core/adapter\";\nimport type { PullCatalogue } from \"../core/catalogue-port\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport type { OpenDeliveryDialect } from \"../open-delivery/client\";\nimport {\n openDeliveryMenuDocument,\n openDeliveryMerchantUpdate,\n openDeliverySwitchAvailability,\n} from \"../open-delivery/merchant\";\n\n/**\n * Keeta's MERCHANT half: the menu (FUT-4768) and the store pause (FUT-4851),\n * both on `POST /v1/merchantUpdate/{merchantId}` (Keeta's path names the\n * merchant, by the SOFTWARE's id; the standard's names none). Read\n * 2026-11-26 at https://api-docs.mykeeta.com/apis/opendelivery/merchantendpoints/merchantupdate.\n *\n * MENU. Keeta's menu API takes the store's menu three ways: an empty body\n * (\"Keeta calls your `GET /v1/merchant` and reloads everything\"),\n * `merchantStatus` alone, or `entityType` + `updatedObjects`. Of the last,\n * only `ITEM_OFFER` and `OPTION` are applied as sent, and only their\n * `status`; `MENU`, `CATEGORY`, `ITEM`… still make Keeta pull the whole menu\n * (\"only full-menu update\"). So a product cannot be PUSHED to Keeta: its\n * name, photo and price reach Keeta only through the `Merchant` document the\n * host serves. The adapter is therefore PULL: `menuDocument` builds the menu\n * part of that document (shared with 99Food: every item `UN` with a status,\n * every offer with `originalValue`, which Keeta requires), and\n * `notifyMenuChanged` sends the empty-body update that makes Keeta pull it.\n *\n * What Keeta reads of the rest of the `Merchant`, the host's to serve (Keeta's\n * `getMerchant` page): `id`, `status`, `basicInfo.contactEmails` (up to 3) and\n * `basicInfo.contactPhones.commercialNumber` (required), `services[]` with\n * `serviceType: DELIVERY` (the only one Keeta uses), `menuId` and\n * `serviceHours` in UTC; `lastUpdate`, `TTL` and the offers' `currency` are\n * ignored. The document's URL is registered per merchant at onboarding\n * (`./authorization.ts`).\n *\n * PAUSE. `{ merchantStatus: \"UNAVAILABLE\" | \"AVAILABLE\" }` closes or opens the\n * store, with no end and no id: a switch, offered only when the host opts in.\n * Answer 204; 400, 401, 503.\n *\n * ESTIMATED: that an update sent with no body (no `Content-Type` either) is\n * read as the documented \"empty body\"; that the menu is PUBLISHED once Keeta\n * took the notification, not once it read the menu (as for 99Food).\n */\n\nconst merchantUpdatePath = (merchantId: string): string => `/v1/merchantUpdate/${encodeURIComponent(merchantId)}`;\n\n/** Keeta's catalogue capability. */\nexport function keetaCatalogue(dialect: OpenDeliveryDialect): PullCatalogue {\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n notifyMenuChanged: (ctx) => openDeliveryMerchantUpdate(ctx, dialect, { path: merchantUpdatePath(ctx.externalMerchantId) }),\n };\n}\n\n/** Open or close the store on Keeta. */\nfunction keetaSetMerchantStatus(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n merchantId: string,\n status: \"AVAILABLE\" | \"UNAVAILABLE\",\n): Promise<OutboundResult> {\n return openDeliveryMerchantUpdate(ctx, dialect, { path: merchantUpdatePath(merchantId), body: { merchantStatus: status } });\n}\n\n/** Keeta's availability capability: `merchantStatus`, a switch. */\nexport function keetaAvailability(dialect: OpenDeliveryDialect): MarketplaceAvailability {\n return openDeliverySwitchAvailability((ctx, merchantId, status) => keetaSetMerchantStatus(ctx, dialect, merchantId, status));\n}\n","import { outboundResultOf, type AdapterCallContext } from \"../core/adapter\";\nimport { firstDate, pick } from \"../core/payload-read\";\nimport type { MarketplaceCourierStep, NormalizedEvent, NormalizedMarketplaceOrder } from \"../core/types\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect } from \"../open-delivery/client\";\nimport { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from \"../open-delivery/normalize\";\n\n/**\n * The Keeta adapter's INBOUND half: Open Delivery's readers\n * (`../open-delivery/normalize.ts`) stamped with Keeta's provider id, plus\n * the one thing Keeta's `Order` does that the standard's does not: personal\n * data arrives ENCRYPTED.\n *\n * Events (Keeta's order guide, read 2026-11-26): `CREATED` → fetch;\n * `CANCELLED` (with a JSON-string `metadata` carrying `reason` and `code`) →\n * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle; `RIDER_ARRIVED_AT_STORE`,\n * `ORDER_COLLECTED` → courier steps (the second a lifecycle too). Keeta has NO\n * `CANCELLATION_REQUEST_DENIED`: a store's request that Keeta does not grant\n * produces no event, so it ends TIMEOUT at the adapter's answer window. The\n * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`, `DELIVERED`,\n * `CANCELLATION_REQUESTED`, `USER_REFUND_REQUEST`, `REFUNDED`,\n * `REFUND_FAILED`, `RECOMMENDED_PREPARATION_START`) are recorded and IGNORED.\n */\n\n/**\n * Keeta's rider events as courier steps (FUT-5665). ESTIMATED: the event names\n * are Keeta's order guide's (read 2026-11-26), their meaning is read off the\n * names; they carry no rider's name, photo or vehicle. `PICKUP_ONGOING` is left\n * IGNORED: whether it means \"on the way\" or \"at the counter\" is not stated.\n */\nconst KEETA_COURIER_STEP_OF: Readonly<Record<string, MarketplaceCourierStep>> = {\n RIDER_ARRIVED_AT_STORE: \"ARRIVED_AT_ORIGIN\",\n ORDER_COLLECTED: \"COLLECTED\",\n};\n\n/** The provider id Keeta is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const KEETA_PROVIDER = \"KEETA\";\n\n/** Keeta's prefix on an encrypted value (`ENC_#MQesaE=#1#`). */\nconst ENCRYPTED_PREFIX = \"ENC_\";\n/** `POST /v1/batchDecrypt` takes at most 50 values a call. */\nconst DECRYPT_BATCH = 50;\n\n/** Normalize one webhook `Event`. Null only when it names no order. */\nexport function normalizeKeetaEvent(payload: unknown): NormalizedEvent | null {\n const event = normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);\n const step = event ? KEETA_COURIER_STEP_OF[event.eventType] : undefined;\n if (!event || !step) return event;\n const courier = { step, at: firstDate(payload, [[\"createdAt\"]]), courier: null, returning: null };\n return { ...event, courier, ...(step === \"COLLECTED\" ? { lifecycle: \"COLLECTED\" as const } : {}) };\n}\n\n/** Normalize one `Order`, after {@link revealKeetaOrder}. Null when it carries no id or no line. */\nexport function normalizeKeetaOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n return normalizeOpenDeliveryOrderAs(KEETA_PROVIDER, order, options);\n}\n\nconst isEncrypted = (value: unknown): value is string =>\n typeof value === \"string\" && value.startsWith(ENCRYPTED_PREFIX);\n\n/** Every encrypted value anywhere in the order, once each. */\nfunction ciphersOf(value: unknown, found: Set<string>): Set<string> {\n if (isEncrypted(value)) found.add(value);\n else if (Array.isArray(value)) for (const entry of value) ciphersOf(entry, found);\n else if (typeof value === \"object\" && value !== null) for (const entry of Object.values(value)) ciphersOf(entry, found);\n return found;\n}\n\n/** A copy of the order with each encrypted value replaced by its plain text, or removed when there is none. */\nfunction replaced(value: unknown, plain: ReadonlyMap<string, string>): unknown {\n if (Array.isArray(value)) return value.map((entry) => replaced(entry, plain));\n if (typeof value === \"object\" && value !== null) {\n const copy: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isEncrypted(entry) && !plain.has(entry)) continue;\n copy[key] = isEncrypted(entry) ? plain.get(entry) : replaced(entry, plain);\n }\n return copy;\n }\n return value;\n}\n\n/** The `{ cipherText, plainText }` pairs a `batchDecrypt` answer carries with `errorCode` 0. */\nfunction plainPairs(body: string): [string, string][] {\n const infos = pick(JSON.parse(body), \"plainInfos\");\n return (Array.isArray(infos) ? infos : []).flatMap((info): [string, string][] => {\n const cipher = pick(info, \"cipherText\");\n const text = pick(info, \"plainText\");\n const code = pick(info, \"errorCode\");\n return typeof cipher === \"string\" && typeof text === \"string\" && (code === undefined || code === 0)\n ? [[cipher, text]]\n : [];\n });\n}\n\n/** One `POST /v1/batchDecrypt` call: the plain texts it gave, none on any failure. */\nasync function decrypt(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n ciphers: readonly string[],\n): Promise<[string, string][]> {\n try {\n const response = await openDeliveryCall(ctx, dialect, {\n method: \"POST\",\n path: \"/v1/batchDecrypt\",\n body: { cipherInfos: ciphers.map((cipherText) => ({ cipherText })) },\n });\n if (isStop(response) || outboundResultOf(response).kind !== \"accepted\") return [];\n return plainPairs(response.body);\n } catch {\n return [];\n }\n}\n\n/**\n * Keeta encrypts `customer.phone.number` and the address's `district`,\n * `number`, `complement` and `formattedAddress` (`ENC_…`). Only an order the\n * MERCHANT delivers (its own courier or its 3PL) may be decrypted, through\n * `POST /v1/batchDecrypt` (at most 50 values a call); on Keeta's own fleet\n * the data stays masked. So: a merchant bag is decrypted, and every value\n * still encrypted after that (Keeta's fleet, a value Keeta would not decrypt,\n * a failed call) is REMOVED, never shown — the address then reads the copy's\n * missing-number text, and the phone is null.\n *\n * Never fails the fetch (choice): Keeta cancels an order not accepted within\n * 5 minutes and may close the store for it, so a decrypt that failed must not\n * keep the order out of the queue; the store reads the address on Keeta.\n */\nexport async function revealKeetaOrder(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: unknown,\n): Promise<unknown> {\n const ciphers = [...ciphersOf(order, new Set())];\n if (ciphers.length === 0) return order;\n const plain = new Map<string, string>();\n if (pick(order, \"delivery\", \"deliveredBy\") === \"MERCHANT\") {\n const batches: string[][] = [];\n for (let start = 0; start < ciphers.length; start += DECRYPT_BATCH) batches.push(ciphers.slice(start, start + DECRYPT_BATCH));\n const answers = await Promise.all(batches.map((batch) => decrypt(ctx, dialect, batch)));\n for (const [cipher, text] of answers.flat()) plain.set(cipher, text);\n }\n return replaced(order, plain);\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Keeta's `X-App-Signature`, both directions (read 2026-11-26 at\n * https://api-docs.mykeeta.com/apis/opendelivery/signature-calculation and its\n * three sub-pages, and the `newEvent` and webhook guide pages).\n *\n * OUTBOUND — every request the software sends Keeta, the token grant\n * included, carries it (Keeta's change to Open Delivery: a token alone is not\n * enough, so an intercepted token cannot be replayed):\n *\n * - the string is the URL without its query, then `&key=value` for each\n * query parameter sorted by key (a null value is `key=`), then `&` and the\n * body when there is one: an empty body, a blank one or `{}` is left out,\n * and so is its `&`;\n * - the body is compact JSON canonicalized by RFC 8785 (JCS), and the SAME\n * string is sent;\n * - HMAC-SHA256 of the string (UTF-8), keyed by the application's\n * `client_secret`, encoded Base64.\n *\n * INBOUND — a webhook Keeta sends (`POST /v1/newEvent`, and the\n * authorization webhook) is signed \"HMAC-SHA256 of the body, with the\n * client_secret as key, in Base64\".\n *\n * ESTIMATED:\n * - query values are signed DECODED (the reference implementations take them\n * from a map, before any URL encoding); only the self-serve authorization\n * calls send a query, and only `redirectUri` can hold a character encoding\n * changes;\n * - the inbound signature covers the raw body bytes as received, with no URL\n * prefix (the pages say \"the body\");\n * - the authorization webhook's header uses the same Base64 HMAC (its schema\n * says only \"SHA256 hash of the request body, using the client secret as the\n * key\").\n */\n\n/**\n * RFC 8785 (JCS) for the JSON this adapter sends: object keys sorted by\n * UTF-16 code units, no whitespace, strings and numbers as ECMAScript's\n * `JSON.stringify` writes them (which is what JCS specifies). `undefined`\n * members are dropped, as `JSON.stringify` drops them.\n */\nexport function canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => (entry === undefined ? \"null\" : canonicalJson(entry))).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter((key) => record[key] !== undefined)\n .sort();\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/** The string Keeta signs for one request. */\nexport function keetaSignatureString(url: string, body: string | undefined): string {\n const parsed = new URL(url);\n const parts = [`${parsed.origin}${parsed.pathname}`];\n const keys = [...new Set(parsed.searchParams.keys())].sort();\n for (const key of keys) parts.push(`${key}=${parsed.searchParams.get(key) ?? \"\"}`);\n const trimmed = body?.trim() ?? \"\";\n if (trimmed !== \"\" && trimmed !== \"{}\") parts.push(body ?? \"\");\n return parts.join(\"&\");\n}\n\n/** The `X-App-Signature` of one outbound request. */\nexport function keetaRequestSignature(url: string, body: string | undefined, clientSecret: string): string {\n return createHmac(\"sha256\", clientSecret).update(keetaSignatureString(url, body), \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify a webhook Keeta sent: Base64 HMAC-SHA256 of the raw body, keyed by\n * the application's client secret, which a connection stores as its webhook\n * secret. The key exists from the moment the store connects, so an unset\n * secret REFUSES: an unsigned CANCELLED for a known order id would otherwise\n * cancel it. Compared in constant time.\n */\nexport function verifyKeetaSignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean {\n if (!webhookSecret || !signature) return false;\n const expected = Buffer.from(createHmac(\"sha256\", webhookSecret).update(rawBody, \"utf8\").digest(\"base64\"), \"utf8\");\n const given = Buffer.from(signature.trim(), \"utf8\");\n return given.length === expected.length && timingSafeEqual(given, expected);\n}\n","import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from \"../open-delivery/client\";\nimport { KEETA_PROVIDER } from \"./normalize\";\nimport { canonicalJson, keetaRequestSignature } from \"./signature\";\n\n/**\n * Keeta's Open Delivery DIALECT. Keeta follows Open Delivery v1.5.0 with\n * changes of its own, and \"the definitions of this document prevail\"\n * (https://api-docs.mykeeta.com/apis/opendelivery/general-info, read\n * 2026-11-26). The calls are `../open-delivery/`'s; this file says how Keeta\n * takes them:\n *\n * - Token: `POST /oauth/token` with a JSON body `{ client_id, client_secret,\n * grant_type: \"app_level_token\" }` (v1.0.9's name for the standard's\n * `client_credentials`, which stays accepted for integrations already\n * certified). The token is the APPLICATION's: one for every store that\n * authorized it, so the cache key (provider, environment, client id) is\n * right as it is. Answer `{ access_token, token_type, expires_in }`; no\n * refresh token in this mode.\n * - Every request, the grant included, carries `X-App-Signature`\n * (`./signature.ts`), and every JSON body is RFC 8785 canonical.\n */\n\n/** Where Keeta serves Open Delivery, per environment. */\nexport type KeetaApiBaseUrls = OpenDeliveryApiBaseUrls;\n\n/**\n * The documented server (`servers[0]` of Keeta's `openapi.json`). ESTIMATED\n * for SANDBOX: Keeta documents one host, and a test application (its own\n * client id and secret, its test stores) is what makes a session a test one.\n */\nexport const KEETA_API_BASE_URL = \"https://open.mykeeta.com/api/open/opendelivery\";\n\nexport const KEETA_DEFAULT_API_BASE_URLS: KeetaApiBaseUrls = {\n SANDBOX: KEETA_API_BASE_URL,\n PRODUCTION: KEETA_API_BASE_URL,\n};\n\n/** Keeta's dialect, for the base URLs it was given. */\nexport function keetaDialect(bases: KeetaApiBaseUrls): OpenDeliveryDialect {\n return {\n provider: KEETA_PROVIDER,\n name: \"Keeta\",\n bases,\n tokenGrant: (ctx) => ({\n contentType: \"application/json\",\n body: canonicalJson({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"app_level_token\",\n }),\n }),\n serialize: canonicalJson,\n sign: (ctx, url, body) => ({ \"X-App-Signature\": keetaRequestSignature(url, body, ctx.credentials.clientSecret) }),\n };\n}\n","import type { AdapterCallContext, CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { assertHttpsUrl } from \"../open-delivery/client\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryRequestCancellation,\n openDeliveryStatus,\n} from \"../open-delivery/orders\";\nimport { OPEN_DELIVERY_ITEM_UNAVAILABLE } from \"../open-delivery/reasons\";\nimport { keetaAuthorization, type KeetaAuthorization } from \"./authorization\";\nimport { KEETA_REASON_CODES, type KeetaAdapterCopy } from \"./copy\";\nimport { keetaAvailability, keetaCatalogue } from \"./merchant\";\nimport { KEETA_PROVIDER, normalizeKeetaEvent, normalizeKeetaOrder, revealKeetaOrder } from \"./normalize\";\nimport { KEETA_DEFAULT_API_BASE_URLS, keetaDialect, type KeetaApiBaseUrls } from \"./outbound\";\nimport { verifyKeetaSignature } from \"./signature\";\n\n/**\n * `@12-apps/marketplace/keeta` — Keeta, as one adapter on the engine.\n *\n * Keeta's API is Open Delivery v1.5.0 with Keeta's own changes\n * (https://api-docs.mykeeta.com/apis/opendelivery, `openapi.json` \"v.1.0.7\"\n * with the changelog to 1.0.9, read 2026-11-26), so the adapter is built on\n * the same Open Delivery module as 99Food's (`../open-delivery/`), which\n * speaks v1.7.1. What Keeta does differently, and where it is handled:\n *\n * | Keeta | 99Food (v1.7.1) | handled in |\n * |---|---|---|\n * | `X-App-Signature` on EVERY request: Base64 HMAC-SHA256 of URL + sorted query + RFC 8785 body, keyed by the client secret | no request signature | `./signature.ts`, `./outbound.ts` |\n * | webhook signature Base64 | lowercase hex | `./signature.ts` |\n * | token: JSON `grant_type: app_level_token`, one token per APPLICATION (every authorized store) | form-encoded `client_credentials` | `./outbound.ts` |\n * | merchant authorization by the software: authorization URL, authorized stores, onboarding, authorization webhook | none | `./authorization.ts` |\n * | `merchantUpdate/{merchantId}` (path names the merchant) | `merchantUpdate` | `./merchant.ts` |\n * | menu: full reload only (`ITEM_OFFER`/`OPTION` status excepted) | full reload | `./merchant.ts` |\n * | personal data encrypted (`ENC_…`), `batchDecrypt` for a merchant's own delivery | plain | `./normalize.ts` |\n * | no `CANCELLATION_REQUEST_DENIED`: a refused request is silent, so it ends TIMEOUT | the denial event | `./normalize.ts`, the answer window below |\n * | `outOfStockItems` carries the PDV codes (`externalCode`) | item uuids, not sent | `../open-delivery/orders.ts` option |\n * | no take-out: no `pickedUp`; `delivered` only for the merchant's bag | `pickedUp` for a take-out | `../open-delivery/orders.ts` option |\n * | one public base URL and portal | given at onboarding | defaults below |\n *\n * ```ts\n * import { createKeetaAdapter } from \"@12-apps/marketplace/keeta\";\n * import { KEETA_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/keeta/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createKeetaAdapter({ copy: KEETA_ADAPTER_COPY_PT_BR })] });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/KEETA`, registered per store as\n * `ordersWebhookURL` at onboarding.\n */\n\nexport { KEETA_PROVIDER } from \"./normalize\";\n\n/**\n * How long Keeta may take to answer a cancellation request. ESTIMATED: Keeta\n * names none, and sends no event for a refusal, so past this the request is\n * failed as TIMEOUT. Keeta's own clock is 5 minutes for the acceptance.\n */\nexport const KEETA_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** Where \"open it on Keeta\" goes by default: the Merchant Portal (Keeta names no per-order link). */\nexport const KEETA_PORTAL_URL = \"https://merchant.mykeeta.com/\";\n\n/** Keeta has no take-out (`PICKED_UP` \"is not sent\"), so no `pickedUp`. */\nconst STATUS = openDeliveryStatus({ takeoutPickedUp: false });\n\nexport interface KeetaAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: KeetaAdapterCopy;\n /** OPTIONAL. Where Keeta serves Open Delivery, per environment. Default: the documented server for both. https only. */\n apiBaseUrl?: KeetaApiBaseUrls;\n /** OPTIONAL. Where \"open it on Keeta\" goes. Default: the Merchant Portal. https only. */\n portalUrl?: string;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through\n * `merchantStatus`, a store-wide switch with no id: a store the owner also\n * closed by hand on Keeta during the kitchen's pause is opened with it.\n */\n pauseByStoreSwitch?: boolean;\n}\n\nconst assertHttps = (name: string, url: string): void => assertHttpsUrl(\"@12-apps/marketplace/keeta\", name, url);\n\n/** The Keeta API base URLs a config names, checked. */\nfunction basesOf(config: Pick<KeetaAdapterConfig, \"apiBaseUrl\">): KeetaApiBaseUrls {\n const bases = { ...(config.apiBaseUrl ?? KEETA_DEFAULT_API_BASE_URLS) };\n assertHttps(\"apiBaseUrl.SANDBOX\", bases.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", bases.PRODUCTION);\n return bases;\n}\n\n/** Build the Keeta adapter. Its reasons are static: a dialog never waits on Keeta. */\nexport function createKeetaAdapter(config: KeetaAdapterConfig): MarketplaceAdapter {\n const dialect = keetaDialect(basesOf(config));\n const portalUrl = config.portalUrl ?? KEETA_PORTAL_URL;\n assertHttps(\"portalUrl\", portalUrl);\n const reasons: readonly CancellationReason[] = KEETA_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional: sent when the store named the SKUs, never required.\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n const fetchOptions = {\n normalize: (order: unknown) => normalizeKeetaOrder(order, normalizeOptions),\n prepare: (ctx: AdapterCallContext, order: unknown) => revealKeetaOrder(ctx, dialect, order),\n };\n // Keeta's own example sends PDV codes in `outOfStockItems` (\"PDV-1002\"). ESTIMATED that it reads them so.\n const cancellation = { outOfStockAsSkus: true };\n return {\n provider: KEETA_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // \"The merchant may cancel up to 48 h after the conclusion\"; the answer is Keeta's.\n cancelAfterAccept: true,\n // 202 (\"received for analysis\"), then CANCELLED, or nothing at all.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: KEETA_CANCELLATION_ANSWER_WINDOW_MS,\n // readyForPickup, dispatch (merchant's bag) and delivered (merchant's bag).\n statusSteps: [\"READY\", \"DISPATCHED\", \"HANDED_OVER\"],\n },\n normalize: normalizeKeetaEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyKeetaSignature,\n cancellationReasons: () => reasons,\n // PULL: Keeta reads the menu the host serves (`GET /v1/merchant`) and is told when it changed.\n catalogue: keetaCatalogue(dialect),\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: () => portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: keetaAvailability(dialect) } : {}),\n };\n}\n\n/** The self-serve merchant authorization calls (`./authorization.ts`), for the same base URLs as the adapter. */\nexport function createKeetaAuthorization(config: Pick<KeetaAdapterConfig, \"apiBaseUrl\"> = {}): KeetaAuthorization {\n return keetaAuthorization(keetaDialect(basesOf(config)));\n}\n\nexport { KEETA_REASON_CODES, type KeetaAdapterCopy, type KeetaReasonCode } from \"./copy\";\nexport { normalizeKeetaEvent, normalizeKeetaOrder } from \"./normalize\";\nexport { canonicalJson, keetaRequestSignature, verifyKeetaSignature } from \"./signature\";\nexport { KEETA_API_BASE_URL, type KeetaApiBaseUrls } from \"./outbound\";\nexport {\n KEETA_AUTHORIZATION_WEBHOOK_ANSWER,\n normalizeKeetaAuthorizationEvent,\n type KeetaAuthorization,\n type KeetaAuthorizationEvent,\n type KeetaAuthorizationResult,\n type KeetaAuthorizedShop,\n type KeetaAuthorizedShops,\n type KeetaOnboarding,\n} from \"./authorization\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCO,IAAM,qCAAqC,EAAE,MAAM,GAAG,SAAS,UAAU;AAezE,SAAS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,7 @@
1
- import { am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-C_3RK8wC.js';
1
+ import { am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-1KlJ_8jK.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
- import '../adapter-CD0SfdVS.js';
4
+ import '../adapter-CQ4QiZPi.js';
5
5
  import 'zod';
6
6
 
7
7
  declare const marketplaceServerManifest: {
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-OS4TSIFU.js";
4
+ } from "../chunk-W57TITU4.js";
5
5
  import "../chunk-SGOTN5PX.js";
6
- import "../chunk-YWMEIMO3.js";
6
+ import "../chunk-CEWTV2TC.js";
7
7
  import "../chunk-7QVYU63E.js";
8
8
 
9
9
  // src/manifest/server.ts
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CD0SfdVS.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CQ4QiZPi.js';
2
2
 
3
3
  /**
4
4
  * The words the Rappi adapter needs from its host, and nothing else.
@@ -9,7 +9,7 @@ import {
9
9
  answered,
10
10
  outboundResultOf,
11
11
  tokenGrantResultOf
12
- } from "../chunk-TVZU4HNT.js";
12
+ } from "../chunk-4J2KJ3ZW.js";
13
13
  import {
14
14
  __name
15
15
  } from "../chunk-7QVYU63E.js";
@@ -1,7 +1,7 @@
1
- import { y as DecisionProblemCode, f as BulkProblemCode, R as LinkRefusalCode, a3 as MarketplaceEngine, a9 as MarketplaceLogger, am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-C_3RK8wC.js';
1
+ import { y as DecisionProblemCode, f as BulkProblemCode, R as LinkRefusalCode, a3 as MarketplaceEngine, a9 as MarketplaceLogger, am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-1KlJ_8jK.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-CD0SfdVS.js';
4
+ import '../adapter-CQ4QiZPi.js';
5
5
 
6
6
  /**
7
7
  * Every problem code a route words from `problems`, decisions and bulk writes
@@ -6,7 +6,7 @@ import {
6
6
  MARKETPLACE_SWEEP_QUEUE,
7
7
  ORDER_NOT_PENDING_CODE,
8
8
  createApiMarketplace
9
- } from "../chunk-OS4TSIFU.js";
9
+ } from "../chunk-W57TITU4.js";
10
10
  import {
11
11
  MARKETPLACE_DECIDE,
12
12
  MARKETPLACE_MANAGE,
@@ -20,7 +20,7 @@ import {
20
20
  upsertMarketplaceIntegrationsBody,
21
21
  upsertMarketplaceMenuLinksBody
22
22
  } from "../chunk-SGOTN5PX.js";
23
- import "../chunk-YWMEIMO3.js";
23
+ import "../chunk-CEWTV2TC.js";
24
24
  import "../chunk-7QVYU63E.js";
25
25
  export {
26
26
  MARKETPLACE_AVAILABILITY_ATTEMPTS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.11.0",
3
+ "version": "1.13.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food and ./keeta on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -1,4 +1,5 @@
1
1
  import type { MarketplaceCatalogue } from "./catalogue-port";
2
+ import type { MarketplaceCourierApi } from "./courier-port";
2
3
  import type { CatalogueReader } from "./catalogue-read-port";
3
4
  import type { MarketplaceLinking } from "./linking-port";
4
5
  import type { MarketplaceAvailability } from "./pause-port";
@@ -236,7 +237,8 @@ export interface MarketplaceAdapter {
236
237
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
237
238
  * marketplace whose events carry no order body). Called only from the
238
239
  * `marketplace.fetch-order` job. An adapter whose events always carry the
239
- * order (iFood) leaves it out.
240
+ * order leaves it out. A final `refused` marked `own` with a 4xx status is
241
+ * our credentials refused: the engine stamps the connection FAILED.
240
242
  */
241
243
  fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;
242
244
  /**
@@ -263,6 +265,11 @@ export interface MarketplaceAdapter {
263
265
  * marketplace (FUT-5613). Absent: a store connects with its own credentials only.
264
266
  */
265
267
  readonly linking?: MarketplaceLinking;
268
+ /**
269
+ * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check
270
+ * and the tracking read. Absent: neither is offered, and the host says so.
271
+ */
272
+ readonly courier?: MarketplaceCourierApi;
266
273
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
267
274
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
268
275
  }
@@ -0,0 +1,61 @@
1
+ import type { EngineContext } from "./ports";
2
+ import type { MarketplaceProvider } from "./types";
3
+
4
+ /**
5
+ * What a call no person made says about a connection's credentials (the order
6
+ * fetch, FUT-5800): refused, or working again. Each stamp is guarded on the
7
+ * sealed credentials the call was made with, as `./link-store.ts`'s
8
+ * `markLinkFailed` is, so a call made with credentials since replaced never
9
+ * judges the new ones.
10
+ */
11
+
12
+ /**
13
+ * The marketplace refused this connection's credentials on a call no person
14
+ * made (the order fetch, FUT-5800): the connection reads FAILED, which is what
15
+ * the connections screen shows, and the staff surfaces are told. Only the
16
+ * credentials the call was made with (`sealed`) are judged: a store that
17
+ * entered new ones meanwhile is left alone. Re-entering the credentials resets
18
+ * it to UNVERIFIED; the next fetch that succeeds, to VERIFIED
19
+ * ({@link markCredentialsAccepted}). Best-effort: never throws.
20
+ */
21
+ export async function markCredentialsRefused(
22
+ ctx: EngineContext,
23
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
24
+ ): Promise<void> {
25
+ await stampConnection(ctx, input, { archivedAt: null }, { status: "FAILED" });
26
+ }
27
+
28
+ /**
29
+ * A call with these credentials (`sealed`) succeeded: a connection that read
30
+ * FAILED for them reads VERIFIED again. Any other status is left as it is.
31
+ * Best-effort: never throws.
32
+ */
33
+ export async function markCredentialsAccepted(
34
+ ctx: EngineContext,
35
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
36
+ ): Promise<void> {
37
+ await stampConnection(ctx, input, { status: "FAILED" }, { status: "VERIFIED", lastVerifiedAt: ctx.ports.clock.now() });
38
+ }
39
+
40
+ /** One guarded status write on the connection the call was made with; tells the staff surfaces when it moved. */
41
+ async function stampConnection(
42
+ ctx: EngineContext,
43
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
44
+ where: Record<string, unknown>,
45
+ data: Record<string, unknown>,
46
+ ): Promise<void> {
47
+ const { clientId, provider, sealed } = input;
48
+ try {
49
+ const db = await ctx.ports.db();
50
+ const { count } = await db.marketplaceIntegration.updateMany({
51
+ where: { clientId, provider, credentials: sealed, ...where },
52
+ data,
53
+ });
54
+ if (count > 0) ctx.ports.publishChanged(clientId);
55
+ } catch (error) {
56
+ ctx.ports.logger.error(
57
+ `marketplace: ${provider} connection of ${clientId} not stamped ${String(data.status)}: ` +
58
+ (error instanceof Error ? error.message : String(error)),
59
+ );
60
+ }
61
+ }
@@ -0,0 +1,100 @@
1
+ import type { AdapterCallContext, OutboundOrderRef, OutboundResult } from "./adapter";
2
+ import type { MarketplaceDeliveredBy } from "./types";
3
+
4
+ /**
5
+ * The marketplace's own courier (FUT-5665): what an adapter can do about the
6
+ * courier its marketplace sends, and what the host is told. Optional in every
7
+ * type, so a host or an adapter that knows nothing of it compiles unchanged.
8
+ */
9
+
10
+ /** Where the marketplace's courier is, as its tracking read says. Every field null when unstated. */
11
+ export interface MarketplaceCourierTracking {
12
+ /** When the courier reaches the store: the "chega em" time. */
13
+ pickupEtaAt: Date | null;
14
+ /** When the marketplace expects the bag at the buyer's door. */
15
+ deliveryEtaAt: Date | null;
16
+ latitude: number | null;
17
+ longitude: number | null;
18
+ /** When the marketplace took this reading. */
19
+ trackedAt: Date | null;
20
+ }
21
+
22
+ /** What an adapter's pickup-code check answers: the marketplace's verdict, or why there is none. */
23
+ export type PickupCodeCallResult =
24
+ | { kind: "answered"; valid: boolean }
25
+ | Exclude<OutboundResult, { kind: "accepted" }>;
26
+
27
+ /**
28
+ * What an adapter's tracking read answers: the reading; `notYet` (no courier
29
+ * is assigned, so there is nothing to track); or the refusal and retry shapes
30
+ * of an outbound call.
31
+ */
32
+ export type CourierTrackingCallResult =
33
+ | { kind: "tracking"; tracking: MarketplaceCourierTracking }
34
+ | { kind: "notYet" }
35
+ | Exclude<OutboundResult, { kind: "accepted" }>;
36
+
37
+ /** The courier calls one marketplace takes. Present on an adapter whose marketplace has them (iFood). */
38
+ export interface MarketplaceCourierApi {
39
+ /**
40
+ * Tell the marketplace the code the store checked at the hand-over, and
41
+ * read its verdict. Called only from the `marketplace.outbound` job, action
42
+ * `validatePickupCode`, after the host's own hand-over committed.
43
+ */
44
+ validatePickupCode(ctx: AdapterCallContext, order: OutboundOrderRef, input: { code: string }): Promise<PickupCodeCallResult>;
45
+ /** Read where the courier is. Called only by `engine.courierTracking`, which the host runs in a job. */
46
+ tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<CourierTrackingCallResult>;
47
+ }
48
+
49
+ /**
50
+ * The marketplace's verdict on a pickup code, as the host is told it:
51
+ * `VALID`, `INVALID` (the hand-over has committed: warn, move nothing) or
52
+ * `UNVERIFIED` (no verdict came: a final refusal, retries that ran out, no
53
+ * connection).
54
+ */
55
+ export type PickupCodeValidation = "VALID" | "INVALID" | "UNVERIFIED";
56
+
57
+ /** What the engine tells the host with a courier event. */
58
+ export interface MarketplaceCourierFacts {
59
+ /** Who carries the delivery, as the acceptance row holds it. */
60
+ deliveredBy: MarketplaceDeliveredBy | null;
61
+ /** When it happened: the event's own instant, or the engine's clock when the event states none. */
62
+ at: Date;
63
+ }
64
+
65
+ /**
66
+ * The host's answer to a courier event: `recorded` (it stored the facts),
67
+ * `unchanged` (nothing to store, with the engine's reason), or `unchanged`
68
+ * with the host's own reason, which becomes the inbox row's.
69
+ */
70
+ export type MarketplaceCourierAnswer = "recorded" | "unchanged" | { kind: "unchanged"; reason: string };
71
+
72
+ /** What `engine.courierTracking` answers. */
73
+ export type CourierTrackingResult =
74
+ | CourierTrackingCallResult
75
+ /** Nothing to call: no such marketplace order, a marketplace with no tracking, or a bag the store carries itself. */
76
+ | { kind: "unsupported"; reason: string };
77
+
78
+ /** What the host says after its hand-over committed. */
79
+ export interface ValidatePickupCodeInput {
80
+ clientId: string;
81
+ /** The host's order id. */
82
+ orderId: string;
83
+ /** The code the store checked (the one the courier stated). */
84
+ code: string;
85
+ /** The hand-over's own instant: it makes the job's key, so a hand-over after an undo is a new job. */
86
+ at: Date;
87
+ }
88
+
89
+ /** The engine's courier calls (FUT-5665), part of `MarketplaceEngine`. */
90
+ export interface MarketplaceCourierEngine {
91
+ /**
92
+ * The store handed a marketplace courier's bag over after checking the
93
+ * pickup code locally: ONE enqueue of `marketplace.outbound`, action
94
+ * `validatePickupCode`, after the hand-over's commit. Never throws, runs no
95
+ * statement and calls nobody. True when the queue took it.
96
+ */
97
+ validatePickupCode(input: ValidatePickupCodeInput): Promise<boolean>;
98
+ /** Read where the marketplace's courier is: one call to the marketplace, at once. Run it from a job. */
99
+ courierTracking(input: { clientId: string; orderId: string }): Promise<CourierTrackingResult>;
100
+ }