@asteby/storefront-react 0.8.0 → 0.9.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/payments.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { isSafeCssValue } from './chunk-672OTUM2.js';
2
+ export { buildPayChoices, cashProviderData, checkoutToAttempt, choiceValue, parseChoice, payErrorResponse, paymentCsp, paymentCspHeaderName, paymentCspHeaders, paymentCspMode, paymentNonce, paymentNonceFromHeaders, voucherRows } from './chunk-ISEOCKIR.js';
2
3
  import { useResolvedLocale, useModalDialog } from './chunk-2WZIWIBW.js';
3
4
  import './chunk-DQBL2DFJ.js';
4
- import { forwardRef, useImperativeHandle, useRef, useEffect, useMemo, useId, useState, useCallback } from 'react';
5
+ import { forwardRef, useImperativeHandle, useRef, useEffect, useMemo, useId, useState, useCallback, useSyncExternalStore } from 'react';
5
6
  import { paymentMessages, formatMoney, generateIdempotencyKey, paymentOutcome, paymentErrorView, formatVoucherExpiry } from '@asteby/storefront';
6
7
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
8
 
@@ -636,45 +637,299 @@ function createFetchTransport(url, options = {}) {
636
637
  };
637
638
  }
638
639
 
639
- // src/payments/csp.ts
640
- var ORIGIN = /^https:\/\/(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/i;
641
- function origins(...lists) {
642
- const out = /* @__PURE__ */ new Set();
643
- for (const list of lists) for (const o of list ?? []) if (ORIGIN.test(o)) out.add(o);
644
- return [...out];
640
+ // src/payments/payment-method.messages.ts
641
+ var ES = {
642
+ legend: "M\xE9todo de pago",
643
+ pay: "Pagar",
644
+ placeOrder: "Realizar el pedido",
645
+ payRedirect: "Continuar al pago",
646
+ continue: "Continuar",
647
+ retryAddress: "Guardar direcci\xF3n y continuar",
648
+ processing: "Procesando\u2026",
649
+ redirectNote: "Te llevamos a la p\xE1gina del proveedor para terminar el pago y regresas aqu\xED.",
650
+ cashPoints: "Elige d\xF3nde pagar en efectivo",
651
+ cashMore: "Ver m\xE1s puntos de pago",
652
+ cashNote: "Al hacer el pedido te damos una ficha con la referencia y la fecha l\xEDmite. El pedido se confirma cuando pagas.",
653
+ secureCard: "Tus datos de tarjeta los captura directamente nuestro proveedor de pagos; la tienda nunca los ve.",
654
+ pickDeliveryFirst: "Elige primero la entrega para ver el total y pagar con tarjeta.",
655
+ updatingTotal: "Actualizando el total\u2026",
656
+ syncFailed: "No pudimos actualizar el total con tu entrega. Puedes continuar al sitio del proveedor para pagar con tarjeta.",
657
+ rebuildCart: "Volver a armar mi carrito",
658
+ noPaymentTitle: "Por ahora no hay formas de pago disponibles",
659
+ noPayment: "Intenta de nuevo en unos minutos o escr\xEDbenos para completar tu pedido.",
660
+ paymentNote: "El pago se procesa de forma segura con nuestro proveedor de pagos.",
661
+ options: {
662
+ card: "Tarjeta de cr\xE9dito o d\xE9bito",
663
+ cash: "Efectivo",
664
+ wallet: "Cuenta del proveedor de pagos",
665
+ credits: "Pagos sin tarjeta"
666
+ }
667
+ };
668
+ var EN = {
669
+ legend: "Payment method",
670
+ pay: "Pay",
671
+ placeOrder: "Place order",
672
+ payRedirect: "Continue to payment",
673
+ continue: "Continue",
674
+ retryAddress: "Save address and continue",
675
+ processing: "Processing\u2026",
676
+ redirectNote: "We'll take you to the provider's page to finish paying, then bring you back here.",
677
+ cashPoints: "Choose where to pay in cash",
678
+ cashMore: "Show more payment points",
679
+ cashNote: "When you place the order you get a slip with the reference and the deadline. The order is confirmed once you pay.",
680
+ secureCard: "Your card details are captured directly by our payment provider; the shop never sees them.",
681
+ pickDeliveryFirst: "Choose delivery first to see the total and pay by card.",
682
+ updatingTotal: "Updating the total\u2026",
683
+ syncFailed: "We couldn't update the total with your delivery. You can continue to the provider's site to pay by card.",
684
+ rebuildCart: "Rebuild my cart",
685
+ noPaymentTitle: "No payment methods are available right now",
686
+ noPayment: "Try again in a few minutes or contact us to complete your order.",
687
+ paymentNote: "Payment is processed securely by our payment provider.",
688
+ options: {
689
+ card: "Credit or debit card",
690
+ cash: "Cash",
691
+ wallet: "Payment provider account",
692
+ credits: "Pay without a card"
693
+ }
694
+ };
695
+ function paymentMethodMessages(locale, overrides) {
696
+ const base = (locale ?? "es-MX").toLowerCase().startsWith("en") ? EN : ES;
697
+ if (!overrides) return base;
698
+ const { options, ...rest } = overrides;
699
+ return { ...base, ...rest, options: { ...base.options, ...options } };
645
700
  }
646
- function paymentCsp(clients, options = {}) {
647
- const list = clients.filter((c) => !!c);
648
- const pick = (k) => list.map((c) => c.csp?.[k]);
649
- const nonce = options.nonce && /^[A-Za-z0-9+/=_-]+$/.test(options.nonce) ? options.nonce : void 0;
650
- const sdkOrigins = list.flatMap((c) => {
651
- try {
652
- const u = new URL(c.sdk_url);
653
- return u.protocol === "https:" ? [u.origin] : [];
654
- } catch {
655
- return [];
701
+ var PAYMENT_CHOICE_FIELD = "payment_choice";
702
+ var CASH_POINT_FIELD = "cash_point";
703
+ function formFields(form) {
704
+ const out = {};
705
+ if (!form) return out;
706
+ for (const [k, v] of new FormData(form).entries()) if (typeof v === "string") out[k] = v;
707
+ return out;
708
+ }
709
+ var useHydrated = () => useSyncExternalStore(
710
+ () => () => {
711
+ },
712
+ () => true,
713
+ () => false
714
+ );
715
+ function PaymentMethodSection(props) {
716
+ const {
717
+ choices,
718
+ amount,
719
+ scope,
720
+ formRef,
721
+ payUrl,
722
+ statusUrl,
723
+ delivery = "",
724
+ deliveryReady = true,
725
+ syncDelivery,
726
+ addressFirst = false,
727
+ retryAddress = false,
728
+ blocked = false,
729
+ busy = false,
730
+ invalid,
731
+ nonce,
732
+ methodLabel,
733
+ icons,
734
+ renderAmount,
735
+ rebuildHref,
736
+ renderLink,
737
+ onDone,
738
+ onAmountChanged,
739
+ onEvent,
740
+ classNames: cx = {},
741
+ testIds = {},
742
+ hideSubmit,
743
+ brickProps
744
+ } = props;
745
+ const locale = useResolvedLocale(props.locale);
746
+ const m = useMemo(() => paymentMethodMessages(locale, props.messages), [locale, props.messages]);
747
+ const hydrated = useHydrated();
748
+ const [choiceValue2, setChoiceValue] = useState(props.defaultChoice ?? choices.defaultValue);
749
+ const selected = choices.choices.find((c) => c.value === choiceValue2) ?? null;
750
+ const noPayment = choices.choices.length === 0;
751
+ const tid = (k) => testIds[k] ? { "data-testid": testIds[k] } : {};
752
+ const [fallback, setFallback] = useState(false);
753
+ const [ready, setReady] = useState(false);
754
+ const [processing, setProcessing] = useState(false);
755
+ const [expired, setExpired] = useState(false);
756
+ const brick = useRef(null);
757
+ const cardChosen = selected?.mode === "card" && !retryAddress && !addressFirst;
758
+ const cardActive = hydrated && cardChosen && !fallback;
759
+ const wantSync = cardActive && deliveryReady && Boolean(syncDelivery);
760
+ const [sync, setSync] = useState(null);
761
+ const syncRef = useRef(syncDelivery);
762
+ syncRef.current = syncDelivery;
763
+ useEffect(() => {
764
+ if (!wantSync || !syncRef.current) return;
765
+ if (sync?.key === delivery && sync.ok) return;
766
+ let cancelled = false;
767
+ syncRef.current(delivery).then(
768
+ (ok) => !cancelled && setSync({ key: delivery, ok }),
769
+ () => !cancelled && setSync({ key: delivery, ok: false })
770
+ );
771
+ return () => {
772
+ cancelled = true;
773
+ };
774
+ }, [wantSync, delivery]);
775
+ const settled = sync?.key === delivery;
776
+ const synced = !syncDelivery || settled && sync.ok;
777
+ const syncFailed = wantSync && settled && !sync.ok;
778
+ const brickReady = cardActive && deliveryReady && synced && !syncFailed;
779
+ const transport = useMemo(
780
+ () => props.transport ?? createFetchTransport(payUrl, {
781
+ ...statusUrl ? { refreshUrl: statusUrl } : {},
782
+ buildBody: (request) => ({ ...request, fields: formFields(formRef.current) })
783
+ }),
784
+ [props.transport, payUrl, statusUrl, formRef]
785
+ );
786
+ const handleEvent = (e) => {
787
+ if (e.type === "form_ready") setReady(true);
788
+ if (e.type === "submit") setProcessing(true);
789
+ if (e.type === "tokenize_error" || e.type === "retry") setProcessing(e.type === "retry");
790
+ if (e.type === "result" && e.status === "rejected") setProcessing(false);
791
+ if (e.type === "error") {
792
+ setProcessing(false);
793
+ if (e.kind === "price_mismatch") onAmountChanged?.();
794
+ if (e.kind === "expired") setExpired(true);
656
795
  }
657
- });
658
- const dir = (name, values) => `${name} ${values.join(" ")}`;
659
- const parts = [
660
- "default-src 'self'",
661
- dir("script-src", ["'self'", ...nonce ? [`'nonce-${nonce}'`] : [], ...origins(sdkOrigins, ...pick("script"), options.extra?.script)]),
662
- dir("frame-src", origins(...pick("frame"), options.extra?.frame).length ? origins(...pick("frame"), options.extra?.frame) : ["'none'"]),
663
- dir("connect-src", ["'self'", ...origins(...pick("connect"), options.extra?.connect)]),
664
- dir("img-src", ["'self'", "data:", ...origins(...pick("img"), options.extra?.img)]),
665
- "style-src 'self' 'unsafe-inline'",
666
- dir("form-action", ["'self'", ...origins(...pick("form"), options.extra?.form)]),
667
- "frame-ancestors 'none'",
668
- "base-uri 'self'",
669
- "object-src 'none'"
670
- ];
671
- if (options.reportUri && /^(https:\/\/|\/)[^\s;,]+$/.test(options.reportUri)) parts.push(`report-uri ${options.reportUri}`);
672
- return parts.join("; ");
796
+ onEvent?.(e);
797
+ };
798
+ const total = renderAmount ? renderAmount(amount) : formatMoney(amount, locale);
799
+ const label = retryAddress ? m.retryAddress : addressFirst ? m.continue : selected?.mode === "plain" || !selected ? /* @__PURE__ */ jsxs(Fragment, { children: [
800
+ m.pay,
801
+ " ",
802
+ total
803
+ ] }) : selected.mode === "redirect" || selected.mode === "card" && (fallback || syncFailed) ? m.payRedirect : /* @__PURE__ */ jsxs(Fragment, { children: [
804
+ m.placeOrder,
805
+ " ",
806
+ total
807
+ ] });
808
+ function onPayClick(event) {
809
+ if (!cardActive || syncFailed) return;
810
+ event.preventDefault();
811
+ const form = formRef.current;
812
+ if (form && !form.reportValidity()) return;
813
+ if (brickReady) void brick.current?.submit();
814
+ }
815
+ const cardNotice = (k, node) => k === "syncFailed" ? /* @__PURE__ */ jsx("p", { role: "alert", className: cx.alert, "data-sf-pay-notice": "sync-failed", ...tid("syncFailed"), children: node }) : /* @__PURE__ */ jsx("p", { role: "status", className: cx.status, "data-sf-pay-notice": k, ...k === "syncing" ? tid("syncing") : {}, children: node });
816
+ const Link = renderLink ?? (({ href, className, children, testId }) => /* @__PURE__ */ jsx("a", { href, className, ...testId ? { "data-testid": testId } : {}, children }));
817
+ return /* @__PURE__ */ jsxs("fieldset", { id: "pago", className: cx.root, "data-sf-pay-method": true, children: [
818
+ /* @__PURE__ */ jsx("legend", { className: cx.legend, children: m.legend }),
819
+ choices.choices.map((choice) => {
820
+ const { label: rowLabel, hint } = rowText(choice, m, methodLabel);
821
+ const checked = choice.value === choiceValue2;
822
+ const icon = icons?.[choice.option ?? "plain"];
823
+ return /* @__PURE__ */ jsxs("div", { className: cx.choice, "data-sf-pay-choice": true, children: [
824
+ /* @__PURE__ */ jsxs("label", { className: cx.radioLabel, children: [
825
+ /* @__PURE__ */ jsx(
826
+ "input",
827
+ {
828
+ type: "radio",
829
+ name: PAYMENT_CHOICE_FIELD,
830
+ value: choice.value,
831
+ checked,
832
+ onChange: () => setChoiceValue(choice.value),
833
+ "aria-invalid": invalid?.has("payment_method") || void 0,
834
+ "data-mode": choice.mode,
835
+ required: true,
836
+ className: cx.radio,
837
+ ...tid("method")
838
+ }
839
+ ),
840
+ icon ? /* @__PURE__ */ jsx("span", { className: cx.icon, "aria-hidden": "true", children: icon }) : null,
841
+ /* @__PURE__ */ jsxs("span", { className: cx.labelText, children: [
842
+ rowLabel,
843
+ hint ? /* @__PURE__ */ jsxs("span", { className: cx.hint, children: [
844
+ " ",
845
+ hint
846
+ ] }) : null
847
+ ] })
848
+ ] }),
849
+ /* @__PURE__ */ jsx(ChoicePanel, { choice, m, invalid, cx, tid, hidden: hydrated && !checked })
850
+ ] }, choice.value);
851
+ }),
852
+ noPayment ? /* @__PURE__ */ jsxs("div", { role: "alert", className: cx.alert, "data-sf-pay-notice": "no-payment", ...tid("noPayment"), children: [
853
+ /* @__PURE__ */ jsx("p", { children: /* @__PURE__ */ jsx("strong", { children: m.noPaymentTitle }) }),
854
+ /* @__PURE__ */ jsx("p", { children: m.noPayment })
855
+ ] }) : null,
856
+ cardChosen && hydrated && choices.cardClient ? /* @__PURE__ */ jsxs("div", { className: cx.brickWrap, "data-sf-pay-card": true, ...tid("card"), children: [
857
+ fallback ? null : !deliveryReady ? cardNotice("pickDelivery", m.pickDeliveryFirst) : syncFailed ? cardNotice("syncFailed", m.syncFailed) : !synced ? cardNotice("syncing", m.updatingTotal) : null,
858
+ brickReady || fallback ? /* @__PURE__ */ jsx(
859
+ PaymentBrick,
860
+ {
861
+ ...brickProps,
862
+ ref: brick,
863
+ client: choices.cardClient,
864
+ amount,
865
+ transport,
866
+ ...nonce ? { nonce } : {},
867
+ locale,
868
+ ...scope ? { scope } : {},
869
+ enabled: brickReady,
870
+ ...cx.brick ? { className: cx.brick } : {},
871
+ onEvent: handleEvent,
872
+ onFallback: () => setFallback(true),
873
+ onResult: (o) => {
874
+ if (o.kind === "approved" || o.kind === "in_review" || o.kind === "voucher") onDone(o);
875
+ }
876
+ }
877
+ ) : null,
878
+ /* @__PURE__ */ jsx("p", { className: cx.note, children: m.secureCard }),
879
+ expired && rebuildHref ? Link({ href: rebuildHref, ...cx.rebuild ? { className: cx.rebuild } : {}, children: m.rebuildCart, ...testIds.rebuild ? { testId: testIds.rebuild } : {} }) : null
880
+ ] }) : null,
881
+ noPayment || choices.choices.some((c) => c.option) ? null : /* @__PURE__ */ jsx("p", { className: cx.note, children: m.paymentNote }),
882
+ hideSubmit ? null : /* @__PURE__ */ jsx(
883
+ "button",
884
+ {
885
+ type: "submit",
886
+ onClick: onPayClick,
887
+ className: cx.submit,
888
+ disabled: busy || blocked,
889
+ "aria-disabled": blocked || brickReady && (!ready || processing) || void 0,
890
+ "aria-busy": processing || void 0,
891
+ "data-sf-pay-method-submit": true,
892
+ ...tid("submit"),
893
+ children: busy || processing ? m.processing : label
894
+ }
895
+ )
896
+ ] });
673
897
  }
674
- function paymentCspHeaderName(reportOnly) {
675
- return reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
898
+ function rowText(choice, m, methodLabel) {
899
+ if (choice.mode === "plain") return methodLabel ? methodLabel(choice.methodKey) : { label: choice.methodKey };
900
+ return { label: choice.label ?? (choice.option ? m.options[choice.option] : void 0) ?? choice.option ?? choice.methodKey };
901
+ }
902
+ function ChoicePanel({
903
+ choice,
904
+ m,
905
+ invalid,
906
+ cx,
907
+ tid,
908
+ hidden
909
+ }) {
910
+ if (choice.mode === "redirect") {
911
+ return /* @__PURE__ */ jsx("p", { className: cx.panel, hidden, "data-sf-pay-panel": "redirect", ...tid("redirectNote"), children: m.redirectNote });
912
+ }
913
+ if (choice.mode !== "cash") return null;
914
+ const main = choice.points.filter((p) => p.group === "main");
915
+ const more = choice.points.filter((p) => p.group !== "main");
916
+ const row = (p, i, first) => /* @__PURE__ */ jsxs("label", { className: cx.cashPoint, "data-sf-pay-point": true, children: [
917
+ /* @__PURE__ */ jsx("input", { type: "radio", name: CASH_POINT_FIELD, value: p.id, defaultChecked: first && i === 0, className: cx.cashPointInput, "aria-invalid": invalid?.has("cash_point") || void 0 }),
918
+ /* @__PURE__ */ jsx("span", { children: p.label })
919
+ ] }, p.id);
920
+ return /* @__PURE__ */ jsxs("div", { className: cx.panel, hidden, "data-sf-pay-panel": "cash", ...tid("cash"), children: [
921
+ /* @__PURE__ */ jsxs("fieldset", { children: [
922
+ /* @__PURE__ */ jsx("legend", { children: m.cashPoints }),
923
+ /* @__PURE__ */ jsx("div", { "data-sf-pay-points": true, children: main.map((p, i) => row(p, i, true)) }),
924
+ more.length ? /* @__PURE__ */ jsxs("details", { children: [
925
+ /* @__PURE__ */ jsx("summary", { className: cx.cashMore, style: { minHeight: 44 }, children: m.cashMore }),
926
+ /* @__PURE__ */ jsx("div", { "data-sf-pay-points": true, children: more.map((p, i) => row(p, i, false)) })
927
+ ] }) : null
928
+ ] }),
929
+ /* @__PURE__ */ jsx("p", { className: cx.note, children: m.cashNote })
930
+ ] });
676
931
  }
677
932
 
678
- export { MERCADOPAGO_BRICKS_KIND, PAYMENT_THEME_TOKENS, PaymentBrick, PaymentChallenge, PaymentHttpError, VoucherCard, createFetchTransport, loadPaymentSdk, mercadoPagoBricksAdapter, paymentCsp, paymentCspHeaderName, readPaymentTheme, resetPaymentSdkCache, sanitizeMercadoPagoFormData, useEmbeddedPayment };
933
+ export { CASH_POINT_FIELD, MERCADOPAGO_BRICKS_KIND, PAYMENT_CHOICE_FIELD, PAYMENT_THEME_TOKENS, PaymentBrick, PaymentChallenge, PaymentHttpError, PaymentMethodSection, VoucherCard, createFetchTransport, formFields, loadPaymentSdk, mercadoPagoBricksAdapter, paymentMethodMessages, readPaymentTheme, resetPaymentSdkCache, sanitizeMercadoPagoFormData, useEmbeddedPayment };
679
934
  //# sourceMappingURL=payments.js.map
680
935
  //# sourceMappingURL=payments.js.map