@storepecker/storefront-core 2.9.1 → 2.10.1

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 (91) 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 +36 -32
  4. package/dist/api/index.d.cts +20 -17
  5. package/dist/api/index.d.ts +20 -17
  6. package/dist/api/index.js +4 -4
  7. package/dist/{buy-now-BqVWXyy8.d.cts → buy-now-CDug6LJ_.d.ts} +2 -2
  8. package/dist/{buy-now-DFdnuLjO.d.ts → buy-now-DrKY5_9R.d.cts} +2 -2
  9. package/dist/checkout/index.cjs +163 -76
  10. package/dist/checkout/index.d.cts +37 -26
  11. package/dist/checkout/index.d.ts +37 -26
  12. package/dist/checkout/index.js +50 -64
  13. package/dist/checkout-totals-CbmXM9L7.d.cts +220 -0
  14. package/dist/checkout-totals-DU8l-Wyb.d.ts +220 -0
  15. package/dist/{chunk-IG4BW3ZB.cjs → chunk-32X4SWN4.cjs} +3 -3
  16. package/dist/{chunk-NQZ5GUOG.cjs → chunk-3YPE6UPC.cjs} +24 -16
  17. package/dist/{chunk-RDUT4W3B.cjs → chunk-6APRQ2ED.cjs} +4 -1
  18. package/dist/{chunk-ICKTXS6B.js → chunk-6IXTFZFS.js} +3 -3
  19. package/dist/{chunk-7M5CVYZJ.js → chunk-A7EI7XLU.js} +8 -1
  20. package/dist/chunk-DZPK7GPG.js +601 -0
  21. package/dist/{chunk-TH7OAMGC.js → chunk-E4D4XOAE.js} +24 -16
  22. package/dist/{chunk-NRPK5GCJ.cjs → chunk-EFYAFXIS.cjs} +3 -3
  23. package/dist/{chunk-CBKJ3Y2I.js → chunk-EWZ7TGI7.js} +11 -1
  24. package/dist/{chunk-5XVHYPOC.js → chunk-FF5N7PTB.js} +1 -1
  25. package/dist/{chunk-NOT6VKXA.cjs → chunk-H6UZTS5O.cjs} +67 -23
  26. package/dist/{chunk-XFOUNOKO.cjs → chunk-KNG4OMS5.cjs} +8 -0
  27. package/dist/{chunk-ZAWZ3RB6.js → chunk-NNE42NMP.js} +1 -1
  28. package/dist/chunk-PN6KH5PX.cjs +661 -0
  29. package/dist/{chunk-QQHQTBAM.js → chunk-QSRVMOXT.js} +48 -6
  30. package/dist/{chunk-W6BDMNSU.js → chunk-QVO56X4E.js} +1 -1
  31. package/dist/{chunk-6LS5F4R3.cjs → chunk-SGJUMI3M.cjs} +11 -0
  32. package/dist/{chunk-YLLAP3H2.cjs → chunk-SGKLMS7W.cjs} +2 -2
  33. package/dist/{chunk-ZGMLOLTC.js → chunk-VRZRV2BR.js} +4 -1
  34. package/dist/{chunk-IVKJJLG7.cjs → chunk-WWJAPKRQ.cjs} +8 -8
  35. package/dist/{collections-CXgOv5_G.d.cts → collections-CKNFcE2d.d.cts} +1 -1
  36. package/dist/{collections-CNh2OGbl.d.ts → collections-CtRKsWVx.d.ts} +1 -1
  37. package/dist/components/address-form.cjs +6 -6
  38. package/dist/components/address-form.d.cts +10 -6
  39. package/dist/components/address-form.d.ts +10 -6
  40. package/dist/components/address-form.js +5 -5
  41. package/dist/components/digital-product-download-modal.d.cts +2 -2
  42. package/dist/components/digital-product-download-modal.d.ts +2 -2
  43. package/dist/components/index.cjs +8 -8
  44. package/dist/components/index.d.cts +6 -7
  45. package/dist/components/index.d.ts +6 -7
  46. package/dist/components/index.js +6 -6
  47. package/dist/components/search-dropdown.d.cts +4 -4
  48. package/dist/components/search-dropdown.d.ts +4 -4
  49. package/dist/components/share-button.cjs +3 -3
  50. package/dist/components/share-button.d.cts +1 -1
  51. package/dist/components/share-button.d.ts +1 -1
  52. package/dist/components/share-button.js +2 -2
  53. package/dist/components/theme-data-initializer.d.cts +4 -5
  54. package/dist/components/theme-data-initializer.d.ts +4 -5
  55. package/dist/hooks/index.cjs +672 -44
  56. package/dist/hooks/index.d.cts +239 -13
  57. package/dist/hooks/index.d.ts +239 -13
  58. package/dist/hooks/index.js +630 -11
  59. package/dist/{instagram-DalreBu6.d.cts → instagram-CSzrxk10.d.cts} +8 -2
  60. package/dist/{instagram-BADLnNQ3.d.ts → instagram-CagTLmyq.d.ts} +8 -2
  61. package/dist/models/index.d.cts +8 -8
  62. package/dist/models/index.d.ts +8 -8
  63. package/dist/orders-B6BmHCJN.d.ts +337 -0
  64. package/dist/orders-ZKP0lqRN.d.cts +337 -0
  65. package/dist/pincode-8u7yWLpQ.d.cts +29 -0
  66. package/dist/pincode-8u7yWLpQ.d.ts +29 -0
  67. package/dist/{pixelEvents-LsealscG.d.ts → pixelEvents-DqJ_CEEr.d.ts} +4 -4
  68. package/dist/{pixelEvents-BtEO5QAR.d.cts → pixelEvents-bahgVW4_.d.cts} +4 -4
  69. package/dist/{product-D9liEtl4.d.cts → product-D4kol-Z-.d.cts} +26 -2
  70. package/dist/{product-D9liEtl4.d.ts → product-D4kol-Z-.d.ts} +26 -2
  71. package/dist/store/index.cjs +20 -30
  72. package/dist/store/index.d.cts +21 -7
  73. package/dist/store/index.d.ts +21 -7
  74. package/dist/store/index.js +9 -26
  75. package/dist/{useAddressForm-DGbEn91-.d.cts → useAddressForm-fMOb5Z-a.d.ts} +6 -1
  76. package/dist/{useAddressForm-cO3Au33k.d.ts → useAddressForm-wleIo78M.d.cts} +6 -1
  77. package/dist/utils/index.cjs +60 -56
  78. package/dist/utils/index.d.cts +24 -9
  79. package/dist/utils/index.d.ts +24 -9
  80. package/dist/utils/index.js +4 -4
  81. package/dist/{wishlist-Cj0sQxiY.d.ts → wishlist-L3fM5-ie.d.ts} +1 -1
  82. package/dist/{wishlist-BakHvIFN.d.cts → wishlist-_0x0r1jt.d.cts} +1 -1
  83. package/package.json +1 -1
  84. package/dist/address-DwBZHzbI.d.cts +0 -19
  85. package/dist/address-DwBZHzbI.d.ts +0 -19
  86. package/dist/cart-DZq1ZEnE.d.ts +0 -153
  87. package/dist/cart-DwMFBmpC.d.cts +0 -153
  88. package/dist/chunk-34Y7Y5FU.cjs +0 -246
  89. package/dist/chunk-VPTN4YXD.js +0 -232
  90. package/dist/orders-B3G4CyhH.d.cts +0 -166
  91. package/dist/orders-Bl-Slh72.d.ts +0 -166
@@ -0,0 +1,601 @@
1
+ import { getCoupons, getAppliedCoupon, applyCoupon, removeCoupon, getPincodeDetails } from './chunk-A7EI7XLU.js';
2
+ import { pixelEvents } from './chunk-VAU5OL72.js';
3
+ import { razorpayPublicOrderSuccess, razorpayOrderSuccess, publicRazorpayOrderFailure, razorpayOrderFail, publicMakeCODOrder, makeCODOrder, stripePublicOrderSuccess, stripeOrderSuccess } from './chunk-KCLVR6G5.js';
4
+ import { getCache, setCache } from './chunk-OSM73ETC.js';
5
+ import { getCloudFront } from './chunk-JQMLHRWL.js';
6
+ import { AxiosError } from 'axios';
7
+ import { isSupportedCountry, parsePhoneNumberFromString, getCountryCallingCode } from 'libphonenumber-js';
8
+ import * as Yup from 'yup';
9
+
10
+ // src/checkout/payment.ts
11
+ function openRazorpayCheckout(order, callbacks, paymentOptions) {
12
+ if (!order) return;
13
+ pixelEvents.initiateCheckout(order, "razorpay");
14
+ const {
15
+ razorpay_order_id,
16
+ razorpay_public_token,
17
+ total_amount,
18
+ razorpay_order_currency,
19
+ store_color_scheme,
20
+ store_logo,
21
+ store_name,
22
+ customer_name,
23
+ customer_phone,
24
+ customer_email
25
+ } = order;
26
+ const cloudFront = getCloudFront();
27
+ const options = {
28
+ key: razorpay_public_token,
29
+ amount: Number(total_amount) * 100,
30
+ currency: razorpay_order_currency,
31
+ name: store_name,
32
+ image: cloudFront ? `${cloudFront}${store_logo}` : store_logo,
33
+ order_id: razorpay_order_id,
34
+ handler: async (response) => {
35
+ handleRazorpaySuccess(
36
+ {
37
+ razorpay_payment_id: response.razorpay_payment_id,
38
+ razorpay_subscription_id: response.razorpay_subscription_id,
39
+ razorpay_signature: response.razorpay_signature,
40
+ order_id: order.id,
41
+ razorpay_order_id,
42
+ payment_id: response.razorpay_payment_id
43
+ },
44
+ order,
45
+ callbacks,
46
+ paymentOptions
47
+ );
48
+ },
49
+ theme: {
50
+ color: store_color_scheme?.primary,
51
+ accent: store_color_scheme?.secondary
52
+ },
53
+ prefill: {
54
+ name: customer_name,
55
+ email: customer_email?.endsWith("@test.com") ? void 0 : customer_email,
56
+ phone: customer_phone
57
+ },
58
+ modal: {
59
+ ondismiss: () => handleRazorpayFail(
60
+ order,
61
+ callbacks,
62
+ {
63
+ description: "User cancelled the payment manually",
64
+ reason: "user_cancelled_payment_manually"
65
+ },
66
+ { isPublic: paymentOptions?.isPublic }
67
+ )
68
+ }
69
+ };
70
+ const paymentObject = new window.Razorpay(options);
71
+ paymentObject.on("payment.failed", (response) => {
72
+ handleRazorpayFail(order, callbacks, response?.error, {
73
+ isPublic: paymentOptions?.isPublic
74
+ });
75
+ });
76
+ paymentObject.open();
77
+ }
78
+ async function handleRazorpaySuccess(data, order, callbacks, options) {
79
+ try {
80
+ callbacks.onPaymentStart?.();
81
+ if (options?.isPublic) {
82
+ await razorpayPublicOrderSuccess({ ...data, order_number: order.order_number });
83
+ } else {
84
+ await razorpayOrderSuccess(data);
85
+ }
86
+ pixelEvents.purchase(order);
87
+ pixelEvents.checkoutCompleted(order);
88
+ callbacks.onCartReset();
89
+ callbacks.onSuccess(order);
90
+ } catch {
91
+ callbacks.onFailure(order);
92
+ } finally {
93
+ callbacks.onPaymentEnd?.();
94
+ }
95
+ }
96
+ async function handleRazorpayFail(order, callbacks, error, options) {
97
+ try {
98
+ const payload = {
99
+ order_id: order.id,
100
+ razorpay_order_id: order.razorpay_order_id,
101
+ error
102
+ };
103
+ options?.isPublic ? await publicRazorpayOrderFailure(payload) : await razorpayOrderFail(payload);
104
+ } catch {
105
+ }
106
+ callbacks.onFailure(order);
107
+ }
108
+ function handlePhonepePayment(order, callbacks) {
109
+ if (!order) return;
110
+ pixelEvents.initiateCheckout(order, "phonepe");
111
+ if (!order.phonepe_redirect_url) {
112
+ callbacks.onFailure(order);
113
+ return;
114
+ }
115
+ callbacks.onRedirect(order.phonepe_redirect_url);
116
+ }
117
+ function handleTabbyPayment(order, callbacks) {
118
+ if (!order) return;
119
+ pixelEvents.initiateCheckout(order, "tabby");
120
+ if (!order.tabby_redirect_url) {
121
+ callbacks.onFailure(order);
122
+ return;
123
+ }
124
+ callbacks.onRedirect(order.tabby_redirect_url);
125
+ }
126
+ async function handleCODPayment(order, callbacks, options) {
127
+ if (!order) return;
128
+ try {
129
+ callbacks.onPaymentStart?.();
130
+ pixelEvents.initiateCheckout(order, "cod");
131
+ if (options?.isPublic) {
132
+ await publicMakeCODOrder(order.order_number, {
133
+ customer_phone: order.customer_phone,
134
+ customer_email: order.customer_email
135
+ });
136
+ } else {
137
+ await makeCODOrder(order.id);
138
+ }
139
+ pixelEvents.purchase(order);
140
+ pixelEvents.checkoutCompleted(order);
141
+ callbacks.onCartReset();
142
+ callbacks.onSuccess(order);
143
+ } catch {
144
+ callbacks.onFailure(order);
145
+ } finally {
146
+ callbacks.onPaymentEnd?.();
147
+ }
148
+ }
149
+ function handleStripePayment(order, callbacks) {
150
+ if (!order) return;
151
+ pixelEvents.initiateCheckout(order, "stripe");
152
+ if (order.stripe_payment_link_url) {
153
+ callbacks.onRedirect(order.stripe_payment_link_url);
154
+ return;
155
+ }
156
+ if (order.stripe_client_secret) {
157
+ callbacks.onStripeModalOpen?.(order);
158
+ return;
159
+ }
160
+ callbacks.onFailure(order);
161
+ }
162
+ async function handleStripeSuccess(order, paymentIntentId, callbacks, options) {
163
+ try {
164
+ callbacks.onPaymentStart?.();
165
+ const stripeSuccessPayload = {
166
+ order_id: order.id,
167
+ payment_intent_id: paymentIntentId
168
+ };
169
+ if (options?.isPublic) {
170
+ await stripePublicOrderSuccess(stripeSuccessPayload);
171
+ } else {
172
+ await stripeOrderSuccess(stripeSuccessPayload);
173
+ }
174
+ pixelEvents.purchase(order);
175
+ pixelEvents.checkoutCompleted(order);
176
+ callbacks.onCartReset();
177
+ callbacks.onSuccess(order);
178
+ } catch {
179
+ callbacks.onFailure(order);
180
+ } finally {
181
+ callbacks.onPaymentEnd?.();
182
+ }
183
+ }
184
+ function processPayment(order, paymentMethod, callbacks, options) {
185
+ if (paymentMethod === "cod") {
186
+ handleCODPayment(order, callbacks, options);
187
+ return;
188
+ }
189
+ if (order.tabby_redirect_url) {
190
+ handleTabbyPayment(order, callbacks);
191
+ return;
192
+ }
193
+ if (order.stripe_client_secret || order.stripe_payment_link_url) {
194
+ handleStripePayment(order, callbacks);
195
+ return;
196
+ }
197
+ if (order.razorpay_public_token) {
198
+ openRazorpayCheckout(order, callbacks, options);
199
+ return;
200
+ }
201
+ handlePhonepePayment(order, callbacks);
202
+ }
203
+ async function fetchAvailableCoupons() {
204
+ const response = await getCoupons();
205
+ return response.data;
206
+ }
207
+ async function fetchAppliedCoupon() {
208
+ try {
209
+ const response = await getAppliedCoupon();
210
+ return response.data || null;
211
+ } catch {
212
+ return null;
213
+ }
214
+ }
215
+ async function applyCheckoutCoupon(code, callbacks) {
216
+ try {
217
+ const response = await applyCoupon(code);
218
+ if (response.data?.coupon) {
219
+ await callbacks.onCartRefresh();
220
+ return response.data.coupon;
221
+ }
222
+ throw new Error("Failed to apply coupon");
223
+ } catch (error) {
224
+ if (error instanceof AxiosError) {
225
+ throw new Error(error.response?.data?.detail || "Failed to apply coupon");
226
+ }
227
+ throw error;
228
+ }
229
+ }
230
+ async function removeCheckoutCoupon(couponCode, callbacks) {
231
+ await removeCoupon(couponCode);
232
+ await callbacks.onCartRefresh();
233
+ }
234
+ function isValidNumber(input, code) {
235
+ if (!isSupportedCountry(code)) return false;
236
+ const phone = parsePhoneNumberFromString(input, code);
237
+ if (!phone || !phone.isValid()) return false;
238
+ return phone.countryCallingCode === getCountryCallingCode(code);
239
+ }
240
+ function detectForeignPhone(raw, countryCode) {
241
+ const value = raw.replace(/[^\d+]/g, "");
242
+ if (!value.startsWith("+")) return null;
243
+ const parsed = parsePhoneNumberFromString(value);
244
+ if (!parsed?.isValid() || !parsed.country) return null;
245
+ const selected = countryCode && isSupportedCountry(countryCode) ? getCountryCallingCode(countryCode) : "";
246
+ if (parsed.countryCallingCode === selected) return null;
247
+ return { country: parsed.country, nationalNumber: parsed.nationalNumber };
248
+ }
249
+ function sanitizePhoneInput(raw, countryCode) {
250
+ const value = raw.replace(/[^\d+]/g, "");
251
+ const callingCode = countryCode && isSupportedCountry(countryCode) ? getCountryCallingCode(countryCode) : "";
252
+ if (value.startsWith("+")) {
253
+ const parsed = parsePhoneNumberFromString(value);
254
+ if (parsed?.nationalNumber) {
255
+ if (callingCode && parsed.countryCallingCode !== callingCode) return value;
256
+ return parsed.nationalNumber;
257
+ }
258
+ }
259
+ let digits = value.replace(/\D/g, "");
260
+ if (digits.startsWith("00")) digits = digits.slice(2);
261
+ if (callingCode && digits.startsWith(callingCode)) {
262
+ const parsed = parsePhoneNumberFromString("+" + digits);
263
+ if (parsed?.isValid()) return parsed.nationalNumber;
264
+ }
265
+ return digits.replace(/^0+/, "");
266
+ }
267
+ var ADDRESS_DATA_URL = "https://chromium-i18n.appspot.com/ssl-address/data";
268
+ var CACHE_PREFIX = "address_format_v1_";
269
+ var CACHE_HOURS = 24 * 7;
270
+ var FETCH_TIMEOUT_MS = 5e3;
271
+ var OVERRIDES = {
272
+ IN: {
273
+ postalRequired: true,
274
+ postalLabel: "PIN code",
275
+ postalPattern: /^[1-9]\d{5}$/,
276
+ postalStrict: true,
277
+ postalInputMode: "numeric",
278
+ postalMaxLength: 6,
279
+ line1Label: "House number, street, area",
280
+ line2Label: "Flat, building"
281
+ },
282
+ US: {
283
+ postalRequired: true,
284
+ postalPattern: /^\d{5}(?:[ -]\d{4})?$/,
285
+ postalStrict: true,
286
+ postalInputMode: "numeric",
287
+ postalMaxLength: 10,
288
+ line2Label: "Apt, suite"
289
+ },
290
+ CA: {
291
+ postalRequired: true,
292
+ postalPattern: /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/,
293
+ postalStrict: true,
294
+ postalMaxLength: 7,
295
+ postalUppercase: true,
296
+ regionLabel: "Province"
297
+ },
298
+ IE: {
299
+ postalRequired: true,
300
+ postalLabel: "Eircode",
301
+ postalPattern: /^(?:[AC-FHKNPRTV-Y]\d{2}|D6W) ?[0-9AC-FHKNPRTV-Y]{4}$/,
302
+ postalStrict: true,
303
+ postalMaxLength: 8,
304
+ postalUppercase: true,
305
+ regionLabel: "County",
306
+ cityLabel: "Town / city",
307
+ line2Label: "Apartment, building"
308
+ },
309
+ GB: {
310
+ postalRequired: true,
311
+ postalLabel: "Postcode",
312
+ regionLabel: "County",
313
+ postalMaxLength: 8,
314
+ postalUppercase: true,
315
+ cityLabel: "Town / city",
316
+ line2Label: "Flat, building"
317
+ },
318
+ AE: {
319
+ hasPostal: false,
320
+ cityLabel: "Area / district",
321
+ line2Label: "Villa / apartment"
322
+ }
323
+ };
324
+ var POSTAL_LABELS = {
325
+ pin: "PIN code",
326
+ zip: "ZIP code",
327
+ postal: "Postal code",
328
+ eircode: "Eircode",
329
+ cep: "CEP",
330
+ cap: "CAP"
331
+ };
332
+ var LOCALITY_LABELS = {
333
+ city: "City",
334
+ post_town: "Town / city",
335
+ district: "District",
336
+ suburb: "Suburb"
337
+ };
338
+ var sentenceCase = (value) => {
339
+ const words = value.replace(/_/g, " ").trim();
340
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : "";
341
+ };
342
+ var toRegExp = (source, flags = "i") => {
343
+ try {
344
+ return new RegExp(source, flags);
345
+ } catch {
346
+ return null;
347
+ }
348
+ };
349
+ function buildAddressFormat(countryCode, raw) {
350
+ const fmt = raw?.fmt ?? "";
351
+ const stateIndex = fmt.indexOf("%S");
352
+ const cityIndex = fmt.indexOf("%C");
353
+ const override = OVERRIDES[countryCode] ?? {};
354
+ const base = {
355
+ countryCode,
356
+ // GB and JP have a postcode but no `zip_name_type`, which is why keying on
357
+ // that field alone used to hide their postcode input.
358
+ hasPostal: raw ? Boolean(raw.zip || raw.zip_name_type || fmt.includes("%Z")) : true,
359
+ // Without metadata, don't demand a postcode: HK, QA and others have none.
360
+ postalRequired: !!raw,
361
+ postalLabel: raw?.zip_name_type && POSTAL_LABELS[raw.zip_name_type] || "Postal code",
362
+ postalPattern: raw?.zip ? toRegExp(`^(?:${raw.zip})$`) : null,
363
+ postalStrict: false,
364
+ postalInputMode: "text",
365
+ postalMaxLength: 12,
366
+ postalUppercase: false,
367
+ regionLabel: sentenceCase(raw?.state_name_type ?? "") || "State",
368
+ cityLabel: raw?.locality_name_type && LOCALITY_LABELS[raw.locality_name_type] || "City",
369
+ line1Label: "House number and street",
370
+ line2Label: "Apartment, suite, building",
371
+ stateFirst: stateIndex !== -1 && (cityIndex === -1 || stateIndex < cityIndex)
372
+ };
373
+ const format = { ...base, ...override };
374
+ return format.hasPostal ? format : { ...format, postalRequired: false };
375
+ }
376
+ var pickRawFields = (data) => {
377
+ const keys = [
378
+ "fmt",
379
+ "require",
380
+ "zip",
381
+ "zip_name_type",
382
+ "state_name_type",
383
+ "locality_name_type"
384
+ ];
385
+ const picked = {};
386
+ keys.forEach((key) => {
387
+ if (typeof data[key] === "string") picked[key] = data[key];
388
+ });
389
+ return picked;
390
+ };
391
+ async function loadAddressFormat(countryCode) {
392
+ const cacheKey = `${CACHE_PREFIX}${countryCode}`;
393
+ const cached = getCache(cacheKey);
394
+ if (cached) return buildAddressFormat(countryCode, cached);
395
+ const controller = new AbortController();
396
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
397
+ try {
398
+ const response = await fetch(`${ADDRESS_DATA_URL}/${countryCode}`, {
399
+ signal: controller.signal
400
+ });
401
+ if (!response.ok) throw new Error(`Address format request failed (${response.status})`);
402
+ const raw = pickRawFields(await response.json());
403
+ setCache(cacheKey, raw, { expiryHours: CACHE_HOURS });
404
+ return buildAddressFormat(countryCode, raw);
405
+ } finally {
406
+ clearTimeout(timeout);
407
+ }
408
+ }
409
+ function sanitizePincode(value) {
410
+ return value.replace(/[^a-zA-Z0-9 ]/g, "").replace(/\s+/g, " ").trimStart();
411
+ }
412
+ function normalizePostcode(format, value) {
413
+ const cleaned = format.countryCode === "JP" || format.countryCode === "US" ? value.replace(/[^0-9 -]/g, "").trimStart() : sanitizePincode(value);
414
+ const cased = format.postalUppercase ? cleaned.toUpperCase() : cleaned;
415
+ return cased.slice(0, format.postalMaxLength);
416
+ }
417
+ function getPostcodeHint(format, value, message = (postal) => `This doesn't look like a usual ${postal}. Check it before you continue.`) {
418
+ const code = value.trim();
419
+ if (!format.hasPostal || format.postalStrict || !format.postalPattern || !code) return void 0;
420
+ return format.postalPattern.test(code) ? void 0 : message(lowerLabel(format.postalLabel));
421
+ }
422
+ var normalizeName = (value) => value.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z]/g, "");
423
+ var STATE_ALIASES = {
424
+ orissa: "odisha",
425
+ pondicherry: "puducherry",
426
+ uttaranchal: "uttarakhand",
427
+ nctofdelhi: "delhi",
428
+ newdelhi: "delhi",
429
+ andamanandnicobar: "andamanandnicobarislands",
430
+ dadraandnagarhaveli: "dadraandnagarhavelianddamananddiu",
431
+ damananddiu: "dadraandnagarhavelianddamananddiu",
432
+ jammukashmir: "jammuandkashmir"
433
+ };
434
+ function findStateByName(states, name) {
435
+ const wanted = normalizeName(name);
436
+ if (!wanted) return void 0;
437
+ const resolved = STATE_ALIASES[wanted] ?? wanted;
438
+ return states.find((s) => {
439
+ const candidate = normalizeName(s.name);
440
+ return candidate === resolved || candidate === wanted;
441
+ });
442
+ }
443
+ function joinAddressLines(line1, line2) {
444
+ return [line1.trim(), line2.trim()].filter(Boolean).join(", ");
445
+ }
446
+ var emailRule = Yup.string().trim().email().required();
447
+ var usableEmail = (value) => typeof value === "string" && emailRule.isValidSync(value) ? value.trim() : "";
448
+ var lowerLabel = (label) => /^[A-Z][a-z]/.test(label) ? label.charAt(0).toLowerCase() + label.slice(1) : label;
449
+ var DEFAULT_ADDRESS_SCHEMA_MESSAGES = {
450
+ nameRequired: "Enter your full name",
451
+ emailInvalid: "Enter a valid email",
452
+ emailRequired: "Enter your email",
453
+ phoneRequired: "Enter your phone number",
454
+ phoneInvalid: "Enter a valid phone number",
455
+ countryRequired: "Select a country",
456
+ line1Required: (label) => `Enter your ${label}`,
457
+ cityRequired: (label) => `Enter your ${label}`,
458
+ stateRequired: (label) => `Select your ${label}`,
459
+ postalRequired: (label) => `Enter your ${label}`,
460
+ postalInvalid: (label) => `Enter a valid ${label}`
461
+ };
462
+ function buildAddressSchema(format, { requireState, messages }) {
463
+ const m = { ...DEFAULT_ADDRESS_SCHEMA_MESSAGES, ...messages };
464
+ return Yup.object({
465
+ customer_name: Yup.string().trim().required(m.nameRequired),
466
+ customer_email: Yup.string().trim().email(m.emailInvalid).required(m.emailRequired),
467
+ customer_phone: Yup.string().required(m.phoneRequired).test("is-valid", m.phoneInvalid, function(value) {
468
+ const { customer_country_code } = this.parent;
469
+ if (!value || !customer_country_code) return false;
470
+ return isValidNumber(value, customer_country_code);
471
+ }),
472
+ country_obj: Yup.string().required(m.countryRequired),
473
+ address: Yup.string().trim().required(m.line1Required(lowerLabel(format.line1Label))),
474
+ address_line_2: Yup.string(),
475
+ city: Yup.string().trim().required(m.cityRequired(lowerLabel(format.cityLabel))),
476
+ state_obj: requireState ? Yup.string().required(m.stateRequired(lowerLabel(format.regionLabel))) : Yup.string().notRequired(),
477
+ pincode: format.hasPostal ? (format.postalRequired ? Yup.string().trim().required(m.postalRequired(lowerLabel(format.postalLabel))) : Yup.string().trim()).test("postal-format", m.postalInvalid(lowerLabel(format.postalLabel)), (value) => {
478
+ if (!value || !format.postalStrict || !format.postalPattern) return true;
479
+ return format.postalPattern.test(value.trim());
480
+ }) : Yup.string().notRequired()
481
+ });
482
+ }
483
+
484
+ // src/checkout/pincode.ts
485
+ var INVALID_PINCODE = "INVALID_PINCODE";
486
+ var PINCODE_VALIDATION_UNAVAILABLE = "PINCODE_VALIDATION_UNAVAILABLE";
487
+ var NO_POSTAL_CODE = "N/A";
488
+ var PINCODE_DEBOUNCE_MS = 600;
489
+ var PINCODE_MIN_LENGTH = 4;
490
+ var UNAVAILABLE_MESSAGE = "We couldn't verify this postal code right now. Please try again.";
491
+ var UNKNOWN = { status: "unknown", match: null };
492
+ var cache = /* @__PURE__ */ new Map();
493
+ async function validatePincode(pincode, countryCode) {
494
+ const value = pincode?.trim();
495
+ if (!value || value === NO_POSTAL_CODE) return UNKNOWN;
496
+ const key = `${countryCode || ""}:${value.toUpperCase()}`;
497
+ const cached = cache.get(key);
498
+ if (cached) return cached;
499
+ let result;
500
+ try {
501
+ const { data } = await getPincodeDetails(value, countryCode);
502
+ if (data?.valid) {
503
+ result = {
504
+ status: "valid",
505
+ match: {
506
+ district: data.province || "",
507
+ city: data.city || "",
508
+ state: data.state || "",
509
+ state_code: data.state_code || "",
510
+ localities: data.localities || []
511
+ }
512
+ };
513
+ } else if (data?.error_code === INVALID_PINCODE) {
514
+ result = { status: "invalid", match: null };
515
+ } else {
516
+ return UNKNOWN;
517
+ }
518
+ } catch {
519
+ return UNKNOWN;
520
+ }
521
+ cache.set(key, result);
522
+ return result;
523
+ }
524
+ function getPincodeError(error, invalidMessage) {
525
+ const data = error?.response?.data;
526
+ if (data?.error_code === INVALID_PINCODE) return invalidMessage;
527
+ if (data?.error_code === PINCODE_VALIDATION_UNAVAILABLE) return data.error || data.message || UNAVAILABLE_MESSAGE;
528
+ return null;
529
+ }
530
+ function clearPincodeCache() {
531
+ cache.clear();
532
+ }
533
+ var bareSubdivisionCode = (code) => (code || "").toUpperCase().split("-").pop() || "";
534
+ function findSubdivision(states, match) {
535
+ const code = bareSubdivisionCode(match.state_code);
536
+ return (code ? states.find((s) => bareSubdivisionCode(s.short_code) === code) : void 0) ?? (match.state ? findStateByName(states, match.state) : void 0);
537
+ }
538
+ var NO_AREAS = [];
539
+ function getAreaOptions(match) {
540
+ const labels = (match?.localities ?? []).map((l) => (l.city || "").trim()).filter(Boolean);
541
+ const unique = Array.from(new Set(labels));
542
+ return unique.length > 1 ? unique : NO_AREAS;
543
+ }
544
+
545
+ // src/checkout/checkout-totals.ts
546
+ function getCustomizationPrice(input) {
547
+ return Number(
548
+ input?.effective_price ?? input?.additional_price ?? input?.customization_price ?? 0
549
+ ) || 0;
550
+ }
551
+ function calculateCartTotals(cart, customizationOverride) {
552
+ var _a;
553
+ const variants = cart?.product_variants || [];
554
+ const quantityOf = (variantId) => {
555
+ const line = variants.find((item) => item.id === variantId);
556
+ return Number(line?.quantity) || Number(cart?.products_quantity?.[variantId]) || 0;
557
+ };
558
+ let subtotal = 0;
559
+ let discountAmount = 0;
560
+ let totalInclusiveTax = 0;
561
+ let totalExclusiveTax = 0;
562
+ for (const item of variants) {
563
+ const quantity = quantityOf(item.id);
564
+ const actualPrice = Number(item.actual_price);
565
+ const sellingPrice = Number(item.selling_price);
566
+ if (actualPrice > 0) {
567
+ subtotal += actualPrice * quantity;
568
+ discountAmount += (actualPrice - sellingPrice) * quantity;
569
+ } else {
570
+ subtotal += sellingPrice * quantity;
571
+ }
572
+ const tax = Number(item.total_tax_price) || 0;
573
+ if (item.is_tax_inclusive_price) totalInclusiveTax += tax;
574
+ else totalExclusiveTax += tax;
575
+ }
576
+ const groupedCustomizeInputs = {};
577
+ for (const input of cart?.customization_inputs || []) {
578
+ (groupedCustomizeInputs[_a = input.product_variant] || (groupedCustomizeInputs[_a] = [])).push(input);
579
+ }
580
+ const customizationTotalsByVariant = {};
581
+ for (const input of customizationOverride || cart?.customization_inputs || []) {
582
+ customizationTotalsByVariant[input.product_variant] = (customizationTotalsByVariant[input.product_variant] || 0) + getCustomizationPrice(input);
583
+ }
584
+ const totalCustomizationPrice = Object.entries(
585
+ customizationTotalsByVariant
586
+ ).reduce(
587
+ (acc, [variantId, perUnit]) => acc + perUnit * quantityOf(Number(variantId)),
588
+ 0
589
+ );
590
+ return {
591
+ subtotal,
592
+ discountAmount,
593
+ totalInclusiveTax,
594
+ totalExclusiveTax,
595
+ totalCustomizationPrice,
596
+ customizationTotalsByVariant,
597
+ groupedCustomizeInputs
598
+ };
599
+ }
600
+
601
+ export { DEFAULT_ADDRESS_SCHEMA_MESSAGES, INVALID_PINCODE, NO_POSTAL_CODE, PINCODE_DEBOUNCE_MS, PINCODE_MIN_LENGTH, PINCODE_VALIDATION_UNAVAILABLE, applyCheckoutCoupon, buildAddressFormat, buildAddressSchema, calculateCartTotals, clearPincodeCache, detectForeignPhone, fetchAppliedCoupon, fetchAvailableCoupons, findStateByName, findSubdivision, getAreaOptions, getCustomizationPrice, getPincodeError, getPostcodeHint, handleCODPayment, handlePhonepePayment, handleRazorpayFail, handleRazorpaySuccess, handleStripePayment, handleStripeSuccess, handleTabbyPayment, isValidNumber, joinAddressLines, loadAddressFormat, lowerLabel, normalizePostcode, openRazorpayCheckout, processPayment, removeCheckoutCoupon, sanitizePhoneInput, sanitizePincode, usableEmail, validatePincode };
@@ -1,6 +1,11 @@
1
1
  import { USER_CART } from './chunk-BQ256JKN.js';
2
2
 
3
3
  // src/utils/cart.ts
4
+ function remainingStock(product, inCart) {
5
+ const stock = Number(product?.stock_quantity);
6
+ if (product?.stock_quantity == null || Number.isNaN(stock)) return null;
7
+ return Math.max(stock - inCart, 0);
8
+ }
4
9
  var LocalCart = {
5
10
  get() {
6
11
  const storeData = localStorage.getItem(USER_CART);
@@ -9,9 +14,21 @@ var LocalCart = {
9
14
  set(cart) {
10
15
  localStorage.setItem(USER_CART, JSON.stringify(cart));
11
16
  },
17
+ /**
18
+ * Adds `quantity` of `product`, capped so the line never goes past the
19
+ * product's stock: the guest cart isn't checked against the server until
20
+ * checkout, so repeated adds would otherwise pile up past what's available.
21
+ * Returns how many units were actually added (0 when at the limit or for a
22
+ * pre-order); compare it with the requested quantity to tell the shopper.
23
+ */
12
24
  add(product, quantity = 1) {
13
- const qty = Number(quantity) || 1;
25
+ if (product?.is_preorder) return 0;
26
+ const requested = Number(quantity) || 1;
14
27
  const cart = this.get();
28
+ const inCart = Number(cart?.products_quantity?.[product.id]) || 0;
29
+ const remaining = remainingStock(product, inCart);
30
+ const qty = remaining === null ? requested : Math.min(requested, remaining);
31
+ if (qty <= 0) return 0;
15
32
  if (!cart) {
16
33
  this.set({
17
34
  product_variants: [product],
@@ -21,31 +38,22 @@ var LocalCart = {
21
38
  total_amount: Number(product.selling_price) * qty,
22
39
  variant_discounts: {}
23
40
  });
24
- return;
41
+ return qty;
25
42
  }
26
43
  const newCart = cart.product_variants || [];
27
- const existingProduct = newCart.find((prod) => prod.id === product.id);
28
- if (existingProduct) {
29
- cart.products_quantity = {
30
- ...cart.products_quantity,
31
- [product.id]: (Number(cart.products_quantity[product.id]) || 0) + qty
32
- };
33
- cart.total_quantity = Number(cart.total_quantity) + qty;
34
- cart.cart_count = Number(cart.cart_count) + qty;
35
- cart.total_amount = Number(cart.total_amount) + Number(product.selling_price) * qty;
36
- this.set(cart);
37
- return;
44
+ if (!newCart.some((prod) => prod.id === product.id)) {
45
+ newCart.push(product);
46
+ cart.product_variants = newCart;
38
47
  }
39
- newCart.push(product);
40
48
  cart.products_quantity = {
41
49
  ...cart.products_quantity,
42
- [product.id]: (cart.products_quantity[product.id] || 0) + qty
50
+ [product.id]: inCart + qty
43
51
  };
44
- cart.product_variants = newCart;
45
52
  cart.total_quantity = Number(cart.total_quantity) + qty;
46
53
  cart.cart_count = Number(cart.cart_count) + qty;
47
54
  cart.total_amount = Number(cart.total_amount) + Number(product.selling_price) * qty;
48
55
  this.set(cart);
56
+ return qty;
49
57
  },
50
58
  remove(product) {
51
59
  const cart = this.get();
@@ -1,12 +1,12 @@
1
1
  'use strict';
2
2
 
3
- var chunkNQZ5GUOG_cjs = require('./chunk-NQZ5GUOG.cjs');
3
+ var chunk3YPE6UPC_cjs = require('./chunk-3YPE6UPC.cjs');
4
4
  var chunkECHV2JSY_cjs = require('./chunk-ECHV2JSY.cjs');
5
5
  var chunkBBRXE57K_cjs = require('./chunk-BBRXE57K.cjs');
6
6
 
7
7
  // src/api/cart.ts
8
8
  async function getCart(url, addressId, shippingOptionId) {
9
- const localCart = chunkNQZ5GUOG_cjs.cart_default.get();
9
+ const localCart = chunk3YPE6UPC_cjs.cart_default.get();
10
10
  return chunkBBRXE57K_cjs.auth_default.getUserDetails() ? (await chunkECHV2JSY_cjs.http_service_default.get(url, { params: { address_id: addressId, shipping_option_id: shippingOptionId } })).data : localCart || {
11
11
  product_variants: [],
12
12
  total_amount: 0,
@@ -28,7 +28,7 @@ async function getCart(url, addressId, shippingOptionId) {
28
28
  };
29
29
  }
30
30
  async function getCartItemQuantity() {
31
- const localCart = chunkNQZ5GUOG_cjs.cart_default.get();
31
+ const localCart = chunk3YPE6UPC_cjs.cart_default.get();
32
32
  return chunkBBRXE57K_cjs.auth_default.getUserDetails() ? (await chunkECHV2JSY_cjs.http_service_default.get("/customer/cart/quantity/")).data : { total_quantity: localCart?.total_quantity || 0 };
33
33
  }
34
34
  async function addToCart(product, customizationInputs) {