@krutai/auth 0.1.1 → 0.1.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.
package/dist/react.js ADDED
@@ -0,0 +1,1648 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+
5
+ // ../../node_modules/@better-auth/core/dist/env/env-impl.mjs
6
+ var _envShim = /* @__PURE__ */ Object.create(null);
7
+ var _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);
8
+ var env = new Proxy(_envShim, {
9
+ get(_, prop) {
10
+ return _getEnv()[prop] ?? _envShim[prop];
11
+ },
12
+ has(_, prop) {
13
+ return prop in _getEnv() || prop in _envShim;
14
+ },
15
+ set(_, prop, value) {
16
+ const env$1 = _getEnv(true);
17
+ env$1[prop] = value;
18
+ return true;
19
+ },
20
+ deleteProperty(_, prop) {
21
+ if (!prop) return false;
22
+ const env$1 = _getEnv(true);
23
+ delete env$1[prop];
24
+ return true;
25
+ },
26
+ ownKeys() {
27
+ const env$1 = _getEnv(true);
28
+ return Object.keys(env$1);
29
+ }
30
+ });
31
+ typeof process !== "undefined" && process.env && process.env.NODE_ENV || "";
32
+ function getEnvVar(key, fallback) {
33
+ if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback;
34
+ if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback;
35
+ if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback;
36
+ return fallback;
37
+ }
38
+
39
+ // ../../node_modules/@better-auth/core/dist/env/color-depth.mjs
40
+ var COLORS_2 = 1;
41
+ var COLORS_16 = 4;
42
+ var COLORS_256 = 8;
43
+ var COLORS_16m = 24;
44
+ var TERM_ENVS = {
45
+ eterm: COLORS_16,
46
+ cons25: COLORS_16,
47
+ console: COLORS_16,
48
+ cygwin: COLORS_16,
49
+ dtterm: COLORS_16,
50
+ gnome: COLORS_16,
51
+ hurd: COLORS_16,
52
+ jfbterm: COLORS_16,
53
+ konsole: COLORS_16,
54
+ kterm: COLORS_16,
55
+ mlterm: COLORS_16,
56
+ mosh: COLORS_16m,
57
+ putty: COLORS_16,
58
+ st: COLORS_16,
59
+ "rxvt-unicode-24bit": COLORS_16m,
60
+ terminator: COLORS_16m,
61
+ "xterm-kitty": COLORS_16m
62
+ };
63
+ var CI_ENVS_MAP = new Map(Object.entries({
64
+ APPVEYOR: COLORS_256,
65
+ BUILDKITE: COLORS_256,
66
+ CIRCLECI: COLORS_16m,
67
+ DRONE: COLORS_256,
68
+ GITEA_ACTIONS: COLORS_16m,
69
+ GITHUB_ACTIONS: COLORS_16m,
70
+ GITLAB_CI: COLORS_256,
71
+ TRAVIS: COLORS_256
72
+ }));
73
+ var TERM_ENVS_REG_EXP = [
74
+ /ansi/,
75
+ /color/,
76
+ /linux/,
77
+ /direct/,
78
+ /^con[0-9]*x[0-9]/,
79
+ /^rxvt/,
80
+ /^screen/,
81
+ /^xterm/,
82
+ /^vt100/,
83
+ /^vt220/
84
+ ];
85
+ function getColorDepth() {
86
+ if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) {
87
+ case "":
88
+ case "1":
89
+ case "true":
90
+ return COLORS_16;
91
+ case "2":
92
+ return COLORS_256;
93
+ case "3":
94
+ return COLORS_16m;
95
+ default:
96
+ return COLORS_2;
97
+ }
98
+ if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2;
99
+ if (getEnvVar("TMUX")) return COLORS_16m;
100
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16;
101
+ if ("CI" in env) {
102
+ for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors;
103
+ if (getEnvVar("CI_NAME") === "codeship") return COLORS_256;
104
+ return COLORS_2;
105
+ }
106
+ if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2;
107
+ switch (getEnvVar("TERM_PROGRAM")) {
108
+ case "iTerm.app":
109
+ if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256;
110
+ return COLORS_16m;
111
+ case "HyperTerm":
112
+ case "MacTerm":
113
+ return COLORS_16m;
114
+ case "Apple_Terminal":
115
+ return COLORS_256;
116
+ }
117
+ if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m;
118
+ if (getEnvVar("TERM")) {
119
+ if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m;
120
+ if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256;
121
+ const termEnv = getEnvVar("TERM").toLowerCase();
122
+ if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv];
123
+ if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16;
124
+ }
125
+ if (getEnvVar("COLORTERM")) return COLORS_16;
126
+ return COLORS_2;
127
+ }
128
+
129
+ // ../../node_modules/@better-auth/core/dist/env/logger.mjs
130
+ var TTY_COLORS = {
131
+ reset: "\x1B[0m",
132
+ bright: "\x1B[1m",
133
+ dim: "\x1B[2m",
134
+ fg: {
135
+ red: "\x1B[31m",
136
+ green: "\x1B[32m",
137
+ yellow: "\x1B[33m",
138
+ blue: "\x1B[34m",
139
+ magenta: "\x1B[35m"}};
140
+ var levels = [
141
+ "debug",
142
+ "info",
143
+ "success",
144
+ "warn",
145
+ "error"
146
+ ];
147
+ function shouldPublishLog(currentLogLevel, logLevel) {
148
+ return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel);
149
+ }
150
+ var levelColors = {
151
+ info: TTY_COLORS.fg.blue,
152
+ success: TTY_COLORS.fg.green,
153
+ warn: TTY_COLORS.fg.yellow,
154
+ error: TTY_COLORS.fg.red,
155
+ debug: TTY_COLORS.fg.magenta
156
+ };
157
+ var formatMessage = (level, message, colorsEnabled) => {
158
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
159
+ if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message}`;
160
+ return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`;
161
+ };
162
+ var createLogger = (options) => {
163
+ const logLevel = "warn";
164
+ const colorsEnabled = getColorDepth() !== 1;
165
+ const LogFunc = (level, message, args = []) => {
166
+ if (!shouldPublishLog(logLevel, level)) return;
167
+ const formattedMessage = formatMessage(level, message, colorsEnabled);
168
+ {
169
+ if (level === "error") console.error(formattedMessage, ...args);
170
+ else if (level === "warn") console.warn(formattedMessage, ...args);
171
+ else console.log(formattedMessage, ...args);
172
+ return;
173
+ }
174
+ };
175
+ return {
176
+ ...Object.fromEntries(levels.map((level) => [level, (...[message, ...args]) => LogFunc(level, message, args)])),
177
+ get level() {
178
+ return logLevel;
179
+ }
180
+ };
181
+ };
182
+ createLogger();
183
+
184
+ // ../../node_modules/@better-auth/core/dist/utils/string.mjs
185
+ function capitalizeFirstLetter(str) {
186
+ return str.charAt(0).toUpperCase() + str.slice(1);
187
+ }
188
+
189
+ // ../../node_modules/@better-auth/core/dist/error/index.mjs
190
+ var BetterAuthError = class extends Error {
191
+ constructor(message, options) {
192
+ super(message, options);
193
+ this.name = "BetterAuthError";
194
+ this.message = message;
195
+ this.stack = "";
196
+ }
197
+ };
198
+
199
+ // ../../node_modules/better-auth/dist/utils/url.mjs
200
+ function checkHasPath(url) {
201
+ try {
202
+ return (new URL(url).pathname.replace(/\/+$/, "") || "/") !== "/";
203
+ } catch {
204
+ throw new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`);
205
+ }
206
+ }
207
+ function assertHasProtocol(url) {
208
+ try {
209
+ const parsedUrl = new URL(url);
210
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new BetterAuthError(`Invalid base URL: ${url}. URL must include 'http://' or 'https://'`);
211
+ } catch (error) {
212
+ if (error instanceof BetterAuthError) throw error;
213
+ throw new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`, { cause: error });
214
+ }
215
+ }
216
+ function withPath(url, path = "/api/auth") {
217
+ assertHasProtocol(url);
218
+ if (checkHasPath(url)) return url;
219
+ const trimmedUrl = url.replace(/\/+$/, "");
220
+ if (!path || path === "/") return trimmedUrl;
221
+ path = path.startsWith("/") ? path : `/${path}`;
222
+ return `${trimmedUrl}${path}`;
223
+ }
224
+ function getBaseURL(url, path, request, loadEnv, trustedProxyHeaders) {
225
+ if (url) return withPath(url, path);
226
+ {
227
+ const fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== "/" ? env.BASE_URL : void 0);
228
+ if (fromEnv) return withPath(fromEnv, path);
229
+ }
230
+ if (typeof window !== "undefined" && window.location) return withPath(window.location.origin, path);
231
+ }
232
+
233
+ // ../../node_modules/better-auth/dist/client/fetch-plugins.mjs
234
+ var redirectPlugin = {
235
+ id: "redirect",
236
+ name: "Redirect",
237
+ hooks: { onSuccess(context) {
238
+ if (context.data?.url && context.data?.redirect) {
239
+ if (typeof window !== "undefined" && window.location) {
240
+ if (window.location) try {
241
+ window.location.href = context.data.url;
242
+ } catch {
243
+ }
244
+ }
245
+ }
246
+ } }
247
+ };
248
+
249
+ // ../../node_modules/better-auth/dist/client/parser.mjs
250
+ var PROTO_POLLUTION_PATTERNS = {
251
+ proto: /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,
252
+ constructor: /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,
253
+ protoShort: /"__proto__"\s*:/,
254
+ constructorShort: /"constructor"\s*:/
255
+ };
256
+ var JSON_SIGNATURE = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
257
+ var SPECIAL_VALUES = {
258
+ true: true,
259
+ false: false,
260
+ null: null,
261
+ undefined: void 0,
262
+ nan: NaN,
263
+ infinity: Number.POSITIVE_INFINITY,
264
+ "-infinity": Number.NEGATIVE_INFINITY
265
+ };
266
+ var ISO_DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
267
+ function isValidDate(date) {
268
+ return date instanceof Date && !isNaN(date.getTime());
269
+ }
270
+ function parseISODate(value) {
271
+ const match = ISO_DATE_REGEX.exec(value);
272
+ if (!match) return null;
273
+ const [, year, month, day, hour, minute, second, ms, offsetSign, offsetHour, offsetMinute] = match;
274
+ const date = new Date(Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10), parseInt(hour, 10), parseInt(minute, 10), parseInt(second, 10), ms ? parseInt(ms.padEnd(3, "0"), 10) : 0));
275
+ if (offsetSign) {
276
+ const offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === "+" ? -1 : 1);
277
+ date.setUTCMinutes(date.getUTCMinutes() + offset);
278
+ }
279
+ return isValidDate(date) ? date : null;
280
+ }
281
+ function betterJSONParse(value, options = {}) {
282
+ const { strict = false, warnings = false, reviver, parseDates = true } = options;
283
+ if (typeof value !== "string") return value;
284
+ const trimmed = value.trim();
285
+ if (trimmed.length > 0 && trimmed[0] === '"' && trimmed.endsWith('"') && !trimmed.slice(1, -1).includes('"')) return trimmed.slice(1, -1);
286
+ const lowerValue = trimmed.toLowerCase();
287
+ if (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue];
288
+ if (!JSON_SIGNATURE.test(trimmed)) {
289
+ if (strict) throw new SyntaxError("[better-json] Invalid JSON");
290
+ return value;
291
+ }
292
+ if (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => {
293
+ const matches = pattern.test(trimmed);
294
+ if (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`);
295
+ return matches;
296
+ }) && strict) throw new Error("[better-json] Potential prototype pollution attempt detected");
297
+ try {
298
+ const secureReviver = (key, value$1) => {
299
+ if (key === "__proto__" || key === "constructor" && value$1 && typeof value$1 === "object" && "prototype" in value$1) {
300
+ if (warnings) console.warn(`[better-json] Dropping "${key}" key to prevent prototype pollution`);
301
+ return;
302
+ }
303
+ if (parseDates && typeof value$1 === "string") {
304
+ const date = parseISODate(value$1);
305
+ if (date) return date;
306
+ }
307
+ return reviver ? reviver(key, value$1) : value$1;
308
+ };
309
+ return JSON.parse(trimmed, secureReviver);
310
+ } catch (error) {
311
+ if (strict) throw error;
312
+ return value;
313
+ }
314
+ }
315
+ function parseJSON(value, options = { strict: true }) {
316
+ return betterJSONParse(value, options);
317
+ }
318
+
319
+ // ../../node_modules/nanostores/clean-stores/index.js
320
+ var clean = /* @__PURE__ */ Symbol("clean");
321
+
322
+ // ../../node_modules/nanostores/atom/index.js
323
+ var listenerQueue = [];
324
+ var lqIndex = 0;
325
+ var QUEUE_ITEMS_PER_LISTENER = 4;
326
+ var atom = /* @__NO_SIDE_EFFECTS__ */ (initialValue) => {
327
+ let listeners = [];
328
+ let $atom = {
329
+ get() {
330
+ if (!$atom.lc) {
331
+ $atom.listen(() => {
332
+ })();
333
+ }
334
+ return $atom.value;
335
+ },
336
+ lc: 0,
337
+ listen(listener) {
338
+ $atom.lc = listeners.push(listener);
339
+ return () => {
340
+ for (let i = lqIndex + QUEUE_ITEMS_PER_LISTENER; i < listenerQueue.length; ) {
341
+ if (listenerQueue[i] === listener) {
342
+ listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER);
343
+ } else {
344
+ i += QUEUE_ITEMS_PER_LISTENER;
345
+ }
346
+ }
347
+ let index = listeners.indexOf(listener);
348
+ if (~index) {
349
+ listeners.splice(index, 1);
350
+ if (!--$atom.lc) $atom.off();
351
+ }
352
+ };
353
+ },
354
+ notify(oldValue, changedKey) {
355
+ let runListenerQueue = !listenerQueue.length;
356
+ for (let listener of listeners) {
357
+ listenerQueue.push(listener, $atom.value, oldValue, changedKey);
358
+ }
359
+ if (runListenerQueue) {
360
+ for (lqIndex = 0; lqIndex < listenerQueue.length; lqIndex += QUEUE_ITEMS_PER_LISTENER) {
361
+ listenerQueue[lqIndex](
362
+ listenerQueue[lqIndex + 1],
363
+ listenerQueue[lqIndex + 2],
364
+ listenerQueue[lqIndex + 3]
365
+ );
366
+ }
367
+ listenerQueue.length = 0;
368
+ }
369
+ },
370
+ /* It will be called on last listener unsubscribing.
371
+ We will redefine it in onMount and onStop. */
372
+ off() {
373
+ },
374
+ set(newValue) {
375
+ let oldValue = $atom.value;
376
+ if (oldValue !== newValue) {
377
+ $atom.value = newValue;
378
+ $atom.notify(oldValue);
379
+ }
380
+ },
381
+ subscribe(listener) {
382
+ let unbind = $atom.listen(listener);
383
+ listener($atom.value);
384
+ return unbind;
385
+ },
386
+ value: initialValue
387
+ };
388
+ if (process.env.NODE_ENV !== "production") {
389
+ $atom[clean] = () => {
390
+ listeners = [];
391
+ $atom.lc = 0;
392
+ $atom.off();
393
+ };
394
+ }
395
+ return $atom;
396
+ };
397
+
398
+ // ../../node_modules/nanostores/lifecycle/index.js
399
+ var MOUNT = 5;
400
+ var UNMOUNT = 6;
401
+ var REVERT_MUTATION = 10;
402
+ var on = (object, listener, eventKey, mutateStore) => {
403
+ object.events = object.events || {};
404
+ if (!object.events[eventKey + REVERT_MUTATION]) {
405
+ object.events[eventKey + REVERT_MUTATION] = mutateStore((eventProps) => {
406
+ object.events[eventKey].reduceRight((event, l) => (l(event), event), {
407
+ shared: {},
408
+ ...eventProps
409
+ });
410
+ });
411
+ }
412
+ object.events[eventKey] = object.events[eventKey] || [];
413
+ object.events[eventKey].push(listener);
414
+ return () => {
415
+ let currentListeners = object.events[eventKey];
416
+ let index = currentListeners.indexOf(listener);
417
+ currentListeners.splice(index, 1);
418
+ if (!currentListeners.length) {
419
+ delete object.events[eventKey];
420
+ object.events[eventKey + REVERT_MUTATION]();
421
+ delete object.events[eventKey + REVERT_MUTATION];
422
+ }
423
+ };
424
+ };
425
+ var STORE_UNMOUNT_DELAY = 1e3;
426
+ var onMount = ($store, initialize) => {
427
+ let listener = (payload) => {
428
+ let destroy = initialize(payload);
429
+ if (destroy) $store.events[UNMOUNT].push(destroy);
430
+ };
431
+ return on($store, listener, MOUNT, (runListeners) => {
432
+ let originListen = $store.listen;
433
+ $store.listen = (...args) => {
434
+ if (!$store.lc && !$store.active) {
435
+ $store.active = true;
436
+ runListeners();
437
+ }
438
+ return originListen(...args);
439
+ };
440
+ let originOff = $store.off;
441
+ $store.events[UNMOUNT] = [];
442
+ $store.off = () => {
443
+ originOff();
444
+ setTimeout(() => {
445
+ if ($store.active && !$store.lc) {
446
+ $store.active = false;
447
+ for (let destroy of $store.events[UNMOUNT]) destroy();
448
+ $store.events[UNMOUNT] = [];
449
+ }
450
+ }, STORE_UNMOUNT_DELAY);
451
+ };
452
+ if (process.env.NODE_ENV !== "production") {
453
+ let originClean = $store[clean];
454
+ $store[clean] = () => {
455
+ for (let destroy of $store.events[UNMOUNT]) destroy();
456
+ $store.events[UNMOUNT] = [];
457
+ $store.active = false;
458
+ originClean();
459
+ };
460
+ }
461
+ return () => {
462
+ $store.listen = originListen;
463
+ $store.off = originOff;
464
+ };
465
+ });
466
+ };
467
+
468
+ // ../../node_modules/nanostores/listen-keys/index.js
469
+ function listenKeys($store, keys, listener) {
470
+ let keysSet = new Set(keys).add(void 0);
471
+ return $store.listen((value, oldValue, changed) => {
472
+ if (keysSet.has(changed)) {
473
+ listener(value, oldValue, changed);
474
+ }
475
+ });
476
+ }
477
+
478
+ // ../../node_modules/better-auth/dist/client/query.mjs
479
+ var isServer = () => typeof window === "undefined";
480
+ var useAuthQuery = (initializedAtom, path, $fetch, options) => {
481
+ const value = atom({
482
+ data: null,
483
+ error: null,
484
+ isPending: true,
485
+ isRefetching: false,
486
+ refetch: (queryParams) => fn(queryParams)
487
+ });
488
+ const fn = async (queryParams) => {
489
+ return new Promise((resolve) => {
490
+ const opts = typeof options === "function" ? options({
491
+ data: value.get().data,
492
+ error: value.get().error,
493
+ isPending: value.get().isPending
494
+ }) : options;
495
+ $fetch(path, {
496
+ ...opts,
497
+ query: {
498
+ ...opts?.query,
499
+ ...queryParams?.query
500
+ },
501
+ async onSuccess(context) {
502
+ value.set({
503
+ data: context.data,
504
+ error: null,
505
+ isPending: false,
506
+ isRefetching: false,
507
+ refetch: value.value.refetch
508
+ });
509
+ await opts?.onSuccess?.(context);
510
+ },
511
+ async onError(context) {
512
+ const { request } = context;
513
+ const retryAttempts = typeof request.retry === "number" ? request.retry : request.retry?.attempts;
514
+ const retryAttempt = request.retryAttempt || 0;
515
+ if (retryAttempts && retryAttempt < retryAttempts) return;
516
+ value.set({
517
+ error: context.error,
518
+ data: null,
519
+ isPending: false,
520
+ isRefetching: false,
521
+ refetch: value.value.refetch
522
+ });
523
+ await opts?.onError?.(context);
524
+ },
525
+ async onRequest(context) {
526
+ const currentValue = value.get();
527
+ value.set({
528
+ isPending: currentValue.data === null,
529
+ data: currentValue.data,
530
+ error: null,
531
+ isRefetching: true,
532
+ refetch: value.value.refetch
533
+ });
534
+ await opts?.onRequest?.(context);
535
+ }
536
+ }).catch((error) => {
537
+ value.set({
538
+ error,
539
+ data: null,
540
+ isPending: false,
541
+ isRefetching: false,
542
+ refetch: value.value.refetch
543
+ });
544
+ }).finally(() => {
545
+ resolve(void 0);
546
+ });
547
+ });
548
+ };
549
+ initializedAtom = Array.isArray(initializedAtom) ? initializedAtom : [initializedAtom];
550
+ let isMounted = false;
551
+ for (const initAtom of initializedAtom) initAtom.subscribe(async () => {
552
+ if (isServer()) return;
553
+ if (isMounted) await fn();
554
+ else onMount(value, () => {
555
+ const timeoutId = setTimeout(async () => {
556
+ if (!isMounted) {
557
+ await fn();
558
+ isMounted = true;
559
+ }
560
+ }, 0);
561
+ return () => {
562
+ value.off();
563
+ initAtom.off();
564
+ clearTimeout(timeoutId);
565
+ };
566
+ });
567
+ });
568
+ return value;
569
+ };
570
+
571
+ // ../../node_modules/better-auth/dist/client/broadcast-channel.mjs
572
+ var kBroadcastChannel = /* @__PURE__ */ Symbol.for("better-auth:broadcast-channel");
573
+ var now = () => Math.floor(Date.now() / 1e3);
574
+ var WindowBroadcastChannel = class {
575
+ listeners = /* @__PURE__ */ new Set();
576
+ name;
577
+ constructor(name = "better-auth.message") {
578
+ this.name = name;
579
+ }
580
+ subscribe(listener) {
581
+ this.listeners.add(listener);
582
+ return () => {
583
+ this.listeners.delete(listener);
584
+ };
585
+ }
586
+ post(message) {
587
+ if (typeof window === "undefined") return;
588
+ try {
589
+ localStorage.setItem(this.name, JSON.stringify({
590
+ ...message,
591
+ timestamp: now()
592
+ }));
593
+ } catch {
594
+ }
595
+ }
596
+ setup() {
597
+ if (typeof window === "undefined" || typeof window.addEventListener === "undefined") return () => {
598
+ };
599
+ const handler = (event) => {
600
+ if (event.key !== this.name) return;
601
+ const message = JSON.parse(event.newValue ?? "{}");
602
+ if (message?.event !== "session" || !message?.data) return;
603
+ this.listeners.forEach((listener) => listener(message));
604
+ };
605
+ window.addEventListener("storage", handler);
606
+ return () => {
607
+ window.removeEventListener("storage", handler);
608
+ };
609
+ }
610
+ };
611
+ function getGlobalBroadcastChannel(name = "better-auth.message") {
612
+ if (!globalThis[kBroadcastChannel]) globalThis[kBroadcastChannel] = new WindowBroadcastChannel(name);
613
+ return globalThis[kBroadcastChannel];
614
+ }
615
+
616
+ // ../../node_modules/better-auth/dist/client/focus-manager.mjs
617
+ var kFocusManager = /* @__PURE__ */ Symbol.for("better-auth:focus-manager");
618
+ var WindowFocusManager = class {
619
+ listeners = /* @__PURE__ */ new Set();
620
+ subscribe(listener) {
621
+ this.listeners.add(listener);
622
+ return () => {
623
+ this.listeners.delete(listener);
624
+ };
625
+ }
626
+ setFocused(focused) {
627
+ this.listeners.forEach((listener) => listener(focused));
628
+ }
629
+ setup() {
630
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof window.addEventListener === "undefined") return () => {
631
+ };
632
+ const visibilityHandler = () => {
633
+ if (document.visibilityState === "visible") this.setFocused(true);
634
+ };
635
+ document.addEventListener("visibilitychange", visibilityHandler, false);
636
+ return () => {
637
+ document.removeEventListener("visibilitychange", visibilityHandler, false);
638
+ };
639
+ }
640
+ };
641
+ function getGlobalFocusManager() {
642
+ if (!globalThis[kFocusManager]) globalThis[kFocusManager] = new WindowFocusManager();
643
+ return globalThis[kFocusManager];
644
+ }
645
+
646
+ // ../../node_modules/better-auth/dist/client/online-manager.mjs
647
+ var kOnlineManager = /* @__PURE__ */ Symbol.for("better-auth:online-manager");
648
+ var WindowOnlineManager = class {
649
+ listeners = /* @__PURE__ */ new Set();
650
+ isOnline = typeof navigator !== "undefined" ? navigator.onLine : true;
651
+ subscribe(listener) {
652
+ this.listeners.add(listener);
653
+ return () => {
654
+ this.listeners.delete(listener);
655
+ };
656
+ }
657
+ setOnline(online) {
658
+ this.isOnline = online;
659
+ this.listeners.forEach((listener) => listener(online));
660
+ }
661
+ setup() {
662
+ if (typeof window === "undefined" || typeof window.addEventListener === "undefined") return () => {
663
+ };
664
+ const onOnline = () => this.setOnline(true);
665
+ const onOffline = () => this.setOnline(false);
666
+ window.addEventListener("online", onOnline, false);
667
+ window.addEventListener("offline", onOffline, false);
668
+ return () => {
669
+ window.removeEventListener("online", onOnline, false);
670
+ window.removeEventListener("offline", onOffline, false);
671
+ };
672
+ }
673
+ };
674
+ function getGlobalOnlineManager() {
675
+ if (!globalThis[kOnlineManager]) globalThis[kOnlineManager] = new WindowOnlineManager();
676
+ return globalThis[kOnlineManager];
677
+ }
678
+
679
+ // ../../node_modules/better-auth/dist/client/session-refresh.mjs
680
+ var now2 = () => Math.floor(Date.now() / 1e3);
681
+ var FOCUS_REFETCH_RATE_LIMIT_SECONDS = 5;
682
+ function createSessionRefreshManager(opts) {
683
+ const { sessionAtom, sessionSignal, $fetch, options = {} } = opts;
684
+ const refetchInterval = options.sessionOptions?.refetchInterval ?? 0;
685
+ const refetchOnWindowFocus = options.sessionOptions?.refetchOnWindowFocus ?? true;
686
+ const refetchWhenOffline = options.sessionOptions?.refetchWhenOffline ?? false;
687
+ const state = {
688
+ lastSync: 0,
689
+ lastSessionRequest: 0,
690
+ cachedSession: void 0
691
+ };
692
+ const shouldRefetch = () => {
693
+ return refetchWhenOffline || getGlobalOnlineManager().isOnline;
694
+ };
695
+ const triggerRefetch = (event) => {
696
+ if (!shouldRefetch()) return;
697
+ if (event?.event === "storage") {
698
+ state.lastSync = now2();
699
+ sessionSignal.set(!sessionSignal.get());
700
+ return;
701
+ }
702
+ const currentSession = sessionAtom.get();
703
+ if (event?.event === "poll") {
704
+ state.lastSessionRequest = now2();
705
+ $fetch("/get-session").then((res) => {
706
+ if (res.error) sessionAtom.set({
707
+ ...currentSession,
708
+ data: null,
709
+ error: res.error
710
+ });
711
+ else sessionAtom.set({
712
+ ...currentSession,
713
+ data: res.data,
714
+ error: null
715
+ });
716
+ state.lastSync = now2();
717
+ sessionSignal.set(!sessionSignal.get());
718
+ }).catch(() => {
719
+ });
720
+ return;
721
+ }
722
+ if (event?.event === "visibilitychange") {
723
+ if (now2() - state.lastSessionRequest < FOCUS_REFETCH_RATE_LIMIT_SECONDS) return;
724
+ state.lastSessionRequest = now2();
725
+ }
726
+ if (currentSession?.data === null || currentSession?.data === void 0 || event?.event === "visibilitychange") {
727
+ state.lastSync = now2();
728
+ sessionSignal.set(!sessionSignal.get());
729
+ }
730
+ };
731
+ const broadcastSessionUpdate = (trigger) => {
732
+ getGlobalBroadcastChannel().post({
733
+ event: "session",
734
+ data: { trigger },
735
+ clientId: Math.random().toString(36).substring(7)
736
+ });
737
+ };
738
+ const setupPolling = () => {
739
+ if (refetchInterval && refetchInterval > 0) state.pollInterval = setInterval(() => {
740
+ if (sessionAtom.get()?.data) triggerRefetch({ event: "poll" });
741
+ }, refetchInterval * 1e3);
742
+ };
743
+ const setupBroadcast = () => {
744
+ state.unsubscribeBroadcast = getGlobalBroadcastChannel().subscribe(() => {
745
+ triggerRefetch({ event: "storage" });
746
+ });
747
+ };
748
+ const setupFocusRefetch = () => {
749
+ if (!refetchOnWindowFocus) return;
750
+ state.unsubscribeFocus = getGlobalFocusManager().subscribe(() => {
751
+ triggerRefetch({ event: "visibilitychange" });
752
+ });
753
+ };
754
+ const setupOnlineRefetch = () => {
755
+ state.unsubscribeOnline = getGlobalOnlineManager().subscribe((online) => {
756
+ if (online) triggerRefetch({ event: "visibilitychange" });
757
+ });
758
+ };
759
+ const init = () => {
760
+ setupPolling();
761
+ setupBroadcast();
762
+ setupFocusRefetch();
763
+ setupOnlineRefetch();
764
+ getGlobalBroadcastChannel().setup();
765
+ getGlobalFocusManager().setup();
766
+ getGlobalOnlineManager().setup();
767
+ };
768
+ const cleanup = () => {
769
+ if (state.pollInterval) {
770
+ clearInterval(state.pollInterval);
771
+ state.pollInterval = void 0;
772
+ }
773
+ if (state.unsubscribeBroadcast) {
774
+ state.unsubscribeBroadcast();
775
+ state.unsubscribeBroadcast = void 0;
776
+ }
777
+ if (state.unsubscribeFocus) {
778
+ state.unsubscribeFocus();
779
+ state.unsubscribeFocus = void 0;
780
+ }
781
+ if (state.unsubscribeOnline) {
782
+ state.unsubscribeOnline();
783
+ state.unsubscribeOnline = void 0;
784
+ }
785
+ state.lastSync = 0;
786
+ state.lastSessionRequest = 0;
787
+ state.cachedSession = void 0;
788
+ };
789
+ return {
790
+ init,
791
+ cleanup,
792
+ triggerRefetch,
793
+ broadcastSessionUpdate
794
+ };
795
+ }
796
+
797
+ // ../../node_modules/better-auth/dist/client/session-atom.mjs
798
+ function getSessionAtom($fetch, options) {
799
+ const $signal = atom(false);
800
+ const session = useAuthQuery($signal, "/get-session", $fetch, { method: "GET" });
801
+ onMount(session, () => {
802
+ const refreshManager = createSessionRefreshManager({
803
+ sessionAtom: session,
804
+ sessionSignal: $signal,
805
+ $fetch,
806
+ options
807
+ });
808
+ refreshManager.init();
809
+ return () => {
810
+ refreshManager.cleanup();
811
+ };
812
+ });
813
+ return {
814
+ session,
815
+ $sessionSignal: $signal
816
+ };
817
+ }
818
+
819
+ // ../../node_modules/defu/dist/defu.mjs
820
+ function isPlainObject(value) {
821
+ if (value === null || typeof value !== "object") {
822
+ return false;
823
+ }
824
+ const prototype = Object.getPrototypeOf(value);
825
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
826
+ return false;
827
+ }
828
+ if (Symbol.iterator in value) {
829
+ return false;
830
+ }
831
+ if (Symbol.toStringTag in value) {
832
+ return Object.prototype.toString.call(value) === "[object Module]";
833
+ }
834
+ return true;
835
+ }
836
+ function _defu(baseObject, defaults, namespace = ".", merger) {
837
+ if (!isPlainObject(defaults)) {
838
+ return _defu(baseObject, {}, namespace, merger);
839
+ }
840
+ const object = Object.assign({}, defaults);
841
+ for (const key in baseObject) {
842
+ if (key === "__proto__" || key === "constructor") {
843
+ continue;
844
+ }
845
+ const value = baseObject[key];
846
+ if (value === null || value === void 0) {
847
+ continue;
848
+ }
849
+ if (merger && merger(object, key, value, namespace)) {
850
+ continue;
851
+ }
852
+ if (Array.isArray(value) && Array.isArray(object[key])) {
853
+ object[key] = [...value, ...object[key]];
854
+ } else if (isPlainObject(value) && isPlainObject(object[key])) {
855
+ object[key] = _defu(
856
+ value,
857
+ object[key],
858
+ (namespace ? `${namespace}.` : "") + key.toString(),
859
+ merger
860
+ );
861
+ } else {
862
+ object[key] = value;
863
+ }
864
+ }
865
+ return object;
866
+ }
867
+ function createDefu(merger) {
868
+ return (...arguments_) => (
869
+ // eslint-disable-next-line unicorn/no-array-reduce
870
+ arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
871
+ );
872
+ }
873
+ var defu = createDefu();
874
+
875
+ // ../../node_modules/@better-fetch/fetch/dist/index.js
876
+ var __defProp = Object.defineProperty;
877
+ var __defProps = Object.defineProperties;
878
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
879
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
880
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
881
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
882
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
883
+ var __spreadValues = (a, b) => {
884
+ for (var prop in b || (b = {}))
885
+ if (__hasOwnProp.call(b, prop))
886
+ __defNormalProp(a, prop, b[prop]);
887
+ if (__getOwnPropSymbols)
888
+ for (var prop of __getOwnPropSymbols(b)) {
889
+ if (__propIsEnum.call(b, prop))
890
+ __defNormalProp(a, prop, b[prop]);
891
+ }
892
+ return a;
893
+ };
894
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
895
+ var BetterFetchError = class extends Error {
896
+ constructor(status, statusText, error) {
897
+ super(statusText || status.toString(), {
898
+ cause: error
899
+ });
900
+ this.status = status;
901
+ this.statusText = statusText;
902
+ this.error = error;
903
+ Error.captureStackTrace(this, this.constructor);
904
+ }
905
+ };
906
+ var initializePlugins = async (url, options) => {
907
+ var _a, _b, _c, _d, _e, _f;
908
+ let opts = options || {};
909
+ const hooks = {
910
+ onRequest: [options == null ? void 0 : options.onRequest],
911
+ onResponse: [options == null ? void 0 : options.onResponse],
912
+ onSuccess: [options == null ? void 0 : options.onSuccess],
913
+ onError: [options == null ? void 0 : options.onError],
914
+ onRetry: [options == null ? void 0 : options.onRetry]
915
+ };
916
+ if (!options || !(options == null ? void 0 : options.plugins)) {
917
+ return {
918
+ url,
919
+ options: opts,
920
+ hooks
921
+ };
922
+ }
923
+ for (const plugin of (options == null ? void 0 : options.plugins) || []) {
924
+ if (plugin.init) {
925
+ const pluginRes = await ((_a = plugin.init) == null ? void 0 : _a.call(plugin, url.toString(), options));
926
+ opts = pluginRes.options || opts;
927
+ url = pluginRes.url;
928
+ }
929
+ hooks.onRequest.push((_b = plugin.hooks) == null ? void 0 : _b.onRequest);
930
+ hooks.onResponse.push((_c = plugin.hooks) == null ? void 0 : _c.onResponse);
931
+ hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess);
932
+ hooks.onError.push((_e = plugin.hooks) == null ? void 0 : _e.onError);
933
+ hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry);
934
+ }
935
+ return {
936
+ url,
937
+ options: opts,
938
+ hooks
939
+ };
940
+ };
941
+ var LinearRetryStrategy = class {
942
+ constructor(options) {
943
+ this.options = options;
944
+ }
945
+ shouldAttemptRetry(attempt, response) {
946
+ if (this.options.shouldRetry) {
947
+ return Promise.resolve(
948
+ attempt < this.options.attempts && this.options.shouldRetry(response)
949
+ );
950
+ }
951
+ return Promise.resolve(attempt < this.options.attempts);
952
+ }
953
+ getDelay() {
954
+ return this.options.delay;
955
+ }
956
+ };
957
+ var ExponentialRetryStrategy = class {
958
+ constructor(options) {
959
+ this.options = options;
960
+ }
961
+ shouldAttemptRetry(attempt, response) {
962
+ if (this.options.shouldRetry) {
963
+ return Promise.resolve(
964
+ attempt < this.options.attempts && this.options.shouldRetry(response)
965
+ );
966
+ }
967
+ return Promise.resolve(attempt < this.options.attempts);
968
+ }
969
+ getDelay(attempt) {
970
+ const delay = Math.min(
971
+ this.options.maxDelay,
972
+ this.options.baseDelay * 2 ** attempt
973
+ );
974
+ return delay;
975
+ }
976
+ };
977
+ function createRetryStrategy(options) {
978
+ if (typeof options === "number") {
979
+ return new LinearRetryStrategy({
980
+ type: "linear",
981
+ attempts: options,
982
+ delay: 1e3
983
+ });
984
+ }
985
+ switch (options.type) {
986
+ case "linear":
987
+ return new LinearRetryStrategy(options);
988
+ case "exponential":
989
+ return new ExponentialRetryStrategy(options);
990
+ default:
991
+ throw new Error("Invalid retry strategy");
992
+ }
993
+ }
994
+ var getAuthHeader = async (options) => {
995
+ const headers = {};
996
+ const getValue = async (value) => typeof value === "function" ? await value() : value;
997
+ if (options == null ? void 0 : options.auth) {
998
+ if (options.auth.type === "Bearer") {
999
+ const token = await getValue(options.auth.token);
1000
+ if (!token) {
1001
+ return headers;
1002
+ }
1003
+ headers["authorization"] = `Bearer ${token}`;
1004
+ } else if (options.auth.type === "Basic") {
1005
+ const [username, password] = await Promise.all([
1006
+ getValue(options.auth.username),
1007
+ getValue(options.auth.password)
1008
+ ]);
1009
+ if (!username || !password) {
1010
+ return headers;
1011
+ }
1012
+ headers["authorization"] = `Basic ${btoa(`${username}:${password}`)}`;
1013
+ } else if (options.auth.type === "Custom") {
1014
+ const [prefix, value] = await Promise.all([
1015
+ getValue(options.auth.prefix),
1016
+ getValue(options.auth.value)
1017
+ ]);
1018
+ if (!value) {
1019
+ return headers;
1020
+ }
1021
+ headers["authorization"] = `${prefix != null ? prefix : ""} ${value}`;
1022
+ }
1023
+ }
1024
+ return headers;
1025
+ };
1026
+ var JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
1027
+ function detectResponseType(request) {
1028
+ const _contentType = request.headers.get("content-type");
1029
+ const textTypes = /* @__PURE__ */ new Set([
1030
+ "image/svg",
1031
+ "application/xml",
1032
+ "application/xhtml",
1033
+ "application/html"
1034
+ ]);
1035
+ if (!_contentType) {
1036
+ return "json";
1037
+ }
1038
+ const contentType = _contentType.split(";").shift() || "";
1039
+ if (JSON_RE.test(contentType)) {
1040
+ return "json";
1041
+ }
1042
+ if (textTypes.has(contentType) || contentType.startsWith("text/")) {
1043
+ return "text";
1044
+ }
1045
+ return "blob";
1046
+ }
1047
+ function isJSONParsable(value) {
1048
+ try {
1049
+ JSON.parse(value);
1050
+ return true;
1051
+ } catch (error) {
1052
+ return false;
1053
+ }
1054
+ }
1055
+ function isJSONSerializable(value) {
1056
+ if (value === void 0) {
1057
+ return false;
1058
+ }
1059
+ const t = typeof value;
1060
+ if (t === "string" || t === "number" || t === "boolean" || t === null) {
1061
+ return true;
1062
+ }
1063
+ if (t !== "object") {
1064
+ return false;
1065
+ }
1066
+ if (Array.isArray(value)) {
1067
+ return true;
1068
+ }
1069
+ if (value.buffer) {
1070
+ return false;
1071
+ }
1072
+ return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
1073
+ }
1074
+ function jsonParse(text) {
1075
+ try {
1076
+ return JSON.parse(text);
1077
+ } catch (error) {
1078
+ return text;
1079
+ }
1080
+ }
1081
+ function isFunction(value) {
1082
+ return typeof value === "function";
1083
+ }
1084
+ function getFetch(options) {
1085
+ if (options == null ? void 0 : options.customFetchImpl) {
1086
+ return options.customFetchImpl;
1087
+ }
1088
+ if (typeof globalThis !== "undefined" && isFunction(globalThis.fetch)) {
1089
+ return globalThis.fetch;
1090
+ }
1091
+ if (typeof window !== "undefined" && isFunction(window.fetch)) {
1092
+ return window.fetch;
1093
+ }
1094
+ throw new Error("No fetch implementation found");
1095
+ }
1096
+ async function getHeaders(opts) {
1097
+ const headers = new Headers(opts == null ? void 0 : opts.headers);
1098
+ const authHeader = await getAuthHeader(opts);
1099
+ for (const [key, value] of Object.entries(authHeader || {})) {
1100
+ headers.set(key, value);
1101
+ }
1102
+ if (!headers.has("content-type")) {
1103
+ const t = detectContentType(opts == null ? void 0 : opts.body);
1104
+ if (t) {
1105
+ headers.set("content-type", t);
1106
+ }
1107
+ }
1108
+ return headers;
1109
+ }
1110
+ function detectContentType(body) {
1111
+ if (isJSONSerializable(body)) {
1112
+ return "application/json";
1113
+ }
1114
+ return null;
1115
+ }
1116
+ function getBody(options) {
1117
+ if (!(options == null ? void 0 : options.body)) {
1118
+ return null;
1119
+ }
1120
+ const headers = new Headers(options == null ? void 0 : options.headers);
1121
+ if (isJSONSerializable(options.body) && !headers.has("content-type")) {
1122
+ for (const [key, value] of Object.entries(options == null ? void 0 : options.body)) {
1123
+ if (value instanceof Date) {
1124
+ options.body[key] = value.toISOString();
1125
+ }
1126
+ }
1127
+ return JSON.stringify(options.body);
1128
+ }
1129
+ if (headers.has("content-type") && headers.get("content-type") === "application/x-www-form-urlencoded") {
1130
+ if (isJSONSerializable(options.body)) {
1131
+ return new URLSearchParams(options.body).toString();
1132
+ }
1133
+ return options.body;
1134
+ }
1135
+ return options.body;
1136
+ }
1137
+ function getMethod(url, options) {
1138
+ var _a;
1139
+ if (options == null ? void 0 : options.method) {
1140
+ return options.method.toUpperCase();
1141
+ }
1142
+ if (url.startsWith("@")) {
1143
+ const pMethod = (_a = url.split("@")[1]) == null ? void 0 : _a.split("/")[0];
1144
+ if (!methods.includes(pMethod)) {
1145
+ return (options == null ? void 0 : options.body) ? "POST" : "GET";
1146
+ }
1147
+ return pMethod.toUpperCase();
1148
+ }
1149
+ return (options == null ? void 0 : options.body) ? "POST" : "GET";
1150
+ }
1151
+ function getTimeout(options, controller) {
1152
+ let abortTimeout;
1153
+ if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) {
1154
+ abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout);
1155
+ }
1156
+ return {
1157
+ abortTimeout,
1158
+ clearTimeout: () => {
1159
+ if (abortTimeout) {
1160
+ clearTimeout(abortTimeout);
1161
+ }
1162
+ }
1163
+ };
1164
+ }
1165
+ var ValidationError = class _ValidationError extends Error {
1166
+ constructor(issues, message) {
1167
+ super(message || JSON.stringify(issues, null, 2));
1168
+ this.issues = issues;
1169
+ Object.setPrototypeOf(this, _ValidationError.prototype);
1170
+ }
1171
+ };
1172
+ async function parseStandardSchema(schema, input) {
1173
+ const result = await schema["~standard"].validate(input);
1174
+ if (result.issues) {
1175
+ throw new ValidationError(result.issues);
1176
+ }
1177
+ return result.value;
1178
+ }
1179
+ var methods = ["get", "post", "put", "patch", "delete"];
1180
+ var applySchemaPlugin = (config) => ({
1181
+ id: "apply-schema",
1182
+ name: "Apply Schema",
1183
+ version: "1.0.0",
1184
+ async init(url, options) {
1185
+ var _a, _b, _c, _d;
1186
+ const schema = ((_b = (_a = config.plugins) == null ? void 0 : _a.find(
1187
+ (plugin) => {
1188
+ var _a2;
1189
+ return ((_a2 = plugin.schema) == null ? void 0 : _a2.config) ? url.startsWith(plugin.schema.config.baseURL || "") || url.startsWith(plugin.schema.config.prefix || "") : false;
1190
+ }
1191
+ )) == null ? void 0 : _b.schema) || config.schema;
1192
+ if (schema) {
1193
+ let urlKey = url;
1194
+ if ((_c = schema.config) == null ? void 0 : _c.prefix) {
1195
+ if (urlKey.startsWith(schema.config.prefix)) {
1196
+ urlKey = urlKey.replace(schema.config.prefix, "");
1197
+ if (schema.config.baseURL) {
1198
+ url = url.replace(schema.config.prefix, schema.config.baseURL);
1199
+ }
1200
+ }
1201
+ }
1202
+ if ((_d = schema.config) == null ? void 0 : _d.baseURL) {
1203
+ if (urlKey.startsWith(schema.config.baseURL)) {
1204
+ urlKey = urlKey.replace(schema.config.baseURL, "");
1205
+ }
1206
+ }
1207
+ const keySchema = schema.schema[urlKey];
1208
+ if (keySchema) {
1209
+ let opts = __spreadProps(__spreadValues({}, options), {
1210
+ method: keySchema.method,
1211
+ output: keySchema.output
1212
+ });
1213
+ if (!(options == null ? void 0 : options.disableValidation)) {
1214
+ opts = __spreadProps(__spreadValues({}, opts), {
1215
+ body: keySchema.input ? await parseStandardSchema(keySchema.input, options == null ? void 0 : options.body) : options == null ? void 0 : options.body,
1216
+ params: keySchema.params ? await parseStandardSchema(keySchema.params, options == null ? void 0 : options.params) : options == null ? void 0 : options.params,
1217
+ query: keySchema.query ? await parseStandardSchema(keySchema.query, options == null ? void 0 : options.query) : options == null ? void 0 : options.query
1218
+ });
1219
+ }
1220
+ return {
1221
+ url,
1222
+ options: opts
1223
+ };
1224
+ }
1225
+ }
1226
+ return {
1227
+ url,
1228
+ options
1229
+ };
1230
+ }
1231
+ });
1232
+ var createFetch = (config) => {
1233
+ async function $fetch(url, options) {
1234
+ const opts = __spreadProps(__spreadValues(__spreadValues({}, config), options), {
1235
+ plugins: [...(config == null ? void 0 : config.plugins) || [], applySchemaPlugin(config || {}), ...(options == null ? void 0 : options.plugins) || []]
1236
+ });
1237
+ if (config == null ? void 0 : config.catchAllError) {
1238
+ try {
1239
+ return await betterFetch(url, opts);
1240
+ } catch (error) {
1241
+ return {
1242
+ data: null,
1243
+ error: {
1244
+ status: 500,
1245
+ statusText: "Fetch Error",
1246
+ message: "Fetch related error. Captured by catchAllError option. See error property for more details.",
1247
+ error
1248
+ }
1249
+ };
1250
+ }
1251
+ }
1252
+ return await betterFetch(url, opts);
1253
+ }
1254
+ return $fetch;
1255
+ };
1256
+ function getURL2(url, option) {
1257
+ const { baseURL, params, query } = option || {
1258
+ query: {},
1259
+ params: {},
1260
+ baseURL: ""
1261
+ };
1262
+ let basePath = url.startsWith("http") ? url.split("/").slice(0, 3).join("/") : baseURL || "";
1263
+ if (url.startsWith("@")) {
1264
+ const m = url.toString().split("@")[1].split("/")[0];
1265
+ if (methods.includes(m)) {
1266
+ url = url.replace(`@${m}/`, "/");
1267
+ }
1268
+ }
1269
+ if (!basePath.endsWith("/")) basePath += "/";
1270
+ let [path, urlQuery] = url.replace(basePath, "").split("?");
1271
+ const queryParams = new URLSearchParams(urlQuery);
1272
+ for (const [key, value] of Object.entries(query || {})) {
1273
+ if (value == null) continue;
1274
+ let serializedValue;
1275
+ if (typeof value === "string") {
1276
+ serializedValue = value;
1277
+ } else if (Array.isArray(value)) {
1278
+ for (const val of value) {
1279
+ queryParams.append(key, val);
1280
+ }
1281
+ continue;
1282
+ } else {
1283
+ serializedValue = JSON.stringify(value);
1284
+ }
1285
+ queryParams.set(key, serializedValue);
1286
+ }
1287
+ if (params) {
1288
+ if (Array.isArray(params)) {
1289
+ const paramPaths = path.split("/").filter((p) => p.startsWith(":"));
1290
+ for (const [index, key] of paramPaths.entries()) {
1291
+ const value = params[index];
1292
+ path = path.replace(key, value);
1293
+ }
1294
+ } else {
1295
+ for (const [key, value] of Object.entries(params)) {
1296
+ path = path.replace(`:${key}`, String(value));
1297
+ }
1298
+ }
1299
+ }
1300
+ path = path.split("/").map(encodeURIComponent).join("/");
1301
+ if (path.startsWith("/")) path = path.slice(1);
1302
+ let queryParamString = queryParams.toString();
1303
+ queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\+/g, "%20") : "";
1304
+ if (!basePath.startsWith("http")) {
1305
+ return `${basePath}${path}${queryParamString}`;
1306
+ }
1307
+ const _url = new URL(`${path}${queryParamString}`, basePath);
1308
+ return _url;
1309
+ }
1310
+ var betterFetch = async (url, options) => {
1311
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1312
+ const {
1313
+ hooks,
1314
+ url: __url,
1315
+ options: opts
1316
+ } = await initializePlugins(url, options);
1317
+ const fetch2 = getFetch(opts);
1318
+ const controller = new AbortController();
1319
+ const signal = (_a = opts.signal) != null ? _a : controller.signal;
1320
+ const _url = getURL2(__url, opts);
1321
+ const body = getBody(opts);
1322
+ const headers = await getHeaders(opts);
1323
+ const method = getMethod(__url, opts);
1324
+ let context = __spreadProps(__spreadValues({}, opts), {
1325
+ url: _url,
1326
+ headers,
1327
+ body,
1328
+ method,
1329
+ signal
1330
+ });
1331
+ for (const onRequest of hooks.onRequest) {
1332
+ if (onRequest) {
1333
+ const res = await onRequest(context);
1334
+ if (typeof res === "object" && res !== null) {
1335
+ context = res;
1336
+ }
1337
+ }
1338
+ }
1339
+ if ("pipeTo" in context && typeof context.pipeTo === "function" || typeof ((_b = options == null ? void 0 : options.body) == null ? void 0 : _b.pipe) === "function") {
1340
+ if (!("duplex" in context)) {
1341
+ context.duplex = "half";
1342
+ }
1343
+ }
1344
+ const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller);
1345
+ let response = await fetch2(context.url, context);
1346
+ clearTimeout2();
1347
+ const responseContext = {
1348
+ response,
1349
+ request: context
1350
+ };
1351
+ for (const onResponse of hooks.onResponse) {
1352
+ if (onResponse) {
1353
+ const r = await onResponse(__spreadProps(__spreadValues({}, responseContext), {
1354
+ response: ((_c = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c.cloneResponse) ? response.clone() : response
1355
+ }));
1356
+ if (r instanceof Response) {
1357
+ response = r;
1358
+ } else if (typeof r === "object" && r !== null) {
1359
+ response = r.response;
1360
+ }
1361
+ }
1362
+ }
1363
+ if (response.ok) {
1364
+ const hasBody = context.method !== "HEAD";
1365
+ if (!hasBody) {
1366
+ return {
1367
+ data: "",
1368
+ error: null
1369
+ };
1370
+ }
1371
+ const responseType = detectResponseType(response);
1372
+ const successContext = {
1373
+ data: null,
1374
+ response,
1375
+ request: context
1376
+ };
1377
+ if (responseType === "json" || responseType === "text") {
1378
+ const text = await response.text();
1379
+ const parser2 = (_d = context.jsonParser) != null ? _d : jsonParse;
1380
+ successContext.data = await parser2(text);
1381
+ } else {
1382
+ successContext.data = await response[responseType]();
1383
+ }
1384
+ if (context == null ? void 0 : context.output) {
1385
+ if (context.output && !context.disableValidation) {
1386
+ successContext.data = await parseStandardSchema(
1387
+ context.output,
1388
+ successContext.data
1389
+ );
1390
+ }
1391
+ }
1392
+ for (const onSuccess of hooks.onSuccess) {
1393
+ if (onSuccess) {
1394
+ await onSuccess(__spreadProps(__spreadValues({}, successContext), {
1395
+ response: ((_e = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e.cloneResponse) ? response.clone() : response
1396
+ }));
1397
+ }
1398
+ }
1399
+ if (options == null ? void 0 : options.throw) {
1400
+ return successContext.data;
1401
+ }
1402
+ return {
1403
+ data: successContext.data,
1404
+ error: null
1405
+ };
1406
+ }
1407
+ const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse;
1408
+ const responseText = await response.text();
1409
+ const isJSONResponse = isJSONParsable(responseText);
1410
+ const errorObject = isJSONResponse ? await parser(responseText) : null;
1411
+ const errorContext = {
1412
+ response,
1413
+ responseText,
1414
+ request: context,
1415
+ error: __spreadProps(__spreadValues({}, errorObject), {
1416
+ status: response.status,
1417
+ statusText: response.statusText
1418
+ })
1419
+ };
1420
+ for (const onError of hooks.onError) {
1421
+ if (onError) {
1422
+ await onError(__spreadProps(__spreadValues({}, errorContext), {
1423
+ response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response
1424
+ }));
1425
+ }
1426
+ }
1427
+ if (options == null ? void 0 : options.retry) {
1428
+ const retryStrategy = createRetryStrategy(options.retry);
1429
+ const _retryAttempt = (_h = options.retryAttempt) != null ? _h : 0;
1430
+ if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) {
1431
+ for (const onRetry of hooks.onRetry) {
1432
+ if (onRetry) {
1433
+ await onRetry(responseContext);
1434
+ }
1435
+ }
1436
+ const delay = retryStrategy.getDelay(_retryAttempt);
1437
+ await new Promise((resolve) => setTimeout(resolve, delay));
1438
+ return await betterFetch(url, __spreadProps(__spreadValues({}, options), {
1439
+ retryAttempt: _retryAttempt + 1
1440
+ }));
1441
+ }
1442
+ }
1443
+ if (options == null ? void 0 : options.throw) {
1444
+ throw new BetterFetchError(
1445
+ response.status,
1446
+ response.statusText,
1447
+ isJSONResponse ? errorObject : responseText
1448
+ );
1449
+ }
1450
+ return {
1451
+ data: null,
1452
+ error: __spreadProps(__spreadValues({}, errorObject), {
1453
+ status: response.status,
1454
+ statusText: response.statusText
1455
+ })
1456
+ };
1457
+ };
1458
+
1459
+ // ../../node_modules/better-auth/dist/client/config.mjs
1460
+ var getClientConfig = (options, loadEnv) => {
1461
+ const isCredentialsSupported = "credentials" in Request.prototype;
1462
+ const baseURL = getBaseURL(options?.baseURL, options?.basePath) ?? "/api/auth";
1463
+ const pluginsFetchPlugins = options?.plugins?.flatMap((plugin) => plugin.fetchPlugins).filter((pl) => pl !== void 0) || [];
1464
+ const lifeCyclePlugin = {
1465
+ id: "lifecycle-hooks",
1466
+ name: "lifecycle-hooks",
1467
+ hooks: {
1468
+ onSuccess: options?.fetchOptions?.onSuccess,
1469
+ onError: options?.fetchOptions?.onError,
1470
+ onRequest: options?.fetchOptions?.onRequest,
1471
+ onResponse: options?.fetchOptions?.onResponse
1472
+ }
1473
+ };
1474
+ const { onSuccess: _onSuccess, onError: _onError, onRequest: _onRequest, onResponse: _onResponse, ...restOfFetchOptions } = options?.fetchOptions || {};
1475
+ const $fetch = createFetch({
1476
+ baseURL,
1477
+ ...isCredentialsSupported ? { credentials: "include" } : {},
1478
+ method: "GET",
1479
+ jsonParser(text) {
1480
+ if (!text) return null;
1481
+ return parseJSON(text, { strict: false });
1482
+ },
1483
+ customFetchImpl: fetch,
1484
+ ...restOfFetchOptions,
1485
+ plugins: [
1486
+ lifeCyclePlugin,
1487
+ ...restOfFetchOptions.plugins || [],
1488
+ ...options?.disableDefaultFetchPlugins ? [] : [redirectPlugin],
1489
+ ...pluginsFetchPlugins
1490
+ ]
1491
+ });
1492
+ const { $sessionSignal, session } = getSessionAtom($fetch, options);
1493
+ const plugins = options?.plugins || [];
1494
+ let pluginsActions = {};
1495
+ const pluginsAtoms = {
1496
+ $sessionSignal,
1497
+ session
1498
+ };
1499
+ const pluginPathMethods = {
1500
+ "/sign-out": "POST",
1501
+ "/revoke-sessions": "POST",
1502
+ "/revoke-other-sessions": "POST",
1503
+ "/delete-user": "POST"
1504
+ };
1505
+ const atomListeners = [{
1506
+ signal: "$sessionSignal",
1507
+ matcher(path) {
1508
+ return path === "/sign-out" || path === "/update-user" || path === "/sign-up/email" || path === "/sign-in/email" || path === "/delete-user" || path === "/verify-email" || path === "/revoke-sessions" || path === "/revoke-session" || path === "/change-email";
1509
+ }
1510
+ }];
1511
+ for (const plugin of plugins) {
1512
+ if (plugin.getAtoms) Object.assign(pluginsAtoms, plugin.getAtoms?.($fetch));
1513
+ if (plugin.pathMethods) Object.assign(pluginPathMethods, plugin.pathMethods);
1514
+ if (plugin.atomListeners) atomListeners.push(...plugin.atomListeners);
1515
+ }
1516
+ const $store = {
1517
+ notify: (signal) => {
1518
+ pluginsAtoms[signal].set(!pluginsAtoms[signal].get());
1519
+ },
1520
+ listen: (signal, listener) => {
1521
+ pluginsAtoms[signal].subscribe(listener);
1522
+ },
1523
+ atoms: pluginsAtoms
1524
+ };
1525
+ for (const plugin of plugins) if (plugin.getActions) pluginsActions = defu(plugin.getActions?.($fetch, $store, options) ?? {}, pluginsActions);
1526
+ return {
1527
+ get baseURL() {
1528
+ return baseURL;
1529
+ },
1530
+ pluginsActions,
1531
+ pluginsAtoms,
1532
+ pluginPathMethods,
1533
+ atomListeners,
1534
+ $fetch,
1535
+ $store
1536
+ };
1537
+ };
1538
+
1539
+ // ../../node_modules/better-auth/dist/utils/is-atom.mjs
1540
+ function isAtom(value) {
1541
+ return typeof value === "object" && value !== null && "get" in value && typeof value.get === "function" && "lc" in value && typeof value.lc === "number";
1542
+ }
1543
+
1544
+ // ../../node_modules/better-auth/dist/client/proxy.mjs
1545
+ function getMethod2(path, knownPathMethods, args) {
1546
+ const method = knownPathMethods[path];
1547
+ const { fetchOptions, query: _query, ...body } = args || {};
1548
+ if (method) return method;
1549
+ if (fetchOptions?.method) return fetchOptions.method;
1550
+ if (body && Object.keys(body).length > 0) return "POST";
1551
+ return "GET";
1552
+ }
1553
+ function createDynamicPathProxy(routes, client, knownPathMethods, atoms, atomListeners) {
1554
+ function createProxy(path = []) {
1555
+ return new Proxy(function() {
1556
+ }, {
1557
+ get(_, prop) {
1558
+ if (typeof prop !== "string") return;
1559
+ if (prop === "then" || prop === "catch" || prop === "finally") return;
1560
+ const fullPath = [...path, prop];
1561
+ let current = routes;
1562
+ for (const segment of fullPath) if (current && typeof current === "object" && segment in current) current = current[segment];
1563
+ else {
1564
+ current = void 0;
1565
+ break;
1566
+ }
1567
+ if (typeof current === "function") return current;
1568
+ if (isAtom(current)) return current;
1569
+ return createProxy(fullPath);
1570
+ },
1571
+ apply: async (_, __, args) => {
1572
+ const routePath = "/" + path.map((segment) => segment.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)).join("/");
1573
+ const arg = args[0] || {};
1574
+ const fetchOptions = args[1] || {};
1575
+ const { query, fetchOptions: argFetchOptions, ...body } = arg;
1576
+ const options = {
1577
+ ...fetchOptions,
1578
+ ...argFetchOptions
1579
+ };
1580
+ const method = getMethod2(routePath, knownPathMethods, arg);
1581
+ return await client(routePath, {
1582
+ ...options,
1583
+ body: method === "GET" ? void 0 : {
1584
+ ...body,
1585
+ ...options?.body || {}
1586
+ },
1587
+ query: query || options?.query,
1588
+ method,
1589
+ async onSuccess(context) {
1590
+ await options?.onSuccess?.(context);
1591
+ if (!atomListeners || options.disableSignal) return;
1592
+ const matches = atomListeners.filter((s) => s.matcher(routePath));
1593
+ if (!matches.length) return;
1594
+ const visited = /* @__PURE__ */ new Set();
1595
+ for (const match of matches) {
1596
+ const signal = atoms[match.signal];
1597
+ if (!signal) return;
1598
+ if (visited.has(match.signal)) continue;
1599
+ visited.add(match.signal);
1600
+ const val = signal.get();
1601
+ setTimeout(() => {
1602
+ signal.set(!val);
1603
+ }, 10);
1604
+ }
1605
+ }
1606
+ });
1607
+ }
1608
+ });
1609
+ }
1610
+ return createProxy();
1611
+ }
1612
+ function useStore(store, options = {}) {
1613
+ const snapshotRef = react.useRef(store.get());
1614
+ const { keys, deps = [store, keys] } = options;
1615
+ const subscribe = react.useCallback((onChange) => {
1616
+ const emitChange = (value) => {
1617
+ if (snapshotRef.current === value) return;
1618
+ snapshotRef.current = value;
1619
+ onChange();
1620
+ };
1621
+ emitChange(store.value);
1622
+ if (keys?.length) return listenKeys(store, keys, emitChange);
1623
+ return store.listen(emitChange);
1624
+ }, deps);
1625
+ const get = () => snapshotRef.current;
1626
+ return react.useSyncExternalStore(subscribe, get, get);
1627
+ }
1628
+
1629
+ // ../../node_modules/better-auth/dist/client/react/index.mjs
1630
+ function getAtomKey(str) {
1631
+ return `use${capitalizeFirstLetter(str)}`;
1632
+ }
1633
+ function createAuthClient(options) {
1634
+ const { pluginPathMethods, pluginsActions, pluginsAtoms, $fetch, $store, atomListeners } = getClientConfig(options);
1635
+ const resolvedHooks = {};
1636
+ for (const [key, value] of Object.entries(pluginsAtoms)) resolvedHooks[getAtomKey(key)] = () => useStore(value);
1637
+ return createDynamicPathProxy({
1638
+ ...pluginsActions,
1639
+ ...resolvedHooks,
1640
+ $fetch,
1641
+ $store
1642
+ }, $fetch, pluginPathMethods, pluginsAtoms, atomListeners);
1643
+ }
1644
+
1645
+ exports.createAuthClient = createAuthClient;
1646
+ exports.useStore = useStore;
1647
+ //# sourceMappingURL=react.js.map
1648
+ //# sourceMappingURL=react.js.map