@smart-cloud/gatey-core 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var P=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var q=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},H=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of J(t))!Y.call(e,r)&&r!==n&&P(e,r,{get:()=>t[r],enumerable:!(o=X(t,r))||o.enumerable});return e};var $=e=>H(P({},"__esModule",{value:!0}),e);var ae={};q(ae,{TEXT_DOMAIN:()=>M,clearMfaPreferences:()=>I,configureAmplify:()=>m,getAmplifyConfig:()=>S,getGroups:()=>h,getMfaPreferences:()=>O,getPreferredRole:()=>F,getRoles:()=>N,getScopes:()=>_,getUserAttributes:()=>R,isAuthenticated:()=>w,isInGroup:()=>G,loadAuthSession:()=>l,loadMFAPreferences:()=>x,loadUserAttributes:()=>E,login:()=>V,logout:()=>A,observeStore:()=>d,store:()=>B});module.exports=$(ae);var s=require("aws-amplify/api"),C=require("@wordpress/data");var U=require("aws-amplify"),i=require("aws-amplify/auth");var k=require("aws-amplify/auth"),T=require("aws-amplify/utils"),a=require("@wordpress/data"),D=require("@smart-cloud/wpsuite-core");var f="gatey_account",M="gatey";var b;typeof WpSuite<"u"?b=WpSuite.siteSettings:b={};var y=e=>{e?.username?window.localStorage.setItem(f,JSON.stringify(e)):window.localStorage.removeItem(f)},p=async e=>{let t=JSON.parse(window.localStorage.getItem(f)??"{}"),n=!1;if(t?.username)try{let o=await(0,k.fetchAuthSession)();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await W(!1),t?.username&&(y(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(y({}),Gatey.cognito.store.then(async o=>{await A(e?.signOutHook),await(0,a.dispatch)(o).clearAccount()})),t},Q=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=Gatey.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(Gatey.settings.secondaryUserPoolDomains.toLowerCase())&&Gatey.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?Gatey.settings?.userPoolConfigurations.secondary:Gatey.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...n.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...n.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+Gatey?.settings?.signInPage],redirectSignOut:[window.location.origin+Gatey?.settings?.signInPage]}}}},API:{...n.API,REST:{...n.API?.REST,admin:{endpoint:Gatey.restUrl}}}},r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;r?.apis?.forEach(u=>{let g=o.API?.REST;g&&(g[u.name]={endpoint:u.endpoint,region:u.region})}),m(o,{API:{REST:{headers:async u=>{let g=r?.apis?.find(c=>c.name===u.apiName);if(u.apiName==="admin"||g?.authorization==="ID_TOKEN"||g?.authorization==="ACCESS_TOKEN")try{let c=await l();if(c?.tokens?.idToken&&c?.tokens?.accessToken)return{Authorization:`Bearer ${u.apiName==="admin"||g?.authorization==="ID_TOKEN"?c.tokens.idToken.toString():c.tokens.accessToken.toString()}`}}catch(c){console.error(c),Gatey.cognito.store.then(j=>{(0,a.dispatch)(j).clearAccount()})}return{}}}}})},Z=async()=>{let e=null;return Gatey.settings.customTranslationsUrl&&(e=await fetch(Gatey.settings.customTranslationsUrl+(Gatey.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+b.lastUpdate).then(t=>t.ok?t.text():null).then(t=>t?JSON.parse(t):null).catch(()=>null)),e??null},ee=async()=>{let e=await(0,D.getConfig)("gatey");Q(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,o=await p(n),r=await Z();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},te={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?T.I18n.setLanguage(""):T.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},ne={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},oe={},v=async()=>{let e=await ee(),t=(0,a.createReduxStore)("wpsuite/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return y(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return y({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:te,selectors:ne,resolvers:oe});return(0,a.register)(t),t},d=(e,t,n)=>{let o;function r(){let u=(0,a.select)(e).getState(),g=t(u);if(g!==o){let c=o;o=g,n(o,c)}}let L=(0,a.subscribe)(r,e);return r(),L};var S=()=>U.Amplify.getConfig(),m=(e,t)=>{U.Amplify.configure(e,t)},l=e=>(0,i.fetchAuthSession)(e),E=()=>(0,i.fetchUserAttributes)(),x=()=>(0,i.fetchMFAPreference)(),W=async(e=!0)=>{let t=e?await p():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await E(),mfaPreferences:await x()}}catch(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},I=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},K=()=>p().then(e=>e?.username),R=()=>p().then(e=>e?.userAttributes),O=()=>p().then(e=>e?.mfaPreferences),w=()=>p().then(e=>!!e?.username),G=e=>h().then(t=>t?.includes(e)||!1),h=()=>l().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),N=async()=>l().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),F=async()=>l().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),_=()=>l().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),V=async e=>{let t;return Gatey.settings.integrateWpLogin&&Gatey.restUrl?.startsWith("http")&&(t=await Gatey.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),Gatey.settings.redirectSignIn??t},A=async e=>{let t;Gatey.settings.integrateWpLogin&&(t=await Gatey.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await(0,i.signOut)()}catch{}return Gatey.settings.redirectSignOut??t};var re=()=>{Gatey.cognito.store.then(e=>{d(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),(0,C.dispatch)(e).clearAccount()})},ie=e=>{Gatey.cognito.store.then(t=>{(0,C.dispatch)(t).setLanguage(e??"en")})},se=e=>{Gatey.cognito.store.then(t=>{(0,C.dispatch)(t).setDirection(e??"auto")})};var z=!!Gatey.cognito?.store,B=Gatey.cognito?.store??v();z||(Gatey.cognito={store:B,observeStore:d,setLanguage:ie,setDirection:se,getAmplifyConfig:S,isAuthenticated:w,isInGroup:G,getUsername:K,getUserAttributes:R,getMfaPreferences:O,clearMfaPreferences:I,getGroups:h,getRoles:N,getPreferredRole:F,getScopes:_,signOut:re,get:s.get,post:s.post,put:s.put,del:s.del,head:s.head,patch:s.patch});z=!0;0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getUserAttributes,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,store});
1
+ "use strict";var P=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var q=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},H=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of J(t))!Y.call(e,r)&&r!==n&&P(e,r,{get:()=>t[r],enumerable:!(o=X(t,r))||o.enumerable});return e};var $=e=>H(P({},"__esModule",{value:!0}),e);var ce={};q(ce,{TEXT_DOMAIN:()=>M,clearMfaPreferences:()=>I,configureAmplify:()=>A,getAmplifyConfig:()=>h,getGroups:()=>C,getMfaPreferences:()=>R,getPreferredRole:()=>F,getRoles:()=>G,getScopes:()=>_,getUserAttributes:()=>O,isAuthenticated:()=>w,isInGroup:()=>N,loadAuthSession:()=>l,loadMFAPreferences:()=>E,loadUserAttributes:()=>x,login:()=>V,logout:()=>S,observeStore:()=>f,store:()=>B});module.exports=$(ce);var s=require("aws-amplify/api");var U=require("aws-amplify"),i=require("aws-amplify/auth");var D=require("aws-amplify/auth"),T=require("aws-amplify/utils"),c=require("@wordpress/data"),k=require("@smart-cloud/wpsuite-core");var y="gatey_account",M="gatey";var b;typeof WpSuite<"u"?b=WpSuite.siteSettings:b={};var m=e=>{e?.username?window.localStorage.setItem(y,JSON.stringify(e)):window.localStorage.removeItem(y)},p=async e=>{let t=JSON.parse(window.localStorage.getItem(y)??"{}"),n=!1;if(t?.username)try{let o=await(0,D.fetchAuthSession)();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await W(!1),t?.username&&(m(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(m({}),Gatey.cognito.store.then(async o=>{await S(e?.signOutHook),await d(o).clearAccount()})),t},Q=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=Gatey.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(Gatey.settings.secondaryUserPoolDomains.toLowerCase())&&Gatey.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?Gatey.settings?.userPoolConfigurations.secondary:Gatey.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...n.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...n.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+Gatey?.settings?.signInPage],redirectSignOut:[window.location.origin+Gatey?.settings?.signInPage]}}}},API:{...n.API,REST:{...n.API?.REST,admin:{endpoint:Gatey.restUrl}}}},r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;r?.apis?.forEach(u=>{let g=o.API?.REST;g&&(g[u.name]={endpoint:u.endpoint,region:u.region})}),A(o,{API:{REST:{headers:async u=>{let g=r?.apis?.find(a=>a.name===u.apiName);if(u.apiName==="admin"||g?.authorization==="ID_TOKEN"||g?.authorization==="ACCESS_TOKEN")try{let a=await l();if(a?.tokens?.idToken&&a?.tokens?.accessToken)return{Authorization:`Bearer ${u.apiName==="admin"||g?.authorization==="ID_TOKEN"?a.tokens.idToken.toString():a.tokens.accessToken.toString()}`}}catch(a){console.error(a),Gatey.cognito.store.then(j=>{d(j).clearAccount()})}return{}}}}})},Z=async()=>{let e=null;return Gatey.settings.customTranslationsUrl&&(e=await fetch(Gatey.settings.customTranslationsUrl+(Gatey.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+b.lastUpdate).then(t=>t.ok?t.text():null).then(t=>t?JSON.parse(t):null).catch(()=>null)),e??null},ee=async()=>{let e=await(0,k.getConfig)("gatey");Q(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,o=await p(n),r=await Z();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},te={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?T.I18n.setLanguage(""):T.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},ne={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},oe={},d=e=>(0,c.dispatch)(e),re=e=>(0,c.select)(e),v=async()=>{let e=await ee(),t=(0,c.createReduxStore)("wpsuite/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return m(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return m({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:te,selectors:ne,resolvers:oe});return(0,c.register)(t),t},f=(e,t,n)=>{let o;function r(){let u=re(e).getState(),g=t(u);if(g!==o){let a=o;o=g,n(o,a)}}let L=(0,c.subscribe)(r,e);return r(),L};var h=()=>U.Amplify.getConfig(),A=(e,t)=>{U.Amplify.configure(e,t)},l=e=>(0,i.fetchAuthSession)(e),x=()=>(0,i.fetchUserAttributes)(),E=()=>(0,i.fetchMFAPreference)(),W=async(e=!0)=>{let t=e?await p():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await x(),mfaPreferences:await E()}}catch(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},I=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},K=()=>p().then(e=>e?.username),O=()=>p().then(e=>e?.userAttributes),R=()=>p().then(e=>e?.mfaPreferences),w=()=>p().then(e=>!!e?.username),N=e=>C().then(t=>t?.includes(e)||!1),C=()=>l().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),G=async()=>l().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),F=async()=>l().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),_=()=>l().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),V=async e=>{let t;return Gatey.settings.integrateWpLogin&&Gatey.restUrl?.startsWith("http")&&(t=await Gatey.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),Gatey.settings.redirectSignIn??t},S=async e=>{let t;Gatey.settings.integrateWpLogin&&(t=await Gatey.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await(0,i.signOut)()}catch{}return Gatey.settings.redirectSignOut??t};var ie=()=>{Gatey.cognito.store.then(e=>{f(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()})},se=e=>{Gatey.cognito.store.then(t=>{d(t).setLanguage(e??"en")})},ae=e=>{Gatey.cognito.store.then(t=>{d(t).setDirection(e??"auto")})};var z=!!Gatey.cognito?.store,B=Gatey.cognito?.store??v();z||(Gatey.cognito={store:B,observeStore:f,setLanguage:se,setDirection:ae,getAmplifyConfig:h,isAuthenticated:w,isInGroup:N,getUsername:K,getUserAttributes:O,getMfaPreferences:R,clearMfaPreferences:I,getGroups:C,getRoles:G,getPreferredRole:F,getScopes:_,signOut:ie,get:s.get,post:s.post,put:s.put,del:s.del,head:s.head,patch:s.patch});z=!0;0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getUserAttributes,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,store});
package/dist/index.d.cts CHANGED
@@ -3,57 +3,54 @@ import { get, post, put, del, head, patch } from 'aws-amplify/api';
3
3
  import { FormFieldOptionValue, LoginMechanism, SignUpAttribute, SocialProvider } from '@aws-amplify/ui';
4
4
  import { FetchUserAttributesOutput, FetchMFAPreferenceOutput, FetchAuthSessionOptions, AuthSession } from 'aws-amplify/auth';
5
5
  import { CustomProvider } from '@aws-amplify/ui-react';
6
- import { StoreDescriptor, ReduxStoreConfig } from '@wordpress/data/build-types/types';
6
+ import { StoreDescriptor as StoreDescriptor$1 } from '@wordpress/data';
7
7
 
8
- declare const actions: {
9
- setAmplifyConfig(amplifyConfig: ResourcesConfig): {
10
- type: string;
11
- amplifyConfig: ResourcesConfig;
12
- };
13
- setAccount(account: Account): {
14
- type: string;
15
- account: Account;
16
- };
17
- clearAccount(): {
18
- type: string;
19
- };
20
- setSignedIn(signedIn: boolean): {
21
- type: string;
22
- signedIn: boolean;
23
- };
24
- setNextUrl(nextUrl: string | undefined | null): {
25
- type: string;
26
- nextUrl: string | null | undefined;
27
- };
28
- setLanguage(language: string | undefined | null): {
29
- type: string;
30
- language: string | null | undefined;
31
- };
32
- setDirection(direction: "ltr" | "rtl" | "auto" | undefined | null): {
33
- type: string;
34
- direction: "ltr" | "rtl" | "auto" | null | undefined;
35
- };
36
- reloadAuthSession(): {
37
- type: string;
38
- };
39
- reloadUserAttributes(): {
40
- type: string;
41
- };
42
- reloadMFAPreferences(): {
43
- type: string;
44
- };
8
+ /**
9
+ * External dependencies
10
+ */
11
+
12
+ type MapOf<T> = {
13
+ [name: string]: T;
45
14
  };
46
- declare const selectors: {
47
- getAmplifyConfig(state: State): ResourcesConfig;
48
- getAccount(state: State): Account;
49
- getNextUrl(state: State): string | null | undefined;
50
- isSignedIn(state: State): boolean;
51
- getConfig(state: State): AuthenticatorConfig | null;
52
- getCustomTranslations(state: State): CustomTranslations | null;
53
- getLanguage(state: State): string | null | undefined;
54
- getDirection(state: State): "ltr" | "rtl" | "auto" | null | undefined;
55
- getState(state: State): State;
15
+ type ActionCreator = (...args: any[]) => any | Generator;
16
+ type Resolver = Function | Generator;
17
+ type AnyConfig = ReduxStoreConfig<any, any, any>;
18
+ interface StoreInstance<Config extends AnyConfig> {
19
+ getSelectors: () => SelectorsOf<Config>;
20
+ getActions: () => ActionCreatorsOf<Config>;
21
+ subscribe: (listener: () => void) => () => void;
22
+ }
23
+ interface StoreDescriptor<Config extends AnyConfig> {
24
+ /**
25
+ * Store Name
26
+ */
27
+ name: string;
28
+ /**
29
+ * Creates a store instance
30
+ */
31
+ instantiate: (registry: DataRegistry) => StoreInstance<Config>;
32
+ }
33
+ interface ReduxStoreConfig<State, ActionCreators extends MapOf<ActionCreator>, Selectors> {
34
+ initialState?: State;
35
+ reducer: (state: any, action: any) => any;
36
+ actions?: ActionCreators;
37
+ resolvers?: MapOf<Resolver>;
38
+ selectors?: Selectors;
39
+ controls?: MapOf<Function>;
40
+ }
41
+ interface DataRegistry {
42
+ register: (store: StoreDescriptor<any>) => void;
43
+ }
44
+ type ActionCreatorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, infer ActionCreators, any> ? PromisifiedActionCreators<ActionCreators> : never;
45
+ type PromisifiedActionCreators<ActionCreators extends MapOf<ActionCreator>> = {
46
+ [Action in keyof ActionCreators]: PromisifyActionCreator<ActionCreators[Action]>;
56
47
  };
48
+ type PromisifyActionCreator<Action extends ActionCreator> = (...args: Parameters<Action>) => Promise<ReturnType<Action> extends (..._args: any[]) => any ? ThunkReturnType<Action> : ReturnType<Action>>;
49
+ type ThunkReturnType<Action extends ActionCreator> = Awaited<ReturnType<ReturnType<Action>>>;
50
+ type SelectorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, any, infer Selectors> ? {
51
+ [name in keyof Selectors]: Function;
52
+ } : never;
53
+
57
54
  interface FormField {
58
55
  name: string;
59
56
  type: string;
@@ -111,7 +108,7 @@ interface State {
111
108
  reloadMFAPreferences: number;
112
109
  }
113
110
  type SubscriptionType = "PROFESSIONAL" | "AGENCY";
114
- type Store = StoreDescriptor<ReduxStoreConfig<State, typeof actions, typeof selectors>>;
111
+ type Store = StoreDescriptor$1;
115
112
  declare const observeStore: (observableStore: Store, selector: (state: State) => ResourcesConfig | Account | boolean | number | string | null | undefined, onChange: (nextValue: ResourcesConfig | Account | boolean | number | string | null | undefined, previousValue: ResourcesConfig | Account | boolean | number | string | null | undefined) => void) => any;
116
113
 
117
114
  interface Account {
@@ -214,6 +211,6 @@ interface Gatey {
214
211
  uploadUrl: string;
215
212
  }
216
213
 
217
- declare const store: Promise<Store>;
214
+ declare const store: Promise<StoreDescriptor<any>>;
218
215
 
219
216
  export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, Gatey, type RoleMapping, type Settings, type SiteSettings, type State, type Store, type SubscriptionType, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getUserAttributes, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, store };
package/dist/index.d.ts CHANGED
@@ -3,57 +3,54 @@ import { get, post, put, del, head, patch } from 'aws-amplify/api';
3
3
  import { FormFieldOptionValue, LoginMechanism, SignUpAttribute, SocialProvider } from '@aws-amplify/ui';
4
4
  import { FetchUserAttributesOutput, FetchMFAPreferenceOutput, FetchAuthSessionOptions, AuthSession } from 'aws-amplify/auth';
5
5
  import { CustomProvider } from '@aws-amplify/ui-react';
6
- import { StoreDescriptor, ReduxStoreConfig } from '@wordpress/data/build-types/types';
6
+ import { StoreDescriptor as StoreDescriptor$1 } from '@wordpress/data';
7
7
 
8
- declare const actions: {
9
- setAmplifyConfig(amplifyConfig: ResourcesConfig): {
10
- type: string;
11
- amplifyConfig: ResourcesConfig;
12
- };
13
- setAccount(account: Account): {
14
- type: string;
15
- account: Account;
16
- };
17
- clearAccount(): {
18
- type: string;
19
- };
20
- setSignedIn(signedIn: boolean): {
21
- type: string;
22
- signedIn: boolean;
23
- };
24
- setNextUrl(nextUrl: string | undefined | null): {
25
- type: string;
26
- nextUrl: string | null | undefined;
27
- };
28
- setLanguage(language: string | undefined | null): {
29
- type: string;
30
- language: string | null | undefined;
31
- };
32
- setDirection(direction: "ltr" | "rtl" | "auto" | undefined | null): {
33
- type: string;
34
- direction: "ltr" | "rtl" | "auto" | null | undefined;
35
- };
36
- reloadAuthSession(): {
37
- type: string;
38
- };
39
- reloadUserAttributes(): {
40
- type: string;
41
- };
42
- reloadMFAPreferences(): {
43
- type: string;
44
- };
8
+ /**
9
+ * External dependencies
10
+ */
11
+
12
+ type MapOf<T> = {
13
+ [name: string]: T;
45
14
  };
46
- declare const selectors: {
47
- getAmplifyConfig(state: State): ResourcesConfig;
48
- getAccount(state: State): Account;
49
- getNextUrl(state: State): string | null | undefined;
50
- isSignedIn(state: State): boolean;
51
- getConfig(state: State): AuthenticatorConfig | null;
52
- getCustomTranslations(state: State): CustomTranslations | null;
53
- getLanguage(state: State): string | null | undefined;
54
- getDirection(state: State): "ltr" | "rtl" | "auto" | null | undefined;
55
- getState(state: State): State;
15
+ type ActionCreator = (...args: any[]) => any | Generator;
16
+ type Resolver = Function | Generator;
17
+ type AnyConfig = ReduxStoreConfig<any, any, any>;
18
+ interface StoreInstance<Config extends AnyConfig> {
19
+ getSelectors: () => SelectorsOf<Config>;
20
+ getActions: () => ActionCreatorsOf<Config>;
21
+ subscribe: (listener: () => void) => () => void;
22
+ }
23
+ interface StoreDescriptor<Config extends AnyConfig> {
24
+ /**
25
+ * Store Name
26
+ */
27
+ name: string;
28
+ /**
29
+ * Creates a store instance
30
+ */
31
+ instantiate: (registry: DataRegistry) => StoreInstance<Config>;
32
+ }
33
+ interface ReduxStoreConfig<State, ActionCreators extends MapOf<ActionCreator>, Selectors> {
34
+ initialState?: State;
35
+ reducer: (state: any, action: any) => any;
36
+ actions?: ActionCreators;
37
+ resolvers?: MapOf<Resolver>;
38
+ selectors?: Selectors;
39
+ controls?: MapOf<Function>;
40
+ }
41
+ interface DataRegistry {
42
+ register: (store: StoreDescriptor<any>) => void;
43
+ }
44
+ type ActionCreatorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, infer ActionCreators, any> ? PromisifiedActionCreators<ActionCreators> : never;
45
+ type PromisifiedActionCreators<ActionCreators extends MapOf<ActionCreator>> = {
46
+ [Action in keyof ActionCreators]: PromisifyActionCreator<ActionCreators[Action]>;
56
47
  };
48
+ type PromisifyActionCreator<Action extends ActionCreator> = (...args: Parameters<Action>) => Promise<ReturnType<Action> extends (..._args: any[]) => any ? ThunkReturnType<Action> : ReturnType<Action>>;
49
+ type ThunkReturnType<Action extends ActionCreator> = Awaited<ReturnType<ReturnType<Action>>>;
50
+ type SelectorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, any, infer Selectors> ? {
51
+ [name in keyof Selectors]: Function;
52
+ } : never;
53
+
57
54
  interface FormField {
58
55
  name: string;
59
56
  type: string;
@@ -111,7 +108,7 @@ interface State {
111
108
  reloadMFAPreferences: number;
112
109
  }
113
110
  type SubscriptionType = "PROFESSIONAL" | "AGENCY";
114
- type Store = StoreDescriptor<ReduxStoreConfig<State, typeof actions, typeof selectors>>;
111
+ type Store = StoreDescriptor$1;
115
112
  declare const observeStore: (observableStore: Store, selector: (state: State) => ResourcesConfig | Account | boolean | number | string | null | undefined, onChange: (nextValue: ResourcesConfig | Account | boolean | number | string | null | undefined, previousValue: ResourcesConfig | Account | boolean | number | string | null | undefined) => void) => any;
116
113
 
117
114
  interface Account {
@@ -214,6 +211,6 @@ interface Gatey {
214
211
  uploadUrl: string;
215
212
  }
216
213
 
217
- declare const store: Promise<Store>;
214
+ declare const store: Promise<StoreDescriptor<any>>;
218
215
 
219
216
  export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, Gatey, type RoleMapping, type Settings, type SiteSettings, type State, type Store, type SubscriptionType, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getUserAttributes, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, store };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{get as re,post as ie,put as se,del as ae,head as ce,patch as ue}from"aws-amplify/api";import{dispatch as S}from"@wordpress/data";import{Amplify as U}from"aws-amplify";import{fetchAuthSession as E,fetchUserAttributes as Z,fetchMFAPreference as ee,getCurrentUser as te,signOut as x,updateMFAPreference as ne}from"aws-amplify/auth";import{fetchAuthSession as K}from"aws-amplify/auth";import{I18n as C}from"aws-amplify/utils";import{createReduxStore as V,register as z,select as B,dispatch as P,subscribe as j}from"@wordpress/data";import{getConfig as X}from"@smart-cloud/wpsuite-core";var g="gatey_account",W="gatey";var d;typeof WpSuite<"u"?d=WpSuite.siteSettings:d={};var l=e=>{e?.username?window.localStorage.setItem(g,JSON.stringify(e)):window.localStorage.removeItem(g)},c=async e=>{let t=JSON.parse(window.localStorage.getItem(g)??"{}"),n=!1;if(t?.username)try{let o=await K();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await b(!1),t?.username&&(l(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(l({}),Gatey.cognito.store.then(async o=>{await y(e?.signOutHook),await P(o).clearAccount()})),t},J=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=Gatey.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(Gatey.settings.secondaryUserPoolDomains.toLowerCase())&&Gatey.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?Gatey.settings?.userPoolConfigurations.secondary:Gatey.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...n.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...n.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+Gatey?.settings?.signInPage],redirectSignOut:[window.location.origin+Gatey?.settings?.signInPage]}}}},API:{...n.API,REST:{...n.API?.REST,admin:{endpoint:Gatey.restUrl}}}},r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;r?.apis?.forEach(s=>{let a=o.API?.REST;a&&(a[s.name]={endpoint:s.endpoint,region:s.region})}),f(o,{API:{REST:{headers:async s=>{let a=r?.apis?.find(i=>i.name===s.apiName);if(s.apiName==="admin"||a?.authorization==="ID_TOKEN"||a?.authorization==="ACCESS_TOKEN")try{let i=await u();if(i?.tokens?.idToken&&i?.tokens?.accessToken)return{Authorization:`Bearer ${s.apiName==="admin"||a?.authorization==="ID_TOKEN"?i.tokens.idToken.toString():i.tokens.accessToken.toString()}`}}catch(i){console.error(i),Gatey.cognito.store.then(v=>{P(v).clearAccount()})}return{}}}}})},Y=async()=>{let e=null;return Gatey.settings.customTranslationsUrl&&(e=await fetch(Gatey.settings.customTranslationsUrl+(Gatey.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+d.lastUpdate).then(t=>t.ok?t.text():null).then(t=>t?JSON.parse(t):null).catch(()=>null)),e??null},q=async()=>{let e=await X("gatey");J(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,o=await c(n),r=await Y();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},H={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?C.setLanguage(""):C.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},$={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},Q={},T=async()=>{let e=await q(),t=V("wpsuite/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return l(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return l({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:H,selectors:$,resolvers:Q});return z(t),t},p=(e,t,n)=>{let o;function r(){let s=B(e).getState(),a=t(s);if(a!==o){let i=o;o=a,n(o,i)}}let h=j(r,e);return r(),h};var m=()=>U.getConfig(),f=(e,t)=>{U.configure(e,t)},u=e=>E(e),I=()=>Z(),R=()=>ee(),b=async(e=!0)=>{let t=e?await c():{};if(t?.username)return t;try{if((await E()).tokens)return{username:(await te()).username,userAttributes:await I(),mfaPreferences:await R()}}catch(n){console.error(n);try{await x()}catch{}}return{}},O=async()=>{await ne({totp:"DISABLED"})},w=()=>c().then(e=>e?.username),G=()=>c().then(e=>e?.userAttributes),N=()=>c().then(e=>e?.mfaPreferences),F=()=>c().then(e=>!!e?.username),_=e=>A().then(t=>t?.includes(e)||!1),A=()=>u().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),L=async()=>u().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),M=async()=>u().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),k=()=>u().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),oe=async e=>{let t;return Gatey.settings.integrateWpLogin&&Gatey.restUrl?.startsWith("http")&&(t=await Gatey.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),Gatey.settings.redirectSignIn??t},y=async e=>{let t;Gatey.settings.integrateWpLogin&&(t=await Gatey.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await x()}catch{}return Gatey.settings.redirectSignOut??t};var ge=()=>{Gatey.cognito.store.then(e=>{p(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),S(e).clearAccount()})},le=e=>{Gatey.cognito.store.then(t=>{S(t).setLanguage(e??"en")})},pe=e=>{Gatey.cognito.store.then(t=>{S(t).setDirection(e??"auto")})};var D=!!Gatey.cognito?.store,de=Gatey.cognito?.store??T();D||(Gatey.cognito={store:de,observeStore:p,setLanguage:le,setDirection:pe,getAmplifyConfig:m,isAuthenticated:F,isInGroup:_,getUsername:w,getUserAttributes:G,getMfaPreferences:N,clearMfaPreferences:O,getGroups:A,getRoles:L,getPreferredRole:M,getScopes:k,signOut:ge,get:re,post:ie,put:se,del:ae,head:ce,patch:ue});D=!0;export{W as TEXT_DOMAIN,O as clearMfaPreferences,f as configureAmplify,m as getAmplifyConfig,A as getGroups,N as getMfaPreferences,M as getPreferredRole,L as getRoles,k as getScopes,G as getUserAttributes,F as isAuthenticated,_ as isInGroup,u as loadAuthSession,R as loadMFAPreferences,I as loadUserAttributes,oe as login,y as logout,p as observeStore,de as store};
1
+ import{get as ie,post as se,put as ae,del as ce,head as ue,patch as ge}from"aws-amplify/api";import{Amplify as b}from"aws-amplify";import{fetchAuthSession as U,fetchUserAttributes as ee,fetchMFAPreference as te,getCurrentUser as ne,signOut as x,updateMFAPreference as oe}from"aws-amplify/auth";import{fetchAuthSession as W}from"aws-amplify/auth";import{I18n as C}from"aws-amplify/utils";import{createReduxStore as K,dispatch as V,register as z,select as B,subscribe as j}from"@wordpress/data";import{getConfig as X}from"@smart-cloud/wpsuite-core";var l="gatey_account",v="gatey";var f;typeof WpSuite<"u"?f=WpSuite.siteSettings:f={};var p=e=>{e?.username?window.localStorage.setItem(l,JSON.stringify(e)):window.localStorage.removeItem(l)},c=async e=>{let t=JSON.parse(window.localStorage.getItem(l)??"{}"),n=!1;if(t?.username)try{let o=await W();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await T(!1),t?.username&&(p(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(p({}),Gatey.cognito.store.then(async o=>{await m(e?.signOutHook),await g(o).clearAccount()})),t},J=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=Gatey.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(Gatey.settings.secondaryUserPoolDomains.toLowerCase())&&Gatey.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?Gatey.settings?.userPoolConfigurations.secondary:Gatey.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...n.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...n.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+Gatey?.settings?.signInPage],redirectSignOut:[window.location.origin+Gatey?.settings?.signInPage]}}}},API:{...n.API,REST:{...n.API?.REST,admin:{endpoint:Gatey.restUrl}}}},r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;r?.apis?.forEach(s=>{let a=o.API?.REST;a&&(a[s.name]={endpoint:s.endpoint,region:s.region})}),y(o,{API:{REST:{headers:async s=>{let a=r?.apis?.find(i=>i.name===s.apiName);if(s.apiName==="admin"||a?.authorization==="ID_TOKEN"||a?.authorization==="ACCESS_TOKEN")try{let i=await u();if(i?.tokens?.idToken&&i?.tokens?.accessToken)return{Authorization:`Bearer ${s.apiName==="admin"||a?.authorization==="ID_TOKEN"?i.tokens.idToken.toString():i.tokens.accessToken.toString()}`}}catch(i){console.error(i),Gatey.cognito.store.then(k=>{g(k).clearAccount()})}return{}}}}})},Y=async()=>{let e=null;return Gatey.settings.customTranslationsUrl&&(e=await fetch(Gatey.settings.customTranslationsUrl+(Gatey.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+f.lastUpdate).then(t=>t.ok?t.text():null).then(t=>t?JSON.parse(t):null).catch(()=>null)),e??null},q=async()=>{let e=await X("gatey");J(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,o=await c(n),r=await Y();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},H={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?C.setLanguage(""):C.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},$={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},Q={},g=e=>V(e),Z=e=>B(e),P=async()=>{let e=await q(),t=K("wpsuite/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return p(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return p({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:H,selectors:$,resolvers:Q});return z(t),t},d=(e,t,n)=>{let o;function r(){let s=Z(e).getState(),a=t(s);if(a!==o){let i=o;o=a,n(o,i)}}let h=j(r,e);return r(),h};var A=()=>b.getConfig(),y=(e,t)=>{b.configure(e,t)},u=e=>U(e),E=()=>ee(),I=()=>te(),T=async(e=!0)=>{let t=e?await c():{};if(t?.username)return t;try{if((await U()).tokens)return{username:(await ne()).username,userAttributes:await E(),mfaPreferences:await I()}}catch(n){console.error(n);try{await x()}catch{}}return{}},O=async()=>{await oe({totp:"DISABLED"})},R=()=>c().then(e=>e?.username),w=()=>c().then(e=>e?.userAttributes),N=()=>c().then(e=>e?.mfaPreferences),G=()=>c().then(e=>!!e?.username),F=e=>S().then(t=>t?.includes(e)||!1),S=()=>u().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),_=async()=>u().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),L=async()=>u().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),M=()=>u().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),re=async e=>{let t;return Gatey.settings.integrateWpLogin&&Gatey.restUrl?.startsWith("http")&&(t=await Gatey.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),Gatey.settings.redirectSignIn??t},m=async e=>{let t;Gatey.settings.integrateWpLogin&&(t=await Gatey.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await x()}catch{}return Gatey.settings.redirectSignOut??t};var le=()=>{Gatey.cognito.store.then(e=>{d(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),g(e).clearAccount()})},pe=e=>{Gatey.cognito.store.then(t=>{g(t).setLanguage(e??"en")})},de=e=>{Gatey.cognito.store.then(t=>{g(t).setDirection(e??"auto")})};var D=!!Gatey.cognito?.store,fe=Gatey.cognito?.store??P();D||(Gatey.cognito={store:fe,observeStore:d,setLanguage:pe,setDirection:de,getAmplifyConfig:A,isAuthenticated:G,isInGroup:F,getUsername:R,getUserAttributes:w,getMfaPreferences:N,clearMfaPreferences:O,getGroups:S,getRoles:_,getPreferredRole:L,getScopes:M,signOut:le,get:ie,post:se,put:ae,del:ce,head:ue,patch:ge});D=!0;export{v as TEXT_DOMAIN,O as clearMfaPreferences,y as configureAmplify,A as getAmplifyConfig,S as getGroups,N as getMfaPreferences,L as getPreferredRole,_ as getRoles,M as getScopes,w as getUserAttributes,G as isAuthenticated,F as isInGroup,u as loadAuthSession,I as loadMFAPreferences,E as loadUserAttributes,re as login,m as logout,d as observeStore,fe as store};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/gatey-core",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Login & SSO with Amazon Cognito",
5
5
  "author": "Smart Cloud Solutions Inc.",
6
6
  "license": "MIT",
@@ -22,19 +22,23 @@
22
22
  "scope": "@smart-cloud/gatey-core"
23
23
  },
24
24
  "dependencies": {
25
- "@aws-amplify/ui-react": "^6.13.0",
26
- "@smart-cloud/wpsuite-core": "^1.0.6",
27
- "@wordpress/data": "^10.32.0",
28
- "aws-amplify": "^6.15.7"
25
+ "@aws-amplify/ui-react": "^6.13.1",
26
+ "@smart-cloud/wpsuite-core": "^1.0.7"
27
+ },
28
+ "peerDependencies": {
29
+ "aws-amplify": "^6.15.8",
30
+ "@wordpress/data": "^10.36.0"
29
31
  },
30
32
  "devDependencies": {
31
- "@types/node": "^24.8.1",
32
- "@typescript-eslint/eslint-plugin": "^8.46.1",
33
- "@typescript-eslint/parser": "^8.46.1",
34
- "eslint": "^9.37.0",
33
+ "@types/node": "^24.10.1",
34
+ "@typescript-eslint/eslint-plugin": "^8.48.1",
35
+ "@typescript-eslint/parser": "^8.48.1",
36
+ "@wordpress/data": "^10.36.0",
37
+ "aws-amplify": "^6.15.8",
38
+ "eslint": "^9.39.1",
35
39
  "ts-node": "^10.9.2",
36
- "tsup": "^8.5.0",
40
+ "tsup": "^8.5.1",
37
41
  "typescript": "^5.9.3",
38
- "typescript-eslint": "^8.46.1"
42
+ "typescript-eslint": "^8.48.1"
39
43
  }
40
44
  }