@apextelemed/partner-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +64 -0
  2. package/README.md +363 -0
  3. package/dist/api/index.d.ts +12 -0
  4. package/dist/api/index.js +8 -0
  5. package/dist/api/index.js.map +1 -0
  6. package/dist/api/index.jsx +127 -0
  7. package/dist/cart-CBH8Em8f.d.ts +189 -0
  8. package/dist/cart-D4mVX_zx.d.ts +66 -0
  9. package/dist/chunk/2OXI5TKO.jsx +249 -0
  10. package/dist/chunk/3A3MF7R2.jsx +1 -0
  11. package/dist/chunk/3VEOP7TZ.jsx +16679 -0
  12. package/dist/chunk/5XGPFYIJ.js +26 -0
  13. package/dist/chunk/5XGPFYIJ.js.map +1 -0
  14. package/dist/chunk/67KHO66G.js +26 -0
  15. package/dist/chunk/67KHO66G.js.map +1 -0
  16. package/dist/chunk/6TFBQECC.jsx +135 -0
  17. package/dist/chunk/AN3WPMEP.js +3 -0
  18. package/dist/chunk/AN3WPMEP.js.map +1 -0
  19. package/dist/chunk/DHII7L5Y.js +686 -0
  20. package/dist/chunk/DHII7L5Y.js.map +1 -0
  21. package/dist/chunk/DS4E7FAI.js +132 -0
  22. package/dist/chunk/DS4E7FAI.js.map +1 -0
  23. package/dist/chunk/DY5BJ6UG.js +1195 -0
  24. package/dist/chunk/DY5BJ6UG.js.map +1 -0
  25. package/dist/chunk/E7722UPF.js +378 -0
  26. package/dist/chunk/E7722UPF.js.map +1 -0
  27. package/dist/chunk/HLXKWRRW.js +16774 -0
  28. package/dist/chunk/HLXKWRRW.js.map +1 -0
  29. package/dist/chunk/I46Y2J5W.jsx +144 -0
  30. package/dist/chunk/J63XPQP4.jsx +21 -0
  31. package/dist/chunk/J6KNY37T.js +122 -0
  32. package/dist/chunk/J6KNY37T.js.map +1 -0
  33. package/dist/chunk/KNTZTYXE.jsx +3315 -0
  34. package/dist/chunk/KZZSQ7LP.jsx +409 -0
  35. package/dist/chunk/L46OKCKG.jsx +733 -0
  36. package/dist/chunk/LDZIUFDM.jsx +31 -0
  37. package/dist/chunk/LZWA44KD.js +3 -0
  38. package/dist/chunk/LZWA44KD.js.map +1 -0
  39. package/dist/chunk/NVRAOAVV.js +3 -0
  40. package/dist/chunk/NVRAOAVV.js.map +1 -0
  41. package/dist/chunk/O3QK7YZR.jsx +1 -0
  42. package/dist/chunk/UZCST66N.jsx +21 -0
  43. package/dist/chunk/V42CGY2S.jsx +1229 -0
  44. package/dist/chunk/YJEHCCLY.js +467 -0
  45. package/dist/chunk/YJEHCCLY.js.map +1 -0
  46. package/dist/chunk/ZMOG2IIC.js +3194 -0
  47. package/dist/chunk/ZMOG2IIC.js.map +1 -0
  48. package/dist/client-BzSg2DEK.d.ts +1539 -0
  49. package/dist/config/index.d.ts +55 -0
  50. package/dist/config/index.js +3 -0
  51. package/dist/config/index.js.map +1 -0
  52. package/dist/config/index.jsx +11 -0
  53. package/dist/flows/index.d.ts +1322 -0
  54. package/dist/flows/index.js +9 -0
  55. package/dist/flows/index.js.map +1 -0
  56. package/dist/flows/index.jsx +124 -0
  57. package/dist/index/index.d.ts +71 -0
  58. package/dist/index/index.js +15 -0
  59. package/dist/index/index.js.map +1 -0
  60. package/dist/index/index.jsx +311 -0
  61. package/dist/pages/index.d.ts +617 -0
  62. package/dist/pages/index.js +10 -0
  63. package/dist/pages/index.js.map +1 -0
  64. package/dist/pages/index.jsx +50 -0
  65. package/dist/primitives/default/index.d.ts +6 -0
  66. package/dist/primitives/default/index.js +3 -0
  67. package/dist/primitives/default/index.js.map +1 -0
  68. package/dist/primitives/default/index.jsx +7 -0
  69. package/dist/primitives/index.d.ts +122 -0
  70. package/dist/primitives/index.js +3 -0
  71. package/dist/primitives/index.js.map +1 -0
  72. package/dist/primitives/index.jsx +9 -0
  73. package/dist/stores/index.d.ts +48 -0
  74. package/dist/stores/index.js +6 -0
  75. package/dist/stores/index.js.map +1 -0
  76. package/dist/stores/index.jsx +16 -0
  77. package/dist/surveyV2-BgQHK0GE.d.ts +48 -0
  78. package/dist/testing/adapter.d.ts +104 -0
  79. package/dist/testing/adapter.d.ts.map +1 -0
  80. package/dist/testing/adapter.js +14 -0
  81. package/dist/testing/adapter.js.map +1 -0
  82. package/dist/testing/env.d.ts +29 -0
  83. package/dist/testing/env.d.ts.map +1 -0
  84. package/dist/testing/env.js +42 -0
  85. package/dist/testing/env.js.map +1 -0
  86. package/dist/testing/fixtures.d.ts +70 -0
  87. package/dist/testing/fixtures.d.ts.map +1 -0
  88. package/dist/testing/fixtures.js +74 -0
  89. package/dist/testing/fixtures.js.map +1 -0
  90. package/dist/testing/index.d.ts +15 -0
  91. package/dist/testing/index.d.ts.map +1 -0
  92. package/dist/testing/index.js +14 -0
  93. package/dist/testing/index.js.map +1 -0
  94. package/dist/testing/mocks.d.ts +53 -0
  95. package/dist/testing/mocks.d.ts.map +1 -0
  96. package/dist/testing/mocks.js +90 -0
  97. package/dist/testing/mocks.js.map +1 -0
  98. package/dist/testing/seam-suite.d.ts +39 -0
  99. package/dist/testing/seam-suite.d.ts.map +1 -0
  100. package/dist/testing/seam-suite.js +196 -0
  101. package/dist/testing/seam-suite.js.map +1 -0
  102. package/dist/testing/storage.d.ts +40 -0
  103. package/dist/testing/storage.d.ts.map +1 -0
  104. package/dist/testing/storage.js +71 -0
  105. package/dist/testing/storage.js.map +1 -0
  106. package/dist/theme/admin.css +579 -0
  107. package/dist/theme/affiliate.css +191 -0
  108. package/dist/theme/flow.css +497 -0
  109. package/dist/theme/index.d.ts +84 -0
  110. package/dist/theme/index.js +94 -0
  111. package/dist/theme/index.js.map +1 -0
  112. package/dist/theme/index.jsx +97 -0
  113. package/dist/theme/member-portal.css +1762 -0
  114. package/package.json +199 -0
@@ -0,0 +1,1195 @@
1
+ import { getConfig } from './5XGPFYIJ.js';
2
+
3
+ // src/api/affiliateRef.ts
4
+ var TTL_MS = 30 * 24 * 60 * 60 * 1e3;
5
+ var storageKey = () => `${getConfig().storagePrefix}-affiliate-ref`;
6
+ function captureAffiliateRef(code) {
7
+ if (typeof localStorage === "undefined") return;
8
+ const trimmed = code.trim();
9
+ if (!trimmed) return;
10
+ try {
11
+ const entry = { code: trimmed, ts: Date.now() };
12
+ localStorage.setItem(storageKey(), JSON.stringify(entry));
13
+ } catch {
14
+ }
15
+ }
16
+ function readAffiliateRef() {
17
+ if (typeof localStorage === "undefined") return null;
18
+ try {
19
+ const raw = localStorage.getItem(storageKey());
20
+ if (!raw) return null;
21
+ const parsed = JSON.parse(raw);
22
+ if (!parsed.code || typeof parsed.ts !== "number") return null;
23
+ if (Date.now() - parsed.ts > TTL_MS) {
24
+ localStorage.removeItem(storageKey());
25
+ return null;
26
+ }
27
+ return parsed.code;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ function clearAffiliateRef() {
33
+ if (typeof localStorage === "undefined") return;
34
+ try {
35
+ localStorage.removeItem(storageKey());
36
+ } catch {
37
+ }
38
+ }
39
+
40
+ // src/api/recaptcha.ts
41
+ var configPromise = null;
42
+ var scriptPromise = null;
43
+ var MINT_TIMEOUT_MS = { monitor: 5e3, enforce: 15e3 };
44
+ var CONFIG_TIMEOUT_MS = 5e3;
45
+ function withTimeout(p, ms) {
46
+ return new Promise((resolve) => {
47
+ let done = false;
48
+ const timer = setTimeout(() => {
49
+ if (done) return;
50
+ done = true;
51
+ console.warn(`[recaptcha] timed out after ${ms}ms; proceeding without a token`);
52
+ resolve(null);
53
+ }, ms);
54
+ p.then(
55
+ (v) => {
56
+ if (done) return;
57
+ done = true;
58
+ clearTimeout(timer);
59
+ resolve(v);
60
+ },
61
+ () => {
62
+ if (done) return;
63
+ done = true;
64
+ clearTimeout(timer);
65
+ resolve(null);
66
+ }
67
+ );
68
+ });
69
+ }
70
+ async function fetchRecaptchaConfig() {
71
+ const cfg = getConfig();
72
+ try {
73
+ const res = await fetch(`${cfg.apiBase}/config/recaptcha`, {
74
+ headers: { "X-Tenant-Key": cfg.tenantKey }
75
+ });
76
+ if (!res.ok) return { enabled: false };
77
+ return await res.json();
78
+ } catch {
79
+ return { enabled: false };
80
+ }
81
+ }
82
+ function getRecaptchaConfig() {
83
+ if (!configPromise) configPromise = fetchRecaptchaConfig();
84
+ return configPromise;
85
+ }
86
+ function loadScript(siteKey, timeoutMs) {
87
+ if (scriptPromise) return scriptPromise;
88
+ scriptPromise = new Promise((resolve, reject) => {
89
+ if (typeof window === "undefined") {
90
+ resolve();
91
+ return;
92
+ }
93
+ if (window.grecaptcha) {
94
+ resolve();
95
+ return;
96
+ }
97
+ const script = document.createElement("script");
98
+ script.src = `https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(siteKey)}`;
99
+ script.async = true;
100
+ const timer = setTimeout(
101
+ () => reject(new Error("reCAPTCHA script load timed out")),
102
+ timeoutMs
103
+ );
104
+ script.onload = () => {
105
+ clearTimeout(timer);
106
+ resolve();
107
+ };
108
+ script.onerror = () => {
109
+ clearTimeout(timer);
110
+ reject(new Error("Failed to load reCAPTCHA"));
111
+ };
112
+ document.head.appendChild(script);
113
+ }).catch((err) => {
114
+ scriptPromise = null;
115
+ throw err;
116
+ });
117
+ return scriptPromise;
118
+ }
119
+ async function executeRecaptcha(action) {
120
+ const cfg = await withTimeout(getRecaptchaConfig(), CONFIG_TIMEOUT_MS);
121
+ if (!cfg?.enabled || !cfg.siteKey) return null;
122
+ const bound = cfg.mode === "enforce" ? MINT_TIMEOUT_MS.enforce : MINT_TIMEOUT_MS.monitor;
123
+ return withTimeout(mintToken(cfg.siteKey, action, bound), bound);
124
+ }
125
+ async function mintToken(siteKey, action, timeoutMs) {
126
+ try {
127
+ await loadScript(siteKey, timeoutMs);
128
+ const grecaptcha = window.grecaptcha;
129
+ if (!grecaptcha) return null;
130
+ return await new Promise((resolve, reject) => {
131
+ grecaptcha.ready(() => {
132
+ grecaptcha.execute(siteKey, { action }).then(resolve).catch(reject);
133
+ });
134
+ });
135
+ } catch (err) {
136
+ console.warn("[recaptcha] execute failed:", err);
137
+ return null;
138
+ }
139
+ }
140
+
141
+ // src/api/client.ts
142
+ var authStorageKey = () => `${getConfig().storagePrefix}-auth`;
143
+ var RECAPTCHA_ACTIONS = {
144
+ "POST /auth/login": "login",
145
+ "POST /auth/register": "register",
146
+ "POST /auth/register-member": "register_member",
147
+ "POST /auth/register-and-subscribe": "register_subscribe",
148
+ "POST /auth/check-email": "check_email",
149
+ "POST /auth/request-password-reset": "password_reset_request",
150
+ "POST /auth/reset-password": "password_reset",
151
+ "POST /payments/checkout": "checkout",
152
+ "POST /payments/prescription-checkout": "prescription_checkout",
153
+ "POST /subscriptions": "subscribe",
154
+ "POST /affiliates/login": "affiliate_login",
155
+ "POST /affiliates/register": "affiliate_register",
156
+ "POST /affiliates/request-password-reset": "affiliate_password_reset_request",
157
+ "POST /affiliates/reset-password": "affiliate_password_reset"
158
+ };
159
+ function recaptchaActionFor(method, endpoint) {
160
+ const path = endpoint.split("?")[0];
161
+ return RECAPTCHA_ACTIONS[`${(method ?? "GET").toUpperCase()} ${path}`] ?? null;
162
+ }
163
+ async function applyRecaptcha(headers, method, endpoint) {
164
+ const action = recaptchaActionFor(method, endpoint);
165
+ if (!action) return;
166
+ const token = await executeRecaptcha(action);
167
+ if (token) headers.set("X-Recaptcha-Token", token);
168
+ }
169
+ var tokensClearedListeners = {
170
+ patient: /* @__PURE__ */ new Set(),
171
+ affiliate: /* @__PURE__ */ new Set()
172
+ };
173
+ function onTokensCleared(track, cb) {
174
+ tokensClearedListeners[track].add(cb);
175
+ return () => tokensClearedListeners[track].delete(cb);
176
+ }
177
+ function notifyTokensCleared(track) {
178
+ for (const cb of tokensClearedListeners[track]) {
179
+ try {
180
+ cb();
181
+ } catch {
182
+ }
183
+ }
184
+ }
185
+ function getTokens() {
186
+ try {
187
+ const raw = localStorage.getItem(authStorageKey());
188
+ if (!raw) return null;
189
+ return JSON.parse(raw);
190
+ } catch {
191
+ return null;
192
+ }
193
+ }
194
+ function setTokens(tokens) {
195
+ localStorage.setItem(authStorageKey(), JSON.stringify(tokens));
196
+ }
197
+ function clearTokens() {
198
+ localStorage.removeItem(authStorageKey());
199
+ notifyTokensCleared("patient");
200
+ }
201
+ var refreshPromise = null;
202
+ var refreshLockName = (storageKey2) => `${storageKey2}-refresh`;
203
+ var patientRefreshLockName = () => refreshLockName(authStorageKey());
204
+ function withRefreshLock(name, fn) {
205
+ const lockManager = typeof navigator !== "undefined" ? navigator.locks : void 0;
206
+ if (!lockManager?.request) return fn();
207
+ let started = false;
208
+ const run = () => {
209
+ started = true;
210
+ return fn();
211
+ };
212
+ try {
213
+ return lockManager.request(name, run).catch((err) => {
214
+ if (!started) return fn();
215
+ throw err;
216
+ });
217
+ } catch {
218
+ return fn();
219
+ }
220
+ }
221
+ function adoptRotatedTokens(getLatest, presented, sameOwner) {
222
+ const latest = getLatest();
223
+ if (latest?.accessToken && latest.refreshToken && latest.refreshToken !== presented.refreshToken && sameOwner(latest)) {
224
+ return latest;
225
+ }
226
+ return null;
227
+ }
228
+ var adoptPatientTokens = (presented) => adoptRotatedTokens(getTokens, presented, (latest) => latest.userId === presented.userId);
229
+ var REFRESH_TIMEOUT_MS = 1e4;
230
+ function fetchWithTimeout(input, init, ms) {
231
+ const controller = new AbortController();
232
+ const timer = setTimeout(() => controller.abort(), ms);
233
+ return fetch(input, { ...init, signal: controller.signal }).finally(() => clearTimeout(timer));
234
+ }
235
+ async function refreshAccessToken() {
236
+ if (refreshPromise) return refreshPromise;
237
+ const presented = getTokens();
238
+ if (!presented?.refreshToken || !presented?.userId) return null;
239
+ refreshPromise = withRefreshLock(patientRefreshLockName(), async () => {
240
+ const adopted = adoptPatientTokens(presented);
241
+ if (adopted) return adopted;
242
+ try {
243
+ const cfg = getConfig();
244
+ const res = await fetchWithTimeout(
245
+ `${cfg.apiBase}/auth/refresh`,
246
+ {
247
+ method: "POST",
248
+ headers: {
249
+ "Content-Type": "application/json",
250
+ "X-Tenant-Key": cfg.tenantKey
251
+ },
252
+ body: JSON.stringify({
253
+ refreshToken: presented.refreshToken,
254
+ userId: presented.userId
255
+ })
256
+ },
257
+ REFRESH_TIMEOUT_MS
258
+ );
259
+ if (!res.ok) {
260
+ const raced = adoptPatientTokens(presented);
261
+ if (raced) return raced;
262
+ if (res.status === 401 || res.status === 403) clearTokens();
263
+ return null;
264
+ }
265
+ const data = await res.json();
266
+ const newTokens = {
267
+ accessToken: data.idToken,
268
+ refreshToken: data.refreshToken,
269
+ userId: data.uid
270
+ };
271
+ setTokens(newTokens);
272
+ return newTokens;
273
+ } catch {
274
+ const raced = adoptPatientTokens(presented);
275
+ if (raced) return raced;
276
+ return null;
277
+ }
278
+ }).finally(() => {
279
+ refreshPromise = null;
280
+ });
281
+ return refreshPromise;
282
+ }
283
+ var ApiError = class extends Error {
284
+ status;
285
+ ambiguous;
286
+ /** Machine-readable error code from the response body, when the endpoint
287
+ * sends one (e.g. `SUBSCRIPTION_EXISTS`). Branch on this, never on message. */
288
+ code;
289
+ constructor(message, opts = {}) {
290
+ super(message);
291
+ this.name = "ApiError";
292
+ this.status = opts.status;
293
+ this.ambiguous = opts.ambiguous ?? false;
294
+ this.code = opts.code;
295
+ if (opts.cause !== void 0) this.cause = opts.cause;
296
+ }
297
+ };
298
+ function newIdempotencyKey() {
299
+ try {
300
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
301
+ return crypto.randomUUID();
302
+ }
303
+ } catch {
304
+ }
305
+ const bytes = new Uint8Array(16);
306
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
307
+ crypto.getRandomValues(bytes);
308
+ } else {
309
+ for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
310
+ }
311
+ bytes[6] = bytes[6] & 15 | 64;
312
+ bytes[8] = bytes[8] & 63 | 128;
313
+ const h = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
314
+ return `${h[0]}${h[1]}${h[2]}${h[3]}-${h[4]}${h[5]}-${h[6]}${h[7]}-${h[8]}${h[9]}-${h[10]}${h[11]}${h[12]}${h[13]}${h[14]}${h[15]}`;
315
+ }
316
+ async function coreFetch(endpoint, fetchOpts, track, call = {}) {
317
+ const { skipAuth, authTokenOverride, idempotencyKey } = call;
318
+ const cfg = getConfig();
319
+ const headers = new Headers(fetchOpts.headers);
320
+ headers.set("X-Tenant-Key", cfg.tenantKey);
321
+ if (!headers.has("Content-Type") && fetchOpts.body && typeof fetchOpts.body === "string") {
322
+ headers.set("Content-Type", "application/json");
323
+ }
324
+ if (idempotencyKey && cfg.idempotencyKeys) {
325
+ headers.set("Idempotency-Key", idempotencyKey);
326
+ }
327
+ if (authTokenOverride) {
328
+ headers.set("Authorization", `Bearer ${authTokenOverride}`);
329
+ } else if (!skipAuth) {
330
+ const token = track.getAccessToken();
331
+ if (token) headers.set("Authorization", `Bearer ${token}`);
332
+ }
333
+ await applyRecaptcha(headers, fetchOpts.method, endpoint);
334
+ const url = `${cfg.apiBase}${endpoint}`;
335
+ const build = () => track.credentials !== void 0 ? { ...fetchOpts, headers, credentials: track.credentials } : { ...fetchOpts, headers };
336
+ const doFetch = async () => {
337
+ try {
338
+ return await fetch(url, build());
339
+ } catch (e) {
340
+ throw new ApiError("Network error \u2014 your connection dropped mid-request. Please try again.", {
341
+ ambiguous: true,
342
+ cause: e
343
+ });
344
+ }
345
+ };
346
+ let res = await doFetch();
347
+ if (res.status === 401 && !skipAuth && !authTokenOverride) {
348
+ const refreshed = await track.refresh();
349
+ if (refreshed) {
350
+ headers.set("Authorization", `Bearer ${refreshed.accessToken}`);
351
+ headers.delete("X-Recaptcha-Token");
352
+ await applyRecaptcha(headers, fetchOpts.method, endpoint);
353
+ res = await doFetch();
354
+ if (res.status === 401) {
355
+ track.clear();
356
+ throw new ApiError(track.sessionExpiredMessage, { status: 401 });
357
+ }
358
+ } else {
359
+ if (track.getAccessToken()) {
360
+ throw new ApiError(
361
+ "We couldn\u2019t reach the server to refresh your session. Please try again."
362
+ );
363
+ }
364
+ track.clear();
365
+ throw new ApiError(track.sessionExpiredMessage, { status: 401 });
366
+ }
367
+ }
368
+ if (!res.ok) {
369
+ let errorMsg = `Request failed: ${res.status}`;
370
+ let errorCode;
371
+ try {
372
+ const body = await res.json();
373
+ errorMsg = body.error || body.message || errorMsg;
374
+ errorCode = typeof body.code === "string" ? body.code : void 0;
375
+ if (track.enrichErrorDetails && Array.isArray(body.details) && body.details.length > 0) {
376
+ errorMsg += `: ${body.details.join("; ")}`;
377
+ }
378
+ } catch {
379
+ }
380
+ if (res.status === 403 && /recaptcha/i.test(errorMsg)) {
381
+ errorMsg = "We couldn\u2019t verify you\u2019re human. Please refresh the page and try again.";
382
+ }
383
+ throw new ApiError(errorMsg, { status: res.status, ambiguous: res.status >= 500, code: errorCode });
384
+ }
385
+ if (res.status === 204) return void 0;
386
+ return await res.json();
387
+ }
388
+ var PATIENT_TRACK = {
389
+ getAccessToken: () => getTokens()?.accessToken,
390
+ clear: clearTokens,
391
+ refresh: () => refreshAccessToken(),
392
+ credentials: void 0,
393
+ sessionExpiredMessage: "Session expired. Please log in again.",
394
+ enrichErrorDetails: true
395
+ };
396
+ async function apiFetch(endpoint, options = {}) {
397
+ const { skipAuth, authToken, idempotencyKey, ...fetchOpts } = options;
398
+ return coreFetch(endpoint, fetchOpts, PATIENT_TRACK, {
399
+ skipAuth,
400
+ authTokenOverride: authToken,
401
+ idempotencyKey
402
+ });
403
+ }
404
+ function qs(params) {
405
+ if (!params) return "";
406
+ const p = new URLSearchParams();
407
+ for (const [k, v] of Object.entries(params)) {
408
+ if (v !== void 0 && v !== null) p.set(k, String(v));
409
+ }
410
+ const s = p.toString();
411
+ return s ? `?${s}` : "";
412
+ }
413
+ function post(endpoint, body, opts) {
414
+ return apiFetch(endpoint, {
415
+ method: "POST",
416
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
417
+ skipAuth: opts?.skipAuth,
418
+ idempotencyKey: opts?.idempotencyKey
419
+ });
420
+ }
421
+ function put(endpoint, body) {
422
+ return apiFetch(endpoint, {
423
+ method: "PUT",
424
+ body: body !== void 0 ? JSON.stringify(body) : void 0
425
+ });
426
+ }
427
+ function patch(endpoint, body) {
428
+ return apiFetch(endpoint, {
429
+ method: "PATCH",
430
+ body: body !== void 0 ? JSON.stringify(body) : void 0
431
+ });
432
+ }
433
+ function del(endpoint) {
434
+ return apiFetch(endpoint, { method: "DELETE" });
435
+ }
436
+ function normalizeAuthResponse(raw) {
437
+ return {
438
+ user: {
439
+ id: raw.uid,
440
+ email: "",
441
+ // Not returned by login/register — fetchProfile fills this in
442
+ firstName: "",
443
+ lastName: "",
444
+ role: "user"
445
+ },
446
+ accessToken: raw.idToken,
447
+ refreshToken: raw.refreshToken,
448
+ userId: raw.uid,
449
+ subscriptionId: raw.subscriptionId
450
+ };
451
+ }
452
+ var authApi = {
453
+ async login(payload) {
454
+ const raw = await post("/auth/login", payload, { skipAuth: true });
455
+ const normalized = normalizeAuthResponse(raw);
456
+ return { data: normalized };
457
+ },
458
+ async register(payload) {
459
+ const raw = await post("/auth/register", payload, { skipAuth: true });
460
+ const normalized = normalizeAuthResponse(raw);
461
+ return { data: normalized };
462
+ },
463
+ async refresh(refreshToken, userId) {
464
+ const raw = await post("/auth/refresh", { refreshToken, userId }, { skipAuth: true });
465
+ const normalized = normalizeAuthResponse(raw);
466
+ return { data: normalized };
467
+ },
468
+ async registerAndSubscribe(payload, opts) {
469
+ const raw = await post(
470
+ "/auth/register-and-subscribe",
471
+ { ...payload, affiliateRef: readAffiliateRef() ?? void 0 },
472
+ { skipAuth: true, idempotencyKey: opts?.idempotencyKey }
473
+ );
474
+ const normalized = normalizeAuthResponse(raw);
475
+ return { data: normalized };
476
+ },
477
+ checkEmail(email) {
478
+ return post("/auth/check-email", { email }, { skipAuth: true });
479
+ },
480
+ // Self-serve password reset. Both endpoints are unauthenticated (skipAuth) and
481
+ // reCAPTCHA-gated (see RECAPTCHA_ACTIONS). `requestPasswordReset` always 200s
482
+ // for anti-enumeration; the returned `message` is generic success copy.
483
+ requestPasswordReset(params) {
484
+ return post("/auth/request-password-reset", params, { skipAuth: true });
485
+ },
486
+ resetPassword(params) {
487
+ return post("/auth/reset-password", params, { skipAuth: true });
488
+ }
489
+ };
490
+ var apexApi = {
491
+ getConfig(surveyType) {
492
+ const params = surveyType ? `?surveyType=${surveyType}` : "";
493
+ return apiFetch(`/apex/config${params}`, { skipAuth: true });
494
+ },
495
+ getSurvey(surveyId) {
496
+ return apiFetch(`/apex/surveys/${surveyId}`, { skipAuth: true });
497
+ },
498
+ getSurveyForDrug(drugId) {
499
+ return apiFetch(
500
+ `/apex/surveys/by-drug/${encodeURIComponent(drugId)}`,
501
+ { skipAuth: true }
502
+ );
503
+ },
504
+ async getSurveyByType(type) {
505
+ const cfgRes = await apiFetch(`/apex/config?surveyType=${type}`, { skipAuth: true });
506
+ const surveyId = cfgRes.data?.surveyId;
507
+ if (!surveyId) throw new Error(`No ${type} survey configured for this tenant`);
508
+ return apiFetch(`/apex/surveys/${surveyId}`, { skipAuth: true });
509
+ },
510
+ submitSurvey(payload, opts) {
511
+ return post(
512
+ `/apex/surveys/${payload.surveyId}/submit`,
513
+ {
514
+ answers: payload.answers,
515
+ patientInfo: payload.patientInfo
516
+ },
517
+ { idempotencyKey: opts?.idempotencyKey }
518
+ );
519
+ },
520
+ checkQualification(surveyId, answers) {
521
+ return post(`/apex/surveys/${surveyId}/check-qualification`, { answers });
522
+ },
523
+ selectDrug(payload) {
524
+ return post(`/apex/surveys/${payload.surveyId}/select-drug`, {
525
+ responseId: payload.responseId,
526
+ drugId: payload.drugId
527
+ });
528
+ },
529
+ getPreviousAnswers(surveyId) {
530
+ return apiFetch(`/apex/surveys/${surveyId}/previous-answers`);
531
+ },
532
+ getRequestStatus(requestId, drugId, opts) {
533
+ const q = drugId ? `?drugId=${encodeURIComponent(drugId)}` : "";
534
+ return apiFetch(`/apex/requests/${requestId}${q}`, { authToken: opts?.authToken });
535
+ },
536
+ listRequests() {
537
+ return apiFetch("/apex/requests");
538
+ },
539
+ sendToPharmacy(payload) {
540
+ return post(`/apex/requests/${payload.requestId}/send-to-pharmacy`);
541
+ },
542
+ createRequest(payload, opts) {
543
+ return post("/apex/requests", payload, { idempotencyKey: opts?.idempotencyKey });
544
+ }
545
+ };
546
+ var addressesApi = {
547
+ /** Server-side US address deliverability check (Shippo). Fails open: the
548
+ * backend returns `unchecked` when unconfigured/unreachable, never an error. */
549
+ verify(address) {
550
+ return post("/addresses/verify", address);
551
+ }
552
+ };
553
+ var paymentsApi = {
554
+ getConfig() {
555
+ return apiFetch("/config/payment");
556
+ },
557
+ /** One-time cart charge. The Idempotency-Key header is only sent when the
558
+ * tenant enables `idempotencyKeys` in PortalConfig, and the backend does NOT
559
+ * yet run its idempotency middleware on POST /payments/checkout (unlike
560
+ * prescription-checkout) — the key is best-effort future-proofing and never
561
+ * a license to auto-retry an ambiguous failure: a replay is a possible
562
+ * second real charge until the backend adds the middleware. */
563
+ checkout(payload, opts) {
564
+ return post("/payments/checkout", {
565
+ ...payload,
566
+ affiliateRef: readAffiliateRef() ?? void 0
567
+ }, { idempotencyKey: opts?.idempotencyKey });
568
+ },
569
+ prescriptionCheckout(payload, opts) {
570
+ return post("/payments/prescription-checkout", {
571
+ ...payload,
572
+ affiliateRef: readAffiliateRef() ?? void 0
573
+ }, { idempotencyKey: opts?.idempotencyKey });
574
+ },
575
+ initiate(payload) {
576
+ return post("/payments/initiate", payload);
577
+ },
578
+ callback(payload) {
579
+ return post("/payments/callback", payload);
580
+ }
581
+ };
582
+ var subscriptionsApi = {
583
+ list(params, opts) {
584
+ return apiFetch(`/subscriptions${qs(params)}`, { authToken: opts?.authToken });
585
+ },
586
+ create(payload, opts) {
587
+ return post(
588
+ "/subscriptions",
589
+ {
590
+ ...payload,
591
+ affiliateRef: readAffiliateRef() ?? void 0
592
+ },
593
+ { idempotencyKey: opts?.idempotencyKey }
594
+ );
595
+ },
596
+ get(id) {
597
+ return apiFetch(`/subscriptions/${id}`);
598
+ },
599
+ cancel(id) {
600
+ return post(`/subscriptions/${id}/cancel`);
601
+ },
602
+ pause(id) {
603
+ return post(`/subscriptions/${id}/pause`);
604
+ },
605
+ resume(id) {
606
+ return post(`/subscriptions/${id}/resume`);
607
+ },
608
+ getPaymentMethod(id) {
609
+ return apiFetch(`/subscriptions/${id}/payment-method`);
610
+ },
611
+ updatePaymentMethod(id, payload) {
612
+ return put(`/subscriptions/${id}/payment-method`, payload);
613
+ }
614
+ };
615
+ var messagesApi = {
616
+ listConversations(params) {
617
+ return apiFetch(`/messages/conversations${qs(params)}`);
618
+ },
619
+ getConversation(id) {
620
+ return apiFetch(`/messages/conversations/${id}`);
621
+ },
622
+ listMessages(conversationId, params) {
623
+ return apiFetch(`/messages/conversations/${conversationId}/messages${qs(params)}`);
624
+ },
625
+ sendMessage(conversationId, payload, opts) {
626
+ return post(`/messages/conversations/${conversationId}/messages`, payload, {
627
+ idempotencyKey: opts?.idempotencyKey
628
+ });
629
+ },
630
+ markAsRead(conversationId) {
631
+ return post(`/messages/conversations/${conversationId}/read`);
632
+ },
633
+ uploadAttachment(conversationId, file) {
634
+ const formData = new FormData();
635
+ formData.append("file", file);
636
+ return apiFetch(`/messages/conversations/${conversationId}/attachments`, {
637
+ method: "POST",
638
+ body: formData
639
+ });
640
+ },
641
+ // Backend answers `{ unreadCount }` at the top level, not `{ count }`.
642
+ getUnreadCount() {
643
+ return apiFetch("/messages/unread-count");
644
+ }
645
+ };
646
+ var SUPPORT_ATTACHMENT_MIME_TYPES = [
647
+ "image/jpeg",
648
+ "image/png",
649
+ "image/webp",
650
+ "image/gif",
651
+ "image/heic",
652
+ "application/pdf",
653
+ "text/plain"
654
+ ];
655
+ var SUPPORT_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
656
+ var supportApi = {
657
+ listThreads() {
658
+ return apiFetch(
659
+ "/support/threads"
660
+ );
661
+ },
662
+ getThread(id) {
663
+ return apiFetch(`/support/threads/${id}`);
664
+ },
665
+ /** Open a new thread. Unlike a clinical conversation this needs a subject. */
666
+ createThread(payload, opts) {
667
+ return post("/support/threads", payload, { idempotencyKey: opts?.idempotencyKey });
668
+ },
669
+ sendMessage(threadId, payload, opts) {
670
+ return post(
671
+ `/support/threads/${threadId}/messages`,
672
+ payload,
673
+ { idempotencyKey: opts?.idempotencyKey }
674
+ );
675
+ },
676
+ markAsRead(threadId) {
677
+ return post(`/support/threads/${threadId}/read`);
678
+ },
679
+ uploadAttachment(threadId, file, body) {
680
+ const formData = new FormData();
681
+ formData.append("file", file);
682
+ if (body) formData.append("body", body);
683
+ return apiFetch(`/support/threads/${threadId}/attachments`, {
684
+ method: "POST",
685
+ body: formData
686
+ });
687
+ },
688
+ /** Short-lived signed URL for a stored attachment. */
689
+ getAttachmentUrl(attachmentId) {
690
+ return apiFetch(
691
+ `/support/attachments/${attachmentId}`
692
+ );
693
+ },
694
+ /** Threads (not messages) carrying an unread reply. */
695
+ getUnreadCount() {
696
+ return apiFetch(
697
+ "/support/unread-count"
698
+ );
699
+ },
700
+ /**
701
+ * Realtime credentials. Answers 503 when the deployment has no anon key
702
+ * configured, which callers should treat as "stay on polling", not an error.
703
+ */
704
+ getRealtimeToken() {
705
+ return apiFetch("/support/realtime-token");
706
+ }
707
+ };
708
+ var productsApi = {
709
+ list(category) {
710
+ const params = {};
711
+ if (category) params.category = category;
712
+ return apiFetch(`/products${qs(params)}`);
713
+ },
714
+ categories() {
715
+ return apiFetch("/products/categories");
716
+ }
717
+ };
718
+ var promoCodesApi = {
719
+ validate(code, opts = {}) {
720
+ const params = { code };
721
+ if (opts.productIds && opts.productIds.length > 0) params.productIds = opts.productIds.join(",");
722
+ if (typeof opts.subtotalCents === "number") params.subtotalCents = opts.subtotalCents;
723
+ return apiFetch(`/promo-codes/validate${qs(params)}`);
724
+ }
725
+ };
726
+ var ordersApi = {
727
+ create(payload) {
728
+ return post("/orders", payload);
729
+ },
730
+ list(params) {
731
+ return apiFetch(`/orders${qs(params)}`);
732
+ },
733
+ get(id) {
734
+ return apiFetch(`/orders/${id}`);
735
+ }
736
+ };
737
+ var usersApi = {
738
+ async getProfile(opts) {
739
+ const raw = await apiFetch("/users/me", { authToken: opts?.authToken });
740
+ const u = raw.user;
741
+ const normalized = {
742
+ ...u,
743
+ id: u.id,
744
+ email: u.email || u.email || "",
745
+ firstName: u.firstName || u.first_name || "",
746
+ lastName: u.lastName || u.last_name || "",
747
+ role: u.role || "user"
748
+ };
749
+ return { data: normalized };
750
+ },
751
+ updateProfile(payload) {
752
+ return patch("/users/me", payload);
753
+ }
754
+ };
755
+ var membersApi = {
756
+ getMe() {
757
+ return apiFetch("/members/me");
758
+ },
759
+ /** The member's own submitted intake/refill surveys (newest first). */
760
+ getSurveyResponses() {
761
+ return apiFetch("/apex/surveys/responses");
762
+ },
763
+ getSurveyResponse(responseId) {
764
+ return apiFetch(
765
+ `/apex/surveys/responses/${encodeURIComponent(responseId)}`
766
+ );
767
+ },
768
+ getRequests(opts) {
769
+ return apiFetch("/members/me/requests", {
770
+ authToken: opts?.authToken
771
+ });
772
+ },
773
+ /** Cancel a still-under-review request (pending/new only). */
774
+ cancelRequest(requestId) {
775
+ return del(`/members/me/requests/${requestId}`);
776
+ },
777
+ getPendingSurveys(opts) {
778
+ return apiFetch("/members/me/surveys", {
779
+ authToken: opts?.authToken
780
+ });
781
+ },
782
+ completeSurvey(renewalId, payload) {
783
+ return post(
784
+ `/members/me/renewals/${renewalId}/complete-survey`,
785
+ payload
786
+ );
787
+ }
788
+ };
789
+ var adminApi = {
790
+ getDashboard() {
791
+ return apiFetch("/admin/dashboard/stats");
792
+ },
793
+ getCustomers(params) {
794
+ return apiFetch(`/admin/customers${qs(params)}`);
795
+ },
796
+ getCustomer(id) {
797
+ return apiFetch(`/admin/customers/${id}`);
798
+ },
799
+ /**
800
+ * Mint a short-lived (15-min) impersonation token to preview the patient
801
+ * dashboard as this customer, read-only. The returned token authenticates
802
+ * GET reads only; any write with it is rejected 403 by the backend.
803
+ */
804
+ impersonateCustomer(uid) {
805
+ return post(
806
+ `/admin/customers/${uid}/impersonate`,
807
+ {}
808
+ );
809
+ },
810
+ updateCustomerEmail(uid, email) {
811
+ return patch(`/admin/customers/${uid}/email`, { email });
812
+ },
813
+ // `redirectUrl` is the absolute URL of the host site's password-reset page;
814
+ // the backend appends `?token=…&email=…` before emailing the customer.
815
+ sendPasswordReset(uid, redirectUrl) {
816
+ return post(`/admin/customers/${uid}/send-password-reset`, { redirectUrl });
817
+ },
818
+ getPayments(params) {
819
+ return apiFetch(`/admin/payments${qs(params)}`);
820
+ },
821
+ refundPayment(id, amountCents) {
822
+ return post(`/admin/payments/${id}/refund`, amountCents ? { amountCents } : {});
823
+ },
824
+ // QuickBooks self-service connect (tenant admin).
825
+ quickbooksStatus() {
826
+ return apiFetch("/admin/quickbooks/status");
827
+ },
828
+ connectQuickBooks(returnUrl) {
829
+ return post("/admin/quickbooks/connect", { returnUrl });
830
+ },
831
+ getSubscriptions(params) {
832
+ return apiFetch(`/admin/subscriptions${qs(params)}`);
833
+ },
834
+ cancelSubscription(id) {
835
+ return post(`/admin/subscriptions/${id}/cancel`);
836
+ },
837
+ /**
838
+ * Cancel a customer's still-unapproved Apex requests without touching billing.
839
+ * Backfill for members cancelled before the on-cancel cascade existed, whose
840
+ * requests are still sitting in the prescriber queue. Idempotent; 409s while
841
+ * the customer has a live subscription unless `force` is set.
842
+ */
843
+ cancelUnapprovedRequests(uid, opts) {
844
+ return post(`/admin/customers/${uid}/cancel-unapproved-requests`, opts?.force ? { force: true } : {});
845
+ },
846
+ getWebhookEvents(params) {
847
+ return apiFetch(`/admin/webhook-events${qs(params)}`);
848
+ },
849
+ getEmailTemplates() {
850
+ return apiFetch(
851
+ "/admin/settings/email-templates"
852
+ );
853
+ },
854
+ saveEmailTemplates(templates) {
855
+ return put("/admin/settings/email-templates", { templates });
856
+ },
857
+ resetEmailTemplate(templateKey) {
858
+ return post("/admin/settings/email-templates/reset", { templateKey });
859
+ },
860
+ sendTestEmail(templateKey) {
861
+ return post("/admin/settings/email-templates/test", { templateKey });
862
+ },
863
+ // ── Products ───────────────────────────────────────────────────
864
+ getProducts(params) {
865
+ return apiFetch(`/admin/products${qs(params)}`);
866
+ },
867
+ getProduct(id) {
868
+ return apiFetch(`/admin/products/${id}`);
869
+ },
870
+ updateProduct(id, payload) {
871
+ return patch(`/admin/products/${id}`, payload);
872
+ },
873
+ deleteProduct(id) {
874
+ return del(`/admin/products/${id}`);
875
+ },
876
+ getApexDrugs() {
877
+ return apiFetch("/admin/products/apex-drugs");
878
+ },
879
+ importFromApex(drugs) {
880
+ return post("/admin/products/import-from-apex", { drugs });
881
+ },
882
+ uploadThumbnail(productId, file) {
883
+ const formData = new FormData();
884
+ formData.append("file", file);
885
+ return apiFetch(`/admin/products/${productId}/thumbnail`, {
886
+ method: "POST",
887
+ body: formData
888
+ });
889
+ },
890
+ deleteThumbnail(productId) {
891
+ return del(`/admin/products/${productId}/thumbnail`);
892
+ },
893
+ // ── Sales ──────────────────────────────────────────────────────
894
+ getSales() {
895
+ return apiFetch("/admin/sales");
896
+ },
897
+ createSale(payload) {
898
+ return post("/admin/sales", payload);
899
+ },
900
+ updateSale(id, payload) {
901
+ return patch(`/admin/sales/${id}`, payload);
902
+ },
903
+ deleteSale(id) {
904
+ return del(`/admin/sales/${id}`);
905
+ },
906
+ // ── Promo Codes ────────────────────────────────────────────────
907
+ getPromoCodes() {
908
+ return apiFetch("/admin/promo-codes");
909
+ },
910
+ createPromoCode(payload) {
911
+ return post("/admin/promo-codes", payload);
912
+ },
913
+ updatePromoCode(id, payload) {
914
+ return patch(`/admin/promo-codes/${id}`, payload);
915
+ },
916
+ deletePromoCode(id) {
917
+ return del(`/admin/promo-codes/${id}`);
918
+ },
919
+ // ── Categories ─────────────────────────────────────────────────
920
+ getCategories() {
921
+ return apiFetch("/admin/categories");
922
+ },
923
+ createCategory(payload) {
924
+ return post("/admin/categories", payload);
925
+ },
926
+ updateCategory(id, payload) {
927
+ return patch(`/admin/categories/${id}`, payload);
928
+ },
929
+ deleteCategory(id) {
930
+ return del(`/admin/categories/${id}`);
931
+ },
932
+ // ── Support inbox ──
933
+ //
934
+ // The admin side of `supportApi`. Deliberately NOT merged with clinical
935
+ // messaging the way the member portal is: support staff triage their own
936
+ // queue and have no business reading patient <-> prescriber threads.
937
+ getSupportStats() {
938
+ return apiFetch("/admin/support/stats");
939
+ },
940
+ getSupportThreads(params) {
941
+ return apiFetch(
942
+ `/admin/support/threads${qs(params)}`
943
+ );
944
+ },
945
+ /** Fetching a thread also clears its unread flag server-side. */
946
+ getSupportThread(id) {
947
+ return apiFetch(`/admin/support/threads/${id}`);
948
+ },
949
+ replyToSupportThread(id, body) {
950
+ return post(`/admin/support/threads/${id}/messages`, { body });
951
+ },
952
+ setSupportThreadStatus(id, status) {
953
+ return patch(`/admin/support/threads/${id}`, { status });
954
+ },
955
+ getSupportAttachmentUrl(attachmentId) {
956
+ return apiFetch(`/admin/support/attachments/${attachmentId}`);
957
+ },
958
+ /** Sends a file as a support reply, with optional accompanying text. */
959
+ uploadSupportAttachment(threadId, file, body) {
960
+ const formData = new FormData();
961
+ formData.append("file", file);
962
+ if (body) formData.append("body", body);
963
+ return apiFetch(`/admin/support/threads/${threadId}/attachments`, {
964
+ method: "POST",
965
+ body: formData
966
+ });
967
+ }
968
+ };
969
+ var adminAffiliatesApi = {
970
+ // Affiliates
971
+ list() {
972
+ return apiFetch("/admin/affiliates");
973
+ },
974
+ get(id) {
975
+ return apiFetch(`/admin/affiliates/${id}`);
976
+ },
977
+ getStats(id) {
978
+ return apiFetch(`/admin/affiliates/${id}/stats`);
979
+ },
980
+ getDownline(id) {
981
+ return apiFetch(`/admin/affiliates/${id}/downline`);
982
+ },
983
+ getPromoCodes(id) {
984
+ return apiFetch(`/admin/affiliates/${id}/promo-codes`);
985
+ },
986
+ create(payload) {
987
+ return post("/admin/affiliates", payload);
988
+ },
989
+ update(id, payload) {
990
+ return patch(`/admin/affiliates/${id}`, payload);
991
+ },
992
+ remove(id) {
993
+ return del(`/admin/affiliates/${id}`);
994
+ },
995
+ // Programs
996
+ listPrograms() {
997
+ return apiFetch("/admin/affiliate-programs");
998
+ },
999
+ getProgram(id) {
1000
+ return apiFetch(`/admin/affiliate-programs/${id}`);
1001
+ },
1002
+ createProgram(payload) {
1003
+ return post("/admin/affiliate-programs", payload);
1004
+ },
1005
+ updateProgram(id, payload) {
1006
+ return patch(`/admin/affiliate-programs/${id}`, payload);
1007
+ },
1008
+ removeProgram(id) {
1009
+ return del(`/admin/affiliate-programs/${id}`);
1010
+ },
1011
+ // Conversions
1012
+ listConversions(params) {
1013
+ return apiFetch(
1014
+ `/admin/affiliate-conversions${qs(params)}`
1015
+ );
1016
+ },
1017
+ runTransitions() {
1018
+ return post("/admin/affiliate-conversions/run-transitions");
1019
+ },
1020
+ markPaid(id, paymentBatchId) {
1021
+ return post(
1022
+ `/admin/affiliate-conversions/${id}/mark-paid`,
1023
+ paymentBatchId ? { paymentBatchId } : {}
1024
+ );
1025
+ }
1026
+ };
1027
+ var affiliateAuthStorageKey = () => `${getConfig().storagePrefix}-affiliate-auth`;
1028
+ function getAffiliateTokens() {
1029
+ try {
1030
+ const raw = localStorage.getItem(affiliateAuthStorageKey());
1031
+ if (!raw) return null;
1032
+ return JSON.parse(raw);
1033
+ } catch {
1034
+ return null;
1035
+ }
1036
+ }
1037
+ function setAffiliateTokens(tokens) {
1038
+ localStorage.setItem(affiliateAuthStorageKey(), JSON.stringify(tokens));
1039
+ }
1040
+ function clearAffiliateTokens() {
1041
+ localStorage.removeItem(affiliateAuthStorageKey());
1042
+ notifyTokensCleared("affiliate");
1043
+ }
1044
+ var affiliateRefreshPromise = null;
1045
+ var affiliateRefreshLockName = () => refreshLockName(affiliateAuthStorageKey());
1046
+ var adoptAffiliateTokens = (presented) => adoptRotatedTokens(
1047
+ getAffiliateTokens,
1048
+ presented,
1049
+ (latest) => latest.affiliateId === presented.affiliateId
1050
+ );
1051
+ async function refreshAffiliateAccessToken() {
1052
+ if (affiliateRefreshPromise) return affiliateRefreshPromise;
1053
+ const presented = getAffiliateTokens();
1054
+ if (!presented?.refreshToken || !presented?.affiliateId) return null;
1055
+ affiliateRefreshPromise = withRefreshLock(affiliateRefreshLockName(), async () => {
1056
+ const adopted = adoptAffiliateTokens(presented);
1057
+ if (adopted) return adopted;
1058
+ try {
1059
+ const cfg = getConfig();
1060
+ const res = await fetchWithTimeout(
1061
+ `${cfg.apiBase}/affiliates/refresh`,
1062
+ {
1063
+ method: "POST",
1064
+ headers: {
1065
+ "Content-Type": "application/json",
1066
+ "X-Tenant-Key": cfg.tenantKey
1067
+ },
1068
+ body: JSON.stringify({
1069
+ refreshToken: presented.refreshToken,
1070
+ affiliateId: presented.affiliateId
1071
+ })
1072
+ },
1073
+ REFRESH_TIMEOUT_MS
1074
+ );
1075
+ if (!res.ok) {
1076
+ const raced = adoptAffiliateTokens(presented);
1077
+ if (raced) return raced;
1078
+ if (res.status === 401 || res.status === 403) clearAffiliateTokens();
1079
+ return null;
1080
+ }
1081
+ const data = await res.json();
1082
+ const newTokens = {
1083
+ accessToken: data.idToken,
1084
+ refreshToken: data.refreshToken,
1085
+ affiliateId: presented.affiliateId
1086
+ };
1087
+ setAffiliateTokens(newTokens);
1088
+ return newTokens;
1089
+ } catch {
1090
+ const raced = adoptAffiliateTokens(presented);
1091
+ if (raced) return raced;
1092
+ return null;
1093
+ }
1094
+ }).finally(() => {
1095
+ affiliateRefreshPromise = null;
1096
+ });
1097
+ return affiliateRefreshPromise;
1098
+ }
1099
+ var AFFILIATE_TRACK = {
1100
+ getAccessToken: () => getAffiliateTokens()?.accessToken,
1101
+ clear: clearAffiliateTokens,
1102
+ refresh: () => refreshAffiliateAccessToken(),
1103
+ credentials: "include",
1104
+ sessionExpiredMessage: "Affiliate session expired. Please log in again.",
1105
+ enrichErrorDetails: false
1106
+ };
1107
+ async function affiliateFetch(endpoint, options = {}) {
1108
+ const { skipAuth, ...fetchOpts } = options;
1109
+ return coreFetch(endpoint, fetchOpts, AFFILIATE_TRACK, { skipAuth });
1110
+ }
1111
+ var affiliatePortalApi = {
1112
+ register(input) {
1113
+ return affiliateFetch("/affiliates/register", {
1114
+ method: "POST",
1115
+ body: JSON.stringify(input),
1116
+ skipAuth: true
1117
+ });
1118
+ },
1119
+ // Self-serve password reset (mirror of authApi's customer pair — affiliates
1120
+ // are a separate account table with their own endpoints). `requestPasswordReset`
1121
+ // always 200s with generic copy for anti-enumeration.
1122
+ requestPasswordReset(params) {
1123
+ return affiliateFetch("/affiliates/request-password-reset", {
1124
+ method: "POST",
1125
+ body: JSON.stringify(params),
1126
+ skipAuth: true
1127
+ });
1128
+ },
1129
+ resetPassword(params) {
1130
+ return affiliateFetch("/affiliates/reset-password", {
1131
+ method: "POST",
1132
+ body: JSON.stringify(params),
1133
+ skipAuth: true
1134
+ });
1135
+ },
1136
+ async login(email, password) {
1137
+ const session = await affiliateFetch("/affiliates/login", {
1138
+ method: "POST",
1139
+ body: JSON.stringify({ email, password }),
1140
+ skipAuth: true
1141
+ });
1142
+ setAffiliateTokens({
1143
+ accessToken: session.idToken,
1144
+ refreshToken: session.refreshToken,
1145
+ affiliateId: session.affiliateId
1146
+ });
1147
+ return session;
1148
+ },
1149
+ async logout() {
1150
+ try {
1151
+ await affiliateFetch("/affiliates/logout", { method: "POST" });
1152
+ } catch {
1153
+ }
1154
+ clearAffiliateTokens();
1155
+ },
1156
+ getProfile() {
1157
+ return affiliateFetch("/affiliates/dashboard/profile");
1158
+ },
1159
+ getStats() {
1160
+ return affiliateFetch("/affiliates/dashboard/stats");
1161
+ },
1162
+ listConversions(params) {
1163
+ return affiliateFetch(
1164
+ `/affiliates/dashboard/conversions${qs(params)}`
1165
+ );
1166
+ },
1167
+ listClicks(params) {
1168
+ return affiliateFetch(
1169
+ `/affiliates/dashboard/clicks${qs(params)}`
1170
+ );
1171
+ },
1172
+ getLinks() {
1173
+ return affiliateFetch("/affiliates/dashboard/links");
1174
+ },
1175
+ getPromoCodes() {
1176
+ return affiliateFetch("/affiliates/dashboard/promo-codes");
1177
+ },
1178
+ getDownline() {
1179
+ return affiliateFetch("/affiliates/dashboard/downline");
1180
+ },
1181
+ // Public: server sets the `affiliate_ref` cookie used by attribution.
1182
+ // Backend route is GET, so we encode query params + use skipAuth.
1183
+ track(refCode, landingPage) {
1184
+ const params = new URLSearchParams({ ref: refCode });
1185
+ if (landingPage) params.set("landing", landingPage);
1186
+ return affiliateFetch(
1187
+ `/affiliates/track?${params.toString()}`,
1188
+ { method: "GET", skipAuth: true }
1189
+ );
1190
+ }
1191
+ };
1192
+
1193
+ export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi };
1194
+ //# sourceMappingURL=DY5BJ6UG.js.map
1195
+ //# sourceMappingURL=DY5BJ6UG.js.map