@12-apps/marketplace 1.19.0 → 1.20.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.
@@ -51,14 +51,17 @@ function defaultCatalogIdIn(body) {
51
51
  return null;
52
52
  }
53
53
  if (!Array.isArray(parsed2)) return null;
54
- for (const entry of parsed2) {
55
- if (typeof entry !== "object" || entry === null) continue;
56
- const { catalogId, context } = entry;
57
- if (typeof catalogId === "string" && catalogId !== "" && Array.isArray(context) && context.includes("DEFAULT")) return catalogId;
58
- }
59
- return null;
54
+ const defaults = parsed2.map(defaultEntryOf).filter((entry) => entry !== null);
55
+ return (defaults.find((entry) => entry.available) ?? defaults[0])?.catalogId ?? null;
60
56
  }
61
57
  __name(defaultCatalogIdIn, "defaultCatalogIdIn");
58
+ function defaultEntryOf(entry) {
59
+ if (typeof entry !== "object" || entry === null) return null;
60
+ const { catalogId, context, status } = entry;
61
+ if (typeof catalogId !== "string" || catalogId === "" || !Array.isArray(context) || !context.includes("DEFAULT")) return null;
62
+ return { catalogId, available: status === "AVAILABLE" };
63
+ }
64
+ __name(defaultEntryOf, "defaultEntryOf");
62
65
  var categoriesPath = /* @__PURE__ */ __name((catalogId) => `catalogs/${encodeURIComponent(catalogId)}/categories`, "categoriesPath");
63
66
 
64
67
  // src/ifood/outbound.ts
@@ -217,7 +220,7 @@ __name(ifoodInformStatus, "ifoodInformStatus");
217
220
  var catalogUrl = /* @__PURE__ */ __name((merchantId, path) => `${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`, "catalogUrl");
218
221
  var ifoodItemId = /* @__PURE__ */ __name((ref) => stableUuid(`${ref}:item`), "ifoodItemId");
219
222
  var ifoodProductId = /* @__PURE__ */ __name((ref) => stableUuid(`${ref}:product`), "ifoodProductId");
220
- var priceOf = /* @__PURE__ */ __name((cents) => ({ value: Math.round(cents) / 100 }), "priceOf");
223
+ var priceOf = /* @__PURE__ */ __name((cents2) => ({ value: Math.round(cents2) / 100 }), "priceOf");
221
224
  async function call(ctx, method, path, body) {
222
225
  const auth = await bearer(ctx);
223
226
  if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
@@ -274,27 +277,25 @@ async function findCategoryIn(ctx, catalogId, name) {
274
277
  return { id: categoryIdIn(listed.body, name) };
275
278
  }
276
279
  __name(findCategoryIn, "findCategoryIn");
277
- async function findCategory(ctx, name) {
278
- const catalog = await catalogOf(ctx);
279
- return "kind" in catalog ? catalog : findCategoryIn(ctx, catalog.catalogId, name);
280
- }
281
- __name(findCategory, "findCategory");
282
- async function findOrCreateCategory(ctx, name) {
283
- const catalog = await catalogOf(ctx);
280
+ async function findOrCreateCategory(ctx, name, catalogId) {
281
+ const catalog = catalogId === void 0 ? await catalogOf(ctx) : { catalogId };
284
282
  if ("kind" in catalog) return catalog;
285
283
  const found = await findCategoryIn(ctx, catalog.catalogId, name);
286
284
  if ("kind" in found) return found;
287
- if (found.id) return { id: found.id };
288
- const created = await call(ctx, "POST", categoriesPath(catalog.catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
285
+ return found.id ? { id: found.id } : createCategoryIn(ctx, catalog.catalogId, name);
286
+ }
287
+ __name(findOrCreateCategory, "findOrCreateCategory");
288
+ async function createCategoryIn(ctx, catalogId, name) {
289
+ const created = await call(ctx, "POST", categoriesPath(catalogId), { name, status: "AVAILABLE", template: "DEFAULT" });
289
290
  if ("kind" in created) return created;
290
291
  if (!ok(created)) return failureOf(created);
291
292
  const id = parse(created.body)?.id;
292
293
  if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
293
- const again = await findCategoryIn(ctx, catalog.catalogId, name);
294
+ const again = await findCategoryIn(ctx, catalogId, name);
294
295
  return "id" in again && again.id ? { id: again.id } : { id };
295
296
  }
296
- __name(findOrCreateCategory, "findOrCreateCategory");
297
- var categoryId = /* @__PURE__ */ __name((ctx, name) => ctx.category(name, () => findOrCreateCategory(ctx, name)), "categoryId");
297
+ __name(createCategoryIn, "createCategoryIn");
298
+ var categoryId = /* @__PURE__ */ __name((ctx, name, catalogId) => ctx.category(name, () => findOrCreateCategory(ctx, name, catalogId)), "categoryId");
298
299
  async function photoFor(ctx, item) {
299
300
  const stored = item.storedImage;
300
301
  if (item.imageUrl === null) return { image: null };
@@ -347,18 +348,22 @@ function ifoodItemBody(item, category, image) {
347
348
  }
348
349
  __name(ifoodItemBody, "ifoodItemBody");
349
350
  async function categoryWentStale(ctx, put, name, used) {
350
- if (put.status !== 400 && put.status !== 404) return false;
351
- const found = await findCategory(ctx, name);
352
- return !("kind" in found) && found.id !== used;
351
+ if (put.status !== 400 && put.status !== 404) return null;
352
+ const catalog = await catalogOf(ctx);
353
+ if ("kind" in catalog) return null;
354
+ const found = await findCategoryIn(ctx, catalog.catalogId, name);
355
+ return !("kind" in found) && found.id !== used ? catalog : null;
353
356
  }
354
357
  __name(categoryWentStale, "categoryWentStale");
355
358
  async function putItem(ctx, item, image) {
356
359
  const category = await categoryId(ctx, item.categoryName);
357
360
  if ("kind" in category) return category;
358
361
  const put = await call(ctx, "PUT", "items", ifoodItemBody(item, category.id, image));
359
- if ("kind" in put || ok(put) || !await categoryWentStale(ctx, put, item.categoryName, category.id)) return put;
362
+ if ("kind" in put || ok(put)) return put;
363
+ const stale = await categoryWentStale(ctx, put, item.categoryName, category.id);
364
+ if (stale === null) return put;
360
365
  await ctx.forgetCategory(item.categoryName);
361
- const again = await categoryId(ctx, item.categoryName);
366
+ const again = await categoryId(ctx, item.categoryName, stale.catalogId);
362
367
  if ("kind" in again) return again;
363
368
  return call(ctx, "PUT", "items", ifoodItemBody(item, again.id, image));
364
369
  }
@@ -790,7 +795,7 @@ function plusSeconds(base, seconds) {
790
795
  return seconds === null ? null : new Date(base.getTime() + seconds * 1e3);
791
796
  }
792
797
  __name(plusSeconds, "plusSeconds");
793
- function readTracking(body, now) {
798
+ function readIfoodTracking(body, now) {
794
799
  const trackedAt = firstDate(body, [["trackDate"]]);
795
800
  const base = trackedAt ?? now;
796
801
  const pickupSeconds = numberAt(body, "pickupEtaStart") ?? numberAt(body, "pickupEta");
@@ -803,7 +808,7 @@ function readTracking(body, now) {
803
808
  trackedAt
804
809
  };
805
810
  }
806
- __name(readTracking, "readTracking");
811
+ __name(readIfoodTracking, "readIfoodTracking");
807
812
  async function tracking(ctx, order) {
808
813
  try {
809
814
  const response = await call2(ctx, { method: "GET", url: orderUrl2(order, "tracking") });
@@ -811,7 +816,7 @@ async function tracking(ctx, order) {
811
816
  if (response.status === 404) return { kind: "notYet" };
812
817
  const read2 = outboundResultOf(response);
813
818
  if (read2.kind !== "accepted") return read2;
814
- return { kind: "tracking", tracking: readTracking(parsed(response.body), ctx.now) };
819
+ return { kind: "tracking", tracking: readIfoodTracking(parsed(response.body), ctx.now) };
815
820
  } catch (error) {
816
821
  return retryOf(error);
817
822
  }
@@ -1173,10 +1178,10 @@ function readIfoodAdditionalFees(order) {
1173
1178
  const raw = pick(order, "additionalFees");
1174
1179
  if (!Array.isArray(raw)) return void 0;
1175
1180
  return raw.flatMap((fee) => {
1176
- const cents = toCents(pick(fee, "value"));
1177
- if (cents === null) return [];
1181
+ const cents2 = toCents(pick(fee, "value"));
1182
+ if (cents2 === null) return [];
1178
1183
  const name = firstString(fee, [["description"]]);
1179
- return [{ kind: firstString(fee, [["type"]])?.toUpperCase() ?? "OTHER", cents, ...name === null ? {} : { name } }];
1184
+ return [{ kind: firstString(fee, [["type"]])?.toUpperCase() ?? "OTHER", cents: cents2, ...name === null ? {} : { name } }];
1180
1185
  });
1181
1186
  }
1182
1187
  __name(readIfoodAdditionalFees, "readIfoodAdditionalFees");
@@ -1485,8 +1490,8 @@ __name(merchantsOf, "merchantsOf");
1485
1490
  var first = /* @__PURE__ */ __name((raw, ...keys) => {
1486
1491
  for (const key of keys) {
1487
1492
  const value = pick(raw, key);
1488
- const text2 = typeof value === "number" ? String(value) : asString(value);
1489
- if (text2 && text2.trim() !== "") return text2.trim();
1493
+ const text3 = typeof value === "number" ? String(value) : asString(value);
1494
+ if (text3 && text3.trim() !== "") return text3.trim();
1490
1495
  }
1491
1496
  return null;
1492
1497
  }, "first");
@@ -1790,6 +1795,486 @@ var IFOOD_AVAILABILITY = {
1790
1795
  resume: ifoodResume
1791
1796
  };
1792
1797
 
1798
+ // src/ifood/shipping-wire.ts
1799
+ var IFOOD_SHIPPING_API = `${IFOOD_API}/shipping/v1.0`;
1800
+ var IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS = 5 * 6e4;
1801
+ var IFOOD_SHIPPING_ERROR_CODES = [
1802
+ "BadRequest",
1803
+ "BadRequestCustomer",
1804
+ "BadRequestMerchant",
1805
+ "DeliveryDistanceTooHigh",
1806
+ "OffOpeningHours",
1807
+ "OriginNotFound",
1808
+ "ServiceAreaMismatch",
1809
+ "HighDemand",
1810
+ "MerchantStatusAvailability",
1811
+ "MerchantEasyDeliveryDisabled",
1812
+ "InvalidPaymentMethods",
1813
+ "SaturatedOfflinePayment",
1814
+ "NRELimitExceeded",
1815
+ "UnavailableFleet",
1816
+ "PaymentMethodNotFound",
1817
+ "PaymentTotalInvalid",
1818
+ "OrderNotFound",
1819
+ "OrderWithoutSafeDelivery",
1820
+ "ChangeAddressOperationConflict",
1821
+ "ChangeAddressOperationNotStarted",
1822
+ "MaxDistanceHigherThanAllowed",
1823
+ "RegionMismatch"
1824
+ ];
1825
+ var TRANSIENT_CODES = /* @__PURE__ */ new Set(["HighDemand", "OffOpeningHours", "NRELimitExceeded", "UnavailableFleet"]);
1826
+ function idempotencyKeyValid(key) {
1827
+ return /^[\w:.-]{1,255}$/.test(key);
1828
+ }
1829
+ __name(idempotencyKeyValid, "idempotencyKeyValid");
1830
+ function errorCodeOf(body) {
1831
+ let parsed2;
1832
+ try {
1833
+ parsed2 = JSON.parse(body);
1834
+ } catch {
1835
+ return null;
1836
+ }
1837
+ const code = pick(parsed2, "code");
1838
+ if (typeof code !== "string") return null;
1839
+ return IFOOD_SHIPPING_ERROR_CODES.includes(code) ? code : "UNKNOWN";
1840
+ }
1841
+ __name(errorCodeOf, "errorCodeOf");
1842
+ var READ_RETRY_STATUSES = /* @__PURE__ */ new Set([408, 425, 429]);
1843
+ var POST_RETRY_STATUSES = /* @__PURE__ */ new Set([425, 429, 503]);
1844
+ function retriable(method, status) {
1845
+ if (method === "POST") return POST_RETRY_STATUSES.has(status);
1846
+ return status >= 500 || READ_RETRY_STATUSES.has(status) || POST_RETRY_STATUSES.has(status);
1847
+ }
1848
+ __name(retriable, "retriable");
1849
+ var mayBeApplied = /* @__PURE__ */ __name((method, status) => method === "POST" && (status >= 500 || status === 408), "mayBeApplied");
1850
+ function failureOf5(method, status, body) {
1851
+ const code = errorCodeOf(body);
1852
+ const reason = `iFood Shipping answered ${status}`;
1853
+ if (status >= 400 && retriable(method, status)) return { kind: "retry", reason };
1854
+ if (mayBeApplied(method, status)) return { kind: "uncertain", reason };
1855
+ if ((status === 400 || status === 409) && code !== null) return { kind: "unavailable", status, code, transient: TRANSIENT_CODES.has(code) };
1856
+ return { kind: "refused", status, message: `${reason}${code ? ` ${code}` : ""}` };
1857
+ }
1858
+ __name(failureOf5, "failureOf");
1859
+ function renewAhead(ctx) {
1860
+ if (ctx.grant) return;
1861
+ const key = ifoodTokenKey(ctx);
1862
+ const cached = ctx.tokens.get(key);
1863
+ if (cached && cached.expiresAt - ctx.now.getTime() <= IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS) ctx.tokens.delete(key);
1864
+ }
1865
+ __name(renewAhead, "renewAhead");
1866
+ async function shippingCall(ctx, request) {
1867
+ let sent = false;
1868
+ try {
1869
+ renewAhead(ctx);
1870
+ const response = await withIfoodToken(ctx, async (token) => {
1871
+ sent = true;
1872
+ const answer = await ctx.http({
1873
+ method: request.method,
1874
+ url: request.url,
1875
+ headers: {
1876
+ Authorization: `Bearer ${token}`,
1877
+ ...request.body === void 0 ? {} : { "Content-Type": "application/json" },
1878
+ ...request.idempotencyKey === void 0 ? {} : { "Idempotency-Key": request.idempotencyKey }
1879
+ },
1880
+ ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) }
1881
+ });
1882
+ if (answer.status === 401) sent = false;
1883
+ return answer;
1884
+ });
1885
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
1886
+ if ("kind" in response) return response.kind === "accepted" ? { kind: "retry", reason: "no token" } : response;
1887
+ if (response.status >= 200 && response.status < 300) return { kind: "answer", status: response.status, body: response.body };
1888
+ return failureOf5(request.method, response.status, response.body);
1889
+ } catch {
1890
+ if (sent && request.method === "POST") return { kind: "uncertain", reason: "iFood Shipping request sent, no answer" };
1891
+ return { kind: "retry", reason: sent ? "iFood Shipping read got no answer" : "iFood token request got no answer" };
1892
+ }
1893
+ }
1894
+ __name(shippingCall, "shippingCall");
1895
+ async function shippingPost(ctx, url, idempotencyKey, body) {
1896
+ if (!idempotencyKeyValid(idempotencyKey)) return { kind: "invalid", reason: "IDEMPOTENCY_KEY" };
1897
+ const answer = await shippingCall(ctx, { method: "POST", url, body, idempotencyKey });
1898
+ return answer.kind === "answer" ? { kind: "requested" } : answer;
1899
+ }
1900
+ __name(shippingPost, "shippingPost");
1901
+ function parsedBody(body) {
1902
+ try {
1903
+ return JSON.parse(body);
1904
+ } catch {
1905
+ return null;
1906
+ }
1907
+ }
1908
+ __name(parsedBody, "parsedBody");
1909
+ function numberAt2(source, ...path) {
1910
+ const value = pick(source, ...path);
1911
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
1912
+ }
1913
+ __name(numberAt2, "numberAt");
1914
+ var reais = /* @__PURE__ */ __name((cents2) => Math.round(cents2) / 100, "reais");
1915
+ function coordinatesValid(point) {
1916
+ const { latitude, longitude } = point;
1917
+ return Number.isFinite(latitude) && Number.isFinite(longitude) && Math.abs(latitude) <= 90 && Math.abs(longitude) <= 180;
1918
+ }
1919
+ __name(coordinatesValid, "coordinatesValid");
1920
+ function ifoodShippingRetryDelayMs(attempt, random = Math.random) {
1921
+ if (!Number.isInteger(attempt) || attempt < 1 || attempt > 5) return null;
1922
+ if (attempt === 1) return 0;
1923
+ return 2 ** (attempt - 2) * 1e3 + Math.floor(random() * 1e3);
1924
+ }
1925
+ __name(ifoodShippingRetryDelayMs, "ifoodShippingRetryDelayMs");
1926
+
1927
+ // src/ifood/shipping.ts
1928
+ var orderUrl3 = /* @__PURE__ */ __name((externalOrderId, action) => `${IFOOD_SHIPPING_API}/orders/${encodeURIComponent(externalOrderId)}/${action}`, "orderUrl");
1929
+ function paymentMethodsOf(body) {
1930
+ const list2 = pick(body, "paymentMethods");
1931
+ if (!Array.isArray(list2)) return [];
1932
+ return list2.flatMap((entry) => {
1933
+ const method = firstString(entry, [["method"]]);
1934
+ const paymentType = firstString(entry, [["paymentType"]]);
1935
+ if (method === null || paymentType === null) return [];
1936
+ return [{ method, paymentType, brand: firstString(entry, [["brand"]]), liability: firstString(entry, [["liability"]]) }];
1937
+ });
1938
+ }
1939
+ __name(paymentMethodsOf, "paymentMethodsOf");
1940
+ function quoteOf(body) {
1941
+ const id = firstString(body, [["id"]]);
1942
+ const expiresAt = firstDate(body, [["expirationAt"]]);
1943
+ const grossCents = toCents(pick(body, "quote", "grossValue"));
1944
+ const netCents = toCents(pick(body, "quote", "netValue"));
1945
+ if (id === null || expiresAt === null || grossCents === null || netCents === null) return null;
1946
+ return {
1947
+ id,
1948
+ expiresAt,
1949
+ createdAt: firstDate(body, [["createdAt"]]),
1950
+ distanceMeters: numberAt2(body, "distance"),
1951
+ preparationTimeSeconds: numberAt2(body, "preparationTime"),
1952
+ grossCents,
1953
+ discountCents: toCents(pick(body, "quote", "discount")) ?? 0,
1954
+ raiseCents: toCents(pick(body, "quote", "raise")) ?? 0,
1955
+ netCents,
1956
+ deliveryTimeSeconds: { min: numberAt2(body, "deliveryTime", "min"), max: numberAt2(body, "deliveryTime", "max") },
1957
+ paymentMethods: paymentMethodsOf(body)
1958
+ };
1959
+ }
1960
+ __name(quoteOf, "quoteOf");
1961
+ async function quote(ctx, url) {
1962
+ const answer = await shippingCall(ctx, { method: "GET", url });
1963
+ if (answer.kind !== "answer") return answer;
1964
+ const read2 = quoteOf(parsedBody(answer.body));
1965
+ return read2 ? { kind: "quote", quote: read2 } : { kind: "retry", reason: "iFood Shipping answered a quote without an id" };
1966
+ }
1967
+ __name(quote, "quote");
1968
+ function ifoodShippingQuoteForOrder(ctx, externalOrderId) {
1969
+ return quote(ctx, orderUrl3(externalOrderId, "deliveryAvailabilities"));
1970
+ }
1971
+ __name(ifoodShippingQuoteForOrder, "ifoodShippingQuoteForOrder");
1972
+ async function ifoodShippingQuoteForAddress(ctx, merchantId, point) {
1973
+ if (!coordinatesValid(point)) return { kind: "invalid", reason: "COORDINATES" };
1974
+ const query = new URLSearchParams({ latitude: String(point.latitude), longitude: String(point.longitude) });
1975
+ return quote(ctx, `${IFOOD_SHIPPING_API}/merchants/${encodeURIComponent(merchantId)}/deliveryAvailabilities?${query.toString()}`);
1976
+ }
1977
+ __name(ifoodShippingQuoteForAddress, "ifoodShippingQuoteForAddress");
1978
+ async function ifoodRequestDriver(ctx, input) {
1979
+ if (input.quote.expiresAt.getTime() <= ctx.now.getTime()) return { kind: "invalid", reason: "QUOTE_EXPIRED" };
1980
+ return shippingPost(ctx, orderUrl3(input.externalOrderId, "requestDriver"), input.idempotencyKey, { quoteId: input.quote.id });
1981
+ }
1982
+ __name(ifoodRequestDriver, "ifoodRequestDriver");
1983
+ function ifoodCancelRequestDriver(ctx, input) {
1984
+ return shippingPost(ctx, orderUrl3(input.externalOrderId, "cancelRequestDriver"), input.idempotencyKey);
1985
+ }
1986
+ __name(ifoodCancelRequestDriver, "ifoodCancelRequestDriver");
1987
+ async function ifoodShippingTracking(ctx, orderId) {
1988
+ const answer = await shippingCall(ctx, { method: "GET", url: orderUrl3(orderId, "tracking") });
1989
+ if (answer.kind === "refused" && answer.status === 404) return { kind: "notYet" };
1990
+ if (answer.kind !== "answer") return answer;
1991
+ return { kind: "tracking", tracking: readIfoodTracking(parsedBody(answer.body), ctx.now) };
1992
+ }
1993
+ __name(ifoodShippingTracking, "ifoodShippingTracking");
1994
+
1995
+ // src/ifood/shipping-address.ts
1996
+ var orderUrl4 = /* @__PURE__ */ __name((orderId, action) => `${IFOOD_SHIPPING_API}/orders/${encodeURIComponent(orderId)}/${action}`, "orderUrl");
1997
+ var trimmed = /* @__PURE__ */ __name((value) => (value ?? "").trim(), "trimmed");
1998
+ function withinLengths(address) {
1999
+ const max = [
2000
+ [address.streetName, 50],
2001
+ [address.neighborhood, 50],
2002
+ [address.city, 50],
2003
+ [address.complement, 50],
2004
+ [address.reference, 70]
2005
+ ];
2006
+ return max.every(([value, limit]) => trimmed(value).length <= limit) && trimmed(address.city).length !== 1;
2007
+ }
2008
+ __name(withinLengths, "withinLengths");
2009
+ function requiredValid(address) {
2010
+ const present = [address.streetName, address.neighborhood, address.city].every((v) => trimmed(v) !== "");
2011
+ const letters = /^[A-Za-z]{2}$/.test(address.state) && /^[A-Za-z]{2}$/.test(address.country);
2012
+ return present && letters && withinLengths(address) && coordinatesValid(address);
2013
+ }
2014
+ __name(requiredValid, "requiredValid");
2015
+ function optionalFields(address) {
2016
+ const fields = {};
2017
+ for (const key of ["streetNumber", "complement", "reference"]) {
2018
+ const value = trimmed(address[key]);
2019
+ if (value !== "") fields[key] = value;
2020
+ }
2021
+ return fields;
2022
+ }
2023
+ __name(optionalFields, "optionalFields");
2024
+ function ifoodShippingAddressBody(address, kind) {
2025
+ const postalCode = address.postalCode.replace(/\D/g, "");
2026
+ const orderValid = postalCode.length === 8 && trimmed(address.streetNumber) !== "";
2027
+ if (kind === "order" && !orderValid || !requiredValid(address)) return null;
2028
+ return {
2029
+ ...kind === "order" ? { postalCode } : {},
2030
+ ...optionalFields(address),
2031
+ streetName: trimmed(address.streetName),
2032
+ neighborhood: trimmed(address.neighborhood),
2033
+ city: trimmed(address.city),
2034
+ state: address.state.toUpperCase(),
2035
+ country: address.country.toUpperCase(),
2036
+ coordinates: { latitude: address.latitude, longitude: address.longitude }
2037
+ };
2038
+ }
2039
+ __name(ifoodShippingAddressBody, "ifoodShippingAddressBody");
2040
+ var ADDRESS_REFUSALS = /* @__PURE__ */ new Set([
2041
+ "ChangeAddressOperationConflict",
2042
+ "ChangeAddressOperationNotStarted",
2043
+ "MaxDistanceHigherThanAllowed",
2044
+ "RegionMismatch"
2045
+ ]);
2046
+ async function addressPost(ctx, url, idempotencyKey, body) {
2047
+ const result = await shippingPost(ctx, url, idempotencyKey, body);
2048
+ if (result.kind === "unavailable" && ADDRESS_REFUSALS.has(result.code)) {
2049
+ return { kind: "address-change-refused", status: result.status, code: result.code };
2050
+ }
2051
+ return result;
2052
+ }
2053
+ __name(addressPost, "addressPost");
2054
+ function ifoodShippingConfirmAddress(ctx, orderId, idempotencyKey) {
2055
+ return addressPost(ctx, orderUrl4(orderId, "userConfirmAddress"), idempotencyKey);
2056
+ }
2057
+ __name(ifoodShippingConfirmAddress, "ifoodShippingConfirmAddress");
2058
+ var IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS = 500;
2059
+ function metersBetween(a, b) {
2060
+ const rad = Math.PI / 180;
2061
+ const dLat = (b.latitude - a.latitude) * rad;
2062
+ const dLon = (b.longitude - a.longitude) * rad;
2063
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(a.latitude * rad) * Math.cos(b.latitude * rad) * Math.sin(dLon / 2) ** 2;
2064
+ return 2 * 6371e3 * Math.asin(Math.sqrt(h));
2065
+ }
2066
+ __name(metersBetween, "metersBetween");
2067
+ function ifoodShippingRequestAddressChange(ctx, orderId, address, idempotencyKey, original) {
2068
+ const body = ifoodShippingAddressBody(address, "change");
2069
+ if (body === null) return Promise.resolve({ kind: "invalid", reason: "ADDRESS" });
2070
+ if (original && metersBetween(original, address) > IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS) {
2071
+ return Promise.resolve({ kind: "invalid", reason: "ADDRESS_TOO_FAR" });
2072
+ }
2073
+ return addressPost(ctx, orderUrl4(orderId, "deliveryAddressChangeRequest"), idempotencyKey, body);
2074
+ }
2075
+ __name(ifoodShippingRequestAddressChange, "ifoodShippingRequestAddressChange");
2076
+ function ifoodShippingAcceptAddressChange(ctx, orderId, idempotencyKey) {
2077
+ return addressPost(ctx, orderUrl4(orderId, "acceptDeliveryAddressChange"), idempotencyKey);
2078
+ }
2079
+ __name(ifoodShippingAcceptAddressChange, "ifoodShippingAcceptAddressChange");
2080
+ function ifoodShippingDenyAddressChange(ctx, orderId, idempotencyKey) {
2081
+ return addressPost(ctx, orderUrl4(orderId, "denyDeliveryAddressChange"), idempotencyKey);
2082
+ }
2083
+ __name(ifoodShippingDenyAddressChange, "ifoodShippingDenyAddressChange");
2084
+ var SCORES = ["LOW", "MODERATE", "HIGH", "VERY_HIGH"];
2085
+ async function ifoodShippingSafeDelivery(ctx, orderId) {
2086
+ const answer = await shippingCall(ctx, { method: "GET", url: orderUrl4(orderId, "safeDelivery") });
2087
+ if (answer.kind === "unavailable" && answer.code === "OrderWithoutSafeDelivery") return { kind: "none" };
2088
+ if (answer.kind !== "answer") return answer;
2089
+ const parsed2 = parsedBody(answer.body);
2090
+ const score = pick(parsed2, "score");
2091
+ if (typeof score !== "string" || !SCORES.includes(score)) return { kind: "retry", reason: "iFood Shipping answered no score" };
2092
+ const rawRules = pick(parsed2, "rules");
2093
+ const rules = Object.fromEntries(
2094
+ Object.entries(rawRules !== null && typeof rawRules === "object" ? rawRules : {}).filter((entry) => typeof entry[1] === "boolean")
2095
+ );
2096
+ return { kind: "score", score, rules };
2097
+ }
2098
+ __name(ifoodShippingSafeDelivery, "ifoodShippingSafeDelivery");
2099
+
2100
+ // src/ifood/shipping-orders.ts
2101
+ var orderUrl5 = /* @__PURE__ */ __name((orderId, action) => `${IFOOD_SHIPPING_API}/orders/${encodeURIComponent(orderId)}/${action}`, "orderUrl");
2102
+ var NAME_MAX = 50;
2103
+ var text2 = /* @__PURE__ */ __name((value, max) => (value ?? "").trim().slice(0, max), "text");
2104
+ function phoneOf(raw) {
2105
+ let digits = raw.replace(/\D/g, "");
2106
+ if (digits.length >= 12 && digits.startsWith("55")) digits = digits.slice(2);
2107
+ if (digits.length < 10 || digits.length > 11) return null;
2108
+ return { countryCode: "55", areaCode: digits.slice(0, 2), number: digits.slice(2) };
2109
+ }
2110
+ __name(phoneOf, "phoneOf");
2111
+ var cents = /* @__PURE__ */ __name((value) => Number.isInteger(value) && value >= 0, "cents");
2112
+ function itemsBody(items) {
2113
+ if (items.length === 0) return null;
2114
+ const valid = items.every(
2115
+ (item) => text2(item.id, 100) !== "" && text2(item.name, NAME_MAX) !== "" && Number.isInteger(item.quantity) && item.quantity > 0 && cents(item.unitPriceCents) && cents(item.optionsPriceCents)
2116
+ );
2117
+ if (!valid) return null;
2118
+ return items.map((item) => {
2119
+ const priceCents = item.quantity * item.unitPriceCents;
2120
+ return {
2121
+ id: item.id,
2122
+ name: text2(item.name, NAME_MAX),
2123
+ ...item.externalCode ? { externalCode: item.externalCode } : {},
2124
+ quantity: item.quantity,
2125
+ unitPrice: reais(item.unitPriceCents),
2126
+ price: reais(priceCents),
2127
+ optionsPrice: reais(item.optionsPriceCents),
2128
+ totalPrice: reais(priceCents + item.optionsPriceCents)
2129
+ };
2130
+ });
2131
+ }
2132
+ __name(itemsBody, "itemsBody");
2133
+ function customerBody(customer) {
2134
+ const name = text2(customer.name, NAME_MAX);
2135
+ if (name === "") return { kind: "invalid", reason: "CUSTOMER_NAME" };
2136
+ const phone = phoneOf(customer.phone);
2137
+ if (phone === null) return { kind: "invalid", reason: "CUSTOMER_PHONE" };
2138
+ return { name, phone: { ...phone, type: "CUSTOMER" } };
2139
+ }
2140
+ __name(customerBody, "customerBody");
2141
+ function deliveryBody(delivery, now) {
2142
+ if (delivery.quote.expiresAt.getTime() <= now.getTime()) return { kind: "invalid", reason: "QUOTE_EXPIRED" };
2143
+ if (!cents(delivery.merchantFeeCents)) return { kind: "invalid", reason: "MERCHANT_FEE" };
2144
+ if (!cents(delivery.preparationTimeSeconds ?? 0)) return { kind: "invalid", reason: "PREPARATION_TIME" };
2145
+ const deliveryAddress = ifoodShippingAddressBody(delivery.address, "order");
2146
+ if (deliveryAddress === null) return { kind: "invalid", reason: "ADDRESS" };
2147
+ return {
2148
+ merchantFee: reais(delivery.merchantFeeCents),
2149
+ ...delivery.preparationTimeSeconds === void 0 ? {} : { preparationTime: delivery.preparationTimeSeconds },
2150
+ quoteId: delivery.quote.id,
2151
+ deliveryAddress
2152
+ };
2153
+ }
2154
+ __name(deliveryBody, "deliveryBody");
2155
+ var isInvalid = /* @__PURE__ */ __name((value) => value.kind === "invalid", "isInvalid");
2156
+ function orderBody(input, now) {
2157
+ const customer = customerBody(input.customer);
2158
+ if (isInvalid(customer)) return customer;
2159
+ const delivery = deliveryBody(input.delivery, now);
2160
+ if (isInvalid(delivery)) return delivery;
2161
+ const items = itemsBody(input.items);
2162
+ if (items === null) return { kind: "invalid", reason: "ITEMS" };
2163
+ if (input.displayId !== void 0 && !/^\S{1,4}$/.test(input.displayId)) return { kind: "invalid", reason: "DISPLAY_ID" };
2164
+ return { customer, delivery, items, ...input.displayId === void 0 ? {} : { displayId: input.displayId } };
2165
+ }
2166
+ __name(orderBody, "orderBody");
2167
+ function httpsUrl2(value) {
2168
+ if (value === null || value.length > 2048) return null;
2169
+ try {
2170
+ return new URL(value).protocol === "https:" ? value : null;
2171
+ } catch {
2172
+ return null;
2173
+ }
2174
+ }
2175
+ __name(httpsUrl2, "httpsUrl");
2176
+ async function ifoodShippingCreateOrder(ctx, merchantId, input, idempotencyKey) {
2177
+ if (!idempotencyKeyValid(idempotencyKey)) return { kind: "invalid", reason: "IDEMPOTENCY_KEY" };
2178
+ const body = orderBody(input, ctx.now);
2179
+ if (isInvalid(body)) return body;
2180
+ const url = `${IFOOD_SHIPPING_API}/merchants/${encodeURIComponent(merchantId)}/orders`;
2181
+ const answer = await shippingCall(ctx, { method: "POST", url, body, idempotencyKey });
2182
+ if (answer.kind !== "answer") return answer;
2183
+ const parsed2 = parsedBody(answer.body);
2184
+ const id = firstString(parsed2, [["id"]]);
2185
+ if (id === null) return { kind: "uncertain", reason: "iFood Shipping took the order without an id" };
2186
+ return { kind: "created", id, trackingUrl: httpsUrl2(firstString(parsed2, [["trackingUrl"]])) };
2187
+ }
2188
+ __name(ifoodShippingCreateOrder, "ifoodShippingCreateOrder");
2189
+ async function ifoodShippingCancellationReasons(ctx, orderId) {
2190
+ const answer = await shippingCall(ctx, { method: "GET", url: orderUrl5(orderId, "cancellationReasons") });
2191
+ if (answer.kind !== "answer") return answer;
2192
+ if (answer.status === 204) return { kind: "not-cancellable" };
2193
+ const list2 = parsedBody(answer.body);
2194
+ if (!Array.isArray(list2)) return { kind: "retry", reason: "iFood Shipping answered the reasons with no list" };
2195
+ const reasons = list2.flatMap((entry) => {
2196
+ const code = pick(entry, "cancelCodeId");
2197
+ if (typeof code !== "string" && typeof code !== "number") return [];
2198
+ return [{ code: String(code), description: firstString(entry, [["description"]]) ?? String(code) }];
2199
+ });
2200
+ return { kind: "reasons", reasons };
2201
+ }
2202
+ __name(ifoodShippingCancellationReasons, "ifoodShippingCancellationReasons");
2203
+ function ifoodShippingCancel(ctx, orderId, input, idempotencyKey) {
2204
+ if (!/^\d{1,9}$/.test(input.code)) return Promise.resolve({ kind: "invalid", reason: "CANCELLATION_CODE" });
2205
+ const reason = input.reason.trim();
2206
+ if (reason === "") return Promise.resolve({ kind: "invalid", reason: "CANCELLATION_REASON" });
2207
+ return shippingPost(ctx, orderUrl5(orderId, "cancel"), idempotencyKey, { reason, cancellationCode: Number(input.code) });
2208
+ }
2209
+ __name(ifoodShippingCancel, "ifoodShippingCancel");
2210
+
2211
+ // src/ifood/shipping-events.ts
2212
+ var IFOOD_SHIPPING_EVENT_TYPES = [
2213
+ "REQUEST_DRIVER",
2214
+ "REQUEST_DRIVER_SUCCESS",
2215
+ "REQUEST_DRIVER_FAILED",
2216
+ "DELIVERY_DROP_CODE_REQUESTED",
2217
+ "DELIVERY_IN_TRANSIT",
2218
+ "DELIVERY_CONCLUDED",
2219
+ "DELIVERY_CANCELLED",
2220
+ "DELIVERY_CANCELLATION_REQUESTED",
2221
+ "DELIVERY_CANCELLATION_REQUEST_ACCEPTED",
2222
+ "DELIVERY_CANCELLATION_REQUEST_REJECTED",
2223
+ "CANCELLATION_REQUESTED",
2224
+ "CANCELLED",
2225
+ "DELIVERY_ADDRESS_CHANGE_USER_CONFIRMED",
2226
+ "DELIVERY_ADDRESS_CHANGE_ACCEPTED"
2227
+ ];
2228
+ var SIMPLE = new Set(IFOOD_SHIPPING_EVENT_TYPES);
2229
+ function metadataOf2(payload) {
2230
+ const raw = pick(payload, "metadata");
2231
+ if (typeof raw !== "string") return raw;
2232
+ try {
2233
+ return JSON.parse(raw);
2234
+ } catch {
2235
+ return null;
2236
+ }
2237
+ }
2238
+ __name(metadataOf2, "metadataOf");
2239
+ function numberAt3(source, ...path) {
2240
+ const value = pick(source, ...path);
2241
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2242
+ }
2243
+ __name(numberAt3, "numberAt");
2244
+ function addressOf(metadata) {
2245
+ const address = pick(metadata, "address");
2246
+ const field = /* @__PURE__ */ __name((key) => firstString(address, [[key]]), "field");
2247
+ return {
2248
+ streetName: field("streetName"),
2249
+ streetNumber: field("streetNumber"),
2250
+ complement: field("complement"),
2251
+ reference: field("reference"),
2252
+ neighborhood: field("neighborhood"),
2253
+ city: field("city"),
2254
+ state: field("state"),
2255
+ country: field("country"),
2256
+ latitude: numberAt3(address, "coordinates", "latitude"),
2257
+ longitude: numberAt3(address, "coordinates", "longitude")
2258
+ };
2259
+ }
2260
+ __name(addressOf, "addressOf");
2261
+ function readIfoodShippingEvent(payload) {
2262
+ const type = (firstString(payload, [["fullCode"], ["code"]]) ?? "").toUpperCase();
2263
+ const eventId = firstString(payload, [["id"], ["eventId"]]);
2264
+ const orderId = firstString(payload, [["orderId"]]);
2265
+ if (eventId === null || orderId === null) return null;
2266
+ const base = { eventId, orderId, salesChannel: firstString(payload, [["salesChannel"]]), at: firstDate(payload, [["createdAt"]]) };
2267
+ if (SIMPLE.has(type)) return { ...base, type };
2268
+ if (type === "DELIVERY_ADDRESS_CHANGE_REQUESTED") return { ...base, type, address: addressOf(metadataOf2(payload)) };
2269
+ if (type === "CANCELLATION_REQUEST_FAILED") {
2270
+ return { ...base, type, reason: firstString(metadataOf2(payload), [["CANCELLATION_REQUEST_FAILED_REASON"]]) };
2271
+ }
2272
+ if (type === "DELIVERY_ADDRESS_CHANGE_DENIED") return { ...base, type, action: firstString(metadataOf2(payload), [["action"]]) };
2273
+ const courier = readIfoodCourierEvent(payload, type);
2274
+ return courier ? { ...base, type: "COURIER", courier } : null;
2275
+ }
2276
+ __name(readIfoodShippingEvent, "readIfoodShippingEvent");
2277
+
1793
2278
  // src/ifood/index.ts
1794
2279
  var IFOOD_PROVIDER = "IFOOD";
1795
2280
  var ITEM_UNAVAILABLE = "503";
@@ -1883,8 +2368,14 @@ export {
1883
2368
  IFOOD_LOGISTICS_VEHICLES,
1884
2369
  IFOOD_PROVIDER,
1885
2370
  IFOOD_REASON_CODES,
2371
+ IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS,
2372
+ IFOOD_SHIPPING_API,
2373
+ IFOOD_SHIPPING_ERROR_CODES,
2374
+ IFOOD_SHIPPING_EVENT_TYPES,
2375
+ IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS,
1886
2376
  createIfoodAdapter,
1887
2377
  ifoodAddressLine,
2378
+ ifoodCancelRequestDriver,
1888
2379
  ifoodFetchOrder,
1889
2380
  ifoodItemBody,
1890
2381
  ifoodItemId,
@@ -1895,11 +2386,25 @@ export {
1895
2386
  ifoodLogisticsVerifyDeliveryCode,
1896
2387
  ifoodPause,
1897
2388
  ifoodProductId,
2389
+ ifoodRequestDriver,
1898
2390
  ifoodResume,
2391
+ ifoodShippingAcceptAddressChange,
2392
+ ifoodShippingCancel,
2393
+ ifoodShippingCancellationReasons,
2394
+ ifoodShippingConfirmAddress,
2395
+ ifoodShippingCreateOrder,
2396
+ ifoodShippingDenyAddressChange,
2397
+ ifoodShippingQuoteForAddress,
2398
+ ifoodShippingQuoteForOrder,
2399
+ ifoodShippingRequestAddressChange,
2400
+ ifoodShippingRetryDelayMs,
2401
+ ifoodShippingSafeDelivery,
2402
+ ifoodShippingTracking,
1899
2403
  normalizeIfoodEvent,
1900
2404
  readIfoodCourierEvent,
1901
2405
  readIfoodOrder,
1902
2406
  readIfoodPresence,
2407
+ readIfoodShippingEvent,
1903
2408
  verifyIfoodSignature
1904
2409
  };
1905
2410
  //# sourceMappingURL=index.js.map