@usethrottle/payment-methods 0.1.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/index.js ADDED
@@ -0,0 +1,338 @@
1
+ import {
2
+ DEFAULT_BASE_URL,
3
+ ThrottleError,
4
+ ThrottlePaymentMethodsError,
5
+ isThrottleError,
6
+ request
7
+ } from "./chunk-T2CV3T5K.js";
8
+
9
+ // src/client.ts
10
+ function createPaymentMethods(opts) {
11
+ const baseUrl = opts.baseUrl ?? DEFAULT_BASE_URL;
12
+ const headers = { "X-Throttle-PM-Token": opts.clientToken };
13
+ return {
14
+ async list() {
15
+ const parsed = await request({ method: "GET", path: "/api/v1/me/payment-methods", baseUrl, headers });
16
+ return parsed.data;
17
+ },
18
+ async setDefault(id) {
19
+ const parsed = await request({
20
+ method: "PATCH",
21
+ path: `/api/v1/me/payment-methods/${encodeURIComponent(id)}`,
22
+ baseUrl,
23
+ headers,
24
+ body: { isDefault: true }
25
+ });
26
+ return parsed.data;
27
+ },
28
+ async remove(id) {
29
+ const parsed = await request({
30
+ method: "DELETE",
31
+ path: `/api/v1/me/payment-methods/${encodeURIComponent(id)}`,
32
+ baseUrl,
33
+ headers
34
+ });
35
+ return parsed.data;
36
+ },
37
+ async startAddCard() {
38
+ const parsed = await request({
39
+ method: "POST",
40
+ path: "/api/v1/me/payment-methods/embed-token",
41
+ baseUrl,
42
+ headers
43
+ });
44
+ return parsed.data;
45
+ }
46
+ };
47
+ }
48
+
49
+ // src/usePaymentMethods.ts
50
+ import { useEffect, useMemo, useRef, useState } from "react";
51
+ function toPaymentMethodsError(err) {
52
+ if (err instanceof ThrottlePaymentMethodsError) return err;
53
+ const message = err instanceof Error ? err.message : String(err);
54
+ return new ThrottlePaymentMethodsError({ code: "unknown_error", message, statusCode: 0 });
55
+ }
56
+ function usePaymentMethods(opts) {
57
+ const { clientToken, baseUrl } = opts;
58
+ const client = useMemo(
59
+ () => createPaymentMethods({ clientToken, baseUrl }),
60
+ // eslint-disable-next-line react-hooks/exhaustive-deps
61
+ [clientToken, baseUrl]
62
+ );
63
+ const [cards, setCards] = useState([]);
64
+ const [isLoading, setIsLoading] = useState(true);
65
+ const [error, setError] = useState(null);
66
+ const genRef = useRef(0);
67
+ const refetch = useMemo(
68
+ () => async () => {
69
+ const myGen = genRef.current;
70
+ try {
71
+ const data = await client.list();
72
+ if (genRef.current !== myGen) return;
73
+ setCards(data);
74
+ setError(null);
75
+ } catch (err) {
76
+ if (genRef.current !== myGen) return;
77
+ setError(toPaymentMethodsError(err));
78
+ }
79
+ },
80
+ [client]
81
+ );
82
+ useEffect(() => {
83
+ const myGen = ++genRef.current;
84
+ (async () => {
85
+ setIsLoading(true);
86
+ try {
87
+ const data = await client.list();
88
+ if (genRef.current !== myGen) return;
89
+ setCards(data);
90
+ setError(null);
91
+ } catch (err) {
92
+ if (genRef.current !== myGen) return;
93
+ setError(toPaymentMethodsError(err));
94
+ } finally {
95
+ if (genRef.current === myGen) {
96
+ setIsLoading(false);
97
+ }
98
+ }
99
+ })();
100
+ }, [client]);
101
+ const setDefault = async (id) => {
102
+ try {
103
+ await client.setDefault(id);
104
+ await refetch();
105
+ } catch (err) {
106
+ const pmErr = toPaymentMethodsError(err);
107
+ setError(pmErr);
108
+ throw pmErr;
109
+ }
110
+ };
111
+ const remove = async (id) => {
112
+ try {
113
+ await client.remove(id);
114
+ await refetch();
115
+ } catch (err) {
116
+ const pmErr = toPaymentMethodsError(err);
117
+ setError(pmErr);
118
+ throw pmErr;
119
+ }
120
+ };
121
+ const addCard = async () => {
122
+ return client.startAddCard();
123
+ };
124
+ return { cards, isLoading, error, setDefault, remove, addCard, refetch };
125
+ }
126
+
127
+ // src/PaymentMethods.tsx
128
+ import React, { Suspense, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
129
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
130
+ var LazyGr4vyAddCard = React.lazy(
131
+ () => import("./Gr4vyAddCard-J3HC6KTK.js").then((m) => ({ default: m.Gr4vyAddCard }))
132
+ );
133
+ function formatCard(card) {
134
+ const brand = card.cardBrand ? card.cardBrand.toUpperCase() : "Card";
135
+ const last4 = card.cardLastFour ? `\u2022\u2022\u2022\u2022 ${card.cardLastFour}` : "\u2022\u2022\u2022\u2022";
136
+ const brandPart = `${brand} ${last4}`;
137
+ if (card.cardExpMonth != null && card.cardExpYear != null) {
138
+ const mm = String(card.cardExpMonth).padStart(2, "0");
139
+ const yy = String(card.cardExpYear).slice(-2);
140
+ return `${brandPart} \xB7 ${mm}/${yy}`;
141
+ }
142
+ return brandPart;
143
+ }
144
+ function PaymentMethods({ clientToken, baseUrl, theme, onChange }) {
145
+ const { cards, isLoading, error, setDefault, remove, addCard, refetch } = usePaymentMethods({
146
+ clientToken,
147
+ baseUrl
148
+ });
149
+ const [busyId, setBusyId] = useState2(null);
150
+ const [addCardPayload, setAddCardPayload] = useState2(null);
151
+ const [externalError, setExternalError] = useState2(null);
152
+ const onChangeRef = useRef2(onChange);
153
+ useEffect2(() => {
154
+ onChangeRef.current = onChange;
155
+ });
156
+ useEffect2(() => {
157
+ if (!isLoading) onChangeRef.current?.(cards);
158
+ }, [cards, isLoading]);
159
+ const primary = theme?.colorPrimary ?? "#1D56E8";
160
+ const colorText = theme?.colorText ?? "#111827";
161
+ const colorBorder = theme?.colorBorder ?? "#E5E7EB";
162
+ const borderRadius = theme?.borderRadius ?? "8px";
163
+ const handleSetDefault = async (id) => {
164
+ setBusyId(id);
165
+ try {
166
+ await setDefault(id);
167
+ } catch {
168
+ } finally {
169
+ setBusyId(null);
170
+ }
171
+ };
172
+ const handleRemove = async (id) => {
173
+ setBusyId(id);
174
+ try {
175
+ await remove(id);
176
+ } catch {
177
+ } finally {
178
+ setBusyId(null);
179
+ }
180
+ };
181
+ const handleAddCard = async () => {
182
+ try {
183
+ const payload = await addCard();
184
+ setExternalError(null);
185
+ setAddCardPayload(payload);
186
+ } catch (err) {
187
+ const message = err instanceof Error ? err.message : String(err);
188
+ setExternalError(new Error(message));
189
+ }
190
+ };
191
+ if (isLoading) {
192
+ return /* @__PURE__ */ jsx("div", { role: "status", "aria-label": "Loading payment methods", style: { color: colorText }, children: "Loading\u2026" });
193
+ }
194
+ const displayError = externalError ?? error;
195
+ return /* @__PURE__ */ jsxs("div", { style: { color: colorText, fontFamily: "inherit" }, children: [
196
+ displayError && /* @__PURE__ */ jsx(
197
+ "div",
198
+ {
199
+ role: "alert",
200
+ style: {
201
+ color: "#DC2626",
202
+ marginBottom: "12px",
203
+ padding: "8px 12px",
204
+ border: `1px solid #FCA5A5`,
205
+ borderRadius,
206
+ fontSize: "14px"
207
+ },
208
+ children: displayError.message
209
+ }
210
+ ),
211
+ /* @__PURE__ */ jsx("ul", { style: { listStyle: "none", margin: 0, padding: 0 }, children: cards.map((card) => {
212
+ const isBusy = busyId === card.id;
213
+ return /* @__PURE__ */ jsxs(
214
+ "li",
215
+ {
216
+ style: {
217
+ display: "flex",
218
+ alignItems: "center",
219
+ gap: "12px",
220
+ padding: "12px",
221
+ border: `1px solid ${colorBorder}`,
222
+ borderRadius,
223
+ marginBottom: "8px"
224
+ },
225
+ children: [
226
+ /* @__PURE__ */ jsx("span", { style: { flex: 1, fontSize: "14px" }, children: formatCard(card) }),
227
+ card.isDefault ? /* @__PURE__ */ jsx(
228
+ "span",
229
+ {
230
+ style: {
231
+ backgroundColor: primary,
232
+ color: "#fff",
233
+ fontSize: "12px",
234
+ fontWeight: 600,
235
+ padding: "2px 8px",
236
+ borderRadius: "999px"
237
+ },
238
+ children: "Default"
239
+ }
240
+ ) : /* @__PURE__ */ jsxs(Fragment, { children: [
241
+ /* @__PURE__ */ jsx(
242
+ "button",
243
+ {
244
+ type: "button",
245
+ disabled: isBusy,
246
+ onClick: () => handleSetDefault(card.id),
247
+ style: {
248
+ fontSize: "13px",
249
+ padding: "4px 10px",
250
+ border: `1px solid ${colorBorder}`,
251
+ borderRadius,
252
+ background: "transparent",
253
+ cursor: isBusy ? "not-allowed" : "pointer",
254
+ opacity: isBusy ? 0.5 : 1
255
+ },
256
+ children: "Make default"
257
+ }
258
+ ),
259
+ /* @__PURE__ */ jsx(
260
+ "button",
261
+ {
262
+ type: "button",
263
+ disabled: isBusy,
264
+ onClick: () => handleRemove(card.id),
265
+ style: {
266
+ fontSize: "13px",
267
+ padding: "4px 10px",
268
+ border: `1px solid #FCA5A5`,
269
+ borderRadius,
270
+ background: "transparent",
271
+ color: "#DC2626",
272
+ cursor: isBusy ? "not-allowed" : "pointer",
273
+ opacity: isBusy ? 0.5 : 1
274
+ },
275
+ children: "Remove"
276
+ }
277
+ )
278
+ ] })
279
+ ]
280
+ },
281
+ card.id
282
+ );
283
+ }) }),
284
+ addCardPayload ? /* @__PURE__ */ jsx(
285
+ Suspense,
286
+ {
287
+ fallback: /* @__PURE__ */ jsx("div", { role: "status", style: { color: colorText, marginTop: "12px" }, children: "Loading\u2026" }),
288
+ children: /* @__PURE__ */ jsx(
289
+ LazyGr4vyAddCard,
290
+ {
291
+ payload: addCardPayload,
292
+ theme,
293
+ onAdded: async (paymentMethodId) => {
294
+ void paymentMethodId;
295
+ await refetch();
296
+ setExternalError(null);
297
+ setAddCardPayload(null);
298
+ },
299
+ onCancel: () => setAddCardPayload(null),
300
+ onError: (err) => {
301
+ const message = err instanceof Error ? err.message : String(err);
302
+ setExternalError(new Error(message));
303
+ setAddCardPayload(null);
304
+ }
305
+ }
306
+ )
307
+ }
308
+ ) : /* @__PURE__ */ jsx(
309
+ "button",
310
+ {
311
+ type: "button",
312
+ onClick: handleAddCard,
313
+ style: {
314
+ marginTop: "12px",
315
+ padding: "8px 16px",
316
+ backgroundColor: primary,
317
+ color: "#fff",
318
+ border: "none",
319
+ borderRadius,
320
+ fontSize: "14px",
321
+ fontWeight: 600,
322
+ cursor: "pointer"
323
+ },
324
+ children: "+ Add card"
325
+ }
326
+ )
327
+ ] });
328
+ }
329
+ export {
330
+ DEFAULT_BASE_URL,
331
+ PaymentMethods,
332
+ ThrottleError,
333
+ ThrottlePaymentMethodsError,
334
+ createPaymentMethods,
335
+ isThrottleError,
336
+ usePaymentMethods
337
+ };
338
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/usePaymentMethods.ts","../src/PaymentMethods.tsx"],"sourcesContent":["import { request } from './request';\nimport { DEFAULT_BASE_URL } from './types';\nimport type { SavedCard, EmbedPayload } from './types';\n\nexport interface PaymentMethodsClient {\n list(): Promise<SavedCard[]>;\n setDefault(id: string): Promise<SavedCard>;\n remove(id: string): Promise<{ id: string }>;\n startAddCard(): Promise<EmbedPayload>;\n}\n\nexport function createPaymentMethods(opts: {\n clientToken: string;\n baseUrl?: string;\n}): PaymentMethodsClient {\n const baseUrl = opts.baseUrl ?? DEFAULT_BASE_URL;\n const headers = { 'X-Throttle-PM-Token': opts.clientToken };\n\n return {\n async list() {\n const parsed = await request({ method: 'GET', path: '/api/v1/me/payment-methods', baseUrl, headers });\n return parsed.data as SavedCard[];\n },\n\n async setDefault(id: string) {\n const parsed = await request({\n method: 'PATCH',\n path: `/api/v1/me/payment-methods/${encodeURIComponent(id)}`,\n baseUrl,\n headers,\n body: { isDefault: true },\n });\n return parsed.data as SavedCard;\n },\n\n async remove(id: string) {\n const parsed = await request({\n method: 'DELETE',\n path: `/api/v1/me/payment-methods/${encodeURIComponent(id)}`,\n baseUrl,\n headers,\n });\n return parsed.data as { id: string };\n },\n\n async startAddCard() {\n const parsed = await request({\n method: 'POST',\n path: '/api/v1/me/payment-methods/embed-token',\n baseUrl,\n headers,\n });\n return parsed.data as EmbedPayload;\n },\n };\n}\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport { createPaymentMethods } from './client';\nimport { ThrottlePaymentMethodsError } from './errors';\nimport type { EmbedPayload, SavedCard } from './types';\n\nexport interface UsePaymentMethodsOpts {\n clientToken: string;\n baseUrl?: string;\n}\n\nexport interface UsePaymentMethodsResult {\n cards: SavedCard[];\n isLoading: boolean;\n error: ThrottlePaymentMethodsError | null;\n setDefault(id: string): Promise<void>;\n remove(id: string): Promise<void>;\n addCard(): Promise<EmbedPayload>;\n refetch(): Promise<void>;\n}\n\nfunction toPaymentMethodsError(err: unknown): ThrottlePaymentMethodsError {\n if (err instanceof ThrottlePaymentMethodsError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new ThrottlePaymentMethodsError({ code: 'unknown_error', message, statusCode: 0 });\n}\n\nexport function usePaymentMethods(opts: UsePaymentMethodsOpts): UsePaymentMethodsResult {\n const { clientToken, baseUrl } = opts;\n\n const client = useMemo(\n () => createPaymentMethods({ clientToken, baseUrl }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [clientToken, baseUrl],\n );\n\n const [cards, setCards] = useState<SavedCard[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<ThrottlePaymentMethodsError | null>(null);\n const genRef = useRef(0);\n\n const refetch = useMemo(\n () => async () => {\n const myGen = genRef.current;\n try {\n const data = await client.list();\n if (genRef.current !== myGen) return;\n setCards(data);\n setError(null);\n } catch (err) {\n if (genRef.current !== myGen) return;\n setError(toPaymentMethodsError(err));\n }\n },\n [client],\n );\n\n useEffect(() => {\n const myGen = ++genRef.current;\n\n (async () => {\n setIsLoading(true);\n try {\n const data = await client.list();\n if (genRef.current !== myGen) return;\n setCards(data);\n setError(null);\n } catch (err) {\n if (genRef.current !== myGen) return;\n setError(toPaymentMethodsError(err));\n } finally {\n if (genRef.current === myGen) {\n setIsLoading(false);\n }\n }\n })();\n }, [client]);\n\n const setDefault = async (id: string): Promise<void> => {\n try {\n await client.setDefault(id);\n await refetch();\n } catch (err) {\n const pmErr = toPaymentMethodsError(err);\n setError(pmErr);\n throw pmErr;\n }\n };\n\n const remove = async (id: string): Promise<void> => {\n try {\n await client.remove(id);\n await refetch();\n } catch (err) {\n const pmErr = toPaymentMethodsError(err);\n setError(pmErr);\n throw pmErr;\n }\n };\n\n const addCard = async (): Promise<EmbedPayload> => {\n return client.startAddCard();\n };\n\n return { cards, isLoading, error, setDefault, remove, addCard, refetch };\n}\n","import React, { Suspense, useEffect, useRef, useState } from 'react';\nimport { usePaymentMethods } from './usePaymentMethods';\nimport type { EmbedPayload, SavedCard, PaymentMethodsTheme } from './types';\n\n// Lazy import — keeps @gr4vy/embed-react out of the eager bundle (SSR-safe).\n// Do NOT hoist this to a top-level import; React.lazy is the only safe path.\nconst LazyGr4vyAddCard = React.lazy(() =>\n import('./Gr4vyAddCard').then((m) => ({ default: m.Gr4vyAddCard })),\n);\n\nexport interface PaymentMethodsProps {\n clientToken: string;\n baseUrl?: string;\n theme?: PaymentMethodsTheme;\n onChange?: (cards: SavedCard[]) => void;\n}\n\nfunction formatCard(card: SavedCard): string {\n const brand = card.cardBrand ? card.cardBrand.toUpperCase() : 'Card';\n const last4 = card.cardLastFour ? `•••• ${card.cardLastFour}` : '••••';\n const brandPart = `${brand} ${last4}`;\n\n if (card.cardExpMonth != null && card.cardExpYear != null) {\n const mm = String(card.cardExpMonth).padStart(2, '0');\n const yy = String(card.cardExpYear).slice(-2);\n return `${brandPart} · ${mm}/${yy}`;\n }\n return brandPart;\n}\n\nexport function PaymentMethods({ clientToken, baseUrl, theme, onChange }: PaymentMethodsProps) {\n const { cards, isLoading, error, setDefault, remove, addCard, refetch } = usePaymentMethods({\n clientToken,\n baseUrl,\n });\n\n const [busyId, setBusyId] = useState<string | null>(null);\n const [addCardPayload, setAddCardPayload] = useState<EmbedPayload | null>(null);\n const [externalError, setExternalError] = useState<Error | null>(null);\n\n const onChangeRef = useRef(onChange);\n useEffect(() => { onChangeRef.current = onChange; });\n useEffect(() => { if (!isLoading) onChangeRef.current?.(cards); }, [cards, isLoading]);\n\n const primary = theme?.colorPrimary ?? '#1D56E8';\n const colorText = theme?.colorText ?? '#111827';\n const colorBorder = theme?.colorBorder ?? '#E5E7EB';\n const borderRadius = theme?.borderRadius ?? '8px';\n\n const handleSetDefault = async (id: string) => {\n setBusyId(id);\n try {\n await setDefault(id);\n } catch {\n // error is already set in the hook\n } finally {\n setBusyId(null);\n }\n };\n\n const handleRemove = async (id: string) => {\n setBusyId(id);\n try {\n await remove(id);\n } catch {\n // error is already set in the hook\n } finally {\n setBusyId(null);\n }\n };\n\n const handleAddCard = async () => {\n try {\n const payload = await addCard();\n setExternalError(null);\n setAddCardPayload(payload);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n setExternalError(new Error(message));\n }\n };\n\n if (isLoading) {\n return (\n <div role=\"status\" aria-label=\"Loading payment methods\" style={{ color: colorText }}>\n Loading…\n </div>\n );\n }\n\n const displayError = externalError ?? error;\n\n return (\n <div style={{ color: colorText, fontFamily: 'inherit' }}>\n {displayError && (\n <div\n role=\"alert\"\n style={{\n color: '#DC2626',\n marginBottom: '12px',\n padding: '8px 12px',\n border: `1px solid #FCA5A5`,\n borderRadius,\n fontSize: '14px',\n }}\n >\n {displayError.message}\n </div>\n )}\n\n <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>\n {cards.map((card) => {\n const isBusy = busyId === card.id;\n return (\n <li\n key={card.id}\n style={{\n display: 'flex',\n alignItems: 'center',\n gap: '12px',\n padding: '12px',\n border: `1px solid ${colorBorder}`,\n borderRadius,\n marginBottom: '8px',\n }}\n >\n <span style={{ flex: 1, fontSize: '14px' }}>{formatCard(card)}</span>\n\n {card.isDefault ? (\n <span\n style={{\n backgroundColor: primary,\n color: '#fff',\n fontSize: '12px',\n fontWeight: 600,\n padding: '2px 8px',\n borderRadius: '999px',\n }}\n >\n Default\n </span>\n ) : (\n <>\n <button\n type=\"button\"\n disabled={isBusy}\n onClick={() => handleSetDefault(card.id)}\n style={{\n fontSize: '13px',\n padding: '4px 10px',\n border: `1px solid ${colorBorder}`,\n borderRadius,\n background: 'transparent',\n cursor: isBusy ? 'not-allowed' : 'pointer',\n opacity: isBusy ? 0.5 : 1,\n }}\n >\n Make default\n </button>\n <button\n type=\"button\"\n disabled={isBusy}\n onClick={() => handleRemove(card.id)}\n style={{\n fontSize: '13px',\n padding: '4px 10px',\n border: `1px solid #FCA5A5`,\n borderRadius,\n background: 'transparent',\n color: '#DC2626',\n cursor: isBusy ? 'not-allowed' : 'pointer',\n opacity: isBusy ? 0.5 : 1,\n }}\n >\n Remove\n </button>\n </>\n )}\n </li>\n );\n })}\n </ul>\n\n {addCardPayload ? (\n <Suspense\n fallback={\n <div role=\"status\" style={{ color: colorText, marginTop: '12px' }}>\n Loading…\n </div>\n }\n >\n <LazyGr4vyAddCard\n payload={addCardPayload}\n theme={theme}\n onAdded={async (paymentMethodId) => {\n void paymentMethodId;\n await refetch();\n setExternalError(null);\n setAddCardPayload(null);\n }}\n onCancel={() => setAddCardPayload(null)}\n onError={(err) => {\n const message = err instanceof Error ? (err as Error).message : String(err);\n setExternalError(new Error(message));\n setAddCardPayload(null);\n }}\n />\n </Suspense>\n ) : (\n <button\n type=\"button\"\n onClick={handleAddCard}\n style={{\n marginTop: '12px',\n padding: '8px 16px',\n backgroundColor: primary,\n color: '#fff',\n border: 'none',\n borderRadius,\n fontSize: '14px',\n fontWeight: 600,\n cursor: 'pointer',\n }}\n >\n + Add card\n </button>\n )}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;AAWO,SAAS,qBAAqB,MAGZ;AACvB,QAAM,UAAU,KAAK,WAAW;AAChC,QAAM,UAAU,EAAE,uBAAuB,KAAK,YAAY;AAE1D,SAAO;AAAA,IACL,MAAM,OAAO;AACX,YAAM,SAAS,MAAM,QAAQ,EAAE,QAAQ,OAAO,MAAM,8BAA8B,SAAS,QAAQ,CAAC;AACpG,aAAO,OAAO;AAAA,IAChB;AAAA,IAEA,MAAM,WAAW,IAAY;AAC3B,YAAM,SAAS,MAAM,QAAQ;AAAA,QAC3B,QAAQ;AAAA,QACR,MAAM,8BAA8B,mBAAmB,EAAE,CAAC;AAAA,QAC1D;AAAA,QACA;AAAA,QACA,MAAM,EAAE,WAAW,KAAK;AAAA,MAC1B,CAAC;AACD,aAAO,OAAO;AAAA,IAChB;AAAA,IAEA,MAA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A,YACT;AAAA,YACA,SAAS,OAAO,oBAAoB;AAClC,mBAAK;AACL,oBAAM,QAAQ;AACd,+BAAiB,IAAI;AACrB,gCAAkB,IAAI;AAAA,YACxB;AAAA,YACA,UAAU,MAAM,kBAAkB,IAAI;AAAA,YACtC,SAAS,CAAC,QAAQ;AAChB,oBAAM,UAAU,eAAe,QAAS,IAAc,UAAU,OAAO,GAAG;AAC1E,+BAAiB,IAAI,MAAM,OAAO,CAAC;AACnC,gCAAkB,IAAI;AAAA,YACxB;AAAA;AAAA,QACF;AAAA;AAAA,IACF,IAEA;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,SAAS;AAAA,QACT,OAAO;AAAA,UACL,WAAW;AAAA,UACX,SAAS;AAAA,UACT,iBAAiB;AAAA,UACjB,OAAO;AAAA,UACP,QAAQ;AAAA,UACR;AAAA,UACA,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,QAAQ;AAAA,QACV;AAAA,QACD;AAAA;AAAA,IAED;AAAA,KAEJ;AAEJ;","names":["useEffect","useRef","useState","useState","useRef","useEffect"]}
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ createServerPaymentMethods: () => createServerPaymentMethods,
24
+ mintClientToken: () => mintClientToken
25
+ });
26
+ module.exports = __toCommonJS(server_exports);
27
+
28
+ // src/errors.ts
29
+ var import_errors = require("@usethrottle/errors");
30
+ var import_errors2 = require("@usethrottle/errors");
31
+ var ThrottlePaymentMethodsError = class extends import_errors.ThrottleError {
32
+ constructor(args) {
33
+ super(args);
34
+ this.name = "ThrottlePaymentMethodsError";
35
+ }
36
+ };
37
+
38
+ // src/request.ts
39
+ async function request(input) {
40
+ const res = await fetch(`${input.baseUrl}${input.path}`, {
41
+ method: input.method,
42
+ headers: {
43
+ ...input.body !== void 0 ? { "Content-Type": "application/json" } : {},
44
+ ...input.headers ?? {}
45
+ },
46
+ ...input.body !== void 0 ? { body: JSON.stringify(input.body) } : {}
47
+ });
48
+ const text = await res.text();
49
+ let parsed = {};
50
+ try {
51
+ parsed = text ? JSON.parse(text) : {};
52
+ } catch {
53
+ }
54
+ if (!res.ok) {
55
+ const e = parsed?.error ?? {};
56
+ throw new ThrottlePaymentMethodsError({
57
+ code: e.code ?? "request_failed",
58
+ message: e.message ?? `Request failed with ${res.status}`,
59
+ statusCode: res.status,
60
+ details: e.details
61
+ });
62
+ }
63
+ return parsed;
64
+ }
65
+
66
+ // src/types.ts
67
+ var DEFAULT_BASE_URL = "https://api.usethrottle.dev";
68
+
69
+ // src/server.ts
70
+ function authHeaders(opts) {
71
+ return {
72
+ "X-API-Key": opts.apiKey,
73
+ ...opts.environmentId ? { "X-Throttle-Environment-Id": opts.environmentId } : {}
74
+ };
75
+ }
76
+ async function mintClientToken(opts) {
77
+ const parsed = await request({
78
+ method: "POST",
79
+ path: "/api/v1/payment-methods/client-token",
80
+ baseUrl: opts.baseUrl ?? DEFAULT_BASE_URL,
81
+ headers: authHeaders(opts),
82
+ body: { customerId: opts.customerId }
83
+ });
84
+ return parsed.data;
85
+ }
86
+ function createServerPaymentMethods(opts) {
87
+ const base = opts.baseUrl ?? DEFAULT_BASE_URL;
88
+ const prefix = `/api/v1/customers/${encodeURIComponent(opts.customerId)}/payment-methods`;
89
+ const headers = authHeaders(opts);
90
+ return {
91
+ async list() {
92
+ const parsed = await request({ method: "GET", path: prefix, baseUrl: base, headers });
93
+ return parsed.data;
94
+ },
95
+ async setDefault(id) {
96
+ const parsed = await request({
97
+ method: "PATCH",
98
+ path: `${prefix}/${encodeURIComponent(id)}`,
99
+ baseUrl: base,
100
+ headers,
101
+ body: { isDefault: true }
102
+ });
103
+ return parsed.data;
104
+ },
105
+ async remove(id) {
106
+ const parsed = await request({
107
+ method: "DELETE",
108
+ path: `${prefix}/${encodeURIComponent(id)}`,
109
+ baseUrl: base,
110
+ headers
111
+ });
112
+ return parsed.data;
113
+ }
114
+ };
115
+ }
116
+ // Annotate the CommonJS export names for ESM import in node:
117
+ 0 && (module.exports = {
118
+ createServerPaymentMethods,
119
+ mintClientToken
120
+ });
121
+ //# sourceMappingURL=server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts","../src/errors.ts","../src/request.ts","../src/types.ts"],"sourcesContent":["/**\n * Server-only entry for @usethrottle/payment-methods.\n *\n * NOTE: No `startAddCard` here — adding a card is inherently a browser flow.\n * The backend's role is to mint a short-lived client token via `mintClientToken`;\n * the browser then passes that token to <PaymentMethods/> (or the headless client)\n * to initiate the card-add UI. The server cannot initiate the Gr4vy embed flow.\n *\n * MUST NOT import React or @gr4vy/embed-react. Only ./request, ./types, ./errors.\n */\n\nimport { request } from './request';\nimport type { MintedClientToken, SavedCard } from './types';\nimport { DEFAULT_BASE_URL } from './types';\n\ninterface ServerOpts {\n apiKey: string;\n customerId: string;\n baseUrl?: string;\n environmentId?: string;\n}\n\nfunction authHeaders(opts: Pick<ServerOpts, 'apiKey' | 'environmentId'>): Record<string, string> {\n return {\n 'X-API-Key': opts.apiKey,\n ...(opts.environmentId ? { 'X-Throttle-Environment-Id': opts.environmentId } : {}),\n };\n}\n\nexport async function mintClientToken(opts: ServerOpts): Promise<MintedClientToken> {\n const parsed = await request({\n method: 'POST',\n path: '/api/v1/payment-methods/client-token',\n baseUrl: opts.baseUrl ?? DEFAULT_BASE_URL,\n headers: authHeaders(opts),\n body: { customerId: opts.customerId },\n });\n return parsed.data as MintedClientToken;\n}\n\nexport function createServerPaymentMethods(opts: ServerOpts): {\n list(): Promise<SavedCard[]>;\n setDefault(id: string): Promise<SavedCard>;\n remove(id: string): Promise<{ id: string }>;\n} {\n const base = opts.baseUrl ?? DEFAULT_BASE_URL;\n const prefix = `/api/v1/customers/${encodeURIComponent(opts.customerId)}/payment-methods`;\n const headers = authHeaders(opts);\n\n return {\n async list() {\n const parsed = await request({ method: 'GET', path: prefix, baseUrl: base, headers });\n return parsed.data as SavedCard[];\n },\n async setDefault(id: string) {\n const parsed = await request({\n method: 'PATCH',\n path: `${prefix}/${encodeURIComponent(id)}`,\n baseUrl: base,\n headers,\n body: { isDefault: true },\n });\n return parsed.data as SavedCard;\n },\n async remove(id: string) {\n const parsed = await request({\n method: 'DELETE',\n path: `${prefix}/${encodeURIComponent(id)}`,\n baseUrl: base,\n headers,\n });\n return parsed.data as { id: string };\n },\n };\n}\n","import { ThrottleError } from '@usethrottle/errors';\n\nexport class ThrottlePaymentMethodsError extends ThrottleError {\n constructor(args: { code: string; message: string; statusCode: number; details?: unknown }) {\n super(args);\n this.name = 'ThrottlePaymentMethodsError';\n }\n}\n\nexport { ThrottleError, isThrottleError } from '@usethrottle/errors';\n","import { ThrottlePaymentMethodsError } from './errors';\n\nexport async function request(input: {\n method: string;\n path: string;\n baseUrl: string;\n headers?: Record<string, string>;\n body?: unknown;\n}): Promise<any> {\n const res = await fetch(`${input.baseUrl}${input.path}`, {\n method: input.method,\n headers: {\n ...(input.body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...(input.headers ?? {}),\n },\n ...(input.body !== undefined ? { body: JSON.stringify(input.body) } : {}),\n });\n const text = await res.text();\n let parsed: any = {};\n try {\n parsed = text ? JSON.parse(text) : {};\n } catch {\n // Non-JSON body (e.g. an HTML 502/503 gateway page). Leave parsed as {} so\n // the non-2xx branch below still throws a typed ThrottlePaymentMethodsError\n // (code 'request_failed') rather than leaking a raw SyntaxError.\n }\n if (!res.ok) {\n const e = parsed?.error ?? {};\n throw new ThrottlePaymentMethodsError({\n code: e.code ?? 'request_failed',\n message: e.message ?? `Request failed with ${res.status}`,\n statusCode: res.status,\n details: e.details,\n });\n }\n return parsed;\n}\n","export interface SavedCard {\n id: string;\n methodType: string;\n cardBrand: string | null;\n cardLastFour: string | null;\n cardExpMonth: number | null;\n cardExpYear: number | null;\n isDefault: boolean;\n}\n\nexport interface EmbedPayload {\n embedToken: string;\n checkoutSessionId: string;\n amount: number;\n currency: string;\n gr4vyId: string;\n merchantAccountId?: string;\n environment: 'sandbox' | 'production';\n hostedUrl?: string;\n embedUrl?: string;\n}\n\nexport interface MintedClientToken {\n token: string;\n expiresAt: string;\n}\n\nexport interface PaymentMethodsTheme {\n colorPrimary?: string;\n colorText?: string;\n colorBorder?: string;\n borderRadius?: string;\n}\n\nexport const DEFAULT_BASE_URL = 'https://api.usethrottle.dev';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA8B;AAS9B,IAAAA,iBAA+C;AAPxC,IAAM,8BAAN,cAA0C,4BAAc;AAAA,EAC7D,YAAY,MAAgF;AAC1F,UAAM,IAAI;AACV,SAAK,OAAO;AAAA,EACd;AACF;;;ACLA,eAAsB,QAAQ,OAMb;AACf,QAAM,MAAM,MAAM,MAAM,GAAG,MAAM,OAAO,GAAG,MAAM,IAAI,IAAI;AAAA,IACvD,QAAQ,MAAM;AAAA,IACd,SAAS;AAAA,MACP,GAAI,MAAM,SAAS,SAAY,EAAE,gBAAgB,mBAAmB,IAAI,CAAC;AAAA,MACzE,GAAI,MAAM,WAAW,CAAC;AAAA,IACxB;AAAA,IACA,GAAI,MAAM,SAAS,SAAY,EAAE,MAAM,KAA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AAM,QAAQ;AAAA,QAC3B,QAAQ;AAAA,QACR,MAAM,GAAG,MAAM,IAAI,mBAAmB,EAAE,CAAC;AAAA,QACzC,SAAS;AAAA,QACT;AAAA,QACA,MAAM,EAAE,WAAW,KAAK;AAAA,MAC1B,CAAC;AACD,aAAO,OAAO;AAAA,IAChB;AAAA,IACA,MAAM,OAAO,IAAY;AACvB,YAAM,SAAS,MAAM,QAAQ;AAAA,QAC3B,QAAQ;AAAA,QACR,MAAM,GAAG,MAAM,IAAI,mBAAmB,EAAE,CAAC;AAAA,QACzC,SAAS;AAAA,QACT;AAAA,MACF,CAAC;AACD,aAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;","names":["import_errors"]}
@@ -0,0 +1,29 @@
1
+ import { S as SavedCard, M as MintedClientToken } from './types-Bleeq_oI.cjs';
2
+
3
+ /**
4
+ * Server-only entry for @usethrottle/payment-methods.
5
+ *
6
+ * NOTE: No `startAddCard` here — adding a card is inherently a browser flow.
7
+ * The backend's role is to mint a short-lived client token via `mintClientToken`;
8
+ * the browser then passes that token to <PaymentMethods/> (or the headless client)
9
+ * to initiate the card-add UI. The server cannot initiate the Gr4vy embed flow.
10
+ *
11
+ * MUST NOT import React or @gr4vy/embed-react. Only ./request, ./types, ./errors.
12
+ */
13
+
14
+ interface ServerOpts {
15
+ apiKey: string;
16
+ customerId: string;
17
+ baseUrl?: string;
18
+ environmentId?: string;
19
+ }
20
+ declare function mintClientToken(opts: ServerOpts): Promise<MintedClientToken>;
21
+ declare function createServerPaymentMethods(opts: ServerOpts): {
22
+ list(): Promise<SavedCard[]>;
23
+ setDefault(id: string): Promise<SavedCard>;
24
+ remove(id: string): Promise<{
25
+ id: string;
26
+ }>;
27
+ };
28
+
29
+ export { createServerPaymentMethods, mintClientToken };
@@ -0,0 +1,29 @@
1
+ import { S as SavedCard, M as MintedClientToken } from './types-Bleeq_oI.js';
2
+
3
+ /**
4
+ * Server-only entry for @usethrottle/payment-methods.
5
+ *
6
+ * NOTE: No `startAddCard` here — adding a card is inherently a browser flow.
7
+ * The backend's role is to mint a short-lived client token via `mintClientToken`;
8
+ * the browser then passes that token to <PaymentMethods/> (or the headless client)
9
+ * to initiate the card-add UI. The server cannot initiate the Gr4vy embed flow.
10
+ *
11
+ * MUST NOT import React or @gr4vy/embed-react. Only ./request, ./types, ./errors.
12
+ */
13
+
14
+ interface ServerOpts {
15
+ apiKey: string;
16
+ customerId: string;
17
+ baseUrl?: string;
18
+ environmentId?: string;
19
+ }
20
+ declare function mintClientToken(opts: ServerOpts): Promise<MintedClientToken>;
21
+ declare function createServerPaymentMethods(opts: ServerOpts): {
22
+ list(): Promise<SavedCard[]>;
23
+ setDefault(id: string): Promise<SavedCard>;
24
+ remove(id: string): Promise<{
25
+ id: string;
26
+ }>;
27
+ };
28
+
29
+ export { createServerPaymentMethods, mintClientToken };
package/dist/server.js ADDED
@@ -0,0 +1,57 @@
1
+ import {
2
+ DEFAULT_BASE_URL,
3
+ request
4
+ } from "./chunk-T2CV3T5K.js";
5
+
6
+ // src/server.ts
7
+ function authHeaders(opts) {
8
+ return {
9
+ "X-API-Key": opts.apiKey,
10
+ ...opts.environmentId ? { "X-Throttle-Environment-Id": opts.environmentId } : {}
11
+ };
12
+ }
13
+ async function mintClientToken(opts) {
14
+ const parsed = await request({
15
+ method: "POST",
16
+ path: "/api/v1/payment-methods/client-token",
17
+ baseUrl: opts.baseUrl ?? DEFAULT_BASE_URL,
18
+ headers: authHeaders(opts),
19
+ body: { customerId: opts.customerId }
20
+ });
21
+ return parsed.data;
22
+ }
23
+ function createServerPaymentMethods(opts) {
24
+ const base = opts.baseUrl ?? DEFAULT_BASE_URL;
25
+ const prefix = `/api/v1/customers/${encodeURIComponent(opts.customerId)}/payment-methods`;
26
+ const headers = authHeaders(opts);
27
+ return {
28
+ async list() {
29
+ const parsed = await request({ method: "GET", path: prefix, baseUrl: base, headers });
30
+ return parsed.data;
31
+ },
32
+ async setDefault(id) {
33
+ const parsed = await request({
34
+ method: "PATCH",
35
+ path: `${prefix}/${encodeURIComponent(id)}`,
36
+ baseUrl: base,
37
+ headers,
38
+ body: { isDefault: true }
39
+ });
40
+ return parsed.data;
41
+ },
42
+ async remove(id) {
43
+ const parsed = await request({
44
+ method: "DELETE",
45
+ path: `${prefix}/${encodeURIComponent(id)}`,
46
+ baseUrl: base,
47
+ headers
48
+ });
49
+ return parsed.data;
50
+ }
51
+ };
52
+ }
53
+ export {
54
+ createServerPaymentMethods,
55
+ mintClientToken
56
+ };
57
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only entry for @usethrottle/payment-methods.\n *\n * NOTE: No `startAddCard` here — adding a card is inherently a browser flow.\n * The backend's role is to mint a short-lived client token via `mintClientToken`;\n * the browser then passes that token to <PaymentMethods/> (or the headless client)\n * to initiate the card-add UI. The server cannot initiate the Gr4vy embed flow.\n *\n * MUST NOT import React or @gr4vy/embed-react. Only ./request, ./types, ./errors.\n */\n\nimport { request } from './request';\nimport type { MintedClientToken, SavedCard } from './types';\nimport { DEFAULT_BASE_URL } from './types';\n\ninterface ServerOpts {\n apiKey: string;\n customerId: string;\n baseUrl?: string;\n environmentId?: string;\n}\n\nfunction authHeaders(opts: Pick<ServerOpts, 'apiKey' | 'environmentId'>): Record<string, string> {\n return {\n 'X-API-Key': opts.apiKey,\n ...(opts.environmentId ? { 'X-Throttle-Environment-Id': opts.environmentId } : {}),\n };\n}\n\nexport async function mintClientToken(opts: ServerOpts): Promise<MintedClientToken> {\n const parsed = await request({\n method: 'POST',\n path: '/api/v1/payment-methods/client-token',\n baseUrl: opts.baseUrl ?? DEFAULT_BASE_URL,\n headers: authHeaders(opts),\n body: { customerId: opts.customerId },\n });\n return parsed.data as MintedClientToken;\n}\n\nexport function createServerPaymentMethods(opts: ServerOpts): {\n list(): Promise<SavedCard[]>;\n setDefault(id: string): Promise<SavedCard>;\n remove(id: string): Promise<{ id: string }>;\n} {\n const base = opts.baseUrl ?? DEFAULT_BASE_URL;\n const prefix = `/api/v1/customers/${encodeURIComponent(opts.customerId)}/payment-methods`;\n const headers = authHeaders(opts);\n\n return {\n async list() {\n const parsed = await request({ method: 'GET', path: prefix, baseUrl: base, headers });\n return parsed.data as SavedCard[];\n },\n async setDefault(id: string) {\n const parsed = await request({\n method: 'PATCH',\n path: `${prefix}/${encodeURIComponent(id)}`,\n baseUrl: base,\n headers,\n body: { isDefault: true },\n });\n return parsed.data as SavedCard;\n },\n async remove(id: string) {\n const parsed = await request({\n method: 'DELETE',\n path: `${prefix}/${encodeURIComponent(id)}`,\n baseUrl: base,\n headers,\n });\n return parsed.data as { id: string };\n },\n };\n}\n"],"mappings":";;;;;;AAsBA,SAAS,YAAY,MAA4E;AAC/F,SAAO;AAAA,IACL,aAAa,KAAK;AAAA,IAClB,GAAI,KAAK,gBAAgB,EAAE,6BAA6B,KAAK,cAAc,IAAI,CAAC;AAAA,EAClF;AACF;AAEA,eAAsB,gBAAgB,MAA8C;AAClF,QAAM,SAAS,MAAM,QAAQ;AAAA,IAC3B,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,SAAS,KAAK,WAAW;AAAA,IACzB,SAAS,YAAY,IAAI;AAAA,IACzB,MAAM,EAAE,YAAY,KAAK,WAAW;AAAA,EACtC,CAAC;AACD,SAAO,OAAO;AAChB;AAEO,SAAS,2BAA2B,MAIzC;AACA,QAAM,OAAO,KAAK,WAAW;AAC7B,QAAM,SAAS,qBAAqB,mBAAmB,KAAK,UAAU,CAAC;AACvE,QAAM,UAAU,YAAY,IAAI;AAEhC,SAAO;AAAA,IACL,MAAM,OAAO;AACX,YAAM,SAAS,MAAM,QAAQ,EAAE,QAAQ,OAAO,MAAM,QAAQ,SAAS,MAAM,QAAQ,CAAC;AACpF,aAAO,OAAO;AAAA,IAChB;AAAA,IACA,MAAM,WAAW,IAAY;AAC3B,YAAM,SAAS,MAAM,QAAQ;AAAA,QAC3B,QAAQ;AAAA,QACR,MAAM,GAAG,MAAM,IAAI,mBAAmB,EAAE,CAAC;AAAA,QACzC,SAAS;AAAA,QACT;AAAA,QACA,MAAM,EAAE,WAAW,KAAK;AAAA,MAC1B,CAAC;AACD,aAAO,OAAO;AAAA,IAChB;AAAA,IACA,MAAM,OAAO,IAAY;AACvB,YAAM,SAAS,MAAM,QAAQ;AAAA,QAC3B,QAAQ;AAAA,QACR,MAAM,GAAG,MAAM,IAAI,mBAAmB,EAAE,CAAC;AAAA,QACzC,SAAS;AAAA,QACT;AAAA,MACF,CAAC;AACD,aAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,33 @@
1
+ interface SavedCard {
2
+ id: string;
3
+ methodType: string;
4
+ cardBrand: string | null;
5
+ cardLastFour: string | null;
6
+ cardExpMonth: number | null;
7
+ cardExpYear: number | null;
8
+ isDefault: boolean;
9
+ }
10
+ interface EmbedPayload {
11
+ embedToken: string;
12
+ checkoutSessionId: string;
13
+ amount: number;
14
+ currency: string;
15
+ gr4vyId: string;
16
+ merchantAccountId?: string;
17
+ environment: 'sandbox' | 'production';
18
+ hostedUrl?: string;
19
+ embedUrl?: string;
20
+ }
21
+ interface MintedClientToken {
22
+ token: string;
23
+ expiresAt: string;
24
+ }
25
+ interface PaymentMethodsTheme {
26
+ colorPrimary?: string;
27
+ colorText?: string;
28
+ colorBorder?: string;
29
+ borderRadius?: string;
30
+ }
31
+ declare const DEFAULT_BASE_URL = "https://api.usethrottle.dev";
32
+
33
+ export { DEFAULT_BASE_URL as D, type EmbedPayload as E, type MintedClientToken as M, type PaymentMethodsTheme as P, type SavedCard as S };