@oxog/authkeeper 1.3.1 → 1.5.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 (53) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +152 -2
  3. package/dist/auth-source-CXqrhLDO.d.ts +37 -0
  4. package/dist/auth-source-rjMWiP1Q.d.cts +37 -0
  5. package/dist/{chunk-NZPSW4M7.cjs → chunk-47JWRVTL.cjs} +21 -29
  6. package/dist/chunk-47JWRVTL.cjs.map +1 -0
  7. package/dist/{chunk-XUTTHBMF.js → chunk-ANGR5HRJ.js} +12 -19
  8. package/dist/chunk-ANGR5HRJ.js.map +1 -0
  9. package/dist/chunk-DLCD3SBV.js +17 -0
  10. package/dist/chunk-DLCD3SBV.js.map +1 -0
  11. package/dist/chunk-LGZGECYE.cjs +96 -0
  12. package/dist/chunk-LGZGECYE.cjs.map +1 -0
  13. package/dist/chunk-UUQDRHGF.js +90 -0
  14. package/dist/chunk-UUQDRHGF.js.map +1 -0
  15. package/dist/chunk-XGKVBZSF.cjs +19 -0
  16. package/dist/chunk-XGKVBZSF.cjs.map +1 -0
  17. package/dist/index-C4pGS-TI.d.cts +488 -0
  18. package/dist/index-CQwGO-Wk.d.ts +488 -0
  19. package/dist/index.cjs +71 -60
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +9 -3
  22. package/dist/index.d.ts +9 -3
  23. package/dist/index.js +24 -12
  24. package/dist/index.js.map +1 -1
  25. package/dist/plugins/index.cjs +15 -14
  26. package/dist/plugins/index.d.cts +2 -1
  27. package/dist/plugins/index.d.ts +2 -1
  28. package/dist/plugins/index.js +2 -1
  29. package/dist/react/index.cjs +124 -3
  30. package/dist/react/index.cjs.map +1 -1
  31. package/dist/react/index.d.cts +136 -5
  32. package/dist/react/index.d.ts +136 -5
  33. package/dist/react/index.js +118 -3
  34. package/dist/react/index.js.map +1 -1
  35. package/dist/svelte/index.cjs +53 -3
  36. package/dist/svelte/index.cjs.map +1 -1
  37. package/dist/svelte/index.d.cts +54 -5
  38. package/dist/svelte/index.d.ts +54 -5
  39. package/dist/svelte/index.js +51 -3
  40. package/dist/svelte/index.js.map +1 -1
  41. package/dist/types-DMPBl-Ym.d.cts +421 -0
  42. package/dist/types-DMPBl-Ym.d.ts +421 -0
  43. package/dist/vue/index.cjs +75 -3
  44. package/dist/vue/index.cjs.map +1 -1
  45. package/dist/vue/index.d.cts +93 -5
  46. package/dist/vue/index.d.ts +93 -5
  47. package/dist/vue/index.js +70 -3
  48. package/dist/vue/index.js.map +1 -1
  49. package/package.json +14 -8
  50. package/dist/chunk-NZPSW4M7.cjs.map +0 -1
  51. package/dist/chunk-XUTTHBMF.js.map +0 -1
  52. package/dist/index-BakvZ2rC.d.cts +0 -906
  53. package/dist/index-BakvZ2rC.d.ts +0 -906
@@ -0,0 +1,421 @@
1
+ /**
2
+ * AuthKeeper Type Definitions
3
+ *
4
+ * Complete type system for the AuthKeeper library.
5
+ * All interfaces and types are exported for use by consumers.
6
+ */
7
+ /**
8
+ * Token set returned from authentication/refresh operations
9
+ */
10
+ interface TokenSet {
11
+ /** JWT access token */
12
+ accessToken: string;
13
+ /** Optional refresh token for obtaining new access tokens */
14
+ refreshToken?: string;
15
+ /** Token expiration in seconds from now */
16
+ expiresIn?: number;
17
+ /** Token expiration as Unix timestamp (seconds) */
18
+ expiresAt?: number;
19
+ /** Token type (default: 'Bearer') */
20
+ tokenType?: string;
21
+ }
22
+ /**
23
+ * Standard JWT payload with common claims
24
+ */
25
+ interface TokenPayload {
26
+ /** Subject - usually the user ID */
27
+ sub?: string;
28
+ /** Issuer - who created the token */
29
+ iss?: string;
30
+ /** Audience - who the token is intended for */
31
+ aud?: string | string[];
32
+ /** Expiration time (Unix timestamp in seconds) */
33
+ exp?: number;
34
+ /** Not before time (Unix timestamp in seconds) */
35
+ nbf?: number;
36
+ /** Issued at time (Unix timestamp in seconds) */
37
+ iat?: number;
38
+ /** JWT ID - unique identifier */
39
+ jti?: string;
40
+ /** User email address */
41
+ email?: string;
42
+ /** User display name */
43
+ name?: string;
44
+ /** User roles */
45
+ roles?: string[];
46
+ /** User permissions */
47
+ permissions?: string[];
48
+ /** OAuth2 scope */
49
+ scope?: string;
50
+ [key: string]: unknown;
51
+ }
52
+ /**
53
+ * JWT header information
54
+ */
55
+ interface TokenHeader {
56
+ /** Algorithm used to sign the token */
57
+ alg: string;
58
+ /** Token type (usually 'JWT') */
59
+ typ?: string;
60
+ /** Key ID used to sign the token */
61
+ kid?: string;
62
+ [key: string]: unknown;
63
+ }
64
+ /**
65
+ * Complete token information including decoded parts
66
+ */
67
+ interface TokenInfo {
68
+ /** Raw JWT string */
69
+ raw: string;
70
+ /** Decoded payload */
71
+ payload: TokenPayload;
72
+ /** Decoded header */
73
+ header: TokenHeader;
74
+ /** When the token expires (null if no expiry) */
75
+ expiresAt: Date | null;
76
+ /** Whether the token is expired */
77
+ isExpired: boolean;
78
+ /** Time until expiry in milliseconds (null if no expiry) */
79
+ expiresIn: number | null;
80
+ }
81
+ /**
82
+ * Stored token data with metadata
83
+ */
84
+ interface StoredTokens {
85
+ /** Access token */
86
+ accessToken: string;
87
+ /** Refresh token (null if not available) */
88
+ refreshToken: string | null;
89
+ /** Token type (e.g., 'Bearer') */
90
+ tokenType: string;
91
+ /** Expiration timestamp in milliseconds (null if no expiry) */
92
+ expiresAt: number | null;
93
+ /** When tokens were set (timestamp in milliseconds) */
94
+ setAt: number;
95
+ /** Number of times tokens have been refreshed */
96
+ refreshCount: number;
97
+ }
98
+ /**
99
+ * Error codes for authentication errors
100
+ */
101
+ type AuthErrorCode = 'TOKEN_EXPIRED' | 'TOKEN_INVALID' | 'TOKEN_DECODE_FAILED' | 'REFRESH_FAILED' | 'REFRESH_TOKEN_MISSING' | 'STORAGE_ERROR' | 'NETWORK_ERROR' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'OAUTH_ERROR' | 'PKCE_ERROR' | 'CALLBACK_ERROR' | 'CONFIG_ERROR';
102
+ /**
103
+ * Options for creating an AuthError
104
+ */
105
+ interface AuthErrorOptions {
106
+ /** Additional context about the error */
107
+ context?: Record<string, unknown>;
108
+ /** Original error that caused this error */
109
+ cause?: Error;
110
+ }
111
+ /**
112
+ * Custom error class for authentication errors
113
+ */
114
+ declare class AuthError extends Error {
115
+ /** Error code identifying the type of error */
116
+ code: AuthErrorCode;
117
+ /** Additional context about the error */
118
+ context?: Record<string, unknown>;
119
+ /** Original error that caused this error */
120
+ cause?: Error;
121
+ constructor(code: AuthErrorCode, message: string, options?: AuthErrorOptions);
122
+ }
123
+ /**
124
+ * All possible event types
125
+ */
126
+ type EventType = 'login' | 'logout' | 'refresh' | 'expired' | 'error' | 'storage-change' | 'tab-sync';
127
+ /**
128
+ * Login event - fired when user logs in
129
+ */
130
+ interface LoginEvent {
131
+ type: 'login';
132
+ tokens: TokenSet;
133
+ timestamp: number;
134
+ }
135
+ /**
136
+ * Logout event - fired when user logs out
137
+ */
138
+ interface LogoutEvent {
139
+ type: 'logout';
140
+ reason: 'manual' | 'expired' | 'error' | 'tab-sync';
141
+ timestamp: number;
142
+ }
143
+ /**
144
+ * Refresh event - fired when tokens are refreshed
145
+ */
146
+ interface RefreshEvent {
147
+ type: 'refresh';
148
+ tokens: TokenSet;
149
+ previousExpiresAt: Date | null;
150
+ newExpiresAt: Date | null;
151
+ timestamp: number;
152
+ }
153
+ /**
154
+ * Expired event - fired when token expires
155
+ */
156
+ interface ExpiredEvent {
157
+ type: 'expired';
158
+ expiredAt: Date;
159
+ timestamp: number;
160
+ }
161
+ /**
162
+ * Error event - fired when an error occurs
163
+ */
164
+ interface ErrorEvent {
165
+ type: 'error';
166
+ error: AuthError;
167
+ context: 'refresh' | 'storage' | 'decode' | 'network' | 'plugin';
168
+ timestamp: number;
169
+ }
170
+ /**
171
+ * Storage change event - fired when storage changes
172
+ */
173
+ interface StorageChangeEvent {
174
+ type: 'storage-change';
175
+ key: string;
176
+ oldValue: string | null;
177
+ newValue: string | null;
178
+ timestamp: number;
179
+ }
180
+ /**
181
+ * Tab sync event - fired when syncing across tabs
182
+ */
183
+ interface TabSyncEvent {
184
+ type: 'tab-sync';
185
+ action: 'login' | 'logout' | 'refresh';
186
+ sourceTabId: string;
187
+ timestamp: number;
188
+ }
189
+ /**
190
+ * Union of all event types
191
+ */
192
+ type AuthEvent = LoginEvent | LogoutEvent | RefreshEvent | ExpiredEvent | ErrorEvent | StorageChangeEvent | TabSyncEvent;
193
+ /**
194
+ * Event handler function type
195
+ */
196
+ type EventHandler<E extends EventType> = (event: Extract<AuthEvent, {
197
+ type: E;
198
+ }>) => void;
199
+ /**
200
+ * Unsubscribe function returned from event handlers
201
+ */
202
+ type Unsubscribe = () => void;
203
+ /**
204
+ * Storage adapter interface for token persistence
205
+ */
206
+ interface StorageAdapter {
207
+ /** Get value by key */
208
+ get(key: string): string | null;
209
+ /** Set value by key */
210
+ set(key: string, value: string): void;
211
+ /** Remove value by key */
212
+ remove(key: string): void;
213
+ /** Clear all values */
214
+ clear(): void;
215
+ }
216
+ /**
217
+ * Built-in storage types
218
+ */
219
+ type StorageType = 'memory' | 'localStorage' | 'sessionStorage' | 'cookie';
220
+ /**
221
+ * Plugin interface for extending AuthKeeper
222
+ */
223
+ interface Plugin {
224
+ /** Unique plugin name */
225
+ name: string;
226
+ /** Plugin version */
227
+ version: string;
228
+ /** Plugin type */
229
+ type: 'core' | 'optional';
230
+ /** Install plugin and return API */
231
+ install(kernel: AuthKeeper): any;
232
+ /** Uninstall plugin and cleanup */
233
+ uninstall?(): void | Promise<void>;
234
+ /** Reserved lifecycle hooks; not invoked by the kernel yet */
235
+ hooks?: {
236
+ /** Called before tokens are set */
237
+ beforeSetTokens?: (tokens: TokenSet) => TokenSet | false;
238
+ /** Called after tokens are set */
239
+ afterSetTokens?: (tokens: TokenSet) => void;
240
+ /** Called before refresh */
241
+ beforeRefresh?: () => boolean;
242
+ /** Called after refresh */
243
+ afterRefresh?: (tokens: TokenSet) => void;
244
+ /** Called before logout */
245
+ beforeLogout?: () => boolean;
246
+ /** Called after logout */
247
+ afterLogout?: () => void;
248
+ /** Called when token expires */
249
+ onExpired?: () => void;
250
+ /** Called on error */
251
+ onError?: (error: AuthError) => void;
252
+ /** Called before request */
253
+ beforeRequest?: (request: Request) => Request;
254
+ /** Called after response */
255
+ afterResponse?: (response: Response) => Response;
256
+ };
257
+ /** Plugin API exposed to consumers */
258
+ api?: Record<string, unknown>;
259
+ }
260
+ /**
261
+ * Plugin information
262
+ */
263
+ interface PluginInfo {
264
+ name: string;
265
+ version: string;
266
+ type: 'core' | 'optional';
267
+ enabled: boolean;
268
+ }
269
+ /**
270
+ * Refresh token function type
271
+ */
272
+ type RefreshTokenFn = (refreshToken: string) => Promise<TokenSet>;
273
+ /**
274
+ * Kernel configuration options
275
+ */
276
+ interface KernelOptions {
277
+ /**
278
+ * Where tokens are persisted (default: 'memory', i.e. not persisted).
279
+ * 'localStorage' / 'sessionStorage' / 'cookie' fall back to memory where
280
+ * unavailable. Persistent storage is readable by any script on the page.
281
+ */
282
+ storage?: StorageType | StorageAdapter;
283
+ /** Function to refresh tokens */
284
+ refreshToken: RefreshTokenFn;
285
+ /** Enable automatic token refresh (default: true) */
286
+ autoRefresh?: boolean;
287
+ /** Seconds before expiry to refresh (default: 60) */
288
+ refreshThreshold?: number;
289
+ /**
290
+ * Reserved for multi-tab sync; not implemented yet (currently a no-op).
291
+ * `getOptions().syncTabs` always reports `false`.
292
+ */
293
+ syncTabs?: boolean;
294
+ /** Error handler */
295
+ onError?: (error: AuthError) => void;
296
+ /** Additional plugins to install */
297
+ plugins?: Plugin[];
298
+ }
299
+ /**
300
+ * Logout options
301
+ */
302
+ interface LogoutOptions {
303
+ /** Reserved for multi-tab logout; not implemented yet (currently a no-op) */
304
+ allTabs?: boolean;
305
+ /** Redirect URL after logout */
306
+ redirect?: string;
307
+ }
308
+ /**
309
+ * Authenticated fetch function
310
+ */
311
+ type AuthFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
312
+ /**
313
+ * Fetch interceptor options
314
+ */
315
+ interface FetchInterceptorOptions {
316
+ /** Header name for auth token (default: 'Authorization') */
317
+ headerName?: string;
318
+ /** Header prefix (default: 'Bearer ') */
319
+ headerPrefix?: string;
320
+ /** Only include auth header for these URLs */
321
+ includeUrls?: (string | RegExp)[];
322
+ /** Exclude auth header for these URLs */
323
+ excludeUrls?: (string | RegExp)[];
324
+ /** Callback on 401 response */
325
+ onUnauthorized?: (response: Response) => void;
326
+ /** Retry on 401 after refresh (default: true) */
327
+ retry401?: boolean;
328
+ /** Max retries (default: 1) */
329
+ maxRetries?: number;
330
+ }
331
+ /**
332
+ * OAuth2 login options
333
+ */
334
+ interface LoginOptions {
335
+ /** OAuth2 scope */
336
+ scope?: string;
337
+ /** OAuth2 state parameter */
338
+ state?: string;
339
+ /** OAuth2 prompt parameter */
340
+ prompt?: 'none' | 'login' | 'consent' | 'select_account';
341
+ /** Login hint (email, etc.) */
342
+ loginHint?: string;
343
+ /** Additional OAuth2 parameters */
344
+ extraParams?: Record<string, string>;
345
+ }
346
+ /**
347
+ * User info from OIDC userinfo endpoint
348
+ */
349
+ interface UserInfo {
350
+ sub: string;
351
+ email?: string;
352
+ name?: string;
353
+ picture?: string;
354
+ [key: string]: unknown;
355
+ }
356
+ /**
357
+ * Main AuthKeeper interface - the kernel
358
+ */
359
+ interface AuthKeeper {
360
+ /** Set authentication tokens */
361
+ setTokens(tokens: TokenSet): void;
362
+ /** Get access token */
363
+ getAccessToken(): string | null;
364
+ /** Get refresh token */
365
+ getRefreshToken(): string | null;
366
+ /** Clear all tokens */
367
+ clearTokens(): void;
368
+ /** Check if user is authenticated */
369
+ isAuthenticated(): boolean;
370
+ /** Check if token is expired */
371
+ isExpired(): boolean;
372
+ /** Get token expiration date */
373
+ getExpiresAt(): Date | null;
374
+ /** Get time until expiry in milliseconds */
375
+ getTimeUntilExpiry(): number | null;
376
+ /** Decode token payload */
377
+ decode<T = TokenPayload>(): T | null;
378
+ /** Get specific claim from token */
379
+ getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined;
380
+ /** Get multiple claims from token */
381
+ getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K>;
382
+ /** Manually refresh tokens */
383
+ refresh(): Promise<TokenSet>;
384
+ /** Schedule automatic refresh */
385
+ scheduleRefresh(): void;
386
+ /** Cancel scheduled refresh */
387
+ cancelScheduledRefresh(): void;
388
+ /** Logout user */
389
+ logout(options?: LogoutOptions): void;
390
+ /** Create authenticated fetch function */
391
+ createFetch(options?: FetchInterceptorOptions): AuthFetch;
392
+ /** Wrap global fetch with auth */
393
+ wrapFetch(fetch: typeof globalThis.fetch): void;
394
+ /**
395
+ * Register and install a plugin. Rejects if installation fails; the failure
396
+ * is also emitted as an 'error' event with context 'plugin'.
397
+ */
398
+ register(plugin: Plugin): Promise<void>;
399
+ /** Unregister a plugin */
400
+ unregister(pluginName: string): Promise<void>;
401
+ /** Get plugin by name */
402
+ getPlugin<P extends Plugin>(name: string): P | undefined;
403
+ /** List all plugins */
404
+ listPlugins(): PluginInfo[];
405
+ /** Emit an event */
406
+ emit(event: AuthEvent): void;
407
+ /** Subscribe to events */
408
+ on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe;
409
+ /** Unsubscribe from events */
410
+ off<E extends EventType>(eventType: E, handler: EventHandler<E>): void;
411
+ /** Initialize kernel */
412
+ init(): Promise<void>;
413
+ /** Destroy kernel and cleanup */
414
+ destroy(): void;
415
+ /** Update configuration */
416
+ configure(options: Partial<KernelOptions>): void;
417
+ /** Get current configuration */
418
+ getOptions(): KernelOptions;
419
+ }
420
+
421
+ export { type AuthFetch as A, type EventType as E, type FetchInterceptorOptions as F, type KernelOptions as K, type LogoutOptions as L, type Plugin as P, type RefreshEvent as R, type StorageAdapter as S, type TokenSet as T, type Unsubscribe as U, type TokenPayload as a, type AuthKeeper as b, AuthError as c, type EventHandler as d, type AuthEvent as e, type PluginInfo as f, type TokenHeader as g, type AuthErrorCode as h, type AuthErrorOptions as i, type ErrorEvent as j, type ExpiredEvent as k, type LoginEvent as l, type LoginOptions as m, type LogoutEvent as n, type RefreshTokenFn as o, type StorageChangeEvent as p, type StorageType as q, type StoredTokens as r, type TabSyncEvent as s, type TokenInfo as t, type UserInfo as u };
@@ -1,8 +1,80 @@
1
1
  'use strict';
2
2
 
3
- // src/adapters/vue/index.ts
4
- var __VUE_ADAPTER_PLACEHOLDER__ = true;
3
+ var chunkXGKVBZSF_cjs = require('../chunk-XGKVBZSF.cjs');
4
+ var chunkLGZGECYE_cjs = require('../chunk-LGZGECYE.cjs');
5
+ var vue = require('vue');
5
6
 
6
- exports.__VUE_ADAPTER_PLACEHOLDER__ = __VUE_ADAPTER_PLACEHOLDER__;
7
+ var AUTH_KEY = /* @__PURE__ */ Symbol("authkeeper");
8
+ function provideAuth(auth) {
9
+ vue.provide(AUTH_KEY, auth);
10
+ }
11
+ function injectAuth() {
12
+ const auth = vue.inject(AUTH_KEY, null);
13
+ if (!auth) {
14
+ throw new chunkXGKVBZSF_cjs.AuthError(
15
+ "CONFIG_ERROR",
16
+ "No AuthKeeper provided: call provideAuth(auth) in an ancestor"
17
+ );
18
+ }
19
+ return auth;
20
+ }
21
+ function authKeeperPlugin(auth) {
22
+ return {
23
+ install(app) {
24
+ app.provide(AUTH_KEY, auth);
25
+ }
26
+ };
27
+ }
28
+ function useSnapshot(auth, read) {
29
+ const instance = auth ?? injectAuth();
30
+ const source = chunkLGZGECYE_cjs.createAuthSource(instance);
31
+ const state = vue.shallowRef(read(source));
32
+ const stop = source.subscribe(() => {
33
+ state.value = read(source);
34
+ });
35
+ if (vue.getCurrentScope()) vue.onScopeDispose(stop);
36
+ return { instance, state, stop };
37
+ }
38
+ function useAuth(auth) {
39
+ const { instance, state, stop } = useSnapshot(auth, (source) => source.getState());
40
+ return {
41
+ isAuthenticated: vue.computed(() => state.value.isAuthenticated),
42
+ accessToken: vue.computed(() => state.value.accessToken),
43
+ user: vue.computed(() => state.value.user),
44
+ expiresAt: vue.computed(() => state.value.expiresAt),
45
+ error: vue.computed(() => state.value.error),
46
+ setTokens: (tokens) => instance.setTokens(tokens),
47
+ logout: (options) => instance.logout(options),
48
+ refresh: () => instance.refresh(),
49
+ stop
50
+ };
51
+ }
52
+ function useToken(auth) {
53
+ const { instance, state, stop } = useSnapshot(auth, (source) => source.getTokenState());
54
+ return {
55
+ accessToken: vue.computed(() => state.value.accessToken),
56
+ refreshToken: vue.computed(() => state.value.refreshToken),
57
+ isExpired: vue.computed(() => state.value.isExpired),
58
+ expiresAt: vue.computed(() => state.value.expiresAt),
59
+ authFetch: instance.createFetch(),
60
+ stop
61
+ };
62
+ }
63
+ function useUser(auth) {
64
+ const { state, stop } = useSnapshot(auth, (source) => source.getState().user);
65
+ return {
66
+ user: vue.computed(() => state.value),
67
+ claims: vue.computed(() => state.value ?? chunkLGZGECYE_cjs.NO_CLAIMS),
68
+ getClaim: (key) => chunkLGZGECYE_cjs.readClaim(state.value, key),
69
+ stop
70
+ };
71
+ }
72
+
73
+ exports.authKeeperPlugin = authKeeperPlugin;
74
+ exports.injectAuth = injectAuth;
75
+ exports.provideAuth = provideAuth;
76
+ exports.useAuth = useAuth;
77
+ exports.useToken = useToken;
78
+ exports.useUser = useUser;
7
79
  //# sourceMappingURL=index.cjs.map
8
80
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/vue/index.ts"],"names":[],"mappings":";;;AAQO,IAAM,2BAAA,GAA8B","file":"index.cjs","sourcesContent":["/**\n * Vue Adapter\n *\n * Vue composables for AuthKeeper.\n * Will be implemented in Phase 8.\n */\n\n// Placeholder export to prevent build errors\nexport const __VUE_ADAPTER_PLACEHOLDER__ = true\n"]}
1
+ {"version":3,"sources":["../../src/adapters/vue/use-auth.ts","../../src/adapters/vue/use-token.ts"],"names":["provide","inject","AuthError","createAuthSource","shallowRef","getCurrentScope","onScopeDispose","computed","NO_CLAIMS","readClaim"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AI,WAAA,CAAY,IAAA,EAAM,CAAC,MAAA,KAAW,MAAA,CAAO,QAAA,EAAS,CAAE,IAAI,CAAA;AAC5E,EAAA,OAAO;AAAA,IACL,IAAA,EAAMA,YAAAA,CAAS,MAAM,KAAA,CAAM,KAAK,CAAA;AAAA,IAChC,MAAA,EAAQA,YAAAA,CAAS,MAAM,KAAA,CAAM,SAASC,2BAAS,CAAA;AAAA,IAC/C,UAAU,CAAC,GAAA,KAAQC,2BAAA,CAAU,KAAA,CAAM,OAAO,GAAG,CAAA;AAAA,IAC7C;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Vue 3 bindings: provideAuth() / injectAuth() and the useAuth() composable\n */\n\nimport {\n computed,\n getCurrentScope,\n inject,\n onScopeDispose,\n provide,\n shallowRef,\n type App,\n type ComputedRef,\n type InjectionKey,\n type ShallowRef,\n} from 'vue'\nimport {\n AuthError,\n type AuthKeeper,\n type LogoutOptions,\n type TokenPayload,\n type TokenSet,\n} from '../../types'\nimport { createAuthSource, type AuthSource } from '../auth-source'\n\nconst AUTH_KEY: InjectionKey<AuthKeeper> = Symbol('authkeeper')\n\n/**\n * Provide an AuthKeeper instance to the component's descendants\n * (call in `setup()`; for the whole app use `app.use(authKeeperPlugin(auth))`)\n */\nexport function provideAuth(auth: AuthKeeper): void {\n provide(AUTH_KEY, auth)\n}\n\n/**\n * The provided AuthKeeper instance (call in `setup()`)\n * @throws {AuthError} CONFIG_ERROR when none was provided\n */\nexport function injectAuth(): AuthKeeper {\n const auth = inject(AUTH_KEY, null)\n if (!auth) {\n throw new AuthError(\n 'CONFIG_ERROR',\n 'No AuthKeeper provided: call provideAuth(auth) in an ancestor',\n )\n }\n return auth\n}\n\n/**\n * Vue plugin: `app.use(authKeeperPlugin(auth))` provides the instance app-wide\n */\nexport function authKeeperPlugin(auth: AuthKeeper): { install(app: App): void } {\n return {\n install(app: App) {\n app.provide(AUTH_KEY, auth)\n },\n }\n}\n\n/**\n * A shallow ref of `read(source)`, updated while the calling component (or\n * effect scope) lives. It only triggers when the snapshot changes.\n * @internal\n */\nexport function useSnapshot<T>(\n auth: AuthKeeper | undefined,\n read: (source: AuthSource) => T,\n): { instance: AuthKeeper; state: Readonly<ShallowRef<T>>; stop: () => void } {\n const instance = auth ?? injectAuth()\n const source = createAuthSource(instance)\n const state = shallowRef(read(source))\n const stop = source.subscribe(() => {\n state.value = read(source)\n })\n if (getCurrentScope()) onScopeDispose(stop)\n return { instance, state, stop }\n}\n\n/**\n * useAuth() return value: read-only refs plus actions\n */\nexport interface UseAuthReturn {\n isAuthenticated: ComputedRef<boolean>\n accessToken: ComputedRef<string | null>\n user: ComputedRef<TokenPayload | null>\n expiresAt: ComputedRef<Date | null>\n error: ComputedRef<AuthError | null>\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive auth state. Updates after login, logout, refresh and error events\n * and when the access token expires; stops when the calling component (or\n * effect scope) is disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useAuth(auth?: AuthKeeper): UseAuthReturn {\n const { instance, state, stop } = useSnapshot(auth, (source) => source.getState())\n return {\n isAuthenticated: computed(() => state.value.isAuthenticated),\n accessToken: computed(() => state.value.accessToken),\n user: computed(() => state.value.user),\n expiresAt: computed(() => state.value.expiresAt),\n error: computed(() => state.value.error),\n setTokens: (tokens) => instance.setTokens(tokens),\n logout: (options) => instance.logout(options),\n refresh: () => instance.refresh(),\n stop,\n }\n}\n","/**\n * Vue 3 bindings: the useToken() and useUser() composables\n */\n\nimport { computed, type ComputedRef } from 'vue'\nimport type { AuthFetch, AuthKeeper, TokenPayload } from '../../types'\nimport { NO_CLAIMS, readClaim } from '../auth-source'\nimport { useSnapshot } from './use-auth'\n\n/**\n * useToken() return value: read-only refs plus an authenticated fetch\n */\nexport interface UseTokenReturn {\n accessToken: ComputedRef<string | null>\n /** Null when none is stored (e.g. an httpOnly cookie) */\n refreshToken: ComputedRef<string | null>\n /** An access token is set but has expired */\n isExpired: ComputedRef<boolean>\n expiresAt: ComputedRef<Date | null>\n /** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */\n authFetch: AuthFetch\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive tokens. Update when a token or the expiry changes (login, refresh,\n * logout, expiry); stop when the calling component (or effect scope) is\n * disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useToken(auth?: AuthKeeper): UseTokenReturn {\n const { instance, state, stop } = useSnapshot(auth, (source) => source.getTokenState())\n return {\n accessToken: computed(() => state.value.accessToken),\n refreshToken: computed(() => state.value.refreshToken),\n isExpired: computed(() => state.value.isExpired),\n expiresAt: computed(() => state.value.expiresAt),\n authFetch: instance.createFetch(),\n stop,\n }\n}\n\n/**\n * useUser() return value\n */\nexport interface UseUserReturn {\n /** Decoded access token payload (null when signed out or for opaque tokens) */\n user: ComputedRef<TokenPayload | null>\n /** The payload's claims (empty when there is no user) */\n claims: ComputedRef<TokenPayload>\n /** One claim of the current payload (reactive inside computed / templates) */\n getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined\n /** Stop updating (done automatically when the component / effect scope is disposed) */\n stop: () => void\n}\n\n/**\n * Reactive decoded access token payload. Updates when the access token\n * changes; stops when the calling component (or effect scope) is disposed.\n *\n * @param auth - Instance to use (default: the provided one)\n */\nexport function useUser(auth?: AuthKeeper): UseUserReturn {\n const { state, stop } = useSnapshot(auth, (source) => source.getState().user)\n return {\n user: computed(() => state.value),\n claims: computed(() => state.value ?? NO_CLAIMS),\n getClaim: (key) => readClaim(state.value, key),\n stop,\n }\n}\n"]}
@@ -1,9 +1,97 @@
1
+ import { ComputedRef, App } from 'vue';
2
+ import { a as TokenPayload, c as AuthError, T as TokenSet, L as LogoutOptions, b as AuthKeeper, A as AuthFetch } from '../types-DMPBl-Ym.cjs';
3
+ export { A as AuthState } from '../auth-source-rjMWiP1Q.cjs';
4
+
5
+ /**
6
+ * Vue 3 bindings: provideAuth() / injectAuth() and the useAuth() composable
7
+ */
8
+
9
+ /**
10
+ * Provide an AuthKeeper instance to the component's descendants
11
+ * (call in `setup()`; for the whole app use `app.use(authKeeperPlugin(auth))`)
12
+ */
13
+ declare function provideAuth(auth: AuthKeeper): void;
14
+ /**
15
+ * The provided AuthKeeper instance (call in `setup()`)
16
+ * @throws {AuthError} CONFIG_ERROR when none was provided
17
+ */
18
+ declare function injectAuth(): AuthKeeper;
19
+ /**
20
+ * Vue plugin: `app.use(authKeeperPlugin(auth))` provides the instance app-wide
21
+ */
22
+ declare function authKeeperPlugin(auth: AuthKeeper): {
23
+ install(app: App): void;
24
+ };
25
+ /**
26
+ * useAuth() return value: read-only refs plus actions
27
+ */
28
+ interface UseAuthReturn {
29
+ isAuthenticated: ComputedRef<boolean>;
30
+ accessToken: ComputedRef<string | null>;
31
+ user: ComputedRef<TokenPayload | null>;
32
+ expiresAt: ComputedRef<Date | null>;
33
+ error: ComputedRef<AuthError | null>;
34
+ setTokens: (tokens: TokenSet) => void;
35
+ logout: (options?: LogoutOptions) => void;
36
+ refresh: () => Promise<TokenSet>;
37
+ /** Stop updating (done automatically when the component / effect scope is disposed) */
38
+ stop: () => void;
39
+ }
40
+ /**
41
+ * Reactive auth state. Updates after login, logout, refresh and error events
42
+ * and when the access token expires; stops when the calling component (or
43
+ * effect scope) is disposed.
44
+ *
45
+ * @param auth - Instance to use (default: the provided one)
46
+ */
47
+ declare function useAuth(auth?: AuthKeeper): UseAuthReturn;
48
+
49
+ /**
50
+ * Vue 3 bindings: the useToken() and useUser() composables
51
+ */
52
+
53
+ /**
54
+ * useToken() return value: read-only refs plus an authenticated fetch
55
+ */
56
+ interface UseTokenReturn {
57
+ accessToken: ComputedRef<string | null>;
58
+ /** Null when none is stored (e.g. an httpOnly cookie) */
59
+ refreshToken: ComputedRef<string | null>;
60
+ /** An access token is set but has expired */
61
+ isExpired: ComputedRef<boolean>;
62
+ expiresAt: ComputedRef<Date | null>;
63
+ /** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */
64
+ authFetch: AuthFetch;
65
+ /** Stop updating (done automatically when the component / effect scope is disposed) */
66
+ stop: () => void;
67
+ }
68
+ /**
69
+ * Reactive tokens. Update when a token or the expiry changes (login, refresh,
70
+ * logout, expiry); stop when the calling component (or effect scope) is
71
+ * disposed.
72
+ *
73
+ * @param auth - Instance to use (default: the provided one)
74
+ */
75
+ declare function useToken(auth?: AuthKeeper): UseTokenReturn;
76
+ /**
77
+ * useUser() return value
78
+ */
79
+ interface UseUserReturn {
80
+ /** Decoded access token payload (null when signed out or for opaque tokens) */
81
+ user: ComputedRef<TokenPayload | null>;
82
+ /** The payload's claims (empty when there is no user) */
83
+ claims: ComputedRef<TokenPayload>;
84
+ /** One claim of the current payload (reactive inside computed / templates) */
85
+ getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined;
86
+ /** Stop updating (done automatically when the component / effect scope is disposed) */
87
+ stop: () => void;
88
+ }
1
89
  /**
2
- * Vue Adapter
90
+ * Reactive decoded access token payload. Updates when the access token
91
+ * changes; stops when the calling component (or effect scope) is disposed.
3
92
  *
4
- * Vue composables for AuthKeeper.
5
- * Will be implemented in Phase 8.
93
+ * @param auth - Instance to use (default: the provided one)
6
94
  */
7
- declare const __VUE_ADAPTER_PLACEHOLDER__ = true;
95
+ declare function useUser(auth?: AuthKeeper): UseUserReturn;
8
96
 
9
- export { __VUE_ADAPTER_PLACEHOLDER__ };
97
+ export { type UseAuthReturn, type UseTokenReturn, type UseUserReturn, authKeeperPlugin, injectAuth, provideAuth, useAuth, useToken, useUser };