@saasquatch/microsite-router
Advanced tools
Comparing version 1.0.0-6 to 1.0.0-7
@@ -1,1 +0,1 @@ | ||
function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var t="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,r,i=0,a=0,s="";r=n.charAt(a++);~r&&(o=i%4?64*o+r:r,i++%4)?s+=String.fromCharCode(255&o>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function n(e){var n=e.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(t(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(n)}catch(e){return t(n)}}function o(e){this.message=e}function r(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}o.prototype=new Error,o.prototype.name="InvalidTokenError";var a=function(){function e(e){var t=this,n=this;this._status="Initial",this.onChange=function(e){n.options.onChange&&n.options.onChange(e)},this.onConnect=function(e){try{return t.status="Connected",t.options.onChange&&t.options.onChange(e),Promise.resolve(new Promise((function(e){t.resolvePromise=e})))}catch(e){return Promise.reject(e)}},this.onDisconnect=function(){n.status="Connecting",n.start()},this.options=e}var t=e.prototype;return t.start=function(){var e=this,t=0;this.status="Connecting";var n=function(){return e.status},o=c(this.options.attempts)||10,r=function(){if("Connected"!==n()){var r=new CustomEvent(e.options.contextName,{bubbles:!0,cancelable:!0,composed:!0,detail:{onConnect:e.onConnect,onChange:e.onChange,onDisconnect:e.onDisconnect}});c(e.options.element).dispatchEvent(r),"Connected"!==n()?++t>=o&&(e._interval&&clearInterval(e._interval),e.status="Timeout"):"Connected"===n()&&e._interval&&clearInterval(e._interval)}};return(c(this.options.pollingMs)||100)>0&&o>1&&(this._interval=setInterval(r,c(this.options.pollingMs)||100)),r(),this},t.stop=function(){return this._interval&&clearInterval(this._interval),this.resolvePromise&&this.resolvePromise(),this.status="Initial",this},i(e,[{key:"status",set:function(e){this._status=e,this.options.onStatus&&this.options.onStatus(e)},get:function(){return this._status}}]),e}(),s=function(){function e(e){var t=this;this.__listeners=[],this.connectListener=function(e){try{e.stopPropagation(),t.__listeners=[].concat(t.__listeners,[e.detail]);var n=function(n,o){try{var r=Promise.resolve(e.detail.onConnect(t.__current)).then((function(){}))}catch(e){return o(!0,e)}return r&&r.then?r.then(o.bind(null,!1),o.bind(null,!0)):o(!1,r)}(0,(function(n,o){var r,i;if(t.__listeners=(i=(r=t.__listeners).indexOf(e.detail),r.slice(0,i).concat(r.slice(i+1,r.length))),n)throw o;return o}));return Promise.resolve(n&&n.then?n.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},this.options=e,this.__current=c(e.initialState)}var t=e.prototype;return t.start=function(){return c(this.options.element).addEventListener(this.options.contextName,this.connectListener),this},t.stop=function(){return c(this.options.element).removeEventListener(this.options.contextName,this.connectListener),this.__listeners.map((function(e){e.onDisconnect()})),this.__listeners=[],this},i(e,[{key:"context",set:function(e){this.__current=e,this.__listeners.forEach((function(t){return t.onChange(e)}))},get:function(){return c(this.__current)}},{key:"listeners",get:function(){return Object.freeze([].concat(this.__listeners))}}]),e}();function c(e){return"function"==typeof typeof e?e():e}var l=Object.defineProperty,u=Object.getOwnPropertySymbols,d=Object.prototype.hasOwnProperty,h=Object.prototype.propertyIsEnumerable,p=(e,t,n)=>t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))d.call(t,n)&&p(e,n,t[n]);if(u)for(var n of u(t))h.call(t,n)&&p(e,n,t[n]);return e};function f(){var e,t;return window.SquatchAndroid?{type:"SquatchAndroid",android:window.SquatchAndroid,widgetIdent:window.widgetIdent}:window.SquatchPortal?{type:"SquatchPortal",env:window.SquatchPortal}:window.SquatchAdmin?{type:"SquatchAdmin",adminSDK:window.SquatchAdmin}:window.widgetIdent&&"demo"!==(null==(e=window.widgetIdent)?void 0:e.env)?{type:"SquatchJS2",api:null==(t=window.frameElement)?void 0:t.squatchJsApi,widgetIdent:window.widgetIdent}:{type:"None"}}function g(){const e=f();switch(e.type){case"SquatchAndroid":case"SquatchJS2":return e.widgetIdent.tenantAlias;case"SquatchAdmin":case"None":return"demo";case"SquatchPortal":return e.env.tenantAlias}}function m(){var e;const t=f();switch(t.type){case"SquatchAndroid":case"SquatchJS2":return t.widgetIdent.appDomain;case"SquatchPortal":return(null==(e=t.env)?void 0:e.appDomain)||"https://app.referralsaasquatch.com";case"SquatchAdmin":case"None":return"https://app.referralsaasquatch.com"}}var v=localStorage.getItem("debug");function y(e,...t){v&&console.debug(`sq:environment:${e}`,...t)}function S(){var e;let t=window.squatchLocale;return t||(((...e)=>{y("sq:locale",...e)})("Creating locale context provider"),t=new s({element:document.documentElement,initialState:(null==(e=window.widgetIdent)?void 0:e.locale)||navigator.language.replace("-","_"),contextName:"sq:locale"}).start(),window.squatchLocale=t),t}function q(){var e;return null==(e=window.squatchLocale)?void 0:e.context}var b=(...e)=>y("sq:locale",...e);var I=(...e)=>y("sq:locale",...e),_=new a({contextName:"sq:user-identity",element:(()=>{const e="__environment_context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),onChange:async e=>{var t;const n=S(),o=(null==(t=window.widgetIdent)?void 0:t.locale)||navigator.language.replace("-","_");let r;if(e){I("User context changed, refetching locale");const e=await async function(){var e;b("Fetching locale from GraphQL for current user");try{const t=await fetch(`${m()}/api/v1/${g()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${null==(e=$())?void 0:e.jwt}`},body:JSON.stringify({query:"\n query {\n viewer {\n ... on User {\n locale\n }\n }\n }\n"})});if(!t.ok)throw new Error("Failed to fetch locale");const n=await t.json();if(n.errors)throw new Error(JSON.stringify(n.errors,null,2));return n.data.viewer.locale||void 0}catch(e){return void b("Failed to fetch locale for current user",e.message)}}();n.context!==e&&(I(`New value fetched from GraphQL [${e}]`),r=e||o)}else r=o;I(`Setting locale context to [${r}]`),n.context=r}});function C(){let e=window.squatchUserIdentity;return e||(((...e)=>{y("sq:user-identity",...e)})("Creating user context provider"),e=new s({element:document.documentElement,initialState:E(),contextName:"sq:user-identity"}).start(),window.squatchUserIdentity=e,I("Starting user context listener for locale updates"),_.start()),e}function P(e){if(e)try{const t=function(e,t){if("string"!=typeof e)throw new o("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(n(e.split(".")[r]))}catch(e){throw new o("Invalid token specified: "+e.message)}}(e),r=t.exp;let i,a;if(function(e){return e.sub&&/.*:.*@.*:users/.test(e.sub)}(t)){const e=t.sub.match(/(.*):(.*)@(.*):users/);(null==e?void 0:e[1])&&(a=atob(e[1])),(null==e?void 0:e[2])&&(i=atob(e[2]))}else(function(e){return e.user&&e.user.id&&e.user.accountId})(t)&&(a=t.user.accountId,i=t.user.id);if(!i||!a)return;if(r&&Date.now()>=1e3*r)return;return{id:i,accountId:a,jwt:e}}catch(e){return}}function E(){const e=f();switch(e.type){case"SquatchAndroid":case"SquatchJS2":return{id:e.widgetIdent.userId,accountId:e.widgetIdent.accountId,jwt:e.widgetIdent.token};case"SquatchPortal":const t=new URLSearchParams(document.location.search);if(t.has("jwt"))return P(t.get("jwt"));const n=localStorage.getItem("sq:user-identity");if(!n)return;try{const e=JSON.parse(n),t=P(e.jwt);return t?w(w({},e),t):void 0}catch(e){return}case"SquatchAdmin":case"None":return}}function $(){var e;return null==(e=window.squatchUserIdentity)?void 0:e.context}function x(e){const t=window.history[e];return function(...n){const o=t.apply(window.history,n),r=new Event(e);return window.dispatchEvent(r),o}}const k=localStorage.getItem("debug");function N(e,...t){k&&console.debug(`sq:microsite:${e}`,...t)}const L={};let A=[];var O;!function(e){e[e.Render=0]="Render",e[e.Redirect=1]="Redirect",e[e.NotAllowed=2]="NotAllowed"}(O||(O={}));async function j(e=window.location.pathname){var t;const n=await async function(e,t){const n=`${e}${t?`_${t}`:""}`;if(L[n])return N("fetchPage",`avoiding GraphQL call in lieu of cache for [${e}]`),L[n];try{const n=await fetch(`${m()}/api/v1/${g()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operationName:"RenderMicrositePage",query:"\n query RenderMicrositePage($urlPath: String!, $locale: RSLocale) {\n renderMicrositePage(urlPath: $urlPath, locale: $locale) {\n micrositePageConfig {\n urlPath\n values\n allowedUsers\n disallowedUrlPath\n }\n micrositeLayoutConfigs {\n key\n values\n }\n }\n }\n",variables:{urlPath:e,locale:t}})});if(!n.ok)throw new Error("Failed to fetch page");const o=await n.json();if(o.errors)throw new Error(JSON.stringify(o.errors,null,2));const r=o.data,i={page:r.renderMicrositePage.micrositePageConfig,layouts:r.renderMicrositePage.micrositeLayoutConfigs};return L[e]=i,i}catch(e){throw document.body.innerHTML=`\n <div style="padding: 12px;">\n <h3>Sorry, something went wrong</h3>\n <p style="background-color: pink; padding: 12px; font-family: monospace; font-size: 12px;">\n <pre>${e.message}</pre>\n </p>\n </div>\n `,e}}(e,q());N("router",`routing to ${e}"`);const o=n.page.allowedUsers,r=n.page.disallowedUrlPath,i=$(),a=i?(null===(t=i.managedIdentity)||void 0===t?void 0:t.emailVerified)?"VERIFIED":"UNVERIFIED":"PUBLIC";let s=O.Render;a!=o&&(s=r?O.Redirect:"PUBLIC"===o?O.Render:O.NotAllowed);let c=`pathname[${e}] userType[${a}] allowedUsers[${o}]`;switch(s){case O.Render:N("router",`${c} user is allowed, rendering the page`),function(e){const t=[];let n=document.body;A.length>0&&(A[A.length-1].element.innerHTML=""),[...e.layouts].reverse().forEach(((e,o)=>{var r;if((null===(r=A[o])||void 0===r?void 0:r.key)===e.key)N("render",`reusing element for layout [${e.key}]`),n=A[o].element,t.push({key:e.key,element:n});else{A.splice(o).forEach((e=>{N("render",`removing element for layout [${e.key}]`),e.element.remove()}));const r=document.createElement("div");r.style.display="contents",r.id=e.key,r.attachShadow({mode:"open"}),r.shadowRoot.innerHTML=e.values.html,n.appendChild(r),n=r,t.push({key:e.key,element:r}),N("render",`created element for layout [${e.key}]`)}})),n.innerHTML=e.page.values.html,document.title=e.page.values.title,A=t}(n);break;case O.Redirect:N("router",`${c} redirecting to ${r}`),window.history.pushState(void 0,"",r);break;case O.NotAllowed:N("router",`${c} user is not allowed, rendering an error page`),document.body.innerHTML='\n <div style="padding: 12px;">\n <h3>Not allowed.</h3>\n </div>\n'}}const R=(()=>{const e="__context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),U=new a({contextName:"sq:user-identity",element:R,onChange:e=>{N("user-context",`old[${JSON.stringify($())}] new[${JSON.stringify(e)}]`)},onStatus:e=>{N("user-context",e)}}),J=new a({contextName:"sq:locale",element:R,onChange:e=>{e&&q()!==e&&(N("locale-context",`old[${q()}] new[${e}]`),j())},onStatus:e=>{N("locale-context",e)}});window.addEventListener("load",(function(){history.pushState=x("pushState"),history.replaceState=x("replaceState"),window.addEventListener("popstate",(()=>j())),window.addEventListener("pushState",(()=>j())),window.addEventListener("replaceState",(()=>j())),window.history.replaceState(void 0,"",""),C(),S(),U.start(),J.start()})); | ||
function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var t="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,r,i=0,a=0,s="";r=n.charAt(a++);~r&&(o=i%4?64*o+r:r,i++%4)?s+=String.fromCharCode(255&o>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function n(e){var n=e.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(t(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(n)}catch(e){return t(n)}}function o(e){this.message=e}function r(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}o.prototype=new Error,o.prototype.name="InvalidTokenError";var a=function(){function e(e){var t=this,n=this;this._status="Initial",this.onChange=function(e){n.options.onChange&&n.options.onChange(e)},this.onConnect=function(e){try{return t.status="Connected",t.options.onChange&&t.options.onChange(e),Promise.resolve(new Promise((function(e){t.resolvePromise=e})))}catch(e){return Promise.reject(e)}},this.onDisconnect=function(){n.status="Connecting",n.start()},this.options=e}var t=e.prototype;return t.start=function(){var e=this,t=0;this.status="Connecting";var n=function(){return e.status},o=c(this.options.attempts)||10,r=function(){if("Connected"!==n()){var r=new CustomEvent(e.options.contextName,{bubbles:!0,cancelable:!0,composed:!0,detail:{onConnect:e.onConnect,onChange:e.onChange,onDisconnect:e.onDisconnect}});c(e.options.element).dispatchEvent(r),"Connected"!==n()?++t>=o&&(e._interval&&clearInterval(e._interval),e.status="Timeout"):"Connected"===n()&&e._interval&&clearInterval(e._interval)}};return(c(this.options.pollingMs)||100)>0&&o>1&&(this._interval=setInterval(r,c(this.options.pollingMs)||100)),r(),this},t.stop=function(){return this._interval&&clearInterval(this._interval),this.resolvePromise&&this.resolvePromise(),this.status="Initial",this},i(e,[{key:"status",set:function(e){this._status=e,this.options.onStatus&&this.options.onStatus(e)},get:function(){return this._status}}]),e}(),s=function(){function e(e){var t=this;this.__listeners=[],this.connectListener=function(e){try{e.stopPropagation(),t.__listeners=[].concat(t.__listeners,[e.detail]);var n=function(n,o){try{var r=Promise.resolve(e.detail.onConnect(t.__current)).then((function(){}))}catch(e){return o(!0,e)}return r&&r.then?r.then(o.bind(null,!1),o.bind(null,!0)):o(!1,r)}(0,(function(n,o){var r,i;if(t.__listeners=(i=(r=t.__listeners).indexOf(e.detail),r.slice(0,i).concat(r.slice(i+1,r.length))),n)throw o;return o}));return Promise.resolve(n&&n.then?n.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},this.options=e,this.__current=c(e.initialState)}var t=e.prototype;return t.start=function(){return c(this.options.element).addEventListener(this.options.contextName,this.connectListener),this},t.stop=function(){return c(this.options.element).removeEventListener(this.options.contextName,this.connectListener),this.__listeners.map((function(e){e.onDisconnect()})),this.__listeners=[],this},i(e,[{key:"context",set:function(e){this.__current=e,this.__listeners.forEach((function(t){return t.onChange(e)}))},get:function(){return c(this.__current)}},{key:"listeners",get:function(){return Object.freeze([].concat(this.__listeners))}}]),e}();function c(e){return"function"==typeof typeof e?e():e}var l=Object.defineProperty,u=Object.getOwnPropertySymbols,d=Object.prototype.hasOwnProperty,h=Object.prototype.propertyIsEnumerable,p=(e,t,n)=>t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))d.call(t,n)&&p(e,n,t[n]);if(u)for(var n of u(t))h.call(t,n)&&p(e,n,t[n]);return e};function f(){var e,t;return window.SquatchAndroid?{type:"SquatchAndroid",android:window.SquatchAndroid,widgetIdent:window.widgetIdent}:window.SquatchPortal?{type:"SquatchPortal",env:window.SquatchPortal}:window.SquatchAdmin?{type:"SquatchAdmin",adminSDK:window.SquatchAdmin}:window.widgetIdent&&"demo"!==(null==(e=window.widgetIdent)?void 0:e.env)?{type:"SquatchJS2",api:null==(t=window.frameElement)?void 0:t.squatchJsApi,widgetIdent:window.widgetIdent}:{type:"None"}}function g(){const e=f();switch(e.type){case"SquatchAndroid":case"SquatchJS2":return e.widgetIdent.tenantAlias;case"SquatchAdmin":case"None":return"demo";case"SquatchPortal":return e.env.tenantAlias}}function m(){var e;const t=f();switch(t.type){case"SquatchAndroid":case"SquatchJS2":return t.widgetIdent.appDomain;case"SquatchPortal":return(null==(e=t.env)?void 0:e.appDomain)||"https://app.referralsaasquatch.com";case"SquatchAdmin":case"None":return"https://app.referralsaasquatch.com"}}var v=localStorage.getItem("debug");function y(e,...t){v&&console.debug(`sq:environment:${e}`,...t)}function S(){var e;let t=window.squatchLocale;return t||(((...e)=>{y("sq:locale",...e)})("Creating locale context provider"),t=new s({element:document.documentElement,initialState:(null==(e=window.widgetIdent)?void 0:e.locale)||navigator.language.replace("-","_"),contextName:"sq:locale"}).start(),window.squatchLocale=t),t}function q(){var e;return null==(e=window.squatchLocale)?void 0:e.context}var b=(...e)=>y("sq:locale",...e);var I=(...e)=>y("sq:locale",...e),_=new a({contextName:"sq:user-identity",element:(()=>{const e="__environment_context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),onChange:async e=>{var t;const n=S(),o=(null==(t=window.widgetIdent)?void 0:t.locale)||navigator.language.replace("-","_");let r;if(e){I("User context changed, refetching locale");const e=await async function(){var e;b("Fetching locale from GraphQL for current user");try{const t=await fetch(`${m()}/api/v1/${g()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${null==(e=$())?void 0:e.jwt}`},body:JSON.stringify({query:"\n query {\n viewer {\n ... on User {\n locale\n }\n }\n }\n"})});if(!t.ok)throw new Error("Failed to fetch locale");const n=await t.json();if(n.errors)throw new Error(JSON.stringify(n.errors,null,2));return n.data.viewer.locale||void 0}catch(e){return void b("Failed to fetch locale for current user",e.message)}}();n.context!==e&&(I(`New value fetched from GraphQL [${e}]`),r=e||o)}else r=o;I(`Setting locale context to [${r}]`),n.context=r}});function C(){let e=window.squatchUserIdentity;return e||(((...e)=>{y("sq:user-identity",...e)})("Creating user context provider"),e=new s({element:document.documentElement,initialState:E(),contextName:"sq:user-identity"}).start(),window.squatchUserIdentity=e,I("Starting user context listener for locale updates"),_.start()),e}function P(e){if(e)try{const t=function(e,t){if("string"!=typeof e)throw new o("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(n(e.split(".")[r]))}catch(e){throw new o("Invalid token specified: "+e.message)}}(e),r=t.exp;let i,a;if(function(e){return e.sub&&/.*:.*@.*:users/.test(e.sub)}(t)){const e=t.sub.match(/(.*):(.*)@(.*):users/);(null==e?void 0:e[1])&&(a=atob(e[1])),(null==e?void 0:e[2])&&(i=atob(e[2]))}else(function(e){return e.user&&e.user.id&&e.user.accountId})(t)&&(a=t.user.accountId,i=t.user.id);if(!i||!a)return;if(r&&Date.now()>=1e3*r)return;return{id:i,accountId:a,jwt:e}}catch(e){return}}function E(){const e=f();switch(e.type){case"SquatchAndroid":case"SquatchJS2":return{id:e.widgetIdent.userId,accountId:e.widgetIdent.accountId,jwt:e.widgetIdent.token};case"SquatchPortal":const t=new URLSearchParams(document.location.search);if(t.has("jwt"))return P(t.get("jwt"));const n=localStorage.getItem("sq:user-identity");if(!n)return;try{const e=JSON.parse(n),t=P(e.jwt);return t?w(w({},e),t):void 0}catch(e){return}case"SquatchAdmin":case"None":return}}function $(){var e;return null==(e=window.squatchUserIdentity)?void 0:e.context}function x(e){const t=window.history[e];return function(...n){const o=t.apply(window.history,n),r=new Event(e);return window.dispatchEvent(r),o}}const k=localStorage.getItem("debug");function N(e,...t){k&&console.debug(`sq:microsite:${e}`,...t)}const L={};let A=[];var O;!function(e){e[e.Render=0]="Render",e[e.Redirect=1]="Redirect",e[e.NotAllowed=2]="NotAllowed"}(O||(O={}));async function j(e=window.location.pathname){var t;const n=await async function(e,t){const n=`${e}${t?`_${t}`:""}`;if(L[n])return N("fetchPage",`avoiding GraphQL call in lieu of cache for [${e}]`),L[n];try{const n=await fetch(`${m()}/api/v1/${g()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operationName:"RenderMicrositePage",query:"\n query RenderMicrositePage($urlPath: String!, $locale: RSLocale) {\n renderMicrositePage(urlPath: $urlPath, locale: $locale) {\n micrositePageConfig {\n urlPath\n values\n allowedUsers\n disallowedUrlPath\n }\n micrositeLayoutConfigs {\n key\n values\n }\n }\n }\n",variables:{urlPath:e,locale:t}})});if(!n.ok)throw new Error("Failed to fetch page");const o=await n.json();if(o.errors)throw new Error(JSON.stringify(o.errors,null,2));const r=o.data,i={page:r.renderMicrositePage.micrositePageConfig,layouts:r.renderMicrositePage.micrositeLayoutConfigs};return L[e]=i,i}catch(e){throw document.body.innerHTML=`\n <div style="padding: 12px;">\n <h3>Sorry, something went wrong</h3>\n <p style="background-color: pink; padding: 12px; font-family: monospace; font-size: 12px;">\n <pre>${e.message}</pre>\n </p>\n </div>\n `,e}}(e,q()),o=n.page.allowedUsers,r=n.page.disallowedUrlPath,i=$(),a=i?(null===(t=i.managedIdentity)||void 0===t?void 0:t.emailVerified)?"VERIFIED":"UNVERIFIED":"PUBLIC";let s=O.Render;a!=o&&(s=r?O.Redirect:"PUBLIC"===o?O.Render:O.NotAllowed);let c=`pathname[${e}] userType[${a}] allowedUsers[${o}]`;switch(s){case O.Render:N("router",`${c} user is allowed, rendering the page`),function(e){const t=[];let n=document.body;A.length>0&&(A[A.length-1].element.innerHTML=""),[...e.layouts].reverse().forEach(((e,o)=>{var r;if((null===(r=A[o])||void 0===r?void 0:r.key)===e.key)N("render",`reusing element for layout [${e.key}]`),n=A[o].element,t.push({key:e.key,element:n});else{A.splice(o).forEach((e=>{N("render",`removing element for layout [${e.key}]`),e.element.remove()}));const r=document.createElement("div");r.style.display="contents",r.id=e.key,r.attachShadow({mode:"open"}),r.shadowRoot.innerHTML=e.values.html,n.appendChild(r),n=r,t.push({key:e.key,element:r}),N("render",`created element for layout [${e.key}]`)}})),n.innerHTML=e.page.values.html,document.title=e.page.values.title,A=t}(n);break;case O.Redirect:N("router",`${c} redirecting to ${r}`),window.history.pushState(void 0,"",r);break;case O.NotAllowed:N("router",`${c} user is not allowed, rendering an error page`),document.body.innerHTML='\n <div style="padding: 12px;">\n <h3>Not allowed.</h3>\n </div>\n'}}const R=(()=>{const e="__context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),U=new a({contextName:"sq:user-identity",element:R,onChange:e=>{N("user-context",`old[${JSON.stringify($())}] new[${JSON.stringify(e)}]`)},onStatus:e=>{N("user-context",e)}}),J=new a({contextName:"sq:locale",element:R,onChange:e=>{e&&q()!==e&&(N("locale-context",`old[${q()}] new[${e}]`),j())},onStatus:e=>{N("locale-context",e)}});window.addEventListener("load",(function(){history.pushState=x("pushState"),history.replaceState=x("replaceState"),window.addEventListener("popstate",(()=>j())),window.addEventListener("pushState",(()=>j())),window.addEventListener("replaceState",(()=>j())),window.history.replaceState(void 0,"",""),C(),S(),U.start(),J.start()})); |
{ | ||
"name": "@saasquatch/microsite-router", | ||
"version": "1.0.0-6", | ||
"version": "1.0.0-7", | ||
"description": "SaaSquatch microsite client-side router and hierarchical layout renderer.", | ||
@@ -5,0 +5,0 @@ "main": "dist/bundle.js", |
13526
46