@12-apps/marketplace 1.1.0 → 1.3.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 +37 -7
- package/README.md +238 -4
- package/dist/99food/en-US.d.ts +19 -0
- package/dist/99food/en-US.js +23 -0
- package/dist/99food/en-US.js.map +1 -0
- package/dist/99food/index.d.ts +162 -0
- package/dist/99food/index.js +444 -0
- package/dist/99food/index.js.map +1 -0
- package/dist/99food/pt-BR.d.ts +23 -0
- package/dist/99food/pt-BR.js +23 -0
- package/dist/99food/pt-BR.js.map +1 -0
- package/dist/{adapter-BggtVFf9.d.ts → adapter-0l_EmuJA.d.ts} +206 -2
- package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
- package/dist/chunk-AYYBRQJV.js.map +1 -0
- package/dist/chunk-BD7DS3XM.js +78 -0
- package/dist/chunk-BD7DS3XM.js.map +1 -0
- package/dist/chunk-M2V4RFMA.js +23 -0
- package/dist/chunk-M2V4RFMA.js.map +1 -0
- package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
- package/dist/chunk-RVBTARIY.js.map +1 -0
- package/dist/chunk-XUAFXNOH.js +1604 -0
- package/dist/chunk-XUAFXNOH.js.map +1 -0
- package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +16 -12
- package/dist/ifood/index.js +248 -121
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +30 -4
- package/dist/index.js +189 -346
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +4 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/en-US.d.ts +14 -0
- package/dist/rappi/en-US.js +18 -0
- package/dist/rappi/en-US.js.map +1 -0
- package/dist/rappi/index.d.ts +190 -0
- package/dist/rappi/index.js +359 -0
- package/dist/rappi/index.js.map +1 -0
- package/dist/rappi/pt-BR.d.ts +18 -0
- package/dist/rappi/pt-BR.js +18 -0
- package/dist/rappi/pt-BR.js.map +1 -0
- package/dist/server/index.d.ts +19 -8
- package/dist/server/index.js +4 -2
- package/package.json +26 -2
- package/prisma/marketplace.prisma +97 -2
- package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
- package/src/99food/catalogue.ts +117 -0
- package/src/99food/copy.ts +36 -0
- package/src/99food/en-US.ts +19 -0
- package/src/99food/index.ts +125 -0
- package/src/99food/normalize.ts +263 -0
- package/src/99food/outbound.ts +220 -0
- package/src/99food/pt-BR.ts +23 -0
- package/src/core/adapter.ts +27 -2
- package/src/core/catalogue-category.ts +119 -0
- package/src/core/catalogue-ids.ts +23 -0
- package/src/core/catalogue-job.ts +332 -0
- package/src/core/catalogue-port.ts +173 -0
- package/src/core/catalogue-store.ts +172 -0
- package/src/core/catalogue-sweep.ts +43 -0
- package/src/core/catalogue.ts +226 -0
- package/src/core/decisions.ts +16 -4
- package/src/core/engine.ts +54 -0
- package/src/core/fetch-order.ts +253 -0
- package/src/core/inbox.ts +8 -2
- package/src/core/ingest.ts +10 -2
- package/src/core/integration.ts +30 -1
- package/src/core/order-fetch-marks.ts +63 -0
- package/src/core/outbound-sweep.ts +7 -2
- package/src/core/outbound.ts +22 -2
- package/src/core/payload-read.ts +101 -0
- package/src/core/pipeline.ts +64 -15
- package/src/core/ports.ts +36 -0
- package/src/core/types.ts +14 -0
- package/src/ifood/catalogue.ts +273 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/normalize.ts +15 -88
- package/src/ifood/outbound.ts +9 -6
- package/src/index.ts +49 -1
- package/src/rappi/copy.ts +39 -0
- package/src/rappi/en-US.ts +14 -0
- package/src/rappi/index.ts +161 -0
- package/src/rappi/normalize.ts +314 -0
- package/src/rappi/outbound.ts +182 -0
- package/src/rappi/pt-BR.ts +18 -0
- package/src/server/index.ts +1 -0
- package/src/server/jobs.ts +71 -8
- package/dist/chunk-7BYVGNU5.js.map +0 -1
- package/dist/chunk-DVIRN42O.js +0 -707
- package/dist/chunk-DVIRN42O.js.map +0 -1
- package/dist/chunk-NGNEL4HS.js.map +0 -1
package/dist/ifood/index.js
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
|
+
import {
|
|
2
|
+
stableUuid
|
|
3
|
+
} from "../chunk-M2V4RFMA.js";
|
|
4
|
+
import {
|
|
5
|
+
asString,
|
|
6
|
+
firstCents,
|
|
7
|
+
firstDate,
|
|
8
|
+
firstString,
|
|
9
|
+
pick,
|
|
10
|
+
verifyHmacSha256Hex
|
|
11
|
+
} from "../chunk-BD7DS3XM.js";
|
|
1
12
|
import {
|
|
2
13
|
answered,
|
|
3
14
|
outboundResultOf
|
|
4
|
-
} from "../chunk-
|
|
15
|
+
} from "../chunk-RVBTARIY.js";
|
|
5
16
|
import {
|
|
6
17
|
__name
|
|
7
18
|
} from "../chunk-7QVYU63E.js";
|
|
@@ -22,70 +33,248 @@ var IFOOD_REASON_CODES = [
|
|
|
22
33
|
"513"
|
|
23
34
|
];
|
|
24
35
|
|
|
25
|
-
// src/ifood/
|
|
26
|
-
|
|
27
|
-
var
|
|
28
|
-
var
|
|
29
|
-
var
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
36
|
+
// src/ifood/outbound.ts
|
|
37
|
+
var IFOOD_API = "https://merchant-api.ifood.com.br";
|
|
38
|
+
var TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
|
|
39
|
+
var orderUrl = /* @__PURE__ */ __name((externalOrderId, action) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`, "orderUrl");
|
|
40
|
+
var IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
|
|
41
|
+
var TOKEN_MARGIN_MS = 6e4;
|
|
42
|
+
var ifoodTokenKey = /* @__PURE__ */ __name((ctx) => `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`, "ifoodTokenKey");
|
|
43
|
+
function tokenOf(body) {
|
|
44
|
+
try {
|
|
45
|
+
const parsed = JSON.parse(body);
|
|
46
|
+
if (typeof parsed.accessToken !== "string" || parsed.accessToken === "") return null;
|
|
47
|
+
const expires = typeof parsed.expiresIn === "number" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;
|
|
48
|
+
return { token: parsed.accessToken, expiresInSeconds: expires };
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
35
51
|
}
|
|
36
|
-
return cursor;
|
|
37
52
|
}
|
|
38
|
-
__name(
|
|
39
|
-
function
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
return
|
|
53
|
+
__name(tokenOf, "tokenOf");
|
|
54
|
+
async function bearer(ctx) {
|
|
55
|
+
const key = ifoodTokenKey(ctx);
|
|
56
|
+
const cached = ctx.tokens.get(key);
|
|
57
|
+
if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
|
|
58
|
+
const response = await ctx.http({
|
|
59
|
+
method: "POST",
|
|
60
|
+
url: TOKEN_URL,
|
|
61
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
62
|
+
body: new URLSearchParams({
|
|
63
|
+
grantType: "client_credentials",
|
|
64
|
+
clientId: ctx.credentials.clientId,
|
|
65
|
+
clientSecret: ctx.credentials.clientSecret
|
|
66
|
+
}).toString()
|
|
67
|
+
});
|
|
68
|
+
if (response.status < 200 || response.status >= 300) return outboundResultOf(response);
|
|
69
|
+
const token = tokenOf(response.body);
|
|
70
|
+
if (!token) return { kind: "retry", reason: "iFood answered the token grant without a token" };
|
|
71
|
+
ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1e3 });
|
|
72
|
+
return { token: token.token };
|
|
43
73
|
}
|
|
44
|
-
__name(
|
|
45
|
-
function
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
if (
|
|
74
|
+
__name(bearer, "bearer");
|
|
75
|
+
function postOrder(ctx, externalOrderId, action, body) {
|
|
76
|
+
return answered(async () => {
|
|
77
|
+
const auth = await bearer(ctx);
|
|
78
|
+
if (!("token" in auth)) return auth;
|
|
79
|
+
const response = await ctx.http({
|
|
80
|
+
method: "POST",
|
|
81
|
+
url: orderUrl(externalOrderId, action),
|
|
82
|
+
headers: {
|
|
83
|
+
Authorization: `Bearer ${auth.token}`,
|
|
84
|
+
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
|
85
|
+
},
|
|
86
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
87
|
+
});
|
|
88
|
+
if (response.status === 401) ctx.tokens.delete(ifoodTokenKey(ctx));
|
|
89
|
+
return response.status === 401 ? { kind: "retry", reason: "iFood refused the token" } : outboundResultOf(response);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
__name(postOrder, "postOrder");
|
|
93
|
+
function ifoodConfirm(ctx, order) {
|
|
94
|
+
return postOrder(ctx, order.externalOrderId, "confirm");
|
|
95
|
+
}
|
|
96
|
+
__name(ifoodConfirm, "ifoodConfirm");
|
|
97
|
+
function ifoodRequestCancellation(ctx, order, input) {
|
|
98
|
+
return postOrder(ctx, order.externalOrderId, "requestCancellation", {
|
|
99
|
+
reason: input.text === "" ? input.reason.label : input.text,
|
|
100
|
+
cancellationCode: input.reason.code
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
__name(ifoodRequestCancellation, "ifoodRequestCancellation");
|
|
104
|
+
|
|
105
|
+
// src/ifood/catalogue.ts
|
|
106
|
+
var catalogUrl = /* @__PURE__ */ __name((merchantId, path) => `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`, "catalogUrl");
|
|
107
|
+
var ifoodItemId = /* @__PURE__ */ __name((ref) => stableUuid(`${ref}:item`), "ifoodItemId");
|
|
108
|
+
var ifoodProductId = /* @__PURE__ */ __name((ref) => stableUuid(`${ref}:product`), "ifoodProductId");
|
|
109
|
+
var priceOf = /* @__PURE__ */ __name((cents) => ({ value: Math.round(cents) / 100 }), "priceOf");
|
|
110
|
+
async function call(ctx, method, path, body) {
|
|
111
|
+
const auth = await bearer(ctx);
|
|
112
|
+
if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
|
|
113
|
+
const response = await ctx.http({
|
|
114
|
+
method,
|
|
115
|
+
url: catalogUrl(ctx.externalMerchantId, path),
|
|
116
|
+
headers: {
|
|
117
|
+
Authorization: `Bearer ${auth.token}`,
|
|
118
|
+
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
|
119
|
+
},
|
|
120
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
121
|
+
});
|
|
122
|
+
if (response.status !== 401) return response;
|
|
123
|
+
ctx.tokens.delete(ifoodTokenKey(ctx));
|
|
124
|
+
return { kind: "retry", reason: "iFood refused the token" };
|
|
125
|
+
}
|
|
126
|
+
__name(call, "call");
|
|
127
|
+
function failureOf(response) {
|
|
128
|
+
const result = outboundResultOf(response);
|
|
129
|
+
return result.kind === "accepted" ? { kind: "retry", reason: "unexpected answer" } : result;
|
|
130
|
+
}
|
|
131
|
+
__name(failureOf, "failureOf");
|
|
132
|
+
var ok = /* @__PURE__ */ __name((response) => response.status >= 200 && response.status < 300, "ok");
|
|
133
|
+
function parse(body) {
|
|
134
|
+
try {
|
|
135
|
+
return JSON.parse(body);
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
49
138
|
}
|
|
50
|
-
return null;
|
|
51
139
|
}
|
|
52
|
-
__name(
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
140
|
+
__name(parse, "parse");
|
|
141
|
+
function categoryIdIn(body, name) {
|
|
142
|
+
const parsed = parse(body);
|
|
143
|
+
if (!Array.isArray(parsed)) return null;
|
|
144
|
+
const wanted = name.trim().toLowerCase();
|
|
145
|
+
const found = parsed.find(
|
|
146
|
+
(entry) => typeof entry === "object" && entry !== null && String(entry.name ?? "").trim().toLowerCase() === wanted
|
|
147
|
+
);
|
|
148
|
+
return typeof found?.id === "string" ? found.id : null;
|
|
149
|
+
}
|
|
150
|
+
__name(categoryIdIn, "categoryIdIn");
|
|
151
|
+
async function findCategory(ctx, name) {
|
|
152
|
+
const listed = await call(ctx, "GET", "categories");
|
|
153
|
+
if ("kind" in listed) return listed;
|
|
154
|
+
if (!ok(listed)) return failureOf(listed);
|
|
155
|
+
return { id: categoryIdIn(listed.body, name) };
|
|
156
|
+
}
|
|
157
|
+
__name(findCategory, "findCategory");
|
|
158
|
+
async function findOrCreateCategory(ctx, name) {
|
|
159
|
+
const found = await findCategory(ctx, name);
|
|
160
|
+
if ("kind" in found) return found;
|
|
161
|
+
if (found.id) return { id: found.id };
|
|
162
|
+
const created = await call(ctx, "POST", "categories", { name, status: "AVAILABLE", template: "DEFAULT" });
|
|
163
|
+
if ("kind" in created) return created;
|
|
164
|
+
if (!ok(created)) return failureOf(created);
|
|
165
|
+
const id = parse(created.body)?.id;
|
|
166
|
+
if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
|
|
167
|
+
const again = await findCategory(ctx, name);
|
|
168
|
+
return "id" in again && again.id ? { id: again.id } : { id };
|
|
169
|
+
}
|
|
170
|
+
__name(findOrCreateCategory, "findOrCreateCategory");
|
|
171
|
+
var categoryId = /* @__PURE__ */ __name((ctx, name) => ctx.category(name, () => findOrCreateCategory(ctx, name)), "categoryId");
|
|
172
|
+
async function photoFor(ctx, item) {
|
|
173
|
+
const stored = item.storedImage;
|
|
174
|
+
if (item.imageUrl === null) return { image: null };
|
|
175
|
+
if (stored && stored.sourceUrl === item.imageUrl) return { image: stored };
|
|
176
|
+
const bytes = await ctx.loadImage(item.imageUrl);
|
|
177
|
+
return bytes ? upload(ctx, bytes, item.imageUrl) : { image: stored };
|
|
178
|
+
}
|
|
179
|
+
__name(photoFor, "photoFor");
|
|
180
|
+
async function upload(ctx, bytes, sourceUrl) {
|
|
181
|
+
const uploaded = await call(ctx, "POST", "image/upload", { image: `data:${bytes.contentType};base64,${bytes.base64}` });
|
|
182
|
+
if ("kind" in uploaded) return uploaded;
|
|
183
|
+
if (!ok(uploaded)) {
|
|
184
|
+
const failure = failureOf(uploaded);
|
|
185
|
+
if (failure.kind === "retry") return failure;
|
|
186
|
+
return { image: null, warning: uploaded.status === 413 ? "IMAGE_TOO_LARGE" : "IMAGE_REFUSED" };
|
|
57
187
|
}
|
|
58
|
-
|
|
188
|
+
const path = parse(uploaded.body)?.imagePath;
|
|
189
|
+
if (typeof path !== "string") return { kind: "retry", reason: "iFood answered the upload without an imagePath" };
|
|
190
|
+
return { image: { ref: path, sourceUrl } };
|
|
191
|
+
}
|
|
192
|
+
__name(upload, "upload");
|
|
193
|
+
function ifoodItemBody(item, category, image) {
|
|
194
|
+
const itemId = ifoodItemId(item.ref);
|
|
195
|
+
const productId = ifoodProductId(item.ref);
|
|
196
|
+
return {
|
|
197
|
+
item: {
|
|
198
|
+
id: itemId,
|
|
199
|
+
type: "DEFAULT",
|
|
200
|
+
categoryId: category,
|
|
201
|
+
status: "AVAILABLE",
|
|
202
|
+
price: priceOf(item.priceCents),
|
|
203
|
+
externalCode: item.productId,
|
|
204
|
+
// ESTIMATED: the guide's examples link item and product implicitly; the
|
|
205
|
+
// field naming the product is not shown on the pages read.
|
|
206
|
+
productId
|
|
207
|
+
},
|
|
208
|
+
products: [
|
|
209
|
+
{
|
|
210
|
+
id: productId,
|
|
211
|
+
name: item.name,
|
|
212
|
+
description: item.description ?? "",
|
|
213
|
+
externalCode: `${item.productId}-product`,
|
|
214
|
+
// ESTIMATED field name: the Errors page names `imagePath` as what the upload returns and the item carries.
|
|
215
|
+
...image === null ? {} : { imagePath: image }
|
|
216
|
+
}
|
|
217
|
+
],
|
|
218
|
+
optionGroups: [],
|
|
219
|
+
options: []
|
|
220
|
+
};
|
|
59
221
|
}
|
|
60
|
-
__name(
|
|
61
|
-
function
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
return
|
|
222
|
+
__name(ifoodItemBody, "ifoodItemBody");
|
|
223
|
+
async function categoryWentStale(ctx, put, name, used) {
|
|
224
|
+
if (put.status !== 400 && put.status !== 404) return false;
|
|
225
|
+
const found = await findCategory(ctx, name);
|
|
226
|
+
return !("kind" in found) && found.id !== used;
|
|
65
227
|
}
|
|
66
|
-
__name(
|
|
67
|
-
function
|
|
68
|
-
const
|
|
69
|
-
if (
|
|
70
|
-
const
|
|
71
|
-
|
|
228
|
+
__name(categoryWentStale, "categoryWentStale");
|
|
229
|
+
async function putItem(ctx, item, image) {
|
|
230
|
+
const category = await categoryId(ctx, item.categoryName);
|
|
231
|
+
if ("kind" in category) return category;
|
|
232
|
+
const put = await call(ctx, "PUT", "items", ifoodItemBody(item, category.id, image));
|
|
233
|
+
if ("kind" in put || ok(put) || !await categoryWentStale(ctx, put, item.categoryName, category.id)) return put;
|
|
234
|
+
await ctx.forgetCategory(item.categoryName);
|
|
235
|
+
const again = await categoryId(ctx, item.categoryName);
|
|
236
|
+
if ("kind" in again) return again;
|
|
237
|
+
return call(ctx, "PUT", "items", ifoodItemBody(item, again.id, image));
|
|
72
238
|
}
|
|
73
|
-
__name(
|
|
74
|
-
function
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
239
|
+
__name(putItem, "putItem");
|
|
240
|
+
async function publish(ctx, item) {
|
|
241
|
+
const photo = await photoFor(ctx, item);
|
|
242
|
+
if ("kind" in photo) return photo;
|
|
243
|
+
const put = await putItem(ctx, item, photo.image?.ref ?? null);
|
|
244
|
+
if ("kind" in put) return put;
|
|
245
|
+
if (!ok(put)) return failureOf(put);
|
|
246
|
+
const published = { kind: "published", externalId: ifoodItemId(item.ref), sku: item.productId, image: photo.image };
|
|
247
|
+
return photo.warning ? { ...published, warning: photo.warning } : published;
|
|
248
|
+
}
|
|
249
|
+
__name(publish, "publish");
|
|
250
|
+
async function withdraw(ctx, item) {
|
|
251
|
+
const itemId = item.externalId ?? ifoodItemId(item.ref);
|
|
252
|
+
const patched = await call(ctx, "PATCH", "items/status", { itemId, status: "UNAVAILABLE" });
|
|
253
|
+
if ("kind" in patched) return patched;
|
|
254
|
+
if (patched.status === 404) return { kind: "accepted" };
|
|
255
|
+
return outboundResultOf(patched);
|
|
256
|
+
}
|
|
257
|
+
__name(withdraw, "withdraw");
|
|
258
|
+
async function publishedOrRetry(run) {
|
|
259
|
+
try {
|
|
260
|
+
return await run();
|
|
261
|
+
} catch (error) {
|
|
262
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
78
263
|
}
|
|
79
|
-
return null;
|
|
80
264
|
}
|
|
81
|
-
__name(
|
|
265
|
+
__name(publishedOrRetry, "publishedOrRetry");
|
|
266
|
+
var IFOOD_CATALOGUE = {
|
|
267
|
+
mode: "push",
|
|
268
|
+
publishItem: /* @__PURE__ */ __name((ctx, item) => publishedOrRetry(() => publish(ctx, item)), "publishItem"),
|
|
269
|
+
withdrawItem: /* @__PURE__ */ __name((ctx, item) => answered(() => withdraw(ctx, item)), "withdrawItem")
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
// src/ifood/normalize.ts
|
|
273
|
+
var ORDER_PLACED = /* @__PURE__ */ new Set(["PLC", "PLACED", "ORDER_PLACED"]);
|
|
274
|
+
var ORDER_CANCELLED = /* @__PURE__ */ new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
|
|
275
|
+
var CANCELLATION_REQUEST_FAILED = /* @__PURE__ */ new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
|
|
82
276
|
function verifyIfoodSignature(rawBody, signature, webhookSecret) {
|
|
83
|
-
|
|
84
|
-
if (!signature) return false;
|
|
85
|
-
const expected = createHmac("sha256", webhookSecret).update(rawBody, "utf8").digest("hex");
|
|
86
|
-
const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, ""), "utf8");
|
|
87
|
-
const mine = Buffer.from(expected, "utf8");
|
|
88
|
-
return given.length === mine.length && timingSafeEqual(given, mine);
|
|
277
|
+
return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
|
|
89
278
|
}
|
|
90
279
|
__name(verifyIfoodSignature, "verifyIfoodSignature");
|
|
91
280
|
function readBuyer(order) {
|
|
@@ -194,74 +383,6 @@ function normalizeIfoodEvent(payload, options) {
|
|
|
194
383
|
}
|
|
195
384
|
__name(normalizeIfoodEvent, "normalizeIfoodEvent");
|
|
196
385
|
|
|
197
|
-
// src/ifood/outbound.ts
|
|
198
|
-
var API = "https://merchant-api.ifood.com.br";
|
|
199
|
-
var TOKEN_URL = `${API}/authentication/v1.0/oauth/token`;
|
|
200
|
-
var orderUrl = /* @__PURE__ */ __name((externalOrderId, action) => `${API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`, "orderUrl");
|
|
201
|
-
var IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
|
|
202
|
-
var TOKEN_MARGIN_MS = 6e4;
|
|
203
|
-
function tokenOf(body) {
|
|
204
|
-
try {
|
|
205
|
-
const parsed = JSON.parse(body);
|
|
206
|
-
if (typeof parsed.accessToken !== "string" || parsed.accessToken === "") return null;
|
|
207
|
-
const expires = typeof parsed.expiresIn === "number" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;
|
|
208
|
-
return { token: parsed.accessToken, expiresInSeconds: expires };
|
|
209
|
-
} catch {
|
|
210
|
-
return null;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
__name(tokenOf, "tokenOf");
|
|
214
|
-
async function bearer(ctx) {
|
|
215
|
-
const key = `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
|
|
216
|
-
const cached = ctx.tokens.get(key);
|
|
217
|
-
if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
|
|
218
|
-
const response = await ctx.http({
|
|
219
|
-
method: "POST",
|
|
220
|
-
url: TOKEN_URL,
|
|
221
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
222
|
-
body: new URLSearchParams({
|
|
223
|
-
grantType: "client_credentials",
|
|
224
|
-
clientId: ctx.credentials.clientId,
|
|
225
|
-
clientSecret: ctx.credentials.clientSecret
|
|
226
|
-
}).toString()
|
|
227
|
-
});
|
|
228
|
-
if (response.status < 200 || response.status >= 300) return outboundResultOf(response);
|
|
229
|
-
const token = tokenOf(response.body);
|
|
230
|
-
if (!token) return { kind: "retry", reason: "iFood answered the token grant without a token" };
|
|
231
|
-
ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1e3 });
|
|
232
|
-
return { token: token.token };
|
|
233
|
-
}
|
|
234
|
-
__name(bearer, "bearer");
|
|
235
|
-
function postOrder(ctx, externalOrderId, action, body) {
|
|
236
|
-
return answered(async () => {
|
|
237
|
-
const auth = await bearer(ctx);
|
|
238
|
-
if (!("token" in auth)) return auth;
|
|
239
|
-
const response = await ctx.http({
|
|
240
|
-
method: "POST",
|
|
241
|
-
url: orderUrl(externalOrderId, action),
|
|
242
|
-
headers: {
|
|
243
|
-
Authorization: `Bearer ${auth.token}`,
|
|
244
|
-
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
|
245
|
-
},
|
|
246
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
247
|
-
});
|
|
248
|
-
if (response.status === 401) ctx.tokens.delete(`IFOOD:${ctx.environment}:${ctx.credentials.clientId}`);
|
|
249
|
-
return response.status === 401 ? { kind: "retry", reason: "iFood refused the token" } : outboundResultOf(response);
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
__name(postOrder, "postOrder");
|
|
253
|
-
function ifoodConfirm(ctx, order) {
|
|
254
|
-
return postOrder(ctx, order.externalOrderId, "confirm");
|
|
255
|
-
}
|
|
256
|
-
__name(ifoodConfirm, "ifoodConfirm");
|
|
257
|
-
function ifoodRequestCancellation(ctx, order, input) {
|
|
258
|
-
return postOrder(ctx, order.externalOrderId, "requestCancellation", {
|
|
259
|
-
reason: input.text === "" ? input.reason.label : input.text,
|
|
260
|
-
cancellationCode: input.reason.code
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
__name(ifoodRequestCancellation, "ifoodRequestCancellation");
|
|
264
|
-
|
|
265
386
|
// src/ifood/index.ts
|
|
266
387
|
var IFOOD_PROVIDER = "IFOOD";
|
|
267
388
|
var ITEM_UNAVAILABLE = "503";
|
|
@@ -294,6 +415,8 @@ function createIfoodAdapter(config) {
|
|
|
294
415
|
readSignature: /* @__PURE__ */ __name((header) => header("x-ifood-signature") ?? header("x-signature"), "readSignature"),
|
|
295
416
|
verifySignature: verifyIfoodSignature,
|
|
296
417
|
cancellationReasons: /* @__PURE__ */ __name(() => reasons, "cancellationReasons"),
|
|
418
|
+
// The Catalog API v2.0: each item is written and paused through the API (FUT-4768).
|
|
419
|
+
catalogue: IFOOD_CATALOGUE,
|
|
297
420
|
confirm: /* @__PURE__ */ __name((ctx, order) => ifoodConfirm(ctx, order), "confirm"),
|
|
298
421
|
requestCancellation: ifoodRequestCancellation,
|
|
299
422
|
// No per-order deep link is known, so the portal, where a live order is
|
|
@@ -304,9 +427,13 @@ function createIfoodAdapter(config) {
|
|
|
304
427
|
__name(createIfoodAdapter, "createIfoodAdapter");
|
|
305
428
|
export {
|
|
306
429
|
IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
|
|
430
|
+
IFOOD_CATALOGUE,
|
|
307
431
|
IFOOD_PROVIDER,
|
|
308
432
|
IFOOD_REASON_CODES,
|
|
309
433
|
createIfoodAdapter,
|
|
434
|
+
ifoodItemBody,
|
|
435
|
+
ifoodItemId,
|
|
436
|
+
ifoodProductId,
|
|
310
437
|
normalizeIfoodEvent,
|
|
311
438
|
verifyIfoodSignature
|
|
312
439
|
};
|
package/dist/ifood/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ifood/copy.ts","../../src/ifood/normalize.ts","../../src/ifood/outbound.ts","../../src/ifood/index.ts"],"sourcesContent":["/**\n * The words the iFood adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * iFood's documented cancellation reason codes. UNVERIFIED: read from the\n * merchant portal's search snippets (2026-11-11), not from a page we could\n * read whole; the homologation run against iFood's sandbox corrects them here.\n */\nexport const IFOOD_REASON_CODES = [\n \"501\",\n \"502\",\n \"503\",\n \"504\",\n \"505\",\n \"506\",\n \"507\",\n \"508\",\n \"509\",\n \"511\",\n \"512\",\n \"513\",\n] as const;\n\nexport type IfoodReasonCode = (typeof IFOOD_REASON_CODES)[number];\n\nexport interface IfoodAdapterCopy {\n /** One label per reason code. Sent to iFood as the reason text when the store wrote none. */\n reasonLabels: Readonly<Record<IfoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedBuyer,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.\n *\n * Everything iFood-shaped about a delivery is in this file, and the engine\n * never learns the name: it reaches this through the adapter registry.\n *\n * The payload is treated as UNTRUSTED and read defensively throughout: iFood's\n * documented shape and iFood's actual shape have drifted before, and a\n * `TypeError` reading a missing field would reject a paid order at the door.\n * Every reader below either produces a value or produces null; the one thing\n * that can refuse an order outright is a missing order ID, because without it\n * there is no idempotency key and ingesting would risk a duplicate.\n */\n\n/** iFood event codes this ingestion acts on. */\nconst ORDER_PLACED = new Set([\"PLC\", \"PLACED\", \"ORDER_PLACED\"]);\nconst ORDER_CANCELLED = new Set([\"CAN\", \"CANCELLED\", \"ORDER_CANCELLED\"]);\n/** iFood refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_FAILED = new Set([\"CARF\", \"CANCELLATION_REQUEST_FAILED\"]);\n\n/** Read a nested value without asserting the shape of anything on the way. */\nfunction 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\nfunction 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 * iFood states the same fact under different keys depending on which API\n * version delivered the order, so nearly every read here is a fallback chain.\n * Expressed as data rather than as `??` so a chain can grow by one entry\n * instead of by one branch.\n */\nfunction 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/** {@link firstString} for money. Same reason, same shape. */\nfunction 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 * iFood states money in DECIMAL reais (`12.9`), this app in 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 — per line, on every order,\n * always in the store's disfavour.\n */\nfunction 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\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. */\nfunction 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 delivery against the merchant's webhook secret.\n *\n * Unsigned deliveries are refused whenever a secret is CONFIGURED. A store that\n * has not set one yet is accepted — iFood's own onboarding issues the secret\n * after the merchant is certified, so refusing before then would make the\n * connection untestable — and that state is visible on the integration screen\n * rather than silent.\n *\n * Compared in constant time over bytes: an early-exit `===` on a hex digest\n * leaks the prefix a forger already got right, one request at a time.\n */\nexport function verifyIfoodSignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return true;\n if (!signature) return false;\n const expected = createHmac(\"sha256\", webhookSecret).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\n/** The buyer, as much of them as iFood discloses on the order. */\nfunction readBuyer(order: unknown): NormalizedBuyer {\n return {\n externalId: asString(pick(order, \"customer\", \"id\")),\n name: asString(pick(order, \"customer\", \"name\")),\n phone: firstString(order, [\n [\"customer\", \"phone\", \"number\"],\n [\"customer\", \"phone\"],\n ]),\n };\n}\n\n/**\n * One iFood item → one normalized line.\n *\n * A line with no resolvable SKU still becomes a line: `externalSku` falls back\n * to the item's own id, and failing that to its name. That fallback is doing\n * real work — an unmapped line is recoverable (the store maps it and it is\n * fixed forever), a DROPPED line is not, because nothing downstream can tell\n * that food is missing from the ticket.\n */\nfunction readLine(item: unknown): NormalizedOrderLine | null {\n const name = firstString(item, [[\"name\"], [\"description\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return null;\n const quantity = Number(pick(item, \"quantity\") ?? 1);\n return {\n externalSku: sku,\n name: name ?? sku,\n quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,\n unitPriceCents: firstCents(item, [[\"unitPrice\"], [\"price\"]]) ?? 0,\n note: firstString(item, [[\"observations\"], [\"note\"]]),\n };\n}\n\n/**\n * The commission iFood states on the order, in cents.\n *\n * Absent on plenty of real payloads (it depends on the merchant's contract and\n * on which API version delivered the order), and absent is stored as NULL\n * rather than as 0 — \"iFood took nothing\" and \"iFood did not say\" are different\n * claims, and only one of them is safe to put in a margin report.\n */\nfunction readCommission(order: unknown): number | null {\n return firstCents(order, [[\"total\", \"commission\"], [\"commission\"], [\"payments\", \"commission\"]]);\n}\n\n/** iFood's `orderType` as the two ways an order reaches the buyer, or null when it says neither. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"orderType\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\n/** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : null;\n}\n\n/**\n * Where a delivery goes. The street is what a courier cannot find a door\n * without, so an address with none is none; a missing number reads as the\n * host's own words for \"no number\" (`copy.missingStreetNumber`), which keeps\n * the street, the neighbourhood and the reference rather than dropping the\n * whole door.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"streetName\"], [\"street\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"streetNumber\"], [\"number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"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\"]]),\n };\n}\n\n/** The order body of a placed-order event, or null when it carries none. */\nfunction readOrder(\n payload: unknown,\n externalOrderId: string,\n missingStreetNumber: string,\n): NormalizedMarketplaceOrder | null {\n const order = pick(payload, \"order\") ?? payload;\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .map(readLine)\n .filter((line): line is NormalizedOrderLine => line !== null);\n if (lines.length === 0) return null;\n\n const stated = firstCents(order, [[\"total\", \"orderAmount\"], [\"totalPrice\"], [\"total\"]]);\n\n return {\n provider: \"IFOOD\",\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]) ?? firstString(payload, [[\"displayId\"]]),\n buyer: readBuyer(order),\n lines,\n // The line sum is the FALLBACK, never the preference: iFood's stated total\n // carries delivery fees, its promotions and its rounding, and it is the\n // number on the buyer's receipt. Summing lines when iFood did say is how a\n // store's revenue quietly stops matching its iFood statement.\n totalCents: stated ?? lines.reduce((sum, l) => sum + l.unitPriceCents * l.quantity, 0),\n commissionCents: readCommission(order),\n deliveryDueAt: firstDate(order, [[\"delivery\", \"deliveryDateTime\"], [\"preparationStartDateTime\"]]),\n placedAt:\n firstDate(order, [[\"createdAt\"]]) ?? firstDate(payload, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, missingStreetNumber),\n };\n}\n\n/**\n * Normalize one iFood delivery.\n *\n * Returns null only when the payload carries no order id at all — the one thing\n * this pipeline cannot proceed without, because it IS the idempotency key and\n * ingesting without it risks the duplicate that \"never lose an order\" is\n * balanced against.\n */\nexport function normalizeIfoodEvent(\n payload: unknown,\n options: { missingStreetNumber: string },\n): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"], [\"order\", \"id\"], [\"id\"]]);\n if (!externalOrderId) return null;\n\n const eventType = firstString(payload, [[\"fullCode\"], [\"code\"]]) ?? \"UNKNOWN\";\n const cancelled = ORDER_CANCELLED.has(eventType.toUpperCase());\n const placed = ORDER_PLACED.has(eventType.toUpperCase());\n const refusedRequest = CANCELLATION_REQUEST_FAILED.has(eventType.toUpperCase());\n\n return {\n provider: \"IFOOD\",\n // iFood's own event id when it sends one. The fallback is deterministic on\n // purpose — (order, type) is stable across a redelivery, so a duplicate\n // still collides on the inbox's unique index instead of creating a second\n // row that would be processed a second time.\n eventId: firstString(payload, [[\"id\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: firstString(payload, [[\"merchantId\"], [\"merchant\", \"id\"]]),\n externalOrderId,\n order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : refusedRequest ? \"FAILED\" : null,\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\n\n/**\n * The iFood adapter's OUTBOUND half: auth, URLs and payload shapes. Everything\n * here is iFood's wire format and nothing else — the job that calls it, its\n * retries and what a failure shows are the engine's (`../core/outbound.ts`).\n *\n * UNVERIFIED. iFood's developer portal refused our reader, so every URL, body\n * field below (and the reason codes in `./copy.ts`) comes from the portal's search snippets\n * (2026-11-11), not from a page we could read whole. They are in THIS file and\n * nowhere else so that the homologation run against iFood's sandbox, once\n * homologation credentials exist, corrects one file. Tests never reach\n * iFood: the HTTP client is the host's port, answered by a fake.\n */\n\n/** iFood's merchant API. Sandbox and production share the host; the credentials differ. */\nconst API = \"https://merchant-api.ifood.com.br\";\nconst TOKEN_URL = `${API}/authentication/v1.0/oauth/token`;\nconst orderUrl = (externalOrderId: string, action: string): string =>\n `${API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;\n\n/**\n * iFood's order-manager portal. No per-order deep link was found in the\n * snippets, so the app link opens the portal, where the order is on the\n * first screen while it is live.\n */\nexport const IFOOD_PORTAL_URL = \"https://portal.ifood.com.br/\";\n\n/** A token is renewed this long before iFood says it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n\n/** iFood's OAuth answer, read defensively: a missing field is \"no token\". */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { accessToken?: unknown; expiresIn?: unknown };\n if (typeof parsed.accessToken !== \"string\" || parsed.accessToken === \"\") return null;\n const expires = typeof parsed.expiresIn === \"number\" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;\n return { token: parsed.accessToken, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token for this merchant app, from the per-process cache or a fresh\n * client-credentials grant. Keyed by the app's client id, so two stores with\n * two apps never share one. The token lives in memory only.\n */\nasync function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {\n const key = `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;\n const cached = ctx.tokens.get(key);\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: TOKEN_URL,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grantType: \"client_credentials\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) return outboundResultOf(response);\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"iFood answered the token grant without a token\" };\n ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated POST to an order's resource. */\nfunction postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: orderUrl(externalOrderId, action),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status === 401) ctx.tokens.delete(`IFOOD:${ctx.environment}:${ctx.credentials.clientId}`);\n return response.status === 401 ? { kind: \"retry\", reason: \"iFood refused the token\" } : outboundResultOf(response);\n });\n}\n\n/** Tell iFood the store accepted the order. No body: the URL names the order. */\nexport function ifoodConfirm(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"confirm\");\n}\n\n/** Ask iFood to cancel the order with one of its reason codes. */\nexport function ifoodRequestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"requestCancellation\", {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancellationCode: input.reason.code,\n });\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nimport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\nimport { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.\n *\n * The owner's rule: adapters live inside the lib, one per subpath, and no\n * provider-specific branch exists anywhere outside an adapter and its\n * registration. Everything iFood is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port.\n *\n * ```ts\n * import { createIfoodAdapter } from \"@12-apps/marketplace/ifood\";\n * import { IFOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/ifood/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })] });\n * ```\n */\n\n/** The provider id iFood is registered under. */\nexport const IFOOD_PROVIDER = \"IFOOD\";\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: IfoodReasonCode = \"503\";\n\n/** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */\nexport const IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\nexport interface IfoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: IfoodAdapterCopy;\n}\n\n/** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */\nexport function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {\n const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: IFOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n cancelAfterAccept: true,\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n confirmTakesPreparationTime: false,\n // How long iFood takes, at most, to answer a cancellation request: its\n // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off\n // iFood's documentation, which names no answer deadline: iFood answers a\n // request in seconds when it answers at all, so 5 minutes is generous.\n // A host overrides it with the engine's `cancellationWindowMs`.\n cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),\n readSignature: (header) => header(\"x-ifood-signature\") ?? header(\"x-signature\"),\n verifySignature: verifyIfoodSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order) => ifoodConfirm(ctx, order),\n requestCancellation: ifoodRequestCancellation,\n // No per-order deep link is known, so the portal, where a live order is\n // on the first screen.\n appLink: () => IFOOD_PORTAL_URL,\n };\n}\n\nexport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nexport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\n"],"mappings":";;;;;;;;;AAaO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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AAAA,MACZ,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,mBAAmB;AAAA,MACnB,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA,MACjB,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAM7B,4BAA4B;AAAA,IAC9B;AAAA,IACA,WAAW,wBAAC,YAAY,oBAAoB,SAAS,gBAAgB,GAA1D;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,mBAAmB,KAAK,OAAO,aAAa,GAA/D;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA,IACrB,SAAS,wBAAC,KAAK,UAAU,aAAa,KAAK,KAAK,GAAvC;AAAA,IACT,qBAAqB;AAAA;AAAA;AAAA,IAGrB,SAAS,6BAAM,kBAAN;AAAA,EACX;AACF;AAlCgB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/ifood/copy.ts","../../src/ifood/outbound.ts","../../src/ifood/catalogue.ts","../../src/ifood/normalize.ts","../../src/ifood/index.ts"],"sourcesContent":["/**\n * The words the iFood adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * iFood's documented cancellation reason codes. UNVERIFIED: read from the\n * merchant portal's search snippets (2026-11-11), not from a page we could\n * read whole; the homologation run against iFood's sandbox corrects them here.\n */\nexport const IFOOD_REASON_CODES = [\n \"501\",\n \"502\",\n \"503\",\n \"504\",\n \"505\",\n \"506\",\n \"507\",\n \"508\",\n \"509\",\n \"511\",\n \"512\",\n \"513\",\n] as const;\n\nexport type IfoodReasonCode = (typeof IFOOD_REASON_CODES)[number];\n\nexport interface IfoodAdapterCopy {\n /** One label per reason code. Sent to iFood as the reason text when the store wrote none. */\n reasonLabels: Readonly<Record<IfoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\n\n/**\n * The iFood adapter's OUTBOUND half: auth, URLs and payload shapes. Everything\n * here is iFood's wire format and nothing else — the job that calls it, its\n * retries and what a failure shows are the engine's (`../core/outbound.ts`).\n *\n * UNVERIFIED. iFood's developer portal refused our reader, so every URL, body\n * field below (and the reason codes in `./copy.ts`) comes from the portal's search snippets\n * (2026-11-11), not from a page we could read whole. They are in THIS file and\n * nowhere else so that the homologation run against iFood's sandbox, once\n * homologation credentials exist, corrects one file. Tests never reach\n * iFood: the HTTP client is the host's port, answered by a fake.\n */\n\n/** iFood's merchant API. Sandbox and production share the host; the credentials differ. */\nexport const IFOOD_API = \"https://merchant-api.ifood.com.br\";\nconst TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;\nconst orderUrl = (externalOrderId: string, action: string): string =>\n `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;\n\n/**\n * iFood's order-manager portal. No per-order deep link was found in the\n * snippets, so the app link opens the portal, where the order is on the\n * first screen while it is live.\n */\nexport const IFOOD_PORTAL_URL = \"https://portal.ifood.com.br/\";\n\n/** A token is renewed this long before iFood says it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n\n/** The token cache key: per environment and merchant app. */\nexport const ifoodTokenKey = (ctx: AdapterCallContext): string => `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** iFood's OAuth answer, read defensively: a missing field is \"no token\". */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { accessToken?: unknown; expiresIn?: unknown };\n if (typeof parsed.accessToken !== \"string\" || parsed.accessToken === \"\") return null;\n const expires = typeof parsed.expiresIn === \"number\" && parsed.expiresIn > 0 ? parsed.expiresIn : 3600;\n return { token: parsed.accessToken, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token for this merchant app, from the per-process cache or a fresh\n * client-credentials grant. Keyed by the app's client id, so two stores with\n * two apps never share one. The token lives in memory only.\n */\nexport async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {\n const key = ifoodTokenKey(ctx);\n const cached = ctx.tokens.get(key);\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: TOKEN_URL,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grantType: \"client_credentials\",\n clientId: ctx.credentials.clientId,\n clientSecret: ctx.credentials.clientSecret,\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) return outboundResultOf(response);\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"iFood answered the token grant without a token\" };\n ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated POST to an order's resource. */\nfunction postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: orderUrl(externalOrderId, action),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status === 401) ctx.tokens.delete(ifoodTokenKey(ctx));\n return response.status === 401 ? { kind: \"retry\", reason: \"iFood refused the token\" } : outboundResultOf(response);\n });\n}\n\n/** Tell iFood the store accepted the order. No body: the URL names the order. */\nexport function ifoodConfirm(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"confirm\");\n}\n\n/** Ask iFood to cancel the order with one of its reason codes. */\nexport function ifoodRequestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return postOrder(ctx, order.externalOrderId, \"requestCancellation\", {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancellationCode: input.reason.code,\n });\n}\n","import {\n answered,\n outboundResultOf,\n type MarketplaceHttpResponse,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type {\n CatalogueCallContext,\n CatalogueImage,\n CatalogueItemOut,\n CatalogueItemRef,\n CataloguePublishResult,\n CatalogueStoredImage,\n CatalogueWarningCode,\n PushCatalogue,\n} from \"../core/catalogue-port\";\nimport { IFOOD_API, bearer, ifoodTokenKey } from \"./outbound\";\n\n/**\n * The iFood adapter's CATALOGUE half: iFood's Catalog API v2.0, push (FUT-4768).\n *\n * Read 2026-11-13 from iFood's developer portal (the Catalog module's\n * Introduction, Fundamentals, Endpoints and Errors pages, and the rate-limit\n * page); the package README's \"Catalogue publishing\" table marks each fact\n * CONFIRMED with its URL or ESTIMATED. What is ESTIMATED here is said beside\n * it, and lives in this file only, so the homologation run corrects one file.\n *\n * One publish is, in order:\n * 1. the category, by name: `GET /categories`, else `POST /categories`\n * (`template: \"DEFAULT\"`);\n * 2. the photo, when the item has one: the `imagePath` iFood already holds\n * for the same photo URL, else `POST /image/upload` with a base64 data URL\n * of the bytes the host's loader reads, which answers `imagePath`;\n * 3. the item: `PUT /items` with `item`, `products`, `optionGroups`,\n * `options` — idempotent, it replaces the whole item, and the item appears\n * at once (synchronous).\n *\n * iFood wants item and product ids the software generates, UUID v4 (any other\n * shape answers 404), so they are derived from the engine's publication\n * reference: a retried publish names the same item. The item's `externalCode`\n * is the host's product id (unique per merchant).\n *\n * A withdraw pauses the item, `PATCH /items/status` with `UNAVAILABLE`: the\n * Endpoints page lists no item delete, and a paused item is not shown in the\n * app (ESTIMATED that this is what \"off\" should mean; a re-publish puts it\n * back AVAILABLE with the same id).\n */\n\nconst catalogUrl = (merchantId: string, path: string): string =>\n `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;\n\n/** The item's and its product's ids, stable per publication. */\nexport const ifoodItemId = (ref: string): string => stableUuid(`${ref}:item`);\nexport const ifoodProductId = (ref: string): string => stableUuid(`${ref}:product`);\n\ntype Failure = Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** iFood's price object: a decimal of the currency's major unit. */\nconst priceOf = (cents: number): { value: number } => ({ value: Math.round(cents) / 100 });\n\n/** One authenticated call to the catalogue: the raw answer, or the failure that ends it. */\nasync function call(\n ctx: CatalogueCallContext,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\",\n path: string,\n body?: unknown,\n): Promise<MarketplaceHttpResponse | Failure> {\n const auth = await bearer(ctx);\n if (!(\"token\" in auth)) return auth.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : auth;\n const response = await ctx.http({\n method,\n url: catalogUrl(ctx.externalMerchantId, path),\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n if (response.status !== 401) return response;\n ctx.tokens.delete(ifoodTokenKey(ctx));\n return { kind: \"retry\", reason: \"iFood refused the token\" };\n}\n\n/** A non-2xx answer as the failure it is (never `accepted`). */\nfunction failureOf(response: MarketplaceHttpResponse): Failure {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected answer\" } : result;\n}\n\nconst ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;\n\nfunction parse(body: string): unknown {\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return null;\n }\n}\n\n/** The id of the category named `name`, from a category list. ESTIMATED: the list answers an array of `{ id, name }`. */\nfunction categoryIdIn(body: string, name: string): string | null {\n const parsed = parse(body);\n if (!Array.isArray(parsed)) return null;\n const wanted = name.trim().toLowerCase();\n const found = parsed.find(\n (entry: unknown) =>\n typeof entry === \"object\" && entry !== null && String((entry as { name?: unknown }).name ?? \"\").trim().toLowerCase() === wanted,\n ) as { id?: unknown } | undefined;\n return typeof found?.id === \"string\" ? found.id : null;\n}\n\n/** The category named `name` on iFood, or null; the failure that ended the read otherwise. */\nasync function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {\n const listed = await call(ctx, \"GET\", \"categories\");\n if (\"kind\" in listed) return listed;\n if (!ok(listed)) return failureOf(listed);\n return { id: categoryIdIn(listed.body, name) };\n}\n\n/**\n * Find the category by name, else create it, then read the list again and\n * adopt the first of that name: a POST whose answer was lost and was retried\n * is found rather than created twice. The engine runs this once per\n * (connection, name) at a time and stores the id (`ctx.category`).\n */\nasync function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {\n const found = await findCategory(ctx, name);\n if (\"kind\" in found) return found;\n if (found.id) return { id: found.id };\n const created = await call(ctx, \"POST\", \"categories\", { name, status: \"AVAILABLE\", template: \"DEFAULT\" });\n if (\"kind\" in created) return created;\n if (!ok(created)) return failureOf(created);\n const id = (parse(created.body) as { id?: unknown } | null)?.id;\n if (typeof id !== \"string\") return { kind: \"retry\", reason: \"iFood created the category without an id\" };\n // ESTIMATED: the list answers categories in creation order, so the first match is the oldest.\n const again = await findCategory(ctx, name);\n return \"id\" in again && again.id ? { id: again.id } : { id };\n}\n\nconst categoryId = (ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> =>\n ctx.category(name, () => findOrCreateCategory(ctx, name));\n\n/** The photo the item goes out with, and what the publish could not do about it. */\ninterface PhotoOutcome {\n image: CatalogueStoredImage | null;\n warning?: CatalogueWarningCode;\n}\n\n/**\n * The photo for this publish, uploading only when it must:\n * - no `imageUrl`: no photo;\n * - the photo iFood already holds was made from this same URL: reuse it;\n * - else upload the bytes the host's loader reads; when it reads nothing,\n * keep the photo iFood holds, if any (PUT replaces the whole item, so\n * sending none would drop it);\n * - an upload iFood refuses (413 over 5 MB, another final 4xx) publishes\n * without a photo and says why as a warning, rather than failing the item.\n */\nasync function photoFor(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<PhotoOutcome | Failure> {\n const stored = item.storedImage;\n if (item.imageUrl === null) return { image: null };\n if (stored && stored.sourceUrl === item.imageUrl) return { image: stored };\n const bytes = await ctx.loadImage(item.imageUrl);\n return bytes ? upload(ctx, bytes, item.imageUrl) : { image: stored };\n}\n\n/** `POST /image/upload`: the new photo, a warning for a refused one, or the failure to retry. */\nasync function upload(ctx: CatalogueCallContext, bytes: CatalogueImage, sourceUrl: string): Promise<PhotoOutcome | Failure> {\n const uploaded = await call(ctx, \"POST\", \"image/upload\", { image: `data:${bytes.contentType};base64,${bytes.base64}` });\n if (\"kind\" in uploaded) return uploaded;\n if (!ok(uploaded)) {\n const failure = failureOf(uploaded);\n if (failure.kind === \"retry\") return failure;\n return { image: null, warning: uploaded.status === 413 ? \"IMAGE_TOO_LARGE\" : \"IMAGE_REFUSED\" };\n }\n const path = (parse(uploaded.body) as { imagePath?: unknown } | null)?.imagePath;\n if (typeof path !== \"string\") return { kind: \"retry\", reason: \"iFood answered the upload without an imagePath\" };\n return { image: { ref: path, sourceUrl } };\n}\n\n/** The `PUT /items` body for one simple item with no add-ons. */\nexport function ifoodItemBody(item: CatalogueItemOut, category: string, image: string | null): unknown {\n const itemId = ifoodItemId(item.ref);\n const productId = ifoodProductId(item.ref);\n return {\n item: {\n id: itemId,\n type: \"DEFAULT\",\n categoryId: category,\n status: \"AVAILABLE\",\n price: priceOf(item.priceCents),\n externalCode: item.productId,\n // ESTIMATED: the guide's examples link item and product implicitly; the\n // field naming the product is not shown on the pages read.\n productId,\n },\n products: [\n {\n id: productId,\n name: item.name,\n description: item.description ?? \"\",\n externalCode: `${item.productId}-product`,\n // ESTIMATED field name: the Errors page names `imagePath` as what the upload returns and the item carries.\n ...(image === null ? {} : { imagePath: image }),\n },\n ],\n optionGroups: [],\n options: [],\n };\n}\n\n/**\n * Whether a refused PUT was refused because the stored category is gone (the\n * store deleted it on iFood's portal): iFood's 400 and 404 do not say which id\n * was unknown, so the list is read again, and a category of that name with\n * another id, or none at all, means the stored one is stale. ESTIMATED that a\n * deleted category answers 400 or 404.\n */\nasync function categoryWentStale(ctx: CatalogueCallContext, put: MarketplaceHttpResponse, name: string, used: string): Promise<boolean> {\n if (put.status !== 400 && put.status !== 404) return false;\n const found = await findCategory(ctx, name);\n return !(\"kind\" in found) && found.id !== used;\n}\n\n/** `PUT /items`, once more with the category found or created again when the stored one went stale. */\nasync function putItem(ctx: CatalogueCallContext, item: CatalogueItemOut, image: string | null): Promise<MarketplaceHttpResponse | Failure> {\n const category = await categoryId(ctx, item.categoryName);\n if (\"kind\" in category) return category;\n const put = await call(ctx, \"PUT\", \"items\", ifoodItemBody(item, category.id, image));\n if (\"kind\" in put || ok(put) || !(await categoryWentStale(ctx, put, item.categoryName, category.id))) return put;\n await ctx.forgetCategory(item.categoryName);\n const again = await categoryId(ctx, item.categoryName);\n if (\"kind\" in again) return again;\n return call(ctx, \"PUT\", \"items\", ifoodItemBody(item, again.id, image));\n}\n\nasync function publish(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult> {\n const photo = await photoFor(ctx, item);\n if (\"kind\" in photo) return photo;\n const put = await putItem(ctx, item, photo.image?.ref ?? null);\n if (\"kind\" in put) return put;\n if (!ok(put)) return failureOf(put);\n // iFood's orders carry the item's `externalCode` as the line's SKU (the order normalizer reads it).\n const published = { kind: \"published\" as const, externalId: ifoodItemId(item.ref), sku: item.productId, image: photo.image };\n return photo.warning ? { ...published, warning: photo.warning } : published;\n}\n\nasync function withdraw(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult> {\n const itemId = item.externalId ?? ifoodItemId(item.ref);\n const patched = await call(ctx, \"PATCH\", \"items/status\", { itemId, status: \"UNAVAILABLE\" });\n if (\"kind\" in patched) return patched;\n // ESTIMATED: a 404 means iFood does not have the item, so it is already out\n // of its catalogue (the Errors page says 404 is \"the resource does not exist\").\n if (patched.status === 404) return { kind: \"accepted\" };\n return outboundResultOf(patched);\n}\n\n/** A call that never got an answer is a retry. */\nasync function publishedOrRetry(run: () => Promise<CataloguePublishResult>): Promise<CataloguePublishResult> {\n try {\n return await run();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** iFood's catalogue capability. */\nexport const IFOOD_CATALOGUE: PushCatalogue = {\n mode: \"push\",\n publishItem: (ctx, item) => publishedOrRetry(() => publish(ctx, item)),\n withdrawItem: (ctx, item) => answered(() => withdraw(ctx, item)),\n};\n","import type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedBuyer,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\nimport {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\n\n/**\n * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.\n *\n * Everything iFood-shaped about a delivery is in this file, and the engine\n * never learns the name: it reaches this through the adapter registry.\n *\n * The payload is treated as UNTRUSTED and read defensively throughout: iFood's\n * documented shape and iFood's actual shape have drifted before, and a\n * `TypeError` reading a missing field would reject a paid order at the door.\n * Every reader below either produces a value or produces null; the one thing\n * that can refuse an order outright is a missing order ID, because without it\n * there is no idempotency key and ingesting would risk a duplicate.\n */\n\n/** iFood event codes this ingestion acts on. */\nconst ORDER_PLACED = new Set([\"PLC\", \"PLACED\", \"ORDER_PLACED\"]);\nconst ORDER_CANCELLED = new Set([\"CAN\", \"CANCELLED\", \"ORDER_CANCELLED\"]);\n/** iFood refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_FAILED = new Set([\"CARF\", \"CANCELLATION_REQUEST_FAILED\"]);\n\n/**\n * Verify a delivery against the merchant's webhook secret: iFood signs the raw\n * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one\n * refuses an unsigned delivery; constant-time compare) is the engine's\n * {@link verifyHmacSha256Hex}. iFood's own onboarding issues the secret after\n * the merchant is certified, so refusing before then would make the\n * connection untestable.\n */\nexport function verifyIfoodSignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/** The buyer, as much of them as iFood discloses on the order. */\nfunction readBuyer(order: unknown): NormalizedBuyer {\n return {\n externalId: asString(pick(order, \"customer\", \"id\")),\n name: asString(pick(order, \"customer\", \"name\")),\n phone: firstString(order, [\n [\"customer\", \"phone\", \"number\"],\n [\"customer\", \"phone\"],\n ]),\n };\n}\n\n/**\n * One iFood item → one normalized line.\n *\n * A line with no resolvable SKU still becomes a line: `externalSku` falls back\n * to the item's own id, and failing that to its name. That fallback is doing\n * real work — an unmapped line is recoverable (the store maps it and it is\n * fixed forever), a DROPPED line is not, because nothing downstream can tell\n * that food is missing from the ticket.\n */\nfunction readLine(item: unknown): NormalizedOrderLine | null {\n const name = firstString(item, [[\"name\"], [\"description\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return null;\n const quantity = Number(pick(item, \"quantity\") ?? 1);\n return {\n externalSku: sku,\n name: name ?? sku,\n quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,\n unitPriceCents: firstCents(item, [[\"unitPrice\"], [\"price\"]]) ?? 0,\n note: firstString(item, [[\"observations\"], [\"note\"]]),\n };\n}\n\n/**\n * The commission iFood states on the order, in cents.\n *\n * Absent on plenty of real payloads (it depends on the merchant's contract and\n * on which API version delivered the order), and absent is stored as NULL\n * rather than as 0 — \"iFood took nothing\" and \"iFood did not say\" are different\n * claims, and only one of them is safe to put in a margin report.\n */\nfunction readCommission(order: unknown): number | null {\n return firstCents(order, [[\"total\", \"commission\"], [\"commission\"], [\"payments\", \"commission\"]]);\n}\n\n/** iFood's `orderType` as the two ways an order reaches the buyer, or null when it says neither. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"orderType\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\n/** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n if (stated === \"IFOOD\") return \"MARKETPLACE\";\n return stated === \"MERCHANT\" ? \"MERCHANT\" : null;\n}\n\n/**\n * Where a delivery goes. The street is what a courier cannot find a door\n * without, so an address with none is none; a missing number reads as the\n * host's own words for \"no number\" (`copy.missingStreetNumber`), which keeps\n * the street, the neighbourhood and the reference rather than dropping the\n * whole door.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"streetName\"], [\"street\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"streetNumber\"], [\"number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"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\"]]),\n };\n}\n\n/** The order body of a placed-order event, or null when it carries none. */\nfunction readOrder(\n payload: unknown,\n externalOrderId: string,\n missingStreetNumber: string,\n): NormalizedMarketplaceOrder | null {\n const order = pick(payload, \"order\") ?? payload;\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .map(readLine)\n .filter((line): line is NormalizedOrderLine => line !== null);\n if (lines.length === 0) return null;\n\n const stated = firstCents(order, [[\"total\", \"orderAmount\"], [\"totalPrice\"], [\"total\"]]);\n\n return {\n provider: \"IFOOD\",\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]) ?? firstString(payload, [[\"displayId\"]]),\n buyer: readBuyer(order),\n lines,\n // The line sum is the FALLBACK, never the preference: iFood's stated total\n // carries delivery fees, its promotions and its rounding, and it is the\n // number on the buyer's receipt. Summing lines when iFood did say is how a\n // store's revenue quietly stops matching its iFood statement.\n totalCents: stated ?? lines.reduce((sum, l) => sum + l.unitPriceCents * l.quantity, 0),\n commissionCents: readCommission(order),\n deliveryDueAt: firstDate(order, [[\"delivery\", \"deliveryDateTime\"], [\"preparationStartDateTime\"]]),\n placedAt:\n firstDate(order, [[\"createdAt\"]]) ?? firstDate(payload, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, missingStreetNumber),\n };\n}\n\n/**\n * Normalize one iFood delivery.\n *\n * Returns null only when the payload carries no order id at all — the one thing\n * this pipeline cannot proceed without, because it IS the idempotency key and\n * ingesting without it risks the duplicate that \"never lose an order\" is\n * balanced against.\n */\nexport function normalizeIfoodEvent(\n payload: unknown,\n options: { missingStreetNumber: string },\n): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"], [\"order\", \"id\"], [\"id\"]]);\n if (!externalOrderId) return null;\n\n const eventType = firstString(payload, [[\"fullCode\"], [\"code\"]]) ?? \"UNKNOWN\";\n const cancelled = ORDER_CANCELLED.has(eventType.toUpperCase());\n const placed = ORDER_PLACED.has(eventType.toUpperCase());\n const refusedRequest = CANCELLATION_REQUEST_FAILED.has(eventType.toUpperCase());\n\n return {\n provider: \"IFOOD\",\n // iFood's own event id when it sends one. The fallback is deterministic on\n // purpose — (order, type) is stable across a redelivery, so a duplicate\n // still collides on the inbox's unique index instead of creating a second\n // row that would be processed a second time.\n eventId: firstString(payload, [[\"id\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: firstString(payload, [[\"merchantId\"], [\"merchant\", \"id\"]]),\n externalOrderId,\n order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : refusedRequest ? \"FAILED\" : null,\n };\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nimport { IFOOD_CATALOGUE } from \"./catalogue\";\nimport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\nimport { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.\n *\n * The owner's rule: adapters live inside the lib, one per subpath, and no\n * provider-specific branch exists anywhere outside an adapter and its\n * registration. Everything iFood is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port.\n *\n * ```ts\n * import { createIfoodAdapter } from \"@12-apps/marketplace/ifood\";\n * import { IFOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/ifood/pt-BR\";\n *\n * createMarketplaceEngine({ …ports, adapters: [createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR })] });\n * ```\n */\n\n/** The provider id iFood is registered under. */\nexport const IFOOD_PROVIDER = \"IFOOD\";\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: IfoodReasonCode = \"503\";\n\n/** How long iFood may take to answer a cancellation request: 5 minutes, ESTIMATED (see the adapter's capabilities). */\nexport const IFOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\nexport interface IfoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: IfoodAdapterCopy;\n}\n\n/** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */\nexport function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {\n const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: IFOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n cancelAfterAccept: true,\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n confirmTakesPreparationTime: false,\n // How long iFood takes, at most, to answer a cancellation request: its\n // CANCELLED or CANCELLATION_REQUEST_FAILED event. ESTIMATED, not read off\n // iFood's documentation, which names no answer deadline: iFood answers a\n // request in seconds when it answers at all, so 5 minutes is generous.\n // A host overrides it with the engine's `cancellationWindowMs`.\n cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),\n readSignature: (header) => header(\"x-ifood-signature\") ?? header(\"x-signature\"),\n verifySignature: verifyIfoodSignature,\n cancellationReasons: () => reasons,\n // The Catalog API v2.0: each item is written and paused through the API (FUT-4768).\n catalogue: IFOOD_CATALOGUE,\n confirm: (ctx, order) => ifoodConfirm(ctx, order),\n requestCancellation: ifoodRequestCancellation,\n // No per-order deep link is known, so the portal, where a live order is\n // on the first screen.\n appLink: () => IFOOD_PORTAL_URL,\n };\n}\n\nexport { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from \"./copy\";\nexport { normalizeIfoodEvent, verifyIfoodSignature } from \"./normalize\";\nexport { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from \"./catalogue\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAaO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACHO,IAAM,YAAY;AACzB,IAAM,YAAY,GAAG,SAAS;AAC9B,IAAM,WAAW,wB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