@finueva/auth 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.
package/dist/index.js ADDED
@@ -0,0 +1,2438 @@
1
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/broadcast-channel.mjs
2
+ const kBroadcastChannel = Symbol.for("better-auth:broadcast-channel");
3
+ const now$1 = () => Math.floor(Date.now() / 1e3);
4
+ var WindowBroadcastChannel = class {
5
+ listeners = new Set();
6
+ name;
7
+ constructor(name = "better-auth.message") {
8
+ this.name = name;
9
+ }
10
+ subscribe(listener) {
11
+ this.listeners.add(listener);
12
+ return () => {
13
+ this.listeners.delete(listener);
14
+ };
15
+ }
16
+ post(message) {
17
+ if (typeof window === "undefined") return;
18
+ try {
19
+ localStorage.setItem(this.name, JSON.stringify({
20
+ ...message,
21
+ timestamp: now$1()
22
+ }));
23
+ } catch {}
24
+ }
25
+ setup() {
26
+ if (typeof window === "undefined" || typeof window.addEventListener === "undefined") return () => {};
27
+ const handler = (event) => {
28
+ if (event.key !== this.name) return;
29
+ const message = JSON.parse(event.newValue ?? "{}");
30
+ if (message?.event !== "session" || !message?.data) return;
31
+ this.listeners.forEach((listener) => listener(message));
32
+ };
33
+ window.addEventListener("storage", handler);
34
+ return () => {
35
+ window.removeEventListener("storage", handler);
36
+ };
37
+ }
38
+ };
39
+ function getGlobalBroadcastChannel(name = "better-auth.message") {
40
+ if (!globalThis[kBroadcastChannel]) globalThis[kBroadcastChannel] = new WindowBroadcastChannel(name);
41
+ return globalThis[kBroadcastChannel];
42
+ }
43
+ //#endregion
44
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/clean-stores/index.js
45
+ const clean = Symbol("clean");
46
+ //#endregion
47
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/atom/index.js
48
+ let listenerQueue = [];
49
+ let lqIndex = 0;
50
+ const QUEUE_ITEMS_PER_LISTENER = 4;
51
+ const nanostoresGlobal = globalThis.nanostoresGlobal ||= { epoch: 0 };
52
+ const atom = (initialValue) => {
53
+ let listeners = [];
54
+ let $atom = {
55
+ get() {
56
+ if (!$atom.lc) $atom.listen(() => {})();
57
+ return $atom.value;
58
+ },
59
+ init: initialValue,
60
+ lc: 0,
61
+ listen(listener) {
62
+ $atom.lc = listeners.push(listener);
63
+ return () => {
64
+ for (let i = lqIndex + QUEUE_ITEMS_PER_LISTENER; i < listenerQueue.length;) if (listenerQueue[i] === listener) listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER);
65
+ else i += QUEUE_ITEMS_PER_LISTENER;
66
+ let index = listeners.indexOf(listener);
67
+ if (~index) {
68
+ listeners.splice(index, 1);
69
+ if (!--$atom.lc) $atom.off();
70
+ }
71
+ };
72
+ },
73
+ notify(oldValue, changedKey) {
74
+ nanostoresGlobal.epoch++;
75
+ let runListenerQueue = !listenerQueue.length;
76
+ for (let listener of listeners) listenerQueue.push(listener, $atom.value, oldValue, changedKey);
77
+ if (runListenerQueue) {
78
+ for (lqIndex = 0; lqIndex < listenerQueue.length; lqIndex += QUEUE_ITEMS_PER_LISTENER) listenerQueue[lqIndex](listenerQueue[lqIndex + 1], listenerQueue[lqIndex + 2], listenerQueue[lqIndex + 3]);
79
+ listenerQueue.length = 0;
80
+ }
81
+ },
82
+ off() {},
83
+ set(newValue) {
84
+ let oldValue = $atom.value;
85
+ if (oldValue !== newValue) {
86
+ $atom.value = newValue;
87
+ $atom.notify(oldValue);
88
+ }
89
+ },
90
+ subscribe(listener) {
91
+ let unbind = $atom.listen(listener);
92
+ listener($atom.value);
93
+ return unbind;
94
+ },
95
+ value: initialValue
96
+ };
97
+ $atom[clean] = () => {
98
+ listeners = [];
99
+ $atom.lc = 0;
100
+ $atom.off();
101
+ };
102
+ return $atom;
103
+ };
104
+ //#endregion
105
+ //#region ../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/lifecycle/index.js
106
+ const SET = 2;
107
+ const MOUNT = 5;
108
+ const UNMOUNT = 6;
109
+ const REVERT_MUTATION = 10;
110
+ let on = (object, listener, eventKey, mutateStore) => {
111
+ object.events = object.events || {};
112
+ if (!object.events[eventKey + REVERT_MUTATION]) object.events[eventKey + REVERT_MUTATION] = mutateStore((eventProps) => {
113
+ object.events[eventKey].reduceRight((event, l) => (l(event), event), {
114
+ shared: {},
115
+ ...eventProps
116
+ });
117
+ });
118
+ object.events[eventKey] = object.events[eventKey] || [];
119
+ object.events[eventKey].push(listener);
120
+ return () => {
121
+ let currentListeners = object.events[eventKey];
122
+ let index = currentListeners.indexOf(listener);
123
+ currentListeners.splice(index, 1);
124
+ if (!currentListeners.length) {
125
+ delete object.events[eventKey];
126
+ object.events[eventKey + REVERT_MUTATION]();
127
+ delete object.events[eventKey + REVERT_MUTATION];
128
+ }
129
+ };
130
+ };
131
+ let onSet = ($store, listener) => on($store, listener, SET, (runListeners) => {
132
+ let originSet = $store.set;
133
+ let originSetKey = $store.setKey;
134
+ if ($store.setKey) $store.setKey = (changed, changedValue) => {
135
+ let isAborted;
136
+ let abort = () => {
137
+ isAborted = true;
138
+ };
139
+ runListeners({
140
+ abort,
141
+ changed,
142
+ newValue: {
143
+ ...$store.value,
144
+ [changed]: changedValue
145
+ }
146
+ });
147
+ if (!isAborted) return originSetKey(changed, changedValue);
148
+ };
149
+ $store.set = (newValue) => {
150
+ let isAborted;
151
+ let abort = () => {
152
+ isAborted = true;
153
+ };
154
+ runListeners({
155
+ abort,
156
+ newValue
157
+ });
158
+ if (!isAborted) return originSet(newValue);
159
+ };
160
+ return () => {
161
+ $store.set = originSet;
162
+ $store.setKey = originSetKey;
163
+ };
164
+ });
165
+ const STORE_UNMOUNT_DELAY = 1e3;
166
+ let onMount = ($store, initialize) => {
167
+ let listener = (payload) => {
168
+ let destroy = initialize(payload);
169
+ if (destroy) $store.events[UNMOUNT].push(destroy);
170
+ };
171
+ return on($store, listener, MOUNT, (runListeners) => {
172
+ let originListen = $store.listen;
173
+ $store.listen = (...args) => {
174
+ if (!$store.lc && !$store.active) {
175
+ $store.active = true;
176
+ runListeners();
177
+ }
178
+ return originListen(...args);
179
+ };
180
+ let originOff = $store.off;
181
+ $store.events[UNMOUNT] = [];
182
+ $store.off = () => {
183
+ originOff();
184
+ setTimeout(() => {
185
+ if ($store.active && !$store.lc) {
186
+ $store.active = false;
187
+ for (let destroy of $store.events[UNMOUNT]) destroy();
188
+ $store.events[UNMOUNT] = [];
189
+ }
190
+ }, STORE_UNMOUNT_DELAY);
191
+ };
192
+ {
193
+ let originClean = $store[clean];
194
+ $store[clean] = () => {
195
+ for (let destroy of $store.events[UNMOUNT]) destroy();
196
+ $store.events[UNMOUNT] = [];
197
+ $store.active = false;
198
+ originClean();
199
+ };
200
+ }
201
+ return () => {
202
+ $store.listen = originListen;
203
+ $store.off = originOff;
204
+ };
205
+ });
206
+ };
207
+ //#endregion
208
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/equality.mjs
209
+ function isPlainObject$1(value) {
210
+ if (typeof value !== "object" || value === null) return false;
211
+ const prototype = Object.getPrototypeOf(value);
212
+ return prototype === Object.prototype || prototype === null;
213
+ }
214
+ function isJsonEqual(a, b) {
215
+ if (a === b) return true;
216
+ if (Array.isArray(a) && Array.isArray(b)) {
217
+ if (a.length !== b.length) return false;
218
+ for (let i = 0; i < a.length; i++) if (!isJsonEqual(a[i], b[i])) return false;
219
+ return true;
220
+ }
221
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
222
+ const keysA = Object.keys(a);
223
+ const keysB = Object.keys(b);
224
+ if (keysA.length !== keysB.length) return false;
225
+ for (const key of keysA) if (!(key in b) || !isJsonEqual(a[key], b[key])) return false;
226
+ return true;
227
+ }
228
+ return false;
229
+ }
230
+ function withEquality(store, isEqual) {
231
+ return onSet(store, ({ newValue, abort }) => {
232
+ if (isEqual(store.value, newValue)) abort();
233
+ });
234
+ }
235
+ //#endregion
236
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/focus-manager.mjs
237
+ const kFocusManager = Symbol.for("better-auth:focus-manager");
238
+ var WindowFocusManager = class {
239
+ listeners = new Set();
240
+ subscribe(listener) {
241
+ this.listeners.add(listener);
242
+ return () => {
243
+ this.listeners.delete(listener);
244
+ };
245
+ }
246
+ setFocused(focused) {
247
+ this.listeners.forEach((listener) => listener(focused));
248
+ }
249
+ setup() {
250
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof window.addEventListener === "undefined") return () => {};
251
+ const visibilityHandler = () => {
252
+ if (document.visibilityState === "visible") this.setFocused(true);
253
+ };
254
+ document.addEventListener("visibilitychange", visibilityHandler, false);
255
+ return () => {
256
+ document.removeEventListener("visibilitychange", visibilityHandler, false);
257
+ };
258
+ }
259
+ };
260
+ function getGlobalFocusManager() {
261
+ if (!globalThis[kFocusManager]) globalThis[kFocusManager] = new WindowFocusManager();
262
+ return globalThis[kFocusManager];
263
+ }
264
+ //#endregion
265
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/online-manager.mjs
266
+ const kOnlineManager = Symbol.for("better-auth:online-manager");
267
+ var WindowOnlineManager = class {
268
+ listeners = new Set();
269
+ isOnline = typeof navigator !== "undefined" ? navigator.onLine : true;
270
+ subscribe(listener) {
271
+ this.listeners.add(listener);
272
+ return () => {
273
+ this.listeners.delete(listener);
274
+ };
275
+ }
276
+ setOnline(online) {
277
+ this.isOnline = online;
278
+ this.listeners.forEach((listener) => listener(online));
279
+ }
280
+ setup() {
281
+ if (typeof window === "undefined" || typeof window.addEventListener === "undefined") return () => {};
282
+ const onOnline = () => this.setOnline(true);
283
+ const onOffline = () => this.setOnline(false);
284
+ window.addEventListener("online", onOnline, false);
285
+ window.addEventListener("offline", onOffline, false);
286
+ return () => {
287
+ window.removeEventListener("online", onOnline, false);
288
+ window.removeEventListener("offline", onOffline, false);
289
+ };
290
+ }
291
+ };
292
+ function getGlobalOnlineManager() {
293
+ if (!globalThis[kOnlineManager]) globalThis[kOnlineManager] = new WindowOnlineManager();
294
+ return globalThis[kOnlineManager];
295
+ }
296
+ //#endregion
297
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/parser.mjs
298
+ const PROTO_POLLUTION_PATTERNS = {
299
+ 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*:/,
300
+ 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*:/,
301
+ protoShort: /"__proto__"\s*:/,
302
+ constructorShort: /"constructor"\s*:/
303
+ };
304
+ const JSON_SIGNATURE = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
305
+ const SPECIAL_VALUES = {
306
+ true: true,
307
+ false: false,
308
+ null: null,
309
+ undefined: void 0,
310
+ nan: NaN,
311
+ infinity: Number.POSITIVE_INFINITY,
312
+ "-infinity": Number.NEGATIVE_INFINITY
313
+ };
314
+ const ISO_DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
315
+ function isValidDate(date) {
316
+ return date instanceof Date && !isNaN(date.getTime());
317
+ }
318
+ function parseISODate(value) {
319
+ const match = ISO_DATE_REGEX.exec(value);
320
+ if (!match) return null;
321
+ const [, year, month, day, hour, minute, second, ms, offsetSign, offsetHour, offsetMinute] = match;
322
+ 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));
323
+ if (offsetSign) {
324
+ const offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === "+" ? -1 : 1);
325
+ date.setUTCMinutes(date.getUTCMinutes() + offset);
326
+ }
327
+ return isValidDate(date) ? date : null;
328
+ }
329
+ function betterJSONParse(value, options = {}) {
330
+ const { strict = false, warnings = false, reviver, parseDates = true } = options;
331
+ if (typeof value !== "string") return value;
332
+ const trimmed = value.trim();
333
+ const lowerValue = trimmed.toLowerCase();
334
+ if (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue];
335
+ if (!JSON_SIGNATURE.test(trimmed)) {
336
+ if (strict) throw new SyntaxError("[better-json] Invalid JSON");
337
+ return value;
338
+ }
339
+ if (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => {
340
+ const matches = pattern.test(trimmed);
341
+ if (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`);
342
+ return matches;
343
+ }) && strict) throw new Error("[better-json] Potential prototype pollution attempt detected");
344
+ try {
345
+ const secureReviver = (key, value) => {
346
+ if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
347
+ if (warnings) console.warn(`[better-json] Dropping "${key}" key to prevent prototype pollution`);
348
+ return;
349
+ }
350
+ if (parseDates && typeof value === "string") {
351
+ const date = parseISODate(value);
352
+ if (date) return date;
353
+ }
354
+ return reviver ? reviver(key, value) : value;
355
+ };
356
+ return JSON.parse(trimmed, secureReviver);
357
+ } catch (error) {
358
+ if (strict) throw error;
359
+ return value;
360
+ }
361
+ }
362
+ function parseJSON(value, options = { strict: true }) {
363
+ return betterJSONParse(value, options);
364
+ }
365
+ //#endregion
366
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/session-refresh.mjs
367
+ const now = () => Math.floor(Date.now() / 1e3);
368
+ const FOCUS_REFETCH_RATE_LIMIT_SECONDS = 5;
369
+ function createSessionRefreshManager(opts) {
370
+ const { fetchSession, shouldPollSession = () => true, sessionSignal, options = {} } = opts;
371
+ const refetchInterval = options.sessionOptions?.refetchInterval ?? 0;
372
+ const refetchOnWindowFocus = options.sessionOptions?.refetchOnWindowFocus ?? true;
373
+ const refetchWhenOffline = options.sessionOptions?.refetchWhenOffline ?? false;
374
+ const state = {
375
+ isInitialized: false,
376
+ lastSessionRequest: 0
377
+ };
378
+ const shouldRefetch = () => {
379
+ return refetchWhenOffline || getGlobalOnlineManager().isOnline;
380
+ };
381
+ const triggerRefetch = (event) => {
382
+ if (!shouldRefetch()) return;
383
+ if (event?.event === "storage") {
384
+ fetchSession();
385
+ return;
386
+ }
387
+ if (event?.event === "poll") {
388
+ state.lastSessionRequest = now();
389
+ fetchSession();
390
+ return;
391
+ }
392
+ if (event?.event === "visibilitychange") {
393
+ if (now() - state.lastSessionRequest < FOCUS_REFETCH_RATE_LIMIT_SECONDS) return;
394
+ state.lastSessionRequest = now();
395
+ fetchSession();
396
+ return;
397
+ }
398
+ fetchSession();
399
+ };
400
+ const broadcastSessionUpdate = (trigger) => {
401
+ getGlobalBroadcastChannel().post({
402
+ event: "session",
403
+ data: { trigger },
404
+ clientId: Math.random().toString(36).substring(7)
405
+ });
406
+ };
407
+ const setupPolling = () => {
408
+ if (refetchInterval && refetchInterval > 0) state.pollInterval = setInterval(() => {
409
+ if (shouldPollSession()) triggerRefetch({ event: "poll" });
410
+ }, refetchInterval * 1e3);
411
+ };
412
+ const setupBroadcast = () => {
413
+ state.unsubscribeBroadcast = getGlobalBroadcastChannel().subscribe(() => {
414
+ triggerRefetch({ event: "storage" });
415
+ });
416
+ };
417
+ const setupFocusRefetch = () => {
418
+ if (!refetchOnWindowFocus) return;
419
+ state.unsubscribeFocus = getGlobalFocusManager().subscribe(() => {
420
+ triggerRefetch({ event: "visibilitychange" });
421
+ });
422
+ };
423
+ const setupOnlineRefetch = () => {
424
+ state.unsubscribeOnline = getGlobalOnlineManager().subscribe((online) => {
425
+ if (online) triggerRefetch({ event: "visibilitychange" });
426
+ });
427
+ };
428
+ const setupSignalSubscription = () => {
429
+ state.unsubscribeSignal = sessionSignal.listen(() => {
430
+ fetchSession();
431
+ });
432
+ };
433
+ const init = () => {
434
+ if (state.isInitialized) return;
435
+ state.isInitialized = true;
436
+ setupPolling();
437
+ setupBroadcast();
438
+ setupFocusRefetch();
439
+ setupOnlineRefetch();
440
+ setupSignalSubscription();
441
+ state.cleanupBroadcastSetup = getGlobalBroadcastChannel().setup();
442
+ state.cleanupFocusSetup = getGlobalFocusManager().setup();
443
+ state.cleanupOnlineSetup = getGlobalOnlineManager().setup();
444
+ };
445
+ const cleanup = () => {
446
+ if (!state.isInitialized) return;
447
+ if (state.pollInterval) {
448
+ clearInterval(state.pollInterval);
449
+ state.pollInterval = void 0;
450
+ }
451
+ if (state.unsubscribeBroadcast) {
452
+ state.unsubscribeBroadcast();
453
+ state.unsubscribeBroadcast = void 0;
454
+ }
455
+ if (state.unsubscribeFocus) {
456
+ state.unsubscribeFocus();
457
+ state.unsubscribeFocus = void 0;
458
+ }
459
+ if (state.unsubscribeOnline) {
460
+ state.unsubscribeOnline();
461
+ state.unsubscribeOnline = void 0;
462
+ }
463
+ if (state.unsubscribeSignal) {
464
+ state.unsubscribeSignal();
465
+ state.unsubscribeSignal = void 0;
466
+ }
467
+ if (state.cleanupBroadcastSetup) {
468
+ state.cleanupBroadcastSetup();
469
+ state.cleanupBroadcastSetup = void 0;
470
+ }
471
+ if (state.cleanupFocusSetup) {
472
+ state.cleanupFocusSetup();
473
+ state.cleanupFocusSetup = void 0;
474
+ }
475
+ if (state.cleanupOnlineSetup) {
476
+ state.cleanupOnlineSetup();
477
+ state.cleanupOnlineSetup = void 0;
478
+ }
479
+ state.isInitialized = false;
480
+ state.lastSessionRequest = 0;
481
+ };
482
+ return {
483
+ init,
484
+ cleanup,
485
+ triggerRefetch,
486
+ broadcastSessionUpdate
487
+ };
488
+ }
489
+ //#endregion
490
+ //#region ../../node_modules/.pnpm/@better-auth+core@1.6.22_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_better-call_17975d57218030f5a353914665f207d6/node_modules/@better-auth/core/dist/env/env-impl.mjs
491
+ const _envShim = Object.create(null);
492
+ const _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);
493
+ const env = new Proxy(_envShim, {
494
+ get(_, prop) {
495
+ return _getEnv()[prop] ?? _envShim[prop];
496
+ },
497
+ has(_, prop) {
498
+ return prop in _getEnv() || prop in _envShim;
499
+ },
500
+ set(_, prop, value) {
501
+ const env = _getEnv(true);
502
+ env[prop] = value;
503
+ return true;
504
+ },
505
+ deleteProperty(_, prop) {
506
+ if (!prop) return false;
507
+ const env = _getEnv(true);
508
+ delete env[prop];
509
+ return true;
510
+ },
511
+ ownKeys() {
512
+ const env = _getEnv(true);
513
+ return Object.keys(env);
514
+ }
515
+ });
516
+ env.NODE_ENV;
517
+ function getEnvVar(key, fallback) {
518
+ if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback;
519
+ if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback;
520
+ if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback;
521
+ return fallback;
522
+ }
523
+ Object.freeze({
524
+ get BETTER_AUTH_SECRET() {
525
+ return getEnvVar("BETTER_AUTH_SECRET");
526
+ },
527
+ get AUTH_SECRET() {
528
+ return getEnvVar("AUTH_SECRET");
529
+ },
530
+ get BETTER_AUTH_TELEMETRY() {
531
+ return getEnvVar("BETTER_AUTH_TELEMETRY");
532
+ },
533
+ get BETTER_AUTH_TELEMETRY_ID() {
534
+ return getEnvVar("BETTER_AUTH_TELEMETRY_ID");
535
+ },
536
+ get NODE_ENV() {
537
+ return getEnvVar("NODE_ENV", "development");
538
+ },
539
+ get PACKAGE_VERSION() {
540
+ return getEnvVar("PACKAGE_VERSION", "0.0.0");
541
+ },
542
+ get BETTER_AUTH_TELEMETRY_ENDPOINT() {
543
+ return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", "");
544
+ }
545
+ });
546
+ //#endregion
547
+ //#region ../../node_modules/.pnpm/better-call@1.3.7_zod@4.4.3/node_modules/better-call/dist/error.mjs
548
+ function isErrorStackTraceLimitWritable() {
549
+ const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
550
+ if (desc === void 0) return Object.isExtensible(Error);
551
+ return Object.prototype.hasOwnProperty.call(desc, "writable") ? desc.writable : desc.set !== void 0;
552
+ }
553
+ function hideInternalStackFrames(stack) {
554
+ const lines = stack.split("\n at ");
555
+ if (lines.length <= 1) return stack;
556
+ lines.splice(1, 1);
557
+ return lines.join("\n at ");
558
+ }
559
+ function makeErrorForHideStackFrame(Base, clazz) {
560
+ class HideStackFramesError extends Base {
561
+ #hiddenStack;
562
+ constructor(...args) {
563
+ if (isErrorStackTraceLimitWritable()) {
564
+ const limit = Error.stackTraceLimit;
565
+ Error.stackTraceLimit = 0;
566
+ super(...args);
567
+ Error.stackTraceLimit = limit;
568
+ } else super(...args);
569
+ const stack = new Error().stack;
570
+ if (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name));
571
+ }
572
+ get errorStack() {
573
+ return this.#hiddenStack;
574
+ }
575
+ }
576
+ Object.defineProperty(HideStackFramesError.prototype, "constructor", {
577
+ get() {
578
+ return clazz;
579
+ },
580
+ enumerable: false,
581
+ configurable: true
582
+ });
583
+ return HideStackFramesError;
584
+ }
585
+ const statusCodes = {
586
+ OK: 200,
587
+ CREATED: 201,
588
+ ACCEPTED: 202,
589
+ NO_CONTENT: 204,
590
+ MULTIPLE_CHOICES: 300,
591
+ MOVED_PERMANENTLY: 301,
592
+ FOUND: 302,
593
+ SEE_OTHER: 303,
594
+ NOT_MODIFIED: 304,
595
+ TEMPORARY_REDIRECT: 307,
596
+ BAD_REQUEST: 400,
597
+ UNAUTHORIZED: 401,
598
+ PAYMENT_REQUIRED: 402,
599
+ FORBIDDEN: 403,
600
+ NOT_FOUND: 404,
601
+ METHOD_NOT_ALLOWED: 405,
602
+ NOT_ACCEPTABLE: 406,
603
+ PROXY_AUTHENTICATION_REQUIRED: 407,
604
+ REQUEST_TIMEOUT: 408,
605
+ CONFLICT: 409,
606
+ GONE: 410,
607
+ LENGTH_REQUIRED: 411,
608
+ PRECONDITION_FAILED: 412,
609
+ PAYLOAD_TOO_LARGE: 413,
610
+ URI_TOO_LONG: 414,
611
+ UNSUPPORTED_MEDIA_TYPE: 415,
612
+ RANGE_NOT_SATISFIABLE: 416,
613
+ EXPECTATION_FAILED: 417,
614
+ "I'M_A_TEAPOT": 418,
615
+ MISDIRECTED_REQUEST: 421,
616
+ UNPROCESSABLE_ENTITY: 422,
617
+ LOCKED: 423,
618
+ FAILED_DEPENDENCY: 424,
619
+ TOO_EARLY: 425,
620
+ UPGRADE_REQUIRED: 426,
621
+ PRECONDITION_REQUIRED: 428,
622
+ TOO_MANY_REQUESTS: 429,
623
+ REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
624
+ UNAVAILABLE_FOR_LEGAL_REASONS: 451,
625
+ INTERNAL_SERVER_ERROR: 500,
626
+ NOT_IMPLEMENTED: 501,
627
+ BAD_GATEWAY: 502,
628
+ SERVICE_UNAVAILABLE: 503,
629
+ GATEWAY_TIMEOUT: 504,
630
+ HTTP_VERSION_NOT_SUPPORTED: 505,
631
+ VARIANT_ALSO_NEGOTIATES: 506,
632
+ INSUFFICIENT_STORAGE: 507,
633
+ LOOP_DETECTED: 508,
634
+ NOT_EXTENDED: 510,
635
+ NETWORK_AUTHENTICATION_REQUIRED: 511
636
+ };
637
+ var InternalAPIError = class extends Error {
638
+ constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) {
639
+ super(body?.message, body?.cause ? { cause: body.cause } : void 0);
640
+ this.status = status;
641
+ this.body = body;
642
+ this.headers = headers;
643
+ this.statusCode = statusCode;
644
+ this.name = "APIError";
645
+ this.status = status;
646
+ this.headers = headers;
647
+ this.statusCode = statusCode;
648
+ this.body = body;
649
+ }
650
+ };
651
+ makeErrorForHideStackFrame(InternalAPIError, Error);
652
+ //#endregion
653
+ //#region ../../node_modules/.pnpm/@better-auth+core@1.6.22_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_better-call_17975d57218030f5a353914665f207d6/node_modules/@better-auth/core/dist/error/index.mjs
654
+ var BetterAuthError = class extends Error {
655
+ constructor(message, options) {
656
+ super(message, options);
657
+ this.name = "BetterAuthError";
658
+ this.message = message;
659
+ this.stack = "";
660
+ }
661
+ };
662
+ //#endregion
663
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/utils/url.mjs
664
+ const SLASH_CHAR_CODE = "/".charCodeAt(0);
665
+ function trimTrailingSlashes(value) {
666
+ let end = value.length;
667
+ while (end > 0 && value.charCodeAt(end - 1) === SLASH_CHAR_CODE) end--;
668
+ return end === value.length ? value : value.slice(0, end);
669
+ }
670
+ function checkHasPath(url) {
671
+ try {
672
+ return (trimTrailingSlashes(new URL(url).pathname) || "/") !== "/";
673
+ } catch {
674
+ throw new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`);
675
+ }
676
+ }
677
+ function assertHasProtocol(url) {
678
+ try {
679
+ const parsedUrl = new URL(url);
680
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new BetterAuthError(`Invalid base URL: ${url}. URL must include 'http://' or 'https://'`);
681
+ } catch (error) {
682
+ if (error instanceof BetterAuthError) throw error;
683
+ throw new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`, { cause: error });
684
+ }
685
+ }
686
+ function withPath(url, path = "/api/auth") {
687
+ assertHasProtocol(url);
688
+ if (checkHasPath(url)) return url;
689
+ const trimmedUrl = trimTrailingSlashes(url);
690
+ if (!path || path === "/") return trimmedUrl;
691
+ path = path.startsWith("/") ? path : `/${path}`;
692
+ return `${trimmedUrl}${path}`;
693
+ }
694
+ function validateProxyHeader(header, type) {
695
+ if (!header || header.trim() === "") return false;
696
+ if (type === "proto") return header === "http" || header === "https";
697
+ if (type === "host") {
698
+ if ([
699
+ /\.\./,
700
+ /\0/,
701
+ /[\s]/,
702
+ /^[.]/,
703
+ /[<>'"]/,
704
+ /javascript:/i,
705
+ /file:/i,
706
+ /data:/i
707
+ ].some((pattern) => pattern.test(header))) return false;
708
+ return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(header) || /^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header);
709
+ }
710
+ return false;
711
+ }
712
+ function getBaseURL(url, path, request, loadEnv, trustedProxyHeaders) {
713
+ if (url) return withPath(url, path);
714
+ if (loadEnv !== false) {
715
+ 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);
716
+ if (fromEnv) return withPath(fromEnv, path);
717
+ }
718
+ const fromRequest = request?.headers.get("x-forwarded-host");
719
+ const fromRequestProto = request?.headers.get("x-forwarded-proto");
720
+ if (fromRequest && fromRequestProto && trustedProxyHeaders) {
721
+ if (validateProxyHeader(fromRequestProto, "proto") && validateProxyHeader(fromRequest, "host")) try {
722
+ return withPath(`${fromRequestProto}://${fromRequest}`, path);
723
+ } catch (_error) {}
724
+ }
725
+ if (request) {
726
+ const url = getOrigin(request.url);
727
+ if (!url) throw new BetterAuthError("Could not get origin from request. Please provide a valid base URL.");
728
+ return withPath(url, path);
729
+ }
730
+ if (typeof window !== "undefined" && window.location) return withPath(window.location.origin, path);
731
+ }
732
+ function getOrigin(url) {
733
+ try {
734
+ const parsedUrl = new URL(url);
735
+ return parsedUrl.origin === "null" ? null : parsedUrl.origin;
736
+ } catch {
737
+ return null;
738
+ }
739
+ }
740
+ //#endregion
741
+ //#region ../../node_modules/.pnpm/@better-auth+core@1.6.22_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_better-call_17975d57218030f5a353914665f207d6/node_modules/@better-auth/core/dist/utils/url.mjs
742
+ const DANGEROUS_URL_SCHEMES = [
743
+ "javascript:",
744
+ "data:",
745
+ "vbscript:"
746
+ ];
747
+ function isSafeUrlScheme(value) {
748
+ let parsed;
749
+ try {
750
+ parsed = new URL(value);
751
+ } catch {
752
+ return true;
753
+ }
754
+ return !DANGEROUS_URL_SCHEMES.includes(parsed.protocol);
755
+ }
756
+ //#endregion
757
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/fetch-plugins.mjs
758
+ const redirectPlugin = {
759
+ id: "redirect",
760
+ name: "Redirect",
761
+ hooks: { onSuccess(context) {
762
+ if (context.data?.url && context.data?.redirect && isSafeUrlScheme(context.data.url)) {
763
+ if (typeof window !== "undefined" && window.location) {
764
+ if (window.location) try {
765
+ window.location.href = context.data.url;
766
+ } catch {}
767
+ }
768
+ }
769
+ } }
770
+ };
771
+ //#endregion
772
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/session-atom.mjs
773
+ const isServer = () => typeof window === "undefined";
774
+ function normalizeSessionResponse(res) {
775
+ if (typeof res === "object" && res !== null && "data" in res && "error" in res) return res;
776
+ return {
777
+ data: res,
778
+ error: null
779
+ };
780
+ }
781
+ function normalizeSessionData(data) {
782
+ if (!data) return null;
783
+ if (data.session === null && data.user === null) return null;
784
+ return data;
785
+ }
786
+ function isSessionAtomEqual(a, b) {
787
+ return isJsonEqual(a.data, b.data) && a.error === b.error && a.isPending === b.isPending && a.isRefetching === b.isRefetching && a.refetch === b.refetch;
788
+ }
789
+ function getSessionAtom($fetch, options) {
790
+ const $signal = atom(false);
791
+ let abortController;
792
+ const refetch = (queryParams) => fetchSession(queryParams);
793
+ const session = atom({
794
+ data: null,
795
+ error: null,
796
+ isPending: true,
797
+ isRefetching: false,
798
+ refetch
799
+ });
800
+ withEquality(session, isSessionAtomEqual);
801
+ const settleAbortedFetch = (controller) => {
802
+ if (abortController !== controller) return;
803
+ const current = session.get();
804
+ abortController = void 0;
805
+ if (!current.isPending && !current.isRefetching) return;
806
+ session.set({
807
+ ...current,
808
+ isPending: false,
809
+ isRefetching: false,
810
+ refetch
811
+ });
812
+ };
813
+ const fetchSession = async (queryParams) => {
814
+ abortController?.abort();
815
+ const controller = new AbortController();
816
+ abortController = controller;
817
+ const current = session.get();
818
+ session.set({
819
+ ...current,
820
+ isPending: current.data === null,
821
+ isRefetching: true,
822
+ error: null,
823
+ refetch
824
+ });
825
+ try {
826
+ const res = await $fetch("/get-session", {
827
+ method: "GET",
828
+ query: queryParams?.query,
829
+ signal: controller.signal
830
+ });
831
+ if (controller.signal.aborted) {
832
+ settleAbortedFetch(controller);
833
+ return;
834
+ }
835
+ let { data, error } = normalizeSessionResponse(res);
836
+ if (data?.needsRefresh) try {
837
+ const refreshRes = await $fetch("/get-session", {
838
+ method: "POST",
839
+ signal: controller.signal
840
+ });
841
+ if (controller.signal.aborted) {
842
+ settleAbortedFetch(controller);
843
+ return;
844
+ }
845
+ ({data, error} = normalizeSessionResponse(refreshRes));
846
+ } catch {
847
+ if (controller.signal.aborted) {
848
+ settleAbortedFetch(controller);
849
+ return;
850
+ }
851
+ }
852
+ if (error) {
853
+ const latest = session.get();
854
+ const isUnauthorized = error?.status === 401;
855
+ session.set({
856
+ data: isUnauthorized ? null : latest.data,
857
+ error,
858
+ isPending: false,
859
+ isRefetching: false,
860
+ refetch
861
+ });
862
+ return;
863
+ }
864
+ const sessionData = normalizeSessionData(data);
865
+ const current = session.get();
866
+ const stableData = current.data != null && sessionData != null && isJsonEqual(current.data, sessionData) ? current.data : sessionData;
867
+ session.set({
868
+ data: stableData,
869
+ error: null,
870
+ isPending: false,
871
+ isRefetching: false,
872
+ refetch
873
+ });
874
+ } catch (fetchError) {
875
+ if (controller.signal.aborted) {
876
+ settleAbortedFetch(controller);
877
+ return;
878
+ }
879
+ const latest = session.get();
880
+ session.set({
881
+ data: latest.data,
882
+ error: fetchError,
883
+ isPending: false,
884
+ isRefetching: false,
885
+ refetch
886
+ });
887
+ }
888
+ };
889
+ let broadcastSessionUpdate = () => {};
890
+ onMount(session, () => {
891
+ let timeoutId;
892
+ if (!isServer()) timeoutId = setTimeout(() => {
893
+ fetchSession();
894
+ }, 0);
895
+ const refreshManager = createSessionRefreshManager({
896
+ fetchSession,
897
+ shouldPollSession: () => session.get().data != null,
898
+ sessionSignal: $signal,
899
+ options
900
+ });
901
+ refreshManager.init();
902
+ broadcastSessionUpdate = refreshManager.broadcastSessionUpdate;
903
+ return () => {
904
+ if (timeoutId) clearTimeout(timeoutId);
905
+ const controller = abortController;
906
+ controller?.abort();
907
+ if (controller) settleAbortedFetch(controller);
908
+ refreshManager.cleanup();
909
+ };
910
+ });
911
+ return {
912
+ session,
913
+ $sessionSignal: $signal,
914
+ broadcastSessionUpdate: (trigger) => broadcastSessionUpdate(trigger)
915
+ };
916
+ }
917
+ //#endregion
918
+ //#region ../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs
919
+ function isPlainObject(value) {
920
+ if (value === null || typeof value !== "object") return false;
921
+ const prototype = Object.getPrototypeOf(value);
922
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
923
+ if (Symbol.iterator in value) return false;
924
+ if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
925
+ return true;
926
+ }
927
+ function _defu(baseObject, defaults, namespace = ".", merger) {
928
+ if (!isPlainObject(defaults)) return _defu(baseObject, {}, namespace, merger);
929
+ const object = { ...defaults };
930
+ for (const key of Object.keys(baseObject)) {
931
+ if (key === "__proto__" || key === "constructor") continue;
932
+ const value = baseObject[key];
933
+ if (value === null || value === void 0) continue;
934
+ if (merger && merger(object, key, value, namespace)) continue;
935
+ if (Array.isArray(value) && Array.isArray(object[key])) object[key] = [...value, ...object[key]];
936
+ else if (isPlainObject(value) && isPlainObject(object[key])) object[key] = _defu(value, object[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
937
+ else object[key] = value;
938
+ }
939
+ return object;
940
+ }
941
+ function createDefu(merger) {
942
+ return (...arguments_) => arguments_.reduce((p, c) => _defu(p, c, "", merger), {});
943
+ }
944
+ const defu = createDefu();
945
+ //#endregion
946
+ //#region ../../node_modules/.pnpm/@better-fetch+fetch@1.3.1/node_modules/@better-fetch/fetch/dist/index.js
947
+ var __defProp = Object.defineProperty;
948
+ var __defProps = Object.defineProperties;
949
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
950
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
951
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
952
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
953
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
954
+ enumerable: true,
955
+ configurable: true,
956
+ writable: true,
957
+ value
958
+ }) : obj[key] = value;
959
+ var __spreadValues = (a, b) => {
960
+ for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]);
961
+ if (__getOwnPropSymbols) {
962
+ for (var prop of __getOwnPropSymbols(b)) if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]);
963
+ }
964
+ return a;
965
+ };
966
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
967
+ var BetterFetchError = class extends Error {
968
+ constructor(status, statusText, error) {
969
+ super(statusText || status.toString(), { cause: error });
970
+ this.status = status;
971
+ this.statusText = statusText;
972
+ this.error = error;
973
+ Error.captureStackTrace(this, this.constructor);
974
+ }
975
+ };
976
+ var initializePlugins = async (url, options) => {
977
+ var _a, _b, _c, _d, _e, _f;
978
+ let opts = options || {};
979
+ const hooks = {
980
+ onRequest: [options == null ? void 0 : options.onRequest],
981
+ onResponse: [options == null ? void 0 : options.onResponse],
982
+ onSuccess: [options == null ? void 0 : options.onSuccess],
983
+ onError: [options == null ? void 0 : options.onError],
984
+ onRetry: [options == null ? void 0 : options.onRetry]
985
+ };
986
+ if (!options || !(options == null ? void 0 : options.plugins)) return {
987
+ url,
988
+ options: opts,
989
+ hooks
990
+ };
991
+ for (const plugin of (options == null ? void 0 : options.plugins) || []) {
992
+ if (plugin.init) {
993
+ const pluginRes = await ((_a = plugin.init) == null ? void 0 : _a.call(plugin, url.toString(), options));
994
+ opts = pluginRes.options || opts;
995
+ url = pluginRes.url;
996
+ }
997
+ hooks.onRequest.push((_b = plugin.hooks) == null ? void 0 : _b.onRequest);
998
+ hooks.onResponse.push((_c = plugin.hooks) == null ? void 0 : _c.onResponse);
999
+ hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess);
1000
+ hooks.onError.push((_e = plugin.hooks) == null ? void 0 : _e.onError);
1001
+ hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry);
1002
+ }
1003
+ return {
1004
+ url,
1005
+ options: opts,
1006
+ hooks
1007
+ };
1008
+ };
1009
+ var LinearRetryStrategy = class {
1010
+ constructor(options) {
1011
+ this.options = options;
1012
+ }
1013
+ shouldAttemptRetry(attempt, response) {
1014
+ if (this.options.shouldRetry) return Promise.resolve(attempt < this.options.attempts && this.options.shouldRetry(response));
1015
+ return Promise.resolve(attempt < this.options.attempts);
1016
+ }
1017
+ getDelay() {
1018
+ return this.options.delay;
1019
+ }
1020
+ };
1021
+ var ExponentialRetryStrategy = class {
1022
+ constructor(options) {
1023
+ this.options = options;
1024
+ }
1025
+ shouldAttemptRetry(attempt, response) {
1026
+ if (this.options.shouldRetry) return Promise.resolve(attempt < this.options.attempts && this.options.shouldRetry(response));
1027
+ return Promise.resolve(attempt < this.options.attempts);
1028
+ }
1029
+ getDelay(attempt) {
1030
+ return Math.min(this.options.maxDelay, this.options.baseDelay * 2 ** attempt);
1031
+ }
1032
+ };
1033
+ function createRetryStrategy(options) {
1034
+ if (typeof options === "number") return new LinearRetryStrategy({
1035
+ type: "linear",
1036
+ attempts: options,
1037
+ delay: 1e3
1038
+ });
1039
+ switch (options.type) {
1040
+ case "linear": return new LinearRetryStrategy(options);
1041
+ case "exponential": return new ExponentialRetryStrategy(options);
1042
+ default: throw new Error("Invalid retry strategy");
1043
+ }
1044
+ }
1045
+ var getAuthHeader = async (options) => {
1046
+ const headers = {};
1047
+ const getValue = async (value) => typeof value === "function" ? await value() : value;
1048
+ if (options == null ? void 0 : options.auth) {
1049
+ if (options.auth.type === "Bearer") {
1050
+ const token = await getValue(options.auth.token);
1051
+ if (!token) return headers;
1052
+ headers["authorization"] = `Bearer ${token}`;
1053
+ } else if (options.auth.type === "Basic") {
1054
+ const [username, password] = await Promise.all([getValue(options.auth.username), getValue(options.auth.password)]);
1055
+ if (!username || !password) return headers;
1056
+ headers["authorization"] = `Basic ${btoa(`${username}:${password}`)}`;
1057
+ } else if (options.auth.type === "Custom") {
1058
+ const [prefix, value] = await Promise.all([getValue(options.auth.prefix), getValue(options.auth.value)]);
1059
+ if (!value) return headers;
1060
+ headers["authorization"] = `${prefix != null ? prefix : ""} ${value}`;
1061
+ }
1062
+ }
1063
+ return headers;
1064
+ };
1065
+ var JSON_RE$1 = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
1066
+ function detectResponseType$1(request) {
1067
+ const _contentType = request.headers.get("content-type");
1068
+ const textTypes = new Set([
1069
+ "image/svg",
1070
+ "application/xml",
1071
+ "application/xhtml",
1072
+ "application/html"
1073
+ ]);
1074
+ if (!_contentType) return "json";
1075
+ const contentType = _contentType.split(";").shift() || "";
1076
+ if (JSON_RE$1.test(contentType)) return "json";
1077
+ if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
1078
+ return "blob";
1079
+ }
1080
+ function isJSONParsable(value) {
1081
+ try {
1082
+ JSON.parse(value);
1083
+ return true;
1084
+ } catch (error) {
1085
+ return false;
1086
+ }
1087
+ }
1088
+ function isJSONSerializable$1(value) {
1089
+ if (value === void 0) return false;
1090
+ const t = typeof value;
1091
+ if (t === "string" || t === "number" || t === "boolean" || t === null) return true;
1092
+ if (t !== "object") return false;
1093
+ if (Array.isArray(value)) return true;
1094
+ if (value.buffer) return false;
1095
+ return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
1096
+ }
1097
+ function jsonParse(text) {
1098
+ try {
1099
+ return JSON.parse(text);
1100
+ } catch (error) {
1101
+ return text;
1102
+ }
1103
+ }
1104
+ function isFunction(value) {
1105
+ return typeof value === "function";
1106
+ }
1107
+ function getFetch(options) {
1108
+ if (options == null ? void 0 : options.customFetchImpl) return options.customFetchImpl;
1109
+ if (typeof globalThis !== "undefined" && isFunction(globalThis.fetch)) return globalThis.fetch;
1110
+ if (typeof window !== "undefined" && isFunction(window.fetch)) return window.fetch;
1111
+ throw new Error("No fetch implementation found");
1112
+ }
1113
+ function mergeHeaders$1(...sources) {
1114
+ const merged = {};
1115
+ for (const source of sources) {
1116
+ if (!source) continue;
1117
+ if (source instanceof Headers) source.forEach((value, key) => {
1118
+ merged[key] = value;
1119
+ });
1120
+ else {
1121
+ const entries = Array.isArray(source) ? source : Object.entries(source);
1122
+ for (const [key, value] of entries) if (value !== null && value !== void 0) merged[key] = value;
1123
+ }
1124
+ }
1125
+ return merged;
1126
+ }
1127
+ async function getHeaders(opts) {
1128
+ const headers = new Headers(mergeHeaders$1(opts == null ? void 0 : opts.headers, await getAuthHeader(opts)));
1129
+ if (!headers.has("content-type")) {
1130
+ const contentType = detectContentType(opts == null ? void 0 : opts.body);
1131
+ if (contentType) headers.set("content-type", contentType);
1132
+ }
1133
+ return headers;
1134
+ }
1135
+ function detectContentType(body) {
1136
+ if (isJSONSerializable$1(body)) return "application/json";
1137
+ return null;
1138
+ }
1139
+ function getMediaType(headers) {
1140
+ const contentType = headers.get("content-type");
1141
+ return contentType ? contentType.split(";")[0].trim().toLowerCase() : null;
1142
+ }
1143
+ function getBody(options, headers) {
1144
+ const { body } = options;
1145
+ if (!body) return null;
1146
+ if (!isJSONSerializable$1(body)) return body;
1147
+ if (typeof body === "string") return body;
1148
+ if (getMediaType(headers) === "application/x-www-form-urlencoded") return new URLSearchParams(body).toString();
1149
+ return JSON.stringify(body);
1150
+ }
1151
+ function getMethod$1(url, options) {
1152
+ var _a;
1153
+ if (options == null ? void 0 : options.method) return options.method.toUpperCase();
1154
+ if (url.startsWith("@")) {
1155
+ const pMethod = (_a = url.split("@")[1]) == null ? void 0 : _a.split("/")[0];
1156
+ if (!methods.includes(pMethod)) return (options == null ? void 0 : options.body) ? "POST" : "GET";
1157
+ return pMethod.toUpperCase();
1158
+ }
1159
+ return (options == null ? void 0 : options.body) ? "POST" : "GET";
1160
+ }
1161
+ function getTimeout(options, controller) {
1162
+ let abortTimeout;
1163
+ if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout);
1164
+ return {
1165
+ abortTimeout,
1166
+ clearTimeout: () => {
1167
+ if (abortTimeout) clearTimeout(abortTimeout);
1168
+ }
1169
+ };
1170
+ }
1171
+ var ValidationError = class _ValidationError extends Error {
1172
+ constructor(issues, message) {
1173
+ super(message || JSON.stringify(issues, null, 2));
1174
+ this.issues = issues;
1175
+ Object.setPrototypeOf(this, _ValidationError.prototype);
1176
+ }
1177
+ };
1178
+ async function parseStandardSchema(schema, input) {
1179
+ const result = await schema["~standard"].validate(input);
1180
+ if (result.issues) throw new ValidationError(result.issues);
1181
+ return result.value;
1182
+ }
1183
+ var methods = [
1184
+ "get",
1185
+ "post",
1186
+ "put",
1187
+ "patch",
1188
+ "delete"
1189
+ ];
1190
+ var applySchemaPlugin = (config) => ({
1191
+ id: "apply-schema",
1192
+ name: "Apply Schema",
1193
+ version: "1.0.0",
1194
+ async init(url, options) {
1195
+ var _a, _b, _c, _d;
1196
+ const schema = ((_b = (_a = config.plugins) == null ? void 0 : _a.find((plugin) => {
1197
+ var _a2;
1198
+ return ((_a2 = plugin.schema) == null ? void 0 : _a2.config) ? url.startsWith(plugin.schema.config.baseURL || "") || url.startsWith(plugin.schema.config.prefix || "") : false;
1199
+ })) == null ? void 0 : _b.schema) || config.schema;
1200
+ if (schema) {
1201
+ let urlKey = url;
1202
+ if ((_c = schema.config) == null ? void 0 : _c.prefix) {
1203
+ if (urlKey.startsWith(schema.config.prefix)) {
1204
+ urlKey = urlKey.replace(schema.config.prefix, "");
1205
+ if (schema.config.baseURL) url = url.replace(schema.config.prefix, schema.config.baseURL);
1206
+ }
1207
+ }
1208
+ if ((_d = schema.config) == null ? void 0 : _d.baseURL) {
1209
+ if (urlKey.startsWith(schema.config.baseURL)) urlKey = urlKey.replace(schema.config.baseURL, "");
1210
+ }
1211
+ if (urlKey.startsWith("/") && urlKey.charAt(1) === "@") urlKey = urlKey.substring(1);
1212
+ const keySchema = schema.schema[urlKey];
1213
+ if (keySchema) {
1214
+ let validatedHeaders = options == null ? void 0 : options.headers;
1215
+ if (keySchema.headers && !(options == null ? void 0 : options.disableValidation)) {
1216
+ const normalizedHeaders = {};
1217
+ if (options == null ? void 0 : options.headers) {
1218
+ if (options.headers instanceof Headers) options.headers.forEach((value, key) => {
1219
+ normalizedHeaders[key.toLowerCase()] = value;
1220
+ });
1221
+ else if (typeof options.headers === "object") {
1222
+ for (const [key, value] of Object.entries(options.headers)) if (value !== null && value !== void 0) normalizedHeaders[key.toLowerCase()] = value;
1223
+ }
1224
+ }
1225
+ const validated = await parseStandardSchema(keySchema.headers, normalizedHeaders);
1226
+ const finalHeaders = {};
1227
+ for (const [key, value] of Object.entries(validated)) finalHeaders[key.toLowerCase()] = value;
1228
+ validatedHeaders = finalHeaders;
1229
+ }
1230
+ let opts = __spreadProps(__spreadValues({}, options), {
1231
+ method: keySchema.method,
1232
+ output: keySchema.output,
1233
+ headers: validatedHeaders
1234
+ });
1235
+ if (!(options == null ? void 0 : options.disableValidation)) opts = __spreadProps(__spreadValues({}, opts), {
1236
+ body: keySchema.input ? await parseStandardSchema(keySchema.input, options == null ? void 0 : options.body) : options == null ? void 0 : options.body,
1237
+ params: keySchema.params ? await parseStandardSchema(keySchema.params, options == null ? void 0 : options.params) : options == null ? void 0 : options.params,
1238
+ query: keySchema.query ? await parseStandardSchema(keySchema.query, options == null ? void 0 : options.query) : options == null ? void 0 : options.query
1239
+ });
1240
+ return {
1241
+ url,
1242
+ options: opts
1243
+ };
1244
+ }
1245
+ }
1246
+ return {
1247
+ url,
1248
+ options
1249
+ };
1250
+ }
1251
+ });
1252
+ var createFetch$1 = (config) => {
1253
+ async function $fetch(url, options) {
1254
+ const opts = __spreadProps(__spreadValues(__spreadValues({}, config), options), {
1255
+ headers: mergeHeaders$1(config == null ? void 0 : config.headers, options == null ? void 0 : options.headers),
1256
+ plugins: [
1257
+ ...(config == null ? void 0 : config.plugins) || [],
1258
+ applySchemaPlugin(config || {}),
1259
+ ...(options == null ? void 0 : options.plugins) || []
1260
+ ]
1261
+ });
1262
+ if (config == null ? void 0 : config.catchAllError) try {
1263
+ return await betterFetch(url, opts);
1264
+ } catch (error) {
1265
+ return {
1266
+ data: null,
1267
+ error: {
1268
+ status: 500,
1269
+ statusText: "Fetch Error",
1270
+ message: "Fetch related error. Captured by catchAllError option. See error property for more details.",
1271
+ error
1272
+ }
1273
+ };
1274
+ }
1275
+ return await betterFetch(url, opts);
1276
+ }
1277
+ return $fetch;
1278
+ };
1279
+ var isReservedPathSegment = (value) => value === "." || value === "..";
1280
+ function encodePathSegment(segment, pathParams) {
1281
+ let pathSegment = segment;
1282
+ for (const [key, value] of pathParams) pathSegment = pathSegment.replace(key, value);
1283
+ if (isReservedPathSegment(pathSegment)) throw new TypeError("Path parameters cannot be reserved path segments");
1284
+ return encodeURIComponent(pathSegment);
1285
+ }
1286
+ function getURL2(url, option) {
1287
+ const { baseURL, params, query } = option || {
1288
+ query: {},
1289
+ params: {},
1290
+ baseURL: ""
1291
+ };
1292
+ let basePath = url.startsWith("http") ? url.split("/").slice(0, 3).join("/") : baseURL || "";
1293
+ if (url.startsWith("@")) {
1294
+ const m = url.toString().split("@")[1].split("/")[0];
1295
+ if (methods.includes(m)) url = url.replace(`@${m}/`, "/");
1296
+ }
1297
+ if (!basePath.endsWith("/")) basePath += "/";
1298
+ let [path, urlQuery] = url.replace(basePath, "").split("?");
1299
+ const queryParams = new URLSearchParams(urlQuery);
1300
+ for (const [key, value] of Object.entries(query || {})) {
1301
+ if (value == null) continue;
1302
+ let serializedValue;
1303
+ if (typeof value === "string") serializedValue = value;
1304
+ else if (Array.isArray(value)) {
1305
+ for (const val of value) queryParams.append(key, val);
1306
+ continue;
1307
+ } else serializedValue = JSON.stringify(value);
1308
+ queryParams.set(key, serializedValue);
1309
+ }
1310
+ const pathParams = new Map();
1311
+ if (params) if (Array.isArray(params)) {
1312
+ const paramPaths = path.split("/").filter((p) => p.startsWith(":"));
1313
+ for (const [index, key] of paramPaths.entries()) {
1314
+ const value = params[index];
1315
+ pathParams.set(key, String(value));
1316
+ }
1317
+ } else for (const [key, value] of Object.entries(params)) pathParams.set(`:${key}`, String(value));
1318
+ path = path.split("/").map((segment) => encodePathSegment(segment, pathParams)).join("/");
1319
+ path = path.replace(/^\/+/, "");
1320
+ let queryParamString = queryParams.toString();
1321
+ queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\+/g, "%20") : "";
1322
+ if (!basePath.startsWith("http")) return `${basePath}${path}${queryParamString}`;
1323
+ return new URL(`${path}${queryParamString}`, basePath);
1324
+ }
1325
+ var betterFetch = async (url, options) => {
1326
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1327
+ const { hooks, url: __url, options: opts } = await initializePlugins(url, options);
1328
+ const fetch = getFetch(opts);
1329
+ const controller = new AbortController();
1330
+ const signal = (_a = opts.signal) != null ? _a : controller.signal;
1331
+ const _url = getURL2(__url, opts);
1332
+ const headers = await getHeaders(opts);
1333
+ const body = getBody(opts, headers);
1334
+ const method = getMethod$1(__url, opts);
1335
+ const context = __spreadProps(__spreadValues({}, opts), {
1336
+ url: _url,
1337
+ headers,
1338
+ body,
1339
+ method,
1340
+ signal
1341
+ });
1342
+ for (const onRequest of hooks.onRequest) if (onRequest) {
1343
+ const res = await onRequest(context);
1344
+ if (typeof res === "object" && res !== null) Object.assign(context, res);
1345
+ }
1346
+ if ("pipeTo" in context && typeof context.pipeTo === "function" || typeof ((_b = options == null ? void 0 : options.body) == null ? void 0 : _b.pipe) === "function") {
1347
+ if (!("duplex" in context)) context.duplex = "half";
1348
+ }
1349
+ const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller);
1350
+ let response = await fetch(context.url, context);
1351
+ clearTimeout2();
1352
+ const responseContext = {
1353
+ response,
1354
+ request: context
1355
+ };
1356
+ for (const onResponse of hooks.onResponse) if (onResponse) {
1357
+ const r = await onResponse(__spreadProps(__spreadValues({}, responseContext), { response: ((_c = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c.cloneResponse) ? response.clone() : response }));
1358
+ if (r instanceof Response) response = r;
1359
+ else if (typeof r === "object" && r !== null) response = r.response;
1360
+ }
1361
+ if (response.ok) {
1362
+ if (!(context.method !== "HEAD")) return {
1363
+ data: "",
1364
+ error: null
1365
+ };
1366
+ const responseType = detectResponseType$1(response);
1367
+ const successContext = {
1368
+ data: null,
1369
+ response,
1370
+ request: context
1371
+ };
1372
+ if (responseType === "json" || responseType === "text") {
1373
+ const text = await response.text();
1374
+ successContext.data = await ((_d = context.jsonParser) != null ? _d : jsonParse)(text);
1375
+ } else successContext.data = await response[responseType]();
1376
+ if (context == null ? void 0 : context.output) {
1377
+ if (context.output && !context.disableValidation) successContext.data = await parseStandardSchema(context.output, successContext.data);
1378
+ }
1379
+ for (const onSuccess of hooks.onSuccess) if (onSuccess) await onSuccess(__spreadProps(__spreadValues({}, successContext), { response: ((_e = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e.cloneResponse) ? response.clone() : response }));
1380
+ if (options == null ? void 0 : options.throw) return successContext.data;
1381
+ return {
1382
+ data: successContext.data,
1383
+ error: null
1384
+ };
1385
+ }
1386
+ const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse;
1387
+ const responseText = await response.text();
1388
+ const isJSONResponse = isJSONParsable(responseText);
1389
+ const errorObject = isJSONResponse ? await parser(responseText) : null;
1390
+ const errorContext = {
1391
+ response,
1392
+ responseText,
1393
+ request: context,
1394
+ error: __spreadProps(__spreadValues({}, errorObject), {
1395
+ status: response.status,
1396
+ statusText: response.statusText
1397
+ })
1398
+ };
1399
+ for (const onError of hooks.onError) if (onError) await onError(__spreadProps(__spreadValues({}, errorContext), { response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response }));
1400
+ if (options == null ? void 0 : options.retry) {
1401
+ const retryStrategy = createRetryStrategy(options.retry);
1402
+ const _retryAttempt = (_h = options.retryAttempt) != null ? _h : 0;
1403
+ if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) {
1404
+ for (const onRetry of hooks.onRetry) if (onRetry) await onRetry(responseContext);
1405
+ const delay = retryStrategy.getDelay(_retryAttempt);
1406
+ await new Promise((resolve) => setTimeout(resolve, delay));
1407
+ return await betterFetch(url, __spreadProps(__spreadValues({}, options), { retryAttempt: _retryAttempt + 1 }));
1408
+ }
1409
+ }
1410
+ if (options == null ? void 0 : options.throw) throw new BetterFetchError(response.status, response.statusText, isJSONResponse ? errorObject : responseText);
1411
+ return {
1412
+ data: null,
1413
+ error: __spreadProps(__spreadValues({}, errorObject), {
1414
+ status: response.status,
1415
+ statusText: response.statusText
1416
+ })
1417
+ };
1418
+ };
1419
+ //#endregion
1420
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/config.mjs
1421
+ const resolvePublicAuthUrl = (basePath) => {
1422
+ if (typeof process === "undefined") return void 0;
1423
+ const path = basePath ?? "/api/auth";
1424
+ if (process.env.NEXT_PUBLIC_AUTH_URL) return process.env.NEXT_PUBLIC_AUTH_URL;
1425
+ if (typeof window === "undefined") {
1426
+ if (process.env.NEXTAUTH_URL) try {
1427
+ return process.env.NEXTAUTH_URL;
1428
+ } catch {}
1429
+ if (process.env.VERCEL_URL) try {
1430
+ const protocol = process.env.VERCEL_URL.startsWith("http") ? "" : "https://";
1431
+ return `${new URL(`${protocol}${process.env.VERCEL_URL}`).origin}${path}`;
1432
+ } catch {}
1433
+ }
1434
+ };
1435
+ const getClientConfig = (options, loadEnv) => {
1436
+ const isCredentialsSupported = "credentials" in Request.prototype;
1437
+ const baseURL = getBaseURL(options?.baseURL, options?.basePath, void 0, loadEnv) ?? resolvePublicAuthUrl(options?.basePath) ?? "/api/auth";
1438
+ const pluginsFetchPlugins = options?.plugins?.flatMap((plugin) => plugin.fetchPlugins).filter((pl) => pl !== void 0) || [];
1439
+ const lifeCyclePlugin = {
1440
+ id: "lifecycle-hooks",
1441
+ name: "lifecycle-hooks",
1442
+ hooks: {
1443
+ onSuccess: options?.fetchOptions?.onSuccess,
1444
+ onError: options?.fetchOptions?.onError,
1445
+ onRequest: options?.fetchOptions?.onRequest,
1446
+ onResponse: options?.fetchOptions?.onResponse
1447
+ }
1448
+ };
1449
+ const { onSuccess: _onSuccess, onError: _onError, onRequest: _onRequest, onResponse: _onResponse, ...restOfFetchOptions } = options?.fetchOptions || {};
1450
+ const $fetch = createFetch$1({
1451
+ baseURL,
1452
+ ...isCredentialsSupported ? { credentials: "include" } : {},
1453
+ method: "GET",
1454
+ jsonParser(text) {
1455
+ if (!text) return null;
1456
+ return parseJSON(text, { strict: false });
1457
+ },
1458
+ customFetchImpl: fetch,
1459
+ ...restOfFetchOptions,
1460
+ plugins: [
1461
+ lifeCyclePlugin,
1462
+ ...restOfFetchOptions.plugins || [],
1463
+ ...options?.disableDefaultFetchPlugins ? [] : [redirectPlugin],
1464
+ ...pluginsFetchPlugins
1465
+ ]
1466
+ });
1467
+ const { $sessionSignal, session, broadcastSessionUpdate } = getSessionAtom($fetch, options);
1468
+ const plugins = options?.plugins || [];
1469
+ let pluginsActions = {};
1470
+ const pluginsAtoms = {
1471
+ $sessionSignal,
1472
+ session
1473
+ };
1474
+ const pluginPathMethods = {
1475
+ "/sign-out": "POST",
1476
+ "/revoke-sessions": "POST",
1477
+ "/revoke-other-sessions": "POST",
1478
+ "/delete-user": "POST"
1479
+ };
1480
+ const atomListeners = [{
1481
+ signal: "$sessionSignal",
1482
+ matcher(path) {
1483
+ return path === "/sign-out" || path === "/update-user" || path === "/update-session" || path === "/sign-up/email" || path === "/sign-in/email" || path === "/delete-user" || path === "/verify-email" || path === "/revoke-sessions" || path === "/revoke-session" || path === "/revoke-other-sessions" || path === "/change-email" || path === "/change-password";
1484
+ },
1485
+ callback(path) {
1486
+ if (path === "/sign-out") broadcastSessionUpdate("signout");
1487
+ else if (path === "/update-user" || path === "/update-session") broadcastSessionUpdate("updateUser");
1488
+ }
1489
+ }];
1490
+ for (const plugin of plugins) {
1491
+ if (plugin.getAtoms) Object.assign(pluginsAtoms, plugin.getAtoms?.($fetch));
1492
+ if (plugin.pathMethods) Object.assign(pluginPathMethods, plugin.pathMethods);
1493
+ if (plugin.atomListeners) atomListeners.push(...plugin.atomListeners);
1494
+ }
1495
+ const $store = {
1496
+ notify: (signal) => {
1497
+ pluginsAtoms[signal].set(!pluginsAtoms[signal].get());
1498
+ },
1499
+ listen: (signal, listener) => {
1500
+ pluginsAtoms[signal].subscribe(listener);
1501
+ },
1502
+ atoms: pluginsAtoms
1503
+ };
1504
+ for (const plugin of plugins) if (plugin.getActions) pluginsActions = defu(plugin.getActions?.($fetch, $store, options) ?? {}, pluginsActions);
1505
+ return {
1506
+ get baseURL() {
1507
+ return baseURL;
1508
+ },
1509
+ pluginsActions,
1510
+ pluginsAtoms,
1511
+ pluginPathMethods,
1512
+ atomListeners,
1513
+ $fetch,
1514
+ $store
1515
+ };
1516
+ };
1517
+ //#endregion
1518
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/utils/is-atom.mjs
1519
+ function isAtom(value) {
1520
+ return typeof value === "object" && value !== null && "get" in value && typeof value.get === "function" && "lc" in value && typeof value.lc === "number";
1521
+ }
1522
+ //#endregion
1523
+ //#region ../../node_modules/.pnpm/@better-auth+core@1.6.22_@better-auth+utils@0.4.2_@better-fetch+fetch@1.3.1_better-call_17975d57218030f5a353914665f207d6/node_modules/@better-auth/core/dist/utils/string.mjs
1524
+ function capitalizeFirstLetter(str) {
1525
+ return str.charAt(0).toUpperCase() + str.slice(1);
1526
+ }
1527
+ const WORD_PATTERN = /[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu;
1528
+ const APOSTROPHE_PATTERN = /['\u2019]/g;
1529
+ function splitWords(input) {
1530
+ return input.replace(APOSTROPHE_PATTERN, "").match(WORD_PATTERN) ?? [];
1531
+ }
1532
+ function toKebabCase(input) {
1533
+ return splitWords(input).map((word) => word.toLowerCase()).join("-");
1534
+ }
1535
+ //#endregion
1536
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/proxy.mjs
1537
+ function getMethod(path, knownPathMethods, args) {
1538
+ const method = knownPathMethods[path];
1539
+ const { fetchOptions, query: _query, ...body } = args || {};
1540
+ if (method) return method;
1541
+ if (fetchOptions?.method) return fetchOptions.method;
1542
+ if (body && Object.keys(body).length > 0) return "POST";
1543
+ return "GET";
1544
+ }
1545
+ function createDynamicPathProxy(routes, client, knownPathMethods, atoms, atomListeners) {
1546
+ function createProxy(path = []) {
1547
+ return new Proxy(function() {}, {
1548
+ get(_, prop) {
1549
+ if (typeof prop !== "string") return;
1550
+ if (prop === "then" || prop === "catch" || prop === "finally") return;
1551
+ const fullPath = [...path, prop];
1552
+ let current = routes;
1553
+ for (const segment of fullPath) if (current && typeof current === "object" && segment in current) current = current[segment];
1554
+ else {
1555
+ current = void 0;
1556
+ break;
1557
+ }
1558
+ if (typeof current === "function") return current;
1559
+ if (isAtom(current)) return current;
1560
+ return createProxy(fullPath);
1561
+ },
1562
+ apply: async (_, __, args) => {
1563
+ const routePath = "/" + path.map(toKebabCase).join("/");
1564
+ const arg = args[0] || {};
1565
+ const fetchOptions = args[1] || {};
1566
+ const { query, fetchOptions: argFetchOptions, ...body } = arg;
1567
+ const options = {
1568
+ ...fetchOptions,
1569
+ ...argFetchOptions
1570
+ };
1571
+ const method = getMethod(routePath, knownPathMethods, arg);
1572
+ return await client(routePath, {
1573
+ ...options,
1574
+ body: method === "GET" ? void 0 : {
1575
+ ...body,
1576
+ ...options?.body || {}
1577
+ },
1578
+ query: query || options?.query,
1579
+ method,
1580
+ async onSuccess(context) {
1581
+ await options?.onSuccess?.(context);
1582
+ if (!atomListeners || options.disableSignal) return;
1583
+ const matches = atomListeners.filter((s) => s.matcher(routePath));
1584
+ if (!matches.length) return;
1585
+ const visited = new Set();
1586
+ for (const match of matches) {
1587
+ const signal = atoms[match.signal];
1588
+ if (!signal) return;
1589
+ if (visited.has(match.signal)) continue;
1590
+ visited.add(match.signal);
1591
+ const val = signal.get();
1592
+ setTimeout(() => {
1593
+ signal.set(!val);
1594
+ }, 10);
1595
+ match.callback?.(routePath);
1596
+ }
1597
+ }
1598
+ });
1599
+ }
1600
+ });
1601
+ }
1602
+ return createProxy();
1603
+ }
1604
+ //#endregion
1605
+ //#region ../../node_modules/.pnpm/better-auth@1.6.22_drizzle-kit@0.31.10_drizzle-orm@0.45.2_@libsql+client@0.17.4_kysely@0.29.2__vitest@4.1.10/node_modules/better-auth/dist/client/vanilla.mjs
1606
+ function createAuthClient$1(options) {
1607
+ const { pluginPathMethods, pluginsActions, pluginsAtoms, $fetch, atomListeners, $store } = getClientConfig(options);
1608
+ const resolvedHooks = {};
1609
+ for (const [key, value] of Object.entries(pluginsAtoms)) resolvedHooks[`use${capitalizeFirstLetter(key)}`] = value;
1610
+ return createDynamicPathProxy({
1611
+ ...pluginsActions,
1612
+ ...resolvedHooks,
1613
+ $fetch,
1614
+ $store
1615
+ }, $fetch, pluginPathMethods, pluginsAtoms, atomListeners);
1616
+ }
1617
+ //#endregion
1618
+ //#region ../../node_modules/.pnpm/@chiballc+utils@2.2.22_magic-string@0.30.21_magicast@0.5.3_rolldown@1.2.0_vite@7.3.6_@t_bb8aca60aa14bf30011cd038d243a4ee/node_modules/@chiballc/utils/dist/index.mjs
1619
+ function isPromise(arg) {
1620
+ return arg && typeof arg.then === "function";
1621
+ }
1622
+ function execute(arg, ...args) {
1623
+ if (isPromise(arg)) return arg.then((v) => ({
1624
+ result: v,
1625
+ error: void 0
1626
+ })).catch((e) => ({
1627
+ result: void 0,
1628
+ error: e
1629
+ }));
1630
+ if (typeof arg === "function") try {
1631
+ return execute(arg(...args));
1632
+ } catch (e) {
1633
+ return {
1634
+ result: void 0,
1635
+ error: e
1636
+ };
1637
+ }
1638
+ return {
1639
+ result: arg,
1640
+ error: void 0
1641
+ };
1642
+ }
1643
+ typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
1644
+ typeof ServiceWorkerGlobalScope !== "undefined" && self instanceof ServiceWorkerGlobalScope;
1645
+ /**
1646
+ * KINOID
1647
+ *
1648
+ * @overview
1649
+ * Kinoid is a lightweight function for generating unique, URL-friendly IDs.
1650
+ * It is designed to work in both Node.js and browser environments.
1651
+ *
1652
+ * @description
1653
+ * Kinoid generates unique identifiers (IDs) that are:
1654
+ * - **Unique**: Each ID is guaranteed to be different from all others
1655
+ * generated before or at the same time on the same machine.
1656
+ * - **Sortable by time**: IDs are based on the timestamp of their creation,
1657
+ * making them naturally sortable.
1658
+ * - **Decodable**: The `decodeId()` function allows you to extract the
1659
+ * components used to generate an ID, such as the timestamp, process ID,
1660
+ * and singularity factor.
1661
+ *
1662
+ * ### How IDs are generated
1663
+ * Each ID is composed of:
1664
+ * - A **timestamp**: The number of milliseconds since the UNIX epoch.
1665
+ * - A **process ID**: Identifies the process in which the program runs.
1666
+ * - A **singularity factor**: A sequential number that ensures uniqueness
1667
+ * even when multiple IDs are generated in the same millisecond.
1668
+ *
1669
+ * ### Main Functions
1670
+ * - `newId()`: Generates a new unique ID as a string.
1671
+ * - `decodeId()`: Decodes an existing ID into its components, such as the
1672
+ * timestamp, singularity factor, and process ID.
1673
+ *
1674
+ * ### Warning
1675
+ * Kinoid ensures that each generated ID is **unique**, but not necessarily
1676
+ * **unpredictable**. If you need cryptographically secure IDs, consider
1677
+ * using a library designed for that purpose.
1678
+ *
1679
+ * @author Thorn Duke
1680
+ * @version 3
1681
+ * @license MIT
1682
+ * @copyright Thorn Duke 2024
1683
+ */
1684
+ String.fromCharCode;
1685
+ const HASH_RE = /#/g;
1686
+ const AMPERSAND_RE = /&/g;
1687
+ const SLASH_RE = /\//g;
1688
+ const EQUAL_RE = /=/g;
1689
+ const PLUS_RE = /\+/g;
1690
+ const ENC_CARET_RE = /%5e/gi;
1691
+ const ENC_BACKTICK_RE = /%60/gi;
1692
+ const ENC_PIPE_RE = /%7c/gi;
1693
+ const ENC_SPACE_RE = /%20/gi;
1694
+ function encode(text) {
1695
+ return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
1696
+ }
1697
+ function encodeQueryValue(input) {
1698
+ return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
1699
+ }
1700
+ function encodeQueryKey(text) {
1701
+ return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
1702
+ }
1703
+ function decode(text = "") {
1704
+ try {
1705
+ return decodeURIComponent("" + text);
1706
+ } catch {
1707
+ return "" + text;
1708
+ }
1709
+ }
1710
+ function decodeQueryKey(text) {
1711
+ return decode(text.replace(PLUS_RE, " "));
1712
+ }
1713
+ function decodeQueryValue(text) {
1714
+ return decode(text.replace(PLUS_RE, " "));
1715
+ }
1716
+ function parseQuery(parametersString = "") {
1717
+ const object = Object.create(null);
1718
+ if (parametersString[0] === "?") parametersString = parametersString.slice(1);
1719
+ for (const parameter of parametersString.split("&")) {
1720
+ const s = parameter.match(/([^=]+)=?(.*)/) || [];
1721
+ if (s.length < 2) continue;
1722
+ const key = decodeQueryKey(s[1]);
1723
+ if (key === "__proto__" || key === "constructor") continue;
1724
+ const value = decodeQueryValue(s[2] || "");
1725
+ if (object[key] === void 0) object[key] = value;
1726
+ else if (Array.isArray(object[key])) object[key].push(value);
1727
+ else object[key] = [object[key], value];
1728
+ }
1729
+ return object;
1730
+ }
1731
+ function encodeQueryItem(key, value) {
1732
+ if (typeof value === "number" || typeof value === "boolean") value = String(value);
1733
+ if (!value) return encodeQueryKey(key);
1734
+ if (Array.isArray(value)) return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
1735
+ return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
1736
+ }
1737
+ function stringifyQuery(query) {
1738
+ return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
1739
+ }
1740
+ const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/;
1741
+ const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/;
1742
+ const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
1743
+ const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
1744
+ const JOIN_LEADING_SLASH_RE = /^\.?\//;
1745
+ function hasProtocol(inputString, opts = {}) {
1746
+ if (typeof opts === "boolean") opts = { acceptRelative: opts };
1747
+ if (opts.strict) return PROTOCOL_STRICT_REGEX.test(inputString);
1748
+ return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false);
1749
+ }
1750
+ function hasTrailingSlash(input = "", respectQueryAndFragment) {
1751
+ if (!respectQueryAndFragment) return input.endsWith("/");
1752
+ return TRAILING_SLASH_RE.test(input);
1753
+ }
1754
+ function withoutTrailingSlash(input = "", respectQueryAndFragment) {
1755
+ if (!respectQueryAndFragment) return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/";
1756
+ if (!hasTrailingSlash(input, true)) return input || "/";
1757
+ let path = input;
1758
+ let fragment = "";
1759
+ const fragmentIndex = input.indexOf("#");
1760
+ if (fragmentIndex !== -1) {
1761
+ path = input.slice(0, fragmentIndex);
1762
+ fragment = input.slice(fragmentIndex);
1763
+ }
1764
+ const [s0, ...s] = path.split("?");
1765
+ return ((s0.endsWith("/") ? s0.slice(0, -1) : s0) || "/") + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
1766
+ }
1767
+ function withTrailingSlash(input = "", respectQueryAndFragment) {
1768
+ if (!respectQueryAndFragment) return input.endsWith("/") ? input : input + "/";
1769
+ if (hasTrailingSlash(input, true)) return input || "/";
1770
+ let path = input;
1771
+ let fragment = "";
1772
+ const fragmentIndex = input.indexOf("#");
1773
+ if (fragmentIndex !== -1) {
1774
+ path = input.slice(0, fragmentIndex);
1775
+ fragment = input.slice(fragmentIndex);
1776
+ if (!path) return fragment;
1777
+ }
1778
+ const [s0, ...s] = path.split("?");
1779
+ return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
1780
+ }
1781
+ function withBase(input, base) {
1782
+ if (isEmptyURL(base) || hasProtocol(input)) return input;
1783
+ const _base = withoutTrailingSlash(base);
1784
+ if (input.startsWith(_base)) {
1785
+ const nextChar = input[_base.length];
1786
+ if (!nextChar || nextChar === "/" || nextChar === "?") return input;
1787
+ }
1788
+ return joinURL(_base, input);
1789
+ }
1790
+ function withQuery(input, query) {
1791
+ const parsed = parseURL(input);
1792
+ parsed.search = stringifyQuery({
1793
+ ...parseQuery(parsed.search),
1794
+ ...query
1795
+ });
1796
+ return stringifyParsedURL(parsed);
1797
+ }
1798
+ function isEmptyURL(url) {
1799
+ return !url || url === "/";
1800
+ }
1801
+ function isNonEmptyURL(url) {
1802
+ return url && url !== "/";
1803
+ }
1804
+ function joinURL(base, ...input) {
1805
+ let url = base || "";
1806
+ for (const segment of input.filter((url2) => isNonEmptyURL(url2))) if (url) {
1807
+ const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
1808
+ url = withTrailingSlash(url) + _segment;
1809
+ } else url = segment;
1810
+ return url;
1811
+ }
1812
+ const protocolRelative = Symbol.for("ufo:protocolRelative");
1813
+ function parseURL(input = "", defaultProto) {
1814
+ const _specialProtoMatch = input.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);
1815
+ if (_specialProtoMatch) {
1816
+ const [, _proto, _pathname = ""] = _specialProtoMatch;
1817
+ return {
1818
+ protocol: _proto.toLowerCase(),
1819
+ pathname: _pathname,
1820
+ href: _proto + _pathname,
1821
+ auth: "",
1822
+ host: "",
1823
+ search: "",
1824
+ hash: ""
1825
+ };
1826
+ }
1827
+ if (!hasProtocol(input, { acceptRelative: true })) return defaultProto ? parseURL(defaultProto + input) : parsePath(input);
1828
+ const [, protocol = "", auth, hostAndPath = ""] = input.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || [];
1829
+ let [, host = "", path = ""] = hostAndPath.match(/([^#/?]*)(.*)?/) || [];
1830
+ if (protocol === "file:") path = path.replace(/\/(?=[A-Za-z]:)/, "");
1831
+ const { pathname, search, hash } = parsePath(path);
1832
+ return {
1833
+ protocol: protocol.toLowerCase(),
1834
+ auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "",
1835
+ host,
1836
+ pathname,
1837
+ search,
1838
+ hash,
1839
+ [protocolRelative]: !protocol
1840
+ };
1841
+ }
1842
+ function parsePath(input = "") {
1843
+ const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1);
1844
+ return {
1845
+ pathname,
1846
+ search,
1847
+ hash
1848
+ };
1849
+ }
1850
+ function stringifyParsedURL(parsed) {
1851
+ const pathname = parsed.pathname || "";
1852
+ const search = parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : "";
1853
+ const hash = parsed.hash || "";
1854
+ const auth = parsed.auth ? parsed.auth + "@" : "";
1855
+ const host = parsed.host || "";
1856
+ return (parsed.protocol || parsed[protocolRelative] ? (parsed.protocol || "") + "//" : "") + auth + host + pathname + search + hash;
1857
+ }
1858
+ //#endregion
1859
+ //#region src/errors.ts
1860
+ const messages = {
1861
+ invalid_credentials: "The credentials are invalid.",
1862
+ authentication_required: "Authentication is required.",
1863
+ request_origin_denied: "The request origin is not allowed.",
1864
+ invalid_workspace_selection: "The workspace selection is invalid.",
1865
+ credential_rate_limited: "Credential requests are temporarily limited.",
1866
+ state_conflict: "The authentication state conflicts with the request.",
1867
+ access_denied: "Access is denied.",
1868
+ identity_authority_unavailable: "Authentication is temporarily unavailable."
1869
+ };
1870
+ var AuthError = class extends Error {
1871
+ code;
1872
+ status;
1873
+ retryAfterSeconds;
1874
+ constructor(code, status, retryAfterSeconds) {
1875
+ super(messages[code]);
1876
+ this.name = "AuthError";
1877
+ this.code = code;
1878
+ this.status = status;
1879
+ this.retryAfterSeconds = retryAfterSeconds;
1880
+ }
1881
+ };
1882
+ //#endregion
1883
+ //#region ../../node_modules/.pnpm/destr@2.0.5/node_modules/destr/dist/index.mjs
1884
+ const suspectProtoRx = /"(?:_|\\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*:/;
1885
+ const suspectConstructorRx = /"(?: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*:/;
1886
+ const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
1887
+ function jsonParseTransform(key, value) {
1888
+ if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
1889
+ warnKeyDropped(key);
1890
+ return;
1891
+ }
1892
+ return value;
1893
+ }
1894
+ function warnKeyDropped(key) {
1895
+ console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
1896
+ }
1897
+ function destr(value, options = {}) {
1898
+ if (typeof value !== "string") return value;
1899
+ if (value[0] === "\"" && value[value.length - 1] === "\"" && value.indexOf("\\") === -1) return value.slice(1, -1);
1900
+ const _value = value.trim();
1901
+ if (_value.length <= 9) switch (_value.toLowerCase()) {
1902
+ case "true": return true;
1903
+ case "false": return false;
1904
+ case "undefined": return;
1905
+ case "null": return null;
1906
+ case "nan": return NaN;
1907
+ case "infinity": return Number.POSITIVE_INFINITY;
1908
+ case "-infinity": return Number.NEGATIVE_INFINITY;
1909
+ }
1910
+ if (!JsonSigRx.test(value)) {
1911
+ if (options.strict) throw new SyntaxError("[destr] Invalid JSON");
1912
+ return value;
1913
+ }
1914
+ try {
1915
+ if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
1916
+ if (options.strict) throw new Error("[destr] Possible prototype pollution");
1917
+ return JSON.parse(value, jsonParseTransform);
1918
+ }
1919
+ return JSON.parse(value);
1920
+ } catch (error) {
1921
+ if (options.strict) throw error;
1922
+ return value;
1923
+ }
1924
+ }
1925
+ //#endregion
1926
+ //#region ../../node_modules/.pnpm/ofetch@1.5.1/node_modules/ofetch/dist/shared/ofetch.CWycOUEr.mjs
1927
+ var FetchError = class extends Error {
1928
+ constructor(message, opts) {
1929
+ super(message, opts);
1930
+ this.name = "FetchError";
1931
+ if (opts?.cause && !this.cause) this.cause = opts.cause;
1932
+ }
1933
+ };
1934
+ function createFetchError(ctx) {
1935
+ const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
1936
+ const method = ctx.request?.method || ctx.options?.method || "GET";
1937
+ const url = ctx.request?.url || String(ctx.request) || "/";
1938
+ const fetchError = new FetchError(`${`[${method}] ${JSON.stringify(url)}`}: ${ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : "<no response>"}${errorMessage ? ` ${errorMessage}` : ""}`, ctx.error ? { cause: ctx.error } : void 0);
1939
+ for (const key of [
1940
+ "request",
1941
+ "options",
1942
+ "response"
1943
+ ]) Object.defineProperty(fetchError, key, { get() {
1944
+ return ctx[key];
1945
+ } });
1946
+ for (const [key, refKey] of [
1947
+ ["data", "_data"],
1948
+ ["status", "status"],
1949
+ ["statusCode", "status"],
1950
+ ["statusText", "statusText"],
1951
+ ["statusMessage", "statusText"]
1952
+ ]) Object.defineProperty(fetchError, key, { get() {
1953
+ return ctx.response && ctx.response[refKey];
1954
+ } });
1955
+ return fetchError;
1956
+ }
1957
+ const payloadMethods = new Set(Object.freeze([
1958
+ "PATCH",
1959
+ "POST",
1960
+ "PUT",
1961
+ "DELETE"
1962
+ ]));
1963
+ function isPayloadMethod(method = "GET") {
1964
+ return payloadMethods.has(method.toUpperCase());
1965
+ }
1966
+ function isJSONSerializable(value) {
1967
+ if (value === void 0) return false;
1968
+ const t = typeof value;
1969
+ if (t === "string" || t === "number" || t === "boolean" || t === null) return true;
1970
+ if (t !== "object") return false;
1971
+ if (Array.isArray(value)) return true;
1972
+ if (value.buffer) return false;
1973
+ if (value instanceof FormData || value instanceof URLSearchParams) return false;
1974
+ return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
1975
+ }
1976
+ const textTypes = new Set([
1977
+ "image/svg",
1978
+ "application/xml",
1979
+ "application/xhtml",
1980
+ "application/html"
1981
+ ]);
1982
+ const JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
1983
+ function detectResponseType(_contentType = "") {
1984
+ if (!_contentType) return "json";
1985
+ const contentType = _contentType.split(";").shift() || "";
1986
+ if (JSON_RE.test(contentType)) return "json";
1987
+ if (contentType === "text/event-stream") return "stream";
1988
+ if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
1989
+ return "blob";
1990
+ }
1991
+ function resolveFetchOptions(request, input, defaults, Headers) {
1992
+ const headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers);
1993
+ let query;
1994
+ if (defaults?.query || defaults?.params || input?.params || input?.query) query = {
1995
+ ...defaults?.params,
1996
+ ...defaults?.query,
1997
+ ...input?.params,
1998
+ ...input?.query
1999
+ };
2000
+ return {
2001
+ ...defaults,
2002
+ ...input,
2003
+ query,
2004
+ params: query,
2005
+ headers
2006
+ };
2007
+ }
2008
+ function mergeHeaders(input, defaults, Headers) {
2009
+ if (!defaults) return new Headers(input);
2010
+ const headers = new Headers(defaults);
2011
+ if (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers(input)) headers.set(key, value);
2012
+ return headers;
2013
+ }
2014
+ async function callHooks(context, hooks) {
2015
+ if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
2016
+ else await hooks(context);
2017
+ }
2018
+ const retryStatusCodes = new Set([
2019
+ 408,
2020
+ 409,
2021
+ 425,
2022
+ 429,
2023
+ 500,
2024
+ 502,
2025
+ 503,
2026
+ 504
2027
+ ]);
2028
+ const nullBodyResponses = new Set([
2029
+ 101,
2030
+ 204,
2031
+ 205,
2032
+ 304
2033
+ ]);
2034
+ function createFetch(globalOptions = {}) {
2035
+ const { fetch = globalThis.fetch, Headers = globalThis.Headers, AbortController = globalThis.AbortController } = globalOptions;
2036
+ async function onError(context) {
2037
+ const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
2038
+ if (context.options.retry !== false && !isAbort) {
2039
+ let retries;
2040
+ if (typeof context.options.retry === "number") retries = context.options.retry;
2041
+ else retries = isPayloadMethod(context.options.method) ? 0 : 1;
2042
+ const responseCode = context.response && context.response.status || 500;
2043
+ if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
2044
+ const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
2045
+ if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));
2046
+ return $fetchRaw(context.request, {
2047
+ ...context.options,
2048
+ retry: retries - 1
2049
+ });
2050
+ }
2051
+ }
2052
+ const error = createFetchError(context);
2053
+ if (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);
2054
+ throw error;
2055
+ }
2056
+ const $fetchRaw = async function $fetchRaw2(_request, _options = {}) {
2057
+ const context = {
2058
+ request: _request,
2059
+ options: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers),
2060
+ response: void 0,
2061
+ error: void 0
2062
+ };
2063
+ if (context.options.method) context.options.method = context.options.method.toUpperCase();
2064
+ if (context.options.onRequest) {
2065
+ await callHooks(context, context.options.onRequest);
2066
+ if (!(context.options.headers instanceof Headers)) context.options.headers = new Headers(context.options.headers || {});
2067
+ }
2068
+ if (typeof context.request === "string") {
2069
+ if (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);
2070
+ if (context.options.query) {
2071
+ context.request = withQuery(context.request, context.options.query);
2072
+ delete context.options.query;
2073
+ }
2074
+ if ("query" in context.options) delete context.options.query;
2075
+ if ("params" in context.options) delete context.options.params;
2076
+ }
2077
+ if (context.options.body && isPayloadMethod(context.options.method)) {
2078
+ if (isJSONSerializable(context.options.body)) {
2079
+ const contentType = context.options.headers.get("content-type");
2080
+ if (typeof context.options.body !== "string") context.options.body = contentType === "application/x-www-form-urlencoded" ? new URLSearchParams(context.options.body).toString() : JSON.stringify(context.options.body);
2081
+ if (!contentType) context.options.headers.set("content-type", "application/json");
2082
+ if (!context.options.headers.has("accept")) context.options.headers.set("accept", "application/json");
2083
+ } else if ("pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || typeof context.options.body.pipe === "function") {
2084
+ if (!("duplex" in context.options)) context.options.duplex = "half";
2085
+ }
2086
+ }
2087
+ let abortTimeout;
2088
+ if (!context.options.signal && context.options.timeout) {
2089
+ const controller = new AbortController();
2090
+ abortTimeout = setTimeout(() => {
2091
+ const error = new Error("[TimeoutError]: The operation was aborted due to timeout");
2092
+ error.name = "TimeoutError";
2093
+ error.code = 23;
2094
+ controller.abort(error);
2095
+ }, context.options.timeout);
2096
+ context.options.signal = controller.signal;
2097
+ }
2098
+ try {
2099
+ context.response = await fetch(context.request, context.options);
2100
+ } catch (error) {
2101
+ context.error = error;
2102
+ if (context.options.onRequestError) await callHooks(context, context.options.onRequestError);
2103
+ return await onError(context);
2104
+ } finally {
2105
+ if (abortTimeout) clearTimeout(abortTimeout);
2106
+ }
2107
+ if ((context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD") {
2108
+ const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
2109
+ switch (responseType) {
2110
+ case "json": {
2111
+ const data = await context.response.text();
2112
+ const parseFunction = context.options.parseResponse || destr;
2113
+ context.response._data = parseFunction(data);
2114
+ break;
2115
+ }
2116
+ case "stream":
2117
+ context.response._data = context.response.body || context.response._bodyInit;
2118
+ break;
2119
+ default: context.response._data = await context.response[responseType]();
2120
+ }
2121
+ }
2122
+ if (context.options.onResponse) await callHooks(context, context.options.onResponse);
2123
+ if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
2124
+ if (context.options.onResponseError) await callHooks(context, context.options.onResponseError);
2125
+ return await onError(context);
2126
+ }
2127
+ return context.response;
2128
+ };
2129
+ const $fetch = async function $fetch2(request, options) {
2130
+ return (await $fetchRaw(request, options))._data;
2131
+ };
2132
+ $fetch.raw = $fetchRaw;
2133
+ $fetch.native = (...args) => fetch(...args);
2134
+ $fetch.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
2135
+ ...globalOptions,
2136
+ ...customGlobalOptions,
2137
+ defaults: {
2138
+ ...globalOptions.defaults,
2139
+ ...customGlobalOptions.defaults,
2140
+ ...defaultOptions
2141
+ }
2142
+ });
2143
+ return $fetch;
2144
+ }
2145
+ //#endregion
2146
+ //#region src/shared.ts
2147
+ const id = /^[A-Za-z0-9_-]{1,128}$/;
2148
+ const email = /^[^\s@]+@[^\s@]+$/;
2149
+ function normalizeOrigin(value, name) {
2150
+ if (value.length === 0 || value.length > 2048 || /[^\x20-\x7e]/.test(value)) throw new TypeError(`${name} must be an ASCII HTTP origin`);
2151
+ let url;
2152
+ try {
2153
+ url = new URL(value);
2154
+ } catch {
2155
+ throw new TypeError(`${name} must be an ASCII HTTP origin`);
2156
+ }
2157
+ const local = url.hostname === "localhost" || url.hostname.endsWith(".localhost") || url.hostname === "127.0.0.1";
2158
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.pathname !== "/" || url.search || url.hash || url.origin !== value) throw new TypeError(`${name} must be an ASCII HTTP origin`);
2159
+ return url.origin;
2160
+ }
2161
+ function normalizeTimeout(value) {
2162
+ const timeout = value ?? 1e4;
2163
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 6e4) throw new TypeError("timeoutMs must be an integer from 1 to 60000");
2164
+ return timeout;
2165
+ }
2166
+ function normalizeSession(value) {
2167
+ if (value === null) return null;
2168
+ if (!isObject(value) || !isObject(value.session) || !isObject(value.user)) throw authorityUnavailable();
2169
+ const expiresAt = toDate(value.session.expiresAt);
2170
+ const image = value.user.image;
2171
+ if (!isId(value.session.id) || !expiresAt || !isId(value.user.id) || typeof value.user.name !== "string" || value.user.name.length > 256 || typeof value.user.email !== "string" || value.user.email.length > 320 || !email.test(value.user.email) || typeof value.user.emailVerified !== "boolean" || image !== null && image !== void 0 && (typeof image !== "string" || image.length > 2048)) throw authorityUnavailable();
2172
+ return {
2173
+ id: value.session.id,
2174
+ expiresAt,
2175
+ user: {
2176
+ id: value.user.id,
2177
+ name: value.user.name,
2178
+ email: value.user.email,
2179
+ emailVerified: value.user.emailVerified,
2180
+ image: image ?? null
2181
+ }
2182
+ };
2183
+ }
2184
+ function normalizeDriveCredential(value, now) {
2185
+ if (!isObject(value) || value.tokenType !== "Bearer" || value.expiresIn !== 900 || typeof value.token !== "string" || value.token.length === 0 || value.token.length + 7 > 16 * 1024) throw authorityUnavailable();
2186
+ return {
2187
+ tokenType: "Bearer",
2188
+ token: value.token,
2189
+ expiresAt: new Date(now + value.expiresIn * 1e3)
2190
+ };
2191
+ }
2192
+ function fromAuthorityError(value, fallbackStatus, retryAfter) {
2193
+ const mapped = mapError(isObject(value) && typeof value.code === "string" ? value.code : void 0, fallbackStatus);
2194
+ return new AuthError(mapped.code, mapped.status, parseRetryAfter(retryAfter));
2195
+ }
2196
+ function authorityUnavailable() {
2197
+ return new AuthError("identity_authority_unavailable", 503);
2198
+ }
2199
+ function mapError(code, status) {
2200
+ if (code === "authentication_required") return {
2201
+ code,
2202
+ status: 401
2203
+ };
2204
+ if (code === "request_origin_denied") return {
2205
+ code,
2206
+ status: 403
2207
+ };
2208
+ if (code === "invalid_workspace_selection") return {
2209
+ code,
2210
+ status: 422
2211
+ };
2212
+ if (code === "credential_rate_limited") return {
2213
+ code,
2214
+ status: 429
2215
+ };
2216
+ if (code === "identity_authority_unavailable") return {
2217
+ code,
2218
+ status: 503
2219
+ };
2220
+ if (status === 401 || status === 400) return {
2221
+ code: "invalid_credentials",
2222
+ status: 401
2223
+ };
2224
+ if (status === 403) return {
2225
+ code: "access_denied",
2226
+ status: 403
2227
+ };
2228
+ if (status === 409) return {
2229
+ code: "state_conflict",
2230
+ status: 409
2231
+ };
2232
+ if (status === 422) return {
2233
+ code: "invalid_workspace_selection",
2234
+ status: 422
2235
+ };
2236
+ if (status === 429) return {
2237
+ code: "credential_rate_limited",
2238
+ status: 429
2239
+ };
2240
+ return {
2241
+ code: "identity_authority_unavailable",
2242
+ status: 503
2243
+ };
2244
+ }
2245
+ function parseRetryAfter(value) {
2246
+ if (!value || !/^\d+$/.test(value)) return void 0;
2247
+ const seconds = Number(value);
2248
+ return Number.isSafeInteger(seconds) && seconds >= 1 && seconds <= 3600 ? seconds : void 0;
2249
+ }
2250
+ function toDate(value) {
2251
+ const result = value instanceof Date ? value : typeof value === "string" ? new Date(value) : void 0;
2252
+ return result && Number.isFinite(result.getTime()) ? result : void 0;
2253
+ }
2254
+ function isId(value) {
2255
+ return typeof value === "string" && id.test(value);
2256
+ }
2257
+ function isObject(value) {
2258
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2259
+ }
2260
+ //#endregion
2261
+ //#region src/http.ts
2262
+ const MAX_RESPONSE_BYTES = 64 * 1024;
2263
+ async function requestJson(url, options) {
2264
+ let response;
2265
+ try {
2266
+ response = await createFetch({ fetch: options.fetch }).raw(url, {
2267
+ method: options.method,
2268
+ headers: options.headers,
2269
+ body: options.body,
2270
+ credentials: "include",
2271
+ retry: 0,
2272
+ timeout: options.timeoutMs,
2273
+ redirect: "manual",
2274
+ responseType: "stream",
2275
+ ignoreResponseError: true
2276
+ });
2277
+ } catch {
2278
+ throw authorityUnavailable();
2279
+ }
2280
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
2281
+ if (response.status >= 300 || response.status < 200 || contentType !== "application/json") {
2282
+ const body = contentType === "application/json" ? await readJson(response) : void 0;
2283
+ await response.body?.cancel();
2284
+ throw fromAuthorityError(body, response.status, response.headers.get("retry-after"));
2285
+ }
2286
+ return readJson(response);
2287
+ }
2288
+ async function readJson(response) {
2289
+ const length = response.headers.get("content-length");
2290
+ if (length && (!/^\d+$/.test(length) || Number(length) > MAX_RESPONSE_BYTES)) {
2291
+ await response.body?.cancel();
2292
+ throw authorityUnavailable();
2293
+ }
2294
+ if (!response.body) throw authorityUnavailable();
2295
+ const reader = response.body.getReader();
2296
+ const chunks = [];
2297
+ let size = 0;
2298
+ try {
2299
+ while (true) {
2300
+ const { done, value } = await reader.read();
2301
+ if (done) break;
2302
+ size += value.byteLength;
2303
+ if (size > MAX_RESPONSE_BYTES) throw authorityUnavailable();
2304
+ chunks.push(value);
2305
+ }
2306
+ } catch (error) {
2307
+ await reader.cancel();
2308
+ throw error;
2309
+ } finally {
2310
+ reader.releaseLock();
2311
+ }
2312
+ const bytes = new Uint8Array(size);
2313
+ let offset = 0;
2314
+ for (const chunk of chunks) {
2315
+ bytes.set(chunk, offset);
2316
+ offset += chunk.byteLength;
2317
+ }
2318
+ try {
2319
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
2320
+ } catch {
2321
+ throw authorityUnavailable();
2322
+ }
2323
+ }
2324
+ //#endregion
2325
+ //#region src/client.ts
2326
+ const REFRESH_WINDOW_MS = 120 * 1e3;
2327
+ function createAuthClient(options) {
2328
+ const authOrigin = normalizeOrigin(options.authOrigin, "authOrigin");
2329
+ const appOrigin = normalizeOrigin(options.appOrigin, "appOrigin");
2330
+ if (typeof location !== "undefined" && location.origin !== appOrigin) throw new TypeError("appOrigin must match the current browser origin");
2331
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2332
+ if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
2333
+ const now = options.now ?? Date.now;
2334
+ const timeoutMs = normalizeTimeout(options.timeoutMs);
2335
+ const betterAuth = createAuthClient$1({
2336
+ baseURL: authOrigin,
2337
+ basePath: "/api/v1/auth",
2338
+ fetchOptions: {
2339
+ customFetchImpl: fetchImpl,
2340
+ retry: 0,
2341
+ timeout: timeoutMs
2342
+ }
2343
+ });
2344
+ let credential;
2345
+ let credentialRequest;
2346
+ let credentialGeneration = 0;
2347
+ let sessionId;
2348
+ function clearCredential() {
2349
+ credential = void 0;
2350
+ credentialRequest = void 0;
2351
+ credentialGeneration += 1;
2352
+ }
2353
+ function updateSession(session) {
2354
+ if (!session || !sessionId && (credential || credentialRequest) || sessionId && session.id !== sessionId) clearCredential();
2355
+ sessionId = session?.id;
2356
+ return session;
2357
+ }
2358
+ async function getSession() {
2359
+ let result;
2360
+ try {
2361
+ result = await betterAuth.getSession();
2362
+ } catch {
2363
+ throw authorityUnavailable();
2364
+ }
2365
+ if (result.error) throw fromAuthorityError(result.error, result.error.status);
2366
+ return updateSession(normalizeSession(result.data));
2367
+ }
2368
+ return {
2369
+ getSession,
2370
+ async signIn(input) {
2371
+ clearCredential();
2372
+ let result;
2373
+ try {
2374
+ result = await betterAuth.signIn.email({
2375
+ email: input.email,
2376
+ password: input.password
2377
+ });
2378
+ } catch {
2379
+ throw authorityUnavailable();
2380
+ }
2381
+ if (result.error) throw fromAuthorityError(result.error, result.error.status);
2382
+ const session = await getSession();
2383
+ if (!session) throw new AuthError("authentication_required", 401);
2384
+ return session;
2385
+ },
2386
+ async signOut() {
2387
+ clearCredential();
2388
+ sessionId = void 0;
2389
+ let result;
2390
+ try {
2391
+ result = await betterAuth.signOut();
2392
+ } catch {
2393
+ throw authorityUnavailable();
2394
+ }
2395
+ if (result.error) throw fromAuthorityError(result.error, result.error.status);
2396
+ },
2397
+ getDriveCredential(input) {
2398
+ if (input.workspace.type !== "personal") return Promise.reject(new AuthError("invalid_workspace_selection", 422));
2399
+ if (!input.forceRefresh && credential && credential.expiresAt.getTime() - now() > REFRESH_WINDOW_MS) return Promise.resolve(credential);
2400
+ if (input.forceRefresh) credential = void 0;
2401
+ if (!credentialRequest) {
2402
+ const generation = credentialGeneration;
2403
+ const request = (async () => {
2404
+ const { error, result } = await execute(requestJson(joinURL(authOrigin, "api/v1/auth/drive-credential"), {
2405
+ fetch: fetchImpl,
2406
+ timeoutMs,
2407
+ method: "POST",
2408
+ headers: { "content-type": "application/json; charset=utf-8" },
2409
+ body: { workspace: { type: "personal" } }
2410
+ }));
2411
+ if (error) throw error;
2412
+ const nextCredential = normalizeDriveCredential(result, now());
2413
+ if (generation !== credentialGeneration) throw new AuthError("authentication_required", 401);
2414
+ credential = nextCredential;
2415
+ return nextCredential;
2416
+ })().finally(() => {
2417
+ if (credentialRequest === request) credentialRequest = void 0;
2418
+ });
2419
+ credentialRequest = request;
2420
+ }
2421
+ return credentialRequest;
2422
+ },
2423
+ onSessionChange(listener) {
2424
+ return betterAuth.useSession.subscribe((state) => {
2425
+ let session;
2426
+ try {
2427
+ session = updateSession(normalizeSession(state.data));
2428
+ } catch {
2429
+ clearCredential();
2430
+ session = null;
2431
+ }
2432
+ listener(session);
2433
+ });
2434
+ }
2435
+ };
2436
+ }
2437
+ //#endregion
2438
+ export { AuthError, createAuthClient };