@asteby/storefront-react 0.18.0 → 0.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.
package/dist/account.cjs CHANGED
@@ -2,8 +2,331 @@
2
2
 
3
3
  var react = require('react');
4
4
  var jsxRuntime = require('react/jsx-runtime');
5
+ var storefront = require('@asteby/storefront');
5
6
 
6
- // src/account/account-auth.tsx
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // src/account/voucher.ts
18
+ function text(v) {
19
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
20
+ if (typeof v !== "string") return null;
21
+ const s = v.trim().slice(0, MAX);
22
+ return s || null;
23
+ }
24
+ function moneyOf(v) {
25
+ if (!v || typeof v !== "object") return null;
26
+ const m = v;
27
+ const amount = text(m.amount);
28
+ const cur = text(m.currency_code);
29
+ return amount && cur && Number.isFinite(Number(amount)) ? { amount, currency_code: cur.toUpperCase() } : null;
30
+ }
31
+ function voucherOf(p) {
32
+ const pay = p?.payment;
33
+ if (!pay || typeof pay !== "object") return null;
34
+ const v = {
35
+ method: text(pay.method ?? pay.provider),
36
+ reference: text(pay.reference),
37
+ barcode: text(pay.barcode),
38
+ clabe: text(pay.clabe),
39
+ expires_at: text(pay.expires_at) ?? text(p?.expires_at),
40
+ amount: moneyOf(pay.amount) ?? moneyOf(p?.total),
41
+ instructions: text(pay.instructions)
42
+ };
43
+ return v.reference || v.barcode || v.clabe ? v : null;
44
+ }
45
+ function barcodeValue(v) {
46
+ return v.barcode ?? (v.method?.toLowerCase() === "oxxo" ? v.reference : null);
47
+ }
48
+ function code128Modules(value) {
49
+ if (!value || value.length > 80) return null;
50
+ let codes;
51
+ if (/^\d+$/.test(value) && value.length % 2 === 0) {
52
+ codes = [105];
53
+ for (let i = 0; i < value.length; i += 2) codes.push(Number(value.slice(i, i + 2)));
54
+ } else {
55
+ codes = [104];
56
+ for (const ch of value) {
57
+ const c = ch.charCodeAt(0);
58
+ if (c < 32 || c > 126) return null;
59
+ codes.push(c - 32);
60
+ }
61
+ }
62
+ let sum = codes[0];
63
+ for (let i = 1; i < codes.length; i++) sum += codes[i] * i;
64
+ codes.push(sum % 103);
65
+ return codes.map((c) => BARS[c]).join("") + STOP;
66
+ }
67
+ function barcodeGeometry(value, opts = {}) {
68
+ const bits = code128Modules(value);
69
+ if (!bits) return null;
70
+ const mod = opts.module ?? 2;
71
+ const quiet = 10;
72
+ const rects = [];
73
+ for (let i = 0; i < bits.length; ) {
74
+ if (bits[i] === "0") {
75
+ i++;
76
+ continue;
77
+ }
78
+ let j = i;
79
+ while (j < bits.length && bits[j] === "1") j++;
80
+ rects.push({ x: (quiet + i) * mod, w: (j - i) * mod });
81
+ i = j;
82
+ }
83
+ return { width: (bits.length + quiet * 2) * mod, height: opts.height ?? 70, rects };
84
+ }
85
+ var MAX, BARS, STOP;
86
+ var init_voucher = __esm({
87
+ "src/account/voucher.ts"() {
88
+ MAX = 256;
89
+ BARS = [
90
+ "11011001100",
91
+ "11001101100",
92
+ "11001100110",
93
+ "10010011000",
94
+ "10010001100",
95
+ "10001001100",
96
+ "10011001000",
97
+ "10011000100",
98
+ "10001100100",
99
+ "11001001000",
100
+ "11001000100",
101
+ "11000100100",
102
+ "10110011100",
103
+ "10011011100",
104
+ "10011001110",
105
+ "10111001100",
106
+ "10011101100",
107
+ "10011100110",
108
+ "11001110010",
109
+ "11001011100",
110
+ "11001001110",
111
+ "11011100100",
112
+ "11001110100",
113
+ "11101101110",
114
+ "11101001100",
115
+ "11100101100",
116
+ "11100100110",
117
+ "11101100100",
118
+ "11100110100",
119
+ "11100110010",
120
+ "11011011000",
121
+ "11011000110",
122
+ "11000110110",
123
+ "10100011000",
124
+ "10001011000",
125
+ "10001000110",
126
+ "10110001000",
127
+ "10001101000",
128
+ "10001100010",
129
+ "11010001000",
130
+ "11000101000",
131
+ "11000100010",
132
+ "10110111000",
133
+ "10110001110",
134
+ "10001101110",
135
+ "10111011000",
136
+ "10111000110",
137
+ "10001110110",
138
+ "11101110110",
139
+ "11010001110",
140
+ "11000101110",
141
+ "11011101000",
142
+ "11011100010",
143
+ "11011101110",
144
+ "11101011000",
145
+ "11101000110",
146
+ "11100010110",
147
+ "11101101000",
148
+ "11101100010",
149
+ "11100011010",
150
+ "11101111010",
151
+ "11001000010",
152
+ "11110001010",
153
+ "10100110000",
154
+ "10100001100",
155
+ "10010110000",
156
+ "10010000110",
157
+ "10000101100",
158
+ "10000100110",
159
+ "10110010000",
160
+ "10110000100",
161
+ "10011010000",
162
+ "10011000010",
163
+ "10000110100",
164
+ "10000110010",
165
+ "11000010010",
166
+ "11001010000",
167
+ "11110111010",
168
+ "11000010100",
169
+ "10001111010",
170
+ "10100111100",
171
+ "10010111100",
172
+ "10010011110",
173
+ "10111100100",
174
+ "10011110100",
175
+ "10011110010",
176
+ "11110100100",
177
+ "11110010100",
178
+ "11110010010",
179
+ "11011011110",
180
+ "11011110110",
181
+ "11110110110",
182
+ "10101111000",
183
+ "10100011110",
184
+ "10001011110",
185
+ "10111101000",
186
+ "10111100010",
187
+ "11110101000",
188
+ "11110100010",
189
+ "10111011110",
190
+ "10111101110",
191
+ "11101011110",
192
+ "11110101110",
193
+ "11010000100",
194
+ "11010010000",
195
+ "11010011100"
196
+ ];
197
+ STOP = "1100011101011";
198
+ }
199
+ });
200
+
201
+ // src/account/voucher-document.ts
202
+ var voucher_document_exports = {};
203
+ __export(voucher_document_exports, {
204
+ esc: () => esc,
205
+ renderVoucherDocument: () => renderVoucherDocument
206
+ });
207
+ function esc(s) {
208
+ return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
209
+ }
210
+ function formatMoney2(m, locale) {
211
+ if (!m) return "";
212
+ try {
213
+ return new Intl.NumberFormat(locale, { style: "currency", currency: m.currency_code }).format(Number(m.amount));
214
+ } catch {
215
+ return `${m.amount} ${m.currency_code}`;
216
+ }
217
+ }
218
+ function formatDate2(iso, locale, timeZone) {
219
+ if (!iso) return "";
220
+ const d = new Date(iso);
221
+ if (Number.isNaN(d.getTime())) return "";
222
+ try {
223
+ return d.toLocaleString(locale, { dateStyle: "long", timeStyle: "short", ...timeZone ? { timeZone } : {} });
224
+ } catch {
225
+ return d.toISOString();
226
+ }
227
+ }
228
+ function barcodeSvg(value, label) {
229
+ const g = barcodeGeometry(value);
230
+ if (!g) return null;
231
+ const rects = g.rects.map((r) => `<rect x="${r.x}" y="0" width="${r.w}" height="${g.height}"/>`).join("");
232
+ return `<svg viewBox="0 0 ${g.width} ${g.height}" width="${g.width}" height="${g.height}" role="img" aria-label="${esc(label)} ${esc(value)}" shape-rendering="crispEdges" fill="#000">${rects}</svg>`;
233
+ }
234
+ function renderVoucherDocument(v, opts = {}) {
235
+ const locale = opts.locale ?? "es-MX";
236
+ const t = locale.toLowerCase().startsWith("en") ? EN5 : ES5;
237
+ const shop = opts.shopName || "";
238
+ const method = v.method ? Object.prototype.hasOwnProperty.call(t.methods, v.method.toLowerCase()) ? t.methods[v.method.toLowerCase()] : v.method : t.cash;
239
+ const isSpei = !!v.clabe && !v.reference;
240
+ const code = barcodeValue(v);
241
+ const svg = code ? barcodeSvg(code, t.barcode) : null;
242
+ const expires = formatDate2(v.expires_at, locale, opts.timeZone);
243
+ const field = (label, value) => value ? `<div class="box"><div class="label">${esc(label)}</div><div class="value">${esc(value)}</div></div>` : "";
244
+ const steps = isSpei ? t.stepsSpei : t.stepsCash;
245
+ const subtitle = [shop, method, opts.number ? `${t.order} ${opts.number}` : ""].filter(Boolean).map(esc).join(" \xB7 ");
246
+ return `<!doctype html>
247
+ <html lang="${esc(locale)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
248
+ <meta name="robots" content="noindex"><title>${esc(t.title)}${shop ? ` - ${esc(shop)}` : ""}</title><style>${CSS}</style></head>
249
+ <body><main>
250
+ <div class="head"><div><h1>${esc(t.title)}</h1><div class="muted">${subtitle}</div></div>
251
+ ${v.amount ? `<div><div class="label" style="text-align:right">${esc(t.total)}</div><div class="amount">${esc(formatMoney2(v.amount, locale))}</div></div>` : ""}</div>
252
+ ${field(t.reference, v.reference)}${field(t.clabe, v.clabe)}
253
+ ${svg ? `<div class="bar">${svg}<div class="muted" style="font-family:ui-monospace,monospace">${esc(code)}</div></div>` : ""}
254
+ ${expires ? `<p><strong>${esc(t.expires)}:</strong> ${esc(expires)}. ${esc(t.expiresNote)}</p>` : ""}
255
+ <ol class="steps">${steps.map((s) => `<li>${esc(s)}</li>`).join("")}</ol>
256
+ ${v.instructions ? `<p class="note pre muted">${esc(v.instructions)}</p>` : ""}
257
+ <p class="note muted">${esc(t.footer)}</p>
258
+ ${opts.printButton ? `<div class="actions"><button type="button" id="print">${esc(t.print)}</button></div>` : ""}
259
+ </main>
260
+ ${opts.printButton || opts.autoPrint ? `<script${opts.nonce ? ` nonce="${esc(opts.nonce)}"` : ""}>(function(){var b=document.getElementById("print");if(b)b.addEventListener("click",function(){window.print()});${opts.autoPrint ? 'window.addEventListener("load",function(){setTimeout(function(){window.print()},300)});' : ""}})();</script>` : ""}
261
+ </body></html>`;
262
+ }
263
+ var ES5, EN5, CSS;
264
+ var init_voucher_document = __esm({
265
+ "src/account/voucher-document.ts"() {
266
+ init_voucher();
267
+ ES5 = {
268
+ title: "Ficha de pago",
269
+ total: "Total a pagar",
270
+ reference: "Referencia",
271
+ clabe: "CLABE",
272
+ expires: "Vence",
273
+ expiresNote: "Pasada esa fecha la ficha deja de ser v\xE1lida.",
274
+ order: "Pedido",
275
+ barcode: "C\xF3digo de barras",
276
+ print: "Imprimir ficha",
277
+ footer: "Tu pedido se genera cuando se confirma el pago. Esta ficha es de un solo uso; no la compartas.",
278
+ stepsCash: [
279
+ "Acude a la tienda OXXO (o el comercio indicado) y di que vas a hacer un pago de servicio en efectivo.",
280
+ "Muestra el c\xF3digo de barras o dicta la referencia y paga el monto exacto.",
281
+ "Conserva tu comprobante: confirmaremos tu pago autom\xE1ticamente."
282
+ ],
283
+ stepsSpei: ["Entra a la banca en l\xEDnea o app de tu banco.", "Haz una transferencia SPEI a la CLABE indicada por el monto exacto.", "Conserva tu comprobante: confirmaremos tu pago autom\xE1ticamente."],
284
+ methods: { oxxo: "OXXO", spei: "Transferencia SPEI", bank_transfer: "Transferencia bancaria", bank_deposit: "Dep\xF3sito bancario", cash: "Pago en efectivo" },
285
+ cash: "Pago en efectivo"
286
+ };
287
+ EN5 = {
288
+ title: "Payment voucher",
289
+ total: "Amount to pay",
290
+ reference: "Reference",
291
+ clabe: "CLABE",
292
+ expires: "Expires",
293
+ expiresNote: "After that date the voucher is no longer valid.",
294
+ order: "Order",
295
+ barcode: "Barcode",
296
+ print: "Print voucher",
297
+ footer: "Your order is created when the payment is confirmed. This voucher is single-use; do not share it.",
298
+ stepsCash: [
299
+ "Go to an OXXO store (or the store indicated) and say you want to make a cash service payment.",
300
+ "Show the barcode or read out the reference and pay the exact amount.",
301
+ "Keep your receipt: we will confirm your payment automatically."
302
+ ],
303
+ stepsSpei: ["Open your bank online or app.", "Make a SPEI transfer to the CLABE below for the exact amount.", "Keep your receipt: we will confirm your payment automatically."],
304
+ methods: { oxxo: "OXXO", spei: "SPEI transfer", bank_transfer: "Bank transfer", bank_deposit: "Bank deposit", cash: "Cash payment" },
305
+ cash: "Cash payment"
306
+ };
307
+ CSS = `
308
+ @page { size: A4; margin: 18mm; }
309
+ * { box-sizing: border-box; }
310
+ body { margin: 0; font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #111; background: #fff; }
311
+ main { max-width: 174mm; margin: 0 auto; padding: 24px 16px; }
312
+ h1 { font-size: 22px; margin: 0; }
313
+ .muted { color: #555; }
314
+ .head { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; border-bottom: 3px solid #111; padding-bottom: 12px; }
315
+ .amount { font-size: 28px; font-weight: 700; text-align: right; }
316
+ .box { border: 1px solid #111; padding: 14px 16px; margin-top: 18px; }
317
+ .label { font-size: 12px; letter-spacing: .08em; text-transform: uppercase; color: #555; }
318
+ .value { font: 700 22px/1.3 ui-monospace, "SF Mono", Menlo, Consolas, monospace; word-break: break-all; letter-spacing: .04em; }
319
+ .bar { margin-top: 18px; text-align: center; }
320
+ .bar svg { max-width: 100%; height: auto; }
321
+ .steps { margin: 18px 0 0; padding-left: 20px; }
322
+ .note { margin-top: 18px; font-size: 12px; }
323
+ .pre { white-space: pre-line; }
324
+ .actions { margin-top: 24px; display: flex; gap: 12px; }
325
+ .actions button { font: inherit; padding: 10px 18px; border: 1px solid #111; background: #111; color: #fff; cursor: pointer; }
326
+ @media print { .actions { display: none; } main { padding: 0; } }
327
+ `;
328
+ }
329
+ });
7
330
  var ES = {
8
331
  valueMissing: "Completa este campo.",
9
332
  choiceMissing: "Elige una opci\xF3n.",
@@ -49,8 +372,8 @@ function labelOf(el) {
49
372
  const legend = el.closest("fieldset")?.querySelector("legend");
50
373
  if (legend?.textContent) return legend.textContent.trim();
51
374
  }
52
- const text = el.labels?.[0]?.getAttribute("data-sf-label") ?? el.labels?.[0]?.textContent ?? el.getAttribute("aria-label") ?? el.name;
53
- return text.trim();
375
+ const text2 = el.labels?.[0]?.getAttribute("data-sf-label") ?? el.labels?.[0]?.textContent ?? el.getAttribute("aria-label") ?? el.name;
376
+ return text2.trim();
54
377
  }
55
378
  function useFieldErrors(formRef, options = {}) {
56
379
  const m = fieldMessages(options.locale, options.messages);
@@ -357,7 +680,7 @@ function AccountAuth({ capabilities, data, next, pending = false, initialView, f
357
680
  ...newPassword ? { minLength: 10, maxLength: 128, hint: m.passwordHint } : {}
358
681
  }
359
682
  );
360
- const link = (to, text) => /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.link, "data-sf-account-link": to, onClick: () => go(to), children: text });
683
+ const link = (to, text2) => /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.link, "data-sf-account-link": to, onClick: () => go(to), children: text2 });
361
684
  let body;
362
685
  let links = null;
363
686
  switch (view) {
@@ -427,8 +750,1188 @@ function AccountAuth({ capabilities, data, next, pending = false, initialView, f
427
750
  ] })
428
751
  ] });
429
752
  }
753
+ var ES3 = {
754
+ title: "Crea tu cuenta para seguir tu pedido",
755
+ benefit: "Con {email} ver\xE1s aqu\xED tu pedido y su env\xEDo, y la pr\xF3xima compra ser\xE1 m\xE1s r\xE1pida. No te pedimos tu direcci\xF3n ni tu tel\xE9fono otra vez.",
756
+ benefitBasic: "Guarda tus datos para que la pr\xF3xima compra sea m\xE1s r\xE1pida.",
757
+ accountFor: "Cuenta para {email}",
758
+ password: "Contrase\xF1a",
759
+ passwordHint: "Entre 10 y 128 caracteres.",
760
+ code: "C\xF3digo",
761
+ codeSentTo: "Enviamos un c\xF3digo a {email}. Puede tardar un minuto.",
762
+ submit: "Crear cuenta",
763
+ submitOtp: "Enviarme un c\xF3digo",
764
+ submitCode: "Confirmar",
765
+ skipNote: "Si no quieres cuenta, no pasa nada: te avisaremos por correo de tu pedido.",
766
+ loginLink: "Ya tengo cuenta",
767
+ errors: {
768
+ invalid_credentials: "El correo o la contrase\xF1a no coinciden.",
769
+ invalid_code: "El c\xF3digo no es v\xE1lido o ya venci\xF3.",
770
+ email_taken: "Ya existe una cuenta con este correo. Entra para ver tu pedido.",
771
+ rate_limited: "Demasiados intentos. Espera unos minutos e int\xE9ntalo de nuevo.",
772
+ validation: "Revisa los datos e int\xE9ntalo de nuevo.",
773
+ unsupported: "Esta tienda no permite crear cuentas por ahora.",
774
+ store_misconfigured: "No pudimos crear tu cuenta por un problema de configuraci\xF3n de la tienda. Tu pedido sigue en pie.",
775
+ unavailable: "No pudimos completar la acci\xF3n. Int\xE9ntalo de nuevo en un momento."
776
+ }
777
+ };
778
+ var EN3 = {
779
+ title: "Create your account to follow your order",
780
+ benefit: "With {email} you will see your order and its shipment here, and your next purchase will be faster. We will not ask for your address or phone again.",
781
+ benefitBasic: "Save your details so your next purchase is faster.",
782
+ accountFor: "Account for {email}",
783
+ password: "Password",
784
+ passwordHint: "Between 10 and 128 characters.",
785
+ code: "Code",
786
+ codeSentTo: "We sent a code to {email}. It can take a minute.",
787
+ submit: "Create account",
788
+ submitOtp: "Email me a code",
789
+ submitCode: "Confirm",
790
+ skipNote: "If you do not want an account, that is fine: we will email you about your order.",
791
+ loginLink: "I already have an account",
792
+ errors: {
793
+ invalid_credentials: "The email and password do not match.",
794
+ invalid_code: "The code is not valid or has expired.",
795
+ email_taken: "An account with this email already exists. Sign in to see your order.",
796
+ rate_limited: "Too many attempts. Wait a few minutes and try again.",
797
+ validation: "Check the details and try again.",
798
+ unsupported: "This store does not allow creating accounts right now.",
799
+ store_misconfigured: "We could not create your account because of a store configuration problem. Your order is safe.",
800
+ unavailable: "We could not complete that. Try again in a moment."
801
+ }
802
+ };
803
+ function postPurchaseAccountPromptMessages(locale, overrides) {
804
+ const base = (locale ?? "es-MX").toLowerCase().startsWith("en") ? EN3 : ES3;
805
+ if (!overrides) return base;
806
+ return { ...base, ...overrides, errors: { ...base.errors, ...overrides.errors } };
807
+ }
808
+ var validEmail = (v) => typeof v === "string" && v.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());
809
+ function PostPurchaseAccountPrompt({
810
+ email,
811
+ capabilities,
812
+ data,
813
+ next,
814
+ pending = false,
815
+ form: FormTag = "form",
816
+ action,
817
+ headingLevel = 2,
818
+ loginHref,
819
+ locale,
820
+ messages,
821
+ classNames: cx = {},
822
+ children
823
+ }) {
824
+ const m = postPurchaseAccountPromptMessages(locale, messages);
825
+ const ref = react.useRef(null);
826
+ const passwordOn = capabilities.password;
827
+ const otpOn = capabilities.otp_channels.includes("email");
828
+ const errorText = data?.error ? m.errors[data.error.code] : null;
829
+ const v = useFieldErrors(ref, { ...locale ? { locale } : {}, serverFields: data?.error?.field === "code" || data?.error?.field === "password" ? [data.error.field] : null, serverMessages: data?.error?.field && errorText ? { [data.error.field]: errorText } : null });
830
+ if (!validEmail(email) || !passwordOn && !otpOn) return null;
831
+ const address = email.trim().toLowerCase();
832
+ const step = data?.step === "verify" || data?.step === "otp" ? data.step : null;
833
+ const view = step ?? (passwordOn ? "register" : "otp-request");
834
+ const intent = step === "verify" ? "verify" : step === "otp" ? "otp-login" : passwordOn ? "register" : "otp-request";
835
+ const label = view === "verify" || view === "otp" ? m.submitCode : view === "otp-request" ? m.submitOtp : m.submit;
836
+ const Heading = `h${headingLevel}`;
837
+ const fieldProps = { classNames: cx.field, ...locale ? { locale } : {} };
838
+ const showAlert = errorText && !(data?.error?.field === "code" || data?.error?.field === "password");
839
+ const benefit = (capabilities.email_verification ? m.benefit : m.benefitBasic).replace("{email}", address);
840
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: cx.root, "data-sf-ppa": true, "data-sf-ppa-view": view, "aria-labelledby": "sf-ppa-title", children: [
841
+ /* @__PURE__ */ jsxRuntime.jsx(Heading, { id: "sf-ppa-title", className: cx.title, children: m.title }),
842
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.text, "data-sf-ppa-benefit": true, children: benefit }),
843
+ /* @__PURE__ */ jsxRuntime.jsxs(FormTag, { ref, method: "post", ...action ? { action } : {}, className: cx.form, "data-sf-ppa-form": true, children: [
844
+ /* @__PURE__ */ jsxRuntime.jsx(ErrorSummary, { items: v.summary, focusKey: v.summaryKey, ...locale ? { locale } : {} }),
845
+ showAlert ? /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", className: cx.error, "data-sf-ppa-error": data.error.code, children: errorText }) : null,
846
+ /* @__PURE__ */ jsxRuntime.jsx("input", { type: "hidden", name: "email", value: address }),
847
+ next ? /* @__PURE__ */ jsxRuntime.jsx("input", { type: "hidden", name: "next", value: next }) : null,
848
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.email, "data-sf-ppa-email": true, children: m.accountFor.replace("{email}", address) }),
849
+ step ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
850
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.notice, role: "status", "data-sf-ppa-notice": true, children: m.codeSentTo.replace("{email}", address) }),
851
+ /* @__PURE__ */ jsxRuntime.jsx(CheckoutField, { ...fieldProps, name: "code", label: m.code, autoComplete: "one-time-code", inputMode: "numeric", pattern: "[0-9]*", error: v.errors.code ?? null })
852
+ ] }) : passwordOn ? /* @__PURE__ */ jsxRuntime.jsx(CheckoutField, { ...fieldProps, name: "password", type: "password", label: m.password, autoComplete: "new-password", minLength: 10, maxLength: 128, hint: m.passwordHint, error: v.errors.password ?? null }) : null,
853
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.actions, children: /* @__PURE__ */ jsxRuntime.jsx("button", { type: "submit", name: "intent", value: intent, disabled: pending, className: cx.submit, "data-sf-ppa-submit": true, children: label }) })
854
+ ] }),
855
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.note, "data-sf-ppa-note": true, children: [
856
+ m.skipNote,
857
+ loginHref ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
858
+ " ",
859
+ /* @__PURE__ */ jsxRuntime.jsx("a", { href: loginHref, className: cx.link, "data-sf-ppa-login": true, children: m.loginLink })
860
+ ] }) : null
861
+ ] }),
862
+ children
863
+ ] });
864
+ }
865
+
866
+ // src/fiscal/messages.ts
867
+ function fill(template, vars) {
868
+ return template.replace(/\{(\w+)\}/g, (m, k) => k in vars ? String(vars[k]) : m);
869
+ }
870
+
871
+ // src/account/orders-messages.ts
872
+ var ES4 = {
873
+ // order list
874
+ "order.number": "Pedido {number}",
875
+ "order.placed": "Realizado el {date}",
876
+ "order.total": "Total",
877
+ "order.view": "Ver pedido",
878
+ "order.items.one": "{count} art\xEDculo",
879
+ "order.items.other": "{count} art\xEDculos",
880
+ "order.stepOf": "Paso {n} de {total}: {step}",
881
+ "order.listLabel": "Tus pedidos",
882
+ "order.loading": "Cargando tus pedidos",
883
+ "order.loadMore": "Ver m\xE1s pedidos",
884
+ "order.loadingMore": "Cargando\u2026",
885
+ "order.error": "No pudimos cargar tus pedidos. Tus compras est\xE1n a salvo.",
886
+ "order.retry": "Reintentar",
887
+ "order.emptyTitle": "A\xFAn no tienes pedidos",
888
+ "order.emptyBody": "Cuando compres, aqu\xED ver\xE1s el estado y el env\xEDo de cada pedido.",
889
+ "order.emptyGuest": "\xBFCompraste como invitado? Verifica tu correo para ver aqu\xED tus pedidos.",
890
+ // stage (order status)
891
+ "stage.pending_payment": "Esperando pago",
892
+ "stage.paid": "Pagado",
893
+ "stage.preparing": "En preparaci\xF3n",
894
+ "stage.ready_for_pickup": "Listo para recoger",
895
+ "stage.shipped": "Enviado",
896
+ "stage.in_transit": "En camino",
897
+ "stage.out_for_delivery": "En reparto",
898
+ "stage.delivered": "Entregado",
899
+ "stage.cancelled": "Cancelado",
900
+ "stage.refunded": "Reembolsado",
901
+ "stage.unknown": "En proceso",
902
+ // progress
903
+ "progress.label": "Progreso del pedido",
904
+ "step.paid": "Pagado",
905
+ "step.preparing": "En preparaci\xF3n",
906
+ "step.shipped": "Enviado",
907
+ "step.in_transit": "En camino",
908
+ "step.ready_for_pickup": "Listo para recoger",
909
+ "step.delivered": "Entregado",
910
+ "step.unknown": "Siguiente paso",
911
+ "stepState.done": "completado",
912
+ "stepState.current": "paso actual",
913
+ "stepState.pending": "pendiente",
914
+ "stepState.problem": "con incidencia",
915
+ "problem.delivery_exception": "Hubo un problema con la entrega. Contacta a la tienda si no se resuelve.",
916
+ "problem.returned": "El paquete regres\xF3 a la tienda. Cont\xE1ctanos para coordinar un nuevo env\xEDo.",
917
+ "problem.lost": "No encontramos tu paquete. Cont\xE1ctanos y lo resolvemos.",
918
+ "problem.payment_failed": "El pago no se complet\xF3. Puedes intentarlo de nuevo.",
919
+ "problem.unknown": "Tu pedido tiene una incidencia. Contacta a la tienda.",
920
+ "progress.cancelled": "Este pedido fue cancelado.",
921
+ "progress.refunded": "Este pedido fue reembolsado.",
922
+ // next action
923
+ "action.pay": "Pagar ahora",
924
+ "action.track": "Rastrear env\xEDo",
925
+ "action.pickup": "Recoger en sucursal",
926
+ "action.download_invoice": "Descargar factura",
927
+ "action.request_invoice": "Solicitar factura",
928
+ "action.correct_invoice_data": "Corregir datos de facturaci\xF3n",
929
+ "action.contact_store": "Contactar a la tienda",
930
+ "action.unknown": "Ver detalle",
931
+ "action.newTab": "(se abre en una pesta\xF1a nueva)",
932
+ "action.label": "Siguiente paso del pedido",
933
+ // shipment
934
+ "shipment.title": "Env\xEDo",
935
+ "shipment.return": "Devoluci\xF3n",
936
+ "shipment.carrier": "Paqueter\xEDa",
937
+ "shipment.service": "Servicio",
938
+ "shipment.number": "N\xFAmero de gu\xEDa",
939
+ "shipment.copy": "Copiar",
940
+ "shipment.copied": "Copiado",
941
+ "shipment.copyFailed": "No pudimos copiar; selecciona el texto.",
942
+ "shipment.track": "Rastrear con {carrier}",
943
+ "shipment.trackGeneric": "Rastrear env\xEDo",
944
+ "shipment.promised": "Llega a m\xE1s tardar el {date}",
945
+ "shipment.delivered": "Entregado el {date}",
946
+ "shipment.shipped": "Enviado el {date}",
947
+ "shipment.events": "Movimientos",
948
+ "shipment.noEvents": "La paqueter\xEDa a\xFAn no registra movimientos; suele tardar 24 horas.",
949
+ "shipment.showAll": "Ver todo ({count})",
950
+ "shipment.showLess": "Ver menos",
951
+ "shipment.returnLabel": "Gu\xEDa de devoluci\xF3n",
952
+ "shipment.test": "De prueba",
953
+ "shipment.testNote": "Env\xEDo de prueba: no es un env\xEDo real.",
954
+ "shipment.preparing": "Preparando tu env\xEDo",
955
+ "shipment.status.pending": "Preparando env\xEDo",
956
+ "shipment.status.label_created": "Gu\xEDa generada",
957
+ "shipment.status.in_transit": "En camino",
958
+ "shipment.status.out_for_delivery": "En reparto",
959
+ "shipment.status.delivered": "Entregado",
960
+ "shipment.status.exception": "Incidencia en la entrega",
961
+ "shipment.status.returned": "Devuelto a la tienda",
962
+ "shipment.status.lost": "Extraviado",
963
+ "shipment.status.cancelled": "Cancelado",
964
+ "shipment.status.unknown": "En proceso",
965
+ "shipment.eventFrom": "{location}",
966
+ // invoices
967
+ "invoice.title": "Facturas",
968
+ "invoice.invoice": "Factura",
969
+ "invoice.creditNote": "Nota de cr\xE9dito",
970
+ "invoice.creditNoteOf": "Corrige la factura {folio}",
971
+ "invoice.folio": "Folio fiscal",
972
+ "invoice.series": "Serie y folio",
973
+ "invoice.issued": "Emitida el {date}",
974
+ "invoice.total": "Total",
975
+ "invoice.pdf": "Descargar PDF",
976
+ "invoice.xml": "Descargar XML",
977
+ "invoice.downloadOf": "{action}, {kind} {name}",
978
+ "invoice.none": "A\xFAn no hay facturas de este pedido.",
979
+ "invoice.test": "Factura de prueba, sin validez",
980
+ "invoice.status.issued": "Emitida",
981
+ "invoice.status.pending": "En proceso",
982
+ "invoice.status.cancelled": "Cancelada",
983
+ "invoice.status.error": "No se pudo emitir",
984
+ "invoice.status.unknown": "En proceso",
985
+ "invoice.statusNote.pending": "La estamos generando; te avisaremos cuando est\xE9 lista.",
986
+ "invoice.statusNote.error": "Contacta a la tienda para resolverlo.",
987
+ "invoice.statusNote.cancelled": "Esta factura fue cancelada y ya no tiene validez.",
988
+ // pending payment
989
+ "pending.title": "Pendientes de pago",
990
+ "pending.intro": "Tu pedido se genera en cuanto confirmamos el pago. Paga con la ficha antes de que venza.",
991
+ "pending.waiting": "Esperando pago",
992
+ "pending.expired": "Vencida",
993
+ "pending.reference": "Referencia",
994
+ "pending.clabe": "CLABE",
995
+ "pending.expires": "Vence el {date}",
996
+ "pending.expiredOn": "Venci\xF3 el {date}",
997
+ "pending.total": "Total",
998
+ "pending.copyReference": "Copiar referencia",
999
+ "pending.copyClabe": "Copiar CLABE",
1000
+ "pending.copied": "Copiada",
1001
+ "pending.copyFailed": "No pudimos copiar; selecciona el texto.",
1002
+ "pending.print": "Ver e imprimir ficha",
1003
+ "pending.download": "Descargar ficha",
1004
+ "pending.expiredNote": "Esta ficha ya no es v\xE1lida. Haz tu pedido de nuevo.",
1005
+ "pending.barcode": "C\xF3digo de barras {code}",
1006
+ "pending.method.oxxo": "OXXO",
1007
+ "pending.method.spei": "Transferencia SPEI",
1008
+ "pending.method.bank_transfer": "Transferencia bancaria",
1009
+ "pending.method.bank_deposit": "Dep\xF3sito bancario",
1010
+ "pending.method.cash": "Pago en efectivo",
1011
+ "pending.method.unknown": "Pago en efectivo",
1012
+ // refunds & payments
1013
+ "refund.title": "Reembolsos",
1014
+ "refund.status.requested": "Solicitado",
1015
+ "refund.status.processing": "En proceso",
1016
+ "refund.status.completed": "Completado",
1017
+ "refund.status.failed": "No se pudo completar",
1018
+ "refund.status.unknown": "En proceso",
1019
+ "refund.requested": "Solicitado el {date}",
1020
+ "refund.completed": "Completado el {date}",
1021
+ "refund.none": "Este pedido no tiene reembolsos.",
1022
+ "payment.title": "Pagos",
1023
+ "payment.status.paid": "Pagado",
1024
+ "payment.status.pending": "Pendiente",
1025
+ "payment.status.failed": "Fallido",
1026
+ "payment.status.refunded": "Reembolsado",
1027
+ "payment.status.partially_refunded": "Reembolsado parcialmente",
1028
+ "payment.status.unknown": "En proceso",
1029
+ "payment.paidOn": "Pagado el {date}",
1030
+ // sections
1031
+ "section.error": "No pudimos cargar esta secci\xF3n.",
1032
+ "section.retry": "Reintentar",
1033
+ "section.loading": "Cargando"
1034
+ };
1035
+ var EN4 = {
1036
+ "order.number": "Order {number}",
1037
+ "order.placed": "Placed on {date}",
1038
+ "order.total": "Total",
1039
+ "order.view": "View order",
1040
+ "order.items.one": "{count} item",
1041
+ "order.items.other": "{count} items",
1042
+ "order.stepOf": "Step {n} of {total}: {step}",
1043
+ "order.listLabel": "Your orders",
1044
+ "order.loading": "Loading your orders",
1045
+ "order.loadMore": "Show more orders",
1046
+ "order.loadingMore": "Loading\u2026",
1047
+ "order.error": "We could not load your orders. Your purchases are safe.",
1048
+ "order.retry": "Try again",
1049
+ "order.emptyTitle": "You have no orders yet",
1050
+ "order.emptyBody": "When you buy, you will see the status and shipment of each order here.",
1051
+ "order.emptyGuest": "Did you buy as a guest? Verify your email to see your orders here.",
1052
+ "stage.pending_payment": "Waiting for payment",
1053
+ "stage.paid": "Paid",
1054
+ "stage.preparing": "Being prepared",
1055
+ "stage.ready_for_pickup": "Ready for pickup",
1056
+ "stage.shipped": "Shipped",
1057
+ "stage.in_transit": "On its way",
1058
+ "stage.out_for_delivery": "Out for delivery",
1059
+ "stage.delivered": "Delivered",
1060
+ "stage.cancelled": "Cancelled",
1061
+ "stage.refunded": "Refunded",
1062
+ "stage.unknown": "In progress",
1063
+ "progress.label": "Order progress",
1064
+ "step.paid": "Paid",
1065
+ "step.preparing": "Being prepared",
1066
+ "step.shipped": "Shipped",
1067
+ "step.in_transit": "On its way",
1068
+ "step.ready_for_pickup": "Ready for pickup",
1069
+ "step.delivered": "Delivered",
1070
+ "step.unknown": "Next step",
1071
+ "stepState.done": "completed",
1072
+ "stepState.current": "current step",
1073
+ "stepState.pending": "pending",
1074
+ "stepState.problem": "has a problem",
1075
+ "problem.delivery_exception": "There was a problem with the delivery. Contact the store if it is not resolved.",
1076
+ "problem.returned": "The package went back to the store. Contact us to arrange a new shipment.",
1077
+ "problem.lost": "We could not find your package. Contact us and we will sort it out.",
1078
+ "problem.payment_failed": "The payment did not go through. You can try again.",
1079
+ "problem.unknown": "Your order has a problem. Contact the store.",
1080
+ "progress.cancelled": "This order was cancelled.",
1081
+ "progress.refunded": "This order was refunded.",
1082
+ "action.pay": "Pay now",
1083
+ "action.track": "Track shipment",
1084
+ "action.pickup": "Pick up in store",
1085
+ "action.download_invoice": "Download invoice",
1086
+ "action.request_invoice": "Request invoice",
1087
+ "action.correct_invoice_data": "Fix billing details",
1088
+ "action.contact_store": "Contact the store",
1089
+ "action.unknown": "View details",
1090
+ "action.newTab": "(opens in a new tab)",
1091
+ "action.label": "Next step of the order",
1092
+ "shipment.title": "Shipment",
1093
+ "shipment.return": "Return",
1094
+ "shipment.carrier": "Carrier",
1095
+ "shipment.service": "Service",
1096
+ "shipment.number": "Tracking number",
1097
+ "shipment.copy": "Copy",
1098
+ "shipment.copied": "Copied",
1099
+ "shipment.copyFailed": "We could not copy; select the text.",
1100
+ "shipment.track": "Track with {carrier}",
1101
+ "shipment.trackGeneric": "Track shipment",
1102
+ "shipment.promised": "Arrives by {date}",
1103
+ "shipment.delivered": "Delivered on {date}",
1104
+ "shipment.shipped": "Shipped on {date}",
1105
+ "shipment.events": "Updates",
1106
+ "shipment.noEvents": "The carrier has not reported any movement yet; it usually takes 24 hours.",
1107
+ "shipment.showAll": "Show all ({count})",
1108
+ "shipment.showLess": "Show less",
1109
+ "shipment.returnLabel": "Return label",
1110
+ "shipment.test": "Test",
1111
+ "shipment.testNote": "Test shipment: it is not a real shipment.",
1112
+ "shipment.preparing": "Preparing your shipment",
1113
+ "shipment.status.pending": "Preparing shipment",
1114
+ "shipment.status.label_created": "Label created",
1115
+ "shipment.status.in_transit": "On its way",
1116
+ "shipment.status.out_for_delivery": "Out for delivery",
1117
+ "shipment.status.delivered": "Delivered",
1118
+ "shipment.status.exception": "Delivery problem",
1119
+ "shipment.status.returned": "Returned to the store",
1120
+ "shipment.status.lost": "Lost",
1121
+ "shipment.status.cancelled": "Cancelled",
1122
+ "shipment.status.unknown": "In progress",
1123
+ "shipment.eventFrom": "{location}",
1124
+ "invoice.title": "Invoices",
1125
+ "invoice.invoice": "Invoice",
1126
+ "invoice.creditNote": "Credit note",
1127
+ "invoice.creditNoteOf": "Corrects invoice {folio}",
1128
+ "invoice.folio": "Tax folio",
1129
+ "invoice.series": "Series and number",
1130
+ "invoice.issued": "Issued on {date}",
1131
+ "invoice.total": "Total",
1132
+ "invoice.pdf": "Download PDF",
1133
+ "invoice.xml": "Download XML",
1134
+ "invoice.downloadOf": "{action}, {kind} {name}",
1135
+ "invoice.none": "There are no invoices for this order yet.",
1136
+ "invoice.test": "Test invoice, not valid",
1137
+ "invoice.status.issued": "Issued",
1138
+ "invoice.status.pending": "In progress",
1139
+ "invoice.status.cancelled": "Cancelled",
1140
+ "invoice.status.error": "Could not be issued",
1141
+ "invoice.status.unknown": "In progress",
1142
+ "invoice.statusNote.pending": "We are generating it; we will let you know when it is ready.",
1143
+ "invoice.statusNote.error": "Contact the store to resolve it.",
1144
+ "invoice.statusNote.cancelled": "This invoice was cancelled and is no longer valid.",
1145
+ "pending.title": "Waiting for payment",
1146
+ "pending.intro": "Your order is created as soon as we confirm the payment. Pay with the voucher before it expires.",
1147
+ "pending.waiting": "Waiting for payment",
1148
+ "pending.expired": "Expired",
1149
+ "pending.reference": "Reference",
1150
+ "pending.clabe": "CLABE",
1151
+ "pending.expires": "Expires on {date}",
1152
+ "pending.expiredOn": "Expired on {date}",
1153
+ "pending.total": "Total",
1154
+ "pending.copyReference": "Copy reference",
1155
+ "pending.copyClabe": "Copy CLABE",
1156
+ "pending.copied": "Copied",
1157
+ "pending.copyFailed": "We could not copy; select the text.",
1158
+ "pending.print": "View and print voucher",
1159
+ "pending.download": "Download voucher",
1160
+ "pending.expiredNote": "This voucher is no longer valid. Place your order again.",
1161
+ "pending.barcode": "Barcode {code}",
1162
+ "pending.method.oxxo": "OXXO",
1163
+ "pending.method.spei": "SPEI transfer",
1164
+ "pending.method.bank_transfer": "Bank transfer",
1165
+ "pending.method.bank_deposit": "Bank deposit",
1166
+ "pending.method.cash": "Cash payment",
1167
+ "pending.method.unknown": "Cash payment",
1168
+ "refund.title": "Refunds",
1169
+ "refund.status.requested": "Requested",
1170
+ "refund.status.processing": "In progress",
1171
+ "refund.status.completed": "Completed",
1172
+ "refund.status.failed": "Could not be completed",
1173
+ "refund.status.unknown": "In progress",
1174
+ "refund.requested": "Requested on {date}",
1175
+ "refund.completed": "Completed on {date}",
1176
+ "refund.none": "This order has no refunds.",
1177
+ "payment.title": "Payments",
1178
+ "payment.status.paid": "Paid",
1179
+ "payment.status.pending": "Pending",
1180
+ "payment.status.failed": "Failed",
1181
+ "payment.status.refunded": "Refunded",
1182
+ "payment.status.partially_refunded": "Partially refunded",
1183
+ "payment.status.unknown": "In progress",
1184
+ "payment.paidOn": "Paid on {date}",
1185
+ "section.error": "We could not load this section.",
1186
+ "section.retry": "Try again",
1187
+ "section.loading": "Loading"
1188
+ };
1189
+ function accountMessages(locale, overrides) {
1190
+ const base = (locale ?? "es-MX").toLowerCase().startsWith("en") ? EN4 : ES4;
1191
+ return overrides ? { ...base, ...overrides } : base;
1192
+ }
1193
+ function enumText(m, group, value) {
1194
+ const key = `${group}.${typeof value === "string" ? value : ""}`;
1195
+ return Object.prototype.hasOwnProperty.call(m, key) ? m[key] : m[`${group}.unknown`];
1196
+ }
1197
+ var StorefrontContext = react.createContext(null);
1198
+ function useOptionalStorefront() {
1199
+ return react.useContext(StorefrontContext);
1200
+ }
1201
+
1202
+ // src/locale.ts
1203
+ function useResolvedLocale(locale) {
1204
+ const sf = useOptionalStorefront();
1205
+ return locale ?? sf?.locale ?? "es-MX";
1206
+ }
1207
+ var SR_ONLY = {
1208
+ position: "absolute",
1209
+ width: 1,
1210
+ height: 1,
1211
+ padding: 0,
1212
+ margin: -1,
1213
+ overflow: "hidden",
1214
+ clip: "rect(0 0 0 0)",
1215
+ whiteSpace: "nowrap",
1216
+ border: 0
1217
+ };
1218
+ function str(v) {
1219
+ if (typeof v === "number") return Number.isFinite(v) ? String(v) : null;
1220
+ if (typeof v !== "string") return null;
1221
+ const s = v.trim();
1222
+ return s ? s : null;
1223
+ }
1224
+ function moneyText(v, locale) {
1225
+ if (!v || typeof v !== "object") return null;
1226
+ const { amount, currency_code } = v;
1227
+ const a = typeof amount === "number" ? String(amount) : amount;
1228
+ if (typeof a !== "string" || !a.trim() || !Number.isFinite(Number(a)) || typeof currency_code !== "string" || !/^[A-Za-z]{3}$/.test(currency_code)) return null;
1229
+ return storefront.formatMoney({ amount: a.trim(), currency_code: currency_code.toUpperCase() }, locale);
1230
+ }
1231
+ function Hidden({ children }) {
1232
+ return /* @__PURE__ */ jsxRuntime.jsx("span", { style: SR_ONLY, children });
1233
+ }
1234
+ function useAccountText({ locale, messages, timeZone }) {
1235
+ const resolved = useResolvedLocale(locale);
1236
+ const m = accountMessages(resolved, messages);
1237
+ const date = (iso, style = "date") => formatDate(iso, resolved, style, timeZone);
1238
+ const t = (key, vars) => vars ? fill(m[key], vars) : m[key];
1239
+ return { locale: resolved, m, t, date, timeZone };
1240
+ }
1241
+ function formatDate(iso, locale, style = "date", timeZone) {
1242
+ if (!iso || typeof iso !== "string") return null;
1243
+ const dayOnly = /^\d{4}-\d{2}-\d{2}$/.test(iso);
1244
+ const d = new Date(dayOnly ? `${iso}T12:00:00Z` : iso);
1245
+ if (Number.isNaN(d.getTime())) return null;
1246
+ const zone = dayOnly ? "UTC" : timeZone;
1247
+ try {
1248
+ return new Intl.DateTimeFormat(locale, { dateStyle: "long", ...style === "datetime" && !dayOnly ? { timeStyle: "short" } : {}, ...zone ? { timeZone: zone } : {} }).format(d);
1249
+ } catch {
1250
+ return d.toISOString().slice(0, 10);
1251
+ }
1252
+ }
1253
+ function Time({ value, text: text2, className }) {
1254
+ if (!value || !text2) return null;
1255
+ return /* @__PURE__ */ jsxRuntime.jsx("time", { dateTime: value, className, suppressHydrationWarning: true, children: text2 });
1256
+ }
1257
+ function plural(m, base, count) {
1258
+ return fill(count === 1 ? m["order.items.one"] : m["order.items.other"], { count });
1259
+ }
1260
+ function CopyButton({ value, label, copiedLabel, failedLabel, className, ariaLabel, ...rest }) {
1261
+ const [state, setState] = react.useState("idle");
1262
+ const timer = react.useRef(void 0);
1263
+ react.useEffect(() => () => clearTimeout(timer.current), []);
1264
+ const copy = react.useCallback(async () => {
1265
+ try {
1266
+ await navigator.clipboard.writeText(value);
1267
+ setState("copied");
1268
+ } catch {
1269
+ setState("failed");
1270
+ }
1271
+ clearTimeout(timer.current);
1272
+ timer.current = setTimeout(() => setState("idle"), 3e3);
1273
+ }, [value]);
1274
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1275
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: copy, className, "aria-label": ariaLabel, "data-sf-copy": rest["data-sf-copy"] ?? "", "data-state": state, children: state === "copied" ? copiedLabel : label }),
1276
+ /* @__PURE__ */ jsxRuntime.jsx("span", { role: "status", "aria-live": "polite", "data-sf-copy-status": true, style: state === "failed" ? void 0 : SR_ONLY, children: state === "copied" ? copiedLabel : state === "failed" ? failedLabel : "" })
1277
+ ] });
1278
+ }
1279
+ var STEP_STATES = /* @__PURE__ */ new Set(["done", "current", "pending", "problem"]);
1280
+ var stepState = (s) => typeof s === "string" && STEP_STATES.has(s) ? s : "pending";
1281
+ var GLYPH = { done: "\u2713", current: "\u25CF", pending: "\u25CB", problem: "!" };
1282
+ function stageTone(stage, problem) {
1283
+ if (problem) return "problem";
1284
+ if (stage === "delivered") return "done";
1285
+ if (stage === "cancelled" || stage === "refunded") return "muted";
1286
+ if (["pending_payment", "paid", "preparing", "ready_for_pickup", "shipped", "in_transit", "out_for_delivery"].includes(stage)) return "current";
1287
+ return "muted";
1288
+ }
1289
+ function OrderStatusBadge({ order, progress, className, ...text2 }) {
1290
+ const { m } = useAccountText(text2);
1291
+ const p = progress ?? (order ? storefront.orderProgress(order) : null);
1292
+ if (!p) return null;
1293
+ return /* @__PURE__ */ jsxRuntime.jsxs("span", { className, "data-sf-order-badge": true, "data-sf-stage": p.stage, "data-sf-tone": stageTone(p.stage, p.problem), children: [
1294
+ enumText(m, "stage", p.stage),
1295
+ p.problem ? /* @__PURE__ */ jsxRuntime.jsx(Hidden, { children: `, ${m["stepState.problem"]}` }) : null
1296
+ ] });
1297
+ }
1298
+ function OrderProgress({ order, progress, variant = "full", classNames: cx = {}, ...text2 }) {
1299
+ const { m, t, date } = useAccountText(text2);
1300
+ const p = progress ?? (order ? storefront.orderProgress(order) : null);
1301
+ if (!p) return null;
1302
+ const steps = Array.isArray(p.steps) ? p.steps.filter((s) => s && typeof s === "object") : [];
1303
+ const stepLabel = (s) => enumText(m, "step", s.key);
1304
+ if (steps.length === 0 || p.stage === "cancelled" || p.stage === "refunded") {
1305
+ const note = p.stage === "cancelled" ? m["progress.cancelled"] : p.stage === "refunded" ? m["progress.refunded"] : enumText(m, "stage", p.stage);
1306
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.root, "data-sf-progress": true, "data-sf-stage": p.stage, "data-sf-variant": variant, children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.terminal, "data-sf-progress-terminal": true, children: note }) });
1307
+ }
1308
+ if (variant === "compact") {
1309
+ const at = Math.max(0, steps.findIndex((s) => stepState(s.state) === "current" || stepState(s.state) === "problem"));
1310
+ const index = steps.some((s) => stepState(s.state) === "current" || stepState(s.state) === "problem") ? at : steps.every((s) => stepState(s.state) === "done") ? steps.length - 1 : 0;
1311
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.root, "data-sf-progress": true, "data-sf-stage": p.stage, "data-sf-variant": "compact", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.label, "data-sf-progress-summary": true, children: t("order.stepOf", { n: index + 1, total: steps.length, step: stepLabel(steps[index]) }) }) });
1312
+ }
1313
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.root, "data-sf-progress": true, "data-sf-stage": p.stage, "data-sf-variant": "full", children: [
1314
+ /* @__PURE__ */ jsxRuntime.jsx("ol", { className: cx.list, "aria-label": m["progress.label"], "data-sf-progress-list": true, children: steps.map((s, i) => {
1315
+ const state = stepState(s.state);
1316
+ return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: cx.step, "data-sf-step": typeof s.key === "string" ? s.key : "unknown", "data-sf-step-state": state, ...state === "current" || state === "problem" ? { "aria-current": "step" } : {}, children: [
1317
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.marker, "aria-hidden": "true", "data-sf-step-marker": true, children: GLYPH[state] }),
1318
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: cx.label, "data-sf-step-label": true, children: [
1319
+ stepLabel(s),
1320
+ /* @__PURE__ */ jsxRuntime.jsx(Hidden, { children: `, ${m[`stepState.${state}`]}` })
1321
+ ] }),
1322
+ /* @__PURE__ */ jsxRuntime.jsx(Time, { value: s.at, text: date(s.at), className: cx.time })
1323
+ ] }, `${s.key}-${i}`);
1324
+ }) }),
1325
+ p.problem ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.problem, "data-sf-progress-problem": typeof p.problem.code === "string" ? p.problem.code : "unknown", children: enumText(m, "problem", p.problem.code) }) : null
1326
+ ] });
1327
+ }
1328
+ function NextActionBar({ order, action, hrefFor, onAction, secondary, classNames: cx = {}, ...text2 }) {
1329
+ const { m } = useAccountText(text2);
1330
+ const a = action ?? (order ? storefront.nextAction(order) : null);
1331
+ if (!a || a.kind === "none") return secondary ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.root, "data-sf-action-bar": true, children: secondary }) : null;
1332
+ const fromApi = a.kind === "track" || a.kind === "pickup" ? storefront.safeTrackingUrl(a.href) : null;
1333
+ const href = hrefFor?.(a) ?? fromApi;
1334
+ const external = !!href && /^https:\/\//i.test(href);
1335
+ const label = enumText(m, "action", a.kind);
1336
+ const common = { className: cx.primary, "data-sf-action": typeof a.kind === "string" ? a.kind : "unknown" };
1337
+ let primary = null;
1338
+ if (href) {
1339
+ primary = /* @__PURE__ */ jsxRuntime.jsxs("a", { href, ...common, ...external ? { target: "_blank", rel: "noopener noreferrer" } : {}, onClick: onAction ? (e) => onAction(a, e) : void 0, children: [
1340
+ label,
1341
+ external ? /* @__PURE__ */ jsxRuntime.jsxs(Hidden, { children: [
1342
+ " ",
1343
+ m["action.newTab"]
1344
+ ] }) : null
1345
+ ] });
1346
+ } else if (onAction) {
1347
+ primary = /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", ...common, onClick: (e) => onAction(a, e), children: label });
1348
+ }
1349
+ if (!primary && !secondary) return null;
1350
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.root, role: "group", "aria-label": m["action.label"], "data-sf-action-bar": true, children: [
1351
+ primary,
1352
+ secondary
1353
+ ] });
1354
+ }
1355
+ function OrderCard({ order, orderHref, actionHref, onAction, headingLevel = 3, classNames: cx = {}, ...text2 }) {
1356
+ const { m, date, locale } = useAccountText(text2);
1357
+ const Heading = `h${headingLevel}`;
1358
+ const progress = storefront.orderProgress(order);
1359
+ const items = (Array.isArray(order.lines) ? order.lines : []).reduce((n, l) => n + (Number.isFinite(l?.quantity) ? l.quantity : 0), 0);
1360
+ const summary = order.shipments_summary && typeof order.shipments_summary === "object" ? order.shipments_summary : null;
1361
+ const shipments = Array.isArray(order.shipments) ? order.shipments : [];
1362
+ const showShipment = !!summary && typeof summary.count === "number" && summary.count > 0 && !(shipments.length > 0 && shipments.every(storefront.isTestShipment)) && !["pending_payment", "cancelled", "refunded"].includes(progress.stage);
1363
+ const action = storefront.nextAction(order);
1364
+ const total = moneyText(order.total, locale);
1365
+ const carrier = summary ? str(summary.carrier) : null;
1366
+ return /* @__PURE__ */ jsxRuntime.jsxs("article", { className: cx.root, "data-sf-order": true, "data-sf-order-status": progress.stage, "data-sf-order-id": order.id, children: [
1367
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: cx.header, children: [
1368
+ /* @__PURE__ */ jsxRuntime.jsx(Heading, { className: cx.number, "data-sf-order-number": true, children: /* @__PURE__ */ jsxRuntime.jsx("a", { href: orderHref(order), className: cx.link, "data-sf-order-link": true, children: fill(m["order.number"], { number: str(order.number) ?? (str(order.id) ?? "").slice(0, 8) }) }) }),
1369
+ /* @__PURE__ */ jsxRuntime.jsx(OrderStatusBadge, { progress, ...text2, ...cx.badge ? { className: cx.badge } : {} })
1370
+ ] }),
1371
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.meta, "data-sf-order-meta": true, children: [
1372
+ /* @__PURE__ */ jsxRuntime.jsx(Time, { value: order.created_at, text: date(order.created_at) ? fill(m["order.placed"], { date: date(order.created_at) }) : null }),
1373
+ items > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1374
+ " \xB7 ",
1375
+ plural(m, "order.items", items)
1376
+ ] }) : null
1377
+ ] }),
1378
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.summary, "data-sf-order-summary": true, children: [
1379
+ /* @__PURE__ */ jsxRuntime.jsx(OrderProgress, { progress, variant: "compact", ...text2, ...cx.progress ? { classNames: cx.progress } : {} }),
1380
+ showShipment ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.shipment, "data-sf-order-shipment": true, children: [
1381
+ carrier ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1382
+ carrier,
1383
+ " \xB7 "
1384
+ ] }) : null,
1385
+ enumText(m, "shipment.status", summary.status)
1386
+ ] }) : null
1387
+ ] }),
1388
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.footer, children: [
1389
+ total ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.total, "data-sf-order-total": true, children: [
1390
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
1391
+ m["order.total"],
1392
+ ": "
1393
+ ] }),
1394
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: total })
1395
+ ] }) : null,
1396
+ /* @__PURE__ */ jsxRuntime.jsx(
1397
+ NextActionBar,
1398
+ {
1399
+ action,
1400
+ ...text2,
1401
+ hrefFor: (a) => actionHref?.(a, order) ?? void 0,
1402
+ ...onAction ? { onAction: (a) => onAction(a, order) } : {},
1403
+ classNames: { ...cx.actions ? { root: cx.actions } : {}, ...cx.action ?? {} }
1404
+ }
1405
+ )
1406
+ ] })
1407
+ ] });
1408
+ }
1409
+ function OrderList({ orders, status = "ready", skeletons = 3, onRetry, hasMore, loadingMore, onLoadMore, emptyAction, guestHint = true, orderHref, actionHref, onAction, headingLevel = 3, classNames: cx = {}, ...text2 }) {
1410
+ const { m } = useAccountText(text2);
1411
+ const list = (Array.isArray(orders) ? orders : []).filter((o) => !!o && typeof o === "object" && typeof o.id === "string");
1412
+ if (status === "loading" && list.length === 0) {
1413
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.root, role: "status", "aria-busy": "true", "data-sf-orders": true, "data-sf-orders-state": "loading", children: [
1414
+ /* @__PURE__ */ jsxRuntime.jsx(Hidden, { children: m["order.loading"] }),
1415
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: cx.list, "aria-hidden": "true", children: Array.from({ length: Math.max(1, skeletons) }, (_, i) => /* @__PURE__ */ jsxRuntime.jsx("li", { className: cx.skeleton, "data-sf-skeleton": true }, i)) })
1416
+ ] });
1417
+ }
1418
+ if (status === "error" && list.length === 0) {
1419
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.root, "data-sf-orders": true, "data-sf-orders-state": "error", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.error, role: "alert", "data-sf-orders-error": true, children: [
1420
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: m["order.error"] }),
1421
+ onRetry ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.retry, onClick: onRetry, "data-sf-retry": true, children: m["order.retry"] }) : null
1422
+ ] }) });
1423
+ }
1424
+ if (list.length === 0) {
1425
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.root, "data-sf-orders": true, "data-sf-orders-state": "empty", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.empty, "data-sf-orders-empty": true, children: [
1426
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.emptyTitle, children: /* @__PURE__ */ jsxRuntime.jsx("strong", { children: m["order.emptyTitle"] }) }),
1427
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.emptyBody, children: m["order.emptyBody"] }),
1428
+ guestHint ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.emptyGuest, "data-sf-orders-guest-hint": true, children: m["order.emptyGuest"] }) : null,
1429
+ emptyAction
1430
+ ] }) });
1431
+ }
1432
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.root, "data-sf-orders": true, "data-sf-orders-state": "ready", children: [
1433
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: cx.list, "aria-label": m["order.listLabel"], "data-sf-orders-list": true, children: list.map((o) => /* @__PURE__ */ jsxRuntime.jsx("li", { className: cx.item, children: /* @__PURE__ */ jsxRuntime.jsx(OrderCard, { order: o, orderHref, ...actionHref ? { actionHref } : {}, ...onAction ? { onAction } : {}, headingLevel, ...text2, ...cx.card ? { classNames: cx.card } : {} }) }, o.id)) }),
1434
+ status === "error" ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.error, role: "alert", "data-sf-orders-error": true, children: [
1435
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: m["order.error"] }),
1436
+ onRetry ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.retry, onClick: onRetry, "data-sf-retry": true, children: m["order.retry"] }) : null
1437
+ ] }) : null,
1438
+ hasMore && onLoadMore ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.more, onClick: onLoadMore, disabled: loadingMore, "aria-disabled": loadingMore || void 0, "data-sf-orders-more": true, children: loadingMore ? m["order.loadingMore"] : m["order.loadMore"] }) : null
1439
+ ] });
1440
+ }
1441
+ function ShipmentCard({ shipment, testMode = "hide", eventsPreview = 3, renderCarrierMark, renderMap, headingLevel = 3, classNames: cx = {}, ...text2 }) {
1442
+ const { m, t, date } = useAccountText(text2);
1443
+ const [open, setOpen] = react.useState(false);
1444
+ const id = react.useId().replace(/:/g, "");
1445
+ if (!shipment || typeof shipment !== "object") return null;
1446
+ const test = storefront.isTestShipment(shipment);
1447
+ if (test && testMode === "hide") return null;
1448
+ const isReturn = shipment.kind === "return";
1449
+ const Heading = `h${headingLevel}`;
1450
+ const SubHeading = `h${headingLevel + 1}`;
1451
+ const carrier = str(shipment.carrier);
1452
+ const service = test ? null : str(shipment.service);
1453
+ const number = test ? null : str(shipment.tracking_number);
1454
+ const trackUrl = test ? null : storefront.safeTrackingUrl(shipment.tracking_url);
1455
+ const labelUrl = isReturn && !test ? storefront.safeTrackingUrl(shipment.label_url) : null;
1456
+ const events = test ? [] : storefront.sortTrackingEvents(shipment.events);
1457
+ const shown = open ? events : events.slice(0, Math.max(1, eventsPreview));
1458
+ const status = test ? m["shipment.preparing"] : enumText(m, "shipment.status", shipment.status);
1459
+ const promised = !test && shipment.status !== "delivered" ? date(shipment.promised_by) : null;
1460
+ const delivered = !test ? date(shipment.delivered_at) : null;
1461
+ const shipped = !test && !delivered ? date(shipment.shipped_at) : null;
1462
+ const titleId = `sf-shp-${id}`;
1463
+ const eventsId = `sf-shp-ev-${id}`;
1464
+ return /* @__PURE__ */ jsxRuntime.jsxs("article", { className: cx.root, "aria-labelledby": titleId, "data-sf-shipment": true, "data-sf-shipment-status": test ? "test" : typeof shipment.status === "string" ? shipment.status : "unknown", "data-sf-shipment-kind": isReturn ? "return" : "outbound", ...test ? { "data-sf-test": "" } : {}, children: [
1465
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: cx.header, "data-sf-shipment-header": true, children: [
1466
+ renderCarrierMark && !test ? /* @__PURE__ */ jsxRuntime.jsx("span", { "data-sf-shipment-mark": true, children: renderCarrierMark(shipment) }) : null,
1467
+ /* @__PURE__ */ jsxRuntime.jsxs(Heading, { id: titleId, className: cx.carrier, "data-sf-shipment-title": true, children: [
1468
+ isReturn ? m["shipment.return"] : carrier ?? m["shipment.title"],
1469
+ isReturn && carrier ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1470
+ " \xB7 ",
1471
+ carrier
1472
+ ] }) : null
1473
+ ] }),
1474
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.status, "data-sf-shipment-state": true, children: status }),
1475
+ test ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.test, "data-sf-shipment-test": true, children: m["shipment.test"] }) : null
1476
+ ] }),
1477
+ test ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.meta, "data-sf-shipment-test-note": true, children: m["shipment.testNote"] }) : null,
1478
+ service ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.meta, "data-sf-shipment-service": true, children: [
1479
+ m["shipment.service"],
1480
+ ": ",
1481
+ service
1482
+ ] }) : null,
1483
+ number ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.number, "data-sf-shipment-number": true, children: [
1484
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
1485
+ m["shipment.number"],
1486
+ ": "
1487
+ ] }),
1488
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: number }),
1489
+ " ",
1490
+ /* @__PURE__ */ jsxRuntime.jsx(CopyButton, { value: number, label: m["shipment.copy"], copiedLabel: m["shipment.copied"], failedLabel: m["shipment.copyFailed"], ariaLabel: `${m["shipment.copy"]} ${m["shipment.number"]}`, className: cx.copy, "data-sf-copy": "tracking" })
1491
+ ] }) : null,
1492
+ promised || delivered || shipped ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.meta, "data-sf-shipment-dates": true, children: delivered ? /* @__PURE__ */ jsxRuntime.jsx(Time, { value: shipment.delivered_at, text: t("shipment.delivered", { date: delivered }) }) : promised ? /* @__PURE__ */ jsxRuntime.jsx(Time, { value: shipment.promised_by, text: t("shipment.promised", { date: promised }) }) : /* @__PURE__ */ jsxRuntime.jsx(Time, { value: shipment.shipped_at, text: t("shipment.shipped", { date: shipped ?? "" }) }) }) : null,
1493
+ trackUrl || labelUrl ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.actions, "data-sf-shipment-actions": true, children: [
1494
+ trackUrl ? /* @__PURE__ */ jsxRuntime.jsxs("a", { href: trackUrl, target: "_blank", rel: "noopener noreferrer", className: cx.link, "data-sf-shipment-track": true, children: [
1495
+ carrier ? t("shipment.track", { carrier }) : m["shipment.trackGeneric"],
1496
+ /* @__PURE__ */ jsxRuntime.jsxs(Hidden, { children: [
1497
+ " ",
1498
+ m["action.newTab"]
1499
+ ] })
1500
+ ] }) : null,
1501
+ labelUrl ? /* @__PURE__ */ jsxRuntime.jsxs("a", { href: labelUrl, target: "_blank", rel: "noopener noreferrer", className: cx.link, "data-sf-shipment-label": true, children: [
1502
+ m["shipment.returnLabel"],
1503
+ /* @__PURE__ */ jsxRuntime.jsxs(Hidden, { children: [
1504
+ " ",
1505
+ m["action.newTab"]
1506
+ ] })
1507
+ ] }) : null
1508
+ ] }) : null,
1509
+ renderMap && !test && shipment.map ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.map, "data-sf-shipment-map-slot": true, children: renderMap({ shipment, map: shipment.map }) }) : null,
1510
+ !test ? events.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.empty, "data-sf-shipment-empty": true, children: m["shipment.noEvents"] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { "data-sf-shipment-events-wrap": true, children: [
1511
+ /* @__PURE__ */ jsxRuntime.jsx(SubHeading, { className: cx.meta, "data-sf-shipment-events-title": true, children: m["shipment.events"] }),
1512
+ /* @__PURE__ */ jsxRuntime.jsx("ol", { className: cx.events, id: eventsId, "data-sf-shipment-events": true, children: shown.map((e, i) => {
1513
+ const description = str(e.description);
1514
+ const location = str(e.location);
1515
+ return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: cx.event, "data-sf-event-status": typeof e.status === "string" ? e.status : "unknown", children: [
1516
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "data-sf-event-state": true, children: enumText(m, "shipment.status", e.status) }),
1517
+ description ? /* @__PURE__ */ jsxRuntime.jsxs("span", { "data-sf-event-description": true, children: [
1518
+ " \xB7 ",
1519
+ description
1520
+ ] }) : null,
1521
+ location ? /* @__PURE__ */ jsxRuntime.jsxs("span", { "data-sf-event-location": true, children: [
1522
+ " \xB7 ",
1523
+ location
1524
+ ] }) : null,
1525
+ " ",
1526
+ /* @__PURE__ */ jsxRuntime.jsx(Time, { value: e.occurred_at, text: date(e.occurred_at, "datetime") })
1527
+ ] }, `${str(e.id) ?? ""}-${i}`);
1528
+ }) }),
1529
+ events.length > Math.max(1, eventsPreview) ? /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.toggle, "aria-expanded": open, "aria-controls": eventsId, onClick: () => setOpen((v) => !v), "data-sf-shipment-toggle": true, children: open ? m["shipment.showLess"] : t("shipment.showAll", { count: events.length }) }) : null
1530
+ ] }) : null
1531
+ ] });
1532
+ }
1533
+ var known = (s) => s === "issued" || s === "pending" || s === "cancelled" || s === "error";
1534
+ function InvoiceList({ invoices, summary, renderSummary, fileHref, onDownload, degraded, onRetry, testMode = "mark", headingLevel = 3, children, classNames: cx = {}, ...text2 }) {
1535
+ const { m, date, locale } = useAccountText(text2);
1536
+ const Heading = `h${headingLevel}`;
1537
+ const titleId = `sf-invoices-${react.useId().replace(/:/g, "")}`;
1538
+ const all = (Array.isArray(invoices) ? invoices : []).filter((d) => !!d && typeof d === "object" && typeof d.id === "string");
1539
+ const docs = testMode === "hide" ? all.filter((d) => !storefront.isTestInvoice(d)) : all;
1540
+ const { groups, orphans } = storefront.groupInvoiceDocs(docs);
1541
+ const renderDoc = (doc, parent) => {
1542
+ const test = storefront.isTestInvoice(doc);
1543
+ const status = known(doc.status) ? doc.status : "unknown";
1544
+ const kindLabel = doc.kind === "credit_note" ? m["invoice.creditNote"] : m["invoice.invoice"];
1545
+ const docName = (d) => [str(d.series), str(d.folio_number)].filter(Boolean).join("-");
1546
+ const name = docName(doc);
1547
+ const folio = str(doc.folio);
1548
+ const canDownload = status === "issued" && !test;
1549
+ const total = moneyText(doc.total, locale);
1550
+ const link = (kind) => {
1551
+ const label = kind === "pdf" ? m["invoice.pdf"] : m["invoice.xml"];
1552
+ const aria = fill(m["invoice.downloadOf"], { action: label, kind: kindLabel.toLowerCase(), name: name || folio || "" }).replace(/\s+,/g, ",").replace(/,\s*$/, "").trim();
1553
+ const href = fileHref?.(doc, kind);
1554
+ if (href) {
1555
+ return /* @__PURE__ */ jsxRuntime.jsx("a", { href, download: true, className: cx.download, "aria-label": aria, "data-sf-invoice-download": kind, children: label }, kind);
1556
+ }
1557
+ if (onDownload) {
1558
+ return /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.download, "aria-label": aria, onClick: () => onDownload(doc, kind), "data-sf-invoice-download": kind, children: label }, kind);
1559
+ }
1560
+ return null;
1561
+ };
1562
+ return /* @__PURE__ */ jsxRuntime.jsxs("li", { className: cx.doc, "data-sf-invoice-doc": true, "data-sf-invoice-kind": doc.kind === "credit_note" ? "credit_note" : "invoice", "data-sf-invoice-status": status, children: [
1563
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.status, "data-sf-invoice-heading": true, children: [
1564
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: kindLabel }),
1565
+ name ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1566
+ " ",
1567
+ name
1568
+ ] }) : null,
1569
+ " \xB7 ",
1570
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "data-sf-invoice-state": true, children: enumText(m, "invoice.status", doc.status) }),
1571
+ test ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1572
+ " ",
1573
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.test, "data-sf-invoice-test": true, children: m["invoice.test"] })
1574
+ ] }) : null
1575
+ ] }),
1576
+ parent ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.meta, "data-sf-invoice-parent": true, children: fill(m["invoice.creditNoteOf"], { folio: docName(parent) || str(parent.folio) || "" }).trim() }) : null,
1577
+ folio && !test ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.meta, "data-sf-invoice-folio": true, children: [
1578
+ m["invoice.folio"],
1579
+ ": ",
1580
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: folio })
1581
+ ] }) : null,
1582
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.meta, children: [
1583
+ doc.issued_at ? /* @__PURE__ */ jsxRuntime.jsx(Time, { value: doc.issued_at, text: fill(m["invoice.issued"], { date: date(doc.issued_at) ?? "" }) }) : null,
1584
+ total ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1585
+ " \xB7 ",
1586
+ m["invoice.total"],
1587
+ ": ",
1588
+ total
1589
+ ] }) : null
1590
+ ] }),
1591
+ status === "pending" || status === "error" || status === "cancelled" ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.note, "data-sf-invoice-note": true, children: m[`invoice.statusNote.${status}`] }) : null,
1592
+ canDownload && (fileHref || onDownload) ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.actions, "data-sf-invoice-actions": true, children: [
1593
+ link("pdf"),
1594
+ link("xml")
1595
+ ] }) : null
1596
+ ] }, doc.id);
1597
+ };
1598
+ const hasDocs = groups.length + orphans.length > 0;
1599
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: cx.root, "aria-labelledby": titleId, "data-sf-invoices": true, children: [
1600
+ /* @__PURE__ */ jsxRuntime.jsx(Heading, { id: titleId, className: cx.title, children: m["invoice.title"] }),
1601
+ degraded ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.error, role: "alert", "data-sf-section-error": "invoices", children: [
1602
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: m["section.error"] }),
1603
+ onRetry ? /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: cx.retry, onClick: onRetry, "data-sf-retry": true, children: [
1604
+ m["section.retry"],
1605
+ /* @__PURE__ */ jsxRuntime.jsxs(Hidden, { children: [
1606
+ " ",
1607
+ m["invoice.title"]
1608
+ ] })
1609
+ ] }) : null
1610
+ ] }) : hasDocs ? /* @__PURE__ */ jsxRuntime.jsxs("ul", { "data-sf-invoice-list": true, children: [
1611
+ groups.map(({ invoice, creditNotes }) => /* @__PURE__ */ jsxRuntime.jsxs("li", { className: cx.group, "data-sf-invoice-group": true, children: [
1612
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { children: renderDoc(invoice) }),
1613
+ creditNotes.length ? /* @__PURE__ */ jsxRuntime.jsx("ul", { className: cx.creditNotes, "data-sf-invoice-credit-notes": true, children: creditNotes.map((nc) => renderDoc(nc, invoice)) }) : null
1614
+ ] }, invoice.id)),
1615
+ orphans.map((nc) => /* @__PURE__ */ jsxRuntime.jsx("li", { className: cx.group, "data-sf-invoice-group": true, children: /* @__PURE__ */ jsxRuntime.jsx("ul", { children: renderDoc(nc) }) }, nc.id))
1616
+ ] }) : summary && renderSummary ? /* @__PURE__ */ jsxRuntime.jsx("div", { "data-sf-invoice-summary": true, children: renderSummary(summary) }) : /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.empty, "data-sf-invoice-empty": true, children: m["invoice.none"] }),
1617
+ children
1618
+ ] });
1619
+ }
1620
+ init_voucher();
1621
+ function Barcode({ value, label, height = 56, className }) {
1622
+ const g = react.useMemo(() => barcodeGeometry(value, { height }), [value, height]);
1623
+ if (!g) return null;
1624
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { className, viewBox: `0 0 ${g.width} ${g.height}`, width: g.width, height: g.height, role: "img", "aria-label": label, shapeRendering: "crispEdges", fill: "#000", "data-sf-voucher-barcode-svg": true, children: g.rects.map((r) => /* @__PURE__ */ jsxRuntime.jsx("rect", { x: r.x, y: 0, width: r.w, height: g.height }, r.x)) });
1625
+ }
1626
+ async function openDocument(payment, mode, opts) {
1627
+ const v = voucherOf(payment);
1628
+ if (!v) return;
1629
+ const { renderVoucherDocument: renderVoucherDocument2 } = await Promise.resolve().then(() => (init_voucher_document(), voucher_document_exports));
1630
+ const html = renderVoucherDocument2(v, { locale: opts.locale, ...opts.shopName ? { shopName: opts.shopName } : {}, ...opts.timeZone ? { timeZone: opts.timeZone } : {}, printButton: mode === "print", autoPrint: mode === "print" });
1631
+ const url = URL.createObjectURL(new Blob([html], { type: "text/html;charset=utf-8" }));
1632
+ const download = () => {
1633
+ const a = document.createElement("a");
1634
+ a.href = url;
1635
+ a.download = "ficha-de-pago.html";
1636
+ a.click();
1637
+ };
1638
+ if (mode === "print") {
1639
+ const w = window.open(url, "_blank");
1640
+ if (w) w.opener = null;
1641
+ else download();
1642
+ } else download();
1643
+ setTimeout(() => URL.revokeObjectURL(url), 6e4);
1644
+ }
1645
+ function PendingPaymentCard({ payment, voucherHref, shopName, headingLevel = 3, classNames: cx = {}, children, ...text2 }) {
1646
+ const { m, date, locale, timeZone } = useAccountText(text2);
1647
+ const titleId = `sf-voucher-${react.useId().replace(/:/g, "")}`;
1648
+ const v = voucherOf(payment);
1649
+ if (!v) return null;
1650
+ const expired = payment.status === "expired";
1651
+ const Heading = `h${headingLevel}`;
1652
+ const code = barcodeValue(v);
1653
+ const methodLabel = enumText(m, "pending.method", v.method?.toLowerCase());
1654
+ const total = moneyText(payment.total, locale) ?? moneyText(v.amount, locale);
1655
+ const copyValue = v.reference ?? v.clabe;
1656
+ const expires = date(v.expires_at ?? payment.expires_at, "datetime");
1657
+ return /* @__PURE__ */ jsxRuntime.jsxs("article", { className: cx.root, "aria-labelledby": titleId, "data-sf-voucher": true, "data-sf-voucher-status": expired ? "expired" : "pending_payment", children: [
1658
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: cx.header, children: [
1659
+ /* @__PURE__ */ jsxRuntime.jsx(Heading, { id: titleId, className: cx.method, "data-sf-voucher-method": true, children: methodLabel }),
1660
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.badge, "data-sf-voucher-badge": true, "data-sf-tone": expired ? "muted" : "current", children: expired ? m["pending.expired"] : m["pending.waiting"] })
1661
+ ] }),
1662
+ v.reference ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.field, "data-sf-voucher-reference": true, children: [
1663
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.label, children: m["pending.reference"] }),
1664
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.value, "data-sf-voucher-value": true, children: v.reference })
1665
+ ] }) : null,
1666
+ v.clabe ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.field, "data-sf-voucher-clabe": true, children: [
1667
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.label, children: m["pending.clabe"] }),
1668
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.value, "data-sf-voucher-value": true, children: v.clabe })
1669
+ ] }) : null,
1670
+ code && !expired ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: cx.barcode, "data-sf-voucher-barcode": true, children: /* @__PURE__ */ jsxRuntime.jsx(Barcode, { value: code, label: fill(m["pending.barcode"], { code }) }) }) : null,
1671
+ expires ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.expiry, "data-sf-voucher-expiry": true, children: /* @__PURE__ */ jsxRuntime.jsx(Time, { value: v.expires_at ?? payment.expires_at, text: fill(m[expired ? "pending.expiredOn" : "pending.expires"], { date: expires }) }) }) : null,
1672
+ total ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: cx.total, "data-sf-voucher-total": true, children: [
1673
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
1674
+ m["pending.total"],
1675
+ ": "
1676
+ ] }),
1677
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: total })
1678
+ ] }) : null,
1679
+ expired ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.note, "data-sf-voucher-expired-note": true, children: m["pending.expiredNote"] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.actions, "data-sf-voucher-actions": true, children: [
1680
+ voucherHref ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1681
+ /* @__PURE__ */ jsxRuntime.jsxs("a", { href: voucherHref(payment, { download: false }), target: "_blank", rel: "noopener", className: cx.primary, "data-sf-voucher-print": true, children: [
1682
+ m["pending.print"],
1683
+ /* @__PURE__ */ jsxRuntime.jsxs(Hidden, { children: [
1684
+ " ",
1685
+ m["action.newTab"]
1686
+ ] })
1687
+ ] }),
1688
+ /* @__PURE__ */ jsxRuntime.jsx("a", { href: voucherHref(payment, { download: true }), download: true, className: cx.secondary, "data-sf-voucher-download": true, children: m["pending.download"] })
1689
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1690
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.primary, onClick: () => void openDocument(payment, "print", { locale, shopName, timeZone }), "data-sf-voucher-print": true, children: m["pending.print"] }),
1691
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: cx.secondary, onClick: () => void openDocument(payment, "download", { locale, shopName, timeZone }), "data-sf-voucher-download": true, children: m["pending.download"] })
1692
+ ] }),
1693
+ copyValue ? /* @__PURE__ */ jsxRuntime.jsx(CopyButton, { value: copyValue, label: v.reference ? m["pending.copyReference"] : m["pending.copyClabe"], copiedLabel: m["pending.copied"], failedLabel: m["pending.copyFailed"], className: cx.secondary, "data-sf-copy": "voucher" }) : null
1694
+ ] }),
1695
+ children
1696
+ ] });
1697
+ }
1698
+ function PendingPaymentList({ payments, voucherHref, shopName, classNames, listClassNames: lc = {}, headingLevel = 2, ...text2 }) {
1699
+ const { m } = useAccountText(text2);
1700
+ const titleId = `sf-pending-${react.useId().replace(/:/g, "")}`;
1701
+ const items = (Array.isArray(payments) ? payments : []).filter((p) => !!voucherOf(p));
1702
+ if (items.length === 0) return null;
1703
+ const sorted = [...items.filter((p) => p.status !== "expired"), ...items.filter((p) => p.status === "expired")];
1704
+ const Heading = `h${headingLevel}`;
1705
+ const cardHeading = headingLevel + 1;
1706
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: lc.root, "aria-labelledby": titleId, "data-sf-pending": true, children: [
1707
+ /* @__PURE__ */ jsxRuntime.jsx(Heading, { id: titleId, className: lc.title, children: m["pending.title"] }),
1708
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: lc.intro, children: m["pending.intro"] }),
1709
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: lc.list, children: sorted.map((p) => /* @__PURE__ */ jsxRuntime.jsx("li", { className: lc.item, children: /* @__PURE__ */ jsxRuntime.jsx(PendingPaymentCard, { payment: p, ...voucherHref ? { voucherHref } : {}, ...shopName ? { shopName } : {}, ...classNames ? { classNames } : {}, headingLevel: cardHeading, ...text2 }) }, p.id)) })
1710
+ ] });
1711
+ }
1712
+ var tone = (s) => s === "completed" ? "done" : s === "failed" ? "problem" : "current";
1713
+ function RefundList({ refunds, showEmpty = false, degraded, onRetry, headingLevel = 3, classNames: cx = {}, ...text2 }) {
1714
+ const { m, locale, date } = useAccountText(text2);
1715
+ const titleId = `sf-refunds-${react.useId().replace(/:/g, "")}`;
1716
+ const items = (Array.isArray(refunds) ? refunds : []).filter((r) => !!r && typeof r === "object" && typeof r.id === "string");
1717
+ if (!degraded && items.length === 0 && !showEmpty) return null;
1718
+ const Heading = `h${headingLevel}`;
1719
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: cx.root, "aria-labelledby": titleId, "data-sf-refunds": true, children: [
1720
+ /* @__PURE__ */ jsxRuntime.jsx(Heading, { id: titleId, className: cx.title, children: m["refund.title"] }),
1721
+ degraded ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx.error, role: "alert", "data-sf-section-error": "refunds", children: [
1722
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: m["section.error"] }),
1723
+ onRetry ? /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: cx.retry, onClick: onRetry, "data-sf-retry": true, children: [
1724
+ m["section.retry"],
1725
+ /* @__PURE__ */ jsxRuntime.jsxs(Hidden, { children: [
1726
+ " ",
1727
+ m["refund.title"]
1728
+ ] })
1729
+ ] }) : null
1730
+ ] }) : items.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.empty, children: m["refund.none"] }) : /* @__PURE__ */ jsxRuntime.jsx("ul", { className: cx.list, children: items.map((r) => /* @__PURE__ */ jsxRuntime.jsxs("li", { className: cx.item, "data-sf-refund": true, "data-sf-refund-status": typeof r.status === "string" ? r.status : "unknown", children: [
1731
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.amount, "data-sf-refund-amount": true, children: moneyText(r.amount, locale) ?? "" }),
1732
+ " ",
1733
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.status, "data-sf-tone": tone(r.status), children: enumText(m, "refund.status", r.status) }),
1734
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: cx.meta, children: [
1735
+ str(r.method_label) ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1736
+ " \xB7 ",
1737
+ str(r.method_label)
1738
+ ] }) : null,
1739
+ r.completed_at ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1740
+ " \xB7 ",
1741
+ /* @__PURE__ */ jsxRuntime.jsx(Time, { value: r.completed_at, text: fill(m["refund.completed"], { date: date(r.completed_at) ?? "" }) })
1742
+ ] }) : r.created_at ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1743
+ " \xB7 ",
1744
+ /* @__PURE__ */ jsxRuntime.jsx(Time, { value: r.created_at, text: fill(m["refund.requested"], { date: date(r.created_at) ?? "" }) })
1745
+ ] }) : null
1746
+ ] })
1747
+ ] }, r.id)) })
1748
+ ] });
1749
+ }
1750
+ function PaymentSummary({ payments, headingLevel = 3, classNames: cx = {}, ...text2 }) {
1751
+ const { m, locale, date } = useAccountText(text2);
1752
+ const titleId = `sf-payments-${react.useId().replace(/:/g, "")}`;
1753
+ const items = (Array.isArray(payments) ? payments : []).filter((p) => !!p && typeof p === "object" && typeof p.method_label === "string");
1754
+ if (items.length === 0) return null;
1755
+ const Heading = `h${headingLevel}`;
1756
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: cx.root, "aria-labelledby": titleId, "data-sf-payments": true, children: [
1757
+ /* @__PURE__ */ jsxRuntime.jsx(Heading, { id: titleId, className: cx.title, children: m["payment.title"] }),
1758
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: cx.list, children: items.map((p, i) => /* @__PURE__ */ jsxRuntime.jsxs("li", { className: cx.item, "data-sf-payment": true, "data-sf-payment-status": typeof p.status === "string" ? p.status : "unknown", children: [
1759
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: p.method_label }),
1760
+ moneyText(p.amount, locale) ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1761
+ " \xB7 ",
1762
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: moneyText(p.amount, locale) })
1763
+ ] }) : null,
1764
+ " \xB7",
1765
+ " ",
1766
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: cx.status, "data-sf-tone": p.status === "failed" ? "problem" : p.status === "paid" ? "done" : "current", children: enumText(m, "payment.status", p.status) }),
1767
+ p.paid_at ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: cx.meta, children: [
1768
+ " \xB7 ",
1769
+ /* @__PURE__ */ jsxRuntime.jsx(Time, { value: p.paid_at, text: fill(m["payment.paidOn"], { date: date(p.paid_at) ?? "" }) })
1770
+ ] }) : null
1771
+ ] }, `${p.method_label}-${i}`)) })
1772
+ ] });
1773
+ }
1774
+ function useClient(client) {
1775
+ const ctx = useOptionalStorefront();
1776
+ return client ?? ctx?.client ?? null;
1777
+ }
1778
+ var asError = (e) => e instanceof Error ? e : new Error("Request failed");
1779
+ var ids = /* @__PURE__ */ new WeakMap();
1780
+ var seq = 0;
1781
+ function clientKey(c) {
1782
+ if (!c) return "none";
1783
+ let k = ids.get(c);
1784
+ if (!k) ids.set(c, k = `c${++seq}`);
1785
+ return k;
1786
+ }
1787
+ function useConnection(fetchPage, client, initial, key) {
1788
+ const owner = `${clientKey(client)}|${key}`;
1789
+ const empty = (status) => ({ status, nodes: [], error: null, cursor: null, hasMore: false, total: null, owner });
1790
+ const [state, setState] = react.useState(
1791
+ () => initial ? { status: "ready", nodes: initial.nodes ?? [], error: null, cursor: initial.page_info?.end_cursor ?? null, hasMore: !!initial.page_info?.has_next_page, total: initial.total_count ?? null, owner } : empty("loading")
1792
+ );
1793
+ const [loadingMore, setLoadingMore] = react.useState(false);
1794
+ const alive = react.useRef(null);
1795
+ const more = react.useRef(null);
1796
+ const fetchRef = react.useRef(fetchPage);
1797
+ fetchRef.current = fetchPage;
1798
+ const first = react.useCallback(() => {
1799
+ alive.current?.abort();
1800
+ more.current?.abort();
1801
+ setLoadingMore(false);
1802
+ if (!client) {
1803
+ setState(empty("loading"));
1804
+ return;
1805
+ }
1806
+ const ctl = new AbortController();
1807
+ alive.current = ctl;
1808
+ setState((s) => s.owner === owner && s.nodes.length ? { ...s, error: null } : empty("loading"));
1809
+ fetchRef.current(client, null, ctl.signal).then(
1810
+ (page) => !ctl.signal.aborted && setState({ status: "ready", nodes: page.nodes ?? [], error: null, cursor: page.page_info?.end_cursor ?? null, hasMore: !!page.page_info?.has_next_page, total: page.total_count ?? null, owner }),
1811
+ (e) => !ctl.signal.aborted && setState((s) => s.owner === owner ? { ...s, status: "error", error: asError(e) } : { ...empty("error"), error: asError(e) })
1812
+ );
1813
+ }, [client, owner]);
1814
+ react.useEffect(() => {
1815
+ if (!(initial && state.owner === owner)) first();
1816
+ return () => {
1817
+ alive.current?.abort();
1818
+ more.current?.abort();
1819
+ };
1820
+ }, [first, owner]);
1821
+ const loadMore = react.useCallback(() => {
1822
+ if (!client || state.owner !== owner || !state.hasMore || loadingMore) return;
1823
+ const ctl = new AbortController();
1824
+ more.current = ctl;
1825
+ setLoadingMore(true);
1826
+ fetchRef.current(client, state.cursor, ctl.signal).then(
1827
+ (page) => {
1828
+ if (ctl.signal.aborted) return;
1829
+ setLoadingMore(false);
1830
+ setState((s) => s.owner !== owner ? s : { ...s, nodes: [...s.nodes, ...page.nodes ?? []], cursor: page.page_info?.end_cursor ?? null, hasMore: !!page.page_info?.has_next_page, total: page.total_count ?? s.total, error: null });
1831
+ },
1832
+ (e) => {
1833
+ if (ctl.signal.aborted) return;
1834
+ setLoadingMore(false);
1835
+ setState((s) => s.owner !== owner ? s : { ...s, error: asError(e) });
1836
+ }
1837
+ );
1838
+ }, [client, owner, state.owner, state.hasMore, state.cursor, loadingMore]);
1839
+ const view = state.owner === owner ? state : empty("loading");
1840
+ return { status: view.status, nodes: view.nodes, error: view.error, hasMore: view.hasMore, loadingMore: state.owner === owner && loadingMore, totalCount: view.total, reload: first, loadMore };
1841
+ }
1842
+ function useCustomerOrders({ client, first = 20, initial } = {}) {
1843
+ return useConnection((c, after, signal) => c.customer.orders({ first, ...after ? { after } : {} }, { signal }), useClient(client), initial, `orders:${first}`);
1844
+ }
1845
+ function usePendingPayments({ client, first = 20, initial } = {}) {
1846
+ return useConnection((c, after, signal) => c.customer.pendingPayments({ first, ...after ? { after } : {} }, { signal }), useClient(client), initial, `pending:${first}`);
1847
+ }
1848
+ function useCustomerOrder(id, { client, initial, poll } = {}) {
1849
+ const c = useClient(client);
1850
+ const given = initial !== void 0;
1851
+ const owner = `${clientKey(c)}|${id ?? ""}`;
1852
+ const [state, setState] = react.useState(() => given ? { status: initial ? "ready" : "not_found", order: initial, error: null, owner } : { status: "loading", order: null, error: null, owner });
1853
+ const [refreshing, setRefreshing] = react.useState(false);
1854
+ const ctlRef = react.useRef(null);
1855
+ const initialOwner = react.useRef(given ? owner : null);
1856
+ const load = react.useCallback(
1857
+ (silent) => {
1858
+ ctlRef.current?.abort();
1859
+ setRefreshing(false);
1860
+ if (!c || !id) {
1861
+ setState({ status: "loading", order: null, error: null, owner });
1862
+ return;
1863
+ }
1864
+ const ctl = new AbortController();
1865
+ ctlRef.current = ctl;
1866
+ if (silent) setRefreshing(true);
1867
+ else setState((s) => s.owner === owner && s.order ? { ...s, error: null } : { status: "loading", order: null, error: null, owner });
1868
+ c.customer.order(id, { signal: ctl.signal }).then(
1869
+ (o) => {
1870
+ if (ctl.signal.aborted) return;
1871
+ setRefreshing(false);
1872
+ setState(o ? { status: "ready", order: o, error: null, owner } : { status: "not_found", order: null, error: null, owner });
1873
+ },
1874
+ (e) => {
1875
+ if (ctl.signal.aborted) return;
1876
+ setRefreshing(false);
1877
+ setState((s) => s.owner === owner && s.order ? { ...s, error: asError(e) } : { status: "error", order: null, error: asError(e), owner });
1878
+ }
1879
+ );
1880
+ },
1881
+ [c, id, owner]
1882
+ );
1883
+ react.useEffect(() => {
1884
+ if (initialOwner.current !== owner) load(false);
1885
+ initialOwner.current = null;
1886
+ return () => ctlRef.current?.abort();
1887
+ }, [load, owner]);
1888
+ const mine = state.owner === owner;
1889
+ const order = mine ? state.order : null;
1890
+ const keepPolling = !!poll && !!order && poll.while(order);
1891
+ const everyMs = poll?.everyMs ?? 1e4;
1892
+ const forMs = poll?.forMs ?? 6e4;
1893
+ react.useEffect(() => {
1894
+ if (!keepPolling) return;
1895
+ const t0 = Date.now();
1896
+ const timer = setInterval(() => {
1897
+ if (Date.now() - t0 >= forMs) clearInterval(timer);
1898
+ else load(true);
1899
+ }, everyMs);
1900
+ return () => clearInterval(timer);
1901
+ }, [keepPolling, everyMs, forMs, load]);
1902
+ const hasOrder = order !== null;
1903
+ const reload = react.useCallback(() => load(hasOrder), [load, hasOrder]);
1904
+ return { status: mine ? state.status : "loading", order, error: mine ? state.error : null, refreshing: mine && refreshing, reload };
1905
+ }
1906
+
1907
+ // src/account/index.ts
1908
+ init_voucher();
430
1909
 
431
1910
  exports.AccountAuth = AccountAuth;
1911
+ exports.Barcode = Barcode;
1912
+ exports.InvoiceList = InvoiceList;
1913
+ exports.NextActionBar = NextActionBar;
1914
+ exports.OrderCard = OrderCard;
1915
+ exports.OrderList = OrderList;
1916
+ exports.OrderProgress = OrderProgress;
1917
+ exports.OrderStatusBadge = OrderStatusBadge;
1918
+ exports.PaymentSummary = PaymentSummary;
1919
+ exports.PendingPaymentCard = PendingPaymentCard;
1920
+ exports.PendingPaymentList = PendingPaymentList;
1921
+ exports.PostPurchaseAccountPrompt = PostPurchaseAccountPrompt;
1922
+ exports.RefundList = RefundList;
1923
+ exports.ShipmentCard = ShipmentCard;
432
1924
  exports.accountAuthMessages = accountAuthMessages;
1925
+ exports.accountMessages = accountMessages;
1926
+ exports.barcodeGeometry = barcodeGeometry;
1927
+ exports.barcodeValue = barcodeValue;
1928
+ exports.code128Modules = code128Modules;
1929
+ exports.enumText = enumText;
1930
+ exports.postPurchaseAccountPromptMessages = postPurchaseAccountPromptMessages;
1931
+ exports.stageTone = stageTone;
1932
+ exports.useCustomerOrder = useCustomerOrder;
1933
+ exports.useCustomerOrders = useCustomerOrders;
1934
+ exports.usePendingPayments = usePendingPayments;
1935
+ exports.voucherOf = voucherOf;
433
1936
  //# sourceMappingURL=account.cjs.map
434
1937
  //# sourceMappingURL=account.cjs.map