@12-apps/marketplace 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/ADOPTING.md +184 -0
  2. package/README.md +39 -4
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-nUyZpLzz.d.ts → adapter-szxo9ohc.d.ts} +84 -3
  6. package/dist/{chunk-L6FG6T4S.js → chunk-BNWRIR5J.js} +2 -2
  7. package/dist/{chunk-LACBT6NC.js → chunk-BTKVZAJI.js} +1 -1
  8. package/dist/chunk-BTKVZAJI.js.map +1 -0
  9. package/dist/{chunk-45ZVN5XI.js → chunk-MDXSVE7Q.js} +707 -255
  10. package/dist/chunk-MDXSVE7Q.js.map +1 -0
  11. package/dist/{chunk-MIPNQ7X5.js → chunk-R3BUW5PX.js} +53 -6
  12. package/dist/chunk-R3BUW5PX.js.map +1 -0
  13. package/dist/{client-Ctas7WCS.d.ts → client-CaZiG7Lw.d.ts} +1 -1
  14. package/dist/{engine-CIy9P7Cq.d.ts → engine-CgKBbk9J.d.ts} +127 -3
  15. package/dist/hono/index.d.ts +2 -2
  16. package/dist/hono/index.js +2 -2
  17. package/dist/ifood/index.d.ts +26 -3
  18. package/dist/ifood/index.js +301 -140
  19. package/dist/ifood/index.js.map +1 -1
  20. package/dist/index.d.ts +29 -5
  21. package/dist/index.js +54 -6
  22. package/dist/index.js.map +1 -1
  23. package/dist/keeta/index.d.ts +2 -2
  24. package/dist/keeta/index.js +2 -2
  25. package/dist/manifest/server.d.ts +4 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +14 -5
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +17 -3
  33. package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
  34. package/src/core/acceptance.ts +12 -6
  35. package/src/core/acknowledge.ts +189 -0
  36. package/src/core/adapter.ts +76 -2
  37. package/src/core/cancellation.ts +10 -6
  38. package/src/core/conformity.ts +63 -0
  39. package/src/core/connection-stamp.ts +61 -0
  40. package/src/core/engine.ts +3 -2
  41. package/src/core/fetch-order.ts +54 -12
  42. package/src/core/ingest.ts +6 -0
  43. package/src/core/integration.ts +19 -4
  44. package/src/core/link-store.ts +2 -4
  45. package/src/core/marketplace-confirmed.ts +229 -0
  46. package/src/core/order-reasons.ts +119 -0
  47. package/src/core/outbound.ts +5 -1
  48. package/src/core/pipeline.ts +27 -1
  49. package/src/core/ports.ts +2 -0
  50. package/src/core/registry.ts +28 -2
  51. package/src/core/state.ts +10 -0
  52. package/src/core/status-job.ts +86 -3
  53. package/src/core/types.ts +6 -0
  54. package/src/ifood/fetch-order.ts +103 -0
  55. package/src/ifood/index.ts +31 -4
  56. package/src/ifood/normalize.ts +39 -3
  57. package/src/ifood/outbound.ts +131 -27
  58. package/src/index.ts +18 -0
  59. package/src/server/jobs.ts +57 -4
  60. package/src/server/webhook.ts +27 -4
  61. package/dist/chunk-45ZVN5XI.js.map +0 -1
  62. package/dist/chunk-LACBT6NC.js.map +0 -1
  63. package/dist/chunk-MIPNQ7X5.js.map +0 -1
  64. /package/dist/{chunk-L6FG6T4S.js.map → chunk-BNWRIR5J.js.map} +0 -0
@@ -17,7 +17,7 @@ import {
17
17
  answered,
18
18
  outboundResultOf,
19
19
  tokenGrantResultOf
20
- } from "../chunk-LACBT6NC.js";
20
+ } from "../chunk-BTKVZAJI.js";
21
21
  import {
22
22
  __name
23
23
  } from "../chunk-7QVYU63E.js";
@@ -43,7 +43,6 @@ var IFOOD_API = "https://merchant-api.ifood.com.br";
43
43
  var TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
44
44
  var orderUrl = /* @__PURE__ */ __name((externalOrderId, action) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`, "orderUrl");
45
45
  var IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
46
- var TOKEN_MARGIN_MS = 6e4;
47
46
  var ifoodTokenKey = /* @__PURE__ */ __name((ctx) => ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`, "ifoodTokenKey");
48
47
  function tokenOf(body) {
49
48
  try {
@@ -60,7 +59,7 @@ async function bearer(ctx) {
60
59
  if (ctx.grant) return ctx.grant.accessToken();
61
60
  const key = ifoodTokenKey(ctx);
62
61
  const cached = ctx.tokens.get(key);
63
- if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
62
+ if (cached && cached.expiresAt > ctx.now.getTime()) return { token: cached.token };
64
63
  const response = await ctx.http({
65
64
  method: "POST",
66
65
  url: TOKEN_URL,
@@ -78,39 +77,109 @@ async function bearer(ctx) {
78
77
  return { token: token.token };
79
78
  }
80
79
  __name(bearer, "bearer");
81
- function postOrder(ctx, externalOrderId, action, body) {
82
- return answered(async () => {
80
+ async function withIfoodToken(ctx, call5) {
81
+ for (let round = 0; round < 2; round += 1) {
83
82
  const auth = await bearer(ctx);
84
83
  if (!("token" in auth)) return auth;
85
- const response = await ctx.http({
86
- method: "POST",
87
- url: orderUrl(externalOrderId, action),
88
- headers: {
89
- Authorization: `Bearer ${auth.token}`,
90
- ...body === void 0 ? {} : { "Content-Type": "application/json" }
91
- },
92
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
93
- });
94
- if (response.status === 401) ctx.tokens.delete(ifoodTokenKey(ctx));
95
- return response.status === 401 ? { kind: "retry", reason: "iFood refused the token" } : outboundResultOf(response);
84
+ const response = await call5(auth.token);
85
+ if (response.status !== 401) return response;
86
+ ctx.tokens.delete(ifoodTokenKey(ctx));
87
+ }
88
+ return null;
89
+ }
90
+ __name(withIfoodToken, "withIfoodToken");
91
+ function callOrder(ctx, externalOrderId, action, body, method = "POST") {
92
+ return answered(async () => {
93
+ const response = await withIfoodToken(
94
+ ctx,
95
+ (token) => ctx.http({
96
+ method,
97
+ url: orderUrl(externalOrderId, action),
98
+ headers: {
99
+ Authorization: `Bearer ${token}`,
100
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
101
+ },
102
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
103
+ })
104
+ );
105
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
106
+ return "kind" in response ? response : outboundResultOf(response);
96
107
  });
97
108
  }
109
+ __name(callOrder, "callOrder");
110
+ function postOrder(ctx, externalOrderId, action, body) {
111
+ return callOrder(ctx, externalOrderId, action, body);
112
+ }
98
113
  __name(postOrder, "postOrder");
99
114
  function ifoodConfirm(ctx, order) {
100
115
  return postOrder(ctx, order.externalOrderId, "confirm");
101
116
  }
102
117
  __name(ifoodConfirm, "ifoodConfirm");
103
118
  function ifoodRequestCancellation(ctx, order, input) {
104
- return postOrder(ctx, order.externalOrderId, "requestCancellation", {
105
- reason: input.text === "" ? input.reason.label : input.text,
106
- cancellationCode: input.reason.code
107
- });
119
+ return postOrder(ctx, order.externalOrderId, "requestCancellation", { reason: input.reason.code });
108
120
  }
109
121
  __name(ifoodRequestCancellation, "ifoodRequestCancellation");
122
+ function reasonsOf(body) {
123
+ try {
124
+ const parsed2 = JSON.parse(body);
125
+ const list2 = Array.isArray(parsed2) ? parsed2 : parsed2?.reasons;
126
+ if (!Array.isArray(list2)) return null;
127
+ return list2.flatMap((entry) => {
128
+ const { code, description } = entry ?? {};
129
+ if (typeof code !== "string" && typeof code !== "number") return [];
130
+ return [{ code: String(code), description: typeof description === "string" ? description : String(code) }];
131
+ });
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ __name(reasonsOf, "reasonsOf");
137
+ async function ifoodOrderCancellationReasons(ctx, order) {
138
+ let body = "";
139
+ const result = await answered(async () => {
140
+ const response = await withIfoodToken(
141
+ ctx,
142
+ (token) => ctx.http({ method: "GET", url: orderUrl(order.externalOrderId, "cancellationReasons"), headers: { Authorization: `Bearer ${token}` } })
143
+ );
144
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
145
+ if ("kind" in response) return response;
146
+ body = response.body;
147
+ return outboundResultOf(response);
148
+ });
149
+ if (result.kind !== "accepted") return result;
150
+ const reasons = reasonsOf(body);
151
+ return reasons ? { kind: "reasons", reasons } : { kind: "retry", reason: "iFood answered the reasons with no list" };
152
+ }
153
+ __name(ifoodOrderCancellationReasons, "ifoodOrderCancellationReasons");
154
+ var IFOOD_EVENT_RETENTION_MS = 8 * 60 * 6e4;
155
+ var IFOOD_ACKNOWLEDGEMENT = {
156
+ batchSize: 2e3,
157
+ retentionMs: IFOOD_EVENT_RETENTION_MS,
158
+ send: /* @__PURE__ */ __name((ctx, eventIds) => answered(async () => {
159
+ const body = JSON.stringify(eventIds.map((id) => ({ id })));
160
+ const response = await withIfoodToken(
161
+ ctx,
162
+ (token) => ctx.http({
163
+ method: "POST",
164
+ url: `${IFOOD_API}/events/v1.0/events/acknowledgment`,
165
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
166
+ body
167
+ })
168
+ );
169
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
170
+ return "kind" in response ? response : outboundResultOf(response);
171
+ }), "send")
172
+ };
110
173
  var STATUS_ACTION = {
111
- READY: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? null : "readyToPickup", "READY"),
174
+ // Every order, the merchant's own bag included (FUT-5984, `endpoints.md`: "Para entrega própria,
175
+ // notifique o pedido pronto via `POST /orders/{id}/readyToPickup` antes de despachar via `/dispatch`").
176
+ READY: /* @__PURE__ */ __name(() => "readyToPickup", "READY"),
112
177
  DISPATCHED: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? "dispatch" : null, "DISPATCHED")
113
178
  };
179
+ function ifoodStatusPrerequisite(facts) {
180
+ return facts.step === "DISPATCHED" && facts.deliveredBy === "MERCHANT" ? "READY" : null;
181
+ }
182
+ __name(ifoodStatusPrerequisite, "ifoodStatusPrerequisite");
114
183
  function ifoodStatusSupported(facts) {
115
184
  return STATUS_ACTION[facts.step]?.(facts) != null;
116
185
  }
@@ -702,123 +771,11 @@ async function tracking(ctx, order) {
702
771
  __name(tracking, "tracking");
703
772
  var IFOOD_COURIER = { validatePickupCode, tracking };
704
773
 
705
- // src/ifood/linking.ts
706
- var USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
707
- var TOKEN_URL2 = `${IFOOD_API}/authentication/v1.0/oauth/token`;
708
- var MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
709
- var USER_CODE_SECONDS = 600;
710
- var ACCESS_TOKEN_SECONDS = 21600;
711
- var MERCHANT_PAGE_SIZE = 100;
712
- var MAX_MERCHANT_PAGES = 20;
713
- var FORM = { "Content-Type": "application/x-www-form-urlencoded" };
714
- function json(body) {
715
- try {
716
- return body === "" ? null : JSON.parse(body);
717
- } catch {
718
- return null;
719
- }
720
- }
721
- __name(json, "json");
722
- async function call3(ctx, request, read2) {
723
- try {
724
- const response = await ctx.http(request);
725
- const result = outboundResultOf(response);
726
- if (result.kind !== "accepted") return result;
727
- const value = read2(json(response.body));
728
- return value === null ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" } : { kind: "ok", value };
729
- } catch (error) {
730
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
731
- }
732
- }
733
- __name(call3, "call");
734
- var positive = /* @__PURE__ */ __name((value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback, "positive");
735
- function codeOf(body) {
736
- const userCode = asString(pick(body, "userCode"));
737
- const verifier = asString(pick(body, "authorizationCodeVerifier"));
738
- const verificationUrl = asString(pick(body, "verificationUrl"));
739
- if (!userCode || !verifier || !verificationUrl) return null;
740
- return {
741
- userCode,
742
- verifier,
743
- verificationUrl,
744
- verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
745
- expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS)
746
- };
747
- }
748
- __name(codeOf, "codeOf");
749
- function grantOf(body, requireRefresh) {
750
- const accessToken = asString(pick(body, "accessToken"));
751
- const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
752
- if (!accessToken || requireRefresh && !refreshToken) return null;
753
- return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
754
- }
755
- __name(grantOf, "grantOf");
756
- function merchantsOf(body) {
757
- if (!Array.isArray(body)) return null;
758
- return body.flatMap((raw) => {
759
- const id = asString(pick(raw, "id"));
760
- return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
761
- });
762
- }
763
- __name(merchantsOf, "merchantsOf");
764
- var tokenRequest = /* @__PURE__ */ __name((fields) => ({
765
- method: "POST",
766
- url: TOKEN_URL2,
767
- headers: FORM,
768
- body: new URLSearchParams(fields).toString()
769
- }), "tokenRequest");
770
- async function listMerchants(ctx, accessToken) {
771
- const all = [];
772
- for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
773
- const answer = await call3(
774
- ctx,
775
- {
776
- method: "GET",
777
- url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
778
- headers: { Authorization: `Bearer ${accessToken}` }
779
- },
780
- merchantsOf
781
- );
782
- if (answer.kind !== "ok") return answer;
783
- all.push(...answer.value);
784
- if (answer.value.length < MERCHANT_PAGE_SIZE) break;
785
- }
786
- return { kind: "ok", value: all };
787
- }
788
- __name(listMerchants, "listMerchants");
789
- var IFOOD_LINKING = {
790
- requestCode: /* @__PURE__ */ __name((ctx) => call3(
791
- ctx,
792
- { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
793
- codeOf
794
- ), "requestCode"),
795
- exchange: /* @__PURE__ */ __name((ctx, input) => call3(
796
- ctx,
797
- tokenRequest({
798
- grantType: "authorization_code",
799
- clientId: ctx.credentials.clientId,
800
- clientSecret: ctx.credentials.clientSecret,
801
- authorizationCode: input.authorizationCode,
802
- authorizationCodeVerifier: input.verifier
803
- }),
804
- (body) => grantOf(body, true)
805
- ), "exchange"),
806
- refresh: /* @__PURE__ */ __name((ctx, input) => call3(
807
- ctx,
808
- tokenRequest({
809
- grantType: "refresh_token",
810
- clientId: ctx.credentials.clientId,
811
- clientSecret: ctx.credentials.clientSecret,
812
- refreshToken: input.refreshToken
813
- }),
814
- (body) => grantOf(body, false)
815
- ), "refresh"),
816
- merchants: /* @__PURE__ */ __name((ctx, input) => listMerchants(ctx, input.accessToken), "merchants")
817
- };
818
-
819
774
  // src/ifood/normalize.ts
820
775
  var ORDER_PLACED = /* @__PURE__ */ new Set(["PLC", "PLACED", "ORDER_PLACED"]);
821
776
  var ORDER_CANCELLED = /* @__PURE__ */ new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
777
+ var ORDER_CONFIRMED = /* @__PURE__ */ new Set(["CFM", "CONFIRMED"]);
778
+ var KEEPALIVE = "KEEPALIVE";
822
779
  var CANCELLATION_REQUEST_FAILED = /* @__PURE__ */ new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
823
780
  var LIFECYCLE_OF = {
824
781
  DSP: "DISPATCHED",
@@ -915,7 +872,7 @@ function optional(key, value) {
915
872
  return value === void 0 ? {} : { [key]: value };
916
873
  }
917
874
  __name(optional, "optional");
918
- function readOrder(payload, externalOrderId, missingStreetNumber) {
875
+ function readIfoodOrder(payload, externalOrderId, missingStreetNumber) {
919
876
  const order = pick(payload, "order") ?? payload;
920
877
  const rawItems = pick(order, "items");
921
878
  const lines = (Array.isArray(rawItems) ? rawItems : []).map(readLine).filter((line) => line !== null);
@@ -948,7 +905,13 @@ function readOrder(payload, externalOrderId, missingStreetNumber) {
948
905
  pickupCode: firstString(order, [["delivery", "pickupCode"]])
949
906
  };
950
907
  }
951
- __name(readOrder, "readOrder");
908
+ __name(readIfoodOrder, "readIfoodOrder");
909
+ function placedOrder(payload, placed, externalOrderId, missingStreetNumber) {
910
+ if (!placed) return { order: null };
911
+ const order = readIfoodOrder(payload, externalOrderId, missingStreetNumber);
912
+ return order ? { order } : { order: null, orderToFetch: true };
913
+ }
914
+ __name(placedOrder, "placedOrder");
952
915
  function normalizeIfoodEvent(payload, options) {
953
916
  const externalOrderId = firstString(payload, [["orderId"], ["order", "id"], ["id"]]);
954
917
  if (!externalOrderId) return null;
@@ -966,14 +929,196 @@ function normalizeIfoodEvent(payload, options) {
966
929
  eventType,
967
930
  externalMerchantId: firstString(payload, [["merchantId"], ["merchant", "id"]]),
968
931
  externalOrderId,
969
- order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
932
+ ...placedOrder(payload, placed, externalOrderId, options.missingStreetNumber),
970
933
  cancelled,
971
934
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
972
935
  ...LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {},
973
- ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? void 0)
936
+ ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? void 0),
937
+ ...ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}
974
938
  };
975
939
  }
976
940
  __name(normalizeIfoodEvent, "normalizeIfoodEvent");
941
+ function readIfoodPresence(payload) {
942
+ const code = firstString(payload, [["fullCode"], ["code"]]);
943
+ if (code?.toUpperCase() !== KEEPALIVE) return null;
944
+ const ids = pick(payload, "merchantIds");
945
+ return { merchantIds: Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : null };
946
+ }
947
+ __name(readIfoodPresence, "readIfoodPresence");
948
+
949
+ // src/ifood/fetch-order.ts
950
+ var orderResourceUrl = /* @__PURE__ */ __name((externalOrderId) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`, "orderResourceUrl");
951
+ async function getOrder(ctx, externalOrderId) {
952
+ const auth = await bearer(ctx);
953
+ if (!("token" in auth)) {
954
+ return auth.kind === "accepted" ? { kind: "retry", reason: "iFood answered the token grant without a token" } : auth;
955
+ }
956
+ const response = await ctx.http({
957
+ method: "GET",
958
+ url: orderResourceUrl(externalOrderId),
959
+ headers: { Authorization: `Bearer ${auth.token}`, Accept: "application/json" }
960
+ });
961
+ return { response };
962
+ }
963
+ __name(getOrder, "getOrder");
964
+ function orderOf(body, externalOrderId, missingStreetNumber) {
965
+ let parsed2;
966
+ try {
967
+ parsed2 = JSON.parse(body);
968
+ } catch {
969
+ return { kind: "retry", reason: "iFood answered the order read with a body that is not JSON" };
970
+ }
971
+ const named = firstString(parsed2, [["id"]]);
972
+ if (named !== null && named !== externalOrderId) {
973
+ return { kind: "refused", status: 200, message: `iFood answered order ${named} for ${externalOrderId}` };
974
+ }
975
+ const order = readIfoodOrder(parsed2, externalOrderId, missingStreetNumber);
976
+ if (!order) return { kind: "refused", status: 200, message: "iFood answered an order with no items" };
977
+ return { kind: "order", order: { ...order, externalMerchantId: firstString(parsed2, [["merchant", "id"]]) } };
978
+ }
979
+ __name(orderOf, "orderOf");
980
+ function failureOf3(response) {
981
+ const message = response.body.slice(0, 300);
982
+ if (response.status === 401 || response.status === 403) {
983
+ return { kind: "refused", status: response.status, message, own: true };
984
+ }
985
+ if (response.status === 404) return { kind: "retry", reason: `status 404: ${message}` };
986
+ const result = outboundResultOf(response);
987
+ return result.kind === "accepted" ? { kind: "retry", reason: `status ${response.status}` } : result;
988
+ }
989
+ __name(failureOf3, "failureOf");
990
+ async function ifoodFetchOrder(ctx, ref, options) {
991
+ try {
992
+ let answer = await getOrder(ctx, ref.externalOrderId);
993
+ if ("response" in answer && answer.response.status === 401) {
994
+ ctx.tokens.delete(ifoodTokenKey(ctx));
995
+ answer = await getOrder(ctx, ref.externalOrderId);
996
+ }
997
+ if (!("response" in answer)) return answer;
998
+ const { response } = answer;
999
+ if (response.status >= 200 && response.status < 300) {
1000
+ return orderOf(response.body, ref.externalOrderId, options.missingStreetNumber);
1001
+ }
1002
+ return failureOf3(response);
1003
+ } catch (error) {
1004
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1005
+ }
1006
+ }
1007
+ __name(ifoodFetchOrder, "ifoodFetchOrder");
1008
+
1009
+ // src/ifood/linking.ts
1010
+ var USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
1011
+ var TOKEN_URL2 = `${IFOOD_API}/authentication/v1.0/oauth/token`;
1012
+ var MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
1013
+ var USER_CODE_SECONDS = 600;
1014
+ var ACCESS_TOKEN_SECONDS = 21600;
1015
+ var MERCHANT_PAGE_SIZE = 100;
1016
+ var MAX_MERCHANT_PAGES = 20;
1017
+ var FORM = { "Content-Type": "application/x-www-form-urlencoded" };
1018
+ function json(body) {
1019
+ try {
1020
+ return body === "" ? null : JSON.parse(body);
1021
+ } catch {
1022
+ return null;
1023
+ }
1024
+ }
1025
+ __name(json, "json");
1026
+ async function call3(ctx, request, read2) {
1027
+ try {
1028
+ const response = await ctx.http(request);
1029
+ const result = outboundResultOf(response);
1030
+ if (result.kind !== "accepted") return result;
1031
+ const value = read2(json(response.body));
1032
+ return value === null ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" } : { kind: "ok", value };
1033
+ } catch (error) {
1034
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1035
+ }
1036
+ }
1037
+ __name(call3, "call");
1038
+ var positive = /* @__PURE__ */ __name((value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback, "positive");
1039
+ function codeOf(body) {
1040
+ const userCode = asString(pick(body, "userCode"));
1041
+ const verifier = asString(pick(body, "authorizationCodeVerifier"));
1042
+ const verificationUrl = asString(pick(body, "verificationUrl"));
1043
+ if (!userCode || !verifier || !verificationUrl) return null;
1044
+ return {
1045
+ userCode,
1046
+ verifier,
1047
+ verificationUrl,
1048
+ verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
1049
+ expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS)
1050
+ };
1051
+ }
1052
+ __name(codeOf, "codeOf");
1053
+ function grantOf(body, requireRefresh) {
1054
+ const accessToken = asString(pick(body, "accessToken"));
1055
+ const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
1056
+ if (!accessToken || requireRefresh && !refreshToken) return null;
1057
+ return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
1058
+ }
1059
+ __name(grantOf, "grantOf");
1060
+ function merchantsOf(body) {
1061
+ if (!Array.isArray(body)) return null;
1062
+ return body.flatMap((raw) => {
1063
+ const id = asString(pick(raw, "id"));
1064
+ return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
1065
+ });
1066
+ }
1067
+ __name(merchantsOf, "merchantsOf");
1068
+ var tokenRequest = /* @__PURE__ */ __name((fields) => ({
1069
+ method: "POST",
1070
+ url: TOKEN_URL2,
1071
+ headers: FORM,
1072
+ body: new URLSearchParams(fields).toString()
1073
+ }), "tokenRequest");
1074
+ async function listMerchants(ctx, accessToken) {
1075
+ const all = [];
1076
+ for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
1077
+ const answer = await call3(
1078
+ ctx,
1079
+ {
1080
+ method: "GET",
1081
+ url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
1082
+ headers: { Authorization: `Bearer ${accessToken}` }
1083
+ },
1084
+ merchantsOf
1085
+ );
1086
+ if (answer.kind !== "ok") return answer;
1087
+ all.push(...answer.value);
1088
+ if (answer.value.length < MERCHANT_PAGE_SIZE) break;
1089
+ }
1090
+ return { kind: "ok", value: all };
1091
+ }
1092
+ __name(listMerchants, "listMerchants");
1093
+ var IFOOD_LINKING = {
1094
+ requestCode: /* @__PURE__ */ __name((ctx) => call3(
1095
+ ctx,
1096
+ { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
1097
+ codeOf
1098
+ ), "requestCode"),
1099
+ exchange: /* @__PURE__ */ __name((ctx, input) => call3(
1100
+ ctx,
1101
+ tokenRequest({
1102
+ grantType: "authorization_code",
1103
+ clientId: ctx.credentials.clientId,
1104
+ clientSecret: ctx.credentials.clientSecret,
1105
+ authorizationCode: input.authorizationCode,
1106
+ authorizationCodeVerifier: input.verifier
1107
+ }),
1108
+ (body) => grantOf(body, true)
1109
+ ), "exchange"),
1110
+ refresh: /* @__PURE__ */ __name((ctx, input) => call3(
1111
+ ctx,
1112
+ tokenRequest({
1113
+ grantType: "refresh_token",
1114
+ clientId: ctx.credentials.clientId,
1115
+ clientSecret: ctx.credentials.clientSecret,
1116
+ refreshToken: input.refreshToken
1117
+ }),
1118
+ (body) => grantOf(body, false)
1119
+ ), "refresh"),
1120
+ merchants: /* @__PURE__ */ __name((ctx, input) => listMerchants(ctx, input.accessToken), "merchants")
1121
+ };
977
1122
 
978
1123
  // src/ifood/pause.ts
979
1124
  var interruptionsUrl = /* @__PURE__ */ __name((merchantId) => `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`, "interruptionsUrl");
@@ -1162,7 +1307,13 @@ function createIfoodAdapter(config) {
1162
1307
  // Told what iFood has an endpoint for (ESTIMATED, see `./outbound.ts`): ready for
1163
1308
  // pickup, and dispatched for a merchant bag. Never "handed over": iFood's own
1164
1309
  // CONCLUDED is that.
1165
- statusSteps: ["READY", "DISPATCHED"]
1310
+ statusSteps: ["READY", "DISPATCHED"],
1311
+ // "Retorne `202 Accepted` em até 5 segundos" (Events `webhook-overview`, FUT-5984).
1312
+ webhookAnswerStatus: 202,
1313
+ // CFM: the store accepted on iFood's own app (FUT-5653).
1314
+ marketplaceConfirms: true,
1315
+ // A step is told only once iFood took the confirm (FUT-5673).
1316
+ statusAfterConfirm: true
1166
1317
  },
1167
1318
  normalize: /* @__PURE__ */ __name((payload) => normalizeIfoodEvent(payload, normalizeOptions), "normalize"),
1168
1319
  readSignature: /* @__PURE__ */ __name((header) => header("x-ifood-signature") ?? header("x-signature"), "readSignature"),
@@ -1174,8 +1325,15 @@ function createIfoodAdapter(config) {
1174
1325
  catalogueReader: IFOOD_CATALOGUE_READER,
1175
1326
  confirm: /* @__PURE__ */ __name((ctx, order) => ifoodConfirm(ctx, order), "confirm"),
1176
1327
  requestCancellation: ifoodRequestCancellation,
1328
+ // iFood's events carry only the order id: a PLACED with no items is fetched (FUT-5800).
1329
+ fetchOrder: /* @__PURE__ */ __name((ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions), "fetchOrder"),
1177
1330
  statusSupported: ifoodStatusSupported,
1178
1331
  informStatus: ifoodInformStatus,
1332
+ statusPrerequisite: ifoodStatusPrerequisite,
1333
+ // The presence heartbeat, the events' acknowledgment and each order's own reasons (FUT-5984).
1334
+ presence: readIfoodPresence,
1335
+ acknowledgement: IFOOD_ACKNOWLEDGEMENT,
1336
+ orderCancellationReasons: ifoodOrderCancellationReasons,
1179
1337
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
1180
1338
  availability: IFOOD_AVAILABILITY,
1181
1339
  // The distributed-app authorization: a store links the software's own app (FUT-5613).
@@ -1199,6 +1357,7 @@ export {
1199
1357
  IFOOD_PROVIDER,
1200
1358
  IFOOD_REASON_CODES,
1201
1359
  createIfoodAdapter,
1360
+ ifoodFetchOrder,
1202
1361
  ifoodItemBody,
1203
1362
  ifoodItemId,
1204
1363
  ifoodLocalTime,
@@ -1207,6 +1366,8 @@ export {
1207
1366
  ifoodResume,
1208
1367
  normalizeIfoodEvent,
1209
1368
  readIfoodCourierEvent,
1369
+ readIfoodOrder,
1370
+ readIfoodPresence,
1210
1371
  verifyIfoodSignature
1211
1372
  };
1212
1373
  //# sourceMappingURL=index.js.map