@12-apps/marketplace 1.16.0 → 1.17.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 +115 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CjVdMhZ2.d.ts → adapter-CxzF-qGx.d.ts} +185 -2
- package/dist/{chunk-TRUK5ZBE.js → chunk-7IYUO2KC.js} +2 -2
- package/dist/{chunk-BTKVZAJI.js → chunk-CF5BSXE5.js} +1 -1
- package/dist/chunk-CF5BSXE5.js.map +1 -0
- package/dist/{chunk-DJIMUEHT.js → chunk-EABVLQKK.js} +79 -7
- package/dist/chunk-EABVLQKK.js.map +1 -0
- package/dist/{chunk-H2VQRD3B.js → chunk-KKFMDV5K.js} +1 -1
- package/dist/chunk-KKFMDV5K.js.map +1 -0
- package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
- package/dist/chunk-LO7OKO6V.js.map +1 -0
- package/dist/{chunk-TICWLBSA.js → chunk-UZO2NILN.js} +365 -6
- package/dist/chunk-UZO2NILN.js.map +1 -0
- package/dist/{client-DgzCkl8u.d.ts → client-C-4QvVq3.d.ts} +1 -1
- package/dist/{engine-DSRj7qnC.d.ts → engine-Y6Rpf5p7.d.ts} +430 -185
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +4 -4
- package/dist/ifood/index.d.ts +9 -2
- package/dist/ifood/index.js +271 -23
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +21 -4
- package/dist/index.js +381 -42
- 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/index.d.ts +78 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +6 -2
- package/dist/manifest/server.js +4 -4
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/index.d.ts +93 -7
- package/dist/server/index.js +4 -4
- package/package.json +1 -1
- package/prisma/marketplace.prisma +69 -1
- package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
- package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
- package/src/core/adapter.ts +12 -1
- package/src/core/app-linking.ts +396 -0
- package/src/core/dispute-engine.ts +32 -0
- package/src/core/dispute-job.ts +142 -0
- package/src/core/dispute-port.ts +133 -0
- package/src/core/dispute-store.ts +203 -0
- package/src/core/disputes.ts +263 -0
- package/src/core/engine.ts +4 -55
- package/src/core/integration.ts +3 -1
- package/src/core/link-engine.ts +176 -0
- package/src/core/link-store.ts +15 -0
- package/src/core/linking-port.ts +35 -1
- package/src/core/linking.ts +8 -0
- package/src/core/outbound-sweep.ts +9 -1
- package/src/core/pipeline.ts +8 -3
- package/src/core/ports.ts +15 -0
- package/src/core/types.ts +8 -0
- package/src/ifood/app-linking.ts +119 -0
- package/src/ifood/disputes.ts +209 -0
- package/src/ifood/index.ts +12 -1
- package/src/ifood/normalize.ts +3 -0
- package/src/index.ts +34 -0
- package/src/server/jobs.ts +51 -3
- package/src/server/link-routes.ts +56 -4
- package/src/server/mcp-link.ts +44 -2
- package/src/server/mcp.ts +2 -1
- package/dist/chunk-BTKVZAJI.js.map +0 -1
- package/dist/chunk-DJIMUEHT.js.map +0 -1
- package/dist/chunk-H2VQRD3B.js.map +0 -1
- package/dist/chunk-SGOTN5PX.js.map +0 -1
- package/dist/chunk-TICWLBSA.js.map +0 -1
- /package/dist/{chunk-TRUK5ZBE.js.map → chunk-7IYUO2KC.js.map} +0 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { answered, outboundResultOf, type AdapterCallContext } from "../core/adapter";
|
|
2
|
+
import type {
|
|
3
|
+
DisputeAlternative,
|
|
4
|
+
DisputeAnswer,
|
|
5
|
+
DisputeAnswerResult,
|
|
6
|
+
DisputeFailureCode,
|
|
7
|
+
DisputeItem,
|
|
8
|
+
DisputeOutcome,
|
|
9
|
+
DisputeReason,
|
|
10
|
+
MarketplaceDisputeApi,
|
|
11
|
+
NormalizedDisputeEvent,
|
|
12
|
+
} from "../core/dispute-port";
|
|
13
|
+
import { asString, firstDate, firstString, pick } from "../core/payload-read";
|
|
14
|
+
import { IFOOD_API, withIfoodToken } from "./outbound";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* iFood's Negotiation Platform ("Plataforma de Negociação", handshake
|
|
18
|
+
* disputes; FUT-6099): the events that open and close a dispute, and the
|
|
19
|
+
* three answers.
|
|
20
|
+
*
|
|
21
|
+
* ESTIMATED, every name in this file. iFood's developer portal answers 403
|
|
22
|
+
* behind Cloudflare to our reader (2026-12-02, curl and WebFetch), so the
|
|
23
|
+
* shapes below are the ones four independent public write-ups of iFood's
|
|
24
|
+
* handshake guide agree on, not read off iFood's page. They sit in this one
|
|
25
|
+
* file so the homologation run corrects one place:
|
|
26
|
+
* - `HANDSHAKE_DISPUTE` (HSD) opens, `HANDSHAKE_SETTLEMENT` (HSS) closes, each
|
|
27
|
+
* naming the order (`orderId`) and carrying the dispute in `metadata`;
|
|
28
|
+
* - money is `{ value, currency }` with `value` in CENTS (a string or a number);
|
|
29
|
+
* - `POST /order/v1.0/disputes/{disputeId}/accept` and `/reject` (`{ reason }`);
|
|
30
|
+
* - the proposal: `POST …/disputes/{disputeId}/alternatives/{alternativeId}` with
|
|
31
|
+
* `{ type, metadata }` (the sources disagree; the other reading is
|
|
32
|
+
* `POST …/alternative` with the type in the body: ADOPTING §15.3, U1);
|
|
33
|
+
* - whether accept takes a reason (U2): sent only when iFood lists accept
|
|
34
|
+
* reasons for the dispute, the first of them.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
const DISPUTE_OPENED = new Set(["HSD", "HANDSHAKE_DISPUTE"]);
|
|
38
|
+
const DISPUTE_SETTLED = new Set(["HSS", "HANDSHAKE_SETTLEMENT"]);
|
|
39
|
+
const OUTCOMES: ReadonlySet<string> = new Set<DisputeOutcome>(["ACCEPTED", "REJECTED", "EXPIRED", "ALTERNATIVE_REPLIED"]);
|
|
40
|
+
|
|
41
|
+
/** `{ value }` in cents (a string or a number), or a bare value; null when not a whole number. */
|
|
42
|
+
function centsOf(money: unknown): number | null {
|
|
43
|
+
const raw = typeof money === "object" && money !== null ? pick(money, "value") : money;
|
|
44
|
+
const numeric = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : raw;
|
|
45
|
+
return typeof numeric === "number" && Number.isInteger(numeric) && numeric >= 0 ? numeric : null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function listOf(source: unknown, key: string): unknown[] {
|
|
49
|
+
const value = pick(source, key);
|
|
50
|
+
return Array.isArray(value) ? value : [];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A reason as iFood lists it: a bare code, or `{ code | reason, description }`. */
|
|
54
|
+
function readReason(entry: unknown): DisputeReason[] {
|
|
55
|
+
if (typeof entry === "string") return entry ? [{ code: entry, description: entry }] : [];
|
|
56
|
+
const code = firstString(entry, [["code"], ["reason"], ["id"]]);
|
|
57
|
+
if (!code) return [];
|
|
58
|
+
return [{ code, description: firstString(entry, [["description"], ["label"], ["name"]]) ?? code }];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function readItem(entry: unknown): DisputeItem[] {
|
|
62
|
+
const name = firstString(entry, [["name"], ["description"]]);
|
|
63
|
+
if (!name) return [];
|
|
64
|
+
const quantity = Number(pick(entry, "quantity") ?? 1);
|
|
65
|
+
return [
|
|
66
|
+
{
|
|
67
|
+
name,
|
|
68
|
+
quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,
|
|
69
|
+
amountCents: centsOf(pick(entry, "amount")) ?? centsOf(pick(entry, "totalPrice")),
|
|
70
|
+
},
|
|
71
|
+
];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const ALTERNATIVE_TYPES: ReadonlySet<string> = new Set(["REFUND", "BENEFIT", "ADDITIONAL_TIME"]);
|
|
75
|
+
|
|
76
|
+
function readAlternative(entry: unknown): DisputeAlternative[] {
|
|
77
|
+
const id = firstString(entry, [["id"]]);
|
|
78
|
+
const type = firstString(entry, [["type"]])?.toUpperCase();
|
|
79
|
+
if (!id || !type || !ALTERNATIVE_TYPES.has(type)) return [];
|
|
80
|
+
const metadata = pick(entry, "metadata");
|
|
81
|
+
const stated = pick(metadata, "maxAmount");
|
|
82
|
+
const maxAmountCents = centsOf(stated);
|
|
83
|
+
// A cap iFood stated and we cannot read is never "no cap": the alternative is not offered.
|
|
84
|
+
if (stated !== undefined && stated !== null && maxAmountCents === null) return [];
|
|
85
|
+
const minutes = listOf(metadata, "allowedsAdditionalTimeInMinutes")
|
|
86
|
+
.map(Number)
|
|
87
|
+
.filter((value) => Number.isInteger(value) && value > 0);
|
|
88
|
+
return [
|
|
89
|
+
{
|
|
90
|
+
id,
|
|
91
|
+
type: type as DisputeAlternative["type"],
|
|
92
|
+
maxAmountCents,
|
|
93
|
+
allowedMinutes: minutes,
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The https photos the buyer sent; any other scheme is dropped. */
|
|
99
|
+
function readEvidences(metadata: unknown): string[] {
|
|
100
|
+
return listOf(metadata, "evidences")
|
|
101
|
+
.map((entry) => (typeof entry === "string" ? entry : asString(pick(entry, "url"))))
|
|
102
|
+
.filter((url): url is string => typeof url === "string" && url.startsWith("https://"));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function sumOf(items: readonly DisputeItem[]): number | null {
|
|
106
|
+
const amounts = items.map((item) => item.amountCents);
|
|
107
|
+
return amounts.length > 0 && amounts.every((value) => value !== null) ? amounts.reduce((a, b) => a! + b!, 0) : null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function readOpened(payload: unknown, metadata: unknown, disputeId: string): NormalizedDisputeEvent {
|
|
111
|
+
const items = listOf(metadata, "garnishItems").flatMap(readItem);
|
|
112
|
+
return {
|
|
113
|
+
kind: "opened",
|
|
114
|
+
dispute: {
|
|
115
|
+
disputeId,
|
|
116
|
+
action: firstString(metadata, [["action"]]) ?? "UNKNOWN",
|
|
117
|
+
handshakeType: firstString(metadata, [["handshakeType"]]),
|
|
118
|
+
reason: firstString(metadata, [["reason"], ["handshakeGroup"]]),
|
|
119
|
+
message: firstString(metadata, [["message"]]),
|
|
120
|
+
evidenceUrls: readEvidences(metadata),
|
|
121
|
+
items,
|
|
122
|
+
requestedAmountCents: centsOf(pick(metadata, "amount")) ?? sumOf(items),
|
|
123
|
+
expiresAt: firstDate(metadata, [["expiresAt"]]),
|
|
124
|
+
openedAt: firstDate(metadata, [["createdAt"]]) ?? firstDate(payload, [["createdAt"]]),
|
|
125
|
+
timeoutAction: firstString(metadata, [["timeoutAction"]]),
|
|
126
|
+
alternatives: listOf(metadata, "alternatives").flatMap(readAlternative),
|
|
127
|
+
rejectReasons: listOf(metadata, "negotiationReasons").flatMap(readReason),
|
|
128
|
+
acceptReasons: listOf(metadata, "acceptCancellationReasons").flatMap(readReason),
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function readSettled(payload: unknown, metadata: unknown, disputeId: string): NormalizedDisputeEvent {
|
|
134
|
+
const status = firstString(metadata, [["status"]])?.toUpperCase() ?? "";
|
|
135
|
+
const selected = pick(metadata, "selectedDisputeAlternative");
|
|
136
|
+
return {
|
|
137
|
+
kind: "settled",
|
|
138
|
+
settlement: {
|
|
139
|
+
disputeId,
|
|
140
|
+
outcome: OUTCOMES.has(status) ? (status as DisputeOutcome) : "OTHER",
|
|
141
|
+
at: firstDate(metadata, [["createdAt"]]) ?? firstDate(payload, [["createdAt"]]),
|
|
142
|
+
amountCents: centsOf(pick(selected, "metadata", "amount")) ?? centsOf(pick(metadata, "amount")),
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The dispute an iFood delivery opens or closes, or null for any other event. */
|
|
148
|
+
export function readIfoodDispute(payload: unknown, eventType: string): NormalizedDisputeEvent | null {
|
|
149
|
+
const code = eventType.toUpperCase();
|
|
150
|
+
const opened = DISPUTE_OPENED.has(code);
|
|
151
|
+
if (!opened && !DISPUTE_SETTLED.has(code)) return null;
|
|
152
|
+
const metadata = pick(payload, "metadata");
|
|
153
|
+
const disputeId = firstString(metadata, [["disputeId"], ["id"]]);
|
|
154
|
+
if (!disputeId) return null;
|
|
155
|
+
return opened ? readOpened(payload, metadata, disputeId) : readSettled(payload, metadata, disputeId);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The path and body of one answer. */
|
|
159
|
+
function requestOf(answer: DisputeAnswer): { path: string; body: unknown } {
|
|
160
|
+
if (answer.kind === "ACCEPT") return { path: "accept", body: answer.reasonCode ? { reason: answer.reasonCode } : undefined };
|
|
161
|
+
if (answer.kind === "REJECT") return { path: "reject", body: { reason: answer.reasonCode } };
|
|
162
|
+
const { alternative } = answer;
|
|
163
|
+
const metadata =
|
|
164
|
+
alternative.type === "ADDITIONAL_TIME"
|
|
165
|
+
? { additionalTimeInMinutes: answer.minutes }
|
|
166
|
+
: { amount: { value: String(answer.amountCents), currency: "BRL" } };
|
|
167
|
+
return { path: `alternatives/${encodeURIComponent(alternative.id)}`, body: { type: alternative.type, metadata } };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** iFood's refusal codes, as the engine names them; any other final 4xx is REFUSED. */
|
|
171
|
+
const FAILURE_OF: readonly [string, DisputeFailureCode][] = [
|
|
172
|
+
["DISPUTE_ALREADY_ANSWERED", "ALREADY_ANSWERED"],
|
|
173
|
+
["DISPUTE_NOT_FOUND", "NOT_FOUND"],
|
|
174
|
+
["INVALID_REASON", "INVALID_REASON"],
|
|
175
|
+
["INVALID_AMOUNT", "INVALID_AMOUNT"],
|
|
176
|
+
];
|
|
177
|
+
|
|
178
|
+
function failureOf(status: number, message: string): DisputeFailureCode {
|
|
179
|
+
const named = FAILURE_OF.find(([code]) => message.includes(code));
|
|
180
|
+
if (named) return named[1];
|
|
181
|
+
if (status === 422) return "ALREADY_ANSWERED";
|
|
182
|
+
return status === 404 ? "NOT_FOUND" : "REFUSED";
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Send one answer. */
|
|
186
|
+
async function answerIfoodDispute(
|
|
187
|
+
ctx: AdapterCallContext,
|
|
188
|
+
target: { externalOrderId: string; disputeId: string },
|
|
189
|
+
answer: DisputeAnswer,
|
|
190
|
+
): Promise<DisputeAnswerResult> {
|
|
191
|
+
const { path, body } = requestOf(answer);
|
|
192
|
+
const result = await answered(async () => {
|
|
193
|
+
const response = await withIfoodToken(ctx, (token) =>
|
|
194
|
+
ctx.http({
|
|
195
|
+
method: "POST",
|
|
196
|
+
url: `${IFOOD_API}/order/v1.0/disputes/${encodeURIComponent(target.disputeId)}/${path}`,
|
|
197
|
+
headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
|
|
198
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
199
|
+
}),
|
|
200
|
+
);
|
|
201
|
+
if (response === null) return { kind: "retry", reason: "iFood refused the token" };
|
|
202
|
+
return "kind" in response ? response : outboundResultOf(response);
|
|
203
|
+
});
|
|
204
|
+
if (result.kind !== "refused") return result;
|
|
205
|
+
return { kind: "refused", status: result.status, message: result.message, code: result.own ? "REFUSED" : failureOf(result.status, result.message) };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** iFood's disputes API. */
|
|
209
|
+
export const IFOOD_DISPUTES: MarketplaceDisputeApi = { answer: answerIfoodDispute };
|
package/src/ifood/index.ts
CHANGED
|
@@ -3,7 +3,9 @@ import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
|
|
|
3
3
|
import { IFOOD_CATALOGUE } from "./catalogue";
|
|
4
4
|
import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
|
|
5
5
|
import { IFOOD_COURIER } from "./courier";
|
|
6
|
+
import { IFOOD_DISPUTES } from "./disputes";
|
|
6
7
|
import { ifoodFetchOrder } from "./fetch-order";
|
|
8
|
+
import { IFOOD_APP_LINKING } from "./app-linking";
|
|
7
9
|
import { IFOOD_LINKING } from "./linking";
|
|
8
10
|
import { normalizeIfoodEvent, readIfoodPresence, verifyIfoodSignature } from "./normalize";
|
|
9
11
|
import {
|
|
@@ -85,6 +87,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
85
87
|
marketplaceConfirms: true,
|
|
86
88
|
// A step is told only once iFood took the confirm (FUT-5673).
|
|
87
89
|
statusAfterConfirm: true,
|
|
90
|
+
// The Negotiation Platform (FUT-6099): HSD / HSS events, answered through `disputes`.
|
|
91
|
+
disputes: true,
|
|
88
92
|
},
|
|
89
93
|
normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
|
|
90
94
|
readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
|
|
@@ -107,10 +111,16 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
107
111
|
orderCancellationReasons: ifoodOrderCancellationReasons,
|
|
108
112
|
// The Merchant API's interruptions: an id and an end per closure (FUT-4851).
|
|
109
113
|
availability: IFOOD_AVAILABILITY,
|
|
110
|
-
// The
|
|
114
|
+
// The CENTRALIZED app (FUT-5798): a store authorizes the software's app on the portal and picks
|
|
115
|
+
// its store from the app's list; iFood's webhook serves centralized apps only. It wins at every
|
|
116
|
+
// entry point. The distributed half (FUT-5613) stays declared: a store linked through it keeps
|
|
117
|
+
// refreshing its own token until it links again.
|
|
118
|
+
appLinking: IFOOD_APP_LINKING,
|
|
111
119
|
linking: IFOOD_LINKING,
|
|
112
120
|
// iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).
|
|
113
121
|
courier: IFOOD_COURIER,
|
|
122
|
+
// The buyer's disputes: accept, reject with iFood's reason, or one of its alternatives (FUT-6099).
|
|
123
|
+
disputes: IFOOD_DISPUTES,
|
|
114
124
|
// No per-order deep link is known, so the portal, where a live order is
|
|
115
125
|
// on the first screen.
|
|
116
126
|
appLink: () => IFOOD_PORTAL_URL,
|
|
@@ -123,6 +133,7 @@ export { ifoodFetchOrder } from "./fetch-order";
|
|
|
123
133
|
export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
|
|
124
134
|
export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
|
|
125
135
|
export { IFOOD_LINKING } from "./linking";
|
|
136
|
+
export { IFOOD_APP_LINKING, IFOOD_APPS_PORTAL_URL, ifoodAddressLine } from "./app-linking";
|
|
126
137
|
export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
|
|
127
138
|
export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
|
|
128
139
|
export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
|
package/src/ifood/normalize.ts
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
verifyHmacSha256Hex,
|
|
22
22
|
} from "../core/payload-read";
|
|
23
23
|
import { readIfoodCourierEvent } from "./courier";
|
|
24
|
+
import { readIfoodDispute } from "./disputes";
|
|
24
25
|
import { readIfoodAdditionalFees, readIfoodBuyerDocument, readIfoodOptions, readIfoodPayments } from "./order-details";
|
|
25
26
|
|
|
26
27
|
/**
|
|
@@ -323,6 +324,8 @@ export function normalizeIfoodEvent(
|
|
|
323
324
|
...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
|
|
324
325
|
...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
|
|
325
326
|
...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),
|
|
327
|
+
// The Negotiation Platform's HSD / HSS (FUT-6099): a dispute opened or closed, never an order body.
|
|
328
|
+
...optional("dispute", readIfoodDispute(payload, eventType) ?? undefined),
|
|
326
329
|
};
|
|
327
330
|
}
|
|
328
331
|
|
package/src/index.ts
CHANGED
|
@@ -162,6 +162,37 @@ export type {
|
|
|
162
162
|
PickupCodeValidation,
|
|
163
163
|
ValidatePickupCodeInput,
|
|
164
164
|
} from "./core/courier-port";
|
|
165
|
+
export type {
|
|
166
|
+
DisputeAlternative,
|
|
167
|
+
DisputeAlternativeType,
|
|
168
|
+
DisputeAnswer,
|
|
169
|
+
DisputeAnswerResult,
|
|
170
|
+
DisputeFailureCode,
|
|
171
|
+
DisputeItem,
|
|
172
|
+
DisputeOutcome,
|
|
173
|
+
DisputeReason,
|
|
174
|
+
MarketplaceDisputeApi,
|
|
175
|
+
MarketplaceDisputeChange,
|
|
176
|
+
MarketplaceDisputeDelegate,
|
|
177
|
+
NormalizedDisputeEvent,
|
|
178
|
+
NormalizedDisputeOpened,
|
|
179
|
+
NormalizedDisputeSettled,
|
|
180
|
+
} from "./core/dispute-port";
|
|
181
|
+
export {
|
|
182
|
+
MARKETPLACE_DISPUTE_ANSWER_JOB,
|
|
183
|
+
disputeView,
|
|
184
|
+
type DisputeAnswerView,
|
|
185
|
+
type DisputeRow,
|
|
186
|
+
type DisputeStatus,
|
|
187
|
+
type MarketplaceDisputeView,
|
|
188
|
+
} from "./core/dispute-store";
|
|
189
|
+
export type { AnswerDisputeResult, DisputeAnswerInput, DisputeRefusalCode } from "./core/disputes";
|
|
190
|
+
export type { MarketplaceDisputeEngine } from "./core/dispute-engine";
|
|
191
|
+
export {
|
|
192
|
+
DisputeAnswerRetryError,
|
|
193
|
+
type DisputeAnswerJobPayload,
|
|
194
|
+
type DisputeAnswerOutcome,
|
|
195
|
+
} from "./core/dispute-job";
|
|
165
196
|
export {
|
|
166
197
|
FetchOrderRetryError,
|
|
167
198
|
MARKETPLACE_FETCH_ORDER_JOB,
|
|
@@ -261,14 +292,17 @@ export {
|
|
|
261
292
|
} from "./core/pause-store";
|
|
262
293
|
export type { AvailabilitySweepResult } from "./core/pause-sweep";
|
|
263
294
|
export type {
|
|
295
|
+
AppLinkCallContext,
|
|
264
296
|
LinkCallContext,
|
|
265
297
|
LinkCode,
|
|
266
298
|
LinkGrant,
|
|
267
299
|
LinkResult,
|
|
268
300
|
LinkedMerchant,
|
|
269
301
|
MarketplaceAppCredentialsPort,
|
|
302
|
+
MarketplaceAppLinking,
|
|
270
303
|
MarketplaceLinkAttemptDelegate,
|
|
271
304
|
MarketplaceLinking,
|
|
272
305
|
} from "./core/linking-port";
|
|
306
|
+
export { MARKETPLACE_LINK_CHECK_JOB, ATTEMPT_MINUTES as LINK_ATTEMPT_MINUTES, CHECK_EVERY_SECONDS as LINK_CHECK_EVERY_SECONDS, type AppLinkPendingView } from "./core/app-linking";
|
|
273
307
|
export type { LinkFailure, LinkFinished, LinkPendingView, LinkRefusalCode } from "./core/linking";
|
|
274
308
|
export type { MarketplaceAuthMode } from "./core/link-store";
|
package/src/server/jobs.ts
CHANGED
|
@@ -8,10 +8,11 @@ import { CancellationReasonsRetryError, type CancellationReasonsJobPayload } fro
|
|
|
8
8
|
import { OutboundRetryError } from "../core/outbound";
|
|
9
9
|
import type { OutboundJobPayload } from "../core/outbound-queue";
|
|
10
10
|
import { AvailabilityRetryError } from "../core/pause-job";
|
|
11
|
+
import { DisputeAnswerRetryError, type DisputeAnswerJobPayload } from "../core/dispute-job";
|
|
11
12
|
import type { AvailabilityJobPayload } from "../core/pause-store";
|
|
12
13
|
|
|
13
14
|
/**
|
|
14
|
-
* The engine's
|
|
15
|
+
* The engine's eleven jobs, declared here because every number in them is the
|
|
15
16
|
* engine's knowledge, not a host's:
|
|
16
17
|
*
|
|
17
18
|
* - `expire-acceptances`, every minute: the unit being measured is minutes (a
|
|
@@ -42,6 +43,9 @@ import type { AvailabilityJobPayload } from "../core/pause-store";
|
|
|
42
43
|
* - `availability`, on demand: brings one marketplace in line with the host's
|
|
43
44
|
* last pause or resume ask for one store (FUT-4851). Three attempts with
|
|
44
45
|
* backoff; the last one stamps FAILED with a failure code.
|
|
46
|
+
* - `dispute-answer`, on demand: sends one store's answer to a buyer's
|
|
47
|
+
* dispute (FUT-6099). Three attempts with backoff; the last gives the
|
|
48
|
+
* answer back OPEN, and the outbound sweep re-queues one still owed.
|
|
45
49
|
* - `availability-sweep`, every five minutes: resumes a pause past its
|
|
46
50
|
* `until` (the host stopped renewing it), re-queues an ask still owed, and
|
|
47
51
|
* gives up on one older than a day.
|
|
@@ -53,8 +57,9 @@ import type { AvailabilityJobPayload } from "../core/pause-store";
|
|
|
53
57
|
* `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
|
|
54
58
|
* `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.acknowledge`,
|
|
55
59
|
* `marketplace.cancellation-reasons`, `marketplace.catalogue`,
|
|
56
|
-
* `marketplace.outbound-sweep`, `marketplace.availability
|
|
57
|
-
* `marketplace.availability-sweep
|
|
60
|
+
* `marketplace.outbound-sweep`, `marketplace.availability`,
|
|
61
|
+
* `marketplace.availability-sweep`, `marketplace.link-check` and
|
|
62
|
+
* `marketplace.dispute-answer`.
|
|
58
63
|
*/
|
|
59
64
|
|
|
60
65
|
/** What the host closes over at bind time: the mounted engine. */
|
|
@@ -73,6 +78,8 @@ export interface MarketplaceJobDeps {
|
|
|
73
78
|
| "sweepOutbound"
|
|
74
79
|
| "runAvailability"
|
|
75
80
|
| "sweepAvailability"
|
|
81
|
+
| "sweepLinks"
|
|
82
|
+
| "runDisputeAnswer"
|
|
76
83
|
>;
|
|
77
84
|
}
|
|
78
85
|
|
|
@@ -290,6 +297,45 @@ const availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
|
|
|
290
297
|
},
|
|
291
298
|
};
|
|
292
299
|
|
|
300
|
+
/**
|
|
301
|
+
* `link-check` (FUT-5798), each minute and once more half a minute later
|
|
302
|
+
* (queued by the tick, only while a store waits): every centralized link
|
|
303
|
+
* attempt still waiting asks the app's list, and a store whose authorization
|
|
304
|
+
* arrived is hinted. Never retried: the next pass re-finds it from the rows.
|
|
305
|
+
*/
|
|
306
|
+
const linkCheck: WireJobBlueprint<{ half?: boolean } | undefined, MarketplaceJobDeps> = {
|
|
307
|
+
name: "link-check",
|
|
308
|
+
queue: MARKETPLACE_SWEEP_QUEUE,
|
|
309
|
+
concurrency: 1,
|
|
310
|
+
schedule: { pattern: "* * * * *", timezone: "UTC" },
|
|
311
|
+
attempts: 1,
|
|
312
|
+
lease: { ttlMs: SWEEP_LEASE_MS },
|
|
313
|
+
handle: async (payload, deps, context) => {
|
|
314
|
+
const result = await deps.engine.sweepLinks({ half: payload?.half === true });
|
|
315
|
+
if (result.seen.length === 0) return;
|
|
316
|
+
context.logger.info(`marketplace.link-check: saw the authorization of ${result.seen.length} store(s); ${result.waiting} still waiting.`);
|
|
317
|
+
},
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
/** The dispute answer's attempts: the last one gives the answer back for a person to send again. */
|
|
321
|
+
const MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS = 3;
|
|
322
|
+
|
|
323
|
+
const disputeAnswer: WireJobBlueprint<DisputeAnswerJobPayload, MarketplaceJobDeps> = {
|
|
324
|
+
name: "dispute-answer",
|
|
325
|
+
attempts: MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS,
|
|
326
|
+
// Short: the marketplace's deadline is minutes, and a person waits on the card.
|
|
327
|
+
backoff: { type: "exponential", delayMs: 10_000 },
|
|
328
|
+
handle: async (payload, deps, context) => {
|
|
329
|
+
try {
|
|
330
|
+
const outcome = await deps.engine.runDisputeAnswer(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });
|
|
331
|
+
if (outcome.kind === "skipped") context.logger.info(`marketplace.dispute-answer: ${payload.disputeId} skipped: ${outcome.reason}`);
|
|
332
|
+
} catch (error) {
|
|
333
|
+
if (error instanceof DisputeAnswerRetryError) context.logger.warn(`marketplace.dispute-answer: ${error.message}`);
|
|
334
|
+
throw error;
|
|
335
|
+
}
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
|
|
293
339
|
/** The jobs contribution. */
|
|
294
340
|
export const MARKETPLACE_JOBS = {
|
|
295
341
|
namespace: "marketplace",
|
|
@@ -304,5 +350,7 @@ export const MARKETPLACE_JOBS = {
|
|
|
304
350
|
"outbound-sweep": outboundSweep,
|
|
305
351
|
availability,
|
|
306
352
|
"availability-sweep": availabilitySweep,
|
|
353
|
+
"link-check": linkCheck,
|
|
354
|
+
"dispute-answer": disputeAnswer,
|
|
307
355
|
},
|
|
308
356
|
} as const satisfies JobsContribution<MarketplaceJobDeps>;
|
|
@@ -4,7 +4,15 @@ import type { MarketplaceIntegrationView } from "../core/integration";
|
|
|
4
4
|
import type { LinkFailure, LinkPendingView, LinkRefusalCode } from "../core/linking";
|
|
5
5
|
import { MARKETPLACE_MANAGE } from "./contribution";
|
|
6
6
|
import { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from "./http";
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
cancelLinkBody,
|
|
9
|
+
checkLinkBody,
|
|
10
|
+
finishLinkBody,
|
|
11
|
+
linkMerchantsQuery,
|
|
12
|
+
linkStateQuery,
|
|
13
|
+
selectLinkMerchantBody,
|
|
14
|
+
startLinkBody,
|
|
15
|
+
} from "./mcp-link";
|
|
8
16
|
|
|
9
17
|
/**
|
|
10
18
|
* Linking a store through the software's own marketplace app (FUT-5613), as
|
|
@@ -14,7 +22,9 @@ import { finishLinkBody, linkMerchantsQuery, linkStateQuery, selectLinkMerchantB
|
|
|
14
22
|
* - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);
|
|
15
23
|
* - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;
|
|
16
24
|
* - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;
|
|
17
|
-
* - `PUT …/marketplace/link/merchant` — which of them this store is
|
|
25
|
+
* - `PUT …/marketplace/link/merchant` — which of them this store is;
|
|
26
|
+
* - `POST …/marketplace/link/check` — centralized linking (FUT-5798): ask the app's list now;
|
|
27
|
+
* - `POST …/marketplace/link/cancel` — Cancelar: end the linking in progress.
|
|
18
28
|
*
|
|
19
29
|
* No answer ever carries a token, a verifier or the app's credentials.
|
|
20
30
|
*/
|
|
@@ -45,7 +55,15 @@ function failed(config: MarketplaceApiConfig, failure: LinkFailure): WireRespons
|
|
|
45
55
|
});
|
|
46
56
|
}
|
|
47
57
|
|
|
48
|
-
const pendingOut = (pending: LinkPendingView | null) =>
|
|
58
|
+
const pendingOut = (pending: LinkPendingView | null) =>
|
|
59
|
+
pending
|
|
60
|
+
? {
|
|
61
|
+
...pending,
|
|
62
|
+
expiresAt: pending.expiresAt.toISOString(),
|
|
63
|
+
...(pending.seenAt === undefined ? {} : { seenAt: iso(pending.seenAt) }),
|
|
64
|
+
...(pending.checkedAt === undefined ? {} : { checkedAt: iso(pending.checkedAt) }),
|
|
65
|
+
}
|
|
66
|
+
: null;
|
|
49
67
|
|
|
50
68
|
function connectionOut(row: MarketplaceIntegrationView) {
|
|
51
69
|
return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };
|
|
@@ -127,10 +145,44 @@ function writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[
|
|
|
127
145
|
if (!parsed.ok) return parsed.response;
|
|
128
146
|
const refusal = unknown(config, parsed.value.provider);
|
|
129
147
|
if (refusal) return refusal;
|
|
130
|
-
const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, ...parsed.value });
|
|
148
|
+
const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });
|
|
131
149
|
return result.kind === "selected" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);
|
|
132
150
|
},
|
|
133
151
|
},
|
|
152
|
+
...appRoutes(config),
|
|
153
|
+
];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Centralized linking (FUT-5798): the manual check, and Cancelar. */
|
|
157
|
+
function appRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
|
|
158
|
+
const { engine, copy } = config;
|
|
159
|
+
return [
|
|
160
|
+
{
|
|
161
|
+
method: "POST",
|
|
162
|
+
path: `${BASE}/check`,
|
|
163
|
+
permission: MARKETPLACE_MANAGE,
|
|
164
|
+
handle: async ({ actor, body }) => {
|
|
165
|
+
const parsed = parse(checkLinkBody, body, copy);
|
|
166
|
+
if (!parsed.ok) return parsed.response;
|
|
167
|
+
const refusal = unknown(config, parsed.value.provider);
|
|
168
|
+
if (refusal) return refusal;
|
|
169
|
+
const result = await engine.checkLink({ clientId: actor.clientId, provider: parsed.value.provider });
|
|
170
|
+
return result.kind === "checked" ? ok({ pending: pendingOut(result.pending), merchants: result.merchants }) : failed(config, result);
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
method: "POST",
|
|
175
|
+
path: `${BASE}/cancel`,
|
|
176
|
+
permission: MARKETPLACE_MANAGE,
|
|
177
|
+
handle: async ({ actor, body }) => {
|
|
178
|
+
const parsed = parse(cancelLinkBody, body, copy);
|
|
179
|
+
if (!parsed.ok) return parsed.response;
|
|
180
|
+
const refusal = unknown(config, parsed.value.provider);
|
|
181
|
+
if (refusal) return refusal;
|
|
182
|
+
await engine.cancelLink({ clientId: actor.clientId, provider: parsed.value.provider });
|
|
183
|
+
return ok({ cancelled: true });
|
|
184
|
+
},
|
|
185
|
+
},
|
|
134
186
|
];
|
|
135
187
|
}
|
|
136
188
|
|
package/src/server/mcp-link.ts
CHANGED
|
@@ -23,6 +23,10 @@ export const finishLinkBody = z.strictObject({
|
|
|
23
23
|
});
|
|
24
24
|
/** The marketplace stores a linked connection's grant covers. */
|
|
25
25
|
export const linkMerchantsQuery = z.strictObject({ provider });
|
|
26
|
+
/** Centralized linking (FUT-5798): ask the app's list now. */
|
|
27
|
+
export const checkLinkBody = z.strictObject({ provider });
|
|
28
|
+
/** Cancelar: end the linking in progress. */
|
|
29
|
+
export const cancelLinkBody = z.strictObject({ provider });
|
|
26
30
|
/** Which of them this store is. */
|
|
27
31
|
export const selectLinkMerchantBody = z.strictObject({ provider, merchantId: z.string().trim().min(1).max(200) });
|
|
28
32
|
|
|
@@ -31,13 +35,22 @@ const pendingSchema = z.object({
|
|
|
31
35
|
verificationUrl: z.string(),
|
|
32
36
|
verificationUrlComplete: z.string(),
|
|
33
37
|
expiresAt: z.string(),
|
|
38
|
+
mode: z.enum(["code", "app"]).optional(),
|
|
39
|
+
seenAt: z.string().nullable().optional(),
|
|
40
|
+
checkedAt: z.string().nullable().optional(),
|
|
34
41
|
});
|
|
35
42
|
|
|
36
|
-
const merchantSchema = z.object({
|
|
43
|
+
const merchantSchema = z.object({
|
|
44
|
+
id: z.string(),
|
|
45
|
+
name: z.string().nullable(),
|
|
46
|
+
corporateName: z.string().nullable(),
|
|
47
|
+
address: z.string().nullable().optional(),
|
|
48
|
+
taken: z.boolean().optional(),
|
|
49
|
+
});
|
|
37
50
|
|
|
38
51
|
const BASE = "/admin/{tenantSlug}/marketplace/link";
|
|
39
52
|
|
|
40
|
-
/** The five linking tools, over the connection schema the connection tools answer. */
|
|
53
|
+
/** The five code-flow linking tools, over the connection schema the connection tools answer. */
|
|
41
54
|
export function marketplaceLinkTools<P extends z.ZodType, I extends z.ZodType>(params: P, integration: I) {
|
|
42
55
|
return [
|
|
43
56
|
{
|
|
@@ -101,3 +114,32 @@ export function marketplaceLinkTools<P extends z.ZodType, I extends z.ZodType>(p
|
|
|
101
114
|
},
|
|
102
115
|
] as const satisfies readonly WireMcpTool<z.ZodType>[];
|
|
103
116
|
}
|
|
117
|
+
|
|
118
|
+
/** The centralized app's two tools (FUT-5798): ask the list now, and Cancelar. */
|
|
119
|
+
export function marketplaceAppLinkTools<P extends z.ZodType>(params: P) {
|
|
120
|
+
return [
|
|
121
|
+
{
|
|
122
|
+
operationId: "checkMarketplaceLink",
|
|
123
|
+
method: "POST",
|
|
124
|
+
path: `${BASE}/check`,
|
|
125
|
+
summary:
|
|
126
|
+
"Ask the marketplace now, in one call, which stores the software's centralized app is authorized for (each `taken` when another store's connection holds it, with its address), and renew the linking in progress; `pending.seenAt` says when a store to pick first appeared. 409 UNAVAILABLE for a marketplace that links with a code.",
|
|
127
|
+
tags: ["marketplace"],
|
|
128
|
+
params,
|
|
129
|
+
body: checkLinkBody,
|
|
130
|
+
response: z.object({ data: z.object({ pending: pendingSchema.nullable(), merchants: z.array(merchantSchema) }) }),
|
|
131
|
+
annotations: { readOnly: false, destructive: false, openWorld: true },
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
operationId: "cancelMarketplaceLink",
|
|
135
|
+
method: "POST",
|
|
136
|
+
path: `${BASE}/cancel`,
|
|
137
|
+
summary: "End a store's linking in progress in one call (Cancelar). A connection already linked stays as it is.",
|
|
138
|
+
tags: ["marketplace"],
|
|
139
|
+
params,
|
|
140
|
+
body: cancelLinkBody,
|
|
141
|
+
response: z.object({ data: z.object({ cancelled: z.literal(true) }) }),
|
|
142
|
+
annotations: { readOnly: false, destructive: false, openWorld: false },
|
|
143
|
+
},
|
|
144
|
+
] as const satisfies readonly WireMcpTool<z.ZodType>[];
|
|
145
|
+
}
|
package/src/server/mcp.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
|
|
3
3
|
import type { WireMcpTool } from "@12-apps/wiring";
|
|
4
4
|
|
|
5
|
-
import { marketplaceLinkTools } from "./mcp-link";
|
|
5
|
+
import { marketplaceAppLinkTools, marketplaceLinkTools } from "./mcp-link";
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* The marketplace tool surface — authored ONCE, beside the route descriptors
|
|
@@ -314,4 +314,5 @@ export const MARKETPLACE_MCP_TOOLS = [
|
|
|
314
314
|
annotations: { readOnly: false, destructive: true, openWorld: true },
|
|
315
315
|
},
|
|
316
316
|
...marketplaceLinkTools(marketplaceParams, integrationSchema),
|
|
317
|
+
...marketplaceAppLinkTools(marketplaceParams),
|
|
317
318
|
] as const satisfies readonly WireMcpTool<z.ZodType>[];
|
|
@@ -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 * 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":[]}
|