@12-apps/marketplace 1.13.0 → 1.14.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 +143 -3
- package/README.md +27 -2
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CQ4QiZPi.d.ts → adapter-szxo9ohc.d.ts} +82 -2
- package/dist/{chunk-NFJQQWG4.js → chunk-BNWRIR5J.js} +2 -2
- package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
- package/dist/chunk-BTKVZAJI.js.map +1 -0
- package/dist/{chunk-CEWTV2TC.js → chunk-MDXSVE7Q.js} +652 -246
- package/dist/chunk-MDXSVE7Q.js.map +1 -0
- package/dist/{chunk-W57TITU4.js → chunk-R3BUW5PX.js} +53 -6
- package/dist/chunk-R3BUW5PX.js.map +1 -0
- package/dist/{client-CCSnylou.d.ts → client-CaZiG7Lw.d.ts} +1 -1
- package/dist/{engine-1KlJ_8jK.d.ts → engine-CgKBbk9J.d.ts} +127 -3
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +13 -3
- package/dist/ifood/index.js +114 -23
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +29 -5
- package/dist/index.js +54 -6
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- package/dist/manifest/server.d.ts +4 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/index.d.ts +14 -5
- package/dist/server/index.js +2 -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 +6 -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/outbound.ts +5 -1
- 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 +6 -0
- package/src/ifood/index.ts +27 -4
- package/src/ifood/normalize.ts +16 -0
- package/src/ifood/outbound.ts +131 -27
- package/src/index.ts +18 -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-CEWTV2TC.js.map +0 -1
- package/dist/chunk-W57TITU4.js.map +0 -1
- /package/dist/{chunk-NFJQQWG4.js.map → chunk-BNWRIR5J.js.map} +0 -0
package/src/server/webhook.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { WireRequest, WireResponse, WireRoute } from "@12-apps/wiring";
|
|
2
2
|
|
|
3
|
+
import type { PresenceProbe } from "../core/adapter";
|
|
3
4
|
import type { IngestionTarget } from "../core/integration";
|
|
4
5
|
import type { MarketplaceApiConfig } from "./http";
|
|
5
6
|
|
|
@@ -13,7 +14,8 @@ import type { MarketplaceApiConfig } from "./http";
|
|
|
13
14
|
* (which header carries the signature, and how it is computed) — the route
|
|
14
15
|
* itself knows no marketplace.
|
|
15
16
|
*
|
|
16
|
-
* It answers 2xx for almost everything, deliberately
|
|
17
|
+
* It answers 2xx for almost everything, deliberately: 200, or the status the
|
|
18
|
+
* adapter states (`webhookAnswerStatus`: iFood's 202, FUT-5984). A marketplace
|
|
17
19
|
* redelivers on any non-2xx, so the only failures worth signalling are the
|
|
18
20
|
* ones a redelivery could fix: a genuine processing failure answers 500, and
|
|
19
21
|
* the inbox row it left is retried by the sweep regardless. Refusals (unknown
|
|
@@ -93,17 +95,31 @@ async function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<
|
|
|
93
95
|
return deliverAdmitted(config, admitted);
|
|
94
96
|
}
|
|
95
97
|
|
|
98
|
+
/**
|
|
99
|
+
* The answer to a proven presence heartbeat (FUT-5984, iFood's `KEEPALIVE`):
|
|
100
|
+
* 202, and in the per-merchant mode every merchant it asked about named
|
|
101
|
+
* online. Nothing is recorded.
|
|
102
|
+
*/
|
|
103
|
+
function presenceAnswer(probe: PresenceProbe): WireResponse {
|
|
104
|
+
return probe.merchantIds === null
|
|
105
|
+
? { status: 202, body: { received: true } }
|
|
106
|
+
: { status: 202, body: { merchantIds: [...probe.merchantIds] } };
|
|
107
|
+
}
|
|
108
|
+
|
|
96
109
|
/** Record and act on a delivery whose store and signature are proven. */
|
|
97
110
|
async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {
|
|
98
111
|
const { clientId, provider, payload, target } = admitted;
|
|
99
112
|
const { engine } = config;
|
|
113
|
+
const probe = engine.presence(provider, payload);
|
|
114
|
+
if (probe) return presenceAnswer(probe);
|
|
115
|
+
const status = engine.answerStatus(provider);
|
|
100
116
|
|
|
101
117
|
const event = engine.normalize(provider, payload);
|
|
102
118
|
if (!event) {
|
|
103
|
-
// Nothing the adapter can key on.
|
|
119
|
+
// Nothing the adapter can key on. 2xx: redelivering an unreadable payload
|
|
104
120
|
// produces an identical unreadable payload.
|
|
105
121
|
config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);
|
|
106
|
-
return { status
|
|
122
|
+
return { status, body: { received: true, ignored: "unrecognized_payload" } };
|
|
107
123
|
}
|
|
108
124
|
const outcome = await engine.deliver({
|
|
109
125
|
clientId,
|
|
@@ -118,7 +134,8 @@ async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted)
|
|
|
118
134
|
if (outcome.kind === "failed") {
|
|
119
135
|
return { status: 500, body: { received: true, error: outcome.reason } };
|
|
120
136
|
}
|
|
121
|
-
|
|
137
|
+
// After the inbox row is written: iFood's 202 means "recorded" (FUT-5984).
|
|
138
|
+
return { status, body: { received: true, outcome: outcome.kind } };
|
|
122
139
|
}
|
|
123
140
|
|
|
124
141
|
/**
|
|
@@ -138,6 +155,12 @@ async function admitApp(
|
|
|
138
155
|
const rawBody = await raw.text();
|
|
139
156
|
const payload = parsedJson(rawBody);
|
|
140
157
|
if (payload === undefined) return { status: 400, body: { error: "invalid_json" } };
|
|
158
|
+
// A presence heartbeat names no store: proved by the app's own key, with no statement (FUT-5984).
|
|
159
|
+
const probe = config.engine.presence(provider, payload);
|
|
160
|
+
if (probe) {
|
|
161
|
+
const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
|
|
162
|
+
return (await config.engine.signedByApp(provider, rawBody, signature)) ? presenceAnswer(probe) : UNAUTHORIZED;
|
|
163
|
+
}
|
|
141
164
|
const found = await appConnection(config, provider, payload);
|
|
142
165
|
if ("status" in found) return found;
|
|
143
166
|
// The app's address never takes an unsigned delivery, whatever the store's own setting.
|
|
@@ -1 +0,0 @@
|
|
|
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\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 /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\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. 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":";;;;;AAyRA,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":[]}
|