@storepecker/storefront-core 2.9.1 → 2.10.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 (65) hide show
  1. package/dist/address-BdIB6IuI.d.cts +42 -0
  2. package/dist/address-BdIB6IuI.d.ts +42 -0
  3. package/dist/api/index.cjs +16 -12
  4. package/dist/api/index.d.cts +13 -3
  5. package/dist/api/index.d.ts +13 -3
  6. package/dist/api/index.js +2 -2
  7. package/dist/{buy-now-BqVWXyy8.d.cts → buy-now-B_15RUVT.d.cts} +1 -1
  8. package/dist/{buy-now-DFdnuLjO.d.ts → buy-now-kII0KrhP.d.ts} +1 -1
  9. package/dist/checkout/index.cjs +108 -15
  10. package/dist/checkout/index.d.cts +25 -1
  11. package/dist/checkout/index.d.ts +25 -1
  12. package/dist/checkout/index.js +3 -2
  13. package/dist/{chunk-IG4BW3ZB.cjs → chunk-32X4SWN4.cjs} +3 -3
  14. package/dist/{chunk-RDUT4W3B.cjs → chunk-6APRQ2ED.cjs} +4 -1
  15. package/dist/{chunk-ICKTXS6B.js → chunk-6IXTFZFS.js} +3 -3
  16. package/dist/{chunk-7M5CVYZJ.js → chunk-A7EI7XLU.js} +8 -1
  17. package/dist/{chunk-CBKJ3Y2I.js → chunk-EWZ7TGI7.js} +11 -1
  18. package/dist/{chunk-5XVHYPOC.js → chunk-FF5N7PTB.js} +1 -1
  19. package/dist/{chunk-XFOUNOKO.cjs → chunk-KNG4OMS5.cjs} +8 -0
  20. package/dist/chunk-QED6QJZC.cjs +603 -0
  21. package/dist/{chunk-W6BDMNSU.js → chunk-QVO56X4E.js} +1 -1
  22. package/dist/{chunk-6LS5F4R3.cjs → chunk-SGJUMI3M.cjs} +11 -0
  23. package/dist/{chunk-YLLAP3H2.cjs → chunk-SGKLMS7W.cjs} +2 -2
  24. package/dist/{chunk-ZGMLOLTC.js → chunk-VRZRV2BR.js} +4 -1
  25. package/dist/{chunk-IVKJJLG7.cjs → chunk-WWJAPKRQ.cjs} +8 -8
  26. package/dist/chunk-Y4RNRPBC.js +545 -0
  27. package/dist/components/address-form.cjs +6 -6
  28. package/dist/components/address-form.d.cts +10 -6
  29. package/dist/components/address-form.d.ts +10 -6
  30. package/dist/components/address-form.js +5 -5
  31. package/dist/components/index.cjs +8 -8
  32. package/dist/components/index.d.cts +3 -3
  33. package/dist/components/index.d.ts +3 -3
  34. package/dist/components/index.js +6 -6
  35. package/dist/components/search-dropdown.d.cts +4 -4
  36. package/dist/components/search-dropdown.d.ts +4 -4
  37. package/dist/components/share-button.cjs +3 -3
  38. package/dist/components/share-button.js +2 -2
  39. package/dist/components/theme-data-initializer.d.cts +1 -1
  40. package/dist/components/theme-data-initializer.d.ts +1 -1
  41. package/dist/hooks/index.cjs +644 -20
  42. package/dist/hooks/index.d.cts +233 -9
  43. package/dist/hooks/index.d.ts +233 -9
  44. package/dist/hooks/index.js +624 -8
  45. package/dist/models/index.d.cts +3 -2
  46. package/dist/models/index.d.ts +3 -2
  47. package/dist/pincode-8u7yWLpQ.d.cts +29 -0
  48. package/dist/pincode-8u7yWLpQ.d.ts +29 -0
  49. package/dist/pincode-CHM-ZD3H.d.ts +179 -0
  50. package/dist/pincode-Ch3bZSJz.d.cts +179 -0
  51. package/dist/{pixelEvents-BtEO5QAR.d.cts → pixelEvents-COqZIgTu.d.cts} +1 -0
  52. package/dist/{pixelEvents-LsealscG.d.ts → pixelEvents-Ds6fwS9t.d.ts} +1 -0
  53. package/dist/store/index.d.cts +1 -1
  54. package/dist/store/index.d.ts +1 -1
  55. package/dist/{useAddressForm-DGbEn91-.d.cts → useAddressForm-fMOb5Z-a.d.ts} +6 -1
  56. package/dist/{useAddressForm-cO3Au33k.d.ts → useAddressForm-wleIo78M.d.cts} +6 -1
  57. package/dist/utils/index.cjs +58 -54
  58. package/dist/utils/index.d.cts +12 -3
  59. package/dist/utils/index.d.ts +12 -3
  60. package/dist/utils/index.js +3 -3
  61. package/package.json +1 -1
  62. package/dist/address-DwBZHzbI.d.cts +0 -19
  63. package/dist/address-DwBZHzbI.d.ts +0 -19
  64. package/dist/chunk-34Y7Y5FU.cjs +0 -246
  65. package/dist/chunk-VPTN4YXD.js +0 -232
@@ -3,22 +3,25 @@ import { findMatchingVariant, findSimilarVariant, isVariantCombinationAvailable,
3
3
  import { useCartStore, useAuthStore } from '../chunk-QQHQTBAM.js';
4
4
  import { getCart, getProductList, getProductDetail, getWishlist, notifyProductStock, getProductCategories, getCategories } from '../chunk-ZAWZ3RB6.js';
5
5
  import { cart_default } from '../chunk-TH7OAMGC.js';
6
- import { processPayment, fetchAvailableCoupons, applyCheckoutCoupon, removeCheckoutCoupon } from '../chunk-VPTN4YXD.js';
7
- import { applyCoupon, removeCoupon, getCoupons, getAppliedCoupon } from '../chunk-7M5CVYZJ.js';
6
+ import { processPayment, fetchAvailableCoupons, applyCheckoutCoupon, removeCheckoutCoupon, buildAddressFormat, validatePincode, PINCODE_DEBOUNCE_MS, findSubdivision, getAreaOptions, NO_POSTAL_CODE, joinAddressLines, sanitizePhoneInput, lowerLabel, buildAddressSchema, usableEmail, findStateByName, normalizePostcode, getPincodeError, detectForeignPhone, PINCODE_MIN_LENGTH, loadAddressFormat } from '../chunk-Y4RNRPBC.js';
7
+ import { applyCoupon, removeCoupon, getCoupons, getAppliedCoupon } from '../chunk-A7EI7XLU.js';
8
8
  import '../chunk-VAU5OL72.js';
9
9
  import { getOrders, placeOrder, buyNowPreview, placeGuestBuyNowOrder, placeBuyNowOrder, publicCheckoutPreview, placePublicOrder } from '../chunk-KCLVR6G5.js';
10
- export { useAddressForm } from '../chunk-ICKTXS6B.js';
11
- import { getAddresses } from '../chunk-ZGMLOLTC.js';
12
- import '../chunk-OSM73ETC.js';
13
- import { shareLink, convertToCurrency } from '../chunk-CBKJ3Y2I.js';
10
+ export { useAddressForm } from '../chunk-6IXTFZFS.js';
11
+ import { getAddresses, getCountries, getSubdivisions } from '../chunk-VRZRV2BR.js';
12
+ import { shareLink, convertToCurrency, focusFirstInvalidField } from '../chunk-EWZ7TGI7.js';
14
13
  import '../chunk-HSF2D56O.js';
15
- import '../chunk-ELP23UGF.js';
14
+ import { useThemeData } from '../chunk-5NUDTIQ2.js';
15
+ import { IP_API_CACHE_KEY } from '../chunk-ELP23UGF.js';
16
+ import { getCache } from '../chunk-OSM73ETC.js';
16
17
  import '../chunk-3SYYP3XV.js';
17
18
  import '../chunk-WEMNXIRS.js';
18
19
  import '../chunk-BQ256JKN.js';
19
20
  import '../chunk-JQMLHRWL.js';
20
21
  import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
21
22
  import { AxiosError } from 'axios';
23
+ import { useFormik } from 'formik';
24
+ import { getCountryCallingCode, isSupportedCountry } from 'libphonenumber-js';
22
25
 
23
26
  var useAddress = () => {
24
27
  const [data, setData] = useState([]);
@@ -1324,4 +1327,617 @@ function useCoupon(options = {}) {
1324
1327
  };
1325
1328
  }
1326
1329
 
1327
- export { BUY_NOW_PAYLOAD_KEY, useAddress, useBuyNow, useCart, useCheckoutCoupon, useCheckoutPayment, useCoupon, useGetProductCategories, useGetProductDetails, useGetProducts, useInlineCheckoutPayment, useOrders, useProductDetailModal, usePublicCheckout, useServiceFormModal, useShopCheckout, useUserDetails, useVariantSelector, useWishlist };
1330
+ // src/utils/once.ts
1331
+ var store = /* @__PURE__ */ new Map();
1332
+ function once(key, fn) {
1333
+ let promise = store.get(key);
1334
+ if (!promise) {
1335
+ promise = fn().catch((error) => {
1336
+ store.delete(key);
1337
+ throw error;
1338
+ });
1339
+ store.set(key, promise);
1340
+ }
1341
+ return promise;
1342
+ }
1343
+
1344
+ // src/hooks/useCountries.ts
1345
+ var NO_COUNTRIES = [];
1346
+ var NO_STATES = [];
1347
+ function useOnce(key, fetcher) {
1348
+ const [state, setState] = useState({ key: null });
1349
+ useEffect(() => {
1350
+ if (!key) return;
1351
+ let active = true;
1352
+ once(key, fetcher).then(
1353
+ (data) => active && setState({ key, data }),
1354
+ (error) => active && setState({ key, error })
1355
+ );
1356
+ return () => {
1357
+ active = false;
1358
+ };
1359
+ }, [key]);
1360
+ const current = state.key === key ? state : { data: void 0, error: void 0 };
1361
+ return {
1362
+ data: current.data,
1363
+ error: current.error,
1364
+ isLoading: !!key && current.data === void 0 && current.error === void 0
1365
+ };
1366
+ }
1367
+ var useCountries = () => {
1368
+ const { data, error, isLoading } = useOnce("utils/countries/", async () => (await getCountries()).data);
1369
+ return { countries: data ?? NO_COUNTRIES, error, isLoading };
1370
+ };
1371
+ var useSubdivisions = (countryId) => {
1372
+ const { data, error, isLoading } = useOnce(
1373
+ countryId ? `utils/subdivisions/:${countryId}` : null,
1374
+ async () => (await getSubdivisions(countryId)).data.results
1375
+ );
1376
+ return { states: data ?? NO_STATES, error, isLoading };
1377
+ };
1378
+ function useAddressFormat(countryCode) {
1379
+ const [state, setState] = useState({});
1380
+ useEffect(() => {
1381
+ if (!countryCode) return;
1382
+ let active = true;
1383
+ once(`address-format:${countryCode}`, () => loadAddressFormat(countryCode)).then(
1384
+ (format) => active && setState({ code: countryCode, format }),
1385
+ (error) => active && setState({ code: countryCode, error })
1386
+ );
1387
+ return () => {
1388
+ active = false;
1389
+ };
1390
+ }, [countryCode]);
1391
+ const fallback = useMemo(() => buildAddressFormat(countryCode ?? "", null), [countryCode]);
1392
+ const current = state.code === countryCode ? state : {};
1393
+ return {
1394
+ format: current.format ?? fallback,
1395
+ error: current.error,
1396
+ isLoading: !!countryCode && !current.format && current.error === void 0
1397
+ };
1398
+ }
1399
+ var NO_ANSWER = { key: "", invalid: false, match: null };
1400
+ var keyFor = (countryCode, pincode) => `${countryCode ?? ""}:${pincode.trim().toUpperCase()}`;
1401
+ function usePincodeLookup({
1402
+ countryCode,
1403
+ pincode,
1404
+ ready,
1405
+ states,
1406
+ stateId,
1407
+ onMatch,
1408
+ enabled: enabledOption
1409
+ }) {
1410
+ const storeEnabled = useThemeData((s) => !!s.themeData?.pincode_validation_enabled);
1411
+ const enabled = enabledOption ?? storeEnabled;
1412
+ const [answer, setAnswer] = useState(NO_ANSWER);
1413
+ const [loading, setLoading] = useState(false);
1414
+ const key = keyFor(countryCode, pincode);
1415
+ const current = answer.key === key ? answer : NO_ANSWER;
1416
+ const onMatchRef = useRef(onMatch);
1417
+ onMatchRef.current = onMatch;
1418
+ const latest = useRef({ pincode, states, stateId });
1419
+ latest.current = { pincode, states, stateId };
1420
+ const requestRef = useRef(0);
1421
+ const lookUp = useCallback(
1422
+ async (value) => {
1423
+ const request = ++requestRef.current;
1424
+ setLoading(true);
1425
+ const result = await validatePincode(value, countryCode);
1426
+ if (request === requestRef.current) {
1427
+ setLoading(false);
1428
+ setAnswer({ key: keyFor(countryCode, value), invalid: result.status === "invalid", match: result.match });
1429
+ }
1430
+ return result;
1431
+ },
1432
+ [countryCode]
1433
+ );
1434
+ useEffect(() => {
1435
+ if (!enabled || !ready) return;
1436
+ const value = pincode.trim();
1437
+ const timer = setTimeout(() => lookUp(value), PINCODE_DEBOUNCE_MS);
1438
+ return () => {
1439
+ clearTimeout(timer);
1440
+ requestRef.current += 1;
1441
+ setLoading(false);
1442
+ };
1443
+ }, [enabled, ready, pincode, lookUp]);
1444
+ const { match } = current;
1445
+ useEffect(() => {
1446
+ if (match) onMatchRef.current(match, findSubdivision(states, match));
1447
+ }, [match, states]);
1448
+ const mismatchState = useMemo(() => {
1449
+ if (!match || !stateId) return void 0;
1450
+ const pincodeState = findSubdivision(states, match);
1451
+ return pincodeState && String(pincodeState.id) !== stateId ? pincodeState.name : void 0;
1452
+ }, [match, states, stateId]);
1453
+ const issue = useMemo(() => {
1454
+ if (current.serverMessage) return { kind: "server", message: current.serverMessage };
1455
+ if (current.invalid) return { kind: "invalid" };
1456
+ if (mismatchState) return { kind: "mismatch", stateName: mismatchState };
1457
+ return null;
1458
+ }, [current.serverMessage, current.invalid, mismatchState]);
1459
+ const checkNow = useCallback(() => {
1460
+ const value = latest.current.pincode.trim();
1461
+ if (enabled && value) lookUp(value);
1462
+ }, [enabled, lookUp]);
1463
+ const verify = useCallback(async () => {
1464
+ const value = latest.current.pincode.trim();
1465
+ if (!enabled || !value) return null;
1466
+ const result = await lookUp(value);
1467
+ const { states: currentStates, stateId: currentStateId } = latest.current;
1468
+ if (result.status === "invalid") return { kind: "invalid" };
1469
+ if (result.status === "valid" && currentStateId) {
1470
+ const pincodeState = findSubdivision(currentStates, result.match);
1471
+ if (pincodeState && String(pincodeState.id) !== currentStateId) {
1472
+ return { kind: "mismatch", stateName: pincodeState.name };
1473
+ }
1474
+ }
1475
+ return null;
1476
+ }, [enabled, lookUp]);
1477
+ const setServerError = useCallback(
1478
+ (message) => setAnswer((prev) => {
1479
+ const serverKey = keyFor(countryCode, latest.current.pincode);
1480
+ return { ...prev.key === serverKey ? prev : NO_ANSWER, key: serverKey, serverMessage: message };
1481
+ }),
1482
+ [countryCode]
1483
+ );
1484
+ const areaOptions = useMemo(() => getAreaOptions(match), [match]);
1485
+ return { enabled, loading, issue, areaOptions, checkNow, verify, setServerError };
1486
+ }
1487
+ var INDIA_ID = 105;
1488
+ var EMPTY_ADDRESS_FORM_VALUES = {
1489
+ customer_name: "",
1490
+ customer_email: "",
1491
+ customer_phone: "",
1492
+ customer_country_code: "",
1493
+ country_obj: "",
1494
+ country_name: "",
1495
+ state_obj: "",
1496
+ state_name: "",
1497
+ city: "",
1498
+ pincode: "",
1499
+ address: "",
1500
+ address_line_2: "",
1501
+ is_default: false
1502
+ };
1503
+ function toAddressPayload(values) {
1504
+ const phoneCountry = values.customer_country_code;
1505
+ return {
1506
+ customer_name: values.customer_name.trim(),
1507
+ customer_email: values.customer_email.trim(),
1508
+ customer_phone: sanitizePhoneInput(values.customer_phone, values.customer_country_code),
1509
+ customer_country_code: phoneCountry ? `+${getCountryCallingCode(phoneCountry)}` : "",
1510
+ address: joinAddressLines(values.address, values.address_line_2),
1511
+ city: values.city.trim(),
1512
+ state_obj: values.state_obj,
1513
+ state: values.state_name,
1514
+ country_obj: Number(values.country_obj),
1515
+ country: values.country_name,
1516
+ pincode: values.pincode.trim() || NO_POSTAL_CODE,
1517
+ is_default: values.is_default
1518
+ };
1519
+ }
1520
+ function isPincodeReady(format, value) {
1521
+ const code = value.trim();
1522
+ if (!format.hasPostal || !code || code === NO_POSTAL_CODE) return false;
1523
+ if (format.postalStrict && format.postalPattern) return format.postalPattern.test(code);
1524
+ return code.length >= PINCODE_MIN_LENGTH && (!format.postalPattern || format.postalPattern.test(code));
1525
+ }
1526
+ function isPincodeCheckableOnBlur(format, value) {
1527
+ const code = value.trim();
1528
+ if (!format.hasPostal || !code || code === NO_POSTAL_CODE) return false;
1529
+ if (format.postalStrict || !format.postalPattern) return false;
1530
+ return format.postalPattern.test(code);
1531
+ }
1532
+ function describePincodeIssue(issue, format) {
1533
+ if (!issue) return void 0;
1534
+ const postal = lowerLabel(format.postalLabel);
1535
+ if (issue.kind === "server") return issue.message;
1536
+ if (issue.kind === "invalid") return `We couldn't find this ${postal}. Check it and try again.`;
1537
+ return `This ${postal} is in ${issue.stateName}. Check the ${postal} or the ${lowerLabel(format.regionLabel)}.`;
1538
+ }
1539
+ var dialCode = (iso) => `+${getCountryCallingCode(iso)}`;
1540
+ function phoneIsoFromDialCode(dial, addressCountry, countries) {
1541
+ if (!dial) return addressCountry.tld_code;
1542
+ const normalized = dial.startsWith("+") ? dial : `+${dial}`;
1543
+ if (dialCode(addressCountry.tld_code) === normalized) return addressCountry.tld_code;
1544
+ return countries.find((c) => dialCode(c.tld_code) === normalized)?.tld_code ?? addressCountry.tld_code;
1545
+ }
1546
+ function resolveInitialValues(countries, address, draft, defaultCountryId, locationCacheKey) {
1547
+ const byId = (id) => countries.find((c) => c.id === Number(id));
1548
+ const byIso = (iso) => countries.find((c) => c.tld_code === iso);
1549
+ const fallback = byId(defaultCountryId) ?? countries[0];
1550
+ if (address) {
1551
+ const country2 = byId(address.country_obj) ?? countries.find((c) => c.name.toLowerCase() === address.country?.toLowerCase()) ?? fallback;
1552
+ const phoneIso = phoneIsoFromDialCode(address.customer_country_code, country2, countries);
1553
+ return {
1554
+ values: {
1555
+ ...EMPTY_ADDRESS_FORM_VALUES,
1556
+ customer_name: address.customer_name ?? "",
1557
+ customer_email: usableEmail(address.customer_email),
1558
+ customer_phone: address.customer_phone ?? "",
1559
+ customer_country_code: phoneIso,
1560
+ country_obj: country2.id,
1561
+ country_name: country2.name,
1562
+ state_obj: address.state_obj ? String(address.state_obj) : "",
1563
+ state_name: address.state ?? "",
1564
+ city: address.city ?? "",
1565
+ pincode: address.pincode ?? "",
1566
+ address: address.address ?? "",
1567
+ is_default: !!address.is_default
1568
+ },
1569
+ phoneFollowsCountry: phoneIso === country2.tld_code
1570
+ };
1571
+ }
1572
+ if (draft) {
1573
+ const draftCountry = byId(draft.country_obj) ?? byIso(draft.country_obj);
1574
+ const country2 = draftCountry ?? fallback;
1575
+ const phoneIso = byIso(draft.customer_country_code)?.tld_code ?? country2.tld_code;
1576
+ const text = (value) => typeof value === "string" ? value : value == null ? "" : String(value);
1577
+ const values = {
1578
+ ...EMPTY_ADDRESS_FORM_VALUES,
1579
+ customer_name: text(draft.customer_name),
1580
+ customer_email: text(draft.customer_email),
1581
+ customer_phone: text(draft.customer_phone),
1582
+ customer_country_code: phoneIso,
1583
+ country_obj: country2.id,
1584
+ country_name: country2.name,
1585
+ state_obj: text(draft.state_obj),
1586
+ state_name: text(draft.state_name),
1587
+ city: text(draft.city),
1588
+ pincode: text(draft.pincode),
1589
+ address: text(draft.address),
1590
+ address_line_2: text(draft.address_line_2),
1591
+ is_default: !!draft.is_default
1592
+ };
1593
+ if (!draftCountry) {
1594
+ values.state_obj = "";
1595
+ values.state_name = "";
1596
+ values.pincode = "";
1597
+ }
1598
+ return { values, phoneFollowsCountry: phoneIso === country2.tld_code };
1599
+ }
1600
+ const location = getCache(locationCacheKey);
1601
+ const country = byIso(location?.country_code) ?? fallback;
1602
+ return {
1603
+ values: {
1604
+ ...EMPTY_ADDRESS_FORM_VALUES,
1605
+ customer_country_code: country.tld_code,
1606
+ country_obj: country.id,
1607
+ country_name: country.name
1608
+ },
1609
+ phoneFollowsCountry: true
1610
+ };
1611
+ }
1612
+ function useCountryAwareAddressForm({
1613
+ address,
1614
+ loadDraft,
1615
+ onSubmit,
1616
+ profile,
1617
+ pincodeValidationEnabled,
1618
+ defaultCountryId = INDIA_ID,
1619
+ locationCacheKey = IP_API_CACHE_KEY,
1620
+ messages,
1621
+ formatPincodeIssue,
1622
+ onInvalid
1623
+ }) {
1624
+ const { countries: allCountries, error: countriesError } = useCountries();
1625
+ const countries = useMemo(
1626
+ () => allCountries.filter((c) => isSupportedCountry(c.tld_code)).sort((a, b) => a.id === defaultCountryId ? -1 : b.id === defaultCountryId ? 1 : 0),
1627
+ [allCountries, defaultCountryId]
1628
+ );
1629
+ const onSubmitRef = useRef(onSubmit);
1630
+ onSubmitRef.current = onSubmit;
1631
+ const onInvalidRef = useRef(onInvalid);
1632
+ onInvalidRef.current = onInvalid;
1633
+ const formRef = useRef(null);
1634
+ const reportInvalid = useCallback((errors) => {
1635
+ if (onInvalidRef.current) onInvalidRef.current(errors);
1636
+ else focusFirstInvalidField(errors, formRef.current);
1637
+ }, []);
1638
+ const loadDraftRef = useRef(loadDraft);
1639
+ loadDraftRef.current = loadDraft;
1640
+ const schemaRef = useRef();
1641
+ const formik = useFormik({
1642
+ initialValues: EMPTY_ADDRESS_FORM_VALUES,
1643
+ validationSchema: () => schemaRef.current,
1644
+ onSubmit: (values2) => onSubmitRef.current(toAddressPayload(values2), values2)
1645
+ });
1646
+ const { values, setValues, setFieldValue, setTouched, validateForm, resetForm, submitForm } = formik;
1647
+ const valuesRef = useRef(values);
1648
+ valuesRef.current = values;
1649
+ const touchedRef = useRef(formik.touched);
1650
+ touchedRef.current = formik.touched;
1651
+ const country = useMemo(() => countries.find((c) => c.id === Number(values.country_obj)), [countries, values.country_obj]);
1652
+ const countryCode = country?.tld_code;
1653
+ const countryCodeRef = useRef(countryCode);
1654
+ countryCodeRef.current = countryCode;
1655
+ const { format, error: formatError } = useAddressFormat(countryCode);
1656
+ const { states, isLoading: statesLoading, error: statesError } = useSubdivisions(country?.id);
1657
+ const statesRef = useRef(states);
1658
+ statesRef.current = states;
1659
+ const showState = statesLoading || !!statesError || states.length > 0;
1660
+ const requireState = !statesError && showState;
1661
+ const messagesRef = useRef(messages);
1662
+ messagesRef.current = messages;
1663
+ const schema = useMemo(
1664
+ () => buildAddressSchema(format, { requireState, messages: messagesRef.current }),
1665
+ [format, requireState]
1666
+ );
1667
+ schemaRef.current = schema;
1668
+ const phoneFollowsCountryRef = useRef(true);
1669
+ const initialPincodeRef = useRef("");
1670
+ const initializedFor = useRef(null);
1671
+ const initKey = address?.id ?? "new";
1672
+ useEffect(() => {
1673
+ if (!countries.length || initializedFor.current === initKey) return;
1674
+ initializedFor.current = initKey;
1675
+ const draft = address ? null : loadDraftRef.current?.() ?? null;
1676
+ const { values: initial, phoneFollowsCountry } = resolveInitialValues(
1677
+ countries,
1678
+ address,
1679
+ draft,
1680
+ defaultCountryId,
1681
+ locationCacheKey
1682
+ );
1683
+ phoneFollowsCountryRef.current = phoneFollowsCountry;
1684
+ initialPincodeRef.current = initial.pincode;
1685
+ resetForm({ values: initial });
1686
+ }, [countries, initKey, resetForm]);
1687
+ const profileAppliedFor = useRef(null);
1688
+ useEffect(() => {
1689
+ const current = valuesRef.current;
1690
+ if (!profile || address || !current.country_obj || initializedFor.current !== initKey || profileAppliedFor.current === initKey) {
1691
+ return;
1692
+ }
1693
+ profileAppliedFor.current = initKey;
1694
+ const next = { ...current };
1695
+ if (!current.customer_name.trim() && profile.customer_name) next.customer_name = profile.customer_name.trim();
1696
+ if (!current.customer_email.trim()) next.customer_email = usableEmail(profile.email);
1697
+ if (!current.customer_phone.trim() && profile.phone) {
1698
+ const delivery = countries.find((c) => c.id === Number(current.country_obj));
1699
+ const code = profile.country_code?.trim();
1700
+ const phoneIso = code && /^[A-Za-z]{2}$/.test(code) ? code.toUpperCase() : delivery ? phoneIsoFromDialCode(code, delivery, countries) : current.customer_country_code;
1701
+ next.customer_country_code = phoneIso;
1702
+ next.customer_phone = sanitizePhoneInput(profile.phone, phoneIso);
1703
+ phoneFollowsCountryRef.current = phoneIso === delivery?.tld_code;
1704
+ }
1705
+ setValues(next, false);
1706
+ }, [profile, initKey, countries, values.country_obj, setValues]);
1707
+ useEffect(() => {
1708
+ if (!countryCode) return;
1709
+ const { pincode } = valuesRef.current;
1710
+ if (!format.hasPostal && pincode !== NO_POSTAL_CODE) setFieldValue("pincode", NO_POSTAL_CODE, false);
1711
+ else if (format.hasPostal && pincode === NO_POSTAL_CODE) setFieldValue("pincode", "", false);
1712
+ }, [format, countryCode, setFieldValue]);
1713
+ useEffect(() => {
1714
+ const { state_obj, state_name } = valuesRef.current;
1715
+ if (!state_obj || statesLoading || statesError || !states.length) return;
1716
+ const byId = states.find((s) => String(s.id) === state_obj);
1717
+ const state = byId ?? findStateByName(states, state_obj) ?? findStateByName(states, state_name);
1718
+ if (state) {
1719
+ if (String(state.id) !== state_obj || state.name !== state_name) {
1720
+ setValues({ ...valuesRef.current, state_obj: String(state.id), state_name: state.name }, false);
1721
+ }
1722
+ } else {
1723
+ setValues({ ...valuesRef.current, state_obj: "", state_name: "" }, false);
1724
+ }
1725
+ }, [states, statesLoading, statesError, values.state_obj, setValues]);
1726
+ const errorsRef = useRef(formik.errors);
1727
+ errorsRef.current = formik.errors;
1728
+ useEffect(() => {
1729
+ if (Object.keys(errorsRef.current).length) validateForm();
1730
+ }, [schema, validateForm]);
1731
+ const [autofill, setAutofill] = useState({});
1732
+ const autofillRef = useRef(autofill);
1733
+ autofillRef.current = autofill;
1734
+ const applyMatch = useCallback(
1735
+ (match, state) => {
1736
+ const current = valuesRef.current;
1737
+ const filledBefore = autofillRef.current;
1738
+ const next = {};
1739
+ const filled = {};
1740
+ const city = countryCodeRef.current === "IN" ? match.district || match.city : match.city || match.district;
1741
+ if (city && (!current.city.trim() || current.city === filledBefore.city)) {
1742
+ filled.city = city;
1743
+ if (current.city !== city) next.city = city;
1744
+ }
1745
+ if (state && (!current.state_obj || current.state_obj === filledBefore.state_obj)) {
1746
+ filled.state_obj = String(state.id);
1747
+ if (current.state_obj !== filled.state_obj) {
1748
+ next.state_obj = filled.state_obj;
1749
+ next.state_name = state.name;
1750
+ }
1751
+ }
1752
+ if (Object.keys(next).length) setValues({ ...current, ...next }, true);
1753
+ if (filled.city !== filledBefore.city || filled.state_obj !== filledBefore.state_obj) {
1754
+ setAutofill((prev) => ({ ...prev, ...filled }));
1755
+ }
1756
+ },
1757
+ [setValues]
1758
+ );
1759
+ const pincodeLookup = usePincodeLookup({
1760
+ countryCode,
1761
+ pincode: values.pincode,
1762
+ // Opening a saved address shouldn't re-check a postcode it already has.
1763
+ ready: !!countryCode && values.pincode !== initialPincodeRef.current && isPincodeReady(format, values.pincode),
1764
+ states,
1765
+ stateId: values.state_obj,
1766
+ onMatch: applyMatch,
1767
+ enabled: pincodeValidationEnabled
1768
+ });
1769
+ const { verify: verifyPincode, setServerError: setPincodeServerError, checkNow: checkPincodeNow } = pincodeLookup;
1770
+ const pincodeIssue = pincodeLookup.issue ? (formatPincodeIssue ?? describePincodeIssue)(pincodeLookup.issue, format) : void 0;
1771
+ const changeCountry = useCallback(
1772
+ (iso) => {
1773
+ const next = countries.find((c) => c.tld_code === iso);
1774
+ const current = valuesRef.current;
1775
+ if (!next || next.id === current.country_obj) return;
1776
+ const cityWasFilled = !!autofillRef.current.city && current.city === autofillRef.current.city;
1777
+ setValues(
1778
+ {
1779
+ ...current,
1780
+ country_obj: next.id,
1781
+ country_name: next.name,
1782
+ state_obj: "",
1783
+ state_name: "",
1784
+ pincode: "",
1785
+ city: cityWasFilled ? "" : current.city,
1786
+ customer_country_code: phoneFollowsCountryRef.current ? next.tld_code : current.customer_country_code
1787
+ },
1788
+ false
1789
+ );
1790
+ setAutofill({});
1791
+ setTouched({ ...touchedRef.current, state_obj: false, pincode: false, city: false }, false);
1792
+ initialPincodeRef.current = "";
1793
+ },
1794
+ [countries, setValues, setTouched]
1795
+ );
1796
+ const changePhoneCountry = useCallback(
1797
+ (iso) => {
1798
+ const current = valuesRef.current;
1799
+ const deliveryIso = countries.find((c) => c.id === current.country_obj)?.tld_code;
1800
+ phoneFollowsCountryRef.current = iso === deliveryIso;
1801
+ setFieldValue("customer_country_code", String(iso));
1802
+ },
1803
+ [countries, setFieldValue]
1804
+ );
1805
+ const changeState = useCallback(
1806
+ (e) => {
1807
+ const id = e.target.value;
1808
+ const name = statesRef.current.find((s) => String(s.id) === id)?.name ?? "";
1809
+ setValues({ ...valuesRef.current, state_obj: id, state_name: name }, true);
1810
+ },
1811
+ [setValues]
1812
+ );
1813
+ const formatRef = useRef(format);
1814
+ formatRef.current = format;
1815
+ const changePostcode = useCallback(
1816
+ (e) => {
1817
+ setFieldValue("pincode", normalizePostcode(formatRef.current, e.target.value));
1818
+ },
1819
+ [setFieldValue]
1820
+ );
1821
+ const handleBlur = formik.handleBlur;
1822
+ const blurPostcode = useCallback(
1823
+ (e) => {
1824
+ handleBlur(e);
1825
+ const { pincode } = valuesRef.current;
1826
+ const format2 = formatRef.current;
1827
+ if (pincode !== initialPincodeRef.current && !isPincodeReady(format2, pincode) && isPincodeCheckableOnBlur(format2, pincode)) {
1828
+ checkPincodeNow();
1829
+ }
1830
+ },
1831
+ [handleBlur, checkPincodeNow]
1832
+ );
1833
+ const addArea = useCallback(
1834
+ (area) => {
1835
+ const line1 = valuesRef.current.address.trim();
1836
+ if (line1.toLowerCase().includes(area.toLowerCase())) return;
1837
+ setFieldValue("address", line1 ? `${line1}, ${area}` : area);
1838
+ },
1839
+ [setFieldValue]
1840
+ );
1841
+ const showServerPincodeError = useCallback(
1842
+ (error) => {
1843
+ const postal = lowerLabel(formatRef.current.postalLabel);
1844
+ const invalidMessage = formatPincodeIssue?.({ kind: "invalid" }, formatRef.current) ?? `We couldn't find this ${postal}. Check it and try again.`;
1845
+ const message = getPincodeError(error, invalidMessage);
1846
+ if (!message) return false;
1847
+ setPincodeServerError(message);
1848
+ reportInvalid({ pincode: message });
1849
+ return true;
1850
+ },
1851
+ // formatPincodeIssue is read at call time; a new inline function shouldn't re-create this.
1852
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1853
+ [setPincodeServerError, reportInvalid]
1854
+ );
1855
+ const changePhone = useCallback(
1856
+ (e) => {
1857
+ const current = valuesRef.current;
1858
+ const foreign = detectForeignPhone(e.target.value, current.customer_country_code);
1859
+ if (foreign && countries.some((c) => c.tld_code === foreign.country)) {
1860
+ const deliveryIso = countries.find((c) => c.id === current.country_obj)?.tld_code;
1861
+ phoneFollowsCountryRef.current = foreign.country === deliveryIso;
1862
+ setValues(
1863
+ { ...current, customer_country_code: foreign.country, customer_phone: foreign.nationalNumber },
1864
+ true
1865
+ );
1866
+ return;
1867
+ }
1868
+ setFieldValue("customer_phone", sanitizePhoneInput(e.target.value, current.customer_country_code));
1869
+ },
1870
+ [countries, setValues, setFieldValue]
1871
+ );
1872
+ const inFlightRef = useRef(null);
1873
+ const [submitting, setSubmitting] = useState(false);
1874
+ const runSubmit = useCallback(async () => {
1875
+ setSubmitting(true);
1876
+ try {
1877
+ const errors = await validateForm();
1878
+ if (Object.keys(errors).length) {
1879
+ const allTouched = Object.fromEntries(Object.keys(valuesRef.current).map((key) => [key, true]));
1880
+ setTouched(allTouched, false);
1881
+ reportInvalid(errors);
1882
+ return false;
1883
+ }
1884
+ const issue = await verifyPincode();
1885
+ if (issue) {
1886
+ reportInvalid({ pincode: true });
1887
+ return false;
1888
+ }
1889
+ await submitForm();
1890
+ return true;
1891
+ } finally {
1892
+ inFlightRef.current = null;
1893
+ setSubmitting(false);
1894
+ }
1895
+ }, [validateForm, setTouched, submitForm, verifyPincode, reportInvalid]);
1896
+ const submit = useCallback(() => {
1897
+ if (!inFlightRef.current) inFlightRef.current = runSubmit();
1898
+ return inFlightRef.current;
1899
+ }, [runSubmit]);
1900
+ const countryOptions = useMemo(
1901
+ () => countries.map((c) => ({ value: c.tld_code, label: c.name })),
1902
+ [countries]
1903
+ );
1904
+ const phoneOptions = useMemo(
1905
+ () => countries.map((c) => {
1906
+ const dial = getCountryCallingCode(c.tld_code);
1907
+ return { value: c.tld_code, label: `${c.name} (+${dial})`, dial };
1908
+ }),
1909
+ [countries]
1910
+ );
1911
+ return {
1912
+ formik,
1913
+ formRef,
1914
+ submitting,
1915
+ country,
1916
+ format,
1917
+ formatError,
1918
+ countriesError,
1919
+ countriesLoading: !countries.length && !countriesError,
1920
+ states,
1921
+ statesError,
1922
+ showState,
1923
+ requireState,
1924
+ countryOptions,
1925
+ phoneOptions,
1926
+ cityAutofilled: !!autofill.city && values.city === autofill.city,
1927
+ stateAutofilled: !!autofill.state_obj && values.state_obj === autofill.state_obj,
1928
+ lookupLoading: pincodeLookup.loading,
1929
+ pincodeIssue,
1930
+ areaOptions: pincodeLookup.areaOptions,
1931
+ changeCountry,
1932
+ changePhoneCountry,
1933
+ changeState,
1934
+ changePostcode,
1935
+ blurPostcode,
1936
+ addArea,
1937
+ changePhone,
1938
+ showServerPincodeError,
1939
+ submit
1940
+ };
1941
+ }
1942
+
1943
+ export { BUY_NOW_PAYLOAD_KEY, EMPTY_ADDRESS_FORM_VALUES, describePincodeIssue, toAddressPayload, useAddress, useAddressFormat, useBuyNow, useCart, useCheckoutCoupon, useCheckoutPayment, useCountries, useCountryAwareAddressForm, useCoupon, useGetProductCategories, useGetProductDetails, useGetProducts, useInlineCheckoutPayment, useOrders, usePincodeLookup, useProductDetailModal, usePublicCheckout, useServiceFormModal, useShopCheckout, useSubdivisions, useUserDetails, useVariantSelector, useWishlist };
@@ -1,12 +1,13 @@
1
- export { A as Address } from '../address-DwBZHzbI.cjs';
1
+ export { A as Address, a as AddressPayload } from '../address-BdIB6IuI.cjs';
2
2
  export { A as Analytics, B as Blog, a as Booking, b as BookingDetails, I as Instagram, R as Review } from '../instagram-DalreBu6.cjs';
3
- export { B as BuyNow, C as Checkout, P as PublicCheckout } from '../buy-now-BqVWXyy8.cjs';
3
+ export { B as BuyNow, C as Checkout, P as PublicCheckout } from '../buy-now-B_15RUVT.cjs';
4
4
  export { A as ApplicableTarget, C as Cart, a as CartState, b as Category, c as Coupon, d as CouponResponse, e as CouponStatus, f as Coupons, D as DiscountType, U as User, V as ValueType } from '../cart-DwMFBmpC.cjs';
5
5
  export { A as CollectionAttributes, C as CollectionResponse, s as singleCollection } from '../collections-CXgOv5_G.cjs';
6
6
  export { O as Order } from '../orders-B3G4CyhH.cjs';
7
7
  export { D as Data, P as PaymentInstrument, a as PhonePe } from '../phonepe-dWMLZel6.cjs';
8
8
  export { A as Attributes, B as BaseProduct, a as BookingService, b as BookingServiceDate, c as Brand, C as CustomField, O as OperatingHours, P as Photos, d as Product, e as ProductAttribute, f as ProductDetail, S as SpecialHours, T as TimeSlot, W as WishlistState } from '../product-D9liEtl4.cjs';
9
9
  export { W as Wishlist } from '../wishlist-BakHvIFN.cjs';
10
+ export { P as Pincode } from '../pincode-8u7yWLpQ.cjs';
10
11
  import 'react-toastify';
11
12
 
12
13
  declare namespace CountryModel {
@@ -1,12 +1,13 @@
1
- export { A as Address } from '../address-DwBZHzbI.js';
1
+ export { A as Address, a as AddressPayload } from '../address-BdIB6IuI.js';
2
2
  export { A as Analytics, B as Blog, a as Booking, b as BookingDetails, I as Instagram, R as Review } from '../instagram-BADLnNQ3.js';
3
- export { B as BuyNow, C as Checkout, P as PublicCheckout } from '../buy-now-DFdnuLjO.js';
3
+ export { B as BuyNow, C as Checkout, P as PublicCheckout } from '../buy-now-kII0KrhP.js';
4
4
  export { A as ApplicableTarget, C as Cart, a as CartState, b as Category, c as Coupon, d as CouponResponse, e as CouponStatus, f as Coupons, D as DiscountType, U as User, V as ValueType } from '../cart-DZq1ZEnE.js';
5
5
  export { A as CollectionAttributes, C as CollectionResponse, s as singleCollection } from '../collections-CNh2OGbl.js';
6
6
  export { O as Order } from '../orders-Bl-Slh72.js';
7
7
  export { D as Data, P as PaymentInstrument, a as PhonePe } from '../phonepe-dWMLZel6.js';
8
8
  export { A as Attributes, B as BaseProduct, a as BookingService, b as BookingServiceDate, c as Brand, C as CustomField, O as OperatingHours, P as Photos, d as Product, e as ProductAttribute, f as ProductDetail, S as SpecialHours, T as TimeSlot, W as WishlistState } from '../product-D9liEtl4.js';
9
9
  export { W as Wishlist } from '../wishlist-Cj0sQxiY.js';
10
+ export { P as Pincode } from '../pincode-8u7yWLpQ.js';
10
11
  import 'react-toastify';
11
12
 
12
13
  declare namespace CountryModel {