@12-apps/marketplace 1.8.0 → 1.10.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 (67) hide show
  1. package/ADOPTING.md +27 -1
  2. package/README.md +103 -9
  3. package/dist/99food/index.d.ts +30 -54
  4. package/dist/99food/index.js +60 -418
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{chunk-BMCERPQX.js → chunk-2BA2EHNF.js} +16 -6
  7. package/dist/chunk-2BA2EHNF.js.map +1 -0
  8. package/dist/chunk-PYHNM47K.js +478 -0
  9. package/dist/chunk-PYHNM47K.js.map +1 -0
  10. package/dist/{chunk-6N2HEV3U.js → chunk-WVZ2IXFH.js} +3 -3
  11. package/dist/{chunk-NP4EYKPO.js → chunk-ZO4S3LF4.js} +5 -3
  12. package/dist/chunk-ZO4S3LF4.js.map +1 -0
  13. package/dist/client-B4EQCRD_.d.ts +20 -0
  14. package/dist/{engine-wmW-VuBL.d.ts → engine-DK3iV_Kk.d.ts} +91 -60
  15. package/dist/hono/index.d.ts +1 -1
  16. package/dist/hono/index.js +3 -3
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +17 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/keeta/en-US.d.ts +19 -0
  21. package/dist/keeta/en-US.js +23 -0
  22. package/dist/keeta/en-US.js.map +1 -0
  23. package/dist/keeta/index.d.ts +253 -0
  24. package/dist/keeta/index.js +388 -0
  25. package/dist/keeta/index.js.map +1 -0
  26. package/dist/keeta/pt-BR.d.ts +23 -0
  27. package/dist/keeta/pt-BR.js +23 -0
  28. package/dist/keeta/pt-BR.js.map +1 -0
  29. package/dist/manifest/index.d.ts +4 -1
  30. package/dist/manifest/index.js +1 -1
  31. package/dist/manifest/server.d.ts +1 -1
  32. package/dist/manifest/server.js +3 -3
  33. package/dist/server/index.d.ts +6 -2
  34. package/dist/server/index.js +3 -3
  35. package/package.json +14 -2
  36. package/prisma/marketplace.prisma +6 -0
  37. package/prisma/migrations/20261126230000_marketplace_menu_link_variation/migration.sql +11 -0
  38. package/src/99food/catalogue.ts +19 -89
  39. package/src/99food/copy.ts +4 -19
  40. package/src/99food/index.ts +28 -33
  41. package/src/99food/normalize.ts +11 -253
  42. package/src/99food/outbound.ts +29 -270
  43. package/src/99food/pause.ts +7 -22
  44. package/src/core/bulk.ts +34 -7
  45. package/src/core/ingest.ts +2 -1
  46. package/src/core/menu-links.ts +36 -6
  47. package/src/core/order-types.ts +74 -0
  48. package/src/core/ports.ts +23 -65
  49. package/src/index.ts +2 -1
  50. package/src/keeta/authorization.ts +226 -0
  51. package/src/keeta/copy.ts +27 -0
  52. package/src/keeta/en-US.ts +19 -0
  53. package/src/keeta/index.ts +162 -0
  54. package/src/keeta/merchant.ts +70 -0
  55. package/src/keeta/normalize.ts +131 -0
  56. package/src/keeta/outbound.ts +55 -0
  57. package/src/keeta/pt-BR.ts +23 -0
  58. package/src/keeta/signature.ts +85 -0
  59. package/src/open-delivery/client.ts +185 -0
  60. package/src/open-delivery/merchant.ts +126 -0
  61. package/src/open-delivery/normalize.ts +269 -0
  62. package/src/open-delivery/orders.ts +241 -0
  63. package/src/open-delivery/reasons.ts +26 -0
  64. package/src/server/mcp.ts +7 -2
  65. package/dist/chunk-BMCERPQX.js.map +0 -1
  66. package/dist/chunk-NP4EYKPO.js.map +0 -1
  67. /package/dist/{chunk-6N2HEV3U.js.map → chunk-WVZ2IXFH.js.map} +0 -0
@@ -0,0 +1,162 @@
1
+ import type { AdapterCallContext, CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
+ import { assertHttpsUrl } from "../open-delivery/client";
3
+ import {
4
+ openDeliveryConfirm,
5
+ openDeliveryFetchOrder,
6
+ openDeliveryRequestCancellation,
7
+ openDeliveryStatus,
8
+ } from "../open-delivery/orders";
9
+ import { OPEN_DELIVERY_ITEM_UNAVAILABLE } from "../open-delivery/reasons";
10
+ import { keetaAuthorization, type KeetaAuthorization } from "./authorization";
11
+ import { KEETA_REASON_CODES, type KeetaAdapterCopy } from "./copy";
12
+ import { keetaAvailability, keetaCatalogue } from "./merchant";
13
+ import { KEETA_PROVIDER, normalizeKeetaEvent, normalizeKeetaOrder, revealKeetaOrder } from "./normalize";
14
+ import { KEETA_DEFAULT_API_BASE_URLS, keetaDialect, type KeetaApiBaseUrls } from "./outbound";
15
+ import { verifyKeetaSignature } from "./signature";
16
+
17
+ /**
18
+ * `@12-apps/marketplace/keeta` — Keeta, as one adapter on the engine.
19
+ *
20
+ * Keeta's API is Open Delivery v1.5.0 with Keeta's own changes
21
+ * (https://api-docs.mykeeta.com/apis/opendelivery, `openapi.json` "v.1.0.7"
22
+ * with the changelog to 1.0.9, read 2026-11-26), so the adapter is built on
23
+ * the same Open Delivery module as 99Food's (`../open-delivery/`), which
24
+ * speaks v1.7.1. What Keeta does differently, and where it is handled:
25
+ *
26
+ * | Keeta | 99Food (v1.7.1) | handled in |
27
+ * |---|---|---|
28
+ * | `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` |
29
+ * | webhook signature Base64 | lowercase hex | `./signature.ts` |
30
+ * | token: JSON `grant_type: app_level_token`, one token per APPLICATION (every authorized store) | form-encoded `client_credentials` | `./outbound.ts` |
31
+ * | merchant authorization by the software: authorization URL, authorized stores, onboarding, authorization webhook | none | `./authorization.ts` |
32
+ * | `merchantUpdate/{merchantId}` (path names the merchant) | `merchantUpdate` | `./merchant.ts` |
33
+ * | menu: full reload only (`ITEM_OFFER`/`OPTION` status excepted) | full reload | `./merchant.ts` |
34
+ * | personal data encrypted (`ENC_…`), `batchDecrypt` for a merchant's own delivery | plain | `./normalize.ts` |
35
+ * | no `CANCELLATION_REQUEST_DENIED`: a refused request is silent, so it ends TIMEOUT | the denial event | `./normalize.ts`, the answer window below |
36
+ * | `outOfStockItems` carries the PDV codes (`externalCode`) | item uuids, not sent | `../open-delivery/orders.ts` option |
37
+ * | no take-out: no `pickedUp`; `delivered` only for the merchant's bag | `pickedUp` for a take-out | `../open-delivery/orders.ts` option |
38
+ * | one public base URL and portal | given at onboarding | defaults below |
39
+ *
40
+ * ```ts
41
+ * import { createKeetaAdapter } from "@12-apps/marketplace/keeta";
42
+ * import { KEETA_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/keeta/pt-BR";
43
+ *
44
+ * createMarketplaceEngine({ …ports, adapters: [createKeetaAdapter({ copy: KEETA_ADAPTER_COPY_PT_BR })] });
45
+ * ```
46
+ *
47
+ * Its webhook is the engine's one route, `POST
48
+ * /webhooks/marketplace/:tenantSlug/KEETA`, registered per store as
49
+ * `ordersWebhookURL` at onboarding.
50
+ */
51
+
52
+ export { KEETA_PROVIDER } from "./normalize";
53
+
54
+ /**
55
+ * How long Keeta may take to answer a cancellation request. ESTIMATED: Keeta
56
+ * names none, and sends no event for a refusal, so past this the request is
57
+ * failed as TIMEOUT. Keeta's own clock is 5 minutes for the acceptance.
58
+ */
59
+ export const KEETA_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
60
+
61
+ /** Where "open it on Keeta" goes by default: the Merchant Portal (Keeta names no per-order link). */
62
+ export const KEETA_PORTAL_URL = "https://merchant.mykeeta.com/";
63
+
64
+ /** Keeta has no take-out (`PICKED_UP` "is not sent"), so no `pickedUp`. */
65
+ const STATUS = openDeliveryStatus({ takeoutPickedUp: false });
66
+
67
+ export interface KeetaAdapterConfig {
68
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
69
+ copy: KeetaAdapterCopy;
70
+ /** OPTIONAL. Where Keeta serves Open Delivery, per environment. Default: the documented server for both. https only. */
71
+ apiBaseUrl?: KeetaApiBaseUrls;
72
+ /** OPTIONAL. Where "open it on Keeta" goes. Default: the Merchant Portal. https only. */
73
+ portalUrl?: string;
74
+ /**
75
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through
76
+ * `merchantStatus`, a store-wide switch with no id: a store the owner also
77
+ * closed by hand on Keeta during the kitchen's pause is opened with it.
78
+ */
79
+ pauseByStoreSwitch?: boolean;
80
+ }
81
+
82
+ const assertHttps = (name: string, url: string): void => assertHttpsUrl("@12-apps/marketplace/keeta", name, url);
83
+
84
+ /** The Keeta API base URLs a config names, checked. */
85
+ function basesOf(config: Pick<KeetaAdapterConfig, "apiBaseUrl">): KeetaApiBaseUrls {
86
+ const bases = { ...(config.apiBaseUrl ?? KEETA_DEFAULT_API_BASE_URLS) };
87
+ assertHttps("apiBaseUrl.SANDBOX", bases.SANDBOX);
88
+ assertHttps("apiBaseUrl.PRODUCTION", bases.PRODUCTION);
89
+ return bases;
90
+ }
91
+
92
+ /** Build the Keeta adapter. Its reasons are static: a dialog never waits on Keeta. */
93
+ export function createKeetaAdapter(config: KeetaAdapterConfig): MarketplaceAdapter {
94
+ const dialect = keetaDialect(basesOf(config));
95
+ const portalUrl = config.portalUrl ?? KEETA_PORTAL_URL;
96
+ assertHttps("portalUrl", portalUrl);
97
+ const reasons: readonly CancellationReason[] = KEETA_REASON_CODES.map((code) => ({
98
+ code,
99
+ label: config.copy.reasonLabels[code],
100
+ itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,
101
+ // `outOfStockItems` is optional: sent when the store named the SKUs, never required.
102
+ needsItems: false,
103
+ }));
104
+ const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };
105
+ const fetchOptions = {
106
+ normalize: (order: unknown) => normalizeKeetaOrder(order, normalizeOptions),
107
+ prepare: (ctx: AdapterCallContext, order: unknown) => revealKeetaOrder(ctx, dialect, order),
108
+ };
109
+ // Keeta's own example sends PDV codes in `outOfStockItems` ("PDV-1002"). ESTIMATED that it reads them so.
110
+ const cancellation = { outOfStockAsSkus: true };
111
+ return {
112
+ provider: KEETA_PROVIDER,
113
+ capabilities: {
114
+ apiConfirm: true,
115
+ apiCancel: true,
116
+ // "The merchant may cancel up to 48 h after the conclusion"; the answer is Keeta's.
117
+ cancelAfterAccept: true,
118
+ // 202 ("received for analysis"), then CANCELLED, or nothing at all.
119
+ asyncCancellationOutcome: true,
120
+ perOrderAppLink: false,
121
+ // `OrderConfirmed.preparationTime`, in minutes.
122
+ confirmTakesPreparationTime: true,
123
+ cancellationAnswerWindowMs: KEETA_CANCELLATION_ANSWER_WINDOW_MS,
124
+ // readyForPickup, dispatch (merchant's bag) and delivered (merchant's bag).
125
+ statusSteps: ["READY", "DISPATCHED", "HANDED_OVER"],
126
+ },
127
+ normalize: normalizeKeetaEvent,
128
+ readSignature: (header) => header("x-app-signature"),
129
+ verifySignature: verifyKeetaSignature,
130
+ cancellationReasons: () => reasons,
131
+ // PULL: Keeta reads the menu the host serves (`GET /v1/merchant`) and is told when it changed.
132
+ catalogue: keetaCatalogue(dialect),
133
+ fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, dialect, order, fetchOptions),
134
+ confirm: (ctx, order, input) => openDeliveryConfirm(ctx, dialect, order, input),
135
+ requestCancellation: (ctx, order, input) =>
136
+ openDeliveryRequestCancellation(ctx, dialect, order, input, cancellation),
137
+ statusSupported: STATUS.supported,
138
+ informStatus: (ctx, order, facts) => STATUS.inform(ctx, dialect, order, facts),
139
+ appLink: () => portalUrl,
140
+ ...(config.pauseByStoreSwitch ? { availability: keetaAvailability(dialect) } : {}),
141
+ };
142
+ }
143
+
144
+ /** The self-serve merchant authorization calls (`./authorization.ts`), for the same base URLs as the adapter. */
145
+ export function createKeetaAuthorization(config: Pick<KeetaAdapterConfig, "apiBaseUrl"> = {}): KeetaAuthorization {
146
+ return keetaAuthorization(keetaDialect(basesOf(config)));
147
+ }
148
+
149
+ export { KEETA_REASON_CODES, type KeetaAdapterCopy, type KeetaReasonCode } from "./copy";
150
+ export { normalizeKeetaEvent, normalizeKeetaOrder } from "./normalize";
151
+ export { canonicalJson, keetaRequestSignature, verifyKeetaSignature } from "./signature";
152
+ export { KEETA_API_BASE_URL, type KeetaApiBaseUrls } from "./outbound";
153
+ export {
154
+ KEETA_AUTHORIZATION_WEBHOOK_ANSWER,
155
+ normalizeKeetaAuthorizationEvent,
156
+ type KeetaAuthorization,
157
+ type KeetaAuthorizationEvent,
158
+ type KeetaAuthorizationResult,
159
+ type KeetaAuthorizedShop,
160
+ type KeetaAuthorizedShops,
161
+ type KeetaOnboarding,
162
+ } from "./authorization";
@@ -0,0 +1,70 @@
1
+ import type { AdapterCallContext, OutboundResult } from "../core/adapter";
2
+ import type { PullCatalogue } from "../core/catalogue-port";
3
+ import type { MarketplaceAvailability } from "../core/pause-port";
4
+ import type { OpenDeliveryDialect } from "../open-delivery/client";
5
+ import {
6
+ openDeliveryMenuDocument,
7
+ openDeliveryMerchantUpdate,
8
+ openDeliverySwitchAvailability,
9
+ } from "../open-delivery/merchant";
10
+
11
+ /**
12
+ * Keeta's MERCHANT half: the menu (FUT-4768) and the store pause (FUT-4851),
13
+ * both on `POST /v1/merchantUpdate/{merchantId}` (Keeta's path names the
14
+ * merchant, by the SOFTWARE's id; the standard's names none). Read
15
+ * 2026-11-26 at https://api-docs.mykeeta.com/apis/opendelivery/merchantendpoints/merchantupdate.
16
+ *
17
+ * MENU. Keeta's menu API takes the store's menu three ways: an empty body
18
+ * ("Keeta calls your `GET /v1/merchant` and reloads everything"),
19
+ * `merchantStatus` alone, or `entityType` + `updatedObjects`. Of the last,
20
+ * only `ITEM_OFFER` and `OPTION` are applied as sent, and only their
21
+ * `status`; `MENU`, `CATEGORY`, `ITEM`… still make Keeta pull the whole menu
22
+ * ("only full-menu update"). So a product cannot be PUSHED to Keeta: its
23
+ * name, photo and price reach Keeta only through the `Merchant` document the
24
+ * host serves. The adapter is therefore PULL: `menuDocument` builds the menu
25
+ * part of that document (shared with 99Food: every item `UN` with a status,
26
+ * every offer with `originalValue`, which Keeta requires), and
27
+ * `notifyMenuChanged` sends the empty-body update that makes Keeta pull it.
28
+ *
29
+ * What Keeta reads of the rest of the `Merchant`, the host's to serve (Keeta's
30
+ * `getMerchant` page): `id`, `status`, `basicInfo.contactEmails` (up to 3) and
31
+ * `basicInfo.contactPhones.commercialNumber` (required), `services[]` with
32
+ * `serviceType: DELIVERY` (the only one Keeta uses), `menuId` and
33
+ * `serviceHours` in UTC; `lastUpdate`, `TTL` and the offers' `currency` are
34
+ * ignored. The document's URL is registered per merchant at onboarding
35
+ * (`./authorization.ts`).
36
+ *
37
+ * PAUSE. `{ merchantStatus: "UNAVAILABLE" | "AVAILABLE" }` closes or opens the
38
+ * store, with no end and no id: a switch, offered only when the host opts in.
39
+ * Answer 204; 400, 401, 503.
40
+ *
41
+ * ESTIMATED: that an update sent with no body (no `Content-Type` either) is
42
+ * read as the documented "empty body"; that the menu is PUBLISHED once Keeta
43
+ * took the notification, not once it read the menu (as for 99Food).
44
+ */
45
+
46
+ const merchantUpdatePath = (merchantId: string): string => `/v1/merchantUpdate/${encodeURIComponent(merchantId)}`;
47
+
48
+ /** Keeta's catalogue capability. */
49
+ export function keetaCatalogue(dialect: OpenDeliveryDialect): PullCatalogue {
50
+ return {
51
+ mode: "pull",
52
+ menuDocument: openDeliveryMenuDocument,
53
+ notifyMenuChanged: (ctx) => openDeliveryMerchantUpdate(ctx, dialect, { path: merchantUpdatePath(ctx.externalMerchantId) }),
54
+ };
55
+ }
56
+
57
+ /** Open or close the store on Keeta. */
58
+ function keetaSetMerchantStatus(
59
+ ctx: AdapterCallContext,
60
+ dialect: OpenDeliveryDialect,
61
+ merchantId: string,
62
+ status: "AVAILABLE" | "UNAVAILABLE",
63
+ ): Promise<OutboundResult> {
64
+ return openDeliveryMerchantUpdate(ctx, dialect, { path: merchantUpdatePath(merchantId), body: { merchantStatus: status } });
65
+ }
66
+
67
+ /** Keeta's availability capability: `merchantStatus`, a switch. */
68
+ export function keetaAvailability(dialect: OpenDeliveryDialect): MarketplaceAvailability {
69
+ return openDeliverySwitchAvailability((ctx, merchantId, status) => keetaSetMerchantStatus(ctx, dialect, merchantId, status));
70
+ }
@@ -0,0 +1,131 @@
1
+ import { outboundResultOf, type AdapterCallContext } from "../core/adapter";
2
+ import { pick } from "../core/payload-read";
3
+ import type { NormalizedEvent, NormalizedMarketplaceOrder } from "../core/types";
4
+ import { isStop, openDeliveryCall, type OpenDeliveryDialect } from "../open-delivery/client";
5
+ import { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from "../open-delivery/normalize";
6
+
7
+ /**
8
+ * The Keeta adapter's INBOUND half: Open Delivery's readers
9
+ * (`../open-delivery/normalize.ts`) stamped with Keeta's provider id, plus
10
+ * the one thing Keeta's `Order` does that the standard's does not: personal
11
+ * data arrives ENCRYPTED.
12
+ *
13
+ * Events (Keeta's order guide, read 2026-11-26): `CREATED` → fetch;
14
+ * `CANCELLED` (with a JSON-string `metadata` carrying `reason` and `code`) →
15
+ * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle. Keeta has NO
16
+ * `CANCELLATION_REQUEST_DENIED`: a store's request that Keeta does not grant
17
+ * produces no event, so it ends TIMEOUT at the adapter's answer window. The
18
+ * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`,
19
+ * `RIDER_ARRIVED_AT_STORE`, `ORDER_COLLECTED`, `DELIVERED`,
20
+ * `CANCELLATION_REQUESTED`, `USER_REFUND_REQUEST`, `REFUNDED`,
21
+ * `REFUND_FAILED`, `RECOMMENDED_PREPARATION_START`) are recorded and IGNORED.
22
+ */
23
+
24
+ /** The provider id Keeta is registered under. Uppercase: the column's CHECK holds that shape. */
25
+ export const KEETA_PROVIDER = "KEETA";
26
+
27
+ /** Keeta's prefix on an encrypted value (`ENC_#MQesaE=#1#`). */
28
+ const ENCRYPTED_PREFIX = "ENC_";
29
+ /** `POST /v1/batchDecrypt` takes at most 50 values a call. */
30
+ const DECRYPT_BATCH = 50;
31
+
32
+ /** Normalize one webhook `Event`. Null only when it names no order. */
33
+ export function normalizeKeetaEvent(payload: unknown): NormalizedEvent | null {
34
+ return normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);
35
+ }
36
+
37
+ /** Normalize one `Order`, after {@link revealKeetaOrder}. Null when it carries no id or no line. */
38
+ export function normalizeKeetaOrder(
39
+ order: unknown,
40
+ options: { missingStreetNumber: string },
41
+ ): NormalizedMarketplaceOrder | null {
42
+ return normalizeOpenDeliveryOrderAs(KEETA_PROVIDER, order, options);
43
+ }
44
+
45
+ const isEncrypted = (value: unknown): value is string =>
46
+ typeof value === "string" && value.startsWith(ENCRYPTED_PREFIX);
47
+
48
+ /** Every encrypted value anywhere in the order, once each. */
49
+ function ciphersOf(value: unknown, found: Set<string>): Set<string> {
50
+ if (isEncrypted(value)) found.add(value);
51
+ else if (Array.isArray(value)) for (const entry of value) ciphersOf(entry, found);
52
+ else if (typeof value === "object" && value !== null) for (const entry of Object.values(value)) ciphersOf(entry, found);
53
+ return found;
54
+ }
55
+
56
+ /** A copy of the order with each encrypted value replaced by its plain text, or removed when there is none. */
57
+ function replaced(value: unknown, plain: ReadonlyMap<string, string>): unknown {
58
+ if (Array.isArray(value)) return value.map((entry) => replaced(entry, plain));
59
+ if (typeof value === "object" && value !== null) {
60
+ const copy: Record<string, unknown> = {};
61
+ for (const [key, entry] of Object.entries(value)) {
62
+ if (isEncrypted(entry) && !plain.has(entry)) continue;
63
+ copy[key] = isEncrypted(entry) ? plain.get(entry) : replaced(entry, plain);
64
+ }
65
+ return copy;
66
+ }
67
+ return value;
68
+ }
69
+
70
+ /** The `{ cipherText, plainText }` pairs a `batchDecrypt` answer carries with `errorCode` 0. */
71
+ function plainPairs(body: string): [string, string][] {
72
+ const infos = pick(JSON.parse(body), "plainInfos");
73
+ return (Array.isArray(infos) ? infos : []).flatMap((info): [string, string][] => {
74
+ const cipher = pick(info, "cipherText");
75
+ const text = pick(info, "plainText");
76
+ const code = pick(info, "errorCode");
77
+ return typeof cipher === "string" && typeof text === "string" && (code === undefined || code === 0)
78
+ ? [[cipher, text]]
79
+ : [];
80
+ });
81
+ }
82
+
83
+ /** One `POST /v1/batchDecrypt` call: the plain texts it gave, none on any failure. */
84
+ async function decrypt(
85
+ ctx: AdapterCallContext,
86
+ dialect: OpenDeliveryDialect,
87
+ ciphers: readonly string[],
88
+ ): Promise<[string, string][]> {
89
+ try {
90
+ const response = await openDeliveryCall(ctx, dialect, {
91
+ method: "POST",
92
+ path: "/v1/batchDecrypt",
93
+ body: { cipherInfos: ciphers.map((cipherText) => ({ cipherText })) },
94
+ });
95
+ if (isStop(response) || outboundResultOf(response).kind !== "accepted") return [];
96
+ return plainPairs(response.body);
97
+ } catch {
98
+ return [];
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Keeta encrypts `customer.phone.number` and the address's `district`,
104
+ * `number`, `complement` and `formattedAddress` (`ENC_…`). Only an order the
105
+ * MERCHANT delivers (its own courier or its 3PL) may be decrypted, through
106
+ * `POST /v1/batchDecrypt` (at most 50 values a call); on Keeta's own fleet
107
+ * the data stays masked. So: a merchant bag is decrypted, and every value
108
+ * still encrypted after that (Keeta's fleet, a value Keeta would not decrypt,
109
+ * a failed call) is REMOVED, never shown — the address then reads the copy's
110
+ * missing-number text, and the phone is null.
111
+ *
112
+ * Never fails the fetch (choice): Keeta cancels an order not accepted within
113
+ * 5 minutes and may close the store for it, so a decrypt that failed must not
114
+ * keep the order out of the queue; the store reads the address on Keeta.
115
+ */
116
+ export async function revealKeetaOrder(
117
+ ctx: AdapterCallContext,
118
+ dialect: OpenDeliveryDialect,
119
+ order: unknown,
120
+ ): Promise<unknown> {
121
+ const ciphers = [...ciphersOf(order, new Set())];
122
+ if (ciphers.length === 0) return order;
123
+ const plain = new Map<string, string>();
124
+ if (pick(order, "delivery", "deliveredBy") === "MERCHANT") {
125
+ const batches: string[][] = [];
126
+ for (let start = 0; start < ciphers.length; start += DECRYPT_BATCH) batches.push(ciphers.slice(start, start + DECRYPT_BATCH));
127
+ const answers = await Promise.all(batches.map((batch) => decrypt(ctx, dialect, batch)));
128
+ for (const [cipher, text] of answers.flat()) plain.set(cipher, text);
129
+ }
130
+ return replaced(order, plain);
131
+ }
@@ -0,0 +1,55 @@
1
+ import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from "../open-delivery/client";
2
+ import { KEETA_PROVIDER } from "./normalize";
3
+ import { canonicalJson, keetaRequestSignature } from "./signature";
4
+
5
+ /**
6
+ * Keeta's Open Delivery DIALECT. Keeta follows Open Delivery v1.5.0 with
7
+ * changes of its own, and "the definitions of this document prevail"
8
+ * (https://api-docs.mykeeta.com/apis/opendelivery/general-info, read
9
+ * 2026-11-26). The calls are `../open-delivery/`'s; this file says how Keeta
10
+ * takes them:
11
+ *
12
+ * - Token: `POST /oauth/token` with a JSON body `{ client_id, client_secret,
13
+ * grant_type: "app_level_token" }` (v1.0.9's name for the standard's
14
+ * `client_credentials`, which stays accepted for integrations already
15
+ * certified). The token is the APPLICATION's: one for every store that
16
+ * authorized it, so the cache key (provider, environment, client id) is
17
+ * right as it is. Answer `{ access_token, token_type, expires_in }`; no
18
+ * refresh token in this mode.
19
+ * - Every request, the grant included, carries `X-App-Signature`
20
+ * (`./signature.ts`), and every JSON body is RFC 8785 canonical.
21
+ */
22
+
23
+ /** Where Keeta serves Open Delivery, per environment. */
24
+ export type KeetaApiBaseUrls = OpenDeliveryApiBaseUrls;
25
+
26
+ /**
27
+ * The documented server (`servers[0]` of Keeta's `openapi.json`). ESTIMATED
28
+ * for SANDBOX: Keeta documents one host, and a test application (its own
29
+ * client id and secret, its test stores) is what makes a session a test one.
30
+ */
31
+ export const KEETA_API_BASE_URL = "https://open.mykeeta.com/api/open/opendelivery";
32
+
33
+ export const KEETA_DEFAULT_API_BASE_URLS: KeetaApiBaseUrls = {
34
+ SANDBOX: KEETA_API_BASE_URL,
35
+ PRODUCTION: KEETA_API_BASE_URL,
36
+ };
37
+
38
+ /** Keeta's dialect, for the base URLs it was given. */
39
+ export function keetaDialect(bases: KeetaApiBaseUrls): OpenDeliveryDialect {
40
+ return {
41
+ provider: KEETA_PROVIDER,
42
+ name: "Keeta",
43
+ bases,
44
+ tokenGrant: (ctx) => ({
45
+ contentType: "application/json",
46
+ body: canonicalJson({
47
+ client_id: ctx.credentials.clientId,
48
+ client_secret: ctx.credentials.clientSecret,
49
+ grant_type: "app_level_token",
50
+ }),
51
+ }),
52
+ serialize: canonicalJson,
53
+ sign: (ctx, url, body) => ({ "X-App-Signature": keetaRequestSignature(url, body, ctx.credentials.clientSecret) }),
54
+ };
55
+ }
@@ -0,0 +1,23 @@
1
+ import type { KeetaAdapterCopy } from "./copy";
2
+
3
+ /**
4
+ * The Keeta adapter's pt-BR pack: each code in the words of Keeta's own
5
+ * cancellation table ("Significado"). A host passes this pack by hand:
6
+ * choosing the language is a line in the host's diff.
7
+ */
8
+ export const KEETA_ADAPTER_COPY_PT_BR = {
9
+ reasonLabels: {
10
+ SYSTEMIC_ISSUES: "Problemas sistêmicos",
11
+ DUPLICATE_APPLICATION: "Pedido duplicado",
12
+ UNAVAILABLE_ITEM: "Item indisponível",
13
+ RESTAURANT_WITHOUT_DELIVERY_PERSON: "Restaurante sem entregador",
14
+ OUTDATED_MENU: "Cardápio desatualizado",
15
+ ORDER_OUTSIDE_THE_DELIVERY_AREA: "Fora da área de entrega",
16
+ BLOCKED_CUSTOMER: "Cliente bloqueado",
17
+ OUTSIDE_DELIVERY_HOURS: "Fora do horário de entrega",
18
+ INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Dificuldades internas",
19
+ RISK_AREA: "Área de risco",
20
+ DELIVERY_PROBLEM: "Problema na entrega",
21
+ },
22
+ missingStreetNumber: "s/n",
23
+ } as const satisfies KeetaAdapterCopy;
@@ -0,0 +1,85 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ /**
4
+ * Keeta's `X-App-Signature`, both directions (read 2026-11-26 at
5
+ * https://api-docs.mykeeta.com/apis/opendelivery/signature-calculation and its
6
+ * three sub-pages, and the `newEvent` and webhook guide pages).
7
+ *
8
+ * OUTBOUND — every request the software sends Keeta, the token grant
9
+ * included, carries it (Keeta's change to Open Delivery: a token alone is not
10
+ * enough, so an intercepted token cannot be replayed):
11
+ *
12
+ * - the string is the URL without its query, then `&key=value` for each
13
+ * query parameter sorted by key (a null value is `key=`), then `&` and the
14
+ * body when there is one: an empty body, a blank one or `{}` is left out,
15
+ * and so is its `&`;
16
+ * - the body is compact JSON canonicalized by RFC 8785 (JCS), and the SAME
17
+ * string is sent;
18
+ * - HMAC-SHA256 of the string (UTF-8), keyed by the application's
19
+ * `client_secret`, encoded Base64.
20
+ *
21
+ * INBOUND — a webhook Keeta sends (`POST /v1/newEvent`, and the
22
+ * authorization webhook) is signed "HMAC-SHA256 of the body, with the
23
+ * client_secret as key, in Base64".
24
+ *
25
+ * ESTIMATED:
26
+ * - query values are signed DECODED (the reference implementations take them
27
+ * from a map, before any URL encoding); only the self-serve authorization
28
+ * calls send a query, and only `redirectUri` can hold a character encoding
29
+ * changes;
30
+ * - the inbound signature covers the raw body bytes as received, with no URL
31
+ * prefix (the pages say "the body");
32
+ * - the authorization webhook's header uses the same Base64 HMAC (its schema
33
+ * says only "SHA256 hash of the request body, using the client secret as the
34
+ * key").
35
+ */
36
+
37
+ /**
38
+ * RFC 8785 (JCS) for the JSON this adapter sends: object keys sorted by
39
+ * UTF-16 code units, no whitespace, strings and numbers as ECMAScript's
40
+ * `JSON.stringify` writes them (which is what JCS specifies). `undefined`
41
+ * members are dropped, as `JSON.stringify` drops them.
42
+ */
43
+ export function canonicalJson(value: unknown): string {
44
+ if (Array.isArray(value)) {
45
+ return `[${value.map((entry) => (entry === undefined ? "null" : canonicalJson(entry))).join(",")}]`;
46
+ }
47
+ if (typeof value === "object" && value !== null) {
48
+ const record = value as Record<string, unknown>;
49
+ const keys = Object.keys(record)
50
+ .filter((key) => record[key] !== undefined)
51
+ .sort();
52
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
53
+ }
54
+ return JSON.stringify(value) ?? "null";
55
+ }
56
+
57
+ /** The string Keeta signs for one request. */
58
+ export function keetaSignatureString(url: string, body: string | undefined): string {
59
+ const parsed = new URL(url);
60
+ const parts = [`${parsed.origin}${parsed.pathname}`];
61
+ const keys = [...new Set(parsed.searchParams.keys())].sort();
62
+ for (const key of keys) parts.push(`${key}=${parsed.searchParams.get(key) ?? ""}`);
63
+ const trimmed = body?.trim() ?? "";
64
+ if (trimmed !== "" && trimmed !== "{}") parts.push(body ?? "");
65
+ return parts.join("&");
66
+ }
67
+
68
+ /** The `X-App-Signature` of one outbound request. */
69
+ export function keetaRequestSignature(url: string, body: string | undefined, clientSecret: string): string {
70
+ return createHmac("sha256", clientSecret).update(keetaSignatureString(url, body), "utf8").digest("base64");
71
+ }
72
+
73
+ /**
74
+ * Verify a webhook Keeta sent: Base64 HMAC-SHA256 of the raw body, keyed by
75
+ * the application's client secret, which a connection stores as its webhook
76
+ * secret. The key exists from the moment the store connects, so an unset
77
+ * secret REFUSES: an unsigned CANCELLED for a known order id would otherwise
78
+ * cancel it. Compared in constant time.
79
+ */
80
+ export function verifyKeetaSignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean {
81
+ if (!webhookSecret || !signature) return false;
82
+ const expected = Buffer.from(createHmac("sha256", webhookSecret).update(rawBody, "utf8").digest("base64"), "utf8");
83
+ const given = Buffer.from(signature.trim(), "utf8");
84
+ return given.length === expected.length && timingSafeEqual(given, expected);
85
+ }