@vite-hub/auth 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +443 -32
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +23 -12
  9. package/dist/agent.js +30 -8
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +7 -0
  15. package/dist/cli.js +108 -0
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -0
  19. package/dist/console-runtime.js +2 -0
  20. package/dist/console-types-CmmnKGMx.js +38 -0
  21. package/dist/console.d.ts +219 -0
  22. package/dist/console.js +15 -0
  23. package/dist/database-options-BRNef9oy.js +29 -0
  24. package/dist/database-schema-options-ENuRMduM.js +12 -0
  25. package/dist/database.d.ts +12 -0
  26. package/dist/database.js +45 -0
  27. package/dist/definition-CqQMcDEK.js +280 -0
  28. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  29. package/dist/events-ByzenEVj.js +314 -0
  30. package/dist/forward.d.ts +50 -0
  31. package/dist/forward.js +120 -0
  32. package/dist/host-declarations.d.ts +6 -1
  33. package/dist/index.d.ts +26 -5
  34. package/dist/index.js +3 -95
  35. package/dist/internal/server.d.ts +5 -0
  36. package/dist/internal/server.js +858 -0
  37. package/dist/invariant-D8_xBqmZ.js +22 -0
  38. package/dist/mcp.d.ts +187 -0
  39. package/dist/mcp.js +353 -0
  40. package/dist/members-D9lfaEO_.js +533 -0
  41. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  42. package/dist/nuxt.d.ts +36 -7
  43. package/dist/nuxt.js +116 -7
  44. package/dist/object-Da1zyPCR.js +11 -0
  45. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  46. package/dist/presets-BGZi6Dfu.d.ts +25 -0
  47. package/dist/presets.d.ts +2 -0
  48. package/dist/presets.js +32 -0
  49. package/dist/request-z6DHHmrb.js +47 -0
  50. package/dist/runtime/console.d.ts +3 -0
  51. package/dist/runtime/console.js +4 -0
  52. package/dist/runtime/empty-abilities.d.ts +5 -0
  53. package/dist/runtime/empty-abilities.js +4 -0
  54. package/dist/runtime/empty-client.d.ts +6 -0
  55. package/dist/runtime/empty-client.js +5 -0
  56. package/dist/runtime/empty-definition.d.ts +1 -2
  57. package/dist/runtime/nuxt.d.ts +2 -3
  58. package/dist/runtime/nuxt.js +3 -2
  59. package/dist/runtime/server.d.ts +2 -0
  60. package/dist/runtime/server.js +77 -0
  61. package/dist/runtime/vue-nuxt.d.ts +4 -0
  62. package/dist/runtime/vue-nuxt.js +160 -0
  63. package/dist/runtime-state-ojQCzKOc.js +25 -0
  64. package/dist/schema.d.ts +137 -0
  65. package/dist/schema.js +147 -0
  66. package/dist/server-C0qnKN2W.d.ts +143 -0
  67. package/dist/server-bQGzVQ--.d.ts +41 -0
  68. package/dist/server.d.ts +3 -22
  69. package/dist/server.js +3 -2
  70. package/dist/session-cookies-BbH3UR2m.js +227 -0
  71. package/dist/set-cookie-C8NOhdRE.js +90 -0
  72. package/dist/shared-BwcdRGxD.js +12 -0
  73. package/dist/table-specs-8gq_FCaq.js +771 -0
  74. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  75. package/dist/test.d.ts +26 -0
  76. package/dist/test.js +25 -0
  77. package/dist/types-CNaeH2Fd.d.ts +569 -0
  78. package/dist/vite-CV400XXY.js +1556 -0
  79. package/dist/vite.d.ts +145 -18
  80. package/dist/vite.js +2 -2
  81. package/dist/vue.d.ts +343 -17
  82. package/dist/vue.js +640 -15
  83. package/package.json +156 -27
  84. package/dist/server-BZn8iQrB.js +0 -370
  85. package/dist/shared-QSYBHaMG.js +0 -12
  86. package/dist/types-jaRlW3D1.d.ts +0 -117
  87. package/dist/vite-Cmey8ODS.js +0 -1018
package/dist/vue.js CHANGED
@@ -1,34 +1,659 @@
1
- import { createAuthClient } from "better-auth/vue";
2
- import { computed } from "vue";
1
+ import { i as resolveAuthMountPath } from "./application-path-DuTpfGFj.js";
2
+ import { n as checkAbility, t as AbilityError } from "./ability-error-CqgBrBfR.js";
3
+ import { a as setRequestFetchResolver, i as setNuxtErrorFactory, n as setDefaultAuthBasePath, o as setSessionSeedResolver, r as setNuxtAppResolver, s as setSignOutHandler, t as authNuxtBridge } from "./nuxt-bridge-Cl988STZ.js";
4
+ import abilities from "#vitehub/auth/abilities";
5
+ import { computed, defineComponent, effectScope, getCurrentInstance, getCurrentScope, inject, onScopeDispose, onServerPrefetch, provide, shallowRef, watch } from "vue";
3
6
  //#region src/vue.ts
4
- const authClient = createAuthClient();
7
+ const LOAD = Symbol.for("vitehub.auth.client.load");
8
+ const ON_LOAD = Symbol.for("vitehub.auth.client.on-load");
9
+ const OPTIONS = Symbol.for("vitehub.auth.client.options");
10
+ const authClientKey = Symbol("vitehub.auth.client");
11
+ const signOutListeners = /* @__PURE__ */ new Set();
12
+ /** The state of a client hook, such as `useSession()`, before Better Auth's client has loaded. */
13
+ const pendingState = (refetch) => ({
14
+ data: null,
15
+ error: null,
16
+ isPending: true,
17
+ isRefetching: false,
18
+ refetch
19
+ });
20
+ /**
21
+ * Better Auth's Vue client with the same options, types, and calls, which loads `better-auth/vue` the first time it is
22
+ * used. Creating one costs nothing, so an app can create it up front and only pages that sign in pay for Better Auth.
23
+ * Calls such as `signIn.social()` wait for the load. Hooks such as `useSession()` return a ref at once that is
24
+ * pending until then. Every `useSession()` call of one client in one app returns the same ref. In Nuxt, a call in a
25
+ * component starts with the session that the server read for the request, so it is settled during server rendering and
26
+ * hydration. The browser then loads Better Auth and reads the session again only when the session can change: a call,
27
+ * `refetch()`, the tab shows again, the network comes back, another tab signs out or updates the user, or the session
28
+ * expires. Use `loadAuthClient()` for anything else, such as `$store`. Without `basePath`, it uses the same default
29
+ * as `authClient`: in Nuxt, the Auth Definition's `basePath` below `app.baseURL`.
30
+ * During Nuxt server rendering, a call such as `listSessions()` reaches the app in-process with the visitor's cookie.
31
+ */
32
+ const createAuthClient = (options) => createLazyAuthClient(() => withDefaultBasePath(options), () => options);
33
+ /**
34
+ * The options with ViteHub's default `basePath` when they set none: in Nuxt, the Auth Definition's `basePath` below
35
+ * `app.baseURL`. Read when Better Auth loads, after the Nuxt module set it.
36
+ */
37
+ function withDefaultBasePath(options) {
38
+ return {
39
+ basePath: authNuxtBridge.defaultBasePath ?? resolveAuthMountPath("/api/auth"),
40
+ ...options
41
+ };
42
+ }
43
+ /**
44
+ * The client of `createAuthClient()`. It runs `resolveOptions` when it loads Better Auth. `knownOptions` returns the
45
+ * options known before the load, such as `sessionOptions`, without loading anything.
46
+ */
47
+ function createLazyAuthClient(resolveOptions, knownOptions = () => void 0) {
48
+ let loaded;
49
+ let betterAuth;
50
+ const onLoad = /* @__PURE__ */ new Set();
51
+ const load = () => loaded ??= Promise.all([import("better-auth/vue"), resolveOptions()]).then(([module, options]) => {
52
+ betterAuth = module.createAuthClient(options);
53
+ for (const run of onLoad) run(betterAuth);
54
+ onLoad.clear();
55
+ return betterAuth;
56
+ }).catch((error) => {
57
+ loaded = void 0;
58
+ throw error;
59
+ });
60
+ const whenLoaded = (run) => {
61
+ if (betterAuth) run(betterAuth);
62
+ else onLoad.add(run);
63
+ };
64
+ const requestClients = /* @__PURE__ */ new WeakMap();
65
+ /**
66
+ * Better Auth's client for a call. On the server, during a request, it calls the app in-process with the visitor's
67
+ * cookie. A client with its own `baseURL` or `customFetchImpl` keeps them. Call it before the caller's first `await`,
68
+ * because only the caller's frame knows the request.
69
+ */
70
+ function loadForCall() {
71
+ const request = "window" in globalThis ? void 0 : authNuxtBridge.requestFetchResolver?.();
72
+ if (!request) return load();
73
+ let client = requestClients.get(request.request);
74
+ if (!client) {
75
+ client = Promise.all([import("better-auth/vue"), resolveOptions()]).then(([module, options]) => {
76
+ if (options?.baseURL || options?.fetchOptions?.customFetchImpl) return load();
77
+ const requestOptions = {
78
+ ...options,
79
+ baseURL: request.origin,
80
+ fetchOptions: {
81
+ ...options?.fetchOptions,
82
+ customFetchImpl: request.fetch
83
+ }
84
+ };
85
+ return module.createAuthClient(requestOptions);
86
+ }).catch((error) => {
87
+ requestClients.delete(request.request);
88
+ throw error;
89
+ });
90
+ requestClients.set(request.request, client);
91
+ }
92
+ return client;
93
+ }
94
+ function hook(name, args) {
95
+ if (name === "useSession" && typeof args[0] !== "function") return sessionStore(client).state;
96
+ const scope = getCurrentScope();
97
+ const nuxtApp = authNuxtBridge.nuxtAppResolver?.() || getCurrentInstance()?.appContext.config.globalProperties.$nuxt;
98
+ const real = (client) => Reflect.get(client, name)(...args);
99
+ if (typeof args[0] === "function") return load().then((client) => runIn(scope, () => nuxtApp ? nuxtApp.runWithContext(() => real(client)) : real(client)));
100
+ const refetch = async (...query) => {
101
+ await load();
102
+ const current = state.value;
103
+ return current === initial ? void 0 : current.refetch?.(...query);
104
+ };
105
+ const initial = pendingState(refetch);
106
+ const state = shallowRef(initial);
107
+ if (!("window" in globalThis)) return state;
108
+ load().then((loaded) => {
109
+ if (scope && !scope.active) return;
110
+ runIn(scope, () => watch(real(loaded), (value) => {
111
+ state.value = value;
112
+ }, { immediate: true }));
113
+ });
114
+ return state;
115
+ }
116
+ function call(path) {
117
+ return new Proxy(function() {}, {
118
+ get(_, key) {
119
+ if (key === LOAD && !path.length) return loadForCall;
120
+ if (key === ON_LOAD && !path.length) return whenLoaded;
121
+ if (key === OPTIONS && !path.length) return knownOptions();
122
+ if (typeof key !== "string" || key === "then" || key === "catch" || key === "finally") return void 0;
123
+ if (!path.length && /^use[A-Z]/.test(key)) return (...args) => hook(key, args);
124
+ return call([...path, key]);
125
+ },
126
+ async apply(_, __, args) {
127
+ const client = await loadForCall();
128
+ return path.reduce((node, key) => Reflect.get(Object(node), key), client)(...args);
129
+ }
130
+ });
131
+ }
132
+ const client = call([]);
133
+ return client;
134
+ }
135
+ function isPendingWithoutData(value) {
136
+ return typeof value === "object" && value !== null && Reflect.get(value, "isPending") === true && !Reflect.get(value, "data");
137
+ }
138
+ /** Run `run` in the scope the hook was called in, so its watchers stop with the component that called it. */
139
+ function runIn(scope, run) {
140
+ return scope ? scope.run(run) : run();
141
+ }
142
+ /** The owner of the stores in the browser: one page has one session per client. */
143
+ const browserOwner = {};
144
+ const stores = /* @__PURE__ */ new WeakMap();
145
+ /**
146
+ * The session store of `client` for the current app. The browser has one store per client. The server has one per
147
+ * request, through the request's Nuxt app or Vue app, so two requests never share a session. On the server, a call
148
+ * outside an app, such as at module scope, gets a store of its own.
149
+ */
150
+ function sessionStore(client) {
151
+ const browser = "window" in globalThis;
152
+ const app = browser ? void 0 : authNuxtBridge.nuxtAppResolver?.();
153
+ const instance = getCurrentInstance();
154
+ const read = !browser && Boolean(instance);
155
+ const owner = browser ? browserOwner : app ?? instance?.appContext.app;
156
+ if (!owner) return createSessionStore(client, void 0, read);
157
+ let byOwner = stores.get(client);
158
+ if (!byOwner) stores.set(client, byOwner = /* @__PURE__ */ new WeakMap());
159
+ let store = byOwner.get(owner);
160
+ if (!store) byOwner.set(owner, store = createSessionStore(client, app, read));
161
+ else store.seed(read);
162
+ store.hold(getCurrentScope());
163
+ const serverRead = read ? store.serverRead() : void 0;
164
+ if (serverRead) onServerPrefetch(() => serverRead);
165
+ return store;
166
+ }
167
+ function createSessionStore(client, app, initialRead) {
168
+ const browser = "window" in globalThis;
169
+ const scope = effectScope(true);
170
+ const settled = (data) => ({
171
+ data,
172
+ error: null,
173
+ isPending: false,
174
+ isRefetching: false,
175
+ refetch
176
+ });
177
+ const state = shallowRef(pendingState(refetch));
178
+ let seeded = false;
179
+ let reading;
180
+ let serverReading;
181
+ let generation = 0;
182
+ let atomGeneration = 0;
183
+ let atom;
184
+ let stopSignal;
185
+ let stopWaking;
186
+ let holders = 0;
187
+ async function refetch(query) {
188
+ await read(query);
189
+ }
190
+ /** Settles the state with the server's session. A promise of it, such as a read still in flight, is the read. */
191
+ function seed(read) {
192
+ if (seeded) return;
193
+ const value = authNuxtBridge.sessionSeedResolver?.(read);
194
+ if (value === void 0) return;
195
+ seeded = true;
196
+ if (!(value instanceof Promise)) {
197
+ if (state.value.isPending) state.value = settled(value);
198
+ return;
199
+ }
200
+ serverReading = reading ??= share(value.then((session) => {
201
+ if (session !== void 0 && state.value.isPending) state.value = settled(session);
202
+ return session ?? null;
203
+ }));
204
+ }
205
+ function serverRead() {
206
+ return !browser && state.value.isPending ? serverReading : void 0;
207
+ }
208
+ /** Makes `read` the read that callers share, until it ends or `clear()` runs. */
209
+ function share(read) {
210
+ const shared = read.finally(() => {
211
+ if (reading === shared) reading = void 0;
212
+ });
213
+ return shared;
214
+ }
215
+ /**
216
+ * Follows Better Auth's session atom with one watcher. It runs when Better Auth loads, before the first call of the
217
+ * client runs, so the session signal of that call, such as after `signOut()`, reaches the state.
218
+ */
219
+ function connect(loaded) {
220
+ if (atom) return atom;
221
+ stopWaking?.();
222
+ stopWaking = void 0;
223
+ stopSignal?.();
224
+ stopSignal = void 0;
225
+ const hydrateSession = Reflect.get(loaded, "hydrateSession");
226
+ if (seeded && state.value.data && typeof hydrateSession === "function") hydrateSession.call(loaded, state.value.data);
227
+ atom = scope.run(() => {
228
+ const ref = Reflect.get(loaded, "useSession")();
229
+ watch(ref, (value, old) => {
230
+ if (value.isRefetching && !old?.isRefetching) atomGeneration = generation;
231
+ if (atomGeneration !== generation) {
232
+ if (!value.isRefetching && value.data) clearAtom(loaded);
233
+ return;
234
+ }
235
+ if (!state.value.isPending && isPendingWithoutData(value)) return;
236
+ state.value = value;
237
+ }, {
238
+ immediate: true,
239
+ flush: "sync"
240
+ });
241
+ return ref;
242
+ });
243
+ return atom;
244
+ }
245
+ /**
246
+ * Waits for the session signal of a client that loaded before the store, such as one from `loadAuthClient()`, and then
247
+ * follows its session atom. Better Auth sends the signal after a call that changes the session, such as a sign-in.
248
+ * Waiting costs no read.
249
+ */
250
+ function followSignal(loaded) {
251
+ const signal = storeAtom(loaded, "$sessionSignal");
252
+ if (!signal) {
253
+ connect(loaded);
254
+ return;
255
+ }
256
+ stopSignal = signal.listen(() => void connect(loaded));
257
+ }
258
+ /** Loads Better Auth in the browser and follows its session atom. */
259
+ async function follow() {
260
+ return atom ?? connect(await loadAuthClient(client));
261
+ }
262
+ function hold(caller) {
263
+ if (!browser || atom || !seeded || state.value.isPending) return;
264
+ holders++;
265
+ stopWaking ??= wakeWhenSessionCanChange(Reflect.get(client, OPTIONS)?.sessionOptions, state.value.data, () => void follow());
266
+ if (caller) runIn(caller, () => onScopeDispose(() => {
267
+ if (--holders || !stopWaking) return;
268
+ stopWaking();
269
+ stopWaking = void 0;
270
+ }));
271
+ }
272
+ async function fetchSession(query) {
273
+ if (!browser) {
274
+ if (!state.value.isPending) return state.value.data;
275
+ const started = generation;
276
+ const session = await (app ? app.runWithContext(() => authNuxtBridge.sessionSeedResolver?.(true)) : authNuxtBridge.sessionSeedResolver?.(true));
277
+ if (started !== generation) return state.value.data;
278
+ if (session === void 0) return null;
279
+ state.value = settled(session);
280
+ return session;
281
+ }
282
+ const followed = await follow();
283
+ await followed.value.refetch(query);
284
+ if (followed.value.isRefetching) await settledAtom(followed);
285
+ return state.value.data ?? null;
286
+ }
287
+ function settledAtom(followed) {
288
+ return new Promise((resolve) => {
289
+ const stop = scope.run(() => watch(followed, (value) => {
290
+ if (value.isRefetching) return;
291
+ stop?.();
292
+ resolve();
293
+ }, { flush: "sync" }));
294
+ });
295
+ }
296
+ function read(query) {
297
+ if (query) return fetchSession(query);
298
+ return reading ??= share(fetchSession());
299
+ }
300
+ function clear(loaded) {
301
+ generation++;
302
+ reading = void 0;
303
+ clearAtom(loaded);
304
+ state.value = settled(null);
305
+ }
306
+ seed(initialRead);
307
+ if (browser) {
308
+ const whenLoaded = Reflect.get(client, ON_LOAD);
309
+ if (whenLoaded) whenLoaded(connect);
310
+ else if (seeded && !state.value.isPending) followSignal(client);
311
+ if (!seeded || state.value.isPending) follow();
312
+ }
313
+ return {
314
+ state,
315
+ read,
316
+ seed,
317
+ serverRead,
318
+ clear,
319
+ hold,
320
+ scope
321
+ };
322
+ }
323
+ /**
324
+ * An atom of Better Auth's `$store` of a loaded client, such as `session` or `$sessionSignal`. Better Auth answers
325
+ * `$store` and `atoms` with path proxies, and a missing atom with a function.
326
+ */
327
+ function storeAtom(loaded, name) {
328
+ const value = Reflect.get(Object(Reflect.get(Object(Reflect.get(loaded, "$store")), "atoms")), name);
329
+ return typeof value === "object" && value !== null ? value : void 0;
330
+ }
331
+ /** Sets Better Auth's session atom of `loaded` to no session, settled. */
332
+ function clearAtom(loaded) {
333
+ const session = storeAtom(loaded, "session");
334
+ session?.set({
335
+ ...session.get(),
336
+ data: null,
337
+ error: null,
338
+ isPending: false,
339
+ isRefetching: false
340
+ });
341
+ }
342
+ /** The longest delay that `setTimeout()` keeps. It runs a longer delay at once. */
343
+ const maxTimerDelay = 2 ** 31 - 1;
344
+ /** Better Auth's channel to other tabs: a tab writes this `localStorage` key when it signs out or updates the user or session. */
345
+ const sessionChannelKey = "better-auth.message";
346
+ /**
347
+ * Calls `wake` at the moments when Better Auth reads the session again: the tab shows again (unless
348
+ * `refetchOnWindowFocus` is `false`), the network comes back, another tab changes the session, `refetchInterval`
349
+ * passes, or the session expires. Like Better Auth, it waits while the browser is offline, unless `refetchWhenOffline`
350
+ * is `true`: Better Auth could not load then, and the `online` event wakes it later. Returns a function that removes
351
+ * the listeners.
352
+ */
353
+ function wakeWhenSessionCanChange(options, seed, wake) {
354
+ const stops = [];
355
+ const { document: page, navigator, window } = globalThis;
356
+ const wakeOnline = () => {
357
+ if (navigator?.onLine === false && options?.refetchWhenOffline !== true) return;
358
+ wake();
359
+ };
360
+ const listen = (target, type, when = () => true) => {
361
+ if (typeof target?.addEventListener !== "function") return;
362
+ const listener = (event) => when(event) && wakeOnline();
363
+ target.addEventListener(type, listener);
364
+ stops.push(() => target.removeEventListener(type, listener));
365
+ };
366
+ if (options?.refetchOnWindowFocus !== false) listen(page, "visibilitychange", () => page?.visibilityState === "visible");
367
+ listen(window, "online");
368
+ listen(window, "storage", (event) => Reflect.get(event, "key") === sessionChannelKey);
369
+ const session = typeof seed === "object" && seed !== null ? Reflect.get(seed, "session") : void 0;
370
+ const expiresAt = typeof session === "object" && session !== null ? Reflect.get(session, "expiresAt") : void 0;
371
+ const times = [];
372
+ if (expiresAt instanceof Date || typeof expiresAt === "string" || typeof expiresAt === "number") times.push(new Date(expiresAt).getTime());
373
+ if (session && options?.refetchInterval && options.refetchInterval > 0) times.push(Date.now() + options.refetchInterval * 1e3);
374
+ const at = Math.min(...times.filter(Number.isFinite));
375
+ if (Number.isFinite(at)) {
376
+ const timer = setTimeout(wakeOnline, Math.min(Math.max(at - Date.now(), 0), maxTimerDelay));
377
+ stops.push(() => clearTimeout(timer));
378
+ }
379
+ return () => {
380
+ for (const stop of stops) stop();
381
+ };
382
+ }
383
+ /**
384
+ * Better Auth's own Vue client behind one that `createAuthClient()` returned, once it has loaded. During Nuxt server
385
+ * rendering, it is the client of the current request.
386
+ */
387
+ async function loadAuthClient(client) {
388
+ const load = Reflect.get(client, LOAD);
389
+ return load ? await load() : client;
390
+ }
391
+ /**
392
+ * The options of the app's Auth client, such as Better Auth's client plugins. Export them from `app/auth.client.ts` in
393
+ * a Nuxt app, or from `auth.client.ts` in the Vite root, and the default client, `useUserSession()`, and the Nuxt page
394
+ * guard use them.
395
+ */
396
+ function defineAuthClient(options) {
397
+ return options;
398
+ }
399
+ /**
400
+ * The client that the composables and the Nuxt page guard share. On first use, it loads `better-auth/vue` and the app's
401
+ * `auth.client.ts` together, and the options of that file replace the defaults. In Nuxt, the default `basePath` is the
402
+ * Auth Definition's `basePath` below the `app.baseURL` of the page, also when `NUXT_APP_BASE_URL` sets it at runtime.
403
+ */
404
+ const authClient = createLazyAuthClient(async () => {
405
+ const { default: options } = await import("#vitehub/auth/client");
406
+ return withDefaultBasePath(options);
407
+ });
408
+ /** Provide the app's configured client to Auth composables and `<Can>` in descendant components. */
409
+ function provideAuthClient(client) {
410
+ provide(authClientKey, client);
411
+ }
5
412
  function useAuthClient() {
6
- return authClient;
413
+ const instance = getCurrentInstance();
414
+ const client = instance ? inject(authClientKey, void 0) : void 0;
415
+ const nuxtApp = authNuxtBridge.nuxtAppResolver?.() || instance?.appContext.config.globalProperties.$nuxt;
416
+ return client ?? nuxtApp?.$vitehubAuthClient ?? authClient;
417
+ }
418
+ /**
419
+ * The session of `client`. Every call for the same client in the same app returns the same ref, so a list of
420
+ * components that call it costs one watcher. In Nuxt, the page guard reads the session into the same ref.
421
+ */
422
+ function useSession(client = useAuthClient()) {
423
+ return sessionStore(client).state;
7
424
  }
8
- function useSession(client = authClient) {
9
- return client.useSession();
425
+ /**
426
+ * The current user and session of `client`, with sign-in and sign-out actions. Every call for the same client in the
427
+ * same app returns the same object, so a list of components that call it costs nothing more.
428
+ */
429
+ function useUserSession(client = useAuthClient()) {
430
+ const store = sessionStore(client);
431
+ return store.userSession ??= store.scope.run(() => createUserSession(client, store));
10
432
  }
11
- function useUserSession(client = authClient) {
12
- const state = client.useSession();
433
+ function createUserSession(client, store) {
434
+ const state = store.state;
435
+ const refresh = store.read;
13
436
  return {
437
+ client,
14
438
  data: computed(() => state.value.data),
15
439
  error: computed(() => state.value.error),
440
+ impersonatedBy: computed(() => {
441
+ const value = state.value.data?.session ? Reflect.get(state.value.data.session, "impersonatedBy") : void 0;
442
+ return typeof value === "string" && value ? value : null;
443
+ }),
16
444
  loggedIn: computed(() => Boolean(state.value.data?.session && state.value.data?.user)),
17
445
  pending: computed(() => state.value.isPending || state.value.isRefetching),
18
446
  ready: computed(() => !state.value.isPending),
19
- refresh: () => state.value.refetch(),
447
+ refresh,
20
448
  session: computed(() => state.value.data?.session ?? null),
21
449
  signIn: client.signIn,
22
- signOut: client.signOut,
450
+ signOut: (options, ...fetchOptions) => signOut(client, store, options, fetchOptions),
23
451
  signUp: client.signUp,
452
+ async stopImpersonating() {
453
+ await client.$fetch("/admin/stop-impersonating", {
454
+ method: "POST",
455
+ body: {},
456
+ throw: true
457
+ });
458
+ await refresh();
459
+ },
24
460
  user: computed(() => state.value.data?.user ?? null)
25
461
  };
26
462
  }
27
- function useSignIn() {
28
- return authClient.signIn;
463
+ /**
464
+ * Calls `listener` in the browser after each `signOut()` of `useUserSession()`, once the server ended the session and
465
+ * before the next page opens. `signOut()` waits for it. Use it to forget data of the person, such as `clearSync()`.
466
+ * Returns a function that stops it.
467
+ */
468
+ function onSignOut(listener) {
469
+ signOutListeners.add(listener);
470
+ return () => {
471
+ signOutListeners.delete(listener);
472
+ };
473
+ }
474
+ /** `value` when it is an object, else an empty one, to spread fetch options that a caller may leave out. */
475
+ function record(value) {
476
+ return typeof value === "object" && value !== null ? { ...value } : {};
477
+ }
478
+ async function signOut(client, store, options = {}, fetchOptions = []) {
479
+ const { redirectTo, fetchOptions: argumentFetchOptions, ...betterAuthOptions } = options;
480
+ const callerFetchOptions = {
481
+ ...record(fetchOptions[0]),
482
+ ...record(argumentFetchOptions)
483
+ };
484
+ const callerSuccess = callerFetchOptions.onSuccess;
485
+ let succeeded;
486
+ const merged = {
487
+ ...callerFetchOptions,
488
+ body: {
489
+ ...record(callerFetchOptions.body),
490
+ disableRedirect: true
491
+ },
492
+ onSuccess(context) {
493
+ succeeded = { context };
494
+ }
495
+ };
496
+ const result = await client.signOut({
497
+ ...betterAuthOptions,
498
+ disableRedirect: true,
499
+ fetchOptions: merged
500
+ });
501
+ const answer = typeof result === "object" && result !== null && "data" in result && "error" in result ? result : {
502
+ data: result,
503
+ error: null
504
+ };
505
+ if (answer.error) return result;
506
+ if (!("window" in globalThis)) {
507
+ if (typeof callerSuccess === "function" && succeeded) await callerSuccess(succeeded.context);
508
+ return result;
509
+ }
510
+ store.clear(await loadAuthClient(client));
511
+ const settled = await Promise.allSettled([...signOutListeners].map(async (listener) => listener()));
512
+ for (const failure of settled) if (failure.status === "rejected") console.error("[vitehub] An onSignOut() listener failed.", failure.reason);
513
+ if (typeof callerSuccess === "function" && succeeded) await callerSuccess(succeeded.context);
514
+ const location = globalThis.location;
515
+ const data = answer.data;
516
+ if (!options.disableRedirect && typeof data === "object" && data !== null) {
517
+ const providerPage = Reflect.get(data, "url");
518
+ if (typeof providerPage === "string" && /^https?:\/\//i.test(providerPage)) {
519
+ location?.assign(providerPage);
520
+ Reflect.set(data, "redirect", true);
521
+ return result;
522
+ }
523
+ }
524
+ if (authNuxtBridge.signOutHandler) await authNuxtBridge.signOutHandler(redirectTo);
525
+ else if (redirectTo) location?.assign(redirectTo);
526
+ return result;
527
+ }
528
+ /** The refusal of a rule for the visitor: `undefined` while the session is unknown, `null` when the rule allows. */
529
+ function abilityRefusal(state, name, args) {
530
+ if (state.isPending) return void 0;
531
+ return checkAbility(abilities, state.data?.user ?? null, name, args);
532
+ }
533
+ /**
534
+ * The user that `authorize()` checks. The server uses the session it read for the request. While Nuxt hydrates, the
535
+ * browser uses the same session, so it decides as the server did. Otherwise the browser asks the client of
536
+ * `useAbility()`, because a sign-in or sign-out in the tab makes the server's session old. In Nuxt, that is the client of
537
+ * the page guard, at the configured Auth `basePath` below `app.baseURL`.
538
+ */
539
+ async function authorizedUser(client, state) {
540
+ const known = !state.value.isPending;
541
+ if (!("window" in globalThis) || known && authNuxtBridge.nuxtAppResolver?.()?.isHydrating) return state.value.data?.user ?? null;
542
+ const { data } = await client.getSession();
543
+ return data?.user ?? null;
544
+ }
545
+ /**
546
+ * Checks the rules of `shared/abilities.ts` in the app, with the same rules the server runs. Read `can()` and
547
+ * `cannot()` in a template or a `computed()`, so they follow the session. Call `authorize()` in a page that the visitor
548
+ * must not see when the rule refuses.
549
+ *
550
+ * @example
551
+ * const { can, authorize } = useAbility()
552
+ * const editable = computed(() => post.value && can("posts.edit", post.value))
553
+ * // In a page, after the post loads:
554
+ * await authorize("posts.edit", loadedPost)
555
+ */
556
+ function useAbility(client = useAuthClient()) {
557
+ const state = useSession(client);
558
+ const allows = (name, args) => {
559
+ const refusal = abilityRefusal(state.value, name, args);
560
+ return refusal === void 0 ? void 0 : refusal === null;
561
+ };
562
+ return {
563
+ can: (name, ...args) => allows(name, args),
564
+ cannot: (name, ...args) => {
565
+ const allowed = allows(name, args);
566
+ return allowed === void 0 ? void 0 : !allowed;
567
+ },
568
+ authorize: async (name, ...args) => {
569
+ const refusal = checkAbility(abilities, await authorizedUser(client, state), name, args);
570
+ if (!refusal) return;
571
+ const error = new AbilityError(refusal);
572
+ throw authNuxtBridge.nuxtErrorFactory ? authNuxtBridge.nuxtErrorFactory({
573
+ ...error.toJSON(),
574
+ fatal: true
575
+ }) : error;
576
+ },
577
+ ready: computed(() => !state.value.isPending)
578
+ };
29
579
  }
30
- function useSignUp() {
31
- return authClient.signUp;
580
+ /** The runtime props of `<Can>` and `<Cannot>`. */
581
+ const abilityProps = {
582
+ do: {
583
+ type: String,
584
+ required: true
585
+ },
586
+ with: {
587
+ type: null,
588
+ default: void 0
589
+ },
590
+ args: {
591
+ type: Array,
592
+ default: void 0
593
+ },
594
+ pending: {
595
+ type: Boolean,
596
+ default: false
597
+ }
598
+ };
599
+ /** The refusal of the rule that the props name. It follows the session, and is `undefined` while `pending` is `true`. */
600
+ function usePropsRefusal(props) {
601
+ const state = useSession();
602
+ return computed(() => {
603
+ if (props.pending) return void 0;
604
+ const args = props.args ?? (props.with === void 0 ? [] : [props.with]);
605
+ return abilityRefusal(state.value, props.do, args);
606
+ });
32
607
  }
608
+ /**
609
+ * Shows its content when a rule from `shared/abilities.ts` allows the visitor, the `#denied` slot with the refusal when
610
+ * it refuses, and nothing while the session is unknown or `pending` is `true`.
611
+ *
612
+ * @example
613
+ * <Can do="posts.edit" :with="post">
614
+ * <button>Edit</button>
615
+ * <template #denied="{ code }">{{ code }}</template>
616
+ * </Can>
617
+ * <Can do="posts.move" :args="[from, to]">Move</Can>
618
+ */
619
+ const Can = defineComponent({
620
+ name: "Can",
621
+ props: abilityProps,
622
+ setup(props, { slots }) {
623
+ const refusal = usePropsRefusal(props);
624
+ return () => {
625
+ const value = refusal.value;
626
+ if (value === void 0) return null;
627
+ if (value === null) return slots.default?.();
628
+ return slots.denied?.({
629
+ code: value.code,
630
+ details: value.details
631
+ });
632
+ };
633
+ }
634
+ });
635
+ /**
636
+ * The mirror of `<Can>`: shows its content, with the refusal, only when a rule from `shared/abilities.ts` refuses the
637
+ * visitor. It shows nothing when the rule allows, while the session is unknown, or while `pending` is `true`.
638
+ *
639
+ * @example
640
+ * <Cannot do="billing.upgrade" v-slot="{ code, details }">
641
+ * <UpgradeHint :code="code" :limit="details.limit" />
642
+ * </Cannot>
643
+ */
644
+ const Cannot = defineComponent({
645
+ name: "Cannot",
646
+ props: abilityProps,
647
+ setup(props, { slots }) {
648
+ const refusal = usePropsRefusal(props);
649
+ return () => {
650
+ const value = refusal.value;
651
+ return value ? slots.default?.({
652
+ code: value.code,
653
+ details: value.details
654
+ }) : null;
655
+ };
656
+ }
657
+ });
33
658
  //#endregion
34
- export { authClient, createAuthClient, useAuthClient, useSession, useSignIn, useSignUp, useUserSession };
659
+ export { Can, Cannot, authClient, createAuthClient, defineAuthClient, loadAuthClient, onSignOut, provideAuthClient, setDefaultAuthBasePath, setNuxtAppResolver, setNuxtErrorFactory, setRequestFetchResolver, setSessionSeedResolver, setSignOutHandler, useAbility, useAuthClient, useSession, useUserSession };