@descope/react-sdk 0.1.3 → 1.0.1
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/README.md +25 -11
- package/dist/cjs/index.cjs.js +1 -1
- package/dist/cjs/index.cjs.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/package.json +12 -12
package/README.md
CHANGED
|
@@ -74,13 +74,13 @@ const App = () => {
|
|
|
74
74
|
// debug can be set to true to enable debug mode
|
|
75
75
|
// debug={true}
|
|
76
76
|
|
|
77
|
-
//
|
|
77
|
+
// tenant ID for SSO (SAML) login. If not provided, Descope will use the domain of available email to choose the tenant
|
|
78
78
|
// tenant=<tenantId>
|
|
79
79
|
|
|
80
80
|
// Redirect URL for OAuth and SSO (will be used when redirecting back from the OAuth provider / IdP), or for "Magic Link" and "Enchanted Link" (will be used as a link in the message sent to the the user)
|
|
81
81
|
// redirectUrl=<redirectUrl>
|
|
82
82
|
|
|
83
|
-
//
|
|
83
|
+
// autoFocus can be true, false or "skipFirstScreen". Default is true.
|
|
84
84
|
// - true: automatically focus on the first input of each screen
|
|
85
85
|
// - false: do not automatically focus on screen's inputs
|
|
86
86
|
// - "skipFirstScreen": automatically focus on the first input of each screen, except first screen
|
|
@@ -228,15 +228,17 @@ npm i && npm start
|
|
|
228
228
|
|
|
229
229
|
See the following table for customization environment variables for the example app:
|
|
230
230
|
|
|
231
|
-
| Env Variable | Description
|
|
232
|
-
| ----------------------- |
|
|
233
|
-
| DESCOPE_FLOW_ID | Which flow
|
|
234
|
-
| DESCOPE_BASE_URL | Custom Descope base URL
|
|
235
|
-
| DESCOPE_THEME |
|
|
236
|
-
|
|
|
237
|
-
|
|
|
238
|
-
|
|
|
239
|
-
|
|
|
231
|
+
| Env Variable | Description | Default value |
|
|
232
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------- | ----------------- |
|
|
233
|
+
| DESCOPE_FLOW_ID | Which flow ID to use in the login page | **sign-up-or-in** |
|
|
234
|
+
| DESCOPE_BASE_URL | Custom Descope base URL | None |
|
|
235
|
+
| DESCOPE_THEME | Flow theme | None |
|
|
236
|
+
| DESCOPE_REDIRECT_URL | Flow redirect URL for OAuth/SSO/Magic Link/Enchanted Link | None |
|
|
237
|
+
| DESCOPE_TENANT_ID | Flow tenant ID for SSO/SAML | None |
|
|
238
|
+
| DESCOPE_DEBUG_MODE | **"true"** - Enable debugger</br>**"false"** - Disable flow debugger | None |
|
|
239
|
+
| DESCOPE_STEP_UP_FLOW_ID | Step up flow ID to show to logged in user (via button). e.g. "step-up". Button will be hidden if not provided | None |
|
|
240
|
+
| DESCOPE_TELEMETRY_KEY | **String** - Telemetry public key provided by Descope Inc | None |
|
|
241
|
+
| | | |
|
|
240
242
|
|
|
241
243
|
Example for `.env` file template:
|
|
242
244
|
|
|
@@ -249,6 +251,10 @@ DESCOPE_FLOW_ID=""
|
|
|
249
251
|
DESCOPE_BASE_URL=""
|
|
250
252
|
# Set flow theme to dark
|
|
251
253
|
DESCOPE_THEME=dark
|
|
254
|
+
# Flow Redirect URL
|
|
255
|
+
DESCOPE_REDIRECT_URL=""
|
|
256
|
+
# Tenant ID
|
|
257
|
+
DESCOPE_TENANT_ID=""
|
|
252
258
|
# Enable debugger
|
|
253
259
|
DESCOPE_DEBUG_MODE=true
|
|
254
260
|
# Show step-up flow for logged in user
|
|
@@ -257,6 +263,14 @@ DESCOPE_STEP_UP_FLOW_ID=step-up
|
|
|
257
263
|
DESCOPE_TELEMETRY_KEY=""
|
|
258
264
|
```
|
|
259
265
|
|
|
266
|
+
## Helper Functions
|
|
267
|
+
|
|
268
|
+
You can also use the following functions to assist with various actions managing your JWT.
|
|
269
|
+
|
|
270
|
+
`refresh(token = getRefreshToken())` - Force a refresh on current session token using an existing valid refresh token.
|
|
271
|
+
`getJwtRoles(token = getSessionToken(), tenant = '')` - Get current roles from an existing session token. Provide tenant id for specific tenant roles.
|
|
272
|
+
`getJwtPermissions(token = getSessionToken(), tenant = '')` - Fet current permissions from an existing session token. Provide tenant id for specific tenant permissions.
|
|
273
|
+
|
|
260
274
|
## Learn More
|
|
261
275
|
|
|
262
276
|
To learn more please see the [Descope Documentation and API reference page](https://docs.descope.com/).
|
package/dist/cjs/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function o(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var r=s(e),n=s(t);const u=r.default.createContext(void 0),i=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},a=e=>(...t)=>{let s;try{s=e(...t)}catch(e){console.error(e)}return s},l={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.1
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function o(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var r=s(e),n=s(t);const u=r.default.createContext(void 0),i=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},a=e=>(...t)=>{let s;try{s=e(...t)}catch(e){console.error(e)}return s},l={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.1"},c="undefined"!=typeof window;let d;const f=e=>{const t=n.default({...e,persistTokens:c,autoRefresh:c});return d=t,t};d=f({projectId:"temp pid"});const p=()=>c?d?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),g=()=>c?d?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),h=a(((e=p(),t)=>d?.getJwtPermissions(e,t))),k=a(((e=p(),t)=>d?.getJwtRoles(e,t)));const m=({projectId:t,baseUrl:s,sessionTokenViaCookie:o,children:n})=>{const[a,c]=e.useState(),[d,p]=e.useState(),[g,h]=e.useState(!1),[k,m]=e.useState(!1),b=(({projectId:t,baseUrl:s,sessionTokenViaCookie:o})=>e.useMemo((()=>{if(t)return f({projectId:t,baseUrl:s,sessionTokenViaCookie:o,baseHeaders:l,persistToken:!0,autoRefresh:!0})}),[t,s,o]))({projectId:t,baseUrl:s,sessionTokenViaCookie:o});e.useEffect((()=>{if(b){const e=b.onSessionTokenChange(p),t=b.onUserChange(c);return()=>{e(),t()}}}),[b]);const w=e.useCallback((()=>{m(!0),i(b?.refresh)().then((()=>{m(!1)}))}),[b]),S=e.useCallback((()=>{h(!0),i(b.me)().then((()=>{h(!1)}))}),[b]),v=e.useCallback(i(b?.logoutAll),[b]),U=e.useCallback(i(b?.logout),[b]),y=e.useMemo((()=>({fetchUser:S,user:a,isUserLoading:g,fetchSession:w,session:d,isSessionLoading:k,logout:U,logoutAll:v,projectId:t,baseUrl:s,setUser:c,setSession:p,sdk:b})),[S,a,g,w,d,k,U,v,t,s,c,p,b]);return r.default.createElement(u.Provider,{value:y},n)};m.defaultProps={baseUrl:"",children:void 0,sessionTokenViaCookie:!1};const b=e.lazy((async()=>((await Promise.resolve().then((function(){return o(require("@descope/web-component"))}))).default.sdkConfigOverrides={baseHeaders:l},{default:({projectId:e,flowId:t,baseUrl:s,innerRef:o,tenant:n,theme:u,debug:i,telemetryKey:a,redirectUrl:l,autoFocus:c})=>r.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":s,ref:o,tenant:n,theme:u,debug:i,telemetryKey:a,"redirect-url":l,"auto-focus":c})}))),w=r.default.forwardRef((({flowId:t,onSuccess:s,onError:o,tenant:n,theme:i,debug:a,telemetryKey:l,redirectUrl:c,autoFocus:d},f)=>{const[p,g]=e.useState(null);e.useImperativeHandle(f,(()=>p));const{projectId:h,baseUrl:k,setUser:m,setSession:w,sdk:S}=r.default.useContext(u),v=e.useCallback((async e=>{m(e.detail?.user);const t=e.detail?.sessionJwt;w(t),await S.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),s&&s(e)}),[m,w,s]);return e.useEffect((()=>{const e=p;return e?.addEventListener("success",v),o&&e?.addEventListener("error",o),()=>{o&&e?.removeEventListener("error",o),e?.removeEventListener("success",v)}}),[p,o,v]),r.default.createElement("form",null,r.default.createElement(e.Suspense,{fallback:null},r.default.createElement(b,{projectId:h,flowId:t,baseUrl:k,innerRef:g,tenant:n,theme:i,debug:a,telemetryKey:l,redirectUrl:c,autoFocus:d})))}));w.defaultProps={onError:void 0,onSuccess:void 0};var S=()=>{const t=e.useContext(u);if(!t)throw Error("You can only use this hook in the context of <AuthProvider />");return t};exports.AuthProvider=m,exports.Descope=w,exports.SignInFlow=e=>r.default.createElement(w,{...e,flowId:"sign-in"}),exports.SignUpFlow=e=>r.default.createElement(w,{...e,flowId:"sign-up"}),exports.SignUpOrInFlow=e=>r.default.createElement(w,{...e,flowId:"sign-up-or-in"}),exports.getJwtPermissions=h,exports.getJwtRoles=k,exports.getRefreshToken=g,exports.getSessionToken=p,exports.refresh=(e=g())=>d?.refresh(e),exports.useDescope=()=>{const{logout:t,logoutAll:s}=S();return e.useMemo((()=>({logoutAll:s,logout:t})),[s,t])},exports.useSession=()=>{const{session:t,isSessionLoading:s,fetchSession:o}=S(),r=e.useRef(s);return e.useMemo((()=>{r.current=s}),[s]),e.useMemo((()=>{t||s||(r.current=!0)}),[o]),e.useEffect((()=>{t||s||o()}),[o]),{isSessionLoading:r.current,sessionToken:t,isAuthenticated:!!t}},exports.useUser=()=>{const{user:t,fetchUser:s,isUserLoading:o,session:r}=S(),[n,u]=e.useState(!1),i=e.useRef(o),a=e.useMemo((()=>!t&&!o&&r&&!n),[s,r,n]);return e.useMemo((()=>{i.current=o}),[o]),e.useMemo((()=>{a&&(i.current=!0)}),[a]),e.useEffect((()=>{a&&(u(!0),s())}),[a]),{isUserLoading:i.current,user:t}};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../../src/hooks/Context.ts","../../src/utils.ts","../../src/constants.ts","../../src/sdk.ts","../../src/components/AuthProvider/AuthProvider.tsx","../../src/components/AuthProvider/useSdk.ts","../../src/components/Descope.tsx","../../src/hooks/useContext.ts","../../src/components/DefaultFlows.tsx","../../src/hooks/useDescope.ts","../../src/hooks/useSession.ts","../../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie,\n\tchildren\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst fetchSession = useCallback(() => {\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nAuthProvider.defaultProps = {\n\tbaseUrl: '',\n\tchildren: undefined,\n\tsessionTokenViaCookie: false\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[setUser, setSession, onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nDescope.defaultProps = {\n\tonError: undefined,\n\tonSuccess: undefined\n};\n\nexport default Descope;\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useMemo } from 'react';\nimport { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getJwtPermissions","token","tenant","getJwtRoles","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","fetchSession","useCallback","refresh","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","Promise","resolve","_interopNamespace","require","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","ctx","props","getRefreshToken","isLoading","useRef","current","sessionToken","isAuthenticated","isInit","setIsInit","shouldFetchUser"],"mappings":"qfAGA,MAAMA,EAAUC,EAAAA,QAAMC,mBAAwBC,GCEjCC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EAAK,EAGPE,EACcH,GAC1B,IAAIC,KACH,IAAIG,EACJ,IACCA,EA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,MAAMiC,OAAEA,EAAMD,UAAEA,GAAc6B,IAE9B,OAAO3C,EAAOA,SACb,KAAO,CACNc,YACAC,YAED,CAACD,EAAWC,GACZ,qBCViB,KAClB,MAAMrB,QAAEA,EAAOI,iBAAEA,EAAgBU,aAAEA,GAAiBmC,IAI9CmB,EAAYC,SAAOjE,GAoBzB,OAjBAE,EAAAA,SAAQ,KACP8D,EAAUE,QAAUlE,CAAgB,GAClC,CAACA,IAGJE,EAAAA,SAAQ,KACFN,GAAYI,IAChBgE,EAAUE,SAAU,EACpB,GACC,CAACxD,IAEJL,EAAAA,WAAU,KACJT,GAAYI,GAChBU,GACA,GACC,CAACA,IAEG,CACNV,iBAAkBgE,EAAUE,QAC5BC,aAAcvE,EACdwE,kBAAmBxE,EACnB,kBC7Bc,KACf,MAAMH,KAAEA,EAAIqB,UAAEA,EAAShB,cAAEA,EAAaF,QAAEA,GAAYiD,KAC7CwB,EAAQC,GAAa3E,EAAQA,UAAC,GAI/BqE,EAAYC,SAAOnE,GAEnByE,EAAkBrE,EAAOA,SAC9B,KAAOT,IAASK,GAAiBF,IAAYyE,GAC7C,CAACvD,EAAWlB,EAASyE,IAsBtB,OAlBAnE,EAAAA,SAAQ,KACP8D,EAAUE,QAAUpE,CAAa,GAC/B,CAACA,IAGJI,EAAAA,SAAQ,KACHqE,IACHP,EAAUE,SAAU,EACpB,GACC,CAACK,IAEJlE,EAAAA,WAAU,KACLkE,IACHD,GAAU,GACVxD,IACA,GACC,CAACyD,IAEG,CAAEzE,cAAekE,EAAUE,QAASzE,OAAM"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../../src/hooks/Context.ts","../../src/utils.ts","../../src/constants.ts","../../src/sdk.ts","../../src/components/AuthProvider/AuthProvider.tsx","../../src/components/AuthProvider/useSdk.ts","../../src/components/Descope.tsx","../../src/hooks/useContext.ts","../../src/components/DefaultFlows.tsx","../../src/hooks/useDescope.ts","../../src/hooks/useSession.ts","../../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie,\n\tchildren\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst fetchSession = useCallback(() => {\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nAuthProvider.defaultProps = {\n\tbaseUrl: '',\n\tchildren: undefined,\n\tsessionTokenViaCookie: false\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[setUser, setSession, onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nDescope.defaultProps = {\n\tonError: undefined,\n\tonSuccess: undefined\n};\n\nexport default Descope;\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useMemo } from 'react';\nimport { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","fetchSession","useCallback","refresh","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","Promise","resolve","_interopNamespace","require","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","ctx","props","isLoading","useRef","current","sessionToken","isAuthenticated","isInit","setIsInit","shouldFetchUser"],"mappings":"qfAGA,MAAMA,EAAUC,EAAAA,QAAMC,mBAAwBC,GCEjCC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EAAK,EAGPE,EACcH,GAC1B,IAAIC,KACH,IAAIG,EACJ,IACCA,EAAMJ,KAAMC,EAGZ,CAFC,MAAOI,GACRC,QAAQC,MAAMF,EACd,CACD,OAAOD,CAAG,ECtBCI,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,SAIbC,EAA+B,oBAAXC,OCJjC,IAAIC,EAEJ,MAAMC,EACLC,IAEA,MAAMC,EAAMC,EAAAA,QAAU,IAClBF,EACHG,cAAeP,EACfQ,YAAaR,IAId,OAFAE,EAAcG,EAEPA,CAAG,EAUXH,EAAcC,EAAiB,CAAEM,UAAW,aAErC,MAAMC,EAAkB,IAC1BV,EACIE,GAAaQ,mBAIrBb,QAAQc,KAAK,6CACN,IAGKC,EAAkB,IAC1BZ,EACIE,GAAaU,mBAGrBf,QAAQc,KAAK,6CACN,IAGKE,EAAoBnB,GAChC,CAACoB,EAAQJ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EACduE,kBAAmBvE,EACnB,kBC7Bc,KACf,MAAMH,KAAEA,EAAIqB,UAAEA,EAAShB,cAAEA,EAAaF,QAAEA,GAAYiD,KAC7CuB,EAAQC,GAAa1E,EAAQA,UAAC,GAI/BoE,EAAYC,SAAOlE,GAEnBwE,EAAkBpE,EAAOA,SAC9B,KAAOT,IAASK,GAAiBF,IAAYwE,GAC7C,CAACtD,EAAWlB,EAASwE,IAsBtB,OAlBAlE,EAAAA,SAAQ,KACP6D,EAAUE,QAAUnE,CAAa,GAC/B,CAACA,IAGJI,EAAAA,SAAQ,KACHoE,IACHP,EAAUE,SAAU,EACpB,GACC,CAACK,IAEJjE,EAAAA,WAAU,KACLiE,IACHD,GAAU,GACVvD,IACA,GACC,CAACwD,IAEG,CAAExE,cAAeiE,EAAUE,QAASxE,OAAM"}
|
package/dist/index.d.ts
CHANGED
|
@@ -38,6 +38,7 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
38
38
|
};
|
|
39
39
|
cookiePolicy?: RequestCredentials;
|
|
40
40
|
baseHeaders?: HeadersInit;
|
|
41
|
+
fetch?: typeof fetch;
|
|
41
42
|
}, "hooks"> & {
|
|
42
43
|
hooks?: {
|
|
43
44
|
beforeRequest?: ((config: _descope_core_js_sdk.RequestConfig) => _descope_core_js_sdk.RequestConfig) | ((config: _descope_core_js_sdk.RequestConfig) => _descope_core_js_sdk.RequestConfig)[];
|
|
@@ -621,6 +622,7 @@ declare const getSessionToken: () => string;
|
|
|
621
622
|
declare const getRefreshToken: () => string;
|
|
622
623
|
declare const getJwtPermissions: (token?: any, tenant?: string) => string[];
|
|
623
624
|
declare const getJwtRoles: (token?: any, tenant?: string) => string[];
|
|
625
|
+
declare const refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
624
626
|
|
|
625
627
|
declare global {
|
|
626
628
|
namespace JSX {
|
|
@@ -674,4 +676,4 @@ declare const useUser: () => {
|
|
|
674
676
|
user: _descope_core_js_sdk.UserResponse;
|
|
675
677
|
};
|
|
676
678
|
|
|
677
|
-
export { AuthProvider, Descope, SignInFlow, SignUpFlow, SignUpOrInFlow, getJwtPermissions, getJwtRoles, getRefreshToken, getSessionToken, useDescope, useSession, useUser };
|
|
679
|
+
export { AuthProvider, Descope, SignInFlow, SignUpFlow, SignUpOrInFlow, getJwtPermissions, getJwtRoles, getRefreshToken, getSessionToken, refresh, useDescope, useSession, useUser };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{useMemo as t,useState as o,useEffect as s,useCallback as r,lazy as n,useImperativeHandle as i,Suspense as c,useContext as a,useRef as l}from"react";import u from"@descope/web-js-sdk";const d=e.createContext(void 0),f=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},p=e=>(...t)=>{let o;try{o=e(...t)}catch(e){console.error(e)}return o},h={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.1
|
|
1
|
+
import e,{useMemo as t,useState as o,useEffect as s,useCallback as r,lazy as n,useImperativeHandle as i,Suspense as c,useContext as a,useRef as l}from"react";import u from"@descope/web-js-sdk";const d=e.createContext(void 0),f=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},p=e=>(...t)=>{let o;try{o=e(...t)}catch(e){console.error(e)}return o},h={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.1"},m="undefined"!=typeof window;let g;const k=e=>{const t=u({...e,persistTokens:m,autoRefresh:m});return g=t,t};g=k({projectId:"temp pid"});const w=()=>m?g?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),U=()=>m?g?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=p(((e=w(),t)=>g?.getJwtPermissions(e,t))),v=p(((e=w(),t)=>g?.getJwtRoles(e,t))),y=(e=U())=>g?.refresh(e);const E=({projectId:n,baseUrl:i,sessionTokenViaCookie:c,children:a})=>{const[l,u]=o(),[p,m]=o(),[g,w]=o(!1),[U,b]=o(!1),v=(({projectId:e,baseUrl:o,sessionTokenViaCookie:s})=>t((()=>{if(e)return k({projectId:e,baseUrl:o,sessionTokenViaCookie:s,baseHeaders:h,persistToken:!0,autoRefresh:!0})}),[e,o,s]))({projectId:n,baseUrl:i,sessionTokenViaCookie:c});s((()=>{if(v){const e=v.onSessionTokenChange(m),t=v.onUserChange(u);return()=>{e(),t()}}}),[v]);const y=r((()=>{b(!0),f(v?.refresh)().then((()=>{b(!1)}))}),[v]),E=r((()=>{w(!0),f(v.me)().then((()=>{w(!1)}))}),[v]),I=r(f(v?.logoutAll),[v]),S=r(f(v?.logout),[v]),j=t((()=>({fetchUser:E,user:l,isUserLoading:g,fetchSession:y,session:p,isSessionLoading:U,logout:S,logoutAll:I,projectId:n,baseUrl:i,setUser:u,setSession:m,sdk:v})),[E,l,g,y,p,U,S,I,n,i,u,m,v]);return e.createElement(d.Provider,{value:j},a)};E.defaultProps={baseUrl:"",children:void 0,sessionTokenViaCookie:!1};const I=n((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:h},{default:({projectId:t,flowId:o,baseUrl:s,innerRef:r,tenant:n,theme:i,debug:c,telemetryKey:a,redirectUrl:l,autoFocus:u})=>e.createElement("descope-wc",{"project-id":t,"flow-id":o,"base-url":s,ref:r,tenant:n,theme:i,debug:c,telemetryKey:a,"redirect-url":l,"auto-focus":u})}))),S=e.forwardRef((({flowId:t,onSuccess:n,onError:a,tenant:l,theme:u,debug:f,telemetryKey:p,redirectUrl:h,autoFocus:m},g)=>{const[k,w]=o(null);i(g,(()=>k));const{projectId:U,baseUrl:b,setUser:v,setSession:y,sdk:E}=e.useContext(d),S=r((async e=>{v(e.detail?.user);const t=e.detail?.sessionJwt;y(t),await E.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[v,y,n]);return s((()=>{const e=k;return e?.addEventListener("success",S),a&&e?.addEventListener("error",a),()=>{a&&e?.removeEventListener("error",a),e?.removeEventListener("success",S)}}),[k,a,S]),e.createElement("form",null,e.createElement(c,{fallback:null},e.createElement(I,{projectId:U,flowId:t,baseUrl:b,innerRef:w,tenant:l,theme:u,debug:f,telemetryKey:p,redirectUrl:h,autoFocus:m})))}));S.defaultProps={onError:void 0,onSuccess:void 0};const j=t=>e.createElement(S,{...t,flowId:"sign-in"}),C=t=>e.createElement(S,{...t,flowId:"sign-up"}),R=t=>e.createElement(S,{...t,flowId:"sign-up-or-in"});var T=()=>{const e=a(d);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const L=()=>{const{logout:e,logoutAll:o}=T();return t((()=>({logoutAll:o,logout:e})),[o,e])},x=()=>{const{session:e,isSessionLoading:o,fetchSession:r}=T(),n=l(o);return t((()=>{n.current=o}),[o]),t((()=>{e||o||(n.current=!0)}),[r]),s((()=>{e||o||r()}),[r]),{isSessionLoading:n.current,sessionToken:e,isAuthenticated:!!e}},A=()=>{const{user:e,fetchUser:r,isUserLoading:n,session:i}=T(),[c,a]=o(!1),u=l(n),d=t((()=>!e&&!n&&i&&!c),[r,i,c]);return t((()=>{u.current=n}),[n]),t((()=>{d&&(u.current=!0)}),[d]),s((()=>{d&&(a(!0),r())}),[d]),{isUserLoading:u.current,user:e}};export{E as AuthProvider,S as Descope,j as SignInFlow,C as SignUpFlow,R as SignUpOrInFlow,b as getJwtPermissions,v as getJwtRoles,U as getRefreshToken,w as getSessionToken,y as refresh,L as useDescope,x as useSession,A as useUser};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/hooks/Context.ts","../src/utils.ts","../src/constants.ts","../src/sdk.ts","../src/components/AuthProvider/AuthProvider.tsx","../src/components/AuthProvider/useSdk.ts","../src/components/Descope.tsx","../src/components/DefaultFlows.tsx","../src/hooks/useContext.ts","../src/hooks/useDescope.ts","../src/hooks/useSession.ts","../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie,\n\tchildren\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst fetchSession = useCallback(() => {\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nAuthProvider.defaultProps = {\n\tbaseUrl: '',\n\tchildren: undefined,\n\tsessionTokenViaCookie: false\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[setUser, setSession, onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nDescope.defaultProps = {\n\tonError: undefined,\n\tonSuccess: undefined\n};\n\nexport default Descope;\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","fetchSession","useCallback","refresh","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","useDescope","useSession","isLoading","useRef","current","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"iMAGA,MAAMA,EAAUC,EAAMC,mBAAwBC,GCEjCC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EAAK,EAGPE,EACcH,GAC1B,IAAIC,KACH,IAAIG,EACJ,IACCA,EAAMJ,KAAMC,EAGZ,CAFC,MAAOI,GACRC,QAAQC,MAAMF,EACd,CACD,OAAOD,CAAG,ECtBCI,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,SAIbC,EAA+B,oBAAXC,OCJjC,IAAIC,EAEJ,MAAMC,EACLC,IAEA,MAAMC,EAAMC,EAAU,IAClBF,EACHG,cAAeP,EACfQ,YAAaR,IAId,OAFAE,EAAcG,EAEPA,CAAG,EAUXH,EAAcC,EAAiB,CAAEM,UAAW,aAErC,MAAMC,EAAkB,IAC1BV,EACIE,GAAaQ,mBAIrBb,QAAQc,KAAK,6CACN,IAGKC,EAAkB,IAC1BZ,EACIE,GAAaU,mBAGrBf,QAAQc,KAAK,6CACN,IAGKE,EAAoBnB,G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K,GAAiBF,IAAY2E,GAC7C,CAACzD,EAAWlB,EAAS2E,IAsBtB,OAlBArE,GAAQ,KACP+D,EAAUE,QAAUrE,CAAa,GAC/B,CAACA,IAGJI,GAAQ,KACHuE,IACHR,EAAUE,SAAU,EACpB,GACC,CAACM,IAEJpE,GAAU,KACLoE,IACHD,GAAU,GACV1D,IACA,GACC,CAAC2D,IAEG,CAAE3E,cAAemE,EAAUE,QAAS1E,OAAM"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/hooks/Context.ts","../src/utils.ts","../src/constants.ts","../src/sdk.ts","../src/components/AuthProvider/AuthProvider.tsx","../src/components/AuthProvider/useSdk.ts","../src/components/Descope.tsx","../src/components/DefaultFlows.tsx","../src/hooks/useContext.ts","../src/hooks/useDescope.ts","../src/hooks/useSession.ts","../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie,\n\tchildren\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst fetchSession = useCallback(() => {\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tlogout,\n\t\t\tlogoutAll,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nAuthProvider.defaultProps = {\n\tbaseUrl: '',\n\tchildren: undefined,\n\tsessionTokenViaCookie: false\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[setUser, setSession, onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nDescope.defaultProps = {\n\tonError: undefined,\n\tonSuccess: undefined\n};\n\nexport default Descope;\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","refresh","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","fetchSession","useCallback","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","useDescope","useSession","isLoading","useRef","current","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"iMAGA,MAAMA,EAAUC,EAAMC,mBAAwBC,GCEjCC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EA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YACAC,YAED,CAACD,EAAWC,GACZ,ECVI+C,EAAa,KAClB,MAAMnE,QAAEA,EAAOI,iBAAEA,EAAgBU,aAAEA,GAAiB+B,IAI9CuB,EAAYC,EAAOjE,GAoBzB,OAjBAE,GAAQ,KACP8D,EAAUE,QAAUlE,CAAgB,GAClC,CAACA,IAGJE,GAAQ,KACFN,GAAYI,IAChBgE,EAAUE,SAAU,EACpB,GACC,CAACxD,IAEJL,GAAU,KACJT,GAAYI,GAChBU,GACA,GACC,CAACA,IAEG,CACNV,iBAAkBgE,EAAUE,QAC5BC,aAAcvE,EACdwE,kBAAmBxE,EACnB,EC7BIyE,EAAU,KACf,MAAM5E,KAAEA,EAAIoB,UAAEA,EAASf,cAAEA,EAAaF,QAAEA,GAAY6C,KAC7C6B,EAAQC,GAAa5E,GAAS,GAI/BqE,EAAYC,EAAOnE,GAEnB0E,EAAkBtE,GACvB,KAAOT,IAASK,GAAiBF,IAAY0E,GAC7C,CAACzD,EAAWjB,EAAS0E,IAsBtB,OAlBApE,GAAQ,KACP8D,EAAUE,QAAUpE,CAAa,GAC/B,CAACA,IAGJI,GAAQ,KACHsE,IACHR,EAAUE,SAAU,EACpB,GACC,CAACM,IAEJnE,GAAU,KACLmE,IACHD,GAAU,GACV1D,IACA,GACC,CAAC2D,IAEG,CAAE1E,cAAekE,EAAUE,QAASzE,OAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@descope/react-sdk",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "Descope React SDK",
|
|
5
5
|
"author": "Descope Team <info@descope.com>",
|
|
6
6
|
"homepage": "https://github.com/descope/react-sdk",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"type": "git",
|
|
13
13
|
"url": "https://github.com/descope/react-sdk.git"
|
|
14
14
|
},
|
|
15
|
-
"license": "
|
|
15
|
+
"license": "MIT",
|
|
16
16
|
"type": "module",
|
|
17
17
|
"exports": {
|
|
18
18
|
"require": "./dist/cjs/index.cjs.js",
|
|
@@ -42,28 +42,28 @@
|
|
|
42
42
|
]
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@descope/web-component": "0.
|
|
46
|
-
"react-router-dom": "6.8.
|
|
45
|
+
"@descope/web-component": "2.0.5",
|
|
46
|
+
"react-router-dom": "6.8.2"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@babel/core": "7.
|
|
49
|
+
"@babel/core": "7.21.0",
|
|
50
50
|
"@babel/preset-env": "7.20.2",
|
|
51
51
|
"@babel/preset-react": "7.18.6",
|
|
52
|
-
"@babel/preset-typescript": "7.
|
|
52
|
+
"@babel/preset-typescript": "7.21.0",
|
|
53
53
|
"@open-wc/rollup-plugin-html": "^1.2.5",
|
|
54
54
|
"@rollup/plugin-commonjs": "^24.0.0",
|
|
55
55
|
"@rollup/plugin-node-resolve": "^15.0.0",
|
|
56
56
|
"@rollup/plugin-replace": "^5.0.0",
|
|
57
57
|
"@rollup/plugin-typescript": "^8.3.0",
|
|
58
58
|
"@testing-library/jest-dom": "5.16.5",
|
|
59
|
-
"@testing-library/react": "
|
|
59
|
+
"@testing-library/react": "14.0.0",
|
|
60
60
|
"@testing-library/user-event": "14.4.3",
|
|
61
61
|
"@types/jest": "^27.0.2",
|
|
62
|
-
"@types/react": "18.0.
|
|
63
|
-
"@types/react-dom": "18.0.
|
|
62
|
+
"@types/react": "18.0.28",
|
|
63
|
+
"@types/react-dom": "18.0.11",
|
|
64
64
|
"@types/react-router-dom": "^5.3.3",
|
|
65
65
|
"babel-jest": "27.5.1",
|
|
66
|
-
"eslint": "8.
|
|
66
|
+
"eslint": "8.35.0",
|
|
67
67
|
"eslint-config-airbnb": "19.0.4",
|
|
68
68
|
"eslint-config-airbnb-typescript": "17.0.0",
|
|
69
69
|
"eslint-config-prettier": "8.6.0",
|
|
@@ -81,7 +81,7 @@
|
|
|
81
81
|
"eslint-plugin-promise": "6.1.1",
|
|
82
82
|
"eslint-plugin-react": "7.32.2",
|
|
83
83
|
"eslint-plugin-react-hooks": "4.6.0",
|
|
84
|
-
"eslint-plugin-testing-library": "5.10.
|
|
84
|
+
"eslint-plugin-testing-library": "5.10.2",
|
|
85
85
|
"husky": "^8.0.1",
|
|
86
86
|
"jest": "^27.3.1",
|
|
87
87
|
"jest-extended": "^3.2.2",
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
"typescript": "^4.5.3"
|
|
105
105
|
},
|
|
106
106
|
"peerDependencies": {
|
|
107
|
-
"@descope/web-js-sdk": "0.
|
|
107
|
+
"@descope/web-js-sdk": "1.0.0",
|
|
108
108
|
"@types/react": ">=16",
|
|
109
109
|
"react": ">=16"
|
|
110
110
|
}
|