@rechargeapps/storefront-client 1.18.3 → 1.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/cjs/api/auth.js +26 -44
- package/dist/cjs/api/auth.js.map +1 -1
- package/dist/cjs/api/bundle.js +1 -3
- package/dist/cjs/api/bundle.js.map +1 -1
- package/dist/cjs/api/credit.js +51 -0
- package/dist/cjs/api/credit.js.map +1 -0
- package/dist/cjs/api/customer.js +2 -18
- package/dist/cjs/api/customer.js.map +1 -1
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/utils/init.js +2 -0
- package/dist/cjs/utils/init.js.map +1 -1
- package/dist/cjs/utils/request.js +5 -2
- package/dist/cjs/utils/request.js.map +1 -1
- package/dist/esm/api/auth.js +26 -44
- package/dist/esm/api/auth.js.map +1 -1
- package/dist/esm/api/bundle.js +1 -3
- package/dist/esm/api/bundle.js.map +1 -1
- package/dist/esm/api/credit.js +47 -0
- package/dist/esm/api/credit.js.map +1 -0
- package/dist/esm/api/customer.js +3 -18
- package/dist/esm/api/customer.js.map +1 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/utils/init.js +2 -0
- package/dist/esm/utils/init.js.map +1 -1
- package/dist/esm/utils/request.js +5 -2
- package/dist/esm/utils/request.js.map +1 -1
- package/dist/index.d.ts +83 -46
- package/dist/umd/recharge-client.min.js +14 -14
- package/package.json +2 -1
package/dist/esm/api/auth.js
CHANGED
|
@@ -15,60 +15,42 @@ async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToke
|
|
|
15
15
|
return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);
|
|
16
16
|
}
|
|
17
17
|
async function loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken) {
|
|
18
|
-
const {
|
|
19
|
-
const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);
|
|
20
|
-
const headers = {};
|
|
21
|
-
if (storefrontAccessToken) {
|
|
22
|
-
headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
|
|
23
|
-
}
|
|
18
|
+
const { storeIdentifier } = getOptions();
|
|
24
19
|
const {
|
|
25
20
|
api_token: apiToken,
|
|
26
21
|
customer_id: customerId,
|
|
27
22
|
message
|
|
28
|
-
} = await
|
|
23
|
+
} = await rechargeAdminRequest("post", "/shopify_storefront_access", {
|
|
29
24
|
data: {
|
|
30
25
|
customer_token: shopifyCustomerAccessToken,
|
|
31
26
|
storefront_token: shopifyStorefrontToken,
|
|
32
27
|
shop_url: storeIdentifier
|
|
33
|
-
}
|
|
34
|
-
headers
|
|
28
|
+
}
|
|
35
29
|
});
|
|
36
30
|
return apiToken ? { apiToken, customerId, message } : null;
|
|
37
31
|
}
|
|
38
32
|
async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken) {
|
|
39
|
-
const {
|
|
40
|
-
const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);
|
|
41
|
-
const headers = {};
|
|
42
|
-
if (storefrontAccessToken) {
|
|
43
|
-
headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
|
|
44
|
-
}
|
|
33
|
+
const { storeIdentifier } = getOptions();
|
|
45
34
|
const {
|
|
46
35
|
api_token: apiToken,
|
|
47
36
|
customer_id: customerId,
|
|
48
37
|
message
|
|
49
|
-
} = await
|
|
38
|
+
} = await rechargeAdminRequest("post", "/shopify_customer_account_api_access", {
|
|
50
39
|
data: {
|
|
51
40
|
customer_token: shopifyCustomerAccessToken,
|
|
52
41
|
shop_url: storeIdentifier
|
|
53
|
-
}
|
|
54
|
-
headers
|
|
42
|
+
}
|
|
55
43
|
});
|
|
56
44
|
return apiToken ? { apiToken, customerId, message } : null;
|
|
57
45
|
}
|
|
58
46
|
async function sendPasswordlessCode(email, options = {}) {
|
|
59
|
-
const {
|
|
60
|
-
const
|
|
61
|
-
const headers = {};
|
|
62
|
-
if (storefrontAccessToken) {
|
|
63
|
-
headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
|
|
64
|
-
}
|
|
65
|
-
const response = await request("post", `${rechargeBaseUrl}/attempt_login`, {
|
|
47
|
+
const { storeIdentifier } = getOptions();
|
|
48
|
+
const response = await rechargeAdminRequest("post", "/attempt_login", {
|
|
66
49
|
data: {
|
|
67
50
|
email,
|
|
68
51
|
shop: storeIdentifier,
|
|
69
52
|
...options
|
|
70
|
-
}
|
|
71
|
-
headers
|
|
53
|
+
}
|
|
72
54
|
});
|
|
73
55
|
if (response.errors) {
|
|
74
56
|
throw new Error(response.errors);
|
|
@@ -94,20 +76,14 @@ async function sendPasswordlessCodeAppProxy(email, options = {}) {
|
|
|
94
76
|
return response.session_token;
|
|
95
77
|
}
|
|
96
78
|
async function validatePasswordlessCode(email, session_token, code) {
|
|
97
|
-
const {
|
|
98
|
-
const
|
|
99
|
-
const headers = {};
|
|
100
|
-
if (storefrontAccessToken) {
|
|
101
|
-
headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
|
|
102
|
-
}
|
|
103
|
-
const response = await request("post", `${rechargeBaseUrl}/validate_login`, {
|
|
79
|
+
const { storeIdentifier } = getOptions();
|
|
80
|
+
const response = await rechargeAdminRequest("post", "/validate_login", {
|
|
104
81
|
data: {
|
|
105
82
|
code,
|
|
106
83
|
email,
|
|
107
84
|
session_token,
|
|
108
85
|
shop: storeIdentifier
|
|
109
|
-
}
|
|
110
|
-
headers
|
|
86
|
+
}
|
|
111
87
|
});
|
|
112
88
|
if (response.errors) {
|
|
113
89
|
throw new Error(response.errors);
|
|
@@ -148,14 +124,8 @@ function getCustomerParams() {
|
|
|
148
124
|
}
|
|
149
125
|
async function loginCustomerPortal() {
|
|
150
126
|
const { customerHash, token } = getCustomerParams();
|
|
151
|
-
const {
|
|
152
|
-
const
|
|
153
|
-
const headers = {};
|
|
154
|
-
if (storefrontAccessToken) {
|
|
155
|
-
headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
|
|
156
|
-
}
|
|
157
|
-
const response = await request("post", `${rechargeBaseUrl}/customers/${customerHash}/access`, {
|
|
158
|
-
headers,
|
|
127
|
+
const { storeIdentifier } = getOptions();
|
|
128
|
+
const response = await rechargeAdminRequest("post", `/customers/${customerHash}/access`, {
|
|
159
129
|
data: {
|
|
160
130
|
token,
|
|
161
131
|
shop: storeIdentifier
|
|
@@ -163,6 +133,18 @@ async function loginCustomerPortal() {
|
|
|
163
133
|
});
|
|
164
134
|
return { apiToken: response.api_token, customerId: response.customer_id };
|
|
165
135
|
}
|
|
136
|
+
async function rechargeAdminRequest(method, url, { id, query, data, headers } = {}) {
|
|
137
|
+
const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();
|
|
138
|
+
const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);
|
|
139
|
+
const reqHeaders = {
|
|
140
|
+
...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
|
|
141
|
+
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
142
|
+
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
|
|
143
|
+
"X-Recharge-Sdk-Version": "1.20.0",
|
|
144
|
+
...headers ? headers : {}
|
|
145
|
+
};
|
|
146
|
+
return request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
|
|
147
|
+
}
|
|
166
148
|
|
|
167
149
|
export { loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, sendPasswordlessCode, sendPasswordlessCodeAppProxy, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
|
|
168
150
|
//# sourceMappingURL=auth.js.map
|
package/dist/esm/api/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_customer_account_api_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const token = urlParams.get('token');\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/customers/${customerHash}/access`, {\n headers,\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n"],"names":["baseRequest"],"mappings":";;;;AAYA,eAAsB,oBAAyC,GAAA;AAC7D,EAAM,MAAA,EAAE,qBAAsB,EAAA,GAAI,UAAW,EAAA,CAAA;AAC7C,EAAA,MAA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B,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAM,MAAA,QAAA,GAAW,MAAMA,OAA2B,CAAA,MAAA,EAAQ,GAAG,eAAe,CAAA,WAAA,EAAc,YAAY,CAAW,OAAA,CAAA,EAAA;AAAA,IAC/G,OAAA;AAAA,IACA,IAAM,EAAA;AAAA,MACJ,KAAA;AAAA,MACA,IAAM,EAAA,eAAA;AAAA,KACR;AAAA,GACD,CAAA,CAAA;AAED,EAAA,OAAO,EAAE,QAAU,EAAA,QAAA,CAAS,SAAW,EAAA,UAAA,EAAY,SAAS,WAAY,EAAA,CAAA;AAC1E;;;;"}
|
|
1
|
+
{"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...options,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const token = urlParams.get('token');\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>('post', `/customers/${customerHash}/access`, {\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, {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 function getTimestampSecondsFromClient() {
|
|
|
9
9
|
}
|
|
10
10
|
async function getTimestampSecondsFromServer() {
|
|
11
11
|
try {
|
|
12
|
-
const { timestamp } = await shopifyAppProxyRequest("get", `${STORE_FRONT_MANAGER_URL}/t
|
|
13
|
-
headers: { "X-Recharge-App": "storefront-client" }
|
|
14
|
-
});
|
|
12
|
+
const { timestamp } = await shopifyAppProxyRequest("get", `${STORE_FRONT_MANAGER_URL}/t`);
|
|
15
13
|
return timestamp;
|
|
16
14
|
} catch (ex) {
|
|
17
15
|
console.error(`Fetch failed: ${ex}. Using client-side date.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid/non-secure';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { toLineItemProperty } from '../utils/bundle';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n}\n\nexport function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n if (!bundle) {\n return 'Bundle is not defined';\n }\n // Don't make bundle settings call due to merchant issues\n // const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n // if (!bundleSettings) {\n // return 'Bundle settings do not exist for the given product';\n // }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'getBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>(\n 'get',\n `/bundle_selections`,\n { query },\n getInternalSession(session, 'listBundleSelections')\n );\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n getInternalSession(session, 'createBundleSelection')\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n getInternalSession(session, 'updateBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'deleteBundleSelection')\n );\n}\n\nexport async function updateBundle(\n session: Session,\n purchase_item_id: string | number,\n updateRequest: UpdateBundlePurchaseItem,\n query?: BundlePurchaseItemParams\n): Promise<BundlePurchaseItem> {\n const { subscription } = await rechargeApiRequest<{ subscription: BundlePurchaseItem }>(\n 'put',\n '/bundles',\n {\n id: purchase_item_id,\n data: updateRequest,\n query,\n },\n getInternalSession(session, 'updateBundle')\n );\n\n return subscription;\n}\n"],"names":[],"mappings":";;;;;AAkBA,MAAM,uBAA0B,GAAA,8BAAA,CAAA;AAEhC,SAAS,6BAAwC,GAAA;AAI/C,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;AAAA,IACA,kBAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACA,EAAO,OAAA,gBAAA,CAAA;AACT,CAAA;AAEgB,SAAA,qBAAA,CAAsB,SAAkB,EAAoC,EAAA;AAC1F,EAAO,OAAA,kBAAA;AAAA,IACL,QAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACF,CAAA;AAEA,eAAsB,YACpB,CAAA,OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC7B,KAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,MACE,EAAI,EAAA,gBAAA;AAAA,MACJ,IAAM,EAAA,aAAA;AAAA,MACN,KAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid/non-secure';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { toLineItemProperty } from '../utils/bundle';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`);\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n}\n\nexport function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n if (!bundle) {\n return 'Bundle is not defined';\n }\n // Don't make bundle settings call due to merchant issues\n // const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n // if (!bundleSettings) {\n // return 'Bundle settings do not exist for the given product';\n // }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'getBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>(\n 'get',\n `/bundle_selections`,\n { query },\n getInternalSession(session, 'listBundleSelections')\n );\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n getInternalSession(session, 'createBundleSelection')\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n getInternalSession(session, 'updateBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'deleteBundleSelection')\n );\n}\n\nexport async function updateBundle(\n session: Session,\n purchase_item_id: string | number,\n updateRequest: UpdateBundlePurchaseItem,\n query?: BundlePurchaseItemParams\n): Promise<BundlePurchaseItem> {\n const { subscription } = await rechargeApiRequest<{ subscription: BundlePurchaseItem }>(\n 'put',\n '/bundles',\n {\n id: purchase_item_id,\n data: updateRequest,\n query,\n },\n getInternalSession(session, 'updateBundle')\n );\n\n return subscription;\n}\n"],"names":[],"mappings":";;;;;AAkBA,MAAM,uBAA0B,GAAA,8BAAA,CAAA;AAEhC,SAAS,6BAAwC,GAAA;AAI/C,EAAA,OAAO,IAAK,CAAA,IAAA,CAAK,IAAK,CAAA,GAAA,KAAQ,GAAI,CAAA,CAAA;AACpC,CAAA;AAEA,eAAe,6BAAiD,GAAA;AAK9D,EAAI,IAAA;AACF,IAAM,MAAA,EAAE,WAAc,GAAA,MAAM,uBAA8C,KAAO,EAAA,CAAA,EAAG,uBAAuB,CAAI,EAAA,CAAA,CAAA,CAAA;AAC/G,IAAO,OAAA,SAAA,CAAA;AAAA,WACA,EAAI,EAAA;AACX,IAAQ,OAAA,CAAA,KAAA,CAAM,CAAiB,cAAA,EAAA,EAAE,CAA2B,yBAAA,CAAA,CAAA,CAAA;AAC5D,IAAA,OAAO,6BAA8B,EAAA,CAAA;AAAA,GACvC;AACF,CAAA;AAEA,eAAsB,YAAY,MAAyC,EAAA;AACzE,EAAA,MAAM,OAAO,UAAW,EAAA,CAAA;AACxB,EAAM,MAAA,OAAA,GAAU,MAAM,cAAA,CAAe,MAAM,CAAA,CAAA;AAC3C,EAAA,IAAI,YAAY,IAAM,EAAA;AACpB,IAAM,MAAA,IAAI,MAAM,OAAO,CAAA,CAAA;AAAA,GACzB;AACA,EAAM,MAAA,gBAAA,GAAmB,MAAM,6BAA8B,EAAA,CAAA;AAC7D,EAAA,MAAM,aAAa,kBAAmB,CAAA;AAAA,IACpC,WAAW,MAAO,CAAA,iBAAA;AAAA,IAClB,OAAS,EAAA,gBAAA;AAAA,IACT,KAAO,EAAA,MAAA,CAAO,UAAW,CAAA,GAAA,CAAI,CAAQ,IAAA,KAAA;AACnC,MAA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,EAAA,EAAA,EACA,aAC0B,EAAA;AAC1B,EAAM,MAAA,EAAE,gBAAiB,EAAA,GAAI,MAAM,kBAAA;AAAA,IACjC,KAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,MACA,IAAM,EAAA,aAAA;AAAA,KACR;AAAA,IACA,kBAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACA,EAAO,OAAA,gBAAA,CAAA;AACT,CAAA;AAEgB,SAAA,qBAAA,CAAsB,SAAkB,EAAoC,EAAA;AAC1F,EAAO,OAAA,kBAAA;AAAA,IACL,QAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACF,CAAA;AAEA,eAAsB,YACpB,CAAA,OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC7B,KAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,MACE,EAAI,EAAA,gBAAA;AAAA,MACJ,IAAM,EAAA,aAAA;AAAA,MACN,KAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { rechargeApiRequest, getInternalSession } from '../utils/request.js';
|
|
2
|
+
import { updateCustomer } from './customer.js';
|
|
3
|
+
|
|
4
|
+
async function getCreditSummary(session, options) {
|
|
5
|
+
const id = session.customerId;
|
|
6
|
+
if (!id) {
|
|
7
|
+
throw new Error("Not logged in.");
|
|
8
|
+
}
|
|
9
|
+
const { credit_summary } = await rechargeApiRequest(
|
|
10
|
+
"get",
|
|
11
|
+
`/customers/${id}/credit_summary`,
|
|
12
|
+
{
|
|
13
|
+
query: { include: options?.include }
|
|
14
|
+
},
|
|
15
|
+
getInternalSession(session, "getCreditSummary")
|
|
16
|
+
);
|
|
17
|
+
return credit_summary;
|
|
18
|
+
}
|
|
19
|
+
function setApplyCreditsToNextCharge(session, { recurring }) {
|
|
20
|
+
const id = session.customerId;
|
|
21
|
+
if (!id) {
|
|
22
|
+
throw new Error("Not logged in.");
|
|
23
|
+
}
|
|
24
|
+
const updateOptions = {};
|
|
25
|
+
if (recurring !== void 0) {
|
|
26
|
+
updateOptions.apply_credit_to_next_recurring_charge = recurring;
|
|
27
|
+
}
|
|
28
|
+
return updateCustomer(getInternalSession(session, "setApplyCreditsToNextCharge"), updateOptions);
|
|
29
|
+
}
|
|
30
|
+
async function listCreditAccounts(session, query) {
|
|
31
|
+
const customer_id = session.customerId;
|
|
32
|
+
if (!customer_id) {
|
|
33
|
+
throw new Error("Not logged in.");
|
|
34
|
+
}
|
|
35
|
+
const response = await rechargeApiRequest(
|
|
36
|
+
"get",
|
|
37
|
+
"/credit_accounts",
|
|
38
|
+
{
|
|
39
|
+
query: { customer_id, ...query }
|
|
40
|
+
},
|
|
41
|
+
getInternalSession(session, "listCreditAccounts")
|
|
42
|
+
);
|
|
43
|
+
return response;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export { getCreditSummary, listCreditAccounts, setApplyCreditsToNextCharge };
|
|
47
|
+
//# sourceMappingURL=credit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credit.js","sources":["../../../src/api/credit.ts"],"sourcesContent":["import {\n ApplyCreditOptions,\n CreditAccountListParams,\n CreditAccountsResponse,\n Customer,\n CustomerCreditSummary,\n GetCreditSummaryOptions,\n Session,\n UpdateCustomerRequest,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport { updateCustomer } from './customer';\n\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${id}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n\nexport function setApplyCreditsToNextCharge(session: Session, { recurring }: ApplyCreditOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const updateOptions: UpdateCustomerRequest = {};\n if (recurring !== undefined) {\n updateOptions.apply_credit_to_next_recurring_charge = recurring;\n }\n return updateCustomer(getInternalSession(session, 'setApplyCreditsToNextCharge'), updateOptions);\n}\n\nexport async function listCreditAccounts(\n session: Session,\n query?: CreditAccountListParams\n): Promise<CreditAccountsResponse> {\n const customer_id = session.customerId;\n if (!customer_id) {\n throw new Error('Not logged in.');\n }\n const response = await rechargeApiRequest<CreditAccountsResponse>(\n 'get',\n '/credit_accounts',\n {\n query: { customer_id, ...query },\n },\n getInternalSession(session, 'listCreditAccounts')\n );\n return response;\n}\n"],"names":[],"mappings":";;;AAasB,eAAA,gBAAA,CACpB,SACA,OACgC,EAAA;AAChC,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,cAAe,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC/B,KAAA;AAAA,IACA,cAAc,EAAE,CAAA,eAAA,CAAA;AAAA,IAChB;AAAA,MACE,KAAO,EAAA,EAAE,OAAS,EAAA,OAAA,EAAS,OAAQ,EAAA;AAAA,KACrC;AAAA,IACA,kBAAA,CAAmB,SAAS,kBAAkB,CAAA;AAAA,GAChD,CAAA;AACA,EAAO,OAAA,cAAA,CAAA;AACT,CAAA;AAEO,SAAS,2BAA4B,CAAA,OAAA,EAAkB,EAAE,SAAA,EAAoD,EAAA;AAClH,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAA,MAAM,gBAAuC,EAAC,CAAA;AAC9C,EAAA,IAAI,cAAc,KAAW,CAAA,EAAA;AAC3B,IAAA,aAAA,CAAc,qCAAwC,GAAA,SAAA,CAAA;AAAA,GACxD;AACA,EAAA,OAAO,cAAe,CAAA,kBAAA,CAAmB,OAAS,EAAA,6BAA6B,GAAG,aAAa,CAAA,CAAA;AACjG,CAAA;AAEsB,eAAA,kBAAA,CACpB,SACA,KACiC,EAAA;AACjC,EAAA,MAAM,cAAc,OAAQ,CAAA,UAAA,CAAA;AAC5B,EAAA,IAAI,CAAC,WAAa,EAAA;AAChB,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAA,MAAM,WAAW,MAAM,kBAAA;AAAA,IACrB,KAAA;AAAA,IACA,kBAAA;AAAA,IACA;AAAA,MACE,KAAO,EAAA,EAAE,WAAa,EAAA,GAAG,KAAM,EAAA;AAAA,KACjC;AAAA,IACA,kBAAA,CAAmB,SAAS,oBAAoB,CAAA;AAAA,GAClD,CAAA;AACA,EAAO,OAAA,QAAA,CAAA;AACT;;;;"}
|
package/dist/esm/api/customer.js
CHANGED
|
@@ -42,11 +42,11 @@ async function getDeliverySchedule(session, query) {
|
|
|
42
42
|
);
|
|
43
43
|
return deliveries;
|
|
44
44
|
}
|
|
45
|
-
async function getCustomerPortalAccess(session) {
|
|
45
|
+
async function getCustomerPortalAccess(session, query) {
|
|
46
46
|
return rechargeApiRequest(
|
|
47
47
|
"get",
|
|
48
48
|
"/portal_access",
|
|
49
|
-
{},
|
|
49
|
+
{ query },
|
|
50
50
|
getInternalSession(session, "getCustomerPortalAccess")
|
|
51
51
|
);
|
|
52
52
|
}
|
|
@@ -95,21 +95,6 @@ async function sendCustomerNotification(session, notification, options) {
|
|
|
95
95
|
getInternalSession(session, "sendCustomerNotification")
|
|
96
96
|
);
|
|
97
97
|
}
|
|
98
|
-
async function getCreditSummary(session, options) {
|
|
99
|
-
const id = session.customerId;
|
|
100
|
-
if (!id) {
|
|
101
|
-
throw new Error("Not logged in.");
|
|
102
|
-
}
|
|
103
|
-
const { credit_summary } = await rechargeApiRequest(
|
|
104
|
-
"get",
|
|
105
|
-
`/customers/${id}/credit_summary`,
|
|
106
|
-
{
|
|
107
|
-
query: { include: options?.include }
|
|
108
|
-
},
|
|
109
|
-
getInternalSession(session, "getCreditSummary")
|
|
110
|
-
);
|
|
111
|
-
return credit_summary;
|
|
112
|
-
}
|
|
113
98
|
|
|
114
|
-
export { getActiveChurnLandingPageURL,
|
|
99
|
+
export { getActiveChurnLandingPageURL, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getGiftRedemptionLandingPageURL, sendCustomerNotification, updateCustomer };
|
|
115
100
|
//# sourceMappingURL=customer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n UpdateCustomerRequest,\n Session,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${id}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(session: Session): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n {},\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${redirectURL}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${redirectURL}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n const data = customerNotificationMap[notification];\n if (!data) {\n throw new Error('Notification not supported.');\n }\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${customerId}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${id}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n UpdateCustomerRequest,\n Session,\n CustomerPortalAccessOptions,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${id}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(\n session: Session,\n query?: CustomerPortalAccessOptions\n): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n { query },\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${redirectURL}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${redirectURL}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n const data = customerNotificationMap[notification];\n if (!data) {\n throw new Error('Notification not supported.');\n }\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${customerId}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\n/** @deprecated Use `getCreditSummary` on credit instead */\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${id}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":[],"mappings":";;AAmBsB,eAAA,WAAA,CAAY,SAAkB,OAAiD,EAAA;AACnG,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,QAAS,EAAA,GAAI,MAAM,kBAAA;AAAA,IACzB,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,MACA,KAAO,EAAA,EAAE,OAAS,EAAA,OAAA,EAAS,OAAQ,EAAA;AAAA,KACrC;AAAA,IACA,kBAAA,CAAmB,SAAS,aAAa,CAAA;AAAA,GAC3C,CAAA;AACA,EAAO,OAAA,QAAA,CAAA;AACT,CAAA;AAEsB,eAAA,cAAA,CAAe,SAAkB,aAAyD,EAAA;AAC9G,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,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A;AAAA,OACjB;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,0BAA0B,CAAA;AAAA,GACxD,CAAA;AACF;;;;"}
|
package/dist/esm/index.js
CHANGED
|
@@ -4,7 +4,8 @@ export { createBundleSelection, deleteBundleSelection, getBundleId, getBundleSel
|
|
|
4
4
|
export { getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, resetCDNCache } from './api/cdn.js';
|
|
5
5
|
export { applyDiscountToCharge, getCharge, listCharges, processCharge, removeDiscountsFromCharge, skipCharge, unskipCharge } from './api/charge.js';
|
|
6
6
|
export { getCollection, listCollectionProducts, listCollections } from './api/collection.js';
|
|
7
|
-
export {
|
|
7
|
+
export { getCreditSummary, listCreditAccounts, setApplyCreditsToNextCharge } from './api/credit.js';
|
|
8
|
+
export { getActiveChurnLandingPageURL, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getGiftRedemptionLandingPageURL, sendCustomerNotification, updateCustomer } from './api/customer.js';
|
|
8
9
|
export { getGiftPurchase, listGiftPurchases } from './api/gift.js';
|
|
9
10
|
export { activateMembership, cancelMembership, changeMembership, getMembership, listMemberships } from './api/membership.js';
|
|
10
11
|
export { getMembershipProgram, listMembershipPrograms } from './api/membershipProgram.js';
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;"}
|
package/dist/esm/utils/init.js
CHANGED
|
@@ -47,6 +47,8 @@ function initRecharge(opt = {}) {
|
|
|
47
47
|
storeIdentifier: getStoreIdentifier(opt.storeIdentifier),
|
|
48
48
|
loginRetryFn: opt.loginRetryFn,
|
|
49
49
|
storefrontAccessToken,
|
|
50
|
+
appName: opt.appName,
|
|
51
|
+
appVersion: opt.appVersion,
|
|
50
52
|
environment: hiddenOpts.environment ? hiddenOpts.environment : "prod",
|
|
51
53
|
environmentUri: hiddenOpts.environmentUri,
|
|
52
54
|
customerHash: hiddenOpts.customerHash
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","sources":["../../../src/utils/init.ts"],"sourcesContent":["import { resetCDNCache } from '../api/cdn';\nimport { StorefrontOptions, CRUDRequestOptions, GetRequestOptions, InitOptions } from '../types';\nimport { setOptions } from './options';\nimport { request } from './request';\n\n/**\n * @internal\n * @deprecated will be removed in next version\n */\nexport const api = {\n get<T>(url: string, requestOptions?: GetRequestOptions): Promise<T> {\n return request<T>('get', url, requestOptions);\n },\n post<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('post', url, requestOptions);\n },\n put<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('put', url, requestOptions);\n },\n delete<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('delete', url, requestOptions);\n },\n};\n\n/**\n * Uses passed in storeIdentifier, but if it's not passed in will try to infer it.\n * Currently it will only infer if we are in the context of a Shopify store. This will not infer headless or hosted yet.\n */\nfunction getStoreIdentifier(storeIdentifier?: string): string {\n if (storeIdentifier) {\n return storeIdentifier;\n }\n\n // Infer's when on Shopify store (non headless)\n if (window?.Shopify?.shop) {\n return window.Shopify.shop;\n }\n\n // Domain exists on hosted themes. If it doesn't for some reason, get the subdomain and create the identifier\n let domain = window?.domain;\n if (!domain) {\n const subdomain = location?.href\n .match(/(?:http[s]*:\\/\\/)*(.*?)\\.(?=admin\\.rechargeapps\\.com)/i)?.[1]\n .replace(/-sp$/, '');\n if (subdomain) {\n domain = `${subdomain}.myshopify.com`;\n }\n }\n\n // Infer's when on Recharge hosted\n if (domain) {\n return domain;\n }\n\n throw new Error(`No storeIdentifier was passed into init.`);\n}\n\nexport function initRecharge(opt: InitOptions = {}) {\n const hiddenOpts = opt as StorefrontOptions;\n const { storefrontAccessToken } = opt;\n if (storefrontAccessToken && !storefrontAccessToken.startsWith('strfnt')) {\n throw new Error(\n 'Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.'\n );\n }\n setOptions({\n storeIdentifier: getStoreIdentifier(opt.storeIdentifier),\n loginRetryFn: opt.loginRetryFn,\n storefrontAccessToken,\n environment: hiddenOpts.environment ? hiddenOpts.environment : 'prod',\n environmentUri: hiddenOpts.environmentUri,\n customerHash: hiddenOpts.customerHash,\n });\n\n // When init is called again, reset the cache to make sure we don't have the old cache around\n resetCDNCache();\n}\n"],"names":[],"mappings":";;;;AASO,MAAM,GAAM,GAAA;AAAA,EACjB,GAAA,CAAO,KAAa,cAAgD,EAAA;AAClE,IAAO,OAAA,OAAA,CAAW,KAAO,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC9C;AAAA,EACA,IAAA,CAAQ,KAAa,cAAiD,EAAA;AACpE,IAAO,OAAA,OAAA,CAAW,MAAQ,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC/C;AAAA,EACA,GAAA,CAAO,KAAa,cAAiD,EAAA;AACnE,IAAO,OAAA,OAAA,CAAW,KAAO,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC9C;AAAA,EACA,MAAA,CAAU,KAAa,cAAiD,EAAA;AACtE,IAAO,OAAA,OAAA,CAAW,QAAU,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GACjD;AACF,EAAA;AAMA,SAAS,mBAAmB,eAAkC,EAAA;AAC5D,EAAA,IAAI,eAAiB,EAAA;AACnB,IAAO,OAAA,eAAA,CAAA;AAAA,GACT;AAGA,EAAI,IAAA,MAAA,EAAQ,SAAS,IAAM,EAAA;AACzB,IAAA,OAAO,OAAO,OAAQ,CAAA,IAAA,CAAA;AAAA,GACxB;AAGA,EAAA,IAAI,SAAS,MAAQ,EAAA,MAAA,CAAA;AACrB,EAAA,IAAI,CAAC,MAAQ,EAAA;AACX,IAAM,MAAA,SAAA,GAAY,QAAU,EAAA,IAAA,CACzB,KAAM,CAAA,wDAAwD,IAAI,CAAC,CAAA,CACnE,OAAQ,CAAA,MAAA,EAAQ,EAAE,CAAA,CAAA;AACrB,IAAA,IAAI,SAAW,EAAA;AACb,MAAA,MAAA,GAAS,GAAG,SAAS,CAAA,cAAA,CAAA,CAAA;AAAA,KACvB;AAAA,GACF;AAGA,EAAA,IAAI,MAAQ,EAAA;AACV,IAAO,OAAA,MAAA,CAAA;AAAA,GACT;AAEA,EAAM,MAAA,IAAI,MAAM,CAA0C,wCAAA,CAAA,CAAA,CAAA;AAC5D,CAAA;AAEgB,SAAA,YAAA,CAAa,GAAmB,GAAA,EAAI,EAAA;AAClD,EAAA,MAAM,UAAa,GAAA,GAAA,CAAA;AACnB,EAAM,MAAA,EAAE,uBAA0B,GAAA,GAAA,CAAA;AAClC,EAAA,IAAI,qBAAyB,IAAA,CAAC,qBAAsB,CAAA,UAAA,CAAW,QAAQ,CAAG,EAAA;AACxE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uKAAA;AAAA,KACF,CAAA;AAAA,GACF;AACA,EAAW,UAAA,CAAA;AAAA,IACT,eAAA,EAAiB,kBAAmB,CAAA,GAAA,CAAI,eAAe,CAAA;AAAA,IACvD,cAAc,GAAI,CAAA,YAAA;AAAA,IAClB,qBAAA;AAAA,IACA,WAAa,EAAA,UAAA,CAAW,WAAc,GAAA,UAAA,CAAW,WAAc,GAAA,MAAA;AAAA,IAC/D,gBAAgB,UAAW,CAAA,cAAA;AAAA,IAC3B,cAAc,UAAW,CAAA,YAAA;AAAA,GAC1B,CAAA,CAAA;AAGD,EAAc,aAAA,EAAA,CAAA;AAChB;;;;"}
|
|
1
|
+
{"version":3,"file":"init.js","sources":["../../../src/utils/init.ts"],"sourcesContent":["import { resetCDNCache } from '../api/cdn';\nimport { StorefrontOptions, CRUDRequestOptions, GetRequestOptions, InitOptions } from '../types';\nimport { setOptions } from './options';\nimport { request } from './request';\n\n/**\n * @internal\n * @deprecated will be removed in next version\n */\nexport const api = {\n get<T>(url: string, requestOptions?: GetRequestOptions): Promise<T> {\n return request<T>('get', url, requestOptions);\n },\n post<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('post', url, requestOptions);\n },\n put<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('put', url, requestOptions);\n },\n delete<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('delete', url, requestOptions);\n },\n};\n\n/**\n * Uses passed in storeIdentifier, but if it's not passed in will try to infer it.\n * Currently it will only infer if we are in the context of a Shopify store. This will not infer headless or hosted yet.\n */\nfunction getStoreIdentifier(storeIdentifier?: string): string {\n if (storeIdentifier) {\n return storeIdentifier;\n }\n\n // Infer's when on Shopify store (non headless)\n if (window?.Shopify?.shop) {\n return window.Shopify.shop;\n }\n\n // Domain exists on hosted themes. If it doesn't for some reason, get the subdomain and create the identifier\n let domain = window?.domain;\n if (!domain) {\n const subdomain = location?.href\n .match(/(?:http[s]*:\\/\\/)*(.*?)\\.(?=admin\\.rechargeapps\\.com)/i)?.[1]\n .replace(/-sp$/, '');\n if (subdomain) {\n domain = `${subdomain}.myshopify.com`;\n }\n }\n\n // Infer's when on Recharge hosted\n if (domain) {\n return domain;\n }\n\n throw new Error(`No storeIdentifier was passed into init.`);\n}\n\nexport function initRecharge(opt: InitOptions = {}) {\n const hiddenOpts = opt as StorefrontOptions;\n const { storefrontAccessToken } = opt;\n if (storefrontAccessToken && !storefrontAccessToken.startsWith('strfnt')) {\n throw new Error(\n 'Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.'\n );\n }\n setOptions({\n storeIdentifier: getStoreIdentifier(opt.storeIdentifier),\n loginRetryFn: opt.loginRetryFn,\n storefrontAccessToken,\n appName: opt.appName,\n appVersion: opt.appVersion,\n environment: hiddenOpts.environment ? hiddenOpts.environment : 'prod',\n environmentUri: hiddenOpts.environmentUri,\n customerHash: hiddenOpts.customerHash,\n });\n\n // When init is called again, reset the cache to make sure we don't have the old cache around\n resetCDNCache();\n}\n"],"names":[],"mappings":";;;;AASO,MAAM,GAAM,GAAA;AAAA,EACjB,GAAA,CAAO,KAAa,cAAgD,EAAA;AAClE,IAAO,OAAA,OAAA,CAAW,KAAO,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC9C;AAAA,EACA,IAAA,CAAQ,KAAa,cAAiD,EAAA;AACpE,IAAO,OAAA,OAAA,CAAW,MAAQ,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC/C;AAAA,EACA,GAAA,CAAO,KAAa,cAAiD,EAAA;AACnE,IAAO,OAAA,OAAA,CAAW,KAAO,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GAC9C;AAAA,EACA,MAAA,CAAU,KAAa,cAAiD,EAAA;AACtE,IAAO,OAAA,OAAA,CAAW,QAAU,EAAA,GAAA,EAAK,cAAc,CAAA,CAAA;AAAA,GACjD;AACF,EAAA;AAMA,SAAS,mBAAmB,eAAkC,EAAA;AAC5D,EAAA,IAAI,eAAiB,EAAA;AACnB,IAAO,OAAA,eAAA,CAAA;AAAA,GACT;AAGA,EAAI,IAAA,MAAA,EAAQ,SAAS,IAAM,EAAA;AACzB,IAAA,OAAO,OAAO,OAAQ,CAAA,IAAA,CAAA;AAAA,GACxB;AAGA,EAAA,IAAI,SAAS,MAAQ,EAAA,MAAA,CAAA;AACrB,EAAA,IAAI,CAAC,MAAQ,EAAA;AACX,IAAM,MAAA,SAAA,GAAY,QAAU,EAAA,IAAA,CACzB,KAAM,CAAA,wDAAwD,IAAI,CAAC,CAAA,CACnE,OAAQ,CAAA,MAAA,EAAQ,EAAE,CAAA,CAAA;AACrB,IAAA,IAAI,SAAW,EAAA;AACb,MAAA,MAAA,GAAS,GAAG,SAAS,CAAA,cAAA,CAAA,CAAA;AAAA,KACvB;AAAA,GACF;AAGA,EAAA,IAAI,MAAQ,EAAA;AACV,IAAO,OAAA,MAAA,CAAA;AAAA,GACT;AAEA,EAAM,MAAA,IAAI,MAAM,CAA0C,wCAAA,CAAA,CAAA,CAAA;AAC5D,CAAA;AAEgB,SAAA,YAAA,CAAa,GAAmB,GAAA,EAAI,EAAA;AAClD,EAAA,MAAM,UAAa,GAAA,GAAA,CAAA;AACnB,EAAM,MAAA,EAAE,uBAA0B,GAAA,GAAA,CAAA;AAClC,EAAA,IAAI,qBAAyB,IAAA,CAAC,qBAAsB,CAAA,UAAA,CAAW,QAAQ,CAAG,EAAA;AACxE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uKAAA;AAAA,KACF,CAAA;AAAA,GACF;AACA,EAAW,UAAA,CAAA;AAAA,IACT,eAAA,EAAiB,kBAAmB,CAAA,GAAA,CAAI,eAAe,CAAA;AAAA,IACvD,cAAc,GAAI,CAAA,YAAA;AAAA,IAClB,qBAAA;AAAA,IACA,SAAS,GAAI,CAAA,OAAA;AAAA,IACb,YAAY,GAAI,CAAA,UAAA;AAAA,IAChB,WAAa,EAAA,UAAA,CAAW,WAAc,GAAA,UAAA,CAAW,WAAc,GAAA,MAAA;AAAA,IAC/D,gBAAgB,UAAW,CAAA,cAAA;AAAA,IAC3B,cAAc,UAAW,CAAA,YAAA;AAAA,GAC1B,CAAA,CAAA;AAGD,EAAc,aAAA,EAAA,CAAA;AAChB;;;;"}
|
|
@@ -24,13 +24,16 @@ async function cdnRequest(method, url, requestOptions = {}) {
|
|
|
24
24
|
return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);
|
|
25
25
|
}
|
|
26
26
|
async function rechargeApiRequest(method, url, { id, query, data, headers } = {}, session) {
|
|
27
|
-
const { environment, environmentUri, storeIdentifier, loginRetryFn } = getOptions();
|
|
27
|
+
const { environment, environmentUri, storeIdentifier, loginRetryFn, appName, appVersion } = getOptions();
|
|
28
28
|
const token = session.apiToken;
|
|
29
29
|
const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);
|
|
30
30
|
const reqHeaders = {
|
|
31
31
|
"X-Recharge-Access-Token": token,
|
|
32
32
|
"X-Recharge-Version": "2021-11",
|
|
33
|
-
"X-Recharge-Fn": session.internalFnCall,
|
|
33
|
+
"X-Recharge-Sdk-Fn": session.internalFnCall,
|
|
34
|
+
...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
|
|
35
|
+
...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
|
|
36
|
+
"X-Recharge-Sdk-Version": "1.20.0",
|
|
34
37
|
"X-Request-Id": session.internalRequestId,
|
|
35
38
|
...headers ? headers : {}
|
|
36
39
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport { nanoid } from 'nanoid/non-secure';\nimport stringify from 'qs/lib/stringify';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\n });\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const { environment, environmentUri, storeIdentifier, loginRetryFn } = getOptions();\n const token = session.apiToken;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Fn': session.internalFnCall,\n 'X-Request-Id': session.internalRequestId,\n ...(headers ? headers : {}),\n };\n\n const localQuery = {\n shop_url: storeIdentifier,\n ...(query as any),\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {\n // call loginRetryFn and retry request on 401\n return loginRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n }\n throw error;\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n reqUrl = [reqUrl, `${id}`.trim()].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["session"],"mappings":";;;;;;;AAUA,SAAS,eAAe,GAAsB,EAAA;AAC5C,EAAA,OAAO,UAAU,GAAK,EAAA;AAAA,IACpB,MAAQ,EAAA,KAAA;AAAA,IACR,OAAS,EAAA,KAAA;AAAA,IACT,WAAa,EAAA,OAAA;AAAA,GACd,CAAA,CAAA;AACH,CAAA;AAGgB,SAAA,kBAAA,CAAmB,SAAoC,MAAiC,EAAA;AACtG,EAAO,OAAA;AAAA,IACL,GAAG,OAAA;AAAA,IACH,cAAA,EAAiB,QAA4B,cAAkB,IAAA,MAAA;AAAA,IAC/D,iBAAA,EAAoB,OAA4B,CAAA,iBAAA,IAAqB,MAAO,EAAA;AAAA,GAC9E,CAAA;AACF,CAAA;AAEA,eAAsB,UAAc,CAAA,MAAA,EAAgB,GAAa,EAAA,cAAA,GAAiC,EAAgB,EAAA;AAChH,EAAA,MAAM,OAAO,UAAW,EAAA,CAAA;AACxB,EAAA,OAAO,OAAQ,CAAA,MAAA,EAAQ,CAAG,EAAA,gBAAA,CAAiB,IAAK,CAAA,WAAW,CAAC,CAAA,OAAA,EAAU,IAAK,CAAA,eAAe,CAAG,EAAA,GAAG,IAAI,cAAc,CAAA,CAAA;AACpH,CAAA;AAEsB,eAAA,kBAAA,CACpB,MACA,EAAA,GAAA,EACA,EAAE,EAAA,EAAI,KAAO,EAAA,IAAA,EAAM,OAAQ,EAAA,GAAoB,EAAC,EAChD,OACY,EAAA;AACZ,
|
|
1
|
+
{"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport { nanoid } from 'nanoid/non-secure';\nimport stringify from 'qs/lib/stringify';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\n });\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const { environment, environmentUri, storeIdentifier, loginRetryFn, appName, appVersion } = getOptions();\n const token = session.apiToken;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(headers ? headers : {}),\n };\n\n const localQuery = {\n shop_url: storeIdentifier,\n ...(query as any),\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {\n // call loginRetryFn and retry request on 401\n return loginRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n }\n throw error;\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n reqUrl = [reqUrl, `${id}`.trim()].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["session"],"mappings":";;;;;;;AAUA,SAAS,eAAe,GAAsB,EAAA;AAC5C,EAAA,OAAO,UAAU,GAAK,EAAA;AAAA,IACpB,MAAQ,EAAA,KAAA;AAAA,IACR,OAAS,EAAA,KAAA;AAAA,IACT,WAAa,EAAA,OAAA;AAAA,G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