@12-apps/marketplace 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +153 -3
  3. package/dist/99food/index.d.ts +30 -52
  4. package/dist/99food/index.js +62 -391
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/chunk-PYHNM47K.js +478 -0
  16. package/dist/chunk-PYHNM47K.js.map +1 -0
  17. package/dist/client-B4EQCRD_.d.ts +20 -0
  18. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  19. package/dist/hono/index.d.ts +2 -2
  20. package/dist/hono/index.js +3 -3
  21. package/dist/ifood/index.d.ts +1 -1
  22. package/dist/ifood/index.js +29 -3
  23. package/dist/ifood/index.js.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +104 -7
  26. package/dist/index.js.map +1 -1
  27. package/dist/keeta/en-US.d.ts +19 -0
  28. package/dist/keeta/en-US.js +23 -0
  29. package/dist/keeta/en-US.js.map +1 -0
  30. package/dist/keeta/index.d.ts +253 -0
  31. package/dist/keeta/index.js +388 -0
  32. package/dist/keeta/index.js.map +1 -0
  33. package/dist/keeta/pt-BR.d.ts +23 -0
  34. package/dist/keeta/pt-BR.js +23 -0
  35. package/dist/keeta/pt-BR.js.map +1 -0
  36. package/dist/manifest/index.d.ts +3 -0
  37. package/dist/manifest/index.js +1 -1
  38. package/dist/manifest/server.d.ts +2 -2
  39. package/dist/manifest/server.js +3 -3
  40. package/dist/rappi/index.d.ts +7 -1
  41. package/dist/rappi/index.js +20 -3
  42. package/dist/rappi/index.js.map +1 -1
  43. package/dist/server/index.d.ts +6 -2
  44. package/dist/server/index.js +3 -3
  45. package/package.json +14 -2
  46. package/prisma/marketplace.prisma +45 -1
  47. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  48. package/src/99food/catalogue.ts +19 -89
  49. package/src/99food/copy.ts +4 -19
  50. package/src/99food/index.ts +29 -28
  51. package/src/99food/normalize.ts +11 -247
  52. package/src/99food/outbound.ts +29 -215
  53. package/src/99food/pause.ts +7 -22
  54. package/src/core/adapter.ts +41 -1
  55. package/src/core/bulk.ts +1 -1
  56. package/src/core/engine.ts +9 -0
  57. package/src/core/ingest.ts +6 -0
  58. package/src/core/integration.ts +17 -0
  59. package/src/core/lifecycle-port.ts +16 -0
  60. package/src/core/lifecycle.ts +133 -0
  61. package/src/core/outbound-queue.ts +24 -4
  62. package/src/core/outbound-sweep.ts +49 -5
  63. package/src/core/outbound.ts +11 -0
  64. package/src/core/pipeline.ts +22 -2
  65. package/src/core/ports.ts +39 -3
  66. package/src/core/status-inform.ts +51 -0
  67. package/src/core/status-job.ts +207 -0
  68. package/src/core/status-store.ts +85 -0
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +7 -1
  71. package/src/ifood/normalize.ts +17 -0
  72. package/src/ifood/outbound.ts +35 -0
  73. package/src/index.ts +8 -1
  74. package/src/keeta/authorization.ts +226 -0
  75. package/src/keeta/copy.ts +27 -0
  76. package/src/keeta/en-US.ts +19 -0
  77. package/src/keeta/index.ts +162 -0
  78. package/src/keeta/merchant.ts +70 -0
  79. package/src/keeta/normalize.ts +131 -0
  80. package/src/keeta/outbound.ts +55 -0
  81. package/src/keeta/pt-BR.ts +23 -0
  82. package/src/keeta/signature.ts +85 -0
  83. package/src/open-delivery/client.ts +185 -0
  84. package/src/open-delivery/merchant.ts +126 -0
  85. package/src/open-delivery/normalize.ts +269 -0
  86. package/src/open-delivery/orders.ts +241 -0
  87. package/src/open-delivery/reasons.ts +26 -0
  88. package/src/rappi/index.ts +6 -1
  89. package/src/rappi/normalize.ts +6 -0
  90. package/src/rappi/outbound.ts +31 -2
  91. package/src/server/mcp.ts +2 -0
  92. package/src/server/webhook.ts +3 -1
  93. package/dist/chunk-L3DCOZUU.js.map +0 -1
  94. package/dist/chunk-SJUKBCVO.js.map +0 -1
  95. package/dist/chunk-UYFYGGCS.js.map +0 -1
  96. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -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
+ }
@@ -0,0 +1,185 @@
1
+ import {
2
+ tokenGrantResultOf,
3
+ type AdapterCallContext,
4
+ type MarketplaceHttpRequest,
5
+ type MarketplaceHttpResponse,
6
+ type OutboundResult,
7
+ } from "../core/adapter";
8
+
9
+ /**
10
+ * The HTTP half every Open Delivery adapter shares: the token grant and its
11
+ * cache, and one authenticated call. Not a subpath: an adapter folder
12
+ * (`../99food`, `../keeta`) builds a {@link OpenDeliveryDialect} and hands it
13
+ * to these functions, so the standard is written once and each marketplace's
14
+ * departures from it are data in its own folder.
15
+ *
16
+ * Open Delivery standardizes the PATHS under each Ordering Application's own
17
+ * base URL, so the base URL per environment is part of the dialect.
18
+ */
19
+
20
+ /** Where an Ordering Application serves Open Delivery, per environment. */
21
+ export type OpenDeliveryApiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
22
+
23
+ /** One marketplace's way of speaking Open Delivery: what differs from the standard, as data. */
24
+ export interface OpenDeliveryDialect {
25
+ /** The provider id the adapter is registered under; it keys the token cache. */
26
+ readonly provider: string;
27
+ /** The marketplace's name, in the reasons a log reads ("99Food refused the token"). */
28
+ readonly name: string;
29
+ readonly bases: OpenDeliveryApiBaseUrls;
30
+ /** The token grant's `Content-Type` and body: the standard's form-encoded `client_credentials`, or the marketplace's own. */
31
+ tokenGrant(ctx: AdapterCallContext): { contentType: string; body: string };
32
+ /** A JSON body exactly as it is sent (and, where a signature covers it, signed). */
33
+ serialize(body: unknown): string;
34
+ /** OPTIONAL. Headers derived from the final URL and body, added to EVERY call, the token grant included (a signature). */
35
+ sign?(ctx: AdapterCallContext, url: string, body: string | undefined): Record<string, string>;
36
+ }
37
+
38
+ /** Refuse, at construction, a configured URL that is not https: credentials travel on it. */
39
+ export function assertHttpsUrl(packagePath: string, name: string, url: string): void {
40
+ let parsed: URL;
41
+ try {
42
+ parsed = new URL(url);
43
+ } catch {
44
+ throw new Error(`${packagePath}: ${name} is not a URL.`);
45
+ }
46
+ if (parsed.protocol !== "https:") throw new Error(`${packagePath}: ${name} must be https.`);
47
+ }
48
+
49
+ /** A token is renewed this long before it expires. */
50
+ const TOKEN_MARGIN_MS = 60_000;
51
+ /** `expires_in` is optional in the standard's `TokenResponse`; an hour when absent. ESTIMATED. */
52
+ const DEFAULT_TOKEN_SECONDS = 3600;
53
+
54
+ /** The result that ends a call before it was answered usefully. */
55
+ export type OpenDeliveryStop = Exclude<OutboundResult, { kind: "accepted" }>;
56
+
57
+ /** The base URL with its trailing slashes cut, by a loop: a `/\/+$/` regex backtracks polynomially on many slashes. */
58
+ function baseOf(ctx: AdapterCallContext, bases: OpenDeliveryApiBaseUrls): string {
59
+ const base = bases[ctx.environment];
60
+ let end = base.length;
61
+ while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
62
+ return base.slice(0, end);
63
+ }
64
+
65
+ const tokenKey = (ctx: AdapterCallContext, dialect: OpenDeliveryDialect): string =>
66
+ `${dialect.provider}:${ctx.environment}:${ctx.credentials.clientId}`;
67
+
68
+ /** The standard's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */
69
+ function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
70
+ try {
71
+ const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };
72
+ if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
73
+ const expires =
74
+ typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
75
+ return { token: parsed.access_token, expiresInSeconds: expires };
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ /** The dialect's signature headers for one request, or none. */
82
+ function signed(
83
+ ctx: AdapterCallContext,
84
+ dialect: OpenDeliveryDialect,
85
+ request: MarketplaceHttpRequest,
86
+ ): MarketplaceHttpRequest {
87
+ if (!dialect.sign) return request;
88
+ return { ...request, headers: { ...request.headers, ...dialect.sign(ctx, request.url, request.body) } };
89
+ }
90
+
91
+ /**
92
+ * A bearer token from the per-process cache, or a fresh grant at `POST
93
+ * /oauth/token`. Keyed by provider, environment and client id; memory only.
94
+ */
95
+ async function bearer(
96
+ ctx: AdapterCallContext,
97
+ dialect: OpenDeliveryDialect,
98
+ ): Promise<{ token: string } | OpenDeliveryStop> {
99
+ const cached = ctx.tokens.get(tokenKey(ctx, dialect));
100
+ if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
101
+ const grant = dialect.tokenGrant(ctx);
102
+ const response = await ctx.http(
103
+ signed(ctx, dialect, {
104
+ method: "POST",
105
+ url: `${baseOf(ctx, dialect.bases)}/oauth/token`,
106
+ headers: { "Content-Type": grant.contentType },
107
+ body: grant.body,
108
+ }),
109
+ );
110
+ if (response.status < 200 || response.status >= 300) {
111
+ const result = tokenGrantResultOf(response);
112
+ return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
113
+ }
114
+ const token = tokenOf(response.body);
115
+ if (!token) return { kind: "retry", reason: `${dialect.name} answered the token grant without a token` };
116
+ ctx.tokens.set(tokenKey(ctx, dialect), {
117
+ token: token.token,
118
+ expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000,
119
+ });
120
+ return { token: token.token };
121
+ }
122
+
123
+ /** One call, as an Open Delivery adapter states it. */
124
+ interface OpenDeliveryCall {
125
+ method: MarketplaceHttpRequest["method"];
126
+ /** From the base: `/v1/orders/…`. Path segments are the caller's to encode. */
127
+ path: string;
128
+ /** Sent as the query string. */
129
+ query?: Readonly<Record<string, string>>;
130
+ /** A JSON body, serialized by the dialect. Absent: no body and no `Content-Type`. */
131
+ body?: unknown;
132
+ /** Extra headers (`X-App-MerchantId`). */
133
+ headers?: Readonly<Record<string, string>>;
134
+ /** Whether the call carries the bearer token. Default true; the standard's few open calls say false. */
135
+ authenticated?: boolean;
136
+ }
137
+
138
+ /** The URL a call goes to: base, path, and the query string when there is one. */
139
+ function urlOf(ctx: AdapterCallContext, dialect: OpenDeliveryDialect, call: OpenDeliveryCall): string {
140
+ const query = call.query && Object.keys(call.query).length > 0 ? `?${new URLSearchParams(call.query).toString()}` : "";
141
+ return `${baseOf(ctx, dialect.bases)}${call.path}${query}`;
142
+ }
143
+
144
+ /** The request a call makes, before its signature. */
145
+ function requestOf(
146
+ ctx: AdapterCallContext,
147
+ dialect: OpenDeliveryDialect,
148
+ call: OpenDeliveryCall,
149
+ token: string | null,
150
+ ): MarketplaceHttpRequest {
151
+ const body = call.body === undefined ? undefined : dialect.serialize(call.body);
152
+ return {
153
+ method: call.method,
154
+ url: urlOf(ctx, dialect, call),
155
+ headers: {
156
+ ...(token === null ? {} : { Authorization: `Bearer ${token}` }),
157
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
158
+ ...call.headers,
159
+ },
160
+ ...(body === undefined ? {} : { body }),
161
+ };
162
+ }
163
+
164
+ /**
165
+ * One call, authenticated unless it says otherwise: the raw answer, or the
166
+ * result that ends it. A 401 is a token that went stale under us: it is
167
+ * forgotten, and the retry fetches another.
168
+ */
169
+ export async function openDeliveryCall(
170
+ ctx: AdapterCallContext,
171
+ dialect: OpenDeliveryDialect,
172
+ call: OpenDeliveryCall,
173
+ ): Promise<MarketplaceHttpResponse | OpenDeliveryStop> {
174
+ const authenticated = call.authenticated ?? true;
175
+ const auth = authenticated ? await bearer(ctx, dialect) : null;
176
+ if (auth && !("token" in auth)) return auth;
177
+ const response = await ctx.http(signed(ctx, dialect, requestOf(ctx, dialect, call, auth?.token ?? null)));
178
+ if (!authenticated || response.status !== 401) return response;
179
+ ctx.tokens.delete(tokenKey(ctx, dialect));
180
+ return { kind: "retry", reason: `${dialect.name} refused the token` };
181
+ }
182
+
183
+ /** Whether a call ended before an answer worth reading. */
184
+ export const isStop = (value: MarketplaceHttpResponse | OpenDeliveryStop): value is OpenDeliveryStop =>
185
+ "kind" in value;
@@ -0,0 +1,126 @@
1
+ import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
2
+ import { stableUuid } from "../core/catalogue-ids";
3
+ import type { CatalogueMenuEntry, CatalogueMenuOptions } from "../core/catalogue-port";
4
+ import type { MarketplaceAvailability } from "../core/pause-port";
5
+ import { isStop, openDeliveryCall, type OpenDeliveryDialect } from "./client";
6
+
7
+ /**
8
+ * The MERCHANT half every Open Delivery adapter shares: the menu part of the
9
+ * `Merchant` document the host serves (`GET /v1/merchant`, PULL: FUT-4768),
10
+ * the `merchantUpdate` notification, and the store pause built on it
11
+ * (FUT-4851). Where a marketplace puts `merchantUpdate` and what it sends
12
+ * with it is its adapter folder's.
13
+ *
14
+ * Every id in the document is a UUID the software generates (the standard's
15
+ * `format: uuid`), derived from the publication's stable reference, so the
16
+ * same product keeps the same ids across pulls.
17
+ */
18
+
19
+ /** One category per host category name, in first-seen order. */
20
+ function categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {
21
+ const byName = new Map<string, { id: string; name: string; offers: string[] }>();
22
+ for (const entry of entries) {
23
+ const name = entry.categoryName.trim();
24
+ const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };
25
+ category.offers.push(stableUuid(`${entry.ref}:offer`));
26
+ byName.set(name, category);
27
+ }
28
+ return [...byName.values()];
29
+ }
30
+
31
+ /**
32
+ * The menu part of Open Delivery's `Merchant`: `menus`, `categories`,
33
+ * `items`, `itemOffers` (the price lives on the offer). Every item is a unit
34
+ * (`UN`) with a status, and every offer states `originalValue`: what both
35
+ * v1.7.1 and Keeta's v1.5.0 require.
36
+ */
37
+ export function openDeliveryMenuDocument(input: {
38
+ externalMerchantId: string;
39
+ entries: readonly CatalogueMenuEntry[];
40
+ options: CatalogueMenuOptions;
41
+ }) {
42
+ const { externalMerchantId: merchantId, entries, options } = input;
43
+ const categories = categoriesOf(merchantId, entries);
44
+ return {
45
+ menus: [
46
+ {
47
+ id: stableUuid(`${merchantId}:menu`),
48
+ name: options.menuName,
49
+ externalCode: "menu",
50
+ categoryId: categories.map((category) => category.id),
51
+ },
52
+ ],
53
+ categories: categories.map((category, index) => ({
54
+ id: category.id,
55
+ index,
56
+ name: category.name,
57
+ externalCode: category.name,
58
+ status: "AVAILABLE",
59
+ itemOfferId: category.offers,
60
+ })),
61
+ items: entries.map((entry) => ({
62
+ id: stableUuid(`${entry.ref}:item`),
63
+ name: entry.name,
64
+ description: entry.description ?? "",
65
+ externalCode: entry.productId,
66
+ status: "AVAILABLE",
67
+ unit: "UN",
68
+ ...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),
69
+ })),
70
+ itemOffers: entries.map((entry, index) => {
71
+ const value = Math.round(entry.priceCents) / 100;
72
+ return {
73
+ id: stableUuid(`${entry.ref}:offer`),
74
+ itemId: stableUuid(`${entry.ref}:item`),
75
+ index,
76
+ status: "AVAILABLE",
77
+ price: { value, originalValue: value, currency: options.currency },
78
+ };
79
+ }),
80
+ };
81
+ }
82
+
83
+ /** One `merchantUpdate` call, where and with what the marketplace takes it. */
84
+ interface OpenDeliveryMerchantUpdate {
85
+ /** From the base: `/v1/merchantUpdate`, or a marketplace's own (Keeta's names the merchant). */
86
+ path: string;
87
+ /** Absent: the empty body that means "pull the whole merchant again". */
88
+ body?: unknown;
89
+ headers?: Readonly<Record<string, string>>;
90
+ }
91
+
92
+ /** `POST {merchantUpdate}`: 2xx accepted (the standard answers 204, 200 "for compatibility"). */
93
+ export function openDeliveryMerchantUpdate(
94
+ ctx: AdapterCallContext,
95
+ dialect: OpenDeliveryDialect,
96
+ update: OpenDeliveryMerchantUpdate,
97
+ ): Promise<OutboundResult> {
98
+ return answered(async () => {
99
+ const response = await openDeliveryCall(ctx, dialect, {
100
+ method: "POST",
101
+ path: update.path,
102
+ ...(update.body === undefined ? {} : { body: update.body }),
103
+ ...(update.headers === undefined ? {} : { headers: update.headers }),
104
+ });
105
+ return isStop(response) ? response : outboundResultOf(response);
106
+ });
107
+ }
108
+
109
+ /**
110
+ * The store pause on `merchantUpdate`'s `merchantStatus` (`AVAILABLE` /
111
+ * `UNAVAILABLE`): a SWITCH, with no id and no end ("you don't know when the
112
+ * service will be re-established"), so an adapter offers it only when its
113
+ * host opts in (see `../core/pause-port.ts`).
114
+ */
115
+ export function openDeliverySwitchAvailability(
116
+ setStatus: (ctx: AdapterCallContext, merchantId: string, status: "AVAILABLE" | "UNAVAILABLE") => Promise<OutboundResult>,
117
+ ): MarketplaceAvailability {
118
+ return {
119
+ kind: "switch",
120
+ pause: async (ctx, request) => {
121
+ const result = await setStatus(ctx, request.merchantId, "UNAVAILABLE");
122
+ return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
123
+ },
124
+ resume: (ctx, ref) => setStatus(ctx, ref.merchantId, "AVAILABLE"),
125
+ };
126
+ }