@descope/react-sdk 0.0.0-next-b00a100d-20251118 → 0.0.0-next-cddfa808-20251204

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +27 -4
  2. package/dist/cjs/components/AuthProvider/AuthProvider.js +1 -1
  3. package/dist/cjs/components/AuthProvider/AuthProvider.js.map +1 -1
  4. package/dist/cjs/components/Descope.js +1 -1
  5. package/dist/cjs/components/Descope.js.map +1 -1
  6. package/dist/cjs/constants.js +1 -1
  7. package/dist/cjs/hooks/useSession.js +1 -1
  8. package/dist/cjs/hooks/useSession.js.map +1 -1
  9. package/dist/cjs/utils.js +1 -1
  10. package/dist/cjs/utils.js.map +1 -1
  11. package/dist/esm/components/AuthProvider/AuthProvider.js +1 -1
  12. package/dist/esm/components/AuthProvider/AuthProvider.js.map +1 -1
  13. package/dist/esm/components/Descope.js +1 -1
  14. package/dist/esm/components/Descope.js.map +1 -1
  15. package/dist/esm/constants.js +1 -1
  16. package/dist/esm/hooks/useSession.js +1 -1
  17. package/dist/esm/hooks/useSession.js.map +1 -1
  18. package/dist/esm/utils.js +1 -1
  19. package/dist/esm/utils.js.map +1 -1
  20. package/dist/index.d.ts +9 -9
  21. package/dist/index.umd.js +2 -2
  22. package/dist/index.umd.js.map +1 -1
  23. package/dist/types/sdk.d.ts +27 -27
  24. package/dist/types/utils.d.ts +1 -0
  25. package/package.json +13 -13
  26. package/dist/cjs/node_modules/.pnpm/@rollup_plugin-typescript@11.1.6_rollup@4.22.4_tslib@2.8.1_typescript@5.4.5/node_modules/tslib/tslib.es6.js +0 -2
  27. package/dist/cjs/node_modules/.pnpm/@rollup_plugin-typescript@11.1.6_rollup@4.22.4_tslib@2.8.1_typescript@5.4.5/node_modules/tslib/tslib.es6.js.map +0 -1
  28. package/dist/esm/node_modules/.pnpm/@rollup_plugin-typescript@11.1.6_rollup@4.22.4_tslib@2.8.1_typescript@5.4.5/node_modules/tslib/tslib.es6.js +0 -2
  29. package/dist/esm/node_modules/.pnpm/@rollup_plugin-typescript@11.1.6_rollup@4.22.4_tslib@2.8.1_typescript@5.4.5/node_modules/tslib/tslib.es6.js.map +0 -1
package/README.md CHANGED
@@ -494,10 +494,7 @@ const AppRoot = () => {
494
494
  }, []);
495
495
 
496
496
  return (
497
- <AuthProvider
498
- projectId="my-project-id"
499
- getExternalToken={externalToken}
500
- >
497
+ <AuthProvider projectId="my-project-id" getExternalToken={externalToken}>
501
498
  <App />
502
499
  </AuthProvider>
503
500
  );
@@ -779,6 +776,32 @@ const AppRoot = () => {
779
776
  };
780
777
  ```
781
778
 
779
+ #### Using Inbound Apps as OIDC Provider
780
+
781
+ To use an inbound app as an OIDC provider, you must provide both the `issuer` and `clientId` configuration options. The `issuer` is the OIDC authority URL, and the `clientId` is the client ID for your inbound app.
782
+
783
+ > **Note:** When configuring an inbound app as an OIDC provider, you must obtain the issuer URL directly from the inbound app settings page in the Descope console. The issuer URL is specific to your inbound app configuration and cannot be constructed manually. In addition, you'll need to provide the client ID from the same inbound app settings.
784
+
785
+ ```js
786
+ <AuthProvider
787
+ projectId="my-project-id"
788
+ oidcConfig={{
789
+ // Required: Get this from your inbound app settings page
790
+ issuer: 'https://api.descope.com/v1/apps/<Project ID>',
791
+ // Required: Client ID from your inbound app settings
792
+ clientId: 'your-inbound-app-client-id',
793
+ // Optional: Custom redirect URI (defaults to current URL)
794
+ redirectUri: 'https://my-app.com/redirect',
795
+ // Optional: Custom scope (defaults to 'openid' when issuer is provided)
796
+ scope: 'openid profile email',
797
+ }}
798
+ >
799
+ <App />
800
+ </AuthProvider>
801
+ ```
802
+
803
+ When using a custom `issuer` (including inbound apps), the default scope is `'openid'` instead of the full Descope scope. You can override this by providing a custom `scope` value.
804
+
782
805
  ### Login
783
806
 
784
807
  Use the `oidc.loginWithRedirect` method from the `useDescope` hook to trigger the OIDC login. Example:
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("../../hooks/Context.js"),s=require("../../utils.js"),r=require("./useSdk.js");function o(e){return e&&e.__esModule?e:{default:e}}var n=o(e);exports.default=({projectId:o,baseUrl:a="",baseStaticUrl:i="",baseCdnUrl:u="",sessionTokenViaCookie:c=!1,hooks:d,persistTokens:l=!0,autoRefresh:h=!0,oidcConfig:f,storeLastAuthenticatedUser:k=!0,keepLastAuthenticatedUserAfterLogout:g=!1,refreshCookieName:S="",getExternalToken:U,customStorage:C,children:L})=>{const[A,m]=e.useState(),[p,b]=e.useState(),[j,v]=e.useState(),[T,I]=e.useState(!1),[x,E]=e.useState(!1),[R,q]=e.useState(!1),[N,V]=e.useState(!!f),_=e.useRef(!1),M=r.default({projectId:o,baseUrl:a,persistTokens:l,autoRefresh:h,sessionTokenViaCookie:c,hooks:d,oidcConfig:f,storeLastAuthenticatedUser:k,keepLastAuthenticatedUserAfterLogout:g,refreshCookieName:S,getExternalToken:U,customStorage:C});e.useEffect((()=>{if(M){const e=M.onSessionTokenChange(b),t=M.onUserChange(m),s=M.onIsAuthenticatedChange(I),r=M.onClaimsChange(v);return()=>{e(),t(),s(),r()}}}),[M]);const w=e.useRef(!1),y=e.useRef(!1);e.useEffect((()=>{M&&f&&!_.current&&(_.current=!0,M.oidc.finishLoginIfNeed().finally((()=>{V(!1),w.current=!0})))}),[]);const F=e.useCallback((()=>{w.current||(w.current=!0,q(!0),s.withValidation(null==M?void 0:M.refresh)(void 0,!0).then((()=>{q(!1)})))}),[M]),O=e.useCallback((()=>{y.current||(y.current=!0,E(!0),s.withValidation(M.me)().then((()=>{E(!1)})))}),[M]),P=e.useMemo((()=>({fetchUser:O,user:A,isUserLoading:x,isUserFetched:y.current,fetchSession:F,session:p,isAuthenticated:T,isSessionLoading:R,isOidcLoading:N,isSessionFetched:w.current,projectId:o,baseUrl:a,baseStaticUrl:i,baseCdnUrl:u,storeLastAuthenticatedUser:k,keepLastAuthenticatedUserAfterLogout:g,refreshCookieName:S,customStorage:C,setUser:m,setSession:b,setIsAuthenticated:I,claims:j,sdk:M})),[O,A,x,y.current,F,p,T,R,N,w.current,o,a,i,u,g,S,C,m,b,I,j,M]);return n.default.createElement(t.default.Provider,{value:P},L)};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("../../hooks/Context.js"),s=require("../../utils.js"),r=require("./useSdk.js");function o(e){return e&&e.__esModule?e:{default:e}}var n=o(e);exports.default=({projectId:o,baseUrl:a="",baseStaticUrl:i="",baseCdnUrl:u="",sessionTokenViaCookie:c=!1,hooks:d,persistTokens:l=!0,autoRefresh:h=!0,oidcConfig:f,storeLastAuthenticatedUser:k=!0,keepLastAuthenticatedUserAfterLogout:g=!1,refreshCookieName:S="",getExternalToken:U,customStorage:C,children:L})=>{const[p,A]=e.useState(),[m,b]=e.useState(),[j,v]=e.useState(),[T,I]=e.useState(!1),[x,E]=e.useState(!1),[R,q]=e.useState(!1),[N,V]=e.useState(!!f),_=e.useRef(!1),M=r.default({projectId:o,baseUrl:a,persistTokens:l,autoRefresh:h,sessionTokenViaCookie:c,hooks:d,oidcConfig:f,storeLastAuthenticatedUser:k,keepLastAuthenticatedUserAfterLogout:g,refreshCookieName:S,getExternalToken:U,customStorage:C});e.useEffect((()=>{if(M){const e=M.onSessionTokenChange(b),t=M.onUserChange(A),s=M.onIsAuthenticatedChange(I),r=M.onClaimsChange(v);return()=>{e(),t(),s(),r()}}}),[M]);const w=e.useRef(!1),y=e.useRef(!1);e.useEffect((()=>{M&&f&&!_.current&&(_.current=!0,M.oidc.finishLoginIfNeed().finally((()=>{V(!1),w.current=!0})))}),[]);const F=e.useCallback((()=>{s.isDescopeBridge()||w.current||(w.current=!0,q(!0),s.withValidation(null==M?void 0:M.refresh)(void 0,!0).then((()=>{q(!1)})))}),[M]),O=e.useCallback((()=>{y.current||(y.current=!0,E(!0),s.withValidation(M.me)().then((()=>{E(!1)})))}),[M]),P=e.useMemo((()=>({fetchUser:O,user:p,isUserLoading:x,isUserFetched:y.current,fetchSession:F,session:m,isAuthenticated:T,isSessionLoading:R,isOidcLoading:N,isSessionFetched:w.current,projectId:o,baseUrl:a,baseStaticUrl:i,baseCdnUrl:u,storeLastAuthenticatedUser:k,keepLastAuthenticatedUserAfterLogout:g,refreshCookieName:S,customStorage:C,setUser:A,setSession:b,setIsAuthenticated:I,claims:j,sdk:M})),[O,p,x,y.current,F,m,T,R,N,w.current,o,a,i,u,g,S,C,A,b,I,j,M]);return n.default.createElement(t.default.Provider,{value:P},L)};
2
2
  //# sourceMappingURL=AuthProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AuthProvider.js","sources":["../../../../src/components/AuthProvider/AuthProvider.tsx"],"sourcesContent":["import React, {\n FC,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { CookieConfig, OidcConfig } from '@descope/web-js-sdk';\nimport { Claims } from '@descope/core-js-sdk';\nimport { CustomStorage } from '@descope/web-component';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ntype Hooks = Parameters<typeof useSdk>[0]['hooks'];\n\ninterface IAuthProviderProps {\n projectId: string;\n baseUrl?: string;\n // allows to override the base URL that is used to fetch static files\n baseStaticUrl?: string;\n // allows to override the base URL that is used to fetch external script files\n baseCdnUrl?: string;\n // Default is true. If true, tokens will be stored on local storage and can accessed with getToken function\n persistTokens?: boolean;\n // Default is true. If true, the SDK will automatically refresh the session token when it is about to expire\n autoRefresh?: boolean;\n // If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n // stored on local storage and can accessed with getSessionToken function\n // Use this option if session token will stay small (less than 1k)\n // NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n sessionTokenViaCookie?: CookieConfig;\n hooks?: Hooks;\n // If truthy he SDK refresh and logout functions will use the OIDC client\n // Accepts boolean or OIDC configuration\n oidcConfig?: OidcConfig;\n // Default is true. If true, last authenticated user will be stored on local storage and can accessed with getUser function\n storeLastAuthenticatedUser?: boolean;\n // If true, last authenticated user will not be removed after logout\n keepLastAuthenticatedUserAfterLogout?: boolean;\n // Use this option if the authentication is done via cookie, and configured with a different name\n // Currently, this is done using Descope Flows\n refreshCookieName?: string;\n // Function to get external token, for seamless migration from external system\n getExternalToken?: () => Promise<string>;\n // Custom storage object for authentication related data\n customStorage?: CustomStorage;\n children?: React.ReactNode;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n projectId,\n baseUrl = '',\n baseStaticUrl = '',\n baseCdnUrl = '',\n sessionTokenViaCookie = false,\n hooks = undefined,\n persistTokens = true,\n autoRefresh = true,\n oidcConfig = undefined,\n storeLastAuthenticatedUser = true,\n keepLastAuthenticatedUserAfterLogout = false,\n refreshCookieName = '',\n getExternalToken = undefined,\n customStorage = undefined,\n children = undefined,\n}) => {\n const [user, setUser] = useState<User>();\n const [session, setSession] = useState<string>();\n const [claims, setClaims] = useState<Claims>();\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n\n const [isUserLoading, setIsUserLoading] = useState(false);\n const [isSessionLoading, setIsSessionLoading] = useState(false);\n\n // if oidc config is enabled, we attempt to finish the login, so we start as loading\n const [isOidcLoading, setIsOidcLoading] = useState(!!oidcConfig);\n const isOidcFinishedLogin = useRef(false);\n\n const sdk = useSdk({\n projectId,\n baseUrl,\n persistTokens,\n autoRefresh,\n sessionTokenViaCookie,\n hooks,\n oidcConfig,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n getExternalToken,\n customStorage,\n });\n\n useEffect(() => {\n if (sdk) {\n const unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n const unsubscribeUser = sdk.onUserChange(setUser);\n const unsubscribeIsAuthenticated =\n sdk.onIsAuthenticatedChange(setIsAuthenticated);\n const unsubscribeClaims = sdk.onClaimsChange(setClaims);\n\n return () => {\n unsubscribeSessionToken();\n unsubscribeUser();\n unsubscribeIsAuthenticated();\n unsubscribeClaims();\n };\n }\n return undefined;\n }, [sdk]);\n\n const isSessionFetched = useRef(false);\n const isUserFetched = useRef(false);\n\n // if oidc config is enabled, and we have oidc params in the url\n // we will finish the login (this should run only once)\n useEffect(() => {\n if (sdk && oidcConfig && !isOidcFinishedLogin.current) {\n isOidcFinishedLogin.current = true;\n sdk.oidc.finishLoginIfNeed().finally(() => {\n setIsOidcLoading(false);\n // We want that the session will fetched only once\n isSessionFetched.current = true;\n });\n }\n }, []);\n\n const fetchSession = useCallback(() => {\n // We want that the session will fetched only once\n if (isSessionFetched.current) return;\n isSessionFetched.current = true;\n\n setIsSessionLoading(true);\n withValidation(sdk?.refresh)(undefined, true).then(() => {\n setIsSessionLoading(false);\n });\n }, [sdk]);\n\n const fetchUser = useCallback(() => {\n // We want that the user will fetched only once\n if (isUserFetched.current) return;\n isUserFetched.current = true;\n\n setIsUserLoading(true);\n withValidation(sdk.me)().then(() => {\n setIsUserLoading(false);\n });\n }, [sdk]);\n\n const value = useMemo<IContext>(\n () => ({\n fetchUser,\n user,\n isUserLoading,\n isUserFetched: isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched: isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n }),\n [\n fetchUser,\n user,\n isUserLoading,\n isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n ],\n );\n return <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n"],"names":["projectId","baseUrl","baseStaticUrl","baseCdnUrl","sessionTokenViaCookie","hooks","persistTokens","autoRefresh","oidcConfig","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","getExternalToken","customStorage","children","user","setUser","useState","session","setSession","claims","setClaims","isAuthenticated","setIsAuthenticated","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","isOidcLoading","setIsOidcLoading","isOidcFinishedLogin","useRef","sdk","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","unsubscribeIsAuthenticated","onIsAuthenticatedChange","unsubscribeClaims","onClaimsChange","isSessionFetched","isUserFetched","current","oidc","finishLoginIfNeed","finally","fetchSession","useCallback","withValidation","refresh","undefined","then","fetchUser","me","value","useMemo","React","default","createElement","Context","Provider"],"mappings":"kQAoD6C,EAC3CA,YACAC,UAAU,GACVC,gBAAgB,GAChBC,aAAa,GACbC,yBAAwB,EACxBC,QACAC,iBAAgB,EAChBC,eAAc,EACdC,aACAC,8BAA6B,EAC7BC,wCAAuC,EACvCC,oBAAoB,GACpBC,mBACAC,gBACAC,eAEA,MAAOC,EAAMC,GAAWC,EAAQA,YACzBC,EAASC,GAAcF,EAAQA,YAC/BG,EAAQC,GAAaJ,EAAQA,YAC7BK,EAAiBC,GAAsBN,EAAQA,UAAC,IAEhDO,EAAeC,GAAoBR,EAAQA,UAAC,IAC5CS,EAAkBC,GAAuBV,EAAQA,UAAC,IAGlDW,EAAeC,GAAoBZ,EAAAA,WAAWT,GAC/CsB,EAAsBC,UAAO,GAE7BC,EAAMC,EAAAA,QAAO,CACjBjC,YACAC,UACAK,gBACAC,cACAH,wBACAC,QACAG,aACAC,6BACAC,uCACAC,oBACAC,mBACAC,kBAGFqB,EAAAA,WAAU,KACR,GAAIF,EAAK,CACP,MAAMG,EAA0BH,EAAII,qBAAqBjB,GACnDkB,EAAkBL,EAAIM,aAAatB,GACnCuB,EACJP,EAAIQ,wBAAwBjB,GACxBkB,EAAoBT,EAAIU,eAAerB,GAE7C,MAAO,KACLc,IACAE,IACAE,IACAE,GAAmB,CAEtB,CACe,GACf,CAACT,IAEJ,MAAMW,EAAmBZ,UAAO,GAC1Ba,EAAgBb,UAAO,GAI7BG,EAAAA,WAAU,KACJF,GAAOxB,IAAesB,EAAoBe,UAC5Cf,EAAoBe,SAAU,EAC9Bb,EAAIc,KAAKC,oBAAoBC,SAAQ,KACnCnB,GAAiB,GAEjBc,EAAiBE,SAAU,CAAI,IAElC,GACA,IAEH,MAAMI,EAAeC,EAAAA,aAAY,KAE3BP,EAAiBE,UACrBF,EAAiBE,SAAU,EAE3BlB,GAAoB,GACpBwB,EAAAA,eAAenB,aAAA,EAAAA,EAAKoB,QAApBD,MAA6BE,GAAW,GAAMC,MAAK,KACjD3B,GAAoB,EAAM,IAC1B,GACD,CAACK,IAEEuB,EAAYL,EAAAA,aAAY,KAExBN,EAAcC,UAClBD,EAAcC,SAAU,EAExBpB,GAAiB,GACjB0B,EAAAA,eAAenB,EAAIwB,GAAnBL,GAAyBG,MAAK,KAC5B7B,GAAiB,EAAM,IACvB,GACD,CAACO,IAEEyB,EAAQC,EAAAA,SACZ,KAAO,CACLH,YACAxC,OACAS,gBACAoB,cAAeA,EAAcC,QAC7BI,eACA/B,UACAI,kBACAI,mBACAE,gBACAe,iBAAkBA,EAAiBE,QACnC7C,YACAC,UACAC,gBACAC,aACAM,6BACAC,uCACAC,oBACAE,gBACAG,UACAG,aACAI,qBACAH,SACAY,SAEF,CACEuB,EACAxC,EACAS,EACAoB,EAAcC,QACdI,EACA/B,EACAI,EACAI,EACAE,EACAe,EAAiBE,QACjB7C,EACAC,EACAC,EACAC,EACAO,EACAC,EACAE,EACAG,EACAG,EACAI,EACAH,EACAY,IAGJ,OAAO2B,EAAAC,QAAAC,cAACC,UAAQC,SAAQ,CAACN,MAAOA,GAAQ3C,EAA4B"}
1
+ {"version":3,"file":"AuthProvider.js","sources":["../../../../src/components/AuthProvider/AuthProvider.tsx"],"sourcesContent":["import React, {\n FC,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { CookieConfig, OidcConfig } from '@descope/web-js-sdk';\nimport { Claims } from '@descope/core-js-sdk';\nimport { CustomStorage } from '@descope/web-component';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { isDescopeBridge, withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ntype Hooks = Parameters<typeof useSdk>[0]['hooks'];\n\ninterface IAuthProviderProps {\n projectId: string;\n baseUrl?: string;\n // allows to override the base URL that is used to fetch static files\n baseStaticUrl?: string;\n // allows to override the base URL that is used to fetch external script files\n baseCdnUrl?: string;\n // Default is true. If true, tokens will be stored on local storage and can accessed with getToken function\n persistTokens?: boolean;\n // Default is true. If true, the SDK will automatically refresh the session token when it is about to expire\n autoRefresh?: boolean;\n // If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n // stored on local storage and can accessed with getSessionToken function\n // Use this option if session token will stay small (less than 1k)\n // NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n sessionTokenViaCookie?: CookieConfig;\n hooks?: Hooks;\n // If truthy he SDK refresh and logout functions will use the OIDC client\n // Accepts boolean or OIDC configuration\n oidcConfig?: OidcConfig;\n // Default is true. If true, last authenticated user will be stored on local storage and can accessed with getUser function\n storeLastAuthenticatedUser?: boolean;\n // If true, last authenticated user will not be removed after logout\n keepLastAuthenticatedUserAfterLogout?: boolean;\n // Use this option if the authentication is done via cookie, and configured with a different name\n // Currently, this is done using Descope Flows\n refreshCookieName?: string;\n // Function to get external token, for seamless migration from external system\n getExternalToken?: () => Promise<string>;\n // Custom storage object for authentication related data\n customStorage?: CustomStorage;\n children?: React.ReactNode;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n projectId,\n baseUrl = '',\n baseStaticUrl = '',\n baseCdnUrl = '',\n sessionTokenViaCookie = false,\n hooks = undefined,\n persistTokens = true,\n autoRefresh = true,\n oidcConfig = undefined,\n storeLastAuthenticatedUser = true,\n keepLastAuthenticatedUserAfterLogout = false,\n refreshCookieName = '',\n getExternalToken = undefined,\n customStorage = undefined,\n children = undefined,\n}) => {\n const [user, setUser] = useState<User>();\n const [session, setSession] = useState<string>();\n const [claims, setClaims] = useState<Claims>();\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n\n const [isUserLoading, setIsUserLoading] = useState(false);\n const [isSessionLoading, setIsSessionLoading] = useState(false);\n\n // if oidc config is enabled, we attempt to finish the login, so we start as loading\n const [isOidcLoading, setIsOidcLoading] = useState(!!oidcConfig);\n const isOidcFinishedLogin = useRef(false);\n\n const sdk = useSdk({\n projectId,\n baseUrl,\n persistTokens,\n autoRefresh,\n sessionTokenViaCookie,\n hooks,\n oidcConfig,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n getExternalToken,\n customStorage,\n });\n\n useEffect(() => {\n if (sdk) {\n const unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n const unsubscribeUser = sdk.onUserChange(setUser);\n const unsubscribeIsAuthenticated =\n sdk.onIsAuthenticatedChange(setIsAuthenticated);\n const unsubscribeClaims = sdk.onClaimsChange(setClaims);\n\n return () => {\n unsubscribeSessionToken();\n unsubscribeUser();\n unsubscribeIsAuthenticated();\n unsubscribeClaims();\n };\n }\n return undefined;\n }, [sdk]);\n\n const isSessionFetched = useRef(false);\n const isUserFetched = useRef(false);\n\n // if oidc config is enabled, and we have oidc params in the url\n // we will finish the login (this should run only once)\n useEffect(() => {\n if (sdk && oidcConfig && !isOidcFinishedLogin.current) {\n isOidcFinishedLogin.current = true;\n sdk.oidc.finishLoginIfNeed().finally(() => {\n setIsOidcLoading(false);\n // We want that the session will fetched only once\n isSessionFetched.current = true;\n });\n }\n }, []);\n\n const fetchSession = useCallback(() => {\n // Don't load the session in native flows, though we'd usually not get here at all from useSession in this case\n if (isDescopeBridge()) return;\n\n // We want that the session will fetched only once\n if (isSessionFetched.current) return;\n isSessionFetched.current = true;\n\n setIsSessionLoading(true);\n withValidation(sdk?.refresh)(undefined, true).then(() => {\n setIsSessionLoading(false);\n });\n }, [sdk]);\n\n const fetchUser = useCallback(() => {\n // We want that the user will fetched only once\n if (isUserFetched.current) return;\n isUserFetched.current = true;\n\n setIsUserLoading(true);\n withValidation(sdk.me)().then(() => {\n setIsUserLoading(false);\n });\n }, [sdk]);\n\n const value = useMemo<IContext>(\n () => ({\n fetchUser,\n user,\n isUserLoading,\n isUserFetched: isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched: isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n }),\n [\n fetchUser,\n user,\n isUserLoading,\n isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n ],\n );\n return <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n"],"names":["projectId","baseUrl","baseStaticUrl","baseCdnUrl","sessionTokenViaCookie","hooks","persistTokens","autoRefresh","oidcConfig","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","getExternalToken","customStorage","children","user","setUser","useState","session","setSession","claims","setClaims","isAuthenticated","setIsAuthenticated","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","isOidcLoading","setIsOidcLoading","isOidcFinishedLogin","useRef","sdk","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","unsubscribeIsAuthenticated","onIsAuthenticatedChange","unsubscribeClaims","onClaimsChange","isSessionFetched","isUserFetched","current","oidc","finishLoginIfNeed","finally","fetchSession","useCallback","isDescopeBridge","withValidation","refresh","undefined","then","fetchUser","me","value","useMemo","React","default","createElement","Context","Provider"],"mappings":"kQAoD6C,EAC3CA,YACAC,UAAU,GACVC,gBAAgB,GAChBC,aAAa,GACbC,yBAAwB,EACxBC,QACAC,iBAAgB,EAChBC,eAAc,EACdC,aACAC,8BAA6B,EAC7BC,wCAAuC,EACvCC,oBAAoB,GACpBC,mBACAC,gBACAC,eAEA,MAAOC,EAAMC,GAAWC,EAAQA,YACzBC,EAASC,GAAcF,EAAQA,YAC/BG,EAAQC,GAAaJ,EAAQA,YAC7BK,EAAiBC,GAAsBN,EAAQA,UAAC,IAEhDO,EAAeC,GAAoBR,EAAQA,UAAC,IAC5CS,EAAkBC,GAAuBV,EAAQA,UAAC,IAGlDW,EAAeC,GAAoBZ,EAAAA,WAAWT,GAC/CsB,EAAsBC,UAAO,GAE7BC,EAAMC,EAAAA,QAAO,CACjBjC,YACAC,UACAK,gBACAC,cACAH,wBACAC,QACAG,aACAC,6BACAC,uCACAC,oBACAC,mBACAC,kBAGFqB,EAAAA,WAAU,KACR,GAAIF,EAAK,CACP,MAAMG,EAA0BH,EAAII,qBAAqBjB,GACnDkB,EAAkBL,EAAIM,aAAatB,GACnCuB,EACJP,EAAIQ,wBAAwBjB,GACxBkB,EAAoBT,EAAIU,eAAerB,GAE7C,MAAO,KACLc,IACAE,IACAE,IACAE,GAAmB,CAEtB,CACe,GACf,CAACT,IAEJ,MAAMW,EAAmBZ,UAAO,GAC1Ba,EAAgBb,UAAO,GAI7BG,EAAAA,WAAU,KACJF,GAAOxB,IAAesB,EAAoBe,UAC5Cf,EAAoBe,SAAU,EAC9Bb,EAAIc,KAAKC,oBAAoBC,SAAQ,KACnCnB,GAAiB,GAEjBc,EAAiBE,SAAU,CAAI,IAElC,GACA,IAEH,MAAMI,EAAeC,EAAAA,aAAY,KAE3BC,qBAGAR,EAAiBE,UACrBF,EAAiBE,SAAU,EAE3BlB,GAAoB,GACpByB,EAAAA,eAAepB,aAAA,EAAAA,EAAKqB,QAApBD,MAA6BE,GAAW,GAAMC,MAAK,KACjD5B,GAAoB,EAAM,IAC1B,GACD,CAACK,IAEEwB,EAAYN,EAAAA,aAAY,KAExBN,EAAcC,UAClBD,EAAcC,SAAU,EAExBpB,GAAiB,GACjB2B,EAAAA,eAAepB,EAAIyB,GAAnBL,GAAyBG,MAAK,KAC5B9B,GAAiB,EAAM,IACvB,GACD,CAACO,IAEE0B,EAAQC,EAAAA,SACZ,KAAO,CACLH,YACAzC,OACAS,gBACAoB,cAAeA,EAAcC,QAC7BI,eACA/B,UACAI,kBACAI,mBACAE,gBACAe,iBAAkBA,EAAiBE,QACnC7C,YACAC,UACAC,gBACAC,aACAM,6BACAC,uCACAC,oBACAE,gBACAG,UACAG,aACAI,qBACAH,SACAY,SAEF,CACEwB,EACAzC,EACAS,EACAoB,EAAcC,QACdI,EACA/B,EACAI,EACAI,EACAE,EACAe,EAAiBE,QACjB7C,EACAC,EACAC,EACAC,EACAO,EACAC,EACAE,EACAG,EACAG,EACAI,EACAH,EACAY,IAGJ,OAAO4B,EAAAC,QAAAC,cAACC,UAAQC,SAAQ,CAACN,MAAOA,GAAQ5C,EAA4B"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../node_modules/.pnpm/@rollup_plugin-typescript@11.1.6_rollup@4.22.4_tslib@2.8.1_typescript@5.4.5/node_modules/tslib/tslib.es6.js"),t=require("react"),r=require("../constants.js"),s=require("../hooks/Context.js"),n=require("../sdk.js"),o=require("./withPropsMapping/index.js");function a(e){return e&&e.__esModule?e:{default:e}}var l=a(t);const u=t.lazy((async()=>(((null===customElements||void 0===customElements?void 0:customElements.get("descope-wc"))||await import("@descope/web-component").then((e=>e.default))).sdkConfigOverrides={baseHeaders:r.baseHeaders,persistTokens:!1,hooks:{get beforeRequest(){return n.getGlobalSdk().httpClient.hooks.beforeRequest},set beforeRequest(e){}}},{default:o.default(l.default.forwardRef(((s,n)=>{var{"external-request-id":o}=s,a=e.__rest(s,["external-request-id"]);return t.useMemo((()=>{var e,t;e="x-external-rid",(t=o)?r.baseHeaders[e]=t:delete r.baseHeaders[e]}),[o]),l.default.createElement("descope-wc",Object.assign({ref:n},a))})))}))),d=l.default.forwardRef((({flowId:e,onSuccess:r,onError:n,onReady:o,logger:a,tenant:d,theme:c,nonce:i,locale:p,debug:f,client:m,form:v,telemetryKey:b,redirectUrl:E,autoFocus:g,validateOnBlur:h,restartOnError:y,errorTransformer:L,styleId:k,onScreenUpdate:q,dismissScreenErrorOnInput:S,outboundAppId:U,outboundAppScopes:_,popupOrigin:w,children:x,externalRequestId:I},C)=>{const[O,R]=t.useState(null);t.useImperativeHandle(C,(()=>O));const{projectId:j,baseUrl:A,baseStaticUrl:H,baseCdnUrl:M,storeLastAuthenticatedUser:N,keepLastAuthenticatedUserAfterLogout:T,refreshCookieName:B,customStorage:F,sdk:K}=l.default.useContext(s.default),P=t.useCallback((async e=>{await K.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return t.useEffect((()=>{const e=O;return null==e||e.addEventListener("success",P),n&&(null==e||e.addEventListener("error",n)),o&&(null==e||e.addEventListener("ready",o)),()=>{n&&(null==e||e.removeEventListener("error",n)),o&&(null==e||e.removeEventListener("ready",o)),null==e||e.removeEventListener("success",P)}}),[O,n,P]),t.useEffect((()=>{const e=O;return null==e||e.addEventListener("success",P),()=>{null==e||e.removeEventListener("success",P)}}),[O,P]),t.useEffect((()=>{const e=O;return n&&(null==e||e.addEventListener("error",n)),()=>{n&&(null==e||e.removeEventListener("error",n))}}),[O,n]),t.useEffect((()=>{const e=O;return o&&(null==e||e.addEventListener("ready",o)),()=>{o&&(null==e||e.removeEventListener("error",o))}}),[O,o]),l.default.createElement("form",null,l.default.createElement(t.Suspense,{fallback:null},l.default.createElement(u,{projectId:j,flowId:e,baseUrl:A,baseStaticUrl:H,baseCdnUrl:M,ref:R,telemetryKey:b,redirectUrl:E,autoFocus:g,styleId:k,validateOnBlur:h,restartOnError:y,keepLastAuthenticatedUserAfterLogout:T,tenant:d,externalRequestId:I,customStorage:F,"theme.attr":c,"nonce.attr":i,"locale.attr":p,"form.attr":v,"client.attr":m,"debug.attr":f,"outbound-app-id.attr":U,"outbound-app-scopes.attr":_,"popup-origin.attr":w,"store-last-authenticated-user.attr":N,"refreshCookieName.attr":B,"dismiss-screen-error-on-input.attr":S,"errorTransformer.prop":L,"logger.prop":a,"onScreenUpdate.prop":q,"customStorage.prop":F},x)))}));exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("react"),r=require("../constants.js"),s=require("../hooks/Context.js"),n=require("../sdk.js"),o=require("./withPropsMapping/index.js");function a(e){return e&&e.__esModule?e:{default:e}}var u=a(t);const l=t.lazy((async()=>(((null===customElements||void 0===customElements?void 0:customElements.get("descope-wc"))||await import("@descope/web-component").then((e=>e.default))).sdkConfigOverrides={baseHeaders:r.baseHeaders,persistTokens:!1,hooks:{get beforeRequest(){return n.getGlobalSdk().httpClient.hooks.beforeRequest},set beforeRequest(e){}}},{default:o.default(u.default.forwardRef(((s,n)=>{var{"external-request-id":o}=s,a=e.__rest(s,["external-request-id"]);return t.useMemo((()=>{var e,t;e="x-external-rid",(t=o)?r.baseHeaders[e]=t:delete r.baseHeaders[e]}),[o]),u.default.createElement("descope-wc",Object.assign({ref:n},a))})))}))),d=u.default.forwardRef((({flowId:e,onSuccess:r,onError:n,onReady:o,logger:a,tenant:d,theme:c,nonce:i,locale:p,debug:f,client:m,form:v,telemetryKey:E,redirectUrl:b,autoFocus:g,validateOnBlur:h,restartOnError:L,errorTransformer:k,styleId:y,onScreenUpdate:q,dismissScreenErrorOnInput:S,outboundAppId:U,outboundAppScopes:w,popupOrigin:x,children:I,externalRequestId:C},O)=>{const[R,j]=t.useState(null);t.useImperativeHandle(O,(()=>R));const{projectId:A,baseUrl:_,baseStaticUrl:H,baseCdnUrl:M,storeLastAuthenticatedUser:N,keepLastAuthenticatedUserAfterLogout:T,refreshCookieName:B,customStorage:F,sdk:K}=u.default.useContext(s.default),P=t.useCallback((async e=>{await K.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return t.useEffect((()=>{const e=R;return null==e||e.addEventListener("success",P),n&&(null==e||e.addEventListener("error",n)),o&&(null==e||e.addEventListener("ready",o)),()=>{n&&(null==e||e.removeEventListener("error",n)),o&&(null==e||e.removeEventListener("ready",o)),null==e||e.removeEventListener("success",P)}}),[R,n,P]),t.useEffect((()=>{const e=R;return null==e||e.addEventListener("success",P),()=>{null==e||e.removeEventListener("success",P)}}),[R,P]),t.useEffect((()=>{const e=R;return n&&(null==e||e.addEventListener("error",n)),()=>{n&&(null==e||e.removeEventListener("error",n))}}),[R,n]),t.useEffect((()=>{const e=R;return o&&(null==e||e.addEventListener("ready",o)),()=>{o&&(null==e||e.removeEventListener("error",o))}}),[R,o]),u.default.createElement("form",null,u.default.createElement(t.Suspense,{fallback:null},u.default.createElement(l,{projectId:A,flowId:e,baseUrl:_,baseStaticUrl:H,baseCdnUrl:M,ref:j,telemetryKey:E,redirectUrl:b,autoFocus:g,styleId:y,validateOnBlur:h,restartOnError:L,keepLastAuthenticatedUserAfterLogout:T,tenant:d,externalRequestId:C,customStorage:F,"theme.attr":c,"nonce.attr":i,"locale.attr":p,"form.attr":v,"client.attr":m,"debug.attr":f,"outbound-app-id.attr":U,"outbound-app-scopes.attr":w,"popup-origin.attr":x,"store-last-authenticated-user.attr":N,"refreshCookieName.attr":B,"dismiss-screen-error-on-input.attr":S,"errorTransformer.prop":k,"logger.prop":a,"onScreenUpdate.prop":q,"customStorage.prop":F},I)))}));exports.default=d;
2
2
  //# sourceMappingURL=Descope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Descope.js","sources":["../../../src/components/Descope.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\nimport React, {\n lazy,\n Suspense,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useState,\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { getGlobalSdk } from '../sdk';\nimport withPropsMapping from './withPropsMapping';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n const updateDynamicHeader = (key: string, value: string) => {\n if (value) {\n baseHeaders[key] = value;\n } else {\n delete baseHeaders[key];\n }\n };\n\n const WebComponent: any =\n customElements?.get('descope-wc') ||\n (await import('@descope/web-component').then((module) => module.default));\n\n WebComponent.sdkConfigOverrides = {\n // Overrides the web-component's base headers to indicate usage via the React SDK\n baseHeaders,\n // Disables token persistence within the web-component to delegate token management\n // to the global SDK hooks. This ensures token handling aligns with the SDK's configuration,\n // and web-component requests leverage the global SDK's beforeRequest hooks for consistency\n persistTokens: false,\n hooks: {\n get beforeRequest() {\n // Retrieves the beforeRequest hook from the global SDK, which is initialized\n // within the AuthProvider using the desired configuration. This approach ensures\n // the web-component utilizes the same beforeRequest hooks as the global SDK\n return getGlobalSdk().httpClient.hooks.beforeRequest;\n },\n set beforeRequest(_) {\n // The empty setter prevents runtime errors when attempts are made to assign a value to 'beforeRequest'.\n // JavaScript objects default to having both getters and setters\n },\n },\n };\n\n return {\n default: withPropsMapping(\n React.forwardRef<HTMLElement>(\n ({ 'external-request-id': externalRequestId, ...props }: any, ref) => {\n // update the dynamic headers with the external request ID if provided\n useMemo(() => {\n updateDynamicHeader('x-external-rid', externalRequestId);\n }, [externalRequestId]);\n\n return <descope-wc ref={ref} {...props} />;\n },\n ),\n ),\n };\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n (\n {\n flowId,\n onSuccess,\n onError,\n onReady,\n logger,\n tenant,\n theme,\n nonce,\n locale,\n debug,\n client,\n form,\n telemetryKey,\n redirectUrl,\n autoFocus,\n validateOnBlur,\n restartOnError,\n errorTransformer,\n styleId,\n onScreenUpdate,\n dismissScreenErrorOnInput,\n outboundAppId,\n outboundAppScopes,\n popupOrigin,\n children,\n externalRequestId,\n },\n ref,\n ) => {\n const [innerRef, setInnerRef] = useState(null);\n\n useImperativeHandle(ref, () => innerRef);\n\n const {\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n sdk,\n } = React.useContext(Context);\n\n const handleSuccess = useCallback(\n async (e: CustomEvent) => {\n // In order to make sure all the after-hooks are running with the success response\n // we are generating a fake response with the success data and calling the http client after hook fn with it\n await sdk.httpClient.hooks.afterRequest(\n {} as any,\n new Response(JSON.stringify(e.detail)),\n );\n if (onSuccess) {\n onSuccess(e);\n }\n },\n [onSuccess],\n );\n\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n if (onError) ele?.addEventListener('error', onError);\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n if (onReady) ele?.removeEventListener('ready', onReady);\n\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, onError, handleSuccess]);\n\n // Success event\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n return () => {\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, handleSuccess]);\n\n // Error event\n useEffect(() => {\n const ele = innerRef;\n if (onError) ele?.addEventListener('error', onError);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n };\n }, [innerRef, onError]);\n\n // Ready event\n useEffect(() => {\n const ele = innerRef;\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onReady) ele?.removeEventListener('error', onReady);\n };\n }, [innerRef, onReady]);\n\n return (\n /**\n * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n * this workaround is done in order to support webauthn passkeys\n * it can be removed once this issue will be solved\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n */\n\t<form>\n\t\t<Suspense fallback={null}>\n\t\t\t<DescopeWC\n projectId={projectId}\n flowId={flowId}\n baseUrl={baseUrl}\n baseStaticUrl={baseStaticUrl}\n baseCdnUrl={baseCdnUrl}\n ref={setInnerRef}\n telemetryKey={telemetryKey}\n redirectUrl={redirectUrl}\n autoFocus={autoFocus}\n styleId={styleId}\n validateOnBlur={validateOnBlur}\n restartOnError={restartOnError}\n keepLastAuthenticatedUserAfterLogout={\n keepLastAuthenticatedUserAfterLogout\n }\n tenant={tenant}\n externalRequestId={externalRequestId}\n customStorage={customStorage}\n {...{\n // attributes\n 'theme.attr': theme,\n 'nonce.attr': nonce,\n 'locale.attr': locale,\n 'form.attr': form,\n 'client.attr': client,\n 'debug.attr': debug,\n 'outbound-app-id.attr': outboundAppId,\n 'outbound-app-scopes.attr': outboundAppScopes,\n 'popup-origin.attr': popupOrigin,\n 'store-last-authenticated-user.attr': storeLastAuthenticatedUser,\n 'refreshCookieName.attr': refreshCookieName,\n 'dismiss-screen-error-on-input.attr': dismissScreenErrorOnInput,\n // props\n 'errorTransformer.prop': errorTransformer,\n 'logger.prop': logger,\n 'onScreenUpdate.prop': onScreenUpdate,\n 'customStorage.prop': customStorage,\n }}\n >\n\t\t\t\t{children}\n\t\t\t</DescopeWC>\n\t\t</Suspense>\n\t</form>\n );\n },\n);\n\nexport default Descope;\n"],"names":["DescopeWC","lazy","async","customElements","get","import","then","module","default","sdkConfigOverrides","baseHeaders","persistTokens","hooks","beforeRequest","getGlobalSdk","httpClient","_","withPropsMapping","React","forwardRef","_a","ref","externalRequestId","props","__rest","useMemo","key","value","Descope","flowId","onSuccess","onError","onReady","logger","tenant","theme","nonce","locale","debug","client","form","telemetryKey","redirectUrl","autoFocus","validateOnBlur","restartOnError","errorTransformer","styleId","onScreenUpdate","dismissScreenErrorOnInput","outboundAppId","outboundAppScopes","popupOrigin","children","innerRef","setInnerRef","useState","useImperativeHandle","projectId","baseUrl","baseStaticUrl","baseCdnUrl","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","customStorage","sdk","useContext","Context","handleSuccess","useCallback","e","afterRequest","Response","JSON","stringify","detail","useEffect","ele","addEventListener","removeEventListener","createElement","Suspense","fallback"],"mappings":"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"}
1
+ {"version":3,"file":"Descope.js","sources":["../../../src/components/Descope.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\nimport React, {\n lazy,\n Suspense,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useState,\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { getGlobalSdk } from '../sdk';\nimport withPropsMapping from './withPropsMapping';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n const updateDynamicHeader = (key: string, value: string) => {\n if (value) {\n baseHeaders[key] = value;\n } else {\n delete baseHeaders[key];\n }\n };\n\n const WebComponent: any =\n customElements?.get('descope-wc') ||\n (await import('@descope/web-component').then((module) => module.default));\n\n WebComponent.sdkConfigOverrides = {\n // Overrides the web-component's base headers to indicate usage via the React SDK\n baseHeaders,\n // Disables token persistence within the web-component to delegate token management\n // to the global SDK hooks. This ensures token handling aligns with the SDK's configuration,\n // and web-component requests leverage the global SDK's beforeRequest hooks for consistency\n persistTokens: false,\n hooks: {\n get beforeRequest() {\n // Retrieves the beforeRequest hook from the global SDK, which is initialized\n // within the AuthProvider using the desired configuration. This approach ensures\n // the web-component utilizes the same beforeRequest hooks as the global SDK\n return getGlobalSdk().httpClient.hooks.beforeRequest;\n },\n set beforeRequest(_) {\n // The empty setter prevents runtime errors when attempts are made to assign a value to 'beforeRequest'.\n // JavaScript objects default to having both getters and setters\n },\n },\n };\n\n return {\n default: withPropsMapping(\n React.forwardRef<HTMLElement>(\n ({ 'external-request-id': externalRequestId, ...props }: any, ref) => {\n // update the dynamic headers with the external request ID if provided\n useMemo(() => {\n updateDynamicHeader('x-external-rid', externalRequestId);\n }, [externalRequestId]);\n\n return <descope-wc ref={ref} {...props} />;\n },\n ),\n ),\n };\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n (\n {\n flowId,\n onSuccess,\n onError,\n onReady,\n logger,\n tenant,\n theme,\n nonce,\n locale,\n debug,\n client,\n form,\n telemetryKey,\n redirectUrl,\n autoFocus,\n validateOnBlur,\n restartOnError,\n errorTransformer,\n styleId,\n onScreenUpdate,\n dismissScreenErrorOnInput,\n outboundAppId,\n outboundAppScopes,\n popupOrigin,\n children,\n externalRequestId,\n },\n ref,\n ) => {\n const [innerRef, setInnerRef] = useState(null);\n\n useImperativeHandle(ref, () => innerRef);\n\n const {\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n sdk,\n } = React.useContext(Context);\n\n const handleSuccess = useCallback(\n async (e: CustomEvent) => {\n // In order to make sure all the after-hooks are running with the success response\n // we are generating a fake response with the success data and calling the http client after hook fn with it\n await sdk.httpClient.hooks.afterRequest(\n {} as any,\n new Response(JSON.stringify(e.detail)),\n );\n if (onSuccess) {\n onSuccess(e);\n }\n },\n [onSuccess],\n );\n\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n if (onError) ele?.addEventListener('error', onError);\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n if (onReady) ele?.removeEventListener('ready', onReady);\n\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, onError, handleSuccess]);\n\n // Success event\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n return () => {\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, handleSuccess]);\n\n // Error event\n useEffect(() => {\n const ele = innerRef;\n if (onError) ele?.addEventListener('error', onError);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n };\n }, [innerRef, onError]);\n\n // Ready event\n useEffect(() => {\n const ele = innerRef;\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onReady) ele?.removeEventListener('error', onReady);\n };\n }, [innerRef, onReady]);\n\n return (\n /**\n * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n * this workaround is done in order to support webauthn passkeys\n * it can be removed once this issue will be solved\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n */\n\t<form>\n\t\t<Suspense fallback={null}>\n\t\t\t<DescopeWC\n projectId={projectId}\n flowId={flowId}\n baseUrl={baseUrl}\n baseStaticUrl={baseStaticUrl}\n baseCdnUrl={baseCdnUrl}\n ref={setInnerRef}\n telemetryKey={telemetryKey}\n redirectUrl={redirectUrl}\n autoFocus={autoFocus}\n styleId={styleId}\n validateOnBlur={validateOnBlur}\n restartOnError={restartOnError}\n keepLastAuthenticatedUserAfterLogout={\n keepLastAuthenticatedUserAfterLogout\n }\n tenant={tenant}\n externalRequestId={externalRequestId}\n customStorage={customStorage}\n {...{\n // attributes\n 'theme.attr': theme,\n 'nonce.attr': nonce,\n 'locale.attr': locale,\n 'form.attr': form,\n 'client.attr': client,\n 'debug.attr': debug,\n 'outbound-app-id.attr': outboundAppId,\n 'outbound-app-scopes.attr': outboundAppScopes,\n 'popup-origin.attr': popupOrigin,\n 'store-last-authenticated-user.attr': storeLastAuthenticatedUser,\n 'refreshCookieName.attr': refreshCookieName,\n 'dismiss-screen-error-on-input.attr': dismissScreenErrorOnInput,\n // props\n 'errorTransformer.prop': errorTransformer,\n 'logger.prop': logger,\n 'onScreenUpdate.prop': onScreenUpdate,\n 'customStorage.prop': customStorage,\n }}\n >\n\t\t\t\t{children}\n\t\t\t</DescopeWC>\n\t\t</Suspense>\n\t</form>\n );\n },\n);\n\nexport default Descope;\n"],"names":["DescopeWC","lazy","async","customElements","get","import","then","module","default","sdkConfigOverrides","baseHeaders","persistTokens","hooks","beforeRequest","getGlobalSdk","httpClient","_","withPropsMapping","React","forwardRef","_a","ref","externalRequestId","props","__rest","useMemo","key","value","Descope","flowId","onSuccess","onError","onReady","logger","tenant","theme","nonce","locale","debug","client","form","telemetryKey","redirectUrl","autoFocus","validateOnBlur","restartOnError","errorTransformer","styleId","onScreenUpdate","dismissScreenErrorOnInput","outboundAppId","outboundAppScopes","popupOrigin","children","innerRef","setInnerRef","useState","useImperativeHandle","projectId","baseUrl","baseStaticUrl","baseCdnUrl","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","customStorage","sdk","useContext","Context","handleSuccess","useCallback","e","afterRequest","Response","JSON","stringify","detail","useEffect","ele","addEventListener","removeEventListener","createElement","Suspense","fallback"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- "use strict";const e="undefined"!=typeof window;exports.IS_BROWSER=e,exports.baseHeaders={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.0.0-next-b00a100d-20251118"};
1
+ "use strict";const e="undefined"!=typeof window;exports.IS_BROWSER=e,exports.baseHeaders={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.0.0-next-cddfa808-20251204"};
2
2
  //# sourceMappingURL=constants.js.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),s=require("./useContext.js");exports.default=()=>{const{session:t,claims:i,isSessionLoading:n,isOidcLoading:o,fetchSession:r,isSessionFetched:u,isAuthenticated:c}=s.default(),a=e.useRef(n||o);e.useMemo((()=>{a.current=n||o}),[n,o]);const d=!c&&!n;return e.useMemo((()=>{d&&!u&&(a.current=!0)}),[u]),e.useEffect((()=>{d&&r()}),[r]),{isSessionLoading:a.current,sessionToken:t,claims:i,isAuthenticated:c}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),s=require("./useContext.js"),i=require("../utils.js");exports.default=()=>{const{session:t,claims:r,isSessionLoading:n,isOidcLoading:o,fetchSession:u,isSessionFetched:c,isAuthenticated:a}=s.default(),d=e.useRef(n||o);e.useMemo((()=>{d.current=n||o}),[n,o]);const f=!a&&!n&&!i.isDescopeBridge();return e.useMemo((()=>{f&&!c&&(d.current=!0)}),[c]),e.useEffect((()=>{f&&u()}),[u]),{isSessionLoading:d.current,sessionToken:t,claims:r,isAuthenticated:a}};
2
2
  //# sourceMappingURL=useSession.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSession.js","sources":["../../../src/hooks/useSession.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n const {\n session,\n claims,\n isSessionLoading,\n isOidcLoading,\n fetchSession,\n isSessionFetched,\n isAuthenticated,\n } = useContext();\n\n // when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n // (and not only when receiving an update from the context)\n const isLoading = useRef(isSessionLoading || isOidcLoading);\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n isLoading.current = isSessionLoading || isOidcLoading;\n }, [isSessionLoading, isOidcLoading]);\n\n const shouldFetchSession = !isAuthenticated && !isSessionLoading;\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n if (shouldFetchSession && !isSessionFetched) {\n isLoading.current = true;\n }\n }, [isSessionFetched]);\n\n // Fetch session if it's not already fetched\n // We want this to happen only once, so the dependency array should not contain shouldFetchSession\n useEffect(() => {\n if (shouldFetchSession) {\n fetchSession();\n }\n }, [fetchSession]);\n return {\n isSessionLoading: isLoading.current,\n sessionToken: session,\n claims,\n isAuthenticated,\n };\n};\n\nexport default useSession;\n"],"names":["session","claims","isSessionLoading","isOidcLoading","fetchSession","isSessionFetched","isAuthenticated","useContext","isLoading","useRef","useMemo","current","shouldFetchSession","useEffect","sessionToken"],"mappings":"wIAGmB,KACjB,MAAMA,QACJA,EAAOC,OACPA,EAAMC,iBACNA,EAAgBC,cAChBA,EAAaC,aACbA,EAAYC,iBACZA,EAAgBC,gBAChBA,GACEC,EAAAA,UAIEC,EAAYC,EAAAA,OAAOP,GAAoBC,GAG7CO,EAAAA,SAAQ,KACNF,EAAUG,QAAUT,GAAoBC,CAAa,GACpD,CAACD,EAAkBC,IAEtB,MAAMS,GAAsBN,IAAoBJ,EAgBhD,OAbAQ,EAAAA,SAAQ,KACFE,IAAuBP,IACzBG,EAAUG,SAAU,EACrB,GACA,CAACN,IAIJQ,EAAAA,WAAU,KACJD,GACFR,GACD,GACA,CAACA,IACG,CACLF,iBAAkBM,EAAUG,QAC5BG,aAAcd,EACdC,SACAK,kBACD"}
1
+ {"version":3,"file":"useSession.js","sources":["../../../src/hooks/useSession.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\nimport { isDescopeBridge } from '../utils';\n\nconst useSession = () => {\n const {\n session,\n claims,\n isSessionLoading,\n isOidcLoading,\n fetchSession,\n isSessionFetched,\n isAuthenticated,\n } = useContext();\n\n // when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n // (and not only when receiving an update from the context)\n const isLoading = useRef(isSessionLoading || isOidcLoading);\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n isLoading.current = isSessionLoading || isOidcLoading;\n }, [isSessionLoading, isOidcLoading]);\n\n // In case we're in a native flow, we won't refresh the session anyway, so no point in marking the state as loading\n const shouldFetchSession = !isAuthenticated && !isSessionLoading && !isDescopeBridge();\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n if (shouldFetchSession && !isSessionFetched) {\n isLoading.current = true;\n }\n }, [isSessionFetched]);\n\n // Fetch session if it's not already fetched\n // We want this to happen only once, so the dependency array should not contain shouldFetchSession\n useEffect(() => {\n if (shouldFetchSession) {\n fetchSession();\n }\n }, [fetchSession]);\n return {\n isSessionLoading: isLoading.current,\n sessionToken: session,\n claims,\n isAuthenticated,\n };\n};\n\nexport default useSession;\n"],"names":["session","claims","isSessionLoading","isOidcLoading","fetchSession","isSessionFetched","isAuthenticated","useContext","isLoading","useRef","useMemo","current","shouldFetchSession","isDescopeBridge","useEffect","sessionToken"],"mappings":"iKAImB,KACjB,MAAMA,QACJA,EAAOC,OACPA,EAAMC,iBACNA,EAAgBC,cAChBA,EAAaC,aACbA,EAAYC,iBACZA,EAAgBC,gBAChBA,GACEC,EAAAA,UAIEC,EAAYC,EAAAA,OAAOP,GAAoBC,GAG7CO,EAAAA,SAAQ,KACNF,EAAUG,QAAUT,GAAoBC,CAAa,GACpD,CAACD,EAAkBC,IAGtB,MAAMS,GAAsBN,IAAoBJ,IAAqBW,EAAeA,kBAgBpF,OAbAH,EAAAA,SAAQ,KACFE,IAAuBP,IACzBG,EAAUG,SAAU,EACrB,GACA,CAACN,IAIJS,EAAAA,WAAU,KACJF,GACFR,GACD,GACA,CAACA,IACG,CACLF,iBAAkBM,EAAUG,QAC5BI,aAAcf,EACdC,SACAK,kBACD"}
package/dist/cjs/utils.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";exports.withValidation=r=>(...t)=>{if(!r)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return r(...t)},exports.wrapInTry=r=>(...t)=>{let o;try{o=r(...t)}catch(r){console.error(r)}return o};
1
+ "use strict";exports.isDescopeBridge=()=>"undefined"!=typeof window&&!!window.descopeBridge,exports.withValidation=e=>(...r)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...r)},exports.wrapInTry=e=>(...r)=>{let o;try{o=e(...r)}catch(e){console.error(e)}return o};
2
2
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["/**\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 extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n if (!fn) {\n throw Error(\n `You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,\n );\n }\n return fn(...args);\n };\n\nexport const wrapInTry =\n <T extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n let res: U;\n try {\n res = fn(...args);\n } catch (err) {\n console.error(err); // eslint-disable-line no-console\n }\n return res;\n };\n"],"names":["fn","args","Error","res","err","console","error"],"mappings":"oCAM4BA,GAC1B,IAAIC,KACF,IAAKD,EACH,MAAME,MACJ,0HAGJ,OAAOF,KAAMC,EAAK,oBAIMD,GAC1B,IAAIC,KACF,IAAIE,EACJ,IACEA,EAAMH,KAAMC,EACb,CAAC,MAAOG,GACPC,QAAQC,MAAMF,EACf,CACD,OAAOD,CAAG"}
1
+ {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["/**\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 extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n if (!fn) {\n throw Error(\n `You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,\n );\n }\n return fn(...args);\n };\n\nexport const wrapInTry =\n <T extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n let res: U;\n try {\n res = fn(...args);\n } catch (err) {\n console.error(err); // eslint-disable-line no-console\n }\n return res;\n };\n\n// Detect if running in a native flow (e.g., mobile app with Descope bridge in a webview)\nexport const isDescopeBridge = () =>\n typeof window !== 'undefined' && !!window['descopeBridge'];\n"],"names":["window","fn","args","Error","res","err","console","error"],"mappings":"qCA6B+B,IACX,oBAAXA,UAA4BA,OAAsB,qCAxB/BC,GAC1B,IAAIC,KACF,IAAKD,EACH,MAAME,MACJ,0HAGJ,OAAOF,KAAMC,EAAK,oBAIMD,GAC1B,IAAIC,KACF,IAAIE,EACJ,IACEA,EAAMH,KAAMC,EACb,CAAC,MAAOG,GACPC,QAAQC,MAAMF,EACf,CACD,OAAOD,CAAG"}
@@ -1,2 +1,2 @@
1
- import e,{useState as t,useRef as s,useEffect as r,useCallback as o,useMemo as n}from"react";import i from"../../hooks/Context.js";import{withValidation as a}from"../../utils.js";import c from"./useSdk.js";const u=({projectId:u,baseUrl:d="",baseStaticUrl:h="",baseCdnUrl:f="",sessionTokenViaCookie:k=!1,hooks:l,persistTokens:g=!0,autoRefresh:m=!0,oidcConfig:U,storeLastAuthenticatedUser:C=!0,keepLastAuthenticatedUserAfterLogout:p=!1,refreshCookieName:L="",getExternalToken:A,customStorage:S,children:b})=>{const[T,j]=t(),[I,v]=t(),[x,N]=t(),[E,F]=t(!1),[R,V]=t(!1),[y,O]=t(!1),[P,q]=t(!!U),w=s(!1),z=c({projectId:u,baseUrl:d,persistTokens:g,autoRefresh:m,sessionTokenViaCookie:k,hooks:l,oidcConfig:U,storeLastAuthenticatedUser:C,keepLastAuthenticatedUserAfterLogout:p,refreshCookieName:L,getExternalToken:A,customStorage:S});r((()=>{if(z){const e=z.onSessionTokenChange(v),t=z.onUserChange(j),s=z.onIsAuthenticatedChange(F),r=z.onClaimsChange(N);return()=>{e(),t(),s(),r()}}}),[z]);const B=s(!1),D=s(!1);r((()=>{z&&U&&!w.current&&(w.current=!0,z.oidc.finishLoginIfNeed().finally((()=>{q(!1),B.current=!0})))}),[]);const G=o((()=>{B.current||(B.current=!0,O(!0),a(null==z?void 0:z.refresh)(void 0,!0).then((()=>{O(!1)})))}),[z]),H=o((()=>{D.current||(D.current=!0,V(!0),a(z.me)().then((()=>{V(!1)})))}),[z]),J=n((()=>({fetchUser:H,user:T,isUserLoading:R,isUserFetched:D.current,fetchSession:G,session:I,isAuthenticated:E,isSessionLoading:y,isOidcLoading:P,isSessionFetched:B.current,projectId:u,baseUrl:d,baseStaticUrl:h,baseCdnUrl:f,storeLastAuthenticatedUser:C,keepLastAuthenticatedUserAfterLogout:p,refreshCookieName:L,customStorage:S,setUser:j,setSession:v,setIsAuthenticated:F,claims:x,sdk:z})),[H,T,R,D.current,G,I,E,y,P,B.current,u,d,h,f,p,L,S,j,v,F,x,z]);return e.createElement(i.Provider,{value:J},b)};export{u as default};
1
+ import e,{useState as t,useRef as s,useEffect as r,useCallback as o,useMemo as n}from"react";import i from"../../hooks/Context.js";import{isDescopeBridge as a,withValidation as c}from"../../utils.js";import u from"./useSdk.js";const d=({projectId:d,baseUrl:h="",baseStaticUrl:f="",baseCdnUrl:k="",sessionTokenViaCookie:l=!1,hooks:g,persistTokens:m=!0,autoRefresh:U=!0,oidcConfig:C,storeLastAuthenticatedUser:p=!0,keepLastAuthenticatedUserAfterLogout:L=!1,refreshCookieName:A="",getExternalToken:S,customStorage:b,children:T})=>{const[j,I]=t(),[v,x]=t(),[N,E]=t(),[F,R]=t(!1),[V,y]=t(!1),[O,P]=t(!1),[q,w]=t(!!C),z=s(!1),B=u({projectId:d,baseUrl:h,persistTokens:m,autoRefresh:U,sessionTokenViaCookie:l,hooks:g,oidcConfig:C,storeLastAuthenticatedUser:p,keepLastAuthenticatedUserAfterLogout:L,refreshCookieName:A,getExternalToken:S,customStorage:b});r((()=>{if(B){const e=B.onSessionTokenChange(x),t=B.onUserChange(I),s=B.onIsAuthenticatedChange(R),r=B.onClaimsChange(E);return()=>{e(),t(),s(),r()}}}),[B]);const D=s(!1),G=s(!1);r((()=>{B&&C&&!z.current&&(z.current=!0,B.oidc.finishLoginIfNeed().finally((()=>{w(!1),D.current=!0})))}),[]);const H=o((()=>{a()||D.current||(D.current=!0,P(!0),c(null==B?void 0:B.refresh)(void 0,!0).then((()=>{P(!1)})))}),[B]),J=o((()=>{G.current||(G.current=!0,y(!0),c(B.me)().then((()=>{y(!1)})))}),[B]),K=n((()=>({fetchUser:J,user:j,isUserLoading:V,isUserFetched:G.current,fetchSession:H,session:v,isAuthenticated:F,isSessionLoading:O,isOidcLoading:q,isSessionFetched:D.current,projectId:d,baseUrl:h,baseStaticUrl:f,baseCdnUrl:k,storeLastAuthenticatedUser:p,keepLastAuthenticatedUserAfterLogout:L,refreshCookieName:A,customStorage:b,setUser:I,setSession:x,setIsAuthenticated:R,claims:N,sdk:B})),[J,j,V,G.current,H,v,F,O,q,D.current,d,h,f,k,L,A,b,I,x,R,N,B]);return e.createElement(i.Provider,{value:K},T)};export{d as default};
2
2
  //# sourceMappingURL=AuthProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AuthProvider.js","sources":["../../../../src/components/AuthProvider/AuthProvider.tsx"],"sourcesContent":["import React, {\n FC,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { CookieConfig, OidcConfig } from '@descope/web-js-sdk';\nimport { Claims } from '@descope/core-js-sdk';\nimport { CustomStorage } from '@descope/web-component';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ntype Hooks = Parameters<typeof useSdk>[0]['hooks'];\n\ninterface IAuthProviderProps {\n projectId: string;\n baseUrl?: string;\n // allows to override the base URL that is used to fetch static files\n baseStaticUrl?: string;\n // allows to override the base URL that is used to fetch external script files\n baseCdnUrl?: string;\n // Default is true. If true, tokens will be stored on local storage and can accessed with getToken function\n persistTokens?: boolean;\n // Default is true. If true, the SDK will automatically refresh the session token when it is about to expire\n autoRefresh?: boolean;\n // If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n // stored on local storage and can accessed with getSessionToken function\n // Use this option if session token will stay small (less than 1k)\n // NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n sessionTokenViaCookie?: CookieConfig;\n hooks?: Hooks;\n // If truthy he SDK refresh and logout functions will use the OIDC client\n // Accepts boolean or OIDC configuration\n oidcConfig?: OidcConfig;\n // Default is true. If true, last authenticated user will be stored on local storage and can accessed with getUser function\n storeLastAuthenticatedUser?: boolean;\n // If true, last authenticated user will not be removed after logout\n keepLastAuthenticatedUserAfterLogout?: boolean;\n // Use this option if the authentication is done via cookie, and configured with a different name\n // Currently, this is done using Descope Flows\n refreshCookieName?: string;\n // Function to get external token, for seamless migration from external system\n getExternalToken?: () => Promise<string>;\n // Custom storage object for authentication related data\n customStorage?: CustomStorage;\n children?: React.ReactNode;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n projectId,\n baseUrl = '',\n baseStaticUrl = '',\n baseCdnUrl = '',\n sessionTokenViaCookie = false,\n hooks = undefined,\n persistTokens = true,\n autoRefresh = true,\n oidcConfig = undefined,\n storeLastAuthenticatedUser = true,\n keepLastAuthenticatedUserAfterLogout = false,\n refreshCookieName = '',\n getExternalToken = undefined,\n customStorage = undefined,\n children = undefined,\n}) => {\n const [user, setUser] = useState<User>();\n const [session, setSession] = useState<string>();\n const [claims, setClaims] = useState<Claims>();\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n\n const [isUserLoading, setIsUserLoading] = useState(false);\n const [isSessionLoading, setIsSessionLoading] = useState(false);\n\n // if oidc config is enabled, we attempt to finish the login, so we start as loading\n const [isOidcLoading, setIsOidcLoading] = useState(!!oidcConfig);\n const isOidcFinishedLogin = useRef(false);\n\n const sdk = useSdk({\n projectId,\n baseUrl,\n persistTokens,\n autoRefresh,\n sessionTokenViaCookie,\n hooks,\n oidcConfig,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n getExternalToken,\n customStorage,\n });\n\n useEffect(() => {\n if (sdk) {\n const unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n const unsubscribeUser = sdk.onUserChange(setUser);\n const unsubscribeIsAuthenticated =\n sdk.onIsAuthenticatedChange(setIsAuthenticated);\n const unsubscribeClaims = sdk.onClaimsChange(setClaims);\n\n return () => {\n unsubscribeSessionToken();\n unsubscribeUser();\n unsubscribeIsAuthenticated();\n unsubscribeClaims();\n };\n }\n return undefined;\n }, [sdk]);\n\n const isSessionFetched = useRef(false);\n const isUserFetched = useRef(false);\n\n // if oidc config is enabled, and we have oidc params in the url\n // we will finish the login (this should run only once)\n useEffect(() => {\n if (sdk && oidcConfig && !isOidcFinishedLogin.current) {\n isOidcFinishedLogin.current = true;\n sdk.oidc.finishLoginIfNeed().finally(() => {\n setIsOidcLoading(false);\n // We want that the session will fetched only once\n isSessionFetched.current = true;\n });\n }\n }, []);\n\n const fetchSession = useCallback(() => {\n // We want that the session will fetched only once\n if (isSessionFetched.current) return;\n isSessionFetched.current = true;\n\n setIsSessionLoading(true);\n withValidation(sdk?.refresh)(undefined, true).then(() => {\n setIsSessionLoading(false);\n });\n }, [sdk]);\n\n const fetchUser = useCallback(() => {\n // We want that the user will fetched only once\n if (isUserFetched.current) return;\n isUserFetched.current = true;\n\n setIsUserLoading(true);\n withValidation(sdk.me)().then(() => {\n setIsUserLoading(false);\n });\n }, [sdk]);\n\n const value = useMemo<IContext>(\n () => ({\n fetchUser,\n user,\n isUserLoading,\n isUserFetched: isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched: isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n }),\n [\n fetchUser,\n user,\n isUserLoading,\n isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n ],\n );\n return <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n"],"names":["AuthProvider","projectId","baseUrl","baseStaticUrl","baseCdnUrl","sessionTokenViaCookie","hooks","persistTokens","autoRefresh","oidcConfig","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","getExternalToken","customStorage","children","user","setUser","useState","session","setSession","claims","setClaims","isAuthenticated","setIsAuthenticated","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","isOidcLoading","setIsOidcLoading","isOidcFinishedLogin","useRef","sdk","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","unsubscribeIsAuthenticated","onIsAuthenticatedChange","unsubscribeClaims","onClaimsChange","isSessionFetched","isUserFetched","current","oidc","finishLoginIfNeed","finally","fetchSession","useCallback","withValidation","refresh","undefined","then","fetchUser","me","value","useMemo","React","createElement","Context","Provider"],"mappings":"8MAoDA,MAAMA,EAAuC,EAC3CC,YACAC,UAAU,GACVC,gBAAgB,GAChBC,aAAa,GACbC,yBAAwB,EACxBC,QACAC,iBAAgB,EAChBC,eAAc,EACdC,aACAC,8BAA6B,EAC7BC,wCAAuC,EACvCC,oBAAoB,GACpBC,mBACAC,gBACAC,eAEA,MAAOC,EAAMC,GAAWC,KACjBC,EAASC,GAAcF,KACvBG,EAAQC,GAAaJ,KACrBK,EAAiBC,GAAsBN,GAAS,IAEhDO,EAAeC,GAAoBR,GAAS,IAC5CS,EAAkBC,GAAuBV,GAAS,IAGlDW,EAAeC,GAAoBZ,IAAWT,GAC/CsB,EAAsBC,GAAO,GAE7BC,EAAMC,EAAO,CACjBjC,YACAC,UACAK,gBACAC,cACAH,wBACAC,QACAG,aACAC,6BACAC,uCACAC,oBACAC,mBACAC,kBAGFqB,GAAU,KACR,GAAIF,EAAK,CACP,MAAMG,EAA0BH,EAAII,qBAAqBjB,GACnDkB,EAAkBL,EAAIM,aAAatB,GACnCuB,EACJP,EAAIQ,wBAAwBjB,GACxBkB,EAAoBT,EAAIU,eAAerB,GAE7C,MAAO,KACLc,IACAE,IACAE,IACAE,GAAmB,CAEtB,CACe,GACf,CAACT,IAEJ,MAAMW,EAAmBZ,GAAO,GAC1Ba,EAAgBb,GAAO,GAI7BG,GAAU,KACJF,GAAOxB,IAAesB,EAAoBe,UAC5Cf,EAAoBe,SAAU,EAC9Bb,EAAIc,KAAKC,oBAAoBC,SAAQ,KACnCnB,GAAiB,GAEjBc,EAAiBE,SAAU,CAAI,IAElC,GACA,IAEH,MAAMI,EAAeC,GAAY,KAE3BP,EAAiBE,UACrBF,EAAiBE,SAAU,EAE3BlB,GAAoB,GACpBwB,EAAenB,aAAA,EAAAA,EAAKoB,QAApBD,MAA6BE,GAAW,GAAMC,MAAK,KACjD3B,GAAoB,EAAM,IAC1B,GACD,CAACK,IAEEuB,EAAYL,GAAY,KAExBN,EAAcC,UAClBD,EAAcC,SAAU,EAExBpB,GAAiB,GACjB0B,EAAenB,EAAIwB,GAAnBL,GAAyBG,MAAK,KAC5B7B,GAAiB,EAAM,IACvB,GACD,CAACO,IAEEyB,EAAQC,GACZ,KAAO,CACLH,YACAxC,OACAS,gBACAoB,cAAeA,EAAcC,QAC7BI,eACA/B,UACAI,kBACAI,mBACAE,gBACAe,iBAAkBA,EAAiBE,QACnC7C,YACAC,UACAC,gBACAC,aACAM,6BACAC,uCACAC,oBACAE,gBACAG,UACAG,aACAI,qBACAH,SACAY,SAEF,CACEuB,EACAxC,EACAS,EACAoB,EAAcC,QACdI,EACA/B,EACAI,EACAI,EACAE,EACAe,EAAiBE,QACjB7C,EACAC,EACAC,EACAC,EACAO,EACAC,EACAE,EACAG,EACAG,EACAI,EACAH,EACAY,IAGJ,OAAO2B,EAAAC,cAACC,EAAQC,SAAQ,CAACL,MAAOA,GAAQ3C,EAA4B"}
1
+ {"version":3,"file":"AuthProvider.js","sources":["../../../../src/components/AuthProvider/AuthProvider.tsx"],"sourcesContent":["import React, {\n FC,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { CookieConfig, OidcConfig } from '@descope/web-js-sdk';\nimport { Claims } from '@descope/core-js-sdk';\nimport { CustomStorage } from '@descope/web-component';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { isDescopeBridge, withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ntype Hooks = Parameters<typeof useSdk>[0]['hooks'];\n\ninterface IAuthProviderProps {\n projectId: string;\n baseUrl?: string;\n // allows to override the base URL that is used to fetch static files\n baseStaticUrl?: string;\n // allows to override the base URL that is used to fetch external script files\n baseCdnUrl?: string;\n // Default is true. If true, tokens will be stored on local storage and can accessed with getToken function\n persistTokens?: boolean;\n // Default is true. If true, the SDK will automatically refresh the session token when it is about to expire\n autoRefresh?: boolean;\n // If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n // stored on local storage and can accessed with getSessionToken function\n // Use this option if session token will stay small (less than 1k)\n // NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n sessionTokenViaCookie?: CookieConfig;\n hooks?: Hooks;\n // If truthy he SDK refresh and logout functions will use the OIDC client\n // Accepts boolean or OIDC configuration\n oidcConfig?: OidcConfig;\n // Default is true. If true, last authenticated user will be stored on local storage and can accessed with getUser function\n storeLastAuthenticatedUser?: boolean;\n // If true, last authenticated user will not be removed after logout\n keepLastAuthenticatedUserAfterLogout?: boolean;\n // Use this option if the authentication is done via cookie, and configured with a different name\n // Currently, this is done using Descope Flows\n refreshCookieName?: string;\n // Function to get external token, for seamless migration from external system\n getExternalToken?: () => Promise<string>;\n // Custom storage object for authentication related data\n customStorage?: CustomStorage;\n children?: React.ReactNode;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n projectId,\n baseUrl = '',\n baseStaticUrl = '',\n baseCdnUrl = '',\n sessionTokenViaCookie = false,\n hooks = undefined,\n persistTokens = true,\n autoRefresh = true,\n oidcConfig = undefined,\n storeLastAuthenticatedUser = true,\n keepLastAuthenticatedUserAfterLogout = false,\n refreshCookieName = '',\n getExternalToken = undefined,\n customStorage = undefined,\n children = undefined,\n}) => {\n const [user, setUser] = useState<User>();\n const [session, setSession] = useState<string>();\n const [claims, setClaims] = useState<Claims>();\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n\n const [isUserLoading, setIsUserLoading] = useState(false);\n const [isSessionLoading, setIsSessionLoading] = useState(false);\n\n // if oidc config is enabled, we attempt to finish the login, so we start as loading\n const [isOidcLoading, setIsOidcLoading] = useState(!!oidcConfig);\n const isOidcFinishedLogin = useRef(false);\n\n const sdk = useSdk({\n projectId,\n baseUrl,\n persistTokens,\n autoRefresh,\n sessionTokenViaCookie,\n hooks,\n oidcConfig,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n getExternalToken,\n customStorage,\n });\n\n useEffect(() => {\n if (sdk) {\n const unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n const unsubscribeUser = sdk.onUserChange(setUser);\n const unsubscribeIsAuthenticated =\n sdk.onIsAuthenticatedChange(setIsAuthenticated);\n const unsubscribeClaims = sdk.onClaimsChange(setClaims);\n\n return () => {\n unsubscribeSessionToken();\n unsubscribeUser();\n unsubscribeIsAuthenticated();\n unsubscribeClaims();\n };\n }\n return undefined;\n }, [sdk]);\n\n const isSessionFetched = useRef(false);\n const isUserFetched = useRef(false);\n\n // if oidc config is enabled, and we have oidc params in the url\n // we will finish the login (this should run only once)\n useEffect(() => {\n if (sdk && oidcConfig && !isOidcFinishedLogin.current) {\n isOidcFinishedLogin.current = true;\n sdk.oidc.finishLoginIfNeed().finally(() => {\n setIsOidcLoading(false);\n // We want that the session will fetched only once\n isSessionFetched.current = true;\n });\n }\n }, []);\n\n const fetchSession = useCallback(() => {\n // Don't load the session in native flows, though we'd usually not get here at all from useSession in this case\n if (isDescopeBridge()) return;\n\n // We want that the session will fetched only once\n if (isSessionFetched.current) return;\n isSessionFetched.current = true;\n\n setIsSessionLoading(true);\n withValidation(sdk?.refresh)(undefined, true).then(() => {\n setIsSessionLoading(false);\n });\n }, [sdk]);\n\n const fetchUser = useCallback(() => {\n // We want that the user will fetched only once\n if (isUserFetched.current) return;\n isUserFetched.current = true;\n\n setIsUserLoading(true);\n withValidation(sdk.me)().then(() => {\n setIsUserLoading(false);\n });\n }, [sdk]);\n\n const value = useMemo<IContext>(\n () => ({\n fetchUser,\n user,\n isUserLoading,\n isUserFetched: isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched: isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n }),\n [\n fetchUser,\n user,\n isUserLoading,\n isUserFetched.current,\n fetchSession,\n session,\n isAuthenticated,\n isSessionLoading,\n isOidcLoading,\n isSessionFetched.current,\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n setUser,\n setSession,\n setIsAuthenticated,\n claims,\n sdk,\n ],\n );\n return <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n"],"names":["AuthProvider","projectId","baseUrl","baseStaticUrl","baseCdnUrl","sessionTokenViaCookie","hooks","persistTokens","autoRefresh","oidcConfig","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","getExternalToken","customStorage","children","user","setUser","useState","session","setSession","claims","setClaims","isAuthenticated","setIsAuthenticated","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","isOidcLoading","setIsOidcLoading","isOidcFinishedLogin","useRef","sdk","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","unsubscribeIsAuthenticated","onIsAuthenticatedChange","unsubscribeClaims","onClaimsChange","isSessionFetched","isUserFetched","current","oidc","finishLoginIfNeed","finally","fetchSession","useCallback","isDescopeBridge","withValidation","refresh","undefined","then","fetchUser","me","value","useMemo","React","createElement","Context","Provider"],"mappings":"mOAoDA,MAAMA,EAAuC,EAC3CC,YACAC,UAAU,GACVC,gBAAgB,GAChBC,aAAa,GACbC,yBAAwB,EACxBC,QACAC,iBAAgB,EAChBC,eAAc,EACdC,aACAC,8BAA6B,EAC7BC,wCAAuC,EACvCC,oBAAoB,GACpBC,mBACAC,gBACAC,eAEA,MAAOC,EAAMC,GAAWC,KACjBC,EAASC,GAAcF,KACvBG,EAAQC,GAAaJ,KACrBK,EAAiBC,GAAsBN,GAAS,IAEhDO,EAAeC,GAAoBR,GAAS,IAC5CS,EAAkBC,GAAuBV,GAAS,IAGlDW,EAAeC,GAAoBZ,IAAWT,GAC/CsB,EAAsBC,GAAO,GAE7BC,EAAMC,EAAO,CACjBjC,YACAC,UACAK,gBACAC,cACAH,wBACAC,QACAG,aACAC,6BACAC,uCACAC,oBACAC,mBACAC,kBAGFqB,GAAU,KACR,GAAIF,EAAK,CACP,MAAMG,EAA0BH,EAAII,qBAAqBjB,GACnDkB,EAAkBL,EAAIM,aAAatB,GACnCuB,EACJP,EAAIQ,wBAAwBjB,GACxBkB,EAAoBT,EAAIU,eAAerB,GAE7C,MAAO,KACLc,IACAE,IACAE,IACAE,GAAmB,CAEtB,CACe,GACf,CAACT,IAEJ,MAAMW,EAAmBZ,GAAO,GAC1Ba,EAAgBb,GAAO,GAI7BG,GAAU,KACJF,GAAOxB,IAAesB,EAAoBe,UAC5Cf,EAAoBe,SAAU,EAC9Bb,EAAIc,KAAKC,oBAAoBC,SAAQ,KACnCnB,GAAiB,GAEjBc,EAAiBE,SAAU,CAAI,IAElC,GACA,IAEH,MAAMI,EAAeC,GAAY,KAE3BC,KAGAR,EAAiBE,UACrBF,EAAiBE,SAAU,EAE3BlB,GAAoB,GACpByB,EAAepB,aAAA,EAAAA,EAAKqB,QAApBD,MAA6BE,GAAW,GAAMC,MAAK,KACjD5B,GAAoB,EAAM,IAC1B,GACD,CAACK,IAEEwB,EAAYN,GAAY,KAExBN,EAAcC,UAClBD,EAAcC,SAAU,EAExBpB,GAAiB,GACjB2B,EAAepB,EAAIyB,GAAnBL,GAAyBG,MAAK,KAC5B9B,GAAiB,EAAM,IACvB,GACD,CAACO,IAEE0B,EAAQC,GACZ,KAAO,CACLH,YACAzC,OACAS,gBACAoB,cAAeA,EAAcC,QAC7BI,eACA/B,UACAI,kBACAI,mBACAE,gBACAe,iBAAkBA,EAAiBE,QACnC7C,YACAC,UACAC,gBACAC,aACAM,6BACAC,uCACAC,oBACAE,gBACAG,UACAG,aACAI,qBACAH,SACAY,SAEF,CACEwB,EACAzC,EACAS,EACAoB,EAAcC,QACdI,EACA/B,EACAI,EACAI,EACAE,EACAe,EAAiBE,QACjB7C,EACAC,EACAC,EACAC,EACAO,EACAC,EACAE,EACAG,EACAG,EACAI,EACAH,EACAY,IAGJ,OAAO4B,EAAAC,cAACC,EAAQC,SAAQ,CAACL,MAAOA,GAAQ5C,EAA4B"}
@@ -1,2 +1,2 @@
1
- import{__rest as e}from"../node_modules/.pnpm/@rollup_plugin-typescript@11.1.6_rollup@4.22.4_tslib@2.8.1_typescript@5.4.5/node_modules/tslib/tslib.es6.js";import t,{lazy as r,useMemo as o,useState as n,useImperativeHandle as s,useCallback as a,useEffect as l,Suspense as u}from"react";import{baseHeaders as d}from"../constants.js";import i from"../hooks/Context.js";import{getGlobalSdk as c}from"../sdk.js";import p from"./withPropsMapping/index.js";const m=r((async()=>(((null===customElements||void 0===customElements?void 0:customElements.get("descope-wc"))||await import("@descope/web-component").then((e=>e.default))).sdkConfigOverrides={baseHeaders:d,persistTokens:!1,hooks:{get beforeRequest(){return c().httpClient.hooks.beforeRequest},set beforeRequest(e){}}},{default:p(t.forwardRef(((r,n)=>{var{"external-request-id":s}=r,a=e(r,["external-request-id"]);return o((()=>{var e,t;e="x-external-rid",(t=s)?d[e]=t:delete d[e]}),[s]),t.createElement("descope-wc",Object.assign({ref:n},a))})))}))),f=t.forwardRef((({flowId:e,onSuccess:r,onError:o,onReady:d,logger:c,tenant:p,theme:f,nonce:v,locale:E,debug:b,client:g,form:h,telemetryKey:L,redirectUrl:y,autoFocus:k,validateOnBlur:U,restartOnError:w,errorTransformer:S,styleId:x,onScreenUpdate:I,dismissScreenErrorOnInput:R,outboundAppId:C,outboundAppScopes:O,popupOrigin:j,children:q,externalRequestId:A},_)=>{const[N,T]=n(null);s(_,(()=>N));const{projectId:B,baseUrl:F,baseStaticUrl:K,baseCdnUrl:H,storeLastAuthenticatedUser:J,keepLastAuthenticatedUserAfterLogout:M,refreshCookieName:P,customStorage:z,sdk:D}=t.useContext(i),G=a((async e=>{await D.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return l((()=>{const e=N;return null==e||e.addEventListener("success",G),o&&(null==e||e.addEventListener("error",o)),d&&(null==e||e.addEventListener("ready",d)),()=>{o&&(null==e||e.removeEventListener("error",o)),d&&(null==e||e.removeEventListener("ready",d)),null==e||e.removeEventListener("success",G)}}),[N,o,G]),l((()=>{const e=N;return null==e||e.addEventListener("success",G),()=>{null==e||e.removeEventListener("success",G)}}),[N,G]),l((()=>{const e=N;return o&&(null==e||e.addEventListener("error",o)),()=>{o&&(null==e||e.removeEventListener("error",o))}}),[N,o]),l((()=>{const e=N;return d&&(null==e||e.addEventListener("ready",d)),()=>{d&&(null==e||e.removeEventListener("error",d))}}),[N,d]),t.createElement("form",null,t.createElement(u,{fallback:null},t.createElement(m,{projectId:B,flowId:e,baseUrl:F,baseStaticUrl:K,baseCdnUrl:H,ref:T,telemetryKey:L,redirectUrl:y,autoFocus:k,styleId:x,validateOnBlur:U,restartOnError:w,keepLastAuthenticatedUserAfterLogout:M,tenant:p,externalRequestId:A,customStorage:z,"theme.attr":f,"nonce.attr":v,"locale.attr":E,"form.attr":h,"client.attr":g,"debug.attr":b,"outbound-app-id.attr":C,"outbound-app-scopes.attr":O,"popup-origin.attr":j,"store-last-authenticated-user.attr":J,"refreshCookieName.attr":P,"dismiss-screen-error-on-input.attr":R,"errorTransformer.prop":S,"logger.prop":c,"onScreenUpdate.prop":I,"customStorage.prop":z},q)))}));export{f as default};
1
+ import{__rest as e}from"tslib";import t,{lazy as r,useMemo as n,useState as o,useImperativeHandle as s,useCallback as a,useEffect as l,Suspense as u}from"react";import{baseHeaders as d}from"../constants.js";import c from"../hooks/Context.js";import{getGlobalSdk as i}from"../sdk.js";import p from"./withPropsMapping/index.js";const m=r((async()=>(((null===customElements||void 0===customElements?void 0:customElements.get("descope-wc"))||await import("@descope/web-component").then((e=>e.default))).sdkConfigOverrides={baseHeaders:d,persistTokens:!1,hooks:{get beforeRequest(){return i().httpClient.hooks.beforeRequest},set beforeRequest(e){}}},{default:p(t.forwardRef(((r,o)=>{var{"external-request-id":s}=r,a=e(r,["external-request-id"]);return n((()=>{var e,t;e="x-external-rid",(t=s)?d[e]=t:delete d[e]}),[s]),t.createElement("descope-wc",Object.assign({ref:o},a))})))}))),f=t.forwardRef((({flowId:e,onSuccess:r,onError:n,onReady:d,logger:i,tenant:p,theme:f,nonce:v,locale:E,debug:b,client:g,form:h,telemetryKey:L,redirectUrl:k,autoFocus:y,validateOnBlur:U,restartOnError:w,errorTransformer:S,styleId:x,onScreenUpdate:I,dismissScreenErrorOnInput:R,outboundAppId:C,outboundAppScopes:O,popupOrigin:q,children:j,externalRequestId:A},N)=>{const[T,B]=o(null);s(N,(()=>T));const{projectId:F,baseUrl:K,baseStaticUrl:H,baseCdnUrl:J,storeLastAuthenticatedUser:M,keepLastAuthenticatedUserAfterLogout:P,refreshCookieName:z,customStorage:D,sdk:G}=t.useContext(c),Q=a((async e=>{await G.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return l((()=>{const e=T;return null==e||e.addEventListener("success",Q),n&&(null==e||e.addEventListener("error",n)),d&&(null==e||e.addEventListener("ready",d)),()=>{n&&(null==e||e.removeEventListener("error",n)),d&&(null==e||e.removeEventListener("ready",d)),null==e||e.removeEventListener("success",Q)}}),[T,n,Q]),l((()=>{const e=T;return null==e||e.addEventListener("success",Q),()=>{null==e||e.removeEventListener("success",Q)}}),[T,Q]),l((()=>{const e=T;return n&&(null==e||e.addEventListener("error",n)),()=>{n&&(null==e||e.removeEventListener("error",n))}}),[T,n]),l((()=>{const e=T;return d&&(null==e||e.addEventListener("ready",d)),()=>{d&&(null==e||e.removeEventListener("error",d))}}),[T,d]),t.createElement("form",null,t.createElement(u,{fallback:null},t.createElement(m,{projectId:F,flowId:e,baseUrl:K,baseStaticUrl:H,baseCdnUrl:J,ref:B,telemetryKey:L,redirectUrl:k,autoFocus:y,styleId:x,validateOnBlur:U,restartOnError:w,keepLastAuthenticatedUserAfterLogout:P,tenant:p,externalRequestId:A,customStorage:D,"theme.attr":f,"nonce.attr":v,"locale.attr":E,"form.attr":h,"client.attr":g,"debug.attr":b,"outbound-app-id.attr":C,"outbound-app-scopes.attr":O,"popup-origin.attr":q,"store-last-authenticated-user.attr":M,"refreshCookieName.attr":z,"dismiss-screen-error-on-input.attr":R,"errorTransformer.prop":S,"logger.prop":i,"onScreenUpdate.prop":I,"customStorage.prop":D},j)))}));export{f as default};
2
2
  //# sourceMappingURL=Descope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Descope.js","sources":["../../../src/components/Descope.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\nimport React, {\n lazy,\n Suspense,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useState,\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { getGlobalSdk } from '../sdk';\nimport withPropsMapping from './withPropsMapping';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n const updateDynamicHeader = (key: string, value: string) => {\n if (value) {\n baseHeaders[key] = value;\n } else {\n delete baseHeaders[key];\n }\n };\n\n const WebComponent: any =\n customElements?.get('descope-wc') ||\n (await import('@descope/web-component').then((module) => module.default));\n\n WebComponent.sdkConfigOverrides = {\n // Overrides the web-component's base headers to indicate usage via the React SDK\n baseHeaders,\n // Disables token persistence within the web-component to delegate token management\n // to the global SDK hooks. This ensures token handling aligns with the SDK's configuration,\n // and web-component requests leverage the global SDK's beforeRequest hooks for consistency\n persistTokens: false,\n hooks: {\n get beforeRequest() {\n // Retrieves the beforeRequest hook from the global SDK, which is initialized\n // within the AuthProvider using the desired configuration. This approach ensures\n // the web-component utilizes the same beforeRequest hooks as the global SDK\n return getGlobalSdk().httpClient.hooks.beforeRequest;\n },\n set beforeRequest(_) {\n // The empty setter prevents runtime errors when attempts are made to assign a value to 'beforeRequest'.\n // JavaScript objects default to having both getters and setters\n },\n },\n };\n\n return {\n default: withPropsMapping(\n React.forwardRef<HTMLElement>(\n ({ 'external-request-id': externalRequestId, ...props }: any, ref) => {\n // update the dynamic headers with the external request ID if provided\n useMemo(() => {\n updateDynamicHeader('x-external-rid', externalRequestId);\n }, [externalRequestId]);\n\n return <descope-wc ref={ref} {...props} />;\n },\n ),\n ),\n };\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n (\n {\n flowId,\n onSuccess,\n onError,\n onReady,\n logger,\n tenant,\n theme,\n nonce,\n locale,\n debug,\n client,\n form,\n telemetryKey,\n redirectUrl,\n autoFocus,\n validateOnBlur,\n restartOnError,\n errorTransformer,\n styleId,\n onScreenUpdate,\n dismissScreenErrorOnInput,\n outboundAppId,\n outboundAppScopes,\n popupOrigin,\n children,\n externalRequestId,\n },\n ref,\n ) => {\n const [innerRef, setInnerRef] = useState(null);\n\n useImperativeHandle(ref, () => innerRef);\n\n const {\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n sdk,\n } = React.useContext(Context);\n\n const handleSuccess = useCallback(\n async (e: CustomEvent) => {\n // In order to make sure all the after-hooks are running with the success response\n // we are generating a fake response with the success data and calling the http client after hook fn with it\n await sdk.httpClient.hooks.afterRequest(\n {} as any,\n new Response(JSON.stringify(e.detail)),\n );\n if (onSuccess) {\n onSuccess(e);\n }\n },\n [onSuccess],\n );\n\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n if (onError) ele?.addEventListener('error', onError);\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n if (onReady) ele?.removeEventListener('ready', onReady);\n\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, onError, handleSuccess]);\n\n // Success event\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n return () => {\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, handleSuccess]);\n\n // Error event\n useEffect(() => {\n const ele = innerRef;\n if (onError) ele?.addEventListener('error', onError);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n };\n }, [innerRef, onError]);\n\n // Ready event\n useEffect(() => {\n const ele = innerRef;\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onReady) ele?.removeEventListener('error', onReady);\n };\n }, [innerRef, onReady]);\n\n return (\n /**\n * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n * this workaround is done in order to support webauthn passkeys\n * it can be removed once this issue will be solved\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n */\n\t<form>\n\t\t<Suspense fallback={null}>\n\t\t\t<DescopeWC\n projectId={projectId}\n flowId={flowId}\n baseUrl={baseUrl}\n baseStaticUrl={baseStaticUrl}\n baseCdnUrl={baseCdnUrl}\n ref={setInnerRef}\n telemetryKey={telemetryKey}\n redirectUrl={redirectUrl}\n autoFocus={autoFocus}\n styleId={styleId}\n validateOnBlur={validateOnBlur}\n restartOnError={restartOnError}\n keepLastAuthenticatedUserAfterLogout={\n keepLastAuthenticatedUserAfterLogout\n }\n tenant={tenant}\n externalRequestId={externalRequestId}\n customStorage={customStorage}\n {...{\n // attributes\n 'theme.attr': theme,\n 'nonce.attr': nonce,\n 'locale.attr': locale,\n 'form.attr': form,\n 'client.attr': client,\n 'debug.attr': debug,\n 'outbound-app-id.attr': outboundAppId,\n 'outbound-app-scopes.attr': outboundAppScopes,\n 'popup-origin.attr': popupOrigin,\n 'store-last-authenticated-user.attr': storeLastAuthenticatedUser,\n 'refreshCookieName.attr': refreshCookieName,\n 'dismiss-screen-error-on-input.attr': dismissScreenErrorOnInput,\n // props\n 'errorTransformer.prop': errorTransformer,\n 'logger.prop': logger,\n 'onScreenUpdate.prop': onScreenUpdate,\n 'customStorage.prop': customStorage,\n }}\n >\n\t\t\t\t{children}\n\t\t\t</DescopeWC>\n\t\t</Suspense>\n\t</form>\n );\n },\n);\n\nexport default Descope;\n"],"names":["DescopeWC","lazy","async","customElements","get","import","then","module","default","sdkConfigOverrides","baseHeaders","persistTokens","hooks","beforeRequest","getGlobalSdk","httpClient","_","withPropsMapping","React","forwardRef","_a","ref","externalRequestId","props","__rest","useMemo","key","value","Descope","flowId","onSuccess","onError","onReady","logger","tenant","theme","nonce","locale","debug","client","form","telemetryKey","redirectUrl","autoFocus","validateOnBlur","restartOnError","errorTransformer","styleId","onScreenUpdate","dismissScreenErrorOnInput","outboundAppId","outboundAppScopes","popupOrigin","children","innerRef","setInnerRef","useState","useImperativeHandle","projectId","baseUrl","baseStaticUrl","baseCdnUrl","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","customStorage","sdk","useContext","Context","handleSuccess","useCallback","e","afterRequest","Response","JSON","stringify","detail","useEffect","ele","addEventListener","removeEventListener","createElement","Suspense","fallback"],"mappings":"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"}
1
+ {"version":3,"file":"Descope.js","sources":["../../../src/components/Descope.tsx"],"sourcesContent":["/* eslint-disable react/prop-types */\nimport React, {\n lazy,\n Suspense,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useState,\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { getGlobalSdk } from '../sdk';\nimport withPropsMapping from './withPropsMapping';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n const updateDynamicHeader = (key: string, value: string) => {\n if (value) {\n baseHeaders[key] = value;\n } else {\n delete baseHeaders[key];\n }\n };\n\n const WebComponent: any =\n customElements?.get('descope-wc') ||\n (await import('@descope/web-component').then((module) => module.default));\n\n WebComponent.sdkConfigOverrides = {\n // Overrides the web-component's base headers to indicate usage via the React SDK\n baseHeaders,\n // Disables token persistence within the web-component to delegate token management\n // to the global SDK hooks. This ensures token handling aligns with the SDK's configuration,\n // and web-component requests leverage the global SDK's beforeRequest hooks for consistency\n persistTokens: false,\n hooks: {\n get beforeRequest() {\n // Retrieves the beforeRequest hook from the global SDK, which is initialized\n // within the AuthProvider using the desired configuration. This approach ensures\n // the web-component utilizes the same beforeRequest hooks as the global SDK\n return getGlobalSdk().httpClient.hooks.beforeRequest;\n },\n set beforeRequest(_) {\n // The empty setter prevents runtime errors when attempts are made to assign a value to 'beforeRequest'.\n // JavaScript objects default to having both getters and setters\n },\n },\n };\n\n return {\n default: withPropsMapping(\n React.forwardRef<HTMLElement>(\n ({ 'external-request-id': externalRequestId, ...props }: any, ref) => {\n // update the dynamic headers with the external request ID if provided\n useMemo(() => {\n updateDynamicHeader('x-external-rid', externalRequestId);\n }, [externalRequestId]);\n\n return <descope-wc ref={ref} {...props} />;\n },\n ),\n ),\n };\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n (\n {\n flowId,\n onSuccess,\n onError,\n onReady,\n logger,\n tenant,\n theme,\n nonce,\n locale,\n debug,\n client,\n form,\n telemetryKey,\n redirectUrl,\n autoFocus,\n validateOnBlur,\n restartOnError,\n errorTransformer,\n styleId,\n onScreenUpdate,\n dismissScreenErrorOnInput,\n outboundAppId,\n outboundAppScopes,\n popupOrigin,\n children,\n externalRequestId,\n },\n ref,\n ) => {\n const [innerRef, setInnerRef] = useState(null);\n\n useImperativeHandle(ref, () => innerRef);\n\n const {\n projectId,\n baseUrl,\n baseStaticUrl,\n baseCdnUrl,\n storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout,\n refreshCookieName,\n customStorage,\n sdk,\n } = React.useContext(Context);\n\n const handleSuccess = useCallback(\n async (e: CustomEvent) => {\n // In order to make sure all the after-hooks are running with the success response\n // we are generating a fake response with the success data and calling the http client after hook fn with it\n await sdk.httpClient.hooks.afterRequest(\n {} as any,\n new Response(JSON.stringify(e.detail)),\n );\n if (onSuccess) {\n onSuccess(e);\n }\n },\n [onSuccess],\n );\n\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n if (onError) ele?.addEventListener('error', onError);\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n if (onReady) ele?.removeEventListener('ready', onReady);\n\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, onError, handleSuccess]);\n\n // Success event\n useEffect(() => {\n const ele = innerRef;\n ele?.addEventListener('success', handleSuccess);\n return () => {\n ele?.removeEventListener('success', handleSuccess);\n };\n }, [innerRef, handleSuccess]);\n\n // Error event\n useEffect(() => {\n const ele = innerRef;\n if (onError) ele?.addEventListener('error', onError);\n\n return () => {\n if (onError) ele?.removeEventListener('error', onError);\n };\n }, [innerRef, onError]);\n\n // Ready event\n useEffect(() => {\n const ele = innerRef;\n if (onReady) ele?.addEventListener('ready', onReady);\n\n return () => {\n if (onReady) ele?.removeEventListener('error', onReady);\n };\n }, [innerRef, onReady]);\n\n return (\n /**\n * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n * this workaround is done in order to support webauthn passkeys\n * it can be removed once this issue will be solved\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n */\n\t<form>\n\t\t<Suspense fallback={null}>\n\t\t\t<DescopeWC\n projectId={projectId}\n flowId={flowId}\n baseUrl={baseUrl}\n baseStaticUrl={baseStaticUrl}\n baseCdnUrl={baseCdnUrl}\n ref={setInnerRef}\n telemetryKey={telemetryKey}\n redirectUrl={redirectUrl}\n autoFocus={autoFocus}\n styleId={styleId}\n validateOnBlur={validateOnBlur}\n restartOnError={restartOnError}\n keepLastAuthenticatedUserAfterLogout={\n keepLastAuthenticatedUserAfterLogout\n }\n tenant={tenant}\n externalRequestId={externalRequestId}\n customStorage={customStorage}\n {...{\n // attributes\n 'theme.attr': theme,\n 'nonce.attr': nonce,\n 'locale.attr': locale,\n 'form.attr': form,\n 'client.attr': client,\n 'debug.attr': debug,\n 'outbound-app-id.attr': outboundAppId,\n 'outbound-app-scopes.attr': outboundAppScopes,\n 'popup-origin.attr': popupOrigin,\n 'store-last-authenticated-user.attr': storeLastAuthenticatedUser,\n 'refreshCookieName.attr': refreshCookieName,\n 'dismiss-screen-error-on-input.attr': dismissScreenErrorOnInput,\n // props\n 'errorTransformer.prop': errorTransformer,\n 'logger.prop': logger,\n 'onScreenUpdate.prop': onScreenUpdate,\n 'customStorage.prop': customStorage,\n }}\n >\n\t\t\t\t{children}\n\t\t\t</DescopeWC>\n\t\t</Suspense>\n\t</form>\n );\n },\n);\n\nexport default Descope;\n"],"names":["DescopeWC","lazy","async","customElements","get","import","then","module","default","sdkConfigOverrides","baseHeaders","persistTokens","hooks","beforeRequest","getGlobalSdk","httpClient","_","withPropsMapping","React","forwardRef","_a","ref","externalRequestId","props","__rest","useMemo","key","value","Descope","flowId","onSuccess","onError","onReady","logger","tenant","theme","nonce","locale","debug","client","form","telemetryKey","redirectUrl","autoFocus","validateOnBlur","restartOnError","errorTransformer","styleId","onScreenUpdate","dismissScreenErrorOnInput","outboundAppId","outboundAppScopes","popupOrigin","children","innerRef","setInnerRef","useState","useImperativeHandle","projectId","baseUrl","baseStaticUrl","baseCdnUrl","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","refreshCookieName","customStorage","sdk","useContext","Context","handleSuccess","useCallback","e","afterRequest","Response","JSON","stringify","detail","useEffect","ele","addEventListener","removeEventListener","createElement","Suspense","fallback"],"mappings":"sUAiBA,MAAMA,EAAYC,GAAKC,YAUnB,OAAAC,qBAAA,IAAAA,oBAAA,EAAAA,eAAgBC,IAAI,sBACbC,OAAO,0BAA0BC,MAAMC,GAAWA,EAAOC,WAErDC,mBAAqB,CAEhCC,cAIAC,eAAe,EACfC,MAAO,CACL,iBAAIC,GAIF,OAAOC,IAAeC,WAAWH,MAAMC,aACxC,EACD,iBAAIA,CAAcG,GAGjB,IAIE,CACLR,QAASS,EACPC,EAAMC,YACJ,CAACC,EAA6DC,SAA3D,sBAAuBC,GAAiBF,EAAKG,EAAKC,EAAAJ,EAApD,yBAMC,OAJAK,GAAQ,KAtCY,IAACC,EAAaC,EAAbD,EAuCC,kBAvCYC,EAuCML,GArC5CZ,EAAYgB,GAAOC,SAEZjB,EAAYgB,EAmC2C,GACvD,CAACJ,IAEGJ,4CAAYG,IAAKA,GAASE,GAAS,SAO9CK,EAAUV,EAAMC,YACpB,EAEIU,SACAC,YACAC,UACAC,UACAC,SACAC,SACAC,QACAC,QACAC,SACAC,QACAC,SACAC,OACAC,eACAC,cACAC,YACAC,iBACAC,iBACAC,mBACAC,UACAC,iBACAC,4BACAC,gBACAC,oBACAC,cACAC,WACA/B,qBAEFD,KAEA,MAAOiC,EAAUC,GAAeC,EAAS,MAEzCC,EAAoBpC,GAAK,IAAMiC,IAE/B,MAAMI,UACJA,EAASC,QACTA,EAAOC,cACPA,EAAaC,WACbA,EAAUC,2BACVA,EAA0BC,qCAC1BA,EAAoCC,kBACpCA,EAAiBC,cACjBA,EAAaC,IACbA,GACEhD,EAAMiD,WAAWC,GAEfC,EAAgBC,GACpBpE,MAAOqE,UAGCL,EAAInD,WAAWH,MAAM4D,aACzB,CAAA,EACA,IAAIC,SAASC,KAAKC,UAAUJ,EAAEK,UAE5B9C,GACFA,EAAUyC,EACX,GAEH,CAACzC,IA8CH,OA3CA+C,GAAU,KACR,MAAMC,EAAMxB,EAKZ,OAJAwB,SAAAA,EAAKC,iBAAiB,UAAWV,GAC7BtC,IAAS+C,SAAAA,EAAKC,iBAAiB,QAAShD,IACxCC,IAAS8C,SAAAA,EAAKC,iBAAiB,QAAS/C,IAErC,KACDD,IAAS+C,SAAAA,EAAKE,oBAAoB,QAASjD,IAC3CC,IAAS8C,SAAAA,EAAKE,oBAAoB,QAAShD,IAE/C8C,SAAAA,EAAKE,oBAAoB,UAAWX,EAAc,CACnD,GACA,CAACf,EAAUvB,EAASsC,IAGvBQ,GAAU,KACR,MAAMC,EAAMxB,EAEZ,OADAwB,SAAAA,EAAKC,iBAAiB,UAAWV,GAC1B,KACLS,SAAAA,EAAKE,oBAAoB,UAAWX,EAAc,CACnD,GACA,CAACf,EAAUe,IAGdQ,GAAU,KACR,MAAMC,EAAMxB,EAGZ,OAFIvB,IAAS+C,SAAAA,EAAKC,iBAAiB,QAAShD,IAErC,KACDA,IAAS+C,SAAAA,EAAKE,oBAAoB,QAASjD,GAAQ,CACxD,GACA,CAACuB,EAAUvB,IAGd8C,GAAU,KACR,MAAMC,EAAMxB,EAGZ,OAFItB,IAAS8C,SAAAA,EAAKC,iBAAiB,QAAS/C,IAErC,KACDA,IAAS8C,SAAAA,EAAKE,oBAAoB,QAAShD,GAAQ,CACxD,GACA,CAACsB,EAAUtB,IASjBd,EAAA+D,cAAA,OAAA,KACC/D,EAAA+D,cAACC,EAAQ,CAACC,SAAU,MACnBjE,EAAA+D,cAACjF,EAAS,CACD0D,UAAWA,EACX7B,OAAQA,EACR8B,QAASA,EACTC,cAAeA,EACfC,WAAYA,EACZxC,IAAKkC,EACLd,aAAcA,EACdC,YAAaA,EACbC,UAAWA,EACXI,QAASA,EACTH,eAAgBA,EAChBC,eAAgBA,EAChBkB,qCACEA,EAEF7B,OAAQA,EACRZ,kBAAmBA,EACnB2C,cAAeA,EAGb,aAAc9B,EACd,aAAcC,EACd,cAAeC,EACf,YAAaG,EACb,cAAeD,EACf,aAAcD,EACd,uBAAwBY,EACxB,2BAA4BC,EAC5B,oBAAqBC,EACrB,qCAAsCU,EACtC,yBAA0BE,EAC1B,qCAAsCf,EAEtC,wBAAyBH,EACzB,cAAeb,EACf,sBAAuBe,EACvB,qBAAsBiB,GAG/BZ,IAIC"}
@@ -1,2 +1,2 @@
1
- const e={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.0.0-next-b00a100d-20251118"},d="undefined"!=typeof window;export{d as IS_BROWSER,e as baseHeaders};
1
+ const e={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.0.0-next-cddfa808-20251204"},d="undefined"!=typeof window;export{d as IS_BROWSER,e as baseHeaders};
2
2
  //# sourceMappingURL=constants.js.map
@@ -1,2 +1,2 @@
1
- import{useRef as s,useMemo as e,useEffect as i}from"react";import t from"./useContext.js";const n=()=>{const{session:n,claims:o,isSessionLoading:c,isOidcLoading:r,fetchSession:a,isSessionFetched:d,isAuthenticated:u}=t(),m=s(c||r);e((()=>{m.current=c||r}),[c,r]);const f=!u&&!c;return e((()=>{f&&!d&&(m.current=!0)}),[d]),i((()=>{f&&a()}),[a]),{isSessionLoading:m.current,sessionToken:n,claims:o,isAuthenticated:u}};export{n as default};
1
+ import{useRef as s,useMemo as i,useEffect as t}from"react";import e from"./useContext.js";import{isDescopeBridge as o}from"../utils.js";const n=()=>{const{session:n,claims:r,isSessionLoading:c,isOidcLoading:a,fetchSession:u,isSessionFetched:d,isAuthenticated:m}=e(),f=s(c||a);i((()=>{f.current=c||a}),[c,a]);const h=!m&&!c&&!o();return i((()=>{h&&!d&&(f.current=!0)}),[d]),t((()=>{h&&u()}),[u]),{isSessionLoading:f.current,sessionToken:n,claims:r,isAuthenticated:m}};export{n as default};
2
2
  //# sourceMappingURL=useSession.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSession.js","sources":["../../../src/hooks/useSession.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n const {\n session,\n claims,\n isSessionLoading,\n isOidcLoading,\n fetchSession,\n isSessionFetched,\n isAuthenticated,\n } = useContext();\n\n // when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n // (and not only when receiving an update from the context)\n const isLoading = useRef(isSessionLoading || isOidcLoading);\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n isLoading.current = isSessionLoading || isOidcLoading;\n }, [isSessionLoading, isOidcLoading]);\n\n const shouldFetchSession = !isAuthenticated && !isSessionLoading;\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n if (shouldFetchSession && !isSessionFetched) {\n isLoading.current = true;\n }\n }, [isSessionFetched]);\n\n // Fetch session if it's not already fetched\n // We want this to happen only once, so the dependency array should not contain shouldFetchSession\n useEffect(() => {\n if (shouldFetchSession) {\n fetchSession();\n }\n }, [fetchSession]);\n return {\n isSessionLoading: isLoading.current,\n sessionToken: session,\n claims,\n isAuthenticated,\n };\n};\n\nexport default useSession;\n"],"names":["useSession","session","claims","isSessionLoading","isOidcLoading","fetchSession","isSessionFetched","isAuthenticated","useContext","isLoading","useRef","useMemo","current","shouldFetchSession","useEffect","sessionToken"],"mappings":"0FAGM,MAAAA,EAAa,KACjB,MAAMC,QACJA,EAAOC,OACPA,EAAMC,iBACNA,EAAgBC,cAChBA,EAAaC,aACbA,EAAYC,iBACZA,EAAgBC,gBAChBA,GACEC,IAIEC,EAAYC,EAAOP,GAAoBC,GAG7CO,GAAQ,KACNF,EAAUG,QAAUT,GAAoBC,CAAa,GACpD,CAACD,EAAkBC,IAEtB,MAAMS,GAAsBN,IAAoBJ,EAgBhD,OAbAQ,GAAQ,KACFE,IAAuBP,IACzBG,EAAUG,SAAU,EACrB,GACA,CAACN,IAIJQ,GAAU,KACJD,GACFR,GACD,GACA,CAACA,IACG,CACLF,iBAAkBM,EAAUG,QAC5BG,aAAcd,EACdC,SACAK,kBACD"}
1
+ {"version":3,"file":"useSession.js","sources":["../../../src/hooks/useSession.ts"],"sourcesContent":["import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\nimport { isDescopeBridge } from '../utils';\n\nconst useSession = () => {\n const {\n session,\n claims,\n isSessionLoading,\n isOidcLoading,\n fetchSession,\n isSessionFetched,\n isAuthenticated,\n } = useContext();\n\n // when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n // (and not only when receiving an update from the context)\n const isLoading = useRef(isSessionLoading || isOidcLoading);\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n isLoading.current = isSessionLoading || isOidcLoading;\n }, [isSessionLoading, isOidcLoading]);\n\n // In case we're in a native flow, we won't refresh the session anyway, so no point in marking the state as loading\n const shouldFetchSession = !isAuthenticated && !isSessionLoading && !isDescopeBridge();\n\n // we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n useMemo(() => {\n if (shouldFetchSession && !isSessionFetched) {\n isLoading.current = true;\n }\n }, [isSessionFetched]);\n\n // Fetch session if it's not already fetched\n // We want this to happen only once, so the dependency array should not contain shouldFetchSession\n useEffect(() => {\n if (shouldFetchSession) {\n fetchSession();\n }\n }, [fetchSession]);\n return {\n isSessionLoading: isLoading.current,\n sessionToken: session,\n claims,\n isAuthenticated,\n };\n};\n\nexport default useSession;\n"],"names":["useSession","session","claims","isSessionLoading","isOidcLoading","fetchSession","isSessionFetched","isAuthenticated","useContext","isLoading","useRef","useMemo","current","shouldFetchSession","isDescopeBridge","useEffect","sessionToken"],"mappings":"wIAIM,MAAAA,EAAa,KACjB,MAAMC,QACJA,EAAOC,OACPA,EAAMC,iBACNA,EAAgBC,cAChBA,EAAaC,aACbA,EAAYC,iBACZA,EAAgBC,gBAChBA,GACEC,IAIEC,EAAYC,EAAOP,GAAoBC,GAG7CO,GAAQ,KACNF,EAAUG,QAAUT,GAAoBC,CAAa,GACpD,CAACD,EAAkBC,IAGtB,MAAMS,GAAsBN,IAAoBJ,IAAqBW,IAgBrE,OAbAH,GAAQ,KACFE,IAAuBP,IACzBG,EAAUG,SAAU,EACrB,GACA,CAACN,IAIJS,GAAU,KACJF,GACFR,GACD,GACA,CAACA,IACG,CACLF,iBAAkBM,EAAUG,QAC5BI,aAAcf,EACdC,SACAK,kBACD"}
package/dist/esm/utils.js CHANGED
@@ -1,2 +1,2 @@
1
- const r=r=>(...t)=>{if(!r)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return r(...t)},t=r=>(...t)=>{let o;try{o=r(...t)}catch(r){console.error(r)}return o};export{r as withValidation,t as wrapInTry};
1
+ const o=o=>(...e)=>{if(!o)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return o(...e)},e=o=>(...e)=>{let r;try{r=o(...e)}catch(o){console.error(o)}return r},r=()=>"undefined"!=typeof window&&!!window.descopeBridge;export{r as isDescopeBridge,o as withValidation,e as wrapInTry};
2
2
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["/**\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 extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n if (!fn) {\n throw Error(\n `You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,\n );\n }\n return fn(...args);\n };\n\nexport const wrapInTry =\n <T extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n let res: U;\n try {\n res = fn(...args);\n } catch (err) {\n console.error(err); // eslint-disable-line no-console\n }\n return res;\n };\n"],"names":["withValidation","fn","args","Error","wrapInTry","res","err","console","error"],"mappings":"AAKO,MAAMA,EACeC,GAC1B,IAAIC,KACF,IAAKD,EACH,MAAME,MACJ,0HAGJ,OAAOF,KAAMC,EAAK,EAGTE,EACeH,GAC1B,IAAIC,KACF,IAAIG,EACJ,IACEA,EAAMJ,KAAMC,EACb,CAAC,MAAOI,GACPC,QAAQC,MAAMF,EACf,CACD,OAAOD,CAAG"}
1
+ {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["/**\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 extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n if (!fn) {\n throw Error(\n `You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,\n );\n }\n return fn(...args);\n };\n\nexport const wrapInTry =\n <T extends Array<any>, U>(fn: (...args: T) => U) =>\n (...args: T): U => {\n let res: U;\n try {\n res = fn(...args);\n } catch (err) {\n console.error(err); // eslint-disable-line no-console\n }\n return res;\n };\n\n// Detect if running in a native flow (e.g., mobile app with Descope bridge in a webview)\nexport const isDescopeBridge = () =>\n typeof window !== 'undefined' && !!window['descopeBridge'];\n"],"names":["withValidation","fn","args","Error","wrapInTry","res","err","console","error","isDescopeBridge","window"],"mappings":"AAKO,MAAMA,EACeC,GAC1B,IAAIC,KACF,IAAKD,EACH,MAAME,MACJ,0HAGJ,OAAOF,KAAMC,EAAK,EAGTE,EACeH,GAC1B,IAAIC,KACF,IAAIG,EACJ,IACEA,EAAMJ,KAAMC,EACb,CAAC,MAAOI,GACPC,QAAQC,MAAMF,EACf,CACD,OAAOD,CAAG,EAIDI,EAAkB,IACX,oBAAXC,UAA4BA,OAAsB"}
package/dist/index.d.ts CHANGED
@@ -117,10 +117,10 @@ declare const createSdkWrapper: <P extends {
117
117
  }, "loginId" | "name">;
118
118
  }, conditionInteractionId?: string, interactionId?: string, componentsVersion?: string, flowVersions?: Record<string, number>, input?: {
119
119
  [x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
120
- }) => Promise<_1.SdkResponse<_1.FlowResponse>>;
120
+ }, isCustomScreen?: any) => Promise<_1.SdkResponse<_1.FlowResponse>>;
121
121
  next: (executionId: string, stepId: string, interactionId: string, version?: number, componentsVersion?: string, input?: {
122
122
  [x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
123
- }) => Promise<_1.SdkResponse<_1.FlowResponse>>;
123
+ }, isCustomScreen?: any) => Promise<_1.SdkResponse<_1.FlowResponse>>;
124
124
  };
125
125
  webauthn: {
126
126
  signUp: ((identifier: string, name: string, passkeyOptions?: _1.PasskeyOptions) => Promise<_1.SdkResponse<_1.JWTResponse>>) & {
@@ -594,7 +594,7 @@ declare const createSdkWrapper: <P extends {
594
594
  }, token?: string) => Promise<_1.SdkResponse<_1.URLResponse>>;
595
595
  };
596
596
  saml: {
597
- start: (tenantIdOrEmail: string, redirectUrl?: string, loginOptions?: _1.LoginOptions, token?: string, ssoId?: string, forceAuthn?: boolean, loginHint?: string) => Promise<_1.SdkResponse<_1.URLResponse>>;
597
+ start: (tenantIdOrEmail: string, redirectUrl?: string, loginOptions?: _1.LoginOptions, token?: string, ssoId?: string, forceAuthn?: boolean, loginHint?: string, enforceInitiatedEmail?: boolean) => Promise<_1.SdkResponse<_1.URLResponse>>;
598
598
  exchange: (code: string) => Promise<_1.SdkResponse<_1.JWTResponse>>;
599
599
  };
600
600
  totp: {
@@ -763,10 +763,10 @@ declare const createSdkWrapper: <P extends {
763
763
  }, "loginId" | "name">;
764
764
  }, conditionInteractionId?: string, interactionId?: string, componentsVersion?: string, flowVersions?: Record<string, number>, input?: {
765
765
  [x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
766
- }) => Promise<_1.SdkResponse<_1.FlowResponse>>;
766
+ }, isCustomScreen?: any) => Promise<_1.SdkResponse<_1.FlowResponse>>;
767
767
  next: (executionId: string, stepId: string, interactionId: string, version?: number, componentsVersion?: string, input?: {
768
768
  [x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
769
- }) => Promise<_1.SdkResponse<_1.FlowResponse>>;
769
+ }, isCustomScreen?: any) => Promise<_1.SdkResponse<_1.FlowResponse>>;
770
770
  };
771
771
  webauthn: {
772
772
  signUp: ((identifier: string, name: string, passkeyOptions?: _1.PasskeyOptions) => Promise<_1.SdkResponse<_1.JWTResponse>>) & {
@@ -1240,7 +1240,7 @@ declare const createSdkWrapper: <P extends {
1240
1240
  }, token?: string) => Promise<_1.SdkResponse<_1.URLResponse>>;
1241
1241
  };
1242
1242
  saml: {
1243
- start: (tenantIdOrEmail: string, redirectUrl?: string, loginOptions?: _1.LoginOptions, token?: string, ssoId?: string, forceAuthn?: boolean, loginHint?: string) => Promise<_1.SdkResponse<_1.URLResponse>>;
1243
+ start: (tenantIdOrEmail: string, redirectUrl?: string, loginOptions?: _1.LoginOptions, token?: string, ssoId?: string, forceAuthn?: boolean, loginHint?: string, enforceInitiatedEmail?: boolean) => Promise<_1.SdkResponse<_1.URLResponse>>;
1244
1244
  exchange: (code: string) => Promise<_1.SdkResponse<_1.JWTResponse>>;
1245
1245
  };
1246
1246
  totp: {
@@ -1409,10 +1409,10 @@ declare const createSdkWrapper: <P extends {
1409
1409
  }, "loginId" | "name">;
1410
1410
  }, conditionInteractionId?: string, interactionId?: string, componentsVersion?: string, flowVersions?: Record<string, number>, input?: {
1411
1411
  [x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
1412
- }) => Promise<_1.SdkResponse<_1.FlowResponse>>;
1412
+ }, isCustomScreen?: any) => Promise<_1.SdkResponse<_1.FlowResponse>>;
1413
1413
  next: (executionId: string, stepId: string, interactionId: string, version?: number, componentsVersion?: string, input?: {
1414
1414
  [x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
1415
- }) => Promise<_1.SdkResponse<_1.FlowResponse>>;
1415
+ }, isCustomScreen?: any) => Promise<_1.SdkResponse<_1.FlowResponse>>;
1416
1416
  };
1417
1417
  webauthn: {
1418
1418
  signUp: ((identifier: string, name: string, passkeyOptions?: _1.PasskeyOptions) => Promise<_1.SdkResponse<_1.JWTResponse>>) & {
@@ -1886,7 +1886,7 @@ declare const createSdkWrapper: <P extends {
1886
1886
  }, token?: string) => Promise<_1.SdkResponse<_1.URLResponse>>;
1887
1887
  };
1888
1888
  saml: {
1889
- start: (tenantIdOrEmail: string, redirectUrl?: string, loginOptions?: _1.LoginOptions, token?: string, ssoId?: string, forceAuthn?: boolean, loginHint?: string) => Promise<_1.SdkResponse<_1.URLResponse>>;
1889
+ start: (tenantIdOrEmail: string, redirectUrl?: string, loginOptions?: _1.LoginOptions, token?: string, ssoId?: string, forceAuthn?: boolean, loginHint?: string, enforceInitiatedEmail?: boolean) => Promise<_1.SdkResponse<_1.URLResponse>>;
1890
1890
  exchange: (code: string) => Promise<_1.SdkResponse<_1.JWTResponse>>;
1891
1891
  };
1892
1892
  totp: {