@framerauth/sdk 2.0.7 → 2.0.9

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.
@@ -1 +1 @@
1
- "use strict";(()=>{var Ee=Object.defineProperty,Te=Object.defineProperties,Le=Object.getOwnPropertyDescriptors,J=Object.getOwnPropertySymbols,Ae=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable,K=(t,e,r)=>e in t?Ee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,L=(t,e)=>{for(var r in e||(e={}))Ae.call(e,r)&&K(t,r,e[r]);if(J)for(var r of J(e))Ue.call(e,r)&&K(t,r,e[r]);return t},A=(t,e)=>Te(t,Le(e)),Oe=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},_e=async(t,e)=>{var r,o,s,n,a,y;let c=e||{},i={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:c,hooks:i};for(let d of e?.plugins||[]){if(d.init){let b=await((r=d.init)==null?void 0:r.call(d,t.toString(),e));c=b.options||c,t=b.url}i.onRequest.push((o=d.hooks)==null?void 0:o.onRequest),i.onResponse.push((s=d.hooks)==null?void 0:s.onResponse),i.onSuccess.push((n=d.hooks)==null?void 0:n.onSuccess),i.onError.push((a=d.hooks)==null?void 0:a.onError),i.onRetry.push((y=d.hooks)==null?void 0:y.onRetry)}return{url:t,options:c,hooks:i}},V=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},xe=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function De(t){if(typeof t=="number")return new V({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new V(t);case"exponential":return new xe(t);default:throw new Error("Invalid retry strategy")}}var Be=async t=>{let e={},r=async o=>typeof o=="function"?await o():o;if(t?.auth){if(t.auth.type==="Bearer"){let o=await r(t.auth.token);if(!o)return e;e.authorization=`Bearer ${o}`}else if(t.auth.type==="Basic"){let o=r(t.auth.username),s=r(t.auth.password);if(!o||!s)return e;e.authorization=`Basic ${btoa(`${o}:${s}`)}`}else if(t.auth.type==="Custom"){let o=r(t.auth.value);if(!o)return e;e.authorization=`${r(t.auth.prefix)} ${o}`}}return e},Ce=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ne(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let o=e.split(";").shift()||"";return Ce.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function Fe(t){try{return JSON.parse(t),!0}catch{return!1}}function Y(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function G(t){try{return JSON.parse(t)}catch{return t}}function Q(t){return typeof t=="function"}function je(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&Q(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Q(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function $e(t){let e=new Headers(t?.headers),r=await Be(t);for(let[o,s]of Object.entries(r||{}))e.set(o,s);if(!e.has("content-type")){let o=Ie(t?.body);o&&e.set("content-type",o)}return e}function Ie(t){return Y(t)?"application/json":null}function Me(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Y(t.body)&&!e.has("content-type")){for(let[r,o]of Object.entries(t?.body))o instanceof Date&&(t.body[r]=o.toISOString());return JSON.stringify(t.body)}return t.body}function We(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let o=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return Z.includes(o)?o.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function ze(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var He=class X extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,X.prototype)}};async function qe(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new He(r.issues);return r.value}var Z=["get","post","put","patch","delete"];function Je(t,e){let{baseURL:r,params:o,query:s}=e||{query:{},params:{},baseURL:""},n=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let b=t.toString().split("@")[1].split("/")[0];Z.includes(b)&&(t=t.replace(`@${b}/`,"/"))}n.endsWith("/")||(n+="/");let[a,y]=t.replace(n,"").split("?"),c=new URLSearchParams(y);for(let[b,h]of Object.entries(s||{}))h!=null&&c.set(b,String(h));if(o)if(Array.isArray(o)){let b=a.split("/").filter(h=>h.startsWith(":"));for(let[h,I]of b.entries()){let x=o[h];a=a.replace(I,x)}}else for(let[b,h]of Object.entries(o))a=a.replace(`:${b}`,String(h));a=a.split("/").map(encodeURIComponent).join("/"),a.startsWith("/")&&(a=a.slice(1));let i=c.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",n.startsWith("http")?new URL(`${a}${i}`,n):`${n}${a}${i}`}var u=async(t,e)=>{var r,o,s,n,a,y,c,i;let{hooks:d,url:b,options:h}=await _e(t,e),I=je(h),x=new AbortController,ye=(r=h.signal)!=null?r:x.signal,ge=Je(b,h),be=Me(h),ve=await $e(h),Se=We(b,h),f=A(L({},h),{url:ge,headers:ve,body:be,method:Se,signal:ye});for(let v of d.onRequest)if(v){let g=await v(f);g instanceof Object&&(f=g)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((o=e?.body)==null?void 0:o.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:we}=ze(h,x),l=await I(f.url,f);we();let H={response:l,request:f};for(let v of d.onResponse)if(v){let g=await v(A(L({},H),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?l.clone():l}));g instanceof Response?l=g:g instanceof Object&&(l=g.response)}if(l.ok){if(!(f.method!=="HEAD"))return{data:"",error:null};let g=Ne(l),k={data:"",response:l,request:f};if(g==="json"||g==="text"){let E=await l.text(),ke=await((n=f.jsonParser)!=null?n:G)(E);k.data=ke}else k.data=await l[g]();f?.output&&f.output&&!f.disableValidation&&(k.data=await qe(f.output,k.data));for(let E of d.onSuccess)E&&await E(A(L({},k),{response:(a=e?.hookOptions)!=null&&a.cloneResponse?l.clone():l}));return e?.throw?k.data:{data:k.data,error:null}}let Re=(y=e?.jsonParser)!=null?y:G,D=await l.text(),q=Fe(D),M=q?await Re(D):null,Pe={response:l,responseText:D,request:f,error:A(L({},M),{status:l.status,statusText:l.statusText})};for(let v of d.onError)v&&await v(A(L({},Pe),{response:(c=e?.hookOptions)!=null&&c.cloneResponse?l.clone():l}));if(e?.retry){let v=De(e.retry),g=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(g,l)){for(let E of d.onRetry)E&&await E(H);let k=v.getDelay(g);return await new Promise(E=>setTimeout(E,k)),await u(t,A(L({},e),{retryAttempt:g+1}))}}if(e?.throw)throw new Oe(l.status,l.statusText,q?M:D);return{data:null,error:A(L({},M),{status:l.status,statusText:l.statusText})}};var Ke="https://core.framerauth.com/v2",B=class{baseURL=null;data;state;api;auth;constructor(e){this.baseURL=null,this.data=e.data,this.state=e.state,this.api={fetchTags:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");return await u(`${this.baseURL}/profile/tags`,{credentials:"include"})},fetchBookmarks:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await u(`${this.baseURL}/profile/bookmarks`,{credentials:"include"});if(!r.data)return r;let o=new Set(r.data),s={};for(let n of o)s[n]=!0;return{data:s,error:null}},fetchProject:async()=>await u(`${Ke}/public/project/config`)},this.auth={getSession:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await u(`${this.baseURL}/get-session`,{method:"GET",credentials:"include",query:{disableCookieCache:!0}});return r.data&&(this.data.user.set(r.data.user),this.data.session.set(r.data.session)),r},signUp:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-up/email`,{method:"POST",credentials:"include",body:r});return o.error||(this.data.user.set(o.data.user),this.auth.getSession(),this.api.fetchTags().then(s=>{this.data.tags.set(s.data??[])}),this.api.fetchBookmarks().then(s=>{this.data.bookmarks.set(s.data??{})})),o},signIn:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-in/email`,{method:"POST",credentials:"include",body:r});return o.error||(this.data.user.set(o.data.user),this.auth.getSession(),this.api.fetchTags().then(s=>{this.data.tags.set(s.data??[])}),this.api.fetchBookmarks().then(s=>{this.data.bookmarks.set(s.data??{})})),o},signInSocial:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-in/social`,{method:"POST",credentials:"include",body:r});return o.data?.url&&(window.location.href=o.data.url),o},signOut:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-out`,{method:"POST",credentials:"include",body:{}});return this.data.user.set(null),this.data.session.set(null),this.data.tags.set([]),this.data.bookmarks.set({}),r?.redirectTo&&(window.location.href=r.redirectTo),o},sendOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/email-otp/send-verification-otp`;return await u(o,{body:r,credentials:"include",method:"POST"})},signInOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/sign-in/email-otp`,s=await u(o,{body:r,credentials:"include",method:"POST"});return s.error||(this.data.user.set(s.data.user),this.auth.getSession(),this.api.fetchTags().then(n=>{this.data.tags.set(n.data??[])}),this.api.fetchBookmarks().then(n=>{this.data.bookmarks.set(n.data??{})})),s},updateProfile:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile`;return await u(o,{body:r,credentials:"include",method:"PATCH"})},updateProfilePicture:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/avatar`;return await u(o,{method:"POST",body:r,credentials:"include"})},createBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks`;return await u(o,{body:r,credentials:"include",method:"POST"})},deleteBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks/${r.bookmark_type}/${r.id}`;return await u(o,{credentials:"include",method:"DELETE"})},sendForgotPasswordEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/forget-password`;return await u(o,{body:r,credentials:"include",method:"POST"})},resetPassword:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/reset-password`;return await u(o,{body:r,credentials:"include",method:"POST"})},storeCheckout:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/store/checkout/session`;return await u(o,{body:r,credentials:"include",method:"POST"})}}}updateBaseURL(e){this.baseURL=e}};var S=[],T=0,C=4,Ve=0,p=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(o){return r.lc=e.push(o),()=>{for(let n=T+C;n<S.length;)S[n]===o?S.splice(n,C):n+=C;let s=e.indexOf(o);~s&&(e.splice(s,1),--r.lc||r.off())}},notify(o,s){Ve++;let n=!S.length;for(let a of e)S.push(a,r.value,o,s);if(n){for(T=0;T<S.length;T+=C)S[T](S[T+1],S[T+2],S[T+3]);S.length=0}},off(){},set(o){let s=r.value;s!==o&&(r.value=o,r.notify(s))},subscribe(o){let s=r.listen(o);return o(r.value),s},value:t};return r};var Ge=5,N=6,F=10,Qe=(t,e,r,o)=>(t.events=t.events||{},t.events[r+F]||(t.events[r+F]=o(s=>{t.events[r].reduceRight((n,a)=>(a(n),n),{shared:{},...s})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let s=t.events[r],n=s.indexOf(e);s.splice(n,1),s.length||(delete t.events[r],t.events[r+F](),delete t.events[r+F])});var ee=1e3,W=(t,e)=>Qe(t,o=>{let s=e(o);s&&t.events[N].push(s)},Ge,o=>{let s=t.listen;t.listen=(...a)=>(!t.lc&&!t.active&&(t.active=!0,o()),s(...a));let n=t.off;return t.events[N]=[],t.off=()=>{n(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let a of t.events[N])a();t.events[N]=[]}},ee)},()=>{t.listen=s,t.off=n}});var j=(t={})=>{let e=p(t);return e.setKey=function(r,o){let s=e.value;typeof o>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(s,r)):e.value[r]!==o&&(e.value={...e.value,[r]:o},e.notify(s,r))},e};var te=t=>t,U={},z={addEventListener(){},removeEventListener(){}};function Ye(){try{return typeof localStorage<"u"}catch{return!1}}Ye()&&(U=localStorage);var Xe={addEventListener(t,e,r){window.addEventListener("storage",e),window.addEventListener("pageshow",r)},removeEventListener(t,e,r){window.removeEventListener("storage",e),window.removeEventListener("pageshow",r)}};typeof window<"u"&&(z=Xe);function w(t,e=void 0,r={}){let o=r.encode||te,s=r.decode||te,n=p(e),a=n.set;n.set=i=>{let d=o(i);typeof d>"u"?delete U[t]:U[t]=d,a(i)};function y(i){i.key===t?i.newValue===null?a(e):a(s(i.newValue)):U[t]||a(e)}function c(){n.set(U[t]?s(U[t]):e)}return W(n,()=>{if(c(),r.listen!==!1)return z.addEventListener(t,y,c),()=>{z.removeEventListener(t,y,c)}}),n}var Ze="framerauth_v2_",re=new TextEncoder,et=new TextDecoder;function oe(){let t=typeof window<"u"?window.location.hostname:"1f8cXd6c7b4a3vL4z5746oUgQ28190adbef";return re.encode(Ze+t)}function tt(t){let e=oe(),r=re.encode(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s++)o[s]=r[s]^e[s%e.length];return o}function rt(t){let e=tt(t),r=Array.from(e,o=>String.fromCharCode(o)).join("");return btoa(r)}function ot(t){let e=oe(),r=atob(t),o=Uint8Array.from(r,n=>n.charCodeAt(0)),s=new Uint8Array(o.length);for(let n=0;n<o.length;n++)s[n]=o[n]^e[n%e.length];return et.decode(s)}function R({obfuscate:t}){return e=>{let r=JSON.stringify(e);return t&&(r=rt(r)),r}}function P({deobfuscate:t}){return e=>{try{return e?(t&&(e=ot(e)),JSON.parse(e)):{}}catch{return{}}}}var se=w("fa-project",null,{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0})}),ne=p(!1);var ae=w("fa-tags",[],{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0})}),ie=p(!1);var le=w("fa-user",null,{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0})}),ce=p(!1);var ue=w("fa-session",null,{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0})}),de=p(!1);var fe=p(!0);function O(){document.body.style.visibility="hidden"}function _(){document.body.style.visibility="visible"}var $=class{hasAccess;errorUrl;onError;observer=null;currentCanonical;originalPushState;originalReplaceState;isMonkeyPatched=!1;constructor(e){this.hasAccess=e.hasAccess,this.errorUrl=e.errorUrl,this.onError=e.onError,this.currentCanonical=this.getCurrentCanonical(),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history)}getCurrentCanonical(){return document.querySelector('link[rel="canonical"]')?.href??null}normalizeToPath(e){if(e instanceof URL)return e.pathname;if(e.startsWith("./"))return e.slice(1);if(e.startsWith("/"))return e;try{return new URL(e).pathname}catch{return e.startsWith("/")?e:"/"+e}}async checkAccess(e){try{return await this.hasAccess(e)}catch(r){return console.error("[Router] Error checking access:",r),!1}}redirectToError(){window.location.replace(this.errorUrl)}handleAccessDenied(e){e&&this.onError&&this.onError(new Error(String(e))),this.redirectToError()}monkeyPatchHistory(){if(this.isMonkeyPatched)return;let e=this;history.pushState=async function(r,o,s){if(s){let n=e.normalizeToPath(s);await e.checkAccess(n)||O()}return e.originalPushState.call(this,r,o,s)},history.replaceState=async function(r,o,s){if(s){let n=e.normalizeToPath(s);await e.checkAccess(n)||(console.warn("Access denied to:",n),O())}return e.originalReplaceState.call(this,r,o,s)},this.isMonkeyPatched=!0}restoreHistory(){this.isMonkeyPatched&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState,this.isMonkeyPatched=!1)}start(){this.stop(),this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.head,{childList:!0,attributes:!0,attributeFilter:["rel","href"],subtree:!0}),this.monkeyPatchHistory()}stop(){this.observer&&(this.observer.disconnect(),this.observer=null),this.restoreHistory(),_()}handleMutations(e){let r=!1;for(let o of e){if(o.type==="childList"){let s=[...Array.from(o.addedNodes),...Array.from(o.removedNodes)];for(let n of s)if(n.nodeType===Node.ELEMENT_NODE){let a=n;if(this.isCanonicalLink(a)){r=!0;break}}}else if(o.type==="attributes"){let s=o.target;(this.isCanonicalLink(s)||o.oldValue==="canonical")&&(r=!0)}if(r)break}r&&this.checkCanonicalChange().catch(o=>{console.error("Error checking canonical change:",o),_()})}isCanonicalLink(e){return e.tagName==="LINK"&&e.getAttribute("rel")==="canonical"}async checkCanonicalChange(){let e=this.getCurrentCanonical();if(e!==this.currentCanonical)if(this.currentCanonical=e,e){let r=this.normalizeToPath(e);try{if(!await this.checkAccess(r)){console.warn("Access denied to canonical URL:",r),this.redirectToError();return}_()}catch(o){this.handleAccessDenied(o instanceof Error?o:new Error(String(o)))}}else _()}};var he=w("fa-bookmarks",j(),{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0})}),pe=p(!1);var me=async(t,e)=>{let r=t.data.session.get(),o=t.data.tags.get(),{pages:s}=t.data.project.get();if(!s.hasOwnProperty(e))return!0;if(!r)return!1;let a=s[e];return a.length===0?!0:a.some(y=>o.find(c=>c.id===y))};console.log("FramerAuth SDK: 2.0.7");var st="/v2",nt="framerauth.io",m=new B({data:{user:le,project:se,tags:ae,bookmarks:he,session:ue},state:{initializing:fe,userLoading:ce,projectLoading:ne,tagsLoading:ie,bookmarksLoading:pe,sessionLoading:de}});window.FramerAuth=m;var at=async()=>{O(),m.state.initializing.set(!0);try{let{data:t,error:e}=await m.api.fetchProject();if(e||!t)throw alert(e?.message||"Unable to load FramerAuth project!"),new Error(`Failed to fetch project: ${e?.message||"Project data is null"}`);m.data.project.set(t);let r=`${t.slug}.${nt}`,o=t.customDomain||r;m.updateBaseURL(`https://${o}${st}`);let{data:s,error:n}=await m.auth.getSession();if(!n&&s!==null){let{user:a,session:y}=s;if(m.data.user.set(a),m.data.session.set(y),a)try{let[c,i]=await Promise.all([m.api.fetchTags(),m.api.fetchBookmarks()]);m.data.tags.set(c.data??[]),m.data.bookmarks.set(i.data??{})}catch(c){console.warn("Failed to fetch tags or bookmarks:",c),m.data.tags.set([]),m.data.bookmarks.set({})}}return window.dispatchEvent(new CustomEvent("framerauth:initialized")),m}catch(t){throw console.error("Failed to initialize FramerAuth:",t),window.dispatchEvent(new CustomEvent("framerauth:initialization-failed",{detail:{error:t}})),t}finally{m.state.initializing.set(!1)}},it=async()=>{try{let t=await at(),e=new $({hasAccess:o=>me(t,o),errorUrl:"/sign-in",onError:o=>{console.error("[Router] Error in router:",o)}});if(!await e.checkAccess(window.location.pathname)){e.redirectToError();return}e.start()}catch(t){console.error("Failed to initialize app:",t)}};it();})();
1
+ "use strict";(()=>{var Ee=Object.defineProperty,Te=Object.defineProperties,Le=Object.getOwnPropertyDescriptors,J=Object.getOwnPropertySymbols,Ae=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable,K=(t,e,r)=>e in t?Ee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,L=(t,e)=>{for(var r in e||(e={}))Ae.call(e,r)&&K(t,r,e[r]);if(J)for(var r of J(e))Ue.call(e,r)&&K(t,r,e[r]);return t},A=(t,e)=>Te(t,Le(e)),Oe=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},_e=async(t,e)=>{var r,o,s,a,n,y;let c=e||{},i={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:c,hooks:i};for(let d of e?.plugins||[]){if(d.init){let b=await((r=d.init)==null?void 0:r.call(d,t.toString(),e));c=b.options||c,t=b.url}i.onRequest.push((o=d.hooks)==null?void 0:o.onRequest),i.onResponse.push((s=d.hooks)==null?void 0:s.onResponse),i.onSuccess.push((a=d.hooks)==null?void 0:a.onSuccess),i.onError.push((n=d.hooks)==null?void 0:n.onError),i.onRetry.push((y=d.hooks)==null?void 0:y.onRetry)}return{url:t,options:c,hooks:i}},V=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},xe=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function De(t){if(typeof t=="number")return new V({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new V(t);case"exponential":return new xe(t);default:throw new Error("Invalid retry strategy")}}var Be=async t=>{let e={},r=async o=>typeof o=="function"?await o():o;if(t?.auth){if(t.auth.type==="Bearer"){let o=await r(t.auth.token);if(!o)return e;e.authorization=`Bearer ${o}`}else if(t.auth.type==="Basic"){let o=r(t.auth.username),s=r(t.auth.password);if(!o||!s)return e;e.authorization=`Basic ${btoa(`${o}:${s}`)}`}else if(t.auth.type==="Custom"){let o=r(t.auth.value);if(!o)return e;e.authorization=`${r(t.auth.prefix)} ${o}`}}return e},Ce=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ne(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let o=e.split(";").shift()||"";return Ce.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function Fe(t){try{return JSON.parse(t),!0}catch{return!1}}function Y(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function G(t){try{return JSON.parse(t)}catch{return t}}function Q(t){return typeof t=="function"}function je(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&Q(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Q(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function $e(t){let e=new Headers(t?.headers),r=await Be(t);for(let[o,s]of Object.entries(r||{}))e.set(o,s);if(!e.has("content-type")){let o=Ie(t?.body);o&&e.set("content-type",o)}return e}function Ie(t){return Y(t)?"application/json":null}function Me(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Y(t.body)&&!e.has("content-type")){for(let[r,o]of Object.entries(t?.body))o instanceof Date&&(t.body[r]=o.toISOString());return JSON.stringify(t.body)}return t.body}function We(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let o=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return Z.includes(o)?o.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function ze(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var qe=class X extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,X.prototype)}};async function He(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new qe(r.issues);return r.value}var Z=["get","post","put","patch","delete"];function Je(t,e){let{baseURL:r,params:o,query:s}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let b=t.toString().split("@")[1].split("/")[0];Z.includes(b)&&(t=t.replace(`@${b}/`,"/"))}a.endsWith("/")||(a+="/");let[n,y]=t.replace(a,"").split("?"),c=new URLSearchParams(y);for(let[b,h]of Object.entries(s||{}))h!=null&&c.set(b,String(h));if(o)if(Array.isArray(o)){let b=n.split("/").filter(h=>h.startsWith(":"));for(let[h,I]of b.entries()){let x=o[h];n=n.replace(I,x)}}else for(let[b,h]of Object.entries(o))n=n.replace(`:${b}`,String(h));n=n.split("/").map(encodeURIComponent).join("/"),n.startsWith("/")&&(n=n.slice(1));let i=c.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${n}${i}`,a):`${a}${n}${i}`}var u=async(t,e)=>{var r,o,s,a,n,y,c,i;let{hooks:d,url:b,options:h}=await _e(t,e),I=je(h),x=new AbortController,ye=(r=h.signal)!=null?r:x.signal,ge=Je(b,h),be=Me(h),ve=await $e(h),Se=We(b,h),f=A(L({},h),{url:ge,headers:ve,body:be,method:Se,signal:ye});for(let v of d.onRequest)if(v){let g=await v(f);g instanceof Object&&(f=g)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((o=e?.body)==null?void 0:o.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:we}=ze(h,x),l=await I(f.url,f);we();let q={response:l,request:f};for(let v of d.onResponse)if(v){let g=await v(A(L({},q),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?l.clone():l}));g instanceof Response?l=g:g instanceof Object&&(l=g.response)}if(l.ok){if(!(f.method!=="HEAD"))return{data:"",error:null};let g=Ne(l),k={data:"",response:l,request:f};if(g==="json"||g==="text"){let E=await l.text(),ke=await((a=f.jsonParser)!=null?a:G)(E);k.data=ke}else k.data=await l[g]();f?.output&&f.output&&!f.disableValidation&&(k.data=await He(f.output,k.data));for(let E of d.onSuccess)E&&await E(A(L({},k),{response:(n=e?.hookOptions)!=null&&n.cloneResponse?l.clone():l}));return e?.throw?k.data:{data:k.data,error:null}}let Re=(y=e?.jsonParser)!=null?y:G,D=await l.text(),H=Fe(D),M=H?await Re(D):null,Pe={response:l,responseText:D,request:f,error:A(L({},M),{status:l.status,statusText:l.statusText})};for(let v of d.onError)v&&await v(A(L({},Pe),{response:(c=e?.hookOptions)!=null&&c.cloneResponse?l.clone():l}));if(e?.retry){let v=De(e.retry),g=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(g,l)){for(let E of d.onRetry)E&&await E(q);let k=v.getDelay(g);return await new Promise(E=>setTimeout(E,k)),await u(t,A(L({},e),{retryAttempt:g+1}))}}if(e?.throw)throw new Oe(l.status,l.statusText,H?M:D);return{data:null,error:A(L({},M),{status:l.status,statusText:l.statusText})}};var Ke="https://core.framerauth.com/v2",B=class{baseURL=null;data;state;api;auth;constructor(e){this.baseURL=null,this.data=e.data,this.state=e.state,this.api={fetchTags:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");return await u(`${this.baseURL}/profile/tags`,{credentials:"include"})},fetchBookmarks:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await u(`${this.baseURL}/profile/bookmarks`,{credentials:"include"});if(!r.data)return r;let o=new Set(r.data),s={};for(let a of o)s[a]=!0;return{data:s,error:null}},fetchProject:async()=>await u(`${Ke}/public/project/config`)},this.auth={getSession:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await u(`${this.baseURL}/get-session`,{method:"GET",credentials:"include",query:{disableCookieCache:!0}});return r.data?(this.data.user.set(r.data.user),this.data.session.set(r.data.session)):(this.data.user.set(null),this.data.session.set(null),this.data.tags.set([]),this.data.bookmarks.set({})),r},signUp:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-up/email`,{method:"POST",credentials:"include",body:r});return o.error||(this.data.user.set(o.data.user),this.auth.getSession(),this.api.fetchTags().then(s=>{this.data.tags.set(s.data??[])}),this.api.fetchBookmarks().then(s=>{this.data.bookmarks.set(s.data??{})})),o},signIn:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-in/email`,{method:"POST",credentials:"include",body:r});return o.error||(this.data.user.set(o.data.user),this.auth.getSession(),this.api.fetchTags().then(s=>{this.data.tags.set(s.data??[])}),this.api.fetchBookmarks().then(s=>{this.data.bookmarks.set(s.data??{})})),o},signInSocial:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-in/social`,{method:"POST",credentials:"include",body:r});return o.data?.url&&(window.location.href=o.data.url),o},signOut:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await u(`${this.baseURL}/sign-out`,{method:"POST",credentials:"include",body:{}});return this.data.user.set(null),this.data.session.set(null),this.data.tags.set([]),this.data.bookmarks.set({}),r?.redirectTo&&(window.location.href=r.redirectTo),o},sendOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/email-otp/send-verification-otp`;return await u(o,{body:r,credentials:"include",method:"POST"})},signInOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/sign-in/email-otp`,s=await u(o,{body:r,credentials:"include",method:"POST"});return s.error||(this.data.user.set(s.data.user),this.auth.getSession(),this.api.fetchTags().then(a=>{this.data.tags.set(a.data??[])}),this.api.fetchBookmarks().then(a=>{this.data.bookmarks.set(a.data??{})})),s},updateProfile:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile`;return await u(o,{body:r,credentials:"include",method:"PATCH"})},updateProfilePicture:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/avatar`;return await u(o,{method:"POST",body:r,credentials:"include"})},createBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks`;return await u(o,{body:r,credentials:"include",method:"POST"})},deleteBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks/${r.bookmark_type}/${r.id}`;return await u(o,{credentials:"include",method:"DELETE"})},sendForgotPasswordEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/request-password-reset`;return await u(o,{body:r,credentials:"include",method:"POST"})},resetPassword:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/reset-password`;return await u(o,{body:r,credentials:"include",method:"POST"})},storeCheckout:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/store/checkout/session`;return await u(o,{body:r,credentials:"include",method:"POST"})}}}updateBaseURL(e){this.baseURL=e}};var S=[],T=0,C=4,Ve=0,p=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(o){return r.lc=e.push(o),()=>{for(let a=T+C;a<S.length;)S[a]===o?S.splice(a,C):a+=C;let s=e.indexOf(o);~s&&(e.splice(s,1),--r.lc||r.off())}},notify(o,s){Ve++;let a=!S.length;for(let n of e)S.push(n,r.value,o,s);if(a){for(T=0;T<S.length;T+=C)S[T](S[T+1],S[T+2],S[T+3]);S.length=0}},off(){},set(o){let s=r.value;s!==o&&(r.value=o,r.notify(s))},subscribe(o){let s=r.listen(o);return o(r.value),s},value:t};return r};var Ge=5,N=6,F=10,Qe=(t,e,r,o)=>(t.events=t.events||{},t.events[r+F]||(t.events[r+F]=o(s=>{t.events[r].reduceRight((a,n)=>(n(a),a),{shared:{},...s})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let s=t.events[r],a=s.indexOf(e);s.splice(a,1),s.length||(delete t.events[r],t.events[r+F](),delete t.events[r+F])});var ee=1e3,W=(t,e)=>Qe(t,o=>{let s=e(o);s&&t.events[N].push(s)},Ge,o=>{let s=t.listen;t.listen=(...n)=>(!t.lc&&!t.active&&(t.active=!0,o()),s(...n));let a=t.off;return t.events[N]=[],t.off=()=>{a(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let n of t.events[N])n();t.events[N]=[]}},ee)},()=>{t.listen=s,t.off=a}});var j=(t={})=>{let e=p(t);return e.setKey=function(r,o){let s=e.value;typeof o>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(s,r)):e.value[r]!==o&&(e.value={...e.value,[r]:o},e.notify(s,r))},e};var te=t=>t,U={},z={addEventListener(){},removeEventListener(){}};function Ye(){try{return typeof localStorage<"u"}catch{return!1}}Ye()&&(U=localStorage);var Xe={addEventListener(t,e,r){window.addEventListener("storage",e),window.addEventListener("pageshow",r)},removeEventListener(t,e,r){window.removeEventListener("storage",e),window.removeEventListener("pageshow",r)}};typeof window<"u"&&(z=Xe);function w(t,e=void 0,r={}){let o=r.encode||te,s=r.decode||te,a=p(e),n=a.set;a.set=i=>{let d=o(i);typeof d>"u"?delete U[t]:U[t]=d,n(i)};function y(i){i.key===t?i.newValue===null?n(e):n(s(i.newValue)):U[t]||n(e)}function c(){a.set(U[t]?s(U[t]):e)}return W(a,()=>{if(c(),r.listen!==!1)return z.addEventListener(t,y,c),()=>{z.removeEventListener(t,y,c)}}),a}var Ze="framerauth_v2_",re=new TextEncoder,et=new TextDecoder;function oe(){let t=typeof window<"u"?window.location.hostname:"1f8cXd6c7b4a3vL4z5746oUgQ28190adbef";return re.encode(Ze+t)}function tt(t){let e=oe(),r=re.encode(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s++)o[s]=r[s]^e[s%e.length];return o}function rt(t){let e=tt(t),r=Array.from(e,o=>String.fromCharCode(o)).join("");return btoa(r)}function ot(t){let e=oe(),r=atob(t),o=Uint8Array.from(r,a=>a.charCodeAt(0)),s=new Uint8Array(o.length);for(let a=0;a<o.length;a++)s[a]=o[a]^e[a%e.length];return et.decode(s)}function R({obfuscate:t}){return e=>{let r=JSON.stringify(e);return t&&(r=rt(r)),r}}function P({deobfuscate:t,fallback:e}){return r=>{try{return r?(t&&(r=ot(r)),JSON.parse(r)):e}catch{return e}}}var se=w("fa-project",null,{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0,fallback:null})}),ae=p(!1);var ne=w("fa-tags",[],{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0,fallback:[]})}),ie=p(!1);var le=w("fa-user",null,{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0,fallback:null})}),ce=p(!1);var ue=w("fa-session",null,{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0,fallback:null})}),de=p(!1);var fe=p(!0);function O(){document.body.style.visibility="hidden"}function _(){document.body.style.visibility="visible"}var $=class{hasAccess;errorUrl;onError;observer=null;currentCanonical;originalPushState;originalReplaceState;isMonkeyPatched=!1;constructor(e){this.hasAccess=e.hasAccess,this.errorUrl=e.errorUrl,this.onError=e.onError,this.currentCanonical=this.getCurrentCanonical(),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history)}getCurrentCanonical(){return document.querySelector('link[rel="canonical"]')?.href??null}normalizeToPath(e){if(e instanceof URL)return e.pathname;if(e.startsWith("./"))return e.slice(1);if(e.startsWith("/"))return e;try{return new URL(e).pathname}catch{return e.startsWith("/")?e:"/"+e}}async checkAccess(e){try{return await this.hasAccess(e)}catch(r){return console.error("[Router] Error checking access:",r),!1}}redirectToError(){window.location.replace(this.errorUrl)}handleAccessDenied(e){e&&this.onError&&this.onError(new Error(String(e))),this.redirectToError()}monkeyPatchHistory(){if(this.isMonkeyPatched)return;let e=this;history.pushState=async function(r,o,s){if(s){let a=e.normalizeToPath(s);await e.checkAccess(a)||O()}return e.originalPushState.call(this,r,o,s)},history.replaceState=async function(r,o,s){if(s){let a=e.normalizeToPath(s);await e.checkAccess(a)||(console.warn("Access denied to:",a),O())}return e.originalReplaceState.call(this,r,o,s)},this.isMonkeyPatched=!0}restoreHistory(){this.isMonkeyPatched&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState,this.isMonkeyPatched=!1)}start(){this.stop(),this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.head,{childList:!0,attributes:!0,attributeFilter:["rel","href"],subtree:!0}),this.monkeyPatchHistory()}stop(){this.observer&&(this.observer.disconnect(),this.observer=null),this.restoreHistory(),_()}handleMutations(e){let r=!1;for(let o of e){if(o.type==="childList"){let s=[...Array.from(o.addedNodes),...Array.from(o.removedNodes)];for(let a of s)if(a.nodeType===Node.ELEMENT_NODE){let n=a;if(this.isCanonicalLink(n)){r=!0;break}}}else if(o.type==="attributes"){let s=o.target;(this.isCanonicalLink(s)||o.oldValue==="canonical")&&(r=!0)}if(r)break}r&&this.checkCanonicalChange().catch(o=>{console.error("Error checking canonical change:",o),_()})}isCanonicalLink(e){return e.tagName==="LINK"&&e.getAttribute("rel")==="canonical"}async checkCanonicalChange(){let e=this.getCurrentCanonical();if(e!==this.currentCanonical)if(this.currentCanonical=e,e){let r=this.normalizeToPath(e);try{if(!await this.checkAccess(r)){console.warn("Access denied to canonical URL:",r),this.redirectToError();return}_()}catch(o){this.handleAccessDenied(o instanceof Error?o:new Error(String(o)))}}else _()}};var he=w("fa-bookmarks",j(),{encode:R({obfuscate:!0}),decode:P({deobfuscate:!0,fallback:{}})}),pe=p(!1);var me=async(t,e)=>{let r=t.data.session.get(),o=t.data.tags.get(),{pages:s}=t.data.project.get();if(!s.hasOwnProperty(e))return!0;if(!r)return!1;let n=s[e];return n.length===0?!0:n.some(y=>o.find(c=>c.id===y))};console.log("FramerAuth SDK: 2.0.9");var st="/v2",at="framerauth.io",m=new B({data:{user:le,project:se,tags:ne,bookmarks:he,session:ue},state:{initializing:fe,userLoading:ce,projectLoading:ae,tagsLoading:ie,bookmarksLoading:pe,sessionLoading:de}});window.FramerAuth=m;var nt=async()=>{O(),m.state.initializing.set(!0);try{let{data:t,error:e}=await m.api.fetchProject();if(e||!t)throw alert(e?.message||"Unable to load FramerAuth project!"),new Error(`Failed to fetch project: ${e?.message||"Project data is null"}`);m.data.project.set(t);let r=`${t.slug}.${at}`,o=t.customDomain||r;m.updateBaseURL(`https://${o}${st}`);let{data:s,error:a}=await m.auth.getSession();if(!a&&s!==null){let{user:n,session:y}=s;if(m.data.user.set(n),m.data.session.set(y),n)try{let[c,i]=await Promise.all([m.api.fetchTags(),m.api.fetchBookmarks()]);m.data.tags.set(c.data??[]),m.data.bookmarks.set(i.data??{})}catch(c){console.warn("Failed to fetch tags or bookmarks:",c),m.data.tags.set([]),m.data.bookmarks.set({})}}return window.dispatchEvent(new CustomEvent("framerauth:initialized")),m}catch(t){throw console.error("Failed to initialize FramerAuth:",t),window.dispatchEvent(new CustomEvent("framerauth:initialization-failed",{detail:{error:t}})),t}finally{m.state.initializing.set(!1)}},it=async()=>{try{let t=await nt(),e=new $({hasAccess:o=>me(t,o),errorUrl:"/sign-in",onError:o=>{console.error("[Router] Error in router:",o)}});if(!await e.checkAccess(window.location.pathname)){e.redirectToError();return}e.start()}catch(t){console.error("Failed to initialize app:",t)}};it();})();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@framerauth/sdk",
3
3
  "license": "MIT",
4
- "version": "2.0.7",
4
+ "version": "2.0.9",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",