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