@strivacity/sdk-react 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # 1.0.0 (2024-09-20)
2
+
3
+
4
+ ### 🚀 Features
5
+
6
+ - @strivacity/sdk-react package implemented
7
+
8
+
9
+ ### 🧱 Updated Dependencies
10
+
11
+ - Updated sdk-core to 1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Strivacity Inc. <info@strivacity.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # @strivacity/sdk-react
2
+
3
+ > **The SDK supports React version 16 and above**
4
+
5
+ ### Install
6
+
7
+ ```bash
8
+ npm install @strivacity/sdk-react
9
+ ```
10
+
11
+ ### Usage
12
+
13
+ #### Wrap your app with Auth Provider:
14
+
15
+ ```js
16
+ import { AuthProvider, useStrivacity } from '@strivacity/sdk-react';
17
+
18
+ const sdkOptions = {
19
+ mode: 'redirect',
20
+ issuer: 'https://<YOUR_DOMAIN>',
21
+ scopes: ['openid', 'profile'],
22
+ clientId: '<YOUR_CLIENT_ID>',
23
+ redirectUri: '<YOUR_REDIRECT_URI>',
24
+ };
25
+ const AppRoot = () => {
26
+ return (
27
+ <AuthProvider options={sdkOptions}>
28
+ <App />
29
+ </AuthProvider>
30
+ );
31
+ };
32
+ ```
33
+
34
+ #### How to use the SDK in your components:
35
+
36
+ ```jsx
37
+ import { useEffect, useCallback } from 'react'
38
+ import { useStrivacity } from '@strivacity/sdk-react';
39
+
40
+ const { isAuthenticated, idTokenClaims, login, logout } = useStrivacity();
41
+ const [name, setName] = useState('');
42
+ const onLogin = useCallback(() => {
43
+ login();
44
+ },[]);
45
+ const onLogout = useCallback(() => {
46
+ logout();
47
+ },[]);
48
+
49
+ useEffect(() => {
50
+ setName(`${idTokenClaims?.given_name} ${idTokenClaims?.family_name}`);
51
+ }, [isAuthenticated, idTokenClaims]);
52
+
53
+ return (
54
+ {isAuthenticated ? (<>
55
+ <div>Welcome, {{ name }}!</div>
56
+ <button onClick={onLogout()}>Logout</button>
57
+ </>) : <>
58
+ <div>Not logged in</div>
59
+ <button onClick={onLogin()}>Log in</button>
60
+ </>}
61
+ )
62
+ ```
63
+
64
+ ### API Documentation
65
+
66
+ #### `useStrivacity` hook
67
+
68
+ ```typescript
69
+ useStrivacity<T extends PopupContext | RedirectContext>(): T;
70
+ ```
71
+
72
+ You can choose between `PopupContext` or `RedirectContext` with the `mode` option when you configure the sdk options.
73
+
74
+ **Properties**
75
+
76
+ - **`loading: boolean`**: Indicates if the session is being loaded.
77
+ - **`isAuthenticated: boolean`**: Indicates whether the user is authenticated.
78
+ - **`idTokenClaims: IdTokenClaims | null`**: Claims from the ID token or null if not available.
79
+ - **`accessToken: string | null`**: The access token or null if not available.
80
+ - **`refreshToken: string | null`**: The refresh token or null if not available.
81
+ - **`accessTokenExpired: boolean`**: Indicates if the access token has expired.
82
+ - **`accessTokenExpirationDate: number | null`**: Expiration date of the access token or null if not set.
83
+
84
+ ---
85
+
86
+ Type: `RedirectContext`
87
+ Represents the available methods for Redirect-based interactions.
88
+
89
+ - **`login(options?: LoginOptions): Promise<void>`**: Initiates the login process by redirecting the user to the identity provider.
90
+ - `options` (optional): Configuration options for login.
91
+ - **`register(options?: RegisterOptions): Promise<void>`**: Registers a new user using a redirect flow.
92
+ - `options` (optional): Configuration options for registration.
93
+ - **`refresh(): Promise<void>`**: Refreshes the user's session using a redirect flow.
94
+ - **`revoke(): Promise<void>`**: Revokes the current session tokens using a redirect flow.
95
+ - **`logout(options?: LogoutOptions): Promise<void>`**: Logs out the user by redirecting to the logout page.
96
+ - `options` (optional): Configuration options for logout.
97
+ - **`handleCallback(url?: string): Promise<void>`**: Handles the callback after a redirect-based authentication or token exchange.
98
+ - `url` (optional): The URL to handle for the callback.
99
+
100
+ ---
101
+
102
+ Type: `PopupContext`
103
+ Represents the available methods for Popup-based interactions.
104
+
105
+ - **`login(options?: LoginOptions): Promise<void>`**: Initiates the login process using a popup window.
106
+ - `options` (optional): Configuration options for login.
107
+ - **`register(options?: RegisterOptions): Promise<void>`**: Registers a new user using a popup flow.
108
+ - `options` (optional): Configuration options for registration.
109
+ - **`refresh(): Promise<void>`**: Refreshes the user's session using a popup.
110
+ - **`revoke(): Promise<void>`**: Revokes the current session tokens using a popup flow.
111
+ - **`logout(options?: LogoutOptions): Promise<void>`**: Logs out the user using a popup window.
112
+ - `options` (optional): Configuration options for logout.
113
+ - **`handleCallback(url?: string): Promise<void>`**: Handles the callback after a popup-based authentication or token exchange.
114
+ - `url` (optional): The URL to handle for the callback.
115
+
116
+ ### Links
117
+
118
+ [Example app](https://github.com/Strivacity/sdk-js/tree/main/apps/react)
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react/jsx-runtime"),s=require("react"),x=require("@strivacity/sdk-core"),p=require("@strivacity/sdk-core/storages/LocalStorage"),m=require("@strivacity/sdk-core/storages/SessionStorage"),k=s.createContext(null);let e;const A=()=>{const o=s.useContext(k);if(!o)throw Error("Missing Strivacity SDK context");return o},C=({options:o,children:S=void 0})=>{const[a,b]=s.useState(!0),[i,T]=s.useState(!1),[r,g]=s.useState(null),[c,v]=s.useState(null),[u,f]=s.useState(null),[l,E]=s.useState(!0),[d,h]=s.useState(null),t=async()=>{T(await e.isAuthenticated),g(e.idTokenClaims||null),v(e.accessToken||null),f(e.refreshToken||null),E(e.accessTokenExpired),h(e.accessTokenExpirationDate||null),a&&b(!1)},w=s.useMemo(()=>(e||(e=x.initFlow(o)),{loading:a,isAuthenticated:i,idTokenClaims:r,accessToken:c,refreshToken:u,accessTokenExpired:l,accessTokenExpirationDate:d,login:async n=>{await e.login(n),await t()},register:async n=>{await e.register(n),await t()},refresh:async()=>{await e.refresh(),await t()},revoke:async()=>{await e.revoke(),await t()},logout:async n=>{await e.logout(n),await t()},handleCallback:async n=>{await e.handleCallback(n),await t()}}),[a,r,c,u,l,d,i]);return s.useEffect(()=>{e&&(e.subscribeToEvent("init",t),e.subscribeToEvent("loggedIn",t),e.subscribeToEvent("sessionLoaded",t),e.subscribeToEvent("tokenRefreshed",t),e.subscribeToEvent("tokenRefreshFailed",t),e.subscribeToEvent("logoutInitiated",t),e.subscribeToEvent("tokenRevoked",t),e.subscribeToEvent("tokenRevokeFailed",t))},[]),y.jsx(k.Provider,{value:w,children:S})};Object.defineProperty(exports,"LocalStorage",{enumerable:!0,get:()=>p.LocalStorage});Object.defineProperty(exports,"SessionStorage",{enumerable:!0,get:()=>m.SessionStorage});exports.AuthProvider=C;exports.useStrivacity=A;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/index.tsx"],"sourcesContent":["import { type FC, createContext, useContext, useMemo, useEffect, useState } from 'react';\nimport { initFlow, type SDKOptions, type SDKStorage, type IdTokenClaims } from '@strivacity/sdk-core';\nimport type { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';\nimport type { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';\nimport { LocalStorage } from '@strivacity/sdk-core/storages/LocalStorage';\nimport { SessionStorage } from '@strivacity/sdk-core/storages/SessionStorage';\nimport type { Session, PopupContext, PopupSDK, RedirectContext, RedirectSDK, Children } from './types';\n\nexport type { SDKOptions, SDKStorage, Session, IdTokenClaims, PopupFlow, RedirectFlow, PopupContext, PopupSDK, RedirectContext, RedirectSDK };\nexport { LocalStorage, SessionStorage };\n\nconst StrivacitySdk = createContext<PopupContext | RedirectContext>(null!);\n\nlet sdk: RedirectFlow | PopupFlow;\n\n/**\n * Hook to access the Strivacity SDK context\n *\n * @template T Extends either PopupContext or RedirectContext.\n *\n * @returns {T} The current Strivacity SDK context.\n *\n * @throws {Error} If the context is not provided by an AuthProvider.\n */\nexport const useStrivacity = <T extends PopupContext | RedirectContext>() => {\n\tconst context = useContext(StrivacitySdk);\n\n\tif (!context) {\n\t\tthrow Error('Missing Strivacity SDK context');\n\t}\n\n\treturn context as T;\n};\n\n/**\n * Strivacity authentication provider component\n *\n * @param {SDKOptions} options - The SDK configuration options.\n * @param {Children} [children] - The child components wrapped by the provider.\n *\n * @returns {JSX.Element} A provider that passes the Strivacity SDK context to its children.\n */\nexport const AuthProvider: FC<{ options: SDKOptions; children?: Children }> = ({\n\toptions,\n\tchildren = undefined,\n}: {\n\toptions: SDKOptions;\n\tchildren?: Children;\n}) => {\n\tconst [loading, setLoading] = useState<boolean>(true);\n\tconst [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n\tconst [idTokenClaims, setIdTokenClaims] = useState<IdTokenClaims | null>(null);\n\tconst [accessToken, setAccessToken] = useState<string | null>(null);\n\tconst [refreshToken, setRefreshToken] = useState<string | null>(null);\n\tconst [accessTokenExpired, setAccessTokenExpired] = useState<boolean>(true);\n\tconst [accessTokenExpirationDate, setAccessTokenExpirationDate] = useState<number | null>(null);\n\n\tconst updateSession = async () => {\n\t\tsetIsAuthenticated(await sdk.isAuthenticated);\n\t\tsetIdTokenClaims(sdk.idTokenClaims || null);\n\t\tsetAccessToken(sdk.accessToken || null);\n\t\tsetRefreshToken(sdk.refreshToken || null);\n\t\tsetAccessTokenExpired(sdk.accessTokenExpired);\n\t\tsetAccessTokenExpirationDate(sdk.accessTokenExpirationDate || null);\n\n\t\tif (loading) {\n\t\t\tsetLoading(false);\n\t\t}\n\t};\n\n\tconst value = useMemo<PopupContext | RedirectContext>(() => {\n\t\tif (!sdk) {\n\t\t\tsdk = initFlow(options);\n\t\t}\n\n\t\treturn {\n\t\t\tloading,\n\t\t\tisAuthenticated,\n\t\t\tidTokenClaims,\n\t\t\taccessToken,\n\t\t\trefreshToken,\n\t\t\taccessTokenExpired,\n\t\t\taccessTokenExpirationDate,\n\n\t\t\tlogin: async (options?: Parameters<PopupFlow['login'] | RedirectFlow['login']>[0]) => {\n\t\t\t\tawait sdk.login(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tregister: async (options?: Parameters<PopupFlow['register'] | RedirectFlow['register']>[0]) => {\n\t\t\t\tawait sdk.register(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trefresh: async () => {\n\t\t\t\tawait sdk.refresh();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trevoke: async () => {\n\t\t\t\tawait sdk.revoke();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tlogout: async (options?: Parameters<PopupFlow['logout'] | RedirectFlow['logout']>[0]) => {\n\t\t\t\tawait sdk.logout(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\thandleCallback: async (url?: Parameters<PopupFlow['handleCallback'] | RedirectFlow['handleCallback']>[0]) => {\n\t\t\t\tawait sdk.handleCallback(url);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t};\n\t}, [loading, idTokenClaims, accessToken, refreshToken, accessTokenExpired, accessTokenExpirationDate, isAuthenticated]);\n\n\tuseEffect(() => {\n\t\tif (!sdk) {\n\t\t\treturn;\n\t\t}\n\n\t\tsdk.subscribeToEvent('init', updateSession);\n\t\tsdk.subscribeToEvent('loggedIn', updateSession);\n\t\tsdk.subscribeToEvent('sessionLoaded', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshed', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshFailed', updateSession);\n\t\tsdk.subscribeToEvent('logoutInitiated', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevoked', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevokeFailed', updateSession);\n\t}, []);\n\n\treturn <StrivacitySdk.Provider value={value}>{children}</StrivacitySdk.Provider>;\n};\n"],"names":["StrivacitySdk","createContext","sdk","useStrivacity","context","useContext","AuthProvider","options","children","loading","setLoading","useState","isAuthenticated","setIsAuthenticated","idTokenClaims","setIdTokenClaims","accessToken","setAccessToken","refreshToken","setRefreshToken","accessTokenExpired","setAccessTokenExpired","accessTokenExpirationDate","setAccessTokenExpirationDate","updateSession","value","useMemo","initFlow","url","useEffect","jsx"],"mappings":"4RAWMA,EAAgBC,EAAAA,cAA8C,IAAK,EAEzE,IAAIC,EAWG,MAAMC,EAAgB,IAAgD,CACtE,MAAAC,EAAUC,aAAWL,CAAa,EAExC,GAAI,CAACI,EACJ,MAAM,MAAM,gCAAgC,EAGtC,OAAAA,CACR,EAUaE,EAAiE,CAAC,CAC9E,QAAAC,EACA,SAAAC,EAAW,MACZ,IAGM,CACL,KAAM,CAACC,EAASC,CAAU,EAAIC,WAAkB,EAAI,EAC9C,CAACC,EAAiBC,CAAkB,EAAIF,WAAkB,EAAK,EAC/D,CAACG,EAAeC,CAAgB,EAAIJ,WAA+B,IAAI,EACvE,CAACK,EAAaC,CAAc,EAAIN,WAAwB,IAAI,EAC5D,CAACO,EAAcC,CAAe,EAAIR,WAAwB,IAA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EAC/CtB,EAAA,iBAAiB,iBAAkBsB,CAAa,EAChDtB,EAAA,iBAAiB,qBAAsBsB,CAAa,EACpDtB,EAAA,iBAAiB,kBAAmBsB,CAAa,EACjDtB,EAAA,iBAAiB,eAAgBsB,CAAa,EAC9CtB,EAAA,iBAAiB,oBAAqBsB,CAAa,EACxD,EAAG,CAAE,CAAA,EAEGM,EAAAA,IAAA9B,EAAc,SAAd,CAAuB,MAAAyB,EAAe,SAAAjB,CAAS,CAAA,CACxD"}
@@ -0,0 +1,31 @@
1
+ import { FC } from 'react';
2
+ import { SDKOptions, SDKStorage, IdTokenClaims } from '@strivacity/sdk-core';
3
+ import { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';
4
+ import { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';
5
+ import { LocalStorage } from '@strivacity/sdk-core/storages/LocalStorage';
6
+ import { SessionStorage } from '@strivacity/sdk-core/storages/SessionStorage';
7
+ import { Session, PopupContext, PopupSDK, RedirectContext, RedirectSDK, Children } from './types';
8
+ export type { SDKOptions, SDKStorage, Session, IdTokenClaims, PopupFlow, RedirectFlow, PopupContext, PopupSDK, RedirectContext, RedirectSDK };
9
+ export { LocalStorage, SessionStorage };
10
+ /**
11
+ * Hook to access the Strivacity SDK context
12
+ *
13
+ * @template T Extends either PopupContext or RedirectContext.
14
+ *
15
+ * @returns {T} The current Strivacity SDK context.
16
+ *
17
+ * @throws {Error} If the context is not provided by an AuthProvider.
18
+ */
19
+ export declare const useStrivacity: <T extends PopupContext | RedirectContext>() => T;
20
+ /**
21
+ * Strivacity authentication provider component
22
+ *
23
+ * @param {SDKOptions} options - The SDK configuration options.
24
+ * @param {Children} [children] - The child components wrapped by the provider.
25
+ *
26
+ * @returns {JSX.Element} A provider that passes the Strivacity SDK context to its children.
27
+ */
28
+ export declare const AuthProvider: FC<{
29
+ options: SDKOptions;
30
+ children?: Children;
31
+ }>;
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import{jsx as p}from"react/jsx-runtime";import{createContext as m,useContext as y,useState as o,useMemo as S,useEffect as A}from"react";import{initFlow as C}from"@strivacity/sdk-core";import{LocalStorage as j}from"@strivacity/sdk-core/storages/LocalStorage";import{SessionStorage as q}from"@strivacity/sdk-core/storages/SessionStorage";const k=m(null);let e;const F=()=>{const n=y(k);if(!n)throw Error("Missing Strivacity SDK context");return n},L=({options:n,children:T=void 0})=>{const[a,f]=o(!0),[i,v]=o(!1),[r,b]=o(null),[c,E]=o(null),[l,w]=o(null),[u,g]=o(!0),[d,h]=o(null),t=async()=>{v(await e.isAuthenticated),b(e.idTokenClaims||null),E(e.accessToken||null),w(e.refreshToken||null),g(e.accessTokenExpired),h(e.accessTokenExpirationDate||null),a&&f(!1)},x=S(()=>(e||(e=C(n)),{loading:a,isAuthenticated:i,idTokenClaims:r,accessToken:c,refreshToken:l,accessTokenExpired:u,accessTokenExpirationDate:d,login:async s=>{await e.login(s),await t()},register:async s=>{await e.register(s),await t()},refresh:async()=>{await e.refresh(),await t()},revoke:async()=>{await e.revoke(),await t()},logout:async s=>{await e.logout(s),await t()},handleCallback:async s=>{await e.handleCallback(s),await t()}}),[a,r,c,l,u,d,i]);return A(()=>{e&&(e.subscribeToEvent("init",t),e.subscribeToEvent("loggedIn",t),e.subscribeToEvent("sessionLoaded",t),e.subscribeToEvent("tokenRefreshed",t),e.subscribeToEvent("tokenRefreshFailed",t),e.subscribeToEvent("logoutInitiated",t),e.subscribeToEvent("tokenRevoked",t),e.subscribeToEvent("tokenRevokeFailed",t))},[]),p(k.Provider,{value:x,children:T})};export{L as AuthProvider,j as LocalStorage,q as SessionStorage,F as useStrivacity};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/index.tsx"],"sourcesContent":["import { type FC, createContext, useContext, useMemo, useEffect, useState } from 'react';\nimport { initFlow, type SDKOptions, type SDKStorage, type IdTokenClaims } from '@strivacity/sdk-core';\nimport type { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';\nimport type { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';\nimport { LocalStorage } from '@strivacity/sdk-core/storages/LocalStorage';\nimport { SessionStorage } from '@strivacity/sdk-core/storages/SessionStorage';\nimport type { Session, PopupContext, PopupSDK, RedirectContext, RedirectSDK, Children } from './types';\n\nexport type { SDKOptions, SDKStorage, Session, IdTokenClaims, PopupFlow, RedirectFlow, PopupContext, PopupSDK, RedirectContext, RedirectSDK };\nexport { LocalStorage, SessionStorage };\n\nconst StrivacitySdk = createContext<PopupContext | RedirectContext>(null!);\n\nlet sdk: RedirectFlow | PopupFlow;\n\n/**\n * Hook to access the Strivacity SDK context\n *\n * @template T Extends either PopupContext or RedirectContext.\n *\n * @returns {T} The current Strivacity SDK context.\n *\n * @throws {Error} If the context is not provided by an AuthProvider.\n */\nexport const useStrivacity = <T extends PopupContext | RedirectContext>() => {\n\tconst context = useContext(StrivacitySdk);\n\n\tif (!context) {\n\t\tthrow Error('Missing Strivacity SDK context');\n\t}\n\n\treturn context as T;\n};\n\n/**\n * Strivacity authentication provider component\n *\n * @param {SDKOptions} options - The SDK configuration options.\n * @param {Children} [children] - The child components wrapped by the provider.\n *\n * @returns {JSX.Element} A provider that passes the Strivacity SDK context to its children.\n */\nexport const AuthProvider: FC<{ options: SDKOptions; children?: Children }> = ({\n\toptions,\n\tchildren = undefined,\n}: {\n\toptions: SDKOptions;\n\tchildren?: Children;\n}) => {\n\tconst [loading, setLoading] = useState<boolean>(true);\n\tconst [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n\tconst [idTokenClaims, setIdTokenClaims] = useState<IdTokenClaims | null>(null);\n\tconst [accessToken, setAccessToken] = useState<string | null>(null);\n\tconst [refreshToken, setRefreshToken] = useState<string | null>(null);\n\tconst [accessTokenExpired, setAccessTokenExpired] = useState<boolean>(true);\n\tconst [accessTokenExpirationDate, setAccessTokenExpirationDate] = useState<number | null>(null);\n\n\tconst updateSession = async () => {\n\t\tsetIsAuthenticated(await sdk.isAuthenticated);\n\t\tsetIdTokenClaims(sdk.idTokenClaims || null);\n\t\tsetAccessToken(sdk.accessToken || null);\n\t\tsetRefreshToken(sdk.refreshToken || null);\n\t\tsetAccessTokenExpired(sdk.accessTokenExpired);\n\t\tsetAccessTokenExpirationDate(sdk.accessTokenExpirationDate || null);\n\n\t\tif (loading) {\n\t\t\tsetLoading(false);\n\t\t}\n\t};\n\n\tconst value = useMemo<PopupContext | RedirectContext>(() => {\n\t\tif (!sdk) {\n\t\t\tsdk = initFlow(options);\n\t\t}\n\n\t\treturn {\n\t\t\tloading,\n\t\t\tisAuthenticated,\n\t\t\tidTokenClaims,\n\t\t\taccessToken,\n\t\t\trefreshToken,\n\t\t\taccessTokenExpired,\n\t\t\taccessTokenExpirationDate,\n\n\t\t\tlogin: async (options?: Parameters<PopupFlow['login'] | RedirectFlow['login']>[0]) => {\n\t\t\t\tawait sdk.login(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tregister: async (options?: Parameters<PopupFlow['register'] | RedirectFlow['register']>[0]) => {\n\t\t\t\tawait sdk.register(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trefresh: async () => {\n\t\t\t\tawait sdk.refresh();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trevoke: async () => {\n\t\t\t\tawait sdk.revoke();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tlogout: async (options?: Parameters<PopupFlow['logout'] | RedirectFlow['logout']>[0]) => {\n\t\t\t\tawait sdk.logout(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\thandleCallback: async (url?: Parameters<PopupFlow['handleCallback'] | RedirectFlow['handleCallback']>[0]) => {\n\t\t\t\tawait sdk.handleCallback(url);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t};\n\t}, [loading, idTokenClaims, accessToken, refreshToken, accessTokenExpired, accessTokenExpirationDate, isAuthenticated]);\n\n\tuseEffect(() => {\n\t\tif (!sdk) {\n\t\t\treturn;\n\t\t}\n\n\t\tsdk.subscribeToEvent('init', updateSession);\n\t\tsdk.subscribeToEvent('loggedIn', updateSession);\n\t\tsdk.subscribeToEvent('sessionLoaded', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshed', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshFailed', updateSession);\n\t\tsdk.subscribeToEvent('logoutInitiated', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevoked', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevokeFailed', updateSession);\n\t}, []);\n\n\treturn <StrivacitySdk.Provider value={value}>{children}</StrivacitySdk.Provider>;\n};\n"],"names":["StrivacitySdk","createContext","sdk","useStrivacity","context","useContext","AuthProvider","options","children","loading","setLoading","useState","isAuthenticated","setIsAuthenticated","idTokenClaims","setIdTokenClaims","accessToken","setAccessToken","refreshToken","setRefreshToken","accessTokenExpired","setAccessTokenExpired","accessTokenExpirationDate","setAccessTokenExpirationDate","updateSession","value","useMemo","initFlow","url","useEffect","jsx"],"mappings":"gVAWA,MAAMA,EAAgBC,EAA8C,IAAK,EAEzE,IAAIC,EAWG,MAAMC,EAAgB,IAAgD,CACtE,MAAAC,EAAUC,EAAWL,CAAa,EAExC,GAAI,CAACI,EACJ,MAAM,MAAM,gCAAgC,EAGtC,OAAAA,CACR,EAUaE,EAAiE,CAAC,CAC9E,QAAAC,EACA,SAAAC,EAAW,MACZ,IAGM,CACL,KAAM,CAACC,EAASC,CAAU,EAAIC,EAAkB,EAAI,EAC9C,CAACC,EAAiBC,CAAkB,EAAIF,EAAkB,EAAK,EAC/D,CAACG,EAAeC,CAAgB,EAAIJ,EAA+B,IAAI,EACvE,CAACK,EAAaC,CAAc,EAAIN,EAAwB,IAAI,EAC5D,CAACO,EAAcC,CAAe,EAAIR,EAAwB,IAAI,EAC9D,CAACS,EAAoBC,CAAqB,EAAIV,EAAkB,EAAI,EACpE,CAACW,EAA2BC,CAA4B,EAAIZ,EAAwB,IAAI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jDtB,EAAA,iBAAiB,eAAgBsB,CAAa,EAC9CtB,EAAA,iBAAiB,oBAAqBsB,CAAa,EACxD,EAAG,CAAE,CAAA,EAEGM,EAAA9B,EAAc,SAAd,CAAuB,MAAAyB,EAAe,SAAAjB,CAAS,CAAA,CACxD"}
package/dist/types.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ //# sourceMappingURL=types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,103 @@
1
+ import { IdTokenClaims } from '@strivacity/sdk-core';
2
+ import { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';
3
+ import { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';
4
+ export type Children = React.ReactElement | React.ReactNode | Array<React.ReactElement | React.ReactNode>;
5
+ /**
6
+ * Represents the session state, including authentication details and token information.
7
+ */
8
+ export type Session = {
9
+ /**
10
+ * Indicates if the session is being loaded.
11
+ */
12
+ loading: boolean;
13
+ /**
14
+ * Indicates whether the user is authenticated.
15
+ */
16
+ isAuthenticated: boolean;
17
+ /**
18
+ * Claims from the ID token or `null` if not available.
19
+ */
20
+ idTokenClaims: IdTokenClaims | null;
21
+ /**
22
+ * The access token or `null` if not available.
23
+ */
24
+ accessToken: string | null;
25
+ /**
26
+ * The refresh token or `null` if not available.
27
+ */
28
+ refreshToken: string | null;
29
+ /**
30
+ * Indicates if the access token has expired.
31
+ */
32
+ accessTokenExpired: boolean;
33
+ /**
34
+ * Expiration date of the access token or `null` if not set.
35
+ */
36
+ accessTokenExpirationDate: number | null;
37
+ };
38
+ /**
39
+ * Represents the available authentication flows and operations for Popup-based interactions.
40
+ */
41
+ export type PopupSDK = {
42
+ /**
43
+ * Initiates the login process using a popup window.
44
+ */
45
+ login: InstanceType<typeof PopupFlow>['login'];
46
+ /**
47
+ * Registers a new user using a popup flow.
48
+ */
49
+ register: InstanceType<typeof PopupFlow>['register'];
50
+ /**
51
+ * Refreshes the user's session using a popup.
52
+ */
53
+ refresh: InstanceType<typeof PopupFlow>['refresh'];
54
+ /**
55
+ * Revokes the current session tokens using a popup flow.
56
+ */
57
+ revoke: InstanceType<typeof PopupFlow>['revoke'];
58
+ /**
59
+ * Logs out the user using a popup window.
60
+ */
61
+ logout: InstanceType<typeof PopupFlow>['logout'];
62
+ /**
63
+ * Handles the callback after a popup-based authentication or token exchange.
64
+ */
65
+ handleCallback: InstanceType<typeof PopupFlow>['handleCallback'];
66
+ };
67
+ /**
68
+ * Represents the available authentication flows and operations for Redirect-based interactions.
69
+ */
70
+ export type RedirectSDK = {
71
+ /**
72
+ * Initiates the login process by redirecting the user to the identity provider.
73
+ */
74
+ login: InstanceType<typeof RedirectFlow>['login'];
75
+ /**
76
+ * Registers a new user using a redirect flow.
77
+ */
78
+ register: InstanceType<typeof RedirectFlow>['register'];
79
+ /**
80
+ * Refreshes the user's session using a redirect flow.
81
+ */
82
+ refresh: InstanceType<typeof RedirectFlow>['refresh'];
83
+ /**
84
+ * Revokes the current session tokens using a redirect flow.
85
+ */
86
+ revoke: InstanceType<typeof RedirectFlow>['revoke'];
87
+ /**
88
+ * Logs out the user by redirecting to the logout page.
89
+ */
90
+ logout: InstanceType<typeof RedirectFlow>['logout'];
91
+ /**
92
+ * Handles the callback after a redirect-based authentication or token exchange.
93
+ */
94
+ handleCallback: InstanceType<typeof RedirectFlow>['handleCallback'];
95
+ };
96
+ /**
97
+ * Represents a combined context for Popup-based flows, containing both the Popup SDK and the session state.
98
+ */
99
+ export type PopupContext = PopupSDK & Session;
100
+ /**
101
+ * Represents a combined context for Redirect-based flows, containing both the Redirect SDK and the session state.
102
+ */
103
+ export type RedirectContext = RedirectSDK & Session;
package/dist/types.mjs ADDED
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@strivacity/sdk-react",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "Strivacity React SDK client",
7
+ "author": "strivacity <info@strivacity.com>",
8
+ "dependencies": {
9
+ "@strivacity/sdk-core": "1.0.0"
10
+ },
11
+ "peerDependencies": {
12
+ "react": ">=18"
13
+ },
14
+ "main": "./dist/index.cjs",
15
+ "module": "./dist/index.mjs",
16
+ "types": "./dist/index.d.ts"
17
+ }