@docyrus/signin 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,679 @@
1
+ import { createContext, useState, useRef, useEffect, useMemo, useContext } from 'react';
2
+ import { BrowserOAuth2TokenStorage, OAuth2Client, RestApiClient } from '@docyrus/api-client';
3
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
4
+
5
+ // src/components/docyrus-auth-provider.tsx
6
+
7
+ // src/constants.ts
8
+ var DEFAULT_API_URL = "https://alpha-api.docyrus.com";
9
+ var DEFAULT_OAUTH_SCOPES = [
10
+ "offline_access",
11
+ "Read.All",
12
+ "Users.Read",
13
+ "Users.Read.All",
14
+ "DS.Read.All"
15
+ ];
16
+ var DEFAULT_CALLBACK_PATH = "/auth/callback";
17
+ var DEFAULT_ALLOWED_HOST_PATTERN = /^https:\/\/[^/]+\.docyrus\.app$/;
18
+ var REDIRECT_RETURN_KEY = "docyrus_auth_return_url";
19
+ var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
20
+ var IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 1e4;
21
+ var DEFAULT_SSR_COOKIE_KEY = "docyrus-token";
22
+
23
+ // src/core/auth-detector.ts
24
+ function detectAuthMode(allowedOrigins, allowedPattern) {
25
+ if (typeof window === "undefined") return "standalone";
26
+ let isInIframe = false;
27
+ try {
28
+ isInIframe = window.self !== window.top;
29
+ } catch {
30
+ isInIframe = true;
31
+ }
32
+ if (!isInIframe) return "standalone";
33
+ const pattern = allowedPattern ?? DEFAULT_ALLOWED_HOST_PATTERN;
34
+ try {
35
+ const referrerOrigin = new URL(document.referrer).origin;
36
+ if (allowedOrigins?.includes(referrerOrigin)) return "iframe";
37
+ if (pattern.test(referrerOrigin)) return "iframe";
38
+ } catch {
39
+ }
40
+ return "standalone";
41
+ }
42
+ var StandaloneOAuth2Auth = class {
43
+ oauth2Client;
44
+ storage;
45
+ callbackPath;
46
+ constructor(config = {}) {
47
+ const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
48
+ if (!config.clientId) {
49
+ throw new Error(
50
+ 'DocyrusAuthProvider: "clientId" is required. Set it via the clientId prop or the VITE_DOCYRUS_CLIENT_ID / NEXT_PUBLIC_DOCYRUS_CLIENT_ID environment variable.'
51
+ );
52
+ }
53
+ const { clientId } = config;
54
+ const scopes = config.scopes ?? DEFAULT_OAUTH_SCOPES;
55
+ this.callbackPath = config.callbackPath ?? DEFAULT_CALLBACK_PATH;
56
+ const redirectUri = config.redirectUri ?? `${window.location.origin}${this.callbackPath}`;
57
+ this.storage = config.tokenStorage ?? new BrowserOAuth2TokenStorage(
58
+ window.localStorage,
59
+ config.storageKeyPrefix ?? "docyrus_oauth2"
60
+ );
61
+ this.oauth2Client = new OAuth2Client({
62
+ baseURL: apiUrl,
63
+ clientId,
64
+ redirectUri,
65
+ defaultScopes: scopes,
66
+ usePKCE: true,
67
+ tokenStorage: this.storage
68
+ });
69
+ }
70
+ /**
71
+ * Check if the current page URL is the OAuth2 callback.
72
+ * Called on app initialization to detect returning from the auth server.
73
+ */
74
+ isCallbackUrl() {
75
+ return window.location.pathname === this.callbackPath && (window.location.search.includes("code=") || window.location.search.includes("error="));
76
+ }
77
+ /**
78
+ * Initiate the OAuth2 authorization code flow.
79
+ * Stores the current URL for post-auth redirect, then navigates
80
+ * the page to the authorization endpoint.
81
+ *
82
+ * PKCE state (codeVerifier, state) is stored in localStorage
83
+ * by the OAuth2Client and survives the page redirect.
84
+ */
85
+ async initiateLogin() {
86
+ window.localStorage.setItem(REDIRECT_RETURN_KEY, window.location.href);
87
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
88
+ window.location.href = url;
89
+ }
90
+ /**
91
+ * Get the authorization URL without navigating.
92
+ * Useful for Electron apps that open the URL in an external browser.
93
+ * PKCE state is stored in storage just like initiateLogin().
94
+ */
95
+ async getAuthorizationUrl() {
96
+ window.localStorage.setItem(REDIRECT_RETURN_KEY, window.location.href);
97
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
98
+ return url;
99
+ }
100
+ /**
101
+ * Handle the OAuth2 callback URL.
102
+ * Reads PKCE state from localStorage, validates the state param,
103
+ * exchanges the authorization code for tokens, and stores them.
104
+ */
105
+ async handleCallback() {
106
+ return this.oauth2Client.handleCallback(window.location.href);
107
+ }
108
+ /**
109
+ * Get the URL the user was on before the OAuth redirect.
110
+ * Clears the stored value after retrieval.
111
+ */
112
+ getReturnUrl() {
113
+ const url = window.localStorage.getItem(REDIRECT_RETURN_KEY);
114
+ window.localStorage.removeItem(REDIRECT_RETURN_KEY);
115
+ return url;
116
+ }
117
+ /** Get currently stored tokens (e.g., on page reload). */
118
+ async getStoredTokens() {
119
+ return this.oauth2Client.getTokens();
120
+ }
121
+ /** Check if the stored token is expired (with 60s buffer). */
122
+ async isTokenExpired() {
123
+ return this.oauth2Client.isTokenExpired();
124
+ }
125
+ /** Refresh the access token using the stored refresh token. */
126
+ async refreshToken() {
127
+ return this.oauth2Client.refreshAccessToken();
128
+ }
129
+ /** Get a valid access token, refreshing if needed. */
130
+ async getValidAccessToken() {
131
+ return this.oauth2Client.getValidAccessToken();
132
+ }
133
+ /** Logout: revoke token and clear storage. */
134
+ async logout() {
135
+ return this.oauth2Client.logout();
136
+ }
137
+ };
138
+
139
+ // src/core/iframe-auth.ts
140
+ var IframeAuth = class {
141
+ allowedOrigins;
142
+ allowedPattern;
143
+ onTokensReceived = null;
144
+ refreshPromise = null;
145
+ messageHandler = null;
146
+ constructor(allowedOrigins, allowedPattern) {
147
+ this.allowedOrigins = allowedOrigins ?? [];
148
+ this.allowedPattern = allowedPattern ?? DEFAULT_ALLOWED_HOST_PATTERN;
149
+ }
150
+ /**
151
+ * Start listening for postMessage events from the host.
152
+ * The callback is invoked every time valid tokens are received.
153
+ */
154
+ start(onTokensReceived) {
155
+ this.onTokensReceived = onTokensReceived;
156
+ this.messageHandler = this.handleMessage.bind(this);
157
+ window.addEventListener("message", this.messageHandler);
158
+ }
159
+ /** Stop listening for postMessage events. */
160
+ stop() {
161
+ if (this.messageHandler) {
162
+ window.removeEventListener("message", this.messageHandler);
163
+ this.messageHandler = null;
164
+ }
165
+ this.rejectPendingRefresh("IframeAuth stopped");
166
+ }
167
+ /**
168
+ * Request fresh tokens from the host.
169
+ * Posts a "token-refresh-request" to the host, then waits for
170
+ * a "signin" response.
171
+ *
172
+ * Only one refresh request can be in-flight at a time.
173
+ * Additional callers share the same promise.
174
+ */
175
+ requestTokenRefresh() {
176
+ if (this.refreshPromise) {
177
+ return new Promise((resolve, reject) => {
178
+ const existing = this.refreshPromise;
179
+ const originalResolve = existing.resolve;
180
+ const originalReject = existing.reject;
181
+ existing.resolve = (tokens) => {
182
+ originalResolve(tokens);
183
+ resolve(tokens);
184
+ };
185
+ existing.reject = (error) => {
186
+ originalReject(error);
187
+ reject(error);
188
+ };
189
+ });
190
+ }
191
+ return new Promise((resolve, reject) => {
192
+ const timeoutId = setTimeout(() => {
193
+ this.refreshPromise = null;
194
+ reject(new Error("Token refresh request timed out"));
195
+ }, IFRAME_TOKEN_REFRESH_TIMEOUT_MS);
196
+ this.refreshPromise = { resolve, reject, timeoutId };
197
+ window.parent.postMessage({ type: "token-refresh-request" }, "*");
198
+ });
199
+ }
200
+ isOriginAllowed(origin) {
201
+ if (this.allowedOrigins.includes(origin)) return true;
202
+ return this.allowedPattern.test(origin);
203
+ }
204
+ handleMessage(ev) {
205
+ if (!this.isOriginAllowed(ev.origin)) return;
206
+ const data = ev.data;
207
+ if (!data || typeof data !== "object" || data.type !== "signin") return;
208
+ const signinData = data;
209
+ if (!signinData.accessToken) return;
210
+ const tokens = {
211
+ accessToken: signinData.accessToken,
212
+ refreshToken: signinData.refreshToken,
213
+ /*
214
+ * We don't know the exact expiry from the host, so estimate 1 hour.
215
+ * The host will send new tokens before expiry via the refresh mechanism.
216
+ */
217
+ expiresAt: Math.floor(Date.now() / 1e3) + 3600,
218
+ scope: ""
219
+ };
220
+ this.onTokensReceived?.(tokens);
221
+ if (this.refreshPromise) {
222
+ clearTimeout(this.refreshPromise.timeoutId);
223
+ this.refreshPromise.resolve(tokens);
224
+ this.refreshPromise = null;
225
+ }
226
+ }
227
+ rejectPendingRefresh(reason) {
228
+ if (this.refreshPromise) {
229
+ clearTimeout(this.refreshPromise.timeoutId);
230
+ this.refreshPromise.reject(new Error(reason));
231
+ this.refreshPromise = null;
232
+ }
233
+ }
234
+ };
235
+
236
+ // src/core/cookie-sync.ts
237
+ var DEFAULT_SSR_COOKIE_KEY2 = "docyrus-token";
238
+ function syncTokenToCookie(accessToken, cookieKey) {
239
+ if (typeof document === "undefined") return;
240
+ const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY2;
241
+ document.cookie = `${key}=${encodeURIComponent(accessToken)};path=/;SameSite=Lax`;
242
+ }
243
+ function clearTokenCookie(cookieKey) {
244
+ if (typeof document === "undefined") return;
245
+ const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY2;
246
+ document.cookie = `${key}=;path=/;max-age=0;SameSite=Lax`;
247
+ }
248
+ function getTokenFromCookie(cookieKey) {
249
+ if (typeof document === "undefined") return null;
250
+ const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY2;
251
+ const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${key}=([^;]*)`));
252
+ return match ? decodeURIComponent(match[1]) : null;
253
+ }
254
+
255
+ // src/core/auth-manager.ts
256
+ var AuthManager = class {
257
+ mode;
258
+ status = "loading";
259
+ tokens = null;
260
+ error = null;
261
+ client = null;
262
+ standaloneAuth = null;
263
+ iframeAuth = null;
264
+ tokenRefreshTimer = null;
265
+ listeners = /* @__PURE__ */ new Set();
266
+ config;
267
+ constructor(config = {}) {
268
+ this.config = config;
269
+ this.mode = config.forceMode ?? detectAuthMode(config.allowedHostOrigins);
270
+ }
271
+ getMode() {
272
+ return this.mode;
273
+ }
274
+ getStatus() {
275
+ return this.status;
276
+ }
277
+ getTokens() {
278
+ return this.tokens;
279
+ }
280
+ getClient() {
281
+ return this.client;
282
+ }
283
+ getError() {
284
+ return this.error;
285
+ }
286
+ subscribe(listener) {
287
+ this.listeners.add(listener);
288
+ return () => this.listeners.delete(listener);
289
+ }
290
+ notify() {
291
+ for (const listener of this.listeners) {
292
+ listener({
293
+ status: this.status,
294
+ tokens: this.tokens,
295
+ error: this.error
296
+ });
297
+ }
298
+ }
299
+ /** Initialize the auth manager. Must be called once on mount. */
300
+ async initialize() {
301
+ try {
302
+ if (this.mode === "iframe") {
303
+ this.initializeIframeMode();
304
+ } else {
305
+ await this.initializeStandaloneMode();
306
+ }
307
+ } catch (err) {
308
+ this.error = err instanceof Error ? err : new Error(String(err));
309
+ this.status = "unauthenticated";
310
+ this.notify();
311
+ }
312
+ }
313
+ /**
314
+ * Standalone mode initialization.
315
+ * 1. Check if we're returning from an OAuth callback.
316
+ * 2. If not, check for existing tokens in localStorage.
317
+ * 3. If tokens are expired, try to refresh.
318
+ */
319
+ async initializeStandaloneMode() {
320
+ this.standaloneAuth = new StandaloneOAuth2Auth(this.config);
321
+ if (this.standaloneAuth.isCallbackUrl()) {
322
+ const tokens = await this.standaloneAuth.handleCallback();
323
+ this.setAuthenticated(tokens);
324
+ const returnUrl = this.standaloneAuth.getReturnUrl();
325
+ if (returnUrl) {
326
+ window.location.replace(returnUrl);
327
+ } else {
328
+ window.history.replaceState({}, "", "/");
329
+ }
330
+ return;
331
+ }
332
+ const stored = await this.standaloneAuth.getStoredTokens();
333
+ if (stored) {
334
+ const isExpired = await this.standaloneAuth.isTokenExpired();
335
+ if (!isExpired) {
336
+ this.setAuthenticated(stored);
337
+ return;
338
+ }
339
+ if (stored.refreshToken) {
340
+ try {
341
+ const newTokens = await this.standaloneAuth.refreshToken();
342
+ this.setAuthenticated(newTokens);
343
+ return;
344
+ } catch {
345
+ }
346
+ }
347
+ }
348
+ this.status = "unauthenticated";
349
+ this.notify();
350
+ }
351
+ /**
352
+ * Iframe mode initialization.
353
+ * Listen for postMessage tokens from the host.
354
+ * Status remains 'loading' until the host sends the first signin message.
355
+ */
356
+ initializeIframeMode() {
357
+ this.iframeAuth = new IframeAuth(this.config.allowedHostOrigins);
358
+ this.iframeAuth.start((tokens) => {
359
+ this.setAuthenticated(tokens);
360
+ });
361
+ }
362
+ /** Initiate sign-in. Only meaningful in standalone mode. */
363
+ async signIn() {
364
+ if (this.mode !== "standalone" || !this.standaloneAuth) return;
365
+ await this.standaloneAuth.initiateLogin();
366
+ }
367
+ /**
368
+ * Get the OAuth2 authorization URL without navigating.
369
+ * Use this in Electron apps to open the URL in an external browser.
370
+ * Returns null if not in standalone mode.
371
+ */
372
+ async getAuthorizationUrl() {
373
+ if (this.mode !== "standalone" || !this.standaloneAuth) return null;
374
+ return this.standaloneAuth.getAuthorizationUrl();
375
+ }
376
+ /**
377
+ * Sign out.
378
+ * Standalone: revoke token, clear localStorage, reset state.
379
+ * Iframe: clear local state (host manages the actual session).
380
+ */
381
+ async signOut() {
382
+ this.clearTokenRefreshTimer();
383
+ if (this.mode === "standalone" && this.standaloneAuth) {
384
+ await this.standaloneAuth.logout();
385
+ }
386
+ if (this.mode === "iframe" && this.iframeAuth) {
387
+ this.iframeAuth.stop();
388
+ }
389
+ if (this.config.ssr) {
390
+ clearTokenCookie(this.config.ssrCookieKey);
391
+ }
392
+ this.tokens = null;
393
+ this.client = null;
394
+ this.status = "unauthenticated";
395
+ this.error = null;
396
+ this.notify();
397
+ }
398
+ /**
399
+ * Called when valid tokens are received (either mode).
400
+ * Creates/updates the RestApiClient and schedules token refresh.
401
+ */
402
+ setAuthenticated(tokens) {
403
+ this.tokens = tokens;
404
+ this.error = null;
405
+ this.status = "authenticated";
406
+ if (this.config.ssr) {
407
+ syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey);
408
+ }
409
+ this.createClient();
410
+ this.scheduleTokenRefresh(tokens);
411
+ this.notify();
412
+ }
413
+ /**
414
+ * Create a RestApiClient with a custom TokenManager that proactively
415
+ * refreshes the token in getToken(). This is necessary because
416
+ * BaseApiClient.getAccessToken() only calls tokenManager.getToken()
417
+ * and does NOT auto-call refreshToken() when the token is expired.
418
+ */
419
+ createClient() {
420
+ const apiUrl = this.config.apiUrl ?? DEFAULT_API_URL;
421
+ const tokenManager = {
422
+ getToken: () => this.getValidToken(),
423
+ setToken: (token) => {
424
+ if (this.tokens) {
425
+ this.tokens = { ...this.tokens, accessToken: token };
426
+ }
427
+ },
428
+ clearToken: () => {
429
+ this.tokens = null;
430
+ },
431
+ refreshToken: () => this.handleTokenRefresh()
432
+ };
433
+ this.client = new RestApiClient({
434
+ baseURL: apiUrl,
435
+ tokenManager
436
+ });
437
+ }
438
+ /**
439
+ * Get a valid access token, proactively refreshing if expired.
440
+ * Called by the RestApiClient on every request via tokenManager.getToken().
441
+ */
442
+ async getValidToken() {
443
+ if (!this.tokens) return null;
444
+ if (this.tokens.expiresAt) {
445
+ const nowSec = Math.floor(Date.now() / 1e3);
446
+ if (nowSec >= this.tokens.expiresAt - TOKEN_EXPIRY_BUFFER_SECONDS) {
447
+ try {
448
+ const freshToken = await this.handleTokenRefresh();
449
+ return freshToken;
450
+ } catch {
451
+ return null;
452
+ }
453
+ }
454
+ }
455
+ return this.tokens.accessToken;
456
+ }
457
+ /**
458
+ * Handle token refresh depending on mode.
459
+ * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
460
+ * Iframe: send postMessage to host requesting new tokens.
461
+ */
462
+ async handleTokenRefresh() {
463
+ if (this.mode === "standalone" && this.standaloneAuth) {
464
+ const newTokens = await this.standaloneAuth.refreshToken();
465
+ this.tokens = newTokens;
466
+ if (this.config.ssr) {
467
+ syncTokenToCookie(newTokens.accessToken, this.config.ssrCookieKey);
468
+ }
469
+ this.scheduleTokenRefresh(newTokens);
470
+ this.notify();
471
+ return newTokens.accessToken;
472
+ }
473
+ if (this.mode === "iframe" && this.iframeAuth) {
474
+ const newTokens = await this.iframeAuth.requestTokenRefresh();
475
+ return newTokens.accessToken;
476
+ }
477
+ throw new Error("Cannot refresh token: auth not initialized");
478
+ }
479
+ /** Schedule proactive token refresh before expiry. */
480
+ scheduleTokenRefresh(tokens) {
481
+ this.clearTokenRefreshTimer();
482
+ if (!tokens.expiresAt) return;
483
+ const expiresAtMs = tokens.expiresAt * 1e3;
484
+ const bufferMs = TOKEN_EXPIRY_BUFFER_SECONDS * 1e3;
485
+ const refreshInMs = expiresAtMs - bufferMs - Date.now();
486
+ if (refreshInMs <= 0) {
487
+ this.handleTokenRefresh().catch((err) => {
488
+ this.error = err instanceof Error ? err : new Error(String(err));
489
+ this.status = "unauthenticated";
490
+ this.notify();
491
+ });
492
+ return;
493
+ }
494
+ this.tokenRefreshTimer = setTimeout(() => {
495
+ this.handleTokenRefresh().catch((err) => {
496
+ this.error = err instanceof Error ? err : new Error(String(err));
497
+ this.status = "unauthenticated";
498
+ this.notify();
499
+ });
500
+ }, refreshInMs);
501
+ }
502
+ clearTokenRefreshTimer() {
503
+ if (this.tokenRefreshTimer) {
504
+ clearTimeout(this.tokenRefreshTimer);
505
+ this.tokenRefreshTimer = null;
506
+ }
507
+ }
508
+ /** Cleanup: remove listeners, timers, stop iframe auth. */
509
+ destroy() {
510
+ this.clearTokenRefreshTimer();
511
+ if (this.iframeAuth) this.iframeAuth.stop();
512
+ this.listeners.clear();
513
+ }
514
+ };
515
+ var DocyrusAuthContext = createContext(null);
516
+ function DocyrusAuthProvider({
517
+ children,
518
+ ...config
519
+ }) {
520
+ const [status, setStatus] = useState("loading");
521
+ const [tokens, setTokens] = useState(null);
522
+ const [client, setClient] = useState(null);
523
+ const [mode, setMode] = useState(null);
524
+ const [error, setError] = useState(null);
525
+ const managerRef = useRef(null);
526
+ useEffect(() => {
527
+ const manager = new AuthManager(config);
528
+ managerRef.current = manager;
529
+ setMode(manager.getMode());
530
+ const unsubscribe = manager.subscribe((state) => {
531
+ setStatus(state.status);
532
+ setTokens(state.tokens);
533
+ setError(state.error);
534
+ setClient(manager.getClient());
535
+ });
536
+ manager.initialize();
537
+ return () => {
538
+ unsubscribe();
539
+ manager.destroy();
540
+ };
541
+ }, []);
542
+ const signIn = useMemo(() => {
543
+ return () => {
544
+ managerRef.current?.signIn();
545
+ };
546
+ }, []);
547
+ const signOut = useMemo(() => {
548
+ return async () => {
549
+ await managerRef.current?.signOut();
550
+ };
551
+ }, []);
552
+ const getAuthorizationUrl = useMemo(() => {
553
+ return async () => {
554
+ return managerRef.current?.getAuthorizationUrl() ?? null;
555
+ };
556
+ }, []);
557
+ const value = useMemo(() => ({
558
+ status,
559
+ mode,
560
+ client,
561
+ tokens,
562
+ signIn,
563
+ getAuthorizationUrl,
564
+ signOut,
565
+ error
566
+ }), [
567
+ status,
568
+ mode,
569
+ client,
570
+ tokens,
571
+ signIn,
572
+ getAuthorizationUrl,
573
+ signOut,
574
+ error
575
+ ]);
576
+ return /* @__PURE__ */ jsx(DocyrusAuthContext.Provider, { value, children });
577
+ }
578
+ function useDocyrusAuth() {
579
+ const context = useContext(DocyrusAuthContext);
580
+ if (!context) {
581
+ throw new Error(
582
+ "useDocyrusAuth must be used within a <DocyrusAuthProvider>. Wrap your app with <DocyrusAuthProvider> to provide auth context."
583
+ );
584
+ }
585
+ return context;
586
+ }
587
+
588
+ // src/hooks/use-docyrus-client.ts
589
+ function useDocyrusClient() {
590
+ const { client } = useDocyrusAuth();
591
+ return client;
592
+ }
593
+ var ICON_SIZE = 20;
594
+ function DocyrusLogo({ size = ICON_SIZE }) {
595
+ return /* @__PURE__ */ jsx(
596
+ "svg",
597
+ {
598
+ xmlns: "http://www.w3.org/2000/svg",
599
+ viewBox: "0 0 1024 1024",
600
+ width: size,
601
+ height: size,
602
+ "aria-hidden": "true",
603
+ style: { display: "block", flexShrink: 0 },
604
+ children: /* @__PURE__ */ jsx(
605
+ "path",
606
+ {
607
+ fill: "#dc2626",
608
+ d: "M768.11,531.68l-.24.21v101.17c0,26.8-21.79,48.63-48.59,48.63h-101.17c-8.72,0-16.82-2.33-23.88-6.35l-113.69,113.73c7.41,11.02,11.77,24.33,11.77,38.47,0,18.98-7.62,36.17-20.04,48.63-12.42,12.42-29.65,20.04-48.63,20.04s-36.2-7.62-48.63-20.04c-12.42-12.46-20.04-29.65-20.04-48.63,0-37.96,30.75-68.91,68.87-68.91,14.48,0,27.76,4.43,38.78,11.94l113.62-113.62c-4.19-7.1-6.55-15.31-6.55-24.09v-101.17c0-11.12,3.81-21.48,10.19-29.68l-93.72-127.52h-229.96V127.7h246.57v225.88l97.6,132.84c5.56-2.23,11.63-3.36,17.95-3.36h101.17c26.8,0,48.63,21.83,48.63,48.63Z"
609
+ }
610
+ )
611
+ }
612
+ );
613
+ }
614
+ function Spinner({ size = ICON_SIZE }) {
615
+ return /* @__PURE__ */ jsxs(
616
+ "svg",
617
+ {
618
+ xmlns: "http://www.w3.org/2000/svg",
619
+ viewBox: "0 0 24 24",
620
+ width: size,
621
+ height: size,
622
+ fill: "none",
623
+ "aria-hidden": "true",
624
+ style: { display: "block", flexShrink: 0, animation: "docyrus-spin 1s linear infinite" },
625
+ children: [
626
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "3", opacity: "0.25" }),
627
+ /* @__PURE__ */ jsx(
628
+ "path",
629
+ {
630
+ d: "M12 2a10 10 0 0 1 10 10",
631
+ stroke: "currentColor",
632
+ strokeWidth: "3",
633
+ strokeLinecap: "round"
634
+ }
635
+ ),
636
+ /* @__PURE__ */ jsx("style", { children: `@keyframes docyrus-spin{to{transform:rotate(360deg)}}` })
637
+ ]
638
+ }
639
+ );
640
+ }
641
+ function SignInButton({
642
+ label = "Sign in with Docyrus",
643
+ className,
644
+ style,
645
+ children,
646
+ disabled = false
647
+ }) {
648
+ const { signIn, status, mode } = useDocyrusAuth();
649
+ const isLoading = status === "loading";
650
+ if (mode === "iframe") return null;
651
+ if (status === "authenticated") return null;
652
+ if (children) {
653
+ return /* @__PURE__ */ jsx(Fragment, { children: children({ signIn, isLoading, status }) });
654
+ }
655
+ return /* @__PURE__ */ jsxs(
656
+ "button",
657
+ {
658
+ type: "button",
659
+ onClick: signIn,
660
+ disabled: disabled || isLoading,
661
+ className,
662
+ style: {
663
+ display: "inline-flex",
664
+ alignItems: "center",
665
+ justifyContent: "center",
666
+ gap: "8px",
667
+ ...style
668
+ },
669
+ children: [
670
+ isLoading ? /* @__PURE__ */ jsx(Spinner, {}) : /* @__PURE__ */ jsx(DocyrusLogo, {}),
671
+ /* @__PURE__ */ jsx("span", { children: label })
672
+ ]
673
+ }
674
+ );
675
+ }
676
+
677
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, DEFAULT_SSR_COOKIE_KEY, DocyrusAuthContext, DocyrusAuthProvider, IframeAuth, SignInButton, StandaloneOAuth2Auth, clearTokenCookie, detectAuthMode, getTokenFromCookie, syncTokenToCookie, useDocyrusAuth, useDocyrusClient };
678
+ //# sourceMappingURL=index.js.map
679
+ //# sourceMappingURL=index.js.map