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