@superlogic/spree-pay 0.4.12 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,9 +8,85 @@ var PaymentType = /* @__PURE__ */ ((PaymentType2) => {
8
8
  PaymentType2["POINTS"] = "POINTS";
9
9
  return PaymentType2;
10
10
  })(PaymentType || {});
11
+ var PaymentStatus = /* @__PURE__ */ ((PaymentStatus2) => {
12
+ PaymentStatus2["NOT_INITIALIZED"] = "NOT_INITIALIZED";
13
+ PaymentStatus2["PENDING"] = "PENDING";
14
+ PaymentStatus2["AUTHORIZED"] = "AUTHORIZED";
15
+ PaymentStatus2["FAILED"] = "FAILED";
16
+ PaymentStatus2["CAPTURED"] = "CAPTURED";
17
+ PaymentStatus2["VOIDED"] = "VOIDED";
18
+ PaymentStatus2["CAPTURE_FAILED"] = "CAPTURE_FAILED";
19
+ return PaymentStatus2;
20
+ })(PaymentStatus || {});
21
+
22
+ // src/types/errors.ts
23
+ var SpreePayHttpError = class extends Error {
24
+ constructor(status, body, url) {
25
+ const snippet = body.length > 200 ? `${body.slice(0, 200)}\u2026` : body;
26
+ super(snippet || `Request failed: ${status}`);
27
+ this.status = status;
28
+ this.body = body;
29
+ this.url = url;
30
+ this.name = "SpreePayHttpError";
31
+ }
32
+ status;
33
+ body;
34
+ url;
35
+ };
36
+ var PaymentErrorCode = /* @__PURE__ */ ((PaymentErrorCode2) => {
37
+ PaymentErrorCode2["CARD_ERROR"] = "CARD_ERROR";
38
+ PaymentErrorCode2["PAYMENT_ERROR"] = "PAYMENT_ERROR";
39
+ return PaymentErrorCode2;
40
+ })(PaymentErrorCode || {});
41
+ var PaymentError = class extends Error {
42
+ status;
43
+ code;
44
+ /**
45
+ * Optional stable code from the backend (e.g. `INSUFFICIENT_FUNDS`) for branching
46
+ * on specific cases without changing the `code` enum. Safe to expose (an
47
+ * identifier, not free-text); absent until the backend supplies one.
48
+ */
49
+ backendCode;
50
+ constructor(message, status, options) {
51
+ super(message, { cause: options?.cause });
52
+ this.name = "PaymentError";
53
+ this.status = status;
54
+ this.code = options?.code ?? "PAYMENT_ERROR" /* PAYMENT_ERROR */;
55
+ this.backendCode = options?.backendCode;
56
+ }
57
+ };
58
+ var isPaymentError = (e) => e instanceof PaymentError;
59
+ var isDeclineStatus = (status) => status === "FAILED" /* FAILED */ || status === "CAPTURE_FAILED" /* CAPTURE_FAILED */;
60
+ var isSuccessStatus = (status) => status === "AUTHORIZED" /* AUTHORIZED */ || status === "CAPTURED" /* CAPTURED */;
61
+ var isProcessorRejection = (e) => e instanceof SpreePayHttpError && e.status >= 400 && e.status < 500 && e.status !== 401 && e.status !== 403 && e.status !== 404;
62
+ var backendCodeFromBody = (e) => {
63
+ try {
64
+ const parsed = JSON.parse(e.body);
65
+ const code = parsed?.code ?? parsed?.errorCode;
66
+ if (typeof code === "string" && code.trim()) return code;
67
+ } catch {
68
+ }
69
+ return void 0;
70
+ };
71
+ var toPaymentError = (e, fallbackMessage = "Payment failed", declineCode = "PAYMENT_ERROR" /* PAYMENT_ERROR */) => {
72
+ if (e instanceof PaymentError) return e;
73
+ return new PaymentError(fallbackMessage, "FAILED" /* FAILED */, {
74
+ code: isProcessorRejection(e) ? declineCode : "PAYMENT_ERROR" /* PAYMENT_ERROR */,
75
+ backendCode: e instanceof SpreePayHttpError ? backendCodeFromBody(e) : void 0,
76
+ cause: e
77
+ });
78
+ };
79
+ var settlePaymentResult = (res, fallbackMessage, failureCode = "PAYMENT_ERROR" /* PAYMENT_ERROR */) => {
80
+ if (isSuccessStatus(res.status)) {
81
+ return res;
82
+ }
83
+ throw new PaymentError(fallbackMessage, res.status, {
84
+ code: isDeclineStatus(res.status) ? failureCode : "PAYMENT_ERROR" /* PAYMENT_ERROR */
85
+ });
86
+ };
11
87
 
12
88
  // package.json
13
- var version = "0.4.12";
89
+ var version = "0.5.1";
14
90
 
15
91
  // src/utils/logger.ts
16
92
  var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
@@ -128,20 +204,6 @@ var configureLogger = (config2) => {
128
204
 
129
205
  // src/context/SpreePayActionsContext.tsx
130
206
  import { createContext, useCallback, useContext, useRef, useState } from "react";
131
-
132
- // src/types/errors.ts
133
- var PaymentError = class extends Error {
134
- status;
135
- details;
136
- constructor(message, status, details) {
137
- super(message);
138
- this.name = "PaymentError";
139
- this.status = status;
140
- this.details = details;
141
- }
142
- };
143
-
144
- // src/context/SpreePayActionsContext.tsx
145
207
  import { jsx } from "react/jsx-runtime";
146
208
  var processLogger = logger.child("process");
147
209
  var SpreePayActionsContext = createContext(void 0);
@@ -168,12 +230,11 @@ var SpreePayProvider = ({ children, env }) => {
168
230
  hash: data.hash,
169
231
  paymentType: selectedPaymentMethod.type
170
232
  });
171
- throw new PaymentError("Payment already in progress", "FAILED" /* FAILED */);
233
+ throw new Error("Payment already in progress");
172
234
  }
173
235
  processLogger.info("Payment process started", {
174
236
  hash: data.hash,
175
237
  capture: data.capture,
176
- hasMetadata: Boolean(data.metadata),
177
238
  paymentType: selectedPaymentMethod.type
178
239
  });
179
240
  inFlightRef.current = true;
@@ -193,8 +254,7 @@ var SpreePayProvider = ({ children, env }) => {
193
254
  paymentType: selectedPaymentMethod.type,
194
255
  errorMessage: e instanceof Error ? e.message : String(e)
195
256
  });
196
- if (e instanceof Error) throw e;
197
- throw new PaymentError("Payment failed", "FAILED" /* FAILED */, e);
257
+ throw toPaymentError(e);
198
258
  } finally {
199
259
  inFlightRef.current = false;
200
260
  setInternalProcessing(false);
@@ -389,6 +449,27 @@ var buildUrl = (key) => {
389
449
  const qs = usp.toString();
390
450
  return cfg.baseUrl + url + (qs ? `?${qs}` : "");
391
451
  };
452
+ var parseResponse = async (res) => {
453
+ if (!res.ok) {
454
+ const text = await res.text().catch(() => "");
455
+ throw new SpreePayHttpError(res.status, text, res.url);
456
+ }
457
+ const contentType = res.headers.get("content-type") || "";
458
+ if (!contentType.includes("application/json")) {
459
+ return await res.text();
460
+ }
461
+ return await res.json();
462
+ };
463
+ var publicGet = async (baseUrl, tenantId, path) => {
464
+ const res = await fetch(`${baseUrl}${path}`, {
465
+ headers: {
466
+ Accept: "application/json",
467
+ ["X-Tenant-ID"]: tenantId
468
+ },
469
+ cache: "no-store"
470
+ });
471
+ return parseResponse(res);
472
+ };
392
473
  var request = async (method, url, body) => {
393
474
  if (!cfg.accessToken) throw new Error("Missing SLAPI accessToken. Call registerApi(...) first.");
394
475
  if (!cfg.tenantId) throw new Error("Missing SLAPI tenantId. Call registerApi(...) first.");
@@ -414,15 +495,7 @@ var request = async (method, url, body) => {
414
495
  body: payload,
415
496
  cache: "no-store"
416
497
  });
417
- if (!res.ok) {
418
- const text = await res.text().catch(() => "");
419
- throw new Error(text || `Request failed: ${res.status}`);
420
- }
421
- const contentType = res.headers.get("content-type") || "";
422
- if (!contentType.includes("application/json")) {
423
- return await res.text();
424
- }
425
- return await res.json();
498
+ return parseResponse(res);
426
499
  };
427
500
  var slapiApi = {
428
501
  get: async () => {
@@ -474,14 +547,26 @@ var registerApi = (config2) => {
474
547
  import useSWR from "swr";
475
548
  var URL = "/v1/tenants/configs/spree-pay";
476
549
  var useSpreePayConfig = () => {
477
- const { origin } = useSpreePayEnv();
478
- const { data, isLoading } = useSWR(origin ? `${URL}?origin=${origin}` : URL);
550
+ const { origin, tenantId } = useSpreePayEnv();
551
+ const { staticConfig } = useStaticConfig();
552
+ const key = origin ? `${URL}?origin=${origin}` : URL;
553
+ const { data, isLoading } = useSWR(
554
+ key,
555
+ (path) => publicGet(staticConfig.slapiUrl, tenantId, path)
556
+ );
479
557
  return { spreePayConfig: data ?? null, configIsLoading: isLoading };
480
558
  };
481
559
 
560
+ // src/context/LoginStatusContext.tsx
561
+ import { createContext as createContext3, useContext as useContext3 } from "react";
562
+ import { jsx as jsx3 } from "react/jsx-runtime";
563
+ var LoginStatusContext = createContext3(false);
564
+ var LoginStatusProvider = ({ isLoggedIn, children }) => /* @__PURE__ */ jsx3(LoginStatusContext.Provider, { value: isLoggedIn, children });
565
+ var useIsLoggedIn = () => useContext3(LoginStatusContext);
566
+
482
567
  // src/components/common/InfoBanner.tsx
483
568
  import xss from "xss";
484
- import { jsx as jsx3, jsxs } from "react/jsx-runtime";
569
+ import { jsx as jsx4, jsxs } from "react/jsx-runtime";
485
570
  var InfoBanner = (props) => {
486
571
  const { type = "info", message } = props;
487
572
  if (!message) return null;
@@ -493,14 +578,14 @@ var InfoBanner = (props) => {
493
578
  "bg-(--s-warning)/10": type === "warning"
494
579
  }),
495
580
  children: [
496
- type === "info" && /* @__PURE__ */ jsx3(
581
+ type === "info" && /* @__PURE__ */ jsx4(
497
582
  "svg",
498
583
  {
499
584
  xmlns: "http://www.w3.org/2000/svg",
500
585
  fill: "none",
501
586
  viewBox: "0 0 20 20",
502
587
  className: "size-5 shrink-0 text-(--positive)",
503
- children: /* @__PURE__ */ jsx3(
588
+ children: /* @__PURE__ */ jsx4(
504
589
  "path",
505
590
  {
506
591
  fill: "currentColor",
@@ -509,14 +594,14 @@ var InfoBanner = (props) => {
509
594
  )
510
595
  }
511
596
  ),
512
- type === "warning" && /* @__PURE__ */ jsx3(
597
+ type === "warning" && /* @__PURE__ */ jsx4(
513
598
  "svg",
514
599
  {
515
600
  xmlns: "http://www.w3.org/2000/svg",
516
601
  fill: "none",
517
602
  viewBox: "0 0 20 20",
518
603
  className: "size-5 shrink-0 text-(--warning)",
519
- children: /* @__PURE__ */ jsx3(
604
+ children: /* @__PURE__ */ jsx4(
520
605
  "path",
521
606
  {
522
607
  fill: "currentColor",
@@ -525,7 +610,7 @@ var InfoBanner = (props) => {
525
610
  )
526
611
  }
527
612
  ),
528
- /* @__PURE__ */ jsx3(
613
+ /* @__PURE__ */ jsx4(
529
614
  "p",
530
615
  {
531
616
  className: "break-anywhere text-[14px] leading-5 text-(--primary) [&_a]:underline",
@@ -538,13 +623,13 @@ var InfoBanner = (props) => {
538
623
  };
539
624
 
540
625
  // src/components/common/Legal.tsx
541
- import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
626
+ import { jsx as jsx5, jsxs as jsxs2 } from "react/jsx-runtime";
542
627
  var Legal = () => {
543
628
  const { spreePayConfig } = useSpreePayConfig();
544
629
  return /* @__PURE__ */ jsxs2("p", { className: "text-xs leading-5 font-medium text-(--secondary)", children: [
545
630
  "By clicking on the button below I acknowledge that I have read and accepted the",
546
631
  " ",
547
- /* @__PURE__ */ jsx4(
632
+ /* @__PURE__ */ jsx5(
548
633
  "a",
549
634
  {
550
635
  className: "whitespace-nowrap underline",
@@ -703,17 +788,17 @@ var SlapiPaymentService = {
703
788
  // src/ui/dialog.tsx
704
789
  import * as DialogPrimitive from "@radix-ui/react-dialog";
705
790
  import { XIcon } from "lucide-react";
706
- import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
791
+ import { jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
707
792
  function Dialog({ ...props }) {
708
- return /* @__PURE__ */ jsx5(DialogPrimitive.Root, { "data-slot": "dialog", ...props });
793
+ return /* @__PURE__ */ jsx6(DialogPrimitive.Root, { "data-slot": "dialog", ...props });
709
794
  }
710
795
  function DialogPortal({ ...props }) {
711
796
  const container = usePortalContainer();
712
797
  const safeContainer = container && document.body.contains(container) ? container : void 0;
713
- return /* @__PURE__ */ jsx5(DialogPrimitive.Portal, { container: safeContainer, "data-slot": "dialog-portal", ...props });
798
+ return /* @__PURE__ */ jsx6(DialogPrimitive.Portal, { container: safeContainer, "data-slot": "dialog-portal", ...props });
714
799
  }
715
800
  function DialogOverlay({ className, ...props }) {
716
- return /* @__PURE__ */ jsx5(
801
+ return /* @__PURE__ */ jsx6(
717
802
  DialogPrimitive.Overlay,
718
803
  {
719
804
  "data-slot": "dialog-overlay",
@@ -732,7 +817,7 @@ function DialogContent({
732
817
  ...props
733
818
  }) {
734
819
  return /* @__PURE__ */ jsxs3(DialogPortal, { "data-slot": "dialog-portal", children: [
735
- /* @__PURE__ */ jsx5(DialogOverlay, {}),
820
+ /* @__PURE__ */ jsx6(DialogOverlay, {}),
736
821
  /* @__PURE__ */ jsxs3(
737
822
  DialogPrimitive.Content,
738
823
  {
@@ -750,8 +835,8 @@ function DialogContent({
750
835
  "data-slot": "dialog-close",
751
836
  className: "ring-offset-background focus:ring-ring absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-(--accent) data-[state=open]:text-(--secondary) [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
752
837
  children: [
753
- /* @__PURE__ */ jsx5(XIcon, {}),
754
- /* @__PURE__ */ jsx5("span", { className: "sr-only", children: "Close" })
838
+ /* @__PURE__ */ jsx6(XIcon, {}),
839
+ /* @__PURE__ */ jsx6("span", { className: "sr-only", children: "Close" })
755
840
  ]
756
841
  }
757
842
  )
@@ -761,7 +846,7 @@ function DialogContent({
761
846
  ] });
762
847
  }
763
848
  function DialogTitle({ className, ...props }) {
764
- return /* @__PURE__ */ jsx5(
849
+ return /* @__PURE__ */ jsx6(
765
850
  DialogPrimitive.Title,
766
851
  {
767
852
  "data-slot": "dialog-title",
@@ -771,7 +856,7 @@ function DialogTitle({ className, ...props }) {
771
856
  );
772
857
  }
773
858
  function DialogDescription({ className, ...props }) {
774
- return /* @__PURE__ */ jsx5(
859
+ return /* @__PURE__ */ jsx6(
775
860
  DialogPrimitive.Description,
776
861
  {
777
862
  "data-slot": "dialog-description",
@@ -782,9 +867,17 @@ function DialogDescription({ className, ...props }) {
782
867
  }
783
868
 
784
869
  export {
785
- PaymentError,
786
870
  isNewCard,
787
871
  PaymentType,
872
+ PaymentStatus,
873
+ SpreePayHttpError,
874
+ PaymentErrorCode,
875
+ PaymentError,
876
+ isPaymentError,
877
+ isDeclineStatus,
878
+ isSuccessStatus,
879
+ toPaymentError,
880
+ settlePaymentResult,
788
881
  LogLevel,
789
882
  logger,
790
883
  configureLogger,
@@ -804,6 +897,8 @@ export {
804
897
  registerApi,
805
898
  SlapiPaymentService,
806
899
  useSpreePayConfig,
900
+ LoginStatusProvider,
901
+ useIsLoggedIn,
807
902
  InfoBanner,
808
903
  Legal
809
904
  };