@framerauth/sdk 2.1.1 → 2.1.3
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/framerauth.js +1 -1
- package/dist/framerauth.mjs +1 -1
- package/package.json +1 -1
package/dist/framerauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var We=Object.defineProperty,ze=Object.defineProperties,Ie=Object.getOwnPropertyDescriptors,X=Object.getOwnPropertySymbols,$e=Object.prototype.hasOwnProperty,Me=Object.prototype.propertyIsEnumerable,Z=(t,e,r)=>e in t?We(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,U=(t,e)=>{for(var r in e||(e={}))$e.call(e,r)&&Z(t,r,e[r]);if(X)for(var r of X(e))Me.call(e,r)&&Z(t,r,e[r]);return t},O=(t,e)=>ze(t,Ie(e)),qe=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},He=async(t,e)=>{var r,n,o,a,s,b;let m=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:m,hooks:i};for(let u of e?.plugins||[]){if(u.init){let P=await((r=u.init)==null?void 0:r.call(u,t.toString(),e));m=P.options||m,t=P.url}i.onRequest.push((n=u.hooks)==null?void 0:n.onRequest),i.onResponse.push((o=u.hooks)==null?void 0:o.onResponse),i.onSuccess.push((a=u.hooks)==null?void 0:a.onSuccess),i.onError.push((s=u.hooks)==null?void 0:s.onError),i.onRetry.push((b=u.hooks)==null?void 0:b.onRetry)}return{url:t,options:m,hooks:i}},ee=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}},Je=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 Ve(t){if(typeof t=="number")return new ee({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new ee(t);case"exponential":return new Je(t);default:throw new Error("Invalid retry strategy")}}var Ke=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),o=r(t.auth.password);if(!n||!o)return e;e.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},Ge=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Qe(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return Ge.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Ye(t){try{return JSON.parse(t),!0}catch{return!1}}function ne(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 te(t){try{return JSON.parse(t)}catch{return t}}function re(t){return typeof t=="function"}function Xe(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&re(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&re(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Ze(t){let e=new Headers(t?.headers),r=await Ke(t);for(let[n,o]of Object.entries(r||{}))e.set(n,o);if(!e.has("content-type")){let n=et(t?.body);n&&e.set("content-type",n)}return e}function et(t){return ne(t)?"application/json":null}function tt(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(ne(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function rt(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return ae.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function nt(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var ot=class oe extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,oe.prototype)}};async function at(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new ot(r.issues);return r.value}var ae=["get","post","put","patch","delete"];function st(t,e){let{baseURL:r,params:n,query:o}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let P=t.toString().split("@")[1].split("/")[0];ae.includes(P)&&(t=t.replace(`@${P}/`,"/"))}a.endsWith("/")||(a+="/");let[s,b]=t.replace(a,"").split("?"),m=new URLSearchParams(b);for(let[P,h]of Object.entries(o||{}))h!=null&&m.set(P,String(h));if(n)if(Array.isArray(n)){let P=s.split("/").filter(h=>h.startsWith(":"));for(let[h,q]of P.entries()){let B=n[h];s=s.replace(q,B)}}else for(let[P,h]of Object.entries(n))s=s.replace(`:${P}`,String(h));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let i=m.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${s}${i}`,a):`${a}${s}${i}`}var f=async(t,e)=>{var r,n,o,a,s,b,m,i;let{hooks:u,url:P,options:h}=await He(t,e),q=Xe(h),B=new AbortController,Oe=(r=h.signal)!=null?r:B.signal,xe=st(P,h),_e=tt(h),Be=await Ze(h),De=rt(P,h),d=O(U({},h),{url:xe,headers:Be,body:_e,method:De,signal:Oe});for(let v of u.onRequest)if(v){let y=await v(d);y instanceof Object&&(d=y)}("pipeTo"in d&&typeof d.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in d||(d.duplex="half"));let{clearTimeout:je}=nt(h,B),l=await q(d.url,d);je();let Q={response:l,request:d};for(let v of u.onResponse)if(v){let y=await v(O(U({},Q),{response:(o=e?.hookOptions)!=null&&o.cloneResponse?l.clone():l}));y instanceof Response?l=y:y instanceof Object&&(l=y.response)}if(l.ok){if(!(d.method!=="HEAD"))return{data:"",error:null};let y=Qe(l),E={data:"",response:l,request:d};if(y==="json"||y==="text"){let T=await l.text(),Fe=await((a=d.jsonParser)!=null?a:te)(T);E.data=Fe}else E.data=await l[y]();d?.output&&d.output&&!d.disableValidation&&(E.data=await at(d.output,E.data));for(let T of u.onSuccess)T&&await T(O(U({},E),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?l.clone():l}));return e?.throw?E.data:{data:E.data,error:null}}let Ce=(b=e?.jsonParser)!=null?b:te,D=await l.text(),Y=Ye(D),H=Y?await Ce(D):null,Ne={response:l,responseText:D,request:d,error:O(U({},H),{status:l.status,statusText:l.statusText})};for(let v of u.onError)v&&await v(O(U({},Ne),{response:(m=e?.hookOptions)!=null&&m.cloneResponse?l.clone():l}));if(e?.retry){let v=Ve(e.retry),y=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(y,l)){for(let T of u.onRetry)T&&await T(Q);let E=v.getDelay(y);return await new Promise(T=>setTimeout(T,E)),await f(t,O(U({},e),{retryAttempt:y+1}))}}if(e?.throw)throw new qe(l.status,l.statusText,Y?H:D);return{data:null,error:O(U({},H),{status:l.status,statusText:l.statusText})}};var it="https://core.framerauth.com/v2",j=class{baseURL=null;data;state;api;auth;constructor(e){this.baseURL=null,this.data=e.data,this.state=e.state,this.api={fetchBookmarks:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await f(`${this.baseURL}/profile/bookmarks`,{credentials:"include"});if(!r.data)return r;let n=new Set(r.data),o={};for(let a of n)o[a]=!0;return{data:o,error:null}},fetchProject:async()=>await f(`${it}/public/project/config`)},this.auth={getSession:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await f(`${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.tags.set(r.data.user.tags??[])):(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 n=await f(`${this.baseURL}/sign-up/email`,{method:"POST",credentials:"include",body:r});return n.error||(this.data.user.set({...n.data.user,tags:[]}),this.auth.getSession(),this.api.fetchBookmarks().then(o=>{this.data.bookmarks.set(o.data??{})})),n},signIn:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=await f(`${this.baseURL}/sign-in/email`,{method:"POST",credentials:"include",body:r});return n.error||(this.data.user.set({...n.data.user,tags:[]}),this.auth.getSession(),this.api.fetchBookmarks().then(o=>{this.data.bookmarks.set(o.data??{})})),n},signInSocial:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=await f(`${this.baseURL}/sign-in/social`,{method:"POST",credentials:"include",body:r});return n.data?.url&&(window.location.href=n.data.url),n},signOut:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=await f(`${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),n},sendOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/email-otp/send-verification-otp`;return await f(n,{body:r,credentials:"include",method:"POST"})},signInOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/sign-in/email-otp`,o=await f(n,{body:r,credentials:"include",method:"POST"});return o.error||(this.data.user.set({...o.data.user,tags:[]}),this.auth.getSession(),this.api.fetchBookmarks().then(a=>{this.data.bookmarks.set(a.data??{})})),o},updateProfile:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile`;return await f(n,{body:r,credentials:"include",method:"PATCH"})},updateProfilePicture:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile/avatar`;return await f(n,{method:"POST",body:r,credentials:"include"})},createBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile/bookmarks`;return await f(n,{body:r,credentials:"include",method:"POST"})},deleteBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile/bookmarks/${r.bookmark_type}/${r.id}`;return await f(n,{credentials:"include",method:"DELETE"})},sendForgotPasswordEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/request-password-reset`;return await f(n,{body:r,credentials:"include",method:"POST"})},resetPassword:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/reset-password`;return await f(n,{body:r,credentials:"include",method:"POST"})},storeCheckout:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/store/checkout/session`;return await f(n,{body:r,credentials:"include",method:"POST"})}}}updateBaseURL(e){this.baseURL=e}};var S=[],A=0,C=4,lt=0,p=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(n){return r.lc=e.push(n),()=>{for(let a=A+C;a<S.length;)S[a]===n?S.splice(a,C):a+=C;let o=e.indexOf(n);~o&&(e.splice(o,1),--r.lc||r.off())}},notify(n,o){lt++;let a=!S.length;for(let s of e)S.push(s,r.value,n,o);if(a){for(A=0;A<S.length;A+=C)S[A](S[A+1],S[A+2],S[A+3]);S.length=0}},off(){},set(n){let o=r.value;o!==n&&(r.value=n,r.notify(o))},subscribe(n){let o=r.listen(n);return n(r.value),o},value:t};return r};var ct=5,N=6,F=10,ut=(t,e,r,n)=>(t.events=t.events||{},t.events[r+F]||(t.events[r+F]=n(o=>{t.events[r].reduceRight((a,s)=>(s(a),a),{shared:{},...o})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let o=t.events[r],a=o.indexOf(e);o.splice(a,1),o.length||(delete t.events[r],t.events[r+F](),delete t.events[r+F])});var se=1e3,J=(t,e)=>ut(t,n=>{let o=e(n);o&&t.events[N].push(o)},ct,n=>{let o=t.listen;t.listen=(...s)=>(!t.lc&&!t.active&&(t.active=!0,n()),o(...s));let a=t.off;return t.events[N]=[],t.off=()=>{a(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let s of t.events[N])s();t.events[N]=[]}},se)},()=>{t.listen=o,t.off=a}});var W=(t={})=>{let e=p(t);return e.setKey=function(r,n){let o=e.value;typeof n>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(o,r)):e.value[r]!==n&&(e.value={...e.value,[r]:n},e.notify(o,r))},e};var ie=t=>t,x={},V={addEventListener(){},removeEventListener(){}};function dt(){try{return typeof localStorage<"u"}catch{return!1}}dt()&&(x=localStorage);var ft={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"&&(V=ft);function k(t,e=void 0,r={}){let n=r.encode||ie,o=r.decode||ie,a=p(e),s=a.set;a.set=i=>{let u=n(i);typeof u>"u"?delete x[t]:x[t]=u,s(i)};function b(i){i.key===t?i.newValue===null?s(e):s(o(i.newValue)):x[t]||s(e)}function m(){a.set(x[t]?o(x[t]):e)}return J(a,()=>{if(m(),r.listen!==!1)return V.addEventListener(t,b,m),()=>{V.removeEventListener(t,b,m)}}),a}var ht="framerauth_v2_",le=new TextEncoder,pt=new TextDecoder;function ce(){let t=typeof window<"u"?window.location.hostname:"1f8cXd6c7b4a3vL4z5746oUgQ28190adbef";return le.encode(ht+t)}function mt(t){let e=ce(),r=le.encode(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r[o]^e[o%e.length];return n}function gt(t){let e=mt(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return btoa(r)}function yt(t){let e=ce(),r=atob(t),n=Uint8Array.from(r,a=>a.charCodeAt(0)),o=new Uint8Array(n.length);for(let a=0;a<n.length;a++)o[a]=n[a]^e[a%e.length];return pt.decode(o)}function w({obfuscate:t}){return e=>{let r=JSON.stringify(e);return t&&(r=gt(r)),r}}function R({deobfuscate:t,fallback:e,validator:r}){return n=>{try{if(!n)return e;t&&(n=yt(n));let o=JSON.parse(n);if(r){let a=r(o);return a===null?e:a}return o}catch{return e}}}var ue=k("fa-project",null,{encode:w({obfuscate:!0}),decode:R({deobfuscate:!0,fallback:null})}),de=p(!1);var fe=k("fa-tags",[],{encode:w({obfuscate:!0}),decode:R({deobfuscate:!0,fallback:[]})}),he=p(!1);function pe(t){return Array.isArray(t)?t.length===0?!0:t.every(e=>e!==null&&typeof e=="object"&&typeof e.id=="string"&&typeof e.name=="string"):!1}function bt(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id!="string"||typeof e.email!="string"||typeof e.name!="string"||typeof e.email_verified!="boolean"||!(e.created_at instanceof Date||typeof e.created_at=="string")||!(e.updated_at instanceof Date||typeof e.updated_at=="string")?!1:pe(e.tags)}function Pt(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.user_id=="string"&&typeof e.token=="string"&&(e.expires_at instanceof Date||typeof e.expires_at=="string")&&(e.created_at instanceof Date||typeof e.created_at=="string")&&(e.updated_at instanceof Date||typeof e.updated_at=="string")}function me(t){if(!t||typeof t!="object")return null;let e=t;return pe(e.tags)||(e.tags=[]),bt(e)?e:null}function ge(t){return Pt(t)?t:null}function vt(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.entries(t).every(([e,r])=>typeof e=="string"&&typeof r=="boolean")}function ye(t){return!t||typeof t!="object"||Array.isArray(t)?{}:vt(t)?t:{}}var be=k("fa-user",null,{encode:w({obfuscate:!0}),decode:R({deobfuscate:!0,fallback:null,validator:me})}),Pe=p(!1);var ve=k("fa-session",null,{encode:w({obfuscate:!0}),decode:R({deobfuscate:!0,fallback:null,validator:ge})}),Se=p(!1);var ke=p(!0);function _(){document.body.style.visibility="hidden"}function L(){document.body.style.visibility="visible"}function z(){let t=document.querySelector('meta[name="framerauth:error-path"]');if(t){let e=t.getAttribute("content");if(e)return e.trim()}return"/sign-in"}function g(t){let r=(t??"").trim();if(r.includes("://"))try{r=new URL(r).pathname}catch{}return r=r.split("#")[0]??"",r=r.split("?")[0]??"",r.length===0&&(r="/"),r.startsWith("/")||(r=`/${r}`),r!=="/"&&r.endsWith("/")&&(r=r.slice(0,-1)),r}function I(t,e){return g(t)===g(e)}function K(t=window.location.pathname){let e=z();return I(t,e)}function we(){let t=document.querySelector('meta[name="framerauth:boost"]');if(!t)return[];let e=t.getAttribute("content");return e?e.split(",").map(r=>r.trim()).filter(Boolean):[]}function Re(t){let e=t.map(r=>r.trim()).filter(Boolean).map(r=>{if(r==="*"||r==="/*")return{kind:"all"};let n=r.startsWith("/")?r:`/${r}`;return n.endsWith("/**")?{kind:"deep",base:g(n.slice(0,-3))}:n.endsWith("/*")?{kind:"oneSegment",base:g(n.slice(0,-2))}:n.endsWith("*")?{kind:"prefixPathSegment",base:g(n.slice(0,-1))}:{kind:"exact",base:g(n)}});return r=>{let n=g(r);return e.some(o=>{if(o.kind==="all")return!0;if(o.kind==="exact")return n===o.base;if(o.kind==="deep")return n.startsWith(`${o.base}/`);if(o.kind==="oneSegment"){if(!n.startsWith(`${o.base}/`))return!1;let a=n.slice(o.base.length+1);return a.length>0&&!a.includes("/")}return n===o.base||n.startsWith(`${o.base}/`)})}}var $=class{hasAccess;isPublicPath;errorPath;onError;observer=null;currentCanonical;originalPushState;originalReplaceState;isMonkeyPatched=!1;constructor(e){this.hasAccess=e.hasAccess,this.isPublicPath=e.isPublicPath,this.errorPath=e.errorPath,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 g(e.pathname);if(e.startsWith("./"))return g(e.slice(1));if(e.startsWith("/"))return g(e);try{let r=new URL(e);return g(r.pathname)}catch{return g(e.startsWith("/")?e:"/"+e)}}normalizePathInput(e){let r=e.startsWith("/")?e:`/${e}`;return g(r)}isErrorPath(e){let r=this.normalizePathInput(e);return I(r,this.errorPath)}checkAccess(e){let r=this.normalizePathInput(e);if(this.isErrorPath(r)||this.isPublicPath(r))return!0;try{return this.hasAccess(r)}catch{return!1}}isOnErrorPage(){let e=this.normalizePathInput(window.location.pathname);return I(e,this.errorPath)}redirectToError(){if(this.isOnErrorPage()){L();return}window.location.replace(this.errorPath)}handleAccessDenied(e){e&&this.onError&&this.onError(e),this.redirectToError()}monkeyPatchHistory(){if(this.isMonkeyPatched)return;let e=this;history.pushState=function(r,n,o){if(o){let a=e.normalizeToPath(o);e.checkAccess(a)||_()}return e.originalPushState.call(this,r,n,o)},history.replaceState=function(r,n,o){if(o){let a=e.normalizeToPath(o);e.checkAccess(a)||_()}return e.originalReplaceState.call(this,r,n,o)},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(),L()}handleMutations(e){let r=!1;for(let n of e){if(n.type==="childList"){let o=[...Array.from(n.addedNodes),...Array.from(n.removedNodes)];for(let a of o)if(a.nodeType===Node.ELEMENT_NODE){let s=a;if(this.isCanonicalLink(s)){r=!0;break}}}else if(n.type==="attributes"){let o=n.target;(this.isCanonicalLink(o)||n.oldValue==="canonical")&&(r=!0)}if(r)break}r&&this.checkCanonicalChange()}isCanonicalLink(e){return e.tagName==="LINK"&&e.getAttribute("rel")==="canonical"}checkCanonicalChange(){let e=this.getCurrentCanonical();if(e!==this.currentCanonical)if(this.currentCanonical=e,e){let r=this.normalizeToPath(e);if(!this.checkAccess(r)){this.handleAccessDenied();return}L()}else L()}};var Ee=k("fa-bookmarks",W(),{encode:w({obfuscate:!0}),decode:R({deobfuscate:!0,fallback:{},validator:ye})}),Te=p(!1);var Ae=(t,e)=>{let r=g(e),n=t.data.user.get(),o=t.data.session.get(),a=t.data.project.get();if(!a)return!1;if(!Object.prototype.hasOwnProperty.call(a.pages,r))return!0;if(!n||!o)return!1;let b=a.pages[r];return b.length===0?!0:b.some(m=>n.tags.find(i=>i.id===m))};console.log("FramerAuth SDK (JavaScript): 2.1.1");var St="/v2",kt="framerauth.io",c=new j({data:{user:be,project:ue,tags:fe,bookmarks:Ee,session:ve},state:{initializing:ke,userLoading:Pe,projectLoading:de,tagsLoading:he,bookmarksLoading:Te,sessionLoading:Se}});window.FramerAuth=c;var wt=we(),Le=Re(wt);function Rt(){return K()?!0:c.data.project.get()!==null&&Le(window.location.pathname)}function M(t){let e=`${t.slug}.${kt}`,r=t.customDomain||e;c.updateBaseURL(`https://${r}${St}`)}function G(){c.api.fetchBookmarks().then(({data:t})=>{c.data.bookmarks.set(t??{})})}function Ue(){let t=z(),e=new $({hasAccess:n=>Ae(c,n),isPublicPath:n=>Le(n),errorPath:t,onError:n=>{console.error("[Router] Error in router:",n)}});return e.checkAccess(window.location.pathname)?(e.start(),!0):(e.handleAccessDenied(),!1)}function Et(){let t=c.data.project.get();return t?(M(t),c.api.fetchProject().then(e=>{e.data&&(c.data.project.set(e.data),M(e.data))}),c.auth.getSession().then(e=>{e.data!==null&&G()})):c.api.fetchProject().then(e=>{if(e.data)return c.data.project.set(e.data),M(e.data),c.auth.getSession()}).then(e=>{e?.data!==null&&G()}),Ue()}async function Tt(){_();let t=c.data.project.get(),e=await c.api.fetchProject();if(e.data)t=e.data,c.data.project.set(t);else if(!t)throw new Error(e.error.message||"Unable to load FramerAuth project!");M(t),(await c.auth.getSession()).data!==null&&G();let n=Ue();return n&&L(),n}async function At(){c.state.initializing.set(!0);try{(Rt()?Et():await Tt())&&window.dispatchEvent(new CustomEvent("framerauth:initialized"))}catch(t){console.error("Failed to initialize FramerAuth:",t),K()?L():window.location.replace(z()),window.dispatchEvent(new CustomEvent("framerauth:initialization-failed",{detail:{error:t}}))}finally{c.state.initializing.set(!1)}}At();})();
|
|
1
|
+
"use strict";(()=>{var ze=Object.defineProperty,We=Object.defineProperties,$e=Object.getOwnPropertyDescriptors,X=Object.getOwnPropertySymbols,Ie=Object.prototype.hasOwnProperty,Me=Object.prototype.propertyIsEnumerable,Z=(t,e,r)=>e in t?ze(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,U=(t,e)=>{for(var r in e||(e={}))Ie.call(e,r)&&Z(t,r,e[r]);if(X)for(var r of X(e))Me.call(e,r)&&Z(t,r,e[r]);return t},O=(t,e)=>We(t,$e(e)),qe=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},He=async(t,e)=>{var r,n,o,a,s,b;let m=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:m,hooks:i};for(let d of e?.plugins||[]){if(d.init){let P=await((r=d.init)==null?void 0:r.call(d,t.toString(),e));m=P.options||m,t=P.url}i.onRequest.push((n=d.hooks)==null?void 0:n.onRequest),i.onResponse.push((o=d.hooks)==null?void 0:o.onResponse),i.onSuccess.push((a=d.hooks)==null?void 0:a.onSuccess),i.onError.push((s=d.hooks)==null?void 0:s.onError),i.onRetry.push((b=d.hooks)==null?void 0:b.onRetry)}return{url:t,options:m,hooks:i}},ee=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}},Je=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 Ve(t){if(typeof t=="number")return new ee({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new ee(t);case"exponential":return new Je(t);default:throw new Error("Invalid retry strategy")}}var Ke=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),o=r(t.auth.password);if(!n||!o)return e;e.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},Ge=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Qe(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return Ge.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Ye(t){try{return JSON.parse(t),!0}catch{return!1}}function ne(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 te(t){try{return JSON.parse(t)}catch{return t}}function re(t){return typeof t=="function"}function Xe(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&re(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&re(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Ze(t){let e=new Headers(t?.headers),r=await Ke(t);for(let[n,o]of Object.entries(r||{}))e.set(n,o);if(!e.has("content-type")){let n=et(t?.body);n&&e.set("content-type",n)}return e}function et(t){return ne(t)?"application/json":null}function tt(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(ne(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function rt(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return ae.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function nt(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var ot=class oe extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,oe.prototype)}};async function at(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new ot(r.issues);return r.value}var ae=["get","post","put","patch","delete"];function st(t,e){let{baseURL:r,params:n,query:o}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let P=t.toString().split("@")[1].split("/")[0];ae.includes(P)&&(t=t.replace(`@${P}/`,"/"))}a.endsWith("/")||(a+="/");let[s,b]=t.replace(a,"").split("?"),m=new URLSearchParams(b);for(let[P,h]of Object.entries(o||{}))h!=null&&m.set(P,String(h));if(n)if(Array.isArray(n)){let P=s.split("/").filter(h=>h.startsWith(":"));for(let[h,q]of P.entries()){let B=n[h];s=s.replace(q,B)}}else for(let[P,h]of Object.entries(n))s=s.replace(`:${P}`,String(h));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let i=m.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${s}${i}`,a):`${a}${s}${i}`}var c=async(t,e)=>{var r,n,o,a,s,b,m,i;let{hooks:d,url:P,options:h}=await He(t,e),q=Xe(h),B=new AbortController,Oe=(r=h.signal)!=null?r:B.signal,xe=st(P,h),_e=tt(h),Be=await Ze(h),De=rt(P,h),f=O(U({},h),{url:xe,headers:Be,body:_e,method:De,signal:Oe});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((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:je}=nt(h,B),l=await q(f.url,f);je();let Q={response:l,request:f};for(let v of d.onResponse)if(v){let g=await v(O(U({},Q),{response:(o=e?.hookOptions)!=null&&o.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=Qe(l),E={data:"",response:l,request:f};if(g==="json"||g==="text"){let T=await l.text(),Fe=await((a=f.jsonParser)!=null?a:te)(T);E.data=Fe}else E.data=await l[g]();f?.output&&f.output&&!f.disableValidation&&(E.data=await at(f.output,E.data));for(let T of d.onSuccess)T&&await T(O(U({},E),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?l.clone():l}));return e?.throw?E.data:{data:E.data,error:null}}let Ce=(b=e?.jsonParser)!=null?b:te,D=await l.text(),Y=Ye(D),H=Y?await Ce(D):null,Ne={response:l,responseText:D,request:f,error:O(U({},H),{status:l.status,statusText:l.statusText})};for(let v of d.onError)v&&await v(O(U({},Ne),{response:(m=e?.hookOptions)!=null&&m.cloneResponse?l.clone():l}));if(e?.retry){let v=Ve(e.retry),g=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(g,l)){for(let T of d.onRetry)T&&await T(Q);let E=v.getDelay(g);return await new Promise(T=>setTimeout(T,E)),await c(t,O(U({},e),{retryAttempt:g+1}))}}if(e?.throw)throw new qe(l.status,l.statusText,Y?H:D);return{data:null,error:O(U({},H),{status:l.status,statusText:l.statusText})}};var it="https://core.framerauth.com/v2",j=class{baseURL=null;data;state;api;auth;constructor(e){this.baseURL=null,this.data=e.data,this.state=e.state,this.api={fetchBookmarks:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await c(`${this.baseURL}/profile/bookmarks`,{credentials:"include"});if(!r.data)return r;let n=new Set(r.data),o={};for(let a of n)o[a]=!0;return{data:o,error:null}},fetchProject:async()=>await c(`${it}/public/project/config`)},this.auth={getSession:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await c(`${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.tags.set(r.data.user.tags??[])):(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 n=await c(`${this.baseURL}/sign-up/email`,{method:"POST",credentials:"include",body:r});return n.error||(await this.auth.getSession(),this.api.fetchBookmarks().then(o=>{this.data.bookmarks.set(o.data??{})})),n},signIn:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=await c(`${this.baseURL}/sign-in/email`,{method:"POST",credentials:"include",body:r});return n.error||(await this.auth.getSession(),this.api.fetchBookmarks().then(o=>{this.data.bookmarks.set(o.data??{})})),n},signInSocial:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=await c(`${this.baseURL}/sign-in/social`,{method:"POST",credentials:"include",body:r});return n.data?.url&&(window.location.href=n.data.url),n},signOut:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=await c(`${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),n},sendOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/email-otp/send-verification-otp`;return await c(n,{body:r,credentials:"include",method:"POST"})},signInOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/sign-in/email-otp`,o=await c(n,{body:r,credentials:"include",method:"POST"});return o.error||(await this.auth.getSession(),this.api.fetchBookmarks().then(a=>{this.data.bookmarks.set(a.data??{})})),o},updateProfile:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile`;return await c(n,{body:r,credentials:"include",method:"PATCH"})},updateProfilePicture:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile/avatar`;return await c(n,{method:"POST",body:r,credentials:"include"})},createBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile/bookmarks`;return await c(n,{body:r,credentials:"include",method:"POST"})},deleteBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/profile/bookmarks/${r.bookmark_type}/${r.id}`;return await c(n,{credentials:"include",method:"DELETE"})},sendForgotPasswordEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/request-password-reset`;return await c(n,{body:r,credentials:"include",method:"POST"})},resetPassword:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/reset-password`;return await c(n,{body:r,credentials:"include",method:"POST"})},storeCheckout:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/store/checkout/session`;return await c(n,{body:r,credentials:"include",method:"POST"})},sendVerificationEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let n=`${this.baseURL}/send-verification-email`;return await c(n,{body:r,credentials:"include",method:"POST"})}}}updateBaseURL(e){this.baseURL=e}};var S=[],L=0,C=4,lt=0,p=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(n){return r.lc=e.push(n),()=>{for(let a=L+C;a<S.length;)S[a]===n?S.splice(a,C):a+=C;let o=e.indexOf(n);~o&&(e.splice(o,1),--r.lc||r.off())}},notify(n,o){lt++;let a=!S.length;for(let s of e)S.push(s,r.value,n,o);if(a){for(L=0;L<S.length;L+=C)S[L](S[L+1],S[L+2],S[L+3]);S.length=0}},off(){},set(n){let o=r.value;o!==n&&(r.value=n,r.notify(o))},subscribe(n){let o=r.listen(n);return n(r.value),o},value:t};return r};var ct=5,N=6,F=10,ut=(t,e,r,n)=>(t.events=t.events||{},t.events[r+F]||(t.events[r+F]=n(o=>{t.events[r].reduceRight((a,s)=>(s(a),a),{shared:{},...o})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let o=t.events[r],a=o.indexOf(e);o.splice(a,1),o.length||(delete t.events[r],t.events[r+F](),delete t.events[r+F])});var se=1e3,J=(t,e)=>ut(t,n=>{let o=e(n);o&&t.events[N].push(o)},ct,n=>{let o=t.listen;t.listen=(...s)=>(!t.lc&&!t.active&&(t.active=!0,n()),o(...s));let a=t.off;return t.events[N]=[],t.off=()=>{a(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let s of t.events[N])s();t.events[N]=[]}},se)},()=>{t.listen=o,t.off=a}});var z=(t={})=>{let e=p(t);return e.setKey=function(r,n){let o=e.value;typeof n>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(o,r)):e.value[r]!==n&&(e.value={...e.value,[r]:n},e.notify(o,r))},e};var ie=t=>t,x={},V={addEventListener(){},removeEventListener(){}};function dt(){try{return typeof localStorage<"u"}catch{return!1}}dt()&&(x=localStorage);var ft={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"&&(V=ft);function w(t,e=void 0,r={}){let n=r.encode||ie,o=r.decode||ie,a=p(e),s=a.set;a.set=i=>{let d=n(i);typeof d>"u"?delete x[t]:x[t]=d,s(i)};function b(i){i.key===t?i.newValue===null?s(e):s(o(i.newValue)):x[t]||s(e)}function m(){a.set(x[t]?o(x[t]):e)}return J(a,()=>{if(m(),r.listen!==!1)return V.addEventListener(t,b,m),()=>{V.removeEventListener(t,b,m)}}),a}var ht="framerauth_v2_",le=new TextEncoder,pt=new TextDecoder;function ce(){let t=typeof window<"u"?window.location.hostname:"1f8cXd6c7b4a3vL4z5746oUgQ28190adbef";return le.encode(ht+t)}function mt(t){let e=ce(),r=le.encode(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r[o]^e[o%e.length];return n}function yt(t){let e=mt(t),r=Array.from(e,n=>String.fromCharCode(n)).join("");return btoa(r)}function gt(t){let e=ce(),r=atob(t),n=Uint8Array.from(r,a=>a.charCodeAt(0)),o=new Uint8Array(n.length);for(let a=0;a<n.length;a++)o[a]=n[a]^e[a%e.length];return pt.decode(o)}function R({obfuscate:t}){return e=>{let r=JSON.stringify(e);return t&&(r=yt(r)),r}}function k({deobfuscate:t,fallback:e,validator:r}){return n=>{try{if(!n)return e;t&&(n=gt(n));let o=JSON.parse(n);if(r){let a=r(o);return a===null?e:a}return o}catch{return e}}}var ue=w("fa-project",null,{encode:R({obfuscate:!0}),decode:k({deobfuscate:!0,fallback:null})}),de=p(!1);var fe=w("fa-tags",[],{encode:R({obfuscate:!0}),decode:k({deobfuscate:!0,fallback:[]})}),he=p(!1);function pe(t){return Array.isArray(t)?t.length===0?!0:t.every(e=>e!==null&&typeof e=="object"&&typeof e.id=="string"&&typeof e.name=="string"):!1}function bt(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id!="string"||typeof e.email!="string"||typeof e.name!="string"||typeof e.email_verified!="boolean"||!(e.created_at instanceof Date||typeof e.created_at=="string")||!(e.updated_at instanceof Date||typeof e.updated_at=="string")?!1:pe(e.tags)}function Pt(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.user_id=="string"&&typeof e.token=="string"&&(e.expires_at instanceof Date||typeof e.expires_at=="string")&&(e.created_at instanceof Date||typeof e.created_at=="string")&&(e.updated_at instanceof Date||typeof e.updated_at=="string")}function me(t){if(!t||typeof t!="object")return null;let e=t;return pe(e.tags)||(e.tags=[]),bt(e)?e:null}function ye(t){return Pt(t)?t:null}function vt(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.entries(t).every(([e,r])=>typeof e=="string"&&typeof r=="boolean")}function ge(t){return!t||typeof t!="object"||Array.isArray(t)?{}:vt(t)?t:{}}var be=w("fa-user",null,{encode:R({obfuscate:!0}),decode:k({deobfuscate:!0,fallback:null,validator:me})}),Pe=p(!1);var ve=w("fa-session",null,{encode:R({obfuscate:!0}),decode:k({deobfuscate:!0,fallback:null,validator:ye})}),Se=p(!1);var we=p(!0);function _(){document.body.style.visibility="hidden"}function A(){document.body.style.visibility="visible"}function W(){let t=document.querySelector('meta[name="framerauth:error-path"]');if(t){let e=t.getAttribute("content");if(e)return e.trim()}return"/sign-in"}function y(t){let r=(t??"").trim();if(r.includes("://"))try{r=new URL(r).pathname}catch{}return r=r.split("#")[0]??"",r=r.split("?")[0]??"",r.length===0&&(r="/"),r.startsWith("/")||(r=`/${r}`),r!=="/"&&r.endsWith("/")&&(r=r.slice(0,-1)),r}function $(t,e){return y(t)===y(e)}function K(t=window.location.pathname){let e=W();return $(t,e)}function Re(){let t=document.querySelector('meta[name="framerauth:boost"]');if(!t)return[];let e=t.getAttribute("content");return e?e.split(",").map(r=>r.trim()).filter(Boolean):[]}function ke(t){let e=t.map(r=>r.trim()).filter(Boolean).map(r=>{if(r==="*"||r==="/*")return{kind:"all"};let n=r.startsWith("/")?r:`/${r}`;return n.endsWith("/**")?{kind:"deep",base:y(n.slice(0,-3))}:n.endsWith("/*")?{kind:"oneSegment",base:y(n.slice(0,-2))}:n.endsWith("*")?{kind:"prefixPathSegment",base:y(n.slice(0,-1))}:{kind:"exact",base:y(n)}});return r=>{let n=y(r);return e.some(o=>{if(o.kind==="all")return!0;if(o.kind==="exact")return n===o.base;if(o.kind==="deep")return n.startsWith(`${o.base}/`);if(o.kind==="oneSegment"){if(!n.startsWith(`${o.base}/`))return!1;let a=n.slice(o.base.length+1);return a.length>0&&!a.includes("/")}return n===o.base||n.startsWith(`${o.base}/`)})}}var I=class{hasAccess;isPublicPath;errorPath;onError;observer=null;currentCanonical;originalPushState;originalReplaceState;isMonkeyPatched=!1;constructor(e){this.hasAccess=e.hasAccess,this.isPublicPath=e.isPublicPath,this.errorPath=e.errorPath,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 y(e.pathname);if(e.startsWith("./"))return y(e.slice(1));if(e.startsWith("/"))return y(e);try{let r=new URL(e);return y(r.pathname)}catch{return y(e.startsWith("/")?e:"/"+e)}}normalizePathInput(e){let r=e.startsWith("/")?e:`/${e}`;return y(r)}isErrorPath(e){let r=this.normalizePathInput(e);return $(r,this.errorPath)}checkAccess(e){let r=this.normalizePathInput(e);if(this.isErrorPath(r)||this.isPublicPath(r))return!0;try{return this.hasAccess(r)}catch{return!1}}isOnErrorPage(){let e=this.normalizePathInput(window.location.pathname);return $(e,this.errorPath)}redirectToError(){if(this.isOnErrorPage()){A();return}window.location.replace(this.errorPath)}handleAccessDenied(e){e&&this.onError&&this.onError(e),this.redirectToError()}monkeyPatchHistory(){if(this.isMonkeyPatched)return;let e=this;history.pushState=function(r,n,o){if(o){let a=e.normalizeToPath(o);e.checkAccess(a)||_()}return e.originalPushState.call(this,r,n,o)},history.replaceState=function(r,n,o){if(o){let a=e.normalizeToPath(o);e.checkAccess(a)||_()}return e.originalReplaceState.call(this,r,n,o)},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(),A()}handleMutations(e){let r=!1;for(let n of e){if(n.type==="childList"){let o=[...Array.from(n.addedNodes),...Array.from(n.removedNodes)];for(let a of o)if(a.nodeType===Node.ELEMENT_NODE){let s=a;if(this.isCanonicalLink(s)){r=!0;break}}}else if(n.type==="attributes"){let o=n.target;(this.isCanonicalLink(o)||n.oldValue==="canonical")&&(r=!0)}if(r)break}r&&this.checkCanonicalChange()}isCanonicalLink(e){return e.tagName==="LINK"&&e.getAttribute("rel")==="canonical"}checkCanonicalChange(){let e=this.getCurrentCanonical();if(e!==this.currentCanonical)if(this.currentCanonical=e,e){let r=this.normalizeToPath(e);if(!this.checkAccess(r)){this.handleAccessDenied();return}A()}else A()}};var Ee=w("fa-bookmarks",z(),{encode:R({obfuscate:!0}),decode:k({deobfuscate:!0,fallback:{},validator:ge})}),Te=p(!1);var Le=(t,e)=>{let r=y(e),n=t.data.user.get(),o=t.data.session.get(),a=t.data.project.get();if(!a)return!1;if(!Object.prototype.hasOwnProperty.call(a.pages,r))return!0;if(!n||!o)return!1;let b=a.pages[r];return b.length===0?!0:b.some(m=>n.tags.find(i=>i.id===m))};console.log("FramerAuth SDK (JavaScript): 2.1.3");var St="/v2",wt="framerauth.io",u=new j({data:{user:be,project:ue,tags:fe,bookmarks:Ee,session:ve},state:{initializing:we,userLoading:Pe,projectLoading:de,tagsLoading:he,bookmarksLoading:Te,sessionLoading:Se}});window.FramerAuth=u;var Rt=Re(),Ae=ke(Rt);function kt(){return K()?!0:u.data.project.get()!==null&&Ae(window.location.pathname)}function M(t){let e=`${t.slug}.${wt}`,r=t.customDomain||e;u.updateBaseURL(`https://${r}${St}`)}function G(){u.api.fetchBookmarks().then(({data:t})=>{u.data.bookmarks.set(t??{})})}function Ue(){let t=W(),e=new I({hasAccess:n=>Le(u,n),isPublicPath:n=>Ae(n),errorPath:t,onError:n=>{console.error("[Router] Error in router:",n)}});return e.checkAccess(window.location.pathname)?(e.start(),!0):(e.handleAccessDenied(),!1)}function Et(){let t=u.data.project.get();return t?(M(t),u.api.fetchProject().then(e=>{e.data&&(u.data.project.set(e.data),M(e.data))}),u.auth.getSession().then(e=>{e.data!==null&&G()})):u.api.fetchProject().then(e=>{if(e.data)return u.data.project.set(e.data),M(e.data),u.auth.getSession()}).then(e=>{e?.data!==null&&G()}),Ue()}async function Tt(){_();let t=u.data.project.get(),e=await u.api.fetchProject();if(e.data)t=e.data,u.data.project.set(t);else if(!t)throw new Error(e.error.message||"Unable to load FramerAuth project!");M(t),(await u.auth.getSession()).data!==null&&G();let n=Ue();return n&&A(),n}async function Lt(){u.state.initializing.set(!0);try{(kt()?Et():await Tt())&&window.dispatchEvent(new CustomEvent("framerauth:initialized"))}catch(t){console.error("Failed to initialize FramerAuth:",t),K()?A():window.location.replace(W()),window.dispatchEvent(new CustomEvent("framerauth:initialization-failed",{detail:{error:t}}))}finally{u.state.initializing.set(!1)}}Lt();})();
|
package/dist/framerauth.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var le=()=>typeof window<"u",fe=()=>window.location.host.endsWith("framercanvas.com"),k="FramerAuth snippet missing from start of <body>",b=()=>!le()||fe()||!window?.FramerAuth?null:window.FramerAuth;async function De(){let t=b();if(!t)return{data:null,error:{message:k}};try{return await t.auth.getSession()}catch(e){return{data:null,error:{message:e instanceof Error?e.message:"Unknown error"}}}}async function Ve(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signUp(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function ze(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signIn(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Je(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signInOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ke(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.sendOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ge(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signOut(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Qe(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.updateProfile(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ye(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.updateProfilePicture(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Xe(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.sendForgotPasswordEmail(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ze(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.resetPassword(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function et(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signInSocial(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function tt(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.storeCheckout(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}var de=Object.defineProperty,me=Object.defineProperties,he=Object.getOwnPropertyDescriptors,J=Object.getOwnPropertySymbols,pe=Object.prototype.hasOwnProperty,ye=Object.prototype.propertyIsEnumerable,K=(t,e,r)=>e in t?de(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))pe.call(e,r)&&K(t,r,e[r]);if(J)for(var r of J(e))ye.call(e,r)&&K(t,r,e[r]);return t},R=(t,e)=>me(t,he(e)),ge=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},we=async(t,e)=>{var r,n,o,a,s,u;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 m of e?.plugins||[]){if(m.init){let l=await((r=m.init)==null?void 0:r.call(m,t.toString(),e));c=l.options||c,t=l.url}i.onRequest.push((n=m.hooks)==null?void 0:n.onRequest),i.onResponse.push((o=m.hooks)==null?void 0:o.onResponse),i.onSuccess.push((a=m.hooks)==null?void 0:a.onSuccess),i.onError.push((s=m.hooks)==null?void 0:s.onError),i.onRetry.push((u=m.hooks)==null?void 0:u.onRetry)}return{url:t,options:c,hooks:i}},G=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}},ve=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 ke(t){if(typeof t=="number")return new G({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new G(t);case"exponential":return new ve(t);default:throw new Error("Invalid retry strategy")}}var be=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),o=r(t.auth.password);if(!n||!o)return e;e.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},Pe=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Se(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return Pe.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Te(t){try{return JSON.parse(t),!0}catch{return!1}}function X(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 Q(t){try{return JSON.parse(t)}catch{return t}}function Y(t){return typeof t=="function"}function xe(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&Y(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Y(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Ae(t){let e=new Headers(t?.headers),r=await be(t);for(let[n,o]of Object.entries(r||{}))e.set(n,o);if(!e.has("content-type")){let n=Re(t?.body);n&&e.set("content-type",n)}return e}function Re(t){return X(t)?"application/json":null}function Oe(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(X(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function _e(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return ee.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function Ee(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Ue=class Z extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,Z.prototype)}};async function Fe(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new Ue(r.issues);return r.value}var ee=["get","post","put","patch","delete"];function je(t,e){let{baseURL:r,params:n,query:o}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let l=t.toString().split("@")[1].split("/")[0];ee.includes(l)&&(t=t.replace(`@${l}/`,"/"))}a.endsWith("/")||(a+="/");let[s,u]=t.replace(a,"").split("?"),c=new URLSearchParams(u);for(let[l,d]of Object.entries(o||{}))d!=null&&c.set(l,String(d));if(n)if(Array.isArray(n)){let l=s.split("/").filter(d=>d.startsWith(":"));for(let[d,x]of l.entries()){let g=n[d];s=s.replace(x,g)}}else for(let[l,d]of Object.entries(n))s=s.replace(`:${l}`,String(d));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let i=c.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${s}${i}`,a):`${a}${s}${i}`}var M=async(t,e)=>{var r,n,o,a,s,u,c,i;let{hooks:m,url:l,options:d}=await we(t,e),x=xe(d),g=new AbortController,F=(r=d.signal)!=null?r:g.signal,B=je(l,d),ne=Oe(d),ae=await Ae(d),oe=_e(l,d),h=R(A({},d),{url:B,headers:ae,body:ne,method:oe,signal:F});for(let v of m.onRequest)if(v){let p=await v(h);p instanceof Object&&(h=p)}("pipeTo"in h&&typeof h.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in h||(h.duplex="half"));let{clearTimeout:se}=Ee(d,g),f=await x(h.url,h);se();let V={response:f,request:h};for(let v of m.onResponse)if(v){let p=await v(R(A({},V),{response:(o=e?.hookOptions)!=null&&o.cloneResponse?f.clone():f}));p instanceof Response?f=p:p instanceof Object&&(f=p.response)}if(f.ok){if(!(h.method!=="HEAD"))return{data:"",error:null};let p=Se(f),P={data:"",response:f,request:h};if(p==="json"||p==="text"){let S=await f.text(),ce=await((a=h.jsonParser)!=null?a:Q)(S);P.data=ce}else P.data=await f[p]();h?.output&&h.output&&!h.disableValidation&&(P.data=await Fe(h.output,P.data));for(let S of m.onSuccess)S&&await S(R(A({},P),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?f.clone():f}));return e?.throw?P.data:{data:P.data,error:null}}let ie=(u=e?.jsonParser)!=null?u:Q,j=await f.text(),z=Te(j),$=z?await ie(j):null,ue={response:f,responseText:j,request:h,error:R(A({},$),{status:f.status,statusText:f.statusText})};for(let v of m.onError)v&&await v(R(A({},ue),{response:(c=e?.hookOptions)!=null&&c.cloneResponse?f.clone():f}));if(e?.retry){let v=ke(e.retry),p=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(p,f)){for(let S of m.onRetry)S&&await S(V);let P=v.getDelay(p);return await new Promise(S=>setTimeout(S,P)),await M(t,R(A({},e),{retryAttempt:p+1}))}}if(e?.throw)throw new ge(f.status,f.statusText,z?$:j);return{data:null,error:R(A({},$),{status:f.status,statusText:f.statusText})}};function q(t,e,r){let n=new Set(e).add(void 0);return t.listen((o,a,s)=>{n.has(s)&&r(o,a,s)})}import{useCallback as Le,useRef as Ce,useSyncExternalStore as Ie}from"react";var W=(t,e)=>r=>{t.current!==r&&(t.current=r,e())};function T(t,{keys:e,deps:r=[t,e]}={}){let n=Ce();n.current=t.get();let o=Le(s=>(W(n,s)(t.value),e?.length>0?q(t,e,W(n,s)):t.listen(W(n,s))),r),a=()=>n.current;return Ie(o,a,a)}import{useState as te}from"react";var Be="https://core.framerauth.com/v2",_=()=>typeof window<"u",E=()=>window.location.host.endsWith("framercanvas.com"),$e=()=>{let t=Object.keys(window.parent);for(let e=t.length-1;e>=0;e--)try{let r=new URLSearchParams(window.parent[t[e]].location.search).get("siteId");if(r)return r}catch{}},Me=async()=>{let t=$e()||"";return await M(`${Be}/public/project/config`,{headers:{"x-framer-project-id":t}})};function gt(){if(!_()||E()||!window?.FramerAuth)return{initializing:!0,setInitializing:()=>{}};let t=window.FramerAuth;return{initializing:T(t.state.initializing)}}function O(){if(!_()||E()||!window?.FramerAuth)return{session:null,loading:!1,setSession:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.session),r=T(t.state.sessionLoading);return{session:e,loading:r,setSession:a=>t.data.session.set(a),setLoading:a=>t.state.sessionLoading.set(a)}}function L(){if(!_()||E()||!window?.FramerAuth)return{user:null,loading:!1,setUser:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.user),r=T(t.state.userLoading),n=a=>t.data.user.set(a),o=a=>t.state.userLoading.set(a);return e&&!Object.prototype.hasOwnProperty.call(e,"tags")&&(e.tags=[]),{user:e,loading:r,setUser:n,setLoading:o}}function wt(){let[t,e]=te(null),[r,n]=te(!1);if(!_())return{project:null,loading:!1,setProject:()=>{},setLoading:()=>{},fetchProject:async()=>({data:null,error:{message:"Browser not available"}})};if(E()&&!window?.FramerAuth){let l=g=>e(g),d=g=>n(g);return{project:t,loading:r,setProject:l,setLoading:d,fetchProject:async()=>{d(!0);let g=await Me();return g.data&&l(g.data),d(!1),g}}}let a=window.FramerAuth,s=T(a.data.project),u=T(a.state.projectLoading),c=l=>a.data.project.set(l),i=l=>a.state.projectLoading.set(l);return{project:s,loading:u,setProject:c,setLoading:i,fetchProject:async()=>{i(!0);let l=await a.api.fetchProject();return l.data&&c(l.data),i(!1),l}}}function C(t){if(!_()||E()||!window?.FramerAuth)return{bookmarks:null,loading:!1,createBookmark:a=>{},deleteBookmark:a=>{},setLoading:()=>{}};let e=window.FramerAuth;return{bookmarks:T(e.data.bookmarks,{keys:t}),createBookmark:a=>{let u={...e.data.bookmarks.get(),[a]:!0};e.data.bookmarks.set(u)},deleteBookmark:a=>{let u={...e.data.bookmarks.get()};delete u[a],e.data.bookmarks.set(u)}}}import{useEffect as N,useMemo as w,useRef as D}from"react";import{useRouter as qe,RenderTarget as re,inferInitialRouteFromPath as We}from"framer";function H(t,e="any"){return t==="all"||t==="any"?t:e}function U(t){return t!==null}function I(t,e,r="all"){if(!U(t))return!1;if(e.length===0)return t.tags.length>0;let n=t.tags.map(o=>o.name);return r==="any"?e.some(o=>n.includes(o)):e.every(o=>n.includes(o))}import{jsx as y}from"react/jsx-runtime";typeof window<"u"&&window.FramerAuth&&console.log("FramerAuth SDK (React): 2.1.1");function Rt(t){return e=>{let{session:r}=O();return r?y(t,{...e}):null}}function Ot(t){return e=>{let{session:r}=O();return r?null:y(t,{...e})}}function _t(t){return e=>{let{session:r}=O(),n=r?null:e?.variant;return y(t,{...e,variant:n})}}function Et(t){return e=>{let{user:r}=L(),n=D(null),o=e?.tags,a=w(()=>!o||typeof o!="string"?null:o.split(",").map(i=>i.trim()).filter(Boolean),[o]),s=H(e?.require),u=w(()=>U(r)?a?I(r,a,s):r.tags.length>0:!1,[r,a,s]);return N(()=>{if(n.current){let i=a?n.current.parentElement:n.current;if(!i)return;u?i.style.display="":i.style.display="none"}},[n.current,u]),w(()=>u!==!0?y("div",{ref:n}):y(t,{ref:n,...e}),[e,u,void 0])}}function Ut(t){return e=>{let{user:r}=L(),n=D(null),o=e?.tags,a=w(()=>!o||typeof o!="string"?null:o.split(",").map(i=>i.trim()).filter(Boolean),[o]),s=H(e?.require),u=w(()=>U(r)?a?I(r,a,s):r.tags.length>0:!1,[r,a,s]);return N(()=>{if(n.current){let i=a?n.current.parentElement:n.current;if(!i)return;u?i.style.display="none":i.style.display=""}},[n.current,u]),w(()=>u===!0?y("div",{ref:n}):y(t,{ref:n,...e}),[e,u,void 0])}}function Ft(t){return e=>{let{user:r}=L(),n=e?.variant,o=e?.tags;if(!o||typeof o!="string"||o.trim().length===0){let c=null;return(!U(r)||r.tags.length===0)&&(c=n),y(t,{...e,variant:c})}let a=o.split(",").map(c=>c.trim()).filter(Boolean),u=I(r,a,"any")?null:n;return y(t,{...e,variant:u})}}function jt(t,e="saved-for-later"){return r=>{let{bookmarks:n}=C(),a=w(()=>n?Object.keys(n).some(u=>u.startsWith(`${e}:`)):!1,[n])?null:"Empty State";return y(t,{...r,variant:a})}}function Lt(t,e="saved-for-later"){return r=>{let{bookmarks:n}=C(),o=D(null),a=w(()=>`${e}:${r?.slug}`,[r]),s=w(()=>He()?!0:n?a in n:!1,[n?.[a],a]);return N(()=>{if(o.current){let c=o.current.parentElement;if(!c)return;s?c.style.display="":c.style.display="none"}},[o.current,s]),w(()=>s?y(t,{ref:o,...r}):y("div",{ref:o}),[r,s,void 0])}}function Ct(t,e="saved-for-later"){return r=>{let n=qe(),{session:o}=O(),{bookmarks:a,createBookmark:s,deleteBookmark:u}=C([`${e}:${r?.slug}`]),c=w(()=>`${e}:${r?.slug}`,[r]),i=w(()=>a?c in a:!1,[a?.[c],c]),m=async d=>{try{if(i)u(c),window?.FramerAuth.auth.deleteBookmark({id:r?.slug,bookmark_type:e});else if(s(c),window?.FramerAuth.auth.createBookmark({id:r?.slug,bookmark_type:e}),r?.link){let[x,g]=r.link.split("#"),{routeId:F,pathVariables:B}=We(n.routes,x);F&&n.navigate(F,g,B)}}catch(x){console.error(x)}},l=w(()=>i?r?.variant:void 0,[i,r?.variant]);return o?y(t,{...r,variant:l,onClick:m}):null}}function It(t){return e=>y(t,{...e,onClick:async n=>{window?.FramerAuth.auth.signInSocial({provider:"github",callbackURL:window.location.origin+"/account"})}})}function Bt(t,e){return r=>{let{session:n}=O();return n?y(t,{...r,onClick:async a=>{window?.FramerAuth.auth.signOut({redirectTo:e.redirectTo})}}):null}}function He(){return re.current()===re.canvas}export{It as buttonSignInSocial,Bt as buttonSignOut,De as getSession,He as isCanvas,Ze as resetPassword,Xe as sendForgotPasswordEmail,Ke as sendOTP,Rt as showIfSignedIn,Ot as showIfSignedOut,Et as showIfWithTag,Ut as showIfWithoutTag,ze as signIn,Je as signInOTP,et as signInSocial,Ge as signOut,Ve as signUp,tt as storeCheckout,_t as toggleVariant,Ft as toggleVariantIfWithTag,Qe as updateProfile,Ye as updateProfilePicture,C as useBookmarks,gt as useIsInitializing,wt as useProject,O as useSession,L as useUser,jt as withBookmarks,Lt as withIsBookmarked,Ct as withToggleBookmark};
|
|
1
|
+
var le=()=>typeof window<"u",fe=()=>window.location.host.endsWith("framercanvas.com"),w="FramerAuth snippet missing from start of <body>",v=()=>!le()||fe()||!window?.FramerAuth?null:window.FramerAuth;async function Ve(){let t=v();if(!t)return{data:null,error:{message:w}};try{return await t.auth.getSession()}catch(e){return{data:null,error:{message:e instanceof Error?e.message:"Unknown error"}}}}async function De(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.signUp(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function ze(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.signIn(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Je(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.signInOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ke(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.sendOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ge(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.signOut(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Qe(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.updateProfile(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ye(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.updateProfilePicture(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Xe(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.sendForgotPasswordEmail(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ze(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.resetPassword(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function et(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.signInSocial(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function tt(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.storeCheckout(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function rt(t){let e=v();if(!e)return{data:null,error:{message:w}};try{return await e.auth.sendVerificationEmail(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}var de=Object.defineProperty,me=Object.defineProperties,he=Object.getOwnPropertyDescriptors,J=Object.getOwnPropertySymbols,pe=Object.prototype.hasOwnProperty,ye=Object.prototype.propertyIsEnumerable,K=(t,e,r)=>e in t?de(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,A=(t,e)=>{for(var r in e||(e={}))pe.call(e,r)&&K(t,r,e[r]);if(J)for(var r of J(e))ye.call(e,r)&&K(t,r,e[r]);return t},R=(t,e)=>me(t,he(e)),ge=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},we=async(t,e)=>{var r,n,o,a,s,u;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 m of e?.plugins||[]){if(m.init){let l=await((r=m.init)==null?void 0:r.call(m,t.toString(),e));c=l.options||c,t=l.url}i.onRequest.push((n=m.hooks)==null?void 0:n.onRequest),i.onResponse.push((o=m.hooks)==null?void 0:o.onResponse),i.onSuccess.push((a=m.hooks)==null?void 0:a.onSuccess),i.onError.push((s=m.hooks)==null?void 0:s.onError),i.onRetry.push((u=m.hooks)==null?void 0:u.onRetry)}return{url:t,options:c,hooks:i}},G=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}},ve=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 ke(t){if(typeof t=="number")return new G({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new G(t);case"exponential":return new ve(t);default:throw new Error("Invalid retry strategy")}}var be=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),o=r(t.auth.password);if(!n||!o)return e;e.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},Pe=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Se(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return Pe.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Te(t){try{return JSON.parse(t),!0}catch{return!1}}function X(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 Q(t){try{return JSON.parse(t)}catch{return t}}function Y(t){return typeof t=="function"}function xe(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&Y(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Y(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Ae(t){let e=new Headers(t?.headers),r=await be(t);for(let[n,o]of Object.entries(r||{}))e.set(n,o);if(!e.has("content-type")){let n=Re(t?.body);n&&e.set("content-type",n)}return e}function Re(t){return X(t)?"application/json":null}function Ee(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(X(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function Oe(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return ee.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function _e(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Ue=class Z extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,Z.prototype)}};async function Fe(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new Ue(r.issues);return r.value}var ee=["get","post","put","patch","delete"];function je(t,e){let{baseURL:r,params:n,query:o}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let l=t.toString().split("@")[1].split("/")[0];ee.includes(l)&&(t=t.replace(`@${l}/`,"/"))}a.endsWith("/")||(a+="/");let[s,u]=t.replace(a,"").split("?"),c=new URLSearchParams(u);for(let[l,d]of Object.entries(o||{}))d!=null&&c.set(l,String(d));if(n)if(Array.isArray(n)){let l=s.split("/").filter(d=>d.startsWith(":"));for(let[d,x]of l.entries()){let g=n[d];s=s.replace(x,g)}}else for(let[l,d]of Object.entries(n))s=s.replace(`:${l}`,String(d));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let i=c.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${s}${i}`,a):`${a}${s}${i}`}var M=async(t,e)=>{var r,n,o,a,s,u,c,i;let{hooks:m,url:l,options:d}=await we(t,e),x=xe(d),g=new AbortController,F=(r=d.signal)!=null?r:g.signal,B=je(l,d),ne=Ee(d),ae=await Ae(d),oe=Oe(l,d),h=R(A({},d),{url:B,headers:ae,body:ne,method:oe,signal:F});for(let b of m.onRequest)if(b){let p=await b(h);p instanceof Object&&(h=p)}("pipeTo"in h&&typeof h.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in h||(h.duplex="half"));let{clearTimeout:se}=_e(d,g),f=await x(h.url,h);se();let D={response:f,request:h};for(let b of m.onResponse)if(b){let p=await b(R(A({},D),{response:(o=e?.hookOptions)!=null&&o.cloneResponse?f.clone():f}));p instanceof Response?f=p:p instanceof Object&&(f=p.response)}if(f.ok){if(!(h.method!=="HEAD"))return{data:"",error:null};let p=Se(f),P={data:"",response:f,request:h};if(p==="json"||p==="text"){let S=await f.text(),ce=await((a=h.jsonParser)!=null?a:Q)(S);P.data=ce}else P.data=await f[p]();h?.output&&h.output&&!h.disableValidation&&(P.data=await Fe(h.output,P.data));for(let S of m.onSuccess)S&&await S(R(A({},P),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?f.clone():f}));return e?.throw?P.data:{data:P.data,error:null}}let ie=(u=e?.jsonParser)!=null?u:Q,j=await f.text(),z=Te(j),$=z?await ie(j):null,ue={response:f,responseText:j,request:h,error:R(A({},$),{status:f.status,statusText:f.statusText})};for(let b of m.onError)b&&await b(R(A({},ue),{response:(c=e?.hookOptions)!=null&&c.cloneResponse?f.clone():f}));if(e?.retry){let b=ke(e.retry),p=(i=e.retryAttempt)!=null?i:0;if(await b.shouldAttemptRetry(p,f)){for(let S of m.onRetry)S&&await S(D);let P=b.getDelay(p);return await new Promise(S=>setTimeout(S,P)),await M(t,R(A({},e),{retryAttempt:p+1}))}}if(e?.throw)throw new ge(f.status,f.statusText,z?$:j);return{data:null,error:R(A({},$),{status:f.status,statusText:f.statusText})}};function q(t,e,r){let n=new Set(e).add(void 0);return t.listen((o,a,s)=>{n.has(s)&&r(o,a,s)})}import{useCallback as Le,useRef as Ce,useSyncExternalStore as Ie}from"react";var W=(t,e)=>r=>{t.current!==r&&(t.current=r,e())};function T(t,{keys:e,deps:r=[t,e]}={}){let n=Ce();n.current=t.get();let o=Le(s=>(W(n,s)(t.value),e?.length>0?q(t,e,W(n,s)):t.listen(W(n,s))),r),a=()=>n.current;return Ie(o,a,a)}import{useState as te}from"react";var Be="https://core.framerauth.com/v2",O=()=>typeof window<"u",_=()=>window.location.host.endsWith("framercanvas.com"),$e=()=>{let t=Object.keys(window.parent);for(let e=t.length-1;e>=0;e--)try{let r=new URLSearchParams(window.parent[t[e]].location.search).get("siteId");if(r)return r}catch{}},Me=async()=>{let t=$e()||"";return await M(`${Be}/public/project/config`,{headers:{"x-framer-project-id":t}})};function wt(){if(!O()||_()||!window?.FramerAuth)return{initializing:!0,setInitializing:()=>{}};let t=window.FramerAuth;return{initializing:T(t.state.initializing)}}function E(){if(!O()||_()||!window?.FramerAuth)return{session:null,loading:!1,setSession:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.session),r=T(t.state.sessionLoading);return{session:e,loading:r,setSession:a=>t.data.session.set(a),setLoading:a=>t.state.sessionLoading.set(a)}}function L(){if(!O()||_()||!window?.FramerAuth)return{user:null,loading:!1,setUser:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.user),r=T(t.state.userLoading),n=a=>t.data.user.set(a),o=a=>t.state.userLoading.set(a);return e&&!Object.prototype.hasOwnProperty.call(e,"tags")&&(e.tags=[]),{user:e,loading:r,setUser:n,setLoading:o}}function vt(){let[t,e]=te(null),[r,n]=te(!1);if(!O())return{project:null,loading:!1,setProject:()=>{},setLoading:()=>{},fetchProject:async()=>({data:null,error:{message:"Browser not available"}})};if(_()&&!window?.FramerAuth){let l=g=>e(g),d=g=>n(g);return{project:t,loading:r,setProject:l,setLoading:d,fetchProject:async()=>{d(!0);let g=await Me();return g.data&&l(g.data),d(!1),g}}}let a=window.FramerAuth,s=T(a.data.project),u=T(a.state.projectLoading),c=l=>a.data.project.set(l),i=l=>a.state.projectLoading.set(l);return{project:s,loading:u,setProject:c,setLoading:i,fetchProject:async()=>{i(!0);let l=await a.api.fetchProject();return l.data&&c(l.data),i(!1),l}}}function C(t){if(!O()||_()||!window?.FramerAuth)return{bookmarks:null,loading:!1,createBookmark:a=>{},deleteBookmark:a=>{},setLoading:()=>{}};let e=window.FramerAuth;return{bookmarks:T(e.data.bookmarks,{keys:t}),createBookmark:a=>{let u={...e.data.bookmarks.get(),[a]:!0};e.data.bookmarks.set(u)},deleteBookmark:a=>{let u={...e.data.bookmarks.get()};delete u[a],e.data.bookmarks.set(u)}}}import{useEffect as N,useMemo as k,useRef as V}from"react";import{useRouter as qe,RenderTarget as re,inferInitialRouteFromPath as We}from"framer";function H(t,e="any"){return t==="all"||t==="any"?t:e}function U(t){return t!==null}function I(t,e,r="all"){if(!U(t))return!1;if(e.length===0)return t.tags.length>0;let n=t.tags.map(o=>o.name);return r==="any"?e.some(o=>n.includes(o)):e.every(o=>n.includes(o))}import{jsx as y}from"react/jsx-runtime";typeof window<"u"&&window.FramerAuth&&console.log("FramerAuth SDK (React): 2.1.3");function Et(t){return e=>{let{session:r}=E();return r?y(t,{...e}):null}}function Ot(t){return e=>{let{session:r}=E();return r?null:y(t,{...e})}}function _t(t){return e=>{let{session:r}=E(),n=r?null:e?.variant;return y(t,{...e,variant:n})}}function Ut(t){return e=>{let{user:r}=L(),n=V(null),o=e?.tags,a=k(()=>!o||typeof o!="string"?null:o.split(",").map(i=>i.trim()).filter(Boolean),[o]),s=H(e?.require),u=k(()=>U(r)?a?I(r,a,s):r.tags.length>0:!1,[r,a,s]);return N(()=>{if(n.current){let i=a?n.current.parentElement:n.current;if(!i)return;u?i.style.display="":i.style.display="none"}},[n.current,u]),k(()=>u!==!0?y("div",{ref:n}):y(t,{ref:n,...e}),[e,u,void 0])}}function Ft(t){return e=>{let{user:r}=L(),n=V(null),o=e?.tags,a=k(()=>!o||typeof o!="string"?null:o.split(",").map(i=>i.trim()).filter(Boolean),[o]),s=H(e?.require),u=k(()=>U(r)?a?I(r,a,s):r.tags.length>0:!1,[r,a,s]);return N(()=>{if(n.current){let i=a?n.current.parentElement:n.current;if(!i)return;u?i.style.display="none":i.style.display=""}},[n.current,u]),k(()=>u===!0?y("div",{ref:n}):y(t,{ref:n,...e}),[e,u,void 0])}}function jt(t){return e=>{let{user:r}=L(),n=e?.variant,o=e?.tags;if(!o||typeof o!="string"||o.trim().length===0){let c=null;return(!U(r)||r.tags.length===0)&&(c=n),y(t,{...e,variant:c})}let a=o.split(",").map(c=>c.trim()).filter(Boolean),u=I(r,a,"any")?null:n;return y(t,{...e,variant:u})}}function Lt(t,e="saved-for-later"){return r=>{let{bookmarks:n}=C(),a=k(()=>n?Object.keys(n).some(u=>u.startsWith(`${e}:`)):!1,[n])?null:"Empty State";return y(t,{...r,variant:a})}}function Ct(t,e="saved-for-later"){return r=>{let{bookmarks:n}=C(),o=V(null),a=k(()=>`${e}:${r?.slug}`,[r]),s=k(()=>He()?!0:n?a in n:!1,[n?.[a],a]);return N(()=>{if(o.current){let c=o.current.parentElement;if(!c)return;s?c.style.display="":c.style.display="none"}},[o.current,s]),k(()=>s?y(t,{ref:o,...r}):y("div",{ref:o}),[r,s,void 0])}}function It(t,e="saved-for-later"){return r=>{let n=qe(),{session:o}=E(),{bookmarks:a,createBookmark:s,deleteBookmark:u}=C([`${e}:${r?.slug}`]),c=k(()=>`${e}:${r?.slug}`,[r]),i=k(()=>a?c in a:!1,[a?.[c],c]),m=async d=>{try{if(i)u(c),window?.FramerAuth.auth.deleteBookmark({id:r?.slug,bookmark_type:e});else if(s(c),window?.FramerAuth.auth.createBookmark({id:r?.slug,bookmark_type:e}),r?.link){let[x,g]=r.link.split("#"),{routeId:F,pathVariables:B}=We(n.routes,x);F&&n.navigate(F,g,B)}}catch(x){console.error(x)}},l=k(()=>i?r?.variant:void 0,[i,r?.variant]);return o?y(t,{...r,variant:l,onClick:m}):null}}function Bt(t){return e=>y(t,{...e,onClick:async n=>{window?.FramerAuth.auth.signInSocial({provider:"github",callbackURL:window.location.origin+"/account"})}})}function $t(t,e){return r=>{let{session:n}=E();return n?y(t,{...r,onClick:async a=>{window?.FramerAuth.auth.signOut({redirectTo:e.redirectTo})}}):null}}function He(){return re.current()===re.canvas}export{Bt as buttonSignInSocial,$t as buttonSignOut,Ve as getSession,He as isCanvas,Ze as resetPassword,Xe as sendForgotPasswordEmail,Ke as sendOTP,rt as sendVerificationEmail,Et as showIfSignedIn,Ot as showIfSignedOut,Ut as showIfWithTag,Ft as showIfWithoutTag,ze as signIn,Je as signInOTP,et as signInSocial,Ge as signOut,De as signUp,tt as storeCheckout,_t as toggleVariant,jt as toggleVariantIfWithTag,Qe as updateProfile,Ye as updateProfilePicture,C as useBookmarks,wt as useIsInitializing,vt as useProject,E as useSession,L as useUser,Lt as withBookmarks,Ct as withIsBookmarked,It as withToggleBookmark};
|