@memberstack/dom 2.0.2-beta.0 → 2.0.3

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.
Files changed (87) hide show
  1. package/lib/index.d.mts +76 -61
  2. package/lib/index.d.ts +76 -61
  3. package/lib/index.js +840 -61
  4. package/lib/index.mjs +840 -61
  5. package/lib/{models-CTRKogoR.d.ts → models-CFT_ABd5.d.ts} +2 -2
  6. package/lib/testing/index.d.mts +25 -2
  7. package/lib/testing/index.d.ts +25 -2
  8. package/lib/testing/index.js +28 -6
  9. package/lib/testing/index.mjs +26 -5
  10. package/package.json +1 -1
  11. package/lib/auth/index.d.mts +0 -63
  12. package/lib/auth/index.d.ts +0 -63
  13. package/lib/auth/index.global.js +0 -244
  14. package/lib/auth/index.js +0 -161
  15. package/lib/auth/index.mjs +0 -123
  16. package/lib/constants/endpoints.d.mts +0 -5
  17. package/lib/constants/endpoints.d.ts +0 -5
  18. package/lib/constants/endpoints.global.js +0 -29
  19. package/lib/constants/endpoints.js +0 -32
  20. package/lib/constants/endpoints.mjs +0 -7
  21. package/lib/methods/dom/index.d.mts +0 -2
  22. package/lib/methods/dom/index.d.ts +0 -2
  23. package/lib/methods/dom/index.global.js +0 -2
  24. package/lib/methods/dom/index.js +0 -1
  25. package/lib/methods/dom/index.mjs +0 -0
  26. package/lib/methods/dom/main-dom.d.mts +0 -2
  27. package/lib/methods/dom/main-dom.d.ts +0 -2
  28. package/lib/methods/dom/main-dom.global.js +0 -30620
  29. package/lib/methods/dom/main-dom.js +0 -15611
  30. package/lib/methods/dom/main-dom.mjs +0 -15593
  31. package/lib/methods/dom/methods.d.mts +0 -100
  32. package/lib/methods/dom/methods.d.ts +0 -100
  33. package/lib/methods/dom/methods.global.js +0 -30827
  34. package/lib/methods/dom/methods.js +0 -335
  35. package/lib/methods/dom/methods.mjs +0 -302
  36. package/lib/methods/index.d.mts +0 -185
  37. package/lib/methods/index.d.ts +0 -185
  38. package/lib/methods/index.global.js +0 -46361
  39. package/lib/methods/index.js +0 -2530
  40. package/lib/methods/index.mjs +0 -2500
  41. package/lib/methods/requests/index.d.mts +0 -912
  42. package/lib/methods/requests/index.d.ts +0 -912
  43. package/lib/methods/requests/index.global.js +0 -15553
  44. package/lib/methods/requests/index.js +0 -2145
  45. package/lib/methods/requests/index.mjs +0 -2110
  46. package/lib/methods/requests/requests.d.mts +0 -43
  47. package/lib/methods/requests/requests.d.ts +0 -43
  48. package/lib/methods/requests/requests.global.js +0 -14528
  49. package/lib/methods/requests/requests.js +0 -244
  50. package/lib/methods/requests/requests.mjs +0 -210
  51. package/lib/models-BmZS-mc4.d.ts +0 -193
  52. package/lib/models-le7xaT4H.d.ts +0 -193
  53. package/lib/types/index.d.mts +0 -5
  54. package/lib/types/index.d.ts +0 -5
  55. package/lib/types/index.global.js +0 -19
  56. package/lib/types/index.js +0 -18
  57. package/lib/types/index.mjs +0 -0
  58. package/lib/types/params.d.mts +0 -946
  59. package/lib/types/params.d.ts +0 -946
  60. package/lib/types/params.global.js +0 -19
  61. package/lib/types/params.js +0 -18
  62. package/lib/types/params.mjs +0 -0
  63. package/lib/types/payloads.d.mts +0 -342
  64. package/lib/types/payloads.d.ts +0 -342
  65. package/lib/types/payloads.global.js +0 -19
  66. package/lib/types/payloads.js +0 -18
  67. package/lib/types/payloads.mjs +0 -0
  68. package/lib/types/translations.d.mts +0 -101
  69. package/lib/types/translations.d.ts +0 -101
  70. package/lib/types/translations.global.js +0 -19
  71. package/lib/types/translations.js +0 -18
  72. package/lib/types/translations.mjs +0 -0
  73. package/lib/types/utils/payloads.d.mts +0 -297
  74. package/lib/types/utils/payloads.d.ts +0 -297
  75. package/lib/types/utils/payloads.global.js +0 -19
  76. package/lib/types/utils/payloads.js +0 -18
  77. package/lib/types/utils/payloads.mjs +0 -0
  78. package/lib/utils/cookies.d.mts +0 -13
  79. package/lib/utils/cookies.d.ts +0 -13
  80. package/lib/utils/cookies.global.js +0 -261
  81. package/lib/utils/cookies.js +0 -190
  82. package/lib/utils/cookies.mjs +0 -148
  83. package/lib/utils/defaultMessageBox.d.mts +0 -5
  84. package/lib/utils/defaultMessageBox.d.ts +0 -5
  85. package/lib/utils/defaultMessageBox.global.js +0 -125
  86. package/lib/utils/defaultMessageBox.js +0 -130
  87. package/lib/utils/defaultMessageBox.mjs +0 -103
@@ -1,2145 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
- var __spreadValues = (a, b) => {
14
- for (var prop in b || (b = {}))
15
- if (__hasOwnProp.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- if (__getOwnPropSymbols)
18
- for (var prop of __getOwnPropSymbols(b)) {
19
- if (__propIsEnum.call(b, prop))
20
- __defNormalProp(a, prop, b[prop]);
21
- }
22
- return a;
23
- };
24
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
- var __export = (target, all) => {
26
- for (var name in all)
27
- __defProp(target, name, { get: all[name], enumerable: true });
28
- };
29
- var __copyProps = (to, from, except, desc) => {
30
- if (from && typeof from === "object" || typeof from === "function") {
31
- for (let key of __getOwnPropNames(from))
32
- if (!__hasOwnProp.call(to, key) && key !== except)
33
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
- }
35
- return to;
36
- };
37
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
- // If the importer is in node compatibility mode or this is not an ESM
39
- // file that has been converted to a CommonJS file using a Babel-
40
- // compatible transform (i.e. "__esModule" has not been set), then set
41
- // "default" to the CommonJS "module.exports" for node compatibility.
42
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
- mod
44
- ));
45
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
- var __async = (__this, __arguments, generator) => {
47
- return new Promise((resolve, reject) => {
48
- var fulfilled = (value) => {
49
- try {
50
- step(generator.next(value));
51
- } catch (e) {
52
- reject(e);
53
- }
54
- };
55
- var rejected = (value) => {
56
- try {
57
- step(generator.throw(value));
58
- } catch (e) {
59
- reject(e);
60
- }
61
- };
62
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
63
- step((generator = generator.apply(__this, __arguments)).next());
64
- });
65
- };
66
-
67
- // src/methods/requests/index.ts
68
- var requests_exports = {};
69
- __export(requests_exports, {
70
- getSessionDurationDays: () => getSessionDurationDays,
71
- initRequest: () => initRequest
72
- });
73
- module.exports = __toCommonJS(requests_exports);
74
-
75
- // src/methods/requests/requests.ts
76
- var import_axios = __toESM(require("axios"));
77
-
78
- // src/constants/endpoints.ts
79
- var endpoints = {
80
- API: "http://localhost:3005"
81
- };
82
-
83
- // src/utils/cookies.ts
84
- var import_js_cookie = __toESM(require("js-cookie"));
85
- var memberAuthTokenName = "_ms-mid";
86
- function isLocalStorageAvailable() {
87
- try {
88
- localStorage.setItem("test", "test");
89
- localStorage.removeItem("test");
90
- return true;
91
- } catch (e) {
92
- return false;
93
- }
94
- }
95
- var localStorageAvailable = isLocalStorageAvailable();
96
- var useCookies = false;
97
- var setCookieOnRootDomain = false;
98
- var apiDomain = "";
99
- var extractDomainFromHostname = (hostname) => {
100
- var _a, _b;
101
- const hostnameParts = hostname.split(".");
102
- const isCountryCodeTLD = hostnameParts.length >= 4 && ((_b = (_a = hostnameParts[hostnameParts.length - 2]) == null ? void 0 : _a.length) != null ? _b : 0) <= 3;
103
- if (isCountryCodeTLD) {
104
- return hostnameParts.slice(-3).join(".");
105
- } else {
106
- return hostnameParts.slice(-2).join(".");
107
- }
108
- };
109
- var useCookiesValid = () => {
110
- if (!useCookies)
111
- return false;
112
- if (setCookieOnRootDomain) {
113
- const apiDomainHost = extractDomainFromHostname(apiDomain);
114
- const currentHost = extractDomainFromHostname(window.location.hostname);
115
- return apiDomainHost === currentHost;
116
- }
117
- return true;
118
- };
119
- var setMemberToken = (token, expires) => {
120
- if (localStorageAvailable && useCookiesValid() === false) {
121
- localStorage.setItem(memberAuthTokenName, token);
122
- } else {
123
- const domain = extractDomainFromHostname(window.location.hostname);
124
- import_js_cookie.default.set(memberAuthTokenName, token, __spreadValues({
125
- expires: expires && Number(expires) || 14,
126
- sameSite: "strict"
127
- }, setCookieOnRootDomain && { domain }));
128
- }
129
- };
130
- var removeMemberToken = () => {
131
- if (localStorageAvailable) {
132
- localStorage.removeItem(memberAuthTokenName);
133
- }
134
- const domain = extractDomainFromHostname(window.location.hostname);
135
- import_js_cookie.default.set(memberAuthTokenName, "", __spreadValues({
136
- expires: -1,
137
- sameSite: "strict"
138
- }, setCookieOnRootDomain && { domain }));
139
- import_js_cookie.default.set(memberAuthTokenName, "", {
140
- expires: -1,
141
- sameSite: "strict"
142
- });
143
- };
144
- var getMemberToken = () => {
145
- if (localStorageAvailable) {
146
- const memAuthToken = localStorage.getItem(memberAuthTokenName);
147
- if (memAuthToken)
148
- return memAuthToken;
149
- }
150
- return import_js_cookie.default.get(memberAuthTokenName);
151
- };
152
- var getSessionId = () => {
153
- if (typeof window === "undefined")
154
- return null;
155
- const sessionId = window.localStorage.getItem("ms_session_id");
156
- if (!sessionId || sessionId.length > 26) {
157
- window.localStorage.removeItem("ms_session_id");
158
- return null;
159
- }
160
- return sessionId;
161
- };
162
- var setSessionId = (sessionId) => {
163
- if (typeof window !== "undefined") {
164
- window.localStorage.setItem("ms_session_id", sessionId);
165
- } else {
166
- console.warn("setSessionId: window is not defined");
167
- }
168
- };
169
- var removeSessionId = () => {
170
- if (typeof window !== "undefined") {
171
- window.localStorage.removeItem("ms_session_id");
172
- } else {
173
- console.warn("removeSessionId: window is not defined");
174
- }
175
- };
176
-
177
- // src/methods/requests/requests.ts
178
- var createRequestHandler = ({
179
- publicKey,
180
- appId,
181
- token,
182
- customEndpoint
183
- }) => {
184
- return {
185
- sendRequest: (data, options) => __async(void 0, null, function* () {
186
- var _a, _b, _c, _d, _e, _f, _g, _h;
187
- try {
188
- const { url } = data;
189
- const memberToken = getMemberToken();
190
- const sessionToken = getSessionId();
191
- const authHeader = [
192
- (_b = (_a = data.headers) == null ? void 0 : _a["Authorization"]) == null ? void 0 : _b.replace("Bearer ", ""),
193
- memberToken,
194
- options == null ? void 0 : options.token
195
- ].find((x) => x);
196
- const formattedUrl = `${customEndpoint || endpoints.API}${url}`;
197
- const res = yield (0, import_axios.default)({
198
- method: data.method,
199
- data: data.data,
200
- url: formattedUrl,
201
- headers: __spreadProps(__spreadValues(__spreadValues(__spreadProps(__spreadValues(__spreadValues(__spreadValues({}, authHeader && { authorization: `Bearer ${authHeader}` }), publicKey && { ["X-API-Key" /* API_KEY */]: publicKey }), appId && { ["X-APP-ID" /* APP_ID */]: appId }), {
202
- ["X-User-Agent" /* USER_AGENT */]: "@memberstack/client@1.2.0"
203
- }), data.contentType && { "Content-Type": data.contentType }), sessionToken && {
204
- ["X-Session-ID" /* SESSION_ID */]: sessionToken
205
- }), {
206
- "referring-path": window.location.pathname
207
- }),
208
- withCredentials: true
209
- });
210
- if ((_c = res == null ? void 0 : res.headers) == null ? void 0 : _c["ms-mid"]) {
211
- token = res.headers["ms-mid"];
212
- }
213
- if ((_d = res == null ? void 0 : res.data) == null ? void 0 : _d.error) {
214
- if (res.data.error.name === "JsonWebTokenError") {
215
- throw {
216
- code: "client/invalid-token",
217
- message: "An invalid token has been provided. Please make sure the token is valid."
218
- };
219
- }
220
- throw (_e = res.data) == null ? void 0 : _e.error;
221
- }
222
- return res == null ? void 0 : res.data;
223
- } catch (e) {
224
- const error = e;
225
- if (!error.response)
226
- throw e;
227
- throw ((_g = (_f = error.response) == null ? void 0 : _f.data) == null ? void 0 : _g.error) || ((_h = error.response) == null ? void 0 : _h.data);
228
- }
229
- }),
230
- sendRequestWithFetch: (data, options) => __async(void 0, null, function* () {
231
- var _a, _b;
232
- try {
233
- const { url, method, data: bodyData, headers, contentType } = data;
234
- const memberToken = getMemberToken();
235
- const authHeader = [
236
- (_a = headers == null ? void 0 : headers["Authorization"]) == null ? void 0 : _a.replace("Bearer ", ""),
237
- memberToken,
238
- options == null ? void 0 : options.token
239
- ].find((x) => x);
240
- const formattedUrl = `${customEndpoint || endpoints.API}${url}`;
241
- const fetchHeaders = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, authHeader && { Authorization: `Bearer ${authHeader}` }), publicKey && { ["X-API-Key" /* API_KEY */]: publicKey }), appId && { ["X-APP-ID" /* APP_ID */]: appId }), {
242
- ["X-User-Agent" /* USER_AGENT */]: "@memberstack/client@1.2.0",
243
- "Content-Type": "application/json",
244
- Referer: window.location.href
245
- });
246
- const response = yield fetch(formattedUrl, {
247
- method,
248
- headers: fetchHeaders,
249
- body: bodyData ? JSON.stringify(bodyData) : void 0,
250
- credentials: "include",
251
- keepalive: true
252
- // Keeps the connection open for further requests
253
- });
254
- const contentTypeHeader = response.headers.get("content-type");
255
- let result;
256
- if (contentTypeHeader == null ? void 0 : contentTypeHeader.includes("application/json")) {
257
- result = yield response.json();
258
- } else if (contentTypeHeader == null ? void 0 : contentTypeHeader.includes("text")) {
259
- result = yield response.text();
260
- } else if (response.status === 204) {
261
- result = null;
262
- } else {
263
- result = yield response.text();
264
- }
265
- if (response.headers.get("ms-mid")) {
266
- token = response.headers.get("ms-mid");
267
- }
268
- if (!response.ok) {
269
- if (((_b = result == null ? void 0 : result.error) == null ? void 0 : _b.name) === "JsonWebTokenError") {
270
- throw {
271
- code: "client/invalid-token",
272
- message: "An invalid token has been provided. Please make sure the token is valid."
273
- };
274
- }
275
- throw (result == null ? void 0 : result.error) || result;
276
- }
277
- return result;
278
- } catch (e) {
279
- console.error("Error in sendRequestWithFetch:", e);
280
- throw e;
281
- }
282
- })
283
- };
284
- };
285
-
286
- // src/auth/index.ts
287
- var createObservable = () => {
288
- const observer = /* @__PURE__ */ new Map();
289
- return {
290
- subscribe: (key, fn) => {
291
- if (typeof fn !== "function")
292
- return;
293
- return observer.set(key, fn);
294
- },
295
- unsubscribe: (key) => {
296
- return observer.delete(key);
297
- },
298
- notify: (data) => {
299
- return [...observer.values()].forEach((fn) => fn(data));
300
- }
301
- };
302
- };
303
- var observable = createObservable();
304
- var getPersistedMember = () => {
305
- const stored = localStorage == null ? void 0 : localStorage.getItem("_ms-mem");
306
- return stored ? JSON.parse(stored) : null;
307
- };
308
- var setPersistedMember = (member) => {
309
- if (member) {
310
- const data = JSON.stringify(member);
311
- if (data)
312
- localStorage == null ? void 0 : localStorage.setItem("_ms-mem", data);
313
- observable.notify(member);
314
- }
315
- };
316
- var updatePersistedMember = (member) => {
317
- if (member) {
318
- const data = JSON.stringify(member);
319
- if (data)
320
- localStorage == null ? void 0 : localStorage.setItem("_ms-mem", data);
321
- } else {
322
- localStorage == null ? void 0 : localStorage.removeItem("_ms-mem");
323
- removeMemberToken();
324
- }
325
- };
326
- var unsetPersistedMember = () => {
327
- localStorage == null ? void 0 : localStorage.removeItem("_ms-mem");
328
- removeMemberToken();
329
- removeSessionId();
330
- observable.notify(null);
331
- };
332
-
333
- // src/methods/requests/index.ts
334
- function getSessionDurationDays(unixTimestampMillis) {
335
- const now = Date.now();
336
- const differenceMillis = unixTimestampMillis - now;
337
- return Math.ceil(differenceMillis / (24 * 60 * 60 * 1e3));
338
- }
339
- var addHeaders = (options) => {
340
- const opts = options;
341
- return __spreadValues({}, (opts == null ? void 0 : opts.token) && {
342
- Authorization: `Bearer ${opts.token}`
343
- });
344
- };
345
- var promiseResolve;
346
- var promiseReject;
347
- var receiveMessage = (event) => {
348
- var _a;
349
- const { data, origin } = event;
350
- if (API_ENDPOINT !== origin)
351
- return;
352
- if ((_a = data == null ? void 0 : data.data) == null ? void 0 : _a.member) {
353
- const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
354
- setPersistedMember(data.data.member);
355
- setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
356
- }
357
- if (data == null ? void 0 : data.error) {
358
- promiseReject == null ? void 0 : promiseReject(data.error);
359
- }
360
- promiseResolve == null ? void 0 : promiseResolve(data);
361
- };
362
- var windowObjectReference = null;
363
- var previousUrl = null;
364
- var openSignInWindow = (url, name) => __async(void 0, null, function* () {
365
- window.removeEventListener("message", receiveMessage);
366
- const dualScreenLeft = window.screenLeft !== void 0 ? window.screenLeft : window.screenX;
367
- const dualScreenTop = window.screenTop !== void 0 ? window.screenTop : window.screenY;
368
- const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
369
- const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
370
- const systemZoom = width / window.screen.availWidth;
371
- const left = (width - 600) / 2 / systemZoom + dualScreenLeft;
372
- const top = (height - 700) / 2 / systemZoom + dualScreenTop;
373
- const strWindowFeatures = `toolbar=no, menubar=no, width=${600 / systemZoom}, height=${700 / systemZoom}, top=${top}, left=${left}`;
374
- if (windowObjectReference === null || windowObjectReference.closed) {
375
- windowObjectReference = window.open(url, name, strWindowFeatures);
376
- } else if (previousUrl !== url) {
377
- windowObjectReference = window.open(url, name, strWindowFeatures);
378
- windowObjectReference == null ? void 0 : windowObjectReference.focus();
379
- } else {
380
- windowObjectReference == null ? void 0 : windowObjectReference.focus();
381
- }
382
- window.addEventListener("message", (event) => receiveMessage(event), false);
383
- previousUrl = url;
384
- window.addEventListener("beforeunload", () => {
385
- windowObjectReference == null ? void 0 : windowObjectReference.close();
386
- });
387
- return new Promise((resolve, reject) => {
388
- promiseResolve = resolve;
389
- promiseReject = reject;
390
- });
391
- });
392
- function getBrowser() {
393
- const userAgent = navigator.userAgent;
394
- if (/Edg/i.test(userAgent))
395
- return "EDGE";
396
- if (/Trident/i.test(userAgent) || /MSIE/i.test(userAgent))
397
- return "INTERNET_EXPLORER";
398
- if (/Safari/i.test(userAgent) && !/Chrome/i.test(userAgent))
399
- return "SAFARI";
400
- if (/Firefox/i.test(userAgent))
401
- return "FIREFOX";
402
- if (/Chrome/i.test(userAgent) && !/Edg/i.test(userAgent))
403
- return "CHROME";
404
- if (/OPR/i.test(userAgent) || /Opera/i.test(userAgent))
405
- return "OPERA";
406
- return "OTHER";
407
- }
408
- function getOS() {
409
- const userAgent = navigator.userAgent;
410
- if (/Windows/i.test(userAgent))
411
- return "WINDOWS";
412
- if (/Macintosh|Mac OS X/i.test(userAgent))
413
- return "MACOS";
414
- if (/Android/i.test(userAgent))
415
- return "ANDROID";
416
- if (/iPhone|iPad|iPod/i.test(userAgent))
417
- return "IOS";
418
- if (/Linux/i.test(userAgent))
419
- return "LINUX";
420
- return "OTHER";
421
- }
422
- function getScreenSize() {
423
- const width = window.innerWidth;
424
- if (width <= 768)
425
- return "PHONE";
426
- if (width <= 1024)
427
- return "TABLET";
428
- return "DESKTOP";
429
- }
430
- function getUTMParams() {
431
- const params = new URLSearchParams(window.location.search);
432
- const utmParams = {};
433
- const utmKeys = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
434
- utmKeys.forEach((key) => {
435
- if (params.has(key)) {
436
- utmParams[key] = params.get(key);
437
- }
438
- });
439
- return utmParams;
440
- }
441
- function getConversionData() {
442
- return {
443
- browser: getBrowser(),
444
- os: getOS(),
445
- screenSize: getScreenSize(),
446
- sessionId: getSessionId(),
447
- utmParams: getUTMParams()
448
- };
449
- }
450
- var API_ENDPOINT;
451
- var initRequest = ({
452
- publicKey,
453
- appId,
454
- token,
455
- domain
456
- //sessionDurationDays
457
- }) => {
458
- const { sendRequest, sendRequestWithFetch } = createRequestHandler({
459
- publicKey,
460
- token,
461
- customEndpoint: domain,
462
- appId
463
- });
464
- API_ENDPOINT = domain;
465
- return {
466
- _Event(params) {
467
- return __async(this, null, function* () {
468
- const payload = __spreadValues(__spreadValues({}, params.data), getConversionData());
469
- return sendRequestWithFetch({
470
- method: "POST" /* POST */,
471
- url: `/event`,
472
- data: payload
473
- });
474
- });
475
- },
476
- /**
477
- * Permanently deletes the current member's account.
478
- * This action cannot be undone. The member will be logged out after deletion.
479
- *
480
- * @returns Promise resolving to deletion confirmation
481
- *
482
- * @example
483
- * ```typescript
484
- * // Confirm with user before calling
485
- * if (confirm('Are you sure? This cannot be undone.')) {
486
- * await memberstack.deleteMember();
487
- * window.location.href = '/goodbye';
488
- * }
489
- * ```
490
- */
491
- deleteMember() {
492
- return __async(this, null, function* () {
493
- const data = yield sendRequest({
494
- method: "DELETE" /* DELETE */,
495
- url: `/member`
496
- });
497
- unsetPersistedMember();
498
- return data;
499
- });
500
- },
501
- postIsTyping(params) {
502
- return __async(this, null, function* () {
503
- return sendRequest({
504
- method: "POST" /* POST */,
505
- url: `/comments/posts/typing`,
506
- data: {
507
- channelKey: params.channelKey
508
- }
509
- });
510
- });
511
- },
512
- getChannelInfo(params) {
513
- return __async(this, null, function* () {
514
- const queryParams = new URLSearchParams({
515
- channelKey: params.channelKey
516
- });
517
- return sendRequest({
518
- method: "GET" /* GET */,
519
- url: `/comments/channels/info?${queryParams}`
520
- });
521
- });
522
- },
523
- subscribeToChannel(params) {
524
- return __async(this, null, function* () {
525
- return sendRequest({
526
- method: "POST" /* POST */,
527
- url: `/comments/channels/manage-subscription`,
528
- data: {
529
- channelKey: params.channelKey,
530
- action: params.action
531
- }
532
- });
533
- });
534
- },
535
- getPosts(params) {
536
- return __async(this, null, function* () {
537
- const queryParams = new URLSearchParams(__spreadValues(__spreadValues(__spreadValues({
538
- channelKey: params.channelKey
539
- }, params.after && {
540
- after: params.after
541
- }), params.order && {
542
- order: params.order
543
- }), params.limit && {
544
- limit: params.limit.toString()
545
- }));
546
- return sendRequest({
547
- method: "GET" /* GET */,
548
- url: `/comments/posts?${queryParams}`
549
- });
550
- });
551
- },
552
- getThreads(params) {
553
- return __async(this, null, function* () {
554
- const queryParams = new URLSearchParams(__spreadValues(__spreadValues(__spreadValues({
555
- postId: params.postId
556
- }, params.after && {
557
- after: params.after
558
- }), params.order && {
559
- order: params.order
560
- }), params.limit && {
561
- limit: params.limit.toString()
562
- }));
563
- return sendRequest({
564
- method: "GET" /* GET */,
565
- url: `/comments/threads?${queryParams}`
566
- });
567
- });
568
- },
569
- createPost(params) {
570
- return __async(this, null, function* () {
571
- return sendRequest({
572
- method: "POST" /* POST */,
573
- url: `/comments/posts`,
574
- data: {
575
- channelKey: params.channelKey,
576
- content: params.content,
577
- _url: window.location.origin + window.location.pathname
578
- }
579
- });
580
- });
581
- },
582
- updatePost(params) {
583
- return __async(this, null, function* () {
584
- return sendRequest({
585
- method: "PATCH" /* PATCH */,
586
- url: `/comments/posts/${params.postId}/update`,
587
- data: {
588
- content: params.content
589
- }
590
- });
591
- });
592
- },
593
- postVote(params) {
594
- return __async(this, null, function* () {
595
- return sendRequest({
596
- method: "POST" /* POST */,
597
- url: `/comments/posts/${params.postId}/vote`,
598
- data: {
599
- vote: params.vote
600
- }
601
- });
602
- });
603
- },
604
- deletePost(params) {
605
- return __async(this, null, function* () {
606
- return sendRequest({
607
- method: "DELETE" /* DELETE */,
608
- url: `/comments/posts/${params.postId}`
609
- });
610
- });
611
- },
612
- createThread(params) {
613
- return __async(this, null, function* () {
614
- return sendRequest({
615
- method: "POST" /* POST */,
616
- url: `/comments/threads`,
617
- data: {
618
- postId: params.postId,
619
- content: params.content
620
- }
621
- });
622
- });
623
- },
624
- updateThread(params) {
625
- return __async(this, null, function* () {
626
- return sendRequest({
627
- method: "PATCH" /* PATCH */,
628
- url: `/comments/threads/${params.threadId}/update`,
629
- data: {
630
- content: params.content
631
- }
632
- });
633
- });
634
- },
635
- // vote thread
636
- threadVote(params) {
637
- return __async(this, null, function* () {
638
- return sendRequest({
639
- method: "POST" /* POST */,
640
- url: `/comments/threads/${params.threadId}/vote`,
641
- data: {
642
- vote: params.vote
643
- }
644
- });
645
- });
646
- },
647
- deleteThread(params) {
648
- return __async(this, null, function* () {
649
- return sendRequest({
650
- method: "DELETE" /* DELETE */,
651
- url: `/comments/threads/${params.threadId}`
652
- });
653
- });
654
- },
655
- /**
656
- * Retrieves gated/secure content by its content ID.
657
- * Use this to fetch content that requires specific plan access.
658
- *
659
- * @param params - Content parameters
660
- * @param params.contentId - The ID of the secure content block to retrieve
661
- * @returns Promise resolving to the secure content data
662
- *
663
- * @example
664
- * ```typescript
665
- * const { data: content } = await memberstack.getSecureContent({
666
- * contentId: 'cnt_abc123'
667
- * });
668
- * document.getElementById('premium-content').innerHTML = content.html;
669
- * ```
670
- */
671
- getSecureContent(params) {
672
- return __async(this, null, function* () {
673
- const data = yield sendRequest({
674
- method: "POST" /* POST */,
675
- url: "/secure-content",
676
- data: {
677
- contentId: params.contentId
678
- }
679
- });
680
- return data;
681
- });
682
- },
683
- /**
684
- * Signs up a new member using an OAuth provider (e.g., Google, Facebook).
685
- * Opens a popup window for the OAuth flow. On success, the member is created and logged in.
686
- *
687
- * @param params - Signup parameters
688
- * @param params.provider - The OAuth provider to use ('google', 'facebook', etc.)
689
- * @param params.customFields - Optional custom field values to set during signup
690
- * @param params.plans - Optional array of plan objects to assign on signup
691
- * @param params.inviteToken - Optional team invite token
692
- * @returns Promise resolving to the authenticated member data
693
- *
694
- * @example Sign up with Google
695
- * ```typescript
696
- * const { data } = await memberstack.signupWithProvider({
697
- * provider: 'google'
698
- * });
699
- * console.log('Signed up:', data.member.auth.email);
700
- * ```
701
- *
702
- * @example Sign up with custom fields
703
- * ```typescript
704
- * await memberstack.signupWithProvider({
705
- * provider: 'google',
706
- * customFields: { role: 'developer' },
707
- * plans: [{ planId: 'pln_free' }]
708
- * });
709
- * ```
710
- */
711
- signupWithProvider(params) {
712
- return __async(this, null, function* () {
713
- const customFields = encodeURIComponent(params.customFields ? JSON.stringify(params.customFields) : "{}");
714
- const plans = encodeURIComponent(params.plans ? JSON.stringify(params.plans) : "[]");
715
- const conversionData = getConversionData();
716
- const queryParams = new URLSearchParams(__spreadProps(__spreadValues(__spreadProps(__spreadValues(__spreadValues({
717
- provider: params.provider,
718
- customFields,
719
- plans,
720
- appId: appId != null ? appId : ""
721
- }, publicKey && {
722
- publicKey
723
- }), params.inviteToken && {
724
- inviteToken: params.inviteToken
725
- }), {
726
- url: window.location.pathname,
727
- origin: window.location.hostname
728
- }), conversionData.sessionId && { sessionId: conversionData.sessionId }), {
729
- browser: conversionData.browser,
730
- os: conversionData.os,
731
- screenSize: conversionData.screenSize
732
- }));
733
- return openSignInWindow(`${domain}/auth-provider/signup?${queryParams}`, "signup");
734
- });
735
- },
736
- /**
737
- * Logs in an existing member using an OAuth provider (e.g., Google, Facebook).
738
- * Opens a popup window for the OAuth flow. Member must already have an account linked to this provider.
739
- *
740
- * @param params - Login parameters
741
- * @param params.provider - The OAuth provider to use ('google', 'facebook', etc.)
742
- * @param params.allowSignup - If true, creates a new account if one doesn't exist (default: false)
743
- * @returns Promise resolving to the authenticated member data
744
- *
745
- * @example Log in with Google
746
- * ```typescript
747
- * const { data } = await memberstack.loginWithProvider({
748
- * provider: 'google'
749
- * });
750
- * console.log('Logged in:', data.member.auth.email);
751
- * ```
752
- *
753
- * @example Allow signup if account doesn't exist
754
- * ```typescript
755
- * const { data } = await memberstack.loginWithProvider({
756
- * provider: 'google',
757
- * allowSignup: true
758
- * });
759
- * ```
760
- */
761
- loginWithProvider(params) {
762
- return __async(this, null, function* () {
763
- const allowSignup = encodeURIComponent(params.allowSignup === true ? "true" : "false");
764
- const queryParams = new URLSearchParams(__spreadProps(__spreadValues({
765
- provider: params.provider,
766
- appId: appId != null ? appId : ""
767
- }, publicKey && {
768
- publicKey
769
- }), {
770
- origin: window.location.hostname,
771
- allowSignup
772
- }));
773
- return openSignInWindow(`${domain}/auth-provider/login?${queryParams}`, "login");
774
- });
775
- },
776
- /**
777
- * Connects an OAuth provider to the current member's account.
778
- * Allows the member to use additional OAuth providers for login.
779
- * Member must be logged in to use this method.
780
- *
781
- * @param params - Provider parameters
782
- * @param params.provider - The OAuth provider to connect ('google', 'facebook', etc.)
783
- * @returns Promise resolving to the connection result
784
- *
785
- * @example Connect Google to existing account
786
- * ```typescript
787
- * await memberstack.connectProvider({
788
- * provider: 'google'
789
- * });
790
- * // Member can now log in with either email/password or Google
791
- * ```
792
- */
793
- connectProvider(params) {
794
- return __async(this, null, function* () {
795
- const memberToken = getMemberToken();
796
- const queryParams = new URLSearchParams(__spreadProps(__spreadValues(__spreadValues({
797
- provider: params.provider,
798
- appId: appId != null ? appId : ""
799
- }, publicKey && {
800
- publicKey
801
- }), memberToken && { member: memberToken }), {
802
- origin: window.location.hostname
803
- }));
804
- return openSignInWindow(`${domain}/auth-provider/connect?${queryParams}`, "connect");
805
- });
806
- },
807
- /**
808
- * Disconnects an OAuth provider from the current member's account.
809
- * After disconnecting, the member can no longer use this provider to log in.
810
- * Member must be logged in and have another login method available.
811
- *
812
- * @param params - Provider parameters
813
- * @param params.provider - The OAuth provider to disconnect ('google', 'facebook', etc.)
814
- * @returns Promise resolving to the disconnection result
815
- *
816
- * @example Disconnect Google from account
817
- * ```typescript
818
- * await memberstack.disconnectProvider({
819
- * provider: 'google'
820
- * });
821
- * // Member must now use email/password or another connected provider
822
- * ```
823
- */
824
- disconnectProvider(params) {
825
- return __async(this, null, function* () {
826
- return sendRequest({
827
- method: "POST" /* POST */,
828
- url: "/member/disconnect-provider",
829
- data: {
830
- provider: params.provider
831
- }
832
- });
833
- });
834
- },
835
- getAppAndMember(params) {
836
- return __async(this, null, function* () {
837
- var _a2, _b;
838
- const data = yield sendRequest({
839
- method: "POST" /* POST */,
840
- url: `/app-member`,
841
- data: {
842
- data: {
843
- // @ts-ignore
844
- includeSSOText: window == null ? void 0 : window.ssoUI,
845
- trackPageView: params == null ? void 0 : params.trackPageView,
846
- sessionData: __spreadValues({}, getConversionData())
847
- }
848
- }
849
- });
850
- try {
851
- const backendSessionId = (_b = (_a2 = data.data) == null ? void 0 : _a2.sessionData) == null ? void 0 : _b.sessionId;
852
- const storedSessionId = getSessionId();
853
- if (storedSessionId !== backendSessionId)
854
- setSessionId(backendSessionId);
855
- } catch (e) {
856
- }
857
- return data;
858
- });
859
- },
860
- /**
861
- * Retrieves your Memberstack app configuration.
862
- * Returns app settings including authentication options, branding, and enabled features.
863
- *
864
- * @returns Promise resolving to the app configuration
865
- *
866
- * @example
867
- * ```typescript
868
- * const { data: app } = await memberstack.getApp();
869
- * console.log('App name:', app.name);
870
- * console.log('OAuth providers:', app.authProviders);
871
- * ```
872
- */
873
- getApp() {
874
- return __async(this, null, function* () {
875
- const queryParams = new URLSearchParams({
876
- // @ts-ignore
877
- includeSSOText: window == null ? void 0 : window.ssoUI
878
- });
879
- return sendRequest({
880
- method: "GET" /* GET */,
881
- url: `/app?${queryParams}`
882
- });
883
- });
884
- },
885
- /**
886
- * Authenticates a member using their email and password.
887
- * On success, the member's session is automatically stored and they become the current user.
888
- *
889
- * @param params - Login credentials
890
- * @param params.email - The member's email address
891
- * @param params.password - The member's password
892
- * @returns Promise resolving to the authenticated member data and tokens
893
- * @throws When credentials are invalid or account doesn't exist
894
- *
895
- * @example
896
- * ```typescript
897
- * try {
898
- * const { data } = await memberstack.loginMemberEmailPassword({
899
- * email: 'user@example.com',
900
- * password: 'securePassword123'
901
- * });
902
- * console.log('Logged in:', data.member.auth.email);
903
- * } catch (error) {
904
- * console.error('Login failed:', error.message);
905
- * }
906
- * ```
907
- */
908
- loginMemberEmailPassword(params, options) {
909
- return __async(this, null, function* () {
910
- const data = yield sendRequest({
911
- method: "POST" /* POST */,
912
- url: `/auth/login`,
913
- data: {
914
- email: params.email,
915
- password: params.password,
916
- options
917
- }
918
- });
919
- const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
920
- setPersistedMember(data.data.member);
921
- setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
922
- return data;
923
- });
924
- },
925
- /**
926
- * Sends a passwordless login code to an existing member's email.
927
- * The member will receive a one-time code they can use to log in without a password.
928
- *
929
- * @param params - Email parameters
930
- * @param params.email - The member's email address
931
- * @returns Promise resolving to success confirmation
932
- * @throws When the email is not associated with an existing member
933
- *
934
- * @example
935
- * ```typescript
936
- * // Step 1: Send the code
937
- * await memberstack.sendMemberLoginPasswordlessEmail({
938
- * email: 'user@example.com'
939
- * });
940
- * // User receives email with code
941
- *
942
- * // Step 2: Complete login with the code (see loginMemberPasswordless)
943
- * ```
944
- */
945
- sendMemberLoginPasswordlessEmail(params, options) {
946
- return __async(this, null, function* () {
947
- return yield sendRequest({
948
- method: "POST" /* POST */,
949
- url: `/auth/passwordless/login/send`,
950
- data: {
951
- email: params.email
952
- }
953
- });
954
- });
955
- },
956
- /**
957
- * Sends a passwordless signup code to a new member's email.
958
- * Use this for registration flows where you don't want to collect passwords.
959
- *
960
- * @param params - Email parameters
961
- * @param params.email - The new member's email address
962
- * @returns Promise resolving to success confirmation
963
- *
964
- * @example
965
- * ```typescript
966
- * // Step 1: Send the signup code
967
- * await memberstack.sendMemberSignupPasswordlessEmail({
968
- * email: 'newuser@example.com'
969
- * });
970
- *
971
- * // Step 2: Complete signup with the code (see signupMemberPasswordless)
972
- * ```
973
- */
974
- sendMemberSignupPasswordlessEmail(params, options) {
975
- return __async(this, null, function* () {
976
- return yield sendRequest({
977
- method: "POST" /* POST */,
978
- url: `/auth/passwordless/signup/send`,
979
- data: {
980
- email: params.email
981
- }
982
- });
983
- });
984
- },
985
- /**
986
- * Completes passwordless login using the code sent via email.
987
- * On success, the member is logged in and their session is stored.
988
- *
989
- * @param params - Login credentials
990
- * @param params.email - The member's email address
991
- * @param params.passwordlessToken - The one-time code from the email
992
- * @returns Promise resolving to the authenticated member data and tokens
993
- * @throws When the code is invalid or expired
994
- *
995
- * @example Complete passwordless login flow
996
- * ```typescript
997
- * // After user enters the code from their email
998
- * const { data } = await memberstack.loginMemberPasswordless({
999
- * email: 'user@example.com',
1000
- * passwordlessToken: '123456' // Code from email
1001
- * });
1002
- * console.log('Logged in:', data.member.auth.email);
1003
- * ```
1004
- */
1005
- loginMemberPasswordless(params, options) {
1006
- return __async(this, null, function* () {
1007
- const data = yield sendRequest({
1008
- method: "POST" /* POST */,
1009
- url: `/auth/passwordless/login`,
1010
- data: {
1011
- passwordlessToken: params.passwordlessToken,
1012
- email: params.email,
1013
- options
1014
- }
1015
- });
1016
- const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
1017
- setPersistedMember(data.data.member);
1018
- setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
1019
- return data;
1020
- });
1021
- },
1022
- /**
1023
- * Retrieves details for a specific plan by ID.
1024
- * Returns plan information including name, description, and pricing.
1025
- *
1026
- * @param params - Plan parameters
1027
- * @param params.planId - The ID of the plan to retrieve
1028
- * @returns Promise resolving to the plan details
1029
- *
1030
- * @example
1031
- * ```typescript
1032
- * const { data: plan } = await memberstack.getPlan({
1033
- * planId: 'pln_pro123'
1034
- * });
1035
- * console.log('Plan:', plan.name);
1036
- * console.log('Prices:', plan.prices);
1037
- * ```
1038
- */
1039
- getPlan(params) {
1040
- return __async(this, null, function* () {
1041
- return sendRequest({
1042
- method: "GET" /* GET */,
1043
- url: `/app/plans/${params.planId}`
1044
- });
1045
- });
1046
- },
1047
- /**
1048
- * Retrieves all plans configured for your Memberstack app.
1049
- * Returns both free and paid plans with their pricing information.
1050
- *
1051
- * @returns Promise resolving to an array of plans
1052
- *
1053
- * @example List all plans
1054
- * ```typescript
1055
- * const { data: plans } = await memberstack.getPlans();
1056
- *
1057
- * plans.forEach(plan => {
1058
- * console.log(plan.name, plan.id);
1059
- * plan.prices?.forEach(price => {
1060
- * console.log(` ${price.name}: ${price.amount} ${price.currency}`);
1061
- * });
1062
- * });
1063
- * ```
1064
- *
1065
- * @example Build a pricing page
1066
- * ```typescript
1067
- * const { data: plans } = await memberstack.getPlans();
1068
- *
1069
- * const pricingHtml = plans.map(plan => `
1070
- * <div class="plan">
1071
- * <h3>${plan.name}</h3>
1072
- * <p>${plan.description}</p>
1073
- * </div>
1074
- * `).join('');
1075
- * ```
1076
- */
1077
- getPlans() {
1078
- return __async(this, null, function* () {
1079
- const { data } = yield sendRequest({
1080
- method: "GET" /* GET */,
1081
- url: `/app`
1082
- });
1083
- return {
1084
- data: data.plans
1085
- };
1086
- });
1087
- },
1088
- /**
1089
- * Retrieves URL restriction groups configured for your app.
1090
- * These define which URLs require specific plans or authentication to access.
1091
- *
1092
- * @returns Promise resolving to an array of content access groups
1093
- *
1094
- * @example
1095
- * ```typescript
1096
- * const { data: groups } = await memberstack.getRestrictedUrlGroups();
1097
- *
1098
- * groups.forEach(group => {
1099
- * console.log('Group:', group.name);
1100
- * console.log('Required plans:', group.planIds);
1101
- * console.log('URLs:', group.urls);
1102
- * });
1103
- * ```
1104
- */
1105
- getRestrictedUrlGroups() {
1106
- return __async(this, null, function* () {
1107
- const { data } = yield sendRequest({
1108
- method: "GET" /* GET */,
1109
- url: `/app`
1110
- });
1111
- return {
1112
- data: data.contentGroups
1113
- };
1114
- });
1115
- },
1116
- /**
1117
- * Retrieves the currently authenticated member's data.
1118
- * Returns `null` if no user is logged in.
1119
- *
1120
- * @param options - Optional configuration
1121
- * @param options.useCache - If true, returns cached member data instead of fetching from server
1122
- * @returns Promise resolving to the current member's data, or null if not authenticated
1123
- *
1124
- * @example Check if user is logged in
1125
- * ```typescript
1126
- * const { data: member } = await memberstack.getCurrentMember();
1127
- *
1128
- * if (member) {
1129
- * console.log('Logged in as:', member.auth.email);
1130
- * console.log('Plans:', member.planConnections);
1131
- * } else {
1132
- * console.log('Not logged in');
1133
- * }
1134
- * ```
1135
- *
1136
- * @example Access member properties
1137
- * ```typescript
1138
- * const { data: member } = await memberstack.getCurrentMember();
1139
- *
1140
- * if (member) {
1141
- * const email = member.auth.email;
1142
- * const isVerified = member.verified;
1143
- * const customFields = member.customFields;
1144
- * const hasPro = member.planConnections.some(p => p.planId === 'pln_pro');
1145
- * }
1146
- * ```
1147
- */
1148
- getCurrentMember(options) {
1149
- return __async(this, null, function* () {
1150
- const memberToken = getMemberToken();
1151
- if (!memberToken)
1152
- return { data: null };
1153
- const getMemberRequest = sendRequest({
1154
- method: "GET" /* GET */,
1155
- url: `/member`,
1156
- headers: addHeaders(options)
1157
- });
1158
- function setMember() {
1159
- return __async(this, null, function* () {
1160
- const data = yield getMemberRequest;
1161
- updatePersistedMember(data.data);
1162
- });
1163
- }
1164
- setMember();
1165
- if ((options == null ? void 0 : options.useCache) === true) {
1166
- const member = getPersistedMember();
1167
- return { data: member };
1168
- } else {
1169
- return getMemberRequest;
1170
- }
1171
- });
1172
- },
1173
- /**
1174
- * Retrieves the current member's JSON data store.
1175
- * This is a flexible key-value store for storing arbitrary member data.
1176
- *
1177
- * @returns Promise resolving to the member's JSON data object
1178
- *
1179
- * @example
1180
- * ```typescript
1181
- * const { data: json } = await memberstack.getMemberJSON();
1182
- * console.log('Preferences:', json.preferences);
1183
- * console.log('Last visited:', json.lastVisitedPage);
1184
- * ```
1185
- */
1186
- getMemberJSON(options) {
1187
- return __async(this, null, function* () {
1188
- return sendRequest({
1189
- method: "GET" /* GET */,
1190
- url: `/member/json`,
1191
- headers: addHeaders(options)
1192
- });
1193
- });
1194
- },
1195
- /**
1196
- * Updates the current member's JSON data store.
1197
- * You can store any JSON-serializable data. Updates are merged with existing data.
1198
- *
1199
- * @param params - JSON data to store
1200
- * @param params.json - Object containing the data to store
1201
- * @returns Promise resolving to the updated JSON data
1202
- *
1203
- * @example Store user preferences
1204
- * ```typescript
1205
- * await memberstack.updateMemberJSON({
1206
- * json: {
1207
- * preferences: { theme: 'dark', notifications: true },
1208
- * lastVisitedPage: '/dashboard',
1209
- * onboardingComplete: true
1210
- * }
1211
- * });
1212
- * ```
1213
- *
1214
- * @example Store app-specific data
1215
- * ```typescript
1216
- * await memberstack.updateMemberJSON({
1217
- * json: {
1218
- * savedItems: ['item1', 'item2'],
1219
- * progress: { level: 5, score: 1200 }
1220
- * }
1221
- * });
1222
- * ```
1223
- */
1224
- updateMemberJSON(params, options) {
1225
- return __async(this, null, function* () {
1226
- return sendRequest({
1227
- method: "POST" /* POST */,
1228
- url: `/member/json`,
1229
- data: {
1230
- json: params.json
1231
- },
1232
- headers: addHeaders(options)
1233
- });
1234
- });
1235
- },
1236
- /**
1237
- * Adds a free plan to the current member.
1238
- * For paid plans, use `purchasePlansWithCheckout()` instead.
1239
- *
1240
- * @param params - Plan parameters
1241
- * @param params.planId - The ID of the free plan to add
1242
- * @returns Promise resolving to the updated member data with the new plan
1243
- *
1244
- * @example Add a free tier plan
1245
- * ```typescript
1246
- * const { data } = await memberstack.addPlan({
1247
- * planId: 'pln_free_tier'
1248
- * });
1249
- * console.log('Plan added, redirect:', data.redirect);
1250
- * ```
1251
- */
1252
- addPlan(params, options) {
1253
- return __async(this, null, function* () {
1254
- return sendRequest({
1255
- method: "POST" /* POST */,
1256
- url: `/member/plans/add`,
1257
- data: {
1258
- planId: params.planId
1259
- },
1260
- headers: addHeaders(options)
1261
- });
1262
- });
1263
- },
1264
- /**
1265
- * Initiates a Stripe checkout session for purchasing a paid plan.
1266
- * By default, redirects the user to Stripe's hosted checkout page.
1267
- *
1268
- * @param params - Checkout configuration
1269
- * @param params.priceId - The Memberstack price ID to purchase (e.g., 'prc_monthly_pro')
1270
- * @param params.successUrl - URL to redirect to after successful payment (relative or absolute)
1271
- * @param params.cancelUrl - URL to redirect to if user cancels checkout (relative or absolute)
1272
- * @param params.couponId - Optional Stripe coupon ID to apply
1273
- * @param params.autoRedirect - Set to `false` to get the checkout URL without redirecting
1274
- * @returns Promise resolving to checkout data (includes URL if autoRedirect is false)
1275
- *
1276
- * @example Start checkout for a plan
1277
- * ```typescript
1278
- * await memberstack.purchasePlansWithCheckout({
1279
- * priceId: 'prc_monthly_pro',
1280
- * successUrl: '/welcome',
1281
- * cancelUrl: '/pricing'
1282
- * });
1283
- * // User is redirected to Stripe checkout
1284
- * ```
1285
- *
1286
- * @example Get checkout URL without redirecting
1287
- * ```typescript
1288
- * const { data } = await memberstack.purchasePlansWithCheckout({
1289
- * priceId: 'prc_monthly_pro',
1290
- * successUrl: '/welcome',
1291
- * cancelUrl: '/pricing',
1292
- * autoRedirect: false
1293
- * });
1294
- * console.log('Checkout URL:', data.url);
1295
- * ```
1296
- *
1297
- * @example Apply a coupon
1298
- * ```typescript
1299
- * await memberstack.purchasePlansWithCheckout({
1300
- * priceId: 'prc_annual_pro',
1301
- * couponId: 'SAVE20',
1302
- * successUrl: '/welcome',
1303
- * cancelUrl: '/pricing'
1304
- * });
1305
- * ```
1306
- */
1307
- purchasePlansWithCheckout(params, options) {
1308
- return __async(this, null, function* () {
1309
- function getRedirectURL(URL2) {
1310
- let redirectUrl = window.location.href;
1311
- const urlParam = URL2;
1312
- if (urlParam) {
1313
- if (urlParam.indexOf("http://") === 0 || urlParam.indexOf("https://") === 0) {
1314
- redirectUrl = urlParam;
1315
- } else {
1316
- redirectUrl = window.location.origin + urlParam;
1317
- }
1318
- }
1319
- return redirectUrl;
1320
- }
1321
- const success_url = params.successUrl ? getRedirectURL(params.successUrl) : void 0;
1322
- const cancel_url = params.cancelUrl ? getRedirectURL(params.cancelUrl) : window.location.href;
1323
- const request = yield sendRequest({
1324
- method: "POST" /* POST */,
1325
- url: `/member/plans/create-checkout-session`,
1326
- data: {
1327
- priceId: params.priceId,
1328
- couponId: params.couponId,
1329
- metadataForCheckout: params.metadataForCheckout,
1330
- //window.location requires dom
1331
- success_url,
1332
- cancel_url,
1333
- origin_url: window.location.href,
1334
- conversionData: __spreadValues({
1335
- url: window.location.pathname
1336
- }, getConversionData())
1337
- },
1338
- headers: addHeaders(options)
1339
- });
1340
- if (params.autoRedirect === false) {
1341
- return request;
1342
- }
1343
- window.location.href = request.data.url;
1344
- return request;
1345
- });
1346
- },
1347
- /**
1348
- * Opens the Stripe Customer Portal for the current member.
1349
- * The portal allows members to manage their subscriptions, update payment methods, and view invoices.
1350
- * By default, redirects the user to the Stripe-hosted portal.
1351
- *
1352
- * @param params - Portal configuration
1353
- * @param params.returnUrl - URL to redirect to when member exits the portal (relative or absolute)
1354
- * @param params.priceIds - Optional array of price IDs to show for plan switching
1355
- * @param params.autoRedirect - Set to `false` to get the portal URL without redirecting
1356
- * @returns Promise resolving to portal data (includes URL if autoRedirect is false)
1357
- *
1358
- * @example Open customer portal
1359
- * ```typescript
1360
- * await memberstack.launchStripeCustomerPortal({
1361
- * returnUrl: '/account'
1362
- * });
1363
- * // User is redirected to Stripe Customer Portal
1364
- * ```
1365
- *
1366
- * @example Get portal URL without redirecting
1367
- * ```typescript
1368
- * const { data } = await memberstack.launchStripeCustomerPortal({
1369
- * returnUrl: '/account',
1370
- * autoRedirect: false
1371
- * });
1372
- * console.log('Portal URL:', data.url);
1373
- * ```
1374
- */
1375
- launchStripeCustomerPortal(params, options) {
1376
- return __async(this, null, function* () {
1377
- function getRedirectURL(URL2) {
1378
- let redirectUrl = window.location.href;
1379
- const urlParam = URL2;
1380
- if (urlParam) {
1381
- if (urlParam.indexOf("http://") === 0 || urlParam.indexOf("https://") === 0) {
1382
- redirectUrl = urlParam;
1383
- } else {
1384
- redirectUrl = window.location.origin + urlParam;
1385
- }
1386
- }
1387
- return redirectUrl;
1388
- }
1389
- const returnUrl = (params == null ? void 0 : params.returnUrl) ? getRedirectURL(params.returnUrl) : void 0;
1390
- const request = yield sendRequest({
1391
- method: "POST" /* POST */,
1392
- url: `/member/create-billing-portal-session`,
1393
- data: __spreadValues({
1394
- //window.location requires dom
1395
- return_url: returnUrl,
1396
- origin_url: window.location.href
1397
- }, params && {
1398
- priceIds: params.priceIds,
1399
- configuration: params.configuration
1400
- }),
1401
- headers: addHeaders(options)
1402
- });
1403
- if ((params == null ? void 0 : params.autoRedirect) === false) {
1404
- return request;
1405
- }
1406
- window.location.href = request.data.url;
1407
- return request;
1408
- });
1409
- },
1410
- /**
1411
- * Removes a plan from the current member.
1412
- * For paid plans, this will cancel the subscription.
1413
- *
1414
- * @param params - Plan parameters
1415
- * @param params.planId - The ID of the plan to remove
1416
- * @returns Promise resolving to the updated member data
1417
- *
1418
- * @example Remove a plan
1419
- * ```typescript
1420
- * await memberstack.removePlan({
1421
- * planId: 'pln_premium'
1422
- * });
1423
- * // Plan removed/subscription cancelled
1424
- * ```
1425
- */
1426
- removePlan(params, options) {
1427
- return __async(this, null, function* () {
1428
- return sendRequest({
1429
- method: "POST" /* POST */,
1430
- url: `/member/plans/remove`,
1431
- data: {
1432
- planId: params.planId
1433
- },
1434
- headers: addHeaders(options)
1435
- });
1436
- });
1437
- },
1438
- /**
1439
- * Updates the current member's custom fields.
1440
- * Only updates the fields you specify; other fields remain unchanged.
1441
- *
1442
- * @param params - Update data
1443
- * @param params.customFields - Object containing custom field key-value pairs to update
1444
- * @returns Promise resolving to the updated member data
1445
- *
1446
- * @example Update custom fields
1447
- * ```typescript
1448
- * const { data: member } = await memberstack.updateMember({
1449
- * customFields: {
1450
- * firstName: 'Jane',
1451
- * company: 'Acme Inc',
1452
- * preferences: { theme: 'dark' }
1453
- * }
1454
- * });
1455
- * console.log('Updated:', member.customFields);
1456
- * ```
1457
- *
1458
- * @example Update a single field
1459
- * ```typescript
1460
- * await memberstack.updateMember({
1461
- * customFields: {
1462
- * lastLoginPage: window.location.pathname
1463
- * }
1464
- * });
1465
- * ```
1466
- */
1467
- updateMember(params, options) {
1468
- return __async(this, null, function* () {
1469
- return sendRequest({
1470
- method: "POST" /* POST */,
1471
- url: `/member`,
1472
- data: __spreadValues({}, params.customFields && { customFields: params.customFields }),
1473
- headers: addHeaders(options)
1474
- });
1475
- });
1476
- },
1477
- /**
1478
- * Updates the current member's authentication credentials (email and/or password).
1479
- * Requires the current password to verify the member's identity.
1480
- *
1481
- * @param params - Auth update parameters
1482
- * @param params.email - New email address (optional)
1483
- * @param params.oldPassword - Current password (required for password changes)
1484
- * @param params.newPassword - New password (optional)
1485
- * @returns Promise resolving to the updated member data
1486
- * @throws When the old password is incorrect
1487
- *
1488
- * @example Change email
1489
- * ```typescript
1490
- * await memberstack.updateMemberAuth({
1491
- * email: 'newemail@example.com',
1492
- * oldPassword: 'currentPassword'
1493
- * });
1494
- * ```
1495
- *
1496
- * @example Change password
1497
- * ```typescript
1498
- * await memberstack.updateMemberAuth({
1499
- * oldPassword: 'currentPassword',
1500
- * newPassword: 'newSecurePassword123'
1501
- * });
1502
- * ```
1503
- */
1504
- updateMemberAuth(params, options) {
1505
- return __async(this, null, function* () {
1506
- return sendRequest({
1507
- method: "POST" /* POST */,
1508
- url: `/member-auth`,
1509
- data: __spreadValues(__spreadValues(__spreadValues({}, params.email && { email: params.email }), params.oldPassword && { oldPassword: params.oldPassword }), params.newPassword && { newPassword: params.newPassword }),
1510
- headers: addHeaders(options)
1511
- });
1512
- });
1513
- },
1514
- /**
1515
- * Sets a password for a member who signed up via passwordless or OAuth.
1516
- * Use this when a member wants to add password-based login to their account.
1517
- *
1518
- * @param params - Password parameters
1519
- * @param params.password - The password to set
1520
- * @returns Promise resolving to the updated member data
1521
- *
1522
- * @example
1523
- * ```typescript
1524
- * // For members who signed up via Google OAuth or passwordless
1525
- * await memberstack.setPassword({
1526
- * password: 'newSecurePassword123'
1527
- * });
1528
- * // Member can now log in with email/password
1529
- * ```
1530
- */
1531
- setPassword(params, options) {
1532
- return __async(this, null, function* () {
1533
- return sendRequest({
1534
- method: "POST" /* POST */,
1535
- url: `/member/set-password`,
1536
- data: {
1537
- password: params.password
1538
- },
1539
- headers: addHeaders(options)
1540
- });
1541
- });
1542
- },
1543
- signupMemberPasswordless(params, options) {
1544
- return __async(this, null, function* () {
1545
- var _a2, _b, _c;
1546
- const data = yield sendRequest({
1547
- method: "POST" /* POST */,
1548
- url: `/auth/signup?isPasswordless=true`,
1549
- data: __spreadValues(__spreadProps(__spreadValues({
1550
- email: params.email,
1551
- customFields: params.customFields,
1552
- passwordlessToken: params.passwordlessToken,
1553
- metaData: params.metaData
1554
- }, params.plans && { plans: params.plans }), {
1555
- //internal use only
1556
- origin_domain: window.location.origin,
1557
- conversionData: __spreadValues(__spreadProps(__spreadValues({}, (_a2 = params == null ? void 0 : params.conversionData) != null ? _a2 : {}), {
1558
- url: window.location.pathname
1559
- }), getConversionData()),
1560
- options
1561
- }), ((_b = window.Rewardful) == null ? void 0 : _b.referral) && {
1562
- rewardfulData: {
1563
- // @ts-ignore
1564
- referral: window.Rewardful.referral,
1565
- // @ts-ignore
1566
- coupon: (_c = window.Rewardful.coupon) == null ? void 0 : _c.id
1567
- }
1568
- })
1569
- });
1570
- const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
1571
- setPersistedMember(data.data.member);
1572
- setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
1573
- return data;
1574
- });
1575
- },
1576
- /**
1577
- * Creates a new member account with email and password.
1578
- * On success, the member is automatically logged in and their session is stored.
1579
- *
1580
- * @param params - Signup details
1581
- * @param params.email - The new member's email address
1582
- * @param params.password - The new member's password (minimum 8 characters recommended)
1583
- * @param params.customFields - Optional custom field values defined in your Memberstack dashboard
1584
- * @param params.plans - Optional array of plan IDs to assign on signup (for free plans)
1585
- * @param params.metaData - Optional metadata to store with the member
1586
- * @param params.inviteToken - Optional team invite token for team signups
1587
- * @returns Promise resolving to the new member data and tokens
1588
- * @throws When email is already in use or validation fails
1589
- *
1590
- * @example Basic signup
1591
- * ```typescript
1592
- * const { data } = await memberstack.signupMemberEmailPassword({
1593
- * email: 'newuser@example.com',
1594
- * password: 'securePassword123'
1595
- * });
1596
- * console.log('Welcome!', data.member.id);
1597
- * ```
1598
- *
1599
- * @example Signup with custom fields and a free plan
1600
- * ```typescript
1601
- * const { data } = await memberstack.signupMemberEmailPassword({
1602
- * email: 'newuser@example.com',
1603
- * password: 'securePassword123',
1604
- * customFields: {
1605
- * firstName: 'Jane',
1606
- * lastName: 'Doe',
1607
- * company: 'Acme Inc'
1608
- * },
1609
- * plans: [{ planId: 'pln_free_tier' }]
1610
- * });
1611
- * ```
1612
- */
1613
- signupMemberEmailPassword(params, options) {
1614
- return __async(this, null, function* () {
1615
- var _a2, _b, _c;
1616
- const data = yield sendRequest({
1617
- method: "POST" /* POST */,
1618
- url: `/auth/signup`,
1619
- data: __spreadValues(__spreadProps(__spreadValues({
1620
- email: params.email,
1621
- password: params.password,
1622
- customFields: params.customFields,
1623
- metaData: params.metaData,
1624
- captchaToken: params.captchaToken,
1625
- inviteToken: params.inviteToken
1626
- }, params.plans && { plans: params.plans }), {
1627
- //internal use only
1628
- origin_domain: window.location.origin,
1629
- conversionData: __spreadValues(__spreadProps(__spreadValues({}, (_a2 = params == null ? void 0 : params.conversionData) != null ? _a2 : {}), {
1630
- url: window.location.pathname
1631
- }), getConversionData()),
1632
- options
1633
- }), ((_b = window.Rewardful) == null ? void 0 : _b.referral) && {
1634
- rewardfulData: {
1635
- // @ts-ignore
1636
- referral: window.Rewardful.referral,
1637
- // @ts-ignore
1638
- coupon: (_c = window.Rewardful.coupon) == null ? void 0 : _c.id
1639
- }
1640
- })
1641
- });
1642
- const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
1643
- setPersistedMember(data.data.member);
1644
- setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
1645
- return data;
1646
- });
1647
- },
1648
- joinTeam(params, options) {
1649
- return __async(this, null, function* () {
1650
- return sendRequest({
1651
- method: "POST" /* POST */,
1652
- url: `/member/team/join`,
1653
- data: {
1654
- inviteToken: params.inviteToken
1655
- },
1656
- headers: addHeaders(options)
1657
- });
1658
- });
1659
- },
1660
- getTeam(params, options) {
1661
- return __async(this, null, function* () {
1662
- return sendRequest({
1663
- method: "GET" /* GET */,
1664
- url: `/member/team/${params.teamId}`,
1665
- headers: addHeaders(options)
1666
- });
1667
- });
1668
- },
1669
- removeMemberFromTeam(params, options) {
1670
- return __async(this, null, function* () {
1671
- return sendRequest({
1672
- method: "POST" /* POST */,
1673
- url: `/member/team/remove-member`,
1674
- data: {
1675
- teamId: params.teamId,
1676
- memberId: params.memberId
1677
- },
1678
- headers: addHeaders(options)
1679
- });
1680
- });
1681
- },
1682
- generateInviteToken(params, options) {
1683
- return __async(this, null, function* () {
1684
- return sendRequest({
1685
- method: "POST" /* POST */,
1686
- url: `/member/team/generate-invite-link`,
1687
- data: {
1688
- teamId: params.teamId
1689
- },
1690
- headers: addHeaders(options)
1691
- });
1692
- });
1693
- },
1694
- /**
1695
- * Uploads a new profile image for the current member.
1696
- * Accepts a File object (from an input element) or a Blob.
1697
- *
1698
- * @param params - Image parameters
1699
- * @param params.profileImage - The image file to upload
1700
- * @returns Promise resolving to the new profile image URL
1701
- *
1702
- * @example Upload from file input
1703
- * ```typescript
1704
- * const input = document.querySelector('input[type="file"]');
1705
- * const file = input.files[0];
1706
- *
1707
- * const { data } = await memberstack.updateMemberProfileImage({
1708
- * profileImage: file
1709
- * });
1710
- * console.log('New image URL:', data.profileImage);
1711
- * ```
1712
- */
1713
- updateMemberProfileImage(params) {
1714
- return __async(this, null, function* () {
1715
- if (!params.profileImage) {
1716
- throw new Error("profileImage is required");
1717
- }
1718
- const formData = new FormData();
1719
- formData.append("profileImage", params.profileImage);
1720
- return sendRequest({
1721
- method: "POST" /* POST */,
1722
- url: `/member/profile-image`,
1723
- data: formData,
1724
- contentType: "multipart/form-data"
1725
- });
1726
- });
1727
- },
1728
- /**
1729
- * Sends a verification email to the current member.
1730
- * Use this when email verification is enabled in your Memberstack settings.
1731
- *
1732
- * @returns Promise resolving to success confirmation
1733
- *
1734
- * @example
1735
- * ```typescript
1736
- * await memberstack.sendMemberVerificationEmail();
1737
- * // Show message: "Verification email sent! Check your inbox."
1738
- * ```
1739
- */
1740
- sendMemberVerificationEmail() {
1741
- return __async(this, null, function* () {
1742
- return sendRequest({
1743
- method: "POST" /* POST */,
1744
- url: `/auth/send-email-verification`,
1745
- data: {
1746
- //internal use only
1747
- origin_domain: window.location.origin
1748
- }
1749
- });
1750
- });
1751
- },
1752
- /**
1753
- * Sends a password reset email to a member.
1754
- * The email contains a link with a token that can be used to reset their password.
1755
- *
1756
- * @param params - Email parameters
1757
- * @param params.email - The member's email address
1758
- * @returns Promise resolving to success confirmation
1759
- *
1760
- * @example
1761
- * ```typescript
1762
- * await memberstack.sendMemberResetPasswordEmail({
1763
- * email: 'user@example.com'
1764
- * });
1765
- * // Show confirmation: "Check your email for reset instructions"
1766
- * ```
1767
- */
1768
- sendMemberResetPasswordEmail(params) {
1769
- return __async(this, null, function* () {
1770
- return sendRequest({
1771
- method: "POST" /* POST */,
1772
- url: `/auth/send-reset-password-email`,
1773
- data: {
1774
- email: params.email
1775
- }
1776
- });
1777
- });
1778
- },
1779
- /**
1780
- * Completes the password reset process using the token from the reset email.
1781
- * Typically called from a password reset page that receives the token via URL parameter.
1782
- *
1783
- * @param params - Reset parameters
1784
- * @param params.token - The reset token from the email link
1785
- * @param params.newPassword - The new password to set
1786
- * @returns Promise resolving to success confirmation
1787
- * @throws When the token is invalid or expired
1788
- *
1789
- * @example
1790
- * ```typescript
1791
- * // Get token from URL: /reset-password?token=abc123
1792
- * const token = new URLSearchParams(window.location.search).get('token');
1793
- *
1794
- * await memberstack.resetMemberPassword({
1795
- * token,
1796
- * newPassword: 'newSecurePassword123'
1797
- * });
1798
- * // Password updated, redirect to login
1799
- * ```
1800
- */
1801
- resetMemberPassword(params) {
1802
- return __async(this, null, function* () {
1803
- return sendRequest({
1804
- method: "POST" /* POST */,
1805
- url: `/auth/reset-password`,
1806
- data: {
1807
- token: params.token,
1808
- newPassword: params.newPassword
1809
- }
1810
- });
1811
- });
1812
- },
1813
- /**
1814
- * Signs out the currently authenticated member.
1815
- * Clears the local session and invalidates the server-side session.
1816
- *
1817
- * @returns Promise resolving to logout confirmation (may include a redirect URL)
1818
- *
1819
- * @example
1820
- * ```typescript
1821
- * await memberstack.logout();
1822
- * // User is now logged out
1823
- * window.location.href = '/login';
1824
- * ```
1825
- *
1826
- * @example With redirect handling
1827
- * ```typescript
1828
- * const { data } = await memberstack.logout();
1829
- * if (data.redirect) {
1830
- * window.location.href = data.redirect;
1831
- * }
1832
- * ```
1833
- */
1834
- logout(options) {
1835
- return __async(this, null, function* () {
1836
- const data = yield sendRequest({
1837
- method: "POST" /* POST */,
1838
- url: `/member/logout`,
1839
- headers: addHeaders(options)
1840
- });
1841
- unsetPersistedMember();
1842
- return data;
1843
- });
1844
- },
1845
- // Data Tables Methods
1846
- /**
1847
- * Retrieves all data tables configured for your app.
1848
- * Returns the list of tables and their schemas.
1849
- *
1850
- * @returns Promise resolving to an array of data tables
1851
- *
1852
- * @example
1853
- * ```typescript
1854
- * const { data: tables } = await memberstack.getDataTables();
1855
- * tables.forEach(table => {
1856
- * console.log('Table:', table.name, table.key);
1857
- * });
1858
- * ```
1859
- */
1860
- getDataTables(options) {
1861
- return __async(this, null, function* () {
1862
- return sendRequest({
1863
- method: "GET" /* GET */,
1864
- url: `/v1/data-tables`,
1865
- headers: addHeaders(options)
1866
- });
1867
- });
1868
- },
1869
- /**
1870
- * Retrieves a specific data table's schema and configuration.
1871
- *
1872
- * @param params - Table parameters
1873
- * @param params.table - The table key/identifier
1874
- * @returns Promise resolving to the table schema
1875
- *
1876
- * @example
1877
- * ```typescript
1878
- * const { data: table } = await memberstack.getDataTable({
1879
- * table: 'posts'
1880
- * });
1881
- * console.log('Columns:', table.columns);
1882
- * ```
1883
- */
1884
- getDataTable(params, options) {
1885
- return __async(this, null, function* () {
1886
- return sendRequest({
1887
- method: "GET" /* GET */,
1888
- //@ts-ignore
1889
- url: `/v1/data-tables/${params.table || params.tableKey}`,
1890
- headers: addHeaders(options)
1891
- });
1892
- });
1893
- },
1894
- /**
1895
- * Retrieves records from a data table with optional filtering and pagination.
1896
- *
1897
- * @param params - Query parameters
1898
- * @param params.table - The table key/identifier
1899
- * @param params.limit - Maximum number of records to return
1900
- * @param params.after - Cursor for pagination (record ID to start after)
1901
- * @param params.sortBy - Field to sort by
1902
- * @param params.sortDirection - Sort direction ('asc' or 'desc')
1903
- * @param params.createdAfter - Filter records created after this date
1904
- * @param params.createdBefore - Filter records created before this date
1905
- * @returns Promise resolving to records array with pagination info
1906
- *
1907
- * @example List records with pagination
1908
- * ```typescript
1909
- * const { data } = await memberstack.getDataRecords({
1910
- * table: 'posts',
1911
- * limit: 10,
1912
- * sortBy: 'createdAt',
1913
- * sortDirection: 'desc'
1914
- * });
1915
- * console.log('Records:', data.records);
1916
- * ```
1917
- */
1918
- getDataRecords(params, options) {
1919
- return __async(this, null, function* () {
1920
- var _a2;
1921
- const query = {};
1922
- if (params.createdAfter || params.createdBefore) {
1923
- query.where = {
1924
- createdAt: __spreadValues(__spreadValues({}, params.createdAfter && { gte: params.createdAfter }), params.createdBefore && { lte: params.createdBefore })
1925
- };
1926
- }
1927
- if (params.sortBy) {
1928
- query.orderBy = {
1929
- [params.sortBy]: params.sortDirection || "asc"
1930
- };
1931
- }
1932
- if (params.limit) {
1933
- query.take = params.limit;
1934
- }
1935
- if (params.after) {
1936
- query.after = params.after;
1937
- }
1938
- const res = yield sendRequest({
1939
- method: "POST" /* POST */,
1940
- url: `/v1/data-records/query`,
1941
- data: {
1942
- // @ts-ignore
1943
- table: params.table || params.tableKey,
1944
- query: {
1945
- findMany: query
1946
- }
1947
- },
1948
- headers: addHeaders(options)
1949
- });
1950
- if ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.records) {
1951
- return {
1952
- data: __spreadValues({
1953
- records: res.data.records
1954
- }, res.data.pagination && { pagination: res.data.pagination })
1955
- };
1956
- }
1957
- return res;
1958
- });
1959
- },
1960
- /**
1961
- * Creates a new record in a data table.
1962
- *
1963
- * @param params - Record parameters
1964
- * @param params.table - The table key/identifier
1965
- * @param params.data - The record data as key-value pairs
1966
- * @param params.memberId - Optional member ID to associate with the record
1967
- * @returns Promise resolving to the created record
1968
- *
1969
- * @example Create a new post
1970
- * ```typescript
1971
- * const { data: record } = await memberstack.createDataRecord({
1972
- * table: 'posts',
1973
- * data: {
1974
- * title: 'My First Post',
1975
- * content: 'Hello world!',
1976
- * published: true
1977
- * }
1978
- * });
1979
- * console.log('Created record:', record.id);
1980
- * ```
1981
- */
1982
- createDataRecord(params, options) {
1983
- return __async(this, null, function* () {
1984
- return sendRequest({
1985
- method: "POST" /* POST */,
1986
- url: `/v1/data-records`,
1987
- data: __spreadValues({
1988
- table: params.table,
1989
- data: params.data
1990
- }, params.memberId && { memberId: params.memberId }),
1991
- headers: addHeaders(options)
1992
- });
1993
- });
1994
- },
1995
- /**
1996
- * Retrieves a single record by ID from a data table.
1997
- *
1998
- * @param params - Record parameters
1999
- * @param params.table - The table key/identifier
2000
- * @param params.recordId - The ID of the record to retrieve
2001
- * @returns Promise resolving to the record data
2002
- *
2003
- * @example Get a specific post
2004
- * ```typescript
2005
- * const { data: record } = await memberstack.getDataRecord({
2006
- * table: 'posts',
2007
- * recordId: 'rec_abc123'
2008
- * });
2009
- * console.log('Post:', record.title);
2010
- * ```
2011
- */
2012
- getDataRecord(params, options) {
2013
- return __async(this, null, function* () {
2014
- var _a2;
2015
- const res = yield sendRequest({
2016
- method: "POST" /* POST */,
2017
- url: `/v1/data-records/query`,
2018
- data: {
2019
- table: params.table,
2020
- query: {
2021
- findUnique: {
2022
- where: { id: params.recordId }
2023
- }
2024
- }
2025
- },
2026
- headers: addHeaders(options)
2027
- });
2028
- if ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.record) {
2029
- return { data: res.data.record };
2030
- }
2031
- return res;
2032
- });
2033
- },
2034
- /**
2035
- * Updates an existing record in a data table.
2036
- *
2037
- * @param params - Update parameters
2038
- * @param params.recordId - The ID of the record to update
2039
- * @param params.data - The fields to update as key-value pairs
2040
- * @returns Promise resolving to the updated record
2041
- *
2042
- * @example Update a post
2043
- * ```typescript
2044
- * const { data: record } = await memberstack.updateDataRecord({
2045
- * recordId: 'rec_abc123',
2046
- * data: {
2047
- * title: 'Updated Title',
2048
- * published: false
2049
- * }
2050
- * });
2051
- * ```
2052
- */
2053
- updateDataRecord(params, options) {
2054
- return __async(this, null, function* () {
2055
- return sendRequest({
2056
- method: "PUT" /* PUT */,
2057
- url: `/v1/data-records/${params.recordId}`,
2058
- data: {
2059
- data: params.data
2060
- },
2061
- headers: addHeaders(options)
2062
- });
2063
- });
2064
- },
2065
- /**
2066
- * Deletes a record from a data table.
2067
- *
2068
- * @param params - Delete parameters
2069
- * @param params.recordId - The ID of the record to delete
2070
- * @returns Promise resolving to deletion confirmation
2071
- *
2072
- * @example Delete a post
2073
- * ```typescript
2074
- * await memberstack.deleteDataRecord({
2075
- * recordId: 'rec_abc123'
2076
- * });
2077
- * ```
2078
- */
2079
- deleteDataRecord(params, options) {
2080
- return __async(this, null, function* () {
2081
- return sendRequest({
2082
- method: "DELETE" /* DELETE */,
2083
- url: `/v1/data-records/${params.recordId}`,
2084
- headers: addHeaders(options)
2085
- });
2086
- });
2087
- },
2088
- /**
2089
- * Queries records from a data table with advanced filtering.
2090
- * Provides more control than getDataRecords for complex queries.
2091
- *
2092
- * @param params - Query parameters
2093
- * @param params.table - The table key/identifier
2094
- * @param params.query - Query object with where, orderBy, take, skip options
2095
- * @returns Promise resolving to matching records
2096
- *
2097
- * @example Query with filters
2098
- * ```typescript
2099
- * const { data } = await memberstack.queryDataRecords({
2100
- * table: 'posts',
2101
- * query: {
2102
- * where: {
2103
- * published: { equals: true },
2104
- * category: { equals: 'tech' }
2105
- * },
2106
- * orderBy: { createdAt: 'desc' },
2107
- * take: 10
2108
- * }
2109
- * });
2110
- * ```
2111
- *
2112
- * @example Query with member filter
2113
- * ```typescript
2114
- * const { data } = await memberstack.queryDataRecords({
2115
- * table: 'comments',
2116
- * query: {
2117
- * where: {
2118
- * memberId: { equals: 'mem_xyz789' }
2119
- * }
2120
- * }
2121
- * });
2122
- * ```
2123
- */
2124
- queryDataRecords(params, options) {
2125
- return __async(this, null, function* () {
2126
- return sendRequest({
2127
- method: "POST" /* POST */,
2128
- url: `/v1/data-records/query`,
2129
- data: {
2130
- table: params.table,
2131
- query: {
2132
- findMany: params.query
2133
- }
2134
- },
2135
- headers: addHeaders(options)
2136
- });
2137
- });
2138
- }
2139
- };
2140
- };
2141
- // Annotate the CommonJS export names for ESM import in node:
2142
- 0 && (module.exports = {
2143
- getSessionDurationDays,
2144
- initRequest
2145
- });