@12-apps/marketplace 1.13.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +258 -3
- package/README.md +27 -2
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +3 -3
- package/dist/{adapter-CQ4QiZPi.d.ts → adapter-CjVdMhZ2.d.ts} +177 -4
- package/dist/{chunk-CEWTV2TC.js → chunk-B4DYPQFE.js} +657 -251
- package/dist/chunk-B4DYPQFE.js.map +1 -0
- package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
- package/dist/chunk-BTKVZAJI.js.map +1 -0
- package/dist/{chunk-BD7DS3XM.js → chunk-E4XJXHUK.js} +20 -1
- package/dist/chunk-E4XJXHUK.js.map +1 -0
- package/dist/{chunk-W57TITU4.js → chunk-FQI56NGC.js} +53 -6
- package/dist/chunk-FQI56NGC.js.map +1 -0
- package/dist/chunk-H2VQRD3B.js +16 -0
- package/dist/chunk-H2VQRD3B.js.map +1 -0
- package/dist/{chunk-NFJQQWG4.js → chunk-TRUK5ZBE.js} +12 -4
- package/dist/chunk-TRUK5ZBE.js.map +1 -0
- package/dist/{client-CCSnylou.d.ts → client-DgzCkl8u.d.ts} +1 -1
- package/dist/{engine-1KlJ_8jK.d.ts → engine-BSLdhAGC.d.ts} +134 -3
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -2
- package/dist/hono/index.js.map +1 -1
- package/dist/ifood/index.d.ts +13 -3
- package/dist/ifood/index.js +219 -29
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +29 -5
- package/dist/index.js +59 -7
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +3 -3
- package/dist/manifest/server.d.ts +4 -2
- package/dist/manifest/server.js +3 -2
- package/dist/manifest/server.js.map +1 -1
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +2 -2
- package/dist/server/index.d.ts +14 -5
- package/dist/server/index.js +3 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +17 -3
- package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
- package/src/core/acceptance.ts +12 -6
- package/src/core/acknowledge.ts +189 -0
- package/src/core/adapter.ts +74 -1
- package/src/core/cancellation.ts +10 -6
- package/src/core/conformity.ts +63 -0
- package/src/core/engine.ts +3 -2
- package/src/core/ingest.ts +7 -0
- package/src/core/link-store.ts +2 -4
- package/src/core/marketplace-confirmed.ts +229 -0
- package/src/core/order-reasons.ts +119 -0
- package/src/core/order-types.ts +8 -0
- package/src/core/outbound.ts +5 -1
- package/src/core/payload-read.ts +24 -0
- package/src/core/pipeline.ts +27 -1
- package/src/core/ports.ts +2 -0
- package/src/core/registry.ts +28 -2
- package/src/core/state.ts +10 -0
- package/src/core/status-job.ts +86 -3
- package/src/core/types.ts +117 -2
- package/src/ifood/index.ts +27 -4
- package/src/ifood/normalize.ts +38 -5
- package/src/ifood/order-details.ts +120 -0
- package/src/ifood/outbound.ts +131 -27
- package/src/index.ts +24 -0
- package/src/open-delivery/normalize.ts +9 -0
- package/src/server/jobs.ts +57 -4
- package/src/server/webhook.ts +27 -4
- package/dist/chunk-4J2KJ3ZW.js.map +0 -1
- package/dist/chunk-BD7DS3XM.js.map +0 -1
- package/dist/chunk-CEWTV2TC.js.map +0 -1
- package/dist/chunk-NFJQQWG4.js.map +0 -1
- package/dist/chunk-W57TITU4.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n /**\n * OPTIONAL. The HTTP status a recorded delivery is answered with (FUT-5984:\n * iFood wants `202 Accepted`). Absent: 200. Refusals and failures keep theirs.\n */\n webhookAnswerStatus?: 200 | 202;\n /**\n * OPTIONAL. The marketplace announces that the store accepted an order in the\n * marketplace's own app (`NormalizedEvent.marketplaceConfirmed`, FUT-5653).\n * Its ingest then applies a confirmation that arrived before the order.\n */\n marketplaceConfirms?: boolean;\n /**\n * OPTIONAL. A status step is told only after the marketplace took the\n * store's confirm (`confirmedAt`, FUT-5673: iFood refuses a step of an order\n * it has not confirmed). Absent: steps never wait on the confirm.\n */\n statusAfterConfirm?: boolean;\n}\n\n/**\n * A marketplace's presence heartbeat (FUT-5984: iFood's `KEEPALIVE`), read off\n * a delivery: `merchantIds` when it asks about named merchants (its\n * per-merchant mode), null when it asks about the whole app.\n */\nexport interface PresenceProbe {\n merchantIds: readonly string[] | null;\n}\n\n/** Acknowledging recorded events to the marketplace (FUT-5984: iFood's `events/acknowledgment`). */\nexport interface MarketplaceAcknowledgement {\n /** At most this many event ids per call. */\n batchSize: number;\n /** How long the marketplace keeps an event: an older one is never acknowledged. */\n retentionMs: number;\n /** Acknowledge these event ids, in one call. */\n send(ctx: AdapterCallContext, eventIds: readonly string[]): Promise<OutboundResult>;\n}\n\n/** One cancellation reason the marketplace lists for one order: its code and its own words. */\nexport interface OrderCancellationReason {\n code: string;\n description: string;\n}\n\n/** One order's reasons read from the marketplace, or the refusal / retry of the read. */\nexport type OrderCancellationReasonsResult =\n | { kind: \"reasons\"; reasons: OrderCancellationReason[] }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /**\n * The marketplace's documented reasons, static and offline: a dialog never\n * waits on the network. With `orderCancellationReasons`, the fallback of an\n * order whose own list could not be read.\n */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. The step that must be told before this one for this kind of\n * order (FUT-5984: iFood's dispatch of a merchant bag follows its\n * `readyToPickup`), or null. The status job sends it first when it is not\n * told yet.\n */\n statusPrerequisite?(facts: StatusFacts): StatusStep | null;\n /**\n * OPTIONAL. A delivery that is the marketplace's presence heartbeat, not an\n * event (FUT-5984: iFood's `KEEPALIVE`), or null. Answered 202 once its\n * signature is proved, with nothing recorded.\n */\n presence?(payload: unknown): PresenceProbe | null;\n /** OPTIONAL. Acknowledging recorded events (FUT-5984). Absent: nothing is acknowledged. */\n readonly acknowledgement?: MarketplaceAcknowledgement;\n /**\n * OPTIONAL. Read the reasons the marketplace accepts for cancelling THIS\n * order (FUT-5984: iFood's `GET /orders/{id}/cancellationReasons`). Called\n * only from the `marketplace.cancellation-reasons` job. Absent: the static\n * `cancellationReasons()` are every order's.\n */\n orderCancellationReasons?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<OrderCancellationReasonsResult>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order leaves it out. A final `refused` marked `own` with a 4xx status is\n * our credentials refused: the engine stamps the connection FAILED.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /**\n * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check\n * and the tracking read. Absent: neither is offered, and the host says so.\n */\n readonly courier?: MarketplaceCourierApi;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAkWA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
|
|
@@ -41,6 +41,24 @@ function firstCents(source, paths) {
|
|
|
41
41
|
return null;
|
|
42
42
|
}
|
|
43
43
|
__name(firstCents, "firstCents");
|
|
44
|
+
function toTaxId(value) {
|
|
45
|
+
if (typeof value === "number") {
|
|
46
|
+
if (!Number.isSafeInteger(value) || value <= 0) return null;
|
|
47
|
+
const digits2 = String(value);
|
|
48
|
+
return digits2.padStart(digits2.length <= 11 ? 11 : 14, "0");
|
|
49
|
+
}
|
|
50
|
+
const digits = asString(value)?.replace(/\D/g, "");
|
|
51
|
+
return digits ? digits : null;
|
|
52
|
+
}
|
|
53
|
+
__name(toTaxId, "toTaxId");
|
|
54
|
+
function firstTaxId(source, paths) {
|
|
55
|
+
for (const path of paths) {
|
|
56
|
+
const found = toTaxId(pick(source, ...path));
|
|
57
|
+
if (found !== null) return found;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
__name(firstTaxId, "firstTaxId");
|
|
44
62
|
function toDate(value) {
|
|
45
63
|
const raw = asString(value);
|
|
46
64
|
if (!raw) return null;
|
|
@@ -72,7 +90,8 @@ export {
|
|
|
72
90
|
firstString,
|
|
73
91
|
toCents,
|
|
74
92
|
firstCents,
|
|
93
|
+
firstTaxId,
|
|
75
94
|
firstDate,
|
|
76
95
|
verifyHmacSha256Hex
|
|
77
96
|
};
|
|
78
|
-
//# sourceMappingURL=chunk-
|
|
97
|
+
//# sourceMappingURL=chunk-E4XJXHUK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/payload-read.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * The defensive readers every adapter's normalizer is built from.\n *\n * A marketplace payload is UNTRUSTED: a documented shape and the shape that\n * actually arrives drift, and a `TypeError` reading a missing field would\n * reject a paid order at the door. Every reader here produces a value or\n * null, never a throw. They are wire-format-neutral (no marketplace's key\n * names), which is why they live beside the engine rather than in an adapter.\n */\n\n/** Read a nested value without asserting the shape of anything on the way. */\nexport function pick(source: unknown, ...path: string[]): unknown {\n let cursor: unknown = source;\n for (const key of path) {\n if (typeof cursor !== \"object\" || cursor === null) return undefined;\n cursor = (cursor as Record<string, unknown>)[key];\n }\n return cursor;\n}\n\n/** A non-blank string (trimmed), a finite number as text, or null. */\nexport function asString(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim() !== \"\") return value.trim();\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return null;\n}\n\n/**\n * The first of several candidate paths that yields a string.\n *\n * A marketplace states the same fact under different keys depending on which\n * API version delivered it, so nearly every read is a fallback chain. Expressed\n * as data rather than as `??` so a chain grows by one entry, not one branch.\n */\nexport function firstString(source: unknown, paths: string[][]): string | null {\n for (const path of paths) {\n const found = asString(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * Money stated in DECIMAL units (`12.9`) → integer cents.\n *\n * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,\n * so truncation loses a cent on ordinary prices, always in the store's\n * disfavour.\n */\nexport function toCents(value: unknown): number | null {\n const numeric = typeof value === \"string\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(numeric * 100);\n}\n\n/** {@link firstString} for money. */\nexport function firstCents(source: unknown, paths: string[][]): number | null {\n for (const path of paths) {\n const found = toCents(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * A CPF or CNPJ → its digits, or null. Text keeps its digits (`123.456.789-09`).\n * A number lost its leading zeros on the way, so it is padded back to a CPF's\n * 11 digits, or a CNPJ's 14 when it is longer than a CPF.\n */\nfunction toTaxId(value: unknown): string | null {\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value <= 0) return null;\n const digits = String(value);\n return digits.padStart(digits.length <= 11 ? 11 : 14, \"0\");\n }\n const digits = asString(value)?.replace(/\\D/g, \"\");\n return digits ? digits : null;\n}\n\n/** {@link firstString} for a tax id (CPF or CNPJ), digits only. */\nexport function firstTaxId(source: unknown, paths: string[][]): string | null {\n for (const path of paths) {\n const found = toTaxId(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/** An ISO timestamp → a Date, or null when absent or unparseable. */\nfunction toDate(value: unknown): Date | null {\n const raw = asString(value);\n if (!raw) return null;\n const parsed = new Date(raw);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n}\n\n/** {@link firstString} for timestamps. */\nexport function firstDate(source: unknown, paths: string[][]): Date | null {\n for (const path of paths) {\n const found = toDate(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * Verify a lowercase-hex HMAC-SHA256 of the raw body (an optional `sha256=`\n * prefix tolerated), keyed by `secret`.\n *\n * Unsigned deliveries are refused whenever a secret is CONFIGURED; a store\n * that has not set one yet is accepted, and that state is visible on the\n * connection screen rather than silent. Compared in constant time over bytes:\n * an early-exit `===` on a hex digest leaks the prefix a forger already got\n * right, one request at a time.\n */\nexport function verifyHmacSha256Hex(rawBody: string, signature: string | null, secret: string | null): boolean {\n if (!secret) return true;\n if (!signature) return false;\n const expected = createHmac(\"sha256\", secret).update(rawBody, \"utf8\").digest(\"hex\");\n const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, \"\"), \"utf8\");\n const mine = Buffer.from(expected, \"utf8\");\n return given.length === mine.length && timingSafeEqual(given, mine);\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY,uBAAuB;AAarC,SAAS,KAAK,WAAoB,MAAyB;AAChE,MAAI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,QAAiB,OAAkC;AAC5E,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,QAAQ,KAAK,QAAQ,GAAG,IAAI,CAAC;AAC3C,QAAI,UAAU,KAAM,QAAO;AAAA,EAC7B;AACA,SAAO;AACT;AANgB;AAShB,SAAS,OAAO,OAA6B;AAC3C,QAAM,MAAM,SAAS,KAAK;AAC1B,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,SAAS,IAAI,KAAK,GAAG;AAC3B,SAAO,OAAO,MAAM,OAAO,QAAQ,CAAC,IAAI,OAAO;AACjD;AALS;AAQF,SAAS,UAAU,QAAiB,OAAgC;AACzE,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,OAAO,KAAK,QAAQ,GAAG,IAAI,CAAC;AAC1C,QAAI,UAAU,KAAM,QAAO;AAAA,EAC7B;AACA,SAAO;AACT;AANgB;AAkBT,SAAS,oBAAoB,SAAiB,WAA0B,QAAgC;AAC7G,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,WAAW,WAAW,UAAU,MAAM,EAAE,OAAO,SAAS,MAAM,EAAE,OAAO,KAAK;AAClF,QAAM,QAAQ,OAAO,KAAK,UAAU,KAAK,EAAE,YAAY,EAAE,QAAQ,aAAa,EAAE,GAAG,MAAM;AACzF,QAAM,OAAO,OAAO,KAAK,UAAU,MAAM;AACzC,SAAO,MAAM,WAAW,KAAK,UAAU,gBAAgB,OAAO,IAAI;AACpE;AAPgB;","names":["digits"]}
|
|
@@ -14,11 +14,13 @@ import {
|
|
|
14
14
|
upsertMarketplaceMenuLinksBody
|
|
15
15
|
} from "./chunk-SGOTN5PX.js";
|
|
16
16
|
import {
|
|
17
|
+
AcknowledgeRetryError,
|
|
17
18
|
AvailabilityRetryError,
|
|
19
|
+
CancellationReasonsRetryError,
|
|
18
20
|
CatalogueRetryError,
|
|
19
21
|
FetchOrderRetryError,
|
|
20
22
|
OutboundRetryError
|
|
21
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-B4DYPQFE.js";
|
|
22
24
|
import {
|
|
23
25
|
__name
|
|
24
26
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -209,13 +211,20 @@ async function handleWebhook(config, request) {
|
|
|
209
211
|
return deliverAdmitted(config, admitted);
|
|
210
212
|
}
|
|
211
213
|
__name(handleWebhook, "handleWebhook");
|
|
214
|
+
function presenceAnswer(probe) {
|
|
215
|
+
return probe.merchantIds === null ? { status: 202, body: { received: true } } : { status: 202, body: { merchantIds: [...probe.merchantIds] } };
|
|
216
|
+
}
|
|
217
|
+
__name(presenceAnswer, "presenceAnswer");
|
|
212
218
|
async function deliverAdmitted(config, admitted) {
|
|
213
219
|
const { clientId, provider, payload, target } = admitted;
|
|
214
220
|
const { engine } = config;
|
|
221
|
+
const probe = engine.presence(provider, payload);
|
|
222
|
+
if (probe) return presenceAnswer(probe);
|
|
223
|
+
const status = engine.answerStatus(provider);
|
|
215
224
|
const event = engine.normalize(provider, payload);
|
|
216
225
|
if (!event) {
|
|
217
226
|
config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);
|
|
218
|
-
return { status
|
|
227
|
+
return { status, body: { received: true, ignored: "unrecognized_payload" } };
|
|
219
228
|
}
|
|
220
229
|
const outcome = await engine.deliver({
|
|
221
230
|
clientId,
|
|
@@ -228,7 +237,7 @@ async function deliverAdmitted(config, admitted) {
|
|
|
228
237
|
if (outcome.kind === "failed") {
|
|
229
238
|
return { status: 500, body: { received: true, error: outcome.reason } };
|
|
230
239
|
}
|
|
231
|
-
return { status
|
|
240
|
+
return { status, body: { received: true, outcome: outcome.kind } };
|
|
232
241
|
}
|
|
233
242
|
__name(deliverAdmitted, "deliverAdmitted");
|
|
234
243
|
async function admitApp(config, request) {
|
|
@@ -239,6 +248,11 @@ async function admitApp(config, request) {
|
|
|
239
248
|
const rawBody = await raw.text();
|
|
240
249
|
const payload = parsedJson(rawBody);
|
|
241
250
|
if (payload === void 0) return { status: 400, body: { error: "invalid_json" } };
|
|
251
|
+
const probe = config.engine.presence(provider, payload);
|
|
252
|
+
if (probe) {
|
|
253
|
+
const signature2 = config.engine.readSignature(provider, (name) => raw.headers.get(name));
|
|
254
|
+
return await config.engine.signedByApp(provider, rawBody, signature2) ? presenceAnswer(probe) : UNAUTHORIZED;
|
|
255
|
+
}
|
|
242
256
|
const found = await appConnection(config, provider, payload);
|
|
243
257
|
if ("status" in found) return found;
|
|
244
258
|
const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
|
|
@@ -500,9 +514,10 @@ var reconcileInbox = {
|
|
|
500
514
|
const outcome = await deps.engine.reprocess(event);
|
|
501
515
|
if (outcome.kind === "ingested") ingested += 1;
|
|
502
516
|
}
|
|
503
|
-
|
|
517
|
+
const { requeued } = await deps.engine.sweepAcknowledgements();
|
|
518
|
+
if (pending.length === 0 && requeued === 0) return;
|
|
504
519
|
context.logger.info(
|
|
505
|
-
`marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s).`
|
|
520
|
+
`marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s); re-queued the acknowledgment of ${requeued} store(s).`
|
|
506
521
|
);
|
|
507
522
|
}, "handle")
|
|
508
523
|
};
|
|
@@ -546,6 +561,36 @@ var fetchOrder = {
|
|
|
546
561
|
}
|
|
547
562
|
}, "handle")
|
|
548
563
|
};
|
|
564
|
+
var MARKETPLACE_ACKNOWLEDGE_ATTEMPTS = 3;
|
|
565
|
+
var acknowledge = {
|
|
566
|
+
name: "acknowledge",
|
|
567
|
+
attempts: MARKETPLACE_ACKNOWLEDGE_ATTEMPTS,
|
|
568
|
+
backoff: { type: "exponential", delayMs: 1e4 },
|
|
569
|
+
handle: /* @__PURE__ */ __name(async (payload, deps, context) => {
|
|
570
|
+
try {
|
|
571
|
+
const outcome = await deps.engine.runAcknowledge(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });
|
|
572
|
+
if (outcome.kind === "skipped") context.logger.info(`marketplace.acknowledge: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);
|
|
573
|
+
} catch (error) {
|
|
574
|
+
if (error instanceof AcknowledgeRetryError) context.logger.warn(`marketplace.acknowledge: ${error.message}`);
|
|
575
|
+
throw error;
|
|
576
|
+
}
|
|
577
|
+
}, "handle")
|
|
578
|
+
};
|
|
579
|
+
var MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS = 3;
|
|
580
|
+
var cancellationReasons = {
|
|
581
|
+
name: "cancellation-reasons",
|
|
582
|
+
attempts: MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS,
|
|
583
|
+
backoff: { type: "exponential", delayMs: 1e4 },
|
|
584
|
+
handle: /* @__PURE__ */ __name(async (payload, deps, context) => {
|
|
585
|
+
try {
|
|
586
|
+
const outcome = await deps.engine.runCancellationReasons(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });
|
|
587
|
+
if (outcome.kind === "skipped") context.logger.info(`marketplace.cancellation-reasons: ${payload.orderId} skipped: ${outcome.reason}`);
|
|
588
|
+
} catch (error) {
|
|
589
|
+
if (error instanceof CancellationReasonsRetryError) context.logger.warn(`marketplace.cancellation-reasons: ${error.message}`);
|
|
590
|
+
throw error;
|
|
591
|
+
}
|
|
592
|
+
}, "handle")
|
|
593
|
+
};
|
|
549
594
|
var MARKETPLACE_CATALOGUE_ATTEMPTS = 3;
|
|
550
595
|
var catalogue = {
|
|
551
596
|
name: "catalogue",
|
|
@@ -626,6 +671,8 @@ var MARKETPLACE_JOBS = {
|
|
|
626
671
|
"reconcile-inbox": reconcileInbox,
|
|
627
672
|
outbound,
|
|
628
673
|
"fetch-order": fetchOrder,
|
|
674
|
+
acknowledge,
|
|
675
|
+
"cancellation-reasons": cancellationReasons,
|
|
629
676
|
catalogue,
|
|
630
677
|
"outbound-sweep": outboundSweep,
|
|
631
678
|
availability,
|
|
@@ -651,4 +698,4 @@ export {
|
|
|
651
698
|
MARKETPLACE_JOBS,
|
|
652
699
|
createApiMarketplace
|
|
653
700
|
};
|
|
654
|
-
//# sourceMappingURL=chunk-
|
|
701
|
+
//# sourceMappingURL=chunk-FQI56NGC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/http.ts","../src/server/link-routes.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { LinkFailure, LinkPendingView, LinkRefusalCode } from \"../core/linking\";\nimport { MARKETPLACE_MANAGE } from \"./contribution\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport { finishLinkBody, linkMerchantsQuery, linkStateQuery, selectLinkMerchantBody, startLinkBody } from \"./mcp-link\";\n\n/**\n * Linking a store through the software's own marketplace app (FUT-5613), as\n * HTTP, beside the connection routes and behind the same permission:\n *\n * - `GET …/marketplace/link?provider=` — whether linking is available, and the code in progress;\n * - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);\n * - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;\n * - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;\n * - `PUT …/marketplace/link/merchant` — which of them this store is.\n *\n * No answer ever carries a token, a verifier or the app's credentials.\n */\n\nconst BASE = \"/admin/:tenantSlug/marketplace/link\";\n\n/** The HTTP status each refusal answers. */\nconst STATUS: Readonly<Record<LinkRefusalCode, number>> = {\n UNAVAILABLE: 409,\n NO_LINK_IN_PROGRESS: 409,\n LINK_EXPIRED: 409,\n CODE_REFUSED: 422,\n MARKETPLACE_REFUSED: 502,\n NOT_LINKED: 409,\n UNKNOWN_MERCHANT: 422,\n MERCHANT_TAKEN: 409,\n};\n\n/** A failure as the routes answer it: the host's sentence, the code, and the marketplace's own words. */\nfunction failed(config: MarketplaceApiConfig, failure: LinkFailure): WireResponse {\n const words = config.copy.link;\n if (failure.kind === \"retry\") {\n return refuse(503, words?.tryAgain ?? \"MARKETPLACE_UNREACHABLE\", { code: \"MARKETPLACE_UNREACHABLE\" });\n }\n return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {\n code: failure.code,\n ...(failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }),\n });\n}\n\nconst pendingOut = (pending: LinkPendingView | null) => (pending ? { ...pending, expiresAt: pending.expiresAt.toISOString() } : null);\n\nfunction connectionOut(row: MarketplaceIntegrationView) {\n return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };\n}\n\n/** An unknown provider, before anything is asked of the engine. */\nfunction unknown(config: MarketplaceApiConfig, id: string): WireResponse | null {\n return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: \"UNKNOWN_PROVIDER\" });\n}\n\nfunction readRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(linkStateQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });\n return ok({ available: state.available, pending: pendingOut(state.pending) });\n },\n },\n {\n method: \"GET\",\n path: `${BASE}/merchants`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(linkMerchantsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });\n return result.kind === \"listed\" ? ok(result.merchants) : failed(config, result);\n },\n },\n ];\n}\n\nfunction writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"POST\",\n path: `${BASE}/start`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(startLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });\n return result.kind === \"started\" ? ok(pendingOut(result.pending)) : failed(config, result);\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/finish`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(finishLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });\n if (result.kind !== \"linked\") return failed(config, result);\n return ok({ integration: connectionOut(result.integration), merchants: result.merchants });\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/merchant`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(selectLinkMerchantBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, ...parsed.value });\n return result.kind === \"selected\" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);\n },\n },\n ];\n}\n\n/** The linking routes, in mount order. */\nexport function linkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n return [...readRoutes(config), ...writeRoutes(config)];\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { PresenceProbe } from \"../core/adapter\";\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately: 200, or the status the\n * adapter states (`webhookAnswerStatus`: iFood's 202, FUT-5984). A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\ninterface Admitted {\n clientId: string;\n provider: string;\n payload: unknown;\n target: IngestionTarget;\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n return deliverAdmitted(config, admitted);\n}\n\n/**\n * The answer to a proven presence heartbeat (FUT-5984, iFood's `KEEPALIVE`):\n * 202, and in the per-merchant mode every merchant it asked about named\n * online. Nothing is recorded.\n */\nfunction presenceAnswer(probe: PresenceProbe): WireResponse {\n return probe.merchantIds === null\n ? { status: 202, body: { received: true } }\n : { status: 202, body: { merchantIds: [...probe.merchantIds] } };\n}\n\n/** Record and act on a delivery whose store and signature are proven. */\nasync function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n const probe = engine.presence(provider, payload);\n if (probe) return presenceAnswer(probe);\n const status = engine.answerStatus(provider);\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 2xx: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled\n ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus }\n : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n // After the inbox row is written: iFood's 202 means \"recorded\" (FUT-5984).\n return { status, body: { received: true, outcome: outcome.kind } };\n}\n\n/**\n * The store a delivery to the APP's single address belongs to, and its\n * connection: resolved from the merchant the payload names, then proved by\n * the signature (FUT-5613). The payload is read before it is verified only to\n * find whose key verifies it; nothing of it is acted on until it is.\n */\nasync function admitApp(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<Admitted | WireResponse> {\n const { provider = \"\" } = request.params;\n if (!config.engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n const rawBody = await raw.text();\n const payload = parsedJson(rawBody);\n if (payload === undefined) return { status: 400, body: { error: \"invalid_json\" } };\n // A presence heartbeat names no store: proved by the app's own key, with no statement (FUT-5984).\n const probe = config.engine.presence(provider, payload);\n if (probe) {\n const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));\n return (await config.engine.signedByApp(provider, rawBody, signature)) ? presenceAnswer(probe) : UNAUTHORIZED;\n }\n const found = await appConnection(config, provider, payload);\n if (\"status\" in found) return found;\n // The app's address never takes an unsigned delivery, whatever the store's own setting.\n const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));\n const secret = found.target.webhookSecret;\n if (!secret || !config.engine.verifySignature(provider, rawBody, signature, secret)) {\n config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);\n return UNAUTHORIZED;\n }\n return { ...found, provider, payload };\n}\n\n/** A JSON body, or undefined when it is not JSON. */\nfunction parsedJson(rawBody: string): unknown {\n try {\n return JSON.parse(rawBody) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** The store whose live connection holds the merchant a delivery names, or the 401. */\nasync function appConnection(\n config: MarketplaceApiConfig,\n provider: string,\n payload: unknown,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;\n const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);\n if (!clientId) return UNAUTHORIZED;\n try {\n const target = await config.engine.target(clientId, provider);\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(`marketplace.webhook: app ${provider} key of ${clientId} unavailable: ${String(error)}`);\n return UNAUTHORIZED;\n }\n}\n\n/**\n * `POST /webhooks/marketplace/:provider` — the ONE address the software's own\n * app registers with a marketplace, for every store linked through it\n * (FUT-5613). The store is found by the merchant id the delivery names, and\n * the delivery must carry a valid signature: unsigned is refused here.\n */\nexport function appWebhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:provider\",\n kind: \"webhook\",\n handle: async (request) => {\n const admitted = await admitApp(config, request);\n return \"status\" in admitted ? admitted : deliverAdmitted(config, admitted);\n },\n };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { linkRoutes } from \"./link-routes\";\nimport { appWebhookRoute, webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? (problem.code === \"MERCHANT_TAKEN\" ? (copy.link?.problems.MERCHANT_TAKEN ?? problem.code) : copy.problems[problem.code]),\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n appWebhookRoute(config),\n ...integrationRoutes(config),\n ...linkRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { AcknowledgeRetryError, type AcknowledgeJobPayload } from \"../core/acknowledge\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { CancellationReasonsRetryError, type CancellationReasonsJobPayload } from \"../core/order-reasons\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\nimport { AvailabilityRetryError } from \"../core/pause-job\";\nimport type { AvailabilityJobPayload } from \"../core/pause-store\";\n\n/**\n * The engine's ten jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `fetch-order`, on demand: one GET of an order a marketplace's event only\n * announced (`orderToFetch`), then the one ingest path. Three attempts with\n * backoff; the reconciliation sweep re-queues a row still owed.\n * - `acknowledge`, on demand: tells the marketplace a store's recorded events\n * were received (FUT-5984, iFood). Three attempts with backoff; the\n * reconcile pass re-queues a store still owing some.\n * - `cancellation-reasons`, on demand: reads one order's own cancellation\n * reasons once, after its ingest (FUT-5984, iFood). Three attempts; the\n * static list stays the fallback.\n * - `catalogue`, on demand: one publish or withdraw of one product on one\n * marketplace's catalogue (FUT-4768). Three attempts with backoff; the\n * last one stamps FAILED with a failure code.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp, a catalogue\n * publish or withdraw on its way) once it is older than the job's own retry\n * span, so a refused enqueue or a dead process loses nothing.\n * - `availability`, on demand: brings one marketplace in line with the host's\n * last pause or resume ask for one store (FUT-4851). Three attempts with\n * backoff; the last one stamps FAILED with a failure code.\n * - `availability-sweep`, every five minutes: resumes a pause past its\n * `until` (the host stopped renewing it), re-queues an ask still owed, and\n * gives up on one older than a day.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.acknowledge`,\n * `marketplace.cancellation-reasons`, `marketplace.catalogue`,\n * `marketplace.outbound-sweep`, `marketplace.availability` and\n * `marketplace.availability-sweep`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<\n MarketplaceEngine,\n | \"expireLapsed\"\n | \"retryable\"\n | \"reprocess\"\n | \"runOutbound\"\n | \"runFetchOrder\"\n | \"runAcknowledge\"\n | \"sweepAcknowledgements\"\n | \"runCancellationReasons\"\n | \"runCatalogue\"\n | \"sweepOutbound\"\n | \"runAvailability\"\n | \"sweepAvailability\"\n >;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n // The events still owed an acknowledgment are re-queued, one job per store (FUT-5984).\n const { requeued } = await deps.engine.sweepAcknowledgements();\n if (pending.length === 0 && requeued === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s); ` +\n `re-queued the acknowledgment of ${requeued} store(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The fetch job's attempts: the last one settles the inbox row FAILED. */\nexport const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;\n\nconst fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {\n name: \"fetch-order\",\n attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n // Short: an order waiting for its body is on the store's acceptance clock.\n backoff: { type: \"exponential\", delayMs: 5_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runFetchOrder(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The acknowledgment's attempts: the last one leaves the events owed, for the reconcile pass. */\nconst MARKETPLACE_ACKNOWLEDGE_ATTEMPTS = 3;\n\nconst acknowledge: WireJobBlueprint<AcknowledgeJobPayload, MarketplaceJobDeps> = {\n name: \"acknowledge\",\n attempts: MARKETPLACE_ACKNOWLEDGE_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAcknowledge(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.acknowledge: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof AcknowledgeRetryError) context.logger.warn(`marketplace.acknowledge: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The reasons read's attempts: the last one leaves the static list in place. */\nconst MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS = 3;\n\nconst cancellationReasons: WireJobBlueprint<CancellationReasonsJobPayload, MarketplaceJobDeps> = {\n name: \"cancellation-reasons\",\n attempts: MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCancellationReasons(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.cancellation-reasons: ${payload.orderId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof CancellationReasonsRetryError) context.logger.warn(`marketplace.cancellation-reasons: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The catalogue job's attempts: the last one stamps FAILED. */\nconst MARKETPLACE_CATALOGUE_ATTEMPTS = 3;\n\nconst catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {\n name: \"catalogue\",\n attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,\n // Short: a person is watching the switch say \"sending\".\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCatalogue(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;\n if (idle) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +\n `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The availability job's attempts: the last one stamps FAILED. */\nexport const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;\n\nconst availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {\n name: \"availability\",\n attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,\n // Short: a store is open on the marketplace while the kitchen is paused.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAvailability(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"availability-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepAvailability();\n if (result.expired + result.requeued + result.givenUp === 0) return;\n context.logger.info(\n `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +\n `gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"fetch-order\": fetchOrder,\n acknowledge,\n \"cancellation-reasons\": cancellationReasons,\n catalogue,\n \"outbound-sweep\": outboundSweep,\n availability,\n \"availability-sweep\": availabilitySweep,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceLinkCopy, MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_AVAILABILITY_ATTEMPTS,\n MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS,OAAO,QAAgB,OAAe,QAAiC,CAAC,GAAiB;AACvG,SAAO,EAAE,QAAQ,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE;AAC7C;AAFgB;AAKT,SAAS,MACd,QACA,OACA,MACgE;AAChE,QAAM,SAAS,OAAO,UAAU,SAAS,CAAC,CAAC;AAC3C,MAAI,OAAO,QAAS,QAAO,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;AAC1D,QAAM,WAAW,OAAO,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,IACnD,MAAM,MAAM,KAAK,IAAI,CAAC,YAAa,OAAO,YAAY,WAAW,UAAU,OAAO,OAAO,CAAE;AAAA,IAC3F,MAAM;AAAA,IACN,SAAS,MAAM;AAAA,EACjB,EAAE;AACF,SAAO,EAAE,IAAI,OAAO,UAAU,OAAO,KAAK,KAAK,cAAc,EAAE,SAAS,CAAC,EAAE;AAC7E;AAbgB;AAgBT,SAAS,IAAI,OAA+C;AACjE,SAAO,QAAQ,MAAM,YAAY,IAAI;AACvC;AAFgB;;;AC1ChB,IAAM,OAAO;AAGb,IAAM,SAAoD;AAAA,EACxD,aAAa;AAAA,EACb,qBAAqB;AAAA,EACrB,cAAc;AAAA,EACd,cAAc;AAAA,EACd,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,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,IACF,SAAS,OAAO;AACd,UAAI,iBAAiB,uBAAwB,SAAQ,OAAO,KAAK,6BAA6B,MAAM,OAAO,EAAE;AAC7G,YAAM;AAAA,IACR;AAAA,EACF,GAbQ;AAcV;AAEA,IAAM,oBAAgE;AAAA,EACpE,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,UAAU,EAAE,SAAS,eAAe,UAAU,MAAM;AAAA,EACpD,UAAU;AAAA,EACV,OAAO,EAAE,OAAO,eAAe;AAAA,EAC/B,QAAQ,8BAAO,UAAU,MAAM,YAAY;AACzC,UAAM,SAAS,MAAM,KAAK,OAAO,kBAAkB;AACnD,QAAI,OAAO,UAAU,OAAO,WAAW,OAAO,YAAY,EAAG;AAC7D,YAAQ,OAAO;AAAA,MACb,2CAA2C,OAAO,OAAO,gCAAgC,OAAO,QAAQ,gBACxF,OAAO,OAAO;AAAA,IAChC;AAAA,EACF,GAPQ;AAQV;AAGO,IAAM,mBAAmB;AAAA,EAC9B,WAAW;AAAA,EACX,YAAY;AAAA,IACV,sBAAsB;AAAA,IACtB,mBAAmB;AAAA,IACnB;AAAA,IACA,eAAe;AAAA,IACf;AAAA,IACA,wBAAwB;AAAA,IACxB;AAAA,IACA,kBAAkB;AAAA,IAClB;AAAA,IACA,sBAAsB;AAAA,EACxB;AACF;;;AC7RO,SAAS,qBAAqB,QAA8C;AACjF,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,kFAAkF;AAAA,EACpG;AACA,SAAO,EAAE,QAAQ,kBAAkB,MAAM,GAAG,QAAQ,OAAO,OAAO;AACpE;AALgB;","names":["signature","BASE"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/core/types.ts
|
|
6
|
+
var PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;
|
|
7
|
+
function normalizedLineTotalCents(line) {
|
|
8
|
+
return line.unitPriceCents * line.quantity + (line.options ?? []).reduce((sum, option) => sum + option.totalCents, 0);
|
|
9
|
+
}
|
|
10
|
+
__name(normalizedLineTotalCents, "normalizedLineTotalCents");
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
PROVIDER_ID_PATTERN,
|
|
14
|
+
normalizedLineTotalCents
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=chunk-H2VQRD3B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts"],"sourcesContent":["/**\n * The canonical shape every marketplace adapter normalizes INTO.\n *\n * This type is the seam. The engine below it knows no marketplace by name: a\n * marketplace is an adapter registered with the engine (`./adapter`), and the\n * provider id is whatever that adapter says it is. A second marketplace is a\n * second adapter, never a second pipeline, a second acceptance clock or a\n * second idea of what an order is.\n *\n * Deliberately POORER than any marketplace's own payload. Everything a store\n * operates on is here; everything else stays in the inbox row's raw `payload`,\n * which is where a normalization bug is reconstructed from.\n */\n\n/**\n * A marketplace's id, as its adapter declares it (`\"IFOOD\"`). Uppercase\n * letters, digits and underscores; the migration's CHECK holds the same shape.\n * A string rather than a closed union, because the set of marketplaces is the\n * set of registered adapters, and a union would make a new one a code change\n * in the engine.\n */\nexport type MarketplaceProvider = string;\n\n/** The shape a provider id must have. Shared by the registry and the CHECK. */\nexport const PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;\n\n/** One line of an incoming order, before it is resolved against the catalog. */\nexport interface NormalizedOrderLine {\n /** The marketplace's own SKU — the key the SKU map is matched on. */\n externalSku: string;\n /** What the marketplace called it. Snapshotted, and the fallback line text. */\n name: string;\n quantity: number;\n /**\n * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A\n * marketplace's menu carries its own prices, and the buyer's receipt is the\n * marketplace's one: re-pricing from the host's catalog would produce a\n * total nobody was charged.\n */\n unitPriceCents: number;\n /** The buyer's note on this line, when they left one. */\n note: string | null;\n /**\n * OPTIONAL (FUT-5803). The options the buyer chose on this line (a\n * complemento: \"borda recheada\", \"sem cebola\"), each priced on its own. When\n * present, `unitPriceCents` is the item ALONE and the line costs\n * `unitPriceCents × quantity + Σ options[].totalCents`\n * ({@link normalizedLineTotalCents}). Absent: none is itemized. Open\n * Delivery and Rappi then fold the options' price into `unitPriceCents`;\n * iFood does not, so an iFood item that states `optionsPrice` but lists no\n * `options[]` is priced as the item alone. Never an empty array.\n */\n options?: NormalizedLineOption[];\n}\n\n/** One option on an order line, as the marketplace priced it (FUT-5803). */\nexport interface NormalizedLineOption {\n /** The marketplace's own code for the option, when it gives one. */\n externalCode: string | null;\n name: string;\n /** The group the marketplace shows it under (\"Borda\", \"Adicionais\"), when it says. */\n groupName: string | null;\n /** How many, for the WHOLE line (never per unit of it). */\n quantity: number;\n unitPriceCents: number;\n /**\n * Always exactly `unitPriceCents × quantity`. A stated price that does not\n * divide by its count arrives as two rows of the same option (the floor,\n * then one unit carrying the remainder), whose counts sum to the stated one.\n */\n totalCents: number;\n}\n\n/** What a line costs: the item times its quantity, plus each of its options. */\nexport function normalizedLineTotalCents(line: Pick<NormalizedOrderLine, \"unitPriceCents\" | \"quantity\" | \"options\">): number {\n return line.unitPriceCents * line.quantity + (line.options ?? []).reduce((sum, option) => sum + option.totalCents, 0);\n}\n\n/** The buyer, as much of them as the marketplace discloses. */\nexport interface NormalizedBuyer {\n /** The marketplace's own stable id for this customer, when it gives one. */\n externalId: string | null;\n name: string | null;\n phone: string | null;\n /**\n * OPTIONAL (FUT-5803). The buyer's tax id for the invoice (a CPF or a CNPJ),\n * digits only. Absent: the marketplace states none.\n */\n document?: string | null;\n /**\n * OPTIONAL (FUT-5803). The extension that reaches the buyer through the\n * marketplace's masked number in `phone` (iFood's `phone.localizer`). Absent: none.\n */\n phoneLocalizer?: string | null;\n}\n\n/** Where a delivery goes, as much of it as the marketplace states. */\nexport interface NormalizedAddress {\n street: string;\n number: string;\n neighborhood: string;\n complement: string | null;\n /** The sentence that finds the door. */\n reference: string | null;\n postalCode: string | null;\n city: string | null;\n state: string | null;\n}\n\n/**\n * How the order reaches the buyer: brought to the door (`DELIVERY`), collected\n * (`TAKEOUT`), eaten at the store (`DINE_IN`), or ordered from inside it, at a\n * table or a spot the buyer names (`INDOOR`, FUT-5803).\n */\nexport type MarketplaceOrderType = \"DELIVERY\" | \"TAKEOUT\" | \"DINE_IN\" | \"INDOOR\";\n\n/** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */\nexport type MarketplaceDeliveredBy = \"MERCHANT\" | \"MARKETPLACE\";\n\n/** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */\nexport type MarketplaceDiscountSponsor = \"MERCHANT\" | \"MARKETPLACE\" | \"OTHER\";\n\n/** One discount on an order, as the part one sponsor pays. */\nexport interface NormalizedOrderDiscount {\n /** The discount's value in the smallest currency unit. */\n cents: number;\n sponsor: MarketplaceDiscountSponsor;\n /** What the marketplace called the campaign, when it says. */\n name?: string;\n}\n\n/**\n * How a buyer paid, as a closed set a host has words for. `OTHER`: stated,\n * and none of these (the marketplace's own word is in `statedMethod`).\n */\nexport type MarketplacePaymentMethod =\n | \"CREDIT\"\n | \"DEBIT\"\n | \"MEAL_VOUCHER\"\n | \"FOOD_VOUCHER\"\n | \"PIX\"\n | \"CASH\"\n | \"DIGITAL_WALLET\"\n | \"OTHER\";\n\n/** One way the buyer pays an order (FUT-5803). */\nexport interface NormalizedPaymentMethod {\n method: MarketplacePaymentMethod;\n /** The marketplace's own word for the method, verbatim; null when it states none. */\n statedMethod: string | null;\n /**\n * True: already paid on the marketplace. False: to collect from the buyer at\n * the door or the counter. Null: unstated.\n */\n prepaid: boolean | null;\n /** What this method pays, in the smallest currency unit. */\n valueCents: number;\n /** The card's brand as the marketplace names it (\"VISA\"), when it does. */\n cardBrand: string | null;\n /** On cash: the note the buyer pays with, so the courier brings the change. Null: no change asked, or unstated. */\n changeForCents: number | null;\n}\n\n/** The order's payment, as the marketplace states it (FUT-5803). */\nexport interface NormalizedPayments {\n /** What the marketplace already collected. Null: unstated. */\n prepaidCents: number | null;\n /** What is still to collect from the buyer. Null: unstated. */\n pendingCents: number | null;\n methods: NormalizedPaymentMethod[];\n}\n\n/** A fee the marketplace charged the buyer besides delivery (FUT-5803), such as a small-order fee. */\nexport interface NormalizedOrderFee {\n /** The marketplace's own kind, verbatim (`SMALL_ORDER_FEE`). */\n kind: string;\n cents: number;\n /** What the marketplace called it, when it says. */\n name?: string;\n}\n\n/** An incoming marketplace order, normalized. */\nexport interface NormalizedMarketplaceOrder {\n provider: MarketplaceProvider;\n /** The marketplace's order id — THE idempotency key for the whole pipeline. */\n externalOrderId: string;\n /** The short code the courier and the buyer say out loud. */\n externalDisplayId: string | null;\n buyer: NormalizedBuyer;\n lines: NormalizedOrderLine[];\n /**\n * What the buyer paid, gross. NOT derived from the lines when the\n * marketplace states it: its total carries fees, promotions and rounding the\n * line sum does not, and the number that must match the receipt is this one.\n */\n totalCents: number;\n /** The marketplace's cut, when it states one. NULL is \"did not say\", not 0. */\n commissionCents: number | null;\n /** The marketplace's own promise to the buyer. */\n deliveryDueAt: Date | null;\n /** When the marketplace says the order was placed. */\n placedAt: Date;\n /** Null when the payload does not say. */\n orderType?: MarketplaceOrderType | null;\n /** Null on a take-out and when unstated. */\n deliveredBy?: MarketplaceDeliveredBy | null;\n /** Null on a take-out and when unstated. */\n deliveryAddress?: NormalizedAddress | null;\n /**\n * OPTIONAL. The delivery fee the buyer was charged, in the smallest currency\n * unit. 0 is a free delivery; null or absent is \"did not say\".\n */\n deliveryFeeCents?: number | null;\n /** OPTIONAL. The items' sum as the marketplace states it, before fees and discounts. Null or absent is \"did not say\". */\n subtotalCents?: number | null;\n /**\n * OPTIONAL. The discounts on the order, one entry per sponsor's share, so a\n * host can tell what the store gave from what the marketplace paid for.\n * Absent is \"did not say\"; an empty array is \"no discount\".\n */\n discounts?: NormalizedOrderDiscount[];\n /**\n * OPTIONAL. The merchant the order names, when its body says (Open\n * Delivery's `merchant.id`). A fetched order naming another merchant than\n * the connection's is refused.\n */\n externalMerchantId?: string | null;\n /**\n * OPTIONAL (FUT-5665). The code the marketplace's courier states at the\n * counter to collect the bag (iFood's `delivery.pickupCode`), for the host\n * to check locally at the hand-over. Null or absent: the marketplace asks\n * none for this order (the check is off for the store, or the store carries\n * the bag itself).\n */\n pickupCode?: string | null;\n /**\n * OPTIONAL (FUT-5803). How the buyer pays: each method, what is prepaid and\n * what is still to collect, and the change a cash buyer asks for. Absent:\n * the marketplace states none.\n */\n payments?: NormalizedPayments;\n /**\n * OPTIONAL (FUT-5803). The fees besides delivery, inside `totalCents`.\n * Absent is \"did not say\"; an empty array is \"none\".\n */\n additionalFees?: NormalizedOrderFee[];\n}\n\n/**\n * What an event says about the STORE's own cancellation request: `CONFIRMED`\n * when the marketplace cancelled the order (a pending request is answered),\n * `FAILED` when it refused the request.\n */\nexport type CancellationOutcome = \"CONFIRMED\" | \"FAILED\";\n\n/**\n * A step of the order's life a marketplace announces about an order it\n * already has (FUT-4653): the courier left (`DISPATCHED`), the marketplace's\n * courier has the bag (`COLLECTED`, FUT-5665: for a fleet bag it is the same\n * hand-over as `DISPATCHED`) or the order is finished (`CONCLUDED`). An event\n * that names one moves nothing by itself; the engine asks the host to move the\n * order forward (`onLifecycle`).\n */\nexport type MarketplaceLifecycle = \"DISPATCHED\" | \"COLLECTED\" | \"CONCLUDED\";\n\n/**\n * Where the marketplace's own courier is with a bag (FUT-5665), provider-\n * neutral: named (`ASSIGNED`), on the way to the store (`GOING_TO_ORIGIN`),\n * at the counter (`ARRIVED_AT_ORIGIN`), holding the bag (`COLLECTED`), or\n * bringing it back (`RETURNING_TO_ORIGIN`, then `RETURNED_TO_ORIGIN`).\n */\nexport type MarketplaceCourierStep =\n | \"ASSIGNED\"\n | \"GOING_TO_ORIGIN\"\n | \"ARRIVED_AT_ORIGIN\"\n | \"COLLECTED\"\n | \"RETURNING_TO_ORIGIN\"\n | \"RETURNED_TO_ORIGIN\";\n\n/** What the courier rides, as a closed set the host has words for. `OTHER`: stated, and none of these. */\nexport type MarketplaceCourierVehicle = \"MOTORCYCLE\" | \"BICYCLE\" | \"CAR\" | \"OTHER\";\n\n/** Who the marketplace sent, as much as it says. */\nexport interface MarketplaceCourier {\n name: string | null;\n /** An https URL of the courier's photo, or null (any other scheme is dropped). */\n photoUrl: string | null;\n vehicle: MarketplaceCourierVehicle | null;\n}\n\n/** One courier event, normalized (FUT-5665). */\nexport interface NormalizedCourierEvent {\n step: MarketplaceCourierStep;\n /** When the marketplace says it happened; null when it does not (the engine then hands the host its clock). */\n at: Date | null;\n /** Who is coming: on `ASSIGNED`, when the marketplace names them; null otherwise. */\n courier: MarketplaceCourier | null;\n /** The bag is coming back (`RETURNING`) or is back (`RETURNED`); null on every other step. */\n returning: \"RETURNING\" | \"RETURNED\" | null;\n}\n\n/** What an adapter makes of one inbound delivery. */\nexport interface NormalizedEvent {\n provider: MarketplaceProvider;\n /** The delivery's own id — the inbox dedup key, paired with the provider. */\n eventId: string;\n /** The provider's event type verbatim, kept for the inbox row and the log. */\n eventType: string;\n /** The merchant this event names, used to attribute it to a tenant. */\n externalMerchantId: string | null;\n externalOrderId: string | null;\n /**\n * The order this event carries, or null when the event is one the engine\n * understands and does not ingest. A null here is an IGNORED inbox row (or a\n * cancellation, below), never a failure.\n */\n order: NormalizedMarketplaceOrder | null;\n /** The marketplace has CANCELLED the order. */\n cancelled: boolean;\n /**\n * The answer to the store's own cancellation request, when this event is\n * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.\n */\n cancellationOutcome?: CancellationOutcome | null;\n /**\n * OPTIONAL. This event announces an order whose body the marketplace serves\n * separately (Open Delivery's `CREATED` carries only the order's id): the\n * engine fetches it through the adapter's `fetchOrder`, in the\n * `marketplace.fetch-order` job, never inside the request that delivered\n * the event. Ignored when `order` is present.\n */\n orderToFetch?: boolean;\n /**\n * OPTIONAL. The lifecycle step this event announces about an order the\n * engine already has. Absent or null: the event names none. An event that\n * names one carries no order body.\n */\n lifecycle?: MarketplaceLifecycle | null;\n /**\n * OPTIONAL (FUT-5665). Where the marketplace's courier is, when this event\n * says. A `COLLECTED` names the lifecycle too. Absent or null: the event\n * names no courier step.\n */\n courier?: NormalizedCourierEvent | null;\n /**\n * OPTIONAL (FUT-5653). The store accepted the order in the marketplace's own\n * app (iFood's `CFM`): an order still AWAITING here is accepted through the\n * host's admit, with no confirm sent back. Carries no order body.\n */\n marketplaceConfirmed?: boolean;\n}\n"],"mappings":";;;;;AAwBO,IAAM,sBAAsB;AAkD5B,SAAS,yBAAyB,MAAoF;AAC3H,SAAO,KAAK,iBAAiB,KAAK,YAAY,KAAK,WAAW,CAAC,GAAG,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,YAAY,CAAC;AACtH;AAFgB;","names":[]}
|
|
@@ -6,15 +6,16 @@ import {
|
|
|
6
6
|
firstCents,
|
|
7
7
|
firstDate,
|
|
8
8
|
firstString,
|
|
9
|
+
firstTaxId,
|
|
9
10
|
pick,
|
|
10
11
|
toCents,
|
|
11
12
|
verifyHmacSha256Hex
|
|
12
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-E4XJXHUK.js";
|
|
13
14
|
import {
|
|
14
15
|
answered,
|
|
15
16
|
outboundResultOf,
|
|
16
17
|
tokenGrantResultOf
|
|
17
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-BTKVZAJI.js";
|
|
18
19
|
import {
|
|
19
20
|
__name
|
|
20
21
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -425,6 +426,11 @@ function readAddress(order, missingStreetNumber) {
|
|
|
425
426
|
};
|
|
426
427
|
}
|
|
427
428
|
__name(readAddress, "readAddress");
|
|
429
|
+
function buyerDocument(order) {
|
|
430
|
+
const digits = firstTaxId(order, [["customer", "documentNumber"]]);
|
|
431
|
+
return digits ? { document: digits } : {};
|
|
432
|
+
}
|
|
433
|
+
__name(buyerDocument, "buyerDocument");
|
|
428
434
|
function normalizeOpenDeliveryOrderAs(provider, order, options) {
|
|
429
435
|
const externalOrderId = firstString(order, [["id"]]);
|
|
430
436
|
const rawItems = pick(order, "items");
|
|
@@ -438,7 +444,9 @@ function normalizeOpenDeliveryOrderAs(provider, order, options) {
|
|
|
438
444
|
buyer: {
|
|
439
445
|
externalId: firstString(order, [["customer", "id"]]),
|
|
440
446
|
name: firstString(order, [["customer", "name"]]),
|
|
441
|
-
phone: firstString(order, [["customer", "phone", "number"]])
|
|
447
|
+
phone: firstString(order, [["customer", "phone", "number"]]),
|
|
448
|
+
// FUT-5803: the CPF or CNPJ for the invoice, digits only; absent when unstated.
|
|
449
|
+
...buyerDocument(order)
|
|
442
450
|
},
|
|
443
451
|
lines,
|
|
444
452
|
// The line sum is the FALLBACK: the stated total carries the fees and
|
|
@@ -475,4 +483,4 @@ export {
|
|
|
475
483
|
normalizeOpenDeliveryEventAs,
|
|
476
484
|
normalizeOpenDeliveryOrderAs
|
|
477
485
|
};
|
|
478
|
-
//# sourceMappingURL=chunk-
|
|
486
|
+
//# sourceMappingURL=chunk-TRUK5ZBE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/open-delivery/client.ts","../src/open-delivery/orders.ts","../src/open-delivery/reasons.ts","../src/open-delivery/merchant.ts","../src/open-delivery/normalize.ts"],"sourcesContent":["import {\n tokenGrantResultOf,\n type AdapterCallContext,\n type MarketplaceHttpRequest,\n type MarketplaceHttpResponse,\n type OutboundResult,\n} from \"../core/adapter\";\n\n/**\n * The HTTP half every Open Delivery adapter shares: the token grant and its\n * cache, and one authenticated call. Not a subpath: an adapter folder\n * (`../99food`, `../keeta`) builds a {@link OpenDeliveryDialect} and hands it\n * to these functions, so the standard is written once and each marketplace's\n * departures from it are data in its own folder.\n *\n * Open Delivery standardizes the PATHS under each Ordering Application's own\n * base URL, so the base URL per environment is part of the dialect.\n */\n\n/** Where an Ordering Application serves Open Delivery, per environment. */\nexport type OpenDeliveryApiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/** One marketplace's way of speaking Open Delivery: what differs from the standard, as data. */\nexport interface OpenDeliveryDialect {\n /** The provider id the adapter is registered under; it keys the token cache. */\n readonly provider: string;\n /** The marketplace's name, in the reasons a log reads (\"99Food refused the token\"). */\n readonly name: string;\n readonly bases: OpenDeliveryApiBaseUrls;\n /** The token grant's `Content-Type` and body: the standard's form-encoded `client_credentials`, or the marketplace's own. */\n tokenGrant(ctx: AdapterCallContext): { contentType: string; body: string };\n /** A JSON body exactly as it is sent (and, where a signature covers it, signed). */\n serialize(body: unknown): string;\n /** OPTIONAL. Headers derived from the final URL and body, added to EVERY call, the token grant included (a signature). */\n sign?(ctx: AdapterCallContext, url: string, body: string | undefined): Record<string, string>;\n}\n\n/** Refuse, at construction, a configured URL that is not https: credentials travel on it. */\nexport function assertHttpsUrl(packagePath: string, name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`${packagePath}: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`${packagePath}: ${name} must be https.`);\n}\n\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/** `expires_in` is optional in the standard's `TokenResponse`; an hour when absent. ESTIMATED. */\nconst DEFAULT_TOKEN_SECONDS = 3600;\n\n/** The result that ends a call before it was answered usefully. */\nexport type OpenDeliveryStop = Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** The base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nfunction baseOf(ctx: AdapterCallContext, bases: OpenDeliveryApiBaseUrls): string {\n const base = bases[ctx.environment];\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\n\nconst tokenKey = (ctx: AdapterCallContext, dialect: OpenDeliveryDialect): string =>\n `${dialect.provider}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The standard's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/** The dialect's signature headers for one request, or none. */\nfunction signed(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n request: MarketplaceHttpRequest,\n): MarketplaceHttpRequest {\n if (!dialect.sign) return request;\n return { ...request, headers: { ...request.headers, ...dialect.sign(ctx, request.url, request.body) } };\n}\n\n/**\n * A bearer token from the per-process cache, or a fresh grant at `POST\n * /oauth/token`. Keyed by provider, environment and client id; memory only.\n */\nasync function bearer(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n): Promise<{ token: string } | OpenDeliveryStop> {\n const cached = ctx.tokens.get(tokenKey(ctx, dialect));\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const grant = dialect.tokenGrant(ctx);\n const response = await ctx.http(\n signed(ctx, dialect, {\n method: \"POST\",\n url: `${baseOf(ctx, dialect.bases)}/oauth/token`,\n headers: { \"Content-Type\": grant.contentType },\n body: grant.body,\n }),\n );\n if (response.status < 200 || response.status >= 300) {\n const result = tokenGrantResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: `${dialect.name} answered the token grant without a token` };\n ctx.tokens.set(tokenKey(ctx, dialect), {\n token: token.token,\n expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000,\n });\n return { token: token.token };\n}\n\n/** One call, as an Open Delivery adapter states it. */\ninterface OpenDeliveryCall {\n method: MarketplaceHttpRequest[\"method\"];\n /** From the base: `/v1/orders/…`. Path segments are the caller's to encode. */\n path: string;\n /** Sent as the query string. */\n query?: Readonly<Record<string, string>>;\n /** A JSON body, serialized by the dialect. Absent: no body and no `Content-Type`. */\n body?: unknown;\n /** Extra headers (`X-App-MerchantId`). */\n headers?: Readonly<Record<string, string>>;\n /** Whether the call carries the bearer token. Default true; the standard's few open calls say false. */\n authenticated?: boolean;\n}\n\n/** The URL a call goes to: base, path, and the query string when there is one. */\nfunction urlOf(ctx: AdapterCallContext, dialect: OpenDeliveryDialect, call: OpenDeliveryCall): string {\n const query = call.query && Object.keys(call.query).length > 0 ? `?${new URLSearchParams(call.query).toString()}` : \"\";\n return `${baseOf(ctx, dialect.bases)}${call.path}${query}`;\n}\n\n/** The request a call makes, before its signature. */\nfunction requestOf(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n call: OpenDeliveryCall,\n token: string | null,\n): MarketplaceHttpRequest {\n const body = call.body === undefined ? undefined : dialect.serialize(call.body);\n return {\n method: call.method,\n url: urlOf(ctx, dialect, call),\n headers: {\n ...(token === null ? {} : { Authorization: `Bearer ${token}` }),\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...call.headers,\n },\n ...(body === undefined ? {} : { body }),\n };\n}\n\n/**\n * One call, authenticated unless it says otherwise: the raw answer, or the\n * result that ends it. A 401 is a token that went stale under us: it is\n * forgotten, and the retry fetches another.\n */\nexport async function openDeliveryCall(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n call: OpenDeliveryCall,\n): Promise<MarketplaceHttpResponse | OpenDeliveryStop> {\n const authenticated = call.authenticated ?? true;\n const auth = authenticated ? await bearer(ctx, dialect) : null;\n if (auth && !(\"token\" in auth)) return auth;\n const response = await ctx.http(signed(ctx, dialect, requestOf(ctx, dialect, call, auth?.token ?? null)));\n if (!authenticated || response.status !== 401) return response;\n ctx.tokens.delete(tokenKey(ctx, dialect));\n return { kind: \"retry\", reason: `${dialect.name} refused the token` };\n}\n\n/** Whether a call ended before an answer worth reading. */\nexport const isStop = (value: MarketplaceHttpResponse | OpenDeliveryStop): value is OpenDeliveryStop =>\n \"kind\" in value;\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n type StatusFacts,\n} from \"../core/adapter\";\nimport type { NormalizedMarketplaceOrder } from \"../core/types\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect, type OpenDeliveryStop } from \"./client\";\n\n/**\n * The ORDER calls every Open Delivery adapter shares: the order fetch,\n * confirm, requestCancellation and the status steps. Paths, verbs, bodies and\n * answers are the standard's (v1.7.1 and v1.5.0 agree on all of them); the\n * job that calls these, its retries and what a failure shows are the\n * engine's. What a marketplace does differently is an option here, set by its\n * adapter folder. Tests never reach a marketplace: the HTTP client is the\n * host's port, answered by a fake.\n */\n\n/** One authenticated call to an order's resource. */\nfunction callOrder(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n request: { method: \"GET\" | \"POST\"; externalOrderId: string; action: string | null; body?: unknown },\n): Promise<MarketplaceHttpResponse | OpenDeliveryStop> {\n const suffix = request.action === null ? \"\" : `/${request.action}`;\n return openDeliveryCall(ctx, dialect, {\n method: request.method,\n path: `/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,\n ...(request.body === undefined ? {} : { body: request.body }),\n });\n}\n\n/** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */\nfunction alreadyCancelled(response: MarketplaceHttpResponse): boolean {\n if (response.status !== 422) return false;\n try {\n return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === \"CANCELLED\";\n } catch {\n return false;\n }\n}\n\n/** {@link answered} for a fetch: a call that never got an answer is a retry. */\nasync function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** How a fetched `Order` becomes the engine's order. */\ninterface OpenDeliveryFetchOptions {\n normalize(order: unknown): NormalizedMarketplaceOrder | null;\n /**\n * OPTIONAL. What the adapter does to the parsed `Order` before it is\n * normalized (Keeta's encrypted fields). Never fails the fetch.\n */\n prepare?(ctx: AdapterCallContext, order: unknown): Promise<unknown>;\n}\n\n/** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */\nexport function openDeliveryFetchOrder(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: { externalOrderId: string },\n options: OpenDeliveryFetchOptions,\n): Promise<FetchOrderResult> {\n return fetched(async () => {\n const response = await callOrder(ctx, dialect, { method: \"GET\", externalOrderId: order.externalOrderId, action: null });\n if (isStop(response)) return response;\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n let body: unknown;\n try {\n body = JSON.parse(response.body);\n } catch {\n return { kind: \"refused\", status: response.status, message: \"the order is not JSON\" };\n }\n const prepared = options.prepare ? await options.prepare(ctx, body) : body;\n const normalized = options.normalize(prepared);\n return normalized\n ? { kind: \"order\", order: normalized }\n : { kind: \"refused\", status: response.status, message: \"the order carries no id or no line\" };\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/confirm` with the standard's `OrderConfirmed`:\n * `orderExternalCode` (the host's own order id) and `createdAt`, plus the\n * `preparationTime` in minutes when the store stated one. `createdAt` is sent\n * as the moment of the confirmation: ESTIMATED (the standard describes it\n * with the ORDER's creation text, a copy of another schema's).\n *\n * Every 422 is a refusal. It is the standard's generic `UnprocessableEntity`\n * (\"check if the instruction has not been sent before\"), and its body cannot\n * tell a duplicate from a cancelled order. So a retried confirm whose first\n * answer was lost reads \"not confirmed\" with the app link (a false alarm a\n * person dismisses on the marketplace), and a confirm the marketplace truly\n * refused is never stamped confirmed.\n */\nexport function openDeliveryConfirm(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, dialect, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"confirm\",\n body: {\n orderExternalCode: order.hostOrderCode,\n createdAt: ctx.now.toISOString(),\n ...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),\n },\n });\n return isStop(response) ? response : outboundResultOf(response);\n });\n}\n\n/** The standard's limit on `outOfStockItems`. */\nconst MAX_OUT_OF_STOCK_ITEMS = 100;\n\n/** How a marketplace reads `RequestCancelled.outOfStockItems`. */\ninterface OpenDeliveryCancellationOptions {\n /**\n * The offending SKUs (`externalCode`) are sent as `outOfStockItems` with an\n * item-unavailable reason. False where the marketplace wants its own item\n * uuids there, which the engine does not keep (99Food, v1.7.1).\n */\n outOfStockAsSkus: boolean;\n}\n\n/**\n * `POST /v1/orders/{orderId}/requestCancellation` with the standard's\n * `RequestCancelled`: `reason` (free text: the store's, else the label),\n * `code` (one of the standard's codes) and `mode` (`MANUAL` or `AUTO`). 202\n * means taken; the outcome is a later event. A 422 whose `cancellationStatus`\n * is `CANCELLED` means the order is cancelled already, which is what the\n * request wanted. A 400 is a malformed request (a bad id or body: ours); a\n * 422 is the business answer and stays a refusal.\n */\nexport function openDeliveryRequestCancellation(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n options: OpenDeliveryCancellationOptions,\n): Promise<OutboundResult> {\n const skus =\n options.outOfStockAsSkus && input.reason.itemUnavailable && input.offendingSkus.length > 0\n ? { outOfStockItems: input.offendingSkus.slice(0, MAX_OUT_OF_STOCK_ITEMS) }\n : {};\n return answered(async () => {\n const response = await callOrder(ctx, dialect, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"requestCancellation\",\n body: {\n reason: input.text === \"\" ? input.reason.label : input.text,\n code: input.reason.code,\n mode: input.mode,\n ...skus,\n },\n });\n if (isStop(response)) return response;\n if (alreadyCancelled(response)) return { kind: \"accepted\" };\n const result = outboundResultOf(response);\n return result.kind === \"refused\" && result.status === 400 ? { ...result, own: true } : result;\n });\n}\n\n/** Which standard status call a step takes, for which kind of order. */\ntype StatusPath = (facts: StatusFacts) => { action: string; body?: unknown } | null;\n\n/** The status calls a marketplace serves. */\ninterface OpenDeliveryStatusOptions {\n /** A take-out's HANDED_OVER is `POST /v1/orders/{id}/pickedUp`. False where the marketplace has no take-out. */\n takeoutPickedUp: boolean;\n}\n\n/**\n * The standard's status calls (FUT-4653):\n *\n * - READY: `POST /v1/orders/{id}/readyForPickup`, no body; 202. Every kind of order.\n * - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`\n * (`deliveryTrackingInfo` optional, sent empty). Only where the logistics\n * is the merchant's.\n * - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a\n * take-out `POST /v1/orders/{id}/pickedUp` where the marketplace serves it.\n * The marketplace's own fleet: none.\n *\n * The kind of order is `deliveredBy` (null: a take-out; ESTIMATED: an order\n * that merely omits it reads as a take-out here).\n */\nfunction statusPaths(options: OpenDeliveryStatusOptions): Readonly<Record<string, StatusPath>> {\n return {\n READY: () => ({ action: \"readyForPickup\" }),\n DISPATCHED: (facts) => (facts.deliveredBy === \"MERCHANT\" ? { action: \"dispatch\", body: {} } : null),\n HANDED_OVER: (facts) =>\n facts.deliveredBy === \"MERCHANT\"\n ? { action: \"delivered\", body: {} }\n : facts.deliveredBy === null && options.takeoutPickedUp\n ? { action: \"pickedUp\", body: {} }\n : null,\n };\n}\n\n/** A marketplace's status half: whether a step is taken (offline), and the call that tells it. */\nexport function openDeliveryStatus(options: OpenDeliveryStatusOptions) {\n const paths = statusPaths(options);\n return {\n supported: (facts: StatusFacts): boolean => paths[facts.step]?.(facts) != null,\n inform(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }> {\n const path = paths[facts.step]?.(facts) ?? null;\n if (path === null) return Promise.resolve({ kind: \"unsupported\" });\n return answered(async () => {\n const response = await callOrder(ctx, dialect, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: path.action,\n ...(path.body === undefined ? {} : { body: path.body }),\n });\n return isStop(response) ? response : outboundResultOf(response);\n });\n },\n };\n}\n","/**\n * The cancellation codes a merchant may send, verbatim from Open Delivery's\n * `RequestCancelled.code`: the same eleven in v1.7.1 and in Keeta's v1.5.0\n * (its \"códigos de cancelamento (v1.0.7+)\"). Pinned by the standard, not\n * estimated. The two codes only the marketplace sends\n * (`CONSUMER_CANCELLATION_REQUESTED`, `OTHER_CANCELLATION_REASON`) are not a\n * store's to choose and are left out.\n */\nexport const OPEN_DELIVERY_MERCHANT_REASON_CODES = [\n \"SYSTEMIC_ISSUES\",\n \"DUPLICATE_APPLICATION\",\n \"UNAVAILABLE_ITEM\",\n \"RESTAURANT_WITHOUT_DELIVERY_PERSON\",\n \"OUTDATED_MENU\",\n \"ORDER_OUTSIDE_THE_DELIVERY_AREA\",\n \"BLOCKED_CUSTOMER\",\n \"OUTSIDE_DELIVERY_HOURS\",\n \"INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT\",\n \"RISK_AREA\",\n \"DELIVERY_PROBLEM\",\n] as const;\n\ntype OpenDeliveryMerchantReasonCode = (typeof OPEN_DELIVERY_MERCHANT_REASON_CODES)[number];\n\n/** The one reason that means \"an item is unavailable\". */\nexport const OPEN_DELIVERY_ITEM_UNAVAILABLE: OpenDeliveryMerchantReasonCode = \"UNAVAILABLE_ITEM\";\n","import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type { CatalogueMenuEntry, CatalogueMenuOptions } from \"../core/catalogue-port\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport { isStop, openDeliveryCall, type OpenDeliveryDialect } from \"./client\";\n\n/**\n * The MERCHANT half every Open Delivery adapter shares: the menu part of the\n * `Merchant` document the host serves (`GET /v1/merchant`, PULL: FUT-4768),\n * the `merchantUpdate` notification, and the store pause built on it\n * (FUT-4851). Where a marketplace puts `merchantUpdate` and what it sends\n * with it is its adapter folder's.\n *\n * Every id in the document is a UUID the software generates (the standard's\n * `format: uuid`), derived from the publication's stable reference, so the\n * same product keeps the same ids across pulls.\n */\n\n/** One category per host category name, in first-seen order. */\nfunction categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {\n const byName = new Map<string, { id: string; name: string; offers: string[] }>();\n for (const entry of entries) {\n const name = entry.categoryName.trim();\n const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };\n category.offers.push(stableUuid(`${entry.ref}:offer`));\n byName.set(name, category);\n }\n return [...byName.values()];\n}\n\n/**\n * The menu part of Open Delivery's `Merchant`: `menus`, `categories`,\n * `items`, `itemOffers` (the price lives on the offer). Every item is a unit\n * (`UN`) with a status, and every offer states `originalValue`: what both\n * v1.7.1 and Keeta's v1.5.0 require.\n */\nexport function openDeliveryMenuDocument(input: {\n externalMerchantId: string;\n entries: readonly CatalogueMenuEntry[];\n options: CatalogueMenuOptions;\n}) {\n const { externalMerchantId: merchantId, entries, options } = input;\n const categories = categoriesOf(merchantId, entries);\n return {\n menus: [\n {\n id: stableUuid(`${merchantId}:menu`),\n name: options.menuName,\n externalCode: \"menu\",\n categoryId: categories.map((category) => category.id),\n },\n ],\n categories: categories.map((category, index) => ({\n id: category.id,\n index,\n name: category.name,\n externalCode: category.name,\n status: \"AVAILABLE\",\n itemOfferId: category.offers,\n })),\n items: entries.map((entry) => ({\n id: stableUuid(`${entry.ref}:item`),\n name: entry.name,\n description: entry.description ?? \"\",\n externalCode: entry.productId,\n status: \"AVAILABLE\",\n unit: \"UN\",\n ...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),\n })),\n itemOffers: entries.map((entry, index) => {\n const value = Math.round(entry.priceCents) / 100;\n return {\n id: stableUuid(`${entry.ref}:offer`),\n itemId: stableUuid(`${entry.ref}:item`),\n index,\n status: \"AVAILABLE\",\n price: { value, originalValue: value, currency: options.currency },\n };\n }),\n };\n}\n\n/** One `merchantUpdate` call, where and with what the marketplace takes it. */\ninterface OpenDeliveryMerchantUpdate {\n /** From the base: `/v1/merchantUpdate`, or a marketplace's own (Keeta's names the merchant). */\n path: string;\n /** Absent: the empty body that means \"pull the whole merchant again\". */\n body?: unknown;\n headers?: Readonly<Record<string, string>>;\n}\n\n/** `POST {merchantUpdate}`: 2xx accepted (the standard answers 204, 200 \"for compatibility\"). */\nexport function openDeliveryMerchantUpdate(\n ctx: AdapterCallContext,\n dialect: OpenDeliveryDialect,\n update: OpenDeliveryMerchantUpdate,\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await openDeliveryCall(ctx, dialect, {\n method: \"POST\",\n path: update.path,\n ...(update.body === undefined ? {} : { body: update.body }),\n ...(update.headers === undefined ? {} : { headers: update.headers }),\n });\n return isStop(response) ? response : outboundResultOf(response);\n });\n}\n\n/**\n * The store pause on `merchantUpdate`'s `merchantStatus` (`AVAILABLE` /\n * `UNAVAILABLE`): a SWITCH, with no id and no end (\"you don't know when the\n * service will be re-established\"), so an adapter offers it only when its\n * host opts in (see `../core/pause-port.ts`).\n */\nexport function openDeliverySwitchAvailability(\n setStatus: (ctx: AdapterCallContext, merchantId: string, status: \"AVAILABLE\" | \"UNAVAILABLE\") => Promise<OutboundResult>,\n): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx, request) => {\n const result = await setStatus(ctx, request.merchantId, \"UNAVAILABLE\");\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx, ref) => setStatus(ctx, ref.merchantId, \"AVAILABLE\"),\n };\n}\n","import {\n asString,\n firstCents,\n firstDate,\n firstString,\n firstTaxId,\n pick,\n toCents,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\nimport type {\n MarketplaceLifecycle,\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The INBOUND half every Open Delivery adapter shares (Abrasel's standard;\n * 99Food speaks v1.7.1, Keeta v1.5.0 with its own changes). Each reader takes\n * the provider id the result is stamped with.\n *\n * Open Delivery splits what iFood sends at once: the webhook's `Event` names\n * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and\n * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So\n * there are two readers here: {@link normalizeOpenDeliveryEvent} for the\n * webhook (a `CREATED` becomes `orderToFetch`), and\n * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.\n *\n * Every shape below is the spec's (`components/schemas/Event`, `Order`,\n * `Price`, `Address`), and every fixture in the tests is the spec's own\n * example. Read defensively all the same: a missing field produces null, and\n * only a missing order id refuses an event (it is the idempotency key).\n */\n\n/** The order exists and its body must be fetched. */\nconst CREATED = \"CREATED\";\n/** The order is cancelled: the store's request was granted, or a mandatory cancellation. */\nconst CANCELLED = \"CANCELLED\";\n/** The order left (DISPATCHED) and the order is finished (CONCLUDED): the lifecycle events (FUT-4653). */\nconst LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = { DISPATCHED: \"DISPATCHED\", CONCLUDED: \"CONCLUDED\" };\n/** The marketplace refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_DENIED = \"CANCELLATION_REQUEST_DENIED\";\n\n/**\n * Verify a delivery: Open Delivery's `X-App-Signature` is \"a lowercased\n * hexadecimal HMAC signature of the webhook HTTP request body, using the\n * client secret as a key and SHA256 as the hash function\". The key is the\n * merchant app's CLIENT SECRET, so a store's connection keeps that same value\n * as its webhook secret.\n *\n * Unlike iFood (whose secret is issued after certification), the key exists\n * from the moment the store connects, so an unset secret REFUSES: an unsigned\n * CANCELLED for a known order id would otherwise cancel it.\n */\nexport function verifyOpenDeliverySignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return false;\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/**\n * Normalize one webhook `Event`. Null only when it names no order.\n *\n * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.\n * - `CANCELLED` is a cancellation, whether the store asked for it or not.\n * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.\n * - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine\n * asks the host to move the order forward, when the store follows them.\n * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, the\n * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and\n * recorded, and acts on nothing: an IGNORED inbox row.\n *\n * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the\n * engine attributes a delivery by its URL's store slug, so it reads none.\n */\nexport function normalizeOpenDeliveryEventAs(provider: string, payload: unknown): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"]]);\n if (!externalOrderId) return null;\n const eventType = (firstString(payload, [[\"eventType\"]]) ?? \"UNKNOWN\").toUpperCase();\n const cancelled = eventType === CANCELLED;\n const denied = eventType === CANCELLATION_REQUEST_DENIED;\n return {\n provider,\n // The spec's own event id. The fallback is deterministic so a redelivery\n // still collides on the inbox's unique index.\n eventId: firstString(payload, [[\"eventId\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: null,\n externalOrderId,\n order: null,\n orderToFetch: eventType === CREATED,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : denied ? \"FAILED\" : null,\n ...(LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}),\n };\n}\n\n/** A `Price` object (`{ value, currency }`) in cents. */\nfunction priceCents(source: unknown, ...path: string[]): number | null {\n return toCents(pick(source, ...path, \"value\"));\n}\n\n/**\n * The note a kitchen reads: the chosen options (a pizza's halves are options)\n * and the buyer's own instructions. The normalized line has no options of its\n * own, and a flavour dropped from the ticket is food made wrong.\n */\nfunction lineNote(item: unknown, fraction: string | null): string | null {\n const rawOptions = pick(item, \"options\");\n const options = (Array.isArray(rawOptions) ? rawOptions : [])\n .map((option) => {\n const name = asString(pick(option, \"name\"));\n const quantity = Number(pick(option, \"quantity\") ?? 1);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n const parts = [fraction, options.join(\", \") || null, firstString(item, [[\"specialInstructions\"]])];\n const note = parts.filter((part): part is string => part !== null).join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * What the buyer paid for the whole line, in cents. The spec's `totalPrice`\n * (\"quantity * (unitPrice + optionsPrice)\") is the figure the order's\n * `itemsPrice` is built from, and it wins whenever it is stated — its own\n * example does not add up otherwise (unit 43, options 50, total 50).\n *\n * Without it: `unitPrice × quantity + optionsPrice`. ESTIMATED: the spec calls\n * `optionsPrice` \"the sum of the total prices of all options of the item\", a\n * LINE figure, so it is added once, never multiplied by the quantity or by a\n * weight.\n */\nfunction lineTotalCents(item: unknown, quantity: number): number {\n const total = priceCents(item, \"totalPrice\");\n if (total !== null) return total;\n const unit = priceCents(item, \"unitPrice\") ?? 0;\n return Math.round(unit * quantity) + (priceCents(item, \"optionsPrice\") ?? 0);\n}\n\n/** The stated quantity (decimal for weighed units), 1 when absent or nonsense. */\nfunction quantityOf(item: unknown): number {\n const stated = Number(pick(item, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\n/**\n * Split a line total over a whole quantity so the lines add up to it EXACTLY:\n * one row at `total / quantity` when it divides; otherwise `quantity - 1`\n * units at the floor and one unit carrying the remainder, under the same SKU\n * (R$ 10.00 over 3 is 3.33 × 2 + 3.34).\n */\nfunction splitWhole(total: number, quantity: number): { quantity: number; unitPriceCents: number }[] {\n const floor = Math.floor(total / quantity);\n const remainder = total - floor * quantity;\n if (remainder === 0) return [{ quantity, unitPriceCents: floor }];\n const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];\n return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];\n}\n\n/**\n * One `Order.items[]` entry → its lines, which always add up to the line's\n * total ({@link lineTotalCents}). A whole quantity is split by\n * {@link splitWhole}; a fractional one (500 g as `0.5 KG`) is one line at its\n * total, the weight in the note.\n *\n * A line with no `externalCode` keys on the item id, then the name: an\n * unmapped line is recoverable, a dropped one is not. ESTIMATED: whether the\n * item id is stable across orders is not pinned by the spec; if it is per\n * order, each such order adds an unmapped SKU row.\n */\nfunction readLines(item: unknown): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = quantityOf(item);\n const whole = Number.isInteger(quantity);\n const fraction = whole ? null : `${quantity} ${firstString(item, [[\"unit\"]]) ?? \"\"}`.trim();\n const total = lineTotalCents(item, quantity);\n const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];\n const note = lineNote(item, fraction);\n return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));\n}\n\n/** `DELIVERY` or `TAKEOUT`; `INDOOR` (eaten at the store) is neither, so unstated. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"type\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n return stated === \"MERCHANT\" || stated === \"MARKETPLACE\" ? stated : null;\n}\n\n/**\n * `delivery.deliveryAddress`. The spec's schema says `street`, `number`,\n * `district`; its own (commented) order example says `streetName`,\n * `streetNumber`, `neighborhood`. Both are read. The state is ISO 3166-2 by\n * recommendation (`BR-SP`), so the country prefix is dropped.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"street\"], [\"streetName\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"number\"], [\"streetNumber\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"district\"], [\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]])?.replace(/^[A-Z]{2}-/u, \"\") ?? null,\n };\n}\n\n/** `customer.documentNumber` (text or a number), digits only, as `{ document }`; nothing when unstated. */\nfunction buyerDocument(order: unknown): { document?: string } {\n const digits = firstTaxId(order, [[\"customer\", \"documentNumber\"]]);\n return digits ? { document: digits } : {};\n}\n\n/**\n * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when\n * it carries no id or no line.\n *\n * The total is `total.orderAmount`, \"the final value of the order (itemsPrice\n * + otherFees - discounts)\": the buyer's receipt, gross. Open Delivery's\n * `Order` states NO commission field, so `commissionCents` is null (\"did not\n * say\"), never 0; the marketplace's cut arrives with its statement.\n */\nexport function normalizeOpenDeliveryOrderAs(\n provider: string,\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n const externalOrderId = firstString(order, [[\"id\"]]);\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .flatMap(readLines);\n if (!externalOrderId || lines.length === 0) return null;\n return {\n provider,\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]),\n externalMerchantId: firstString(order, [[\"merchant\", \"id\"]]),\n buyer: {\n externalId: firstString(order, [[\"customer\", \"id\"]]),\n name: firstString(order, [[\"customer\", \"name\"]]),\n phone: firstString(order, [[\"customer\", \"phone\", \"number\"]]),\n // FUT-5803: the CPF or CNPJ for the invoice, digits only; absent when unstated.\n ...buyerDocument(order),\n },\n lines,\n // The line sum is the FALLBACK: the stated total carries the fees and\n // discounts the lines do not, and it is the number on the receipt.\n totalCents:\n firstCents(order, [[\"total\", \"orderAmount\", \"value\"]]) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n deliveryDueAt: firstDate(order, [\n [\"delivery\", \"estimatedDeliveryDateTime\"],\n [\"takeout\", \"takeoutDateTime\"],\n [\"schedule\", \"scheduledDateTimeEnd\"],\n ]),\n placedAt: firstDate(order, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, options.missingStreetNumber),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsCO,SAAS,eAAe,aAAqB,MAAc,KAAmB;AACnF,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG;AAAA,EACtB,QAAQ;AACN,UAAM,IAAI,MAAM,GAAG,WAAW,KAAK,IAAI,gBAAgB;AAAA,EACzD;AACA,MAAI,OAAO,aAAa,SAAU,OAAM,IAAI,MAAM,GAAG,WAAW,KAAK,IAAI,iBAAiB;AAC5F;AARgB;AAWhB,IAAM,kBAAkB;AAExB,IAAM,wBAAwB;AAM9B,SAAS,OAAO,KAAyB,OAAwC;AAC/E,QAAM,OAAO,MAAM,IAAI,WAAW;AAClC,MAAI,MAAM,KAAK;AACf,SAAO,MAAM,KAAK,KAAK,WAAW,MAAM,CAAC,MAAM,GAAI,QAAO;AAC1D,SAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AALS;AAOT,IAAM,WAAW,wBAAC,KAAyB,YACzC,GAAG,QAAQ,QAAQ,IAAI,IAAI,WAAW,IAAI,IAAI,YAAY,QAAQ,IADnD;AAIjB,SAAS,QAAQ,MAAkE;AACjF,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,QAAI,OAAO,OAAO,iBAAiB,YAAY,OAAO,iBAAiB,GAAI,QAAO;AAClF,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